2 * Copyright (c) 2012-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
47 * DRAMCtrl declaration
50 #ifndef __MEM_DRAM_CTRL_HH__
51 #define __MEM_DRAM_CTRL_HH__
55 #include "base/statistics.hh"
56 #include "enums/AddrMap.hh"
57 #include "enums/MemSched.hh"
58 #include "enums/PageManage.hh"
59 #include "mem/abstract_mem.hh"
60 #include "mem/qport.hh"
61 #include "params/DRAMCtrl.hh"
62 #include "sim/eventq.hh"
63 #include "mem/drampower.hh"
66 * The DRAM controller is a single-channel memory controller capturing
67 * the most important timing constraints associated with a
68 * contemporary DRAM. For multi-channel memory systems, the controller
69 * is combined with a crossbar model, with the channel address
70 * interleaving taking part in the crossbar.
72 * As a basic design principle, this controller
73 * model is not cycle callable, but instead uses events to: 1) decide
74 * when new decisions can be made, 2) when resources become available,
75 * 3) when things are to be considered done, and 4) when to send
76 * things back. Through these simple principles, the model delivers
77 * high performance, and lots of flexibility, allowing users to
78 * evaluate the system impact of a wide range of memory technologies,
79 * such as DDR3/4, LPDDR2/3/4, WideIO1/2, HBM and HMC.
81 * For more details, please see Hansson et al, "Simulating DRAM
82 * controllers for future system architecture exploration",
83 * Proc. ISPASS, 2014. If you use this model as part of your research
84 * please cite the paper.
86 class DRAMCtrl : public AbstractMemory
91 // For now, make use of a queued slave port to avoid dealing with
92 // flow control for the responses being sent back
93 class MemoryPort : public QueuedSlavePort
96 SlavePacketQueue queue;
101 MemoryPort(const std::string& name, DRAMCtrl& _memory);
105 Tick recvAtomic(PacketPtr pkt);
107 void recvFunctional(PacketPtr pkt);
109 bool recvTimingReq(PacketPtr);
111 virtual AddrRangeList getAddrRanges() const;
116 * Our incoming port, for a multi-ported controller add a crossbar
122 * Remember if we have to retry a request when available.
128 * Bus state used to control the read/write switching and drive
129 * the scheduling of the next request.
140 /** List to keep track of activate ticks */
141 std::vector<std::deque<Tick>> actTicks;
144 * A basic class to track the bank state, i.e. what row is
145 * currently open (if any), when is the bank free to accept a new
146 * column (read/write) command, when can it be precharged, and
147 * when can it be activated.
149 * The bank also keeps track of how many bytes have been accessed
150 * in the open row since it was opened.
157 static const uint32_t NO_ROW = -1;
168 uint32_t rowAccesses;
169 uint32_t bytesAccessed;
172 openRow(NO_ROW), rank(0), bank(0), bankgr(0),
173 colAllowedAt(0), preAllowedAt(0), actAllowedAt(0),
174 rowAccesses(0), bytesAccessed(0)
179 * A burst helper helps organize and manage a packet that is larger than
180 * the DRAM burst size. A system packet that is larger than the burst size
181 * is split into multiple DRAM packets and all those DRAM packets point to
182 * a single burst helper such that we know when the whole packet is served.
188 /** Number of DRAM bursts requred for a system packet **/
189 const unsigned int burstCount;
191 /** Number of DRAM bursts serviced so far for a system packet **/
192 unsigned int burstsServiced;
194 BurstHelper(unsigned int _burstCount)
195 : burstCount(_burstCount), burstsServiced(0)
200 * A DRAM packet stores packets along with the timestamp of when
201 * the packet entered the queue, and also the decoded address.
207 /** When did request enter the controller */
208 const Tick entryTime;
210 /** When will request leave the controller */
213 /** This comes from the outside world */
218 /** Will be populated by address decoder */
224 * Bank id is calculated considering banks in all the ranks
225 * eg: 2 ranks each with 8 banks, then bankId = 0 --> rank0, bank0 and
226 * bankId = 8 --> rank1, bank0
228 const uint16_t bankId;
231 * The starting address of the DRAM packet.
232 * This address could be unaligned to burst size boundaries. The
233 * reason is to keep the address offset so we can accurately check
234 * incoming read packets with packets in the write queue.
239 * The size of this dram packet in bytes
240 * It is always equal or smaller than DRAM burst size
245 * A pointer to the BurstHelper if this DRAMPacket is a split packet
246 * If not a split packet (common case), this is set to NULL
248 BurstHelper* burstHelper;
251 DRAMPacket(PacketPtr _pkt, bool is_read, uint8_t _rank, uint8_t _bank,
252 uint32_t _row, uint16_t bank_id, Addr _addr,
253 unsigned int _size, Bank& bank_ref)
254 : entryTime(curTick()), readyTime(curTick()),
255 pkt(_pkt), isRead(is_read), rank(_rank), bank(_bank), row(_row),
256 bankId(bank_id), addr(_addr), size(_size), burstHelper(NULL),
263 * Bunch of things requires to setup "events" in gem5
264 * When event "respondEvent" occurs for example, the method
265 * processRespondEvent is called; no parameters are allowed
268 void processNextReqEvent();
269 EventWrapper<DRAMCtrl,&DRAMCtrl::processNextReqEvent> nextReqEvent;
271 void processRespondEvent();
272 EventWrapper<DRAMCtrl, &DRAMCtrl::processRespondEvent> respondEvent;
274 void processActivateEvent();
275 EventWrapper<DRAMCtrl, &DRAMCtrl::processActivateEvent> activateEvent;
277 void processPrechargeEvent();
278 EventWrapper<DRAMCtrl, &DRAMCtrl::processPrechargeEvent> prechargeEvent;
280 void processRefreshEvent();
281 EventWrapper<DRAMCtrl, &DRAMCtrl::processRefreshEvent> refreshEvent;
283 void processPowerEvent();
284 EventWrapper<DRAMCtrl,&DRAMCtrl::processPowerEvent> powerEvent;
287 * Check if the read queue has room for more entries
289 * @param pktCount The number of entries needed in the read queue
290 * @return true if read queue is full, false otherwise
292 bool readQueueFull(unsigned int pktCount) const;
295 * Check if the write queue has room for more entries
297 * @param pktCount The number of entries needed in the write queue
298 * @return true if write queue is full, false otherwise
300 bool writeQueueFull(unsigned int pktCount) const;
303 * When a new read comes in, first check if the write q has a
304 * pending request to the same address.\ If not, decode the
305 * address to populate rank/bank/row, create one or mutliple
306 * "dram_pkt", and push them to the back of the read queue.\
307 * If this is the only
308 * read request in the system, schedule an event to start
311 * @param pkt The request packet from the outside world
312 * @param pktCount The number of DRAM bursts the pkt
313 * translate to. If pkt size is larger then one full burst,
314 * then pktCount is greater than one.
316 void addToReadQueue(PacketPtr pkt, unsigned int pktCount);
319 * Decode the incoming pkt, create a dram_pkt and push to the
320 * back of the write queue. \If the write q length is more than
321 * the threshold specified by the user, ie the queue is beginning
322 * to get full, stop reads, and start draining writes.
324 * @param pkt The request packet from the outside world
325 * @param pktCount The number of DRAM bursts the pkt
326 * translate to. If pkt size is larger then one full burst,
327 * then pktCount is greater than one.
329 void addToWriteQueue(PacketPtr pkt, unsigned int pktCount);
332 * Actually do the DRAM access - figure out the latency it
333 * will take to service the req based on bank state, channel state etc
334 * and then update those states to account for this request.\ Based
335 * on this, update the packet's "readyTime" and move it to the
336 * response q from where it will eventually go back to the outside
339 * @param pkt The DRAM packet created from the outside world pkt
341 void doDRAMAccess(DRAMPacket* dram_pkt);
344 * When a packet reaches its "readyTime" in the response Q,
345 * use the "access()" method in AbstractMemory to actually
346 * create the response packet, and send it back to the outside
349 * @param pkt The packet from the outside world
350 * @param static_latency Static latency to add before sending the packet
352 void accessAndRespond(PacketPtr pkt, Tick static_latency);
355 * Address decoder to figure out physical mapping onto ranks,
356 * banks, and rows. This function is called multiple times on the same
357 * system packet if the pakcet is larger than burst of the memory. The
358 * dramPktAddr is used for the offset within the packet.
360 * @param pkt The packet from the outside world
361 * @param dramPktAddr The starting address of the DRAM packet
362 * @param size The size of the DRAM packet in bytes
363 * @param isRead Is the request for a read or a write to DRAM
364 * @return A DRAMPacket pointer with the decoded information
366 DRAMPacket* decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned int size,
370 * The memory schduler/arbiter - picks which request needs to
371 * go next, based on the specified policy such as FCFS or FR-FCFS
372 * and moves it to the head of the queue.
373 * Prioritizes accesses to the same rank as previous burst unless
374 * controller is switching command type.
376 * @param queue Queued requests to consider
377 * @param switched_cmd_type Command type is changing
379 void chooseNext(std::deque<DRAMPacket*>& queue, bool switched_cmd_type);
382 * For FR-FCFS policy reorder the read/write queue depending on row buffer
383 * hits and earliest banks available in DRAM
384 * Prioritizes accesses to the same rank as previous burst unless
385 * controller is switching command type.
387 * @param queue Queued requests to consider
388 * @param switched_cmd_type Command type is changing
390 void reorderQueue(std::deque<DRAMPacket*>& queue, bool switched_cmd_type);
393 * Find which are the earliest banks ready to issue an activate
394 * for the enqueued requests. Assumes maximum of 64 banks per DIMM
395 * Also checks if the bank is already prepped.
397 * @param queue Queued requests to consider
398 * @param switched_cmd_type Command type is changing
399 * @return One-hot encoded mask of bank indices
401 uint64_t minBankPrep(const std::deque<DRAMPacket*>& queue,
402 bool switched_cmd_type) const;
405 * Keep track of when row activations happen, in order to enforce
406 * the maximum number of activations in the activation window. The
407 * method updates the time that the banks become available based
408 * on the current limits.
410 * @param bank Reference to the bank
411 * @param act_tick Time when the activation takes place
412 * @param row Index of the row
414 void activateBank(Bank& bank, Tick act_tick, uint32_t row);
417 * Precharge a given bank and also update when the precharge is
418 * done. This will also deal with any stats related to the
419 * accesses to the open page.
421 * @param bank_ref The bank to precharge
422 * @param pre_at Time when the precharge takes place
423 * @param trace Is this an auto precharge then do not add to trace
425 void prechargeBank(Bank& bank_ref, Tick pre_at, bool trace = true);
428 * Used for debugging to observe the contents of the queues.
430 void printQs() const;
433 * The controller's main read and write queues
435 std::deque<DRAMPacket*> readQueue;
436 std::deque<DRAMPacket*> writeQueue;
439 * Response queue where read packets wait after we're done working
440 * with them, but it's not time to send the response yet. The
441 * responses are stored seperately mostly to keep the code clean
442 * and help with events scheduling. For all logical purposes such
443 * as sizing the read queue, this and the main read queue need to
446 std::deque<DRAMPacket*> respQueue;
449 * If we need to drain, keep the drain manager around until we're
452 DrainManager *drainManager;
455 * Multi-dimensional vector of banks, first dimension is ranks,
458 std::vector<std::vector<Bank> > banks;
461 * The following are basic design parameters of the memory
462 * controller, and are initialized based on parameter values.
463 * The rowsPerBank is determined based on the capacity, number of
464 * ranks and banks, the burst size, and the row buffer size.
466 const uint32_t deviceBusWidth;
467 const uint32_t burstLength;
468 const uint32_t deviceRowBufferSize;
469 const uint32_t devicesPerRank;
470 const uint32_t burstSize;
471 const uint32_t rowBufferSize;
472 const uint32_t columnsPerRowBuffer;
473 const uint32_t columnsPerStripe;
474 const uint32_t ranksPerChannel;
475 const uint32_t bankGroupsPerRank;
476 const bool bankGroupArch;
477 const uint32_t banksPerRank;
478 const uint32_t channels;
479 uint32_t rowsPerBank;
480 const uint32_t readBufferSize;
481 const uint32_t writeBufferSize;
482 const uint32_t writeHighThreshold;
483 const uint32_t writeLowThreshold;
484 const uint32_t minWritesPerSwitch;
485 uint32_t writesThisTime;
486 uint32_t readsThisTime;
489 * Basic memory timing parameters initialized based on parameter
492 const Tick M5_CLASS_VAR_USED tCK;
509 const uint32_t activationLimit;
512 * Memory controller configuration initialized based on parameter
515 Enums::MemSched memSchedPolicy;
516 Enums::AddrMap addrMapping;
517 Enums::PageManage pageMgmt;
520 * Max column accesses (read and write) per row, before forefully
523 const uint32_t maxAccessesPerRow;
526 * Pipeline latency of the controller frontend. The frontend
527 * contribution is added to writes (that complete when they are in
528 * the write buffer) and reads that are serviced the write buffer.
530 const Tick frontendLatency;
533 * Pipeline latency of the backend and PHY. Along with the
534 * frontend contribution, this latency is added to reads serviced
537 const Tick backendLatency;
540 * Till when has the main data bus been spoken for already?
545 * Keep track of when a refresh is due.
550 * The refresh state is used to control the progress of the
551 * refresh scheduling. When normal operation is in progress the
552 * refresh state is idle. From there, it progresses to the refresh
553 * drain state once tREFI has passed. The refresh drain state
554 * captures the DRAM row active state, as it will stay there until
555 * all ongoing accesses complete. Thereafter all banks are
556 * precharged, and lastly, the DRAM is refreshed.
565 RefreshState refreshState;
568 * The power state captures the different operational states of
569 * the DRAM and interacts with the bus read/write state machine,
570 * and the refresh state machine. In the idle state all banks are
571 * precharged. From there we either go to an auto refresh (as
572 * determined by the refresh state machine), or to a precharge
573 * power down mode. From idle the memory can also go to the active
574 * state (with one or more banks active), and in turn from there
575 * to active power down. At the moment we do not capture the deep
576 * power down and self-refresh state.
587 * Since we are taking decisions out of order, we need to keep
588 * track of what power transition is happening at what time, such
589 * that we can go back in time and change history. For example, if
590 * we precharge all banks and schedule going to the idle state, we
591 * might at a later point decide to activate a bank before the
592 * transition to idle would have taken place.
594 PowerState pwrStateTrans;
597 * Current power state.
602 * Schedule a power state transition in the future, and
603 * potentially override an already scheduled transition.
605 * @param pwr_state Power state to transition to
606 * @param tick Tick when transition should take place
608 void schedulePowerEvent(PowerState pwr_state, Tick tick);
613 * The soonest you have to start thinking about the next request
614 * is the longest access time that can occur before
615 * busBusyUntil. Assuming you need to precharge, open a new row,
616 * and access, it is tRP + tRCD + tCL.
620 // All statistics that the model needs to capture
621 Stats::Scalar readReqs;
622 Stats::Scalar writeReqs;
623 Stats::Scalar readBursts;
624 Stats::Scalar writeBursts;
625 Stats::Scalar bytesReadDRAM;
626 Stats::Scalar bytesReadWrQ;
627 Stats::Scalar bytesWritten;
628 Stats::Scalar bytesReadSys;
629 Stats::Scalar bytesWrittenSys;
630 Stats::Scalar servicedByWrQ;
631 Stats::Scalar mergedWrBursts;
632 Stats::Scalar neitherReadNorWrite;
633 Stats::Vector perBankRdBursts;
634 Stats::Vector perBankWrBursts;
635 Stats::Scalar numRdRetry;
636 Stats::Scalar numWrRetry;
637 Stats::Scalar totGap;
638 Stats::Vector readPktSize;
639 Stats::Vector writePktSize;
640 Stats::Vector rdQLenPdf;
641 Stats::Vector wrQLenPdf;
642 Stats::Histogram bytesPerActivate;
643 Stats::Histogram rdPerTurnAround;
644 Stats::Histogram wrPerTurnAround;
646 // Latencies summed over all requests
647 Stats::Scalar totQLat;
648 Stats::Scalar totMemAccLat;
649 Stats::Scalar totBusLat;
651 // Average latencies per request
652 Stats::Formula avgQLat;
653 Stats::Formula avgBusLat;
654 Stats::Formula avgMemAccLat;
657 Stats::Formula avgRdBW;
658 Stats::Formula avgWrBW;
659 Stats::Formula avgRdBWSys;
660 Stats::Formula avgWrBWSys;
661 Stats::Formula peakBW;
662 Stats::Formula busUtil;
663 Stats::Formula busUtilRead;
664 Stats::Formula busUtilWrite;
666 // Average queue lengths
667 Stats::Average avgRdQLen;
668 Stats::Average avgWrQLen;
670 // Row hit count and rate
671 Stats::Scalar readRowHits;
672 Stats::Scalar writeRowHits;
673 Stats::Formula readRowHitRate;
674 Stats::Formula writeRowHitRate;
675 Stats::Formula avgGap;
677 // DRAM Power Calculation
678 Stats::Formula pageHitRate;
679 Stats::Vector pwrStateTime;
682 Stats::Vector actEnergy;
683 Stats::Vector preEnergy;
684 Stats::Vector readEnergy;
685 Stats::Vector writeEnergy;
686 Stats::Vector refreshEnergy;
687 //Active Background Energy
688 Stats::Vector actBackEnergy;
689 //Precharge Background Energy
690 Stats::Vector preBackEnergy;
691 Stats::Vector totalEnergy;
693 Stats::Vector averagePower;
695 // Track when we transitioned to the current power state
698 // To track number of banks which are currently active
699 unsigned int numBanksActive;
701 // Holds the value of the rank of burst issued
705 uint64_t timeStampOffset;
707 /** @todo this is a temporary workaround until the 4-phase code is
708 * committed. upstream caches needs this packet until true is returned, so
709 * hold onto it for deletion until a subsequent call
711 std::vector<PacketPtr> pendingDelete;
713 // One DRAMPower instance per rank
714 std::vector<DRAMPower> rankPower;
717 * This function increments the energy when called. If stats are
718 * dumped periodically, note accumulated energy values will
719 * appear in the stats (even if the stats are reset). This is a
720 * result of the energy values coming from DRAMPower, and there
721 * is currently no support for resetting the state.
723 * @param rank Currrent rank
725 void updatePowerStats(uint8_t rank);
728 * Function for sorting commands in the command list of DRAMPower.
730 * @param a Memory Command in command list of DRAMPower library
731 * @param next Memory Command in command list of DRAMPower
732 * @return true if timestamp of Command 1 < timestamp of Command 2
734 static bool sortTime(const Data::MemCommand& m1,
735 const Data::MemCommand& m2) {
736 return m1.getTime() < m2.getTime();
744 DRAMCtrl(const DRAMCtrlParams* p);
746 unsigned int drain(DrainManager* dm);
748 virtual BaseSlavePort& getSlavePort(const std::string& if_name,
749 PortID idx = InvalidPortID);
752 virtual void startup();
756 Tick recvAtomic(PacketPtr pkt);
757 void recvFunctional(PacketPtr pkt);
758 bool recvTimingReq(PacketPtr pkt);
762 #endif //__MEM_DRAM_CTRL_HH__