dram_ctrl.cc revision 9972
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" : "CLOSE";
602
603    DPRINTF(DRAM,
604            "Memory controller %s characteristics\n"    \
605            "Read buffer size     %d\n"                 \
606            "Write buffer size    %d\n"                 \
607            "Write buffer thresh  %d\n"                 \
608            "Scheduler            %s\n"                 \
609            "Address mapping      %s\n"                 \
610            "Page policy          %s\n",
611            name(), readBufferSize, writeBufferSize, writeHighThreshold,
612            scheduler, address_mapping, page_policy);
613
614    DPRINTF(DRAM, "Memory controller %s timing specs\n" \
615            "tRCD      %d ticks\n"                        \
616            "tCL       %d ticks\n"                        \
617            "tRP       %d ticks\n"                        \
618            "tBURST    %d ticks\n"                        \
619            "tRFC      %d ticks\n"                        \
620            "tREFI     %d ticks\n"                        \
621            "tWTR      %d ticks\n"                        \
622            "tXAW (%d) %d ticks\n",
623            name(), tRCD, tCL, tRP, tBURST, tRFC, tREFI, tWTR,
624            activationLimit, tXAW);
625}
626
627void
628SimpleDRAM::printQs() const {
629    DPRINTF(DRAM, "===READ QUEUE===\n\n");
630    for (auto i = readQueue.begin() ;  i != readQueue.end() ; ++i) {
631        DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
632    }
633    DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
634    for (auto i = respQueue.begin() ;  i != respQueue.end() ; ++i) {
635        DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
636    }
637    DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
638    for (auto i = writeQueue.begin() ;  i != writeQueue.end() ; ++i) {
639        DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
640    }
641}
642
643bool
644SimpleDRAM::recvTimingReq(PacketPtr pkt)
645{
646    /// @todo temporary hack to deal with memory corruption issues until
647    /// 4-phase transactions are complete
648    for (int x = 0; x < pendingDelete.size(); x++)
649        delete pendingDelete[x];
650    pendingDelete.clear();
651
652    // This is where we enter from the outside world
653    DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
654            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
655
656    // simply drop inhibited packets for now
657    if (pkt->memInhibitAsserted()) {
658        DPRINTF(DRAM,"Inhibited packet -- Dropping it now\n");
659        pendingDelete.push_back(pkt);
660        return true;
661    }
662
663   // Every million accesses, print the state of the queues
664   if (numReqs % 1000000 == 0)
665       printQs();
666
667    // Calc avg gap between requests
668    if (prevArrival != 0) {
669        totGap += curTick() - prevArrival;
670    }
671    prevArrival = curTick();
672
673
674    // Find out how many dram packets a pkt translates to
675    // If the burst size is equal or larger than the pkt size, then a pkt
676    // translates to only one dram packet. Otherwise, a pkt translates to
677    // multiple dram packets
678    unsigned size = pkt->getSize();
679    unsigned offset = pkt->getAddr() & (burstSize - 1);
680    unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
681
682    // check local buffers and do not accept if full
683    if (pkt->isRead()) {
684        assert(size != 0);
685        if (readQueueFull(dram_pkt_count)) {
686            DPRINTF(DRAM, "Read queue full, not accepting\n");
687            // remember that we have to retry this port
688            retryRdReq = true;
689            numRdRetry++;
690            return false;
691        } else {
692            addToReadQueue(pkt, dram_pkt_count);
693            readReqs++;
694            numReqs++;
695        }
696    } else if (pkt->isWrite()) {
697        assert(size != 0);
698        if (writeQueueFull(dram_pkt_count)) {
699            DPRINTF(DRAM, "Write queue full, not accepting\n");
700            // remember that we have to retry this port
701            retryWrReq = true;
702            numWrRetry++;
703            return false;
704        } else {
705            addToWriteQueue(pkt, dram_pkt_count);
706            writeReqs++;
707            numReqs++;
708        }
709    } else {
710        DPRINTF(DRAM,"Neither read nor write, ignore timing\n");
711        neitherReadNorWrite++;
712        accessAndRespond(pkt, 1);
713    }
714
715    retryRdReq = false;
716    retryWrReq = false;
717    return true;
718}
719
720void
721SimpleDRAM::processRespondEvent()
722{
723    DPRINTF(DRAM,
724            "processRespondEvent(): Some req has reached its readyTime\n");
725
726    DRAMPacket* dram_pkt = respQueue.front();
727
728    // Actually responds to the requestor
729    bytesConsumedRd += dram_pkt->size;
730    bytesRead += burstSize;
731    if (dram_pkt->burstHelper) {
732        // it is a split packet
733        dram_pkt->burstHelper->burstsServiced++;
734        if (dram_pkt->burstHelper->burstsServiced ==
735                                  dram_pkt->burstHelper->burstCount) {
736            // we have now serviced all children packets of a system packet
737            // so we can now respond to the requester
738            // @todo we probably want to have a different front end and back
739            // end latency for split packets
740            accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
741            delete dram_pkt->burstHelper;
742            dram_pkt->burstHelper = NULL;
743        }
744    } else {
745        // it is not a split packet
746        accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
747    }
748
749    delete respQueue.front();
750    respQueue.pop_front();
751
752    // Update stats
753    avgRdQLen = readQueue.size() + respQueue.size();
754
755    if (!respQueue.empty()) {
756        assert(respQueue.front()->readyTime >= curTick());
757        assert(!respondEvent.scheduled());
758        schedule(respondEvent, respQueue.front()->readyTime);
759    } else {
760        // if there is nothing left in any queue, signal a drain
761        if (writeQueue.empty() && readQueue.empty() &&
762            drainManager) {
763            drainManager->signalDrainDone();
764            drainManager = NULL;
765        }
766    }
767
768    // We have made a location in the queue available at this point,
769    // so if there is a read that was forced to wait, retry now
770    if (retryRdReq) {
771        retryRdReq = false;
772        port.sendRetry();
773    }
774}
775
776void
777SimpleDRAM::chooseNextWrite()
778{
779    // This method does the arbitration between write requests. The
780    // chosen packet is simply moved to the head of the write
781    // queue. The other methods know that this is the place to
782    // look. For example, with FCFS, this method does nothing
783    assert(!writeQueue.empty());
784
785    if (writeQueue.size() == 1) {
786        DPRINTF(DRAM, "Single write request, nothing to do\n");
787        return;
788    }
789
790    if (memSchedPolicy == Enums::fcfs) {
791        // Do nothing, since the correct request is already head
792    } else if (memSchedPolicy == Enums::frfcfs) {
793        // Only determine bank availability when needed
794        uint64_t earliest_banks = 0;
795
796        auto i = writeQueue.begin();
797        bool foundRowHit = false;
798        while (!foundRowHit && i != writeQueue.end()) {
799            DRAMPacket* dram_pkt = *i;
800            const Bank& bank = dram_pkt->bankRef;
801            if (bank.openRow == dram_pkt->row) {
802                DPRINTF(DRAM, "Write row buffer hit\n");
803                writeQueue.erase(i);
804                writeQueue.push_front(dram_pkt);
805                foundRowHit = true;
806            } else {
807                // No row hit, go for first ready
808                if (earliest_banks == 0)
809                    earliest_banks = minBankFreeAt(writeQueue);
810
811                // Bank is ready or is one of the first available bank
812                if (bank.freeAt <= curTick() ||
813                    bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
814                    writeQueue.erase(i);
815                    writeQueue.push_front(dram_pkt);
816                    break;
817                }
818            }
819            ++i;
820        }
821    } else
822        panic("No scheduling policy chosen\n");
823
824    DPRINTF(DRAM, "Selected next write request\n");
825}
826
827bool
828SimpleDRAM::chooseNextRead()
829{
830    // This method does the arbitration between read requests. The
831    // chosen packet is simply moved to the head of the queue. The
832    // other methods know that this is the place to look. For example,
833    // with FCFS, this method does nothing
834    if (readQueue.empty()) {
835        DPRINTF(DRAM, "No read request to select\n");
836        return false;
837    }
838
839    // If there is only one request then there is nothing left to do
840    if (readQueue.size() == 1)
841        return true;
842
843    if (memSchedPolicy == Enums::fcfs) {
844        // Do nothing, since the request to serve is already the first
845        // one in the read queue
846    } else if (memSchedPolicy == Enums::frfcfs) {
847        // Only determine this when needed
848        uint64_t earliest_banks = 0;
849
850        for (auto i = readQueue.begin(); i != readQueue.end() ; ++i) {
851            DRAMPacket* dram_pkt = *i;
852            const Bank& bank = dram_pkt->bankRef;
853            // Check if it is a row hit
854            if (bank.openRow == dram_pkt->row) {
855                DPRINTF(DRAM, "Row buffer hit\n");
856                readQueue.erase(i);
857                readQueue.push_front(dram_pkt);
858                break;
859            } else {
860                // No row hit, go for first ready
861                if (earliest_banks == 0)
862                    earliest_banks = minBankFreeAt(readQueue);
863
864                // Bank is ready or is the first available bank
865                if (bank.freeAt <= curTick() ||
866                    bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
867                    readQueue.erase(i);
868                    readQueue.push_front(dram_pkt);
869                    break;
870                }
871            }
872        }
873    } else
874        panic("No scheduling policy chosen!\n");
875
876    DPRINTF(DRAM, "Selected next read request\n");
877    return true;
878}
879
880void
881SimpleDRAM::accessAndRespond(PacketPtr pkt, Tick static_latency)
882{
883    DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
884
885    bool needsResponse = pkt->needsResponse();
886    // do the actual memory access which also turns the packet into a
887    // response
888    access(pkt);
889
890    // turn packet around to go back to requester if response expected
891    if (needsResponse) {
892        // access already turned the packet into a response
893        assert(pkt->isResponse());
894
895        // @todo someone should pay for this
896        pkt->busFirstWordDelay = pkt->busLastWordDelay = 0;
897
898        // queue the packet in the response queue to be sent out after
899        // the static latency has passed
900        port.schedTimingResp(pkt, curTick() + static_latency);
901    } else {
902        // @todo the packet is going to be deleted, and the DRAMPacket
903        // is still having a pointer to it
904        pendingDelete.push_back(pkt);
905    }
906
907    DPRINTF(DRAM, "Done\n");
908
909    return;
910}
911
912pair<Tick, Tick>
913SimpleDRAM::estimateLatency(DRAMPacket* dram_pkt, Tick inTime)
914{
915    // If a request reaches a bank at tick 'inTime', how much time
916    // *after* that does it take to finish the request, depending
917    // on bank status and page open policy. Note that this method
918    // considers only the time taken for the actual read or write
919    // to complete, NOT any additional time thereafter for tRAS or
920    // tRP.
921    Tick accLat = 0;
922    Tick bankLat = 0;
923    rowHitFlag = false;
924    Tick potentialActTick;
925
926    const Bank& bank = dram_pkt->bankRef;
927    if (pageMgmt == Enums::open) { // open-page policy
928        if (bank.openRow == dram_pkt->row) {
929            // When we have a row-buffer hit,
930            // we don't care about tRAS having expired or not,
931            // but do care about bank being free for access
932            rowHitFlag = true;
933
934            // When a series of requests arrive to the same row,
935            // DDR systems are capable of streaming data continuously
936            // at maximum bandwidth (subject to tCCD). Here, we approximate
937            // this condition, and assume that if whenever a bank is already
938            // busy and a new request comes in, it can be completed with no
939            // penalty beyond waiting for the existing read to complete.
940            if (bank.freeAt > inTime) {
941                accLat += bank.freeAt - inTime;
942                bankLat += 0;
943            } else {
944               // CAS latency only
945               accLat += tCL;
946               bankLat += tCL;
947            }
948
949        } else {
950            // Row-buffer miss, need to close existing row
951            // once tRAS has expired, then open the new one,
952            // then add cas latency.
953            Tick freeTime = std::max(bank.tRASDoneAt, bank.freeAt);
954
955            if (freeTime > inTime)
956               accLat += freeTime - inTime;
957
958            //The bank is free, and you may be able to activate
959            potentialActTick = inTime + accLat + tRP;
960            if (potentialActTick < bank.actAllowedAt)
961                accLat += bank.actAllowedAt - potentialActTick;
962
963            accLat += tRP + tRCD + tCL;
964            bankLat += tRP + tRCD + tCL;
965        }
966    } else if (pageMgmt == Enums::close) {
967        // With a close page policy, no notion of
968        // bank.tRASDoneAt
969        if (bank.freeAt > inTime)
970            accLat += bank.freeAt - inTime;
971
972        //The bank is free, and you may be able to activate
973        potentialActTick = inTime + accLat;
974        if (potentialActTick < bank.actAllowedAt)
975            accLat += bank.actAllowedAt - potentialActTick;
976
977        // page already closed, simply open the row, and
978        // add cas latency
979        accLat += tRCD + tCL;
980        bankLat += tRCD + tCL;
981    } else
982        panic("No page management policy chosen\n");
983
984    DPRINTF(DRAM, "Returning < %lld, %lld > from estimateLatency()\n",
985            bankLat, accLat);
986
987    return make_pair(bankLat, accLat);
988}
989
990void
991SimpleDRAM::processNextReqEvent()
992{
993    scheduleNextReq();
994}
995
996void
997SimpleDRAM::recordActivate(Tick act_tick, uint8_t rank, uint8_t bank)
998{
999    assert(0 <= rank && rank < ranksPerChannel);
1000    assert(actTicks[rank].size() == activationLimit);
1001
1002    DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
1003
1004    // start by enforcing tRRD
1005    for(int i = 0; i < banksPerRank; i++) {
1006        // next activate must not happen before tRRD
1007        banks[rank][i].actAllowedAt = act_tick + tRRD;
1008    }
1009    // tRC should be added to activation tick of the bank currently accessed,
1010    // where tRC = tRAS + tRP, this is just for a check as actAllowedAt for same
1011    // bank is already captured by bank.freeAt and bank.tRASDoneAt
1012    banks[rank][bank].actAllowedAt = act_tick + tRAS + tRP;
1013
1014    // next, we deal with tXAW, if the activation limit is disabled
1015    // then we are done
1016    if (actTicks[rank].empty())
1017        return;
1018
1019    // sanity check
1020    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
1021        // @todo For now, stick with a warning
1022        warn("Got %d activates in window %d (%d - %d) which is smaller "
1023             "than %d\n", activationLimit, act_tick - actTicks[rank].back(),
1024             act_tick, actTicks[rank].back(), tXAW);
1025    }
1026
1027    // shift the times used for the book keeping, the last element
1028    // (highest index) is the oldest one and hence the lowest value
1029    actTicks[rank].pop_back();
1030
1031    // record an new activation (in the future)
1032    actTicks[rank].push_front(act_tick);
1033
1034    // cannot activate more than X times in time window tXAW, push the
1035    // next one (the X + 1'st activate) to be tXAW away from the
1036    // oldest in our window of X
1037    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
1038        DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate no earlier "
1039                "than %d\n", activationLimit, actTicks[rank].back() + tXAW);
1040            for(int j = 0; j < banksPerRank; j++)
1041                // next activate must not happen before end of window
1042                banks[rank][j].actAllowedAt = actTicks[rank].back() + tXAW;
1043    }
1044}
1045
1046void
1047SimpleDRAM::doDRAMAccess(DRAMPacket* dram_pkt)
1048{
1049
1050    DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1051            dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1052
1053    // estimate the bank and access latency
1054    pair<Tick, Tick> lat = estimateLatency(dram_pkt, curTick());
1055    Tick bankLat = lat.first;
1056    Tick accessLat = lat.second;
1057    Tick actTick;
1058
1059    // This request was woken up at this time based on a prior call
1060    // to estimateLatency(). However, between then and now, both the
1061    // accessLatency and/or busBusyUntil may have changed. We need
1062    // to correct for that.
1063
1064    Tick addDelay = (curTick() + accessLat < busBusyUntil) ?
1065        busBusyUntil - (curTick() + accessLat) : 0;
1066
1067    Bank& bank = dram_pkt->bankRef;
1068
1069    // Update bank state
1070    if (pageMgmt == Enums::open) {
1071        bank.openRow = dram_pkt->row;
1072        bank.freeAt = curTick() + addDelay + accessLat;
1073        bank.bytesAccessed += burstSize;
1074
1075        // If you activated a new row do to this access, the next access
1076        // will have to respect tRAS for this bank.
1077        if (!rowHitFlag) {
1078            // any waiting for banks account for in freeAt
1079            actTick = bank.freeAt - tCL - tRCD;
1080            bank.tRASDoneAt = actTick + tRAS;
1081            recordActivate(actTick, dram_pkt->rank, dram_pkt->bank);
1082
1083            // sample the number of bytes accessed and reset it as
1084            // we are now closing this row
1085            bytesPerActivate.sample(bank.bytesAccessed);
1086            bank.bytesAccessed = 0;
1087        }
1088        DPRINTF(DRAM, "doDRAMAccess::bank.freeAt is %lld\n", bank.freeAt);
1089    } else if (pageMgmt == Enums::close) {
1090        actTick = curTick() + addDelay + accessLat - tRCD - tCL;
1091        recordActivate(actTick, dram_pkt->rank, dram_pkt->bank);
1092
1093        // If the DRAM has a very quick tRAS, bank can be made free
1094        // after consecutive tCL,tRCD,tRP times. In general, however,
1095        // an additional wait is required to respect tRAS.
1096        bank.freeAt = std::max(actTick + tRAS + tRP,
1097                actTick + tRCD + tCL + tRP);
1098        DPRINTF(DRAM, "doDRAMAccess::bank.freeAt is %lld\n", bank.freeAt);
1099        bytesPerActivate.sample(burstSize);
1100    } else
1101        panic("No page management policy chosen\n");
1102
1103    // Update request parameters
1104    dram_pkt->readyTime = curTick() + addDelay + accessLat + tBURST;
1105
1106
1107    DPRINTF(DRAM, "Req %lld: curtick is %lld accessLat is %d " \
1108                  "readytime is %lld busbusyuntil is %lld. " \
1109                  "Scheduling at readyTime\n", dram_pkt->addr,
1110                   curTick(), accessLat, dram_pkt->readyTime, busBusyUntil);
1111
1112    // Make sure requests are not overlapping on the databus
1113    assert (dram_pkt->readyTime - busBusyUntil >= tBURST);
1114
1115    // Update bus state
1116    busBusyUntil = dram_pkt->readyTime;
1117
1118    DPRINTF(DRAM,"Access time is %lld\n",
1119            dram_pkt->readyTime - dram_pkt->entryTime);
1120
1121    if (rowHitFlag) {
1122        if(dram_pkt->isRead)
1123            readRowHits++;
1124         else
1125            writeRowHits++;
1126    }
1127
1128    // Update the minimum timing between the requests
1129    newTime = (busBusyUntil > tRP + tRCD + tCL) ?
1130        std::max(busBusyUntil - (tRP + tRCD + tCL), curTick()) : curTick();
1131
1132    // At this point, commonality between reads and writes ends.
1133    // For writes, we are done since we long ago responded to the
1134    // requestor. We also don't care about stats for writes. For
1135    // reads, we still need to figure out respoding to the requestor,
1136    // and capture stats.
1137
1138    if (!dram_pkt->isRead) {
1139        return;
1140    }
1141
1142    // Update stats
1143    totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1144    totBankLat += bankLat;
1145    totBusLat += tBURST;
1146    totQLat += dram_pkt->readyTime - dram_pkt->entryTime - bankLat - tBURST;
1147
1148
1149    // At this point we're done dealing with the request
1150    // It will be moved to a separate response queue with a
1151    // correct readyTime, and eventually be sent back at that
1152    //time
1153    moveToRespQ();
1154
1155    // Schedule the next read event
1156    if (!nextReqEvent.scheduled() && !stopReads){
1157        schedule(nextReqEvent, newTime);
1158    } else {
1159        if (newTime < nextReqEvent.when())
1160            reschedule(nextReqEvent, newTime);
1161    }
1162}
1163
1164void
1165SimpleDRAM::moveToRespQ()
1166{
1167    // Remove from read queue
1168    DRAMPacket* dram_pkt = readQueue.front();
1169    readQueue.pop_front();
1170
1171    // sanity check
1172    assert(dram_pkt->size <= burstSize);
1173
1174    // Insert into response queue sorted by readyTime
1175    // It will be sent back to the requestor at its
1176    // readyTime
1177    if (respQueue.empty()) {
1178        respQueue.push_front(dram_pkt);
1179        assert(!respondEvent.scheduled());
1180        assert(dram_pkt->readyTime >= curTick());
1181        schedule(respondEvent, dram_pkt->readyTime);
1182    } else {
1183        bool done = false;
1184        auto i = respQueue.begin();
1185        while (!done && i != respQueue.end()) {
1186            if ((*i)->readyTime > dram_pkt->readyTime) {
1187                respQueue.insert(i, dram_pkt);
1188                done = true;
1189            }
1190            ++i;
1191        }
1192
1193        if (!done)
1194            respQueue.push_back(dram_pkt);
1195
1196        assert(respondEvent.scheduled());
1197
1198        if (respQueue.front()->readyTime < respondEvent.when()) {
1199            assert(respQueue.front()->readyTime >= curTick());
1200            reschedule(respondEvent, respQueue.front()->readyTime);
1201        }
1202    }
1203}
1204
1205void
1206SimpleDRAM::scheduleNextReq()
1207{
1208    DPRINTF(DRAM, "Reached scheduleNextReq()\n");
1209
1210    // Figure out which read request goes next, and move it to the
1211    // front of the read queue
1212    if (!chooseNextRead()) {
1213        // In the case there is no read request to go next, see if we
1214        // are asked to drain, and if so trigger writes, this also
1215        // ensures that if we hit the write limit we will do this
1216        // multiple times until we are completely drained
1217        if (drainManager && !writeQueue.empty() && !writeEvent.scheduled())
1218            triggerWrites();
1219    } else {
1220        doDRAMAccess(readQueue.front());
1221    }
1222}
1223
1224Tick
1225SimpleDRAM::maxBankFreeAt() const
1226{
1227    Tick banksFree = 0;
1228
1229    for(int i = 0; i < ranksPerChannel; i++)
1230        for(int j = 0; j < banksPerRank; j++)
1231            banksFree = std::max(banks[i][j].freeAt, banksFree);
1232
1233    return banksFree;
1234}
1235
1236uint64_t
1237SimpleDRAM::minBankFreeAt(const deque<DRAMPacket*>& queue) const
1238{
1239    uint64_t bank_mask = 0;
1240    Tick freeAt = MaxTick;
1241
1242    // detemrine if we have queued transactions targetting the
1243    // bank in question
1244    vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
1245    for (auto p = queue.begin(); p != queue.end(); ++p) {
1246        got_waiting[(*p)->bankId] = true;
1247    }
1248
1249    for (int i = 0; i < ranksPerChannel; i++) {
1250        for (int j = 0; j < banksPerRank; j++) {
1251            // if we have waiting requests for the bank, and it is
1252            // amongst the first available, update the mask
1253            if (got_waiting[i * banksPerRank + j] &&
1254                banks[i][j].freeAt <= freeAt) {
1255                // reset bank mask if new minimum is found
1256                if (banks[i][j].freeAt < freeAt)
1257                    bank_mask = 0;
1258                // set the bit corresponding to the available bank
1259                uint8_t bit_index = i * ranksPerChannel + j;
1260                replaceBits(bank_mask, bit_index, bit_index, 1);
1261                freeAt = banks[i][j].freeAt;
1262            }
1263        }
1264    }
1265    return bank_mask;
1266}
1267
1268void
1269SimpleDRAM::processRefreshEvent()
1270{
1271    DPRINTF(DRAM, "Refreshing at tick %ld\n", curTick());
1272
1273    Tick banksFree = std::max(curTick(), maxBankFreeAt()) + tRFC;
1274
1275    for(int i = 0; i < ranksPerChannel; i++)
1276        for(int j = 0; j < banksPerRank; j++)
1277            banks[i][j].freeAt = banksFree;
1278
1279    schedule(refreshEvent, curTick() + tREFI);
1280}
1281
1282void
1283SimpleDRAM::regStats()
1284{
1285    using namespace Stats;
1286
1287    AbstractMemory::regStats();
1288
1289    readReqs
1290        .name(name() + ".readReqs")
1291        .desc("Total number of read requests accepted by DRAM controller");
1292
1293    writeReqs
1294        .name(name() + ".writeReqs")
1295        .desc("Total number of write requests accepted by DRAM controller");
1296
1297    readBursts
1298        .name(name() + ".readBursts")
1299        .desc("Total number of DRAM read bursts. "
1300              "Each DRAM read request translates to either one or multiple "
1301              "DRAM read bursts");
1302
1303    writeBursts
1304        .name(name() + ".writeBursts")
1305        .desc("Total number of DRAM write bursts. "
1306              "Each DRAM write request translates to either one or multiple "
1307              "DRAM write bursts");
1308
1309    servicedByWrQ
1310        .name(name() + ".servicedByWrQ")
1311        .desc("Number of DRAM read bursts serviced by write Q");
1312
1313    neitherReadNorWrite
1314        .name(name() + ".neitherReadNorWrite")
1315        .desc("Reqs where no action is needed");
1316
1317    perBankRdReqs
1318        .init(banksPerRank * ranksPerChannel)
1319        .name(name() + ".perBankRdReqs")
1320        .desc("Track reads on a per bank basis");
1321
1322    perBankWrReqs
1323        .init(banksPerRank * ranksPerChannel)
1324        .name(name() + ".perBankWrReqs")
1325        .desc("Track writes on a per bank basis");
1326
1327    avgRdQLen
1328        .name(name() + ".avgRdQLen")
1329        .desc("Average read queue length over time")
1330        .precision(2);
1331
1332    avgWrQLen
1333        .name(name() + ".avgWrQLen")
1334        .desc("Average write queue length over time")
1335        .precision(2);
1336
1337    totQLat
1338        .name(name() + ".totQLat")
1339        .desc("Total cycles spent in queuing delays");
1340
1341    totBankLat
1342        .name(name() + ".totBankLat")
1343        .desc("Total cycles spent in bank access");
1344
1345    totBusLat
1346        .name(name() + ".totBusLat")
1347        .desc("Total cycles spent in databus access");
1348
1349    totMemAccLat
1350        .name(name() + ".totMemAccLat")
1351        .desc("Sum of mem lat for all requests");
1352
1353    avgQLat
1354        .name(name() + ".avgQLat")
1355        .desc("Average queueing delay per request")
1356        .precision(2);
1357
1358    avgQLat = totQLat / (readBursts - servicedByWrQ);
1359
1360    avgBankLat
1361        .name(name() + ".avgBankLat")
1362        .desc("Average bank access latency per request")
1363        .precision(2);
1364
1365    avgBankLat = totBankLat / (readBursts - servicedByWrQ);
1366
1367    avgBusLat
1368        .name(name() + ".avgBusLat")
1369        .desc("Average bus latency per request")
1370        .precision(2);
1371
1372    avgBusLat = totBusLat / (readBursts - servicedByWrQ);
1373
1374    avgMemAccLat
1375        .name(name() + ".avgMemAccLat")
1376        .desc("Average memory access latency")
1377        .precision(2);
1378
1379    avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
1380
1381    numRdRetry
1382        .name(name() + ".numRdRetry")
1383        .desc("Number of times rd buffer was full causing retry");
1384
1385    numWrRetry
1386        .name(name() + ".numWrRetry")
1387        .desc("Number of times wr buffer was full causing retry");
1388
1389    readRowHits
1390        .name(name() + ".readRowHits")
1391        .desc("Number of row buffer hits during reads");
1392
1393    writeRowHits
1394        .name(name() + ".writeRowHits")
1395        .desc("Number of row buffer hits during writes");
1396
1397    readRowHitRate
1398        .name(name() + ".readRowHitRate")
1399        .desc("Row buffer hit rate for reads")
1400        .precision(2);
1401
1402    readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
1403
1404    writeRowHitRate
1405        .name(name() + ".writeRowHitRate")
1406        .desc("Row buffer hit rate for writes")
1407        .precision(2);
1408
1409    writeRowHitRate = (writeRowHits / writeBursts) * 100;
1410
1411    readPktSize
1412        .init(ceilLog2(burstSize) + 1)
1413        .name(name() + ".readPktSize")
1414        .desc("Categorize read packet sizes");
1415
1416     writePktSize
1417        .init(ceilLog2(burstSize) + 1)
1418        .name(name() + ".writePktSize")
1419        .desc("Categorize write packet sizes");
1420
1421     rdQLenPdf
1422        .init(readBufferSize)
1423        .name(name() + ".rdQLenPdf")
1424        .desc("What read queue length does an incoming req see");
1425
1426     wrQLenPdf
1427        .init(writeBufferSize)
1428        .name(name() + ".wrQLenPdf")
1429        .desc("What write queue length does an incoming req see");
1430
1431     bytesPerActivate
1432         .init(rowBufferSize)
1433         .name(name() + ".bytesPerActivate")
1434         .desc("Bytes accessed per row activation")
1435         .flags(nozero);
1436
1437    bytesRead
1438        .name(name() + ".bytesRead")
1439        .desc("Total number of bytes read from memory");
1440
1441    bytesWritten
1442        .name(name() + ".bytesWritten")
1443        .desc("Total number of bytes written to memory");
1444
1445    bytesConsumedRd
1446        .name(name() + ".bytesConsumedRd")
1447        .desc("bytesRead derated as per pkt->getSize()");
1448
1449    bytesConsumedWr
1450        .name(name() + ".bytesConsumedWr")
1451        .desc("bytesWritten derated as per pkt->getSize()");
1452
1453    avgRdBW
1454        .name(name() + ".avgRdBW")
1455        .desc("Average achieved read bandwidth in MB/s")
1456        .precision(2);
1457
1458    avgRdBW = (bytesRead / 1000000) / simSeconds;
1459
1460    avgWrBW
1461        .name(name() + ".avgWrBW")
1462        .desc("Average achieved write bandwidth in MB/s")
1463        .precision(2);
1464
1465    avgWrBW = (bytesWritten / 1000000) / simSeconds;
1466
1467    avgConsumedRdBW
1468        .name(name() + ".avgConsumedRdBW")
1469        .desc("Average consumed read bandwidth in MB/s")
1470        .precision(2);
1471
1472    avgConsumedRdBW = (bytesConsumedRd / 1000000) / simSeconds;
1473
1474    avgConsumedWrBW
1475        .name(name() + ".avgConsumedWrBW")
1476        .desc("Average consumed write bandwidth in MB/s")
1477        .precision(2);
1478
1479    avgConsumedWrBW = (bytesConsumedWr / 1000000) / simSeconds;
1480
1481    peakBW
1482        .name(name() + ".peakBW")
1483        .desc("Theoretical peak bandwidth in MB/s")
1484        .precision(2);
1485
1486    peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
1487
1488    busUtil
1489        .name(name() + ".busUtil")
1490        .desc("Data bus utilization in percentage")
1491        .precision(2);
1492
1493    busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
1494
1495    totGap
1496        .name(name() + ".totGap")
1497        .desc("Total gap between requests");
1498
1499    avgGap
1500        .name(name() + ".avgGap")
1501        .desc("Average gap between requests")
1502        .precision(2);
1503
1504    avgGap = totGap / (readReqs + writeReqs);
1505}
1506
1507void
1508SimpleDRAM::recvFunctional(PacketPtr pkt)
1509{
1510    // rely on the abstract memory
1511    functionalAccess(pkt);
1512}
1513
1514BaseSlavePort&
1515SimpleDRAM::getSlavePort(const string &if_name, PortID idx)
1516{
1517    if (if_name != "port") {
1518        return MemObject::getSlavePort(if_name, idx);
1519    } else {
1520        return port;
1521    }
1522}
1523
1524unsigned int
1525SimpleDRAM::drain(DrainManager *dm)
1526{
1527    unsigned int count = port.drain(dm);
1528
1529    // if there is anything in any of our internal queues, keep track
1530    // of that as well
1531    if (!(writeQueue.empty() && readQueue.empty() &&
1532          respQueue.empty())) {
1533        DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
1534                " resp: %d\n", writeQueue.size(), readQueue.size(),
1535                respQueue.size());
1536        ++count;
1537        drainManager = dm;
1538        // the only part that is not drained automatically over time
1539        // is the write queue, thus trigger writes if there are any
1540        // waiting and no reads waiting, otherwise wait until the
1541        // reads are done
1542        if (readQueue.empty() && !writeQueue.empty() &&
1543            !writeEvent.scheduled())
1544            triggerWrites();
1545    }
1546
1547    if (count)
1548        setDrainState(Drainable::Draining);
1549    else
1550        setDrainState(Drainable::Drained);
1551    return count;
1552}
1553
1554SimpleDRAM::MemoryPort::MemoryPort(const std::string& name, SimpleDRAM& _memory)
1555    : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
1556      memory(_memory)
1557{ }
1558
1559AddrRangeList
1560SimpleDRAM::MemoryPort::getAddrRanges() const
1561{
1562    AddrRangeList ranges;
1563    ranges.push_back(memory.getAddrRange());
1564    return ranges;
1565}
1566
1567void
1568SimpleDRAM::MemoryPort::recvFunctional(PacketPtr pkt)
1569{
1570    pkt->pushLabel(memory.name());
1571
1572    if (!queue.checkFunctional(pkt)) {
1573        // Default implementation of SimpleTimingPort::recvFunctional()
1574        // calls recvAtomic() and throws away the latency; we can save a
1575        // little here by just not calculating the latency.
1576        memory.recvFunctional(pkt);
1577    }
1578
1579    pkt->popLabel();
1580}
1581
1582Tick
1583SimpleDRAM::MemoryPort::recvAtomic(PacketPtr pkt)
1584{
1585    return memory.recvAtomic(pkt);
1586}
1587
1588bool
1589SimpleDRAM::MemoryPort::recvTimingReq(PacketPtr pkt)
1590{
1591    // pass it to the memory controller
1592    return memory.recvTimingReq(pkt);
1593}
1594
1595SimpleDRAM*
1596SimpleDRAMParams::create()
1597{
1598    return new SimpleDRAM(this);
1599}
1600