dram_ctrl.cc revision 10214:39eb5d4c400a
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 */ 44 45#include "base/bitfield.hh" 46#include "base/trace.hh" 47#include "debug/DRAM.hh" 48#include "debug/DRAMState.hh" 49#include "debug/Drain.hh" 50#include "mem/dram_ctrl.hh" 51#include "sim/system.hh" 52 53using namespace std; 54 55DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) : 56 AbstractMemory(p), 57 port(name() + ".port", *this), 58 retryRdReq(false), retryWrReq(false), 59 busState(READ), 60 nextReqEvent(this), respondEvent(this), activateEvent(this), 61 prechargeEvent(this), refreshEvent(this), powerEvent(this), 62 drainManager(NULL), 63 deviceBusWidth(p->device_bus_width), burstLength(p->burst_length), 64 deviceRowBufferSize(p->device_rowbuffer_size), 65 devicesPerRank(p->devices_per_rank), 66 burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8), 67 rowBufferSize(devicesPerRank * deviceRowBufferSize), 68 columnsPerRowBuffer(rowBufferSize / burstSize), 69 ranksPerChannel(p->ranks_per_channel), 70 banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0), 71 readBufferSize(p->read_buffer_size), 72 writeBufferSize(p->write_buffer_size), 73 writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0), 74 writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0), 75 minWritesPerSwitch(p->min_writes_per_switch), 76 writesThisTime(0), readsThisTime(0), 77 tWTR(p->tWTR), tRTW(p->tRTW), tBURST(p->tBURST), 78 tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS), tWR(p->tWR), 79 tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD), 80 tXAW(p->tXAW), activationLimit(p->activation_limit), 81 memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping), 82 pageMgmt(p->page_policy), 83 maxAccessesPerRow(p->max_accesses_per_row), 84 frontendLatency(p->static_frontend_latency), 85 backendLatency(p->static_backend_latency), 86 busBusyUntil(0), refreshDueAt(0), refreshState(REF_IDLE), 87 pwrStateTrans(PWR_IDLE), pwrState(PWR_IDLE), prevArrival(0), 88 nextReqTime(0), pwrStateTick(0), numBanksActive(0) 89{ 90 // create the bank states based on the dimensions of the ranks and 91 // banks 92 banks.resize(ranksPerChannel); 93 actTicks.resize(ranksPerChannel); 94 for (size_t c = 0; c < ranksPerChannel; ++c) { 95 banks[c].resize(banksPerRank); 96 actTicks[c].resize(activationLimit, 0); 97 } 98 99 // perform a basic check of the write thresholds 100 if (p->write_low_thresh_perc >= p->write_high_thresh_perc) 101 fatal("Write buffer low threshold %d must be smaller than the " 102 "high threshold %d\n", p->write_low_thresh_perc, 103 p->write_high_thresh_perc); 104 105 // determine the rows per bank by looking at the total capacity 106 uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size()); 107 108 DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity, 109 AbstractMemory::size()); 110 111 DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n", 112 rowBufferSize, columnsPerRowBuffer); 113 114 rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel); 115 116 if (range.interleaved()) { 117 if (channels != range.stripes()) 118 fatal("%s has %d interleaved address stripes but %d channel(s)\n", 119 name(), range.stripes(), channels); 120 121 if (addrMapping == Enums::RoRaBaChCo) { 122 if (rowBufferSize != range.granularity()) { 123 fatal("Interleaving of %s doesn't match RoRaBaChCo " 124 "address map\n", name()); 125 } 126 } else if (addrMapping == Enums::RoRaBaCoCh) { 127 if (system()->cacheLineSize() != range.granularity()) { 128 fatal("Interleaving of %s doesn't match RoRaBaCoCh " 129 "address map\n", name()); 130 } 131 } else if (addrMapping == Enums::RoCoRaBaCh) { 132 if (system()->cacheLineSize() != range.granularity()) 133 fatal("Interleaving of %s doesn't match RoCoRaBaCh " 134 "address map\n", name()); 135 } 136 } 137 138 // some basic sanity checks 139 if (tREFI <= tRP || tREFI <= tRFC) { 140 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n", 141 tREFI, tRP, tRFC); 142 } 143} 144 145void 146DRAMCtrl::init() 147{ 148 if (!port.isConnected()) { 149 fatal("DRAMCtrl %s is unconnected!\n", name()); 150 } else { 151 port.sendRangeChange(); 152 } 153} 154 155void 156DRAMCtrl::startup() 157{ 158 // update the start tick for the precharge accounting to the 159 // current tick 160 pwrStateTick = curTick(); 161 162 // shift the bus busy time sufficiently far ahead that we never 163 // have to worry about negative values when computing the time for 164 // the next request, this will add an insignificant bubble at the 165 // start of simulation 166 busBusyUntil = curTick() + tRP + tRCD + tCL; 167 168 // kick off the refresh, and give ourselves enough time to 169 // precharge 170 schedule(refreshEvent, curTick() + tREFI - tRP); 171} 172 173Tick 174DRAMCtrl::recvAtomic(PacketPtr pkt) 175{ 176 DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr()); 177 178 // do the actual memory access and turn the packet into a response 179 access(pkt); 180 181 Tick latency = 0; 182 if (!pkt->memInhibitAsserted() && pkt->hasData()) { 183 // this value is not supposed to be accurate, just enough to 184 // keep things going, mimic a closed page 185 latency = tRP + tRCD + tCL; 186 } 187 return latency; 188} 189 190bool 191DRAMCtrl::readQueueFull(unsigned int neededEntries) const 192{ 193 DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n", 194 readBufferSize, readQueue.size() + respQueue.size(), 195 neededEntries); 196 197 return 198 (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize; 199} 200 201bool 202DRAMCtrl::writeQueueFull(unsigned int neededEntries) const 203{ 204 DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n", 205 writeBufferSize, writeQueue.size(), neededEntries); 206 return (writeQueue.size() + neededEntries) > writeBufferSize; 207} 208 209DRAMCtrl::DRAMPacket* 210DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size, 211 bool isRead) 212{ 213 // decode the address based on the address mapping scheme, with 214 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and 215 // channel, respectively 216 uint8_t rank; 217 uint8_t bank; 218 uint16_t row; 219 220 // truncate the address to the access granularity 221 Addr addr = dramPktAddr / burstSize; 222 223 // we have removed the lowest order address bits that denote the 224 // position within the column 225 if (addrMapping == Enums::RoRaBaChCo) { 226 // the lowest order bits denote the column to ensure that 227 // sequential cache lines occupy the same row 228 addr = addr / columnsPerRowBuffer; 229 230 // take out the channel part of the address 231 addr = addr / channels; 232 233 // after the channel bits, get the bank bits to interleave 234 // over the banks 235 bank = addr % banksPerRank; 236 addr = addr / banksPerRank; 237 238 // after the bank, we get the rank bits which thus interleaves 239 // over the ranks 240 rank = addr % ranksPerChannel; 241 addr = addr / ranksPerChannel; 242 243 // lastly, get the row bits 244 row = addr % rowsPerBank; 245 addr = addr / rowsPerBank; 246 } else if (addrMapping == Enums::RoRaBaCoCh) { 247 // take out the channel part of the address 248 addr = addr / channels; 249 250 // next, the column 251 addr = addr / columnsPerRowBuffer; 252 253 // after the column bits, we get the bank bits to interleave 254 // over the banks 255 bank = addr % banksPerRank; 256 addr = addr / banksPerRank; 257 258 // after the bank, we get the rank bits which thus interleaves 259 // over the ranks 260 rank = addr % ranksPerChannel; 261 addr = addr / ranksPerChannel; 262 263 // lastly, get the row bits 264 row = addr % rowsPerBank; 265 addr = addr / rowsPerBank; 266 } else if (addrMapping == Enums::RoCoRaBaCh) { 267 // optimise for closed page mode and utilise maximum 268 // parallelism of the DRAM (at the cost of power) 269 270 // take out the channel part of the address, not that this has 271 // to match with how accesses are interleaved between the 272 // controllers in the address mapping 273 addr = addr / channels; 274 275 // start with the bank bits, as this provides the maximum 276 // opportunity for parallelism between requests 277 bank = addr % banksPerRank; 278 addr = addr / banksPerRank; 279 280 // next get the rank bits 281 rank = addr % ranksPerChannel; 282 addr = addr / ranksPerChannel; 283 284 // next the column bits which we do not need to keep track of 285 // and simply skip past 286 addr = addr / columnsPerRowBuffer; 287 288 // lastly, get the row bits 289 row = addr % rowsPerBank; 290 addr = addr / rowsPerBank; 291 } else 292 panic("Unknown address mapping policy chosen!"); 293 294 assert(rank < ranksPerChannel); 295 assert(bank < banksPerRank); 296 assert(row < rowsPerBank); 297 298 DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n", 299 dramPktAddr, rank, bank, row); 300 301 // create the corresponding DRAM packet with the entry time and 302 // ready time set to the current tick, the latter will be updated 303 // later 304 uint16_t bank_id = banksPerRank * rank + bank; 305 return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr, 306 size, banks[rank][bank]); 307} 308 309void 310DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount) 311{ 312 // only add to the read queue here. whenever the request is 313 // eventually done, set the readyTime, and call schedule() 314 assert(!pkt->isWrite()); 315 316 assert(pktCount != 0); 317 318 // if the request size is larger than burst size, the pkt is split into 319 // multiple DRAM packets 320 // Note if the pkt starting address is not aligened to burst size, the 321 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets 322 // are aligned to burst size boundaries. This is to ensure we accurately 323 // check read packets against packets in write queue. 324 Addr addr = pkt->getAddr(); 325 unsigned pktsServicedByWrQ = 0; 326 BurstHelper* burst_helper = NULL; 327 for (int cnt = 0; cnt < pktCount; ++cnt) { 328 unsigned size = std::min((addr | (burstSize - 1)) + 1, 329 pkt->getAddr() + pkt->getSize()) - addr; 330 readPktSize[ceilLog2(size)]++; 331 readBursts++; 332 333 // First check write buffer to see if the data is already at 334 // the controller 335 bool foundInWrQ = false; 336 for (auto i = writeQueue.begin(); i != writeQueue.end(); ++i) { 337 // check if the read is subsumed in the write entry we are 338 // looking at 339 if ((*i)->addr <= addr && 340 (addr + size) <= ((*i)->addr + (*i)->size)) { 341 foundInWrQ = true; 342 servicedByWrQ++; 343 pktsServicedByWrQ++; 344 DPRINTF(DRAM, "Read to addr %lld with size %d serviced by " 345 "write queue\n", addr, size); 346 bytesReadWrQ += burstSize; 347 break; 348 } 349 } 350 351 // If not found in the write q, make a DRAM packet and 352 // push it onto the read queue 353 if (!foundInWrQ) { 354 355 // Make the burst helper for split packets 356 if (pktCount > 1 && burst_helper == NULL) { 357 DPRINTF(DRAM, "Read to addr %lld translates to %d " 358 "dram requests\n", pkt->getAddr(), pktCount); 359 burst_helper = new BurstHelper(pktCount); 360 } 361 362 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true); 363 dram_pkt->burstHelper = burst_helper; 364 365 assert(!readQueueFull(1)); 366 rdQLenPdf[readQueue.size() + respQueue.size()]++; 367 368 DPRINTF(DRAM, "Adding to read queue\n"); 369 370 readQueue.push_back(dram_pkt); 371 372 // Update stats 373 avgRdQLen = readQueue.size() + respQueue.size(); 374 } 375 376 // Starting address of next dram pkt (aligend to burstSize boundary) 377 addr = (addr | (burstSize - 1)) + 1; 378 } 379 380 // If all packets are serviced by write queue, we send the repsonse back 381 if (pktsServicedByWrQ == pktCount) { 382 accessAndRespond(pkt, frontendLatency); 383 return; 384 } 385 386 // Update how many split packets are serviced by write queue 387 if (burst_helper != NULL) 388 burst_helper->burstsServiced = pktsServicedByWrQ; 389 390 // If we are not already scheduled to get a request out of the 391 // queue, do so now 392 if (!nextReqEvent.scheduled()) { 393 DPRINTF(DRAM, "Request scheduled immediately\n"); 394 schedule(nextReqEvent, curTick()); 395 } 396} 397 398void 399DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount) 400{ 401 // only add to the write queue here. whenever the request is 402 // eventually done, set the readyTime, and call schedule() 403 assert(pkt->isWrite()); 404 405 // if the request size is larger than burst size, the pkt is split into 406 // multiple DRAM packets 407 Addr addr = pkt->getAddr(); 408 for (int cnt = 0; cnt < pktCount; ++cnt) { 409 unsigned size = std::min((addr | (burstSize - 1)) + 1, 410 pkt->getAddr() + pkt->getSize()) - addr; 411 writePktSize[ceilLog2(size)]++; 412 writeBursts++; 413 414 // see if we can merge with an existing item in the write 415 // queue and keep track of whether we have merged or not so we 416 // can stop at that point and also avoid enqueueing a new 417 // request 418 bool merged = false; 419 auto w = writeQueue.begin(); 420 421 while(!merged && w != writeQueue.end()) { 422 // either of the two could be first, if they are the same 423 // it does not matter which way we go 424 if ((*w)->addr >= addr) { 425 // the existing one starts after the new one, figure 426 // out where the new one ends with respect to the 427 // existing one 428 if ((addr + size) >= ((*w)->addr + (*w)->size)) { 429 // check if the existing one is completely 430 // subsumed in the new one 431 DPRINTF(DRAM, "Merging write covering existing burst\n"); 432 merged = true; 433 // update both the address and the size 434 (*w)->addr = addr; 435 (*w)->size = size; 436 } else if ((addr + size) >= (*w)->addr && 437 ((*w)->addr + (*w)->size - addr) <= burstSize) { 438 // the new one is just before or partially 439 // overlapping with the existing one, and together 440 // they fit within a burst 441 DPRINTF(DRAM, "Merging write before existing burst\n"); 442 merged = true; 443 // the existing queue item needs to be adjusted with 444 // respect to both address and size 445 (*w)->size = (*w)->addr + (*w)->size - addr; 446 (*w)->addr = addr; 447 } 448 } else { 449 // the new one starts after the current one, figure 450 // out where the existing one ends with respect to the 451 // new one 452 if (((*w)->addr + (*w)->size) >= (addr + size)) { 453 // check if the new one is completely subsumed in the 454 // existing one 455 DPRINTF(DRAM, "Merging write into existing burst\n"); 456 merged = true; 457 // no adjustments necessary 458 } else if (((*w)->addr + (*w)->size) >= addr && 459 (addr + size - (*w)->addr) <= burstSize) { 460 // the existing one is just before or partially 461 // overlapping with the new one, and together 462 // they fit within a burst 463 DPRINTF(DRAM, "Merging write after existing burst\n"); 464 merged = true; 465 // the address is right, and only the size has 466 // to be adjusted 467 (*w)->size = addr + size - (*w)->addr; 468 } 469 } 470 ++w; 471 } 472 473 // if the item was not merged we need to create a new write 474 // and enqueue it 475 if (!merged) { 476 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false); 477 478 assert(writeQueue.size() < writeBufferSize); 479 wrQLenPdf[writeQueue.size()]++; 480 481 DPRINTF(DRAM, "Adding to write queue\n"); 482 483 writeQueue.push_back(dram_pkt); 484 485 // Update stats 486 avgWrQLen = writeQueue.size(); 487 } else { 488 // keep track of the fact that this burst effectively 489 // disappeared as it was merged with an existing one 490 mergedWrBursts++; 491 } 492 493 // Starting address of next dram pkt (aligend to burstSize boundary) 494 addr = (addr | (burstSize - 1)) + 1; 495 } 496 497 // we do not wait for the writes to be send to the actual memory, 498 // but instead take responsibility for the consistency here and 499 // snoop the write queue for any upcoming reads 500 // @todo, if a pkt size is larger than burst size, we might need a 501 // different front end latency 502 accessAndRespond(pkt, frontendLatency); 503 504 // If we are not already scheduled to get a request out of the 505 // queue, do so now 506 if (!nextReqEvent.scheduled()) { 507 DPRINTF(DRAM, "Request scheduled immediately\n"); 508 schedule(nextReqEvent, curTick()); 509 } 510} 511 512void 513DRAMCtrl::printQs() const { 514 DPRINTF(DRAM, "===READ QUEUE===\n\n"); 515 for (auto i = readQueue.begin() ; i != readQueue.end() ; ++i) { 516 DPRINTF(DRAM, "Read %lu\n", (*i)->addr); 517 } 518 DPRINTF(DRAM, "\n===RESP QUEUE===\n\n"); 519 for (auto i = respQueue.begin() ; i != respQueue.end() ; ++i) { 520 DPRINTF(DRAM, "Response %lu\n", (*i)->addr); 521 } 522 DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n"); 523 for (auto i = writeQueue.begin() ; i != writeQueue.end() ; ++i) { 524 DPRINTF(DRAM, "Write %lu\n", (*i)->addr); 525 } 526} 527 528bool 529DRAMCtrl::recvTimingReq(PacketPtr pkt) 530{ 531 /// @todo temporary hack to deal with memory corruption issues until 532 /// 4-phase transactions are complete 533 for (int x = 0; x < pendingDelete.size(); x++) 534 delete pendingDelete[x]; 535 pendingDelete.clear(); 536 537 // This is where we enter from the outside world 538 DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n", 539 pkt->cmdString(), pkt->getAddr(), pkt->getSize()); 540 541 // simply drop inhibited packets for now 542 if (pkt->memInhibitAsserted()) { 543 DPRINTF(DRAM, "Inhibited packet -- Dropping it now\n"); 544 pendingDelete.push_back(pkt); 545 return true; 546 } 547 548 // Calc avg gap between requests 549 if (prevArrival != 0) { 550 totGap += curTick() - prevArrival; 551 } 552 prevArrival = curTick(); 553 554 555 // Find out how many dram packets a pkt translates to 556 // If the burst size is equal or larger than the pkt size, then a pkt 557 // translates to only one dram packet. Otherwise, a pkt translates to 558 // multiple dram packets 559 unsigned size = pkt->getSize(); 560 unsigned offset = pkt->getAddr() & (burstSize - 1); 561 unsigned int dram_pkt_count = divCeil(offset + size, burstSize); 562 563 // check local buffers and do not accept if full 564 if (pkt->isRead()) { 565 assert(size != 0); 566 if (readQueueFull(dram_pkt_count)) { 567 DPRINTF(DRAM, "Read queue full, not accepting\n"); 568 // remember that we have to retry this port 569 retryRdReq = true; 570 numRdRetry++; 571 return false; 572 } else { 573 addToReadQueue(pkt, dram_pkt_count); 574 readReqs++; 575 bytesReadSys += size; 576 } 577 } else if (pkt->isWrite()) { 578 assert(size != 0); 579 if (writeQueueFull(dram_pkt_count)) { 580 DPRINTF(DRAM, "Write queue full, not accepting\n"); 581 // remember that we have to retry this port 582 retryWrReq = true; 583 numWrRetry++; 584 return false; 585 } else { 586 addToWriteQueue(pkt, dram_pkt_count); 587 writeReqs++; 588 bytesWrittenSys += size; 589 } 590 } else { 591 DPRINTF(DRAM,"Neither read nor write, ignore timing\n"); 592 neitherReadNorWrite++; 593 accessAndRespond(pkt, 1); 594 } 595 596 return true; 597} 598 599void 600DRAMCtrl::processRespondEvent() 601{ 602 DPRINTF(DRAM, 603 "processRespondEvent(): Some req has reached its readyTime\n"); 604 605 DRAMPacket* dram_pkt = respQueue.front(); 606 607 if (dram_pkt->burstHelper) { 608 // it is a split packet 609 dram_pkt->burstHelper->burstsServiced++; 610 if (dram_pkt->burstHelper->burstsServiced == 611 dram_pkt->burstHelper->burstCount) { 612 // we have now serviced all children packets of a system packet 613 // so we can now respond to the requester 614 // @todo we probably want to have a different front end and back 615 // end latency for split packets 616 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency); 617 delete dram_pkt->burstHelper; 618 dram_pkt->burstHelper = NULL; 619 } 620 } else { 621 // it is not a split packet 622 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency); 623 } 624 625 delete respQueue.front(); 626 respQueue.pop_front(); 627 628 if (!respQueue.empty()) { 629 assert(respQueue.front()->readyTime >= curTick()); 630 assert(!respondEvent.scheduled()); 631 schedule(respondEvent, respQueue.front()->readyTime); 632 } else { 633 // if there is nothing left in any queue, signal a drain 634 if (writeQueue.empty() && readQueue.empty() && 635 drainManager) { 636 drainManager->signalDrainDone(); 637 drainManager = NULL; 638 } 639 } 640 641 // We have made a location in the queue available at this point, 642 // so if there is a read that was forced to wait, retry now 643 if (retryRdReq) { 644 retryRdReq = false; 645 port.sendRetry(); 646 } 647} 648 649void 650DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue) 651{ 652 // This method does the arbitration between requests. The chosen 653 // packet is simply moved to the head of the queue. The other 654 // methods know that this is the place to look. For example, with 655 // FCFS, this method does nothing 656 assert(!queue.empty()); 657 658 if (queue.size() == 1) { 659 DPRINTF(DRAM, "Single request, nothing to do\n"); 660 return; 661 } 662 663 if (memSchedPolicy == Enums::fcfs) { 664 // Do nothing, since the correct request is already head 665 } else if (memSchedPolicy == Enums::frfcfs) { 666 reorderQueue(queue); 667 } else 668 panic("No scheduling policy chosen\n"); 669} 670 671void 672DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue) 673{ 674 // Only determine this when needed 675 uint64_t earliest_banks = 0; 676 677 // Search for row hits first, if no row hit is found then schedule the 678 // packet to one of the earliest banks available 679 bool found_earliest_pkt = false; 680 auto selected_pkt_it = queue.begin(); 681 682 for (auto i = queue.begin(); i != queue.end() ; ++i) { 683 DRAMPacket* dram_pkt = *i; 684 const Bank& bank = dram_pkt->bankRef; 685 // Check if it is a row hit 686 if (bank.openRow == dram_pkt->row) { 687 // FCFS within the hits 688 DPRINTF(DRAM, "Row buffer hit\n"); 689 selected_pkt_it = i; 690 break; 691 } else if (!found_earliest_pkt) { 692 // No row hit, go for first ready 693 if (earliest_banks == 0) 694 earliest_banks = minBankActAt(queue); 695 696 // simplistic approximation of when the bank can issue an 697 // activate, this is calculated in minBankActAt and could 698 // be cached 699 Tick act_at = bank.openRow == Bank::NO_ROW ? 700 bank.actAllowedAt : 701 std::max(bank.preAllowedAt, curTick()) + tRP; 702 703 // Bank is ready or is the first available bank 704 if (act_at <= curTick() || 705 bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) { 706 // Remember the packet to be scheduled to one of the earliest 707 // banks available, FCFS amongst the earliest banks 708 selected_pkt_it = i; 709 found_earliest_pkt = true; 710 } 711 } 712 } 713 714 DRAMPacket* selected_pkt = *selected_pkt_it; 715 queue.erase(selected_pkt_it); 716 queue.push_front(selected_pkt); 717} 718 719void 720DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency) 721{ 722 DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr()); 723 724 bool needsResponse = pkt->needsResponse(); 725 // do the actual memory access which also turns the packet into a 726 // response 727 access(pkt); 728 729 // turn packet around to go back to requester if response expected 730 if (needsResponse) { 731 // access already turned the packet into a response 732 assert(pkt->isResponse()); 733 734 // @todo someone should pay for this 735 pkt->busFirstWordDelay = pkt->busLastWordDelay = 0; 736 737 // queue the packet in the response queue to be sent out after 738 // the static latency has passed 739 port.schedTimingResp(pkt, curTick() + static_latency); 740 } else { 741 // @todo the packet is going to be deleted, and the DRAMPacket 742 // is still having a pointer to it 743 pendingDelete.push_back(pkt); 744 } 745 746 DPRINTF(DRAM, "Done\n"); 747 748 return; 749} 750 751void 752DRAMCtrl::activateBank(Tick act_tick, uint8_t rank, uint8_t bank, 753 uint16_t row, Bank& bank_ref) 754{ 755 assert(0 <= rank && rank < ranksPerChannel); 756 assert(actTicks[rank].size() == activationLimit); 757 758 DPRINTF(DRAM, "Activate at tick %d\n", act_tick); 759 760 // update the open row 761 assert(bank_ref.openRow == Bank::NO_ROW); 762 bank_ref.openRow = row; 763 764 // start counting anew, this covers both the case when we 765 // auto-precharged, and when this access is forced to 766 // precharge 767 bank_ref.bytesAccessed = 0; 768 bank_ref.rowAccesses = 0; 769 770 ++numBanksActive; 771 assert(numBanksActive <= banksPerRank * ranksPerChannel); 772 773 DPRINTF(DRAM, "Activate bank at tick %lld, now got %d active\n", 774 act_tick, numBanksActive); 775 776 // The next access has to respect tRAS for this bank 777 bank_ref.preAllowedAt = act_tick + tRAS; 778 779 // Respect the row-to-column command delay 780 bank_ref.colAllowedAt = act_tick + tRCD; 781 782 // start by enforcing tRRD 783 for(int i = 0; i < banksPerRank; i++) { 784 // next activate to any bank in this rank must not happen 785 // before tRRD 786 banks[rank][i].actAllowedAt = std::max(act_tick + tRRD, 787 banks[rank][i].actAllowedAt); 788 } 789 790 // next, we deal with tXAW, if the activation limit is disabled 791 // then we are done 792 if (actTicks[rank].empty()) 793 return; 794 795 // sanity check 796 if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) { 797 panic("Got %d activates in window %d (%llu - %llu) which is smaller " 798 "than %llu\n", activationLimit, act_tick - actTicks[rank].back(), 799 act_tick, actTicks[rank].back(), tXAW); 800 } 801 802 // shift the times used for the book keeping, the last element 803 // (highest index) is the oldest one and hence the lowest value 804 actTicks[rank].pop_back(); 805 806 // record an new activation (in the future) 807 actTicks[rank].push_front(act_tick); 808 809 // cannot activate more than X times in time window tXAW, push the 810 // next one (the X + 1'st activate) to be tXAW away from the 811 // oldest in our window of X 812 if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) { 813 DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate no earlier " 814 "than %llu\n", activationLimit, actTicks[rank].back() + tXAW); 815 for(int j = 0; j < banksPerRank; j++) 816 // next activate must not happen before end of window 817 banks[rank][j].actAllowedAt = 818 std::max(actTicks[rank].back() + tXAW, 819 banks[rank][j].actAllowedAt); 820 } 821 822 // at the point when this activate takes place, make sure we 823 // transition to the active power state 824 if (!activateEvent.scheduled()) 825 schedule(activateEvent, act_tick); 826 else if (activateEvent.when() > act_tick) 827 // move it sooner in time 828 reschedule(activateEvent, act_tick); 829} 830 831void 832DRAMCtrl::processActivateEvent() 833{ 834 // we should transition to the active state as soon as any bank is active 835 if (pwrState != PWR_ACT) 836 // note that at this point numBanksActive could be back at 837 // zero again due to a precharge scheduled in the future 838 schedulePowerEvent(PWR_ACT, curTick()); 839} 840 841void 842DRAMCtrl::prechargeBank(Bank& bank, Tick pre_at) 843{ 844 // make sure the bank has an open row 845 assert(bank.openRow != Bank::NO_ROW); 846 847 // sample the bytes per activate here since we are closing 848 // the page 849 bytesPerActivate.sample(bank.bytesAccessed); 850 851 bank.openRow = Bank::NO_ROW; 852 853 // no precharge allowed before this one 854 bank.preAllowedAt = pre_at; 855 856 Tick pre_done_at = pre_at + tRP; 857 858 bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at); 859 860 assert(numBanksActive != 0); 861 --numBanksActive; 862 863 DPRINTF(DRAM, "Precharging bank at tick %lld, now got %d active\n", 864 pre_at, numBanksActive); 865 866 // if we look at the current number of active banks we might be 867 // tempted to think the DRAM is now idle, however this can be 868 // undone by an activate that is scheduled to happen before we 869 // would have reached the idle state, so schedule an event and 870 // rather check once we actually make it to the point in time when 871 // the (last) precharge takes place 872 if (!prechargeEvent.scheduled()) 873 schedule(prechargeEvent, pre_done_at); 874 else if (prechargeEvent.when() < pre_done_at) 875 reschedule(prechargeEvent, pre_done_at); 876} 877 878void 879DRAMCtrl::processPrechargeEvent() 880{ 881 // if we reached zero, then special conditions apply as we track 882 // if all banks are precharged for the power models 883 if (numBanksActive == 0) { 884 // we should transition to the idle state when the last bank 885 // is precharged 886 schedulePowerEvent(PWR_IDLE, curTick()); 887 } 888} 889 890void 891DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt) 892{ 893 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n", 894 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row); 895 896 // get the bank 897 Bank& bank = dram_pkt->bankRef; 898 899 // for the state we need to track if it is a row hit or not 900 bool row_hit = true; 901 902 // respect any constraints on the command (e.g. tRCD or tCCD) 903 Tick cmd_at = std::max(bank.colAllowedAt, curTick()); 904 905 // Determine the access latency and update the bank state 906 if (bank.openRow == dram_pkt->row) { 907 // nothing to do 908 } else { 909 row_hit = false; 910 911 // If there is a page open, precharge it. 912 if (bank.openRow != Bank::NO_ROW) { 913 prechargeBank(bank, std::max(bank.preAllowedAt, curTick())); 914 } 915 916 // next we need to account for the delay in activating the 917 // page 918 Tick act_tick = std::max(bank.actAllowedAt, curTick()); 919 920 // Record the activation and deal with all the global timing 921 // constraints caused be a new activation (tRRD and tXAW) 922 activateBank(act_tick, dram_pkt->rank, dram_pkt->bank, 923 dram_pkt->row, bank); 924 925 // issue the command as early as possible 926 cmd_at = bank.colAllowedAt; 927 } 928 929 // we need to wait until the bus is available before we can issue 930 // the command 931 cmd_at = std::max(cmd_at, busBusyUntil - tCL); 932 933 // update the packet ready time 934 dram_pkt->readyTime = cmd_at + tCL + tBURST; 935 936 // only one burst can use the bus at any one point in time 937 assert(dram_pkt->readyTime - busBusyUntil >= tBURST); 938 939 // not strictly necessary, but update the time for the next 940 // read/write (add a max with tCCD here) 941 bank.colAllowedAt = cmd_at + tBURST; 942 943 // If this is a write, we also need to respect the write recovery 944 // time before a precharge, in the case of a read, respect the 945 // read to precharge constraint 946 bank.preAllowedAt = std::max(bank.preAllowedAt, 947 dram_pkt->isRead ? cmd_at + tRTP : 948 dram_pkt->readyTime + tWR); 949 950 // increment the bytes accessed and the accesses per row 951 bank.bytesAccessed += burstSize; 952 ++bank.rowAccesses; 953 954 // if we reached the max, then issue with an auto-precharge 955 bool auto_precharge = pageMgmt == Enums::close || 956 bank.rowAccesses == maxAccessesPerRow; 957 958 // if we did not hit the limit, we might still want to 959 // auto-precharge 960 if (!auto_precharge && 961 (pageMgmt == Enums::open_adaptive || 962 pageMgmt == Enums::close_adaptive)) { 963 // a twist on the open and close page policies: 964 // 1) open_adaptive page policy does not blindly keep the 965 // page open, but close it if there are no row hits, and there 966 // are bank conflicts in the queue 967 // 2) close_adaptive page policy does not blindly close the 968 // page, but closes it only if there are no row hits in the queue. 969 // In this case, only force an auto precharge when there 970 // are no same page hits in the queue 971 bool got_more_hits = false; 972 bool got_bank_conflict = false; 973 974 // either look at the read queue or write queue 975 const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue : 976 writeQueue; 977 auto p = queue.begin(); 978 // make sure we are not considering the packet that we are 979 // currently dealing with (which is the head of the queue) 980 ++p; 981 982 // keep on looking until we have found required condition or 983 // reached the end 984 while (!(got_more_hits && 985 (got_bank_conflict || pageMgmt == Enums::close_adaptive)) && 986 p != queue.end()) { 987 bool same_rank_bank = (dram_pkt->rank == (*p)->rank) && 988 (dram_pkt->bank == (*p)->bank); 989 bool same_row = dram_pkt->row == (*p)->row; 990 got_more_hits |= same_rank_bank && same_row; 991 got_bank_conflict |= same_rank_bank && !same_row; 992 ++p; 993 } 994 995 // auto pre-charge when either 996 // 1) open_adaptive policy, we have not got any more hits, and 997 // have a bank conflict 998 // 2) close_adaptive policy and we have not got any more hits 999 auto_precharge = !got_more_hits && 1000 (got_bank_conflict || pageMgmt == Enums::close_adaptive); 1001 } 1002 1003 // if this access should use auto-precharge, then we are 1004 // closing the row 1005 if (auto_precharge) { 1006 prechargeBank(bank, std::max(curTick(), bank.preAllowedAt)); 1007 1008 DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId); 1009 } 1010 1011 // Update bus state 1012 busBusyUntil = dram_pkt->readyTime; 1013 1014 DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n", 1015 dram_pkt->addr, dram_pkt->readyTime, busBusyUntil); 1016 1017 // Update the minimum timing between the requests, this is a 1018 // conservative estimate of when we have to schedule the next 1019 // request to not introduce any unecessary bubbles. In most cases 1020 // we will wake up sooner than we have to. 1021 nextReqTime = busBusyUntil - (tRP + tRCD + tCL); 1022 1023 // Update the stats and schedule the next request 1024 if (dram_pkt->isRead) { 1025 ++readsThisTime; 1026 if (row_hit) 1027 readRowHits++; 1028 bytesReadDRAM += burstSize; 1029 perBankRdBursts[dram_pkt->bankId]++; 1030 1031 // Update latency stats 1032 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime; 1033 totBusLat += tBURST; 1034 totQLat += cmd_at - dram_pkt->entryTime; 1035 } else { 1036 ++writesThisTime; 1037 if (row_hit) 1038 writeRowHits++; 1039 bytesWritten += burstSize; 1040 perBankWrBursts[dram_pkt->bankId]++; 1041 } 1042} 1043 1044void 1045DRAMCtrl::moveToRespQ() 1046{ 1047 // Remove from read queue 1048 DRAMPacket* dram_pkt = readQueue.front(); 1049 readQueue.pop_front(); 1050 1051 // sanity check 1052 assert(dram_pkt->size <= burstSize); 1053 1054 // Insert into response queue sorted by readyTime 1055 // It will be sent back to the requestor at its 1056 // readyTime 1057 if (respQueue.empty()) { 1058 respQueue.push_front(dram_pkt); 1059 assert(!respondEvent.scheduled()); 1060 assert(dram_pkt->readyTime >= curTick()); 1061 schedule(respondEvent, dram_pkt->readyTime); 1062 } else { 1063 bool done = false; 1064 auto i = respQueue.begin(); 1065 while (!done && i != respQueue.end()) { 1066 if ((*i)->readyTime > dram_pkt->readyTime) { 1067 respQueue.insert(i, dram_pkt); 1068 done = true; 1069 } 1070 ++i; 1071 } 1072 1073 if (!done) 1074 respQueue.push_back(dram_pkt); 1075 1076 assert(respondEvent.scheduled()); 1077 1078 if (respQueue.front()->readyTime < respondEvent.when()) { 1079 assert(respQueue.front()->readyTime >= curTick()); 1080 reschedule(respondEvent, respQueue.front()->readyTime); 1081 } 1082 } 1083} 1084 1085void 1086DRAMCtrl::processNextReqEvent() 1087{ 1088 if (busState == READ_TO_WRITE) { 1089 DPRINTF(DRAM, "Switching to writes after %d reads with %d reads " 1090 "waiting\n", readsThisTime, readQueue.size()); 1091 1092 // sample and reset the read-related stats as we are now 1093 // transitioning to writes, and all reads are done 1094 rdPerTurnAround.sample(readsThisTime); 1095 readsThisTime = 0; 1096 1097 // now proceed to do the actual writes 1098 busState = WRITE; 1099 } else if (busState == WRITE_TO_READ) { 1100 DPRINTF(DRAM, "Switching to reads after %d writes with %d writes " 1101 "waiting\n", writesThisTime, writeQueue.size()); 1102 1103 wrPerTurnAround.sample(writesThisTime); 1104 writesThisTime = 0; 1105 1106 busState = READ; 1107 } 1108 1109 if (refreshState != REF_IDLE) { 1110 // if a refresh waiting for this event loop to finish, then hand 1111 // over now, and do not schedule a new nextReqEvent 1112 if (refreshState == REF_DRAIN) { 1113 DPRINTF(DRAM, "Refresh drain done, now precharging\n"); 1114 1115 refreshState = REF_PRE; 1116 1117 // hand control back to the refresh event loop 1118 schedule(refreshEvent, curTick()); 1119 } 1120 1121 // let the refresh finish before issuing any further requests 1122 return; 1123 } 1124 1125 // when we get here it is either a read or a write 1126 if (busState == READ) { 1127 1128 // track if we should switch or not 1129 bool switch_to_writes = false; 1130 1131 if (readQueue.empty()) { 1132 // In the case there is no read request to go next, 1133 // trigger writes if we have passed the low threshold (or 1134 // if we are draining) 1135 if (!writeQueue.empty() && 1136 (drainManager || writeQueue.size() > writeLowThreshold)) { 1137 1138 switch_to_writes = true; 1139 } else { 1140 // check if we are drained 1141 if (respQueue.empty () && drainManager) { 1142 drainManager->signalDrainDone(); 1143 drainManager = NULL; 1144 } 1145 1146 // nothing to do, not even any point in scheduling an 1147 // event for the next request 1148 return; 1149 } 1150 } else { 1151 // Figure out which read request goes next, and move it to the 1152 // front of the read queue 1153 chooseNext(readQueue); 1154 1155 doDRAMAccess(readQueue.front()); 1156 1157 // At this point we're done dealing with the request 1158 // It will be moved to a separate response queue with a 1159 // correct readyTime, and eventually be sent back at that 1160 // time 1161 moveToRespQ(); 1162 1163 // we have so many writes that we have to transition 1164 if (writeQueue.size() > writeHighThreshold) { 1165 switch_to_writes = true; 1166 } 1167 } 1168 1169 // switching to writes, either because the read queue is empty 1170 // and the writes have passed the low threshold (or we are 1171 // draining), or because the writes hit the hight threshold 1172 if (switch_to_writes) { 1173 // transition to writing 1174 busState = READ_TO_WRITE; 1175 1176 // add a bubble to the data bus, as defined by the 1177 // tRTW parameter 1178 busBusyUntil += tRTW; 1179 1180 // update the minimum timing between the requests, 1181 // this shifts us back in time far enough to do any 1182 // bank preparation 1183 nextReqTime = busBusyUntil - (tRP + tRCD + tCL); 1184 } 1185 } else { 1186 chooseNext(writeQueue); 1187 DRAMPacket* dram_pkt = writeQueue.front(); 1188 // sanity check 1189 assert(dram_pkt->size <= burstSize); 1190 doDRAMAccess(dram_pkt); 1191 1192 writeQueue.pop_front(); 1193 delete dram_pkt; 1194 1195 // If we emptied the write queue, or got sufficiently below the 1196 // threshold (using the minWritesPerSwitch as the hysteresis) and 1197 // are not draining, or we have reads waiting and have done enough 1198 // writes, then switch to reads. 1199 if (writeQueue.empty() || 1200 (writeQueue.size() + minWritesPerSwitch < writeLowThreshold && 1201 !drainManager) || 1202 (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) { 1203 // turn the bus back around for reads again 1204 busState = WRITE_TO_READ; 1205 1206 // note that the we switch back to reads also in the idle 1207 // case, which eventually will check for any draining and 1208 // also pause any further scheduling if there is really 1209 // nothing to do 1210 1211 // here we get a bit creative and shift the bus busy time not 1212 // just the tWTR, but also a CAS latency to capture the fact 1213 // that we are allowed to prepare a new bank, but not issue a 1214 // read command until after tWTR, in essence we capture a 1215 // bubble on the data bus that is tWTR + tCL 1216 busBusyUntil += tWTR + tCL; 1217 1218 // update the minimum timing between the requests, this shifts 1219 // us back in time far enough to do any bank preparation 1220 nextReqTime = busBusyUntil - (tRP + tRCD + tCL); 1221 } 1222 } 1223 1224 schedule(nextReqEvent, std::max(nextReqTime, curTick())); 1225 1226 // If there is space available and we have writes waiting then let 1227 // them retry. This is done here to ensure that the retry does not 1228 // cause a nextReqEvent to be scheduled before we do so as part of 1229 // the next request processing 1230 if (retryWrReq && writeQueue.size() < writeBufferSize) { 1231 retryWrReq = false; 1232 port.sendRetry(); 1233 } 1234} 1235 1236uint64_t 1237DRAMCtrl::minBankActAt(const deque<DRAMPacket*>& queue) const 1238{ 1239 uint64_t bank_mask = 0; 1240 Tick min_act_at = MaxTick; 1241 1242 // deterimne if we have queued transactions targetting a 1243 // bank in question 1244 vector<bool> got_waiting(ranksPerChannel * banksPerRank, false); 1245 for (auto p = queue.begin(); p != queue.end(); ++p) { 1246 got_waiting[(*p)->bankId] = true; 1247 } 1248 1249 for (int i = 0; i < ranksPerChannel; i++) { 1250 for (int j = 0; j < banksPerRank; j++) { 1251 uint8_t bank_id = i * banksPerRank + j; 1252 1253 // if we have waiting requests for the bank, and it is 1254 // amongst the first available, update the mask 1255 if (got_waiting[bank_id]) { 1256 // simplistic approximation of when the bank can issue 1257 // an activate, ignoring any rank-to-rank switching 1258 // cost 1259 Tick act_at = banks[i][j].openRow == Bank::NO_ROW ? 1260 banks[i][j].actAllowedAt : 1261 std::max(banks[i][j].preAllowedAt, curTick()) + tRP; 1262 1263 if (act_at <= min_act_at) { 1264 // reset bank mask if new minimum is found 1265 if (act_at < min_act_at) 1266 bank_mask = 0; 1267 // set the bit corresponding to the available bank 1268 replaceBits(bank_mask, bank_id, bank_id, 1); 1269 min_act_at = act_at; 1270 } 1271 } 1272 } 1273 } 1274 1275 return bank_mask; 1276} 1277 1278void 1279DRAMCtrl::processRefreshEvent() 1280{ 1281 // when first preparing the refresh, remember when it was due 1282 if (refreshState == REF_IDLE) { 1283 // remember when the refresh is due 1284 refreshDueAt = curTick(); 1285 1286 // proceed to drain 1287 refreshState = REF_DRAIN; 1288 1289 DPRINTF(DRAM, "Refresh due\n"); 1290 } 1291 1292 // let any scheduled read or write go ahead, after which it will 1293 // hand control back to this event loop 1294 if (refreshState == REF_DRAIN) { 1295 if (nextReqEvent.scheduled()) { 1296 // hand control over to the request loop until it is 1297 // evaluated next 1298 DPRINTF(DRAM, "Refresh awaiting draining\n"); 1299 1300 return; 1301 } else { 1302 refreshState = REF_PRE; 1303 } 1304 } 1305 1306 // at this point, ensure that all banks are precharged 1307 if (refreshState == REF_PRE) { 1308 // precharge any active bank if we are not already in the idle 1309 // state 1310 if (pwrState != PWR_IDLE) { 1311 // at the moment, we use a precharge all even if there is 1312 // only a single bank open 1313 DPRINTF(DRAM, "Precharging all\n"); 1314 1315 // first determine when we can precharge 1316 Tick pre_at = curTick(); 1317 for (int i = 0; i < ranksPerChannel; i++) { 1318 for (int j = 0; j < banksPerRank; j++) { 1319 // respect both causality and any existing bank 1320 // constraints, some banks could already have a 1321 // (auto) precharge scheduled 1322 pre_at = std::max(banks[i][j].preAllowedAt, pre_at); 1323 } 1324 } 1325 1326 // make sure all banks are precharged, and for those that 1327 // already are, update their availability 1328 Tick act_allowed_at = pre_at + tRP; 1329 1330 for (int i = 0; i < ranksPerChannel; i++) { 1331 for (int j = 0; j < banksPerRank; j++) { 1332 if (banks[i][j].openRow != Bank::NO_ROW) { 1333 prechargeBank(banks[i][j], pre_at); 1334 } else { 1335 banks[i][j].actAllowedAt = 1336 std::max(banks[i][j].actAllowedAt, act_allowed_at); 1337 banks[i][j].preAllowedAt = 1338 std::max(banks[i][j].preAllowedAt, pre_at); 1339 } 1340 } 1341 } 1342 } else { 1343 DPRINTF(DRAM, "All banks already precharged, starting refresh\n"); 1344 1345 // go ahead and kick the power state machine into gear if 1346 // we are already idle 1347 schedulePowerEvent(PWR_REF, curTick()); 1348 } 1349 1350 refreshState = REF_RUN; 1351 assert(numBanksActive == 0); 1352 1353 // wait for all banks to be precharged, at which point the 1354 // power state machine will transition to the idle state, and 1355 // automatically move to a refresh, at that point it will also 1356 // call this method to get the refresh event loop going again 1357 return; 1358 } 1359 1360 // last but not least we perform the actual refresh 1361 if (refreshState == REF_RUN) { 1362 // should never get here with any banks active 1363 assert(numBanksActive == 0); 1364 assert(pwrState == PWR_REF); 1365 1366 Tick ref_done_at = curTick() + tRFC; 1367 1368 for (int i = 0; i < ranksPerChannel; i++) { 1369 for (int j = 0; j < banksPerRank; j++) { 1370 banks[i][j].actAllowedAt = ref_done_at; 1371 } 1372 } 1373 1374 // make sure we did not wait so long that we cannot make up 1375 // for it 1376 if (refreshDueAt + tREFI < ref_done_at) { 1377 fatal("Refresh was delayed so long we cannot catch up\n"); 1378 } 1379 1380 // compensate for the delay in actually performing the refresh 1381 // when scheduling the next one 1382 schedule(refreshEvent, refreshDueAt + tREFI - tRP); 1383 1384 assert(!powerEvent.scheduled()); 1385 1386 // move to the idle power state once the refresh is done, this 1387 // will also move the refresh state machine to the refresh 1388 // idle state 1389 schedulePowerEvent(PWR_IDLE, ref_done_at); 1390 1391 DPRINTF(DRAMState, "Refresh done at %llu and next refresh at %llu\n", 1392 ref_done_at, refreshDueAt + tREFI); 1393 } 1394} 1395 1396void 1397DRAMCtrl::schedulePowerEvent(PowerState pwr_state, Tick tick) 1398{ 1399 // respect causality 1400 assert(tick >= curTick()); 1401 1402 if (!powerEvent.scheduled()) { 1403 DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n", 1404 tick, pwr_state); 1405 1406 // insert the new transition 1407 pwrStateTrans = pwr_state; 1408 1409 schedule(powerEvent, tick); 1410 } else { 1411 panic("Scheduled power event at %llu to state %d, " 1412 "with scheduled event at %llu to %d\n", tick, pwr_state, 1413 powerEvent.when(), pwrStateTrans); 1414 } 1415} 1416 1417void 1418DRAMCtrl::processPowerEvent() 1419{ 1420 // remember where we were, and for how long 1421 Tick duration = curTick() - pwrStateTick; 1422 PowerState prev_state = pwrState; 1423 1424 // update the accounting 1425 pwrStateTime[prev_state] += duration; 1426 1427 pwrState = pwrStateTrans; 1428 pwrStateTick = curTick(); 1429 1430 if (pwrState == PWR_IDLE) { 1431 DPRINTF(DRAMState, "All banks precharged\n"); 1432 1433 // if we were refreshing, make sure we start scheduling requests again 1434 if (prev_state == PWR_REF) { 1435 DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration); 1436 assert(pwrState == PWR_IDLE); 1437 1438 // kick things into action again 1439 refreshState = REF_IDLE; 1440 assert(!nextReqEvent.scheduled()); 1441 schedule(nextReqEvent, curTick()); 1442 } else { 1443 assert(prev_state == PWR_ACT); 1444 1445 // if we have a pending refresh, and are now moving to 1446 // the idle state, direclty transition to a refresh 1447 if (refreshState == REF_RUN) { 1448 // there should be nothing waiting at this point 1449 assert(!powerEvent.scheduled()); 1450 1451 // update the state in zero time and proceed below 1452 pwrState = PWR_REF; 1453 } 1454 } 1455 } 1456 1457 // we transition to the refresh state, let the refresh state 1458 // machine know of this state update and let it deal with the 1459 // scheduling of the next power state transition as well as the 1460 // following refresh 1461 if (pwrState == PWR_REF) { 1462 DPRINTF(DRAMState, "Refreshing\n"); 1463 // kick the refresh event loop into action again, and that 1464 // in turn will schedule a transition to the idle power 1465 // state once the refresh is done 1466 assert(refreshState == REF_RUN); 1467 processRefreshEvent(); 1468 } 1469} 1470 1471void 1472DRAMCtrl::regStats() 1473{ 1474 using namespace Stats; 1475 1476 AbstractMemory::regStats(); 1477 1478 readReqs 1479 .name(name() + ".readReqs") 1480 .desc("Number of read requests accepted"); 1481 1482 writeReqs 1483 .name(name() + ".writeReqs") 1484 .desc("Number of write requests accepted"); 1485 1486 readBursts 1487 .name(name() + ".readBursts") 1488 .desc("Number of DRAM read bursts, " 1489 "including those serviced by the write queue"); 1490 1491 writeBursts 1492 .name(name() + ".writeBursts") 1493 .desc("Number of DRAM write bursts, " 1494 "including those merged in the write queue"); 1495 1496 servicedByWrQ 1497 .name(name() + ".servicedByWrQ") 1498 .desc("Number of DRAM read bursts serviced by the write queue"); 1499 1500 mergedWrBursts 1501 .name(name() + ".mergedWrBursts") 1502 .desc("Number of DRAM write bursts merged with an existing one"); 1503 1504 neitherReadNorWrite 1505 .name(name() + ".neitherReadNorWriteReqs") 1506 .desc("Number of requests that are neither read nor write"); 1507 1508 perBankRdBursts 1509 .init(banksPerRank * ranksPerChannel) 1510 .name(name() + ".perBankRdBursts") 1511 .desc("Per bank write bursts"); 1512 1513 perBankWrBursts 1514 .init(banksPerRank * ranksPerChannel) 1515 .name(name() + ".perBankWrBursts") 1516 .desc("Per bank write bursts"); 1517 1518 avgRdQLen 1519 .name(name() + ".avgRdQLen") 1520 .desc("Average read queue length when enqueuing") 1521 .precision(2); 1522 1523 avgWrQLen 1524 .name(name() + ".avgWrQLen") 1525 .desc("Average write queue length when enqueuing") 1526 .precision(2); 1527 1528 totQLat 1529 .name(name() + ".totQLat") 1530 .desc("Total ticks spent queuing"); 1531 1532 totBusLat 1533 .name(name() + ".totBusLat") 1534 .desc("Total ticks spent in databus transfers"); 1535 1536 totMemAccLat 1537 .name(name() + ".totMemAccLat") 1538 .desc("Total ticks spent from burst creation until serviced " 1539 "by the DRAM"); 1540 1541 avgQLat 1542 .name(name() + ".avgQLat") 1543 .desc("Average queueing delay per DRAM burst") 1544 .precision(2); 1545 1546 avgQLat = totQLat / (readBursts - servicedByWrQ); 1547 1548 avgBusLat 1549 .name(name() + ".avgBusLat") 1550 .desc("Average bus latency per DRAM burst") 1551 .precision(2); 1552 1553 avgBusLat = totBusLat / (readBursts - servicedByWrQ); 1554 1555 avgMemAccLat 1556 .name(name() + ".avgMemAccLat") 1557 .desc("Average memory access latency per DRAM burst") 1558 .precision(2); 1559 1560 avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ); 1561 1562 numRdRetry 1563 .name(name() + ".numRdRetry") 1564 .desc("Number of times read queue was full causing retry"); 1565 1566 numWrRetry 1567 .name(name() + ".numWrRetry") 1568 .desc("Number of times write queue was full causing retry"); 1569 1570 readRowHits 1571 .name(name() + ".readRowHits") 1572 .desc("Number of row buffer hits during reads"); 1573 1574 writeRowHits 1575 .name(name() + ".writeRowHits") 1576 .desc("Number of row buffer hits during writes"); 1577 1578 readRowHitRate 1579 .name(name() + ".readRowHitRate") 1580 .desc("Row buffer hit rate for reads") 1581 .precision(2); 1582 1583 readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100; 1584 1585 writeRowHitRate 1586 .name(name() + ".writeRowHitRate") 1587 .desc("Row buffer hit rate for writes") 1588 .precision(2); 1589 1590 writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100; 1591 1592 readPktSize 1593 .init(ceilLog2(burstSize) + 1) 1594 .name(name() + ".readPktSize") 1595 .desc("Read request sizes (log2)"); 1596 1597 writePktSize 1598 .init(ceilLog2(burstSize) + 1) 1599 .name(name() + ".writePktSize") 1600 .desc("Write request sizes (log2)"); 1601 1602 rdQLenPdf 1603 .init(readBufferSize) 1604 .name(name() + ".rdQLenPdf") 1605 .desc("What read queue length does an incoming req see"); 1606 1607 wrQLenPdf 1608 .init(writeBufferSize) 1609 .name(name() + ".wrQLenPdf") 1610 .desc("What write queue length does an incoming req see"); 1611 1612 bytesPerActivate 1613 .init(maxAccessesPerRow) 1614 .name(name() + ".bytesPerActivate") 1615 .desc("Bytes accessed per row activation") 1616 .flags(nozero); 1617 1618 rdPerTurnAround 1619 .init(readBufferSize) 1620 .name(name() + ".rdPerTurnAround") 1621 .desc("Reads before turning the bus around for writes") 1622 .flags(nozero); 1623 1624 wrPerTurnAround 1625 .init(writeBufferSize) 1626 .name(name() + ".wrPerTurnAround") 1627 .desc("Writes before turning the bus around for reads") 1628 .flags(nozero); 1629 1630 bytesReadDRAM 1631 .name(name() + ".bytesReadDRAM") 1632 .desc("Total number of bytes read from DRAM"); 1633 1634 bytesReadWrQ 1635 .name(name() + ".bytesReadWrQ") 1636 .desc("Total number of bytes read from write queue"); 1637 1638 bytesWritten 1639 .name(name() + ".bytesWritten") 1640 .desc("Total number of bytes written to DRAM"); 1641 1642 bytesReadSys 1643 .name(name() + ".bytesReadSys") 1644 .desc("Total read bytes from the system interface side"); 1645 1646 bytesWrittenSys 1647 .name(name() + ".bytesWrittenSys") 1648 .desc("Total written bytes from the system interface side"); 1649 1650 avgRdBW 1651 .name(name() + ".avgRdBW") 1652 .desc("Average DRAM read bandwidth in MiByte/s") 1653 .precision(2); 1654 1655 avgRdBW = (bytesReadDRAM / 1000000) / simSeconds; 1656 1657 avgWrBW 1658 .name(name() + ".avgWrBW") 1659 .desc("Average achieved write bandwidth in MiByte/s") 1660 .precision(2); 1661 1662 avgWrBW = (bytesWritten / 1000000) / simSeconds; 1663 1664 avgRdBWSys 1665 .name(name() + ".avgRdBWSys") 1666 .desc("Average system read bandwidth in MiByte/s") 1667 .precision(2); 1668 1669 avgRdBWSys = (bytesReadSys / 1000000) / simSeconds; 1670 1671 avgWrBWSys 1672 .name(name() + ".avgWrBWSys") 1673 .desc("Average system write bandwidth in MiByte/s") 1674 .precision(2); 1675 1676 avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds; 1677 1678 peakBW 1679 .name(name() + ".peakBW") 1680 .desc("Theoretical peak bandwidth in MiByte/s") 1681 .precision(2); 1682 1683 peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000; 1684 1685 busUtil 1686 .name(name() + ".busUtil") 1687 .desc("Data bus utilization in percentage") 1688 .precision(2); 1689 1690 busUtil = (avgRdBW + avgWrBW) / peakBW * 100; 1691 1692 totGap 1693 .name(name() + ".totGap") 1694 .desc("Total gap between requests"); 1695 1696 avgGap 1697 .name(name() + ".avgGap") 1698 .desc("Average gap between requests") 1699 .precision(2); 1700 1701 avgGap = totGap / (readReqs + writeReqs); 1702 1703 // Stats for DRAM Power calculation based on Micron datasheet 1704 busUtilRead 1705 .name(name() + ".busUtilRead") 1706 .desc("Data bus utilization in percentage for reads") 1707 .precision(2); 1708 1709 busUtilRead = avgRdBW / peakBW * 100; 1710 1711 busUtilWrite 1712 .name(name() + ".busUtilWrite") 1713 .desc("Data bus utilization in percentage for writes") 1714 .precision(2); 1715 1716 busUtilWrite = avgWrBW / peakBW * 100; 1717 1718 pageHitRate 1719 .name(name() + ".pageHitRate") 1720 .desc("Row buffer hit rate, read and write combined") 1721 .precision(2); 1722 1723 pageHitRate = (writeRowHits + readRowHits) / 1724 (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100; 1725 1726 pwrStateTime 1727 .init(5) 1728 .name(name() + ".memoryStateTime") 1729 .desc("Time in different power states"); 1730 pwrStateTime.subname(0, "IDLE"); 1731 pwrStateTime.subname(1, "REF"); 1732 pwrStateTime.subname(2, "PRE_PDN"); 1733 pwrStateTime.subname(3, "ACT"); 1734 pwrStateTime.subname(4, "ACT_PDN"); 1735} 1736 1737void 1738DRAMCtrl::recvFunctional(PacketPtr pkt) 1739{ 1740 // rely on the abstract memory 1741 functionalAccess(pkt); 1742} 1743 1744BaseSlavePort& 1745DRAMCtrl::getSlavePort(const string &if_name, PortID idx) 1746{ 1747 if (if_name != "port") { 1748 return MemObject::getSlavePort(if_name, idx); 1749 } else { 1750 return port; 1751 } 1752} 1753 1754unsigned int 1755DRAMCtrl::drain(DrainManager *dm) 1756{ 1757 unsigned int count = port.drain(dm); 1758 1759 // if there is anything in any of our internal queues, keep track 1760 // of that as well 1761 if (!(writeQueue.empty() && readQueue.empty() && 1762 respQueue.empty())) { 1763 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d," 1764 " resp: %d\n", writeQueue.size(), readQueue.size(), 1765 respQueue.size()); 1766 ++count; 1767 drainManager = dm; 1768 1769 // the only part that is not drained automatically over time 1770 // is the write queue, thus kick things into action if needed 1771 if (!writeQueue.empty() && !nextReqEvent.scheduled()) { 1772 schedule(nextReqEvent, curTick()); 1773 } 1774 } 1775 1776 if (count) 1777 setDrainState(Drainable::Draining); 1778 else 1779 setDrainState(Drainable::Drained); 1780 return count; 1781} 1782 1783DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory) 1784 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this), 1785 memory(_memory) 1786{ } 1787 1788AddrRangeList 1789DRAMCtrl::MemoryPort::getAddrRanges() const 1790{ 1791 AddrRangeList ranges; 1792 ranges.push_back(memory.getAddrRange()); 1793 return ranges; 1794} 1795 1796void 1797DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt) 1798{ 1799 pkt->pushLabel(memory.name()); 1800 1801 if (!queue.checkFunctional(pkt)) { 1802 // Default implementation of SimpleTimingPort::recvFunctional() 1803 // calls recvAtomic() and throws away the latency; we can save a 1804 // little here by just not calculating the latency. 1805 memory.recvFunctional(pkt); 1806 } 1807 1808 pkt->popLabel(); 1809} 1810 1811Tick 1812DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt) 1813{ 1814 return memory.recvAtomic(pkt); 1815} 1816 1817bool 1818DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt) 1819{ 1820 // pass it to the memory controller 1821 return memory.recvTimingReq(pkt); 1822} 1823 1824DRAMCtrl* 1825DRAMCtrlParams::create() 1826{ 1827 return new DRAMCtrl(this); 1828} 1829