fetch.hh revision 4302:c45514c856b0
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Kevin Lim
29 *          Korey Sewell
30 */
31
32#ifndef __CPU_O3_FETCH_HH__
33#define __CPU_O3_FETCH_HH__
34
35#include "arch/utility.hh"
36#include "arch/predecoder.hh"
37#include "base/statistics.hh"
38#include "base/timebuf.hh"
39#include "cpu/pc_event.hh"
40#include "mem/packet.hh"
41#include "mem/port.hh"
42#include "sim/eventq.hh"
43
44/**
45 * DefaultFetch class handles both single threaded and SMT fetch. Its
46 * width is specified by the parameters; each cycle it tries to fetch
47 * that many instructions. It supports using a branch predictor to
48 * predict direction and targets.
49 * It supports the idling functionality of the CPU by indicating to
50 * the CPU when it is active and inactive.
51 */
52template <class Impl>
53class DefaultFetch
54{
55  public:
56    /** Typedefs from Impl. */
57    typedef typename Impl::CPUPol CPUPol;
58    typedef typename Impl::DynInst DynInst;
59    typedef typename Impl::DynInstPtr DynInstPtr;
60    typedef typename Impl::O3CPU O3CPU;
61    typedef typename Impl::Params Params;
62
63    /** Typedefs from the CPU policy. */
64    typedef typename CPUPol::BPredUnit BPredUnit;
65    typedef typename CPUPol::FetchStruct FetchStruct;
66    typedef typename CPUPol::TimeStruct TimeStruct;
67
68    /** Typedefs from ISA. */
69    typedef TheISA::MachInst MachInst;
70    typedef TheISA::ExtMachInst ExtMachInst;
71
72    /** IcachePort class for DefaultFetch.  Handles doing the
73     * communication with the cache/memory.
74     */
75    class IcachePort : public Port
76    {
77      protected:
78        /** Pointer to fetch. */
79        DefaultFetch<Impl> *fetch;
80
81      public:
82        /** Default constructor. */
83        IcachePort(DefaultFetch<Impl> *_fetch)
84            : Port(_fetch->name() + "-iport"), fetch(_fetch)
85        { }
86
87        bool snoopRangeSent;
88
89        virtual void setPeer(Port *port);
90
91      protected:
92        /** Atomic version of receive.  Panics. */
93        virtual Tick recvAtomic(PacketPtr pkt);
94
95        /** Functional version of receive.  Panics. */
96        virtual void recvFunctional(PacketPtr pkt);
97
98        /** Receives status change.  Other than range changing, panics. */
99        virtual void recvStatusChange(Status status);
100
101        /** Returns the address ranges of this device. */
102        virtual void getDeviceAddressRanges(AddrRangeList &resp,
103                                            AddrRangeList &snoop)
104        { resp.clear(); snoop.clear(); snoop.push_back(RangeSize(0,0)); }
105
106        /** Timing version of receive.  Handles setting fetch to the
107         * proper status to start fetching. */
108        virtual bool recvTiming(PacketPtr pkt);
109
110        /** Handles doing a retry of a failed fetch. */
111        virtual void recvRetry();
112    };
113
114
115  public:
116    /** Overall fetch status. Used to determine if the CPU can
117     * deschedule itsef due to a lack of activity.
118     */
119    enum FetchStatus {
120        Active,
121        Inactive
122    };
123
124    /** Individual thread status. */
125    enum ThreadStatus {
126        Running,
127        Idle,
128        Squashing,
129        Blocked,
130        Fetching,
131        TrapPending,
132        QuiescePending,
133        SwitchOut,
134        IcacheWaitResponse,
135        IcacheWaitRetry,
136        IcacheAccessComplete
137    };
138
139    /** Fetching Policy, Add new policies here.*/
140    enum FetchPriority {
141        SingleThread,
142        RoundRobin,
143        Branch,
144        IQ,
145        LSQ
146    };
147
148  private:
149    /** Fetch status. */
150    FetchStatus _status;
151
152    /** Per-thread status. */
153    ThreadStatus fetchStatus[Impl::MaxThreads];
154
155    /** Fetch policy. */
156    FetchPriority fetchPolicy;
157
158    /** List that has the threads organized by priority. */
159    std::list<unsigned> priorityList;
160
161  public:
162    /** DefaultFetch constructor. */
163    DefaultFetch(Params *params);
164
165    /** Returns the name of fetch. */
166    std::string name() const;
167
168    /** Registers statistics. */
169    void regStats();
170
171    /** Returns the icache port. */
172    Port *getIcachePort() { return icachePort; }
173
174    /** Sets CPU pointer. */
175    void setCPU(O3CPU *cpu_ptr);
176
177    /** Sets the main backwards communication time buffer pointer. */
178    void setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer);
179
180    /** Sets pointer to list of active threads. */
181    void setActiveThreads(std::list<unsigned> *at_ptr);
182
183    /** Sets pointer to time buffer used to communicate to the next stage. */
184    void setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr);
185
186    /** Initialize stage. */
187    void initStage();
188
189    /** Tells the fetch stage that the Icache is set. */
190    void setIcache();
191
192    /** Processes cache completion event. */
193    void processCacheCompletion(PacketPtr pkt);
194
195    /** Begins the drain of the fetch stage. */
196    bool drain();
197
198    /** Resumes execution after a drain. */
199    void resume();
200
201    /** Tells fetch stage to prepare to be switched out. */
202    void switchOut();
203
204    /** Takes over from another CPU's thread. */
205    void takeOverFrom();
206
207    /** Checks if the fetch stage is switched out. */
208    bool isSwitchedOut() { return switchedOut; }
209
210    /** Tells fetch to wake up from a quiesce instruction. */
211    void wakeFromQuiesce();
212
213  private:
214    /** Changes the status of this stage to active, and indicates this
215     * to the CPU.
216     */
217    inline void switchToActive();
218
219    /** Changes the status of this stage to inactive, and indicates
220     * this to the CPU.
221     */
222    inline void switchToInactive();
223
224    /**
225     * Looks up in the branch predictor to see if the next PC should be
226     * either next PC+=MachInst or a branch target.
227     * @param next_PC Next PC variable passed in by reference.  It is
228     * expected to be set to the current PC; it will be updated with what
229     * the next PC will be.
230     * @param next_NPC Used for ISAs which use delay slots.
231     * @return Whether or not a branch was predicted as taken.
232     */
233    bool lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC, Addr &next_NPC);
234
235    /**
236     * Fetches the cache line that contains fetch_PC.  Returns any
237     * fault that happened.  Puts the data into the class variable
238     * cacheData.
239     * @param fetch_PC The PC address that is being fetched from.
240     * @param ret_fault The fault reference that will be set to the result of
241     * the icache access.
242     * @param tid Thread id.
243     * @return Any fault that occured.
244     */
245    bool fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid);
246
247    /** Squashes a specific thread and resets the PC. */
248    inline void doSquash(const Addr &new_PC, const Addr &new_NPC, unsigned tid);
249
250    /** Squashes a specific thread and resets the PC. Also tells the CPU to
251     * remove any instructions between fetch and decode that should be sqaushed.
252     */
253    void squashFromDecode(const Addr &new_PC, const Addr &new_NPC,
254                          const InstSeqNum &seq_num, unsigned tid);
255
256    /** Checks if a thread is stalled. */
257    bool checkStall(unsigned tid) const;
258
259    /** Updates overall fetch stage status; to be called at the end of each
260     * cycle. */
261    FetchStatus updateFetchStatus();
262
263  public:
264    /** Squashes a specific thread and resets the PC. Also tells the CPU to
265     * remove any instructions that are not in the ROB. The source of this
266     * squash should be the commit stage.
267     */
268    void squash(const Addr &new_PC, const Addr &new_NPC,
269                const InstSeqNum &seq_num,
270                bool squash_delay_slot, unsigned tid);
271
272    /** Ticks the fetch stage, processing all inputs signals and fetching
273     * as many instructions as possible.
274     */
275    void tick();
276
277    /** Checks all input signals and updates the status as necessary.
278     *  @return: Returns if the status has changed due to input signals.
279     */
280    bool checkSignalsAndUpdate(unsigned tid);
281
282    /** Does the actual fetching of instructions and passing them on to the
283     * next stage.
284     * @param status_change fetch() sets this variable if there was a status
285     * change (ie switching to IcacheMissStall).
286     */
287    void fetch(bool &status_change);
288
289    /** Align a PC to the start of an I-cache block. */
290    Addr icacheBlockAlignPC(Addr addr)
291    {
292        addr = TheISA::realPCToFetchPC(addr);
293        return (addr & ~(cacheBlkMask));
294    }
295
296  private:
297    /** Handles retrying the fetch access. */
298    void recvRetry();
299
300    /** Returns the appropriate thread to fetch, given the fetch policy. */
301    int getFetchingThread(FetchPriority &fetch_priority);
302
303    /** Returns the appropriate thread to fetch using a round robin policy. */
304    int roundRobin();
305
306    /** Returns the appropriate thread to fetch using the IQ count policy. */
307    int iqCount();
308
309    /** Returns the appropriate thread to fetch using the LSQ count policy. */
310    int lsqCount();
311
312    /** Returns the appropriate thread to fetch using the branch count policy. */
313    int branchCount();
314
315  private:
316    /** Pointer to the O3CPU. */
317    O3CPU *cpu;
318
319    /** Time buffer interface. */
320    TimeBuffer<TimeStruct> *timeBuffer;
321
322    /** Wire to get decode's information from backwards time buffer. */
323    typename TimeBuffer<TimeStruct>::wire fromDecode;
324
325    /** Wire to get rename's information from backwards time buffer. */
326    typename TimeBuffer<TimeStruct>::wire fromRename;
327
328    /** Wire to get iew's information from backwards time buffer. */
329    typename TimeBuffer<TimeStruct>::wire fromIEW;
330
331    /** Wire to get commit's information from backwards time buffer. */
332    typename TimeBuffer<TimeStruct>::wire fromCommit;
333
334    /** Internal fetch instruction queue. */
335    TimeBuffer<FetchStruct> *fetchQueue;
336
337    //Might be annoying how this name is different than the queue.
338    /** Wire used to write any information heading to decode. */
339    typename TimeBuffer<FetchStruct>::wire toDecode;
340
341    /** Icache interface. */
342    IcachePort *icachePort;
343
344    /** BPredUnit. */
345    BPredUnit branchPred;
346
347    /** Predecoder. */
348    TheISA::Predecoder predecoder;
349
350    /** Per-thread fetch PC. */
351    Addr PC[Impl::MaxThreads];
352
353    /** Per-thread next PC. */
354    Addr nextPC[Impl::MaxThreads];
355
356    /** Per-thread next Next PC.
357     *  This is not a real register but is used for
358     *  architectures that use a branch-delay slot.
359     *  (such as MIPS or Sparc)
360     */
361    Addr nextNPC[Impl::MaxThreads];
362
363    /** Memory request used to access cache. */
364    RequestPtr memReq[Impl::MaxThreads];
365
366    /** Variable that tracks if fetch has written to the time buffer this
367     * cycle. Used to tell CPU if there is activity this cycle.
368     */
369    bool wroteToTimeBuffer;
370
371    /** Tracks how many instructions has been fetched this cycle. */
372    int numInst;
373
374    /** Source of possible stalls. */
375    struct Stalls {
376        bool decode;
377        bool rename;
378        bool iew;
379        bool commit;
380    };
381
382    /** Tracks which stages are telling fetch to stall. */
383    Stalls stalls[Impl::MaxThreads];
384
385    /** Decode to fetch delay, in ticks. */
386    unsigned decodeToFetchDelay;
387
388    /** Rename to fetch delay, in ticks. */
389    unsigned renameToFetchDelay;
390
391    /** IEW to fetch delay, in ticks. */
392    unsigned iewToFetchDelay;
393
394    /** Commit to fetch delay, in ticks. */
395    unsigned commitToFetchDelay;
396
397    /** The width of fetch in instructions. */
398    unsigned fetchWidth;
399
400    /** Is the cache blocked?  If so no threads can access it. */
401    bool cacheBlocked;
402
403    /** The packet that is waiting to be retried. */
404    PacketPtr retryPkt;
405
406    /** The thread that is waiting on the cache to tell fetch to retry. */
407    int retryTid;
408
409    /** Cache block size. */
410    int cacheBlkSize;
411
412    /** Mask to get a cache block's address. */
413    Addr cacheBlkMask;
414
415    /** The cache line being fetched. */
416    uint8_t *cacheData[Impl::MaxThreads];
417
418    /** The PC of the cacheline that has been loaded. */
419    Addr cacheDataPC[Impl::MaxThreads];
420
421    /** Whether or not the cache data is valid. */
422    bool cacheDataValid[Impl::MaxThreads];
423
424    /** Size of instructions. */
425    int instSize;
426
427    /** Icache stall statistics. */
428    Counter lastIcacheStall[Impl::MaxThreads];
429
430    /** List of Active Threads */
431    std::list<unsigned> *activeThreads;
432
433    /** Number of threads. */
434    unsigned numThreads;
435
436    /** Number of threads that are actively fetching. */
437    unsigned numFetchingThreads;
438
439    /** Thread ID being fetched. */
440    int threadFetched;
441
442    /** Checks if there is an interrupt pending.  If there is, fetch
443     * must stop once it is not fetching PAL instructions.
444     */
445    bool interruptPending;
446
447    /** Is there a drain pending. */
448    bool drainPending;
449
450    /** Records if fetch is switched out. */
451    bool switchedOut;
452
453    // @todo: Consider making these vectors and tracking on a per thread basis.
454    /** Stat for total number of cycles stalled due to an icache miss. */
455    Stats::Scalar<> icacheStallCycles;
456    /** Stat for total number of fetched instructions. */
457    Stats::Scalar<> fetchedInsts;
458    /** Total number of fetched branches. */
459    Stats::Scalar<> fetchedBranches;
460    /** Stat for total number of predicted branches. */
461    Stats::Scalar<> predictedBranches;
462    /** Stat for total number of cycles spent fetching. */
463    Stats::Scalar<> fetchCycles;
464    /** Stat for total number of cycles spent squashing. */
465    Stats::Scalar<> fetchSquashCycles;
466    /** Stat for total number of cycles spent blocked due to other stages in
467     * the pipeline.
468     */
469    Stats::Scalar<> fetchIdleCycles;
470    /** Total number of cycles spent blocked. */
471    Stats::Scalar<> fetchBlockedCycles;
472    /** Total number of cycles spent in any other state. */
473    Stats::Scalar<> fetchMiscStallCycles;
474    /** Stat for total number of fetched cache lines. */
475    Stats::Scalar<> fetchedCacheLines;
476    /** Total number of outstanding icache accesses that were dropped
477     * due to a squash.
478     */
479    Stats::Scalar<> fetchIcacheSquashes;
480    /** Distribution of number of instructions fetched each cycle. */
481    Stats::Distribution<> fetchNisnDist;
482    /** Rate of how often fetch was idle. */
483    Stats::Formula idleRate;
484    /** Number of branch fetches per cycle. */
485    Stats::Formula branchRate;
486    /** Number of instruction fetched per cycle. */
487    Stats::Formula fetchRate;
488};
489
490#endif //__CPU_O3_FETCH_HH__
491