dram_ctrl.cc revision 9974
1/*
2 * Copyright (c) 2010-2013 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/trace.hh"
46#include "base/bitfield.hh"
47#include "debug/Drain.hh"
48#include "debug/DRAM.hh"
49#include "mem/simple_dram.hh"
50#include "sim/system.hh"
51
52using namespace std;
53
54SimpleDRAM::SimpleDRAM(const SimpleDRAMParams* p) :
55    AbstractMemory(p),
56    port(name() + ".port", *this),
57    retryRdReq(false), retryWrReq(false),
58    rowHitFlag(false), stopReads(false),
59    writeEvent(this), respondEvent(this),
60    refreshEvent(this), nextReqEvent(this), drainManager(NULL),
61    deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
62    deviceRowBufferSize(p->device_rowbuffer_size),
63    devicesPerRank(p->devices_per_rank),
64    burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8),
65    rowBufferSize(devicesPerRank * deviceRowBufferSize),
66    ranksPerChannel(p->ranks_per_channel),
67    banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0),
68    readBufferSize(p->read_buffer_size),
69    writeBufferSize(p->write_buffer_size),
70    writeHighThresholdPerc(p->write_high_thresh_perc),
71    writeLowThresholdPerc(p->write_low_thresh_perc),
72    tWTR(p->tWTR), tBURST(p->tBURST),
73    tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
74    tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
75    tXAW(p->tXAW), activationLimit(p->activation_limit),
76    memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
77    pageMgmt(p->page_policy),
78    frontendLatency(p->static_frontend_latency),
79    backendLatency(p->static_backend_latency),
80    busBusyUntil(0), writeStartTime(0),
81    prevArrival(0), numReqs(0),
82    numWritesThisTime(0), newTime(0)
83{
84    // create the bank states based on the dimensions of the ranks and
85    // banks
86    banks.resize(ranksPerChannel);
87    actTicks.resize(ranksPerChannel);
88    for (size_t c = 0; c < ranksPerChannel; ++c) {
89        banks[c].resize(banksPerRank);
90        actTicks[c].resize(activationLimit, 0);
91    }
92
93    // round the write thresholds percent to a whole number of entries
94    // in the buffer.
95    writeHighThreshold = writeBufferSize * writeHighThresholdPerc / 100.0;
96    writeLowThreshold = writeBufferSize * writeLowThresholdPerc / 100.0;
97}
98
99void
100SimpleDRAM::init()
101{
102    if (!port.isConnected()) {
103        fatal("SimpleDRAM %s is unconnected!\n", name());
104    } else {
105        port.sendRangeChange();
106    }
107
108    // we could deal with plenty options here, but for now do a quick
109    // sanity check
110    DPRINTF(DRAM, "Burst size %d bytes\n", burstSize);
111
112    // determine the rows per bank by looking at the total capacity
113    uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
114
115    DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
116            AbstractMemory::size());
117
118    columnsPerRowBuffer = rowBufferSize / burstSize;
119
120    DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
121            rowBufferSize, columnsPerRowBuffer);
122
123    rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
124
125    if (range.interleaved()) {
126        if (channels != range.stripes())
127            panic("%s has %d interleaved address stripes but %d channel(s)\n",
128                  name(), range.stripes(), channels);
129
130        if (addrMapping == Enums::RaBaChCo) {
131            if (rowBufferSize != range.granularity()) {
132                panic("Interleaving of %s doesn't match RaBaChCo address map\n",
133                      name());
134            }
135        } else if (addrMapping == Enums::RaBaCoCh) {
136            if (burstSize != range.granularity()) {
137                panic("Interleaving of %s doesn't match RaBaCoCh address map\n",
138                      name());
139            }
140        } else if (addrMapping == Enums::CoRaBaCh) {
141            if (burstSize != range.granularity())
142                panic("Interleaving of %s doesn't match CoRaBaCh address map\n",
143                      name());
144        }
145    }
146}
147
148void
149SimpleDRAM::startup()
150{
151    // print the configuration of the controller
152    printParams();
153
154    // kick off the refresh
155    schedule(refreshEvent, curTick() + tREFI);
156}
157
158Tick
159SimpleDRAM::recvAtomic(PacketPtr pkt)
160{
161    DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
162
163    // do the actual memory access and turn the packet into a response
164    access(pkt);
165
166    Tick latency = 0;
167    if (!pkt->memInhibitAsserted() && pkt->hasData()) {
168        // this value is not supposed to be accurate, just enough to
169        // keep things going, mimic a closed page
170        latency = tRP + tRCD + tCL;
171    }
172    return latency;
173}
174
175bool
176SimpleDRAM::readQueueFull(unsigned int neededEntries) const
177{
178    DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
179            readBufferSize, readQueue.size() + respQueue.size(),
180            neededEntries);
181
182    return
183        (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
184}
185
186bool
187SimpleDRAM::writeQueueFull(unsigned int neededEntries) const
188{
189    DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
190            writeBufferSize, writeQueue.size(), neededEntries);
191    return (writeQueue.size() + neededEntries) > writeBufferSize;
192}
193
194SimpleDRAM::DRAMPacket*
195SimpleDRAM::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size, bool isRead)
196{
197    // decode the address based on the address mapping scheme, with
198    // Ra, Co, Ba and Ch denoting rank, column, bank and channel,
199    // respectively
200    uint8_t rank;
201    uint8_t bank;
202    uint16_t row;
203
204    // truncate the address to the access granularity
205    Addr addr = dramPktAddr / burstSize;
206
207    // we have removed the lowest order address bits that denote the
208    // position within the column
209    if (addrMapping == Enums::RaBaChCo) {
210        // the lowest order bits denote the column to ensure that
211        // sequential cache lines occupy the same row
212        addr = addr / columnsPerRowBuffer;
213
214        // take out the channel part of the address
215        addr = addr / channels;
216
217        // after the channel bits, get the bank bits to interleave
218        // over the banks
219        bank = addr % banksPerRank;
220        addr = addr / banksPerRank;
221
222        // after the bank, we get the rank bits which thus interleaves
223        // over the ranks
224        rank = addr % ranksPerChannel;
225        addr = addr / ranksPerChannel;
226
227        // lastly, get the row bits
228        row = addr % rowsPerBank;
229        addr = addr / rowsPerBank;
230    } else if (addrMapping == Enums::RaBaCoCh) {
231        // take out the channel part of the address
232        addr = addr / channels;
233
234        // next, the column
235        addr = addr / columnsPerRowBuffer;
236
237        // after the column bits, we get the bank bits to interleave
238        // over the banks
239        bank = addr % banksPerRank;
240        addr = addr / banksPerRank;
241
242        // after the bank, we get the rank bits which thus interleaves
243        // over the ranks
244        rank = addr % ranksPerChannel;
245        addr = addr / ranksPerChannel;
246
247        // lastly, get the row bits
248        row = addr % rowsPerBank;
249        addr = addr / rowsPerBank;
250    } else if (addrMapping == Enums::CoRaBaCh) {
251        // optimise for closed page mode and utilise maximum
252        // parallelism of the DRAM (at the cost of power)
253
254        // take out the channel part of the address, not that this has
255        // to match with how accesses are interleaved between the
256        // controllers in the address mapping
257        addr = addr / channels;
258
259        // start with the bank bits, as this provides the maximum
260        // opportunity for parallelism between requests
261        bank = addr % banksPerRank;
262        addr = addr / banksPerRank;
263
264        // next get the rank bits
265        rank = addr % ranksPerChannel;
266        addr = addr / ranksPerChannel;
267
268        // next the column bits which we do not need to keep track of
269        // and simply skip past
270        addr = addr / columnsPerRowBuffer;
271
272        // lastly, get the row bits
273        row = addr % rowsPerBank;
274        addr = addr / rowsPerBank;
275    } else
276        panic("Unknown address mapping policy chosen!");
277
278    assert(rank < ranksPerChannel);
279    assert(bank < banksPerRank);
280    assert(row < rowsPerBank);
281
282    DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
283            dramPktAddr, rank, bank, row);
284
285    // create the corresponding DRAM packet with the entry time and
286    // ready time set to the current tick, the latter will be updated
287    // later
288    uint16_t bank_id = banksPerRank * rank + bank;
289    return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
290                          size, banks[rank][bank]);
291}
292
293void
294SimpleDRAM::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
295{
296    // only add to the read queue here. whenever the request is
297    // eventually done, set the readyTime, and call schedule()
298    assert(!pkt->isWrite());
299
300    assert(pktCount != 0);
301
302    // if the request size is larger than burst size, the pkt is split into
303    // multiple DRAM packets
304    // Note if the pkt starting address is not aligened to burst size, the
305    // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
306    // are aligned to burst size boundaries. This is to ensure we accurately
307    // check read packets against packets in write queue.
308    Addr addr = pkt->getAddr();
309    unsigned pktsServicedByWrQ = 0;
310    BurstHelper* burst_helper = NULL;
311    for (int cnt = 0; cnt < pktCount; ++cnt) {
312        unsigned size = std::min((addr | (burstSize - 1)) + 1,
313                        pkt->getAddr() + pkt->getSize()) - addr;
314        readPktSize[ceilLog2(size)]++;
315        readBursts++;
316
317        // First check write buffer to see if the data is already at
318        // the controller
319        bool foundInWrQ = false;
320        for (auto i = writeQueue.begin(); i != writeQueue.end(); ++i) {
321            // check if the read is subsumed in the write entry we are
322            // looking at
323            if ((*i)->addr <= addr &&
324                (addr + size) <= ((*i)->addr + (*i)->size)) {
325                foundInWrQ = true;
326                servicedByWrQ++;
327                pktsServicedByWrQ++;
328                DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
329                        "write queue\n", addr, size);
330                bytesRead += burstSize;
331                bytesConsumedRd += size;
332                break;
333            }
334        }
335
336        // If not found in the write q, make a DRAM packet and
337        // push it onto the read queue
338        if (!foundInWrQ) {
339
340            // Make the burst helper for split packets
341            if (pktCount > 1 && burst_helper == NULL) {
342                DPRINTF(DRAM, "Read to addr %lld translates to %d "
343                        "dram requests\n", pkt->getAddr(), pktCount);
344                burst_helper = new BurstHelper(pktCount);
345            }
346
347            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
348            dram_pkt->burstHelper = burst_helper;
349
350            assert(!readQueueFull(1));
351            rdQLenPdf[readQueue.size() + respQueue.size()]++;
352
353            DPRINTF(DRAM, "Adding to read queue\n");
354
355            readQueue.push_back(dram_pkt);
356
357            // Update stats
358            assert(dram_pkt->bankId < ranksPerChannel * banksPerRank);
359            perBankRdReqs[dram_pkt->bankId]++;
360
361            avgRdQLen = readQueue.size() + respQueue.size();
362        }
363
364        // Starting address of next dram pkt (aligend to burstSize boundary)
365        addr = (addr | (burstSize - 1)) + 1;
366    }
367
368    // If all packets are serviced by write queue, we send the repsonse back
369    if (pktsServicedByWrQ == pktCount) {
370        accessAndRespond(pkt, frontendLatency);
371        return;
372    }
373
374    // Update how many split packets are serviced by write queue
375    if (burst_helper != NULL)
376        burst_helper->burstsServiced = pktsServicedByWrQ;
377
378    // If we are not already scheduled to get the read request out of
379    // the queue, do so now
380    if (!nextReqEvent.scheduled() && !stopReads) {
381        DPRINTF(DRAM, "Request scheduled immediately\n");
382        schedule(nextReqEvent, curTick());
383    }
384}
385
386void
387SimpleDRAM::processWriteEvent()
388{
389    assert(!writeQueue.empty());
390
391    DPRINTF(DRAM, "Beginning DRAM Write\n");
392    Tick temp1 M5_VAR_USED = std::max(curTick(), busBusyUntil);
393    Tick temp2 M5_VAR_USED = std::max(curTick(), maxBankFreeAt());
394
395    chooseNextWrite();
396    DRAMPacket* dram_pkt = writeQueue.front();
397    // sanity check
398    assert(dram_pkt->size <= burstSize);
399    doDRAMAccess(dram_pkt);
400
401    writeQueue.pop_front();
402    delete dram_pkt;
403    numWritesThisTime++;
404
405    DPRINTF(DRAM, "Completed %d writes, bus busy for %lld ticks,"\
406            "banks busy for %lld ticks\n", numWritesThisTime,
407            busBusyUntil - temp1, maxBankFreeAt() - temp2);
408
409    // Update stats
410    avgWrQLen = writeQueue.size();
411
412    if (numWritesThisTime >= writeHighThreshold) {
413        DPRINTF(DRAM, "Hit write threshold %d\n", writeHighThreshold);
414    }
415
416    // If number of writes in the queue fall below the low thresholds and
417    // read queue is not empty then schedule a request event else continue
418    // with writes. The retry above could already have caused it to be
419    // scheduled, so first check
420    if (((writeQueue.size() <= writeLowThreshold) && !readQueue.empty()) ||
421        writeQueue.empty()) {
422        numWritesThisTime = 0;
423        // turn the bus back around for reads again
424        busBusyUntil += tWTR;
425        stopReads = false;
426
427        if (!nextReqEvent.scheduled())
428            schedule(nextReqEvent, busBusyUntil);
429    } else {
430        assert(!writeEvent.scheduled());
431        DPRINTF(DRAM, "Next write scheduled at %lld\n", newTime);
432        schedule(writeEvent, newTime);
433    }
434
435    if (retryWrReq) {
436        retryWrReq = false;
437        port.sendRetry();
438    }
439
440    // if there is nothing left in any queue, signal a drain
441    if (writeQueue.empty() && readQueue.empty() &&
442        respQueue.empty () && drainManager) {
443        drainManager->signalDrainDone();
444        drainManager = NULL;
445    }
446}
447
448
449void
450SimpleDRAM::triggerWrites()
451{
452    DPRINTF(DRAM, "Writes triggered at %lld\n", curTick());
453    // Flag variable to stop any more read scheduling
454    stopReads = true;
455
456    writeStartTime = std::max(busBusyUntil, curTick()) + tWTR;
457
458    DPRINTF(DRAM, "Writes scheduled at %lld\n", writeStartTime);
459
460    assert(writeStartTime >= curTick());
461    assert(!writeEvent.scheduled());
462    schedule(writeEvent, writeStartTime);
463}
464
465void
466SimpleDRAM::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
467{
468    // only add to the write queue here. whenever the request is
469    // eventually done, set the readyTime, and call schedule()
470    assert(pkt->isWrite());
471
472    // if the request size is larger than burst size, the pkt is split into
473    // multiple DRAM packets
474    Addr addr = pkt->getAddr();
475    for (int cnt = 0; cnt < pktCount; ++cnt) {
476        unsigned size = std::min((addr | (burstSize - 1)) + 1,
477                        pkt->getAddr() + pkt->getSize()) - addr;
478        writePktSize[ceilLog2(size)]++;
479        writeBursts++;
480
481        // see if we can merge with an existing item in the write
482        // queue and keep track of whether we have merged or not so we
483        // can stop at that point and also avoid enqueueing a new
484        // request
485        bool merged = false;
486        auto w = writeQueue.begin();
487
488        while(!merged && w != writeQueue.end()) {
489            // either of the two could be first, if they are the same
490            // it does not matter which way we go
491            if ((*w)->addr >= addr) {
492                // the existing one starts after the new one, figure
493                // out where the new one ends with respect to the
494                // existing one
495                if ((addr + size) >= ((*w)->addr + (*w)->size)) {
496                    // check if the existing one is completely
497                    // subsumed in the new one
498                    DPRINTF(DRAM, "Merging write covering existing burst\n");
499                    merged = true;
500                    // update both the address and the size
501                    (*w)->addr = addr;
502                    (*w)->size = size;
503                } else if ((addr + size) >= (*w)->addr &&
504                           ((*w)->addr + (*w)->size - addr) <= burstSize) {
505                    // the new one is just before or partially
506                    // overlapping with the existing one, and together
507                    // they fit within a burst
508                    DPRINTF(DRAM, "Merging write before existing burst\n");
509                    merged = true;
510                    // the existing queue item needs to be adjusted with
511                    // respect to both address and size
512                    (*w)->addr = addr;
513                    (*w)->size = (*w)->addr + (*w)->size - addr;
514                }
515            } else {
516                // the new one starts after the current one, figure
517                // out where the existing one ends with respect to the
518                // new one
519                if (((*w)->addr + (*w)->size) >= (addr + size)) {
520                    // check if the new one is completely subsumed in the
521                    // existing one
522                    DPRINTF(DRAM, "Merging write into existing burst\n");
523                    merged = true;
524                    // no adjustments necessary
525                } else if (((*w)->addr + (*w)->size) >= addr &&
526                           (addr + size - (*w)->addr) <= burstSize) {
527                    // the existing one is just before or partially
528                    // overlapping with the new one, and together
529                    // they fit within a burst
530                    DPRINTF(DRAM, "Merging write after existing burst\n");
531                    merged = true;
532                    // the address is right, and only the size has
533                    // to be adjusted
534                    (*w)->size = addr + size - (*w)->addr;
535                }
536            }
537            ++w;
538        }
539
540        // if the item was not merged we need to create a new write
541        // and enqueue it
542        if (!merged) {
543            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
544
545            assert(writeQueue.size() < writeBufferSize);
546            wrQLenPdf[writeQueue.size()]++;
547
548            DPRINTF(DRAM, "Adding to write queue\n");
549
550            writeQueue.push_back(dram_pkt);
551
552            // Update stats
553            assert(dram_pkt->bankId < ranksPerChannel * banksPerRank);
554            perBankWrReqs[dram_pkt->bankId]++;
555
556            avgWrQLen = writeQueue.size();
557        }
558
559        bytesConsumedWr += size;
560        bytesWritten += burstSize;
561
562        // Starting address of next dram pkt (aligend to burstSize boundary)
563        addr = (addr | (burstSize - 1)) + 1;
564    }
565
566    // we do not wait for the writes to be send to the actual memory,
567    // but instead take responsibility for the consistency here and
568    // snoop the write queue for any upcoming reads
569    // @todo, if a pkt size is larger than burst size, we might need a
570    // different front end latency
571    accessAndRespond(pkt, frontendLatency);
572
573    // If your write buffer is starting to fill up, drain it!
574    if (writeQueue.size() >= writeHighThreshold && !stopReads){
575        triggerWrites();
576    }
577}
578
579void
580SimpleDRAM::printParams() const
581{
582    // Sanity check print of important parameters
583    DPRINTF(DRAM,
584            "Memory controller %s physical organization\n"      \
585            "Number of devices per rank   %d\n"                 \
586            "Device bus width (in bits)   %d\n"                 \
587            "DRAM data bus burst          %d\n"                 \
588            "Row buffer size              %d\n"                 \
589            "Columns per row buffer       %d\n"                 \
590            "Rows    per bank             %d\n"                 \
591            "Banks   per rank             %d\n"                 \
592            "Ranks   per channel          %d\n"                 \
593            "Total mem capacity           %u\n",
594            name(), devicesPerRank, deviceBusWidth, burstSize, rowBufferSize,
595            columnsPerRowBuffer, rowsPerBank, banksPerRank, ranksPerChannel,
596            rowBufferSize * rowsPerBank * banksPerRank * ranksPerChannel);
597
598    string scheduler =  memSchedPolicy == Enums::fcfs ? "FCFS" : "FR-FCFS";
599    string address_mapping = addrMapping == Enums::RaBaChCo ? "RaBaChCo" :
600        (addrMapping == Enums::RaBaCoCh ? "RaBaCoCh" : "CoRaBaCh");
601    string page_policy = pageMgmt == Enums::open ? "OPEN" :
602        (pageMgmt == Enums::open_adaptive ? "OPEN (adaptive)" : "CLOSE");
603
604    DPRINTF(DRAM,
605            "Memory controller %s characteristics\n"    \
606            "Read buffer size     %d\n"                 \
607            "Write buffer size    %d\n"                 \
608            "Write buffer thresh  %d\n"                 \
609            "Scheduler            %s\n"                 \
610            "Address mapping      %s\n"                 \
611            "Page policy          %s\n",
612            name(), readBufferSize, writeBufferSize, writeHighThreshold,
613            scheduler, address_mapping, page_policy);
614
615    DPRINTF(DRAM, "Memory controller %s timing specs\n" \
616            "tRCD      %d ticks\n"                        \
617            "tCL       %d ticks\n"                        \
618            "tRP       %d ticks\n"                        \
619            "tBURST    %d ticks\n"                        \
620            "tRFC      %d ticks\n"                        \
621            "tREFI     %d ticks\n"                        \
622            "tWTR      %d ticks\n"                        \
623            "tXAW (%d) %d ticks\n",
624            name(), tRCD, tCL, tRP, tBURST, tRFC, tREFI, tWTR,
625            activationLimit, tXAW);
626}
627
628void
629SimpleDRAM::printQs() const {
630    DPRINTF(DRAM, "===READ QUEUE===\n\n");
631    for (auto i = readQueue.begin() ;  i != readQueue.end() ; ++i) {
632        DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
633    }
634    DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
635    for (auto i = respQueue.begin() ;  i != respQueue.end() ; ++i) {
636        DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
637    }
638    DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
639    for (auto i = writeQueue.begin() ;  i != writeQueue.end() ; ++i) {
640        DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
641    }
642}
643
644bool
645SimpleDRAM::recvTimingReq(PacketPtr pkt)
646{
647    /// @todo temporary hack to deal with memory corruption issues until
648    /// 4-phase transactions are complete
649    for (int x = 0; x < pendingDelete.size(); x++)
650        delete pendingDelete[x];
651    pendingDelete.clear();
652
653    // This is where we enter from the outside world
654    DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
655            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
656
657    // simply drop inhibited packets for now
658    if (pkt->memInhibitAsserted()) {
659        DPRINTF(DRAM,"Inhibited packet -- Dropping it now\n");
660        pendingDelete.push_back(pkt);
661        return true;
662    }
663
664   // Every million accesses, print the state of the queues
665   if (numReqs % 1000000 == 0)
666       printQs();
667
668    // Calc avg gap between requests
669    if (prevArrival != 0) {
670        totGap += curTick() - prevArrival;
671    }
672    prevArrival = curTick();
673
674
675    // Find out how many dram packets a pkt translates to
676    // If the burst size is equal or larger than the pkt size, then a pkt
677    // translates to only one dram packet. Otherwise, a pkt translates to
678    // multiple dram packets
679    unsigned size = pkt->getSize();
680    unsigned offset = pkt->getAddr() & (burstSize - 1);
681    unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
682
683    // check local buffers and do not accept if full
684    if (pkt->isRead()) {
685        assert(size != 0);
686        if (readQueueFull(dram_pkt_count)) {
687            DPRINTF(DRAM, "Read queue full, not accepting\n");
688            // remember that we have to retry this port
689            retryRdReq = true;
690            numRdRetry++;
691            return false;
692        } else {
693            addToReadQueue(pkt, dram_pkt_count);
694            readReqs++;
695            numReqs++;
696        }
697    } else if (pkt->isWrite()) {
698        assert(size != 0);
699        if (writeQueueFull(dram_pkt_count)) {
700            DPRINTF(DRAM, "Write queue full, not accepting\n");
701            // remember that we have to retry this port
702            retryWrReq = true;
703            numWrRetry++;
704            return false;
705        } else {
706            addToWriteQueue(pkt, dram_pkt_count);
707            writeReqs++;
708            numReqs++;
709        }
710    } else {
711        DPRINTF(DRAM,"Neither read nor write, ignore timing\n");
712        neitherReadNorWrite++;
713        accessAndRespond(pkt, 1);
714    }
715
716    retryRdReq = false;
717    retryWrReq = false;
718    return true;
719}
720
721void
722SimpleDRAM::processRespondEvent()
723{
724    DPRINTF(DRAM,
725            "processRespondEvent(): Some req has reached its readyTime\n");
726
727    DRAMPacket* dram_pkt = respQueue.front();
728
729    // Actually responds to the requestor
730    bytesConsumedRd += dram_pkt->size;
731    bytesRead += burstSize;
732    if (dram_pkt->burstHelper) {
733        // it is a split packet
734        dram_pkt->burstHelper->burstsServiced++;
735        if (dram_pkt->burstHelper->burstsServiced ==
736                                  dram_pkt->burstHelper->burstCount) {
737            // we have now serviced all children packets of a system packet
738            // so we can now respond to the requester
739            // @todo we probably want to have a different front end and back
740            // end latency for split packets
741            accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
742            delete dram_pkt->burstHelper;
743            dram_pkt->burstHelper = NULL;
744        }
745    } else {
746        // it is not a split packet
747        accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
748    }
749
750    delete respQueue.front();
751    respQueue.pop_front();
752
753    // Update stats
754    avgRdQLen = readQueue.size() + respQueue.size();
755
756    if (!respQueue.empty()) {
757        assert(respQueue.front()->readyTime >= curTick());
758        assert(!respondEvent.scheduled());
759        schedule(respondEvent, respQueue.front()->readyTime);
760    } else {
761        // if there is nothing left in any queue, signal a drain
762        if (writeQueue.empty() && readQueue.empty() &&
763            drainManager) {
764            drainManager->signalDrainDone();
765            drainManager = NULL;
766        }
767    }
768
769    // We have made a location in the queue available at this point,
770    // so if there is a read that was forced to wait, retry now
771    if (retryRdReq) {
772        retryRdReq = false;
773        port.sendRetry();
774    }
775}
776
777void
778SimpleDRAM::chooseNextWrite()
779{
780    // This method does the arbitration between write requests. The
781    // chosen packet is simply moved to the head of the write
782    // queue. The other methods know that this is the place to
783    // look. For example, with FCFS, this method does nothing
784    assert(!writeQueue.empty());
785
786    if (writeQueue.size() == 1) {
787        DPRINTF(DRAM, "Single write request, nothing to do\n");
788        return;
789    }
790
791    if (memSchedPolicy == Enums::fcfs) {
792        // Do nothing, since the correct request is already head
793    } else if (memSchedPolicy == Enums::frfcfs) {
794        reorderQueue(writeQueue);
795    } else
796        panic("No scheduling policy chosen\n");
797
798    DPRINTF(DRAM, "Selected next write request\n");
799}
800
801bool
802SimpleDRAM::chooseNextRead()
803{
804    // This method does the arbitration between read requests. The
805    // chosen packet is simply moved to the head of the queue. The
806    // other methods know that this is the place to look. For example,
807    // with FCFS, this method does nothing
808    if (readQueue.empty()) {
809        DPRINTF(DRAM, "No read request to select\n");
810        return false;
811    }
812
813    // If there is only one request then there is nothing left to do
814    if (readQueue.size() == 1)
815        return true;
816
817    if (memSchedPolicy == Enums::fcfs) {
818        // Do nothing, since the request to serve is already the first
819        // one in the read queue
820    } else if (memSchedPolicy == Enums::frfcfs) {
821        reorderQueue(readQueue);
822    } else
823        panic("No scheduling policy chosen!\n");
824
825    DPRINTF(DRAM, "Selected next read request\n");
826    return true;
827}
828
829void
830SimpleDRAM::reorderQueue(std::deque<DRAMPacket*>& queue)
831{
832    // Only determine this when needed
833    uint64_t earliest_banks = 0;
834
835    // Search for row hits first, if no row hit is found then schedule the
836    // packet to one of the earliest banks available
837    bool found_earliest_pkt = false;
838    auto selected_pkt_it = queue.begin();
839
840    for (auto i = queue.begin(); i != queue.end() ; ++i) {
841        DRAMPacket* dram_pkt = *i;
842        const Bank& bank = dram_pkt->bankRef;
843        // Check if it is a row hit
844        if (bank.openRow == dram_pkt->row) {
845            DPRINTF(DRAM, "Row buffer hit\n");
846            selected_pkt_it = i;
847            break;
848        } else if (!found_earliest_pkt) {
849            // No row hit, go for first ready
850            if (earliest_banks == 0)
851                earliest_banks = minBankFreeAt(queue);
852
853            // Bank is ready or is the first available bank
854            if (bank.freeAt <= curTick() ||
855                bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
856                // Remember the packet to be scheduled to one of the earliest
857                // banks available
858                selected_pkt_it = i;
859                found_earliest_pkt = true;
860            }
861        }
862    }
863
864    DRAMPacket* selected_pkt = *selected_pkt_it;
865    queue.erase(selected_pkt_it);
866    queue.push_front(selected_pkt);
867}
868
869void
870SimpleDRAM::accessAndRespond(PacketPtr pkt, Tick static_latency)
871{
872    DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
873
874    bool needsResponse = pkt->needsResponse();
875    // do the actual memory access which also turns the packet into a
876    // response
877    access(pkt);
878
879    // turn packet around to go back to requester if response expected
880    if (needsResponse) {
881        // access already turned the packet into a response
882        assert(pkt->isResponse());
883
884        // @todo someone should pay for this
885        pkt->busFirstWordDelay = pkt->busLastWordDelay = 0;
886
887        // queue the packet in the response queue to be sent out after
888        // the static latency has passed
889        port.schedTimingResp(pkt, curTick() + static_latency);
890    } else {
891        // @todo the packet is going to be deleted, and the DRAMPacket
892        // is still having a pointer to it
893        pendingDelete.push_back(pkt);
894    }
895
896    DPRINTF(DRAM, "Done\n");
897
898    return;
899}
900
901pair<Tick, Tick>
902SimpleDRAM::estimateLatency(DRAMPacket* dram_pkt, Tick inTime)
903{
904    // If a request reaches a bank at tick 'inTime', how much time
905    // *after* that does it take to finish the request, depending
906    // on bank status and page open policy. Note that this method
907    // considers only the time taken for the actual read or write
908    // to complete, NOT any additional time thereafter for tRAS or
909    // tRP.
910    Tick accLat = 0;
911    Tick bankLat = 0;
912    rowHitFlag = false;
913    Tick potentialActTick;
914
915    const Bank& bank = dram_pkt->bankRef;
916     // open-page policy
917    if (pageMgmt == Enums::open || pageMgmt == Enums::open_adaptive) {
918        if (bank.openRow == dram_pkt->row) {
919            // When we have a row-buffer hit,
920            // we don't care about tRAS having expired or not,
921            // but do care about bank being free for access
922            rowHitFlag = true;
923
924            // When a series of requests arrive to the same row,
925            // DDR systems are capable of streaming data continuously
926            // at maximum bandwidth (subject to tCCD). Here, we approximate
927            // this condition, and assume that if whenever a bank is already
928            // busy and a new request comes in, it can be completed with no
929            // penalty beyond waiting for the existing read to complete.
930            if (bank.freeAt > inTime) {
931                accLat += bank.freeAt - inTime;
932                bankLat += 0;
933            } else {
934               // CAS latency only
935               accLat += tCL;
936               bankLat += tCL;
937            }
938
939        } else {
940            // Row-buffer miss, need to close existing row
941            // once tRAS has expired, then open the new one,
942            // then add cas latency.
943            Tick freeTime = std::max(bank.tRASDoneAt, bank.freeAt);
944
945            if (freeTime > inTime)
946               accLat += freeTime - inTime;
947
948            // If the there is no open row (open adaptive), then there
949            // is no precharge delay, otherwise go with tRP
950            Tick precharge_delay = bank.openRow == -1 ? 0 : tRP;
951
952            //The bank is free, and you may be able to activate
953            potentialActTick = inTime + accLat + precharge_delay;
954            if (potentialActTick < bank.actAllowedAt)
955                accLat += bank.actAllowedAt - potentialActTick;
956
957            accLat += precharge_delay + tRCD + tCL;
958            bankLat += precharge_delay + tRCD + tCL;
959        }
960    } else if (pageMgmt == Enums::close) {
961        // With a close page policy, no notion of
962        // bank.tRASDoneAt
963        if (bank.freeAt > inTime)
964            accLat += bank.freeAt - inTime;
965
966        //The bank is free, and you may be able to activate
967        potentialActTick = inTime + accLat;
968        if (potentialActTick < bank.actAllowedAt)
969            accLat += bank.actAllowedAt - potentialActTick;
970
971        // page already closed, simply open the row, and
972        // add cas latency
973        accLat += tRCD + tCL;
974        bankLat += tRCD + tCL;
975    } else
976        panic("No page management policy chosen\n");
977
978    DPRINTF(DRAM, "Returning < %lld, %lld > from estimateLatency()\n",
979            bankLat, accLat);
980
981    return make_pair(bankLat, accLat);
982}
983
984void
985SimpleDRAM::processNextReqEvent()
986{
987    scheduleNextReq();
988}
989
990void
991SimpleDRAM::recordActivate(Tick act_tick, uint8_t rank, uint8_t bank)
992{
993    assert(0 <= rank && rank < ranksPerChannel);
994    assert(actTicks[rank].size() == activationLimit);
995
996    DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
997
998    // start by enforcing tRRD
999    for(int i = 0; i < banksPerRank; i++) {
1000        // next activate must not happen before tRRD
1001        banks[rank][i].actAllowedAt = act_tick + tRRD;
1002    }
1003    // tRC should be added to activation tick of the bank currently accessed,
1004    // where tRC = tRAS + tRP, this is just for a check as actAllowedAt for same
1005    // bank is already captured by bank.freeAt and bank.tRASDoneAt
1006    banks[rank][bank].actAllowedAt = act_tick + tRAS + tRP;
1007
1008    // next, we deal with tXAW, if the activation limit is disabled
1009    // then we are done
1010    if (actTicks[rank].empty())
1011        return;
1012
1013    // sanity check
1014    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
1015        // @todo For now, stick with a warning
1016        warn("Got %d activates in window %d (%d - %d) which is smaller "
1017             "than %d\n", activationLimit, act_tick - actTicks[rank].back(),
1018             act_tick, actTicks[rank].back(), tXAW);
1019    }
1020
1021    // shift the times used for the book keeping, the last element
1022    // (highest index) is the oldest one and hence the lowest value
1023    actTicks[rank].pop_back();
1024
1025    // record an new activation (in the future)
1026    actTicks[rank].push_front(act_tick);
1027
1028    // cannot activate more than X times in time window tXAW, push the
1029    // next one (the X + 1'st activate) to be tXAW away from the
1030    // oldest in our window of X
1031    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
1032        DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate no earlier "
1033                "than %d\n", activationLimit, actTicks[rank].back() + tXAW);
1034            for(int j = 0; j < banksPerRank; j++)
1035                // next activate must not happen before end of window
1036                banks[rank][j].actAllowedAt = actTicks[rank].back() + tXAW;
1037    }
1038}
1039
1040void
1041SimpleDRAM::doDRAMAccess(DRAMPacket* dram_pkt)
1042{
1043
1044    DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1045            dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1046
1047    // estimate the bank and access latency
1048    pair<Tick, Tick> lat = estimateLatency(dram_pkt, curTick());
1049    Tick bankLat = lat.first;
1050    Tick accessLat = lat.second;
1051    Tick actTick;
1052
1053    // This request was woken up at this time based on a prior call
1054    // to estimateLatency(). However, between then and now, both the
1055    // accessLatency and/or busBusyUntil may have changed. We need
1056    // to correct for that.
1057
1058    Tick addDelay = (curTick() + accessLat < busBusyUntil) ?
1059        busBusyUntil - (curTick() + accessLat) : 0;
1060
1061    Bank& bank = dram_pkt->bankRef;
1062
1063    // Update bank state
1064    if (pageMgmt == Enums::open || pageMgmt == Enums::open_adaptive) {
1065        bank.openRow = dram_pkt->row;
1066        bank.freeAt = curTick() + addDelay + accessLat;
1067        bank.bytesAccessed += burstSize;
1068
1069        // If you activated a new row do to this access, the next access
1070        // will have to respect tRAS for this bank.
1071        if (!rowHitFlag) {
1072            // any waiting for banks account for in freeAt
1073            actTick = bank.freeAt - tCL - tRCD;
1074            bank.tRASDoneAt = actTick + tRAS;
1075            recordActivate(actTick, dram_pkt->rank, dram_pkt->bank);
1076
1077            // sample the number of bytes accessed and reset it as
1078            // we are now closing this row
1079            bytesPerActivate.sample(bank.bytesAccessed);
1080            bank.bytesAccessed = 0;
1081        }
1082
1083        if (pageMgmt == Enums::open_adaptive) {
1084            // a twist on the open page policy is to not blindly keep the
1085            // page open, but close it if there are no row hits, and there
1086            // are bank conflicts in the queue
1087            bool got_more_hits = false;
1088            bool got_bank_conflict = false;
1089
1090            // either look at the read queue or write queue
1091            const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
1092                writeQueue;
1093            auto p = queue.begin();
1094            // make sure we are not considering the packet that we are
1095            // currently dealing with (which is the head of the queue)
1096            ++p;
1097
1098            // keep on looking until we have found both or reached
1099            // the end
1100            while (!(got_more_hits && got_bank_conflict) &&
1101                   p != queue.end()) {
1102                bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
1103                    (dram_pkt->bank == (*p)->bank);
1104                bool same_row = dram_pkt->row == (*p)->row;
1105                got_more_hits |= same_rank_bank && same_row;
1106                got_bank_conflict |= same_rank_bank && !same_row;
1107                ++p;
1108            }
1109
1110            // auto pre-charge
1111            if (!got_more_hits && got_bank_conflict) {
1112                bank.openRow = -1;
1113                bank.freeAt = std::max(bank.freeAt, bank.tRASDoneAt) + tRP;
1114            }
1115        }
1116
1117        DPRINTF(DRAM, "doDRAMAccess::bank.freeAt is %lld\n", bank.freeAt);
1118    } else if (pageMgmt == Enums::close) {
1119        actTick = curTick() + addDelay + accessLat - tRCD - tCL;
1120        recordActivate(actTick, dram_pkt->rank, dram_pkt->bank);
1121
1122        // If the DRAM has a very quick tRAS, bank can be made free
1123        // after consecutive tCL,tRCD,tRP times. In general, however,
1124        // an additional wait is required to respect tRAS.
1125        bank.freeAt = std::max(actTick + tRAS + tRP,
1126                actTick + tRCD + tCL + tRP);
1127        DPRINTF(DRAM, "doDRAMAccess::bank.freeAt is %lld\n", bank.freeAt);
1128        bytesPerActivate.sample(burstSize);
1129    } else
1130        panic("No page management policy chosen\n");
1131
1132    // Update request parameters
1133    dram_pkt->readyTime = curTick() + addDelay + accessLat + tBURST;
1134
1135
1136    DPRINTF(DRAM, "Req %lld: curtick is %lld accessLat is %d " \
1137                  "readytime is %lld busbusyuntil is %lld. " \
1138                  "Scheduling at readyTime\n", dram_pkt->addr,
1139                   curTick(), accessLat, dram_pkt->readyTime, busBusyUntil);
1140
1141    // Make sure requests are not overlapping on the databus
1142    assert (dram_pkt->readyTime - busBusyUntil >= tBURST);
1143
1144    // Update bus state
1145    busBusyUntil = dram_pkt->readyTime;
1146
1147    DPRINTF(DRAM,"Access time is %lld\n",
1148            dram_pkt->readyTime - dram_pkt->entryTime);
1149
1150    if (rowHitFlag) {
1151        if(dram_pkt->isRead)
1152            readRowHits++;
1153         else
1154            writeRowHits++;
1155    }
1156
1157    // Update the minimum timing between the requests
1158    newTime = (busBusyUntil > tRP + tRCD + tCL) ?
1159        std::max(busBusyUntil - (tRP + tRCD + tCL), curTick()) : curTick();
1160
1161    // At this point, commonality between reads and writes ends.
1162    // For writes, we are done since we long ago responded to the
1163    // requestor. We also don't care about stats for writes. For
1164    // reads, we still need to figure out respoding to the requestor,
1165    // and capture stats.
1166
1167    if (!dram_pkt->isRead) {
1168        return;
1169    }
1170
1171    // Update stats
1172    totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1173    totBankLat += bankLat;
1174    totBusLat += tBURST;
1175    totQLat += dram_pkt->readyTime - dram_pkt->entryTime - bankLat - tBURST;
1176
1177
1178    // At this point we're done dealing with the request
1179    // It will be moved to a separate response queue with a
1180    // correct readyTime, and eventually be sent back at that
1181    //time
1182    moveToRespQ();
1183
1184    // Schedule the next read event
1185    if (!nextReqEvent.scheduled() && !stopReads){
1186        schedule(nextReqEvent, newTime);
1187    } else {
1188        if (newTime < nextReqEvent.when())
1189            reschedule(nextReqEvent, newTime);
1190    }
1191}
1192
1193void
1194SimpleDRAM::moveToRespQ()
1195{
1196    // Remove from read queue
1197    DRAMPacket* dram_pkt = readQueue.front();
1198    readQueue.pop_front();
1199
1200    // sanity check
1201    assert(dram_pkt->size <= burstSize);
1202
1203    // Insert into response queue sorted by readyTime
1204    // It will be sent back to the requestor at its
1205    // readyTime
1206    if (respQueue.empty()) {
1207        respQueue.push_front(dram_pkt);
1208        assert(!respondEvent.scheduled());
1209        assert(dram_pkt->readyTime >= curTick());
1210        schedule(respondEvent, dram_pkt->readyTime);
1211    } else {
1212        bool done = false;
1213        auto i = respQueue.begin();
1214        while (!done && i != respQueue.end()) {
1215            if ((*i)->readyTime > dram_pkt->readyTime) {
1216                respQueue.insert(i, dram_pkt);
1217                done = true;
1218            }
1219            ++i;
1220        }
1221
1222        if (!done)
1223            respQueue.push_back(dram_pkt);
1224
1225        assert(respondEvent.scheduled());
1226
1227        if (respQueue.front()->readyTime < respondEvent.when()) {
1228            assert(respQueue.front()->readyTime >= curTick());
1229            reschedule(respondEvent, respQueue.front()->readyTime);
1230        }
1231    }
1232}
1233
1234void
1235SimpleDRAM::scheduleNextReq()
1236{
1237    DPRINTF(DRAM, "Reached scheduleNextReq()\n");
1238
1239    // Figure out which read request goes next, and move it to the
1240    // front of the read queue
1241    if (!chooseNextRead()) {
1242        // In the case there is no read request to go next, see if we
1243        // are asked to drain, and if so trigger writes, this also
1244        // ensures that if we hit the write limit we will do this
1245        // multiple times until we are completely drained
1246        if (drainManager && !writeQueue.empty() && !writeEvent.scheduled())
1247            triggerWrites();
1248    } else {
1249        doDRAMAccess(readQueue.front());
1250    }
1251}
1252
1253Tick
1254SimpleDRAM::maxBankFreeAt() const
1255{
1256    Tick banksFree = 0;
1257
1258    for(int i = 0; i < ranksPerChannel; i++)
1259        for(int j = 0; j < banksPerRank; j++)
1260            banksFree = std::max(banks[i][j].freeAt, banksFree);
1261
1262    return banksFree;
1263}
1264
1265uint64_t
1266SimpleDRAM::minBankFreeAt(const deque<DRAMPacket*>& queue) const
1267{
1268    uint64_t bank_mask = 0;
1269    Tick freeAt = MaxTick;
1270
1271    // detemrine if we have queued transactions targetting the
1272    // bank in question
1273    vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
1274    for (auto p = queue.begin(); p != queue.end(); ++p) {
1275        got_waiting[(*p)->bankId] = true;
1276    }
1277
1278    for (int i = 0; i < ranksPerChannel; i++) {
1279        for (int j = 0; j < banksPerRank; j++) {
1280            // if we have waiting requests for the bank, and it is
1281            // amongst the first available, update the mask
1282            if (got_waiting[i * banksPerRank + j] &&
1283                banks[i][j].freeAt <= freeAt) {
1284                // reset bank mask if new minimum is found
1285                if (banks[i][j].freeAt < freeAt)
1286                    bank_mask = 0;
1287                // set the bit corresponding to the available bank
1288                uint8_t bit_index = i * ranksPerChannel + j;
1289                replaceBits(bank_mask, bit_index, bit_index, 1);
1290                freeAt = banks[i][j].freeAt;
1291            }
1292        }
1293    }
1294    return bank_mask;
1295}
1296
1297void
1298SimpleDRAM::processRefreshEvent()
1299{
1300    DPRINTF(DRAM, "Refreshing at tick %ld\n", curTick());
1301
1302    Tick banksFree = std::max(curTick(), maxBankFreeAt()) + tRFC;
1303
1304    for(int i = 0; i < ranksPerChannel; i++)
1305        for(int j = 0; j < banksPerRank; j++)
1306            banks[i][j].freeAt = banksFree;
1307
1308    schedule(refreshEvent, curTick() + tREFI);
1309}
1310
1311void
1312SimpleDRAM::regStats()
1313{
1314    using namespace Stats;
1315
1316    AbstractMemory::regStats();
1317
1318    readReqs
1319        .name(name() + ".readReqs")
1320        .desc("Total number of read requests accepted by DRAM controller");
1321
1322    writeReqs
1323        .name(name() + ".writeReqs")
1324        .desc("Total number of write requests accepted by DRAM controller");
1325
1326    readBursts
1327        .name(name() + ".readBursts")
1328        .desc("Total number of DRAM read bursts. "
1329              "Each DRAM read request translates to either one or multiple "
1330              "DRAM read bursts");
1331
1332    writeBursts
1333        .name(name() + ".writeBursts")
1334        .desc("Total number of DRAM write bursts. "
1335              "Each DRAM write request translates to either one or multiple "
1336              "DRAM write bursts");
1337
1338    servicedByWrQ
1339        .name(name() + ".servicedByWrQ")
1340        .desc("Number of DRAM read bursts serviced by write Q");
1341
1342    neitherReadNorWrite
1343        .name(name() + ".neitherReadNorWrite")
1344        .desc("Reqs where no action is needed");
1345
1346    perBankRdReqs
1347        .init(banksPerRank * ranksPerChannel)
1348        .name(name() + ".perBankRdReqs")
1349        .desc("Track reads on a per bank basis");
1350
1351    perBankWrReqs
1352        .init(banksPerRank * ranksPerChannel)
1353        .name(name() + ".perBankWrReqs")
1354        .desc("Track writes on a per bank basis");
1355
1356    avgRdQLen
1357        .name(name() + ".avgRdQLen")
1358        .desc("Average read queue length over time")
1359        .precision(2);
1360
1361    avgWrQLen
1362        .name(name() + ".avgWrQLen")
1363        .desc("Average write queue length over time")
1364        .precision(2);
1365
1366    totQLat
1367        .name(name() + ".totQLat")
1368        .desc("Total cycles spent in queuing delays");
1369
1370    totBankLat
1371        .name(name() + ".totBankLat")
1372        .desc("Total cycles spent in bank access");
1373
1374    totBusLat
1375        .name(name() + ".totBusLat")
1376        .desc("Total cycles spent in databus access");
1377
1378    totMemAccLat
1379        .name(name() + ".totMemAccLat")
1380        .desc("Sum of mem lat for all requests");
1381
1382    avgQLat
1383        .name(name() + ".avgQLat")
1384        .desc("Average queueing delay per request")
1385        .precision(2);
1386
1387    avgQLat = totQLat / (readBursts - servicedByWrQ);
1388
1389    avgBankLat
1390        .name(name() + ".avgBankLat")
1391        .desc("Average bank access latency per request")
1392        .precision(2);
1393
1394    avgBankLat = totBankLat / (readBursts - servicedByWrQ);
1395
1396    avgBusLat
1397        .name(name() + ".avgBusLat")
1398        .desc("Average bus latency per request")
1399        .precision(2);
1400
1401    avgBusLat = totBusLat / (readBursts - servicedByWrQ);
1402
1403    avgMemAccLat
1404        .name(name() + ".avgMemAccLat")
1405        .desc("Average memory access latency")
1406        .precision(2);
1407
1408    avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
1409
1410    numRdRetry
1411        .name(name() + ".numRdRetry")
1412        .desc("Number of times rd buffer was full causing retry");
1413
1414    numWrRetry
1415        .name(name() + ".numWrRetry")
1416        .desc("Number of times wr buffer was full causing retry");
1417
1418    readRowHits
1419        .name(name() + ".readRowHits")
1420        .desc("Number of row buffer hits during reads");
1421
1422    writeRowHits
1423        .name(name() + ".writeRowHits")
1424        .desc("Number of row buffer hits during writes");
1425
1426    readRowHitRate
1427        .name(name() + ".readRowHitRate")
1428        .desc("Row buffer hit rate for reads")
1429        .precision(2);
1430
1431    readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
1432
1433    writeRowHitRate
1434        .name(name() + ".writeRowHitRate")
1435        .desc("Row buffer hit rate for writes")
1436        .precision(2);
1437
1438    writeRowHitRate = (writeRowHits / writeBursts) * 100;
1439
1440    readPktSize
1441        .init(ceilLog2(burstSize) + 1)
1442        .name(name() + ".readPktSize")
1443        .desc("Categorize read packet sizes");
1444
1445     writePktSize
1446        .init(ceilLog2(burstSize) + 1)
1447        .name(name() + ".writePktSize")
1448        .desc("Categorize write packet sizes");
1449
1450     rdQLenPdf
1451        .init(readBufferSize)
1452        .name(name() + ".rdQLenPdf")
1453        .desc("What read queue length does an incoming req see");
1454
1455     wrQLenPdf
1456        .init(writeBufferSize)
1457        .name(name() + ".wrQLenPdf")
1458        .desc("What write queue length does an incoming req see");
1459
1460     bytesPerActivate
1461         .init(rowBufferSize)
1462         .name(name() + ".bytesPerActivate")
1463         .desc("Bytes accessed per row activation")
1464         .flags(nozero);
1465
1466    bytesRead
1467        .name(name() + ".bytesRead")
1468        .desc("Total number of bytes read from memory");
1469
1470    bytesWritten
1471        .name(name() + ".bytesWritten")
1472        .desc("Total number of bytes written to memory");
1473
1474    bytesConsumedRd
1475        .name(name() + ".bytesConsumedRd")
1476        .desc("bytesRead derated as per pkt->getSize()");
1477
1478    bytesConsumedWr
1479        .name(name() + ".bytesConsumedWr")
1480        .desc("bytesWritten derated as per pkt->getSize()");
1481
1482    avgRdBW
1483        .name(name() + ".avgRdBW")
1484        .desc("Average achieved read bandwidth in MB/s")
1485        .precision(2);
1486
1487    avgRdBW = (bytesRead / 1000000) / simSeconds;
1488
1489    avgWrBW
1490        .name(name() + ".avgWrBW")
1491        .desc("Average achieved write bandwidth in MB/s")
1492        .precision(2);
1493
1494    avgWrBW = (bytesWritten / 1000000) / simSeconds;
1495
1496    avgConsumedRdBW
1497        .name(name() + ".avgConsumedRdBW")
1498        .desc("Average consumed read bandwidth in MB/s")
1499        .precision(2);
1500
1501    avgConsumedRdBW = (bytesConsumedRd / 1000000) / simSeconds;
1502
1503    avgConsumedWrBW
1504        .name(name() + ".avgConsumedWrBW")
1505        .desc("Average consumed write bandwidth in MB/s")
1506        .precision(2);
1507
1508    avgConsumedWrBW = (bytesConsumedWr / 1000000) / simSeconds;
1509
1510    peakBW
1511        .name(name() + ".peakBW")
1512        .desc("Theoretical peak bandwidth in MB/s")
1513        .precision(2);
1514
1515    peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
1516
1517    busUtil
1518        .name(name() + ".busUtil")
1519        .desc("Data bus utilization in percentage")
1520        .precision(2);
1521
1522    busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
1523
1524    totGap
1525        .name(name() + ".totGap")
1526        .desc("Total gap between requests");
1527
1528    avgGap
1529        .name(name() + ".avgGap")
1530        .desc("Average gap between requests")
1531        .precision(2);
1532
1533    avgGap = totGap / (readReqs + writeReqs);
1534}
1535
1536void
1537SimpleDRAM::recvFunctional(PacketPtr pkt)
1538{
1539    // rely on the abstract memory
1540    functionalAccess(pkt);
1541}
1542
1543BaseSlavePort&
1544SimpleDRAM::getSlavePort(const string &if_name, PortID idx)
1545{
1546    if (if_name != "port") {
1547        return MemObject::getSlavePort(if_name, idx);
1548    } else {
1549        return port;
1550    }
1551}
1552
1553unsigned int
1554SimpleDRAM::drain(DrainManager *dm)
1555{
1556    unsigned int count = port.drain(dm);
1557
1558    // if there is anything in any of our internal queues, keep track
1559    // of that as well
1560    if (!(writeQueue.empty() && readQueue.empty() &&
1561          respQueue.empty())) {
1562        DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
1563                " resp: %d\n", writeQueue.size(), readQueue.size(),
1564                respQueue.size());
1565        ++count;
1566        drainManager = dm;
1567        // the only part that is not drained automatically over time
1568        // is the write queue, thus trigger writes if there are any
1569        // waiting and no reads waiting, otherwise wait until the
1570        // reads are done
1571        if (readQueue.empty() && !writeQueue.empty() &&
1572            !writeEvent.scheduled())
1573            triggerWrites();
1574    }
1575
1576    if (count)
1577        setDrainState(Drainable::Draining);
1578    else
1579        setDrainState(Drainable::Drained);
1580    return count;
1581}
1582
1583SimpleDRAM::MemoryPort::MemoryPort(const std::string& name, SimpleDRAM& _memory)
1584    : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
1585      memory(_memory)
1586{ }
1587
1588AddrRangeList
1589SimpleDRAM::MemoryPort::getAddrRanges() const
1590{
1591    AddrRangeList ranges;
1592    ranges.push_back(memory.getAddrRange());
1593    return ranges;
1594}
1595
1596void
1597SimpleDRAM::MemoryPort::recvFunctional(PacketPtr pkt)
1598{
1599    pkt->pushLabel(memory.name());
1600
1601    if (!queue.checkFunctional(pkt)) {
1602        // Default implementation of SimpleTimingPort::recvFunctional()
1603        // calls recvAtomic() and throws away the latency; we can save a
1604        // little here by just not calculating the latency.
1605        memory.recvFunctional(pkt);
1606    }
1607
1608    pkt->popLabel();
1609}
1610
1611Tick
1612SimpleDRAM::MemoryPort::recvAtomic(PacketPtr pkt)
1613{
1614    return memory.recvAtomic(pkt);
1615}
1616
1617bool
1618SimpleDRAM::MemoryPort::recvTimingReq(PacketPtr pkt)
1619{
1620    // pass it to the memory controller
1621    return memory.recvTimingReq(pkt);
1622}
1623
1624SimpleDRAM*
1625SimpleDRAMParams::create()
1626{
1627    return new SimpleDRAM(this);
1628}
1629