dram_ctrl.hh revision 10212
1/*
2 * Copyright (c) 2012-2014 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 */
44
45/**
46 * @file
47 * DRAMCtrl declaration
48 */
49
50#ifndef __MEM_DRAM_CTRL_HH__
51#define __MEM_DRAM_CTRL_HH__
52
53#include <deque>
54
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
64/**
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
72 * model.
73 *
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.
82 */
83class DRAMCtrl : public AbstractMemory
84{
85
86  private:
87
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
91    {
92
93        SlavePacketQueue queue;
94        DRAMCtrl& memory;
95
96      public:
97
98        MemoryPort(const std::string& name, DRAMCtrl& _memory);
99
100      protected:
101
102        Tick recvAtomic(PacketPtr pkt);
103
104        void recvFunctional(PacketPtr pkt);
105
106        bool recvTimingReq(PacketPtr);
107
108        virtual AddrRangeList getAddrRanges() const;
109
110    };
111
112    /**
113     * Our incoming port, for a multi-ported controller add a crossbar
114     * in front of it
115     */
116    MemoryPort port;
117
118    /**
119     * Remember if we have to retry a request when available.
120     */
121    bool retryRdReq;
122    bool retryWrReq;
123
124    /**
125     * Bus state used to control the read/write switching and drive
126     * the scheduling of the next request.
127     */
128    enum BusState {
129        READ = 0,
130        READ_TO_WRITE,
131        WRITE,
132        WRITE_TO_READ
133    };
134
135    BusState busState;
136
137    /** List to keep track of activate ticks */
138    std::vector<std::deque<Tick>> actTicks;
139
140    /**
141     * A basic class to track the bank state, i.e. what row is
142     * currently open (if any), when is the bank free to accept a new
143     * column (read/write) command, when can it be precharged, and
144     * when can it be activated.
145     *
146     * The bank also keeps track of how many bytes have been accessed
147     * in the open row since it was opened.
148     */
149    class Bank
150    {
151
152      public:
153
154        static const uint32_t NO_ROW = -1;
155
156        uint32_t openRow;
157
158        Tick colAllowedAt;
159        Tick preAllowedAt;
160        Tick actAllowedAt;
161
162        uint32_t rowAccesses;
163        uint32_t bytesAccessed;
164
165        Bank() :
166            openRow(NO_ROW), colAllowedAt(0), preAllowedAt(0), actAllowedAt(0),
167            rowAccesses(0), bytesAccessed(0)
168        { }
169    };
170
171    /**
172     * A burst helper helps organize and manage a packet that is larger than
173     * the DRAM burst size. A system packet that is larger than the burst size
174     * is split into multiple DRAM packets and all those DRAM packets point to
175     * a single burst helper such that we know when the whole packet is served.
176     */
177    class BurstHelper {
178
179      public:
180
181        /** Number of DRAM bursts requred for a system packet **/
182        const unsigned int burstCount;
183
184        /** Number of DRAM bursts serviced so far for a system packet **/
185        unsigned int burstsServiced;
186
187        BurstHelper(unsigned int _burstCount)
188            : burstCount(_burstCount), burstsServiced(0)
189            { }
190    };
191
192    /**
193     * A DRAM packet stores packets along with the timestamp of when
194     * the packet entered the queue, and also the decoded address.
195     */
196    class DRAMPacket {
197
198      public:
199
200        /** When did request enter the controller */
201        const Tick entryTime;
202
203        /** When will request leave the controller */
204        Tick readyTime;
205
206        /** This comes from the outside world */
207        const PacketPtr pkt;
208
209        const bool isRead;
210
211        /** Will be populated by address decoder */
212        const uint8_t rank;
213        const uint8_t bank;
214        const uint16_t row;
215
216        /**
217         * Bank id is calculated considering banks in all the ranks
218         * eg: 2 ranks each with 8 banks, then bankId = 0 --> rank0, bank0 and
219         * bankId = 8 --> rank1, bank0
220         */
221        const uint16_t bankId;
222
223        /**
224         * The starting address of the DRAM packet.
225         * This address could be unaligned to burst size boundaries. The
226         * reason is to keep the address offset so we can accurately check
227         * incoming read packets with packets in the write queue.
228         */
229        Addr addr;
230
231        /**
232         * The size of this dram packet in bytes
233         * It is always equal or smaller than DRAM burst size
234         */
235        unsigned int size;
236
237        /**
238         * A pointer to the BurstHelper if this DRAMPacket is a split packet
239         * If not a split packet (common case), this is set to NULL
240         */
241        BurstHelper* burstHelper;
242        Bank& bankRef;
243
244        DRAMPacket(PacketPtr _pkt, bool is_read, uint8_t _rank, uint8_t _bank,
245                   uint16_t _row, uint16_t bank_id, Addr _addr,
246                   unsigned int _size, Bank& bank_ref)
247            : entryTime(curTick()), readyTime(curTick()),
248              pkt(_pkt), isRead(is_read), rank(_rank), bank(_bank), row(_row),
249              bankId(bank_id), addr(_addr), size(_size), burstHelper(NULL),
250              bankRef(bank_ref)
251        { }
252
253    };
254
255    /**
256     * Bunch of things requires to setup "events" in gem5
257     * When event "respondEvent" occurs for example, the method
258     * processRespondEvent is called; no parameters are allowed
259     * in these methods
260     */
261    void processNextReqEvent();
262    EventWrapper<DRAMCtrl,&DRAMCtrl::processNextReqEvent> nextReqEvent;
263
264    void processRespondEvent();
265    EventWrapper<DRAMCtrl, &DRAMCtrl::processRespondEvent> respondEvent;
266
267    void processActivateEvent();
268    EventWrapper<DRAMCtrl, &DRAMCtrl::processActivateEvent> activateEvent;
269
270    void processPrechargeEvent();
271    EventWrapper<DRAMCtrl, &DRAMCtrl::processPrechargeEvent> prechargeEvent;
272
273    void processRefreshEvent();
274    EventWrapper<DRAMCtrl, &DRAMCtrl::processRefreshEvent> refreshEvent;
275
276    void processPowerEvent();
277    EventWrapper<DRAMCtrl,&DRAMCtrl::processPowerEvent> powerEvent;
278
279    /**
280     * Check if the read queue has room for more entries
281     *
282     * @param pktCount The number of entries needed in the read queue
283     * @return true if read queue is full, false otherwise
284     */
285    bool readQueueFull(unsigned int pktCount) const;
286
287    /**
288     * Check if the write queue has room for more entries
289     *
290     * @param pktCount The number of entries needed in the write queue
291     * @return true if write queue is full, false otherwise
292     */
293    bool writeQueueFull(unsigned int pktCount) const;
294
295    /**
296     * When a new read comes in, first check if the write q has a
297     * pending request to the same address.\ If not, decode the
298     * address to populate rank/bank/row, create one or mutliple
299     * "dram_pkt", and push them to the back of the read queue.\
300     * If this is the only
301     * read request in the system, schedule an event to start
302     * servicing it.
303     *
304     * @param pkt The request packet from the outside world
305     * @param pktCount The number of DRAM bursts the pkt
306     * translate to. If pkt size is larger then one full burst,
307     * then pktCount is greater than one.
308     */
309    void addToReadQueue(PacketPtr pkt, unsigned int pktCount);
310
311    /**
312     * Decode the incoming pkt, create a dram_pkt and push to the
313     * back of the write queue. \If the write q length is more than
314     * the threshold specified by the user, ie the queue is beginning
315     * to get full, stop reads, and start draining writes.
316     *
317     * @param pkt The request packet from the outside world
318     * @param pktCount The number of DRAM bursts the pkt
319     * translate to. If pkt size is larger then one full burst,
320     * then pktCount is greater than one.
321     */
322    void addToWriteQueue(PacketPtr pkt, unsigned int pktCount);
323
324    /**
325     * Actually do the DRAM access - figure out the latency it
326     * will take to service the req based on bank state, channel state etc
327     * and then update those states to account for this request.\ Based
328     * on this, update the packet's "readyTime" and move it to the
329     * response q from where it will eventually go back to the outside
330     * world.
331     *
332     * @param pkt The DRAM packet created from the outside world pkt
333     */
334    void doDRAMAccess(DRAMPacket* dram_pkt);
335
336    /**
337     * When a packet reaches its "readyTime" in the response Q,
338     * use the "access()" method in AbstractMemory to actually
339     * create the response packet, and send it back to the outside
340     * world requestor.
341     *
342     * @param pkt The packet from the outside world
343     * @param static_latency Static latency to add before sending the packet
344     */
345    void accessAndRespond(PacketPtr pkt, Tick static_latency);
346
347    /**
348     * Address decoder to figure out physical mapping onto ranks,
349     * banks, and rows. This function is called multiple times on the same
350     * system packet if the pakcet is larger than burst of the memory. The
351     * dramPktAddr is used for the offset within the packet.
352     *
353     * @param pkt The packet from the outside world
354     * @param dramPktAddr The starting address of the DRAM packet
355     * @param size The size of the DRAM packet in bytes
356     * @param isRead Is the request for a read or a write to DRAM
357     * @return A DRAMPacket pointer with the decoded information
358     */
359    DRAMPacket* decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned int size,
360                           bool isRead);
361
362    /**
363     * The memory schduler/arbiter - picks which request needs to
364     * go next, based on the specified policy such as FCFS or FR-FCFS
365     * and moves it to the head of the queue.
366     */
367    void chooseNext(std::deque<DRAMPacket*>& queue);
368
369    /**
370     * Move the request at the head of the read queue to the response
371     * queue, sorting by readyTime.\ If it is the only packet in the
372     * response queue, schedule a respond event to send it back to the
373     * outside world
374     */
375    void moveToRespQ();
376
377    /**
378     * For FR-FCFS policy reorder the read/write queue depending on row buffer
379     * hits and earliest banks available in DRAM
380     */
381    void reorderQueue(std::deque<DRAMPacket*>& queue);
382
383    /**
384     * Find which are the earliest banks ready to issue an activate
385     * for the enqueued requests. Assumes maximum of 64 banks per DIMM
386     *
387     * @param Queued requests to consider
388     * @return One-hot encoded mask of bank indices
389     */
390    uint64_t minBankActAt(const std::deque<DRAMPacket*>& queue) const;
391
392    /**
393     * Keep track of when row activations happen, in order to enforce
394     * the maximum number of activations in the activation window. The
395     * method updates the time that the banks become available based
396     * on the current limits.
397     *
398     * @param act_tick Time when the activation takes place
399     * @param rank Index of the rank
400     * @param bank Index of the bank
401     * @param row Index of the row
402     * @param bank_ref Reference to the bank
403     */
404    void activateBank(Tick act_tick, uint8_t rank, uint8_t bank,
405                      uint16_t row, Bank& bank_ref);
406
407    /**
408     * Precharge a given bank and also update when the precharge is
409     * done. This will also deal with any stats related to the
410     * accesses to the open page.
411     *
412     * @param bank The bank to precharge
413     * @param pre_at Time when the precharge takes place
414     */
415    void prechargeBank(Bank& bank, Tick pre_at);
416
417    void printParams() const;
418
419    /**
420     * Used for debugging to observe the contents of the queues.
421     */
422    void printQs() const;
423
424    /**
425     * The controller's main read and write queues
426     */
427    std::deque<DRAMPacket*> readQueue;
428    std::deque<DRAMPacket*> writeQueue;
429
430    /**
431     * Response queue where read packets wait after we're done working
432     * with them, but it's not time to send the response yet. The
433     * responses are stored seperately mostly to keep the code clean
434     * and help with events scheduling. For all logical purposes such
435     * as sizing the read queue, this and the main read queue need to
436     * be added together.
437     */
438    std::deque<DRAMPacket*> respQueue;
439
440    /**
441     * If we need to drain, keep the drain manager around until we're
442     * done here.
443     */
444    DrainManager *drainManager;
445
446    /**
447     * Multi-dimensional vector of banks, first dimension is ranks,
448     * second is bank
449     */
450    std::vector<std::vector<Bank> > banks;
451
452    /**
453     * The following are basic design parameters of the memory
454     * controller, and are initialized based on parameter values.
455     * The rowsPerBank is determined based on the capacity, number of
456     * ranks and banks, the burst size, and the row buffer size.
457     */
458    const uint32_t deviceBusWidth;
459    const uint32_t burstLength;
460    const uint32_t deviceRowBufferSize;
461    const uint32_t devicesPerRank;
462    const uint32_t burstSize;
463    const uint32_t rowBufferSize;
464    const uint32_t columnsPerRowBuffer;
465    const uint32_t ranksPerChannel;
466    const uint32_t banksPerRank;
467    const uint32_t channels;
468    uint32_t rowsPerBank;
469    const uint32_t readBufferSize;
470    const uint32_t writeBufferSize;
471    const uint32_t writeHighThreshold;
472    const uint32_t writeLowThreshold;
473    const uint32_t minWritesPerSwitch;
474    uint32_t writesThisTime;
475    uint32_t readsThisTime;
476
477    /**
478     * Basic memory timing parameters initialized based on parameter
479     * values.
480     */
481    const Tick tWTR;
482    const Tick tRTW;
483    const Tick tBURST;
484    const Tick tRCD;
485    const Tick tCL;
486    const Tick tRP;
487    const Tick tRAS;
488    const Tick tWR;
489    const Tick tRTP;
490    const Tick tRFC;
491    const Tick tREFI;
492    const Tick tRRD;
493    const Tick tXAW;
494    const uint32_t activationLimit;
495
496    /**
497     * Memory controller configuration initialized based on parameter
498     * values.
499     */
500    Enums::MemSched memSchedPolicy;
501    Enums::AddrMap addrMapping;
502    Enums::PageManage pageMgmt;
503
504    /**
505     * Max column accesses (read and write) per row, before forefully
506     * closing it.
507     */
508    const uint32_t maxAccessesPerRow;
509
510    /**
511     * Pipeline latency of the controller frontend. The frontend
512     * contribution is added to writes (that complete when they are in
513     * the write buffer) and reads that are serviced the write buffer.
514     */
515    const Tick frontendLatency;
516
517    /**
518     * Pipeline latency of the backend and PHY. Along with the
519     * frontend contribution, this latency is added to reads serviced
520     * by the DRAM.
521     */
522    const Tick backendLatency;
523
524    /**
525     * Till when has the main data bus been spoken for already?
526     */
527    Tick busBusyUntil;
528
529    /**
530     * Keep track of when a refresh is due.
531     */
532    Tick refreshDueAt;
533
534    /**
535     * The refresh state is used to control the progress of the
536     * refresh scheduling. When normal operation is in progress the
537     * refresh state is idle. From there, it progresses to the refresh
538     * drain state once tREFI has passed. The refresh drain state
539     * captures the DRAM row active state, as it will stay there until
540     * all ongoing accesses complete. Thereafter all banks are
541     * precharged, and lastly, the DRAM is refreshed.
542     */
543    enum RefreshState {
544        REF_IDLE = 0,
545        REF_DRAIN,
546        REF_PRE,
547        REF_RUN
548    };
549
550    RefreshState refreshState;
551
552    /**
553     * The power state captures the different operational states of
554     * the DRAM and interacts with the bus read/write state machine,
555     * and the refresh state machine. In the idle state all banks are
556     * precharged. From there we either go to an auto refresh (as
557     * determined by the refresh state machine), or to a precharge
558     * power down mode. From idle the memory can also go to the active
559     * state (with one or more banks active), and in turn from there
560     * to active power down. At the moment we do not capture the deep
561     * power down and self-refresh state.
562     */
563    enum PowerState {
564        PWR_IDLE = 0,
565        PWR_REF,
566        PWR_PRE_PDN,
567        PWR_ACT,
568        PWR_ACT_PDN
569    };
570
571    /**
572     * Since we are taking decisions out of order, we need to keep
573     * track of what power transition is happening at what time, such
574     * that we can go back in time and change history. For example, if
575     * we precharge all banks and schedule going to the idle state, we
576     * might at a later point decide to activate a bank before the
577     * transition to idle would have taken place.
578     */
579    PowerState pwrStateTrans;
580
581    /**
582     * Current power state.
583     */
584    PowerState pwrState;
585
586    /**
587     * Schedule a power state transition in the future, and
588     * potentially override an already scheduled transition.
589     *
590     * @param pwr_state Power state to transition to
591     * @param tick Tick when transition should take place
592     */
593    void schedulePowerEvent(PowerState pwr_state, Tick tick);
594
595    Tick prevArrival;
596
597    /**
598     * The soonest you have to start thinking about the next request
599     * is the longest access time that can occur before
600     * busBusyUntil. Assuming you need to precharge, open a new row,
601     * and access, it is tRP + tRCD + tCL.
602     */
603    Tick nextReqTime;
604
605    // All statistics that the model needs to capture
606    Stats::Scalar readReqs;
607    Stats::Scalar writeReqs;
608    Stats::Scalar readBursts;
609    Stats::Scalar writeBursts;
610    Stats::Scalar bytesReadDRAM;
611    Stats::Scalar bytesReadWrQ;
612    Stats::Scalar bytesWritten;
613    Stats::Scalar bytesReadSys;
614    Stats::Scalar bytesWrittenSys;
615    Stats::Scalar servicedByWrQ;
616    Stats::Scalar mergedWrBursts;
617    Stats::Scalar neitherReadNorWrite;
618    Stats::Vector perBankRdBursts;
619    Stats::Vector perBankWrBursts;
620    Stats::Scalar numRdRetry;
621    Stats::Scalar numWrRetry;
622    Stats::Scalar totGap;
623    Stats::Vector readPktSize;
624    Stats::Vector writePktSize;
625    Stats::Vector rdQLenPdf;
626    Stats::Vector wrQLenPdf;
627    Stats::Histogram bytesPerActivate;
628    Stats::Histogram rdPerTurnAround;
629    Stats::Histogram wrPerTurnAround;
630
631    // Latencies summed over all requests
632    Stats::Scalar totQLat;
633    Stats::Scalar totMemAccLat;
634    Stats::Scalar totBusLat;
635
636    // Average latencies per request
637    Stats::Formula avgQLat;
638    Stats::Formula avgBusLat;
639    Stats::Formula avgMemAccLat;
640
641    // Average bandwidth
642    Stats::Formula avgRdBW;
643    Stats::Formula avgWrBW;
644    Stats::Formula avgRdBWSys;
645    Stats::Formula avgWrBWSys;
646    Stats::Formula peakBW;
647    Stats::Formula busUtil;
648    Stats::Formula busUtilRead;
649    Stats::Formula busUtilWrite;
650
651    // Average queue lengths
652    Stats::Average avgRdQLen;
653    Stats::Average avgWrQLen;
654
655    // Row hit count and rate
656    Stats::Scalar readRowHits;
657    Stats::Scalar writeRowHits;
658    Stats::Formula readRowHitRate;
659    Stats::Formula writeRowHitRate;
660    Stats::Formula avgGap;
661
662    // DRAM Power Calculation
663    Stats::Formula pageHitRate;
664    Stats::Vector pwrStateTime;
665
666    // Track when we transitioned to the current power state
667    Tick pwrStateTick;
668
669    // To track number of banks which are currently active
670    unsigned int numBanksActive;
671
672    /** @todo this is a temporary workaround until the 4-phase code is
673     * committed. upstream caches needs this packet until true is returned, so
674     * hold onto it for deletion until a subsequent call
675     */
676    std::vector<PacketPtr> pendingDelete;
677
678  public:
679
680    void regStats();
681
682    DRAMCtrl(const DRAMCtrlParams* p);
683
684    unsigned int drain(DrainManager* dm);
685
686    virtual BaseSlavePort& getSlavePort(const std::string& if_name,
687                                        PortID idx = InvalidPortID);
688
689    virtual void init();
690    virtual void startup();
691
692  protected:
693
694    Tick recvAtomic(PacketPtr pkt);
695    void recvFunctional(PacketPtr pkt);
696    bool recvTimingReq(PacketPtr pkt);
697
698};
699
700#endif //__MEM_DRAM_CTRL_HH__
701