dram_ctrl.cc revision 10466
1/*
2 * Copyright (c) 2010-2014 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/bitfield.hh"
46#include "base/trace.hh"
47#include "debug/DRAM.hh"
48#include "debug/DRAMPower.hh"
49#include "debug/DRAMState.hh"
50#include "debug/Drain.hh"
51#include "mem/dram_ctrl.hh"
52#include "sim/system.hh"
53
54using namespace std;
55using namespace Data;
56
57DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
58    AbstractMemory(p),
59    port(name() + ".port", *this),
60    retryRdReq(false), retryWrReq(false),
61    busState(READ),
62    nextReqEvent(this), respondEvent(this), activateEvent(this),
63    prechargeEvent(this), refreshEvent(this), powerEvent(this),
64    drainManager(NULL),
65    deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
66    deviceRowBufferSize(p->device_rowbuffer_size),
67    devicesPerRank(p->devices_per_rank),
68    burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8),
69    rowBufferSize(devicesPerRank * deviceRowBufferSize),
70    columnsPerRowBuffer(rowBufferSize / burstSize),
71    columnsPerStripe(range.granularity() / burstSize),
72    ranksPerChannel(p->ranks_per_channel),
73    bankGroupsPerRank(p->bank_groups_per_rank),
74    bankGroupArch(p->bank_groups_per_rank > 0),
75    banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0),
76    readBufferSize(p->read_buffer_size),
77    writeBufferSize(p->write_buffer_size),
78    writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0),
79    writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0),
80    minWritesPerSwitch(p->min_writes_per_switch),
81    writesThisTime(0), readsThisTime(0),
82    tCK(p->tCK), tWTR(p->tWTR), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST),
83    tCCD_L(p->tCCD_L), tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
84    tWR(p->tWR), tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
85    tRRD_L(p->tRRD_L), tXAW(p->tXAW), activationLimit(p->activation_limit),
86    memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
87    pageMgmt(p->page_policy),
88    maxAccessesPerRow(p->max_accesses_per_row),
89    frontendLatency(p->static_frontend_latency),
90    backendLatency(p->static_backend_latency),
91    busBusyUntil(0), refreshDueAt(0), refreshState(REF_IDLE),
92    pwrStateTrans(PWR_IDLE), pwrState(PWR_IDLE), prevArrival(0),
93    nextReqTime(0), pwrStateTick(0), numBanksActive(0),
94    activeRank(0), timeStampOffset(0)
95{
96    // create the bank states based on the dimensions of the ranks and
97    // banks
98    banks.resize(ranksPerChannel);
99
100    //create list of drampower objects. For each rank 1 drampower instance.
101    for (int i = 0; i < ranksPerChannel; i++) {
102        DRAMPower drampower = DRAMPower(p, false);
103        rankPower.emplace_back(drampower);
104    }
105
106    actTicks.resize(ranksPerChannel);
107    for (size_t c = 0; c < ranksPerChannel; ++c) {
108        banks[c].resize(banksPerRank);
109        actTicks[c].resize(activationLimit, 0);
110    }
111
112    // set the bank indices
113    for (int r = 0; r < ranksPerChannel; r++) {
114        for (int b = 0; b < banksPerRank; b++) {
115            banks[r][b].rank = r;
116            banks[r][b].bank = b;
117            if (bankGroupArch) {
118                // Simply assign lower bits to bank group in order to
119                // rotate across bank groups as banks are incremented
120                // e.g. with 4 banks per bank group and 16 banks total:
121                //    banks 0,4,8,12  are in bank group 0
122                //    banks 1,5,9,13  are in bank group 1
123                //    banks 2,6,10,14 are in bank group 2
124                //    banks 3,7,11,15 are in bank group 3
125                banks[r][b].bankgr = b % bankGroupsPerRank;
126            } else {
127                // No bank groups; simply assign to bank number
128                banks[r][b].bankgr = b;
129            }
130        }
131    }
132
133    // perform a basic check of the write thresholds
134    if (p->write_low_thresh_perc >= p->write_high_thresh_perc)
135        fatal("Write buffer low threshold %d must be smaller than the "
136              "high threshold %d\n", p->write_low_thresh_perc,
137              p->write_high_thresh_perc);
138
139    // determine the rows per bank by looking at the total capacity
140    uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
141
142    DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
143            AbstractMemory::size());
144
145    DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
146            rowBufferSize, columnsPerRowBuffer);
147
148    rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
149
150    // a bit of sanity checks on the interleaving
151    if (range.interleaved()) {
152        if (channels != range.stripes())
153            fatal("%s has %d interleaved address stripes but %d channel(s)\n",
154                  name(), range.stripes(), channels);
155
156        if (addrMapping == Enums::RoRaBaChCo) {
157            if (rowBufferSize != range.granularity()) {
158                fatal("Channel interleaving of %s doesn't match RoRaBaChCo "
159                      "address map\n", name());
160            }
161        } else if (addrMapping == Enums::RoRaBaCoCh ||
162                   addrMapping == Enums::RoCoRaBaCh) {
163            // for the interleavings with channel bits in the bottom,
164            // if the system uses a channel striping granularity that
165            // is larger than the DRAM burst size, then map the
166            // sequential accesses within a stripe to a number of
167            // columns in the DRAM, effectively placing some of the
168            // lower-order column bits as the least-significant bits
169            // of the address (above the ones denoting the burst size)
170            assert(columnsPerStripe >= 1);
171
172            // channel striping has to be done at a granularity that
173            // is equal or larger to a cache line
174            if (system()->cacheLineSize() > range.granularity()) {
175                fatal("Channel interleaving of %s must be at least as large "
176                      "as the cache line size\n", name());
177            }
178
179            // ...and equal or smaller than the row-buffer size
180            if (rowBufferSize < range.granularity()) {
181                fatal("Channel interleaving of %s must be at most as large "
182                      "as the row-buffer size\n", name());
183            }
184            // this is essentially the check above, so just to be sure
185            assert(columnsPerStripe <= columnsPerRowBuffer);
186        }
187    }
188
189    // some basic sanity checks
190    if (tREFI <= tRP || tREFI <= tRFC) {
191        fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
192              tREFI, tRP, tRFC);
193    }
194
195    // basic bank group architecture checks ->
196    if (bankGroupArch) {
197        // must have at least one bank per bank group
198        if (bankGroupsPerRank > banksPerRank) {
199            fatal("banks per rank (%d) must be equal to or larger than "
200                  "banks groups per rank (%d)\n",
201                  banksPerRank, bankGroupsPerRank);
202        }
203        // must have same number of banks in each bank group
204        if ((banksPerRank % bankGroupsPerRank) != 0) {
205            fatal("Banks per rank (%d) must be evenly divisible by bank groups "
206                  "per rank (%d) for equal banks per bank group\n",
207                  banksPerRank, bankGroupsPerRank);
208        }
209        // tCCD_L should be greater than minimal, back-to-back burst delay
210        if (tCCD_L <= tBURST) {
211            fatal("tCCD_L (%d) should be larger than tBURST (%d) when "
212                  "bank groups per rank (%d) is greater than 1\n",
213                  tCCD_L, tBURST, bankGroupsPerRank);
214        }
215        // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
216        if (tRRD_L <= tRRD) {
217            fatal("tRRD_L (%d) should be larger than tRRD (%d) when "
218                  "bank groups per rank (%d) is greater than 1\n",
219                  tRRD_L, tRRD, bankGroupsPerRank);
220        }
221    }
222
223}
224
225void
226DRAMCtrl::init()
227{
228    AbstractMemory::init();
229
230   if (!port.isConnected()) {
231        fatal("DRAMCtrl %s is unconnected!\n", name());
232    } else {
233        port.sendRangeChange();
234    }
235}
236
237void
238DRAMCtrl::startup()
239{
240    // timestamp offset should be in clock cycles for DRAMPower
241    timeStampOffset = divCeil(curTick(), tCK);
242    // update the start tick for the precharge accounting to the
243    // current tick
244    pwrStateTick = curTick();
245
246    // shift the bus busy time sufficiently far ahead that we never
247    // have to worry about negative values when computing the time for
248    // the next request, this will add an insignificant bubble at the
249    // start of simulation
250    busBusyUntil = curTick() + tRP + tRCD + tCL;
251
252    // kick off the refresh, and give ourselves enough time to
253    // precharge
254    schedule(refreshEvent, curTick() + tREFI - tRP);
255}
256
257Tick
258DRAMCtrl::recvAtomic(PacketPtr pkt)
259{
260    DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
261
262    // do the actual memory access and turn the packet into a response
263    access(pkt);
264
265    Tick latency = 0;
266    if (!pkt->memInhibitAsserted() && pkt->hasData()) {
267        // this value is not supposed to be accurate, just enough to
268        // keep things going, mimic a closed page
269        latency = tRP + tRCD + tCL;
270    }
271    return latency;
272}
273
274bool
275DRAMCtrl::readQueueFull(unsigned int neededEntries) const
276{
277    DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
278            readBufferSize, readQueue.size() + respQueue.size(),
279            neededEntries);
280
281    return
282        (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
283}
284
285bool
286DRAMCtrl::writeQueueFull(unsigned int neededEntries) const
287{
288    DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
289            writeBufferSize, writeQueue.size(), neededEntries);
290    return (writeQueue.size() + neededEntries) > writeBufferSize;
291}
292
293DRAMCtrl::DRAMPacket*
294DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size,
295                       bool isRead)
296{
297    // decode the address based on the address mapping scheme, with
298    // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
299    // channel, respectively
300    uint8_t rank;
301    uint8_t bank;
302    // use a 64-bit unsigned during the computations as the row is
303    // always the top bits, and check before creating the DRAMPacket
304    uint64_t row;
305
306    // truncate the address to a DRAM burst, which makes it unique to
307    // a specific column, row, bank, rank and channel
308    Addr addr = dramPktAddr / burstSize;
309
310    // we have removed the lowest order address bits that denote the
311    // position within the column
312    if (addrMapping == Enums::RoRaBaChCo) {
313        // the lowest order bits denote the column to ensure that
314        // sequential cache lines occupy the same row
315        addr = addr / columnsPerRowBuffer;
316
317        // take out the channel part of the address
318        addr = addr / channels;
319
320        // after the channel bits, get the bank bits to interleave
321        // over the banks
322        bank = addr % banksPerRank;
323        addr = addr / banksPerRank;
324
325        // after the bank, we get the rank bits which thus interleaves
326        // over the ranks
327        rank = addr % ranksPerChannel;
328        addr = addr / ranksPerChannel;
329
330        // lastly, get the row bits
331        row = addr % rowsPerBank;
332        addr = addr / rowsPerBank;
333    } else if (addrMapping == Enums::RoRaBaCoCh) {
334        // take out the lower-order column bits
335        addr = addr / columnsPerStripe;
336
337        // take out the channel part of the address
338        addr = addr / channels;
339
340        // next, the higher-order column bites
341        addr = addr / (columnsPerRowBuffer / columnsPerStripe);
342
343        // after the column bits, we get the bank bits to interleave
344        // over the banks
345        bank = addr % banksPerRank;
346        addr = addr / banksPerRank;
347
348        // after the bank, we get the rank bits which thus interleaves
349        // over the ranks
350        rank = addr % ranksPerChannel;
351        addr = addr / ranksPerChannel;
352
353        // lastly, get the row bits
354        row = addr % rowsPerBank;
355        addr = addr / rowsPerBank;
356    } else if (addrMapping == Enums::RoCoRaBaCh) {
357        // optimise for closed page mode and utilise maximum
358        // parallelism of the DRAM (at the cost of power)
359
360        // take out the lower-order column bits
361        addr = addr / columnsPerStripe;
362
363        // take out the channel part of the address, not that this has
364        // to match with how accesses are interleaved between the
365        // controllers in the address mapping
366        addr = addr / channels;
367
368        // start with the bank bits, as this provides the maximum
369        // opportunity for parallelism between requests
370        bank = addr % banksPerRank;
371        addr = addr / banksPerRank;
372
373        // next get the rank bits
374        rank = addr % ranksPerChannel;
375        addr = addr / ranksPerChannel;
376
377        // next, the higher-order column bites
378        addr = addr / (columnsPerRowBuffer / columnsPerStripe);
379
380        // lastly, get the row bits
381        row = addr % rowsPerBank;
382        addr = addr / rowsPerBank;
383    } else
384        panic("Unknown address mapping policy chosen!");
385
386    assert(rank < ranksPerChannel);
387    assert(bank < banksPerRank);
388    assert(row < rowsPerBank);
389    assert(row < Bank::NO_ROW);
390
391    DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
392            dramPktAddr, rank, bank, row);
393
394    // create the corresponding DRAM packet with the entry time and
395    // ready time set to the current tick, the latter will be updated
396    // later
397    uint16_t bank_id = banksPerRank * rank + bank;
398    return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
399                          size, banks[rank][bank]);
400}
401
402void
403DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
404{
405    // only add to the read queue here. whenever the request is
406    // eventually done, set the readyTime, and call schedule()
407    assert(!pkt->isWrite());
408
409    assert(pktCount != 0);
410
411    // if the request size is larger than burst size, the pkt is split into
412    // multiple DRAM packets
413    // Note if the pkt starting address is not aligened to burst size, the
414    // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
415    // are aligned to burst size boundaries. This is to ensure we accurately
416    // check read packets against packets in write queue.
417    Addr addr = pkt->getAddr();
418    unsigned pktsServicedByWrQ = 0;
419    BurstHelper* burst_helper = NULL;
420    for (int cnt = 0; cnt < pktCount; ++cnt) {
421        unsigned size = std::min((addr | (burstSize - 1)) + 1,
422                        pkt->getAddr() + pkt->getSize()) - addr;
423        readPktSize[ceilLog2(size)]++;
424        readBursts++;
425
426        // First check write buffer to see if the data is already at
427        // the controller
428        bool foundInWrQ = false;
429        for (auto i = writeQueue.begin(); i != writeQueue.end(); ++i) {
430            // check if the read is subsumed in the write entry we are
431            // looking at
432            if ((*i)->addr <= addr &&
433                (addr + size) <= ((*i)->addr + (*i)->size)) {
434                foundInWrQ = true;
435                servicedByWrQ++;
436                pktsServicedByWrQ++;
437                DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
438                        "write queue\n", addr, size);
439                bytesReadWrQ += burstSize;
440                break;
441            }
442        }
443
444        // If not found in the write q, make a DRAM packet and
445        // push it onto the read queue
446        if (!foundInWrQ) {
447
448            // Make the burst helper for split packets
449            if (pktCount > 1 && burst_helper == NULL) {
450                DPRINTF(DRAM, "Read to addr %lld translates to %d "
451                        "dram requests\n", pkt->getAddr(), pktCount);
452                burst_helper = new BurstHelper(pktCount);
453            }
454
455            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
456            dram_pkt->burstHelper = burst_helper;
457
458            assert(!readQueueFull(1));
459            rdQLenPdf[readQueue.size() + respQueue.size()]++;
460
461            DPRINTF(DRAM, "Adding to read queue\n");
462
463            readQueue.push_back(dram_pkt);
464
465            // Update stats
466            avgRdQLen = readQueue.size() + respQueue.size();
467        }
468
469        // Starting address of next dram pkt (aligend to burstSize boundary)
470        addr = (addr | (burstSize - 1)) + 1;
471    }
472
473    // If all packets are serviced by write queue, we send the repsonse back
474    if (pktsServicedByWrQ == pktCount) {
475        accessAndRespond(pkt, frontendLatency);
476        return;
477    }
478
479    // Update how many split packets are serviced by write queue
480    if (burst_helper != NULL)
481        burst_helper->burstsServiced = pktsServicedByWrQ;
482
483    // If we are not already scheduled to get a request out of the
484    // queue, do so now
485    if (!nextReqEvent.scheduled()) {
486        DPRINTF(DRAM, "Request scheduled immediately\n");
487        schedule(nextReqEvent, curTick());
488    }
489}
490
491void
492DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
493{
494    // only add to the write queue here. whenever the request is
495    // eventually done, set the readyTime, and call schedule()
496    assert(pkt->isWrite());
497
498    // if the request size is larger than burst size, the pkt is split into
499    // multiple DRAM packets
500    Addr addr = pkt->getAddr();
501    for (int cnt = 0; cnt < pktCount; ++cnt) {
502        unsigned size = std::min((addr | (burstSize - 1)) + 1,
503                        pkt->getAddr() + pkt->getSize()) - addr;
504        writePktSize[ceilLog2(size)]++;
505        writeBursts++;
506
507        // see if we can merge with an existing item in the write
508        // queue and keep track of whether we have merged or not so we
509        // can stop at that point and also avoid enqueueing a new
510        // request
511        bool merged = false;
512        auto w = writeQueue.begin();
513
514        while(!merged && w != writeQueue.end()) {
515            // either of the two could be first, if they are the same
516            // it does not matter which way we go
517            if ((*w)->addr >= addr) {
518                // the existing one starts after the new one, figure
519                // out where the new one ends with respect to the
520                // existing one
521                if ((addr + size) >= ((*w)->addr + (*w)->size)) {
522                    // check if the existing one is completely
523                    // subsumed in the new one
524                    DPRINTF(DRAM, "Merging write covering existing burst\n");
525                    merged = true;
526                    // update both the address and the size
527                    (*w)->addr = addr;
528                    (*w)->size = size;
529                } else if ((addr + size) >= (*w)->addr &&
530                           ((*w)->addr + (*w)->size - addr) <= burstSize) {
531                    // the new one is just before or partially
532                    // overlapping with the existing one, and together
533                    // they fit within a burst
534                    DPRINTF(DRAM, "Merging write before existing burst\n");
535                    merged = true;
536                    // the existing queue item needs to be adjusted with
537                    // respect to both address and size
538                    (*w)->size = (*w)->addr + (*w)->size - addr;
539                    (*w)->addr = addr;
540                }
541            } else {
542                // the new one starts after the current one, figure
543                // out where the existing one ends with respect to the
544                // new one
545                if (((*w)->addr + (*w)->size) >= (addr + size)) {
546                    // check if the new one is completely subsumed in the
547                    // existing one
548                    DPRINTF(DRAM, "Merging write into existing burst\n");
549                    merged = true;
550                    // no adjustments necessary
551                } else if (((*w)->addr + (*w)->size) >= addr &&
552                           (addr + size - (*w)->addr) <= burstSize) {
553                    // the existing one is just before or partially
554                    // overlapping with the new one, and together
555                    // they fit within a burst
556                    DPRINTF(DRAM, "Merging write after existing burst\n");
557                    merged = true;
558                    // the address is right, and only the size has
559                    // to be adjusted
560                    (*w)->size = addr + size - (*w)->addr;
561                }
562            }
563            ++w;
564        }
565
566        // if the item was not merged we need to create a new write
567        // and enqueue it
568        if (!merged) {
569            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
570
571            assert(writeQueue.size() < writeBufferSize);
572            wrQLenPdf[writeQueue.size()]++;
573
574            DPRINTF(DRAM, "Adding to write queue\n");
575
576            writeQueue.push_back(dram_pkt);
577
578            // Update stats
579            avgWrQLen = writeQueue.size();
580        } else {
581            // keep track of the fact that this burst effectively
582            // disappeared as it was merged with an existing one
583            mergedWrBursts++;
584        }
585
586        // Starting address of next dram pkt (aligend to burstSize boundary)
587        addr = (addr | (burstSize - 1)) + 1;
588    }
589
590    // we do not wait for the writes to be send to the actual memory,
591    // but instead take responsibility for the consistency here and
592    // snoop the write queue for any upcoming reads
593    // @todo, if a pkt size is larger than burst size, we might need a
594    // different front end latency
595    accessAndRespond(pkt, frontendLatency);
596
597    // If we are not already scheduled to get a request out of the
598    // queue, do so now
599    if (!nextReqEvent.scheduled()) {
600        DPRINTF(DRAM, "Request scheduled immediately\n");
601        schedule(nextReqEvent, curTick());
602    }
603}
604
605void
606DRAMCtrl::printQs() const {
607    DPRINTF(DRAM, "===READ QUEUE===\n\n");
608    for (auto i = readQueue.begin() ;  i != readQueue.end() ; ++i) {
609        DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
610    }
611    DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
612    for (auto i = respQueue.begin() ;  i != respQueue.end() ; ++i) {
613        DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
614    }
615    DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
616    for (auto i = writeQueue.begin() ;  i != writeQueue.end() ; ++i) {
617        DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
618    }
619}
620
621bool
622DRAMCtrl::recvTimingReq(PacketPtr pkt)
623{
624    /// @todo temporary hack to deal with memory corruption issues until
625    /// 4-phase transactions are complete
626    for (int x = 0; x < pendingDelete.size(); x++)
627        delete pendingDelete[x];
628    pendingDelete.clear();
629
630    // This is where we enter from the outside world
631    DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
632            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
633
634    // simply drop inhibited packets for now
635    if (pkt->memInhibitAsserted()) {
636        DPRINTF(DRAM, "Inhibited packet -- Dropping it now\n");
637        pendingDelete.push_back(pkt);
638        return true;
639    }
640
641    // Calc avg gap between requests
642    if (prevArrival != 0) {
643        totGap += curTick() - prevArrival;
644    }
645    prevArrival = curTick();
646
647
648    // Find out how many dram packets a pkt translates to
649    // If the burst size is equal or larger than the pkt size, then a pkt
650    // translates to only one dram packet. Otherwise, a pkt translates to
651    // multiple dram packets
652    unsigned size = pkt->getSize();
653    unsigned offset = pkt->getAddr() & (burstSize - 1);
654    unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
655
656    // check local buffers and do not accept if full
657    if (pkt->isRead()) {
658        assert(size != 0);
659        if (readQueueFull(dram_pkt_count)) {
660            DPRINTF(DRAM, "Read queue full, not accepting\n");
661            // remember that we have to retry this port
662            retryRdReq = true;
663            numRdRetry++;
664            return false;
665        } else {
666            addToReadQueue(pkt, dram_pkt_count);
667            readReqs++;
668            bytesReadSys += size;
669        }
670    } else if (pkt->isWrite()) {
671        assert(size != 0);
672        if (writeQueueFull(dram_pkt_count)) {
673            DPRINTF(DRAM, "Write queue full, not accepting\n");
674            // remember that we have to retry this port
675            retryWrReq = true;
676            numWrRetry++;
677            return false;
678        } else {
679            addToWriteQueue(pkt, dram_pkt_count);
680            writeReqs++;
681            bytesWrittenSys += size;
682        }
683    } else {
684        DPRINTF(DRAM,"Neither read nor write, ignore timing\n");
685        neitherReadNorWrite++;
686        accessAndRespond(pkt, 1);
687    }
688
689    return true;
690}
691
692void
693DRAMCtrl::processRespondEvent()
694{
695    DPRINTF(DRAM,
696            "processRespondEvent(): Some req has reached its readyTime\n");
697
698    DRAMPacket* dram_pkt = respQueue.front();
699
700    if (dram_pkt->burstHelper) {
701        // it is a split packet
702        dram_pkt->burstHelper->burstsServiced++;
703        if (dram_pkt->burstHelper->burstsServiced ==
704            dram_pkt->burstHelper->burstCount) {
705            // we have now serviced all children packets of a system packet
706            // so we can now respond to the requester
707            // @todo we probably want to have a different front end and back
708            // end latency for split packets
709            accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
710            delete dram_pkt->burstHelper;
711            dram_pkt->burstHelper = NULL;
712        }
713    } else {
714        // it is not a split packet
715        accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
716    }
717
718    delete respQueue.front();
719    respQueue.pop_front();
720
721    if (!respQueue.empty()) {
722        assert(respQueue.front()->readyTime >= curTick());
723        assert(!respondEvent.scheduled());
724        schedule(respondEvent, respQueue.front()->readyTime);
725    } else {
726        // if there is nothing left in any queue, signal a drain
727        if (writeQueue.empty() && readQueue.empty() &&
728            drainManager) {
729            drainManager->signalDrainDone();
730            drainManager = NULL;
731        }
732    }
733
734    // We have made a location in the queue available at this point,
735    // so if there is a read that was forced to wait, retry now
736    if (retryRdReq) {
737        retryRdReq = false;
738        port.sendRetry();
739    }
740}
741
742void
743DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue, bool switched_cmd_type)
744{
745    // This method does the arbitration between requests. The chosen
746    // packet is simply moved to the head of the queue. The other
747    // methods know that this is the place to look. For example, with
748    // FCFS, this method does nothing
749    assert(!queue.empty());
750
751    if (queue.size() == 1) {
752        DPRINTF(DRAM, "Single request, nothing to do\n");
753        return;
754    }
755
756    if (memSchedPolicy == Enums::fcfs) {
757        // Do nothing, since the correct request is already head
758    } else if (memSchedPolicy == Enums::frfcfs) {
759        reorderQueue(queue, switched_cmd_type);
760    } else
761        panic("No scheduling policy chosen\n");
762}
763
764void
765DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, bool switched_cmd_type)
766{
767    // Only determine this when needed
768    uint64_t earliest_banks = 0;
769
770    // Search for row hits first, if no row hit is found then schedule the
771    // packet to one of the earliest banks available
772    bool found_earliest_pkt = false;
773    bool found_prepped_diff_rank_pkt = false;
774    auto selected_pkt_it = queue.begin();
775
776    for (auto i = queue.begin(); i != queue.end() ; ++i) {
777        DRAMPacket* dram_pkt = *i;
778        const Bank& bank = dram_pkt->bankRef;
779        // Check if it is a row hit
780        if (bank.openRow == dram_pkt->row) {
781            if (dram_pkt->rank == activeRank || switched_cmd_type) {
782                // FCFS within the hits, giving priority to commands
783                // that access the same rank as the previous burst
784                // to minimize bus turnaround delays
785                // Only give rank prioity when command type is not changing
786                DPRINTF(DRAM, "Row buffer hit\n");
787                selected_pkt_it = i;
788                break;
789            } else if (!found_prepped_diff_rank_pkt) {
790                // found row hit for command on different rank than prev burst
791                selected_pkt_it = i;
792                found_prepped_diff_rank_pkt = true;
793            }
794        } else if (!found_earliest_pkt & !found_prepped_diff_rank_pkt) {
795            // No row hit and
796            // haven't found an entry with a row hit to a new rank
797            if (earliest_banks == 0)
798                // Determine entries with earliest bank prep delay
799                // Function will give priority to commands that access the
800                // same rank as previous burst and can prep the bank seamlessly
801                earliest_banks = minBankPrep(queue, switched_cmd_type);
802
803            // FCFS - Bank is first available bank
804            if (bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
805                // Remember the packet to be scheduled to one of the earliest
806                // banks available, FCFS amongst the earliest banks
807                selected_pkt_it = i;
808                found_earliest_pkt = true;
809            }
810        }
811    }
812
813    DRAMPacket* selected_pkt = *selected_pkt_it;
814    queue.erase(selected_pkt_it);
815    queue.push_front(selected_pkt);
816}
817
818void
819DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
820{
821    DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
822
823    bool needsResponse = pkt->needsResponse();
824    // do the actual memory access which also turns the packet into a
825    // response
826    access(pkt);
827
828    // turn packet around to go back to requester if response expected
829    if (needsResponse) {
830        // access already turned the packet into a response
831        assert(pkt->isResponse());
832
833        // @todo someone should pay for this
834        pkt->firstWordDelay = pkt->lastWordDelay = 0;
835
836        // queue the packet in the response queue to be sent out after
837        // the static latency has passed
838        port.schedTimingResp(pkt, curTick() + static_latency);
839    } else {
840        // @todo the packet is going to be deleted, and the DRAMPacket
841        // is still having a pointer to it
842        pendingDelete.push_back(pkt);
843    }
844
845    DPRINTF(DRAM, "Done\n");
846
847    return;
848}
849
850void
851DRAMCtrl::activateBank(Bank& bank, Tick act_tick, uint32_t row)
852{
853    // get the rank index from the bank
854    uint8_t rank = bank.rank;
855
856    assert(actTicks[rank].size() == activationLimit);
857
858    DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
859
860    // update the open row
861    assert(bank.openRow == Bank::NO_ROW);
862    bank.openRow = row;
863
864    // start counting anew, this covers both the case when we
865    // auto-precharged, and when this access is forced to
866    // precharge
867    bank.bytesAccessed = 0;
868    bank.rowAccesses = 0;
869
870    ++numBanksActive;
871    assert(numBanksActive <= banksPerRank * ranksPerChannel);
872
873    DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
874            bank.bank, bank.rank, act_tick, numBanksActive);
875
876    rankPower[bank.rank].powerlib.doCommand(MemCommand::ACT, bank.bank,
877                                            divCeil(act_tick, tCK) -
878                                            timeStampOffset);
879
880    DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) -
881            timeStampOffset, bank.bank, bank.rank);
882
883    // The next access has to respect tRAS for this bank
884    bank.preAllowedAt = act_tick + tRAS;
885
886    // Respect the row-to-column command delay
887    bank.colAllowedAt = std::max(act_tick + tRCD, bank.colAllowedAt);
888
889    // start by enforcing tRRD
890    for(int i = 0; i < banksPerRank; i++) {
891        // next activate to any bank in this rank must not happen
892        // before tRRD
893        if (bankGroupArch && (bank.bankgr == banks[rank][i].bankgr)) {
894            // bank group architecture requires longer delays between
895            // ACT commands within the same bank group.  Use tRRD_L
896            // in this case
897            banks[rank][i].actAllowedAt = std::max(act_tick + tRRD_L,
898                                                   banks[rank][i].actAllowedAt);
899        } else {
900            // use shorter tRRD value when either
901            // 1) bank group architecture is not supportted
902            // 2) bank is in a different bank group
903            banks[rank][i].actAllowedAt = std::max(act_tick + tRRD,
904                                                   banks[rank][i].actAllowedAt);
905        }
906    }
907
908    // next, we deal with tXAW, if the activation limit is disabled
909    // then we are done
910    if (actTicks[rank].empty())
911        return;
912
913    // sanity check
914    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
915        panic("Got %d activates in window %d (%llu - %llu) which is smaller "
916              "than %llu\n", activationLimit, act_tick - actTicks[rank].back(),
917              act_tick, actTicks[rank].back(), tXAW);
918    }
919
920    // shift the times used for the book keeping, the last element
921    // (highest index) is the oldest one and hence the lowest value
922    actTicks[rank].pop_back();
923
924    // record an new activation (in the future)
925    actTicks[rank].push_front(act_tick);
926
927    // cannot activate more than X times in time window tXAW, push the
928    // next one (the X + 1'st activate) to be tXAW away from the
929    // oldest in our window of X
930    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
931        DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate no earlier "
932                "than %llu\n", activationLimit, actTicks[rank].back() + tXAW);
933            for(int j = 0; j < banksPerRank; j++)
934                // next activate must not happen before end of window
935                banks[rank][j].actAllowedAt =
936                    std::max(actTicks[rank].back() + tXAW,
937                             banks[rank][j].actAllowedAt);
938    }
939
940    // at the point when this activate takes place, make sure we
941    // transition to the active power state
942    if (!activateEvent.scheduled())
943        schedule(activateEvent, act_tick);
944    else if (activateEvent.when() > act_tick)
945        // move it sooner in time
946        reschedule(activateEvent, act_tick);
947}
948
949void
950DRAMCtrl::processActivateEvent()
951{
952    // we should transition to the active state as soon as any bank is active
953    if (pwrState != PWR_ACT)
954        // note that at this point numBanksActive could be back at
955        // zero again due to a precharge scheduled in the future
956        schedulePowerEvent(PWR_ACT, curTick());
957}
958
959void
960DRAMCtrl::prechargeBank(Bank& bank, Tick pre_at, bool trace)
961{
962    // make sure the bank has an open row
963    assert(bank.openRow != Bank::NO_ROW);
964
965    // sample the bytes per activate here since we are closing
966    // the page
967    bytesPerActivate.sample(bank.bytesAccessed);
968
969    bank.openRow = Bank::NO_ROW;
970
971    // no precharge allowed before this one
972    bank.preAllowedAt = pre_at;
973
974    Tick pre_done_at = pre_at + tRP;
975
976    bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at);
977
978    assert(numBanksActive != 0);
979    --numBanksActive;
980
981    DPRINTF(DRAM, "Precharging bank %d, rank %d at tick %lld, now got "
982            "%d active\n", bank.bank, bank.rank, pre_at, numBanksActive);
983
984    if (trace) {
985
986        rankPower[bank.rank].powerlib.doCommand(MemCommand::PRE, bank.bank,
987                                                divCeil(pre_at, tCK) -
988                                                timeStampOffset);
989        DPRINTF(DRAMPower, "%llu,PRE,%d,%d\n", divCeil(pre_at, tCK) -
990                timeStampOffset, bank.bank, bank.rank);
991    }
992    // if we look at the current number of active banks we might be
993    // tempted to think the DRAM is now idle, however this can be
994    // undone by an activate that is scheduled to happen before we
995    // would have reached the idle state, so schedule an event and
996    // rather check once we actually make it to the point in time when
997    // the (last) precharge takes place
998    if (!prechargeEvent.scheduled())
999        schedule(prechargeEvent, pre_done_at);
1000    else if (prechargeEvent.when() < pre_done_at)
1001        reschedule(prechargeEvent, pre_done_at);
1002}
1003
1004void
1005DRAMCtrl::processPrechargeEvent()
1006{
1007    // if we reached zero, then special conditions apply as we track
1008    // if all banks are precharged for the power models
1009    if (numBanksActive == 0) {
1010        // we should transition to the idle state when the last bank
1011        // is precharged
1012        schedulePowerEvent(PWR_IDLE, curTick());
1013    }
1014}
1015
1016void
1017DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
1018{
1019    DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1020            dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1021
1022    // get the bank
1023    Bank& bank = dram_pkt->bankRef;
1024
1025    // for the state we need to track if it is a row hit or not
1026    bool row_hit = true;
1027
1028    // respect any constraints on the command (e.g. tRCD or tCCD)
1029    Tick cmd_at = std::max(bank.colAllowedAt, curTick());
1030
1031    // Determine the access latency and update the bank state
1032    if (bank.openRow == dram_pkt->row) {
1033        // nothing to do
1034    } else {
1035        row_hit = false;
1036
1037        // If there is a page open, precharge it.
1038        if (bank.openRow != Bank::NO_ROW) {
1039            prechargeBank(bank, std::max(bank.preAllowedAt, curTick()));
1040        }
1041
1042        // next we need to account for the delay in activating the
1043        // page
1044        Tick act_tick = std::max(bank.actAllowedAt, curTick());
1045
1046        // Record the activation and deal with all the global timing
1047        // constraints caused be a new activation (tRRD and tXAW)
1048        activateBank(bank, act_tick, dram_pkt->row);
1049
1050        // issue the command as early as possible
1051        cmd_at = bank.colAllowedAt;
1052    }
1053
1054    // we need to wait until the bus is available before we can issue
1055    // the command
1056    cmd_at = std::max(cmd_at, busBusyUntil - tCL);
1057
1058    // update the packet ready time
1059    dram_pkt->readyTime = cmd_at + tCL + tBURST;
1060
1061    // only one burst can use the bus at any one point in time
1062    assert(dram_pkt->readyTime - busBusyUntil >= tBURST);
1063
1064    // update the time for the next read/write burst for each
1065    // bank (add a max with tCCD/tCCD_L here)
1066    Tick cmd_dly;
1067    for(int j = 0; j < ranksPerChannel; j++) {
1068        for(int i = 0; i < banksPerRank; i++) {
1069            // next burst to same bank group in this rank must not happen
1070            // before tCCD_L.  Different bank group timing requirement is
1071            // tBURST; Add tCS for different ranks
1072            if (dram_pkt->rank == j) {
1073                if (bankGroupArch && (bank.bankgr == banks[j][i].bankgr)) {
1074                    // bank group architecture requires longer delays between
1075                    // RD/WR burst commands to the same bank group.
1076                    // Use tCCD_L in this case
1077                    cmd_dly = tCCD_L;
1078                } else {
1079                    // use tBURST (equivalent to tCCD_S), the shorter
1080                    // cas-to-cas delay value, when either:
1081                    // 1) bank group architecture is not supportted
1082                    // 2) bank is in a different bank group
1083                    cmd_dly = tBURST;
1084                }
1085            } else {
1086                // different rank is by default in a different bank group
1087                // use tBURST (equivalent to tCCD_S), which is the shorter
1088                // cas-to-cas delay in this case
1089                // Add tCS to account for rank-to-rank bus delay requirements
1090                cmd_dly = tBURST + tCS;
1091            }
1092            banks[j][i].colAllowedAt = std::max(cmd_at + cmd_dly,
1093                                                banks[j][i].colAllowedAt);
1094        }
1095    }
1096
1097    // Save rank of current access
1098    activeRank = dram_pkt->rank;
1099
1100    // If this is a write, we also need to respect the write recovery
1101    // time before a precharge, in the case of a read, respect the
1102    // read to precharge constraint
1103    bank.preAllowedAt = std::max(bank.preAllowedAt,
1104                                 dram_pkt->isRead ? cmd_at + tRTP :
1105                                 dram_pkt->readyTime + tWR);
1106
1107    // increment the bytes accessed and the accesses per row
1108    bank.bytesAccessed += burstSize;
1109    ++bank.rowAccesses;
1110
1111    // if we reached the max, then issue with an auto-precharge
1112    bool auto_precharge = pageMgmt == Enums::close ||
1113        bank.rowAccesses == maxAccessesPerRow;
1114
1115    // if we did not hit the limit, we might still want to
1116    // auto-precharge
1117    if (!auto_precharge &&
1118        (pageMgmt == Enums::open_adaptive ||
1119         pageMgmt == Enums::close_adaptive)) {
1120        // a twist on the open and close page policies:
1121        // 1) open_adaptive page policy does not blindly keep the
1122        // page open, but close it if there are no row hits, and there
1123        // are bank conflicts in the queue
1124        // 2) close_adaptive page policy does not blindly close the
1125        // page, but closes it only if there are no row hits in the queue.
1126        // In this case, only force an auto precharge when there
1127        // are no same page hits in the queue
1128        bool got_more_hits = false;
1129        bool got_bank_conflict = false;
1130
1131        // either look at the read queue or write queue
1132        const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
1133            writeQueue;
1134        auto p = queue.begin();
1135        // make sure we are not considering the packet that we are
1136        // currently dealing with (which is the head of the queue)
1137        ++p;
1138
1139        // keep on looking until we have found required condition or
1140        // reached the end
1141        while (!(got_more_hits &&
1142                 (got_bank_conflict || pageMgmt == Enums::close_adaptive)) &&
1143               p != queue.end()) {
1144            bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
1145                (dram_pkt->bank == (*p)->bank);
1146            bool same_row = dram_pkt->row == (*p)->row;
1147            got_more_hits |= same_rank_bank && same_row;
1148            got_bank_conflict |= same_rank_bank && !same_row;
1149            ++p;
1150        }
1151
1152        // auto pre-charge when either
1153        // 1) open_adaptive policy, we have not got any more hits, and
1154        //    have a bank conflict
1155        // 2) close_adaptive policy and we have not got any more hits
1156        auto_precharge = !got_more_hits &&
1157            (got_bank_conflict || pageMgmt == Enums::close_adaptive);
1158    }
1159
1160    // DRAMPower trace command to be written
1161    std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR";
1162
1163    // MemCommand required for DRAMPower library
1164    MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD :
1165                                                   MemCommand::WR;
1166
1167    // if this access should use auto-precharge, then we are
1168    // closing the row
1169    if (auto_precharge) {
1170        // if auto-precharge push a PRE command at the correct tick to the
1171        // list used by DRAMPower library to calculate power
1172        prechargeBank(bank, std::max(curTick(), bank.preAllowedAt));
1173
1174        DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId);
1175    }
1176
1177    // Update bus state
1178    busBusyUntil = dram_pkt->readyTime;
1179
1180    DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n",
1181            dram_pkt->addr, dram_pkt->readyTime, busBusyUntil);
1182
1183    rankPower[dram_pkt->rank].powerlib.doCommand(command, dram_pkt->bank,
1184                                                 divCeil(cmd_at, tCK) -
1185                                                 timeStampOffset);
1186
1187    DPRINTF(DRAMPower, "%llu,%s,%d,%d\n", divCeil(cmd_at, tCK) -
1188            timeStampOffset, mem_cmd, dram_pkt->bank, dram_pkt->rank);
1189
1190    // Update the minimum timing between the requests, this is a
1191    // conservative estimate of when we have to schedule the next
1192    // request to not introduce any unecessary bubbles. In most cases
1193    // we will wake up sooner than we have to.
1194    nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
1195
1196    // Update the stats and schedule the next request
1197    if (dram_pkt->isRead) {
1198        ++readsThisTime;
1199        if (row_hit)
1200            readRowHits++;
1201        bytesReadDRAM += burstSize;
1202        perBankRdBursts[dram_pkt->bankId]++;
1203
1204        // Update latency stats
1205        totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1206        totBusLat += tBURST;
1207        totQLat += cmd_at - dram_pkt->entryTime;
1208    } else {
1209        ++writesThisTime;
1210        if (row_hit)
1211            writeRowHits++;
1212        bytesWritten += burstSize;
1213        perBankWrBursts[dram_pkt->bankId]++;
1214    }
1215}
1216
1217void
1218DRAMCtrl::processNextReqEvent()
1219{
1220    // pre-emptively set to false.  Overwrite if in READ_TO_WRITE
1221    // or WRITE_TO_READ state
1222    bool switched_cmd_type = false;
1223    if (busState == READ_TO_WRITE) {
1224        DPRINTF(DRAM, "Switching to writes after %d reads with %d reads "
1225                "waiting\n", readsThisTime, readQueue.size());
1226
1227        // sample and reset the read-related stats as we are now
1228        // transitioning to writes, and all reads are done
1229        rdPerTurnAround.sample(readsThisTime);
1230        readsThisTime = 0;
1231
1232        // now proceed to do the actual writes
1233        busState = WRITE;
1234        switched_cmd_type = true;
1235    } else if (busState == WRITE_TO_READ) {
1236        DPRINTF(DRAM, "Switching to reads after %d writes with %d writes "
1237                "waiting\n", writesThisTime, writeQueue.size());
1238
1239        wrPerTurnAround.sample(writesThisTime);
1240        writesThisTime = 0;
1241
1242        busState = READ;
1243        switched_cmd_type = true;
1244    }
1245
1246    if (refreshState != REF_IDLE) {
1247        // if a refresh waiting for this event loop to finish, then hand
1248        // over now, and do not schedule a new nextReqEvent
1249        if (refreshState == REF_DRAIN) {
1250            DPRINTF(DRAM, "Refresh drain done, now precharging\n");
1251
1252            refreshState = REF_PRE;
1253
1254            // hand control back to the refresh event loop
1255            schedule(refreshEvent, curTick());
1256        }
1257
1258        // let the refresh finish before issuing any further requests
1259        return;
1260    }
1261
1262    // when we get here it is either a read or a write
1263    if (busState == READ) {
1264
1265        // track if we should switch or not
1266        bool switch_to_writes = false;
1267
1268        if (readQueue.empty()) {
1269            // In the case there is no read request to go next,
1270            // trigger writes if we have passed the low threshold (or
1271            // if we are draining)
1272            if (!writeQueue.empty() &&
1273                (drainManager || writeQueue.size() > writeLowThreshold)) {
1274
1275                switch_to_writes = true;
1276            } else {
1277                // check if we are drained
1278                if (respQueue.empty () && drainManager) {
1279                    drainManager->signalDrainDone();
1280                    drainManager = NULL;
1281                }
1282
1283                // nothing to do, not even any point in scheduling an
1284                // event for the next request
1285                return;
1286            }
1287        } else {
1288            // Figure out which read request goes next, and move it to the
1289            // front of the read queue
1290            chooseNext(readQueue, switched_cmd_type);
1291
1292            DRAMPacket* dram_pkt = readQueue.front();
1293
1294            // here we get a bit creative and shift the bus busy time not
1295            // just the tWTR, but also a CAS latency to capture the fact
1296            // that we are allowed to prepare a new bank, but not issue a
1297            // read command until after tWTR, in essence we capture a
1298            // bubble on the data bus that is tWTR + tCL
1299            if (switched_cmd_type && dram_pkt->rank == activeRank) {
1300                busBusyUntil += tWTR + tCL;
1301            }
1302
1303            doDRAMAccess(dram_pkt);
1304
1305            // At this point we're done dealing with the request
1306            readQueue.pop_front();
1307
1308            // sanity check
1309            assert(dram_pkt->size <= burstSize);
1310            assert(dram_pkt->readyTime >= curTick());
1311
1312            // Insert into response queue. It will be sent back to the
1313            // requestor at its readyTime
1314            if (respQueue.empty()) {
1315                assert(!respondEvent.scheduled());
1316                schedule(respondEvent, dram_pkt->readyTime);
1317            } else {
1318                assert(respQueue.back()->readyTime <= dram_pkt->readyTime);
1319                assert(respondEvent.scheduled());
1320            }
1321
1322            respQueue.push_back(dram_pkt);
1323
1324            // we have so many writes that we have to transition
1325            if (writeQueue.size() > writeHighThreshold) {
1326                switch_to_writes = true;
1327            }
1328        }
1329
1330        // switching to writes, either because the read queue is empty
1331        // and the writes have passed the low threshold (or we are
1332        // draining), or because the writes hit the hight threshold
1333        if (switch_to_writes) {
1334            // transition to writing
1335            busState = READ_TO_WRITE;
1336        }
1337    } else {
1338        chooseNext(writeQueue, switched_cmd_type);
1339        DRAMPacket* dram_pkt = writeQueue.front();
1340        // sanity check
1341        assert(dram_pkt->size <= burstSize);
1342
1343        // add a bubble to the data bus, as defined by the
1344        // tRTW when access is to the same rank as previous burst
1345        // Different rank timing is handled with tCS, which is
1346        // applied to colAllowedAt
1347        if (switched_cmd_type && dram_pkt->rank == activeRank) {
1348            busBusyUntil += tRTW;
1349        }
1350
1351        doDRAMAccess(dram_pkt);
1352
1353        writeQueue.pop_front();
1354        delete dram_pkt;
1355
1356        // If we emptied the write queue, or got sufficiently below the
1357        // threshold (using the minWritesPerSwitch as the hysteresis) and
1358        // are not draining, or we have reads waiting and have done enough
1359        // writes, then switch to reads.
1360        if (writeQueue.empty() ||
1361            (writeQueue.size() + minWritesPerSwitch < writeLowThreshold &&
1362             !drainManager) ||
1363            (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) {
1364            // turn the bus back around for reads again
1365            busState = WRITE_TO_READ;
1366
1367            // note that the we switch back to reads also in the idle
1368            // case, which eventually will check for any draining and
1369            // also pause any further scheduling if there is really
1370            // nothing to do
1371        }
1372    }
1373
1374    schedule(nextReqEvent, std::max(nextReqTime, curTick()));
1375
1376    // If there is space available and we have writes waiting then let
1377    // them retry. This is done here to ensure that the retry does not
1378    // cause a nextReqEvent to be scheduled before we do so as part of
1379    // the next request processing
1380    if (retryWrReq && writeQueue.size() < writeBufferSize) {
1381        retryWrReq = false;
1382        port.sendRetry();
1383    }
1384}
1385
1386uint64_t
1387DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
1388                      bool switched_cmd_type) const
1389{
1390    uint64_t bank_mask = 0;
1391    Tick min_act_at = MaxTick;
1392
1393    uint64_t bank_mask_same_rank = 0;
1394    Tick min_act_at_same_rank = MaxTick;
1395
1396    // Give precedence to commands that access same rank as previous command
1397    bool same_rank_match = false;
1398
1399    // determine if we have queued transactions targetting the
1400    // bank in question
1401    vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
1402    for (auto p = queue.begin(); p != queue.end(); ++p) {
1403        got_waiting[(*p)->bankId] = true;
1404    }
1405
1406    for (int i = 0; i < ranksPerChannel; i++) {
1407        for (int j = 0; j < banksPerRank; j++) {
1408            uint8_t bank_id = i * banksPerRank + j;
1409
1410            // if we have waiting requests for the bank, and it is
1411            // amongst the first available, update the mask
1412            if (got_waiting[bank_id]) {
1413                // simplistic approximation of when the bank can issue
1414                // an activate, ignoring any rank-to-rank switching
1415                // cost in this calculation
1416                Tick act_at = banks[i][j].openRow == Bank::NO_ROW ?
1417                    banks[i][j].actAllowedAt :
1418                    std::max(banks[i][j].preAllowedAt, curTick()) + tRP;
1419
1420                // prioritize commands that access the
1421                // same rank as previous burst
1422                // Calculate bank mask separately for the case and
1423                // evaluate after loop iterations complete
1424                if (i == activeRank && ranksPerChannel > 1) {
1425                    if (act_at <= min_act_at_same_rank) {
1426                        // reset same rank bank mask if new minimum is found
1427                        // and previous minimum could not immediately send ACT
1428                        if (act_at < min_act_at_same_rank &&
1429                            min_act_at_same_rank > curTick())
1430                            bank_mask_same_rank = 0;
1431
1432                        // Set flag indicating that a same rank
1433                        // opportunity was found
1434                        same_rank_match = true;
1435
1436                        // set the bit corresponding to the available bank
1437                        replaceBits(bank_mask_same_rank, bank_id, bank_id, 1);
1438                        min_act_at_same_rank = act_at;
1439                    }
1440                } else {
1441                    if (act_at <= min_act_at) {
1442                        // reset bank mask if new minimum is found
1443                        // and either previous minimum could not immediately send ACT
1444                        if (act_at < min_act_at && min_act_at > curTick())
1445                            bank_mask = 0;
1446                        // set the bit corresponding to the available bank
1447                        replaceBits(bank_mask, bank_id, bank_id, 1);
1448                        min_act_at = act_at;
1449                    }
1450                }
1451            }
1452        }
1453    }
1454
1455    // Determine the earliest time when the next burst can issue based
1456    // on the current busBusyUntil delay.
1457    // Offset by tRCD to correlate with ACT timing variables
1458    Tick min_cmd_at = busBusyUntil - tCL - tRCD;
1459
1460    // Prioritize same rank accesses that can issue B2B
1461    // Only optimize for same ranks when the command type
1462    // does not change; do not want to unnecessarily incur tWTR
1463    //
1464    // Resulting FCFS prioritization Order is:
1465    // 1) Commands that access the same rank as previous burst
1466    //    and can prep the bank seamlessly.
1467    // 2) Commands (any rank) with earliest bank prep
1468    if (!switched_cmd_type && same_rank_match &&
1469        min_act_at_same_rank <= min_cmd_at) {
1470        bank_mask = bank_mask_same_rank;
1471    }
1472
1473    return bank_mask;
1474}
1475
1476void
1477DRAMCtrl::processRefreshEvent()
1478{
1479    // when first preparing the refresh, remember when it was due
1480    if (refreshState == REF_IDLE) {
1481        // remember when the refresh is due
1482        refreshDueAt = curTick();
1483
1484        // proceed to drain
1485        refreshState = REF_DRAIN;
1486
1487        DPRINTF(DRAM, "Refresh due\n");
1488    }
1489
1490    // let any scheduled read or write go ahead, after which it will
1491    // hand control back to this event loop
1492    if (refreshState == REF_DRAIN) {
1493        if (nextReqEvent.scheduled()) {
1494            // hand control over to the request loop until it is
1495            // evaluated next
1496            DPRINTF(DRAM, "Refresh awaiting draining\n");
1497
1498            return;
1499        } else {
1500            refreshState = REF_PRE;
1501        }
1502    }
1503
1504    // at this point, ensure that all banks are precharged
1505    if (refreshState == REF_PRE) {
1506        // precharge any active bank if we are not already in the idle
1507        // state
1508        if (pwrState != PWR_IDLE) {
1509            // at the moment, we use a precharge all even if there is
1510            // only a single bank open
1511            DPRINTF(DRAM, "Precharging all\n");
1512
1513            // first determine when we can precharge
1514            Tick pre_at = curTick();
1515            for (int i = 0; i < ranksPerChannel; i++) {
1516                for (int j = 0; j < banksPerRank; j++) {
1517                    // respect both causality and any existing bank
1518                    // constraints, some banks could already have a
1519                    // (auto) precharge scheduled
1520                    pre_at = std::max(banks[i][j].preAllowedAt, pre_at);
1521                }
1522            }
1523
1524            // make sure all banks are precharged, and for those that
1525            // already are, update their availability
1526            Tick act_allowed_at = pre_at + tRP;
1527
1528            for (int i = 0; i < ranksPerChannel; i++) {
1529                for (int j = 0; j < banksPerRank; j++) {
1530                    if (banks[i][j].openRow != Bank::NO_ROW) {
1531                        prechargeBank(banks[i][j], pre_at, false);
1532                    } else {
1533                        banks[i][j].actAllowedAt =
1534                            std::max(banks[i][j].actAllowedAt, act_allowed_at);
1535                        banks[i][j].preAllowedAt =
1536                            std::max(banks[i][j].preAllowedAt, pre_at);
1537                    }
1538                }
1539
1540                // at the moment this affects all ranks
1541                rankPower[i].powerlib.doCommand(MemCommand::PREA, 0,
1542                                                divCeil(pre_at, tCK) -
1543                                                timeStampOffset);
1544
1545                DPRINTF(DRAMPower, "%llu,PREA,0,%d\n", divCeil(pre_at, tCK) -
1546                        timeStampOffset, i);
1547            }
1548        } else {
1549            DPRINTF(DRAM, "All banks already precharged, starting refresh\n");
1550
1551            // go ahead and kick the power state machine into gear if
1552            // we are already idle
1553            schedulePowerEvent(PWR_REF, curTick());
1554        }
1555
1556        refreshState = REF_RUN;
1557        assert(numBanksActive == 0);
1558
1559        // wait for all banks to be precharged, at which point the
1560        // power state machine will transition to the idle state, and
1561        // automatically move to a refresh, at that point it will also
1562        // call this method to get the refresh event loop going again
1563        return;
1564    }
1565
1566    // last but not least we perform the actual refresh
1567    if (refreshState == REF_RUN) {
1568        // should never get here with any banks active
1569        assert(numBanksActive == 0);
1570        assert(pwrState == PWR_REF);
1571
1572        Tick ref_done_at = curTick() + tRFC;
1573
1574        for (int i = 0; i < ranksPerChannel; i++) {
1575            for (int j = 0; j < banksPerRank; j++) {
1576                banks[i][j].actAllowedAt = ref_done_at;
1577            }
1578
1579            // at the moment this affects all ranks
1580            rankPower[i].powerlib.doCommand(MemCommand::REF, 0,
1581                                            divCeil(curTick(), tCK) -
1582                                            timeStampOffset);
1583
1584            // at the moment sort the list of commands and update the counters
1585            // for DRAMPower libray when doing a refresh
1586            sort(rankPower[i].powerlib.cmdList.begin(),
1587                 rankPower[i].powerlib.cmdList.end(), DRAMCtrl::sortTime);
1588
1589            // update the counters for DRAMPower, passing false to
1590            // indicate that this is not the last command in the
1591            // list. DRAMPower requires this information for the
1592            // correct calculation of the background energy at the end
1593            // of the simulation. Ideally we would want to call this
1594            // function with true once at the end of the
1595            // simulation. However, the discarded energy is extremly
1596            // small and does not effect the final results.
1597            rankPower[i].powerlib.updateCounters(false);
1598
1599            // call the energy function
1600            rankPower[i].powerlib.calcEnergy();
1601
1602            // Update the stats
1603            updatePowerStats(i);
1604
1605            DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), tCK) -
1606                    timeStampOffset, i);
1607        }
1608
1609        // make sure we did not wait so long that we cannot make up
1610        // for it
1611        if (refreshDueAt + tREFI < ref_done_at) {
1612            fatal("Refresh was delayed so long we cannot catch up\n");
1613        }
1614
1615        // compensate for the delay in actually performing the refresh
1616        // when scheduling the next one
1617        schedule(refreshEvent, refreshDueAt + tREFI - tRP);
1618
1619        assert(!powerEvent.scheduled());
1620
1621        // move to the idle power state once the refresh is done, this
1622        // will also move the refresh state machine to the refresh
1623        // idle state
1624        schedulePowerEvent(PWR_IDLE, ref_done_at);
1625
1626        DPRINTF(DRAMState, "Refresh done at %llu and next refresh at %llu\n",
1627                ref_done_at, refreshDueAt + tREFI);
1628    }
1629}
1630
1631void
1632DRAMCtrl::schedulePowerEvent(PowerState pwr_state, Tick tick)
1633{
1634    // respect causality
1635    assert(tick >= curTick());
1636
1637    if (!powerEvent.scheduled()) {
1638        DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n",
1639                tick, pwr_state);
1640
1641        // insert the new transition
1642        pwrStateTrans = pwr_state;
1643
1644        schedule(powerEvent, tick);
1645    } else {
1646        panic("Scheduled power event at %llu to state %d, "
1647              "with scheduled event at %llu to %d\n", tick, pwr_state,
1648              powerEvent.when(), pwrStateTrans);
1649    }
1650}
1651
1652void
1653DRAMCtrl::processPowerEvent()
1654{
1655    // remember where we were, and for how long
1656    Tick duration = curTick() - pwrStateTick;
1657    PowerState prev_state = pwrState;
1658
1659    // update the accounting
1660    pwrStateTime[prev_state] += duration;
1661
1662    pwrState = pwrStateTrans;
1663    pwrStateTick = curTick();
1664
1665    if (pwrState == PWR_IDLE) {
1666        DPRINTF(DRAMState, "All banks precharged\n");
1667
1668        // if we were refreshing, make sure we start scheduling requests again
1669        if (prev_state == PWR_REF) {
1670            DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration);
1671            assert(pwrState == PWR_IDLE);
1672
1673            // kick things into action again
1674            refreshState = REF_IDLE;
1675            assert(!nextReqEvent.scheduled());
1676            schedule(nextReqEvent, curTick());
1677        } else {
1678            assert(prev_state == PWR_ACT);
1679
1680            // if we have a pending refresh, and are now moving to
1681            // the idle state, direclty transition to a refresh
1682            if (refreshState == REF_RUN) {
1683                // there should be nothing waiting at this point
1684                assert(!powerEvent.scheduled());
1685
1686                // update the state in zero time and proceed below
1687                pwrState = PWR_REF;
1688            }
1689        }
1690    }
1691
1692    // we transition to the refresh state, let the refresh state
1693    // machine know of this state update and let it deal with the
1694    // scheduling of the next power state transition as well as the
1695    // following refresh
1696    if (pwrState == PWR_REF) {
1697        DPRINTF(DRAMState, "Refreshing\n");
1698        // kick the refresh event loop into action again, and that
1699        // in turn will schedule a transition to the idle power
1700        // state once the refresh is done
1701        assert(refreshState == REF_RUN);
1702        processRefreshEvent();
1703    }
1704}
1705
1706void
1707DRAMCtrl::updatePowerStats(uint8_t rank)
1708{
1709    // Get the energy and power from DRAMPower
1710    Data::MemoryPowerModel::Energy energy =
1711        rankPower[rank].powerlib.getEnergy();
1712    Data::MemoryPowerModel::Power power =
1713        rankPower[rank].powerlib.getPower();
1714
1715    actEnergy[rank] = energy.act_energy * devicesPerRank;
1716    preEnergy[rank] = energy.pre_energy * devicesPerRank;
1717    readEnergy[rank] = energy.read_energy * devicesPerRank;
1718    writeEnergy[rank] = energy.write_energy * devicesPerRank;
1719    refreshEnergy[rank] = energy.ref_energy * devicesPerRank;
1720    actBackEnergy[rank] = energy.act_stdby_energy * devicesPerRank;
1721    preBackEnergy[rank] = energy.pre_stdby_energy * devicesPerRank;
1722    totalEnergy[rank] = energy.total_energy * devicesPerRank;
1723    averagePower[rank] = power.average_power * devicesPerRank;
1724}
1725
1726void
1727DRAMCtrl::regStats()
1728{
1729    using namespace Stats;
1730
1731    AbstractMemory::regStats();
1732
1733    readReqs
1734        .name(name() + ".readReqs")
1735        .desc("Number of read requests accepted");
1736
1737    writeReqs
1738        .name(name() + ".writeReqs")
1739        .desc("Number of write requests accepted");
1740
1741    readBursts
1742        .name(name() + ".readBursts")
1743        .desc("Number of DRAM read bursts, "
1744              "including those serviced by the write queue");
1745
1746    writeBursts
1747        .name(name() + ".writeBursts")
1748        .desc("Number of DRAM write bursts, "
1749              "including those merged in the write queue");
1750
1751    servicedByWrQ
1752        .name(name() + ".servicedByWrQ")
1753        .desc("Number of DRAM read bursts serviced by the write queue");
1754
1755    mergedWrBursts
1756        .name(name() + ".mergedWrBursts")
1757        .desc("Number of DRAM write bursts merged with an existing one");
1758
1759    neitherReadNorWrite
1760        .name(name() + ".neitherReadNorWriteReqs")
1761        .desc("Number of requests that are neither read nor write");
1762
1763    perBankRdBursts
1764        .init(banksPerRank * ranksPerChannel)
1765        .name(name() + ".perBankRdBursts")
1766        .desc("Per bank write bursts");
1767
1768    perBankWrBursts
1769        .init(banksPerRank * ranksPerChannel)
1770        .name(name() + ".perBankWrBursts")
1771        .desc("Per bank write bursts");
1772
1773    avgRdQLen
1774        .name(name() + ".avgRdQLen")
1775        .desc("Average read queue length when enqueuing")
1776        .precision(2);
1777
1778    avgWrQLen
1779        .name(name() + ".avgWrQLen")
1780        .desc("Average write queue length when enqueuing")
1781        .precision(2);
1782
1783    totQLat
1784        .name(name() + ".totQLat")
1785        .desc("Total ticks spent queuing");
1786
1787    totBusLat
1788        .name(name() + ".totBusLat")
1789        .desc("Total ticks spent in databus transfers");
1790
1791    totMemAccLat
1792        .name(name() + ".totMemAccLat")
1793        .desc("Total ticks spent from burst creation until serviced "
1794              "by the DRAM");
1795
1796    avgQLat
1797        .name(name() + ".avgQLat")
1798        .desc("Average queueing delay per DRAM burst")
1799        .precision(2);
1800
1801    avgQLat = totQLat / (readBursts - servicedByWrQ);
1802
1803    avgBusLat
1804        .name(name() + ".avgBusLat")
1805        .desc("Average bus latency per DRAM burst")
1806        .precision(2);
1807
1808    avgBusLat = totBusLat / (readBursts - servicedByWrQ);
1809
1810    avgMemAccLat
1811        .name(name() + ".avgMemAccLat")
1812        .desc("Average memory access latency per DRAM burst")
1813        .precision(2);
1814
1815    avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
1816
1817    numRdRetry
1818        .name(name() + ".numRdRetry")
1819        .desc("Number of times read queue was full causing retry");
1820
1821    numWrRetry
1822        .name(name() + ".numWrRetry")
1823        .desc("Number of times write queue was full causing retry");
1824
1825    readRowHits
1826        .name(name() + ".readRowHits")
1827        .desc("Number of row buffer hits during reads");
1828
1829    writeRowHits
1830        .name(name() + ".writeRowHits")
1831        .desc("Number of row buffer hits during writes");
1832
1833    readRowHitRate
1834        .name(name() + ".readRowHitRate")
1835        .desc("Row buffer hit rate for reads")
1836        .precision(2);
1837
1838    readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
1839
1840    writeRowHitRate
1841        .name(name() + ".writeRowHitRate")
1842        .desc("Row buffer hit rate for writes")
1843        .precision(2);
1844
1845    writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
1846
1847    readPktSize
1848        .init(ceilLog2(burstSize) + 1)
1849        .name(name() + ".readPktSize")
1850        .desc("Read request sizes (log2)");
1851
1852     writePktSize
1853        .init(ceilLog2(burstSize) + 1)
1854        .name(name() + ".writePktSize")
1855        .desc("Write request sizes (log2)");
1856
1857     rdQLenPdf
1858        .init(readBufferSize)
1859        .name(name() + ".rdQLenPdf")
1860        .desc("What read queue length does an incoming req see");
1861
1862     wrQLenPdf
1863        .init(writeBufferSize)
1864        .name(name() + ".wrQLenPdf")
1865        .desc("What write queue length does an incoming req see");
1866
1867     bytesPerActivate
1868         .init(maxAccessesPerRow)
1869         .name(name() + ".bytesPerActivate")
1870         .desc("Bytes accessed per row activation")
1871         .flags(nozero);
1872
1873     rdPerTurnAround
1874         .init(readBufferSize)
1875         .name(name() + ".rdPerTurnAround")
1876         .desc("Reads before turning the bus around for writes")
1877         .flags(nozero);
1878
1879     wrPerTurnAround
1880         .init(writeBufferSize)
1881         .name(name() + ".wrPerTurnAround")
1882         .desc("Writes before turning the bus around for reads")
1883         .flags(nozero);
1884
1885    bytesReadDRAM
1886        .name(name() + ".bytesReadDRAM")
1887        .desc("Total number of bytes read from DRAM");
1888
1889    bytesReadWrQ
1890        .name(name() + ".bytesReadWrQ")
1891        .desc("Total number of bytes read from write queue");
1892
1893    bytesWritten
1894        .name(name() + ".bytesWritten")
1895        .desc("Total number of bytes written to DRAM");
1896
1897    bytesReadSys
1898        .name(name() + ".bytesReadSys")
1899        .desc("Total read bytes from the system interface side");
1900
1901    bytesWrittenSys
1902        .name(name() + ".bytesWrittenSys")
1903        .desc("Total written bytes from the system interface side");
1904
1905    avgRdBW
1906        .name(name() + ".avgRdBW")
1907        .desc("Average DRAM read bandwidth in MiByte/s")
1908        .precision(2);
1909
1910    avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
1911
1912    avgWrBW
1913        .name(name() + ".avgWrBW")
1914        .desc("Average achieved write bandwidth in MiByte/s")
1915        .precision(2);
1916
1917    avgWrBW = (bytesWritten / 1000000) / simSeconds;
1918
1919    avgRdBWSys
1920        .name(name() + ".avgRdBWSys")
1921        .desc("Average system read bandwidth in MiByte/s")
1922        .precision(2);
1923
1924    avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
1925
1926    avgWrBWSys
1927        .name(name() + ".avgWrBWSys")
1928        .desc("Average system write bandwidth in MiByte/s")
1929        .precision(2);
1930
1931    avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
1932
1933    peakBW
1934        .name(name() + ".peakBW")
1935        .desc("Theoretical peak bandwidth in MiByte/s")
1936        .precision(2);
1937
1938    peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
1939
1940    busUtil
1941        .name(name() + ".busUtil")
1942        .desc("Data bus utilization in percentage")
1943        .precision(2);
1944
1945    busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
1946
1947    totGap
1948        .name(name() + ".totGap")
1949        .desc("Total gap between requests");
1950
1951    avgGap
1952        .name(name() + ".avgGap")
1953        .desc("Average gap between requests")
1954        .precision(2);
1955
1956    avgGap = totGap / (readReqs + writeReqs);
1957
1958    // Stats for DRAM Power calculation based on Micron datasheet
1959    busUtilRead
1960        .name(name() + ".busUtilRead")
1961        .desc("Data bus utilization in percentage for reads")
1962        .precision(2);
1963
1964    busUtilRead = avgRdBW / peakBW * 100;
1965
1966    busUtilWrite
1967        .name(name() + ".busUtilWrite")
1968        .desc("Data bus utilization in percentage for writes")
1969        .precision(2);
1970
1971    busUtilWrite = avgWrBW / peakBW * 100;
1972
1973    pageHitRate
1974        .name(name() + ".pageHitRate")
1975        .desc("Row buffer hit rate, read and write combined")
1976        .precision(2);
1977
1978    pageHitRate = (writeRowHits + readRowHits) /
1979        (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
1980
1981    pwrStateTime
1982        .init(5)
1983        .name(name() + ".memoryStateTime")
1984        .desc("Time in different power states");
1985    pwrStateTime.subname(0, "IDLE");
1986    pwrStateTime.subname(1, "REF");
1987    pwrStateTime.subname(2, "PRE_PDN");
1988    pwrStateTime.subname(3, "ACT");
1989    pwrStateTime.subname(4, "ACT_PDN");
1990
1991    actEnergy
1992        .init(ranksPerChannel)
1993        .name(name() + ".actEnergy")
1994        .desc("Energy for activate commands per rank (pJ)");
1995
1996    preEnergy
1997        .init(ranksPerChannel)
1998        .name(name() + ".preEnergy")
1999        .desc("Energy for precharge commands per rank (pJ)");
2000
2001    readEnergy
2002        .init(ranksPerChannel)
2003        .name(name() + ".readEnergy")
2004        .desc("Energy for read commands per rank (pJ)");
2005
2006    writeEnergy
2007        .init(ranksPerChannel)
2008        .name(name() + ".writeEnergy")
2009        .desc("Energy for write commands per rank (pJ)");
2010
2011    refreshEnergy
2012        .init(ranksPerChannel)
2013        .name(name() + ".refreshEnergy")
2014        .desc("Energy for refresh commands per rank (pJ)");
2015
2016    actBackEnergy
2017        .init(ranksPerChannel)
2018        .name(name() + ".actBackEnergy")
2019        .desc("Energy for active background per rank (pJ)");
2020
2021    preBackEnergy
2022        .init(ranksPerChannel)
2023        .name(name() + ".preBackEnergy")
2024        .desc("Energy for precharge background per rank (pJ)");
2025
2026    totalEnergy
2027        .init(ranksPerChannel)
2028        .name(name() + ".totalEnergy")
2029        .desc("Total energy per rank (pJ)");
2030
2031    averagePower
2032        .init(ranksPerChannel)
2033        .name(name() + ".averagePower")
2034        .desc("Core power per rank (mW)");
2035}
2036
2037void
2038DRAMCtrl::recvFunctional(PacketPtr pkt)
2039{
2040    // rely on the abstract memory
2041    functionalAccess(pkt);
2042}
2043
2044BaseSlavePort&
2045DRAMCtrl::getSlavePort(const string &if_name, PortID idx)
2046{
2047    if (if_name != "port") {
2048        return MemObject::getSlavePort(if_name, idx);
2049    } else {
2050        return port;
2051    }
2052}
2053
2054unsigned int
2055DRAMCtrl::drain(DrainManager *dm)
2056{
2057    unsigned int count = port.drain(dm);
2058
2059    // if there is anything in any of our internal queues, keep track
2060    // of that as well
2061    if (!(writeQueue.empty() && readQueue.empty() &&
2062          respQueue.empty())) {
2063        DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
2064                " resp: %d\n", writeQueue.size(), readQueue.size(),
2065                respQueue.size());
2066        ++count;
2067        drainManager = dm;
2068
2069        // the only part that is not drained automatically over time
2070        // is the write queue, thus kick things into action if needed
2071        if (!writeQueue.empty() && !nextReqEvent.scheduled()) {
2072            schedule(nextReqEvent, curTick());
2073        }
2074    }
2075
2076    if (count)
2077        setDrainState(Drainable::Draining);
2078    else
2079        setDrainState(Drainable::Drained);
2080    return count;
2081}
2082
2083DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
2084    : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
2085      memory(_memory)
2086{ }
2087
2088AddrRangeList
2089DRAMCtrl::MemoryPort::getAddrRanges() const
2090{
2091    AddrRangeList ranges;
2092    ranges.push_back(memory.getAddrRange());
2093    return ranges;
2094}
2095
2096void
2097DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
2098{
2099    pkt->pushLabel(memory.name());
2100
2101    if (!queue.checkFunctional(pkt)) {
2102        // Default implementation of SimpleTimingPort::recvFunctional()
2103        // calls recvAtomic() and throws away the latency; we can save a
2104        // little here by just not calculating the latency.
2105        memory.recvFunctional(pkt);
2106    }
2107
2108    pkt->popLabel();
2109}
2110
2111Tick
2112DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt)
2113{
2114    return memory.recvAtomic(pkt);
2115}
2116
2117bool
2118DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt)
2119{
2120    // pass it to the memory controller
2121    return memory.recvTimingReq(pkt);
2122}
2123
2124DRAMCtrl*
2125DRAMCtrlParams::create()
2126{
2127    return new DRAMCtrl(this);
2128}
2129