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