fetch.hh revision 2670:9107b8bd08cd
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 functionalitiy 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    void switchOut();
176
177    void doSwitchOut();
178
179    void takeOverFrom();
180
181    bool isSwitchedOut() { return switchedOut; }
182
183    void wakeFromQuiesce();
184
185  private:
186    /** Changes the status of this stage to active, and indicates this
187     * to the CPU.
188     */
189    inline void switchToActive();
190
191    /** Changes the status of this stage to inactive, and indicates
192     * this to the CPU.
193     */
194    inline void switchToInactive();
195
196    /**
197     * Looks up in the branch predictor to see if the next PC should be
198     * either next PC+=MachInst or a branch target.
199     * @param next_PC Next PC variable passed in by reference.  It is
200     * expected to be set to the current PC; it will be updated with what
201     * the next PC will be.
202     * @return Whether or not a branch was predicted as taken.
203     */
204    bool lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC);
205
206    /**
207     * Fetches the cache line that contains fetch_PC.  Returns any
208     * fault that happened.  Puts the data into the class variable
209     * cacheData.
210     * @param fetch_PC The PC address that is being fetched from.
211     * @param ret_fault The fault reference that will be set to the result of
212     * the icache access.
213     * @param tid Thread id.
214     * @return Any fault that occured.
215     */
216    bool fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid);
217
218    /** Squashes a specific thread and resets the PC. */
219    inline void doSquash(const Addr &new_PC, unsigned tid);
220
221    /** Squashes a specific thread and resets the PC. Also tells the CPU to
222     * remove any instructions between fetch and decode that should be sqaushed.
223     */
224    void squashFromDecode(const Addr &new_PC, const InstSeqNum &seq_num,
225                          unsigned tid);
226
227    /** Checks if a thread is stalled. */
228    bool checkStall(unsigned tid) const;
229
230    /** Updates overall fetch stage status; to be called at the end of each
231     * cycle. */
232    FetchStatus updateFetchStatus();
233
234  public:
235    /** Squashes a specific thread and resets the PC. Also tells the CPU to
236     * remove any instructions that are not in the ROB. The source of this
237     * squash should be the commit stage.
238     */
239    void squash(const Addr &new_PC, unsigned tid);
240
241    /** Ticks the fetch stage, processing all inputs signals and fetching
242     * as many instructions as possible.
243     */
244    void tick();
245
246    /** Checks all input signals and updates the status as necessary.
247     *  @return: Returns if the status has changed due to input signals.
248     */
249    bool checkSignalsAndUpdate(unsigned tid);
250
251    /** Does the actual fetching of instructions and passing them on to the
252     * next stage.
253     * @param status_change fetch() sets this variable if there was a status
254     * change (ie switching to IcacheMissStall).
255     */
256    void fetch(bool &status_change);
257
258    /** Align a PC to the start of an I-cache block. */
259    Addr icacheBlockAlignPC(Addr addr)
260    {
261        addr = TheISA::realPCToFetchPC(addr);
262        return (addr & ~(cacheBlkMask));
263    }
264
265  private:
266    /** Returns the appropriate thread to fetch, given the fetch policy. */
267    int getFetchingThread(FetchPriority &fetch_priority);
268
269    /** Returns the appropriate thread to fetch using a round robin policy. */
270    int roundRobin();
271
272    /** Returns the appropriate thread to fetch using the IQ count policy. */
273    int iqCount();
274
275    /** Returns the appropriate thread to fetch using the LSQ count policy. */
276    int lsqCount();
277
278    /** Returns the appropriate thread to fetch using the branch count policy. */
279    int branchCount();
280
281  private:
282    /** Pointer to the FullCPU. */
283    FullCPU *cpu;
284
285    /** Time buffer interface. */
286    TimeBuffer<TimeStruct> *timeBuffer;
287
288    /** Wire to get decode's information from backwards time buffer. */
289    typename TimeBuffer<TimeStruct>::wire fromDecode;
290
291    /** Wire to get rename's information from backwards time buffer. */
292    typename TimeBuffer<TimeStruct>::wire fromRename;
293
294    /** Wire to get iew's information from backwards time buffer. */
295    typename TimeBuffer<TimeStruct>::wire fromIEW;
296
297    /** Wire to get commit's information from backwards time buffer. */
298    typename TimeBuffer<TimeStruct>::wire fromCommit;
299
300    /** Internal fetch instruction queue. */
301    TimeBuffer<FetchStruct> *fetchQueue;
302
303    //Might be annoying how this name is different than the queue.
304    /** Wire used to write any information heading to decode. */
305    typename TimeBuffer<FetchStruct>::wire toDecode;
306
307    MemObject *mem;
308
309    /** Icache interface. */
310    IcachePort *icachePort;
311
312    /** BPredUnit. */
313    BPredUnit branchPred;
314
315    Addr PC[Impl::MaxThreads];
316
317    Addr nextPC[Impl::MaxThreads];
318
319    /** Memory packet used to access cache. */
320    PacketPtr memPkt[Impl::MaxThreads];
321
322    /** Variable that tracks if fetch has written to the time buffer this
323     * cycle. Used to tell CPU if there is activity this cycle.
324     */
325    bool wroteToTimeBuffer;
326
327    /** Tracks how many instructions has been fetched this cycle. */
328    int numInst;
329
330    /** Source of possible stalls. */
331    struct Stalls {
332        bool decode;
333        bool rename;
334        bool iew;
335        bool commit;
336    };
337
338    /** Tracks which stages are telling fetch to stall. */
339    Stalls stalls[Impl::MaxThreads];
340
341    /** Decode to fetch delay, in ticks. */
342    unsigned decodeToFetchDelay;
343
344    /** Rename to fetch delay, in ticks. */
345    unsigned renameToFetchDelay;
346
347    /** IEW to fetch delay, in ticks. */
348    unsigned iewToFetchDelay;
349
350    /** Commit to fetch delay, in ticks. */
351    unsigned commitToFetchDelay;
352
353    /** The width of fetch in instructions. */
354    unsigned fetchWidth;
355
356    /** Cache block size. */
357    int cacheBlkSize;
358
359    /** Mask to get a cache block's address. */
360    Addr cacheBlkMask;
361
362    /** The cache line being fetched. */
363    uint8_t *cacheData[Impl::MaxThreads];
364
365    /** Size of instructions. */
366    int instSize;
367
368    /** Icache stall statistics. */
369    Counter lastIcacheStall[Impl::MaxThreads];
370
371    /** List of Active Threads */
372    std::list<unsigned> *activeThreads;
373
374    /** Number of threads. */
375    unsigned numThreads;
376
377    /** Number of threads that are actively fetching. */
378    unsigned numFetchingThreads;
379
380    /** Thread ID being fetched. */
381    int threadFetched;
382
383    bool interruptPending;
384
385    bool switchedOut;
386
387#if !FULL_SYSTEM
388    /** Page table pointer. */
389//    PageTable *pTable;
390#endif
391
392    // @todo: Consider making these vectors and tracking on a per thread basis.
393    /** Stat for total number of cycles stalled due to an icache miss. */
394    Stats::Scalar<> icacheStallCycles;
395    /** Stat for total number of fetched instructions. */
396    Stats::Scalar<> fetchedInsts;
397    Stats::Scalar<> fetchedBranches;
398    /** Stat for total number of predicted branches. */
399    Stats::Scalar<> predictedBranches;
400    /** Stat for total number of cycles spent fetching. */
401    Stats::Scalar<> fetchCycles;
402    /** Stat for total number of cycles spent squashing. */
403    Stats::Scalar<> fetchSquashCycles;
404    /** Stat for total number of cycles spent blocked due to other stages in
405     * the pipeline.
406     */
407    Stats::Scalar<> fetchIdleCycles;
408    Stats::Scalar<> fetchBlockedCycles;
409
410    Stats::Scalar<> fetchMiscStallCycles;
411    /** Stat for total number of fetched cache lines. */
412    Stats::Scalar<> fetchedCacheLines;
413
414    Stats::Scalar<> fetchIcacheSquashes;
415    /** Distribution of number of instructions fetched each cycle. */
416    Stats::Distribution<> fetchNisnDist;
417    Stats::Formula idleRate;
418    Stats::Formula branchRate;
419    Stats::Formula fetchRate;
420};
421
422#endif //__CPU_O3_FETCH_HH__
423