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