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