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