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