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