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