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/DRAMState.hh"
49 #include "debug/Drain.hh"
50 #include "mem/dram_ctrl.hh"
51 #include "sim/system.hh"
55 DRAMCtrl::DRAMCtrl(const DRAMCtrlParams
* p
) :
57 port(name() + ".port", *this),
58 retryRdReq(false), retryWrReq(false),
59 rowHitFlag(false), busState(READ
),
60 nextReqEvent(this), respondEvent(this), activateEvent(this),
61 prechargeEvent(this), refreshEvent(this), powerEvent(this),
63 deviceBusWidth(p
->device_bus_width
), burstLength(p
->burst_length
),
64 deviceRowBufferSize(p
->device_rowbuffer_size
),
65 devicesPerRank(p
->devices_per_rank
),
66 burstSize((devicesPerRank
* burstLength
* deviceBusWidth
) / 8),
67 rowBufferSize(devicesPerRank
* deviceRowBufferSize
),
68 columnsPerRowBuffer(rowBufferSize
/ burstSize
),
69 ranksPerChannel(p
->ranks_per_channel
),
70 banksPerRank(p
->banks_per_rank
), channels(p
->channels
), rowsPerBank(0),
71 readBufferSize(p
->read_buffer_size
),
72 writeBufferSize(p
->write_buffer_size
),
73 writeHighThreshold(writeBufferSize
* p
->write_high_thresh_perc
/ 100.0),
74 writeLowThreshold(writeBufferSize
* p
->write_low_thresh_perc
/ 100.0),
75 minWritesPerSwitch(p
->min_writes_per_switch
),
76 writesThisTime(0), readsThisTime(0),
77 tWTR(p
->tWTR
), tRTW(p
->tRTW
), tBURST(p
->tBURST
),
78 tRCD(p
->tRCD
), tCL(p
->tCL
), tRP(p
->tRP
), tRAS(p
->tRAS
),
79 tRFC(p
->tRFC
), tREFI(p
->tREFI
), tRRD(p
->tRRD
),
80 tXAW(p
->tXAW
), activationLimit(p
->activation_limit
),
81 memSchedPolicy(p
->mem_sched_policy
), addrMapping(p
->addr_mapping
),
82 pageMgmt(p
->page_policy
),
83 maxAccessesPerRow(p
->max_accesses_per_row
),
84 frontendLatency(p
->static_frontend_latency
),
85 backendLatency(p
->static_backend_latency
),
86 busBusyUntil(0), refreshDueAt(0), refreshState(REF_IDLE
),
87 pwrStateTrans(PWR_IDLE
), pwrState(PWR_IDLE
), prevArrival(0),
88 nextReqTime(0), pwrStateTick(0), numBanksActive(0)
90 // create the bank states based on the dimensions of the ranks and
92 banks
.resize(ranksPerChannel
);
93 actTicks
.resize(ranksPerChannel
);
94 for (size_t c
= 0; c
< ranksPerChannel
; ++c
) {
95 banks
[c
].resize(banksPerRank
);
96 actTicks
[c
].resize(activationLimit
, 0);
99 // perform a basic check of the write thresholds
100 if (p
->write_low_thresh_perc
>= p
->write_high_thresh_perc
)
101 fatal("Write buffer low threshold %d must be smaller than the "
102 "high threshold %d\n", p
->write_low_thresh_perc
,
103 p
->write_high_thresh_perc
);
105 // determine the rows per bank by looking at the total capacity
106 uint64_t capacity
= ULL(1) << ceilLog2(AbstractMemory::size());
108 DPRINTF(DRAM
, "Memory capacity %lld (%lld) bytes\n", capacity
,
109 AbstractMemory::size());
111 DPRINTF(DRAM
, "Row buffer size %d bytes with %d columns per row buffer\n",
112 rowBufferSize
, columnsPerRowBuffer
);
114 rowsPerBank
= capacity
/ (rowBufferSize
* banksPerRank
* ranksPerChannel
);
116 if (range
.interleaved()) {
117 if (channels
!= range
.stripes())
118 fatal("%s has %d interleaved address stripes but %d channel(s)\n",
119 name(), range
.stripes(), channels
);
121 if (addrMapping
== Enums::RoRaBaChCo
) {
122 if (rowBufferSize
!= range
.granularity()) {
123 fatal("Interleaving of %s doesn't match RoRaBaChCo "
124 "address map\n", name());
126 } else if (addrMapping
== Enums::RoRaBaCoCh
) {
127 if (system()->cacheLineSize() != range
.granularity()) {
128 fatal("Interleaving of %s doesn't match RoRaBaCoCh "
129 "address map\n", name());
131 } else if (addrMapping
== Enums::RoCoRaBaCh
) {
132 if (system()->cacheLineSize() != range
.granularity())
133 fatal("Interleaving of %s doesn't match RoCoRaBaCh "
134 "address map\n", name());
138 // some basic sanity checks
139 if (tREFI
<= tRP
|| tREFI
<= tRFC
) {
140 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
148 if (!port
.isConnected()) {
149 fatal("DRAMCtrl %s is unconnected!\n", name());
151 port
.sendRangeChange();
158 // update the start tick for the precharge accounting to the
160 pwrStateTick
= curTick();
162 // shift the bus busy time sufficiently far ahead that we never
163 // have to worry about negative values when computing the time for
164 // the next request, this will add an insignificant bubble at the
165 // start of simulation
166 busBusyUntil
= curTick() + tRP
+ tRCD
+ tCL
;
168 // print the configuration of the controller
171 // kick off the refresh, and give ourselves enough time to
173 schedule(refreshEvent
, curTick() + tREFI
- tRP
);
177 DRAMCtrl::recvAtomic(PacketPtr pkt
)
179 DPRINTF(DRAM
, "recvAtomic: %s 0x%x\n", pkt
->cmdString(), pkt
->getAddr());
181 // do the actual memory access and turn the packet into a response
185 if (!pkt
->memInhibitAsserted() && pkt
->hasData()) {
186 // this value is not supposed to be accurate, just enough to
187 // keep things going, mimic a closed page
188 latency
= tRP
+ tRCD
+ tCL
;
194 DRAMCtrl::readQueueFull(unsigned int neededEntries
) const
196 DPRINTF(DRAM
, "Read queue limit %d, current size %d, entries needed %d\n",
197 readBufferSize
, readQueue
.size() + respQueue
.size(),
201 (readQueue
.size() + respQueue
.size() + neededEntries
) > readBufferSize
;
205 DRAMCtrl::writeQueueFull(unsigned int neededEntries
) const
207 DPRINTF(DRAM
, "Write queue limit %d, current size %d, entries needed %d\n",
208 writeBufferSize
, writeQueue
.size(), neededEntries
);
209 return (writeQueue
.size() + neededEntries
) > writeBufferSize
;
212 DRAMCtrl::DRAMPacket
*
213 DRAMCtrl::decodeAddr(PacketPtr pkt
, Addr dramPktAddr
, unsigned size
,
216 // decode the address based on the address mapping scheme, with
217 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
218 // channel, respectively
223 // truncate the address to the access granularity
224 Addr addr
= dramPktAddr
/ burstSize
;
226 // we have removed the lowest order address bits that denote the
227 // position within the column
228 if (addrMapping
== Enums::RoRaBaChCo
) {
229 // the lowest order bits denote the column to ensure that
230 // sequential cache lines occupy the same row
231 addr
= addr
/ columnsPerRowBuffer
;
233 // take out the channel part of the address
234 addr
= addr
/ channels
;
236 // after the channel bits, get the bank bits to interleave
238 bank
= addr
% banksPerRank
;
239 addr
= addr
/ banksPerRank
;
241 // after the bank, we get the rank bits which thus interleaves
243 rank
= addr
% ranksPerChannel
;
244 addr
= addr
/ ranksPerChannel
;
246 // lastly, get the row bits
247 row
= addr
% rowsPerBank
;
248 addr
= addr
/ rowsPerBank
;
249 } else if (addrMapping
== Enums::RoRaBaCoCh
) {
250 // take out the channel part of the address
251 addr
= addr
/ channels
;
254 addr
= addr
/ columnsPerRowBuffer
;
256 // after the column bits, we get the bank bits to interleave
258 bank
= addr
% banksPerRank
;
259 addr
= addr
/ banksPerRank
;
261 // after the bank, we get the rank bits which thus interleaves
263 rank
= addr
% ranksPerChannel
;
264 addr
= addr
/ ranksPerChannel
;
266 // lastly, get the row bits
267 row
= addr
% rowsPerBank
;
268 addr
= addr
/ rowsPerBank
;
269 } else if (addrMapping
== Enums::RoCoRaBaCh
) {
270 // optimise for closed page mode and utilise maximum
271 // parallelism of the DRAM (at the cost of power)
273 // take out the channel part of the address, not that this has
274 // to match with how accesses are interleaved between the
275 // controllers in the address mapping
276 addr
= addr
/ channels
;
278 // start with the bank bits, as this provides the maximum
279 // opportunity for parallelism between requests
280 bank
= addr
% banksPerRank
;
281 addr
= addr
/ banksPerRank
;
283 // next get the rank bits
284 rank
= addr
% ranksPerChannel
;
285 addr
= addr
/ ranksPerChannel
;
287 // next the column bits which we do not need to keep track of
288 // and simply skip past
289 addr
= addr
/ columnsPerRowBuffer
;
291 // lastly, get the row bits
292 row
= addr
% rowsPerBank
;
293 addr
= addr
/ rowsPerBank
;
295 panic("Unknown address mapping policy chosen!");
297 assert(rank
< ranksPerChannel
);
298 assert(bank
< banksPerRank
);
299 assert(row
< rowsPerBank
);
301 DPRINTF(DRAM
, "Address: %lld Rank %d Bank %d Row %d\n",
302 dramPktAddr
, rank
, bank
, row
);
304 // create the corresponding DRAM packet with the entry time and
305 // ready time set to the current tick, the latter will be updated
307 uint16_t bank_id
= banksPerRank
* rank
+ bank
;
308 return new DRAMPacket(pkt
, isRead
, rank
, bank
, row
, bank_id
, dramPktAddr
,
309 size
, banks
[rank
][bank
]);
313 DRAMCtrl::addToReadQueue(PacketPtr pkt
, unsigned int pktCount
)
315 // only add to the read queue here. whenever the request is
316 // eventually done, set the readyTime, and call schedule()
317 assert(!pkt
->isWrite());
319 assert(pktCount
!= 0);
321 // if the request size is larger than burst size, the pkt is split into
322 // multiple DRAM packets
323 // Note if the pkt starting address is not aligened to burst size, the
324 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
325 // are aligned to burst size boundaries. This is to ensure we accurately
326 // check read packets against packets in write queue.
327 Addr addr
= pkt
->getAddr();
328 unsigned pktsServicedByWrQ
= 0;
329 BurstHelper
* burst_helper
= NULL
;
330 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
331 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
332 pkt
->getAddr() + pkt
->getSize()) - addr
;
333 readPktSize
[ceilLog2(size
)]++;
336 // First check write buffer to see if the data is already at
338 bool foundInWrQ
= false;
339 for (auto i
= writeQueue
.begin(); i
!= writeQueue
.end(); ++i
) {
340 // check if the read is subsumed in the write entry we are
342 if ((*i
)->addr
<= addr
&&
343 (addr
+ size
) <= ((*i
)->addr
+ (*i
)->size
)) {
347 DPRINTF(DRAM
, "Read to addr %lld with size %d serviced by "
348 "write queue\n", addr
, size
);
349 bytesReadWrQ
+= burstSize
;
354 // If not found in the write q, make a DRAM packet and
355 // push it onto the read queue
358 // Make the burst helper for split packets
359 if (pktCount
> 1 && burst_helper
== NULL
) {
360 DPRINTF(DRAM
, "Read to addr %lld translates to %d "
361 "dram requests\n", pkt
->getAddr(), pktCount
);
362 burst_helper
= new BurstHelper(pktCount
);
365 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, true);
366 dram_pkt
->burstHelper
= burst_helper
;
368 assert(!readQueueFull(1));
369 rdQLenPdf
[readQueue
.size() + respQueue
.size()]++;
371 DPRINTF(DRAM
, "Adding to read queue\n");
373 readQueue
.push_back(dram_pkt
);
376 avgRdQLen
= readQueue
.size() + respQueue
.size();
379 // Starting address of next dram pkt (aligend to burstSize boundary)
380 addr
= (addr
| (burstSize
- 1)) + 1;
383 // If all packets are serviced by write queue, we send the repsonse back
384 if (pktsServicedByWrQ
== pktCount
) {
385 accessAndRespond(pkt
, frontendLatency
);
389 // Update how many split packets are serviced by write queue
390 if (burst_helper
!= NULL
)
391 burst_helper
->burstsServiced
= pktsServicedByWrQ
;
393 // If we are not already scheduled to get a request out of the
395 if (!nextReqEvent
.scheduled()) {
396 DPRINTF(DRAM
, "Request scheduled immediately\n");
397 schedule(nextReqEvent
, curTick());
402 DRAMCtrl::addToWriteQueue(PacketPtr pkt
, unsigned int pktCount
)
404 // only add to the write queue here. whenever the request is
405 // eventually done, set the readyTime, and call schedule()
406 assert(pkt
->isWrite());
408 // if the request size is larger than burst size, the pkt is split into
409 // multiple DRAM packets
410 Addr addr
= pkt
->getAddr();
411 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
412 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
413 pkt
->getAddr() + pkt
->getSize()) - addr
;
414 writePktSize
[ceilLog2(size
)]++;
417 // see if we can merge with an existing item in the write
418 // queue and keep track of whether we have merged or not so we
419 // can stop at that point and also avoid enqueueing a new
422 auto w
= writeQueue
.begin();
424 while(!merged
&& w
!= writeQueue
.end()) {
425 // either of the two could be first, if they are the same
426 // it does not matter which way we go
427 if ((*w
)->addr
>= addr
) {
428 // the existing one starts after the new one, figure
429 // out where the new one ends with respect to the
431 if ((addr
+ size
) >= ((*w
)->addr
+ (*w
)->size
)) {
432 // check if the existing one is completely
433 // subsumed in the new one
434 DPRINTF(DRAM
, "Merging write covering existing burst\n");
436 // update both the address and the size
439 } else if ((addr
+ size
) >= (*w
)->addr
&&
440 ((*w
)->addr
+ (*w
)->size
- addr
) <= burstSize
) {
441 // the new one is just before or partially
442 // overlapping with the existing one, and together
443 // they fit within a burst
444 DPRINTF(DRAM
, "Merging write before existing burst\n");
446 // the existing queue item needs to be adjusted with
447 // respect to both address and size
448 (*w
)->size
= (*w
)->addr
+ (*w
)->size
- addr
;
452 // the new one starts after the current one, figure
453 // out where the existing one ends with respect to the
455 if (((*w
)->addr
+ (*w
)->size
) >= (addr
+ size
)) {
456 // check if the new one is completely subsumed in the
458 DPRINTF(DRAM
, "Merging write into existing burst\n");
460 // no adjustments necessary
461 } else if (((*w
)->addr
+ (*w
)->size
) >= addr
&&
462 (addr
+ size
- (*w
)->addr
) <= burstSize
) {
463 // the existing one is just before or partially
464 // overlapping with the new one, and together
465 // they fit within a burst
466 DPRINTF(DRAM
, "Merging write after existing burst\n");
468 // the address is right, and only the size has
470 (*w
)->size
= addr
+ size
- (*w
)->addr
;
476 // if the item was not merged we need to create a new write
479 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, false);
481 assert(writeQueue
.size() < writeBufferSize
);
482 wrQLenPdf
[writeQueue
.size()]++;
484 DPRINTF(DRAM
, "Adding to write queue\n");
486 writeQueue
.push_back(dram_pkt
);
489 avgWrQLen
= writeQueue
.size();
491 // keep track of the fact that this burst effectively
492 // disappeared as it was merged with an existing one
496 // Starting address of next dram pkt (aligend to burstSize boundary)
497 addr
= (addr
| (burstSize
- 1)) + 1;
500 // we do not wait for the writes to be send to the actual memory,
501 // but instead take responsibility for the consistency here and
502 // snoop the write queue for any upcoming reads
503 // @todo, if a pkt size is larger than burst size, we might need a
504 // different front end latency
505 accessAndRespond(pkt
, frontendLatency
);
507 // If we are not already scheduled to get a request out of the
509 if (!nextReqEvent
.scheduled()) {
510 DPRINTF(DRAM
, "Request scheduled immediately\n");
511 schedule(nextReqEvent
, curTick());
516 DRAMCtrl::printParams() const
518 // Sanity check print of important parameters
520 "Memory controller %s physical organization\n" \
521 "Number of devices per rank %d\n" \
522 "Device bus width (in bits) %d\n" \
523 "DRAM data bus burst (bytes) %d\n" \
524 "Row buffer size (bytes) %d\n" \
525 "Columns per row buffer %d\n" \
526 "Rows per bank %d\n" \
527 "Banks per rank %d\n" \
528 "Ranks per channel %d\n" \
529 "Total mem capacity (bytes) %u\n",
530 name(), devicesPerRank
, deviceBusWidth
, burstSize
, rowBufferSize
,
531 columnsPerRowBuffer
, rowsPerBank
, banksPerRank
, ranksPerChannel
,
532 rowBufferSize
* rowsPerBank
* banksPerRank
* ranksPerChannel
);
534 string scheduler
= memSchedPolicy
== Enums::fcfs
? "FCFS" : "FR-FCFS";
535 string address_mapping
= addrMapping
== Enums::RoRaBaChCo
? "RoRaBaChCo" :
536 (addrMapping
== Enums::RoRaBaCoCh
? "RoRaBaCoCh" : "RoCoRaBaCh");
537 string page_policy
= pageMgmt
== Enums::open
? "OPEN" :
538 (pageMgmt
== Enums::open_adaptive
? "OPEN (adaptive)" :
539 (pageMgmt
== Enums::close_adaptive
? "CLOSE (adaptive)" : "CLOSE"));
542 "Memory controller %s characteristics\n" \
543 "Read buffer size %d\n" \
544 "Write buffer size %d\n" \
545 "Write high thresh %d\n" \
546 "Write low thresh %d\n" \
548 "Address mapping %s\n" \
550 name(), readBufferSize
, writeBufferSize
, writeHighThreshold
,
551 writeLowThreshold
, scheduler
, address_mapping
, page_policy
);
553 DPRINTF(DRAM
, "Memory controller %s timing specs\n" \
557 "tBURST %d ticks\n" \
562 "tXAW (%d) %d ticks\n",
563 name(), tRCD
, tCL
, tRP
, tBURST
, tRFC
, tREFI
, tWTR
,
564 tRTW
, activationLimit
, tXAW
);
568 DRAMCtrl::printQs() const {
569 DPRINTF(DRAM
, "===READ QUEUE===\n\n");
570 for (auto i
= readQueue
.begin() ; i
!= readQueue
.end() ; ++i
) {
571 DPRINTF(DRAM
, "Read %lu\n", (*i
)->addr
);
573 DPRINTF(DRAM
, "\n===RESP QUEUE===\n\n");
574 for (auto i
= respQueue
.begin() ; i
!= respQueue
.end() ; ++i
) {
575 DPRINTF(DRAM
, "Response %lu\n", (*i
)->addr
);
577 DPRINTF(DRAM
, "\n===WRITE QUEUE===\n\n");
578 for (auto i
= writeQueue
.begin() ; i
!= writeQueue
.end() ; ++i
) {
579 DPRINTF(DRAM
, "Write %lu\n", (*i
)->addr
);
584 DRAMCtrl::recvTimingReq(PacketPtr pkt
)
586 /// @todo temporary hack to deal with memory corruption issues until
587 /// 4-phase transactions are complete
588 for (int x
= 0; x
< pendingDelete
.size(); x
++)
589 delete pendingDelete
[x
];
590 pendingDelete
.clear();
592 // This is where we enter from the outside world
593 DPRINTF(DRAM
, "recvTimingReq: request %s addr %lld size %d\n",
594 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
596 // simply drop inhibited packets for now
597 if (pkt
->memInhibitAsserted()) {
598 DPRINTF(DRAM
, "Inhibited packet -- Dropping it now\n");
599 pendingDelete
.push_back(pkt
);
603 // Calc avg gap between requests
604 if (prevArrival
!= 0) {
605 totGap
+= curTick() - prevArrival
;
607 prevArrival
= curTick();
610 // Find out how many dram packets a pkt translates to
611 // If the burst size is equal or larger than the pkt size, then a pkt
612 // translates to only one dram packet. Otherwise, a pkt translates to
613 // multiple dram packets
614 unsigned size
= pkt
->getSize();
615 unsigned offset
= pkt
->getAddr() & (burstSize
- 1);
616 unsigned int dram_pkt_count
= divCeil(offset
+ size
, burstSize
);
618 // check local buffers and do not accept if full
621 if (readQueueFull(dram_pkt_count
)) {
622 DPRINTF(DRAM
, "Read queue full, not accepting\n");
623 // remember that we have to retry this port
628 addToReadQueue(pkt
, dram_pkt_count
);
630 bytesReadSys
+= size
;
632 } else if (pkt
->isWrite()) {
634 if (writeQueueFull(dram_pkt_count
)) {
635 DPRINTF(DRAM
, "Write queue full, not accepting\n");
636 // remember that we have to retry this port
641 addToWriteQueue(pkt
, dram_pkt_count
);
643 bytesWrittenSys
+= size
;
646 DPRINTF(DRAM
,"Neither read nor write, ignore timing\n");
647 neitherReadNorWrite
++;
648 accessAndRespond(pkt
, 1);
655 DRAMCtrl::processRespondEvent()
658 "processRespondEvent(): Some req has reached its readyTime\n");
660 DRAMPacket
* dram_pkt
= respQueue
.front();
662 if (dram_pkt
->burstHelper
) {
663 // it is a split packet
664 dram_pkt
->burstHelper
->burstsServiced
++;
665 if (dram_pkt
->burstHelper
->burstsServiced
==
666 dram_pkt
->burstHelper
->burstCount
) {
667 // we have now serviced all children packets of a system packet
668 // so we can now respond to the requester
669 // @todo we probably want to have a different front end and back
670 // end latency for split packets
671 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
672 delete dram_pkt
->burstHelper
;
673 dram_pkt
->burstHelper
= NULL
;
676 // it is not a split packet
677 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
680 delete respQueue
.front();
681 respQueue
.pop_front();
683 if (!respQueue
.empty()) {
684 assert(respQueue
.front()->readyTime
>= curTick());
685 assert(!respondEvent
.scheduled());
686 schedule(respondEvent
, respQueue
.front()->readyTime
);
688 // if there is nothing left in any queue, signal a drain
689 if (writeQueue
.empty() && readQueue
.empty() &&
691 drainManager
->signalDrainDone();
696 // We have made a location in the queue available at this point,
697 // so if there is a read that was forced to wait, retry now
705 DRAMCtrl::chooseNext(std::deque
<DRAMPacket
*>& queue
)
707 // This method does the arbitration between requests. The chosen
708 // packet is simply moved to the head of the queue. The other
709 // methods know that this is the place to look. For example, with
710 // FCFS, this method does nothing
711 assert(!queue
.empty());
713 if (queue
.size() == 1) {
714 DPRINTF(DRAM
, "Single request, nothing to do\n");
718 if (memSchedPolicy
== Enums::fcfs
) {
719 // Do nothing, since the correct request is already head
720 } else if (memSchedPolicy
== Enums::frfcfs
) {
723 panic("No scheduling policy chosen\n");
727 DRAMCtrl::reorderQueue(std::deque
<DRAMPacket
*>& queue
)
729 // Only determine this when needed
730 uint64_t earliest_banks
= 0;
732 // Search for row hits first, if no row hit is found then schedule the
733 // packet to one of the earliest banks available
734 bool found_earliest_pkt
= false;
735 auto selected_pkt_it
= queue
.begin();
737 for (auto i
= queue
.begin(); i
!= queue
.end() ; ++i
) {
738 DRAMPacket
* dram_pkt
= *i
;
739 const Bank
& bank
= dram_pkt
->bankRef
;
740 // Check if it is a row hit
741 if (bank
.openRow
== dram_pkt
->row
) {
742 DPRINTF(DRAM
, "Row buffer hit\n");
745 } else if (!found_earliest_pkt
) {
746 // No row hit, go for first ready
747 if (earliest_banks
== 0)
748 earliest_banks
= minBankFreeAt(queue
);
750 // Bank is ready or is the first available bank
751 if (bank
.freeAt
<= curTick() ||
752 bits(earliest_banks
, dram_pkt
->bankId
, dram_pkt
->bankId
)) {
753 // Remember the packet to be scheduled to one of the earliest
756 found_earliest_pkt
= true;
761 DRAMPacket
* selected_pkt
= *selected_pkt_it
;
762 queue
.erase(selected_pkt_it
);
763 queue
.push_front(selected_pkt
);
767 DRAMCtrl::accessAndRespond(PacketPtr pkt
, Tick static_latency
)
769 DPRINTF(DRAM
, "Responding to Address %lld.. ",pkt
->getAddr());
771 bool needsResponse
= pkt
->needsResponse();
772 // do the actual memory access which also turns the packet into a
776 // turn packet around to go back to requester if response expected
778 // access already turned the packet into a response
779 assert(pkt
->isResponse());
781 // @todo someone should pay for this
782 pkt
->busFirstWordDelay
= pkt
->busLastWordDelay
= 0;
784 // queue the packet in the response queue to be sent out after
785 // the static latency has passed
786 port
.schedTimingResp(pkt
, curTick() + static_latency
);
788 // @todo the packet is going to be deleted, and the DRAMPacket
789 // is still having a pointer to it
790 pendingDelete
.push_back(pkt
);
793 DPRINTF(DRAM
, "Done\n");
799 DRAMCtrl::estimateLatency(DRAMPacket
* dram_pkt
, Tick inTime
)
801 // If a request reaches a bank at tick 'inTime', how much time
802 // *after* that does it take to finish the request, depending
803 // on bank status and page open policy. Note that this method
804 // considers only the time taken for the actual read or write
805 // to complete, NOT any additional time thereafter for tRAS or
810 Tick potentialActTick
;
812 const Bank
& bank
= dram_pkt
->bankRef
;
813 // open-page policy or close_adaptive policy
814 if (pageMgmt
== Enums::open
|| pageMgmt
== Enums::open_adaptive
||
815 pageMgmt
== Enums::close_adaptive
) {
816 if (bank
.openRow
== dram_pkt
->row
) {
817 // When we have a row-buffer hit,
818 // we don't care about tRAS having expired or not,
819 // but do care about bank being free for access
822 // When a series of requests arrive to the same row,
823 // DDR systems are capable of streaming data continuously
824 // at maximum bandwidth (subject to tCCD). Here, we approximate
825 // this condition, and assume that if whenever a bank is already
826 // busy and a new request comes in, it can be completed with no
827 // penalty beyond waiting for the existing read to complete.
828 if (bank
.freeAt
> inTime
) {
829 accLat
+= bank
.freeAt
- inTime
;
838 // Row-buffer miss, need to close existing row
839 // once tRAS has expired, then open the new one,
840 // then add cas latency.
841 Tick freeTime
= std::max(bank
.tRASDoneAt
, bank
.freeAt
);
843 if (freeTime
> inTime
)
844 accLat
+= freeTime
- inTime
;
846 // If the there is no open row (open adaptive), then there
847 // is no precharge delay, otherwise go with tRP
848 Tick precharge_delay
= bank
.openRow
== Bank::NO_ROW
? 0 : tRP
;
850 //The bank is free, and you may be able to activate
851 potentialActTick
= inTime
+ accLat
+ precharge_delay
;
852 if (potentialActTick
< bank
.actAllowedAt
)
853 accLat
+= bank
.actAllowedAt
- potentialActTick
;
855 accLat
+= precharge_delay
+ tRCD
+ tCL
;
856 bankLat
+= precharge_delay
+ tRCD
+ tCL
;
858 } else if (pageMgmt
== Enums::close
) {
859 // With a close page policy, no notion of
861 if (bank
.freeAt
> inTime
)
862 accLat
+= bank
.freeAt
- inTime
;
864 //The bank is free, and you may be able to activate
865 potentialActTick
= inTime
+ accLat
;
866 if (potentialActTick
< bank
.actAllowedAt
)
867 accLat
+= bank
.actAllowedAt
- potentialActTick
;
869 // page already closed, simply open the row, and
871 accLat
+= tRCD
+ tCL
;
872 bankLat
+= tRCD
+ tCL
;
874 panic("No page management policy chosen\n");
876 DPRINTF(DRAM
, "Returning < %lld, %lld > from estimateLatency()\n",
879 return make_pair(bankLat
, accLat
);
883 DRAMCtrl::recordActivate(Tick act_tick
, uint8_t rank
, uint8_t bank
,
886 assert(0 <= rank
&& rank
< ranksPerChannel
);
887 assert(actTicks
[rank
].size() == activationLimit
);
889 DPRINTF(DRAM
, "Activate at tick %d\n", act_tick
);
891 // update the open row
892 assert(banks
[rank
][bank
].openRow
== Bank::NO_ROW
);
893 banks
[rank
][bank
].openRow
= row
;
895 // start counting anew, this covers both the case when we
896 // auto-precharged, and when this access is forced to
898 banks
[rank
][bank
].bytesAccessed
= 0;
899 banks
[rank
][bank
].rowAccesses
= 0;
902 assert(numBanksActive
<= banksPerRank
* ranksPerChannel
);
904 DPRINTF(DRAM
, "Activate bank at tick %lld, now got %d active\n",
905 act_tick
, numBanksActive
);
907 // start by enforcing tRRD
908 for(int i
= 0; i
< banksPerRank
; i
++) {
909 // next activate must not happen before tRRD
910 banks
[rank
][i
].actAllowedAt
= act_tick
+ tRRD
;
913 // tRC should be added to activation tick of the bank currently accessed,
914 // where tRC = tRAS + tRP, this is just for a check as actAllowedAt for same
915 // bank is already captured by bank.freeAt and bank.tRASDoneAt
916 banks
[rank
][bank
].actAllowedAt
= act_tick
+ tRAS
+ tRP
;
918 // next, we deal with tXAW, if the activation limit is disabled
920 if (actTicks
[rank
].empty())
924 if (actTicks
[rank
].back() && (act_tick
- actTicks
[rank
].back()) < tXAW
) {
925 // @todo For now, stick with a warning
926 warn("Got %d activates in window %d (%d - %d) which is smaller "
927 "than %d\n", activationLimit
, act_tick
- actTicks
[rank
].back(),
928 act_tick
, actTicks
[rank
].back(), tXAW
);
931 // shift the times used for the book keeping, the last element
932 // (highest index) is the oldest one and hence the lowest value
933 actTicks
[rank
].pop_back();
935 // record an new activation (in the future)
936 actTicks
[rank
].push_front(act_tick
);
938 // cannot activate more than X times in time window tXAW, push the
939 // next one (the X + 1'st activate) to be tXAW away from the
940 // oldest in our window of X
941 if (actTicks
[rank
].back() && (act_tick
- actTicks
[rank
].back()) < tXAW
) {
942 DPRINTF(DRAM
, "Enforcing tXAW with X = %d, next activate no earlier "
943 "than %d\n", activationLimit
, actTicks
[rank
].back() + tXAW
);
944 for(int j
= 0; j
< banksPerRank
; j
++)
945 // next activate must not happen before end of window
946 banks
[rank
][j
].actAllowedAt
= actTicks
[rank
].back() + tXAW
;
949 // at the point when this activate takes place, make sure we
950 // transition to the active power state
951 if (!activateEvent
.scheduled())
952 schedule(activateEvent
, act_tick
);
953 else if (activateEvent
.when() > act_tick
)
954 // move it sooner in time
955 reschedule(activateEvent
, act_tick
);
959 DRAMCtrl::processActivateEvent()
961 // we should transition to the active state as soon as any bank is active
962 if (pwrState
!= PWR_ACT
)
963 // note that at this point numBanksActive could be back at
964 // zero again due to a precharge scheduled in the future
965 schedulePowerEvent(PWR_ACT
, curTick());
969 DRAMCtrl::prechargeBank(Bank
& bank
, Tick free_at
)
971 // make sure the bank has an open row
972 assert(bank
.openRow
!= Bank::NO_ROW
);
974 // sample the bytes per activate here since we are closing
976 bytesPerActivate
.sample(bank
.bytesAccessed
);
978 bank
.openRow
= Bank::NO_ROW
;
980 bank
.freeAt
= free_at
;
982 assert(numBanksActive
!= 0);
985 DPRINTF(DRAM
, "Precharged bank, done at tick %lld, now got %d active\n",
986 bank
.freeAt
, numBanksActive
);
988 // if we look at the current number of active banks we might be
989 // tempted to think the DRAM is now idle, however this can be
990 // undone by an activate that is scheduled to happen before we
991 // would have reached the idle state, so schedule an event and
992 // rather check once we actually make it to the point in time when
993 // the (last) precharge takes place
994 if (!prechargeEvent
.scheduled())
995 schedule(prechargeEvent
, free_at
);
996 else if (prechargeEvent
.when() < free_at
)
997 reschedule(prechargeEvent
, free_at
);
1001 DRAMCtrl::processPrechargeEvent()
1003 // if we reached zero, then special conditions apply as we track
1004 // if all banks are precharged for the power models
1005 if (numBanksActive
== 0) {
1006 // we should transition to the idle state when the last bank
1008 schedulePowerEvent(PWR_IDLE
, curTick());
1013 DRAMCtrl::doDRAMAccess(DRAMPacket
* dram_pkt
)
1016 DPRINTF(DRAM
, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1017 dram_pkt
->addr
, dram_pkt
->rank
, dram_pkt
->bank
, dram_pkt
->row
);
1019 // estimate the bank and access latency
1020 pair
<Tick
, Tick
> lat
= estimateLatency(dram_pkt
, curTick());
1021 Tick bankLat
= lat
.first
;
1022 Tick accessLat
= lat
.second
;
1025 // This request was woken up at this time based on a prior call
1026 // to estimateLatency(). However, between then and now, both the
1027 // accessLatency and/or busBusyUntil may have changed. We need
1028 // to correct for that.
1030 Tick addDelay
= (curTick() + accessLat
< busBusyUntil
) ?
1031 busBusyUntil
- (curTick() + accessLat
) : 0;
1033 Bank
& bank
= dram_pkt
->bankRef
;
1035 // Update bank state
1036 if (pageMgmt
== Enums::open
|| pageMgmt
== Enums::open_adaptive
||
1037 pageMgmt
== Enums::close_adaptive
) {
1040 bank
.freeAt
= curTick() + addDelay
+ accessLat
;
1042 // If there is a page open, precharge it.
1043 if (bank
.openRow
!= Bank::NO_ROW
) {
1044 prechargeBank(bank
, std::max(std::max(bank
.freeAt
,
1049 // Any precharge is already part of the latency
1050 // estimation, so update the bank free time
1051 bank
.freeAt
= curTick() + addDelay
+ accessLat
;
1053 // any waiting for banks account for in freeAt
1054 actTick
= bank
.freeAt
- tCL
- tRCD
;
1056 // If you activated a new row do to this access, the next access
1057 // will have to respect tRAS for this bank
1058 bank
.tRASDoneAt
= actTick
+ tRAS
;
1060 recordActivate(actTick
, dram_pkt
->rank
, dram_pkt
->bank
,
1064 // increment the bytes accessed and the accesses per row
1065 bank
.bytesAccessed
+= burstSize
;
1068 // if we reached the max, then issue with an auto-precharge
1069 bool auto_precharge
= bank
.rowAccesses
== maxAccessesPerRow
;
1071 // if we did not hit the limit, we might still want to
1073 if (!auto_precharge
&&
1074 (pageMgmt
== Enums::open_adaptive
||
1075 pageMgmt
== Enums::close_adaptive
)) {
1076 // a twist on the open and close page policies:
1077 // 1) open_adaptive page policy does not blindly keep the
1078 // page open, but close it if there are no row hits, and there
1079 // are bank conflicts in the queue
1080 // 2) close_adaptive page policy does not blindly close the
1081 // page, but closes it only if there are no row hits in the queue.
1082 // In this case, only force an auto precharge when there
1083 // are no same page hits in the queue
1084 bool got_more_hits
= false;
1085 bool got_bank_conflict
= false;
1087 // either look at the read queue or write queue
1088 const deque
<DRAMPacket
*>& queue
= dram_pkt
->isRead
? readQueue
:
1090 auto p
= queue
.begin();
1091 // make sure we are not considering the packet that we are
1092 // currently dealing with (which is the head of the queue)
1095 // keep on looking until we have found required condition or
1097 while (!(got_more_hits
&&
1098 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
)) &&
1100 bool same_rank_bank
= (dram_pkt
->rank
== (*p
)->rank
) &&
1101 (dram_pkt
->bank
== (*p
)->bank
);
1102 bool same_row
= dram_pkt
->row
== (*p
)->row
;
1103 got_more_hits
|= same_rank_bank
&& same_row
;
1104 got_bank_conflict
|= same_rank_bank
&& !same_row
;
1108 // auto pre-charge when either
1109 // 1) open_adaptive policy, we have not got any more hits, and
1110 // have a bank conflict
1111 // 2) close_adaptive policy and we have not got any more hits
1112 auto_precharge
= !got_more_hits
&&
1113 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
);
1116 // if this access should use auto-precharge, then we are
1118 if (auto_precharge
) {
1119 prechargeBank(bank
, std::max(bank
.freeAt
, bank
.tRASDoneAt
) + tRP
);
1121 DPRINTF(DRAM
, "Auto-precharged bank: %d\n", dram_pkt
->bankId
);
1124 DPRINTF(DRAM
, "doDRAMAccess::bank.freeAt is %lld\n", bank
.freeAt
);
1125 } else if (pageMgmt
== Enums::close
) {
1126 actTick
= curTick() + addDelay
+ accessLat
- tRCD
- tCL
;
1127 recordActivate(actTick
, dram_pkt
->rank
, dram_pkt
->bank
, dram_pkt
->row
);
1129 bank
.freeAt
= actTick
+ tRCD
+ tCL
;
1130 bank
.tRASDoneAt
= actTick
+ tRAS
;
1132 // sample the relevant values when precharging
1133 bank
.bytesAccessed
= burstSize
;
1134 bank
.rowAccesses
= 1;
1136 prechargeBank(bank
, std::max(bank
.freeAt
, bank
.tRASDoneAt
) + tRP
);
1137 DPRINTF(DRAM
, "doDRAMAccess::bank.freeAt is %lld\n", bank
.freeAt
);
1139 panic("No page management policy chosen\n");
1141 // Update request parameters
1142 dram_pkt
->readyTime
= curTick() + addDelay
+ accessLat
+ tBURST
;
1145 DPRINTF(DRAM
, "Req %lld: curtick is %lld accessLat is %d " \
1146 "readytime is %lld busbusyuntil is %lld. " \
1147 "Scheduling at readyTime\n", dram_pkt
->addr
,
1148 curTick(), accessLat
, dram_pkt
->readyTime
, busBusyUntil
);
1150 // Make sure requests are not overlapping on the databus
1151 assert(dram_pkt
->readyTime
- busBusyUntil
>= tBURST
);
1154 busBusyUntil
= dram_pkt
->readyTime
;
1156 DPRINTF(DRAM
,"Access time is %lld\n",
1157 dram_pkt
->readyTime
- dram_pkt
->entryTime
);
1159 // Update the minimum timing between the requests, this is a
1160 // conservative estimate of when we have to schedule the next
1161 // request to not introduce any unecessary bubbles. In most cases
1162 // we will wake up sooner than we have to.
1163 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1165 // Update the stats and schedule the next request
1166 if (dram_pkt
->isRead
) {
1170 bytesReadDRAM
+= burstSize
;
1171 perBankRdBursts
[dram_pkt
->bankId
]++;
1173 // Update latency stats
1174 totMemAccLat
+= dram_pkt
->readyTime
- dram_pkt
->entryTime
;
1175 totBankLat
+= bankLat
;
1176 totBusLat
+= tBURST
;
1177 totQLat
+= dram_pkt
->readyTime
- dram_pkt
->entryTime
- bankLat
-
1183 bytesWritten
+= burstSize
;
1184 perBankWrBursts
[dram_pkt
->bankId
]++;
1189 DRAMCtrl::moveToRespQ()
1191 // Remove from read queue
1192 DRAMPacket
* dram_pkt
= readQueue
.front();
1193 readQueue
.pop_front();
1196 assert(dram_pkt
->size
<= burstSize
);
1198 // Insert into response queue sorted by readyTime
1199 // It will be sent back to the requestor at its
1201 if (respQueue
.empty()) {
1202 respQueue
.push_front(dram_pkt
);
1203 assert(!respondEvent
.scheduled());
1204 assert(dram_pkt
->readyTime
>= curTick());
1205 schedule(respondEvent
, dram_pkt
->readyTime
);
1208 auto i
= respQueue
.begin();
1209 while (!done
&& i
!= respQueue
.end()) {
1210 if ((*i
)->readyTime
> dram_pkt
->readyTime
) {
1211 respQueue
.insert(i
, dram_pkt
);
1218 respQueue
.push_back(dram_pkt
);
1220 assert(respondEvent
.scheduled());
1222 if (respQueue
.front()->readyTime
< respondEvent
.when()) {
1223 assert(respQueue
.front()->readyTime
>= curTick());
1224 reschedule(respondEvent
, respQueue
.front()->readyTime
);
1230 DRAMCtrl::processNextReqEvent()
1232 if (busState
== READ_TO_WRITE
) {
1233 DPRINTF(DRAM
, "Switching to writes after %d reads with %d reads "
1234 "waiting\n", readsThisTime
, readQueue
.size());
1236 // sample and reset the read-related stats as we are now
1237 // transitioning to writes, and all reads are done
1238 rdPerTurnAround
.sample(readsThisTime
);
1241 // now proceed to do the actual writes
1243 } else if (busState
== WRITE_TO_READ
) {
1244 DPRINTF(DRAM
, "Switching to reads after %d writes with %d writes "
1245 "waiting\n", writesThisTime
, writeQueue
.size());
1247 wrPerTurnAround
.sample(writesThisTime
);
1253 if (refreshState
!= REF_IDLE
) {
1254 // if a refresh waiting for this event loop to finish, then hand
1255 // over now, and do not schedule a new nextReqEvent
1256 if (refreshState
== REF_DRAIN
) {
1257 DPRINTF(DRAM
, "Refresh drain done, now precharging\n");
1259 refreshState
= REF_PRE
;
1261 // hand control back to the refresh event loop
1262 schedule(refreshEvent
, curTick());
1265 // let the refresh finish before issuing any further requests
1269 // when we get here it is either a read or a write
1270 if (busState
== READ
) {
1272 // track if we should switch or not
1273 bool switch_to_writes
= false;
1275 if (readQueue
.empty()) {
1276 // In the case there is no read request to go next,
1277 // trigger writes if we have passed the low threshold (or
1278 // if we are draining)
1279 if (!writeQueue
.empty() &&
1280 (drainManager
|| writeQueue
.size() > writeLowThreshold
)) {
1282 switch_to_writes
= true;
1284 // check if we are drained
1285 if (respQueue
.empty () && drainManager
) {
1286 drainManager
->signalDrainDone();
1287 drainManager
= NULL
;
1290 // nothing to do, not even any point in scheduling an
1291 // event for the next request
1295 // Figure out which read request goes next, and move it to the
1296 // front of the read queue
1297 chooseNext(readQueue
);
1299 doDRAMAccess(readQueue
.front());
1301 // At this point we're done dealing with the request
1302 // It will be moved to a separate response queue with a
1303 // correct readyTime, and eventually be sent back at that
1307 // we have so many writes that we have to transition
1308 if (writeQueue
.size() > writeHighThreshold
) {
1309 switch_to_writes
= true;
1313 // switching to writes, either because the read queue is empty
1314 // and the writes have passed the low threshold (or we are
1315 // draining), or because the writes hit the hight threshold
1316 if (switch_to_writes
) {
1317 // transition to writing
1318 busState
= READ_TO_WRITE
;
1320 // add a bubble to the data bus, as defined by the
1322 busBusyUntil
+= tRTW
;
1324 // update the minimum timing between the requests,
1325 // this shifts us back in time far enough to do any
1327 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1330 chooseNext(writeQueue
);
1331 DRAMPacket
* dram_pkt
= writeQueue
.front();
1333 assert(dram_pkt
->size
<= burstSize
);
1334 doDRAMAccess(dram_pkt
);
1336 writeQueue
.pop_front();
1339 // If we emptied the write queue, or got sufficiently below the
1340 // threshold (using the minWritesPerSwitch as the hysteresis) and
1341 // are not draining, or we have reads waiting and have done enough
1342 // writes, then switch to reads.
1343 if (writeQueue
.empty() ||
1344 (writeQueue
.size() + minWritesPerSwitch
< writeLowThreshold
&&
1346 (!readQueue
.empty() && writesThisTime
>= minWritesPerSwitch
)) {
1347 // turn the bus back around for reads again
1348 busState
= WRITE_TO_READ
;
1350 // note that the we switch back to reads also in the idle
1351 // case, which eventually will check for any draining and
1352 // also pause any further scheduling if there is really
1355 // here we get a bit creative and shift the bus busy time not
1356 // just the tWTR, but also a CAS latency to capture the fact
1357 // that we are allowed to prepare a new bank, but not issue a
1358 // read command until after tWTR, in essence we capture a
1359 // bubble on the data bus that is tWTR + tCL
1360 busBusyUntil
+= tWTR
+ tCL
;
1362 // update the minimum timing between the requests, this shifts
1363 // us back in time far enough to do any bank preparation
1364 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1368 schedule(nextReqEvent
, std::max(nextReqTime
, curTick()));
1370 // If there is space available and we have writes waiting then let
1371 // them retry. This is done here to ensure that the retry does not
1372 // cause a nextReqEvent to be scheduled before we do so as part of
1373 // the next request processing
1374 if (retryWrReq
&& writeQueue
.size() < writeBufferSize
) {
1381 DRAMCtrl::minBankFreeAt(const deque
<DRAMPacket
*>& queue
) const
1383 uint64_t bank_mask
= 0;
1384 Tick freeAt
= MaxTick
;
1386 // detemrine if we have queued transactions targetting the
1388 vector
<bool> got_waiting(ranksPerChannel
* banksPerRank
, false);
1389 for (auto p
= queue
.begin(); p
!= queue
.end(); ++p
) {
1390 got_waiting
[(*p
)->bankId
] = true;
1393 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1394 for (int j
= 0; j
< banksPerRank
; j
++) {
1395 // if we have waiting requests for the bank, and it is
1396 // amongst the first available, update the mask
1397 if (got_waiting
[i
* banksPerRank
+ j
] &&
1398 banks
[i
][j
].freeAt
<= freeAt
) {
1399 // reset bank mask if new minimum is found
1400 if (banks
[i
][j
].freeAt
< freeAt
)
1402 // set the bit corresponding to the available bank
1403 uint8_t bit_index
= i
* ranksPerChannel
+ j
;
1404 replaceBits(bank_mask
, bit_index
, bit_index
, 1);
1405 freeAt
= banks
[i
][j
].freeAt
;
1413 DRAMCtrl::processRefreshEvent()
1415 // when first preparing the refresh, remember when it was due
1416 if (refreshState
== REF_IDLE
) {
1417 // remember when the refresh is due
1418 refreshDueAt
= curTick();
1421 refreshState
= REF_DRAIN
;
1423 DPRINTF(DRAM
, "Refresh due\n");
1426 // let any scheduled read or write go ahead, after which it will
1427 // hand control back to this event loop
1428 if (refreshState
== REF_DRAIN
) {
1429 if (nextReqEvent
.scheduled()) {
1430 // hand control over to the request loop until it is
1432 DPRINTF(DRAM
, "Refresh awaiting draining\n");
1436 refreshState
= REF_PRE
;
1440 // at this point, ensure that all banks are precharged
1441 if (refreshState
== REF_PRE
) {
1442 // precharge any active bank if we are not already in the idle
1444 if (pwrState
!= PWR_IDLE
) {
1445 DPRINTF(DRAM
, "Precharging all\n");
1446 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1447 for (int j
= 0; j
< banksPerRank
; j
++) {
1448 if (banks
[i
][j
].openRow
!= Bank::NO_ROW
) {
1449 // respect both causality and any existing bank
1452 std::max(std::max(banks
[i
][j
].freeAt
,
1453 banks
[i
][j
].tRASDoneAt
),
1456 prechargeBank(banks
[i
][j
], free_at
);
1461 DPRINTF(DRAM
, "All banks already precharged, starting refresh\n");
1463 // go ahead and kick the power state machine into gear if
1464 // we are already idle
1465 schedulePowerEvent(PWR_REF
, curTick());
1468 refreshState
= REF_RUN
;
1469 assert(numBanksActive
== 0);
1471 // wait for all banks to be precharged, at which point the
1472 // power state machine will transition to the idle state, and
1473 // automatically move to a refresh, at that point it will also
1474 // call this method to get the refresh event loop going again
1478 // last but not least we perform the actual refresh
1479 if (refreshState
== REF_RUN
) {
1480 // should never get here with any banks active
1481 assert(numBanksActive
== 0);
1482 assert(pwrState
== PWR_REF
);
1484 Tick banksFree
= curTick() + tRFC
;
1486 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1487 for (int j
= 0; j
< banksPerRank
; j
++) {
1488 banks
[i
][j
].freeAt
= banksFree
;
1492 // make sure we did not wait so long that we cannot make up
1494 if (refreshDueAt
+ tREFI
< banksFree
) {
1495 fatal("Refresh was delayed so long we cannot catch up\n");
1498 // compensate for the delay in actually performing the refresh
1499 // when scheduling the next one
1500 schedule(refreshEvent
, refreshDueAt
+ tREFI
- tRP
);
1502 assert(!powerEvent
.scheduled());
1504 // move to the idle power state once the refresh is done, this
1505 // will also move the refresh state machine to the refresh
1507 schedulePowerEvent(PWR_IDLE
, banksFree
);
1509 DPRINTF(DRAMState
, "Refresh done at %llu and next refresh at %llu\n",
1510 banksFree
, refreshDueAt
+ tREFI
);
1515 DRAMCtrl::schedulePowerEvent(PowerState pwr_state
, Tick tick
)
1517 // respect causality
1518 assert(tick
>= curTick());
1520 if (!powerEvent
.scheduled()) {
1521 DPRINTF(DRAMState
, "Scheduling power event at %llu to state %d\n",
1524 // insert the new transition
1525 pwrStateTrans
= pwr_state
;
1527 schedule(powerEvent
, tick
);
1529 panic("Scheduled power event at %llu to state %d, "
1530 "with scheduled event at %llu to %d\n", tick
, pwr_state
,
1531 powerEvent
.when(), pwrStateTrans
);
1536 DRAMCtrl::processPowerEvent()
1538 // remember where we were, and for how long
1539 Tick duration
= curTick() - pwrStateTick
;
1540 PowerState prev_state
= pwrState
;
1542 // update the accounting
1543 pwrStateTime
[prev_state
] += duration
;
1545 pwrState
= pwrStateTrans
;
1546 pwrStateTick
= curTick();
1548 if (pwrState
== PWR_IDLE
) {
1549 DPRINTF(DRAMState
, "All banks precharged\n");
1551 // if we were refreshing, make sure we start scheduling requests again
1552 if (prev_state
== PWR_REF
) {
1553 DPRINTF(DRAMState
, "Was refreshing for %llu ticks\n", duration
);
1554 assert(pwrState
== PWR_IDLE
);
1556 // kick things into action again
1557 refreshState
= REF_IDLE
;
1558 assert(!nextReqEvent
.scheduled());
1559 schedule(nextReqEvent
, curTick());
1561 assert(prev_state
== PWR_ACT
);
1563 // if we have a pending refresh, and are now moving to
1564 // the idle state, direclty transition to a refresh
1565 if (refreshState
== REF_RUN
) {
1566 // there should be nothing waiting at this point
1567 assert(!powerEvent
.scheduled());
1569 // update the state in zero time and proceed below
1575 // we transition to the refresh state, let the refresh state
1576 // machine know of this state update and let it deal with the
1577 // scheduling of the next power state transition as well as the
1578 // following refresh
1579 if (pwrState
== PWR_REF
) {
1580 DPRINTF(DRAMState
, "Refreshing\n");
1581 // kick the refresh event loop into action again, and that
1582 // in turn will schedule a transition to the idle power
1583 // state once the refresh is done
1584 assert(refreshState
== REF_RUN
);
1585 processRefreshEvent();
1590 DRAMCtrl::regStats()
1592 using namespace Stats
;
1594 AbstractMemory::regStats();
1597 .name(name() + ".readReqs")
1598 .desc("Number of read requests accepted");
1601 .name(name() + ".writeReqs")
1602 .desc("Number of write requests accepted");
1605 .name(name() + ".readBursts")
1606 .desc("Number of DRAM read bursts, "
1607 "including those serviced by the write queue");
1610 .name(name() + ".writeBursts")
1611 .desc("Number of DRAM write bursts, "
1612 "including those merged in the write queue");
1615 .name(name() + ".servicedByWrQ")
1616 .desc("Number of DRAM read bursts serviced by the write queue");
1619 .name(name() + ".mergedWrBursts")
1620 .desc("Number of DRAM write bursts merged with an existing one");
1623 .name(name() + ".neitherReadNorWriteReqs")
1624 .desc("Number of requests that are neither read nor write");
1627 .init(banksPerRank
* ranksPerChannel
)
1628 .name(name() + ".perBankRdBursts")
1629 .desc("Per bank write bursts");
1632 .init(banksPerRank
* ranksPerChannel
)
1633 .name(name() + ".perBankWrBursts")
1634 .desc("Per bank write bursts");
1637 .name(name() + ".avgRdQLen")
1638 .desc("Average read queue length when enqueuing")
1642 .name(name() + ".avgWrQLen")
1643 .desc("Average write queue length when enqueuing")
1647 .name(name() + ".totQLat")
1648 .desc("Total ticks spent queuing");
1651 .name(name() + ".totBankLat")
1652 .desc("Total ticks spent accessing banks");
1655 .name(name() + ".totBusLat")
1656 .desc("Total ticks spent in databus transfers");
1659 .name(name() + ".totMemAccLat")
1660 .desc("Total ticks spent from burst creation until serviced "
1664 .name(name() + ".avgQLat")
1665 .desc("Average queueing delay per DRAM burst")
1668 avgQLat
= totQLat
/ (readBursts
- servicedByWrQ
);
1671 .name(name() + ".avgBankLat")
1672 .desc("Average bank access latency per DRAM burst")
1675 avgBankLat
= totBankLat
/ (readBursts
- servicedByWrQ
);
1678 .name(name() + ".avgBusLat")
1679 .desc("Average bus latency per DRAM burst")
1682 avgBusLat
= totBusLat
/ (readBursts
- servicedByWrQ
);
1685 .name(name() + ".avgMemAccLat")
1686 .desc("Average memory access latency per DRAM burst")
1689 avgMemAccLat
= totMemAccLat
/ (readBursts
- servicedByWrQ
);
1692 .name(name() + ".numRdRetry")
1693 .desc("Number of times read queue was full causing retry");
1696 .name(name() + ".numWrRetry")
1697 .desc("Number of times write queue was full causing retry");
1700 .name(name() + ".readRowHits")
1701 .desc("Number of row buffer hits during reads");
1704 .name(name() + ".writeRowHits")
1705 .desc("Number of row buffer hits during writes");
1708 .name(name() + ".readRowHitRate")
1709 .desc("Row buffer hit rate for reads")
1712 readRowHitRate
= (readRowHits
/ (readBursts
- servicedByWrQ
)) * 100;
1715 .name(name() + ".writeRowHitRate")
1716 .desc("Row buffer hit rate for writes")
1719 writeRowHitRate
= (writeRowHits
/ (writeBursts
- mergedWrBursts
)) * 100;
1722 .init(ceilLog2(burstSize
) + 1)
1723 .name(name() + ".readPktSize")
1724 .desc("Read request sizes (log2)");
1727 .init(ceilLog2(burstSize
) + 1)
1728 .name(name() + ".writePktSize")
1729 .desc("Write request sizes (log2)");
1732 .init(readBufferSize
)
1733 .name(name() + ".rdQLenPdf")
1734 .desc("What read queue length does an incoming req see");
1737 .init(writeBufferSize
)
1738 .name(name() + ".wrQLenPdf")
1739 .desc("What write queue length does an incoming req see");
1742 .init(maxAccessesPerRow
)
1743 .name(name() + ".bytesPerActivate")
1744 .desc("Bytes accessed per row activation")
1748 .init(readBufferSize
)
1749 .name(name() + ".rdPerTurnAround")
1750 .desc("Reads before turning the bus around for writes")
1754 .init(writeBufferSize
)
1755 .name(name() + ".wrPerTurnAround")
1756 .desc("Writes before turning the bus around for reads")
1760 .name(name() + ".bytesReadDRAM")
1761 .desc("Total number of bytes read from DRAM");
1764 .name(name() + ".bytesReadWrQ")
1765 .desc("Total number of bytes read from write queue");
1768 .name(name() + ".bytesWritten")
1769 .desc("Total number of bytes written to DRAM");
1772 .name(name() + ".bytesReadSys")
1773 .desc("Total read bytes from the system interface side");
1776 .name(name() + ".bytesWrittenSys")
1777 .desc("Total written bytes from the system interface side");
1780 .name(name() + ".avgRdBW")
1781 .desc("Average DRAM read bandwidth in MiByte/s")
1784 avgRdBW
= (bytesReadDRAM
/ 1000000) / simSeconds
;
1787 .name(name() + ".avgWrBW")
1788 .desc("Average achieved write bandwidth in MiByte/s")
1791 avgWrBW
= (bytesWritten
/ 1000000) / simSeconds
;
1794 .name(name() + ".avgRdBWSys")
1795 .desc("Average system read bandwidth in MiByte/s")
1798 avgRdBWSys
= (bytesReadSys
/ 1000000) / simSeconds
;
1801 .name(name() + ".avgWrBWSys")
1802 .desc("Average system write bandwidth in MiByte/s")
1805 avgWrBWSys
= (bytesWrittenSys
/ 1000000) / simSeconds
;
1808 .name(name() + ".peakBW")
1809 .desc("Theoretical peak bandwidth in MiByte/s")
1812 peakBW
= (SimClock::Frequency
/ tBURST
) * burstSize
/ 1000000;
1815 .name(name() + ".busUtil")
1816 .desc("Data bus utilization in percentage")
1819 busUtil
= (avgRdBW
+ avgWrBW
) / peakBW
* 100;
1822 .name(name() + ".totGap")
1823 .desc("Total gap between requests");
1826 .name(name() + ".avgGap")
1827 .desc("Average gap between requests")
1830 avgGap
= totGap
/ (readReqs
+ writeReqs
);
1832 // Stats for DRAM Power calculation based on Micron datasheet
1834 .name(name() + ".busUtilRead")
1835 .desc("Data bus utilization in percentage for reads")
1838 busUtilRead
= avgRdBW
/ peakBW
* 100;
1841 .name(name() + ".busUtilWrite")
1842 .desc("Data bus utilization in percentage for writes")
1845 busUtilWrite
= avgWrBW
/ peakBW
* 100;
1848 .name(name() + ".pageHitRate")
1849 .desc("Row buffer hit rate, read and write combined")
1852 pageHitRate
= (writeRowHits
+ readRowHits
) /
1853 (writeBursts
- mergedWrBursts
+ readBursts
- servicedByWrQ
) * 100;
1857 .name(name() + ".memoryStateTime")
1858 .desc("Time in different power states");
1859 pwrStateTime
.subname(0, "IDLE");
1860 pwrStateTime
.subname(1, "REF");
1861 pwrStateTime
.subname(2, "PRE_PDN");
1862 pwrStateTime
.subname(3, "ACT");
1863 pwrStateTime
.subname(4, "ACT_PDN");
1867 DRAMCtrl::recvFunctional(PacketPtr pkt
)
1869 // rely on the abstract memory
1870 functionalAccess(pkt
);
1874 DRAMCtrl::getSlavePort(const string
&if_name
, PortID idx
)
1876 if (if_name
!= "port") {
1877 return MemObject::getSlavePort(if_name
, idx
);
1884 DRAMCtrl::drain(DrainManager
*dm
)
1886 unsigned int count
= port
.drain(dm
);
1888 // if there is anything in any of our internal queues, keep track
1890 if (!(writeQueue
.empty() && readQueue
.empty() &&
1891 respQueue
.empty())) {
1892 DPRINTF(Drain
, "DRAM controller not drained, write: %d, read: %d,"
1893 " resp: %d\n", writeQueue
.size(), readQueue
.size(),
1898 // the only part that is not drained automatically over time
1899 // is the write queue, thus kick things into action if needed
1900 if (!writeQueue
.empty() && !nextReqEvent
.scheduled()) {
1901 schedule(nextReqEvent
, curTick());
1906 setDrainState(Drainable::Draining
);
1908 setDrainState(Drainable::Drained
);
1912 DRAMCtrl::MemoryPort::MemoryPort(const std::string
& name
, DRAMCtrl
& _memory
)
1913 : QueuedSlavePort(name
, &_memory
, queue
), queue(_memory
, *this),
1918 DRAMCtrl::MemoryPort::getAddrRanges() const
1920 AddrRangeList ranges
;
1921 ranges
.push_back(memory
.getAddrRange());
1926 DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt
)
1928 pkt
->pushLabel(memory
.name());
1930 if (!queue
.checkFunctional(pkt
)) {
1931 // Default implementation of SimpleTimingPort::recvFunctional()
1932 // calls recvAtomic() and throws away the latency; we can save a
1933 // little here by just not calculating the latency.
1934 memory
.recvFunctional(pkt
);
1941 DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt
)
1943 return memory
.recvAtomic(pkt
);
1947 DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt
)
1949 // pass it to the memory controller
1950 return memory
.recvTimingReq(pkt
);
1954 DRAMCtrlParams::create()
1956 return new DRAMCtrl(this);