dram_ctrl.cc revision 10206
19243SN/A/*
210206Sandreas.hansson@arm.com * Copyright (c) 2010-2014 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),
5810206Sandreas.hansson@arm.com    rowHitFlag(false), busState(READ),
5910206Sandreas.hansson@arm.com    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),
7310147Sandreas.hansson@arm.com    minWritesPerSwitch(p->min_writes_per_switch),
7410147Sandreas.hansson@arm.com    writesThisTime(0), readsThisTime(0),
7510206Sandreas.hansson@arm.com    tWTR(p->tWTR), tRTW(p->tRTW), tBURST(p->tBURST),
769963SN/A    tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
779971SN/A    tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
789488SN/A    tXAW(p->tXAW), activationLimit(p->activation_limit),
799243SN/A    memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
809243SN/A    pageMgmt(p->page_policy),
8110141SN/A    maxAccessesPerRow(p->max_accesses_per_row),
829726SN/A    frontendLatency(p->static_frontend_latency),
839726SN/A    backendLatency(p->static_backend_latency),
8410143SN/A    busBusyUntil(0),  prevArrival(0),
8510206Sandreas.hansson@arm.com    nextReqTime(0), startTickPrechargeAll(0), numBanksActive(0)
869243SN/A{
879243SN/A    // create the bank states based on the dimensions of the ranks and
889243SN/A    // banks
899243SN/A    banks.resize(ranksPerChannel);
909969SN/A    actTicks.resize(ranksPerChannel);
919243SN/A    for (size_t c = 0; c < ranksPerChannel; ++c) {
929243SN/A        banks[c].resize(banksPerRank);
939969SN/A        actTicks[c].resize(activationLimit, 0);
949243SN/A    }
959243SN/A
9610140SN/A    // perform a basic check of the write thresholds
9710140SN/A    if (p->write_low_thresh_perc >= p->write_high_thresh_perc)
9810140SN/A        fatal("Write buffer low threshold %d must be smaller than the "
9910140SN/A              "high threshold %d\n", p->write_low_thresh_perc,
10010140SN/A              p->write_high_thresh_perc);
1019243SN/A
1029243SN/A    // determine the rows per bank by looking at the total capacity
1039567SN/A    uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
1049243SN/A
1059243SN/A    DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
1069243SN/A            AbstractMemory::size());
1079831SN/A
1089831SN/A    DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
1099831SN/A            rowBufferSize, columnsPerRowBuffer);
1109831SN/A
1119831SN/A    rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
1129243SN/A
1139566SN/A    if (range.interleaved()) {
1149566SN/A        if (channels != range.stripes())
11510143SN/A            fatal("%s has %d interleaved address stripes but %d channel(s)\n",
1169566SN/A                  name(), range.stripes(), channels);
1179566SN/A
11810136SN/A        if (addrMapping == Enums::RoRaBaChCo) {
1199831SN/A            if (rowBufferSize != range.granularity()) {
12010143SN/A                fatal("Interleaving of %s doesn't match RoRaBaChCo "
12110136SN/A                      "address map\n", name());
1229566SN/A            }
12310136SN/A        } else if (addrMapping == Enums::RoRaBaCoCh) {
12410136SN/A            if (system()->cacheLineSize() != range.granularity()) {
12510143SN/A                fatal("Interleaving of %s doesn't match RoRaBaCoCh "
12610136SN/A                      "address map\n", name());
1279669SN/A            }
12810136SN/A        } else if (addrMapping == Enums::RoCoRaBaCh) {
12910136SN/A            if (system()->cacheLineSize() != range.granularity())
13010143SN/A                fatal("Interleaving of %s doesn't match RoCoRaBaCh "
13110136SN/A                      "address map\n", name());
1329566SN/A        }
1339566SN/A    }
1349243SN/A}
1359243SN/A
1369243SN/Avoid
13710146Sandreas.hansson@arm.comDRAMCtrl::init()
13810140SN/A{
13910140SN/A    if (!port.isConnected()) {
14010146Sandreas.hansson@arm.com        fatal("DRAMCtrl %s is unconnected!\n", name());
14110140SN/A    } else {
14210140SN/A        port.sendRangeChange();
14310140SN/A    }
14410140SN/A}
14510140SN/A
14610140SN/Avoid
14710146Sandreas.hansson@arm.comDRAMCtrl::startup()
1489243SN/A{
14910143SN/A    // update the start tick for the precharge accounting to the
15010143SN/A    // current tick
15110143SN/A    startTickPrechargeAll = curTick();
15210143SN/A
15310206Sandreas.hansson@arm.com    // shift the bus busy time sufficiently far ahead that we never
15410206Sandreas.hansson@arm.com    // have to worry about negative values when computing the time for
15510206Sandreas.hansson@arm.com    // the next request, this will add an insignificant bubble at the
15610206Sandreas.hansson@arm.com    // start of simulation
15710206Sandreas.hansson@arm.com    busBusyUntil = curTick() + tRP + tRCD + tCL;
15810206Sandreas.hansson@arm.com
1599243SN/A    // print the configuration of the controller
1609243SN/A    printParams();
1619243SN/A
1629243SN/A    // kick off the refresh
1639567SN/A    schedule(refreshEvent, curTick() + tREFI);
1649243SN/A}
1659243SN/A
1669243SN/ATick
16710146Sandreas.hansson@arm.comDRAMCtrl::recvAtomic(PacketPtr pkt)
1689243SN/A{
1699243SN/A    DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
1709243SN/A
1719243SN/A    // do the actual memory access and turn the packet into a response
1729243SN/A    access(pkt);
1739243SN/A
1749243SN/A    Tick latency = 0;
1759243SN/A    if (!pkt->memInhibitAsserted() && pkt->hasData()) {
1769243SN/A        // this value is not supposed to be accurate, just enough to
1779243SN/A        // keep things going, mimic a closed page
1789243SN/A        latency = tRP + tRCD + tCL;
1799243SN/A    }
1809243SN/A    return latency;
1819243SN/A}
1829243SN/A
1839243SN/Abool
18410146Sandreas.hansson@arm.comDRAMCtrl::readQueueFull(unsigned int neededEntries) const
1859243SN/A{
1869831SN/A    DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
1879831SN/A            readBufferSize, readQueue.size() + respQueue.size(),
1889831SN/A            neededEntries);
1899243SN/A
1909831SN/A    return
1919831SN/A        (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
1929243SN/A}
1939243SN/A
1949243SN/Abool
19510146Sandreas.hansson@arm.comDRAMCtrl::writeQueueFull(unsigned int neededEntries) const
1969243SN/A{
1979831SN/A    DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
1989831SN/A            writeBufferSize, writeQueue.size(), neededEntries);
1999831SN/A    return (writeQueue.size() + neededEntries) > writeBufferSize;
2009243SN/A}
2019243SN/A
20210146Sandreas.hansson@arm.comDRAMCtrl::DRAMPacket*
20310146Sandreas.hansson@arm.comDRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size,
20410143SN/A                       bool isRead)
2059243SN/A{
2069669SN/A    // decode the address based on the address mapping scheme, with
20710136SN/A    // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
20810136SN/A    // channel, respectively
2099243SN/A    uint8_t rank;
2109967SN/A    uint8_t bank;
2119243SN/A    uint16_t row;
2129243SN/A
2139243SN/A    // truncate the address to the access granularity
2149831SN/A    Addr addr = dramPktAddr / burstSize;
2159243SN/A
2169491SN/A    // we have removed the lowest order address bits that denote the
2179831SN/A    // position within the column
21810136SN/A    if (addrMapping == Enums::RoRaBaChCo) {
2199491SN/A        // the lowest order bits denote the column to ensure that
2209491SN/A        // sequential cache lines occupy the same row
2219831SN/A        addr = addr / columnsPerRowBuffer;
2229243SN/A
2239669SN/A        // take out the channel part of the address
2249566SN/A        addr = addr / channels;
2259566SN/A
2269669SN/A        // after the channel bits, get the bank bits to interleave
2279669SN/A        // over the banks
2289669SN/A        bank = addr % banksPerRank;
2299669SN/A        addr = addr / banksPerRank;
2309669SN/A
2319669SN/A        // after the bank, we get the rank bits which thus interleaves
2329669SN/A        // over the ranks
2339669SN/A        rank = addr % ranksPerChannel;
2349669SN/A        addr = addr / ranksPerChannel;
2359669SN/A
2369669SN/A        // lastly, get the row bits
2379669SN/A        row = addr % rowsPerBank;
2389669SN/A        addr = addr / rowsPerBank;
23910136SN/A    } else if (addrMapping == Enums::RoRaBaCoCh) {
2409669SN/A        // take out the channel part of the address
2419669SN/A        addr = addr / channels;
2429669SN/A
2439669SN/A        // next, the column
2449831SN/A        addr = addr / columnsPerRowBuffer;
2459669SN/A
2469669SN/A        // after the column bits, we get the bank bits to interleave
2479491SN/A        // over the banks
2489243SN/A        bank = addr % banksPerRank;
2499243SN/A        addr = addr / banksPerRank;
2509243SN/A
2519491SN/A        // after the bank, we get the rank bits which thus interleaves
2529491SN/A        // over the ranks
2539243SN/A        rank = addr % ranksPerChannel;
2549243SN/A        addr = addr / ranksPerChannel;
2559243SN/A
2569491SN/A        // lastly, get the row bits
2579243SN/A        row = addr % rowsPerBank;
2589243SN/A        addr = addr / rowsPerBank;
25910136SN/A    } else if (addrMapping == Enums::RoCoRaBaCh) {
2609491SN/A        // optimise for closed page mode and utilise maximum
2619491SN/A        // parallelism of the DRAM (at the cost of power)
2629491SN/A
2639566SN/A        // take out the channel part of the address, not that this has
2649566SN/A        // to match with how accesses are interleaved between the
2659566SN/A        // controllers in the address mapping
2669566SN/A        addr = addr / channels;
2679566SN/A
2689491SN/A        // start with the bank bits, as this provides the maximum
2699491SN/A        // opportunity for parallelism between requests
2709243SN/A        bank = addr % banksPerRank;
2719243SN/A        addr = addr / banksPerRank;
2729243SN/A
2739491SN/A        // next get the rank bits
2749243SN/A        rank = addr % ranksPerChannel;
2759243SN/A        addr = addr / ranksPerChannel;
2769243SN/A
2779491SN/A        // next the column bits which we do not need to keep track of
2789491SN/A        // and simply skip past
2799831SN/A        addr = addr / columnsPerRowBuffer;
2809243SN/A
2819491SN/A        // lastly, get the row bits
2829243SN/A        row = addr % rowsPerBank;
2839243SN/A        addr = addr / rowsPerBank;
2849243SN/A    } else
2859243SN/A        panic("Unknown address mapping policy chosen!");
2869243SN/A
2879243SN/A    assert(rank < ranksPerChannel);
2889243SN/A    assert(bank < banksPerRank);
2899243SN/A    assert(row < rowsPerBank);
2909243SN/A
2919243SN/A    DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
2929831SN/A            dramPktAddr, rank, bank, row);
2939243SN/A
2949243SN/A    // create the corresponding DRAM packet with the entry time and
2959567SN/A    // ready time set to the current tick, the latter will be updated
2969567SN/A    // later
2979967SN/A    uint16_t bank_id = banksPerRank * rank + bank;
2989967SN/A    return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
2999967SN/A                          size, banks[rank][bank]);
3009243SN/A}
3019243SN/A
3029243SN/Avoid
30310146Sandreas.hansson@arm.comDRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
3049243SN/A{
3059243SN/A    // only add to the read queue here. whenever the request is
3069243SN/A    // eventually done, set the readyTime, and call schedule()
3079243SN/A    assert(!pkt->isWrite());
3089243SN/A
3099831SN/A    assert(pktCount != 0);
3109831SN/A
3119831SN/A    // if the request size is larger than burst size, the pkt is split into
3129831SN/A    // multiple DRAM packets
3139831SN/A    // Note if the pkt starting address is not aligened to burst size, the
3149831SN/A    // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
3159831SN/A    // are aligned to burst size boundaries. This is to ensure we accurately
3169831SN/A    // check read packets against packets in write queue.
3179243SN/A    Addr addr = pkt->getAddr();
3189831SN/A    unsigned pktsServicedByWrQ = 0;
3199831SN/A    BurstHelper* burst_helper = NULL;
3209831SN/A    for (int cnt = 0; cnt < pktCount; ++cnt) {
3219831SN/A        unsigned size = std::min((addr | (burstSize - 1)) + 1,
3229831SN/A                        pkt->getAddr() + pkt->getSize()) - addr;
3239831SN/A        readPktSize[ceilLog2(size)]++;
3249831SN/A        readBursts++;
3259243SN/A
3269831SN/A        // First check write buffer to see if the data is already at
3279831SN/A        // the controller
3289831SN/A        bool foundInWrQ = false;
3299833SN/A        for (auto i = writeQueue.begin(); i != writeQueue.end(); ++i) {
3309832SN/A            // check if the read is subsumed in the write entry we are
3319832SN/A            // looking at
3329832SN/A            if ((*i)->addr <= addr &&
3339832SN/A                (addr + size) <= ((*i)->addr + (*i)->size)) {
3349831SN/A                foundInWrQ = true;
3359831SN/A                servicedByWrQ++;
3369831SN/A                pktsServicedByWrQ++;
3379831SN/A                DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
3389831SN/A                        "write queue\n", addr, size);
3399975SN/A                bytesReadWrQ += burstSize;
3409831SN/A                break;
3419831SN/A            }
3429243SN/A        }
3439831SN/A
3449831SN/A        // If not found in the write q, make a DRAM packet and
3459831SN/A        // push it onto the read queue
3469831SN/A        if (!foundInWrQ) {
3479831SN/A
3489831SN/A            // Make the burst helper for split packets
3499831SN/A            if (pktCount > 1 && burst_helper == NULL) {
3509831SN/A                DPRINTF(DRAM, "Read to addr %lld translates to %d "
3519831SN/A                        "dram requests\n", pkt->getAddr(), pktCount);
3529831SN/A                burst_helper = new BurstHelper(pktCount);
3539831SN/A            }
3549831SN/A
3559966SN/A            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
3569831SN/A            dram_pkt->burstHelper = burst_helper;
3579831SN/A
3589831SN/A            assert(!readQueueFull(1));
3599831SN/A            rdQLenPdf[readQueue.size() + respQueue.size()]++;
3609831SN/A
3619831SN/A            DPRINTF(DRAM, "Adding to read queue\n");
3629831SN/A
3639831SN/A            readQueue.push_back(dram_pkt);
3649831SN/A
3659831SN/A            // Update stats
3669831SN/A            avgRdQLen = readQueue.size() + respQueue.size();
3679831SN/A        }
3689831SN/A
3699831SN/A        // Starting address of next dram pkt (aligend to burstSize boundary)
3709831SN/A        addr = (addr | (burstSize - 1)) + 1;
3719243SN/A    }
3729243SN/A
3739831SN/A    // If all packets are serviced by write queue, we send the repsonse back
3749831SN/A    if (pktsServicedByWrQ == pktCount) {
3759831SN/A        accessAndRespond(pkt, frontendLatency);
3769831SN/A        return;
3779831SN/A    }
3789243SN/A
3799831SN/A    // Update how many split packets are serviced by write queue
3809831SN/A    if (burst_helper != NULL)
3819831SN/A        burst_helper->burstsServiced = pktsServicedByWrQ;
3829243SN/A
38310206Sandreas.hansson@arm.com    // If we are not already scheduled to get a request out of the
38410206Sandreas.hansson@arm.com    // queue, do so now
38510206Sandreas.hansson@arm.com    if (!nextReqEvent.scheduled()) {
3869567SN/A        DPRINTF(DRAM, "Request scheduled immediately\n");
3879567SN/A        schedule(nextReqEvent, curTick());
3889243SN/A    }
3899243SN/A}
3909243SN/A
3919243SN/Avoid
39210146Sandreas.hansson@arm.comDRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
3939243SN/A{
3949243SN/A    // only add to the write queue here. whenever the request is
3959243SN/A    // eventually done, set the readyTime, and call schedule()
3969243SN/A    assert(pkt->isWrite());
3979243SN/A
3989831SN/A    // if the request size is larger than burst size, the pkt is split into
3999831SN/A    // multiple DRAM packets
4009831SN/A    Addr addr = pkt->getAddr();
4019831SN/A    for (int cnt = 0; cnt < pktCount; ++cnt) {
4029831SN/A        unsigned size = std::min((addr | (burstSize - 1)) + 1,
4039831SN/A                        pkt->getAddr() + pkt->getSize()) - addr;
4049831SN/A        writePktSize[ceilLog2(size)]++;
4059831SN/A        writeBursts++;
4069243SN/A
4079832SN/A        // see if we can merge with an existing item in the write
4089838SN/A        // queue and keep track of whether we have merged or not so we
4099838SN/A        // can stop at that point and also avoid enqueueing a new
4109838SN/A        // request
4119832SN/A        bool merged = false;
4129832SN/A        auto w = writeQueue.begin();
4139243SN/A
4149832SN/A        while(!merged && w != writeQueue.end()) {
4159832SN/A            // either of the two could be first, if they are the same
4169832SN/A            // it does not matter which way we go
4179832SN/A            if ((*w)->addr >= addr) {
4189838SN/A                // the existing one starts after the new one, figure
4199838SN/A                // out where the new one ends with respect to the
4209838SN/A                // existing one
4219832SN/A                if ((addr + size) >= ((*w)->addr + (*w)->size)) {
4229832SN/A                    // check if the existing one is completely
4239832SN/A                    // subsumed in the new one
4249832SN/A                    DPRINTF(DRAM, "Merging write covering existing burst\n");
4259832SN/A                    merged = true;
4269832SN/A                    // update both the address and the size
4279832SN/A                    (*w)->addr = addr;
4289832SN/A                    (*w)->size = size;
4299832SN/A                } else if ((addr + size) >= (*w)->addr &&
4309832SN/A                           ((*w)->addr + (*w)->size - addr) <= burstSize) {
4319832SN/A                    // the new one is just before or partially
4329832SN/A                    // overlapping with the existing one, and together
4339832SN/A                    // they fit within a burst
4349832SN/A                    DPRINTF(DRAM, "Merging write before existing burst\n");
4359832SN/A                    merged = true;
4369832SN/A                    // the existing queue item needs to be adjusted with
4379832SN/A                    // respect to both address and size
43810047SN/A                    (*w)->size = (*w)->addr + (*w)->size - addr;
4399832SN/A                    (*w)->addr = addr;
4409832SN/A                }
4419832SN/A            } else {
4429838SN/A                // the new one starts after the current one, figure
4439838SN/A                // out where the existing one ends with respect to the
4449838SN/A                // new one
4459832SN/A                if (((*w)->addr + (*w)->size) >= (addr + size)) {
4469832SN/A                    // check if the new one is completely subsumed in the
4479832SN/A                    // existing one
4489832SN/A                    DPRINTF(DRAM, "Merging write into existing burst\n");
4499832SN/A                    merged = true;
4509832SN/A                    // no adjustments necessary
4519832SN/A                } else if (((*w)->addr + (*w)->size) >= addr &&
4529832SN/A                           (addr + size - (*w)->addr) <= burstSize) {
4539832SN/A                    // the existing one is just before or partially
4549832SN/A                    // overlapping with the new one, and together
4559832SN/A                    // they fit within a burst
4569832SN/A                    DPRINTF(DRAM, "Merging write after existing burst\n");
4579832SN/A                    merged = true;
4589832SN/A                    // the address is right, and only the size has
4599832SN/A                    // to be adjusted
4609832SN/A                    (*w)->size = addr + size - (*w)->addr;
4619832SN/A                }
4629832SN/A            }
4639832SN/A            ++w;
4649832SN/A        }
4659243SN/A
4669832SN/A        // if the item was not merged we need to create a new write
4679832SN/A        // and enqueue it
4689832SN/A        if (!merged) {
4699966SN/A            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
4709243SN/A
4719832SN/A            assert(writeQueue.size() < writeBufferSize);
4729832SN/A            wrQLenPdf[writeQueue.size()]++;
4739243SN/A
4749832SN/A            DPRINTF(DRAM, "Adding to write queue\n");
4759831SN/A
4769832SN/A            writeQueue.push_back(dram_pkt);
4779831SN/A
4789832SN/A            // Update stats
4799832SN/A            avgWrQLen = writeQueue.size();
4809977SN/A        } else {
4819977SN/A            // keep track of the fact that this burst effectively
4829977SN/A            // disappeared as it was merged with an existing one
4839977SN/A            mergedWrBursts++;
4849832SN/A        }
4859832SN/A
4869831SN/A        // Starting address of next dram pkt (aligend to burstSize boundary)
4879831SN/A        addr = (addr | (burstSize - 1)) + 1;
4889831SN/A    }
4899243SN/A
4909243SN/A    // we do not wait for the writes to be send to the actual memory,
4919243SN/A    // but instead take responsibility for the consistency here and
4929243SN/A    // snoop the write queue for any upcoming reads
4939831SN/A    // @todo, if a pkt size is larger than burst size, we might need a
4949831SN/A    // different front end latency
4959726SN/A    accessAndRespond(pkt, frontendLatency);
4969243SN/A
49710206Sandreas.hansson@arm.com    // If we are not already scheduled to get a request out of the
49810206Sandreas.hansson@arm.com    // queue, do so now
49910206Sandreas.hansson@arm.com    if (!nextReqEvent.scheduled()) {
50010206Sandreas.hansson@arm.com        DPRINTF(DRAM, "Request scheduled immediately\n");
50110206Sandreas.hansson@arm.com        schedule(nextReqEvent, curTick());
5029243SN/A    }
5039243SN/A}
5049243SN/A
5059243SN/Avoid
50610146Sandreas.hansson@arm.comDRAMCtrl::printParams() const
5079243SN/A{
5089243SN/A    // Sanity check print of important parameters
5099243SN/A    DPRINTF(DRAM,
5109243SN/A            "Memory controller %s physical organization\n"      \
5119831SN/A            "Number of devices per rank   %d\n"                 \
5129831SN/A            "Device bus width (in bits)   %d\n"                 \
51310143SN/A            "DRAM data bus burst (bytes)  %d\n"                 \
51410143SN/A            "Row buffer size (bytes)      %d\n"                 \
5159831SN/A            "Columns per row buffer       %d\n"                 \
5169831SN/A            "Rows    per bank             %d\n"                 \
5179831SN/A            "Banks   per rank             %d\n"                 \
5189831SN/A            "Ranks   per channel          %d\n"                 \
51910143SN/A            "Total mem capacity (bytes)   %u\n",
5209831SN/A            name(), devicesPerRank, deviceBusWidth, burstSize, rowBufferSize,
5219831SN/A            columnsPerRowBuffer, rowsPerBank, banksPerRank, ranksPerChannel,
5229831SN/A            rowBufferSize * rowsPerBank * banksPerRank * ranksPerChannel);
5239243SN/A
5249243SN/A    string scheduler =  memSchedPolicy == Enums::fcfs ? "FCFS" : "FR-FCFS";
52510136SN/A    string address_mapping = addrMapping == Enums::RoRaBaChCo ? "RoRaBaChCo" :
52610136SN/A        (addrMapping == Enums::RoRaBaCoCh ? "RoRaBaCoCh" : "RoCoRaBaCh");
5279973SN/A    string page_policy = pageMgmt == Enums::open ? "OPEN" :
52810144SN/A        (pageMgmt == Enums::open_adaptive ? "OPEN (adaptive)" :
52910144SN/A        (pageMgmt == Enums::close_adaptive ? "CLOSE (adaptive)" : "CLOSE"));
5309243SN/A
5319243SN/A    DPRINTF(DRAM,
5329243SN/A            "Memory controller %s characteristics\n"    \
5339243SN/A            "Read buffer size     %d\n"                 \
5349243SN/A            "Write buffer size    %d\n"                 \
53510140SN/A            "Write high thresh    %d\n"                 \
53610140SN/A            "Write low thresh     %d\n"                 \
5379243SN/A            "Scheduler            %s\n"                 \
5389243SN/A            "Address mapping      %s\n"                 \
5399243SN/A            "Page policy          %s\n",
5409972SN/A            name(), readBufferSize, writeBufferSize, writeHighThreshold,
54110140SN/A            writeLowThreshold, scheduler, address_mapping, page_policy);
5429243SN/A
5439243SN/A    DPRINTF(DRAM, "Memory controller %s timing specs\n" \
5449567SN/A            "tRCD      %d ticks\n"                        \
5459567SN/A            "tCL       %d ticks\n"                        \
5469567SN/A            "tRP       %d ticks\n"                        \
5479567SN/A            "tBURST    %d ticks\n"                        \
5489567SN/A            "tRFC      %d ticks\n"                        \
5499567SN/A            "tREFI     %d ticks\n"                        \
5509567SN/A            "tWTR      %d ticks\n"                        \
55110206Sandreas.hansson@arm.com            "tRTW      %d ticks\n"                        \
5529567SN/A            "tXAW (%d) %d ticks\n",
5539567SN/A            name(), tRCD, tCL, tRP, tBURST, tRFC, tREFI, tWTR,
55410206Sandreas.hansson@arm.com            tRTW, activationLimit, tXAW);
5559243SN/A}
5569243SN/A
5579243SN/Avoid
55810146Sandreas.hansson@arm.comDRAMCtrl::printQs() const {
5599243SN/A    DPRINTF(DRAM, "===READ QUEUE===\n\n");
5609833SN/A    for (auto i = readQueue.begin() ;  i != readQueue.end() ; ++i) {
5619243SN/A        DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
5629243SN/A    }
5639243SN/A    DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
5649833SN/A    for (auto i = respQueue.begin() ;  i != respQueue.end() ; ++i) {
5659243SN/A        DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
5669243SN/A    }
5679243SN/A    DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
5689833SN/A    for (auto i = writeQueue.begin() ;  i != writeQueue.end() ; ++i) {
5699243SN/A        DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
5709243SN/A    }
5719243SN/A}
5729243SN/A
5739243SN/Abool
57410146Sandreas.hansson@arm.comDRAMCtrl::recvTimingReq(PacketPtr pkt)
5759243SN/A{
5769349SN/A    /// @todo temporary hack to deal with memory corruption issues until
5779349SN/A    /// 4-phase transactions are complete
5789349SN/A    for (int x = 0; x < pendingDelete.size(); x++)
5799349SN/A        delete pendingDelete[x];
5809349SN/A    pendingDelete.clear();
5819349SN/A
5829243SN/A    // This is where we enter from the outside world
5839567SN/A    DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
5849831SN/A            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
5859243SN/A
5869567SN/A    // simply drop inhibited packets for now
5879567SN/A    if (pkt->memInhibitAsserted()) {
58810143SN/A        DPRINTF(DRAM, "Inhibited packet -- Dropping it now\n");
5899567SN/A        pendingDelete.push_back(pkt);
5909567SN/A        return true;
5919567SN/A    }
5929243SN/A
5939243SN/A    // Calc avg gap between requests
5949243SN/A    if (prevArrival != 0) {
5959243SN/A        totGap += curTick() - prevArrival;
5969243SN/A    }
5979243SN/A    prevArrival = curTick();
5989243SN/A
5999831SN/A
6009831SN/A    // Find out how many dram packets a pkt translates to
6019831SN/A    // If the burst size is equal or larger than the pkt size, then a pkt
6029831SN/A    // translates to only one dram packet. Otherwise, a pkt translates to
6039831SN/A    // multiple dram packets
6049243SN/A    unsigned size = pkt->getSize();
6059831SN/A    unsigned offset = pkt->getAddr() & (burstSize - 1);
6069831SN/A    unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
6079243SN/A
6089243SN/A    // check local buffers and do not accept if full
6099243SN/A    if (pkt->isRead()) {
6109567SN/A        assert(size != 0);
6119831SN/A        if (readQueueFull(dram_pkt_count)) {
6129567SN/A            DPRINTF(DRAM, "Read queue full, not accepting\n");
6139243SN/A            // remember that we have to retry this port
6149243SN/A            retryRdReq = true;
6159243SN/A            numRdRetry++;
6169243SN/A            return false;
6179243SN/A        } else {
6189831SN/A            addToReadQueue(pkt, dram_pkt_count);
6199243SN/A            readReqs++;
6209977SN/A            bytesReadSys += size;
6219243SN/A        }
6229243SN/A    } else if (pkt->isWrite()) {
6239567SN/A        assert(size != 0);
6249831SN/A        if (writeQueueFull(dram_pkt_count)) {
6259567SN/A            DPRINTF(DRAM, "Write queue full, not accepting\n");
6269243SN/A            // remember that we have to retry this port
6279243SN/A            retryWrReq = true;
6289243SN/A            numWrRetry++;
6299243SN/A            return false;
6309243SN/A        } else {
6319831SN/A            addToWriteQueue(pkt, dram_pkt_count);
6329243SN/A            writeReqs++;
6339977SN/A            bytesWrittenSys += size;
6349243SN/A        }
6359243SN/A    } else {
6369243SN/A        DPRINTF(DRAM,"Neither read nor write, ignore timing\n");
6379243SN/A        neitherReadNorWrite++;
6389726SN/A        accessAndRespond(pkt, 1);
6399243SN/A    }
6409243SN/A
6419243SN/A    return true;
6429243SN/A}
6439243SN/A
6449243SN/Avoid
64510146Sandreas.hansson@arm.comDRAMCtrl::processRespondEvent()
6469243SN/A{
6479243SN/A    DPRINTF(DRAM,
6489243SN/A            "processRespondEvent(): Some req has reached its readyTime\n");
6499243SN/A
6509831SN/A    DRAMPacket* dram_pkt = respQueue.front();
6519243SN/A
6529831SN/A    if (dram_pkt->burstHelper) {
6539831SN/A        // it is a split packet
6549831SN/A        dram_pkt->burstHelper->burstsServiced++;
6559831SN/A        if (dram_pkt->burstHelper->burstsServiced ==
65610143SN/A            dram_pkt->burstHelper->burstCount) {
6579831SN/A            // we have now serviced all children packets of a system packet
6589831SN/A            // so we can now respond to the requester
6599831SN/A            // @todo we probably want to have a different front end and back
6609831SN/A            // end latency for split packets
6619831SN/A            accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
6629831SN/A            delete dram_pkt->burstHelper;
6639831SN/A            dram_pkt->burstHelper = NULL;
6649831SN/A        }
6659831SN/A    } else {
6669831SN/A        // it is not a split packet
6679831SN/A        accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
6689831SN/A    }
6699243SN/A
6709831SN/A    delete respQueue.front();
6719831SN/A    respQueue.pop_front();
6729243SN/A
6739831SN/A    if (!respQueue.empty()) {
6749831SN/A        assert(respQueue.front()->readyTime >= curTick());
6759831SN/A        assert(!respondEvent.scheduled());
6769831SN/A        schedule(respondEvent, respQueue.front()->readyTime);
6779831SN/A    } else {
6789831SN/A        // if there is nothing left in any queue, signal a drain
6799831SN/A        if (writeQueue.empty() && readQueue.empty() &&
6809831SN/A            drainManager) {
6819831SN/A            drainManager->signalDrainDone();
6829831SN/A            drainManager = NULL;
6839831SN/A        }
6849831SN/A    }
6859567SN/A
6869831SN/A    // We have made a location in the queue available at this point,
6879831SN/A    // so if there is a read that was forced to wait, retry now
6889831SN/A    if (retryRdReq) {
6899831SN/A        retryRdReq = false;
6909831SN/A        port.sendRetry();
6919831SN/A    }
6929243SN/A}
6939243SN/A
6949243SN/Avoid
69510206Sandreas.hansson@arm.comDRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue)
6969243SN/A{
69710206Sandreas.hansson@arm.com    // This method does the arbitration between requests. The chosen
69810206Sandreas.hansson@arm.com    // packet is simply moved to the head of the queue. The other
69910206Sandreas.hansson@arm.com    // methods know that this is the place to look. For example, with
70010206Sandreas.hansson@arm.com    // FCFS, this method does nothing
70110206Sandreas.hansson@arm.com    assert(!queue.empty());
7029243SN/A
70310206Sandreas.hansson@arm.com    if (queue.size() == 1) {
70410206Sandreas.hansson@arm.com        DPRINTF(DRAM, "Single request, nothing to do\n");
7059243SN/A        return;
7069243SN/A    }
7079243SN/A
7089243SN/A    if (memSchedPolicy == Enums::fcfs) {
7099243SN/A        // Do nothing, since the correct request is already head
7109243SN/A    } else if (memSchedPolicy == Enums::frfcfs) {
71110206Sandreas.hansson@arm.com        reorderQueue(queue);
7129243SN/A    } else
7139243SN/A        panic("No scheduling policy chosen\n");
7149243SN/A}
7159243SN/A
7169243SN/Avoid
71710146Sandreas.hansson@arm.comDRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue)
7189974SN/A{
7199974SN/A    // Only determine this when needed
7209974SN/A    uint64_t earliest_banks = 0;
7219974SN/A
7229974SN/A    // Search for row hits first, if no row hit is found then schedule the
7239974SN/A    // packet to one of the earliest banks available
7249974SN/A    bool found_earliest_pkt = false;
7259974SN/A    auto selected_pkt_it = queue.begin();
7269974SN/A
7279974SN/A    for (auto i = queue.begin(); i != queue.end() ; ++i) {
7289974SN/A        DRAMPacket* dram_pkt = *i;
7299974SN/A        const Bank& bank = dram_pkt->bankRef;
7309974SN/A        // Check if it is a row hit
7319974SN/A        if (bank.openRow == dram_pkt->row) {
7329974SN/A            DPRINTF(DRAM, "Row buffer hit\n");
7339974SN/A            selected_pkt_it = i;
7349974SN/A            break;
7359974SN/A        } else if (!found_earliest_pkt) {
7369974SN/A            // No row hit, go for first ready
7379974SN/A            if (earliest_banks == 0)
7389974SN/A                earliest_banks = minBankFreeAt(queue);
7399974SN/A
7409974SN/A            // Bank is ready or is the first available bank
7419974SN/A            if (bank.freeAt <= curTick() ||
7429974SN/A                bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
7439974SN/A                // Remember the packet to be scheduled to one of the earliest
7449974SN/A                // banks available
7459974SN/A                selected_pkt_it = i;
7469974SN/A                found_earliest_pkt = true;
7479974SN/A            }
7489974SN/A        }
7499974SN/A    }
7509974SN/A
7519974SN/A    DRAMPacket* selected_pkt = *selected_pkt_it;
7529974SN/A    queue.erase(selected_pkt_it);
7539974SN/A    queue.push_front(selected_pkt);
7549974SN/A}
7559974SN/A
7569974SN/Avoid
75710146Sandreas.hansson@arm.comDRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
7589243SN/A{
7599243SN/A    DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
7609243SN/A
7619243SN/A    bool needsResponse = pkt->needsResponse();
7629243SN/A    // do the actual memory access which also turns the packet into a
7639243SN/A    // response
7649243SN/A    access(pkt);
7659243SN/A
7669243SN/A    // turn packet around to go back to requester if response expected
7679243SN/A    if (needsResponse) {
7689243SN/A        // access already turned the packet into a response
7699243SN/A        assert(pkt->isResponse());
7709243SN/A
7719549SN/A        // @todo someone should pay for this
7729549SN/A        pkt->busFirstWordDelay = pkt->busLastWordDelay = 0;
7739549SN/A
7749726SN/A        // queue the packet in the response queue to be sent out after
7759726SN/A        // the static latency has passed
7769726SN/A        port.schedTimingResp(pkt, curTick() + static_latency);
7779243SN/A    } else {
7789587SN/A        // @todo the packet is going to be deleted, and the DRAMPacket
7799587SN/A        // is still having a pointer to it
7809587SN/A        pendingDelete.push_back(pkt);
7819243SN/A    }
7829243SN/A
7839243SN/A    DPRINTF(DRAM, "Done\n");
7849243SN/A
7859243SN/A    return;
7869243SN/A}
7879243SN/A
7889243SN/Apair<Tick, Tick>
78910146Sandreas.hansson@arm.comDRAMCtrl::estimateLatency(DRAMPacket* dram_pkt, Tick inTime)
7909243SN/A{
7919243SN/A    // If a request reaches a bank at tick 'inTime', how much time
7929243SN/A    // *after* that does it take to finish the request, depending
7939243SN/A    // on bank status and page open policy. Note that this method
7949243SN/A    // considers only the time taken for the actual read or write
7959243SN/A    // to complete, NOT any additional time thereafter for tRAS or
7969243SN/A    // tRP.
7979243SN/A    Tick accLat = 0;
7989243SN/A    Tick bankLat = 0;
7999243SN/A    rowHitFlag = false;
8009969SN/A    Tick potentialActTick;
8019243SN/A
8029967SN/A    const Bank& bank = dram_pkt->bankRef;
80310144SN/A     // open-page policy or close_adaptive policy
80410144SN/A    if (pageMgmt == Enums::open || pageMgmt == Enums::open_adaptive ||
80510144SN/A        pageMgmt == Enums::close_adaptive) {
8069243SN/A        if (bank.openRow == dram_pkt->row) {
8079243SN/A            // When we have a row-buffer hit,
8089243SN/A            // we don't care about tRAS having expired or not,
8099243SN/A            // but do care about bank being free for access
8109243SN/A            rowHitFlag = true;
8119243SN/A
8129965SN/A            // When a series of requests arrive to the same row,
8139965SN/A            // DDR systems are capable of streaming data continuously
8149965SN/A            // at maximum bandwidth (subject to tCCD). Here, we approximate
8159965SN/A            // this condition, and assume that if whenever a bank is already
8169965SN/A            // busy and a new request comes in, it can be completed with no
8179965SN/A            // penalty beyond waiting for the existing read to complete.
8189965SN/A            if (bank.freeAt > inTime) {
8199965SN/A                accLat += bank.freeAt - inTime;
8209966SN/A                bankLat += 0;
8219965SN/A            } else {
8229243SN/A               // CAS latency only
8239243SN/A               accLat += tCL;
8249243SN/A               bankLat += tCL;
8259243SN/A            }
8269243SN/A
8279243SN/A        } else {
8289243SN/A            // Row-buffer miss, need to close existing row
8299243SN/A            // once tRAS has expired, then open the new one,
8309243SN/A            // then add cas latency.
8319243SN/A            Tick freeTime = std::max(bank.tRASDoneAt, bank.freeAt);
8329243SN/A
8339243SN/A            if (freeTime > inTime)
8349243SN/A               accLat += freeTime - inTime;
8359243SN/A
8369973SN/A            // If the there is no open row (open adaptive), then there
8379973SN/A            // is no precharge delay, otherwise go with tRP
8389973SN/A            Tick precharge_delay = bank.openRow == -1 ? 0 : tRP;
8399973SN/A
8409969SN/A            //The bank is free, and you may be able to activate
8419973SN/A            potentialActTick = inTime + accLat + precharge_delay;
8429969SN/A            if (potentialActTick < bank.actAllowedAt)
8439969SN/A                accLat += bank.actAllowedAt - potentialActTick;
8449969SN/A
8459973SN/A            accLat += precharge_delay + tRCD + tCL;
8469973SN/A            bankLat += precharge_delay + tRCD + tCL;
8479243SN/A        }
8489243SN/A    } else if (pageMgmt == Enums::close) {
8499243SN/A        // With a close page policy, no notion of
8509243SN/A        // bank.tRASDoneAt
8519243SN/A        if (bank.freeAt > inTime)
8529243SN/A            accLat += bank.freeAt - inTime;
8539243SN/A
8549969SN/A        //The bank is free, and you may be able to activate
8559969SN/A        potentialActTick = inTime + accLat;
8569969SN/A        if (potentialActTick < bank.actAllowedAt)
8579969SN/A            accLat += bank.actAllowedAt - potentialActTick;
8589969SN/A
8599243SN/A        // page already closed, simply open the row, and
8609243SN/A        // add cas latency
8619243SN/A        accLat += tRCD + tCL;
8629243SN/A        bankLat += tRCD + tCL;
8639243SN/A    } else
8649243SN/A        panic("No page management policy chosen\n");
8659243SN/A
8669487SN/A    DPRINTF(DRAM, "Returning < %lld, %lld > from estimateLatency()\n",
8679487SN/A            bankLat, accLat);
8689243SN/A
8699243SN/A    return make_pair(bankLat, accLat);
8709243SN/A}
8719243SN/A
8729243SN/Avoid
87310146Sandreas.hansson@arm.comDRAMCtrl::recordActivate(Tick act_tick, uint8_t rank, uint8_t bank)
8749488SN/A{
8759969SN/A    assert(0 <= rank && rank < ranksPerChannel);
8769969SN/A    assert(actTicks[rank].size() == activationLimit);
8779488SN/A
8789488SN/A    DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
8799488SN/A
8809975SN/A    // Tracking accesses after all banks are precharged.
8819975SN/A    // startTickPrechargeAll: is the tick when all the banks were again
8829975SN/A    // precharged. The difference between act_tick and startTickPrechargeAll
8839975SN/A    // gives the time for which DRAM doesn't get any accesses after refreshing
8849975SN/A    // or after a page is closed in closed-page or open-adaptive-page policy.
8859975SN/A    if ((numBanksActive == 0) && (act_tick > startTickPrechargeAll)) {
8869975SN/A        prechargeAllTime += act_tick - startTickPrechargeAll;
8879975SN/A    }
8889975SN/A
8899975SN/A    // No need to update number of active banks for closed-page policy as only 1
8909975SN/A    // bank will be activated at any given point, which will be instatntly
8919975SN/A    // precharged
89210144SN/A    if (pageMgmt == Enums::open || pageMgmt == Enums::open_adaptive ||
89310144SN/A        pageMgmt == Enums::close_adaptive)
8949975SN/A        ++numBanksActive;
8959975SN/A
8969971SN/A    // start by enforcing tRRD
8979971SN/A    for(int i = 0; i < banksPerRank; i++) {
8989971SN/A        // next activate must not happen before tRRD
8999971SN/A        banks[rank][i].actAllowedAt = act_tick + tRRD;
9009971SN/A    }
9019971SN/A    // tRC should be added to activation tick of the bank currently accessed,
9029971SN/A    // where tRC = tRAS + tRP, this is just for a check as actAllowedAt for same
9039971SN/A    // bank is already captured by bank.freeAt and bank.tRASDoneAt
9049971SN/A    banks[rank][bank].actAllowedAt = act_tick + tRAS + tRP;
9059971SN/A
9069971SN/A    // next, we deal with tXAW, if the activation limit is disabled
9079971SN/A    // then we are done
9089969SN/A    if (actTicks[rank].empty())
9099824SN/A        return;
9109824SN/A
9119488SN/A    // sanity check
9129969SN/A    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
9139825SN/A        // @todo For now, stick with a warning
9149825SN/A        warn("Got %d activates in window %d (%d - %d) which is smaller "
9159969SN/A             "than %d\n", activationLimit, act_tick - actTicks[rank].back(),
9169969SN/A             act_tick, actTicks[rank].back(), tXAW);
9179488SN/A    }
9189488SN/A
9199488SN/A    // shift the times used for the book keeping, the last element
9209488SN/A    // (highest index) is the oldest one and hence the lowest value
9219969SN/A    actTicks[rank].pop_back();
9229488SN/A
9239488SN/A    // record an new activation (in the future)
9249969SN/A    actTicks[rank].push_front(act_tick);
9259488SN/A
9269488SN/A    // cannot activate more than X times in time window tXAW, push the
9279488SN/A    // next one (the X + 1'st activate) to be tXAW away from the
9289488SN/A    // oldest in our window of X
9299969SN/A    if (actTicks[rank].back() && (act_tick - actTicks[rank].back()) < tXAW) {
9309488SN/A        DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate no earlier "
9319969SN/A                "than %d\n", activationLimit, actTicks[rank].back() + tXAW);
9329488SN/A            for(int j = 0; j < banksPerRank; j++)
9339488SN/A                // next activate must not happen before end of window
9349969SN/A                banks[rank][j].actAllowedAt = actTicks[rank].back() + tXAW;
9359488SN/A    }
9369488SN/A}
9379488SN/A
9389488SN/Avoid
93910146Sandreas.hansson@arm.comDRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
9409243SN/A{
9419243SN/A
9429243SN/A    DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
9439243SN/A            dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
9449243SN/A
9459243SN/A    // estimate the bank and access latency
9469243SN/A    pair<Tick, Tick> lat = estimateLatency(dram_pkt, curTick());
9479243SN/A    Tick bankLat = lat.first;
9489243SN/A    Tick accessLat = lat.second;
9499963SN/A    Tick actTick;
9509243SN/A
9519243SN/A    // This request was woken up at this time based on a prior call
9529243SN/A    // to estimateLatency(). However, between then and now, both the
9539243SN/A    // accessLatency and/or busBusyUntil may have changed. We need
9549243SN/A    // to correct for that.
9559243SN/A
9569243SN/A    Tick addDelay = (curTick() + accessLat < busBusyUntil) ?
9579243SN/A        busBusyUntil - (curTick() + accessLat) : 0;
9589243SN/A
9599967SN/A    Bank& bank = dram_pkt->bankRef;
9609243SN/A
9619243SN/A    // Update bank state
96210144SN/A    if (pageMgmt == Enums::open || pageMgmt == Enums::open_adaptive ||
96310144SN/A        pageMgmt == Enums::close_adaptive) {
9649243SN/A        bank.freeAt = curTick() + addDelay + accessLat;
9659727SN/A
9669243SN/A        // If you activated a new row do to this access, the next access
9679963SN/A        // will have to respect tRAS for this bank.
9689488SN/A        if (!rowHitFlag) {
9699963SN/A            // any waiting for banks account for in freeAt
9709963SN/A            actTick = bank.freeAt - tCL - tRCD;
9719963SN/A            bank.tRASDoneAt = actTick + tRAS;
9729971SN/A            recordActivate(actTick, dram_pkt->rank, dram_pkt->bank);
9739963SN/A
97410142SN/A            // if we closed an open row as a result of this access,
97510142SN/A            // then sample the number of bytes accessed before
97610142SN/A            // resetting it
97710142SN/A            if (bank.openRow != -1)
97810142SN/A                bytesPerActivate.sample(bank.bytesAccessed);
97910142SN/A
98010142SN/A            // update the open row
98110142SN/A            bank.openRow = dram_pkt->row;
98210142SN/A
98310142SN/A            // start counting anew, this covers both the case when we
98410142SN/A            // auto-precharged, and when this access is forced to
98510142SN/A            // precharge
9869727SN/A            bank.bytesAccessed = 0;
98710141SN/A            bank.rowAccesses = 0;
9889488SN/A        }
9899973SN/A
99010141SN/A        // increment the bytes accessed and the accesses per row
99110141SN/A        bank.bytesAccessed += burstSize;
99210141SN/A        ++bank.rowAccesses;
99310141SN/A
99410141SN/A        // if we reached the max, then issue with an auto-precharge
99510141SN/A        bool auto_precharge = bank.rowAccesses == maxAccessesPerRow;
99610141SN/A
99710141SN/A        // if we did not hit the limit, we might still want to
99810141SN/A        // auto-precharge
99910144SN/A        if (!auto_precharge &&
100010144SN/A            (pageMgmt == Enums::open_adaptive ||
100110144SN/A             pageMgmt == Enums::close_adaptive)) {
100210144SN/A            // a twist on the open and close page policies:
100310144SN/A            // 1) open_adaptive page policy does not blindly keep the
10049973SN/A            // page open, but close it if there are no row hits, and there
10059973SN/A            // are bank conflicts in the queue
100610144SN/A            // 2) close_adaptive page policy does not blindly close the
100710144SN/A            // page, but closes it only if there are no row hits in the queue.
100810144SN/A            // In this case, only force an auto precharge when there
100910144SN/A            // are no same page hits in the queue
10109973SN/A            bool got_more_hits = false;
10119973SN/A            bool got_bank_conflict = false;
10129973SN/A
10139973SN/A            // either look at the read queue or write queue
10149973SN/A            const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
10159973SN/A                writeQueue;
10169973SN/A            auto p = queue.begin();
10179973SN/A            // make sure we are not considering the packet that we are
10189973SN/A            // currently dealing with (which is the head of the queue)
10199973SN/A            ++p;
10209973SN/A
102110144SN/A            // keep on looking until we have found required condition or
102210144SN/A            // reached the end
102310144SN/A            while (!(got_more_hits &&
102410144SN/A                    (got_bank_conflict || pageMgmt == Enums::close_adaptive)) &&
10259973SN/A                   p != queue.end()) {
10269973SN/A                bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
10279973SN/A                    (dram_pkt->bank == (*p)->bank);
10289973SN/A                bool same_row = dram_pkt->row == (*p)->row;
10299973SN/A                got_more_hits |= same_rank_bank && same_row;
10309973SN/A                got_bank_conflict |= same_rank_bank && !same_row;
10319973SN/A                ++p;
10329973SN/A            }
10339973SN/A
103410144SN/A            // auto pre-charge when either
103510144SN/A            // 1) open_adaptive policy, we have not got any more hits, and
103610144SN/A            //    have a bank conflict
103710144SN/A            // 2) close_adaptive policy and we have not got any more hits
103810144SN/A            auto_precharge = !got_more_hits &&
103910144SN/A                (got_bank_conflict || pageMgmt == Enums::close_adaptive);
104010141SN/A        }
104110141SN/A
104210141SN/A        // if this access should use auto-precharge, then we are
104310141SN/A        // closing the row
104410141SN/A        if (auto_precharge) {
104510141SN/A            bank.openRow = -1;
104610141SN/A            bank.freeAt = std::max(bank.freeAt, bank.tRASDoneAt) + tRP;
104710141SN/A            --numBanksActive;
104810141SN/A            if (numBanksActive == 0) {
104910141SN/A                startTickPrechargeAll = std::max(startTickPrechargeAll,
105010141SN/A                                                 bank.freeAt);
105110141SN/A                DPRINTF(DRAM, "All banks precharged at tick: %ld\n",
105210141SN/A                        startTickPrechargeAll);
10539973SN/A            }
105410142SN/A
105510142SN/A            // sample the bytes per activate here since we are closing
105610142SN/A            // the page
105710142SN/A            bytesPerActivate.sample(bank.bytesAccessed);
105810142SN/A
105910141SN/A            DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId);
10609973SN/A        }
10619973SN/A
10629971SN/A        DPRINTF(DRAM, "doDRAMAccess::bank.freeAt is %lld\n", bank.freeAt);
10639963SN/A    } else if (pageMgmt == Enums::close) {
10649963SN/A        actTick = curTick() + addDelay + accessLat - tRCD - tCL;
10659971SN/A        recordActivate(actTick, dram_pkt->rank, dram_pkt->bank);
10669963SN/A
10679963SN/A        // If the DRAM has a very quick tRAS, bank can be made free
10689963SN/A        // after consecutive tCL,tRCD,tRP times. In general, however,
10699963SN/A        // an additional wait is required to respect tRAS.
10709963SN/A        bank.freeAt = std::max(actTick + tRAS + tRP,
10719963SN/A                actTick + tRCD + tCL + tRP);
10729971SN/A        DPRINTF(DRAM, "doDRAMAccess::bank.freeAt is %lld\n", bank.freeAt);
10739831SN/A        bytesPerActivate.sample(burstSize);
10749975SN/A        startTickPrechargeAll = std::max(startTickPrechargeAll, bank.freeAt);
10759243SN/A    } else
10769243SN/A        panic("No page management policy chosen\n");
10779243SN/A
10789243SN/A    // Update request parameters
10799243SN/A    dram_pkt->readyTime = curTick() + addDelay + accessLat + tBURST;
10809243SN/A
10819243SN/A
10829243SN/A    DPRINTF(DRAM, "Req %lld: curtick is %lld accessLat is %d " \
10839243SN/A                  "readytime is %lld busbusyuntil is %lld. " \
10849243SN/A                  "Scheduling at readyTime\n", dram_pkt->addr,
10859243SN/A                   curTick(), accessLat, dram_pkt->readyTime, busBusyUntil);
10869243SN/A
10879243SN/A    // Make sure requests are not overlapping on the databus
108810206Sandreas.hansson@arm.com    assert(dram_pkt->readyTime - busBusyUntil >= tBURST);
10899243SN/A
10909243SN/A    // Update bus state
10919243SN/A    busBusyUntil = dram_pkt->readyTime;
10929243SN/A
10939243SN/A    DPRINTF(DRAM,"Access time is %lld\n",
10949243SN/A            dram_pkt->readyTime - dram_pkt->entryTime);
10959243SN/A
109610206Sandreas.hansson@arm.com    // Update the minimum timing between the requests, this is a
109710206Sandreas.hansson@arm.com    // conservative estimate of when we have to schedule the next
109810206Sandreas.hansson@arm.com    // request to not introduce any unecessary bubbles. In most cases
109910206Sandreas.hansson@arm.com    // we will wake up sooner than we have to.
110010206Sandreas.hansson@arm.com    nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
11019972SN/A
110210206Sandreas.hansson@arm.com    // Update the stats and schedule the next request
11039977SN/A    if (dram_pkt->isRead) {
110410147Sandreas.hansson@arm.com        ++readsThisTime;
11059977SN/A        if (rowHitFlag)
11069977SN/A            readRowHits++;
11079977SN/A        bytesReadDRAM += burstSize;
11089977SN/A        perBankRdBursts[dram_pkt->bankId]++;
110910206Sandreas.hansson@arm.com
111010206Sandreas.hansson@arm.com        // Update latency stats
111110206Sandreas.hansson@arm.com        totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
111210206Sandreas.hansson@arm.com        totBankLat += bankLat;
111310206Sandreas.hansson@arm.com        totBusLat += tBURST;
111410206Sandreas.hansson@arm.com        totQLat += dram_pkt->readyTime - dram_pkt->entryTime - bankLat -
111510206Sandreas.hansson@arm.com            tBURST;
11169977SN/A    } else {
111710147Sandreas.hansson@arm.com        ++writesThisTime;
11189977SN/A        if (rowHitFlag)
11199977SN/A            writeRowHits++;
11209977SN/A        bytesWritten += burstSize;
11219977SN/A        perBankWrBursts[dram_pkt->bankId]++;
11229243SN/A    }
11239243SN/A}
11249243SN/A
11259243SN/Avoid
112610146Sandreas.hansson@arm.comDRAMCtrl::moveToRespQ()
11279243SN/A{
11289243SN/A    // Remove from read queue
11299567SN/A    DRAMPacket* dram_pkt = readQueue.front();
11309567SN/A    readQueue.pop_front();
11319243SN/A
11329832SN/A    // sanity check
11339832SN/A    assert(dram_pkt->size <= burstSize);
11349832SN/A
11359243SN/A    // Insert into response queue sorted by readyTime
11369243SN/A    // It will be sent back to the requestor at its
11379243SN/A    // readyTime
11389567SN/A    if (respQueue.empty()) {
11399567SN/A        respQueue.push_front(dram_pkt);
11409243SN/A        assert(!respondEvent.scheduled());
11419243SN/A        assert(dram_pkt->readyTime >= curTick());
11429567SN/A        schedule(respondEvent, dram_pkt->readyTime);
11439243SN/A    } else {
11449243SN/A        bool done = false;
11459833SN/A        auto i = respQueue.begin();
11469567SN/A        while (!done && i != respQueue.end()) {
11479243SN/A            if ((*i)->readyTime > dram_pkt->readyTime) {
11489567SN/A                respQueue.insert(i, dram_pkt);
11499243SN/A                done = true;
11509243SN/A            }
11519243SN/A            ++i;
11529243SN/A        }
11539243SN/A
11549243SN/A        if (!done)
11559567SN/A            respQueue.push_back(dram_pkt);
11569243SN/A
11579243SN/A        assert(respondEvent.scheduled());
11589243SN/A
11599567SN/A        if (respQueue.front()->readyTime < respondEvent.when()) {
11609567SN/A            assert(respQueue.front()->readyTime >= curTick());
11619567SN/A            reschedule(respondEvent, respQueue.front()->readyTime);
11629243SN/A        }
11639243SN/A    }
11649243SN/A}
11659243SN/A
11669243SN/Avoid
116710206Sandreas.hansson@arm.comDRAMCtrl::processNextReqEvent()
11689243SN/A{
116910206Sandreas.hansson@arm.com    if (busState == READ_TO_WRITE) {
117010206Sandreas.hansson@arm.com        DPRINTF(DRAM, "Switching to writes after %d reads with %d reads "
117110206Sandreas.hansson@arm.com                "waiting\n", readsThisTime, readQueue.size());
11729243SN/A
117310206Sandreas.hansson@arm.com        // sample and reset the read-related stats as we are now
117410206Sandreas.hansson@arm.com        // transitioning to writes, and all reads are done
117510206Sandreas.hansson@arm.com        rdPerTurnAround.sample(readsThisTime);
117610206Sandreas.hansson@arm.com        readsThisTime = 0;
117710206Sandreas.hansson@arm.com
117810206Sandreas.hansson@arm.com        // now proceed to do the actual writes
117910206Sandreas.hansson@arm.com        busState = WRITE;
118010206Sandreas.hansson@arm.com    } else if (busState == WRITE_TO_READ) {
118110206Sandreas.hansson@arm.com        DPRINTF(DRAM, "Switching to reads after %d writes with %d writes "
118210206Sandreas.hansson@arm.com                "waiting\n", writesThisTime, writeQueue.size());
118310206Sandreas.hansson@arm.com
118410206Sandreas.hansson@arm.com        wrPerTurnAround.sample(writesThisTime);
118510206Sandreas.hansson@arm.com        writesThisTime = 0;
118610206Sandreas.hansson@arm.com
118710206Sandreas.hansson@arm.com        busState = READ;
118810206Sandreas.hansson@arm.com    }
118910206Sandreas.hansson@arm.com
119010206Sandreas.hansson@arm.com    // when we get here it is either a read or a write
119110206Sandreas.hansson@arm.com    if (busState == READ) {
119210206Sandreas.hansson@arm.com
119310206Sandreas.hansson@arm.com        // track if we should switch or not
119410206Sandreas.hansson@arm.com        bool switch_to_writes = false;
119510206Sandreas.hansson@arm.com
119610206Sandreas.hansson@arm.com        if (readQueue.empty()) {
119710206Sandreas.hansson@arm.com            // In the case there is no read request to go next,
119810206Sandreas.hansson@arm.com            // trigger writes if we have passed the low threshold (or
119910206Sandreas.hansson@arm.com            // if we are draining)
120010206Sandreas.hansson@arm.com            if (!writeQueue.empty() &&
120110206Sandreas.hansson@arm.com                (drainManager || writeQueue.size() > writeLowThreshold)) {
120210206Sandreas.hansson@arm.com
120310206Sandreas.hansson@arm.com                switch_to_writes = true;
120410206Sandreas.hansson@arm.com            } else {
120510206Sandreas.hansson@arm.com                // check if we are drained
120610206Sandreas.hansson@arm.com                if (respQueue.empty () && drainManager) {
120710206Sandreas.hansson@arm.com                    drainManager->signalDrainDone();
120810206Sandreas.hansson@arm.com                    drainManager = NULL;
120910206Sandreas.hansson@arm.com                }
121010206Sandreas.hansson@arm.com
121110206Sandreas.hansson@arm.com                // nothing to do, not even any point in scheduling an
121210206Sandreas.hansson@arm.com                // event for the next request
121310206Sandreas.hansson@arm.com                return;
121410206Sandreas.hansson@arm.com            }
121510206Sandreas.hansson@arm.com        } else {
121610206Sandreas.hansson@arm.com            // Figure out which read request goes next, and move it to the
121710206Sandreas.hansson@arm.com            // front of the read queue
121810206Sandreas.hansson@arm.com            chooseNext(readQueue);
121910206Sandreas.hansson@arm.com
122010206Sandreas.hansson@arm.com            doDRAMAccess(readQueue.front());
122110206Sandreas.hansson@arm.com
122210206Sandreas.hansson@arm.com            // At this point we're done dealing with the request
122310206Sandreas.hansson@arm.com            // It will be moved to a separate response queue with a
122410206Sandreas.hansson@arm.com            // correct readyTime, and eventually be sent back at that
122510206Sandreas.hansson@arm.com            // time
122610206Sandreas.hansson@arm.com            moveToRespQ();
122710206Sandreas.hansson@arm.com
122810206Sandreas.hansson@arm.com            // we have so many writes that we have to transition
122910206Sandreas.hansson@arm.com            if (writeQueue.size() > writeHighThreshold) {
123010206Sandreas.hansson@arm.com                switch_to_writes = true;
123110206Sandreas.hansson@arm.com            }
123210206Sandreas.hansson@arm.com        }
123310206Sandreas.hansson@arm.com
123410206Sandreas.hansson@arm.com        // switching to writes, either because the read queue is empty
123510206Sandreas.hansson@arm.com        // and the writes have passed the low threshold (or we are
123610206Sandreas.hansson@arm.com        // draining), or because the writes hit the hight threshold
123710206Sandreas.hansson@arm.com        if (switch_to_writes) {
123810206Sandreas.hansson@arm.com            // transition to writing
123910206Sandreas.hansson@arm.com            busState = READ_TO_WRITE;
124010206Sandreas.hansson@arm.com
124110206Sandreas.hansson@arm.com            // add a bubble to the data bus, as defined by the
124210206Sandreas.hansson@arm.com            // tRTW parameter
124310206Sandreas.hansson@arm.com            busBusyUntil += tRTW;
124410206Sandreas.hansson@arm.com
124510206Sandreas.hansson@arm.com            // update the minimum timing between the requests,
124610206Sandreas.hansson@arm.com            // this shifts us back in time far enough to do any
124710206Sandreas.hansson@arm.com            // bank preparation
124810206Sandreas.hansson@arm.com            nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
124910206Sandreas.hansson@arm.com        }
12509352SN/A    } else {
125110206Sandreas.hansson@arm.com        chooseNext(writeQueue);
125210206Sandreas.hansson@arm.com        DRAMPacket* dram_pkt = writeQueue.front();
125310206Sandreas.hansson@arm.com        // sanity check
125410206Sandreas.hansson@arm.com        assert(dram_pkt->size <= burstSize);
125510206Sandreas.hansson@arm.com        doDRAMAccess(dram_pkt);
125610206Sandreas.hansson@arm.com
125710206Sandreas.hansson@arm.com        writeQueue.pop_front();
125810206Sandreas.hansson@arm.com        delete dram_pkt;
125910206Sandreas.hansson@arm.com
126010206Sandreas.hansson@arm.com        // If we emptied the write queue, or got sufficiently below the
126110206Sandreas.hansson@arm.com        // threshold (using the minWritesPerSwitch as the hysteresis) and
126210206Sandreas.hansson@arm.com        // are not draining, or we have reads waiting and have done enough
126310206Sandreas.hansson@arm.com        // writes, then switch to reads.
126410206Sandreas.hansson@arm.com        if (writeQueue.empty() ||
126510206Sandreas.hansson@arm.com            (writeQueue.size() + minWritesPerSwitch < writeLowThreshold &&
126610206Sandreas.hansson@arm.com             !drainManager) ||
126710206Sandreas.hansson@arm.com            (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) {
126810206Sandreas.hansson@arm.com            // turn the bus back around for reads again
126910206Sandreas.hansson@arm.com            busState = WRITE_TO_READ;
127010206Sandreas.hansson@arm.com
127110206Sandreas.hansson@arm.com            // note that the we switch back to reads also in the idle
127210206Sandreas.hansson@arm.com            // case, which eventually will check for any draining and
127310206Sandreas.hansson@arm.com            // also pause any further scheduling if there is really
127410206Sandreas.hansson@arm.com            // nothing to do
127510206Sandreas.hansson@arm.com
127610206Sandreas.hansson@arm.com            // here we get a bit creative and shift the bus busy time not
127710206Sandreas.hansson@arm.com            // just the tWTR, but also a CAS latency to capture the fact
127810206Sandreas.hansson@arm.com            // that we are allowed to prepare a new bank, but not issue a
127910206Sandreas.hansson@arm.com            // read command until after tWTR, in essence we capture a
128010206Sandreas.hansson@arm.com            // bubble on the data bus that is tWTR + tCL
128110206Sandreas.hansson@arm.com            busBusyUntil += tWTR + tCL;
128210206Sandreas.hansson@arm.com
128310206Sandreas.hansson@arm.com            // update the minimum timing between the requests, this shifts
128410206Sandreas.hansson@arm.com            // us back in time far enough to do any bank preparation
128510206Sandreas.hansson@arm.com            nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
128610206Sandreas.hansson@arm.com        }
128710206Sandreas.hansson@arm.com    }
128810206Sandreas.hansson@arm.com
128910206Sandreas.hansson@arm.com    schedule(nextReqEvent, std::max(nextReqTime, curTick()));
129010206Sandreas.hansson@arm.com
129110206Sandreas.hansson@arm.com    // If there is space available and we have writes waiting then let
129210206Sandreas.hansson@arm.com    // them retry. This is done here to ensure that the retry does not
129310206Sandreas.hansson@arm.com    // cause a nextReqEvent to be scheduled before we do so as part of
129410206Sandreas.hansson@arm.com    // the next request processing
129510206Sandreas.hansson@arm.com    if (retryWrReq && writeQueue.size() < writeBufferSize) {
129610206Sandreas.hansson@arm.com        retryWrReq = false;
129710206Sandreas.hansson@arm.com        port.sendRetry();
12989352SN/A    }
12999243SN/A}
13009243SN/A
13019243SN/ATick
130210146Sandreas.hansson@arm.comDRAMCtrl::maxBankFreeAt() const
13039243SN/A{
13049243SN/A    Tick banksFree = 0;
13059243SN/A
13069243SN/A    for(int i = 0; i < ranksPerChannel; i++)
13079243SN/A        for(int j = 0; j < banksPerRank; j++)
13089243SN/A            banksFree = std::max(banks[i][j].freeAt, banksFree);
13099243SN/A
13109243SN/A    return banksFree;
13119243SN/A}
13129243SN/A
13139967SN/Auint64_t
131410146Sandreas.hansson@arm.comDRAMCtrl::minBankFreeAt(const deque<DRAMPacket*>& queue) const
13159967SN/A{
13169967SN/A    uint64_t bank_mask = 0;
13179967SN/A    Tick freeAt = MaxTick;
13189967SN/A
13199967SN/A    // detemrine if we have queued transactions targetting the
13209967SN/A    // bank in question
13219967SN/A    vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
13229967SN/A    for (auto p = queue.begin(); p != queue.end(); ++p) {
13239967SN/A        got_waiting[(*p)->bankId] = true;
13249967SN/A    }
13259967SN/A
13269967SN/A    for (int i = 0; i < ranksPerChannel; i++) {
13279967SN/A        for (int j = 0; j < banksPerRank; j++) {
13289967SN/A            // if we have waiting requests for the bank, and it is
13299967SN/A            // amongst the first available, update the mask
13309967SN/A            if (got_waiting[i * banksPerRank + j] &&
13319967SN/A                banks[i][j].freeAt <= freeAt) {
13329967SN/A                // reset bank mask if new minimum is found
13339967SN/A                if (banks[i][j].freeAt < freeAt)
13349967SN/A                    bank_mask = 0;
13359967SN/A                // set the bit corresponding to the available bank
13369967SN/A                uint8_t bit_index = i * ranksPerChannel + j;
13379967SN/A                replaceBits(bank_mask, bit_index, bit_index, 1);
13389967SN/A                freeAt = banks[i][j].freeAt;
13399967SN/A            }
13409967SN/A        }
13419967SN/A    }
13429967SN/A    return bank_mask;
13439967SN/A}
13449967SN/A
13459243SN/Avoid
134610146Sandreas.hansson@arm.comDRAMCtrl::processRefreshEvent()
13479243SN/A{
13489243SN/A    DPRINTF(DRAM, "Refreshing at tick %ld\n", curTick());
13499243SN/A
13509243SN/A    Tick banksFree = std::max(curTick(), maxBankFreeAt()) + tRFC;
13519243SN/A
13529243SN/A    for(int i = 0; i < ranksPerChannel; i++)
13539975SN/A        for(int j = 0; j < banksPerRank; j++) {
13549243SN/A            banks[i][j].freeAt = banksFree;
13559975SN/A            banks[i][j].openRow = -1;
13569975SN/A        }
13579975SN/A
13589975SN/A    // updating startTickPrechargeAll, isprechargeAll
13599975SN/A    numBanksActive = 0;
13609975SN/A    startTickPrechargeAll = banksFree;
13619243SN/A
13629567SN/A    schedule(refreshEvent, curTick() + tREFI);
13639243SN/A}
13649243SN/A
13659243SN/Avoid
136610146Sandreas.hansson@arm.comDRAMCtrl::regStats()
13679243SN/A{
13689243SN/A    using namespace Stats;
13699243SN/A
13709243SN/A    AbstractMemory::regStats();
13719243SN/A
13729243SN/A    readReqs
13739243SN/A        .name(name() + ".readReqs")
13749977SN/A        .desc("Number of read requests accepted");
13759243SN/A
13769243SN/A    writeReqs
13779243SN/A        .name(name() + ".writeReqs")
13789977SN/A        .desc("Number of write requests accepted");
13799831SN/A
13809831SN/A    readBursts
13819831SN/A        .name(name() + ".readBursts")
13829977SN/A        .desc("Number of DRAM read bursts, "
13839977SN/A              "including those serviced by the write queue");
13849831SN/A
13859831SN/A    writeBursts
13869831SN/A        .name(name() + ".writeBursts")
13879977SN/A        .desc("Number of DRAM write bursts, "
13889977SN/A              "including those merged in the write queue");
13899243SN/A
13909243SN/A    servicedByWrQ
13919243SN/A        .name(name() + ".servicedByWrQ")
13929977SN/A        .desc("Number of DRAM read bursts serviced by the write queue");
13939977SN/A
13949977SN/A    mergedWrBursts
13959977SN/A        .name(name() + ".mergedWrBursts")
13969977SN/A        .desc("Number of DRAM write bursts merged with an existing one");
13979243SN/A
13989243SN/A    neitherReadNorWrite
13999977SN/A        .name(name() + ".neitherReadNorWriteReqs")
14009977SN/A        .desc("Number of requests that are neither read nor write");
14019243SN/A
14029977SN/A    perBankRdBursts
14039243SN/A        .init(banksPerRank * ranksPerChannel)
14049977SN/A        .name(name() + ".perBankRdBursts")
14059977SN/A        .desc("Per bank write bursts");
14069243SN/A
14079977SN/A    perBankWrBursts
14089243SN/A        .init(banksPerRank * ranksPerChannel)
14099977SN/A        .name(name() + ".perBankWrBursts")
14109977SN/A        .desc("Per bank write bursts");
14119243SN/A
14129243SN/A    avgRdQLen
14139243SN/A        .name(name() + ".avgRdQLen")
14149977SN/A        .desc("Average read queue length when enqueuing")
14159243SN/A        .precision(2);
14169243SN/A
14179243SN/A    avgWrQLen
14189243SN/A        .name(name() + ".avgWrQLen")
14199977SN/A        .desc("Average write queue length when enqueuing")
14209243SN/A        .precision(2);
14219243SN/A
14229243SN/A    totQLat
14239243SN/A        .name(name() + ".totQLat")
14249977SN/A        .desc("Total ticks spent queuing");
14259243SN/A
14269243SN/A    totBankLat
14279243SN/A        .name(name() + ".totBankLat")
14289977SN/A        .desc("Total ticks spent accessing banks");
14299243SN/A
14309243SN/A    totBusLat
14319243SN/A        .name(name() + ".totBusLat")
14329977SN/A        .desc("Total ticks spent in databus transfers");
14339243SN/A
14349243SN/A    totMemAccLat
14359243SN/A        .name(name() + ".totMemAccLat")
14369977SN/A        .desc("Total ticks spent from burst creation until serviced "
14379977SN/A              "by the DRAM");
14389243SN/A
14399243SN/A    avgQLat
14409243SN/A        .name(name() + ".avgQLat")
14419977SN/A        .desc("Average queueing delay per DRAM burst")
14429243SN/A        .precision(2);
14439243SN/A
14449831SN/A    avgQLat = totQLat / (readBursts - servicedByWrQ);
14459243SN/A
14469243SN/A    avgBankLat
14479243SN/A        .name(name() + ".avgBankLat")
14489977SN/A        .desc("Average bank access latency per DRAM burst")
14499243SN/A        .precision(2);
14509243SN/A
14519831SN/A    avgBankLat = totBankLat / (readBursts - servicedByWrQ);
14529243SN/A
14539243SN/A    avgBusLat
14549243SN/A        .name(name() + ".avgBusLat")
14559977SN/A        .desc("Average bus latency per DRAM burst")
14569243SN/A        .precision(2);
14579243SN/A
14589831SN/A    avgBusLat = totBusLat / (readBursts - servicedByWrQ);
14599243SN/A
14609243SN/A    avgMemAccLat
14619243SN/A        .name(name() + ".avgMemAccLat")
14629977SN/A        .desc("Average memory access latency per DRAM burst")
14639243SN/A        .precision(2);
14649243SN/A
14659831SN/A    avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
14669243SN/A
14679243SN/A    numRdRetry
14689243SN/A        .name(name() + ".numRdRetry")
14699977SN/A        .desc("Number of times read queue was full causing retry");
14709243SN/A
14719243SN/A    numWrRetry
14729243SN/A        .name(name() + ".numWrRetry")
14739977SN/A        .desc("Number of times write queue was full causing retry");
14749243SN/A
14759243SN/A    readRowHits
14769243SN/A        .name(name() + ".readRowHits")
14779243SN/A        .desc("Number of row buffer hits during reads");
14789243SN/A
14799243SN/A    writeRowHits
14809243SN/A        .name(name() + ".writeRowHits")
14819243SN/A        .desc("Number of row buffer hits during writes");
14829243SN/A
14839243SN/A    readRowHitRate
14849243SN/A        .name(name() + ".readRowHitRate")
14859243SN/A        .desc("Row buffer hit rate for reads")
14869243SN/A        .precision(2);
14879243SN/A
14889831SN/A    readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
14899243SN/A
14909243SN/A    writeRowHitRate
14919243SN/A        .name(name() + ".writeRowHitRate")
14929243SN/A        .desc("Row buffer hit rate for writes")
14939243SN/A        .precision(2);
14949243SN/A
14959977SN/A    writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
14969243SN/A
14979243SN/A    readPktSize
14989831SN/A        .init(ceilLog2(burstSize) + 1)
14999243SN/A        .name(name() + ".readPktSize")
15009977SN/A        .desc("Read request sizes (log2)");
15019243SN/A
15029243SN/A     writePktSize
15039831SN/A        .init(ceilLog2(burstSize) + 1)
15049243SN/A        .name(name() + ".writePktSize")
15059977SN/A        .desc("Write request sizes (log2)");
15069243SN/A
15079243SN/A     rdQLenPdf
15089567SN/A        .init(readBufferSize)
15099243SN/A        .name(name() + ".rdQLenPdf")
15109243SN/A        .desc("What read queue length does an incoming req see");
15119243SN/A
15129243SN/A     wrQLenPdf
15139567SN/A        .init(writeBufferSize)
15149243SN/A        .name(name() + ".wrQLenPdf")
15159243SN/A        .desc("What write queue length does an incoming req see");
15169243SN/A
15179727SN/A     bytesPerActivate
151810141SN/A         .init(maxAccessesPerRow)
15199727SN/A         .name(name() + ".bytesPerActivate")
15209727SN/A         .desc("Bytes accessed per row activation")
15219727SN/A         .flags(nozero);
15229243SN/A
152310147Sandreas.hansson@arm.com     rdPerTurnAround
152410147Sandreas.hansson@arm.com         .init(readBufferSize)
152510147Sandreas.hansson@arm.com         .name(name() + ".rdPerTurnAround")
152610147Sandreas.hansson@arm.com         .desc("Reads before turning the bus around for writes")
152710147Sandreas.hansson@arm.com         .flags(nozero);
152810147Sandreas.hansson@arm.com
152910147Sandreas.hansson@arm.com     wrPerTurnAround
153010147Sandreas.hansson@arm.com         .init(writeBufferSize)
153110147Sandreas.hansson@arm.com         .name(name() + ".wrPerTurnAround")
153210147Sandreas.hansson@arm.com         .desc("Writes before turning the bus around for reads")
153310147Sandreas.hansson@arm.com         .flags(nozero);
153410147Sandreas.hansson@arm.com
15359975SN/A    bytesReadDRAM
15369975SN/A        .name(name() + ".bytesReadDRAM")
15379975SN/A        .desc("Total number of bytes read from DRAM");
15389975SN/A
15399975SN/A    bytesReadWrQ
15409975SN/A        .name(name() + ".bytesReadWrQ")
15419975SN/A        .desc("Total number of bytes read from write queue");
15429243SN/A
15439243SN/A    bytesWritten
15449243SN/A        .name(name() + ".bytesWritten")
15459977SN/A        .desc("Total number of bytes written to DRAM");
15469243SN/A
15479977SN/A    bytesReadSys
15489977SN/A        .name(name() + ".bytesReadSys")
15499977SN/A        .desc("Total read bytes from the system interface side");
15509243SN/A
15519977SN/A    bytesWrittenSys
15529977SN/A        .name(name() + ".bytesWrittenSys")
15539977SN/A        .desc("Total written bytes from the system interface side");
15549243SN/A
15559243SN/A    avgRdBW
15569243SN/A        .name(name() + ".avgRdBW")
15579977SN/A        .desc("Average DRAM read bandwidth in MiByte/s")
15589243SN/A        .precision(2);
15599243SN/A
15609977SN/A    avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
15619243SN/A
15629243SN/A    avgWrBW
15639243SN/A        .name(name() + ".avgWrBW")
15649977SN/A        .desc("Average achieved write bandwidth in MiByte/s")
15659243SN/A        .precision(2);
15669243SN/A
15679243SN/A    avgWrBW = (bytesWritten / 1000000) / simSeconds;
15689243SN/A
15699977SN/A    avgRdBWSys
15709977SN/A        .name(name() + ".avgRdBWSys")
15719977SN/A        .desc("Average system read bandwidth in MiByte/s")
15729243SN/A        .precision(2);
15739243SN/A
15749977SN/A    avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
15759243SN/A
15769977SN/A    avgWrBWSys
15779977SN/A        .name(name() + ".avgWrBWSys")
15789977SN/A        .desc("Average system write bandwidth in MiByte/s")
15799243SN/A        .precision(2);
15809243SN/A
15819977SN/A    avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
15829243SN/A
15839243SN/A    peakBW
15849243SN/A        .name(name() + ".peakBW")
15859977SN/A        .desc("Theoretical peak bandwidth in MiByte/s")
15869243SN/A        .precision(2);
15879243SN/A
15889831SN/A    peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
15899243SN/A
15909243SN/A    busUtil
15919243SN/A        .name(name() + ".busUtil")
15929243SN/A        .desc("Data bus utilization in percentage")
15939243SN/A        .precision(2);
15949243SN/A
15959243SN/A    busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
15969243SN/A
15979243SN/A    totGap
15989243SN/A        .name(name() + ".totGap")
15999243SN/A        .desc("Total gap between requests");
16009243SN/A
16019243SN/A    avgGap
16029243SN/A        .name(name() + ".avgGap")
16039243SN/A        .desc("Average gap between requests")
16049243SN/A        .precision(2);
16059243SN/A
16069243SN/A    avgGap = totGap / (readReqs + writeReqs);
16079975SN/A
16089975SN/A    // Stats for DRAM Power calculation based on Micron datasheet
16099975SN/A    busUtilRead
16109975SN/A        .name(name() + ".busUtilRead")
16119975SN/A        .desc("Data bus utilization in percentage for reads")
16129975SN/A        .precision(2);
16139975SN/A
16149975SN/A    busUtilRead = avgRdBW / peakBW * 100;
16159975SN/A
16169975SN/A    busUtilWrite
16179975SN/A        .name(name() + ".busUtilWrite")
16189975SN/A        .desc("Data bus utilization in percentage for writes")
16199975SN/A        .precision(2);
16209975SN/A
16219975SN/A    busUtilWrite = avgWrBW / peakBW * 100;
16229975SN/A
16239975SN/A    pageHitRate
16249975SN/A        .name(name() + ".pageHitRate")
16259975SN/A        .desc("Row buffer hit rate, read and write combined")
16269975SN/A        .precision(2);
16279975SN/A
16289977SN/A    pageHitRate = (writeRowHits + readRowHits) /
16299977SN/A        (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
16309975SN/A
16319975SN/A    prechargeAllPercent
16329975SN/A        .name(name() + ".prechargeAllPercent")
16339975SN/A        .desc("Percentage of time for which DRAM has all the banks in "
16349975SN/A              "precharge state")
16359975SN/A        .precision(2);
16369975SN/A
16379975SN/A    prechargeAllPercent = prechargeAllTime / simTicks * 100;
16389243SN/A}
16399243SN/A
16409243SN/Avoid
164110146Sandreas.hansson@arm.comDRAMCtrl::recvFunctional(PacketPtr pkt)
16429243SN/A{
16439243SN/A    // rely on the abstract memory
16449243SN/A    functionalAccess(pkt);
16459243SN/A}
16469243SN/A
16479294SN/ABaseSlavePort&
164810146Sandreas.hansson@arm.comDRAMCtrl::getSlavePort(const string &if_name, PortID idx)
16499243SN/A{
16509243SN/A    if (if_name != "port") {
16519243SN/A        return MemObject::getSlavePort(if_name, idx);
16529243SN/A    } else {
16539243SN/A        return port;
16549243SN/A    }
16559243SN/A}
16569243SN/A
16579243SN/Aunsigned int
165810146Sandreas.hansson@arm.comDRAMCtrl::drain(DrainManager *dm)
16599243SN/A{
16609342SN/A    unsigned int count = port.drain(dm);
16619243SN/A
16629243SN/A    // if there is anything in any of our internal queues, keep track
16639243SN/A    // of that as well
16649567SN/A    if (!(writeQueue.empty() && readQueue.empty() &&
16659567SN/A          respQueue.empty())) {
16669352SN/A        DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
16679567SN/A                " resp: %d\n", writeQueue.size(), readQueue.size(),
16689567SN/A                respQueue.size());
16699243SN/A        ++count;
16709342SN/A        drainManager = dm;
167110206Sandreas.hansson@arm.com
16729352SN/A        // the only part that is not drained automatically over time
167310206Sandreas.hansson@arm.com        // is the write queue, thus kick things into action if needed
167410206Sandreas.hansson@arm.com        if (!writeQueue.empty() && !nextReqEvent.scheduled()) {
167510206Sandreas.hansson@arm.com            schedule(nextReqEvent, curTick());
167610206Sandreas.hansson@arm.com        }
16779243SN/A    }
16789243SN/A
16799243SN/A    if (count)
16809342SN/A        setDrainState(Drainable::Draining);
16819243SN/A    else
16829342SN/A        setDrainState(Drainable::Drained);
16839243SN/A    return count;
16849243SN/A}
16859243SN/A
168610146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
16879243SN/A    : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
16889243SN/A      memory(_memory)
16899243SN/A{ }
16909243SN/A
16919243SN/AAddrRangeList
169210146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::getAddrRanges() const
16939243SN/A{
16949243SN/A    AddrRangeList ranges;
16959243SN/A    ranges.push_back(memory.getAddrRange());
16969243SN/A    return ranges;
16979243SN/A}
16989243SN/A
16999243SN/Avoid
170010146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
17019243SN/A{
17029243SN/A    pkt->pushLabel(memory.name());
17039243SN/A
17049243SN/A    if (!queue.checkFunctional(pkt)) {
17059243SN/A        // Default implementation of SimpleTimingPort::recvFunctional()
17069243SN/A        // calls recvAtomic() and throws away the latency; we can save a
17079243SN/A        // little here by just not calculating the latency.
17089243SN/A        memory.recvFunctional(pkt);
17099243SN/A    }
17109243SN/A
17119243SN/A    pkt->popLabel();
17129243SN/A}
17139243SN/A
17149243SN/ATick
171510146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt)
17169243SN/A{
17179243SN/A    return memory.recvAtomic(pkt);
17189243SN/A}
17199243SN/A
17209243SN/Abool
172110146Sandreas.hansson@arm.comDRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt)
17229243SN/A{
17239243SN/A    // pass it to the memory controller
17249243SN/A    return memory.recvTimingReq(pkt);
17259243SN/A}
17269243SN/A
172710146Sandreas.hansson@arm.comDRAMCtrl*
172810146Sandreas.hansson@arm.comDRAMCtrlParams::create()
17299243SN/A{
173010146Sandreas.hansson@arm.com    return new DRAMCtrl(this);
17319243SN/A}
1732