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