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