dram_ctrl.cc revision 9567
1/* 2 * Copyright (c) 2010-2012 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 * Redistribution and use in source and binary forms, with or without 15 * modification, are permitted provided that the following conditions are 16 * met: redistributions of source code must retain the above copyright 17 * notice, this list of conditions and the following disclaimer; 18 * redistributions in binary form must reproduce the above copyright 19 * notice, this list of conditions and the following disclaimer in the 20 * documentation and/or other materials provided with the distribution; 21 * neither the name of the copyright holders nor the names of its 22 * contributors may be used to endorse or promote products derived from 23 * this software without specific prior written permission. 24 * 25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 36 * 37 * Authors: Andreas Hansson 38 * Ani Udipi 39 */ 40 41#include "base/trace.hh" 42#include "debug/Drain.hh" 43#include "debug/DRAM.hh" 44#include "debug/DRAMWR.hh" 45#include "mem/simple_dram.hh" 46 47using namespace std; 48 49SimpleDRAM::SimpleDRAM(const SimpleDRAMParams* p) : 50 AbstractMemory(p), 51 port(name() + ".port", *this), 52 retryRdReq(false), retryWrReq(false), 53 rowHitFlag(false), stopReads(false), actTicks(p->activation_limit, 0), 54 writeEvent(this), respondEvent(this), 55 refreshEvent(this), nextReqEvent(this), drainManager(NULL), 56 bytesPerCacheLine(0), 57 linesPerRowBuffer(p->lines_per_rowbuffer), 58 ranksPerChannel(p->ranks_per_channel), 59 banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0), 60 readBufferSize(p->read_buffer_size), 61 writeBufferSize(p->write_buffer_size), 62 writeThresholdPerc(p->write_thresh_perc), 63 tWTR(p->tWTR), tBURST(p->tBURST), 64 tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), 65 tRFC(p->tRFC), tREFI(p->tREFI), 66 tXAW(p->tXAW), activationLimit(p->activation_limit), 67 memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping), 68 pageMgmt(p->page_policy), 69 busBusyUntil(0), writeStartTime(0), 70 prevArrival(0), numReqs(0) 71{ 72 // create the bank states based on the dimensions of the ranks and 73 // banks 74 banks.resize(ranksPerChannel); 75 for (size_t c = 0; c < ranksPerChannel; ++c) { 76 banks[c].resize(banksPerRank); 77 } 78 79 // round the write threshold percent to a whole number of entries 80 // in the buffer 81 writeThreshold = writeBufferSize * writeThresholdPerc / 100.0; 82} 83 84void 85SimpleDRAM::init() 86{ 87 if (!port.isConnected()) { 88 fatal("SimpleDRAM %s is unconnected!\n", name()); 89 } else { 90 port.sendRangeChange(); 91 } 92 93 // get the burst size from the connected port as it is currently 94 // assumed to be equal to the cache line size 95 bytesPerCacheLine = port.peerBlockSize(); 96 97 // we could deal with plenty options here, but for now do a quick 98 // sanity check 99 if (bytesPerCacheLine != 64 && bytesPerCacheLine != 32) 100 panic("Unexpected burst size %d", bytesPerCacheLine); 101 102 // determine the rows per bank by looking at the total capacity 103 uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size()); 104 105 DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity, 106 AbstractMemory::size()); 107 rowsPerBank = capacity / (bytesPerCacheLine * linesPerRowBuffer * 108 banksPerRank * ranksPerChannel); 109 110 if (range.interleaved()) { 111 if (channels != range.stripes()) 112 panic("%s has %d interleaved address stripes but %d channel(s)\n", 113 name(), range.stripes(), channels); 114 115 if (addrMapping == Enums::openmap) { 116 if (bytesPerCacheLine * linesPerRowBuffer != 117 range.granularity()) { 118 panic("Interleaving of %s doesn't match open address map\n", 119 name()); 120 } 121 } else if (addrMapping == Enums::closemap) { 122 if (bytesPerCacheLine != range.granularity()) 123 panic("Interleaving of %s doesn't match closed address map\n", 124 name()); 125 } 126 } 127} 128 129void 130SimpleDRAM::startup() 131{ 132 // print the configuration of the controller 133 printParams(); 134 135 // kick off the refresh 136 schedule(refreshEvent, curTick() + tREFI); 137} 138 139Tick 140SimpleDRAM::recvAtomic(PacketPtr pkt) 141{ 142 DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr()); 143 144 // do the actual memory access and turn the packet into a response 145 access(pkt); 146 147 Tick latency = 0; 148 if (!pkt->memInhibitAsserted() && pkt->hasData()) { 149 // this value is not supposed to be accurate, just enough to 150 // keep things going, mimic a closed page 151 latency = tRP + tRCD + tCL; 152 } 153 return latency; 154} 155 156bool 157SimpleDRAM::readQueueFull() const 158{ 159 DPRINTF(DRAM, "Read queue limit %d current size %d\n", 160 readBufferSize, readQueue.size() + respQueue.size()); 161 162 return (readQueue.size() + respQueue.size()) == readBufferSize; 163} 164 165bool 166SimpleDRAM::writeQueueFull() const 167{ 168 DPRINTF(DRAM, "Write queue limit %d current size %d\n", 169 writeBufferSize, writeQueue.size()); 170 return writeQueue.size() == writeBufferSize; 171} 172 173SimpleDRAM::DRAMPacket* 174SimpleDRAM::decodeAddr(PacketPtr pkt) 175{ 176 // decode the address based on the address mapping scheme 177 // 178 // with R, C, B and K denoting rank, column, bank and rank, 179 // respectively, and going from MSB to LSB, the two schemes are 180 // RKBC (openmap) and RCKB (closedmap) 181 uint8_t rank; 182 uint16_t bank; 183 uint16_t row; 184 185 Addr addr = pkt->getAddr(); 186 187 // truncate the address to the access granularity 188 addr = addr / bytesPerCacheLine; 189 190 // we have removed the lowest order address bits that denote the 191 // position within the cache line, proceed and select the 192 // appropriate bits for bank, rank and row (no column address is 193 // needed) 194 if (addrMapping == Enums::openmap) { 195 // the lowest order bits denote the column to ensure that 196 // sequential cache lines occupy the same row 197 addr = addr / linesPerRowBuffer; 198 199 // take out the channel part of the address, note that this has 200 // to match with how accesses are interleaved between the 201 // controllers in the address mapping 202 addr = addr / channels; 203 204 // after the column bits, we get the bank bits to interleave 205 // over the banks 206 bank = addr % banksPerRank; 207 addr = addr / banksPerRank; 208 209 // after the bank, we get the rank bits which thus interleaves 210 // over the ranks 211 rank = addr % ranksPerChannel; 212 addr = addr / ranksPerChannel; 213 214 // lastly, get the row bits 215 row = addr % rowsPerBank; 216 addr = addr / rowsPerBank; 217 } else if (addrMapping == Enums::closemap) { 218 // optimise for closed page mode and utilise maximum 219 // parallelism of the DRAM (at the cost of power) 220 221 // take out the channel part of the address, not that this has 222 // to match with how accesses are interleaved between the 223 // controllers in the address mapping 224 addr = addr / channels; 225 226 // start with the bank bits, as this provides the maximum 227 // opportunity for parallelism between requests 228 bank = addr % banksPerRank; 229 addr = addr / banksPerRank; 230 231 // next get the rank bits 232 rank = addr % ranksPerChannel; 233 addr = addr / ranksPerChannel; 234 235 // next the column bits which we do not need to keep track of 236 // and simply skip past 237 addr = addr / linesPerRowBuffer; 238 239 // lastly, get the row bits 240 row = addr % rowsPerBank; 241 addr = addr / rowsPerBank; 242 } else 243 panic("Unknown address mapping policy chosen!"); 244 245 assert(rank < ranksPerChannel); 246 assert(bank < banksPerRank); 247 assert(row < rowsPerBank); 248 249 DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n", 250 pkt->getAddr(), rank, bank, row); 251 252 // create the corresponding DRAM packet with the entry time and 253 // ready time set to the current tick, the latter will be updated 254 // later 255 return new DRAMPacket(pkt, rank, bank, row, pkt->getAddr(), 256 banks[rank][bank]); 257} 258 259void 260SimpleDRAM::addToReadQueue(PacketPtr pkt) 261{ 262 // only add to the read queue here. whenever the request is 263 // eventually done, set the readyTime, and call schedule() 264 assert(!pkt->isWrite()); 265 266 // First check write buffer to see if the data is already at 267 // the controller 268 list<DRAMPacket*>::const_iterator i; 269 Addr addr = pkt->getAddr(); 270 271 // @todo: add size check 272 for (i = writeQueue.begin(); i != writeQueue.end(); ++i) { 273 if ((*i)->addr == addr){ 274 servicedByWrQ++; 275 DPRINTF(DRAM, "Read to %lld serviced by write queue\n", addr); 276 bytesRead += bytesPerCacheLine; 277 bytesConsumedRd += pkt->getSize(); 278 accessAndRespond(pkt); 279 return; 280 } 281 } 282 283 DRAMPacket* dram_pkt = decodeAddr(pkt); 284 285 assert(readQueue.size() + respQueue.size() < readBufferSize); 286 rdQLenPdf[readQueue.size() + respQueue.size()]++; 287 288 DPRINTF(DRAM, "Adding to read queue\n"); 289 290 readQueue.push_back(dram_pkt); 291 292 // Update stats 293 uint32_t bank_id = banksPerRank * dram_pkt->rank + dram_pkt->bank; 294 assert(bank_id < ranksPerChannel * banksPerRank); 295 perBankRdReqs[bank_id]++; 296 297 avgRdQLen = readQueue.size() + respQueue.size(); 298 299 // If we are not already scheduled to get the read request out of 300 // the queue, do so now 301 if (!nextReqEvent.scheduled() && !stopReads) { 302 DPRINTF(DRAM, "Request scheduled immediately\n"); 303 schedule(nextReqEvent, curTick()); 304 } 305} 306 307void 308SimpleDRAM::processWriteEvent() 309{ 310 assert(!writeQueue.empty()); 311 uint32_t numWritesThisTime = 0; 312 313 DPRINTF(DRAMWR, "Beginning DRAM Writes\n"); 314 Tick temp1 M5_VAR_USED = std::max(curTick(), busBusyUntil); 315 Tick temp2 M5_VAR_USED = std::max(curTick(), maxBankFreeAt()); 316 317 // @todo: are there any dangers with the untimed while loop? 318 while (!writeQueue.empty()) { 319 if (numWritesThisTime > writeThreshold) { 320 DPRINTF(DRAMWR, "Hit write threshold %d\n", writeThreshold); 321 break; 322 } 323 324 chooseNextWrite(); 325 DRAMPacket* dram_pkt = writeQueue.front(); 326 // What's the earliest the request can be put on the bus 327 Tick schedTime = std::max(curTick(), busBusyUntil); 328 329 DPRINTF(DRAMWR, "Asking for latency estimate at %lld\n", 330 schedTime + tBURST); 331 332 pair<Tick, Tick> lat = estimateLatency(dram_pkt, schedTime + tBURST); 333 Tick accessLat = lat.second; 334 335 // look at the rowHitFlag set by estimateLatency 336 if (rowHitFlag) 337 writeRowHits++; 338 339 Bank& bank = dram_pkt->bank_ref; 340 341 if (pageMgmt == Enums::open) { 342 bank.openRow = dram_pkt->row; 343 bank.freeAt = schedTime + tBURST + std::max(accessLat, tCL); 344 busBusyUntil = bank.freeAt - tCL; 345 346 if (!rowHitFlag) { 347 bank.tRASDoneAt = bank.freeAt + tRP; 348 recordActivate(bank.freeAt - tCL - tRCD); 349 busBusyUntil = bank.freeAt - tCL - tRCD; 350 } 351 } else if (pageMgmt == Enums::close) { 352 bank.freeAt = schedTime + tBURST + accessLat + tRP + tRP; 353 // Work backwards from bank.freeAt to determine activate time 354 recordActivate(bank.freeAt - tRP - tRP - tCL - tRCD); 355 busBusyUntil = bank.freeAt - tRP - tRP - tCL - tRCD; 356 DPRINTF(DRAMWR, "processWriteEvent::bank.freeAt for " 357 "banks_id %d is %lld\n", 358 dram_pkt->rank * banksPerRank + dram_pkt->bank, 359 bank.freeAt); 360 } else 361 panic("Unknown page management policy chosen\n"); 362 363 DPRINTF(DRAMWR, "Done writing to address %lld\n", dram_pkt->addr); 364 365 DPRINTF(DRAMWR, "schedtime is %lld, tBURST is %lld, " 366 "busbusyuntil is %lld\n", 367 schedTime, tBURST, busBusyUntil); 368 369 writeQueue.pop_front(); 370 delete dram_pkt; 371 372 numWritesThisTime++; 373 } 374 375 DPRINTF(DRAMWR, "Completed %d writes, bus busy for %lld ticks,"\ 376 "banks busy for %lld ticks\n", numWritesThisTime, 377 busBusyUntil - temp1, maxBankFreeAt() - temp2); 378 379 // Update stats 380 avgWrQLen = writeQueue.size(); 381 382 // turn the bus back around for reads again 383 busBusyUntil += tWTR; 384 stopReads = false; 385 386 if (retryWrReq) { 387 retryWrReq = false; 388 port.sendRetry(); 389 } 390 391 // if there is nothing left in any queue, signal a drain 392 if (writeQueue.empty() && readQueue.empty() && 393 respQueue.empty () && drainManager) { 394 drainManager->signalDrainDone(); 395 drainManager = NULL; 396 } 397 398 // Once you're done emptying the write queue, check if there's 399 // anything in the read queue, and call schedule if required 400 schedule(nextReqEvent, busBusyUntil); 401} 402 403void 404SimpleDRAM::triggerWrites() 405{ 406 DPRINTF(DRAM, "Writes triggered at %lld\n", curTick()); 407 // Flag variable to stop any more read scheduling 408 stopReads = true; 409 410 writeStartTime = std::max(busBusyUntil, curTick()) + tWTR; 411 412 DPRINTF(DRAM, "Writes scheduled at %lld\n", writeStartTime); 413 414 assert(writeStartTime >= curTick()); 415 assert(!writeEvent.scheduled()); 416 schedule(writeEvent, writeStartTime); 417} 418 419void 420SimpleDRAM::addToWriteQueue(PacketPtr pkt) 421{ 422 // only add to the write queue here. whenever the request is 423 // eventually done, set the readyTime, and call schedule() 424 assert(pkt->isWrite()); 425 426 DRAMPacket* dram_pkt = decodeAddr(pkt); 427 428 assert(writeQueue.size() < writeBufferSize); 429 wrQLenPdf[writeQueue.size()]++; 430 431 DPRINTF(DRAM, "Adding to write queue\n"); 432 433 writeQueue.push_back(dram_pkt); 434 435 // Update stats 436 uint32_t bank_id = banksPerRank * dram_pkt->rank + dram_pkt->bank; 437 assert(bank_id < ranksPerChannel * banksPerRank); 438 perBankWrReqs[bank_id]++; 439 440 avgWrQLen = writeQueue.size(); 441 442 // we do not wait for the writes to be send to the actual memory, 443 // but instead take responsibility for the consistency here and 444 // snoop the write queue for any upcoming reads 445 446 bytesConsumedWr += pkt->getSize(); 447 bytesWritten += bytesPerCacheLine; 448 accessAndRespond(pkt); 449 450 // If your write buffer is starting to fill up, drain it! 451 if (writeQueue.size() > writeThreshold && !stopReads){ 452 triggerWrites(); 453 } 454} 455 456void 457SimpleDRAM::printParams() const 458{ 459 // Sanity check print of important parameters 460 DPRINTF(DRAM, 461 "Memory controller %s physical organization\n" \ 462 "Bytes per cacheline %d\n" \ 463 "Lines per row buffer %d\n" \ 464 "Rows per bank %d\n" \ 465 "Banks per rank %d\n" \ 466 "Ranks per channel %d\n" \ 467 "Total mem capacity %u\n", 468 name(), bytesPerCacheLine, linesPerRowBuffer, rowsPerBank, 469 banksPerRank, ranksPerChannel, bytesPerCacheLine * 470 linesPerRowBuffer * rowsPerBank * banksPerRank * ranksPerChannel); 471 472 string scheduler = memSchedPolicy == Enums::fcfs ? "FCFS" : "FR-FCFS"; 473 string address_mapping = addrMapping == Enums::openmap ? "OPENMAP" : 474 "CLOSEMAP"; 475 string page_policy = pageMgmt == Enums::open ? "OPEN" : "CLOSE"; 476 477 DPRINTF(DRAM, 478 "Memory controller %s characteristics\n" \ 479 "Read buffer size %d\n" \ 480 "Write buffer size %d\n" \ 481 "Write buffer thresh %d\n" \ 482 "Scheduler %s\n" \ 483 "Address mapping %s\n" \ 484 "Page policy %s\n", 485 name(), readBufferSize, writeBufferSize, writeThreshold, 486 scheduler, address_mapping, page_policy); 487 488 DPRINTF(DRAM, "Memory controller %s timing specs\n" \ 489 "tRCD %d ticks\n" \ 490 "tCL %d ticks\n" \ 491 "tRP %d ticks\n" \ 492 "tBURST %d ticks\n" \ 493 "tRFC %d ticks\n" \ 494 "tREFI %d ticks\n" \ 495 "tWTR %d ticks\n" \ 496 "tXAW (%d) %d ticks\n", 497 name(), tRCD, tCL, tRP, tBURST, tRFC, tREFI, tWTR, 498 activationLimit, tXAW); 499} 500 501void 502SimpleDRAM::printQs() const { 503 504 list<DRAMPacket*>::const_iterator i; 505 506 DPRINTF(DRAM, "===READ QUEUE===\n\n"); 507 for (i = readQueue.begin() ; i != readQueue.end() ; ++i) { 508 DPRINTF(DRAM, "Read %lu\n", (*i)->addr); 509 } 510 DPRINTF(DRAM, "\n===RESP QUEUE===\n\n"); 511 for (i = respQueue.begin() ; i != respQueue.end() ; ++i) { 512 DPRINTF(DRAM, "Response %lu\n", (*i)->addr); 513 } 514 DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n"); 515 for (i = writeQueue.begin() ; i != writeQueue.end() ; ++i) { 516 DPRINTF(DRAM, "Write %lu\n", (*i)->addr); 517 } 518} 519 520bool 521SimpleDRAM::recvTimingReq(PacketPtr pkt) 522{ 523 /// @todo temporary hack to deal with memory corruption issues until 524 /// 4-phase transactions are complete 525 for (int x = 0; x < pendingDelete.size(); x++) 526 delete pendingDelete[x]; 527 pendingDelete.clear(); 528 529 // This is where we enter from the outside world 530 DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n", 531 pkt->cmdString(),pkt->getAddr(), pkt->getSize()); 532 533 // simply drop inhibited packets for now 534 if (pkt->memInhibitAsserted()) { 535 DPRINTF(DRAM,"Inhibited packet -- Dropping it now\n"); 536 pendingDelete.push_back(pkt); 537 return true; 538 } 539 540 if (pkt->getSize() == bytesPerCacheLine) 541 cpuReqs++; 542 543 // Every million accesses, print the state of the queues 544 if (numReqs % 1000000 == 0) 545 printQs(); 546 547 // Calc avg gap between requests 548 if (prevArrival != 0) { 549 totGap += curTick() - prevArrival; 550 } 551 prevArrival = curTick(); 552 553 unsigned size = pkt->getSize(); 554 if (size > bytesPerCacheLine) 555 panic("Request size %d is greater than burst size %d", 556 size, bytesPerCacheLine); 557 558 // check local buffers and do not accept if full 559 if (pkt->isRead()) { 560 assert(size != 0); 561 if (readQueueFull()) { 562 DPRINTF(DRAM, "Read queue full, not accepting\n"); 563 // remember that we have to retry this port 564 retryRdReq = true; 565 numRdRetry++; 566 return false; 567 } else { 568 readPktSize[ceilLog2(size)]++; 569 addToReadQueue(pkt); 570 readReqs++; 571 numReqs++; 572 } 573 } else if (pkt->isWrite()) { 574 assert(size != 0); 575 if (writeQueueFull()) { 576 DPRINTF(DRAM, "Write queue full, not accepting\n"); 577 // remember that we have to retry this port 578 retryWrReq = true; 579 numWrRetry++; 580 return false; 581 } else { 582 writePktSize[ceilLog2(size)]++; 583 addToWriteQueue(pkt); 584 writeReqs++; 585 numReqs++; 586 } 587 } else { 588 DPRINTF(DRAM,"Neither read nor write, ignore timing\n"); 589 neitherReadNorWrite++; 590 accessAndRespond(pkt); 591 } 592 593 retryRdReq = false; 594 retryWrReq = false; 595 return true; 596} 597 598void 599SimpleDRAM::processRespondEvent() 600{ 601 DPRINTF(DRAM, 602 "processRespondEvent(): Some req has reached its readyTime\n"); 603 604 PacketPtr pkt = respQueue.front()->pkt; 605 606 // Actually responds to the requestor 607 bytesConsumedRd += pkt->getSize(); 608 bytesRead += bytesPerCacheLine; 609 accessAndRespond(pkt); 610 611 delete respQueue.front(); 612 respQueue.pop_front(); 613 614 // Update stats 615 avgRdQLen = readQueue.size() + respQueue.size(); 616 617 if (!respQueue.empty()) { 618 assert(respQueue.front()->readyTime >= curTick()); 619 assert(!respondEvent.scheduled()); 620 schedule(respondEvent, respQueue.front()->readyTime); 621 } else { 622 // if there is nothing left in any queue, signal a drain 623 if (writeQueue.empty() && readQueue.empty() && 624 drainManager) { 625 drainManager->signalDrainDone(); 626 drainManager = NULL; 627 } 628 } 629 630 // We have made a location in the queue available at this point, 631 // so if there is a read that was forced to wait, retry now 632 if (retryRdReq) { 633 retryRdReq = false; 634 port.sendRetry(); 635 } 636} 637 638void 639SimpleDRAM::chooseNextWrite() 640{ 641 // This method does the arbitration between write requests. The 642 // chosen packet is simply moved to the head of the write 643 // queue. The other methods know that this is the place to 644 // look. For example, with FCFS, this method does nothing 645 assert(!writeQueue.empty()); 646 647 if (writeQueue.size() == 1) { 648 DPRINTF(DRAMWR, "Single write request, nothing to do\n"); 649 return; 650 } 651 652 if (memSchedPolicy == Enums::fcfs) { 653 // Do nothing, since the correct request is already head 654 } else if (memSchedPolicy == Enums::frfcfs) { 655 list<DRAMPacket*>::iterator i = writeQueue.begin(); 656 bool foundRowHit = false; 657 while (!foundRowHit && i != writeQueue.end()) { 658 DRAMPacket* dram_pkt = *i; 659 const Bank& bank = dram_pkt->bank_ref; 660 if (bank.openRow == dram_pkt->row) { //FR part 661 DPRINTF(DRAMWR, "Write row buffer hit\n"); 662 writeQueue.erase(i); 663 writeQueue.push_front(dram_pkt); 664 foundRowHit = true; 665 } else { //FCFS part 666 ; 667 } 668 ++i; 669 } 670 } else 671 panic("No scheduling policy chosen\n"); 672 673 DPRINTF(DRAMWR, "Selected next write request\n"); 674} 675 676bool 677SimpleDRAM::chooseNextRead() 678{ 679 // This method does the arbitration between read requests. The 680 // chosen packet is simply moved to the head of the queue. The 681 // other methods know that this is the place to look. For example, 682 // with FCFS, this method does nothing 683 if (readQueue.empty()) { 684 DPRINTF(DRAM, "No read request to select\n"); 685 return false; 686 } 687 688 // If there is only one request then there is nothing left to do 689 if (readQueue.size() == 1) 690 return true; 691 692 if (memSchedPolicy == Enums::fcfs) { 693 // Do nothing, since the request to serve is already the first 694 // one in the read queue 695 } else if (memSchedPolicy == Enums::frfcfs) { 696 for (list<DRAMPacket*>::iterator i = readQueue.begin(); 697 i != readQueue.end() ; ++i) { 698 DRAMPacket* dram_pkt = *i; 699 const Bank& bank = dram_pkt->bank_ref; 700 // Check if it is a row hit 701 if (bank.openRow == dram_pkt->row) { //FR part 702 DPRINTF(DRAM, "Row buffer hit\n"); 703 readQueue.erase(i); 704 readQueue.push_front(dram_pkt); 705 break; 706 } else { //FCFS part 707 ; 708 } 709 } 710 } else 711 panic("No scheduling policy chosen!\n"); 712 713 DPRINTF(DRAM, "Selected next read request\n"); 714 return true; 715} 716 717void 718SimpleDRAM::accessAndRespond(PacketPtr pkt) 719{ 720 DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr()); 721 722 bool needsResponse = pkt->needsResponse(); 723 // do the actual memory access which also turns the packet into a 724 // response 725 access(pkt); 726 727 // turn packet around to go back to requester if response expected 728 if (needsResponse) { 729 // access already turned the packet into a response 730 assert(pkt->isResponse()); 731 732 // @todo someone should pay for this 733 pkt->busFirstWordDelay = pkt->busLastWordDelay = 0; 734 735 // queue the packet in the response queue to be sent out the 736 // next tick 737 port.schedTimingResp(pkt, curTick() + 1); 738 } else { 739 } 740 741 DPRINTF(DRAM, "Done\n"); 742 743 return; 744} 745 746pair<Tick, Tick> 747SimpleDRAM::estimateLatency(DRAMPacket* dram_pkt, Tick inTime) 748{ 749 // If a request reaches a bank at tick 'inTime', how much time 750 // *after* that does it take to finish the request, depending 751 // on bank status and page open policy. Note that this method 752 // considers only the time taken for the actual read or write 753 // to complete, NOT any additional time thereafter for tRAS or 754 // tRP. 755 Tick accLat = 0; 756 Tick bankLat = 0; 757 rowHitFlag = false; 758 759 const Bank& bank = dram_pkt->bank_ref; 760 if (pageMgmt == Enums::open) { // open-page policy 761 if (bank.openRow == dram_pkt->row) { 762 // When we have a row-buffer hit, 763 // we don't care about tRAS having expired or not, 764 // but do care about bank being free for access 765 rowHitFlag = true; 766 767 if (bank.freeAt < inTime) { 768 // CAS latency only 769 accLat += tCL; 770 bankLat += tCL; 771 } else { 772 accLat += 0; 773 bankLat += 0; 774 } 775 776 } else { 777 // Row-buffer miss, need to close existing row 778 // once tRAS has expired, then open the new one, 779 // then add cas latency. 780 Tick freeTime = std::max(bank.tRASDoneAt, bank.freeAt); 781 782 if (freeTime > inTime) 783 accLat += freeTime - inTime; 784 785 accLat += tRP + tRCD + tCL; 786 bankLat += tRP + tRCD + tCL; 787 } 788 } else if (pageMgmt == Enums::close) { 789 // With a close page policy, no notion of 790 // bank.tRASDoneAt 791 if (bank.freeAt > inTime) 792 accLat += bank.freeAt - inTime; 793 794 // page already closed, simply open the row, and 795 // add cas latency 796 accLat += tRCD + tCL; 797 bankLat += tRCD + tCL; 798 } else 799 panic("No page management policy chosen\n"); 800 801 DPRINTF(DRAM, "Returning < %lld, %lld > from estimateLatency()\n", 802 bankLat, accLat); 803 804 return make_pair(bankLat, accLat); 805} 806 807void 808SimpleDRAM::processNextReqEvent() 809{ 810 scheduleNextReq(); 811} 812 813void 814SimpleDRAM::recordActivate(Tick act_tick) 815{ 816 assert(actTicks.size() == activationLimit); 817 818 DPRINTF(DRAM, "Activate at tick %d\n", act_tick); 819 820 // sanity check 821 if (actTicks.back() && (act_tick - actTicks.back()) < tXAW) { 822 panic("Got %d activates in window %d (%d - %d) which is smaller " 823 "than %d\n", activationLimit, act_tick - actTicks.back(), 824 act_tick, actTicks.back(), tXAW); 825 } 826 827 // shift the times used for the book keeping, the last element 828 // (highest index) is the oldest one and hence the lowest value 829 actTicks.pop_back(); 830 831 // record an new activation (in the future) 832 actTicks.push_front(act_tick); 833 834 // cannot activate more than X times in time window tXAW, push the 835 // next one (the X + 1'st activate) to be tXAW away from the 836 // oldest in our window of X 837 if (actTicks.back() && (act_tick - actTicks.back()) < tXAW) { 838 DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate no earlier " 839 "than %d\n", activationLimit, actTicks.back() + tXAW); 840 for(int i = 0; i < ranksPerChannel; i++) 841 for(int j = 0; j < banksPerRank; j++) 842 // next activate must not happen before end of window 843 banks[i][j].freeAt = std::max(banks[i][j].freeAt, 844 actTicks.back() + tXAW); 845 } 846} 847 848void 849SimpleDRAM::doDRAMAccess(DRAMPacket* dram_pkt) 850{ 851 852 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n", 853 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row); 854 855 // estimate the bank and access latency 856 pair<Tick, Tick> lat = estimateLatency(dram_pkt, curTick()); 857 Tick bankLat = lat.first; 858 Tick accessLat = lat.second; 859 860 // This request was woken up at this time based on a prior call 861 // to estimateLatency(). However, between then and now, both the 862 // accessLatency and/or busBusyUntil may have changed. We need 863 // to correct for that. 864 865 Tick addDelay = (curTick() + accessLat < busBusyUntil) ? 866 busBusyUntil - (curTick() + accessLat) : 0; 867 868 Bank& bank = dram_pkt->bank_ref; 869 870 // Update bank state 871 if (pageMgmt == Enums::open) { 872 bank.openRow = dram_pkt->row; 873 bank.freeAt = curTick() + addDelay + accessLat; 874 // If you activated a new row do to this access, the next access 875 // will have to respect tRAS for this bank. Assume tRAS ~= 3 * tRP. 876 // Also need to account for t_XAW 877 if (!rowHitFlag) { 878 bank.tRASDoneAt = bank.freeAt + tRP; 879 recordActivate(bank.freeAt - tCL - tRCD); //since this is open page, 880 //no tRP by default 881 } 882 } else if (pageMgmt == Enums::close) { // accounting for tRAS also 883 // assuming that tRAS ~= 3 * tRP, and tRC ~= 4 * tRP, as is common 884 // (refer Jacob/Ng/Wang and Micron datasheets) 885 bank.freeAt = curTick() + addDelay + accessLat + tRP + tRP; 886 recordActivate(bank.freeAt - tRP - tRP - tCL - tRCD); //essentially (freeAt - tRC) 887 DPRINTF(DRAM,"doDRAMAccess::bank.freeAt is %lld\n",bank.freeAt); 888 } else 889 panic("No page management policy chosen\n"); 890 891 // Update request parameters 892 dram_pkt->readyTime = curTick() + addDelay + accessLat + tBURST; 893 894 895 DPRINTF(DRAM, "Req %lld: curtick is %lld accessLat is %d " \ 896 "readytime is %lld busbusyuntil is %lld. " \ 897 "Scheduling at readyTime\n", dram_pkt->addr, 898 curTick(), accessLat, dram_pkt->readyTime, busBusyUntil); 899 900 // Make sure requests are not overlapping on the databus 901 assert (dram_pkt->readyTime - busBusyUntil >= tBURST); 902 903 // Update bus state 904 busBusyUntil = dram_pkt->readyTime; 905 906 DPRINTF(DRAM,"Access time is %lld\n", 907 dram_pkt->readyTime - dram_pkt->entryTime); 908 909 // Update stats 910 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime; 911 totBankLat += bankLat; 912 totBusLat += tBURST; 913 totQLat += dram_pkt->readyTime - dram_pkt->entryTime - bankLat - tBURST; 914 915 if (rowHitFlag) 916 readRowHits++; 917 918 // At this point we're done dealing with the request 919 // It will be moved to a separate response queue with a 920 // correct readyTime, and eventually be sent back at that 921 //time 922 moveToRespQ(); 923 924 // The absolute soonest you have to start thinking about the 925 // next request is the longest access time that can occur before 926 // busBusyUntil. Assuming you need to meet tRAS, then precharge, 927 // open a new row, and access, it is ~4*tRCD. 928 929 930 Tick newTime = (busBusyUntil > 4 * tRCD) ? 931 std::max(busBusyUntil - 4 * tRCD, curTick()) : 932 curTick(); 933 934 if (!nextReqEvent.scheduled() && !stopReads){ 935 schedule(nextReqEvent, newTime); 936 } else { 937 if (newTime < nextReqEvent.when()) 938 reschedule(nextReqEvent, newTime); 939 } 940 941 942} 943 944void 945SimpleDRAM::moveToRespQ() 946{ 947 // Remove from read queue 948 DRAMPacket* dram_pkt = readQueue.front(); 949 readQueue.pop_front(); 950 951 // Insert into response queue sorted by readyTime 952 // It will be sent back to the requestor at its 953 // readyTime 954 if (respQueue.empty()) { 955 respQueue.push_front(dram_pkt); 956 assert(!respondEvent.scheduled()); 957 assert(dram_pkt->readyTime >= curTick()); 958 schedule(respondEvent, dram_pkt->readyTime); 959 } else { 960 bool done = false; 961 list<DRAMPacket*>::iterator i = respQueue.begin(); 962 while (!done && i != respQueue.end()) { 963 if ((*i)->readyTime > dram_pkt->readyTime) { 964 respQueue.insert(i, dram_pkt); 965 done = true; 966 } 967 ++i; 968 } 969 970 if (!done) 971 respQueue.push_back(dram_pkt); 972 973 assert(respondEvent.scheduled()); 974 975 if (respQueue.front()->readyTime < respondEvent.when()) { 976 assert(respQueue.front()->readyTime >= curTick()); 977 reschedule(respondEvent, respQueue.front()->readyTime); 978 } 979 } 980} 981 982void 983SimpleDRAM::scheduleNextReq() 984{ 985 DPRINTF(DRAM, "Reached scheduleNextReq()\n"); 986 987 // Figure out which read request goes next, and move it to the 988 // front of the read queue 989 if (!chooseNextRead()) { 990 // In the case there is no read request to go next, see if we 991 // are asked to drain, and if so trigger writes, this also 992 // ensures that if we hit the write limit we will do this 993 // multiple times until we are completely drained 994 if (drainManager && !writeQueue.empty() && !writeEvent.scheduled()) 995 triggerWrites(); 996 } else { 997 doDRAMAccess(readQueue.front()); 998 } 999} 1000 1001Tick 1002SimpleDRAM::maxBankFreeAt() const 1003{ 1004 Tick banksFree = 0; 1005 1006 for(int i = 0; i < ranksPerChannel; i++) 1007 for(int j = 0; j < banksPerRank; j++) 1008 banksFree = std::max(banks[i][j].freeAt, banksFree); 1009 1010 return banksFree; 1011} 1012 1013void 1014SimpleDRAM::processRefreshEvent() 1015{ 1016 DPRINTF(DRAM, "Refreshing at tick %ld\n", curTick()); 1017 1018 Tick banksFree = std::max(curTick(), maxBankFreeAt()) + tRFC; 1019 1020 for(int i = 0; i < ranksPerChannel; i++) 1021 for(int j = 0; j < banksPerRank; j++) 1022 banks[i][j].freeAt = banksFree; 1023 1024 schedule(refreshEvent, curTick() + tREFI); 1025} 1026 1027void 1028SimpleDRAM::regStats() 1029{ 1030 using namespace Stats; 1031 1032 AbstractMemory::regStats(); 1033 1034 readReqs 1035 .name(name() + ".readReqs") 1036 .desc("Total number of read requests seen"); 1037 1038 writeReqs 1039 .name(name() + ".writeReqs") 1040 .desc("Total number of write requests seen"); 1041 1042 servicedByWrQ 1043 .name(name() + ".servicedByWrQ") 1044 .desc("Number of read reqs serviced by write Q"); 1045 1046 cpuReqs 1047 .name(name() + ".cpureqs") 1048 .desc("Reqs generatd by CPU via cache - shady"); 1049 1050 neitherReadNorWrite 1051 .name(name() + ".neitherReadNorWrite") 1052 .desc("Reqs where no action is needed"); 1053 1054 perBankRdReqs 1055 .init(banksPerRank * ranksPerChannel) 1056 .name(name() + ".perBankRdReqs") 1057 .desc("Track reads on a per bank basis"); 1058 1059 perBankWrReqs 1060 .init(banksPerRank * ranksPerChannel) 1061 .name(name() + ".perBankWrReqs") 1062 .desc("Track writes on a per bank basis"); 1063 1064 avgRdQLen 1065 .name(name() + ".avgRdQLen") 1066 .desc("Average read queue length over time") 1067 .precision(2); 1068 1069 avgWrQLen 1070 .name(name() + ".avgWrQLen") 1071 .desc("Average write queue length over time") 1072 .precision(2); 1073 1074 totQLat 1075 .name(name() + ".totQLat") 1076 .desc("Total cycles spent in queuing delays"); 1077 1078 totBankLat 1079 .name(name() + ".totBankLat") 1080 .desc("Total cycles spent in bank access"); 1081 1082 totBusLat 1083 .name(name() + ".totBusLat") 1084 .desc("Total cycles spent in databus access"); 1085 1086 totMemAccLat 1087 .name(name() + ".totMemAccLat") 1088 .desc("Sum of mem lat for all requests"); 1089 1090 avgQLat 1091 .name(name() + ".avgQLat") 1092 .desc("Average queueing delay per request") 1093 .precision(2); 1094 1095 avgQLat = totQLat / (readReqs - servicedByWrQ); 1096 1097 avgBankLat 1098 .name(name() + ".avgBankLat") 1099 .desc("Average bank access latency per request") 1100 .precision(2); 1101 1102 avgBankLat = totBankLat / (readReqs - servicedByWrQ); 1103 1104 avgBusLat 1105 .name(name() + ".avgBusLat") 1106 .desc("Average bus latency per request") 1107 .precision(2); 1108 1109 avgBusLat = totBusLat / (readReqs - servicedByWrQ); 1110 1111 avgMemAccLat 1112 .name(name() + ".avgMemAccLat") 1113 .desc("Average memory access latency") 1114 .precision(2); 1115 1116 avgMemAccLat = totMemAccLat / (readReqs - servicedByWrQ); 1117 1118 numRdRetry 1119 .name(name() + ".numRdRetry") 1120 .desc("Number of times rd buffer was full causing retry"); 1121 1122 numWrRetry 1123 .name(name() + ".numWrRetry") 1124 .desc("Number of times wr buffer was full causing retry"); 1125 1126 readRowHits 1127 .name(name() + ".readRowHits") 1128 .desc("Number of row buffer hits during reads"); 1129 1130 writeRowHits 1131 .name(name() + ".writeRowHits") 1132 .desc("Number of row buffer hits during writes"); 1133 1134 readRowHitRate 1135 .name(name() + ".readRowHitRate") 1136 .desc("Row buffer hit rate for reads") 1137 .precision(2); 1138 1139 readRowHitRate = (readRowHits / (readReqs - servicedByWrQ)) * 100; 1140 1141 writeRowHitRate 1142 .name(name() + ".writeRowHitRate") 1143 .desc("Row buffer hit rate for writes") 1144 .precision(2); 1145 1146 writeRowHitRate = (writeRowHits / writeReqs) * 100; 1147 1148 readPktSize 1149 .init(ceilLog2(bytesPerCacheLine) + 1) 1150 .name(name() + ".readPktSize") 1151 .desc("Categorize read packet sizes"); 1152 1153 writePktSize 1154 .init(ceilLog2(bytesPerCacheLine) + 1) 1155 .name(name() + ".writePktSize") 1156 .desc("Categorize write packet sizes"); 1157 1158 rdQLenPdf 1159 .init(readBufferSize) 1160 .name(name() + ".rdQLenPdf") 1161 .desc("What read queue length does an incoming req see"); 1162 1163 wrQLenPdf 1164 .init(writeBufferSize) 1165 .name(name() + ".wrQLenPdf") 1166 .desc("What write queue length does an incoming req see"); 1167 1168 1169 bytesRead 1170 .name(name() + ".bytesRead") 1171 .desc("Total number of bytes read from memory"); 1172 1173 bytesWritten 1174 .name(name() + ".bytesWritten") 1175 .desc("Total number of bytes written to memory"); 1176 1177 bytesConsumedRd 1178 .name(name() + ".bytesConsumedRd") 1179 .desc("bytesRead derated as per pkt->getSize()"); 1180 1181 bytesConsumedWr 1182 .name(name() + ".bytesConsumedWr") 1183 .desc("bytesWritten derated as per pkt->getSize()"); 1184 1185 avgRdBW 1186 .name(name() + ".avgRdBW") 1187 .desc("Average achieved read bandwidth in MB/s") 1188 .precision(2); 1189 1190 avgRdBW = (bytesRead / 1000000) / simSeconds; 1191 1192 avgWrBW 1193 .name(name() + ".avgWrBW") 1194 .desc("Average achieved write bandwidth in MB/s") 1195 .precision(2); 1196 1197 avgWrBW = (bytesWritten / 1000000) / simSeconds; 1198 1199 avgConsumedRdBW 1200 .name(name() + ".avgConsumedRdBW") 1201 .desc("Average consumed read bandwidth in MB/s") 1202 .precision(2); 1203 1204 avgConsumedRdBW = (bytesConsumedRd / 1000000) / simSeconds; 1205 1206 avgConsumedWrBW 1207 .name(name() + ".avgConsumedWrBW") 1208 .desc("Average consumed write bandwidth in MB/s") 1209 .precision(2); 1210 1211 avgConsumedWrBW = (bytesConsumedWr / 1000000) / simSeconds; 1212 1213 peakBW 1214 .name(name() + ".peakBW") 1215 .desc("Theoretical peak bandwidth in MB/s") 1216 .precision(2); 1217 1218 peakBW = (SimClock::Frequency / tBURST) * bytesPerCacheLine / 1000000; 1219 1220 busUtil 1221 .name(name() + ".busUtil") 1222 .desc("Data bus utilization in percentage") 1223 .precision(2); 1224 1225 busUtil = (avgRdBW + avgWrBW) / peakBW * 100; 1226 1227 totGap 1228 .name(name() + ".totGap") 1229 .desc("Total gap between requests"); 1230 1231 avgGap 1232 .name(name() + ".avgGap") 1233 .desc("Average gap between requests") 1234 .precision(2); 1235 1236 avgGap = totGap / (readReqs + writeReqs); 1237} 1238 1239void 1240SimpleDRAM::recvFunctional(PacketPtr pkt) 1241{ 1242 // rely on the abstract memory 1243 functionalAccess(pkt); 1244} 1245 1246BaseSlavePort& 1247SimpleDRAM::getSlavePort(const string &if_name, PortID idx) 1248{ 1249 if (if_name != "port") { 1250 return MemObject::getSlavePort(if_name, idx); 1251 } else { 1252 return port; 1253 } 1254} 1255 1256unsigned int 1257SimpleDRAM::drain(DrainManager *dm) 1258{ 1259 unsigned int count = port.drain(dm); 1260 1261 // if there is anything in any of our internal queues, keep track 1262 // of that as well 1263 if (!(writeQueue.empty() && readQueue.empty() && 1264 respQueue.empty())) { 1265 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d," 1266 " resp: %d\n", writeQueue.size(), readQueue.size(), 1267 respQueue.size()); 1268 ++count; 1269 drainManager = dm; 1270 // the only part that is not drained automatically over time 1271 // is the write queue, thus trigger writes if there are any 1272 // waiting and no reads waiting, otherwise wait until the 1273 // reads are done 1274 if (readQueue.empty() && !writeQueue.empty() && 1275 !writeEvent.scheduled()) 1276 triggerWrites(); 1277 } 1278 1279 if (count) 1280 setDrainState(Drainable::Draining); 1281 else 1282 setDrainState(Drainable::Drained); 1283 return count; 1284} 1285 1286SimpleDRAM::MemoryPort::MemoryPort(const std::string& name, SimpleDRAM& _memory) 1287 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this), 1288 memory(_memory) 1289{ } 1290 1291AddrRangeList 1292SimpleDRAM::MemoryPort::getAddrRanges() const 1293{ 1294 AddrRangeList ranges; 1295 ranges.push_back(memory.getAddrRange()); 1296 return ranges; 1297} 1298 1299void 1300SimpleDRAM::MemoryPort::recvFunctional(PacketPtr pkt) 1301{ 1302 pkt->pushLabel(memory.name()); 1303 1304 if (!queue.checkFunctional(pkt)) { 1305 // Default implementation of SimpleTimingPort::recvFunctional() 1306 // calls recvAtomic() and throws away the latency; we can save a 1307 // little here by just not calculating the latency. 1308 memory.recvFunctional(pkt); 1309 } 1310 1311 pkt->popLabel(); 1312} 1313 1314Tick 1315SimpleDRAM::MemoryPort::recvAtomic(PacketPtr pkt) 1316{ 1317 return memory.recvAtomic(pkt); 1318} 1319 1320bool 1321SimpleDRAM::MemoryPort::recvTimingReq(PacketPtr pkt) 1322{ 1323 // pass it to the memory controller 1324 return memory.recvTimingReq(pkt); 1325} 1326 1327SimpleDRAM* 1328SimpleDRAMParams::create() 1329{ 1330 return new SimpleDRAM(this); 1331} 1332