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