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