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
.interleaved() ? range
.granularity() / burstSize
: 1),
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 // some basic sanity checks
157 if (tREFI
<= tRP
|| tREFI
<= tRFC
) {
158 fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
162 // basic bank group architecture checks ->
164 // must have at least one bank per bank group
165 if (bankGroupsPerRank
> banksPerRank
) {
166 fatal("banks per rank (%d) must be equal to or larger than "
167 "banks groups per rank (%d)\n",
168 banksPerRank
, bankGroupsPerRank
);
170 // must have same number of banks in each bank group
171 if ((banksPerRank
% bankGroupsPerRank
) != 0) {
172 fatal("Banks per rank (%d) must be evenly divisible by bank groups "
173 "per rank (%d) for equal banks per bank group\n",
174 banksPerRank
, bankGroupsPerRank
);
176 // tCCD_L should be greater than minimal, back-to-back burst delay
177 if (tCCD_L
<= tBURST
) {
178 fatal("tCCD_L (%d) should be larger than tBURST (%d) when "
179 "bank groups per rank (%d) is greater than 1\n",
180 tCCD_L
, tBURST
, bankGroupsPerRank
);
182 // tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
183 // some datasheets might specify it equal to tRRD
185 fatal("tRRD_L (%d) should be larger than tRRD (%d) when "
186 "bank groups per rank (%d) is greater than 1\n",
187 tRRD_L
, tRRD
, bankGroupsPerRank
);
196 AbstractMemory::init();
198 if (!port
.isConnected()) {
199 fatal("DRAMCtrl %s is unconnected!\n", name());
201 port
.sendRangeChange();
204 // a bit of sanity checks on the interleaving, save it for here to
205 // ensure that the system pointer is initialised
206 if (range
.interleaved()) {
207 if (channels
!= range
.stripes())
208 fatal("%s has %d interleaved address stripes but %d channel(s)\n",
209 name(), range
.stripes(), channels
);
211 if (addrMapping
== Enums::RoRaBaChCo
) {
212 if (rowBufferSize
!= range
.granularity()) {
213 fatal("Channel interleaving of %s doesn't match RoRaBaChCo "
214 "address map\n", name());
216 } else if (addrMapping
== Enums::RoRaBaCoCh
||
217 addrMapping
== Enums::RoCoRaBaCh
) {
218 // for the interleavings with channel bits in the bottom,
219 // if the system uses a channel striping granularity that
220 // is larger than the DRAM burst size, then map the
221 // sequential accesses within a stripe to a number of
222 // columns in the DRAM, effectively placing some of the
223 // lower-order column bits as the least-significant bits
224 // of the address (above the ones denoting the burst size)
225 assert(columnsPerStripe
>= 1);
227 // channel striping has to be done at a granularity that
228 // is equal or larger to a cache line
229 if (system()->cacheLineSize() > range
.granularity()) {
230 fatal("Channel interleaving of %s must be at least as large "
231 "as the cache line size\n", name());
234 // ...and equal or smaller than the row-buffer size
235 if (rowBufferSize
< range
.granularity()) {
236 fatal("Channel interleaving of %s must be at most as large "
237 "as the row-buffer size\n", name());
239 // this is essentially the check above, so just to be sure
240 assert(columnsPerStripe
<= columnsPerRowBuffer
);
248 // remember the memory system mode of operation
249 isTimingMode
= system()->isTimingMode();
252 // timestamp offset should be in clock cycles for DRAMPower
253 timeStampOffset
= divCeil(curTick(), tCK
);
255 // update the start tick for the precharge accounting to the
257 for (auto r
: ranks
) {
258 r
->startup(curTick() + tREFI
- tRP
);
261 // shift the bus busy time sufficiently far ahead that we never
262 // have to worry about negative values when computing the time for
263 // the next request, this will add an insignificant bubble at the
264 // start of simulation
265 busBusyUntil
= curTick() + tRP
+ tRCD
+ tCL
;
270 DRAMCtrl::recvAtomic(PacketPtr pkt
)
272 DPRINTF(DRAM
, "recvAtomic: %s 0x%x\n", pkt
->cmdString(), pkt
->getAddr());
274 // do the actual memory access and turn the packet into a response
278 if (!pkt
->memInhibitAsserted() && pkt
->hasData()) {
279 // this value is not supposed to be accurate, just enough to
280 // keep things going, mimic a closed page
281 latency
= tRP
+ tRCD
+ tCL
;
287 DRAMCtrl::readQueueFull(unsigned int neededEntries
) const
289 DPRINTF(DRAM
, "Read queue limit %d, current size %d, entries needed %d\n",
290 readBufferSize
, readQueue
.size() + respQueue
.size(),
294 (readQueue
.size() + respQueue
.size() + neededEntries
) > readBufferSize
;
298 DRAMCtrl::writeQueueFull(unsigned int neededEntries
) const
300 DPRINTF(DRAM
, "Write queue limit %d, current size %d, entries needed %d\n",
301 writeBufferSize
, writeQueue
.size(), neededEntries
);
302 return (writeQueue
.size() + neededEntries
) > writeBufferSize
;
305 DRAMCtrl::DRAMPacket
*
306 DRAMCtrl::decodeAddr(PacketPtr pkt
, Addr dramPktAddr
, unsigned size
,
309 // decode the address based on the address mapping scheme, with
310 // Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
311 // channel, respectively
314 // use a 64-bit unsigned during the computations as the row is
315 // always the top bits, and check before creating the DRAMPacket
318 // truncate the address to a DRAM burst, which makes it unique to
319 // a specific column, row, bank, rank and channel
320 Addr addr
= dramPktAddr
/ burstSize
;
322 // we have removed the lowest order address bits that denote the
323 // position within the column
324 if (addrMapping
== Enums::RoRaBaChCo
) {
325 // the lowest order bits denote the column to ensure that
326 // sequential cache lines occupy the same row
327 addr
= addr
/ columnsPerRowBuffer
;
329 // take out the channel part of the address
330 addr
= addr
/ channels
;
332 // after the channel bits, get the bank bits to interleave
334 bank
= addr
% banksPerRank
;
335 addr
= addr
/ banksPerRank
;
337 // after the bank, we get the rank bits which thus interleaves
339 rank
= addr
% ranksPerChannel
;
340 addr
= addr
/ ranksPerChannel
;
342 // lastly, get the row bits
343 row
= addr
% rowsPerBank
;
344 addr
= addr
/ rowsPerBank
;
345 } else if (addrMapping
== Enums::RoRaBaCoCh
) {
346 // take out the lower-order column bits
347 addr
= addr
/ columnsPerStripe
;
349 // take out the channel part of the address
350 addr
= addr
/ channels
;
352 // next, the higher-order column bites
353 addr
= addr
/ (columnsPerRowBuffer
/ columnsPerStripe
);
355 // after the column bits, we get the bank bits to interleave
357 bank
= addr
% banksPerRank
;
358 addr
= addr
/ banksPerRank
;
360 // after the bank, we get the rank bits which thus interleaves
362 rank
= addr
% ranksPerChannel
;
363 addr
= addr
/ ranksPerChannel
;
365 // lastly, get the row bits
366 row
= addr
% rowsPerBank
;
367 addr
= addr
/ rowsPerBank
;
368 } else if (addrMapping
== Enums::RoCoRaBaCh
) {
369 // optimise for closed page mode and utilise maximum
370 // parallelism of the DRAM (at the cost of power)
372 // take out the lower-order column bits
373 addr
= addr
/ columnsPerStripe
;
375 // take out the channel part of the address, not that this has
376 // to match with how accesses are interleaved between the
377 // controllers in the address mapping
378 addr
= addr
/ channels
;
380 // start with the bank bits, as this provides the maximum
381 // opportunity for parallelism between requests
382 bank
= addr
% banksPerRank
;
383 addr
= addr
/ banksPerRank
;
385 // next get the rank bits
386 rank
= addr
% ranksPerChannel
;
387 addr
= addr
/ ranksPerChannel
;
389 // next, the higher-order column bites
390 addr
= addr
/ (columnsPerRowBuffer
/ columnsPerStripe
);
392 // lastly, get the row bits
393 row
= addr
% rowsPerBank
;
394 addr
= addr
/ rowsPerBank
;
396 panic("Unknown address mapping policy chosen!");
398 assert(rank
< ranksPerChannel
);
399 assert(bank
< banksPerRank
);
400 assert(row
< rowsPerBank
);
401 assert(row
< Bank::NO_ROW
);
403 DPRINTF(DRAM
, "Address: %lld Rank %d Bank %d Row %d\n",
404 dramPktAddr
, rank
, bank
, row
);
406 // create the corresponding DRAM packet with the entry time and
407 // ready time set to the current tick, the latter will be updated
409 uint16_t bank_id
= banksPerRank
* rank
+ bank
;
410 return new DRAMPacket(pkt
, isRead
, rank
, bank
, row
, bank_id
, dramPktAddr
,
411 size
, ranks
[rank
]->banks
[bank
], *ranks
[rank
]);
415 DRAMCtrl::addToReadQueue(PacketPtr pkt
, unsigned int pktCount
)
417 // only add to the read queue here. whenever the request is
418 // eventually done, set the readyTime, and call schedule()
419 assert(!pkt
->isWrite());
421 assert(pktCount
!= 0);
423 // if the request size is larger than burst size, the pkt is split into
424 // multiple DRAM packets
425 // Note if the pkt starting address is not aligened to burst size, the
426 // address of first DRAM packet is kept unaliged. Subsequent DRAM packets
427 // are aligned to burst size boundaries. This is to ensure we accurately
428 // check read packets against packets in write queue.
429 Addr addr
= pkt
->getAddr();
430 unsigned pktsServicedByWrQ
= 0;
431 BurstHelper
* burst_helper
= NULL
;
432 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
433 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
434 pkt
->getAddr() + pkt
->getSize()) - addr
;
435 readPktSize
[ceilLog2(size
)]++;
438 // First check write buffer to see if the data is already at
440 bool foundInWrQ
= false;
441 for (auto i
= writeQueue
.begin(); i
!= writeQueue
.end(); ++i
) {
442 // check if the read is subsumed in the write entry we are
444 if ((*i
)->addr
<= addr
&&
445 (addr
+ size
) <= ((*i
)->addr
+ (*i
)->size
)) {
449 DPRINTF(DRAM
, "Read to addr %lld with size %d serviced by "
450 "write queue\n", addr
, size
);
451 bytesReadWrQ
+= burstSize
;
456 // If not found in the write q, make a DRAM packet and
457 // push it onto the read queue
460 // Make the burst helper for split packets
461 if (pktCount
> 1 && burst_helper
== NULL
) {
462 DPRINTF(DRAM
, "Read to addr %lld translates to %d "
463 "dram requests\n", pkt
->getAddr(), pktCount
);
464 burst_helper
= new BurstHelper(pktCount
);
467 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, true);
468 dram_pkt
->burstHelper
= burst_helper
;
470 assert(!readQueueFull(1));
471 rdQLenPdf
[readQueue
.size() + respQueue
.size()]++;
473 DPRINTF(DRAM
, "Adding to read queue\n");
475 readQueue
.push_back(dram_pkt
);
478 avgRdQLen
= readQueue
.size() + respQueue
.size();
481 // Starting address of next dram pkt (aligend to burstSize boundary)
482 addr
= (addr
| (burstSize
- 1)) + 1;
485 // If all packets are serviced by write queue, we send the repsonse back
486 if (pktsServicedByWrQ
== pktCount
) {
487 accessAndRespond(pkt
, frontendLatency
);
491 // Update how many split packets are serviced by write queue
492 if (burst_helper
!= NULL
)
493 burst_helper
->burstsServiced
= pktsServicedByWrQ
;
495 // If we are not already scheduled to get a request out of the
497 if (!nextReqEvent
.scheduled()) {
498 DPRINTF(DRAM
, "Request scheduled immediately\n");
499 schedule(nextReqEvent
, curTick());
504 DRAMCtrl::addToWriteQueue(PacketPtr pkt
, unsigned int pktCount
)
506 // only add to the write queue here. whenever the request is
507 // eventually done, set the readyTime, and call schedule()
508 assert(pkt
->isWrite());
510 // if the request size is larger than burst size, the pkt is split into
511 // multiple DRAM packets
512 Addr addr
= pkt
->getAddr();
513 for (int cnt
= 0; cnt
< pktCount
; ++cnt
) {
514 unsigned size
= std::min((addr
| (burstSize
- 1)) + 1,
515 pkt
->getAddr() + pkt
->getSize()) - addr
;
516 writePktSize
[ceilLog2(size
)]++;
519 // see if we can merge with an existing item in the write
520 // queue and keep track of whether we have merged or not so we
521 // can stop at that point and also avoid enqueueing a new
524 auto w
= writeQueue
.begin();
526 while(!merged
&& w
!= writeQueue
.end()) {
527 // either of the two could be first, if they are the same
528 // it does not matter which way we go
529 if ((*w
)->addr
>= addr
) {
530 // the existing one starts after the new one, figure
531 // out where the new one ends with respect to the
533 if ((addr
+ size
) >= ((*w
)->addr
+ (*w
)->size
)) {
534 // check if the existing one is completely
535 // subsumed in the new one
536 DPRINTF(DRAM
, "Merging write covering existing burst\n");
538 // update both the address and the size
541 } else if ((addr
+ size
) >= (*w
)->addr
&&
542 ((*w
)->addr
+ (*w
)->size
- addr
) <= burstSize
) {
543 // the new one is just before or partially
544 // overlapping with the existing one, and together
545 // they fit within a burst
546 DPRINTF(DRAM
, "Merging write before existing burst\n");
548 // the existing queue item needs to be adjusted with
549 // respect to both address and size
550 (*w
)->size
= (*w
)->addr
+ (*w
)->size
- addr
;
554 // the new one starts after the current one, figure
555 // out where the existing one ends with respect to the
557 if (((*w
)->addr
+ (*w
)->size
) >= (addr
+ size
)) {
558 // check if the new one is completely subsumed in the
560 DPRINTF(DRAM
, "Merging write into existing burst\n");
562 // no adjustments necessary
563 } else if (((*w
)->addr
+ (*w
)->size
) >= addr
&&
564 (addr
+ size
- (*w
)->addr
) <= burstSize
) {
565 // the existing one is just before or partially
566 // overlapping with the new one, and together
567 // they fit within a burst
568 DPRINTF(DRAM
, "Merging write after existing burst\n");
570 // the address is right, and only the size has
572 (*w
)->size
= addr
+ size
- (*w
)->addr
;
578 // if the item was not merged we need to create a new write
581 DRAMPacket
* dram_pkt
= decodeAddr(pkt
, addr
, size
, false);
583 assert(writeQueue
.size() < writeBufferSize
);
584 wrQLenPdf
[writeQueue
.size()]++;
586 DPRINTF(DRAM
, "Adding to write queue\n");
588 writeQueue
.push_back(dram_pkt
);
591 avgWrQLen
= writeQueue
.size();
593 // keep track of the fact that this burst effectively
594 // disappeared as it was merged with an existing one
598 // Starting address of next dram pkt (aligend to burstSize boundary)
599 addr
= (addr
| (burstSize
- 1)) + 1;
602 // we do not wait for the writes to be send to the actual memory,
603 // but instead take responsibility for the consistency here and
604 // snoop the write queue for any upcoming reads
605 // @todo, if a pkt size is larger than burst size, we might need a
606 // different front end latency
607 accessAndRespond(pkt
, frontendLatency
);
609 // If we are not already scheduled to get a request out of the
611 if (!nextReqEvent
.scheduled()) {
612 DPRINTF(DRAM
, "Request scheduled immediately\n");
613 schedule(nextReqEvent
, curTick());
618 DRAMCtrl::printQs() const {
619 DPRINTF(DRAM
, "===READ QUEUE===\n\n");
620 for (auto i
= readQueue
.begin() ; i
!= readQueue
.end() ; ++i
) {
621 DPRINTF(DRAM
, "Read %lu\n", (*i
)->addr
);
623 DPRINTF(DRAM
, "\n===RESP QUEUE===\n\n");
624 for (auto i
= respQueue
.begin() ; i
!= respQueue
.end() ; ++i
) {
625 DPRINTF(DRAM
, "Response %lu\n", (*i
)->addr
);
627 DPRINTF(DRAM
, "\n===WRITE QUEUE===\n\n");
628 for (auto i
= writeQueue
.begin() ; i
!= writeQueue
.end() ; ++i
) {
629 DPRINTF(DRAM
, "Write %lu\n", (*i
)->addr
);
634 DRAMCtrl::recvTimingReq(PacketPtr pkt
)
636 /// @todo temporary hack to deal with memory corruption issues until
637 /// 4-phase transactions are complete
638 for (int x
= 0; x
< pendingDelete
.size(); x
++)
639 delete pendingDelete
[x
];
640 pendingDelete
.clear();
642 // This is where we enter from the outside world
643 DPRINTF(DRAM
, "recvTimingReq: request %s addr %lld size %d\n",
644 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
646 // simply drop inhibited packets for now
647 if (pkt
->memInhibitAsserted()) {
648 DPRINTF(DRAM
, "Inhibited packet -- Dropping it now\n");
649 pendingDelete
.push_back(pkt
);
653 // Calc avg gap between requests
654 if (prevArrival
!= 0) {
655 totGap
+= curTick() - prevArrival
;
657 prevArrival
= curTick();
660 // Find out how many dram packets a pkt translates to
661 // If the burst size is equal or larger than the pkt size, then a pkt
662 // translates to only one dram packet. Otherwise, a pkt translates to
663 // multiple dram packets
664 unsigned size
= pkt
->getSize();
665 unsigned offset
= pkt
->getAddr() & (burstSize
- 1);
666 unsigned int dram_pkt_count
= divCeil(offset
+ size
, burstSize
);
668 // check local buffers and do not accept if full
671 if (readQueueFull(dram_pkt_count
)) {
672 DPRINTF(DRAM
, "Read queue full, not accepting\n");
673 // remember that we have to retry this port
678 addToReadQueue(pkt
, dram_pkt_count
);
680 bytesReadSys
+= size
;
682 } else if (pkt
->isWrite()) {
684 if (writeQueueFull(dram_pkt_count
)) {
685 DPRINTF(DRAM
, "Write queue full, not accepting\n");
686 // remember that we have to retry this port
691 addToWriteQueue(pkt
, dram_pkt_count
);
693 bytesWrittenSys
+= size
;
696 DPRINTF(DRAM
,"Neither read nor write, ignore timing\n");
697 neitherReadNorWrite
++;
698 accessAndRespond(pkt
, 1);
705 DRAMCtrl::processRespondEvent()
708 "processRespondEvent(): Some req has reached its readyTime\n");
710 DRAMPacket
* dram_pkt
= respQueue
.front();
712 if (dram_pkt
->burstHelper
) {
713 // it is a split packet
714 dram_pkt
->burstHelper
->burstsServiced
++;
715 if (dram_pkt
->burstHelper
->burstsServiced
==
716 dram_pkt
->burstHelper
->burstCount
) {
717 // we have now serviced all children packets of a system packet
718 // so we can now respond to the requester
719 // @todo we probably want to have a different front end and back
720 // end latency for split packets
721 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
722 delete dram_pkt
->burstHelper
;
723 dram_pkt
->burstHelper
= NULL
;
726 // it is not a split packet
727 accessAndRespond(dram_pkt
->pkt
, frontendLatency
+ backendLatency
);
730 delete respQueue
.front();
731 respQueue
.pop_front();
733 if (!respQueue
.empty()) {
734 assert(respQueue
.front()->readyTime
>= curTick());
735 assert(!respondEvent
.scheduled());
736 schedule(respondEvent
, respQueue
.front()->readyTime
);
738 // if there is nothing left in any queue, signal a drain
739 if (writeQueue
.empty() && readQueue
.empty() &&
741 DPRINTF(Drain
, "DRAM controller done draining\n");
742 drainManager
->signalDrainDone();
747 // We have made a location in the queue available at this point,
748 // so if there is a read that was forced to wait, retry now
756 DRAMCtrl::chooseNext(std::deque
<DRAMPacket
*>& queue
, bool switched_cmd_type
)
758 // This method does the arbitration between requests. The chosen
759 // packet is simply moved to the head of the queue. The other
760 // methods know that this is the place to look. For example, with
761 // FCFS, this method does nothing
762 assert(!queue
.empty());
764 // bool to indicate if a packet to an available rank is found
765 bool found_packet
= false;
766 if (queue
.size() == 1) {
767 DRAMPacket
* dram_pkt
= queue
.front();
768 // available rank corresponds to state refresh idle
769 if (ranks
[dram_pkt
->rank
]->isAvailable()) {
771 DPRINTF(DRAM
, "Single request, going to a free rank\n");
773 DPRINTF(DRAM
, "Single request, going to a busy rank\n");
778 if (memSchedPolicy
== Enums::fcfs
) {
779 // check if there is a packet going to a free rank
780 for(auto i
= queue
.begin(); i
!= queue
.end() ; ++i
) {
781 DRAMPacket
* dram_pkt
= *i
;
782 if (ranks
[dram_pkt
->rank
]->isAvailable()) {
784 queue
.push_front(dram_pkt
);
789 } else if (memSchedPolicy
== Enums::frfcfs
) {
790 found_packet
= reorderQueue(queue
, switched_cmd_type
);
792 panic("No scheduling policy chosen\n");
797 DRAMCtrl::reorderQueue(std::deque
<DRAMPacket
*>& queue
, bool switched_cmd_type
)
799 // Only determine this when needed
800 uint64_t earliest_banks
= 0;
802 // Search for row hits first, if no row hit is found then schedule the
803 // packet to one of the earliest banks available
804 bool found_packet
= false;
805 bool found_earliest_pkt
= false;
806 bool found_prepped_diff_rank_pkt
= false;
807 auto selected_pkt_it
= queue
.end();
809 for (auto i
= queue
.begin(); i
!= queue
.end() ; ++i
) {
810 DRAMPacket
* dram_pkt
= *i
;
811 const Bank
& bank
= dram_pkt
->bankRef
;
812 // check if rank is busy. If this is the case jump to the next packet
813 // Check if it is a row hit
814 if (dram_pkt
->rankRef
.isAvailable()) {
815 if (bank
.openRow
== dram_pkt
->row
) {
816 if (dram_pkt
->rank
== activeRank
|| switched_cmd_type
) {
817 // FCFS within the hits, giving priority to commands
818 // that access the same rank as the previous burst
819 // to minimize bus turnaround delays
820 // Only give rank prioity when command type is
822 DPRINTF(DRAM
, "Row buffer hit\n");
825 } else if (!found_prepped_diff_rank_pkt
) {
826 // found row hit for command on different rank
829 found_prepped_diff_rank_pkt
= true;
831 } else if (!found_earliest_pkt
& !found_prepped_diff_rank_pkt
) {
832 // packet going to a rank which is currently not waiting for a
833 // refresh, No row hit and
834 // haven't found an entry with a row hit to a new rank
835 if (earliest_banks
== 0)
836 // Determine entries with earliest bank prep delay
837 // Function will give priority to commands that access the
838 // same rank as previous burst and can prep
839 // the bank seamlessly
840 earliest_banks
= minBankPrep(queue
, switched_cmd_type
);
842 // FCFS - Bank is first available bank
843 if (bits(earliest_banks
, dram_pkt
->bankId
,
845 // Remember the packet to be scheduled to one of
846 // the earliest banks available, FCFS amongst the
849 //if the packet found is going to a rank that is currently
850 //not busy then update the found_packet to true
851 found_earliest_pkt
= true;
857 if (selected_pkt_it
!= queue
.end()) {
858 DRAMPacket
* selected_pkt
= *selected_pkt_it
;
859 queue
.erase(selected_pkt_it
);
860 queue
.push_front(selected_pkt
);
867 DRAMCtrl::accessAndRespond(PacketPtr pkt
, Tick static_latency
)
869 DPRINTF(DRAM
, "Responding to Address %lld.. ",pkt
->getAddr());
871 bool needsResponse
= pkt
->needsResponse();
872 // do the actual memory access which also turns the packet into a
876 // turn packet around to go back to requester if response expected
878 // access already turned the packet into a response
879 assert(pkt
->isResponse());
881 // @todo someone should pay for this
882 pkt
->firstWordDelay
= pkt
->lastWordDelay
= 0;
884 // queue the packet in the response queue to be sent out after
885 // the static latency has passed
886 port
.schedTimingResp(pkt
, curTick() + static_latency
);
888 // @todo the packet is going to be deleted, and the DRAMPacket
889 // is still having a pointer to it
890 pendingDelete
.push_back(pkt
);
893 DPRINTF(DRAM
, "Done\n");
899 DRAMCtrl::activateBank(Rank
& rank_ref
, Bank
& bank_ref
,
900 Tick act_tick
, uint32_t row
)
902 assert(rank_ref
.actTicks
.size() == activationLimit
);
904 DPRINTF(DRAM
, "Activate at tick %d\n", act_tick
);
906 // update the open row
907 assert(bank_ref
.openRow
== Bank::NO_ROW
);
908 bank_ref
.openRow
= row
;
910 // start counting anew, this covers both the case when we
911 // auto-precharged, and when this access is forced to
913 bank_ref
.bytesAccessed
= 0;
914 bank_ref
.rowAccesses
= 0;
916 ++rank_ref
.numBanksActive
;
917 assert(rank_ref
.numBanksActive
<= banksPerRank
);
919 DPRINTF(DRAM
, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
920 bank_ref
.bank
, rank_ref
.rank
, act_tick
,
921 ranks
[rank_ref
.rank
]->numBanksActive
);
923 rank_ref
.power
.powerlib
.doCommand(MemCommand::ACT
, bank_ref
.bank
,
924 divCeil(act_tick
, tCK
) -
927 DPRINTF(DRAMPower
, "%llu,ACT,%d,%d\n", divCeil(act_tick
, tCK
) -
928 timeStampOffset
, bank_ref
.bank
, rank_ref
.rank
);
930 // The next access has to respect tRAS for this bank
931 bank_ref
.preAllowedAt
= act_tick
+ tRAS
;
933 // Respect the row-to-column command delay
934 bank_ref
.colAllowedAt
= std::max(act_tick
+ tRCD
, bank_ref
.colAllowedAt
);
936 // start by enforcing tRRD
937 for(int i
= 0; i
< banksPerRank
; i
++) {
938 // next activate to any bank in this rank must not happen
940 if (bankGroupArch
&& (bank_ref
.bankgr
== rank_ref
.banks
[i
].bankgr
)) {
941 // bank group architecture requires longer delays between
942 // ACT commands within the same bank group. Use tRRD_L
944 rank_ref
.banks
[i
].actAllowedAt
= std::max(act_tick
+ tRRD_L
,
945 rank_ref
.banks
[i
].actAllowedAt
);
947 // use shorter tRRD value when either
948 // 1) bank group architecture is not supportted
949 // 2) bank is in a different bank group
950 rank_ref
.banks
[i
].actAllowedAt
= std::max(act_tick
+ tRRD
,
951 rank_ref
.banks
[i
].actAllowedAt
);
955 // next, we deal with tXAW, if the activation limit is disabled
956 // then we directly schedule an activate power event
957 if (!rank_ref
.actTicks
.empty()) {
959 if (rank_ref
.actTicks
.back() &&
960 (act_tick
- rank_ref
.actTicks
.back()) < tXAW
) {
961 panic("Got %d activates in window %d (%llu - %llu) which "
962 "is smaller than %llu\n", activationLimit
, act_tick
-
963 rank_ref
.actTicks
.back(), act_tick
,
964 rank_ref
.actTicks
.back(), tXAW
);
967 // shift the times used for the book keeping, the last element
968 // (highest index) is the oldest one and hence the lowest value
969 rank_ref
.actTicks
.pop_back();
971 // record an new activation (in the future)
972 rank_ref
.actTicks
.push_front(act_tick
);
974 // cannot activate more than X times in time window tXAW, push the
975 // next one (the X + 1'st activate) to be tXAW away from the
976 // oldest in our window of X
977 if (rank_ref
.actTicks
.back() &&
978 (act_tick
- rank_ref
.actTicks
.back()) < tXAW
) {
979 DPRINTF(DRAM
, "Enforcing tXAW with X = %d, next activate "
980 "no earlier than %llu\n", activationLimit
,
981 rank_ref
.actTicks
.back() + tXAW
);
982 for(int j
= 0; j
< banksPerRank
; j
++)
983 // next activate must not happen before end of window
984 rank_ref
.banks
[j
].actAllowedAt
=
985 std::max(rank_ref
.actTicks
.back() + tXAW
,
986 rank_ref
.banks
[j
].actAllowedAt
);
990 // at the point when this activate takes place, make sure we
991 // transition to the active power state
992 if (!rank_ref
.activateEvent
.scheduled())
993 schedule(rank_ref
.activateEvent
, act_tick
);
994 else if (rank_ref
.activateEvent
.when() > act_tick
)
995 // move it sooner in time
996 reschedule(rank_ref
.activateEvent
, act_tick
);
1000 DRAMCtrl::prechargeBank(Rank
& rank_ref
, Bank
& bank
, Tick pre_at
, bool trace
)
1002 // make sure the bank has an open row
1003 assert(bank
.openRow
!= Bank::NO_ROW
);
1005 // sample the bytes per activate here since we are closing
1007 bytesPerActivate
.sample(bank
.bytesAccessed
);
1009 bank
.openRow
= Bank::NO_ROW
;
1011 // no precharge allowed before this one
1012 bank
.preAllowedAt
= pre_at
;
1014 Tick pre_done_at
= pre_at
+ tRP
;
1016 bank
.actAllowedAt
= std::max(bank
.actAllowedAt
, pre_done_at
);
1018 assert(rank_ref
.numBanksActive
!= 0);
1019 --rank_ref
.numBanksActive
;
1021 DPRINTF(DRAM
, "Precharging bank %d, rank %d at tick %lld, now got "
1022 "%d active\n", bank
.bank
, rank_ref
.rank
, pre_at
,
1023 rank_ref
.numBanksActive
);
1027 rank_ref
.power
.powerlib
.doCommand(MemCommand::PRE
, bank
.bank
,
1028 divCeil(pre_at
, tCK
) -
1030 DPRINTF(DRAMPower
, "%llu,PRE,%d,%d\n", divCeil(pre_at
, tCK
) -
1031 timeStampOffset
, bank
.bank
, rank_ref
.rank
);
1033 // if we look at the current number of active banks we might be
1034 // tempted to think the DRAM is now idle, however this can be
1035 // undone by an activate that is scheduled to happen before we
1036 // would have reached the idle state, so schedule an event and
1037 // rather check once we actually make it to the point in time when
1038 // the (last) precharge takes place
1039 if (!rank_ref
.prechargeEvent
.scheduled())
1040 schedule(rank_ref
.prechargeEvent
, pre_done_at
);
1041 else if (rank_ref
.prechargeEvent
.when() < pre_done_at
)
1042 reschedule(rank_ref
.prechargeEvent
, pre_done_at
);
1046 DRAMCtrl::doDRAMAccess(DRAMPacket
* dram_pkt
)
1048 DPRINTF(DRAM
, "Timing access to addr %lld, rank/bank/row %d %d %d\n",
1049 dram_pkt
->addr
, dram_pkt
->rank
, dram_pkt
->bank
, dram_pkt
->row
);
1052 Rank
& rank
= dram_pkt
->rankRef
;
1055 Bank
& bank
= dram_pkt
->bankRef
;
1057 // for the state we need to track if it is a row hit or not
1058 bool row_hit
= true;
1060 // respect any constraints on the command (e.g. tRCD or tCCD)
1061 Tick cmd_at
= std::max(bank
.colAllowedAt
, curTick());
1063 // Determine the access latency and update the bank state
1064 if (bank
.openRow
== dram_pkt
->row
) {
1069 // If there is a page open, precharge it.
1070 if (bank
.openRow
!= Bank::NO_ROW
) {
1071 prechargeBank(rank
, bank
, std::max(bank
.preAllowedAt
, curTick()));
1074 // next we need to account for the delay in activating the
1076 Tick act_tick
= std::max(bank
.actAllowedAt
, curTick());
1078 // Record the activation and deal with all the global timing
1079 // constraints caused be a new activation (tRRD and tXAW)
1080 activateBank(rank
, bank
, act_tick
, dram_pkt
->row
);
1082 // issue the command as early as possible
1083 cmd_at
= bank
.colAllowedAt
;
1086 // we need to wait until the bus is available before we can issue
1088 cmd_at
= std::max(cmd_at
, busBusyUntil
- tCL
);
1090 // update the packet ready time
1091 dram_pkt
->readyTime
= cmd_at
+ tCL
+ tBURST
;
1093 // only one burst can use the bus at any one point in time
1094 assert(dram_pkt
->readyTime
- busBusyUntil
>= tBURST
);
1096 // update the time for the next read/write burst for each
1097 // bank (add a max with tCCD/tCCD_L here)
1099 for(int j
= 0; j
< ranksPerChannel
; j
++) {
1100 for(int i
= 0; i
< banksPerRank
; i
++) {
1101 // next burst to same bank group in this rank must not happen
1102 // before tCCD_L. Different bank group timing requirement is
1103 // tBURST; Add tCS for different ranks
1104 if (dram_pkt
->rank
== j
) {
1105 if (bankGroupArch
&&
1106 (bank
.bankgr
== ranks
[j
]->banks
[i
].bankgr
)) {
1107 // bank group architecture requires longer delays between
1108 // RD/WR burst commands to the same bank group.
1109 // Use tCCD_L in this case
1112 // use tBURST (equivalent to tCCD_S), the shorter
1113 // cas-to-cas delay value, when either:
1114 // 1) bank group architecture is not supportted
1115 // 2) bank is in a different bank group
1119 // different rank is by default in a different bank group
1120 // use tBURST (equivalent to tCCD_S), which is the shorter
1121 // cas-to-cas delay in this case
1122 // Add tCS to account for rank-to-rank bus delay requirements
1123 cmd_dly
= tBURST
+ tCS
;
1125 ranks
[j
]->banks
[i
].colAllowedAt
= std::max(cmd_at
+ cmd_dly
,
1126 ranks
[j
]->banks
[i
].colAllowedAt
);
1130 // Save rank of current access
1131 activeRank
= dram_pkt
->rank
;
1133 // If this is a write, we also need to respect the write recovery
1134 // time before a precharge, in the case of a read, respect the
1135 // read to precharge constraint
1136 bank
.preAllowedAt
= std::max(bank
.preAllowedAt
,
1137 dram_pkt
->isRead
? cmd_at
+ tRTP
:
1138 dram_pkt
->readyTime
+ tWR
);
1140 // increment the bytes accessed and the accesses per row
1141 bank
.bytesAccessed
+= burstSize
;
1144 // if we reached the max, then issue with an auto-precharge
1145 bool auto_precharge
= pageMgmt
== Enums::close
||
1146 bank
.rowAccesses
== maxAccessesPerRow
;
1148 // if we did not hit the limit, we might still want to
1150 if (!auto_precharge
&&
1151 (pageMgmt
== Enums::open_adaptive
||
1152 pageMgmt
== Enums::close_adaptive
)) {
1153 // a twist on the open and close page policies:
1154 // 1) open_adaptive page policy does not blindly keep the
1155 // page open, but close it if there are no row hits, and there
1156 // are bank conflicts in the queue
1157 // 2) close_adaptive page policy does not blindly close the
1158 // page, but closes it only if there are no row hits in the queue.
1159 // In this case, only force an auto precharge when there
1160 // are no same page hits in the queue
1161 bool got_more_hits
= false;
1162 bool got_bank_conflict
= false;
1164 // either look at the read queue or write queue
1165 const deque
<DRAMPacket
*>& queue
= dram_pkt
->isRead
? readQueue
:
1167 auto p
= queue
.begin();
1168 // make sure we are not considering the packet that we are
1169 // currently dealing with (which is the head of the queue)
1172 // keep on looking until we have found required condition or
1174 while (!(got_more_hits
&&
1175 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
)) &&
1177 bool same_rank_bank
= (dram_pkt
->rank
== (*p
)->rank
) &&
1178 (dram_pkt
->bank
== (*p
)->bank
);
1179 bool same_row
= dram_pkt
->row
== (*p
)->row
;
1180 got_more_hits
|= same_rank_bank
&& same_row
;
1181 got_bank_conflict
|= same_rank_bank
&& !same_row
;
1185 // auto pre-charge when either
1186 // 1) open_adaptive policy, we have not got any more hits, and
1187 // have a bank conflict
1188 // 2) close_adaptive policy and we have not got any more hits
1189 auto_precharge
= !got_more_hits
&&
1190 (got_bank_conflict
|| pageMgmt
== Enums::close_adaptive
);
1193 // DRAMPower trace command to be written
1194 std::string mem_cmd
= dram_pkt
->isRead
? "RD" : "WR";
1196 // MemCommand required for DRAMPower library
1197 MemCommand::cmds command
= (mem_cmd
== "RD") ? MemCommand::RD
:
1200 // if this access should use auto-precharge, then we are
1202 if (auto_precharge
) {
1203 // if auto-precharge push a PRE command at the correct tick to the
1204 // list used by DRAMPower library to calculate power
1205 prechargeBank(rank
, bank
, std::max(curTick(), bank
.preAllowedAt
));
1207 DPRINTF(DRAM
, "Auto-precharged bank: %d\n", dram_pkt
->bankId
);
1211 busBusyUntil
= dram_pkt
->readyTime
;
1213 DPRINTF(DRAM
, "Access to %lld, ready at %lld bus busy until %lld.\n",
1214 dram_pkt
->addr
, dram_pkt
->readyTime
, busBusyUntil
);
1216 dram_pkt
->rankRef
.power
.powerlib
.doCommand(command
, dram_pkt
->bank
,
1217 divCeil(cmd_at
, tCK
) -
1220 DPRINTF(DRAMPower
, "%llu,%s,%d,%d\n", divCeil(cmd_at
, tCK
) -
1221 timeStampOffset
, mem_cmd
, dram_pkt
->bank
, dram_pkt
->rank
);
1223 // Update the minimum timing between the requests, this is a
1224 // conservative estimate of when we have to schedule the next
1225 // request to not introduce any unecessary bubbles. In most cases
1226 // we will wake up sooner than we have to.
1227 nextReqTime
= busBusyUntil
- (tRP
+ tRCD
+ tCL
);
1229 // Update the stats and schedule the next request
1230 if (dram_pkt
->isRead
) {
1234 bytesReadDRAM
+= burstSize
;
1235 perBankRdBursts
[dram_pkt
->bankId
]++;
1237 // Update latency stats
1238 totMemAccLat
+= dram_pkt
->readyTime
- dram_pkt
->entryTime
;
1239 totBusLat
+= tBURST
;
1240 totQLat
+= cmd_at
- dram_pkt
->entryTime
;
1245 bytesWritten
+= burstSize
;
1246 perBankWrBursts
[dram_pkt
->bankId
]++;
1251 DRAMCtrl::processNextReqEvent()
1254 for (auto r
: ranks
) {
1255 if (!r
->isAvailable()) {
1256 // rank is busy refreshing
1259 // let the rank know that if it was waiting to drain, it
1260 // is now done and ready to proceed
1261 r
->checkDrainDone();
1265 if (busyRanks
== ranksPerChannel
) {
1266 // if all ranks are refreshing wait for them to finish
1267 // and stall this state machine without taking any further
1268 // action, and do not schedule a new nextReqEvent
1272 // pre-emptively set to false. Overwrite if in READ_TO_WRITE
1273 // or WRITE_TO_READ state
1274 bool switched_cmd_type
= false;
1275 if (busState
== READ_TO_WRITE
) {
1276 DPRINTF(DRAM
, "Switching to writes after %d reads with %d reads "
1277 "waiting\n", readsThisTime
, readQueue
.size());
1279 // sample and reset the read-related stats as we are now
1280 // transitioning to writes, and all reads are done
1281 rdPerTurnAround
.sample(readsThisTime
);
1284 // now proceed to do the actual writes
1286 switched_cmd_type
= true;
1287 } else if (busState
== WRITE_TO_READ
) {
1288 DPRINTF(DRAM
, "Switching to reads after %d writes with %d writes "
1289 "waiting\n", writesThisTime
, writeQueue
.size());
1291 wrPerTurnAround
.sample(writesThisTime
);
1295 switched_cmd_type
= true;
1298 // when we get here it is either a read or a write
1299 if (busState
== READ
) {
1301 // track if we should switch or not
1302 bool switch_to_writes
= false;
1304 if (readQueue
.empty()) {
1305 // In the case there is no read request to go next,
1306 // trigger writes if we have passed the low threshold (or
1307 // if we are draining)
1308 if (!writeQueue
.empty() &&
1309 (drainManager
|| writeQueue
.size() > writeLowThreshold
)) {
1311 switch_to_writes
= true;
1313 // check if we are drained
1314 if (respQueue
.empty () && drainManager
) {
1315 DPRINTF(Drain
, "DRAM controller done draining\n");
1316 drainManager
->signalDrainDone();
1317 drainManager
= NULL
;
1320 // nothing to do, not even any point in scheduling an
1321 // event for the next request
1325 // bool to check if there is a read to a free rank
1326 bool found_read
= false;
1328 // Figure out which read request goes next, and move it to the
1329 // front of the read queue
1330 found_read
= chooseNext(readQueue
, switched_cmd_type
);
1332 // if no read to an available rank is found then return
1333 // at this point. There could be writes to the available ranks
1334 // which are above the required threshold. However, to
1335 // avoid adding more complexity to the code, return and wait
1336 // for a refresh event to kick things into action again.
1340 DRAMPacket
* dram_pkt
= readQueue
.front();
1341 assert(dram_pkt
->rankRef
.isAvailable());
1342 // here we get a bit creative and shift the bus busy time not
1343 // just the tWTR, but also a CAS latency to capture the fact
1344 // that we are allowed to prepare a new bank, but not issue a
1345 // read command until after tWTR, in essence we capture a
1346 // bubble on the data bus that is tWTR + tCL
1347 if (switched_cmd_type
&& dram_pkt
->rank
== activeRank
) {
1348 busBusyUntil
+= tWTR
+ tCL
;
1351 doDRAMAccess(dram_pkt
);
1353 // At this point we're done dealing with the request
1354 readQueue
.pop_front();
1357 assert(dram_pkt
->size
<= burstSize
);
1358 assert(dram_pkt
->readyTime
>= curTick());
1360 // Insert into response queue. It will be sent back to the
1361 // requestor at its readyTime
1362 if (respQueue
.empty()) {
1363 assert(!respondEvent
.scheduled());
1364 schedule(respondEvent
, dram_pkt
->readyTime
);
1366 assert(respQueue
.back()->readyTime
<= dram_pkt
->readyTime
);
1367 assert(respondEvent
.scheduled());
1370 respQueue
.push_back(dram_pkt
);
1372 // we have so many writes that we have to transition
1373 if (writeQueue
.size() > writeHighThreshold
) {
1374 switch_to_writes
= true;
1378 // switching to writes, either because the read queue is empty
1379 // and the writes have passed the low threshold (or we are
1380 // draining), or because the writes hit the hight threshold
1381 if (switch_to_writes
) {
1382 // transition to writing
1383 busState
= READ_TO_WRITE
;
1386 // bool to check if write to free rank is found
1387 bool found_write
= false;
1389 found_write
= chooseNext(writeQueue
, switched_cmd_type
);
1391 // if no writes to an available rank are found then return.
1392 // There could be reads to the available ranks. However, to avoid
1393 // adding more complexity to the code, return at this point and wait
1394 // for a refresh event to kick things into action again.
1398 DRAMPacket
* dram_pkt
= writeQueue
.front();
1399 assert(dram_pkt
->rankRef
.isAvailable());
1401 assert(dram_pkt
->size
<= burstSize
);
1403 // add a bubble to the data bus, as defined by the
1404 // tRTW when access is to the same rank as previous burst
1405 // Different rank timing is handled with tCS, which is
1406 // applied to colAllowedAt
1407 if (switched_cmd_type
&& dram_pkt
->rank
== activeRank
) {
1408 busBusyUntil
+= tRTW
;
1411 doDRAMAccess(dram_pkt
);
1413 writeQueue
.pop_front();
1416 // If we emptied the write queue, or got sufficiently below the
1417 // threshold (using the minWritesPerSwitch as the hysteresis) and
1418 // are not draining, or we have reads waiting and have done enough
1419 // writes, then switch to reads.
1420 if (writeQueue
.empty() ||
1421 (writeQueue
.size() + minWritesPerSwitch
< writeLowThreshold
&&
1423 (!readQueue
.empty() && writesThisTime
>= minWritesPerSwitch
)) {
1424 // turn the bus back around for reads again
1425 busState
= WRITE_TO_READ
;
1427 // note that the we switch back to reads also in the idle
1428 // case, which eventually will check for any draining and
1429 // also pause any further scheduling if there is really
1433 // It is possible that a refresh to another rank kicks things back into
1434 // action before reaching this point.
1435 if (!nextReqEvent
.scheduled())
1436 schedule(nextReqEvent
, std::max(nextReqTime
, curTick()));
1438 // If there is space available and we have writes waiting then let
1439 // them retry. This is done here to ensure that the retry does not
1440 // cause a nextReqEvent to be scheduled before we do so as part of
1441 // the next request processing
1442 if (retryWrReq
&& writeQueue
.size() < writeBufferSize
) {
1449 DRAMCtrl::minBankPrep(const deque
<DRAMPacket
*>& queue
,
1450 bool switched_cmd_type
) const
1452 uint64_t bank_mask
= 0;
1453 Tick min_act_at
= MaxTick
;
1455 uint64_t bank_mask_same_rank
= 0;
1456 Tick min_act_at_same_rank
= MaxTick
;
1458 // Give precedence to commands that access same rank as previous command
1459 bool same_rank_match
= false;
1461 // determine if we have queued transactions targetting the
1463 vector
<bool> got_waiting(ranksPerChannel
* banksPerRank
, false);
1464 for (const auto& p
: queue
) {
1465 if(p
->rankRef
.isAvailable())
1466 got_waiting
[p
->bankId
] = true;
1469 for (int i
= 0; i
< ranksPerChannel
; i
++) {
1470 for (int j
= 0; j
< banksPerRank
; j
++) {
1471 uint16_t bank_id
= i
* banksPerRank
+ j
;
1473 // if we have waiting requests for the bank, and it is
1474 // amongst the first available, update the mask
1475 if (got_waiting
[bank_id
]) {
1476 // make sure this rank is not currently refreshing.
1477 assert(ranks
[i
]->isAvailable());
1478 // simplistic approximation of when the bank can issue
1479 // an activate, ignoring any rank-to-rank switching
1480 // cost in this calculation
1481 Tick act_at
= ranks
[i
]->banks
[j
].openRow
== Bank::NO_ROW
?
1482 ranks
[i
]->banks
[j
].actAllowedAt
:
1483 std::max(ranks
[i
]->banks
[j
].preAllowedAt
, curTick()) + tRP
;
1485 // prioritize commands that access the
1486 // same rank as previous burst
1487 // Calculate bank mask separately for the case and
1488 // evaluate after loop iterations complete
1489 if (i
== activeRank
&& ranksPerChannel
> 1) {
1490 if (act_at
<= min_act_at_same_rank
) {
1491 // reset same rank bank mask if new minimum is found
1492 // and previous minimum could not immediately send ACT
1493 if (act_at
< min_act_at_same_rank
&&
1494 min_act_at_same_rank
> curTick())
1495 bank_mask_same_rank
= 0;
1497 // Set flag indicating that a same rank
1498 // opportunity was found
1499 same_rank_match
= true;
1501 // set the bit corresponding to the available bank
1502 replaceBits(bank_mask_same_rank
, bank_id
, bank_id
, 1);
1503 min_act_at_same_rank
= act_at
;
1506 if (act_at
<= min_act_at
) {
1507 // reset bank mask if new minimum is found
1508 // and either previous minimum could not immediately send ACT
1509 if (act_at
< min_act_at
&& min_act_at
> curTick())
1511 // set the bit corresponding to the available bank
1512 replaceBits(bank_mask
, bank_id
, bank_id
, 1);
1513 min_act_at
= act_at
;
1520 // Determine the earliest time when the next burst can issue based
1521 // on the current busBusyUntil delay.
1522 // Offset by tRCD to correlate with ACT timing variables
1523 Tick min_cmd_at
= busBusyUntil
- tCL
- tRCD
;
1525 // if we have multiple ranks and all
1526 // waiting packets are accessing a rank which was previously active
1527 // then bank_mask_same_rank will be set to a value while bank_mask will
1528 // remain 0. In this case, the function should return the value of
1529 // bank_mask_same_rank.
1530 // else if waiting packets access a rank which was previously active and
1531 // other ranks, prioritize same rank accesses that can issue B2B
1532 // Only optimize for same ranks when the command type
1533 // does not change; do not want to unnecessarily incur tWTR
1535 // Resulting FCFS prioritization Order is:
1536 // 1) Commands that access the same rank as previous burst
1537 // and can prep the bank seamlessly.
1538 // 2) Commands (any rank) with earliest bank prep
1539 if ((bank_mask
== 0) || (!switched_cmd_type
&& same_rank_match
&&
1540 min_act_at_same_rank
<= min_cmd_at
)) {
1541 bank_mask
= bank_mask_same_rank
;
1547 DRAMCtrl::Rank::Rank(DRAMCtrl
& _memory
, const DRAMCtrlParams
* _p
)
1548 : EventManager(&_memory
), memory(_memory
),
1549 pwrStateTrans(PWR_IDLE
), pwrState(PWR_IDLE
), pwrStateTick(0),
1550 refreshState(REF_IDLE
), refreshDueAt(0),
1551 power(_p
, false), numBanksActive(0),
1552 activateEvent(*this), prechargeEvent(*this),
1553 refreshEvent(*this), powerEvent(*this)
1557 DRAMCtrl::Rank::startup(Tick ref_tick
)
1559 assert(ref_tick
> curTick());
1561 pwrStateTick
= curTick();
1563 // kick off the refresh, and give ourselves enough time to
1565 schedule(refreshEvent
, ref_tick
);
1569 DRAMCtrl::Rank::suspend()
1571 deschedule(refreshEvent
);
1575 DRAMCtrl::Rank::checkDrainDone()
1577 // if this rank was waiting to drain it is now able to proceed to
1579 if (refreshState
== REF_DRAIN
) {
1580 DPRINTF(DRAM
, "Refresh drain done, now precharging\n");
1582 refreshState
= REF_PRE
;
1584 // hand control back to the refresh event loop
1585 schedule(refreshEvent
, curTick());
1590 DRAMCtrl::Rank::processActivateEvent()
1592 // we should transition to the active state as soon as any bank is active
1593 if (pwrState
!= PWR_ACT
)
1594 // note that at this point numBanksActive could be back at
1595 // zero again due to a precharge scheduled in the future
1596 schedulePowerEvent(PWR_ACT
, curTick());
1600 DRAMCtrl::Rank::processPrechargeEvent()
1602 // if we reached zero, then special conditions apply as we track
1603 // if all banks are precharged for the power models
1604 if (numBanksActive
== 0) {
1605 // we should transition to the idle state when the last bank
1607 schedulePowerEvent(PWR_IDLE
, curTick());
1612 DRAMCtrl::Rank::processRefreshEvent()
1614 // when first preparing the refresh, remember when it was due
1615 if (refreshState
== REF_IDLE
) {
1616 // remember when the refresh is due
1617 refreshDueAt
= curTick();
1620 refreshState
= REF_DRAIN
;
1622 DPRINTF(DRAM
, "Refresh due\n");
1625 // let any scheduled read or write to the same rank go ahead,
1626 // after which it will
1627 // hand control back to this event loop
1628 if (refreshState
== REF_DRAIN
) {
1629 // if a request is at the moment being handled and this request is
1630 // accessing the current rank then wait for it to finish
1631 if ((rank
== memory
.activeRank
)
1632 && (memory
.nextReqEvent
.scheduled())) {
1633 // hand control over to the request loop until it is
1635 DPRINTF(DRAM
, "Refresh awaiting draining\n");
1639 refreshState
= REF_PRE
;
1643 // at this point, ensure that all banks are precharged
1644 if (refreshState
== REF_PRE
) {
1645 // precharge any active bank if we are not already in the idle
1647 if (pwrState
!= PWR_IDLE
) {
1648 // at the moment, we use a precharge all even if there is
1649 // only a single bank open
1650 DPRINTF(DRAM
, "Precharging all\n");
1652 // first determine when we can precharge
1653 Tick pre_at
= curTick();
1655 for (auto &b
: banks
) {
1656 // respect both causality and any existing bank
1657 // constraints, some banks could already have a
1658 // (auto) precharge scheduled
1659 pre_at
= std::max(b
.preAllowedAt
, pre_at
);
1662 // make sure all banks per rank are precharged, and for those that
1663 // already are, update their availability
1664 Tick act_allowed_at
= pre_at
+ memory
.tRP
;
1666 for (auto &b
: banks
) {
1667 if (b
.openRow
!= Bank::NO_ROW
) {
1668 memory
.prechargeBank(*this, b
, pre_at
, false);
1670 b
.actAllowedAt
= std::max(b
.actAllowedAt
, act_allowed_at
);
1671 b
.preAllowedAt
= std::max(b
.preAllowedAt
, pre_at
);
1675 // precharge all banks in rank
1676 power
.powerlib
.doCommand(MemCommand::PREA
, 0,
1677 divCeil(pre_at
, memory
.tCK
) -
1678 memory
.timeStampOffset
);
1680 DPRINTF(DRAMPower
, "%llu,PREA,0,%d\n",
1681 divCeil(pre_at
, memory
.tCK
) -
1682 memory
.timeStampOffset
, rank
);
1684 DPRINTF(DRAM
, "All banks already precharged, starting refresh\n");
1686 // go ahead and kick the power state machine into gear if
1687 // we are already idle
1688 schedulePowerEvent(PWR_REF
, curTick());
1691 refreshState
= REF_RUN
;
1692 assert(numBanksActive
== 0);
1694 // wait for all banks to be precharged, at which point the
1695 // power state machine will transition to the idle state, and
1696 // automatically move to a refresh, at that point it will also
1697 // call this method to get the refresh event loop going again
1701 // last but not least we perform the actual refresh
1702 if (refreshState
== REF_RUN
) {
1703 // should never get here with any banks active
1704 assert(numBanksActive
== 0);
1705 assert(pwrState
== PWR_REF
);
1707 Tick ref_done_at
= curTick() + memory
.tRFC
;
1709 for (auto &b
: banks
) {
1710 b
.actAllowedAt
= ref_done_at
;
1713 // at the moment this affects all ranks
1714 power
.powerlib
.doCommand(MemCommand::REF
, 0,
1715 divCeil(curTick(), memory
.tCK
) -
1716 memory
.timeStampOffset
);
1718 // at the moment sort the list of commands and update the counters
1719 // for DRAMPower libray when doing a refresh
1720 sort(power
.powerlib
.cmdList
.begin(),
1721 power
.powerlib
.cmdList
.end(), DRAMCtrl::sortTime
);
1723 // update the counters for DRAMPower, passing false to
1724 // indicate that this is not the last command in the
1725 // list. DRAMPower requires this information for the
1726 // correct calculation of the background energy at the end
1727 // of the simulation. Ideally we would want to call this
1728 // function with true once at the end of the
1729 // simulation. However, the discarded energy is extremly
1730 // small and does not effect the final results.
1731 power
.powerlib
.updateCounters(false);
1733 // call the energy function
1734 power
.powerlib
.calcEnergy();
1739 DPRINTF(DRAMPower
, "%llu,REF,0,%d\n", divCeil(curTick(), memory
.tCK
) -
1740 memory
.timeStampOffset
, rank
);
1742 // make sure we did not wait so long that we cannot make up
1744 if (refreshDueAt
+ memory
.tREFI
< ref_done_at
) {
1745 fatal("Refresh was delayed so long we cannot catch up\n");
1748 // compensate for the delay in actually performing the refresh
1749 // when scheduling the next one
1750 schedule(refreshEvent
, refreshDueAt
+ memory
.tREFI
- memory
.tRP
);
1752 assert(!powerEvent
.scheduled());
1754 // move to the idle power state once the refresh is done, this
1755 // will also move the refresh state machine to the refresh
1757 schedulePowerEvent(PWR_IDLE
, ref_done_at
);
1759 DPRINTF(DRAMState
, "Refresh done at %llu and next refresh at %llu\n",
1760 ref_done_at
, refreshDueAt
+ memory
.tREFI
);
1765 DRAMCtrl::Rank::schedulePowerEvent(PowerState pwr_state
, Tick tick
)
1767 // respect causality
1768 assert(tick
>= curTick());
1770 if (!powerEvent
.scheduled()) {
1771 DPRINTF(DRAMState
, "Scheduling power event at %llu to state %d\n",
1774 // insert the new transition
1775 pwrStateTrans
= pwr_state
;
1777 schedule(powerEvent
, tick
);
1779 panic("Scheduled power event at %llu to state %d, "
1780 "with scheduled event at %llu to %d\n", tick
, pwr_state
,
1781 powerEvent
.when(), pwrStateTrans
);
1786 DRAMCtrl::Rank::processPowerEvent()
1788 // remember where we were, and for how long
1789 Tick duration
= curTick() - pwrStateTick
;
1790 PowerState prev_state
= pwrState
;
1792 // update the accounting
1793 pwrStateTime
[prev_state
] += duration
;
1795 pwrState
= pwrStateTrans
;
1796 pwrStateTick
= curTick();
1798 if (pwrState
== PWR_IDLE
) {
1799 DPRINTF(DRAMState
, "All banks precharged\n");
1801 // if we were refreshing, make sure we start scheduling requests again
1802 if (prev_state
== PWR_REF
) {
1803 DPRINTF(DRAMState
, "Was refreshing for %llu ticks\n", duration
);
1804 assert(pwrState
== PWR_IDLE
);
1806 // kick things into action again
1807 refreshState
= REF_IDLE
;
1808 // a request event could be already scheduled by the state
1809 // machine of the other rank
1810 if (!memory
.nextReqEvent
.scheduled())
1811 schedule(memory
.nextReqEvent
, curTick());
1813 assert(prev_state
== PWR_ACT
);
1815 // if we have a pending refresh, and are now moving to
1816 // the idle state, direclty transition to a refresh
1817 if (refreshState
== REF_RUN
) {
1818 // there should be nothing waiting at this point
1819 assert(!powerEvent
.scheduled());
1821 // update the state in zero time and proceed below
1827 // we transition to the refresh state, let the refresh state
1828 // machine know of this state update and let it deal with the
1829 // scheduling of the next power state transition as well as the
1830 // following refresh
1831 if (pwrState
== PWR_REF
) {
1832 DPRINTF(DRAMState
, "Refreshing\n");
1833 // kick the refresh event loop into action again, and that
1834 // in turn will schedule a transition to the idle power
1835 // state once the refresh is done
1836 assert(refreshState
== REF_RUN
);
1837 processRefreshEvent();
1842 DRAMCtrl::Rank::updatePowerStats()
1844 // Get the energy and power from DRAMPower
1845 Data::MemoryPowerModel::Energy energy
=
1846 power
.powerlib
.getEnergy();
1847 Data::MemoryPowerModel::Power rank_power
=
1848 power
.powerlib
.getPower();
1850 actEnergy
= energy
.act_energy
* memory
.devicesPerRank
;
1851 preEnergy
= energy
.pre_energy
* memory
.devicesPerRank
;
1852 readEnergy
= energy
.read_energy
* memory
.devicesPerRank
;
1853 writeEnergy
= energy
.write_energy
* memory
.devicesPerRank
;
1854 refreshEnergy
= energy
.ref_energy
* memory
.devicesPerRank
;
1855 actBackEnergy
= energy
.act_stdby_energy
* memory
.devicesPerRank
;
1856 preBackEnergy
= energy
.pre_stdby_energy
* memory
.devicesPerRank
;
1857 totalEnergy
= energy
.total_energy
* memory
.devicesPerRank
;
1858 averagePower
= rank_power
.average_power
* memory
.devicesPerRank
;
1862 DRAMCtrl::Rank::regStats()
1864 using namespace Stats
;
1868 .name(name() + ".memoryStateTime")
1869 .desc("Time in different power states");
1870 pwrStateTime
.subname(0, "IDLE");
1871 pwrStateTime
.subname(1, "REF");
1872 pwrStateTime
.subname(2, "PRE_PDN");
1873 pwrStateTime
.subname(3, "ACT");
1874 pwrStateTime
.subname(4, "ACT_PDN");
1877 .name(name() + ".actEnergy")
1878 .desc("Energy for activate commands per rank (pJ)");
1881 .name(name() + ".preEnergy")
1882 .desc("Energy for precharge commands per rank (pJ)");
1885 .name(name() + ".readEnergy")
1886 .desc("Energy for read commands per rank (pJ)");
1889 .name(name() + ".writeEnergy")
1890 .desc("Energy for write commands per rank (pJ)");
1893 .name(name() + ".refreshEnergy")
1894 .desc("Energy for refresh commands per rank (pJ)");
1897 .name(name() + ".actBackEnergy")
1898 .desc("Energy for active background per rank (pJ)");
1901 .name(name() + ".preBackEnergy")
1902 .desc("Energy for precharge background per rank (pJ)");
1905 .name(name() + ".totalEnergy")
1906 .desc("Total energy per rank (pJ)");
1909 .name(name() + ".averagePower")
1910 .desc("Core power per rank (mW)");
1913 DRAMCtrl::regStats()
1915 using namespace Stats
;
1917 AbstractMemory::regStats();
1919 for (auto r
: ranks
) {
1924 .name(name() + ".readReqs")
1925 .desc("Number of read requests accepted");
1928 .name(name() + ".writeReqs")
1929 .desc("Number of write requests accepted");
1932 .name(name() + ".readBursts")
1933 .desc("Number of DRAM read bursts, "
1934 "including those serviced by the write queue");
1937 .name(name() + ".writeBursts")
1938 .desc("Number of DRAM write bursts, "
1939 "including those merged in the write queue");
1942 .name(name() + ".servicedByWrQ")
1943 .desc("Number of DRAM read bursts serviced by the write queue");
1946 .name(name() + ".mergedWrBursts")
1947 .desc("Number of DRAM write bursts merged with an existing one");
1950 .name(name() + ".neitherReadNorWriteReqs")
1951 .desc("Number of requests that are neither read nor write");
1954 .init(banksPerRank
* ranksPerChannel
)
1955 .name(name() + ".perBankRdBursts")
1956 .desc("Per bank write bursts");
1959 .init(banksPerRank
* ranksPerChannel
)
1960 .name(name() + ".perBankWrBursts")
1961 .desc("Per bank write bursts");
1964 .name(name() + ".avgRdQLen")
1965 .desc("Average read queue length when enqueuing")
1969 .name(name() + ".avgWrQLen")
1970 .desc("Average write queue length when enqueuing")
1974 .name(name() + ".totQLat")
1975 .desc("Total ticks spent queuing");
1978 .name(name() + ".totBusLat")
1979 .desc("Total ticks spent in databus transfers");
1982 .name(name() + ".totMemAccLat")
1983 .desc("Total ticks spent from burst creation until serviced "
1987 .name(name() + ".avgQLat")
1988 .desc("Average queueing delay per DRAM burst")
1991 avgQLat
= totQLat
/ (readBursts
- servicedByWrQ
);
1994 .name(name() + ".avgBusLat")
1995 .desc("Average bus latency per DRAM burst")
1998 avgBusLat
= totBusLat
/ (readBursts
- servicedByWrQ
);
2001 .name(name() + ".avgMemAccLat")
2002 .desc("Average memory access latency per DRAM burst")
2005 avgMemAccLat
= totMemAccLat
/ (readBursts
- servicedByWrQ
);
2008 .name(name() + ".numRdRetry")
2009 .desc("Number of times read queue was full causing retry");
2012 .name(name() + ".numWrRetry")
2013 .desc("Number of times write queue was full causing retry");
2016 .name(name() + ".readRowHits")
2017 .desc("Number of row buffer hits during reads");
2020 .name(name() + ".writeRowHits")
2021 .desc("Number of row buffer hits during writes");
2024 .name(name() + ".readRowHitRate")
2025 .desc("Row buffer hit rate for reads")
2028 readRowHitRate
= (readRowHits
/ (readBursts
- servicedByWrQ
)) * 100;
2031 .name(name() + ".writeRowHitRate")
2032 .desc("Row buffer hit rate for writes")
2035 writeRowHitRate
= (writeRowHits
/ (writeBursts
- mergedWrBursts
)) * 100;
2038 .init(ceilLog2(burstSize
) + 1)
2039 .name(name() + ".readPktSize")
2040 .desc("Read request sizes (log2)");
2043 .init(ceilLog2(burstSize
) + 1)
2044 .name(name() + ".writePktSize")
2045 .desc("Write request sizes (log2)");
2048 .init(readBufferSize
)
2049 .name(name() + ".rdQLenPdf")
2050 .desc("What read queue length does an incoming req see");
2053 .init(writeBufferSize
)
2054 .name(name() + ".wrQLenPdf")
2055 .desc("What write queue length does an incoming req see");
2058 .init(maxAccessesPerRow
)
2059 .name(name() + ".bytesPerActivate")
2060 .desc("Bytes accessed per row activation")
2064 .init(readBufferSize
)
2065 .name(name() + ".rdPerTurnAround")
2066 .desc("Reads before turning the bus around for writes")
2070 .init(writeBufferSize
)
2071 .name(name() + ".wrPerTurnAround")
2072 .desc("Writes before turning the bus around for reads")
2076 .name(name() + ".bytesReadDRAM")
2077 .desc("Total number of bytes read from DRAM");
2080 .name(name() + ".bytesReadWrQ")
2081 .desc("Total number of bytes read from write queue");
2084 .name(name() + ".bytesWritten")
2085 .desc("Total number of bytes written to DRAM");
2088 .name(name() + ".bytesReadSys")
2089 .desc("Total read bytes from the system interface side");
2092 .name(name() + ".bytesWrittenSys")
2093 .desc("Total written bytes from the system interface side");
2096 .name(name() + ".avgRdBW")
2097 .desc("Average DRAM read bandwidth in MiByte/s")
2100 avgRdBW
= (bytesReadDRAM
/ 1000000) / simSeconds
;
2103 .name(name() + ".avgWrBW")
2104 .desc("Average achieved write bandwidth in MiByte/s")
2107 avgWrBW
= (bytesWritten
/ 1000000) / simSeconds
;
2110 .name(name() + ".avgRdBWSys")
2111 .desc("Average system read bandwidth in MiByte/s")
2114 avgRdBWSys
= (bytesReadSys
/ 1000000) / simSeconds
;
2117 .name(name() + ".avgWrBWSys")
2118 .desc("Average system write bandwidth in MiByte/s")
2121 avgWrBWSys
= (bytesWrittenSys
/ 1000000) / simSeconds
;
2124 .name(name() + ".peakBW")
2125 .desc("Theoretical peak bandwidth in MiByte/s")
2128 peakBW
= (SimClock::Frequency
/ tBURST
) * burstSize
/ 1000000;
2131 .name(name() + ".busUtil")
2132 .desc("Data bus utilization in percentage")
2134 busUtil
= (avgRdBW
+ avgWrBW
) / peakBW
* 100;
2137 .name(name() + ".totGap")
2138 .desc("Total gap between requests");
2141 .name(name() + ".avgGap")
2142 .desc("Average gap between requests")
2145 avgGap
= totGap
/ (readReqs
+ writeReqs
);
2147 // Stats for DRAM Power calculation based on Micron datasheet
2149 .name(name() + ".busUtilRead")
2150 .desc("Data bus utilization in percentage for reads")
2153 busUtilRead
= avgRdBW
/ peakBW
* 100;
2156 .name(name() + ".busUtilWrite")
2157 .desc("Data bus utilization in percentage for writes")
2160 busUtilWrite
= avgWrBW
/ peakBW
* 100;
2163 .name(name() + ".pageHitRate")
2164 .desc("Row buffer hit rate, read and write combined")
2167 pageHitRate
= (writeRowHits
+ readRowHits
) /
2168 (writeBursts
- mergedWrBursts
+ readBursts
- servicedByWrQ
) * 100;
2172 DRAMCtrl::recvFunctional(PacketPtr pkt
)
2174 // rely on the abstract memory
2175 functionalAccess(pkt
);
2179 DRAMCtrl::getSlavePort(const string
&if_name
, PortID idx
)
2181 if (if_name
!= "port") {
2182 return MemObject::getSlavePort(if_name
, idx
);
2189 DRAMCtrl::drain(DrainManager
*dm
)
2191 unsigned int count
= port
.drain(dm
);
2193 // if there is anything in any of our internal queues, keep track
2195 if (!(writeQueue
.empty() && readQueue
.empty() &&
2196 respQueue
.empty())) {
2197 DPRINTF(Drain
, "DRAM controller not drained, write: %d, read: %d,"
2198 " resp: %d\n", writeQueue
.size(), readQueue
.size(),
2203 // the only part that is not drained automatically over time
2204 // is the write queue, thus kick things into action if needed
2205 if (!writeQueue
.empty() && !nextReqEvent
.scheduled()) {
2206 schedule(nextReqEvent
, curTick());
2211 setDrainState(Drainable::Draining
);
2213 setDrainState(Drainable::Drained
);
2218 DRAMCtrl::drainResume()
2220 if (!isTimingMode
&& system()->isTimingMode()) {
2221 // if we switched to timing mode, kick things into action,
2222 // and behave as if we restored from a checkpoint
2224 } else if (isTimingMode
&& !system()->isTimingMode()) {
2225 // if we switch from timing mode, stop the refresh events to
2226 // not cause issues with KVM
2227 for (auto r
: ranks
) {
2233 isTimingMode
= system()->isTimingMode();
2236 DRAMCtrl::MemoryPort::MemoryPort(const std::string
& name
, DRAMCtrl
& _memory
)
2237 : QueuedSlavePort(name
, &_memory
, queue
), queue(_memory
, *this),
2242 DRAMCtrl::MemoryPort::getAddrRanges() const
2244 AddrRangeList ranges
;
2245 ranges
.push_back(memory
.getAddrRange());
2250 DRAMCtrl::MemoryPort::recvFunctional(PacketPtr pkt
)
2252 pkt
->pushLabel(memory
.name());
2254 if (!queue
.checkFunctional(pkt
)) {
2255 // Default implementation of SimpleTimingPort::recvFunctional()
2256 // calls recvAtomic() and throws away the latency; we can save a
2257 // little here by just not calculating the latency.
2258 memory
.recvFunctional(pkt
);
2265 DRAMCtrl::MemoryPort::recvAtomic(PacketPtr pkt
)
2267 return memory
.recvAtomic(pkt
);
2271 DRAMCtrl::MemoryPort::recvTimingReq(PacketPtr pkt
)
2273 // pass it to the memory controller
2274 return memory
.recvTimingReq(pkt
);
2278 DRAMCtrlParams::create()
2280 return new DRAMCtrl(this);