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 ranksPerChannel(p
->ranks_per_channel
),
71 banksPerRank(p
->banks_per_rank
), channels(p
->channels
), rowsPerBank(0),
72 readBufferSize(p
->read_buffer_size
),
73 writeBufferSize(p
->write_buffer_size
),
74 writeHighThreshold(writeBufferSize
* p
->write_high_thresh_perc
/ 100.0),
75 writeLowThreshold(writeBufferSize
* p
->write_low_thresh_perc
/ 100.0),
76 minWritesPerSwitch(p
->min_writes_per_switch
),
77 writesThisTime(0), readsThisTime(0),
78 tCK(p
->tCK
), tWTR(p
->tWTR
), tRTW(p
->tRTW
), tBURST(p
->tBURST
),
79 tRCD(p
->tRCD
), tCL(p
->tCL
), tRP(p
->tRP
), tRAS(p
->tRAS
), tWR(p
->tWR
),
80 tRTP(p
->tRTP
), tRFC(p
->tRFC
), tREFI(p
->tREFI
), tRRD(p
->tRRD
),
81 tXAW(p
->tXAW
), activationLimit(p
->activation_limit
),
82 memSchedPolicy(p
->mem_sched_policy
), addrMapping(p
->addr_mapping
),
83 pageMgmt(p
->page_policy
),
84 maxAccessesPerRow(p
->max_accesses_per_row
),
85 frontendLatency(p
->static_frontend_latency
),
86 backendLatency(p
->static_backend_latency
),
87 busBusyUntil(0), refreshDueAt(0), refreshState(REF_IDLE
),
88 pwrStateTrans(PWR_IDLE
), pwrState(PWR_IDLE
), prevArrival(0),
89 nextReqTime(0), pwrStateTick(0), numBanksActive(0)
91 // create the bank states based on the dimensions of the ranks and
93 banks
.resize(ranksPerChannel
);
94 actTicks
.resize(ranksPerChannel
);
95 for (size_t c
= 0; c
< ranksPerChannel
; ++c
) {
96 banks
[c
].resize(banksPerRank
);
97 actTicks
[c
].resize(activationLimit
, 0);
100 // set the bank indices
101 for (int r
= 0; r
< ranksPerChannel
; r
++) {
102 for (int b
= 0; b
< banksPerRank
; b
++) {
103 banks
[r
][b
].rank
= r
;
104 banks
[r
][b
].bank
= b
;
108 // perform a basic check of the write thresholds
109 if (p
->write_low_thresh_perc
>= p
->write_high_thresh_perc
)
110 fatal("Write buffer low threshold %d must be smaller than the "
111 "high threshold %d\n", p
->write_low_thresh_perc
,
112 p
->write_high_thresh_perc
);
114 // determine the rows per bank by looking at the total capacity
115 uint64_t capacity
= ULL(1) << ceilLog2(AbstractMemory::size());
117 DPRINTF(DRAM
, "Memory capacity %lld (%lld) bytes\n", capacity
,
118 AbstractMemory::size());
120 DPRINTF(DRAM
, "Row buffer size %d bytes with %d columns per row buffer\n",
121 rowBufferSize
, columnsPerRowBuffer
);
123 rowsPerBank
= capacity
/ (rowBufferSize
* banksPerRank
* ranksPerChannel
);
125 if (range
.interleaved()) {
126 if (channels
!= range
.stripes())
127 fatal("%s has %d interleaved address stripes but %d channel(s)\n",
128 name(), range
.stripes(), channels
);
130 if (addrMapping
== Enums::RoRaBaChCo
) {
131 if (rowBufferSize
!= range
.granularity()) {
132 fatal("Interleaving of %s doesn't match RoRaBaChCo "
133 "address map\n", name());
135 } else if (addrMapping
== Enums::RoRaBaCoCh
) {
136 if (system()->cacheLineSize() != range
.granularity()) {
137 fatal("Interleaving of %s doesn't match RoRaBaCoCh "
138 "address map\n", name());
140 } else if (addrMapping
== Enums::RoCoRaBaCh
) {
141 if (system()->cacheLineSize() != range
.granularity())
142 fatal("Interleaving of %s doesn't match RoCoRaBaCh "
143 "address map\n", name());
147 // some basic sanity checks
148 if (tREFI
<= tRP
|| tREFI
<= tRFC
) {
149 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
157 if (!port
.isConnected()) {
158 fatal("DRAMCtrl %s is unconnected!\n", name());
160 port
.sendRangeChange();
167 // update the start tick for the precharge accounting to the
169 pwrStateTick
= curTick();
171 // shift the bus busy time sufficiently far ahead that we never
172 // have to worry about negative values when computing the time for
173 // the next request, this will add an insignificant bubble at the
174 // start of simulation
175 busBusyUntil
= curTick() + tRP
+ tRCD
+ tCL
;
177 // kick off the refresh, and give ourselves enough time to
179 schedule(refreshEvent
, curTick() + tREFI
- tRP
);
183 DRAMCtrl::recvAtomic(PacketPtr pkt
)
185 DPRINTF(DRAM
, "recvAtomic: %s 0x%x\n", pkt
->cmdString(), pkt
->getAddr());
187 // do the actual memory access and turn the packet into a response
191 if (!pkt
->memInhibitAsserted() && pkt
->hasData()) {
192 // this value is not supposed to be accurate, just enough to
193 // keep things going, mimic a closed page
194 latency
= tRP
+ tRCD
+ tCL
;
200 DRAMCtrl::readQueueFull(unsigned int neededEntries
) const
202 DPRINTF(DRAM
, "Read queue limit %d, current size %d, entries needed %d\n",
203 readBufferSize
, readQueue
.size() + respQueue
.size(),
207 (readQueue
.size() + respQueue
.size() + neededEntries
) > readBufferSize
;
211 DRAMCtrl::writeQueueFull(unsigned int neededEntries
) const
213 DPRINTF(DRAM
, "Write queue limit %d, current size %d, entries needed %d\n",
214 writeBufferSize
, writeQueue
.size(), neededEntries
);
215 return (writeQueue
.size() + neededEntries
) > writeBufferSize
;
218 DRAMCtrl::DRAMPacket
*
219 DRAMCtrl::decodeAddr(PacketPtr pkt
, Addr dramPktAddr
, unsigned size
,
222 // decode the address based on the address mapping scheme, with
223 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
224 // channel, respectively
227 // use a 64-bit unsigned during the computations as the row is
228 // always the top bits, and check before creating the DRAMPacket
231 // truncate the address to the access granularity
232 Addr addr
= dramPktAddr
/ burstSize
;
234 // we have removed the lowest order address bits that denote the
235 // position within the column
236 if (addrMapping
== Enums::RoRaBaChCo
) {
237 // the lowest order bits denote the column to ensure that
238 // sequential cache lines occupy the same row
239 addr
= addr
/ columnsPerRowBuffer
;
241 // take out the channel part of the address
242 addr
= addr
/ channels
;
244 // after the channel bits, get the bank bits to interleave
246 bank
= addr
% banksPerRank
;
247 addr
= addr
/ banksPerRank
;
249 // after the bank, we get the rank bits which thus interleaves
251 rank
= addr
% ranksPerChannel
;
252 addr
= addr
/ ranksPerChannel
;
254 // lastly, get the row bits
255 row
= addr
% rowsPerBank
;
256 addr
= addr
/ rowsPerBank
;
257 } else if (addrMapping
== Enums::RoRaBaCoCh
) {
258 // take out the channel part of the address
259 addr
= addr
/ channels
;
262 addr
= addr
/ columnsPerRowBuffer
;
264 // after the column bits, we get the bank bits to interleave
266 bank
= addr
% banksPerRank
;
267 addr
= addr
/ banksPerRank
;
269 // after the bank, we get the rank bits which thus interleaves
271 rank
= addr
% ranksPerChannel
;
272 addr
= addr
/ ranksPerChannel
;
274 // lastly, get the row bits
275 row
= addr
% rowsPerBank
;
276 addr
= addr
/ rowsPerBank
;
277 } else if (addrMapping
== Enums::RoCoRaBaCh
) {
278 // optimise for closed page mode and utilise maximum
279 // parallelism of the DRAM (at the cost of power)
281 // take out the channel part of the address, not that this has
282 // to match with how accesses are interleaved between the
283 // controllers in the address mapping
284 addr
= addr
/ channels
;
286 // start with the bank bits, as this provides the maximum
287 // opportunity for parallelism between requests
288 bank
= addr
% banksPerRank
;
289 addr
= addr
/ banksPerRank
;
291 // next get the rank bits
292 rank
= addr
% ranksPerChannel
;
293 addr
= addr
/ ranksPerChannel
;
295 // next the column bits which we do not need to keep track of
296 // and simply skip past
297 addr
= addr
/ columnsPerRowBuffer
;
299 // lastly, get the row bits
300 row
= addr
% rowsPerBank
;
301 addr
= addr
/ rowsPerBank
;
303 panic("Unknown address mapping policy chosen!");
305 assert(rank
< ranksPerChannel
);
306 assert(bank
< banksPerRank
);
307 assert(row
< rowsPerBank
);
308 assert(row
< Bank::NO_ROW
);
310 DPRINTF(DRAM
, "Address: %lld Rank %d Bank %d Row %d\n",
311 dramPktAddr
, rank
, bank
, row
);
313 // create the corresponding DRAM packet with the entry time and
314 // ready time set to the current tick, the latter will be updated
316 uint16_t bank_id
= banksPerRank
* rank
+ bank
;
317 return new DRAMPacket(pkt
, isRead
, rank
, bank
, row
, bank_id
, dramPktAddr
,
318 size
, banks
[rank
][bank
]);
322 DRAMCtrl::addToReadQueue(PacketPtr pkt
, unsigned int pktCount
)
324 // only add to the read queue here. whenever the request is
325 // eventually done, set the readyTime, and call schedule()
326 assert(!pkt
->isWrite());
328 assert(pktCount
!= 0);
330 // if the request size is larger than burst size, the pkt is split into
331 // multiple DRAM packets
332 // Note if the pkt starting address is not aligened to burst size, the
333 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
334 // are aligned to burst size boundaries. This is to ensure we accurately
335 // check read packets against packets in write queue.
336 Addr addr
= pkt
->getAddr();
337 unsigned pktsServicedByWrQ
= 0;
338 BurstHelper
* burst_helper
= NULL
;
339 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
340 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
341 pkt
->getAddr() + pkt
->getSize()) - addr
;
342 readPktSize
[ceilLog2(size
)]++;
345 // First check write buffer to see if the data is already at
347 bool foundInWrQ
= false;
348 for (auto i
= writeQueue
.begin(); i
!= writeQueue
.end(); ++i
) {
349 // check if the read is subsumed in the write entry we are
351 if ((*i
)->addr
<= addr
&&
352 (addr
+ size
) <= ((*i
)->addr
+ (*i
)->size
)) {
356 DPRINTF(DRAM
, "Read to addr %lld with size %d serviced by "
357 "write queue\n", addr
, size
);
358 bytesReadWrQ
+= burstSize
;
363 // If not found in the write q, make a DRAM packet and
364 // push it onto the read queue
367 // Make the burst helper for split packets
368 if (pktCount
> 1 && burst_helper
== NULL
) {
369 DPRINTF(DRAM
, "Read to addr %lld translates to %d "
370 "dram requests\n", pkt
->getAddr(), pktCount
);
371 burst_helper
= new BurstHelper(pktCount
);
374 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, true);
375 dram_pkt
->burstHelper
= burst_helper
;
377 assert(!readQueueFull(1));
378 rdQLenPdf
[readQueue
.size() + respQueue
.size()]++;
380 DPRINTF(DRAM
, "Adding to read queue\n");
382 readQueue
.push_back(dram_pkt
);
385 avgRdQLen
= readQueue
.size() + respQueue
.size();
388 // Starting address of next dram pkt (aligend to burstSize boundary)
389 addr
= (addr
| (burstSize
- 1)) + 1;
392 // If all packets are serviced by write queue, we send the repsonse back
393 if (pktsServicedByWrQ
== pktCount
) {
394 accessAndRespond(pkt
, frontendLatency
);
398 // Update how many split packets are serviced by write queue
399 if (burst_helper
!= NULL
)
400 burst_helper
->burstsServiced
= pktsServicedByWrQ
;
402 // If we are not already scheduled to get a request out of the
404 if (!nextReqEvent
.scheduled()) {
405 DPRINTF(DRAM
, "Request scheduled immediately\n");
406 schedule(nextReqEvent
, curTick());
411 DRAMCtrl::addToWriteQueue(PacketPtr pkt
, unsigned int pktCount
)
413 // only add to the write queue here. whenever the request is
414 // eventually done, set the readyTime, and call schedule()
415 assert(pkt
->isWrite());
417 // if the request size is larger than burst size, the pkt is split into
418 // multiple DRAM packets
419 Addr addr
= pkt
->getAddr();
420 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
421 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
422 pkt
->getAddr() + pkt
->getSize()) - addr
;
423 writePktSize
[ceilLog2(size
)]++;
426 // see if we can merge with an existing item in the write
427 // queue and keep track of whether we have merged or not so we
428 // can stop at that point and also avoid enqueueing a new
431 auto w
= writeQueue
.begin();
433 while(!merged
&& w
!= writeQueue
.end()) {
434 // either of the two could be first, if they are the same
435 // it does not matter which way we go
436 if ((*w
)->addr
>= addr
) {
437 // the existing one starts after the new one, figure
438 // out where the new one ends with respect to the
440 if ((addr
+ size
) >= ((*w
)->addr
+ (*w
)->size
)) {
441 // check if the existing one is completely
442 // subsumed in the new one
443 DPRINTF(DRAM
, "Merging write covering existing burst\n");
445 // update both the address and the size
448 } else if ((addr
+ size
) >= (*w
)->addr
&&
449 ((*w
)->addr
+ (*w
)->size
- addr
) <= burstSize
) {
450 // the new one is just before or partially
451 // overlapping with the existing one, and together
452 // they fit within a burst
453 DPRINTF(DRAM
, "Merging write before existing burst\n");
455 // the existing queue item needs to be adjusted with
456 // respect to both address and size
457 (*w
)->size
= (*w
)->addr
+ (*w
)->size
- addr
;
461 // the new one starts after the current one, figure
462 // out where the existing one ends with respect to the
464 if (((*w
)->addr
+ (*w
)->size
) >= (addr
+ size
)) {
465 // check if the new one is completely subsumed in the
467 DPRINTF(DRAM
, "Merging write into existing burst\n");
469 // no adjustments necessary
470 } else if (((*w
)->addr
+ (*w
)->size
) >= addr
&&
471 (addr
+ size
- (*w
)->addr
) <= burstSize
) {
472 // the existing one is just before or partially
473 // overlapping with the new one, and together
474 // they fit within a burst
475 DPRINTF(DRAM
, "Merging write after existing burst\n");
477 // the address is right, and only the size has
479 (*w
)->size
= addr
+ size
- (*w
)->addr
;
485 // if the item was not merged we need to create a new write
488 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, false);
490 assert(writeQueue
.size() < writeBufferSize
);
491 wrQLenPdf
[writeQueue
.size()]++;
493 DPRINTF(DRAM
, "Adding to write queue\n");
495 writeQueue
.push_back(dram_pkt
);
498 avgWrQLen
= writeQueue
.size();
500 // keep track of the fact that this burst effectively
501 // disappeared as it was merged with an existing one
505 // Starting address of next dram pkt (aligend to burstSize boundary)
506 addr
= (addr
| (burstSize
- 1)) + 1;
509 // we do not wait for the writes to be send to the actual memory,
510 // but instead take responsibility for the consistency here and
511 // snoop the write queue for any upcoming reads
512 // @todo, if a pkt size is larger than burst size, we might need a
513 // different front end latency
514 accessAndRespond(pkt
, frontendLatency
);
516 // If we are not already scheduled to get a request out of the
518 if (!nextReqEvent
.scheduled()) {
519 DPRINTF(DRAM
, "Request scheduled immediately\n");
520 schedule(nextReqEvent
, curTick());
525 DRAMCtrl::printQs() const {
526 DPRINTF(DRAM
, "===READ QUEUE===\n\n");
527 for (auto i
= readQueue
.begin() ; i
!= readQueue
.end() ; ++i
) {
528 DPRINTF(DRAM
, "Read %lu\n", (*i
)->addr
);
530 DPRINTF(DRAM
, "\n===RESP QUEUE===\n\n");
531 for (auto i
= respQueue
.begin() ; i
!= respQueue
.end() ; ++i
) {
532 DPRINTF(DRAM
, "Response %lu\n", (*i
)->addr
);
534 DPRINTF(DRAM
, "\n===WRITE QUEUE===\n\n");
535 for (auto i
= writeQueue
.begin() ; i
!= writeQueue
.end() ; ++i
) {
536 DPRINTF(DRAM
, "Write %lu\n", (*i
)->addr
);
541 DRAMCtrl::recvTimingReq(PacketPtr pkt
)
543 /// @todo temporary hack to deal with memory corruption issues until
544 /// 4-phase transactions are complete
545 for (int x
= 0; x
< pendingDelete
.size(); x
++)
546 delete pendingDelete
[x
];
547 pendingDelete
.clear();
549 // This is where we enter from the outside world
550 DPRINTF(DRAM
, "recvTimingReq: request %s addr %lld size %d\n",
551 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
553 // simply drop inhibited packets for now
554 if (pkt
->memInhibitAsserted()) {
555 DPRINTF(DRAM
, "Inhibited packet -- Dropping it now\n");
556 pendingDelete
.push_back(pkt
);
560 // Calc avg gap between requests
561 if (prevArrival
!= 0) {
562 totGap
+= curTick() - prevArrival
;
564 prevArrival
= curTick();
567 // Find out how many dram packets a pkt translates to
568 // If the burst size is equal or larger than the pkt size, then a pkt
569 // translates to only one dram packet. Otherwise, a pkt translates to
570 // multiple dram packets
571 unsigned size
= pkt
->getSize();
572 unsigned offset
= pkt
->getAddr() & (burstSize
- 1);
573 unsigned int dram_pkt_count
= divCeil(offset
+ size
, burstSize
);
575 // check local buffers and do not accept if full
578 if (readQueueFull(dram_pkt_count
)) {
579 DPRINTF(DRAM
, "Read queue full, not accepting\n");
580 // remember that we have to retry this port
585 addToReadQueue(pkt
, dram_pkt_count
);
587 bytesReadSys
+= size
;
589 } else if (pkt
->isWrite()) {
591 if (writeQueueFull(dram_pkt_count
)) {
592 DPRINTF(DRAM
, "Write queue full, not accepting\n");
593 // remember that we have to retry this port
598 addToWriteQueue(pkt
, dram_pkt_count
);
600 bytesWrittenSys
+= size
;
603 DPRINTF(DRAM
,"Neither read nor write, ignore timing\n");
604 neitherReadNorWrite
++;
605 accessAndRespond(pkt
, 1);
612 DRAMCtrl::processRespondEvent()
615 "processRespondEvent(): Some req has reached its readyTime\n");
617 DRAMPacket
* dram_pkt
= respQueue
.front();
619 if (dram_pkt
->burstHelper
) {
620 // it is a split packet
621 dram_pkt
->burstHelper
->burstsServiced
++;
622 if (dram_pkt
->burstHelper
->burstsServiced
==
623 dram_pkt
->burstHelper
->burstCount
) {
624 // we have now serviced all children packets of a system packet
625 // so we can now respond to the requester
626 // @todo we probably want to have a different front end and back
627 // end latency for split packets
628 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
629 delete dram_pkt
->burstHelper
;
630 dram_pkt
->burstHelper
= NULL
;
633 // it is not a split packet
634 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
637 delete respQueue
.front();
638 respQueue
.pop_front();
640 if (!respQueue
.empty()) {
641 assert(respQueue
.front()->readyTime
>= curTick());
642 assert(!respondEvent
.scheduled());
643 schedule(respondEvent
, respQueue
.front()->readyTime
);
645 // if there is nothing left in any queue, signal a drain
646 if (writeQueue
.empty() && readQueue
.empty() &&
648 drainManager
->signalDrainDone();
653 // We have made a location in the queue available at this point,
654 // so if there is a read that was forced to wait, retry now
662 DRAMCtrl::chooseNext(std::deque
<DRAMPacket
*>& queue
)
664 // This method does the arbitration between requests. The chosen
665 // packet is simply moved to the head of the queue. The other
666 // methods know that this is the place to look. For example, with
667 // FCFS, this method does nothing
668 assert(!queue
.empty());
670 if (queue
.size() == 1) {
671 DPRINTF(DRAM
, "Single request, nothing to do\n");
675 if (memSchedPolicy
== Enums::fcfs
) {
676 // Do nothing, since the correct request is already head
677 } else if (memSchedPolicy
== Enums::frfcfs
) {
680 panic("No scheduling policy chosen\n");
684 DRAMCtrl::reorderQueue(std::deque
<DRAMPacket
*>& queue
)
686 // Only determine this when needed
687 uint64_t earliest_banks
= 0;
689 // Search for row hits first, if no row hit is found then schedule the
690 // packet to one of the earliest banks available
691 bool found_earliest_pkt
= false;
692 auto selected_pkt_it
= queue
.begin();
694 for (auto i
= queue
.begin(); i
!= queue
.end() ; ++i
) {
695 DRAMPacket
* dram_pkt
= *i
;
696 const Bank
& bank
= dram_pkt
->bankRef
;
697 // Check if it is a row hit
698 if (bank
.openRow
== dram_pkt
->row
) {
699 // FCFS within the hits
700 DPRINTF(DRAM
, "Row buffer hit\n");
703 } else if (!found_earliest_pkt
) {
704 // No row hit, go for first ready
705 if (earliest_banks
== 0)
706 earliest_banks
= minBankActAt(queue
);
708 // simplistic approximation of when the bank can issue an
709 // activate, this is calculated in minBankActAt and could
711 Tick act_at
= bank
.openRow
== Bank::NO_ROW
?
713 std::max(bank
.preAllowedAt
, curTick()) + tRP
;
715 // Bank is ready or is the first available bank
716 if (act_at
<= curTick() ||
717 bits(earliest_banks
, dram_pkt
->bankId
, dram_pkt
->bankId
)) {
718 // Remember the packet to be scheduled to one of the earliest
719 // banks available, FCFS amongst the earliest banks
721 found_earliest_pkt
= true;
726 DRAMPacket
* selected_pkt
= *selected_pkt_it
;
727 queue
.erase(selected_pkt_it
);
728 queue
.push_front(selected_pkt
);
732 DRAMCtrl::accessAndRespond(PacketPtr pkt
, Tick static_latency
)
734 DPRINTF(DRAM
, "Responding to Address %lld.. ",pkt
->getAddr());
736 bool needsResponse
= pkt
->needsResponse();
737 // do the actual memory access which also turns the packet into a
741 // turn packet around to go back to requester if response expected
743 // access already turned the packet into a response
744 assert(pkt
->isResponse());
746 // @todo someone should pay for this
747 pkt
->busFirstWordDelay
= pkt
->busLastWordDelay
= 0;
749 // queue the packet in the response queue to be sent out after
750 // the static latency has passed
751 port
.schedTimingResp(pkt
, curTick() + static_latency
);
753 // @todo the packet is going to be deleted, and the DRAMPacket
754 // is still having a pointer to it
755 pendingDelete
.push_back(pkt
);
758 DPRINTF(DRAM
, "Done\n");
764 DRAMCtrl::activateBank(Bank
& bank
, Tick act_tick
, uint32_t row
)
766 // get the rank index from the bank
767 uint8_t rank
= bank
.rank
;
769 assert(actTicks
[rank
].size() == activationLimit
);
771 DPRINTF(DRAM
, "Activate at tick %d\n", act_tick
);
773 // update the open row
774 assert(bank
.openRow
== Bank::NO_ROW
);
777 // start counting anew, this covers both the case when we
778 // auto-precharged, and when this access is forced to
780 bank
.bytesAccessed
= 0;
781 bank
.rowAccesses
= 0;
784 assert(numBanksActive
<= banksPerRank
* ranksPerChannel
);
786 DPRINTF(DRAM
, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
787 bank
.bank
, bank
.rank
, act_tick
, numBanksActive
);
789 DPRINTF(DRAMPower
, "%llu,ACT,%d,%d\n", divCeil(act_tick
, tCK
), bank
.bank
,
792 // The next access has to respect tRAS for this bank
793 bank
.preAllowedAt
= act_tick
+ tRAS
;
795 // Respect the row-to-column command delay
796 bank
.colAllowedAt
= act_tick
+ tRCD
;
798 // start by enforcing tRRD
799 for(int i
= 0; i
< banksPerRank
; i
++) {
800 // next activate to any bank in this rank must not happen
802 banks
[rank
][i
].actAllowedAt
= std::max(act_tick
+ tRRD
,
803 banks
[rank
][i
].actAllowedAt
);
806 // next, we deal with tXAW, if the activation limit is disabled
808 if (actTicks
[rank
].empty())
812 if (actTicks
[rank
].back() && (act_tick
- actTicks
[rank
].back()) < tXAW
) {
813 panic("Got %d activates in window %d (%llu - %llu) which is smaller "
814 "than %llu\n", activationLimit
, act_tick
- actTicks
[rank
].back(),
815 act_tick
, actTicks
[rank
].back(), tXAW
);
818 // shift the times used for the book keeping, the last element
819 // (highest index) is the oldest one and hence the lowest value
820 actTicks
[rank
].pop_back();
822 // record an new activation (in the future)
823 actTicks
[rank
].push_front(act_tick
);
825 // cannot activate more than X times in time window tXAW, push the
826 // next one (the X + 1'st activate) to be tXAW away from the
827 // oldest in our window of X
828 if (actTicks
[rank
].back() && (act_tick
- actTicks
[rank
].back()) < tXAW
) {
829 DPRINTF(DRAM
, "Enforcing tXAW with X = %d, next activate no earlier "
830 "than %llu\n", activationLimit
, actTicks
[rank
].back() + tXAW
);
831 for(int j
= 0; j
< banksPerRank
; j
++)
832 // next activate must not happen before end of window
833 banks
[rank
][j
].actAllowedAt
=
834 std::max(actTicks
[rank
].back() + tXAW
,
835 banks
[rank
][j
].actAllowedAt
);
838 // at the point when this activate takes place, make sure we
839 // transition to the active power state
840 if (!activateEvent
.scheduled())
841 schedule(activateEvent
, act_tick
);
842 else if (activateEvent
.when() > act_tick
)
843 // move it sooner in time
844 reschedule(activateEvent
, act_tick
);
848 DRAMCtrl::processActivateEvent()
850 // we should transition to the active state as soon as any bank is active
851 if (pwrState
!= PWR_ACT
)
852 // note that at this point numBanksActive could be back at
853 // zero again due to a precharge scheduled in the future
854 schedulePowerEvent(PWR_ACT
, curTick());
858 DRAMCtrl::prechargeBank(Bank
& bank
, Tick pre_at
, bool trace
)
860 // make sure the bank has an open row
861 assert(bank
.openRow
!= Bank::NO_ROW
);
863 // sample the bytes per activate here since we are closing
865 bytesPerActivate
.sample(bank
.bytesAccessed
);
867 bank
.openRow
= Bank::NO_ROW
;
869 // no precharge allowed before this one
870 bank
.preAllowedAt
= pre_at
;
872 Tick pre_done_at
= pre_at
+ tRP
;
874 bank
.actAllowedAt
= std::max(bank
.actAllowedAt
, pre_done_at
);
876 assert(numBanksActive
!= 0);
879 DPRINTF(DRAM
, "Precharging bank %d, rank %d at tick %lld, now got "
880 "%d active\n", bank
.bank
, bank
.rank
, pre_at
, numBanksActive
);
883 DPRINTF(DRAMPower
, "%llu,PRE,%d,%d\n", divCeil(pre_at
, tCK
),
884 bank
.bank
, bank
.rank
);
886 // if we look at the current number of active banks we might be
887 // tempted to think the DRAM is now idle, however this can be
888 // undone by an activate that is scheduled to happen before we
889 // would have reached the idle state, so schedule an event and
890 // rather check once we actually make it to the point in time when
891 // the (last) precharge takes place
892 if (!prechargeEvent
.scheduled())
893 schedule(prechargeEvent
, pre_done_at
);
894 else if (prechargeEvent
.when() < pre_done_at
)
895 reschedule(prechargeEvent
, pre_done_at
);
899 DRAMCtrl::processPrechargeEvent()
901 // if we reached zero, then special conditions apply as we track
902 // if all banks are precharged for the power models
903 if (numBanksActive
== 0) {
904 // we should transition to the idle state when the last bank
906 schedulePowerEvent(PWR_IDLE
, curTick());
911 DRAMCtrl::doDRAMAccess(DRAMPacket
* dram_pkt
)
913 DPRINTF(DRAM
, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
914 dram_pkt
->addr
, dram_pkt
->rank
, dram_pkt
->bank
, dram_pkt
->row
);
917 Bank
& bank
= dram_pkt
->bankRef
;
919 // for the state we need to track if it is a row hit or not
922 // respect any constraints on the command (e.g. tRCD or tCCD)
923 Tick cmd_at
= std::max(bank
.colAllowedAt
, curTick());
925 // Determine the access latency and update the bank state
926 if (bank
.openRow
== dram_pkt
->row
) {
931 // If there is a page open, precharge it.
932 if (bank
.openRow
!= Bank::NO_ROW
) {
933 prechargeBank(bank
, std::max(bank
.preAllowedAt
, curTick()));
936 // next we need to account for the delay in activating the
938 Tick act_tick
= std::max(bank
.actAllowedAt
, curTick());
940 // Record the activation and deal with all the global timing
941 // constraints caused be a new activation (tRRD and tXAW)
942 activateBank(bank
, act_tick
, dram_pkt
->row
);
944 // issue the command as early as possible
945 cmd_at
= bank
.colAllowedAt
;
948 // we need to wait until the bus is available before we can issue
950 cmd_at
= std::max(cmd_at
, busBusyUntil
- tCL
);
952 // update the packet ready time
953 dram_pkt
->readyTime
= cmd_at
+ tCL
+ tBURST
;
955 // only one burst can use the bus at any one point in time
956 assert(dram_pkt
->readyTime
- busBusyUntil
>= tBURST
);
958 // not strictly necessary, but update the time for the next
959 // read/write (add a max with tCCD here)
960 bank
.colAllowedAt
= cmd_at
+ tBURST
;
962 // If this is a write, we also need to respect the write recovery
963 // time before a precharge, in the case of a read, respect the
964 // read to precharge constraint
965 bank
.preAllowedAt
= std::max(bank
.preAllowedAt
,
966 dram_pkt
->isRead
? cmd_at
+ tRTP
:
967 dram_pkt
->readyTime
+ tWR
);
969 // increment the bytes accessed and the accesses per row
970 bank
.bytesAccessed
+= burstSize
;
973 // if we reached the max, then issue with an auto-precharge
974 bool auto_precharge
= pageMgmt
== Enums::close
||
975 bank
.rowAccesses
== maxAccessesPerRow
;
977 // if we did not hit the limit, we might still want to
979 if (!auto_precharge
&&
980 (pageMgmt
== Enums::open_adaptive
||
981 pageMgmt
== Enums::close_adaptive
)) {
982 // a twist on the open and close page policies:
983 // 1) open_adaptive page policy does not blindly keep the
984 // page open, but close it if there are no row hits, and there
985 // are bank conflicts in the queue
986 // 2) close_adaptive page policy does not blindly close the
987 // page, but closes it only if there are no row hits in the queue.
988 // In this case, only force an auto precharge when there
989 // are no same page hits in the queue
990 bool got_more_hits
= false;
991 bool got_bank_conflict
= false;
993 // either look at the read queue or write queue
994 const deque
<DRAMPacket
*>& queue
= dram_pkt
->isRead
? readQueue
:
996 auto p
= queue
.begin();
997 // make sure we are not considering the packet that we are
998 // currently dealing with (which is the head of the queue)
1001 // keep on looking until we have found required condition or
1003 while (!(got_more_hits
&&
1004 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
)) &&
1006 bool same_rank_bank
= (dram_pkt
->rank
== (*p
)->rank
) &&
1007 (dram_pkt
->bank
== (*p
)->bank
);
1008 bool same_row
= dram_pkt
->row
== (*p
)->row
;
1009 got_more_hits
|= same_rank_bank
&& same_row
;
1010 got_bank_conflict
|= same_rank_bank
&& !same_row
;
1014 // auto pre-charge when either
1015 // 1) open_adaptive policy, we have not got any more hits, and
1016 // have a bank conflict
1017 // 2) close_adaptive policy and we have not got any more hits
1018 auto_precharge
= !got_more_hits
&&
1019 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
);
1022 // DRAMPower trace command to be written
1023 std::string mem_cmd
= dram_pkt
->isRead
? "RD" : "WR";
1025 // if this access should use auto-precharge, then we are
1027 if (auto_precharge
) {
1028 prechargeBank(bank
, std::max(curTick(), bank
.preAllowedAt
), false);
1030 mem_cmd
.append("A");
1032 DPRINTF(DRAM
, "Auto-precharged bank: %d\n", dram_pkt
->bankId
);
1036 busBusyUntil
= dram_pkt
->readyTime
;
1038 DPRINTF(DRAM
, "Access to %lld, ready at %lld bus busy until %lld.\n",
1039 dram_pkt
->addr
, dram_pkt
->readyTime
, busBusyUntil
);
1041 DPRINTF(DRAMPower
, "%llu,%s,%d,%d\n", divCeil(cmd_at
, tCK
), mem_cmd
,
1042 dram_pkt
->bank
, dram_pkt
->rank
);
1044 // Update the minimum timing between the requests, this is a
1045 // conservative estimate of when we have to schedule the next
1046 // request to not introduce any unecessary bubbles. In most cases
1047 // we will wake up sooner than we have to.
1048 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1050 // Update the stats and schedule the next request
1051 if (dram_pkt
->isRead
) {
1055 bytesReadDRAM
+= burstSize
;
1056 perBankRdBursts
[dram_pkt
->bankId
]++;
1058 // Update latency stats
1059 totMemAccLat
+= dram_pkt
->readyTime
- dram_pkt
->entryTime
;
1060 totBusLat
+= tBURST
;
1061 totQLat
+= cmd_at
- dram_pkt
->entryTime
;
1066 bytesWritten
+= burstSize
;
1067 perBankWrBursts
[dram_pkt
->bankId
]++;
1072 DRAMCtrl::processNextReqEvent()
1074 if (busState
== READ_TO_WRITE
) {
1075 DPRINTF(DRAM
, "Switching to writes after %d reads with %d reads "
1076 "waiting\n", readsThisTime
, readQueue
.size());
1078 // sample and reset the read-related stats as we are now
1079 // transitioning to writes, and all reads are done
1080 rdPerTurnAround
.sample(readsThisTime
);
1083 // now proceed to do the actual writes
1085 } else if (busState
== WRITE_TO_READ
) {
1086 DPRINTF(DRAM
, "Switching to reads after %d writes with %d writes "
1087 "waiting\n", writesThisTime
, writeQueue
.size());
1089 wrPerTurnAround
.sample(writesThisTime
);
1095 if (refreshState
!= REF_IDLE
) {
1096 // if a refresh waiting for this event loop to finish, then hand
1097 // over now, and do not schedule a new nextReqEvent
1098 if (refreshState
== REF_DRAIN
) {
1099 DPRINTF(DRAM
, "Refresh drain done, now precharging\n");
1101 refreshState
= REF_PRE
;
1103 // hand control back to the refresh event loop
1104 schedule(refreshEvent
, curTick());
1107 // let the refresh finish before issuing any further requests
1111 // when we get here it is either a read or a write
1112 if (busState
== READ
) {
1114 // track if we should switch or not
1115 bool switch_to_writes
= false;
1117 if (readQueue
.empty()) {
1118 // In the case there is no read request to go next,
1119 // trigger writes if we have passed the low threshold (or
1120 // if we are draining)
1121 if (!writeQueue
.empty() &&
1122 (drainManager
|| writeQueue
.size() > writeLowThreshold
)) {
1124 switch_to_writes
= true;
1126 // check if we are drained
1127 if (respQueue
.empty () && drainManager
) {
1128 drainManager
->signalDrainDone();
1129 drainManager
= NULL
;
1132 // nothing to do, not even any point in scheduling an
1133 // event for the next request
1137 // Figure out which read request goes next, and move it to the
1138 // front of the read queue
1139 chooseNext(readQueue
);
1141 DRAMPacket
* dram_pkt
= readQueue
.front();
1143 doDRAMAccess(dram_pkt
);
1145 // At this point we're done dealing with the request
1146 readQueue
.pop_front();
1149 assert(dram_pkt
->size
<= burstSize
);
1150 assert(dram_pkt
->readyTime
>= curTick());
1152 // Insert into response queue. It will be sent back to the
1153 // requestor at its readyTime
1154 if (respQueue
.empty()) {
1155 assert(!respondEvent
.scheduled());
1156 schedule(respondEvent
, dram_pkt
->readyTime
);
1158 assert(respQueue
.back()->readyTime
<= dram_pkt
->readyTime
);
1159 assert(respondEvent
.scheduled());
1162 respQueue
.push_back(dram_pkt
);
1164 // we have so many writes that we have to transition
1165 if (writeQueue
.size() > writeHighThreshold
) {
1166 switch_to_writes
= true;
1170 // switching to writes, either because the read queue is empty
1171 // and the writes have passed the low threshold (or we are
1172 // draining), or because the writes hit the hight threshold
1173 if (switch_to_writes
) {
1174 // transition to writing
1175 busState
= READ_TO_WRITE
;
1177 // add a bubble to the data bus, as defined by the
1179 busBusyUntil
+= tRTW
;
1181 // update the minimum timing between the requests,
1182 // this shifts us back in time far enough to do any
1184 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1187 chooseNext(writeQueue
);
1188 DRAMPacket
* dram_pkt
= writeQueue
.front();
1190 assert(dram_pkt
->size
<= burstSize
);
1191 doDRAMAccess(dram_pkt
);
1193 writeQueue
.pop_front();
1196 // If we emptied the write queue, or got sufficiently below the
1197 // threshold (using the minWritesPerSwitch as the hysteresis) and
1198 // are not draining, or we have reads waiting and have done enough
1199 // writes, then switch to reads.
1200 if (writeQueue
.empty() ||
1201 (writeQueue
.size() + minWritesPerSwitch
< writeLowThreshold
&&
1203 (!readQueue
.empty() && writesThisTime
>= minWritesPerSwitch
)) {
1204 // turn the bus back around for reads again
1205 busState
= WRITE_TO_READ
;
1207 // note that the we switch back to reads also in the idle
1208 // case, which eventually will check for any draining and
1209 // also pause any further scheduling if there is really
1212 // here we get a bit creative and shift the bus busy time not
1213 // just the tWTR, but also a CAS latency to capture the fact
1214 // that we are allowed to prepare a new bank, but not issue a
1215 // read command until after tWTR, in essence we capture a
1216 // bubble on the data bus that is tWTR + tCL
1217 busBusyUntil
+= tWTR
+ tCL
;
1219 // update the minimum timing between the requests, this shifts
1220 // us back in time far enough to do any bank preparation
1221 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1225 schedule(nextReqEvent
, std::max(nextReqTime
, curTick()));
1227 // If there is space available and we have writes waiting then let
1228 // them retry. This is done here to ensure that the retry does not
1229 // cause a nextReqEvent to be scheduled before we do so as part of
1230 // the next request processing
1231 if (retryWrReq
&& writeQueue
.size() < writeBufferSize
) {
1238 DRAMCtrl::minBankActAt(const deque
<DRAMPacket
*>& queue
) const
1240 uint64_t bank_mask
= 0;
1241 Tick min_act_at
= MaxTick
;
1243 // deterimne if we have queued transactions targetting a
1245 vector
<bool> got_waiting(ranksPerChannel
* banksPerRank
, false);
1246 for (auto p
= queue
.begin(); p
!= queue
.end(); ++p
) {
1247 got_waiting
[(*p
)->bankId
] = true;
1250 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1251 for (int j
= 0; j
< banksPerRank
; j
++) {
1252 uint8_t bank_id
= i
* banksPerRank
+ j
;
1254 // if we have waiting requests for the bank, and it is
1255 // amongst the first available, update the mask
1256 if (got_waiting
[bank_id
]) {
1257 // simplistic approximation of when the bank can issue
1258 // an activate, ignoring any rank-to-rank switching
1260 Tick act_at
= banks
[i
][j
].openRow
== Bank::NO_ROW
?
1261 banks
[i
][j
].actAllowedAt
:
1262 std::max(banks
[i
][j
].preAllowedAt
, curTick()) + tRP
;
1264 if (act_at
<= min_act_at
) {
1265 // reset bank mask if new minimum is found
1266 if (act_at
< min_act_at
)
1268 // set the bit corresponding to the available bank
1269 replaceBits(bank_mask
, bank_id
, bank_id
, 1);
1270 min_act_at
= act_at
;
1280 DRAMCtrl::processRefreshEvent()
1282 // when first preparing the refresh, remember when it was due
1283 if (refreshState
== REF_IDLE
) {
1284 // remember when the refresh is due
1285 refreshDueAt
= curTick();
1288 refreshState
= REF_DRAIN
;
1290 DPRINTF(DRAM
, "Refresh due\n");
1293 // let any scheduled read or write go ahead, after which it will
1294 // hand control back to this event loop
1295 if (refreshState
== REF_DRAIN
) {
1296 if (nextReqEvent
.scheduled()) {
1297 // hand control over to the request loop until it is
1299 DPRINTF(DRAM
, "Refresh awaiting draining\n");
1303 refreshState
= REF_PRE
;
1307 // at this point, ensure that all banks are precharged
1308 if (refreshState
== REF_PRE
) {
1309 // precharge any active bank if we are not already in the idle
1311 if (pwrState
!= PWR_IDLE
) {
1312 // at the moment, we use a precharge all even if there is
1313 // only a single bank open
1314 DPRINTF(DRAM
, "Precharging all\n");
1316 // first determine when we can precharge
1317 Tick pre_at
= curTick();
1318 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1319 for (int j
= 0; j
< banksPerRank
; j
++) {
1320 // respect both causality and any existing bank
1321 // constraints, some banks could already have a
1322 // (auto) precharge scheduled
1323 pre_at
= std::max(banks
[i
][j
].preAllowedAt
, pre_at
);
1327 // make sure all banks are precharged, and for those that
1328 // already are, update their availability
1329 Tick act_allowed_at
= pre_at
+ tRP
;
1331 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1332 for (int j
= 0; j
< banksPerRank
; j
++) {
1333 if (banks
[i
][j
].openRow
!= Bank::NO_ROW
) {
1334 prechargeBank(banks
[i
][j
], pre_at
, false);
1336 banks
[i
][j
].actAllowedAt
=
1337 std::max(banks
[i
][j
].actAllowedAt
, act_allowed_at
);
1338 banks
[i
][j
].preAllowedAt
=
1339 std::max(banks
[i
][j
].preAllowedAt
, pre_at
);
1343 // at the moment this affects all ranks
1344 DPRINTF(DRAMPower
, "%llu,PREA,0,%d\n", divCeil(pre_at
, tCK
),
1348 DPRINTF(DRAM
, "All banks already precharged, starting refresh\n");
1350 // go ahead and kick the power state machine into gear if
1351 // we are already idle
1352 schedulePowerEvent(PWR_REF
, curTick());
1355 refreshState
= REF_RUN
;
1356 assert(numBanksActive
== 0);
1358 // wait for all banks to be precharged, at which point the
1359 // power state machine will transition to the idle state, and
1360 // automatically move to a refresh, at that point it will also
1361 // call this method to get the refresh event loop going again
1365 // last but not least we perform the actual refresh
1366 if (refreshState
== REF_RUN
) {
1367 // should never get here with any banks active
1368 assert(numBanksActive
== 0);
1369 assert(pwrState
== PWR_REF
);
1371 Tick ref_done_at
= curTick() + tRFC
;
1373 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1374 for (int j
= 0; j
< banksPerRank
; j
++) {
1375 banks
[i
][j
].actAllowedAt
= ref_done_at
;
1378 // at the moment this affects all ranks
1379 DPRINTF(DRAMPower
, "%llu,REF,0,%d\n", divCeil(curTick(), tCK
), i
);
1382 // make sure we did not wait so long that we cannot make up
1384 if (refreshDueAt
+ tREFI
< ref_done_at
) {
1385 fatal("Refresh was delayed so long we cannot catch up\n");
1388 // compensate for the delay in actually performing the refresh
1389 // when scheduling the next one
1390 schedule(refreshEvent
, refreshDueAt
+ tREFI
- tRP
);
1392 assert(!powerEvent
.scheduled());
1394 // move to the idle power state once the refresh is done, this
1395 // will also move the refresh state machine to the refresh
1397 schedulePowerEvent(PWR_IDLE
, ref_done_at
);
1399 DPRINTF(DRAMState
, "Refresh done at %llu and next refresh at %llu\n",
1400 ref_done_at
, refreshDueAt
+ tREFI
);
1405 DRAMCtrl::schedulePowerEvent(PowerState pwr_state
, Tick tick
)
1407 // respect causality
1408 assert(tick
>= curTick());
1410 if (!powerEvent
.scheduled()) {
1411 DPRINTF(DRAMState
, "Scheduling power event at %llu to state %d\n",
1414 // insert the new transition
1415 pwrStateTrans
= pwr_state
;
1417 schedule(powerEvent
, tick
);
1419 panic("Scheduled power event at %llu to state %d, "
1420 "with scheduled event at %llu to %d\n", tick
, pwr_state
,
1421 powerEvent
.when(), pwrStateTrans
);
1426 DRAMCtrl::processPowerEvent()
1428 // remember where we were, and for how long
1429 Tick duration
= curTick() - pwrStateTick
;
1430 PowerState prev_state
= pwrState
;
1432 // update the accounting
1433 pwrStateTime
[prev_state
] += duration
;
1435 pwrState
= pwrStateTrans
;
1436 pwrStateTick
= curTick();
1438 if (pwrState
== PWR_IDLE
) {
1439 DPRINTF(DRAMState
, "All banks precharged\n");
1441 // if we were refreshing, make sure we start scheduling requests again
1442 if (prev_state
== PWR_REF
) {
1443 DPRINTF(DRAMState
, "Was refreshing for %llu ticks\n", duration
);
1444 assert(pwrState
== PWR_IDLE
);
1446 // kick things into action again
1447 refreshState
= REF_IDLE
;
1448 assert(!nextReqEvent
.scheduled());
1449 schedule(nextReqEvent
, curTick());
1451 assert(prev_state
== PWR_ACT
);
1453 // if we have a pending refresh, and are now moving to
1454 // the idle state, direclty transition to a refresh
1455 if (refreshState
== REF_RUN
) {
1456 // there should be nothing waiting at this point
1457 assert(!powerEvent
.scheduled());
1459 // update the state in zero time and proceed below
1465 // we transition to the refresh state, let the refresh state
1466 // machine know of this state update and let it deal with the
1467 // scheduling of the next power state transition as well as the
1468 // following refresh
1469 if (pwrState
== PWR_REF
) {
1470 DPRINTF(DRAMState
, "Refreshing\n");
1471 // kick the refresh event loop into action again, and that
1472 // in turn will schedule a transition to the idle power
1473 // state once the refresh is done
1474 assert(refreshState
== REF_RUN
);
1475 processRefreshEvent();
1480 DRAMCtrl::regStats()
1482 using namespace Stats
;
1484 AbstractMemory::regStats();
1487 .name(name() + ".readReqs")
1488 .desc("Number of read requests accepted");
1491 .name(name() + ".writeReqs")
1492 .desc("Number of write requests accepted");
1495 .name(name() + ".readBursts")
1496 .desc("Number of DRAM read bursts, "
1497 "including those serviced by the write queue");
1500 .name(name() + ".writeBursts")
1501 .desc("Number of DRAM write bursts, "
1502 "including those merged in the write queue");
1505 .name(name() + ".servicedByWrQ")
1506 .desc("Number of DRAM read bursts serviced by the write queue");
1509 .name(name() + ".mergedWrBursts")
1510 .desc("Number of DRAM write bursts merged with an existing one");
1513 .name(name() + ".neitherReadNorWriteReqs")
1514 .desc("Number of requests that are neither read nor write");
1517 .init(banksPerRank
* ranksPerChannel
)
1518 .name(name() + ".perBankRdBursts")
1519 .desc("Per bank write bursts");
1522 .init(banksPerRank
* ranksPerChannel
)
1523 .name(name() + ".perBankWrBursts")
1524 .desc("Per bank write bursts");
1527 .name(name() + ".avgRdQLen")
1528 .desc("Average read queue length when enqueuing")
1532 .name(name() + ".avgWrQLen")
1533 .desc("Average write queue length when enqueuing")
1537 .name(name() + ".totQLat")
1538 .desc("Total ticks spent queuing");
1541 .name(name() + ".totBusLat")
1542 .desc("Total ticks spent in databus transfers");
1545 .name(name() + ".totMemAccLat")
1546 .desc("Total ticks spent from burst creation until serviced "
1550 .name(name() + ".avgQLat")
1551 .desc("Average queueing delay per DRAM burst")
1554 avgQLat
= totQLat
/ (readBursts
- servicedByWrQ
);
1557 .name(name() + ".avgBusLat")
1558 .desc("Average bus latency per DRAM burst")
1561 avgBusLat
= totBusLat
/ (readBursts
- servicedByWrQ
);
1564 .name(name() + ".avgMemAccLat")
1565 .desc("Average memory access latency per DRAM burst")
1568 avgMemAccLat
= totMemAccLat
/ (readBursts
- servicedByWrQ
);
1571 .name(name() + ".numRdRetry")
1572 .desc("Number of times read queue was full causing retry");
1575 .name(name() + ".numWrRetry")
1576 .desc("Number of times write queue was full causing retry");
1579 .name(name() + ".readRowHits")
1580 .desc("Number of row buffer hits during reads");
1583 .name(name() + ".writeRowHits")
1584 .desc("Number of row buffer hits during writes");
1587 .name(name() + ".readRowHitRate")
1588 .desc("Row buffer hit rate for reads")
1591 readRowHitRate
= (readRowHits
/ (readBursts
- servicedByWrQ
)) * 100;
1594 .name(name() + ".writeRowHitRate")
1595 .desc("Row buffer hit rate for writes")
1598 writeRowHitRate
= (writeRowHits
/ (writeBursts
- mergedWrBursts
)) * 100;
1601 .init(ceilLog2(burstSize
) + 1)
1602 .name(name() + ".readPktSize")
1603 .desc("Read request sizes (log2)");
1606 .init(ceilLog2(burstSize
) + 1)
1607 .name(name() + ".writePktSize")
1608 .desc("Write request sizes (log2)");
1611 .init(readBufferSize
)
1612 .name(name() + ".rdQLenPdf")
1613 .desc("What read queue length does an incoming req see");
1616 .init(writeBufferSize
)
1617 .name(name() + ".wrQLenPdf")
1618 .desc("What write queue length does an incoming req see");
1621 .init(maxAccessesPerRow
)
1622 .name(name() + ".bytesPerActivate")
1623 .desc("Bytes accessed per row activation")
1627 .init(readBufferSize
)
1628 .name(name() + ".rdPerTurnAround")
1629 .desc("Reads before turning the bus around for writes")
1633 .init(writeBufferSize
)
1634 .name(name() + ".wrPerTurnAround")
1635 .desc("Writes before turning the bus around for reads")
1639 .name(name() + ".bytesReadDRAM")
1640 .desc("Total number of bytes read from DRAM");
1643 .name(name() + ".bytesReadWrQ")
1644 .desc("Total number of bytes read from write queue");
1647 .name(name() + ".bytesWritten")
1648 .desc("Total number of bytes written to DRAM");
1651 .name(name() + ".bytesReadSys")
1652 .desc("Total read bytes from the system interface side");
1655 .name(name() + ".bytesWrittenSys")
1656 .desc("Total written bytes from the system interface side");
1659 .name(name() + ".avgRdBW")
1660 .desc("Average DRAM read bandwidth in MiByte/s")
1663 avgRdBW
= (bytesReadDRAM
/ 1000000) / simSeconds
;
1666 .name(name() + ".avgWrBW")
1667 .desc("Average achieved write bandwidth in MiByte/s")
1670 avgWrBW
= (bytesWritten
/ 1000000) / simSeconds
;
1673 .name(name() + ".avgRdBWSys")
1674 .desc("Average system read bandwidth in MiByte/s")
1677 avgRdBWSys
= (bytesReadSys
/ 1000000) / simSeconds
;
1680 .name(name() + ".avgWrBWSys")
1681 .desc("Average system write bandwidth in MiByte/s")
1684 avgWrBWSys
= (bytesWrittenSys
/ 1000000) / simSeconds
;
1687 .name(name() + ".peakBW")
1688 .desc("Theoretical peak bandwidth in MiByte/s")
1691 peakBW
= (SimClock::Frequency
/ tBURST
) * burstSize
/ 1000000;
1694 .name(name() + ".busUtil")
1695 .desc("Data bus utilization in percentage")
1698 busUtil
= (avgRdBW
+ avgWrBW
) / peakBW
* 100;
1701 .name(name() + ".totGap")
1702 .desc("Total gap between requests");
1705 .name(name() + ".avgGap")
1706 .desc("Average gap between requests")
1709 avgGap
= totGap
/ (readReqs
+ writeReqs
);
1711 // Stats for DRAM Power calculation based on Micron datasheet
1713 .name(name() + ".busUtilRead")
1714 .desc("Data bus utilization in percentage for reads")
1717 busUtilRead
= avgRdBW
/ peakBW
* 100;
1720 .name(name() + ".busUtilWrite")
1721 .desc("Data bus utilization in percentage for writes")
1724 busUtilWrite
= avgWrBW
/ peakBW
* 100;
1727 .name(name() + ".pageHitRate")
1728 .desc("Row buffer hit rate, read and write combined")
1731 pageHitRate
= (writeRowHits
+ readRowHits
) /
1732 (writeBursts
- mergedWrBursts
+ readBursts
- servicedByWrQ
) * 100;
1736 .name(name() + ".memoryStateTime")
1737 .desc("Time in different power states");
1738 pwrStateTime
.subname(0, "IDLE");
1739 pwrStateTime
.subname(1, "REF");
1740 pwrStateTime
.subname(2, "PRE_PDN");
1741 pwrStateTime
.subname(3, "ACT");
1742 pwrStateTime
.subname(4, "ACT_PDN");
1746 DRAMCtrl::recvFunctional(PacketPtr pkt
)
1748 // rely on the abstract memory
1749 functionalAccess(pkt
);
1753 DRAMCtrl::getSlavePort(const string
&if_name
, PortID idx
)
1755 if (if_name
!= "port") {
1756 return MemObject::getSlavePort(if_name
, idx
);
1763 DRAMCtrl::drain(DrainManager
*dm
)
1765 unsigned int count
= port
.drain(dm
);
1767 // if there is anything in any of our internal queues, keep track
1769 if (!(writeQueue
.empty() && readQueue
.empty() &&
1770 respQueue
.empty())) {
1771 DPRINTF(Drain
, "DRAM controller not drained, write: %d, read: %d,"
1772 " resp: %d\n", writeQueue
.size(), readQueue
.size(),
1777 // the only part that is not drained automatically over time
1778 // is the write queue, thus kick things into action if needed
1779 if (!writeQueue
.empty() && !nextReqEvent
.scheduled()) {
1780 schedule(nextReqEvent
, curTick());
1785 setDrainState(Drainable::Draining
);
1787 setDrainState(Drainable::Drained
);
1791 DRAMCtrl::MemoryPort::MemoryPort(const std::string
& name
, DRAMCtrl
& _memory
)
1792 : QueuedSlavePort(name
, &_memory
, queue
), queue(_memory
, *this),
1797 DRAMCtrl::MemoryPort::getAddrRanges() const
1799 AddrRangeList ranges
;
1800 ranges
.push_back(memory
.getAddrRange());
1805 DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt
)
1807 pkt
->pushLabel(memory
.name());
1809 if (!queue
.checkFunctional(pkt
)) {
1810 // Default implementation of SimpleTimingPort::recvFunctional()
1811 // calls recvAtomic() and throws away the latency; we can save a
1812 // little here by just not calculating the latency.
1813 memory
.recvFunctional(pkt
);
1820 DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt
)
1822 return memory
.recvAtomic(pkt
);
1826 DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt
)
1828 // pass it to the memory controller
1829 return memory
.recvTimingReq(pkt
);
1833 DRAMCtrlParams::create()
1835 return new DRAMCtrl(this);