fetch_impl.hh revision 2863:2592e056dc5c
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        drainPending) {
359        ++fetchIcacheSquashes;
360        delete pkt->req;
361        delete pkt;
362        return;
363    }
364
365    // Wake up the CPU (if it went to sleep and was waiting on this completion
366    // event).
367    cpu->wakeCPU();
368
369    DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
370            tid);
371
372    switchToActive();
373
374    // Only switch to IcacheAccessComplete if we're not stalled as well.
375    if (checkStall(tid)) {
376        fetchStatus[tid] = Blocked;
377    } else {
378        fetchStatus[tid] = IcacheAccessComplete;
379    }
380
381    // Reset the mem req to NULL.
382    delete pkt->req;
383    delete pkt;
384    memReq[tid] = NULL;
385}
386
387template <class Impl>
388bool
389DefaultFetch<Impl>::drain()
390{
391    // Fetch is ready to drain at any time.
392    cpu->signalDrained();
393    drainPending = true;
394    return true;
395}
396
397template <class Impl>
398void
399DefaultFetch<Impl>::resume()
400{
401    drainPending = false;
402}
403
404template <class Impl>
405void
406DefaultFetch<Impl>::switchOut()
407{
408    switchedOut = true;
409    // Branch predictor needs to have its state cleared.
410    branchPred.switchOut();
411}
412
413template <class Impl>
414void
415DefaultFetch<Impl>::takeOverFrom()
416{
417    // Reset all state
418    for (int i = 0; i < Impl::MaxThreads; ++i) {
419        stalls[i].decode = 0;
420        stalls[i].rename = 0;
421        stalls[i].iew = 0;
422        stalls[i].commit = 0;
423        PC[i] = cpu->readPC(i);
424        nextPC[i] = cpu->readNextPC(i);
425#if THE_ISA != ALPHA_ISA
426        nextNPC[i] = cpu->readNextNPC(i);
427#endif
428        fetchStatus[i] = Running;
429    }
430    numInst = 0;
431    wroteToTimeBuffer = false;
432    _status = Inactive;
433    switchedOut = false;
434    branchPred.takeOverFrom();
435}
436
437template <class Impl>
438void
439DefaultFetch<Impl>::wakeFromQuiesce()
440{
441    DPRINTF(Fetch, "Waking up from quiesce\n");
442    // Hopefully this is safe
443    // @todo: Allow other threads to wake from quiesce.
444    fetchStatus[0] = Running;
445}
446
447template <class Impl>
448inline void
449DefaultFetch<Impl>::switchToActive()
450{
451    if (_status == Inactive) {
452        DPRINTF(Activity, "Activating stage.\n");
453
454        cpu->activateStage(O3CPU::FetchIdx);
455
456        _status = Active;
457    }
458}
459
460template <class Impl>
461inline void
462DefaultFetch<Impl>::switchToInactive()
463{
464    if (_status == Active) {
465        DPRINTF(Activity, "Deactivating stage.\n");
466
467        cpu->deactivateStage(O3CPU::FetchIdx);
468
469        _status = Inactive;
470    }
471}
472
473template <class Impl>
474bool
475DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC)
476{
477    // Do branch prediction check here.
478    // A bit of a misnomer...next_PC is actually the current PC until
479    // this function updates it.
480    bool predict_taken;
481
482    if (!inst->isControl()) {
483        next_PC = next_PC + instSize;
484        inst->setPredTarg(next_PC);
485        return false;
486    }
487
488    predict_taken = branchPred.predict(inst, next_PC, inst->threadNumber);
489
490    ++fetchedBranches;
491
492    if (predict_taken) {
493        ++predictedBranches;
494    }
495
496    return predict_taken;
497}
498
499template <class Impl>
500bool
501DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
502{
503    Fault fault = NoFault;
504
505#if FULL_SYSTEM
506    // Flag to say whether or not address is physical addr.
507    unsigned flags = cpu->inPalMode(fetch_PC) ? PHYSICAL : 0;
508#else
509    unsigned flags = 0;
510#endif // FULL_SYSTEM
511
512    if (cacheBlocked || (interruptPending && flags == 0) || drainPending) {
513        // Hold off fetch from getting new instructions when:
514        // Cache is blocked, or
515        // while an interrupt is pending and we're not in PAL mode, or
516        // fetch is switched out.
517        return false;
518    }
519
520    // Align the fetch PC so it's at the start of a cache block.
521    fetch_PC = icacheBlockAlignPC(fetch_PC);
522
523    // Setup the memReq to do a read of the first instruction's address.
524    // Set the appropriate read size and flags as well.
525    // Build request here.
526    RequestPtr mem_req = new Request(tid, fetch_PC, cacheBlkSize, flags,
527                                     fetch_PC, cpu->readCpuId(), tid);
528
529    memReq[tid] = mem_req;
530
531    // Translate the instruction request.
532    fault = cpu->translateInstReq(mem_req, cpu->thread[tid]);
533
534    // In the case of faults, the fetch stage may need to stall and wait
535    // for the ITB miss to be handled.
536
537    // If translation was successful, attempt to read the first
538    // instruction.
539    if (fault == NoFault) {
540#if 0
541        if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
542            memReq[tid]->flags & UNCACHEABLE) {
543            DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
544                    "misspeculating path)!",
545                    memReq[tid]->paddr);
546            ret_fault = TheISA::genMachineCheckFault();
547            return false;
548        }
549#endif
550
551        // Build packet here.
552        PacketPtr data_pkt = new Packet(mem_req,
553                                        Packet::ReadReq, Packet::Broadcast);
554        data_pkt->dataStatic(cacheData[tid]);
555
556        DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
557
558        fetchedCacheLines++;
559
560        // Now do the timing access to see whether or not the instruction
561        // exists within the cache.
562        if (!icachePort->sendTiming(data_pkt)) {
563            assert(retryPkt == NULL);
564            assert(retryTid == -1);
565            DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
566            fetchStatus[tid] = IcacheWaitRetry;
567            retryPkt = data_pkt;
568            retryTid = tid;
569            cacheBlocked = true;
570            return false;
571        }
572
573        DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
574
575        lastIcacheStall[tid] = curTick;
576
577        DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
578                "response.\n", tid);
579
580        fetchStatus[tid] = IcacheWaitResponse;
581    } else {
582        delete mem_req;
583        memReq[tid] = NULL;
584    }
585
586    ret_fault = fault;
587    return true;
588}
589
590template <class Impl>
591inline void
592DefaultFetch<Impl>::doSquash(const Addr &new_PC, unsigned tid)
593{
594    DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x.\n",
595            tid, new_PC);
596
597    PC[tid] = new_PC;
598    nextPC[tid] = new_PC + instSize;
599
600    // Clear the icache miss if it's outstanding.
601    if (fetchStatus[tid] == IcacheWaitResponse) {
602        DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
603                tid);
604        memReq[tid] = NULL;
605    }
606
607    // Get rid of the retrying packet if it was from this thread.
608    if (retryTid == tid) {
609        assert(cacheBlocked);
610        cacheBlocked = false;
611        retryTid = -1;
612        retryPkt = NULL;
613        delete retryPkt->req;
614        delete retryPkt;
615    }
616
617    fetchStatus[tid] = Squashing;
618
619    ++fetchSquashCycles;
620}
621
622template<class Impl>
623void
624DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC,
625                                     const InstSeqNum &seq_num,
626                                     unsigned tid)
627{
628    DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
629
630    doSquash(new_PC, tid);
631
632    // Tell the CPU to remove any instructions that are in flight between
633    // fetch and decode.
634    cpu->removeInstsUntil(seq_num, tid);
635}
636
637template<class Impl>
638bool
639DefaultFetch<Impl>::checkStall(unsigned tid) const
640{
641    bool ret_val = false;
642
643    if (cpu->contextSwitch) {
644        DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
645        ret_val = true;
646    } else if (stalls[tid].decode) {
647        DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
648        ret_val = true;
649    } else if (stalls[tid].rename) {
650        DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
651        ret_val = true;
652    } else if (stalls[tid].iew) {
653        DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
654        ret_val = true;
655    } else if (stalls[tid].commit) {
656        DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
657        ret_val = true;
658    }
659
660    return ret_val;
661}
662
663template<class Impl>
664typename DefaultFetch<Impl>::FetchStatus
665DefaultFetch<Impl>::updateFetchStatus()
666{
667    //Check Running
668    list<unsigned>::iterator threads = (*activeThreads).begin();
669
670    while (threads != (*activeThreads).end()) {
671
672        unsigned tid = *threads++;
673
674        if (fetchStatus[tid] == Running ||
675            fetchStatus[tid] == Squashing ||
676            fetchStatus[tid] == IcacheAccessComplete) {
677
678            if (_status == Inactive) {
679                DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
680
681                if (fetchStatus[tid] == IcacheAccessComplete) {
682                    DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
683                            "completion\n",tid);
684                }
685
686                cpu->activateStage(O3CPU::FetchIdx);
687            }
688
689            return Active;
690        }
691    }
692
693    // Stage is switching from active to inactive, notify CPU of it.
694    if (_status == Active) {
695        DPRINTF(Activity, "Deactivating stage.\n");
696
697        cpu->deactivateStage(O3CPU::FetchIdx);
698    }
699
700    return Inactive;
701}
702
703template <class Impl>
704void
705DefaultFetch<Impl>::squash(const Addr &new_PC, unsigned tid)
706{
707    DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
708
709    doSquash(new_PC, tid);
710
711    // Tell the CPU to remove any instructions that are not in the ROB.
712    cpu->removeInstsNotInROB(tid);
713}
714
715template <class Impl>
716void
717DefaultFetch<Impl>::tick()
718{
719    list<unsigned>::iterator threads = (*activeThreads).begin();
720    bool status_change = false;
721
722    wroteToTimeBuffer = false;
723
724    while (threads != (*activeThreads).end()) {
725        unsigned tid = *threads++;
726
727        // Check the signals for each thread to determine the proper status
728        // for each thread.
729        bool updated_status = checkSignalsAndUpdate(tid);
730        status_change =  status_change || updated_status;
731    }
732
733    DPRINTF(Fetch, "Running stage.\n");
734
735    // Reset the number of the instruction we're fetching.
736    numInst = 0;
737
738#if FULL_SYSTEM
739    if (fromCommit->commitInfo[0].interruptPending) {
740        interruptPending = true;
741    }
742
743    if (fromCommit->commitInfo[0].clearInterrupt) {
744        interruptPending = false;
745    }
746#endif
747
748    for (threadFetched = 0; threadFetched < numFetchingThreads;
749         threadFetched++) {
750        // Fetch each of the actively fetching threads.
751        fetch(status_change);
752    }
753
754    // Record number of instructions fetched this cycle for distribution.
755    fetchNisnDist.sample(numInst);
756
757    if (status_change) {
758        // Change the fetch stage status if there was a status change.
759        _status = updateFetchStatus();
760    }
761
762    // If there was activity this cycle, inform the CPU of it.
763    if (wroteToTimeBuffer || cpu->contextSwitch) {
764        DPRINTF(Activity, "Activity this cycle.\n");
765
766        cpu->activityThisCycle();
767    }
768}
769
770template <class Impl>
771bool
772DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
773{
774    // Update the per thread stall statuses.
775    if (fromDecode->decodeBlock[tid]) {
776        stalls[tid].decode = true;
777    }
778
779    if (fromDecode->decodeUnblock[tid]) {
780        assert(stalls[tid].decode);
781        assert(!fromDecode->decodeBlock[tid]);
782        stalls[tid].decode = false;
783    }
784
785    if (fromRename->renameBlock[tid]) {
786        stalls[tid].rename = true;
787    }
788
789    if (fromRename->renameUnblock[tid]) {
790        assert(stalls[tid].rename);
791        assert(!fromRename->renameBlock[tid]);
792        stalls[tid].rename = false;
793    }
794
795    if (fromIEW->iewBlock[tid]) {
796        stalls[tid].iew = true;
797    }
798
799    if (fromIEW->iewUnblock[tid]) {
800        assert(stalls[tid].iew);
801        assert(!fromIEW->iewBlock[tid]);
802        stalls[tid].iew = false;
803    }
804
805    if (fromCommit->commitBlock[tid]) {
806        stalls[tid].commit = true;
807    }
808
809    if (fromCommit->commitUnblock[tid]) {
810        assert(stalls[tid].commit);
811        assert(!fromCommit->commitBlock[tid]);
812        stalls[tid].commit = false;
813    }
814
815    // Check squash signals from commit.
816    if (fromCommit->commitInfo[tid].squash) {
817
818        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
819                "from commit.\n",tid);
820
821        // In any case, squash.
822        squash(fromCommit->commitInfo[tid].nextPC,tid);
823
824        // Also check if there's a mispredict that happened.
825        if (fromCommit->commitInfo[tid].branchMispredict) {
826            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
827                              fromCommit->commitInfo[tid].nextPC,
828                              fromCommit->commitInfo[tid].branchTaken,
829                              tid);
830        } else {
831            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
832                              tid);
833        }
834
835        return true;
836    } else if (fromCommit->commitInfo[tid].doneSeqNum) {
837        // Update the branch predictor if it wasn't a squashed instruction
838        // that was broadcasted.
839        branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
840    }
841
842    // Check ROB squash signals from commit.
843    if (fromCommit->commitInfo[tid].robSquashing) {
844        DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
845
846        // Continue to squash.
847        fetchStatus[tid] = Squashing;
848
849        return true;
850    }
851
852    // Check squash signals from decode.
853    if (fromDecode->decodeInfo[tid].squash) {
854        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
855                "from decode.\n",tid);
856
857        // Update the branch predictor.
858        if (fromDecode->decodeInfo[tid].branchMispredict) {
859            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
860                              fromDecode->decodeInfo[tid].nextPC,
861                              fromDecode->decodeInfo[tid].branchTaken,
862                              tid);
863        } else {
864            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
865                              tid);
866        }
867
868        if (fetchStatus[tid] != Squashing) {
869            // Squash unless we're already squashing
870            squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
871                             fromDecode->decodeInfo[tid].doneSeqNum,
872                             tid);
873
874            return true;
875        }
876    }
877
878    if (checkStall(tid) && fetchStatus[tid] != IcacheWaitResponse) {
879        DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
880
881        fetchStatus[tid] = Blocked;
882
883        return true;
884    }
885
886    if (fetchStatus[tid] == Blocked ||
887        fetchStatus[tid] == Squashing) {
888        // Switch status to running if fetch isn't being told to block or
889        // squash this cycle.
890        DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
891                tid);
892
893        fetchStatus[tid] = Running;
894
895        return true;
896    }
897
898    // If we've reached this point, we have not gotten any signals that
899    // cause fetch to change its status.  Fetch remains the same as before.
900    return false;
901}
902
903template<class Impl>
904void
905DefaultFetch<Impl>::fetch(bool &status_change)
906{
907    //////////////////////////////////////////
908    // Start actual fetch
909    //////////////////////////////////////////
910    int tid = getFetchingThread(fetchPolicy);
911
912    if (tid == -1) {
913        DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
914
915        // Breaks looping condition in tick()
916        threadFetched = numFetchingThreads;
917        return;
918    }
919
920    DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
921
922    // The current PC.
923    Addr &fetch_PC = PC[tid];
924
925    // Fault code for memory access.
926    Fault fault = NoFault;
927
928    // If returning from the delay of a cache miss, then update the status
929    // to running, otherwise do the cache access.  Possibly move this up
930    // to tick() function.
931    if (fetchStatus[tid] == IcacheAccessComplete) {
932        DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
933                tid);
934
935        fetchStatus[tid] = Running;
936        status_change = true;
937    } else if (fetchStatus[tid] == Running) {
938        DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
939                "instruction, starting at PC %08p.\n",
940                tid, fetch_PC);
941
942        bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
943        if (!fetch_success) {
944            if (cacheBlocked) {
945                ++icacheStallCycles;
946            } else {
947                ++fetchMiscStallCycles;
948            }
949            return;
950        }
951    } else {
952        if (fetchStatus[tid] == Idle) {
953            ++fetchIdleCycles;
954        } else if (fetchStatus[tid] == Blocked) {
955            ++fetchBlockedCycles;
956        } else if (fetchStatus[tid] == Squashing) {
957            ++fetchSquashCycles;
958        } else if (fetchStatus[tid] == IcacheWaitResponse) {
959            ++icacheStallCycles;
960        }
961
962        // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
963        // fetch should do nothing.
964        return;
965    }
966
967    ++fetchCycles;
968
969    // If we had a stall due to an icache miss, then return.
970    if (fetchStatus[tid] == IcacheWaitResponse) {
971        ++icacheStallCycles;
972        status_change = true;
973        return;
974    }
975
976    Addr next_PC = fetch_PC;
977    InstSeqNum inst_seq;
978    MachInst inst;
979    ExtMachInst ext_inst;
980    // @todo: Fix this hack.
981    unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
982
983    if (fault == NoFault) {
984        // If the read of the first instruction was successful, then grab the
985        // instructions from the rest of the cache line and put them into the
986        // queue heading to decode.
987
988        DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
989                "decode.\n",tid);
990
991        // Need to keep track of whether or not a predicted branch
992        // ended this fetch block.
993        bool predicted_branch = false;
994
995        for (;
996             offset < cacheBlkSize &&
997                 numInst < fetchWidth &&
998                 !predicted_branch;
999             ++numInst) {
1000
1001            // Get a sequence number.
1002            inst_seq = cpu->getAndIncrementInstSeq();
1003
1004            // Make sure this is a valid index.
1005            assert(offset <= cacheBlkSize - instSize);
1006
1007            // Get the instruction from the array of the cache line.
1008            inst = gtoh(*reinterpret_cast<MachInst *>
1009                        (&cacheData[tid][offset]));
1010
1011            ext_inst = TheISA::makeExtMI(inst, fetch_PC);
1012
1013            // Create a new DynInst from the instruction fetched.
1014            DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
1015                                                 next_PC,
1016                                                 inst_seq, cpu);
1017            instruction->setTid(tid);
1018
1019            instruction->setASID(tid);
1020
1021            instruction->setThreadState(cpu->thread[tid]);
1022
1023            DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1024                    "[sn:%lli]\n",
1025                    tid, instruction->readPC(), inst_seq);
1026
1027            DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1028                    tid, instruction->staticInst->disassemble(fetch_PC));
1029
1030            instruction->traceData =
1031                Trace::getInstRecord(curTick, cpu->tcBase(tid), cpu,
1032                                     instruction->staticInst,
1033                                     instruction->readPC(),tid);
1034
1035            predicted_branch = lookupAndUpdateNextPC(instruction, next_PC);
1036
1037            // Add instruction to the CPU's list of instructions.
1038            instruction->setInstListIt(cpu->addInst(instruction));
1039
1040            // Write the instruction to the first slot in the queue
1041            // that heads to decode.
1042            toDecode->insts[numInst] = instruction;
1043
1044            toDecode->size++;
1045
1046            // Increment stat of fetched instructions.
1047            ++fetchedInsts;
1048
1049            // Move to the next instruction, unless we have a branch.
1050            fetch_PC = next_PC;
1051
1052            if (instruction->isQuiesce()) {
1053                warn("cycle %lli: Quiesce instruction encountered, halting fetch!",
1054                     curTick);
1055                fetchStatus[tid] = QuiescePending;
1056                ++numInst;
1057                status_change = true;
1058                break;
1059            }
1060
1061            offset+= instSize;
1062        }
1063    }
1064
1065    if (numInst > 0) {
1066        wroteToTimeBuffer = true;
1067    }
1068
1069    // Now that fetching is completed, update the PC to signify what the next
1070    // cycle will be.
1071    if (fault == NoFault) {
1072        DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n",tid, next_PC);
1073
1074#if THE_ISA == ALPHA_ISA
1075        PC[tid] = next_PC;
1076        nextPC[tid] = next_PC + instSize;
1077#else
1078        PC[tid] = next_PC;
1079        nextPC[tid] = next_PC + instSize;
1080        nextPC[tid] = next_PC + instSize;
1081
1082        thread->setNextPC(thread->readNextNPC());
1083        thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));
1084#endif
1085    } else {
1086        // We shouldn't be in an icache miss and also have a fault (an ITB
1087        // miss)
1088        if (fetchStatus[tid] == IcacheWaitResponse) {
1089            panic("Fetch should have exited prior to this!");
1090        }
1091
1092        // Send the fault to commit.  This thread will not do anything
1093        // until commit handles the fault.  The only other way it can
1094        // wake up is if a squash comes along and changes the PC.
1095#if FULL_SYSTEM
1096        assert(numInst != fetchWidth);
1097        // Get a sequence number.
1098        inst_seq = cpu->getAndIncrementInstSeq();
1099        // We will use a nop in order to carry the fault.
1100        ext_inst = TheISA::NoopMachInst;
1101
1102        // Create a new DynInst from the dummy nop.
1103        DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
1104                                             next_PC,
1105                                             inst_seq, cpu);
1106        instruction->setPredTarg(next_PC + instSize);
1107        instruction->setTid(tid);
1108
1109        instruction->setASID(tid);
1110
1111        instruction->setThreadState(cpu->thread[tid]);
1112
1113        instruction->traceData = NULL;
1114
1115        instruction->setInstListIt(cpu->addInst(instruction));
1116
1117        instruction->fault = fault;
1118
1119        toDecode->insts[numInst] = instruction;
1120        toDecode->size++;
1121
1122        DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1123
1124        fetchStatus[tid] = TrapPending;
1125        status_change = true;
1126
1127        warn("cycle %lli: fault (%d) detected @ PC %08p", curTick, fault, PC[tid]);
1128#else // !FULL_SYSTEM
1129        warn("cycle %lli: fault (%d) detected @ PC %08p", curTick, fault, PC[tid]);
1130#endif // FULL_SYSTEM
1131    }
1132}
1133
1134template<class Impl>
1135void
1136DefaultFetch<Impl>::recvRetry()
1137{
1138    assert(cacheBlocked);
1139    if (retryPkt != NULL) {
1140        assert(retryTid != -1);
1141        assert(fetchStatus[retryTid] == IcacheWaitRetry);
1142
1143        if (icachePort->sendTiming(retryPkt)) {
1144            fetchStatus[retryTid] = IcacheWaitResponse;
1145            retryPkt = NULL;
1146            retryTid = -1;
1147            cacheBlocked = false;
1148        }
1149    } else {
1150        assert(retryTid == -1);
1151        // Access has been squashed since it was sent out.  Just clear
1152        // the cache being blocked.
1153        cacheBlocked = false;
1154    }
1155}
1156
1157///////////////////////////////////////
1158//                                   //
1159//  SMT FETCH POLICY MAINTAINED HERE //
1160//                                   //
1161///////////////////////////////////////
1162template<class Impl>
1163int
1164DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1165{
1166    if (numThreads > 1) {
1167        switch (fetch_priority) {
1168
1169          case SingleThread:
1170            return 0;
1171
1172          case RoundRobin:
1173            return roundRobin();
1174
1175          case IQ:
1176            return iqCount();
1177
1178          case LSQ:
1179            return lsqCount();
1180
1181          case Branch:
1182            return branchCount();
1183
1184          default:
1185            return -1;
1186        }
1187    } else {
1188        int tid = *((*activeThreads).begin());
1189
1190        if (fetchStatus[tid] == Running ||
1191            fetchStatus[tid] == IcacheAccessComplete ||
1192            fetchStatus[tid] == Idle) {
1193            return tid;
1194        } else {
1195            return -1;
1196        }
1197    }
1198
1199}
1200
1201
1202template<class Impl>
1203int
1204DefaultFetch<Impl>::roundRobin()
1205{
1206    list<unsigned>::iterator pri_iter = priorityList.begin();
1207    list<unsigned>::iterator end      = priorityList.end();
1208
1209    int high_pri;
1210
1211    while (pri_iter != end) {
1212        high_pri = *pri_iter;
1213
1214        assert(high_pri <= numThreads);
1215
1216        if (fetchStatus[high_pri] == Running ||
1217            fetchStatus[high_pri] == IcacheAccessComplete ||
1218            fetchStatus[high_pri] == Idle) {
1219
1220            priorityList.erase(pri_iter);
1221            priorityList.push_back(high_pri);
1222
1223            return high_pri;
1224        }
1225
1226        pri_iter++;
1227    }
1228
1229    return -1;
1230}
1231
1232template<class Impl>
1233int
1234DefaultFetch<Impl>::iqCount()
1235{
1236    priority_queue<unsigned> PQ;
1237
1238    list<unsigned>::iterator threads = (*activeThreads).begin();
1239
1240    while (threads != (*activeThreads).end()) {
1241        unsigned tid = *threads++;
1242
1243        PQ.push(fromIEW->iewInfo[tid].iqCount);
1244    }
1245
1246    while (!PQ.empty()) {
1247
1248        unsigned high_pri = PQ.top();
1249
1250        if (fetchStatus[high_pri] == Running ||
1251            fetchStatus[high_pri] == IcacheAccessComplete ||
1252            fetchStatus[high_pri] == Idle)
1253            return high_pri;
1254        else
1255            PQ.pop();
1256
1257    }
1258
1259    return -1;
1260}
1261
1262template<class Impl>
1263int
1264DefaultFetch<Impl>::lsqCount()
1265{
1266    priority_queue<unsigned> PQ;
1267
1268
1269    list<unsigned>::iterator threads = (*activeThreads).begin();
1270
1271    while (threads != (*activeThreads).end()) {
1272        unsigned tid = *threads++;
1273
1274        PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1275    }
1276
1277    while (!PQ.empty()) {
1278
1279        unsigned high_pri = PQ.top();
1280
1281        if (fetchStatus[high_pri] == Running ||
1282            fetchStatus[high_pri] == IcacheAccessComplete ||
1283            fetchStatus[high_pri] == Idle)
1284            return high_pri;
1285        else
1286            PQ.pop();
1287
1288    }
1289
1290    return -1;
1291}
1292
1293template<class Impl>
1294int
1295DefaultFetch<Impl>::branchCount()
1296{
1297    list<unsigned>::iterator threads = (*activeThreads).begin();
1298    panic("Branch Count Fetch policy unimplemented\n");
1299    return *threads;
1300}
1301