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