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