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