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