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),
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 tCK(p
->tCK
), tWTR(p
->tWTR
), tRTW(p
->tRTW
), tBURST(p
->tBURST
),
78 tRCD(p
->tRCD
), tCL(p
->tCL
), tRP(p
->tRP
), tRAS(p
->tRAS
), tWR(p
->tWR
),
79 tRTP(p
->tRTP
), 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 // set the bank indices
100 for (int r
= 0; r
< ranksPerChannel
; r
++) {
101 for (int b
= 0; b
< banksPerRank
; b
++) {
102 banks
[r
][b
].rank
= r
;
103 banks
[r
][b
].bank
= b
;
107 // perform a basic check of the write thresholds
108 if (p
->write_low_thresh_perc
>= p
->write_high_thresh_perc
)
109 fatal("Write buffer low threshold %d must be smaller than the "
110 "high threshold %d\n", p
->write_low_thresh_perc
,
111 p
->write_high_thresh_perc
);
113 // determine the rows per bank by looking at the total capacity
114 uint64_t capacity
= ULL(1) << ceilLog2(AbstractMemory::size());
116 DPRINTF(DRAM
, "Memory capacity %lld (%lld) bytes\n", capacity
,
117 AbstractMemory::size());
119 DPRINTF(DRAM
, "Row buffer size %d bytes with %d columns per row buffer\n",
120 rowBufferSize
, columnsPerRowBuffer
);
122 rowsPerBank
= capacity
/ (rowBufferSize
* banksPerRank
* ranksPerChannel
);
124 if (range
.interleaved()) {
125 if (channels
!= range
.stripes())
126 fatal("%s has %d interleaved address stripes but %d channel(s)\n",
127 name(), range
.stripes(), channels
);
129 if (addrMapping
== Enums::RoRaBaChCo
) {
130 if (rowBufferSize
!= range
.granularity()) {
131 fatal("Interleaving of %s doesn't match RoRaBaChCo "
132 "address map\n", name());
134 } else if (addrMapping
== Enums::RoRaBaCoCh
) {
135 if (system()->cacheLineSize() != range
.granularity()) {
136 fatal("Interleaving of %s doesn't match RoRaBaCoCh "
137 "address map\n", name());
139 } else if (addrMapping
== Enums::RoCoRaBaCh
) {
140 if (system()->cacheLineSize() != range
.granularity())
141 fatal("Interleaving of %s doesn't match RoCoRaBaCh "
142 "address map\n", name());
146 // some basic sanity checks
147 if (tREFI
<= tRP
|| tREFI
<= tRFC
) {
148 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
156 if (!port
.isConnected()) {
157 fatal("DRAMCtrl %s is unconnected!\n", name());
159 port
.sendRangeChange();
166 // update the start tick for the precharge accounting to the
168 pwrStateTick
= curTick();
170 // shift the bus busy time sufficiently far ahead that we never
171 // have to worry about negative values when computing the time for
172 // the next request, this will add an insignificant bubble at the
173 // start of simulation
174 busBusyUntil
= curTick() + tRP
+ tRCD
+ tCL
;
176 // kick off the refresh, and give ourselves enough time to
178 schedule(refreshEvent
, curTick() + tREFI
- tRP
);
182 DRAMCtrl::recvAtomic(PacketPtr pkt
)
184 DPRINTF(DRAM
, "recvAtomic: %s 0x%x\n", pkt
->cmdString(), pkt
->getAddr());
186 // do the actual memory access and turn the packet into a response
190 if (!pkt
->memInhibitAsserted() && pkt
->hasData()) {
191 // this value is not supposed to be accurate, just enough to
192 // keep things going, mimic a closed page
193 latency
= tRP
+ tRCD
+ tCL
;
199 DRAMCtrl::readQueueFull(unsigned int neededEntries
) const
201 DPRINTF(DRAM
, "Read queue limit %d, current size %d, entries needed %d\n",
202 readBufferSize
, readQueue
.size() + respQueue
.size(),
206 (readQueue
.size() + respQueue
.size() + neededEntries
) > readBufferSize
;
210 DRAMCtrl::writeQueueFull(unsigned int neededEntries
) const
212 DPRINTF(DRAM
, "Write queue limit %d, current size %d, entries needed %d\n",
213 writeBufferSize
, writeQueue
.size(), neededEntries
);
214 return (writeQueue
.size() + neededEntries
) > writeBufferSize
;
217 DRAMCtrl::DRAMPacket
*
218 DRAMCtrl::decodeAddr(PacketPtr pkt
, Addr dramPktAddr
, unsigned size
,
221 // decode the address based on the address mapping scheme, with
222 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
223 // channel, respectively
226 // use a 64-bit unsigned during the computations as the row is
227 // always the top bits, and check before creating the DRAMPacket
230 // truncate the address to the access granularity
231 Addr addr
= dramPktAddr
/ burstSize
;
233 // we have removed the lowest order address bits that denote the
234 // position within the column
235 if (addrMapping
== Enums::RoRaBaChCo
) {
236 // the lowest order bits denote the column to ensure that
237 // sequential cache lines occupy the same row
238 addr
= addr
/ columnsPerRowBuffer
;
240 // take out the channel part of the address
241 addr
= addr
/ channels
;
243 // after the channel bits, get the bank bits to interleave
245 bank
= addr
% banksPerRank
;
246 addr
= addr
/ banksPerRank
;
248 // after the bank, we get the rank bits which thus interleaves
250 rank
= addr
% ranksPerChannel
;
251 addr
= addr
/ ranksPerChannel
;
253 // lastly, get the row bits
254 row
= addr
% rowsPerBank
;
255 addr
= addr
/ rowsPerBank
;
256 } else if (addrMapping
== Enums::RoRaBaCoCh
) {
257 // take out the channel part of the address
258 addr
= addr
/ channels
;
261 addr
= addr
/ columnsPerRowBuffer
;
263 // after the column bits, we get the bank bits to interleave
265 bank
= addr
% banksPerRank
;
266 addr
= addr
/ banksPerRank
;
268 // after the bank, we get the rank bits which thus interleaves
270 rank
= addr
% ranksPerChannel
;
271 addr
= addr
/ ranksPerChannel
;
273 // lastly, get the row bits
274 row
= addr
% rowsPerBank
;
275 addr
= addr
/ rowsPerBank
;
276 } else if (addrMapping
== Enums::RoCoRaBaCh
) {
277 // optimise for closed page mode and utilise maximum
278 // parallelism of the DRAM (at the cost of power)
280 // take out the channel part of the address, not that this has
281 // to match with how accesses are interleaved between the
282 // controllers in the address mapping
283 addr
= addr
/ channels
;
285 // start with the bank bits, as this provides the maximum
286 // opportunity for parallelism between requests
287 bank
= addr
% banksPerRank
;
288 addr
= addr
/ banksPerRank
;
290 // next get the rank bits
291 rank
= addr
% ranksPerChannel
;
292 addr
= addr
/ ranksPerChannel
;
294 // next the column bits which we do not need to keep track of
295 // and simply skip past
296 addr
= addr
/ columnsPerRowBuffer
;
298 // lastly, get the row bits
299 row
= addr
% rowsPerBank
;
300 addr
= addr
/ rowsPerBank
;
302 panic("Unknown address mapping policy chosen!");
304 assert(rank
< ranksPerChannel
);
305 assert(bank
< banksPerRank
);
306 assert(row
< rowsPerBank
);
307 assert(row
< Bank::NO_ROW
);
309 DPRINTF(DRAM
, "Address: %lld Rank %d Bank %d Row %d\n",
310 dramPktAddr
, rank
, bank
, row
);
312 // create the corresponding DRAM packet with the entry time and
313 // ready time set to the current tick, the latter will be updated
315 uint16_t bank_id
= banksPerRank
* rank
+ bank
;
316 return new DRAMPacket(pkt
, isRead
, rank
, bank
, row
, bank_id
, dramPktAddr
,
317 size
, banks
[rank
][bank
]);
321 DRAMCtrl::addToReadQueue(PacketPtr pkt
, unsigned int pktCount
)
323 // only add to the read queue here. whenever the request is
324 // eventually done, set the readyTime, and call schedule()
325 assert(!pkt
->isWrite());
327 assert(pktCount
!= 0);
329 // if the request size is larger than burst size, the pkt is split into
330 // multiple DRAM packets
331 // Note if the pkt starting address is not aligened to burst size, the
332 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
333 // are aligned to burst size boundaries. This is to ensure we accurately
334 // check read packets against packets in write queue.
335 Addr addr
= pkt
->getAddr();
336 unsigned pktsServicedByWrQ
= 0;
337 BurstHelper
* burst_helper
= NULL
;
338 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
339 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
340 pkt
->getAddr() + pkt
->getSize()) - addr
;
341 readPktSize
[ceilLog2(size
)]++;
344 // First check write buffer to see if the data is already at
346 bool foundInWrQ
= false;
347 for (auto i
= writeQueue
.begin(); i
!= writeQueue
.end(); ++i
) {
348 // check if the read is subsumed in the write entry we are
350 if ((*i
)->addr
<= addr
&&
351 (addr
+ size
) <= ((*i
)->addr
+ (*i
)->size
)) {
355 DPRINTF(DRAM
, "Read to addr %lld with size %d serviced by "
356 "write queue\n", addr
, size
);
357 bytesReadWrQ
+= burstSize
;
362 // If not found in the write q, make a DRAM packet and
363 // push it onto the read queue
366 // Make the burst helper for split packets
367 if (pktCount
> 1 && burst_helper
== NULL
) {
368 DPRINTF(DRAM
, "Read to addr %lld translates to %d "
369 "dram requests\n", pkt
->getAddr(), pktCount
);
370 burst_helper
= new BurstHelper(pktCount
);
373 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, true);
374 dram_pkt
->burstHelper
= burst_helper
;
376 assert(!readQueueFull(1));
377 rdQLenPdf
[readQueue
.size() + respQueue
.size()]++;
379 DPRINTF(DRAM
, "Adding to read queue\n");
381 readQueue
.push_back(dram_pkt
);
384 avgRdQLen
= readQueue
.size() + respQueue
.size();
387 // Starting address of next dram pkt (aligend to burstSize boundary)
388 addr
= (addr
| (burstSize
- 1)) + 1;
391 // If all packets are serviced by write queue, we send the repsonse back
392 if (pktsServicedByWrQ
== pktCount
) {
393 accessAndRespond(pkt
, frontendLatency
);
397 // Update how many split packets are serviced by write queue
398 if (burst_helper
!= NULL
)
399 burst_helper
->burstsServiced
= pktsServicedByWrQ
;
401 // If we are not already scheduled to get a request out of the
403 if (!nextReqEvent
.scheduled()) {
404 DPRINTF(DRAM
, "Request scheduled immediately\n");
405 schedule(nextReqEvent
, curTick());
410 DRAMCtrl::addToWriteQueue(PacketPtr pkt
, unsigned int pktCount
)
412 // only add to the write queue here. whenever the request is
413 // eventually done, set the readyTime, and call schedule()
414 assert(pkt
->isWrite());
416 // if the request size is larger than burst size, the pkt is split into
417 // multiple DRAM packets
418 Addr addr
= pkt
->getAddr();
419 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
420 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
421 pkt
->getAddr() + pkt
->getSize()) - addr
;
422 writePktSize
[ceilLog2(size
)]++;
425 // see if we can merge with an existing item in the write
426 // queue and keep track of whether we have merged or not so we
427 // can stop at that point and also avoid enqueueing a new
430 auto w
= writeQueue
.begin();
432 while(!merged
&& w
!= writeQueue
.end()) {
433 // either of the two could be first, if they are the same
434 // it does not matter which way we go
435 if ((*w
)->addr
>= addr
) {
436 // the existing one starts after the new one, figure
437 // out where the new one ends with respect to the
439 if ((addr
+ size
) >= ((*w
)->addr
+ (*w
)->size
)) {
440 // check if the existing one is completely
441 // subsumed in the new one
442 DPRINTF(DRAM
, "Merging write covering existing burst\n");
444 // update both the address and the size
447 } else if ((addr
+ size
) >= (*w
)->addr
&&
448 ((*w
)->addr
+ (*w
)->size
- addr
) <= burstSize
) {
449 // the new one is just before or partially
450 // overlapping with the existing one, and together
451 // they fit within a burst
452 DPRINTF(DRAM
, "Merging write before existing burst\n");
454 // the existing queue item needs to be adjusted with
455 // respect to both address and size
456 (*w
)->size
= (*w
)->addr
+ (*w
)->size
- addr
;
460 // the new one starts after the current one, figure
461 // out where the existing one ends with respect to the
463 if (((*w
)->addr
+ (*w
)->size
) >= (addr
+ size
)) {
464 // check if the new one is completely subsumed in the
466 DPRINTF(DRAM
, "Merging write into existing burst\n");
468 // no adjustments necessary
469 } else if (((*w
)->addr
+ (*w
)->size
) >= addr
&&
470 (addr
+ size
- (*w
)->addr
) <= burstSize
) {
471 // the existing one is just before or partially
472 // overlapping with the new one, and together
473 // they fit within a burst
474 DPRINTF(DRAM
, "Merging write after existing burst\n");
476 // the address is right, and only the size has
478 (*w
)->size
= addr
+ size
- (*w
)->addr
;
484 // if the item was not merged we need to create a new write
487 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, false);
489 assert(writeQueue
.size() < writeBufferSize
);
490 wrQLenPdf
[writeQueue
.size()]++;
492 DPRINTF(DRAM
, "Adding to write queue\n");
494 writeQueue
.push_back(dram_pkt
);
497 avgWrQLen
= writeQueue
.size();
499 // keep track of the fact that this burst effectively
500 // disappeared as it was merged with an existing one
504 // Starting address of next dram pkt (aligend to burstSize boundary)
505 addr
= (addr
| (burstSize
- 1)) + 1;
508 // we do not wait for the writes to be send to the actual memory,
509 // but instead take responsibility for the consistency here and
510 // snoop the write queue for any upcoming reads
511 // @todo, if a pkt size is larger than burst size, we might need a
512 // different front end latency
513 accessAndRespond(pkt
, frontendLatency
);
515 // If we are not already scheduled to get a request out of the
517 if (!nextReqEvent
.scheduled()) {
518 DPRINTF(DRAM
, "Request scheduled immediately\n");
519 schedule(nextReqEvent
, curTick());
524 DRAMCtrl::printQs() const {
525 DPRINTF(DRAM
, "===READ QUEUE===\n\n");
526 for (auto i
= readQueue
.begin() ; i
!= readQueue
.end() ; ++i
) {
527 DPRINTF(DRAM
, "Read %lu\n", (*i
)->addr
);
529 DPRINTF(DRAM
, "\n===RESP QUEUE===\n\n");
530 for (auto i
= respQueue
.begin() ; i
!= respQueue
.end() ; ++i
) {
531 DPRINTF(DRAM
, "Response %lu\n", (*i
)->addr
);
533 DPRINTF(DRAM
, "\n===WRITE QUEUE===\n\n");
534 for (auto i
= writeQueue
.begin() ; i
!= writeQueue
.end() ; ++i
) {
535 DPRINTF(DRAM
, "Write %lu\n", (*i
)->addr
);
540 DRAMCtrl::recvTimingReq(PacketPtr pkt
)
542 /// @todo temporary hack to deal with memory corruption issues until
543 /// 4-phase transactions are complete
544 for (int x
= 0; x
< pendingDelete
.size(); x
++)
545 delete pendingDelete
[x
];
546 pendingDelete
.clear();
548 // This is where we enter from the outside world
549 DPRINTF(DRAM
, "recvTimingReq: request %s addr %lld size %d\n",
550 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
552 // simply drop inhibited packets for now
553 if (pkt
->memInhibitAsserted()) {
554 DPRINTF(DRAM
, "Inhibited packet -- Dropping it now\n");
555 pendingDelete
.push_back(pkt
);
559 // Calc avg gap between requests
560 if (prevArrival
!= 0) {
561 totGap
+= curTick() - prevArrival
;
563 prevArrival
= curTick();
566 // Find out how many dram packets a pkt translates to
567 // If the burst size is equal or larger than the pkt size, then a pkt
568 // translates to only one dram packet. Otherwise, a pkt translates to
569 // multiple dram packets
570 unsigned size
= pkt
->getSize();
571 unsigned offset
= pkt
->getAddr() & (burstSize
- 1);
572 unsigned int dram_pkt_count
= divCeil(offset
+ size
, burstSize
);
574 // check local buffers and do not accept if full
577 if (readQueueFull(dram_pkt_count
)) {
578 DPRINTF(DRAM
, "Read queue full, not accepting\n");
579 // remember that we have to retry this port
584 addToReadQueue(pkt
, dram_pkt_count
);
586 bytesReadSys
+= size
;
588 } else if (pkt
->isWrite()) {
590 if (writeQueueFull(dram_pkt_count
)) {
591 DPRINTF(DRAM
, "Write queue full, not accepting\n");
592 // remember that we have to retry this port
597 addToWriteQueue(pkt
, dram_pkt_count
);
599 bytesWrittenSys
+= size
;
602 DPRINTF(DRAM
,"Neither read nor write, ignore timing\n");
603 neitherReadNorWrite
++;
604 accessAndRespond(pkt
, 1);
611 DRAMCtrl::processRespondEvent()
614 "processRespondEvent(): Some req has reached its readyTime\n");
616 DRAMPacket
* dram_pkt
= respQueue
.front();
618 if (dram_pkt
->burstHelper
) {
619 // it is a split packet
620 dram_pkt
->burstHelper
->burstsServiced
++;
621 if (dram_pkt
->burstHelper
->burstsServiced
==
622 dram_pkt
->burstHelper
->burstCount
) {
623 // we have now serviced all children packets of a system packet
624 // so we can now respond to the requester
625 // @todo we probably want to have a different front end and back
626 // end latency for split packets
627 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
628 delete dram_pkt
->burstHelper
;
629 dram_pkt
->burstHelper
= NULL
;
632 // it is not a split packet
633 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
636 delete respQueue
.front();
637 respQueue
.pop_front();
639 if (!respQueue
.empty()) {
640 assert(respQueue
.front()->readyTime
>= curTick());
641 assert(!respondEvent
.scheduled());
642 schedule(respondEvent
, respQueue
.front()->readyTime
);
644 // if there is nothing left in any queue, signal a drain
645 if (writeQueue
.empty() && readQueue
.empty() &&
647 drainManager
->signalDrainDone();
652 // We have made a location in the queue available at this point,
653 // so if there is a read that was forced to wait, retry now
661 DRAMCtrl::chooseNext(std::deque
<DRAMPacket
*>& queue
)
663 // This method does the arbitration between requests. The chosen
664 // packet is simply moved to the head of the queue. The other
665 // methods know that this is the place to look. For example, with
666 // FCFS, this method does nothing
667 assert(!queue
.empty());
669 if (queue
.size() == 1) {
670 DPRINTF(DRAM
, "Single request, nothing to do\n");
674 if (memSchedPolicy
== Enums::fcfs
) {
675 // Do nothing, since the correct request is already head
676 } else if (memSchedPolicy
== Enums::frfcfs
) {
679 panic("No scheduling policy chosen\n");
683 DRAMCtrl::reorderQueue(std::deque
<DRAMPacket
*>& queue
)
685 // Only determine this when needed
686 uint64_t earliest_banks
= 0;
688 // Search for row hits first, if no row hit is found then schedule the
689 // packet to one of the earliest banks available
690 bool found_earliest_pkt
= false;
691 auto selected_pkt_it
= queue
.begin();
693 for (auto i
= queue
.begin(); i
!= queue
.end() ; ++i
) {
694 DRAMPacket
* dram_pkt
= *i
;
695 const Bank
& bank
= dram_pkt
->bankRef
;
696 // Check if it is a row hit
697 if (bank
.openRow
== dram_pkt
->row
) {
698 // FCFS within the hits
699 DPRINTF(DRAM
, "Row buffer hit\n");
702 } else if (!found_earliest_pkt
) {
703 // No row hit, go for first ready
704 if (earliest_banks
== 0)
705 earliest_banks
= minBankActAt(queue
);
707 // simplistic approximation of when the bank can issue an
708 // activate, this is calculated in minBankActAt and could
710 Tick act_at
= bank
.openRow
== Bank::NO_ROW
?
712 std::max(bank
.preAllowedAt
, curTick()) + tRP
;
714 // Bank is ready or is the first available bank
715 if (act_at
<= curTick() ||
716 bits(earliest_banks
, dram_pkt
->bankId
, dram_pkt
->bankId
)) {
717 // Remember the packet to be scheduled to one of the earliest
718 // banks available, FCFS amongst the earliest banks
720 found_earliest_pkt
= true;
725 DRAMPacket
* selected_pkt
= *selected_pkt_it
;
726 queue
.erase(selected_pkt_it
);
727 queue
.push_front(selected_pkt
);
731 DRAMCtrl::accessAndRespond(PacketPtr pkt
, Tick static_latency
)
733 DPRINTF(DRAM
, "Responding to Address %lld.. ",pkt
->getAddr());
735 bool needsResponse
= pkt
->needsResponse();
736 // do the actual memory access which also turns the packet into a
740 // turn packet around to go back to requester if response expected
742 // access already turned the packet into a response
743 assert(pkt
->isResponse());
745 // @todo someone should pay for this
746 pkt
->busFirstWordDelay
= pkt
->busLastWordDelay
= 0;
748 // queue the packet in the response queue to be sent out after
749 // the static latency has passed
750 port
.schedTimingResp(pkt
, curTick() + static_latency
);
752 // @todo the packet is going to be deleted, and the DRAMPacket
753 // is still having a pointer to it
754 pendingDelete
.push_back(pkt
);
757 DPRINTF(DRAM
, "Done\n");
763 DRAMCtrl::activateBank(Bank
& bank
, Tick act_tick
, uint32_t row
)
765 // get the rank index from the bank
766 uint8_t rank
= bank
.rank
;
768 assert(actTicks
[rank
].size() == activationLimit
);
770 DPRINTF(DRAM
, "Activate at tick %d\n", act_tick
);
772 // update the open row
773 assert(bank
.openRow
== Bank::NO_ROW
);
776 // start counting anew, this covers both the case when we
777 // auto-precharged, and when this access is forced to
779 bank
.bytesAccessed
= 0;
780 bank
.rowAccesses
= 0;
783 assert(numBanksActive
<= banksPerRank
* ranksPerChannel
);
785 DPRINTF(DRAM
, "Activate bank at tick %lld, now got %d active\n",
786 act_tick
, numBanksActive
);
788 // The next access has to respect tRAS for this bank
789 bank
.preAllowedAt
= act_tick
+ tRAS
;
791 // Respect the row-to-column command delay
792 bank
.colAllowedAt
= act_tick
+ tRCD
;
794 // start by enforcing tRRD
795 for(int i
= 0; i
< banksPerRank
; i
++) {
796 // next activate to any bank in this rank must not happen
798 banks
[rank
][i
].actAllowedAt
= std::max(act_tick
+ tRRD
,
799 banks
[rank
][i
].actAllowedAt
);
802 // next, we deal with tXAW, if the activation limit is disabled
804 if (actTicks
[rank
].empty())
808 if (actTicks
[rank
].back() && (act_tick
- actTicks
[rank
].back()) < tXAW
) {
809 panic("Got %d activates in window %d (%llu - %llu) which is smaller "
810 "than %llu\n", activationLimit
, act_tick
- actTicks
[rank
].back(),
811 act_tick
, actTicks
[rank
].back(), tXAW
);
814 // shift the times used for the book keeping, the last element
815 // (highest index) is the oldest one and hence the lowest value
816 actTicks
[rank
].pop_back();
818 // record an new activation (in the future)
819 actTicks
[rank
].push_front(act_tick
);
821 // cannot activate more than X times in time window tXAW, push the
822 // next one (the X + 1'st activate) to be tXAW away from the
823 // oldest in our window of X
824 if (actTicks
[rank
].back() && (act_tick
- actTicks
[rank
].back()) < tXAW
) {
825 DPRINTF(DRAM
, "Enforcing tXAW with X = %d, next activate no earlier "
826 "than %llu\n", activationLimit
, actTicks
[rank
].back() + tXAW
);
827 for(int j
= 0; j
< banksPerRank
; j
++)
828 // next activate must not happen before end of window
829 banks
[rank
][j
].actAllowedAt
=
830 std::max(actTicks
[rank
].back() + tXAW
,
831 banks
[rank
][j
].actAllowedAt
);
834 // at the point when this activate takes place, make sure we
835 // transition to the active power state
836 if (!activateEvent
.scheduled())
837 schedule(activateEvent
, act_tick
);
838 else if (activateEvent
.when() > act_tick
)
839 // move it sooner in time
840 reschedule(activateEvent
, act_tick
);
844 DRAMCtrl::processActivateEvent()
846 // we should transition to the active state as soon as any bank is active
847 if (pwrState
!= PWR_ACT
)
848 // note that at this point numBanksActive could be back at
849 // zero again due to a precharge scheduled in the future
850 schedulePowerEvent(PWR_ACT
, curTick());
854 DRAMCtrl::prechargeBank(Bank
& bank
, Tick pre_at
)
856 // make sure the bank has an open row
857 assert(bank
.openRow
!= Bank::NO_ROW
);
859 // sample the bytes per activate here since we are closing
861 bytesPerActivate
.sample(bank
.bytesAccessed
);
863 bank
.openRow
= Bank::NO_ROW
;
865 // no precharge allowed before this one
866 bank
.preAllowedAt
= pre_at
;
868 Tick pre_done_at
= pre_at
+ tRP
;
870 bank
.actAllowedAt
= std::max(bank
.actAllowedAt
, pre_done_at
);
872 assert(numBanksActive
!= 0);
875 DPRINTF(DRAM
, "Precharging bank at tick %lld, now got %d active\n",
876 pre_at
, numBanksActive
);
878 // if we look at the current number of active banks we might be
879 // tempted to think the DRAM is now idle, however this can be
880 // undone by an activate that is scheduled to happen before we
881 // would have reached the idle state, so schedule an event and
882 // rather check once we actually make it to the point in time when
883 // the (last) precharge takes place
884 if (!prechargeEvent
.scheduled())
885 schedule(prechargeEvent
, pre_done_at
);
886 else if (prechargeEvent
.when() < pre_done_at
)
887 reschedule(prechargeEvent
, pre_done_at
);
891 DRAMCtrl::processPrechargeEvent()
893 // if we reached zero, then special conditions apply as we track
894 // if all banks are precharged for the power models
895 if (numBanksActive
== 0) {
896 // we should transition to the idle state when the last bank
898 schedulePowerEvent(PWR_IDLE
, curTick());
903 DRAMCtrl::doDRAMAccess(DRAMPacket
* dram_pkt
)
905 DPRINTF(DRAM
, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
906 dram_pkt
->addr
, dram_pkt
->rank
, dram_pkt
->bank
, dram_pkt
->row
);
909 Bank
& bank
= dram_pkt
->bankRef
;
911 // for the state we need to track if it is a row hit or not
914 // respect any constraints on the command (e.g. tRCD or tCCD)
915 Tick cmd_at
= std::max(bank
.colAllowedAt
, curTick());
917 // Determine the access latency and update the bank state
918 if (bank
.openRow
== dram_pkt
->row
) {
923 // If there is a page open, precharge it.
924 if (bank
.openRow
!= Bank::NO_ROW
) {
925 prechargeBank(bank
, std::max(bank
.preAllowedAt
, curTick()));
928 // next we need to account for the delay in activating the
930 Tick act_tick
= std::max(bank
.actAllowedAt
, curTick());
932 // Record the activation and deal with all the global timing
933 // constraints caused be a new activation (tRRD and tXAW)
934 activateBank(bank
, act_tick
, dram_pkt
->row
);
936 // issue the command as early as possible
937 cmd_at
= bank
.colAllowedAt
;
940 // we need to wait until the bus is available before we can issue
942 cmd_at
= std::max(cmd_at
, busBusyUntil
- tCL
);
944 // update the packet ready time
945 dram_pkt
->readyTime
= cmd_at
+ tCL
+ tBURST
;
947 // only one burst can use the bus at any one point in time
948 assert(dram_pkt
->readyTime
- busBusyUntil
>= tBURST
);
950 // not strictly necessary, but update the time for the next
951 // read/write (add a max with tCCD here)
952 bank
.colAllowedAt
= cmd_at
+ tBURST
;
954 // If this is a write, we also need to respect the write recovery
955 // time before a precharge, in the case of a read, respect the
956 // read to precharge constraint
957 bank
.preAllowedAt
= std::max(bank
.preAllowedAt
,
958 dram_pkt
->isRead
? cmd_at
+ tRTP
:
959 dram_pkt
->readyTime
+ tWR
);
961 // increment the bytes accessed and the accesses per row
962 bank
.bytesAccessed
+= burstSize
;
965 // if we reached the max, then issue with an auto-precharge
966 bool auto_precharge
= pageMgmt
== Enums::close
||
967 bank
.rowAccesses
== maxAccessesPerRow
;
969 // if we did not hit the limit, we might still want to
971 if (!auto_precharge
&&
972 (pageMgmt
== Enums::open_adaptive
||
973 pageMgmt
== Enums::close_adaptive
)) {
974 // a twist on the open and close page policies:
975 // 1) open_adaptive page policy does not blindly keep the
976 // page open, but close it if there are no row hits, and there
977 // are bank conflicts in the queue
978 // 2) close_adaptive page policy does not blindly close the
979 // page, but closes it only if there are no row hits in the queue.
980 // In this case, only force an auto precharge when there
981 // are no same page hits in the queue
982 bool got_more_hits
= false;
983 bool got_bank_conflict
= false;
985 // either look at the read queue or write queue
986 const deque
<DRAMPacket
*>& queue
= dram_pkt
->isRead
? readQueue
:
988 auto p
= queue
.begin();
989 // make sure we are not considering the packet that we are
990 // currently dealing with (which is the head of the queue)
993 // keep on looking until we have found required condition or
995 while (!(got_more_hits
&&
996 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
)) &&
998 bool same_rank_bank
= (dram_pkt
->rank
== (*p
)->rank
) &&
999 (dram_pkt
->bank
== (*p
)->bank
);
1000 bool same_row
= dram_pkt
->row
== (*p
)->row
;
1001 got_more_hits
|= same_rank_bank
&& same_row
;
1002 got_bank_conflict
|= same_rank_bank
&& !same_row
;
1006 // auto pre-charge when either
1007 // 1) open_adaptive policy, we have not got any more hits, and
1008 // have a bank conflict
1009 // 2) close_adaptive policy and we have not got any more hits
1010 auto_precharge
= !got_more_hits
&&
1011 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
);
1014 // if this access should use auto-precharge, then we are
1016 if (auto_precharge
) {
1017 prechargeBank(bank
, std::max(curTick(), bank
.preAllowedAt
));
1019 DPRINTF(DRAM
, "Auto-precharged bank: %d\n", dram_pkt
->bankId
);
1023 busBusyUntil
= dram_pkt
->readyTime
;
1025 DPRINTF(DRAM
, "Access to %lld, ready at %lld bus busy until %lld.\n",
1026 dram_pkt
->addr
, dram_pkt
->readyTime
, busBusyUntil
);
1028 // Update the minimum timing between the requests, this is a
1029 // conservative estimate of when we have to schedule the next
1030 // request to not introduce any unecessary bubbles. In most cases
1031 // we will wake up sooner than we have to.
1032 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1034 // Update the stats and schedule the next request
1035 if (dram_pkt
->isRead
) {
1039 bytesReadDRAM
+= burstSize
;
1040 perBankRdBursts
[dram_pkt
->bankId
]++;
1042 // Update latency stats
1043 totMemAccLat
+= dram_pkt
->readyTime
- dram_pkt
->entryTime
;
1044 totBusLat
+= tBURST
;
1045 totQLat
+= cmd_at
- dram_pkt
->entryTime
;
1050 bytesWritten
+= burstSize
;
1051 perBankWrBursts
[dram_pkt
->bankId
]++;
1056 DRAMCtrl::processNextReqEvent()
1058 if (busState
== READ_TO_WRITE
) {
1059 DPRINTF(DRAM
, "Switching to writes after %d reads with %d reads "
1060 "waiting\n", readsThisTime
, readQueue
.size());
1062 // sample and reset the read-related stats as we are now
1063 // transitioning to writes, and all reads are done
1064 rdPerTurnAround
.sample(readsThisTime
);
1067 // now proceed to do the actual writes
1069 } else if (busState
== WRITE_TO_READ
) {
1070 DPRINTF(DRAM
, "Switching to reads after %d writes with %d writes "
1071 "waiting\n", writesThisTime
, writeQueue
.size());
1073 wrPerTurnAround
.sample(writesThisTime
);
1079 if (refreshState
!= REF_IDLE
) {
1080 // if a refresh waiting for this event loop to finish, then hand
1081 // over now, and do not schedule a new nextReqEvent
1082 if (refreshState
== REF_DRAIN
) {
1083 DPRINTF(DRAM
, "Refresh drain done, now precharging\n");
1085 refreshState
= REF_PRE
;
1087 // hand control back to the refresh event loop
1088 schedule(refreshEvent
, curTick());
1091 // let the refresh finish before issuing any further requests
1095 // when we get here it is either a read or a write
1096 if (busState
== READ
) {
1098 // track if we should switch or not
1099 bool switch_to_writes
= false;
1101 if (readQueue
.empty()) {
1102 // In the case there is no read request to go next,
1103 // trigger writes if we have passed the low threshold (or
1104 // if we are draining)
1105 if (!writeQueue
.empty() &&
1106 (drainManager
|| writeQueue
.size() > writeLowThreshold
)) {
1108 switch_to_writes
= true;
1110 // check if we are drained
1111 if (respQueue
.empty () && drainManager
) {
1112 drainManager
->signalDrainDone();
1113 drainManager
= NULL
;
1116 // nothing to do, not even any point in scheduling an
1117 // event for the next request
1121 // Figure out which read request goes next, and move it to the
1122 // front of the read queue
1123 chooseNext(readQueue
);
1125 DRAMPacket
* dram_pkt
= readQueue
.front();
1127 doDRAMAccess(dram_pkt
);
1129 // At this point we're done dealing with the request
1130 readQueue
.pop_front();
1133 assert(dram_pkt
->size
<= burstSize
);
1134 assert(dram_pkt
->readyTime
>= curTick());
1136 // Insert into response queue. It will be sent back to the
1137 // requestor at its readyTime
1138 if (respQueue
.empty()) {
1139 assert(!respondEvent
.scheduled());
1140 schedule(respondEvent
, dram_pkt
->readyTime
);
1142 assert(respQueue
.back()->readyTime
<= dram_pkt
->readyTime
);
1143 assert(respondEvent
.scheduled());
1146 respQueue
.push_back(dram_pkt
);
1148 // we have so many writes that we have to transition
1149 if (writeQueue
.size() > writeHighThreshold
) {
1150 switch_to_writes
= true;
1154 // switching to writes, either because the read queue is empty
1155 // and the writes have passed the low threshold (or we are
1156 // draining), or because the writes hit the hight threshold
1157 if (switch_to_writes
) {
1158 // transition to writing
1159 busState
= READ_TO_WRITE
;
1161 // add a bubble to the data bus, as defined by the
1163 busBusyUntil
+= tRTW
;
1165 // update the minimum timing between the requests,
1166 // this shifts us back in time far enough to do any
1168 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1171 chooseNext(writeQueue
);
1172 DRAMPacket
* dram_pkt
= writeQueue
.front();
1174 assert(dram_pkt
->size
<= burstSize
);
1175 doDRAMAccess(dram_pkt
);
1177 writeQueue
.pop_front();
1180 // If we emptied the write queue, or got sufficiently below the
1181 // threshold (using the minWritesPerSwitch as the hysteresis) and
1182 // are not draining, or we have reads waiting and have done enough
1183 // writes, then switch to reads.
1184 if (writeQueue
.empty() ||
1185 (writeQueue
.size() + minWritesPerSwitch
< writeLowThreshold
&&
1187 (!readQueue
.empty() && writesThisTime
>= minWritesPerSwitch
)) {
1188 // turn the bus back around for reads again
1189 busState
= WRITE_TO_READ
;
1191 // note that the we switch back to reads also in the idle
1192 // case, which eventually will check for any draining and
1193 // also pause any further scheduling if there is really
1196 // here we get a bit creative and shift the bus busy time not
1197 // just the tWTR, but also a CAS latency to capture the fact
1198 // that we are allowed to prepare a new bank, but not issue a
1199 // read command until after tWTR, in essence we capture a
1200 // bubble on the data bus that is tWTR + tCL
1201 busBusyUntil
+= tWTR
+ tCL
;
1203 // update the minimum timing between the requests, this shifts
1204 // us back in time far enough to do any bank preparation
1205 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1209 schedule(nextReqEvent
, std::max(nextReqTime
, curTick()));
1211 // If there is space available and we have writes waiting then let
1212 // them retry. This is done here to ensure that the retry does not
1213 // cause a nextReqEvent to be scheduled before we do so as part of
1214 // the next request processing
1215 if (retryWrReq
&& writeQueue
.size() < writeBufferSize
) {
1222 DRAMCtrl::minBankActAt(const deque
<DRAMPacket
*>& queue
) const
1224 uint64_t bank_mask
= 0;
1225 Tick min_act_at
= MaxTick
;
1227 // deterimne if we have queued transactions targetting a
1229 vector
<bool> got_waiting(ranksPerChannel
* banksPerRank
, false);
1230 for (auto p
= queue
.begin(); p
!= queue
.end(); ++p
) {
1231 got_waiting
[(*p
)->bankId
] = true;
1234 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1235 for (int j
= 0; j
< banksPerRank
; j
++) {
1236 uint8_t bank_id
= i
* banksPerRank
+ j
;
1238 // if we have waiting requests for the bank, and it is
1239 // amongst the first available, update the mask
1240 if (got_waiting
[bank_id
]) {
1241 // simplistic approximation of when the bank can issue
1242 // an activate, ignoring any rank-to-rank switching
1244 Tick act_at
= banks
[i
][j
].openRow
== Bank::NO_ROW
?
1245 banks
[i
][j
].actAllowedAt
:
1246 std::max(banks
[i
][j
].preAllowedAt
, curTick()) + tRP
;
1248 if (act_at
<= min_act_at
) {
1249 // reset bank mask if new minimum is found
1250 if (act_at
< min_act_at
)
1252 // set the bit corresponding to the available bank
1253 replaceBits(bank_mask
, bank_id
, bank_id
, 1);
1254 min_act_at
= act_at
;
1264 DRAMCtrl::processRefreshEvent()
1266 // when first preparing the refresh, remember when it was due
1267 if (refreshState
== REF_IDLE
) {
1268 // remember when the refresh is due
1269 refreshDueAt
= curTick();
1272 refreshState
= REF_DRAIN
;
1274 DPRINTF(DRAM
, "Refresh due\n");
1277 // let any scheduled read or write go ahead, after which it will
1278 // hand control back to this event loop
1279 if (refreshState
== REF_DRAIN
) {
1280 if (nextReqEvent
.scheduled()) {
1281 // hand control over to the request loop until it is
1283 DPRINTF(DRAM
, "Refresh awaiting draining\n");
1287 refreshState
= REF_PRE
;
1291 // at this point, ensure that all banks are precharged
1292 if (refreshState
== REF_PRE
) {
1293 // precharge any active bank if we are not already in the idle
1295 if (pwrState
!= PWR_IDLE
) {
1296 // at the moment, we use a precharge all even if there is
1297 // only a single bank open
1298 DPRINTF(DRAM
, "Precharging all\n");
1300 // first determine when we can precharge
1301 Tick pre_at
= curTick();
1302 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1303 for (int j
= 0; j
< banksPerRank
; j
++) {
1304 // respect both causality and any existing bank
1305 // constraints, some banks could already have a
1306 // (auto) precharge scheduled
1307 pre_at
= std::max(banks
[i
][j
].preAllowedAt
, pre_at
);
1311 // make sure all banks are precharged, and for those that
1312 // already are, update their availability
1313 Tick act_allowed_at
= pre_at
+ tRP
;
1315 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1316 for (int j
= 0; j
< banksPerRank
; j
++) {
1317 if (banks
[i
][j
].openRow
!= Bank::NO_ROW
) {
1318 prechargeBank(banks
[i
][j
], pre_at
);
1320 banks
[i
][j
].actAllowedAt
=
1321 std::max(banks
[i
][j
].actAllowedAt
, act_allowed_at
);
1322 banks
[i
][j
].preAllowedAt
=
1323 std::max(banks
[i
][j
].preAllowedAt
, pre_at
);
1328 DPRINTF(DRAM
, "All banks already precharged, starting refresh\n");
1330 // go ahead and kick the power state machine into gear if
1331 // we are already idle
1332 schedulePowerEvent(PWR_REF
, curTick());
1335 refreshState
= REF_RUN
;
1336 assert(numBanksActive
== 0);
1338 // wait for all banks to be precharged, at which point the
1339 // power state machine will transition to the idle state, and
1340 // automatically move to a refresh, at that point it will also
1341 // call this method to get the refresh event loop going again
1345 // last but not least we perform the actual refresh
1346 if (refreshState
== REF_RUN
) {
1347 // should never get here with any banks active
1348 assert(numBanksActive
== 0);
1349 assert(pwrState
== PWR_REF
);
1351 Tick ref_done_at
= curTick() + tRFC
;
1353 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1354 for (int j
= 0; j
< banksPerRank
; j
++) {
1355 banks
[i
][j
].actAllowedAt
= ref_done_at
;
1359 // make sure we did not wait so long that we cannot make up
1361 if (refreshDueAt
+ tREFI
< ref_done_at
) {
1362 fatal("Refresh was delayed so long we cannot catch up\n");
1365 // compensate for the delay in actually performing the refresh
1366 // when scheduling the next one
1367 schedule(refreshEvent
, refreshDueAt
+ tREFI
- tRP
);
1369 assert(!powerEvent
.scheduled());
1371 // move to the idle power state once the refresh is done, this
1372 // will also move the refresh state machine to the refresh
1374 schedulePowerEvent(PWR_IDLE
, ref_done_at
);
1376 DPRINTF(DRAMState
, "Refresh done at %llu and next refresh at %llu\n",
1377 ref_done_at
, refreshDueAt
+ tREFI
);
1382 DRAMCtrl::schedulePowerEvent(PowerState pwr_state
, Tick tick
)
1384 // respect causality
1385 assert(tick
>= curTick());
1387 if (!powerEvent
.scheduled()) {
1388 DPRINTF(DRAMState
, "Scheduling power event at %llu to state %d\n",
1391 // insert the new transition
1392 pwrStateTrans
= pwr_state
;
1394 schedule(powerEvent
, tick
);
1396 panic("Scheduled power event at %llu to state %d, "
1397 "with scheduled event at %llu to %d\n", tick
, pwr_state
,
1398 powerEvent
.when(), pwrStateTrans
);
1403 DRAMCtrl::processPowerEvent()
1405 // remember where we were, and for how long
1406 Tick duration
= curTick() - pwrStateTick
;
1407 PowerState prev_state
= pwrState
;
1409 // update the accounting
1410 pwrStateTime
[prev_state
] += duration
;
1412 pwrState
= pwrStateTrans
;
1413 pwrStateTick
= curTick();
1415 if (pwrState
== PWR_IDLE
) {
1416 DPRINTF(DRAMState
, "All banks precharged\n");
1418 // if we were refreshing, make sure we start scheduling requests again
1419 if (prev_state
== PWR_REF
) {
1420 DPRINTF(DRAMState
, "Was refreshing for %llu ticks\n", duration
);
1421 assert(pwrState
== PWR_IDLE
);
1423 // kick things into action again
1424 refreshState
= REF_IDLE
;
1425 assert(!nextReqEvent
.scheduled());
1426 schedule(nextReqEvent
, curTick());
1428 assert(prev_state
== PWR_ACT
);
1430 // if we have a pending refresh, and are now moving to
1431 // the idle state, direclty transition to a refresh
1432 if (refreshState
== REF_RUN
) {
1433 // there should be nothing waiting at this point
1434 assert(!powerEvent
.scheduled());
1436 // update the state in zero time and proceed below
1442 // we transition to the refresh state, let the refresh state
1443 // machine know of this state update and let it deal with the
1444 // scheduling of the next power state transition as well as the
1445 // following refresh
1446 if (pwrState
== PWR_REF
) {
1447 DPRINTF(DRAMState
, "Refreshing\n");
1448 // kick the refresh event loop into action again, and that
1449 // in turn will schedule a transition to the idle power
1450 // state once the refresh is done
1451 assert(refreshState
== REF_RUN
);
1452 processRefreshEvent();
1457 DRAMCtrl::regStats()
1459 using namespace Stats
;
1461 AbstractMemory::regStats();
1464 .name(name() + ".readReqs")
1465 .desc("Number of read requests accepted");
1468 .name(name() + ".writeReqs")
1469 .desc("Number of write requests accepted");
1472 .name(name() + ".readBursts")
1473 .desc("Number of DRAM read bursts, "
1474 "including those serviced by the write queue");
1477 .name(name() + ".writeBursts")
1478 .desc("Number of DRAM write bursts, "
1479 "including those merged in the write queue");
1482 .name(name() + ".servicedByWrQ")
1483 .desc("Number of DRAM read bursts serviced by the write queue");
1486 .name(name() + ".mergedWrBursts")
1487 .desc("Number of DRAM write bursts merged with an existing one");
1490 .name(name() + ".neitherReadNorWriteReqs")
1491 .desc("Number of requests that are neither read nor write");
1494 .init(banksPerRank
* ranksPerChannel
)
1495 .name(name() + ".perBankRdBursts")
1496 .desc("Per bank write bursts");
1499 .init(banksPerRank
* ranksPerChannel
)
1500 .name(name() + ".perBankWrBursts")
1501 .desc("Per bank write bursts");
1504 .name(name() + ".avgRdQLen")
1505 .desc("Average read queue length when enqueuing")
1509 .name(name() + ".avgWrQLen")
1510 .desc("Average write queue length when enqueuing")
1514 .name(name() + ".totQLat")
1515 .desc("Total ticks spent queuing");
1518 .name(name() + ".totBusLat")
1519 .desc("Total ticks spent in databus transfers");
1522 .name(name() + ".totMemAccLat")
1523 .desc("Total ticks spent from burst creation until serviced "
1527 .name(name() + ".avgQLat")
1528 .desc("Average queueing delay per DRAM burst")
1531 avgQLat
= totQLat
/ (readBursts
- servicedByWrQ
);
1534 .name(name() + ".avgBusLat")
1535 .desc("Average bus latency per DRAM burst")
1538 avgBusLat
= totBusLat
/ (readBursts
- servicedByWrQ
);
1541 .name(name() + ".avgMemAccLat")
1542 .desc("Average memory access latency per DRAM burst")
1545 avgMemAccLat
= totMemAccLat
/ (readBursts
- servicedByWrQ
);
1548 .name(name() + ".numRdRetry")
1549 .desc("Number of times read queue was full causing retry");
1552 .name(name() + ".numWrRetry")
1553 .desc("Number of times write queue was full causing retry");
1556 .name(name() + ".readRowHits")
1557 .desc("Number of row buffer hits during reads");
1560 .name(name() + ".writeRowHits")
1561 .desc("Number of row buffer hits during writes");
1564 .name(name() + ".readRowHitRate")
1565 .desc("Row buffer hit rate for reads")
1568 readRowHitRate
= (readRowHits
/ (readBursts
- servicedByWrQ
)) * 100;
1571 .name(name() + ".writeRowHitRate")
1572 .desc("Row buffer hit rate for writes")
1575 writeRowHitRate
= (writeRowHits
/ (writeBursts
- mergedWrBursts
)) * 100;
1578 .init(ceilLog2(burstSize
) + 1)
1579 .name(name() + ".readPktSize")
1580 .desc("Read request sizes (log2)");
1583 .init(ceilLog2(burstSize
) + 1)
1584 .name(name() + ".writePktSize")
1585 .desc("Write request sizes (log2)");
1588 .init(readBufferSize
)
1589 .name(name() + ".rdQLenPdf")
1590 .desc("What read queue length does an incoming req see");
1593 .init(writeBufferSize
)
1594 .name(name() + ".wrQLenPdf")
1595 .desc("What write queue length does an incoming req see");
1598 .init(maxAccessesPerRow
)
1599 .name(name() + ".bytesPerActivate")
1600 .desc("Bytes accessed per row activation")
1604 .init(readBufferSize
)
1605 .name(name() + ".rdPerTurnAround")
1606 .desc("Reads before turning the bus around for writes")
1610 .init(writeBufferSize
)
1611 .name(name() + ".wrPerTurnAround")
1612 .desc("Writes before turning the bus around for reads")
1616 .name(name() + ".bytesReadDRAM")
1617 .desc("Total number of bytes read from DRAM");
1620 .name(name() + ".bytesReadWrQ")
1621 .desc("Total number of bytes read from write queue");
1624 .name(name() + ".bytesWritten")
1625 .desc("Total number of bytes written to DRAM");
1628 .name(name() + ".bytesReadSys")
1629 .desc("Total read bytes from the system interface side");
1632 .name(name() + ".bytesWrittenSys")
1633 .desc("Total written bytes from the system interface side");
1636 .name(name() + ".avgRdBW")
1637 .desc("Average DRAM read bandwidth in MiByte/s")
1640 avgRdBW
= (bytesReadDRAM
/ 1000000) / simSeconds
;
1643 .name(name() + ".avgWrBW")
1644 .desc("Average achieved write bandwidth in MiByte/s")
1647 avgWrBW
= (bytesWritten
/ 1000000) / simSeconds
;
1650 .name(name() + ".avgRdBWSys")
1651 .desc("Average system read bandwidth in MiByte/s")
1654 avgRdBWSys
= (bytesReadSys
/ 1000000) / simSeconds
;
1657 .name(name() + ".avgWrBWSys")
1658 .desc("Average system write bandwidth in MiByte/s")
1661 avgWrBWSys
= (bytesWrittenSys
/ 1000000) / simSeconds
;
1664 .name(name() + ".peakBW")
1665 .desc("Theoretical peak bandwidth in MiByte/s")
1668 peakBW
= (SimClock::Frequency
/ tBURST
) * burstSize
/ 1000000;
1671 .name(name() + ".busUtil")
1672 .desc("Data bus utilization in percentage")
1675 busUtil
= (avgRdBW
+ avgWrBW
) / peakBW
* 100;
1678 .name(name() + ".totGap")
1679 .desc("Total gap between requests");
1682 .name(name() + ".avgGap")
1683 .desc("Average gap between requests")
1686 avgGap
= totGap
/ (readReqs
+ writeReqs
);
1688 // Stats for DRAM Power calculation based on Micron datasheet
1690 .name(name() + ".busUtilRead")
1691 .desc("Data bus utilization in percentage for reads")
1694 busUtilRead
= avgRdBW
/ peakBW
* 100;
1697 .name(name() + ".busUtilWrite")
1698 .desc("Data bus utilization in percentage for writes")
1701 busUtilWrite
= avgWrBW
/ peakBW
* 100;
1704 .name(name() + ".pageHitRate")
1705 .desc("Row buffer hit rate, read and write combined")
1708 pageHitRate
= (writeRowHits
+ readRowHits
) /
1709 (writeBursts
- mergedWrBursts
+ readBursts
- servicedByWrQ
) * 100;
1713 .name(name() + ".memoryStateTime")
1714 .desc("Time in different power states");
1715 pwrStateTime
.subname(0, "IDLE");
1716 pwrStateTime
.subname(1, "REF");
1717 pwrStateTime
.subname(2, "PRE_PDN");
1718 pwrStateTime
.subname(3, "ACT");
1719 pwrStateTime
.subname(4, "ACT_PDN");
1723 DRAMCtrl::recvFunctional(PacketPtr pkt
)
1725 // rely on the abstract memory
1726 functionalAccess(pkt
);
1730 DRAMCtrl::getSlavePort(const string
&if_name
, PortID idx
)
1732 if (if_name
!= "port") {
1733 return MemObject::getSlavePort(if_name
, idx
);
1740 DRAMCtrl::drain(DrainManager
*dm
)
1742 unsigned int count
= port
.drain(dm
);
1744 // if there is anything in any of our internal queues, keep track
1746 if (!(writeQueue
.empty() && readQueue
.empty() &&
1747 respQueue
.empty())) {
1748 DPRINTF(Drain
, "DRAM controller not drained, write: %d, read: %d,"
1749 " resp: %d\n", writeQueue
.size(), readQueue
.size(),
1754 // the only part that is not drained automatically over time
1755 // is the write queue, thus kick things into action if needed
1756 if (!writeQueue
.empty() && !nextReqEvent
.scheduled()) {
1757 schedule(nextReqEvent
, curTick());
1762 setDrainState(Drainable::Draining
);
1764 setDrainState(Drainable::Drained
);
1768 DRAMCtrl::MemoryPort::MemoryPort(const std::string
& name
, DRAMCtrl
& _memory
)
1769 : QueuedSlavePort(name
, &_memory
, queue
), queue(_memory
, *this),
1774 DRAMCtrl::MemoryPort::getAddrRanges() const
1776 AddrRangeList ranges
;
1777 ranges
.push_back(memory
.getAddrRange());
1782 DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt
)
1784 pkt
->pushLabel(memory
.name());
1786 if (!queue
.checkFunctional(pkt
)) {
1787 // Default implementation of SimpleTimingPort::recvFunctional()
1788 // calls recvAtomic() and throws away the latency; we can save a
1789 // little here by just not calculating the latency.
1790 memory
.recvFunctional(pkt
);
1797 DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt
)
1799 return memory
.recvAtomic(pkt
);
1803 DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt
)
1805 // pass it to the memory controller
1806 return memory
.recvTimingReq(pkt
);
1810 DRAMCtrlParams::create()
1812 return new DRAMCtrl(this);