dram_ctrl.cc revision 10146
19243SN/A/*
29832SN/A * Copyright (c) 2010-2013 ARM Limited
39243SN/A * All rights reserved
49243SN/A *
59243SN/A * The license below extends only to copyright in the software and shall
69243SN/A * not be construed as granting a license to any other intellectual
79243SN/A * property including but not limited to intellectual property relating
89243SN/A * to a hardware implementation of the functionality of the software
99243SN/A * licensed hereunder.  You may use the software subject to the license
109243SN/A * terms below provided that you ensure that this notice is replicated
119243SN/A * unmodified and in its entirety in all distributions of the software,
129243SN/A * modified or unmodified, in source code or in binary form.
139243SN/A *
149831SN/A * Copyright (c) 2013 Amin Farmahini-Farahani
159831SN/A * All rights reserved.
169831SN/A *
179243SN/A * Redistribution and use in source and binary forms, with or without
189243SN/A * modification, are permitted provided that the following conditions are
199243SN/A * met: redistributions of source code must retain the above copyright
209243SN/A * notice, this list of conditions and the following disclaimer;
219243SN/A * redistributions in binary form must reproduce the above copyright
229243SN/A * notice, this list of conditions and the following disclaimer in the
239243SN/A * documentation and/or other materials provided with the distribution;
249243SN/A * neither the name of the copyright holders nor the names of its
259243SN/A * contributors may be used to endorse or promote products derived from
269243SN/A * this software without specific prior written permission.
279243SN/A *
289243SN/A * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
299243SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
309243SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
319243SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
329243SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
339243SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
349243SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
359243SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
369243SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
379243SN/A * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
389243SN/A * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
399243SN/A *
409243SN/A * Authors: Andreas Hansson
419243SN/A *          Ani Udipi
429967SN/A *          Neha Agarwal
439243SN/A */
449243SN/A
4510146Sandreas.hansson@arm.com#include "base/bitfield.hh"
469356SN/A#include "base/trace.hh"
4710146Sandreas.hansson@arm.com#include "debug/DRAM.hh"
489352SN/A#include "debug/Drain.hh"
4910146Sandreas.hansson@arm.com#include "mem/dram_ctrl.hh"
509814SN/A#include "sim/system.hh"
519243SN/A
529243SN/Ausing namespace std;
539243SN/A
5410146Sandreas.hansson@arm.comDRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
559243SN/A    AbstractMemory(p),
569243SN/A    port(name() + ".port", *this),
579243SN/A    retryRdReq(false), retryWrReq(false),
589969SN/A    rowHitFlag(false), stopReads(false),
599243SN/A    writeEvent(this), respondEvent(this),
609342SN/A    refreshEvent(this), nextReqEvent(this), drainManager(NULL),
619831SN/A    deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
629831SN/A    deviceRowBufferSize(p->device_rowbuffer_size),
639831SN/A    devicesPerRank(p->devices_per_rank),
649831SN/A    burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8),
659831SN/A    rowBufferSize(devicesPerRank * deviceRowBufferSize),
6610140SN/A    columnsPerRowBuffer(rowBufferSize / burstSize),
679243SN/A    ranksPerChannel(p->ranks_per_channel),
689566SN/A    banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0),
699243SN/A    readBufferSize(p->read_buffer_size),
709243SN/A    writeBufferSize(p->write_buffer_size),
7110140SN/A    writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0),
7210140SN/A    writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0),
7310140SN/A    minWritesPerSwitch(p->min_writes_per_switch), writesThisTime(0),
749243SN/A    tWTR(p->tWTR), tBURST(p->tBURST),
759963SN/A    tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
769971SN/A    tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
779488SN/A    tXAW(p->tXAW), activationLimit(p->activation_limit),
789243SN/A    memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
799243SN/A    pageMgmt(p->page_policy),
8010141SN/A    maxAccessesPerRow(p->max_accesses_per_row),
819726SN/A    frontendLatency(p->static_frontend_latency),
829726SN/A    backendLatency(p->static_backend_latency),
8310143SN/A    busBusyUntil(0),  prevArrival(0),
8410140SN/A    newTime(0), startTickPrechargeAll(0), numBanksActive(0)
859243SN/A{
869243SN/A    // create the bank states based on the dimensions of the ranks and
879243SN/A    // banks
889243SN/A    banks.resize(ranksPerChannel);
899969SN/A    actTicks.resize(ranksPerChannel);
909243SN/A    for (size_t c = 0; c < ranksPerChannel; ++c) {
919243SN/A        banks[c].resize(banksPerRank);
929969SN/A        actTicks[c].resize(activationLimit, 0);
939243SN/A    }
949243SN/A
9510140SN/A    // perform a basic check of the write thresholds
9610140SN/A    if (p->write_low_thresh_perc >= p->write_high_thresh_perc)
9710140SN/A        fatal("Write buffer low threshold %d must be smaller than the "
9810140SN/A              "high threshold %d\n", p->write_low_thresh_perc,
9910140SN/A              p->write_high_thresh_perc);
1009243SN/A
1019243SN/A    // determine the rows per bank by looking at the total capacity
1029567SN/A    uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
1039243SN/A
1049243SN/A    DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
1059243SN/A            AbstractMemory::size());
1069831SN/A
1079831SN/A    DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
1089831SN/A            rowBufferSize, columnsPerRowBuffer);
1099831SN/A
1109831SN/A    rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
1119243SN/A
1129566SN/A    if (range.interleaved()) {
1139566SN/A        if (channels != range.stripes())
11410143SN/A            fatal("%s has %d interleaved address stripes but %d channel(s)\n",
1159566SN/A                  name(), range.stripes(), channels);
1169566SN/A
11710136SN/A        if (addrMapping == Enums::RoRaBaChCo) {
1189831SN/A            if (rowBufferSize != range.granularity()) {
11910143SN/A                fatal("Interleaving of %s doesn't match RoRaBaChCo "
12010136SN/A                      "address map\n", name());
1219566SN/A            }
12210136SN/A        } else if (addrMapping == Enums::RoRaBaCoCh) {
12310136SN/A            if (system()->cacheLineSize() != range.granularity()) {
12410143SN/A                fatal("Interleaving of %s doesn't match RoRaBaCoCh "
12510136SN/A                      "address map\n", name());
1269669SN/A            }
12710136SN/A        } else if (addrMapping == Enums::RoCoRaBaCh) {
12810136SN/A            if (system()->cacheLineSize() != range.granularity())
12910143SN/A                fatal("Interleaving of %s doesn't match RoCoRaBaCh "
13010136SN/A                      "address map\n", name());
1319566SN/A        }
1329566SN/A    }
1339243SN/A}
1349243SN/A
1359243SN/Avoid
13610146Sandreas.hansson@arm.comDRAMCtrl::init()
13710140SN/A{
13810140SN/A    if (!port.isConnected()) {
13910146Sandreas.hansson@arm.com        fatal("DRAMCtrl %s is unconnected!\n", name());
14010140SN/A    } else {
14110140SN/A        port.sendRangeChange();
14210140SN/A    }
14310140SN/A}
14410140SN/A
14510140SN/Avoid
14610146Sandreas.hansson@arm.comDRAMCtrl::startup()
1479243SN/A{
14810143SN/A    // update the start tick for the precharge accounting to the
14910143SN/A    // current tick
15010143SN/A    startTickPrechargeAll = curTick();
15110143SN/A
1529243SN/A    // print the configuration of the controller
1539243SN/A    printParams();
1549243SN/A
1559243SN/A    // kick off the refresh
1569567SN/A    schedule(refreshEvent, curTick() + tREFI);
1579243SN/A}
1589243SN/A
1599243SN/ATick
16010146Sandreas.hansson@arm.comDRAMCtrl::recvAtomic(PacketPtr pkt)
1619243SN/A{
1629243SN/A    DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
1639243SN/A
1649243SN/A    // do the actual memory access and turn the packet into a response
1659243SN/A    access(pkt);
1669243SN/A
1679243SN/A    Tick latency = 0;
1689243SN/A    if (!pkt->memInhibitAsserted() && pkt->hasData()) {
1699243SN/A        // this value is not supposed to be accurate, just enough to
1709243SN/A        // keep things going, mimic a closed page
1719243SN/A        latency = tRP + tRCD + tCL;
1729243SN/A    }
1739243SN/A    return latency;
1749243SN/A}
1759243SN/A
1769243SN/Abool
17710146Sandreas.hansson@arm.comDRAMCtrl::readQueueFull(unsigned int neededEntries) const
1789243SN/A{
1799831SN/A    DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
1809831SN/A            readBufferSize, readQueue.size() + respQueue.size(),
1819831SN/A            neededEntries);
1829243SN/A
1839831SN/A    return
1849831SN/A        (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
1859243SN/A}
1869243SN/A
1879243SN/Abool
18810146Sandreas.hansson@arm.comDRAMCtrl::writeQueueFull(unsigned int neededEntries) const
1899243SN/A{
1909831SN/A    DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
1919831SN/A            writeBufferSize, writeQueue.size(), neededEntries);
1929831SN/A    return (writeQueue.size() + neededEntries) > writeBufferSize;
1939243SN/A}
1949243SN/A
19510146Sandreas.hansson@arm.comDRAMCtrl::DRAMPacket*
19610146Sandreas.hansson@arm.comDRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size,
19710143SN/A                       bool isRead)
1989243SN/A{
1999669SN/A    // decode the address based on the address mapping scheme, with
20010136SN/A    // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
20110136SN/A    // channel, respectively
2029243SN/A    uint8_t rank;
2039967SN/A    uint8_t bank;
2049243SN/A    uint16_t row;
2059243SN/A
2069243SN/A    // truncate the address to the access granularity
2079831SN/A    Addr addr = dramPktAddr / burstSize;
2089243SN/A
2099491SN/A    // we have removed the lowest order address bits that denote the
2109831SN/A    // position within the column
21110136SN/A    if (addrMapping == Enums::RoRaBaChCo) {
2129491SN/A        // the lowest order bits denote the column to ensure that
2139491SN/A        // sequential cache lines occupy the same row
2149831SN/A        addr = addr / columnsPerRowBuffer;
2159243SN/A
2169669SN/A        // take out the channel part of the address
2179566SN/A        addr = addr / channels;
2189566SN/A
2199669SN/A        // after the channel bits, get the bank bits to interleave
2209669SN/A        // over the banks
2219669SN/A        bank = addr % banksPerRank;
2229669SN/A        addr = addr / banksPerRank;
2239669SN/A
2249669SN/A        // after the bank, we get the rank bits which thus interleaves
2259669SN/A        // over the ranks
2269669SN/A        rank = addr % ranksPerChannel;
2279669SN/A        addr = addr / ranksPerChannel;
2289669SN/A
2299669SN/A        // lastly, get the row bits
2309669SN/A        row = addr % rowsPerBank;
2319669SN/A        addr = addr / rowsPerBank;
23210136SN/A    } else if (addrMapping == Enums::RoRaBaCoCh) {
2339669SN/A        // take out the channel part of the address
2349669SN/A        addr = addr / channels;
2359669SN/A
2369669SN/A        // next, the column
2379831SN/A        addr = addr / columnsPerRowBuffer;
2389669SN/A
2399669SN/A        // after the column bits, we get the bank bits to interleave
2409491SN/A        // over the banks
2419243SN/A        bank = addr % banksPerRank;
2429243SN/A        addr = addr / banksPerRank;
2439243SN/A
2449491SN/A        // after the bank, we get the rank bits which thus interleaves
2459491SN/A        // over the ranks
2469243SN/A        rank = addr % ranksPerChannel;
2479243SN/A        addr = addr / ranksPerChannel;
2489243SN/A
2499491SN/A        // lastly, get the row bits
2509243SN/A        row = addr % rowsPerBank;
2519243SN/A        addr = addr / rowsPerBank;
25210136SN/A    } else if (addrMapping == Enums::RoCoRaBaCh) {
2539491SN/A        // optimise for closed page mode and utilise maximum
2549491SN/A        // parallelism of the DRAM (at the cost of power)
2559491SN/A
2569566SN/A        // take out the channel part of the address, not that this has
2579566SN/A        // to match with how accesses are interleaved between the
2589566SN/A        // controllers in the address mapping
2599566SN/A        addr = addr / channels;
2609566SN/A
2619491SN/A        // start with the bank bits, as this provides the maximum
2629491SN/A        // opportunity for parallelism between requests
2639243SN/A        bank = addr % banksPerRank;
2649243SN/A        addr = addr / banksPerRank;
2659243SN/A
2669491SN/A        // next get the rank bits
2679243SN/A        rank = addr % ranksPerChannel;
2689243SN/A        addr = addr / ranksPerChannel;
2699243SN/A
2709491SN/A        // next the column bits which we do not need to keep track of
2719491SN/A        // and simply skip past
2729831SN/A        addr = addr / columnsPerRowBuffer;
2739243SN/A
2749491SN/A        // lastly, get the row bits
2759243SN/A        row = addr % rowsPerBank;
2769243SN/A        addr = addr / rowsPerBank;
2779243SN/A    } else
2789243SN/A        panic("Unknown address mapping policy chosen!");
2799243SN/A
2809243SN/A    assert(rank < ranksPerChannel);
2819243SN/A    assert(bank < banksPerRank);
2829243SN/A    assert(row < rowsPerBank);
2839243SN/A
2849243SN/A    DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
2859831SN/A            dramPktAddr, rank, bank, row);
2869243SN/A
2879243SN/A    // create the corresponding DRAM packet with the entry time and
2889567SN/A    // ready time set to the current tick, the latter will be updated
2899567SN/A    // later
2909967SN/A    uint16_t bank_id = banksPerRank * rank + bank;
2919967SN/A    return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
2929967SN/A                          size, banks[rank][bank]);
2939243SN/A}
2949243SN/A
2959243SN/Avoid
29610146Sandreas.hansson@arm.comDRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
2979243SN/A{
2989243SN/A    // only add to the read queue here. whenever the request is
2999243SN/A    // eventually done, set the readyTime, and call schedule()
3009243SN/A    assert(!pkt->isWrite());
3019243SN/A
3029831SN/A    assert(pktCount != 0);
3039831SN/A
3049831SN/A    // if the request size is larger than burst size, the pkt is split into
3059831SN/A    // multiple DRAM packets
3069831SN/A    // Note if the pkt starting address is not aligened to burst size, the
3079831SN/A    // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
3089831SN/A    // are aligned to burst size boundaries. This is to ensure we accurately
3099831SN/A    // check read packets against packets in write queue.
3109243SN/A    Addr addr = pkt->getAddr();
3119831SN/A    unsigned pktsServicedByWrQ = 0;
3129831SN/A    BurstHelper* burst_helper = NULL;
3139831SN/A    for (int cnt = 0; cnt < pktCount; ++cnt) {
3149831SN/A        unsigned size = std::min((addr | (burstSize - 1)) + 1,
3159831SN/A                        pkt->getAddr() + pkt->getSize()) - addr;
3169831SN/A        readPktSize[ceilLog2(size)]++;
3179831SN/A        readBursts++;
3189243SN/A
3199831SN/A        // First check write buffer to see if the data is already at
3209831SN/A        // the controller
3219831SN/A        bool foundInWrQ = false;
3229833SN/A        for (auto i = writeQueue.begin(); i != writeQueue.end(); ++i) {
3239832SN/A            // check if the read is subsumed in the write entry we are
3249832SN/A            // looking at
3259832SN/A            if ((*i)->addr <= addr &&
3269832SN/A                (addr + size) <= ((*i)->addr + (*i)->size)) {
3279831SN/A                foundInWrQ = true;
3289831SN/A                servicedByWrQ++;
3299831SN/A                pktsServicedByWrQ++;
3309831SN/A                DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
3319831SN/A                        "write queue\n", addr, size);
3329975SN/A                bytesReadWrQ += burstSize;
3339831SN/A                break;
3349831SN/A            }
3359243SN/A        }
3369831SN/A
3379831SN/A        // If not found in the write q, make a DRAM packet and
3389831SN/A        // push it onto the read queue
3399831SN/A        if (!foundInWrQ) {
3409831SN/A
3419831SN/A            // Make the burst helper for split packets
3429831SN/A            if (pktCount > 1 && burst_helper == NULL) {
3439831SN/A                DPRINTF(DRAM, "Read to addr %lld translates to %d "
3449831SN/A                        "dram requests\n", pkt->getAddr(), pktCount);
3459831SN/A                burst_helper = new BurstHelper(pktCount);
3469831SN/A            }
3479831SN/A
3489966SN/A            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
3499831SN/A            dram_pkt->burstHelper = burst_helper;
3509831SN/A
3519831SN/A            assert(!readQueueFull(1));
3529831SN/A            rdQLenPdf[readQueue.size() + respQueue.size()]++;
3539831SN/A
3549831SN/A            DPRINTF(DRAM, "Adding to read queue\n");
3559831SN/A
3569831SN/A            readQueue.push_back(dram_pkt);
3579831SN/A
3589831SN/A            // Update stats
3599831SN/A            avgRdQLen = readQueue.size() + respQueue.size();
3609831SN/A        }
3619831SN/A
3629831SN/A        // Starting address of next dram pkt (aligend to burstSize boundary)
3639831SN/A        addr = (addr | (burstSize - 1)) + 1;
3649243SN/A    }
3659243SN/A
3669831SN/A    // If all packets are serviced by write queue, we send the repsonse back
3679831SN/A    if (pktsServicedByWrQ == pktCount) {
3689831SN/A        accessAndRespond(pkt, frontendLatency);
3699831SN/A        return;
3709831SN/A    }
3719243SN/A
3729831SN/A    // Update how many split packets are serviced by write queue
3739831SN/A    if (burst_helper != NULL)
3749831SN/A        burst_helper->burstsServiced = pktsServicedByWrQ;
3759243SN/A
3769567SN/A    // If we are not already scheduled to get the read request out of
3779567SN/A    // the queue, do so now
3789243SN/A    if (!nextReqEvent.scheduled() && !stopReads) {
3799567SN/A        DPRINTF(DRAM, "Request scheduled immediately\n");
3809567SN/A        schedule(nextReqEvent, curTick());
3819243SN/A    }
3829243SN/A}
3839243SN/A
3849243SN/Avoid
38510146Sandreas.hansson@arm.comDRAMCtrl::processWriteEvent()
3869243SN/A{
3879567SN/A    assert(!writeQueue.empty());
3889243SN/A
3899972SN/A    DPRINTF(DRAM, "Beginning DRAM Write\n");
3909243SN/A    Tick temp1 M5_VAR_USED = std::max(curTick(), busBusyUntil);
3919243SN/A    Tick temp2 M5_VAR_USED = std::max(curTick(), maxBankFreeAt());
3929243SN/A
3939972SN/A    chooseNextWrite();
3949972SN/A    DRAMPacket* dram_pkt = writeQueue.front();
3959972SN/A    // sanity check
3969972SN/A    assert(dram_pkt->size <= burstSize);
3979972SN/A    doDRAMAccess(dram_pkt);
3989243SN/A
3999972SN/A    writeQueue.pop_front();
4009972SN/A    delete dram_pkt;
4019243SN/A
40210140SN/A    ++writesThisTime;
40310140SN/A
40410140SN/A    DPRINTF(DRAM, "Writing, bus busy for %lld ticks, banks busy "
40510140SN/A            "for %lld ticks\n", busBusyUntil - temp1, maxBankFreeAt() - temp2);
4069243SN/A
40710140SN/A    // If we emptied the write queue, or got below the threshold and
40810140SN/A    // are not draining, or we have reads waiting and have done enough
40910140SN/A    // writes, then switch to reads. The retry above could already
41010140SN/A    // have caused it to be scheduled, so first check
41110140SN/A    if (writeQueue.empty() ||
41210140SN/A        (writeQueue.size() < writeLowThreshold && !drainManager) ||
41310140SN/A        (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) {
4149972SN/A        // turn the bus back around for reads again
4159972SN/A        busBusyUntil += tWTR;
4169972SN/A        stopReads = false;
41710140SN/A        writesThisTime = 0;
4189972SN/A
4199972SN/A        if (!nextReqEvent.scheduled())
4209972SN/A            schedule(nextReqEvent, busBusyUntil);
4219972SN/A    } else {
4229972SN/A        assert(!writeEvent.scheduled());
4239972SN/A        DPRINTF(DRAM, "Next write scheduled at %lld\n", newTime);
4249972SN/A        schedule(writeEvent, newTime);
4259972SN/A    }
4269243SN/A
4279243SN/A    if (retryWrReq) {
4289243SN/A        retryWrReq = false;
4299243SN/A        port.sendRetry();
4309243SN/A    }
4319243SN/A
4329243SN/A    // if there is nothing left in any queue, signal a drain
4339567SN/A    if (writeQueue.empty() && readQueue.empty() &&
4349567SN/A        respQueue.empty () && drainManager) {
4359342SN/A        drainManager->signalDrainDone();
4369342SN/A        drainManager = NULL;
4379243SN/A    }
4389243SN/A}
4399243SN/A
4409966SN/A
4419243SN/Avoid
44210146Sandreas.hansson@arm.comDRAMCtrl::triggerWrites()
4439243SN/A{
4449243SN/A    DPRINTF(DRAM, "Writes triggered at %lld\n", curTick());
4459243SN/A    // Flag variable to stop any more read scheduling
4469243SN/A    stopReads = true;
4479243SN/A
44810143SN/A    Tick write_start_time = std::max(busBusyUntil, curTick()) + tWTR;
4499243SN/A
45010143SN/A    DPRINTF(DRAM, "Writes scheduled at %lld\n", write_start_time);
4519243SN/A
45210143SN/A    assert(write_start_time >= curTick());
4539243SN/A    assert(!writeEvent.scheduled());
45410143SN/A    schedule(writeEvent, write_start_time);
4559243SN/A}
4569243SN/A
4579243SN/Avoid
45810146Sandreas.hansson@arm.comDRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
4599243SN/A{
4609243SN/A    // only add to the write queue here. whenever the request is
4619243SN/A    // eventually done, set the readyTime, and call schedule()
4629243SN/A    assert(pkt->isWrite());
4639243SN/A
4649831SN/A    // if the request size is larger than burst size, the pkt is split into
4659831SN/A    // multiple DRAM packets
4669831SN/A    Addr addr = pkt->getAddr();
4679831SN/A    for (int cnt = 0; cnt < pktCount; ++cnt) {
4689831SN/A        unsigned size = std::min((addr | (burstSize - 1)) + 1,
4699831SN/A                        pkt->getAddr() + pkt->getSize()) - addr;
4709831SN/A        writePktSize[ceilLog2(size)]++;
4719831SN/A        writeBursts++;
4729243SN/A
4739832SN/A        // see if we can merge with an existing item in the write
4749838SN/A        // queue and keep track of whether we have merged or not so we
4759838SN/A        // can stop at that point and also avoid enqueueing a new
4769838SN/A        // request
4779832SN/A        bool merged = false;
4789832SN/A        auto w = writeQueue.begin();
4799243SN/A
4809832SN/A        while(!merged && w != writeQueue.end()) {
4819832SN/A            // either of the two could be first, if they are the same
4829832SN/A            // it does not matter which way we go
4839832SN/A            if ((*w)->addr >= addr) {
4849838SN/A                // the existing one starts after the new one, figure
4859838SN/A                // out where the new one ends with respect to the
4869838SN/A                // existing one
4879832SN/A                if ((addr + size) >= ((*w)->addr + (*w)->size)) {
4889832SN/A                    // check if the existing one is completely
4899832SN/A                    // subsumed in the new one
4909832SN/A                    DPRINTF(DRAM, "Merging write covering existing burst\n");
4919832SN/A                    merged = true;
4929832SN/A                    // update both the address and the size
4939832SN/A                    (*w)->addr = addr;
4949832SN/A                    (*w)->size = size;
4959832SN/A                } else if ((addr + size) >= (*w)->addr &&
4969832SN/A                           ((*w)->addr + (*w)->size - addr) <= burstSize) {
4979832SN/A                    // the new one is just before or partially
4989832SN/A                    // overlapping with the existing one, and together
4999832SN/A                    // they fit within a burst
5009832SN/A                    DPRINTF(DRAM, "Merging write before existing burst\n");
5019832SN/A                    merged = true;
5029832SN/A                    // the existing queue item needs to be adjusted with
5039832SN/A                    // respect to both address and size
50410047SN/A                    (*w)->size = (*w)->addr + (*w)->size - addr;
5059832SN/A                    (*w)->addr = addr;
5069832SN/A                }
5079832SN/A            } else {
5089838SN/A                // the new one starts after the current one, figure
5099838SN/A                // out where the existing one ends with respect to the
5109838SN/A                // new one
5119832SN/A                if (((*w)->addr + (*w)->size) >= (addr + size)) {
5129832SN/A                    // check if the new one is completely subsumed in the
5139832SN/A                    // existing one
5149832SN/A                    DPRINTF(DRAM, "Merging write into existing burst\n");
5159832SN/A                    merged = true;
5169832SN/A                    // no adjustments necessary
5179832SN/A                } else if (((*w)->addr + (*w)->size) >= addr &&
5189832SN/A                           (addr + size - (*w)->addr) <= burstSize) {
5199832SN/A                    // the existing one is just before or partially
5209832SN/A                    // overlapping with the new one, and together
5219832SN/A                    // they fit within a burst
5229832SN/A                    DPRINTF(DRAM, "Merging write after existing burst\n");
5239832SN/A                    merged = true;
5249832SN/A                    // the address is right, and only the size has
5259832SN/A                    // to be adjusted
5269832SN/A                    (*w)->size = addr + size - (*w)->addr;
5279832SN/A                }
5289832SN/A            }
5299832SN/A            ++w;
5309832SN/A        }
5319243SN/A
5329832SN/A        // if the item was not merged we need to create a new write
5339832SN/A        // and enqueue it
5349832SN/A        if (!merged) {
5359966SN/A            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
5369243SN/A
5379832SN/A            assert(writeQueue.size() < writeBufferSize);
5389832SN/A            wrQLenPdf[writeQueue.size()]++;
5399243SN/A
5409832SN/A            DPRINTF(DRAM, "Adding to write queue\n");
5419831SN/A
5429832SN/A            writeQueue.push_back(dram_pkt);
5439831SN/A
5449832SN/A            // Update stats
5459832SN/A            avgWrQLen = writeQueue.size();
5469977SN/A        } else {
5479977SN/A            // keep track of the fact that this burst effectively
5489977SN/A            // disappeared as it was merged with an existing one
5499977SN/A            mergedWrBursts++;
5509832SN/A        }
5519832SN/A
5529831SN/A        // Starting address of next dram pkt (aligend to burstSize boundary)
5539831SN/A        addr = (addr | (burstSize - 1)) + 1;
5549831SN/A    }
5559243SN/A
5569243SN/A    // we do not wait for the writes to be send to the actual memory,
5579243SN/A    // but instead take responsibility for the consistency here and
5589243SN/A    // snoop the write queue for any upcoming reads
5599831SN/A    // @todo, if a pkt size is larger than burst size, we might need a
5609831SN/A    // different front end latency
5619726SN/A    accessAndRespond(pkt, frontendLatency);
5629243SN/A
5639243SN/A    // If your write buffer is starting to fill up, drain it!
5649972SN/A    if (writeQueue.size() >= writeHighThreshold && !stopReads){
5659243SN/A        triggerWrites();
5669243SN/A    }
5679243SN/A}
5689243SN/A
5699243SN/Avoid
57010146Sandreas.hansson@arm.comDRAMCtrl::printParams() const
5719243SN/A{
5729243SN/A    // Sanity check print of important parameters
5739243SN/A    DPRINTF(DRAM,
5749243SN/A            "Memory controller %s physical organization\n"      \
5759831SN/A            "Number of devices per rank   %d\n"                 \
5769831SN/A            "Device bus width (in bits)   %d\n"                 \
57710143SN/A            "DRAM data bus burst (bytes)  %d\n"                 \
57810143SN/A            "Row buffer size (bytes)      %d\n"                 \
5799831SN/A            "Columns per row buffer       %d\n"                 \
5809831SN/A            "Rows    per bank             %d\n"                 \
5819831SN/A            "Banks   per rank             %d\n"                 \
5829831SN/A            "Ranks   per channel          %d\n"                 \
58310143SN/A            "Total mem capacity (bytes)   %u\n",
5849831SN/A            name(), devicesPerRank, deviceBusWidth, burstSize, rowBufferSize,
5859831SN/A            columnsPerRowBuffer, rowsPerBank, banksPerRank, ranksPerChannel,
5869831SN/A            rowBufferSize * rowsPerBank * banksPerRank * ranksPerChannel);
5879243SN/A
5889243SN/A    string scheduler =  memSchedPolicy == Enums::fcfs ? "FCFS" : "FR-FCFS";
58910136SN/A    string address_mapping = addrMapping == Enums::RoRaBaChCo ? "RoRaBaChCo" :
59010136SN/A        (addrMapping == Enums::RoRaBaCoCh ? "RoRaBaCoCh" : "RoCoRaBaCh");
5919973SN/A    string page_policy = pageMgmt == Enums::open ? "OPEN" :
59210144SN/A        (pageMgmt == Enums::open_adaptive ? "OPEN (adaptive)" :
59310144SN/A        (pageMgmt == Enums::close_adaptive ? "CLOSE (adaptive)" : "CLOSE"));
5949243SN/A
5959243SN/A    DPRINTF(DRAM,
5969243SN/A            "Memory controller %s characteristics\n"    \
5979243SN/A            "Read buffer size     %d\n"                 \
5989243SN/A            "Write buffer size    %d\n"                 \
59910140SN/A            "Write high thresh    %d\n"                 \
60010140SN/A            "Write low thresh     %d\n"                 \
6019243SN/A            "Scheduler            %s\n"                 \
6029243SN/A            "Address mapping      %s\n"                 \
6039243SN/A            "Page policy          %s\n",
6049972SN/A            name(), readBufferSize, writeBufferSize, writeHighThreshold,
60510140SN/A            writeLowThreshold, scheduler, address_mapping, page_policy);
6069243SN/A
6079243SN/A    DPRINTF(DRAM, "Memory controller %s timing specs\n" \
6089567SN/A            "tRCD      %d ticks\n"                        \
6099567SN/A            "tCL       %d ticks\n"                        \
6109567SN/A            "tRP       %d ticks\n"                        \
6119567SN/A            "tBURST    %d ticks\n"                        \
6129567SN/A            "tRFC      %d ticks\n"                        \
6139567SN/A            "tREFI     %d ticks\n"                        \
6149567SN/A            "tWTR      %d ticks\n"                        \
6159567SN/A            "tXAW (%d) %d ticks\n",
6169567SN/A            name(), tRCD, tCL, tRP, tBURST, tRFC, tREFI, tWTR,
6179567SN/A            activationLimit, tXAW);
6189243SN/A}
6199243SN/A
6209243SN/Avoid
62110146Sandreas.hansson@arm.comDRAMCtrl::printQs() const {
6229243SN/A    DPRINTF(DRAM, "===READ QUEUE===\n\n");
6239833SN/A    for (auto i = readQueue.begin() ;  i != readQueue.end() ; ++i) {
6249243SN/A        DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
6259243SN/A    }
6269243SN/A    DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
6279833SN/A    for (auto i = respQueue.begin() ;  i != respQueue.end() ; ++i) {
6289243SN/A        DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
6299243SN/A    }
6309243SN/A    DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
6319833SN/A    for (auto i = writeQueue.begin() ;  i != writeQueue.end() ; ++i) {
6329243SN/A        DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
6339243SN/A    }
6349243SN/A}
6359243SN/A
6369243SN/Abool
63710146Sandreas.hansson@arm.comDRAMCtrl::recvTimingReq(PacketPtr pkt)
6389243SN/A{
6399349SN/A    /// @todo temporary hack to deal with memory corruption issues until
6409349SN/A    /// 4-phase transactions are complete
6419349SN/A    for (int x = 0; x < pendingDelete.size(); x++)
6429349SN/A        delete pendingDelete[x];
6439349SN/A    pendingDelete.clear();
6449349SN/A
6459243SN/A    // This is where we enter from the outside world
6469567SN/A    DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
6479831SN/A            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
6489243SN/A
6499567SN/A    // simply drop inhibited packets for now
6509567SN/A    if (pkt->memInhibitAsserted()) {
65110143SN/A        DPRINTF(DRAM, "Inhibited packet -- Dropping it now\n");
6529567SN/A        pendingDelete.push_back(pkt);
6539567SN/A        return true;
6549567SN/A    }
6559243SN/A
6569243SN/A    // Calc avg gap between requests
6579243SN/A    if (prevArrival != 0) {
6589243SN/A        totGap += curTick() - prevArrival;
6599243SN/A    }
6609243SN/A    prevArrival = curTick();
6619243SN/A
6629831SN/A
6639831SN/A    // Find out how many dram packets a pkt translates to
6649831SN/A    // If the burst size is equal or larger than the pkt size, then a pkt
6659831SN/A    // translates to only one dram packet. Otherwise, a pkt translates to
6669831SN/A    // multiple dram packets
6679243SN/A    unsigned size = pkt->getSize();
6689831SN/A    unsigned offset = pkt->getAddr() & (burstSize - 1);
6699831SN/A    unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
6709243SN/A
6719243SN/A    // check local buffers and do not accept if full
6729243SN/A    if (pkt->isRead()) {
6739567SN/A        assert(size != 0);
6749831SN/A        if (readQueueFull(dram_pkt_count)) {
6759567SN/A            DPRINTF(DRAM, "Read queue full, not accepting\n");
6769243SN/A            // remember that we have to retry this port
6779243SN/A            retryRdReq = true;
6789243SN/A            numRdRetry++;
6799243SN/A            return false;
6809243SN/A        } else {
6819831SN/A            addToReadQueue(pkt, dram_pkt_count);
6829243SN/A            readReqs++;
6839977SN/A            bytesReadSys += size;
6849243SN/A        }
6859243SN/A    } else if (pkt->isWrite()) {
6869567SN/A        assert(size != 0);
6879831SN/A        if (writeQueueFull(dram_pkt_count)) {
6889567SN/A            DPRINTF(DRAM, "Write queue full, not accepting\n");
6899243SN/A            // remember that we have to retry this port
6909243SN/A            retryWrReq = true;
6919243SN/A            numWrRetry++;
6929243SN/A            return false;
6939243SN/A        } else {
6949831SN/A            addToWriteQueue(pkt, dram_pkt_count);
6959243SN/A            writeReqs++;
6969977SN/A            bytesWrittenSys += size;
6979243SN/A        }
6989243SN/A    } else {
6999243SN/A        DPRINTF(DRAM,"Neither read nor write, ignore timing\n");
7009243SN/A        neitherReadNorWrite++;
7019726SN/A        accessAndRespond(pkt, 1);
7029243SN/A    }
7039243SN/A
7049243SN/A    return true;
7059243SN/A}
7069243SN/A
7079243SN/Avoid
70810146Sandreas.hansson@arm.comDRAMCtrl::processRespondEvent()
7099243SN/A{
7109243SN/A    DPRINTF(DRAM,
7119243SN/A            "processRespondEvent(): Some req has reached its readyTime\n");
7129243SN/A
7139831SN/A    DRAMPacket* dram_pkt = respQueue.front();
7149243SN/A
7159831SN/A    if (dram_pkt->burstHelper) {
7169831SN/A        // it is a split packet
7179831SN/A        dram_pkt->burstHelper->burstsServiced++;
7189831SN/A        if (dram_pkt->burstHelper->burstsServiced ==
71910143SN/A            dram_pkt->burstHelper->burstCount) {
7209831SN/A            // we have now serviced all children packets of a system packet
7219831SN/A            // so we can now respond to the requester
7229831SN/A            // @todo we probably want to have a different front end and back
7239831SN/A            // end latency for split packets
7249831SN/A            accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
7259831SN/A            delete dram_pkt->burstHelper;
7269831SN/A            dram_pkt->burstHelper = NULL;
7279831SN/A        }
7289831SN/A    } else {
7299831SN/A        // it is not a split packet
7309831SN/A        accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
7319831SN/A    }
7329243SN/A
7339831SN/A    delete respQueue.front();
7349831SN/A    respQueue.pop_front();
7359243SN/A
7369831SN/A    if (!respQueue.empty()) {
7379831SN/A        assert(respQueue.front()->readyTime >= curTick());
7389831SN/A        assert(!respondEvent.scheduled());
7399831SN/A        schedule(respondEvent, respQueue.front()->readyTime);
7409831SN/A    } else {
7419831SN/A        // if there is nothing left in any queue, signal a drain
7429831SN/A        if (writeQueue.empty() && readQueue.empty() &&
7439831SN/A            drainManager) {
7449831SN/A            drainManager->signalDrainDone();
7459831SN/A            drainManager = NULL;
7469831SN/A        }
7479831SN/A    }
7489567SN/A
7499831SN/A    // We have made a location in the queue available at this point,
7509831SN/A    // so if there is a read that was forced to wait, retry now
7519831SN/A    if (retryRdReq) {
7529831SN/A        retryRdReq = false;
7539831SN/A        port.sendRetry();
7549831SN/A    }
7559243SN/A}
7569243SN/A
7579243SN/Avoid
75810146Sandreas.hansson@arm.comDRAMCtrl::chooseNextWrite()
7599243SN/A{
7609567SN/A    // This method does the arbitration between write requests. The
7619567SN/A    // chosen packet is simply moved to the head of the write
7629567SN/A    // queue. The other methods know that this is the place to
7639567SN/A    // look. For example, with FCFS, this method does nothing
7649567SN/A    assert(!writeQueue.empty());
7659243SN/A
7669567SN/A    if (writeQueue.size() == 1) {
7679966SN/A        DPRINTF(DRAM, "Single write request, nothing to do\n");
7689243SN/A        return;
7699243SN/A    }
7709243SN/A
7719243SN/A    if (memSchedPolicy == Enums::fcfs) {
7729243SN/A        // Do nothing, since the correct request is already head
7739243SN/A    } else if (memSchedPolicy == Enums::frfcfs) {
7749974SN/A        reorderQueue(writeQueue);
7759243SN/A    } else
7769243SN/A        panic("No scheduling policy chosen\n");
7779243SN/A
7789966SN/A    DPRINTF(DRAM, "Selected next write request\n");
7799243SN/A}
7809243SN/A
7819243SN/Abool
78210146Sandreas.hansson@arm.comDRAMCtrl::chooseNextRead()
7839243SN/A{
7849567SN/A    // This method does the arbitration between read requests. The
7859567SN/A    // chosen packet is simply moved to the head of the queue. The
7869567SN/A    // other methods know that this is the place to look. For example,
7879567SN/A    // with FCFS, this method does nothing
7889567SN/A    if (readQueue.empty()) {
7899567SN/A        DPRINTF(DRAM, "No read request to select\n");
7909243SN/A        return false;
7919243SN/A    }
7929243SN/A
7939567SN/A    // If there is only one request then there is nothing left to do
7949567SN/A    if (readQueue.size() == 1)
7959243SN/A        return true;
7969243SN/A
7979243SN/A    if (memSchedPolicy == Enums::fcfs) {
7989567SN/A        // Do nothing, since the request to serve is already the first
7999567SN/A        // one in the read queue
8009243SN/A    } else if (memSchedPolicy == Enums::frfcfs) {
8019974SN/A        reorderQueue(readQueue);
8029243SN/A    } else
8039243SN/A        panic("No scheduling policy chosen!\n");
8049243SN/A
8059567SN/A    DPRINTF(DRAM, "Selected next read request\n");
8069243SN/A    return true;
8079243SN/A}
8089243SN/A
8099243SN/Avoid
81010146Sandreas.hansson@arm.comDRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue)
8119974SN/A{
8129974SN/A    // Only determine this when needed
8139974SN/A    uint64_t earliest_banks = 0;
8149974SN/A
8159974SN/A    // Search for row hits first, if no row hit is found then schedule the
8169974SN/A    // packet to one of the earliest banks available
8179974SN/A    bool found_earliest_pkt = false;
8189974SN/A    auto selected_pkt_it = queue.begin();
8199974SN/A
8209974SN/A    for (auto i = queue.begin(); i != queue.end() ; ++i) {
8219974SN/A        DRAMPacket* dram_pkt = *i;
8229974SN/A        const Bank& bank = dram_pkt->bankRef;
8239974SN/A        // Check if it is a row hit
8249974SN/A        if (bank.openRow == dram_pkt->row) {
8259974SN/A            DPRINTF(DRAM, "Row buffer hit\n");
8269974SN/A            selected_pkt_it = i;
8279974SN/A            break;
8289974SN/A        } else if (!found_earliest_pkt) {
8299974SN/A            // No row hit, go for first ready
8309974SN/A            if (earliest_banks == 0)
8319974SN/A                earliest_banks = minBankFreeAt(queue);
8329974SN/A
8339974SN/A            // Bank is ready or is the first available bank
8349974SN/A            if (bank.freeAt <= curTick() ||
8359974SN/A                bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
8369974SN/A                // Remember the packet to be scheduled to one of the earliest
8379974SN/A                // banks available
8389974SN/A                selected_pkt_it = i;
8399974SN/A                found_earliest_pkt = true;
8409974SN/A            }
8419974SN/A        }
8429974SN/A    }
8439974SN/A
8449974SN/A    DRAMPacket* selected_pkt = *selected_pkt_it;
8459974SN/A    queue.erase(selected_pkt_it);
8469974SN/A    queue.push_front(selected_pkt);
8479974SN/A}
8489974SN/A
8499974SN/Avoid
85010146Sandreas.hansson@arm.comDRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
8519243SN/A{
8529243SN/A    DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
8539243SN/A
8549243SN/A    bool needsResponse = pkt->needsResponse();
8559243SN/A    // do the actual memory access which also turns the packet into a
8569243SN/A    // response
8579243SN/A    access(pkt);
8589243SN/A
8599243SN/A    // turn packet around to go back to requester if response expected
8609243SN/A    if (needsResponse) {
8619243SN/A        // access already turned the packet into a response
8629243SN/A        assert(pkt->isResponse());
8639243SN/A
8649549SN/A        // @todo someone should pay for this
8659549SN/A        pkt->busFirstWordDelay = pkt->busLastWordDelay = 0;
8669549SN/A
8679726SN/A        // queue the packet in the response queue to be sent out after
8689726SN/A        // the static latency has passed
8699726SN/A        port.schedTimingResp(pkt, curTick() + static_latency);
8709243SN/A    } else {
8719587SN/A        // @todo the packet is going to be deleted, and the DRAMPacket
8729587SN/A        // is still having a pointer to it
8739587SN/A        pendingDelete.push_back(pkt);
8749243SN/A    }
8759243SN/A
8769243SN/A    DPRINTF(DRAM, "Done\n");
8779243SN/A
8789243SN/A    return;
8799243SN/A}
8809243SN/A
8819243SN/Apair<Tick, Tick>
88210146Sandreas.hansson@arm.comDRAMCtrl::estimateLatency(DRAMPacket* dram_pkt, Tick inTime)
8839243SN/A{
8849243SN/A    // If a request reaches a bank at tick 'inTime', how much time
8859243SN/A    // *after* that does it take to finish the request, depending
8869243SN/A    // on bank status and page open policy. Note that this method
8879243SN/A    // considers only the time taken for the actual read or write
8889243SN/A    // to complete, NOT any additional time thereafter for tRAS or
8899243SN/A    // tRP.
8909243SN/A    Tick accLat = 0;
8919243SN/A    Tick bankLat = 0;
8929243SN/A    rowHitFlag = false;
8939969SN/A    Tick potentialActTick;
8949243SN/A
8959967SN/A    const Bank& bank = dram_pkt->bankRef;
89610144SN/A     // open-page policy or close_adaptive policy
89710144SN/A    if (pageMgmt == Enums::open || pageMgmt == Enums::open_adaptive ||
89810144SN/A        pageMgmt == Enums::close_adaptive) {
8999243SN/A        if (bank.openRow == dram_pkt->row) {
9009243SN/A            // When we have a row-buffer hit,
9019243SN/A            // we don't care about tRAS having expired or not,
9029243SN/A            // but do care about bank being free for access
9039243SN/A            rowHitFlag = true;
9049243SN/A
9059965SN/A            // When a series of requests arrive to the same row,
9069965SN/A            // DDR systems are capable of streaming data continuously
9079965SN/A            // at maximum bandwidth (subject to tCCD). Here, we approximate
9089965SN/A            // this condition, and assume that if whenever a bank is already
9099965SN/A            // busy and a new request comes in, it can be completed with no
9109965SN/A            // penalty beyond waiting for the existing read to complete.
9119965SN/A            if (bank.freeAt > inTime) {
9129965SN/A                accLat += bank.freeAt - inTime;
9139966SN/A                bankLat += 0;
9149965SN/A            } else {
9159243SN/A               // CAS latency only
9169243SN/A               accLat += tCL;
9179243SN/A               bankLat += tCL;
9189243SN/A            }
9199243SN/A
9209243SN/A        } else {
9219243SN/A            // Row-buffer miss, need to close existing row
9229243SN/A            // once tRAS has expired, then open the new one,
9239243SN/A            // then add cas latency.
9249243SN/A            Tick freeTime = std::max(bank.tRASDoneAt, bank.freeAt);
9259243SN/A
9269243SN/A            if (freeTime > inTime)
9279243SN/A               accLat += freeTime - inTime;
9289243SN/A
9299973SN/A            // If the there is no open row (open adaptive), then there
9309973SN/A            // is no precharge delay, otherwise go with tRP
9319973SN/A            Tick precharge_delay = bank.openRow == -1 ? 0 : tRP;
9329973SN/A
9339969SN/A            //The bank is free, and you may be able to activate
9349973SN/A            potentialActTick = inTime + accLat + precharge_delay;
9359969SN/A            if (potentialActTick < bank.actAllowedAt)
9369969SN/A                accLat += bank.actAllowedAt - potentialActTick;
9379969SN/A
9389973SN/A            accLat += precharge_delay + tRCD + tCL;
9399973SN/A            bankLat += precharge_delay + tRCD + tCL;
9409243SN/A        }
9419243SN/A    } else if (pageMgmt == Enums::close) {
9429243SN/A        // With a close page policy, no notion of
9439243SN/A        // bank.tRASDoneAt
9449243SN/A        if (bank.freeAt > inTime)
9459243SN/A            accLat += bank.freeAt - inTime;
9469243SN/A
9479969SN/A        //The bank is free, and you may be able to activate
9489969SN/A        potentialActTick = inTime + accLat;
9499969SN/A        if (potentialActTick < bank.actAllowedAt)
9509969SN/A            accLat += bank.actAllowedAt - potentialActTick;
9519969SN/A
9529243SN/A        // page already closed, simply open the row, and
9539243SN/A        // add cas latency
9549243SN/A        accLat += tRCD + tCL;
9559243SN/A        bankLat += tRCD + tCL;
9569243SN/A    } else
9579243SN/A        panic("No page management policy chosen\n");
9589243SN/A
9599487SN/A    DPRINTF(DRAM, "Returning < %lld, %lld > from estimateLatency()\n",
9609487SN/A            bankLat, accLat);
9619243SN/A
9629243SN/A    return make_pair(bankLat, accLat);
9639243SN/A}
9649243SN/A
9659243SN/Avoid
96610146Sandreas.hansson@arm.comDRAMCtrl::processNextReqEvent()
9679243SN/A{
9689243SN/A    scheduleNextReq();
9699243SN/A}
9709243SN/A
9719243SN/Avoid
97210146Sandreas.hansson@arm.comDRAMCtrl::recordActivate(Tick act_tick, uint8_t rank, uint8_t bank)
9739488SN/A{
9749969SN/A    assert(0 <= rank && rank < ranksPerChannel);
9759969SN/A    assert(actTicks[rank].size() == activationLimit);
9769488SN/A
9779488SN/A    DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
9789488SN/A
9799975SN/A    // Tracking accesses after all banks are precharged.
9809975SN/A    // startTickPrechargeAll: is the tick when all the banks were again
9819975SN/A    // precharged. The difference between act_tick and startTickPrechargeAll
9829975SN/A    // gives the time for which DRAM doesn't get any accesses after refreshing
9839975SN/A    // or after a page is closed in closed-page or open-adaptive-page policy.
9849975SN/A    if ((numBanksActive == 0) && (act_tick > startTickPrechargeAll)) {
9859975SN/A        prechargeAllTime += act_tick - startTickPrechargeAll;
9869975SN/A    }
9879975SN/A
9889975SN/A    // No need to update number of active banks for closed-page policy as only 1
9899975SN/A    // bank will be activated at any given point, which will be instatntly
9909975SN/A    // precharged
99110144SN/A    if (pageMgmt == Enums::open || pageMgmt == Enums::open_adaptive ||
99210144SN/A        pageMgmt == Enums::close_adaptive)
9939975SN/A        ++numBanksActive;
9949975SN/A
9959971SN/A    // start by enforcing tRRD
9969971SN/A    for(int i = 0; i < banksPerRank; i++) {
9979971SN/A        // next activate must not happen before tRRD
9989971SN/A        banks[rank][i].actAllowedAt = act_tick + tRRD;
9999971SN/A    }
10009971SN/A    // tRC should be added to activation tick of the bank currently accessed,
10019971SN/A    // where tRC = tRAS + tRP, this is just for a check as actAllowedAt for same
10029971SN/A    // bank is already captured by bank.freeAt and bank.tRASDoneAt
10039971SN/A    banks[rank][bank].actAllowedAt = act_tick + tRAS + tRP;
10049971SN/A
10059971SN/A    // next, we deal with tXAW, if the activation limit is disabled
10069971SN/A    // then we are done
10079969SN/A    if (actTicks[rank].empty())
10089824SN/A        return;
10099824SN/A
10109488SN/A    // sanity check
10119969SN/A    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
10129825SN/A        // @todo For now, stick with a warning
10139825SN/A        warn("Got %d activates in window %d (%d - %d) which is smaller "
10149969SN/A             "than %d\n", activationLimit, act_tick - actTicks[rank].back(),
10159969SN/A             act_tick, actTicks[rank].back(), tXAW);
10169488SN/A    }
10179488SN/A
10189488SN/A    // shift the times used for the book keeping, the last element
10199488SN/A    // (highest index) is the oldest one and hence the lowest value
10209969SN/A    actTicks[rank].pop_back();
10219488SN/A
10229488SN/A    // record an new activation (in the future)
10239969SN/A    actTicks[rank].push_front(act_tick);
10249488SN/A
10259488SN/A    // cannot activate more than X times in time window tXAW, push the
10269488SN/A    // next one (the X + 1'st activate) to be tXAW away from the
10279488SN/A    // oldest in our window of X
10289969SN/A    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
10299488SN/A        DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate no earlier "
10309969SN/A                "than %d\n", activationLimit, actTicks[rank].back() + tXAW);
10319488SN/A            for(int j = 0; j < banksPerRank; j++)
10329488SN/A                // next activate must not happen before end of window
10339969SN/A                banks[rank][j].actAllowedAt = actTicks[rank].back() + tXAW;
10349488SN/A    }
10359488SN/A}
10369488SN/A
10379488SN/Avoid
103810146Sandreas.hansson@arm.comDRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
10399243SN/A{
10409243SN/A
10419243SN/A    DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
10429243SN/A            dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
10439243SN/A
10449243SN/A    // estimate the bank and access latency
10459243SN/A    pair<Tick, Tick> lat = estimateLatency(dram_pkt, curTick());
10469243SN/A    Tick bankLat = lat.first;
10479243SN/A    Tick accessLat = lat.second;
10489963SN/A    Tick actTick;
10499243SN/A
10509243SN/A    // This request was woken up at this time based on a prior call
10519243SN/A    // to estimateLatency(). However, between then and now, both the
10529243SN/A    // accessLatency and/or busBusyUntil may have changed. We need
10539243SN/A    // to correct for that.
10549243SN/A
10559243SN/A    Tick addDelay = (curTick() + accessLat < busBusyUntil) ?
10569243SN/A        busBusyUntil - (curTick() + accessLat) : 0;
10579243SN/A
10589967SN/A    Bank& bank = dram_pkt->bankRef;
10599243SN/A
10609243SN/A    // Update bank state
106110144SN/A    if (pageMgmt == Enums::open || pageMgmt == Enums::open_adaptive ||
106210144SN/A        pageMgmt == Enums::close_adaptive) {
10639243SN/A        bank.freeAt = curTick() + addDelay + accessLat;
10649727SN/A
10659243SN/A        // If you activated a new row do to this access, the next access
10669963SN/A        // will have to respect tRAS for this bank.
10679488SN/A        if (!rowHitFlag) {
10689963SN/A            // any waiting for banks account for in freeAt
10699963SN/A            actTick = bank.freeAt - tCL - tRCD;
10709963SN/A            bank.tRASDoneAt = actTick + tRAS;
10719971SN/A            recordActivate(actTick, dram_pkt->rank, dram_pkt->bank);
10729963SN/A
107310142SN/A            // if we closed an open row as a result of this access,
107410142SN/A            // then sample the number of bytes accessed before
107510142SN/A            // resetting it
107610142SN/A            if (bank.openRow != -1)
107710142SN/A                bytesPerActivate.sample(bank.bytesAccessed);
107810142SN/A
107910142SN/A            // update the open row
108010142SN/A            bank.openRow = dram_pkt->row;
108110142SN/A
108210142SN/A            // start counting anew, this covers both the case when we
108310142SN/A            // auto-precharged, and when this access is forced to
108410142SN/A            // precharge
10859727SN/A            bank.bytesAccessed = 0;
108610141SN/A            bank.rowAccesses = 0;
10879488SN/A        }
10889973SN/A
108910141SN/A        // increment the bytes accessed and the accesses per row
109010141SN/A        bank.bytesAccessed += burstSize;
109110141SN/A        ++bank.rowAccesses;
109210141SN/A
109310141SN/A        // if we reached the max, then issue with an auto-precharge
109410141SN/A        bool auto_precharge = bank.rowAccesses == maxAccessesPerRow;
109510141SN/A
109610141SN/A        // if we did not hit the limit, we might still want to
109710141SN/A        // auto-precharge
109810144SN/A        if (!auto_precharge &&
109910144SN/A            (pageMgmt == Enums::open_adaptive ||
110010144SN/A             pageMgmt == Enums::close_adaptive)) {
110110144SN/A            // a twist on the open and close page policies:
110210144SN/A            // 1) open_adaptive page policy does not blindly keep the
11039973SN/A            // page open, but close it if there are no row hits, and there
11049973SN/A            // are bank conflicts in the queue
110510144SN/A            // 2) close_adaptive page policy does not blindly close the
110610144SN/A            // page, but closes it only if there are no row hits in the queue.
110710144SN/A            // In this case, only force an auto precharge when there
110810144SN/A            // are no same page hits in the queue
11099973SN/A            bool got_more_hits = false;
11109973SN/A            bool got_bank_conflict = false;
11119973SN/A
11129973SN/A            // either look at the read queue or write queue
11139973SN/A            const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
11149973SN/A                writeQueue;
11159973SN/A            auto p = queue.begin();
11169973SN/A            // make sure we are not considering the packet that we are
11179973SN/A            // currently dealing with (which is the head of the queue)
11189973SN/A            ++p;
11199973SN/A
112010144SN/A            // keep on looking until we have found required condition or
112110144SN/A            // reached the end
112210144SN/A            while (!(got_more_hits &&
112310144SN/A                    (got_bank_conflict || pageMgmt == Enums::close_adaptive)) &&
11249973SN/A                   p != queue.end()) {
11259973SN/A                bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
11269973SN/A                    (dram_pkt->bank == (*p)->bank);
11279973SN/A                bool same_row = dram_pkt->row == (*p)->row;
11289973SN/A                got_more_hits |= same_rank_bank && same_row;
11299973SN/A                got_bank_conflict |= same_rank_bank && !same_row;
11309973SN/A                ++p;
11319973SN/A            }
11329973SN/A
113310144SN/A            // auto pre-charge when either
113410144SN/A            // 1) open_adaptive policy, we have not got any more hits, and
113510144SN/A            //    have a bank conflict
113610144SN/A            // 2) close_adaptive policy and we have not got any more hits
113710144SN/A            auto_precharge = !got_more_hits &&
113810144SN/A                (got_bank_conflict || pageMgmt == Enums::close_adaptive);
113910141SN/A        }
114010141SN/A
114110141SN/A        // if this access should use auto-precharge, then we are
114210141SN/A        // closing the row
114310141SN/A        if (auto_precharge) {
114410141SN/A            bank.openRow = -1;
114510141SN/A            bank.freeAt = std::max(bank.freeAt, bank.tRASDoneAt) + tRP;
114610141SN/A            --numBanksActive;
114710141SN/A            if (numBanksActive == 0) {
114810141SN/A                startTickPrechargeAll = std::max(startTickPrechargeAll,
114910141SN/A                                                 bank.freeAt);
115010141SN/A                DPRINTF(DRAM, "All banks precharged at tick: %ld\n",
115110141SN/A                        startTickPrechargeAll);
11529973SN/A            }
115310142SN/A
115410142SN/A            // sample the bytes per activate here since we are closing
115510142SN/A            // the page
115610142SN/A            bytesPerActivate.sample(bank.bytesAccessed);
115710142SN/A
115810141SN/A            DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId);
11599973SN/A        }
11609973SN/A
11619971SN/A        DPRINTF(DRAM, "doDRAMAccess::bank.freeAt is %lld\n", bank.freeAt);
11629963SN/A    } else if (pageMgmt == Enums::close) {
11639963SN/A        actTick = curTick() + addDelay + accessLat - tRCD - tCL;
11649971SN/A        recordActivate(actTick, dram_pkt->rank, dram_pkt->bank);
11659963SN/A
11669963SN/A        // If the DRAM has a very quick tRAS, bank can be made free
11679963SN/A        // after consecutive tCL,tRCD,tRP times. In general, however,
11689963SN/A        // an additional wait is required to respect tRAS.
11699963SN/A        bank.freeAt = std::max(actTick + tRAS + tRP,
11709963SN/A                actTick + tRCD + tCL + tRP);
11719971SN/A        DPRINTF(DRAM, "doDRAMAccess::bank.freeAt is %lld\n", bank.freeAt);
11729831SN/A        bytesPerActivate.sample(burstSize);
11739975SN/A        startTickPrechargeAll = std::max(startTickPrechargeAll, bank.freeAt);
11749243SN/A    } else
11759243SN/A        panic("No page management policy chosen\n");
11769243SN/A
11779243SN/A    // Update request parameters
11789243SN/A    dram_pkt->readyTime = curTick() + addDelay + accessLat + tBURST;
11799243SN/A
11809243SN/A
11819243SN/A    DPRINTF(DRAM, "Req %lld: curtick is %lld accessLat is %d " \
11829243SN/A                  "readytime is %lld busbusyuntil is %lld. " \
11839243SN/A                  "Scheduling at readyTime\n", dram_pkt->addr,
11849243SN/A                   curTick(), accessLat, dram_pkt->readyTime, busBusyUntil);
11859243SN/A
11869243SN/A    // Make sure requests are not overlapping on the databus
11879243SN/A    assert (dram_pkt->readyTime - busBusyUntil >= tBURST);
11889243SN/A
11899243SN/A    // Update bus state
11909243SN/A    busBusyUntil = dram_pkt->readyTime;
11919243SN/A
11929243SN/A    DPRINTF(DRAM,"Access time is %lld\n",
11939243SN/A            dram_pkt->readyTime - dram_pkt->entryTime);
11949243SN/A
11959972SN/A    // Update the minimum timing between the requests
11969972SN/A    newTime = (busBusyUntil > tRP + tRCD + tCL) ?
11979972SN/A        std::max(busBusyUntil - (tRP + tRCD + tCL), curTick()) : curTick();
11989972SN/A
11999977SN/A    // Update the access related stats
12009977SN/A    if (dram_pkt->isRead) {
12019977SN/A        if (rowHitFlag)
12029977SN/A            readRowHits++;
12039977SN/A        bytesReadDRAM += burstSize;
12049977SN/A        perBankRdBursts[dram_pkt->bankId]++;
12059977SN/A    } else {
12069977SN/A        if (rowHitFlag)
12079977SN/A            writeRowHits++;
12089977SN/A        bytesWritten += burstSize;
12099977SN/A        perBankWrBursts[dram_pkt->bankId]++;
12109966SN/A
12119977SN/A        // At this point, commonality between reads and writes ends.
12129977SN/A        // For writes, we are done since we long ago responded to the
12139977SN/A        // requestor.
12149966SN/A        return;
12159966SN/A    }
12169966SN/A
12179977SN/A    // Update latency stats
12189243SN/A    totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
12199243SN/A    totBankLat += bankLat;
12209243SN/A    totBusLat += tBURST;
12219243SN/A    totQLat += dram_pkt->readyTime - dram_pkt->entryTime - bankLat - tBURST;
12229243SN/A
12239243SN/A
12249243SN/A    // At this point we're done dealing with the request
12259243SN/A    // It will be moved to a separate response queue with a
12269243SN/A    // correct readyTime, and eventually be sent back at that
12279243SN/A    //time
12289243SN/A    moveToRespQ();
12299243SN/A
12309972SN/A    // Schedule the next read event
123110143SN/A    if (!nextReqEvent.scheduled() && !stopReads) {
12329567SN/A        schedule(nextReqEvent, newTime);
12339243SN/A    } else {
12349243SN/A        if (newTime < nextReqEvent.when())
12359567SN/A            reschedule(nextReqEvent, newTime);
12369243SN/A    }
12379243SN/A}
12389243SN/A
12399243SN/Avoid
124010146Sandreas.hansson@arm.comDRAMCtrl::moveToRespQ()
12419243SN/A{
12429243SN/A    // Remove from read queue
12439567SN/A    DRAMPacket* dram_pkt = readQueue.front();
12449567SN/A    readQueue.pop_front();
12459243SN/A
12469832SN/A    // sanity check
12479832SN/A    assert(dram_pkt->size <= burstSize);
12489832SN/A
12499243SN/A    // Insert into response queue sorted by readyTime
12509243SN/A    // It will be sent back to the requestor at its
12519243SN/A    // readyTime
12529567SN/A    if (respQueue.empty()) {
12539567SN/A        respQueue.push_front(dram_pkt);
12549243SN/A        assert(!respondEvent.scheduled());
12559243SN/A        assert(dram_pkt->readyTime >= curTick());
12569567SN/A        schedule(respondEvent, dram_pkt->readyTime);
12579243SN/A    } else {
12589243SN/A        bool done = false;
12599833SN/A        auto i = respQueue.begin();
12609567SN/A        while (!done && i != respQueue.end()) {
12619243SN/A            if ((*i)->readyTime > dram_pkt->readyTime) {
12629567SN/A                respQueue.insert(i, dram_pkt);
12639243SN/A                done = true;
12649243SN/A            }
12659243SN/A            ++i;
12669243SN/A        }
12679243SN/A
12689243SN/A        if (!done)
12699567SN/A            respQueue.push_back(dram_pkt);
12709243SN/A
12719243SN/A        assert(respondEvent.scheduled());
12729243SN/A
12739567SN/A        if (respQueue.front()->readyTime < respondEvent.when()) {
12749567SN/A            assert(respQueue.front()->readyTime >= curTick());
12759567SN/A            reschedule(respondEvent, respQueue.front()->readyTime);
12769243SN/A        }
12779243SN/A    }
12789243SN/A}
12799243SN/A
12809243SN/Avoid
128110146Sandreas.hansson@arm.comDRAMCtrl::scheduleNextReq()
12829243SN/A{
12839243SN/A    DPRINTF(DRAM, "Reached scheduleNextReq()\n");
12849243SN/A
12859567SN/A    // Figure out which read request goes next, and move it to the
12869567SN/A    // front of the read queue
12879567SN/A    if (!chooseNextRead()) {
128810140SN/A        // In the case there is no read request to go next, trigger
128910140SN/A        // writes if we have passed the low threshold (or if we are
129010140SN/A        // draining)
129110140SN/A        if (!writeQueue.empty() && !writeEvent.scheduled() &&
129210140SN/A            (writeQueue.size() > writeLowThreshold || drainManager))
12939352SN/A            triggerWrites();
12949352SN/A    } else {
12959567SN/A        doDRAMAccess(readQueue.front());
12969352SN/A    }
12979243SN/A}
12989243SN/A
12999243SN/ATick
130010146Sandreas.hansson@arm.comDRAMCtrl::maxBankFreeAt() const
13019243SN/A{
13029243SN/A    Tick banksFree = 0;
13039243SN/A
13049243SN/A    for(int i = 0; i < ranksPerChannel; i++)
13059243SN/A        for(int j = 0; j < banksPerRank; j++)
13069243SN/A            banksFree = std::max(banks[i][j].freeAt, banksFree);
13079243SN/A
13089243SN/A    return banksFree;
13099243SN/A}
13109243SN/A
13119967SN/Auint64_t
131210146Sandreas.hansson@arm.comDRAMCtrl::minBankFreeAt(const deque<DRAMPacket*>& queue) const
13139967SN/A{
13149967SN/A    uint64_t bank_mask = 0;
13159967SN/A    Tick freeAt = MaxTick;
13169967SN/A
13179967SN/A    // detemrine if we have queued transactions targetting the
13189967SN/A    // bank in question
13199967SN/A    vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
13209967SN/A    for (auto p = queue.begin(); p != queue.end(); ++p) {
13219967SN/A        got_waiting[(*p)->bankId] = true;
13229967SN/A    }
13239967SN/A
13249967SN/A    for (int i = 0; i < ranksPerChannel; i++) {
13259967SN/A        for (int j = 0; j < banksPerRank; j++) {
13269967SN/A            // if we have waiting requests for the bank, and it is
13279967SN/A            // amongst the first available, update the mask
13289967SN/A            if (got_waiting[i * banksPerRank + j] &&
13299967SN/A                banks[i][j].freeAt <= freeAt) {
13309967SN/A                // reset bank mask if new minimum is found
13319967SN/A                if (banks[i][j].freeAt < freeAt)
13329967SN/A                    bank_mask = 0;
13339967SN/A                // set the bit corresponding to the available bank
13349967SN/A                uint8_t bit_index = i * ranksPerChannel + j;
13359967SN/A                replaceBits(bank_mask, bit_index, bit_index, 1);
13369967SN/A                freeAt = banks[i][j].freeAt;
13379967SN/A            }
13389967SN/A        }
13399967SN/A    }
13409967SN/A    return bank_mask;
13419967SN/A}
13429967SN/A
13439243SN/Avoid
134410146Sandreas.hansson@arm.comDRAMCtrl::processRefreshEvent()
13459243SN/A{
13469243SN/A    DPRINTF(DRAM, "Refreshing at tick %ld\n", curTick());
13479243SN/A
13489243SN/A    Tick banksFree = std::max(curTick(), maxBankFreeAt()) + tRFC;
13499243SN/A
13509243SN/A    for(int i = 0; i < ranksPerChannel; i++)
13519975SN/A        for(int j = 0; j < banksPerRank; j++) {
13529243SN/A            banks[i][j].freeAt = banksFree;
13539975SN/A            banks[i][j].openRow = -1;
13549975SN/A        }
13559975SN/A
13569975SN/A    // updating startTickPrechargeAll, isprechargeAll
13579975SN/A    numBanksActive = 0;
13589975SN/A    startTickPrechargeAll = banksFree;
13599243SN/A
13609567SN/A    schedule(refreshEvent, curTick() + tREFI);
13619243SN/A}
13629243SN/A
13639243SN/Avoid
136410146Sandreas.hansson@arm.comDRAMCtrl::regStats()
13659243SN/A{
13669243SN/A    using namespace Stats;
13679243SN/A
13689243SN/A    AbstractMemory::regStats();
13699243SN/A
13709243SN/A    readReqs
13719243SN/A        .name(name() + ".readReqs")
13729977SN/A        .desc("Number of read requests accepted");
13739243SN/A
13749243SN/A    writeReqs
13759243SN/A        .name(name() + ".writeReqs")
13769977SN/A        .desc("Number of write requests accepted");
13779831SN/A
13789831SN/A    readBursts
13799831SN/A        .name(name() + ".readBursts")
13809977SN/A        .desc("Number of DRAM read bursts, "
13819977SN/A              "including those serviced by the write queue");
13829831SN/A
13839831SN/A    writeBursts
13849831SN/A        .name(name() + ".writeBursts")
13859977SN/A        .desc("Number of DRAM write bursts, "
13869977SN/A              "including those merged in the write queue");
13879243SN/A
13889243SN/A    servicedByWrQ
13899243SN/A        .name(name() + ".servicedByWrQ")
13909977SN/A        .desc("Number of DRAM read bursts serviced by the write queue");
13919977SN/A
13929977SN/A    mergedWrBursts
13939977SN/A        .name(name() + ".mergedWrBursts")
13949977SN/A        .desc("Number of DRAM write bursts merged with an existing one");
13959243SN/A
13969243SN/A    neitherReadNorWrite
13979977SN/A        .name(name() + ".neitherReadNorWriteReqs")
13989977SN/A        .desc("Number of requests that are neither read nor write");
13999243SN/A
14009977SN/A    perBankRdBursts
14019243SN/A        .init(banksPerRank * ranksPerChannel)
14029977SN/A        .name(name() + ".perBankRdBursts")
14039977SN/A        .desc("Per bank write bursts");
14049243SN/A
14059977SN/A    perBankWrBursts
14069243SN/A        .init(banksPerRank * ranksPerChannel)
14079977SN/A        .name(name() + ".perBankWrBursts")
14089977SN/A        .desc("Per bank write bursts");
14099243SN/A
14109243SN/A    avgRdQLen
14119243SN/A        .name(name() + ".avgRdQLen")
14129977SN/A        .desc("Average read queue length when enqueuing")
14139243SN/A        .precision(2);
14149243SN/A
14159243SN/A    avgWrQLen
14169243SN/A        .name(name() + ".avgWrQLen")
14179977SN/A        .desc("Average write queue length when enqueuing")
14189243SN/A        .precision(2);
14199243SN/A
14209243SN/A    totQLat
14219243SN/A        .name(name() + ".totQLat")
14229977SN/A        .desc("Total ticks spent queuing");
14239243SN/A
14249243SN/A    totBankLat
14259243SN/A        .name(name() + ".totBankLat")
14269977SN/A        .desc("Total ticks spent accessing banks");
14279243SN/A
14289243SN/A    totBusLat
14299243SN/A        .name(name() + ".totBusLat")
14309977SN/A        .desc("Total ticks spent in databus transfers");
14319243SN/A
14329243SN/A    totMemAccLat
14339243SN/A        .name(name() + ".totMemAccLat")
14349977SN/A        .desc("Total ticks spent from burst creation until serviced "
14359977SN/A              "by the DRAM");
14369243SN/A
14379243SN/A    avgQLat
14389243SN/A        .name(name() + ".avgQLat")
14399977SN/A        .desc("Average queueing delay per DRAM burst")
14409243SN/A        .precision(2);
14419243SN/A
14429831SN/A    avgQLat = totQLat / (readBursts - servicedByWrQ);
14439243SN/A
14449243SN/A    avgBankLat
14459243SN/A        .name(name() + ".avgBankLat")
14469977SN/A        .desc("Average bank access latency per DRAM burst")
14479243SN/A        .precision(2);
14489243SN/A
14499831SN/A    avgBankLat = totBankLat / (readBursts - servicedByWrQ);
14509243SN/A
14519243SN/A    avgBusLat
14529243SN/A        .name(name() + ".avgBusLat")
14539977SN/A        .desc("Average bus latency per DRAM burst")
14549243SN/A        .precision(2);
14559243SN/A
14569831SN/A    avgBusLat = totBusLat / (readBursts - servicedByWrQ);
14579243SN/A
14589243SN/A    avgMemAccLat
14599243SN/A        .name(name() + ".avgMemAccLat")
14609977SN/A        .desc("Average memory access latency per DRAM burst")
14619243SN/A        .precision(2);
14629243SN/A
14639831SN/A    avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
14649243SN/A
14659243SN/A    numRdRetry
14669243SN/A        .name(name() + ".numRdRetry")
14679977SN/A        .desc("Number of times read queue was full causing retry");
14689243SN/A
14699243SN/A    numWrRetry
14709243SN/A        .name(name() + ".numWrRetry")
14719977SN/A        .desc("Number of times write queue was full causing retry");
14729243SN/A
14739243SN/A    readRowHits
14749243SN/A        .name(name() + ".readRowHits")
14759243SN/A        .desc("Number of row buffer hits during reads");
14769243SN/A
14779243SN/A    writeRowHits
14789243SN/A        .name(name() + ".writeRowHits")
14799243SN/A        .desc("Number of row buffer hits during writes");
14809243SN/A
14819243SN/A    readRowHitRate
14829243SN/A        .name(name() + ".readRowHitRate")
14839243SN/A        .desc("Row buffer hit rate for reads")
14849243SN/A        .precision(2);
14859243SN/A
14869831SN/A    readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
14879243SN/A
14889243SN/A    writeRowHitRate
14899243SN/A        .name(name() + ".writeRowHitRate")
14909243SN/A        .desc("Row buffer hit rate for writes")
14919243SN/A        .precision(2);
14929243SN/A
14939977SN/A    writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
14949243SN/A
14959243SN/A    readPktSize
14969831SN/A        .init(ceilLog2(burstSize) + 1)
14979243SN/A        .name(name() + ".readPktSize")
14989977SN/A        .desc("Read request sizes (log2)");
14999243SN/A
15009243SN/A     writePktSize
15019831SN/A        .init(ceilLog2(burstSize) + 1)
15029243SN/A        .name(name() + ".writePktSize")
15039977SN/A        .desc("Write request sizes (log2)");
15049243SN/A
15059243SN/A     rdQLenPdf
15069567SN/A        .init(readBufferSize)
15079243SN/A        .name(name() + ".rdQLenPdf")
15089243SN/A        .desc("What read queue length does an incoming req see");
15099243SN/A
15109243SN/A     wrQLenPdf
15119567SN/A        .init(writeBufferSize)
15129243SN/A        .name(name() + ".wrQLenPdf")
15139243SN/A        .desc("What write queue length does an incoming req see");
15149243SN/A
15159727SN/A     bytesPerActivate
151610141SN/A         .init(maxAccessesPerRow)
15179727SN/A         .name(name() + ".bytesPerActivate")
15189727SN/A         .desc("Bytes accessed per row activation")
15199727SN/A         .flags(nozero);
15209243SN/A
15219975SN/A    bytesReadDRAM
15229975SN/A        .name(name() + ".bytesReadDRAM")
15239975SN/A        .desc("Total number of bytes read from DRAM");
15249975SN/A
15259975SN/A    bytesReadWrQ
15269975SN/A        .name(name() + ".bytesReadWrQ")
15279975SN/A        .desc("Total number of bytes read from write queue");
15289243SN/A
15299243SN/A    bytesWritten
15309243SN/A        .name(name() + ".bytesWritten")
15319977SN/A        .desc("Total number of bytes written to DRAM");
15329243SN/A
15339977SN/A    bytesReadSys
15349977SN/A        .name(name() + ".bytesReadSys")
15359977SN/A        .desc("Total read bytes from the system interface side");
15369243SN/A
15379977SN/A    bytesWrittenSys
15389977SN/A        .name(name() + ".bytesWrittenSys")
15399977SN/A        .desc("Total written bytes from the system interface side");
15409243SN/A
15419243SN/A    avgRdBW
15429243SN/A        .name(name() + ".avgRdBW")
15439977SN/A        .desc("Average DRAM read bandwidth in MiByte/s")
15449243SN/A        .precision(2);
15459243SN/A
15469977SN/A    avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
15479243SN/A
15489243SN/A    avgWrBW
15499243SN/A        .name(name() + ".avgWrBW")
15509977SN/A        .desc("Average achieved write bandwidth in MiByte/s")
15519243SN/A        .precision(2);
15529243SN/A
15539243SN/A    avgWrBW = (bytesWritten / 1000000) / simSeconds;
15549243SN/A
15559977SN/A    avgRdBWSys
15569977SN/A        .name(name() + ".avgRdBWSys")
15579977SN/A        .desc("Average system read bandwidth in MiByte/s")
15589243SN/A        .precision(2);
15599243SN/A
15609977SN/A    avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
15619243SN/A
15629977SN/A    avgWrBWSys
15639977SN/A        .name(name() + ".avgWrBWSys")
15649977SN/A        .desc("Average system write bandwidth in MiByte/s")
15659243SN/A        .precision(2);
15669243SN/A
15679977SN/A    avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
15689243SN/A
15699243SN/A    peakBW
15709243SN/A        .name(name() + ".peakBW")
15719977SN/A        .desc("Theoretical peak bandwidth in MiByte/s")
15729243SN/A        .precision(2);
15739243SN/A
15749831SN/A    peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
15759243SN/A
15769243SN/A    busUtil
15779243SN/A        .name(name() + ".busUtil")
15789243SN/A        .desc("Data bus utilization in percentage")
15799243SN/A        .precision(2);
15809243SN/A
15819243SN/A    busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
15829243SN/A
15839243SN/A    totGap
15849243SN/A        .name(name() + ".totGap")
15859243SN/A        .desc("Total gap between requests");
15869243SN/A
15879243SN/A    avgGap
15889243SN/A        .name(name() + ".avgGap")
15899243SN/A        .desc("Average gap between requests")
15909243SN/A        .precision(2);
15919243SN/A
15929243SN/A    avgGap = totGap / (readReqs + writeReqs);
15939975SN/A
15949975SN/A    // Stats for DRAM Power calculation based on Micron datasheet
15959975SN/A    busUtilRead
15969975SN/A        .name(name() + ".busUtilRead")
15979975SN/A        .desc("Data bus utilization in percentage for reads")
15989975SN/A        .precision(2);
15999975SN/A
16009975SN/A    busUtilRead = avgRdBW / peakBW * 100;
16019975SN/A
16029975SN/A    busUtilWrite
16039975SN/A        .name(name() + ".busUtilWrite")
16049975SN/A        .desc("Data bus utilization in percentage for writes")
16059975SN/A        .precision(2);
16069975SN/A
16079975SN/A    busUtilWrite = avgWrBW / peakBW * 100;
16089975SN/A
16099975SN/A    pageHitRate
16109975SN/A        .name(name() + ".pageHitRate")
16119975SN/A        .desc("Row buffer hit rate, read and write combined")
16129975SN/A        .precision(2);
16139975SN/A
16149977SN/A    pageHitRate = (writeRowHits + readRowHits) /
16159977SN/A        (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
16169975SN/A
16179975SN/A    prechargeAllPercent
16189975SN/A        .name(name() + ".prechargeAllPercent")
16199975SN/A        .desc("Percentage of time for which DRAM has all the banks in "
16209975SN/A              "precharge state")
16219975SN/A        .precision(2);
16229975SN/A
16239975SN/A    prechargeAllPercent = prechargeAllTime / simTicks * 100;
16249243SN/A}
16259243SN/A
16269243SN/Avoid
162710146Sandreas.hansson@arm.comDRAMCtrl::recvFunctional(PacketPtr pkt)
16289243SN/A{
16299243SN/A    // rely on the abstract memory
16309243SN/A    functionalAccess(pkt);
16319243SN/A}
16329243SN/A
16339294SN/ABaseSlavePort&
163410146Sandreas.hansson@arm.comDRAMCtrl::getSlavePort(const string &if_name, PortID idx)
16359243SN/A{
16369243SN/A    if (if_name != "port") {
16379243SN/A        return MemObject::getSlavePort(if_name, idx);
16389243SN/A    } else {
16399243SN/A        return port;
16409243SN/A    }
16419243SN/A}
16429243SN/A
16439243SN/Aunsigned int
164410146Sandreas.hansson@arm.comDRAMCtrl::drain(DrainManager *dm)
16459243SN/A{
16469342SN/A    unsigned int count = port.drain(dm);
16479243SN/A
16489243SN/A    // if there is anything in any of our internal queues, keep track
16499243SN/A    // of that as well
16509567SN/A    if (!(writeQueue.empty() && readQueue.empty() &&
16519567SN/A          respQueue.empty())) {
16529352SN/A        DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
16539567SN/A                " resp: %d\n", writeQueue.size(), readQueue.size(),
16549567SN/A                respQueue.size());
16559243SN/A        ++count;
16569342SN/A        drainManager = dm;
16579352SN/A        // the only part that is not drained automatically over time
16589352SN/A        // is the write queue, thus trigger writes if there are any
16599352SN/A        // waiting and no reads waiting, otherwise wait until the
16609352SN/A        // reads are done
16619567SN/A        if (readQueue.empty() && !writeQueue.empty() &&
16629352SN/A            !writeEvent.scheduled())
16639352SN/A            triggerWrites();
16649243SN/A    }
16659243SN/A
16669243SN/A    if (count)
16679342SN/A        setDrainState(Drainable::Draining);
16689243SN/A    else
16699342SN/A        setDrainState(Drainable::Drained);
16709243SN/A    return count;
16719243SN/A}
16729243SN/A
167310146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
16749243SN/A    : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
16759243SN/A      memory(_memory)
16769243SN/A{ }
16779243SN/A
16789243SN/AAddrRangeList
167910146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::getAddrRanges() const
16809243SN/A{
16819243SN/A    AddrRangeList ranges;
16829243SN/A    ranges.push_back(memory.getAddrRange());
16839243SN/A    return ranges;
16849243SN/A}
16859243SN/A
16869243SN/Avoid
168710146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
16889243SN/A{
16899243SN/A    pkt->pushLabel(memory.name());
16909243SN/A
16919243SN/A    if (!queue.checkFunctional(pkt)) {
16929243SN/A        // Default implementation of SimpleTimingPort::recvFunctional()
16939243SN/A        // calls recvAtomic() and throws away the latency; we can save a
16949243SN/A        // little here by just not calculating the latency.
16959243SN/A        memory.recvFunctional(pkt);
16969243SN/A    }
16979243SN/A
16989243SN/A    pkt->popLabel();
16999243SN/A}
17009243SN/A
17019243SN/ATick
170210146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt)
17039243SN/A{
17049243SN/A    return memory.recvAtomic(pkt);
17059243SN/A}
17069243SN/A
17079243SN/Abool
170810146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt)
17099243SN/A{
17109243SN/A    // pass it to the memory controller
17119243SN/A    return memory.recvTimingReq(pkt);
17129243SN/A}
17139243SN/A
171410146Sandreas.hansson@arm.comDRAMCtrl*
171510146Sandreas.hansson@arm.comDRAMCtrlParams::create()
17169243SN/A{
171710146Sandreas.hansson@arm.com    return new DRAMCtrl(this);
17189243SN/A}
1719