fetch_impl.hh revision 9023:e9201a7bce59
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 "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 "params/DerivO3CPU.hh"
64#include "sim/byteswap.hh"
65#include "sim/core.hh"
66#include "sim/eventq.hh"
67#include "sim/full_system.hh"
68#include "sim/system.hh"
69
70using namespace std;
71
72template<class Impl>
73DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
74    : cpu(_cpu),
75      branchPred(params),
76      numInst(0),
77      decodeToFetchDelay(params->decodeToFetchDelay),
78      renameToFetchDelay(params->renameToFetchDelay),
79      iewToFetchDelay(params->iewToFetchDelay),
80      commitToFetchDelay(params->commitToFetchDelay),
81      fetchWidth(params->fetchWidth),
82      cacheBlocked(false),
83      retryPkt(NULL),
84      retryTid(InvalidThreadID),
85      numThreads(params->numThreads),
86      numFetchingThreads(params->smtNumFetchingThreads),
87      interruptPending(false),
88      drainPending(false),
89      switchedOut(false),
90      finishTranslationEvent(this)
91{
92    if (numThreads > Impl::MaxThreads)
93        fatal("numThreads (%d) is larger than compiled limit (%d),\n"
94              "\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
95              numThreads, static_cast<int>(Impl::MaxThreads));
96    if (fetchWidth > Impl::MaxWidth)
97        fatal("fetchWidth (%d) is larger than compiled limit (%d),\n"
98             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
99             fetchWidth, static_cast<int>(Impl::MaxWidth));
100
101    // Set fetch stage's status to inactive.
102    _status = Inactive;
103
104    std::string policy = params->smtFetchPolicy;
105
106    // Convert string to lowercase
107    std::transform(policy.begin(), policy.end(), policy.begin(),
108                   (int(*)(int)) tolower);
109
110    // Figure out fetch policy
111    if (policy == "singlethread") {
112        fetchPolicy = SingleThread;
113        if (numThreads > 1)
114            panic("Invalid Fetch Policy for a SMT workload.");
115    } else if (policy == "roundrobin") {
116        fetchPolicy = RoundRobin;
117        DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
118    } else if (policy == "branch") {
119        fetchPolicy = Branch;
120        DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
121    } else if (policy == "iqcount") {
122        fetchPolicy = IQ;
123        DPRINTF(Fetch, "Fetch policy set to IQ count\n");
124    } else if (policy == "lsqcount") {
125        fetchPolicy = LSQ;
126        DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
127    } else {
128        fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
129              " RoundRobin,LSQcount,IQcount}\n");
130    }
131
132    // Get the size of an instruction.
133    instSize = sizeof(TheISA::MachInst);
134
135    for (int i = 0; i < Impl::MaxThreads; i++)
136        decoder[i] = new TheISA::Decoder(NULL);
137}
138
139template <class Impl>
140std::string
141DefaultFetch<Impl>::name() const
142{
143    return cpu->name() + ".fetch";
144}
145
146template <class Impl>
147void
148DefaultFetch<Impl>::regStats()
149{
150    icacheStallCycles
151        .name(name() + ".icacheStallCycles")
152        .desc("Number of cycles fetch is stalled on an Icache miss")
153        .prereq(icacheStallCycles);
154
155    fetchedInsts
156        .name(name() + ".Insts")
157        .desc("Number of instructions fetch has processed")
158        .prereq(fetchedInsts);
159
160    fetchedBranches
161        .name(name() + ".Branches")
162        .desc("Number of branches that fetch encountered")
163        .prereq(fetchedBranches);
164
165    predictedBranches
166        .name(name() + ".predictedBranches")
167        .desc("Number of branches that fetch has predicted taken")
168        .prereq(predictedBranches);
169
170    fetchCycles
171        .name(name() + ".Cycles")
172        .desc("Number of cycles fetch has run and was not squashing or"
173              " blocked")
174        .prereq(fetchCycles);
175
176    fetchSquashCycles
177        .name(name() + ".SquashCycles")
178        .desc("Number of cycles fetch has spent squashing")
179        .prereq(fetchSquashCycles);
180
181    fetchTlbCycles
182        .name(name() + ".TlbCycles")
183        .desc("Number of cycles fetch has spent waiting for tlb")
184        .prereq(fetchTlbCycles);
185
186    fetchIdleCycles
187        .name(name() + ".IdleCycles")
188        .desc("Number of cycles fetch was idle")
189        .prereq(fetchIdleCycles);
190
191    fetchBlockedCycles
192        .name(name() + ".BlockedCycles")
193        .desc("Number of cycles fetch has spent blocked")
194        .prereq(fetchBlockedCycles);
195
196    fetchedCacheLines
197        .name(name() + ".CacheLines")
198        .desc("Number of cache lines fetched")
199        .prereq(fetchedCacheLines);
200
201    fetchMiscStallCycles
202        .name(name() + ".MiscStallCycles")
203        .desc("Number of cycles fetch has spent waiting on interrupts, or "
204              "bad addresses, or out of MSHRs")
205        .prereq(fetchMiscStallCycles);
206
207    fetchPendingDrainCycles
208        .name(name() + ".PendingDrainCycles")
209        .desc("Number of cycles fetch has spent waiting on pipes to drain")
210        .prereq(fetchPendingDrainCycles);
211
212    fetchNoActiveThreadStallCycles
213        .name(name() + ".NoActiveThreadStallCycles")
214        .desc("Number of stall cycles due to no active thread to fetch from")
215        .prereq(fetchNoActiveThreadStallCycles);
216
217    fetchPendingTrapStallCycles
218        .name(name() + ".PendingTrapStallCycles")
219        .desc("Number of stall cycles due to pending traps")
220        .prereq(fetchPendingTrapStallCycles);
221
222    fetchPendingQuiesceStallCycles
223        .name(name() + ".PendingQuiesceStallCycles")
224        .desc("Number of stall cycles due to pending quiesce instructions")
225        .prereq(fetchPendingQuiesceStallCycles);
226
227    fetchIcacheWaitRetryStallCycles
228        .name(name() + ".IcacheWaitRetryStallCycles")
229        .desc("Number of stall cycles due to full MSHR")
230        .prereq(fetchIcacheWaitRetryStallCycles);
231
232    fetchIcacheSquashes
233        .name(name() + ".IcacheSquashes")
234        .desc("Number of outstanding Icache misses that were squashed")
235        .prereq(fetchIcacheSquashes);
236
237    fetchTlbSquashes
238        .name(name() + ".ItlbSquashes")
239        .desc("Number of outstanding ITLB misses that were squashed")
240        .prereq(fetchTlbSquashes);
241
242    fetchNisnDist
243        .init(/* base value */ 0,
244              /* last value */ fetchWidth,
245              /* bucket size */ 1)
246        .name(name() + ".rateDist")
247        .desc("Number of instructions fetched each cycle (Total)")
248        .flags(Stats::pdf);
249
250    idleRate
251        .name(name() + ".idleRate")
252        .desc("Percent of cycles fetch was idle")
253        .prereq(idleRate);
254    idleRate = fetchIdleCycles * 100 / cpu->numCycles;
255
256    branchRate
257        .name(name() + ".branchRate")
258        .desc("Number of branch fetches per cycle")
259        .flags(Stats::total);
260    branchRate = fetchedBranches / cpu->numCycles;
261
262    fetchRate
263        .name(name() + ".rate")
264        .desc("Number of inst fetches per cycle")
265        .flags(Stats::total);
266    fetchRate = fetchedInsts / cpu->numCycles;
267
268    branchPred.regStats();
269}
270
271template<class Impl>
272void
273DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
274{
275    timeBuffer = time_buffer;
276
277    // Create wires to get information from proper places in time buffer.
278    fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
279    fromRename = timeBuffer->getWire(-renameToFetchDelay);
280    fromIEW = timeBuffer->getWire(-iewToFetchDelay);
281    fromCommit = timeBuffer->getWire(-commitToFetchDelay);
282}
283
284template<class Impl>
285void
286DefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
287{
288    activeThreads = at_ptr;
289}
290
291template<class Impl>
292void
293DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
294{
295    fetchQueue = fq_ptr;
296
297    // Create wire to write information to proper place in fetch queue.
298    toDecode = fetchQueue->getWire(0);
299}
300
301template<class Impl>
302void
303DefaultFetch<Impl>::initStage()
304{
305    // Setup PC and nextPC with initial state.
306    for (ThreadID tid = 0; tid < numThreads; tid++) {
307        pc[tid] = cpu->pcState(tid);
308        fetchOffset[tid] = 0;
309        macroop[tid] = NULL;
310        delayedCommit[tid] = false;
311    }
312
313    for (ThreadID tid = 0; tid < numThreads; tid++) {
314
315        fetchStatus[tid] = Running;
316
317        priorityList.push_back(tid);
318
319        memReq[tid] = NULL;
320
321        stalls[tid].decode = false;
322        stalls[tid].rename = false;
323        stalls[tid].iew = false;
324        stalls[tid].commit = false;
325    }
326
327    // Schedule fetch to get the correct PC from the CPU
328    // scheduleFetchStartupEvent(1);
329
330    // Fetch needs to start fetching instructions at the very beginning,
331    // so it must start up in active state.
332    switchToActive();
333}
334
335template<class Impl>
336void
337DefaultFetch<Impl>::setIcache()
338{
339    assert(cpu->getInstPort().isConnected());
340
341    // Size of cache block.
342    cacheBlkSize = cpu->getInstPort().peerBlockSize();
343
344    // Create mask to get rid of offset bits.
345    cacheBlkMask = (cacheBlkSize - 1);
346
347    for (ThreadID tid = 0; tid < numThreads; tid++) {
348        // Create space to store a cache line.
349        cacheData[tid] = new uint8_t[cacheBlkSize];
350        cacheDataPC[tid] = 0;
351        cacheDataValid[tid] = false;
352    }
353}
354
355template<class Impl>
356void
357DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
358{
359    ThreadID tid = pkt->req->threadId();
360
361    DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n", tid);
362
363    assert(!pkt->wasNacked());
364
365    // Only change the status if it's still waiting on the icache access
366    // to return.
367    if (fetchStatus[tid] != IcacheWaitResponse ||
368        pkt->req != memReq[tid] ||
369        isSwitchedOut()) {
370        ++fetchIcacheSquashes;
371        delete pkt->req;
372        delete pkt;
373        return;
374    }
375
376    memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
377    cacheDataValid[tid] = true;
378
379    if (!drainPending) {
380        // Wake up the CPU (if it went to sleep and was waiting on
381        // this completion event).
382        cpu->wakeCPU();
383
384        DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
385                tid);
386
387        switchToActive();
388    }
389
390    // Only switch to IcacheAccessComplete if we're not stalled as well.
391    if (checkStall(tid)) {
392        fetchStatus[tid] = Blocked;
393    } else {
394        fetchStatus[tid] = IcacheAccessComplete;
395    }
396
397    // Reset the mem req to NULL.
398    delete pkt->req;
399    delete pkt;
400    memReq[tid] = NULL;
401}
402
403template <class Impl>
404bool
405DefaultFetch<Impl>::drain()
406{
407    // Fetch is ready to drain at any time.
408    cpu->signalDrained();
409    drainPending = true;
410    return true;
411}
412
413template <class Impl>
414void
415DefaultFetch<Impl>::resume()
416{
417    drainPending = false;
418}
419
420template <class Impl>
421void
422DefaultFetch<Impl>::switchOut()
423{
424    switchedOut = true;
425    // Branch predictor needs to have its state cleared.
426    branchPred.switchOut();
427}
428
429template <class Impl>
430void
431DefaultFetch<Impl>::takeOverFrom()
432{
433    // the instruction port is now connected so we can get the block
434    // size
435    setIcache();
436
437    // Reset all state
438    for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
439        stalls[i].decode = 0;
440        stalls[i].rename = 0;
441        stalls[i].iew = 0;
442        stalls[i].commit = 0;
443        pc[i] = cpu->pcState(i);
444        fetchStatus[i] = Running;
445    }
446    numInst = 0;
447    wroteToTimeBuffer = false;
448    _status = Inactive;
449    switchedOut = false;
450    interruptPending = false;
451    branchPred.takeOverFrom();
452}
453
454template <class Impl>
455void
456DefaultFetch<Impl>::wakeFromQuiesce()
457{
458    DPRINTF(Fetch, "Waking up from quiesce\n");
459    // Hopefully this is safe
460    // @todo: Allow other threads to wake from quiesce.
461    fetchStatus[0] = Running;
462}
463
464template <class Impl>
465inline void
466DefaultFetch<Impl>::switchToActive()
467{
468    if (_status == Inactive) {
469        DPRINTF(Activity, "Activating stage.\n");
470
471        cpu->activateStage(O3CPU::FetchIdx);
472
473        _status = Active;
474    }
475}
476
477template <class Impl>
478inline void
479DefaultFetch<Impl>::switchToInactive()
480{
481    if (_status == Active) {
482        DPRINTF(Activity, "Deactivating stage.\n");
483
484        cpu->deactivateStage(O3CPU::FetchIdx);
485
486        _status = Inactive;
487    }
488}
489
490template <class Impl>
491bool
492DefaultFetch<Impl>::lookupAndUpdateNextPC(
493        DynInstPtr &inst, TheISA::PCState &nextPC)
494{
495    // Do branch prediction check here.
496    // A bit of a misnomer...next_PC is actually the current PC until
497    // this function updates it.
498    bool predict_taken;
499
500    if (!inst->isControl()) {
501        TheISA::advancePC(nextPC, inst->staticInst);
502        inst->setPredTarg(nextPC);
503        inst->setPredTaken(false);
504        return false;
505    }
506
507    ThreadID tid = inst->threadNumber;
508    predict_taken = branchPred.predict(inst, nextPC, tid);
509
510    if (predict_taken) {
511        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:  Branch predicted to be taken to %s.\n",
512                tid, inst->seqNum, nextPC);
513    } else {
514        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
515                tid, inst->seqNum);
516    }
517
518    DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n",
519            tid, inst->seqNum, nextPC);
520    inst->setPredTarg(nextPC);
521    inst->setPredTaken(predict_taken);
522
523    ++fetchedBranches;
524
525    if (predict_taken) {
526        ++predictedBranches;
527    }
528
529    return predict_taken;
530}
531
532template <class Impl>
533bool
534DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
535{
536    Fault fault = NoFault;
537
538    // @todo: not sure if these should block translation.
539    //AlphaDep
540    if (cacheBlocked) {
541        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
542                tid);
543        return false;
544    } else if (isSwitchedOut()) {
545        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
546                tid);
547        return false;
548    } else if (checkInterrupt(pc) && !delayedCommit[tid]) {
549        // Hold off fetch from getting new instructions when:
550        // Cache is blocked, or
551        // while an interrupt is pending and we're not in PAL mode, or
552        // fetch is switched out.
553        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
554                tid);
555        return false;
556    }
557
558    // Align the fetch address so it's at the start of a cache block.
559    Addr block_PC = icacheBlockAlignPC(vaddr);
560
561    DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n",
562            tid, block_PC, vaddr);
563
564    // Setup the memReq to do a read of the first instruction's address.
565    // Set the appropriate read size and flags as well.
566    // Build request here.
567    RequestPtr mem_req =
568        new Request(tid, block_PC, cacheBlkSize, Request::INST_FETCH,
569                    cpu->instMasterId(), pc, cpu->thread[tid]->contextId(), tid);
570
571    memReq[tid] = mem_req;
572
573    // Initiate translation of the icache block
574    fetchStatus[tid] = ItlbWait;
575    FetchTranslation *trans = new FetchTranslation(this);
576    cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(),
577                              trans, BaseTLB::Execute);
578    return true;
579}
580
581template <class Impl>
582void
583DefaultFetch<Impl>::finishTranslation(Fault fault, RequestPtr mem_req)
584{
585    ThreadID tid = mem_req->threadId();
586    Addr block_PC = mem_req->getVaddr();
587
588    // Wake up CPU if it was idle
589    cpu->wakeCPU();
590
591    if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] ||
592        mem_req->getVaddr() != memReq[tid]->getVaddr() || isSwitchedOut()) {
593        DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n",
594                tid);
595        ++fetchTlbSquashes;
596        delete mem_req;
597        return;
598    }
599
600
601    // If translation was successful, attempt to read the icache block.
602    if (fault == NoFault) {
603        // Check that we're not going off into random memory
604        // If we have, just wait around for commit to squash something and put
605        // us on the right track
606        if (!cpu->system->isMemAddr(mem_req->getPaddr())) {
607            warn("Address %#x is outside of physical memory, stopping fetch\n",
608                    mem_req->getPaddr());
609            fetchStatus[tid] = NoGoodAddr;
610            delete mem_req;
611            memReq[tid] = NULL;
612            return;
613        }
614
615        // Build packet here.
616        PacketPtr data_pkt = new Packet(mem_req, MemCmd::ReadReq);
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().sendTimingReq(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[tid]->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    decoder[tid]->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 decoder.
1199        bool needMem = !inRom && !curMacroop &&
1200            !decoder[tid]->instReady();
1201        fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1202        Addr block_PC = icacheBlockAlignPC(fetchAddr);
1203
1204        if (needMem) {
1205            // If buffer is no longer valid or fetchAddr has moved to point
1206            // to the next cache block then start fetch from icache.
1207            if (!cacheDataValid[tid] || block_PC != cacheDataPC[tid])
1208                break;
1209
1210            if (blkOffset >= numInsts) {
1211                // We need to process more memory, but we've run out of the
1212                // current block.
1213                break;
1214            }
1215
1216            if (ISA_HAS_DELAY_SLOT && pcOffset == 0) {
1217                // Walk past any annulled delay slot instructions.
1218                Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask;
1219                while (fetchAddr != pcAddr && blkOffset < numInsts) {
1220                    blkOffset++;
1221                    fetchAddr += instSize;
1222                }
1223                if (blkOffset >= numInsts)
1224                    break;
1225            }
1226            MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]);
1227
1228            decoder[tid]->setTC(cpu->thread[tid]->getTC());
1229            decoder[tid]->moreBytes(thisPC, fetchAddr, inst);
1230
1231            if (decoder[tid]->needMoreBytes()) {
1232                blkOffset++;
1233                fetchAddr += instSize;
1234                pcOffset += instSize;
1235            }
1236        }
1237
1238        // Extract as many instructions and/or microops as we can from
1239        // the memory we've processed so far.
1240        do {
1241            if (!(curMacroop || inRom)) {
1242                if (decoder[tid]->instReady()) {
1243                    staticInst = decoder[tid]->decode(thisPC);
1244
1245                    // Increment stat of fetched instructions.
1246                    ++fetchedInsts;
1247
1248                    if (staticInst->isMacroop()) {
1249                        curMacroop = staticInst;
1250                    } else {
1251                        pcOffset = 0;
1252                    }
1253                } else {
1254                    // We need more bytes for this instruction so blkOffset and
1255                    // pcOffset will be updated
1256                    break;
1257                }
1258            }
1259            // Whether we're moving to a new macroop because we're at the
1260            // end of the current one, or the branch predictor incorrectly
1261            // thinks we are...
1262            bool newMacro = false;
1263            if (curMacroop || inRom) {
1264                if (inRom) {
1265                    staticInst = cpu->microcodeRom.fetchMicroop(
1266                            thisPC.microPC(), curMacroop);
1267                } else {
1268                    staticInst = curMacroop->fetchMicroop(thisPC.microPC());
1269                }
1270                newMacro |= staticInst->isLastMicroop();
1271            }
1272
1273            DynInstPtr instruction =
1274                buildInst(tid, staticInst, curMacroop,
1275                          thisPC, nextPC, true);
1276
1277            numInst++;
1278
1279#if TRACING_ON
1280            instruction->fetchTick = curTick();
1281#endif
1282
1283            nextPC = thisPC;
1284
1285            // If we're branching after this instruction, quite fetching
1286            // from the same block then.
1287            predictedBranch |= thisPC.branching();
1288            predictedBranch |=
1289                lookupAndUpdateNextPC(instruction, nextPC);
1290            if (predictedBranch) {
1291                DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC);
1292            }
1293
1294            newMacro |= thisPC.instAddr() != nextPC.instAddr();
1295
1296            // Move to the next instruction, unless we have a branch.
1297            thisPC = nextPC;
1298            inRom = isRomMicroPC(thisPC.microPC());
1299
1300            if (newMacro) {
1301                fetchAddr = thisPC.instAddr() & BaseCPU::PCMask;
1302                blkOffset = (fetchAddr - cacheDataPC[tid]) / instSize;
1303                pcOffset = 0;
1304                curMacroop = NULL;
1305            }
1306
1307            if (instruction->isQuiesce()) {
1308                DPRINTF(Fetch,
1309                        "Quiesce instruction encountered, halting fetch!");
1310                fetchStatus[tid] = QuiescePending;
1311                status_change = true;
1312                break;
1313            }
1314        } while ((curMacroop || decoder[tid]->instReady()) &&
1315                 numInst < fetchWidth);
1316    }
1317
1318    if (predictedBranch) {
1319        DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1320                "instruction encountered.\n", tid);
1321    } else if (numInst >= fetchWidth) {
1322        DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1323                "for this cycle.\n", tid);
1324    } else if (blkOffset >= cacheBlkSize) {
1325        DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1326                "block.\n", tid);
1327    }
1328
1329    macroop[tid] = curMacroop;
1330    fetchOffset[tid] = pcOffset;
1331
1332    if (numInst > 0) {
1333        wroteToTimeBuffer = true;
1334    }
1335
1336    pc[tid] = thisPC;
1337
1338    // pipeline a fetch if we're crossing a cache boundary and not in
1339    // a state that would preclude fetching
1340    fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1341    Addr block_PC = icacheBlockAlignPC(fetchAddr);
1342    issuePipelinedIfetch[tid] = block_PC != cacheDataPC[tid] &&
1343        fetchStatus[tid] != IcacheWaitResponse &&
1344        fetchStatus[tid] != ItlbWait &&
1345        fetchStatus[tid] != IcacheWaitRetry &&
1346        fetchStatus[tid] != QuiescePending &&
1347        !curMacroop;
1348}
1349
1350template<class Impl>
1351void
1352DefaultFetch<Impl>::recvRetry()
1353{
1354    if (retryPkt != NULL) {
1355        assert(cacheBlocked);
1356        assert(retryTid != InvalidThreadID);
1357        assert(fetchStatus[retryTid] == IcacheWaitRetry);
1358
1359        if (cpu->getInstPort().sendTimingReq(retryPkt)) {
1360            fetchStatus[retryTid] = IcacheWaitResponse;
1361            retryPkt = NULL;
1362            retryTid = InvalidThreadID;
1363            cacheBlocked = false;
1364        }
1365    } else {
1366        assert(retryTid == InvalidThreadID);
1367        // Access has been squashed since it was sent out.  Just clear
1368        // the cache being blocked.
1369        cacheBlocked = false;
1370    }
1371}
1372
1373///////////////////////////////////////
1374//                                   //
1375//  SMT FETCH POLICY MAINTAINED HERE //
1376//                                   //
1377///////////////////////////////////////
1378template<class Impl>
1379ThreadID
1380DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1381{
1382    if (numThreads > 1) {
1383        switch (fetch_priority) {
1384
1385          case SingleThread:
1386            return 0;
1387
1388          case RoundRobin:
1389            return roundRobin();
1390
1391          case IQ:
1392            return iqCount();
1393
1394          case LSQ:
1395            return lsqCount();
1396
1397          case Branch:
1398            return branchCount();
1399
1400          default:
1401            return InvalidThreadID;
1402        }
1403    } else {
1404        list<ThreadID>::iterator thread = activeThreads->begin();
1405        if (thread == activeThreads->end()) {
1406            return InvalidThreadID;
1407        }
1408
1409        ThreadID tid = *thread;
1410
1411        if (fetchStatus[tid] == Running ||
1412            fetchStatus[tid] == IcacheAccessComplete ||
1413            fetchStatus[tid] == Idle) {
1414            return tid;
1415        } else {
1416            return InvalidThreadID;
1417        }
1418    }
1419}
1420
1421
1422template<class Impl>
1423ThreadID
1424DefaultFetch<Impl>::roundRobin()
1425{
1426    list<ThreadID>::iterator pri_iter = priorityList.begin();
1427    list<ThreadID>::iterator end      = priorityList.end();
1428
1429    ThreadID high_pri;
1430
1431    while (pri_iter != end) {
1432        high_pri = *pri_iter;
1433
1434        assert(high_pri <= numThreads);
1435
1436        if (fetchStatus[high_pri] == Running ||
1437            fetchStatus[high_pri] == IcacheAccessComplete ||
1438            fetchStatus[high_pri] == Idle) {
1439
1440            priorityList.erase(pri_iter);
1441            priorityList.push_back(high_pri);
1442
1443            return high_pri;
1444        }
1445
1446        pri_iter++;
1447    }
1448
1449    return InvalidThreadID;
1450}
1451
1452template<class Impl>
1453ThreadID
1454DefaultFetch<Impl>::iqCount()
1455{
1456    std::priority_queue<unsigned> PQ;
1457    std::map<unsigned, ThreadID> threadMap;
1458
1459    list<ThreadID>::iterator threads = activeThreads->begin();
1460    list<ThreadID>::iterator end = activeThreads->end();
1461
1462    while (threads != end) {
1463        ThreadID tid = *threads++;
1464        unsigned iqCount = fromIEW->iewInfo[tid].iqCount;
1465
1466        PQ.push(iqCount);
1467        threadMap[iqCount] = tid;
1468    }
1469
1470    while (!PQ.empty()) {
1471        ThreadID high_pri = threadMap[PQ.top()];
1472
1473        if (fetchStatus[high_pri] == Running ||
1474            fetchStatus[high_pri] == IcacheAccessComplete ||
1475            fetchStatus[high_pri] == Idle)
1476            return high_pri;
1477        else
1478            PQ.pop();
1479
1480    }
1481
1482    return InvalidThreadID;
1483}
1484
1485template<class Impl>
1486ThreadID
1487DefaultFetch<Impl>::lsqCount()
1488{
1489    std::priority_queue<unsigned> PQ;
1490    std::map<unsigned, ThreadID> threadMap;
1491
1492    list<ThreadID>::iterator threads = activeThreads->begin();
1493    list<ThreadID>::iterator end = activeThreads->end();
1494
1495    while (threads != end) {
1496        ThreadID tid = *threads++;
1497        unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount;
1498
1499        PQ.push(ldstqCount);
1500        threadMap[ldstqCount] = tid;
1501    }
1502
1503    while (!PQ.empty()) {
1504        ThreadID high_pri = threadMap[PQ.top()];
1505
1506        if (fetchStatus[high_pri] == Running ||
1507            fetchStatus[high_pri] == IcacheAccessComplete ||
1508            fetchStatus[high_pri] == Idle)
1509            return high_pri;
1510        else
1511            PQ.pop();
1512    }
1513
1514    return InvalidThreadID;
1515}
1516
1517template<class Impl>
1518ThreadID
1519DefaultFetch<Impl>::branchCount()
1520{
1521#if 0
1522    list<ThreadID>::iterator thread = activeThreads->begin();
1523    assert(thread != activeThreads->end());
1524    ThreadID tid = *thread;
1525#endif
1526
1527    panic("Branch Count Fetch policy unimplemented\n");
1528    return InvalidThreadID;
1529}
1530
1531template<class Impl>
1532void
1533DefaultFetch<Impl>::pipelineIcacheAccesses(ThreadID tid)
1534{
1535    if (!issuePipelinedIfetch[tid]) {
1536        return;
1537    }
1538
1539    // The next PC to access.
1540    TheISA::PCState thisPC = pc[tid];
1541
1542    if (isRomMicroPC(thisPC.microPC())) {
1543        return;
1544    }
1545
1546    Addr pcOffset = fetchOffset[tid];
1547    Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1548
1549    // Align the fetch PC so its at the start of a cache block.
1550    Addr block_PC = icacheBlockAlignPC(fetchAddr);
1551
1552    // Unless buffer already got the block, fetch it from icache.
1553    if (!(cacheDataValid[tid] && block_PC == cacheDataPC[tid])) {
1554        DPRINTF(Fetch, "[tid:%i]: Issuing a pipelined I-cache access, "
1555                "starting at PC %s.\n", tid, thisPC);
1556
1557        fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
1558    }
1559}
1560
1561template<class Impl>
1562void
1563DefaultFetch<Impl>::profileStall(ThreadID tid) {
1564    DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1565
1566    // @todo Per-thread stats
1567
1568    if (drainPending) {
1569        ++fetchPendingDrainCycles;
1570        DPRINTF(Fetch, "Fetch is waiting for a drain!\n");
1571    } else if (activeThreads->empty()) {
1572        ++fetchNoActiveThreadStallCycles;
1573        DPRINTF(Fetch, "Fetch has no active thread!\n");
1574    } else if (fetchStatus[tid] == Blocked) {
1575        ++fetchBlockedCycles;
1576        DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1577    } else if (fetchStatus[tid] == Squashing) {
1578        ++fetchSquashCycles;
1579        DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1580    } else if (fetchStatus[tid] == IcacheWaitResponse) {
1581        ++icacheStallCycles;
1582        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n",
1583                tid);
1584    } else if (fetchStatus[tid] == ItlbWait) {
1585        ++fetchTlbCycles;
1586        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to "
1587                "finish!\n", tid);
1588    } else if (fetchStatus[tid] == TrapPending) {
1589        ++fetchPendingTrapStallCycles;
1590        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap!\n",
1591                tid);
1592    } else if (fetchStatus[tid] == QuiescePending) {
1593        ++fetchPendingQuiesceStallCycles;
1594        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending quiesce "
1595                "instruction!\n", tid);
1596    } else if (fetchStatus[tid] == IcacheWaitRetry) {
1597        ++fetchIcacheWaitRetryStallCycles;
1598        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for an I-cache retry!\n",
1599                tid);
1600    } else if (fetchStatus[tid] == NoGoodAddr) {
1601            DPRINTF(Fetch, "[tid:%i]: Fetch predicted non-executable address\n",
1602                    tid);
1603    } else {
1604        DPRINTF(Fetch, "[tid:%i]: Unexpected fetch stall reason (Status: %i).\n",
1605             tid, fetchStatus[tid]);
1606    }
1607}
1608