fetch_impl.hh (5714:76abee886def) fetch_impl.hh (5890:bdef71accd68)
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#include <algorithm>
33#include <cstring>
34
35#include "config/use_checker.hh"
36
37#include "arch/isa_traits.hh"
38#include "arch/utility.hh"
39#include "cpu/checker/cpu.hh"
40#include "cpu/exetrace.hh"
41#include "cpu/o3/fetch.hh"
42#include "mem/packet.hh"
43#include "mem/request.hh"
44#include "sim/byteswap.hh"
45#include "sim/host.hh"
46#include "sim/core.hh"
47
48#if FULL_SYSTEM
49#include "arch/tlb.hh"
50#include "arch/vtophys.hh"
51#include "sim/system.hh"
52#endif // FULL_SYSTEM
53
54#include "params/DerivO3CPU.hh"
55
56template<class Impl>
57void
58DefaultFetch<Impl>::IcachePort::setPeer(Port *port)
59{
60 Port::setPeer(port);
61
62 fetch->setIcache();
63}
64
65template<class Impl>
66Tick
67DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
68{
69 panic("DefaultFetch doesn't expect recvAtomic callback!");
70 return curTick;
71}
72
73template<class Impl>
74void
75DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
76{
77 DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
78 "functional call.");
79}
80
81template<class Impl>
82void
83DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
84{
85 if (status == RangeChange) {
86 if (!snoopRangeSent) {
87 snoopRangeSent = true;
88 sendStatusChange(Port::RangeChange);
89 }
90 return;
91 }
92
93 panic("DefaultFetch doesn't expect recvStatusChange callback!");
94}
95
96template<class Impl>
97bool
98DefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
99{
100 DPRINTF(Fetch, "Received timing\n");
101 if (pkt->isResponse()) {
102 fetch->processCacheCompletion(pkt);
103 }
104 //else Snooped a coherence request, just return
105 return true;
106}
107
108template<class Impl>
109void
110DefaultFetch<Impl>::IcachePort::recvRetry()
111{
112 fetch->recvRetry();
113}
114
115template<class Impl>
116DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
117 : cpu(_cpu),
118 branchPred(params),
119 predecoder(NULL),
120 decodeToFetchDelay(params->decodeToFetchDelay),
121 renameToFetchDelay(params->renameToFetchDelay),
122 iewToFetchDelay(params->iewToFetchDelay),
123 commitToFetchDelay(params->commitToFetchDelay),
124 fetchWidth(params->fetchWidth),
125 cacheBlocked(false),
126 retryPkt(NULL),
127 retryTid(-1),
128 numThreads(params->numThreads),
129 numFetchingThreads(params->smtNumFetchingThreads),
130 interruptPending(false),
131 drainPending(false),
132 switchedOut(false)
133{
134 if (numThreads > Impl::MaxThreads)
135 fatal("numThreads is not a valid value\n");
136
137 // Set fetch stage's status to inactive.
138 _status = Inactive;
139
140 std::string policy = params->smtFetchPolicy;
141
142 // Convert string to lowercase
143 std::transform(policy.begin(), policy.end(), policy.begin(),
144 (int(*)(int)) tolower);
145
146 // Figure out fetch policy
147 if (policy == "singlethread") {
148 fetchPolicy = SingleThread;
149 if (numThreads > 1)
150 panic("Invalid Fetch Policy for a SMT workload.");
151 } else if (policy == "roundrobin") {
152 fetchPolicy = RoundRobin;
153 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
154 } else if (policy == "branch") {
155 fetchPolicy = Branch;
156 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
157 } else if (policy == "iqcount") {
158 fetchPolicy = IQ;
159 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
160 } else if (policy == "lsqcount") {
161 fetchPolicy = LSQ;
162 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
163 } else {
164 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
165 " RoundRobin,LSQcount,IQcount}\n");
166 }
167
168 // Get the size of an instruction.
169 instSize = sizeof(TheISA::MachInst);
170
171 // Name is finally available, so create the port.
172 icachePort = new IcachePort(this);
173
174 icachePort->snoopRangeSent = false;
175
176#if USE_CHECKER
177 if (cpu->checker) {
178 cpu->checker->setIcachePort(icachePort);
179 }
180#endif
181}
182
183template <class Impl>
184std::string
185DefaultFetch<Impl>::name() const
186{
187 return cpu->name() + ".fetch";
188}
189
190template <class Impl>
191void
192DefaultFetch<Impl>::regStats()
193{
194 icacheStallCycles
195 .name(name() + ".icacheStallCycles")
196 .desc("Number of cycles fetch is stalled on an Icache miss")
197 .prereq(icacheStallCycles);
198
199 fetchedInsts
200 .name(name() + ".Insts")
201 .desc("Number of instructions fetch has processed")
202 .prereq(fetchedInsts);
203
204 fetchedBranches
205 .name(name() + ".Branches")
206 .desc("Number of branches that fetch encountered")
207 .prereq(fetchedBranches);
208
209 predictedBranches
210 .name(name() + ".predictedBranches")
211 .desc("Number of branches that fetch has predicted taken")
212 .prereq(predictedBranches);
213
214 fetchCycles
215 .name(name() + ".Cycles")
216 .desc("Number of cycles fetch has run and was not squashing or"
217 " blocked")
218 .prereq(fetchCycles);
219
220 fetchSquashCycles
221 .name(name() + ".SquashCycles")
222 .desc("Number of cycles fetch has spent squashing")
223 .prereq(fetchSquashCycles);
224
225 fetchIdleCycles
226 .name(name() + ".IdleCycles")
227 .desc("Number of cycles fetch was idle")
228 .prereq(fetchIdleCycles);
229
230 fetchBlockedCycles
231 .name(name() + ".BlockedCycles")
232 .desc("Number of cycles fetch has spent blocked")
233 .prereq(fetchBlockedCycles);
234
235 fetchedCacheLines
236 .name(name() + ".CacheLines")
237 .desc("Number of cache lines fetched")
238 .prereq(fetchedCacheLines);
239
240 fetchMiscStallCycles
241 .name(name() + ".MiscStallCycles")
242 .desc("Number of cycles fetch has spent waiting on interrupts, or "
243 "bad addresses, or out of MSHRs")
244 .prereq(fetchMiscStallCycles);
245
246 fetchIcacheSquashes
247 .name(name() + ".IcacheSquashes")
248 .desc("Number of outstanding Icache misses that were squashed")
249 .prereq(fetchIcacheSquashes);
250
251 fetchNisnDist
252 .init(/* base value */ 0,
253 /* last value */ fetchWidth,
254 /* bucket size */ 1)
255 .name(name() + ".rateDist")
256 .desc("Number of instructions fetched each cycle (Total)")
257 .flags(Stats::pdf);
258
259 idleRate
260 .name(name() + ".idleRate")
261 .desc("Percent of cycles fetch was idle")
262 .prereq(idleRate);
263 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
264
265 branchRate
266 .name(name() + ".branchRate")
267 .desc("Number of branch fetches per cycle")
268 .flags(Stats::total);
269 branchRate = fetchedBranches / cpu->numCycles;
270
271 fetchRate
272 .name(name() + ".rate")
273 .desc("Number of inst fetches per cycle")
274 .flags(Stats::total);
275 fetchRate = fetchedInsts / cpu->numCycles;
276
277 branchPred.regStats();
278}
279
280template<class Impl>
281void
282DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
283{
284 timeBuffer = time_buffer;
285
286 // Create wires to get information from proper places in time buffer.
287 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
288 fromRename = timeBuffer->getWire(-renameToFetchDelay);
289 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
290 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
291}
292
293template<class Impl>
294void
295DefaultFetch<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
296{
297 activeThreads = at_ptr;
298}
299
300template<class Impl>
301void
302DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
303{
304 fetchQueue = fq_ptr;
305
306 // Create wire to write information to proper place in fetch queue.
307 toDecode = fetchQueue->getWire(0);
308}
309
310template<class Impl>
311void
312DefaultFetch<Impl>::initStage()
313{
314 // Setup PC and nextPC with initial state.
315 for (int tid = 0; tid < numThreads; tid++) {
316 PC[tid] = cpu->readPC(tid);
317 nextPC[tid] = cpu->readNextPC(tid);
318 microPC[tid] = cpu->readMicroPC(tid);
319 }
320
321 for (int tid=0; tid < numThreads; tid++) {
322
323 fetchStatus[tid] = Running;
324
325 priorityList.push_back(tid);
326
327 memReq[tid] = NULL;
328
329 stalls[tid].decode = false;
330 stalls[tid].rename = false;
331 stalls[tid].iew = false;
332 stalls[tid].commit = false;
333 }
334
335 // Schedule fetch to get the correct PC from the CPU
336 // scheduleFetchStartupEvent(1);
337
338 // Fetch needs to start fetching instructions at the very beginning,
339 // so it must start up in active state.
340 switchToActive();
341}
342
343template<class Impl>
344void
345DefaultFetch<Impl>::setIcache()
346{
347 // Size of cache block.
348 cacheBlkSize = icachePort->peerBlockSize();
349
350 // Create mask to get rid of offset bits.
351 cacheBlkMask = (cacheBlkSize - 1);
352
353 for (int tid=0; tid < numThreads; tid++) {
354 // Create space to store a cache line.
355 cacheData[tid] = new uint8_t[cacheBlkSize];
356 cacheDataPC[tid] = 0;
357 cacheDataValid[tid] = false;
358 }
359}
360
361template<class Impl>
362void
363DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
364{
365 unsigned tid = pkt->req->threadId();
366
367 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
368
369 assert(!pkt->wasNacked());
370
371 // Only change the status if it's still waiting on the icache access
372 // to return.
373 if (fetchStatus[tid] != IcacheWaitResponse ||
374 pkt->req != memReq[tid] ||
375 isSwitchedOut()) {
376 ++fetchIcacheSquashes;
377 delete pkt->req;
378 delete pkt;
379 return;
380 }
381
382 memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
383 cacheDataValid[tid] = true;
384
385 if (!drainPending) {
386 // Wake up the CPU (if it went to sleep and was waiting on
387 // this completion event).
388 cpu->wakeCPU();
389
390 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
391 tid);
392
393 switchToActive();
394 }
395
396 // Only switch to IcacheAccessComplete if we're not stalled as well.
397 if (checkStall(tid)) {
398 fetchStatus[tid] = Blocked;
399 } else {
400 fetchStatus[tid] = IcacheAccessComplete;
401 }
402
403 // Reset the mem req to NULL.
404 delete pkt->req;
405 delete pkt;
406 memReq[tid] = NULL;
407}
408
409template <class Impl>
410bool
411DefaultFetch<Impl>::drain()
412{
413 // Fetch is ready to drain at any time.
414 cpu->signalDrained();
415 drainPending = true;
416 return true;
417}
418
419template <class Impl>
420void
421DefaultFetch<Impl>::resume()
422{
423 drainPending = false;
424}
425
426template <class Impl>
427void
428DefaultFetch<Impl>::switchOut()
429{
430 switchedOut = true;
431 // Branch predictor needs to have its state cleared.
432 branchPred.switchOut();
433}
434
435template <class Impl>
436void
437DefaultFetch<Impl>::takeOverFrom()
438{
439 // Reset all state
440 for (int i = 0; i < Impl::MaxThreads; ++i) {
441 stalls[i].decode = 0;
442 stalls[i].rename = 0;
443 stalls[i].iew = 0;
444 stalls[i].commit = 0;
445 PC[i] = cpu->readPC(i);
446 nextPC[i] = cpu->readNextPC(i);
447 microPC[i] = cpu->readMicroPC(i);
448 fetchStatus[i] = Running;
449 }
450 numInst = 0;
451 wroteToTimeBuffer = false;
452 _status = Inactive;
453 switchedOut = false;
454 interruptPending = false;
455 branchPred.takeOverFrom();
456}
457
458template <class Impl>
459void
460DefaultFetch<Impl>::wakeFromQuiesce()
461{
462 DPRINTF(Fetch, "Waking up from quiesce\n");
463 // Hopefully this is safe
464 // @todo: Allow other threads to wake from quiesce.
465 fetchStatus[0] = Running;
466}
467
468template <class Impl>
469inline void
470DefaultFetch<Impl>::switchToActive()
471{
472 if (_status == Inactive) {
473 DPRINTF(Activity, "Activating stage.\n");
474
475 cpu->activateStage(O3CPU::FetchIdx);
476
477 _status = Active;
478 }
479}
480
481template <class Impl>
482inline void
483DefaultFetch<Impl>::switchToInactive()
484{
485 if (_status == Active) {
486 DPRINTF(Activity, "Deactivating stage.\n");
487
488 cpu->deactivateStage(O3CPU::FetchIdx);
489
490 _status = Inactive;
491 }
492}
493
494template <class Impl>
495bool
496DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC,
497 Addr &next_NPC, Addr &next_MicroPC)
498{
499 // Do branch prediction check here.
500 // A bit of a misnomer...next_PC is actually the current PC until
501 // this function updates it.
502 bool predict_taken;
503
504 if (!inst->isControl()) {
505 if (inst->isMicroop() && !inst->isLastMicroop()) {
506 next_MicroPC++;
507 } else {
508 next_PC = next_NPC;
509 next_NPC = next_NPC + instSize;
510 next_MicroPC = 0;
511 }
512 inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
513 inst->setPredTaken(false);
514 return false;
515 }
516
517 //Assume for now that all control flow is to a different macroop which
518 //would reset the micro pc to 0.
519 next_MicroPC = 0;
520
521 int tid = inst->threadNumber;
522 Addr pred_PC = next_PC;
523 predict_taken = branchPred.predict(inst, pred_PC, tid);
524
525/* if (predict_taken) {
526 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be taken to %#x.\n",
527 tid, pred_PC);
528 } else {
529 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be not taken.\n", tid);
530 }*/
531
532#if ISA_HAS_DELAY_SLOT
533 next_PC = next_NPC;
534 if (predict_taken)
535 next_NPC = pred_PC;
536 else
537 next_NPC += instSize;
538#else
539 if (predict_taken)
540 next_PC = pred_PC;
541 else
542 next_PC += instSize;
543 next_NPC = next_PC + instSize;
544#endif
545/* DPRINTF(Fetch, "[tid:%i]: Branch predicted to go to %#x and then %#x.\n",
546 tid, next_PC, next_NPC);*/
547 inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
548 inst->setPredTaken(predict_taken);
549
550 ++fetchedBranches;
551
552 if (predict_taken) {
553 ++predictedBranches;
554 }
555
556 return predict_taken;
557}
558
559template <class Impl>
560bool
561DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
562{
563 Fault fault = NoFault;
564
565 //AlphaDep
566 if (cacheBlocked) {
567 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
568 tid);
569 return false;
570 } else if (isSwitchedOut()) {
571 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
572 tid);
573 return false;
574 } else if (interruptPending && !(fetch_PC & 0x3)) {
575 // Hold off fetch from getting new instructions when:
576 // Cache is blocked, or
577 // while an interrupt is pending and we're not in PAL mode, or
578 // fetch is switched out.
579 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
580 tid);
581 return false;
582 }
583
584 // Align the fetch PC so it's at the start of a cache block.
585 Addr block_PC = icacheBlockAlignPC(fetch_PC);
586
587 // If we've already got the block, no need to try to fetch it again.
588 if (cacheDataValid[tid] && block_PC == cacheDataPC[tid]) {
589 return true;
590 }
591
592 // Setup the memReq to do a read of the first instruction's address.
593 // Set the appropriate read size and flags as well.
594 // Build request here.
595 RequestPtr mem_req = new Request(tid, block_PC, cacheBlkSize, 0,
596 fetch_PC, cpu->thread[tid]->contextId(),
597 tid);
598
599 memReq[tid] = mem_req;
600
601 // Translate the instruction request.
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#include <algorithm>
33#include <cstring>
34
35#include "config/use_checker.hh"
36
37#include "arch/isa_traits.hh"
38#include "arch/utility.hh"
39#include "cpu/checker/cpu.hh"
40#include "cpu/exetrace.hh"
41#include "cpu/o3/fetch.hh"
42#include "mem/packet.hh"
43#include "mem/request.hh"
44#include "sim/byteswap.hh"
45#include "sim/host.hh"
46#include "sim/core.hh"
47
48#if FULL_SYSTEM
49#include "arch/tlb.hh"
50#include "arch/vtophys.hh"
51#include "sim/system.hh"
52#endif // FULL_SYSTEM
53
54#include "params/DerivO3CPU.hh"
55
56template<class Impl>
57void
58DefaultFetch<Impl>::IcachePort::setPeer(Port *port)
59{
60 Port::setPeer(port);
61
62 fetch->setIcache();
63}
64
65template<class Impl>
66Tick
67DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
68{
69 panic("DefaultFetch doesn't expect recvAtomic callback!");
70 return curTick;
71}
72
73template<class Impl>
74void
75DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
76{
77 DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
78 "functional call.");
79}
80
81template<class Impl>
82void
83DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
84{
85 if (status == RangeChange) {
86 if (!snoopRangeSent) {
87 snoopRangeSent = true;
88 sendStatusChange(Port::RangeChange);
89 }
90 return;
91 }
92
93 panic("DefaultFetch doesn't expect recvStatusChange callback!");
94}
95
96template<class Impl>
97bool
98DefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
99{
100 DPRINTF(Fetch, "Received timing\n");
101 if (pkt->isResponse()) {
102 fetch->processCacheCompletion(pkt);
103 }
104 //else Snooped a coherence request, just return
105 return true;
106}
107
108template<class Impl>
109void
110DefaultFetch<Impl>::IcachePort::recvRetry()
111{
112 fetch->recvRetry();
113}
114
115template<class Impl>
116DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
117 : cpu(_cpu),
118 branchPred(params),
119 predecoder(NULL),
120 decodeToFetchDelay(params->decodeToFetchDelay),
121 renameToFetchDelay(params->renameToFetchDelay),
122 iewToFetchDelay(params->iewToFetchDelay),
123 commitToFetchDelay(params->commitToFetchDelay),
124 fetchWidth(params->fetchWidth),
125 cacheBlocked(false),
126 retryPkt(NULL),
127 retryTid(-1),
128 numThreads(params->numThreads),
129 numFetchingThreads(params->smtNumFetchingThreads),
130 interruptPending(false),
131 drainPending(false),
132 switchedOut(false)
133{
134 if (numThreads > Impl::MaxThreads)
135 fatal("numThreads is not a valid value\n");
136
137 // Set fetch stage's status to inactive.
138 _status = Inactive;
139
140 std::string policy = params->smtFetchPolicy;
141
142 // Convert string to lowercase
143 std::transform(policy.begin(), policy.end(), policy.begin(),
144 (int(*)(int)) tolower);
145
146 // Figure out fetch policy
147 if (policy == "singlethread") {
148 fetchPolicy = SingleThread;
149 if (numThreads > 1)
150 panic("Invalid Fetch Policy for a SMT workload.");
151 } else if (policy == "roundrobin") {
152 fetchPolicy = RoundRobin;
153 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
154 } else if (policy == "branch") {
155 fetchPolicy = Branch;
156 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
157 } else if (policy == "iqcount") {
158 fetchPolicy = IQ;
159 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
160 } else if (policy == "lsqcount") {
161 fetchPolicy = LSQ;
162 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
163 } else {
164 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
165 " RoundRobin,LSQcount,IQcount}\n");
166 }
167
168 // Get the size of an instruction.
169 instSize = sizeof(TheISA::MachInst);
170
171 // Name is finally available, so create the port.
172 icachePort = new IcachePort(this);
173
174 icachePort->snoopRangeSent = false;
175
176#if USE_CHECKER
177 if (cpu->checker) {
178 cpu->checker->setIcachePort(icachePort);
179 }
180#endif
181}
182
183template <class Impl>
184std::string
185DefaultFetch<Impl>::name() const
186{
187 return cpu->name() + ".fetch";
188}
189
190template <class Impl>
191void
192DefaultFetch<Impl>::regStats()
193{
194 icacheStallCycles
195 .name(name() + ".icacheStallCycles")
196 .desc("Number of cycles fetch is stalled on an Icache miss")
197 .prereq(icacheStallCycles);
198
199 fetchedInsts
200 .name(name() + ".Insts")
201 .desc("Number of instructions fetch has processed")
202 .prereq(fetchedInsts);
203
204 fetchedBranches
205 .name(name() + ".Branches")
206 .desc("Number of branches that fetch encountered")
207 .prereq(fetchedBranches);
208
209 predictedBranches
210 .name(name() + ".predictedBranches")
211 .desc("Number of branches that fetch has predicted taken")
212 .prereq(predictedBranches);
213
214 fetchCycles
215 .name(name() + ".Cycles")
216 .desc("Number of cycles fetch has run and was not squashing or"
217 " blocked")
218 .prereq(fetchCycles);
219
220 fetchSquashCycles
221 .name(name() + ".SquashCycles")
222 .desc("Number of cycles fetch has spent squashing")
223 .prereq(fetchSquashCycles);
224
225 fetchIdleCycles
226 .name(name() + ".IdleCycles")
227 .desc("Number of cycles fetch was idle")
228 .prereq(fetchIdleCycles);
229
230 fetchBlockedCycles
231 .name(name() + ".BlockedCycles")
232 .desc("Number of cycles fetch has spent blocked")
233 .prereq(fetchBlockedCycles);
234
235 fetchedCacheLines
236 .name(name() + ".CacheLines")
237 .desc("Number of cache lines fetched")
238 .prereq(fetchedCacheLines);
239
240 fetchMiscStallCycles
241 .name(name() + ".MiscStallCycles")
242 .desc("Number of cycles fetch has spent waiting on interrupts, or "
243 "bad addresses, or out of MSHRs")
244 .prereq(fetchMiscStallCycles);
245
246 fetchIcacheSquashes
247 .name(name() + ".IcacheSquashes")
248 .desc("Number of outstanding Icache misses that were squashed")
249 .prereq(fetchIcacheSquashes);
250
251 fetchNisnDist
252 .init(/* base value */ 0,
253 /* last value */ fetchWidth,
254 /* bucket size */ 1)
255 .name(name() + ".rateDist")
256 .desc("Number of instructions fetched each cycle (Total)")
257 .flags(Stats::pdf);
258
259 idleRate
260 .name(name() + ".idleRate")
261 .desc("Percent of cycles fetch was idle")
262 .prereq(idleRate);
263 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
264
265 branchRate
266 .name(name() + ".branchRate")
267 .desc("Number of branch fetches per cycle")
268 .flags(Stats::total);
269 branchRate = fetchedBranches / cpu->numCycles;
270
271 fetchRate
272 .name(name() + ".rate")
273 .desc("Number of inst fetches per cycle")
274 .flags(Stats::total);
275 fetchRate = fetchedInsts / cpu->numCycles;
276
277 branchPred.regStats();
278}
279
280template<class Impl>
281void
282DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
283{
284 timeBuffer = time_buffer;
285
286 // Create wires to get information from proper places in time buffer.
287 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
288 fromRename = timeBuffer->getWire(-renameToFetchDelay);
289 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
290 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
291}
292
293template<class Impl>
294void
295DefaultFetch<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
296{
297 activeThreads = at_ptr;
298}
299
300template<class Impl>
301void
302DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
303{
304 fetchQueue = fq_ptr;
305
306 // Create wire to write information to proper place in fetch queue.
307 toDecode = fetchQueue->getWire(0);
308}
309
310template<class Impl>
311void
312DefaultFetch<Impl>::initStage()
313{
314 // Setup PC and nextPC with initial state.
315 for (int tid = 0; tid < numThreads; tid++) {
316 PC[tid] = cpu->readPC(tid);
317 nextPC[tid] = cpu->readNextPC(tid);
318 microPC[tid] = cpu->readMicroPC(tid);
319 }
320
321 for (int tid=0; tid < numThreads; tid++) {
322
323 fetchStatus[tid] = Running;
324
325 priorityList.push_back(tid);
326
327 memReq[tid] = NULL;
328
329 stalls[tid].decode = false;
330 stalls[tid].rename = false;
331 stalls[tid].iew = false;
332 stalls[tid].commit = false;
333 }
334
335 // Schedule fetch to get the correct PC from the CPU
336 // scheduleFetchStartupEvent(1);
337
338 // Fetch needs to start fetching instructions at the very beginning,
339 // so it must start up in active state.
340 switchToActive();
341}
342
343template<class Impl>
344void
345DefaultFetch<Impl>::setIcache()
346{
347 // Size of cache block.
348 cacheBlkSize = icachePort->peerBlockSize();
349
350 // Create mask to get rid of offset bits.
351 cacheBlkMask = (cacheBlkSize - 1);
352
353 for (int tid=0; tid < numThreads; tid++) {
354 // Create space to store a cache line.
355 cacheData[tid] = new uint8_t[cacheBlkSize];
356 cacheDataPC[tid] = 0;
357 cacheDataValid[tid] = false;
358 }
359}
360
361template<class Impl>
362void
363DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
364{
365 unsigned tid = pkt->req->threadId();
366
367 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
368
369 assert(!pkt->wasNacked());
370
371 // Only change the status if it's still waiting on the icache access
372 // to return.
373 if (fetchStatus[tid] != IcacheWaitResponse ||
374 pkt->req != memReq[tid] ||
375 isSwitchedOut()) {
376 ++fetchIcacheSquashes;
377 delete pkt->req;
378 delete pkt;
379 return;
380 }
381
382 memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
383 cacheDataValid[tid] = true;
384
385 if (!drainPending) {
386 // Wake up the CPU (if it went to sleep and was waiting on
387 // this completion event).
388 cpu->wakeCPU();
389
390 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
391 tid);
392
393 switchToActive();
394 }
395
396 // Only switch to IcacheAccessComplete if we're not stalled as well.
397 if (checkStall(tid)) {
398 fetchStatus[tid] = Blocked;
399 } else {
400 fetchStatus[tid] = IcacheAccessComplete;
401 }
402
403 // Reset the mem req to NULL.
404 delete pkt->req;
405 delete pkt;
406 memReq[tid] = NULL;
407}
408
409template <class Impl>
410bool
411DefaultFetch<Impl>::drain()
412{
413 // Fetch is ready to drain at any time.
414 cpu->signalDrained();
415 drainPending = true;
416 return true;
417}
418
419template <class Impl>
420void
421DefaultFetch<Impl>::resume()
422{
423 drainPending = false;
424}
425
426template <class Impl>
427void
428DefaultFetch<Impl>::switchOut()
429{
430 switchedOut = true;
431 // Branch predictor needs to have its state cleared.
432 branchPred.switchOut();
433}
434
435template <class Impl>
436void
437DefaultFetch<Impl>::takeOverFrom()
438{
439 // Reset all state
440 for (int i = 0; i < Impl::MaxThreads; ++i) {
441 stalls[i].decode = 0;
442 stalls[i].rename = 0;
443 stalls[i].iew = 0;
444 stalls[i].commit = 0;
445 PC[i] = cpu->readPC(i);
446 nextPC[i] = cpu->readNextPC(i);
447 microPC[i] = cpu->readMicroPC(i);
448 fetchStatus[i] = Running;
449 }
450 numInst = 0;
451 wroteToTimeBuffer = false;
452 _status = Inactive;
453 switchedOut = false;
454 interruptPending = false;
455 branchPred.takeOverFrom();
456}
457
458template <class Impl>
459void
460DefaultFetch<Impl>::wakeFromQuiesce()
461{
462 DPRINTF(Fetch, "Waking up from quiesce\n");
463 // Hopefully this is safe
464 // @todo: Allow other threads to wake from quiesce.
465 fetchStatus[0] = Running;
466}
467
468template <class Impl>
469inline void
470DefaultFetch<Impl>::switchToActive()
471{
472 if (_status == Inactive) {
473 DPRINTF(Activity, "Activating stage.\n");
474
475 cpu->activateStage(O3CPU::FetchIdx);
476
477 _status = Active;
478 }
479}
480
481template <class Impl>
482inline void
483DefaultFetch<Impl>::switchToInactive()
484{
485 if (_status == Active) {
486 DPRINTF(Activity, "Deactivating stage.\n");
487
488 cpu->deactivateStage(O3CPU::FetchIdx);
489
490 _status = Inactive;
491 }
492}
493
494template <class Impl>
495bool
496DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC,
497 Addr &next_NPC, Addr &next_MicroPC)
498{
499 // Do branch prediction check here.
500 // A bit of a misnomer...next_PC is actually the current PC until
501 // this function updates it.
502 bool predict_taken;
503
504 if (!inst->isControl()) {
505 if (inst->isMicroop() && !inst->isLastMicroop()) {
506 next_MicroPC++;
507 } else {
508 next_PC = next_NPC;
509 next_NPC = next_NPC + instSize;
510 next_MicroPC = 0;
511 }
512 inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
513 inst->setPredTaken(false);
514 return false;
515 }
516
517 //Assume for now that all control flow is to a different macroop which
518 //would reset the micro pc to 0.
519 next_MicroPC = 0;
520
521 int tid = inst->threadNumber;
522 Addr pred_PC = next_PC;
523 predict_taken = branchPred.predict(inst, pred_PC, tid);
524
525/* if (predict_taken) {
526 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be taken to %#x.\n",
527 tid, pred_PC);
528 } else {
529 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be not taken.\n", tid);
530 }*/
531
532#if ISA_HAS_DELAY_SLOT
533 next_PC = next_NPC;
534 if (predict_taken)
535 next_NPC = pred_PC;
536 else
537 next_NPC += instSize;
538#else
539 if (predict_taken)
540 next_PC = pred_PC;
541 else
542 next_PC += instSize;
543 next_NPC = next_PC + instSize;
544#endif
545/* DPRINTF(Fetch, "[tid:%i]: Branch predicted to go to %#x and then %#x.\n",
546 tid, next_PC, next_NPC);*/
547 inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
548 inst->setPredTaken(predict_taken);
549
550 ++fetchedBranches;
551
552 if (predict_taken) {
553 ++predictedBranches;
554 }
555
556 return predict_taken;
557}
558
559template <class Impl>
560bool
561DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
562{
563 Fault fault = NoFault;
564
565 //AlphaDep
566 if (cacheBlocked) {
567 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
568 tid);
569 return false;
570 } else if (isSwitchedOut()) {
571 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
572 tid);
573 return false;
574 } else if (interruptPending && !(fetch_PC & 0x3)) {
575 // Hold off fetch from getting new instructions when:
576 // Cache is blocked, or
577 // while an interrupt is pending and we're not in PAL mode, or
578 // fetch is switched out.
579 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
580 tid);
581 return false;
582 }
583
584 // Align the fetch PC so it's at the start of a cache block.
585 Addr block_PC = icacheBlockAlignPC(fetch_PC);
586
587 // If we've already got the block, no need to try to fetch it again.
588 if (cacheDataValid[tid] && block_PC == cacheDataPC[tid]) {
589 return true;
590 }
591
592 // Setup the memReq to do a read of the first instruction's address.
593 // Set the appropriate read size and flags as well.
594 // Build request here.
595 RequestPtr mem_req = new Request(tid, block_PC, cacheBlkSize, 0,
596 fetch_PC, cpu->thread[tid]->contextId(),
597 tid);
598
599 memReq[tid] = mem_req;
600
601 // Translate the instruction request.
602 fault = cpu->translateInstReq(mem_req, cpu->thread[tid]);
602 fault = cpu->itb->translate(mem_req, cpu->thread[tid]->getTC());
603
604 // In the case of faults, the fetch stage may need to stall and wait
605 // for the ITB miss to be handled.
606
607 // If translation was successful, attempt to read the first
608 // instruction.
609 if (fault == NoFault) {
610#if 0
611 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
612 memReq[tid]->isUncacheable()) {
613 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
614 "misspeculating path)!",
615 memReq[tid]->paddr);
616 ret_fault = TheISA::genMachineCheckFault();
617 return false;
618 }
619#endif
620
621 // Build packet here.
622 PacketPtr data_pkt = new Packet(mem_req,
623 MemCmd::ReadReq, Packet::Broadcast);
624 data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
625
626 cacheDataPC[tid] = block_PC;
627 cacheDataValid[tid] = false;
628
629 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
630
631 fetchedCacheLines++;
632
633 // Now do the timing access to see whether or not the instruction
634 // exists within the cache.
635 if (!icachePort->sendTiming(data_pkt)) {
636 assert(retryPkt == NULL);
637 assert(retryTid == -1);
638 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
639 fetchStatus[tid] = IcacheWaitRetry;
640 retryPkt = data_pkt;
641 retryTid = tid;
642 cacheBlocked = true;
643 return false;
644 }
645
646 DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
647
648 lastIcacheStall[tid] = curTick;
649
650 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
651 "response.\n", tid);
652
653 fetchStatus[tid] = IcacheWaitResponse;
654 } else {
655 delete mem_req;
656 memReq[tid] = NULL;
657 }
658
659 ret_fault = fault;
660 return true;
661}
662
663template <class Impl>
664inline void
665DefaultFetch<Impl>::doSquash(const Addr &new_PC,
666 const Addr &new_NPC, const Addr &new_microPC, unsigned tid)
667{
668 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x, NPC to: %#x.\n",
669 tid, new_PC, new_NPC);
670
671 PC[tid] = new_PC;
672 nextPC[tid] = new_NPC;
673 microPC[tid] = new_microPC;
674
675 // Clear the icache miss if it's outstanding.
676 if (fetchStatus[tid] == IcacheWaitResponse) {
677 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
678 tid);
679 memReq[tid] = NULL;
680 }
681
682 // Get rid of the retrying packet if it was from this thread.
683 if (retryTid == tid) {
684 assert(cacheBlocked);
685 if (retryPkt) {
686 delete retryPkt->req;
687 delete retryPkt;
688 }
689 retryPkt = NULL;
690 retryTid = -1;
691 }
692
693 fetchStatus[tid] = Squashing;
694
695 ++fetchSquashCycles;
696}
697
698template<class Impl>
699void
700DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC, const Addr &new_NPC,
701 const Addr &new_MicroPC,
702 const InstSeqNum &seq_num, unsigned tid)
703{
704 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
705
706 doSquash(new_PC, new_NPC, new_MicroPC, tid);
707
708 // Tell the CPU to remove any instructions that are in flight between
709 // fetch and decode.
710 cpu->removeInstsUntil(seq_num, tid);
711}
712
713template<class Impl>
714bool
715DefaultFetch<Impl>::checkStall(unsigned tid) const
716{
717 bool ret_val = false;
718
719 if (cpu->contextSwitch) {
720 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
721 ret_val = true;
722 } else if (stalls[tid].decode) {
723 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
724 ret_val = true;
725 } else if (stalls[tid].rename) {
726 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
727 ret_val = true;
728 } else if (stalls[tid].iew) {
729 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
730 ret_val = true;
731 } else if (stalls[tid].commit) {
732 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
733 ret_val = true;
734 }
735
736 return ret_val;
737}
738
739template<class Impl>
740typename DefaultFetch<Impl>::FetchStatus
741DefaultFetch<Impl>::updateFetchStatus()
742{
743 //Check Running
744 std::list<unsigned>::iterator threads = activeThreads->begin();
745 std::list<unsigned>::iterator end = activeThreads->end();
746
747 while (threads != end) {
748 unsigned tid = *threads++;
749
750 if (fetchStatus[tid] == Running ||
751 fetchStatus[tid] == Squashing ||
752 fetchStatus[tid] == IcacheAccessComplete) {
753
754 if (_status == Inactive) {
755 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
756
757 if (fetchStatus[tid] == IcacheAccessComplete) {
758 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
759 "completion\n",tid);
760 }
761
762 cpu->activateStage(O3CPU::FetchIdx);
763 }
764
765 return Active;
766 }
767 }
768
769 // Stage is switching from active to inactive, notify CPU of it.
770 if (_status == Active) {
771 DPRINTF(Activity, "Deactivating stage.\n");
772
773 cpu->deactivateStage(O3CPU::FetchIdx);
774 }
775
776 return Inactive;
777}
778
779template <class Impl>
780void
781DefaultFetch<Impl>::squash(const Addr &new_PC, const Addr &new_NPC,
782 const Addr &new_MicroPC,
783 const InstSeqNum &seq_num, unsigned tid)
784{
785 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
786
787 doSquash(new_PC, new_NPC, new_MicroPC, tid);
788
789 // Tell the CPU to remove any instructions that are not in the ROB.
790 cpu->removeInstsNotInROB(tid);
791}
792
793template <class Impl>
794void
795DefaultFetch<Impl>::tick()
796{
797 std::list<unsigned>::iterator threads = activeThreads->begin();
798 std::list<unsigned>::iterator end = activeThreads->end();
799 bool status_change = false;
800
801 wroteToTimeBuffer = false;
802
803 while (threads != end) {
804 unsigned tid = *threads++;
805
806 // Check the signals for each thread to determine the proper status
807 // for each thread.
808 bool updated_status = checkSignalsAndUpdate(tid);
809 status_change = status_change || updated_status;
810 }
811
812 DPRINTF(Fetch, "Running stage.\n");
813
814 // Reset the number of the instruction we're fetching.
815 numInst = 0;
816
817#if FULL_SYSTEM
818 if (fromCommit->commitInfo[0].interruptPending) {
819 interruptPending = true;
820 }
821
822 if (fromCommit->commitInfo[0].clearInterrupt) {
823 interruptPending = false;
824 }
825#endif
826
827 for (threadFetched = 0; threadFetched < numFetchingThreads;
828 threadFetched++) {
829 // Fetch each of the actively fetching threads.
830 fetch(status_change);
831 }
832
833 // Record number of instructions fetched this cycle for distribution.
834 fetchNisnDist.sample(numInst);
835
836 if (status_change) {
837 // Change the fetch stage status if there was a status change.
838 _status = updateFetchStatus();
839 }
840
841 // If there was activity this cycle, inform the CPU of it.
842 if (wroteToTimeBuffer || cpu->contextSwitch) {
843 DPRINTF(Activity, "Activity this cycle.\n");
844
845 cpu->activityThisCycle();
846 }
847}
848
849template <class Impl>
850bool
851DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
852{
853 // Update the per thread stall statuses.
854 if (fromDecode->decodeBlock[tid]) {
855 stalls[tid].decode = true;
856 }
857
858 if (fromDecode->decodeUnblock[tid]) {
859 assert(stalls[tid].decode);
860 assert(!fromDecode->decodeBlock[tid]);
861 stalls[tid].decode = false;
862 }
863
864 if (fromRename->renameBlock[tid]) {
865 stalls[tid].rename = true;
866 }
867
868 if (fromRename->renameUnblock[tid]) {
869 assert(stalls[tid].rename);
870 assert(!fromRename->renameBlock[tid]);
871 stalls[tid].rename = false;
872 }
873
874 if (fromIEW->iewBlock[tid]) {
875 stalls[tid].iew = true;
876 }
877
878 if (fromIEW->iewUnblock[tid]) {
879 assert(stalls[tid].iew);
880 assert(!fromIEW->iewBlock[tid]);
881 stalls[tid].iew = false;
882 }
883
884 if (fromCommit->commitBlock[tid]) {
885 stalls[tid].commit = true;
886 }
887
888 if (fromCommit->commitUnblock[tid]) {
889 assert(stalls[tid].commit);
890 assert(!fromCommit->commitBlock[tid]);
891 stalls[tid].commit = false;
892 }
893
894 // Check squash signals from commit.
895 if (fromCommit->commitInfo[tid].squash) {
896
897 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
898 "from commit.\n",tid);
899 // In any case, squash.
900 squash(fromCommit->commitInfo[tid].nextPC,
901 fromCommit->commitInfo[tid].nextNPC,
902 fromCommit->commitInfo[tid].nextMicroPC,
903 fromCommit->commitInfo[tid].doneSeqNum,
904 tid);
905
906 // Also check if there's a mispredict that happened.
907 if (fromCommit->commitInfo[tid].branchMispredict) {
908 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
909 fromCommit->commitInfo[tid].nextPC,
910 fromCommit->commitInfo[tid].branchTaken,
911 tid);
912 } else {
913 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
914 tid);
915 }
916
917 return true;
918 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
919 // Update the branch predictor if it wasn't a squashed instruction
920 // that was broadcasted.
921 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
922 }
923
924 // Check ROB squash signals from commit.
925 if (fromCommit->commitInfo[tid].robSquashing) {
926 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
927
928 // Continue to squash.
929 fetchStatus[tid] = Squashing;
930
931 return true;
932 }
933
934 // Check squash signals from decode.
935 if (fromDecode->decodeInfo[tid].squash) {
936 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
937 "from decode.\n",tid);
938
939 // Update the branch predictor.
940 if (fromDecode->decodeInfo[tid].branchMispredict) {
941 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
942 fromDecode->decodeInfo[tid].nextPC,
943 fromDecode->decodeInfo[tid].branchTaken,
944 tid);
945 } else {
946 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
947 tid);
948 }
949
950 if (fetchStatus[tid] != Squashing) {
951
952 DPRINTF(Fetch, "Squashing from decode with PC = %#x, NPC = %#x\n",
953 fromDecode->decodeInfo[tid].nextPC,
954 fromDecode->decodeInfo[tid].nextNPC);
955 // Squash unless we're already squashing
956 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
957 fromDecode->decodeInfo[tid].nextNPC,
958 fromDecode->decodeInfo[tid].nextMicroPC,
959 fromDecode->decodeInfo[tid].doneSeqNum,
960 tid);
961
962 return true;
963 }
964 }
965
966 if (checkStall(tid) &&
967 fetchStatus[tid] != IcacheWaitResponse &&
968 fetchStatus[tid] != IcacheWaitRetry) {
969 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
970
971 fetchStatus[tid] = Blocked;
972
973 return true;
974 }
975
976 if (fetchStatus[tid] == Blocked ||
977 fetchStatus[tid] == Squashing) {
978 // Switch status to running if fetch isn't being told to block or
979 // squash this cycle.
980 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
981 tid);
982
983 fetchStatus[tid] = Running;
984
985 return true;
986 }
987
988 // If we've reached this point, we have not gotten any signals that
989 // cause fetch to change its status. Fetch remains the same as before.
990 return false;
991}
992
993template<class Impl>
994void
995DefaultFetch<Impl>::fetch(bool &status_change)
996{
997 //////////////////////////////////////////
998 // Start actual fetch
999 //////////////////////////////////////////
1000 int tid = getFetchingThread(fetchPolicy);
1001
1002 if (tid == -1 || drainPending) {
1003 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1004
1005 // Breaks looping condition in tick()
1006 threadFetched = numFetchingThreads;
1007 return;
1008 }
1009
1010 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1011
1012 // The current PC.
1013 Addr fetch_PC = PC[tid];
1014 Addr fetch_NPC = nextPC[tid];
1015 Addr fetch_MicroPC = microPC[tid];
1016
1017 // Fault code for memory access.
1018 Fault fault = NoFault;
1019
1020 // If returning from the delay of a cache miss, then update the status
1021 // to running, otherwise do the cache access. Possibly move this up
1022 // to tick() function.
1023 if (fetchStatus[tid] == IcacheAccessComplete) {
1024 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
1025 tid);
1026
1027 fetchStatus[tid] = Running;
1028 status_change = true;
1029 } else if (fetchStatus[tid] == Running) {
1030 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1031 "instruction, starting at PC %08p.\n",
1032 tid, fetch_PC);
1033
1034 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
1035 if (!fetch_success) {
1036 if (cacheBlocked) {
1037 ++icacheStallCycles;
1038 } else {
1039 ++fetchMiscStallCycles;
1040 }
1041 return;
1042 }
1043 } else {
1044 if (fetchStatus[tid] == Idle) {
1045 ++fetchIdleCycles;
1046 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1047 } else if (fetchStatus[tid] == Blocked) {
1048 ++fetchBlockedCycles;
1049 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1050 } else if (fetchStatus[tid] == Squashing) {
1051 ++fetchSquashCycles;
1052 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1053 } else if (fetchStatus[tid] == IcacheWaitResponse) {
1054 ++icacheStallCycles;
1055 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", tid);
1056 }
1057
1058 // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
1059 // fetch should do nothing.
1060 return;
1061 }
1062
1063 ++fetchCycles;
1064
1065 // If we had a stall due to an icache miss, then return.
1066 if (fetchStatus[tid] == IcacheWaitResponse) {
1067 ++icacheStallCycles;
1068 status_change = true;
1069 return;
1070 }
1071
1072 Addr next_PC = fetch_PC;
1073 Addr next_NPC = fetch_NPC;
1074 Addr next_MicroPC = fetch_MicroPC;
1075
1076 InstSeqNum inst_seq;
1077 MachInst inst;
1078 ExtMachInst ext_inst;
1079 // @todo: Fix this hack.
1080 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
1081
1082 StaticInstPtr staticInst = NULL;
1083 StaticInstPtr macroop = NULL;
1084
1085 if (fault == NoFault) {
1086 // If the read of the first instruction was successful, then grab the
1087 // instructions from the rest of the cache line and put them into the
1088 // queue heading to decode.
1089
1090 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1091 "decode.\n",tid);
1092
1093 // Need to keep track of whether or not a predicted branch
1094 // ended this fetch block.
1095 bool predicted_branch = false;
1096
1097 while (offset < cacheBlkSize &&
1098 numInst < fetchWidth &&
1099 !predicted_branch) {
1100
1101 // If we're branching after this instruction, quite fetching
1102 // from the same block then.
1103 predicted_branch =
1104 (fetch_PC + sizeof(TheISA::MachInst) != fetch_NPC);
1105 if (predicted_branch) {
1106 DPRINTF(Fetch, "Branch detected with PC = %#x, NPC = %#x\n",
1107 fetch_PC, fetch_NPC);
1108 }
1109
1110 // Make sure this is a valid index.
1111 assert(offset <= cacheBlkSize - instSize);
1112
1113 if (!macroop) {
1114 // Get the instruction from the array of the cache line.
1115 inst = TheISA::gtoh(*reinterpret_cast<TheISA::MachInst *>
1116 (&cacheData[tid][offset]));
1117
1118 predecoder.setTC(cpu->thread[tid]->getTC());
1119 predecoder.moreBytes(fetch_PC, fetch_PC, inst);
1120
1121 ext_inst = predecoder.getExtMachInst();
1122 staticInst = StaticInstPtr(ext_inst, fetch_PC);
1123 if (staticInst->isMacroop())
1124 macroop = staticInst;
1125 }
1126 do {
1127 if (macroop) {
1128 staticInst = macroop->fetchMicroop(fetch_MicroPC);
1129 if (staticInst->isLastMicroop())
1130 macroop = NULL;
1131 }
1132
1133 // Get a sequence number.
1134 inst_seq = cpu->getAndIncrementInstSeq();
1135
1136 // Create a new DynInst from the instruction fetched.
1137 DynInstPtr instruction = new DynInst(staticInst,
1138 fetch_PC, fetch_NPC, fetch_MicroPC,
1139 next_PC, next_NPC, next_MicroPC,
1140 inst_seq, cpu);
1141 instruction->setTid(tid);
1142
1143 instruction->setASID(tid);
1144
1145 instruction->setThreadState(cpu->thread[tid]);
1146
1147 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1148 "[sn:%lli]\n",
1149 tid, instruction->readPC(), inst_seq);
1150
1151 //DPRINTF(Fetch, "[tid:%i]: MachInst is %#x\n", tid, ext_inst);
1152
1153 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1154 tid, instruction->staticInst->disassemble(fetch_PC));
1155
1156#if TRACING_ON
1157 instruction->traceData =
1158 cpu->getTracer()->getInstRecord(curTick, cpu->tcBase(tid),
1159 instruction->staticInst, instruction->readPC());
1160#else
1161 instruction->traceData = NULL;
1162#endif
1163
1164 ///FIXME This needs to be more robust in dealing with delay slots
1165 predicted_branch |=
1166 lookupAndUpdateNextPC(instruction, next_PC, next_NPC, next_MicroPC);
1167
1168 // Add instruction to the CPU's list of instructions.
1169 instruction->setInstListIt(cpu->addInst(instruction));
1170
1171 // Write the instruction to the first slot in the queue
1172 // that heads to decode.
1173 toDecode->insts[numInst] = instruction;
1174
1175 toDecode->size++;
1176
1177 // Increment stat of fetched instructions.
1178 ++fetchedInsts;
1179
1180 // Move to the next instruction, unless we have a branch.
1181 fetch_PC = next_PC;
1182 fetch_NPC = next_NPC;
1183 fetch_MicroPC = next_MicroPC;
1184
1185 if (instruction->isQuiesce()) {
1186 DPRINTF(Fetch, "Quiesce instruction encountered, halting fetch!",
1187 curTick);
1188 fetchStatus[tid] = QuiescePending;
1189 ++numInst;
1190 status_change = true;
1191 break;
1192 }
1193
1194 ++numInst;
1195 } while (staticInst->isMicroop() &&
1196 !staticInst->isLastMicroop() &&
1197 numInst < fetchWidth);
1198 offset += instSize;
1199 }
1200
1201 if (predicted_branch) {
1202 DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1203 "instruction encountered.\n", tid);
1204 } else if (numInst >= fetchWidth) {
1205 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1206 "for this cycle.\n", tid);
1207 } else if (offset >= cacheBlkSize) {
1208 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1209 "block.\n", tid);
1210 }
1211 }
1212
1213 if (numInst > 0) {
1214 wroteToTimeBuffer = true;
1215 }
1216
1217 // Now that fetching is completed, update the PC to signify what the next
1218 // cycle will be.
1219 if (fault == NoFault) {
1220 PC[tid] = next_PC;
1221 nextPC[tid] = next_NPC;
1222 microPC[tid] = next_MicroPC;
1223 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, next_PC);
1224 } else {
1225 // We shouldn't be in an icache miss and also have a fault (an ITB
1226 // miss)
1227 if (fetchStatus[tid] == IcacheWaitResponse) {
1228 panic("Fetch should have exited prior to this!");
1229 }
1230
1231 // Send the fault to commit. This thread will not do anything
1232 // until commit handles the fault. The only other way it can
1233 // wake up is if a squash comes along and changes the PC.
1234 assert(numInst < fetchWidth);
1235 // Get a sequence number.
1236 inst_seq = cpu->getAndIncrementInstSeq();
1237 // We will use a nop in order to carry the fault.
1238 ext_inst = TheISA::NoopMachInst;
1239
1240 // Create a new DynInst from the dummy nop.
1241 DynInstPtr instruction = new DynInst(ext_inst,
1242 fetch_PC, fetch_NPC, fetch_MicroPC,
1243 next_PC, next_NPC, next_MicroPC,
1244 inst_seq, cpu);
1245 instruction->setPredTarg(next_NPC, next_NPC + instSize, 0);
1246 instruction->setTid(tid);
1247
1248 instruction->setASID(tid);
1249
1250 instruction->setThreadState(cpu->thread[tid]);
1251
1252 instruction->traceData = NULL;
1253
1254 instruction->setInstListIt(cpu->addInst(instruction));
1255
1256 instruction->fault = fault;
1257
1258 toDecode->insts[numInst] = instruction;
1259 toDecode->size++;
1260
1261 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1262
1263 fetchStatus[tid] = TrapPending;
1264 status_change = true;
1265
1266 DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %08p",
1267 tid, fault->name(), PC[tid]);
1268 }
1269}
1270
1271template<class Impl>
1272void
1273DefaultFetch<Impl>::recvRetry()
1274{
1275 if (retryPkt != NULL) {
1276 assert(cacheBlocked);
1277 assert(retryTid != -1);
1278 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1279
1280 if (icachePort->sendTiming(retryPkt)) {
1281 fetchStatus[retryTid] = IcacheWaitResponse;
1282 retryPkt = NULL;
1283 retryTid = -1;
1284 cacheBlocked = false;
1285 }
1286 } else {
1287 assert(retryTid == -1);
1288 // Access has been squashed since it was sent out. Just clear
1289 // the cache being blocked.
1290 cacheBlocked = false;
1291 }
1292}
1293
1294///////////////////////////////////////
1295// //
1296// SMT FETCH POLICY MAINTAINED HERE //
1297// //
1298///////////////////////////////////////
1299template<class Impl>
1300int
1301DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1302{
1303 if (numThreads > 1) {
1304 switch (fetch_priority) {
1305
1306 case SingleThread:
1307 return 0;
1308
1309 case RoundRobin:
1310 return roundRobin();
1311
1312 case IQ:
1313 return iqCount();
1314
1315 case LSQ:
1316 return lsqCount();
1317
1318 case Branch:
1319 return branchCount();
1320
1321 default:
1322 return -1;
1323 }
1324 } else {
1325 std::list<unsigned>::iterator thread = activeThreads->begin();
1326 assert(thread != activeThreads->end());
1327 int tid = *thread;
1328
1329 if (fetchStatus[tid] == Running ||
1330 fetchStatus[tid] == IcacheAccessComplete ||
1331 fetchStatus[tid] == Idle) {
1332 return tid;
1333 } else {
1334 return -1;
1335 }
1336 }
1337
1338}
1339
1340
1341template<class Impl>
1342int
1343DefaultFetch<Impl>::roundRobin()
1344{
1345 std::list<unsigned>::iterator pri_iter = priorityList.begin();
1346 std::list<unsigned>::iterator end = priorityList.end();
1347
1348 int high_pri;
1349
1350 while (pri_iter != end) {
1351 high_pri = *pri_iter;
1352
1353 assert(high_pri <= numThreads);
1354
1355 if (fetchStatus[high_pri] == Running ||
1356 fetchStatus[high_pri] == IcacheAccessComplete ||
1357 fetchStatus[high_pri] == Idle) {
1358
1359 priorityList.erase(pri_iter);
1360 priorityList.push_back(high_pri);
1361
1362 return high_pri;
1363 }
1364
1365 pri_iter++;
1366 }
1367
1368 return -1;
1369}
1370
1371template<class Impl>
1372int
1373DefaultFetch<Impl>::iqCount()
1374{
1375 std::priority_queue<unsigned> PQ;
1376
1377 std::list<unsigned>::iterator threads = activeThreads->begin();
1378 std::list<unsigned>::iterator end = activeThreads->end();
1379
1380 while (threads != end) {
1381 unsigned tid = *threads++;
1382
1383 PQ.push(fromIEW->iewInfo[tid].iqCount);
1384 }
1385
1386 while (!PQ.empty()) {
1387
1388 unsigned high_pri = PQ.top();
1389
1390 if (fetchStatus[high_pri] == Running ||
1391 fetchStatus[high_pri] == IcacheAccessComplete ||
1392 fetchStatus[high_pri] == Idle)
1393 return high_pri;
1394 else
1395 PQ.pop();
1396
1397 }
1398
1399 return -1;
1400}
1401
1402template<class Impl>
1403int
1404DefaultFetch<Impl>::lsqCount()
1405{
1406 std::priority_queue<unsigned> PQ;
1407
1408 std::list<unsigned>::iterator threads = activeThreads->begin();
1409 std::list<unsigned>::iterator end = activeThreads->end();
1410
1411 while (threads != end) {
1412 unsigned tid = *threads++;
1413
1414 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1415 }
1416
1417 while (!PQ.empty()) {
1418
1419 unsigned high_pri = PQ.top();
1420
1421 if (fetchStatus[high_pri] == Running ||
1422 fetchStatus[high_pri] == IcacheAccessComplete ||
1423 fetchStatus[high_pri] == Idle)
1424 return high_pri;
1425 else
1426 PQ.pop();
1427
1428 }
1429
1430 return -1;
1431}
1432
1433template<class Impl>
1434int
1435DefaultFetch<Impl>::branchCount()
1436{
1437 std::list<unsigned>::iterator thread = activeThreads->begin();
1438 assert(thread != activeThreads->end());
1439 unsigned tid = *thread;
1440
1441 panic("Branch Count Fetch policy unimplemented\n");
1442 return 0 * tid;
1443}
603
604 // In the case of faults, the fetch stage may need to stall and wait
605 // for the ITB miss to be handled.
606
607 // If translation was successful, attempt to read the first
608 // instruction.
609 if (fault == NoFault) {
610#if 0
611 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
612 memReq[tid]->isUncacheable()) {
613 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
614 "misspeculating path)!",
615 memReq[tid]->paddr);
616 ret_fault = TheISA::genMachineCheckFault();
617 return false;
618 }
619#endif
620
621 // Build packet here.
622 PacketPtr data_pkt = new Packet(mem_req,
623 MemCmd::ReadReq, Packet::Broadcast);
624 data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
625
626 cacheDataPC[tid] = block_PC;
627 cacheDataValid[tid] = false;
628
629 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
630
631 fetchedCacheLines++;
632
633 // Now do the timing access to see whether or not the instruction
634 // exists within the cache.
635 if (!icachePort->sendTiming(data_pkt)) {
636 assert(retryPkt == NULL);
637 assert(retryTid == -1);
638 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
639 fetchStatus[tid] = IcacheWaitRetry;
640 retryPkt = data_pkt;
641 retryTid = tid;
642 cacheBlocked = true;
643 return false;
644 }
645
646 DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
647
648 lastIcacheStall[tid] = curTick;
649
650 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
651 "response.\n", tid);
652
653 fetchStatus[tid] = IcacheWaitResponse;
654 } else {
655 delete mem_req;
656 memReq[tid] = NULL;
657 }
658
659 ret_fault = fault;
660 return true;
661}
662
663template <class Impl>
664inline void
665DefaultFetch<Impl>::doSquash(const Addr &new_PC,
666 const Addr &new_NPC, const Addr &new_microPC, unsigned tid)
667{
668 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x, NPC to: %#x.\n",
669 tid, new_PC, new_NPC);
670
671 PC[tid] = new_PC;
672 nextPC[tid] = new_NPC;
673 microPC[tid] = new_microPC;
674
675 // Clear the icache miss if it's outstanding.
676 if (fetchStatus[tid] == IcacheWaitResponse) {
677 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
678 tid);
679 memReq[tid] = NULL;
680 }
681
682 // Get rid of the retrying packet if it was from this thread.
683 if (retryTid == tid) {
684 assert(cacheBlocked);
685 if (retryPkt) {
686 delete retryPkt->req;
687 delete retryPkt;
688 }
689 retryPkt = NULL;
690 retryTid = -1;
691 }
692
693 fetchStatus[tid] = Squashing;
694
695 ++fetchSquashCycles;
696}
697
698template<class Impl>
699void
700DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC, const Addr &new_NPC,
701 const Addr &new_MicroPC,
702 const InstSeqNum &seq_num, unsigned tid)
703{
704 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
705
706 doSquash(new_PC, new_NPC, new_MicroPC, tid);
707
708 // Tell the CPU to remove any instructions that are in flight between
709 // fetch and decode.
710 cpu->removeInstsUntil(seq_num, tid);
711}
712
713template<class Impl>
714bool
715DefaultFetch<Impl>::checkStall(unsigned tid) const
716{
717 bool ret_val = false;
718
719 if (cpu->contextSwitch) {
720 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
721 ret_val = true;
722 } else if (stalls[tid].decode) {
723 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
724 ret_val = true;
725 } else if (stalls[tid].rename) {
726 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
727 ret_val = true;
728 } else if (stalls[tid].iew) {
729 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
730 ret_val = true;
731 } else if (stalls[tid].commit) {
732 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
733 ret_val = true;
734 }
735
736 return ret_val;
737}
738
739template<class Impl>
740typename DefaultFetch<Impl>::FetchStatus
741DefaultFetch<Impl>::updateFetchStatus()
742{
743 //Check Running
744 std::list<unsigned>::iterator threads = activeThreads->begin();
745 std::list<unsigned>::iterator end = activeThreads->end();
746
747 while (threads != end) {
748 unsigned tid = *threads++;
749
750 if (fetchStatus[tid] == Running ||
751 fetchStatus[tid] == Squashing ||
752 fetchStatus[tid] == IcacheAccessComplete) {
753
754 if (_status == Inactive) {
755 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
756
757 if (fetchStatus[tid] == IcacheAccessComplete) {
758 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
759 "completion\n",tid);
760 }
761
762 cpu->activateStage(O3CPU::FetchIdx);
763 }
764
765 return Active;
766 }
767 }
768
769 // Stage is switching from active to inactive, notify CPU of it.
770 if (_status == Active) {
771 DPRINTF(Activity, "Deactivating stage.\n");
772
773 cpu->deactivateStage(O3CPU::FetchIdx);
774 }
775
776 return Inactive;
777}
778
779template <class Impl>
780void
781DefaultFetch<Impl>::squash(const Addr &new_PC, const Addr &new_NPC,
782 const Addr &new_MicroPC,
783 const InstSeqNum &seq_num, unsigned tid)
784{
785 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
786
787 doSquash(new_PC, new_NPC, new_MicroPC, tid);
788
789 // Tell the CPU to remove any instructions that are not in the ROB.
790 cpu->removeInstsNotInROB(tid);
791}
792
793template <class Impl>
794void
795DefaultFetch<Impl>::tick()
796{
797 std::list<unsigned>::iterator threads = activeThreads->begin();
798 std::list<unsigned>::iterator end = activeThreads->end();
799 bool status_change = false;
800
801 wroteToTimeBuffer = false;
802
803 while (threads != end) {
804 unsigned tid = *threads++;
805
806 // Check the signals for each thread to determine the proper status
807 // for each thread.
808 bool updated_status = checkSignalsAndUpdate(tid);
809 status_change = status_change || updated_status;
810 }
811
812 DPRINTF(Fetch, "Running stage.\n");
813
814 // Reset the number of the instruction we're fetching.
815 numInst = 0;
816
817#if FULL_SYSTEM
818 if (fromCommit->commitInfo[0].interruptPending) {
819 interruptPending = true;
820 }
821
822 if (fromCommit->commitInfo[0].clearInterrupt) {
823 interruptPending = false;
824 }
825#endif
826
827 for (threadFetched = 0; threadFetched < numFetchingThreads;
828 threadFetched++) {
829 // Fetch each of the actively fetching threads.
830 fetch(status_change);
831 }
832
833 // Record number of instructions fetched this cycle for distribution.
834 fetchNisnDist.sample(numInst);
835
836 if (status_change) {
837 // Change the fetch stage status if there was a status change.
838 _status = updateFetchStatus();
839 }
840
841 // If there was activity this cycle, inform the CPU of it.
842 if (wroteToTimeBuffer || cpu->contextSwitch) {
843 DPRINTF(Activity, "Activity this cycle.\n");
844
845 cpu->activityThisCycle();
846 }
847}
848
849template <class Impl>
850bool
851DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
852{
853 // Update the per thread stall statuses.
854 if (fromDecode->decodeBlock[tid]) {
855 stalls[tid].decode = true;
856 }
857
858 if (fromDecode->decodeUnblock[tid]) {
859 assert(stalls[tid].decode);
860 assert(!fromDecode->decodeBlock[tid]);
861 stalls[tid].decode = false;
862 }
863
864 if (fromRename->renameBlock[tid]) {
865 stalls[tid].rename = true;
866 }
867
868 if (fromRename->renameUnblock[tid]) {
869 assert(stalls[tid].rename);
870 assert(!fromRename->renameBlock[tid]);
871 stalls[tid].rename = false;
872 }
873
874 if (fromIEW->iewBlock[tid]) {
875 stalls[tid].iew = true;
876 }
877
878 if (fromIEW->iewUnblock[tid]) {
879 assert(stalls[tid].iew);
880 assert(!fromIEW->iewBlock[tid]);
881 stalls[tid].iew = false;
882 }
883
884 if (fromCommit->commitBlock[tid]) {
885 stalls[tid].commit = true;
886 }
887
888 if (fromCommit->commitUnblock[tid]) {
889 assert(stalls[tid].commit);
890 assert(!fromCommit->commitBlock[tid]);
891 stalls[tid].commit = false;
892 }
893
894 // Check squash signals from commit.
895 if (fromCommit->commitInfo[tid].squash) {
896
897 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
898 "from commit.\n",tid);
899 // In any case, squash.
900 squash(fromCommit->commitInfo[tid].nextPC,
901 fromCommit->commitInfo[tid].nextNPC,
902 fromCommit->commitInfo[tid].nextMicroPC,
903 fromCommit->commitInfo[tid].doneSeqNum,
904 tid);
905
906 // Also check if there's a mispredict that happened.
907 if (fromCommit->commitInfo[tid].branchMispredict) {
908 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
909 fromCommit->commitInfo[tid].nextPC,
910 fromCommit->commitInfo[tid].branchTaken,
911 tid);
912 } else {
913 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
914 tid);
915 }
916
917 return true;
918 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
919 // Update the branch predictor if it wasn't a squashed instruction
920 // that was broadcasted.
921 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
922 }
923
924 // Check ROB squash signals from commit.
925 if (fromCommit->commitInfo[tid].robSquashing) {
926 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
927
928 // Continue to squash.
929 fetchStatus[tid] = Squashing;
930
931 return true;
932 }
933
934 // Check squash signals from decode.
935 if (fromDecode->decodeInfo[tid].squash) {
936 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
937 "from decode.\n",tid);
938
939 // Update the branch predictor.
940 if (fromDecode->decodeInfo[tid].branchMispredict) {
941 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
942 fromDecode->decodeInfo[tid].nextPC,
943 fromDecode->decodeInfo[tid].branchTaken,
944 tid);
945 } else {
946 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
947 tid);
948 }
949
950 if (fetchStatus[tid] != Squashing) {
951
952 DPRINTF(Fetch, "Squashing from decode with PC = %#x, NPC = %#x\n",
953 fromDecode->decodeInfo[tid].nextPC,
954 fromDecode->decodeInfo[tid].nextNPC);
955 // Squash unless we're already squashing
956 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
957 fromDecode->decodeInfo[tid].nextNPC,
958 fromDecode->decodeInfo[tid].nextMicroPC,
959 fromDecode->decodeInfo[tid].doneSeqNum,
960 tid);
961
962 return true;
963 }
964 }
965
966 if (checkStall(tid) &&
967 fetchStatus[tid] != IcacheWaitResponse &&
968 fetchStatus[tid] != IcacheWaitRetry) {
969 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
970
971 fetchStatus[tid] = Blocked;
972
973 return true;
974 }
975
976 if (fetchStatus[tid] == Blocked ||
977 fetchStatus[tid] == Squashing) {
978 // Switch status to running if fetch isn't being told to block or
979 // squash this cycle.
980 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
981 tid);
982
983 fetchStatus[tid] = Running;
984
985 return true;
986 }
987
988 // If we've reached this point, we have not gotten any signals that
989 // cause fetch to change its status. Fetch remains the same as before.
990 return false;
991}
992
993template<class Impl>
994void
995DefaultFetch<Impl>::fetch(bool &status_change)
996{
997 //////////////////////////////////////////
998 // Start actual fetch
999 //////////////////////////////////////////
1000 int tid = getFetchingThread(fetchPolicy);
1001
1002 if (tid == -1 || drainPending) {
1003 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1004
1005 // Breaks looping condition in tick()
1006 threadFetched = numFetchingThreads;
1007 return;
1008 }
1009
1010 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1011
1012 // The current PC.
1013 Addr fetch_PC = PC[tid];
1014 Addr fetch_NPC = nextPC[tid];
1015 Addr fetch_MicroPC = microPC[tid];
1016
1017 // Fault code for memory access.
1018 Fault fault = NoFault;
1019
1020 // If returning from the delay of a cache miss, then update the status
1021 // to running, otherwise do the cache access. Possibly move this up
1022 // to tick() function.
1023 if (fetchStatus[tid] == IcacheAccessComplete) {
1024 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
1025 tid);
1026
1027 fetchStatus[tid] = Running;
1028 status_change = true;
1029 } else if (fetchStatus[tid] == Running) {
1030 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1031 "instruction, starting at PC %08p.\n",
1032 tid, fetch_PC);
1033
1034 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
1035 if (!fetch_success) {
1036 if (cacheBlocked) {
1037 ++icacheStallCycles;
1038 } else {
1039 ++fetchMiscStallCycles;
1040 }
1041 return;
1042 }
1043 } else {
1044 if (fetchStatus[tid] == Idle) {
1045 ++fetchIdleCycles;
1046 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1047 } else if (fetchStatus[tid] == Blocked) {
1048 ++fetchBlockedCycles;
1049 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1050 } else if (fetchStatus[tid] == Squashing) {
1051 ++fetchSquashCycles;
1052 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1053 } else if (fetchStatus[tid] == IcacheWaitResponse) {
1054 ++icacheStallCycles;
1055 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", tid);
1056 }
1057
1058 // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
1059 // fetch should do nothing.
1060 return;
1061 }
1062
1063 ++fetchCycles;
1064
1065 // If we had a stall due to an icache miss, then return.
1066 if (fetchStatus[tid] == IcacheWaitResponse) {
1067 ++icacheStallCycles;
1068 status_change = true;
1069 return;
1070 }
1071
1072 Addr next_PC = fetch_PC;
1073 Addr next_NPC = fetch_NPC;
1074 Addr next_MicroPC = fetch_MicroPC;
1075
1076 InstSeqNum inst_seq;
1077 MachInst inst;
1078 ExtMachInst ext_inst;
1079 // @todo: Fix this hack.
1080 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
1081
1082 StaticInstPtr staticInst = NULL;
1083 StaticInstPtr macroop = NULL;
1084
1085 if (fault == NoFault) {
1086 // If the read of the first instruction was successful, then grab the
1087 // instructions from the rest of the cache line and put them into the
1088 // queue heading to decode.
1089
1090 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1091 "decode.\n",tid);
1092
1093 // Need to keep track of whether or not a predicted branch
1094 // ended this fetch block.
1095 bool predicted_branch = false;
1096
1097 while (offset < cacheBlkSize &&
1098 numInst < fetchWidth &&
1099 !predicted_branch) {
1100
1101 // If we're branching after this instruction, quite fetching
1102 // from the same block then.
1103 predicted_branch =
1104 (fetch_PC + sizeof(TheISA::MachInst) != fetch_NPC);
1105 if (predicted_branch) {
1106 DPRINTF(Fetch, "Branch detected with PC = %#x, NPC = %#x\n",
1107 fetch_PC, fetch_NPC);
1108 }
1109
1110 // Make sure this is a valid index.
1111 assert(offset <= cacheBlkSize - instSize);
1112
1113 if (!macroop) {
1114 // Get the instruction from the array of the cache line.
1115 inst = TheISA::gtoh(*reinterpret_cast<TheISA::MachInst *>
1116 (&cacheData[tid][offset]));
1117
1118 predecoder.setTC(cpu->thread[tid]->getTC());
1119 predecoder.moreBytes(fetch_PC, fetch_PC, inst);
1120
1121 ext_inst = predecoder.getExtMachInst();
1122 staticInst = StaticInstPtr(ext_inst, fetch_PC);
1123 if (staticInst->isMacroop())
1124 macroop = staticInst;
1125 }
1126 do {
1127 if (macroop) {
1128 staticInst = macroop->fetchMicroop(fetch_MicroPC);
1129 if (staticInst->isLastMicroop())
1130 macroop = NULL;
1131 }
1132
1133 // Get a sequence number.
1134 inst_seq = cpu->getAndIncrementInstSeq();
1135
1136 // Create a new DynInst from the instruction fetched.
1137 DynInstPtr instruction = new DynInst(staticInst,
1138 fetch_PC, fetch_NPC, fetch_MicroPC,
1139 next_PC, next_NPC, next_MicroPC,
1140 inst_seq, cpu);
1141 instruction->setTid(tid);
1142
1143 instruction->setASID(tid);
1144
1145 instruction->setThreadState(cpu->thread[tid]);
1146
1147 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1148 "[sn:%lli]\n",
1149 tid, instruction->readPC(), inst_seq);
1150
1151 //DPRINTF(Fetch, "[tid:%i]: MachInst is %#x\n", tid, ext_inst);
1152
1153 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1154 tid, instruction->staticInst->disassemble(fetch_PC));
1155
1156#if TRACING_ON
1157 instruction->traceData =
1158 cpu->getTracer()->getInstRecord(curTick, cpu->tcBase(tid),
1159 instruction->staticInst, instruction->readPC());
1160#else
1161 instruction->traceData = NULL;
1162#endif
1163
1164 ///FIXME This needs to be more robust in dealing with delay slots
1165 predicted_branch |=
1166 lookupAndUpdateNextPC(instruction, next_PC, next_NPC, next_MicroPC);
1167
1168 // Add instruction to the CPU's list of instructions.
1169 instruction->setInstListIt(cpu->addInst(instruction));
1170
1171 // Write the instruction to the first slot in the queue
1172 // that heads to decode.
1173 toDecode->insts[numInst] = instruction;
1174
1175 toDecode->size++;
1176
1177 // Increment stat of fetched instructions.
1178 ++fetchedInsts;
1179
1180 // Move to the next instruction, unless we have a branch.
1181 fetch_PC = next_PC;
1182 fetch_NPC = next_NPC;
1183 fetch_MicroPC = next_MicroPC;
1184
1185 if (instruction->isQuiesce()) {
1186 DPRINTF(Fetch, "Quiesce instruction encountered, halting fetch!",
1187 curTick);
1188 fetchStatus[tid] = QuiescePending;
1189 ++numInst;
1190 status_change = true;
1191 break;
1192 }
1193
1194 ++numInst;
1195 } while (staticInst->isMicroop() &&
1196 !staticInst->isLastMicroop() &&
1197 numInst < fetchWidth);
1198 offset += instSize;
1199 }
1200
1201 if (predicted_branch) {
1202 DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1203 "instruction encountered.\n", tid);
1204 } else if (numInst >= fetchWidth) {
1205 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1206 "for this cycle.\n", tid);
1207 } else if (offset >= cacheBlkSize) {
1208 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1209 "block.\n", tid);
1210 }
1211 }
1212
1213 if (numInst > 0) {
1214 wroteToTimeBuffer = true;
1215 }
1216
1217 // Now that fetching is completed, update the PC to signify what the next
1218 // cycle will be.
1219 if (fault == NoFault) {
1220 PC[tid] = next_PC;
1221 nextPC[tid] = next_NPC;
1222 microPC[tid] = next_MicroPC;
1223 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, next_PC);
1224 } else {
1225 // We shouldn't be in an icache miss and also have a fault (an ITB
1226 // miss)
1227 if (fetchStatus[tid] == IcacheWaitResponse) {
1228 panic("Fetch should have exited prior to this!");
1229 }
1230
1231 // Send the fault to commit. This thread will not do anything
1232 // until commit handles the fault. The only other way it can
1233 // wake up is if a squash comes along and changes the PC.
1234 assert(numInst < fetchWidth);
1235 // Get a sequence number.
1236 inst_seq = cpu->getAndIncrementInstSeq();
1237 // We will use a nop in order to carry the fault.
1238 ext_inst = TheISA::NoopMachInst;
1239
1240 // Create a new DynInst from the dummy nop.
1241 DynInstPtr instruction = new DynInst(ext_inst,
1242 fetch_PC, fetch_NPC, fetch_MicroPC,
1243 next_PC, next_NPC, next_MicroPC,
1244 inst_seq, cpu);
1245 instruction->setPredTarg(next_NPC, next_NPC + instSize, 0);
1246 instruction->setTid(tid);
1247
1248 instruction->setASID(tid);
1249
1250 instruction->setThreadState(cpu->thread[tid]);
1251
1252 instruction->traceData = NULL;
1253
1254 instruction->setInstListIt(cpu->addInst(instruction));
1255
1256 instruction->fault = fault;
1257
1258 toDecode->insts[numInst] = instruction;
1259 toDecode->size++;
1260
1261 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1262
1263 fetchStatus[tid] = TrapPending;
1264 status_change = true;
1265
1266 DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %08p",
1267 tid, fault->name(), PC[tid]);
1268 }
1269}
1270
1271template<class Impl>
1272void
1273DefaultFetch<Impl>::recvRetry()
1274{
1275 if (retryPkt != NULL) {
1276 assert(cacheBlocked);
1277 assert(retryTid != -1);
1278 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1279
1280 if (icachePort->sendTiming(retryPkt)) {
1281 fetchStatus[retryTid] = IcacheWaitResponse;
1282 retryPkt = NULL;
1283 retryTid = -1;
1284 cacheBlocked = false;
1285 }
1286 } else {
1287 assert(retryTid == -1);
1288 // Access has been squashed since it was sent out. Just clear
1289 // the cache being blocked.
1290 cacheBlocked = false;
1291 }
1292}
1293
1294///////////////////////////////////////
1295// //
1296// SMT FETCH POLICY MAINTAINED HERE //
1297// //
1298///////////////////////////////////////
1299template<class Impl>
1300int
1301DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1302{
1303 if (numThreads > 1) {
1304 switch (fetch_priority) {
1305
1306 case SingleThread:
1307 return 0;
1308
1309 case RoundRobin:
1310 return roundRobin();
1311
1312 case IQ:
1313 return iqCount();
1314
1315 case LSQ:
1316 return lsqCount();
1317
1318 case Branch:
1319 return branchCount();
1320
1321 default:
1322 return -1;
1323 }
1324 } else {
1325 std::list<unsigned>::iterator thread = activeThreads->begin();
1326 assert(thread != activeThreads->end());
1327 int tid = *thread;
1328
1329 if (fetchStatus[tid] == Running ||
1330 fetchStatus[tid] == IcacheAccessComplete ||
1331 fetchStatus[tid] == Idle) {
1332 return tid;
1333 } else {
1334 return -1;
1335 }
1336 }
1337
1338}
1339
1340
1341template<class Impl>
1342int
1343DefaultFetch<Impl>::roundRobin()
1344{
1345 std::list<unsigned>::iterator pri_iter = priorityList.begin();
1346 std::list<unsigned>::iterator end = priorityList.end();
1347
1348 int high_pri;
1349
1350 while (pri_iter != end) {
1351 high_pri = *pri_iter;
1352
1353 assert(high_pri <= numThreads);
1354
1355 if (fetchStatus[high_pri] == Running ||
1356 fetchStatus[high_pri] == IcacheAccessComplete ||
1357 fetchStatus[high_pri] == Idle) {
1358
1359 priorityList.erase(pri_iter);
1360 priorityList.push_back(high_pri);
1361
1362 return high_pri;
1363 }
1364
1365 pri_iter++;
1366 }
1367
1368 return -1;
1369}
1370
1371template<class Impl>
1372int
1373DefaultFetch<Impl>::iqCount()
1374{
1375 std::priority_queue<unsigned> PQ;
1376
1377 std::list<unsigned>::iterator threads = activeThreads->begin();
1378 std::list<unsigned>::iterator end = activeThreads->end();
1379
1380 while (threads != end) {
1381 unsigned tid = *threads++;
1382
1383 PQ.push(fromIEW->iewInfo[tid].iqCount);
1384 }
1385
1386 while (!PQ.empty()) {
1387
1388 unsigned high_pri = PQ.top();
1389
1390 if (fetchStatus[high_pri] == Running ||
1391 fetchStatus[high_pri] == IcacheAccessComplete ||
1392 fetchStatus[high_pri] == Idle)
1393 return high_pri;
1394 else
1395 PQ.pop();
1396
1397 }
1398
1399 return -1;
1400}
1401
1402template<class Impl>
1403int
1404DefaultFetch<Impl>::lsqCount()
1405{
1406 std::priority_queue<unsigned> PQ;
1407
1408 std::list<unsigned>::iterator threads = activeThreads->begin();
1409 std::list<unsigned>::iterator end = activeThreads->end();
1410
1411 while (threads != end) {
1412 unsigned tid = *threads++;
1413
1414 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1415 }
1416
1417 while (!PQ.empty()) {
1418
1419 unsigned high_pri = PQ.top();
1420
1421 if (fetchStatus[high_pri] == Running ||
1422 fetchStatus[high_pri] == IcacheAccessComplete ||
1423 fetchStatus[high_pri] == Idle)
1424 return high_pri;
1425 else
1426 PQ.pop();
1427
1428 }
1429
1430 return -1;
1431}
1432
1433template<class Impl>
1434int
1435DefaultFetch<Impl>::branchCount()
1436{
1437 std::list<unsigned>::iterator thread = activeThreads->begin();
1438 assert(thread != activeThreads->end());
1439 unsigned tid = *thread;
1440
1441 panic("Branch Count Fetch policy unimplemented\n");
1442 return 0 * tid;
1443}