dram_ctrl.cc revision 14038:8ba13d8b7810
110923SN/A/*
210923SN/A * Copyright (c) 2010-2018 ARM Limited
310923SN/A * All rights reserved
410923SN/A *
510923SN/A * The license below extends only to copyright in the software and shall
610923SN/A * not be construed as granting a license to any other intellectual
710923SN/A * property including but not limited to intellectual property relating
810923SN/A * to a hardware implementation of the functionality of the software
910923SN/A * licensed hereunder.  You may use the software subject to the license
1010923SN/A * terms below provided that you ensure that this notice is replicated
1110923SN/A * unmodified and in its entirety in all distributions of the software,
1210923SN/A * modified or unmodified, in source code or in binary form.
1310923SN/A *
1410923SN/A * Copyright (c) 2013 Amin Farmahini-Farahani
1510923SN/A * All rights reserved.
1610923SN/A *
1710923SN/A * Redistribution and use in source and binary forms, with or without
1810923SN/A * modification, are permitted provided that the following conditions are
1910923SN/A * met: redistributions of source code must retain the above copyright
2010923SN/A * notice, this list of conditions and the following disclaimer;
2110923SN/A * redistributions in binary form must reproduce the above copyright
2210923SN/A * notice, this list of conditions and the following disclaimer in the
2310923SN/A * documentation and/or other materials provided with the distribution;
2410923SN/A * neither the name of the copyright holders nor the names of its
2510923SN/A * contributors may be used to endorse or promote products derived from
2610923SN/A * this software without specific prior written permission.
2710923SN/A *
2810923SN/A * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2910923SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3010923SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3110923SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3210923SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3310923SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3410923SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3510923SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3610923SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3710923SN/A * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3810923SN/A * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3910923SN/A *
4010923SN/A * Authors: Andreas Hansson
4111290Sgabor.dozsa@arm.com *          Ani Udipi
4210923SN/A *          Neha Agarwal
4310923SN/A *          Omar Naji
4411290Sgabor.dozsa@arm.com *          Wendy Elsasser
4510923SN/A *          Radhika Jagtap
4610923SN/A */
4710923SN/A
4810923SN/A#include "mem/dram_ctrl.hh"
4910923SN/A
5010923SN/A#include "base/bitfield.hh"
5111703Smichael.lebeane@amd.com#include "base/trace.hh"
5211290Sgabor.dozsa@arm.com#include "debug/DRAM.hh"
5311290Sgabor.dozsa@arm.com#include "debug/DRAMPower.hh"
5411263SN/A#include "debug/DRAMState.hh"
5510923SN/A#include "debug/Drain.hh"
5610923SN/A#include "debug/QOS.hh"
5711703Smichael.lebeane@amd.com#include "sim/system.hh"
5810923SN/A
5911290Sgabor.dozsa@arm.comusing namespace std;
6011290Sgabor.dozsa@arm.comusing namespace Data;
6111703Smichael.lebeane@amd.com
6211290Sgabor.dozsa@arm.comDRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
6311290Sgabor.dozsa@arm.com    QoS::MemCtrl(p),
6411290Sgabor.dozsa@arm.com    port(name() + ".port", *this), isTimingMode(false),
6511290Sgabor.dozsa@arm.com    retryRdReq(false), retryWrReq(false),
6611703Smichael.lebeane@amd.com    nextReqEvent([this]{ processNextReqEvent(); }, name()),
6710923SN/A    respondEvent([this]{ processRespondEvent(); }, name()),
6811290Sgabor.dozsa@arm.com    deviceSize(p->device_size),
6911290Sgabor.dozsa@arm.com    deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
7011290Sgabor.dozsa@arm.com    deviceRowBufferSize(p->device_rowbuffer_size),
7111703Smichael.lebeane@amd.com    devicesPerRank(p->devices_per_rank),
7211703Smichael.lebeane@amd.com    burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8),
7311290Sgabor.dozsa@arm.com    rowBufferSize(devicesPerRank * deviceRowBufferSize),
7411290Sgabor.dozsa@arm.com    columnsPerRowBuffer(rowBufferSize / burstSize),
7510923SN/A    columnsPerStripe(range.interleaved() ? range.granularity() / burstSize : 1),
7611290Sgabor.dozsa@arm.com    ranksPerChannel(p->ranks_per_channel),
7711290Sgabor.dozsa@arm.com    bankGroupsPerRank(p->bank_groups_per_rank),
7811290Sgabor.dozsa@arm.com    bankGroupArch(p->bank_groups_per_rank > 0),
7911290Sgabor.dozsa@arm.com    banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0),
8011290Sgabor.dozsa@arm.com    readBufferSize(p->read_buffer_size),
8111290Sgabor.dozsa@arm.com    writeBufferSize(p->write_buffer_size),
8211290Sgabor.dozsa@arm.com    writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0),
8311290Sgabor.dozsa@arm.com    writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0),
8411290Sgabor.dozsa@arm.com    minWritesPerSwitch(p->min_writes_per_switch),
8511290Sgabor.dozsa@arm.com    writesThisTime(0), readsThisTime(0),
8611290Sgabor.dozsa@arm.com    tCK(p->tCK), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST),
8711290Sgabor.dozsa@arm.com    tCCD_L_WR(p->tCCD_L_WR),
8811290Sgabor.dozsa@arm.com    tCCD_L(p->tCCD_L), tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
8911290Sgabor.dozsa@arm.com    tWR(p->tWR), tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
9011290Sgabor.dozsa@arm.com    tRRD_L(p->tRRD_L), tXAW(p->tXAW), tXP(p->tXP), tXS(p->tXS),
9111290Sgabor.dozsa@arm.com    activationLimit(p->activation_limit), rankToRankDly(tCS + tBURST),
9211703Smichael.lebeane@amd.com    wrToRdDly(tCL + tBURST + p->tWTR), rdToWrDly(tRTW + tBURST),
9311290Sgabor.dozsa@arm.com    memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
9411290Sgabor.dozsa@arm.com    pageMgmt(p->page_policy),
9511703Smichael.lebeane@amd.com    maxAccessesPerRow(p->max_accesses_per_row),
9611703Smichael.lebeane@amd.com    frontendLatency(p->static_frontend_latency),
9711290Sgabor.dozsa@arm.com    backendLatency(p->static_backend_latency),
9811290Sgabor.dozsa@arm.com    nextBurstAt(0), prevArrival(0),
9911290Sgabor.dozsa@arm.com    nextReqTime(0), activeRank(0), timeStampOffset(0),
10011290Sgabor.dozsa@arm.com    lastStatsResetTick(0), enableDRAMPowerdown(p->enable_dram_powerdown)
10111290Sgabor.dozsa@arm.com{
10211290Sgabor.dozsa@arm.com    // sanity check the ranks since we rely on bit slicing for the
10311290Sgabor.dozsa@arm.com    // address decoding
10411290Sgabor.dozsa@arm.com    fatal_if(!isPowerOf2(ranksPerChannel), "DRAM rank count of %d is not "
10511703Smichael.lebeane@amd.com             "allowed, must be a power of two\n", ranksPerChannel);
10611290Sgabor.dozsa@arm.com
10711290Sgabor.dozsa@arm.com    fatal_if(!isPowerOf2(burstSize), "DRAM burst size %d is not allowed, "
10811703Smichael.lebeane@amd.com             "must be a power of two\n", burstSize);
10911703Smichael.lebeane@amd.com    readQueue.resize(p->qos_priorities);
11011290Sgabor.dozsa@arm.com    writeQueue.resize(p->qos_priorities);
11111290Sgabor.dozsa@arm.com
11211290Sgabor.dozsa@arm.com
11311290Sgabor.dozsa@arm.com    for (int i = 0; i < ranksPerChannel; i++) {
11411290Sgabor.dozsa@arm.com        Rank* rank = new Rank(*this, p, i);
11510923SN/A        ranks.push_back(rank);
11610923SN/A    }
11711290Sgabor.dozsa@arm.com
11810923SN/A    // perform a basic check of the write thresholds
11911290Sgabor.dozsa@arm.com    if (p->write_low_thresh_perc >= p->write_high_thresh_perc)
12011290Sgabor.dozsa@arm.com        fatal("Write buffer low threshold %d must be smaller than the "
12111290Sgabor.dozsa@arm.com              "high threshold %d\n", p->write_low_thresh_perc,
12211290Sgabor.dozsa@arm.com              p->write_high_thresh_perc);
12311290Sgabor.dozsa@arm.com
12411290Sgabor.dozsa@arm.com    // determine the rows per bank by looking at the total capacity
12511290Sgabor.dozsa@arm.com    uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
12611703Smichael.lebeane@amd.com
12711290Sgabor.dozsa@arm.com    // determine the dram actual capacity from the DRAM config in Mbytes
12811290Sgabor.dozsa@arm.com    uint64_t deviceCapacity = deviceSize / (1024 * 1024) * devicesPerRank *
12911290Sgabor.dozsa@arm.com        ranksPerChannel;
13011290Sgabor.dozsa@arm.com
13111290Sgabor.dozsa@arm.com    // if actual DRAM size does not match memory capacity in system warn!
13211703Smichael.lebeane@amd.com    if (deviceCapacity != capacity / (1024 * 1024))
13311703Smichael.lebeane@amd.com        warn("DRAM device capacity (%d Mbytes) does not match the "
13411290Sgabor.dozsa@arm.com             "address range assigned (%d Mbytes)\n", deviceCapacity,
13510923SN/A             capacity / (1024 * 1024));
13610923SN/A
13710923SN/A    DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
13811290Sgabor.dozsa@arm.com            AbstractMemory::size());
13911290Sgabor.dozsa@arm.com
14011290Sgabor.dozsa@arm.com    DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
14110923SN/A            rowBufferSize, columnsPerRowBuffer);
14211290Sgabor.dozsa@arm.com
14311290Sgabor.dozsa@arm.com    rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
14411290Sgabor.dozsa@arm.com
14511290Sgabor.dozsa@arm.com    // some basic sanity checks
14611290Sgabor.dozsa@arm.com    if (tREFI <= tRP || tREFI <= tRFC) {
14711290Sgabor.dozsa@arm.com        fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
14811290Sgabor.dozsa@arm.com              tREFI, tRP, tRFC);
14911290Sgabor.dozsa@arm.com    }
15011290Sgabor.dozsa@arm.com
15111290Sgabor.dozsa@arm.com    // basic bank group architecture checks ->
15211290Sgabor.dozsa@arm.com    if (bankGroupArch) {
15311290Sgabor.dozsa@arm.com        // must have at least one bank per bank group
15411290Sgabor.dozsa@arm.com        if (bankGroupsPerRank > banksPerRank) {
15511290Sgabor.dozsa@arm.com            fatal("banks per rank (%d) must be equal to or larger than "
15611290Sgabor.dozsa@arm.com                  "banks groups per rank (%d)\n",
15711290Sgabor.dozsa@arm.com                  banksPerRank, bankGroupsPerRank);
15811290Sgabor.dozsa@arm.com        }
15911290Sgabor.dozsa@arm.com        // must have same number of banks in each bank group
16011290Sgabor.dozsa@arm.com        if ((banksPerRank % bankGroupsPerRank) != 0) {
16111290Sgabor.dozsa@arm.com            fatal("Banks per rank (%d) must be evenly divisible by bank groups "
16211290Sgabor.dozsa@arm.com                  "per rank (%d) for equal banks per bank group\n",
16311290Sgabor.dozsa@arm.com                  banksPerRank, bankGroupsPerRank);
16411290Sgabor.dozsa@arm.com        }
16511290Sgabor.dozsa@arm.com        // tCCD_L should be greater than minimal, back-to-back burst delay
16611290Sgabor.dozsa@arm.com        if (tCCD_L <= tBURST) {
16711290Sgabor.dozsa@arm.com            fatal("tCCD_L (%d) should be larger than tBURST (%d) when "
16811290Sgabor.dozsa@arm.com                  "bank groups per rank (%d) is greater than 1\n",
16911290Sgabor.dozsa@arm.com                  tCCD_L, tBURST, bankGroupsPerRank);
17011290Sgabor.dozsa@arm.com        }
17111290Sgabor.dozsa@arm.com        // tCCD_L_WR should be greater than minimal, back-to-back burst delay
17211290Sgabor.dozsa@arm.com        if (tCCD_L_WR <= tBURST) {
17311703Smichael.lebeane@amd.com            fatal("tCCD_L_WR (%d) should be larger than tBURST (%d) when "
17411703Smichael.lebeane@amd.com                  "bank groups per rank (%d) is greater than 1\n",
17511703Smichael.lebeane@amd.com                  tCCD_L_WR, tBURST, bankGroupsPerRank);
17611703Smichael.lebeane@amd.com        }
17711703Smichael.lebeane@amd.com        // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
17811703Smichael.lebeane@amd.com        // some datasheets might specify it equal to tRRD
17911703Smichael.lebeane@amd.com        if (tRRD_L < tRRD) {
18011290Sgabor.dozsa@arm.com            fatal("tRRD_L (%d) should be larger than tRRD (%d) when "
18110923SN/A                  "bank groups per rank (%d) is greater than 1\n",
18210923SN/A                  tRRD_L, tRRD, bankGroupsPerRank);
18310923SN/A        }
18411290Sgabor.dozsa@arm.com    }
18511290Sgabor.dozsa@arm.com
18611290Sgabor.dozsa@arm.com}
18711703Smichael.lebeane@amd.com
18811703Smichael.lebeane@amd.comvoid
18910923SN/ADRAMCtrl::init()
19010923SN/A{
19111290Sgabor.dozsa@arm.com    MemCtrl::init();
19210923SN/A
19311290Sgabor.dozsa@arm.com   if (!port.isConnected()) {
19411290Sgabor.dozsa@arm.com        fatal("DRAMCtrl %s is unconnected!\n", name());
19511290Sgabor.dozsa@arm.com    } else {
19611290Sgabor.dozsa@arm.com        port.sendRangeChange();
19711290Sgabor.dozsa@arm.com    }
19811290Sgabor.dozsa@arm.com
19911290Sgabor.dozsa@arm.com    // a bit of sanity checks on the interleaving, save it for here to
20011290Sgabor.dozsa@arm.com    // ensure that the system pointer is initialised
20111290Sgabor.dozsa@arm.com    if (range.interleaved()) {
20211290Sgabor.dozsa@arm.com        if (channels != range.stripes())
20311290Sgabor.dozsa@arm.com            fatal("%s has %d interleaved address stripes but %d channel(s)\n",
20411290Sgabor.dozsa@arm.com                  name(), range.stripes(), channels);
20511290Sgabor.dozsa@arm.com
20611703Smichael.lebeane@amd.com        if (addrMapping == Enums::RoRaBaChCo) {
20711703Smichael.lebeane@amd.com            if (rowBufferSize != range.granularity()) {
20811703Smichael.lebeane@amd.com                fatal("Channel interleaving of %s doesn't match RoRaBaChCo "
20911703Smichael.lebeane@amd.com                      "address map\n", name());
21011290Sgabor.dozsa@arm.com            }
21110923SN/A        } else if (addrMapping == Enums::RoRaBaCoCh ||
21211290Sgabor.dozsa@arm.com                   addrMapping == Enums::RoCoRaBaCh) {
21311290Sgabor.dozsa@arm.com            // for the interleavings with channel bits in the bottom,
21410923SN/A            // if the system uses a channel striping granularity that
21510923SN/A            // is larger than the DRAM burst size, then map the
21610923SN/A            // sequential accesses within a stripe to a number of
21710923SN/A            // columns in the DRAM, effectively placing some of the
21810923SN/A            // lower-order column bits as the least-significant bits
21911290Sgabor.dozsa@arm.com            // of the address (above the ones denoting the burst size)
22011290Sgabor.dozsa@arm.com            assert(columnsPerStripe >= 1);
22111290Sgabor.dozsa@arm.com
22211290Sgabor.dozsa@arm.com            // channel striping has to be done at a granularity that
22311703Smichael.lebeane@amd.com            // is equal or larger to a cache line
22411703Smichael.lebeane@amd.com            if (system()->cacheLineSize() > range.granularity()) {
22510923SN/A                fatal("Channel interleaving of %s must be at least as large "
22611290Sgabor.dozsa@arm.com                      "as the cache line size\n", name());
22711290Sgabor.dozsa@arm.com            }
22811290Sgabor.dozsa@arm.com
22911290Sgabor.dozsa@arm.com            // ...and equal or smaller than the row-buffer size
23011290Sgabor.dozsa@arm.com            if (rowBufferSize < range.granularity()) {
23111290Sgabor.dozsa@arm.com                fatal("Channel interleaving of %s must be at most as large "
23211290Sgabor.dozsa@arm.com                      "as the row-buffer size\n", name());
23311703Smichael.lebeane@amd.com            }
23411290Sgabor.dozsa@arm.com            // this is essentially the check above, so just to be sure
23511290Sgabor.dozsa@arm.com            assert(columnsPerStripe <= columnsPerRowBuffer);
23611290Sgabor.dozsa@arm.com        }
23711290Sgabor.dozsa@arm.com    }
23811290Sgabor.dozsa@arm.com}
23911290Sgabor.dozsa@arm.com
24011290Sgabor.dozsa@arm.comvoid
24110923SN/ADRAMCtrl::startup()
24210923SN/A{
24310923SN/A    // remember the memory system mode of operation
24411290Sgabor.dozsa@arm.com    isTimingMode = system()->isTimingMode();
24510923SN/A
24611290Sgabor.dozsa@arm.com    if (isTimingMode) {
24711290Sgabor.dozsa@arm.com        // timestamp offset should be in clock cycles for DRAMPower
24811290Sgabor.dozsa@arm.com        timeStampOffset = divCeil(curTick(), tCK);
24911290Sgabor.dozsa@arm.com
25011290Sgabor.dozsa@arm.com        // update the start tick for the precharge accounting to the
25111290Sgabor.dozsa@arm.com        // current tick
25210923SN/A        for (auto r : ranks) {
25310923SN/A            r->startup(curTick() + tREFI - tRP);
25410923SN/A        }
25511290Sgabor.dozsa@arm.com
25610923SN/A        // shift the bus busy time sufficiently far ahead that we never
25711290Sgabor.dozsa@arm.com        // have to worry about negative values when computing the time for
25811290Sgabor.dozsa@arm.com        // the next request, this will add an insignificant bubble at the
25911290Sgabor.dozsa@arm.com        // start of simulation
26011290Sgabor.dozsa@arm.com        nextBurstAt = curTick() + tRP + tRCD;
26111290Sgabor.dozsa@arm.com    }
26211290Sgabor.dozsa@arm.com}
26311290Sgabor.dozsa@arm.com
26411290Sgabor.dozsa@arm.comTick
26511290Sgabor.dozsa@arm.comDRAMCtrl::recvAtomic(PacketPtr pkt)
26611290Sgabor.dozsa@arm.com{
26711290Sgabor.dozsa@arm.com    DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
26811290Sgabor.dozsa@arm.com
26911290Sgabor.dozsa@arm.com    panic_if(pkt->cacheResponding(), "Should not see packets where cache "
27011290Sgabor.dozsa@arm.com             "is responding");
27111290Sgabor.dozsa@arm.com
27211290Sgabor.dozsa@arm.com    // do the actual memory access and turn the packet into a response
27311290Sgabor.dozsa@arm.com    access(pkt);
27411290Sgabor.dozsa@arm.com
27511290Sgabor.dozsa@arm.com    Tick latency = 0;
27611290Sgabor.dozsa@arm.com    if (pkt->hasData()) {
27711290Sgabor.dozsa@arm.com        // this value is not supposed to be accurate, just enough to
27811290Sgabor.dozsa@arm.com        // keep things going, mimic a closed page
27911290Sgabor.dozsa@arm.com        latency = tRP + tRCD + tCL;
28011290Sgabor.dozsa@arm.com    }
28111290Sgabor.dozsa@arm.com    return latency;
28211290Sgabor.dozsa@arm.com}
28311290Sgabor.dozsa@arm.com
28411290Sgabor.dozsa@arm.combool
28511290Sgabor.dozsa@arm.comDRAMCtrl::readQueueFull(unsigned int neededEntries) const
28611290Sgabor.dozsa@arm.com{
28711290Sgabor.dozsa@arm.com    DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
28811290Sgabor.dozsa@arm.com            readBufferSize, totalReadQueueSize + respQueue.size(),
28911290Sgabor.dozsa@arm.com            neededEntries);
29011290Sgabor.dozsa@arm.com
29111290Sgabor.dozsa@arm.com    auto rdsize_new = totalReadQueueSize + respQueue.size() + neededEntries;
29211290Sgabor.dozsa@arm.com    return rdsize_new > readBufferSize;
29311290Sgabor.dozsa@arm.com}
29411290Sgabor.dozsa@arm.com
29511290Sgabor.dozsa@arm.combool
29611290Sgabor.dozsa@arm.comDRAMCtrl::writeQueueFull(unsigned int neededEntries) const
29711290Sgabor.dozsa@arm.com{
29811290Sgabor.dozsa@arm.com    DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
29911290Sgabor.dozsa@arm.com            writeBufferSize, totalWriteQueueSize, neededEntries);
30011290Sgabor.dozsa@arm.com
30111290Sgabor.dozsa@arm.com    auto wrsize_new = (totalWriteQueueSize + neededEntries);
30211290Sgabor.dozsa@arm.com    return  wrsize_new > writeBufferSize;
30311290Sgabor.dozsa@arm.com}
30411290Sgabor.dozsa@arm.com
30511290Sgabor.dozsa@arm.comDRAMCtrl::DRAMPacket*
30611290Sgabor.dozsa@arm.comDRAMCtrl::decodeAddr(const PacketPtr pkt, Addr dramPktAddr, unsigned size,
30711290Sgabor.dozsa@arm.com                     bool isRead) const
30811290Sgabor.dozsa@arm.com{
30911290Sgabor.dozsa@arm.com    // decode the address based on the address mapping scheme, with
31011290Sgabor.dozsa@arm.com    // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
31111290Sgabor.dozsa@arm.com    // channel, respectively
31211290Sgabor.dozsa@arm.com    uint8_t rank;
31311290Sgabor.dozsa@arm.com    uint8_t bank;
31411290Sgabor.dozsa@arm.com    // use a 64-bit unsigned during the computations as the row is
31511290Sgabor.dozsa@arm.com    // always the top bits, and check before creating the DRAMPacket
31611703Smichael.lebeane@amd.com    uint64_t row;
31711703Smichael.lebeane@amd.com
31811290Sgabor.dozsa@arm.com    // truncate the address to a DRAM burst, which makes it unique to
31911290Sgabor.dozsa@arm.com    // a specific column, row, bank, rank and channel
32011290Sgabor.dozsa@arm.com    Addr addr = dramPktAddr / burstSize;
32111703Smichael.lebeane@amd.com
32211290Sgabor.dozsa@arm.com    // we have removed the lowest order address bits that denote the
32311290Sgabor.dozsa@arm.com    // position within the column
32411290Sgabor.dozsa@arm.com    if (addrMapping == Enums::RoRaBaChCo) {
32511703Smichael.lebeane@amd.com        // the lowest order bits denote the column to ensure that
32611290Sgabor.dozsa@arm.com        // sequential cache lines occupy the same row
32711703Smichael.lebeane@amd.com        addr = addr / columnsPerRowBuffer;
32811703Smichael.lebeane@amd.com
32911703Smichael.lebeane@amd.com        // take out the channel part of the address
33011703Smichael.lebeane@amd.com        addr = addr / channels;
33111703Smichael.lebeane@amd.com
33211703Smichael.lebeane@amd.com        // after the channel bits, get the bank bits to interleave
33311703Smichael.lebeane@amd.com        // over the banks
33411703Smichael.lebeane@amd.com        bank = addr % banksPerRank;
33511290Sgabor.dozsa@arm.com        addr = addr / banksPerRank;
33611290Sgabor.dozsa@arm.com
33711290Sgabor.dozsa@arm.com        // after the bank, we get the rank bits which thus interleaves
33811290Sgabor.dozsa@arm.com        // over the ranks
33911290Sgabor.dozsa@arm.com        rank = addr % ranksPerChannel;
34011290Sgabor.dozsa@arm.com        addr = addr / ranksPerChannel;
34111290Sgabor.dozsa@arm.com
34211290Sgabor.dozsa@arm.com        // lastly, get the row bits, no need to remove them from addr
34311290Sgabor.dozsa@arm.com        row = addr % rowsPerBank;
34411290Sgabor.dozsa@arm.com    } else if (addrMapping == Enums::RoRaBaCoCh) {
34511290Sgabor.dozsa@arm.com        // take out the lower-order column bits
34611290Sgabor.dozsa@arm.com        addr = addr / columnsPerStripe;
34711290Sgabor.dozsa@arm.com
34811290Sgabor.dozsa@arm.com        // take out the channel part of the address
34911290Sgabor.dozsa@arm.com        addr = addr / channels;
35011290Sgabor.dozsa@arm.com
35111290Sgabor.dozsa@arm.com        // next, the higher-order column bites
35211290Sgabor.dozsa@arm.com        addr = addr / (columnsPerRowBuffer / columnsPerStripe);
35311290Sgabor.dozsa@arm.com
35410923SN/A        // after the column bits, we get the bank bits to interleave
35510923SN/A        // over the banks
35610923SN/A        bank = addr % banksPerRank;
35710923SN/A        addr = addr / banksPerRank;
35810923SN/A
35910923SN/A        // after the bank, we get the rank bits which thus interleaves
36010923SN/A        // over the ranks
36111290Sgabor.dozsa@arm.com        rank = addr % ranksPerChannel;
36210923SN/A        addr = addr / ranksPerChannel;
36310923SN/A
36410923SN/A        // lastly, get the row bits, no need to remove them from addr
36511290Sgabor.dozsa@arm.com        row = addr % rowsPerBank;
36611290Sgabor.dozsa@arm.com    } else if (addrMapping == Enums::RoCoRaBaCh) {
36711290Sgabor.dozsa@arm.com        // optimise for closed page mode and utilise maximum
36811290Sgabor.dozsa@arm.com        // parallelism of the DRAM (at the cost of power)
36911290Sgabor.dozsa@arm.com
37011290Sgabor.dozsa@arm.com        // take out the lower-order column bits
37111290Sgabor.dozsa@arm.com        addr = addr / columnsPerStripe;
37211290Sgabor.dozsa@arm.com
37311290Sgabor.dozsa@arm.com        // take out the channel part of the address, not that this has
37411290Sgabor.dozsa@arm.com        // to match with how accesses are interleaved between the
37511290Sgabor.dozsa@arm.com        // controllers in the address mapping
37611703Smichael.lebeane@amd.com        addr = addr / channels;
37711703Smichael.lebeane@amd.com
37811703Smichael.lebeane@amd.com        // start with the bank bits, as this provides the maximum
37911290Sgabor.dozsa@arm.com        // opportunity for parallelism between requests
38011703Smichael.lebeane@amd.com        bank = addr % banksPerRank;
38111703Smichael.lebeane@amd.com        addr = addr / banksPerRank;
38211703Smichael.lebeane@amd.com
38311703Smichael.lebeane@amd.com        // next get the rank bits
38411703Smichael.lebeane@amd.com        rank = addr % ranksPerChannel;
38511703Smichael.lebeane@amd.com        addr = addr / ranksPerChannel;
38611703Smichael.lebeane@amd.com
38711703Smichael.lebeane@amd.com        // next, the higher-order column bites
38811703Smichael.lebeane@amd.com        addr = addr / (columnsPerRowBuffer / columnsPerStripe);
38911703Smichael.lebeane@amd.com
39011703Smichael.lebeane@amd.com        // lastly, get the row bits, no need to remove them from addr
39111703Smichael.lebeane@amd.com        row = addr % rowsPerBank;
39211703Smichael.lebeane@amd.com    } else
39311703Smichael.lebeane@amd.com        panic("Unknown address mapping policy chosen!");
39411703Smichael.lebeane@amd.com
39511703Smichael.lebeane@amd.com    assert(rank < ranksPerChannel);
39611703Smichael.lebeane@amd.com    assert(bank < banksPerRank);
39711290Sgabor.dozsa@arm.com    assert(row < rowsPerBank);
39811290Sgabor.dozsa@arm.com    assert(row < Bank::NO_ROW);
39911290Sgabor.dozsa@arm.com
40010923SN/A    DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
40110923SN/A            dramPktAddr, rank, bank, row);
40211290Sgabor.dozsa@arm.com
40311290Sgabor.dozsa@arm.com    // create the corresponding DRAM packet with the entry time and
40410923SN/A    // ready time set to the current tick, the latter will be updated
40511290Sgabor.dozsa@arm.com    // later
40611290Sgabor.dozsa@arm.com    uint16_t bank_id = banksPerRank * rank + bank;
40711290Sgabor.dozsa@arm.com    return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
40811290Sgabor.dozsa@arm.com                          size, ranks[rank]->banks[bank], *ranks[rank]);
40911290Sgabor.dozsa@arm.com}
41011290Sgabor.dozsa@arm.com
41111290Sgabor.dozsa@arm.comvoid
41210923SN/ADRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
41310923SN/A{
41411290Sgabor.dozsa@arm.com    // only add to the read queue here. whenever the request is
41511290Sgabor.dozsa@arm.com    // eventually done, set the readyTime, and call schedule()
41611290Sgabor.dozsa@arm.com    assert(!pkt->isWrite());
41711290Sgabor.dozsa@arm.com
41810923SN/A    assert(pktCount != 0);
41911290Sgabor.dozsa@arm.com
42011290Sgabor.dozsa@arm.com    // if the request size is larger than burst size, the pkt is split into
42111290Sgabor.dozsa@arm.com    // multiple DRAM packets
42211290Sgabor.dozsa@arm.com    // Note if the pkt starting address is not aligened to burst size, the
42311290Sgabor.dozsa@arm.com    // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
42411290Sgabor.dozsa@arm.com    // are aligned to burst size boundaries. This is to ensure we accurately
42511290Sgabor.dozsa@arm.com    // check read packets against packets in write queue.
42611290Sgabor.dozsa@arm.com    Addr addr = pkt->getAddr();
42711290Sgabor.dozsa@arm.com    unsigned pktsServicedByWrQ = 0;
42811290Sgabor.dozsa@arm.com    BurstHelper* burst_helper = NULL;
42911290Sgabor.dozsa@arm.com    for (int cnt = 0; cnt < pktCount; ++cnt) {
43011290Sgabor.dozsa@arm.com        unsigned size = std::min((addr | (burstSize - 1)) + 1,
43111290Sgabor.dozsa@arm.com                        pkt->getAddr() + pkt->getSize()) - addr;
43210923SN/A        readPktSize[ceilLog2(size)]++;
43310923SN/A        readBursts++;
43411290Sgabor.dozsa@arm.com        masterReadAccesses[pkt->masterId()]++;
43511290Sgabor.dozsa@arm.com
43610923SN/A        // First check write buffer to see if the data is already at
43711290Sgabor.dozsa@arm.com        // the controller
43811290Sgabor.dozsa@arm.com        bool foundInWrQ = false;
43911290Sgabor.dozsa@arm.com        Addr burst_addr = burstAlign(addr);
44011290Sgabor.dozsa@arm.com        // if the burst address is not present then there is no need
44111290Sgabor.dozsa@arm.com        // looking any further
44211290Sgabor.dozsa@arm.com        if (isInWriteQueue.find(burst_addr) != isInWriteQueue.end()) {
44311290Sgabor.dozsa@arm.com            for (const auto& vec : writeQueue) {
44411290Sgabor.dozsa@arm.com                for (const auto& p : vec) {
44511290Sgabor.dozsa@arm.com                    // check if the read is subsumed in the write queue
44611290Sgabor.dozsa@arm.com                    // packet we are looking at
44711290Sgabor.dozsa@arm.com                    if (p->addr <= addr &&
44811290Sgabor.dozsa@arm.com                       ((addr + size) <= (p->addr + p->size))) {
44911290Sgabor.dozsa@arm.com
45011290Sgabor.dozsa@arm.com                        foundInWrQ = true;
45111701Smichael.lebeane@amd.com                        servicedByWrQ++;
45211290Sgabor.dozsa@arm.com                        pktsServicedByWrQ++;
45311290Sgabor.dozsa@arm.com                        DPRINTF(DRAM,
45411290Sgabor.dozsa@arm.com                                "Read to addr %lld with size %d serviced by "
45511290Sgabor.dozsa@arm.com                                "write queue\n",
45611290Sgabor.dozsa@arm.com                                addr, size);
45711290Sgabor.dozsa@arm.com                        bytesReadWrQ += burstSize;
45811290Sgabor.dozsa@arm.com                        break;
45911290Sgabor.dozsa@arm.com                    }
46011290Sgabor.dozsa@arm.com                }
46111290Sgabor.dozsa@arm.com            }
46211290Sgabor.dozsa@arm.com        }
46311290Sgabor.dozsa@arm.com
46411290Sgabor.dozsa@arm.com        // If not found in the write q, make a DRAM packet and
46510923SN/A        // push it onto the read queue
46610923SN/A        if (!foundInWrQ) {
46711290Sgabor.dozsa@arm.com
46811290Sgabor.dozsa@arm.com            // Make the burst helper for split packets
46911290Sgabor.dozsa@arm.com            if (pktCount > 1 && burst_helper == NULL) {
47011290Sgabor.dozsa@arm.com                DPRINTF(DRAM, "Read to addr %lld translates to %d "
47111290Sgabor.dozsa@arm.com                        "dram requests\n", pkt->getAddr(), pktCount);
47211290Sgabor.dozsa@arm.com                burst_helper = new BurstHelper(pktCount);
47311290Sgabor.dozsa@arm.com            }
47411290Sgabor.dozsa@arm.com
47511290Sgabor.dozsa@arm.com            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
47611290Sgabor.dozsa@arm.com            dram_pkt->burstHelper = burst_helper;
47711290Sgabor.dozsa@arm.com
47811290Sgabor.dozsa@arm.com            assert(!readQueueFull(1));
47911290Sgabor.dozsa@arm.com            rdQLenPdf[totalReadQueueSize + respQueue.size()]++;
48011290Sgabor.dozsa@arm.com
48111290Sgabor.dozsa@arm.com            DPRINTF(DRAM, "Adding to read queue\n");
48211290Sgabor.dozsa@arm.com
48311290Sgabor.dozsa@arm.com            readQueue[dram_pkt->qosValue()].push_back(dram_pkt);
48411290Sgabor.dozsa@arm.com
48511290Sgabor.dozsa@arm.com            ++dram_pkt->rankRef.readEntries;
48611290Sgabor.dozsa@arm.com
48711290Sgabor.dozsa@arm.com            // log packet
48811290Sgabor.dozsa@arm.com            logRequest(MemCtrl::READ, pkt->masterId(), pkt->qosValue(),
48911290Sgabor.dozsa@arm.com                       dram_pkt->addr, 1);
49011290Sgabor.dozsa@arm.com
49111290Sgabor.dozsa@arm.com            // Update stats
49211290Sgabor.dozsa@arm.com            avgRdQLen = totalReadQueueSize + respQueue.size();
49311290Sgabor.dozsa@arm.com        }
49411290Sgabor.dozsa@arm.com
49511290Sgabor.dozsa@arm.com        // Starting address of next dram pkt (aligend to burstSize boundary)
49611290Sgabor.dozsa@arm.com        addr = (addr | (burstSize - 1)) + 1;
49711290Sgabor.dozsa@arm.com    }
49811290Sgabor.dozsa@arm.com
49911290Sgabor.dozsa@arm.com    // If all packets are serviced by write queue, we send the repsonse back
50011290Sgabor.dozsa@arm.com    if (pktsServicedByWrQ == pktCount) {
50111290Sgabor.dozsa@arm.com        accessAndRespond(pkt, frontendLatency);
50211290Sgabor.dozsa@arm.com        return;
50311290Sgabor.dozsa@arm.com    }
50411290Sgabor.dozsa@arm.com
50511290Sgabor.dozsa@arm.com    // Update how many split packets are serviced by write queue
50611290Sgabor.dozsa@arm.com    if (burst_helper != NULL)
50711290Sgabor.dozsa@arm.com        burst_helper->burstsServiced = pktsServicedByWrQ;
50811290Sgabor.dozsa@arm.com
50911290Sgabor.dozsa@arm.com    // If we are not already scheduled to get a request out of the
51011290Sgabor.dozsa@arm.com    // queue, do so now
51111290Sgabor.dozsa@arm.com    if (!nextReqEvent.scheduled()) {
51211290Sgabor.dozsa@arm.com        DPRINTF(DRAM, "Request scheduled immediately\n");
51311290Sgabor.dozsa@arm.com        schedule(nextReqEvent, curTick());
51411290Sgabor.dozsa@arm.com    }
51511290Sgabor.dozsa@arm.com}
51611290Sgabor.dozsa@arm.com
51711290Sgabor.dozsa@arm.comvoid
51811290Sgabor.dozsa@arm.comDRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
51911290Sgabor.dozsa@arm.com{
52011290Sgabor.dozsa@arm.com    // only add to the write queue here. whenever the request is
52111290Sgabor.dozsa@arm.com    // eventually done, set the readyTime, and call schedule()
52211290Sgabor.dozsa@arm.com    assert(pkt->isWrite());
52311290Sgabor.dozsa@arm.com
52411290Sgabor.dozsa@arm.com    // if the request size is larger than burst size, the pkt is split into
52511290Sgabor.dozsa@arm.com    // multiple DRAM packets
52611290Sgabor.dozsa@arm.com    Addr addr = pkt->getAddr();
52711290Sgabor.dozsa@arm.com    for (int cnt = 0; cnt < pktCount; ++cnt) {
52811290Sgabor.dozsa@arm.com        unsigned size = std::min((addr | (burstSize - 1)) + 1,
52911290Sgabor.dozsa@arm.com                        pkt->getAddr() + pkt->getSize()) - addr;
53011290Sgabor.dozsa@arm.com        writePktSize[ceilLog2(size)]++;
53111290Sgabor.dozsa@arm.com        writeBursts++;
53211290Sgabor.dozsa@arm.com        masterWriteAccesses[pkt->masterId()]++;
53311290Sgabor.dozsa@arm.com
53411290Sgabor.dozsa@arm.com        // see if we can merge with an existing item in the write
53511290Sgabor.dozsa@arm.com        // queue and keep track of whether we have merged or not
53611290Sgabor.dozsa@arm.com        bool merged = isInWriteQueue.find(burstAlign(addr)) !=
53711701Smichael.lebeane@amd.com            isInWriteQueue.end();
53811290Sgabor.dozsa@arm.com
53911290Sgabor.dozsa@arm.com        // if the item was not merged we need to create a new write
54011290Sgabor.dozsa@arm.com        // and enqueue it
54111290Sgabor.dozsa@arm.com        if (!merged) {
54211290Sgabor.dozsa@arm.com            DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
54311290Sgabor.dozsa@arm.com
54411290Sgabor.dozsa@arm.com            assert(totalWriteQueueSize < writeBufferSize);
54511290Sgabor.dozsa@arm.com            wrQLenPdf[totalWriteQueueSize]++;
54611290Sgabor.dozsa@arm.com
54711290Sgabor.dozsa@arm.com            DPRINTF(DRAM, "Adding to write queue\n");
54811290Sgabor.dozsa@arm.com
54911290Sgabor.dozsa@arm.com            writeQueue[dram_pkt->qosValue()].push_back(dram_pkt);
55011290Sgabor.dozsa@arm.com            isInWriteQueue.insert(burstAlign(addr));
55111290Sgabor.dozsa@arm.com
55211290Sgabor.dozsa@arm.com            // log packet
55311290Sgabor.dozsa@arm.com            logRequest(MemCtrl::WRITE, pkt->masterId(), pkt->qosValue(),
55411290Sgabor.dozsa@arm.com                       dram_pkt->addr, 1);
55511290Sgabor.dozsa@arm.com
55611290Sgabor.dozsa@arm.com            assert(totalWriteQueueSize == isInWriteQueue.size());
55711290Sgabor.dozsa@arm.com
55811290Sgabor.dozsa@arm.com            // Update stats
55911290Sgabor.dozsa@arm.com            avgWrQLen = totalWriteQueueSize;
56011290Sgabor.dozsa@arm.com
56111325Ssteve.reinhardt@amd.com            // increment write entries of the rank
56211325Ssteve.reinhardt@amd.com            ++dram_pkt->rankRef.writeEntries;
56311290Sgabor.dozsa@arm.com        } else {
56411290Sgabor.dozsa@arm.com            DPRINTF(DRAM, "Merging write burst with existing queue entry\n");
56511290Sgabor.dozsa@arm.com
56611290Sgabor.dozsa@arm.com            // keep track of the fact that this burst effectively
56711290Sgabor.dozsa@arm.com            // disappeared as it was merged with an existing one
56811290Sgabor.dozsa@arm.com            mergedWrBursts++;
56911290Sgabor.dozsa@arm.com        }
57011290Sgabor.dozsa@arm.com
57111290Sgabor.dozsa@arm.com        // Starting address of next dram pkt (aligend to burstSize boundary)
57211290Sgabor.dozsa@arm.com        addr = (addr | (burstSize - 1)) + 1;
57311290Sgabor.dozsa@arm.com    }
57411290Sgabor.dozsa@arm.com
57511290Sgabor.dozsa@arm.com    // we do not wait for the writes to be send to the actual memory,
57611290Sgabor.dozsa@arm.com    // but instead take responsibility for the consistency here and
57711290Sgabor.dozsa@arm.com    // snoop the write queue for any upcoming reads
57811290Sgabor.dozsa@arm.com    // @todo, if a pkt size is larger than burst size, we might need a
57911290Sgabor.dozsa@arm.com    // different front end latency
58011290Sgabor.dozsa@arm.com    accessAndRespond(pkt, frontendLatency);
58111703Smichael.lebeane@amd.com
58211290Sgabor.dozsa@arm.com    // If we are not already scheduled to get a request out of the
58310923SN/A    // queue, do so now
58411703Smichael.lebeane@amd.com    if (!nextReqEvent.scheduled()) {
58511290Sgabor.dozsa@arm.com        DPRINTF(DRAM, "Request scheduled immediately\n");
58610923SN/A        schedule(nextReqEvent, curTick());
58711290Sgabor.dozsa@arm.com    }
58811290Sgabor.dozsa@arm.com}
58910923SN/A
59010923SN/Avoid
59110923SN/ADRAMCtrl::printQs() const
59211703Smichael.lebeane@amd.com{
59311290Sgabor.dozsa@arm.com#if TRACING_ON
59411290Sgabor.dozsa@arm.com    DPRINTF(DRAM, "===READ QUEUE===\n\n");
59511290Sgabor.dozsa@arm.com    for (const auto& queue : readQueue) {
59611290Sgabor.dozsa@arm.com        for (const auto& packet : queue) {
59710923SN/A            DPRINTF(DRAM, "Read %lu\n", packet->addr);
59810923SN/A        }
59911290Sgabor.dozsa@arm.com    }
60010923SN/A
60111290Sgabor.dozsa@arm.com    DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
60211290Sgabor.dozsa@arm.com    for (const auto& packet : respQueue) {
60310923SN/A        DPRINTF(DRAM, "Response %lu\n", packet->addr);
60410923SN/A    }
60511290Sgabor.dozsa@arm.com
60610923SN/A    DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
60710923SN/A    for (const auto& queue : writeQueue) {
60810923SN/A        for (const auto& packet : queue) {
60910923SN/A            DPRINTF(DRAM, "Write %lu\n", packet->addr);
61010923SN/A        }
61110923SN/A    }
61210923SN/A#endif // TRACING_ON
61310923SN/A}
61411290Sgabor.dozsa@arm.com
61510923SN/Abool
61610923SN/ADRAMCtrl::recvTimingReq(PacketPtr pkt)
61710923SN/A{
61810923SN/A    // This is where we enter from the outside world
61911290Sgabor.dozsa@arm.com    DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
62010923SN/A            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
62111290Sgabor.dozsa@arm.com
62210923SN/A    panic_if(pkt->cacheResponding(), "Should not see packets where cache "
62311290Sgabor.dozsa@arm.com             "is responding");
62410923SN/A
62511290Sgabor.dozsa@arm.com    panic_if(!(pkt->isRead() || pkt->isWrite()),
62611290Sgabor.dozsa@arm.com             "Should only see read and writes at memory controller\n");
62711290Sgabor.dozsa@arm.com
62810923SN/A    // Calc avg gap between requests
62911701Smichael.lebeane@amd.com    if (prevArrival != 0) {
63011701Smichael.lebeane@amd.com        totGap += curTick() - prevArrival;
63110923SN/A    }
63211290Sgabor.dozsa@arm.com    prevArrival = curTick();
63311290Sgabor.dozsa@arm.com
63410923SN/A
63511290Sgabor.dozsa@arm.com    // Find out how many dram packets a pkt translates to
63611290Sgabor.dozsa@arm.com    // If the burst size is equal or larger than the pkt size, then a pkt
63711701Smichael.lebeane@amd.com    // translates to only one dram packet. Otherwise, a pkt translates to
63810923SN/A    // multiple dram packets
63910923SN/A    unsigned size = pkt->getSize();
64010923SN/A    unsigned offset = pkt->getAddr() & (burstSize - 1);
64111290Sgabor.dozsa@arm.com    unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
64210923SN/A
64310923SN/A    // run the QoS scheduler and assign a QoS priority value to the packet
64411290Sgabor.dozsa@arm.com    qosSchedule( { &readQueue, &writeQueue }, burstSize, pkt);
64510923SN/A
64611290Sgabor.dozsa@arm.com    // check local buffers and do not accept if full
64711290Sgabor.dozsa@arm.com    if (pkt->isWrite()) {
64811290Sgabor.dozsa@arm.com        assert(size != 0);
64910923SN/A        if (writeQueueFull(dram_pkt_count)) {
65010923SN/A            DPRINTF(DRAM, "Write queue full, not accepting\n");
65111290Sgabor.dozsa@arm.com            // remember that we have to retry this port
65210923SN/A            retryWrReq = true;
65310923SN/A            numWrRetry++;
65410923SN/A            return false;
65511290Sgabor.dozsa@arm.com        } else {
65611290Sgabor.dozsa@arm.com            addToWriteQueue(pkt, dram_pkt_count);
65711622Smichael.lebeane@amd.com            writeReqs++;
65811622Smichael.lebeane@amd.com            bytesWrittenSys += size;
65911622Smichael.lebeane@amd.com        }
66011622Smichael.lebeane@amd.com    } else {
66110923SN/A        assert(pkt->isRead());
66211290Sgabor.dozsa@arm.com        assert(size != 0);
66311290Sgabor.dozsa@arm.com        if (readQueueFull(dram_pkt_count)) {
66410923SN/A            DPRINTF(DRAM, "Read queue full, not accepting\n");
66511290Sgabor.dozsa@arm.com            // remember that we have to retry this port
66611290Sgabor.dozsa@arm.com            retryRdReq = true;
66711290Sgabor.dozsa@arm.com            numRdRetry++;
66811290Sgabor.dozsa@arm.com            return false;
66910923SN/A        } else {
67010923SN/A            addToReadQueue(pkt, dram_pkt_count);
67111290Sgabor.dozsa@arm.com            readReqs++;
67211290Sgabor.dozsa@arm.com            bytesReadSys += size;
67311290Sgabor.dozsa@arm.com        }
67411703Smichael.lebeane@amd.com    }
67511703Smichael.lebeane@amd.com
67610923SN/A    return true;
67710923SN/A}
67810923SN/A
67910923SN/Avoid
68010923SN/ADRAMCtrl::processRespondEvent()
68111290Sgabor.dozsa@arm.com{
68210923SN/A    DPRINTF(DRAM,
68310923SN/A            "processRespondEvent(): Some req has reached its readyTime\n");
68410923SN/A
68511290Sgabor.dozsa@arm.com    DRAMPacket* dram_pkt = respQueue.front();
68611290Sgabor.dozsa@arm.com
68711290Sgabor.dozsa@arm.com    // if a read has reached its ready-time, decrement the number of reads
68811290Sgabor.dozsa@arm.com    // At this point the packet has been handled and there is a possibility
68910923SN/A    // to switch to low-power mode if no other packet is available
69010923SN/A    --dram_pkt->rankRef.readEntries;
69110923SN/A    DPRINTF(DRAM, "number of read entries for rank %d is %d\n",
69210923SN/A            dram_pkt->rank, dram_pkt->rankRef.readEntries);
69311290Sgabor.dozsa@arm.com
69410923SN/A    // counter should at least indicate one outstanding request
69511290Sgabor.dozsa@arm.com    // for this read
69610923SN/A    assert(dram_pkt->rankRef.outstandingEvents > 0);
69711290Sgabor.dozsa@arm.com    // read response received, decrement count
69811290Sgabor.dozsa@arm.com    --dram_pkt->rankRef.outstandingEvents;
69910923SN/A
70010923SN/A    // at this moment should not have transitioned to a low-power state
70110923SN/A    assert((dram_pkt->rankRef.pwrState != PWR_SREF) &&
70211290Sgabor.dozsa@arm.com           (dram_pkt->rankRef.pwrState != PWR_PRE_PDN) &&
70311290Sgabor.dozsa@arm.com           (dram_pkt->rankRef.pwrState != PWR_ACT_PDN));
70411290Sgabor.dozsa@arm.com
70511290Sgabor.dozsa@arm.com    // track if this is the last packet before idling
70611290Sgabor.dozsa@arm.com    // and that there are no outstanding commands to this rank
70711290Sgabor.dozsa@arm.com    if (dram_pkt->rankRef.isQueueEmpty() &&
70811290Sgabor.dozsa@arm.com        dram_pkt->rankRef.outstandingEvents == 0 && enableDRAMPowerdown) {
70911290Sgabor.dozsa@arm.com        // verify that there are no events scheduled
71011290Sgabor.dozsa@arm.com        assert(!dram_pkt->rankRef.activateEvent.scheduled());
71111290Sgabor.dozsa@arm.com        assert(!dram_pkt->rankRef.prechargeEvent.scheduled());
71211290Sgabor.dozsa@arm.com
71311290Sgabor.dozsa@arm.com        // if coming from active state, schedule power event to
71411290Sgabor.dozsa@arm.com        // active power-down else go to precharge power-down
71511290Sgabor.dozsa@arm.com        DPRINTF(DRAMState, "Rank %d sleep at tick %d; current power state is "
71611290Sgabor.dozsa@arm.com                "%d\n", dram_pkt->rank, curTick(), dram_pkt->rankRef.pwrState);
71711290Sgabor.dozsa@arm.com
71811290Sgabor.dozsa@arm.com        // default to ACT power-down unless already in IDLE state
71911290Sgabor.dozsa@arm.com        // could be in IDLE if PRE issued before data returned
72011290Sgabor.dozsa@arm.com        PowerState next_pwr_state = PWR_ACT_PDN;
72111290Sgabor.dozsa@arm.com        if (dram_pkt->rankRef.pwrState == PWR_IDLE) {
72211290Sgabor.dozsa@arm.com            next_pwr_state = PWR_PRE_PDN;
72311290Sgabor.dozsa@arm.com        }
72411290Sgabor.dozsa@arm.com
72511290Sgabor.dozsa@arm.com        dram_pkt->rankRef.powerDownSleep(next_pwr_state, curTick());
72610923SN/A    }
72710923SN/A
72810923SN/A    if (dram_pkt->burstHelper) {
72911290Sgabor.dozsa@arm.com        // it is a split packet
73011290Sgabor.dozsa@arm.com        dram_pkt->burstHelper->burstsServiced++;
73110923SN/A        if (dram_pkt->burstHelper->burstsServiced ==
73211290Sgabor.dozsa@arm.com            dram_pkt->burstHelper->burstCount) {
73311290Sgabor.dozsa@arm.com            // we have now serviced all children packets of a system packet
73411290Sgabor.dozsa@arm.com            // so we can now respond to the requester
73510923SN/A            // @todo we probably want to have a different front end and back
73611290Sgabor.dozsa@arm.com            // end latency for split packets
73711290Sgabor.dozsa@arm.com            accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
73811290Sgabor.dozsa@arm.com            delete dram_pkt->burstHelper;
73911290Sgabor.dozsa@arm.com            dram_pkt->burstHelper = NULL;
74011290Sgabor.dozsa@arm.com        }
74110923SN/A    } else {
74211290Sgabor.dozsa@arm.com        // it is not a split packet
74311290Sgabor.dozsa@arm.com        accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
74411290Sgabor.dozsa@arm.com    }
74510923SN/A
74610923SN/A    delete respQueue.front();
74710923SN/A    respQueue.pop_front();
74811290Sgabor.dozsa@arm.com
74911290Sgabor.dozsa@arm.com    if (!respQueue.empty()) {
75010923SN/A        assert(respQueue.front()->readyTime >= curTick());
75111290Sgabor.dozsa@arm.com        assert(!respondEvent.scheduled());
75211290Sgabor.dozsa@arm.com        schedule(respondEvent, respQueue.front()->readyTime);
75311290Sgabor.dozsa@arm.com    } else {
75410923SN/A        // if there is nothing left in any queue, signal a drain
75511290Sgabor.dozsa@arm.com        if (drainState() == DrainState::Draining &&
75611290Sgabor.dozsa@arm.com            !totalWriteQueueSize && !totalReadQueueSize && allRanksDrained()) {
75711290Sgabor.dozsa@arm.com
75811290Sgabor.dozsa@arm.com            DPRINTF(Drain, "DRAM controller done draining\n");
75911290Sgabor.dozsa@arm.com            signalDrainDone();
76010923SN/A        }
76110923SN/A    }
76211290Sgabor.dozsa@arm.com
76311290Sgabor.dozsa@arm.com    // We have made a location in the queue available at this point,
76411290Sgabor.dozsa@arm.com    // so if there is a read that was forced to wait, retry now
76511290Sgabor.dozsa@arm.com    if (retryRdReq) {
76611290Sgabor.dozsa@arm.com        retryRdReq = false;
76710923SN/A        port.sendRetryReq();
76810923SN/A    }
76910923SN/A}
77010923SN/A
77110923SN/ADRAMCtrl::DRAMPacketQueue::iterator
77210923SN/ADRAMCtrl::chooseNext(DRAMPacketQueue& queue, Tick extra_col_delay)
77310923SN/A{
77410923SN/A    // This method does the arbitration between requests.
77511290Sgabor.dozsa@arm.com
77611290Sgabor.dozsa@arm.com    DRAMCtrl::DRAMPacketQueue::iterator ret = queue.end();
77710923SN/A
77811290Sgabor.dozsa@arm.com    if (!queue.empty()) {
77911703Smichael.lebeane@amd.com        if (queue.size() == 1) {
78011703Smichael.lebeane@amd.com            // available rank corresponds to state refresh idle
78111290Sgabor.dozsa@arm.com            DRAMPacket* dram_pkt = *(queue.begin());
78211290Sgabor.dozsa@arm.com            if (ranks[dram_pkt->rank]->inRefIdleState()) {
78311290Sgabor.dozsa@arm.com                ret = queue.begin();
78410923SN/A                DPRINTF(DRAM, "Single request, going to a free rank\n");
78511290Sgabor.dozsa@arm.com            } else {
78611290Sgabor.dozsa@arm.com                DPRINTF(DRAM, "Single request, going to a busy rank\n");
78711290Sgabor.dozsa@arm.com            }
78811290Sgabor.dozsa@arm.com        } else if (memSchedPolicy == Enums::fcfs) {
78911290Sgabor.dozsa@arm.com            // check if there is a packet going to a free rank
79011290Sgabor.dozsa@arm.com            for (auto i = queue.begin(); i != queue.end(); ++i) {
79111290Sgabor.dozsa@arm.com                DRAMPacket* dram_pkt = *i;
79211290Sgabor.dozsa@arm.com                if (ranks[dram_pkt->rank]->inRefIdleState()) {
79311290Sgabor.dozsa@arm.com                    ret = i;
79411290Sgabor.dozsa@arm.com                    break;
79511290Sgabor.dozsa@arm.com                }
79610923SN/A            }
79711290Sgabor.dozsa@arm.com        } else if (memSchedPolicy == Enums::frfcfs) {
79811290Sgabor.dozsa@arm.com            ret = chooseNextFRFCFS(queue, extra_col_delay);
79911290Sgabor.dozsa@arm.com        } else {
80010923SN/A            panic("No scheduling policy chosen\n");
80111290Sgabor.dozsa@arm.com        }
80211290Sgabor.dozsa@arm.com    }
80311290Sgabor.dozsa@arm.com    return ret;
80411290Sgabor.dozsa@arm.com}
80511290Sgabor.dozsa@arm.com
80611290Sgabor.dozsa@arm.comDRAMCtrl::DRAMPacketQueue::iterator
80711290Sgabor.dozsa@arm.comDRAMCtrl::chooseNextFRFCFS(DRAMPacketQueue& queue, Tick extra_col_delay)
80811290Sgabor.dozsa@arm.com{
80911703Smichael.lebeane@amd.com    // Only determine this if needed
81011703Smichael.lebeane@amd.com    vector<uint32_t> earliest_banks(ranksPerChannel, 0);
81111703Smichael.lebeane@amd.com
81211703Smichael.lebeane@amd.com    // Has minBankPrep been called to populate earliest_banks?
81311703Smichael.lebeane@amd.com    bool filled_earliest_banks = false;
81411703Smichael.lebeane@amd.com    // can the PRE/ACT sequence be done without impacting utlization?
81511703Smichael.lebeane@amd.com    bool hidden_bank_prep = false;
81611703Smichael.lebeane@amd.com
81711703Smichael.lebeane@amd.com    // search for seamless row hits first, if no seamless row hit is
81811703Smichael.lebeane@amd.com    // found then determine if there are other packets that can be issued
81911703Smichael.lebeane@amd.com    // without incurring additional bus delay due to bank timing
82011703Smichael.lebeane@amd.com    // Will select closed rows first to enable more open row possibilies
82111703Smichael.lebeane@amd.com    // in future selections
82211703Smichael.lebeane@amd.com    bool found_hidden_bank = false;
82311703Smichael.lebeane@amd.com
82411703Smichael.lebeane@amd.com    // remember if we found a row hit, not seamless, but bank prepped
82511703Smichael.lebeane@amd.com    // and ready
82611703Smichael.lebeane@amd.com    bool found_prepped_pkt = false;
82711703Smichael.lebeane@amd.com
82811703Smichael.lebeane@amd.com    // if we have no row hit, prepped or not, and no seamless packet,
82911703Smichael.lebeane@amd.com    // just go for the earliest possible
83011703Smichael.lebeane@amd.com    bool found_earliest_pkt = false;
83111703Smichael.lebeane@amd.com
83211703Smichael.lebeane@amd.com    auto selected_pkt_it = queue.end();
83311703Smichael.lebeane@amd.com
83411703Smichael.lebeane@amd.com    // time we need to issue a column command to be seamless
83511703Smichael.lebeane@amd.com    const Tick min_col_at = std::max(nextBurstAt + extra_col_delay, curTick());
83611703Smichael.lebeane@amd.com
83711703Smichael.lebeane@amd.com    for (auto i = queue.begin(); i != queue.end() ; ++i) {
83811703Smichael.lebeane@amd.com        DRAMPacket* dram_pkt = *i;
83911703Smichael.lebeane@amd.com        const Bank& bank = dram_pkt->bankRef;
84011703Smichael.lebeane@amd.com        const Tick col_allowed_at = dram_pkt->isRead() ? bank.rdAllowedAt :
84111703Smichael.lebeane@amd.com                                                         bank.wrAllowedAt;
84211703Smichael.lebeane@amd.com
84311703Smichael.lebeane@amd.com        DPRINTF(DRAM, "%s checking packet in bank %d\n",
84411703Smichael.lebeane@amd.com                __func__, dram_pkt->bankRef.bank);
84511703Smichael.lebeane@amd.com
84611703Smichael.lebeane@amd.com        // check if rank is not doing a refresh and thus is available, if not,
84711703Smichael.lebeane@amd.com        // jump to the next packet
84811703Smichael.lebeane@amd.com        if (dram_pkt->rankRef.inRefIdleState()) {
84911703Smichael.lebeane@amd.com
85011703Smichael.lebeane@amd.com            DPRINTF(DRAM,
85111703Smichael.lebeane@amd.com                    "%s bank %d - Rank %d available\n", __func__,
85211703Smichael.lebeane@amd.com                    dram_pkt->bankRef.bank, dram_pkt->rankRef.rank);
85311703Smichael.lebeane@amd.com
85411703Smichael.lebeane@amd.com            // check if it is a row hit
85511290Sgabor.dozsa@arm.com            if (bank.openRow == dram_pkt->row) {
85611290Sgabor.dozsa@arm.com                // no additional rank-to-rank or same bank-group
85711290Sgabor.dozsa@arm.com                // delays, or we switched read/write and might as well
85811290Sgabor.dozsa@arm.com                // go for the row hit
85911290Sgabor.dozsa@arm.com                if (col_allowed_at <= min_col_at) {
86011290Sgabor.dozsa@arm.com                    // FCFS within the hits, giving priority to
86111290Sgabor.dozsa@arm.com                    // commands that can issue seamlessly, without
86211703Smichael.lebeane@amd.com                    // additional delay, such as same rank accesses
86311703Smichael.lebeane@amd.com                    // and/or different bank-group accesses
86411703Smichael.lebeane@amd.com                    DPRINTF(DRAM, "%s Seamless row buffer hit\n", __func__);
86511703Smichael.lebeane@amd.com                    selected_pkt_it = i;
86611290Sgabor.dozsa@arm.com                    // no need to look through the remaining queue entries
86711290Sgabor.dozsa@arm.com                    break;
86811290Sgabor.dozsa@arm.com                } else if (!found_hidden_bank && !found_prepped_pkt) {
86911290Sgabor.dozsa@arm.com                    // if we did not find a packet to a closed row that can
87011290Sgabor.dozsa@arm.com                    // issue the bank commands without incurring delay, and
87111290Sgabor.dozsa@arm.com                    // did not yet find a packet to a prepped row, remember
87211290Sgabor.dozsa@arm.com                    // the current one
87311290Sgabor.dozsa@arm.com                    selected_pkt_it = i;
87411290Sgabor.dozsa@arm.com                    found_prepped_pkt = true;
87511290Sgabor.dozsa@arm.com                    DPRINTF(DRAM, "%s Prepped row buffer hit\n", __func__);
87611290Sgabor.dozsa@arm.com                }
87711290Sgabor.dozsa@arm.com            } else if (!found_earliest_pkt) {
87811290Sgabor.dozsa@arm.com                // if we have not initialised the bank status, do it
87911290Sgabor.dozsa@arm.com                // now, and only once per scheduling decisions
88011290Sgabor.dozsa@arm.com                if (!filled_earliest_banks) {
88111290Sgabor.dozsa@arm.com                    // determine entries with earliest bank delay
88211290Sgabor.dozsa@arm.com                    std::tie(earliest_banks, hidden_bank_prep) =
88311290Sgabor.dozsa@arm.com                        minBankPrep(queue, min_col_at);
88411290Sgabor.dozsa@arm.com                    filled_earliest_banks = true;
88511290Sgabor.dozsa@arm.com                }
88610923SN/A
88711290Sgabor.dozsa@arm.com                // bank is amongst first available banks
88811290Sgabor.dozsa@arm.com                // minBankPrep will give priority to packets that can
88910923SN/A                // issue seamlessly
89011290Sgabor.dozsa@arm.com                if (bits(earliest_banks[dram_pkt->rank],
89110923SN/A                         dram_pkt->bank, dram_pkt->bank)) {
89211290Sgabor.dozsa@arm.com                    found_earliest_pkt = true;
89311290Sgabor.dozsa@arm.com                    found_hidden_bank = hidden_bank_prep;
89411290Sgabor.dozsa@arm.com
89511290Sgabor.dozsa@arm.com                    // give priority to packets that can issue
89611290Sgabor.dozsa@arm.com                    // bank commands 'behind the scenes'
89711290Sgabor.dozsa@arm.com                    // any additional delay if any will be due to
89811290Sgabor.dozsa@arm.com                    // col-to-col command requirements
89911290Sgabor.dozsa@arm.com                    if (hidden_bank_prep || !found_prepped_pkt)
90011290Sgabor.dozsa@arm.com                        selected_pkt_it = i;
90111290Sgabor.dozsa@arm.com                }
90211290Sgabor.dozsa@arm.com            }
90311290Sgabor.dozsa@arm.com        } else {
90411290Sgabor.dozsa@arm.com            DPRINTF(DRAM, "%s bank %d - Rank %d not available\n", __func__,
905                    dram_pkt->bankRef.bank, dram_pkt->rankRef.rank);
906        }
907    }
908
909    if (selected_pkt_it == queue.end()) {
910        DPRINTF(DRAM, "%s no available ranks found\n", __func__);
911    }
912
913    return selected_pkt_it;
914}
915
916void
917DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
918{
919    DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
920
921    bool needsResponse = pkt->needsResponse();
922    // do the actual memory access which also turns the packet into a
923    // response
924    access(pkt);
925
926    // turn packet around to go back to requester if response expected
927    if (needsResponse) {
928        // access already turned the packet into a response
929        assert(pkt->isResponse());
930        // response_time consumes the static latency and is charged also
931        // with headerDelay that takes into account the delay provided by
932        // the xbar and also the payloadDelay that takes into account the
933        // number of data beats.
934        Tick response_time = curTick() + static_latency + pkt->headerDelay +
935                             pkt->payloadDelay;
936        // Here we reset the timing of the packet before sending it out.
937        pkt->headerDelay = pkt->payloadDelay = 0;
938
939        // queue the packet in the response queue to be sent out after
940        // the static latency has passed
941        port.schedTimingResp(pkt, response_time);
942    } else {
943        // @todo the packet is going to be deleted, and the DRAMPacket
944        // is still having a pointer to it
945        pendingDelete.reset(pkt);
946    }
947
948    DPRINTF(DRAM, "Done\n");
949
950    return;
951}
952
953void
954DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref,
955                       Tick act_tick, uint32_t row)
956{
957    assert(rank_ref.actTicks.size() == activationLimit);
958
959    DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
960
961    // update the open row
962    assert(bank_ref.openRow == Bank::NO_ROW);
963    bank_ref.openRow = row;
964
965    // start counting anew, this covers both the case when we
966    // auto-precharged, and when this access is forced to
967    // precharge
968    bank_ref.bytesAccessed = 0;
969    bank_ref.rowAccesses = 0;
970
971    ++rank_ref.numBanksActive;
972    assert(rank_ref.numBanksActive <= banksPerRank);
973
974    DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
975            bank_ref.bank, rank_ref.rank, act_tick,
976            ranks[rank_ref.rank]->numBanksActive);
977
978    rank_ref.cmdList.push_back(Command(MemCommand::ACT, bank_ref.bank,
979                               act_tick));
980
981    DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) -
982            timeStampOffset, bank_ref.bank, rank_ref.rank);
983
984    // The next access has to respect tRAS for this bank
985    bank_ref.preAllowedAt = act_tick + tRAS;
986
987    // Respect the row-to-column command delay for both read and write cmds
988    bank_ref.rdAllowedAt = std::max(act_tick + tRCD, bank_ref.rdAllowedAt);
989    bank_ref.wrAllowedAt = std::max(act_tick + tRCD, bank_ref.wrAllowedAt);
990
991    // start by enforcing tRRD
992    for (int i = 0; i < banksPerRank; i++) {
993        // next activate to any bank in this rank must not happen
994        // before tRRD
995        if (bankGroupArch && (bank_ref.bankgr == rank_ref.banks[i].bankgr)) {
996            // bank group architecture requires longer delays between
997            // ACT commands within the same bank group.  Use tRRD_L
998            // in this case
999            rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD_L,
1000                                             rank_ref.banks[i].actAllowedAt);
1001        } else {
1002            // use shorter tRRD value when either
1003            // 1) bank group architecture is not supportted
1004            // 2) bank is in a different bank group
1005            rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD,
1006                                             rank_ref.banks[i].actAllowedAt);
1007        }
1008    }
1009
1010    // next, we deal with tXAW, if the activation limit is disabled
1011    // then we directly schedule an activate power event
1012    if (!rank_ref.actTicks.empty()) {
1013        // sanity check
1014        if (rank_ref.actTicks.back() &&
1015           (act_tick - rank_ref.actTicks.back()) < tXAW) {
1016            panic("Got %d activates in window %d (%llu - %llu) which "
1017                  "is smaller than %llu\n", activationLimit, act_tick -
1018                  rank_ref.actTicks.back(), act_tick,
1019                  rank_ref.actTicks.back(), tXAW);
1020        }
1021
1022        // shift the times used for the book keeping, the last element
1023        // (highest index) is the oldest one and hence the lowest value
1024        rank_ref.actTicks.pop_back();
1025
1026        // record an new activation (in the future)
1027        rank_ref.actTicks.push_front(act_tick);
1028
1029        // cannot activate more than X times in time window tXAW, push the
1030        // next one (the X + 1'st activate) to be tXAW away from the
1031        // oldest in our window of X
1032        if (rank_ref.actTicks.back() &&
1033           (act_tick - rank_ref.actTicks.back()) < tXAW) {
1034            DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate "
1035                    "no earlier than %llu\n", activationLimit,
1036                    rank_ref.actTicks.back() + tXAW);
1037            for (int j = 0; j < banksPerRank; j++)
1038                // next activate must not happen before end of window
1039                rank_ref.banks[j].actAllowedAt =
1040                    std::max(rank_ref.actTicks.back() + tXAW,
1041                             rank_ref.banks[j].actAllowedAt);
1042        }
1043    }
1044
1045    // at the point when this activate takes place, make sure we
1046    // transition to the active power state
1047    if (!rank_ref.activateEvent.scheduled())
1048        schedule(rank_ref.activateEvent, act_tick);
1049    else if (rank_ref.activateEvent.when() > act_tick)
1050        // move it sooner in time
1051        reschedule(rank_ref.activateEvent, act_tick);
1052}
1053
1054void
1055DRAMCtrl::prechargeBank(Rank& rank_ref, Bank& bank, Tick pre_at, bool trace)
1056{
1057    // make sure the bank has an open row
1058    assert(bank.openRow != Bank::NO_ROW);
1059
1060    // sample the bytes per activate here since we are closing
1061    // the page
1062    bytesPerActivate.sample(bank.bytesAccessed);
1063
1064    bank.openRow = Bank::NO_ROW;
1065
1066    // no precharge allowed before this one
1067    bank.preAllowedAt = pre_at;
1068
1069    Tick pre_done_at = pre_at + tRP;
1070
1071    bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at);
1072
1073    assert(rank_ref.numBanksActive != 0);
1074    --rank_ref.numBanksActive;
1075
1076    DPRINTF(DRAM, "Precharging bank %d, rank %d at tick %lld, now got "
1077            "%d active\n", bank.bank, rank_ref.rank, pre_at,
1078            rank_ref.numBanksActive);
1079
1080    if (trace) {
1081
1082        rank_ref.cmdList.push_back(Command(MemCommand::PRE, bank.bank,
1083                                   pre_at));
1084        DPRINTF(DRAMPower, "%llu,PRE,%d,%d\n", divCeil(pre_at, tCK) -
1085                timeStampOffset, bank.bank, rank_ref.rank);
1086    }
1087    // if we look at the current number of active banks we might be
1088    // tempted to think the DRAM is now idle, however this can be
1089    // undone by an activate that is scheduled to happen before we
1090    // would have reached the idle state, so schedule an event and
1091    // rather check once we actually make it to the point in time when
1092    // the (last) precharge takes place
1093    if (!rank_ref.prechargeEvent.scheduled()) {
1094        schedule(rank_ref.prechargeEvent, pre_done_at);
1095        // New event, increment count
1096        ++rank_ref.outstandingEvents;
1097    } else if (rank_ref.prechargeEvent.when() < pre_done_at) {
1098        reschedule(rank_ref.prechargeEvent, pre_done_at);
1099    }
1100}
1101
1102void
1103DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
1104{
1105    DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1106            dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1107
1108    // get the rank
1109    Rank& rank = dram_pkt->rankRef;
1110
1111    // are we in or transitioning to a low-power state and have not scheduled
1112    // a power-up event?
1113    // if so, wake up from power down to issue RD/WR burst
1114    if (rank.inLowPowerState) {
1115        assert(rank.pwrState != PWR_SREF);
1116        rank.scheduleWakeUpEvent(tXP);
1117    }
1118
1119    // get the bank
1120    Bank& bank = dram_pkt->bankRef;
1121
1122    // for the state we need to track if it is a row hit or not
1123    bool row_hit = true;
1124
1125    // Determine the access latency and update the bank state
1126    if (bank.openRow == dram_pkt->row) {
1127        // nothing to do
1128    } else {
1129        row_hit = false;
1130
1131        // If there is a page open, precharge it.
1132        if (bank.openRow != Bank::NO_ROW) {
1133            prechargeBank(rank, bank, std::max(bank.preAllowedAt, curTick()));
1134        }
1135
1136        // next we need to account for the delay in activating the
1137        // page
1138        Tick act_tick = std::max(bank.actAllowedAt, curTick());
1139
1140        // Record the activation and deal with all the global timing
1141        // constraints caused be a new activation (tRRD and tXAW)
1142        activateBank(rank, bank, act_tick, dram_pkt->row);
1143    }
1144
1145    // respect any constraints on the command (e.g. tRCD or tCCD)
1146    const Tick col_allowed_at = dram_pkt->isRead() ?
1147                                          bank.rdAllowedAt : bank.wrAllowedAt;
1148
1149    // we need to wait until the bus is available before we can issue
1150    // the command; need minimum of tBURST between commands
1151    Tick cmd_at = std::max({col_allowed_at, nextBurstAt, curTick()});
1152
1153    // update the packet ready time
1154    dram_pkt->readyTime = cmd_at + tCL + tBURST;
1155
1156    // update the time for the next read/write burst for each
1157    // bank (add a max with tCCD/tCCD_L/tCCD_L_WR here)
1158    Tick dly_to_rd_cmd;
1159    Tick dly_to_wr_cmd;
1160    for (int j = 0; j < ranksPerChannel; j++) {
1161        for (int i = 0; i < banksPerRank; i++) {
1162            // next burst to same bank group in this rank must not happen
1163            // before tCCD_L.  Different bank group timing requirement is
1164            // tBURST; Add tCS for different ranks
1165            if (dram_pkt->rank == j) {
1166                if (bankGroupArch &&
1167                   (bank.bankgr == ranks[j]->banks[i].bankgr)) {
1168                    // bank group architecture requires longer delays between
1169                    // RD/WR burst commands to the same bank group.
1170                    // tCCD_L is default requirement for same BG timing
1171                    // tCCD_L_WR is required for write-to-write
1172                    // Need to also take bus turnaround delays into account
1173                    dly_to_rd_cmd = dram_pkt->isRead() ?
1174                                    tCCD_L : std::max(tCCD_L, wrToRdDly);
1175                    dly_to_wr_cmd = dram_pkt->isRead() ?
1176                                    std::max(tCCD_L, rdToWrDly) : tCCD_L_WR;
1177                } else {
1178                    // tBURST is default requirement for diff BG timing
1179                    // Need to also take bus turnaround delays into account
1180                    dly_to_rd_cmd = dram_pkt->isRead() ? tBURST : wrToRdDly;
1181                    dly_to_wr_cmd = dram_pkt->isRead() ? rdToWrDly : tBURST;
1182                }
1183            } else {
1184                // different rank is by default in a different bank group and
1185                // doesn't require longer tCCD or additional RTW, WTR delays
1186                // Need to account for rank-to-rank switching with tCS
1187                dly_to_wr_cmd = rankToRankDly;
1188                dly_to_rd_cmd = rankToRankDly;
1189            }
1190            ranks[j]->banks[i].rdAllowedAt = std::max(cmd_at + dly_to_rd_cmd,
1191                                             ranks[j]->banks[i].rdAllowedAt);
1192            ranks[j]->banks[i].wrAllowedAt = std::max(cmd_at + dly_to_wr_cmd,
1193                                             ranks[j]->banks[i].wrAllowedAt);
1194        }
1195    }
1196
1197    // Save rank of current access
1198    activeRank = dram_pkt->rank;
1199
1200    // If this is a write, we also need to respect the write recovery
1201    // time before a precharge, in the case of a read, respect the
1202    // read to precharge constraint
1203    bank.preAllowedAt = std::max(bank.preAllowedAt,
1204                                 dram_pkt->isRead() ? cmd_at + tRTP :
1205                                 dram_pkt->readyTime + tWR);
1206
1207    // increment the bytes accessed and the accesses per row
1208    bank.bytesAccessed += burstSize;
1209    ++bank.rowAccesses;
1210
1211    // if we reached the max, then issue with an auto-precharge
1212    bool auto_precharge = pageMgmt == Enums::close ||
1213        bank.rowAccesses == maxAccessesPerRow;
1214
1215    // if we did not hit the limit, we might still want to
1216    // auto-precharge
1217    if (!auto_precharge &&
1218        (pageMgmt == Enums::open_adaptive ||
1219         pageMgmt == Enums::close_adaptive)) {
1220        // a twist on the open and close page policies:
1221        // 1) open_adaptive page policy does not blindly keep the
1222        // page open, but close it if there are no row hits, and there
1223        // are bank conflicts in the queue
1224        // 2) close_adaptive page policy does not blindly close the
1225        // page, but closes it only if there are no row hits in the queue.
1226        // In this case, only force an auto precharge when there
1227        // are no same page hits in the queue
1228        bool got_more_hits = false;
1229        bool got_bank_conflict = false;
1230
1231        // either look at the read queue or write queue
1232        const std::vector<DRAMPacketQueue>& queue =
1233                dram_pkt->isRead() ? readQueue : writeQueue;
1234
1235        for (uint8_t i = 0; i < numPriorities(); ++i) {
1236            auto p = queue[i].begin();
1237            // keep on looking until we find a hit or reach the end of the queue
1238            // 1) if a hit is found, then both open and close adaptive policies keep
1239            // the page open
1240            // 2) if no hit is found, got_bank_conflict is set to true if a bank
1241            // conflict request is waiting in the queue
1242            // 3) make sure we are not considering the packet that we are
1243            // currently dealing with
1244            while (!got_more_hits && p != queue[i].end()) {
1245                if (dram_pkt != (*p)) {
1246                    bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
1247                                          (dram_pkt->bank == (*p)->bank);
1248
1249                    bool same_row = dram_pkt->row == (*p)->row;
1250                    got_more_hits |= same_rank_bank && same_row;
1251                    got_bank_conflict |= same_rank_bank && !same_row;
1252                }
1253                ++p;
1254            }
1255
1256            if (got_more_hits)
1257                break;
1258        }
1259
1260        // auto pre-charge when either
1261        // 1) open_adaptive policy, we have not got any more hits, and
1262        //    have a bank conflict
1263        // 2) close_adaptive policy and we have not got any more hits
1264        auto_precharge = !got_more_hits &&
1265            (got_bank_conflict || pageMgmt == Enums::close_adaptive);
1266    }
1267
1268    // DRAMPower trace command to be written
1269    std::string mem_cmd = dram_pkt->isRead() ? "RD" : "WR";
1270
1271    // MemCommand required for DRAMPower library
1272    MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD :
1273                                                   MemCommand::WR;
1274
1275    // Update bus state to reflect when previous command was issued
1276    nextBurstAt = cmd_at + tBURST;
1277
1278    DPRINTF(DRAM, "Access to %lld, ready at %lld next burst at %lld.\n",
1279            dram_pkt->addr, dram_pkt->readyTime, nextBurstAt);
1280
1281    dram_pkt->rankRef.cmdList.push_back(Command(command, dram_pkt->bank,
1282                                        cmd_at));
1283
1284    DPRINTF(DRAMPower, "%llu,%s,%d,%d\n", divCeil(cmd_at, tCK) -
1285            timeStampOffset, mem_cmd, dram_pkt->bank, dram_pkt->rank);
1286
1287    // if this access should use auto-precharge, then we are
1288    // closing the row after the read/write burst
1289    if (auto_precharge) {
1290        // if auto-precharge push a PRE command at the correct tick to the
1291        // list used by DRAMPower library to calculate power
1292        prechargeBank(rank, bank, std::max(curTick(), bank.preAllowedAt));
1293
1294        DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId);
1295    }
1296
1297    // Update the minimum timing between the requests, this is a
1298    // conservative estimate of when we have to schedule the next
1299    // request to not introduce any unecessary bubbles. In most cases
1300    // we will wake up sooner than we have to.
1301    nextReqTime = nextBurstAt - (tRP + tRCD);
1302
1303    // Update the stats and schedule the next request
1304    if (dram_pkt->isRead()) {
1305        ++readsThisTime;
1306        if (row_hit)
1307            readRowHits++;
1308        bytesReadDRAM += burstSize;
1309        perBankRdBursts[dram_pkt->bankId]++;
1310
1311        // Update latency stats
1312        totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1313        masterReadTotalLat[dram_pkt->masterId()] +=
1314            dram_pkt->readyTime - dram_pkt->entryTime;
1315
1316        totBusLat += tBURST;
1317        totQLat += cmd_at - dram_pkt->entryTime;
1318        masterReadBytes[dram_pkt->masterId()] += dram_pkt->size;
1319    } else {
1320        ++writesThisTime;
1321        if (row_hit)
1322            writeRowHits++;
1323        bytesWritten += burstSize;
1324        perBankWrBursts[dram_pkt->bankId]++;
1325        masterWriteBytes[dram_pkt->masterId()] += dram_pkt->size;
1326        masterWriteTotalLat[dram_pkt->masterId()] +=
1327            dram_pkt->readyTime - dram_pkt->entryTime;
1328    }
1329}
1330
1331void
1332DRAMCtrl::processNextReqEvent()
1333{
1334    // transition is handled by QoS algorithm if enabled
1335    if (turnPolicy) {
1336        // select bus state - only done if QoS algorithms are in use
1337        busStateNext = selectNextBusState();
1338    }
1339
1340    // detect bus state change
1341    bool switched_cmd_type = (busState != busStateNext);
1342    // record stats
1343    recordTurnaroundStats();
1344
1345    DPRINTF(DRAM, "QoS Turnarounds selected state %s %s\n",
1346            (busState==MemCtrl::READ)?"READ":"WRITE",
1347            switched_cmd_type?"[turnaround triggered]":"");
1348
1349    if (switched_cmd_type) {
1350        if (busState == READ) {
1351            DPRINTF(DRAM,
1352                    "Switching to writes after %d reads with %d reads "
1353                    "waiting\n", readsThisTime, totalReadQueueSize);
1354            rdPerTurnAround.sample(readsThisTime);
1355            readsThisTime = 0;
1356        } else {
1357            DPRINTF(DRAM,
1358                    "Switching to reads after %d writes with %d writes "
1359                    "waiting\n", writesThisTime, totalWriteQueueSize);
1360            wrPerTurnAround.sample(writesThisTime);
1361            writesThisTime = 0;
1362        }
1363    }
1364
1365    // updates current state
1366    busState = busStateNext;
1367
1368    // check ranks for refresh/wakeup - uses busStateNext, so done after turnaround
1369    // decisions
1370    int busyRanks = 0;
1371    for (auto r : ranks) {
1372        if (!r->inRefIdleState()) {
1373            if (r->pwrState != PWR_SREF) {
1374                // rank is busy refreshing
1375                DPRINTF(DRAMState, "Rank %d is not available\n", r->rank);
1376                busyRanks++;
1377
1378                // let the rank know that if it was waiting to drain, it
1379                // is now done and ready to proceed
1380                r->checkDrainDone();
1381            }
1382
1383            // check if we were in self-refresh and haven't started
1384            // to transition out
1385            if ((r->pwrState == PWR_SREF) && r->inLowPowerState) {
1386                DPRINTF(DRAMState, "Rank %d is in self-refresh\n", r->rank);
1387                // if we have commands queued to this rank and we don't have
1388                // a minimum number of active commands enqueued,
1389                // exit self-refresh
1390                if (r->forceSelfRefreshExit()) {
1391                    DPRINTF(DRAMState, "rank %d was in self refresh and"
1392                           " should wake up\n", r->rank);
1393                    //wake up from self-refresh
1394                    r->scheduleWakeUpEvent(tXS);
1395                    // things are brought back into action once a refresh is
1396                    // performed after self-refresh
1397                    // continue with selection for other ranks
1398                }
1399            }
1400        }
1401    }
1402
1403    if (busyRanks == ranksPerChannel) {
1404        // if all ranks are refreshing wait for them to finish
1405        // and stall this state machine without taking any further
1406        // action, and do not schedule a new nextReqEvent
1407        return;
1408    }
1409
1410    // when we get here it is either a read or a write
1411    if (busState == READ) {
1412
1413        // track if we should switch or not
1414        bool switch_to_writes = false;
1415
1416        if (totalReadQueueSize == 0) {
1417            // In the case there is no read request to go next,
1418            // trigger writes if we have passed the low threshold (or
1419            // if we are draining)
1420            if (!(totalWriteQueueSize == 0) &&
1421                (drainState() == DrainState::Draining ||
1422                 totalWriteQueueSize > writeLowThreshold)) {
1423
1424                DPRINTF(DRAM, "Switching to writes due to read queue empty\n");
1425                switch_to_writes = true;
1426            } else {
1427                // check if we are drained
1428                // not done draining until in PWR_IDLE state
1429                // ensuring all banks are closed and
1430                // have exited low power states
1431                if (drainState() == DrainState::Draining &&
1432                    respQueue.empty() && allRanksDrained()) {
1433
1434                    DPRINTF(Drain, "DRAM controller done draining\n");
1435                    signalDrainDone();
1436                }
1437
1438                // nothing to do, not even any point in scheduling an
1439                // event for the next request
1440                return;
1441            }
1442        } else {
1443
1444            bool read_found = false;
1445            DRAMPacketQueue::iterator to_read;
1446            uint8_t prio = numPriorities();
1447
1448            for (auto queue = readQueue.rbegin();
1449                 queue != readQueue.rend(); ++queue) {
1450
1451                prio--;
1452
1453                DPRINTF(QOS,
1454                        "DRAM controller checking READ queue [%d] priority [%d elements]\n",
1455                        prio, queue->size());
1456
1457                // Figure out which read request goes next
1458                // If we are changing command type, incorporate the minimum
1459                // bus turnaround delay which will be tCS (different rank) case
1460                to_read = chooseNext((*queue), switched_cmd_type ? tCS : 0);
1461
1462                if (to_read != queue->end()) {
1463                    // candidate read found
1464                    read_found = true;
1465                    break;
1466                }
1467            }
1468
1469            // if no read to an available rank is found then return
1470            // at this point. There could be writes to the available ranks
1471            // which are above the required threshold. However, to
1472            // avoid adding more complexity to the code, return and wait
1473            // for a refresh event to kick things into action again.
1474            if (!read_found) {
1475                DPRINTF(DRAM, "No Reads Found - exiting\n");
1476                return;
1477            }
1478
1479            auto dram_pkt = *to_read;
1480
1481            assert(dram_pkt->rankRef.inRefIdleState());
1482
1483            doDRAMAccess(dram_pkt);
1484
1485            // Every respQueue which will generate an event, increment count
1486            ++dram_pkt->rankRef.outstandingEvents;
1487            // sanity check
1488            assert(dram_pkt->size <= burstSize);
1489            assert(dram_pkt->readyTime >= curTick());
1490
1491            // log the response
1492            logResponse(MemCtrl::READ, (*to_read)->masterId(),
1493                        dram_pkt->qosValue(), dram_pkt->getAddr(), 1,
1494                        dram_pkt->readyTime - dram_pkt->entryTime);
1495
1496
1497            // Insert into response queue. It will be sent back to the
1498            // requester at its readyTime
1499            if (respQueue.empty()) {
1500                assert(!respondEvent.scheduled());
1501                schedule(respondEvent, dram_pkt->readyTime);
1502            } else {
1503                assert(respQueue.back()->readyTime <= dram_pkt->readyTime);
1504                assert(respondEvent.scheduled());
1505            }
1506
1507            respQueue.push_back(dram_pkt);
1508
1509            // we have so many writes that we have to transition
1510            if (totalWriteQueueSize > writeHighThreshold) {
1511                switch_to_writes = true;
1512            }
1513
1514            // remove the request from the queue - the iterator is no longer valid .
1515            readQueue[dram_pkt->qosValue()].erase(to_read);
1516        }
1517
1518        // switching to writes, either because the read queue is empty
1519        // and the writes have passed the low threshold (or we are
1520        // draining), or because the writes hit the hight threshold
1521        if (switch_to_writes) {
1522            // transition to writing
1523            busStateNext = WRITE;
1524        }
1525    } else {
1526
1527        bool write_found = false;
1528        DRAMPacketQueue::iterator to_write;
1529        uint8_t prio = numPriorities();
1530
1531        for (auto queue = writeQueue.rbegin();
1532             queue != writeQueue.rend(); ++queue) {
1533
1534            prio--;
1535
1536            DPRINTF(QOS,
1537                    "DRAM controller checking WRITE queue [%d] priority [%d elements]\n",
1538                    prio, queue->size());
1539
1540            // If we are changing command type, incorporate the minimum
1541            // bus turnaround delay
1542            to_write = chooseNext((*queue),
1543                                  switched_cmd_type ? std::min(tRTW, tCS) : 0);
1544
1545            if (to_write != queue->end()) {
1546                write_found = true;
1547                break;
1548            }
1549        }
1550
1551        // if there are no writes to a rank that is available to service
1552        // requests (i.e. rank is in refresh idle state) are found then
1553        // return. There could be reads to the available ranks. However, to
1554        // avoid adding more complexity to the code, return at this point and
1555        // wait for a refresh event to kick things into action again.
1556        if (!write_found) {
1557            DPRINTF(DRAM, "No Writes Found - exiting\n");
1558            return;
1559        }
1560
1561        auto dram_pkt = *to_write;
1562
1563        assert(dram_pkt->rankRef.inRefIdleState());
1564        // sanity check
1565        assert(dram_pkt->size <= burstSize);
1566
1567        doDRAMAccess(dram_pkt);
1568
1569        // removed write from queue, decrement count
1570        --dram_pkt->rankRef.writeEntries;
1571
1572        // Schedule write done event to decrement event count
1573        // after the readyTime has been reached
1574        // Only schedule latest write event to minimize events
1575        // required; only need to ensure that final event scheduled covers
1576        // the time that writes are outstanding and bus is active
1577        // to holdoff power-down entry events
1578        if (!dram_pkt->rankRef.writeDoneEvent.scheduled()) {
1579            schedule(dram_pkt->rankRef.writeDoneEvent, dram_pkt->readyTime);
1580            // New event, increment count
1581            ++dram_pkt->rankRef.outstandingEvents;
1582
1583        } else if (dram_pkt->rankRef.writeDoneEvent.when() <
1584                   dram_pkt->readyTime) {
1585
1586            reschedule(dram_pkt->rankRef.writeDoneEvent, dram_pkt->readyTime);
1587        }
1588
1589        isInWriteQueue.erase(burstAlign(dram_pkt->addr));
1590
1591        // log the response
1592        logResponse(MemCtrl::WRITE, dram_pkt->masterId(),
1593                    dram_pkt->qosValue(), dram_pkt->getAddr(), 1,
1594                    dram_pkt->readyTime - dram_pkt->entryTime);
1595
1596
1597        // remove the request from the queue - the iterator is no longer valid
1598        writeQueue[dram_pkt->qosValue()].erase(to_write);
1599
1600        delete dram_pkt;
1601
1602        // If we emptied the write queue, or got sufficiently below the
1603        // threshold (using the minWritesPerSwitch as the hysteresis) and
1604        // are not draining, or we have reads waiting and have done enough
1605        // writes, then switch to reads.
1606        bool below_threshold =
1607            totalWriteQueueSize + minWritesPerSwitch < writeLowThreshold;
1608
1609        if (totalWriteQueueSize == 0 ||
1610            (below_threshold && drainState() != DrainState::Draining) ||
1611            (totalReadQueueSize && writesThisTime >= minWritesPerSwitch)) {
1612
1613            // turn the bus back around for reads again
1614            busStateNext = READ;
1615
1616            // note that the we switch back to reads also in the idle
1617            // case, which eventually will check for any draining and
1618            // also pause any further scheduling if there is really
1619            // nothing to do
1620        }
1621    }
1622    // It is possible that a refresh to another rank kicks things back into
1623    // action before reaching this point.
1624    if (!nextReqEvent.scheduled())
1625        schedule(nextReqEvent, std::max(nextReqTime, curTick()));
1626
1627    // If there is space available and we have writes waiting then let
1628    // them retry. This is done here to ensure that the retry does not
1629    // cause a nextReqEvent to be scheduled before we do so as part of
1630    // the next request processing
1631    if (retryWrReq && totalWriteQueueSize < writeBufferSize) {
1632        retryWrReq = false;
1633        port.sendRetryReq();
1634    }
1635}
1636
1637pair<vector<uint32_t>, bool>
1638DRAMCtrl::minBankPrep(const DRAMPacketQueue& queue,
1639                      Tick min_col_at) const
1640{
1641    Tick min_act_at = MaxTick;
1642    vector<uint32_t> bank_mask(ranksPerChannel, 0);
1643
1644    // latest Tick for which ACT can occur without incurring additoinal
1645    // delay on the data bus
1646    const Tick hidden_act_max = std::max(min_col_at - tRCD, curTick());
1647
1648    // Flag condition when burst can issue back-to-back with previous burst
1649    bool found_seamless_bank = false;
1650
1651    // Flag condition when bank can be opened without incurring additional
1652    // delay on the data bus
1653    bool hidden_bank_prep = false;
1654
1655    // determine if we have queued transactions targetting the
1656    // bank in question
1657    vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
1658    for (const auto& p : queue) {
1659        if (p->rankRef.inRefIdleState())
1660            got_waiting[p->bankId] = true;
1661    }
1662
1663    // Find command with optimal bank timing
1664    // Will prioritize commands that can issue seamlessly.
1665    for (int i = 0; i < ranksPerChannel; i++) {
1666        for (int j = 0; j < banksPerRank; j++) {
1667            uint16_t bank_id = i * banksPerRank + j;
1668
1669            // if we have waiting requests for the bank, and it is
1670            // amongst the first available, update the mask
1671            if (got_waiting[bank_id]) {
1672                // make sure this rank is not currently refreshing.
1673                assert(ranks[i]->inRefIdleState());
1674                // simplistic approximation of when the bank can issue
1675                // an activate, ignoring any rank-to-rank switching
1676                // cost in this calculation
1677                Tick act_at = ranks[i]->banks[j].openRow == Bank::NO_ROW ?
1678                    std::max(ranks[i]->banks[j].actAllowedAt, curTick()) :
1679                    std::max(ranks[i]->banks[j].preAllowedAt, curTick()) + tRP;
1680
1681                // When is the earliest the R/W burst can issue?
1682                const Tick col_allowed_at = (busState == READ) ?
1683                                              ranks[i]->banks[j].rdAllowedAt :
1684                                              ranks[i]->banks[j].wrAllowedAt;
1685                Tick col_at = std::max(col_allowed_at, act_at + tRCD);
1686
1687                // bank can issue burst back-to-back (seamlessly) with
1688                // previous burst
1689                bool new_seamless_bank = col_at <= min_col_at;
1690
1691                // if we found a new seamless bank or we have no
1692                // seamless banks, and got a bank with an earlier
1693                // activate time, it should be added to the bit mask
1694                if (new_seamless_bank ||
1695                    (!found_seamless_bank && act_at <= min_act_at)) {
1696                    // if we did not have a seamless bank before, and
1697                    // we do now, reset the bank mask, also reset it
1698                    // if we have not yet found a seamless bank and
1699                    // the activate time is smaller than what we have
1700                    // seen so far
1701                    if (!found_seamless_bank &&
1702                        (new_seamless_bank || act_at < min_act_at)) {
1703                        std::fill(bank_mask.begin(), bank_mask.end(), 0);
1704                    }
1705
1706                    found_seamless_bank |= new_seamless_bank;
1707
1708                    // ACT can occur 'behind the scenes'
1709                    hidden_bank_prep = act_at <= hidden_act_max;
1710
1711                    // set the bit corresponding to the available bank
1712                    replaceBits(bank_mask[i], j, j, 1);
1713                    min_act_at = act_at;
1714                }
1715            }
1716        }
1717    }
1718
1719    return make_pair(bank_mask, hidden_bank_prep);
1720}
1721
1722DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p, int rank)
1723    : EventManager(&_memory), memory(_memory),
1724      pwrStateTrans(PWR_IDLE), pwrStatePostRefresh(PWR_IDLE),
1725      pwrStateTick(0), refreshDueAt(0), pwrState(PWR_IDLE),
1726      refreshState(REF_IDLE), inLowPowerState(false), rank(rank),
1727      readEntries(0), writeEntries(0), outstandingEvents(0),
1728      wakeUpAllowedAt(0), power(_p, false), banks(_p->banks_per_rank),
1729      numBanksActive(0), actTicks(_p->activation_limit, 0),
1730      writeDoneEvent([this]{ processWriteDoneEvent(); }, name()),
1731      activateEvent([this]{ processActivateEvent(); }, name()),
1732      prechargeEvent([this]{ processPrechargeEvent(); }, name()),
1733      refreshEvent([this]{ processRefreshEvent(); }, name()),
1734      powerEvent([this]{ processPowerEvent(); }, name()),
1735      wakeUpEvent([this]{ processWakeUpEvent(); }, name())
1736{
1737    for (int b = 0; b < _p->banks_per_rank; b++) {
1738        banks[b].bank = b;
1739        // GDDR addressing of banks to BG is linear.
1740        // Here we assume that all DRAM generations address bank groups as
1741        // follows:
1742        if (_p->bank_groups_per_rank > 0) {
1743            // Simply assign lower bits to bank group in order to
1744            // rotate across bank groups as banks are incremented
1745            // e.g. with 4 banks per bank group and 16 banks total:
1746            //    banks 0,4,8,12  are in bank group 0
1747            //    banks 1,5,9,13  are in bank group 1
1748            //    banks 2,6,10,14 are in bank group 2
1749            //    banks 3,7,11,15 are in bank group 3
1750            banks[b].bankgr = b % _p->bank_groups_per_rank;
1751        } else {
1752            // No bank groups; simply assign to bank number
1753            banks[b].bankgr = b;
1754        }
1755    }
1756}
1757
1758void
1759DRAMCtrl::Rank::startup(Tick ref_tick)
1760{
1761    assert(ref_tick > curTick());
1762
1763    pwrStateTick = curTick();
1764
1765    // kick off the refresh, and give ourselves enough time to
1766    // precharge
1767    schedule(refreshEvent, ref_tick);
1768}
1769
1770void
1771DRAMCtrl::Rank::suspend()
1772{
1773    deschedule(refreshEvent);
1774
1775    // Update the stats
1776    updatePowerStats();
1777
1778    // don't automatically transition back to LP state after next REF
1779    pwrStatePostRefresh = PWR_IDLE;
1780}
1781
1782bool
1783DRAMCtrl::Rank::isQueueEmpty() const
1784{
1785    // check commmands in Q based on current bus direction
1786    bool no_queued_cmds = ((memory.busStateNext == READ) && (readEntries == 0))
1787                          || ((memory.busStateNext == WRITE) &&
1788                              (writeEntries == 0));
1789    return no_queued_cmds;
1790}
1791
1792void
1793DRAMCtrl::Rank::checkDrainDone()
1794{
1795    // if this rank was waiting to drain it is now able to proceed to
1796    // precharge
1797    if (refreshState == REF_DRAIN) {
1798        DPRINTF(DRAM, "Refresh drain done, now precharging\n");
1799
1800        refreshState = REF_PD_EXIT;
1801
1802        // hand control back to the refresh event loop
1803        schedule(refreshEvent, curTick());
1804    }
1805}
1806
1807void
1808DRAMCtrl::Rank::flushCmdList()
1809{
1810    // at the moment sort the list of commands and update the counters
1811    // for DRAMPower libray when doing a refresh
1812    sort(cmdList.begin(), cmdList.end(), DRAMCtrl::sortTime);
1813
1814    auto next_iter = cmdList.begin();
1815    // push to commands to DRAMPower
1816    for ( ; next_iter != cmdList.end() ; ++next_iter) {
1817         Command cmd = *next_iter;
1818         if (cmd.timeStamp <= curTick()) {
1819             // Move all commands at or before curTick to DRAMPower
1820             power.powerlib.doCommand(cmd.type, cmd.bank,
1821                                      divCeil(cmd.timeStamp, memory.tCK) -
1822                                      memory.timeStampOffset);
1823         } else {
1824             // done - found all commands at or before curTick()
1825             // next_iter references the 1st command after curTick
1826             break;
1827         }
1828    }
1829    // reset cmdList to only contain commands after curTick
1830    // if there are no commands after curTick, updated cmdList will be empty
1831    // in this case, next_iter is cmdList.end()
1832    cmdList.assign(next_iter, cmdList.end());
1833}
1834
1835void
1836DRAMCtrl::Rank::processActivateEvent()
1837{
1838    // we should transition to the active state as soon as any bank is active
1839    if (pwrState != PWR_ACT)
1840        // note that at this point numBanksActive could be back at
1841        // zero again due to a precharge scheduled in the future
1842        schedulePowerEvent(PWR_ACT, curTick());
1843}
1844
1845void
1846DRAMCtrl::Rank::processPrechargeEvent()
1847{
1848    // counter should at least indicate one outstanding request
1849    // for this precharge
1850    assert(outstandingEvents > 0);
1851    // precharge complete, decrement count
1852    --outstandingEvents;
1853
1854    // if we reached zero, then special conditions apply as we track
1855    // if all banks are precharged for the power models
1856    if (numBanksActive == 0) {
1857        // no reads to this rank in the Q and no pending
1858        // RD/WR or refresh commands
1859        if (isQueueEmpty() && outstandingEvents == 0 &&
1860            memory.enableDRAMPowerdown) {
1861            // should still be in ACT state since bank still open
1862            assert(pwrState == PWR_ACT);
1863
1864            // All banks closed - switch to precharge power down state.
1865            DPRINTF(DRAMState, "Rank %d sleep at tick %d\n",
1866                    rank, curTick());
1867            powerDownSleep(PWR_PRE_PDN, curTick());
1868        } else {
1869            // we should transition to the idle state when the last bank
1870            // is precharged
1871            schedulePowerEvent(PWR_IDLE, curTick());
1872        }
1873    }
1874}
1875
1876void
1877DRAMCtrl::Rank::processWriteDoneEvent()
1878{
1879    // counter should at least indicate one outstanding request
1880    // for this write
1881    assert(outstandingEvents > 0);
1882    // Write transfer on bus has completed
1883    // decrement per rank counter
1884    --outstandingEvents;
1885}
1886
1887void
1888DRAMCtrl::Rank::processRefreshEvent()
1889{
1890    // when first preparing the refresh, remember when it was due
1891    if ((refreshState == REF_IDLE) || (refreshState == REF_SREF_EXIT)) {
1892        // remember when the refresh is due
1893        refreshDueAt = curTick();
1894
1895        // proceed to drain
1896        refreshState = REF_DRAIN;
1897
1898        // make nonzero while refresh is pending to ensure
1899        // power down and self-refresh are not entered
1900        ++outstandingEvents;
1901
1902        DPRINTF(DRAM, "Refresh due\n");
1903    }
1904
1905    // let any scheduled read or write to the same rank go ahead,
1906    // after which it will
1907    // hand control back to this event loop
1908    if (refreshState == REF_DRAIN) {
1909        // if a request is at the moment being handled and this request is
1910        // accessing the current rank then wait for it to finish
1911        if ((rank == memory.activeRank)
1912            && (memory.nextReqEvent.scheduled())) {
1913            // hand control over to the request loop until it is
1914            // evaluated next
1915            DPRINTF(DRAM, "Refresh awaiting draining\n");
1916
1917            return;
1918        } else {
1919            refreshState = REF_PD_EXIT;
1920        }
1921    }
1922
1923    // at this point, ensure that rank is not in a power-down state
1924    if (refreshState == REF_PD_EXIT) {
1925        // if rank was sleeping and we have't started exit process,
1926        // wake-up for refresh
1927        if (inLowPowerState) {
1928            DPRINTF(DRAM, "Wake Up for refresh\n");
1929            // save state and return after refresh completes
1930            scheduleWakeUpEvent(memory.tXP);
1931            return;
1932        } else {
1933            refreshState = REF_PRE;
1934        }
1935    }
1936
1937    // at this point, ensure that all banks are precharged
1938    if (refreshState == REF_PRE) {
1939        // precharge any active bank
1940        if (numBanksActive != 0) {
1941            // at the moment, we use a precharge all even if there is
1942            // only a single bank open
1943            DPRINTF(DRAM, "Precharging all\n");
1944
1945            // first determine when we can precharge
1946            Tick pre_at = curTick();
1947
1948            for (auto &b : banks) {
1949                // respect both causality and any existing bank
1950                // constraints, some banks could already have a
1951                // (auto) precharge scheduled
1952                pre_at = std::max(b.preAllowedAt, pre_at);
1953            }
1954
1955            // make sure all banks per rank are precharged, and for those that
1956            // already are, update their availability
1957            Tick act_allowed_at = pre_at + memory.tRP;
1958
1959            for (auto &b : banks) {
1960                if (b.openRow != Bank::NO_ROW) {
1961                    memory.prechargeBank(*this, b, pre_at, false);
1962                } else {
1963                    b.actAllowedAt = std::max(b.actAllowedAt, act_allowed_at);
1964                    b.preAllowedAt = std::max(b.preAllowedAt, pre_at);
1965                }
1966            }
1967
1968            // precharge all banks in rank
1969            cmdList.push_back(Command(MemCommand::PREA, 0, pre_at));
1970
1971            DPRINTF(DRAMPower, "%llu,PREA,0,%d\n",
1972                    divCeil(pre_at, memory.tCK) -
1973                            memory.timeStampOffset, rank);
1974        } else if ((pwrState == PWR_IDLE) && (outstandingEvents == 1))  {
1975            // Banks are closed, have transitioned to IDLE state, and
1976            // no outstanding ACT,RD/WR,Auto-PRE sequence scheduled
1977            DPRINTF(DRAM, "All banks already precharged, starting refresh\n");
1978
1979            // go ahead and kick the power state machine into gear since
1980            // we are already idle
1981            schedulePowerEvent(PWR_REF, curTick());
1982        } else {
1983            // banks state is closed but haven't transitioned pwrState to IDLE
1984            // or have outstanding ACT,RD/WR,Auto-PRE sequence scheduled
1985            // should have outstanding precharge event in this case
1986            assert(prechargeEvent.scheduled());
1987            // will start refresh when pwrState transitions to IDLE
1988        }
1989
1990        assert(numBanksActive == 0);
1991
1992        // wait for all banks to be precharged, at which point the
1993        // power state machine will transition to the idle state, and
1994        // automatically move to a refresh, at that point it will also
1995        // call this method to get the refresh event loop going again
1996        return;
1997    }
1998
1999    // last but not least we perform the actual refresh
2000    if (refreshState == REF_START) {
2001        // should never get here with any banks active
2002        assert(numBanksActive == 0);
2003        assert(pwrState == PWR_REF);
2004
2005        Tick ref_done_at = curTick() + memory.tRFC;
2006
2007        for (auto &b : banks) {
2008            b.actAllowedAt = ref_done_at;
2009        }
2010
2011        // at the moment this affects all ranks
2012        cmdList.push_back(Command(MemCommand::REF, 0, curTick()));
2013
2014        // Update the stats
2015        updatePowerStats();
2016
2017        DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), memory.tCK) -
2018                memory.timeStampOffset, rank);
2019
2020        // Update for next refresh
2021        refreshDueAt += memory.tREFI;
2022
2023        // make sure we did not wait so long that we cannot make up
2024        // for it
2025        if (refreshDueAt < ref_done_at) {
2026            fatal("Refresh was delayed so long we cannot catch up\n");
2027        }
2028
2029        // Run the refresh and schedule event to transition power states
2030        // when refresh completes
2031        refreshState = REF_RUN;
2032        schedule(refreshEvent, ref_done_at);
2033        return;
2034    }
2035
2036    if (refreshState == REF_RUN) {
2037        // should never get here with any banks active
2038        assert(numBanksActive == 0);
2039        assert(pwrState == PWR_REF);
2040
2041        assert(!powerEvent.scheduled());
2042
2043        if ((memory.drainState() == DrainState::Draining) ||
2044            (memory.drainState() == DrainState::Drained)) {
2045            // if draining, do not re-enter low-power mode.
2046            // simply go to IDLE and wait
2047            schedulePowerEvent(PWR_IDLE, curTick());
2048        } else {
2049            // At the moment, we sleep when the refresh ends and wait to be
2050            // woken up again if previously in a low-power state.
2051            if (pwrStatePostRefresh != PWR_IDLE) {
2052                // power State should be power Refresh
2053                assert(pwrState == PWR_REF);
2054                DPRINTF(DRAMState, "Rank %d sleeping after refresh and was in "
2055                        "power state %d before refreshing\n", rank,
2056                        pwrStatePostRefresh);
2057                powerDownSleep(pwrState, curTick());
2058
2059            // Force PRE power-down if there are no outstanding commands
2060            // in Q after refresh.
2061            } else if (isQueueEmpty() && memory.enableDRAMPowerdown) {
2062                // still have refresh event outstanding but there should
2063                // be no other events outstanding
2064                assert(outstandingEvents == 1);
2065                DPRINTF(DRAMState, "Rank %d sleeping after refresh but was NOT"
2066                        " in a low power state before refreshing\n", rank);
2067                powerDownSleep(PWR_PRE_PDN, curTick());
2068
2069            } else {
2070                // move to the idle power state once the refresh is done, this
2071                // will also move the refresh state machine to the refresh
2072                // idle state
2073                schedulePowerEvent(PWR_IDLE, curTick());
2074            }
2075        }
2076
2077        // At this point, we have completed the current refresh.
2078        // In the SREF bypass case, we do not get to this state in the
2079        // refresh STM and therefore can always schedule next event.
2080        // Compensate for the delay in actually performing the refresh
2081        // when scheduling the next one
2082        schedule(refreshEvent, refreshDueAt - memory.tRP);
2083
2084        DPRINTF(DRAMState, "Refresh done at %llu and next refresh"
2085                " at %llu\n", curTick(), refreshDueAt);
2086    }
2087}
2088
2089void
2090DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state, Tick tick)
2091{
2092    // respect causality
2093    assert(tick >= curTick());
2094
2095    if (!powerEvent.scheduled()) {
2096        DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n",
2097                tick, pwr_state);
2098
2099        // insert the new transition
2100        pwrStateTrans = pwr_state;
2101
2102        schedule(powerEvent, tick);
2103    } else {
2104        panic("Scheduled power event at %llu to state %d, "
2105              "with scheduled event at %llu to %d\n", tick, pwr_state,
2106              powerEvent.when(), pwrStateTrans);
2107    }
2108}
2109
2110void
2111DRAMCtrl::Rank::powerDownSleep(PowerState pwr_state, Tick tick)
2112{
2113    // if low power state is active low, schedule to active low power state.
2114    // in reality tCKE is needed to enter active low power. This is neglected
2115    // here and could be added in the future.
2116    if (pwr_state == PWR_ACT_PDN) {
2117        schedulePowerEvent(pwr_state, tick);
2118        // push command to DRAMPower
2119        cmdList.push_back(Command(MemCommand::PDN_F_ACT, 0, tick));
2120        DPRINTF(DRAMPower, "%llu,PDN_F_ACT,0,%d\n", divCeil(tick,
2121                memory.tCK) - memory.timeStampOffset, rank);
2122    } else if (pwr_state == PWR_PRE_PDN) {
2123        // if low power state is precharge low, schedule to precharge low
2124        // power state. In reality tCKE is needed to enter active low power.
2125        // This is neglected here.
2126        schedulePowerEvent(pwr_state, tick);
2127        //push Command to DRAMPower
2128        cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick));
2129        DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick,
2130                memory.tCK) - memory.timeStampOffset, rank);
2131    } else if (pwr_state == PWR_REF) {
2132        // if a refresh just occurred
2133        // transition to PRE_PDN now that all banks are closed
2134        // precharge power down requires tCKE to enter. For simplicity
2135        // this is not considered.
2136        schedulePowerEvent(PWR_PRE_PDN, tick);
2137        //push Command to DRAMPower
2138        cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick));
2139        DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick,
2140                memory.tCK) - memory.timeStampOffset, rank);
2141    } else if (pwr_state == PWR_SREF) {
2142        // should only enter SREF after PRE-PD wakeup to do a refresh
2143        assert(pwrStatePostRefresh == PWR_PRE_PDN);
2144        // self refresh requires time tCKESR to enter. For simplicity,
2145        // this is not considered.
2146        schedulePowerEvent(PWR_SREF, tick);
2147        // push Command to DRAMPower
2148        cmdList.push_back(Command(MemCommand::SREN, 0, tick));
2149        DPRINTF(DRAMPower, "%llu,SREN,0,%d\n", divCeil(tick,
2150                memory.tCK) - memory.timeStampOffset, rank);
2151    }
2152    // Ensure that we don't power-down and back up in same tick
2153    // Once we commit to PD entry, do it and wait for at least 1tCK
2154    // This could be replaced with tCKE if/when that is added to the model
2155    wakeUpAllowedAt = tick + memory.tCK;
2156
2157    // Transitioning to a low power state, set flag
2158    inLowPowerState = true;
2159}
2160
2161void
2162DRAMCtrl::Rank::scheduleWakeUpEvent(Tick exit_delay)
2163{
2164    Tick wake_up_tick = std::max(curTick(), wakeUpAllowedAt);
2165
2166    DPRINTF(DRAMState, "Scheduling wake-up for rank %d at tick %d\n",
2167            rank, wake_up_tick);
2168
2169    // if waking for refresh, hold previous state
2170    // else reset state back to IDLE
2171    if (refreshState == REF_PD_EXIT) {
2172        pwrStatePostRefresh = pwrState;
2173    } else {
2174        // don't automatically transition back to LP state after next REF
2175        pwrStatePostRefresh = PWR_IDLE;
2176    }
2177
2178    // schedule wake-up with event to ensure entry has completed before
2179    // we try to wake-up
2180    schedule(wakeUpEvent, wake_up_tick);
2181
2182    for (auto &b : banks) {
2183        // respect both causality and any existing bank
2184        // constraints, some banks could already have a
2185        // (auto) precharge scheduled
2186        b.wrAllowedAt = std::max(wake_up_tick + exit_delay, b.wrAllowedAt);
2187        b.rdAllowedAt = std::max(wake_up_tick + exit_delay, b.rdAllowedAt);
2188        b.preAllowedAt = std::max(wake_up_tick + exit_delay, b.preAllowedAt);
2189        b.actAllowedAt = std::max(wake_up_tick + exit_delay, b.actAllowedAt);
2190    }
2191    // Transitioning out of low power state, clear flag
2192    inLowPowerState = false;
2193
2194    // push to DRAMPower
2195    // use pwrStateTrans for cases where we have a power event scheduled
2196    // to enter low power that has not yet been processed
2197    if (pwrStateTrans == PWR_ACT_PDN) {
2198        cmdList.push_back(Command(MemCommand::PUP_ACT, 0, wake_up_tick));
2199        DPRINTF(DRAMPower, "%llu,PUP_ACT,0,%d\n", divCeil(wake_up_tick,
2200                memory.tCK) - memory.timeStampOffset, rank);
2201
2202    } else if (pwrStateTrans == PWR_PRE_PDN) {
2203        cmdList.push_back(Command(MemCommand::PUP_PRE, 0, wake_up_tick));
2204        DPRINTF(DRAMPower, "%llu,PUP_PRE,0,%d\n", divCeil(wake_up_tick,
2205                memory.tCK) - memory.timeStampOffset, rank);
2206    } else if (pwrStateTrans == PWR_SREF) {
2207        cmdList.push_back(Command(MemCommand::SREX, 0, wake_up_tick));
2208        DPRINTF(DRAMPower, "%llu,SREX,0,%d\n", divCeil(wake_up_tick,
2209                memory.tCK) - memory.timeStampOffset, rank);
2210    }
2211}
2212
2213void
2214DRAMCtrl::Rank::processWakeUpEvent()
2215{
2216    // Should be in a power-down or self-refresh state
2217    assert((pwrState == PWR_ACT_PDN) || (pwrState == PWR_PRE_PDN) ||
2218           (pwrState == PWR_SREF));
2219
2220    // Check current state to determine transition state
2221    if (pwrState == PWR_ACT_PDN) {
2222        // banks still open, transition to PWR_ACT
2223        schedulePowerEvent(PWR_ACT, curTick());
2224    } else {
2225        // transitioning from a precharge power-down or self-refresh state
2226        // banks are closed - transition to PWR_IDLE
2227        schedulePowerEvent(PWR_IDLE, curTick());
2228    }
2229}
2230
2231void
2232DRAMCtrl::Rank::processPowerEvent()
2233{
2234    assert(curTick() >= pwrStateTick);
2235    // remember where we were, and for how long
2236    Tick duration = curTick() - pwrStateTick;
2237    PowerState prev_state = pwrState;
2238
2239    // update the accounting
2240    pwrStateTime[prev_state] += duration;
2241
2242    // track to total idle time
2243    if ((prev_state == PWR_PRE_PDN) || (prev_state == PWR_ACT_PDN) ||
2244        (prev_state == PWR_SREF)) {
2245        totalIdleTime += duration;
2246    }
2247
2248    pwrState = pwrStateTrans;
2249    pwrStateTick = curTick();
2250
2251    // if rank was refreshing, make sure to start scheduling requests again
2252    if (prev_state == PWR_REF) {
2253        // bus IDLED prior to REF
2254        // counter should be one for refresh command only
2255        assert(outstandingEvents == 1);
2256        // REF complete, decrement count and go back to IDLE
2257        --outstandingEvents;
2258        refreshState = REF_IDLE;
2259
2260        DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration);
2261        // if moving back to power-down after refresh
2262        if (pwrState != PWR_IDLE) {
2263            assert(pwrState == PWR_PRE_PDN);
2264            DPRINTF(DRAMState, "Switching to power down state after refreshing"
2265                    " rank %d at %llu tick\n", rank, curTick());
2266        }
2267
2268        // completed refresh event, ensure next request is scheduled
2269        if (!memory.nextReqEvent.scheduled()) {
2270            DPRINTF(DRAM, "Scheduling next request after refreshing"
2271                           " rank %d\n", rank);
2272            schedule(memory.nextReqEvent, curTick());
2273        }
2274    }
2275
2276    if ((pwrState == PWR_ACT) && (refreshState == REF_PD_EXIT)) {
2277        // have exited ACT PD
2278        assert(prev_state == PWR_ACT_PDN);
2279
2280        // go back to REF event and close banks
2281        refreshState = REF_PRE;
2282        schedule(refreshEvent, curTick());
2283    } else if (pwrState == PWR_IDLE) {
2284        DPRINTF(DRAMState, "All banks precharged\n");
2285        if (prev_state == PWR_SREF) {
2286            // set refresh state to REF_SREF_EXIT, ensuring inRefIdleState
2287            // continues to return false during tXS after SREF exit
2288            // Schedule a refresh which kicks things back into action
2289            // when it finishes
2290            refreshState = REF_SREF_EXIT;
2291            schedule(refreshEvent, curTick() + memory.tXS);
2292        } else {
2293            // if we have a pending refresh, and are now moving to
2294            // the idle state, directly transition to, or schedule refresh
2295            if ((refreshState == REF_PRE) || (refreshState == REF_PD_EXIT)) {
2296                // ensure refresh is restarted only after final PRE command.
2297                // do not restart refresh if controller is in an intermediate
2298                // state, after PRE_PDN exit, when banks are IDLE but an
2299                // ACT is scheduled.
2300                if (!activateEvent.scheduled()) {
2301                    // there should be nothing waiting at this point
2302                    assert(!powerEvent.scheduled());
2303                    if (refreshState == REF_PD_EXIT) {
2304                        // exiting PRE PD, will be in IDLE until tXP expires
2305                        // and then should transition to PWR_REF state
2306                        assert(prev_state == PWR_PRE_PDN);
2307                        schedulePowerEvent(PWR_REF, curTick() + memory.tXP);
2308                    } else if (refreshState == REF_PRE) {
2309                        // can directly move to PWR_REF state and proceed below
2310                        pwrState = PWR_REF;
2311                    }
2312                } else {
2313                    // must have PRE scheduled to transition back to IDLE
2314                    // and re-kick off refresh
2315                    assert(prechargeEvent.scheduled());
2316                }
2317            }
2318        }
2319    }
2320
2321    // transition to the refresh state and re-start refresh process
2322    // refresh state machine will schedule the next power state transition
2323    if (pwrState == PWR_REF) {
2324        // completed final PRE for refresh or exiting power-down
2325        assert(refreshState == REF_PRE || refreshState == REF_PD_EXIT);
2326
2327        // exited PRE PD for refresh, with no pending commands
2328        // bypass auto-refresh and go straight to SREF, where memory
2329        // will issue refresh immediately upon entry
2330        if (pwrStatePostRefresh == PWR_PRE_PDN && isQueueEmpty() &&
2331           (memory.drainState() != DrainState::Draining) &&
2332           (memory.drainState() != DrainState::Drained) &&
2333           memory.enableDRAMPowerdown) {
2334            DPRINTF(DRAMState, "Rank %d bypassing refresh and transitioning "
2335                    "to self refresh at %11u tick\n", rank, curTick());
2336            powerDownSleep(PWR_SREF, curTick());
2337
2338            // Since refresh was bypassed, remove event by decrementing count
2339            assert(outstandingEvents == 1);
2340            --outstandingEvents;
2341
2342            // reset state back to IDLE temporarily until SREF is entered
2343            pwrState = PWR_IDLE;
2344
2345        // Not bypassing refresh for SREF entry
2346        } else {
2347            DPRINTF(DRAMState, "Refreshing\n");
2348
2349            // there should be nothing waiting at this point
2350            assert(!powerEvent.scheduled());
2351
2352            // kick the refresh event loop into action again, and that
2353            // in turn will schedule a transition to the idle power
2354            // state once the refresh is done
2355            schedule(refreshEvent, curTick());
2356
2357            // Banks transitioned to IDLE, start REF
2358            refreshState = REF_START;
2359        }
2360    }
2361
2362}
2363
2364void
2365DRAMCtrl::Rank::updatePowerStats()
2366{
2367    // All commands up to refresh have completed
2368    // flush cmdList to DRAMPower
2369    flushCmdList();
2370
2371    // Call the function that calculates window energy at intermediate update
2372    // events like at refresh, stats dump as well as at simulation exit.
2373    // Window starts at the last time the calcWindowEnergy function was called
2374    // and is upto current time.
2375    power.powerlib.calcWindowEnergy(divCeil(curTick(), memory.tCK) -
2376                                    memory.timeStampOffset);
2377
2378    // Get the energy from DRAMPower
2379    Data::MemoryPowerModel::Energy energy = power.powerlib.getEnergy();
2380
2381    // The energy components inside the power lib are calculated over
2382    // the window so accumulate into the corresponding gem5 stat
2383    actEnergy += energy.act_energy * memory.devicesPerRank;
2384    preEnergy += energy.pre_energy * memory.devicesPerRank;
2385    readEnergy += energy.read_energy * memory.devicesPerRank;
2386    writeEnergy += energy.write_energy * memory.devicesPerRank;
2387    refreshEnergy += energy.ref_energy * memory.devicesPerRank;
2388    actBackEnergy += energy.act_stdby_energy * memory.devicesPerRank;
2389    preBackEnergy += energy.pre_stdby_energy * memory.devicesPerRank;
2390    actPowerDownEnergy += energy.f_act_pd_energy * memory.devicesPerRank;
2391    prePowerDownEnergy += energy.f_pre_pd_energy * memory.devicesPerRank;
2392    selfRefreshEnergy += energy.sref_energy * memory.devicesPerRank;
2393
2394    // Accumulate window energy into the total energy.
2395    totalEnergy += energy.window_energy * memory.devicesPerRank;
2396    // Average power must not be accumulated but calculated over the time
2397    // since last stats reset. SimClock::Frequency is tick period not tick
2398    // frequency.
2399    //              energy (pJ)     1e-9
2400    // power (mW) = ----------- * ----------
2401    //              time (tick)   tick_frequency
2402    averagePower = (totalEnergy.value() /
2403                    (curTick() - memory.lastStatsResetTick)) *
2404                    (SimClock::Frequency / 1000000000.0);
2405}
2406
2407void
2408DRAMCtrl::Rank::computeStats()
2409{
2410    DPRINTF(DRAM,"Computing stats due to a dump callback\n");
2411
2412    // Update the stats
2413    updatePowerStats();
2414
2415    // final update of power state times
2416    pwrStateTime[pwrState] += (curTick() - pwrStateTick);
2417    pwrStateTick = curTick();
2418
2419}
2420
2421void
2422DRAMCtrl::Rank::resetStats() {
2423    // The only way to clear the counters in DRAMPower is to call
2424    // calcWindowEnergy function as that then calls clearCounters. The
2425    // clearCounters method itself is private.
2426    power.powerlib.calcWindowEnergy(divCeil(curTick(), memory.tCK) -
2427                                    memory.timeStampOffset);
2428
2429}
2430
2431void
2432DRAMCtrl::Rank::regStats()
2433{
2434    pwrStateTime
2435        .init(6)
2436        .name(name() + ".memoryStateTime")
2437        .desc("Time in different power states");
2438    pwrStateTime.subname(0, "IDLE");
2439    pwrStateTime.subname(1, "REF");
2440    pwrStateTime.subname(2, "SREF");
2441    pwrStateTime.subname(3, "PRE_PDN");
2442    pwrStateTime.subname(4, "ACT");
2443    pwrStateTime.subname(5, "ACT_PDN");
2444
2445    actEnergy
2446        .name(name() + ".actEnergy")
2447        .desc("Energy for activate commands per rank (pJ)");
2448
2449    preEnergy
2450        .name(name() + ".preEnergy")
2451        .desc("Energy for precharge commands per rank (pJ)");
2452
2453    readEnergy
2454        .name(name() + ".readEnergy")
2455        .desc("Energy for read commands per rank (pJ)");
2456
2457    writeEnergy
2458        .name(name() + ".writeEnergy")
2459        .desc("Energy for write commands per rank (pJ)");
2460
2461    refreshEnergy
2462        .name(name() + ".refreshEnergy")
2463        .desc("Energy for refresh commands per rank (pJ)");
2464
2465    actBackEnergy
2466        .name(name() + ".actBackEnergy")
2467        .desc("Energy for active background per rank (pJ)");
2468
2469    preBackEnergy
2470        .name(name() + ".preBackEnergy")
2471        .desc("Energy for precharge background per rank (pJ)");
2472
2473    actPowerDownEnergy
2474        .name(name() + ".actPowerDownEnergy")
2475        .desc("Energy for active power-down per rank (pJ)");
2476
2477    prePowerDownEnergy
2478        .name(name() + ".prePowerDownEnergy")
2479        .desc("Energy for precharge power-down per rank (pJ)");
2480
2481    selfRefreshEnergy
2482        .name(name() + ".selfRefreshEnergy")
2483        .desc("Energy for self refresh per rank (pJ)");
2484
2485    totalEnergy
2486        .name(name() + ".totalEnergy")
2487        .desc("Total energy per rank (pJ)");
2488
2489    averagePower
2490        .name(name() + ".averagePower")
2491        .desc("Core power per rank (mW)");
2492
2493    totalIdleTime
2494        .name(name() + ".totalIdleTime")
2495        .desc("Total Idle time Per DRAM Rank");
2496
2497    Stats::registerDumpCallback(new RankDumpCallback(this));
2498    Stats::registerResetCallback(new RankResetCallback(this));
2499}
2500void
2501DRAMCtrl::regStats()
2502{
2503    using namespace Stats;
2504
2505    MemCtrl::regStats();
2506
2507    for (auto r : ranks) {
2508        r->regStats();
2509    }
2510
2511    registerResetCallback(new MemResetCallback(this));
2512
2513    readReqs
2514        .name(name() + ".readReqs")
2515        .desc("Number of read requests accepted");
2516
2517    writeReqs
2518        .name(name() + ".writeReqs")
2519        .desc("Number of write requests accepted");
2520
2521    readBursts
2522        .name(name() + ".readBursts")
2523        .desc("Number of DRAM read bursts, "
2524              "including those serviced by the write queue");
2525
2526    writeBursts
2527        .name(name() + ".writeBursts")
2528        .desc("Number of DRAM write bursts, "
2529              "including those merged in the write queue");
2530
2531    servicedByWrQ
2532        .name(name() + ".servicedByWrQ")
2533        .desc("Number of DRAM read bursts serviced by the write queue");
2534
2535    mergedWrBursts
2536        .name(name() + ".mergedWrBursts")
2537        .desc("Number of DRAM write bursts merged with an existing one");
2538
2539    neitherReadNorWrite
2540        .name(name() + ".neitherReadNorWriteReqs")
2541        .desc("Number of requests that are neither read nor write");
2542
2543    perBankRdBursts
2544        .init(banksPerRank * ranksPerChannel)
2545        .name(name() + ".perBankRdBursts")
2546        .desc("Per bank write bursts");
2547
2548    perBankWrBursts
2549        .init(banksPerRank * ranksPerChannel)
2550        .name(name() + ".perBankWrBursts")
2551        .desc("Per bank write bursts");
2552
2553    avgRdQLen
2554        .name(name() + ".avgRdQLen")
2555        .desc("Average read queue length when enqueuing")
2556        .precision(2);
2557
2558    avgWrQLen
2559        .name(name() + ".avgWrQLen")
2560        .desc("Average write queue length when enqueuing")
2561        .precision(2);
2562
2563    totQLat
2564        .name(name() + ".totQLat")
2565        .desc("Total ticks spent queuing");
2566
2567    totBusLat
2568        .name(name() + ".totBusLat")
2569        .desc("Total ticks spent in databus transfers");
2570
2571    totMemAccLat
2572        .name(name() + ".totMemAccLat")
2573        .desc("Total ticks spent from burst creation until serviced "
2574              "by the DRAM");
2575
2576    avgQLat
2577        .name(name() + ".avgQLat")
2578        .desc("Average queueing delay per DRAM burst")
2579        .precision(2);
2580
2581    avgQLat = totQLat / (readBursts - servicedByWrQ);
2582
2583    avgBusLat
2584        .name(name() + ".avgBusLat")
2585        .desc("Average bus latency per DRAM burst")
2586        .precision(2);
2587
2588    avgBusLat = totBusLat / (readBursts - servicedByWrQ);
2589
2590    avgMemAccLat
2591        .name(name() + ".avgMemAccLat")
2592        .desc("Average memory access latency per DRAM burst")
2593        .precision(2);
2594
2595    avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
2596
2597    numRdRetry
2598        .name(name() + ".numRdRetry")
2599        .desc("Number of times read queue was full causing retry");
2600
2601    numWrRetry
2602        .name(name() + ".numWrRetry")
2603        .desc("Number of times write queue was full causing retry");
2604
2605    readRowHits
2606        .name(name() + ".readRowHits")
2607        .desc("Number of row buffer hits during reads");
2608
2609    writeRowHits
2610        .name(name() + ".writeRowHits")
2611        .desc("Number of row buffer hits during writes");
2612
2613    readRowHitRate
2614        .name(name() + ".readRowHitRate")
2615        .desc("Row buffer hit rate for reads")
2616        .precision(2);
2617
2618    readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
2619
2620    writeRowHitRate
2621        .name(name() + ".writeRowHitRate")
2622        .desc("Row buffer hit rate for writes")
2623        .precision(2);
2624
2625    writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
2626
2627    readPktSize
2628        .init(ceilLog2(burstSize) + 1)
2629        .name(name() + ".readPktSize")
2630        .desc("Read request sizes (log2)");
2631
2632     writePktSize
2633        .init(ceilLog2(burstSize) + 1)
2634        .name(name() + ".writePktSize")
2635        .desc("Write request sizes (log2)");
2636
2637     rdQLenPdf
2638        .init(readBufferSize)
2639        .name(name() + ".rdQLenPdf")
2640        .desc("What read queue length does an incoming req see");
2641
2642     wrQLenPdf
2643        .init(writeBufferSize)
2644        .name(name() + ".wrQLenPdf")
2645        .desc("What write queue length does an incoming req see");
2646
2647     bytesPerActivate
2648         .init(maxAccessesPerRow ? maxAccessesPerRow : rowBufferSize)
2649         .name(name() + ".bytesPerActivate")
2650         .desc("Bytes accessed per row activation")
2651         .flags(nozero);
2652
2653     rdPerTurnAround
2654         .init(readBufferSize)
2655         .name(name() + ".rdPerTurnAround")
2656         .desc("Reads before turning the bus around for writes")
2657         .flags(nozero);
2658
2659     wrPerTurnAround
2660         .init(writeBufferSize)
2661         .name(name() + ".wrPerTurnAround")
2662         .desc("Writes before turning the bus around for reads")
2663         .flags(nozero);
2664
2665    bytesReadDRAM
2666        .name(name() + ".bytesReadDRAM")
2667        .desc("Total number of bytes read from DRAM");
2668
2669    bytesReadWrQ
2670        .name(name() + ".bytesReadWrQ")
2671        .desc("Total number of bytes read from write queue");
2672
2673    bytesWritten
2674        .name(name() + ".bytesWritten")
2675        .desc("Total number of bytes written to DRAM");
2676
2677    bytesReadSys
2678        .name(name() + ".bytesReadSys")
2679        .desc("Total read bytes from the system interface side");
2680
2681    bytesWrittenSys
2682        .name(name() + ".bytesWrittenSys")
2683        .desc("Total written bytes from the system interface side");
2684
2685    avgRdBW
2686        .name(name() + ".avgRdBW")
2687        .desc("Average DRAM read bandwidth in MiByte/s")
2688        .precision(2);
2689
2690    avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
2691
2692    avgWrBW
2693        .name(name() + ".avgWrBW")
2694        .desc("Average achieved write bandwidth in MiByte/s")
2695        .precision(2);
2696
2697    avgWrBW = (bytesWritten / 1000000) / simSeconds;
2698
2699    avgRdBWSys
2700        .name(name() + ".avgRdBWSys")
2701        .desc("Average system read bandwidth in MiByte/s")
2702        .precision(2);
2703
2704    avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
2705
2706    avgWrBWSys
2707        .name(name() + ".avgWrBWSys")
2708        .desc("Average system write bandwidth in MiByte/s")
2709        .precision(2);
2710
2711    avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
2712
2713    peakBW
2714        .name(name() + ".peakBW")
2715        .desc("Theoretical peak bandwidth in MiByte/s")
2716        .precision(2);
2717
2718    peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
2719
2720    busUtil
2721        .name(name() + ".busUtil")
2722        .desc("Data bus utilization in percentage")
2723        .precision(2);
2724    busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
2725
2726    totGap
2727        .name(name() + ".totGap")
2728        .desc("Total gap between requests");
2729
2730    avgGap
2731        .name(name() + ".avgGap")
2732        .desc("Average gap between requests")
2733        .precision(2);
2734
2735    avgGap = totGap / (readReqs + writeReqs);
2736
2737    // Stats for DRAM Power calculation based on Micron datasheet
2738    busUtilRead
2739        .name(name() + ".busUtilRead")
2740        .desc("Data bus utilization in percentage for reads")
2741        .precision(2);
2742
2743    busUtilRead = avgRdBW / peakBW * 100;
2744
2745    busUtilWrite
2746        .name(name() + ".busUtilWrite")
2747        .desc("Data bus utilization in percentage for writes")
2748        .precision(2);
2749
2750    busUtilWrite = avgWrBW / peakBW * 100;
2751
2752    pageHitRate
2753        .name(name() + ".pageHitRate")
2754        .desc("Row buffer hit rate, read and write combined")
2755        .precision(2);
2756
2757    pageHitRate = (writeRowHits + readRowHits) /
2758        (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
2759
2760    // per-master bytes read and written to memory
2761    masterReadBytes
2762        .init(_system->maxMasters())
2763        .name(name() + ".masterReadBytes")
2764        .desc("Per-master bytes read from memory")
2765        .flags(nozero | nonan);
2766
2767    masterWriteBytes
2768        .init(_system->maxMasters())
2769        .name(name() + ".masterWriteBytes")
2770        .desc("Per-master bytes write to memory")
2771        .flags(nozero | nonan);
2772
2773    // per-master bytes read and written to memory rate
2774    masterReadRate.name(name() + ".masterReadRate")
2775        .desc("Per-master bytes read from memory rate (Bytes/sec)")
2776        .flags(nozero | nonan)
2777        .precision(12);
2778
2779    masterReadRate = masterReadBytes/simSeconds;
2780
2781    masterWriteRate
2782        .name(name() + ".masterWriteRate")
2783        .desc("Per-master bytes write to memory rate (Bytes/sec)")
2784        .flags(nozero | nonan)
2785        .precision(12);
2786
2787    masterWriteRate = masterWriteBytes/simSeconds;
2788
2789    masterReadAccesses
2790        .init(_system->maxMasters())
2791        .name(name() + ".masterReadAccesses")
2792        .desc("Per-master read serviced memory accesses")
2793        .flags(nozero);
2794
2795    masterWriteAccesses
2796        .init(_system->maxMasters())
2797        .name(name() + ".masterWriteAccesses")
2798        .desc("Per-master write serviced memory accesses")
2799        .flags(nozero);
2800
2801
2802    masterReadTotalLat
2803        .init(_system->maxMasters())
2804        .name(name() + ".masterReadTotalLat")
2805        .desc("Per-master read total memory access latency")
2806        .flags(nozero | nonan);
2807
2808    masterReadAvgLat.name(name() + ".masterReadAvgLat")
2809        .desc("Per-master read average memory access latency")
2810        .flags(nonan)
2811        .precision(2);
2812
2813    masterReadAvgLat = masterReadTotalLat/masterReadAccesses;
2814
2815    masterWriteTotalLat
2816        .init(_system->maxMasters())
2817        .name(name() + ".masterWriteTotalLat")
2818        .desc("Per-master write total memory access latency")
2819        .flags(nozero | nonan);
2820
2821    masterWriteAvgLat.name(name() + ".masterWriteAvgLat")
2822        .desc("Per-master write average memory access latency")
2823        .flags(nonan)
2824        .precision(2);
2825
2826    masterWriteAvgLat = masterWriteTotalLat/masterWriteAccesses;
2827
2828    for (int i = 0; i < _system->maxMasters(); i++) {
2829        const std::string master = _system->getMasterName(i);
2830        masterReadBytes.subname(i, master);
2831        masterReadRate.subname(i, master);
2832        masterWriteBytes.subname(i, master);
2833        masterWriteRate.subname(i, master);
2834        masterReadAccesses.subname(i, master);
2835        masterWriteAccesses.subname(i, master);
2836        masterReadTotalLat.subname(i, master);
2837        masterReadAvgLat.subname(i, master);
2838        masterWriteTotalLat.subname(i, master);
2839        masterWriteAvgLat.subname(i, master);
2840    }
2841}
2842
2843void
2844DRAMCtrl::recvFunctional(PacketPtr pkt)
2845{
2846    // rely on the abstract memory
2847    functionalAccess(pkt);
2848}
2849
2850Port &
2851DRAMCtrl::getPort(const string &if_name, PortID idx)
2852{
2853    if (if_name != "port") {
2854        return QoS::MemCtrl::getPort(if_name, idx);
2855    } else {
2856        return port;
2857    }
2858}
2859
2860DrainState
2861DRAMCtrl::drain()
2862{
2863    // if there is anything in any of our internal queues, keep track
2864    // of that as well
2865    if (!(!totalWriteQueueSize && !totalReadQueueSize && respQueue.empty() &&
2866          allRanksDrained())) {
2867
2868        DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
2869                " resp: %d\n", totalWriteQueueSize, totalReadQueueSize,
2870                respQueue.size());
2871
2872        // the only queue that is not drained automatically over time
2873        // is the write queue, thus kick things into action if needed
2874        if (!totalWriteQueueSize && !nextReqEvent.scheduled()) {
2875            schedule(nextReqEvent, curTick());
2876        }
2877
2878        // also need to kick off events to exit self-refresh
2879        for (auto r : ranks) {
2880            // force self-refresh exit, which in turn will issue auto-refresh
2881            if (r->pwrState == PWR_SREF) {
2882                DPRINTF(DRAM,"Rank%d: Forcing self-refresh wakeup in drain\n",
2883                        r->rank);
2884                r->scheduleWakeUpEvent(tXS);
2885            }
2886        }
2887
2888        return DrainState::Draining;
2889    } else {
2890        return DrainState::Drained;
2891    }
2892}
2893
2894bool
2895DRAMCtrl::allRanksDrained() const
2896{
2897    // true until proven false
2898    bool all_ranks_drained = true;
2899    for (auto r : ranks) {
2900        // then verify that the power state is IDLE ensuring all banks are
2901        // closed and rank is not in a low power state. Also verify that rank
2902        // is idle from a refresh point of view.
2903        all_ranks_drained = r->inPwrIdleState() && r->inRefIdleState() &&
2904            all_ranks_drained;
2905    }
2906    return all_ranks_drained;
2907}
2908
2909void
2910DRAMCtrl::drainResume()
2911{
2912    if (!isTimingMode && system()->isTimingMode()) {
2913        // if we switched to timing mode, kick things into action,
2914        // and behave as if we restored from a checkpoint
2915        startup();
2916    } else if (isTimingMode && !system()->isTimingMode()) {
2917        // if we switch from timing mode, stop the refresh events to
2918        // not cause issues with KVM
2919        for (auto r : ranks) {
2920            r->suspend();
2921        }
2922    }
2923
2924    // update the mode
2925    isTimingMode = system()->isTimingMode();
2926}
2927
2928DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
2929    : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this, true),
2930      memory(_memory)
2931{ }
2932
2933AddrRangeList
2934DRAMCtrl::MemoryPort::getAddrRanges() const
2935{
2936    AddrRangeList ranges;
2937    ranges.push_back(memory.getAddrRange());
2938    return ranges;
2939}
2940
2941void
2942DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
2943{
2944    pkt->pushLabel(memory.name());
2945
2946    if (!queue.trySatisfyFunctional(pkt)) {
2947        // Default implementation of SimpleTimingPort::recvFunctional()
2948        // calls recvAtomic() and throws away the latency; we can save a
2949        // little here by just not calculating the latency.
2950        memory.recvFunctional(pkt);
2951    }
2952
2953    pkt->popLabel();
2954}
2955
2956Tick
2957DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt)
2958{
2959    return memory.recvAtomic(pkt);
2960}
2961
2962bool
2963DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt)
2964{
2965    // pass it to the memory controller
2966    return memory.recvTimingReq(pkt);
2967}
2968
2969DRAMCtrl*
2970DRAMCtrlParams::create()
2971{
2972    return new DRAMCtrl(this);
2973}
2974