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
46 #include "base/bitfield.hh"
47 #include "base/trace.hh"
48 #include "debug/DRAM.hh"
49 #include "debug/DRAMPower.hh"
50 #include "debug/DRAMState.hh"
51 #include "debug/Drain.hh"
52 #include "mem/dram_ctrl.hh"
53 #include "sim/system.hh"
58 DRAMCtrl::DRAMCtrl(const DRAMCtrlParams
* p
) :
60 port(name() + ".port", *this), isTimingMode(false),
61 retryRdReq(false), retryWrReq(false),
63 nextReqEvent(this), respondEvent(this),
65 deviceSize(p
->device_size
),
66 deviceBusWidth(p
->device_bus_width
), burstLength(p
->burst_length
),
67 deviceRowBufferSize(p
->device_rowbuffer_size
),
68 devicesPerRank(p
->devices_per_rank
),
69 burstSize((devicesPerRank
* burstLength
* deviceBusWidth
) / 8),
70 rowBufferSize(devicesPerRank
* deviceRowBufferSize
),
71 columnsPerRowBuffer(rowBufferSize
/ burstSize
),
72 columnsPerStripe(range
.granularity() / burstSize
),
73 ranksPerChannel(p
->ranks_per_channel
),
74 bankGroupsPerRank(p
->bank_groups_per_rank
),
75 bankGroupArch(p
->bank_groups_per_rank
> 0),
76 banksPerRank(p
->banks_per_rank
), channels(p
->channels
), rowsPerBank(0),
77 readBufferSize(p
->read_buffer_size
),
78 writeBufferSize(p
->write_buffer_size
),
79 writeHighThreshold(writeBufferSize
* p
->write_high_thresh_perc
/ 100.0),
80 writeLowThreshold(writeBufferSize
* p
->write_low_thresh_perc
/ 100.0),
81 minWritesPerSwitch(p
->min_writes_per_switch
),
82 writesThisTime(0), readsThisTime(0),
83 tCK(p
->tCK
), tWTR(p
->tWTR
), tRTW(p
->tRTW
), tCS(p
->tCS
), tBURST(p
->tBURST
),
84 tCCD_L(p
->tCCD_L
), tRCD(p
->tRCD
), tCL(p
->tCL
), tRP(p
->tRP
), tRAS(p
->tRAS
),
85 tWR(p
->tWR
), tRTP(p
->tRTP
), tRFC(p
->tRFC
), tREFI(p
->tREFI
), tRRD(p
->tRRD
),
86 tRRD_L(p
->tRRD_L
), tXAW(p
->tXAW
), activationLimit(p
->activation_limit
),
87 memSchedPolicy(p
->mem_sched_policy
), addrMapping(p
->addr_mapping
),
88 pageMgmt(p
->page_policy
),
89 maxAccessesPerRow(p
->max_accesses_per_row
),
90 frontendLatency(p
->static_frontend_latency
),
91 backendLatency(p
->static_backend_latency
),
92 busBusyUntil(0), prevArrival(0),
93 nextReqTime(0), activeRank(0), timeStampOffset(0)
95 // sanity check the ranks since we rely on bit slicing for the
97 fatal_if(!isPowerOf2(ranksPerChannel
), "DRAM rank count of %d is not "
98 "allowed, must be a power of two\n", ranksPerChannel
);
100 for (int i
= 0; i
< ranksPerChannel
; i
++) {
101 Rank
* rank
= new Rank(*this, p
);
102 ranks
.push_back(rank
);
104 rank
->actTicks
.resize(activationLimit
, 0);
105 rank
->banks
.resize(banksPerRank
);
108 for (int b
= 0; b
< banksPerRank
; b
++) {
109 rank
->banks
[b
].bank
= b
;
110 // GDDR addressing of banks to BG is linear.
111 // Here we assume that all DRAM generations address bank groups as
114 // Simply assign lower bits to bank group in order to
115 // rotate across bank groups as banks are incremented
116 // e.g. with 4 banks per bank group and 16 banks total:
117 // banks 0,4,8,12 are in bank group 0
118 // banks 1,5,9,13 are in bank group 1
119 // banks 2,6,10,14 are in bank group 2
120 // banks 3,7,11,15 are in bank group 3
121 rank
->banks
[b
].bankgr
= b
% bankGroupsPerRank
;
123 // No bank groups; simply assign to bank number
124 rank
->banks
[b
].bankgr
= b
;
129 // perform a basic check of the write thresholds
130 if (p
->write_low_thresh_perc
>= p
->write_high_thresh_perc
)
131 fatal("Write buffer low threshold %d must be smaller than the "
132 "high threshold %d\n", p
->write_low_thresh_perc
,
133 p
->write_high_thresh_perc
);
135 // determine the rows per bank by looking at the total capacity
136 uint64_t capacity
= ULL(1) << ceilLog2(AbstractMemory::size());
138 // determine the dram actual capacity from the DRAM config in Mbytes
139 uint64_t deviceCapacity
= deviceSize
/ (1024 * 1024) * devicesPerRank
*
142 // if actual DRAM size does not match memory capacity in system warn!
143 if (deviceCapacity
!= capacity
/ (1024 * 1024))
144 warn("DRAM device capacity (%d Mbytes) does not match the "
145 "address range assigned (%d Mbytes)\n", deviceCapacity
,
146 capacity
/ (1024 * 1024));
148 DPRINTF(DRAM
, "Memory capacity %lld (%lld) bytes\n", capacity
,
149 AbstractMemory::size());
151 DPRINTF(DRAM
, "Row buffer size %d bytes with %d columns per row buffer\n",
152 rowBufferSize
, columnsPerRowBuffer
);
154 rowsPerBank
= capacity
/ (rowBufferSize
* banksPerRank
* ranksPerChannel
);
156 // a bit of sanity checks on the interleaving
157 if (range
.interleaved()) {
158 if (channels
!= range
.stripes())
159 fatal("%s has %d interleaved address stripes but %d channel(s)\n",
160 name(), range
.stripes(), channels
);
162 if (addrMapping
== Enums::RoRaBaChCo
) {
163 if (rowBufferSize
!= range
.granularity()) {
164 fatal("Channel interleaving of %s doesn't match RoRaBaChCo "
165 "address map\n", name());
167 } else if (addrMapping
== Enums::RoRaBaCoCh
||
168 addrMapping
== Enums::RoCoRaBaCh
) {
169 // for the interleavings with channel bits in the bottom,
170 // if the system uses a channel striping granularity that
171 // is larger than the DRAM burst size, then map the
172 // sequential accesses within a stripe to a number of
173 // columns in the DRAM, effectively placing some of the
174 // lower-order column bits as the least-significant bits
175 // of the address (above the ones denoting the burst size)
176 assert(columnsPerStripe
>= 1);
178 // channel striping has to be done at a granularity that
179 // is equal or larger to a cache line
180 if (system()->cacheLineSize() > range
.granularity()) {
181 fatal("Channel interleaving of %s must be at least as large "
182 "as the cache line size\n", name());
185 // ...and equal or smaller than the row-buffer size
186 if (rowBufferSize
< range
.granularity()) {
187 fatal("Channel interleaving of %s must be at most as large "
188 "as the row-buffer size\n", name());
190 // this is essentially the check above, so just to be sure
191 assert(columnsPerStripe
<= columnsPerRowBuffer
);
195 // some basic sanity checks
196 if (tREFI
<= tRP
|| tREFI
<= tRFC
) {
197 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
201 // basic bank group architecture checks ->
203 // must have at least one bank per bank group
204 if (bankGroupsPerRank
> banksPerRank
) {
205 fatal("banks per rank (%d) must be equal to or larger than "
206 "banks groups per rank (%d)\n",
207 banksPerRank
, bankGroupsPerRank
);
209 // must have same number of banks in each bank group
210 if ((banksPerRank
% bankGroupsPerRank
) != 0) {
211 fatal("Banks per rank (%d) must be evenly divisible by bank groups "
212 "per rank (%d) for equal banks per bank group\n",
213 banksPerRank
, bankGroupsPerRank
);
215 // tCCD_L should be greater than minimal, back-to-back burst delay
216 if (tCCD_L
<= tBURST
) {
217 fatal("tCCD_L (%d) should be larger than tBURST (%d) when "
218 "bank groups per rank (%d) is greater than 1\n",
219 tCCD_L
, tBURST
, bankGroupsPerRank
);
221 // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
222 // some datasheets might specify it equal to tRRD
224 fatal("tRRD_L (%d) should be larger than tRRD (%d) when "
225 "bank groups per rank (%d) is greater than 1\n",
226 tRRD_L
, tRRD
, bankGroupsPerRank
);
235 AbstractMemory::init();
237 if (!port
.isConnected()) {
238 fatal("DRAMCtrl %s is unconnected!\n", name());
240 port
.sendRangeChange();
247 // remember the memory system mode of operation
248 isTimingMode
= system()->isTimingMode();
251 // timestamp offset should be in clock cycles for DRAMPower
252 timeStampOffset
= divCeil(curTick(), tCK
);
254 // update the start tick for the precharge accounting to the
256 for (auto r
: ranks
) {
257 r
->startup(curTick() + tREFI
- tRP
);
260 // shift the bus busy time sufficiently far ahead that we never
261 // have to worry about negative values when computing the time for
262 // the next request, this will add an insignificant bubble at the
263 // start of simulation
264 busBusyUntil
= curTick() + tRP
+ tRCD
+ tCL
;
269 DRAMCtrl::recvAtomic(PacketPtr pkt
)
271 DPRINTF(DRAM
, "recvAtomic: %s 0x%x\n", pkt
->cmdString(), pkt
->getAddr());
273 // do the actual memory access and turn the packet into a response
277 if (!pkt
->memInhibitAsserted() && pkt
->hasData()) {
278 // this value is not supposed to be accurate, just enough to
279 // keep things going, mimic a closed page
280 latency
= tRP
+ tRCD
+ tCL
;
286 DRAMCtrl::readQueueFull(unsigned int neededEntries
) const
288 DPRINTF(DRAM
, "Read queue limit %d, current size %d, entries needed %d\n",
289 readBufferSize
, readQueue
.size() + respQueue
.size(),
293 (readQueue
.size() + respQueue
.size() + neededEntries
) > readBufferSize
;
297 DRAMCtrl::writeQueueFull(unsigned int neededEntries
) const
299 DPRINTF(DRAM
, "Write queue limit %d, current size %d, entries needed %d\n",
300 writeBufferSize
, writeQueue
.size(), neededEntries
);
301 return (writeQueue
.size() + neededEntries
) > writeBufferSize
;
304 DRAMCtrl::DRAMPacket
*
305 DRAMCtrl::decodeAddr(PacketPtr pkt
, Addr dramPktAddr
, unsigned size
,
308 // decode the address based on the address mapping scheme, with
309 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
310 // channel, respectively
313 // use a 64-bit unsigned during the computations as the row is
314 // always the top bits, and check before creating the DRAMPacket
317 // truncate the address to a DRAM burst, which makes it unique to
318 // a specific column, row, bank, rank and channel
319 Addr addr
= dramPktAddr
/ burstSize
;
321 // we have removed the lowest order address bits that denote the
322 // position within the column
323 if (addrMapping
== Enums::RoRaBaChCo
) {
324 // the lowest order bits denote the column to ensure that
325 // sequential cache lines occupy the same row
326 addr
= addr
/ columnsPerRowBuffer
;
328 // take out the channel part of the address
329 addr
= addr
/ channels
;
331 // after the channel bits, get the bank bits to interleave
333 bank
= addr
% banksPerRank
;
334 addr
= addr
/ banksPerRank
;
336 // after the bank, we get the rank bits which thus interleaves
338 rank
= addr
% ranksPerChannel
;
339 addr
= addr
/ ranksPerChannel
;
341 // lastly, get the row bits
342 row
= addr
% rowsPerBank
;
343 addr
= addr
/ rowsPerBank
;
344 } else if (addrMapping
== Enums::RoRaBaCoCh
) {
345 // take out the lower-order column bits
346 addr
= addr
/ columnsPerStripe
;
348 // take out the channel part of the address
349 addr
= addr
/ channels
;
351 // next, the higher-order column bites
352 addr
= addr
/ (columnsPerRowBuffer
/ columnsPerStripe
);
354 // after the column bits, we get the bank bits to interleave
356 bank
= addr
% banksPerRank
;
357 addr
= addr
/ banksPerRank
;
359 // after the bank, we get the rank bits which thus interleaves
361 rank
= addr
% ranksPerChannel
;
362 addr
= addr
/ ranksPerChannel
;
364 // lastly, get the row bits
365 row
= addr
% rowsPerBank
;
366 addr
= addr
/ rowsPerBank
;
367 } else if (addrMapping
== Enums::RoCoRaBaCh
) {
368 // optimise for closed page mode and utilise maximum
369 // parallelism of the DRAM (at the cost of power)
371 // take out the lower-order column bits
372 addr
= addr
/ columnsPerStripe
;
374 // take out the channel part of the address, not that this has
375 // to match with how accesses are interleaved between the
376 // controllers in the address mapping
377 addr
= addr
/ channels
;
379 // start with the bank bits, as this provides the maximum
380 // opportunity for parallelism between requests
381 bank
= addr
% banksPerRank
;
382 addr
= addr
/ banksPerRank
;
384 // next get the rank bits
385 rank
= addr
% ranksPerChannel
;
386 addr
= addr
/ ranksPerChannel
;
388 // next, the higher-order column bites
389 addr
= addr
/ (columnsPerRowBuffer
/ columnsPerStripe
);
391 // lastly, get the row bits
392 row
= addr
% rowsPerBank
;
393 addr
= addr
/ rowsPerBank
;
395 panic("Unknown address mapping policy chosen!");
397 assert(rank
< ranksPerChannel
);
398 assert(bank
< banksPerRank
);
399 assert(row
< rowsPerBank
);
400 assert(row
< Bank::NO_ROW
);
402 DPRINTF(DRAM
, "Address: %lld Rank %d Bank %d Row %d\n",
403 dramPktAddr
, rank
, bank
, row
);
405 // create the corresponding DRAM packet with the entry time and
406 // ready time set to the current tick, the latter will be updated
408 uint16_t bank_id
= banksPerRank
* rank
+ bank
;
409 return new DRAMPacket(pkt
, isRead
, rank
, bank
, row
, bank_id
, dramPktAddr
,
410 size
, ranks
[rank
]->banks
[bank
], *ranks
[rank
]);
414 DRAMCtrl::addToReadQueue(PacketPtr pkt
, unsigned int pktCount
)
416 // only add to the read queue here. whenever the request is
417 // eventually done, set the readyTime, and call schedule()
418 assert(!pkt
->isWrite());
420 assert(pktCount
!= 0);
422 // if the request size is larger than burst size, the pkt is split into
423 // multiple DRAM packets
424 // Note if the pkt starting address is not aligened to burst size, the
425 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
426 // are aligned to burst size boundaries. This is to ensure we accurately
427 // check read packets against packets in write queue.
428 Addr addr
= pkt
->getAddr();
429 unsigned pktsServicedByWrQ
= 0;
430 BurstHelper
* burst_helper
= NULL
;
431 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
432 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
433 pkt
->getAddr() + pkt
->getSize()) - addr
;
434 readPktSize
[ceilLog2(size
)]++;
437 // First check write buffer to see if the data is already at
439 bool foundInWrQ
= false;
440 for (auto i
= writeQueue
.begin(); i
!= writeQueue
.end(); ++i
) {
441 // check if the read is subsumed in the write entry we are
443 if ((*i
)->addr
<= addr
&&
444 (addr
+ size
) <= ((*i
)->addr
+ (*i
)->size
)) {
448 DPRINTF(DRAM
, "Read to addr %lld with size %d serviced by "
449 "write queue\n", addr
, size
);
450 bytesReadWrQ
+= burstSize
;
455 // If not found in the write q, make a DRAM packet and
456 // push it onto the read queue
459 // Make the burst helper for split packets
460 if (pktCount
> 1 && burst_helper
== NULL
) {
461 DPRINTF(DRAM
, "Read to addr %lld translates to %d "
462 "dram requests\n", pkt
->getAddr(), pktCount
);
463 burst_helper
= new BurstHelper(pktCount
);
466 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, true);
467 dram_pkt
->burstHelper
= burst_helper
;
469 assert(!readQueueFull(1));
470 rdQLenPdf
[readQueue
.size() + respQueue
.size()]++;
472 DPRINTF(DRAM
, "Adding to read queue\n");
474 readQueue
.push_back(dram_pkt
);
477 avgRdQLen
= readQueue
.size() + respQueue
.size();
480 // Starting address of next dram pkt (aligend to burstSize boundary)
481 addr
= (addr
| (burstSize
- 1)) + 1;
484 // If all packets are serviced by write queue, we send the repsonse back
485 if (pktsServicedByWrQ
== pktCount
) {
486 accessAndRespond(pkt
, frontendLatency
);
490 // Update how many split packets are serviced by write queue
491 if (burst_helper
!= NULL
)
492 burst_helper
->burstsServiced
= pktsServicedByWrQ
;
494 // If we are not already scheduled to get a request out of the
496 if (!nextReqEvent
.scheduled()) {
497 DPRINTF(DRAM
, "Request scheduled immediately\n");
498 schedule(nextReqEvent
, curTick());
503 DRAMCtrl::addToWriteQueue(PacketPtr pkt
, unsigned int pktCount
)
505 // only add to the write queue here. whenever the request is
506 // eventually done, set the readyTime, and call schedule()
507 assert(pkt
->isWrite());
509 // if the request size is larger than burst size, the pkt is split into
510 // multiple DRAM packets
511 Addr addr
= pkt
->getAddr();
512 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
513 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
514 pkt
->getAddr() + pkt
->getSize()) - addr
;
515 writePktSize
[ceilLog2(size
)]++;
518 // see if we can merge with an existing item in the write
519 // queue and keep track of whether we have merged or not so we
520 // can stop at that point and also avoid enqueueing a new
523 auto w
= writeQueue
.begin();
525 while(!merged
&& w
!= writeQueue
.end()) {
526 // either of the two could be first, if they are the same
527 // it does not matter which way we go
528 if ((*w
)->addr
>= addr
) {
529 // the existing one starts after the new one, figure
530 // out where the new one ends with respect to the
532 if ((addr
+ size
) >= ((*w
)->addr
+ (*w
)->size
)) {
533 // check if the existing one is completely
534 // subsumed in the new one
535 DPRINTF(DRAM
, "Merging write covering existing burst\n");
537 // update both the address and the size
540 } else if ((addr
+ size
) >= (*w
)->addr
&&
541 ((*w
)->addr
+ (*w
)->size
- addr
) <= burstSize
) {
542 // the new one is just before or partially
543 // overlapping with the existing one, and together
544 // they fit within a burst
545 DPRINTF(DRAM
, "Merging write before existing burst\n");
547 // the existing queue item needs to be adjusted with
548 // respect to both address and size
549 (*w
)->size
= (*w
)->addr
+ (*w
)->size
- addr
;
553 // the new one starts after the current one, figure
554 // out where the existing one ends with respect to the
556 if (((*w
)->addr
+ (*w
)->size
) >= (addr
+ size
)) {
557 // check if the new one is completely subsumed in the
559 DPRINTF(DRAM
, "Merging write into existing burst\n");
561 // no adjustments necessary
562 } else if (((*w
)->addr
+ (*w
)->size
) >= addr
&&
563 (addr
+ size
- (*w
)->addr
) <= burstSize
) {
564 // the existing one is just before or partially
565 // overlapping with the new one, and together
566 // they fit within a burst
567 DPRINTF(DRAM
, "Merging write after existing burst\n");
569 // the address is right, and only the size has
571 (*w
)->size
= addr
+ size
- (*w
)->addr
;
577 // if the item was not merged we need to create a new write
580 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, false);
582 assert(writeQueue
.size() < writeBufferSize
);
583 wrQLenPdf
[writeQueue
.size()]++;
585 DPRINTF(DRAM
, "Adding to write queue\n");
587 writeQueue
.push_back(dram_pkt
);
590 avgWrQLen
= writeQueue
.size();
592 // keep track of the fact that this burst effectively
593 // disappeared as it was merged with an existing one
597 // Starting address of next dram pkt (aligend to burstSize boundary)
598 addr
= (addr
| (burstSize
- 1)) + 1;
601 // we do not wait for the writes to be send to the actual memory,
602 // but instead take responsibility for the consistency here and
603 // snoop the write queue for any upcoming reads
604 // @todo, if a pkt size is larger than burst size, we might need a
605 // different front end latency
606 accessAndRespond(pkt
, frontendLatency
);
608 // If we are not already scheduled to get a request out of the
610 if (!nextReqEvent
.scheduled()) {
611 DPRINTF(DRAM
, "Request scheduled immediately\n");
612 schedule(nextReqEvent
, curTick());
617 DRAMCtrl::printQs() const {
618 DPRINTF(DRAM
, "===READ QUEUE===\n\n");
619 for (auto i
= readQueue
.begin() ; i
!= readQueue
.end() ; ++i
) {
620 DPRINTF(DRAM
, "Read %lu\n", (*i
)->addr
);
622 DPRINTF(DRAM
, "\n===RESP QUEUE===\n\n");
623 for (auto i
= respQueue
.begin() ; i
!= respQueue
.end() ; ++i
) {
624 DPRINTF(DRAM
, "Response %lu\n", (*i
)->addr
);
626 DPRINTF(DRAM
, "\n===WRITE QUEUE===\n\n");
627 for (auto i
= writeQueue
.begin() ; i
!= writeQueue
.end() ; ++i
) {
628 DPRINTF(DRAM
, "Write %lu\n", (*i
)->addr
);
633 DRAMCtrl::recvTimingReq(PacketPtr pkt
)
635 /// @todo temporary hack to deal with memory corruption issues until
636 /// 4-phase transactions are complete
637 for (int x
= 0; x
< pendingDelete
.size(); x
++)
638 delete pendingDelete
[x
];
639 pendingDelete
.clear();
641 // This is where we enter from the outside world
642 DPRINTF(DRAM
, "recvTimingReq: request %s addr %lld size %d\n",
643 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
645 // simply drop inhibited packets for now
646 if (pkt
->memInhibitAsserted()) {
647 DPRINTF(DRAM
, "Inhibited packet -- Dropping it now\n");
648 pendingDelete
.push_back(pkt
);
652 // Calc avg gap between requests
653 if (prevArrival
!= 0) {
654 totGap
+= curTick() - prevArrival
;
656 prevArrival
= curTick();
659 // Find out how many dram packets a pkt translates to
660 // If the burst size is equal or larger than the pkt size, then a pkt
661 // translates to only one dram packet. Otherwise, a pkt translates to
662 // multiple dram packets
663 unsigned size
= pkt
->getSize();
664 unsigned offset
= pkt
->getAddr() & (burstSize
- 1);
665 unsigned int dram_pkt_count
= divCeil(offset
+ size
, burstSize
);
667 // check local buffers and do not accept if full
670 if (readQueueFull(dram_pkt_count
)) {
671 DPRINTF(DRAM
, "Read queue full, not accepting\n");
672 // remember that we have to retry this port
677 addToReadQueue(pkt
, dram_pkt_count
);
679 bytesReadSys
+= size
;
681 } else if (pkt
->isWrite()) {
683 if (writeQueueFull(dram_pkt_count
)) {
684 DPRINTF(DRAM
, "Write queue full, not accepting\n");
685 // remember that we have to retry this port
690 addToWriteQueue(pkt
, dram_pkt_count
);
692 bytesWrittenSys
+= size
;
695 DPRINTF(DRAM
,"Neither read nor write, ignore timing\n");
696 neitherReadNorWrite
++;
697 accessAndRespond(pkt
, 1);
704 DRAMCtrl::processRespondEvent()
707 "processRespondEvent(): Some req has reached its readyTime\n");
709 DRAMPacket
* dram_pkt
= respQueue
.front();
711 if (dram_pkt
->burstHelper
) {
712 // it is a split packet
713 dram_pkt
->burstHelper
->burstsServiced
++;
714 if (dram_pkt
->burstHelper
->burstsServiced
==
715 dram_pkt
->burstHelper
->burstCount
) {
716 // we have now serviced all children packets of a system packet
717 // so we can now respond to the requester
718 // @todo we probably want to have a different front end and back
719 // end latency for split packets
720 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
721 delete dram_pkt
->burstHelper
;
722 dram_pkt
->burstHelper
= NULL
;
725 // it is not a split packet
726 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
729 delete respQueue
.front();
730 respQueue
.pop_front();
732 if (!respQueue
.empty()) {
733 assert(respQueue
.front()->readyTime
>= curTick());
734 assert(!respondEvent
.scheduled());
735 schedule(respondEvent
, respQueue
.front()->readyTime
);
737 // if there is nothing left in any queue, signal a drain
738 if (writeQueue
.empty() && readQueue
.empty() &&
740 DPRINTF(Drain
, "DRAM controller done draining\n");
741 drainManager
->signalDrainDone();
746 // We have made a location in the queue available at this point,
747 // so if there is a read that was forced to wait, retry now
755 DRAMCtrl::chooseNext(std::deque
<DRAMPacket
*>& queue
, bool switched_cmd_type
)
757 // This method does the arbitration between requests. The chosen
758 // packet is simply moved to the head of the queue. The other
759 // methods know that this is the place to look. For example, with
760 // FCFS, this method does nothing
761 assert(!queue
.empty());
763 // bool to indicate if a packet to an available rank is found
764 bool found_packet
= false;
765 if (queue
.size() == 1) {
766 DRAMPacket
* dram_pkt
= queue
.front();
767 // available rank corresponds to state refresh idle
768 if (ranks
[dram_pkt
->rank
]->isAvailable()) {
770 DPRINTF(DRAM
, "Single request, going to a free rank\n");
772 DPRINTF(DRAM
, "Single request, going to a busy rank\n");
777 if (memSchedPolicy
== Enums::fcfs
) {
778 // check if there is a packet going to a free rank
779 for(auto i
= queue
.begin(); i
!= queue
.end() ; ++i
) {
780 DRAMPacket
* dram_pkt
= *i
;
781 if (ranks
[dram_pkt
->rank
]->isAvailable()) {
783 queue
.push_front(dram_pkt
);
788 } else if (memSchedPolicy
== Enums::frfcfs
) {
789 found_packet
= reorderQueue(queue
, switched_cmd_type
);
791 panic("No scheduling policy chosen\n");
796 DRAMCtrl::reorderQueue(std::deque
<DRAMPacket
*>& queue
, bool switched_cmd_type
)
798 // Only determine this when needed
799 uint64_t earliest_banks
= 0;
801 // Search for row hits first, if no row hit is found then schedule the
802 // packet to one of the earliest banks available
803 bool found_packet
= false;
804 bool found_earliest_pkt
= false;
805 bool found_prepped_diff_rank_pkt
= false;
806 auto selected_pkt_it
= queue
.end();
808 for (auto i
= queue
.begin(); i
!= queue
.end() ; ++i
) {
809 DRAMPacket
* dram_pkt
= *i
;
810 const Bank
& bank
= dram_pkt
->bankRef
;
811 // check if rank is busy. If this is the case jump to the next packet
812 // Check if it is a row hit
813 if (dram_pkt
->rankRef
.isAvailable()) {
814 if (bank
.openRow
== dram_pkt
->row
) {
815 if (dram_pkt
->rank
== activeRank
|| switched_cmd_type
) {
816 // FCFS within the hits, giving priority to commands
817 // that access the same rank as the previous burst
818 // to minimize bus turnaround delays
819 // Only give rank prioity when command type is
821 DPRINTF(DRAM
, "Row buffer hit\n");
824 } else if (!found_prepped_diff_rank_pkt
) {
825 // found row hit for command on different rank
828 found_prepped_diff_rank_pkt
= true;
830 } else if (!found_earliest_pkt
& !found_prepped_diff_rank_pkt
) {
831 // packet going to a rank which is currently not waiting for a
832 // refresh, No row hit and
833 // haven't found an entry with a row hit to a new rank
834 if (earliest_banks
== 0)
835 // Determine entries with earliest bank prep delay
836 // Function will give priority to commands that access the
837 // same rank as previous burst and can prep
838 // the bank seamlessly
839 earliest_banks
= minBankPrep(queue
, switched_cmd_type
);
841 // FCFS - Bank is first available bank
842 if (bits(earliest_banks
, dram_pkt
->bankId
,
844 // Remember the packet to be scheduled to one of
845 // the earliest banks available, FCFS amongst the
848 //if the packet found is going to a rank that is currently
849 //not busy then update the found_packet to true
850 found_earliest_pkt
= true;
856 if (selected_pkt_it
!= queue
.end()) {
857 DRAMPacket
* selected_pkt
= *selected_pkt_it
;
858 queue
.erase(selected_pkt_it
);
859 queue
.push_front(selected_pkt
);
866 DRAMCtrl::accessAndRespond(PacketPtr pkt
, Tick static_latency
)
868 DPRINTF(DRAM
, "Responding to Address %lld.. ",pkt
->getAddr());
870 bool needsResponse
= pkt
->needsResponse();
871 // do the actual memory access which also turns the packet into a
875 // turn packet around to go back to requester if response expected
877 // access already turned the packet into a response
878 assert(pkt
->isResponse());
880 // @todo someone should pay for this
881 pkt
->firstWordDelay
= pkt
->lastWordDelay
= 0;
883 // queue the packet in the response queue to be sent out after
884 // the static latency has passed
885 port
.schedTimingResp(pkt
, curTick() + static_latency
);
887 // @todo the packet is going to be deleted, and the DRAMPacket
888 // is still having a pointer to it
889 pendingDelete
.push_back(pkt
);
892 DPRINTF(DRAM
, "Done\n");
898 DRAMCtrl::activateBank(Rank
& rank_ref
, Bank
& bank_ref
,
899 Tick act_tick
, uint32_t row
)
901 assert(rank_ref
.actTicks
.size() == activationLimit
);
903 DPRINTF(DRAM
, "Activate at tick %d\n", act_tick
);
905 // update the open row
906 assert(bank_ref
.openRow
== Bank::NO_ROW
);
907 bank_ref
.openRow
= row
;
909 // start counting anew, this covers both the case when we
910 // auto-precharged, and when this access is forced to
912 bank_ref
.bytesAccessed
= 0;
913 bank_ref
.rowAccesses
= 0;
915 ++rank_ref
.numBanksActive
;
916 assert(rank_ref
.numBanksActive
<= banksPerRank
);
918 DPRINTF(DRAM
, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
919 bank_ref
.bank
, rank_ref
.rank
, act_tick
,
920 ranks
[rank_ref
.rank
]->numBanksActive
);
922 rank_ref
.power
.powerlib
.doCommand(MemCommand::ACT
, bank_ref
.bank
,
923 divCeil(act_tick
, tCK
) -
926 DPRINTF(DRAMPower
, "%llu,ACT,%d,%d\n", divCeil(act_tick
, tCK
) -
927 timeStampOffset
, bank_ref
.bank
, rank_ref
.rank
);
929 // The next access has to respect tRAS for this bank
930 bank_ref
.preAllowedAt
= act_tick
+ tRAS
;
932 // Respect the row-to-column command delay
933 bank_ref
.colAllowedAt
= std::max(act_tick
+ tRCD
, bank_ref
.colAllowedAt
);
935 // start by enforcing tRRD
936 for(int i
= 0; i
< banksPerRank
; i
++) {
937 // next activate to any bank in this rank must not happen
939 if (bankGroupArch
&& (bank_ref
.bankgr
== rank_ref
.banks
[i
].bankgr
)) {
940 // bank group architecture requires longer delays between
941 // ACT commands within the same bank group. Use tRRD_L
943 rank_ref
.banks
[i
].actAllowedAt
= std::max(act_tick
+ tRRD_L
,
944 rank_ref
.banks
[i
].actAllowedAt
);
946 // use shorter tRRD value when either
947 // 1) bank group architecture is not supportted
948 // 2) bank is in a different bank group
949 rank_ref
.banks
[i
].actAllowedAt
= std::max(act_tick
+ tRRD
,
950 rank_ref
.banks
[i
].actAllowedAt
);
954 // next, we deal with tXAW, if the activation limit is disabled
955 // then we directly schedule an activate power event
956 if (!rank_ref
.actTicks
.empty()) {
958 if (rank_ref
.actTicks
.back() &&
959 (act_tick
- rank_ref
.actTicks
.back()) < tXAW
) {
960 panic("Got %d activates in window %d (%llu - %llu) which "
961 "is smaller than %llu\n", activationLimit
, act_tick
-
962 rank_ref
.actTicks
.back(), act_tick
,
963 rank_ref
.actTicks
.back(), tXAW
);
966 // shift the times used for the book keeping, the last element
967 // (highest index) is the oldest one and hence the lowest value
968 rank_ref
.actTicks
.pop_back();
970 // record an new activation (in the future)
971 rank_ref
.actTicks
.push_front(act_tick
);
973 // cannot activate more than X times in time window tXAW, push the
974 // next one (the X + 1'st activate) to be tXAW away from the
975 // oldest in our window of X
976 if (rank_ref
.actTicks
.back() &&
977 (act_tick
- rank_ref
.actTicks
.back()) < tXAW
) {
978 DPRINTF(DRAM
, "Enforcing tXAW with X = %d, next activate "
979 "no earlier than %llu\n", activationLimit
,
980 rank_ref
.actTicks
.back() + tXAW
);
981 for(int j
= 0; j
< banksPerRank
; j
++)
982 // next activate must not happen before end of window
983 rank_ref
.banks
[j
].actAllowedAt
=
984 std::max(rank_ref
.actTicks
.back() + tXAW
,
985 rank_ref
.banks
[j
].actAllowedAt
);
989 // at the point when this activate takes place, make sure we
990 // transition to the active power state
991 if (!rank_ref
.activateEvent
.scheduled())
992 schedule(rank_ref
.activateEvent
, act_tick
);
993 else if (rank_ref
.activateEvent
.when() > act_tick
)
994 // move it sooner in time
995 reschedule(rank_ref
.activateEvent
, act_tick
);
999 DRAMCtrl::prechargeBank(Rank
& rank_ref
, Bank
& bank
, Tick pre_at
, bool trace
)
1001 // make sure the bank has an open row
1002 assert(bank
.openRow
!= Bank::NO_ROW
);
1004 // sample the bytes per activate here since we are closing
1006 bytesPerActivate
.sample(bank
.bytesAccessed
);
1008 bank
.openRow
= Bank::NO_ROW
;
1010 // no precharge allowed before this one
1011 bank
.preAllowedAt
= pre_at
;
1013 Tick pre_done_at
= pre_at
+ tRP
;
1015 bank
.actAllowedAt
= std::max(bank
.actAllowedAt
, pre_done_at
);
1017 assert(rank_ref
.numBanksActive
!= 0);
1018 --rank_ref
.numBanksActive
;
1020 DPRINTF(DRAM
, "Precharging bank %d, rank %d at tick %lld, now got "
1021 "%d active\n", bank
.bank
, rank_ref
.rank
, pre_at
,
1022 rank_ref
.numBanksActive
);
1026 rank_ref
.power
.powerlib
.doCommand(MemCommand::PRE
, bank
.bank
,
1027 divCeil(pre_at
, tCK
) -
1029 DPRINTF(DRAMPower
, "%llu,PRE,%d,%d\n", divCeil(pre_at
, tCK
) -
1030 timeStampOffset
, bank
.bank
, rank_ref
.rank
);
1032 // if we look at the current number of active banks we might be
1033 // tempted to think the DRAM is now idle, however this can be
1034 // undone by an activate that is scheduled to happen before we
1035 // would have reached the idle state, so schedule an event and
1036 // rather check once we actually make it to the point in time when
1037 // the (last) precharge takes place
1038 if (!rank_ref
.prechargeEvent
.scheduled())
1039 schedule(rank_ref
.prechargeEvent
, pre_done_at
);
1040 else if (rank_ref
.prechargeEvent
.when() < pre_done_at
)
1041 reschedule(rank_ref
.prechargeEvent
, pre_done_at
);
1045 DRAMCtrl::doDRAMAccess(DRAMPacket
* dram_pkt
)
1047 DPRINTF(DRAM
, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1048 dram_pkt
->addr
, dram_pkt
->rank
, dram_pkt
->bank
, dram_pkt
->row
);
1051 Rank
& rank
= dram_pkt
->rankRef
;
1054 Bank
& bank
= dram_pkt
->bankRef
;
1056 // for the state we need to track if it is a row hit or not
1057 bool row_hit
= true;
1059 // respect any constraints on the command (e.g. tRCD or tCCD)
1060 Tick cmd_at
= std::max(bank
.colAllowedAt
, curTick());
1062 // Determine the access latency and update the bank state
1063 if (bank
.openRow
== dram_pkt
->row
) {
1068 // If there is a page open, precharge it.
1069 if (bank
.openRow
!= Bank::NO_ROW
) {
1070 prechargeBank(rank
, bank
, std::max(bank
.preAllowedAt
, curTick()));
1073 // next we need to account for the delay in activating the
1075 Tick act_tick
= std::max(bank
.actAllowedAt
, curTick());
1077 // Record the activation and deal with all the global timing
1078 // constraints caused be a new activation (tRRD and tXAW)
1079 activateBank(rank
, bank
, act_tick
, dram_pkt
->row
);
1081 // issue the command as early as possible
1082 cmd_at
= bank
.colAllowedAt
;
1085 // we need to wait until the bus is available before we can issue
1087 cmd_at
= std::max(cmd_at
, busBusyUntil
- tCL
);
1089 // update the packet ready time
1090 dram_pkt
->readyTime
= cmd_at
+ tCL
+ tBURST
;
1092 // only one burst can use the bus at any one point in time
1093 assert(dram_pkt
->readyTime
- busBusyUntil
>= tBURST
);
1095 // update the time for the next read/write burst for each
1096 // bank (add a max with tCCD/tCCD_L here)
1098 for(int j
= 0; j
< ranksPerChannel
; j
++) {
1099 for(int i
= 0; i
< banksPerRank
; i
++) {
1100 // next burst to same bank group in this rank must not happen
1101 // before tCCD_L. Different bank group timing requirement is
1102 // tBURST; Add tCS for different ranks
1103 if (dram_pkt
->rank
== j
) {
1104 if (bankGroupArch
&&
1105 (bank
.bankgr
== ranks
[j
]->banks
[i
].bankgr
)) {
1106 // bank group architecture requires longer delays between
1107 // RD/WR burst commands to the same bank group.
1108 // Use tCCD_L in this case
1111 // use tBURST (equivalent to tCCD_S), the shorter
1112 // cas-to-cas delay value, when either:
1113 // 1) bank group architecture is not supportted
1114 // 2) bank is in a different bank group
1118 // different rank is by default in a different bank group
1119 // use tBURST (equivalent to tCCD_S), which is the shorter
1120 // cas-to-cas delay in this case
1121 // Add tCS to account for rank-to-rank bus delay requirements
1122 cmd_dly
= tBURST
+ tCS
;
1124 ranks
[j
]->banks
[i
].colAllowedAt
= std::max(cmd_at
+ cmd_dly
,
1125 ranks
[j
]->banks
[i
].colAllowedAt
);
1129 // Save rank of current access
1130 activeRank
= dram_pkt
->rank
;
1132 // If this is a write, we also need to respect the write recovery
1133 // time before a precharge, in the case of a read, respect the
1134 // read to precharge constraint
1135 bank
.preAllowedAt
= std::max(bank
.preAllowedAt
,
1136 dram_pkt
->isRead
? cmd_at
+ tRTP
:
1137 dram_pkt
->readyTime
+ tWR
);
1139 // increment the bytes accessed and the accesses per row
1140 bank
.bytesAccessed
+= burstSize
;
1143 // if we reached the max, then issue with an auto-precharge
1144 bool auto_precharge
= pageMgmt
== Enums::close
||
1145 bank
.rowAccesses
== maxAccessesPerRow
;
1147 // if we did not hit the limit, we might still want to
1149 if (!auto_precharge
&&
1150 (pageMgmt
== Enums::open_adaptive
||
1151 pageMgmt
== Enums::close_adaptive
)) {
1152 // a twist on the open and close page policies:
1153 // 1) open_adaptive page policy does not blindly keep the
1154 // page open, but close it if there are no row hits, and there
1155 // are bank conflicts in the queue
1156 // 2) close_adaptive page policy does not blindly close the
1157 // page, but closes it only if there are no row hits in the queue.
1158 // In this case, only force an auto precharge when there
1159 // are no same page hits in the queue
1160 bool got_more_hits
= false;
1161 bool got_bank_conflict
= false;
1163 // either look at the read queue or write queue
1164 const deque
<DRAMPacket
*>& queue
= dram_pkt
->isRead
? readQueue
:
1166 auto p
= queue
.begin();
1167 // make sure we are not considering the packet that we are
1168 // currently dealing with (which is the head of the queue)
1171 // keep on looking until we have found required condition or
1173 while (!(got_more_hits
&&
1174 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
)) &&
1176 bool same_rank_bank
= (dram_pkt
->rank
== (*p
)->rank
) &&
1177 (dram_pkt
->bank
== (*p
)->bank
);
1178 bool same_row
= dram_pkt
->row
== (*p
)->row
;
1179 got_more_hits
|= same_rank_bank
&& same_row
;
1180 got_bank_conflict
|= same_rank_bank
&& !same_row
;
1184 // auto pre-charge when either
1185 // 1) open_adaptive policy, we have not got any more hits, and
1186 // have a bank conflict
1187 // 2) close_adaptive policy and we have not got any more hits
1188 auto_precharge
= !got_more_hits
&&
1189 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
);
1192 // DRAMPower trace command to be written
1193 std::string mem_cmd
= dram_pkt
->isRead
? "RD" : "WR";
1195 // MemCommand required for DRAMPower library
1196 MemCommand::cmds command
= (mem_cmd
== "RD") ? MemCommand::RD
:
1199 // if this access should use auto-precharge, then we are
1201 if (auto_precharge
) {
1202 // if auto-precharge push a PRE command at the correct tick to the
1203 // list used by DRAMPower library to calculate power
1204 prechargeBank(rank
, bank
, std::max(curTick(), bank
.preAllowedAt
));
1206 DPRINTF(DRAM
, "Auto-precharged bank: %d\n", dram_pkt
->bankId
);
1210 busBusyUntil
= dram_pkt
->readyTime
;
1212 DPRINTF(DRAM
, "Access to %lld, ready at %lld bus busy until %lld.\n",
1213 dram_pkt
->addr
, dram_pkt
->readyTime
, busBusyUntil
);
1215 dram_pkt
->rankRef
.power
.powerlib
.doCommand(command
, dram_pkt
->bank
,
1216 divCeil(cmd_at
, tCK
) -
1219 DPRINTF(DRAMPower
, "%llu,%s,%d,%d\n", divCeil(cmd_at
, tCK
) -
1220 timeStampOffset
, mem_cmd
, dram_pkt
->bank
, dram_pkt
->rank
);
1222 // Update the minimum timing between the requests, this is a
1223 // conservative estimate of when we have to schedule the next
1224 // request to not introduce any unecessary bubbles. In most cases
1225 // we will wake up sooner than we have to.
1226 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1228 // Update the stats and schedule the next request
1229 if (dram_pkt
->isRead
) {
1233 bytesReadDRAM
+= burstSize
;
1234 perBankRdBursts
[dram_pkt
->bankId
]++;
1236 // Update latency stats
1237 totMemAccLat
+= dram_pkt
->readyTime
- dram_pkt
->entryTime
;
1238 totBusLat
+= tBURST
;
1239 totQLat
+= cmd_at
- dram_pkt
->entryTime
;
1244 bytesWritten
+= burstSize
;
1245 perBankWrBursts
[dram_pkt
->bankId
]++;
1250 DRAMCtrl::processNextReqEvent()
1253 for (auto r
: ranks
) {
1254 if (!r
->isAvailable()) {
1255 // rank is busy refreshing
1258 // let the rank know that if it was waiting to drain, it
1259 // is now done and ready to proceed
1260 r
->checkDrainDone();
1264 if (busyRanks
== ranksPerChannel
) {
1265 // if all ranks are refreshing wait for them to finish
1266 // and stall this state machine without taking any further
1267 // action, and do not schedule a new nextReqEvent
1271 // pre-emptively set to false. Overwrite if in READ_TO_WRITE
1272 // or WRITE_TO_READ state
1273 bool switched_cmd_type
= false;
1274 if (busState
== READ_TO_WRITE
) {
1275 DPRINTF(DRAM
, "Switching to writes after %d reads with %d reads "
1276 "waiting\n", readsThisTime
, readQueue
.size());
1278 // sample and reset the read-related stats as we are now
1279 // transitioning to writes, and all reads are done
1280 rdPerTurnAround
.sample(readsThisTime
);
1283 // now proceed to do the actual writes
1285 switched_cmd_type
= true;
1286 } else if (busState
== WRITE_TO_READ
) {
1287 DPRINTF(DRAM
, "Switching to reads after %d writes with %d writes "
1288 "waiting\n", writesThisTime
, writeQueue
.size());
1290 wrPerTurnAround
.sample(writesThisTime
);
1294 switched_cmd_type
= true;
1297 // when we get here it is either a read or a write
1298 if (busState
== READ
) {
1300 // track if we should switch or not
1301 bool switch_to_writes
= false;
1303 if (readQueue
.empty()) {
1304 // In the case there is no read request to go next,
1305 // trigger writes if we have passed the low threshold (or
1306 // if we are draining)
1307 if (!writeQueue
.empty() &&
1308 (drainManager
|| writeQueue
.size() > writeLowThreshold
)) {
1310 switch_to_writes
= true;
1312 // check if we are drained
1313 if (respQueue
.empty () && drainManager
) {
1314 DPRINTF(Drain
, "DRAM controller done draining\n");
1315 drainManager
->signalDrainDone();
1316 drainManager
= NULL
;
1319 // nothing to do, not even any point in scheduling an
1320 // event for the next request
1324 // bool to check if there is a read to a free rank
1325 bool found_read
= false;
1327 // Figure out which read request goes next, and move it to the
1328 // front of the read queue
1329 found_read
= chooseNext(readQueue
, switched_cmd_type
);
1331 // if no read to an available rank is found then return
1332 // at this point. There could be writes to the available ranks
1333 // which are above the required threshold. However, to
1334 // avoid adding more complexity to the code, return and wait
1335 // for a refresh event to kick things into action again.
1339 DRAMPacket
* dram_pkt
= readQueue
.front();
1340 assert(dram_pkt
->rankRef
.isAvailable());
1341 // here we get a bit creative and shift the bus busy time not
1342 // just the tWTR, but also a CAS latency to capture the fact
1343 // that we are allowed to prepare a new bank, but not issue a
1344 // read command until after tWTR, in essence we capture a
1345 // bubble on the data bus that is tWTR + tCL
1346 if (switched_cmd_type
&& dram_pkt
->rank
== activeRank
) {
1347 busBusyUntil
+= tWTR
+ tCL
;
1350 doDRAMAccess(dram_pkt
);
1352 // At this point we're done dealing with the request
1353 readQueue
.pop_front();
1356 assert(dram_pkt
->size
<= burstSize
);
1357 assert(dram_pkt
->readyTime
>= curTick());
1359 // Insert into response queue. It will be sent back to the
1360 // requestor at its readyTime
1361 if (respQueue
.empty()) {
1362 assert(!respondEvent
.scheduled());
1363 schedule(respondEvent
, dram_pkt
->readyTime
);
1365 assert(respQueue
.back()->readyTime
<= dram_pkt
->readyTime
);
1366 assert(respondEvent
.scheduled());
1369 respQueue
.push_back(dram_pkt
);
1371 // we have so many writes that we have to transition
1372 if (writeQueue
.size() > writeHighThreshold
) {
1373 switch_to_writes
= true;
1377 // switching to writes, either because the read queue is empty
1378 // and the writes have passed the low threshold (or we are
1379 // draining), or because the writes hit the hight threshold
1380 if (switch_to_writes
) {
1381 // transition to writing
1382 busState
= READ_TO_WRITE
;
1385 // bool to check if write to free rank is found
1386 bool found_write
= false;
1388 found_write
= chooseNext(writeQueue
, switched_cmd_type
);
1390 // if no writes to an available rank are found then return.
1391 // There could be reads to the available ranks. However, to avoid
1392 // adding more complexity to the code, return at this point and wait
1393 // for a refresh event to kick things into action again.
1397 DRAMPacket
* dram_pkt
= writeQueue
.front();
1398 assert(dram_pkt
->rankRef
.isAvailable());
1400 assert(dram_pkt
->size
<= burstSize
);
1402 // add a bubble to the data bus, as defined by the
1403 // tRTW when access is to the same rank as previous burst
1404 // Different rank timing is handled with tCS, which is
1405 // applied to colAllowedAt
1406 if (switched_cmd_type
&& dram_pkt
->rank
== activeRank
) {
1407 busBusyUntil
+= tRTW
;
1410 doDRAMAccess(dram_pkt
);
1412 writeQueue
.pop_front();
1415 // If we emptied the write queue, or got sufficiently below the
1416 // threshold (using the minWritesPerSwitch as the hysteresis) and
1417 // are not draining, or we have reads waiting and have done enough
1418 // writes, then switch to reads.
1419 if (writeQueue
.empty() ||
1420 (writeQueue
.size() + minWritesPerSwitch
< writeLowThreshold
&&
1422 (!readQueue
.empty() && writesThisTime
>= minWritesPerSwitch
)) {
1423 // turn the bus back around for reads again
1424 busState
= WRITE_TO_READ
;
1426 // note that the we switch back to reads also in the idle
1427 // case, which eventually will check for any draining and
1428 // also pause any further scheduling if there is really
1432 // It is possible that a refresh to another rank kicks things back into
1433 // action before reaching this point.
1434 if (!nextReqEvent
.scheduled())
1435 schedule(nextReqEvent
, std::max(nextReqTime
, curTick()));
1437 // If there is space available and we have writes waiting then let
1438 // them retry. This is done here to ensure that the retry does not
1439 // cause a nextReqEvent to be scheduled before we do so as part of
1440 // the next request processing
1441 if (retryWrReq
&& writeQueue
.size() < writeBufferSize
) {
1448 DRAMCtrl::minBankPrep(const deque
<DRAMPacket
*>& queue
,
1449 bool switched_cmd_type
) const
1451 uint64_t bank_mask
= 0;
1452 Tick min_act_at
= MaxTick
;
1454 uint64_t bank_mask_same_rank
= 0;
1455 Tick min_act_at_same_rank
= MaxTick
;
1457 // Give precedence to commands that access same rank as previous command
1458 bool same_rank_match
= false;
1460 // determine if we have queued transactions targetting the
1462 vector
<bool> got_waiting(ranksPerChannel
* banksPerRank
, false);
1463 for (const auto& p
: queue
) {
1464 if(p
->rankRef
.isAvailable())
1465 got_waiting
[p
->bankId
] = true;
1468 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1469 for (int j
= 0; j
< banksPerRank
; j
++) {
1470 uint16_t bank_id
= i
* banksPerRank
+ j
;
1472 // if we have waiting requests for the bank, and it is
1473 // amongst the first available, update the mask
1474 if (got_waiting
[bank_id
]) {
1475 // make sure this rank is not currently refreshing.
1476 assert(ranks
[i
]->isAvailable());
1477 // simplistic approximation of when the bank can issue
1478 // an activate, ignoring any rank-to-rank switching
1479 // cost in this calculation
1480 Tick act_at
= ranks
[i
]->banks
[j
].openRow
== Bank::NO_ROW
?
1481 ranks
[i
]->banks
[j
].actAllowedAt
:
1482 std::max(ranks
[i
]->banks
[j
].preAllowedAt
, curTick()) + tRP
;
1484 // prioritize commands that access the
1485 // same rank as previous burst
1486 // Calculate bank mask separately for the case and
1487 // evaluate after loop iterations complete
1488 if (i
== activeRank
&& ranksPerChannel
> 1) {
1489 if (act_at
<= min_act_at_same_rank
) {
1490 // reset same rank bank mask if new minimum is found
1491 // and previous minimum could not immediately send ACT
1492 if (act_at
< min_act_at_same_rank
&&
1493 min_act_at_same_rank
> curTick())
1494 bank_mask_same_rank
= 0;
1496 // Set flag indicating that a same rank
1497 // opportunity was found
1498 same_rank_match
= true;
1500 // set the bit corresponding to the available bank
1501 replaceBits(bank_mask_same_rank
, bank_id
, bank_id
, 1);
1502 min_act_at_same_rank
= act_at
;
1505 if (act_at
<= min_act_at
) {
1506 // reset bank mask if new minimum is found
1507 // and either previous minimum could not immediately send ACT
1508 if (act_at
< min_act_at
&& min_act_at
> curTick())
1510 // set the bit corresponding to the available bank
1511 replaceBits(bank_mask
, bank_id
, bank_id
, 1);
1512 min_act_at
= act_at
;
1519 // Determine the earliest time when the next burst can issue based
1520 // on the current busBusyUntil delay.
1521 // Offset by tRCD to correlate with ACT timing variables
1522 Tick min_cmd_at
= busBusyUntil
- tCL
- tRCD
;
1524 // if we have multiple ranks and all
1525 // waiting packets are accessing a rank which was previously active
1526 // then bank_mask_same_rank will be set to a value while bank_mask will
1527 // remain 0. In this case, the function should return the value of
1528 // bank_mask_same_rank.
1529 // else if waiting packets access a rank which was previously active and
1530 // other ranks, prioritize same rank accesses that can issue B2B
1531 // Only optimize for same ranks when the command type
1532 // does not change; do not want to unnecessarily incur tWTR
1534 // Resulting FCFS prioritization Order is:
1535 // 1) Commands that access the same rank as previous burst
1536 // and can prep the bank seamlessly.
1537 // 2) Commands (any rank) with earliest bank prep
1538 if ((bank_mask
== 0) || (!switched_cmd_type
&& same_rank_match
&&
1539 min_act_at_same_rank
<= min_cmd_at
)) {
1540 bank_mask
= bank_mask_same_rank
;
1546 DRAMCtrl::Rank::Rank(DRAMCtrl
& _memory
, const DRAMCtrlParams
* _p
)
1547 : EventManager(&_memory
), memory(_memory
),
1548 pwrStateTrans(PWR_IDLE
), pwrState(PWR_IDLE
), pwrStateTick(0),
1549 refreshState(REF_IDLE
), refreshDueAt(0),
1550 power(_p
, false), numBanksActive(0),
1551 activateEvent(*this), prechargeEvent(*this),
1552 refreshEvent(*this), powerEvent(*this)
1556 DRAMCtrl::Rank::startup(Tick ref_tick
)
1558 assert(ref_tick
> curTick());
1560 pwrStateTick
= curTick();
1562 // kick off the refresh, and give ourselves enough time to
1564 schedule(refreshEvent
, ref_tick
);
1568 DRAMCtrl::Rank::suspend()
1570 deschedule(refreshEvent
);
1574 DRAMCtrl::Rank::checkDrainDone()
1576 // if this rank was waiting to drain it is now able to proceed to
1578 if (refreshState
== REF_DRAIN
) {
1579 DPRINTF(DRAM
, "Refresh drain done, now precharging\n");
1581 refreshState
= REF_PRE
;
1583 // hand control back to the refresh event loop
1584 schedule(refreshEvent
, curTick());
1589 DRAMCtrl::Rank::processActivateEvent()
1591 // we should transition to the active state as soon as any bank is active
1592 if (pwrState
!= PWR_ACT
)
1593 // note that at this point numBanksActive could be back at
1594 // zero again due to a precharge scheduled in the future
1595 schedulePowerEvent(PWR_ACT
, curTick());
1599 DRAMCtrl::Rank::processPrechargeEvent()
1601 // if we reached zero, then special conditions apply as we track
1602 // if all banks are precharged for the power models
1603 if (numBanksActive
== 0) {
1604 // we should transition to the idle state when the last bank
1606 schedulePowerEvent(PWR_IDLE
, curTick());
1611 DRAMCtrl::Rank::processRefreshEvent()
1613 // when first preparing the refresh, remember when it was due
1614 if (refreshState
== REF_IDLE
) {
1615 // remember when the refresh is due
1616 refreshDueAt
= curTick();
1619 refreshState
= REF_DRAIN
;
1621 DPRINTF(DRAM
, "Refresh due\n");
1624 // let any scheduled read or write to the same rank go ahead,
1625 // after which it will
1626 // hand control back to this event loop
1627 if (refreshState
== REF_DRAIN
) {
1628 // if a request is at the moment being handled and this request is
1629 // accessing the current rank then wait for it to finish
1630 if ((rank
== memory
.activeRank
)
1631 && (memory
.nextReqEvent
.scheduled())) {
1632 // hand control over to the request loop until it is
1634 DPRINTF(DRAM
, "Refresh awaiting draining\n");
1638 refreshState
= REF_PRE
;
1642 // at this point, ensure that all banks are precharged
1643 if (refreshState
== REF_PRE
) {
1644 // precharge any active bank if we are not already in the idle
1646 if (pwrState
!= PWR_IDLE
) {
1647 // at the moment, we use a precharge all even if there is
1648 // only a single bank open
1649 DPRINTF(DRAM
, "Precharging all\n");
1651 // first determine when we can precharge
1652 Tick pre_at
= curTick();
1654 for (auto &b
: banks
) {
1655 // respect both causality and any existing bank
1656 // constraints, some banks could already have a
1657 // (auto) precharge scheduled
1658 pre_at
= std::max(b
.preAllowedAt
, pre_at
);
1661 // make sure all banks per rank are precharged, and for those that
1662 // already are, update their availability
1663 Tick act_allowed_at
= pre_at
+ memory
.tRP
;
1665 for (auto &b
: banks
) {
1666 if (b
.openRow
!= Bank::NO_ROW
) {
1667 memory
.prechargeBank(*this, b
, pre_at
, false);
1669 b
.actAllowedAt
= std::max(b
.actAllowedAt
, act_allowed_at
);
1670 b
.preAllowedAt
= std::max(b
.preAllowedAt
, pre_at
);
1674 // precharge all banks in rank
1675 power
.powerlib
.doCommand(MemCommand::PREA
, 0,
1676 divCeil(pre_at
, memory
.tCK
) -
1677 memory
.timeStampOffset
);
1679 DPRINTF(DRAMPower
, "%llu,PREA,0,%d\n",
1680 divCeil(pre_at
, memory
.tCK
) -
1681 memory
.timeStampOffset
, rank
);
1683 DPRINTF(DRAM
, "All banks already precharged, starting refresh\n");
1685 // go ahead and kick the power state machine into gear if
1686 // we are already idle
1687 schedulePowerEvent(PWR_REF
, curTick());
1690 refreshState
= REF_RUN
;
1691 assert(numBanksActive
== 0);
1693 // wait for all banks to be precharged, at which point the
1694 // power state machine will transition to the idle state, and
1695 // automatically move to a refresh, at that point it will also
1696 // call this method to get the refresh event loop going again
1700 // last but not least we perform the actual refresh
1701 if (refreshState
== REF_RUN
) {
1702 // should never get here with any banks active
1703 assert(numBanksActive
== 0);
1704 assert(pwrState
== PWR_REF
);
1706 Tick ref_done_at
= curTick() + memory
.tRFC
;
1708 for (auto &b
: banks
) {
1709 b
.actAllowedAt
= ref_done_at
;
1712 // at the moment this affects all ranks
1713 power
.powerlib
.doCommand(MemCommand::REF
, 0,
1714 divCeil(curTick(), memory
.tCK
) -
1715 memory
.timeStampOffset
);
1717 // at the moment sort the list of commands and update the counters
1718 // for DRAMPower libray when doing a refresh
1719 sort(power
.powerlib
.cmdList
.begin(),
1720 power
.powerlib
.cmdList
.end(), DRAMCtrl::sortTime
);
1722 // update the counters for DRAMPower, passing false to
1723 // indicate that this is not the last command in the
1724 // list. DRAMPower requires this information for the
1725 // correct calculation of the background energy at the end
1726 // of the simulation. Ideally we would want to call this
1727 // function with true once at the end of the
1728 // simulation. However, the discarded energy is extremly
1729 // small and does not effect the final results.
1730 power
.powerlib
.updateCounters(false);
1732 // call the energy function
1733 power
.powerlib
.calcEnergy();
1738 DPRINTF(DRAMPower
, "%llu,REF,0,%d\n", divCeil(curTick(), memory
.tCK
) -
1739 memory
.timeStampOffset
, rank
);
1741 // make sure we did not wait so long that we cannot make up
1743 if (refreshDueAt
+ memory
.tREFI
< ref_done_at
) {
1744 fatal("Refresh was delayed so long we cannot catch up\n");
1747 // compensate for the delay in actually performing the refresh
1748 // when scheduling the next one
1749 schedule(refreshEvent
, refreshDueAt
+ memory
.tREFI
- memory
.tRP
);
1751 assert(!powerEvent
.scheduled());
1753 // move to the idle power state once the refresh is done, this
1754 // will also move the refresh state machine to the refresh
1756 schedulePowerEvent(PWR_IDLE
, ref_done_at
);
1758 DPRINTF(DRAMState
, "Refresh done at %llu and next refresh at %llu\n",
1759 ref_done_at
, refreshDueAt
+ memory
.tREFI
);
1764 DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state
, Tick tick
)
1766 // respect causality
1767 assert(tick
>= curTick());
1769 if (!powerEvent
.scheduled()) {
1770 DPRINTF(DRAMState
, "Scheduling power event at %llu to state %d\n",
1773 // insert the new transition
1774 pwrStateTrans
= pwr_state
;
1776 schedule(powerEvent
, tick
);
1778 panic("Scheduled power event at %llu to state %d, "
1779 "with scheduled event at %llu to %d\n", tick
, pwr_state
,
1780 powerEvent
.when(), pwrStateTrans
);
1785 DRAMCtrl::Rank::processPowerEvent()
1787 // remember where we were, and for how long
1788 Tick duration
= curTick() - pwrStateTick
;
1789 PowerState prev_state
= pwrState
;
1791 // update the accounting
1792 pwrStateTime
[prev_state
] += duration
;
1794 pwrState
= pwrStateTrans
;
1795 pwrStateTick
= curTick();
1797 if (pwrState
== PWR_IDLE
) {
1798 DPRINTF(DRAMState
, "All banks precharged\n");
1800 // if we were refreshing, make sure we start scheduling requests again
1801 if (prev_state
== PWR_REF
) {
1802 DPRINTF(DRAMState
, "Was refreshing for %llu ticks\n", duration
);
1803 assert(pwrState
== PWR_IDLE
);
1805 // kick things into action again
1806 refreshState
= REF_IDLE
;
1807 // a request event could be already scheduled by the state
1808 // machine of the other rank
1809 if (!memory
.nextReqEvent
.scheduled())
1810 schedule(memory
.nextReqEvent
, curTick());
1812 assert(prev_state
== PWR_ACT
);
1814 // if we have a pending refresh, and are now moving to
1815 // the idle state, direclty transition to a refresh
1816 if (refreshState
== REF_RUN
) {
1817 // there should be nothing waiting at this point
1818 assert(!powerEvent
.scheduled());
1820 // update the state in zero time and proceed below
1826 // we transition to the refresh state, let the refresh state
1827 // machine know of this state update and let it deal with the
1828 // scheduling of the next power state transition as well as the
1829 // following refresh
1830 if (pwrState
== PWR_REF
) {
1831 DPRINTF(DRAMState
, "Refreshing\n");
1832 // kick the refresh event loop into action again, and that
1833 // in turn will schedule a transition to the idle power
1834 // state once the refresh is done
1835 assert(refreshState
== REF_RUN
);
1836 processRefreshEvent();
1841 DRAMCtrl::Rank::updatePowerStats()
1843 // Get the energy and power from DRAMPower
1844 Data::MemoryPowerModel::Energy energy
=
1845 power
.powerlib
.getEnergy();
1846 Data::MemoryPowerModel::Power rank_power
=
1847 power
.powerlib
.getPower();
1849 actEnergy
= energy
.act_energy
* memory
.devicesPerRank
;
1850 preEnergy
= energy
.pre_energy
* memory
.devicesPerRank
;
1851 readEnergy
= energy
.read_energy
* memory
.devicesPerRank
;
1852 writeEnergy
= energy
.write_energy
* memory
.devicesPerRank
;
1853 refreshEnergy
= energy
.ref_energy
* memory
.devicesPerRank
;
1854 actBackEnergy
= energy
.act_stdby_energy
* memory
.devicesPerRank
;
1855 preBackEnergy
= energy
.pre_stdby_energy
* memory
.devicesPerRank
;
1856 totalEnergy
= energy
.total_energy
* memory
.devicesPerRank
;
1857 averagePower
= rank_power
.average_power
* memory
.devicesPerRank
;
1861 DRAMCtrl::Rank::regStats()
1863 using namespace Stats
;
1867 .name(name() + ".memoryStateTime")
1868 .desc("Time in different power states");
1869 pwrStateTime
.subname(0, "IDLE");
1870 pwrStateTime
.subname(1, "REF");
1871 pwrStateTime
.subname(2, "PRE_PDN");
1872 pwrStateTime
.subname(3, "ACT");
1873 pwrStateTime
.subname(4, "ACT_PDN");
1876 .name(name() + ".actEnergy")
1877 .desc("Energy for activate commands per rank (pJ)");
1880 .name(name() + ".preEnergy")
1881 .desc("Energy for precharge commands per rank (pJ)");
1884 .name(name() + ".readEnergy")
1885 .desc("Energy for read commands per rank (pJ)");
1888 .name(name() + ".writeEnergy")
1889 .desc("Energy for write commands per rank (pJ)");
1892 .name(name() + ".refreshEnergy")
1893 .desc("Energy for refresh commands per rank (pJ)");
1896 .name(name() + ".actBackEnergy")
1897 .desc("Energy for active background per rank (pJ)");
1900 .name(name() + ".preBackEnergy")
1901 .desc("Energy for precharge background per rank (pJ)");
1904 .name(name() + ".totalEnergy")
1905 .desc("Total energy per rank (pJ)");
1908 .name(name() + ".averagePower")
1909 .desc("Core power per rank (mW)");
1912 DRAMCtrl::regStats()
1914 using namespace Stats
;
1916 AbstractMemory::regStats();
1918 for (auto r
: ranks
) {
1923 .name(name() + ".readReqs")
1924 .desc("Number of read requests accepted");
1927 .name(name() + ".writeReqs")
1928 .desc("Number of write requests accepted");
1931 .name(name() + ".readBursts")
1932 .desc("Number of DRAM read bursts, "
1933 "including those serviced by the write queue");
1936 .name(name() + ".writeBursts")
1937 .desc("Number of DRAM write bursts, "
1938 "including those merged in the write queue");
1941 .name(name() + ".servicedByWrQ")
1942 .desc("Number of DRAM read bursts serviced by the write queue");
1945 .name(name() + ".mergedWrBursts")
1946 .desc("Number of DRAM write bursts merged with an existing one");
1949 .name(name() + ".neitherReadNorWriteReqs")
1950 .desc("Number of requests that are neither read nor write");
1953 .init(banksPerRank
* ranksPerChannel
)
1954 .name(name() + ".perBankRdBursts")
1955 .desc("Per bank write bursts");
1958 .init(banksPerRank
* ranksPerChannel
)
1959 .name(name() + ".perBankWrBursts")
1960 .desc("Per bank write bursts");
1963 .name(name() + ".avgRdQLen")
1964 .desc("Average read queue length when enqueuing")
1968 .name(name() + ".avgWrQLen")
1969 .desc("Average write queue length when enqueuing")
1973 .name(name() + ".totQLat")
1974 .desc("Total ticks spent queuing");
1977 .name(name() + ".totBusLat")
1978 .desc("Total ticks spent in databus transfers");
1981 .name(name() + ".totMemAccLat")
1982 .desc("Total ticks spent from burst creation until serviced "
1986 .name(name() + ".avgQLat")
1987 .desc("Average queueing delay per DRAM burst")
1990 avgQLat
= totQLat
/ (readBursts
- servicedByWrQ
);
1993 .name(name() + ".avgBusLat")
1994 .desc("Average bus latency per DRAM burst")
1997 avgBusLat
= totBusLat
/ (readBursts
- servicedByWrQ
);
2000 .name(name() + ".avgMemAccLat")
2001 .desc("Average memory access latency per DRAM burst")
2004 avgMemAccLat
= totMemAccLat
/ (readBursts
- servicedByWrQ
);
2007 .name(name() + ".numRdRetry")
2008 .desc("Number of times read queue was full causing retry");
2011 .name(name() + ".numWrRetry")
2012 .desc("Number of times write queue was full causing retry");
2015 .name(name() + ".readRowHits")
2016 .desc("Number of row buffer hits during reads");
2019 .name(name() + ".writeRowHits")
2020 .desc("Number of row buffer hits during writes");
2023 .name(name() + ".readRowHitRate")
2024 .desc("Row buffer hit rate for reads")
2027 readRowHitRate
= (readRowHits
/ (readBursts
- servicedByWrQ
)) * 100;
2030 .name(name() + ".writeRowHitRate")
2031 .desc("Row buffer hit rate for writes")
2034 writeRowHitRate
= (writeRowHits
/ (writeBursts
- mergedWrBursts
)) * 100;
2037 .init(ceilLog2(burstSize
) + 1)
2038 .name(name() + ".readPktSize")
2039 .desc("Read request sizes (log2)");
2042 .init(ceilLog2(burstSize
) + 1)
2043 .name(name() + ".writePktSize")
2044 .desc("Write request sizes (log2)");
2047 .init(readBufferSize
)
2048 .name(name() + ".rdQLenPdf")
2049 .desc("What read queue length does an incoming req see");
2052 .init(writeBufferSize
)
2053 .name(name() + ".wrQLenPdf")
2054 .desc("What write queue length does an incoming req see");
2057 .init(maxAccessesPerRow
)
2058 .name(name() + ".bytesPerActivate")
2059 .desc("Bytes accessed per row activation")
2063 .init(readBufferSize
)
2064 .name(name() + ".rdPerTurnAround")
2065 .desc("Reads before turning the bus around for writes")
2069 .init(writeBufferSize
)
2070 .name(name() + ".wrPerTurnAround")
2071 .desc("Writes before turning the bus around for reads")
2075 .name(name() + ".bytesReadDRAM")
2076 .desc("Total number of bytes read from DRAM");
2079 .name(name() + ".bytesReadWrQ")
2080 .desc("Total number of bytes read from write queue");
2083 .name(name() + ".bytesWritten")
2084 .desc("Total number of bytes written to DRAM");
2087 .name(name() + ".bytesReadSys")
2088 .desc("Total read bytes from the system interface side");
2091 .name(name() + ".bytesWrittenSys")
2092 .desc("Total written bytes from the system interface side");
2095 .name(name() + ".avgRdBW")
2096 .desc("Average DRAM read bandwidth in MiByte/s")
2099 avgRdBW
= (bytesReadDRAM
/ 1000000) / simSeconds
;
2102 .name(name() + ".avgWrBW")
2103 .desc("Average achieved write bandwidth in MiByte/s")
2106 avgWrBW
= (bytesWritten
/ 1000000) / simSeconds
;
2109 .name(name() + ".avgRdBWSys")
2110 .desc("Average system read bandwidth in MiByte/s")
2113 avgRdBWSys
= (bytesReadSys
/ 1000000) / simSeconds
;
2116 .name(name() + ".avgWrBWSys")
2117 .desc("Average system write bandwidth in MiByte/s")
2120 avgWrBWSys
= (bytesWrittenSys
/ 1000000) / simSeconds
;
2123 .name(name() + ".peakBW")
2124 .desc("Theoretical peak bandwidth in MiByte/s")
2127 peakBW
= (SimClock::Frequency
/ tBURST
) * burstSize
/ 1000000;
2130 .name(name() + ".busUtil")
2131 .desc("Data bus utilization in percentage")
2133 busUtil
= (avgRdBW
+ avgWrBW
) / peakBW
* 100;
2136 .name(name() + ".totGap")
2137 .desc("Total gap between requests");
2140 .name(name() + ".avgGap")
2141 .desc("Average gap between requests")
2144 avgGap
= totGap
/ (readReqs
+ writeReqs
);
2146 // Stats for DRAM Power calculation based on Micron datasheet
2148 .name(name() + ".busUtilRead")
2149 .desc("Data bus utilization in percentage for reads")
2152 busUtilRead
= avgRdBW
/ peakBW
* 100;
2155 .name(name() + ".busUtilWrite")
2156 .desc("Data bus utilization in percentage for writes")
2159 busUtilWrite
= avgWrBW
/ peakBW
* 100;
2162 .name(name() + ".pageHitRate")
2163 .desc("Row buffer hit rate, read and write combined")
2166 pageHitRate
= (writeRowHits
+ readRowHits
) /
2167 (writeBursts
- mergedWrBursts
+ readBursts
- servicedByWrQ
) * 100;
2171 DRAMCtrl::recvFunctional(PacketPtr pkt
)
2173 // rely on the abstract memory
2174 functionalAccess(pkt
);
2178 DRAMCtrl::getSlavePort(const string
&if_name
, PortID idx
)
2180 if (if_name
!= "port") {
2181 return MemObject::getSlavePort(if_name
, idx
);
2188 DRAMCtrl::drain(DrainManager
*dm
)
2190 unsigned int count
= port
.drain(dm
);
2192 // if there is anything in any of our internal queues, keep track
2194 if (!(writeQueue
.empty() && readQueue
.empty() &&
2195 respQueue
.empty())) {
2196 DPRINTF(Drain
, "DRAM controller not drained, write: %d, read: %d,"
2197 " resp: %d\n", writeQueue
.size(), readQueue
.size(),
2202 // the only part that is not drained automatically over time
2203 // is the write queue, thus kick things into action if needed
2204 if (!writeQueue
.empty() && !nextReqEvent
.scheduled()) {
2205 schedule(nextReqEvent
, curTick());
2210 setDrainState(Drainable::Draining
);
2212 setDrainState(Drainable::Drained
);
2217 DRAMCtrl::drainResume()
2219 if (!isTimingMode
&& system()->isTimingMode()) {
2220 // if we switched to timing mode, kick things into action,
2221 // and behave as if we restored from a checkpoint
2223 } else if (isTimingMode
&& !system()->isTimingMode()) {
2224 // if we switch from timing mode, stop the refresh events to
2225 // not cause issues with KVM
2226 for (auto r
: ranks
) {
2232 isTimingMode
= system()->isTimingMode();
2235 DRAMCtrl::MemoryPort::MemoryPort(const std::string
& name
, DRAMCtrl
& _memory
)
2236 : QueuedSlavePort(name
, &_memory
, queue
), queue(_memory
, *this),
2241 DRAMCtrl::MemoryPort::getAddrRanges() const
2243 AddrRangeList ranges
;
2244 ranges
.push_back(memory
.getAddrRange());
2249 DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt
)
2251 pkt
->pushLabel(memory
.name());
2253 if (!queue
.checkFunctional(pkt
)) {
2254 // Default implementation of SimpleTimingPort::recvFunctional()
2255 // calls recvAtomic() and throws away the latency; we can save a
2256 // little here by just not calculating the latency.
2257 memory
.recvFunctional(pkt
);
2264 DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt
)
2266 return memory
.recvAtomic(pkt
);
2270 DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt
)
2272 // pass it to the memory controller
2273 return memory
.recvTimingReq(pkt
);
2277 DRAMCtrlParams::create()
2279 return new DRAMCtrl(this);