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