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