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