dram_ctrl.cc (11677:beaf1afe2f83) dram_ctrl.cc (11678:8c6991a00515)
1/*
2 * Copyright (c) 2010-2016 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2013 Amin Farmahini-Farahani
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Andreas Hansson
41 * Ani Udipi
42 * Neha Agarwal
43 * Omar Naji
1/*
2 * Copyright (c) 2010-2016 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2013 Amin Farmahini-Farahani
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Andreas Hansson
41 * Ani Udipi
42 * Neha Agarwal
43 * Omar Naji
44 * Wendy Elsasser
44 */
45
46#include "base/bitfield.hh"
47#include "base/trace.hh"
48#include "debug/DRAM.hh"
49#include "debug/DRAMPower.hh"
50#include "debug/DRAMState.hh"
51#include "debug/Drain.hh"
52#include "mem/dram_ctrl.hh"
53#include "sim/system.hh"
54
55using namespace std;
56using namespace Data;
57
58DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
59 AbstractMemory(p),
60 port(name() + ".port", *this), isTimingMode(false),
61 retryRdReq(false), retryWrReq(false),
62 busState(READ),
45 */
46
47#include "base/bitfield.hh"
48#include "base/trace.hh"
49#include "debug/DRAM.hh"
50#include "debug/DRAMPower.hh"
51#include "debug/DRAMState.hh"
52#include "debug/Drain.hh"
53#include "mem/dram_ctrl.hh"
54#include "sim/system.hh"
55
56using namespace std;
57using namespace Data;
58
59DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
60 AbstractMemory(p),
61 port(name() + ".port", *this), isTimingMode(false),
62 retryRdReq(false), retryWrReq(false),
63 busState(READ),
64 busStateNext(READ),
63 nextReqEvent(this), respondEvent(this),
64 deviceSize(p->device_size),
65 deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
66 deviceRowBufferSize(p->device_rowbuffer_size),
67 devicesPerRank(p->devices_per_rank),
68 burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8),
69 rowBufferSize(devicesPerRank * deviceRowBufferSize),
70 columnsPerRowBuffer(rowBufferSize / burstSize),
71 columnsPerStripe(range.interleaved() ? range.granularity() / burstSize : 1),
72 ranksPerChannel(p->ranks_per_channel),
73 bankGroupsPerRank(p->bank_groups_per_rank),
74 bankGroupArch(p->bank_groups_per_rank > 0),
75 banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0),
76 readBufferSize(p->read_buffer_size),
77 writeBufferSize(p->write_buffer_size),
78 writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0),
79 writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0),
80 minWritesPerSwitch(p->min_writes_per_switch),
81 writesThisTime(0), readsThisTime(0),
82 tCK(p->tCK), tWTR(p->tWTR), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST),
83 tCCD_L(p->tCCD_L), tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
84 tWR(p->tWR), tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
85 tRRD_L(p->tRRD_L), tXAW(p->tXAW), tXP(p->tXP), tXS(p->tXS),
86 activationLimit(p->activation_limit),
87 memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
88 pageMgmt(p->page_policy),
89 maxAccessesPerRow(p->max_accesses_per_row),
90 frontendLatency(p->static_frontend_latency),
91 backendLatency(p->static_backend_latency),
92 busBusyUntil(0), prevArrival(0),
93 nextReqTime(0), activeRank(0), timeStampOffset(0)
94{
95 // sanity check the ranks since we rely on bit slicing for the
96 // address decoding
97 fatal_if(!isPowerOf2(ranksPerChannel), "DRAM rank count of %d is not "
98 "allowed, must be a power of two\n", ranksPerChannel);
99
100 fatal_if(!isPowerOf2(burstSize), "DRAM burst size %d is not allowed, "
101 "must be a power of two\n", burstSize);
102
103 for (int i = 0; i < ranksPerChannel; i++) {
104 Rank* rank = new Rank(*this, p);
105 ranks.push_back(rank);
106
107 rank->actTicks.resize(activationLimit, 0);
108 rank->banks.resize(banksPerRank);
109 rank->rank = i;
110
111 for (int b = 0; b < banksPerRank; b++) {
112 rank->banks[b].bank = b;
113 // GDDR addressing of banks to BG is linear.
114 // Here we assume that all DRAM generations address bank groups as
115 // follows:
116 if (bankGroupArch) {
117 // Simply assign lower bits to bank group in order to
118 // rotate across bank groups as banks are incremented
119 // e.g. with 4 banks per bank group and 16 banks total:
120 // banks 0,4,8,12 are in bank group 0
121 // banks 1,5,9,13 are in bank group 1
122 // banks 2,6,10,14 are in bank group 2
123 // banks 3,7,11,15 are in bank group 3
124 rank->banks[b].bankgr = b % bankGroupsPerRank;
125 } else {
126 // No bank groups; simply assign to bank number
127 rank->banks[b].bankgr = b;
128 }
129 }
130 }
131
132 // perform a basic check of the write thresholds
133 if (p->write_low_thresh_perc >= p->write_high_thresh_perc)
134 fatal("Write buffer low threshold %d must be smaller than the "
135 "high threshold %d\n", p->write_low_thresh_perc,
136 p->write_high_thresh_perc);
137
138 // determine the rows per bank by looking at the total capacity
139 uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
140
141 // determine the dram actual capacity from the DRAM config in Mbytes
142 uint64_t deviceCapacity = deviceSize / (1024 * 1024) * devicesPerRank *
143 ranksPerChannel;
144
145 // if actual DRAM size does not match memory capacity in system warn!
146 if (deviceCapacity != capacity / (1024 * 1024))
147 warn("DRAM device capacity (%d Mbytes) does not match the "
148 "address range assigned (%d Mbytes)\n", deviceCapacity,
149 capacity / (1024 * 1024));
150
151 DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
152 AbstractMemory::size());
153
154 DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
155 rowBufferSize, columnsPerRowBuffer);
156
157 rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
158
159 // some basic sanity checks
160 if (tREFI <= tRP || tREFI <= tRFC) {
161 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
162 tREFI, tRP, tRFC);
163 }
164
165 // basic bank group architecture checks ->
166 if (bankGroupArch) {
167 // must have at least one bank per bank group
168 if (bankGroupsPerRank > banksPerRank) {
169 fatal("banks per rank (%d) must be equal to or larger than "
170 "banks groups per rank (%d)\n",
171 banksPerRank, bankGroupsPerRank);
172 }
173 // must have same number of banks in each bank group
174 if ((banksPerRank % bankGroupsPerRank) != 0) {
175 fatal("Banks per rank (%d) must be evenly divisible by bank groups "
176 "per rank (%d) for equal banks per bank group\n",
177 banksPerRank, bankGroupsPerRank);
178 }
179 // tCCD_L should be greater than minimal, back-to-back burst delay
180 if (tCCD_L <= tBURST) {
181 fatal("tCCD_L (%d) should be larger than tBURST (%d) when "
182 "bank groups per rank (%d) is greater than 1\n",
183 tCCD_L, tBURST, bankGroupsPerRank);
184 }
185 // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
186 // some datasheets might specify it equal to tRRD
187 if (tRRD_L < tRRD) {
188 fatal("tRRD_L (%d) should be larger than tRRD (%d) when "
189 "bank groups per rank (%d) is greater than 1\n",
190 tRRD_L, tRRD, bankGroupsPerRank);
191 }
192 }
193
194}
195
196void
197DRAMCtrl::init()
198{
199 AbstractMemory::init();
200
201 if (!port.isConnected()) {
202 fatal("DRAMCtrl %s is unconnected!\n", name());
203 } else {
204 port.sendRangeChange();
205 }
206
207 // a bit of sanity checks on the interleaving, save it for here to
208 // ensure that the system pointer is initialised
209 if (range.interleaved()) {
210 if (channels != range.stripes())
211 fatal("%s has %d interleaved address stripes but %d channel(s)\n",
212 name(), range.stripes(), channels);
213
214 if (addrMapping == Enums::RoRaBaChCo) {
215 if (rowBufferSize != range.granularity()) {
216 fatal("Channel interleaving of %s doesn't match RoRaBaChCo "
217 "address map\n", name());
218 }
219 } else if (addrMapping == Enums::RoRaBaCoCh ||
220 addrMapping == Enums::RoCoRaBaCh) {
221 // for the interleavings with channel bits in the bottom,
222 // if the system uses a channel striping granularity that
223 // is larger than the DRAM burst size, then map the
224 // sequential accesses within a stripe to a number of
225 // columns in the DRAM, effectively placing some of the
226 // lower-order column bits as the least-significant bits
227 // of the address (above the ones denoting the burst size)
228 assert(columnsPerStripe >= 1);
229
230 // channel striping has to be done at a granularity that
231 // is equal or larger to a cache line
232 if (system()->cacheLineSize() > range.granularity()) {
233 fatal("Channel interleaving of %s must be at least as large "
234 "as the cache line size\n", name());
235 }
236
237 // ...and equal or smaller than the row-buffer size
238 if (rowBufferSize < range.granularity()) {
239 fatal("Channel interleaving of %s must be at most as large "
240 "as the row-buffer size\n", name());
241 }
242 // this is essentially the check above, so just to be sure
243 assert(columnsPerStripe <= columnsPerRowBuffer);
244 }
245 }
246}
247
248void
249DRAMCtrl::startup()
250{
251 // remember the memory system mode of operation
252 isTimingMode = system()->isTimingMode();
253
254 if (isTimingMode) {
255 // timestamp offset should be in clock cycles for DRAMPower
256 timeStampOffset = divCeil(curTick(), tCK);
257
258 // update the start tick for the precharge accounting to the
259 // current tick
260 for (auto r : ranks) {
261 r->startup(curTick() + tREFI - tRP);
262 }
263
264 // shift the bus busy time sufficiently far ahead that we never
265 // have to worry about negative values when computing the time for
266 // the next request, this will add an insignificant bubble at the
267 // start of simulation
268 busBusyUntil = curTick() + tRP + tRCD + tCL;
269 }
270}
271
272Tick
273DRAMCtrl::recvAtomic(PacketPtr pkt)
274{
275 DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
276
277 panic_if(pkt->cacheResponding(), "Should not see packets where cache "
278 "is responding");
279
280 // do the actual memory access and turn the packet into a response
281 access(pkt);
282
283 Tick latency = 0;
284 if (pkt->hasData()) {
285 // this value is not supposed to be accurate, just enough to
286 // keep things going, mimic a closed page
287 latency = tRP + tRCD + tCL;
288 }
289 return latency;
290}
291
292bool
293DRAMCtrl::readQueueFull(unsigned int neededEntries) const
294{
295 DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
296 readBufferSize, readQueue.size() + respQueue.size(),
297 neededEntries);
298
299 return
300 (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
301}
302
303bool
304DRAMCtrl::writeQueueFull(unsigned int neededEntries) const
305{
306 DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
307 writeBufferSize, writeQueue.size(), neededEntries);
308 return (writeQueue.size() + neededEntries) > writeBufferSize;
309}
310
311DRAMCtrl::DRAMPacket*
312DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size,
313 bool isRead)
314{
315 // decode the address based on the address mapping scheme, with
316 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
317 // channel, respectively
318 uint8_t rank;
319 uint8_t bank;
320 // use a 64-bit unsigned during the computations as the row is
321 // always the top bits, and check before creating the DRAMPacket
322 uint64_t row;
323
324 // truncate the address to a DRAM burst, which makes it unique to
325 // a specific column, row, bank, rank and channel
326 Addr addr = dramPktAddr / burstSize;
327
328 // we have removed the lowest order address bits that denote the
329 // position within the column
330 if (addrMapping == Enums::RoRaBaChCo) {
331 // the lowest order bits denote the column to ensure that
332 // sequential cache lines occupy the same row
333 addr = addr / columnsPerRowBuffer;
334
335 // take out the channel part of the address
336 addr = addr / channels;
337
338 // after the channel bits, get the bank bits to interleave
339 // over the banks
340 bank = addr % banksPerRank;
341 addr = addr / banksPerRank;
342
343 // after the bank, we get the rank bits which thus interleaves
344 // over the ranks
345 rank = addr % ranksPerChannel;
346 addr = addr / ranksPerChannel;
347
348 // lastly, get the row bits, no need to remove them from addr
349 row = addr % rowsPerBank;
350 } else if (addrMapping == Enums::RoRaBaCoCh) {
351 // take out the lower-order column bits
352 addr = addr / columnsPerStripe;
353
354 // take out the channel part of the address
355 addr = addr / channels;
356
357 // next, the higher-order column bites
358 addr = addr / (columnsPerRowBuffer / columnsPerStripe);
359
360 // after the column bits, we get the bank bits to interleave
361 // over the banks
362 bank = addr % banksPerRank;
363 addr = addr / banksPerRank;
364
365 // after the bank, we get the rank bits which thus interleaves
366 // over the ranks
367 rank = addr % ranksPerChannel;
368 addr = addr / ranksPerChannel;
369
370 // lastly, get the row bits, no need to remove them from addr
371 row = addr % rowsPerBank;
372 } else if (addrMapping == Enums::RoCoRaBaCh) {
373 // optimise for closed page mode and utilise maximum
374 // parallelism of the DRAM (at the cost of power)
375
376 // take out the lower-order column bits
377 addr = addr / columnsPerStripe;
378
379 // take out the channel part of the address, not that this has
380 // to match with how accesses are interleaved between the
381 // controllers in the address mapping
382 addr = addr / channels;
383
384 // start with the bank bits, as this provides the maximum
385 // opportunity for parallelism between requests
386 bank = addr % banksPerRank;
387 addr = addr / banksPerRank;
388
389 // next get the rank bits
390 rank = addr % ranksPerChannel;
391 addr = addr / ranksPerChannel;
392
393 // next, the higher-order column bites
394 addr = addr / (columnsPerRowBuffer / columnsPerStripe);
395
396 // lastly, get the row bits, no need to remove them from addr
397 row = addr % rowsPerBank;
398 } else
399 panic("Unknown address mapping policy chosen!");
400
401 assert(rank < ranksPerChannel);
402 assert(bank < banksPerRank);
403 assert(row < rowsPerBank);
404 assert(row < Bank::NO_ROW);
405
406 DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
407 dramPktAddr, rank, bank, row);
408
409 // create the corresponding DRAM packet with the entry time and
410 // ready time set to the current tick, the latter will be updated
411 // later
412 uint16_t bank_id = banksPerRank * rank + bank;
413 return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
414 size, ranks[rank]->banks[bank], *ranks[rank]);
415}
416
417void
418DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
419{
420 // only add to the read queue here. whenever the request is
421 // eventually done, set the readyTime, and call schedule()
422 assert(!pkt->isWrite());
423
424 assert(pktCount != 0);
425
426 // if the request size is larger than burst size, the pkt is split into
427 // multiple DRAM packets
428 // Note if the pkt starting address is not aligened to burst size, the
429 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
430 // are aligned to burst size boundaries. This is to ensure we accurately
431 // check read packets against packets in write queue.
432 Addr addr = pkt->getAddr();
433 unsigned pktsServicedByWrQ = 0;
434 BurstHelper* burst_helper = NULL;
435 for (int cnt = 0; cnt < pktCount; ++cnt) {
436 unsigned size = std::min((addr | (burstSize - 1)) + 1,
437 pkt->getAddr() + pkt->getSize()) - addr;
438 readPktSize[ceilLog2(size)]++;
439 readBursts++;
440
441 // First check write buffer to see if the data is already at
442 // the controller
443 bool foundInWrQ = false;
444 Addr burst_addr = burstAlign(addr);
445 // if the burst address is not present then there is no need
446 // looking any further
447 if (isInWriteQueue.find(burst_addr) != isInWriteQueue.end()) {
448 for (const auto& p : writeQueue) {
449 // check if the read is subsumed in the write queue
450 // packet we are looking at
451 if (p->addr <= addr && (addr + size) <= (p->addr + p->size)) {
452 foundInWrQ = true;
453 servicedByWrQ++;
454 pktsServicedByWrQ++;
455 DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
456 "write queue\n", addr, size);
457 bytesReadWrQ += burstSize;
458 break;
459 }
460 }
461 }
462
463 // If not found in the write q, make a DRAM packet and
464 // push it onto the read queue
465 if (!foundInWrQ) {
466
467 // Make the burst helper for split packets
468 if (pktCount > 1 && burst_helper == NULL) {
469 DPRINTF(DRAM, "Read to addr %lld translates to %d "
470 "dram requests\n", pkt->getAddr(), pktCount);
471 burst_helper = new BurstHelper(pktCount);
472 }
473
474 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
475 dram_pkt->burstHelper = burst_helper;
476
477 assert(!readQueueFull(1));
478 rdQLenPdf[readQueue.size() + respQueue.size()]++;
479
480 DPRINTF(DRAM, "Adding to read queue\n");
481
482 readQueue.push_back(dram_pkt);
483
65 nextReqEvent(this), respondEvent(this),
66 deviceSize(p->device_size),
67 deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
68 deviceRowBufferSize(p->device_rowbuffer_size),
69 devicesPerRank(p->devices_per_rank),
70 burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8),
71 rowBufferSize(devicesPerRank * deviceRowBufferSize),
72 columnsPerRowBuffer(rowBufferSize / burstSize),
73 columnsPerStripe(range.interleaved() ? range.granularity() / burstSize : 1),
74 ranksPerChannel(p->ranks_per_channel),
75 bankGroupsPerRank(p->bank_groups_per_rank),
76 bankGroupArch(p->bank_groups_per_rank > 0),
77 banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0),
78 readBufferSize(p->read_buffer_size),
79 writeBufferSize(p->write_buffer_size),
80 writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0),
81 writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0),
82 minWritesPerSwitch(p->min_writes_per_switch),
83 writesThisTime(0), readsThisTime(0),
84 tCK(p->tCK), tWTR(p->tWTR), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST),
85 tCCD_L(p->tCCD_L), tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
86 tWR(p->tWR), tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
87 tRRD_L(p->tRRD_L), tXAW(p->tXAW), tXP(p->tXP), tXS(p->tXS),
88 activationLimit(p->activation_limit),
89 memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
90 pageMgmt(p->page_policy),
91 maxAccessesPerRow(p->max_accesses_per_row),
92 frontendLatency(p->static_frontend_latency),
93 backendLatency(p->static_backend_latency),
94 busBusyUntil(0), prevArrival(0),
95 nextReqTime(0), activeRank(0), timeStampOffset(0)
96{
97 // sanity check the ranks since we rely on bit slicing for the
98 // address decoding
99 fatal_if(!isPowerOf2(ranksPerChannel), "DRAM rank count of %d is not "
100 "allowed, must be a power of two\n", ranksPerChannel);
101
102 fatal_if(!isPowerOf2(burstSize), "DRAM burst size %d is not allowed, "
103 "must be a power of two\n", burstSize);
104
105 for (int i = 0; i < ranksPerChannel; i++) {
106 Rank* rank = new Rank(*this, p);
107 ranks.push_back(rank);
108
109 rank->actTicks.resize(activationLimit, 0);
110 rank->banks.resize(banksPerRank);
111 rank->rank = i;
112
113 for (int b = 0; b < banksPerRank; b++) {
114 rank->banks[b].bank = b;
115 // GDDR addressing of banks to BG is linear.
116 // Here we assume that all DRAM generations address bank groups as
117 // follows:
118 if (bankGroupArch) {
119 // Simply assign lower bits to bank group in order to
120 // rotate across bank groups as banks are incremented
121 // e.g. with 4 banks per bank group and 16 banks total:
122 // banks 0,4,8,12 are in bank group 0
123 // banks 1,5,9,13 are in bank group 1
124 // banks 2,6,10,14 are in bank group 2
125 // banks 3,7,11,15 are in bank group 3
126 rank->banks[b].bankgr = b % bankGroupsPerRank;
127 } else {
128 // No bank groups; simply assign to bank number
129 rank->banks[b].bankgr = b;
130 }
131 }
132 }
133
134 // perform a basic check of the write thresholds
135 if (p->write_low_thresh_perc >= p->write_high_thresh_perc)
136 fatal("Write buffer low threshold %d must be smaller than the "
137 "high threshold %d\n", p->write_low_thresh_perc,
138 p->write_high_thresh_perc);
139
140 // determine the rows per bank by looking at the total capacity
141 uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
142
143 // determine the dram actual capacity from the DRAM config in Mbytes
144 uint64_t deviceCapacity = deviceSize / (1024 * 1024) * devicesPerRank *
145 ranksPerChannel;
146
147 // if actual DRAM size does not match memory capacity in system warn!
148 if (deviceCapacity != capacity / (1024 * 1024))
149 warn("DRAM device capacity (%d Mbytes) does not match the "
150 "address range assigned (%d Mbytes)\n", deviceCapacity,
151 capacity / (1024 * 1024));
152
153 DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
154 AbstractMemory::size());
155
156 DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
157 rowBufferSize, columnsPerRowBuffer);
158
159 rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
160
161 // some basic sanity checks
162 if (tREFI <= tRP || tREFI <= tRFC) {
163 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
164 tREFI, tRP, tRFC);
165 }
166
167 // basic bank group architecture checks ->
168 if (bankGroupArch) {
169 // must have at least one bank per bank group
170 if (bankGroupsPerRank > banksPerRank) {
171 fatal("banks per rank (%d) must be equal to or larger than "
172 "banks groups per rank (%d)\n",
173 banksPerRank, bankGroupsPerRank);
174 }
175 // must have same number of banks in each bank group
176 if ((banksPerRank % bankGroupsPerRank) != 0) {
177 fatal("Banks per rank (%d) must be evenly divisible by bank groups "
178 "per rank (%d) for equal banks per bank group\n",
179 banksPerRank, bankGroupsPerRank);
180 }
181 // tCCD_L should be greater than minimal, back-to-back burst delay
182 if (tCCD_L <= tBURST) {
183 fatal("tCCD_L (%d) should be larger than tBURST (%d) when "
184 "bank groups per rank (%d) is greater than 1\n",
185 tCCD_L, tBURST, bankGroupsPerRank);
186 }
187 // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
188 // some datasheets might specify it equal to tRRD
189 if (tRRD_L < tRRD) {
190 fatal("tRRD_L (%d) should be larger than tRRD (%d) when "
191 "bank groups per rank (%d) is greater than 1\n",
192 tRRD_L, tRRD, bankGroupsPerRank);
193 }
194 }
195
196}
197
198void
199DRAMCtrl::init()
200{
201 AbstractMemory::init();
202
203 if (!port.isConnected()) {
204 fatal("DRAMCtrl %s is unconnected!\n", name());
205 } else {
206 port.sendRangeChange();
207 }
208
209 // a bit of sanity checks on the interleaving, save it for here to
210 // ensure that the system pointer is initialised
211 if (range.interleaved()) {
212 if (channels != range.stripes())
213 fatal("%s has %d interleaved address stripes but %d channel(s)\n",
214 name(), range.stripes(), channels);
215
216 if (addrMapping == Enums::RoRaBaChCo) {
217 if (rowBufferSize != range.granularity()) {
218 fatal("Channel interleaving of %s doesn't match RoRaBaChCo "
219 "address map\n", name());
220 }
221 } else if (addrMapping == Enums::RoRaBaCoCh ||
222 addrMapping == Enums::RoCoRaBaCh) {
223 // for the interleavings with channel bits in the bottom,
224 // if the system uses a channel striping granularity that
225 // is larger than the DRAM burst size, then map the
226 // sequential accesses within a stripe to a number of
227 // columns in the DRAM, effectively placing some of the
228 // lower-order column bits as the least-significant bits
229 // of the address (above the ones denoting the burst size)
230 assert(columnsPerStripe >= 1);
231
232 // channel striping has to be done at a granularity that
233 // is equal or larger to a cache line
234 if (system()->cacheLineSize() > range.granularity()) {
235 fatal("Channel interleaving of %s must be at least as large "
236 "as the cache line size\n", name());
237 }
238
239 // ...and equal or smaller than the row-buffer size
240 if (rowBufferSize < range.granularity()) {
241 fatal("Channel interleaving of %s must be at most as large "
242 "as the row-buffer size\n", name());
243 }
244 // this is essentially the check above, so just to be sure
245 assert(columnsPerStripe <= columnsPerRowBuffer);
246 }
247 }
248}
249
250void
251DRAMCtrl::startup()
252{
253 // remember the memory system mode of operation
254 isTimingMode = system()->isTimingMode();
255
256 if (isTimingMode) {
257 // timestamp offset should be in clock cycles for DRAMPower
258 timeStampOffset = divCeil(curTick(), tCK);
259
260 // update the start tick for the precharge accounting to the
261 // current tick
262 for (auto r : ranks) {
263 r->startup(curTick() + tREFI - tRP);
264 }
265
266 // shift the bus busy time sufficiently far ahead that we never
267 // have to worry about negative values when computing the time for
268 // the next request, this will add an insignificant bubble at the
269 // start of simulation
270 busBusyUntil = curTick() + tRP + tRCD + tCL;
271 }
272}
273
274Tick
275DRAMCtrl::recvAtomic(PacketPtr pkt)
276{
277 DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
278
279 panic_if(pkt->cacheResponding(), "Should not see packets where cache "
280 "is responding");
281
282 // do the actual memory access and turn the packet into a response
283 access(pkt);
284
285 Tick latency = 0;
286 if (pkt->hasData()) {
287 // this value is not supposed to be accurate, just enough to
288 // keep things going, mimic a closed page
289 latency = tRP + tRCD + tCL;
290 }
291 return latency;
292}
293
294bool
295DRAMCtrl::readQueueFull(unsigned int neededEntries) const
296{
297 DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
298 readBufferSize, readQueue.size() + respQueue.size(),
299 neededEntries);
300
301 return
302 (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
303}
304
305bool
306DRAMCtrl::writeQueueFull(unsigned int neededEntries) const
307{
308 DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
309 writeBufferSize, writeQueue.size(), neededEntries);
310 return (writeQueue.size() + neededEntries) > writeBufferSize;
311}
312
313DRAMCtrl::DRAMPacket*
314DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size,
315 bool isRead)
316{
317 // decode the address based on the address mapping scheme, with
318 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
319 // channel, respectively
320 uint8_t rank;
321 uint8_t bank;
322 // use a 64-bit unsigned during the computations as the row is
323 // always the top bits, and check before creating the DRAMPacket
324 uint64_t row;
325
326 // truncate the address to a DRAM burst, which makes it unique to
327 // a specific column, row, bank, rank and channel
328 Addr addr = dramPktAddr / burstSize;
329
330 // we have removed the lowest order address bits that denote the
331 // position within the column
332 if (addrMapping == Enums::RoRaBaChCo) {
333 // the lowest order bits denote the column to ensure that
334 // sequential cache lines occupy the same row
335 addr = addr / columnsPerRowBuffer;
336
337 // take out the channel part of the address
338 addr = addr / channels;
339
340 // after the channel bits, get the bank bits to interleave
341 // over the banks
342 bank = addr % banksPerRank;
343 addr = addr / banksPerRank;
344
345 // after the bank, we get the rank bits which thus interleaves
346 // over the ranks
347 rank = addr % ranksPerChannel;
348 addr = addr / ranksPerChannel;
349
350 // lastly, get the row bits, no need to remove them from addr
351 row = addr % rowsPerBank;
352 } else if (addrMapping == Enums::RoRaBaCoCh) {
353 // take out the lower-order column bits
354 addr = addr / columnsPerStripe;
355
356 // take out the channel part of the address
357 addr = addr / channels;
358
359 // next, the higher-order column bites
360 addr = addr / (columnsPerRowBuffer / columnsPerStripe);
361
362 // after the column bits, we get the bank bits to interleave
363 // over the banks
364 bank = addr % banksPerRank;
365 addr = addr / banksPerRank;
366
367 // after the bank, we get the rank bits which thus interleaves
368 // over the ranks
369 rank = addr % ranksPerChannel;
370 addr = addr / ranksPerChannel;
371
372 // lastly, get the row bits, no need to remove them from addr
373 row = addr % rowsPerBank;
374 } else if (addrMapping == Enums::RoCoRaBaCh) {
375 // optimise for closed page mode and utilise maximum
376 // parallelism of the DRAM (at the cost of power)
377
378 // take out the lower-order column bits
379 addr = addr / columnsPerStripe;
380
381 // take out the channel part of the address, not that this has
382 // to match with how accesses are interleaved between the
383 // controllers in the address mapping
384 addr = addr / channels;
385
386 // start with the bank bits, as this provides the maximum
387 // opportunity for parallelism between requests
388 bank = addr % banksPerRank;
389 addr = addr / banksPerRank;
390
391 // next get the rank bits
392 rank = addr % ranksPerChannel;
393 addr = addr / ranksPerChannel;
394
395 // next, the higher-order column bites
396 addr = addr / (columnsPerRowBuffer / columnsPerStripe);
397
398 // lastly, get the row bits, no need to remove them from addr
399 row = addr % rowsPerBank;
400 } else
401 panic("Unknown address mapping policy chosen!");
402
403 assert(rank < ranksPerChannel);
404 assert(bank < banksPerRank);
405 assert(row < rowsPerBank);
406 assert(row < Bank::NO_ROW);
407
408 DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
409 dramPktAddr, rank, bank, row);
410
411 // create the corresponding DRAM packet with the entry time and
412 // ready time set to the current tick, the latter will be updated
413 // later
414 uint16_t bank_id = banksPerRank * rank + bank;
415 return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
416 size, ranks[rank]->banks[bank], *ranks[rank]);
417}
418
419void
420DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
421{
422 // only add to the read queue here. whenever the request is
423 // eventually done, set the readyTime, and call schedule()
424 assert(!pkt->isWrite());
425
426 assert(pktCount != 0);
427
428 // if the request size is larger than burst size, the pkt is split into
429 // multiple DRAM packets
430 // Note if the pkt starting address is not aligened to burst size, the
431 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
432 // are aligned to burst size boundaries. This is to ensure we accurately
433 // check read packets against packets in write queue.
434 Addr addr = pkt->getAddr();
435 unsigned pktsServicedByWrQ = 0;
436 BurstHelper* burst_helper = NULL;
437 for (int cnt = 0; cnt < pktCount; ++cnt) {
438 unsigned size = std::min((addr | (burstSize - 1)) + 1,
439 pkt->getAddr() + pkt->getSize()) - addr;
440 readPktSize[ceilLog2(size)]++;
441 readBursts++;
442
443 // First check write buffer to see if the data is already at
444 // the controller
445 bool foundInWrQ = false;
446 Addr burst_addr = burstAlign(addr);
447 // if the burst address is not present then there is no need
448 // looking any further
449 if (isInWriteQueue.find(burst_addr) != isInWriteQueue.end()) {
450 for (const auto& p : writeQueue) {
451 // check if the read is subsumed in the write queue
452 // packet we are looking at
453 if (p->addr <= addr && (addr + size) <= (p->addr + p->size)) {
454 foundInWrQ = true;
455 servicedByWrQ++;
456 pktsServicedByWrQ++;
457 DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
458 "write queue\n", addr, size);
459 bytesReadWrQ += burstSize;
460 break;
461 }
462 }
463 }
464
465 // If not found in the write q, make a DRAM packet and
466 // push it onto the read queue
467 if (!foundInWrQ) {
468
469 // Make the burst helper for split packets
470 if (pktCount > 1 && burst_helper == NULL) {
471 DPRINTF(DRAM, "Read to addr %lld translates to %d "
472 "dram requests\n", pkt->getAddr(), pktCount);
473 burst_helper = new BurstHelper(pktCount);
474 }
475
476 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
477 dram_pkt->burstHelper = burst_helper;
478
479 assert(!readQueueFull(1));
480 rdQLenPdf[readQueue.size() + respQueue.size()]++;
481
482 DPRINTF(DRAM, "Adding to read queue\n");
483
484 readQueue.push_back(dram_pkt);
485
486 // increment read entries of the rank
487 ++dram_pkt->rankRef.readEntries;
488
484 // Update stats
485 avgRdQLen = readQueue.size() + respQueue.size();
486 }
487
488 // Starting address of next dram pkt (aligend to burstSize boundary)
489 addr = (addr | (burstSize - 1)) + 1;
490 }
491
492 // If all packets are serviced by write queue, we send the repsonse back
493 if (pktsServicedByWrQ == pktCount) {
494 accessAndRespond(pkt, frontendLatency);
495 return;
496 }
497
498 // Update how many split packets are serviced by write queue
499 if (burst_helper != NULL)
500 burst_helper->burstsServiced = pktsServicedByWrQ;
501
502 // If we are not already scheduled to get a request out of the
503 // queue, do so now
504 if (!nextReqEvent.scheduled()) {
505 DPRINTF(DRAM, "Request scheduled immediately\n");
506 schedule(nextReqEvent, curTick());
507 }
508}
509
510void
511DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
512{
513 // only add to the write queue here. whenever the request is
514 // eventually done, set the readyTime, and call schedule()
515 assert(pkt->isWrite());
516
517 // if the request size is larger than burst size, the pkt is split into
518 // multiple DRAM packets
519 Addr addr = pkt->getAddr();
520 for (int cnt = 0; cnt < pktCount; ++cnt) {
521 unsigned size = std::min((addr | (burstSize - 1)) + 1,
522 pkt->getAddr() + pkt->getSize()) - addr;
523 writePktSize[ceilLog2(size)]++;
524 writeBursts++;
525
526 // see if we can merge with an existing item in the write
527 // queue and keep track of whether we have merged or not
528 bool merged = isInWriteQueue.find(burstAlign(addr)) !=
529 isInWriteQueue.end();
530
531 // if the item was not merged we need to create a new write
532 // and enqueue it
533 if (!merged) {
534 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
535
536 assert(writeQueue.size() < writeBufferSize);
537 wrQLenPdf[writeQueue.size()]++;
538
539 DPRINTF(DRAM, "Adding to write queue\n");
540
541 writeQueue.push_back(dram_pkt);
542 isInWriteQueue.insert(burstAlign(addr));
543 assert(writeQueue.size() == isInWriteQueue.size());
544
545 // Update stats
546 avgWrQLen = writeQueue.size();
489 // Update stats
490 avgRdQLen = readQueue.size() + respQueue.size();
491 }
492
493 // Starting address of next dram pkt (aligend to burstSize boundary)
494 addr = (addr | (burstSize - 1)) + 1;
495 }
496
497 // If all packets are serviced by write queue, we send the repsonse back
498 if (pktsServicedByWrQ == pktCount) {
499 accessAndRespond(pkt, frontendLatency);
500 return;
501 }
502
503 // Update how many split packets are serviced by write queue
504 if (burst_helper != NULL)
505 burst_helper->burstsServiced = pktsServicedByWrQ;
506
507 // If we are not already scheduled to get a request out of the
508 // queue, do so now
509 if (!nextReqEvent.scheduled()) {
510 DPRINTF(DRAM, "Request scheduled immediately\n");
511 schedule(nextReqEvent, curTick());
512 }
513}
514
515void
516DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
517{
518 // only add to the write queue here. whenever the request is
519 // eventually done, set the readyTime, and call schedule()
520 assert(pkt->isWrite());
521
522 // if the request size is larger than burst size, the pkt is split into
523 // multiple DRAM packets
524 Addr addr = pkt->getAddr();
525 for (int cnt = 0; cnt < pktCount; ++cnt) {
526 unsigned size = std::min((addr | (burstSize - 1)) + 1,
527 pkt->getAddr() + pkt->getSize()) - addr;
528 writePktSize[ceilLog2(size)]++;
529 writeBursts++;
530
531 // see if we can merge with an existing item in the write
532 // queue and keep track of whether we have merged or not
533 bool merged = isInWriteQueue.find(burstAlign(addr)) !=
534 isInWriteQueue.end();
535
536 // if the item was not merged we need to create a new write
537 // and enqueue it
538 if (!merged) {
539 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
540
541 assert(writeQueue.size() < writeBufferSize);
542 wrQLenPdf[writeQueue.size()]++;
543
544 DPRINTF(DRAM, "Adding to write queue\n");
545
546 writeQueue.push_back(dram_pkt);
547 isInWriteQueue.insert(burstAlign(addr));
548 assert(writeQueue.size() == isInWriteQueue.size());
549
550 // Update stats
551 avgWrQLen = writeQueue.size();
552
553 // increment write entries of the rank
554 ++dram_pkt->rankRef.writeEntries;
547 } else {
548 DPRINTF(DRAM, "Merging write burst with existing queue entry\n");
549
550 // keep track of the fact that this burst effectively
551 // disappeared as it was merged with an existing one
552 mergedWrBursts++;
553 }
554
555 // Starting address of next dram pkt (aligend to burstSize boundary)
556 addr = (addr | (burstSize - 1)) + 1;
557 }
558
559 // we do not wait for the writes to be send to the actual memory,
560 // but instead take responsibility for the consistency here and
561 // snoop the write queue for any upcoming reads
562 // @todo, if a pkt size is larger than burst size, we might need a
563 // different front end latency
564 accessAndRespond(pkt, frontendLatency);
565
566 // If we are not already scheduled to get a request out of the
567 // queue, do so now
568 if (!nextReqEvent.scheduled()) {
569 DPRINTF(DRAM, "Request scheduled immediately\n");
570 schedule(nextReqEvent, curTick());
571 }
572}
573
574void
575DRAMCtrl::printQs() const {
576 DPRINTF(DRAM, "===READ QUEUE===\n\n");
577 for (auto i = readQueue.begin() ; i != readQueue.end() ; ++i) {
578 DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
579 }
580 DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
581 for (auto i = respQueue.begin() ; i != respQueue.end() ; ++i) {
582 DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
583 }
584 DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
585 for (auto i = writeQueue.begin() ; i != writeQueue.end() ; ++i) {
586 DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
587 }
588}
589
590bool
591DRAMCtrl::recvTimingReq(PacketPtr pkt)
592{
593 // This is where we enter from the outside world
594 DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
595 pkt->cmdString(), pkt->getAddr(), pkt->getSize());
596
597 panic_if(pkt->cacheResponding(), "Should not see packets where cache "
598 "is responding");
599
600 panic_if(!(pkt->isRead() || pkt->isWrite()),
601 "Should only see read and writes at memory controller\n");
602
603 // Calc avg gap between requests
604 if (prevArrival != 0) {
605 totGap += curTick() - prevArrival;
606 }
607 prevArrival = curTick();
608
609
610 // Find out how many dram packets a pkt translates to
611 // If the burst size is equal or larger than the pkt size, then a pkt
612 // translates to only one dram packet. Otherwise, a pkt translates to
613 // multiple dram packets
614 unsigned size = pkt->getSize();
615 unsigned offset = pkt->getAddr() & (burstSize - 1);
616 unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
617
618 // check local buffers and do not accept if full
619 if (pkt->isRead()) {
620 assert(size != 0);
621 if (readQueueFull(dram_pkt_count)) {
622 DPRINTF(DRAM, "Read queue full, not accepting\n");
623 // remember that we have to retry this port
624 retryRdReq = true;
625 numRdRetry++;
626 return false;
627 } else {
628 addToReadQueue(pkt, dram_pkt_count);
629 readReqs++;
630 bytesReadSys += size;
631 }
632 } else {
633 assert(pkt->isWrite());
634 assert(size != 0);
635 if (writeQueueFull(dram_pkt_count)) {
636 DPRINTF(DRAM, "Write queue full, not accepting\n");
637 // remember that we have to retry this port
638 retryWrReq = true;
639 numWrRetry++;
640 return false;
641 } else {
642 addToWriteQueue(pkt, dram_pkt_count);
643 writeReqs++;
644 bytesWrittenSys += size;
645 }
646 }
647
648 return true;
649}
650
651void
652DRAMCtrl::processRespondEvent()
653{
654 DPRINTF(DRAM,
655 "processRespondEvent(): Some req has reached its readyTime\n");
656
657 DRAMPacket* dram_pkt = respQueue.front();
658
555 } else {
556 DPRINTF(DRAM, "Merging write burst with existing queue entry\n");
557
558 // keep track of the fact that this burst effectively
559 // disappeared as it was merged with an existing one
560 mergedWrBursts++;
561 }
562
563 // Starting address of next dram pkt (aligend to burstSize boundary)
564 addr = (addr | (burstSize - 1)) + 1;
565 }
566
567 // we do not wait for the writes to be send to the actual memory,
568 // but instead take responsibility for the consistency here and
569 // snoop the write queue for any upcoming reads
570 // @todo, if a pkt size is larger than burst size, we might need a
571 // different front end latency
572 accessAndRespond(pkt, frontendLatency);
573
574 // If we are not already scheduled to get a request out of the
575 // queue, do so now
576 if (!nextReqEvent.scheduled()) {
577 DPRINTF(DRAM, "Request scheduled immediately\n");
578 schedule(nextReqEvent, curTick());
579 }
580}
581
582void
583DRAMCtrl::printQs() const {
584 DPRINTF(DRAM, "===READ QUEUE===\n\n");
585 for (auto i = readQueue.begin() ; i != readQueue.end() ; ++i) {
586 DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
587 }
588 DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
589 for (auto i = respQueue.begin() ; i != respQueue.end() ; ++i) {
590 DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
591 }
592 DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
593 for (auto i = writeQueue.begin() ; i != writeQueue.end() ; ++i) {
594 DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
595 }
596}
597
598bool
599DRAMCtrl::recvTimingReq(PacketPtr pkt)
600{
601 // This is where we enter from the outside world
602 DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
603 pkt->cmdString(), pkt->getAddr(), pkt->getSize());
604
605 panic_if(pkt->cacheResponding(), "Should not see packets where cache "
606 "is responding");
607
608 panic_if(!(pkt->isRead() || pkt->isWrite()),
609 "Should only see read and writes at memory controller\n");
610
611 // Calc avg gap between requests
612 if (prevArrival != 0) {
613 totGap += curTick() - prevArrival;
614 }
615 prevArrival = curTick();
616
617
618 // Find out how many dram packets a pkt translates to
619 // If the burst size is equal or larger than the pkt size, then a pkt
620 // translates to only one dram packet. Otherwise, a pkt translates to
621 // multiple dram packets
622 unsigned size = pkt->getSize();
623 unsigned offset = pkt->getAddr() & (burstSize - 1);
624 unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
625
626 // check local buffers and do not accept if full
627 if (pkt->isRead()) {
628 assert(size != 0);
629 if (readQueueFull(dram_pkt_count)) {
630 DPRINTF(DRAM, "Read queue full, not accepting\n");
631 // remember that we have to retry this port
632 retryRdReq = true;
633 numRdRetry++;
634 return false;
635 } else {
636 addToReadQueue(pkt, dram_pkt_count);
637 readReqs++;
638 bytesReadSys += size;
639 }
640 } else {
641 assert(pkt->isWrite());
642 assert(size != 0);
643 if (writeQueueFull(dram_pkt_count)) {
644 DPRINTF(DRAM, "Write queue full, not accepting\n");
645 // remember that we have to retry this port
646 retryWrReq = true;
647 numWrRetry++;
648 return false;
649 } else {
650 addToWriteQueue(pkt, dram_pkt_count);
651 writeReqs++;
652 bytesWrittenSys += size;
653 }
654 }
655
656 return true;
657}
658
659void
660DRAMCtrl::processRespondEvent()
661{
662 DPRINTF(DRAM,
663 "processRespondEvent(): Some req has reached its readyTime\n");
664
665 DRAMPacket* dram_pkt = respQueue.front();
666
667 // if a read has reached its ready-time, decrement the number of reads
668 // At this point the packet has been handled and there is a possibility
669 // to switch to low-power mode if no other packet is available
670 --dram_pkt->rankRef.readEntries;
671 DPRINTF(DRAM, "number of read entries for rank %d is %d\n",
672 dram_pkt->rank, dram_pkt->rankRef.readEntries);
673
674 // counter should at least indicate one outstanding request
675 // for this read
676 assert(dram_pkt->rankRef.outstandingEvents > 0);
677 // read response received, decrement count
678 --dram_pkt->rankRef.outstandingEvents;
679
680 // at this moment should be either ACT or IDLE depending on
681 // if PRE has occurred to close all banks
682 assert((dram_pkt->rankRef.pwrState == PWR_ACT) ||
683 (dram_pkt->rankRef.pwrState == PWR_IDLE));
684
685 // track if this is the last packet before idling
686 // and that there are no outstanding commands to this rank
687 if (dram_pkt->rankRef.lowPowerEntryReady()) {
688 // verify that there are no events scheduled
689 assert(!dram_pkt->rankRef.activateEvent.scheduled());
690 assert(!dram_pkt->rankRef.prechargeEvent.scheduled());
691 assert(dram_pkt->rankRef.refreshState == REF_IDLE);
692
693 // if coming from active state, schedule power event to
694 // active power-down else go to precharge power-down
695 DPRINTF(DRAMState, "Rank %d sleep at tick %d; current power state is "
696 "%d\n", dram_pkt->rank, curTick(), dram_pkt->rankRef.pwrState);
697
698 // default to ACT power-down unless already in IDLE state
699 // could be in IDLE if PRE issued before data returned
700 PowerState next_pwr_state = PWR_ACT_PDN;
701 if (dram_pkt->rankRef.pwrState == PWR_IDLE) {
702 next_pwr_state = PWR_PRE_PDN;
703 }
704
705 dram_pkt->rankRef.powerDownSleep(next_pwr_state, curTick());
706 }
707
659 if (dram_pkt->burstHelper) {
660 // it is a split packet
661 dram_pkt->burstHelper->burstsServiced++;
662 if (dram_pkt->burstHelper->burstsServiced ==
663 dram_pkt->burstHelper->burstCount) {
664 // we have now serviced all children packets of a system packet
665 // so we can now respond to the requester
666 // @todo we probably want to have a different front end and back
667 // end latency for split packets
668 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
669 delete dram_pkt->burstHelper;
670 dram_pkt->burstHelper = NULL;
671 }
672 } else {
673 // it is not a split packet
674 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
675 }
676
677 delete respQueue.front();
678 respQueue.pop_front();
679
680 if (!respQueue.empty()) {
681 assert(respQueue.front()->readyTime >= curTick());
682 assert(!respondEvent.scheduled());
683 schedule(respondEvent, respQueue.front()->readyTime);
684 } else {
685 // if there is nothing left in any queue, signal a drain
686 if (drainState() == DrainState::Draining &&
687 writeQueue.empty() && readQueue.empty() && allRanksDrained()) {
688
689 DPRINTF(Drain, "DRAM controller done draining\n");
690 signalDrainDone();
691 }
692 }
693
694 // We have made a location in the queue available at this point,
695 // so if there is a read that was forced to wait, retry now
696 if (retryRdReq) {
697 retryRdReq = false;
698 port.sendRetryReq();
699 }
700}
701
702bool
703DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
704{
705 // This method does the arbitration between requests. The chosen
706 // packet is simply moved to the head of the queue. The other
707 // methods know that this is the place to look. For example, with
708 // FCFS, this method does nothing
709 assert(!queue.empty());
710
711 // bool to indicate if a packet to an available rank is found
712 bool found_packet = false;
713 if (queue.size() == 1) {
714 DRAMPacket* dram_pkt = queue.front();
715 // available rank corresponds to state refresh idle
716 if (ranks[dram_pkt->rank]->isAvailable()) {
717 found_packet = true;
718 DPRINTF(DRAM, "Single request, going to a free rank\n");
719 } else {
720 DPRINTF(DRAM, "Single request, going to a busy rank\n");
721 }
722 return found_packet;
723 }
724
725 if (memSchedPolicy == Enums::fcfs) {
726 // check if there is a packet going to a free rank
727 for (auto i = queue.begin(); i != queue.end() ; ++i) {
728 DRAMPacket* dram_pkt = *i;
729 if (ranks[dram_pkt->rank]->isAvailable()) {
730 queue.erase(i);
731 queue.push_front(dram_pkt);
732 found_packet = true;
733 break;
734 }
735 }
736 } else if (memSchedPolicy == Enums::frfcfs) {
737 found_packet = reorderQueue(queue, extra_col_delay);
738 } else
739 panic("No scheduling policy chosen\n");
740 return found_packet;
741}
742
743bool
744DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
745{
746 // Only determine this if needed
747 uint64_t earliest_banks = 0;
748 bool hidden_bank_prep = false;
749
750 // search for seamless row hits first, if no seamless row hit is
751 // found then determine if there are other packets that can be issued
752 // without incurring additional bus delay due to bank timing
753 // Will select closed rows first to enable more open row possibilies
754 // in future selections
755 bool found_hidden_bank = false;
756
757 // remember if we found a row hit, not seamless, but bank prepped
758 // and ready
759 bool found_prepped_pkt = false;
760
761 // if we have no row hit, prepped or not, and no seamless packet,
762 // just go for the earliest possible
763 bool found_earliest_pkt = false;
764
765 auto selected_pkt_it = queue.end();
766
767 // time we need to issue a column command to be seamless
768 const Tick min_col_at = std::max(busBusyUntil - tCL + extra_col_delay,
769 curTick());
770
771 for (auto i = queue.begin(); i != queue.end() ; ++i) {
772 DRAMPacket* dram_pkt = *i;
773 const Bank& bank = dram_pkt->bankRef;
774
775 // check if rank is available, if not, jump to the next packet
776 if (dram_pkt->rankRef.isAvailable()) {
777 // check if it is a row hit
778 if (bank.openRow == dram_pkt->row) {
779 // no additional rank-to-rank or same bank-group
780 // delays, or we switched read/write and might as well
781 // go for the row hit
782 if (bank.colAllowedAt <= min_col_at) {
783 // FCFS within the hits, giving priority to
784 // commands that can issue seamlessly, without
785 // additional delay, such as same rank accesses
786 // and/or different bank-group accesses
787 DPRINTF(DRAM, "Seamless row buffer hit\n");
788 selected_pkt_it = i;
789 // no need to look through the remaining queue entries
790 break;
791 } else if (!found_hidden_bank && !found_prepped_pkt) {
792 // if we did not find a packet to a closed row that can
793 // issue the bank commands without incurring delay, and
794 // did not yet find a packet to a prepped row, remember
795 // the current one
796 selected_pkt_it = i;
797 found_prepped_pkt = true;
798 DPRINTF(DRAM, "Prepped row buffer hit\n");
799 }
800 } else if (!found_earliest_pkt) {
801 // if we have not initialised the bank status, do it
802 // now, and only once per scheduling decisions
803 if (earliest_banks == 0) {
804 // determine entries with earliest bank delay
805 pair<uint64_t, bool> bankStatus =
806 minBankPrep(queue, min_col_at);
807 earliest_banks = bankStatus.first;
808 hidden_bank_prep = bankStatus.second;
809 }
810
811 // bank is amongst first available banks
812 // minBankPrep will give priority to packets that can
813 // issue seamlessly
814 if (bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
815 found_earliest_pkt = true;
816 found_hidden_bank = hidden_bank_prep;
817
818 // give priority to packets that can issue
819 // bank commands 'behind the scenes'
820 // any additional delay if any will be due to
821 // col-to-col command requirements
822 if (hidden_bank_prep || !found_prepped_pkt)
823 selected_pkt_it = i;
824 }
825 }
826 }
827 }
828
829 if (selected_pkt_it != queue.end()) {
830 DRAMPacket* selected_pkt = *selected_pkt_it;
831 queue.erase(selected_pkt_it);
832 queue.push_front(selected_pkt);
833 return true;
834 }
835
836 return false;
837}
838
839void
840DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
841{
842 DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
843
844 bool needsResponse = pkt->needsResponse();
845 // do the actual memory access which also turns the packet into a
846 // response
847 access(pkt);
848
849 // turn packet around to go back to requester if response expected
850 if (needsResponse) {
851 // access already turned the packet into a response
852 assert(pkt->isResponse());
853 // response_time consumes the static latency and is charged also
854 // with headerDelay that takes into account the delay provided by
855 // the xbar and also the payloadDelay that takes into account the
856 // number of data beats.
857 Tick response_time = curTick() + static_latency + pkt->headerDelay +
858 pkt->payloadDelay;
859 // Here we reset the timing of the packet before sending it out.
860 pkt->headerDelay = pkt->payloadDelay = 0;
861
862 // queue the packet in the response queue to be sent out after
863 // the static latency has passed
864 port.schedTimingResp(pkt, response_time, true);
865 } else {
866 // @todo the packet is going to be deleted, and the DRAMPacket
867 // is still having a pointer to it
868 pendingDelete.reset(pkt);
869 }
870
871 DPRINTF(DRAM, "Done\n");
872
873 return;
874}
875
876void
877DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref,
878 Tick act_tick, uint32_t row)
879{
880 assert(rank_ref.actTicks.size() == activationLimit);
881
882 DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
883
884 // update the open row
885 assert(bank_ref.openRow == Bank::NO_ROW);
886 bank_ref.openRow = row;
887
888 // start counting anew, this covers both the case when we
889 // auto-precharged, and when this access is forced to
890 // precharge
891 bank_ref.bytesAccessed = 0;
892 bank_ref.rowAccesses = 0;
893
894 ++rank_ref.numBanksActive;
895 assert(rank_ref.numBanksActive <= banksPerRank);
896
897 DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
898 bank_ref.bank, rank_ref.rank, act_tick,
899 ranks[rank_ref.rank]->numBanksActive);
900
901 rank_ref.cmdList.push_back(Command(MemCommand::ACT, bank_ref.bank,
902 act_tick));
903
904 DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) -
905 timeStampOffset, bank_ref.bank, rank_ref.rank);
906
907 // The next access has to respect tRAS for this bank
908 bank_ref.preAllowedAt = act_tick + tRAS;
909
910 // Respect the row-to-column command delay
911 bank_ref.colAllowedAt = std::max(act_tick + tRCD, bank_ref.colAllowedAt);
912
913 // start by enforcing tRRD
914 for (int i = 0; i < banksPerRank; i++) {
915 // next activate to any bank in this rank must not happen
916 // before tRRD
917 if (bankGroupArch && (bank_ref.bankgr == rank_ref.banks[i].bankgr)) {
918 // bank group architecture requires longer delays between
919 // ACT commands within the same bank group. Use tRRD_L
920 // in this case
921 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD_L,
922 rank_ref.banks[i].actAllowedAt);
923 } else {
924 // use shorter tRRD value when either
925 // 1) bank group architecture is not supportted
926 // 2) bank is in a different bank group
927 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD,
928 rank_ref.banks[i].actAllowedAt);
929 }
930 }
931
932 // next, we deal with tXAW, if the activation limit is disabled
933 // then we directly schedule an activate power event
934 if (!rank_ref.actTicks.empty()) {
935 // sanity check
936 if (rank_ref.actTicks.back() &&
937 (act_tick - rank_ref.actTicks.back()) < tXAW) {
938 panic("Got %d activates in window %d (%llu - %llu) which "
939 "is smaller than %llu\n", activationLimit, act_tick -
940 rank_ref.actTicks.back(), act_tick,
941 rank_ref.actTicks.back(), tXAW);
942 }
943
944 // shift the times used for the book keeping, the last element
945 // (highest index) is the oldest one and hence the lowest value
946 rank_ref.actTicks.pop_back();
947
948 // record an new activation (in the future)
949 rank_ref.actTicks.push_front(act_tick);
950
951 // cannot activate more than X times in time window tXAW, push the
952 // next one (the X + 1'st activate) to be tXAW away from the
953 // oldest in our window of X
954 if (rank_ref.actTicks.back() &&
955 (act_tick - rank_ref.actTicks.back()) < tXAW) {
956 DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate "
957 "no earlier than %llu\n", activationLimit,
958 rank_ref.actTicks.back() + tXAW);
959 for (int j = 0; j < banksPerRank; j++)
960 // next activate must not happen before end of window
961 rank_ref.banks[j].actAllowedAt =
962 std::max(rank_ref.actTicks.back() + tXAW,
963 rank_ref.banks[j].actAllowedAt);
964 }
965 }
966
967 // at the point when this activate takes place, make sure we
968 // transition to the active power state
969 if (!rank_ref.activateEvent.scheduled())
970 schedule(rank_ref.activateEvent, act_tick);
971 else if (rank_ref.activateEvent.when() > act_tick)
972 // move it sooner in time
973 reschedule(rank_ref.activateEvent, act_tick);
974}
975
976void
977DRAMCtrl::prechargeBank(Rank& rank_ref, Bank& bank, Tick pre_at, bool trace)
978{
979 // make sure the bank has an open row
980 assert(bank.openRow != Bank::NO_ROW);
981
982 // sample the bytes per activate here since we are closing
983 // the page
984 bytesPerActivate.sample(bank.bytesAccessed);
985
986 bank.openRow = Bank::NO_ROW;
987
988 // no precharge allowed before this one
989 bank.preAllowedAt = pre_at;
990
991 Tick pre_done_at = pre_at + tRP;
992
993 bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at);
994
995 assert(rank_ref.numBanksActive != 0);
996 --rank_ref.numBanksActive;
997
998 DPRINTF(DRAM, "Precharging bank %d, rank %d at tick %lld, now got "
999 "%d active\n", bank.bank, rank_ref.rank, pre_at,
1000 rank_ref.numBanksActive);
1001
1002 if (trace) {
1003
1004 rank_ref.cmdList.push_back(Command(MemCommand::PRE, bank.bank,
1005 pre_at));
1006 DPRINTF(DRAMPower, "%llu,PRE,%d,%d\n", divCeil(pre_at, tCK) -
1007 timeStampOffset, bank.bank, rank_ref.rank);
1008 }
1009 // if we look at the current number of active banks we might be
1010 // tempted to think the DRAM is now idle, however this can be
1011 // undone by an activate that is scheduled to happen before we
1012 // would have reached the idle state, so schedule an event and
1013 // rather check once we actually make it to the point in time when
1014 // the (last) precharge takes place
708 if (dram_pkt->burstHelper) {
709 // it is a split packet
710 dram_pkt->burstHelper->burstsServiced++;
711 if (dram_pkt->burstHelper->burstsServiced ==
712 dram_pkt->burstHelper->burstCount) {
713 // we have now serviced all children packets of a system packet
714 // so we can now respond to the requester
715 // @todo we probably want to have a different front end and back
716 // end latency for split packets
717 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
718 delete dram_pkt->burstHelper;
719 dram_pkt->burstHelper = NULL;
720 }
721 } else {
722 // it is not a split packet
723 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
724 }
725
726 delete respQueue.front();
727 respQueue.pop_front();
728
729 if (!respQueue.empty()) {
730 assert(respQueue.front()->readyTime >= curTick());
731 assert(!respondEvent.scheduled());
732 schedule(respondEvent, respQueue.front()->readyTime);
733 } else {
734 // if there is nothing left in any queue, signal a drain
735 if (drainState() == DrainState::Draining &&
736 writeQueue.empty() && readQueue.empty() && allRanksDrained()) {
737
738 DPRINTF(Drain, "DRAM controller done draining\n");
739 signalDrainDone();
740 }
741 }
742
743 // We have made a location in the queue available at this point,
744 // so if there is a read that was forced to wait, retry now
745 if (retryRdReq) {
746 retryRdReq = false;
747 port.sendRetryReq();
748 }
749}
750
751bool
752DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
753{
754 // This method does the arbitration between requests. The chosen
755 // packet is simply moved to the head of the queue. The other
756 // methods know that this is the place to look. For example, with
757 // FCFS, this method does nothing
758 assert(!queue.empty());
759
760 // bool to indicate if a packet to an available rank is found
761 bool found_packet = false;
762 if (queue.size() == 1) {
763 DRAMPacket* dram_pkt = queue.front();
764 // available rank corresponds to state refresh idle
765 if (ranks[dram_pkt->rank]->isAvailable()) {
766 found_packet = true;
767 DPRINTF(DRAM, "Single request, going to a free rank\n");
768 } else {
769 DPRINTF(DRAM, "Single request, going to a busy rank\n");
770 }
771 return found_packet;
772 }
773
774 if (memSchedPolicy == Enums::fcfs) {
775 // check if there is a packet going to a free rank
776 for (auto i = queue.begin(); i != queue.end() ; ++i) {
777 DRAMPacket* dram_pkt = *i;
778 if (ranks[dram_pkt->rank]->isAvailable()) {
779 queue.erase(i);
780 queue.push_front(dram_pkt);
781 found_packet = true;
782 break;
783 }
784 }
785 } else if (memSchedPolicy == Enums::frfcfs) {
786 found_packet = reorderQueue(queue, extra_col_delay);
787 } else
788 panic("No scheduling policy chosen\n");
789 return found_packet;
790}
791
792bool
793DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
794{
795 // Only determine this if needed
796 uint64_t earliest_banks = 0;
797 bool hidden_bank_prep = false;
798
799 // search for seamless row hits first, if no seamless row hit is
800 // found then determine if there are other packets that can be issued
801 // without incurring additional bus delay due to bank timing
802 // Will select closed rows first to enable more open row possibilies
803 // in future selections
804 bool found_hidden_bank = false;
805
806 // remember if we found a row hit, not seamless, but bank prepped
807 // and ready
808 bool found_prepped_pkt = false;
809
810 // if we have no row hit, prepped or not, and no seamless packet,
811 // just go for the earliest possible
812 bool found_earliest_pkt = false;
813
814 auto selected_pkt_it = queue.end();
815
816 // time we need to issue a column command to be seamless
817 const Tick min_col_at = std::max(busBusyUntil - tCL + extra_col_delay,
818 curTick());
819
820 for (auto i = queue.begin(); i != queue.end() ; ++i) {
821 DRAMPacket* dram_pkt = *i;
822 const Bank& bank = dram_pkt->bankRef;
823
824 // check if rank is available, if not, jump to the next packet
825 if (dram_pkt->rankRef.isAvailable()) {
826 // check if it is a row hit
827 if (bank.openRow == dram_pkt->row) {
828 // no additional rank-to-rank or same bank-group
829 // delays, or we switched read/write and might as well
830 // go for the row hit
831 if (bank.colAllowedAt <= min_col_at) {
832 // FCFS within the hits, giving priority to
833 // commands that can issue seamlessly, without
834 // additional delay, such as same rank accesses
835 // and/or different bank-group accesses
836 DPRINTF(DRAM, "Seamless row buffer hit\n");
837 selected_pkt_it = i;
838 // no need to look through the remaining queue entries
839 break;
840 } else if (!found_hidden_bank && !found_prepped_pkt) {
841 // if we did not find a packet to a closed row that can
842 // issue the bank commands without incurring delay, and
843 // did not yet find a packet to a prepped row, remember
844 // the current one
845 selected_pkt_it = i;
846 found_prepped_pkt = true;
847 DPRINTF(DRAM, "Prepped row buffer hit\n");
848 }
849 } else if (!found_earliest_pkt) {
850 // if we have not initialised the bank status, do it
851 // now, and only once per scheduling decisions
852 if (earliest_banks == 0) {
853 // determine entries with earliest bank delay
854 pair<uint64_t, bool> bankStatus =
855 minBankPrep(queue, min_col_at);
856 earliest_banks = bankStatus.first;
857 hidden_bank_prep = bankStatus.second;
858 }
859
860 // bank is amongst first available banks
861 // minBankPrep will give priority to packets that can
862 // issue seamlessly
863 if (bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
864 found_earliest_pkt = true;
865 found_hidden_bank = hidden_bank_prep;
866
867 // give priority to packets that can issue
868 // bank commands 'behind the scenes'
869 // any additional delay if any will be due to
870 // col-to-col command requirements
871 if (hidden_bank_prep || !found_prepped_pkt)
872 selected_pkt_it = i;
873 }
874 }
875 }
876 }
877
878 if (selected_pkt_it != queue.end()) {
879 DRAMPacket* selected_pkt = *selected_pkt_it;
880 queue.erase(selected_pkt_it);
881 queue.push_front(selected_pkt);
882 return true;
883 }
884
885 return false;
886}
887
888void
889DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
890{
891 DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
892
893 bool needsResponse = pkt->needsResponse();
894 // do the actual memory access which also turns the packet into a
895 // response
896 access(pkt);
897
898 // turn packet around to go back to requester if response expected
899 if (needsResponse) {
900 // access already turned the packet into a response
901 assert(pkt->isResponse());
902 // response_time consumes the static latency and is charged also
903 // with headerDelay that takes into account the delay provided by
904 // the xbar and also the payloadDelay that takes into account the
905 // number of data beats.
906 Tick response_time = curTick() + static_latency + pkt->headerDelay +
907 pkt->payloadDelay;
908 // Here we reset the timing of the packet before sending it out.
909 pkt->headerDelay = pkt->payloadDelay = 0;
910
911 // queue the packet in the response queue to be sent out after
912 // the static latency has passed
913 port.schedTimingResp(pkt, response_time, true);
914 } else {
915 // @todo the packet is going to be deleted, and the DRAMPacket
916 // is still having a pointer to it
917 pendingDelete.reset(pkt);
918 }
919
920 DPRINTF(DRAM, "Done\n");
921
922 return;
923}
924
925void
926DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref,
927 Tick act_tick, uint32_t row)
928{
929 assert(rank_ref.actTicks.size() == activationLimit);
930
931 DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
932
933 // update the open row
934 assert(bank_ref.openRow == Bank::NO_ROW);
935 bank_ref.openRow = row;
936
937 // start counting anew, this covers both the case when we
938 // auto-precharged, and when this access is forced to
939 // precharge
940 bank_ref.bytesAccessed = 0;
941 bank_ref.rowAccesses = 0;
942
943 ++rank_ref.numBanksActive;
944 assert(rank_ref.numBanksActive <= banksPerRank);
945
946 DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
947 bank_ref.bank, rank_ref.rank, act_tick,
948 ranks[rank_ref.rank]->numBanksActive);
949
950 rank_ref.cmdList.push_back(Command(MemCommand::ACT, bank_ref.bank,
951 act_tick));
952
953 DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) -
954 timeStampOffset, bank_ref.bank, rank_ref.rank);
955
956 // The next access has to respect tRAS for this bank
957 bank_ref.preAllowedAt = act_tick + tRAS;
958
959 // Respect the row-to-column command delay
960 bank_ref.colAllowedAt = std::max(act_tick + tRCD, bank_ref.colAllowedAt);
961
962 // start by enforcing tRRD
963 for (int i = 0; i < banksPerRank; i++) {
964 // next activate to any bank in this rank must not happen
965 // before tRRD
966 if (bankGroupArch && (bank_ref.bankgr == rank_ref.banks[i].bankgr)) {
967 // bank group architecture requires longer delays between
968 // ACT commands within the same bank group. Use tRRD_L
969 // in this case
970 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD_L,
971 rank_ref.banks[i].actAllowedAt);
972 } else {
973 // use shorter tRRD value when either
974 // 1) bank group architecture is not supportted
975 // 2) bank is in a different bank group
976 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD,
977 rank_ref.banks[i].actAllowedAt);
978 }
979 }
980
981 // next, we deal with tXAW, if the activation limit is disabled
982 // then we directly schedule an activate power event
983 if (!rank_ref.actTicks.empty()) {
984 // sanity check
985 if (rank_ref.actTicks.back() &&
986 (act_tick - rank_ref.actTicks.back()) < tXAW) {
987 panic("Got %d activates in window %d (%llu - %llu) which "
988 "is smaller than %llu\n", activationLimit, act_tick -
989 rank_ref.actTicks.back(), act_tick,
990 rank_ref.actTicks.back(), tXAW);
991 }
992
993 // shift the times used for the book keeping, the last element
994 // (highest index) is the oldest one and hence the lowest value
995 rank_ref.actTicks.pop_back();
996
997 // record an new activation (in the future)
998 rank_ref.actTicks.push_front(act_tick);
999
1000 // cannot activate more than X times in time window tXAW, push the
1001 // next one (the X + 1'st activate) to be tXAW away from the
1002 // oldest in our window of X
1003 if (rank_ref.actTicks.back() &&
1004 (act_tick - rank_ref.actTicks.back()) < tXAW) {
1005 DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate "
1006 "no earlier than %llu\n", activationLimit,
1007 rank_ref.actTicks.back() + tXAW);
1008 for (int j = 0; j < banksPerRank; j++)
1009 // next activate must not happen before end of window
1010 rank_ref.banks[j].actAllowedAt =
1011 std::max(rank_ref.actTicks.back() + tXAW,
1012 rank_ref.banks[j].actAllowedAt);
1013 }
1014 }
1015
1016 // at the point when this activate takes place, make sure we
1017 // transition to the active power state
1018 if (!rank_ref.activateEvent.scheduled())
1019 schedule(rank_ref.activateEvent, act_tick);
1020 else if (rank_ref.activateEvent.when() > act_tick)
1021 // move it sooner in time
1022 reschedule(rank_ref.activateEvent, act_tick);
1023}
1024
1025void
1026DRAMCtrl::prechargeBank(Rank& rank_ref, Bank& bank, Tick pre_at, bool trace)
1027{
1028 // make sure the bank has an open row
1029 assert(bank.openRow != Bank::NO_ROW);
1030
1031 // sample the bytes per activate here since we are closing
1032 // the page
1033 bytesPerActivate.sample(bank.bytesAccessed);
1034
1035 bank.openRow = Bank::NO_ROW;
1036
1037 // no precharge allowed before this one
1038 bank.preAllowedAt = pre_at;
1039
1040 Tick pre_done_at = pre_at + tRP;
1041
1042 bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at);
1043
1044 assert(rank_ref.numBanksActive != 0);
1045 --rank_ref.numBanksActive;
1046
1047 DPRINTF(DRAM, "Precharging bank %d, rank %d at tick %lld, now got "
1048 "%d active\n", bank.bank, rank_ref.rank, pre_at,
1049 rank_ref.numBanksActive);
1050
1051 if (trace) {
1052
1053 rank_ref.cmdList.push_back(Command(MemCommand::PRE, bank.bank,
1054 pre_at));
1055 DPRINTF(DRAMPower, "%llu,PRE,%d,%d\n", divCeil(pre_at, tCK) -
1056 timeStampOffset, bank.bank, rank_ref.rank);
1057 }
1058 // if we look at the current number of active banks we might be
1059 // tempted to think the DRAM is now idle, however this can be
1060 // undone by an activate that is scheduled to happen before we
1061 // would have reached the idle state, so schedule an event and
1062 // rather check once we actually make it to the point in time when
1063 // the (last) precharge takes place
1015 if (!rank_ref.prechargeEvent.scheduled())
1064 if (!rank_ref.prechargeEvent.scheduled()) {
1016 schedule(rank_ref.prechargeEvent, pre_done_at);
1065 schedule(rank_ref.prechargeEvent, pre_done_at);
1017 else if (rank_ref.prechargeEvent.when() < pre_done_at)
1066 // New event, increment count
1067 ++rank_ref.outstandingEvents;
1068 } else if (rank_ref.prechargeEvent.when() < pre_done_at) {
1018 reschedule(rank_ref.prechargeEvent, pre_done_at);
1069 reschedule(rank_ref.prechargeEvent, pre_done_at);
1070 }
1019}
1020
1021void
1022DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
1023{
1024 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1025 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1026
1027 // get the rank
1028 Rank& rank = dram_pkt->rankRef;
1029
1071}
1072
1073void
1074DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
1075{
1076 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1077 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1078
1079 // get the rank
1080 Rank& rank = dram_pkt->rankRef;
1081
1082 // are we in or transitioning to a low-power state and have not scheduled
1083 // a power-up event?
1084 // if so, wake up from power down to issue RD/WR burst
1085 if (rank.inLowPowerState) {
1086 assert(rank.pwrState != PWR_SREF);
1087 rank.scheduleWakeUpEvent(tXP);
1088 }
1089
1030 // get the bank
1031 Bank& bank = dram_pkt->bankRef;
1032
1033 // for the state we need to track if it is a row hit or not
1034 bool row_hit = true;
1035
1036 // respect any constraints on the command (e.g. tRCD or tCCD)
1037 Tick cmd_at = std::max(bank.colAllowedAt, curTick());
1038
1039 // Determine the access latency and update the bank state
1040 if (bank.openRow == dram_pkt->row) {
1041 // nothing to do
1042 } else {
1043 row_hit = false;
1044
1045 // If there is a page open, precharge it.
1046 if (bank.openRow != Bank::NO_ROW) {
1047 prechargeBank(rank, bank, std::max(bank.preAllowedAt, curTick()));
1048 }
1049
1050 // next we need to account for the delay in activating the
1051 // page
1052 Tick act_tick = std::max(bank.actAllowedAt, curTick());
1053
1054 // Record the activation and deal with all the global timing
1055 // constraints caused be a new activation (tRRD and tXAW)
1056 activateBank(rank, bank, act_tick, dram_pkt->row);
1057
1058 // issue the command as early as possible
1059 cmd_at = bank.colAllowedAt;
1060 }
1061
1062 // we need to wait until the bus is available before we can issue
1063 // the command
1064 cmd_at = std::max(cmd_at, busBusyUntil - tCL);
1065
1066 // update the packet ready time
1067 dram_pkt->readyTime = cmd_at + tCL + tBURST;
1068
1069 // only one burst can use the bus at any one point in time
1070 assert(dram_pkt->readyTime - busBusyUntil >= tBURST);
1071
1072 // update the time for the next read/write burst for each
1073 // bank (add a max with tCCD/tCCD_L here)
1074 Tick cmd_dly;
1075 for (int j = 0; j < ranksPerChannel; j++) {
1076 for (int i = 0; i < banksPerRank; i++) {
1077 // next burst to same bank group in this rank must not happen
1078 // before tCCD_L. Different bank group timing requirement is
1079 // tBURST; Add tCS for different ranks
1080 if (dram_pkt->rank == j) {
1081 if (bankGroupArch &&
1082 (bank.bankgr == ranks[j]->banks[i].bankgr)) {
1083 // bank group architecture requires longer delays between
1084 // RD/WR burst commands to the same bank group.
1085 // Use tCCD_L in this case
1086 cmd_dly = tCCD_L;
1087 } else {
1088 // use tBURST (equivalent to tCCD_S), the shorter
1089 // cas-to-cas delay value, when either:
1090 // 1) bank group architecture is not supportted
1091 // 2) bank is in a different bank group
1092 cmd_dly = tBURST;
1093 }
1094 } else {
1095 // different rank is by default in a different bank group
1096 // use tBURST (equivalent to tCCD_S), which is the shorter
1097 // cas-to-cas delay in this case
1098 // Add tCS to account for rank-to-rank bus delay requirements
1099 cmd_dly = tBURST + tCS;
1100 }
1101 ranks[j]->banks[i].colAllowedAt = std::max(cmd_at + cmd_dly,
1102 ranks[j]->banks[i].colAllowedAt);
1103 }
1104 }
1105
1106 // Save rank of current access
1107 activeRank = dram_pkt->rank;
1108
1109 // If this is a write, we also need to respect the write recovery
1110 // time before a precharge, in the case of a read, respect the
1111 // read to precharge constraint
1112 bank.preAllowedAt = std::max(bank.preAllowedAt,
1113 dram_pkt->isRead ? cmd_at + tRTP :
1114 dram_pkt->readyTime + tWR);
1115
1116 // increment the bytes accessed and the accesses per row
1117 bank.bytesAccessed += burstSize;
1118 ++bank.rowAccesses;
1119
1120 // if we reached the max, then issue with an auto-precharge
1121 bool auto_precharge = pageMgmt == Enums::close ||
1122 bank.rowAccesses == maxAccessesPerRow;
1123
1124 // if we did not hit the limit, we might still want to
1125 // auto-precharge
1126 if (!auto_precharge &&
1127 (pageMgmt == Enums::open_adaptive ||
1128 pageMgmt == Enums::close_adaptive)) {
1129 // a twist on the open and close page policies:
1130 // 1) open_adaptive page policy does not blindly keep the
1131 // page open, but close it if there are no row hits, and there
1132 // are bank conflicts in the queue
1133 // 2) close_adaptive page policy does not blindly close the
1134 // page, but closes it only if there are no row hits in the queue.
1135 // In this case, only force an auto precharge when there
1136 // are no same page hits in the queue
1137 bool got_more_hits = false;
1138 bool got_bank_conflict = false;
1139
1140 // either look at the read queue or write queue
1141 const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
1142 writeQueue;
1143 auto p = queue.begin();
1144 // make sure we are not considering the packet that we are
1145 // currently dealing with (which is the head of the queue)
1146 ++p;
1147
1148 // keep on looking until we find a hit or reach the end of the queue
1149 // 1) if a hit is found, then both open and close adaptive policies keep
1150 // the page open
1151 // 2) if no hit is found, got_bank_conflict is set to true if a bank
1152 // conflict request is waiting in the queue
1153 while (!got_more_hits && p != queue.end()) {
1154 bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
1155 (dram_pkt->bank == (*p)->bank);
1156 bool same_row = dram_pkt->row == (*p)->row;
1157 got_more_hits |= same_rank_bank && same_row;
1158 got_bank_conflict |= same_rank_bank && !same_row;
1159 ++p;
1160 }
1161
1162 // auto pre-charge when either
1163 // 1) open_adaptive policy, we have not got any more hits, and
1164 // have a bank conflict
1165 // 2) close_adaptive policy and we have not got any more hits
1166 auto_precharge = !got_more_hits &&
1167 (got_bank_conflict || pageMgmt == Enums::close_adaptive);
1168 }
1169
1170 // DRAMPower trace command to be written
1171 std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR";
1172
1173 // MemCommand required for DRAMPower library
1174 MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD :
1175 MemCommand::WR;
1176
1177 // Update bus state
1178 busBusyUntil = dram_pkt->readyTime;
1179
1180 DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n",
1181 dram_pkt->addr, dram_pkt->readyTime, busBusyUntil);
1182
1183 dram_pkt->rankRef.cmdList.push_back(Command(command, dram_pkt->bank,
1184 cmd_at));
1185
1186 DPRINTF(DRAMPower, "%llu,%s,%d,%d\n", divCeil(cmd_at, tCK) -
1187 timeStampOffset, mem_cmd, dram_pkt->bank, dram_pkt->rank);
1188
1189 // if this access should use auto-precharge, then we are
1190 // closing the row after the read/write burst
1191 if (auto_precharge) {
1192 // if auto-precharge push a PRE command at the correct tick to the
1193 // list used by DRAMPower library to calculate power
1194 prechargeBank(rank, bank, std::max(curTick(), bank.preAllowedAt));
1195
1196 DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId);
1197 }
1198
1199 // Update the minimum timing between the requests, this is a
1200 // conservative estimate of when we have to schedule the next
1201 // request to not introduce any unecessary bubbles. In most cases
1202 // we will wake up sooner than we have to.
1203 nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
1204
1205 // Update the stats and schedule the next request
1206 if (dram_pkt->isRead) {
1207 ++readsThisTime;
1208 if (row_hit)
1209 readRowHits++;
1210 bytesReadDRAM += burstSize;
1211 perBankRdBursts[dram_pkt->bankId]++;
1212
1213 // Update latency stats
1214 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1215 totBusLat += tBURST;
1216 totQLat += cmd_at - dram_pkt->entryTime;
1217 } else {
1218 ++writesThisTime;
1219 if (row_hit)
1220 writeRowHits++;
1221 bytesWritten += burstSize;
1222 perBankWrBursts[dram_pkt->bankId]++;
1223 }
1224}
1225
1226void
1227DRAMCtrl::processNextReqEvent()
1228{
1229 int busyRanks = 0;
1230 for (auto r : ranks) {
1231 if (!r->isAvailable()) {
1090 // get the bank
1091 Bank& bank = dram_pkt->bankRef;
1092
1093 // for the state we need to track if it is a row hit or not
1094 bool row_hit = true;
1095
1096 // respect any constraints on the command (e.g. tRCD or tCCD)
1097 Tick cmd_at = std::max(bank.colAllowedAt, curTick());
1098
1099 // Determine the access latency and update the bank state
1100 if (bank.openRow == dram_pkt->row) {
1101 // nothing to do
1102 } else {
1103 row_hit = false;
1104
1105 // If there is a page open, precharge it.
1106 if (bank.openRow != Bank::NO_ROW) {
1107 prechargeBank(rank, bank, std::max(bank.preAllowedAt, curTick()));
1108 }
1109
1110 // next we need to account for the delay in activating the
1111 // page
1112 Tick act_tick = std::max(bank.actAllowedAt, curTick());
1113
1114 // Record the activation and deal with all the global timing
1115 // constraints caused be a new activation (tRRD and tXAW)
1116 activateBank(rank, bank, act_tick, dram_pkt->row);
1117
1118 // issue the command as early as possible
1119 cmd_at = bank.colAllowedAt;
1120 }
1121
1122 // we need to wait until the bus is available before we can issue
1123 // the command
1124 cmd_at = std::max(cmd_at, busBusyUntil - tCL);
1125
1126 // update the packet ready time
1127 dram_pkt->readyTime = cmd_at + tCL + tBURST;
1128
1129 // only one burst can use the bus at any one point in time
1130 assert(dram_pkt->readyTime - busBusyUntil >= tBURST);
1131
1132 // update the time for the next read/write burst for each
1133 // bank (add a max with tCCD/tCCD_L here)
1134 Tick cmd_dly;
1135 for (int j = 0; j < ranksPerChannel; j++) {
1136 for (int i = 0; i < banksPerRank; i++) {
1137 // next burst to same bank group in this rank must not happen
1138 // before tCCD_L. Different bank group timing requirement is
1139 // tBURST; Add tCS for different ranks
1140 if (dram_pkt->rank == j) {
1141 if (bankGroupArch &&
1142 (bank.bankgr == ranks[j]->banks[i].bankgr)) {
1143 // bank group architecture requires longer delays between
1144 // RD/WR burst commands to the same bank group.
1145 // Use tCCD_L in this case
1146 cmd_dly = tCCD_L;
1147 } else {
1148 // use tBURST (equivalent to tCCD_S), the shorter
1149 // cas-to-cas delay value, when either:
1150 // 1) bank group architecture is not supportted
1151 // 2) bank is in a different bank group
1152 cmd_dly = tBURST;
1153 }
1154 } else {
1155 // different rank is by default in a different bank group
1156 // use tBURST (equivalent to tCCD_S), which is the shorter
1157 // cas-to-cas delay in this case
1158 // Add tCS to account for rank-to-rank bus delay requirements
1159 cmd_dly = tBURST + tCS;
1160 }
1161 ranks[j]->banks[i].colAllowedAt = std::max(cmd_at + cmd_dly,
1162 ranks[j]->banks[i].colAllowedAt);
1163 }
1164 }
1165
1166 // Save rank of current access
1167 activeRank = dram_pkt->rank;
1168
1169 // If this is a write, we also need to respect the write recovery
1170 // time before a precharge, in the case of a read, respect the
1171 // read to precharge constraint
1172 bank.preAllowedAt = std::max(bank.preAllowedAt,
1173 dram_pkt->isRead ? cmd_at + tRTP :
1174 dram_pkt->readyTime + tWR);
1175
1176 // increment the bytes accessed and the accesses per row
1177 bank.bytesAccessed += burstSize;
1178 ++bank.rowAccesses;
1179
1180 // if we reached the max, then issue with an auto-precharge
1181 bool auto_precharge = pageMgmt == Enums::close ||
1182 bank.rowAccesses == maxAccessesPerRow;
1183
1184 // if we did not hit the limit, we might still want to
1185 // auto-precharge
1186 if (!auto_precharge &&
1187 (pageMgmt == Enums::open_adaptive ||
1188 pageMgmt == Enums::close_adaptive)) {
1189 // a twist on the open and close page policies:
1190 // 1) open_adaptive page policy does not blindly keep the
1191 // page open, but close it if there are no row hits, and there
1192 // are bank conflicts in the queue
1193 // 2) close_adaptive page policy does not blindly close the
1194 // page, but closes it only if there are no row hits in the queue.
1195 // In this case, only force an auto precharge when there
1196 // are no same page hits in the queue
1197 bool got_more_hits = false;
1198 bool got_bank_conflict = false;
1199
1200 // either look at the read queue or write queue
1201 const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
1202 writeQueue;
1203 auto p = queue.begin();
1204 // make sure we are not considering the packet that we are
1205 // currently dealing with (which is the head of the queue)
1206 ++p;
1207
1208 // keep on looking until we find a hit or reach the end of the queue
1209 // 1) if a hit is found, then both open and close adaptive policies keep
1210 // the page open
1211 // 2) if no hit is found, got_bank_conflict is set to true if a bank
1212 // conflict request is waiting in the queue
1213 while (!got_more_hits && p != queue.end()) {
1214 bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
1215 (dram_pkt->bank == (*p)->bank);
1216 bool same_row = dram_pkt->row == (*p)->row;
1217 got_more_hits |= same_rank_bank && same_row;
1218 got_bank_conflict |= same_rank_bank && !same_row;
1219 ++p;
1220 }
1221
1222 // auto pre-charge when either
1223 // 1) open_adaptive policy, we have not got any more hits, and
1224 // have a bank conflict
1225 // 2) close_adaptive policy and we have not got any more hits
1226 auto_precharge = !got_more_hits &&
1227 (got_bank_conflict || pageMgmt == Enums::close_adaptive);
1228 }
1229
1230 // DRAMPower trace command to be written
1231 std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR";
1232
1233 // MemCommand required for DRAMPower library
1234 MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD :
1235 MemCommand::WR;
1236
1237 // Update bus state
1238 busBusyUntil = dram_pkt->readyTime;
1239
1240 DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n",
1241 dram_pkt->addr, dram_pkt->readyTime, busBusyUntil);
1242
1243 dram_pkt->rankRef.cmdList.push_back(Command(command, dram_pkt->bank,
1244 cmd_at));
1245
1246 DPRINTF(DRAMPower, "%llu,%s,%d,%d\n", divCeil(cmd_at, tCK) -
1247 timeStampOffset, mem_cmd, dram_pkt->bank, dram_pkt->rank);
1248
1249 // if this access should use auto-precharge, then we are
1250 // closing the row after the read/write burst
1251 if (auto_precharge) {
1252 // if auto-precharge push a PRE command at the correct tick to the
1253 // list used by DRAMPower library to calculate power
1254 prechargeBank(rank, bank, std::max(curTick(), bank.preAllowedAt));
1255
1256 DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId);
1257 }
1258
1259 // Update the minimum timing between the requests, this is a
1260 // conservative estimate of when we have to schedule the next
1261 // request to not introduce any unecessary bubbles. In most cases
1262 // we will wake up sooner than we have to.
1263 nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
1264
1265 // Update the stats and schedule the next request
1266 if (dram_pkt->isRead) {
1267 ++readsThisTime;
1268 if (row_hit)
1269 readRowHits++;
1270 bytesReadDRAM += burstSize;
1271 perBankRdBursts[dram_pkt->bankId]++;
1272
1273 // Update latency stats
1274 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1275 totBusLat += tBURST;
1276 totQLat += cmd_at - dram_pkt->entryTime;
1277 } else {
1278 ++writesThisTime;
1279 if (row_hit)
1280 writeRowHits++;
1281 bytesWritten += burstSize;
1282 perBankWrBursts[dram_pkt->bankId]++;
1283 }
1284}
1285
1286void
1287DRAMCtrl::processNextReqEvent()
1288{
1289 int busyRanks = 0;
1290 for (auto r : ranks) {
1291 if (!r->isAvailable()) {
1232 // rank is busy refreshing
1233 busyRanks++;
1292 if (r->pwrState != PWR_SREF) {
1293 // rank is busy refreshing
1294 DPRINTF(DRAMState, "Rank %d is not available\n", r->rank);
1295 busyRanks++;
1234
1296
1235 // let the rank know that if it was waiting to drain, it
1236 // is now done and ready to proceed
1237 r->checkDrainDone();
1297 // let the rank know that if it was waiting to drain, it
1298 // is now done and ready to proceed
1299 r->checkDrainDone();
1300 }
1301
1302 // check if we were in self-refresh and haven't started
1303 // to transition out
1304 if ((r->pwrState == PWR_SREF) && r->inLowPowerState) {
1305 DPRINTF(DRAMState, "Rank %d is in self-refresh\n", r->rank);
1306 // if we have commands queued to this rank and we don't have
1307 // a minimum number of active commands enqueued,
1308 // exit self-refresh
1309 if (r->forceSelfRefreshExit()) {
1310 DPRINTF(DRAMState, "rank %d was in self refresh and"
1311 " should wake up\n", r->rank);
1312 //wake up from self-refresh
1313 r->scheduleWakeUpEvent(tXS);
1314 // things are brought back into action once a refresh is
1315 // performed after self-refresh
1316 // continue with selection for other ranks
1317 }
1318 }
1238 }
1239 }
1240
1241 if (busyRanks == ranksPerChannel) {
1242 // if all ranks are refreshing wait for them to finish
1243 // and stall this state machine without taking any further
1244 // action, and do not schedule a new nextReqEvent
1245 return;
1246 }
1247
1319 }
1320 }
1321
1322 if (busyRanks == ranksPerChannel) {
1323 // if all ranks are refreshing wait for them to finish
1324 // and stall this state machine without taking any further
1325 // action, and do not schedule a new nextReqEvent
1326 return;
1327 }
1328
1248 // pre-emptively set to false. Overwrite if in READ_TO_WRITE
1249 // or WRITE_TO_READ state
1329 // pre-emptively set to false. Overwrite if in transitioning to
1330 // a new state
1250 bool switched_cmd_type = false;
1331 bool switched_cmd_type = false;
1251 if (busState == READ_TO_WRITE) {
1252 DPRINTF(DRAM, "Switching to writes after %d reads with %d reads "
1253 "waiting\n", readsThisTime, readQueue.size());
1332 if (busState != busStateNext) {
1333 if (busState == READ) {
1334 DPRINTF(DRAM, "Switching to writes after %d reads with %d reads "
1335 "waiting\n", readsThisTime, readQueue.size());
1254
1336
1255 // sample and reset the read-related stats as we are now
1256 // transitioning to writes, and all reads are done
1257 rdPerTurnAround.sample(readsThisTime);
1258 readsThisTime = 0;
1337 // sample and reset the read-related stats as we are now
1338 // transitioning to writes, and all reads are done
1339 rdPerTurnAround.sample(readsThisTime);
1340 readsThisTime = 0;
1259
1341
1260 // now proceed to do the actual writes
1261 busState = WRITE;
1262 switched_cmd_type = true;
1263 } else if (busState == WRITE_TO_READ) {
1264 DPRINTF(DRAM, "Switching to reads after %d writes with %d writes "
1265 "waiting\n", writesThisTime, writeQueue.size());
1342 // now proceed to do the actual writes
1343 switched_cmd_type = true;
1344 } else {
1345 DPRINTF(DRAM, "Switching to reads after %d writes with %d writes "
1346 "waiting\n", writesThisTime, writeQueue.size());
1266
1347
1267 wrPerTurnAround.sample(writesThisTime);
1268 writesThisTime = 0;
1348 wrPerTurnAround.sample(writesThisTime);
1349 writesThisTime = 0;
1269
1350
1270 busState = READ;
1271 switched_cmd_type = true;
1351 switched_cmd_type = true;
1352 }
1353 // update busState to match next state until next transition
1354 busState = busStateNext;
1272 }
1273
1274 // when we get here it is either a read or a write
1275 if (busState == READ) {
1276
1277 // track if we should switch or not
1278 bool switch_to_writes = false;
1279
1280 if (readQueue.empty()) {
1281 // In the case there is no read request to go next,
1282 // trigger writes if we have passed the low threshold (or
1283 // if we are draining)
1284 if (!writeQueue.empty() &&
1285 (drainState() == DrainState::Draining ||
1286 writeQueue.size() > writeLowThreshold)) {
1287
1288 switch_to_writes = true;
1289 } else {
1290 // check if we are drained
1291 // not done draining until in PWR_IDLE state
1292 // ensuring all banks are closed and
1293 // have exited low power states
1294 if (drainState() == DrainState::Draining &&
1295 respQueue.empty() && allRanksDrained()) {
1296
1297 DPRINTF(Drain, "DRAM controller done draining\n");
1298 signalDrainDone();
1299 }
1300
1301 // nothing to do, not even any point in scheduling an
1302 // event for the next request
1303 return;
1304 }
1305 } else {
1306 // bool to check if there is a read to a free rank
1307 bool found_read = false;
1308
1309 // Figure out which read request goes next, and move it to the
1310 // front of the read queue
1311 // If we are changing command type, incorporate the minimum
1312 // bus turnaround delay which will be tCS (different rank) case
1313 found_read = chooseNext(readQueue,
1314 switched_cmd_type ? tCS : 0);
1315
1316 // if no read to an available rank is found then return
1317 // at this point. There could be writes to the available ranks
1318 // which are above the required threshold. However, to
1319 // avoid adding more complexity to the code, return and wait
1320 // for a refresh event to kick things into action again.
1321 if (!found_read)
1322 return;
1323
1324 DRAMPacket* dram_pkt = readQueue.front();
1325 assert(dram_pkt->rankRef.isAvailable());
1355 }
1356
1357 // when we get here it is either a read or a write
1358 if (busState == READ) {
1359
1360 // track if we should switch or not
1361 bool switch_to_writes = false;
1362
1363 if (readQueue.empty()) {
1364 // In the case there is no read request to go next,
1365 // trigger writes if we have passed the low threshold (or
1366 // if we are draining)
1367 if (!writeQueue.empty() &&
1368 (drainState() == DrainState::Draining ||
1369 writeQueue.size() > writeLowThreshold)) {
1370
1371 switch_to_writes = true;
1372 } else {
1373 // check if we are drained
1374 // not done draining until in PWR_IDLE state
1375 // ensuring all banks are closed and
1376 // have exited low power states
1377 if (drainState() == DrainState::Draining &&
1378 respQueue.empty() && allRanksDrained()) {
1379
1380 DPRINTF(Drain, "DRAM controller done draining\n");
1381 signalDrainDone();
1382 }
1383
1384 // nothing to do, not even any point in scheduling an
1385 // event for the next request
1386 return;
1387 }
1388 } else {
1389 // bool to check if there is a read to a free rank
1390 bool found_read = false;
1391
1392 // Figure out which read request goes next, and move it to the
1393 // front of the read queue
1394 // If we are changing command type, incorporate the minimum
1395 // bus turnaround delay which will be tCS (different rank) case
1396 found_read = chooseNext(readQueue,
1397 switched_cmd_type ? tCS : 0);
1398
1399 // if no read to an available rank is found then return
1400 // at this point. There could be writes to the available ranks
1401 // which are above the required threshold. However, to
1402 // avoid adding more complexity to the code, return and wait
1403 // for a refresh event to kick things into action again.
1404 if (!found_read)
1405 return;
1406
1407 DRAMPacket* dram_pkt = readQueue.front();
1408 assert(dram_pkt->rankRef.isAvailable());
1409
1326 // here we get a bit creative and shift the bus busy time not
1327 // just the tWTR, but also a CAS latency to capture the fact
1328 // that we are allowed to prepare a new bank, but not issue a
1329 // read command until after tWTR, in essence we capture a
1330 // bubble on the data bus that is tWTR + tCL
1331 if (switched_cmd_type && dram_pkt->rank == activeRank) {
1332 busBusyUntil += tWTR + tCL;
1333 }
1334
1335 doDRAMAccess(dram_pkt);
1336
1337 // At this point we're done dealing with the request
1338 readQueue.pop_front();
1339
1410 // here we get a bit creative and shift the bus busy time not
1411 // just the tWTR, but also a CAS latency to capture the fact
1412 // that we are allowed to prepare a new bank, but not issue a
1413 // read command until after tWTR, in essence we capture a
1414 // bubble on the data bus that is tWTR + tCL
1415 if (switched_cmd_type && dram_pkt->rank == activeRank) {
1416 busBusyUntil += tWTR + tCL;
1417 }
1418
1419 doDRAMAccess(dram_pkt);
1420
1421 // At this point we're done dealing with the request
1422 readQueue.pop_front();
1423
1424 // Every respQueue which will generate an event, increment count
1425 ++dram_pkt->rankRef.outstandingEvents;
1426
1340 // sanity check
1341 assert(dram_pkt->size <= burstSize);
1342 assert(dram_pkt->readyTime >= curTick());
1343
1344 // Insert into response queue. It will be sent back to the
1345 // requestor at its readyTime
1346 if (respQueue.empty()) {
1347 assert(!respondEvent.scheduled());
1348 schedule(respondEvent, dram_pkt->readyTime);
1349 } else {
1350 assert(respQueue.back()->readyTime <= dram_pkt->readyTime);
1351 assert(respondEvent.scheduled());
1352 }
1353
1354 respQueue.push_back(dram_pkt);
1355
1356 // we have so many writes that we have to transition
1357 if (writeQueue.size() > writeHighThreshold) {
1358 switch_to_writes = true;
1359 }
1360 }
1361
1362 // switching to writes, either because the read queue is empty
1363 // and the writes have passed the low threshold (or we are
1364 // draining), or because the writes hit the hight threshold
1365 if (switch_to_writes) {
1366 // transition to writing
1427 // sanity check
1428 assert(dram_pkt->size <= burstSize);
1429 assert(dram_pkt->readyTime >= curTick());
1430
1431 // Insert into response queue. It will be sent back to the
1432 // requestor at its readyTime
1433 if (respQueue.empty()) {
1434 assert(!respondEvent.scheduled());
1435 schedule(respondEvent, dram_pkt->readyTime);
1436 } else {
1437 assert(respQueue.back()->readyTime <= dram_pkt->readyTime);
1438 assert(respondEvent.scheduled());
1439 }
1440
1441 respQueue.push_back(dram_pkt);
1442
1443 // we have so many writes that we have to transition
1444 if (writeQueue.size() > writeHighThreshold) {
1445 switch_to_writes = true;
1446 }
1447 }
1448
1449 // switching to writes, either because the read queue is empty
1450 // and the writes have passed the low threshold (or we are
1451 // draining), or because the writes hit the hight threshold
1452 if (switch_to_writes) {
1453 // transition to writing
1367 busState = READ_TO_WRITE;
1454 busStateNext = WRITE;
1368 }
1369 } else {
1370 // bool to check if write to free rank is found
1371 bool found_write = false;
1372
1373 // If we are changing command type, incorporate the minimum
1374 // bus turnaround delay
1375 found_write = chooseNext(writeQueue,
1376 switched_cmd_type ? std::min(tRTW, tCS) : 0);
1377
1378 // if no writes to an available rank are found then return.
1379 // There could be reads to the available ranks. However, to avoid
1380 // adding more complexity to the code, return at this point and wait
1381 // for a refresh event to kick things into action again.
1382 if (!found_write)
1383 return;
1384
1385 DRAMPacket* dram_pkt = writeQueue.front();
1386 assert(dram_pkt->rankRef.isAvailable());
1387 // sanity check
1388 assert(dram_pkt->size <= burstSize);
1389
1390 // add a bubble to the data bus, as defined by the
1391 // tRTW when access is to the same rank as previous burst
1392 // Different rank timing is handled with tCS, which is
1393 // applied to colAllowedAt
1394 if (switched_cmd_type && dram_pkt->rank == activeRank) {
1395 busBusyUntil += tRTW;
1396 }
1397
1398 doDRAMAccess(dram_pkt);
1399
1400 writeQueue.pop_front();
1455 }
1456 } else {
1457 // bool to check if write to free rank is found
1458 bool found_write = false;
1459
1460 // If we are changing command type, incorporate the minimum
1461 // bus turnaround delay
1462 found_write = chooseNext(writeQueue,
1463 switched_cmd_type ? std::min(tRTW, tCS) : 0);
1464
1465 // if no writes to an available rank are found then return.
1466 // There could be reads to the available ranks. However, to avoid
1467 // adding more complexity to the code, return at this point and wait
1468 // for a refresh event to kick things into action again.
1469 if (!found_write)
1470 return;
1471
1472 DRAMPacket* dram_pkt = writeQueue.front();
1473 assert(dram_pkt->rankRef.isAvailable());
1474 // sanity check
1475 assert(dram_pkt->size <= burstSize);
1476
1477 // add a bubble to the data bus, as defined by the
1478 // tRTW when access is to the same rank as previous burst
1479 // Different rank timing is handled with tCS, which is
1480 // applied to colAllowedAt
1481 if (switched_cmd_type && dram_pkt->rank == activeRank) {
1482 busBusyUntil += tRTW;
1483 }
1484
1485 doDRAMAccess(dram_pkt);
1486
1487 writeQueue.pop_front();
1488
1489 // removed write from queue, decrement count
1490 --dram_pkt->rankRef.writeEntries;
1491
1492 // Schedule write done event to decrement event count
1493 // after the readyTime has been reached
1494 // Only schedule latest write event to minimize events
1495 // required; only need to ensure that final event scheduled covers
1496 // the time that writes are outstanding and bus is active
1497 // to holdoff power-down entry events
1498 if (!dram_pkt->rankRef.writeDoneEvent.scheduled()) {
1499 schedule(dram_pkt->rankRef.writeDoneEvent, dram_pkt->readyTime);
1500 // New event, increment count
1501 ++dram_pkt->rankRef.outstandingEvents;
1502
1503 } else if (dram_pkt->rankRef.writeDoneEvent.when() <
1504 dram_pkt-> readyTime) {
1505 reschedule(dram_pkt->rankRef.writeDoneEvent, dram_pkt->readyTime);
1506 }
1507
1401 isInWriteQueue.erase(burstAlign(dram_pkt->addr));
1402 delete dram_pkt;
1403
1404 // If we emptied the write queue, or got sufficiently below the
1405 // threshold (using the minWritesPerSwitch as the hysteresis) and
1406 // are not draining, or we have reads waiting and have done enough
1407 // writes, then switch to reads.
1408 if (writeQueue.empty() ||
1409 (writeQueue.size() + minWritesPerSwitch < writeLowThreshold &&
1410 drainState() != DrainState::Draining) ||
1411 (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) {
1412 // turn the bus back around for reads again
1508 isInWriteQueue.erase(burstAlign(dram_pkt->addr));
1509 delete dram_pkt;
1510
1511 // If we emptied the write queue, or got sufficiently below the
1512 // threshold (using the minWritesPerSwitch as the hysteresis) and
1513 // are not draining, or we have reads waiting and have done enough
1514 // writes, then switch to reads.
1515 if (writeQueue.empty() ||
1516 (writeQueue.size() + minWritesPerSwitch < writeLowThreshold &&
1517 drainState() != DrainState::Draining) ||
1518 (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) {
1519 // turn the bus back around for reads again
1413 busState = WRITE_TO_READ;
1520 busStateNext = READ;
1414
1415 // note that the we switch back to reads also in the idle
1416 // case, which eventually will check for any draining and
1417 // also pause any further scheduling if there is really
1418 // nothing to do
1419 }
1420 }
1421 // It is possible that a refresh to another rank kicks things back into
1422 // action before reaching this point.
1423 if (!nextReqEvent.scheduled())
1424 schedule(nextReqEvent, std::max(nextReqTime, curTick()));
1425
1426 // If there is space available and we have writes waiting then let
1427 // them retry. This is done here to ensure that the retry does not
1428 // cause a nextReqEvent to be scheduled before we do so as part of
1429 // the next request processing
1430 if (retryWrReq && writeQueue.size() < writeBufferSize) {
1431 retryWrReq = false;
1432 port.sendRetryReq();
1433 }
1434}
1435
1436pair<uint64_t, bool>
1437DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
1438 Tick min_col_at) const
1439{
1440 uint64_t bank_mask = 0;
1441 Tick min_act_at = MaxTick;
1442
1443 // latest Tick for which ACT can occur without incurring additoinal
1444 // delay on the data bus
1445 const Tick hidden_act_max = std::max(min_col_at - tRCD, curTick());
1446
1447 // Flag condition when burst can issue back-to-back with previous burst
1448 bool found_seamless_bank = false;
1449
1450 // Flag condition when bank can be opened without incurring additional
1451 // delay on the data bus
1452 bool hidden_bank_prep = false;
1453
1454 // determine if we have queued transactions targetting the
1455 // bank in question
1456 vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
1457 for (const auto& p : queue) {
1458 if (p->rankRef.isAvailable())
1459 got_waiting[p->bankId] = true;
1460 }
1461
1462 // Find command with optimal bank timing
1463 // Will prioritize commands that can issue seamlessly.
1464 for (int i = 0; i < ranksPerChannel; i++) {
1465 for (int j = 0; j < banksPerRank; j++) {
1466 uint16_t bank_id = i * banksPerRank + j;
1467
1468 // if we have waiting requests for the bank, and it is
1469 // amongst the first available, update the mask
1470 if (got_waiting[bank_id]) {
1471 // make sure this rank is not currently refreshing.
1472 assert(ranks[i]->isAvailable());
1473 // simplistic approximation of when the bank can issue
1474 // an activate, ignoring any rank-to-rank switching
1475 // cost in this calculation
1476 Tick act_at = ranks[i]->banks[j].openRow == Bank::NO_ROW ?
1477 std::max(ranks[i]->banks[j].actAllowedAt, curTick()) :
1478 std::max(ranks[i]->banks[j].preAllowedAt, curTick()) + tRP;
1479
1480 // When is the earliest the R/W burst can issue?
1481 Tick col_at = std::max(ranks[i]->banks[j].colAllowedAt,
1482 act_at + tRCD);
1483
1484 // bank can issue burst back-to-back (seamlessly) with
1485 // previous burst
1486 bool new_seamless_bank = col_at <= min_col_at;
1487
1488 // if we found a new seamless bank or we have no
1489 // seamless banks, and got a bank with an earlier
1490 // activate time, it should be added to the bit mask
1491 if (new_seamless_bank ||
1492 (!found_seamless_bank && act_at <= min_act_at)) {
1493 // if we did not have a seamless bank before, and
1494 // we do now, reset the bank mask, also reset it
1495 // if we have not yet found a seamless bank and
1496 // the activate time is smaller than what we have
1497 // seen so far
1498 if (!found_seamless_bank &&
1499 (new_seamless_bank || act_at < min_act_at)) {
1500 bank_mask = 0;
1501 }
1502
1503 found_seamless_bank |= new_seamless_bank;
1504
1505 // ACT can occur 'behind the scenes'
1506 hidden_bank_prep = act_at <= hidden_act_max;
1507
1508 // set the bit corresponding to the available bank
1509 replaceBits(bank_mask, bank_id, bank_id, 1);
1510 min_act_at = act_at;
1511 }
1512 }
1513 }
1514 }
1515
1516 return make_pair(bank_mask, hidden_bank_prep);
1517}
1518
1519DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p)
1520 : EventManager(&_memory), memory(_memory),
1521
1522 // note that the we switch back to reads also in the idle
1523 // case, which eventually will check for any draining and
1524 // also pause any further scheduling if there is really
1525 // nothing to do
1526 }
1527 }
1528 // It is possible that a refresh to another rank kicks things back into
1529 // action before reaching this point.
1530 if (!nextReqEvent.scheduled())
1531 schedule(nextReqEvent, std::max(nextReqTime, curTick()));
1532
1533 // If there is space available and we have writes waiting then let
1534 // them retry. This is done here to ensure that the retry does not
1535 // cause a nextReqEvent to be scheduled before we do so as part of
1536 // the next request processing
1537 if (retryWrReq && writeQueue.size() < writeBufferSize) {
1538 retryWrReq = false;
1539 port.sendRetryReq();
1540 }
1541}
1542
1543pair<uint64_t, bool>
1544DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
1545 Tick min_col_at) const
1546{
1547 uint64_t bank_mask = 0;
1548 Tick min_act_at = MaxTick;
1549
1550 // latest Tick for which ACT can occur without incurring additoinal
1551 // delay on the data bus
1552 const Tick hidden_act_max = std::max(min_col_at - tRCD, curTick());
1553
1554 // Flag condition when burst can issue back-to-back with previous burst
1555 bool found_seamless_bank = false;
1556
1557 // Flag condition when bank can be opened without incurring additional
1558 // delay on the data bus
1559 bool hidden_bank_prep = false;
1560
1561 // determine if we have queued transactions targetting the
1562 // bank in question
1563 vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
1564 for (const auto& p : queue) {
1565 if (p->rankRef.isAvailable())
1566 got_waiting[p->bankId] = true;
1567 }
1568
1569 // Find command with optimal bank timing
1570 // Will prioritize commands that can issue seamlessly.
1571 for (int i = 0; i < ranksPerChannel; i++) {
1572 for (int j = 0; j < banksPerRank; j++) {
1573 uint16_t bank_id = i * banksPerRank + j;
1574
1575 // if we have waiting requests for the bank, and it is
1576 // amongst the first available, update the mask
1577 if (got_waiting[bank_id]) {
1578 // make sure this rank is not currently refreshing.
1579 assert(ranks[i]->isAvailable());
1580 // simplistic approximation of when the bank can issue
1581 // an activate, ignoring any rank-to-rank switching
1582 // cost in this calculation
1583 Tick act_at = ranks[i]->banks[j].openRow == Bank::NO_ROW ?
1584 std::max(ranks[i]->banks[j].actAllowedAt, curTick()) :
1585 std::max(ranks[i]->banks[j].preAllowedAt, curTick()) + tRP;
1586
1587 // When is the earliest the R/W burst can issue?
1588 Tick col_at = std::max(ranks[i]->banks[j].colAllowedAt,
1589 act_at + tRCD);
1590
1591 // bank can issue burst back-to-back (seamlessly) with
1592 // previous burst
1593 bool new_seamless_bank = col_at <= min_col_at;
1594
1595 // if we found a new seamless bank or we have no
1596 // seamless banks, and got a bank with an earlier
1597 // activate time, it should be added to the bit mask
1598 if (new_seamless_bank ||
1599 (!found_seamless_bank && act_at <= min_act_at)) {
1600 // if we did not have a seamless bank before, and
1601 // we do now, reset the bank mask, also reset it
1602 // if we have not yet found a seamless bank and
1603 // the activate time is smaller than what we have
1604 // seen so far
1605 if (!found_seamless_bank &&
1606 (new_seamless_bank || act_at < min_act_at)) {
1607 bank_mask = 0;
1608 }
1609
1610 found_seamless_bank |= new_seamless_bank;
1611
1612 // ACT can occur 'behind the scenes'
1613 hidden_bank_prep = act_at <= hidden_act_max;
1614
1615 // set the bit corresponding to the available bank
1616 replaceBits(bank_mask, bank_id, bank_id, 1);
1617 min_act_at = act_at;
1618 }
1619 }
1620 }
1621 }
1622
1623 return make_pair(bank_mask, hidden_bank_prep);
1624}
1625
1626DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p)
1627 : EventManager(&_memory), memory(_memory),
1521 pwrStateTrans(PWR_IDLE), pwrState(PWR_IDLE), pwrStateTick(0),
1522 refreshState(REF_IDLE), refreshDueAt(0),
1523 power(_p, false), numBanksActive(0),
1524 activateEvent(*this), prechargeEvent(*this),
1525 refreshEvent(*this), powerEvent(*this)
1628 pwrStateTrans(PWR_IDLE), pwrStatePostRefresh(PWR_IDLE),
1629 pwrStateTick(0), refreshDueAt(0), pwrState(PWR_IDLE),
1630 refreshState(REF_IDLE), inLowPowerState(false), rank(0),
1631 readEntries(0), writeEntries(0), outstandingEvents(0),
1632 wakeUpAllowedAt(0), power(_p, false), numBanksActive(0),
1633 writeDoneEvent(*this), activateEvent(*this), prechargeEvent(*this),
1634 refreshEvent(*this), powerEvent(*this), wakeUpEvent(*this)
1526{ }
1527
1528void
1529DRAMCtrl::Rank::startup(Tick ref_tick)
1530{
1531 assert(ref_tick > curTick());
1532
1533 pwrStateTick = curTick();
1534
1535 // kick off the refresh, and give ourselves enough time to
1536 // precharge
1537 schedule(refreshEvent, ref_tick);
1538}
1539
1540void
1541DRAMCtrl::Rank::suspend()
1542{
1543 deschedule(refreshEvent);
1544
1545 // Update the stats
1546 updatePowerStats();
1635{ }
1636
1637void
1638DRAMCtrl::Rank::startup(Tick ref_tick)
1639{
1640 assert(ref_tick > curTick());
1641
1642 pwrStateTick = curTick();
1643
1644 // kick off the refresh, and give ourselves enough time to
1645 // precharge
1646 schedule(refreshEvent, ref_tick);
1647}
1648
1649void
1650DRAMCtrl::Rank::suspend()
1651{
1652 deschedule(refreshEvent);
1653
1654 // Update the stats
1655 updatePowerStats();
1656
1657 // don't automatically transition back to LP state after next REF
1658 pwrStatePostRefresh = PWR_IDLE;
1547}
1548
1659}
1660
1661bool
1662DRAMCtrl::Rank::lowPowerEntryReady() const
1663{
1664 bool no_queued_cmds = ((memory.busStateNext == READ) && (readEntries == 0))
1665 || ((memory.busStateNext == WRITE) &&
1666 (writeEntries == 0));
1667
1668 if (refreshState == REF_RUN) {
1669 // have not decremented outstandingEvents for refresh command
1670 // still check if there are no commands queued to force PD
1671 // entry after refresh completes
1672 return no_queued_cmds;
1673 } else {
1674 // ensure no commands in Q and no commands scheduled
1675 return (no_queued_cmds && (outstandingEvents == 0));
1676 }
1677}
1678
1549void
1550DRAMCtrl::Rank::checkDrainDone()
1551{
1552 // if this rank was waiting to drain it is now able to proceed to
1553 // precharge
1554 if (refreshState == REF_DRAIN) {
1555 DPRINTF(DRAM, "Refresh drain done, now precharging\n");
1556
1679void
1680DRAMCtrl::Rank::checkDrainDone()
1681{
1682 // if this rank was waiting to drain it is now able to proceed to
1683 // precharge
1684 if (refreshState == REF_DRAIN) {
1685 DPRINTF(DRAM, "Refresh drain done, now precharging\n");
1686
1557 refreshState = REF_PRE;
1687 refreshState = REF_PD_EXIT;
1558
1559 // hand control back to the refresh event loop
1560 schedule(refreshEvent, curTick());
1561 }
1562}
1563
1564void
1565DRAMCtrl::Rank::flushCmdList()
1566{
1567 // at the moment sort the list of commands and update the counters
1568 // for DRAMPower libray when doing a refresh
1569 sort(cmdList.begin(), cmdList.end(), DRAMCtrl::sortTime);
1570
1571 auto next_iter = cmdList.begin();
1572 // push to commands to DRAMPower
1573 for ( ; next_iter != cmdList.end() ; ++next_iter) {
1574 Command cmd = *next_iter;
1575 if (cmd.timeStamp <= curTick()) {
1576 // Move all commands at or before curTick to DRAMPower
1577 power.powerlib.doCommand(cmd.type, cmd.bank,
1578 divCeil(cmd.timeStamp, memory.tCK) -
1579 memory.timeStampOffset);
1580 } else {
1581 // done - found all commands at or before curTick()
1582 // next_iter references the 1st command after curTick
1583 break;
1584 }
1585 }
1586 // reset cmdList to only contain commands after curTick
1587 // if there are no commands after curTick, updated cmdList will be empty
1588 // in this case, next_iter is cmdList.end()
1589 cmdList.assign(next_iter, cmdList.end());
1590}
1591
1592void
1593DRAMCtrl::Rank::processActivateEvent()
1594{
1595 // we should transition to the active state as soon as any bank is active
1596 if (pwrState != PWR_ACT)
1597 // note that at this point numBanksActive could be back at
1598 // zero again due to a precharge scheduled in the future
1599 schedulePowerEvent(PWR_ACT, curTick());
1600}
1601
1602void
1603DRAMCtrl::Rank::processPrechargeEvent()
1604{
1688
1689 // hand control back to the refresh event loop
1690 schedule(refreshEvent, curTick());
1691 }
1692}
1693
1694void
1695DRAMCtrl::Rank::flushCmdList()
1696{
1697 // at the moment sort the list of commands and update the counters
1698 // for DRAMPower libray when doing a refresh
1699 sort(cmdList.begin(), cmdList.end(), DRAMCtrl::sortTime);
1700
1701 auto next_iter = cmdList.begin();
1702 // push to commands to DRAMPower
1703 for ( ; next_iter != cmdList.end() ; ++next_iter) {
1704 Command cmd = *next_iter;
1705 if (cmd.timeStamp <= curTick()) {
1706 // Move all commands at or before curTick to DRAMPower
1707 power.powerlib.doCommand(cmd.type, cmd.bank,
1708 divCeil(cmd.timeStamp, memory.tCK) -
1709 memory.timeStampOffset);
1710 } else {
1711 // done - found all commands at or before curTick()
1712 // next_iter references the 1st command after curTick
1713 break;
1714 }
1715 }
1716 // reset cmdList to only contain commands after curTick
1717 // if there are no commands after curTick, updated cmdList will be empty
1718 // in this case, next_iter is cmdList.end()
1719 cmdList.assign(next_iter, cmdList.end());
1720}
1721
1722void
1723DRAMCtrl::Rank::processActivateEvent()
1724{
1725 // we should transition to the active state as soon as any bank is active
1726 if (pwrState != PWR_ACT)
1727 // note that at this point numBanksActive could be back at
1728 // zero again due to a precharge scheduled in the future
1729 schedulePowerEvent(PWR_ACT, curTick());
1730}
1731
1732void
1733DRAMCtrl::Rank::processPrechargeEvent()
1734{
1735 // counter should at least indicate one outstanding request
1736 // for this precharge
1737 assert(outstandingEvents > 0);
1738 // precharge complete, decrement count
1739 --outstandingEvents;
1740
1605 // if we reached zero, then special conditions apply as we track
1606 // if all banks are precharged for the power models
1607 if (numBanksActive == 0) {
1741 // if we reached zero, then special conditions apply as we track
1742 // if all banks are precharged for the power models
1743 if (numBanksActive == 0) {
1608 // we should transition to the idle state when the last bank
1609 // is precharged
1610 schedulePowerEvent(PWR_IDLE, curTick());
1744 // no reads to this rank in the Q and no pending
1745 // RD/WR or refresh commands
1746 if (lowPowerEntryReady()) {
1747 // should still be in ACT state since bank still open
1748 assert(pwrState == PWR_ACT);
1749
1750 // All banks closed - switch to precharge power down state.
1751 DPRINTF(DRAMState, "Rank %d sleep at tick %d\n",
1752 rank, curTick());
1753 powerDownSleep(PWR_PRE_PDN, curTick());
1754 } else {
1755 // we should transition to the idle state when the last bank
1756 // is precharged
1757 schedulePowerEvent(PWR_IDLE, curTick());
1758 }
1611 }
1612}
1613
1614void
1759 }
1760}
1761
1762void
1763DRAMCtrl::Rank::processWriteDoneEvent()
1764{
1765 // counter should at least indicate one outstanding request
1766 // for this write
1767 assert(outstandingEvents > 0);
1768 // Write transfer on bus has completed
1769 // decrement per rank counter
1770 --outstandingEvents;
1771}
1772
1773void
1615DRAMCtrl::Rank::processRefreshEvent()
1616{
1617 // when first preparing the refresh, remember when it was due
1774DRAMCtrl::Rank::processRefreshEvent()
1775{
1776 // when first preparing the refresh, remember when it was due
1618 if (refreshState == REF_IDLE) {
1777 if ((refreshState == REF_IDLE) || (refreshState == REF_SREF_EXIT)) {
1619 // remember when the refresh is due
1620 refreshDueAt = curTick();
1621
1622 // proceed to drain
1623 refreshState = REF_DRAIN;
1624
1778 // remember when the refresh is due
1779 refreshDueAt = curTick();
1780
1781 // proceed to drain
1782 refreshState = REF_DRAIN;
1783
1784 // make nonzero while refresh is pending to ensure
1785 // power down and self-refresh are not entered
1786 ++outstandingEvents;
1787
1625 DPRINTF(DRAM, "Refresh due\n");
1626 }
1627
1628 // let any scheduled read or write to the same rank go ahead,
1629 // after which it will
1630 // hand control back to this event loop
1631 if (refreshState == REF_DRAIN) {
1632 // if a request is at the moment being handled and this request is
1633 // accessing the current rank then wait for it to finish
1634 if ((rank == memory.activeRank)
1635 && (memory.nextReqEvent.scheduled())) {
1636 // hand control over to the request loop until it is
1637 // evaluated next
1638 DPRINTF(DRAM, "Refresh awaiting draining\n");
1639
1640 return;
1641 } else {
1788 DPRINTF(DRAM, "Refresh due\n");
1789 }
1790
1791 // let any scheduled read or write to the same rank go ahead,
1792 // after which it will
1793 // hand control back to this event loop
1794 if (refreshState == REF_DRAIN) {
1795 // if a request is at the moment being handled and this request is
1796 // accessing the current rank then wait for it to finish
1797 if ((rank == memory.activeRank)
1798 && (memory.nextReqEvent.scheduled())) {
1799 // hand control over to the request loop until it is
1800 // evaluated next
1801 DPRINTF(DRAM, "Refresh awaiting draining\n");
1802
1803 return;
1804 } else {
1805 refreshState = REF_PD_EXIT;
1806 }
1807 }
1808
1809 // at this point, ensure that rank is not in a power-down state
1810 if (refreshState == REF_PD_EXIT) {
1811 // if rank was sleeping and we have't started exit process,
1812 // wake-up for refresh
1813 if (inLowPowerState) {
1814 DPRINTF(DRAM, "Wake Up for refresh\n");
1815 // save state and return after refresh completes
1816 scheduleWakeUpEvent(memory.tXP);
1817 return;
1818 } else {
1642 refreshState = REF_PRE;
1643 }
1644 }
1645
1646 // at this point, ensure that all banks are precharged
1647 if (refreshState == REF_PRE) {
1819 refreshState = REF_PRE;
1820 }
1821 }
1822
1823 // at this point, ensure that all banks are precharged
1824 if (refreshState == REF_PRE) {
1648 // precharge any active bank if we are not already in the idle
1649 // state
1650 if (pwrState != PWR_IDLE) {
1825 // precharge any active bank
1826 if (numBanksActive != 0) {
1651 // at the moment, we use a precharge all even if there is
1652 // only a single bank open
1653 DPRINTF(DRAM, "Precharging all\n");
1654
1655 // first determine when we can precharge
1656 Tick pre_at = curTick();
1657
1658 for (auto &b : banks) {
1659 // respect both causality and any existing bank
1660 // constraints, some banks could already have a
1661 // (auto) precharge scheduled
1662 pre_at = std::max(b.preAllowedAt, pre_at);
1663 }
1664
1665 // make sure all banks per rank are precharged, and for those that
1666 // already are, update their availability
1667 Tick act_allowed_at = pre_at + memory.tRP;
1668
1669 for (auto &b : banks) {
1670 if (b.openRow != Bank::NO_ROW) {
1671 memory.prechargeBank(*this, b, pre_at, false);
1672 } else {
1673 b.actAllowedAt = std::max(b.actAllowedAt, act_allowed_at);
1674 b.preAllowedAt = std::max(b.preAllowedAt, pre_at);
1675 }
1676 }
1677
1678 // precharge all banks in rank
1679 cmdList.push_back(Command(MemCommand::PREA, 0, pre_at));
1680
1681 DPRINTF(DRAMPower, "%llu,PREA,0,%d\n",
1682 divCeil(pre_at, memory.tCK) -
1683 memory.timeStampOffset, rank);
1827 // at the moment, we use a precharge all even if there is
1828 // only a single bank open
1829 DPRINTF(DRAM, "Precharging all\n");
1830
1831 // first determine when we can precharge
1832 Tick pre_at = curTick();
1833
1834 for (auto &b : banks) {
1835 // respect both causality and any existing bank
1836 // constraints, some banks could already have a
1837 // (auto) precharge scheduled
1838 pre_at = std::max(b.preAllowedAt, pre_at);
1839 }
1840
1841 // make sure all banks per rank are precharged, and for those that
1842 // already are, update their availability
1843 Tick act_allowed_at = pre_at + memory.tRP;
1844
1845 for (auto &b : banks) {
1846 if (b.openRow != Bank::NO_ROW) {
1847 memory.prechargeBank(*this, b, pre_at, false);
1848 } else {
1849 b.actAllowedAt = std::max(b.actAllowedAt, act_allowed_at);
1850 b.preAllowedAt = std::max(b.preAllowedAt, pre_at);
1851 }
1852 }
1853
1854 // precharge all banks in rank
1855 cmdList.push_back(Command(MemCommand::PREA, 0, pre_at));
1856
1857 DPRINTF(DRAMPower, "%llu,PREA,0,%d\n",
1858 divCeil(pre_at, memory.tCK) -
1859 memory.timeStampOffset, rank);
1684 } else {
1860 } else if ((pwrState == PWR_IDLE) && (outstandingEvents == 1)) {
1861 // Banks are closed, have transitioned to IDLE state, and
1862 // no outstanding ACT,RD/WR,Auto-PRE sequence scheduled
1685 DPRINTF(DRAM, "All banks already precharged, starting refresh\n");
1686
1863 DPRINTF(DRAM, "All banks already precharged, starting refresh\n");
1864
1687 // go ahead and kick the power state machine into gear if
1865 // go ahead and kick the power state machine into gear since
1688 // we are already idle
1689 schedulePowerEvent(PWR_REF, curTick());
1866 // we are already idle
1867 schedulePowerEvent(PWR_REF, curTick());
1868 } else {
1869 // banks state is closed but haven't transitioned pwrState to IDLE
1870 // or have outstanding ACT,RD/WR,Auto-PRE sequence scheduled
1871 // should have outstanding precharge event in this case
1872 assert(prechargeEvent.scheduled());
1873 // will start refresh when pwrState transitions to IDLE
1690 }
1691
1874 }
1875
1692 refreshState = REF_RUN;
1693 assert(numBanksActive == 0);
1694
1695 // wait for all banks to be precharged, at which point the
1696 // power state machine will transition to the idle state, and
1697 // automatically move to a refresh, at that point it will also
1698 // call this method to get the refresh event loop going again
1699 return;
1700 }
1701
1702 // last but not least we perform the actual refresh
1876 assert(numBanksActive == 0);
1877
1878 // wait for all banks to be precharged, at which point the
1879 // power state machine will transition to the idle state, and
1880 // automatically move to a refresh, at that point it will also
1881 // call this method to get the refresh event loop going again
1882 return;
1883 }
1884
1885 // last but not least we perform the actual refresh
1703 if (refreshState == REF_RUN) {
1886 if (refreshState == REF_START) {
1704 // should never get here with any banks active
1705 assert(numBanksActive == 0);
1706 assert(pwrState == PWR_REF);
1707
1708 Tick ref_done_at = curTick() + memory.tRFC;
1709
1710 for (auto &b : banks) {
1711 b.actAllowedAt = ref_done_at;
1712 }
1713
1714 // at the moment this affects all ranks
1715 cmdList.push_back(Command(MemCommand::REF, 0, curTick()));
1716
1717 // Update the stats
1718 updatePowerStats();
1719
1720 DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), memory.tCK) -
1721 memory.timeStampOffset, rank);
1722
1887 // should never get here with any banks active
1888 assert(numBanksActive == 0);
1889 assert(pwrState == PWR_REF);
1890
1891 Tick ref_done_at = curTick() + memory.tRFC;
1892
1893 for (auto &b : banks) {
1894 b.actAllowedAt = ref_done_at;
1895 }
1896
1897 // at the moment this affects all ranks
1898 cmdList.push_back(Command(MemCommand::REF, 0, curTick()));
1899
1900 // Update the stats
1901 updatePowerStats();
1902
1903 DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), memory.tCK) -
1904 memory.timeStampOffset, rank);
1905
1906 // Update for next refresh
1907 refreshDueAt += memory.tREFI;
1908
1723 // make sure we did not wait so long that we cannot make up
1724 // for it
1909 // make sure we did not wait so long that we cannot make up
1910 // for it
1725 if (refreshDueAt + memory.tREFI < ref_done_at) {
1911 if (refreshDueAt < ref_done_at) {
1726 fatal("Refresh was delayed so long we cannot catch up\n");
1727 }
1728
1912 fatal("Refresh was delayed so long we cannot catch up\n");
1913 }
1914
1729 // compensate for the delay in actually performing the refresh
1730 // when scheduling the next one
1731 schedule(refreshEvent, refreshDueAt + memory.tREFI - memory.tRP);
1915 // Run the refresh and schedule event to transition power states
1916 // when refresh completes
1917 refreshState = REF_RUN;
1918 schedule(refreshEvent, ref_done_at);
1919 return;
1920 }
1732
1921
1922 if (refreshState == REF_RUN) {
1923 // should never get here with any banks active
1924 assert(numBanksActive == 0);
1925 assert(pwrState == PWR_REF);
1926
1733 assert(!powerEvent.scheduled());
1734
1927 assert(!powerEvent.scheduled());
1928
1735 // move to the idle power state once the refresh is done, this
1736 // will also move the refresh state machine to the refresh
1737 // idle state
1738 schedulePowerEvent(PWR_IDLE, ref_done_at);
1929 if ((memory.drainState() == DrainState::Draining) ||
1930 (memory.drainState() == DrainState::Drained)) {
1931 // if draining, do not re-enter low-power mode.
1932 // simply go to IDLE and wait
1933 schedulePowerEvent(PWR_IDLE, curTick());
1934 } else {
1935 // At the moment, we sleep when the refresh ends and wait to be
1936 // woken up again if previously in a low-power state.
1937 if (pwrStatePostRefresh != PWR_IDLE) {
1938 // power State should be power Refresh
1939 assert(pwrState == PWR_REF);
1940 DPRINTF(DRAMState, "Rank %d sleeping after refresh and was in "
1941 "power state %d before refreshing\n", rank,
1942 pwrStatePostRefresh);
1943 powerDownSleep(pwrState, curTick());
1739
1944
1740 DPRINTF(DRAMState, "Refresh done at %llu and next refresh at %llu\n",
1741 ref_done_at, refreshDueAt + memory.tREFI);
1945 // Force PRE power-down if there are no outstanding commands
1946 // in Q after refresh.
1947 } else if (lowPowerEntryReady()) {
1948 DPRINTF(DRAMState, "Rank %d sleeping after refresh but was NOT"
1949 " in a low power state before refreshing\n", rank);
1950 powerDownSleep(PWR_PRE_PDN, curTick());
1951
1952 } else {
1953 // move to the idle power state once the refresh is done, this
1954 // will also move the refresh state machine to the refresh
1955 // idle state
1956 schedulePowerEvent(PWR_IDLE, curTick());
1957 }
1958 }
1959
1960 // if transitioning to self refresh do not schedule a new refresh;
1961 // when waking from self refresh, a refresh is scheduled again.
1962 if (pwrStateTrans != PWR_SREF) {
1963 // compensate for the delay in actually performing the refresh
1964 // when scheduling the next one
1965 schedule(refreshEvent, refreshDueAt - memory.tRP);
1966
1967 DPRINTF(DRAMState, "Refresh done at %llu and next refresh"
1968 " at %llu\n", curTick(), refreshDueAt);
1969 }
1742 }
1743}
1744
1745void
1746DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state, Tick tick)
1747{
1748 // respect causality
1749 assert(tick >= curTick());
1750
1751 if (!powerEvent.scheduled()) {
1752 DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n",
1753 tick, pwr_state);
1754
1755 // insert the new transition
1756 pwrStateTrans = pwr_state;
1757
1758 schedule(powerEvent, tick);
1759 } else {
1760 panic("Scheduled power event at %llu to state %d, "
1761 "with scheduled event at %llu to %d\n", tick, pwr_state,
1762 powerEvent.when(), pwrStateTrans);
1763 }
1764}
1765
1766void
1970 }
1971}
1972
1973void
1974DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state, Tick tick)
1975{
1976 // respect causality
1977 assert(tick >= curTick());
1978
1979 if (!powerEvent.scheduled()) {
1980 DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n",
1981 tick, pwr_state);
1982
1983 // insert the new transition
1984 pwrStateTrans = pwr_state;
1985
1986 schedule(powerEvent, tick);
1987 } else {
1988 panic("Scheduled power event at %llu to state %d, "
1989 "with scheduled event at %llu to %d\n", tick, pwr_state,
1990 powerEvent.when(), pwrStateTrans);
1991 }
1992}
1993
1994void
1995DRAMCtrl::Rank::powerDownSleep(PowerState pwr_state, Tick tick)
1996{
1997 // if low power state is active low, schedule to active low power state.
1998 // in reality tCKE is needed to enter active low power. This is neglected
1999 // here and could be added in the future.
2000 if (pwr_state == PWR_ACT_PDN) {
2001 schedulePowerEvent(pwr_state, tick);
2002 // push command to DRAMPower
2003 cmdList.push_back(Command(MemCommand::PDN_F_ACT, 0, tick));
2004 DPRINTF(DRAMPower, "%llu,PDN_F_ACT,0,%d\n", divCeil(tick,
2005 memory.tCK) - memory.timeStampOffset, rank);
2006 } else if (pwr_state == PWR_PRE_PDN) {
2007 // if low power state is precharge low, schedule to precharge low
2008 // power state. In reality tCKE is needed to enter active low power.
2009 // This is neglected here.
2010 schedulePowerEvent(pwr_state, tick);
2011 //push Command to DRAMPower
2012 cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick));
2013 DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick,
2014 memory.tCK) - memory.timeStampOffset, rank);
2015 } else if (pwr_state == PWR_REF) {
2016 // if a refresh just occured
2017 // transition to PRE_PDN now that all banks are closed
2018 // do not transition to SREF if commands are in Q; stay in PRE_PDN
2019 if (pwrStatePostRefresh == PWR_ACT_PDN || !lowPowerEntryReady()) {
2020 // prechage power down requires tCKE to enter. For simplicity
2021 // this is not considered.
2022 schedulePowerEvent(PWR_PRE_PDN, tick);
2023 //push Command to DRAMPower
2024 cmdList.push_back(Command(MemCommand::PDN_F_PRE, 0, tick));
2025 DPRINTF(DRAMPower, "%llu,PDN_F_PRE,0,%d\n", divCeil(tick,
2026 memory.tCK) - memory.timeStampOffset, rank);
2027 } else {
2028 // last low power State was power precharge
2029 assert(pwrStatePostRefresh == PWR_PRE_PDN);
2030 // self refresh requires time tCKESR to enter. For simplicity,
2031 // this is not considered.
2032 schedulePowerEvent(PWR_SREF, tick);
2033 // push Command to DRAMPower
2034 cmdList.push_back(Command(MemCommand::SREN, 0, tick));
2035 DPRINTF(DRAMPower, "%llu,SREN,0,%d\n", divCeil(tick,
2036 memory.tCK) - memory.timeStampOffset, rank);
2037 }
2038 }
2039 // Ensure that we don't power-down and back up in same tick
2040 // Once we commit to PD entry, do it and wait for at least 1tCK
2041 // This could be replaced with tCKE if/when that is added to the model
2042 wakeUpAllowedAt = tick + memory.tCK;
2043
2044 // Transitioning to a low power state, set flag
2045 inLowPowerState = true;
2046}
2047
2048void
2049DRAMCtrl::Rank::scheduleWakeUpEvent(Tick exit_delay)
2050{
2051 Tick wake_up_tick = std::max(curTick(), wakeUpAllowedAt);
2052
2053 DPRINTF(DRAMState, "Scheduling wake-up for rank %d at tick %d\n",
2054 rank, wake_up_tick);
2055
2056 // if waking for refresh, hold previous state
2057 // else reset state back to IDLE
2058 if (refreshState == REF_PD_EXIT) {
2059 pwrStatePostRefresh = pwrState;
2060 } else {
2061 // don't automatically transition back to LP state after next REF
2062 pwrStatePostRefresh = PWR_IDLE;
2063 }
2064
2065 // schedule wake-up with event to ensure entry has completed before
2066 // we try to wake-up
2067 schedule(wakeUpEvent, wake_up_tick);
2068
2069 for (auto &b : banks) {
2070 // respect both causality and any existing bank
2071 // constraints, some banks could already have a
2072 // (auto) precharge scheduled
2073 b.colAllowedAt = std::max(wake_up_tick + exit_delay, b.colAllowedAt);
2074 b.preAllowedAt = std::max(wake_up_tick + exit_delay, b.preAllowedAt);
2075 b.actAllowedAt = std::max(wake_up_tick + exit_delay, b.actAllowedAt);
2076 }
2077 // Transitioning out of low power state, clear flag
2078 inLowPowerState = false;
2079
2080 // push to DRAMPower
2081 // use pwrStateTrans for cases where we have a power event scheduled
2082 // to enter low power that has not yet been processed
2083 if (pwrStateTrans == PWR_ACT_PDN) {
2084 cmdList.push_back(Command(MemCommand::PUP_ACT, 0, wake_up_tick));
2085 DPRINTF(DRAMPower, "%llu,PUP_ACT,0,%d\n", divCeil(wake_up_tick,
2086 memory.tCK) - memory.timeStampOffset, rank);
2087
2088 } else if (pwrStateTrans == PWR_PRE_PDN) {
2089 cmdList.push_back(Command(MemCommand::PUP_PRE, 0, wake_up_tick));
2090 DPRINTF(DRAMPower, "%llu,PUP_PRE,0,%d\n", divCeil(wake_up_tick,
2091 memory.tCK) - memory.timeStampOffset, rank);
2092 } else if (pwrStateTrans == PWR_SREF) {
2093 cmdList.push_back(Command(MemCommand::SREX, 0, wake_up_tick));
2094 DPRINTF(DRAMPower, "%llu,SREX,0,%d\n", divCeil(wake_up_tick,
2095 memory.tCK) - memory.timeStampOffset, rank);
2096 }
2097}
2098
2099void
2100DRAMCtrl::Rank::processWakeUpEvent()
2101{
2102 // Should be in a power-down or self-refresh state
2103 assert((pwrState == PWR_ACT_PDN) || (pwrState == PWR_PRE_PDN) ||
2104 (pwrState == PWR_SREF));
2105
2106 // Check current state to determine transition state
2107 if (pwrState == PWR_ACT_PDN) {
2108 // banks still open, transition to PWR_ACT
2109 schedulePowerEvent(PWR_ACT, curTick());
2110 } else {
2111 // transitioning from a precharge power-down or self-refresh state
2112 // banks are closed - transition to PWR_IDLE
2113 schedulePowerEvent(PWR_IDLE, curTick());
2114 }
2115}
2116
2117void
1767DRAMCtrl::Rank::processPowerEvent()
1768{
2118DRAMCtrl::Rank::processPowerEvent()
2119{
2120 assert(curTick() >= pwrStateTick);
1769 // remember where we were, and for how long
1770 Tick duration = curTick() - pwrStateTick;
1771 PowerState prev_state = pwrState;
1772
1773 // update the accounting
1774 pwrStateTime[prev_state] += duration;
1775
2121 // remember where we were, and for how long
2122 Tick duration = curTick() - pwrStateTick;
2123 PowerState prev_state = pwrState;
2124
2125 // update the accounting
2126 pwrStateTime[prev_state] += duration;
2127
2128 // track to total idle time
2129 if ((prev_state == PWR_PRE_PDN) || (prev_state == PWR_ACT_PDN) ||
2130 (prev_state == PWR_SREF)) {
2131 totalIdleTime += duration;
2132 }
2133
1776 pwrState = pwrStateTrans;
1777 pwrStateTick = curTick();
1778
2134 pwrState = pwrStateTrans;
2135 pwrStateTick = curTick();
2136
1779 if (pwrState == PWR_IDLE) {
1780 DPRINTF(DRAMState, "All banks precharged\n");
2137 // if rank was refreshing, make sure to start scheduling requests again
2138 if (prev_state == PWR_REF) {
2139 // bus IDLED prior to REF
2140 // counter should be one for refresh command only
2141 assert(outstandingEvents == 1);
2142 // REF complete, decrement count
2143 --outstandingEvents;
1781
2144
1782 // if we were refreshing, make sure we start scheduling requests again
1783 if (prev_state == PWR_REF) {
1784 DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration);
1785 assert(pwrState == PWR_IDLE);
1786
1787 // kick things into action again
2145 DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration);
2146 // if sleeping after refresh
2147 if (pwrState != PWR_IDLE) {
2148 assert((pwrState == PWR_PRE_PDN) || (pwrState == PWR_SREF));
2149 DPRINTF(DRAMState, "Switching to power down state after refreshing"
2150 " rank %d at %llu tick\n", rank, curTick());
2151 }
2152 if (pwrState != PWR_SREF) {
2153 // rank is not available in SREF
2154 // don't transition to IDLE in this case
1788 refreshState = REF_IDLE;
2155 refreshState = REF_IDLE;
1789 // a request event could be already scheduled by the state
1790 // machine of the other rank
1791 if (!memory.nextReqEvent.scheduled())
1792 schedule(memory.nextReqEvent, curTick());
1793 } else {
1794 assert(prev_state == PWR_ACT);
2156 }
2157 // a request event could be already scheduled by the state
2158 // machine of the other rank
2159 if (!memory.nextReqEvent.scheduled()) {
2160 DPRINTF(DRAM, "Scheduling next request after refreshing rank %d\n",
2161 rank);
2162 schedule(memory.nextReqEvent, curTick());
2163 }
2164 } else if (pwrState == PWR_ACT) {
2165 if (refreshState == REF_PD_EXIT) {
2166 // kick the refresh event loop into action again
2167 assert(prev_state == PWR_ACT_PDN);
1795
2168
2169 // go back to REF event and close banks
2170 refreshState = REF_PRE;
2171 schedule(refreshEvent, curTick());
2172 }
2173 } else if (pwrState == PWR_IDLE) {
2174 DPRINTF(DRAMState, "All banks precharged\n");
2175 if (prev_state == PWR_SREF) {
2176 // set refresh state to REF_SREF_EXIT, ensuring isAvailable
2177 // continues to return false during tXS after SREF exit
2178 // Schedule a refresh which kicks things back into action
2179 // when it finishes
2180 refreshState = REF_SREF_EXIT;
2181 schedule(refreshEvent, curTick() + memory.tXS);
2182 } else {
1796 // if we have a pending refresh, and are now moving to
2183 // if we have a pending refresh, and are now moving to
1797 // the idle state, direclty transition to a refresh
1798 if (refreshState == REF_RUN) {
1799 // there should be nothing waiting at this point
1800 assert(!powerEvent.scheduled());
1801
1802 // update the state in zero time and proceed below
1803 pwrState = PWR_REF;
2184 // the idle state, directly transition to a refresh
2185 if ((refreshState == REF_PRE) || (refreshState == REF_PD_EXIT)) {
2186 // ensure refresh is restarted only after final PRE command.
2187 // do not restart refresh if controller is in an intermediate
2188 // state, after PRE_PDN exit, when banks are IDLE but an
2189 // ACT is scheduled.
2190 if (!activateEvent.scheduled()) {
2191 // there should be nothing waiting at this point
2192 assert(!powerEvent.scheduled());
2193 // update the state in zero time and proceed below
2194 pwrState = PWR_REF;
2195 } else {
2196 // must have PRE scheduled to transition back to IDLE
2197 // and re-kick off refresh
2198 assert(prechargeEvent.scheduled());
2199 }
1804 }
2200 }
1805 }
2201 }
1806 }
1807
1808 // we transition to the refresh state, let the refresh state
1809 // machine know of this state update and let it deal with the
1810 // scheduling of the next power state transition as well as the
1811 // following refresh
1812 if (pwrState == PWR_REF) {
2202 }
2203
2204 // we transition to the refresh state, let the refresh state
2205 // machine know of this state update and let it deal with the
2206 // scheduling of the next power state transition as well as the
2207 // following refresh
2208 if (pwrState == PWR_REF) {
2209 assert(refreshState == REF_PRE || refreshState == REF_PD_EXIT);
1813 DPRINTF(DRAMState, "Refreshing\n");
2210 DPRINTF(DRAMState, "Refreshing\n");
2211
1814 // kick the refresh event loop into action again, and that
1815 // in turn will schedule a transition to the idle power
1816 // state once the refresh is done
2212 // kick the refresh event loop into action again, and that
2213 // in turn will schedule a transition to the idle power
2214 // state once the refresh is done
1817 assert(refreshState == REF_RUN);
1818 processRefreshEvent();
2215 if (refreshState == REF_PD_EXIT) {
2216 // Wait for PD exit timing to complete before issuing REF
2217 schedule(refreshEvent, curTick() + memory.tXP);
2218 } else {
2219 schedule(refreshEvent, curTick());
2220 }
2221 // Banks transitioned to IDLE, start REF
2222 refreshState = REF_START;
1819 }
1820}
1821
1822void
1823DRAMCtrl::Rank::updatePowerStats()
1824{
1825 // All commands up to refresh have completed
1826 // flush cmdList to DRAMPower
1827 flushCmdList();
1828
1829 // update the counters for DRAMPower, passing false to
1830 // indicate that this is not the last command in the
1831 // list. DRAMPower requires this information for the
1832 // correct calculation of the background energy at the end
1833 // of the simulation. Ideally we would want to call this
1834 // function with true once at the end of the
1835 // simulation. However, the discarded energy is extremly
1836 // small and does not effect the final results.
1837 power.powerlib.updateCounters(false);
1838
1839 // call the energy function
1840 power.powerlib.calcEnergy();
1841
1842 // Get the energy and power from DRAMPower
1843 Data::MemoryPowerModel::Energy energy =
1844 power.powerlib.getEnergy();
1845 Data::MemoryPowerModel::Power rank_power =
1846 power.powerlib.getPower();
1847
1848 actEnergy = energy.act_energy * memory.devicesPerRank;
1849 preEnergy = energy.pre_energy * memory.devicesPerRank;
1850 readEnergy = energy.read_energy * memory.devicesPerRank;
1851 writeEnergy = energy.write_energy * memory.devicesPerRank;
1852 refreshEnergy = energy.ref_energy * memory.devicesPerRank;
1853 actBackEnergy = energy.act_stdby_energy * memory.devicesPerRank;
1854 preBackEnergy = energy.pre_stdby_energy * memory.devicesPerRank;
2223 }
2224}
2225
2226void
2227DRAMCtrl::Rank::updatePowerStats()
2228{
2229 // All commands up to refresh have completed
2230 // flush cmdList to DRAMPower
2231 flushCmdList();
2232
2233 // update the counters for DRAMPower, passing false to
2234 // indicate that this is not the last command in the
2235 // list. DRAMPower requires this information for the
2236 // correct calculation of the background energy at the end
2237 // of the simulation. Ideally we would want to call this
2238 // function with true once at the end of the
2239 // simulation. However, the discarded energy is extremly
2240 // small and does not effect the final results.
2241 power.powerlib.updateCounters(false);
2242
2243 // call the energy function
2244 power.powerlib.calcEnergy();
2245
2246 // Get the energy and power from DRAMPower
2247 Data::MemoryPowerModel::Energy energy =
2248 power.powerlib.getEnergy();
2249 Data::MemoryPowerModel::Power rank_power =
2250 power.powerlib.getPower();
2251
2252 actEnergy = energy.act_energy * memory.devicesPerRank;
2253 preEnergy = energy.pre_energy * memory.devicesPerRank;
2254 readEnergy = energy.read_energy * memory.devicesPerRank;
2255 writeEnergy = energy.write_energy * memory.devicesPerRank;
2256 refreshEnergy = energy.ref_energy * memory.devicesPerRank;
2257 actBackEnergy = energy.act_stdby_energy * memory.devicesPerRank;
2258 preBackEnergy = energy.pre_stdby_energy * memory.devicesPerRank;
2259 actPowerDownEnergy = energy.f_act_pd_energy * memory.devicesPerRank;
2260 prePowerDownEnergy = energy.f_pre_pd_energy * memory.devicesPerRank;
2261 selfRefreshEnergy = energy.sref_energy * memory.devicesPerRank;
1855 totalEnergy = energy.total_energy * memory.devicesPerRank;
1856 averagePower = rank_power.average_power * memory.devicesPerRank;
1857}
1858
1859void
1860DRAMCtrl::Rank::computeStats()
1861{
1862 DPRINTF(DRAM,"Computing final stats\n");
1863
1864 // Force DRAM power to update counters based on time spent in
1865 // current state up to curTick()
1866 cmdList.push_back(Command(MemCommand::NOP, 0, curTick()));
1867
1868 // Update the stats
1869 updatePowerStats();
1870
1871 // final update of power state times
1872 pwrStateTime[pwrState] += (curTick() - pwrStateTick);
1873 pwrStateTick = curTick();
1874
1875}
1876
1877void
1878DRAMCtrl::Rank::regStats()
1879{
1880 using namespace Stats;
1881
1882 pwrStateTime
2262 totalEnergy = energy.total_energy * memory.devicesPerRank;
2263 averagePower = rank_power.average_power * memory.devicesPerRank;
2264}
2265
2266void
2267DRAMCtrl::Rank::computeStats()
2268{
2269 DPRINTF(DRAM,"Computing final stats\n");
2270
2271 // Force DRAM power to update counters based on time spent in
2272 // current state up to curTick()
2273 cmdList.push_back(Command(MemCommand::NOP, 0, curTick()));
2274
2275 // Update the stats
2276 updatePowerStats();
2277
2278 // final update of power state times
2279 pwrStateTime[pwrState] += (curTick() - pwrStateTick);
2280 pwrStateTick = curTick();
2281
2282}
2283
2284void
2285DRAMCtrl::Rank::regStats()
2286{
2287 using namespace Stats;
2288
2289 pwrStateTime
1883 .init(5)
2290 .init(6)
1884 .name(name() + ".memoryStateTime")
1885 .desc("Time in different power states");
1886 pwrStateTime.subname(0, "IDLE");
1887 pwrStateTime.subname(1, "REF");
2291 .name(name() + ".memoryStateTime")
2292 .desc("Time in different power states");
2293 pwrStateTime.subname(0, "IDLE");
2294 pwrStateTime.subname(1, "REF");
1888 pwrStateTime.subname(2, "PRE_PDN");
1889 pwrStateTime.subname(3, "ACT");
1890 pwrStateTime.subname(4, "ACT_PDN");
2295 pwrStateTime.subname(2, "SREF");
2296 pwrStateTime.subname(3, "PRE_PDN");
2297 pwrStateTime.subname(4, "ACT");
2298 pwrStateTime.subname(5, "ACT_PDN");
1891
1892 actEnergy
1893 .name(name() + ".actEnergy")
1894 .desc("Energy for activate commands per rank (pJ)");
1895
1896 preEnergy
1897 .name(name() + ".preEnergy")
1898 .desc("Energy for precharge commands per rank (pJ)");
1899
1900 readEnergy
1901 .name(name() + ".readEnergy")
1902 .desc("Energy for read commands per rank (pJ)");
1903
1904 writeEnergy
1905 .name(name() + ".writeEnergy")
1906 .desc("Energy for write commands per rank (pJ)");
1907
1908 refreshEnergy
1909 .name(name() + ".refreshEnergy")
1910 .desc("Energy for refresh commands per rank (pJ)");
1911
1912 actBackEnergy
1913 .name(name() + ".actBackEnergy")
1914 .desc("Energy for active background per rank (pJ)");
1915
1916 preBackEnergy
1917 .name(name() + ".preBackEnergy")
1918 .desc("Energy for precharge background per rank (pJ)");
1919
2299
2300 actEnergy
2301 .name(name() + ".actEnergy")
2302 .desc("Energy for activate commands per rank (pJ)");
2303
2304 preEnergy
2305 .name(name() + ".preEnergy")
2306 .desc("Energy for precharge commands per rank (pJ)");
2307
2308 readEnergy
2309 .name(name() + ".readEnergy")
2310 .desc("Energy for read commands per rank (pJ)");
2311
2312 writeEnergy
2313 .name(name() + ".writeEnergy")
2314 .desc("Energy for write commands per rank (pJ)");
2315
2316 refreshEnergy
2317 .name(name() + ".refreshEnergy")
2318 .desc("Energy for refresh commands per rank (pJ)");
2319
2320 actBackEnergy
2321 .name(name() + ".actBackEnergy")
2322 .desc("Energy for active background per rank (pJ)");
2323
2324 preBackEnergy
2325 .name(name() + ".preBackEnergy")
2326 .desc("Energy for precharge background per rank (pJ)");
2327
2328 actPowerDownEnergy
2329 .name(name() + ".actPowerDownEnergy")
2330 .desc("Energy for active power-down per rank (pJ)");
2331
2332 prePowerDownEnergy
2333 .name(name() + ".prePowerDownEnergy")
2334 .desc("Energy for precharge power-down per rank (pJ)");
2335
2336 selfRefreshEnergy
2337 .name(name() + ".selfRefreshEnergy")
2338 .desc("Energy for self refresh per rank (pJ)");
2339
1920 totalEnergy
1921 .name(name() + ".totalEnergy")
1922 .desc("Total energy per rank (pJ)");
1923
1924 averagePower
1925 .name(name() + ".averagePower")
1926 .desc("Core power per rank (mW)");
1927
2340 totalEnergy
2341 .name(name() + ".totalEnergy")
2342 .desc("Total energy per rank (pJ)");
2343
2344 averagePower
2345 .name(name() + ".averagePower")
2346 .desc("Core power per rank (mW)");
2347
2348 totalIdleTime
2349 .name(name() + ".totalIdleTime")
2350 .desc("Total Idle time Per DRAM Rank");
2351
1928 registerDumpCallback(new RankDumpCallback(this));
1929}
1930void
1931DRAMCtrl::regStats()
1932{
1933 using namespace Stats;
1934
1935 AbstractMemory::regStats();
1936
1937 for (auto r : ranks) {
1938 r->regStats();
1939 }
1940
1941 readReqs
1942 .name(name() + ".readReqs")
1943 .desc("Number of read requests accepted");
1944
1945 writeReqs
1946 .name(name() + ".writeReqs")
1947 .desc("Number of write requests accepted");
1948
1949 readBursts
1950 .name(name() + ".readBursts")
1951 .desc("Number of DRAM read bursts, "
1952 "including those serviced by the write queue");
1953
1954 writeBursts
1955 .name(name() + ".writeBursts")
1956 .desc("Number of DRAM write bursts, "
1957 "including those merged in the write queue");
1958
1959 servicedByWrQ
1960 .name(name() + ".servicedByWrQ")
1961 .desc("Number of DRAM read bursts serviced by the write queue");
1962
1963 mergedWrBursts
1964 .name(name() + ".mergedWrBursts")
1965 .desc("Number of DRAM write bursts merged with an existing one");
1966
1967 neitherReadNorWrite
1968 .name(name() + ".neitherReadNorWriteReqs")
1969 .desc("Number of requests that are neither read nor write");
1970
1971 perBankRdBursts
1972 .init(banksPerRank * ranksPerChannel)
1973 .name(name() + ".perBankRdBursts")
1974 .desc("Per bank write bursts");
1975
1976 perBankWrBursts
1977 .init(banksPerRank * ranksPerChannel)
1978 .name(name() + ".perBankWrBursts")
1979 .desc("Per bank write bursts");
1980
1981 avgRdQLen
1982 .name(name() + ".avgRdQLen")
1983 .desc("Average read queue length when enqueuing")
1984 .precision(2);
1985
1986 avgWrQLen
1987 .name(name() + ".avgWrQLen")
1988 .desc("Average write queue length when enqueuing")
1989 .precision(2);
1990
1991 totQLat
1992 .name(name() + ".totQLat")
1993 .desc("Total ticks spent queuing");
1994
1995 totBusLat
1996 .name(name() + ".totBusLat")
1997 .desc("Total ticks spent in databus transfers");
1998
1999 totMemAccLat
2000 .name(name() + ".totMemAccLat")
2001 .desc("Total ticks spent from burst creation until serviced "
2002 "by the DRAM");
2003
2004 avgQLat
2005 .name(name() + ".avgQLat")
2006 .desc("Average queueing delay per DRAM burst")
2007 .precision(2);
2008
2009 avgQLat = totQLat / (readBursts - servicedByWrQ);
2010
2011 avgBusLat
2012 .name(name() + ".avgBusLat")
2013 .desc("Average bus latency per DRAM burst")
2014 .precision(2);
2015
2016 avgBusLat = totBusLat / (readBursts - servicedByWrQ);
2017
2018 avgMemAccLat
2019 .name(name() + ".avgMemAccLat")
2020 .desc("Average memory access latency per DRAM burst")
2021 .precision(2);
2022
2023 avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
2024
2025 numRdRetry
2026 .name(name() + ".numRdRetry")
2027 .desc("Number of times read queue was full causing retry");
2028
2029 numWrRetry
2030 .name(name() + ".numWrRetry")
2031 .desc("Number of times write queue was full causing retry");
2032
2033 readRowHits
2034 .name(name() + ".readRowHits")
2035 .desc("Number of row buffer hits during reads");
2036
2037 writeRowHits
2038 .name(name() + ".writeRowHits")
2039 .desc("Number of row buffer hits during writes");
2040
2041 readRowHitRate
2042 .name(name() + ".readRowHitRate")
2043 .desc("Row buffer hit rate for reads")
2044 .precision(2);
2045
2046 readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
2047
2048 writeRowHitRate
2049 .name(name() + ".writeRowHitRate")
2050 .desc("Row buffer hit rate for writes")
2051 .precision(2);
2052
2053 writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
2054
2055 readPktSize
2056 .init(ceilLog2(burstSize) + 1)
2057 .name(name() + ".readPktSize")
2058 .desc("Read request sizes (log2)");
2059
2060 writePktSize
2061 .init(ceilLog2(burstSize) + 1)
2062 .name(name() + ".writePktSize")
2063 .desc("Write request sizes (log2)");
2064
2065 rdQLenPdf
2066 .init(readBufferSize)
2067 .name(name() + ".rdQLenPdf")
2068 .desc("What read queue length does an incoming req see");
2069
2070 wrQLenPdf
2071 .init(writeBufferSize)
2072 .name(name() + ".wrQLenPdf")
2073 .desc("What write queue length does an incoming req see");
2074
2075 bytesPerActivate
2076 .init(maxAccessesPerRow)
2077 .name(name() + ".bytesPerActivate")
2078 .desc("Bytes accessed per row activation")
2079 .flags(nozero);
2080
2081 rdPerTurnAround
2082 .init(readBufferSize)
2083 .name(name() + ".rdPerTurnAround")
2084 .desc("Reads before turning the bus around for writes")
2085 .flags(nozero);
2086
2087 wrPerTurnAround
2088 .init(writeBufferSize)
2089 .name(name() + ".wrPerTurnAround")
2090 .desc("Writes before turning the bus around for reads")
2091 .flags(nozero);
2092
2093 bytesReadDRAM
2094 .name(name() + ".bytesReadDRAM")
2095 .desc("Total number of bytes read from DRAM");
2096
2097 bytesReadWrQ
2098 .name(name() + ".bytesReadWrQ")
2099 .desc("Total number of bytes read from write queue");
2100
2101 bytesWritten
2102 .name(name() + ".bytesWritten")
2103 .desc("Total number of bytes written to DRAM");
2104
2105 bytesReadSys
2106 .name(name() + ".bytesReadSys")
2107 .desc("Total read bytes from the system interface side");
2108
2109 bytesWrittenSys
2110 .name(name() + ".bytesWrittenSys")
2111 .desc("Total written bytes from the system interface side");
2112
2113 avgRdBW
2114 .name(name() + ".avgRdBW")
2115 .desc("Average DRAM read bandwidth in MiByte/s")
2116 .precision(2);
2117
2118 avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
2119
2120 avgWrBW
2121 .name(name() + ".avgWrBW")
2122 .desc("Average achieved write bandwidth in MiByte/s")
2123 .precision(2);
2124
2125 avgWrBW = (bytesWritten / 1000000) / simSeconds;
2126
2127 avgRdBWSys
2128 .name(name() + ".avgRdBWSys")
2129 .desc("Average system read bandwidth in MiByte/s")
2130 .precision(2);
2131
2132 avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
2133
2134 avgWrBWSys
2135 .name(name() + ".avgWrBWSys")
2136 .desc("Average system write bandwidth in MiByte/s")
2137 .precision(2);
2138
2139 avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
2140
2141 peakBW
2142 .name(name() + ".peakBW")
2143 .desc("Theoretical peak bandwidth in MiByte/s")
2144 .precision(2);
2145
2146 peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
2147
2148 busUtil
2149 .name(name() + ".busUtil")
2150 .desc("Data bus utilization in percentage")
2151 .precision(2);
2152 busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
2153
2154 totGap
2155 .name(name() + ".totGap")
2156 .desc("Total gap between requests");
2157
2158 avgGap
2159 .name(name() + ".avgGap")
2160 .desc("Average gap between requests")
2161 .precision(2);
2162
2163 avgGap = totGap / (readReqs + writeReqs);
2164
2165 // Stats for DRAM Power calculation based on Micron datasheet
2166 busUtilRead
2167 .name(name() + ".busUtilRead")
2168 .desc("Data bus utilization in percentage for reads")
2169 .precision(2);
2170
2171 busUtilRead = avgRdBW / peakBW * 100;
2172
2173 busUtilWrite
2174 .name(name() + ".busUtilWrite")
2175 .desc("Data bus utilization in percentage for writes")
2176 .precision(2);
2177
2178 busUtilWrite = avgWrBW / peakBW * 100;
2179
2180 pageHitRate
2181 .name(name() + ".pageHitRate")
2182 .desc("Row buffer hit rate, read and write combined")
2183 .precision(2);
2184
2185 pageHitRate = (writeRowHits + readRowHits) /
2186 (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
2187}
2188
2189void
2190DRAMCtrl::recvFunctional(PacketPtr pkt)
2191{
2192 // rely on the abstract memory
2193 functionalAccess(pkt);
2194}
2195
2196BaseSlavePort&
2197DRAMCtrl::getSlavePort(const string &if_name, PortID idx)
2198{
2199 if (if_name != "port") {
2200 return MemObject::getSlavePort(if_name, idx);
2201 } else {
2202 return port;
2203 }
2204}
2205
2206DrainState
2207DRAMCtrl::drain()
2208{
2209 // if there is anything in any of our internal queues, keep track
2210 // of that as well
2211 if (!(writeQueue.empty() && readQueue.empty() && respQueue.empty() &&
2212 allRanksDrained())) {
2213
2214 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
2215 " resp: %d\n", writeQueue.size(), readQueue.size(),
2216 respQueue.size());
2217
2352 registerDumpCallback(new RankDumpCallback(this));
2353}
2354void
2355DRAMCtrl::regStats()
2356{
2357 using namespace Stats;
2358
2359 AbstractMemory::regStats();
2360
2361 for (auto r : ranks) {
2362 r->regStats();
2363 }
2364
2365 readReqs
2366 .name(name() + ".readReqs")
2367 .desc("Number of read requests accepted");
2368
2369 writeReqs
2370 .name(name() + ".writeReqs")
2371 .desc("Number of write requests accepted");
2372
2373 readBursts
2374 .name(name() + ".readBursts")
2375 .desc("Number of DRAM read bursts, "
2376 "including those serviced by the write queue");
2377
2378 writeBursts
2379 .name(name() + ".writeBursts")
2380 .desc("Number of DRAM write bursts, "
2381 "including those merged in the write queue");
2382
2383 servicedByWrQ
2384 .name(name() + ".servicedByWrQ")
2385 .desc("Number of DRAM read bursts serviced by the write queue");
2386
2387 mergedWrBursts
2388 .name(name() + ".mergedWrBursts")
2389 .desc("Number of DRAM write bursts merged with an existing one");
2390
2391 neitherReadNorWrite
2392 .name(name() + ".neitherReadNorWriteReqs")
2393 .desc("Number of requests that are neither read nor write");
2394
2395 perBankRdBursts
2396 .init(banksPerRank * ranksPerChannel)
2397 .name(name() + ".perBankRdBursts")
2398 .desc("Per bank write bursts");
2399
2400 perBankWrBursts
2401 .init(banksPerRank * ranksPerChannel)
2402 .name(name() + ".perBankWrBursts")
2403 .desc("Per bank write bursts");
2404
2405 avgRdQLen
2406 .name(name() + ".avgRdQLen")
2407 .desc("Average read queue length when enqueuing")
2408 .precision(2);
2409
2410 avgWrQLen
2411 .name(name() + ".avgWrQLen")
2412 .desc("Average write queue length when enqueuing")
2413 .precision(2);
2414
2415 totQLat
2416 .name(name() + ".totQLat")
2417 .desc("Total ticks spent queuing");
2418
2419 totBusLat
2420 .name(name() + ".totBusLat")
2421 .desc("Total ticks spent in databus transfers");
2422
2423 totMemAccLat
2424 .name(name() + ".totMemAccLat")
2425 .desc("Total ticks spent from burst creation until serviced "
2426 "by the DRAM");
2427
2428 avgQLat
2429 .name(name() + ".avgQLat")
2430 .desc("Average queueing delay per DRAM burst")
2431 .precision(2);
2432
2433 avgQLat = totQLat / (readBursts - servicedByWrQ);
2434
2435 avgBusLat
2436 .name(name() + ".avgBusLat")
2437 .desc("Average bus latency per DRAM burst")
2438 .precision(2);
2439
2440 avgBusLat = totBusLat / (readBursts - servicedByWrQ);
2441
2442 avgMemAccLat
2443 .name(name() + ".avgMemAccLat")
2444 .desc("Average memory access latency per DRAM burst")
2445 .precision(2);
2446
2447 avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
2448
2449 numRdRetry
2450 .name(name() + ".numRdRetry")
2451 .desc("Number of times read queue was full causing retry");
2452
2453 numWrRetry
2454 .name(name() + ".numWrRetry")
2455 .desc("Number of times write queue was full causing retry");
2456
2457 readRowHits
2458 .name(name() + ".readRowHits")
2459 .desc("Number of row buffer hits during reads");
2460
2461 writeRowHits
2462 .name(name() + ".writeRowHits")
2463 .desc("Number of row buffer hits during writes");
2464
2465 readRowHitRate
2466 .name(name() + ".readRowHitRate")
2467 .desc("Row buffer hit rate for reads")
2468 .precision(2);
2469
2470 readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
2471
2472 writeRowHitRate
2473 .name(name() + ".writeRowHitRate")
2474 .desc("Row buffer hit rate for writes")
2475 .precision(2);
2476
2477 writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
2478
2479 readPktSize
2480 .init(ceilLog2(burstSize) + 1)
2481 .name(name() + ".readPktSize")
2482 .desc("Read request sizes (log2)");
2483
2484 writePktSize
2485 .init(ceilLog2(burstSize) + 1)
2486 .name(name() + ".writePktSize")
2487 .desc("Write request sizes (log2)");
2488
2489 rdQLenPdf
2490 .init(readBufferSize)
2491 .name(name() + ".rdQLenPdf")
2492 .desc("What read queue length does an incoming req see");
2493
2494 wrQLenPdf
2495 .init(writeBufferSize)
2496 .name(name() + ".wrQLenPdf")
2497 .desc("What write queue length does an incoming req see");
2498
2499 bytesPerActivate
2500 .init(maxAccessesPerRow)
2501 .name(name() + ".bytesPerActivate")
2502 .desc("Bytes accessed per row activation")
2503 .flags(nozero);
2504
2505 rdPerTurnAround
2506 .init(readBufferSize)
2507 .name(name() + ".rdPerTurnAround")
2508 .desc("Reads before turning the bus around for writes")
2509 .flags(nozero);
2510
2511 wrPerTurnAround
2512 .init(writeBufferSize)
2513 .name(name() + ".wrPerTurnAround")
2514 .desc("Writes before turning the bus around for reads")
2515 .flags(nozero);
2516
2517 bytesReadDRAM
2518 .name(name() + ".bytesReadDRAM")
2519 .desc("Total number of bytes read from DRAM");
2520
2521 bytesReadWrQ
2522 .name(name() + ".bytesReadWrQ")
2523 .desc("Total number of bytes read from write queue");
2524
2525 bytesWritten
2526 .name(name() + ".bytesWritten")
2527 .desc("Total number of bytes written to DRAM");
2528
2529 bytesReadSys
2530 .name(name() + ".bytesReadSys")
2531 .desc("Total read bytes from the system interface side");
2532
2533 bytesWrittenSys
2534 .name(name() + ".bytesWrittenSys")
2535 .desc("Total written bytes from the system interface side");
2536
2537 avgRdBW
2538 .name(name() + ".avgRdBW")
2539 .desc("Average DRAM read bandwidth in MiByte/s")
2540 .precision(2);
2541
2542 avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
2543
2544 avgWrBW
2545 .name(name() + ".avgWrBW")
2546 .desc("Average achieved write bandwidth in MiByte/s")
2547 .precision(2);
2548
2549 avgWrBW = (bytesWritten / 1000000) / simSeconds;
2550
2551 avgRdBWSys
2552 .name(name() + ".avgRdBWSys")
2553 .desc("Average system read bandwidth in MiByte/s")
2554 .precision(2);
2555
2556 avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
2557
2558 avgWrBWSys
2559 .name(name() + ".avgWrBWSys")
2560 .desc("Average system write bandwidth in MiByte/s")
2561 .precision(2);
2562
2563 avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
2564
2565 peakBW
2566 .name(name() + ".peakBW")
2567 .desc("Theoretical peak bandwidth in MiByte/s")
2568 .precision(2);
2569
2570 peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
2571
2572 busUtil
2573 .name(name() + ".busUtil")
2574 .desc("Data bus utilization in percentage")
2575 .precision(2);
2576 busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
2577
2578 totGap
2579 .name(name() + ".totGap")
2580 .desc("Total gap between requests");
2581
2582 avgGap
2583 .name(name() + ".avgGap")
2584 .desc("Average gap between requests")
2585 .precision(2);
2586
2587 avgGap = totGap / (readReqs + writeReqs);
2588
2589 // Stats for DRAM Power calculation based on Micron datasheet
2590 busUtilRead
2591 .name(name() + ".busUtilRead")
2592 .desc("Data bus utilization in percentage for reads")
2593 .precision(2);
2594
2595 busUtilRead = avgRdBW / peakBW * 100;
2596
2597 busUtilWrite
2598 .name(name() + ".busUtilWrite")
2599 .desc("Data bus utilization in percentage for writes")
2600 .precision(2);
2601
2602 busUtilWrite = avgWrBW / peakBW * 100;
2603
2604 pageHitRate
2605 .name(name() + ".pageHitRate")
2606 .desc("Row buffer hit rate, read and write combined")
2607 .precision(2);
2608
2609 pageHitRate = (writeRowHits + readRowHits) /
2610 (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
2611}
2612
2613void
2614DRAMCtrl::recvFunctional(PacketPtr pkt)
2615{
2616 // rely on the abstract memory
2617 functionalAccess(pkt);
2618}
2619
2620BaseSlavePort&
2621DRAMCtrl::getSlavePort(const string &if_name, PortID idx)
2622{
2623 if (if_name != "port") {
2624 return MemObject::getSlavePort(if_name, idx);
2625 } else {
2626 return port;
2627 }
2628}
2629
2630DrainState
2631DRAMCtrl::drain()
2632{
2633 // if there is anything in any of our internal queues, keep track
2634 // of that as well
2635 if (!(writeQueue.empty() && readQueue.empty() && respQueue.empty() &&
2636 allRanksDrained())) {
2637
2638 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
2639 " resp: %d\n", writeQueue.size(), readQueue.size(),
2640 respQueue.size());
2641
2218 // the only part that is not drained automatically over time
2642 // the only queue that is not drained automatically over time
2219 // is the write queue, thus kick things into action if needed
2220 if (!writeQueue.empty() && !nextReqEvent.scheduled()) {
2221 schedule(nextReqEvent, curTick());
2222 }
2643 // is the write queue, thus kick things into action if needed
2644 if (!writeQueue.empty() && !nextReqEvent.scheduled()) {
2645 schedule(nextReqEvent, curTick());
2646 }
2647
2648 // also need to kick off events to exit self-refresh
2649 for (auto r : ranks) {
2650 // force self-refresh exit, which in turn will issue auto-refresh
2651 if (r->pwrState == PWR_SREF) {
2652 DPRINTF(DRAM,"Rank%d: Forcing self-refresh wakeup in drain\n",
2653 r->rank);
2654 r->scheduleWakeUpEvent(tXS);
2655 }
2656 }
2657
2223 return DrainState::Draining;
2224 } else {
2225 return DrainState::Drained;
2226 }
2227}
2228
2229bool
2230DRAMCtrl::allRanksDrained() const
2231{
2232 // true until proven false
2233 bool all_ranks_drained = true;
2234 for (auto r : ranks) {
2235 // then verify that the power state is IDLE
2236 // ensuring all banks are closed and rank is not in a low power state
2237 all_ranks_drained = r->inPwrIdleState() && all_ranks_drained;
2238 }
2239 return all_ranks_drained;
2240}
2241
2242void
2243DRAMCtrl::drainResume()
2244{
2245 if (!isTimingMode && system()->isTimingMode()) {
2246 // if we switched to timing mode, kick things into action,
2247 // and behave as if we restored from a checkpoint
2248 startup();
2249 } else if (isTimingMode && !system()->isTimingMode()) {
2250 // if we switch from timing mode, stop the refresh events to
2251 // not cause issues with KVM
2252 for (auto r : ranks) {
2253 r->suspend();
2254 }
2255 }
2256
2257 // update the mode
2258 isTimingMode = system()->isTimingMode();
2259}
2260
2261DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
2262 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
2263 memory(_memory)
2264{ }
2265
2266AddrRangeList
2267DRAMCtrl::MemoryPort::getAddrRanges() const
2268{
2269 AddrRangeList ranges;
2270 ranges.push_back(memory.getAddrRange());
2271 return ranges;
2272}
2273
2274void
2275DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
2276{
2277 pkt->pushLabel(memory.name());
2278
2279 if (!queue.checkFunctional(pkt)) {
2280 // Default implementation of SimpleTimingPort::recvFunctional()
2281 // calls recvAtomic() and throws away the latency; we can save a
2282 // little here by just not calculating the latency.
2283 memory.recvFunctional(pkt);
2284 }
2285
2286 pkt->popLabel();
2287}
2288
2289Tick
2290DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt)
2291{
2292 return memory.recvAtomic(pkt);
2293}
2294
2295bool
2296DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt)
2297{
2298 // pass it to the memory controller
2299 return memory.recvTimingReq(pkt);
2300}
2301
2302DRAMCtrl*
2303DRAMCtrlParams::create()
2304{
2305 return new DRAMCtrl(this);
2306}
2658 return DrainState::Draining;
2659 } else {
2660 return DrainState::Drained;
2661 }
2662}
2663
2664bool
2665DRAMCtrl::allRanksDrained() const
2666{
2667 // true until proven false
2668 bool all_ranks_drained = true;
2669 for (auto r : ranks) {
2670 // then verify that the power state is IDLE
2671 // ensuring all banks are closed and rank is not in a low power state
2672 all_ranks_drained = r->inPwrIdleState() && all_ranks_drained;
2673 }
2674 return all_ranks_drained;
2675}
2676
2677void
2678DRAMCtrl::drainResume()
2679{
2680 if (!isTimingMode && system()->isTimingMode()) {
2681 // if we switched to timing mode, kick things into action,
2682 // and behave as if we restored from a checkpoint
2683 startup();
2684 } else if (isTimingMode && !system()->isTimingMode()) {
2685 // if we switch from timing mode, stop the refresh events to
2686 // not cause issues with KVM
2687 for (auto r : ranks) {
2688 r->suspend();
2689 }
2690 }
2691
2692 // update the mode
2693 isTimingMode = system()->isTimingMode();
2694}
2695
2696DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
2697 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
2698 memory(_memory)
2699{ }
2700
2701AddrRangeList
2702DRAMCtrl::MemoryPort::getAddrRanges() const
2703{
2704 AddrRangeList ranges;
2705 ranges.push_back(memory.getAddrRange());
2706 return ranges;
2707}
2708
2709void
2710DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
2711{
2712 pkt->pushLabel(memory.name());
2713
2714 if (!queue.checkFunctional(pkt)) {
2715 // Default implementation of SimpleTimingPort::recvFunctional()
2716 // calls recvAtomic() and throws away the latency; we can save a
2717 // little here by just not calculating the latency.
2718 memory.recvFunctional(pkt);
2719 }
2720
2721 pkt->popLabel();
2722}
2723
2724Tick
2725DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt)
2726{
2727 return memory.recvAtomic(pkt);
2728}
2729
2730bool
2731DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt)
2732{
2733 // pass it to the memory controller
2734 return memory.recvTimingReq(pkt);
2735}
2736
2737DRAMCtrl*
2738DRAMCtrlParams::create()
2739{
2740 return new DRAMCtrl(this);
2741}