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