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