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