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