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"
65 * The DRAM controller is a basic single-channel memory controller
66 * aiming to mimic a high-level DRAM controller and the most important
67 * timing constraints associated with the DRAM. The focus is really on
68 * modelling the impact on the system rather than the DRAM itself,
69 * hence the focus is on the controller model and not on the
70 * memory. By adhering to the correct timing constraints, ultimately
71 * there is no need for a memory model in addition to the controller
74 * As a basic design principle, this controller is not cycle callable,
75 * but instead uses events to decide when new decisions can be made,
76 * when resources become available, when things are to be considered
77 * done, and when to send things back. Through these simple
78 * principles, we achieve a performant model that is not
79 * cycle-accurate, but enables us to evaluate the system impact of a
80 * wide range of memory technologies, and also collect statistics
81 * about the use of the memory.
83 class DRAMCtrl : public AbstractMemory
88 // For now, make use of a queued slave port to avoid dealing with
89 // flow control for the responses being sent back
90 class MemoryPort : public QueuedSlavePort
93 SlavePacketQueue queue;
98 MemoryPort(const std::string& name, DRAMCtrl& _memory);
102 Tick recvAtomic(PacketPtr pkt);
104 void recvFunctional(PacketPtr pkt);
106 bool recvTimingReq(PacketPtr);
108 virtual AddrRangeList getAddrRanges() const;
113 * Our incoming port, for a multi-ported controller add a crossbar
119 * Remember if we have to retry a request when available.
125 * Remember that a row buffer hit occured
130 * Bus state used to control the read/write switching and drive
131 * the scheduling of the next request.
142 /** List to keep track of activate ticks */
143 std::vector<std::deque<Tick>> actTicks;
146 * A basic class to track the bank state indirectly via times
147 * "freeAt" and "tRASDoneAt" and what page is currently open. The
148 * bank also keeps track of how many bytes have been accessed in
149 * the open row since it was opened.
156 static const uint32_t INVALID_ROW = -1;
164 uint32_t rowAccesses;
165 uint32_t bytesAccessed;
168 openRow(INVALID_ROW), freeAt(0), tRASDoneAt(0), actAllowedAt(0),
169 rowAccesses(0), bytesAccessed(0)
174 * A burst helper helps organize and manage a packet that is larger than
175 * the DRAM burst size. A system packet that is larger than the burst size
176 * is split into multiple DRAM packets and all those DRAM packets point to
177 * a single burst helper such that we know when the whole packet is served.
183 /** Number of DRAM bursts requred for a system packet **/
184 const unsigned int burstCount;
186 /** Number of DRAM bursts serviced so far for a system packet **/
187 unsigned int burstsServiced;
189 BurstHelper(unsigned int _burstCount)
190 : burstCount(_burstCount), burstsServiced(0)
195 * A DRAM packet stores packets along with the timestamp of when
196 * the packet entered the queue, and also the decoded address.
202 /** When did request enter the controller */
203 const Tick entryTime;
205 /** When will request leave the controller */
208 /** This comes from the outside world */
213 /** Will be populated by address decoder */
219 * Bank id is calculated considering banks in all the ranks
220 * eg: 2 ranks each with 8 banks, then bankId = 0 --> rank0, bank0 and
221 * bankId = 8 --> rank1, bank0
223 const uint16_t bankId;
226 * The starting address of the DRAM packet.
227 * This address could be unaligned to burst size boundaries. The
228 * reason is to keep the address offset so we can accurately check
229 * incoming read packets with packets in the write queue.
234 * The size of this dram packet in bytes
235 * It is always equal or smaller than DRAM burst size
240 * A pointer to the BurstHelper if this DRAMPacket is a split packet
241 * If not a split packet (common case), this is set to NULL
243 BurstHelper* burstHelper;
246 DRAMPacket(PacketPtr _pkt, bool is_read, uint8_t _rank, uint8_t _bank,
247 uint16_t _row, uint16_t bank_id, Addr _addr,
248 unsigned int _size, Bank& bank_ref)
249 : entryTime(curTick()), readyTime(curTick()),
250 pkt(_pkt), isRead(is_read), rank(_rank), bank(_bank), row(_row),
251 bankId(bank_id), addr(_addr), size(_size), burstHelper(NULL),
258 * Bunch of things requires to setup "events" in gem5
259 * When event "respondEvent" occurs for example, the method
260 * processRespondEvent is called; no parameters are allowed
263 void processRespondEvent();
264 EventWrapper<DRAMCtrl, &DRAMCtrl::processRespondEvent> respondEvent;
266 void processRefreshEvent();
267 EventWrapper<DRAMCtrl, &DRAMCtrl::processRefreshEvent> refreshEvent;
269 void processNextReqEvent();
270 EventWrapper<DRAMCtrl,&DRAMCtrl::processNextReqEvent> nextReqEvent;
274 * Check if the read queue has room for more entries
276 * @param pktCount The number of entries needed in the read queue
277 * @return true if read queue is full, false otherwise
279 bool readQueueFull(unsigned int pktCount) const;
282 * Check if the write queue has room for more entries
284 * @param pktCount The number of entries needed in the write queue
285 * @return true if write queue is full, false otherwise
287 bool writeQueueFull(unsigned int pktCount) const;
290 * When a new read comes in, first check if the write q has a
291 * pending request to the same address.\ If not, decode the
292 * address to populate rank/bank/row, create one or mutliple
293 * "dram_pkt", and push them to the back of the read queue.\
294 * If this is the only
295 * read request in the system, schedule an event to start
298 * @param pkt The request packet from the outside world
299 * @param pktCount The number of DRAM bursts the pkt
300 * translate to. If pkt size is larger then one full burst,
301 * then pktCount is greater than one.
303 void addToReadQueue(PacketPtr pkt, unsigned int pktCount);
306 * Decode the incoming pkt, create a dram_pkt and push to the
307 * back of the write queue. \If the write q length is more than
308 * the threshold specified by the user, ie the queue is beginning
309 * to get full, stop reads, and start draining writes.
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 addToWriteQueue(PacketPtr pkt, unsigned int pktCount);
319 * Actually do the DRAM access - figure out the latency it
320 * will take to service the req based on bank state, channel state etc
321 * and then update those states to account for this request.\ Based
322 * on this, update the packet's "readyTime" and move it to the
323 * response q from where it will eventually go back to the outside
326 * @param pkt The DRAM packet created from the outside world pkt
328 void doDRAMAccess(DRAMPacket* dram_pkt);
331 * When a packet reaches its "readyTime" in the response Q,
332 * use the "access()" method in AbstractMemory to actually
333 * create the response packet, and send it back to the outside
336 * @param pkt The packet from the outside world
337 * @param static_latency Static latency to add before sending the packet
339 void accessAndRespond(PacketPtr pkt, Tick static_latency);
342 * Address decoder to figure out physical mapping onto ranks,
343 * banks, and rows. This function is called multiple times on the same
344 * system packet if the pakcet is larger than burst of the memory. The
345 * dramPktAddr is used for the offset within the packet.
347 * @param pkt The packet from the outside world
348 * @param dramPktAddr The starting address of the DRAM packet
349 * @param size The size of the DRAM packet in bytes
350 * @param isRead Is the request for a read or a write to DRAM
351 * @return A DRAMPacket pointer with the decoded information
353 DRAMPacket* decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned int size,
357 * The memory schduler/arbiter - picks which request needs to
358 * go next, based on the specified policy such as FCFS or FR-FCFS
359 * and moves it to the head of the queue.
361 void chooseNext(std::deque<DRAMPacket*>& queue);
364 *Looks at the state of the banks, channels, row buffer hits etc
365 * to estimate how long a request will take to complete.
367 * @param dram_pkt The request for which we want to estimate latency
368 * @param inTime The tick at which you want to probe the memory
370 * @return A pair of ticks, one indicating how many ticks *after*
371 * inTime the request require, and the other indicating how
372 * much of that was just the bank access time, ignoring the
373 * ticks spent simply waiting for resources to become free
375 std::pair<Tick, Tick> estimateLatency(DRAMPacket* dram_pkt, Tick inTime);
378 * Move the request at the head of the read queue to the response
379 * queue, sorting by readyTime.\ If it is the only packet in the
380 * response queue, schedule a respond event to send it back to the
386 * For FR-FCFS policy reorder the read/write queue depending on row buffer
387 * hits and earliest banks available in DRAM
389 void reorderQueue(std::deque<DRAMPacket*>& queue);
392 * Looking at all banks, determine the moment in time when they
395 * @return The tick when all banks are free
397 Tick maxBankFreeAt() const;
400 * Find which are the earliest available banks for the enqueued
401 * requests. Assumes maximum of 64 banks per DIMM
403 * @param Queued requests to consider
404 * @return One-hot encoded mask of bank indices
406 uint64_t minBankFreeAt(const std::deque<DRAMPacket*>& queue) const;
409 * Keep track of when row activations happen, in order to enforce
410 * the maximum number of activations in the activation window. The
411 * method updates the time that the banks become available based
412 * on the current limits.
414 void recordActivate(Tick act_tick, uint8_t rank, uint8_t bank);
416 void printParams() const;
419 * Used for debugging to observe the contents of the queues.
421 void printQs() const;
424 * The controller's main read and write queues
426 std::deque<DRAMPacket*> readQueue;
427 std::deque<DRAMPacket*> writeQueue;
430 * Response queue where read packets wait after we're done working
431 * with them, but it's not time to send the response yet. The
432 * responses are stored seperately mostly to keep the code clean
433 * and help with events scheduling. For all logical purposes such
434 * as sizing the read queue, this and the main read queue need to
437 std::deque<DRAMPacket*> respQueue;
440 * If we need to drain, keep the drain manager around until we're
443 DrainManager *drainManager;
446 * Multi-dimensional vector of banks, first dimension is ranks,
449 std::vector<std::vector<Bank> > banks;
452 * The following are basic design parameters of the memory
453 * controller, and are initialized based on parameter values.
454 * The rowsPerBank is determined based on the capacity, number of
455 * ranks and banks, the burst size, and the row buffer size.
457 const uint32_t deviceBusWidth;
458 const uint32_t burstLength;
459 const uint32_t deviceRowBufferSize;
460 const uint32_t devicesPerRank;
461 const uint32_t burstSize;
462 const uint32_t rowBufferSize;
463 const uint32_t columnsPerRowBuffer;
464 const uint32_t ranksPerChannel;
465 const uint32_t banksPerRank;
466 const uint32_t channels;
467 uint32_t rowsPerBank;
468 const uint32_t readBufferSize;
469 const uint32_t writeBufferSize;
470 const uint32_t writeHighThreshold;
471 const uint32_t writeLowThreshold;
472 const uint32_t minWritesPerSwitch;
473 uint32_t writesThisTime;
474 uint32_t readsThisTime;
477 * Basic memory timing parameters initialized based on parameter
491 const uint32_t activationLimit;
494 * Memory controller configuration initialized based on parameter
497 Enums::MemSched memSchedPolicy;
498 Enums::AddrMap addrMapping;
499 Enums::PageManage pageMgmt;
502 * Max column accesses (read and write) per row, before forefully
505 const uint32_t maxAccessesPerRow;
508 * Pipeline latency of the controller frontend. The frontend
509 * contribution is added to writes (that complete when they are in
510 * the write buffer) and reads that are serviced the write buffer.
512 const Tick frontendLatency;
515 * Pipeline latency of the backend and PHY. Along with the
516 * frontend contribution, this latency is added to reads serviced
519 const Tick backendLatency;
522 * Till when has the main data bus been spoken for already?
529 * The soonest you have to start thinking about the next request
530 * is the longest access time that can occur before
531 * busBusyUntil. Assuming you need to precharge, open a new row,
532 * and access, it is tRP + tRCD + tCL.
536 // All statistics that the model needs to capture
537 Stats::Scalar readReqs;
538 Stats::Scalar writeReqs;
539 Stats::Scalar readBursts;
540 Stats::Scalar writeBursts;
541 Stats::Scalar bytesReadDRAM;
542 Stats::Scalar bytesReadWrQ;
543 Stats::Scalar bytesWritten;
544 Stats::Scalar bytesReadSys;
545 Stats::Scalar bytesWrittenSys;
546 Stats::Scalar servicedByWrQ;
547 Stats::Scalar mergedWrBursts;
548 Stats::Scalar neitherReadNorWrite;
549 Stats::Vector perBankRdBursts;
550 Stats::Vector perBankWrBursts;
551 Stats::Scalar numRdRetry;
552 Stats::Scalar numWrRetry;
553 Stats::Scalar totGap;
554 Stats::Vector readPktSize;
555 Stats::Vector writePktSize;
556 Stats::Vector rdQLenPdf;
557 Stats::Vector wrQLenPdf;
558 Stats::Histogram bytesPerActivate;
559 Stats::Histogram rdPerTurnAround;
560 Stats::Histogram wrPerTurnAround;
562 // Latencies summed over all requests
563 Stats::Scalar totQLat;
564 Stats::Scalar totMemAccLat;
565 Stats::Scalar totBusLat;
566 Stats::Scalar totBankLat;
568 // Average latencies per request
569 Stats::Formula avgQLat;
570 Stats::Formula avgBankLat;
571 Stats::Formula avgBusLat;
572 Stats::Formula avgMemAccLat;
575 Stats::Formula avgRdBW;
576 Stats::Formula avgWrBW;
577 Stats::Formula avgRdBWSys;
578 Stats::Formula avgWrBWSys;
579 Stats::Formula peakBW;
580 Stats::Formula busUtil;
581 Stats::Formula busUtilRead;
582 Stats::Formula busUtilWrite;
584 // Average queue lengths
585 Stats::Average avgRdQLen;
586 Stats::Average avgWrQLen;
588 // Row hit count and rate
589 Stats::Scalar readRowHits;
590 Stats::Scalar writeRowHits;
591 Stats::Formula readRowHitRate;
592 Stats::Formula writeRowHitRate;
593 Stats::Formula avgGap;
595 // DRAM Power Calculation
596 Stats::Formula pageHitRate;
597 Stats::Formula prechargeAllPercent;
598 Stats::Scalar prechargeAllTime;
600 // To track number of cycles all the banks are precharged
601 Tick startTickPrechargeAll;
602 // To track number of banks which are currently active
603 unsigned int numBanksActive;
605 /** @todo this is a temporary workaround until the 4-phase code is
606 * committed. upstream caches needs this packet until true is returned, so
607 * hold onto it for deletion until a subsequent call
609 std::vector<PacketPtr> pendingDelete;
615 DRAMCtrl(const DRAMCtrlParams* p);
617 unsigned int drain(DrainManager* dm);
619 virtual BaseSlavePort& getSlavePort(const std::string& if_name,
620 PortID idx = InvalidPortID);
623 virtual void startup();
627 Tick recvAtomic(PacketPtr pkt);
628 void recvFunctional(PacketPtr pkt);
629 bool recvTimingReq(PacketPtr pkt);
633 #endif //__MEM_DRAM_CTRL_HH__