dram_ctrl.cc (11334:9bd2e84abdca) dram_ctrl.cc (11673:9f3ccf96bb5a)
1/*
2 * Copyright (c) 2010-2015 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 */
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),
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),
1/*
2 * Copyright (c) 2010-2015 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 */
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),
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), activationLimit(p->activation_limit),
85 tRRD_L(p->tRRD_L), tXAW(p->tXAW), tXP(p->tXP), tXS(p->tXS),
86 activationLimit(p->activation_limit),
86 memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
87 pageMgmt(p->page_policy),
88 maxAccessesPerRow(p->max_accesses_per_row),
89 frontendLatency(p->static_frontend_latency),
90 backendLatency(p->static_backend_latency),
91 busBusyUntil(0), prevArrival(0),
92 nextReqTime(0), activeRank(0), timeStampOffset(0)
93{
94 // sanity check the ranks since we rely on bit slicing for the
95 // address decoding
96 fatal_if(!isPowerOf2(ranksPerChannel), "DRAM rank count of %d is not "
97 "allowed, must be a power of two\n", ranksPerChannel);
98
99 fatal_if(!isPowerOf2(burstSize), "DRAM burst size %d is not allowed, "
100 "must be a power of two\n", burstSize);
101
102 for (int i = 0; i < ranksPerChannel; i++) {
103 Rank* rank = new Rank(*this, p);
104 ranks.push_back(rank);
105
106 rank->actTicks.resize(activationLimit, 0);
107 rank->banks.resize(banksPerRank);
108 rank->rank = i;
109
110 for (int b = 0; b < banksPerRank; b++) {
111 rank->banks[b].bank = b;
112 // GDDR addressing of banks to BG is linear.
113 // Here we assume that all DRAM generations address bank groups as
114 // follows:
115 if (bankGroupArch) {
116 // Simply assign lower bits to bank group in order to
117 // rotate across bank groups as banks are incremented
118 // e.g. with 4 banks per bank group and 16 banks total:
119 // banks 0,4,8,12 are in bank group 0
120 // banks 1,5,9,13 are in bank group 1
121 // banks 2,6,10,14 are in bank group 2
122 // banks 3,7,11,15 are in bank group 3
123 rank->banks[b].bankgr = b % bankGroupsPerRank;
124 } else {
125 // No bank groups; simply assign to bank number
126 rank->banks[b].bankgr = b;
127 }
128 }
129 }
130
131 // perform a basic check of the write thresholds
132 if (p->write_low_thresh_perc >= p->write_high_thresh_perc)
133 fatal("Write buffer low threshold %d must be smaller than the "
134 "high threshold %d\n", p->write_low_thresh_perc,
135 p->write_high_thresh_perc);
136
137 // determine the rows per bank by looking at the total capacity
138 uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
139
140 // determine the dram actual capacity from the DRAM config in Mbytes
141 uint64_t deviceCapacity = deviceSize / (1024 * 1024) * devicesPerRank *
142 ranksPerChannel;
143
144 // if actual DRAM size does not match memory capacity in system warn!
145 if (deviceCapacity != capacity / (1024 * 1024))
146 warn("DRAM device capacity (%d Mbytes) does not match the "
147 "address range assigned (%d Mbytes)\n", deviceCapacity,
148 capacity / (1024 * 1024));
149
150 DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
151 AbstractMemory::size());
152
153 DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
154 rowBufferSize, columnsPerRowBuffer);
155
156 rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
157
158 // some basic sanity checks
159 if (tREFI <= tRP || tREFI <= tRFC) {
160 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
161 tREFI, tRP, tRFC);
162 }
163
164 // basic bank group architecture checks ->
165 if (bankGroupArch) {
166 // must have at least one bank per bank group
167 if (bankGroupsPerRank > banksPerRank) {
168 fatal("banks per rank (%d) must be equal to or larger than "
169 "banks groups per rank (%d)\n",
170 banksPerRank, bankGroupsPerRank);
171 }
172 // must have same number of banks in each bank group
173 if ((banksPerRank % bankGroupsPerRank) != 0) {
174 fatal("Banks per rank (%d) must be evenly divisible by bank groups "
175 "per rank (%d) for equal banks per bank group\n",
176 banksPerRank, bankGroupsPerRank);
177 }
178 // tCCD_L should be greater than minimal, back-to-back burst delay
179 if (tCCD_L <= tBURST) {
180 fatal("tCCD_L (%d) should be larger than tBURST (%d) when "
181 "bank groups per rank (%d) is greater than 1\n",
182 tCCD_L, tBURST, bankGroupsPerRank);
183 }
184 // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
185 // some datasheets might specify it equal to tRRD
186 if (tRRD_L < tRRD) {
187 fatal("tRRD_L (%d) should be larger than tRRD (%d) when "
188 "bank groups per rank (%d) is greater than 1\n",
189 tRRD_L, tRRD, bankGroupsPerRank);
190 }
191 }
192
193}
194
195void
196DRAMCtrl::init()
197{
198 AbstractMemory::init();
199
200 if (!port.isConnected()) {
201 fatal("DRAMCtrl %s is unconnected!\n", name());
202 } else {
203 port.sendRangeChange();
204 }
205
206 // a bit of sanity checks on the interleaving, save it for here to
207 // ensure that the system pointer is initialised
208 if (range.interleaved()) {
209 if (channels != range.stripes())
210 fatal("%s has %d interleaved address stripes but %d channel(s)\n",
211 name(), range.stripes(), channels);
212
213 if (addrMapping == Enums::RoRaBaChCo) {
214 if (rowBufferSize != range.granularity()) {
215 fatal("Channel interleaving of %s doesn't match RoRaBaChCo "
216 "address map\n", name());
217 }
218 } else if (addrMapping == Enums::RoRaBaCoCh ||
219 addrMapping == Enums::RoCoRaBaCh) {
220 // for the interleavings with channel bits in the bottom,
221 // if the system uses a channel striping granularity that
222 // is larger than the DRAM burst size, then map the
223 // sequential accesses within a stripe to a number of
224 // columns in the DRAM, effectively placing some of the
225 // lower-order column bits as the least-significant bits
226 // of the address (above the ones denoting the burst size)
227 assert(columnsPerStripe >= 1);
228
229 // channel striping has to be done at a granularity that
230 // is equal or larger to a cache line
231 if (system()->cacheLineSize() > range.granularity()) {
232 fatal("Channel interleaving of %s must be at least as large "
233 "as the cache line size\n", name());
234 }
235
236 // ...and equal or smaller than the row-buffer size
237 if (rowBufferSize < range.granularity()) {
238 fatal("Channel interleaving of %s must be at most as large "
239 "as the row-buffer size\n", name());
240 }
241 // this is essentially the check above, so just to be sure
242 assert(columnsPerStripe <= columnsPerRowBuffer);
243 }
244 }
245}
246
247void
248DRAMCtrl::startup()
249{
250 // remember the memory system mode of operation
251 isTimingMode = system()->isTimingMode();
252
253 if (isTimingMode) {
254 // timestamp offset should be in clock cycles for DRAMPower
255 timeStampOffset = divCeil(curTick(), tCK);
256
257 // update the start tick for the precharge accounting to the
258 // current tick
259 for (auto r : ranks) {
260 r->startup(curTick() + tREFI - tRP);
261 }
262
263 // shift the bus busy time sufficiently far ahead that we never
264 // have to worry about negative values when computing the time for
265 // the next request, this will add an insignificant bubble at the
266 // start of simulation
267 busBusyUntil = curTick() + tRP + tRCD + tCL;
268 }
269}
270
271Tick
272DRAMCtrl::recvAtomic(PacketPtr pkt)
273{
274 DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
275
276 panic_if(pkt->cacheResponding(), "Should not see packets where cache "
277 "is responding");
278
279 // do the actual memory access and turn the packet into a response
280 access(pkt);
281
282 Tick latency = 0;
283 if (pkt->hasData()) {
284 // this value is not supposed to be accurate, just enough to
285 // keep things going, mimic a closed page
286 latency = tRP + tRCD + tCL;
287 }
288 return latency;
289}
290
291bool
292DRAMCtrl::readQueueFull(unsigned int neededEntries) const
293{
294 DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
295 readBufferSize, readQueue.size() + respQueue.size(),
296 neededEntries);
297
298 return
299 (readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
300}
301
302bool
303DRAMCtrl::writeQueueFull(unsigned int neededEntries) const
304{
305 DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
306 writeBufferSize, writeQueue.size(), neededEntries);
307 return (writeQueue.size() + neededEntries) > writeBufferSize;
308}
309
310DRAMCtrl::DRAMPacket*
311DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size,
312 bool isRead)
313{
314 // decode the address based on the address mapping scheme, with
315 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
316 // channel, respectively
317 uint8_t rank;
318 uint8_t bank;
319 // use a 64-bit unsigned during the computations as the row is
320 // always the top bits, and check before creating the DRAMPacket
321 uint64_t row;
322
323 // truncate the address to a DRAM burst, which makes it unique to
324 // a specific column, row, bank, rank and channel
325 Addr addr = dramPktAddr / burstSize;
326
327 // we have removed the lowest order address bits that denote the
328 // position within the column
329 if (addrMapping == Enums::RoRaBaChCo) {
330 // the lowest order bits denote the column to ensure that
331 // sequential cache lines occupy the same row
332 addr = addr / columnsPerRowBuffer;
333
334 // take out the channel part of the address
335 addr = addr / channels;
336
337 // after the channel bits, get the bank bits to interleave
338 // over the banks
339 bank = addr % banksPerRank;
340 addr = addr / banksPerRank;
341
342 // after the bank, we get the rank bits which thus interleaves
343 // over the ranks
344 rank = addr % ranksPerChannel;
345 addr = addr / ranksPerChannel;
346
347 // lastly, get the row bits, no need to remove them from addr
348 row = addr % rowsPerBank;
349 } else if (addrMapping == Enums::RoRaBaCoCh) {
350 // take out the lower-order column bits
351 addr = addr / columnsPerStripe;
352
353 // take out the channel part of the address
354 addr = addr / channels;
355
356 // next, the higher-order column bites
357 addr = addr / (columnsPerRowBuffer / columnsPerStripe);
358
359 // after the column bits, we get the bank bits to interleave
360 // over the banks
361 bank = addr % banksPerRank;
362 addr = addr / banksPerRank;
363
364 // after the bank, we get the rank bits which thus interleaves
365 // over the ranks
366 rank = addr % ranksPerChannel;
367 addr = addr / ranksPerChannel;
368
369 // lastly, get the row bits, no need to remove them from addr
370 row = addr % rowsPerBank;
371 } else if (addrMapping == Enums::RoCoRaBaCh) {
372 // optimise for closed page mode and utilise maximum
373 // parallelism of the DRAM (at the cost of power)
374
375 // take out the lower-order column bits
376 addr = addr / columnsPerStripe;
377
378 // take out the channel part of the address, not that this has
379 // to match with how accesses are interleaved between the
380 // controllers in the address mapping
381 addr = addr / channels;
382
383 // start with the bank bits, as this provides the maximum
384 // opportunity for parallelism between requests
385 bank = addr % banksPerRank;
386 addr = addr / banksPerRank;
387
388 // next get the rank bits
389 rank = addr % ranksPerChannel;
390 addr = addr / ranksPerChannel;
391
392 // next, the higher-order column bites
393 addr = addr / (columnsPerRowBuffer / columnsPerStripe);
394
395 // lastly, get the row bits, no need to remove them from addr
396 row = addr % rowsPerBank;
397 } else
398 panic("Unknown address mapping policy chosen!");
399
400 assert(rank < ranksPerChannel);
401 assert(bank < banksPerRank);
402 assert(row < rowsPerBank);
403 assert(row < Bank::NO_ROW);
404
405 DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
406 dramPktAddr, rank, bank, row);
407
408 // create the corresponding DRAM packet with the entry time and
409 // ready time set to the current tick, the latter will be updated
410 // later
411 uint16_t bank_id = banksPerRank * rank + bank;
412 return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
413 size, ranks[rank]->banks[bank], *ranks[rank]);
414}
415
416void
417DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
418{
419 // only add to the read queue here. whenever the request is
420 // eventually done, set the readyTime, and call schedule()
421 assert(!pkt->isWrite());
422
423 assert(pktCount != 0);
424
425 // if the request size is larger than burst size, the pkt is split into
426 // multiple DRAM packets
427 // Note if the pkt starting address is not aligened to burst size, the
428 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
429 // are aligned to burst size boundaries. This is to ensure we accurately
430 // check read packets against packets in write queue.
431 Addr addr = pkt->getAddr();
432 unsigned pktsServicedByWrQ = 0;
433 BurstHelper* burst_helper = NULL;
434 for (int cnt = 0; cnt < pktCount; ++cnt) {
435 unsigned size = std::min((addr | (burstSize - 1)) + 1,
436 pkt->getAddr() + pkt->getSize()) - addr;
437 readPktSize[ceilLog2(size)]++;
438 readBursts++;
439
440 // First check write buffer to see if the data is already at
441 // the controller
442 bool foundInWrQ = false;
443 Addr burst_addr = burstAlign(addr);
444 // if the burst address is not present then there is no need
445 // looking any further
446 if (isInWriteQueue.find(burst_addr) != isInWriteQueue.end()) {
447 for (const auto& p : writeQueue) {
448 // check if the read is subsumed in the write queue
449 // packet we are looking at
450 if (p->addr <= addr && (addr + size) <= (p->addr + p->size)) {
451 foundInWrQ = true;
452 servicedByWrQ++;
453 pktsServicedByWrQ++;
454 DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
455 "write queue\n", addr, size);
456 bytesReadWrQ += burstSize;
457 break;
458 }
459 }
460 }
461
462 // If not found in the write q, make a DRAM packet and
463 // push it onto the read queue
464 if (!foundInWrQ) {
465
466 // Make the burst helper for split packets
467 if (pktCount > 1 && burst_helper == NULL) {
468 DPRINTF(DRAM, "Read to addr %lld translates to %d "
469 "dram requests\n", pkt->getAddr(), pktCount);
470 burst_helper = new BurstHelper(pktCount);
471 }
472
473 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
474 dram_pkt->burstHelper = burst_helper;
475
476 assert(!readQueueFull(1));
477 rdQLenPdf[readQueue.size() + respQueue.size()]++;
478
479 DPRINTF(DRAM, "Adding to read queue\n");
480
481 readQueue.push_back(dram_pkt);
482
483 // Update stats
484 avgRdQLen = readQueue.size() + respQueue.size();
485 }
486
487 // Starting address of next dram pkt (aligend to burstSize boundary)
488 addr = (addr | (burstSize - 1)) + 1;
489 }
490
491 // If all packets are serviced by write queue, we send the repsonse back
492 if (pktsServicedByWrQ == pktCount) {
493 accessAndRespond(pkt, frontendLatency);
494 return;
495 }
496
497 // Update how many split packets are serviced by write queue
498 if (burst_helper != NULL)
499 burst_helper->burstsServiced = pktsServicedByWrQ;
500
501 // If we are not already scheduled to get a request out of the
502 // queue, do so now
503 if (!nextReqEvent.scheduled()) {
504 DPRINTF(DRAM, "Request scheduled immediately\n");
505 schedule(nextReqEvent, curTick());
506 }
507}
508
509void
510DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
511{
512 // only add to the write queue here. whenever the request is
513 // eventually done, set the readyTime, and call schedule()
514 assert(pkt->isWrite());
515
516 // if the request size is larger than burst size, the pkt is split into
517 // multiple DRAM packets
518 Addr addr = pkt->getAddr();
519 for (int cnt = 0; cnt < pktCount; ++cnt) {
520 unsigned size = std::min((addr | (burstSize - 1)) + 1,
521 pkt->getAddr() + pkt->getSize()) - addr;
522 writePktSize[ceilLog2(size)]++;
523 writeBursts++;
524
525 // see if we can merge with an existing item in the write
526 // queue and keep track of whether we have merged or not
527 bool merged = isInWriteQueue.find(burstAlign(addr)) !=
528 isInWriteQueue.end();
529
530 // if the item was not merged we need to create a new write
531 // and enqueue it
532 if (!merged) {
533 DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
534
535 assert(writeQueue.size() < writeBufferSize);
536 wrQLenPdf[writeQueue.size()]++;
537
538 DPRINTF(DRAM, "Adding to write queue\n");
539
540 writeQueue.push_back(dram_pkt);
541 isInWriteQueue.insert(burstAlign(addr));
542 assert(writeQueue.size() == isInWriteQueue.size());
543
544 // Update stats
545 avgWrQLen = writeQueue.size();
546 } else {
547 DPRINTF(DRAM, "Merging write burst with existing queue entry\n");
548
549 // keep track of the fact that this burst effectively
550 // disappeared as it was merged with an existing one
551 mergedWrBursts++;
552 }
553
554 // Starting address of next dram pkt (aligend to burstSize boundary)
555 addr = (addr | (burstSize - 1)) + 1;
556 }
557
558 // we do not wait for the writes to be send to the actual memory,
559 // but instead take responsibility for the consistency here and
560 // snoop the write queue for any upcoming reads
561 // @todo, if a pkt size is larger than burst size, we might need a
562 // different front end latency
563 accessAndRespond(pkt, frontendLatency);
564
565 // If we are not already scheduled to get a request out of the
566 // queue, do so now
567 if (!nextReqEvent.scheduled()) {
568 DPRINTF(DRAM, "Request scheduled immediately\n");
569 schedule(nextReqEvent, curTick());
570 }
571}
572
573void
574DRAMCtrl::printQs() const {
575 DPRINTF(DRAM, "===READ QUEUE===\n\n");
576 for (auto i = readQueue.begin() ; i != readQueue.end() ; ++i) {
577 DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
578 }
579 DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
580 for (auto i = respQueue.begin() ; i != respQueue.end() ; ++i) {
581 DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
582 }
583 DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
584 for (auto i = writeQueue.begin() ; i != writeQueue.end() ; ++i) {
585 DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
586 }
587}
588
589bool
590DRAMCtrl::recvTimingReq(PacketPtr pkt)
591{
592 // This is where we enter from the outside world
593 DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
594 pkt->cmdString(), pkt->getAddr(), pkt->getSize());
595
596 panic_if(pkt->cacheResponding(), "Should not see packets where cache "
597 "is responding");
598
599 panic_if(!(pkt->isRead() || pkt->isWrite()),
600 "Should only see read and writes at memory controller\n");
601
602 // Calc avg gap between requests
603 if (prevArrival != 0) {
604 totGap += curTick() - prevArrival;
605 }
606 prevArrival = curTick();
607
608
609 // Find out how many dram packets a pkt translates to
610 // If the burst size is equal or larger than the pkt size, then a pkt
611 // translates to only one dram packet. Otherwise, a pkt translates to
612 // multiple dram packets
613 unsigned size = pkt->getSize();
614 unsigned offset = pkt->getAddr() & (burstSize - 1);
615 unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
616
617 // check local buffers and do not accept if full
618 if (pkt->isRead()) {
619 assert(size != 0);
620 if (readQueueFull(dram_pkt_count)) {
621 DPRINTF(DRAM, "Read queue full, not accepting\n");
622 // remember that we have to retry this port
623 retryRdReq = true;
624 numRdRetry++;
625 return false;
626 } else {
627 addToReadQueue(pkt, dram_pkt_count);
628 readReqs++;
629 bytesReadSys += size;
630 }
631 } else {
632 assert(pkt->isWrite());
633 assert(size != 0);
634 if (writeQueueFull(dram_pkt_count)) {
635 DPRINTF(DRAM, "Write queue full, not accepting\n");
636 // remember that we have to retry this port
637 retryWrReq = true;
638 numWrRetry++;
639 return false;
640 } else {
641 addToWriteQueue(pkt, dram_pkt_count);
642 writeReqs++;
643 bytesWrittenSys += size;
644 }
645 }
646
647 return true;
648}
649
650void
651DRAMCtrl::processRespondEvent()
652{
653 DPRINTF(DRAM,
654 "processRespondEvent(): Some req has reached its readyTime\n");
655
656 DRAMPacket* dram_pkt = respQueue.front();
657
658 if (dram_pkt->burstHelper) {
659 // it is a split packet
660 dram_pkt->burstHelper->burstsServiced++;
661 if (dram_pkt->burstHelper->burstsServiced ==
662 dram_pkt->burstHelper->burstCount) {
663 // we have now serviced all children packets of a system packet
664 // so we can now respond to the requester
665 // @todo we probably want to have a different front end and back
666 // end latency for split packets
667 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
668 delete dram_pkt->burstHelper;
669 dram_pkt->burstHelper = NULL;
670 }
671 } else {
672 // it is not a split packet
673 accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
674 }
675
676 delete respQueue.front();
677 respQueue.pop_front();
678
679 if (!respQueue.empty()) {
680 assert(respQueue.front()->readyTime >= curTick());
681 assert(!respondEvent.scheduled());
682 schedule(respondEvent, respQueue.front()->readyTime);
683 } else {
684 // if there is nothing left in any queue, signal a drain
685 if (drainState() == DrainState::Draining &&
686 writeQueue.empty() && readQueue.empty()) {
687
688 DPRINTF(Drain, "DRAM controller done draining\n");
689 signalDrainDone();
690 }
691 }
692
693 // We have made a location in the queue available at this point,
694 // so if there is a read that was forced to wait, retry now
695 if (retryRdReq) {
696 retryRdReq = false;
697 port.sendRetryReq();
698 }
699}
700
701bool
702DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
703{
704 // This method does the arbitration between requests. The chosen
705 // packet is simply moved to the head of the queue. The other
706 // methods know that this is the place to look. For example, with
707 // FCFS, this method does nothing
708 assert(!queue.empty());
709
710 // bool to indicate if a packet to an available rank is found
711 bool found_packet = false;
712 if (queue.size() == 1) {
713 DRAMPacket* dram_pkt = queue.front();
714 // available rank corresponds to state refresh idle
715 if (ranks[dram_pkt->rank]->isAvailable()) {
716 found_packet = true;
717 DPRINTF(DRAM, "Single request, going to a free rank\n");
718 } else {
719 DPRINTF(DRAM, "Single request, going to a busy rank\n");
720 }
721 return found_packet;
722 }
723
724 if (memSchedPolicy == Enums::fcfs) {
725 // check if there is a packet going to a free rank
726 for (auto i = queue.begin(); i != queue.end() ; ++i) {
727 DRAMPacket* dram_pkt = *i;
728 if (ranks[dram_pkt->rank]->isAvailable()) {
729 queue.erase(i);
730 queue.push_front(dram_pkt);
731 found_packet = true;
732 break;
733 }
734 }
735 } else if (memSchedPolicy == Enums::frfcfs) {
736 found_packet = reorderQueue(queue, extra_col_delay);
737 } else
738 panic("No scheduling policy chosen\n");
739 return found_packet;
740}
741
742bool
743DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, Tick extra_col_delay)
744{
745 // Only determine this if needed
746 uint64_t earliest_banks = 0;
747 bool hidden_bank_prep = false;
748
749 // search for seamless row hits first, if no seamless row hit is
750 // found then determine if there are other packets that can be issued
751 // without incurring additional bus delay due to bank timing
752 // Will select closed rows first to enable more open row possibilies
753 // in future selections
754 bool found_hidden_bank = false;
755
756 // remember if we found a row hit, not seamless, but bank prepped
757 // and ready
758 bool found_prepped_pkt = false;
759
760 // if we have no row hit, prepped or not, and no seamless packet,
761 // just go for the earliest possible
762 bool found_earliest_pkt = false;
763
764 auto selected_pkt_it = queue.end();
765
766 // time we need to issue a column command to be seamless
767 const Tick min_col_at = std::max(busBusyUntil - tCL + extra_col_delay,
768 curTick());
769
770 for (auto i = queue.begin(); i != queue.end() ; ++i) {
771 DRAMPacket* dram_pkt = *i;
772 const Bank& bank = dram_pkt->bankRef;
773
774 // check if rank is available, if not, jump to the next packet
775 if (dram_pkt->rankRef.isAvailable()) {
776 // check if it is a row hit
777 if (bank.openRow == dram_pkt->row) {
778 // no additional rank-to-rank or same bank-group
779 // delays, or we switched read/write and might as well
780 // go for the row hit
781 if (bank.colAllowedAt <= min_col_at) {
782 // FCFS within the hits, giving priority to
783 // commands that can issue seamlessly, without
784 // additional delay, such as same rank accesses
785 // and/or different bank-group accesses
786 DPRINTF(DRAM, "Seamless row buffer hit\n");
787 selected_pkt_it = i;
788 // no need to look through the remaining queue entries
789 break;
790 } else if (!found_hidden_bank && !found_prepped_pkt) {
791 // if we did not find a packet to a closed row that can
792 // issue the bank commands without incurring delay, and
793 // did not yet find a packet to a prepped row, remember
794 // the current one
795 selected_pkt_it = i;
796 found_prepped_pkt = true;
797 DPRINTF(DRAM, "Prepped row buffer hit\n");
798 }
799 } else if (!found_earliest_pkt) {
800 // if we have not initialised the bank status, do it
801 // now, and only once per scheduling decisions
802 if (earliest_banks == 0) {
803 // determine entries with earliest bank delay
804 pair<uint64_t, bool> bankStatus =
805 minBankPrep(queue, min_col_at);
806 earliest_banks = bankStatus.first;
807 hidden_bank_prep = bankStatus.second;
808 }
809
810 // bank is amongst first available banks
811 // minBankPrep will give priority to packets that can
812 // issue seamlessly
813 if (bits(earliest_banks, dram_pkt->bankId, dram_pkt->bankId)) {
814 found_earliest_pkt = true;
815 found_hidden_bank = hidden_bank_prep;
816
817 // give priority to packets that can issue
818 // bank commands 'behind the scenes'
819 // any additional delay if any will be due to
820 // col-to-col command requirements
821 if (hidden_bank_prep || !found_prepped_pkt)
822 selected_pkt_it = i;
823 }
824 }
825 }
826 }
827
828 if (selected_pkt_it != queue.end()) {
829 DRAMPacket* selected_pkt = *selected_pkt_it;
830 queue.erase(selected_pkt_it);
831 queue.push_front(selected_pkt);
832 return true;
833 }
834
835 return false;
836}
837
838void
839DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
840{
841 DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
842
843 bool needsResponse = pkt->needsResponse();
844 // do the actual memory access which also turns the packet into a
845 // response
846 access(pkt);
847
848 // turn packet around to go back to requester if response expected
849 if (needsResponse) {
850 // access already turned the packet into a response
851 assert(pkt->isResponse());
852 // response_time consumes the static latency and is charged also
853 // with headerDelay that takes into account the delay provided by
854 // the xbar and also the payloadDelay that takes into account the
855 // number of data beats.
856 Tick response_time = curTick() + static_latency + pkt->headerDelay +
857 pkt->payloadDelay;
858 // Here we reset the timing of the packet before sending it out.
859 pkt->headerDelay = pkt->payloadDelay = 0;
860
861 // queue the packet in the response queue to be sent out after
862 // the static latency has passed
863 port.schedTimingResp(pkt, response_time, true);
864 } else {
865 // @todo the packet is going to be deleted, and the DRAMPacket
866 // is still having a pointer to it
867 pendingDelete.reset(pkt);
868 }
869
870 DPRINTF(DRAM, "Done\n");
871
872 return;
873}
874
875void
876DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref,
877 Tick act_tick, uint32_t row)
878{
879 assert(rank_ref.actTicks.size() == activationLimit);
880
881 DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
882
883 // update the open row
884 assert(bank_ref.openRow == Bank::NO_ROW);
885 bank_ref.openRow = row;
886
887 // start counting anew, this covers both the case when we
888 // auto-precharged, and when this access is forced to
889 // precharge
890 bank_ref.bytesAccessed = 0;
891 bank_ref.rowAccesses = 0;
892
893 ++rank_ref.numBanksActive;
894 assert(rank_ref.numBanksActive <= banksPerRank);
895
896 DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
897 bank_ref.bank, rank_ref.rank, act_tick,
898 ranks[rank_ref.rank]->numBanksActive);
899
900 rank_ref.power.powerlib.doCommand(MemCommand::ACT, bank_ref.bank,
901 divCeil(act_tick, tCK) -
902 timeStampOffset);
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.power.powerlib.doCommand(MemCommand::PRE, bank.bank,
1005 divCeil(pre_at, tCK) -
1006 timeStampOffset);
1007 DPRINTF(DRAMPower, "%llu,PRE,%d,%d\n", divCeil(pre_at, tCK) -
1008 timeStampOffset, bank.bank, rank_ref.rank);
1009 }
1010 // if we look at the current number of active banks we might be
1011 // tempted to think the DRAM is now idle, however this can be
1012 // undone by an activate that is scheduled to happen before we
1013 // would have reached the idle state, so schedule an event and
1014 // rather check once we actually make it to the point in time when
1015 // the (last) precharge takes place
1016 if (!rank_ref.prechargeEvent.scheduled())
1017 schedule(rank_ref.prechargeEvent, pre_done_at);
1018 else if (rank_ref.prechargeEvent.when() < pre_done_at)
1019 reschedule(rank_ref.prechargeEvent, pre_done_at);
1020}
1021
1022void
1023DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
1024{
1025 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1026 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1027
1028 // get the rank
1029 Rank& rank = dram_pkt->rankRef;
1030
1031 // get the bank
1032 Bank& bank = dram_pkt->bankRef;
1033
1034 // for the state we need to track if it is a row hit or not
1035 bool row_hit = true;
1036
1037 // respect any constraints on the command (e.g. tRCD or tCCD)
1038 Tick cmd_at = std::max(bank.colAllowedAt, curTick());
1039
1040 // Determine the access latency and update the bank state
1041 if (bank.openRow == dram_pkt->row) {
1042 // nothing to do
1043 } else {
1044 row_hit = false;
1045
1046 // If there is a page open, precharge it.
1047 if (bank.openRow != Bank::NO_ROW) {
1048 prechargeBank(rank, bank, std::max(bank.preAllowedAt, curTick()));
1049 }
1050
1051 // next we need to account for the delay in activating the
1052 // page
1053 Tick act_tick = std::max(bank.actAllowedAt, curTick());
1054
1055 // Record the activation and deal with all the global timing
1056 // constraints caused be a new activation (tRRD and tXAW)
1057 activateBank(rank, bank, act_tick, dram_pkt->row);
1058
1059 // issue the command as early as possible
1060 cmd_at = bank.colAllowedAt;
1061 }
1062
1063 // we need to wait until the bus is available before we can issue
1064 // the command
1065 cmd_at = std::max(cmd_at, busBusyUntil - tCL);
1066
1067 // update the packet ready time
1068 dram_pkt->readyTime = cmd_at + tCL + tBURST;
1069
1070 // only one burst can use the bus at any one point in time
1071 assert(dram_pkt->readyTime - busBusyUntil >= tBURST);
1072
1073 // update the time for the next read/write burst for each
1074 // bank (add a max with tCCD/tCCD_L here)
1075 Tick cmd_dly;
1076 for (int j = 0; j < ranksPerChannel; j++) {
1077 for (int i = 0; i < banksPerRank; i++) {
1078 // next burst to same bank group in this rank must not happen
1079 // before tCCD_L. Different bank group timing requirement is
1080 // tBURST; Add tCS for different ranks
1081 if (dram_pkt->rank == j) {
1082 if (bankGroupArch &&
1083 (bank.bankgr == ranks[j]->banks[i].bankgr)) {
1084 // bank group architecture requires longer delays between
1085 // RD/WR burst commands to the same bank group.
1086 // Use tCCD_L in this case
1087 cmd_dly = tCCD_L;
1088 } else {
1089 // use tBURST (equivalent to tCCD_S), the shorter
1090 // cas-to-cas delay value, when either:
1091 // 1) bank group architecture is not supportted
1092 // 2) bank is in a different bank group
1093 cmd_dly = tBURST;
1094 }
1095 } else {
1096 // different rank is by default in a different bank group
1097 // use tBURST (equivalent to tCCD_S), which is the shorter
1098 // cas-to-cas delay in this case
1099 // Add tCS to account for rank-to-rank bus delay requirements
1100 cmd_dly = tBURST + tCS;
1101 }
1102 ranks[j]->banks[i].colAllowedAt = std::max(cmd_at + cmd_dly,
1103 ranks[j]->banks[i].colAllowedAt);
1104 }
1105 }
1106
1107 // Save rank of current access
1108 activeRank = dram_pkt->rank;
1109
1110 // If this is a write, we also need to respect the write recovery
1111 // time before a precharge, in the case of a read, respect the
1112 // read to precharge constraint
1113 bank.preAllowedAt = std::max(bank.preAllowedAt,
1114 dram_pkt->isRead ? cmd_at + tRTP :
1115 dram_pkt->readyTime + tWR);
1116
1117 // increment the bytes accessed and the accesses per row
1118 bank.bytesAccessed += burstSize;
1119 ++bank.rowAccesses;
1120
1121 // if we reached the max, then issue with an auto-precharge
1122 bool auto_precharge = pageMgmt == Enums::close ||
1123 bank.rowAccesses == maxAccessesPerRow;
1124
1125 // if we did not hit the limit, we might still want to
1126 // auto-precharge
1127 if (!auto_precharge &&
1128 (pageMgmt == Enums::open_adaptive ||
1129 pageMgmt == Enums::close_adaptive)) {
1130 // a twist on the open and close page policies:
1131 // 1) open_adaptive page policy does not blindly keep the
1132 // page open, but close it if there are no row hits, and there
1133 // are bank conflicts in the queue
1134 // 2) close_adaptive page policy does not blindly close the
1135 // page, but closes it only if there are no row hits in the queue.
1136 // In this case, only force an auto precharge when there
1137 // are no same page hits in the queue
1138 bool got_more_hits = false;
1139 bool got_bank_conflict = false;
1140
1141 // either look at the read queue or write queue
1142 const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
1143 writeQueue;
1144 auto p = queue.begin();
1145 // make sure we are not considering the packet that we are
1146 // currently dealing with (which is the head of the queue)
1147 ++p;
1148
1149 // keep on looking until we find a hit or reach the end of the queue
1150 // 1) if a hit is found, then both open and close adaptive policies keep
1151 // the page open
1152 // 2) if no hit is found, got_bank_conflict is set to true if a bank
1153 // conflict request is waiting in the queue
1154 while (!got_more_hits && p != queue.end()) {
1155 bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
1156 (dram_pkt->bank == (*p)->bank);
1157 bool same_row = dram_pkt->row == (*p)->row;
1158 got_more_hits |= same_rank_bank && same_row;
1159 got_bank_conflict |= same_rank_bank && !same_row;
1160 ++p;
1161 }
1162
1163 // auto pre-charge when either
1164 // 1) open_adaptive policy, we have not got any more hits, and
1165 // have a bank conflict
1166 // 2) close_adaptive policy and we have not got any more hits
1167 auto_precharge = !got_more_hits &&
1168 (got_bank_conflict || pageMgmt == Enums::close_adaptive);
1169 }
1170
1171 // DRAMPower trace command to be written
1172 std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR";
1173
1174 // MemCommand required for DRAMPower library
1175 MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD :
1176 MemCommand::WR;
1177
1178 // if this access should use auto-precharge, then we are
1179 // closing the row
1180 if (auto_precharge) {
1181 // if auto-precharge push a PRE command at the correct tick to the
1182 // list used by DRAMPower library to calculate power
1183 prechargeBank(rank, bank, std::max(curTick(), bank.preAllowedAt));
1184
1185 DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId);
1186 }
1187
1188 // Update bus state
1189 busBusyUntil = dram_pkt->readyTime;
1190
1191 DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n",
1192 dram_pkt->addr, dram_pkt->readyTime, busBusyUntil);
1193
1194 dram_pkt->rankRef.power.powerlib.doCommand(command, dram_pkt->bank,
1195 divCeil(cmd_at, tCK) -
1196 timeStampOffset);
1197
1198 DPRINTF(DRAMPower, "%llu,%s,%d,%d\n", divCeil(cmd_at, tCK) -
1199 timeStampOffset, mem_cmd, dram_pkt->bank, dram_pkt->rank);
1200
1201 // Update the minimum timing between the requests, this is a
1202 // conservative estimate of when we have to schedule the next
1203 // request to not introduce any unecessary bubbles. In most cases
1204 // we will wake up sooner than we have to.
1205 nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
1206
1207 // Update the stats and schedule the next request
1208 if (dram_pkt->isRead) {
1209 ++readsThisTime;
1210 if (row_hit)
1211 readRowHits++;
1212 bytesReadDRAM += burstSize;
1213 perBankRdBursts[dram_pkt->bankId]++;
1214
1215 // Update latency stats
1216 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1217 totBusLat += tBURST;
1218 totQLat += cmd_at - dram_pkt->entryTime;
1219 } else {
1220 ++writesThisTime;
1221 if (row_hit)
1222 writeRowHits++;
1223 bytesWritten += burstSize;
1224 perBankWrBursts[dram_pkt->bankId]++;
1225 }
1226}
1227
1228void
1229DRAMCtrl::processNextReqEvent()
1230{
1231 int busyRanks = 0;
1232 for (auto r : ranks) {
1233 if (!r->isAvailable()) {
1234 // rank is busy refreshing
1235 busyRanks++;
1236
1237 // let the rank know that if it was waiting to drain, it
1238 // is now done and ready to proceed
1239 r->checkDrainDone();
1240 }
1241 }
1242
1243 if (busyRanks == ranksPerChannel) {
1244 // if all ranks are refreshing wait for them to finish
1245 // and stall this state machine without taking any further
1246 // action, and do not schedule a new nextReqEvent
1247 return;
1248 }
1249
1250 // pre-emptively set to false. Overwrite if in READ_TO_WRITE
1251 // or WRITE_TO_READ state
1252 bool switched_cmd_type = false;
1253 if (busState == READ_TO_WRITE) {
1254 DPRINTF(DRAM, "Switching to writes after %d reads with %d reads "
1255 "waiting\n", readsThisTime, readQueue.size());
1256
1257 // sample and reset the read-related stats as we are now
1258 // transitioning to writes, and all reads are done
1259 rdPerTurnAround.sample(readsThisTime);
1260 readsThisTime = 0;
1261
1262 // now proceed to do the actual writes
1263 busState = WRITE;
1264 switched_cmd_type = true;
1265 } else if (busState == WRITE_TO_READ) {
1266 DPRINTF(DRAM, "Switching to reads after %d writes with %d writes "
1267 "waiting\n", writesThisTime, writeQueue.size());
1268
1269 wrPerTurnAround.sample(writesThisTime);
1270 writesThisTime = 0;
1271
1272 busState = READ;
1273 switched_cmd_type = true;
1274 }
1275
1276 // when we get here it is either a read or a write
1277 if (busState == READ) {
1278
1279 // track if we should switch or not
1280 bool switch_to_writes = false;
1281
1282 if (readQueue.empty()) {
1283 // In the case there is no read request to go next,
1284 // trigger writes if we have passed the low threshold (or
1285 // if we are draining)
1286 if (!writeQueue.empty() &&
1287 (drainState() == DrainState::Draining ||
1288 writeQueue.size() > writeLowThreshold)) {
1289
1290 switch_to_writes = true;
1291 } else {
1292 // check if we are drained
1293 if (drainState() == DrainState::Draining &&
1294 respQueue.empty()) {
1295
1296 DPRINTF(Drain, "DRAM controller done draining\n");
1297 signalDrainDone();
1298 }
1299
1300 // nothing to do, not even any point in scheduling an
1301 // event for the next request
1302 return;
1303 }
1304 } else {
1305 // bool to check if there is a read to a free rank
1306 bool found_read = false;
1307
1308 // Figure out which read request goes next, and move it to the
1309 // front of the read queue
1310 // If we are changing command type, incorporate the minimum
1311 // bus turnaround delay which will be tCS (different rank) case
1312 found_read = chooseNext(readQueue,
1313 switched_cmd_type ? tCS : 0);
1314
1315 // if no read to an available rank is found then return
1316 // at this point. There could be writes to the available ranks
1317 // which are above the required threshold. However, to
1318 // avoid adding more complexity to the code, return and wait
1319 // for a refresh event to kick things into action again.
1320 if (!found_read)
1321 return;
1322
1323 DRAMPacket* dram_pkt = readQueue.front();
1324 assert(dram_pkt->rankRef.isAvailable());
1325 // here we get a bit creative and shift the bus busy time not
1326 // just the tWTR, but also a CAS latency to capture the fact
1327 // that we are allowed to prepare a new bank, but not issue a
1328 // read command until after tWTR, in essence we capture a
1329 // bubble on the data bus that is tWTR + tCL
1330 if (switched_cmd_type && dram_pkt->rank == activeRank) {
1331 busBusyUntil += tWTR + tCL;
1332 }
1333
1334 doDRAMAccess(dram_pkt);
1335
1336 // At this point we're done dealing with the request
1337 readQueue.pop_front();
1338
1339 // sanity check
1340 assert(dram_pkt->size <= burstSize);
1341 assert(dram_pkt->readyTime >= curTick());
1342
1343 // Insert into response queue. It will be sent back to the
1344 // requestor at its readyTime
1345 if (respQueue.empty()) {
1346 assert(!respondEvent.scheduled());
1347 schedule(respondEvent, dram_pkt->readyTime);
1348 } else {
1349 assert(respQueue.back()->readyTime <= dram_pkt->readyTime);
1350 assert(respondEvent.scheduled());
1351 }
1352
1353 respQueue.push_back(dram_pkt);
1354
1355 // we have so many writes that we have to transition
1356 if (writeQueue.size() > writeHighThreshold) {
1357 switch_to_writes = true;
1358 }
1359 }
1360
1361 // switching to writes, either because the read queue is empty
1362 // and the writes have passed the low threshold (or we are
1363 // draining), or because the writes hit the hight threshold
1364 if (switch_to_writes) {
1365 // transition to writing
1366 busState = READ_TO_WRITE;
1367 }
1368 } else {
1369 // bool to check if write to free rank is found
1370 bool found_write = false;
1371
1372 // If we are changing command type, incorporate the minimum
1373 // bus turnaround delay
1374 found_write = chooseNext(writeQueue,
1375 switched_cmd_type ? std::min(tRTW, tCS) : 0);
1376
1377 // if no writes to an available rank are found then return.
1378 // There could be reads to the available ranks. However, to avoid
1379 // adding more complexity to the code, return at this point and wait
1380 // for a refresh event to kick things into action again.
1381 if (!found_write)
1382 return;
1383
1384 DRAMPacket* dram_pkt = writeQueue.front();
1385 assert(dram_pkt->rankRef.isAvailable());
1386 // sanity check
1387 assert(dram_pkt->size <= burstSize);
1388
1389 // add a bubble to the data bus, as defined by the
1390 // tRTW when access is to the same rank as previous burst
1391 // Different rank timing is handled with tCS, which is
1392 // applied to colAllowedAt
1393 if (switched_cmd_type && dram_pkt->rank == activeRank) {
1394 busBusyUntil += tRTW;
1395 }
1396
1397 doDRAMAccess(dram_pkt);
1398
1399 writeQueue.pop_front();
1400 isInWriteQueue.erase(burstAlign(dram_pkt->addr));
1401 delete dram_pkt;
1402
1403 // If we emptied the write queue, or got sufficiently below the
1404 // threshold (using the minWritesPerSwitch as the hysteresis) and
1405 // are not draining, or we have reads waiting and have done enough
1406 // writes, then switch to reads.
1407 if (writeQueue.empty() ||
1408 (writeQueue.size() + minWritesPerSwitch < writeLowThreshold &&
1409 drainState() != DrainState::Draining) ||
1410 (!readQueue.empty() && writesThisTime >= minWritesPerSwitch)) {
1411 // turn the bus back around for reads again
1412 busState = WRITE_TO_READ;
1413
1414 // note that the we switch back to reads also in the idle
1415 // case, which eventually will check for any draining and
1416 // also pause any further scheduling if there is really
1417 // nothing to do
1418 }
1419 }
1420 // It is possible that a refresh to another rank kicks things back into
1421 // action before reaching this point.
1422 if (!nextReqEvent.scheduled())
1423 schedule(nextReqEvent, std::max(nextReqTime, curTick()));
1424
1425 // If there is space available and we have writes waiting then let
1426 // them retry. This is done here to ensure that the retry does not
1427 // cause a nextReqEvent to be scheduled before we do so as part of
1428 // the next request processing
1429 if (retryWrReq && writeQueue.size() < writeBufferSize) {
1430 retryWrReq = false;
1431 port.sendRetryReq();
1432 }
1433}
1434
1435pair<uint64_t, bool>
1436DRAMCtrl::minBankPrep(const deque<DRAMPacket*>& queue,
1437 Tick min_col_at) const
1438{
1439 uint64_t bank_mask = 0;
1440 Tick min_act_at = MaxTick;
1441
1442 // latest Tick for which ACT can occur without incurring additoinal
1443 // delay on the data bus
1444 const Tick hidden_act_max = std::max(min_col_at - tRCD, curTick());
1445
1446 // Flag condition when burst can issue back-to-back with previous burst
1447 bool found_seamless_bank = false;
1448
1449 // Flag condition when bank can be opened without incurring additional
1450 // delay on the data bus
1451 bool hidden_bank_prep = false;
1452
1453 // determine if we have queued transactions targetting the
1454 // bank in question
1455 vector<bool> got_waiting(ranksPerChannel * banksPerRank, false);
1456 for (const auto& p : queue) {
1457 if (p->rankRef.isAvailable())
1458 got_waiting[p->bankId] = true;
1459 }
1460
1461 // Find command with optimal bank timing
1462 // Will prioritize commands that can issue seamlessly.
1463 for (int i = 0; i < ranksPerChannel; i++) {
1464 for (int j = 0; j < banksPerRank; j++) {
1465 uint16_t bank_id = i * banksPerRank + j;
1466
1467 // if we have waiting requests for the bank, and it is
1468 // amongst the first available, update the mask
1469 if (got_waiting[bank_id]) {
1470 // make sure this rank is not currently refreshing.
1471 assert(ranks[i]->isAvailable());
1472 // simplistic approximation of when the bank can issue
1473 // an activate, ignoring any rank-to-rank switching
1474 // cost in this calculation
1475 Tick act_at = ranks[i]->banks[j].openRow == Bank::NO_ROW ?
1476 std::max(ranks[i]->banks[j].actAllowedAt, curTick()) :
1477 std::max(ranks[i]->banks[j].preAllowedAt, curTick()) + tRP;
1478
1479 // When is the earliest the R/W burst can issue?
1480 Tick col_at = std::max(ranks[i]->banks[j].colAllowedAt,
1481 act_at + tRCD);
1482
1483 // bank can issue burst back-to-back (seamlessly) with
1484 // previous burst
1485 bool new_seamless_bank = col_at <= min_col_at;
1486
1487 // if we found a new seamless bank or we have no
1488 // seamless banks, and got a bank with an earlier
1489 // activate time, it should be added to the bit mask
1490 if (new_seamless_bank ||
1491 (!found_seamless_bank && act_at <= min_act_at)) {
1492 // if we did not have a seamless bank before, and
1493 // we do now, reset the bank mask, also reset it
1494 // if we have not yet found a seamless bank and
1495 // the activate time is smaller than what we have
1496 // seen so far
1497 if (!found_seamless_bank &&
1498 (new_seamless_bank || act_at < min_act_at)) {
1499 bank_mask = 0;
1500 }
1501
1502 found_seamless_bank |= new_seamless_bank;
1503
1504 // ACT can occur 'behind the scenes'
1505 hidden_bank_prep = act_at <= hidden_act_max;
1506
1507 // set the bit corresponding to the available bank
1508 replaceBits(bank_mask, bank_id, bank_id, 1);
1509 min_act_at = act_at;
1510 }
1511 }
1512 }
1513 }
1514
1515 return make_pair(bank_mask, hidden_bank_prep);
1516}
1517
1518DRAMCtrl::Rank::Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p)
1519 : EventManager(&_memory), memory(_memory),
1520 pwrStateTrans(PWR_IDLE), pwrState(PWR_IDLE), pwrStateTick(0),
1521 refreshState(REF_IDLE), refreshDueAt(0),
1522 power(_p, false), numBanksActive(0),
1523 activateEvent(*this), prechargeEvent(*this),
1524 refreshEvent(*this), powerEvent(*this)
1525{ }
1526
1527void
1528DRAMCtrl::Rank::startup(Tick ref_tick)
1529{
1530 assert(ref_tick > curTick());
1531
1532 pwrStateTick = curTick();
1533
1534 // kick off the refresh, and give ourselves enough time to
1535 // precharge
1536 schedule(refreshEvent, ref_tick);
1537}
1538
1539void
1540DRAMCtrl::Rank::suspend()
1541{
1542 deschedule(refreshEvent);
1543}
1544
1545void
1546DRAMCtrl::Rank::checkDrainDone()
1547{
1548 // if this rank was waiting to drain it is now able to proceed to
1549 // precharge
1550 if (refreshState == REF_DRAIN) {
1551 DPRINTF(DRAM, "Refresh drain done, now precharging\n");
1552
1553 refreshState = REF_PRE;
1554
1555 // hand control back to the refresh event loop
1556 schedule(refreshEvent, curTick());
1557 }
1558}
1559
1560void
1561DRAMCtrl::Rank::processActivateEvent()
1562{
1563 // we should transition to the active state as soon as any bank is active
1564 if (pwrState != PWR_ACT)
1565 // note that at this point numBanksActive could be back at
1566 // zero again due to a precharge scheduled in the future
1567 schedulePowerEvent(PWR_ACT, curTick());
1568}
1569
1570void
1571DRAMCtrl::Rank::processPrechargeEvent()
1572{
1573 // if we reached zero, then special conditions apply as we track
1574 // if all banks are precharged for the power models
1575 if (numBanksActive == 0) {
1576 // we should transition to the idle state when the last bank
1577 // is precharged
1578 schedulePowerEvent(PWR_IDLE, curTick());
1579 }
1580}
1581
1582void
1583DRAMCtrl::Rank::processRefreshEvent()
1584{
1585 // when first preparing the refresh, remember when it was due
1586 if (refreshState == REF_IDLE) {
1587 // remember when the refresh is due
1588 refreshDueAt = curTick();
1589
1590 // proceed to drain
1591 refreshState = REF_DRAIN;
1592
1593 DPRINTF(DRAM, "Refresh due\n");
1594 }
1595
1596 // let any scheduled read or write to the same rank go ahead,
1597 // after which it will
1598 // hand control back to this event loop
1599 if (refreshState == REF_DRAIN) {
1600 // if a request is at the moment being handled and this request is
1601 // accessing the current rank then wait for it to finish
1602 if ((rank == memory.activeRank)
1603 && (memory.nextReqEvent.scheduled())) {
1604 // hand control over to the request loop until it is
1605 // evaluated next
1606 DPRINTF(DRAM, "Refresh awaiting draining\n");
1607
1608 return;
1609 } else {
1610 refreshState = REF_PRE;
1611 }
1612 }
1613
1614 // at this point, ensure that all banks are precharged
1615 if (refreshState == REF_PRE) {
1616 // precharge any active bank if we are not already in the idle
1617 // state
1618 if (pwrState != PWR_IDLE) {
1619 // at the moment, we use a precharge all even if there is
1620 // only a single bank open
1621 DPRINTF(DRAM, "Precharging all\n");
1622
1623 // first determine when we can precharge
1624 Tick pre_at = curTick();
1625
1626 for (auto &b : banks) {
1627 // respect both causality and any existing bank
1628 // constraints, some banks could already have a
1629 // (auto) precharge scheduled
1630 pre_at = std::max(b.preAllowedAt, pre_at);
1631 }
1632
1633 // make sure all banks per rank are precharged, and for those that
1634 // already are, update their availability
1635 Tick act_allowed_at = pre_at + memory.tRP;
1636
1637 for (auto &b : banks) {
1638 if (b.openRow != Bank::NO_ROW) {
1639 memory.prechargeBank(*this, b, pre_at, false);
1640 } else {
1641 b.actAllowedAt = std::max(b.actAllowedAt, act_allowed_at);
1642 b.preAllowedAt = std::max(b.preAllowedAt, pre_at);
1643 }
1644 }
1645
1646 // precharge all banks in rank
1647 power.powerlib.doCommand(MemCommand::PREA, 0,
1648 divCeil(pre_at, memory.tCK) -
1649 memory.timeStampOffset);
1650
1651 DPRINTF(DRAMPower, "%llu,PREA,0,%d\n",
1652 divCeil(pre_at, memory.tCK) -
1653 memory.timeStampOffset, rank);
1654 } else {
1655 DPRINTF(DRAM, "All banks already precharged, starting refresh\n");
1656
1657 // go ahead and kick the power state machine into gear if
1658 // we are already idle
1659 schedulePowerEvent(PWR_REF, curTick());
1660 }
1661
1662 refreshState = REF_RUN;
1663 assert(numBanksActive == 0);
1664
1665 // wait for all banks to be precharged, at which point the
1666 // power state machine will transition to the idle state, and
1667 // automatically move to a refresh, at that point it will also
1668 // call this method to get the refresh event loop going again
1669 return;
1670 }
1671
1672 // last but not least we perform the actual refresh
1673 if (refreshState == REF_RUN) {
1674 // should never get here with any banks active
1675 assert(numBanksActive == 0);
1676 assert(pwrState == PWR_REF);
1677
1678 Tick ref_done_at = curTick() + memory.tRFC;
1679
1680 for (auto &b : banks) {
1681 b.actAllowedAt = ref_done_at;
1682 }
1683
1684 // at the moment this affects all ranks
1685 power.powerlib.doCommand(MemCommand::REF, 0,
1686 divCeil(curTick(), memory.tCK) -
1687 memory.timeStampOffset);
1688
1689 // at the moment sort the list of commands and update the counters
1690 // for DRAMPower libray when doing a refresh
1691 sort(power.powerlib.cmdList.begin(),
1692 power.powerlib.cmdList.end(), DRAMCtrl::sortTime);
1693
1694 // update the counters for DRAMPower, passing false to
1695 // indicate that this is not the last command in the
1696 // list. DRAMPower requires this information for the
1697 // correct calculation of the background energy at the end
1698 // of the simulation. Ideally we would want to call this
1699 // function with true once at the end of the
1700 // simulation. However, the discarded energy is extremly
1701 // small and does not effect the final results.
1702 power.powerlib.updateCounters(false);
1703
1704 // call the energy function
1705 power.powerlib.calcEnergy();
1706
1707 // Update the stats
1708 updatePowerStats();
1709
1710 DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), memory.tCK) -
1711 memory.timeStampOffset, rank);
1712
1713 // make sure we did not wait so long that we cannot make up
1714 // for it
1715 if (refreshDueAt + memory.tREFI < ref_done_at) {
1716 fatal("Refresh was delayed so long we cannot catch up\n");
1717 }
1718
1719 // compensate for the delay in actually performing the refresh
1720 // when scheduling the next one
1721 schedule(refreshEvent, refreshDueAt + memory.tREFI - memory.tRP);
1722
1723 assert(!powerEvent.scheduled());
1724
1725 // move to the idle power state once the refresh is done, this
1726 // will also move the refresh state machine to the refresh
1727 // idle state
1728 schedulePowerEvent(PWR_IDLE, ref_done_at);
1729
1730 DPRINTF(DRAMState, "Refresh done at %llu and next refresh at %llu\n",
1731 ref_done_at, refreshDueAt + memory.tREFI);
1732 }
1733}
1734
1735void
1736DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state, Tick tick)
1737{
1738 // respect causality
1739 assert(tick >= curTick());
1740
1741 if (!powerEvent.scheduled()) {
1742 DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n",
1743 tick, pwr_state);
1744
1745 // insert the new transition
1746 pwrStateTrans = pwr_state;
1747
1748 schedule(powerEvent, tick);
1749 } else {
1750 panic("Scheduled power event at %llu to state %d, "
1751 "with scheduled event at %llu to %d\n", tick, pwr_state,
1752 powerEvent.when(), pwrStateTrans);
1753 }
1754}
1755
1756void
1757DRAMCtrl::Rank::processPowerEvent()
1758{
1759 // remember where we were, and for how long
1760 Tick duration = curTick() - pwrStateTick;
1761 PowerState prev_state = pwrState;
1762
1763 // update the accounting
1764 pwrStateTime[prev_state] += duration;
1765
1766 pwrState = pwrStateTrans;
1767 pwrStateTick = curTick();
1768
1769 if (pwrState == PWR_IDLE) {
1770 DPRINTF(DRAMState, "All banks precharged\n");
1771
1772 // if we were refreshing, make sure we start scheduling requests again
1773 if (prev_state == PWR_REF) {
1774 DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration);
1775 assert(pwrState == PWR_IDLE);
1776
1777 // kick things into action again
1778 refreshState = REF_IDLE;
1779 // a request event could be already scheduled by the state
1780 // machine of the other rank
1781 if (!memory.nextReqEvent.scheduled())
1782 schedule(memory.nextReqEvent, curTick());
1783 } else {
1784 assert(prev_state == PWR_ACT);
1785
1786 // if we have a pending refresh, and are now moving to
1787 // the idle state, direclty transition to a refresh
1788 if (refreshState == REF_RUN) {
1789 // there should be nothing waiting at this point
1790 assert(!powerEvent.scheduled());
1791
1792 // update the state in zero time and proceed below
1793 pwrState = PWR_REF;
1794 }
1795 }
1796 }
1797
1798 // we transition to the refresh state, let the refresh state
1799 // machine know of this state update and let it deal with the
1800 // scheduling of the next power state transition as well as the
1801 // following refresh
1802 if (pwrState == PWR_REF) {
1803 DPRINTF(DRAMState, "Refreshing\n");
1804 // kick the refresh event loop into action again, and that
1805 // in turn will schedule a transition to the idle power
1806 // state once the refresh is done
1807 assert(refreshState == REF_RUN);
1808 processRefreshEvent();
1809 }
1810}
1811
1812void
1813DRAMCtrl::Rank::updatePowerStats()
1814{
1815 // Get the energy and power from DRAMPower
1816 Data::MemoryPowerModel::Energy energy =
1817 power.powerlib.getEnergy();
1818 Data::MemoryPowerModel::Power rank_power =
1819 power.powerlib.getPower();
1820
1821 actEnergy = energy.act_energy * memory.devicesPerRank;
1822 preEnergy = energy.pre_energy * memory.devicesPerRank;
1823 readEnergy = energy.read_energy * memory.devicesPerRank;
1824 writeEnergy = energy.write_energy * memory.devicesPerRank;
1825 refreshEnergy = energy.ref_energy * memory.devicesPerRank;
1826 actBackEnergy = energy.act_stdby_energy * memory.devicesPerRank;
1827 preBackEnergy = energy.pre_stdby_energy * memory.devicesPerRank;
1828 totalEnergy = energy.total_energy * memory.devicesPerRank;
1829 averagePower = rank_power.average_power * memory.devicesPerRank;
1830}
1831
1832void
1833DRAMCtrl::Rank::regStats()
1834{
1835 using namespace Stats;
1836
1837 pwrStateTime
1838 .init(5)
1839 .name(name() + ".memoryStateTime")
1840 .desc("Time in different power states");
1841 pwrStateTime.subname(0, "IDLE");
1842 pwrStateTime.subname(1, "REF");
1843 pwrStateTime.subname(2, "PRE_PDN");
1844 pwrStateTime.subname(3, "ACT");
1845 pwrStateTime.subname(4, "ACT_PDN");
1846
1847 actEnergy
1848 .name(name() + ".actEnergy")
1849 .desc("Energy for activate commands per rank (pJ)");
1850
1851 preEnergy
1852 .name(name() + ".preEnergy")
1853 .desc("Energy for precharge commands per rank (pJ)");
1854
1855 readEnergy
1856 .name(name() + ".readEnergy")
1857 .desc("Energy for read commands per rank (pJ)");
1858
1859 writeEnergy
1860 .name(name() + ".writeEnergy")
1861 .desc("Energy for write commands per rank (pJ)");
1862
1863 refreshEnergy
1864 .name(name() + ".refreshEnergy")
1865 .desc("Energy for refresh commands per rank (pJ)");
1866
1867 actBackEnergy
1868 .name(name() + ".actBackEnergy")
1869 .desc("Energy for active background per rank (pJ)");
1870
1871 preBackEnergy
1872 .name(name() + ".preBackEnergy")
1873 .desc("Energy for precharge background per rank (pJ)");
1874
1875 totalEnergy
1876 .name(name() + ".totalEnergy")
1877 .desc("Total energy per rank (pJ)");
1878
1879 averagePower
1880 .name(name() + ".averagePower")
1881 .desc("Core power per rank (mW)");
1882}
1883void
1884DRAMCtrl::regStats()
1885{
1886 using namespace Stats;
1887
1888 AbstractMemory::regStats();
1889
1890 for (auto r : ranks) {
1891 r->regStats();
1892 }
1893
1894 readReqs
1895 .name(name() + ".readReqs")
1896 .desc("Number of read requests accepted");
1897
1898 writeReqs
1899 .name(name() + ".writeReqs")
1900 .desc("Number of write requests accepted");
1901
1902 readBursts
1903 .name(name() + ".readBursts")
1904 .desc("Number of DRAM read bursts, "
1905 "including those serviced by the write queue");
1906
1907 writeBursts
1908 .name(name() + ".writeBursts")
1909 .desc("Number of DRAM write bursts, "
1910 "including those merged in the write queue");
1911
1912 servicedByWrQ
1913 .name(name() + ".servicedByWrQ")
1914 .desc("Number of DRAM read bursts serviced by the write queue");
1915
1916 mergedWrBursts
1917 .name(name() + ".mergedWrBursts")
1918 .desc("Number of DRAM write bursts merged with an existing one");
1919
1920 neitherReadNorWrite
1921 .name(name() + ".neitherReadNorWriteReqs")
1922 .desc("Number of requests that are neither read nor write");
1923
1924 perBankRdBursts
1925 .init(banksPerRank * ranksPerChannel)
1926 .name(name() + ".perBankRdBursts")
1927 .desc("Per bank write bursts");
1928
1929 perBankWrBursts
1930 .init(banksPerRank * ranksPerChannel)
1931 .name(name() + ".perBankWrBursts")
1932 .desc("Per bank write bursts");
1933
1934 avgRdQLen
1935 .name(name() + ".avgRdQLen")
1936 .desc("Average read queue length when enqueuing")
1937 .precision(2);
1938
1939 avgWrQLen
1940 .name(name() + ".avgWrQLen")
1941 .desc("Average write queue length when enqueuing")
1942 .precision(2);
1943
1944 totQLat
1945 .name(name() + ".totQLat")
1946 .desc("Total ticks spent queuing");
1947
1948 totBusLat
1949 .name(name() + ".totBusLat")
1950 .desc("Total ticks spent in databus transfers");
1951
1952 totMemAccLat
1953 .name(name() + ".totMemAccLat")
1954 .desc("Total ticks spent from burst creation until serviced "
1955 "by the DRAM");
1956
1957 avgQLat
1958 .name(name() + ".avgQLat")
1959 .desc("Average queueing delay per DRAM burst")
1960 .precision(2);
1961
1962 avgQLat = totQLat / (readBursts - servicedByWrQ);
1963
1964 avgBusLat
1965 .name(name() + ".avgBusLat")
1966 .desc("Average bus latency per DRAM burst")
1967 .precision(2);
1968
1969 avgBusLat = totBusLat / (readBursts - servicedByWrQ);
1970
1971 avgMemAccLat
1972 .name(name() + ".avgMemAccLat")
1973 .desc("Average memory access latency per DRAM burst")
1974 .precision(2);
1975
1976 avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
1977
1978 numRdRetry
1979 .name(name() + ".numRdRetry")
1980 .desc("Number of times read queue was full causing retry");
1981
1982 numWrRetry
1983 .name(name() + ".numWrRetry")
1984 .desc("Number of times write queue was full causing retry");
1985
1986 readRowHits
1987 .name(name() + ".readRowHits")
1988 .desc("Number of row buffer hits during reads");
1989
1990 writeRowHits
1991 .name(name() + ".writeRowHits")
1992 .desc("Number of row buffer hits during writes");
1993
1994 readRowHitRate
1995 .name(name() + ".readRowHitRate")
1996 .desc("Row buffer hit rate for reads")
1997 .precision(2);
1998
1999 readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
2000
2001 writeRowHitRate
2002 .name(name() + ".writeRowHitRate")
2003 .desc("Row buffer hit rate for writes")
2004 .precision(2);
2005
2006 writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
2007
2008 readPktSize
2009 .init(ceilLog2(burstSize) + 1)
2010 .name(name() + ".readPktSize")
2011 .desc("Read request sizes (log2)");
2012
2013 writePktSize
2014 .init(ceilLog2(burstSize) + 1)
2015 .name(name() + ".writePktSize")
2016 .desc("Write request sizes (log2)");
2017
2018 rdQLenPdf
2019 .init(readBufferSize)
2020 .name(name() + ".rdQLenPdf")
2021 .desc("What read queue length does an incoming req see");
2022
2023 wrQLenPdf
2024 .init(writeBufferSize)
2025 .name(name() + ".wrQLenPdf")
2026 .desc("What write queue length does an incoming req see");
2027
2028 bytesPerActivate
2029 .init(maxAccessesPerRow)
2030 .name(name() + ".bytesPerActivate")
2031 .desc("Bytes accessed per row activation")
2032 .flags(nozero);
2033
2034 rdPerTurnAround
2035 .init(readBufferSize)
2036 .name(name() + ".rdPerTurnAround")
2037 .desc("Reads before turning the bus around for writes")
2038 .flags(nozero);
2039
2040 wrPerTurnAround
2041 .init(writeBufferSize)
2042 .name(name() + ".wrPerTurnAround")
2043 .desc("Writes before turning the bus around for reads")
2044 .flags(nozero);
2045
2046 bytesReadDRAM
2047 .name(name() + ".bytesReadDRAM")
2048 .desc("Total number of bytes read from DRAM");
2049
2050 bytesReadWrQ
2051 .name(name() + ".bytesReadWrQ")
2052 .desc("Total number of bytes read from write queue");
2053
2054 bytesWritten
2055 .name(name() + ".bytesWritten")
2056 .desc("Total number of bytes written to DRAM");
2057
2058 bytesReadSys
2059 .name(name() + ".bytesReadSys")
2060 .desc("Total read bytes from the system interface side");
2061
2062 bytesWrittenSys
2063 .name(name() + ".bytesWrittenSys")
2064 .desc("Total written bytes from the system interface side");
2065
2066 avgRdBW
2067 .name(name() + ".avgRdBW")
2068 .desc("Average DRAM read bandwidth in MiByte/s")
2069 .precision(2);
2070
2071 avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
2072
2073 avgWrBW
2074 .name(name() + ".avgWrBW")
2075 .desc("Average achieved write bandwidth in MiByte/s")
2076 .precision(2);
2077
2078 avgWrBW = (bytesWritten / 1000000) / simSeconds;
2079
2080 avgRdBWSys
2081 .name(name() + ".avgRdBWSys")
2082 .desc("Average system read bandwidth in MiByte/s")
2083 .precision(2);
2084
2085 avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
2086
2087 avgWrBWSys
2088 .name(name() + ".avgWrBWSys")
2089 .desc("Average system write bandwidth in MiByte/s")
2090 .precision(2);
2091
2092 avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
2093
2094 peakBW
2095 .name(name() + ".peakBW")
2096 .desc("Theoretical peak bandwidth in MiByte/s")
2097 .precision(2);
2098
2099 peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
2100
2101 busUtil
2102 .name(name() + ".busUtil")
2103 .desc("Data bus utilization in percentage")
2104 .precision(2);
2105 busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
2106
2107 totGap
2108 .name(name() + ".totGap")
2109 .desc("Total gap between requests");
2110
2111 avgGap
2112 .name(name() + ".avgGap")
2113 .desc("Average gap between requests")
2114 .precision(2);
2115
2116 avgGap = totGap / (readReqs + writeReqs);
2117
2118 // Stats for DRAM Power calculation based on Micron datasheet
2119 busUtilRead
2120 .name(name() + ".busUtilRead")
2121 .desc("Data bus utilization in percentage for reads")
2122 .precision(2);
2123
2124 busUtilRead = avgRdBW / peakBW * 100;
2125
2126 busUtilWrite
2127 .name(name() + ".busUtilWrite")
2128 .desc("Data bus utilization in percentage for writes")
2129 .precision(2);
2130
2131 busUtilWrite = avgWrBW / peakBW * 100;
2132
2133 pageHitRate
2134 .name(name() + ".pageHitRate")
2135 .desc("Row buffer hit rate, read and write combined")
2136 .precision(2);
2137
2138 pageHitRate = (writeRowHits + readRowHits) /
2139 (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
2140}
2141
2142void
2143DRAMCtrl::recvFunctional(PacketPtr pkt)
2144{
2145 // rely on the abstract memory
2146 functionalAccess(pkt);
2147}
2148
2149BaseSlavePort&
2150DRAMCtrl::getSlavePort(const string &if_name, PortID idx)
2151{
2152 if (if_name != "port") {
2153 return MemObject::getSlavePort(if_name, idx);
2154 } else {
2155 return port;
2156 }
2157}
2158
2159DrainState
2160DRAMCtrl::drain()
2161{
2162 // if there is anything in any of our internal queues, keep track
2163 // of that as well
2164 if (!(writeQueue.empty() && readQueue.empty() && respQueue.empty())) {
2165 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
2166 " resp: %d\n", writeQueue.size(), readQueue.size(),
2167 respQueue.size());
2168
2169 // the only part that is not drained automatically over time
2170 // is the write queue, thus kick things into action if needed
2171 if (!writeQueue.empty() && !nextReqEvent.scheduled()) {
2172 schedule(nextReqEvent, curTick());
2173 }
2174 return DrainState::Draining;
2175 } else {
2176 return DrainState::Drained;
2177 }
2178}
2179
2180void
2181DRAMCtrl::drainResume()
2182{
2183 if (!isTimingMode && system()->isTimingMode()) {
2184 // if we switched to timing mode, kick things into action,
2185 // and behave as if we restored from a checkpoint
2186 startup();
2187 } else if (isTimingMode && !system()->isTimingMode()) {
2188 // if we switch from timing mode, stop the refresh events to
2189 // not cause issues with KVM
2190 for (auto r : ranks) {
2191 r->suspend();
2192 }
2193 }
2194
2195 // update the mode
2196 isTimingMode = system()->isTimingMode();
2197}
2198
2199DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
2200 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
2201 memory(_memory)
2202{ }
2203
2204AddrRangeList
2205DRAMCtrl::MemoryPort::getAddrRanges() const
2206{
2207 AddrRangeList ranges;
2208 ranges.push_back(memory.getAddrRange());
2209 return ranges;
2210}
2211
2212void
2213DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
2214{
2215 pkt->pushLabel(memory.name());
2216
2217 if (!queue.checkFunctional(pkt)) {
2218 // Default implementation of SimpleTimingPort::recvFunctional()
2219 // calls recvAtomic() and throws away the latency; we can save a
2220 // little here by just not calculating the latency.
2221 memory.recvFunctional(pkt);
2222 }
2223
2224 pkt->popLabel();
2225}
2226
2227Tick
2228DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt)
2229{
2230 return memory.recvAtomic(pkt);
2231}
2232
2233bool
2234DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt)
2235{
2236 // pass it to the memory controller
2237 return memory.recvTimingReq(pkt);
2238}
2239
2240DRAMCtrl*
2241DRAMCtrlParams::create()
2242{
2243 return new DRAMCtrl(this);
2244}
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
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();
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
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()) {
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.power.powerlib.doCommand(MemCommand::ACT, bank_ref.bank,
902 divCeil(act_tick, tCK) -
903 timeStampOffset);
904
905 DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) -
906 timeStampOffset, bank_ref.bank, rank_ref.rank);
907
908 // The next access has to respect tRAS for this bank
909 bank_ref.preAllowedAt = act_tick + tRAS;
910
911 // Respect the row-to-column command delay
912 bank_ref.colAllowedAt = std::max(act_tick + tRCD, bank_ref.colAllowedAt);
913
914 // start by enforcing tRRD
915 for (int i = 0; i < banksPerRank; i++) {
916 // next activate to any bank in this rank must not happen
917 // before tRRD
918 if (bankGroupArch && (bank_ref.bankgr == rank_ref.banks[i].bankgr)) {
919 // bank group architecture requires longer delays between
920 // ACT commands within the same bank group. Use tRRD_L
921 // in this case
922 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD_L,
923 rank_ref.banks[i].actAllowedAt);
924 } else {
925 // use shorter tRRD value when either
926 // 1) bank group architecture is not supportted
927 // 2) bank is in a different bank group
928 rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD,
929 rank_ref.banks[i].actAllowedAt);
930 }
931 }
932
933 // next, we deal with tXAW, if the activation limit is disabled
934 // then we directly schedule an activate power event
935 if (!rank_ref.actTicks.empty()) {
936 // sanity check
937 if (rank_ref.actTicks.back() &&
938 (act_tick - rank_ref.actTicks.back()) < tXAW) {
939 panic("Got %d activates in window %d (%llu - %llu) which "
940 "is smaller than %llu\n", activationLimit, act_tick -
941 rank_ref.actTicks.back(), act_tick,
942 rank_ref.actTicks.back(), tXAW);
943 }
944
945 // shift the times used for the book keeping, the last element
946 // (highest index) is the oldest one and hence the lowest value
947 rank_ref.actTicks.pop_back();
948
949 // record an new activation (in the future)
950 rank_ref.actTicks.push_front(act_tick);
951
952 // cannot activate more than X times in time window tXAW, push the
953 // next one (the X + 1'st activate) to be tXAW away from the
954 // oldest in our window of X
955 if (rank_ref.actTicks.back() &&
956 (act_tick - rank_ref.actTicks.back()) < tXAW) {
957 DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate "
958 "no earlier than %llu\n", activationLimit,
959 rank_ref.actTicks.back() + tXAW);
960 for (int j = 0; j < banksPerRank; j++)
961 // next activate must not happen before end of window
962 rank_ref.banks[j].actAllowedAt =
963 std::max(rank_ref.actTicks.back() + tXAW,
964 rank_ref.banks[j].actAllowedAt);
965 }
966 }
967
968 // at the point when this activate takes place, make sure we
969 // transition to the active power state
970 if (!rank_ref.activateEvent.scheduled())
971 schedule(rank_ref.activateEvent, act_tick);
972 else if (rank_ref.activateEvent.when() > act_tick)
973 // move it sooner in time
974 reschedule(rank_ref.activateEvent, act_tick);
975}
976
977void
978DRAMCtrl::prechargeBank(Rank& rank_ref, Bank& bank, Tick pre_at, bool trace)
979{
980 // make sure the bank has an open row
981 assert(bank.openRow != Bank::NO_ROW);
982
983 // sample the bytes per activate here since we are closing
984 // the page
985 bytesPerActivate.sample(bank.bytesAccessed);
986
987 bank.openRow = Bank::NO_ROW;
988
989 // no precharge allowed before this one
990 bank.preAllowedAt = pre_at;
991
992 Tick pre_done_at = pre_at + tRP;
993
994 bank.actAllowedAt = std::max(bank.actAllowedAt, pre_done_at);
995
996 assert(rank_ref.numBanksActive != 0);
997 --rank_ref.numBanksActive;
998
999 DPRINTF(DRAM, "Precharging bank %d, rank %d at tick %lld, now got "
1000 "%d active\n", bank.bank, rank_ref.rank, pre_at,
1001 rank_ref.numBanksActive);
1002
1003 if (trace) {
1004
1005 rank_ref.power.powerlib.doCommand(MemCommand::PRE, bank.bank,
1006 divCeil(pre_at, tCK) -
1007 timeStampOffset);
1008 DPRINTF(DRAMPower, "%llu,PRE,%d,%d\n", divCeil(pre_at, tCK) -
1009 timeStampOffset, bank.bank, rank_ref.rank);
1010 }
1011 // if we look at the current number of active banks we might be
1012 // tempted to think the DRAM is now idle, however this can be
1013 // undone by an activate that is scheduled to happen before we
1014 // would have reached the idle state, so schedule an event and
1015 // rather check once we actually make it to the point in time when
1016 // the (last) precharge takes place
1017 if (!rank_ref.prechargeEvent.scheduled())
1018 schedule(rank_ref.prechargeEvent, pre_done_at);
1019 else if (rank_ref.prechargeEvent.when() < pre_done_at)
1020 reschedule(rank_ref.prechargeEvent, pre_done_at);
1021}
1022
1023void
1024DRAMCtrl::doDRAMAccess(DRAMPacket* dram_pkt)
1025{
1026 DPRINTF(DRAM, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1027 dram_pkt->addr, dram_pkt->rank, dram_pkt->bank, dram_pkt->row);
1028
1029 // get the rank
1030 Rank& rank = dram_pkt->rankRef;
1031
1032 // get the bank
1033 Bank& bank = dram_pkt->bankRef;
1034
1035 // for the state we need to track if it is a row hit or not
1036 bool row_hit = true;
1037
1038 // respect any constraints on the command (e.g. tRCD or tCCD)
1039 Tick cmd_at = std::max(bank.colAllowedAt, curTick());
1040
1041 // Determine the access latency and update the bank state
1042 if (bank.openRow == dram_pkt->row) {
1043 // nothing to do
1044 } else {
1045 row_hit = false;
1046
1047 // If there is a page open, precharge it.
1048 if (bank.openRow != Bank::NO_ROW) {
1049 prechargeBank(rank, bank, std::max(bank.preAllowedAt, curTick()));
1050 }
1051
1052 // next we need to account for the delay in activating the
1053 // page
1054 Tick act_tick = std::max(bank.actAllowedAt, curTick());
1055
1056 // Record the activation and deal with all the global timing
1057 // constraints caused be a new activation (tRRD and tXAW)
1058 activateBank(rank, bank, act_tick, dram_pkt->row);
1059
1060 // issue the command as early as possible
1061 cmd_at = bank.colAllowedAt;
1062 }
1063
1064 // we need to wait until the bus is available before we can issue
1065 // the command
1066 cmd_at = std::max(cmd_at, busBusyUntil - tCL);
1067
1068 // update the packet ready time
1069 dram_pkt->readyTime = cmd_at + tCL + tBURST;
1070
1071 // only one burst can use the bus at any one point in time
1072 assert(dram_pkt->readyTime - busBusyUntil >= tBURST);
1073
1074 // update the time for the next read/write burst for each
1075 // bank (add a max with tCCD/tCCD_L here)
1076 Tick cmd_dly;
1077 for (int j = 0; j < ranksPerChannel; j++) {
1078 for (int i = 0; i < banksPerRank; i++) {
1079 // next burst to same bank group in this rank must not happen
1080 // before tCCD_L. Different bank group timing requirement is
1081 // tBURST; Add tCS for different ranks
1082 if (dram_pkt->rank == j) {
1083 if (bankGroupArch &&
1084 (bank.bankgr == ranks[j]->banks[i].bankgr)) {
1085 // bank group architecture requires longer delays between
1086 // RD/WR burst commands to the same bank group.
1087 // Use tCCD_L in this case
1088 cmd_dly = tCCD_L;
1089 } else {
1090 // use tBURST (equivalent to tCCD_S), the shorter
1091 // cas-to-cas delay value, when either:
1092 // 1) bank group architecture is not supportted
1093 // 2) bank is in a different bank group
1094 cmd_dly = tBURST;
1095 }
1096 } else {
1097 // different rank is by default in a different bank group
1098 // use tBURST (equivalent to tCCD_S), which is the shorter
1099 // cas-to-cas delay in this case
1100 // Add tCS to account for rank-to-rank bus delay requirements
1101 cmd_dly = tBURST + tCS;
1102 }
1103 ranks[j]->banks[i].colAllowedAt = std::max(cmd_at + cmd_dly,
1104 ranks[j]->banks[i].colAllowedAt);
1105 }
1106 }
1107
1108 // Save rank of current access
1109 activeRank = dram_pkt->rank;
1110
1111 // If this is a write, we also need to respect the write recovery
1112 // time before a precharge, in the case of a read, respect the
1113 // read to precharge constraint
1114 bank.preAllowedAt = std::max(bank.preAllowedAt,
1115 dram_pkt->isRead ? cmd_at + tRTP :
1116 dram_pkt->readyTime + tWR);
1117
1118 // increment the bytes accessed and the accesses per row
1119 bank.bytesAccessed += burstSize;
1120 ++bank.rowAccesses;
1121
1122 // if we reached the max, then issue with an auto-precharge
1123 bool auto_precharge = pageMgmt == Enums::close ||
1124 bank.rowAccesses == maxAccessesPerRow;
1125
1126 // if we did not hit the limit, we might still want to
1127 // auto-precharge
1128 if (!auto_precharge &&
1129 (pageMgmt == Enums::open_adaptive ||
1130 pageMgmt == Enums::close_adaptive)) {
1131 // a twist on the open and close page policies:
1132 // 1) open_adaptive page policy does not blindly keep the
1133 // page open, but close it if there are no row hits, and there
1134 // are bank conflicts in the queue
1135 // 2) close_adaptive page policy does not blindly close the
1136 // page, but closes it only if there are no row hits in the queue.
1137 // In this case, only force an auto precharge when there
1138 // are no same page hits in the queue
1139 bool got_more_hits = false;
1140 bool got_bank_conflict = false;
1141
1142 // either look at the read queue or write queue
1143 const deque<DRAMPacket*>& queue = dram_pkt->isRead ? readQueue :
1144 writeQueue;
1145 auto p = queue.begin();
1146 // make sure we are not considering the packet that we are
1147 // currently dealing with (which is the head of the queue)
1148 ++p;
1149
1150 // keep on looking until we find a hit or reach the end of the queue
1151 // 1) if a hit is found, then both open and close adaptive policies keep
1152 // the page open
1153 // 2) if no hit is found, got_bank_conflict is set to true if a bank
1154 // conflict request is waiting in the queue
1155 while (!got_more_hits && p != queue.end()) {
1156 bool same_rank_bank = (dram_pkt->rank == (*p)->rank) &&
1157 (dram_pkt->bank == (*p)->bank);
1158 bool same_row = dram_pkt->row == (*p)->row;
1159 got_more_hits |= same_rank_bank && same_row;
1160 got_bank_conflict |= same_rank_bank && !same_row;
1161 ++p;
1162 }
1163
1164 // auto pre-charge when either
1165 // 1) open_adaptive policy, we have not got any more hits, and
1166 // have a bank conflict
1167 // 2) close_adaptive policy and we have not got any more hits
1168 auto_precharge = !got_more_hits &&
1169 (got_bank_conflict || pageMgmt == Enums::close_adaptive);
1170 }
1171
1172 // DRAMPower trace command to be written
1173 std::string mem_cmd = dram_pkt->isRead ? "RD" : "WR";
1174
1175 // MemCommand required for DRAMPower library
1176 MemCommand::cmds command = (mem_cmd == "RD") ? MemCommand::RD :
1177 MemCommand::WR;
1178
1179 // if this access should use auto-precharge, then we are
1180 // closing the row
1181 if (auto_precharge) {
1182 // if auto-precharge push a PRE command at the correct tick to the
1183 // list used by DRAMPower library to calculate power
1184 prechargeBank(rank, bank, std::max(curTick(), bank.preAllowedAt));
1185
1186 DPRINTF(DRAM, "Auto-precharged bank: %d\n", dram_pkt->bankId);
1187 }
1188
1189 // Update bus state
1190 busBusyUntil = dram_pkt->readyTime;
1191
1192 DPRINTF(DRAM, "Access to %lld, ready at %lld bus busy until %lld.\n",
1193 dram_pkt->addr, dram_pkt->readyTime, busBusyUntil);
1194
1195 dram_pkt->rankRef.power.powerlib.doCommand(command, dram_pkt->bank,
1196 divCeil(cmd_at, tCK) -
1197 timeStampOffset);
1198
1199 DPRINTF(DRAMPower, "%llu,%s,%d,%d\n", divCeil(cmd_at, tCK) -
1200 timeStampOffset, mem_cmd, dram_pkt->bank, dram_pkt->rank);
1201
1202 // Update the minimum timing between the requests, this is a
1203 // conservative estimate of when we have to schedule the next
1204 // request to not introduce any unecessary bubbles. In most cases
1205 // we will wake up sooner than we have to.
1206 nextReqTime = busBusyUntil - (tRP + tRCD + tCL);
1207
1208 // Update the stats and schedule the next request
1209 if (dram_pkt->isRead) {
1210 ++readsThisTime;
1211 if (row_hit)
1212 readRowHits++;
1213 bytesReadDRAM += burstSize;
1214 perBankRdBursts[dram_pkt->bankId]++;
1215
1216 // Update latency stats
1217 totMemAccLat += dram_pkt->readyTime - dram_pkt->entryTime;
1218 totBusLat += tBURST;
1219 totQLat += cmd_at - dram_pkt->entryTime;
1220 } else {
1221 ++writesThisTime;
1222 if (row_hit)
1223 writeRowHits++;
1224 bytesWritten += burstSize;
1225 perBankWrBursts[dram_pkt->bankId]++;
1226 }
1227}
1228
1229void
1230DRAMCtrl::processNextReqEvent()
1231{
1232 int busyRanks = 0;
1233 for (auto r : ranks) {
1234 if (!r->isAvailable()) {
1235 // rank is busy refreshing
1236 busyRanks++;
1237
1238 // let the rank know that if it was waiting to drain, it
1239 // is now done and ready to proceed
1240 r->checkDrainDone();
1241 }
1242 }
1243
1244 if (busyRanks == ranksPerChannel) {
1245 // if all ranks are refreshing wait for them to finish
1246 // and stall this state machine without taking any further
1247 // action, and do not schedule a new nextReqEvent
1248 return;
1249 }
1250
1251 // pre-emptively set to false. Overwrite if in READ_TO_WRITE
1252 // or WRITE_TO_READ state
1253 bool switched_cmd_type = false;
1254 if (busState == READ_TO_WRITE) {
1255 DPRINTF(DRAM, "Switching to writes after %d reads with %d reads "
1256 "waiting\n", readsThisTime, readQueue.size());
1257
1258 // sample and reset the read-related stats as we are now
1259 // transitioning to writes, and all reads are done
1260 rdPerTurnAround.sample(readsThisTime);
1261 readsThisTime = 0;
1262
1263 // now proceed to do the actual writes
1264 busState = WRITE;
1265 switched_cmd_type = true;
1266 } else if (busState == WRITE_TO_READ) {
1267 DPRINTF(DRAM, "Switching to reads after %d writes with %d writes "
1268 "waiting\n", writesThisTime, writeQueue.size());
1269
1270 wrPerTurnAround.sample(writesThisTime);
1271 writesThisTime = 0;
1272
1273 busState = READ;
1274 switched_cmd_type = true;
1275 }
1276
1277 // when we get here it is either a read or a write
1278 if (busState == READ) {
1279
1280 // track if we should switch or not
1281 bool switch_to_writes = false;
1282
1283 if (readQueue.empty()) {
1284 // In the case there is no read request to go next,
1285 // trigger writes if we have passed the low threshold (or
1286 // if we are draining)
1287 if (!writeQueue.empty() &&
1288 (drainState() == DrainState::Draining ||
1289 writeQueue.size() > writeLowThreshold)) {
1290
1291 switch_to_writes = true;
1292 } else {
1293 // check if we are drained
1294 if (drainState() == DrainState::Draining &&
1295 respQueue.empty()) {
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());
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
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
1367 busState = READ_TO_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();
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
1413 busState = WRITE_TO_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 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)
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
1546void
1547DRAMCtrl::Rank::checkDrainDone()
1548{
1549 // if this rank was waiting to drain it is now able to proceed to
1550 // precharge
1551 if (refreshState == REF_DRAIN) {
1552 DPRINTF(DRAM, "Refresh drain done, now precharging\n");
1553
1554 refreshState = REF_PRE;
1555
1556 // hand control back to the refresh event loop
1557 schedule(refreshEvent, curTick());
1558 }
1559}
1560
1561void
1562DRAMCtrl::Rank::processActivateEvent()
1563{
1564 // we should transition to the active state as soon as any bank is active
1565 if (pwrState != PWR_ACT)
1566 // note that at this point numBanksActive could be back at
1567 // zero again due to a precharge scheduled in the future
1568 schedulePowerEvent(PWR_ACT, curTick());
1569}
1570
1571void
1572DRAMCtrl::Rank::processPrechargeEvent()
1573{
1574 // if we reached zero, then special conditions apply as we track
1575 // if all banks are precharged for the power models
1576 if (numBanksActive == 0) {
1577 // we should transition to the idle state when the last bank
1578 // is precharged
1579 schedulePowerEvent(PWR_IDLE, curTick());
1580 }
1581}
1582
1583void
1584DRAMCtrl::Rank::processRefreshEvent()
1585{
1586 // when first preparing the refresh, remember when it was due
1587 if (refreshState == REF_IDLE) {
1588 // remember when the refresh is due
1589 refreshDueAt = curTick();
1590
1591 // proceed to drain
1592 refreshState = REF_DRAIN;
1593
1594 DPRINTF(DRAM, "Refresh due\n");
1595 }
1596
1597 // let any scheduled read or write to the same rank go ahead,
1598 // after which it will
1599 // hand control back to this event loop
1600 if (refreshState == REF_DRAIN) {
1601 // if a request is at the moment being handled and this request is
1602 // accessing the current rank then wait for it to finish
1603 if ((rank == memory.activeRank)
1604 && (memory.nextReqEvent.scheduled())) {
1605 // hand control over to the request loop until it is
1606 // evaluated next
1607 DPRINTF(DRAM, "Refresh awaiting draining\n");
1608
1609 return;
1610 } else {
1611 refreshState = REF_PRE;
1612 }
1613 }
1614
1615 // at this point, ensure that all banks are precharged
1616 if (refreshState == REF_PRE) {
1617 // precharge any active bank if we are not already in the idle
1618 // state
1619 if (pwrState != PWR_IDLE) {
1620 // at the moment, we use a precharge all even if there is
1621 // only a single bank open
1622 DPRINTF(DRAM, "Precharging all\n");
1623
1624 // first determine when we can precharge
1625 Tick pre_at = curTick();
1626
1627 for (auto &b : banks) {
1628 // respect both causality and any existing bank
1629 // constraints, some banks could already have a
1630 // (auto) precharge scheduled
1631 pre_at = std::max(b.preAllowedAt, pre_at);
1632 }
1633
1634 // make sure all banks per rank are precharged, and for those that
1635 // already are, update their availability
1636 Tick act_allowed_at = pre_at + memory.tRP;
1637
1638 for (auto &b : banks) {
1639 if (b.openRow != Bank::NO_ROW) {
1640 memory.prechargeBank(*this, b, pre_at, false);
1641 } else {
1642 b.actAllowedAt = std::max(b.actAllowedAt, act_allowed_at);
1643 b.preAllowedAt = std::max(b.preAllowedAt, pre_at);
1644 }
1645 }
1646
1647 // precharge all banks in rank
1648 power.powerlib.doCommand(MemCommand::PREA, 0,
1649 divCeil(pre_at, memory.tCK) -
1650 memory.timeStampOffset);
1651
1652 DPRINTF(DRAMPower, "%llu,PREA,0,%d\n",
1653 divCeil(pre_at, memory.tCK) -
1654 memory.timeStampOffset, rank);
1655 } else {
1656 DPRINTF(DRAM, "All banks already precharged, starting refresh\n");
1657
1658 // go ahead and kick the power state machine into gear if
1659 // we are already idle
1660 schedulePowerEvent(PWR_REF, curTick());
1661 }
1662
1663 refreshState = REF_RUN;
1664 assert(numBanksActive == 0);
1665
1666 // wait for all banks to be precharged, at which point the
1667 // power state machine will transition to the idle state, and
1668 // automatically move to a refresh, at that point it will also
1669 // call this method to get the refresh event loop going again
1670 return;
1671 }
1672
1673 // last but not least we perform the actual refresh
1674 if (refreshState == REF_RUN) {
1675 // should never get here with any banks active
1676 assert(numBanksActive == 0);
1677 assert(pwrState == PWR_REF);
1678
1679 Tick ref_done_at = curTick() + memory.tRFC;
1680
1681 for (auto &b : banks) {
1682 b.actAllowedAt = ref_done_at;
1683 }
1684
1685 // at the moment this affects all ranks
1686 power.powerlib.doCommand(MemCommand::REF, 0,
1687 divCeil(curTick(), memory.tCK) -
1688 memory.timeStampOffset);
1689
1690 // at the moment sort the list of commands and update the counters
1691 // for DRAMPower libray when doing a refresh
1692 sort(power.powerlib.cmdList.begin(),
1693 power.powerlib.cmdList.end(), DRAMCtrl::sortTime);
1694
1695 // update the counters for DRAMPower, passing false to
1696 // indicate that this is not the last command in the
1697 // list. DRAMPower requires this information for the
1698 // correct calculation of the background energy at the end
1699 // of the simulation. Ideally we would want to call this
1700 // function with true once at the end of the
1701 // simulation. However, the discarded energy is extremly
1702 // small and does not effect the final results.
1703 power.powerlib.updateCounters(false);
1704
1705 // call the energy function
1706 power.powerlib.calcEnergy();
1707
1708 // Update the stats
1709 updatePowerStats();
1710
1711 DPRINTF(DRAMPower, "%llu,REF,0,%d\n", divCeil(curTick(), memory.tCK) -
1712 memory.timeStampOffset, rank);
1713
1714 // make sure we did not wait so long that we cannot make up
1715 // for it
1716 if (refreshDueAt + memory.tREFI < ref_done_at) {
1717 fatal("Refresh was delayed so long we cannot catch up\n");
1718 }
1719
1720 // compensate for the delay in actually performing the refresh
1721 // when scheduling the next one
1722 schedule(refreshEvent, refreshDueAt + memory.tREFI - memory.tRP);
1723
1724 assert(!powerEvent.scheduled());
1725
1726 // move to the idle power state once the refresh is done, this
1727 // will also move the refresh state machine to the refresh
1728 // idle state
1729 schedulePowerEvent(PWR_IDLE, ref_done_at);
1730
1731 DPRINTF(DRAMState, "Refresh done at %llu and next refresh at %llu\n",
1732 ref_done_at, refreshDueAt + memory.tREFI);
1733 }
1734}
1735
1736void
1737DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state, Tick tick)
1738{
1739 // respect causality
1740 assert(tick >= curTick());
1741
1742 if (!powerEvent.scheduled()) {
1743 DPRINTF(DRAMState, "Scheduling power event at %llu to state %d\n",
1744 tick, pwr_state);
1745
1746 // insert the new transition
1747 pwrStateTrans = pwr_state;
1748
1749 schedule(powerEvent, tick);
1750 } else {
1751 panic("Scheduled power event at %llu to state %d, "
1752 "with scheduled event at %llu to %d\n", tick, pwr_state,
1753 powerEvent.when(), pwrStateTrans);
1754 }
1755}
1756
1757void
1758DRAMCtrl::Rank::processPowerEvent()
1759{
1760 // remember where we were, and for how long
1761 Tick duration = curTick() - pwrStateTick;
1762 PowerState prev_state = pwrState;
1763
1764 // update the accounting
1765 pwrStateTime[prev_state] += duration;
1766
1767 pwrState = pwrStateTrans;
1768 pwrStateTick = curTick();
1769
1770 if (pwrState == PWR_IDLE) {
1771 DPRINTF(DRAMState, "All banks precharged\n");
1772
1773 // if we were refreshing, make sure we start scheduling requests again
1774 if (prev_state == PWR_REF) {
1775 DPRINTF(DRAMState, "Was refreshing for %llu ticks\n", duration);
1776 assert(pwrState == PWR_IDLE);
1777
1778 // kick things into action again
1779 refreshState = REF_IDLE;
1780 // a request event could be already scheduled by the state
1781 // machine of the other rank
1782 if (!memory.nextReqEvent.scheduled())
1783 schedule(memory.nextReqEvent, curTick());
1784 } else {
1785 assert(prev_state == PWR_ACT);
1786
1787 // if we have a pending refresh, and are now moving to
1788 // the idle state, direclty transition to a refresh
1789 if (refreshState == REF_RUN) {
1790 // there should be nothing waiting at this point
1791 assert(!powerEvent.scheduled());
1792
1793 // update the state in zero time and proceed below
1794 pwrState = PWR_REF;
1795 }
1796 }
1797 }
1798
1799 // we transition to the refresh state, let the refresh state
1800 // machine know of this state update and let it deal with the
1801 // scheduling of the next power state transition as well as the
1802 // following refresh
1803 if (pwrState == PWR_REF) {
1804 DPRINTF(DRAMState, "Refreshing\n");
1805 // kick the refresh event loop into action again, and that
1806 // in turn will schedule a transition to the idle power
1807 // state once the refresh is done
1808 assert(refreshState == REF_RUN);
1809 processRefreshEvent();
1810 }
1811}
1812
1813void
1814DRAMCtrl::Rank::updatePowerStats()
1815{
1816 // Get the energy and power from DRAMPower
1817 Data::MemoryPowerModel::Energy energy =
1818 power.powerlib.getEnergy();
1819 Data::MemoryPowerModel::Power rank_power =
1820 power.powerlib.getPower();
1821
1822 actEnergy = energy.act_energy * memory.devicesPerRank;
1823 preEnergy = energy.pre_energy * memory.devicesPerRank;
1824 readEnergy = energy.read_energy * memory.devicesPerRank;
1825 writeEnergy = energy.write_energy * memory.devicesPerRank;
1826 refreshEnergy = energy.ref_energy * memory.devicesPerRank;
1827 actBackEnergy = energy.act_stdby_energy * memory.devicesPerRank;
1828 preBackEnergy = energy.pre_stdby_energy * memory.devicesPerRank;
1829 totalEnergy = energy.total_energy * memory.devicesPerRank;
1830 averagePower = rank_power.average_power * memory.devicesPerRank;
1831}
1832
1833void
1834DRAMCtrl::Rank::regStats()
1835{
1836 using namespace Stats;
1837
1838 pwrStateTime
1839 .init(5)
1840 .name(name() + ".memoryStateTime")
1841 .desc("Time in different power states");
1842 pwrStateTime.subname(0, "IDLE");
1843 pwrStateTime.subname(1, "REF");
1844 pwrStateTime.subname(2, "PRE_PDN");
1845 pwrStateTime.subname(3, "ACT");
1846 pwrStateTime.subname(4, "ACT_PDN");
1847
1848 actEnergy
1849 .name(name() + ".actEnergy")
1850 .desc("Energy for activate commands per rank (pJ)");
1851
1852 preEnergy
1853 .name(name() + ".preEnergy")
1854 .desc("Energy for precharge commands per rank (pJ)");
1855
1856 readEnergy
1857 .name(name() + ".readEnergy")
1858 .desc("Energy for read commands per rank (pJ)");
1859
1860 writeEnergy
1861 .name(name() + ".writeEnergy")
1862 .desc("Energy for write commands per rank (pJ)");
1863
1864 refreshEnergy
1865 .name(name() + ".refreshEnergy")
1866 .desc("Energy for refresh commands per rank (pJ)");
1867
1868 actBackEnergy
1869 .name(name() + ".actBackEnergy")
1870 .desc("Energy for active background per rank (pJ)");
1871
1872 preBackEnergy
1873 .name(name() + ".preBackEnergy")
1874 .desc("Energy for precharge background per rank (pJ)");
1875
1876 totalEnergy
1877 .name(name() + ".totalEnergy")
1878 .desc("Total energy per rank (pJ)");
1879
1880 averagePower
1881 .name(name() + ".averagePower")
1882 .desc("Core power per rank (mW)");
1883}
1884void
1885DRAMCtrl::regStats()
1886{
1887 using namespace Stats;
1888
1889 AbstractMemory::regStats();
1890
1891 for (auto r : ranks) {
1892 r->regStats();
1893 }
1894
1895 readReqs
1896 .name(name() + ".readReqs")
1897 .desc("Number of read requests accepted");
1898
1899 writeReqs
1900 .name(name() + ".writeReqs")
1901 .desc("Number of write requests accepted");
1902
1903 readBursts
1904 .name(name() + ".readBursts")
1905 .desc("Number of DRAM read bursts, "
1906 "including those serviced by the write queue");
1907
1908 writeBursts
1909 .name(name() + ".writeBursts")
1910 .desc("Number of DRAM write bursts, "
1911 "including those merged in the write queue");
1912
1913 servicedByWrQ
1914 .name(name() + ".servicedByWrQ")
1915 .desc("Number of DRAM read bursts serviced by the write queue");
1916
1917 mergedWrBursts
1918 .name(name() + ".mergedWrBursts")
1919 .desc("Number of DRAM write bursts merged with an existing one");
1920
1921 neitherReadNorWrite
1922 .name(name() + ".neitherReadNorWriteReqs")
1923 .desc("Number of requests that are neither read nor write");
1924
1925 perBankRdBursts
1926 .init(banksPerRank * ranksPerChannel)
1927 .name(name() + ".perBankRdBursts")
1928 .desc("Per bank write bursts");
1929
1930 perBankWrBursts
1931 .init(banksPerRank * ranksPerChannel)
1932 .name(name() + ".perBankWrBursts")
1933 .desc("Per bank write bursts");
1934
1935 avgRdQLen
1936 .name(name() + ".avgRdQLen")
1937 .desc("Average read queue length when enqueuing")
1938 .precision(2);
1939
1940 avgWrQLen
1941 .name(name() + ".avgWrQLen")
1942 .desc("Average write queue length when enqueuing")
1943 .precision(2);
1944
1945 totQLat
1946 .name(name() + ".totQLat")
1947 .desc("Total ticks spent queuing");
1948
1949 totBusLat
1950 .name(name() + ".totBusLat")
1951 .desc("Total ticks spent in databus transfers");
1952
1953 totMemAccLat
1954 .name(name() + ".totMemAccLat")
1955 .desc("Total ticks spent from burst creation until serviced "
1956 "by the DRAM");
1957
1958 avgQLat
1959 .name(name() + ".avgQLat")
1960 .desc("Average queueing delay per DRAM burst")
1961 .precision(2);
1962
1963 avgQLat = totQLat / (readBursts - servicedByWrQ);
1964
1965 avgBusLat
1966 .name(name() + ".avgBusLat")
1967 .desc("Average bus latency per DRAM burst")
1968 .precision(2);
1969
1970 avgBusLat = totBusLat / (readBursts - servicedByWrQ);
1971
1972 avgMemAccLat
1973 .name(name() + ".avgMemAccLat")
1974 .desc("Average memory access latency per DRAM burst")
1975 .precision(2);
1976
1977 avgMemAccLat = totMemAccLat / (readBursts - servicedByWrQ);
1978
1979 numRdRetry
1980 .name(name() + ".numRdRetry")
1981 .desc("Number of times read queue was full causing retry");
1982
1983 numWrRetry
1984 .name(name() + ".numWrRetry")
1985 .desc("Number of times write queue was full causing retry");
1986
1987 readRowHits
1988 .name(name() + ".readRowHits")
1989 .desc("Number of row buffer hits during reads");
1990
1991 writeRowHits
1992 .name(name() + ".writeRowHits")
1993 .desc("Number of row buffer hits during writes");
1994
1995 readRowHitRate
1996 .name(name() + ".readRowHitRate")
1997 .desc("Row buffer hit rate for reads")
1998 .precision(2);
1999
2000 readRowHitRate = (readRowHits / (readBursts - servicedByWrQ)) * 100;
2001
2002 writeRowHitRate
2003 .name(name() + ".writeRowHitRate")
2004 .desc("Row buffer hit rate for writes")
2005 .precision(2);
2006
2007 writeRowHitRate = (writeRowHits / (writeBursts - mergedWrBursts)) * 100;
2008
2009 readPktSize
2010 .init(ceilLog2(burstSize) + 1)
2011 .name(name() + ".readPktSize")
2012 .desc("Read request sizes (log2)");
2013
2014 writePktSize
2015 .init(ceilLog2(burstSize) + 1)
2016 .name(name() + ".writePktSize")
2017 .desc("Write request sizes (log2)");
2018
2019 rdQLenPdf
2020 .init(readBufferSize)
2021 .name(name() + ".rdQLenPdf")
2022 .desc("What read queue length does an incoming req see");
2023
2024 wrQLenPdf
2025 .init(writeBufferSize)
2026 .name(name() + ".wrQLenPdf")
2027 .desc("What write queue length does an incoming req see");
2028
2029 bytesPerActivate
2030 .init(maxAccessesPerRow)
2031 .name(name() + ".bytesPerActivate")
2032 .desc("Bytes accessed per row activation")
2033 .flags(nozero);
2034
2035 rdPerTurnAround
2036 .init(readBufferSize)
2037 .name(name() + ".rdPerTurnAround")
2038 .desc("Reads before turning the bus around for writes")
2039 .flags(nozero);
2040
2041 wrPerTurnAround
2042 .init(writeBufferSize)
2043 .name(name() + ".wrPerTurnAround")
2044 .desc("Writes before turning the bus around for reads")
2045 .flags(nozero);
2046
2047 bytesReadDRAM
2048 .name(name() + ".bytesReadDRAM")
2049 .desc("Total number of bytes read from DRAM");
2050
2051 bytesReadWrQ
2052 .name(name() + ".bytesReadWrQ")
2053 .desc("Total number of bytes read from write queue");
2054
2055 bytesWritten
2056 .name(name() + ".bytesWritten")
2057 .desc("Total number of bytes written to DRAM");
2058
2059 bytesReadSys
2060 .name(name() + ".bytesReadSys")
2061 .desc("Total read bytes from the system interface side");
2062
2063 bytesWrittenSys
2064 .name(name() + ".bytesWrittenSys")
2065 .desc("Total written bytes from the system interface side");
2066
2067 avgRdBW
2068 .name(name() + ".avgRdBW")
2069 .desc("Average DRAM read bandwidth in MiByte/s")
2070 .precision(2);
2071
2072 avgRdBW = (bytesReadDRAM / 1000000) / simSeconds;
2073
2074 avgWrBW
2075 .name(name() + ".avgWrBW")
2076 .desc("Average achieved write bandwidth in MiByte/s")
2077 .precision(2);
2078
2079 avgWrBW = (bytesWritten / 1000000) / simSeconds;
2080
2081 avgRdBWSys
2082 .name(name() + ".avgRdBWSys")
2083 .desc("Average system read bandwidth in MiByte/s")
2084 .precision(2);
2085
2086 avgRdBWSys = (bytesReadSys / 1000000) / simSeconds;
2087
2088 avgWrBWSys
2089 .name(name() + ".avgWrBWSys")
2090 .desc("Average system write bandwidth in MiByte/s")
2091 .precision(2);
2092
2093 avgWrBWSys = (bytesWrittenSys / 1000000) / simSeconds;
2094
2095 peakBW
2096 .name(name() + ".peakBW")
2097 .desc("Theoretical peak bandwidth in MiByte/s")
2098 .precision(2);
2099
2100 peakBW = (SimClock::Frequency / tBURST) * burstSize / 1000000;
2101
2102 busUtil
2103 .name(name() + ".busUtil")
2104 .desc("Data bus utilization in percentage")
2105 .precision(2);
2106 busUtil = (avgRdBW + avgWrBW) / peakBW * 100;
2107
2108 totGap
2109 .name(name() + ".totGap")
2110 .desc("Total gap between requests");
2111
2112 avgGap
2113 .name(name() + ".avgGap")
2114 .desc("Average gap between requests")
2115 .precision(2);
2116
2117 avgGap = totGap / (readReqs + writeReqs);
2118
2119 // Stats for DRAM Power calculation based on Micron datasheet
2120 busUtilRead
2121 .name(name() + ".busUtilRead")
2122 .desc("Data bus utilization in percentage for reads")
2123 .precision(2);
2124
2125 busUtilRead = avgRdBW / peakBW * 100;
2126
2127 busUtilWrite
2128 .name(name() + ".busUtilWrite")
2129 .desc("Data bus utilization in percentage for writes")
2130 .precision(2);
2131
2132 busUtilWrite = avgWrBW / peakBW * 100;
2133
2134 pageHitRate
2135 .name(name() + ".pageHitRate")
2136 .desc("Row buffer hit rate, read and write combined")
2137 .precision(2);
2138
2139 pageHitRate = (writeRowHits + readRowHits) /
2140 (writeBursts - mergedWrBursts + readBursts - servicedByWrQ) * 100;
2141}
2142
2143void
2144DRAMCtrl::recvFunctional(PacketPtr pkt)
2145{
2146 // rely on the abstract memory
2147 functionalAccess(pkt);
2148}
2149
2150BaseSlavePort&
2151DRAMCtrl::getSlavePort(const string &if_name, PortID idx)
2152{
2153 if (if_name != "port") {
2154 return MemObject::getSlavePort(if_name, idx);
2155 } else {
2156 return port;
2157 }
2158}
2159
2160DrainState
2161DRAMCtrl::drain()
2162{
2163 // if there is anything in any of our internal queues, keep track
2164 // of that as well
2165 if (!(writeQueue.empty() && readQueue.empty() && respQueue.empty())) {
2166 DPRINTF(Drain, "DRAM controller not drained, write: %d, read: %d,"
2167 " resp: %d\n", writeQueue.size(), readQueue.size(),
2168 respQueue.size());
2169
2170 // the only part that is not drained automatically over time
2171 // is the write queue, thus kick things into action if needed
2172 if (!writeQueue.empty() && !nextReqEvent.scheduled()) {
2173 schedule(nextReqEvent, curTick());
2174 }
2175 return DrainState::Draining;
2176 } else {
2177 return DrainState::Drained;
2178 }
2179}
2180
2181void
2182DRAMCtrl::drainResume()
2183{
2184 if (!isTimingMode && system()->isTimingMode()) {
2185 // if we switched to timing mode, kick things into action,
2186 // and behave as if we restored from a checkpoint
2187 startup();
2188 } else if (isTimingMode && !system()->isTimingMode()) {
2189 // if we switch from timing mode, stop the refresh events to
2190 // not cause issues with KVM
2191 for (auto r : ranks) {
2192 r->suspend();
2193 }
2194 }
2195
2196 // update the mode
2197 isTimingMode = system()->isTimingMode();
2198}
2199
2200DRAMCtrl::MemoryPort::MemoryPort(const std::string& name, DRAMCtrl& _memory)
2201 : QueuedSlavePort(name, &_memory, queue), queue(_memory, *this),
2202 memory(_memory)
2203{ }
2204
2205AddrRangeList
2206DRAMCtrl::MemoryPort::getAddrRanges() const
2207{
2208 AddrRangeList ranges;
2209 ranges.push_back(memory.getAddrRange());
2210 return ranges;
2211}
2212
2213void
2214DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt)
2215{
2216 pkt->pushLabel(memory.name());
2217
2218 if (!queue.checkFunctional(pkt)) {
2219 // Default implementation of SimpleTimingPort::recvFunctional()
2220 // calls recvAtomic() and throws away the latency; we can save a
2221 // little here by just not calculating the latency.
2222 memory.recvFunctional(pkt);
2223 }
2224
2225 pkt->popLabel();
2226}
2227
2228Tick
2229DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt)
2230{
2231 return memory.recvAtomic(pkt);
2232}
2233
2234bool
2235DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt)
2236{
2237 // pass it to the memory controller
2238 return memory.recvTimingReq(pkt);
2239}
2240
2241DRAMCtrl*
2242DRAMCtrlParams::create()
2243{
2244 return new DRAMCtrl(this);
2245}