dram_ctrl.cc revision 10883
1/* 2 * Copyright (c) 2010-2014 ARM Limited 3 * All rights reserved 4 * 5 * The license below extends only to copyright in the software and shall 6 * not be construed as granting a license to any other intellectual 7 * property including but not limited to intellectual property relating 8 * to a hardware implementation of the functionality of the software 9 * licensed hereunder. You may use the software subject to the license 10 * terms below provided that you ensure that this notice is replicated 11 * unmodified and in its entirety in all distributions of the software, 12 * modified or unmodified, in source code or in binary form. 13 * 14 * Copyright (c) 2013 Amin Farmahini-Farahani 15 * All rights reserved. 16 * 17 * Redistribution and use in source and binary forms, with or without 18 * modification, are permitted provided that the following conditions are 19 * met: redistributions of source code must retain the above copyright 20 * notice, this list of conditions and the following disclaimer; 21 * redistributions in binary form must reproduce the above copyright 22 * notice, this list of conditions and the following disclaimer in the 23 * documentation and/or other materials provided with the distribution; 24 * neither the name of the copyright holders nor the names of its 25 * contributors may be used to endorse or promote products derived from 26 * this software without specific prior written permission. 27 * 28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 39 * 40 * Authors: Andreas Hansson 41 * Ani Udipi 42 * Neha Agarwal 43 * Omar Naji 44 */ 45 46#include "base/bitfield.hh" 47#include "base/trace.hh" 48#include "debug/DRAM.hh" 49#include "debug/DRAMPower.hh" 50#include "debug/DRAMState.hh" 51#include "debug/Drain.hh" 52#include "mem/dram_ctrl.hh" 53#include "sim/system.hh" 54 55using namespace std; 56using namespace Data; 57 58DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) : 59 AbstractMemory(p), 60 port(name() + ".port", *this), isTimingMode(false), 61 retryRdReq(false), retryWrReq(false), 62 busState(READ), 63 nextReqEvent(this), respondEvent(this), 64 drainManager(NULL), 65 deviceSize(p->device_size), 66 deviceBusWidth(p->device_bus_width), burstLength(p->burst_length), 67 deviceRowBufferSize(p->device_rowbuffer_size), 68 devicesPerRank(p->devices_per_rank), 69 burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8), 70 rowBufferSize(devicesPerRank * deviceRowBufferSize), 71 columnsPerRowBuffer(rowBufferSize / burstSize), 72 columnsPerStripe(range.interleaved() ? range.granularity() / burstSize : 1), 73 ranksPerChannel(p->ranks_per_channel), 74 bankGroupsPerRank(p->bank_groups_per_rank), 75 bankGroupArch(p->bank_groups_per_rank > 0), 76 banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0), 77 readBufferSize(p->read_buffer_size), 78 writeBufferSize(p->write_buffer_size), 79 writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0), 80 writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0), 81 minWritesPerSwitch(p->min_writes_per_switch), 82 writesThisTime(0), readsThisTime(0), 83 tCK(p->tCK), tWTR(p->tWTR), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST), 84 tCCD_L(p->tCCD_L), tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS), 85 tWR(p->tWR), tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD), 86 tRRD_L(p->tRRD_L), tXAW(p->tXAW), activationLimit(p->activation_limit), 87 memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping), 88 pageMgmt(p->page_policy), 89 maxAccessesPerRow(p->max_accesses_per_row), 90 frontendLatency(p->static_frontend_latency), 91 backendLatency(p->static_backend_latency), 92 busBusyUntil(0), prevArrival(0), 93 nextReqTime(0), activeRank(0), timeStampOffset(0) 94{ 95 // sanity check the ranks since we rely on bit slicing for the 96 // address decoding 97 fatal_if(!isPowerOf2(ranksPerChannel), "DRAM rank count of %d is not " 98 "allowed, must be a power of two\n", ranksPerChannel); 99 100 for (int i = 0; i < ranksPerChannel; i++) { 101 Rank* rank = new Rank(*this, p); 102 ranks.push_back(rank); 103 104 rank->actTicks.resize(activationLimit, 0); 105 rank->banks.resize(banksPerRank); 106 rank->rank = i; 107 108 for (int b = 0; b < banksPerRank; b++) { 109 rank->banks[b].bank = b; 110 // GDDR addressing of banks to BG is linear. 111 // Here we assume that all DRAM generations address bank groups as 112 // follows: 113 if (bankGroupArch) { 114 // Simply assign lower bits to bank group in order to 115 // rotate across bank groups as banks are incremented 116 // e.g. with 4 banks per bank group and 16 banks total: 117 // banks 0,4,8,12 are in bank group 0 118 // banks 1,5,9,13 are in bank group 1 119 // banks 2,6,10,14 are in bank group 2 120 // banks 3,7,11,15 are in bank group 3 121 rank->banks[b].bankgr = b % bankGroupsPerRank; 122 } else { 123 // No bank groups; simply assign to bank number 124 rank->banks[b].bankgr = b; 125 } 126 } 127 } 128 129 // perform a basic check of the write thresholds 130 if (p->write_low_thresh_perc >= p->write_high_thresh_perc) 131 fatal("Write buffer low threshold %d must be smaller than the " 132 "high threshold %d\n", p->write_low_thresh_perc, 133 p->write_high_thresh_perc); 134 135 // determine the rows per bank by looking at the total capacity 136 uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size()); 137 138 // determine the dram actual capacity from the DRAM config in Mbytes 139 uint64_t deviceCapacity = deviceSize / (1024 * 1024) * devicesPerRank * 140 ranksPerChannel; 141 142 // if actual DRAM size does not match memory capacity in system warn! 143 if (deviceCapacity != capacity / (1024 * 1024)) 144 warn("DRAM device capacity (%d Mbytes) does not match the " 145 "address range assigned (%d Mbytes)\n", deviceCapacity, 146 capacity / (1024 * 1024)); 147 148 DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity, 149 AbstractMemory::size()); 150 151 DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n", 152 rowBufferSize, columnsPerRowBuffer); 153 154 rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel); 155 156 // some basic sanity checks 157 if (tREFI <= tRP || tREFI <= tRFC) { 158 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n", 159 tREFI, tRP, tRFC); 160 } 161 162 // basic bank group architecture checks -> 163 if (bankGroupArch) { 164 // must have at least one bank per bank group 165 if (bankGroupsPerRank > banksPerRank) { 166 fatal("banks per rank (%d) must be equal to or larger than " 167 "banks groups per rank (%d)\n", 168 banksPerRank, bankGroupsPerRank); 169 } 170 // must have same number of banks in each bank group 171 if ((banksPerRank % bankGroupsPerRank) != 0) { 172 fatal("Banks per rank (%d) must be evenly divisible by bank groups " 173 "per rank (%d) for equal banks per bank group\n", 174 banksPerRank, bankGroupsPerRank); 175 } 176 // tCCD_L should be greater than minimal, back-to-back burst delay 177 if (tCCD_L <= tBURST) { 178 fatal("tCCD_L (%d) should be larger than tBURST (%d) when " 179 "bank groups per rank (%d) is greater than 1\n", 180 tCCD_L, tBURST, bankGroupsPerRank); 181 } 182 // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay 183 // some datasheets might specify it equal to tRRD 184 if (tRRD_L < tRRD) { 185 fatal("tRRD_L (%d) should be larger than tRRD (%d) when " 186 "bank groups per rank (%d) is greater than 1\n", 187 tRRD_L, tRRD, bankGroupsPerRank); 188 } 189 } 190 191} 192 193void 194DRAMCtrl::init() 195{ 196 AbstractMemory::init(); 197 198 if (!port.isConnected()) { 199 fatal("DRAMCtrl %s is unconnected!\n", name()); 200 } else { 201 port.sendRangeChange(); 202 } 203 204 // a bit of sanity checks on the interleaving, save it for here to 205 // ensure that the system pointer is initialised 206 if (range.interleaved()) { 207 if (channels != range.stripes()) 208 fatal("%s has %d interleaved address stripes but %d channel(s)\n", 209 name(), range.stripes(), channels); 210 211 if (addrMapping == Enums::RoRaBaChCo) { 212 if (rowBufferSize != range.granularity()) { 213 fatal("Channel interleaving of %s doesn't match RoRaBaChCo " 214 "address map\n", name()); 215 } 216 } else if (addrMapping == Enums::RoRaBaCoCh || 217 addrMapping == Enums::RoCoRaBaCh) { 218 // for the interleavings with channel bits in the bottom, 219 // if the system uses a channel striping granularity that 220 // is larger than the DRAM burst size, then map the 221 // sequential accesses within a stripe to a number of 222 // columns in the DRAM, effectively placing some of the 223 // lower-order column bits as the least-significant bits 224 // of the address (above the ones denoting the burst size) 225 assert(columnsPerStripe >= 1); 226 227 // channel striping has to be done at a granularity that 228 // is equal or larger to a cache line 229 if (system()->cacheLineSize() > range.granularity()) { 230 fatal("Channel interleaving of %s must be at least as large " 231 "as the cache line size\n", name()); 232 } 233 234 // ...and equal or smaller than the row-buffer size 235 if (rowBufferSize < range.granularity()) { 236 fatal("Channel interleaving of %s must be at most as large " 237 "as the row-buffer size\n", name()); 238 } 239 // this is essentially the check above, so just to be sure 240 assert(columnsPerStripe <= columnsPerRowBuffer); 241 } 242 } 243} 244 245void 246DRAMCtrl::startup() 247{ 248 // remember the memory system mode of operation 249 isTimingMode = system()->isTimingMode(); 250 251 if (isTimingMode) { 252 // timestamp offset should be in clock cycles for DRAMPower 253 timeStampOffset = divCeil(curTick(), tCK); 254 255 // update the start tick for the precharge accounting to the 256 // current tick 257 for (auto r : ranks) { 258 r->startup(curTick() + tREFI - tRP); 259 } 260 261 // shift the bus busy time sufficiently far ahead that we never 262 // have to worry about negative values when computing the time for 263 // the next request, this will add an insignificant bubble at the 264 // start of simulation 265 busBusyUntil = curTick() + tRP + tRCD + tCL; 266 } 267} 268 269Tick 270DRAMCtrl::recvAtomic(PacketPtr pkt) 271{ 272 DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr()); 273 274 // do the actual memory access and turn the packet into a response 275 access(pkt); 276 277 Tick latency = 0; 278 if (!pkt->memInhibitAsserted() && pkt->hasData()) { 279 // this value is not supposed to be accurate, just enough to 280 // keep things going, mimic a closed page 281 latency = tRP + tRCD + tCL; 282 } 283 return latency; 284} 285 286bool 287DRAMCtrl::readQueueFull(unsigned int neededEntries) const 288{ 289 DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n", 290 readBufferSize, readQueue.size() + respQueue.size(), 291 neededEntries); 292 293 return 294 (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize; 295} 296 297bool 298DRAMCtrl::writeQueueFull(unsigned int neededEntries) const 299{ 300 DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n", 301 writeBufferSize, writeQueue.size(), neededEntries); 302 return (writeQueue.size() + neededEntries) > writeBufferSize; 303} 304 305DRAMCtrl::DRAMPacket* 306DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size, 307 bool isRead) 308{ 309 // decode the address based on the address mapping scheme, with 310 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and 311 // channel, respectively 312 uint8_t rank; 313 uint8_t bank; 314 // use a 64-bit unsigned during the computations as the row is 315 // always the top bits, and check before creating the DRAMPacket 316 uint64_t row; 317 318 // truncate the address to a DRAM burst, which makes it unique to 319 // a specific column, row, bank, rank and channel 320 Addr addr = dramPktAddr / burstSize; 321 322 // we have removed the lowest order address bits that denote the 323 // position within the column 324 if (addrMapping == Enums::RoRaBaChCo) { 325 // the lowest order bits denote the column to ensure that 326 // sequential cache lines occupy the same row 327 addr = addr / columnsPerRowBuffer; 328 329 // take out the channel part of the address 330 addr = addr / channels; 331 332 // after the channel bits, get the bank bits to interleave 333 // over the banks 334 bank = addr % banksPerRank; 335 addr = addr / banksPerRank; 336 337 // after the bank, we get the rank bits which thus interleaves 338 // over the ranks 339 rank = addr % ranksPerChannel; 340 addr = addr / ranksPerChannel; 341 342 // lastly, get the row bits 343 row = addr % rowsPerBank; 344 addr = addr / rowsPerBank; 345 } else if (addrMapping == Enums::RoRaBaCoCh) { 346 // take out the lower-order column bits 347 addr = addr / columnsPerStripe; 348 349 // take out the channel part of the address 350 addr = addr / channels; 351 352 // next, the higher-order column bites 353 addr = addr / (columnsPerRowBuffer / columnsPerStripe); 354 355 // after the column bits, we get the bank bits to interleave 356 // over the banks 357 bank = addr % banksPerRank; 358 addr = addr / banksPerRank; 359 360 // after the bank, we get the rank bits which thus interleaves 361 // over the ranks 362 rank = addr % ranksPerChannel; 363 addr = addr / ranksPerChannel; 364 365 // lastly, get the row bits 366 row = addr % rowsPerBank; 367 addr = addr / rowsPerBank; 368 } else if (addrMapping == Enums::RoCoRaBaCh) { 369 // optimise for closed page mode and utilise maximum 370 // parallelism of the DRAM (at the cost of power) 371 372 // take out the lower-order column bits 373 addr = addr / columnsPerStripe; 374 375 // take out the channel part of the address, not that this has 376 // to match with how accesses are interleaved between the 377 // controllers in the address mapping 378 addr = addr / channels; 379 380 // start with the bank bits, as this provides the maximum 381 // opportunity for parallelism between requests 382 bank = addr % banksPerRank; 383 addr = addr / banksPerRank; 384 385 // next get the rank bits 386 rank = addr % ranksPerChannel; 387 addr = addr / ranksPerChannel; 388 389 // next, the higher-order column bites 390 addr = addr / (columnsPerRowBuffer / columnsPerStripe); 391 392 // lastly, get the row bits 393 row = addr % rowsPerBank; 394 addr = addr / rowsPerBank; 395 } else 396 panic("Unknown address mapping policy chosen!"); 397 398 assert(rank < ranksPerChannel); 399 assert(bank < banksPerRank); 400 assert(row < rowsPerBank); 401 assert(row < Bank::NO_ROW); 402 403 DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n", 404 dramPktAddr, rank, bank, row); 405 406 // create the corresponding DRAM packet with the entry time and 407 // ready time set to the current tick, the latter will be updated 408 // later 409 uint16_t bank_id = banksPerRank * rank + bank; 410 return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr, 411 size, ranks[rank]->banks[bank], *ranks[rank]); 412} 413 414void 415DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount) 416{ 417 // only add to the read queue here. whenever the request is 418 // eventually done, set the readyTime, and call schedule() 419 assert(!pkt->isWrite()); 420 421 assert(pktCount != 0); 422 423 // if the request size is larger than burst size, the pkt is split into 424 // multiple DRAM packets 425 // Note if the pkt starting address is not aligened to burst size, the 426 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets 427 // are aligned to burst size boundaries. This is to ensure we accurately 428 // check read packets against packets in write queue. 429 Addr addr = pkt->getAddr(); 430 unsigned pktsServicedByWrQ = 0; 431 BurstHelper* burst_helper = NULL; 432 for (int cnt = 0; cnt < pktCount; ++cnt) { 433 unsigned size = std::min((addr | (burstSize - 1)) + 1, 434 pkt->getAddr() + pkt->getSize()) - addr; 435 readPktSize[ceilLog2(size)]++; 436 readBursts++; 437 438 // First check write buffer to see if the data is already at 439 // the controller 440 bool foundInWrQ = false; 441 for (auto i = writeQueue.begin(); i != writeQueue.end(); ++i) { 442 // check if the read is subsumed in the write entry we are 443 // looking at 444 if ((*i)->addr <= addr && 445 (addr + size) <= ((*i)->addr + (*i)->size)) { 446 foundInWrQ = true; 447 servicedByWrQ++; 448 pktsServicedByWrQ++; 449 DPRINTF(DRAM, "Read to addr %lld with size %d serviced by " 450 "write queue\n", addr, size); 451 bytesReadWrQ += burstSize; 452 break; 453 } 454 } 455 456 // If not found in the write q, make a DRAM packet and 457 // push it onto the read queue 458 if (!foundInWrQ) { 459 460 // Make the burst helper for split packets 461 if (pktCount > 1 && burst_helper == NULL) { 462 DPRINTF(DRAM, "Read to addr %lld translates to %d " 463 "dram requests\n", pkt->getAddr(), pktCount); 464 burst_helper = new BurstHelper(pktCount); 465 } 466 467 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true); 468 dram_pkt->burstHelper = burst_helper; 469 470 assert(!readQueueFull(1)); 471 rdQLenPdf[readQueue.size() + respQueue.size()]++; 472 473 DPRINTF(DRAM, "Adding to read queue\n"); 474 475 readQueue.push_back(dram_pkt); 476 477 // Update stats 478 avgRdQLen = readQueue.size() + respQueue.size(); 479 } 480 481 // Starting address of next dram pkt (aligend to burstSize boundary) 482 addr = (addr | (burstSize - 1)) + 1; 483 } 484 485 // If all packets are serviced by write queue, we send the repsonse back 486 if (pktsServicedByWrQ == pktCount) { 487 accessAndRespond(pkt, frontendLatency); 488 return; 489 } 490 491 // Update how many split packets are serviced by write queue 492 if (burst_helper != NULL) 493 burst_helper->burstsServiced = pktsServicedByWrQ; 494 495 // If we are not already scheduled to get a request out of the 496 // queue, do so now 497 if (!nextReqEvent.scheduled()) { 498 DPRINTF(DRAM, "Request scheduled immediately\n"); 499 schedule(nextReqEvent, curTick()); 500 } 501} 502 503void 504DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount) 505{ 506 // only add to the write queue here. whenever the request is 507 // eventually done, set the readyTime, and call schedule() 508 assert(pkt->isWrite()); 509 510 // if the request size is larger than burst size, the pkt is split into 511 // multiple DRAM packets 512 Addr addr = pkt->getAddr(); 513 for (int cnt = 0; cnt < pktCount; ++cnt) { 514 unsigned size = std::min((addr | (burstSize - 1)) + 1, 515 pkt->getAddr() + pkt->getSize()) - addr; 516 writePktSize[ceilLog2(size)]++; 517 writeBursts++; 518 519 // see if we can merge with an existing item in the write 520 // queue and keep track of whether we have merged or not so we 521 // can stop at that point and also avoid enqueueing a new 522 // request 523 bool merged = false; 524 auto w = writeQueue.begin(); 525 526 while(!merged && w != writeQueue.end()) { 527 // either of the two could be first, if they are the same 528 // it does not matter which way we go 529 if ((*w)->addr >= addr) { 530 // the existing one starts after the new one, figure 531 // out where the new one ends with respect to the 532 // existing one 533 if ((addr + size) >= ((*w)->addr + (*w)->size)) { 534 // check if the existing one is completely 535 // subsumed in the new one 536 DPRINTF(DRAM, "Merging write covering existing burst\n"); 537 merged = true; 538 // update both the address and the size 539 (*w)->addr = addr; 540 (*w)->size = size; 541 } else if ((addr + size) >= (*w)->addr && 542 ((*w)->addr + (*w)->size - addr) <= burstSize) { 543 // the new one is just before or partially 544 // overlapping with the existing one, and together 545 // they fit within a burst 546 DPRINTF(DRAM, "Merging write before existing burst\n"); 547 merged = true; 548 // the existing queue item needs to be adjusted with 549 // respect to both address and size 550 (*w)->size = (*w)->addr + (*w)->size - addr; 551 (*w)->addr = addr; 552 } 553 } else { 554 // the new one starts after the current one, figure 555 // out where the existing one ends with respect to the 556 // new one 557 if (((*w)->addr + (*w)->size) >= (addr + size)) { 558 // check if the new one is completely subsumed in the 559 // existing one 560 DPRINTF(DRAM, "Merging write into existing burst\n"); 561 merged = true; 562 // no adjustments necessary 563 } else if (((*w)->addr + (*w)->size) >= addr && 564 (addr + size - (*w)->addr) <= burstSize) { 565 // the existing one is just before or partially 566 // overlapping with the new one, and together 567 // they fit within a burst 568 DPRINTF(DRAM, "Merging write after existing burst\n"); 569 merged = true; 570 // the address is right, and only the size has 571 // to be adjusted 572 (*w)->size = addr + size - (*w)->addr; 573 } 574 } 575 ++w; 576 } 577 578 // if the item was not merged we need to create a new write 579 // and enqueue it 580 if (!merged) { 581 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false); 582 583 assert(writeQueue.size() < writeBufferSize); 584 wrQLenPdf[writeQueue.size()]++; 585 586 DPRINTF(DRAM, "Adding to write queue\n"); 587 588 writeQueue.push_back(dram_pkt); 589 590 // Update stats 591 avgWrQLen = writeQueue.size(); 592 } else { 593 // keep track of the fact that this burst effectively 594 // disappeared as it was merged with an existing one 595 mergedWrBursts++; 596 } 597 598 // Starting address of next dram pkt (aligend to burstSize boundary) 599 addr = (addr | (burstSize - 1)) + 1; 600 } 601 602 // we do not wait for the writes to be send to the actual memory, 603 // but instead take responsibility for the consistency here and 604 // snoop the write queue for any upcoming reads 605 // @todo, if a pkt size is larger than burst size, we might need a 606 // different front end latency 607 accessAndRespond(pkt, frontendLatency); 608 609 // If we are not already scheduled to get a request out of the 610 // queue, do so now 611 if (!nextReqEvent.scheduled()) { 612 DPRINTF(DRAM, "Request scheduled immediately\n"); 613 schedule(nextReqEvent, curTick()); 614 } 615} 616 617void 618DRAMCtrl::printQs() const { 619 DPRINTF(DRAM, "===READ QUEUE===\n\n"); 620 for (auto i = readQueue.begin() ; i != readQueue.end() ; ++i) { 621 DPRINTF(DRAM, "Read %lu\n", (*i)->addr); 622 } 623 DPRINTF(DRAM, "\n===RESP QUEUE===\n\n"); 624 for (auto i = respQueue.begin() ; i != respQueue.end() ; ++i) { 625 DPRINTF(DRAM, "Response %lu\n", (*i)->addr); 626 } 627 DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n"); 628 for (auto i = writeQueue.begin() ; i != writeQueue.end() ; ++i) { 629 DPRINTF(DRAM, "Write %lu\n", (*i)->addr); 630 } 631} 632 633bool 634DRAMCtrl::recvTimingReq(PacketPtr pkt) 635{ 636 /// @todo temporary hack to deal with memory corruption issues until 637 /// 4-phase transactions are complete 638 for (int x = 0; x < pendingDelete.size(); x++) 639 delete pendingDelete[x]; 640 pendingDelete.clear(); 641 642 // This is where we enter from the outside world 643 DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n", 644 pkt->cmdString(), pkt->getAddr(), pkt->getSize()); 645 646 // simply drop inhibited packets and clean evictions 647 if (pkt->memInhibitAsserted() || 648 pkt->cmd == MemCmd::CleanEvict) { 649 DPRINTF(DRAM, "Inhibited packet or clean evict -- Dropping it now\n"); 650 pendingDelete.push_back(pkt); 651 return true; 652 } 653 654 // Calc avg gap between requests 655 if (prevArrival != 0) { 656 totGap += curTick() - prevArrival; 657 } 658 prevArrival = curTick(); 659 660 661 // Find out how many dram packets a pkt translates to 662 // If the burst size is equal or larger than the pkt size, then a pkt 663 // translates to only one dram packet. Otherwise, a pkt translates to 664 // multiple dram packets 665 unsigned size = pkt->getSize(); 666 unsigned offset = pkt->getAddr() & (burstSize - 1); 667 unsigned int dram_pkt_count = divCeil(offset + size, burstSize); 668 669 // check local buffers and do not accept if full 670 if (pkt->isRead()) { 671 assert(size != 0); 672 if (readQueueFull(dram_pkt_count)) { 673 DPRINTF(DRAM, "Read queue full, not accepting\n"); 674 // remember that we have to retry this port 675 retryRdReq = true; 676 numRdRetry++; 677 return false; 678 } else { 679 addToReadQueue(pkt, dram_pkt_count); 680 readReqs++; 681 bytesReadSys += size; 682 } 683 } else if (pkt->isWrite()) { 684 assert(size != 0); 685 if (writeQueueFull(dram_pkt_count)) { 686 DPRINTF(DRAM, "Write queue full, not accepting\n"); 687 // remember that we have to retry this port 688 retryWrReq = true; 689 numWrRetry++; 690 return false; 691 } else { 692 addToWriteQueue(pkt, dram_pkt_count); 693 writeReqs++; 694 bytesWrittenSys += size; 695 } 696 } else { 697 DPRINTF(DRAM,"Neither read nor write, ignore timing\n"); 698 neitherReadNorWrite++; 699 accessAndRespond(pkt, 1); 700 } 701 702 return true; 703} 704 705void 706DRAMCtrl::processRespondEvent() 707{ 708 DPRINTF(DRAM, 709 "processRespondEvent(): Some req has reached its readyTime\n"); 710 711 DRAMPacket* dram_pkt = respQueue.front(); 712 713 if (dram_pkt->burstHelper) { 714 // it is a split packet 715 dram_pkt->burstHelper->burstsServiced++; 716 if (dram_pkt->burstHelper->burstsServiced == 717 dram_pkt->burstHelper->burstCount) { 718 // we have now serviced all children packets of a system packet 719 // so we can now respond to the requester 720 // @todo we probably want to have a different front end and back 721 // end latency for split packets 722 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency); 723 delete dram_pkt->burstHelper; 724 dram_pkt->burstHelper = NULL; 725 } 726 } else { 727 // it is not a split packet 728 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency); 729 } 730 731 delete respQueue.front(); 732 respQueue.pop_front(); 733 734 if (!respQueue.empty()) { 735 assert(respQueue.front()->readyTime >= curTick()); 736 assert(!respondEvent.scheduled()); 737 schedule(respondEvent, respQueue.front()->readyTime); 738 } else { 739 // if there is nothing left in any queue, signal a drain 740 if (writeQueue.empty() && readQueue.empty() && 741 drainManager) { 742 DPRINTF(Drain, "DRAM controller done draining\n"); 743 drainManager->signalDrainDone(); 744 drainManager = NULL; 745 } 746 } 747 748 // We have made a location in the queue available at this point, 749 // so if there is a read that was forced to wait, retry now 750 if (retryRdReq) { 751 retryRdReq = false; 752 port.sendRetryReq(); 753 } 754} 755 756bool 757DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue, bool switched_cmd_type) 758{ 759 // This method does the arbitration between requests. The chosen 760 // packet is simply moved to the head of the queue. The other 761 // methods know that this is the place to look. For example, with 762 // FCFS, this method does nothing 763 assert(!queue.empty()); 764 765 // bool to indicate if a packet to an available rank is found 766 bool found_packet = false; 767 if (queue.size() == 1) { 768 DRAMPacket* dram_pkt = queue.front(); 769 // available rank corresponds to state refresh idle 770 if (ranks[dram_pkt->rank]->isAvailable()) { 771 found_packet = true; 772 DPRINTF(DRAM, "Single request, going to a free rank\n"); 773 } else { 774 DPRINTF(DRAM, "Single request, going to a busy rank\n"); 775 } 776 return found_packet; 777 } 778 779 if (memSchedPolicy == Enums::fcfs) { 780 // check if there is a packet going to a free rank 781 for(auto i = queue.begin(); i != queue.end() ; ++i) { 782 DRAMPacket* dram_pkt = *i; 783 if (ranks[dram_pkt->rank]->isAvailable()) { 784 queue.erase(i); 785 queue.push_front(dram_pkt); 786 found_packet = true; 787 break; 788 } 789 } 790 } else if (memSchedPolicy == Enums::frfcfs) { 791 found_packet = reorderQueue(queue, switched_cmd_type); 792 } else 793 panic("No scheduling policy chosen\n"); 794 return found_packet; 795} 796 797bool 798DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, bool switched_cmd_type) 799{ 800 // Only determine this when needed 801 uint64_t earliest_banks = 0; 802 803 // Search for row hits first, if no row hit is found then schedule the 804 // packet to one of the earliest banks available 805 bool found_packet = false; 806 bool found_earliest_pkt = false; 807 bool found_prepped_diff_rank_pkt = false; 808 auto selected_pkt_it = queue.end(); 809 810 for (auto i = queue.begin(); i != queue.end() ; ++i) { 811 DRAMPacket* dram_pkt = *i; 812 const Bank& bank = dram_pkt->bankRef; 813 // check if rank is busy. If this is the case jump to the next packet 814 // Check if it is a row hit 815 if (dram_pkt->rankRef.isAvailable()) { 816 if (bank.openRow == dram_pkt->row) { 817 if (dram_pkt->rank == activeRank || switched_cmd_type) { 818 // FCFS within the hits, giving priority to commands 819 // that access the same rank as the previous burst 820 // to minimize bus turnaround delays 821 // Only give rank prioity when command type is 822 // not changing 823 DPRINTF(DRAM, "Row buffer hit\n"); 824 selected_pkt_it = i; 825 break; 826 } else if (!found_prepped_diff_rank_pkt) { 827 // found row hit for command on different rank 828 // than prev burst 829 selected_pkt_it = i; 830 found_prepped_diff_rank_pkt = true; 831 } 832 } else if (!found_earliest_pkt & !found_prepped_diff_rank_pkt) { 833 // packet going to a rank which is currently not waiting for a 834 // refresh, No row hit and 835 // haven't found an entry with a row hit to a new rank 836 if (earliest_banks == 0) 837 // Determine entries with earliest bank prep delay 838 // Function will give priority to commands that access the 839 // same rank as previous burst and can prep 840 // the bank seamlessly 841 earliest_banks = minBankPrep(queue, switched_cmd_type); 842 843 // FCFS - Bank is first available bank 844 if (bits(earliest_banks, dram_pkt->bankId, 845 dram_pkt->bankId)) { 846 // Remember the packet to be scheduled to one of 847 // the earliest banks available, FCFS amongst the 848 // earliest banks 849 selected_pkt_it = i; 850 //if the packet found is going to a rank that is currently 851 //not busy then update the found_packet to true 852 found_earliest_pkt = true; 853 } 854 } 855 } 856 } 857 858 if (selected_pkt_it != queue.end()) { 859 DRAMPacket* selected_pkt = *selected_pkt_it; 860 queue.erase(selected_pkt_it); 861 queue.push_front(selected_pkt); 862 found_packet = true; 863 } 864 return found_packet; 865} 866 867void 868DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency) 869{ 870 DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr()); 871 872 bool needsResponse = pkt->needsResponse(); 873 // do the actual memory access which also turns the packet into a 874 // response 875 access(pkt); 876 877 // turn packet around to go back to requester if response expected 878 if (needsResponse) { 879 // access already turned the packet into a response 880 assert(pkt->isResponse()); 881 // response_time consumes the static latency and is charged also 882 // with headerDelay that takes into account the delay provided by 883 // the xbar and also the payloadDelay that takes into account the 884 // number of data beats. 885 Tick response_time = curTick() + static_latency + pkt->headerDelay + 886 pkt->payloadDelay; 887 // Here we reset the timing of the packet before sending it out. 888 pkt->headerDelay = pkt->payloadDelay = 0; 889 890 // queue the packet in the response queue to be sent out after 891 // the static latency has passed 892 port.schedTimingResp(pkt, response_time); 893 } else { 894 // @todo the packet is going to be deleted, and the DRAMPacket 895 // is still having a pointer to it 896 pendingDelete.push_back(pkt); 897 } 898 899 DPRINTF(DRAM, "Done\n"); 900 901 return; 902} 903 904void 905DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref, 906 Tick act_tick, uint32_t row) 907{ 908 assert(rank_ref.actTicks.size() == activationLimit); 909 910 DPRINTF(DRAM, "Activate at tick %d\n", act_tick); 911 912 // update the open row 913 assert(bank_ref.openRow == Bank::NO_ROW); 914 bank_ref.openRow = row; 915 916 // start counting anew, this covers both the case when we 917 // auto-precharged, and when this access is forced to 918 // precharge 919 bank_ref.bytesAccessed = 0; 920 bank_ref.rowAccesses = 0; 921 922 ++rank_ref.numBanksActive; 923 assert(rank_ref.numBanksActive <= banksPerRank); 924 925 DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n", 926 bank_ref.bank, rank_ref.rank, act_tick, 927 ranks[rank_ref.rank]->numBanksActive); 928 929 rank_ref.power.powerlib.doCommand(MemCommand::ACT, bank_ref.bank, 930 divCeil(act_tick, tCK) - 931 timeStampOffset); 932 933 DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) - 934 timeStampOffset, bank_ref.bank, rank_ref.rank); 935 936 // The next access has to respect tRAS for this bank 937 bank_ref.preAllowedAt = act_tick + tRAS; 938 939 // Respect the row-to-column command delay 940 bank_ref.colAllowedAt = std::max(act_tick + tRCD, bank_ref.colAllowedAt); 941 942 // start by enforcing tRRD 943 for(int i = 0; i < banksPerRank; i++) { 944 // next activate to any bank in this rank must not happen 945 // before tRRD 946 if (bankGroupArch && (bank_ref.bankgr == rank_ref.banks[i].bankgr)) { 947 // bank group architecture requires longer delays between 948 // ACT commands within the same bank group. Use tRRD_L 949 // in this case 950 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD_L, 951 rank_ref.banks[i].actAllowedAt); 952 } else { 953 // use shorter tRRD value when either 954 // 1) bank group architecture is not supportted 955 // 2) bank is in a different bank group 956 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD, 957 rank_ref.banks[i].actAllowedAt); 958 } 959 } 960 961 // next, we deal with tXAW, if the activation limit is disabled 962 // then we directly schedule an activate power event 963 if (!rank_ref.actTicks.empty()) { 964 // sanity check 965 if (rank_ref.actTicks.back() && 966 (act_tick - rank_ref.actTicks.back()) < tXAW) { 967 panic("Got %d activates in window %d (%llu - %llu) which " 968 "is smaller than %llu\n", activationLimit, act_tick - 969 rank_ref.actTicks.back(), act_tick, 970 rank_ref.actTicks.back(), tXAW); 971 } 972 973 // shift the times used for the book keeping, the last element 974 // (highest index) is the oldest one and hence the lowest value 975 rank_ref.actTicks.pop_back(); 976 977 // record an new activation (in the future) 978 rank_ref.actTicks.push_front(act_tick); 979 980 // cannot activate more than X times in time window tXAW, push the 981 // next one (the X + 1'st activate) to be tXAW away from the 982 // oldest in our window of X 983 if (rank_ref.actTicks.back() && 984 (act_tick - rank_ref.actTicks.back()) < tXAW) { 985 DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate " 986 "no earlier than %llu\n", activationLimit, 987 rank_ref.actTicks.back() + tXAW); 988 for(int j = 0; j < banksPerRank; j++) 989 // next activate must not happen before end of window 990 rank_ref.banks[j].actAllowedAt = 991 std::max(rank_ref.actTicks.back() + tXAW, 992 rank_ref.banks[j].actAllowedAt); 993 } 994 } 995 996 // at the point when this activate takes place, make sure we 997 // transition to the active power state 998 if (!rank_ref.activateEvent.scheduled()) 999 schedule(rank_ref.activateEvent, act_tick); 1000 else if (rank_ref.activateEvent.when() > act_tick) 1001 // move it sooner in time 1002 reschedule(rank_ref.activateEvent, act_tick); 1003} 1004 1005void 1006DRAMCtrl::prechargeBank(Rank& rank_ref, Bank& bank, Tick pre_at, bool trace) 1007{ 1008 // make sure the bank has an open row 1009 assert(bank.openRow != Bank::NO_ROW); 1010 1011 // sample the bytes per activate here since we are closing 1012 // the page 1013 bytesPerActivate.sample(bank.bytesAccessed); 1014 1015 bank.openRow = Bank::NO_ROW; 1016 1017 // no precharge allowed before this one 1018 bank.preAllowedAt = pre_at; 1019 1020 Tick pre_done_at = pre_at + tRP; 1021 1022 bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at); 1023 1024 assert(rank_ref.numBanksActive != 0); 1025 --rank_ref.numBanksActive; 1026 1027 DPRINTF(DRAM, "Precharging bank %d, rank %d at tick %lld, now got " 1028 "%d active\n", bank.bank, rank_ref.rank, pre_at, 1029 rank_ref.numBanksActive); 1030 1031 if (trace) { 1032 1033 rank_ref.power.powerlib.doCommand(MemCommand::PRE, bank.bank, 1034 divCeil(pre_at, tCK) - 1035 timeStampOffset); 1036 DPRINTF(DRAMPower, "%llu,PRE,%d,%d\n", divCeil(pre_at, tCK) - 1037 timeStampOffset, bank.bank, rank_ref.rank); 1038 } 1039 // if we look at the current number of active banks we might be 1040 // tempted to think the DRAM is now idle, however this can be 1041 // undone by an activate that is scheduled to happen before we 1042 // would have reached the idle state, so schedule an event and 1043 // rather check once we actually make it to the point in time when 1044 // the (last) precharge takes place 1045 if (!rank_ref.prechargeEvent.scheduled()) 1046 schedule(rank_ref.prechargeEvent, pre_done_at); 1047 else if (rank_ref.prechargeEvent.when() < pre_done_at) 1048 reschedule(rank_ref.prechargeEvent, pre_done_at); 1049} 1050 1051void 1052DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt) 1053{ 1054 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n", 1055 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row); 1056 1057 // get the rank 1058 Rank& rank = dram_pkt->rankRef; 1059 1060 // get the bank 1061 Bank& bank = dram_pkt->bankRef; 1062 1063 // for the state we need to track if it is a row hit or not 1064 bool row_hit = true; 1065 1066 // respect any constraints on the command (e.g. tRCD or tCCD) 1067 Tick cmd_at = std::max(bank.colAllowedAt, curTick()); 1068 1069 // Determine the access latency and update the bank state 1070 if (bank.openRow == dram_pkt->row) { 1071 // nothing to do 1072 } else { 1073 row_hit = false; 1074 1075 // If there is a page open, precharge it. 1076 if (bank.openRow != Bank::NO_ROW) { 1077 prechargeBank(rank, bank, std::max(bank.preAllowedAt, curTick())); 1078 } 1079 1080 // next we need to account for the delay in activating the 1081 // page 1082 Tick act_tick = std::max(bank.actAllowedAt, curTick()); 1083 1084 // Record the activation and deal with all the global timing 1085 // constraints caused be a new activation (tRRD and tXAW) 1086 activateBank(rank, bank, act_tick, dram_pkt->row); 1087 1088 // issue the command as early as possible 1089 cmd_at = bank.colAllowedAt; 1090 } 1091 1092 // we need to wait until the bus is available before we can issue 1093 // the command 1094 cmd_at = std::max(cmd_at, busBusyUntil - tCL); 1095 1096 // update the packet ready time 1097 dram_pkt->readyTime = cmd_at + tCL + tBURST; 1098 1099 // only one burst can use the bus at any one point in time 1100 assert(dram_pkt->readyTime - busBusyUntil >= tBURST); 1101 1102 // update the time for the next read/write burst for each 1103 // bank (add a max with tCCD/tCCD_L here) 1104 Tick cmd_dly; 1105 for(int j = 0; j < ranksPerChannel; j++) { 1106 for(int i = 0; i < banksPerRank; i++) { 1107 // next burst to same bank group in this rank must not happen 1108 // before tCCD_L. Different bank group timing requirement is 1109 // tBURST; Add tCS for different ranks 1110 if (dram_pkt->rank == j) { 1111 if (bankGroupArch && 1112 (bank.bankgr == ranks[j]->banks[i].bankgr)) { 1113 // bank group architecture requires longer delays between 1114 // RD/WR burst commands to the same bank group. 1115 // Use tCCD_L in this case 1116 cmd_dly = tCCD_L; 1117 } else { 1118 // use tBURST (equivalent to tCCD_S), the shorter 1119 // cas-to-cas delay value, when either: 1120 // 1) bank group architecture is not supportted 1121 // 2) bank is in a different bank group 1122 cmd_dly = tBURST; 1123 } 1124 } else { 1125 // different rank is by default in a different bank group 1126 // use tBURST (equivalent to tCCD_S), which is the shorter 1127 // cas-to-cas delay in this case 1128 // Add tCS to account for rank-to-rank bus delay requirements 1129 cmd_dly = tBURST + tCS; 1130 } 1131 ranks[j]->banks[i].colAllowedAt = std::max(cmd_at + cmd_dly, 1132 ranks[j]->banks[i].colAllowedAt); 1133 } 1134 } 1135 1136 // Save rank of current access 1137 activeRank = dram_pkt->rank; 1138 1139 // If this is a write, we also need to respect the write recovery 1140 // time before a precharge, in the case of a read, respect the 1141 // read to precharge constraint 1142 bank.preAllowedAt = std::max(bank.preAllowedAt, 1143 dram_pkt->isRead ? cmd_at + tRTP : 1144 dram_pkt->readyTime + tWR); 1145 1146 // increment the bytes accessed and the accesses per row 1147 bank.bytesAccessed += burstSize; 1148 ++bank.rowAccesses; 1149 1150 // if we reached the max, then issue with an auto-precharge 1151 bool auto_precharge = pageMgmt == Enums::close || 1152 bank.rowAccesses == maxAccessesPerRow; 1153 1154 // if we did not hit the limit, we might still want to 1155 // auto-precharge 1156 if (!auto_precharge && 1157 (pageMgmt == Enums::open_adaptive || 1158 pageMgmt == Enums::close_adaptive)) { 1159 // a twist on the open and close page policies: 1160 // 1) open_adaptive page policy does not blindly keep the 1161 // page open, but close it if there are no row hits, and there 1162 // are bank conflicts in the queue 1163 // 2) close_adaptive page policy does not blindly close the 1164 // page, but closes it only if there are no row hits in the queue. 1165 // In this case, only force an auto precharge when there 1166 // are no same page hits in the queue 1167 bool got_more_hits = false; 1168 bool got_bank_conflict = false; 1169 1170 // either look at the read queue or write queue 1171 const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue : 1172 writeQueue; 1173 auto p = queue.begin(); 1174 // make sure we are not considering the packet that we are 1175 // currently dealing with (which is the head of the queue) 1176 ++p; 1177 1178 // keep on looking until we find a hit or reach the end of the queue 1179 // 1) if a hit is found, then both open and close adaptive policies keep 1180 // the page open 1181 // 2) if no hit is found, got_bank_conflict is set to true if a bank 1182 // conflict request is waiting in the queue 1183 while (!got_more_hits && p != queue.end()) { 1184 bool same_rank_bank = (dram_pkt->rank == (*p)->rank) && 1185 (dram_pkt->bank == (*p)->bank); 1186 bool same_row = dram_pkt->row == (*p)->row; 1187 got_more_hits |= same_rank_bank && same_row; 1188 got_bank_conflict |= same_rank_bank && !same_row; 1189 ++p; 1190 } 1191 1192 // auto pre-charge when either 1193 // 1) open_adaptive policy, we have not got any more hits, and 1194 // have a bank conflict 1195 // 2) close_adaptive policy and we have not got any more hits 1196 auto_precharge = !got_more_hits && 1197 (got_bank_conflict || pageMgmt == Enums::close_adaptive); 1198 } 1199 1200 // DRAMPower trace command to be written 1201 std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR"; 1202 1203 // MemCommand required for DRAMPower library 1204 MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD : 1205 MemCommand::WR; 1206 1207 // if this access should use auto-precharge, then we are 1208 // closing the row 1209 if (auto_precharge) { 1210 // if auto-precharge push a PRE command at the correct tick to the 1211 // list used by DRAMPower library to calculate power 1212 prechargeBank(rank, bank, std::max(curTick(), bank.preAllowedAt)); 1213 1214 DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId); 1215 } 1216 1217 // Update bus state 1218 busBusyUntil = dram_pkt->readyTime; 1219 1220 DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n", 1221 dram_pkt->addr, dram_pkt->readyTime, busBusyUntil); 1222 1223 dram_pkt->rankRef.power.powerlib.doCommand(command, dram_pkt->bank, 1224 divCeil(cmd_at, tCK) - 1225 timeStampOffset); 1226 1227 DPRINTF(DRAMPower, "%llu,%s,%d,%d\n", divCeil(cmd_at, tCK) - 1228 timeStampOffset, mem_cmd, dram_pkt->bank, dram_pkt->rank); 1229 1230 // Update the minimum timing between the requests, this is a 1231 // conservative estimate of when we have to schedule the next 1232 // request to not introduce any unecessary bubbles. In most cases 1233 // we will wake up sooner than we have to. 1234 nextReqTime = busBusyUntil - (tRP + tRCD + tCL); 1235 1236 // Update the stats and schedule the next request 1237 if (dram_pkt->isRead) { 1238 ++readsThisTime; 1239 if (row_hit) 1240 readRowHits++; 1241 bytesReadDRAM += burstSize; 1242 perBankRdBursts[dram_pkt->bankId]++; 1243 1244 // Update latency stats 1245 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime; 1246 totBusLat += tBURST; 1247 totQLat += cmd_at - dram_pkt->entryTime; 1248 } else { 1249 ++writesThisTime; 1250 if (row_hit) 1251 writeRowHits++; 1252 bytesWritten += burstSize; 1253 perBankWrBursts[dram_pkt->bankId]++; 1254 } 1255} 1256 1257void 1258DRAMCtrl::processNextReqEvent() 1259{ 1260 int busyRanks = 0; 1261 for (auto r : ranks) { 1262 if (!r->isAvailable()) { 1263 // rank is busy refreshing 1264 busyRanks++; 1265 1266 // let the rank know that if it was waiting to drain, it 1267 // is now done and ready to proceed 1268 r->checkDrainDone(); 1269 } 1270 } 1271 1272 if (busyRanks == ranksPerChannel) { 1273 // if all ranks are refreshing wait for them to finish 1274 // and stall this state machine without taking any further 1275 // action, and do not schedule a new nextReqEvent 1276 return; 1277 } 1278 1279 // pre-emptively set to false. Overwrite if in READ_TO_WRITE 1280 // or WRITE_TO_READ state 1281 bool switched_cmd_type = false; 1282 if (busState == READ_TO_WRITE) { 1283 DPRINTF(DRAM, "Switching to writes after %d reads with %d reads " 1284 "waiting\n", readsThisTime, readQueue.size()); 1285 1286 // sample and reset the read-related stats as we are now 1287 // transitioning to writes, and all reads are done 1288 rdPerTurnAround.sample(readsThisTime); 1289 readsThisTime = 0; 1290 1291 // now proceed to do the actual writes 1292 busState = WRITE; 1293 switched_cmd_type = true; 1294 } else if (busState == WRITE_TO_READ) { 1295 DPRINTF(DRAM, "Switching to reads after %d writes with %d writes " 1296 "waiting\n", writesThisTime, writeQueue.size()); 1297 1298 wrPerTurnAround.sample(writesThisTime); 1299 writesThisTime = 0; 1300 1301 busState = READ; 1302 switched_cmd_type = true; 1303 } 1304 1305 // when we get here it is either a read or a write 1306 if (busState == READ) { 1307 1308 // track if we should switch or not 1309 bool switch_to_writes = false; 1310 1311 if (readQueue.empty()) { 1312 // In the case there is no read request to go next, 1313 // trigger writes if we have passed the low threshold (or 1314 // if we are draining) 1315 if (!writeQueue.empty() && 1316 (drainManager || writeQueue.size() > writeLowThreshold)) { 1317 1318 switch_to_writes = true; 1319 } else { 1320 // check if we are drained 1321 if (respQueue.empty () && drainManager) { 1322 DPRINTF(Drain, "DRAM controller done draining\n"); 1323 drainManager->signalDrainDone(); 1324 drainManager = NULL; 1325 } 1326 1327 // nothing to do, not even any point in scheduling an 1328 // event for the next request 1329 return; 1330 } 1331 } else { 1332 // bool to check if there is a read to a free rank 1333 bool found_read = false; 1334 1335 // Figure out which read request goes next, and move it to the 1336 // front of the read queue 1337 found_read = chooseNext(readQueue, switched_cmd_type); 1338 1339 // if no read to an available rank is found then return 1340 // at this point. There could be writes to the available ranks 1341 // which are above the required threshold. However, to 1342 // avoid adding more complexity to the code, return and wait 1343 // for a refresh event to kick things into action again. 1344 if (!found_read) 1345 return; 1346 1347 DRAMPacket* dram_pkt = readQueue.front(); 1348 assert(dram_pkt->rankRef.isAvailable()); 1349 // here we get a bit creative and shift the bus busy time not 1350 // just the tWTR, but also a CAS latency to capture the fact 1351 // that we are allowed to prepare a new bank, but not issue a 1352 // read command until after tWTR, in essence we capture a 1353 // bubble on the data bus that is tWTR + tCL 1354 if (switched_cmd_type && dram_pkt->rank == activeRank) { 1355 busBusyUntil += tWTR + tCL; 1356 } 1357 1358 doDRAMAccess(dram_pkt); 1359 1360 // At this point we're done dealing with the request 1361 readQueue.pop_front(); 1362 1363 // sanity check 1364 assert(dram_pkt->size <= burstSize); 1365 assert(dram_pkt->readyTime >= curTick()); 1366 1367 // Insert into response queue. It will be sent back to the 1368 // requestor at its readyTime 1369 if (respQueue.empty()) { 1370 assert(!respondEvent.scheduled()); 1371 schedule(respondEvent, dram_pkt->readyTime); 1372 } else { 1373 assert(respQueue.back()->readyTime <= dram_pkt->readyTime); 1374 assert(respondEvent.scheduled()); 1375 } 1376 1377 respQueue.push_back(dram_pkt); 1378 1379 // we have so many writes that we have to transition 1380 if (writeQueue.size() > writeHighThreshold) { 1381 switch_to_writes = true; 1382 } 1383 } 1384 1385 // switching to writes, either because the read queue is empty 1386 // and the writes have passed the low threshold (or we are 1387 // draining), or because the writes hit the hight threshold 1388 if (switch_to_writes) { 1389 // transition to writing 1390 busState = READ_TO_WRITE; 1391 } 1392 } else { 1393 // bool to check if write to free rank is found 1394 bool found_write = false; 1395 1396 found_write = chooseNext(writeQueue, switched_cmd_type); 1397 1398 // if no writes to an available rank are found then return. 1399 // There could be reads to the available ranks. However, to avoid 1400 // adding more complexity to the code, return at this point and wait 1401 // for a refresh event to kick things into action again. 1402 if (!found_write) 1403 return; 1404 1405 DRAMPacket* dram_pkt = writeQueue.front(); 1406 assert(dram_pkt->rankRef.isAvailable()); 1407 // sanity check 1408 assert(dram_pkt->size <= burstSize); 1409 1410 // add a bubble to the data bus, as defined by the 1411 // tRTW when access is to the same rank as previous burst 1412 // Different rank timing is handled with tCS, which is 1413 // applied to colAllowedAt 1414 if (switched_cmd_type && dram_pkt->rank == activeRank) { 1415 busBusyUntil += tRTW; 1416 } 1417 1418 doDRAMAccess(dram_pkt); 1419 1420 writeQueue.pop_front(); 1421 delete dram_pkt; 1422 1423 // If we emptied the write queue, or got sufficiently below the 1424 // threshold (using the minWritesPerSwitch as the hysteresis) and 1425 // are not draining, or we have reads waiting and have done enough 1426 // writes, then switch to reads. 1427 if (writeQueue.empty() || 1428 (writeQueue.size() + minWritesPerSwitch < writeLowThreshold && 1429 !drainManager) || 1430 (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) { 1431 // turn the bus back around for reads again 1432 busState = WRITE_TO_READ; 1433 1434 // note that the we switch back to reads also in the idle 1435 // case, which eventually will check for any draining and 1436 // also pause any further scheduling if there is really 1437 // nothing to do 1438 } 1439 } 1440 // It is possible that a refresh to another rank kicks things back into 1441 // action before reaching this point. 1442 if (!nextReqEvent.scheduled()) 1443 schedule(nextReqEvent, std::max(nextReqTime, curTick())); 1444 1445 // If there is space available and we have writes waiting then let 1446 // them retry. This is done here to ensure that the retry does not 1447 // cause a nextReqEvent to be scheduled before we do so as part of 1448 // the next request processing 1449 if (retryWrReq && writeQueue.size() < writeBufferSize) { 1450 retryWrReq = false; 1451 port.sendRetryReq(); 1452 } 1453} 1454 1455uint64_t 1456DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue, 1457 bool switched_cmd_type) const 1458{ 1459 uint64_t bank_mask = 0; 1460 Tick min_act_at = MaxTick; 1461 1462 uint64_t bank_mask_same_rank = 0; 1463 Tick min_act_at_same_rank = MaxTick; 1464 1465 // Give precedence to commands that access same rank as previous command 1466 bool same_rank_match = false; 1467 1468 // determine if we have queued transactions targetting the 1469 // bank in question 1470 vector<bool> got_waiting(ranksPerChannel * banksPerRank, false); 1471 for (const auto& p : queue) { 1472 if(p->rankRef.isAvailable()) 1473 got_waiting[p->bankId] = true; 1474 } 1475 1476 for (int i = 0; i < ranksPerChannel; i++) { 1477 for (int j = 0; j < banksPerRank; j++) { 1478 uint16_t bank_id = i * banksPerRank + j; 1479 1480 // if we have waiting requests for the bank, and it is 1481 // amongst the first available, update the mask 1482 if (got_waiting[bank_id]) { 1483 // make sure this rank is not currently refreshing. 1484 assert(ranks[i]->isAvailable()); 1485 // simplistic approximation of when the bank can issue 1486 // an activate, ignoring any rank-to-rank switching 1487 // cost in this calculation 1488 Tick act_at = ranks[i]->banks[j].openRow == Bank::NO_ROW ? 1489 ranks[i]->banks[j].actAllowedAt : 1490 std::max(ranks[i]->banks[j].preAllowedAt, curTick()) + tRP; 1491 1492 // prioritize commands that access the 1493 // same rank as previous burst 1494 // Calculate bank mask separately for the case and 1495 // evaluate after loop iterations complete 1496 if (i == activeRank && ranksPerChannel > 1) { 1497 if (act_at <= min_act_at_same_rank) { 1498 // reset same rank bank mask if new minimum is found 1499 // and previous minimum could not immediately send ACT 1500 if (act_at < min_act_at_same_rank && 1501 min_act_at_same_rank > curTick()) 1502 bank_mask_same_rank = 0; 1503 1504 // Set flag indicating that a same rank 1505 // opportunity was found 1506 same_rank_match = true; 1507 1508 // set the bit corresponding to the available bank 1509 replaceBits(bank_mask_same_rank, bank_id, bank_id, 1); 1510 min_act_at_same_rank = act_at; 1511 } 1512 } else { 1513 if (act_at <= min_act_at) { 1514 // reset bank mask if new minimum is found 1515 // and either previous minimum could not immediately send ACT 1516 if (act_at < min_act_at && min_act_at > curTick()) 1517 bank_mask = 0; 1518 // set the bit corresponding to the available bank 1519 replaceBits(bank_mask, bank_id, bank_id, 1); 1520 min_act_at = act_at; 1521 } 1522 } 1523 } 1524 } 1525 } 1526 1527 // Determine the earliest time when the next burst can issue based 1528 // on the current busBusyUntil delay. 1529 // Offset by tRCD to correlate with ACT timing variables 1530 Tick min_cmd_at = busBusyUntil - tCL - tRCD; 1531 1532 // if we have multiple ranks and all 1533 // waiting packets are accessing a rank which was previously active 1534 // then bank_mask_same_rank will be set to a value while bank_mask will 1535 // remain 0. In this case, the function should return the value of 1536 // bank_mask_same_rank. 1537 // else if waiting packets access a rank which was previously active and 1538 // other ranks, prioritize same rank accesses that can issue B2B 1539 // Only optimize for same ranks when the command type 1540 // does not change; do not want to unnecessarily incur tWTR 1541 // 1542 // Resulting FCFS prioritization Order is: 1543 // 1) Commands that access the same rank as previous burst 1544 // and can prep the bank seamlessly. 1545 // 2) Commands (any rank) with earliest bank prep 1546 if ((bank_mask == 0) || (!switched_cmd_type && same_rank_match && 1547 min_act_at_same_rank <= min_cmd_at)) { 1548 bank_mask = bank_mask_same_rank; 1549 } 1550 1551 return bank_mask; 1552} 1553 1554DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p) 1555 : EventManager(&_memory), memory(_memory), 1556 pwrStateTrans(PWR_IDLE), pwrState(PWR_IDLE), pwrStateTick(0), 1557 refreshState(REF_IDLE), refreshDueAt(0), 1558 power(_p, false), numBanksActive(0), 1559 activateEvent(*this), prechargeEvent(*this), 1560 refreshEvent(*this), powerEvent(*this) 1561{ } 1562 1563void 1564DRAMCtrl::Rank::startup(Tick ref_tick) 1565{ 1566 assert(ref_tick > curTick()); 1567 1568 pwrStateTick = curTick(); 1569 1570 // kick off the refresh, and give ourselves enough time to 1571 // precharge 1572 schedule(refreshEvent, ref_tick); 1573} 1574 1575void 1576DRAMCtrl::Rank::suspend() 1577{ 1578 deschedule(refreshEvent); 1579} 1580 1581void 1582DRAMCtrl::Rank::checkDrainDone() 1583{ 1584 // if this rank was waiting to drain it is now able to proceed to 1585 // precharge 1586 if (refreshState == REF_DRAIN) { 1587 DPRINTF(DRAM, "Refresh drain done, now precharging\n"); 1588 1589 refreshState = REF_PRE; 1590 1591 // hand control back to the refresh event loop 1592 schedule(refreshEvent, curTick()); 1593 } 1594} 1595 1596void 1597DRAMCtrl::Rank::processActivateEvent() 1598{ 1599 // we should transition to the active state as soon as any bank is active 1600 if (pwrState != PWR_ACT) 1601 // note that at this point numBanksActive could be back at 1602 // zero again due to a precharge scheduled in the future 1603 schedulePowerEvent(PWR_ACT, curTick()); 1604} 1605 1606void 1607DRAMCtrl::Rank::processPrechargeEvent() 1608{ 1609 // if we reached zero, then special conditions apply as we track 1610 // if all banks are precharged for the power models 1611 if (numBanksActive == 0) { 1612 // we should transition to the idle state when the last bank 1613 // is precharged 1614 schedulePowerEvent(PWR_IDLE, curTick()); 1615 } 1616} 1617 1618void 1619DRAMCtrl::Rank::processRefreshEvent() 1620{ 1621 // when first preparing the refresh, remember when it was due 1622 if (refreshState == REF_IDLE) { 1623 // remember when the refresh is due 1624 refreshDueAt = curTick(); 1625 1626 // proceed to drain 1627 refreshState = REF_DRAIN; 1628 1629 DPRINTF(DRAM, "Refresh due\n"); 1630 } 1631 1632 // let any scheduled read or write to the same rank go ahead, 1633 // after which it will 1634 // hand control back to this event loop 1635 if (refreshState == REF_DRAIN) { 1636 // if a request is at the moment being handled and this request is 1637 // accessing the current rank then wait for it to finish 1638 if ((rank == memory.activeRank) 1639 && (memory.nextReqEvent.scheduled())) { 1640 // hand control over to the request loop until it is 1641 // evaluated next 1642 DPRINTF(DRAM, "Refresh awaiting draining\n"); 1643 1644 return; 1645 } else { 1646 refreshState = REF_PRE; 1647 } 1648 } 1649 1650 // at this point, ensure that all banks are precharged 1651 if (refreshState == REF_PRE) { 1652 // precharge any active bank if we are not already in the idle 1653 // state 1654 if (pwrState != PWR_IDLE) { 1655 // at the moment, we use a precharge all even if there is 1656 // only a single bank open 1657 DPRINTF(DRAM, "Precharging all\n"); 1658 1659 // first determine when we can precharge 1660 Tick pre_at = curTick(); 1661 1662 for (auto &b : banks) { 1663 // respect both causality and any existing bank 1664 // constraints, some banks could already have a 1665 // (auto) precharge scheduled 1666 pre_at = std::max(b.preAllowedAt, pre_at); 1667 } 1668 1669 // make sure all banks per rank are precharged, and for those that 1670 // already are, update their availability 1671 Tick act_allowed_at = pre_at + memory.tRP; 1672 1673 for (auto &b : banks) { 1674 if (b.openRow != Bank::NO_ROW) { 1675 memory.prechargeBank(*this, b, pre_at, false); 1676 } else { 1677 b.actAllowedAt = std::max(b.actAllowedAt, act_allowed_at); 1678 b.preAllowedAt = std::max(b.preAllowedAt, pre_at); 1679 } 1680 } 1681 1682 // precharge all banks in rank 1683 power.powerlib.doCommand(MemCommand::PREA, 0, 1684 divCeil(pre_at, memory.tCK) - 1685 memory.timeStampOffset); 1686 1687 DPRINTF(DRAMPower, "%llu,PREA,0,%d\n", 1688 divCeil(pre_at, memory.tCK) - 1689 memory.timeStampOffset, rank); 1690 } else { 1691 DPRINTF(DRAM, "All banks already precharged, starting refresh\n"); 1692 1693 // go ahead and kick the power state machine into gear if 1694 // we are already idle 1695 schedulePowerEvent(PWR_REF, curTick()); 1696 } 1697 1698 refreshState = REF_RUN; 1699 assert(numBanksActive == 0); 1700 1701 // wait for all banks to be precharged, at which point the 1702 // power state machine will transition to the idle state, and 1703 // automatically move to a refresh, at that point it will also 1704 // call this method to get the refresh event loop going again 1705 return; 1706 } 1707 1708 // last but not least we perform the actual refresh 1709 if (refreshState == REF_RUN) { 1710 // should never get here with any banks active 1711 assert(numBanksActive == 0); 1712 assert(pwrState == PWR_REF); 1713 1714 Tick ref_done_at = curTick() + memory.tRFC; 1715 1716 for (auto &b : banks) { 1717 b.actAllowedAt = ref_done_at; 1718 } 1719 1720 // at the moment this affects all ranks 1721 power.powerlib.doCommand(MemCommand::REF, 0, 1722 divCeil(curTick(), memory.tCK) - 1723 memory.timeStampOffset); 1724 1725 // at the moment sort the list of commands and update the counters 1726 // for DRAMPower libray when doing a refresh 1727 sort(power.powerlib.cmdList.begin(), 1728 power.powerlib.cmdList.end(), DRAMCtrl::sortTime); 1729 1730 // update the counters for DRAMPower, passing false to 1731 // indicate that this is not the last command in the 1732 // list. DRAMPower requires this information for the 1733 // correct calculation of the background energy at the end 1734 // of the simulation. Ideally we would want to call this 1735 // function with true once at the end of the 1736 // simulation. However, the discarded energy is extremly 1737 // small and does not effect the final results. 1738 power.powerlib.updateCounters(false); 1739 1740 // call the energy function 1741 power.powerlib.calcEnergy(); 1742 1743 // Update the stats 1744 updatePowerStats(); 1745 1746 DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), memory.tCK) - 1747 memory.timeStampOffset, rank); 1748 1749 // make sure we did not wait so long that we cannot make up 1750 // for it 1751 if (refreshDueAt + memory.tREFI < ref_done_at) { 1752 fatal("Refresh was delayed so long we cannot catch up\n"); 1753 } 1754 1755 // compensate for the delay in actually performing the refresh 1756 // when scheduling the next one 1757 schedule(refreshEvent, refreshDueAt + memory.tREFI - memory.tRP); 1758 1759 assert(!powerEvent.scheduled()); 1760 1761 // move to the idle power state once the refresh is done, this 1762 // will also move the refresh state machine to the refresh 1763 // idle state 1764 schedulePowerEvent(PWR_IDLE, ref_done_at); 1765 1766 DPRINTF(DRAMState, "Refresh done at %llu and next refresh at %llu\n", 1767 ref_done_at, refreshDueAt + memory.tREFI); 1768 } 1769} 1770 1771void 1772DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state, Tick tick) 1773{ 1774 // respect causality 1775 assert(tick >= curTick()); 1776 1777 if (!powerEvent.scheduled()) { 1778 DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n", 1779 tick, pwr_state); 1780 1781 // insert the new transition 1782 pwrStateTrans = pwr_state; 1783 1784 schedule(powerEvent, tick); 1785 } else { 1786 panic("Scheduled power event at %llu to state %d, " 1787 "with scheduled event at %llu to %d\n", tick, pwr_state, 1788 powerEvent.when(), pwrStateTrans); 1789 } 1790} 1791 1792void 1793DRAMCtrl::Rank::processPowerEvent() 1794{ 1795 // remember where we were, and for how long 1796 Tick duration = curTick() - pwrStateTick; 1797 PowerState prev_state = pwrState; 1798 1799 // update the accounting 1800 pwrStateTime[prev_state] += duration; 1801 1802 pwrState = pwrStateTrans; 1803 pwrStateTick = curTick(); 1804 1805 if (pwrState == PWR_IDLE) { 1806 DPRINTF(DRAMState, "All banks precharged\n"); 1807 1808 // if we were refreshing, make sure we start scheduling requests again 1809 if (prev_state == PWR_REF) { 1810 DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration); 1811 assert(pwrState == PWR_IDLE); 1812 1813 // kick things into action again 1814 refreshState = REF_IDLE; 1815 // a request event could be already scheduled by the state 1816 // machine of the other rank 1817 if (!memory.nextReqEvent.scheduled()) 1818 schedule(memory.nextReqEvent, curTick()); 1819 } else { 1820 assert(prev_state == PWR_ACT); 1821 1822 // if we have a pending refresh, and are now moving to 1823 // the idle state, direclty transition to a refresh 1824 if (refreshState == REF_RUN) { 1825 // there should be nothing waiting at this point 1826 assert(!powerEvent.scheduled()); 1827 1828 // update the state in zero time and proceed below 1829 pwrState = PWR_REF; 1830 } 1831 } 1832 } 1833 1834 // we transition to the refresh state, let the refresh state 1835 // machine know of this state update and let it deal with the 1836 // scheduling of the next power state transition as well as the 1837 // following refresh 1838 if (pwrState == PWR_REF) { 1839 DPRINTF(DRAMState, "Refreshing\n"); 1840 // kick the refresh event loop into action again, and that 1841 // in turn will schedule a transition to the idle power 1842 // state once the refresh is done 1843 assert(refreshState == REF_RUN); 1844 processRefreshEvent(); 1845 } 1846} 1847 1848void 1849DRAMCtrl::Rank::updatePowerStats() 1850{ 1851 // Get the energy and power from DRAMPower 1852 Data::MemoryPowerModel::Energy energy = 1853 power.powerlib.getEnergy(); 1854 Data::MemoryPowerModel::Power rank_power = 1855 power.powerlib.getPower(); 1856 1857 actEnergy = energy.act_energy * memory.devicesPerRank; 1858 preEnergy = energy.pre_energy * memory.devicesPerRank; 1859 readEnergy = energy.read_energy * memory.devicesPerRank; 1860 writeEnergy = energy.write_energy * memory.devicesPerRank; 1861 refreshEnergy = energy.ref_energy * memory.devicesPerRank; 1862 actBackEnergy = energy.act_stdby_energy * memory.devicesPerRank; 1863 preBackEnergy = energy.pre_stdby_energy * memory.devicesPerRank; 1864 totalEnergy = energy.total_energy * memory.devicesPerRank; 1865 averagePower = rank_power.average_power * memory.devicesPerRank; 1866} 1867 1868void 1869DRAMCtrl::Rank::regStats() 1870{ 1871 using namespace Stats; 1872 1873 pwrStateTime 1874 .init(5) 1875 .name(name() + ".memoryStateTime") 1876 .desc("Time in different power states"); 1877 pwrStateTime.subname(0, "IDLE"); 1878 pwrStateTime.subname(1, "REF"); 1879 pwrStateTime.subname(2, "PRE_PDN"); 1880 pwrStateTime.subname(3, "ACT"); 1881 pwrStateTime.subname(4, "ACT_PDN"); 1882 1883 actEnergy 1884 .name(name() + ".actEnergy") 1885 .desc("Energy for activate commands per rank (pJ)"); 1886 1887 preEnergy 1888 .name(name() + ".preEnergy") 1889 .desc("Energy for precharge commands per rank (pJ)"); 1890 1891 readEnergy 1892 .name(name() + ".readEnergy") 1893 .desc("Energy for read commands per rank (pJ)"); 1894 1895 writeEnergy 1896 .name(name() + ".writeEnergy") 1897 .desc("Energy for write commands per rank (pJ)"); 1898 1899 refreshEnergy 1900 .name(name() + ".refreshEnergy") 1901 .desc("Energy for refresh commands per rank (pJ)"); 1902 1903 actBackEnergy 1904 .name(name() + ".actBackEnergy") 1905 .desc("Energy for active background per rank (pJ)"); 1906 1907 preBackEnergy 1908 .name(name() + ".preBackEnergy") 1909 .desc("Energy for precharge background per rank (pJ)"); 1910 1911 totalEnergy 1912 .name(name() + ".totalEnergy") 1913 .desc("Total energy per rank (pJ)"); 1914 1915 averagePower 1916 .name(name() + ".averagePower") 1917 .desc("Core power per rank (mW)"); 1918} 1919void 1920DRAMCtrl::regStats() 1921{ 1922 using namespace Stats; 1923 1924 AbstractMemory::regStats(); 1925 1926 for (auto r : ranks) { 1927 r->regStats(); 1928 } 1929 1930 readReqs 1931 .name(name() + ".readReqs") 1932 .desc("Number of read requests accepted"); 1933 1934 writeReqs 1935 .name(name() + ".writeReqs") 1936 .desc("Number of write requests accepted"); 1937 1938 readBursts 1939 .name(name() + ".readBursts") 1940 .desc("Number of DRAM read bursts, " 1941 "including those serviced by the write queue"); 1942 1943 writeBursts 1944 .name(name() + ".writeBursts") 1945 .desc("Number of DRAM write bursts, " 1946 "including those merged in the write queue"); 1947 1948 servicedByWrQ 1949 .name(name() + ".servicedByWrQ") 1950 .desc("Number of DRAM read bursts serviced by the write queue"); 1951 1952 mergedWrBursts 1953 .name(name() + ".mergedWrBursts") 1954 .desc("Number of DRAM write bursts merged with an existing one"); 1955 1956 neitherReadNorWrite 1957 .name(name() + ".neitherReadNorWriteReqs") 1958 .desc("Number of requests that are neither read nor write"); 1959 1960 perBankRdBursts 1961 .init(banksPerRank * ranksPerChannel) 1962 .name(name() + ".perBankRdBursts") 1963 .desc("Per bank write bursts"); 1964 1965 perBankWrBursts 1966 .init(banksPerRank * ranksPerChannel) 1967 .name(name() + ".perBankWrBursts") 1968 .desc("Per bank write bursts"); 1969 1970 avgRdQLen 1971 .name(name() + ".avgRdQLen") 1972 .desc("Average read queue length when enqueuing") 1973 .precision(2); 1974 1975 avgWrQLen 1976 .name(name() + ".avgWrQLen") 1977 .desc("Average write queue length when enqueuing") 1978 .precision(2); 1979 1980 totQLat 1981 .name(name() + ".totQLat") 1982 .desc("Total ticks spent queuing"); 1983 1984 totBusLat 1985 .name(name() + ".totBusLat") 1986 .desc("Total ticks spent in databus transfers"); 1987 1988 totMemAccLat 1989 .name(name() + ".totMemAccLat") 1990 .desc("Total ticks spent from burst creation until serviced " 1991 "by the DRAM"); 1992 1993 avgQLat 1994 .name(name() + ".avgQLat") 1995 .desc("Average queueing delay per DRAM burst") 1996 .precision(2); 1997 1998 avgQLat = totQLat / (readBursts - servicedByWrQ); 1999 2000 avgBusLat 2001 .name(name() + ".avgBusLat") 2002 .desc("Average bus latency per DRAM burst") 2003 .precision(2); 2004 2005 avgBusLat = totBusLat / (readBursts - servicedByWrQ); 2006 2007 avgMemAccLat 2008 .name(name() + ".avgMemAccLat") 2009 .desc("Average memory access latency per DRAM burst") 2010 .precision(2); 2011 2012 avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ); 2013 2014 numRdRetry 2015 .name(name() + ".numRdRetry") 2016 .desc("Number of times read queue was full causing retry"); 2017 2018 numWrRetry 2019 .name(name() + ".numWrRetry") 2020 .desc("Number of times write queue was full causing retry"); 2021 2022 readRowHits 2023 .name(name() + ".readRowHits") 2024 .desc("Number of row buffer hits during reads"); 2025 2026 writeRowHits 2027 .name(name() + ".writeRowHits") 2028 .desc("Number of row buffer hits during writes"); 2029 2030 readRowHitRate 2031 .name(name() + ".readRowHitRate") 2032 .desc("Row buffer hit rate for reads") 2033 .precision(2); 2034 2035 readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100; 2036 2037 writeRowHitRate 2038 .name(name() + ".writeRowHitRate") 2039 .desc("Row buffer hit rate for writes") 2040 .precision(2); 2041 2042 writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100; 2043 2044 readPktSize 2045 .init(ceilLog2(burstSize) + 1) 2046 .name(name() + ".readPktSize") 2047 .desc("Read request sizes (log2)"); 2048 2049 writePktSize 2050 .init(ceilLog2(burstSize) + 1) 2051 .name(name() + ".writePktSize") 2052 .desc("Write request sizes (log2)"); 2053 2054 rdQLenPdf 2055 .init(readBufferSize) 2056 .name(name() + ".rdQLenPdf") 2057 .desc("What read queue length does an incoming req see"); 2058 2059 wrQLenPdf 2060 .init(writeBufferSize) 2061 .name(name() + ".wrQLenPdf") 2062 .desc("What write queue length does an incoming req see"); 2063 2064 bytesPerActivate 2065 .init(maxAccessesPerRow) 2066 .name(name() + ".bytesPerActivate") 2067 .desc("Bytes accessed per row activation") 2068 .flags(nozero); 2069 2070 rdPerTurnAround 2071 .init(readBufferSize) 2072 .name(name() + ".rdPerTurnAround") 2073 .desc("Reads before turning the bus around for writes") 2074 .flags(nozero); 2075 2076 wrPerTurnAround 2077 .init(writeBufferSize) 2078 .name(name() + ".wrPerTurnAround") 2079 .desc("Writes before turning the bus around for reads") 2080 .flags(nozero); 2081 2082 bytesReadDRAM 2083 .name(name() + ".bytesReadDRAM") 2084 .desc("Total number of bytes read from DRAM"); 2085 2086 bytesReadWrQ 2087 .name(name() + ".bytesReadWrQ") 2088 .desc("Total number of bytes read from write queue"); 2089 2090 bytesWritten 2091 .name(name() + ".bytesWritten") 2092 .desc("Total number of bytes written to DRAM"); 2093 2094 bytesReadSys 2095 .name(name() + ".bytesReadSys") 2096 .desc("Total read bytes from the system interface side"); 2097 2098 bytesWrittenSys 2099 .name(name() + ".bytesWrittenSys") 2100 .desc("Total written bytes from the system interface side"); 2101 2102 avgRdBW 2103 .name(name() + ".avgRdBW") 2104 .desc("Average DRAM read bandwidth in MiByte/s") 2105 .precision(2); 2106 2107 avgRdBW = (bytesReadDRAM / 1000000) / simSeconds; 2108 2109 avgWrBW 2110 .name(name() + ".avgWrBW") 2111 .desc("Average achieved write bandwidth in MiByte/s") 2112 .precision(2); 2113 2114 avgWrBW = (bytesWritten / 1000000) / simSeconds; 2115 2116 avgRdBWSys 2117 .name(name() + ".avgRdBWSys") 2118 .desc("Average system read bandwidth in MiByte/s") 2119 .precision(2); 2120 2121 avgRdBWSys = (bytesReadSys / 1000000) / simSeconds; 2122 2123 avgWrBWSys 2124 .name(name() + ".avgWrBWSys") 2125 .desc("Average system write bandwidth in MiByte/s") 2126 .precision(2); 2127 2128 avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds; 2129 2130 peakBW 2131 .name(name() + ".peakBW") 2132 .desc("Theoretical peak bandwidth in MiByte/s") 2133 .precision(2); 2134 2135 peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000; 2136 2137 busUtil 2138 .name(name() + ".busUtil") 2139 .desc("Data bus utilization in percentage") 2140 .precision(2); 2141 busUtil = (avgRdBW + avgWrBW) / peakBW * 100; 2142 2143 totGap 2144 .name(name() + ".totGap") 2145 .desc("Total gap between requests"); 2146 2147 avgGap 2148 .name(name() + ".avgGap") 2149 .desc("Average gap between requests") 2150 .precision(2); 2151 2152 avgGap = totGap / (readReqs + writeReqs); 2153 2154 // Stats for DRAM Power calculation based on Micron datasheet 2155 busUtilRead 2156 .name(name() + ".busUtilRead") 2157 .desc("Data bus utilization in percentage for reads") 2158 .precision(2); 2159 2160 busUtilRead = avgRdBW / peakBW * 100; 2161 2162 busUtilWrite 2163 .name(name() + ".busUtilWrite") 2164 .desc("Data bus utilization in percentage for writes") 2165 .precision(2); 2166 2167 busUtilWrite = avgWrBW / peakBW * 100; 2168 2169 pageHitRate 2170 .name(name() + ".pageHitRate") 2171 .desc("Row buffer hit rate, read and write combined") 2172 .precision(2); 2173 2174 pageHitRate = (writeRowHits + readRowHits) / 2175 (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100; 2176} 2177 2178void 2179DRAMCtrl::recvFunctional(PacketPtr pkt) 2180{ 2181 // rely on the abstract memory 2182 functionalAccess(pkt); 2183} 2184 2185BaseSlavePort& 2186DRAMCtrl::getSlavePort(const string &if_name, PortID idx) 2187{ 2188 if (if_name != "port") { 2189 return MemObject::getSlavePort(if_name, idx); 2190 } else { 2191 return port; 2192 } 2193} 2194 2195unsigned int 2196DRAMCtrl::drain(DrainManager *dm) 2197{ 2198 unsigned int count = port.drain(dm); 2199 2200 // if there is anything in any of our internal queues, keep track 2201 // of that as well 2202 if (!(writeQueue.empty() && readQueue.empty() && 2203 respQueue.empty())) { 2204 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d," 2205 " resp: %d\n", writeQueue.size(), readQueue.size(), 2206 respQueue.size()); 2207 ++count; 2208 drainManager = dm; 2209 2210 // the only part that is not drained automatically over time 2211 // is the write queue, thus kick things into action if needed 2212 if (!writeQueue.empty() && !nextReqEvent.scheduled()) { 2213 schedule(nextReqEvent, curTick()); 2214 } 2215 } 2216 2217 if (count) 2218 setDrainState(Drainable::Draining); 2219 else 2220 setDrainState(Drainable::Drained); 2221 return count; 2222} 2223 2224void 2225DRAMCtrl::drainResume() 2226{ 2227 if (!isTimingMode && system()->isTimingMode()) { 2228 // if we switched to timing mode, kick things into action, 2229 // and behave as if we restored from a checkpoint 2230 startup(); 2231 } else if (isTimingMode && !system()->isTimingMode()) { 2232 // if we switch from timing mode, stop the refresh events to 2233 // not cause issues with KVM 2234 for (auto r : ranks) { 2235 r->suspend(); 2236 } 2237 } 2238 2239 // update the mode 2240 isTimingMode = system()->isTimingMode(); 2241} 2242 2243DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory) 2244 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this), 2245 memory(_memory) 2246{ } 2247 2248AddrRangeList 2249DRAMCtrl::MemoryPort::getAddrRanges() const 2250{ 2251 AddrRangeList ranges; 2252 ranges.push_back(memory.getAddrRange()); 2253 return ranges; 2254} 2255 2256void 2257DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt) 2258{ 2259 pkt->pushLabel(memory.name()); 2260 2261 if (!queue.checkFunctional(pkt)) { 2262 // Default implementation of SimpleTimingPort::recvFunctional() 2263 // calls recvAtomic() and throws away the latency; we can save a 2264 // little here by just not calculating the latency. 2265 memory.recvFunctional(pkt); 2266 } 2267 2268 pkt->popLabel(); 2269} 2270 2271Tick 2272DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt) 2273{ 2274 return memory.recvAtomic(pkt); 2275} 2276 2277bool 2278DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt) 2279{ 2280 // pass it to the memory controller 2281 return memory.recvTimingReq(pkt); 2282} 2283 2284DRAMCtrl* 2285DRAMCtrlParams::create() 2286{ 2287 return new DRAMCtrl(this); 2288} 2289