dram_ctrl.cc revision 12705:9668a82ead4b
1/* 2 * Copyright (c) 2010-2017 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 * Wendy Elsasser 45 * Radhika Jagtap 46 */ 47 48#include "mem/dram_ctrl.hh" 49 50#include "base/bitfield.hh" 51#include "base/trace.hh" 52#include "debug/DRAM.hh" 53#include "debug/DRAMPower.hh" 54#include "debug/DRAMState.hh" 55#include "debug/Drain.hh" 56#include "sim/system.hh" 57 58using namespace std; 59using namespace Data; 60 61DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) : 62 AbstractMemory(p), 63 port(name() + ".port", *this), isTimingMode(false), 64 retryRdReq(false), retryWrReq(false), 65 busState(READ), 66 busStateNext(READ), 67 nextReqEvent([this]{ processNextReqEvent(); }, name()), 68 respondEvent([this]{ processRespondEvent(); }, name()), 69 deviceSize(p->device_size), 70 deviceBusWidth(p->device_bus_width), burstLength(p->burst_length), 71 deviceRowBufferSize(p->device_rowbuffer_size), 72 devicesPerRank(p->devices_per_rank), 73 burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8), 74 rowBufferSize(devicesPerRank * deviceRowBufferSize), 75 columnsPerRowBuffer(rowBufferSize / burstSize), 76 columnsPerStripe(range.interleaved() ? range.granularity() / burstSize : 1), 77 ranksPerChannel(p->ranks_per_channel), 78 bankGroupsPerRank(p->bank_groups_per_rank), 79 bankGroupArch(p->bank_groups_per_rank > 0), 80 banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0), 81 readBufferSize(p->read_buffer_size), 82 writeBufferSize(p->write_buffer_size), 83 writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0), 84 writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0), 85 minWritesPerSwitch(p->min_writes_per_switch), 86 writesThisTime(0), readsThisTime(0), 87 tCK(p->tCK), tWTR(p->tWTR), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST), 88 tCCD_L(p->tCCD_L), tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS), 89 tWR(p->tWR), tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD), 90 tRRD_L(p->tRRD_L), tXAW(p->tXAW), tXP(p->tXP), tXS(p->tXS), 91 activationLimit(p->activation_limit), 92 memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping), 93 pageMgmt(p->page_policy), 94 maxAccessesPerRow(p->max_accesses_per_row), 95 frontendLatency(p->static_frontend_latency), 96 backendLatency(p->static_backend_latency), 97 busBusyUntil(0), prevArrival(0), 98 nextReqTime(0), activeRank(0), timeStampOffset(0), 99 lastStatsResetTick(0) 100{ 101 // sanity check the ranks since we rely on bit slicing for the 102 // address decoding 103 fatal_if(!isPowerOf2(ranksPerChannel), "DRAM rank count of %d is not " 104 "allowed, must be a power of two\n", ranksPerChannel); 105 106 fatal_if(!isPowerOf2(burstSize), "DRAM burst size %d is not allowed, " 107 "must be a power of two\n", burstSize); 108 109 for (int i = 0; i < ranksPerChannel; i++) { 110 Rank* rank = new Rank(*this, p, i); 111 ranks.push_back(rank); 112 } 113 114 // perform a basic check of the write thresholds 115 if (p->write_low_thresh_perc >= p->write_high_thresh_perc) 116 fatal("Write buffer low threshold %d must be smaller than the " 117 "high threshold %d\n", p->write_low_thresh_perc, 118 p->write_high_thresh_perc); 119 120 // determine the rows per bank by looking at the total capacity 121 uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size()); 122 123 // determine the dram actual capacity from the DRAM config in Mbytes 124 uint64_t deviceCapacity = deviceSize / (1024 * 1024) * devicesPerRank * 125 ranksPerChannel; 126 127 // if actual DRAM size does not match memory capacity in system warn! 128 if (deviceCapacity != capacity / (1024 * 1024)) 129 warn("DRAM device capacity (%d Mbytes) does not match the " 130 "address range assigned (%d Mbytes)\n", deviceCapacity, 131 capacity / (1024 * 1024)); 132 133 DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity, 134 AbstractMemory::size()); 135 136 DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n", 137 rowBufferSize, columnsPerRowBuffer); 138 139 rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel); 140 141 // some basic sanity checks 142 if (tREFI <= tRP || tREFI <= tRFC) { 143 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n", 144 tREFI, tRP, tRFC); 145 } 146 147 // basic bank group architecture checks -> 148 if (bankGroupArch) { 149 // must have at least one bank per bank group 150 if (bankGroupsPerRank > banksPerRank) { 151 fatal("banks per rank (%d) must be equal to or larger than " 152 "banks groups per rank (%d)\n", 153 banksPerRank, bankGroupsPerRank); 154 } 155 // must have same number of banks in each bank group 156 if ((banksPerRank % bankGroupsPerRank) != 0) { 157 fatal("Banks per rank (%d) must be evenly divisible by bank groups " 158 "per rank (%d) for equal banks per bank group\n", 159 banksPerRank, bankGroupsPerRank); 160 } 161 // tCCD_L should be greater than minimal, back-to-back burst delay 162 if (tCCD_L <= tBURST) { 163 fatal("tCCD_L (%d) should be larger than tBURST (%d) when " 164 "bank groups per rank (%d) is greater than 1\n", 165 tCCD_L, tBURST, bankGroupsPerRank); 166 } 167 // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay 168 // some datasheets might specify it equal to tRRD 169 if (tRRD_L < tRRD) { 170 fatal("tRRD_L (%d) should be larger than tRRD (%d) when " 171 "bank groups per rank (%d) is greater than 1\n", 172 tRRD_L, tRRD, bankGroupsPerRank); 173 } 174 } 175 176} 177 178void 179DRAMCtrl::init() 180{ 181 AbstractMemory::init(); 182 183 if (!port.isConnected()) { 184 fatal("DRAMCtrl %s is unconnected!\n", name()); 185 } else { 186 port.sendRangeChange(); 187 } 188 189 // a bit of sanity checks on the interleaving, save it for here to 190 // ensure that the system pointer is initialised 191 if (range.interleaved()) { 192 if (channels != range.stripes()) 193 fatal("%s has %d interleaved address stripes but %d channel(s)\n", 194 name(), range.stripes(), channels); 195 196 if (addrMapping == Enums::RoRaBaChCo) { 197 if (rowBufferSize != range.granularity()) { 198 fatal("Channel interleaving of %s doesn't match RoRaBaChCo " 199 "address map\n", name()); 200 } 201 } else if (addrMapping == Enums::RoRaBaCoCh || 202 addrMapping == Enums::RoCoRaBaCh) { 203 // for the interleavings with channel bits in the bottom, 204 // if the system uses a channel striping granularity that 205 // is larger than the DRAM burst size, then map the 206 // sequential accesses within a stripe to a number of 207 // columns in the DRAM, effectively placing some of the 208 // lower-order column bits as the least-significant bits 209 // of the address (above the ones denoting the burst size) 210 assert(columnsPerStripe >= 1); 211 212 // channel striping has to be done at a granularity that 213 // is equal or larger to a cache line 214 if (system()->cacheLineSize() > range.granularity()) { 215 fatal("Channel interleaving of %s must be at least as large " 216 "as the cache line size\n", name()); 217 } 218 219 // ...and equal or smaller than the row-buffer size 220 if (rowBufferSize < range.granularity()) { 221 fatal("Channel interleaving of %s must be at most as large " 222 "as the row-buffer size\n", name()); 223 } 224 // this is essentially the check above, so just to be sure 225 assert(columnsPerStripe <= columnsPerRowBuffer); 226 } 227 } 228} 229 230void 231DRAMCtrl::startup() 232{ 233 // remember the memory system mode of operation 234 isTimingMode = system()->isTimingMode(); 235 236 if (isTimingMode) { 237 // timestamp offset should be in clock cycles for DRAMPower 238 timeStampOffset = divCeil(curTick(), tCK); 239 240 // update the start tick for the precharge accounting to the 241 // current tick 242 for (auto r : ranks) { 243 r->startup(curTick() + tREFI - tRP); 244 } 245 246 // shift the bus busy time sufficiently far ahead that we never 247 // have to worry about negative values when computing the time for 248 // the next request, this will add an insignificant bubble at the 249 // start of simulation 250 busBusyUntil = curTick() + tRP + tRCD + tCL; 251 } 252} 253 254Tick 255DRAMCtrl::recvAtomic(PacketPtr pkt) 256{ 257 DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr()); 258 259 panic_if(pkt->cacheResponding(), "Should not see packets where cache " 260 "is responding"); 261 262 // do the actual memory access and turn the packet into a response 263 access(pkt); 264 265 Tick latency = 0; 266 if (pkt->hasData()) { 267 // this value is not supposed to be accurate, just enough to 268 // keep things going, mimic a closed page 269 latency = tRP + tRCD + tCL; 270 } 271 return latency; 272} 273 274bool 275DRAMCtrl::readQueueFull(unsigned int neededEntries) const 276{ 277 DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n", 278 readBufferSize, readQueue.size() + respQueue.size(), 279 neededEntries); 280 281 return 282 (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize; 283} 284 285bool 286DRAMCtrl::writeQueueFull(unsigned int neededEntries) const 287{ 288 DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n", 289 writeBufferSize, writeQueue.size(), neededEntries); 290 return (writeQueue.size() + neededEntries) > writeBufferSize; 291} 292 293DRAMCtrl::DRAMPacket* 294DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size, 295 bool isRead) 296{ 297 // decode the address based on the address mapping scheme, with 298 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and 299 // channel, respectively 300 uint8_t rank; 301 uint8_t bank; 302 // use a 64-bit unsigned during the computations as the row is 303 // always the top bits, and check before creating the DRAMPacket 304 uint64_t row; 305 306 // truncate the address to a DRAM burst, which makes it unique to 307 // a specific column, row, bank, rank and channel 308 Addr addr = dramPktAddr / burstSize; 309 310 // we have removed the lowest order address bits that denote the 311 // position within the column 312 if (addrMapping == Enums::RoRaBaChCo) { 313 // the lowest order bits denote the column to ensure that 314 // sequential cache lines occupy the same row 315 addr = addr / columnsPerRowBuffer; 316 317 // take out the channel part of the address 318 addr = addr / channels; 319 320 // after the channel bits, get the bank bits to interleave 321 // over the banks 322 bank = addr % banksPerRank; 323 addr = addr / banksPerRank; 324 325 // after the bank, we get the rank bits which thus interleaves 326 // over the ranks 327 rank = addr % ranksPerChannel; 328 addr = addr / ranksPerChannel; 329 330 // lastly, get the row bits, no need to remove them from addr 331 row = addr % rowsPerBank; 332 } else if (addrMapping == Enums::RoRaBaCoCh) { 333 // take out the lower-order column bits 334 addr = addr / columnsPerStripe; 335 336 // take out the channel part of the address 337 addr = addr / channels; 338 339 // next, the higher-order column bites 340 addr = addr / (columnsPerRowBuffer / columnsPerStripe); 341 342 // after the column bits, we get the bank bits to interleave 343 // over the banks 344 bank = addr % banksPerRank; 345 addr = addr / banksPerRank; 346 347 // after the bank, we get the rank bits which thus interleaves 348 // over the ranks 349 rank = addr % ranksPerChannel; 350 addr = addr / ranksPerChannel; 351 352 // lastly, get the row bits, no need to remove them from addr 353 row = addr % rowsPerBank; 354 } else if (addrMapping == Enums::RoCoRaBaCh) { 355 // optimise for closed page mode and utilise maximum 356 // parallelism of the DRAM (at the cost of power) 357 358 // take out the lower-order column bits 359 addr = addr / columnsPerStripe; 360 361 // take out the channel part of the address, not that this has 362 // to match with how accesses are interleaved between the 363 // controllers in the address mapping 364 addr = addr / channels; 365 366 // start with the bank bits, as this provides the maximum 367 // opportunity for parallelism between requests 368 bank = addr % banksPerRank; 369 addr = addr / banksPerRank; 370 371 // next get the rank bits 372 rank = addr % ranksPerChannel; 373 addr = addr / ranksPerChannel; 374 375 // next, the higher-order column bites 376 addr = addr / (columnsPerRowBuffer / columnsPerStripe); 377 378 // lastly, get the row bits, no need to remove them from addr 379 row = addr % rowsPerBank; 380 } else 381 panic("Unknown address mapping policy chosen!"); 382 383 assert(rank < ranksPerChannel); 384 assert(bank < banksPerRank); 385 assert(row < rowsPerBank); 386 assert(row < Bank::NO_ROW); 387 388 DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n", 389 dramPktAddr, rank, bank, row); 390 391 // create the corresponding DRAM packet with the entry time and 392 // ready time set to the current tick, the latter will be updated 393 // later 394 uint16_t bank_id = banksPerRank * rank + bank; 395 return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr, 396 size, ranks[rank]->banks[bank], *ranks[rank]); 397} 398 399void 400DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount) 401{ 402 // only add to the read queue here. whenever the request is 403 // eventually done, set the readyTime, and call schedule() 404 assert(!pkt->isWrite()); 405 406 assert(pktCount != 0); 407 408 // if the request size is larger than burst size, the pkt is split into 409 // multiple DRAM packets 410 // Note if the pkt starting address is not aligened to burst size, the 411 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets 412 // are aligned to burst size boundaries. This is to ensure we accurately 413 // check read packets against packets in write queue. 414 Addr addr = pkt->getAddr(); 415 unsigned pktsServicedByWrQ = 0; 416 BurstHelper* burst_helper = NULL; 417 for (int cnt = 0; cnt < pktCount; ++cnt) { 418 unsigned size = std::min((addr | (burstSize - 1)) + 1, 419 pkt->getAddr() + pkt->getSize()) - addr; 420 readPktSize[ceilLog2(size)]++; 421 readBursts++; 422 423 // First check write buffer to see if the data is already at 424 // the controller 425 bool foundInWrQ = false; 426 Addr burst_addr = burstAlign(addr); 427 // if the burst address is not present then there is no need 428 // looking any further 429 if (isInWriteQueue.find(burst_addr) != isInWriteQueue.end()) { 430 for (const auto& p : writeQueue) { 431 // check if the read is subsumed in the write queue 432 // packet we are looking at 433 if (p->addr <= addr && (addr + size) <= (p->addr + p->size)) { 434 foundInWrQ = true; 435 servicedByWrQ++; 436 pktsServicedByWrQ++; 437 DPRINTF(DRAM, "Read to addr %lld with size %d serviced by " 438 "write queue\n", addr, size); 439 bytesReadWrQ += burstSize; 440 break; 441 } 442 } 443 } 444 445 // If not found in the write q, make a DRAM packet and 446 // push it onto the read queue 447 if (!foundInWrQ) { 448 449 // Make the burst helper for split packets 450 if (pktCount > 1 && burst_helper == NULL) { 451 DPRINTF(DRAM, "Read to addr %lld translates to %d " 452 "dram requests\n", pkt->getAddr(), pktCount); 453 burst_helper = new BurstHelper(pktCount); 454 } 455 456 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true); 457 dram_pkt->burstHelper = burst_helper; 458 459 assert(!readQueueFull(1)); 460 rdQLenPdf[readQueue.size() + respQueue.size()]++; 461 462 DPRINTF(DRAM, "Adding to read queue\n"); 463 464 readQueue.push_back(dram_pkt); 465 466 // increment read entries of the rank 467 ++dram_pkt->rankRef.readEntries; 468 469 // Update stats 470 avgRdQLen = readQueue.size() + respQueue.size(); 471 } 472 473 // Starting address of next dram pkt (aligend to burstSize boundary) 474 addr = (addr | (burstSize - 1)) + 1; 475 } 476 477 // If all packets are serviced by write queue, we send the repsonse back 478 if (pktsServicedByWrQ == pktCount) { 479 accessAndRespond(pkt, frontendLatency); 480 return; 481 } 482 483 // Update how many split packets are serviced by write queue 484 if (burst_helper != NULL) 485 burst_helper->burstsServiced = pktsServicedByWrQ; 486 487 // If we are not already scheduled to get a request out of the 488 // queue, do so now 489 if (!nextReqEvent.scheduled()) { 490 DPRINTF(DRAM, "Request scheduled immediately\n"); 491 schedule(nextReqEvent, curTick()); 492 } 493} 494 495void 496DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount) 497{ 498 // only add to the write queue here. whenever the request is 499 // eventually done, set the readyTime, and call schedule() 500 assert(pkt->isWrite()); 501 502 // if the request size is larger than burst size, the pkt is split into 503 // multiple DRAM packets 504 Addr addr = pkt->getAddr(); 505 for (int cnt = 0; cnt < pktCount; ++cnt) { 506 unsigned size = std::min((addr | (burstSize - 1)) + 1, 507 pkt->getAddr() + pkt->getSize()) - addr; 508 writePktSize[ceilLog2(size)]++; 509 writeBursts++; 510 511 // see if we can merge with an existing item in the write 512 // queue and keep track of whether we have merged or not 513 bool merged = isInWriteQueue.find(burstAlign(addr)) != 514 isInWriteQueue.end(); 515 516 // if the item was not merged we need to create a new write 517 // and enqueue it 518 if (!merged) { 519 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false); 520 521 assert(writeQueue.size() < writeBufferSize); 522 wrQLenPdf[writeQueue.size()]++; 523 524 DPRINTF(DRAM, "Adding to write queue\n"); 525 526 writeQueue.push_back(dram_pkt); 527 isInWriteQueue.insert(burstAlign(addr)); 528 assert(writeQueue.size() == isInWriteQueue.size()); 529 530 // Update stats 531 avgWrQLen = writeQueue.size(); 532 533 // increment write entries of the rank 534 ++dram_pkt->rankRef.writeEntries; 535 } else { 536 DPRINTF(DRAM, "Merging write burst with existing queue entry\n"); 537 538 // keep track of the fact that this burst effectively 539 // disappeared as it was merged with an existing one 540 mergedWrBursts++; 541 } 542 543 // Starting address of next dram pkt (aligend to burstSize boundary) 544 addr = (addr | (burstSize - 1)) + 1; 545 } 546 547 // we do not wait for the writes to be send to the actual memory, 548 // but instead take responsibility for the consistency here and 549 // snoop the write queue for any upcoming reads 550 // @todo, if a pkt size is larger than burst size, we might need a 551 // different front end latency 552 accessAndRespond(pkt, frontendLatency); 553 554 // If we are not already scheduled to get a request out of the 555 // queue, do so now 556 if (!nextReqEvent.scheduled()) { 557 DPRINTF(DRAM, "Request scheduled immediately\n"); 558 schedule(nextReqEvent, curTick()); 559 } 560} 561 562void 563DRAMCtrl::printQs() const { 564 DPRINTF(DRAM, "===READ QUEUE===\n\n"); 565 for (auto i = readQueue.begin() ; i != readQueue.end() ; ++i) { 566 DPRINTF(DRAM, "Read %lu\n", (*i)->addr); 567 } 568 DPRINTF(DRAM, "\n===RESP QUEUE===\n\n"); 569 for (auto i = respQueue.begin() ; i != respQueue.end() ; ++i) { 570 DPRINTF(DRAM, "Response %lu\n", (*i)->addr); 571 } 572 DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n"); 573 for (auto i = writeQueue.begin() ; i != writeQueue.end() ; ++i) { 574 DPRINTF(DRAM, "Write %lu\n", (*i)->addr); 575 } 576} 577 578bool 579DRAMCtrl::recvTimingReq(PacketPtr pkt) 580{ 581 // This is where we enter from the outside world 582 DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n", 583 pkt->cmdString(), pkt->getAddr(), pkt->getSize()); 584 585 panic_if(pkt->cacheResponding(), "Should not see packets where cache " 586 "is responding"); 587 588 panic_if(!(pkt->isRead() || pkt->isWrite()), 589 "Should only see read and writes at memory controller\n"); 590 591 // Calc avg gap between requests 592 if (prevArrival != 0) { 593 totGap += curTick() - prevArrival; 594 } 595 prevArrival = curTick(); 596 597 598 // Find out how many dram packets a pkt translates to 599 // If the burst size is equal or larger than the pkt size, then a pkt 600 // translates to only one dram packet. Otherwise, a pkt translates to 601 // multiple dram packets 602 unsigned size = pkt->getSize(); 603 unsigned offset = pkt->getAddr() & (burstSize - 1); 604 unsigned int dram_pkt_count = divCeil(offset + size, burstSize); 605 606 // check local buffers and do not accept if full 607 if (pkt->isRead()) { 608 assert(size != 0); 609 if (readQueueFull(dram_pkt_count)) { 610 DPRINTF(DRAM, "Read queue full, not accepting\n"); 611 // remember that we have to retry this port 612 retryRdReq = true; 613 numRdRetry++; 614 return false; 615 } else { 616 addToReadQueue(pkt, dram_pkt_count); 617 readReqs++; 618 bytesReadSys += size; 619 } 620 } else { 621 assert(pkt->isWrite()); 622 assert(size != 0); 623 if (writeQueueFull(dram_pkt_count)) { 624 DPRINTF(DRAM, "Write queue full, not accepting\n"); 625 // remember that we have to retry this port 626 retryWrReq = true; 627 numWrRetry++; 628 return false; 629 } else { 630 addToWriteQueue(pkt, dram_pkt_count); 631 writeReqs++; 632 bytesWrittenSys += size; 633 } 634 } 635 636 return true; 637} 638 639void 640DRAMCtrl::processRespondEvent() 641{ 642 DPRINTF(DRAM, 643 "processRespondEvent(): Some req has reached its readyTime\n"); 644 645 DRAMPacket* dram_pkt = respQueue.front(); 646 647 // if a read has reached its ready-time, decrement the number of reads 648 // At this point the packet has been handled and there is a possibility 649 // to switch to low-power mode if no other packet is available 650 --dram_pkt->rankRef.readEntries; 651 DPRINTF(DRAM, "number of read entries for rank %d is %d\n", 652 dram_pkt->rank, dram_pkt->rankRef.readEntries); 653 654 // counter should at least indicate one outstanding request 655 // for this read 656 assert(dram_pkt->rankRef.outstandingEvents > 0); 657 // read response received, decrement count 658 --dram_pkt->rankRef.outstandingEvents; 659 660 // at this moment should not have transitioned to a low-power state 661 assert((dram_pkt->rankRef.pwrState != PWR_SREF) && 662 (dram_pkt->rankRef.pwrState != PWR_PRE_PDN) && 663 (dram_pkt->rankRef.pwrState != PWR_ACT_PDN)); 664 665 // track if this is the last packet before idling 666 // and that there are no outstanding commands to this rank 667 if (dram_pkt->rankRef.isQueueEmpty() && 668 dram_pkt->rankRef.outstandingEvents == 0) { 669 // verify that there are no events scheduled 670 assert(!dram_pkt->rankRef.activateEvent.scheduled()); 671 assert(!dram_pkt->rankRef.prechargeEvent.scheduled()); 672 673 // if coming from active state, schedule power event to 674 // active power-down else go to precharge power-down 675 DPRINTF(DRAMState, "Rank %d sleep at tick %d; current power state is " 676 "%d\n", dram_pkt->rank, curTick(), dram_pkt->rankRef.pwrState); 677 678 // default to ACT power-down unless already in IDLE state 679 // could be in IDLE if PRE issued before data returned 680 PowerState next_pwr_state = PWR_ACT_PDN; 681 if (dram_pkt->rankRef.pwrState == PWR_IDLE) { 682 next_pwr_state = PWR_PRE_PDN; 683 } 684 685 dram_pkt->rankRef.powerDownSleep(next_pwr_state, curTick()); 686 } 687 688 if (dram_pkt->burstHelper) { 689 // it is a split packet 690 dram_pkt->burstHelper->burstsServiced++; 691 if (dram_pkt->burstHelper->burstsServiced == 692 dram_pkt->burstHelper->burstCount) { 693 // we have now serviced all children packets of a system packet 694 // so we can now respond to the requester 695 // @todo we probably want to have a different front end and back 696 // end latency for split packets 697 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency); 698 delete dram_pkt->burstHelper; 699 dram_pkt->burstHelper = NULL; 700 } 701 } else { 702 // it is not a split packet 703 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency); 704 } 705 706 delete respQueue.front(); 707 respQueue.pop_front(); 708 709 if (!respQueue.empty()) { 710 assert(respQueue.front()->readyTime >= curTick()); 711 assert(!respondEvent.scheduled()); 712 schedule(respondEvent, respQueue.front()->readyTime); 713 } else { 714 // if there is nothing left in any queue, signal a drain 715 if (drainState() == DrainState::Draining && 716 writeQueue.empty() && readQueue.empty() && allRanksDrained()) { 717 718 DPRINTF(Drain, "DRAM controller done draining\n"); 719 signalDrainDone(); 720 } 721 } 722 723 // We have made a location in the queue available at this point, 724 // so if there is a read that was forced to wait, retry now 725 if (retryRdReq) { 726 retryRdReq = false; 727 port.sendRetryReq(); 728 } 729} 730 731bool 732DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue, Tick extra_col_delay) 733{ 734 // This method does the arbitration between requests. The chosen 735 // packet is simply moved to the head of the queue. The other 736 // methods know that this is the place to look. For example, with 737 // FCFS, this method does nothing 738 assert(!queue.empty()); 739 740 // bool to indicate if a packet to an available rank is found 741 bool found_packet = false; 742 if (queue.size() == 1) { 743 DRAMPacket* dram_pkt = queue.front(); 744 // available rank corresponds to state refresh idle 745 if (ranks[dram_pkt->rank]->inRefIdleState()) { 746 found_packet = true; 747 DPRINTF(DRAM, "Single request, going to a free rank\n"); 748 } else { 749 DPRINTF(DRAM, "Single request, going to a busy rank\n"); 750 } 751 return found_packet; 752 } 753 754 if (memSchedPolicy == Enums::fcfs) { 755 // check if there is a packet going to a free rank 756 for (auto i = queue.begin(); i != queue.end() ; ++i) { 757 DRAMPacket* dram_pkt = *i; 758 if (ranks[dram_pkt->rank]->inRefIdleState()) { 759 queue.erase(i); 760 queue.push_front(dram_pkt); 761 found_packet = true; 762 break; 763 } 764 } 765 } else if (memSchedPolicy == Enums::frfcfs) { 766 found_packet = reorderQueue(queue, extra_col_delay); 767 } else 768 panic("No scheduling policy chosen\n"); 769 return found_packet; 770} 771 772bool 773DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, Tick extra_col_delay) 774{ 775 // Only determine this if needed 776 uint64_t earliest_banks = 0; 777 bool hidden_bank_prep = false; 778 779 // search for seamless row hits first, if no seamless row hit is 780 // found then determine if there are other packets that can be issued 781 // without incurring additional bus delay due to bank timing 782 // Will select closed rows first to enable more open row possibilies 783 // in future selections 784 bool found_hidden_bank = false; 785 786 // remember if we found a row hit, not seamless, but bank prepped 787 // and ready 788 bool found_prepped_pkt = false; 789 790 // if we have no row hit, prepped or not, and no seamless packet, 791 // just go for the earliest possible 792 bool found_earliest_pkt = false; 793 794 auto selected_pkt_it = queue.end(); 795 796 // time we need to issue a column command to be seamless 797 const Tick min_col_at = std::max(busBusyUntil - tCL + extra_col_delay, 798 curTick()); 799 800 for (auto i = queue.begin(); i != queue.end() ; ++i) { 801 DRAMPacket* dram_pkt = *i; 802 const Bank& bank = dram_pkt->bankRef; 803 804 // check if rank is not doing a refresh and thus is available, if not, 805 // jump to the next packet 806 if (dram_pkt->rankRef.inRefIdleState()) { 807 // check if it is a row hit 808 if (bank.openRow == dram_pkt->row) { 809 // no additional rank-to-rank or same bank-group 810 // delays, or we switched read/write and might as well 811 // go for the row hit 812 if (bank.colAllowedAt <= min_col_at) { 813 // FCFS within the hits, giving priority to 814 // commands that can issue seamlessly, without 815 // additional delay, such as same rank accesses 816 // and/or different bank-group accesses 817 DPRINTF(DRAM, "Seamless row buffer hit\n"); 818 selected_pkt_it = i; 819 // no need to look through the remaining queue entries 820 break; 821 } else if (!found_hidden_bank && !found_prepped_pkt) { 822 // if we did not find a packet to a closed row that can 823 // issue the bank commands without incurring delay, and 824 // did not yet find a packet to a prepped row, remember 825 // the current one 826 selected_pkt_it = i; 827 found_prepped_pkt = true; 828 DPRINTF(DRAM, "Prepped row buffer hit\n"); 829 } 830 } else if (!found_earliest_pkt) { 831 // if we have not initialised the bank status, do it 832 // now, and only once per scheduling decisions 833 if (earliest_banks == 0) { 834 // determine entries with earliest bank delay 835 pair<uint64_t, bool> bankStatus = 836 minBankPrep(queue, min_col_at); 837 earliest_banks = bankStatus.first; 838 hidden_bank_prep = bankStatus.second; 839 } 840 841 // bank is amongst first available banks 842 // minBankPrep will give priority to packets that can 843 // issue seamlessly 844 if (bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) { 845 found_earliest_pkt = true; 846 found_hidden_bank = hidden_bank_prep; 847 848 // give priority to packets that can issue 849 // bank commands 'behind the scenes' 850 // any additional delay if any will be due to 851 // col-to-col command requirements 852 if (hidden_bank_prep || !found_prepped_pkt) 853 selected_pkt_it = i; 854 } 855 } 856 } 857 } 858 859 if (selected_pkt_it != queue.end()) { 860 DRAMPacket* selected_pkt = *selected_pkt_it; 861 queue.erase(selected_pkt_it); 862 queue.push_front(selected_pkt); 863 return true; 864 } 865 866 return false; 867} 868 869void 870DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency) 871{ 872 DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr()); 873 874 bool needsResponse = pkt->needsResponse(); 875 // do the actual memory access which also turns the packet into a 876 // response 877 access(pkt); 878 879 // turn packet around to go back to requester if response expected 880 if (needsResponse) { 881 // access already turned the packet into a response 882 assert(pkt->isResponse()); 883 // response_time consumes the static latency and is charged also 884 // with headerDelay that takes into account the delay provided by 885 // the xbar and also the payloadDelay that takes into account the 886 // number of data beats. 887 Tick response_time = curTick() + static_latency + pkt->headerDelay + 888 pkt->payloadDelay; 889 // Here we reset the timing of the packet before sending it out. 890 pkt->headerDelay = pkt->payloadDelay = 0; 891 892 // queue the packet in the response queue to be sent out after 893 // the static latency has passed 894 port.schedTimingResp(pkt, response_time, true); 895 } else { 896 // @todo the packet is going to be deleted, and the DRAMPacket 897 // is still having a pointer to it 898 pendingDelete.reset(pkt); 899 } 900 901 DPRINTF(DRAM, "Done\n"); 902 903 return; 904} 905 906void 907DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref, 908 Tick act_tick, uint32_t row) 909{ 910 assert(rank_ref.actTicks.size() == activationLimit); 911 912 DPRINTF(DRAM, "Activate at tick %d\n", act_tick); 913 914 // update the open row 915 assert(bank_ref.openRow == Bank::NO_ROW); 916 bank_ref.openRow = row; 917 918 // start counting anew, this covers both the case when we 919 // auto-precharged, and when this access is forced to 920 // precharge 921 bank_ref.bytesAccessed = 0; 922 bank_ref.rowAccesses = 0; 923 924 ++rank_ref.numBanksActive; 925 assert(rank_ref.numBanksActive <= banksPerRank); 926 927 DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n", 928 bank_ref.bank, rank_ref.rank, act_tick, 929 ranks[rank_ref.rank]->numBanksActive); 930 931 rank_ref.cmdList.push_back(Command(MemCommand::ACT, bank_ref.bank, 932 act_tick)); 933 934 DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) - 935 timeStampOffset, bank_ref.bank, rank_ref.rank); 936 937 // The next access has to respect tRAS for this bank 938 bank_ref.preAllowedAt = act_tick + tRAS; 939 940 // Respect the row-to-column command delay 941 bank_ref.colAllowedAt = std::max(act_tick + tRCD, bank_ref.colAllowedAt); 942 943 // start by enforcing tRRD 944 for (int i = 0; i < banksPerRank; i++) { 945 // next activate to any bank in this rank must not happen 946 // before tRRD 947 if (bankGroupArch && (bank_ref.bankgr == rank_ref.banks[i].bankgr)) { 948 // bank group architecture requires longer delays between 949 // ACT commands within the same bank group. Use tRRD_L 950 // in this case 951 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD_L, 952 rank_ref.banks[i].actAllowedAt); 953 } else { 954 // use shorter tRRD value when either 955 // 1) bank group architecture is not supportted 956 // 2) bank is in a different bank group 957 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD, 958 rank_ref.banks[i].actAllowedAt); 959 } 960 } 961 962 // next, we deal with tXAW, if the activation limit is disabled 963 // then we directly schedule an activate power event 964 if (!rank_ref.actTicks.empty()) { 965 // sanity check 966 if (rank_ref.actTicks.back() && 967 (act_tick - rank_ref.actTicks.back()) < tXAW) { 968 panic("Got %d activates in window %d (%llu - %llu) which " 969 "is smaller than %llu\n", activationLimit, act_tick - 970 rank_ref.actTicks.back(), act_tick, 971 rank_ref.actTicks.back(), tXAW); 972 } 973 974 // shift the times used for the book keeping, the last element 975 // (highest index) is the oldest one and hence the lowest value 976 rank_ref.actTicks.pop_back(); 977 978 // record an new activation (in the future) 979 rank_ref.actTicks.push_front(act_tick); 980 981 // cannot activate more than X times in time window tXAW, push the 982 // next one (the X + 1'st activate) to be tXAW away from the 983 // oldest in our window of X 984 if (rank_ref.actTicks.back() && 985 (act_tick - rank_ref.actTicks.back()) < tXAW) { 986 DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate " 987 "no earlier than %llu\n", activationLimit, 988 rank_ref.actTicks.back() + tXAW); 989 for (int j = 0; j < banksPerRank; j++) 990 // next activate must not happen before end of window 991 rank_ref.banks[j].actAllowedAt = 992 std::max(rank_ref.actTicks.back() + tXAW, 993 rank_ref.banks[j].actAllowedAt); 994 } 995 } 996 997 // at the point when this activate takes place, make sure we 998 // transition to the active power state 999 if (!rank_ref.activateEvent.scheduled()) 1000 schedule(rank_ref.activateEvent, act_tick); 1001 else if (rank_ref.activateEvent.when() > act_tick) 1002 // move it sooner in time 1003 reschedule(rank_ref.activateEvent, act_tick); 1004} 1005 1006void 1007DRAMCtrl::prechargeBank(Rank& rank_ref, Bank& bank, Tick pre_at, bool trace) 1008{ 1009 // make sure the bank has an open row 1010 assert(bank.openRow != Bank::NO_ROW); 1011 1012 // sample the bytes per activate here since we are closing 1013 // the page 1014 bytesPerActivate.sample(bank.bytesAccessed); 1015 1016 bank.openRow = Bank::NO_ROW; 1017 1018 // no precharge allowed before this one 1019 bank.preAllowedAt = pre_at; 1020 1021 Tick pre_done_at = pre_at + tRP; 1022 1023 bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at); 1024 1025 assert(rank_ref.numBanksActive != 0); 1026 --rank_ref.numBanksActive; 1027 1028 DPRINTF(DRAM, "Precharging bank %d, rank %d at tick %lld, now got " 1029 "%d active\n", bank.bank, rank_ref.rank, pre_at, 1030 rank_ref.numBanksActive); 1031 1032 if (trace) { 1033 1034 rank_ref.cmdList.push_back(Command(MemCommand::PRE, bank.bank, 1035 pre_at)); 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 // New event, increment count 1048 ++rank_ref.outstandingEvents; 1049 } else if (rank_ref.prechargeEvent.when() < pre_done_at) { 1050 reschedule(rank_ref.prechargeEvent, pre_done_at); 1051 } 1052} 1053 1054void 1055DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt) 1056{ 1057 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n", 1058 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row); 1059 1060 // get the rank 1061 Rank& rank = dram_pkt->rankRef; 1062 1063 // are we in or transitioning to a low-power state and have not scheduled 1064 // a power-up event? 1065 // if so, wake up from power down to issue RD/WR burst 1066 if (rank.inLowPowerState) { 1067 assert(rank.pwrState != PWR_SREF); 1068 rank.scheduleWakeUpEvent(tXP); 1069 } 1070 1071 // get the bank 1072 Bank& bank = dram_pkt->bankRef; 1073 1074 // for the state we need to track if it is a row hit or not 1075 bool row_hit = true; 1076 1077 // respect any constraints on the command (e.g. tRCD or tCCD) 1078 Tick cmd_at = std::max(bank.colAllowedAt, curTick()); 1079 1080 // Determine the access latency and update the bank state 1081 if (bank.openRow == dram_pkt->row) { 1082 // nothing to do 1083 } else { 1084 row_hit = false; 1085 1086 // If there is a page open, precharge it. 1087 if (bank.openRow != Bank::NO_ROW) { 1088 prechargeBank(rank, bank, std::max(bank.preAllowedAt, curTick())); 1089 } 1090 1091 // next we need to account for the delay in activating the 1092 // page 1093 Tick act_tick = std::max(bank.actAllowedAt, curTick()); 1094 1095 // Record the activation and deal with all the global timing 1096 // constraints caused be a new activation (tRRD and tXAW) 1097 activateBank(rank, bank, act_tick, dram_pkt->row); 1098 1099 // issue the command as early as possible 1100 cmd_at = bank.colAllowedAt; 1101 } 1102 1103 // we need to wait until the bus is available before we can issue 1104 // the command 1105 cmd_at = std::max(cmd_at, busBusyUntil - tCL); 1106 1107 // update the packet ready time 1108 dram_pkt->readyTime = cmd_at + tCL + tBURST; 1109 1110 // only one burst can use the bus at any one point in time 1111 assert(dram_pkt->readyTime - busBusyUntil >= tBURST); 1112 1113 // update the time for the next read/write burst for each 1114 // bank (add a max with tCCD/tCCD_L here) 1115 Tick cmd_dly; 1116 for (int j = 0; j < ranksPerChannel; j++) { 1117 for (int i = 0; i < banksPerRank; i++) { 1118 // next burst to same bank group in this rank must not happen 1119 // before tCCD_L. Different bank group timing requirement is 1120 // tBURST; Add tCS for different ranks 1121 if (dram_pkt->rank == j) { 1122 if (bankGroupArch && 1123 (bank.bankgr == ranks[j]->banks[i].bankgr)) { 1124 // bank group architecture requires longer delays between 1125 // RD/WR burst commands to the same bank group. 1126 // Use tCCD_L in this case 1127 cmd_dly = tCCD_L; 1128 } else { 1129 // use tBURST (equivalent to tCCD_S), the shorter 1130 // cas-to-cas delay value, when either: 1131 // 1) bank group architecture is not supportted 1132 // 2) bank is in a different bank group 1133 cmd_dly = tBURST; 1134 } 1135 } else { 1136 // different rank is by default in a different bank group 1137 // use tBURST (equivalent to tCCD_S), which is the shorter 1138 // cas-to-cas delay in this case 1139 // Add tCS to account for rank-to-rank bus delay requirements 1140 cmd_dly = tBURST + tCS; 1141 } 1142 ranks[j]->banks[i].colAllowedAt = std::max(cmd_at + cmd_dly, 1143 ranks[j]->banks[i].colAllowedAt); 1144 } 1145 } 1146 1147 // Save rank of current access 1148 activeRank = dram_pkt->rank; 1149 1150 // If this is a write, we also need to respect the write recovery 1151 // time before a precharge, in the case of a read, respect the 1152 // read to precharge constraint 1153 bank.preAllowedAt = std::max(bank.preAllowedAt, 1154 dram_pkt->isRead ? cmd_at + tRTP : 1155 dram_pkt->readyTime + tWR); 1156 1157 // increment the bytes accessed and the accesses per row 1158 bank.bytesAccessed += burstSize; 1159 ++bank.rowAccesses; 1160 1161 // if we reached the max, then issue with an auto-precharge 1162 bool auto_precharge = pageMgmt == Enums::close || 1163 bank.rowAccesses == maxAccessesPerRow; 1164 1165 // if we did not hit the limit, we might still want to 1166 // auto-precharge 1167 if (!auto_precharge && 1168 (pageMgmt == Enums::open_adaptive || 1169 pageMgmt == Enums::close_adaptive)) { 1170 // a twist on the open and close page policies: 1171 // 1) open_adaptive page policy does not blindly keep the 1172 // page open, but close it if there are no row hits, and there 1173 // are bank conflicts in the queue 1174 // 2) close_adaptive page policy does not blindly close the 1175 // page, but closes it only if there are no row hits in the queue. 1176 // In this case, only force an auto precharge when there 1177 // are no same page hits in the queue 1178 bool got_more_hits = false; 1179 bool got_bank_conflict = false; 1180 1181 // either look at the read queue or write queue 1182 const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue : 1183 writeQueue; 1184 auto p = queue.begin(); 1185 // make sure we are not considering the packet that we are 1186 // currently dealing with (which is the head of the queue) 1187 ++p; 1188 1189 // keep on looking until we find a hit or reach the end of the queue 1190 // 1) if a hit is found, then both open and close adaptive policies keep 1191 // the page open 1192 // 2) if no hit is found, got_bank_conflict is set to true if a bank 1193 // conflict request is waiting in the queue 1194 while (!got_more_hits && p != queue.end()) { 1195 bool same_rank_bank = (dram_pkt->rank == (*p)->rank) && 1196 (dram_pkt->bank == (*p)->bank); 1197 bool same_row = dram_pkt->row == (*p)->row; 1198 got_more_hits |= same_rank_bank && same_row; 1199 got_bank_conflict |= same_rank_bank && !same_row; 1200 ++p; 1201 } 1202 1203 // auto pre-charge when either 1204 // 1) open_adaptive policy, we have not got any more hits, and 1205 // have a bank conflict 1206 // 2) close_adaptive policy and we have not got any more hits 1207 auto_precharge = !got_more_hits && 1208 (got_bank_conflict || pageMgmt == Enums::close_adaptive); 1209 } 1210 1211 // DRAMPower trace command to be written 1212 std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR"; 1213 1214 // MemCommand required for DRAMPower library 1215 MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD : 1216 MemCommand::WR; 1217 1218 // Update bus state 1219 busBusyUntil = dram_pkt->readyTime; 1220 1221 DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n", 1222 dram_pkt->addr, dram_pkt->readyTime, busBusyUntil); 1223 1224 dram_pkt->rankRef.cmdList.push_back(Command(command, dram_pkt->bank, 1225 cmd_at)); 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 // if this access should use auto-precharge, then we are 1231 // closing the row after the read/write burst 1232 if (auto_precharge) { 1233 // if auto-precharge push a PRE command at the correct tick to the 1234 // list used by DRAMPower library to calculate power 1235 prechargeBank(rank, bank, std::max(curTick(), bank.preAllowedAt)); 1236 1237 DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId); 1238 } 1239 1240 // Update the minimum timing between the requests, this is a 1241 // conservative estimate of when we have to schedule the next 1242 // request to not introduce any unecessary bubbles. In most cases 1243 // we will wake up sooner than we have to. 1244 nextReqTime = busBusyUntil - (tRP + tRCD + tCL); 1245 1246 // Update the stats and schedule the next request 1247 if (dram_pkt->isRead) { 1248 ++readsThisTime; 1249 if (row_hit) 1250 readRowHits++; 1251 bytesReadDRAM += burstSize; 1252 perBankRdBursts[dram_pkt->bankId]++; 1253 1254 // Update latency stats 1255 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime; 1256 totBusLat += tBURST; 1257 totQLat += cmd_at - dram_pkt->entryTime; 1258 } else { 1259 ++writesThisTime; 1260 if (row_hit) 1261 writeRowHits++; 1262 bytesWritten += burstSize; 1263 perBankWrBursts[dram_pkt->bankId]++; 1264 } 1265} 1266 1267void 1268DRAMCtrl::processNextReqEvent() 1269{ 1270 int busyRanks = 0; 1271 for (auto r : ranks) { 1272 if (!r->inRefIdleState()) { 1273 if (r->pwrState != PWR_SREF) { 1274 // rank is busy refreshing 1275 DPRINTF(DRAMState, "Rank %d is not available\n", r->rank); 1276 busyRanks++; 1277 1278 // let the rank know that if it was waiting to drain, it 1279 // is now done and ready to proceed 1280 r->checkDrainDone(); 1281 } 1282 1283 // check if we were in self-refresh and haven't started 1284 // to transition out 1285 if ((r->pwrState == PWR_SREF) && r->inLowPowerState) { 1286 DPRINTF(DRAMState, "Rank %d is in self-refresh\n", r->rank); 1287 // if we have commands queued to this rank and we don't have 1288 // a minimum number of active commands enqueued, 1289 // exit self-refresh 1290 if (r->forceSelfRefreshExit()) { 1291 DPRINTF(DRAMState, "rank %d was in self refresh and" 1292 " should wake up\n", r->rank); 1293 //wake up from self-refresh 1294 r->scheduleWakeUpEvent(tXS); 1295 // things are brought back into action once a refresh is 1296 // performed after self-refresh 1297 // continue with selection for other ranks 1298 } 1299 } 1300 } 1301 } 1302 1303 if (busyRanks == ranksPerChannel) { 1304 // if all ranks are refreshing wait for them to finish 1305 // and stall this state machine without taking any further 1306 // action, and do not schedule a new nextReqEvent 1307 return; 1308 } 1309 1310 // pre-emptively set to false. Overwrite if in transitioning to 1311 // a new state 1312 bool switched_cmd_type = false; 1313 if (busState != busStateNext) { 1314 if (busState == READ) { 1315 DPRINTF(DRAM, "Switching to writes after %d reads with %d reads " 1316 "waiting\n", readsThisTime, readQueue.size()); 1317 1318 // sample and reset the read-related stats as we are now 1319 // transitioning to writes, and all reads are done 1320 rdPerTurnAround.sample(readsThisTime); 1321 readsThisTime = 0; 1322 1323 // now proceed to do the actual writes 1324 switched_cmd_type = true; 1325 } else { 1326 DPRINTF(DRAM, "Switching to reads after %d writes with %d writes " 1327 "waiting\n", writesThisTime, writeQueue.size()); 1328 1329 wrPerTurnAround.sample(writesThisTime); 1330 writesThisTime = 0; 1331 1332 switched_cmd_type = true; 1333 } 1334 // update busState to match next state until next transition 1335 busState = busStateNext; 1336 } 1337 1338 // when we get here it is either a read or a write 1339 if (busState == READ) { 1340 1341 // track if we should switch or not 1342 bool switch_to_writes = false; 1343 1344 if (readQueue.empty()) { 1345 // In the case there is no read request to go next, 1346 // trigger writes if we have passed the low threshold (or 1347 // if we are draining) 1348 if (!writeQueue.empty() && 1349 (drainState() == DrainState::Draining || 1350 writeQueue.size() > writeLowThreshold)) { 1351 1352 switch_to_writes = true; 1353 } else { 1354 // check if we are drained 1355 // not done draining until in PWR_IDLE state 1356 // ensuring all banks are closed and 1357 // have exited low power states 1358 if (drainState() == DrainState::Draining && 1359 respQueue.empty() && allRanksDrained()) { 1360 1361 DPRINTF(Drain, "DRAM controller done draining\n"); 1362 signalDrainDone(); 1363 } 1364 1365 // nothing to do, not even any point in scheduling an 1366 // event for the next request 1367 return; 1368 } 1369 } else { 1370 // bool to check if there is a read to a free rank 1371 bool found_read = false; 1372 1373 // Figure out which read request goes next, and move it to the 1374 // front of the read queue 1375 // If we are changing command type, incorporate the minimum 1376 // bus turnaround delay which will be tCS (different rank) case 1377 found_read = chooseNext(readQueue, 1378 switched_cmd_type ? tCS : 0); 1379 1380 // if no read to an available rank is found then return 1381 // at this point. There could be writes to the available ranks 1382 // which are above the required threshold. However, to 1383 // avoid adding more complexity to the code, return and wait 1384 // for a refresh event to kick things into action again. 1385 if (!found_read) 1386 return; 1387 1388 DRAMPacket* dram_pkt = readQueue.front(); 1389 assert(dram_pkt->rankRef.inRefIdleState()); 1390 1391 // here we get a bit creative and shift the bus busy time not 1392 // just the tWTR, but also a CAS latency to capture the fact 1393 // that we are allowed to prepare a new bank, but not issue a 1394 // read command until after tWTR, in essence we capture a 1395 // bubble on the data bus that is tWTR + tCL 1396 if (switched_cmd_type && dram_pkt->rank == activeRank) { 1397 busBusyUntil += tWTR + tCL; 1398 } 1399 1400 doDRAMAccess(dram_pkt); 1401 1402 // At this point we're done dealing with the request 1403 readQueue.pop_front(); 1404 1405 // Every respQueue which will generate an event, increment count 1406 ++dram_pkt->rankRef.outstandingEvents; 1407 1408 // sanity check 1409 assert(dram_pkt->size <= burstSize); 1410 assert(dram_pkt->readyTime >= curTick()); 1411 1412 // Insert into response queue. It will be sent back to the 1413 // requestor at its readyTime 1414 if (respQueue.empty()) { 1415 assert(!respondEvent.scheduled()); 1416 schedule(respondEvent, dram_pkt->readyTime); 1417 } else { 1418 assert(respQueue.back()->readyTime <= dram_pkt->readyTime); 1419 assert(respondEvent.scheduled()); 1420 } 1421 1422 respQueue.push_back(dram_pkt); 1423 1424 // we have so many writes that we have to transition 1425 if (writeQueue.size() > writeHighThreshold) { 1426 switch_to_writes = true; 1427 } 1428 } 1429 1430 // switching to writes, either because the read queue is empty 1431 // and the writes have passed the low threshold (or we are 1432 // draining), or because the writes hit the hight threshold 1433 if (switch_to_writes) { 1434 // transition to writing 1435 busStateNext = WRITE; 1436 } 1437 } else { 1438 // bool to check if write to free rank is found 1439 bool found_write = false; 1440 1441 // If we are changing command type, incorporate the minimum 1442 // bus turnaround delay 1443 found_write = chooseNext(writeQueue, 1444 switched_cmd_type ? std::min(tRTW, tCS) : 0); 1445 1446 // if there are no writes to a rank that is available to service 1447 // requests (i.e. rank is in refresh idle state) are found then 1448 // return. There could be reads to the available ranks. However, to 1449 // avoid adding more complexity to the code, return at this point and 1450 // wait for a refresh event to kick things into action again. 1451 if (!found_write) 1452 return; 1453 1454 DRAMPacket* dram_pkt = writeQueue.front(); 1455 assert(dram_pkt->rankRef.inRefIdleState()); 1456 // sanity check 1457 assert(dram_pkt->size <= burstSize); 1458 1459 // add a bubble to the data bus, as defined by the 1460 // tRTW when access is to the same rank as previous burst 1461 // Different rank timing is handled with tCS, which is 1462 // applied to colAllowedAt 1463 if (switched_cmd_type && dram_pkt->rank == activeRank) { 1464 busBusyUntil += tRTW; 1465 } 1466 1467 doDRAMAccess(dram_pkt); 1468 1469 writeQueue.pop_front(); 1470 1471 // removed write from queue, decrement count 1472 --dram_pkt->rankRef.writeEntries; 1473 1474 // Schedule write done event to decrement event count 1475 // after the readyTime has been reached 1476 // Only schedule latest write event to minimize events 1477 // required; only need to ensure that final event scheduled covers 1478 // the time that writes are outstanding and bus is active 1479 // to holdoff power-down entry events 1480 if (!dram_pkt->rankRef.writeDoneEvent.scheduled()) { 1481 schedule(dram_pkt->rankRef.writeDoneEvent, dram_pkt->readyTime); 1482 // New event, increment count 1483 ++dram_pkt->rankRef.outstandingEvents; 1484 1485 } else if (dram_pkt->rankRef.writeDoneEvent.when() < 1486 dram_pkt-> readyTime) { 1487 reschedule(dram_pkt->rankRef.writeDoneEvent, dram_pkt->readyTime); 1488 } 1489 1490 isInWriteQueue.erase(burstAlign(dram_pkt->addr)); 1491 delete dram_pkt; 1492 1493 // If we emptied the write queue, or got sufficiently below the 1494 // threshold (using the minWritesPerSwitch as the hysteresis) and 1495 // are not draining, or we have reads waiting and have done enough 1496 // writes, then switch to reads. 1497 if (writeQueue.empty() || 1498 (writeQueue.size() + minWritesPerSwitch < writeLowThreshold && 1499 drainState() != DrainState::Draining) || 1500 (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) { 1501 // turn the bus back around for reads again 1502 busStateNext = READ; 1503 1504 // note that the we switch back to reads also in the idle 1505 // case, which eventually will check for any draining and 1506 // also pause any further scheduling if there is really 1507 // nothing to do 1508 } 1509 } 1510 // It is possible that a refresh to another rank kicks things back into 1511 // action before reaching this point. 1512 if (!nextReqEvent.scheduled()) 1513 schedule(nextReqEvent, std::max(nextReqTime, curTick())); 1514 1515 // If there is space available and we have writes waiting then let 1516 // them retry. This is done here to ensure that the retry does not 1517 // cause a nextReqEvent to be scheduled before we do so as part of 1518 // the next request processing 1519 if (retryWrReq && writeQueue.size() < writeBufferSize) { 1520 retryWrReq = false; 1521 port.sendRetryReq(); 1522 } 1523} 1524 1525pair<uint64_t, bool> 1526DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue, 1527 Tick min_col_at) const 1528{ 1529 uint64_t bank_mask = 0; 1530 Tick min_act_at = MaxTick; 1531 1532 // latest Tick for which ACT can occur without incurring additoinal 1533 // delay on the data bus 1534 const Tick hidden_act_max = std::max(min_col_at - tRCD, curTick()); 1535 1536 // Flag condition when burst can issue back-to-back with previous burst 1537 bool found_seamless_bank = false; 1538 1539 // Flag condition when bank can be opened without incurring additional 1540 // delay on the data bus 1541 bool hidden_bank_prep = false; 1542 1543 // determine if we have queued transactions targetting the 1544 // bank in question 1545 vector<bool> got_waiting(ranksPerChannel * banksPerRank, false); 1546 for (const auto& p : queue) { 1547 if (p->rankRef.inRefIdleState()) 1548 got_waiting[p->bankId] = true; 1549 } 1550 1551 // Find command with optimal bank timing 1552 // Will prioritize commands that can issue seamlessly. 1553 for (int i = 0; i < ranksPerChannel; i++) { 1554 for (int j = 0; j < banksPerRank; j++) { 1555 uint16_t bank_id = i * banksPerRank + j; 1556 1557 // if we have waiting requests for the bank, and it is 1558 // amongst the first available, update the mask 1559 if (got_waiting[bank_id]) { 1560 // make sure this rank is not currently refreshing. 1561 assert(ranks[i]->inRefIdleState()); 1562 // simplistic approximation of when the bank can issue 1563 // an activate, ignoring any rank-to-rank switching 1564 // cost in this calculation 1565 Tick act_at = ranks[i]->banks[j].openRow == Bank::NO_ROW ? 1566 std::max(ranks[i]->banks[j].actAllowedAt, curTick()) : 1567 std::max(ranks[i]->banks[j].preAllowedAt, curTick()) + tRP; 1568 1569 // When is the earliest the R/W burst can issue? 1570 Tick col_at = std::max(ranks[i]->banks[j].colAllowedAt, 1571 act_at + tRCD); 1572 1573 // bank can issue burst back-to-back (seamlessly) with 1574 // previous burst 1575 bool new_seamless_bank = col_at <= min_col_at; 1576 1577 // if we found a new seamless bank or we have no 1578 // seamless banks, and got a bank with an earlier 1579 // activate time, it should be added to the bit mask 1580 if (new_seamless_bank || 1581 (!found_seamless_bank && act_at <= min_act_at)) { 1582 // if we did not have a seamless bank before, and 1583 // we do now, reset the bank mask, also reset it 1584 // if we have not yet found a seamless bank and 1585 // the activate time is smaller than what we have 1586 // seen so far 1587 if (!found_seamless_bank && 1588 (new_seamless_bank || act_at < min_act_at)) { 1589 bank_mask = 0; 1590 } 1591 1592 found_seamless_bank |= new_seamless_bank; 1593 1594 // ACT can occur 'behind the scenes' 1595 hidden_bank_prep = act_at <= hidden_act_max; 1596 1597 // set the bit corresponding to the available bank 1598 replaceBits(bank_mask, bank_id, bank_id, 1); 1599 min_act_at = act_at; 1600 } 1601 } 1602 } 1603 } 1604 1605 return make_pair(bank_mask, hidden_bank_prep); 1606} 1607 1608DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p, int rank) 1609 : EventManager(&_memory), memory(_memory), 1610 pwrStateTrans(PWR_IDLE), pwrStatePostRefresh(PWR_IDLE), 1611 pwrStateTick(0), refreshDueAt(0), pwrState(PWR_IDLE), 1612 refreshState(REF_IDLE), inLowPowerState(false), rank(rank), 1613 readEntries(0), writeEntries(0), outstandingEvents(0), 1614 wakeUpAllowedAt(0), power(_p, false), banks(_p->banks_per_rank), 1615 numBanksActive(0), actTicks(_p->activation_limit, 0), 1616 writeDoneEvent([this]{ processWriteDoneEvent(); }, name()), 1617 activateEvent([this]{ processActivateEvent(); }, name()), 1618 prechargeEvent([this]{ processPrechargeEvent(); }, name()), 1619 refreshEvent([this]{ processRefreshEvent(); }, name()), 1620 powerEvent([this]{ processPowerEvent(); }, name()), 1621 wakeUpEvent([this]{ processWakeUpEvent(); }, name()) 1622{ 1623 for (int b = 0; b < _p->banks_per_rank; b++) { 1624 banks[b].bank = b; 1625 // GDDR addressing of banks to BG is linear. 1626 // Here we assume that all DRAM generations address bank groups as 1627 // follows: 1628 if (_p->bank_groups_per_rank > 0) { 1629 // Simply assign lower bits to bank group in order to 1630 // rotate across bank groups as banks are incremented 1631 // e.g. with 4 banks per bank group and 16 banks total: 1632 // banks 0,4,8,12 are in bank group 0 1633 // banks 1,5,9,13 are in bank group 1 1634 // banks 2,6,10,14 are in bank group 2 1635 // banks 3,7,11,15 are in bank group 3 1636 banks[b].bankgr = b % _p->bank_groups_per_rank; 1637 } else { 1638 // No bank groups; simply assign to bank number 1639 banks[b].bankgr = b; 1640 } 1641 } 1642} 1643 1644void 1645DRAMCtrl::Rank::startup(Tick ref_tick) 1646{ 1647 assert(ref_tick > curTick()); 1648 1649 pwrStateTick = curTick(); 1650 1651 // kick off the refresh, and give ourselves enough time to 1652 // precharge 1653 schedule(refreshEvent, ref_tick); 1654} 1655 1656void 1657DRAMCtrl::Rank::suspend() 1658{ 1659 deschedule(refreshEvent); 1660 1661 // Update the stats 1662 updatePowerStats(); 1663 1664 // don't automatically transition back to LP state after next REF 1665 pwrStatePostRefresh = PWR_IDLE; 1666} 1667 1668bool 1669DRAMCtrl::Rank::isQueueEmpty() const 1670{ 1671 // check commmands in Q based on current bus direction 1672 bool no_queued_cmds = ((memory.busStateNext == READ) && (readEntries == 0)) 1673 || ((memory.busStateNext == WRITE) && 1674 (writeEntries == 0)); 1675 return no_queued_cmds; 1676} 1677 1678void 1679DRAMCtrl::Rank::checkDrainDone() 1680{ 1681 // if this rank was waiting to drain it is now able to proceed to 1682 // precharge 1683 if (refreshState == REF_DRAIN) { 1684 DPRINTF(DRAM, "Refresh drain done, now precharging\n"); 1685 1686 refreshState = REF_PD_EXIT; 1687 1688 // hand control back to the refresh event loop 1689 schedule(refreshEvent, curTick()); 1690 } 1691} 1692 1693void 1694DRAMCtrl::Rank::flushCmdList() 1695{ 1696 // at the moment sort the list of commands and update the counters 1697 // for DRAMPower libray when doing a refresh 1698 sort(cmdList.begin(), cmdList.end(), DRAMCtrl::sortTime); 1699 1700 auto next_iter = cmdList.begin(); 1701 // push to commands to DRAMPower 1702 for ( ; next_iter != cmdList.end() ; ++next_iter) { 1703 Command cmd = *next_iter; 1704 if (cmd.timeStamp <= curTick()) { 1705 // Move all commands at or before curTick to DRAMPower 1706 power.powerlib.doCommand(cmd.type, cmd.bank, 1707 divCeil(cmd.timeStamp, memory.tCK) - 1708 memory.timeStampOffset); 1709 } else { 1710 // done - found all commands at or before curTick() 1711 // next_iter references the 1st command after curTick 1712 break; 1713 } 1714 } 1715 // reset cmdList to only contain commands after curTick 1716 // if there are no commands after curTick, updated cmdList will be empty 1717 // in this case, next_iter is cmdList.end() 1718 cmdList.assign(next_iter, cmdList.end()); 1719} 1720 1721void 1722DRAMCtrl::Rank::processActivateEvent() 1723{ 1724 // we should transition to the active state as soon as any bank is active 1725 if (pwrState != PWR_ACT) 1726 // note that at this point numBanksActive could be back at 1727 // zero again due to a precharge scheduled in the future 1728 schedulePowerEvent(PWR_ACT, curTick()); 1729} 1730 1731void 1732DRAMCtrl::Rank::processPrechargeEvent() 1733{ 1734 // counter should at least indicate one outstanding request 1735 // for this precharge 1736 assert(outstandingEvents > 0); 1737 // precharge complete, decrement count 1738 --outstandingEvents; 1739 1740 // if we reached zero, then special conditions apply as we track 1741 // if all banks are precharged for the power models 1742 if (numBanksActive == 0) { 1743 // no reads to this rank in the Q and no pending 1744 // RD/WR or refresh commands 1745 if (isQueueEmpty() && outstandingEvents == 0) { 1746 // should still be in ACT state since bank still open 1747 assert(pwrState == PWR_ACT); 1748 1749 // All banks closed - switch to precharge power down state. 1750 DPRINTF(DRAMState, "Rank %d sleep at tick %d\n", 1751 rank, curTick()); 1752 powerDownSleep(PWR_PRE_PDN, curTick()); 1753 } else { 1754 // we should transition to the idle state when the last bank 1755 // is precharged 1756 schedulePowerEvent(PWR_IDLE, curTick()); 1757 } 1758 } 1759} 1760 1761void 1762DRAMCtrl::Rank::processWriteDoneEvent() 1763{ 1764 // counter should at least indicate one outstanding request 1765 // for this write 1766 assert(outstandingEvents > 0); 1767 // Write transfer on bus has completed 1768 // decrement per rank counter 1769 --outstandingEvents; 1770} 1771 1772void 1773DRAMCtrl::Rank::processRefreshEvent() 1774{ 1775 // when first preparing the refresh, remember when it was due 1776 if ((refreshState == REF_IDLE) || (refreshState == REF_SREF_EXIT)) { 1777 // remember when the refresh is due 1778 refreshDueAt = curTick(); 1779 1780 // proceed to drain 1781 refreshState = REF_DRAIN; 1782 1783 // make nonzero while refresh is pending to ensure 1784 // power down and self-refresh are not entered 1785 ++outstandingEvents; 1786 1787 DPRINTF(DRAM, "Refresh due\n"); 1788 } 1789 1790 // let any scheduled read or write to the same rank go ahead, 1791 // after which it will 1792 // hand control back to this event loop 1793 if (refreshState == REF_DRAIN) { 1794 // if a request is at the moment being handled and this request is 1795 // accessing the current rank then wait for it to finish 1796 if ((rank == memory.activeRank) 1797 && (memory.nextReqEvent.scheduled())) { 1798 // hand control over to the request loop until it is 1799 // evaluated next 1800 DPRINTF(DRAM, "Refresh awaiting draining\n"); 1801 1802 return; 1803 } else { 1804 refreshState = REF_PD_EXIT; 1805 } 1806 } 1807 1808 // at this point, ensure that rank is not in a power-down state 1809 if (refreshState == REF_PD_EXIT) { 1810 // if rank was sleeping and we have't started exit process, 1811 // wake-up for refresh 1812 if (inLowPowerState) { 1813 DPRINTF(DRAM, "Wake Up for refresh\n"); 1814 // save state and return after refresh completes 1815 scheduleWakeUpEvent(memory.tXP); 1816 return; 1817 } else { 1818 refreshState = REF_PRE; 1819 } 1820 } 1821 1822 // at this point, ensure that all banks are precharged 1823 if (refreshState == REF_PRE) { 1824 // precharge any active bank 1825 if (numBanksActive != 0) { 1826 // at the moment, we use a precharge all even if there is 1827 // only a single bank open 1828 DPRINTF(DRAM, "Precharging all\n"); 1829 1830 // first determine when we can precharge 1831 Tick pre_at = curTick(); 1832 1833 for (auto &b : banks) { 1834 // respect both causality and any existing bank 1835 // constraints, some banks could already have a 1836 // (auto) precharge scheduled 1837 pre_at = std::max(b.preAllowedAt, pre_at); 1838 } 1839 1840 // make sure all banks per rank are precharged, and for those that 1841 // already are, update their availability 1842 Tick act_allowed_at = pre_at + memory.tRP; 1843 1844 for (auto &b : banks) { 1845 if (b.openRow != Bank::NO_ROW) { 1846 memory.prechargeBank(*this, b, pre_at, false); 1847 } else { 1848 b.actAllowedAt = std::max(b.actAllowedAt, act_allowed_at); 1849 b.preAllowedAt = std::max(b.preAllowedAt, pre_at); 1850 } 1851 } 1852 1853 // precharge all banks in rank 1854 cmdList.push_back(Command(MemCommand::PREA, 0, pre_at)); 1855 1856 DPRINTF(DRAMPower, "%llu,PREA,0,%d\n", 1857 divCeil(pre_at, memory.tCK) - 1858 memory.timeStampOffset, rank); 1859 } else if ((pwrState == PWR_IDLE) && (outstandingEvents == 1)) { 1860 // Banks are closed, have transitioned to IDLE state, and 1861 // no outstanding ACT,RD/WR,Auto-PRE sequence scheduled 1862 DPRINTF(DRAM, "All banks already precharged, starting refresh\n"); 1863 1864 // go ahead and kick the power state machine into gear since 1865 // we are already idle 1866 schedulePowerEvent(PWR_REF, curTick()); 1867 } else { 1868 // banks state is closed but haven't transitioned pwrState to IDLE 1869 // or have outstanding ACT,RD/WR,Auto-PRE sequence scheduled 1870 // should have outstanding precharge event in this case 1871 assert(prechargeEvent.scheduled()); 1872 // will start refresh when pwrState transitions to IDLE 1873 } 1874 1875 assert(numBanksActive == 0); 1876 1877 // wait for all banks to be precharged, at which point the 1878 // power state machine will transition to the idle state, and 1879 // automatically move to a refresh, at that point it will also 1880 // call this method to get the refresh event loop going again 1881 return; 1882 } 1883 1884 // last but not least we perform the actual refresh 1885 if (refreshState == REF_START) { 1886 // should never get here with any banks active 1887 assert(numBanksActive == 0); 1888 assert(pwrState == PWR_REF); 1889 1890 Tick ref_done_at = curTick() + memory.tRFC; 1891 1892 for (auto &b : banks) { 1893 b.actAllowedAt = ref_done_at; 1894 } 1895 1896 // at the moment this affects all ranks 1897 cmdList.push_back(Command(MemCommand::REF, 0, curTick())); 1898 1899 // Update the stats 1900 updatePowerStats(); 1901 1902 DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), memory.tCK) - 1903 memory.timeStampOffset, rank); 1904 1905 // Update for next refresh 1906 refreshDueAt += memory.tREFI; 1907 1908 // make sure we did not wait so long that we cannot make up 1909 // for it 1910 if (refreshDueAt < ref_done_at) { 1911 fatal("Refresh was delayed so long we cannot catch up\n"); 1912 } 1913 1914 // Run the refresh and schedule event to transition power states 1915 // when refresh completes 1916 refreshState = REF_RUN; 1917 schedule(refreshEvent, ref_done_at); 1918 return; 1919 } 1920 1921 if (refreshState == REF_RUN) { 1922 // should never get here with any banks active 1923 assert(numBanksActive == 0); 1924 assert(pwrState == PWR_REF); 1925 1926 assert(!powerEvent.scheduled()); 1927 1928 if ((memory.drainState() == DrainState::Draining) || 1929 (memory.drainState() == DrainState::Drained)) { 1930 // if draining, do not re-enter low-power mode. 1931 // simply go to IDLE and wait 1932 schedulePowerEvent(PWR_IDLE, curTick()); 1933 } else { 1934 // At the moment, we sleep when the refresh ends and wait to be 1935 // woken up again if previously in a low-power state. 1936 if (pwrStatePostRefresh != PWR_IDLE) { 1937 // power State should be power Refresh 1938 assert(pwrState == PWR_REF); 1939 DPRINTF(DRAMState, "Rank %d sleeping after refresh and was in " 1940 "power state %d before refreshing\n", rank, 1941 pwrStatePostRefresh); 1942 powerDownSleep(pwrState, curTick()); 1943 1944 // Force PRE power-down if there are no outstanding commands 1945 // in Q after refresh. 1946 } else if (isQueueEmpty()) { 1947 // still have refresh event outstanding but there should 1948 // be no other events outstanding 1949 assert(outstandingEvents == 1); 1950 DPRINTF(DRAMState, "Rank %d sleeping after refresh but was NOT" 1951 " in a low power state before refreshing\n", rank); 1952 powerDownSleep(PWR_PRE_PDN, curTick()); 1953 1954 } else { 1955 // move to the idle power state once the refresh is done, this 1956 // will also move the refresh state machine to the refresh 1957 // idle state 1958 schedulePowerEvent(PWR_IDLE, curTick()); 1959 } 1960 } 1961 1962 // At this point, we have completed the current refresh. 1963 // In the SREF bypass case, we do not get to this state in the 1964 // refresh STM and therefore can always schedule next event. 1965 // Compensate for the delay in actually performing the refresh 1966 // when scheduling the next one 1967 schedule(refreshEvent, refreshDueAt - memory.tRP); 1968 1969 DPRINTF(DRAMState, "Refresh done at %llu and next refresh" 1970 " at %llu\n", curTick(), refreshDueAt); 1971 } 1972} 1973 1974void 1975DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state, Tick tick) 1976{ 1977 // respect causality 1978 assert(tick >= curTick()); 1979 1980 if (!powerEvent.scheduled()) { 1981 DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n", 1982 tick, pwr_state); 1983 1984 // insert the new transition 1985 pwrStateTrans = pwr_state; 1986 1987 schedule(powerEvent, tick); 1988 } else { 1989 panic("Scheduled power event at %llu to state %d, " 1990 "with scheduled event at %llu to %d\n", tick, pwr_state, 1991 powerEvent.when(), pwrStateTrans); 1992 } 1993} 1994 1995void 1996DRAMCtrl::Rank::powerDownSleep(PowerState pwr_state, Tick tick) 1997{ 1998 // if low power state is active low, schedule to active low power state. 1999 // in reality tCKE is needed to enter active low power. This is neglected 2000 // here and could be added in the future. 2001 if (pwr_state == PWR_ACT_PDN) { 2002 schedulePowerEvent(pwr_state, tick); 2003 // push command to DRAMPower 2004 cmdList.push_back(Command(MemCommand::PDN_F_ACT, 0, tick)); 2005 DPRINTF(DRAMPower, "%llu,PDN_F_ACT,0,%d\n", divCeil(tick, 2006 memory.tCK) - memory.timeStampOffset, rank); 2007 } else if (pwr_state == PWR_PRE_PDN) { 2008 // if low power state is precharge low, schedule to precharge low 2009 // power state. In reality tCKE is needed to enter active low power. 2010 // This is neglected here. 2011 schedulePowerEvent(pwr_state, tick); 2012 //push Command to DRAMPower 2013 cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick)); 2014 DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick, 2015 memory.tCK) - memory.timeStampOffset, rank); 2016 } else if (pwr_state == PWR_REF) { 2017 // if a refresh just occurred 2018 // transition to PRE_PDN now that all banks are closed 2019 // precharge power down requires tCKE to enter. For simplicity 2020 // this is not considered. 2021 schedulePowerEvent(PWR_PRE_PDN, tick); 2022 //push Command to DRAMPower 2023 cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick)); 2024 DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick, 2025 memory.tCK) - memory.timeStampOffset, rank); 2026 } else if (pwr_state == PWR_SREF) { 2027 // should only enter SREF after PRE-PD wakeup to do a refresh 2028 assert(pwrStatePostRefresh == PWR_PRE_PDN); 2029 // self refresh requires time tCKESR to enter. For simplicity, 2030 // this is not considered. 2031 schedulePowerEvent(PWR_SREF, tick); 2032 // push Command to DRAMPower 2033 cmdList.push_back(Command(MemCommand::SREN, 0, tick)); 2034 DPRINTF(DRAMPower, "%llu,SREN,0,%d\n", divCeil(tick, 2035 memory.tCK) - memory.timeStampOffset, rank); 2036 } 2037 // Ensure that we don't power-down and back up in same tick 2038 // Once we commit to PD entry, do it and wait for at least 1tCK 2039 // This could be replaced with tCKE if/when that is added to the model 2040 wakeUpAllowedAt = tick + memory.tCK; 2041 2042 // Transitioning to a low power state, set flag 2043 inLowPowerState = true; 2044} 2045 2046void 2047DRAMCtrl::Rank::scheduleWakeUpEvent(Tick exit_delay) 2048{ 2049 Tick wake_up_tick = std::max(curTick(), wakeUpAllowedAt); 2050 2051 DPRINTF(DRAMState, "Scheduling wake-up for rank %d at tick %d\n", 2052 rank, wake_up_tick); 2053 2054 // if waking for refresh, hold previous state 2055 // else reset state back to IDLE 2056 if (refreshState == REF_PD_EXIT) { 2057 pwrStatePostRefresh = pwrState; 2058 } else { 2059 // don't automatically transition back to LP state after next REF 2060 pwrStatePostRefresh = PWR_IDLE; 2061 } 2062 2063 // schedule wake-up with event to ensure entry has completed before 2064 // we try to wake-up 2065 schedule(wakeUpEvent, wake_up_tick); 2066 2067 for (auto &b : banks) { 2068 // respect both causality and any existing bank 2069 // constraints, some banks could already have a 2070 // (auto) precharge scheduled 2071 b.colAllowedAt = std::max(wake_up_tick + exit_delay, b.colAllowedAt); 2072 b.preAllowedAt = std::max(wake_up_tick + exit_delay, b.preAllowedAt); 2073 b.actAllowedAt = std::max(wake_up_tick + exit_delay, b.actAllowedAt); 2074 } 2075 // Transitioning out of low power state, clear flag 2076 inLowPowerState = false; 2077 2078 // push to DRAMPower 2079 // use pwrStateTrans for cases where we have a power event scheduled 2080 // to enter low power that has not yet been processed 2081 if (pwrStateTrans == PWR_ACT_PDN) { 2082 cmdList.push_back(Command(MemCommand::PUP_ACT, 0, wake_up_tick)); 2083 DPRINTF(DRAMPower, "%llu,PUP_ACT,0,%d\n", divCeil(wake_up_tick, 2084 memory.tCK) - memory.timeStampOffset, rank); 2085 2086 } else if (pwrStateTrans == PWR_PRE_PDN) { 2087 cmdList.push_back(Command(MemCommand::PUP_PRE, 0, wake_up_tick)); 2088 DPRINTF(DRAMPower, "%llu,PUP_PRE,0,%d\n", divCeil(wake_up_tick, 2089 memory.tCK) - memory.timeStampOffset, rank); 2090 } else if (pwrStateTrans == PWR_SREF) { 2091 cmdList.push_back(Command(MemCommand::SREX, 0, wake_up_tick)); 2092 DPRINTF(DRAMPower, "%llu,SREX,0,%d\n", divCeil(wake_up_tick, 2093 memory.tCK) - memory.timeStampOffset, rank); 2094 } 2095} 2096 2097void 2098DRAMCtrl::Rank::processWakeUpEvent() 2099{ 2100 // Should be in a power-down or self-refresh state 2101 assert((pwrState == PWR_ACT_PDN) || (pwrState == PWR_PRE_PDN) || 2102 (pwrState == PWR_SREF)); 2103 2104 // Check current state to determine transition state 2105 if (pwrState == PWR_ACT_PDN) { 2106 // banks still open, transition to PWR_ACT 2107 schedulePowerEvent(PWR_ACT, curTick()); 2108 } else { 2109 // transitioning from a precharge power-down or self-refresh state 2110 // banks are closed - transition to PWR_IDLE 2111 schedulePowerEvent(PWR_IDLE, curTick()); 2112 } 2113} 2114 2115void 2116DRAMCtrl::Rank::processPowerEvent() 2117{ 2118 assert(curTick() >= pwrStateTick); 2119 // remember where we were, and for how long 2120 Tick duration = curTick() - pwrStateTick; 2121 PowerState prev_state = pwrState; 2122 2123 // update the accounting 2124 pwrStateTime[prev_state] += duration; 2125 2126 // track to total idle time 2127 if ((prev_state == PWR_PRE_PDN) || (prev_state == PWR_ACT_PDN) || 2128 (prev_state == PWR_SREF)) { 2129 totalIdleTime += duration; 2130 } 2131 2132 pwrState = pwrStateTrans; 2133 pwrStateTick = curTick(); 2134 2135 // if rank was refreshing, make sure to start scheduling requests again 2136 if (prev_state == PWR_REF) { 2137 // bus IDLED prior to REF 2138 // counter should be one for refresh command only 2139 assert(outstandingEvents == 1); 2140 // REF complete, decrement count and go back to IDLE 2141 --outstandingEvents; 2142 refreshState = REF_IDLE; 2143 2144 DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration); 2145 // if moving back to power-down after refresh 2146 if (pwrState != PWR_IDLE) { 2147 assert(pwrState == PWR_PRE_PDN); 2148 DPRINTF(DRAMState, "Switching to power down state after refreshing" 2149 " rank %d at %llu tick\n", rank, curTick()); 2150 } 2151 2152 // completed refresh event, ensure next request is scheduled 2153 if (!memory.nextReqEvent.scheduled()) { 2154 DPRINTF(DRAM, "Scheduling next request after refreshing" 2155 " rank %d\n", rank); 2156 schedule(memory.nextReqEvent, curTick()); 2157 } 2158 } 2159 2160 if ((pwrState == PWR_ACT) && (refreshState == REF_PD_EXIT)) { 2161 // have exited ACT PD 2162 assert(prev_state == PWR_ACT_PDN); 2163 2164 // go back to REF event and close banks 2165 refreshState = REF_PRE; 2166 schedule(refreshEvent, curTick()); 2167 } else if (pwrState == PWR_IDLE) { 2168 DPRINTF(DRAMState, "All banks precharged\n"); 2169 if (prev_state == PWR_SREF) { 2170 // set refresh state to REF_SREF_EXIT, ensuring inRefIdleState 2171 // continues to return false during tXS after SREF exit 2172 // Schedule a refresh which kicks things back into action 2173 // when it finishes 2174 refreshState = REF_SREF_EXIT; 2175 schedule(refreshEvent, curTick() + memory.tXS); 2176 } else { 2177 // if we have a pending refresh, and are now moving to 2178 // the idle state, directly transition to, or schedule refresh 2179 if ((refreshState == REF_PRE) || (refreshState == REF_PD_EXIT)) { 2180 // ensure refresh is restarted only after final PRE command. 2181 // do not restart refresh if controller is in an intermediate 2182 // state, after PRE_PDN exit, when banks are IDLE but an 2183 // ACT is scheduled. 2184 if (!activateEvent.scheduled()) { 2185 // there should be nothing waiting at this point 2186 assert(!powerEvent.scheduled()); 2187 if (refreshState == REF_PD_EXIT) { 2188 // exiting PRE PD, will be in IDLE until tXP expires 2189 // and then should transition to PWR_REF state 2190 assert(prev_state == PWR_PRE_PDN); 2191 schedulePowerEvent(PWR_REF, curTick() + memory.tXP); 2192 } else if (refreshState == REF_PRE) { 2193 // can directly move to PWR_REF state and proceed below 2194 pwrState = PWR_REF; 2195 } 2196 } else { 2197 // must have PRE scheduled to transition back to IDLE 2198 // and re-kick off refresh 2199 assert(prechargeEvent.scheduled()); 2200 } 2201 } 2202 } 2203 } 2204 2205 // transition to the refresh state and re-start refresh process 2206 // refresh state machine will schedule the next power state transition 2207 if (pwrState == PWR_REF) { 2208 // completed final PRE for refresh or exiting power-down 2209 assert(refreshState == REF_PRE || refreshState == REF_PD_EXIT); 2210 2211 // exited PRE PD for refresh, with no pending commands 2212 // bypass auto-refresh and go straight to SREF, where memory 2213 // will issue refresh immediately upon entry 2214 if (pwrStatePostRefresh == PWR_PRE_PDN && isQueueEmpty() && 2215 (memory.drainState() != DrainState::Draining) && 2216 (memory.drainState() != DrainState::Drained)) { 2217 DPRINTF(DRAMState, "Rank %d bypassing refresh and transitioning " 2218 "to self refresh at %11u tick\n", rank, curTick()); 2219 powerDownSleep(PWR_SREF, curTick()); 2220 2221 // Since refresh was bypassed, remove event by decrementing count 2222 assert(outstandingEvents == 1); 2223 --outstandingEvents; 2224 2225 // reset state back to IDLE temporarily until SREF is entered 2226 pwrState = PWR_IDLE; 2227 2228 // Not bypassing refresh for SREF entry 2229 } else { 2230 DPRINTF(DRAMState, "Refreshing\n"); 2231 2232 // there should be nothing waiting at this point 2233 assert(!powerEvent.scheduled()); 2234 2235 // kick the refresh event loop into action again, and that 2236 // in turn will schedule a transition to the idle power 2237 // state once the refresh is done 2238 schedule(refreshEvent, curTick()); 2239 2240 // Banks transitioned to IDLE, start REF 2241 refreshState = REF_START; 2242 } 2243 } 2244 2245} 2246 2247void 2248DRAMCtrl::Rank::updatePowerStats() 2249{ 2250 // All commands up to refresh have completed 2251 // flush cmdList to DRAMPower 2252 flushCmdList(); 2253 2254 // Call the function that calculates window energy at intermediate update 2255 // events like at refresh, stats dump as well as at simulation exit. 2256 // Window starts at the last time the calcWindowEnergy function was called 2257 // and is upto current time. 2258 power.powerlib.calcWindowEnergy(divCeil(curTick(), memory.tCK) - 2259 memory.timeStampOffset); 2260 2261 // Get the energy from DRAMPower 2262 Data::MemoryPowerModel::Energy energy = power.powerlib.getEnergy(); 2263 2264 // The energy components inside the power lib are calculated over 2265 // the window so accumulate into the corresponding gem5 stat 2266 actEnergy += energy.act_energy * memory.devicesPerRank; 2267 preEnergy += energy.pre_energy * memory.devicesPerRank; 2268 readEnergy += energy.read_energy * memory.devicesPerRank; 2269 writeEnergy += energy.write_energy * memory.devicesPerRank; 2270 refreshEnergy += energy.ref_energy * memory.devicesPerRank; 2271 actBackEnergy += energy.act_stdby_energy * memory.devicesPerRank; 2272 preBackEnergy += energy.pre_stdby_energy * memory.devicesPerRank; 2273 actPowerDownEnergy += energy.f_act_pd_energy * memory.devicesPerRank; 2274 prePowerDownEnergy += energy.f_pre_pd_energy * memory.devicesPerRank; 2275 selfRefreshEnergy += energy.sref_energy * memory.devicesPerRank; 2276 2277 // Accumulate window energy into the total energy. 2278 totalEnergy += energy.window_energy * memory.devicesPerRank; 2279 // Average power must not be accumulated but calculated over the time 2280 // since last stats reset. SimClock::Frequency is tick period not tick 2281 // frequency. 2282 // energy (pJ) 1e-9 2283 // power (mW) = ----------- * ---------- 2284 // time (tick) tick_frequency 2285 averagePower = (totalEnergy.value() / 2286 (curTick() - memory.lastStatsResetTick)) * 2287 (SimClock::Frequency / 1000000000.0); 2288} 2289 2290void 2291DRAMCtrl::Rank::computeStats() 2292{ 2293 DPRINTF(DRAM,"Computing stats due to a dump callback\n"); 2294 2295 // Update the stats 2296 updatePowerStats(); 2297 2298 // final update of power state times 2299 pwrStateTime[pwrState] += (curTick() - pwrStateTick); 2300 pwrStateTick = curTick(); 2301 2302} 2303 2304void 2305DRAMCtrl::Rank::resetStats() { 2306 // The only way to clear the counters in DRAMPower is to call 2307 // calcWindowEnergy function as that then calls clearCounters. The 2308 // clearCounters method itself is private. 2309 power.powerlib.calcWindowEnergy(divCeil(curTick(), memory.tCK) - 2310 memory.timeStampOffset); 2311 2312} 2313 2314void 2315DRAMCtrl::Rank::regStats() 2316{ 2317 pwrStateTime 2318 .init(6) 2319 .name(name() + ".memoryStateTime") 2320 .desc("Time in different power states"); 2321 pwrStateTime.subname(0, "IDLE"); 2322 pwrStateTime.subname(1, "REF"); 2323 pwrStateTime.subname(2, "SREF"); 2324 pwrStateTime.subname(3, "PRE_PDN"); 2325 pwrStateTime.subname(4, "ACT"); 2326 pwrStateTime.subname(5, "ACT_PDN"); 2327 2328 actEnergy 2329 .name(name() + ".actEnergy") 2330 .desc("Energy for activate commands per rank (pJ)"); 2331 2332 preEnergy 2333 .name(name() + ".preEnergy") 2334 .desc("Energy for precharge commands per rank (pJ)"); 2335 2336 readEnergy 2337 .name(name() + ".readEnergy") 2338 .desc("Energy for read commands per rank (pJ)"); 2339 2340 writeEnergy 2341 .name(name() + ".writeEnergy") 2342 .desc("Energy for write commands per rank (pJ)"); 2343 2344 refreshEnergy 2345 .name(name() + ".refreshEnergy") 2346 .desc("Energy for refresh commands per rank (pJ)"); 2347 2348 actBackEnergy 2349 .name(name() + ".actBackEnergy") 2350 .desc("Energy for active background per rank (pJ)"); 2351 2352 preBackEnergy 2353 .name(name() + ".preBackEnergy") 2354 .desc("Energy for precharge background per rank (pJ)"); 2355 2356 actPowerDownEnergy 2357 .name(name() + ".actPowerDownEnergy") 2358 .desc("Energy for active power-down per rank (pJ)"); 2359 2360 prePowerDownEnergy 2361 .name(name() + ".prePowerDownEnergy") 2362 .desc("Energy for precharge power-down per rank (pJ)"); 2363 2364 selfRefreshEnergy 2365 .name(name() + ".selfRefreshEnergy") 2366 .desc("Energy for self refresh per rank (pJ)"); 2367 2368 totalEnergy 2369 .name(name() + ".totalEnergy") 2370 .desc("Total energy per rank (pJ)"); 2371 2372 averagePower 2373 .name(name() + ".averagePower") 2374 .desc("Core power per rank (mW)"); 2375 2376 totalIdleTime 2377 .name(name() + ".totalIdleTime") 2378 .desc("Total Idle time Per DRAM Rank"); 2379 2380 Stats::registerDumpCallback(new RankDumpCallback(this)); 2381 Stats::registerResetCallback(new RankResetCallback(this)); 2382} 2383void 2384DRAMCtrl::regStats() 2385{ 2386 using namespace Stats; 2387 2388 AbstractMemory::regStats(); 2389 2390 for (auto r : ranks) { 2391 r->regStats(); 2392 } 2393 2394 registerResetCallback(new MemResetCallback(this)); 2395 2396 readReqs 2397 .name(name() + ".readReqs") 2398 .desc("Number of read requests accepted"); 2399 2400 writeReqs 2401 .name(name() + ".writeReqs") 2402 .desc("Number of write requests accepted"); 2403 2404 readBursts 2405 .name(name() + ".readBursts") 2406 .desc("Number of DRAM read bursts, " 2407 "including those serviced by the write queue"); 2408 2409 writeBursts 2410 .name(name() + ".writeBursts") 2411 .desc("Number of DRAM write bursts, " 2412 "including those merged in the write queue"); 2413 2414 servicedByWrQ 2415 .name(name() + ".servicedByWrQ") 2416 .desc("Number of DRAM read bursts serviced by the write queue"); 2417 2418 mergedWrBursts 2419 .name(name() + ".mergedWrBursts") 2420 .desc("Number of DRAM write bursts merged with an existing one"); 2421 2422 neitherReadNorWrite 2423 .name(name() + ".neitherReadNorWriteReqs") 2424 .desc("Number of requests that are neither read nor write"); 2425 2426 perBankRdBursts 2427 .init(banksPerRank * ranksPerChannel) 2428 .name(name() + ".perBankRdBursts") 2429 .desc("Per bank write bursts"); 2430 2431 perBankWrBursts 2432 .init(banksPerRank * ranksPerChannel) 2433 .name(name() + ".perBankWrBursts") 2434 .desc("Per bank write bursts"); 2435 2436 avgRdQLen 2437 .name(name() + ".avgRdQLen") 2438 .desc("Average read queue length when enqueuing") 2439 .precision(2); 2440 2441 avgWrQLen 2442 .name(name() + ".avgWrQLen") 2443 .desc("Average write queue length when enqueuing") 2444 .precision(2); 2445 2446 totQLat 2447 .name(name() + ".totQLat") 2448 .desc("Total ticks spent queuing"); 2449 2450 totBusLat 2451 .name(name() + ".totBusLat") 2452 .desc("Total ticks spent in databus transfers"); 2453 2454 totMemAccLat 2455 .name(name() + ".totMemAccLat") 2456 .desc("Total ticks spent from burst creation until serviced " 2457 "by the DRAM"); 2458 2459 avgQLat 2460 .name(name() + ".avgQLat") 2461 .desc("Average queueing delay per DRAM burst") 2462 .precision(2); 2463 2464 avgQLat = totQLat / (readBursts - servicedByWrQ); 2465 2466 avgBusLat 2467 .name(name() + ".avgBusLat") 2468 .desc("Average bus latency per DRAM burst") 2469 .precision(2); 2470 2471 avgBusLat = totBusLat / (readBursts - servicedByWrQ); 2472 2473 avgMemAccLat 2474 .name(name() + ".avgMemAccLat") 2475 .desc("Average memory access latency per DRAM burst") 2476 .precision(2); 2477 2478 avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ); 2479 2480 numRdRetry 2481 .name(name() + ".numRdRetry") 2482 .desc("Number of times read queue was full causing retry"); 2483 2484 numWrRetry 2485 .name(name() + ".numWrRetry") 2486 .desc("Number of times write queue was full causing retry"); 2487 2488 readRowHits 2489 .name(name() + ".readRowHits") 2490 .desc("Number of row buffer hits during reads"); 2491 2492 writeRowHits 2493 .name(name() + ".writeRowHits") 2494 .desc("Number of row buffer hits during writes"); 2495 2496 readRowHitRate 2497 .name(name() + ".readRowHitRate") 2498 .desc("Row buffer hit rate for reads") 2499 .precision(2); 2500 2501 readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100; 2502 2503 writeRowHitRate 2504 .name(name() + ".writeRowHitRate") 2505 .desc("Row buffer hit rate for writes") 2506 .precision(2); 2507 2508 writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100; 2509 2510 readPktSize 2511 .init(ceilLog2(burstSize) + 1) 2512 .name(name() + ".readPktSize") 2513 .desc("Read request sizes (log2)"); 2514 2515 writePktSize 2516 .init(ceilLog2(burstSize) + 1) 2517 .name(name() + ".writePktSize") 2518 .desc("Write request sizes (log2)"); 2519 2520 rdQLenPdf 2521 .init(readBufferSize) 2522 .name(name() + ".rdQLenPdf") 2523 .desc("What read queue length does an incoming req see"); 2524 2525 wrQLenPdf 2526 .init(writeBufferSize) 2527 .name(name() + ".wrQLenPdf") 2528 .desc("What write queue length does an incoming req see"); 2529 2530 bytesPerActivate 2531 .init(maxAccessesPerRow) 2532 .name(name() + ".bytesPerActivate") 2533 .desc("Bytes accessed per row activation") 2534 .flags(nozero); 2535 2536 rdPerTurnAround 2537 .init(readBufferSize) 2538 .name(name() + ".rdPerTurnAround") 2539 .desc("Reads before turning the bus around for writes") 2540 .flags(nozero); 2541 2542 wrPerTurnAround 2543 .init(writeBufferSize) 2544 .name(name() + ".wrPerTurnAround") 2545 .desc("Writes before turning the bus around for reads") 2546 .flags(nozero); 2547 2548 bytesReadDRAM 2549 .name(name() + ".bytesReadDRAM") 2550 .desc("Total number of bytes read from DRAM"); 2551 2552 bytesReadWrQ 2553 .name(name() + ".bytesReadWrQ") 2554 .desc("Total number of bytes read from write queue"); 2555 2556 bytesWritten 2557 .name(name() + ".bytesWritten") 2558 .desc("Total number of bytes written to DRAM"); 2559 2560 bytesReadSys 2561 .name(name() + ".bytesReadSys") 2562 .desc("Total read bytes from the system interface side"); 2563 2564 bytesWrittenSys 2565 .name(name() + ".bytesWrittenSys") 2566 .desc("Total written bytes from the system interface side"); 2567 2568 avgRdBW 2569 .name(name() + ".avgRdBW") 2570 .desc("Average DRAM read bandwidth in MiByte/s") 2571 .precision(2); 2572 2573 avgRdBW = (bytesReadDRAM / 1000000) / simSeconds; 2574 2575 avgWrBW 2576 .name(name() + ".avgWrBW") 2577 .desc("Average achieved write bandwidth in MiByte/s") 2578 .precision(2); 2579 2580 avgWrBW = (bytesWritten / 1000000) / simSeconds; 2581 2582 avgRdBWSys 2583 .name(name() + ".avgRdBWSys") 2584 .desc("Average system read bandwidth in MiByte/s") 2585 .precision(2); 2586 2587 avgRdBWSys = (bytesReadSys / 1000000) / simSeconds; 2588 2589 avgWrBWSys 2590 .name(name() + ".avgWrBWSys") 2591 .desc("Average system write bandwidth in MiByte/s") 2592 .precision(2); 2593 2594 avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds; 2595 2596 peakBW 2597 .name(name() + ".peakBW") 2598 .desc("Theoretical peak bandwidth in MiByte/s") 2599 .precision(2); 2600 2601 peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000; 2602 2603 busUtil 2604 .name(name() + ".busUtil") 2605 .desc("Data bus utilization in percentage") 2606 .precision(2); 2607 busUtil = (avgRdBW + avgWrBW) / peakBW * 100; 2608 2609 totGap 2610 .name(name() + ".totGap") 2611 .desc("Total gap between requests"); 2612 2613 avgGap 2614 .name(name() + ".avgGap") 2615 .desc("Average gap between requests") 2616 .precision(2); 2617 2618 avgGap = totGap / (readReqs + writeReqs); 2619 2620 // Stats for DRAM Power calculation based on Micron datasheet 2621 busUtilRead 2622 .name(name() + ".busUtilRead") 2623 .desc("Data bus utilization in percentage for reads") 2624 .precision(2); 2625 2626 busUtilRead = avgRdBW / peakBW * 100; 2627 2628 busUtilWrite 2629 .name(name() + ".busUtilWrite") 2630 .desc("Data bus utilization in percentage for writes") 2631 .precision(2); 2632 2633 busUtilWrite = avgWrBW / peakBW * 100; 2634 2635 pageHitRate 2636 .name(name() + ".pageHitRate") 2637 .desc("Row buffer hit rate, read and write combined") 2638 .precision(2); 2639 2640 pageHitRate = (writeRowHits + readRowHits) / 2641 (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100; 2642} 2643 2644void 2645DRAMCtrl::recvFunctional(PacketPtr pkt) 2646{ 2647 // rely on the abstract memory 2648 functionalAccess(pkt); 2649} 2650 2651BaseSlavePort& 2652DRAMCtrl::getSlavePort(const string &if_name, PortID idx) 2653{ 2654 if (if_name != "port") { 2655 return MemObject::getSlavePort(if_name, idx); 2656 } else { 2657 return port; 2658 } 2659} 2660 2661DrainState 2662DRAMCtrl::drain() 2663{ 2664 // if there is anything in any of our internal queues, keep track 2665 // of that as well 2666 if (!(writeQueue.empty() && readQueue.empty() && respQueue.empty() && 2667 allRanksDrained())) { 2668 2669 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d," 2670 " resp: %d\n", writeQueue.size(), readQueue.size(), 2671 respQueue.size()); 2672 2673 // the only queue that is not drained automatically over time 2674 // is the write queue, thus kick things into action if needed 2675 if (!writeQueue.empty() && !nextReqEvent.scheduled()) { 2676 schedule(nextReqEvent, curTick()); 2677 } 2678 2679 // also need to kick off events to exit self-refresh 2680 for (auto r : ranks) { 2681 // force self-refresh exit, which in turn will issue auto-refresh 2682 if (r->pwrState == PWR_SREF) { 2683 DPRINTF(DRAM,"Rank%d: Forcing self-refresh wakeup in drain\n", 2684 r->rank); 2685 r->scheduleWakeUpEvent(tXS); 2686 } 2687 } 2688 2689 return DrainState::Draining; 2690 } else { 2691 return DrainState::Drained; 2692 } 2693} 2694 2695bool 2696DRAMCtrl::allRanksDrained() const 2697{ 2698 // true until proven false 2699 bool all_ranks_drained = true; 2700 for (auto r : ranks) { 2701 // then verify that the power state is IDLE ensuring all banks are 2702 // closed and rank is not in a low power state. Also verify that rank 2703 // is idle from a refresh point of view. 2704 all_ranks_drained = r->inPwrIdleState() && r->inRefIdleState() && 2705 all_ranks_drained; 2706 } 2707 return all_ranks_drained; 2708} 2709 2710void 2711DRAMCtrl::drainResume() 2712{ 2713 if (!isTimingMode && system()->isTimingMode()) { 2714 // if we switched to timing mode, kick things into action, 2715 // and behave as if we restored from a checkpoint 2716 startup(); 2717 } else if (isTimingMode && !system()->isTimingMode()) { 2718 // if we switch from timing mode, stop the refresh events to 2719 // not cause issues with KVM 2720 for (auto r : ranks) { 2721 r->suspend(); 2722 } 2723 } 2724 2725 // update the mode 2726 isTimingMode = system()->isTimingMode(); 2727} 2728 2729DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory) 2730 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this), 2731 memory(_memory) 2732{ } 2733 2734AddrRangeList 2735DRAMCtrl::MemoryPort::getAddrRanges() const 2736{ 2737 AddrRangeList ranges; 2738 ranges.push_back(memory.getAddrRange()); 2739 return ranges; 2740} 2741 2742void 2743DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt) 2744{ 2745 pkt->pushLabel(memory.name()); 2746 2747 if (!queue.checkFunctional(pkt)) { 2748 // Default implementation of SimpleTimingPort::recvFunctional() 2749 // calls recvAtomic() and throws away the latency; we can save a 2750 // little here by just not calculating the latency. 2751 memory.recvFunctional(pkt); 2752 } 2753 2754 pkt->popLabel(); 2755} 2756 2757Tick 2758DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt) 2759{ 2760 return memory.recvAtomic(pkt); 2761} 2762 2763bool 2764DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt) 2765{ 2766 // pass it to the memory controller 2767 return memory.recvTimingReq(pkt); 2768} 2769 2770DRAMCtrl* 2771DRAMCtrlParams::create() 2772{ 2773 return new DRAMCtrl(this); 2774} 2775