dram_ctrl.cc revision 9833
16145Snate@binkert.org/*
26145Snate@binkert.org * Copyright (c) 2010-2013 ARM Limited
36145Snate@binkert.org * All rights reserved
46145Snate@binkert.org *
56145Snate@binkert.org * The license below extends only to copyright in the software and shall
66145Snate@binkert.org * not be construed as granting a license to any other intellectual
76145Snate@binkert.org * property including but not limited to intellectual property relating
86145Snate@binkert.org * to a hardware implementation of the functionality of the software
96145Snate@binkert.org * licensed hereunder.  You may use the software subject to the license
106145Snate@binkert.org * terms below provided that you ensure that this notice is replicated
116145Snate@binkert.org * unmodified and in its entirety in all distributions of the software,
126145Snate@binkert.org * modified or unmodified, in source code or in binary form.
136145Snate@binkert.org *
146145Snate@binkert.org * Copyright (c) 2013 Amin Farmahini-Farahani
156145Snate@binkert.org * All rights reserved.
166145Snate@binkert.org *
176145Snate@binkert.org * Redistribution and use in source and binary forms, with or without
186145Snate@binkert.org * modification, are permitted provided that the following conditions are
196145Snate@binkert.org * met: redistributions of source code must retain the above copyright
206145Snate@binkert.org * notice, this list of conditions and the following disclaimer;
216145Snate@binkert.org * redistributions in binary form must reproduce the above copyright
226145Snate@binkert.org * notice, this list of conditions and the following disclaimer in the
236145Snate@binkert.org * documentation and/or other materials provided with the distribution;
246145Snate@binkert.org * neither the name of the copyright holders nor the names of its
256145Snate@binkert.org * contributors may be used to endorse or promote products derived from
266145Snate@binkert.org * this software without specific prior written permission.
276145Snate@binkert.org *
286145Snate@binkert.org * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
297832Snate@binkert.org * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
307832Snate@binkert.org * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
317054Snate@binkert.org * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
328232Snate@binkert.org * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
336154Snate@binkert.org * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
348229Snate@binkert.org * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
356154Snate@binkert.org * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
367054Snate@binkert.org * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
376154Snate@binkert.org * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
386145Snate@binkert.org * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
397055Snate@binkert.org *
407055Snate@binkert.org * Authors: Andreas Hansson
416145Snate@binkert.org *          Ani Udipi
426145Snate@binkert.org */
436145Snate@binkert.org
446145Snate@binkert.org#include "base/trace.hh"
456145Snate@binkert.org#include "debug/Drain.hh"
466145Snate@binkert.org#include "debug/DRAM.hh"
476145Snate@binkert.org#include "debug/DRAMWR.hh"
486145Snate@binkert.org#include "mem/simple_dram.hh"
496145Snate@binkert.org#include "sim/system.hh"
507054Snate@binkert.org
518259SBrad.Beckmann@amd.comusing namespace std;
526145Snate@binkert.org
538259SBrad.Beckmann@amd.comSimpleDRAM::SimpleDRAM(const SimpleDRAMParams* p) :
547054Snate@binkert.org    AbstractMemory(p),
556145Snate@binkert.org    port(name() + ".port", *this),
566145Snate@binkert.org    retryRdReq(false), retryWrReq(false),
577054Snate@binkert.org    rowHitFlag(false), stopReads(false), actTicks(p->activation_limit, 0),
588259SBrad.Beckmann@amd.com    writeEvent(this), respondEvent(this),
596145Snate@binkert.org    refreshEvent(this), nextReqEvent(this), drainManager(NULL),
608259SBrad.Beckmann@amd.com    deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
617054Snate@binkert.org    deviceRowBufferSize(p->device_rowbuffer_size),
626145Snate@binkert.org    devicesPerRank(p->devices_per_rank),
636145Snate@binkert.org    burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8),
647054Snate@binkert.org    rowBufferSize(devicesPerRank * deviceRowBufferSize),
658259SBrad.Beckmann@amd.com    ranksPerChannel(p->ranks_per_channel),
668259SBrad.Beckmann@amd.com    banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0),
676145Snate@binkert.org    readBufferSize(p->read_buffer_size),
687054Snate@binkert.org    writeBufferSize(p->write_buffer_size),
697054Snate@binkert.org    writeThresholdPerc(p->write_thresh_perc),
706145Snate@binkert.org    tWTR(p->tWTR), tBURST(p->tBURST),
717832Snate@binkert.org    tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP),
727054Snate@binkert.org    tRFC(p->tRFC), tREFI(p->tREFI),
737054Snate@binkert.org    tXAW(p->tXAW), activationLimit(p->activation_limit),
748259SBrad.Beckmann@amd.com    memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
756145Snate@binkert.org    pageMgmt(p->page_policy),
767054Snate@binkert.org    frontendLatency(p->static_frontend_latency),
777054Snate@binkert.org    backendLatency(p->static_backend_latency),
786145Snate@binkert.org    busBusyUntil(0), writeStartTime(0),
796145Snate@binkert.org    prevArrival(0), numReqs(0)
807054Snate@binkert.org{
817054Snate@binkert.org    // create the bank states based on the dimensions of the ranks and
826145Snate@binkert.org    // banks
837054Snate@binkert.org    banks.resize(ranksPerChannel);
847054Snate@binkert.org    for (size_t c = 0; c < ranksPerChannel; ++c) {
857054Snate@binkert.org        banks[c].resize(banksPerRank);
867054Snate@binkert.org    }
876145Snate@binkert.org
886145Snate@binkert.org    // round the write threshold percent to a whole number of entries
897054Snate@binkert.org    // in the buffer
907454Snate@binkert.org    writeThreshold = writeBufferSize * writeThresholdPerc / 100.0;
917454Snate@binkert.org}
926145Snate@binkert.org
937054Snate@binkert.orgvoid
947054Snate@binkert.orgSimpleDRAM::init()
957054Snate@binkert.org{
967054Snate@binkert.org    if (!port.isConnected()) {
976145Snate@binkert.org        fatal("SimpleDRAM %s is unconnected!\n", name());
987454Snate@binkert.org    } else {
997054Snate@binkert.org        port.sendRangeChange();
1007454Snate@binkert.org    }
1017054Snate@binkert.org
1027054Snate@binkert.org    // we could deal with plenty options here, but for now do a quick
1037054Snate@binkert.org    // sanity check
1046145Snate@binkert.org    DPRINTF(DRAM, "Burst size %d bytes\n", burstSize);
1056145Snate@binkert.org
1066145Snate@binkert.org    // determine the rows per bank by looking at the total capacity
1077054Snate@binkert.org    uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
1087054Snate@binkert.org
1096145Snate@binkert.org    DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
1107454Snate@binkert.org            AbstractMemory::size());
1117454Snate@binkert.org
1127454Snate@binkert.org    columnsPerRowBuffer = rowBufferSize / burstSize;
1136145Snate@binkert.org
1147054Snate@binkert.org    DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
1157054Snate@binkert.org            rowBufferSize, columnsPerRowBuffer);
1168608Snilay@cs.wisc.edu
1178608Snilay@cs.wisc.edu    rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
1187054Snate@binkert.org
1197054Snate@binkert.org    if (range.interleaved()) {
1206145Snate@binkert.org        if (channels != range.stripes())
1216145Snate@binkert.org            panic("%s has %d interleaved address stripes but %d channel(s)\n",
1227054Snate@binkert.org                  name(), range.stripes(), channels);
1237054Snate@binkert.org
1246145Snate@binkert.org        if (addrMapping == Enums::RaBaChCo) {
1257054Snate@binkert.org            if (rowBufferSize != range.granularity()) {
1267054Snate@binkert.org                panic("Interleaving of %s doesn't match RaBaChCo address map\n",
1277054Snate@binkert.org                      name());
1286145Snate@binkert.org            }
1297054Snate@binkert.org        } else if (addrMapping == Enums::RaBaCoCh) {
1307054Snate@binkert.org            if (burstSize != range.granularity()) {
1317054Snate@binkert.org                panic("Interleaving of %s doesn't match RaBaCoCh address map\n",
1327054Snate@binkert.org                      name());
1337054Snate@binkert.org            }
1347054Snate@binkert.org        } else if (addrMapping == Enums::CoRaBaCh) {
1356145Snate@binkert.org            if (burstSize != range.granularity())
1367054Snate@binkert.org                panic("Interleaving of %s doesn't match CoRaBaCh address map\n",
1377054Snate@binkert.org                      name());
1387054Snate@binkert.org        }
1397054Snate@binkert.org    }
1407054Snate@binkert.org}
1417054Snate@binkert.org
1426145Snate@binkert.orgvoid
1436145Snate@binkert.orgSimpleDRAM::startup()
1447054Snate@binkert.org{
1457054Snate@binkert.org    // print the configuration of the controller
1467054Snate@binkert.org    printParams();
1477054Snate@binkert.org
1487054Snate@binkert.org    // kick off the refresh
1497054Snate@binkert.org    schedule(refreshEvent, curTick() + tREFI);
1507054Snate@binkert.org}
1517054Snate@binkert.org
1527054Snate@binkert.orgTick
1537054Snate@binkert.orgSimpleDRAM::recvAtomic(PacketPtr pkt)
1547054Snate@binkert.org{
1557054Snate@binkert.org    DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
1567054Snate@binkert.org
1577054Snate@binkert.org    // do the actual memory access and turn the packet into a response
1587054Snate@binkert.org    access(pkt);
1597054Snate@binkert.org
1607054Snate@binkert.org    Tick latency = 0;
1617054Snate@binkert.org    if (!pkt->memInhibitAsserted() && pkt->hasData()) {
1627453Snate@binkert.org        // this value is not supposed to be accurate, just enough to
1637054Snate@binkert.org        // keep things going, mimic a closed page
1647054Snate@binkert.org        latency = tRP + tRCD + tCL;
1657054Snate@binkert.org    }
1667780Snilay@cs.wisc.edu    return latency;
1677780Snilay@cs.wisc.edu}
1687054Snate@binkert.org
1697780Snilay@cs.wisc.edubool
1707054Snate@binkert.orgSimpleDRAM::readQueueFull(unsigned int neededEntries) const
1717054Snate@binkert.org{
1727054Snate@binkert.org    DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
1737054Snate@binkert.org            readBufferSize, readQueue.size() + respQueue.size(),
1747054Snate@binkert.org            neededEntries);
1757054Snate@binkert.org
1767054Snate@binkert.org    return
1777054Snate@binkert.org        (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
1787780Snilay@cs.wisc.edu}
1797054Snate@binkert.org
1807054Snate@binkert.orgbool
1817054Snate@binkert.orgSimpleDRAM::writeQueueFull(unsigned int neededEntries) const
1827054Snate@binkert.org{
1837054Snate@binkert.org    DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
1847054Snate@binkert.org            writeBufferSize, writeQueue.size(), neededEntries);
1857054Snate@binkert.org    return (writeQueue.size() + neededEntries) > writeBufferSize;
1867054Snate@binkert.org}
1877054Snate@binkert.org
1887054Snate@binkert.orgSimpleDRAM::DRAMPacket*
1897054Snate@binkert.orgSimpleDRAM::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size)
1907780Snilay@cs.wisc.edu{
1917054Snate@binkert.org    // decode the address based on the address mapping scheme, with
1927054Snate@binkert.org    // Ra, Co, Ba and Ch denoting rank, column, bank and channel,
1937054Snate@binkert.org    // respectively
1947054Snate@binkert.org    uint8_t rank;
1956145Snate@binkert.org    uint16_t bank;
1966145Snate@binkert.org    uint16_t row;
1977054Snate@binkert.org
1987054Snate@binkert.org    // truncate the address to the access granularity
1997054Snate@binkert.org    Addr addr = dramPktAddr / burstSize;
2006145Snate@binkert.org
2017054Snate@binkert.org    // we have removed the lowest order address bits that denote the
2027054Snate@binkert.org    // position within the column
2036145Snate@binkert.org    if (addrMapping == Enums::RaBaChCo) {
2047054Snate@binkert.org        // the lowest order bits denote the column to ensure that
2057054Snate@binkert.org        // sequential cache lines occupy the same row
2067054Snate@binkert.org        addr = addr / columnsPerRowBuffer;
2077054Snate@binkert.org
2087054Snate@binkert.org        // take out the channel part of the address
2097054Snate@binkert.org        addr = addr / channels;
2107054Snate@binkert.org
2117780Snilay@cs.wisc.edu        // after the channel bits, get the bank bits to interleave
2127054Snate@binkert.org        // over the banks
2137780Snilay@cs.wisc.edu        bank = addr % banksPerRank;
2147054Snate@binkert.org        addr = addr / banksPerRank;
2157054Snate@binkert.org
2167054Snate@binkert.org        // after the bank, we get the rank bits which thus interleaves
2177054Snate@binkert.org        // over the ranks
2187054Snate@binkert.org        rank = addr % ranksPerChannel;
2196145Snate@binkert.org        addr = addr / ranksPerChannel;
2206145Snate@binkert.org
2217054Snate@binkert.org        // lastly, get the row bits
2227054Snate@binkert.org        row = addr % rowsPerBank;
2236145Snate@binkert.org        addr = addr / rowsPerBank;
2247054Snate@binkert.org    } else if (addrMapping == Enums::RaBaCoCh) {
2256145Snate@binkert.org        // take out the channel part of the address
2266145Snate@binkert.org        addr = addr / channels;
2277054Snate@binkert.org
2287054Snate@binkert.org        // next, the column
2296145Snate@binkert.org        addr = addr / columnsPerRowBuffer;
2307054Snate@binkert.org
2317054Snate@binkert.org        // after the column bits, we get the bank bits to interleave
2326145Snate@binkert.org        // over the banks
2337054Snate@binkert.org        bank = addr % banksPerRank;
2347054Snate@binkert.org        addr = addr / banksPerRank;
2357054Snate@binkert.org
2367054Snate@binkert.org        // after the bank, we get the rank bits which thus interleaves
2376145Snate@binkert.org        // over the ranks
2386145Snate@binkert.org        rank = addr % ranksPerChannel;
2396145Snate@binkert.org        addr = addr / ranksPerChannel;
2407054Snate@binkert.org
2417054Snate@binkert.org        // lastly, get the row bits
2426145Snate@binkert.org        row = addr % rowsPerBank;
2436145Snate@binkert.org        addr = addr / rowsPerBank;
2446145Snate@binkert.org    } else if (addrMapping == Enums::CoRaBaCh) {
2457054Snate@binkert.org        // optimise for closed page mode and utilise maximum
2467054Snate@binkert.org        // parallelism of the DRAM (at the cost of power)
2476145Snate@binkert.org
2487054Snate@binkert.org        // take out the channel part of the address, not that this has
2497054Snate@binkert.org        // to match with how accesses are interleaved between the
2506145Snate@binkert.org        // controllers in the address mapping
2516145Snate@binkert.org        addr = addr / channels;
2527054Snate@binkert.org
2537054Snate@binkert.org        // start with the bank bits, as this provides the maximum
2546145Snate@binkert.org        // opportunity for parallelism between requests
2558054Sksewell@umich.edu        bank = addr % banksPerRank;
2566145Snate@binkert.org        addr = addr / banksPerRank;
2576145Snate@binkert.org
2587054Snate@binkert.org        // next get the rank bits
2597054Snate@binkert.org        rank = addr % ranksPerChannel;
2607054Snate@binkert.org        addr = addr / ranksPerChannel;
2617054Snate@binkert.org
2626145Snate@binkert.org        // next the column bits which we do not need to keep track of
2637054Snate@binkert.org        // and simply skip past
2647054Snate@binkert.org        addr = addr / columnsPerRowBuffer;
2657054Snate@binkert.org
2666145Snate@binkert.org        // lastly, get the row bits
2677054Snate@binkert.org        row = addr % rowsPerBank;
2687054Snate@binkert.org        addr = addr / rowsPerBank;
2697054Snate@binkert.org    } else
2707054Snate@binkert.org        panic("Unknown address mapping policy chosen!");
2717054Snate@binkert.org
2726145Snate@binkert.org    assert(rank < ranksPerChannel);
273    assert(bank < banksPerRank);
274    assert(row < rowsPerBank);
275
276    DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
277            dramPktAddr, rank, bank, row);
278
279    // create the corresponding DRAM packet with the entry time and
280    // ready time set to the current tick, the latter will be updated
281    // later
282    return new DRAMPacket(pkt, rank, bank, row, dramPktAddr, size,
283                          banks[rank][bank]);
284}
285
286void
287SimpleDRAM::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
288{
289    // only add to the read queue here. whenever the request is
290    // eventually done, set the readyTime, and call schedule()
291    assert(!pkt->isWrite());
292
293    assert(pktCount != 0);
294
295    // if the request size is larger than burst size, the pkt is split into
296    // multiple DRAM packets
297    // Note if the pkt starting address is not aligened to burst size, the
298    // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
299    // are aligned to burst size boundaries. This is to ensure we accurately
300    // check read packets against packets in write queue.
301    Addr addr = pkt->getAddr();
302    unsigned pktsServicedByWrQ = 0;
303    BurstHelper* burst_helper = NULL;
304    for (int cnt = 0; cnt < pktCount; ++cnt) {
305        unsigned size = std::min((addr | (burstSize - 1)) + 1,
306                        pkt->getAddr() + pkt->getSize()) - addr;
307        readPktSize[ceilLog2(size)]++;
308        readBursts++;
309
310        // First check write buffer to see if the data is already at
311        // the controller
312        bool foundInWrQ = false;
313        for (auto i = writeQueue.begin(); i != writeQueue.end(); ++i) {
314            // check if the read is subsumed in the write entry we are
315            // looking at
316            if ((*i)->addr <= addr &&
317                (addr + size) <= ((*i)->addr + (*i)->size)) {
318                foundInWrQ = true;
319                servicedByWrQ++;
320                pktsServicedByWrQ++;
321                DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
322                        "write queue\n", addr, size);
323                bytesRead += burstSize;
324                bytesConsumedRd += size;
325                break;
326            }
327        }
328
329        // If not found in the write q, make a DRAM packet and
330        // push it onto the read queue
331        if (!foundInWrQ) {
332
333            // Make the burst helper for split packets
334            if (pktCount > 1 && burst_helper == NULL) {
335                DPRINTF(DRAM, "Read to addr %lld translates to %d "
336                        "dram requests\n", pkt->getAddr(), pktCount);
337                burst_helper = new BurstHelper(pktCount);
338            }
339
340            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size);
341            dram_pkt->burstHelper = burst_helper;
342
343            assert(!readQueueFull(1));
344            rdQLenPdf[readQueue.size() + respQueue.size()]++;
345
346            DPRINTF(DRAM, "Adding to read queue\n");
347
348            readQueue.push_back(dram_pkt);
349
350            // Update stats
351            uint32_t bank_id = banksPerRank * dram_pkt->rank + dram_pkt->bank;
352            assert(bank_id < ranksPerChannel * banksPerRank);
353            perBankRdReqs[bank_id]++;
354
355            avgRdQLen = readQueue.size() + respQueue.size();
356        }
357
358        // Starting address of next dram pkt (aligend to burstSize boundary)
359        addr = (addr | (burstSize - 1)) + 1;
360    }
361
362    // If all packets are serviced by write queue, we send the repsonse back
363    if (pktsServicedByWrQ == pktCount) {
364        accessAndRespond(pkt, frontendLatency);
365        return;
366    }
367
368    // Update how many split packets are serviced by write queue
369    if (burst_helper != NULL)
370        burst_helper->burstsServiced = pktsServicedByWrQ;
371
372    // If we are not already scheduled to get the read request out of
373    // the queue, do so now
374    if (!nextReqEvent.scheduled() && !stopReads) {
375        DPRINTF(DRAM, "Request scheduled immediately\n");
376        schedule(nextReqEvent, curTick());
377    }
378}
379
380void
381SimpleDRAM::processWriteEvent()
382{
383    assert(!writeQueue.empty());
384    uint32_t numWritesThisTime = 0;
385
386    DPRINTF(DRAMWR, "Beginning DRAM Writes\n");
387    Tick temp1 M5_VAR_USED = std::max(curTick(), busBusyUntil);
388    Tick temp2 M5_VAR_USED = std::max(curTick(), maxBankFreeAt());
389
390    // @todo: are there any dangers with the untimed while loop?
391    while (!writeQueue.empty()) {
392        if (numWritesThisTime > writeThreshold) {
393            DPRINTF(DRAMWR, "Hit write threshold %d\n", writeThreshold);
394            break;
395        }
396
397        chooseNextWrite();
398        DRAMPacket* dram_pkt = writeQueue.front();
399
400        // sanity check
401        assert(dram_pkt->size <= burstSize);
402
403        // What's the earliest the request can be put on the bus
404        Tick schedTime = std::max(curTick(), busBusyUntil);
405
406        DPRINTF(DRAMWR, "Asking for latency estimate at %lld\n",
407                schedTime + tBURST);
408
409        pair<Tick, Tick> lat = estimateLatency(dram_pkt, schedTime + tBURST);
410        Tick accessLat = lat.second;
411
412        // look at the rowHitFlag set by estimateLatency
413        if (rowHitFlag)
414            writeRowHits++;
415
416        Bank& bank = dram_pkt->bank_ref;
417
418        if (pageMgmt == Enums::open) {
419            bank.openRow = dram_pkt->row;
420            bank.freeAt = schedTime + tBURST + std::max(accessLat, tCL);
421            busBusyUntil = bank.freeAt - tCL;
422            bank.bytesAccessed += burstSize;
423
424            if (!rowHitFlag) {
425                bank.tRASDoneAt = bank.freeAt + tRP;
426                recordActivate(bank.freeAt - tCL - tRCD);
427                busBusyUntil = bank.freeAt - tCL - tRCD;
428
429                // sample the number of bytes accessed and reset it as
430                // we are now closing this row
431                bytesPerActivate.sample(bank.bytesAccessed);
432                bank.bytesAccessed = 0;
433            }
434        } else if (pageMgmt == Enums::close) {
435            bank.freeAt = schedTime + tBURST + accessLat + tRP + tRP;
436            // Work backwards from bank.freeAt to determine activate time
437            recordActivate(bank.freeAt - tRP - tRP - tCL - tRCD);
438            busBusyUntil = bank.freeAt - tRP - tRP - tCL - tRCD;
439            DPRINTF(DRAMWR, "processWriteEvent::bank.freeAt for "
440                    "banks_id %d is %lld\n",
441                    dram_pkt->rank * banksPerRank + dram_pkt->bank,
442                    bank.freeAt);
443            bytesPerActivate.sample(burstSize);
444        } else
445            panic("Unknown page management policy chosen\n");
446
447        DPRINTF(DRAMWR, "Done writing to address %lld\n", dram_pkt->addr);
448
449        DPRINTF(DRAMWR, "schedtime is %lld, tBURST is %lld, "
450                "busbusyuntil is %lld\n",
451                schedTime, tBURST, busBusyUntil);
452
453        writeQueue.pop_front();
454        delete dram_pkt;
455
456        numWritesThisTime++;
457    }
458
459    DPRINTF(DRAMWR, "Completed %d writes, bus busy for %lld ticks,"\
460            "banks busy for %lld ticks\n", numWritesThisTime,
461            busBusyUntil - temp1, maxBankFreeAt() - temp2);
462
463    // Update stats
464    avgWrQLen = writeQueue.size();
465
466    // turn the bus back around for reads again
467    busBusyUntil += tWTR;
468    stopReads = false;
469
470    if (retryWrReq) {
471        retryWrReq = false;
472        port.sendRetry();
473    }
474
475    // if there is nothing left in any queue, signal a drain
476    if (writeQueue.empty() && readQueue.empty() &&
477        respQueue.empty () && drainManager) {
478        drainManager->signalDrainDone();
479        drainManager = NULL;
480    }
481
482    // Once you're done emptying the write queue, check if there's
483    // anything in the read queue, and call schedule if required. The
484    // retry above could already have caused it to be scheduled, so
485    // first check
486    if (!nextReqEvent.scheduled())
487        schedule(nextReqEvent, busBusyUntil);
488}
489
490void
491SimpleDRAM::triggerWrites()
492{
493    DPRINTF(DRAM, "Writes triggered at %lld\n", curTick());
494    // Flag variable to stop any more read scheduling
495    stopReads = true;
496
497    writeStartTime = std::max(busBusyUntil, curTick()) + tWTR;
498
499    DPRINTF(DRAM, "Writes scheduled at %lld\n", writeStartTime);
500
501    assert(writeStartTime >= curTick());
502    assert(!writeEvent.scheduled());
503    schedule(writeEvent, writeStartTime);
504}
505
506void
507SimpleDRAM::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
508{
509    // only add to the write queue here. whenever the request is
510    // eventually done, set the readyTime, and call schedule()
511    assert(pkt->isWrite());
512
513    // if the request size is larger than burst size, the pkt is split into
514    // multiple DRAM packets
515    Addr addr = pkt->getAddr();
516    for (int cnt = 0; cnt < pktCount; ++cnt) {
517        unsigned size = std::min((addr | (burstSize - 1)) + 1,
518                        pkt->getAddr() + pkt->getSize()) - addr;
519        writePktSize[ceilLog2(size)]++;
520        writeBursts++;
521
522        // see if we can merge with an existing item in the write
523        // queue and keep track of whether we have merged or not, as
524        // there is only ever one item to merge with
525        bool merged = false;
526        auto w = writeQueue.begin();
527
528        while(!merged && w != writeQueue.end()) {
529            // either of the two could be first, if they are the same
530            // it does not matter which way we go
531            if ((*w)->addr >= addr) {
532                if ((addr + size) >= ((*w)->addr + (*w)->size)) {
533                    // check if the existing one is completely
534                    // subsumed in the new one
535                    DPRINTF(DRAM, "Merging write covering existing burst\n");
536                    merged = true;
537                    // update both the address and the size
538                    (*w)->addr = addr;
539                    (*w)->size = size;
540                } else if ((addr + size) >= (*w)->addr &&
541                           ((*w)->addr + (*w)->size - addr) <= burstSize) {
542                    // the new one is just before or partially
543                    // overlapping with the existing one, and together
544                    // they fit within a burst
545                    DPRINTF(DRAM, "Merging write before existing burst\n");
546                    merged = true;
547                    // the existing queue item needs to be adjusted with
548                    // respect to both address and size
549                    (*w)->addr = addr;
550                    (*w)->size = (*w)->addr + (*w)->size - addr;
551                }
552            } else {
553                if (((*w)->addr + (*w)->size) >= (addr + size)) {
554                    // check if the new one is completely subsumed in the
555                    // existing one
556                    DPRINTF(DRAM, "Merging write into existing burst\n");
557                    merged = true;
558                    // no adjustments necessary
559                } else if (((*w)->addr + (*w)->size) >= addr &&
560                           (addr + size - (*w)->addr) <= burstSize) {
561                    // the existing one is just before or partially
562                    // overlapping with the new one, and together
563                    // they fit within a burst
564                    DPRINTF(DRAM, "Merging write after existing burst\n");
565                    merged = true;
566                    // the address is right, and only the size has
567                    // to be adjusted
568                    (*w)->size = addr + size - (*w)->addr;
569                }
570            }
571            ++w;
572        }
573
574        // if the item was not merged we need to create a new write
575        // and enqueue it
576        if (!merged) {
577            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size);
578
579            assert(writeQueue.size() < writeBufferSize);
580            wrQLenPdf[writeQueue.size()]++;
581
582            DPRINTF(DRAM, "Adding to write queue\n");
583
584            writeQueue.push_back(dram_pkt);
585
586            // Update stats
587            uint32_t bank_id = banksPerRank * dram_pkt->rank + dram_pkt->bank;
588            assert(bank_id < ranksPerChannel * banksPerRank);
589            perBankWrReqs[bank_id]++;
590
591            avgWrQLen = writeQueue.size();
592        }
593
594        bytesConsumedWr += size;
595        bytesWritten += burstSize;
596
597        // Starting address of next dram pkt (aligend to burstSize boundary)
598        addr = (addr | (burstSize - 1)) + 1;
599    }
600
601    // we do not wait for the writes to be send to the actual memory,
602    // but instead take responsibility for the consistency here and
603    // snoop the write queue for any upcoming reads
604    // @todo, if a pkt size is larger than burst size, we might need a
605    // different front end latency
606    accessAndRespond(pkt, frontendLatency);
607
608    // If your write buffer is starting to fill up, drain it!
609    if (writeQueue.size() > writeThreshold && !stopReads){
610        triggerWrites();
611    }
612}
613
614void
615SimpleDRAM::printParams() const
616{
617    // Sanity check print of important parameters
618    DPRINTF(DRAM,
619            "Memory controller %s physical organization\n"      \
620            "Number of devices per rank   %d\n"                 \
621            "Device bus width (in bits)   %d\n"                 \
622            "DRAM data bus burst          %d\n"                 \
623            "Row buffer size              %d\n"                 \
624            "Columns per row buffer       %d\n"                 \
625            "Rows    per bank             %d\n"                 \
626            "Banks   per rank             %d\n"                 \
627            "Ranks   per channel          %d\n"                 \
628            "Total mem capacity           %u\n",
629            name(), devicesPerRank, deviceBusWidth, burstSize, rowBufferSize,
630            columnsPerRowBuffer, rowsPerBank, banksPerRank, ranksPerChannel,
631            rowBufferSize * rowsPerBank * banksPerRank * ranksPerChannel);
632
633    string scheduler =  memSchedPolicy == Enums::fcfs ? "FCFS" : "FR-FCFS";
634    string address_mapping = addrMapping == Enums::RaBaChCo ? "RaBaChCo" :
635        (addrMapping == Enums::RaBaCoCh ? "RaBaCoCh" : "CoRaBaCh");
636    string page_policy = pageMgmt == Enums::open ? "OPEN" : "CLOSE";
637
638    DPRINTF(DRAM,
639            "Memory controller %s characteristics\n"    \
640            "Read buffer size     %d\n"                 \
641            "Write buffer size    %d\n"                 \
642            "Write buffer thresh  %d\n"                 \
643            "Scheduler            %s\n"                 \
644            "Address mapping      %s\n"                 \
645            "Page policy          %s\n",
646            name(), readBufferSize, writeBufferSize, writeThreshold,
647            scheduler, address_mapping, page_policy);
648
649    DPRINTF(DRAM, "Memory controller %s timing specs\n" \
650            "tRCD      %d ticks\n"                        \
651            "tCL       %d ticks\n"                        \
652            "tRP       %d ticks\n"                        \
653            "tBURST    %d ticks\n"                        \
654            "tRFC      %d ticks\n"                        \
655            "tREFI     %d ticks\n"                        \
656            "tWTR      %d ticks\n"                        \
657            "tXAW (%d) %d ticks\n",
658            name(), tRCD, tCL, tRP, tBURST, tRFC, tREFI, tWTR,
659            activationLimit, tXAW);
660}
661
662void
663SimpleDRAM::printQs() const {
664    DPRINTF(DRAM, "===READ QUEUE===\n\n");
665    for (auto i = readQueue.begin() ;  i != readQueue.end() ; ++i) {
666        DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
667    }
668    DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
669    for (auto i = respQueue.begin() ;  i != respQueue.end() ; ++i) {
670        DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
671    }
672    DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
673    for (auto i = writeQueue.begin() ;  i != writeQueue.end() ; ++i) {
674        DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
675    }
676}
677
678bool
679SimpleDRAM::recvTimingReq(PacketPtr pkt)
680{
681    /// @todo temporary hack to deal with memory corruption issues until
682    /// 4-phase transactions are complete
683    for (int x = 0; x < pendingDelete.size(); x++)
684        delete pendingDelete[x];
685    pendingDelete.clear();
686
687    // This is where we enter from the outside world
688    DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
689            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
690
691    // simply drop inhibited packets for now
692    if (pkt->memInhibitAsserted()) {
693        DPRINTF(DRAM,"Inhibited packet -- Dropping it now\n");
694        pendingDelete.push_back(pkt);
695        return true;
696    }
697
698   // Every million accesses, print the state of the queues
699   if (numReqs % 1000000 == 0)
700       printQs();
701
702    // Calc avg gap between requests
703    if (prevArrival != 0) {
704        totGap += curTick() - prevArrival;
705    }
706    prevArrival = curTick();
707
708
709    // Find out how many dram packets a pkt translates to
710    // If the burst size is equal or larger than the pkt size, then a pkt
711    // translates to only one dram packet. Otherwise, a pkt translates to
712    // multiple dram packets
713    unsigned size = pkt->getSize();
714    unsigned offset = pkt->getAddr() & (burstSize - 1);
715    unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
716
717    // check local buffers and do not accept if full
718    if (pkt->isRead()) {
719        assert(size != 0);
720        if (readQueueFull(dram_pkt_count)) {
721            DPRINTF(DRAM, "Read queue full, not accepting\n");
722            // remember that we have to retry this port
723            retryRdReq = true;
724            numRdRetry++;
725            return false;
726        } else {
727            addToReadQueue(pkt, dram_pkt_count);
728            readReqs++;
729            numReqs++;
730        }
731    } else if (pkt->isWrite()) {
732        assert(size != 0);
733        if (writeQueueFull(dram_pkt_count)) {
734            DPRINTF(DRAM, "Write queue full, not accepting\n");
735            // remember that we have to retry this port
736            retryWrReq = true;
737            numWrRetry++;
738            return false;
739        } else {
740            addToWriteQueue(pkt, dram_pkt_count);
741            writeReqs++;
742            numReqs++;
743        }
744    } else {
745        DPRINTF(DRAM,"Neither read nor write, ignore timing\n");
746        neitherReadNorWrite++;
747        accessAndRespond(pkt, 1);
748    }
749
750    retryRdReq = false;
751    retryWrReq = false;
752    return true;
753}
754
755void
756SimpleDRAM::processRespondEvent()
757{
758    DPRINTF(DRAM,
759            "processRespondEvent(): Some req has reached its readyTime\n");
760
761    DRAMPacket* dram_pkt = respQueue.front();
762
763    // Actually responds to the requestor
764    bytesConsumedRd += dram_pkt->size;
765    bytesRead += burstSize;
766    if (dram_pkt->burstHelper) {
767        // it is a split packet
768        dram_pkt->burstHelper->burstsServiced++;
769        if (dram_pkt->burstHelper->burstsServiced ==
770                                  dram_pkt->burstHelper->burstCount) {
771            // we have now serviced all children packets of a system packet
772            // so we can now respond to the requester
773            // @todo we probably want to have a different front end and back
774            // end latency for split packets
775            accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
776            delete dram_pkt->burstHelper;
777            dram_pkt->burstHelper = NULL;
778        }
779    } else {
780        // it is not a split packet
781        accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
782    }
783
784    delete respQueue.front();
785    respQueue.pop_front();
786
787    // Update stats
788    avgRdQLen = readQueue.size() + respQueue.size();
789
790    if (!respQueue.empty()) {
791        assert(respQueue.front()->readyTime >= curTick());
792        assert(!respondEvent.scheduled());
793        schedule(respondEvent, respQueue.front()->readyTime);
794    } else {
795        // if there is nothing left in any queue, signal a drain
796        if (writeQueue.empty() && readQueue.empty() &&
797            drainManager) {
798            drainManager->signalDrainDone();
799            drainManager = NULL;
800        }
801    }
802
803    // We have made a location in the queue available at this point,
804    // so if there is a read that was forced to wait, retry now
805    if (retryRdReq) {
806        retryRdReq = false;
807        port.sendRetry();
808    }
809}
810
811void
812SimpleDRAM::chooseNextWrite()
813{
814    // This method does the arbitration between write requests. The
815    // chosen packet is simply moved to the head of the write
816    // queue. The other methods know that this is the place to
817    // look. For example, with FCFS, this method does nothing
818    assert(!writeQueue.empty());
819
820    if (writeQueue.size() == 1) {
821        DPRINTF(DRAMWR, "Single write request, nothing to do\n");
822        return;
823    }
824
825    if (memSchedPolicy == Enums::fcfs) {
826        // Do nothing, since the correct request is already head
827    } else if (memSchedPolicy == Enums::frfcfs) {
828        auto i = writeQueue.begin();
829        bool foundRowHit = false;
830        while (!foundRowHit && i != writeQueue.end()) {
831            DRAMPacket* dram_pkt = *i;
832            const Bank& bank = dram_pkt->bank_ref;
833            if (bank.openRow == dram_pkt->row) { //FR part
834                DPRINTF(DRAMWR, "Write row buffer hit\n");
835                writeQueue.erase(i);
836                writeQueue.push_front(dram_pkt);
837                foundRowHit = true;
838            } else { //FCFS part
839                ;
840            }
841            ++i;
842        }
843    } else
844        panic("No scheduling policy chosen\n");
845
846    DPRINTF(DRAMWR, "Selected next write request\n");
847}
848
849bool
850SimpleDRAM::chooseNextRead()
851{
852    // This method does the arbitration between read requests. The
853    // chosen packet is simply moved to the head of the queue. The
854    // other methods know that this is the place to look. For example,
855    // with FCFS, this method does nothing
856    if (readQueue.empty()) {
857        DPRINTF(DRAM, "No read request to select\n");
858        return false;
859    }
860
861    // If there is only one request then there is nothing left to do
862    if (readQueue.size() == 1)
863        return true;
864
865    if (memSchedPolicy == Enums::fcfs) {
866        // Do nothing, since the request to serve is already the first
867        // one in the read queue
868    } else if (memSchedPolicy == Enums::frfcfs) {
869        for (auto i = readQueue.begin(); i != readQueue.end() ; ++i) {
870            DRAMPacket* dram_pkt = *i;
871            const Bank& bank = dram_pkt->bank_ref;
872            // Check if it is a row hit
873            if (bank.openRow == dram_pkt->row) { //FR part
874                DPRINTF(DRAM, "Row buffer hit\n");
875                readQueue.erase(i);
876                readQueue.push_front(dram_pkt);
877                break;
878            } else { //FCFS part
879                ;
880            }
881        }
882    } else
883        panic("No scheduling policy chosen!\n");
884
885    DPRINTF(DRAM, "Selected next read request\n");
886    return true;
887}
888
889void
890SimpleDRAM::accessAndRespond(PacketPtr pkt, Tick static_latency)
891{
892    DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
893
894    bool needsResponse = pkt->needsResponse();
895    // do the actual memory access which also turns the packet into a
896    // response
897    access(pkt);
898
899    // turn packet around to go back to requester if response expected
900    if (needsResponse) {
901        // access already turned the packet into a response
902        assert(pkt->isResponse());
903
904        // @todo someone should pay for this
905        pkt->busFirstWordDelay = pkt->busLastWordDelay = 0;
906
907        // queue the packet in the response queue to be sent out after
908        // the static latency has passed
909        port.schedTimingResp(pkt, curTick() + static_latency);
910    } else {
911        // @todo the packet is going to be deleted, and the DRAMPacket
912        // is still having a pointer to it
913        pendingDelete.push_back(pkt);
914    }
915
916    DPRINTF(DRAM, "Done\n");
917
918    return;
919}
920
921pair<Tick, Tick>
922SimpleDRAM::estimateLatency(DRAMPacket* dram_pkt, Tick inTime)
923{
924    // If a request reaches a bank at tick 'inTime', how much time
925    // *after* that does it take to finish the request, depending
926    // on bank status and page open policy. Note that this method
927    // considers only the time taken for the actual read or write
928    // to complete, NOT any additional time thereafter for tRAS or
929    // tRP.
930    Tick accLat = 0;
931    Tick bankLat = 0;
932    rowHitFlag = false;
933
934    const Bank& bank = dram_pkt->bank_ref;
935    if (pageMgmt == Enums::open) { // open-page policy
936        if (bank.openRow == dram_pkt->row) {
937            // When we have a row-buffer hit,
938            // we don't care about tRAS having expired or not,
939            // but do care about bank being free for access
940            rowHitFlag = true;
941
942            if (bank.freeAt < inTime) {
943               // CAS latency only
944               accLat += tCL;
945               bankLat += tCL;
946            } else {
947                accLat += 0;
948                bankLat += 0;
949            }
950
951        } else {
952            // Row-buffer miss, need to close existing row
953            // once tRAS has expired, then open the new one,
954            // then add cas latency.
955            Tick freeTime = std::max(bank.tRASDoneAt, bank.freeAt);
956
957            if (freeTime > inTime)
958               accLat += freeTime - inTime;
959
960            accLat += tRP + tRCD + tCL;
961            bankLat += tRP + tRCD + tCL;
962        }
963    } else if (pageMgmt == Enums::close) {
964        // With a close page policy, no notion of
965        // bank.tRASDoneAt
966        if (bank.freeAt > inTime)
967            accLat += bank.freeAt - inTime;
968
969        // page already closed, simply open the row, and
970        // add cas latency
971        accLat += tRCD + tCL;
972        bankLat += tRCD + tCL;
973    } else
974        panic("No page management policy chosen\n");
975
976    DPRINTF(DRAM, "Returning < %lld, %lld > from estimateLatency()\n",
977            bankLat, accLat);
978
979    return make_pair(bankLat, accLat);
980}
981
982void
983SimpleDRAM::processNextReqEvent()
984{
985    scheduleNextReq();
986}
987
988void
989SimpleDRAM::recordActivate(Tick act_tick)
990{
991    assert(actTicks.size() == activationLimit);
992
993    DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
994
995    // if the activation limit is disabled then we are done
996    if (actTicks.empty())
997        return;
998
999    // sanity check
1000    if (actTicks.back() && (act_tick - actTicks.back()) < tXAW) {
1001        // @todo For now, stick with a warning
1002        warn("Got %d activates in window %d (%d - %d) which is smaller "
1003             "than %d\n", activationLimit, act_tick - actTicks.back(),
1004             act_tick, actTicks.back(), tXAW);
1005    }
1006
1007    // shift the times used for the book keeping, the last element
1008    // (highest index) is the oldest one and hence the lowest value
1009    actTicks.pop_back();
1010
1011    // record an new activation (in the future)
1012    actTicks.push_front(act_tick);
1013
1014    // cannot activate more than X times in time window tXAW, push the
1015    // next one (the X + 1'st activate) to be tXAW away from the
1016    // oldest in our window of X
1017    if (actTicks.back() && (act_tick - actTicks.back()) < tXAW) {
1018        DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate no earlier "
1019                "than %d\n", activationLimit, actTicks.back() + tXAW);
1020        for(int i = 0; i < ranksPerChannel; i++)
1021            for(int j = 0; j < banksPerRank; j++)
1022                // next activate must not happen before end of window
1023                banks[i][j].freeAt = std::max(banks[i][j].freeAt,
1024                                              actTicks.back() + tXAW);
1025    }
1026}
1027
1028void
1029SimpleDRAM::doDRAMAccess(DRAMPacket* dram_pkt)
1030{
1031
1032    DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1033            dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1034
1035    // estimate the bank and access latency
1036    pair<Tick, Tick> lat = estimateLatency(dram_pkt, curTick());
1037    Tick bankLat = lat.first;
1038    Tick accessLat = lat.second;
1039
1040    // This request was woken up at this time based on a prior call
1041    // to estimateLatency(). However, between then and now, both the
1042    // accessLatency and/or busBusyUntil may have changed. We need
1043    // to correct for that.
1044
1045    Tick addDelay = (curTick() + accessLat < busBusyUntil) ?
1046        busBusyUntil - (curTick() + accessLat) : 0;
1047
1048    Bank& bank = dram_pkt->bank_ref;
1049
1050    // Update bank state
1051    if (pageMgmt == Enums::open) {
1052        bank.openRow = dram_pkt->row;
1053        bank.freeAt = curTick() + addDelay + accessLat;
1054        bank.bytesAccessed += burstSize;
1055
1056        // If you activated a new row do to this access, the next access
1057        // will have to respect tRAS for this bank. Assume tRAS ~= 3 * tRP.
1058        // Also need to account for t_XAW
1059        if (!rowHitFlag) {
1060            bank.tRASDoneAt = bank.freeAt + tRP;
1061            recordActivate(bank.freeAt - tCL - tRCD); //since this is open page,
1062                                                      //no tRP by default
1063            // sample the number of bytes accessed and reset it as
1064            // we are now closing this row
1065            bytesPerActivate.sample(bank.bytesAccessed);
1066            bank.bytesAccessed = 0;
1067        }
1068    } else if (pageMgmt == Enums::close) { // accounting for tRAS also
1069        // assuming that tRAS ~= 3 * tRP, and tRC ~= 4 * tRP, as is common
1070        // (refer Jacob/Ng/Wang and Micron datasheets)
1071        bank.freeAt = curTick() + addDelay + accessLat + tRP + tRP;
1072        recordActivate(bank.freeAt - tRP - tRP - tCL - tRCD); //essentially (freeAt - tRC)
1073        DPRINTF(DRAM,"doDRAMAccess::bank.freeAt is %lld\n",bank.freeAt);
1074        bytesPerActivate.sample(burstSize);
1075    } else
1076        panic("No page management policy chosen\n");
1077
1078    // Update request parameters
1079    dram_pkt->readyTime = curTick() + addDelay + accessLat + tBURST;
1080
1081
1082    DPRINTF(DRAM, "Req %lld: curtick is %lld accessLat is %d " \
1083                  "readytime is %lld busbusyuntil is %lld. " \
1084                  "Scheduling at readyTime\n", dram_pkt->addr,
1085                   curTick(), accessLat, dram_pkt->readyTime, busBusyUntil);
1086
1087    // Make sure requests are not overlapping on the databus
1088    assert (dram_pkt->readyTime - busBusyUntil >= tBURST);
1089
1090    // Update bus state
1091    busBusyUntil = dram_pkt->readyTime;
1092
1093    DPRINTF(DRAM,"Access time is %lld\n",
1094            dram_pkt->readyTime - dram_pkt->entryTime);
1095
1096    // Update stats
1097    totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1098    totBankLat += bankLat;
1099    totBusLat += tBURST;
1100    totQLat += dram_pkt->readyTime - dram_pkt->entryTime - bankLat - tBURST;
1101
1102    if (rowHitFlag)
1103        readRowHits++;
1104
1105    // At this point we're done dealing with the request
1106    // It will be moved to a separate response queue with a
1107    // correct readyTime, and eventually be sent back at that
1108    //time
1109    moveToRespQ();
1110
1111    // The absolute soonest you have to start thinking about the
1112    // next request is the longest access time that can occur before
1113    // busBusyUntil. Assuming you need to meet tRAS, then precharge,
1114    // open a new row, and access, it is ~4*tRCD.
1115
1116
1117    Tick newTime = (busBusyUntil > 4 * tRCD) ?
1118                   std::max(busBusyUntil - 4 * tRCD, curTick()) :
1119                   curTick();
1120
1121    if (!nextReqEvent.scheduled() && !stopReads){
1122        schedule(nextReqEvent, newTime);
1123    } else {
1124        if (newTime < nextReqEvent.when())
1125            reschedule(nextReqEvent, newTime);
1126    }
1127
1128
1129}
1130
1131void
1132SimpleDRAM::moveToRespQ()
1133{
1134    // Remove from read queue
1135    DRAMPacket* dram_pkt = readQueue.front();
1136    readQueue.pop_front();
1137
1138    // sanity check
1139    assert(dram_pkt->size <= burstSize);
1140
1141    // Insert into response queue sorted by readyTime
1142    // It will be sent back to the requestor at its
1143    // readyTime
1144    if (respQueue.empty()) {
1145        respQueue.push_front(dram_pkt);
1146        assert(!respondEvent.scheduled());
1147        assert(dram_pkt->readyTime >= curTick());
1148        schedule(respondEvent, dram_pkt->readyTime);
1149    } else {
1150        bool done = false;
1151        auto i = respQueue.begin();
1152        while (!done && i != respQueue.end()) {
1153            if ((*i)->readyTime > dram_pkt->readyTime) {
1154                respQueue.insert(i, dram_pkt);
1155                done = true;
1156            }
1157            ++i;
1158        }
1159
1160        if (!done)
1161            respQueue.push_back(dram_pkt);
1162
1163        assert(respondEvent.scheduled());
1164
1165        if (respQueue.front()->readyTime < respondEvent.when()) {
1166            assert(respQueue.front()->readyTime >= curTick());
1167            reschedule(respondEvent, respQueue.front()->readyTime);
1168        }
1169    }
1170}
1171
1172void
1173SimpleDRAM::scheduleNextReq()
1174{
1175    DPRINTF(DRAM, "Reached scheduleNextReq()\n");
1176
1177    // Figure out which read request goes next, and move it to the
1178    // front of the read queue
1179    if (!chooseNextRead()) {
1180        // In the case there is no read request to go next, see if we
1181        // are asked to drain, and if so trigger writes, this also
1182        // ensures that if we hit the write limit we will do this
1183        // multiple times until we are completely drained
1184        if (drainManager && !writeQueue.empty() && !writeEvent.scheduled())
1185            triggerWrites();
1186    } else {
1187        doDRAMAccess(readQueue.front());
1188    }
1189}
1190
1191Tick
1192SimpleDRAM::maxBankFreeAt() const
1193{
1194    Tick banksFree = 0;
1195
1196    for(int i = 0; i < ranksPerChannel; i++)
1197        for(int j = 0; j < banksPerRank; j++)
1198            banksFree = std::max(banks[i][j].freeAt, banksFree);
1199
1200    return banksFree;
1201}
1202
1203void
1204SimpleDRAM::processRefreshEvent()
1205{
1206    DPRINTF(DRAM, "Refreshing at tick %ld\n", curTick());
1207
1208    Tick banksFree = std::max(curTick(), maxBankFreeAt()) + tRFC;
1209
1210    for(int i = 0; i < ranksPerChannel; i++)
1211        for(int j = 0; j < banksPerRank; j++)
1212            banks[i][j].freeAt = banksFree;
1213
1214    schedule(refreshEvent, curTick() + tREFI);
1215}
1216
1217void
1218SimpleDRAM::regStats()
1219{
1220    using namespace Stats;
1221
1222    AbstractMemory::regStats();
1223
1224    readReqs
1225        .name(name() + ".readReqs")
1226        .desc("Total number of read requests accepted by DRAM controller");
1227
1228    writeReqs
1229        .name(name() + ".writeReqs")
1230        .desc("Total number of write requests accepted by DRAM controller");
1231
1232    readBursts
1233        .name(name() + ".readBursts")
1234        .desc("Total number of DRAM read bursts. "
1235              "Each DRAM read request translates to either one or multiple "
1236              "DRAM read bursts");
1237
1238    writeBursts
1239        .name(name() + ".writeBursts")
1240        .desc("Total number of DRAM write bursts. "
1241              "Each DRAM write request translates to either one or multiple "
1242              "DRAM write bursts");
1243
1244    servicedByWrQ
1245        .name(name() + ".servicedByWrQ")
1246        .desc("Number of DRAM read bursts serviced by write Q");
1247
1248    neitherReadNorWrite
1249        .name(name() + ".neitherReadNorWrite")
1250        .desc("Reqs where no action is needed");
1251
1252    perBankRdReqs
1253        .init(banksPerRank * ranksPerChannel)
1254        .name(name() + ".perBankRdReqs")
1255        .desc("Track reads on a per bank basis");
1256
1257    perBankWrReqs
1258        .init(banksPerRank * ranksPerChannel)
1259        .name(name() + ".perBankWrReqs")
1260        .desc("Track writes on a per bank basis");
1261
1262    avgRdQLen
1263        .name(name() + ".avgRdQLen")
1264        .desc("Average read queue length over time")
1265        .precision(2);
1266
1267    avgWrQLen
1268        .name(name() + ".avgWrQLen")
1269        .desc("Average write queue length over time")
1270        .precision(2);
1271
1272    totQLat
1273        .name(name() + ".totQLat")
1274        .desc("Total cycles spent in queuing delays");
1275
1276    totBankLat
1277        .name(name() + ".totBankLat")
1278        .desc("Total cycles spent in bank access");
1279
1280    totBusLat
1281        .name(name() + ".totBusLat")
1282        .desc("Total cycles spent in databus access");
1283
1284    totMemAccLat
1285        .name(name() + ".totMemAccLat")
1286        .desc("Sum of mem lat for all requests");
1287
1288    avgQLat
1289        .name(name() + ".avgQLat")
1290        .desc("Average queueing delay per request")
1291        .precision(2);
1292
1293    avgQLat = totQLat / (readBursts - servicedByWrQ);
1294
1295    avgBankLat
1296        .name(name() + ".avgBankLat")
1297        .desc("Average bank access latency per request")
1298        .precision(2);
1299
1300    avgBankLat = totBankLat / (readBursts - servicedByWrQ);
1301
1302    avgBusLat
1303        .name(name() + ".avgBusLat")
1304        .desc("Average bus latency per request")
1305        .precision(2);
1306
1307    avgBusLat = totBusLat / (readBursts - servicedByWrQ);
1308
1309    avgMemAccLat
1310        .name(name() + ".avgMemAccLat")
1311        .desc("Average memory access latency")
1312        .precision(2);
1313
1314    avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
1315
1316    numRdRetry
1317        .name(name() + ".numRdRetry")
1318        .desc("Number of times rd buffer was full causing retry");
1319
1320    numWrRetry
1321        .name(name() + ".numWrRetry")
1322        .desc("Number of times wr buffer was full causing retry");
1323
1324    readRowHits
1325        .name(name() + ".readRowHits")
1326        .desc("Number of row buffer hits during reads");
1327
1328    writeRowHits
1329        .name(name() + ".writeRowHits")
1330        .desc("Number of row buffer hits during writes");
1331
1332    readRowHitRate
1333        .name(name() + ".readRowHitRate")
1334        .desc("Row buffer hit rate for reads")
1335        .precision(2);
1336
1337    readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
1338
1339    writeRowHitRate
1340        .name(name() + ".writeRowHitRate")
1341        .desc("Row buffer hit rate for writes")
1342        .precision(2);
1343
1344    writeRowHitRate = (writeRowHits / writeBursts) * 100;
1345
1346    readPktSize
1347        .init(ceilLog2(burstSize) + 1)
1348        .name(name() + ".readPktSize")
1349        .desc("Categorize read packet sizes");
1350
1351     writePktSize
1352        .init(ceilLog2(burstSize) + 1)
1353        .name(name() + ".writePktSize")
1354        .desc("Categorize write packet sizes");
1355
1356     rdQLenPdf
1357        .init(readBufferSize)
1358        .name(name() + ".rdQLenPdf")
1359        .desc("What read queue length does an incoming req see");
1360
1361     wrQLenPdf
1362        .init(writeBufferSize)
1363        .name(name() + ".wrQLenPdf")
1364        .desc("What write queue length does an incoming req see");
1365
1366     bytesPerActivate
1367         .init(rowBufferSize)
1368         .name(name() + ".bytesPerActivate")
1369         .desc("Bytes accessed per row activation")
1370         .flags(nozero);
1371
1372    bytesRead
1373        .name(name() + ".bytesRead")
1374        .desc("Total number of bytes read from memory");
1375
1376    bytesWritten
1377        .name(name() + ".bytesWritten")
1378        .desc("Total number of bytes written to memory");
1379
1380    bytesConsumedRd
1381        .name(name() + ".bytesConsumedRd")
1382        .desc("bytesRead derated as per pkt->getSize()");
1383
1384    bytesConsumedWr
1385        .name(name() + ".bytesConsumedWr")
1386        .desc("bytesWritten derated as per pkt->getSize()");
1387
1388    avgRdBW
1389        .name(name() + ".avgRdBW")
1390        .desc("Average achieved read bandwidth in MB/s")
1391        .precision(2);
1392
1393    avgRdBW = (bytesRead / 1000000) / simSeconds;
1394
1395    avgWrBW
1396        .name(name() + ".avgWrBW")
1397        .desc("Average achieved write bandwidth in MB/s")
1398        .precision(2);
1399
1400    avgWrBW = (bytesWritten / 1000000) / simSeconds;
1401
1402    avgConsumedRdBW
1403        .name(name() + ".avgConsumedRdBW")
1404        .desc("Average consumed read bandwidth in MB/s")
1405        .precision(2);
1406
1407    avgConsumedRdBW = (bytesConsumedRd / 1000000) / simSeconds;
1408
1409    avgConsumedWrBW
1410        .name(name() + ".avgConsumedWrBW")
1411        .desc("Average consumed write bandwidth in MB/s")
1412        .precision(2);
1413
1414    avgConsumedWrBW = (bytesConsumedWr / 1000000) / simSeconds;
1415
1416    peakBW
1417        .name(name() + ".peakBW")
1418        .desc("Theoretical peak bandwidth in MB/s")
1419        .precision(2);
1420
1421    peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
1422
1423    busUtil
1424        .name(name() + ".busUtil")
1425        .desc("Data bus utilization in percentage")
1426        .precision(2);
1427
1428    busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
1429
1430    totGap
1431        .name(name() + ".totGap")
1432        .desc("Total gap between requests");
1433
1434    avgGap
1435        .name(name() + ".avgGap")
1436        .desc("Average gap between requests")
1437        .precision(2);
1438
1439    avgGap = totGap / (readReqs + writeReqs);
1440}
1441
1442void
1443SimpleDRAM::recvFunctional(PacketPtr pkt)
1444{
1445    // rely on the abstract memory
1446    functionalAccess(pkt);
1447}
1448
1449BaseSlavePort&
1450SimpleDRAM::getSlavePort(const string &if_name, PortID idx)
1451{
1452    if (if_name != "port") {
1453        return MemObject::getSlavePort(if_name, idx);
1454    } else {
1455        return port;
1456    }
1457}
1458
1459unsigned int
1460SimpleDRAM::drain(DrainManager *dm)
1461{
1462    unsigned int count = port.drain(dm);
1463
1464    // if there is anything in any of our internal queues, keep track
1465    // of that as well
1466    if (!(writeQueue.empty() && readQueue.empty() &&
1467          respQueue.empty())) {
1468        DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
1469                " resp: %d\n", writeQueue.size(), readQueue.size(),
1470                respQueue.size());
1471        ++count;
1472        drainManager = dm;
1473        // the only part that is not drained automatically over time
1474        // is the write queue, thus trigger writes if there are any
1475        // waiting and no reads waiting, otherwise wait until the
1476        // reads are done
1477        if (readQueue.empty() && !writeQueue.empty() &&
1478            !writeEvent.scheduled())
1479            triggerWrites();
1480    }
1481
1482    if (count)
1483        setDrainState(Drainable::Draining);
1484    else
1485        setDrainState(Drainable::Drained);
1486    return count;
1487}
1488
1489SimpleDRAM::MemoryPort::MemoryPort(const std::string& name, SimpleDRAM& _memory)
1490    : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
1491      memory(_memory)
1492{ }
1493
1494AddrRangeList
1495SimpleDRAM::MemoryPort::getAddrRanges() const
1496{
1497    AddrRangeList ranges;
1498    ranges.push_back(memory.getAddrRange());
1499    return ranges;
1500}
1501
1502void
1503SimpleDRAM::MemoryPort::recvFunctional(PacketPtr pkt)
1504{
1505    pkt->pushLabel(memory.name());
1506
1507    if (!queue.checkFunctional(pkt)) {
1508        // Default implementation of SimpleTimingPort::recvFunctional()
1509        // calls recvAtomic() and throws away the latency; we can save a
1510        // little here by just not calculating the latency.
1511        memory.recvFunctional(pkt);
1512    }
1513
1514    pkt->popLabel();
1515}
1516
1517Tick
1518SimpleDRAM::MemoryPort::recvAtomic(PacketPtr pkt)
1519{
1520    return memory.recvAtomic(pkt);
1521}
1522
1523bool
1524SimpleDRAM::MemoryPort::recvTimingReq(PacketPtr pkt)
1525{
1526    // pass it to the memory controller
1527    return memory.recvTimingReq(pkt);
1528}
1529
1530SimpleDRAM*
1531SimpleDRAMParams::create()
1532{
1533    return new SimpleDRAM(this);
1534}
1535