fetch.hh revision 2674:6d4afef73a20
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 */
30
31#ifndef __CPU_O3_FETCH_HH__
32#define __CPU_O3_FETCH_HH__
33
34#include "arch/utility.hh"
35#include "base/statistics.hh"
36#include "base/timebuf.hh"
37#include "cpu/pc_event.hh"
38#include "mem/packet.hh"
39#include "mem/port.hh"
40#include "sim/eventq.hh"
41
42class Sampler;
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::FullCPU FullCPU;
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    class IcachePort : public Port
73    {
74      protected:
75        DefaultFetch<Impl> *fetch;
76
77      public:
78        IcachePort(DefaultFetch<Impl> *_fetch)
79            : Port(_fetch->name() + "-iport"), fetch(_fetch)
80        { }
81
82      protected:
83        virtual Tick recvAtomic(PacketPtr pkt);
84
85        virtual void recvFunctional(PacketPtr pkt);
86
87        virtual void recvStatusChange(Status status);
88
89        virtual void getDeviceAddressRanges(AddrRangeList &resp,
90                                            AddrRangeList &snoop)
91        { resp.clear(); snoop.clear(); }
92
93        virtual bool recvTiming(PacketPtr pkt);
94
95        virtual void recvRetry();
96    };
97
98  public:
99    /** Overall fetch status. Used to determine if the CPU can
100     * deschedule itsef due to a lack of activity.
101     */
102    enum FetchStatus {
103        Active,
104        Inactive
105    };
106
107    /** Individual thread status. */
108    enum ThreadStatus {
109        Running,
110        Idle,
111        Squashing,
112        Blocked,
113        Fetching,
114        TrapPending,
115        QuiescePending,
116        SwitchOut,
117        IcacheWaitResponse,
118        IcacheRetry,
119        IcacheAccessComplete
120    };
121
122    /** Fetching Policy, Add new policies here.*/
123    enum FetchPriority {
124        SingleThread,
125        RoundRobin,
126        Branch,
127        IQ,
128        LSQ
129    };
130
131  private:
132    /** Fetch status. */
133    FetchStatus _status;
134
135    /** Per-thread status. */
136    ThreadStatus fetchStatus[Impl::MaxThreads];
137
138    /** Fetch policy. */
139    FetchPriority fetchPolicy;
140
141    /** List that has the threads organized by priority. */
142    std::list<unsigned> priorityList;
143
144  public:
145    /** DefaultFetch constructor. */
146    DefaultFetch(Params *params);
147
148    /** Returns the name of fetch. */
149    std::string name() const;
150
151    /** Registers statistics. */
152    void regStats();
153
154    /** Sets CPU pointer. */
155    void setCPU(FullCPU *cpu_ptr);
156
157    /** Sets the main backwards communication time buffer pointer. */
158    void setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer);
159
160    /** Sets pointer to list of active threads. */
161    void setActiveThreads(std::list<unsigned> *at_ptr);
162
163    /** Sets pointer to time buffer used to communicate to the next stage. */
164    void setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr);
165
166    /** Sets pointer to page table. */
167//    void setPageTable(PageTable *pt_ptr);
168
169    /** Initialize stage. */
170    void initStage();
171
172    /** Processes cache completion event. */
173    void processCacheCompletion(PacketPtr pkt);
174
175    /** Begins the switch out of the fetch stage. */
176    void switchOut();
177
178    /** Completes the switch out of the fetch stage. */
179    void doSwitchOut();
180
181    /** Takes over from another CPU's thread. */
182    void takeOverFrom();
183
184    /** Checks if the fetch stage is switched out. */
185    bool isSwitchedOut() { return switchedOut; }
186
187    /** Tells fetch to wake up from a quiesce instruction. */
188    void wakeFromQuiesce();
189
190  private:
191    /** Changes the status of this stage to active, and indicates this
192     * to the CPU.
193     */
194    inline void switchToActive();
195
196    /** Changes the status of this stage to inactive, and indicates
197     * this to the CPU.
198     */
199    inline void switchToInactive();
200
201    /**
202     * Looks up in the branch predictor to see if the next PC should be
203     * either next PC+=MachInst or a branch target.
204     * @param next_PC Next PC variable passed in by reference.  It is
205     * expected to be set to the current PC; it will be updated with what
206     * the next PC will be.
207     * @return Whether or not a branch was predicted as taken.
208     */
209    bool lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC);
210
211    /**
212     * Fetches the cache line that contains fetch_PC.  Returns any
213     * fault that happened.  Puts the data into the class variable
214     * cacheData.
215     * @param fetch_PC The PC address that is being fetched from.
216     * @param ret_fault The fault reference that will be set to the result of
217     * the icache access.
218     * @param tid Thread id.
219     * @return Any fault that occured.
220     */
221    bool fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid);
222
223    /** Squashes a specific thread and resets the PC. */
224    inline void doSquash(const Addr &new_PC, unsigned tid);
225
226    /** Squashes a specific thread and resets the PC. Also tells the CPU to
227     * remove any instructions between fetch and decode that should be sqaushed.
228     */
229    void squashFromDecode(const Addr &new_PC, const InstSeqNum &seq_num,
230                          unsigned tid);
231
232    /** Checks if a thread is stalled. */
233    bool checkStall(unsigned tid) const;
234
235    /** Updates overall fetch stage status; to be called at the end of each
236     * cycle. */
237    FetchStatus updateFetchStatus();
238
239  public:
240    /** Squashes a specific thread and resets the PC. Also tells the CPU to
241     * remove any instructions that are not in the ROB. The source of this
242     * squash should be the commit stage.
243     */
244    void squash(const Addr &new_PC, unsigned tid);
245
246    /** Ticks the fetch stage, processing all inputs signals and fetching
247     * as many instructions as possible.
248     */
249    void tick();
250
251    /** Checks all input signals and updates the status as necessary.
252     *  @return: Returns if the status has changed due to input signals.
253     */
254    bool checkSignalsAndUpdate(unsigned tid);
255
256    /** Does the actual fetching of instructions and passing them on to the
257     * next stage.
258     * @param status_change fetch() sets this variable if there was a status
259     * change (ie switching to IcacheMissStall).
260     */
261    void fetch(bool &status_change);
262
263    /** Align a PC to the start of an I-cache block. */
264    Addr icacheBlockAlignPC(Addr addr)
265    {
266        addr = TheISA::realPCToFetchPC(addr);
267        return (addr & ~(cacheBlkMask));
268    }
269
270  private:
271    /** Returns the appropriate thread to fetch, given the fetch policy. */
272    int getFetchingThread(FetchPriority &fetch_priority);
273
274    /** Returns the appropriate thread to fetch using a round robin policy. */
275    int roundRobin();
276
277    /** Returns the appropriate thread to fetch using the IQ count policy. */
278    int iqCount();
279
280    /** Returns the appropriate thread to fetch using the LSQ count policy. */
281    int lsqCount();
282
283    /** Returns the appropriate thread to fetch using the branch count policy. */
284    int branchCount();
285
286  private:
287    /** Pointer to the FullCPU. */
288    FullCPU *cpu;
289
290    /** Time buffer interface. */
291    TimeBuffer<TimeStruct> *timeBuffer;
292
293    /** Wire to get decode's information from backwards time buffer. */
294    typename TimeBuffer<TimeStruct>::wire fromDecode;
295
296    /** Wire to get rename's information from backwards time buffer. */
297    typename TimeBuffer<TimeStruct>::wire fromRename;
298
299    /** Wire to get iew's information from backwards time buffer. */
300    typename TimeBuffer<TimeStruct>::wire fromIEW;
301
302    /** Wire to get commit's information from backwards time buffer. */
303    typename TimeBuffer<TimeStruct>::wire fromCommit;
304
305    /** Internal fetch instruction queue. */
306    TimeBuffer<FetchStruct> *fetchQueue;
307
308    //Might be annoying how this name is different than the queue.
309    /** Wire used to write any information heading to decode. */
310    typename TimeBuffer<FetchStruct>::wire toDecode;
311
312    MemObject *mem;
313
314    /** Icache interface. */
315    IcachePort *icachePort;
316
317    /** BPredUnit. */
318    BPredUnit branchPred;
319
320    /** Per-thread fetch PC. */
321    Addr PC[Impl::MaxThreads];
322
323    /** Per-thread next PC. */
324    Addr nextPC[Impl::MaxThreads];
325
326    /** Memory packet used to access cache. */
327    PacketPtr memPkt[Impl::MaxThreads];
328
329    /** Variable that tracks if fetch has written to the time buffer this
330     * cycle. Used to tell CPU if there is activity this cycle.
331     */
332    bool wroteToTimeBuffer;
333
334    /** Tracks how many instructions has been fetched this cycle. */
335    int numInst;
336
337    /** Source of possible stalls. */
338    struct Stalls {
339        bool decode;
340        bool rename;
341        bool iew;
342        bool commit;
343    };
344
345    /** Tracks which stages are telling fetch to stall. */
346    Stalls stalls[Impl::MaxThreads];
347
348    /** Decode to fetch delay, in ticks. */
349    unsigned decodeToFetchDelay;
350
351    /** Rename to fetch delay, in ticks. */
352    unsigned renameToFetchDelay;
353
354    /** IEW to fetch delay, in ticks. */
355    unsigned iewToFetchDelay;
356
357    /** Commit to fetch delay, in ticks. */
358    unsigned commitToFetchDelay;
359
360    /** The width of fetch in instructions. */
361    unsigned fetchWidth;
362
363    /** Cache block size. */
364    int cacheBlkSize;
365
366    /** Mask to get a cache block's address. */
367    Addr cacheBlkMask;
368
369    /** The cache line being fetched. */
370    uint8_t *cacheData[Impl::MaxThreads];
371
372    /** Size of instructions. */
373    int instSize;
374
375    /** Icache stall statistics. */
376    Counter lastIcacheStall[Impl::MaxThreads];
377
378    /** List of Active Threads */
379    std::list<unsigned> *activeThreads;
380
381    /** Number of threads. */
382    unsigned numThreads;
383
384    /** Number of threads that are actively fetching. */
385    unsigned numFetchingThreads;
386
387    /** Thread ID being fetched. */
388    int threadFetched;
389
390    /** Checks if there is an interrupt pending.  If there is, fetch
391     * must stop once it is not fetching PAL instructions.
392     */
393    bool interruptPending;
394
395    /** Records if fetch is switched out. */
396    bool switchedOut;
397
398#if !FULL_SYSTEM
399    /** Page table pointer. */
400//    PageTable *pTable;
401#endif
402
403    // @todo: Consider making these vectors and tracking on a per thread basis.
404    /** Stat for total number of cycles stalled due to an icache miss. */
405    Stats::Scalar<> icacheStallCycles;
406    /** Stat for total number of fetched instructions. */
407    Stats::Scalar<> fetchedInsts;
408    Stats::Scalar<> fetchedBranches;
409    /** Stat for total number of predicted branches. */
410    Stats::Scalar<> predictedBranches;
411    /** Stat for total number of cycles spent fetching. */
412    Stats::Scalar<> fetchCycles;
413    /** Stat for total number of cycles spent squashing. */
414    Stats::Scalar<> fetchSquashCycles;
415    /** Stat for total number of cycles spent blocked due to other stages in
416     * the pipeline.
417     */
418    Stats::Scalar<> fetchIdleCycles;
419    /** Total number of cycles spent blocked. */
420    Stats::Scalar<> fetchBlockedCycles;
421    /** Total number of cycles spent in any other state. */
422    Stats::Scalar<> fetchMiscStallCycles;
423    /** Stat for total number of fetched cache lines. */
424    Stats::Scalar<> fetchedCacheLines;
425    /** Total number of outstanding icache accesses that were dropped
426     * due to a squash.
427     */
428    Stats::Scalar<> fetchIcacheSquashes;
429    /** Distribution of number of instructions fetched each cycle. */
430    Stats::Distribution<> fetchNisnDist;
431    /** Rate of how often fetch was idle. */
432    Stats::Formula idleRate;
433    /** Number of branch fetches per cycle. */
434    Stats::Formula branchRate;
435    /** Number of instruction fetched per cycle. */
436    Stats::Formula fetchRate;
437};
438
439#endif //__CPU_O3_FETCH_HH__
440