fetch_impl.hh revision 13453:4a7a060ea26e
1/*
2 * Copyright (c) 2010-2014 ARM Limited
3 * Copyright (c) 2012-2013 AMD
4 * All rights reserved.
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2004-2006 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Kevin Lim
42 *          Korey Sewell
43 */
44
45#ifndef __CPU_O3_FETCH_IMPL_HH__
46#define __CPU_O3_FETCH_IMPL_HH__
47
48#include <algorithm>
49#include <cstring>
50#include <list>
51#include <map>
52#include <queue>
53
54#include "arch/generic/tlb.hh"
55#include "arch/isa_traits.hh"
56#include "arch/utility.hh"
57#include "arch/vtophys.hh"
58#include "base/random.hh"
59#include "base/types.hh"
60#include "config/the_isa.hh"
61#include "cpu/base.hh"
62//#include "cpu/checker/cpu.hh"
63#include "cpu/o3/fetch.hh"
64#include "cpu/exetrace.hh"
65#include "debug/Activity.hh"
66#include "debug/Drain.hh"
67#include "debug/Fetch.hh"
68#include "debug/O3PipeView.hh"
69#include "mem/packet.hh"
70#include "params/DerivO3CPU.hh"
71#include "sim/byteswap.hh"
72#include "sim/core.hh"
73#include "sim/eventq.hh"
74#include "sim/full_system.hh"
75#include "sim/system.hh"
76#include "cpu/o3/isa_specific.hh"
77
78using namespace std;
79
80template<class Impl>
81DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
82    : cpu(_cpu),
83      branchPred(nullptr),
84      decodeToFetchDelay(params->decodeToFetchDelay),
85      renameToFetchDelay(params->renameToFetchDelay),
86      iewToFetchDelay(params->iewToFetchDelay),
87      commitToFetchDelay(params->commitToFetchDelay),
88      fetchWidth(params->fetchWidth),
89      decodeWidth(params->decodeWidth),
90      retryPkt(NULL),
91      retryTid(InvalidThreadID),
92      cacheBlkSize(cpu->cacheLineSize()),
93      fetchBufferSize(params->fetchBufferSize),
94      fetchBufferMask(fetchBufferSize - 1),
95      fetchQueueSize(params->fetchQueueSize),
96      numThreads(params->numThreads),
97      numFetchingThreads(params->smtNumFetchingThreads),
98      finishTranslationEvent(this)
99{
100    if (numThreads > Impl::MaxThreads)
101        fatal("numThreads (%d) is larger than compiled limit (%d),\n"
102              "\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
103              numThreads, static_cast<int>(Impl::MaxThreads));
104    if (fetchWidth > Impl::MaxWidth)
105        fatal("fetchWidth (%d) is larger than compiled limit (%d),\n"
106             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
107             fetchWidth, static_cast<int>(Impl::MaxWidth));
108    if (fetchBufferSize > cacheBlkSize)
109        fatal("fetch buffer size (%u bytes) is greater than the cache "
110              "block size (%u bytes)\n", fetchBufferSize, cacheBlkSize);
111    if (cacheBlkSize % fetchBufferSize)
112        fatal("cache block (%u bytes) is not a multiple of the "
113              "fetch buffer (%u bytes)\n", cacheBlkSize, fetchBufferSize);
114
115    std::string policy = params->smtFetchPolicy;
116
117    // Convert string to lowercase
118    std::transform(policy.begin(), policy.end(), policy.begin(),
119                   (int(*)(int)) tolower);
120
121    // Figure out fetch policy
122    if (policy == "singlethread") {
123        fetchPolicy = SingleThread;
124        if (numThreads > 1)
125            panic("Invalid Fetch Policy for a SMT workload.");
126    } else if (policy == "roundrobin") {
127        fetchPolicy = RoundRobin;
128        DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
129    } else if (policy == "branch") {
130        fetchPolicy = Branch;
131        DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
132    } else if (policy == "iqcount") {
133        fetchPolicy = IQ;
134        DPRINTF(Fetch, "Fetch policy set to IQ count\n");
135    } else if (policy == "lsqcount") {
136        fetchPolicy = LSQ;
137        DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
138    } else {
139        fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
140              " RoundRobin,LSQcount,IQcount}\n");
141    }
142
143    // Get the size of an instruction.
144    instSize = sizeof(TheISA::MachInst);
145
146    for (int i = 0; i < Impl::MaxThreads; i++) {
147        fetchStatus[i] = Idle;
148        decoder[i] = nullptr;
149        pc[i] = 0;
150        fetchOffset[i] = 0;
151        macroop[i] = nullptr;
152        delayedCommit[i] = false;
153        memReq[i] = nullptr;
154        stalls[i] = {false, false};
155        fetchBuffer[i] = NULL;
156        fetchBufferPC[i] = 0;
157        fetchBufferValid[i] = false;
158        lastIcacheStall[i] = 0;
159        issuePipelinedIfetch[i] = false;
160    }
161
162    branchPred = params->branchPred;
163
164    for (ThreadID tid = 0; tid < numThreads; tid++) {
165        decoder[tid] = new TheISA::Decoder(params->isa[tid]);
166        // Create space to buffer the cache line data,
167        // which may not hold the entire cache line.
168        fetchBuffer[tid] = new uint8_t[fetchBufferSize];
169    }
170}
171
172template <class Impl>
173std::string
174DefaultFetch<Impl>::name() const
175{
176    return cpu->name() + ".fetch";
177}
178
179template <class Impl>
180void
181DefaultFetch<Impl>::regProbePoints()
182{
183    ppFetch = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Fetch");
184    ppFetchRequestSent = new ProbePointArg<RequestPtr>(cpu->getProbeManager(),
185                                                       "FetchRequest");
186
187}
188
189template <class Impl>
190void
191DefaultFetch<Impl>::regStats()
192{
193    icacheStallCycles
194        .name(name() + ".icacheStallCycles")
195        .desc("Number of cycles fetch is stalled on an Icache miss")
196        .prereq(icacheStallCycles);
197
198    fetchedInsts
199        .name(name() + ".Insts")
200        .desc("Number of instructions fetch has processed")
201        .prereq(fetchedInsts);
202
203    fetchedBranches
204        .name(name() + ".Branches")
205        .desc("Number of branches that fetch encountered")
206        .prereq(fetchedBranches);
207
208    predictedBranches
209        .name(name() + ".predictedBranches")
210        .desc("Number of branches that fetch has predicted taken")
211        .prereq(predictedBranches);
212
213    fetchCycles
214        .name(name() + ".Cycles")
215        .desc("Number of cycles fetch has run and was not squashing or"
216              " blocked")
217        .prereq(fetchCycles);
218
219    fetchSquashCycles
220        .name(name() + ".SquashCycles")
221        .desc("Number of cycles fetch has spent squashing")
222        .prereq(fetchSquashCycles);
223
224    fetchTlbCycles
225        .name(name() + ".TlbCycles")
226        .desc("Number of cycles fetch has spent waiting for tlb")
227        .prereq(fetchTlbCycles);
228
229    fetchIdleCycles
230        .name(name() + ".IdleCycles")
231        .desc("Number of cycles fetch was idle")
232        .prereq(fetchIdleCycles);
233
234    fetchBlockedCycles
235        .name(name() + ".BlockedCycles")
236        .desc("Number of cycles fetch has spent blocked")
237        .prereq(fetchBlockedCycles);
238
239    fetchedCacheLines
240        .name(name() + ".CacheLines")
241        .desc("Number of cache lines fetched")
242        .prereq(fetchedCacheLines);
243
244    fetchMiscStallCycles
245        .name(name() + ".MiscStallCycles")
246        .desc("Number of cycles fetch has spent waiting on interrupts, or "
247              "bad addresses, or out of MSHRs")
248        .prereq(fetchMiscStallCycles);
249
250    fetchPendingDrainCycles
251        .name(name() + ".PendingDrainCycles")
252        .desc("Number of cycles fetch has spent waiting on pipes to drain")
253        .prereq(fetchPendingDrainCycles);
254
255    fetchNoActiveThreadStallCycles
256        .name(name() + ".NoActiveThreadStallCycles")
257        .desc("Number of stall cycles due to no active thread to fetch from")
258        .prereq(fetchNoActiveThreadStallCycles);
259
260    fetchPendingTrapStallCycles
261        .name(name() + ".PendingTrapStallCycles")
262        .desc("Number of stall cycles due to pending traps")
263        .prereq(fetchPendingTrapStallCycles);
264
265    fetchPendingQuiesceStallCycles
266        .name(name() + ".PendingQuiesceStallCycles")
267        .desc("Number of stall cycles due to pending quiesce instructions")
268        .prereq(fetchPendingQuiesceStallCycles);
269
270    fetchIcacheWaitRetryStallCycles
271        .name(name() + ".IcacheWaitRetryStallCycles")
272        .desc("Number of stall cycles due to full MSHR")
273        .prereq(fetchIcacheWaitRetryStallCycles);
274
275    fetchIcacheSquashes
276        .name(name() + ".IcacheSquashes")
277        .desc("Number of outstanding Icache misses that were squashed")
278        .prereq(fetchIcacheSquashes);
279
280    fetchTlbSquashes
281        .name(name() + ".ItlbSquashes")
282        .desc("Number of outstanding ITLB misses that were squashed")
283        .prereq(fetchTlbSquashes);
284
285    fetchNisnDist
286        .init(/* base value */ 0,
287              /* last value */ fetchWidth,
288              /* bucket size */ 1)
289        .name(name() + ".rateDist")
290        .desc("Number of instructions fetched each cycle (Total)")
291        .flags(Stats::pdf);
292
293    idleRate
294        .name(name() + ".idleRate")
295        .desc("Percent of cycles fetch was idle")
296        .prereq(idleRate);
297    idleRate = fetchIdleCycles * 100 / cpu->numCycles;
298
299    branchRate
300        .name(name() + ".branchRate")
301        .desc("Number of branch fetches per cycle")
302        .flags(Stats::total);
303    branchRate = fetchedBranches / cpu->numCycles;
304
305    fetchRate
306        .name(name() + ".rate")
307        .desc("Number of inst fetches per cycle")
308        .flags(Stats::total);
309    fetchRate = fetchedInsts / cpu->numCycles;
310}
311
312template<class Impl>
313void
314DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
315{
316    timeBuffer = time_buffer;
317
318    // Create wires to get information from proper places in time buffer.
319    fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
320    fromRename = timeBuffer->getWire(-renameToFetchDelay);
321    fromIEW = timeBuffer->getWire(-iewToFetchDelay);
322    fromCommit = timeBuffer->getWire(-commitToFetchDelay);
323}
324
325template<class Impl>
326void
327DefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
328{
329    activeThreads = at_ptr;
330}
331
332template<class Impl>
333void
334DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *ftb_ptr)
335{
336    // Create wire to write information to proper place in fetch time buf.
337    toDecode = ftb_ptr->getWire(0);
338}
339
340template<class Impl>
341void
342DefaultFetch<Impl>::startupStage()
343{
344    assert(priorityList.empty());
345    resetStage();
346
347    // Fetch needs to start fetching instructions at the very beginning,
348    // so it must start up in active state.
349    switchToActive();
350}
351
352template<class Impl>
353void
354DefaultFetch<Impl>::resetStage()
355{
356    numInst = 0;
357    interruptPending = false;
358    cacheBlocked = false;
359
360    priorityList.clear();
361
362    // Setup PC and nextPC with initial state.
363    for (ThreadID tid = 0; tid < numThreads; ++tid) {
364        fetchStatus[tid] = Running;
365        pc[tid] = cpu->pcState(tid);
366        fetchOffset[tid] = 0;
367        macroop[tid] = NULL;
368
369        delayedCommit[tid] = false;
370        memReq[tid] = NULL;
371
372        stalls[tid].decode = false;
373        stalls[tid].drain = false;
374
375        fetchBufferPC[tid] = 0;
376        fetchBufferValid[tid] = false;
377
378        fetchQueue[tid].clear();
379
380        priorityList.push_back(tid);
381    }
382
383    wroteToTimeBuffer = false;
384    _status = Inactive;
385}
386
387template<class Impl>
388void
389DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
390{
391    ThreadID tid = cpu->contextToThread(pkt->req->contextId());
392
393    DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n", tid);
394    assert(!cpu->switchedOut());
395
396    // Only change the status if it's still waiting on the icache access
397    // to return.
398    if (fetchStatus[tid] != IcacheWaitResponse ||
399        pkt->req != memReq[tid]) {
400        ++fetchIcacheSquashes;
401        delete pkt;
402        return;
403    }
404
405    memcpy(fetchBuffer[tid], pkt->getConstPtr<uint8_t>(), fetchBufferSize);
406    fetchBufferValid[tid] = true;
407
408    // Wake up the CPU (if it went to sleep and was waiting on
409    // this completion event).
410    cpu->wakeCPU();
411
412    DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
413            tid);
414
415    switchToActive();
416
417    // Only switch to IcacheAccessComplete if we're not stalled as well.
418    if (checkStall(tid)) {
419        fetchStatus[tid] = Blocked;
420    } else {
421        fetchStatus[tid] = IcacheAccessComplete;
422    }
423
424    pkt->req->setAccessLatency();
425    cpu->ppInstAccessComplete->notify(pkt);
426    // Reset the mem req to NULL.
427    delete pkt;
428    memReq[tid] = NULL;
429}
430
431template <class Impl>
432void
433DefaultFetch<Impl>::drainResume()
434{
435    for (ThreadID i = 0; i < numThreads; ++i) {
436        stalls[i].decode = false;
437        stalls[i].drain = false;
438    }
439}
440
441template <class Impl>
442void
443DefaultFetch<Impl>::drainSanityCheck() const
444{
445    assert(isDrained());
446    assert(retryPkt == NULL);
447    assert(retryTid == InvalidThreadID);
448    assert(!cacheBlocked);
449    assert(!interruptPending);
450
451    for (ThreadID i = 0; i < numThreads; ++i) {
452        assert(!memReq[i]);
453        assert(fetchStatus[i] == Idle || stalls[i].drain);
454    }
455
456    branchPred->drainSanityCheck();
457}
458
459template <class Impl>
460bool
461DefaultFetch<Impl>::isDrained() const
462{
463    /* Make sure that threads are either idle of that the commit stage
464     * has signaled that draining has completed by setting the drain
465     * stall flag. This effectively forces the pipeline to be disabled
466     * until the whole system is drained (simulation may continue to
467     * drain other components).
468     */
469    for (ThreadID i = 0; i < numThreads; ++i) {
470        // Verify fetch queues are drained
471        if (!fetchQueue[i].empty())
472            return false;
473
474        // Return false if not idle or drain stalled
475        if (fetchStatus[i] != Idle) {
476            if (fetchStatus[i] == Blocked && stalls[i].drain)
477                continue;
478            else
479                return false;
480        }
481    }
482
483    /* The pipeline might start up again in the middle of the drain
484     * cycle if the finish translation event is scheduled, so make
485     * sure that's not the case.
486     */
487    return !finishTranslationEvent.scheduled();
488}
489
490template <class Impl>
491void
492DefaultFetch<Impl>::takeOverFrom()
493{
494    assert(cpu->getInstPort().isConnected());
495    resetStage();
496
497}
498
499template <class Impl>
500void
501DefaultFetch<Impl>::drainStall(ThreadID tid)
502{
503    assert(cpu->isDraining());
504    assert(!stalls[tid].drain);
505    DPRINTF(Drain, "%i: Thread drained.\n", tid);
506    stalls[tid].drain = true;
507}
508
509template <class Impl>
510void
511DefaultFetch<Impl>::wakeFromQuiesce()
512{
513    DPRINTF(Fetch, "Waking up from quiesce\n");
514    // Hopefully this is safe
515    // @todo: Allow other threads to wake from quiesce.
516    fetchStatus[0] = Running;
517}
518
519template <class Impl>
520inline void
521DefaultFetch<Impl>::switchToActive()
522{
523    if (_status == Inactive) {
524        DPRINTF(Activity, "Activating stage.\n");
525
526        cpu->activateStage(O3CPU::FetchIdx);
527
528        _status = Active;
529    }
530}
531
532template <class Impl>
533inline void
534DefaultFetch<Impl>::switchToInactive()
535{
536    if (_status == Active) {
537        DPRINTF(Activity, "Deactivating stage.\n");
538
539        cpu->deactivateStage(O3CPU::FetchIdx);
540
541        _status = Inactive;
542    }
543}
544
545template <class Impl>
546void
547DefaultFetch<Impl>::deactivateThread(ThreadID tid)
548{
549    // Update priority list
550    auto thread_it = std::find(priorityList.begin(), priorityList.end(), tid);
551    if (thread_it != priorityList.end()) {
552        priorityList.erase(thread_it);
553    }
554}
555
556template <class Impl>
557bool
558DefaultFetch<Impl>::lookupAndUpdateNextPC(
559        const DynInstPtr &inst, TheISA::PCState &nextPC)
560{
561    // Do branch prediction check here.
562    // A bit of a misnomer...next_PC is actually the current PC until
563    // this function updates it.
564    bool predict_taken;
565
566    if (!inst->isControl()) {
567        TheISA::advancePC(nextPC, inst->staticInst);
568        inst->setPredTarg(nextPC);
569        inst->setPredTaken(false);
570        return false;
571    }
572
573    ThreadID tid = inst->threadNumber;
574    predict_taken = branchPred->predict(inst->staticInst, inst->seqNum,
575                                        nextPC, tid);
576
577    if (predict_taken) {
578        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:  Branch predicted to be taken to %s.\n",
579                tid, inst->seqNum, nextPC);
580    } else {
581        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
582                tid, inst->seqNum);
583    }
584
585    DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n",
586            tid, inst->seqNum, nextPC);
587    inst->setPredTarg(nextPC);
588    inst->setPredTaken(predict_taken);
589
590    ++fetchedBranches;
591
592    if (predict_taken) {
593        ++predictedBranches;
594    }
595
596    return predict_taken;
597}
598
599template <class Impl>
600bool
601DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
602{
603    Fault fault = NoFault;
604
605    assert(!cpu->switchedOut());
606
607    // @todo: not sure if these should block translation.
608    //AlphaDep
609    if (cacheBlocked) {
610        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
611                tid);
612        return false;
613    } else if (checkInterrupt(pc) && !delayedCommit[tid]) {
614        // Hold off fetch from getting new instructions when:
615        // Cache is blocked, or
616        // while an interrupt is pending and we're not in PAL mode, or
617        // fetch is switched out.
618        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
619                tid);
620        return false;
621    }
622
623    // Align the fetch address to the start of a fetch buffer segment.
624    Addr fetchBufferBlockPC = fetchBufferAlignPC(vaddr);
625
626    DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n",
627            tid, fetchBufferBlockPC, vaddr);
628
629    // Setup the memReq to do a read of the first instruction's address.
630    // Set the appropriate read size and flags as well.
631    // Build request here.
632    RequestPtr mem_req = std::make_shared<Request>(
633        tid, fetchBufferBlockPC, fetchBufferSize,
634        Request::INST_FETCH, cpu->instMasterId(), pc,
635        cpu->thread[tid]->contextId());
636
637    mem_req->taskId(cpu->taskId());
638
639    memReq[tid] = mem_req;
640
641    // Initiate translation of the icache block
642    fetchStatus[tid] = ItlbWait;
643    FetchTranslation *trans = new FetchTranslation(this);
644    cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(),
645                              trans, BaseTLB::Execute);
646    return true;
647}
648
649template <class Impl>
650void
651DefaultFetch<Impl>::finishTranslation(const Fault &fault,
652                                      const RequestPtr &mem_req)
653{
654    ThreadID tid = cpu->contextToThread(mem_req->contextId());
655    Addr fetchBufferBlockPC = mem_req->getVaddr();
656
657    assert(!cpu->switchedOut());
658
659    // Wake up CPU if it was idle
660    cpu->wakeCPU();
661
662    if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] ||
663        mem_req->getVaddr() != memReq[tid]->getVaddr()) {
664        DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n",
665                tid);
666        ++fetchTlbSquashes;
667        return;
668    }
669
670
671    // If translation was successful, attempt to read the icache block.
672    if (fault == NoFault) {
673        // Check that we're not going off into random memory
674        // If we have, just wait around for commit to squash something and put
675        // us on the right track
676        if (!cpu->system->isMemAddr(mem_req->getPaddr())) {
677            warn("Address %#x is outside of physical memory, stopping fetch\n",
678                    mem_req->getPaddr());
679            fetchStatus[tid] = NoGoodAddr;
680            memReq[tid] = NULL;
681            return;
682        }
683
684        // Build packet here.
685        PacketPtr data_pkt = new Packet(mem_req, MemCmd::ReadReq);
686        data_pkt->dataDynamic(new uint8_t[fetchBufferSize]);
687
688        fetchBufferPC[tid] = fetchBufferBlockPC;
689        fetchBufferValid[tid] = false;
690        DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
691
692        fetchedCacheLines++;
693
694        // Access the cache.
695        if (!cpu->getInstPort().sendTimingReq(data_pkt)) {
696            assert(retryPkt == NULL);
697            assert(retryTid == InvalidThreadID);
698            DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
699
700            fetchStatus[tid] = IcacheWaitRetry;
701            retryPkt = data_pkt;
702            retryTid = tid;
703            cacheBlocked = true;
704        } else {
705            DPRINTF(Fetch, "[tid:%i]: Doing Icache access.\n", tid);
706            DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
707                    "response.\n", tid);
708            lastIcacheStall[tid] = curTick();
709            fetchStatus[tid] = IcacheWaitResponse;
710            // Notify Fetch Request probe when a packet containing a fetch
711            // request is successfully sent
712            ppFetchRequestSent->notify(mem_req);
713        }
714    } else {
715        // Don't send an instruction to decode if we can't handle it.
716        if (!(numInst < fetchWidth) || !(fetchQueue[tid].size() < fetchQueueSize)) {
717            assert(!finishTranslationEvent.scheduled());
718            finishTranslationEvent.setFault(fault);
719            finishTranslationEvent.setReq(mem_req);
720            cpu->schedule(finishTranslationEvent,
721                          cpu->clockEdge(Cycles(1)));
722            return;
723        }
724        DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected %#x\n",
725                tid, mem_req->getVaddr(), memReq[tid]->getVaddr());
726        // Translation faulted, icache request won't be sent.
727        memReq[tid] = NULL;
728
729        // Send the fault to commit.  This thread will not do anything
730        // until commit handles the fault.  The only other way it can
731        // wake up is if a squash comes along and changes the PC.
732        TheISA::PCState fetchPC = pc[tid];
733
734        DPRINTF(Fetch, "[tid:%i]: Translation faulted, building noop.\n", tid);
735        // We will use a nop in ordier to carry the fault.
736        DynInstPtr instruction = buildInst(tid, StaticInst::nopStaticInstPtr,
737                                           NULL, fetchPC, fetchPC, false);
738        instruction->setNotAnInst();
739
740        instruction->setPredTarg(fetchPC);
741        instruction->fault = fault;
742        wroteToTimeBuffer = true;
743
744        DPRINTF(Activity, "Activity this cycle.\n");
745        cpu->activityThisCycle();
746
747        fetchStatus[tid] = TrapPending;
748
749        DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n", tid);
750        DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %s.\n",
751                tid, fault->name(), pc[tid]);
752    }
753    _status = updateFetchStatus();
754}
755
756template <class Impl>
757inline void
758DefaultFetch<Impl>::doSquash(const TheISA::PCState &newPC,
759                             const DynInstPtr squashInst, ThreadID tid)
760{
761    DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %s.\n",
762            tid, newPC);
763
764    pc[tid] = newPC;
765    fetchOffset[tid] = 0;
766    if (squashInst && squashInst->pcState().instAddr() == newPC.instAddr())
767        macroop[tid] = squashInst->macroop;
768    else
769        macroop[tid] = NULL;
770    decoder[tid]->reset();
771
772    // Clear the icache miss if it's outstanding.
773    if (fetchStatus[tid] == IcacheWaitResponse) {
774        DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
775                tid);
776        memReq[tid] = NULL;
777    } else if (fetchStatus[tid] == ItlbWait) {
778        DPRINTF(Fetch, "[tid:%i]: Squashing outstanding ITLB miss.\n",
779                tid);
780        memReq[tid] = NULL;
781    }
782
783    // Get rid of the retrying packet if it was from this thread.
784    if (retryTid == tid) {
785        assert(cacheBlocked);
786        if (retryPkt) {
787            delete retryPkt;
788        }
789        retryPkt = NULL;
790        retryTid = InvalidThreadID;
791    }
792
793    fetchStatus[tid] = Squashing;
794
795    // Empty fetch queue
796    fetchQueue[tid].clear();
797
798    // microops are being squashed, it is not known wheather the
799    // youngest non-squashed microop was  marked delayed commit
800    // or not. Setting the flag to true ensures that the
801    // interrupts are not handled when they cannot be, though
802    // some opportunities to handle interrupts may be missed.
803    delayedCommit[tid] = true;
804
805    ++fetchSquashCycles;
806}
807
808template<class Impl>
809void
810DefaultFetch<Impl>::squashFromDecode(const TheISA::PCState &newPC,
811                                     const DynInstPtr squashInst,
812                                     const InstSeqNum seq_num, ThreadID tid)
813{
814    DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n", tid);
815
816    doSquash(newPC, squashInst, tid);
817
818    // Tell the CPU to remove any instructions that are in flight between
819    // fetch and decode.
820    cpu->removeInstsUntil(seq_num, tid);
821}
822
823template<class Impl>
824bool
825DefaultFetch<Impl>::checkStall(ThreadID tid) const
826{
827    bool ret_val = false;
828
829    if (stalls[tid].drain) {
830        assert(cpu->isDraining());
831        DPRINTF(Fetch,"[tid:%i]: Drain stall detected.\n",tid);
832        ret_val = true;
833    }
834
835    return ret_val;
836}
837
838template<class Impl>
839typename DefaultFetch<Impl>::FetchStatus
840DefaultFetch<Impl>::updateFetchStatus()
841{
842    //Check Running
843    list<ThreadID>::iterator threads = activeThreads->begin();
844    list<ThreadID>::iterator end = activeThreads->end();
845
846    while (threads != end) {
847        ThreadID tid = *threads++;
848
849        if (fetchStatus[tid] == Running ||
850            fetchStatus[tid] == Squashing ||
851            fetchStatus[tid] == IcacheAccessComplete) {
852
853            if (_status == Inactive) {
854                DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
855
856                if (fetchStatus[tid] == IcacheAccessComplete) {
857                    DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
858                            "completion\n",tid);
859                }
860
861                cpu->activateStage(O3CPU::FetchIdx);
862            }
863
864            return Active;
865        }
866    }
867
868    // Stage is switching from active to inactive, notify CPU of it.
869    if (_status == Active) {
870        DPRINTF(Activity, "Deactivating stage.\n");
871
872        cpu->deactivateStage(O3CPU::FetchIdx);
873    }
874
875    return Inactive;
876}
877
878template <class Impl>
879void
880DefaultFetch<Impl>::squash(const TheISA::PCState &newPC,
881                           const InstSeqNum seq_num, DynInstPtr squashInst,
882                           ThreadID tid)
883{
884    DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid);
885
886    doSquash(newPC, squashInst, tid);
887
888    // Tell the CPU to remove any instructions that are not in the ROB.
889    cpu->removeInstsNotInROB(tid);
890}
891
892template <class Impl>
893void
894DefaultFetch<Impl>::tick()
895{
896    list<ThreadID>::iterator threads = activeThreads->begin();
897    list<ThreadID>::iterator end = activeThreads->end();
898    bool status_change = false;
899
900    wroteToTimeBuffer = false;
901
902    for (ThreadID i = 0; i < numThreads; ++i) {
903        issuePipelinedIfetch[i] = false;
904    }
905
906    while (threads != end) {
907        ThreadID tid = *threads++;
908
909        // Check the signals for each thread to determine the proper status
910        // for each thread.
911        bool updated_status = checkSignalsAndUpdate(tid);
912        status_change =  status_change || updated_status;
913    }
914
915    DPRINTF(Fetch, "Running stage.\n");
916
917    if (FullSystem) {
918        if (fromCommit->commitInfo[0].interruptPending) {
919            interruptPending = true;
920        }
921
922        if (fromCommit->commitInfo[0].clearInterrupt) {
923            interruptPending = false;
924        }
925    }
926
927    for (threadFetched = 0; threadFetched < numFetchingThreads;
928         threadFetched++) {
929        // Fetch each of the actively fetching threads.
930        fetch(status_change);
931    }
932
933    // Record number of instructions fetched this cycle for distribution.
934    fetchNisnDist.sample(numInst);
935
936    if (status_change) {
937        // Change the fetch stage status if there was a status change.
938        _status = updateFetchStatus();
939    }
940
941    // Issue the next I-cache request if possible.
942    for (ThreadID i = 0; i < numThreads; ++i) {
943        if (issuePipelinedIfetch[i]) {
944            pipelineIcacheAccesses(i);
945        }
946    }
947
948    // Send instructions enqueued into the fetch queue to decode.
949    // Limit rate by fetchWidth.  Stall if decode is stalled.
950    unsigned insts_to_decode = 0;
951    unsigned available_insts = 0;
952
953    for (auto tid : *activeThreads) {
954        if (!stalls[tid].decode) {
955            available_insts += fetchQueue[tid].size();
956        }
957    }
958
959    // Pick a random thread to start trying to grab instructions from
960    auto tid_itr = activeThreads->begin();
961    std::advance(tid_itr, random_mt.random<uint8_t>(0, activeThreads->size() - 1));
962
963    while (available_insts != 0 && insts_to_decode < decodeWidth) {
964        ThreadID tid = *tid_itr;
965        if (!stalls[tid].decode && !fetchQueue[tid].empty()) {
966            const auto& inst = fetchQueue[tid].front();
967            toDecode->insts[toDecode->size++] = inst;
968            DPRINTF(Fetch, "[tid:%i][sn:%i]: Sending instruction to decode from "
969                    "fetch queue. Fetch queue size: %i.\n",
970                    tid, inst->seqNum, fetchQueue[tid].size());
971
972            wroteToTimeBuffer = true;
973            fetchQueue[tid].pop_front();
974            insts_to_decode++;
975            available_insts--;
976        }
977
978        tid_itr++;
979        // Wrap around if at end of active threads list
980        if (tid_itr == activeThreads->end())
981            tid_itr = activeThreads->begin();
982    }
983
984    // If there was activity this cycle, inform the CPU of it.
985    if (wroteToTimeBuffer) {
986        DPRINTF(Activity, "Activity this cycle.\n");
987        cpu->activityThisCycle();
988    }
989
990    // Reset the number of the instruction we've fetched.
991    numInst = 0;
992}
993
994template <class Impl>
995bool
996DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
997{
998    // Update the per thread stall statuses.
999    if (fromDecode->decodeBlock[tid]) {
1000        stalls[tid].decode = true;
1001    }
1002
1003    if (fromDecode->decodeUnblock[tid]) {
1004        assert(stalls[tid].decode);
1005        assert(!fromDecode->decodeBlock[tid]);
1006        stalls[tid].decode = false;
1007    }
1008
1009    // Check squash signals from commit.
1010    if (fromCommit->commitInfo[tid].squash) {
1011
1012        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
1013                "from commit.\n",tid);
1014        // In any case, squash.
1015        squash(fromCommit->commitInfo[tid].pc,
1016               fromCommit->commitInfo[tid].doneSeqNum,
1017               fromCommit->commitInfo[tid].squashInst, tid);
1018
1019        // If it was a branch mispredict on a control instruction, update the
1020        // branch predictor with that instruction, otherwise just kill the
1021        // invalid state we generated in after sequence number
1022        if (fromCommit->commitInfo[tid].mispredictInst &&
1023            fromCommit->commitInfo[tid].mispredictInst->isControl()) {
1024            branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum,
1025                              fromCommit->commitInfo[tid].pc,
1026                              fromCommit->commitInfo[tid].branchTaken,
1027                              tid);
1028        } else {
1029            branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum,
1030                              tid);
1031        }
1032
1033        return true;
1034    } else if (fromCommit->commitInfo[tid].doneSeqNum) {
1035        // Update the branch predictor if it wasn't a squashed instruction
1036        // that was broadcasted.
1037        branchPred->update(fromCommit->commitInfo[tid].doneSeqNum, tid);
1038    }
1039
1040    // Check squash signals from decode.
1041    if (fromDecode->decodeInfo[tid].squash) {
1042        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
1043                "from decode.\n",tid);
1044
1045        // Update the branch predictor.
1046        if (fromDecode->decodeInfo[tid].branchMispredict) {
1047            branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum,
1048                              fromDecode->decodeInfo[tid].nextPC,
1049                              fromDecode->decodeInfo[tid].branchTaken,
1050                              tid);
1051        } else {
1052            branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum,
1053                              tid);
1054        }
1055
1056        if (fetchStatus[tid] != Squashing) {
1057
1058            DPRINTF(Fetch, "Squashing from decode with PC = %s\n",
1059                fromDecode->decodeInfo[tid].nextPC);
1060            // Squash unless we're already squashing
1061            squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
1062                             fromDecode->decodeInfo[tid].squashInst,
1063                             fromDecode->decodeInfo[tid].doneSeqNum,
1064                             tid);
1065
1066            return true;
1067        }
1068    }
1069
1070    if (checkStall(tid) &&
1071        fetchStatus[tid] != IcacheWaitResponse &&
1072        fetchStatus[tid] != IcacheWaitRetry &&
1073        fetchStatus[tid] != ItlbWait &&
1074        fetchStatus[tid] != QuiescePending) {
1075        DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
1076
1077        fetchStatus[tid] = Blocked;
1078
1079        return true;
1080    }
1081
1082    if (fetchStatus[tid] == Blocked ||
1083        fetchStatus[tid] == Squashing) {
1084        // Switch status to running if fetch isn't being told to block or
1085        // squash this cycle.
1086        DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
1087                tid);
1088
1089        fetchStatus[tid] = Running;
1090
1091        return true;
1092    }
1093
1094    // If we've reached this point, we have not gotten any signals that
1095    // cause fetch to change its status.  Fetch remains the same as before.
1096    return false;
1097}
1098
1099template<class Impl>
1100typename Impl::DynInstPtr
1101DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst,
1102                              StaticInstPtr curMacroop, TheISA::PCState thisPC,
1103                              TheISA::PCState nextPC, bool trace)
1104{
1105    // Get a sequence number.
1106    InstSeqNum seq = cpu->getAndIncrementInstSeq();
1107
1108    // Create a new DynInst from the instruction fetched.
1109    DynInstPtr instruction =
1110        new DynInst(staticInst, curMacroop, thisPC, nextPC, seq, cpu);
1111    instruction->setTid(tid);
1112
1113    instruction->setASID(tid);
1114
1115    instruction->setThreadState(cpu->thread[tid]);
1116
1117    DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created "
1118            "[sn:%lli].\n", tid, thisPC.instAddr(),
1119            thisPC.microPC(), seq);
1120
1121    DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid,
1122            instruction->staticInst->
1123            disassemble(thisPC.instAddr()));
1124
1125#if TRACING_ON
1126    if (trace) {
1127        instruction->traceData =
1128            cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid),
1129                    instruction->staticInst, thisPC, curMacroop);
1130    }
1131#else
1132    instruction->traceData = NULL;
1133#endif
1134
1135    // Add instruction to the CPU's list of instructions.
1136    instruction->setInstListIt(cpu->addInst(instruction));
1137
1138    // Write the instruction to the first slot in the queue
1139    // that heads to decode.
1140    assert(numInst < fetchWidth);
1141    fetchQueue[tid].push_back(instruction);
1142    assert(fetchQueue[tid].size() <= fetchQueueSize);
1143    DPRINTF(Fetch, "[tid:%i]: Fetch queue entry created (%i/%i).\n",
1144            tid, fetchQueue[tid].size(), fetchQueueSize);
1145    //toDecode->insts[toDecode->size++] = instruction;
1146
1147    // Keep track of if we can take an interrupt at this boundary
1148    delayedCommit[tid] = instruction->isDelayedCommit();
1149
1150    return instruction;
1151}
1152
1153template<class Impl>
1154void
1155DefaultFetch<Impl>::fetch(bool &status_change)
1156{
1157    //////////////////////////////////////////
1158    // Start actual fetch
1159    //////////////////////////////////////////
1160    ThreadID tid = getFetchingThread(fetchPolicy);
1161
1162    assert(!cpu->switchedOut());
1163
1164    if (tid == InvalidThreadID) {
1165        // Breaks looping condition in tick()
1166        threadFetched = numFetchingThreads;
1167
1168        if (numThreads == 1) {  // @todo Per-thread stats
1169            profileStall(0);
1170        }
1171
1172        return;
1173    }
1174
1175    DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1176
1177    // The current PC.
1178    TheISA::PCState thisPC = pc[tid];
1179
1180    Addr pcOffset = fetchOffset[tid];
1181    Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1182
1183    bool inRom = isRomMicroPC(thisPC.microPC());
1184
1185    // If returning from the delay of a cache miss, then update the status
1186    // to running, otherwise do the cache access.  Possibly move this up
1187    // to tick() function.
1188    if (fetchStatus[tid] == IcacheAccessComplete) {
1189        DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid);
1190
1191        fetchStatus[tid] = Running;
1192        status_change = true;
1193    } else if (fetchStatus[tid] == Running) {
1194        // Align the fetch PC so its at the start of a fetch buffer segment.
1195        Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
1196
1197        // If buffer is no longer valid or fetchAddr has moved to point
1198        // to the next cache block, AND we have no remaining ucode
1199        // from a macro-op, then start fetch from icache.
1200        if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])
1201            && !inRom && !macroop[tid]) {
1202            DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1203                    "instruction, starting at PC %s.\n", tid, thisPC);
1204
1205            fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
1206
1207            if (fetchStatus[tid] == IcacheWaitResponse)
1208                ++icacheStallCycles;
1209            else if (fetchStatus[tid] == ItlbWait)
1210                ++fetchTlbCycles;
1211            else
1212                ++fetchMiscStallCycles;
1213            return;
1214        } else if ((checkInterrupt(thisPC.instAddr()) && !delayedCommit[tid])) {
1215            // Stall CPU if an interrupt is posted and we're not issuing
1216            // an delayed commit micro-op currently (delayed commit instructions
1217            // are not interruptable by interrupts, only faults)
1218            ++fetchMiscStallCycles;
1219            DPRINTF(Fetch, "[tid:%i]: Fetch is stalled!\n", tid);
1220            return;
1221        }
1222    } else {
1223        if (fetchStatus[tid] == Idle) {
1224            ++fetchIdleCycles;
1225            DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1226        }
1227
1228        // Status is Idle, so fetch should do nothing.
1229        return;
1230    }
1231
1232    ++fetchCycles;
1233
1234    TheISA::PCState nextPC = thisPC;
1235
1236    StaticInstPtr staticInst = NULL;
1237    StaticInstPtr curMacroop = macroop[tid];
1238
1239    // If the read of the first instruction was successful, then grab the
1240    // instructions from the rest of the cache line and put them into the
1241    // queue heading to decode.
1242
1243    DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1244            "decode.\n", tid);
1245
1246    // Need to keep track of whether or not a predicted branch
1247    // ended this fetch block.
1248    bool predictedBranch = false;
1249
1250    // Need to halt fetch if quiesce instruction detected
1251    bool quiesce = false;
1252
1253    TheISA::MachInst *cacheInsts =
1254        reinterpret_cast<TheISA::MachInst *>(fetchBuffer[tid]);
1255
1256    const unsigned numInsts = fetchBufferSize / instSize;
1257    unsigned blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize;
1258
1259    // Loop through instruction memory from the cache.
1260    // Keep issuing while fetchWidth is available and branch is not
1261    // predicted taken
1262    while (numInst < fetchWidth && fetchQueue[tid].size() < fetchQueueSize
1263           && !predictedBranch && !quiesce) {
1264        // We need to process more memory if we aren't going to get a
1265        // StaticInst from the rom, the current macroop, or what's already
1266        // in the decoder.
1267        bool needMem = !inRom && !curMacroop &&
1268            !decoder[tid]->instReady();
1269        fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1270        Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
1271
1272        if (needMem) {
1273            // If buffer is no longer valid or fetchAddr has moved to point
1274            // to the next cache block then start fetch from icache.
1275            if (!fetchBufferValid[tid] ||
1276                fetchBufferBlockPC != fetchBufferPC[tid])
1277                break;
1278
1279            if (blkOffset >= numInsts) {
1280                // We need to process more memory, but we've run out of the
1281                // current block.
1282                break;
1283            }
1284
1285            MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]);
1286            decoder[tid]->moreBytes(thisPC, fetchAddr, inst);
1287
1288            if (decoder[tid]->needMoreBytes()) {
1289                blkOffset++;
1290                fetchAddr += instSize;
1291                pcOffset += instSize;
1292            }
1293        }
1294
1295        // Extract as many instructions and/or microops as we can from
1296        // the memory we've processed so far.
1297        do {
1298            if (!(curMacroop || inRom)) {
1299                if (decoder[tid]->instReady()) {
1300                    staticInst = decoder[tid]->decode(thisPC);
1301
1302                    // Increment stat of fetched instructions.
1303                    ++fetchedInsts;
1304
1305                    if (staticInst->isMacroop()) {
1306                        curMacroop = staticInst;
1307                    } else {
1308                        pcOffset = 0;
1309                    }
1310                } else {
1311                    // We need more bytes for this instruction so blkOffset and
1312                    // pcOffset will be updated
1313                    break;
1314                }
1315            }
1316            // Whether we're moving to a new macroop because we're at the
1317            // end of the current one, or the branch predictor incorrectly
1318            // thinks we are...
1319            bool newMacro = false;
1320            if (curMacroop || inRom) {
1321                if (inRom) {
1322                    staticInst = cpu->microcodeRom.fetchMicroop(
1323                            thisPC.microPC(), curMacroop);
1324                } else {
1325                    staticInst = curMacroop->fetchMicroop(thisPC.microPC());
1326                }
1327                newMacro |= staticInst->isLastMicroop();
1328            }
1329
1330            DynInstPtr instruction =
1331                buildInst(tid, staticInst, curMacroop,
1332                          thisPC, nextPC, true);
1333
1334            ppFetch->notify(instruction);
1335            numInst++;
1336
1337#if TRACING_ON
1338            if (DTRACE(O3PipeView)) {
1339                instruction->fetchTick = curTick();
1340            }
1341#endif
1342
1343            nextPC = thisPC;
1344
1345            // If we're branching after this instruction, quit fetching
1346            // from the same block.
1347            predictedBranch |= thisPC.branching();
1348            predictedBranch |=
1349                lookupAndUpdateNextPC(instruction, nextPC);
1350            if (predictedBranch) {
1351                DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC);
1352            }
1353
1354            newMacro |= thisPC.instAddr() != nextPC.instAddr();
1355
1356            // Move to the next instruction, unless we have a branch.
1357            thisPC = nextPC;
1358            inRom = isRomMicroPC(thisPC.microPC());
1359
1360            if (newMacro) {
1361                fetchAddr = thisPC.instAddr() & BaseCPU::PCMask;
1362                blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize;
1363                pcOffset = 0;
1364                curMacroop = NULL;
1365            }
1366
1367            if (instruction->isQuiesce()) {
1368                DPRINTF(Fetch,
1369                        "Quiesce instruction encountered, halting fetch!\n");
1370                fetchStatus[tid] = QuiescePending;
1371                status_change = true;
1372                quiesce = true;
1373                break;
1374            }
1375        } while ((curMacroop || decoder[tid]->instReady()) &&
1376                 numInst < fetchWidth &&
1377                 fetchQueue[tid].size() < fetchQueueSize);
1378
1379        // Re-evaluate whether the next instruction to fetch is in micro-op ROM
1380        // or not.
1381        inRom = isRomMicroPC(thisPC.microPC());
1382    }
1383
1384    if (predictedBranch) {
1385        DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1386                "instruction encountered.\n", tid);
1387    } else if (numInst >= fetchWidth) {
1388        DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1389                "for this cycle.\n", tid);
1390    } else if (blkOffset >= fetchBufferSize) {
1391        DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of the"
1392                "fetch buffer.\n", tid);
1393    }
1394
1395    macroop[tid] = curMacroop;
1396    fetchOffset[tid] = pcOffset;
1397
1398    if (numInst > 0) {
1399        wroteToTimeBuffer = true;
1400    }
1401
1402    pc[tid] = thisPC;
1403
1404    // pipeline a fetch if we're crossing a fetch buffer boundary and not in
1405    // a state that would preclude fetching
1406    fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1407    Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
1408    issuePipelinedIfetch[tid] = fetchBufferBlockPC != fetchBufferPC[tid] &&
1409        fetchStatus[tid] != IcacheWaitResponse &&
1410        fetchStatus[tid] != ItlbWait &&
1411        fetchStatus[tid] != IcacheWaitRetry &&
1412        fetchStatus[tid] != QuiescePending &&
1413        !curMacroop;
1414}
1415
1416template<class Impl>
1417void
1418DefaultFetch<Impl>::recvReqRetry()
1419{
1420    if (retryPkt != NULL) {
1421        assert(cacheBlocked);
1422        assert(retryTid != InvalidThreadID);
1423        assert(fetchStatus[retryTid] == IcacheWaitRetry);
1424
1425        if (cpu->getInstPort().sendTimingReq(retryPkt)) {
1426            fetchStatus[retryTid] = IcacheWaitResponse;
1427            // Notify Fetch Request probe when a retryPkt is successfully sent.
1428            // Note that notify must be called before retryPkt is set to NULL.
1429            ppFetchRequestSent->notify(retryPkt->req);
1430            retryPkt = NULL;
1431            retryTid = InvalidThreadID;
1432            cacheBlocked = false;
1433        }
1434    } else {
1435        assert(retryTid == InvalidThreadID);
1436        // Access has been squashed since it was sent out.  Just clear
1437        // the cache being blocked.
1438        cacheBlocked = false;
1439    }
1440}
1441
1442///////////////////////////////////////
1443//                                   //
1444//  SMT FETCH POLICY MAINTAINED HERE //
1445//                                   //
1446///////////////////////////////////////
1447template<class Impl>
1448ThreadID
1449DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1450{
1451    if (numThreads > 1) {
1452        switch (fetch_priority) {
1453
1454          case SingleThread:
1455            return 0;
1456
1457          case RoundRobin:
1458            return roundRobin();
1459
1460          case IQ:
1461            return iqCount();
1462
1463          case LSQ:
1464            return lsqCount();
1465
1466          case Branch:
1467            return branchCount();
1468
1469          default:
1470            return InvalidThreadID;
1471        }
1472    } else {
1473        list<ThreadID>::iterator thread = activeThreads->begin();
1474        if (thread == activeThreads->end()) {
1475            return InvalidThreadID;
1476        }
1477
1478        ThreadID tid = *thread;
1479
1480        if (fetchStatus[tid] == Running ||
1481            fetchStatus[tid] == IcacheAccessComplete ||
1482            fetchStatus[tid] == Idle) {
1483            return tid;
1484        } else {
1485            return InvalidThreadID;
1486        }
1487    }
1488}
1489
1490
1491template<class Impl>
1492ThreadID
1493DefaultFetch<Impl>::roundRobin()
1494{
1495    list<ThreadID>::iterator pri_iter = priorityList.begin();
1496    list<ThreadID>::iterator end      = priorityList.end();
1497
1498    ThreadID high_pri;
1499
1500    while (pri_iter != end) {
1501        high_pri = *pri_iter;
1502
1503        assert(high_pri <= numThreads);
1504
1505        if (fetchStatus[high_pri] == Running ||
1506            fetchStatus[high_pri] == IcacheAccessComplete ||
1507            fetchStatus[high_pri] == Idle) {
1508
1509            priorityList.erase(pri_iter);
1510            priorityList.push_back(high_pri);
1511
1512            return high_pri;
1513        }
1514
1515        pri_iter++;
1516    }
1517
1518    return InvalidThreadID;
1519}
1520
1521template<class Impl>
1522ThreadID
1523DefaultFetch<Impl>::iqCount()
1524{
1525    //sorted from lowest->highest
1526    std::priority_queue<unsigned,vector<unsigned>,
1527                        std::greater<unsigned> > PQ;
1528    std::map<unsigned, ThreadID> threadMap;
1529
1530    list<ThreadID>::iterator threads = activeThreads->begin();
1531    list<ThreadID>::iterator end = activeThreads->end();
1532
1533    while (threads != end) {
1534        ThreadID tid = *threads++;
1535        unsigned iqCount = fromIEW->iewInfo[tid].iqCount;
1536
1537        //we can potentially get tid collisions if two threads
1538        //have the same iqCount, but this should be rare.
1539        PQ.push(iqCount);
1540        threadMap[iqCount] = tid;
1541    }
1542
1543    while (!PQ.empty()) {
1544        ThreadID high_pri = threadMap[PQ.top()];
1545
1546        if (fetchStatus[high_pri] == Running ||
1547            fetchStatus[high_pri] == IcacheAccessComplete ||
1548            fetchStatus[high_pri] == Idle)
1549            return high_pri;
1550        else
1551            PQ.pop();
1552
1553    }
1554
1555    return InvalidThreadID;
1556}
1557
1558template<class Impl>
1559ThreadID
1560DefaultFetch<Impl>::lsqCount()
1561{
1562    //sorted from lowest->highest
1563    std::priority_queue<unsigned,vector<unsigned>,
1564                        std::greater<unsigned> > PQ;
1565    std::map<unsigned, ThreadID> threadMap;
1566
1567    list<ThreadID>::iterator threads = activeThreads->begin();
1568    list<ThreadID>::iterator end = activeThreads->end();
1569
1570    while (threads != end) {
1571        ThreadID tid = *threads++;
1572        unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount;
1573
1574        //we can potentially get tid collisions if two threads
1575        //have the same iqCount, but this should be rare.
1576        PQ.push(ldstqCount);
1577        threadMap[ldstqCount] = tid;
1578    }
1579
1580    while (!PQ.empty()) {
1581        ThreadID high_pri = threadMap[PQ.top()];
1582
1583        if (fetchStatus[high_pri] == Running ||
1584            fetchStatus[high_pri] == IcacheAccessComplete ||
1585            fetchStatus[high_pri] == Idle)
1586            return high_pri;
1587        else
1588            PQ.pop();
1589    }
1590
1591    return InvalidThreadID;
1592}
1593
1594template<class Impl>
1595ThreadID
1596DefaultFetch<Impl>::branchCount()
1597{
1598#if 0
1599    list<ThreadID>::iterator thread = activeThreads->begin();
1600    assert(thread != activeThreads->end());
1601    ThreadID tid = *thread;
1602#endif
1603
1604    panic("Branch Count Fetch policy unimplemented\n");
1605    return InvalidThreadID;
1606}
1607
1608template<class Impl>
1609void
1610DefaultFetch<Impl>::pipelineIcacheAccesses(ThreadID tid)
1611{
1612    if (!issuePipelinedIfetch[tid]) {
1613        return;
1614    }
1615
1616    // The next PC to access.
1617    TheISA::PCState thisPC = pc[tid];
1618
1619    if (isRomMicroPC(thisPC.microPC())) {
1620        return;
1621    }
1622
1623    Addr pcOffset = fetchOffset[tid];
1624    Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1625
1626    // Align the fetch PC so its at the start of a fetch buffer segment.
1627    Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
1628
1629    // Unless buffer already got the block, fetch it from icache.
1630    if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])) {
1631        DPRINTF(Fetch, "[tid:%i]: Issuing a pipelined I-cache access, "
1632                "starting at PC %s.\n", tid, thisPC);
1633
1634        fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
1635    }
1636}
1637
1638template<class Impl>
1639void
1640DefaultFetch<Impl>::profileStall(ThreadID tid) {
1641    DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1642
1643    // @todo Per-thread stats
1644
1645    if (stalls[tid].drain) {
1646        ++fetchPendingDrainCycles;
1647        DPRINTF(Fetch, "Fetch is waiting for a drain!\n");
1648    } else if (activeThreads->empty()) {
1649        ++fetchNoActiveThreadStallCycles;
1650        DPRINTF(Fetch, "Fetch has no active thread!\n");
1651    } else if (fetchStatus[tid] == Blocked) {
1652        ++fetchBlockedCycles;
1653        DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1654    } else if (fetchStatus[tid] == Squashing) {
1655        ++fetchSquashCycles;
1656        DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1657    } else if (fetchStatus[tid] == IcacheWaitResponse) {
1658        ++icacheStallCycles;
1659        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n",
1660                tid);
1661    } else if (fetchStatus[tid] == ItlbWait) {
1662        ++fetchTlbCycles;
1663        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to "
1664                "finish!\n", tid);
1665    } else if (fetchStatus[tid] == TrapPending) {
1666        ++fetchPendingTrapStallCycles;
1667        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap!\n",
1668                tid);
1669    } else if (fetchStatus[tid] == QuiescePending) {
1670        ++fetchPendingQuiesceStallCycles;
1671        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending quiesce "
1672                "instruction!\n", tid);
1673    } else if (fetchStatus[tid] == IcacheWaitRetry) {
1674        ++fetchIcacheWaitRetryStallCycles;
1675        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for an I-cache retry!\n",
1676                tid);
1677    } else if (fetchStatus[tid] == NoGoodAddr) {
1678            DPRINTF(Fetch, "[tid:%i]: Fetch predicted non-executable address\n",
1679                    tid);
1680    } else {
1681        DPRINTF(Fetch, "[tid:%i]: Unexpected fetch stall reason (Status: %i).\n",
1682             tid, fetchStatus[tid]);
1683    }
1684}
1685
1686#endif//__CPU_O3_FETCH_IMPL_HH__
1687