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