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