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