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