mem: Replace EventWrapper use with EventFunctionWrapper
[gem5.git] / src / mem / dram_ctrl.cc
1 /*
2 * Copyright (c) 2010-2017 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 * Omar Naji
44 * Wendy Elsasser
45 */
46
47 #include "mem/dram_ctrl.hh"
48
49 #include "base/bitfield.hh"
50 #include "base/trace.hh"
51 #include "debug/DRAM.hh"
52 #include "debug/DRAMPower.hh"
53 #include "debug/DRAMState.hh"
54 #include "debug/Drain.hh"
55 #include "sim/system.hh"
56
57 using namespace std;
58 using namespace Data;
59
60 DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
61 AbstractMemory(p),
62 port(name() + ".port", *this), isTimingMode(false),
63 retryRdReq(false), retryWrReq(false),
64 busState(READ),
65 busStateNext(READ),
66 nextReqEvent([this]{ processNextReqEvent(); }, name()),
67 respondEvent([this]{ processRespondEvent(); }, name()),
68 deviceSize(p->device_size),
69 deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
70 deviceRowBufferSize(p->device_rowbuffer_size),
71 devicesPerRank(p->devices_per_rank),
72 burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8),
73 rowBufferSize(devicesPerRank * deviceRowBufferSize),
74 columnsPerRowBuffer(rowBufferSize / burstSize),
75 columnsPerStripe(range.interleaved() ? range.granularity() / burstSize : 1),
76 ranksPerChannel(p->ranks_per_channel),
77 bankGroupsPerRank(p->bank_groups_per_rank),
78 bankGroupArch(p->bank_groups_per_rank > 0),
79 banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0),
80 readBufferSize(p->read_buffer_size),
81 writeBufferSize(p->write_buffer_size),
82 writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0),
83 writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0),
84 minWritesPerSwitch(p->min_writes_per_switch),
85 writesThisTime(0), readsThisTime(0),
86 tCK(p->tCK), tWTR(p->tWTR), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST),
87 tCCD_L(p->tCCD_L), tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
88 tWR(p->tWR), tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
89 tRRD_L(p->tRRD_L), tXAW(p->tXAW), tXP(p->tXP), tXS(p->tXS),
90 activationLimit(p->activation_limit),
91 memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
92 pageMgmt(p->page_policy),
93 maxAccessesPerRow(p->max_accesses_per_row),
94 frontendLatency(p->static_frontend_latency),
95 backendLatency(p->static_backend_latency),
96 busBusyUntil(0), prevArrival(0),
97 nextReqTime(0), activeRank(0), timeStampOffset(0)
98 {
99 // sanity check the ranks since we rely on bit slicing for the
100 // address decoding
101 fatal_if(!isPowerOf2(ranksPerChannel), "DRAM rank count of %d is not "
102 "allowed, must be a power of two\n", ranksPerChannel);
103
104 fatal_if(!isPowerOf2(burstSize), "DRAM burst size %d is not allowed, "
105 "must be a power of two\n", burstSize);
106
107 for (int i = 0; i < ranksPerChannel; i++) {
108 Rank* rank = new Rank(*this, p, i);
109 ranks.push_back(rank);
110 }
111
112 // perform a basic check of the write thresholds
113 if (p->write_low_thresh_perc >= p->write_high_thresh_perc)
114 fatal("Write buffer low threshold %d must be smaller than the "
115 "high threshold %d\n", p->write_low_thresh_perc,
116 p->write_high_thresh_perc);
117
118 // determine the rows per bank by looking at the total capacity
119 uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
120
121 // determine the dram actual capacity from the DRAM config in Mbytes
122 uint64_t deviceCapacity = deviceSize / (1024 * 1024) * devicesPerRank *
123 ranksPerChannel;
124
125 // if actual DRAM size does not match memory capacity in system warn!
126 if (deviceCapacity != capacity / (1024 * 1024))
127 warn("DRAM device capacity (%d Mbytes) does not match the "
128 "address range assigned (%d Mbytes)\n", deviceCapacity,
129 capacity / (1024 * 1024));
130
131 DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
132 AbstractMemory::size());
133
134 DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
135 rowBufferSize, columnsPerRowBuffer);
136
137 rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
138
139 // some basic sanity checks
140 if (tREFI <= tRP || tREFI <= tRFC) {
141 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
142 tREFI, tRP, tRFC);
143 }
144
145 // basic bank group architecture checks ->
146 if (bankGroupArch) {
147 // must have at least one bank per bank group
148 if (bankGroupsPerRank > banksPerRank) {
149 fatal("banks per rank (%d) must be equal to or larger than "
150 "banks groups per rank (%d)\n",
151 banksPerRank, bankGroupsPerRank);
152 }
153 // must have same number of banks in each bank group
154 if ((banksPerRank % bankGroupsPerRank) != 0) {
155 fatal("Banks per rank (%d) must be evenly divisible by bank groups "
156 "per rank (%d) for equal banks per bank group\n",
157 banksPerRank, bankGroupsPerRank);
158 }
159 // tCCD_L should be greater than minimal, back-to-back burst delay
160 if (tCCD_L <= tBURST) {
161 fatal("tCCD_L (%d) should be larger than tBURST (%d) when "
162 "bank groups per rank (%d) is greater than 1\n",
163 tCCD_L, tBURST, bankGroupsPerRank);
164 }
165 // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
166 // some datasheets might specify it equal to tRRD
167 if (tRRD_L < tRRD) {
168 fatal("tRRD_L (%d) should be larger than tRRD (%d) when "
169 "bank groups per rank (%d) is greater than 1\n",
170 tRRD_L, tRRD, bankGroupsPerRank);
171 }
172 }
173
174 }
175
176 void
177 DRAMCtrl::init()
178 {
179 AbstractMemory::init();
180
181 if (!port.isConnected()) {
182 fatal("DRAMCtrl %s is unconnected!\n", name());
183 } else {
184 port.sendRangeChange();
185 }
186
187 // a bit of sanity checks on the interleaving, save it for here to
188 // ensure that the system pointer is initialised
189 if (range.interleaved()) {
190 if (channels != range.stripes())
191 fatal("%s has %d interleaved address stripes but %d channel(s)\n",
192 name(), range.stripes(), channels);
193
194 if (addrMapping == Enums::RoRaBaChCo) {
195 if (rowBufferSize != range.granularity()) {
196 fatal("Channel interleaving of %s doesn't match RoRaBaChCo "
197 "address map\n", name());
198 }
199 } else if (addrMapping == Enums::RoRaBaCoCh ||
200 addrMapping == Enums::RoCoRaBaCh) {
201 // for the interleavings with channel bits in the bottom,
202 // if the system uses a channel striping granularity that
203 // is larger than the DRAM burst size, then map the
204 // sequential accesses within a stripe to a number of
205 // columns in the DRAM, effectively placing some of the
206 // lower-order column bits as the least-significant bits
207 // of the address (above the ones denoting the burst size)
208 assert(columnsPerStripe >= 1);
209
210 // channel striping has to be done at a granularity that
211 // is equal or larger to a cache line
212 if (system()->cacheLineSize() > range.granularity()) {
213 fatal("Channel interleaving of %s must be at least as large "
214 "as the cache line size\n", name());
215 }
216
217 // ...and equal or smaller than the row-buffer size
218 if (rowBufferSize < range.granularity()) {
219 fatal("Channel interleaving of %s must be at most as large "
220 "as the row-buffer size\n", name());
221 }
222 // this is essentially the check above, so just to be sure
223 assert(columnsPerStripe <= columnsPerRowBuffer);
224 }
225 }
226 }
227
228 void
229 DRAMCtrl::startup()
230 {
231 // remember the memory system mode of operation
232 isTimingMode = system()->isTimingMode();
233
234 if (isTimingMode) {
235 // timestamp offset should be in clock cycles for DRAMPower
236 timeStampOffset = divCeil(curTick(), tCK);
237
238 // update the start tick for the precharge accounting to the
239 // current tick
240 for (auto r : ranks) {
241 r->startup(curTick() + tREFI - tRP);
242 }
243
244 // shift the bus busy time sufficiently far ahead that we never
245 // have to worry about negative values when computing the time for
246 // the next request, this will add an insignificant bubble at the
247 // start of simulation
248 busBusyUntil = curTick() + tRP + tRCD + tCL;
249 }
250 }
251
252 Tick
253 DRAMCtrl::recvAtomic(PacketPtr pkt)
254 {
255 DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
256
257 panic_if(pkt->cacheResponding(), "Should not see packets where cache "
258 "is responding");
259
260 // do the actual memory access and turn the packet into a response
261 access(pkt);
262
263 Tick latency = 0;
264 if (pkt->hasData()) {
265 // this value is not supposed to be accurate, just enough to
266 // keep things going, mimic a closed page
267 latency = tRP + tRCD + tCL;
268 }
269 return latency;
270 }
271
272 bool
273 DRAMCtrl::readQueueFull(unsigned int neededEntries) const
274 {
275 DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
276 readBufferSize, readQueue.size() + respQueue.size(),
277 neededEntries);
278
279 return
280 (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
281 }
282
283 bool
284 DRAMCtrl::writeQueueFull(unsigned int neededEntries) const
285 {
286 DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
287 writeBufferSize, writeQueue.size(), neededEntries);
288 return (writeQueue.size() + neededEntries) > writeBufferSize;
289 }
290
291 DRAMCtrl::DRAMPacket*
292 DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size,
293 bool isRead)
294 {
295 // decode the address based on the address mapping scheme, with
296 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
297 // channel, respectively
298 uint8_t rank;
299 uint8_t bank;
300 // use a 64-bit unsigned during the computations as the row is
301 // always the top bits, and check before creating the DRAMPacket
302 uint64_t row;
303
304 // truncate the address to a DRAM burst, which makes it unique to
305 // a specific column, row, bank, rank and channel
306 Addr addr = dramPktAddr / burstSize;
307
308 // we have removed the lowest order address bits that denote the
309 // position within the column
310 if (addrMapping == Enums::RoRaBaChCo) {
311 // the lowest order bits denote the column to ensure that
312 // sequential cache lines occupy the same row
313 addr = addr / columnsPerRowBuffer;
314
315 // take out the channel part of the address
316 addr = addr / channels;
317
318 // after the channel bits, get the bank bits to interleave
319 // over the banks
320 bank = addr % banksPerRank;
321 addr = addr / banksPerRank;
322
323 // after the bank, we get the rank bits which thus interleaves
324 // over the ranks
325 rank = addr % ranksPerChannel;
326 addr = addr / ranksPerChannel;
327
328 // lastly, get the row bits, no need to remove them from addr
329 row = addr % rowsPerBank;
330 } else if (addrMapping == Enums::RoRaBaCoCh) {
331 // take out the lower-order column bits
332 addr = addr / columnsPerStripe;
333
334 // take out the channel part of the address
335 addr = addr / channels;
336
337 // next, the higher-order column bites
338 addr = addr / (columnsPerRowBuffer / columnsPerStripe);
339
340 // after the column bits, we get the bank bits to interleave
341 // over the banks
342 bank = addr % banksPerRank;
343 addr = addr / banksPerRank;
344
345 // after the bank, we get the rank bits which thus interleaves
346 // over the ranks
347 rank = addr % ranksPerChannel;
348 addr = addr / ranksPerChannel;
349
350 // lastly, get the row bits, no need to remove them from addr
351 row = addr % rowsPerBank;
352 } else if (addrMapping == Enums::RoCoRaBaCh) {
353 // optimise for closed page mode and utilise maximum
354 // parallelism of the DRAM (at the cost of power)
355
356 // take out the lower-order column bits
357 addr = addr / columnsPerStripe;
358
359 // take out the channel part of the address, not that this has
360 // to match with how accesses are interleaved between the
361 // controllers in the address mapping
362 addr = addr / channels;
363
364 // start with the bank bits, as this provides the maximum
365 // opportunity for parallelism between requests
366 bank = addr % banksPerRank;
367 addr = addr / banksPerRank;
368
369 // next get the rank bits
370 rank = addr % ranksPerChannel;
371 addr = addr / ranksPerChannel;
372
373 // next, the higher-order column bites
374 addr = addr / (columnsPerRowBuffer / columnsPerStripe);
375
376 // lastly, get the row bits, no need to remove them from addr
377 row = addr % rowsPerBank;
378 } else
379 panic("Unknown address mapping policy chosen!");
380
381 assert(rank < ranksPerChannel);
382 assert(bank < banksPerRank);
383 assert(row < rowsPerBank);
384 assert(row < Bank::NO_ROW);
385
386 DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
387 dramPktAddr, rank, bank, row);
388
389 // create the corresponding DRAM packet with the entry time and
390 // ready time set to the current tick, the latter will be updated
391 // later
392 uint16_t bank_id = banksPerRank * rank + bank;
393 return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
394 size, ranks[rank]->banks[bank], *ranks[rank]);
395 }
396
397 void
398 DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
399 {
400 // only add to the read queue here. whenever the request is
401 // eventually done, set the readyTime, and call schedule()
402 assert(!pkt->isWrite());
403
404 assert(pktCount != 0);
405
406 // if the request size is larger than burst size, the pkt is split into
407 // multiple DRAM packets
408 // Note if the pkt starting address is not aligened to burst size, the
409 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
410 // are aligned to burst size boundaries. This is to ensure we accurately
411 // check read packets against packets in write queue.
412 Addr addr = pkt->getAddr();
413 unsigned pktsServicedByWrQ = 0;
414 BurstHelper* burst_helper = NULL;
415 for (int cnt = 0; cnt < pktCount; ++cnt) {
416 unsigned size = std::min((addr | (burstSize - 1)) + 1,
417 pkt->getAddr() + pkt->getSize()) - addr;
418 readPktSize[ceilLog2(size)]++;
419 readBursts++;
420
421 // First check write buffer to see if the data is already at
422 // the controller
423 bool foundInWrQ = false;
424 Addr burst_addr = burstAlign(addr);
425 // if the burst address is not present then there is no need
426 // looking any further
427 if (isInWriteQueue.find(burst_addr) != isInWriteQueue.end()) {
428 for (const auto& p : writeQueue) {
429 // check if the read is subsumed in the write queue
430 // packet we are looking at
431 if (p->addr <= addr && (addr + size) <= (p->addr + p->size)) {
432 foundInWrQ = true;
433 servicedByWrQ++;
434 pktsServicedByWrQ++;
435 DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
436 "write queue\n", addr, size);
437 bytesReadWrQ += burstSize;
438 break;
439 }
440 }
441 }
442
443 // If not found in the write q, make a DRAM packet and
444 // push it onto the read queue
445 if (!foundInWrQ) {
446
447 // Make the burst helper for split packets
448 if (pktCount > 1 && burst_helper == NULL) {
449 DPRINTF(DRAM, "Read to addr %lld translates to %d "
450 "dram requests\n", pkt->getAddr(), pktCount);
451 burst_helper = new BurstHelper(pktCount);
452 }
453
454 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
455 dram_pkt->burstHelper = burst_helper;
456
457 assert(!readQueueFull(1));
458 rdQLenPdf[readQueue.size() + respQueue.size()]++;
459
460 DPRINTF(DRAM, "Adding to read queue\n");
461
462 readQueue.push_back(dram_pkt);
463
464 // increment read entries of the rank
465 ++dram_pkt->rankRef.readEntries;
466
467 // Update stats
468 avgRdQLen = readQueue.size() + respQueue.size();
469 }
470
471 // Starting address of next dram pkt (aligend to burstSize boundary)
472 addr = (addr | (burstSize - 1)) + 1;
473 }
474
475 // If all packets are serviced by write queue, we send the repsonse back
476 if (pktsServicedByWrQ == pktCount) {
477 accessAndRespond(pkt, frontendLatency);
478 return;
479 }
480
481 // Update how many split packets are serviced by write queue
482 if (burst_helper != NULL)
483 burst_helper->burstsServiced = pktsServicedByWrQ;
484
485 // If we are not already scheduled to get a request out of the
486 // queue, do so now
487 if (!nextReqEvent.scheduled()) {
488 DPRINTF(DRAM, "Request scheduled immediately\n");
489 schedule(nextReqEvent, curTick());
490 }
491 }
492
493 void
494 DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
495 {
496 // only add to the write queue here. whenever the request is
497 // eventually done, set the readyTime, and call schedule()
498 assert(pkt->isWrite());
499
500 // if the request size is larger than burst size, the pkt is split into
501 // multiple DRAM packets
502 Addr addr = pkt->getAddr();
503 for (int cnt = 0; cnt < pktCount; ++cnt) {
504 unsigned size = std::min((addr | (burstSize - 1)) + 1,
505 pkt->getAddr() + pkt->getSize()) - addr;
506 writePktSize[ceilLog2(size)]++;
507 writeBursts++;
508
509 // see if we can merge with an existing item in the write
510 // queue and keep track of whether we have merged or not
511 bool merged = isInWriteQueue.find(burstAlign(addr)) !=
512 isInWriteQueue.end();
513
514 // if the item was not merged we need to create a new write
515 // and enqueue it
516 if (!merged) {
517 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
518
519 assert(writeQueue.size() < writeBufferSize);
520 wrQLenPdf[writeQueue.size()]++;
521
522 DPRINTF(DRAM, "Adding to write queue\n");
523
524 writeQueue.push_back(dram_pkt);
525 isInWriteQueue.insert(burstAlign(addr));
526 assert(writeQueue.size() == isInWriteQueue.size());
527
528 // Update stats
529 avgWrQLen = writeQueue.size();
530
531 // increment write entries of the rank
532 ++dram_pkt->rankRef.writeEntries;
533 } else {
534 DPRINTF(DRAM, "Merging write burst with existing queue entry\n");
535
536 // keep track of the fact that this burst effectively
537 // disappeared as it was merged with an existing one
538 mergedWrBursts++;
539 }
540
541 // Starting address of next dram pkt (aligend to burstSize boundary)
542 addr = (addr | (burstSize - 1)) + 1;
543 }
544
545 // we do not wait for the writes to be send to the actual memory,
546 // but instead take responsibility for the consistency here and
547 // snoop the write queue for any upcoming reads
548 // @todo, if a pkt size is larger than burst size, we might need a
549 // different front end latency
550 accessAndRespond(pkt, frontendLatency);
551
552 // If we are not already scheduled to get a request out of the
553 // queue, do so now
554 if (!nextReqEvent.scheduled()) {
555 DPRINTF(DRAM, "Request scheduled immediately\n");
556 schedule(nextReqEvent, curTick());
557 }
558 }
559
560 void
561 DRAMCtrl::printQs() const {
562 DPRINTF(DRAM, "===READ QUEUE===\n\n");
563 for (auto i = readQueue.begin() ; i != readQueue.end() ; ++i) {
564 DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
565 }
566 DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
567 for (auto i = respQueue.begin() ; i != respQueue.end() ; ++i) {
568 DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
569 }
570 DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
571 for (auto i = writeQueue.begin() ; i != writeQueue.end() ; ++i) {
572 DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
573 }
574 }
575
576 bool
577 DRAMCtrl::recvTimingReq(PacketPtr pkt)
578 {
579 // This is where we enter from the outside world
580 DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
581 pkt->cmdString(), pkt->getAddr(), pkt->getSize());
582
583 panic_if(pkt->cacheResponding(), "Should not see packets where cache "
584 "is responding");
585
586 panic_if(!(pkt->isRead() || pkt->isWrite()),
587 "Should only see read and writes at memory controller\n");
588
589 // Calc avg gap between requests
590 if (prevArrival != 0) {
591 totGap += curTick() - prevArrival;
592 }
593 prevArrival = curTick();
594
595
596 // Find out how many dram packets a pkt translates to
597 // If the burst size is equal or larger than the pkt size, then a pkt
598 // translates to only one dram packet. Otherwise, a pkt translates to
599 // multiple dram packets
600 unsigned size = pkt->getSize();
601 unsigned offset = pkt->getAddr() & (burstSize - 1);
602 unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
603
604 // check local buffers and do not accept if full
605 if (pkt->isRead()) {
606 assert(size != 0);
607 if (readQueueFull(dram_pkt_count)) {
608 DPRINTF(DRAM, "Read queue full, not accepting\n");
609 // remember that we have to retry this port
610 retryRdReq = true;
611 numRdRetry++;
612 return false;
613 } else {
614 addToReadQueue(pkt, dram_pkt_count);
615 readReqs++;
616 bytesReadSys += size;
617 }
618 } else {
619 assert(pkt->isWrite());
620 assert(size != 0);
621 if (writeQueueFull(dram_pkt_count)) {
622 DPRINTF(DRAM, "Write queue full, not accepting\n");
623 // remember that we have to retry this port
624 retryWrReq = true;
625 numWrRetry++;
626 return false;
627 } else {
628 addToWriteQueue(pkt, dram_pkt_count);
629 writeReqs++;
630 bytesWrittenSys += size;
631 }
632 }
633
634 return true;
635 }
636
637 void
638 DRAMCtrl::processRespondEvent()
639 {
640 DPRINTF(DRAM,
641 "processRespondEvent(): Some req has reached its readyTime\n");
642
643 DRAMPacket* dram_pkt = respQueue.front();
644
645 // if a read has reached its ready-time, decrement the number of reads
646 // At this point the packet has been handled and there is a possibility
647 // to switch to low-power mode if no other packet is available
648 --dram_pkt->rankRef.readEntries;
649 DPRINTF(DRAM, "number of read entries for rank %d is %d\n",
650 dram_pkt->rank, dram_pkt->rankRef.readEntries);
651
652 // counter should at least indicate one outstanding request
653 // for this read
654 assert(dram_pkt->rankRef.outstandingEvents > 0);
655 // read response received, decrement count
656 --dram_pkt->rankRef.outstandingEvents;
657
658 // at this moment should not have transitioned to a low-power state
659 assert((dram_pkt->rankRef.pwrState != PWR_SREF) &&
660 (dram_pkt->rankRef.pwrState != PWR_PRE_PDN) &&
661 (dram_pkt->rankRef.pwrState != PWR_ACT_PDN));
662
663 // track if this is the last packet before idling
664 // and that there are no outstanding commands to this rank
665 // if REF in progress, transition to LP state should not occur
666 // until REF completes
667 if ((dram_pkt->rankRef.refreshState == REF_IDLE) &&
668 (dram_pkt->rankRef.lowPowerEntryReady())) {
669 // verify that there are no events scheduled
670 assert(!dram_pkt->rankRef.activateEvent.scheduled());
671 assert(!dram_pkt->rankRef.prechargeEvent.scheduled());
672
673 // if coming from active state, schedule power event to
674 // active power-down else go to precharge power-down
675 DPRINTF(DRAMState, "Rank %d sleep at tick %d; current power state is "
676 "%d\n", dram_pkt->rank, curTick(), dram_pkt->rankRef.pwrState);
677
678 // default to ACT power-down unless already in IDLE state
679 // could be in IDLE if PRE issued before data returned
680 PowerState next_pwr_state = PWR_ACT_PDN;
681 if (dram_pkt->rankRef.pwrState == PWR_IDLE) {
682 next_pwr_state = PWR_PRE_PDN;
683 }
684
685 dram_pkt->rankRef.powerDownSleep(next_pwr_state, curTick());
686 }
687
688 if (dram_pkt->burstHelper) {
689 // it is a split packet
690 dram_pkt->burstHelper->burstsServiced++;
691 if (dram_pkt->burstHelper->burstsServiced ==
692 dram_pkt->burstHelper->burstCount) {
693 // we have now serviced all children packets of a system packet
694 // so we can now respond to the requester
695 // @todo we probably want to have a different front end and back
696 // end latency for split packets
697 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
698 delete dram_pkt->burstHelper;
699 dram_pkt->burstHelper = NULL;
700 }
701 } else {
702 // it is not a split packet
703 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
704 }
705
706 delete respQueue.front();
707 respQueue.pop_front();
708
709 if (!respQueue.empty()) {
710 assert(respQueue.front()->readyTime >= curTick());
711 assert(!respondEvent.scheduled());
712 schedule(respondEvent, respQueue.front()->readyTime);
713 } else {
714 // if there is nothing left in any queue, signal a drain
715 if (drainState() == DrainState::Draining &&
716 writeQueue.empty() && readQueue.empty() && allRanksDrained()) {
717
718 DPRINTF(Drain, "DRAM controller done draining\n");
719 signalDrainDone();
720 }
721 }
722
723 // We have made a location in the queue available at this point,
724 // so if there is a read that was forced to wait, retry now
725 if (retryRdReq) {
726 retryRdReq = false;
727 port.sendRetryReq();
728 }
729 }
730
731 bool
732 DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
733 {
734 // This method does the arbitration between requests. The chosen
735 // packet is simply moved to the head of the queue. The other
736 // methods know that this is the place to look. For example, with
737 // FCFS, this method does nothing
738 assert(!queue.empty());
739
740 // bool to indicate if a packet to an available rank is found
741 bool found_packet = false;
742 if (queue.size() == 1) {
743 DRAMPacket* dram_pkt = queue.front();
744 // available rank corresponds to state refresh idle
745 if (ranks[dram_pkt->rank]->isAvailable()) {
746 found_packet = true;
747 DPRINTF(DRAM, "Single request, going to a free rank\n");
748 } else {
749 DPRINTF(DRAM, "Single request, going to a busy rank\n");
750 }
751 return found_packet;
752 }
753
754 if (memSchedPolicy == Enums::fcfs) {
755 // check if there is a packet going to a free rank
756 for (auto i = queue.begin(); i != queue.end() ; ++i) {
757 DRAMPacket* dram_pkt = *i;
758 if (ranks[dram_pkt->rank]->isAvailable()) {
759 queue.erase(i);
760 queue.push_front(dram_pkt);
761 found_packet = true;
762 break;
763 }
764 }
765 } else if (memSchedPolicy == Enums::frfcfs) {
766 found_packet = reorderQueue(queue, extra_col_delay);
767 } else
768 panic("No scheduling policy chosen\n");
769 return found_packet;
770 }
771
772 bool
773 DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
774 {
775 // Only determine this if needed
776 uint64_t earliest_banks = 0;
777 bool hidden_bank_prep = false;
778
779 // search for seamless row hits first, if no seamless row hit is
780 // found then determine if there are other packets that can be issued
781 // without incurring additional bus delay due to bank timing
782 // Will select closed rows first to enable more open row possibilies
783 // in future selections
784 bool found_hidden_bank = false;
785
786 // remember if we found a row hit, not seamless, but bank prepped
787 // and ready
788 bool found_prepped_pkt = false;
789
790 // if we have no row hit, prepped or not, and no seamless packet,
791 // just go for the earliest possible
792 bool found_earliest_pkt = false;
793
794 auto selected_pkt_it = queue.end();
795
796 // time we need to issue a column command to be seamless
797 const Tick min_col_at = std::max(busBusyUntil - tCL + extra_col_delay,
798 curTick());
799
800 for (auto i = queue.begin(); i != queue.end() ; ++i) {
801 DRAMPacket* dram_pkt = *i;
802 const Bank& bank = dram_pkt->bankRef;
803
804 // check if rank is available, if not, jump to the next packet
805 if (dram_pkt->rankRef.isAvailable()) {
806 // check if it is a row hit
807 if (bank.openRow == dram_pkt->row) {
808 // no additional rank-to-rank or same bank-group
809 // delays, or we switched read/write and might as well
810 // go for the row hit
811 if (bank.colAllowedAt <= min_col_at) {
812 // FCFS within the hits, giving priority to
813 // commands that can issue seamlessly, without
814 // additional delay, such as same rank accesses
815 // and/or different bank-group accesses
816 DPRINTF(DRAM, "Seamless row buffer hit\n");
817 selected_pkt_it = i;
818 // no need to look through the remaining queue entries
819 break;
820 } else if (!found_hidden_bank && !found_prepped_pkt) {
821 // if we did not find a packet to a closed row that can
822 // issue the bank commands without incurring delay, and
823 // did not yet find a packet to a prepped row, remember
824 // the current one
825 selected_pkt_it = i;
826 found_prepped_pkt = true;
827 DPRINTF(DRAM, "Prepped row buffer hit\n");
828 }
829 } else if (!found_earliest_pkt) {
830 // if we have not initialised the bank status, do it
831 // now, and only once per scheduling decisions
832 if (earliest_banks == 0) {
833 // determine entries with earliest bank delay
834 pair<uint64_t, bool> bankStatus =
835 minBankPrep(queue, min_col_at);
836 earliest_banks = bankStatus.first;
837 hidden_bank_prep = bankStatus.second;
838 }
839
840 // bank is amongst first available banks
841 // minBankPrep will give priority to packets that can
842 // issue seamlessly
843 if (bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
844 found_earliest_pkt = true;
845 found_hidden_bank = hidden_bank_prep;
846
847 // give priority to packets that can issue
848 // bank commands 'behind the scenes'
849 // any additional delay if any will be due to
850 // col-to-col command requirements
851 if (hidden_bank_prep || !found_prepped_pkt)
852 selected_pkt_it = i;
853 }
854 }
855 }
856 }
857
858 if (selected_pkt_it != queue.end()) {
859 DRAMPacket* selected_pkt = *selected_pkt_it;
860 queue.erase(selected_pkt_it);
861 queue.push_front(selected_pkt);
862 return true;
863 }
864
865 return false;
866 }
867
868 void
869 DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
870 {
871 DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
872
873 bool needsResponse = pkt->needsResponse();
874 // do the actual memory access which also turns the packet into a
875 // response
876 access(pkt);
877
878 // turn packet around to go back to requester if response expected
879 if (needsResponse) {
880 // access already turned the packet into a response
881 assert(pkt->isResponse());
882 // response_time consumes the static latency and is charged also
883 // with headerDelay that takes into account the delay provided by
884 // the xbar and also the payloadDelay that takes into account the
885 // number of data beats.
886 Tick response_time = curTick() + static_latency + pkt->headerDelay +
887 pkt->payloadDelay;
888 // Here we reset the timing of the packet before sending it out.
889 pkt->headerDelay = pkt->payloadDelay = 0;
890
891 // queue the packet in the response queue to be sent out after
892 // the static latency has passed
893 port.schedTimingResp(pkt, response_time, true);
894 } else {
895 // @todo the packet is going to be deleted, and the DRAMPacket
896 // is still having a pointer to it
897 pendingDelete.reset(pkt);
898 }
899
900 DPRINTF(DRAM, "Done\n");
901
902 return;
903 }
904
905 void
906 DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref,
907 Tick act_tick, uint32_t row)
908 {
909 assert(rank_ref.actTicks.size() == activationLimit);
910
911 DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
912
913 // update the open row
914 assert(bank_ref.openRow == Bank::NO_ROW);
915 bank_ref.openRow = row;
916
917 // start counting anew, this covers both the case when we
918 // auto-precharged, and when this access is forced to
919 // precharge
920 bank_ref.bytesAccessed = 0;
921 bank_ref.rowAccesses = 0;
922
923 ++rank_ref.numBanksActive;
924 assert(rank_ref.numBanksActive <= banksPerRank);
925
926 DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
927 bank_ref.bank, rank_ref.rank, act_tick,
928 ranks[rank_ref.rank]->numBanksActive);
929
930 rank_ref.cmdList.push_back(Command(MemCommand::ACT, bank_ref.bank,
931 act_tick));
932
933 DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) -
934 timeStampOffset, bank_ref.bank, rank_ref.rank);
935
936 // The next access has to respect tRAS for this bank
937 bank_ref.preAllowedAt = act_tick + tRAS;
938
939 // Respect the row-to-column command delay
940 bank_ref.colAllowedAt = std::max(act_tick + tRCD, bank_ref.colAllowedAt);
941
942 // start by enforcing tRRD
943 for (int i = 0; i < banksPerRank; i++) {
944 // next activate to any bank in this rank must not happen
945 // before tRRD
946 if (bankGroupArch && (bank_ref.bankgr == rank_ref.banks[i].bankgr)) {
947 // bank group architecture requires longer delays between
948 // ACT commands within the same bank group. Use tRRD_L
949 // in this case
950 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD_L,
951 rank_ref.banks[i].actAllowedAt);
952 } else {
953 // use shorter tRRD value when either
954 // 1) bank group architecture is not supportted
955 // 2) bank is in a different bank group
956 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD,
957 rank_ref.banks[i].actAllowedAt);
958 }
959 }
960
961 // next, we deal with tXAW, if the activation limit is disabled
962 // then we directly schedule an activate power event
963 if (!rank_ref.actTicks.empty()) {
964 // sanity check
965 if (rank_ref.actTicks.back() &&
966 (act_tick - rank_ref.actTicks.back()) < tXAW) {
967 panic("Got %d activates in window %d (%llu - %llu) which "
968 "is smaller than %llu\n", activationLimit, act_tick -
969 rank_ref.actTicks.back(), act_tick,
970 rank_ref.actTicks.back(), tXAW);
971 }
972
973 // shift the times used for the book keeping, the last element
974 // (highest index) is the oldest one and hence the lowest value
975 rank_ref.actTicks.pop_back();
976
977 // record an new activation (in the future)
978 rank_ref.actTicks.push_front(act_tick);
979
980 // cannot activate more than X times in time window tXAW, push the
981 // next one (the X + 1'st activate) to be tXAW away from the
982 // oldest in our window of X
983 if (rank_ref.actTicks.back() &&
984 (act_tick - rank_ref.actTicks.back()) < tXAW) {
985 DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate "
986 "no earlier than %llu\n", activationLimit,
987 rank_ref.actTicks.back() + tXAW);
988 for (int j = 0; j < banksPerRank; j++)
989 // next activate must not happen before end of window
990 rank_ref.banks[j].actAllowedAt =
991 std::max(rank_ref.actTicks.back() + tXAW,
992 rank_ref.banks[j].actAllowedAt);
993 }
994 }
995
996 // at the point when this activate takes place, make sure we
997 // transition to the active power state
998 if (!rank_ref.activateEvent.scheduled())
999 schedule(rank_ref.activateEvent, act_tick);
1000 else if (rank_ref.activateEvent.when() > act_tick)
1001 // move it sooner in time
1002 reschedule(rank_ref.activateEvent, act_tick);
1003 }
1004
1005 void
1006 DRAMCtrl::prechargeBank(Rank& rank_ref, Bank& bank, Tick pre_at, bool trace)
1007 {
1008 // make sure the bank has an open row
1009 assert(bank.openRow != Bank::NO_ROW);
1010
1011 // sample the bytes per activate here since we are closing
1012 // the page
1013 bytesPerActivate.sample(bank.bytesAccessed);
1014
1015 bank.openRow = Bank::NO_ROW;
1016
1017 // no precharge allowed before this one
1018 bank.preAllowedAt = pre_at;
1019
1020 Tick pre_done_at = pre_at + tRP;
1021
1022 bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at);
1023
1024 assert(rank_ref.numBanksActive != 0);
1025 --rank_ref.numBanksActive;
1026
1027 DPRINTF(DRAM, "Precharging bank %d, rank %d at tick %lld, now got "
1028 "%d active\n", bank.bank, rank_ref.rank, pre_at,
1029 rank_ref.numBanksActive);
1030
1031 if (trace) {
1032
1033 rank_ref.cmdList.push_back(Command(MemCommand::PRE, bank.bank,
1034 pre_at));
1035 DPRINTF(DRAMPower, "%llu,PRE,%d,%d\n", divCeil(pre_at, tCK) -
1036 timeStampOffset, bank.bank, rank_ref.rank);
1037 }
1038 // if we look at the current number of active banks we might be
1039 // tempted to think the DRAM is now idle, however this can be
1040 // undone by an activate that is scheduled to happen before we
1041 // would have reached the idle state, so schedule an event and
1042 // rather check once we actually make it to the point in time when
1043 // the (last) precharge takes place
1044 if (!rank_ref.prechargeEvent.scheduled()) {
1045 schedule(rank_ref.prechargeEvent, pre_done_at);
1046 // New event, increment count
1047 ++rank_ref.outstandingEvents;
1048 } else if (rank_ref.prechargeEvent.when() < pre_done_at) {
1049 reschedule(rank_ref.prechargeEvent, pre_done_at);
1050 }
1051 }
1052
1053 void
1054 DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
1055 {
1056 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1057 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1058
1059 // get the rank
1060 Rank& rank = dram_pkt->rankRef;
1061
1062 // are we in or transitioning to a low-power state and have not scheduled
1063 // a power-up event?
1064 // if so, wake up from power down to issue RD/WR burst
1065 if (rank.inLowPowerState) {
1066 assert(rank.pwrState != PWR_SREF);
1067 rank.scheduleWakeUpEvent(tXP);
1068 }
1069
1070 // get the bank
1071 Bank& bank = dram_pkt->bankRef;
1072
1073 // for the state we need to track if it is a row hit or not
1074 bool row_hit = true;
1075
1076 // respect any constraints on the command (e.g. tRCD or tCCD)
1077 Tick cmd_at = std::max(bank.colAllowedAt, curTick());
1078
1079 // Determine the access latency and update the bank state
1080 if (bank.openRow == dram_pkt->row) {
1081 // nothing to do
1082 } else {
1083 row_hit = false;
1084
1085 // If there is a page open, precharge it.
1086 if (bank.openRow != Bank::NO_ROW) {
1087 prechargeBank(rank, bank, std::max(bank.preAllowedAt, curTick()));
1088 }
1089
1090 // next we need to account for the delay in activating the
1091 // page
1092 Tick act_tick = std::max(bank.actAllowedAt, curTick());
1093
1094 // Record the activation and deal with all the global timing
1095 // constraints caused be a new activation (tRRD and tXAW)
1096 activateBank(rank, bank, act_tick, dram_pkt->row);
1097
1098 // issue the command as early as possible
1099 cmd_at = bank.colAllowedAt;
1100 }
1101
1102 // we need to wait until the bus is available before we can issue
1103 // the command
1104 cmd_at = std::max(cmd_at, busBusyUntil - tCL);
1105
1106 // update the packet ready time
1107 dram_pkt->readyTime = cmd_at + tCL + tBURST;
1108
1109 // only one burst can use the bus at any one point in time
1110 assert(dram_pkt->readyTime - busBusyUntil >= tBURST);
1111
1112 // update the time for the next read/write burst for each
1113 // bank (add a max with tCCD/tCCD_L here)
1114 Tick cmd_dly;
1115 for (int j = 0; j < ranksPerChannel; j++) {
1116 for (int i = 0; i < banksPerRank; i++) {
1117 // next burst to same bank group in this rank must not happen
1118 // before tCCD_L. Different bank group timing requirement is
1119 // tBURST; Add tCS for different ranks
1120 if (dram_pkt->rank == j) {
1121 if (bankGroupArch &&
1122 (bank.bankgr == ranks[j]->banks[i].bankgr)) {
1123 // bank group architecture requires longer delays between
1124 // RD/WR burst commands to the same bank group.
1125 // Use tCCD_L in this case
1126 cmd_dly = tCCD_L;
1127 } else {
1128 // use tBURST (equivalent to tCCD_S), the shorter
1129 // cas-to-cas delay value, when either:
1130 // 1) bank group architecture is not supportted
1131 // 2) bank is in a different bank group
1132 cmd_dly = tBURST;
1133 }
1134 } else {
1135 // different rank is by default in a different bank group
1136 // use tBURST (equivalent to tCCD_S), which is the shorter
1137 // cas-to-cas delay in this case
1138 // Add tCS to account for rank-to-rank bus delay requirements
1139 cmd_dly = tBURST + tCS;
1140 }
1141 ranks[j]->banks[i].colAllowedAt = std::max(cmd_at + cmd_dly,
1142 ranks[j]->banks[i].colAllowedAt);
1143 }
1144 }
1145
1146 // Save rank of current access
1147 activeRank = dram_pkt->rank;
1148
1149 // If this is a write, we also need to respect the write recovery
1150 // time before a precharge, in the case of a read, respect the
1151 // read to precharge constraint
1152 bank.preAllowedAt = std::max(bank.preAllowedAt,
1153 dram_pkt->isRead ? cmd_at + tRTP :
1154 dram_pkt->readyTime + tWR);
1155
1156 // increment the bytes accessed and the accesses per row
1157 bank.bytesAccessed += burstSize;
1158 ++bank.rowAccesses;
1159
1160 // if we reached the max, then issue with an auto-precharge
1161 bool auto_precharge = pageMgmt == Enums::close ||
1162 bank.rowAccesses == maxAccessesPerRow;
1163
1164 // if we did not hit the limit, we might still want to
1165 // auto-precharge
1166 if (!auto_precharge &&
1167 (pageMgmt == Enums::open_adaptive ||
1168 pageMgmt == Enums::close_adaptive)) {
1169 // a twist on the open and close page policies:
1170 // 1) open_adaptive page policy does not blindly keep the
1171 // page open, but close it if there are no row hits, and there
1172 // are bank conflicts in the queue
1173 // 2) close_adaptive page policy does not blindly close the
1174 // page, but closes it only if there are no row hits in the queue.
1175 // In this case, only force an auto precharge when there
1176 // are no same page hits in the queue
1177 bool got_more_hits = false;
1178 bool got_bank_conflict = false;
1179
1180 // either look at the read queue or write queue
1181 const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
1182 writeQueue;
1183 auto p = queue.begin();
1184 // make sure we are not considering the packet that we are
1185 // currently dealing with (which is the head of the queue)
1186 ++p;
1187
1188 // keep on looking until we find a hit or reach the end of the queue
1189 // 1) if a hit is found, then both open and close adaptive policies keep
1190 // the page open
1191 // 2) if no hit is found, got_bank_conflict is set to true if a bank
1192 // conflict request is waiting in the queue
1193 while (!got_more_hits && p != queue.end()) {
1194 bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
1195 (dram_pkt->bank == (*p)->bank);
1196 bool same_row = dram_pkt->row == (*p)->row;
1197 got_more_hits |= same_rank_bank && same_row;
1198 got_bank_conflict |= same_rank_bank && !same_row;
1199 ++p;
1200 }
1201
1202 // auto pre-charge when either
1203 // 1) open_adaptive policy, we have not got any more hits, and
1204 // have a bank conflict
1205 // 2) close_adaptive policy and we have not got any more hits
1206 auto_precharge = !got_more_hits &&
1207 (got_bank_conflict || pageMgmt == Enums::close_adaptive);
1208 }
1209
1210 // DRAMPower trace command to be written
1211 std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR";
1212
1213 // MemCommand required for DRAMPower library
1214 MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD :
1215 MemCommand::WR;
1216
1217 // Update bus state
1218 busBusyUntil = dram_pkt->readyTime;
1219
1220 DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n",
1221 dram_pkt->addr, dram_pkt->readyTime, busBusyUntil);
1222
1223 dram_pkt->rankRef.cmdList.push_back(Command(command, dram_pkt->bank,
1224 cmd_at));
1225
1226 DPRINTF(DRAMPower, "%llu,%s,%d,%d\n", divCeil(cmd_at, tCK) -
1227 timeStampOffset, mem_cmd, dram_pkt->bank, dram_pkt->rank);
1228
1229 // if this access should use auto-precharge, then we are
1230 // closing the row after the read/write burst
1231 if (auto_precharge) {
1232 // if auto-precharge push a PRE command at the correct tick to the
1233 // list used by DRAMPower library to calculate power
1234 prechargeBank(rank, bank, std::max(curTick(), bank.preAllowedAt));
1235
1236 DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId);
1237 }
1238
1239 // Update the minimum timing between the requests, this is a
1240 // conservative estimate of when we have to schedule the next
1241 // request to not introduce any unecessary bubbles. In most cases
1242 // we will wake up sooner than we have to.
1243 nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
1244
1245 // Update the stats and schedule the next request
1246 if (dram_pkt->isRead) {
1247 ++readsThisTime;
1248 if (row_hit)
1249 readRowHits++;
1250 bytesReadDRAM += burstSize;
1251 perBankRdBursts[dram_pkt->bankId]++;
1252
1253 // Update latency stats
1254 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1255 totBusLat += tBURST;
1256 totQLat += cmd_at - dram_pkt->entryTime;
1257 } else {
1258 ++writesThisTime;
1259 if (row_hit)
1260 writeRowHits++;
1261 bytesWritten += burstSize;
1262 perBankWrBursts[dram_pkt->bankId]++;
1263 }
1264 }
1265
1266 void
1267 DRAMCtrl::processNextReqEvent()
1268 {
1269 int busyRanks = 0;
1270 for (auto r : ranks) {
1271 if (!r->isAvailable()) {
1272 if (r->pwrState != PWR_SREF) {
1273 // rank is busy refreshing
1274 DPRINTF(DRAMState, "Rank %d is not available\n", r->rank);
1275 busyRanks++;
1276
1277 // let the rank know that if it was waiting to drain, it
1278 // is now done and ready to proceed
1279 r->checkDrainDone();
1280 }
1281
1282 // check if we were in self-refresh and haven't started
1283 // to transition out
1284 if ((r->pwrState == PWR_SREF) && r->inLowPowerState) {
1285 DPRINTF(DRAMState, "Rank %d is in self-refresh\n", r->rank);
1286 // if we have commands queued to this rank and we don't have
1287 // a minimum number of active commands enqueued,
1288 // exit self-refresh
1289 if (r->forceSelfRefreshExit()) {
1290 DPRINTF(DRAMState, "rank %d was in self refresh and"
1291 " should wake up\n", r->rank);
1292 //wake up from self-refresh
1293 r->scheduleWakeUpEvent(tXS);
1294 // things are brought back into action once a refresh is
1295 // performed after self-refresh
1296 // continue with selection for other ranks
1297 }
1298 }
1299 }
1300 }
1301
1302 if (busyRanks == ranksPerChannel) {
1303 // if all ranks are refreshing wait for them to finish
1304 // and stall this state machine without taking any further
1305 // action, and do not schedule a new nextReqEvent
1306 return;
1307 }
1308
1309 // pre-emptively set to false. Overwrite if in transitioning to
1310 // a new state
1311 bool switched_cmd_type = false;
1312 if (busState != busStateNext) {
1313 if (busState == READ) {
1314 DPRINTF(DRAM, "Switching to writes after %d reads with %d reads "
1315 "waiting\n", readsThisTime, readQueue.size());
1316
1317 // sample and reset the read-related stats as we are now
1318 // transitioning to writes, and all reads are done
1319 rdPerTurnAround.sample(readsThisTime);
1320 readsThisTime = 0;
1321
1322 // now proceed to do the actual writes
1323 switched_cmd_type = true;
1324 } else {
1325 DPRINTF(DRAM, "Switching to reads after %d writes with %d writes "
1326 "waiting\n", writesThisTime, writeQueue.size());
1327
1328 wrPerTurnAround.sample(writesThisTime);
1329 writesThisTime = 0;
1330
1331 switched_cmd_type = true;
1332 }
1333 // update busState to match next state until next transition
1334 busState = busStateNext;
1335 }
1336
1337 // when we get here it is either a read or a write
1338 if (busState == READ) {
1339
1340 // track if we should switch or not
1341 bool switch_to_writes = false;
1342
1343 if (readQueue.empty()) {
1344 // In the case there is no read request to go next,
1345 // trigger writes if we have passed the low threshold (or
1346 // if we are draining)
1347 if (!writeQueue.empty() &&
1348 (drainState() == DrainState::Draining ||
1349 writeQueue.size() > writeLowThreshold)) {
1350
1351 switch_to_writes = true;
1352 } else {
1353 // check if we are drained
1354 // not done draining until in PWR_IDLE state
1355 // ensuring all banks are closed and
1356 // have exited low power states
1357 if (drainState() == DrainState::Draining &&
1358 respQueue.empty() && allRanksDrained()) {
1359
1360 DPRINTF(Drain, "DRAM controller done draining\n");
1361 signalDrainDone();
1362 }
1363
1364 // nothing to do, not even any point in scheduling an
1365 // event for the next request
1366 return;
1367 }
1368 } else {
1369 // bool to check if there is a read to a free rank
1370 bool found_read = false;
1371
1372 // Figure out which read request goes next, and move it to the
1373 // front of the read queue
1374 // If we are changing command type, incorporate the minimum
1375 // bus turnaround delay which will be tCS (different rank) case
1376 found_read = chooseNext(readQueue,
1377 switched_cmd_type ? tCS : 0);
1378
1379 // if no read to an available rank is found then return
1380 // at this point. There could be writes to the available ranks
1381 // which are above the required threshold. However, to
1382 // avoid adding more complexity to the code, return and wait
1383 // for a refresh event to kick things into action again.
1384 if (!found_read)
1385 return;
1386
1387 DRAMPacket* dram_pkt = readQueue.front();
1388 assert(dram_pkt->rankRef.isAvailable());
1389
1390 // here we get a bit creative and shift the bus busy time not
1391 // just the tWTR, but also a CAS latency to capture the fact
1392 // that we are allowed to prepare a new bank, but not issue a
1393 // read command until after tWTR, in essence we capture a
1394 // bubble on the data bus that is tWTR + tCL
1395 if (switched_cmd_type && dram_pkt->rank == activeRank) {
1396 busBusyUntil += tWTR + tCL;
1397 }
1398
1399 doDRAMAccess(dram_pkt);
1400
1401 // At this point we're done dealing with the request
1402 readQueue.pop_front();
1403
1404 // Every respQueue which will generate an event, increment count
1405 ++dram_pkt->rankRef.outstandingEvents;
1406
1407 // sanity check
1408 assert(dram_pkt->size <= burstSize);
1409 assert(dram_pkt->readyTime >= curTick());
1410
1411 // Insert into response queue. It will be sent back to the
1412 // requestor at its readyTime
1413 if (respQueue.empty()) {
1414 assert(!respondEvent.scheduled());
1415 schedule(respondEvent, dram_pkt->readyTime);
1416 } else {
1417 assert(respQueue.back()->readyTime <= dram_pkt->readyTime);
1418 assert(respondEvent.scheduled());
1419 }
1420
1421 respQueue.push_back(dram_pkt);
1422
1423 // we have so many writes that we have to transition
1424 if (writeQueue.size() > writeHighThreshold) {
1425 switch_to_writes = true;
1426 }
1427 }
1428
1429 // switching to writes, either because the read queue is empty
1430 // and the writes have passed the low threshold (or we are
1431 // draining), or because the writes hit the hight threshold
1432 if (switch_to_writes) {
1433 // transition to writing
1434 busStateNext = WRITE;
1435 }
1436 } else {
1437 // bool to check if write to free rank is found
1438 bool found_write = false;
1439
1440 // If we are changing command type, incorporate the minimum
1441 // bus turnaround delay
1442 found_write = chooseNext(writeQueue,
1443 switched_cmd_type ? std::min(tRTW, tCS) : 0);
1444
1445 // if no writes to an available rank are found then return.
1446 // There could be reads to the available ranks. However, to avoid
1447 // adding more complexity to the code, return at this point and wait
1448 // for a refresh event to kick things into action again.
1449 if (!found_write)
1450 return;
1451
1452 DRAMPacket* dram_pkt = writeQueue.front();
1453 assert(dram_pkt->rankRef.isAvailable());
1454 // sanity check
1455 assert(dram_pkt->size <= burstSize);
1456
1457 // add a bubble to the data bus, as defined by the
1458 // tRTW when access is to the same rank as previous burst
1459 // Different rank timing is handled with tCS, which is
1460 // applied to colAllowedAt
1461 if (switched_cmd_type && dram_pkt->rank == activeRank) {
1462 busBusyUntil += tRTW;
1463 }
1464
1465 doDRAMAccess(dram_pkt);
1466
1467 writeQueue.pop_front();
1468
1469 // removed write from queue, decrement count
1470 --dram_pkt->rankRef.writeEntries;
1471
1472 // Schedule write done event to decrement event count
1473 // after the readyTime has been reached
1474 // Only schedule latest write event to minimize events
1475 // required; only need to ensure that final event scheduled covers
1476 // the time that writes are outstanding and bus is active
1477 // to holdoff power-down entry events
1478 if (!dram_pkt->rankRef.writeDoneEvent.scheduled()) {
1479 schedule(dram_pkt->rankRef.writeDoneEvent, dram_pkt->readyTime);
1480 // New event, increment count
1481 ++dram_pkt->rankRef.outstandingEvents;
1482
1483 } else if (dram_pkt->rankRef.writeDoneEvent.when() <
1484 dram_pkt-> readyTime) {
1485 reschedule(dram_pkt->rankRef.writeDoneEvent, dram_pkt->readyTime);
1486 }
1487
1488 isInWriteQueue.erase(burstAlign(dram_pkt->addr));
1489 delete dram_pkt;
1490
1491 // If we emptied the write queue, or got sufficiently below the
1492 // threshold (using the minWritesPerSwitch as the hysteresis) and
1493 // are not draining, or we have reads waiting and have done enough
1494 // writes, then switch to reads.
1495 if (writeQueue.empty() ||
1496 (writeQueue.size() + minWritesPerSwitch < writeLowThreshold &&
1497 drainState() != DrainState::Draining) ||
1498 (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) {
1499 // turn the bus back around for reads again
1500 busStateNext = READ;
1501
1502 // note that the we switch back to reads also in the idle
1503 // case, which eventually will check for any draining and
1504 // also pause any further scheduling if there is really
1505 // nothing to do
1506 }
1507 }
1508 // It is possible that a refresh to another rank kicks things back into
1509 // action before reaching this point.
1510 if (!nextReqEvent.scheduled())
1511 schedule(nextReqEvent, std::max(nextReqTime, curTick()));
1512
1513 // If there is space available and we have writes waiting then let
1514 // them retry. This is done here to ensure that the retry does not
1515 // cause a nextReqEvent to be scheduled before we do so as part of
1516 // the next request processing
1517 if (retryWrReq && writeQueue.size() < writeBufferSize) {
1518 retryWrReq = false;
1519 port.sendRetryReq();
1520 }
1521 }
1522
1523 pair<uint64_t, bool>
1524 DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
1525 Tick min_col_at) const
1526 {
1527 uint64_t bank_mask = 0;
1528 Tick min_act_at = MaxTick;
1529
1530 // latest Tick for which ACT can occur without incurring additoinal
1531 // delay on the data bus
1532 const Tick hidden_act_max = std::max(min_col_at - tRCD, curTick());
1533
1534 // Flag condition when burst can issue back-to-back with previous burst
1535 bool found_seamless_bank = false;
1536
1537 // Flag condition when bank can be opened without incurring additional
1538 // delay on the data bus
1539 bool hidden_bank_prep = false;
1540
1541 // determine if we have queued transactions targetting the
1542 // bank in question
1543 vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
1544 for (const auto& p : queue) {
1545 if (p->rankRef.isAvailable())
1546 got_waiting[p->bankId] = true;
1547 }
1548
1549 // Find command with optimal bank timing
1550 // Will prioritize commands that can issue seamlessly.
1551 for (int i = 0; i < ranksPerChannel; i++) {
1552 for (int j = 0; j < banksPerRank; j++) {
1553 uint16_t bank_id = i * banksPerRank + j;
1554
1555 // if we have waiting requests for the bank, and it is
1556 // amongst the first available, update the mask
1557 if (got_waiting[bank_id]) {
1558 // make sure this rank is not currently refreshing.
1559 assert(ranks[i]->isAvailable());
1560 // simplistic approximation of when the bank can issue
1561 // an activate, ignoring any rank-to-rank switching
1562 // cost in this calculation
1563 Tick act_at = ranks[i]->banks[j].openRow == Bank::NO_ROW ?
1564 std::max(ranks[i]->banks[j].actAllowedAt, curTick()) :
1565 std::max(ranks[i]->banks[j].preAllowedAt, curTick()) + tRP;
1566
1567 // When is the earliest the R/W burst can issue?
1568 Tick col_at = std::max(ranks[i]->banks[j].colAllowedAt,
1569 act_at + tRCD);
1570
1571 // bank can issue burst back-to-back (seamlessly) with
1572 // previous burst
1573 bool new_seamless_bank = col_at <= min_col_at;
1574
1575 // if we found a new seamless bank or we have no
1576 // seamless banks, and got a bank with an earlier
1577 // activate time, it should be added to the bit mask
1578 if (new_seamless_bank ||
1579 (!found_seamless_bank && act_at <= min_act_at)) {
1580 // if we did not have a seamless bank before, and
1581 // we do now, reset the bank mask, also reset it
1582 // if we have not yet found a seamless bank and
1583 // the activate time is smaller than what we have
1584 // seen so far
1585 if (!found_seamless_bank &&
1586 (new_seamless_bank || act_at < min_act_at)) {
1587 bank_mask = 0;
1588 }
1589
1590 found_seamless_bank |= new_seamless_bank;
1591
1592 // ACT can occur 'behind the scenes'
1593 hidden_bank_prep = act_at <= hidden_act_max;
1594
1595 // set the bit corresponding to the available bank
1596 replaceBits(bank_mask, bank_id, bank_id, 1);
1597 min_act_at = act_at;
1598 }
1599 }
1600 }
1601 }
1602
1603 return make_pair(bank_mask, hidden_bank_prep);
1604 }
1605
1606 DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p, int rank)
1607 : EventManager(&_memory), memory(_memory),
1608 pwrStateTrans(PWR_IDLE), pwrStatePostRefresh(PWR_IDLE),
1609 pwrStateTick(0), refreshDueAt(0), pwrState(PWR_IDLE),
1610 refreshState(REF_IDLE), inLowPowerState(false), rank(rank),
1611 readEntries(0), writeEntries(0), outstandingEvents(0),
1612 wakeUpAllowedAt(0), power(_p, false), banks(_p->banks_per_rank),
1613 numBanksActive(0), actTicks(_p->activation_limit, 0),
1614 writeDoneEvent([this]{ processWriteDoneEvent(); }, name()),
1615 activateEvent([this]{ processActivateEvent(); }, name()),
1616 prechargeEvent([this]{ processPrechargeEvent(); }, name()),
1617 refreshEvent([this]{ processRefreshEvent(); }, name()),
1618 powerEvent([this]{ processPowerEvent(); }, name()),
1619 wakeUpEvent([this]{ processWakeUpEvent(); }, name())
1620 {
1621 for (int b = 0; b < _p->banks_per_rank; b++) {
1622 banks[b].bank = b;
1623 // GDDR addressing of banks to BG is linear.
1624 // Here we assume that all DRAM generations address bank groups as
1625 // follows:
1626 if (_p->bank_groups_per_rank > 0) {
1627 // Simply assign lower bits to bank group in order to
1628 // rotate across bank groups as banks are incremented
1629 // e.g. with 4 banks per bank group and 16 banks total:
1630 // banks 0,4,8,12 are in bank group 0
1631 // banks 1,5,9,13 are in bank group 1
1632 // banks 2,6,10,14 are in bank group 2
1633 // banks 3,7,11,15 are in bank group 3
1634 banks[b].bankgr = b % _p->bank_groups_per_rank;
1635 } else {
1636 // No bank groups; simply assign to bank number
1637 banks[b].bankgr = b;
1638 }
1639 }
1640 }
1641
1642 void
1643 DRAMCtrl::Rank::startup(Tick ref_tick)
1644 {
1645 assert(ref_tick > curTick());
1646
1647 pwrStateTick = curTick();
1648
1649 // kick off the refresh, and give ourselves enough time to
1650 // precharge
1651 schedule(refreshEvent, ref_tick);
1652 }
1653
1654 void
1655 DRAMCtrl::Rank::suspend()
1656 {
1657 deschedule(refreshEvent);
1658
1659 // Update the stats
1660 updatePowerStats();
1661
1662 // don't automatically transition back to LP state after next REF
1663 pwrStatePostRefresh = PWR_IDLE;
1664 }
1665
1666 bool
1667 DRAMCtrl::Rank::lowPowerEntryReady() const
1668 {
1669 bool no_queued_cmds = ((memory.busStateNext == READ) && (readEntries == 0))
1670 || ((memory.busStateNext == WRITE) &&
1671 (writeEntries == 0));
1672
1673 if (refreshState == REF_RUN) {
1674 // have not decremented outstandingEvents for refresh command
1675 // still check if there are no commands queued to force PD
1676 // entry after refresh completes
1677 return no_queued_cmds;
1678 } else {
1679 // ensure no commands in Q and no commands scheduled
1680 return (no_queued_cmds && (outstandingEvents == 0));
1681 }
1682 }
1683
1684 void
1685 DRAMCtrl::Rank::checkDrainDone()
1686 {
1687 // if this rank was waiting to drain it is now able to proceed to
1688 // precharge
1689 if (refreshState == REF_DRAIN) {
1690 DPRINTF(DRAM, "Refresh drain done, now precharging\n");
1691
1692 refreshState = REF_PD_EXIT;
1693
1694 // hand control back to the refresh event loop
1695 schedule(refreshEvent, curTick());
1696 }
1697 }
1698
1699 void
1700 DRAMCtrl::Rank::flushCmdList()
1701 {
1702 // at the moment sort the list of commands and update the counters
1703 // for DRAMPower libray when doing a refresh
1704 sort(cmdList.begin(), cmdList.end(), DRAMCtrl::sortTime);
1705
1706 auto next_iter = cmdList.begin();
1707 // push to commands to DRAMPower
1708 for ( ; next_iter != cmdList.end() ; ++next_iter) {
1709 Command cmd = *next_iter;
1710 if (cmd.timeStamp <= curTick()) {
1711 // Move all commands at or before curTick to DRAMPower
1712 power.powerlib.doCommand(cmd.type, cmd.bank,
1713 divCeil(cmd.timeStamp, memory.tCK) -
1714 memory.timeStampOffset);
1715 } else {
1716 // done - found all commands at or before curTick()
1717 // next_iter references the 1st command after curTick
1718 break;
1719 }
1720 }
1721 // reset cmdList to only contain commands after curTick
1722 // if there are no commands after curTick, updated cmdList will be empty
1723 // in this case, next_iter is cmdList.end()
1724 cmdList.assign(next_iter, cmdList.end());
1725 }
1726
1727 void
1728 DRAMCtrl::Rank::processActivateEvent()
1729 {
1730 // we should transition to the active state as soon as any bank is active
1731 if (pwrState != PWR_ACT)
1732 // note that at this point numBanksActive could be back at
1733 // zero again due to a precharge scheduled in the future
1734 schedulePowerEvent(PWR_ACT, curTick());
1735 }
1736
1737 void
1738 DRAMCtrl::Rank::processPrechargeEvent()
1739 {
1740 // counter should at least indicate one outstanding request
1741 // for this precharge
1742 assert(outstandingEvents > 0);
1743 // precharge complete, decrement count
1744 --outstandingEvents;
1745
1746 // if we reached zero, then special conditions apply as we track
1747 // if all banks are precharged for the power models
1748 if (numBanksActive == 0) {
1749 // no reads to this rank in the Q and no pending
1750 // RD/WR or refresh commands
1751 if (lowPowerEntryReady()) {
1752 // should still be in ACT state since bank still open
1753 assert(pwrState == PWR_ACT);
1754
1755 // All banks closed - switch to precharge power down state.
1756 DPRINTF(DRAMState, "Rank %d sleep at tick %d\n",
1757 rank, curTick());
1758 powerDownSleep(PWR_PRE_PDN, curTick());
1759 } else {
1760 // we should transition to the idle state when the last bank
1761 // is precharged
1762 schedulePowerEvent(PWR_IDLE, curTick());
1763 }
1764 }
1765 }
1766
1767 void
1768 DRAMCtrl::Rank::processWriteDoneEvent()
1769 {
1770 // counter should at least indicate one outstanding request
1771 // for this write
1772 assert(outstandingEvents > 0);
1773 // Write transfer on bus has completed
1774 // decrement per rank counter
1775 --outstandingEvents;
1776 }
1777
1778 void
1779 DRAMCtrl::Rank::processRefreshEvent()
1780 {
1781 // when first preparing the refresh, remember when it was due
1782 if ((refreshState == REF_IDLE) || (refreshState == REF_SREF_EXIT)) {
1783 // remember when the refresh is due
1784 refreshDueAt = curTick();
1785
1786 // proceed to drain
1787 refreshState = REF_DRAIN;
1788
1789 // make nonzero while refresh is pending to ensure
1790 // power down and self-refresh are not entered
1791 ++outstandingEvents;
1792
1793 DPRINTF(DRAM, "Refresh due\n");
1794 }
1795
1796 // let any scheduled read or write to the same rank go ahead,
1797 // after which it will
1798 // hand control back to this event loop
1799 if (refreshState == REF_DRAIN) {
1800 // if a request is at the moment being handled and this request is
1801 // accessing the current rank then wait for it to finish
1802 if ((rank == memory.activeRank)
1803 && (memory.nextReqEvent.scheduled())) {
1804 // hand control over to the request loop until it is
1805 // evaluated next
1806 DPRINTF(DRAM, "Refresh awaiting draining\n");
1807
1808 return;
1809 } else {
1810 refreshState = REF_PD_EXIT;
1811 }
1812 }
1813
1814 // at this point, ensure that rank is not in a power-down state
1815 if (refreshState == REF_PD_EXIT) {
1816 // if rank was sleeping and we have't started exit process,
1817 // wake-up for refresh
1818 if (inLowPowerState) {
1819 DPRINTF(DRAM, "Wake Up for refresh\n");
1820 // save state and return after refresh completes
1821 scheduleWakeUpEvent(memory.tXP);
1822 return;
1823 } else {
1824 refreshState = REF_PRE;
1825 }
1826 }
1827
1828 // at this point, ensure that all banks are precharged
1829 if (refreshState == REF_PRE) {
1830 // precharge any active bank
1831 if (numBanksActive != 0) {
1832 // at the moment, we use a precharge all even if there is
1833 // only a single bank open
1834 DPRINTF(DRAM, "Precharging all\n");
1835
1836 // first determine when we can precharge
1837 Tick pre_at = curTick();
1838
1839 for (auto &b : banks) {
1840 // respect both causality and any existing bank
1841 // constraints, some banks could already have a
1842 // (auto) precharge scheduled
1843 pre_at = std::max(b.preAllowedAt, pre_at);
1844 }
1845
1846 // make sure all banks per rank are precharged, and for those that
1847 // already are, update their availability
1848 Tick act_allowed_at = pre_at + memory.tRP;
1849
1850 for (auto &b : banks) {
1851 if (b.openRow != Bank::NO_ROW) {
1852 memory.prechargeBank(*this, b, pre_at, false);
1853 } else {
1854 b.actAllowedAt = std::max(b.actAllowedAt, act_allowed_at);
1855 b.preAllowedAt = std::max(b.preAllowedAt, pre_at);
1856 }
1857 }
1858
1859 // precharge all banks in rank
1860 cmdList.push_back(Command(MemCommand::PREA, 0, pre_at));
1861
1862 DPRINTF(DRAMPower, "%llu,PREA,0,%d\n",
1863 divCeil(pre_at, memory.tCK) -
1864 memory.timeStampOffset, rank);
1865 } else if ((pwrState == PWR_IDLE) && (outstandingEvents == 1)) {
1866 // Banks are closed, have transitioned to IDLE state, and
1867 // no outstanding ACT,RD/WR,Auto-PRE sequence scheduled
1868 DPRINTF(DRAM, "All banks already precharged, starting refresh\n");
1869
1870 // go ahead and kick the power state machine into gear since
1871 // we are already idle
1872 schedulePowerEvent(PWR_REF, curTick());
1873 } else {
1874 // banks state is closed but haven't transitioned pwrState to IDLE
1875 // or have outstanding ACT,RD/WR,Auto-PRE sequence scheduled
1876 // should have outstanding precharge event in this case
1877 assert(prechargeEvent.scheduled());
1878 // will start refresh when pwrState transitions to IDLE
1879 }
1880
1881 assert(numBanksActive == 0);
1882
1883 // wait for all banks to be precharged, at which point the
1884 // power state machine will transition to the idle state, and
1885 // automatically move to a refresh, at that point it will also
1886 // call this method to get the refresh event loop going again
1887 return;
1888 }
1889
1890 // last but not least we perform the actual refresh
1891 if (refreshState == REF_START) {
1892 // should never get here with any banks active
1893 assert(numBanksActive == 0);
1894 assert(pwrState == PWR_REF);
1895
1896 Tick ref_done_at = curTick() + memory.tRFC;
1897
1898 for (auto &b : banks) {
1899 b.actAllowedAt = ref_done_at;
1900 }
1901
1902 // at the moment this affects all ranks
1903 cmdList.push_back(Command(MemCommand::REF, 0, curTick()));
1904
1905 // Update the stats
1906 updatePowerStats();
1907
1908 DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), memory.tCK) -
1909 memory.timeStampOffset, rank);
1910
1911 // Update for next refresh
1912 refreshDueAt += memory.tREFI;
1913
1914 // make sure we did not wait so long that we cannot make up
1915 // for it
1916 if (refreshDueAt < ref_done_at) {
1917 fatal("Refresh was delayed so long we cannot catch up\n");
1918 }
1919
1920 // Run the refresh and schedule event to transition power states
1921 // when refresh completes
1922 refreshState = REF_RUN;
1923 schedule(refreshEvent, ref_done_at);
1924 return;
1925 }
1926
1927 if (refreshState == REF_RUN) {
1928 // should never get here with any banks active
1929 assert(numBanksActive == 0);
1930 assert(pwrState == PWR_REF);
1931
1932 assert(!powerEvent.scheduled());
1933
1934 if ((memory.drainState() == DrainState::Draining) ||
1935 (memory.drainState() == DrainState::Drained)) {
1936 // if draining, do not re-enter low-power mode.
1937 // simply go to IDLE and wait
1938 schedulePowerEvent(PWR_IDLE, curTick());
1939 } else {
1940 // At the moment, we sleep when the refresh ends and wait to be
1941 // woken up again if previously in a low-power state.
1942 if (pwrStatePostRefresh != PWR_IDLE) {
1943 // power State should be power Refresh
1944 assert(pwrState == PWR_REF);
1945 DPRINTF(DRAMState, "Rank %d sleeping after refresh and was in "
1946 "power state %d before refreshing\n", rank,
1947 pwrStatePostRefresh);
1948 powerDownSleep(pwrState, curTick());
1949
1950 // Force PRE power-down if there are no outstanding commands
1951 // in Q after refresh.
1952 } else if (lowPowerEntryReady()) {
1953 DPRINTF(DRAMState, "Rank %d sleeping after refresh but was NOT"
1954 " in a low power state before refreshing\n", rank);
1955 powerDownSleep(PWR_PRE_PDN, curTick());
1956
1957 } else {
1958 // move to the idle power state once the refresh is done, this
1959 // will also move the refresh state machine to the refresh
1960 // idle state
1961 schedulePowerEvent(PWR_IDLE, curTick());
1962 }
1963 }
1964
1965 // if transitioning to self refresh do not schedule a new refresh;
1966 // when waking from self refresh, a refresh is scheduled again.
1967 if (pwrStateTrans != PWR_SREF) {
1968 // compensate for the delay in actually performing the refresh
1969 // when scheduling the next one
1970 schedule(refreshEvent, refreshDueAt - memory.tRP);
1971
1972 DPRINTF(DRAMState, "Refresh done at %llu and next refresh"
1973 " at %llu\n", curTick(), refreshDueAt);
1974 }
1975 }
1976 }
1977
1978 void
1979 DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state, Tick tick)
1980 {
1981 // respect causality
1982 assert(tick >= curTick());
1983
1984 if (!powerEvent.scheduled()) {
1985 DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n",
1986 tick, pwr_state);
1987
1988 // insert the new transition
1989 pwrStateTrans = pwr_state;
1990
1991 schedule(powerEvent, tick);
1992 } else {
1993 panic("Scheduled power event at %llu to state %d, "
1994 "with scheduled event at %llu to %d\n", tick, pwr_state,
1995 powerEvent.when(), pwrStateTrans);
1996 }
1997 }
1998
1999 void
2000 DRAMCtrl::Rank::powerDownSleep(PowerState pwr_state, Tick tick)
2001 {
2002 // if low power state is active low, schedule to active low power state.
2003 // in reality tCKE is needed to enter active low power. This is neglected
2004 // here and could be added in the future.
2005 if (pwr_state == PWR_ACT_PDN) {
2006 schedulePowerEvent(pwr_state, tick);
2007 // push command to DRAMPower
2008 cmdList.push_back(Command(MemCommand::PDN_F_ACT, 0, tick));
2009 DPRINTF(DRAMPower, "%llu,PDN_F_ACT,0,%d\n", divCeil(tick,
2010 memory.tCK) - memory.timeStampOffset, rank);
2011 } else if (pwr_state == PWR_PRE_PDN) {
2012 // if low power state is precharge low, schedule to precharge low
2013 // power state. In reality tCKE is needed to enter active low power.
2014 // This is neglected here.
2015 schedulePowerEvent(pwr_state, tick);
2016 //push Command to DRAMPower
2017 cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick));
2018 DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick,
2019 memory.tCK) - memory.timeStampOffset, rank);
2020 } else if (pwr_state == PWR_REF) {
2021 // if a refresh just occured
2022 // transition to PRE_PDN now that all banks are closed
2023 // do not transition to SREF if commands are in Q; stay in PRE_PDN
2024 if (pwrStatePostRefresh == PWR_ACT_PDN || !lowPowerEntryReady()) {
2025 // prechage power down requires tCKE to enter. For simplicity
2026 // this is not considered.
2027 schedulePowerEvent(PWR_PRE_PDN, tick);
2028 //push Command to DRAMPower
2029 cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick));
2030 DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick,
2031 memory.tCK) - memory.timeStampOffset, rank);
2032 } else {
2033 // last low power State was power precharge
2034 assert(pwrStatePostRefresh == PWR_PRE_PDN);
2035 // self refresh requires time tCKESR to enter. For simplicity,
2036 // this is not considered.
2037 schedulePowerEvent(PWR_SREF, tick);
2038 // push Command to DRAMPower
2039 cmdList.push_back(Command(MemCommand::SREN, 0, tick));
2040 DPRINTF(DRAMPower, "%llu,SREN,0,%d\n", divCeil(tick,
2041 memory.tCK) - memory.timeStampOffset, rank);
2042 }
2043 }
2044 // Ensure that we don't power-down and back up in same tick
2045 // Once we commit to PD entry, do it and wait for at least 1tCK
2046 // This could be replaced with tCKE if/when that is added to the model
2047 wakeUpAllowedAt = tick + memory.tCK;
2048
2049 // Transitioning to a low power state, set flag
2050 inLowPowerState = true;
2051 }
2052
2053 void
2054 DRAMCtrl::Rank::scheduleWakeUpEvent(Tick exit_delay)
2055 {
2056 Tick wake_up_tick = std::max(curTick(), wakeUpAllowedAt);
2057
2058 DPRINTF(DRAMState, "Scheduling wake-up for rank %d at tick %d\n",
2059 rank, wake_up_tick);
2060
2061 // if waking for refresh, hold previous state
2062 // else reset state back to IDLE
2063 if (refreshState == REF_PD_EXIT) {
2064 pwrStatePostRefresh = pwrState;
2065 } else {
2066 // don't automatically transition back to LP state after next REF
2067 pwrStatePostRefresh = PWR_IDLE;
2068 }
2069
2070 // schedule wake-up with event to ensure entry has completed before
2071 // we try to wake-up
2072 schedule(wakeUpEvent, wake_up_tick);
2073
2074 for (auto &b : banks) {
2075 // respect both causality and any existing bank
2076 // constraints, some banks could already have a
2077 // (auto) precharge scheduled
2078 b.colAllowedAt = std::max(wake_up_tick + exit_delay, b.colAllowedAt);
2079 b.preAllowedAt = std::max(wake_up_tick + exit_delay, b.preAllowedAt);
2080 b.actAllowedAt = std::max(wake_up_tick + exit_delay, b.actAllowedAt);
2081 }
2082 // Transitioning out of low power state, clear flag
2083 inLowPowerState = false;
2084
2085 // push to DRAMPower
2086 // use pwrStateTrans for cases where we have a power event scheduled
2087 // to enter low power that has not yet been processed
2088 if (pwrStateTrans == PWR_ACT_PDN) {
2089 cmdList.push_back(Command(MemCommand::PUP_ACT, 0, wake_up_tick));
2090 DPRINTF(DRAMPower, "%llu,PUP_ACT,0,%d\n", divCeil(wake_up_tick,
2091 memory.tCK) - memory.timeStampOffset, rank);
2092
2093 } else if (pwrStateTrans == PWR_PRE_PDN) {
2094 cmdList.push_back(Command(MemCommand::PUP_PRE, 0, wake_up_tick));
2095 DPRINTF(DRAMPower, "%llu,PUP_PRE,0,%d\n", divCeil(wake_up_tick,
2096 memory.tCK) - memory.timeStampOffset, rank);
2097 } else if (pwrStateTrans == PWR_SREF) {
2098 cmdList.push_back(Command(MemCommand::SREX, 0, wake_up_tick));
2099 DPRINTF(DRAMPower, "%llu,SREX,0,%d\n", divCeil(wake_up_tick,
2100 memory.tCK) - memory.timeStampOffset, rank);
2101 }
2102 }
2103
2104 void
2105 DRAMCtrl::Rank::processWakeUpEvent()
2106 {
2107 // Should be in a power-down or self-refresh state
2108 assert((pwrState == PWR_ACT_PDN) || (pwrState == PWR_PRE_PDN) ||
2109 (pwrState == PWR_SREF));
2110
2111 // Check current state to determine transition state
2112 if (pwrState == PWR_ACT_PDN) {
2113 // banks still open, transition to PWR_ACT
2114 schedulePowerEvent(PWR_ACT, curTick());
2115 } else {
2116 // transitioning from a precharge power-down or self-refresh state
2117 // banks are closed - transition to PWR_IDLE
2118 schedulePowerEvent(PWR_IDLE, curTick());
2119 }
2120 }
2121
2122 void
2123 DRAMCtrl::Rank::processPowerEvent()
2124 {
2125 assert(curTick() >= pwrStateTick);
2126 // remember where we were, and for how long
2127 Tick duration = curTick() - pwrStateTick;
2128 PowerState prev_state = pwrState;
2129
2130 // update the accounting
2131 pwrStateTime[prev_state] += duration;
2132
2133 // track to total idle time
2134 if ((prev_state == PWR_PRE_PDN) || (prev_state == PWR_ACT_PDN) ||
2135 (prev_state == PWR_SREF)) {
2136 totalIdleTime += duration;
2137 }
2138
2139 pwrState = pwrStateTrans;
2140 pwrStateTick = curTick();
2141
2142 // if rank was refreshing, make sure to start scheduling requests again
2143 if (prev_state == PWR_REF) {
2144 // bus IDLED prior to REF
2145 // counter should be one for refresh command only
2146 assert(outstandingEvents == 1);
2147 // REF complete, decrement count
2148 --outstandingEvents;
2149
2150 DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration);
2151 // if sleeping after refresh
2152 if (pwrState != PWR_IDLE) {
2153 assert((pwrState == PWR_PRE_PDN) || (pwrState == PWR_SREF));
2154 DPRINTF(DRAMState, "Switching to power down state after refreshing"
2155 " rank %d at %llu tick\n", rank, curTick());
2156 }
2157 if (pwrState != PWR_SREF) {
2158 // rank is not available in SREF
2159 // don't transition to IDLE in this case
2160 refreshState = REF_IDLE;
2161 }
2162 // a request event could be already scheduled by the state
2163 // machine of the other rank
2164 if (!memory.nextReqEvent.scheduled()) {
2165 DPRINTF(DRAM, "Scheduling next request after refreshing rank %d\n",
2166 rank);
2167 schedule(memory.nextReqEvent, curTick());
2168 }
2169 } else if (pwrState == PWR_ACT) {
2170 if (refreshState == REF_PD_EXIT) {
2171 // kick the refresh event loop into action again
2172 assert(prev_state == PWR_ACT_PDN);
2173
2174 // go back to REF event and close banks
2175 refreshState = REF_PRE;
2176 schedule(refreshEvent, curTick());
2177 }
2178 } else if (pwrState == PWR_IDLE) {
2179 DPRINTF(DRAMState, "All banks precharged\n");
2180 if (prev_state == PWR_SREF) {
2181 // set refresh state to REF_SREF_EXIT, ensuring isAvailable
2182 // continues to return false during tXS after SREF exit
2183 // Schedule a refresh which kicks things back into action
2184 // when it finishes
2185 refreshState = REF_SREF_EXIT;
2186 schedule(refreshEvent, curTick() + memory.tXS);
2187 } else {
2188 // if we have a pending refresh, and are now moving to
2189 // the idle state, directly transition to a refresh
2190 if ((refreshState == REF_PRE) || (refreshState == REF_PD_EXIT)) {
2191 // ensure refresh is restarted only after final PRE command.
2192 // do not restart refresh if controller is in an intermediate
2193 // state, after PRE_PDN exit, when banks are IDLE but an
2194 // ACT is scheduled.
2195 if (!activateEvent.scheduled()) {
2196 // there should be nothing waiting at this point
2197 assert(!powerEvent.scheduled());
2198 // update the state in zero time and proceed below
2199 pwrState = PWR_REF;
2200 } else {
2201 // must have PRE scheduled to transition back to IDLE
2202 // and re-kick off refresh
2203 assert(prechargeEvent.scheduled());
2204 }
2205 }
2206 }
2207 }
2208
2209 // we transition to the refresh state, let the refresh state
2210 // machine know of this state update and let it deal with the
2211 // scheduling of the next power state transition as well as the
2212 // following refresh
2213 if (pwrState == PWR_REF) {
2214 assert(refreshState == REF_PRE || refreshState == REF_PD_EXIT);
2215 DPRINTF(DRAMState, "Refreshing\n");
2216
2217 // kick the refresh event loop into action again, and that
2218 // in turn will schedule a transition to the idle power
2219 // state once the refresh is done
2220 if (refreshState == REF_PD_EXIT) {
2221 // Wait for PD exit timing to complete before issuing REF
2222 schedule(refreshEvent, curTick() + memory.tXP);
2223 } else {
2224 schedule(refreshEvent, curTick());
2225 }
2226 // Banks transitioned to IDLE, start REF
2227 refreshState = REF_START;
2228 }
2229 }
2230
2231 void
2232 DRAMCtrl::Rank::updatePowerStats()
2233 {
2234 // All commands up to refresh have completed
2235 // flush cmdList to DRAMPower
2236 flushCmdList();
2237
2238 // update the counters for DRAMPower, passing false to
2239 // indicate that this is not the last command in the
2240 // list. DRAMPower requires this information for the
2241 // correct calculation of the background energy at the end
2242 // of the simulation. Ideally we would want to call this
2243 // function with true once at the end of the
2244 // simulation. However, the discarded energy is extremly
2245 // small and does not effect the final results.
2246 power.powerlib.updateCounters(false);
2247
2248 // call the energy function
2249 power.powerlib.calcEnergy();
2250
2251 // Get the energy and power from DRAMPower
2252 Data::MemoryPowerModel::Energy energy =
2253 power.powerlib.getEnergy();
2254 Data::MemoryPowerModel::Power rank_power =
2255 power.powerlib.getPower();
2256
2257 actEnergy = energy.act_energy * memory.devicesPerRank;
2258 preEnergy = energy.pre_energy * memory.devicesPerRank;
2259 readEnergy = energy.read_energy * memory.devicesPerRank;
2260 writeEnergy = energy.write_energy * memory.devicesPerRank;
2261 refreshEnergy = energy.ref_energy * memory.devicesPerRank;
2262 actBackEnergy = energy.act_stdby_energy * memory.devicesPerRank;
2263 preBackEnergy = energy.pre_stdby_energy * memory.devicesPerRank;
2264 actPowerDownEnergy = energy.f_act_pd_energy * memory.devicesPerRank;
2265 prePowerDownEnergy = energy.f_pre_pd_energy * memory.devicesPerRank;
2266 selfRefreshEnergy = energy.sref_energy * memory.devicesPerRank;
2267 totalEnergy = energy.total_energy * memory.devicesPerRank;
2268 averagePower = rank_power.average_power * memory.devicesPerRank;
2269 }
2270
2271 void
2272 DRAMCtrl::Rank::computeStats()
2273 {
2274 DPRINTF(DRAM,"Computing final stats\n");
2275
2276 // Force DRAM power to update counters based on time spent in
2277 // current state up to curTick()
2278 cmdList.push_back(Command(MemCommand::NOP, 0, curTick()));
2279
2280 // Update the stats
2281 updatePowerStats();
2282
2283 // final update of power state times
2284 pwrStateTime[pwrState] += (curTick() - pwrStateTick);
2285 pwrStateTick = curTick();
2286
2287 }
2288
2289 void
2290 DRAMCtrl::Rank::regStats()
2291 {
2292 using namespace Stats;
2293
2294 pwrStateTime
2295 .init(6)
2296 .name(name() + ".memoryStateTime")
2297 .desc("Time in different power states");
2298 pwrStateTime.subname(0, "IDLE");
2299 pwrStateTime.subname(1, "REF");
2300 pwrStateTime.subname(2, "SREF");
2301 pwrStateTime.subname(3, "PRE_PDN");
2302 pwrStateTime.subname(4, "ACT");
2303 pwrStateTime.subname(5, "ACT_PDN");
2304
2305 actEnergy
2306 .name(name() + ".actEnergy")
2307 .desc("Energy for activate commands per rank (pJ)");
2308
2309 preEnergy
2310 .name(name() + ".preEnergy")
2311 .desc("Energy for precharge commands per rank (pJ)");
2312
2313 readEnergy
2314 .name(name() + ".readEnergy")
2315 .desc("Energy for read commands per rank (pJ)");
2316
2317 writeEnergy
2318 .name(name() + ".writeEnergy")
2319 .desc("Energy for write commands per rank (pJ)");
2320
2321 refreshEnergy
2322 .name(name() + ".refreshEnergy")
2323 .desc("Energy for refresh commands per rank (pJ)");
2324
2325 actBackEnergy
2326 .name(name() + ".actBackEnergy")
2327 .desc("Energy for active background per rank (pJ)");
2328
2329 preBackEnergy
2330 .name(name() + ".preBackEnergy")
2331 .desc("Energy for precharge background per rank (pJ)");
2332
2333 actPowerDownEnergy
2334 .name(name() + ".actPowerDownEnergy")
2335 .desc("Energy for active power-down per rank (pJ)");
2336
2337 prePowerDownEnergy
2338 .name(name() + ".prePowerDownEnergy")
2339 .desc("Energy for precharge power-down per rank (pJ)");
2340
2341 selfRefreshEnergy
2342 .name(name() + ".selfRefreshEnergy")
2343 .desc("Energy for self refresh per rank (pJ)");
2344
2345 totalEnergy
2346 .name(name() + ".totalEnergy")
2347 .desc("Total energy per rank (pJ)");
2348
2349 averagePower
2350 .name(name() + ".averagePower")
2351 .desc("Core power per rank (mW)");
2352
2353 totalIdleTime
2354 .name(name() + ".totalIdleTime")
2355 .desc("Total Idle time Per DRAM Rank");
2356
2357 registerDumpCallback(new RankDumpCallback(this));
2358 }
2359 void
2360 DRAMCtrl::regStats()
2361 {
2362 using namespace Stats;
2363
2364 AbstractMemory::regStats();
2365
2366 for (auto r : ranks) {
2367 r->regStats();
2368 }
2369
2370 readReqs
2371 .name(name() + ".readReqs")
2372 .desc("Number of read requests accepted");
2373
2374 writeReqs
2375 .name(name() + ".writeReqs")
2376 .desc("Number of write requests accepted");
2377
2378 readBursts
2379 .name(name() + ".readBursts")
2380 .desc("Number of DRAM read bursts, "
2381 "including those serviced by the write queue");
2382
2383 writeBursts
2384 .name(name() + ".writeBursts")
2385 .desc("Number of DRAM write bursts, "
2386 "including those merged in the write queue");
2387
2388 servicedByWrQ
2389 .name(name() + ".servicedByWrQ")
2390 .desc("Number of DRAM read bursts serviced by the write queue");
2391
2392 mergedWrBursts
2393 .name(name() + ".mergedWrBursts")
2394 .desc("Number of DRAM write bursts merged with an existing one");
2395
2396 neitherReadNorWrite
2397 .name(name() + ".neitherReadNorWriteReqs")
2398 .desc("Number of requests that are neither read nor write");
2399
2400 perBankRdBursts
2401 .init(banksPerRank * ranksPerChannel)
2402 .name(name() + ".perBankRdBursts")
2403 .desc("Per bank write bursts");
2404
2405 perBankWrBursts
2406 .init(banksPerRank * ranksPerChannel)
2407 .name(name() + ".perBankWrBursts")
2408 .desc("Per bank write bursts");
2409
2410 avgRdQLen
2411 .name(name() + ".avgRdQLen")
2412 .desc("Average read queue length when enqueuing")
2413 .precision(2);
2414
2415 avgWrQLen
2416 .name(name() + ".avgWrQLen")
2417 .desc("Average write queue length when enqueuing")
2418 .precision(2);
2419
2420 totQLat
2421 .name(name() + ".totQLat")
2422 .desc("Total ticks spent queuing");
2423
2424 totBusLat
2425 .name(name() + ".totBusLat")
2426 .desc("Total ticks spent in databus transfers");
2427
2428 totMemAccLat
2429 .name(name() + ".totMemAccLat")
2430 .desc("Total ticks spent from burst creation until serviced "
2431 "by the DRAM");
2432
2433 avgQLat
2434 .name(name() + ".avgQLat")
2435 .desc("Average queueing delay per DRAM burst")
2436 .precision(2);
2437
2438 avgQLat = totQLat / (readBursts - servicedByWrQ);
2439
2440 avgBusLat
2441 .name(name() + ".avgBusLat")
2442 .desc("Average bus latency per DRAM burst")
2443 .precision(2);
2444
2445 avgBusLat = totBusLat / (readBursts - servicedByWrQ);
2446
2447 avgMemAccLat
2448 .name(name() + ".avgMemAccLat")
2449 .desc("Average memory access latency per DRAM burst")
2450 .precision(2);
2451
2452 avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
2453
2454 numRdRetry
2455 .name(name() + ".numRdRetry")
2456 .desc("Number of times read queue was full causing retry");
2457
2458 numWrRetry
2459 .name(name() + ".numWrRetry")
2460 .desc("Number of times write queue was full causing retry");
2461
2462 readRowHits
2463 .name(name() + ".readRowHits")
2464 .desc("Number of row buffer hits during reads");
2465
2466 writeRowHits
2467 .name(name() + ".writeRowHits")
2468 .desc("Number of row buffer hits during writes");
2469
2470 readRowHitRate
2471 .name(name() + ".readRowHitRate")
2472 .desc("Row buffer hit rate for reads")
2473 .precision(2);
2474
2475 readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
2476
2477 writeRowHitRate
2478 .name(name() + ".writeRowHitRate")
2479 .desc("Row buffer hit rate for writes")
2480 .precision(2);
2481
2482 writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
2483
2484 readPktSize
2485 .init(ceilLog2(burstSize) + 1)
2486 .name(name() + ".readPktSize")
2487 .desc("Read request sizes (log2)");
2488
2489 writePktSize
2490 .init(ceilLog2(burstSize) + 1)
2491 .name(name() + ".writePktSize")
2492 .desc("Write request sizes (log2)");
2493
2494 rdQLenPdf
2495 .init(readBufferSize)
2496 .name(name() + ".rdQLenPdf")
2497 .desc("What read queue length does an incoming req see");
2498
2499 wrQLenPdf
2500 .init(writeBufferSize)
2501 .name(name() + ".wrQLenPdf")
2502 .desc("What write queue length does an incoming req see");
2503
2504 bytesPerActivate
2505 .init(maxAccessesPerRow)
2506 .name(name() + ".bytesPerActivate")
2507 .desc("Bytes accessed per row activation")
2508 .flags(nozero);
2509
2510 rdPerTurnAround
2511 .init(readBufferSize)
2512 .name(name() + ".rdPerTurnAround")
2513 .desc("Reads before turning the bus around for writes")
2514 .flags(nozero);
2515
2516 wrPerTurnAround
2517 .init(writeBufferSize)
2518 .name(name() + ".wrPerTurnAround")
2519 .desc("Writes before turning the bus around for reads")
2520 .flags(nozero);
2521
2522 bytesReadDRAM
2523 .name(name() + ".bytesReadDRAM")
2524 .desc("Total number of bytes read from DRAM");
2525
2526 bytesReadWrQ
2527 .name(name() + ".bytesReadWrQ")
2528 .desc("Total number of bytes read from write queue");
2529
2530 bytesWritten
2531 .name(name() + ".bytesWritten")
2532 .desc("Total number of bytes written to DRAM");
2533
2534 bytesReadSys
2535 .name(name() + ".bytesReadSys")
2536 .desc("Total read bytes from the system interface side");
2537
2538 bytesWrittenSys
2539 .name(name() + ".bytesWrittenSys")
2540 .desc("Total written bytes from the system interface side");
2541
2542 avgRdBW
2543 .name(name() + ".avgRdBW")
2544 .desc("Average DRAM read bandwidth in MiByte/s")
2545 .precision(2);
2546
2547 avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
2548
2549 avgWrBW
2550 .name(name() + ".avgWrBW")
2551 .desc("Average achieved write bandwidth in MiByte/s")
2552 .precision(2);
2553
2554 avgWrBW = (bytesWritten / 1000000) / simSeconds;
2555
2556 avgRdBWSys
2557 .name(name() + ".avgRdBWSys")
2558 .desc("Average system read bandwidth in MiByte/s")
2559 .precision(2);
2560
2561 avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
2562
2563 avgWrBWSys
2564 .name(name() + ".avgWrBWSys")
2565 .desc("Average system write bandwidth in MiByte/s")
2566 .precision(2);
2567
2568 avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
2569
2570 peakBW
2571 .name(name() + ".peakBW")
2572 .desc("Theoretical peak bandwidth in MiByte/s")
2573 .precision(2);
2574
2575 peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
2576
2577 busUtil
2578 .name(name() + ".busUtil")
2579 .desc("Data bus utilization in percentage")
2580 .precision(2);
2581 busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
2582
2583 totGap
2584 .name(name() + ".totGap")
2585 .desc("Total gap between requests");
2586
2587 avgGap
2588 .name(name() + ".avgGap")
2589 .desc("Average gap between requests")
2590 .precision(2);
2591
2592 avgGap = totGap / (readReqs + writeReqs);
2593
2594 // Stats for DRAM Power calculation based on Micron datasheet
2595 busUtilRead
2596 .name(name() + ".busUtilRead")
2597 .desc("Data bus utilization in percentage for reads")
2598 .precision(2);
2599
2600 busUtilRead = avgRdBW / peakBW * 100;
2601
2602 busUtilWrite
2603 .name(name() + ".busUtilWrite")
2604 .desc("Data bus utilization in percentage for writes")
2605 .precision(2);
2606
2607 busUtilWrite = avgWrBW / peakBW * 100;
2608
2609 pageHitRate
2610 .name(name() + ".pageHitRate")
2611 .desc("Row buffer hit rate, read and write combined")
2612 .precision(2);
2613
2614 pageHitRate = (writeRowHits + readRowHits) /
2615 (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
2616 }
2617
2618 void
2619 DRAMCtrl::recvFunctional(PacketPtr pkt)
2620 {
2621 // rely on the abstract memory
2622 functionalAccess(pkt);
2623 }
2624
2625 BaseSlavePort&
2626 DRAMCtrl::getSlavePort(const string &if_name, PortID idx)
2627 {
2628 if (if_name != "port") {
2629 return MemObject::getSlavePort(if_name, idx);
2630 } else {
2631 return port;
2632 }
2633 }
2634
2635 DrainState
2636 DRAMCtrl::drain()
2637 {
2638 // if there is anything in any of our internal queues, keep track
2639 // of that as well
2640 if (!(writeQueue.empty() && readQueue.empty() && respQueue.empty() &&
2641 allRanksDrained())) {
2642
2643 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
2644 " resp: %d\n", writeQueue.size(), readQueue.size(),
2645 respQueue.size());
2646
2647 // the only queue that is not drained automatically over time
2648 // is the write queue, thus kick things into action if needed
2649 if (!writeQueue.empty() && !nextReqEvent.scheduled()) {
2650 schedule(nextReqEvent, curTick());
2651 }
2652
2653 // also need to kick off events to exit self-refresh
2654 for (auto r : ranks) {
2655 // force self-refresh exit, which in turn will issue auto-refresh
2656 if (r->pwrState == PWR_SREF) {
2657 DPRINTF(DRAM,"Rank%d: Forcing self-refresh wakeup in drain\n",
2658 r->rank);
2659 r->scheduleWakeUpEvent(tXS);
2660 }
2661 }
2662
2663 return DrainState::Draining;
2664 } else {
2665 return DrainState::Drained;
2666 }
2667 }
2668
2669 bool
2670 DRAMCtrl::allRanksDrained() const
2671 {
2672 // true until proven false
2673 bool all_ranks_drained = true;
2674 for (auto r : ranks) {
2675 // then verify that the power state is IDLE
2676 // ensuring all banks are closed and rank is not in a low power state
2677 all_ranks_drained = r->inPwrIdleState() && all_ranks_drained;
2678 }
2679 return all_ranks_drained;
2680 }
2681
2682 void
2683 DRAMCtrl::drainResume()
2684 {
2685 if (!isTimingMode && system()->isTimingMode()) {
2686 // if we switched to timing mode, kick things into action,
2687 // and behave as if we restored from a checkpoint
2688 startup();
2689 } else if (isTimingMode && !system()->isTimingMode()) {
2690 // if we switch from timing mode, stop the refresh events to
2691 // not cause issues with KVM
2692 for (auto r : ranks) {
2693 r->suspend();
2694 }
2695 }
2696
2697 // update the mode
2698 isTimingMode = system()->isTimingMode();
2699 }
2700
2701 DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
2702 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
2703 memory(_memory)
2704 { }
2705
2706 AddrRangeList
2707 DRAMCtrl::MemoryPort::getAddrRanges() const
2708 {
2709 AddrRangeList ranges;
2710 ranges.push_back(memory.getAddrRange());
2711 return ranges;
2712 }
2713
2714 void
2715 DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
2716 {
2717 pkt->pushLabel(memory.name());
2718
2719 if (!queue.checkFunctional(pkt)) {
2720 // Default implementation of SimpleTimingPort::recvFunctional()
2721 // calls recvAtomic() and throws away the latency; we can save a
2722 // little here by just not calculating the latency.
2723 memory.recvFunctional(pkt);
2724 }
2725
2726 pkt->popLabel();
2727 }
2728
2729 Tick
2730 DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt)
2731 {
2732 return memory.recvAtomic(pkt);
2733 }
2734
2735 bool
2736 DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt)
2737 {
2738 // pass it to the memory controller
2739 return memory.recvTimingReq(pkt);
2740 }
2741
2742 DRAMCtrl*
2743 DRAMCtrlParams::create()
2744 {
2745 return new DRAMCtrl(this);
2746 }