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