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