dram_ctrl.cc revision 10809:e3963342ead4
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.sendRetryReq(); 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 // response_time consumes the static latency and is charged also 881 // with headerDelay that takes into account the delay provided by 882 // the xbar and also the payloadDelay that takes into account the 883 // number of data beats. 884 Tick response_time = curTick() + static_latency + pkt->headerDelay + 885 pkt->payloadDelay; 886 // Here we reset the timing of the packet before sending it out. 887 pkt->headerDelay = pkt->payloadDelay = 0; 888 889 // queue the packet in the response queue to be sent out after 890 // the static latency has passed 891 port.schedTimingResp(pkt, response_time); 892 } else { 893 // @todo the packet is going to be deleted, and the DRAMPacket 894 // is still having a pointer to it 895 pendingDelete.push_back(pkt); 896 } 897 898 DPRINTF(DRAM, "Done\n"); 899 900 return; 901} 902 903void 904DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref, 905 Tick act_tick, uint32_t row) 906{ 907 assert(rank_ref.actTicks.size() == activationLimit); 908 909 DPRINTF(DRAM, "Activate at tick %d\n", act_tick); 910 911 // update the open row 912 assert(bank_ref.openRow == Bank::NO_ROW); 913 bank_ref.openRow = row; 914 915 // start counting anew, this covers both the case when we 916 // auto-precharged, and when this access is forced to 917 // precharge 918 bank_ref.bytesAccessed = 0; 919 bank_ref.rowAccesses = 0; 920 921 ++rank_ref.numBanksActive; 922 assert(rank_ref.numBanksActive <= banksPerRank); 923 924 DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n", 925 bank_ref.bank, rank_ref.rank, act_tick, 926 ranks[rank_ref.rank]->numBanksActive); 927 928 rank_ref.power.powerlib.doCommand(MemCommand::ACT, bank_ref.bank, 929 divCeil(act_tick, tCK) - 930 timeStampOffset); 931 932 DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) - 933 timeStampOffset, bank_ref.bank, rank_ref.rank); 934 935 // The next access has to respect tRAS for this bank 936 bank_ref.preAllowedAt = act_tick + tRAS; 937 938 // Respect the row-to-column command delay 939 bank_ref.colAllowedAt = std::max(act_tick + tRCD, bank_ref.colAllowedAt); 940 941 // start by enforcing tRRD 942 for(int i = 0; i < banksPerRank; i++) { 943 // next activate to any bank in this rank must not happen 944 // before tRRD 945 if (bankGroupArch && (bank_ref.bankgr == rank_ref.banks[i].bankgr)) { 946 // bank group architecture requires longer delays between 947 // ACT commands within the same bank group. Use tRRD_L 948 // in this case 949 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD_L, 950 rank_ref.banks[i].actAllowedAt); 951 } else { 952 // use shorter tRRD value when either 953 // 1) bank group architecture is not supportted 954 // 2) bank is in a different bank group 955 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD, 956 rank_ref.banks[i].actAllowedAt); 957 } 958 } 959 960 // next, we deal with tXAW, if the activation limit is disabled 961 // then we directly schedule an activate power event 962 if (!rank_ref.actTicks.empty()) { 963 // sanity check 964 if (rank_ref.actTicks.back() && 965 (act_tick - rank_ref.actTicks.back()) < tXAW) { 966 panic("Got %d activates in window %d (%llu - %llu) which " 967 "is smaller than %llu\n", activationLimit, act_tick - 968 rank_ref.actTicks.back(), act_tick, 969 rank_ref.actTicks.back(), tXAW); 970 } 971 972 // shift the times used for the book keeping, the last element 973 // (highest index) is the oldest one and hence the lowest value 974 rank_ref.actTicks.pop_back(); 975 976 // record an new activation (in the future) 977 rank_ref.actTicks.push_front(act_tick); 978 979 // cannot activate more than X times in time window tXAW, push the 980 // next one (the X + 1'st activate) to be tXAW away from the 981 // oldest in our window of X 982 if (rank_ref.actTicks.back() && 983 (act_tick - rank_ref.actTicks.back()) < tXAW) { 984 DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate " 985 "no earlier than %llu\n", activationLimit, 986 rank_ref.actTicks.back() + tXAW); 987 for(int j = 0; j < banksPerRank; j++) 988 // next activate must not happen before end of window 989 rank_ref.banks[j].actAllowedAt = 990 std::max(rank_ref.actTicks.back() + tXAW, 991 rank_ref.banks[j].actAllowedAt); 992 } 993 } 994 995 // at the point when this activate takes place, make sure we 996 // transition to the active power state 997 if (!rank_ref.activateEvent.scheduled()) 998 schedule(rank_ref.activateEvent, act_tick); 999 else if (rank_ref.activateEvent.when() > act_tick) 1000 // move it sooner in time 1001 reschedule(rank_ref.activateEvent, act_tick); 1002} 1003 1004void 1005DRAMCtrl::prechargeBank(Rank& rank_ref, Bank& bank, Tick pre_at, bool trace) 1006{ 1007 // make sure the bank has an open row 1008 assert(bank.openRow != Bank::NO_ROW); 1009 1010 // sample the bytes per activate here since we are closing 1011 // the page 1012 bytesPerActivate.sample(bank.bytesAccessed); 1013 1014 bank.openRow = Bank::NO_ROW; 1015 1016 // no precharge allowed before this one 1017 bank.preAllowedAt = pre_at; 1018 1019 Tick pre_done_at = pre_at + tRP; 1020 1021 bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at); 1022 1023 assert(rank_ref.numBanksActive != 0); 1024 --rank_ref.numBanksActive; 1025 1026 DPRINTF(DRAM, "Precharging bank %d, rank %d at tick %lld, now got " 1027 "%d active\n", bank.bank, rank_ref.rank, pre_at, 1028 rank_ref.numBanksActive); 1029 1030 if (trace) { 1031 1032 rank_ref.power.powerlib.doCommand(MemCommand::PRE, bank.bank, 1033 divCeil(pre_at, tCK) - 1034 timeStampOffset); 1035 DPRINTF(DRAMPower, "%llu,PRE,%d,%d\n", divCeil(pre_at, tCK) - 1036 timeStampOffset, bank.bank, rank_ref.rank); 1037 } 1038 // if we look at the current number of active banks we might be 1039 // tempted to think the DRAM is now idle, however this can be 1040 // undone by an activate that is scheduled to happen before we 1041 // would have reached the idle state, so schedule an event and 1042 // rather check once we actually make it to the point in time when 1043 // the (last) precharge takes place 1044 if (!rank_ref.prechargeEvent.scheduled()) 1045 schedule(rank_ref.prechargeEvent, pre_done_at); 1046 else if (rank_ref.prechargeEvent.when() < pre_done_at) 1047 reschedule(rank_ref.prechargeEvent, pre_done_at); 1048} 1049 1050void 1051DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt) 1052{ 1053 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n", 1054 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row); 1055 1056 // get the rank 1057 Rank& rank = dram_pkt->rankRef; 1058 1059 // get the bank 1060 Bank& bank = dram_pkt->bankRef; 1061 1062 // for the state we need to track if it is a row hit or not 1063 bool row_hit = true; 1064 1065 // respect any constraints on the command (e.g. tRCD or tCCD) 1066 Tick cmd_at = std::max(bank.colAllowedAt, curTick()); 1067 1068 // Determine the access latency and update the bank state 1069 if (bank.openRow == dram_pkt->row) { 1070 // nothing to do 1071 } else { 1072 row_hit = false; 1073 1074 // If there is a page open, precharge it. 1075 if (bank.openRow != Bank::NO_ROW) { 1076 prechargeBank(rank, bank, std::max(bank.preAllowedAt, curTick())); 1077 } 1078 1079 // next we need to account for the delay in activating the 1080 // page 1081 Tick act_tick = std::max(bank.actAllowedAt, curTick()); 1082 1083 // Record the activation and deal with all the global timing 1084 // constraints caused be a new activation (tRRD and tXAW) 1085 activateBank(rank, bank, act_tick, dram_pkt->row); 1086 1087 // issue the command as early as possible 1088 cmd_at = bank.colAllowedAt; 1089 } 1090 1091 // we need to wait until the bus is available before we can issue 1092 // the command 1093 cmd_at = std::max(cmd_at, busBusyUntil - tCL); 1094 1095 // update the packet ready time 1096 dram_pkt->readyTime = cmd_at + tCL + tBURST; 1097 1098 // only one burst can use the bus at any one point in time 1099 assert(dram_pkt->readyTime - busBusyUntil >= tBURST); 1100 1101 // update the time for the next read/write burst for each 1102 // bank (add a max with tCCD/tCCD_L here) 1103 Tick cmd_dly; 1104 for(int j = 0; j < ranksPerChannel; j++) { 1105 for(int i = 0; i < banksPerRank; i++) { 1106 // next burst to same bank group in this rank must not happen 1107 // before tCCD_L. Different bank group timing requirement is 1108 // tBURST; Add tCS for different ranks 1109 if (dram_pkt->rank == j) { 1110 if (bankGroupArch && 1111 (bank.bankgr == ranks[j]->banks[i].bankgr)) { 1112 // bank group architecture requires longer delays between 1113 // RD/WR burst commands to the same bank group. 1114 // Use tCCD_L in this case 1115 cmd_dly = tCCD_L; 1116 } else { 1117 // use tBURST (equivalent to tCCD_S), the shorter 1118 // cas-to-cas delay value, when either: 1119 // 1) bank group architecture is not supportted 1120 // 2) bank is in a different bank group 1121 cmd_dly = tBURST; 1122 } 1123 } else { 1124 // different rank is by default in a different bank group 1125 // use tBURST (equivalent to tCCD_S), which is the shorter 1126 // cas-to-cas delay in this case 1127 // Add tCS to account for rank-to-rank bus delay requirements 1128 cmd_dly = tBURST + tCS; 1129 } 1130 ranks[j]->banks[i].colAllowedAt = std::max(cmd_at + cmd_dly, 1131 ranks[j]->banks[i].colAllowedAt); 1132 } 1133 } 1134 1135 // Save rank of current access 1136 activeRank = dram_pkt->rank; 1137 1138 // If this is a write, we also need to respect the write recovery 1139 // time before a precharge, in the case of a read, respect the 1140 // read to precharge constraint 1141 bank.preAllowedAt = std::max(bank.preAllowedAt, 1142 dram_pkt->isRead ? cmd_at + tRTP : 1143 dram_pkt->readyTime + tWR); 1144 1145 // increment the bytes accessed and the accesses per row 1146 bank.bytesAccessed += burstSize; 1147 ++bank.rowAccesses; 1148 1149 // if we reached the max, then issue with an auto-precharge 1150 bool auto_precharge = pageMgmt == Enums::close || 1151 bank.rowAccesses == maxAccessesPerRow; 1152 1153 // if we did not hit the limit, we might still want to 1154 // auto-precharge 1155 if (!auto_precharge && 1156 (pageMgmt == Enums::open_adaptive || 1157 pageMgmt == Enums::close_adaptive)) { 1158 // a twist on the open and close page policies: 1159 // 1) open_adaptive page policy does not blindly keep the 1160 // page open, but close it if there are no row hits, and there 1161 // are bank conflicts in the queue 1162 // 2) close_adaptive page policy does not blindly close the 1163 // page, but closes it only if there are no row hits in the queue. 1164 // In this case, only force an auto precharge when there 1165 // are no same page hits in the queue 1166 bool got_more_hits = false; 1167 bool got_bank_conflict = false; 1168 1169 // either look at the read queue or write queue 1170 const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue : 1171 writeQueue; 1172 auto p = queue.begin(); 1173 // make sure we are not considering the packet that we are 1174 // currently dealing with (which is the head of the queue) 1175 ++p; 1176 1177 // keep on looking until we find a hit or reach the end of the queue 1178 // 1) if a hit is found, then both open and close adaptive policies keep 1179 // the page open 1180 // 2) if no hit is found, got_bank_conflict is set to true if a bank 1181 // conflict request is waiting in the queue 1182 while (!got_more_hits && p != queue.end()) { 1183 bool same_rank_bank = (dram_pkt->rank == (*p)->rank) && 1184 (dram_pkt->bank == (*p)->bank); 1185 bool same_row = dram_pkt->row == (*p)->row; 1186 got_more_hits |= same_rank_bank && same_row; 1187 got_bank_conflict |= same_rank_bank && !same_row; 1188 ++p; 1189 } 1190 1191 // auto pre-charge when either 1192 // 1) open_adaptive policy, we have not got any more hits, and 1193 // have a bank conflict 1194 // 2) close_adaptive policy and we have not got any more hits 1195 auto_precharge = !got_more_hits && 1196 (got_bank_conflict || pageMgmt == Enums::close_adaptive); 1197 } 1198 1199 // DRAMPower trace command to be written 1200 std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR"; 1201 1202 // MemCommand required for DRAMPower library 1203 MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD : 1204 MemCommand::WR; 1205 1206 // if this access should use auto-precharge, then we are 1207 // closing the row 1208 if (auto_precharge) { 1209 // if auto-precharge push a PRE command at the correct tick to the 1210 // list used by DRAMPower library to calculate power 1211 prechargeBank(rank, bank, std::max(curTick(), bank.preAllowedAt)); 1212 1213 DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId); 1214 } 1215 1216 // Update bus state 1217 busBusyUntil = dram_pkt->readyTime; 1218 1219 DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n", 1220 dram_pkt->addr, dram_pkt->readyTime, busBusyUntil); 1221 1222 dram_pkt->rankRef.power.powerlib.doCommand(command, dram_pkt->bank, 1223 divCeil(cmd_at, tCK) - 1224 timeStampOffset); 1225 1226 DPRINTF(DRAMPower, "%llu,%s,%d,%d\n", divCeil(cmd_at, tCK) - 1227 timeStampOffset, mem_cmd, dram_pkt->bank, dram_pkt->rank); 1228 1229 // Update the minimum timing between the requests, this is a 1230 // conservative estimate of when we have to schedule the next 1231 // request to not introduce any unecessary bubbles. In most cases 1232 // we will wake up sooner than we have to. 1233 nextReqTime = busBusyUntil - (tRP + tRCD + tCL); 1234 1235 // Update the stats and schedule the next request 1236 if (dram_pkt->isRead) { 1237 ++readsThisTime; 1238 if (row_hit) 1239 readRowHits++; 1240 bytesReadDRAM += burstSize; 1241 perBankRdBursts[dram_pkt->bankId]++; 1242 1243 // Update latency stats 1244 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime; 1245 totBusLat += tBURST; 1246 totQLat += cmd_at - dram_pkt->entryTime; 1247 } else { 1248 ++writesThisTime; 1249 if (row_hit) 1250 writeRowHits++; 1251 bytesWritten += burstSize; 1252 perBankWrBursts[dram_pkt->bankId]++; 1253 } 1254} 1255 1256void 1257DRAMCtrl::processNextReqEvent() 1258{ 1259 int busyRanks = 0; 1260 for (auto r : ranks) { 1261 if (!r->isAvailable()) { 1262 // rank is busy refreshing 1263 busyRanks++; 1264 1265 // let the rank know that if it was waiting to drain, it 1266 // is now done and ready to proceed 1267 r->checkDrainDone(); 1268 } 1269 } 1270 1271 if (busyRanks == ranksPerChannel) { 1272 // if all ranks are refreshing wait for them to finish 1273 // and stall this state machine without taking any further 1274 // action, and do not schedule a new nextReqEvent 1275 return; 1276 } 1277 1278 // pre-emptively set to false. Overwrite if in READ_TO_WRITE 1279 // or WRITE_TO_READ state 1280 bool switched_cmd_type = false; 1281 if (busState == READ_TO_WRITE) { 1282 DPRINTF(DRAM, "Switching to writes after %d reads with %d reads " 1283 "waiting\n", readsThisTime, readQueue.size()); 1284 1285 // sample and reset the read-related stats as we are now 1286 // transitioning to writes, and all reads are done 1287 rdPerTurnAround.sample(readsThisTime); 1288 readsThisTime = 0; 1289 1290 // now proceed to do the actual writes 1291 busState = WRITE; 1292 switched_cmd_type = true; 1293 } else if (busState == WRITE_TO_READ) { 1294 DPRINTF(DRAM, "Switching to reads after %d writes with %d writes " 1295 "waiting\n", writesThisTime, writeQueue.size()); 1296 1297 wrPerTurnAround.sample(writesThisTime); 1298 writesThisTime = 0; 1299 1300 busState = READ; 1301 switched_cmd_type = true; 1302 } 1303 1304 // when we get here it is either a read or a write 1305 if (busState == READ) { 1306 1307 // track if we should switch or not 1308 bool switch_to_writes = false; 1309 1310 if (readQueue.empty()) { 1311 // In the case there is no read request to go next, 1312 // trigger writes if we have passed the low threshold (or 1313 // if we are draining) 1314 if (!writeQueue.empty() && 1315 (drainManager || writeQueue.size() > writeLowThreshold)) { 1316 1317 switch_to_writes = true; 1318 } else { 1319 // check if we are drained 1320 if (respQueue.empty () && drainManager) { 1321 DPRINTF(Drain, "DRAM controller done draining\n"); 1322 drainManager->signalDrainDone(); 1323 drainManager = NULL; 1324 } 1325 1326 // nothing to do, not even any point in scheduling an 1327 // event for the next request 1328 return; 1329 } 1330 } else { 1331 // bool to check if there is a read to a free rank 1332 bool found_read = false; 1333 1334 // Figure out which read request goes next, and move it to the 1335 // front of the read queue 1336 found_read = chooseNext(readQueue, switched_cmd_type); 1337 1338 // if no read to an available rank is found then return 1339 // at this point. There could be writes to the available ranks 1340 // which are above the required threshold. However, to 1341 // avoid adding more complexity to the code, return and wait 1342 // for a refresh event to kick things into action again. 1343 if (!found_read) 1344 return; 1345 1346 DRAMPacket* dram_pkt = readQueue.front(); 1347 assert(dram_pkt->rankRef.isAvailable()); 1348 // here we get a bit creative and shift the bus busy time not 1349 // just the tWTR, but also a CAS latency to capture the fact 1350 // that we are allowed to prepare a new bank, but not issue a 1351 // read command until after tWTR, in essence we capture a 1352 // bubble on the data bus that is tWTR + tCL 1353 if (switched_cmd_type && dram_pkt->rank == activeRank) { 1354 busBusyUntil += tWTR + tCL; 1355 } 1356 1357 doDRAMAccess(dram_pkt); 1358 1359 // At this point we're done dealing with the request 1360 readQueue.pop_front(); 1361 1362 // sanity check 1363 assert(dram_pkt->size <= burstSize); 1364 assert(dram_pkt->readyTime >= curTick()); 1365 1366 // Insert into response queue. It will be sent back to the 1367 // requestor at its readyTime 1368 if (respQueue.empty()) { 1369 assert(!respondEvent.scheduled()); 1370 schedule(respondEvent, dram_pkt->readyTime); 1371 } else { 1372 assert(respQueue.back()->readyTime <= dram_pkt->readyTime); 1373 assert(respondEvent.scheduled()); 1374 } 1375 1376 respQueue.push_back(dram_pkt); 1377 1378 // we have so many writes that we have to transition 1379 if (writeQueue.size() > writeHighThreshold) { 1380 switch_to_writes = true; 1381 } 1382 } 1383 1384 // switching to writes, either because the read queue is empty 1385 // and the writes have passed the low threshold (or we are 1386 // draining), or because the writes hit the hight threshold 1387 if (switch_to_writes) { 1388 // transition to writing 1389 busState = READ_TO_WRITE; 1390 } 1391 } else { 1392 // bool to check if write to free rank is found 1393 bool found_write = false; 1394 1395 found_write = chooseNext(writeQueue, switched_cmd_type); 1396 1397 // if no writes to an available rank are found then return. 1398 // There could be reads to the available ranks. However, to avoid 1399 // adding more complexity to the code, return at this point and wait 1400 // for a refresh event to kick things into action again. 1401 if (!found_write) 1402 return; 1403 1404 DRAMPacket* dram_pkt = writeQueue.front(); 1405 assert(dram_pkt->rankRef.isAvailable()); 1406 // sanity check 1407 assert(dram_pkt->size <= burstSize); 1408 1409 // add a bubble to the data bus, as defined by the 1410 // tRTW when access is to the same rank as previous burst 1411 // Different rank timing is handled with tCS, which is 1412 // applied to colAllowedAt 1413 if (switched_cmd_type && dram_pkt->rank == activeRank) { 1414 busBusyUntil += tRTW; 1415 } 1416 1417 doDRAMAccess(dram_pkt); 1418 1419 writeQueue.pop_front(); 1420 delete dram_pkt; 1421 1422 // If we emptied the write queue, or got sufficiently below the 1423 // threshold (using the minWritesPerSwitch as the hysteresis) and 1424 // are not draining, or we have reads waiting and have done enough 1425 // writes, then switch to reads. 1426 if (writeQueue.empty() || 1427 (writeQueue.size() + minWritesPerSwitch < writeLowThreshold && 1428 !drainManager) || 1429 (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) { 1430 // turn the bus back around for reads again 1431 busState = WRITE_TO_READ; 1432 1433 // note that the we switch back to reads also in the idle 1434 // case, which eventually will check for any draining and 1435 // also pause any further scheduling if there is really 1436 // nothing to do 1437 } 1438 } 1439 // It is possible that a refresh to another rank kicks things back into 1440 // action before reaching this point. 1441 if (!nextReqEvent.scheduled()) 1442 schedule(nextReqEvent, std::max(nextReqTime, curTick())); 1443 1444 // If there is space available and we have writes waiting then let 1445 // them retry. This is done here to ensure that the retry does not 1446 // cause a nextReqEvent to be scheduled before we do so as part of 1447 // the next request processing 1448 if (retryWrReq && writeQueue.size() < writeBufferSize) { 1449 retryWrReq = false; 1450 port.sendRetryReq(); 1451 } 1452} 1453 1454uint64_t 1455DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue, 1456 bool switched_cmd_type) const 1457{ 1458 uint64_t bank_mask = 0; 1459 Tick min_act_at = MaxTick; 1460 1461 uint64_t bank_mask_same_rank = 0; 1462 Tick min_act_at_same_rank = MaxTick; 1463 1464 // Give precedence to commands that access same rank as previous command 1465 bool same_rank_match = false; 1466 1467 // determine if we have queued transactions targetting the 1468 // bank in question 1469 vector<bool> got_waiting(ranksPerChannel * banksPerRank, false); 1470 for (const auto& p : queue) { 1471 if(p->rankRef.isAvailable()) 1472 got_waiting[p->bankId] = true; 1473 } 1474 1475 for (int i = 0; i < ranksPerChannel; i++) { 1476 for (int j = 0; j < banksPerRank; j++) { 1477 uint16_t bank_id = i * banksPerRank + j; 1478 1479 // if we have waiting requests for the bank, and it is 1480 // amongst the first available, update the mask 1481 if (got_waiting[bank_id]) { 1482 // make sure this rank is not currently refreshing. 1483 assert(ranks[i]->isAvailable()); 1484 // simplistic approximation of when the bank can issue 1485 // an activate, ignoring any rank-to-rank switching 1486 // cost in this calculation 1487 Tick act_at = ranks[i]->banks[j].openRow == Bank::NO_ROW ? 1488 ranks[i]->banks[j].actAllowedAt : 1489 std::max(ranks[i]->banks[j].preAllowedAt, curTick()) + tRP; 1490 1491 // prioritize commands that access the 1492 // same rank as previous burst 1493 // Calculate bank mask separately for the case and 1494 // evaluate after loop iterations complete 1495 if (i == activeRank && ranksPerChannel > 1) { 1496 if (act_at <= min_act_at_same_rank) { 1497 // reset same rank bank mask if new minimum is found 1498 // and previous minimum could not immediately send ACT 1499 if (act_at < min_act_at_same_rank && 1500 min_act_at_same_rank > curTick()) 1501 bank_mask_same_rank = 0; 1502 1503 // Set flag indicating that a same rank 1504 // opportunity was found 1505 same_rank_match = true; 1506 1507 // set the bit corresponding to the available bank 1508 replaceBits(bank_mask_same_rank, bank_id, bank_id, 1); 1509 min_act_at_same_rank = act_at; 1510 } 1511 } else { 1512 if (act_at <= min_act_at) { 1513 // reset bank mask if new minimum is found 1514 // and either previous minimum could not immediately send ACT 1515 if (act_at < min_act_at && min_act_at > curTick()) 1516 bank_mask = 0; 1517 // set the bit corresponding to the available bank 1518 replaceBits(bank_mask, bank_id, bank_id, 1); 1519 min_act_at = act_at; 1520 } 1521 } 1522 } 1523 } 1524 } 1525 1526 // Determine the earliest time when the next burst can issue based 1527 // on the current busBusyUntil delay. 1528 // Offset by tRCD to correlate with ACT timing variables 1529 Tick min_cmd_at = busBusyUntil - tCL - tRCD; 1530 1531 // if we have multiple ranks and all 1532 // waiting packets are accessing a rank which was previously active 1533 // then bank_mask_same_rank will be set to a value while bank_mask will 1534 // remain 0. In this case, the function should return the value of 1535 // bank_mask_same_rank. 1536 // else if waiting packets access a rank which was previously active and 1537 // other ranks, prioritize same rank accesses that can issue B2B 1538 // Only optimize for same ranks when the command type 1539 // does not change; do not want to unnecessarily incur tWTR 1540 // 1541 // Resulting FCFS prioritization Order is: 1542 // 1) Commands that access the same rank as previous burst 1543 // and can prep the bank seamlessly. 1544 // 2) Commands (any rank) with earliest bank prep 1545 if ((bank_mask == 0) || (!switched_cmd_type && same_rank_match && 1546 min_act_at_same_rank <= min_cmd_at)) { 1547 bank_mask = bank_mask_same_rank; 1548 } 1549 1550 return bank_mask; 1551} 1552 1553DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p) 1554 : EventManager(&_memory), memory(_memory), 1555 pwrStateTrans(PWR_IDLE), pwrState(PWR_IDLE), pwrStateTick(0), 1556 refreshState(REF_IDLE), refreshDueAt(0), 1557 power(_p, false), numBanksActive(0), 1558 activateEvent(*this), prechargeEvent(*this), 1559 refreshEvent(*this), powerEvent(*this) 1560{ } 1561 1562void 1563DRAMCtrl::Rank::startup(Tick ref_tick) 1564{ 1565 assert(ref_tick > curTick()); 1566 1567 pwrStateTick = curTick(); 1568 1569 // kick off the refresh, and give ourselves enough time to 1570 // precharge 1571 schedule(refreshEvent, ref_tick); 1572} 1573 1574void 1575DRAMCtrl::Rank::suspend() 1576{ 1577 deschedule(refreshEvent); 1578} 1579 1580void 1581DRAMCtrl::Rank::checkDrainDone() 1582{ 1583 // if this rank was waiting to drain it is now able to proceed to 1584 // precharge 1585 if (refreshState == REF_DRAIN) { 1586 DPRINTF(DRAM, "Refresh drain done, now precharging\n"); 1587 1588 refreshState = REF_PRE; 1589 1590 // hand control back to the refresh event loop 1591 schedule(refreshEvent, curTick()); 1592 } 1593} 1594 1595void 1596DRAMCtrl::Rank::processActivateEvent() 1597{ 1598 // we should transition to the active state as soon as any bank is active 1599 if (pwrState != PWR_ACT) 1600 // note that at this point numBanksActive could be back at 1601 // zero again due to a precharge scheduled in the future 1602 schedulePowerEvent(PWR_ACT, curTick()); 1603} 1604 1605void 1606DRAMCtrl::Rank::processPrechargeEvent() 1607{ 1608 // if we reached zero, then special conditions apply as we track 1609 // if all banks are precharged for the power models 1610 if (numBanksActive == 0) { 1611 // we should transition to the idle state when the last bank 1612 // is precharged 1613 schedulePowerEvent(PWR_IDLE, curTick()); 1614 } 1615} 1616 1617void 1618DRAMCtrl::Rank::processRefreshEvent() 1619{ 1620 // when first preparing the refresh, remember when it was due 1621 if (refreshState == REF_IDLE) { 1622 // remember when the refresh is due 1623 refreshDueAt = curTick(); 1624 1625 // proceed to drain 1626 refreshState = REF_DRAIN; 1627 1628 DPRINTF(DRAM, "Refresh due\n"); 1629 } 1630 1631 // let any scheduled read or write to the same rank go ahead, 1632 // after which it will 1633 // hand control back to this event loop 1634 if (refreshState == REF_DRAIN) { 1635 // if a request is at the moment being handled and this request is 1636 // accessing the current rank then wait for it to finish 1637 if ((rank == memory.activeRank) 1638 && (memory.nextReqEvent.scheduled())) { 1639 // hand control over to the request loop until it is 1640 // evaluated next 1641 DPRINTF(DRAM, "Refresh awaiting draining\n"); 1642 1643 return; 1644 } else { 1645 refreshState = REF_PRE; 1646 } 1647 } 1648 1649 // at this point, ensure that all banks are precharged 1650 if (refreshState == REF_PRE) { 1651 // precharge any active bank if we are not already in the idle 1652 // state 1653 if (pwrState != PWR_IDLE) { 1654 // at the moment, we use a precharge all even if there is 1655 // only a single bank open 1656 DPRINTF(DRAM, "Precharging all\n"); 1657 1658 // first determine when we can precharge 1659 Tick pre_at = curTick(); 1660 1661 for (auto &b : banks) { 1662 // respect both causality and any existing bank 1663 // constraints, some banks could already have a 1664 // (auto) precharge scheduled 1665 pre_at = std::max(b.preAllowedAt, pre_at); 1666 } 1667 1668 // make sure all banks per rank are precharged, and for those that 1669 // already are, update their availability 1670 Tick act_allowed_at = pre_at + memory.tRP; 1671 1672 for (auto &b : banks) { 1673 if (b.openRow != Bank::NO_ROW) { 1674 memory.prechargeBank(*this, b, pre_at, false); 1675 } else { 1676 b.actAllowedAt = std::max(b.actAllowedAt, act_allowed_at); 1677 b.preAllowedAt = std::max(b.preAllowedAt, pre_at); 1678 } 1679 } 1680 1681 // precharge all banks in rank 1682 power.powerlib.doCommand(MemCommand::PREA, 0, 1683 divCeil(pre_at, memory.tCK) - 1684 memory.timeStampOffset); 1685 1686 DPRINTF(DRAMPower, "%llu,PREA,0,%d\n", 1687 divCeil(pre_at, memory.tCK) - 1688 memory.timeStampOffset, rank); 1689 } else { 1690 DPRINTF(DRAM, "All banks already precharged, starting refresh\n"); 1691 1692 // go ahead and kick the power state machine into gear if 1693 // we are already idle 1694 schedulePowerEvent(PWR_REF, curTick()); 1695 } 1696 1697 refreshState = REF_RUN; 1698 assert(numBanksActive == 0); 1699 1700 // wait for all banks to be precharged, at which point the 1701 // power state machine will transition to the idle state, and 1702 // automatically move to a refresh, at that point it will also 1703 // call this method to get the refresh event loop going again 1704 return; 1705 } 1706 1707 // last but not least we perform the actual refresh 1708 if (refreshState == REF_RUN) { 1709 // should never get here with any banks active 1710 assert(numBanksActive == 0); 1711 assert(pwrState == PWR_REF); 1712 1713 Tick ref_done_at = curTick() + memory.tRFC; 1714 1715 for (auto &b : banks) { 1716 b.actAllowedAt = ref_done_at; 1717 } 1718 1719 // at the moment this affects all ranks 1720 power.powerlib.doCommand(MemCommand::REF, 0, 1721 divCeil(curTick(), memory.tCK) - 1722 memory.timeStampOffset); 1723 1724 // at the moment sort the list of commands and update the counters 1725 // for DRAMPower libray when doing a refresh 1726 sort(power.powerlib.cmdList.begin(), 1727 power.powerlib.cmdList.end(), DRAMCtrl::sortTime); 1728 1729 // update the counters for DRAMPower, passing false to 1730 // indicate that this is not the last command in the 1731 // list. DRAMPower requires this information for the 1732 // correct calculation of the background energy at the end 1733 // of the simulation. Ideally we would want to call this 1734 // function with true once at the end of the 1735 // simulation. However, the discarded energy is extremly 1736 // small and does not effect the final results. 1737 power.powerlib.updateCounters(false); 1738 1739 // call the energy function 1740 power.powerlib.calcEnergy(); 1741 1742 // Update the stats 1743 updatePowerStats(); 1744 1745 DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), memory.tCK) - 1746 memory.timeStampOffset, rank); 1747 1748 // make sure we did not wait so long that we cannot make up 1749 // for it 1750 if (refreshDueAt + memory.tREFI < ref_done_at) { 1751 fatal("Refresh was delayed so long we cannot catch up\n"); 1752 } 1753 1754 // compensate for the delay in actually performing the refresh 1755 // when scheduling the next one 1756 schedule(refreshEvent, refreshDueAt + memory.tREFI - memory.tRP); 1757 1758 assert(!powerEvent.scheduled()); 1759 1760 // move to the idle power state once the refresh is done, this 1761 // will also move the refresh state machine to the refresh 1762 // idle state 1763 schedulePowerEvent(PWR_IDLE, ref_done_at); 1764 1765 DPRINTF(DRAMState, "Refresh done at %llu and next refresh at %llu\n", 1766 ref_done_at, refreshDueAt + memory.tREFI); 1767 } 1768} 1769 1770void 1771DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state, Tick tick) 1772{ 1773 // respect causality 1774 assert(tick >= curTick()); 1775 1776 if (!powerEvent.scheduled()) { 1777 DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n", 1778 tick, pwr_state); 1779 1780 // insert the new transition 1781 pwrStateTrans = pwr_state; 1782 1783 schedule(powerEvent, tick); 1784 } else { 1785 panic("Scheduled power event at %llu to state %d, " 1786 "with scheduled event at %llu to %d\n", tick, pwr_state, 1787 powerEvent.when(), pwrStateTrans); 1788 } 1789} 1790 1791void 1792DRAMCtrl::Rank::processPowerEvent() 1793{ 1794 // remember where we were, and for how long 1795 Tick duration = curTick() - pwrStateTick; 1796 PowerState prev_state = pwrState; 1797 1798 // update the accounting 1799 pwrStateTime[prev_state] += duration; 1800 1801 pwrState = pwrStateTrans; 1802 pwrStateTick = curTick(); 1803 1804 if (pwrState == PWR_IDLE) { 1805 DPRINTF(DRAMState, "All banks precharged\n"); 1806 1807 // if we were refreshing, make sure we start scheduling requests again 1808 if (prev_state == PWR_REF) { 1809 DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration); 1810 assert(pwrState == PWR_IDLE); 1811 1812 // kick things into action again 1813 refreshState = REF_IDLE; 1814 // a request event could be already scheduled by the state 1815 // machine of the other rank 1816 if (!memory.nextReqEvent.scheduled()) 1817 schedule(memory.nextReqEvent, curTick()); 1818 } else { 1819 assert(prev_state == PWR_ACT); 1820 1821 // if we have a pending refresh, and are now moving to 1822 // the idle state, direclty transition to a refresh 1823 if (refreshState == REF_RUN) { 1824 // there should be nothing waiting at this point 1825 assert(!powerEvent.scheduled()); 1826 1827 // update the state in zero time and proceed below 1828 pwrState = PWR_REF; 1829 } 1830 } 1831 } 1832 1833 // we transition to the refresh state, let the refresh state 1834 // machine know of this state update and let it deal with the 1835 // scheduling of the next power state transition as well as the 1836 // following refresh 1837 if (pwrState == PWR_REF) { 1838 DPRINTF(DRAMState, "Refreshing\n"); 1839 // kick the refresh event loop into action again, and that 1840 // in turn will schedule a transition to the idle power 1841 // state once the refresh is done 1842 assert(refreshState == REF_RUN); 1843 processRefreshEvent(); 1844 } 1845} 1846 1847void 1848DRAMCtrl::Rank::updatePowerStats() 1849{ 1850 // Get the energy and power from DRAMPower 1851 Data::MemoryPowerModel::Energy energy = 1852 power.powerlib.getEnergy(); 1853 Data::MemoryPowerModel::Power rank_power = 1854 power.powerlib.getPower(); 1855 1856 actEnergy = energy.act_energy * memory.devicesPerRank; 1857 preEnergy = energy.pre_energy * memory.devicesPerRank; 1858 readEnergy = energy.read_energy * memory.devicesPerRank; 1859 writeEnergy = energy.write_energy * memory.devicesPerRank; 1860 refreshEnergy = energy.ref_energy * memory.devicesPerRank; 1861 actBackEnergy = energy.act_stdby_energy * memory.devicesPerRank; 1862 preBackEnergy = energy.pre_stdby_energy * memory.devicesPerRank; 1863 totalEnergy = energy.total_energy * memory.devicesPerRank; 1864 averagePower = rank_power.average_power * memory.devicesPerRank; 1865} 1866 1867void 1868DRAMCtrl::Rank::regStats() 1869{ 1870 using namespace Stats; 1871 1872 pwrStateTime 1873 .init(5) 1874 .name(name() + ".memoryStateTime") 1875 .desc("Time in different power states"); 1876 pwrStateTime.subname(0, "IDLE"); 1877 pwrStateTime.subname(1, "REF"); 1878 pwrStateTime.subname(2, "PRE_PDN"); 1879 pwrStateTime.subname(3, "ACT"); 1880 pwrStateTime.subname(4, "ACT_PDN"); 1881 1882 actEnergy 1883 .name(name() + ".actEnergy") 1884 .desc("Energy for activate commands per rank (pJ)"); 1885 1886 preEnergy 1887 .name(name() + ".preEnergy") 1888 .desc("Energy for precharge commands per rank (pJ)"); 1889 1890 readEnergy 1891 .name(name() + ".readEnergy") 1892 .desc("Energy for read commands per rank (pJ)"); 1893 1894 writeEnergy 1895 .name(name() + ".writeEnergy") 1896 .desc("Energy for write commands per rank (pJ)"); 1897 1898 refreshEnergy 1899 .name(name() + ".refreshEnergy") 1900 .desc("Energy for refresh commands per rank (pJ)"); 1901 1902 actBackEnergy 1903 .name(name() + ".actBackEnergy") 1904 .desc("Energy for active background per rank (pJ)"); 1905 1906 preBackEnergy 1907 .name(name() + ".preBackEnergy") 1908 .desc("Energy for precharge background per rank (pJ)"); 1909 1910 totalEnergy 1911 .name(name() + ".totalEnergy") 1912 .desc("Total energy per rank (pJ)"); 1913 1914 averagePower 1915 .name(name() + ".averagePower") 1916 .desc("Core power per rank (mW)"); 1917} 1918void 1919DRAMCtrl::regStats() 1920{ 1921 using namespace Stats; 1922 1923 AbstractMemory::regStats(); 1924 1925 for (auto r : ranks) { 1926 r->regStats(); 1927 } 1928 1929 readReqs 1930 .name(name() + ".readReqs") 1931 .desc("Number of read requests accepted"); 1932 1933 writeReqs 1934 .name(name() + ".writeReqs") 1935 .desc("Number of write requests accepted"); 1936 1937 readBursts 1938 .name(name() + ".readBursts") 1939 .desc("Number of DRAM read bursts, " 1940 "including those serviced by the write queue"); 1941 1942 writeBursts 1943 .name(name() + ".writeBursts") 1944 .desc("Number of DRAM write bursts, " 1945 "including those merged in the write queue"); 1946 1947 servicedByWrQ 1948 .name(name() + ".servicedByWrQ") 1949 .desc("Number of DRAM read bursts serviced by the write queue"); 1950 1951 mergedWrBursts 1952 .name(name() + ".mergedWrBursts") 1953 .desc("Number of DRAM write bursts merged with an existing one"); 1954 1955 neitherReadNorWrite 1956 .name(name() + ".neitherReadNorWriteReqs") 1957 .desc("Number of requests that are neither read nor write"); 1958 1959 perBankRdBursts 1960 .init(banksPerRank * ranksPerChannel) 1961 .name(name() + ".perBankRdBursts") 1962 .desc("Per bank write bursts"); 1963 1964 perBankWrBursts 1965 .init(banksPerRank * ranksPerChannel) 1966 .name(name() + ".perBankWrBursts") 1967 .desc("Per bank write bursts"); 1968 1969 avgRdQLen 1970 .name(name() + ".avgRdQLen") 1971 .desc("Average read queue length when enqueuing") 1972 .precision(2); 1973 1974 avgWrQLen 1975 .name(name() + ".avgWrQLen") 1976 .desc("Average write queue length when enqueuing") 1977 .precision(2); 1978 1979 totQLat 1980 .name(name() + ".totQLat") 1981 .desc("Total ticks spent queuing"); 1982 1983 totBusLat 1984 .name(name() + ".totBusLat") 1985 .desc("Total ticks spent in databus transfers"); 1986 1987 totMemAccLat 1988 .name(name() + ".totMemAccLat") 1989 .desc("Total ticks spent from burst creation until serviced " 1990 "by the DRAM"); 1991 1992 avgQLat 1993 .name(name() + ".avgQLat") 1994 .desc("Average queueing delay per DRAM burst") 1995 .precision(2); 1996 1997 avgQLat = totQLat / (readBursts - servicedByWrQ); 1998 1999 avgBusLat 2000 .name(name() + ".avgBusLat") 2001 .desc("Average bus latency per DRAM burst") 2002 .precision(2); 2003 2004 avgBusLat = totBusLat / (readBursts - servicedByWrQ); 2005 2006 avgMemAccLat 2007 .name(name() + ".avgMemAccLat") 2008 .desc("Average memory access latency per DRAM burst") 2009 .precision(2); 2010 2011 avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ); 2012 2013 numRdRetry 2014 .name(name() + ".numRdRetry") 2015 .desc("Number of times read queue was full causing retry"); 2016 2017 numWrRetry 2018 .name(name() + ".numWrRetry") 2019 .desc("Number of times write queue was full causing retry"); 2020 2021 readRowHits 2022 .name(name() + ".readRowHits") 2023 .desc("Number of row buffer hits during reads"); 2024 2025 writeRowHits 2026 .name(name() + ".writeRowHits") 2027 .desc("Number of row buffer hits during writes"); 2028 2029 readRowHitRate 2030 .name(name() + ".readRowHitRate") 2031 .desc("Row buffer hit rate for reads") 2032 .precision(2); 2033 2034 readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100; 2035 2036 writeRowHitRate 2037 .name(name() + ".writeRowHitRate") 2038 .desc("Row buffer hit rate for writes") 2039 .precision(2); 2040 2041 writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100; 2042 2043 readPktSize 2044 .init(ceilLog2(burstSize) + 1) 2045 .name(name() + ".readPktSize") 2046 .desc("Read request sizes (log2)"); 2047 2048 writePktSize 2049 .init(ceilLog2(burstSize) + 1) 2050 .name(name() + ".writePktSize") 2051 .desc("Write request sizes (log2)"); 2052 2053 rdQLenPdf 2054 .init(readBufferSize) 2055 .name(name() + ".rdQLenPdf") 2056 .desc("What read queue length does an incoming req see"); 2057 2058 wrQLenPdf 2059 .init(writeBufferSize) 2060 .name(name() + ".wrQLenPdf") 2061 .desc("What write queue length does an incoming req see"); 2062 2063 bytesPerActivate 2064 .init(maxAccessesPerRow) 2065 .name(name() + ".bytesPerActivate") 2066 .desc("Bytes accessed per row activation") 2067 .flags(nozero); 2068 2069 rdPerTurnAround 2070 .init(readBufferSize) 2071 .name(name() + ".rdPerTurnAround") 2072 .desc("Reads before turning the bus around for writes") 2073 .flags(nozero); 2074 2075 wrPerTurnAround 2076 .init(writeBufferSize) 2077 .name(name() + ".wrPerTurnAround") 2078 .desc("Writes before turning the bus around for reads") 2079 .flags(nozero); 2080 2081 bytesReadDRAM 2082 .name(name() + ".bytesReadDRAM") 2083 .desc("Total number of bytes read from DRAM"); 2084 2085 bytesReadWrQ 2086 .name(name() + ".bytesReadWrQ") 2087 .desc("Total number of bytes read from write queue"); 2088 2089 bytesWritten 2090 .name(name() + ".bytesWritten") 2091 .desc("Total number of bytes written to DRAM"); 2092 2093 bytesReadSys 2094 .name(name() + ".bytesReadSys") 2095 .desc("Total read bytes from the system interface side"); 2096 2097 bytesWrittenSys 2098 .name(name() + ".bytesWrittenSys") 2099 .desc("Total written bytes from the system interface side"); 2100 2101 avgRdBW 2102 .name(name() + ".avgRdBW") 2103 .desc("Average DRAM read bandwidth in MiByte/s") 2104 .precision(2); 2105 2106 avgRdBW = (bytesReadDRAM / 1000000) / simSeconds; 2107 2108 avgWrBW 2109 .name(name() + ".avgWrBW") 2110 .desc("Average achieved write bandwidth in MiByte/s") 2111 .precision(2); 2112 2113 avgWrBW = (bytesWritten / 1000000) / simSeconds; 2114 2115 avgRdBWSys 2116 .name(name() + ".avgRdBWSys") 2117 .desc("Average system read bandwidth in MiByte/s") 2118 .precision(2); 2119 2120 avgRdBWSys = (bytesReadSys / 1000000) / simSeconds; 2121 2122 avgWrBWSys 2123 .name(name() + ".avgWrBWSys") 2124 .desc("Average system write bandwidth in MiByte/s") 2125 .precision(2); 2126 2127 avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds; 2128 2129 peakBW 2130 .name(name() + ".peakBW") 2131 .desc("Theoretical peak bandwidth in MiByte/s") 2132 .precision(2); 2133 2134 peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000; 2135 2136 busUtil 2137 .name(name() + ".busUtil") 2138 .desc("Data bus utilization in percentage") 2139 .precision(2); 2140 busUtil = (avgRdBW + avgWrBW) / peakBW * 100; 2141 2142 totGap 2143 .name(name() + ".totGap") 2144 .desc("Total gap between requests"); 2145 2146 avgGap 2147 .name(name() + ".avgGap") 2148 .desc("Average gap between requests") 2149 .precision(2); 2150 2151 avgGap = totGap / (readReqs + writeReqs); 2152 2153 // Stats for DRAM Power calculation based on Micron datasheet 2154 busUtilRead 2155 .name(name() + ".busUtilRead") 2156 .desc("Data bus utilization in percentage for reads") 2157 .precision(2); 2158 2159 busUtilRead = avgRdBW / peakBW * 100; 2160 2161 busUtilWrite 2162 .name(name() + ".busUtilWrite") 2163 .desc("Data bus utilization in percentage for writes") 2164 .precision(2); 2165 2166 busUtilWrite = avgWrBW / peakBW * 100; 2167 2168 pageHitRate 2169 .name(name() + ".pageHitRate") 2170 .desc("Row buffer hit rate, read and write combined") 2171 .precision(2); 2172 2173 pageHitRate = (writeRowHits + readRowHits) / 2174 (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100; 2175} 2176 2177void 2178DRAMCtrl::recvFunctional(PacketPtr pkt) 2179{ 2180 // rely on the abstract memory 2181 functionalAccess(pkt); 2182} 2183 2184BaseSlavePort& 2185DRAMCtrl::getSlavePort(const string &if_name, PortID idx) 2186{ 2187 if (if_name != "port") { 2188 return MemObject::getSlavePort(if_name, idx); 2189 } else { 2190 return port; 2191 } 2192} 2193 2194unsigned int 2195DRAMCtrl::drain(DrainManager *dm) 2196{ 2197 unsigned int count = port.drain(dm); 2198 2199 // if there is anything in any of our internal queues, keep track 2200 // of that as well 2201 if (!(writeQueue.empty() && readQueue.empty() && 2202 respQueue.empty())) { 2203 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d," 2204 " resp: %d\n", writeQueue.size(), readQueue.size(), 2205 respQueue.size()); 2206 ++count; 2207 drainManager = dm; 2208 2209 // the only part that is not drained automatically over time 2210 // is the write queue, thus kick things into action if needed 2211 if (!writeQueue.empty() && !nextReqEvent.scheduled()) { 2212 schedule(nextReqEvent, curTick()); 2213 } 2214 } 2215 2216 if (count) 2217 setDrainState(Drainable::Draining); 2218 else 2219 setDrainState(Drainable::Drained); 2220 return count; 2221} 2222 2223void 2224DRAMCtrl::drainResume() 2225{ 2226 if (!isTimingMode && system()->isTimingMode()) { 2227 // if we switched to timing mode, kick things into action, 2228 // and behave as if we restored from a checkpoint 2229 startup(); 2230 } else if (isTimingMode && !system()->isTimingMode()) { 2231 // if we switch from timing mode, stop the refresh events to 2232 // not cause issues with KVM 2233 for (auto r : ranks) { 2234 r->suspend(); 2235 } 2236 } 2237 2238 // update the mode 2239 isTimingMode = system()->isTimingMode(); 2240} 2241 2242DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory) 2243 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this), 2244 memory(_memory) 2245{ } 2246 2247AddrRangeList 2248DRAMCtrl::MemoryPort::getAddrRanges() const 2249{ 2250 AddrRangeList ranges; 2251 ranges.push_back(memory.getAddrRange()); 2252 return ranges; 2253} 2254 2255void 2256DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt) 2257{ 2258 pkt->pushLabel(memory.name()); 2259 2260 if (!queue.checkFunctional(pkt)) { 2261 // Default implementation of SimpleTimingPort::recvFunctional() 2262 // calls recvAtomic() and throws away the latency; we can save a 2263 // little here by just not calculating the latency. 2264 memory.recvFunctional(pkt); 2265 } 2266 2267 pkt->popLabel(); 2268} 2269 2270Tick 2271DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt) 2272{ 2273 return memory.recvAtomic(pkt); 2274} 2275 2276bool 2277DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt) 2278{ 2279 // pass it to the memory controller 2280 return memory.recvTimingReq(pkt); 2281} 2282 2283DRAMCtrl* 2284DRAMCtrlParams::create() 2285{ 2286 return new DRAMCtrl(this); 2287} 2288