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