mem: Fix DRAM controller to operate on its own address space
[gem5.git] / src / mem / dram_ctrl.hh
1 /*
2 * Copyright (c) 2012-2019 ARM Limited
3 * All rights reserved
4 *
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.
13 *
14 * Copyright (c) 2013 Amin Farmahini-Farahani
15 * All rights reserved.
16 *
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.
27 *
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.
39 *
40 * Authors: Andreas Hansson
41 * Ani Udipi
42 * Neha Agarwal
43 * Omar Naji
44 * Matthias Jung
45 * Wendy Elsasser
46 * Radhika Jagtap
47 */
48
49 /**
50 * @file
51 * DRAMCtrl declaration
52 */
53
54 #ifndef __MEM_DRAM_CTRL_HH__
55 #define __MEM_DRAM_CTRL_HH__
56
57 #include <deque>
58 #include <string>
59 #include <unordered_set>
60 #include <vector>
61
62 #include "base/callback.hh"
63 #include "base/statistics.hh"
64 #include "enums/AddrMap.hh"
65 #include "enums/MemSched.hh"
66 #include "enums/PageManage.hh"
67 #include "mem/drampower.hh"
68 #include "mem/qos/mem_ctrl.hh"
69 #include "mem/qport.hh"
70 #include "params/DRAMCtrl.hh"
71 #include "sim/eventq.hh"
72
73 /**
74 * The DRAM controller is a single-channel memory controller capturing
75 * the most important timing constraints associated with a
76 * contemporary DRAM. For multi-channel memory systems, the controller
77 * is combined with a crossbar model, with the channel address
78 * interleaving taking part in the crossbar.
79 *
80 * As a basic design principle, this controller
81 * model is not cycle callable, but instead uses events to: 1) decide
82 * when new decisions can be made, 2) when resources become available,
83 * 3) when things are to be considered done, and 4) when to send
84 * things back. Through these simple principles, the model delivers
85 * high performance, and lots of flexibility, allowing users to
86 * evaluate the system impact of a wide range of memory technologies,
87 * such as DDR3/4, LPDDR2/3/4, WideIO1/2, HBM and HMC.
88 *
89 * For more details, please see Hansson et al, "Simulating DRAM
90 * controllers for future system architecture exploration",
91 * Proc. ISPASS, 2014. If you use this model as part of your research
92 * please cite the paper.
93 *
94 * The low-power functionality implements a staggered powerdown
95 * similar to that described in "Optimized Active and Power-Down Mode
96 * Refresh Control in 3D-DRAMs" by Jung et al, VLSI-SoC, 2014.
97 */
98 class DRAMCtrl : public QoS::MemCtrl
99 {
100
101 private:
102
103 // For now, make use of a queued slave port to avoid dealing with
104 // flow control for the responses being sent back
105 class MemoryPort : public QueuedSlavePort
106 {
107
108 RespPacketQueue queue;
109 DRAMCtrl& memory;
110
111 public:
112
113 MemoryPort(const std::string& name, DRAMCtrl& _memory);
114
115 protected:
116
117 Tick recvAtomic(PacketPtr pkt);
118
119 void recvFunctional(PacketPtr pkt);
120
121 bool recvTimingReq(PacketPtr);
122
123 virtual AddrRangeList getAddrRanges() const;
124
125 };
126
127 /**
128 * Our incoming port, for a multi-ported controller add a crossbar
129 * in front of it
130 */
131 MemoryPort port;
132
133 /**
134 * Remember if the memory system is in timing mode
135 */
136 bool isTimingMode;
137
138 /**
139 * Remember if we have to retry a request when available.
140 */
141 bool retryRdReq;
142 bool retryWrReq;
143
144 /**/
145
146 /**
147 * Simple structure to hold the values needed to keep track of
148 * commands for DRAMPower
149 */
150 struct Command {
151 Data::MemCommand::cmds type;
152 uint8_t bank;
153 Tick timeStamp;
154
155 constexpr Command(Data::MemCommand::cmds _type, uint8_t _bank,
156 Tick time_stamp)
157 : type(_type), bank(_bank), timeStamp(time_stamp)
158 { }
159 };
160
161 /**
162 * A basic class to track the bank state, i.e. what row is
163 * currently open (if any), when is the bank free to accept a new
164 * column (read/write) command, when can it be precharged, and
165 * when can it be activated.
166 *
167 * The bank also keeps track of how many bytes have been accessed
168 * in the open row since it was opened.
169 */
170 class Bank
171 {
172
173 public:
174
175 static const uint32_t NO_ROW = -1;
176
177 uint32_t openRow;
178 uint8_t bank;
179 uint8_t bankgr;
180
181 Tick rdAllowedAt;
182 Tick wrAllowedAt;
183 Tick preAllowedAt;
184 Tick actAllowedAt;
185
186 uint32_t rowAccesses;
187 uint32_t bytesAccessed;
188
189 Bank() :
190 openRow(NO_ROW), bank(0), bankgr(0),
191 rdAllowedAt(0), wrAllowedAt(0), preAllowedAt(0), actAllowedAt(0),
192 rowAccesses(0), bytesAccessed(0)
193 { }
194 };
195
196
197 /**
198 * The power state captures the different operational states of
199 * the DRAM and interacts with the bus read/write state machine,
200 * and the refresh state machine.
201 *
202 * PWR_IDLE : The idle state in which all banks are closed
203 * From here can transition to: PWR_REF, PWR_ACT,
204 * PWR_PRE_PDN
205 *
206 * PWR_REF : Auto-refresh state. Will transition when refresh is
207 * complete based on power state prior to PWR_REF
208 * From here can transition to: PWR_IDLE, PWR_PRE_PDN,
209 * PWR_SREF
210 *
211 * PWR_SREF : Self-refresh state. Entered after refresh if
212 * previous state was PWR_PRE_PDN
213 * From here can transition to: PWR_IDLE
214 *
215 * PWR_PRE_PDN : Precharge power down state
216 * From here can transition to: PWR_REF, PWR_IDLE
217 *
218 * PWR_ACT : Activate state in which one or more banks are open
219 * From here can transition to: PWR_IDLE, PWR_ACT_PDN
220 *
221 * PWR_ACT_PDN : Activate power down state
222 * From here can transition to: PWR_ACT
223 */
224 enum PowerState {
225 PWR_IDLE = 0,
226 PWR_REF,
227 PWR_SREF,
228 PWR_PRE_PDN,
229 PWR_ACT,
230 PWR_ACT_PDN
231 };
232
233 /**
234 * The refresh state is used to control the progress of the
235 * refresh scheduling. When normal operation is in progress the
236 * refresh state is idle. Once tREFI has elasped, a refresh event
237 * is triggered to start the following STM transitions which are
238 * used to issue a refresh and return back to normal operation
239 *
240 * REF_IDLE : IDLE state used during normal operation
241 * From here can transition to: REF_DRAIN
242 *
243 * REF_SREF_EXIT : Exiting a self-refresh; refresh event scheduled
244 * after self-refresh exit completes
245 * From here can transition to: REF_DRAIN
246 *
247 * REF_DRAIN : Drain state in which on going accesses complete.
248 * From here can transition to: REF_PD_EXIT
249 *
250 * REF_PD_EXIT : Evaluate pwrState and issue wakeup if needed
251 * Next state dependent on whether banks are open
252 * From here can transition to: REF_PRE, REF_START
253 *
254 * REF_PRE : Close (precharge) all open banks
255 * From here can transition to: REF_START
256 *
257 * REF_START : Issue refresh command and update DRAMPower stats
258 * From here can transition to: REF_RUN
259 *
260 * REF_RUN : Refresh running, waiting for tRFC to expire
261 * From here can transition to: REF_IDLE, REF_SREF_EXIT
262 */
263 enum RefreshState {
264 REF_IDLE = 0,
265 REF_DRAIN,
266 REF_PD_EXIT,
267 REF_SREF_EXIT,
268 REF_PRE,
269 REF_START,
270 REF_RUN
271 };
272
273 class Rank;
274 struct RankStats : public Stats::Group
275 {
276 RankStats(DRAMCtrl& memory, Rank &rank);
277
278 void regStats() override;
279 void resetStats() override;
280 void preDumpStats() override;
281
282 Rank &rank;
283
284 /*
285 * Command energies
286 */
287 Stats::Scalar actEnergy;
288 Stats::Scalar preEnergy;
289 Stats::Scalar readEnergy;
290 Stats::Scalar writeEnergy;
291 Stats::Scalar refreshEnergy;
292
293 /*
294 * Active Background Energy
295 */
296 Stats::Scalar actBackEnergy;
297
298 /*
299 * Precharge Background Energy
300 */
301 Stats::Scalar preBackEnergy;
302
303 /*
304 * Active Power-Down Energy
305 */
306 Stats::Scalar actPowerDownEnergy;
307
308 /*
309 * Precharge Power-Down Energy
310 */
311 Stats::Scalar prePowerDownEnergy;
312
313 /*
314 * self Refresh Energy
315 */
316 Stats::Scalar selfRefreshEnergy;
317
318 Stats::Scalar totalEnergy;
319 Stats::Scalar averagePower;
320
321 /**
322 * Stat to track total DRAM idle time
323 *
324 */
325 Stats::Scalar totalIdleTime;
326
327 /**
328 * Track time spent in each power state.
329 */
330 Stats::Vector memoryStateTime;
331 };
332
333 /**
334 * Rank class includes a vector of banks. Refresh and Power state
335 * machines are defined per rank. Events required to change the
336 * state of the refresh and power state machine are scheduled per
337 * rank. This class allows the implementation of rank-wise refresh
338 * and rank-wise power-down.
339 */
340 class Rank : public EventManager
341 {
342
343 private:
344
345 /**
346 * A reference to the parent DRAMCtrl instance
347 */
348 DRAMCtrl& memory;
349
350 /**
351 * Since we are taking decisions out of order, we need to keep
352 * track of what power transition is happening at what time
353 */
354 PowerState pwrStateTrans;
355
356 /**
357 * Previous low-power state, which will be re-entered after refresh.
358 */
359 PowerState pwrStatePostRefresh;
360
361 /**
362 * Track when we transitioned to the current power state
363 */
364 Tick pwrStateTick;
365
366 /**
367 * Keep track of when a refresh is due.
368 */
369 Tick refreshDueAt;
370
371 /**
372 * Function to update Power Stats
373 */
374 void updatePowerStats();
375
376 /**
377 * Schedule a power state transition in the future, and
378 * potentially override an already scheduled transition.
379 *
380 * @param pwr_state Power state to transition to
381 * @param tick Tick when transition should take place
382 */
383 void schedulePowerEvent(PowerState pwr_state, Tick tick);
384
385 public:
386
387 /**
388 * Current power state.
389 */
390 PowerState pwrState;
391
392 /**
393 * current refresh state
394 */
395 RefreshState refreshState;
396
397 /**
398 * rank is in or transitioning to power-down or self-refresh
399 */
400 bool inLowPowerState;
401
402 /**
403 * Current Rank index
404 */
405 uint8_t rank;
406
407 /**
408 * Track number of packets in read queue going to this rank
409 */
410 uint32_t readEntries;
411
412 /**
413 * Track number of packets in write queue going to this rank
414 */
415 uint32_t writeEntries;
416
417 /**
418 * Number of ACT, RD, and WR events currently scheduled
419 * Incremented when a refresh event is started as well
420 * Used to determine when a low-power state can be entered
421 */
422 uint8_t outstandingEvents;
423
424 /**
425 * delay power-down and self-refresh exit until this requirement is met
426 */
427 Tick wakeUpAllowedAt;
428
429 /**
430 * One DRAMPower instance per rank
431 */
432 DRAMPower power;
433
434 /**
435 * List of commands issued, to be sent to DRAMPpower at refresh
436 * and stats dump. Keep commands here since commands to different
437 * banks are added out of order. Will only pass commands up to
438 * curTick() to DRAMPower after sorting.
439 */
440 std::vector<Command> cmdList;
441
442 /**
443 * Vector of Banks. Each rank is made of several devices which in
444 * term are made from several banks.
445 */
446 std::vector<Bank> banks;
447
448 /**
449 * To track number of banks which are currently active for
450 * this rank.
451 */
452 unsigned int numBanksActive;
453
454 /** List to keep track of activate ticks */
455 std::deque<Tick> actTicks;
456
457 Rank(DRAMCtrl& _memory, const DRAMCtrlParams* _p, int rank);
458
459 const std::string name() const
460 {
461 return csprintf("%s_%d", memory.name(), rank);
462 }
463
464 /**
465 * Kick off accounting for power and refresh states and
466 * schedule initial refresh.
467 *
468 * @param ref_tick Tick for first refresh
469 */
470 void startup(Tick ref_tick);
471
472 /**
473 * Stop the refresh events.
474 */
475 void suspend();
476
477 /**
478 * Check if there is no refresh and no preparation of refresh ongoing
479 * i.e. the refresh state machine is in idle
480 *
481 * @param Return true if the rank is idle from a refresh point of view
482 */
483 bool inRefIdleState() const { return refreshState == REF_IDLE; }
484
485 /**
486 * Check if the current rank has all banks closed and is not
487 * in a low power state
488 *
489 * @param Return true if the rank is idle from a bank
490 * and power point of view
491 */
492 bool inPwrIdleState() const { return pwrState == PWR_IDLE; }
493
494 /**
495 * Trigger a self-refresh exit if there are entries enqueued
496 * Exit if there are any read entries regardless of the bus state.
497 * If we are currently issuing write commands, exit if we have any
498 * write commands enqueued as well.
499 * Could expand this in the future to analyze state of entire queue
500 * if needed.
501 *
502 * @return boolean indicating self-refresh exit should be scheduled
503 */
504 bool forceSelfRefreshExit() const {
505 return (readEntries != 0) ||
506 ((memory.busStateNext == WRITE) && (writeEntries != 0));
507 }
508
509 /**
510 * Check if the command queue of current rank is idle
511 *
512 * @param Return true if the there are no commands in Q.
513 * Bus direction determines queue checked.
514 */
515 bool isQueueEmpty() const;
516
517 /**
518 * Let the rank check if it was waiting for requests to drain
519 * to allow it to transition states.
520 */
521 void checkDrainDone();
522
523 /**
524 * Push command out of cmdList queue that are scheduled at
525 * or before curTick() to DRAMPower library
526 * All commands before curTick are guaranteed to be complete
527 * and can safely be flushed.
528 */
529 void flushCmdList();
530
531 /*
532 * Function to register Stats
533 */
534 void regStats();
535
536 /**
537 * Computes stats just prior to dump event
538 */
539 void computeStats();
540
541 /**
542 * Reset stats on a stats event
543 */
544 void resetStats();
545
546 /**
547 * Schedule a transition to power-down (sleep)
548 *
549 * @param pwr_state Power state to transition to
550 * @param tick Absolute tick when transition should take place
551 */
552 void powerDownSleep(PowerState pwr_state, Tick tick);
553
554 /**
555 * schedule and event to wake-up from power-down or self-refresh
556 * and update bank timing parameters
557 *
558 * @param exit_delay Relative tick defining the delay required between
559 * low-power exit and the next command
560 */
561 void scheduleWakeUpEvent(Tick exit_delay);
562
563 void processWriteDoneEvent();
564 EventFunctionWrapper writeDoneEvent;
565
566 void processActivateEvent();
567 EventFunctionWrapper activateEvent;
568
569 void processPrechargeEvent();
570 EventFunctionWrapper prechargeEvent;
571
572 void processRefreshEvent();
573 EventFunctionWrapper refreshEvent;
574
575 void processPowerEvent();
576 EventFunctionWrapper powerEvent;
577
578 void processWakeUpEvent();
579 EventFunctionWrapper wakeUpEvent;
580
581 protected:
582 RankStats stats;
583 };
584
585 /**
586 * A burst helper helps organize and manage a packet that is larger than
587 * the DRAM burst size. A system packet that is larger than the burst size
588 * is split into multiple DRAM packets and all those DRAM packets point to
589 * a single burst helper such that we know when the whole packet is served.
590 */
591 class BurstHelper {
592
593 public:
594
595 /** Number of DRAM bursts requred for a system packet **/
596 const unsigned int burstCount;
597
598 /** Number of DRAM bursts serviced so far for a system packet **/
599 unsigned int burstsServiced;
600
601 BurstHelper(unsigned int _burstCount)
602 : burstCount(_burstCount), burstsServiced(0)
603 { }
604 };
605
606 /**
607 * A DRAM packet stores packets along with the timestamp of when
608 * the packet entered the queue, and also the decoded address.
609 */
610 class DRAMPacket {
611
612 public:
613
614 /** When did request enter the controller */
615 const Tick entryTime;
616
617 /** When will request leave the controller */
618 Tick readyTime;
619
620 /** This comes from the outside world */
621 const PacketPtr pkt;
622
623 /** MasterID associated with the packet */
624 const MasterID _masterId;
625
626 const bool read;
627
628 /** Will be populated by address decoder */
629 const uint8_t rank;
630 const uint8_t bank;
631 const uint32_t row;
632
633 /**
634 * Bank id is calculated considering banks in all the ranks
635 * eg: 2 ranks each with 8 banks, then bankId = 0 --> rank0, bank0 and
636 * bankId = 8 --> rank1, bank0
637 */
638 const uint16_t bankId;
639
640 /**
641 * The starting address of the DRAM packet.
642 * This address could be unaligned to burst size boundaries. The
643 * reason is to keep the address offset so we can accurately check
644 * incoming read packets with packets in the write queue.
645 */
646 Addr addr;
647
648 /**
649 * The size of this dram packet in bytes
650 * It is always equal or smaller than DRAM burst size
651 */
652 unsigned int size;
653
654 /**
655 * A pointer to the BurstHelper if this DRAMPacket is a split packet
656 * If not a split packet (common case), this is set to NULL
657 */
658 BurstHelper* burstHelper;
659 Bank& bankRef;
660 Rank& rankRef;
661
662 /**
663 * QoS value of the encapsulated packet read at queuing time
664 */
665 uint8_t _qosValue;
666
667 /**
668 * Set the packet QoS value
669 * (interface compatibility with Packet)
670 */
671 inline void qosValue(const uint8_t qv) { _qosValue = qv; }
672
673 /**
674 * Get the packet QoS value
675 * (interface compatibility with Packet)
676 */
677 inline uint8_t qosValue() const { return _qosValue; }
678
679 /**
680 * Get the packet MasterID
681 * (interface compatibility with Packet)
682 */
683 inline MasterID masterId() const { return _masterId; }
684
685 /**
686 * Get the packet size
687 * (interface compatibility with Packet)
688 */
689 inline unsigned int getSize() const { return size; }
690
691 /**
692 * Get the packet address
693 * (interface compatibility with Packet)
694 */
695 inline Addr getAddr() const { return addr; }
696
697 /**
698 * Return true if its a read packet
699 * (interface compatibility with Packet)
700 */
701 inline bool isRead() const { return read; }
702
703 /**
704 * Return true if its a write packet
705 * (interface compatibility with Packet)
706 */
707 inline bool isWrite() const { return !read; }
708
709
710 DRAMPacket(PacketPtr _pkt, bool is_read, uint8_t _rank, uint8_t _bank,
711 uint32_t _row, uint16_t bank_id, Addr _addr,
712 unsigned int _size, Bank& bank_ref, Rank& rank_ref)
713 : entryTime(curTick()), readyTime(curTick()), pkt(_pkt),
714 _masterId(pkt->masterId()),
715 read(is_read), rank(_rank), bank(_bank), row(_row),
716 bankId(bank_id), addr(_addr), size(_size), burstHelper(NULL),
717 bankRef(bank_ref), rankRef(rank_ref), _qosValue(_pkt->qosValue())
718 { }
719
720 };
721
722 // The DRAM packets are store in a multiple dequeue structure,
723 // based on their QoS priority
724 typedef std::deque<DRAMPacket*> DRAMPacketQueue;
725
726 /**
727 * Bunch of things requires to setup "events" in gem5
728 * When event "respondEvent" occurs for example, the method
729 * processRespondEvent is called; no parameters are allowed
730 * in these methods
731 */
732 void processNextReqEvent();
733 EventFunctionWrapper nextReqEvent;
734
735 void processRespondEvent();
736 EventFunctionWrapper respondEvent;
737
738 /**
739 * Check if the read queue has room for more entries
740 *
741 * @param pktCount The number of entries needed in the read queue
742 * @return true if read queue is full, false otherwise
743 */
744 bool readQueueFull(unsigned int pktCount) const;
745
746 /**
747 * Check if the write queue has room for more entries
748 *
749 * @param pktCount The number of entries needed in the write queue
750 * @return true if write queue is full, false otherwise
751 */
752 bool writeQueueFull(unsigned int pktCount) const;
753
754 /**
755 * When a new read comes in, first check if the write q has a
756 * pending request to the same address.\ If not, decode the
757 * address to populate rank/bank/row, create one or mutliple
758 * "dram_pkt", and push them to the back of the read queue.\
759 * If this is the only
760 * read request in the system, schedule an event to start
761 * servicing it.
762 *
763 * @param pkt The request packet from the outside world
764 * @param pktCount The number of DRAM bursts the pkt
765 * translate to. If pkt size is larger then one full burst,
766 * then pktCount is greater than one.
767 */
768 void addToReadQueue(PacketPtr pkt, unsigned int pktCount);
769
770 /**
771 * Decode the incoming pkt, create a dram_pkt and push to the
772 * back of the write queue. \If the write q length is more than
773 * the threshold specified by the user, ie the queue is beginning
774 * to get full, stop reads, and start draining writes.
775 *
776 * @param pkt The request packet from the outside world
777 * @param pktCount The number of DRAM bursts the pkt
778 * translate to. If pkt size is larger then one full burst,
779 * then pktCount is greater than one.
780 */
781 void addToWriteQueue(PacketPtr pkt, unsigned int pktCount);
782
783 /**
784 * Actually do the DRAM access - figure out the latency it
785 * will take to service the req based on bank state, channel state etc
786 * and then update those states to account for this request.\ Based
787 * on this, update the packet's "readyTime" and move it to the
788 * response q from where it will eventually go back to the outside
789 * world.
790 *
791 * @param pkt The DRAM packet created from the outside world pkt
792 */
793 void doDRAMAccess(DRAMPacket* dram_pkt);
794
795 /**
796 * When a packet reaches its "readyTime" in the response Q,
797 * use the "access()" method in AbstractMemory to actually
798 * create the response packet, and send it back to the outside
799 * world requestor.
800 *
801 * @param pkt The packet from the outside world
802 * @param static_latency Static latency to add before sending the packet
803 */
804 void accessAndRespond(PacketPtr pkt, Tick static_latency);
805
806 /**
807 * Address decoder to figure out physical mapping onto ranks,
808 * banks, and rows. This function is called multiple times on the same
809 * system packet if the pakcet is larger than burst of the memory. The
810 * dramPktAddr is used for the offset within the packet.
811 *
812 * @param pkt The packet from the outside world
813 * @param dramPktAddr The starting address of the DRAM packet
814 * @param size The size of the DRAM packet in bytes
815 * @param isRead Is the request for a read or a write to DRAM
816 * @return A DRAMPacket pointer with the decoded information
817 */
818 DRAMPacket* decodeAddr(const PacketPtr pkt, Addr dramPktAddr,
819 unsigned int size, bool isRead) const;
820
821 /**
822 * Get an address in a dense range which starts from 0. The input
823 * address is the physical address of the request in an address
824 * space that contains other SimObjects apart from this
825 * controller.
826 *
827 * @param addr The intput address which should be in the addrRange
828 * @return An address in the continues range [0, max)
829 */
830 Addr getCtrlAddr(Addr addr)
831 {
832 return range.getOffset(addr);
833 }
834
835 /**
836 * The memory schduler/arbiter - picks which request needs to
837 * go next, based on the specified policy such as FCFS or FR-FCFS
838 * and moves it to the head of the queue.
839 * Prioritizes accesses to the same rank as previous burst unless
840 * controller is switching command type.
841 *
842 * @param queue Queued requests to consider
843 * @param extra_col_delay Any extra delay due to a read/write switch
844 * @return an iterator to the selected packet, else queue.end()
845 */
846 DRAMPacketQueue::iterator chooseNext(DRAMPacketQueue& queue,
847 Tick extra_col_delay);
848
849 /**
850 * For FR-FCFS policy reorder the read/write queue depending on row buffer
851 * hits and earliest bursts available in DRAM
852 *
853 * @param queue Queued requests to consider
854 * @param extra_col_delay Any extra delay due to a read/write switch
855 * @return an iterator to the selected packet, else queue.end()
856 */
857 DRAMPacketQueue::iterator chooseNextFRFCFS(DRAMPacketQueue& queue,
858 Tick extra_col_delay);
859
860 /**
861 * Find which are the earliest banks ready to issue an activate
862 * for the enqueued requests. Assumes maximum of 32 banks per rank
863 * Also checks if the bank is already prepped.
864 *
865 * @param queue Queued requests to consider
866 * @param min_col_at time of seamless burst command
867 * @return One-hot encoded mask of bank indices
868 * @return boolean indicating burst can issue seamlessly, with no gaps
869 */
870 std::pair<std::vector<uint32_t>, bool>
871 minBankPrep(const DRAMPacketQueue& queue, Tick min_col_at) const;
872
873 /**
874 * Keep track of when row activations happen, in order to enforce
875 * the maximum number of activations in the activation window. The
876 * method updates the time that the banks become available based
877 * on the current limits.
878 *
879 * @param rank_ref Reference to the rank
880 * @param bank_ref Reference to the bank
881 * @param act_tick Time when the activation takes place
882 * @param row Index of the row
883 */
884 void activateBank(Rank& rank_ref, Bank& bank_ref, Tick act_tick,
885 uint32_t row);
886
887 /**
888 * Precharge a given bank and also update when the precharge is
889 * done. This will also deal with any stats related to the
890 * accesses to the open page.
891 *
892 * @param rank_ref The rank to precharge
893 * @param bank_ref The bank to precharge
894 * @param pre_at Time when the precharge takes place
895 * @param trace Is this an auto precharge then do not add to trace
896 */
897 void prechargeBank(Rank& rank_ref, Bank& bank_ref,
898 Tick pre_at, bool trace = true);
899
900 /**
901 * Used for debugging to observe the contents of the queues.
902 */
903 void printQs() const;
904
905 /**
906 * Burst-align an address.
907 *
908 * @param addr The potentially unaligned address
909 *
910 * @return An address aligned to a DRAM burst
911 */
912 Addr burstAlign(Addr addr) const { return (addr & ~(Addr(burstSize - 1))); }
913
914 /**
915 * The controller's main read and write queues, with support for QoS reordering
916 */
917 std::vector<DRAMPacketQueue> readQueue;
918 std::vector<DRAMPacketQueue> writeQueue;
919
920 /**
921 * To avoid iterating over the write queue to check for
922 * overlapping transactions, maintain a set of burst addresses
923 * that are currently queued. Since we merge writes to the same
924 * location we never have more than one address to the same burst
925 * address.
926 */
927 std::unordered_set<Addr> isInWriteQueue;
928
929 /**
930 * Response queue where read packets wait after we're done working
931 * with them, but it's not time to send the response yet. The
932 * responses are stored separately mostly to keep the code clean
933 * and help with events scheduling. For all logical purposes such
934 * as sizing the read queue, this and the main read queue need to
935 * be added together.
936 */
937 std::deque<DRAMPacket*> respQueue;
938
939 /**
940 * Vector of ranks
941 */
942 std::vector<Rank*> ranks;
943
944 /**
945 * The following are basic design parameters of the memory
946 * controller, and are initialized based on parameter values.
947 * The rowsPerBank is determined based on the capacity, number of
948 * ranks and banks, the burst size, and the row buffer size.
949 */
950 const uint32_t deviceSize;
951 const uint32_t deviceBusWidth;
952 const uint32_t burstLength;
953 const uint32_t deviceRowBufferSize;
954 const uint32_t devicesPerRank;
955 const uint32_t burstSize;
956 const uint32_t rowBufferSize;
957 const uint32_t columnsPerRowBuffer;
958 const uint32_t columnsPerStripe;
959 const uint32_t ranksPerChannel;
960 const uint32_t bankGroupsPerRank;
961 const bool bankGroupArch;
962 const uint32_t banksPerRank;
963 uint32_t rowsPerBank;
964 const uint32_t readBufferSize;
965 const uint32_t writeBufferSize;
966 const uint32_t writeHighThreshold;
967 const uint32_t writeLowThreshold;
968 const uint32_t minWritesPerSwitch;
969 uint32_t writesThisTime;
970 uint32_t readsThisTime;
971
972 /**
973 * Basic memory timing parameters initialized based on parameter
974 * values.
975 */
976 const Tick M5_CLASS_VAR_USED tCK;
977 const Tick tRTW;
978 const Tick tCS;
979 const Tick tBURST;
980 const Tick tCCD_L_WR;
981 const Tick tCCD_L;
982 const Tick tRCD;
983 const Tick tCL;
984 const Tick tRP;
985 const Tick tRAS;
986 const Tick tWR;
987 const Tick tRTP;
988 const Tick tRFC;
989 const Tick tREFI;
990 const Tick tRRD;
991 const Tick tRRD_L;
992 const Tick tXAW;
993 const Tick tXP;
994 const Tick tXS;
995 const uint32_t activationLimit;
996 const Tick rankToRankDly;
997 const Tick wrToRdDly;
998 const Tick rdToWrDly;
999
1000 /**
1001 * Memory controller configuration initialized based on parameter
1002 * values.
1003 */
1004 Enums::MemSched memSchedPolicy;
1005 Enums::AddrMap addrMapping;
1006 Enums::PageManage pageMgmt;
1007
1008 /**
1009 * Max column accesses (read and write) per row, before forcefully
1010 * closing it.
1011 */
1012 const uint32_t maxAccessesPerRow;
1013
1014 /**
1015 * Pipeline latency of the controller frontend. The frontend
1016 * contribution is added to writes (that complete when they are in
1017 * the write buffer) and reads that are serviced the write buffer.
1018 */
1019 const Tick frontendLatency;
1020
1021 /**
1022 * Pipeline latency of the backend and PHY. Along with the
1023 * frontend contribution, this latency is added to reads serviced
1024 * by the DRAM.
1025 */
1026 const Tick backendLatency;
1027
1028 /**
1029 * Till when must we wait before issuing next RD/WR burst?
1030 */
1031 Tick nextBurstAt;
1032
1033 Tick prevArrival;
1034
1035 /**
1036 * The soonest you have to start thinking about the next request
1037 * is the longest access time that can occur before
1038 * nextBurstAt. Assuming you need to precharge, open a new row,
1039 * and access, it is tRP + tRCD + tCL.
1040 */
1041 Tick nextReqTime;
1042
1043 /** All statistics that the model needs to capture */
1044 struct DRAMStats : public Stats::Group {
1045 DRAMStats(DRAMCtrl &dram);
1046
1047 void regStats() override;
1048 void resetStats() override;
1049
1050 DRAMCtrl &dram;
1051
1052 Stats::Scalar readReqs;
1053 Stats::Scalar writeReqs;
1054 Stats::Scalar readBursts;
1055 Stats::Scalar writeBursts;
1056 Stats::Scalar servicedByWrQ;
1057 Stats::Scalar mergedWrBursts;
1058 Stats::Scalar neitherReadNorWriteReqs;
1059 Stats::Vector perBankRdBursts;
1060 Stats::Vector perBankWrBursts;
1061
1062 // Average queue lengths
1063 Stats::Average avgRdQLen;
1064 Stats::Average avgWrQLen;
1065
1066 // Latencies summed over all requests
1067 Stats::Scalar totQLat;
1068 Stats::Scalar totBusLat;
1069 Stats::Scalar totMemAccLat;
1070
1071 // Average latencies per request
1072 Stats::Formula avgQLat;
1073 Stats::Formula avgBusLat;
1074 Stats::Formula avgMemAccLat;
1075
1076 Stats::Scalar numRdRetry;
1077 Stats::Scalar numWrRetry;
1078
1079 // Row hit count and rate
1080 Stats::Scalar readRowHits;
1081 Stats::Scalar writeRowHits;
1082 Stats::Formula readRowHitRate;
1083 Stats::Formula writeRowHitRate;
1084
1085 Stats::Vector readPktSize;
1086 Stats::Vector writePktSize;
1087 Stats::Vector rdQLenPdf;
1088 Stats::Vector wrQLenPdf;
1089 Stats::Histogram bytesPerActivate;
1090 Stats::Histogram rdPerTurnAround;
1091 Stats::Histogram wrPerTurnAround;
1092
1093 Stats::Scalar bytesReadDRAM;
1094 Stats::Scalar bytesReadWrQ;
1095 Stats::Scalar bytesWritten;
1096 Stats::Scalar bytesReadSys;
1097 Stats::Scalar bytesWrittenSys;
1098
1099 // Average bandwidth
1100 Stats::Formula avgRdBW;
1101 Stats::Formula avgWrBW;
1102 Stats::Formula avgRdBWSys;
1103 Stats::Formula avgWrBWSys;
1104 Stats::Formula peakBW;
1105
1106 Stats::Formula busUtil;
1107 Stats::Formula busUtilRead;
1108 Stats::Formula busUtilWrite;
1109
1110 Stats::Scalar totGap;
1111 Stats::Formula avgGap;
1112
1113 // per-master bytes read and written to memory
1114 Stats::Vector masterReadBytes;
1115 Stats::Vector masterWriteBytes;
1116
1117 // per-master bytes read and written to memory rate
1118 Stats::Formula masterReadRate;
1119 Stats::Formula masterWriteRate;
1120
1121 // per-master read and write serviced memory accesses
1122 Stats::Vector masterReadAccesses;
1123 Stats::Vector masterWriteAccesses;
1124
1125 // per-master read and write total memory access latency
1126 Stats::Vector masterReadTotalLat;
1127 Stats::Vector masterWriteTotalLat;
1128
1129 // per-master raed and write average memory access latency
1130 Stats::Formula masterReadAvgLat;
1131 Stats::Formula masterWriteAvgLat;
1132
1133 // DRAM Power Calculation
1134 Stats::Formula pageHitRate;
1135 };
1136
1137 DRAMStats stats;
1138
1139 // Holds the value of the rank of burst issued
1140 uint8_t activeRank;
1141
1142 // timestamp offset
1143 uint64_t timeStampOffset;
1144
1145 /** The time when stats were last reset used to calculate average power */
1146 Tick lastStatsResetTick;
1147
1148 /** Enable or disable DRAM powerdown states. */
1149 bool enableDRAMPowerdown;
1150
1151 /**
1152 * Upstream caches need this packet until true is returned, so
1153 * hold it for deletion until a subsequent call
1154 */
1155 std::unique_ptr<Packet> pendingDelete;
1156
1157 /**
1158 * This function increments the energy when called. If stats are
1159 * dumped periodically, note accumulated energy values will
1160 * appear in the stats (even if the stats are reset). This is a
1161 * result of the energy values coming from DRAMPower, and there
1162 * is currently no support for resetting the state.
1163 *
1164 * @param rank Current rank
1165 */
1166 void updatePowerStats(Rank& rank_ref);
1167
1168 /**
1169 * Function for sorting Command structures based on timeStamp
1170 *
1171 * @param a Memory Command
1172 * @param next Memory Command
1173 * @return true if timeStamp of Command 1 < timeStamp of Command 2
1174 */
1175 static bool sortTime(const Command& cmd, const Command& cmd_next) {
1176 return cmd.timeStamp < cmd_next.timeStamp;
1177 };
1178
1179 public:
1180 DRAMCtrl(const DRAMCtrlParams* p);
1181
1182 DrainState drain() override;
1183
1184 Port &getPort(const std::string &if_name,
1185 PortID idx=InvalidPortID) override;
1186
1187 virtual void init() override;
1188 virtual void startup() override;
1189 virtual void drainResume() override;
1190
1191 /**
1192 * Return true once refresh is complete for all ranks and there are no
1193 * additional commands enqueued. (only evaluated when draining)
1194 * This will ensure that all banks are closed, power state is IDLE, and
1195 * power stats have been updated
1196 *
1197 * @return true if all ranks have refreshed, with no commands enqueued
1198 *
1199 */
1200 bool allRanksDrained() const;
1201
1202 protected:
1203
1204 Tick recvAtomic(PacketPtr pkt);
1205 void recvFunctional(PacketPtr pkt);
1206 bool recvTimingReq(PacketPtr pkt);
1207
1208 };
1209
1210 #endif //__MEM_DRAM_CTRL_HH__