2 * Copyright (c) 2010-2014 ARM Limited
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.
14 * Copyright (c) 2013 Amin Farmahini-Farahani
15 * All rights reserved.
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.
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.
40 * Authors: Andreas Hansson
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"
56 DRAMCtrl::DRAMCtrl(const DRAMCtrlParams
* p
) :
58 port(name() + ".port", *this),
59 retryRdReq(false), retryWrReq(false),
61 nextReqEvent(this), respondEvent(this), activateEvent(this),
62 prechargeEvent(this), refreshEvent(this), powerEvent(this),
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)
92 // create the bank states based on the dimensions of the ranks and
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);
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
;
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
);
115 // determine the rows per bank by looking at the total capacity
116 uint64_t capacity
= ULL(1) << ceilLog2(AbstractMemory::size());
118 DPRINTF(DRAM
, "Memory capacity %lld (%lld) bytes\n", capacity
,
119 AbstractMemory::size());
121 DPRINTF(DRAM
, "Row buffer size %d bytes with %d columns per row buffer\n",
122 rowBufferSize
, columnsPerRowBuffer
);
124 rowsPerBank
= capacity
/ (rowBufferSize
* banksPerRank
* ranksPerChannel
);
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
);
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());
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);
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());
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());
160 // this is essentially the check above, so just to be sure
161 assert(columnsPerStripe
<= columnsPerRowBuffer
);
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",
175 if (!port
.isConnected()) {
176 fatal("DRAMCtrl %s is unconnected!\n", name());
178 port
.sendRangeChange();
185 // update the start tick for the precharge accounting to the
187 pwrStateTick
= curTick();
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
;
195 // kick off the refresh, and give ourselves enough time to
197 schedule(refreshEvent
, curTick() + tREFI
- tRP
);
201 DRAMCtrl::recvAtomic(PacketPtr pkt
)
203 DPRINTF(DRAM
, "recvAtomic: %s 0x%x\n", pkt
->cmdString(), pkt
->getAddr());
205 // do the actual memory access and turn the packet into a response
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
;
218 DRAMCtrl::readQueueFull(unsigned int neededEntries
) const
220 DPRINTF(DRAM
, "Read queue limit %d, current size %d, entries needed %d\n",
221 readBufferSize
, readQueue
.size() + respQueue
.size(),
225 (readQueue
.size() + respQueue
.size() + neededEntries
) > readBufferSize
;
229 DRAMCtrl::writeQueueFull(unsigned int neededEntries
) const
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
;
236 DRAMCtrl::DRAMPacket
*
237 DRAMCtrl::decodeAddr(PacketPtr pkt
, Addr dramPktAddr
, unsigned size
,
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
245 // use a 64-bit unsigned during the computations as the row is
246 // always the top bits, and check before creating the DRAMPacket
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
;
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
;
260 // take out the channel part of the address
261 addr
= addr
/ channels
;
263 // after the channel bits, get the bank bits to interleave
265 bank
= addr
% banksPerRank
;
266 addr
= addr
/ banksPerRank
;
268 // after the bank, we get the rank bits which thus interleaves
270 rank
= addr
% ranksPerChannel
;
271 addr
= addr
/ ranksPerChannel
;
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
;
280 // take out the channel part of the address
281 addr
= addr
/ channels
;
283 // next, the higher-order column bites
284 addr
= addr
/ (columnsPerRowBuffer
/ columnsPerStripe
);
286 // after the column bits, we get the bank bits to interleave
288 bank
= addr
% banksPerRank
;
289 addr
= addr
/ banksPerRank
;
291 // after the bank, we get the rank bits which thus interleaves
293 rank
= addr
% ranksPerChannel
;
294 addr
= addr
/ ranksPerChannel
;
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)
303 // take out the lower-order column bits
304 addr
= addr
/ columnsPerStripe
;
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
;
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
;
316 // next get the rank bits
317 rank
= addr
% ranksPerChannel
;
318 addr
= addr
/ ranksPerChannel
;
320 // next, the higher-order column bites
321 addr
= addr
/ (columnsPerRowBuffer
/ columnsPerStripe
);
323 // lastly, get the row bits
324 row
= addr
% rowsPerBank
;
325 addr
= addr
/ rowsPerBank
;
327 panic("Unknown address mapping policy chosen!");
329 assert(rank
< ranksPerChannel
);
330 assert(bank
< banksPerRank
);
331 assert(row
< rowsPerBank
);
332 assert(row
< Bank::NO_ROW
);
334 DPRINTF(DRAM
, "Address: %lld Rank %d Bank %d Row %d\n",
335 dramPktAddr
, rank
, bank
, row
);
337 // create the corresponding DRAM packet with the entry time and
338 // ready time set to the current tick, the latter will be updated
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
]);
346 DRAMCtrl::addToReadQueue(PacketPtr pkt
, unsigned int pktCount
)
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());
352 assert(pktCount
!= 0);
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
)]++;
369 // First check write buffer to see if the data is already at
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
375 if ((*i
)->addr
<= addr
&&
376 (addr
+ size
) <= ((*i
)->addr
+ (*i
)->size
)) {
380 DPRINTF(DRAM
, "Read to addr %lld with size %d serviced by "
381 "write queue\n", addr
, size
);
382 bytesReadWrQ
+= burstSize
;
387 // If not found in the write q, make a DRAM packet and
388 // push it onto the read queue
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
);
398 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, true);
399 dram_pkt
->burstHelper
= burst_helper
;
401 assert(!readQueueFull(1));
402 rdQLenPdf
[readQueue
.size() + respQueue
.size()]++;
404 DPRINTF(DRAM
, "Adding to read queue\n");
406 readQueue
.push_back(dram_pkt
);
409 avgRdQLen
= readQueue
.size() + respQueue
.size();
412 // Starting address of next dram pkt (aligend to burstSize boundary)
413 addr
= (addr
| (burstSize
- 1)) + 1;
416 // If all packets are serviced by write queue, we send the repsonse back
417 if (pktsServicedByWrQ
== pktCount
) {
418 accessAndRespond(pkt
, frontendLatency
);
422 // Update how many split packets are serviced by write queue
423 if (burst_helper
!= NULL
)
424 burst_helper
->burstsServiced
= pktsServicedByWrQ
;
426 // If we are not already scheduled to get a request out of the
428 if (!nextReqEvent
.scheduled()) {
429 DPRINTF(DRAM
, "Request scheduled immediately\n");
430 schedule(nextReqEvent
, curTick());
435 DRAMCtrl::addToWriteQueue(PacketPtr pkt
, unsigned int pktCount
)
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());
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
)]++;
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
455 auto w
= writeQueue
.begin();
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
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");
469 // update both the address and the 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");
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
;
485 // the new one starts after the current one, figure
486 // out where the existing one ends with respect to the
488 if (((*w
)->addr
+ (*w
)->size
) >= (addr
+ size
)) {
489 // check if the new one is completely subsumed in the
491 DPRINTF(DRAM
, "Merging write into existing burst\n");
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");
501 // the address is right, and only the size has
503 (*w
)->size
= addr
+ size
- (*w
)->addr
;
509 // if the item was not merged we need to create a new write
512 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, false);
514 assert(writeQueue
.size() < writeBufferSize
);
515 wrQLenPdf
[writeQueue
.size()]++;
517 DPRINTF(DRAM
, "Adding to write queue\n");
519 writeQueue
.push_back(dram_pkt
);
522 avgWrQLen
= writeQueue
.size();
524 // keep track of the fact that this burst effectively
525 // disappeared as it was merged with an existing one
529 // Starting address of next dram pkt (aligend to burstSize boundary)
530 addr
= (addr
| (burstSize
- 1)) + 1;
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
);
540 // If we are not already scheduled to get a request out of the
542 if (!nextReqEvent
.scheduled()) {
543 DPRINTF(DRAM
, "Request scheduled immediately\n");
544 schedule(nextReqEvent
, curTick());
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
);
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
);
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
);
565 DRAMCtrl::recvTimingReq(PacketPtr pkt
)
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();
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());
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
);
584 // Calc avg gap between requests
585 if (prevArrival
!= 0) {
586 totGap
+= curTick() - prevArrival
;
588 prevArrival
= curTick();
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
);
599 // check local buffers and do not accept if full
602 if (readQueueFull(dram_pkt_count
)) {
603 DPRINTF(DRAM
, "Read queue full, not accepting\n");
604 // remember that we have to retry this port
609 addToReadQueue(pkt
, dram_pkt_count
);
611 bytesReadSys
+= size
;
613 } else if (pkt
->isWrite()) {
615 if (writeQueueFull(dram_pkt_count
)) {
616 DPRINTF(DRAM
, "Write queue full, not accepting\n");
617 // remember that we have to retry this port
622 addToWriteQueue(pkt
, dram_pkt_count
);
624 bytesWrittenSys
+= size
;
627 DPRINTF(DRAM
,"Neither read nor write, ignore timing\n");
628 neitherReadNorWrite
++;
629 accessAndRespond(pkt
, 1);
636 DRAMCtrl::processRespondEvent()
639 "processRespondEvent(): Some req has reached its readyTime\n");
641 DRAMPacket
* dram_pkt
= respQueue
.front();
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
;
657 // it is not a split packet
658 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
661 delete respQueue
.front();
662 respQueue
.pop_front();
664 if (!respQueue
.empty()) {
665 assert(respQueue
.front()->readyTime
>= curTick());
666 assert(!respondEvent
.scheduled());
667 schedule(respondEvent
, respQueue
.front()->readyTime
);
669 // if there is nothing left in any queue, signal a drain
670 if (writeQueue
.empty() && readQueue
.empty() &&
672 drainManager
->signalDrainDone();
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
686 DRAMCtrl::chooseNext(std::deque
<DRAMPacket
*>& queue
)
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());
694 if (queue
.size() == 1) {
695 DPRINTF(DRAM
, "Single request, nothing to do\n");
699 if (memSchedPolicy
== Enums::fcfs
) {
700 // Do nothing, since the correct request is already head
701 } else if (memSchedPolicy
== Enums::frfcfs
) {
704 panic("No scheduling policy chosen\n");
708 DRAMCtrl::reorderQueue(std::deque
<DRAMPacket
*>& queue
)
710 // Only determine this when needed
711 uint64_t earliest_banks
= 0;
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();
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");
727 } else if (!found_earliest_pkt
) {
728 // No row hit, go for first ready
729 if (earliest_banks
== 0)
730 earliest_banks
= minBankActAt(queue
);
732 // simplistic approximation of when the bank can issue an
733 // activate, this is calculated in minBankActAt and could
735 Tick act_at
= bank
.openRow
== Bank::NO_ROW
?
737 std::max(bank
.preAllowedAt
, curTick()) + tRP
;
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
745 found_earliest_pkt
= true;
750 DRAMPacket
* selected_pkt
= *selected_pkt_it
;
751 queue
.erase(selected_pkt_it
);
752 queue
.push_front(selected_pkt
);
756 DRAMCtrl::accessAndRespond(PacketPtr pkt
, Tick static_latency
)
758 DPRINTF(DRAM
, "Responding to Address %lld.. ",pkt
->getAddr());
760 bool needsResponse
= pkt
->needsResponse();
761 // do the actual memory access which also turns the packet into a
765 // turn packet around to go back to requester if response expected
767 // access already turned the packet into a response
768 assert(pkt
->isResponse());
770 // @todo someone should pay for this
771 pkt
->busFirstWordDelay
= pkt
->busLastWordDelay
= 0;
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
);
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
);
782 DPRINTF(DRAM
, "Done\n");
788 DRAMCtrl::activateBank(Bank
& bank
, Tick act_tick
, uint32_t row
)
790 // get the rank index from the bank
791 uint8_t rank
= bank
.rank
;
793 assert(actTicks
[rank
].size() == activationLimit
);
795 DPRINTF(DRAM
, "Activate at tick %d\n", act_tick
);
797 // update the open row
798 assert(bank
.openRow
== Bank::NO_ROW
);
801 // start counting anew, this covers both the case when we
802 // auto-precharged, and when this access is forced to
804 bank
.bytesAccessed
= 0;
805 bank
.rowAccesses
= 0;
808 assert(numBanksActive
<= banksPerRank
* ranksPerChannel
);
810 DPRINTF(DRAM
, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
811 bank
.bank
, bank
.rank
, act_tick
, numBanksActive
);
813 DPRINTF(DRAMPower
, "%llu,ACT,%d,%d\n", divCeil(act_tick
, tCK
), bank
.bank
,
816 // The next access has to respect tRAS for this bank
817 bank
.preAllowedAt
= act_tick
+ tRAS
;
819 // Respect the row-to-column command delay
820 bank
.colAllowedAt
= act_tick
+ tRCD
;
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
826 banks
[rank
][i
].actAllowedAt
= std::max(act_tick
+ tRRD
,
827 banks
[rank
][i
].actAllowedAt
);
830 // next, we deal with tXAW, if the activation limit is disabled
832 if (actTicks
[rank
].empty())
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
);
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();
846 // record an new activation (in the future)
847 actTicks
[rank
].push_front(act_tick
);
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
);
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
);
872 DRAMCtrl::processActivateEvent()
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());
882 DRAMCtrl::prechargeBank(Bank
& bank
, Tick pre_at
, bool trace
)
884 // make sure the bank has an open row
885 assert(bank
.openRow
!= Bank::NO_ROW
);
887 // sample the bytes per activate here since we are closing
889 bytesPerActivate
.sample(bank
.bytesAccessed
);
891 bank
.openRow
= Bank::NO_ROW
;
893 // no precharge allowed before this one
894 bank
.preAllowedAt
= pre_at
;
896 Tick pre_done_at
= pre_at
+ tRP
;
898 bank
.actAllowedAt
= std::max(bank
.actAllowedAt
, pre_done_at
);
900 assert(numBanksActive
!= 0);
903 DPRINTF(DRAM
, "Precharging bank %d, rank %d at tick %lld, now got "
904 "%d active\n", bank
.bank
, bank
.rank
, pre_at
, numBanksActive
);
907 DPRINTF(DRAMPower
, "%llu,PRE,%d,%d\n", divCeil(pre_at
, tCK
),
908 bank
.bank
, bank
.rank
);
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
);
923 DRAMCtrl::processPrechargeEvent()
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
930 schedulePowerEvent(PWR_IDLE
, curTick());
935 DRAMCtrl::doDRAMAccess(DRAMPacket
* dram_pkt
)
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
);
941 Bank
& bank
= dram_pkt
->bankRef
;
943 // for the state we need to track if it is a row hit or not
946 // respect any constraints on the command (e.g. tRCD or tCCD)
947 Tick cmd_at
= std::max(bank
.colAllowedAt
, curTick());
949 // Determine the access latency and update the bank state
950 if (bank
.openRow
== dram_pkt
->row
) {
955 // If there is a page open, precharge it.
956 if (bank
.openRow
!= Bank::NO_ROW
) {
957 prechargeBank(bank
, std::max(bank
.preAllowedAt
, curTick()));
960 // next we need to account for the delay in activating the
962 Tick act_tick
= std::max(bank
.actAllowedAt
, curTick());
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
);
968 // issue the command as early as possible
969 cmd_at
= bank
.colAllowedAt
;
972 // we need to wait until the bus is available before we can issue
974 cmd_at
= std::max(cmd_at
, busBusyUntil
- tCL
);
976 // update the packet ready time
977 dram_pkt
->readyTime
= cmd_at
+ tCL
+ tBURST
;
979 // only one burst can use the bus at any one point in time
980 assert(dram_pkt
->readyTime
- busBusyUntil
>= tBURST
);
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
;
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
);
993 // increment the bytes accessed and the accesses per row
994 bank
.bytesAccessed
+= burstSize
;
997 // if we reached the max, then issue with an auto-precharge
998 bool auto_precharge
= pageMgmt
== Enums::close
||
999 bank
.rowAccesses
== maxAccessesPerRow
;
1001 // if we did not hit the limit, we might still want to
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;
1017 // either look at the read queue or write queue
1018 const deque
<DRAMPacket
*>& queue
= dram_pkt
->isRead
? readQueue
:
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)
1025 // keep on looking until we have found required condition or
1027 while (!(got_more_hits
&&
1028 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
)) &&
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
;
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
);
1046 // DRAMPower trace command to be written
1047 std::string mem_cmd
= dram_pkt
->isRead
? "RD" : "WR";
1049 // if this access should use auto-precharge, then we are
1051 if (auto_precharge
) {
1052 prechargeBank(bank
, std::max(curTick(), bank
.preAllowedAt
), false);
1054 mem_cmd
.append("A");
1056 DPRINTF(DRAM
, "Auto-precharged bank: %d\n", dram_pkt
->bankId
);
1060 busBusyUntil
= dram_pkt
->readyTime
;
1062 DPRINTF(DRAM
, "Access to %lld, ready at %lld bus busy until %lld.\n",
1063 dram_pkt
->addr
, dram_pkt
->readyTime
, busBusyUntil
);
1065 DPRINTF(DRAMPower
, "%llu,%s,%d,%d\n", divCeil(cmd_at
, tCK
), mem_cmd
,
1066 dram_pkt
->bank
, dram_pkt
->rank
);
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
);
1074 // Update the stats and schedule the next request
1075 if (dram_pkt
->isRead
) {
1079 bytesReadDRAM
+= burstSize
;
1080 perBankRdBursts
[dram_pkt
->bankId
]++;
1082 // Update latency stats
1083 totMemAccLat
+= dram_pkt
->readyTime
- dram_pkt
->entryTime
;
1084 totBusLat
+= tBURST
;
1085 totQLat
+= cmd_at
- dram_pkt
->entryTime
;
1090 bytesWritten
+= burstSize
;
1091 perBankWrBursts
[dram_pkt
->bankId
]++;
1096 DRAMCtrl::processNextReqEvent()
1098 if (busState
== READ_TO_WRITE
) {
1099 DPRINTF(DRAM
, "Switching to writes after %d reads with %d reads "
1100 "waiting\n", readsThisTime
, readQueue
.size());
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
);
1107 // now proceed to do the actual writes
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());
1113 wrPerTurnAround
.sample(writesThisTime
);
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");
1125 refreshState
= REF_PRE
;
1127 // hand control back to the refresh event loop
1128 schedule(refreshEvent
, curTick());
1131 // let the refresh finish before issuing any further requests
1135 // when we get here it is either a read or a write
1136 if (busState
== READ
) {
1138 // track if we should switch or not
1139 bool switch_to_writes
= false;
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
)) {
1148 switch_to_writes
= true;
1150 // check if we are drained
1151 if (respQueue
.empty () && drainManager
) {
1152 drainManager
->signalDrainDone();
1153 drainManager
= NULL
;
1156 // nothing to do, not even any point in scheduling an
1157 // event for the next request
1161 // Figure out which read request goes next, and move it to the
1162 // front of the read queue
1163 chooseNext(readQueue
);
1165 DRAMPacket
* dram_pkt
= readQueue
.front();
1167 doDRAMAccess(dram_pkt
);
1169 // At this point we're done dealing with the request
1170 readQueue
.pop_front();
1173 assert(dram_pkt
->size
<= burstSize
);
1174 assert(dram_pkt
->readyTime
>= curTick());
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
);
1182 assert(respQueue
.back()->readyTime
<= dram_pkt
->readyTime
);
1183 assert(respondEvent
.scheduled());
1186 respQueue
.push_back(dram_pkt
);
1188 // we have so many writes that we have to transition
1189 if (writeQueue
.size() > writeHighThreshold
) {
1190 switch_to_writes
= true;
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
;
1201 // add a bubble to the data bus, as defined by the
1203 busBusyUntil
+= tRTW
;
1205 // update the minimum timing between the requests,
1206 // this shifts us back in time far enough to do any
1208 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1211 chooseNext(writeQueue
);
1212 DRAMPacket
* dram_pkt
= writeQueue
.front();
1214 assert(dram_pkt
->size
<= burstSize
);
1215 doDRAMAccess(dram_pkt
);
1217 writeQueue
.pop_front();
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
&&
1227 (!readQueue
.empty() && writesThisTime
>= minWritesPerSwitch
)) {
1228 // turn the bus back around for reads again
1229 busState
= WRITE_TO_READ
;
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
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
;
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
);
1249 schedule(nextReqEvent
, std::max(nextReqTime
, curTick()));
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
) {
1262 DRAMCtrl::minBankActAt(const deque
<DRAMPacket
*>& queue
) const
1264 uint64_t bank_mask
= 0;
1265 Tick min_act_at
= MaxTick
;
1267 // deterimne if we have queued transactions targetting a
1269 vector
<bool> got_waiting(ranksPerChannel
* banksPerRank
, false);
1270 for (auto p
= queue
.begin(); p
!= queue
.end(); ++p
) {
1271 got_waiting
[(*p
)->bankId
] = true;
1274 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1275 for (int j
= 0; j
< banksPerRank
; j
++) {
1276 uint8_t bank_id
= i
* banksPerRank
+ j
;
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
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
;
1288 if (act_at
<= min_act_at
) {
1289 // reset bank mask if new minimum is found
1290 if (act_at
< min_act_at
)
1292 // set the bit corresponding to the available bank
1293 replaceBits(bank_mask
, bank_id
, bank_id
, 1);
1294 min_act_at
= act_at
;
1304 DRAMCtrl::processRefreshEvent()
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();
1312 refreshState
= REF_DRAIN
;
1314 DPRINTF(DRAM
, "Refresh due\n");
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
1323 DPRINTF(DRAM
, "Refresh awaiting draining\n");
1327 refreshState
= REF_PRE
;
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
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");
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
);
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
;
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);
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
);
1367 // at the moment this affects all ranks
1368 DPRINTF(DRAMPower
, "%llu,PREA,0,%d\n", divCeil(pre_at
, tCK
),
1372 DPRINTF(DRAM
, "All banks already precharged, starting refresh\n");
1374 // go ahead and kick the power state machine into gear if
1375 // we are already idle
1376 schedulePowerEvent(PWR_REF
, curTick());
1379 refreshState
= REF_RUN
;
1380 assert(numBanksActive
== 0);
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
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
);
1395 Tick ref_done_at
= curTick() + tRFC
;
1397 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1398 for (int j
= 0; j
< banksPerRank
; j
++) {
1399 banks
[i
][j
].actAllowedAt
= ref_done_at
;
1402 // at the moment this affects all ranks
1403 DPRINTF(DRAMPower
, "%llu,REF,0,%d\n", divCeil(curTick(), tCK
), i
);
1406 // make sure we did not wait so long that we cannot make up
1408 if (refreshDueAt
+ tREFI
< ref_done_at
) {
1409 fatal("Refresh was delayed so long we cannot catch up\n");
1412 // compensate for the delay in actually performing the refresh
1413 // when scheduling the next one
1414 schedule(refreshEvent
, refreshDueAt
+ tREFI
- tRP
);
1416 assert(!powerEvent
.scheduled());
1418 // move to the idle power state once the refresh is done, this
1419 // will also move the refresh state machine to the refresh
1421 schedulePowerEvent(PWR_IDLE
, ref_done_at
);
1423 DPRINTF(DRAMState
, "Refresh done at %llu and next refresh at %llu\n",
1424 ref_done_at
, refreshDueAt
+ tREFI
);
1429 DRAMCtrl::schedulePowerEvent(PowerState pwr_state
, Tick tick
)
1431 // respect causality
1432 assert(tick
>= curTick());
1434 if (!powerEvent
.scheduled()) {
1435 DPRINTF(DRAMState
, "Scheduling power event at %llu to state %d\n",
1438 // insert the new transition
1439 pwrStateTrans
= pwr_state
;
1441 schedule(powerEvent
, tick
);
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
);
1450 DRAMCtrl::processPowerEvent()
1452 // remember where we were, and for how long
1453 Tick duration
= curTick() - pwrStateTick
;
1454 PowerState prev_state
= pwrState
;
1456 // update the accounting
1457 pwrStateTime
[prev_state
] += duration
;
1459 pwrState
= pwrStateTrans
;
1460 pwrStateTick
= curTick();
1462 if (pwrState
== PWR_IDLE
) {
1463 DPRINTF(DRAMState
, "All banks precharged\n");
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
);
1470 // kick things into action again
1471 refreshState
= REF_IDLE
;
1472 assert(!nextReqEvent
.scheduled());
1473 schedule(nextReqEvent
, curTick());
1475 assert(prev_state
== PWR_ACT
);
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());
1483 // update the state in zero time and proceed below
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();
1504 DRAMCtrl::regStats()
1506 using namespace Stats
;
1508 AbstractMemory::regStats();
1511 .name(name() + ".readReqs")
1512 .desc("Number of read requests accepted");
1515 .name(name() + ".writeReqs")
1516 .desc("Number of write requests accepted");
1519 .name(name() + ".readBursts")
1520 .desc("Number of DRAM read bursts, "
1521 "including those serviced by the write queue");
1524 .name(name() + ".writeBursts")
1525 .desc("Number of DRAM write bursts, "
1526 "including those merged in the write queue");
1529 .name(name() + ".servicedByWrQ")
1530 .desc("Number of DRAM read bursts serviced by the write queue");
1533 .name(name() + ".mergedWrBursts")
1534 .desc("Number of DRAM write bursts merged with an existing one");
1537 .name(name() + ".neitherReadNorWriteReqs")
1538 .desc("Number of requests that are neither read nor write");
1541 .init(banksPerRank
* ranksPerChannel
)
1542 .name(name() + ".perBankRdBursts")
1543 .desc("Per bank write bursts");
1546 .init(banksPerRank
* ranksPerChannel
)
1547 .name(name() + ".perBankWrBursts")
1548 .desc("Per bank write bursts");
1551 .name(name() + ".avgRdQLen")
1552 .desc("Average read queue length when enqueuing")
1556 .name(name() + ".avgWrQLen")
1557 .desc("Average write queue length when enqueuing")
1561 .name(name() + ".totQLat")
1562 .desc("Total ticks spent queuing");
1565 .name(name() + ".totBusLat")
1566 .desc("Total ticks spent in databus transfers");
1569 .name(name() + ".totMemAccLat")
1570 .desc("Total ticks spent from burst creation until serviced "
1574 .name(name() + ".avgQLat")
1575 .desc("Average queueing delay per DRAM burst")
1578 avgQLat
= totQLat
/ (readBursts
- servicedByWrQ
);
1581 .name(name() + ".avgBusLat")
1582 .desc("Average bus latency per DRAM burst")
1585 avgBusLat
= totBusLat
/ (readBursts
- servicedByWrQ
);
1588 .name(name() + ".avgMemAccLat")
1589 .desc("Average memory access latency per DRAM burst")
1592 avgMemAccLat
= totMemAccLat
/ (readBursts
- servicedByWrQ
);
1595 .name(name() + ".numRdRetry")
1596 .desc("Number of times read queue was full causing retry");
1599 .name(name() + ".numWrRetry")
1600 .desc("Number of times write queue was full causing retry");
1603 .name(name() + ".readRowHits")
1604 .desc("Number of row buffer hits during reads");
1607 .name(name() + ".writeRowHits")
1608 .desc("Number of row buffer hits during writes");
1611 .name(name() + ".readRowHitRate")
1612 .desc("Row buffer hit rate for reads")
1615 readRowHitRate
= (readRowHits
/ (readBursts
- servicedByWrQ
)) * 100;
1618 .name(name() + ".writeRowHitRate")
1619 .desc("Row buffer hit rate for writes")
1622 writeRowHitRate
= (writeRowHits
/ (writeBursts
- mergedWrBursts
)) * 100;
1625 .init(ceilLog2(burstSize
) + 1)
1626 .name(name() + ".readPktSize")
1627 .desc("Read request sizes (log2)");
1630 .init(ceilLog2(burstSize
) + 1)
1631 .name(name() + ".writePktSize")
1632 .desc("Write request sizes (log2)");
1635 .init(readBufferSize
)
1636 .name(name() + ".rdQLenPdf")
1637 .desc("What read queue length does an incoming req see");
1640 .init(writeBufferSize
)
1641 .name(name() + ".wrQLenPdf")
1642 .desc("What write queue length does an incoming req see");
1645 .init(maxAccessesPerRow
)
1646 .name(name() + ".bytesPerActivate")
1647 .desc("Bytes accessed per row activation")
1651 .init(readBufferSize
)
1652 .name(name() + ".rdPerTurnAround")
1653 .desc("Reads before turning the bus around for writes")
1657 .init(writeBufferSize
)
1658 .name(name() + ".wrPerTurnAround")
1659 .desc("Writes before turning the bus around for reads")
1663 .name(name() + ".bytesReadDRAM")
1664 .desc("Total number of bytes read from DRAM");
1667 .name(name() + ".bytesReadWrQ")
1668 .desc("Total number of bytes read from write queue");
1671 .name(name() + ".bytesWritten")
1672 .desc("Total number of bytes written to DRAM");
1675 .name(name() + ".bytesReadSys")
1676 .desc("Total read bytes from the system interface side");
1679 .name(name() + ".bytesWrittenSys")
1680 .desc("Total written bytes from the system interface side");
1683 .name(name() + ".avgRdBW")
1684 .desc("Average DRAM read bandwidth in MiByte/s")
1687 avgRdBW
= (bytesReadDRAM
/ 1000000) / simSeconds
;
1690 .name(name() + ".avgWrBW")
1691 .desc("Average achieved write bandwidth in MiByte/s")
1694 avgWrBW
= (bytesWritten
/ 1000000) / simSeconds
;
1697 .name(name() + ".avgRdBWSys")
1698 .desc("Average system read bandwidth in MiByte/s")
1701 avgRdBWSys
= (bytesReadSys
/ 1000000) / simSeconds
;
1704 .name(name() + ".avgWrBWSys")
1705 .desc("Average system write bandwidth in MiByte/s")
1708 avgWrBWSys
= (bytesWrittenSys
/ 1000000) / simSeconds
;
1711 .name(name() + ".peakBW")
1712 .desc("Theoretical peak bandwidth in MiByte/s")
1715 peakBW
= (SimClock::Frequency
/ tBURST
) * burstSize
/ 1000000;
1718 .name(name() + ".busUtil")
1719 .desc("Data bus utilization in percentage")
1722 busUtil
= (avgRdBW
+ avgWrBW
) / peakBW
* 100;
1725 .name(name() + ".totGap")
1726 .desc("Total gap between requests");
1729 .name(name() + ".avgGap")
1730 .desc("Average gap between requests")
1733 avgGap
= totGap
/ (readReqs
+ writeReqs
);
1735 // Stats for DRAM Power calculation based on Micron datasheet
1737 .name(name() + ".busUtilRead")
1738 .desc("Data bus utilization in percentage for reads")
1741 busUtilRead
= avgRdBW
/ peakBW
* 100;
1744 .name(name() + ".busUtilWrite")
1745 .desc("Data bus utilization in percentage for writes")
1748 busUtilWrite
= avgWrBW
/ peakBW
* 100;
1751 .name(name() + ".pageHitRate")
1752 .desc("Row buffer hit rate, read and write combined")
1755 pageHitRate
= (writeRowHits
+ readRowHits
) /
1756 (writeBursts
- mergedWrBursts
+ readBursts
- servicedByWrQ
) * 100;
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");
1770 DRAMCtrl::recvFunctional(PacketPtr pkt
)
1772 // rely on the abstract memory
1773 functionalAccess(pkt
);
1777 DRAMCtrl::getSlavePort(const string
&if_name
, PortID idx
)
1779 if (if_name
!= "port") {
1780 return MemObject::getSlavePort(if_name
, idx
);
1787 DRAMCtrl::drain(DrainManager
*dm
)
1789 unsigned int count
= port
.drain(dm
);
1791 // if there is anything in any of our internal queues, keep track
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(),
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());
1809 setDrainState(Drainable::Draining
);
1811 setDrainState(Drainable::Drained
);
1815 DRAMCtrl::MemoryPort::MemoryPort(const std::string
& name
, DRAMCtrl
& _memory
)
1816 : QueuedSlavePort(name
, &_memory
, queue
), queue(_memory
, *this),
1821 DRAMCtrl::MemoryPort::getAddrRanges() const
1823 AddrRangeList ranges
;
1824 ranges
.push_back(memory
.getAddrRange());
1829 DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt
)
1831 pkt
->pushLabel(memory
.name());
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
);
1844 DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt
)
1846 return memory
.recvAtomic(pkt
);
1850 DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt
)
1852 // pass it to the memory controller
1853 return memory
.recvTimingReq(pkt
);
1857 DRAMCtrlParams::create()
1859 return new DRAMCtrl(this);