cpu: Apply the ARM TLB rework to the O3 checker CPU.
[gem5.git] / src / mem / dram_ctrl.cc
index ada70279f257a3d4d1850dff8caf049f5ad0fe66..37db27ce07974d0651923cca39d2c588716dd682 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010-2016 ARM Limited
+ * Copyright (c) 2010-2019 ARM Limited
  * All rights reserved
  *
  * The license below extends only to copyright in the software and shall
@@ -42,6 +42,7 @@
  *          Neha Agarwal
  *          Omar Naji
  *          Wendy Elsasser
+ *          Radhika Jagtap
  */
 
 #include "mem/dram_ctrl.hh"
 #include "debug/DRAMPower.hh"
 #include "debug/DRAMState.hh"
 #include "debug/Drain.hh"
+#include "debug/QOS.hh"
 #include "sim/system.hh"
 
 using namespace std;
 using namespace Data;
 
 DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
-    AbstractMemory(p),
+    QoS::MemCtrl(p),
     port(name() + ".port", *this), isTimingMode(false),
     retryRdReq(false), retryWrReq(false),
-    busState(READ),
-    busStateNext(READ),
-    nextReqEvent(this), respondEvent(this),
+    nextReqEvent([this]{ processNextReqEvent(); }, name()),
+    respondEvent([this]{ processRespondEvent(); }, name()),
     deviceSize(p->device_size),
     deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
     deviceRowBufferSize(p->device_rowbuffer_size),
@@ -82,18 +83,23 @@ DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
     writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0),
     minWritesPerSwitch(p->min_writes_per_switch),
     writesThisTime(0), readsThisTime(0),
-    tCK(p->tCK), tWTR(p->tWTR), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST),
+    tCK(p->tCK), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST),
+    tCCD_L_WR(p->tCCD_L_WR),
     tCCD_L(p->tCCD_L), tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
     tWR(p->tWR), tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
     tRRD_L(p->tRRD_L), tXAW(p->tXAW), tXP(p->tXP), tXS(p->tXS),
-    activationLimit(p->activation_limit),
+    activationLimit(p->activation_limit), rankToRankDly(tCS + tBURST),
+    wrToRdDly(tCL + tBURST + p->tWTR), rdToWrDly(tRTW + tBURST),
     memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
     pageMgmt(p->page_policy),
     maxAccessesPerRow(p->max_accesses_per_row),
     frontendLatency(p->static_frontend_latency),
     backendLatency(p->static_backend_latency),
-    busBusyUntil(0), prevArrival(0),
-    nextReqTime(0), activeRank(0), timeStampOffset(0)
+    nextBurstAt(0), prevArrival(0),
+    nextReqTime(0),
+    stats(*this),
+    activeRank(0), timeStampOffset(0),
+    lastStatsResetTick(0), enableDRAMPowerdown(p->enable_dram_powerdown)
 {
     // sanity check the ranks since we rely on bit slicing for the
     // address decoding
@@ -102,34 +108,13 @@ DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
 
     fatal_if(!isPowerOf2(burstSize), "DRAM burst size %d is not allowed, "
              "must be a power of two\n", burstSize);
+    readQueue.resize(p->qos_priorities);
+    writeQueue.resize(p->qos_priorities);
+
 
     for (int i = 0; i < ranksPerChannel; i++) {
-        Rank* rank = new Rank(*this, p);
+        Rank* rank = new Rank(*this, p, i);
         ranks.push_back(rank);
-
-        rank->actTicks.resize(activationLimit, 0);
-        rank->banks.resize(banksPerRank);
-        rank->rank = i;
-
-        for (int b = 0; b < banksPerRank; b++) {
-            rank->banks[b].bank = b;
-            // GDDR addressing of banks to BG is linear.
-            // Here we assume that all DRAM generations address bank groups as
-            // follows:
-            if (bankGroupArch) {
-                // Simply assign lower bits to bank group in order to
-                // rotate across bank groups as banks are incremented
-                // e.g. with 4 banks per bank group and 16 banks total:
-                //    banks 0,4,8,12  are in bank group 0
-                //    banks 1,5,9,13  are in bank group 1
-                //    banks 2,6,10,14 are in bank group 2
-                //    banks 3,7,11,15 are in bank group 3
-                rank->banks[b].bankgr = b % bankGroupsPerRank;
-            } else {
-                // No bank groups; simply assign to bank number
-                rank->banks[b].bankgr = b;
-            }
-        }
     }
 
     // perform a basic check of the write thresholds
@@ -185,6 +170,12 @@ DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
                   "bank groups per rank (%d) is greater than 1\n",
                   tCCD_L, tBURST, bankGroupsPerRank);
         }
+        // tCCD_L_WR should be greater than minimal, back-to-back burst delay
+        if (tCCD_L_WR <= tBURST) {
+            fatal("tCCD_L_WR (%d) should be larger than tBURST (%d) when "
+                  "bank groups per rank (%d) is greater than 1\n",
+                  tCCD_L_WR, tBURST, bankGroupsPerRank);
+        }
         // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
         // some datasheets might specify it equal to tRRD
         if (tRRD_L < tRRD) {
@@ -199,7 +190,7 @@ DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
 void
 DRAMCtrl::init()
 {
-    AbstractMemory::init();
+    MemCtrl::init();
 
    if (!port.isConnected()) {
         fatal("DRAMCtrl %s is unconnected!\n", name());
@@ -268,7 +259,7 @@ DRAMCtrl::startup()
         // have to worry about negative values when computing the time for
         // the next request, this will add an insignificant bubble at the
         // start of simulation
-        busBusyUntil = curTick() + tRP + tRCD + tCL;
+        nextBurstAt = curTick() + tRP + tRCD;
     }
 }
 
@@ -296,24 +287,26 @@ bool
 DRAMCtrl::readQueueFull(unsigned int neededEntries) const
 {
     DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
-            readBufferSize, readQueue.size() + respQueue.size(),
+            readBufferSize, totalReadQueueSize + respQueue.size(),
             neededEntries);
 
-    return
-        (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
+    auto rdsize_new = totalReadQueueSize + respQueue.size() + neededEntries;
+    return rdsize_new > readBufferSize;
 }
 
 bool
 DRAMCtrl::writeQueueFull(unsigned int neededEntries) const
 {
     DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
-            writeBufferSize, writeQueue.size(), neededEntries);
-    return (writeQueue.size() + neededEntries) > writeBufferSize;
+            writeBufferSize, totalWriteQueueSize, neededEntries);
+
+    auto wrsize_new = (totalWriteQueueSize + neededEntries);
+    return  wrsize_new > writeBufferSize;
 }
 
 DRAMCtrl::DRAMPacket*
-DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size,
-                       bool isRead)
+DRAMCtrl::decodeAddr(const PacketPtr pkt, Addr dramPktAddr, unsigned size,
+                     bool isRead) const
 {
     // decode the address based on the address mapping scheme, with
     // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
@@ -438,8 +431,9 @@ DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
     for (int cnt = 0; cnt < pktCount; ++cnt) {
         unsigned size = std::min((addr | (burstSize - 1)) + 1,
                         pkt->getAddr() + pkt->getSize()) - addr;
-        readPktSize[ceilLog2(size)]++;
-        readBursts++;
+        stats.readPktSize[ceilLog2(size)]++;
+        stats.readBursts++;
+        stats.masterReadAccesses[pkt->masterId()]++;
 
         // First check write buffer to see if the data is already at
         // the controller
@@ -448,17 +442,23 @@ DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
         // if the burst address is not present then there is no need
         // looking any further
         if (isInWriteQueue.find(burst_addr) != isInWriteQueue.end()) {
-            for (const auto& p : writeQueue) {
-                // check if the read is subsumed in the write queue
-                // packet we are looking at
-                if (p->addr <= addr && (addr + size) <= (p->addr + p->size)) {
-                    foundInWrQ = true;
-                    servicedByWrQ++;
-                    pktsServicedByWrQ++;
-                    DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
-                            "write queue\n", addr, size);
-                    bytesReadWrQ += burstSize;
-                    break;
+            for (const auto& vec : writeQueue) {
+                for (const auto& p : vec) {
+                    // check if the read is subsumed in the write queue
+                    // packet we are looking at
+                    if (p->addr <= addr &&
+                       ((addr + size) <= (p->addr + p->size))) {
+
+                        foundInWrQ = true;
+                        stats.servicedByWrQ++;
+                        pktsServicedByWrQ++;
+                        DPRINTF(DRAM,
+                                "Read to addr %lld with size %d serviced by "
+                                "write queue\n",
+                                addr, size);
+                        stats.bytesReadWrQ += burstSize;
+                        break;
+                    }
                 }
             }
         }
@@ -478,17 +478,20 @@ DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
             dram_pkt->burstHelper = burst_helper;
 
             assert(!readQueueFull(1));
-            rdQLenPdf[readQueue.size() + respQueue.size()]++;
+            stats.rdQLenPdf[totalReadQueueSize + respQueue.size()]++;
 
             DPRINTF(DRAM, "Adding to read queue\n");
 
-            readQueue.push_back(dram_pkt);
+            readQueue[dram_pkt->qosValue()].push_back(dram_pkt);
 
-            // increment read entries of the rank
             ++dram_pkt->rankRef.readEntries;
 
+            // log packet
+            logRequest(MemCtrl::READ, pkt->masterId(), pkt->qosValue(),
+                       dram_pkt->addr, 1);
+
             // Update stats
-            avgRdQLen = readQueue.size() + respQueue.size();
+            stats.avgRdQLen = totalReadQueueSize + respQueue.size();
         }
 
         // Starting address of next dram pkt (aligend to burstSize boundary)
@@ -526,8 +529,9 @@ DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
     for (int cnt = 0; cnt < pktCount; ++cnt) {
         unsigned size = std::min((addr | (burstSize - 1)) + 1,
                         pkt->getAddr() + pkt->getSize()) - addr;
-        writePktSize[ceilLog2(size)]++;
-        writeBursts++;
+        stats.writePktSize[ceilLog2(size)]++;
+        stats.writeBursts++;
+        stats.masterWriteAccesses[pkt->masterId()]++;
 
         // see if we can merge with an existing item in the write
         // queue and keep track of whether we have merged or not
@@ -539,17 +543,22 @@ DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
         if (!merged) {
             DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
 
-            assert(writeQueue.size() < writeBufferSize);
-            wrQLenPdf[writeQueue.size()]++;
+            assert(totalWriteQueueSize < writeBufferSize);
+            stats.wrQLenPdf[totalWriteQueueSize]++;
 
             DPRINTF(DRAM, "Adding to write queue\n");
 
-            writeQueue.push_back(dram_pkt);
+            writeQueue[dram_pkt->qosValue()].push_back(dram_pkt);
             isInWriteQueue.insert(burstAlign(addr));
-            assert(writeQueue.size() == isInWriteQueue.size());
+
+            // log packet
+            logRequest(MemCtrl::WRITE, pkt->masterId(), pkt->qosValue(),
+                       dram_pkt->addr, 1);
+
+            assert(totalWriteQueueSize == isInWriteQueue.size());
 
             // Update stats
-            avgWrQLen = writeQueue.size();
+            stats.avgWrQLen = totalWriteQueueSize;
 
             // increment write entries of the rank
             ++dram_pkt->rankRef.writeEntries;
@@ -558,7 +567,7 @@ DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
 
             // keep track of the fact that this burst effectively
             // disappeared as it was merged with an existing one
-            mergedWrBursts++;
+            stats.mergedWrBursts++;
         }
 
         // Starting address of next dram pkt (aligend to burstSize boundary)
@@ -581,19 +590,28 @@ DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
 }
 
 void
-DRAMCtrl::printQs() const {
+DRAMCtrl::printQs() const
+{
+#if TRACING_ON
     DPRINTF(DRAM, "===READ QUEUE===\n\n");
-    for (auto i = readQueue.begin() ;  i != readQueue.end() ; ++i) {
-        DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
+    for (const auto& queue : readQueue) {
+        for (const auto& packet : queue) {
+            DPRINTF(DRAM, "Read %lu\n", packet->addr);
+        }
     }
+
     DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
-    for (auto i = respQueue.begin() ;  i != respQueue.end() ; ++i) {
-        DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
+    for (const auto& packet : respQueue) {
+        DPRINTF(DRAM, "Response %lu\n", packet->addr);
     }
+
     DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
-    for (auto i = writeQueue.begin() ;  i != writeQueue.end() ; ++i) {
-        DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
+    for (const auto& queue : writeQueue) {
+        for (const auto& packet : queue) {
+            DPRINTF(DRAM, "Write %lu\n", packet->addr);
+        }
     }
+#endif // TRACING_ON
 }
 
 bool
@@ -611,7 +629,7 @@ DRAMCtrl::recvTimingReq(PacketPtr pkt)
 
     // Calc avg gap between requests
     if (prevArrival != 0) {
-        totGap += curTick() - prevArrival;
+        stats.totGap += curTick() - prevArrival;
     }
     prevArrival = curTick();
 
@@ -624,33 +642,36 @@ DRAMCtrl::recvTimingReq(PacketPtr pkt)
     unsigned offset = pkt->getAddr() & (burstSize - 1);
     unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
 
+    // run the QoS scheduler and assign a QoS priority value to the packet
+    qosSchedule( { &readQueue, &writeQueue }, burstSize, pkt);
+
     // check local buffers and do not accept if full
-    if (pkt->isRead()) {
+    if (pkt->isWrite()) {
         assert(size != 0);
-        if (readQueueFull(dram_pkt_count)) {
-            DPRINTF(DRAM, "Read queue full, not accepting\n");
+        if (writeQueueFull(dram_pkt_count)) {
+            DPRINTF(DRAM, "Write queue full, not accepting\n");
             // remember that we have to retry this port
-            retryRdReq = true;
-            numRdRetry++;
+            retryWrReq = true;
+            stats.numWrRetry++;
             return false;
         } else {
-            addToReadQueue(pkt, dram_pkt_count);
-            readReqs++;
-            bytesReadSys += size;
+            addToWriteQueue(pkt, dram_pkt_count);
+            stats.writeReqs++;
+            stats.bytesWrittenSys += size;
         }
     } else {
-        assert(pkt->isWrite());
+        assert(pkt->isRead());
         assert(size != 0);
-        if (writeQueueFull(dram_pkt_count)) {
-            DPRINTF(DRAM, "Write queue full, not accepting\n");
+        if (readQueueFull(dram_pkt_count)) {
+            DPRINTF(DRAM, "Read queue full, not accepting\n");
             // remember that we have to retry this port
-            retryWrReq = true;
-            numWrRetry++;
+            retryRdReq = true;
+            stats.numRdRetry++;
             return false;
         } else {
-            addToWriteQueue(pkt, dram_pkt_count);
-            writeReqs++;
-            bytesWrittenSys += size;
+            addToReadQueue(pkt, dram_pkt_count);
+            stats.readReqs++;
+            stats.bytesReadSys += size;
         }
     }
 
@@ -678,18 +699,18 @@ DRAMCtrl::processRespondEvent()
     // read response received, decrement count
     --dram_pkt->rankRef.outstandingEvents;
 
-    // at this moment should be either ACT or IDLE depending on
-    // if PRE has occurred to close all banks
-    assert((dram_pkt->rankRef.pwrState == PWR_ACT) ||
-           (dram_pkt->rankRef.pwrState == PWR_IDLE));
+    // at this moment should not have transitioned to a low-power state
+    assert((dram_pkt->rankRef.pwrState != PWR_SREF) &&
+           (dram_pkt->rankRef.pwrState != PWR_PRE_PDN) &&
+           (dram_pkt->rankRef.pwrState != PWR_ACT_PDN));
 
     // track if this is the last packet before idling
     // and that there are no outstanding commands to this rank
-    if (dram_pkt->rankRef.lowPowerEntryReady()) {
+    if (dram_pkt->rankRef.isQueueEmpty() &&
+        dram_pkt->rankRef.outstandingEvents == 0 && enableDRAMPowerdown) {
         // verify that there are no events scheduled
         assert(!dram_pkt->rankRef.activateEvent.scheduled());
         assert(!dram_pkt->rankRef.prechargeEvent.scheduled());
-        assert(dram_pkt->rankRef.refreshState == REF_IDLE);
 
         // if coming from active state, schedule power event to
         // active power-down else go to precharge power-down
@@ -734,7 +755,7 @@ DRAMCtrl::processRespondEvent()
     } else {
         // if there is nothing left in any queue, signal a drain
         if (drainState() == DrainState::Draining &&
-            writeQueue.empty() && readQueue.empty() && allRanksDrained()) {
+            !totalWriteQueueSize && !totalReadQueueSize && allRanksDrained()) {
 
             DPRINTF(Drain, "DRAM controller done draining\n");
             signalDrainDone();
@@ -749,52 +770,50 @@ DRAMCtrl::processRespondEvent()
     }
 }
 
-bool
-DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
+DRAMCtrl::DRAMPacketQueue::iterator
+DRAMCtrl::chooseNext(DRAMPacketQueue& queue, Tick extra_col_delay)
 {
-    // This method does the arbitration between requests. The chosen
-    // packet is simply moved to the head of the queue. The other
-    // methods know that this is the place to look. For example, with
-    // FCFS, this method does nothing
-    assert(!queue.empty());
-
-    // bool to indicate if a packet to an available rank is found
-    bool found_packet = false;
-    if (queue.size() == 1) {
-        DRAMPacket* dram_pkt = queue.front();
-        // available rank corresponds to state refresh idle
-        if (ranks[dram_pkt->rank]->isAvailable()) {
-            found_packet = true;
-            DPRINTF(DRAM, "Single request, going to a free rank\n");
-        } else {
-            DPRINTF(DRAM, "Single request, going to a busy rank\n");
-        }
-        return found_packet;
-    }
+    // This method does the arbitration between requests.
 
-    if (memSchedPolicy == Enums::fcfs) {
-        // check if there is a packet going to a free rank
-        for (auto i = queue.begin(); i != queue.end() ; ++i) {
-            DRAMPacket* dram_pkt = *i;
-            if (ranks[dram_pkt->rank]->isAvailable()) {
-                queue.erase(i);
-                queue.push_front(dram_pkt);
-                found_packet = true;
-                break;
+    DRAMCtrl::DRAMPacketQueue::iterator ret = queue.end();
+
+    if (!queue.empty()) {
+        if (queue.size() == 1) {
+            // available rank corresponds to state refresh idle
+            DRAMPacket* dram_pkt = *(queue.begin());
+            if (ranks[dram_pkt->rank]->inRefIdleState()) {
+                ret = queue.begin();
+                DPRINTF(DRAM, "Single request, going to a free rank\n");
+            } else {
+                DPRINTF(DRAM, "Single request, going to a busy rank\n");
             }
+        } else if (memSchedPolicy == Enums::fcfs) {
+            // check if there is a packet going to a free rank
+            for (auto i = queue.begin(); i != queue.end(); ++i) {
+                DRAMPacket* dram_pkt = *i;
+                if (ranks[dram_pkt->rank]->inRefIdleState()) {
+                    ret = i;
+                    break;
+                }
+            }
+        } else if (memSchedPolicy == Enums::frfcfs) {
+            ret = chooseNextFRFCFS(queue, extra_col_delay);
+        } else {
+            panic("No scheduling policy chosen\n");
         }
-    } else if (memSchedPolicy == Enums::frfcfs) {
-        found_packet = reorderQueue(queue, extra_col_delay);
-    } else
-        panic("No scheduling policy chosen\n");
-    return found_packet;
+    }
+    return ret;
 }
 
-bool
-DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
+DRAMCtrl::DRAMPacketQueue::iterator
+DRAMCtrl::chooseNextFRFCFS(DRAMPacketQueue& queue, Tick extra_col_delay)
 {
     // Only determine this if needed
-    uint64_t earliest_banks = 0;
+    vector<uint32_t> earliest_banks(ranksPerChannel, 0);
+
+    // Has minBankPrep been called to populate earliest_banks?
+    bool filled_earliest_banks = false;
+    // can the PRE/ACT sequence be done without impacting utlization?
     bool hidden_bank_prep = false;
 
     // search for seamless row hits first, if no seamless row hit is
@@ -815,26 +834,36 @@ DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
     auto selected_pkt_it = queue.end();
 
     // time we need to issue a column command to be seamless
-    const Tick min_col_at = std::max(busBusyUntil - tCL + extra_col_delay,
-                                     curTick());
+    const Tick min_col_at = std::max(nextBurstAt + extra_col_delay, curTick());
 
     for (auto i = queue.begin(); i != queue.end() ; ++i) {
         DRAMPacket* dram_pkt = *i;
         const Bank& bank = dram_pkt->bankRef;
+        const Tick col_allowed_at = dram_pkt->isRead() ? bank.rdAllowedAt :
+                                                         bank.wrAllowedAt;
+
+        DPRINTF(DRAM, "%s checking packet in bank %d\n",
+                __func__, dram_pkt->bankRef.bank);
+
+        // check if rank is not doing a refresh and thus is available, if not,
+        // jump to the next packet
+        if (dram_pkt->rankRef.inRefIdleState()) {
+
+            DPRINTF(DRAM,
+                    "%s bank %d - Rank %d available\n", __func__,
+                    dram_pkt->bankRef.bank, dram_pkt->rankRef.rank);
 
-        // check if rank is available, if not, jump to the next packet
-        if (dram_pkt->rankRef.isAvailable()) {
             // check if it is a row hit
             if (bank.openRow == dram_pkt->row) {
                 // no additional rank-to-rank or same bank-group
                 // delays, or we switched read/write and might as well
                 // go for the row hit
-                if (bank.colAllowedAt <= min_col_at) {
+                if (col_allowed_at <= min_col_at) {
                     // FCFS within the hits, giving priority to
                     // commands that can issue seamlessly, without
                     // additional delay, such as same rank accesses
                     // and/or different bank-group accesses
-                    DPRINTF(DRAM, "Seamless row buffer hit\n");
+                    DPRINTF(DRAM, "%s Seamless row buffer hit\n", __func__);
                     selected_pkt_it = i;
                     // no need to look through the remaining queue entries
                     break;
@@ -845,23 +874,23 @@ DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
                     // the current one
                     selected_pkt_it = i;
                     found_prepped_pkt = true;
-                    DPRINTF(DRAM, "Prepped row buffer hit\n");
+                    DPRINTF(DRAM, "%s Prepped row buffer hit\n", __func__);
                 }
             } else if (!found_earliest_pkt) {
                 // if we have not initialised the bank status, do it
                 // now, and only once per scheduling decisions
-                if (earliest_banks == 0) {
+                if (!filled_earliest_banks) {
                     // determine entries with earliest bank delay
-                    pair<uint64_t, bool> bankStatus =
+                    std::tie(earliest_banks, hidden_bank_prep) =
                         minBankPrep(queue, min_col_at);
-                    earliest_banks = bankStatus.first;
-                    hidden_bank_prep = bankStatus.second;
+                    filled_earliest_banks = true;
                 }
 
                 // bank is amongst first available banks
                 // minBankPrep will give priority to packets that can
                 // issue seamlessly
-                if (bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
+                if (bits(earliest_banks[dram_pkt->rank],
+                         dram_pkt->bank, dram_pkt->bank)) {
                     found_earliest_pkt = true;
                     found_hidden_bank = hidden_bank_prep;
 
@@ -873,17 +902,17 @@ DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
                         selected_pkt_it = i;
                 }
             }
+        } else {
+            DPRINTF(DRAM, "%s bank %d - Rank %d not available\n", __func__,
+                    dram_pkt->bankRef.bank, dram_pkt->rankRef.rank);
         }
     }
 
-    if (selected_pkt_it != queue.end()) {
-        DRAMPacket* selected_pkt = *selected_pkt_it;
-        queue.erase(selected_pkt_it);
-        queue.push_front(selected_pkt);
-        return true;
+    if (selected_pkt_it == queue.end()) {
+        DPRINTF(DRAM, "%s no available ranks found\n", __func__);
     }
 
-    return false;
+    return selected_pkt_it;
 }
 
 void
@@ -911,7 +940,7 @@ DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
 
         // queue the packet in the response queue to be sent out after
         // the static latency has passed
-        port.schedTimingResp(pkt, response_time, true);
+        port.schedTimingResp(pkt, response_time);
     } else {
         // @todo the packet is going to be deleted, and the DRAMPacket
         // is still having a pointer to it
@@ -957,8 +986,9 @@ DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref,
     // The next access has to respect tRAS for this bank
     bank_ref.preAllowedAt = act_tick + tRAS;
 
-    // Respect the row-to-column command delay
-    bank_ref.colAllowedAt = std::max(act_tick + tRCD, bank_ref.colAllowedAt);
+    // Respect the row-to-column command delay for both read and write cmds
+    bank_ref.rdAllowedAt = std::max(act_tick + tRCD, bank_ref.rdAllowedAt);
+    bank_ref.wrAllowedAt = std::max(act_tick + tRCD, bank_ref.wrAllowedAt);
 
     // start by enforcing tRRD
     for (int i = 0; i < banksPerRank; i++) {
@@ -1031,7 +1061,7 @@ DRAMCtrl::prechargeBank(Rank& rank_ref, Bank& bank, Tick pre_at, bool trace)
 
     // sample the bytes per activate here since we are closing
     // the page
-    bytesPerActivate.sample(bank.bytesAccessed);
+    stats.bytesPerActivate.sample(bank.bytesAccessed);
 
     bank.openRow = Bank::NO_ROW;
 
@@ -1094,9 +1124,6 @@ DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
     // for the state we need to track if it is a row hit or not
     bool row_hit = true;
 
-    // respect any constraints on the command (e.g. tRCD or tCCD)
-    Tick cmd_at = std::max(bank.colAllowedAt, curTick());
-
     // Determine the access latency and update the bank state
     if (bank.openRow == dram_pkt->row) {
         // nothing to do
@@ -1115,24 +1142,23 @@ DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
         // Record the activation and deal with all the global timing
         // constraints caused be a new activation (tRRD and tXAW)
         activateBank(rank, bank, act_tick, dram_pkt->row);
-
-        // issue the command as early as possible
-        cmd_at = bank.colAllowedAt;
     }
 
+    // respect any constraints on the command (e.g. tRCD or tCCD)
+    const Tick col_allowed_at = dram_pkt->isRead() ?
+                                          bank.rdAllowedAt : bank.wrAllowedAt;
+
     // we need to wait until the bus is available before we can issue
-    // the command
-    cmd_at = std::max(cmd_at, busBusyUntil - tCL);
+    // the command; need minimum of tBURST between commands
+    Tick cmd_at = std::max({col_allowed_at, nextBurstAt, curTick()});
 
     // update the packet ready time
     dram_pkt->readyTime = cmd_at + tCL + tBURST;
 
-    // only one burst can use the bus at any one point in time
-    assert(dram_pkt->readyTime - busBusyUntil >= tBURST);
-
     // update the time for the next read/write burst for each
-    // bank (add a max with tCCD/tCCD_L here)
-    Tick cmd_dly;
+    // bank (add a max with tCCD/tCCD_L/tCCD_L_WR here)
+    Tick dly_to_rd_cmd;
+    Tick dly_to_wr_cmd;
     for (int j = 0; j < ranksPerChannel; j++) {
         for (int i = 0; i < banksPerRank; i++) {
             // next burst to same bank group in this rank must not happen
@@ -1143,24 +1169,30 @@ DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
                    (bank.bankgr == ranks[j]->banks[i].bankgr)) {
                     // bank group architecture requires longer delays between
                     // RD/WR burst commands to the same bank group.
-                    // Use tCCD_L in this case
-                    cmd_dly = tCCD_L;
+                    // tCCD_L is default requirement for same BG timing
+                    // tCCD_L_WR is required for write-to-write
+                    // Need to also take bus turnaround delays into account
+                    dly_to_rd_cmd = dram_pkt->isRead() ?
+                                    tCCD_L : std::max(tCCD_L, wrToRdDly);
+                    dly_to_wr_cmd = dram_pkt->isRead() ?
+                                    std::max(tCCD_L, rdToWrDly) : tCCD_L_WR;
                 } else {
-                    // use tBURST (equivalent to tCCD_S), the shorter
-                    // cas-to-cas delay value, when either:
-                    // 1) bank group architecture is not supportted
-                    // 2) bank is in a different bank group
-                    cmd_dly = tBURST;
+                    // tBURST is default requirement for diff BG timing
+                    // Need to also take bus turnaround delays into account
+                    dly_to_rd_cmd = dram_pkt->isRead() ? tBURST : wrToRdDly;
+                    dly_to_wr_cmd = dram_pkt->isRead() ? rdToWrDly : tBURST;
                 }
             } else {
-                // different rank is by default in a different bank group
-                // use tBURST (equivalent to tCCD_S), which is the shorter
-                // cas-to-cas delay in this case
-                // Add tCS to account for rank-to-rank bus delay requirements
-                cmd_dly = tBURST + tCS;
+                // different rank is by default in a different bank group and
+                // doesn't require longer tCCD or additional RTW, WTR delays
+                // Need to account for rank-to-rank switching with tCS
+                dly_to_wr_cmd = rankToRankDly;
+                dly_to_rd_cmd = rankToRankDly;
             }
-            ranks[j]->banks[i].colAllowedAt = std::max(cmd_at + cmd_dly,
-                                             ranks[j]->banks[i].colAllowedAt);
+            ranks[j]->banks[i].rdAllowedAt = std::max(cmd_at + dly_to_rd_cmd,
+                                             ranks[j]->banks[i].rdAllowedAt);
+            ranks[j]->banks[i].wrAllowedAt = std::max(cmd_at + dly_to_wr_cmd,
+                                             ranks[j]->banks[i].wrAllowedAt);
         }
     }
 
@@ -1171,7 +1203,7 @@ DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
     // time before a precharge, in the case of a read, respect the
     // read to precharge constraint
     bank.preAllowedAt = std::max(bank.preAllowedAt,
-                                 dram_pkt->isRead ? cmd_at + tRTP :
+                                 dram_pkt->isRead() ? cmd_at + tRTP :
                                  dram_pkt->readyTime + tWR);
 
     // increment the bytes accessed and the accesses per row
@@ -1199,25 +1231,32 @@ DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
         bool got_bank_conflict = false;
 
         // either look at the read queue or write queue
-        const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
-            writeQueue;
-        auto p = queue.begin();
-        // make sure we are not considering the packet that we are
-        // currently dealing with (which is the head of the queue)
-        ++p;
-
-        // keep on looking until we find a hit or reach the end of the queue
-        // 1) if a hit is found, then both open and close adaptive policies keep
-        // the page open
-        // 2) if no hit is found, got_bank_conflict is set to true if a bank
-        // conflict request is waiting in the queue
-        while (!got_more_hits && p != queue.end()) {
-            bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
-                (dram_pkt->bank == (*p)->bank);
-            bool same_row = dram_pkt->row == (*p)->row;
-            got_more_hits |= same_rank_bank && same_row;
-            got_bank_conflict |= same_rank_bank && !same_row;
-            ++p;
+        const std::vector<DRAMPacketQueue>& queue =
+                dram_pkt->isRead() ? readQueue : writeQueue;
+
+        for (uint8_t i = 0; i < numPriorities(); ++i) {
+            auto p = queue[i].begin();
+            // keep on looking until we find a hit or reach the end of the queue
+            // 1) if a hit is found, then both open and close adaptive policies keep
+            // the page open
+            // 2) if no hit is found, got_bank_conflict is set to true if a bank
+            // conflict request is waiting in the queue
+            // 3) make sure we are not considering the packet that we are
+            // currently dealing with
+            while (!got_more_hits && p != queue[i].end()) {
+                if (dram_pkt != (*p)) {
+                    bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
+                                          (dram_pkt->bank == (*p)->bank);
+
+                    bool same_row = dram_pkt->row == (*p)->row;
+                    got_more_hits |= same_rank_bank && same_row;
+                    got_bank_conflict |= same_rank_bank && !same_row;
+                }
+                ++p;
+            }
+
+            if (got_more_hits)
+                break;
         }
 
         // auto pre-charge when either
@@ -1229,17 +1268,17 @@ DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
     }
 
     // DRAMPower trace command to be written
-    std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR";
+    std::string mem_cmd = dram_pkt->isRead() ? "RD" : "WR";
 
     // MemCommand required for DRAMPower library
     MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD :
                                                    MemCommand::WR;
 
-    // Update bus state
-    busBusyUntil = dram_pkt->readyTime;
+    // Update bus state to reflect when previous command was issued
+    nextBurstAt = cmd_at + tBURST;
 
-    DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n",
-            dram_pkt->addr, dram_pkt->readyTime, busBusyUntil);
+    DPRINTF(DRAM, "Access to %lld, ready at %lld next burst at %lld.\n",
+            dram_pkt->addr, dram_pkt->readyTime, nextBurstAt);
 
     dram_pkt->rankRef.cmdList.push_back(Command(command, dram_pkt->bank,
                                         cmd_at));
@@ -1261,35 +1300,78 @@ DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
     // conservative estimate of when we have to schedule the next
     // request to not introduce any unecessary bubbles. In most cases
     // we will wake up sooner than we have to.
-    nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
+    nextReqTime = nextBurstAt - (tRP + tRCD);
 
     // Update the stats and schedule the next request
-    if (dram_pkt->isRead) {
+    if (dram_pkt->isRead()) {
         ++readsThisTime;
         if (row_hit)
-            readRowHits++;
-        bytesReadDRAM += burstSize;
-        perBankRdBursts[dram_pkt->bankId]++;
+            stats.readRowHits++;
+        stats.bytesReadDRAM += burstSize;
+        stats.perBankRdBursts[dram_pkt->bankId]++;
 
         // Update latency stats
-        totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
-        totBusLat += tBURST;
-        totQLat += cmd_at - dram_pkt->entryTime;
+        stats.totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
+        stats.masterReadTotalLat[dram_pkt->masterId()] +=
+            dram_pkt->readyTime - dram_pkt->entryTime;
+
+        stats.totBusLat += tBURST;
+        stats.totQLat += cmd_at - dram_pkt->entryTime;
+        stats.masterReadBytes[dram_pkt->masterId()] += dram_pkt->size;
     } else {
         ++writesThisTime;
         if (row_hit)
-            writeRowHits++;
-        bytesWritten += burstSize;
-        perBankWrBursts[dram_pkt->bankId]++;
+            stats.writeRowHits++;
+        stats.bytesWritten += burstSize;
+        stats.perBankWrBursts[dram_pkt->bankId]++;
+        stats.masterWriteBytes[dram_pkt->masterId()] += dram_pkt->size;
+        stats.masterWriteTotalLat[dram_pkt->masterId()] +=
+            dram_pkt->readyTime - dram_pkt->entryTime;
     }
 }
 
 void
 DRAMCtrl::processNextReqEvent()
 {
+    // transition is handled by QoS algorithm if enabled
+    if (turnPolicy) {
+        // select bus state - only done if QoS algorithms are in use
+        busStateNext = selectNextBusState();
+    }
+
+    // detect bus state change
+    bool switched_cmd_type = (busState != busStateNext);
+    // record stats
+    recordTurnaroundStats();
+
+    DPRINTF(DRAM, "QoS Turnarounds selected state %s %s\n",
+            (busState==MemCtrl::READ)?"READ":"WRITE",
+            switched_cmd_type?"[turnaround triggered]":"");
+
+    if (switched_cmd_type) {
+        if (busState == READ) {
+            DPRINTF(DRAM,
+                    "Switching to writes after %d reads with %d reads "
+                    "waiting\n", readsThisTime, totalReadQueueSize);
+            stats.rdPerTurnAround.sample(readsThisTime);
+            readsThisTime = 0;
+        } else {
+            DPRINTF(DRAM,
+                    "Switching to reads after %d writes with %d writes "
+                    "waiting\n", writesThisTime, totalWriteQueueSize);
+            stats.wrPerTurnAround.sample(writesThisTime);
+            writesThisTime = 0;
+        }
+    }
+
+    // updates current state
+    busState = busStateNext;
+
+    // check ranks for refresh/wakeup - uses busStateNext, so done after turnaround
+    // decisions
     int busyRanks = 0;
     for (auto r : ranks) {
-        if (!r->isAvailable()) {
+        if (!r->inRefIdleState()) {
             if (r->pwrState != PWR_SREF) {
                 // rank is busy refreshing
                 DPRINTF(DRAMState, "Rank %d is not available\n", r->rank);
@@ -1327,48 +1409,21 @@ DRAMCtrl::processNextReqEvent()
         return;
     }
 
-    // pre-emptively set to false.  Overwrite if in transitioning to
-    // a new state
-    bool switched_cmd_type = false;
-    if (busState != busStateNext) {
-        if (busState == READ) {
-            DPRINTF(DRAM, "Switching to writes after %d reads with %d reads "
-                    "waiting\n", readsThisTime, readQueue.size());
-
-            // sample and reset the read-related stats as we are now
-            // transitioning to writes, and all reads are done
-            rdPerTurnAround.sample(readsThisTime);
-            readsThisTime = 0;
-
-            // now proceed to do the actual writes
-            switched_cmd_type = true;
-        } else {
-            DPRINTF(DRAM, "Switching to reads after %d writes with %d writes "
-                    "waiting\n", writesThisTime, writeQueue.size());
-
-            wrPerTurnAround.sample(writesThisTime);
-            writesThisTime = 0;
-
-            switched_cmd_type = true;
-        }
-        // update busState to match next state until next transition
-        busState = busStateNext;
-    }
-
     // when we get here it is either a read or a write
     if (busState == READ) {
 
         // track if we should switch or not
         bool switch_to_writes = false;
 
-        if (readQueue.empty()) {
+        if (totalReadQueueSize == 0) {
             // In the case there is no read request to go next,
             // trigger writes if we have passed the low threshold (or
             // if we are draining)
-            if (!writeQueue.empty() &&
+            if (!(totalWriteQueueSize == 0) &&
                 (drainState() == DrainState::Draining ||
-                 writeQueue.size() > writeLowThreshold)) {
+                 totalWriteQueueSize > writeLowThreshold)) {
 
+                DPRINTF(DRAM, "Switching to writes due to read queue empty\n");
                 switch_to_writes = true;
             } else {
                 // check if we are drained
@@ -1387,50 +1442,62 @@ DRAMCtrl::processNextReqEvent()
                 return;
             }
         } else {
-            // bool to check if there is a read to a free rank
-            bool found_read = false;
 
-            // Figure out which read request goes next, and move it to the
-            // front of the read queue
-            // If we are changing command type, incorporate the minimum
-            // bus turnaround delay which will be tCS (different rank) case
-            found_read = chooseNext(readQueue,
-                             switched_cmd_type ? tCS : 0);
+            bool read_found = false;
+            DRAMPacketQueue::iterator to_read;
+            uint8_t prio = numPriorities();
+
+            for (auto queue = readQueue.rbegin();
+                 queue != readQueue.rend(); ++queue) {
+
+                prio--;
+
+                DPRINTF(QOS,
+                        "DRAM controller checking READ queue [%d] priority [%d elements]\n",
+                        prio, queue->size());
+
+                // Figure out which read request goes next
+                // If we are changing command type, incorporate the minimum
+                // bus turnaround delay which will be tCS (different rank) case
+                to_read = chooseNext((*queue), switched_cmd_type ? tCS : 0);
+
+                if (to_read != queue->end()) {
+                    // candidate read found
+                    read_found = true;
+                    break;
+                }
+            }
 
             // if no read to an available rank is found then return
             // at this point. There could be writes to the available ranks
             // which are above the required threshold. However, to
             // avoid adding more complexity to the code, return and wait
             // for a refresh event to kick things into action again.
-            if (!found_read)
+            if (!read_found) {
+                DPRINTF(DRAM, "No Reads Found - exiting\n");
                 return;
+            }
 
-            DRAMPacket* dram_pkt = readQueue.front();
-            assert(dram_pkt->rankRef.isAvailable());
+            auto dram_pkt = *to_read;
 
-            // here we get a bit creative and shift the bus busy time not
-            // just the tWTR, but also a CAS latency to capture the fact
-            // that we are allowed to prepare a new bank, but not issue a
-            // read command until after tWTR, in essence we capture a
-            // bubble on the data bus that is tWTR + tCL
-            if (switched_cmd_type && dram_pkt->rank == activeRank) {
-                busBusyUntil += tWTR + tCL;
-            }
+            assert(dram_pkt->rankRef.inRefIdleState());
 
             doDRAMAccess(dram_pkt);
 
-            // At this point we're done dealing with the request
-            readQueue.pop_front();
-
             // Every respQueue which will generate an event, increment count
             ++dram_pkt->rankRef.outstandingEvents;
-
             // sanity check
             assert(dram_pkt->size <= burstSize);
             assert(dram_pkt->readyTime >= curTick());
 
+            // log the response
+            logResponse(MemCtrl::READ, (*to_read)->masterId(),
+                        dram_pkt->qosValue(), dram_pkt->getAddr(), 1,
+                        dram_pkt->readyTime - dram_pkt->entryTime);
+
+
             // Insert into response queue. It will be sent back to the
-            // requestor at its readyTime
+            // requester at its readyTime
             if (respQueue.empty()) {
                 assert(!respondEvent.scheduled());
                 schedule(respondEvent, dram_pkt->readyTime);
@@ -1442,9 +1509,12 @@ DRAMCtrl::processNextReqEvent()
             respQueue.push_back(dram_pkt);
 
             // we have so many writes that we have to transition
-            if (writeQueue.size() > writeHighThreshold) {
+            if (totalWriteQueueSize > writeHighThreshold) {
                 switch_to_writes = true;
             }
+
+            // remove the request from the queue - the iterator is no longer valid .
+            readQueue[dram_pkt->qosValue()].erase(to_read);
         }
 
         // switching to writes, either because the read queue is empty
@@ -1455,38 +1525,49 @@ DRAMCtrl::processNextReqEvent()
             busStateNext = WRITE;
         }
     } else {
-        // bool to check if write to free rank is found
-        bool found_write = false;
-
-        // If we are changing command type, incorporate the minimum
-        // bus turnaround delay
-        found_write = chooseNext(writeQueue,
-                                 switched_cmd_type ? std::min(tRTW, tCS) : 0);
-
-        // if no writes to an available rank are found then return.
-        // There could be reads to the available ranks. However, to avoid
-        // adding more complexity to the code, return at this point and wait
-        // for a refresh event to kick things into action again.
-        if (!found_write)
+
+        bool write_found = false;
+        DRAMPacketQueue::iterator to_write;
+        uint8_t prio = numPriorities();
+
+        for (auto queue = writeQueue.rbegin();
+             queue != writeQueue.rend(); ++queue) {
+
+            prio--;
+
+            DPRINTF(QOS,
+                    "DRAM controller checking WRITE queue [%d] priority [%d elements]\n",
+                    prio, queue->size());
+
+            // If we are changing command type, incorporate the minimum
+            // bus turnaround delay
+            to_write = chooseNext((*queue),
+                                  switched_cmd_type ? std::min(tRTW, tCS) : 0);
+
+            if (to_write != queue->end()) {
+                write_found = true;
+                break;
+            }
+        }
+
+        // if there are no writes to a rank that is available to service
+        // requests (i.e. rank is in refresh idle state) are found then
+        // return. There could be reads to the available ranks. However, to
+        // avoid adding more complexity to the code, return at this point and
+        // wait for a refresh event to kick things into action again.
+        if (!write_found) {
+            DPRINTF(DRAM, "No Writes Found - exiting\n");
             return;
+        }
+
+        auto dram_pkt = *to_write;
 
-        DRAMPacket* dram_pkt = writeQueue.front();
-        assert(dram_pkt->rankRef.isAvailable());
+        assert(dram_pkt->rankRef.inRefIdleState());
         // sanity check
         assert(dram_pkt->size <= burstSize);
 
-        // add a bubble to the data bus, as defined by the
-        // tRTW when access is to the same rank as previous burst
-        // Different rank timing is handled with tCS, which is
-        // applied to colAllowedAt
-        if (switched_cmd_type && dram_pkt->rank == activeRank) {
-            busBusyUntil += tRTW;
-        }
-
         doDRAMAccess(dram_pkt);
 
-        writeQueue.pop_front();
-
         // removed write from queue, decrement count
         --dram_pkt->rankRef.writeEntries;
 
@@ -1502,21 +1583,35 @@ DRAMCtrl::processNextReqEvent()
             ++dram_pkt->rankRef.outstandingEvents;
 
         } else if (dram_pkt->rankRef.writeDoneEvent.when() <
-                   dram_pkt-> readyTime) {
+                   dram_pkt->readyTime) {
+
             reschedule(dram_pkt->rankRef.writeDoneEvent, dram_pkt->readyTime);
         }
 
         isInWriteQueue.erase(burstAlign(dram_pkt->addr));
+
+        // log the response
+        logResponse(MemCtrl::WRITE, dram_pkt->masterId(),
+                    dram_pkt->qosValue(), dram_pkt->getAddr(), 1,
+                    dram_pkt->readyTime - dram_pkt->entryTime);
+
+
+        // remove the request from the queue - the iterator is no longer valid
+        writeQueue[dram_pkt->qosValue()].erase(to_write);
+
         delete dram_pkt;
 
         // If we emptied the write queue, or got sufficiently below the
         // threshold (using the minWritesPerSwitch as the hysteresis) and
         // are not draining, or we have reads waiting and have done enough
         // writes, then switch to reads.
-        if (writeQueue.empty() ||
-            (writeQueue.size() + minWritesPerSwitch < writeLowThreshold &&
-             drainState() != DrainState::Draining) ||
-            (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) {
+        bool below_threshold =
+            totalWriteQueueSize + minWritesPerSwitch < writeLowThreshold;
+
+        if (totalWriteQueueSize == 0 ||
+            (below_threshold && drainState() != DrainState::Draining) ||
+            (totalReadQueueSize && writesThisTime >= minWritesPerSwitch)) {
+
             // turn the bus back around for reads again
             busStateNext = READ;
 
@@ -1535,18 +1630,18 @@ DRAMCtrl::processNextReqEvent()
     // them retry. This is done here to ensure that the retry does not
     // cause a nextReqEvent to be scheduled before we do so as part of
     // the next request processing
-    if (retryWrReq && writeQueue.size() < writeBufferSize) {
+    if (retryWrReq && totalWriteQueueSize < writeBufferSize) {
         retryWrReq = false;
         port.sendRetryReq();
     }
 }
 
-pair<uint64_t, bool>
-DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
+pair<vector<uint32_t>, bool>
+DRAMCtrl::minBankPrep(const DRAMPacketQueue& queue,
                       Tick min_col_at) const
 {
-    uint64_t bank_mask = 0;
     Tick min_act_at = MaxTick;
+    vector<uint32_t> bank_mask(ranksPerChannel, 0);
 
     // latest Tick for which ACT can occur without incurring additoinal
     // delay on the data bus
@@ -1563,7 +1658,7 @@ DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
     // bank in question
     vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
     for (const auto& p : queue) {
-        if (p->rankRef.isAvailable())
+        if (p->rankRef.inRefIdleState())
             got_waiting[p->bankId] = true;
     }
 
@@ -1577,7 +1672,7 @@ DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
             // amongst the first available, update the mask
             if (got_waiting[bank_id]) {
                 // make sure this rank is not currently refreshing.
-                assert(ranks[i]->isAvailable());
+                assert(ranks[i]->inRefIdleState());
                 // simplistic approximation of when the bank can issue
                 // an activate, ignoring any rank-to-rank switching
                 // cost in this calculation
@@ -1586,8 +1681,10 @@ DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
                     std::max(ranks[i]->banks[j].preAllowedAt, curTick()) + tRP;
 
                 // When is the earliest the R/W burst can issue?
-                Tick col_at = std::max(ranks[i]->banks[j].colAllowedAt,
-                                       act_at + tRCD);
+                const Tick col_allowed_at = (busState == READ) ?
+                                              ranks[i]->banks[j].rdAllowedAt :
+                                              ranks[i]->banks[j].wrAllowedAt;
+                Tick col_at = std::max(col_allowed_at, act_at + tRCD);
 
                 // bank can issue burst back-to-back (seamlessly) with
                 // previous burst
@@ -1605,7 +1702,7 @@ DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
                     // seen so far
                     if (!found_seamless_bank &&
                         (new_seamless_bank || act_at < min_act_at)) {
-                        bank_mask = 0;
+                        std::fill(bank_mask.begin(), bank_mask.end(), 0);
                     }
 
                     found_seamless_bank |= new_seamless_bank;
@@ -1614,7 +1711,7 @@ DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
                     hidden_bank_prep = act_at <= hidden_act_max;
 
                     // set the bit corresponding to the available bank
-                    replaceBits(bank_mask, bank_id, bank_id, 1);
+                    replaceBits(bank_mask[i], j, j, 1);
                     min_act_at = act_at;
                 }
             }
@@ -1624,16 +1721,42 @@ DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
     return make_pair(bank_mask, hidden_bank_prep);
 }
 
-DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p)
+DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p, int rank)
     : EventManager(&_memory), memory(_memory),
       pwrStateTrans(PWR_IDLE), pwrStatePostRefresh(PWR_IDLE),
       pwrStateTick(0), refreshDueAt(0), pwrState(PWR_IDLE),
-      refreshState(REF_IDLE), inLowPowerState(false), rank(0),
+      refreshState(REF_IDLE), inLowPowerState(false), rank(rank),
       readEntries(0), writeEntries(0), outstandingEvents(0),
-      wakeUpAllowedAt(0), power(_p, false), numBanksActive(0),
-      writeDoneEvent(*this), activateEvent(*this), prechargeEvent(*this),
-      refreshEvent(*this), powerEvent(*this), wakeUpEvent(*this)
-{ }
+      wakeUpAllowedAt(0), power(_p, false), banks(_p->banks_per_rank),
+      numBanksActive(0), actTicks(_p->activation_limit, 0),
+      writeDoneEvent([this]{ processWriteDoneEvent(); }, name()),
+      activateEvent([this]{ processActivateEvent(); }, name()),
+      prechargeEvent([this]{ processPrechargeEvent(); }, name()),
+      refreshEvent([this]{ processRefreshEvent(); }, name()),
+      powerEvent([this]{ processPowerEvent(); }, name()),
+      wakeUpEvent([this]{ processWakeUpEvent(); }, name()),
+      stats(_memory, *this)
+{
+    for (int b = 0; b < _p->banks_per_rank; b++) {
+        banks[b].bank = b;
+        // GDDR addressing of banks to BG is linear.
+        // Here we assume that all DRAM generations address bank groups as
+        // follows:
+        if (_p->bank_groups_per_rank > 0) {
+            // Simply assign lower bits to bank group in order to
+            // rotate across bank groups as banks are incremented
+            // e.g. with 4 banks per bank group and 16 banks total:
+            //    banks 0,4,8,12  are in bank group 0
+            //    banks 1,5,9,13  are in bank group 1
+            //    banks 2,6,10,14 are in bank group 2
+            //    banks 3,7,11,15 are in bank group 3
+            banks[b].bankgr = b % _p->bank_groups_per_rank;
+        } else {
+            // No bank groups; simply assign to bank number
+            banks[b].bankgr = b;
+        }
+    }
+}
 
 void
 DRAMCtrl::Rank::startup(Tick ref_tick)
@@ -1660,21 +1783,13 @@ DRAMCtrl::Rank::suspend()
 }
 
 bool
-DRAMCtrl::Rank::lowPowerEntryReady() const
+DRAMCtrl::Rank::isQueueEmpty() const
 {
+    // check commmands in Q based on current bus direction
     bool no_queued_cmds = ((memory.busStateNext == READ) && (readEntries == 0))
                           || ((memory.busStateNext == WRITE) &&
                               (writeEntries == 0));
-
-    if (refreshState == REF_RUN) {
-       // have not decremented outstandingEvents for refresh command
-       // still check if there are no commands queued to force PD
-       // entry after refresh completes
-       return no_queued_cmds;
-    } else {
-       // ensure no commands in Q and no commands scheduled
-       return (no_queued_cmds && (outstandingEvents == 0));
-    }
+    return no_queued_cmds;
 }
 
 void
@@ -1744,7 +1859,8 @@ DRAMCtrl::Rank::processPrechargeEvent()
     if (numBanksActive == 0) {
         // no reads to this rank in the Q and no pending
         // RD/WR or refresh commands
-        if (lowPowerEntryReady()) {
+        if (isQueueEmpty() && outstandingEvents == 0 &&
+            memory.enableDRAMPowerdown) {
             // should still be in ACT state since bank still open
             assert(pwrState == PWR_ACT);
 
@@ -1945,7 +2061,10 @@ DRAMCtrl::Rank::processRefreshEvent()
 
             // Force PRE power-down if there are no outstanding commands
             // in Q after refresh.
-            } else if (lowPowerEntryReady()) {
+            } else if (isQueueEmpty() && memory.enableDRAMPowerdown) {
+                // still have refresh event outstanding but there should
+                // be no other events outstanding
+                assert(outstandingEvents == 1);
                 DPRINTF(DRAMState, "Rank %d sleeping after refresh but was NOT"
                         " in a low power state before refreshing\n", rank);
                 powerDownSleep(PWR_PRE_PDN, curTick());
@@ -1958,16 +2077,15 @@ DRAMCtrl::Rank::processRefreshEvent()
             }
         }
 
-        // if transitioning to self refresh do not schedule a new refresh;
-        // when waking from self refresh, a refresh is scheduled again.
-        if (pwrStateTrans != PWR_SREF) {
-            // compensate for the delay in actually performing the refresh
-            // when scheduling the next one
-            schedule(refreshEvent, refreshDueAt - memory.tRP);
+        // At this point, we have completed the current refresh.
+        // In the SREF bypass case, we do not get to this state in the
+        // refresh STM and therefore can always schedule next event.
+        // Compensate for the delay in actually performing the refresh
+        // when scheduling the next one
+        schedule(refreshEvent, refreshDueAt - memory.tRP);
 
-            DPRINTF(DRAMState, "Refresh done at %llu and next refresh"
-                    " at %llu\n", curTick(), refreshDueAt);
-        }
+        DPRINTF(DRAMState, "Refresh done at %llu and next refresh"
+                " at %llu\n", curTick(), refreshDueAt);
     }
 }
 
@@ -2014,28 +2132,25 @@ DRAMCtrl::Rank::powerDownSleep(PowerState pwr_state, Tick tick)
         DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick,
                 memory.tCK) - memory.timeStampOffset, rank);
     } else if (pwr_state == PWR_REF) {
-        // if a refresh just occured
+        // if a refresh just occurred
         // transition to PRE_PDN now that all banks are closed
-        // do not transition to SREF if commands are in Q; stay in PRE_PDN
-        if (pwrStatePostRefresh == PWR_ACT_PDN || !lowPowerEntryReady()) {
-            // prechage power down requires tCKE to enter. For simplicity
-            // this is not considered.
-            schedulePowerEvent(PWR_PRE_PDN, tick);
-            //push Command to DRAMPower
-            cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick));
-            DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick,
-                    memory.tCK) - memory.timeStampOffset, rank);
-        } else {
-            // last low power State was power precharge
-            assert(pwrStatePostRefresh == PWR_PRE_PDN);
-            // self refresh requires time tCKESR to enter. For simplicity,
-            // this is not considered.
-            schedulePowerEvent(PWR_SREF, tick);
-            // push Command to DRAMPower
-            cmdList.push_back(Command(MemCommand::SREN, 0, tick));
-            DPRINTF(DRAMPower, "%llu,SREN,0,%d\n", divCeil(tick,
-                    memory.tCK) - memory.timeStampOffset, rank);
-        }
+        // precharge power down requires tCKE to enter. For simplicity
+        // this is not considered.
+        schedulePowerEvent(PWR_PRE_PDN, tick);
+        //push Command to DRAMPower
+        cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick));
+        DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick,
+                memory.tCK) - memory.timeStampOffset, rank);
+    } else if (pwr_state == PWR_SREF) {
+        // should only enter SREF after PRE-PD wakeup to do a refresh
+        assert(pwrStatePostRefresh == PWR_PRE_PDN);
+        // self refresh requires time tCKESR to enter. For simplicity,
+        // this is not considered.
+        schedulePowerEvent(PWR_SREF, tick);
+        // push Command to DRAMPower
+        cmdList.push_back(Command(MemCommand::SREN, 0, tick));
+        DPRINTF(DRAMPower, "%llu,SREN,0,%d\n", divCeil(tick,
+                memory.tCK) - memory.timeStampOffset, rank);
     }
     // Ensure that we don't power-down and back up in same tick
     // Once we commit to PD entry, do it and wait for at least 1tCK
@@ -2071,7 +2186,8 @@ DRAMCtrl::Rank::scheduleWakeUpEvent(Tick exit_delay)
         // respect both causality and any existing bank
         // constraints, some banks could already have a
         // (auto) precharge scheduled
-        b.colAllowedAt = std::max(wake_up_tick + exit_delay, b.colAllowedAt);
+        b.wrAllowedAt = std::max(wake_up_tick + exit_delay, b.wrAllowedAt);
+        b.rdAllowedAt = std::max(wake_up_tick + exit_delay, b.rdAllowedAt);
         b.preAllowedAt = std::max(wake_up_tick + exit_delay, b.preAllowedAt);
         b.actAllowedAt = std::max(wake_up_tick + exit_delay, b.actAllowedAt);
     }
@@ -2124,12 +2240,12 @@ DRAMCtrl::Rank::processPowerEvent()
     PowerState prev_state = pwrState;
 
     // update the accounting
-    pwrStateTime[prev_state] += duration;
+    stats.memoryStateTime[prev_state] += duration;
 
     // track to total idle time
     if ((prev_state == PWR_PRE_PDN) || (prev_state == PWR_ACT_PDN) ||
         (prev_state == PWR_SREF)) {
-        totalIdleTime += duration;
+        stats.totalIdleTime += duration;
     }
 
     pwrState = pwrStateTrans;
@@ -2140,41 +2256,37 @@ DRAMCtrl::Rank::processPowerEvent()
         // bus IDLED prior to REF
         // counter should be one for refresh command only
         assert(outstandingEvents == 1);
-        // REF complete, decrement count
+        // REF complete, decrement count and go back to IDLE
         --outstandingEvents;
+        refreshState = REF_IDLE;
 
         DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration);
-        // if sleeping after refresh
+        // if moving back to power-down after refresh
         if (pwrState != PWR_IDLE) {
-            assert((pwrState == PWR_PRE_PDN) || (pwrState == PWR_SREF));
+            assert(pwrState == PWR_PRE_PDN);
             DPRINTF(DRAMState, "Switching to power down state after refreshing"
                     " rank %d at %llu tick\n", rank, curTick());
         }
-        if (pwrState != PWR_SREF) {
-            // rank is not available in SREF
-            // don't transition to IDLE in this case
-            refreshState = REF_IDLE;
-        }
-        // a request event could be already scheduled by the state
-        // machine of the other rank
+
+        // completed refresh event, ensure next request is scheduled
         if (!memory.nextReqEvent.scheduled()) {
-            DPRINTF(DRAM, "Scheduling next request after refreshing rank %d\n",
-                    rank);
+            DPRINTF(DRAM, "Scheduling next request after refreshing"
+                           " rank %d\n", rank);
             schedule(memory.nextReqEvent, curTick());
         }
-    } else if (pwrState == PWR_ACT) {
-        if (refreshState == REF_PD_EXIT) {
-            // kick the refresh event loop into action again
-            assert(prev_state == PWR_ACT_PDN);
+    }
 
-            // go back to REF event and close banks
-            refreshState = REF_PRE;
-            schedule(refreshEvent, curTick());
-        }
+    if ((pwrState == PWR_ACT) && (refreshState == REF_PD_EXIT)) {
+        // have exited ACT PD
+        assert(prev_state == PWR_ACT_PDN);
+
+        // go back to REF event and close banks
+        refreshState = REF_PRE;
+        schedule(refreshEvent, curTick());
     } else if (pwrState == PWR_IDLE) {
         DPRINTF(DRAMState, "All banks precharged\n");
         if (prev_state == PWR_SREF) {
-            // set refresh state to REF_SREF_EXIT, ensuring isAvailable
+            // set refresh state to REF_SREF_EXIT, ensuring inRefIdleState
             // continues to return false during tXS after SREF exit
             // Schedule a refresh which kicks things back into action
             // when it finishes
@@ -2182,7 +2294,7 @@ DRAMCtrl::Rank::processPowerEvent()
             schedule(refreshEvent, curTick() + memory.tXS);
         } else {
             // if we have a pending refresh, and are now moving to
-            // the idle state, directly transition to a refresh
+            // the idle state, directly transition to, or schedule refresh
             if ((refreshState == REF_PRE) || (refreshState == REF_PD_EXIT)) {
                 // ensure refresh is restarted only after final PRE command.
                 // do not restart refresh if controller is in an intermediate
@@ -2191,37 +2303,65 @@ DRAMCtrl::Rank::processPowerEvent()
                 if (!activateEvent.scheduled()) {
                     // there should be nothing waiting at this point
                     assert(!powerEvent.scheduled());
-                    // update the state in zero time and proceed below
-                    pwrState = PWR_REF;
+                    if (refreshState == REF_PD_EXIT) {
+                        // exiting PRE PD, will be in IDLE until tXP expires
+                        // and then should transition to PWR_REF state
+                        assert(prev_state == PWR_PRE_PDN);
+                        schedulePowerEvent(PWR_REF, curTick() + memory.tXP);
+                    } else if (refreshState == REF_PRE) {
+                        // can directly move to PWR_REF state and proceed below
+                        pwrState = PWR_REF;
+                    }
                 } else {
                     // must have PRE scheduled to transition back to IDLE
                     // and re-kick off refresh
                     assert(prechargeEvent.scheduled());
                 }
             }
-       }
+        }
     }
 
-    // we transition to the refresh state, let the refresh state
-    // machine know of this state update and let it deal with the
-    // scheduling of the next power state transition as well as the
-    // following refresh
+    // transition to the refresh state and re-start refresh process
+    // refresh state machine will schedule the next power state transition
     if (pwrState == PWR_REF) {
+        // completed final PRE for refresh or exiting power-down
         assert(refreshState == REF_PRE || refreshState == REF_PD_EXIT);
-        DPRINTF(DRAMState, "Refreshing\n");
-
-        // kick the refresh event loop into action again, and that
-        // in turn will schedule a transition to the idle power
-        // state once the refresh is done
-        if (refreshState == REF_PD_EXIT) {
-            // Wait for PD exit timing to complete before issuing REF
-            schedule(refreshEvent, curTick() + memory.tXP);
+
+        // exited PRE PD for refresh, with no pending commands
+        // bypass auto-refresh and go straight to SREF, where memory
+        // will issue refresh immediately upon entry
+        if (pwrStatePostRefresh == PWR_PRE_PDN && isQueueEmpty() &&
+           (memory.drainState() != DrainState::Draining) &&
+           (memory.drainState() != DrainState::Drained) &&
+           memory.enableDRAMPowerdown) {
+            DPRINTF(DRAMState, "Rank %d bypassing refresh and transitioning "
+                    "to self refresh at %11u tick\n", rank, curTick());
+            powerDownSleep(PWR_SREF, curTick());
+
+            // Since refresh was bypassed, remove event by decrementing count
+            assert(outstandingEvents == 1);
+            --outstandingEvents;
+
+            // reset state back to IDLE temporarily until SREF is entered
+            pwrState = PWR_IDLE;
+
+        // Not bypassing refresh for SREF entry
         } else {
+            DPRINTF(DRAMState, "Refreshing\n");
+
+            // there should be nothing waiting at this point
+            assert(!powerEvent.scheduled());
+
+            // kick the refresh event loop into action again, and that
+            // in turn will schedule a transition to the idle power
+            // state once the refresh is done
             schedule(refreshEvent, curTick());
+
+            // Banks transitioned to IDLE, start REF
+            refreshState = REF_START;
         }
-        // Banks transitioned to IDLE, start REF
-        refreshState = REF_START;
     }
+
 }
 
 void
@@ -2231,384 +2371,363 @@ DRAMCtrl::Rank::updatePowerStats()
     // flush cmdList to DRAMPower
     flushCmdList();
 
-    // update the counters for DRAMPower, passing false to
-    // indicate that this is not the last command in the
-    // list. DRAMPower requires this information for the
-    // correct calculation of the background energy at the end
-    // of the simulation. Ideally we would want to call this
-    // function with true once at the end of the
-    // simulation. However, the discarded energy is extremly
-    // small and does not effect the final results.
-    power.powerlib.updateCounters(false);
-
-    // call the energy function
-    power.powerlib.calcEnergy();
-
-    // Get the energy and power from DRAMPower
-    Data::MemoryPowerModel::Energy energy =
-        power.powerlib.getEnergy();
-    Data::MemoryPowerModel::Power rank_power =
-        power.powerlib.getPower();
-
-    actEnergy = energy.act_energy * memory.devicesPerRank;
-    preEnergy = energy.pre_energy * memory.devicesPerRank;
-    readEnergy = energy.read_energy * memory.devicesPerRank;
-    writeEnergy = energy.write_energy * memory.devicesPerRank;
-    refreshEnergy = energy.ref_energy * memory.devicesPerRank;
-    actBackEnergy = energy.act_stdby_energy * memory.devicesPerRank;
-    preBackEnergy = energy.pre_stdby_energy * memory.devicesPerRank;
-    actPowerDownEnergy = energy.f_act_pd_energy * memory.devicesPerRank;
-    prePowerDownEnergy = energy.f_pre_pd_energy * memory.devicesPerRank;
-    selfRefreshEnergy = energy.sref_energy * memory.devicesPerRank;
-    totalEnergy = energy.total_energy * memory.devicesPerRank;
-    averagePower = rank_power.average_power * memory.devicesPerRank;
+    // Call the function that calculates window energy at intermediate update
+    // events like at refresh, stats dump as well as at simulation exit.
+    // Window starts at the last time the calcWindowEnergy function was called
+    // and is upto current time.
+    power.powerlib.calcWindowEnergy(divCeil(curTick(), memory.tCK) -
+                                    memory.timeStampOffset);
+
+    // Get the energy from DRAMPower
+    Data::MemoryPowerModel::Energy energy = power.powerlib.getEnergy();
+
+    // The energy components inside the power lib are calculated over
+    // the window so accumulate into the corresponding gem5 stat
+    stats.actEnergy += energy.act_energy * memory.devicesPerRank;
+    stats.preEnergy += energy.pre_energy * memory.devicesPerRank;
+    stats.readEnergy += energy.read_energy * memory.devicesPerRank;
+    stats.writeEnergy += energy.write_energy * memory.devicesPerRank;
+    stats.refreshEnergy += energy.ref_energy * memory.devicesPerRank;
+    stats.actBackEnergy += energy.act_stdby_energy * memory.devicesPerRank;
+    stats.preBackEnergy += energy.pre_stdby_energy * memory.devicesPerRank;
+    stats.actPowerDownEnergy += energy.f_act_pd_energy * memory.devicesPerRank;
+    stats.prePowerDownEnergy += energy.f_pre_pd_energy * memory.devicesPerRank;
+    stats.selfRefreshEnergy += energy.sref_energy * memory.devicesPerRank;
+
+    // Accumulate window energy into the total energy.
+    stats.totalEnergy += energy.window_energy * memory.devicesPerRank;
+    // Average power must not be accumulated but calculated over the time
+    // since last stats reset. SimClock::Frequency is tick period not tick
+    // frequency.
+    //              energy (pJ)     1e-9
+    // power (mW) = ----------- * ----------
+    //              time (tick)   tick_frequency
+    stats.averagePower = (stats.totalEnergy.value() /
+                          (curTick() - memory.lastStatsResetTick)) *
+                         (SimClock::Frequency / 1000000000.0);
 }
 
 void
 DRAMCtrl::Rank::computeStats()
 {
-    DPRINTF(DRAM,"Computing final stats\n");
-
-    // Force DRAM power to update counters based on time spent in
-    // current state up to curTick()
-    cmdList.push_back(Command(MemCommand::NOP, 0, curTick()));
+    DPRINTF(DRAM,"Computing stats due to a dump callback\n");
 
     // Update the stats
     updatePowerStats();
 
     // final update of power state times
-    pwrStateTime[pwrState] += (curTick() - pwrStateTick);
+    stats.memoryStateTime[pwrState] += (curTick() - pwrStateTick);
     pwrStateTick = curTick();
-
 }
 
 void
-DRAMCtrl::Rank::regStats()
-{
-    using namespace Stats;
+DRAMCtrl::Rank::resetStats() {
+    // The only way to clear the counters in DRAMPower is to call
+    // calcWindowEnergy function as that then calls clearCounters. The
+    // clearCounters method itself is private.
+    power.powerlib.calcWindowEnergy(divCeil(curTick(), memory.tCK) -
+                                    memory.timeStampOffset);
 
-    pwrStateTime
-        .init(6)
-        .name(name() + ".memoryStateTime")
-        .desc("Time in different power states");
-    pwrStateTime.subname(0, "IDLE");
-    pwrStateTime.subname(1, "REF");
-    pwrStateTime.subname(2, "SREF");
-    pwrStateTime.subname(3, "PRE_PDN");
-    pwrStateTime.subname(4, "ACT");
-    pwrStateTime.subname(5, "ACT_PDN");
-
-    actEnergy
-        .name(name() + ".actEnergy")
-        .desc("Energy for activate commands per rank (pJ)");
-
-    preEnergy
-        .name(name() + ".preEnergy")
-        .desc("Energy for precharge commands per rank (pJ)");
-
-    readEnergy
-        .name(name() + ".readEnergy")
-        .desc("Energy for read commands per rank (pJ)");
-
-    writeEnergy
-        .name(name() + ".writeEnergy")
-        .desc("Energy for write commands per rank (pJ)");
-
-    refreshEnergy
-        .name(name() + ".refreshEnergy")
-        .desc("Energy for refresh commands per rank (pJ)");
-
-    actBackEnergy
-        .name(name() + ".actBackEnergy")
-        .desc("Energy for active background per rank (pJ)");
-
-    preBackEnergy
-        .name(name() + ".preBackEnergy")
-        .desc("Energy for precharge background per rank (pJ)");
-
-    actPowerDownEnergy
-        .name(name() + ".actPowerDownEnergy")
-        .desc("Energy for active power-down per rank (pJ)");
-
-    prePowerDownEnergy
-        .name(name() + ".prePowerDownEnergy")
-        .desc("Energy for precharge power-down per rank (pJ)");
-
-    selfRefreshEnergy
-        .name(name() + ".selfRefreshEnergy")
-        .desc("Energy for self refresh per rank (pJ)");
-
-    totalEnergy
-        .name(name() + ".totalEnergy")
-        .desc("Total energy per rank (pJ)");
-
-    averagePower
-        .name(name() + ".averagePower")
-        .desc("Core power per rank (mW)");
-
-    totalIdleTime
-        .name(name() + ".totalIdleTime")
-        .desc("Total Idle time Per DRAM Rank");
-
-    registerDumpCallback(new RankDumpCallback(this));
 }
+
+DRAMCtrl::DRAMStats::DRAMStats(DRAMCtrl &_dram)
+    : Stats::Group(&_dram),
+    dram(_dram),
+
+    ADD_STAT(readReqs, "Number of read requests accepted"),
+    ADD_STAT(writeReqs, "Number of write requests accepted"),
+
+    ADD_STAT(readBursts,
+             "Number of DRAM read bursts, "
+             "including those serviced by the write queue"),
+    ADD_STAT(writeBursts,
+             "Number of DRAM write bursts, "
+             "including those merged in the write queue"),
+    ADD_STAT(servicedByWrQ,
+             "Number of DRAM read bursts serviced by the write queue"),
+    ADD_STAT(mergedWrBursts,
+             "Number of DRAM write bursts merged with an existing one"),
+
+    ADD_STAT(neitherReadNorWriteReqs,
+             "Number of requests that are neither read nor write"),
+
+    ADD_STAT(perBankRdBursts, "Per bank write bursts"),
+    ADD_STAT(perBankWrBursts, "Per bank write bursts"),
+
+    ADD_STAT(avgRdQLen, "Average read queue length when enqueuing"),
+    ADD_STAT(avgWrQLen, "Average write queue length when enqueuing"),
+
+    ADD_STAT(totQLat, "Total ticks spent queuing"),
+    ADD_STAT(totBusLat, "Total ticks spent in databus transfers"),
+    ADD_STAT(totMemAccLat,
+             "Total ticks spent from burst creation until serviced "
+             "by the DRAM"),
+    ADD_STAT(avgQLat, "Average queueing delay per DRAM burst"),
+    ADD_STAT(avgBusLat, "Average bus latency per DRAM burst"),
+    ADD_STAT(avgMemAccLat, "Average memory access latency per DRAM burst"),
+
+    ADD_STAT(numRdRetry, "Number of times read queue was full causing retry"),
+    ADD_STAT(numWrRetry, "Number of times write queue was full causing retry"),
+
+    ADD_STAT(readRowHits, "Number of row buffer hits during reads"),
+    ADD_STAT(writeRowHits, "Number of row buffer hits during writes"),
+    ADD_STAT(readRowHitRate, "Row buffer hit rate for reads"),
+    ADD_STAT(writeRowHitRate, "Row buffer hit rate for writes"),
+
+    ADD_STAT(readPktSize, "Read request sizes (log2)"),
+    ADD_STAT(writePktSize, "Write request sizes (log2)"),
+
+    ADD_STAT(rdQLenPdf, "What read queue length does an incoming req see"),
+    ADD_STAT(wrQLenPdf, "What write queue length does an incoming req see"),
+
+    ADD_STAT(bytesPerActivate, "Bytes accessed per row activation"),
+
+    ADD_STAT(rdPerTurnAround,
+             "Reads before turning the bus around for writes"),
+    ADD_STAT(wrPerTurnAround,
+             "Writes before turning the bus around for reads"),
+
+    ADD_STAT(bytesReadDRAM, "Total number of bytes read from DRAM"),
+    ADD_STAT(bytesReadWrQ, "Total number of bytes read from write queue"),
+    ADD_STAT(bytesWritten, "Total number of bytes written to DRAM"),
+    ADD_STAT(bytesReadSys, "Total read bytes from the system interface side"),
+    ADD_STAT(bytesWrittenSys,
+             "Total written bytes from the system interface side"),
+
+    ADD_STAT(avgRdBW, "Average DRAM read bandwidth in MiByte/s"),
+    ADD_STAT(avgWrBW, "Average achieved write bandwidth in MiByte/s"),
+    ADD_STAT(avgRdBWSys, "Average system read bandwidth in MiByte/s"),
+    ADD_STAT(avgWrBWSys, "Average system write bandwidth in MiByte/s"),
+    ADD_STAT(peakBW, "Theoretical peak bandwidth in MiByte/s"),
+
+    ADD_STAT(busUtil, "Data bus utilization in percentage"),
+    ADD_STAT(busUtilRead, "Data bus utilization in percentage for reads"),
+    ADD_STAT(busUtilWrite, "Data bus utilization in percentage for writes"),
+
+    ADD_STAT(totGap, "Total gap between requests"),
+    ADD_STAT(avgGap, "Average gap between requests"),
+
+    ADD_STAT(masterReadBytes, "Per-master bytes read from memory"),
+    ADD_STAT(masterWriteBytes, "Per-master bytes write to memory"),
+    ADD_STAT(masterReadRate,
+             "Per-master bytes read from memory rate (Bytes/sec)"),
+    ADD_STAT(masterWriteRate,
+             "Per-master bytes write to memory rate (Bytes/sec)"),
+    ADD_STAT(masterReadAccesses,
+             "Per-master read serviced memory accesses"),
+    ADD_STAT(masterWriteAccesses,
+             "Per-master write serviced memory accesses"),
+    ADD_STAT(masterReadTotalLat,
+             "Per-master read total memory access latency"),
+    ADD_STAT(masterWriteTotalLat,
+             "Per-master write total memory access latency"),
+    ADD_STAT(masterReadAvgLat,
+             "Per-master read average memory access latency"),
+    ADD_STAT(masterWriteAvgLat,
+             "Per-master write average memory access latency"),
+
+    ADD_STAT(pageHitRate, "Row buffer hit rate, read and write combined")
+{
+}
+
 void
-DRAMCtrl::regStats()
+DRAMCtrl::DRAMStats::regStats()
 {
     using namespace Stats;
 
-    AbstractMemory::regStats();
-
-    for (auto r : ranks) {
-        r->regStats();
-    }
-
-    readReqs
-        .name(name() + ".readReqs")
-        .desc("Number of read requests accepted");
-
-    writeReqs
-        .name(name() + ".writeReqs")
-        .desc("Number of write requests accepted");
-
-    readBursts
-        .name(name() + ".readBursts")
-        .desc("Number of DRAM read bursts, "
-              "including those serviced by the write queue");
-
-    writeBursts
-        .name(name() + ".writeBursts")
-        .desc("Number of DRAM write bursts, "
-              "including those merged in the write queue");
-
-    servicedByWrQ
-        .name(name() + ".servicedByWrQ")
-        .desc("Number of DRAM read bursts serviced by the write queue");
-
-    mergedWrBursts
-        .name(name() + ".mergedWrBursts")
-        .desc("Number of DRAM write bursts merged with an existing one");
-
-    neitherReadNorWrite
-        .name(name() + ".neitherReadNorWriteReqs")
-        .desc("Number of requests that are neither read nor write");
-
-    perBankRdBursts
-        .init(banksPerRank * ranksPerChannel)
-        .name(name() + ".perBankRdBursts")
-        .desc("Per bank write bursts");
-
-    perBankWrBursts
-        .init(banksPerRank * ranksPerChannel)
-        .name(name() + ".perBankWrBursts")
-        .desc("Per bank write bursts");
-
-    avgRdQLen
-        .name(name() + ".avgRdQLen")
-        .desc("Average read queue length when enqueuing")
+    assert(dram._system);
+    const auto max_masters = dram._system->maxMasters();
+
+    perBankRdBursts.init(dram.banksPerRank * dram.ranksPerChannel);
+    perBankWrBursts.init(dram.banksPerRank * dram.ranksPerChannel);
+
+    avgRdQLen.precision(2);
+    avgWrQLen.precision(2);
+    avgQLat.precision(2);
+    avgBusLat.precision(2);
+    avgMemAccLat.precision(2);
+
+    readRowHitRate.precision(2);
+    writeRowHitRate.precision(2);
+
+    readPktSize.init(ceilLog2(dram.burstSize) + 1);
+    writePktSize.init(ceilLog2(dram.burstSize) + 1);
+
+    rdQLenPdf.init(dram.readBufferSize);
+    wrQLenPdf.init(dram.writeBufferSize);
+
+    bytesPerActivate
+        .init(dram.maxAccessesPerRow ?
+              dram.maxAccessesPerRow : dram.rowBufferSize)
+        .flags(nozero);
+
+    rdPerTurnAround
+        .init(dram.readBufferSize)
+        .flags(nozero);
+    wrPerTurnAround
+        .init(dram.writeBufferSize)
+        .flags(nozero);
+
+    avgRdBW.precision(2);
+    avgWrBW.precision(2);
+    avgRdBWSys.precision(2);
+    avgWrBWSys.precision(2);
+    peakBW.precision(2);
+    busUtil.precision(2);
+    avgGap.precision(2);
+    busUtilWrite.precision(2);
+    pageHitRate.precision(2);
+
+
+    // per-master bytes read and written to memory
+    masterReadBytes
+        .init(max_masters)
+        .flags(nozero | nonan);
+
+    masterWriteBytes
+        .init(max_masters)
+        .flags(nozero | nonan);
+
+    // per-master bytes read and written to memory rate
+    masterReadRate
+        .flags(nozero | nonan)
+        .precision(12);
+
+    masterReadAccesses
+        .init(max_masters)
+        .flags(nozero);
+
+    masterWriteAccesses
+        .init(max_masters)
+        .flags(nozero);
+
+    masterReadTotalLat
+        .init(max_masters)
+        .flags(nozero | nonan);
+
+    masterReadAvgLat
+        .flags(nonan)
         .precision(2);
 
-    avgWrQLen
-        .name(name() + ".avgWrQLen")
-        .desc("Average write queue length when enqueuing")
-        .precision(2);
 
-    totQLat
-        .name(name() + ".totQLat")
-        .desc("Total ticks spent queuing");
+    busUtilRead
+        .precision(2);
 
-    totBusLat
-        .name(name() + ".totBusLat")
-        .desc("Total ticks spent in databus transfers");
+    masterWriteRate
+        .flags(nozero | nonan)
+        .precision(12);
 
-    totMemAccLat
-        .name(name() + ".totMemAccLat")
-        .desc("Total ticks spent from burst creation until serviced "
-              "by the DRAM");
+    masterWriteTotalLat
+        .init(max_masters)
+        .flags(nozero | nonan);
 
-    avgQLat
-        .name(name() + ".avgQLat")
-        .desc("Average queueing delay per DRAM burst")
+    masterWriteAvgLat
+        .flags(nonan)
         .precision(2);
 
+    for (int i = 0; i < max_masters; i++) {
+        const std::string master = dram._system->getMasterName(i);
+        masterReadBytes.subname(i, master);
+        masterReadRate.subname(i, master);
+        masterWriteBytes.subname(i, master);
+        masterWriteRate.subname(i, master);
+        masterReadAccesses.subname(i, master);
+        masterWriteAccesses.subname(i, master);
+        masterReadTotalLat.subname(i, master);
+        masterReadAvgLat.subname(i, master);
+        masterWriteTotalLat.subname(i, master);
+        masterWriteAvgLat.subname(i, master);
+    }
+
+    // Formula stats
     avgQLat = totQLat / (readBursts - servicedByWrQ);
-
-    avgBusLat
-        .name(name() + ".avgBusLat")
-        .desc("Average bus latency per DRAM burst")
-        .precision(2);
-
     avgBusLat = totBusLat / (readBursts - servicedByWrQ);
-
-    avgMemAccLat
-        .name(name() + ".avgMemAccLat")
-        .desc("Average memory access latency per DRAM burst")
-        .precision(2);
-
     avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
 
-    numRdRetry
-        .name(name() + ".numRdRetry")
-        .desc("Number of times read queue was full causing retry");
-
-    numWrRetry
-        .name(name() + ".numWrRetry")
-        .desc("Number of times write queue was full causing retry");
-
-    readRowHits
-        .name(name() + ".readRowHits")
-        .desc("Number of row buffer hits during reads");
-
-    writeRowHits
-        .name(name() + ".writeRowHits")
-        .desc("Number of row buffer hits during writes");
-
-    readRowHitRate
-        .name(name() + ".readRowHitRate")
-        .desc("Row buffer hit rate for reads")
-        .precision(2);
-
     readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
-
-    writeRowHitRate
-        .name(name() + ".writeRowHitRate")
-        .desc("Row buffer hit rate for writes")
-        .precision(2);
-
     writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
 
-    readPktSize
-        .init(ceilLog2(burstSize) + 1)
-        .name(name() + ".readPktSize")
-        .desc("Read request sizes (log2)");
-
-     writePktSize
-        .init(ceilLog2(burstSize) + 1)
-        .name(name() + ".writePktSize")
-        .desc("Write request sizes (log2)");
-
-     rdQLenPdf
-        .init(readBufferSize)
-        .name(name() + ".rdQLenPdf")
-        .desc("What read queue length does an incoming req see");
-
-     wrQLenPdf
-        .init(writeBufferSize)
-        .name(name() + ".wrQLenPdf")
-        .desc("What write queue length does an incoming req see");
-
-     bytesPerActivate
-         .init(maxAccessesPerRow)
-         .name(name() + ".bytesPerActivate")
-         .desc("Bytes accessed per row activation")
-         .flags(nozero);
-
-     rdPerTurnAround
-         .init(readBufferSize)
-         .name(name() + ".rdPerTurnAround")
-         .desc("Reads before turning the bus around for writes")
-         .flags(nozero);
-
-     wrPerTurnAround
-         .init(writeBufferSize)
-         .name(name() + ".wrPerTurnAround")
-         .desc("Writes before turning the bus around for reads")
-         .flags(nozero);
-
-    bytesReadDRAM
-        .name(name() + ".bytesReadDRAM")
-        .desc("Total number of bytes read from DRAM");
-
-    bytesReadWrQ
-        .name(name() + ".bytesReadWrQ")
-        .desc("Total number of bytes read from write queue");
-
-    bytesWritten
-        .name(name() + ".bytesWritten")
-        .desc("Total number of bytes written to DRAM");
-
-    bytesReadSys
-        .name(name() + ".bytesReadSys")
-        .desc("Total read bytes from the system interface side");
-
-    bytesWrittenSys
-        .name(name() + ".bytesWrittenSys")
-        .desc("Total written bytes from the system interface side");
-
-    avgRdBW
-        .name(name() + ".avgRdBW")
-        .desc("Average DRAM read bandwidth in MiByte/s")
-        .precision(2);
-
     avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
-
-    avgWrBW
-        .name(name() + ".avgWrBW")
-        .desc("Average achieved write bandwidth in MiByte/s")
-        .precision(2);
-
     avgWrBW = (bytesWritten / 1000000) / simSeconds;
-
-    avgRdBWSys
-        .name(name() + ".avgRdBWSys")
-        .desc("Average system read bandwidth in MiByte/s")
-        .precision(2);
-
     avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
-
-    avgWrBWSys
-        .name(name() + ".avgWrBWSys")
-        .desc("Average system write bandwidth in MiByte/s")
-        .precision(2);
-
     avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
+    peakBW = (SimClock::Frequency / dram.tBURST) * dram.burstSize / 1000000;
 
-    peakBW
-        .name(name() + ".peakBW")
-        .desc("Theoretical peak bandwidth in MiByte/s")
-        .precision(2);
+    busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
 
-    peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
+    avgGap = totGap / (readReqs + writeReqs);
 
-    busUtil
-        .name(name() + ".busUtil")
-        .desc("Data bus utilization in percentage")
-        .precision(2);
-    busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
+    busUtilRead = avgRdBW / peakBW * 100;
+    busUtilWrite = avgWrBW / peakBW * 100;
 
-    totGap
-        .name(name() + ".totGap")
-        .desc("Total gap between requests");
+    pageHitRate = (writeRowHits + readRowHits) /
+        (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
 
-    avgGap
-        .name(name() + ".avgGap")
-        .desc("Average gap between requests")
-        .precision(2);
+    masterReadRate = masterReadBytes / simSeconds;
+    masterWriteRate = masterWriteBytes / simSeconds;
+    masterReadAvgLat = masterReadTotalLat / masterReadAccesses;
+    masterWriteAvgLat = masterWriteTotalLat / masterWriteAccesses;
+}
 
-    avgGap = totGap / (readReqs + writeReqs);
+void
+DRAMCtrl::DRAMStats::resetStats()
+{
+    dram.lastStatsResetTick = curTick();
+}
 
-    // Stats for DRAM Power calculation based on Micron datasheet
-    busUtilRead
-        .name(name() + ".busUtilRead")
-        .desc("Data bus utilization in percentage for reads")
-        .precision(2);
+DRAMCtrl::RankStats::RankStats(DRAMCtrl &_memory, Rank &_rank)
+    : Stats::Group(&_memory, csprintf("rank%d", _rank.rank).c_str()),
+    rank(_rank),
+
+    ADD_STAT(actEnergy, "Energy for activate commands per rank (pJ)"),
+    ADD_STAT(preEnergy, "Energy for precharge commands per rank (pJ)"),
+    ADD_STAT(readEnergy, "Energy for read commands per rank (pJ)"),
+    ADD_STAT(writeEnergy, "Energy for write commands per rank (pJ)"),
+    ADD_STAT(refreshEnergy, "Energy for refresh commands per rank (pJ)"),
+    ADD_STAT(actBackEnergy, "Energy for active background per rank (pJ)"),
+    ADD_STAT(preBackEnergy, "Energy for precharge background per rank (pJ)"),
+    ADD_STAT(actPowerDownEnergy,
+             "Energy for active power-down per rank (pJ)"),
+    ADD_STAT(prePowerDownEnergy,
+             "Energy for precharge power-down per rank (pJ)"),
+    ADD_STAT(selfRefreshEnergy, "Energy for self refresh per rank (pJ)"),
+
+    ADD_STAT(totalEnergy, "Total energy per rank (pJ)"),
+    ADD_STAT(averagePower, "Core power per rank (mW)"),
+
+    ADD_STAT(totalIdleTime, "Total Idle time Per DRAM Rank"),
+    ADD_STAT(memoryStateTime, "Time in different power states")
+{
+}
 
-    busUtilRead = avgRdBW / peakBW * 100;
+void
+DRAMCtrl::RankStats::regStats()
+{
+    Stats::Group::regStats();
+
+    memoryStateTime.init(6);
+    memoryStateTime.subname(0, "IDLE");
+    memoryStateTime.subname(1, "REF");
+    memoryStateTime.subname(2, "SREF");
+    memoryStateTime.subname(3, "PRE_PDN");
+    memoryStateTime.subname(4, "ACT");
+    memoryStateTime.subname(5, "ACT_PDN");
+}
 
-    busUtilWrite
-        .name(name() + ".busUtilWrite")
-        .desc("Data bus utilization in percentage for writes")
-        .precision(2);
+void
+DRAMCtrl::RankStats::resetStats()
+{
+    Stats::Group::resetStats();
 
-    busUtilWrite = avgWrBW / peakBW * 100;
+    rank.resetStats();
+}
 
-    pageHitRate
-        .name(name() + ".pageHitRate")
-        .desc("Row buffer hit rate, read and write combined")
-        .precision(2);
+void
+DRAMCtrl::RankStats::preDumpStats()
+{
+    Stats::Group::preDumpStats();
 
-    pageHitRate = (writeRowHits + readRowHits) /
-        (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
+    rank.computeStats();
 }
 
 void
@@ -2618,11 +2737,11 @@ DRAMCtrl::recvFunctional(PacketPtr pkt)
     functionalAccess(pkt);
 }
 
-BaseSlavePort&
-DRAMCtrl::getSlavePort(const string &if_name, PortID idx)
+Port &
+DRAMCtrl::getPort(const string &if_name, PortID idx)
 {
     if (if_name != "port") {
-        return MemObject::getSlavePort(if_name, idx);
+        return QoS::MemCtrl::getPort(if_name, idx);
     } else {
         return port;
     }
@@ -2633,16 +2752,16 @@ DRAMCtrl::drain()
 {
     // if there is anything in any of our internal queues, keep track
     // of that as well
-    if (!(writeQueue.empty() && readQueue.empty() && respQueue.empty() &&
+    if (!(!totalWriteQueueSize && !totalReadQueueSize && respQueue.empty() &&
           allRanksDrained())) {
 
         DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
-                " resp: %d\n", writeQueue.size(), readQueue.size(),
+                " resp: %d\n", totalWriteQueueSize, totalReadQueueSize,
                 respQueue.size());
 
         // the only queue that is not drained automatically over time
         // is the write queue, thus kick things into action if needed
-        if (!writeQueue.empty() && !nextReqEvent.scheduled()) {
+        if (!totalWriteQueueSize && !nextReqEvent.scheduled()) {
             schedule(nextReqEvent, curTick());
         }
 
@@ -2668,9 +2787,11 @@ DRAMCtrl::allRanksDrained() const
     // true until proven false
     bool all_ranks_drained = true;
     for (auto r : ranks) {
-        // then verify that the power state is IDLE
-        // ensuring all banks are closed and rank is not in a low power state
-        all_ranks_drained = r->inPwrIdleState() && all_ranks_drained;
+        // then verify that the power state is IDLE ensuring all banks are
+        // closed and rank is not in a low power state. Also verify that rank
+        // is idle from a refresh point of view.
+        all_ranks_drained = r->inPwrIdleState() && r->inRefIdleState() &&
+            all_ranks_drained;
     }
     return all_ranks_drained;
 }
@@ -2695,7 +2816,7 @@ DRAMCtrl::drainResume()
 }
 
 DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
-    : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
+    : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this, true),
       memory(_memory)
 { }
 
@@ -2712,7 +2833,7 @@ DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
 {
     pkt->pushLabel(memory.name());
 
-    if (!queue.checkFunctional(pkt)) {
+    if (!queue.trySatisfyFunctional(pkt)) {
         // Default implementation of SimpleTimingPort::recvFunctional()
         // calls recvAtomic() and throws away the latency; we can save a
         // little here by just not calculating the latency.