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