fetch.hh revision 9184:a1a8f137b796
1/*
2 * Copyright (c) 2010-2011 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) 2004-2006 The Regents of The University of Michigan
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: Kevin Lim
41 *          Korey Sewell
42 */
43
44#ifndef __CPU_O3_FETCH_HH__
45#define __CPU_O3_FETCH_HH__
46
47#include "arch/decoder.hh"
48#include "arch/utility.hh"
49#include "base/statistics.hh"
50#include "config/the_isa.hh"
51#include "cpu/pc_event.hh"
52#include "cpu/timebuf.hh"
53#include "cpu/translation.hh"
54#include "mem/packet.hh"
55#include "mem/port.hh"
56#include "sim/eventq.hh"
57
58struct DerivO3CPUParams;
59
60/**
61 * DefaultFetch class handles both single threaded and SMT fetch. Its
62 * width is specified by the parameters; each cycle it tries to fetch
63 * that many instructions. It supports using a branch predictor to
64 * predict direction and targets.
65 * It supports the idling functionality of the CPU by indicating to
66 * the CPU when it is active and inactive.
67 */
68template <class Impl>
69class DefaultFetch
70{
71  public:
72    /** Typedefs from Impl. */
73    typedef typename Impl::CPUPol CPUPol;
74    typedef typename Impl::DynInst DynInst;
75    typedef typename Impl::DynInstPtr DynInstPtr;
76    typedef typename Impl::O3CPU O3CPU;
77
78    /** Typedefs from the CPU policy. */
79    typedef typename CPUPol::BPredUnit BPredUnit;
80    typedef typename CPUPol::FetchStruct FetchStruct;
81    typedef typename CPUPol::TimeStruct TimeStruct;
82
83    /** Typedefs from ISA. */
84    typedef TheISA::MachInst MachInst;
85    typedef TheISA::ExtMachInst ExtMachInst;
86
87    class FetchTranslation : public BaseTLB::Translation
88    {
89      protected:
90        DefaultFetch<Impl> *fetch;
91
92      public:
93        FetchTranslation(DefaultFetch<Impl> *_fetch)
94            : fetch(_fetch)
95        {}
96
97        void
98        markDelayed()
99        {}
100
101        void
102        finish(Fault fault, RequestPtr req, ThreadContext *tc,
103               BaseTLB::Mode mode)
104        {
105            assert(mode == BaseTLB::Execute);
106            fetch->finishTranslation(fault, req);
107            delete this;
108        }
109    };
110
111  private:
112    /* Event to delay delivery of a fetch translation result in case of
113     * a fault and the nop to carry the fault cannot be generated
114     * immediately */
115    class FinishTranslationEvent : public Event
116    {
117      private:
118        DefaultFetch<Impl> *fetch;
119        Fault fault;
120        RequestPtr req;
121
122      public:
123        FinishTranslationEvent(DefaultFetch<Impl> *_fetch)
124            : fetch(_fetch)
125        {}
126
127        void setFault(Fault _fault)
128        {
129            fault = _fault;
130        }
131
132        void setReq(RequestPtr _req)
133        {
134            req = _req;
135        }
136
137        /** Process the delayed finish translation */
138        void process()
139        {
140            assert(fetch->numInst < fetch->fetchWidth);
141            fetch->finishTranslation(fault, req);
142        }
143
144        const char *description() const
145        {
146            return "FullO3CPU FetchFinishTranslation";
147        }
148      };
149
150  public:
151    /** Overall fetch status. Used to determine if the CPU can
152     * deschedule itsef due to a lack of activity.
153     */
154    enum FetchStatus {
155        Active,
156        Inactive
157    };
158
159    /** Individual thread status. */
160    enum ThreadStatus {
161        Running,
162        Idle,
163        Squashing,
164        Blocked,
165        Fetching,
166        TrapPending,
167        QuiescePending,
168        SwitchOut,
169        ItlbWait,
170        IcacheWaitResponse,
171        IcacheWaitRetry,
172        IcacheAccessComplete,
173        NoGoodAddr
174    };
175
176    /** Fetching Policy, Add new policies here.*/
177    enum FetchPriority {
178        SingleThread,
179        RoundRobin,
180        Branch,
181        IQ,
182        LSQ
183    };
184
185  private:
186    /** Fetch status. */
187    FetchStatus _status;
188
189    /** Per-thread status. */
190    ThreadStatus fetchStatus[Impl::MaxThreads];
191
192    /** Fetch policy. */
193    FetchPriority fetchPolicy;
194
195    /** List that has the threads organized by priority. */
196    std::list<ThreadID> priorityList;
197
198  public:
199    /** DefaultFetch constructor. */
200    DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params);
201
202    /** Returns the name of fetch. */
203    std::string name() const;
204
205    /** Registers statistics. */
206    void regStats();
207
208    /** Sets the main backwards communication time buffer pointer. */
209    void setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer);
210
211    /** Sets pointer to list of active threads. */
212    void setActiveThreads(std::list<ThreadID> *at_ptr);
213
214    /** Sets pointer to time buffer used to communicate to the next stage. */
215    void setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr);
216
217    /** Initialize stage. */
218    void initStage();
219
220    /** Tells the fetch stage that the Icache is set. */
221    void setIcache();
222
223    /** Handles retrying the fetch access. */
224    void recvRetry();
225
226    /** Processes cache completion event. */
227    void processCacheCompletion(PacketPtr pkt);
228
229    /** Begins the drain of the fetch stage. */
230    bool drain();
231
232    /** Resumes execution after a drain. */
233    void resume();
234
235    /** Tells fetch stage to prepare to be switched out. */
236    void switchOut();
237
238    /** Takes over from another CPU's thread. */
239    void takeOverFrom();
240
241    /** Checks if the fetch stage is switched out. */
242    bool isSwitchedOut() { return switchedOut; }
243
244    /** Tells fetch to wake up from a quiesce instruction. */
245    void wakeFromQuiesce();
246
247  private:
248    /** Changes the status of this stage to active, and indicates this
249     * to the CPU.
250     */
251    inline void switchToActive();
252
253    /** Changes the status of this stage to inactive, and indicates
254     * this to the CPU.
255     */
256    inline void switchToInactive();
257
258    /**
259     * Looks up in the branch predictor to see if the next PC should be
260     * either next PC+=MachInst or a branch target.
261     * @param next_PC Next PC variable passed in by reference.  It is
262     * expected to be set to the current PC; it will be updated with what
263     * the next PC will be.
264     * @param next_NPC Used for ISAs which use delay slots.
265     * @return Whether or not a branch was predicted as taken.
266     */
267    bool lookupAndUpdateNextPC(DynInstPtr &inst, TheISA::PCState &pc);
268
269    /**
270     * Fetches the cache line that contains fetch_PC.  Returns any
271     * fault that happened.  Puts the data into the class variable
272     * cacheData.
273     * @param vaddr The memory address that is being fetched from.
274     * @param ret_fault The fault reference that will be set to the result of
275     * the icache access.
276     * @param tid Thread id.
277     * @param pc The actual PC of the current instruction.
278     * @return Any fault that occured.
279     */
280    bool fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc);
281    void finishTranslation(Fault fault, RequestPtr mem_req);
282
283
284    /** Check if an interrupt is pending and that we need to handle
285     */
286    bool
287    checkInterrupt(Addr pc)
288    {
289        return (interruptPending && (THE_ISA != ALPHA_ISA || !(pc & 0x3)));
290    }
291
292    /** Squashes a specific thread and resets the PC. */
293    inline void doSquash(const TheISA::PCState &newPC,
294                         const DynInstPtr squashInst, ThreadID tid);
295
296    /** Squashes a specific thread and resets the PC. Also tells the CPU to
297     * remove any instructions between fetch and decode that should be sqaushed.
298     */
299    void squashFromDecode(const TheISA::PCState &newPC,
300                          const DynInstPtr squashInst,
301                          const InstSeqNum seq_num, ThreadID tid);
302
303    /** Checks if a thread is stalled. */
304    bool checkStall(ThreadID tid) const;
305
306    /** Updates overall fetch stage status; to be called at the end of each
307     * cycle. */
308    FetchStatus updateFetchStatus();
309
310  public:
311    /** Squashes a specific thread and resets the PC. Also tells the CPU to
312     * remove any instructions that are not in the ROB. The source of this
313     * squash should be the commit stage.
314     */
315    void squash(const TheISA::PCState &newPC, const InstSeqNum seq_num,
316                DynInstPtr squashInst, ThreadID tid);
317
318    /** Ticks the fetch stage, processing all inputs signals and fetching
319     * as many instructions as possible.
320     */
321    void tick();
322
323    /** Checks all input signals and updates the status as necessary.
324     *  @return: Returns if the status has changed due to input signals.
325     */
326    bool checkSignalsAndUpdate(ThreadID tid);
327
328    /** Does the actual fetching of instructions and passing them on to the
329     * next stage.
330     * @param status_change fetch() sets this variable if there was a status
331     * change (ie switching to IcacheMissStall).
332     */
333    void fetch(bool &status_change);
334
335    /** Align a PC to the start of an I-cache block. */
336    Addr icacheBlockAlignPC(Addr addr)
337    {
338        return (addr & ~(cacheBlkMask));
339    }
340
341    /** The decoder. */
342    TheISA::Decoder *decoder[Impl::MaxThreads];
343
344  private:
345    DynInstPtr buildInst(ThreadID tid, StaticInstPtr staticInst,
346                         StaticInstPtr curMacroop, TheISA::PCState thisPC,
347                         TheISA::PCState nextPC, bool trace);
348
349    /** Returns the appropriate thread to fetch, given the fetch policy. */
350    ThreadID getFetchingThread(FetchPriority &fetch_priority);
351
352    /** Returns the appropriate thread to fetch using a round robin policy. */
353    ThreadID roundRobin();
354
355    /** Returns the appropriate thread to fetch using the IQ count policy. */
356    ThreadID iqCount();
357
358    /** Returns the appropriate thread to fetch using the LSQ count policy. */
359    ThreadID lsqCount();
360
361    /** Returns the appropriate thread to fetch using the branch count
362     * policy. */
363    ThreadID branchCount();
364
365    /** Pipeline the next I-cache access to the current one. */
366    void pipelineIcacheAccesses(ThreadID tid);
367
368    /** Profile the reasons of fetch stall. */
369    void profileStall(ThreadID tid);
370
371  private:
372    /** Pointer to the O3CPU. */
373    O3CPU *cpu;
374
375    /** Time buffer interface. */
376    TimeBuffer<TimeStruct> *timeBuffer;
377
378    /** Wire to get decode's information from backwards time buffer. */
379    typename TimeBuffer<TimeStruct>::wire fromDecode;
380
381    /** Wire to get rename's information from backwards time buffer. */
382    typename TimeBuffer<TimeStruct>::wire fromRename;
383
384    /** Wire to get iew's information from backwards time buffer. */
385    typename TimeBuffer<TimeStruct>::wire fromIEW;
386
387    /** Wire to get commit's information from backwards time buffer. */
388    typename TimeBuffer<TimeStruct>::wire fromCommit;
389
390    /** Internal fetch instruction queue. */
391    TimeBuffer<FetchStruct> *fetchQueue;
392
393    //Might be annoying how this name is different than the queue.
394    /** Wire used to write any information heading to decode. */
395    typename TimeBuffer<FetchStruct>::wire toDecode;
396
397    /** BPredUnit. */
398    BPredUnit branchPred;
399
400    TheISA::PCState pc[Impl::MaxThreads];
401
402    Addr fetchOffset[Impl::MaxThreads];
403
404    StaticInstPtr macroop[Impl::MaxThreads];
405
406    /** Can the fetch stage redirect from an interrupt on this instruction? */
407    bool delayedCommit[Impl::MaxThreads];
408
409    /** Memory request used to access cache. */
410    RequestPtr memReq[Impl::MaxThreads];
411
412    /** Variable that tracks if fetch has written to the time buffer this
413     * cycle. Used to tell CPU if there is activity this cycle.
414     */
415    bool wroteToTimeBuffer;
416
417    /** Tracks how many instructions has been fetched this cycle. */
418    int numInst;
419
420    /** Source of possible stalls. */
421    struct Stalls {
422        bool decode;
423        bool rename;
424        bool iew;
425        bool commit;
426    };
427
428    /** Tracks which stages are telling fetch to stall. */
429    Stalls stalls[Impl::MaxThreads];
430
431    /** Decode to fetch delay. */
432    Cycles decodeToFetchDelay;
433
434    /** Rename to fetch delay. */
435    Cycles renameToFetchDelay;
436
437    /** IEW to fetch delay. */
438    Cycles iewToFetchDelay;
439
440    /** Commit to fetch delay. */
441    Cycles commitToFetchDelay;
442
443    /** The width of fetch in instructions. */
444    unsigned fetchWidth;
445
446    /** Is the cache blocked?  If so no threads can access it. */
447    bool cacheBlocked;
448
449    /** The packet that is waiting to be retried. */
450    PacketPtr retryPkt;
451
452    /** The thread that is waiting on the cache to tell fetch to retry. */
453    ThreadID retryTid;
454
455    /** Cache block size. */
456    int cacheBlkSize;
457
458    /** Mask to get a cache block's address. */
459    Addr cacheBlkMask;
460
461    /** The cache line being fetched. */
462    uint8_t *cacheData[Impl::MaxThreads];
463
464    /** The PC of the cacheline that has been loaded. */
465    Addr cacheDataPC[Impl::MaxThreads];
466
467    /** Whether or not the cache data is valid. */
468    bool cacheDataValid[Impl::MaxThreads];
469
470    /** Size of instructions. */
471    int instSize;
472
473    /** Icache stall statistics. */
474    Counter lastIcacheStall[Impl::MaxThreads];
475
476    /** List of Active Threads */
477    std::list<ThreadID> *activeThreads;
478
479    /** Number of threads. */
480    ThreadID numThreads;
481
482    /** Number of threads that are actively fetching. */
483    ThreadID numFetchingThreads;
484
485    /** Thread ID being fetched. */
486    ThreadID threadFetched;
487
488    /** Checks if there is an interrupt pending.  If there is, fetch
489     * must stop once it is not fetching PAL instructions.
490     */
491    bool interruptPending;
492
493    /** Is there a drain pending. */
494    bool drainPending;
495
496    /** Records if fetch is switched out. */
497    bool switchedOut;
498
499    /** Set to true if a pipelined I-cache request should be issued. */
500    bool issuePipelinedIfetch[Impl::MaxThreads];
501
502    /** Event used to delay fault generation of translation faults */
503    FinishTranslationEvent finishTranslationEvent;
504
505    // @todo: Consider making these vectors and tracking on a per thread basis.
506    /** Stat for total number of cycles stalled due to an icache miss. */
507    Stats::Scalar icacheStallCycles;
508    /** Stat for total number of fetched instructions. */
509    Stats::Scalar fetchedInsts;
510    /** Total number of fetched branches. */
511    Stats::Scalar fetchedBranches;
512    /** Stat for total number of predicted branches. */
513    Stats::Scalar predictedBranches;
514    /** Stat for total number of cycles spent fetching. */
515    Stats::Scalar fetchCycles;
516    /** Stat for total number of cycles spent squashing. */
517    Stats::Scalar fetchSquashCycles;
518    /** Stat for total number of cycles spent waiting for translation */
519    Stats::Scalar fetchTlbCycles;
520    /** Stat for total number of cycles spent blocked due to other stages in
521     * the pipeline.
522     */
523    Stats::Scalar fetchIdleCycles;
524    /** Total number of cycles spent blocked. */
525    Stats::Scalar fetchBlockedCycles;
526    /** Total number of cycles spent in any other state. */
527    Stats::Scalar fetchMiscStallCycles;
528    /** Total number of cycles spent in waiting for drains. */
529    Stats::Scalar fetchPendingDrainCycles;
530    /** Total number of stall cycles caused by no active threads to run. */
531    Stats::Scalar fetchNoActiveThreadStallCycles;
532    /** Total number of stall cycles caused by pending traps. */
533    Stats::Scalar fetchPendingTrapStallCycles;
534    /** Total number of stall cycles caused by pending quiesce instructions. */
535    Stats::Scalar fetchPendingQuiesceStallCycles;
536    /** Total number of stall cycles caused by I-cache wait retrys. */
537    Stats::Scalar fetchIcacheWaitRetryStallCycles;
538    /** Stat for total number of fetched cache lines. */
539    Stats::Scalar fetchedCacheLines;
540    /** Total number of outstanding icache accesses that were dropped
541     * due to a squash.
542     */
543    Stats::Scalar fetchIcacheSquashes;
544    /** Total number of outstanding tlb accesses that were dropped
545     * due to a squash.
546     */
547    Stats::Scalar fetchTlbSquashes;
548    /** Distribution of number of instructions fetched each cycle. */
549    Stats::Distribution fetchNisnDist;
550    /** Rate of how often fetch was idle. */
551    Stats::Formula idleRate;
552    /** Number of branch fetches per cycle. */
553    Stats::Formula branchRate;
554    /** Number of instruction fetched per cycle. */
555    Stats::Formula fetchRate;
556};
557
558#endif //__CPU_O3_FETCH_HH__
559