fetch_impl.hh revision 6429:7ed8937e375a
112837Sgabeblack@google.com/*
212837Sgabeblack@google.com * Copyright (c) 2004-2006 The Regents of The University of Michigan
312837Sgabeblack@google.com * All rights reserved.
412837Sgabeblack@google.com *
512837Sgabeblack@google.com * Redistribution and use in source and binary forms, with or without
612837Sgabeblack@google.com * modification, are permitted provided that the following conditions are
712837Sgabeblack@google.com * met: redistributions of source code must retain the above copyright
812837Sgabeblack@google.com * notice, this list of conditions and the following disclaimer;
912837Sgabeblack@google.com * redistributions in binary form must reproduce the above copyright
1012837Sgabeblack@google.com * notice, this list of conditions and the following disclaimer in the
1112837Sgabeblack@google.com * documentation and/or other materials provided with the distribution;
1212837Sgabeblack@google.com * neither the name of the copyright holders nor the names of its
1312837Sgabeblack@google.com * contributors may be used to endorse or promote products derived from
1412837Sgabeblack@google.com * this software without specific prior written permission.
1512837Sgabeblack@google.com *
1612837Sgabeblack@google.com * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1712837Sgabeblack@google.com * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1812837Sgabeblack@google.com * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1912837Sgabeblack@google.com * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2012837Sgabeblack@google.com * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2112837Sgabeblack@google.com * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2212837Sgabeblack@google.com * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2312837Sgabeblack@google.com * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2412837Sgabeblack@google.com * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2512837Sgabeblack@google.com * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2612837Sgabeblack@google.com * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2712837Sgabeblack@google.com *
2812837Sgabeblack@google.com * Authors: Kevin Lim
2912837Sgabeblack@google.com *          Korey Sewell
3012901Sgabeblack@google.com */
3112901Sgabeblack@google.com
3212901Sgabeblack@google.com#include <algorithm>
3312837Sgabeblack@google.com#include <cstring>
3412982Sgabeblack@google.com
3512951Sgabeblack@google.com#include "arch/isa_traits.hh"
3612953Sgabeblack@google.com#include "arch/utility.hh"
3712837Sgabeblack@google.com#include "base/types.hh"
3812951Sgabeblack@google.com#include "config/use_checker.hh"
3912837Sgabeblack@google.com#include "cpu/checker/cpu.hh"
4012952Sgabeblack@google.com#include "cpu/exetrace.hh"
4112952Sgabeblack@google.com#include "cpu/o3/fetch.hh"
4212952Sgabeblack@google.com#include "mem/packet.hh"
4312952Sgabeblack@google.com#include "mem/request.hh"
4412952Sgabeblack@google.com#include "params/DerivO3CPU.hh"
4512952Sgabeblack@google.com#include "sim/byteswap.hh"
4612993Sgabeblack@google.com#include "sim/core.hh"
4712993Sgabeblack@google.com
4812993Sgabeblack@google.com#if FULL_SYSTEM
4912952Sgabeblack@google.com#include "arch/tlb.hh"
5012952Sgabeblack@google.com#include "arch/vtophys.hh"
5112952Sgabeblack@google.com#include "sim/system.hh"
5212952Sgabeblack@google.com#endif // FULL_SYSTEM
5312952Sgabeblack@google.com
5412993Sgabeblack@google.comusing namespace std;
5512993Sgabeblack@google.com
5612993Sgabeblack@google.comtemplate<class Impl>
5712952Sgabeblack@google.comvoid
5812952Sgabeblack@google.comDefaultFetch<Impl>::IcachePort::setPeer(Port *port)
5912952Sgabeblack@google.com{
6012952Sgabeblack@google.com    Port::setPeer(port);
6112952Sgabeblack@google.com
6212993Sgabeblack@google.com    fetch->setIcache();
6312993Sgabeblack@google.com}
6413060Sgabeblack@google.com
6512993Sgabeblack@google.comtemplate<class Impl>
6612952Sgabeblack@google.comTick
6712952Sgabeblack@google.comDefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
6813035Sgabeblack@google.com{
6913035Sgabeblack@google.com    panic("DefaultFetch doesn't expect recvAtomic callback!");
7012952Sgabeblack@google.com    return curTick;
7112952Sgabeblack@google.com}
7212837Sgabeblack@google.com
7312837Sgabeblack@google.comtemplate<class Impl>
7412837Sgabeblack@google.comvoid
7513091Sgabeblack@google.comDefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
7612951Sgabeblack@google.com{
7712951Sgabeblack@google.com    DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
7812837Sgabeblack@google.com            "functional call.");
7913091Sgabeblack@google.com}
8012951Sgabeblack@google.com
8112951Sgabeblack@google.comtemplate<class Impl>
8212837Sgabeblack@google.comvoid
8313091Sgabeblack@google.comDefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
8412837Sgabeblack@google.com{
8512982Sgabeblack@google.com    if (status == RangeChange) {
8612837Sgabeblack@google.com        if (!snoopRangeSent) {
8713091Sgabeblack@google.com            snoopRangeSent = true;
8812837Sgabeblack@google.com            sendStatusChange(Port::RangeChange);
8912837Sgabeblack@google.com        }
9012837Sgabeblack@google.com        return;
9112837Sgabeblack@google.com    }
9212837Sgabeblack@google.com
9312837Sgabeblack@google.com    panic("DefaultFetch doesn't expect recvStatusChange callback!");
9412837Sgabeblack@google.com}
9512837Sgabeblack@google.com
9612837Sgabeblack@google.comtemplate<class Impl>
9712837Sgabeblack@google.combool
9812837Sgabeblack@google.comDefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
9912837Sgabeblack@google.com{
10012837Sgabeblack@google.com    DPRINTF(Fetch, "Received timing\n");
10112837Sgabeblack@google.com    if (pkt->isResponse()) {
10212837Sgabeblack@google.com        fetch->processCacheCompletion(pkt);
10312837Sgabeblack@google.com    }
10412837Sgabeblack@google.com    //else Snooped a coherence request, just return
10512837Sgabeblack@google.com    return true;
10612837Sgabeblack@google.com}
10712837Sgabeblack@google.com
10812837Sgabeblack@google.comtemplate<class Impl>
10912837Sgabeblack@google.comvoid
11012837Sgabeblack@google.comDefaultFetch<Impl>::IcachePort::recvRetry()
11112837Sgabeblack@google.com{
11212837Sgabeblack@google.com    fetch->recvRetry();
11312837Sgabeblack@google.com}
11412837Sgabeblack@google.com
11512837Sgabeblack@google.comtemplate<class Impl>
11612837Sgabeblack@google.comDefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
11712837Sgabeblack@google.com    : cpu(_cpu),
11812837Sgabeblack@google.com      branchPred(params),
11912837Sgabeblack@google.com      predecoder(NULL),
12012837Sgabeblack@google.com      decodeToFetchDelay(params->decodeToFetchDelay),
12112837Sgabeblack@google.com      renameToFetchDelay(params->renameToFetchDelay),
12212837Sgabeblack@google.com      iewToFetchDelay(params->iewToFetchDelay),
12312837Sgabeblack@google.com      commitToFetchDelay(params->commitToFetchDelay),
12412837Sgabeblack@google.com      fetchWidth(params->fetchWidth),
12512837Sgabeblack@google.com      cacheBlocked(false),
12612837Sgabeblack@google.com      retryPkt(NULL),
12712837Sgabeblack@google.com      retryTid(InvalidThreadID),
12812837Sgabeblack@google.com      numThreads(params->numThreads),
12912837Sgabeblack@google.com      numFetchingThreads(params->smtNumFetchingThreads),
13012837Sgabeblack@google.com      interruptPending(false),
13112837Sgabeblack@google.com      drainPending(false),
13212837Sgabeblack@google.com      switchedOut(false)
13312837Sgabeblack@google.com{
13412837Sgabeblack@google.com    if (numThreads > Impl::MaxThreads)
13512837Sgabeblack@google.com        fatal("numThreads (%d) is larger than compiled limit (%d),\n"
13612837Sgabeblack@google.com              "\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
13712837Sgabeblack@google.com              numThreads, static_cast<int>(Impl::MaxThreads));
13812837Sgabeblack@google.com
13912837Sgabeblack@google.com    // Set fetch stage's status to inactive.
14012837Sgabeblack@google.com    _status = Inactive;
14112837Sgabeblack@google.com
14212837Sgabeblack@google.com    std::string policy = params->smtFetchPolicy;
14312837Sgabeblack@google.com
14412837Sgabeblack@google.com    // Convert string to lowercase
14512837Sgabeblack@google.com    std::transform(policy.begin(), policy.end(), policy.begin(),
14612837Sgabeblack@google.com                   (int(*)(int)) tolower);
14712837Sgabeblack@google.com
14812837Sgabeblack@google.com    // Figure out fetch policy
14912837Sgabeblack@google.com    if (policy == "singlethread") {
15012837Sgabeblack@google.com        fetchPolicy = SingleThread;
15112837Sgabeblack@google.com        if (numThreads > 1)
15212837Sgabeblack@google.com            panic("Invalid Fetch Policy for a SMT workload.");
15312837Sgabeblack@google.com    } else if (policy == "roundrobin") {
15412837Sgabeblack@google.com        fetchPolicy = RoundRobin;
15513091Sgabeblack@google.com        DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
15613091Sgabeblack@google.com    } else if (policy == "branch") {
15713091Sgabeblack@google.com        fetchPolicy = Branch;
15813091Sgabeblack@google.com        DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
15913091Sgabeblack@google.com    } else if (policy == "iqcount") {
16013091Sgabeblack@google.com        fetchPolicy = IQ;
16113091Sgabeblack@google.com        DPRINTF(Fetch, "Fetch policy set to IQ count\n");
16213091Sgabeblack@google.com    } else if (policy == "lsqcount") {
16313091Sgabeblack@google.com        fetchPolicy = LSQ;
16413091Sgabeblack@google.com        DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
16513091Sgabeblack@google.com    } else {
16613091Sgabeblack@google.com        fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
16713091Sgabeblack@google.com              " RoundRobin,LSQcount,IQcount}\n");
16813091Sgabeblack@google.com    }
16913091Sgabeblack@google.com
17013091Sgabeblack@google.com    // Get the size of an instruction.
17113091Sgabeblack@google.com    instSize = sizeof(TheISA::MachInst);
17213091Sgabeblack@google.com
17313091Sgabeblack@google.com    // Name is finally available, so create the port.
17413091Sgabeblack@google.com    icachePort = new IcachePort(this);
17513091Sgabeblack@google.com
17613091Sgabeblack@google.com    icachePort->snoopRangeSent = false;
17713091Sgabeblack@google.com
17813091Sgabeblack@google.com#if USE_CHECKER
17912837Sgabeblack@google.com    if (cpu->checker) {
18012837Sgabeblack@google.com        cpu->checker->setIcachePort(icachePort);
18112837Sgabeblack@google.com    }
18212837Sgabeblack@google.com#endif
18312837Sgabeblack@google.com}
18412951Sgabeblack@google.com
18512837Sgabeblack@google.comtemplate <class Impl>
18612837Sgabeblack@google.comstd::string
18712837Sgabeblack@google.comDefaultFetch<Impl>::name() const
18812837Sgabeblack@google.com{
18912837Sgabeblack@google.com    return cpu->name() + ".fetch";
19012951Sgabeblack@google.com}
19112837Sgabeblack@google.com
19212837Sgabeblack@google.comtemplate <class Impl>
19312951Sgabeblack@google.comvoid
19413079Sgabeblack@google.comDefaultFetch<Impl>::regStats()
19512951Sgabeblack@google.com{
19612951Sgabeblack@google.com    icacheStallCycles
19712837Sgabeblack@google.com        .name(name() + ".icacheStallCycles")
19812951Sgabeblack@google.com        .desc("Number of cycles fetch is stalled on an Icache miss")
19912951Sgabeblack@google.com        .prereq(icacheStallCycles);
20012951Sgabeblack@google.com
20112951Sgabeblack@google.com    fetchedInsts
20212951Sgabeblack@google.com        .name(name() + ".Insts")
20312928Sgabeblack@google.com        .desc("Number of instructions fetch has processed")
20412837Sgabeblack@google.com        .prereq(fetchedInsts);
20512837Sgabeblack@google.com
20612837Sgabeblack@google.com    fetchedBranches
20712837Sgabeblack@google.com        .name(name() + ".Branches")
20812837Sgabeblack@google.com        .desc("Number of branches that fetch encountered")
20912837Sgabeblack@google.com        .prereq(fetchedBranches);
21012837Sgabeblack@google.com
21112837Sgabeblack@google.com    predictedBranches
21212837Sgabeblack@google.com        .name(name() + ".predictedBranches")
21312837Sgabeblack@google.com        .desc("Number of branches that fetch has predicted taken")
21412837Sgabeblack@google.com        .prereq(predictedBranches);
21512837Sgabeblack@google.com
21612837Sgabeblack@google.com    fetchCycles
21712837Sgabeblack@google.com        .name(name() + ".Cycles")
21812837Sgabeblack@google.com        .desc("Number of cycles fetch has run and was not squashing or"
21912837Sgabeblack@google.com              " blocked")
22012837Sgabeblack@google.com        .prereq(fetchCycles);
22112837Sgabeblack@google.com
22212837Sgabeblack@google.com    fetchSquashCycles
22312837Sgabeblack@google.com        .name(name() + ".SquashCycles")
22412837Sgabeblack@google.com        .desc("Number of cycles fetch has spent squashing")
22512837Sgabeblack@google.com        .prereq(fetchSquashCycles);
22612837Sgabeblack@google.com
22712837Sgabeblack@google.com    fetchIdleCycles
22812837Sgabeblack@google.com        .name(name() + ".IdleCycles")
22912837Sgabeblack@google.com        .desc("Number of cycles fetch was idle")
23012837Sgabeblack@google.com        .prereq(fetchIdleCycles);
23112837Sgabeblack@google.com
23212837Sgabeblack@google.com    fetchBlockedCycles
23312837Sgabeblack@google.com        .name(name() + ".BlockedCycles")
23412837Sgabeblack@google.com        .desc("Number of cycles fetch has spent blocked")
23512837Sgabeblack@google.com        .prereq(fetchBlockedCycles);
23612837Sgabeblack@google.com
23712837Sgabeblack@google.com    fetchedCacheLines
23812837Sgabeblack@google.com        .name(name() + ".CacheLines")
23912837Sgabeblack@google.com        .desc("Number of cache lines fetched")
24012837Sgabeblack@google.com        .prereq(fetchedCacheLines);
24112837Sgabeblack@google.com
24212837Sgabeblack@google.com    fetchMiscStallCycles
24312837Sgabeblack@google.com        .name(name() + ".MiscStallCycles")
24412837Sgabeblack@google.com        .desc("Number of cycles fetch has spent waiting on interrupts, or "
24512837Sgabeblack@google.com              "bad addresses, or out of MSHRs")
24612837Sgabeblack@google.com        .prereq(fetchMiscStallCycles);
24712837Sgabeblack@google.com
24812837Sgabeblack@google.com    fetchIcacheSquashes
24912837Sgabeblack@google.com        .name(name() + ".IcacheSquashes")
25012837Sgabeblack@google.com        .desc("Number of outstanding Icache misses that were squashed")
25112837Sgabeblack@google.com        .prereq(fetchIcacheSquashes);
25212837Sgabeblack@google.com
25312837Sgabeblack@google.com    fetchNisnDist
25412837Sgabeblack@google.com        .init(/* base value */ 0,
25512837Sgabeblack@google.com              /* last value */ fetchWidth,
25612837Sgabeblack@google.com              /* bucket size */ 1)
25712953Sgabeblack@google.com        .name(name() + ".rateDist")
25812837Sgabeblack@google.com        .desc("Number of instructions fetched each cycle (Total)")
25912837Sgabeblack@google.com        .flags(Stats::pdf);
26012837Sgabeblack@google.com
26112953Sgabeblack@google.com    idleRate
26212837Sgabeblack@google.com        .name(name() + ".idleRate")
26312953Sgabeblack@google.com        .desc("Percent of cycles fetch was idle")
26412837Sgabeblack@google.com        .prereq(idleRate);
26512837Sgabeblack@google.com    idleRate = fetchIdleCycles * 100 / cpu->numCycles;
26612837Sgabeblack@google.com
26712951Sgabeblack@google.com    branchRate
26812951Sgabeblack@google.com        .name(name() + ".branchRate")
26912837Sgabeblack@google.com        .desc("Number of branch fetches per cycle")
27012951Sgabeblack@google.com        .flags(Stats::total);
27112837Sgabeblack@google.com    branchRate = fetchedBranches / cpu->numCycles;
27212951Sgabeblack@google.com
27312837Sgabeblack@google.com    fetchRate
27412837Sgabeblack@google.com        .name(name() + ".rate")
27512837Sgabeblack@google.com        .desc("Number of inst fetches per cycle")
27612951Sgabeblack@google.com        .flags(Stats::total);
27712837Sgabeblack@google.com    fetchRate = fetchedInsts / cpu->numCycles;
27812951Sgabeblack@google.com
27912837Sgabeblack@google.com    branchPred.regStats();
28012837Sgabeblack@google.com}
28112837Sgabeblack@google.com
28212951Sgabeblack@google.comtemplate<class Impl>
28312837Sgabeblack@google.comvoid
28412951Sgabeblack@google.comDefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
28512837Sgabeblack@google.com{
28612837Sgabeblack@google.com    timeBuffer = time_buffer;
28712837Sgabeblack@google.com
28812951Sgabeblack@google.com    // Create wires to get information from proper places in time buffer.
28912837Sgabeblack@google.com    fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
29012951Sgabeblack@google.com    fromRename = timeBuffer->getWire(-renameToFetchDelay);
29112837Sgabeblack@google.com    fromIEW = timeBuffer->getWire(-iewToFetchDelay);
29212837Sgabeblack@google.com    fromCommit = timeBuffer->getWire(-commitToFetchDelay);
29312837Sgabeblack@google.com}
29412951Sgabeblack@google.com
29512837Sgabeblack@google.comtemplate<class Impl>
29612951Sgabeblack@google.comvoid
29712837Sgabeblack@google.comDefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
29812837Sgabeblack@google.com{
29912837Sgabeblack@google.com    activeThreads = at_ptr;
30012951Sgabeblack@google.com}
30112837Sgabeblack@google.com
30212951Sgabeblack@google.comtemplate<class Impl>
30312837Sgabeblack@google.comvoid
30412837Sgabeblack@google.comDefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
30512837Sgabeblack@google.com{
30612951Sgabeblack@google.com    fetchQueue = fq_ptr;
30712837Sgabeblack@google.com
30812951Sgabeblack@google.com    // Create wire to write information to proper place in fetch queue.
30912837Sgabeblack@google.com    toDecode = fetchQueue->getWire(0);
31012837Sgabeblack@google.com}
31112837Sgabeblack@google.com
31212951Sgabeblack@google.comtemplate<class Impl>
31312837Sgabeblack@google.comvoid
31412951Sgabeblack@google.comDefaultFetch<Impl>::initStage()
31512837Sgabeblack@google.com{
31612837Sgabeblack@google.com    // Setup PC and nextPC with initial state.
31712837Sgabeblack@google.com    for (ThreadID tid = 0; tid < numThreads; tid++) {
31812951Sgabeblack@google.com        PC[tid] = cpu->readPC(tid);
31912837Sgabeblack@google.com        nextPC[tid] = cpu->readNextPC(tid);
32012951Sgabeblack@google.com        microPC[tid] = cpu->readMicroPC(tid);
32112837Sgabeblack@google.com    }
32212837Sgabeblack@google.com
32312837Sgabeblack@google.com    for (ThreadID tid = 0; tid < numThreads; tid++) {
32412951Sgabeblack@google.com
32512837Sgabeblack@google.com        fetchStatus[tid] = Running;
32612951Sgabeblack@google.com
32712837Sgabeblack@google.com        priorityList.push_back(tid);
32812837Sgabeblack@google.com
32912837Sgabeblack@google.com        memReq[tid] = NULL;
33012951Sgabeblack@google.com
33112837Sgabeblack@google.com        stalls[tid].decode = false;
33212951Sgabeblack@google.com        stalls[tid].rename = false;
33312837Sgabeblack@google.com        stalls[tid].iew = false;
33412837Sgabeblack@google.com        stalls[tid].commit = false;
33512837Sgabeblack@google.com    }
33612929Sgabeblack@google.com
33712929Sgabeblack@google.com    // Schedule fetch to get the correct PC from the CPU
33812929Sgabeblack@google.com    // scheduleFetchStartupEvent(1);
33912929Sgabeblack@google.com
34012929Sgabeblack@google.com    // Fetch needs to start fetching instructions at the very beginning,
34112929Sgabeblack@google.com    // so it must start up in active state.
34212929Sgabeblack@google.com    switchToActive();
34312929Sgabeblack@google.com}
34412837Sgabeblack@google.com
34512837Sgabeblack@google.comtemplate<class Impl>
34612837Sgabeblack@google.comvoid
34712951Sgabeblack@google.comDefaultFetch<Impl>::setIcache()
34812837Sgabeblack@google.com{
34912837Sgabeblack@google.com    // Size of cache block.
35012837Sgabeblack@google.com    cacheBlkSize = icachePort->peerBlockSize();
35112951Sgabeblack@google.com
35212837Sgabeblack@google.com    // Create mask to get rid of offset bits.
35312951Sgabeblack@google.com    cacheBlkMask = (cacheBlkSize - 1);
35412837Sgabeblack@google.com
35512837Sgabeblack@google.com    for (ThreadID tid = 0; tid < numThreads; tid++) {
35612837Sgabeblack@google.com        // Create space to store a cache line.
35712951Sgabeblack@google.com        cacheData[tid] = new uint8_t[cacheBlkSize];
35812837Sgabeblack@google.com        cacheDataPC[tid] = 0;
35912951Sgabeblack@google.com        cacheDataValid[tid] = false;
36012837Sgabeblack@google.com    }
36112837Sgabeblack@google.com}
36212837Sgabeblack@google.com
36312951Sgabeblack@google.comtemplate<class Impl>
36412837Sgabeblack@google.comvoid
36512951Sgabeblack@google.comDefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
36612837Sgabeblack@google.com{
36712837Sgabeblack@google.com    ThreadID tid = pkt->req->threadId();
36812837Sgabeblack@google.com
36912951Sgabeblack@google.com    DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
37012837Sgabeblack@google.com
37112951Sgabeblack@google.com    assert(!pkt->wasNacked());
37212837Sgabeblack@google.com
37312837Sgabeblack@google.com    // Only change the status if it's still waiting on the icache access
37412837Sgabeblack@google.com    // to return.
37512951Sgabeblack@google.com    if (fetchStatus[tid] != IcacheWaitResponse ||
37612837Sgabeblack@google.com        pkt->req != memReq[tid] ||
37712951Sgabeblack@google.com        isSwitchedOut()) {
37812837Sgabeblack@google.com        ++fetchIcacheSquashes;
37912837Sgabeblack@google.com        delete pkt->req;
38012837Sgabeblack@google.com        delete pkt;
38112951Sgabeblack@google.com        return;
38212837Sgabeblack@google.com    }
38312951Sgabeblack@google.com
38412837Sgabeblack@google.com    memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
38512837Sgabeblack@google.com    cacheDataValid[tid] = true;
38612837Sgabeblack@google.com
38712951Sgabeblack@google.com    if (!drainPending) {
38812837Sgabeblack@google.com        // Wake up the CPU (if it went to sleep and was waiting on
38912951Sgabeblack@google.com        // this completion event).
39012837Sgabeblack@google.com        cpu->wakeCPU();
39112837Sgabeblack@google.com
39212837Sgabeblack@google.com        DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
39312951Sgabeblack@google.com                tid);
39412837Sgabeblack@google.com
39512951Sgabeblack@google.com        switchToActive();
39612837Sgabeblack@google.com    }
39712837Sgabeblack@google.com
39812837Sgabeblack@google.com    // Only switch to IcacheAccessComplete if we're not stalled as well.
39912951Sgabeblack@google.com    if (checkStall(tid)) {
40012837Sgabeblack@google.com        fetchStatus[tid] = Blocked;
40112951Sgabeblack@google.com    } else {
40212837Sgabeblack@google.com        fetchStatus[tid] = IcacheAccessComplete;
40312837Sgabeblack@google.com    }
40412837Sgabeblack@google.com
40512951Sgabeblack@google.com    // Reset the mem req to NULL.
40612837Sgabeblack@google.com    delete pkt->req;
40712951Sgabeblack@google.com    delete pkt;
40812837Sgabeblack@google.com    memReq[tid] = NULL;
40912837Sgabeblack@google.com}
41012837Sgabeblack@google.com
41112951Sgabeblack@google.comtemplate <class Impl>
41212837Sgabeblack@google.combool
41312951Sgabeblack@google.comDefaultFetch<Impl>::drain()
41412837Sgabeblack@google.com{
41512837Sgabeblack@google.com    // Fetch is ready to drain at any time.
41612837Sgabeblack@google.com    cpu->signalDrained();
41712951Sgabeblack@google.com    drainPending = true;
41812837Sgabeblack@google.com    return true;
41912951Sgabeblack@google.com}
42012837Sgabeblack@google.com
42112837Sgabeblack@google.comtemplate <class Impl>
42212837Sgabeblack@google.comvoid
42312837Sgabeblack@google.comDefaultFetch<Impl>::resume()
42412909Sgabeblack@google.com{
42512909Sgabeblack@google.com    drainPending = false;
42612951Sgabeblack@google.com}
42712909Sgabeblack@google.com
42812909Sgabeblack@google.comtemplate <class Impl>
42912914Sgabeblack@google.comvoid
43012951Sgabeblack@google.comDefaultFetch<Impl>::switchOut()
43112914Sgabeblack@google.com{
43212951Sgabeblack@google.com    switchedOut = true;
43312914Sgabeblack@google.com    // Branch predictor needs to have its state cleared.
43412914Sgabeblack@google.com    branchPred.switchOut();
43512914Sgabeblack@google.com}
43612951Sgabeblack@google.com
43712914Sgabeblack@google.comtemplate <class Impl>
43812951Sgabeblack@google.comvoid
43912914Sgabeblack@google.comDefaultFetch<Impl>::takeOverFrom()
44012914Sgabeblack@google.com{
44112914Sgabeblack@google.com    // Reset all state
44212951Sgabeblack@google.com    for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
44312914Sgabeblack@google.com        stalls[i].decode = 0;
44412951Sgabeblack@google.com        stalls[i].rename = 0;
44512914Sgabeblack@google.com        stalls[i].iew = 0;
44612914Sgabeblack@google.com        stalls[i].commit = 0;
44712914Sgabeblack@google.com        PC[i] = cpu->readPC(i);
44812951Sgabeblack@google.com        nextPC[i] = cpu->readNextPC(i);
44912914Sgabeblack@google.com        microPC[i] = cpu->readMicroPC(i);
45012951Sgabeblack@google.com        fetchStatus[i] = Running;
45112914Sgabeblack@google.com    }
45212914Sgabeblack@google.com    numInst = 0;
45312909Sgabeblack@google.com    wroteToTimeBuffer = false;
45412909Sgabeblack@google.com    _status = Inactive;
45512837Sgabeblack@google.com    switchedOut = false;
45612837Sgabeblack@google.com    interruptPending = false;
45712958Sgabeblack@google.com    branchPred.takeOverFrom();
45812958Sgabeblack@google.com}
45912837Sgabeblack@google.com
46012837Sgabeblack@google.comtemplate <class Impl>
46112837Sgabeblack@google.comvoid
46212958Sgabeblack@google.comDefaultFetch<Impl>::wakeFromQuiesce()
46312837Sgabeblack@google.com{
46412958Sgabeblack@google.com    DPRINTF(Fetch, "Waking up from quiesce\n");
46512958Sgabeblack@google.com    // Hopefully this is safe
46612837Sgabeblack@google.com    // @todo: Allow other threads to wake from quiesce.
46712837Sgabeblack@google.com    fetchStatus[0] = Running;
46812837Sgabeblack@google.com}
46912958Sgabeblack@google.com
47012837Sgabeblack@google.comtemplate <class Impl>
47112958Sgabeblack@google.cominline void
47212958Sgabeblack@google.comDefaultFetch<Impl>::switchToActive()
47312837Sgabeblack@google.com{
47412837Sgabeblack@google.com    if (_status == Inactive) {
47512837Sgabeblack@google.com        DPRINTF(Activity, "Activating stage.\n");
47612958Sgabeblack@google.com
47712837Sgabeblack@google.com        cpu->activateStage(O3CPU::FetchIdx);
47812958Sgabeblack@google.com
47912958Sgabeblack@google.com        _status = Active;
48012837Sgabeblack@google.com    }
48112837Sgabeblack@google.com}
48212837Sgabeblack@google.com
48312958Sgabeblack@google.comtemplate <class Impl>
48412837Sgabeblack@google.cominline void
48512958Sgabeblack@google.comDefaultFetch<Impl>::switchToInactive()
48612958Sgabeblack@google.com{
48712837Sgabeblack@google.com    if (_status == Active) {
48812837Sgabeblack@google.com        DPRINTF(Activity, "Deactivating stage.\n");
48912837Sgabeblack@google.com
49012951Sgabeblack@google.com        cpu->deactivateStage(O3CPU::FetchIdx);
49112837Sgabeblack@google.com
49212951Sgabeblack@google.com        _status = Inactive;
49312837Sgabeblack@google.com    }
49412837Sgabeblack@google.com}
49512837Sgabeblack@google.com
49612958Sgabeblack@google.comtemplate <class Impl>
49712837Sgabeblack@google.combool
49812958Sgabeblack@google.comDefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC,
49912958Sgabeblack@google.com                                          Addr &next_NPC, Addr &next_MicroPC)
50012837Sgabeblack@google.com{
50112837Sgabeblack@google.com    // Do branch prediction check here.
50212837Sgabeblack@google.com    // A bit of a misnomer...next_PC is actually the current PC until
50312951Sgabeblack@google.com    // this function updates it.
50412837Sgabeblack@google.com    bool predict_taken;
50512951Sgabeblack@google.com
50612837Sgabeblack@google.com    if (!inst->isControl()) {
50712837Sgabeblack@google.com        if (inst->isMicroop() && !inst->isLastMicroop()) {
50812837Sgabeblack@google.com            next_MicroPC++;
50912958Sgabeblack@google.com        } else {
51012837Sgabeblack@google.com            next_PC  = next_NPC;
51112958Sgabeblack@google.com            next_NPC = next_NPC + instSize;
51212958Sgabeblack@google.com            next_MicroPC = 0;
51312958Sgabeblack@google.com        }
51412837Sgabeblack@google.com        inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
51512837Sgabeblack@google.com        inst->setPredTaken(false);
51612837Sgabeblack@google.com        return false;
51712951Sgabeblack@google.com    }
51812837Sgabeblack@google.com
51912951Sgabeblack@google.com    //Assume for now that all control flow is to a different macroop which
52012837Sgabeblack@google.com    //would reset the micro pc to 0.
52112837Sgabeblack@google.com    next_MicroPC = 0;
52212837Sgabeblack@google.com
52312958Sgabeblack@google.com    ThreadID tid = inst->threadNumber;
52412837Sgabeblack@google.com    Addr pred_PC = next_PC;
52512958Sgabeblack@google.com    predict_taken = branchPred.predict(inst, pred_PC, tid);
52612958Sgabeblack@google.com
52712958Sgabeblack@google.com    if (predict_taken) {
52812837Sgabeblack@google.com        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:  Branch predicted to be taken to %#x.\n",
52912837Sgabeblack@google.com                tid, inst->seqNum, pred_PC);
53012837Sgabeblack@google.com    } else {
53112951Sgabeblack@google.com        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
53212837Sgabeblack@google.com                tid, inst->seqNum);
53312951Sgabeblack@google.com    }
53412837Sgabeblack@google.com
53512837Sgabeblack@google.com#if ISA_HAS_DELAY_SLOT
53612929Sgabeblack@google.com    next_PC = next_NPC;
53712929Sgabeblack@google.com    if (predict_taken)
53812929Sgabeblack@google.com        next_NPC = pred_PC;
53912929Sgabeblack@google.com    else
54012929Sgabeblack@google.com        next_NPC += instSize;
54112929Sgabeblack@google.com#else
54212929Sgabeblack@google.com    if (predict_taken)
54312837Sgabeblack@google.com        next_PC = pred_PC;
54412837Sgabeblack@google.com    else
54512837Sgabeblack@google.com        next_PC += instSize;
54612837Sgabeblack@google.com    next_NPC = next_PC + instSize;
54712958Sgabeblack@google.com#endif
54812958Sgabeblack@google.com
54912958Sgabeblack@google.com    DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %#x and then %#x.\n",
55012837Sgabeblack@google.com            tid, inst->seqNum, next_PC, next_NPC);
55112837Sgabeblack@google.com    inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
55212837Sgabeblack@google.com    inst->setPredTaken(predict_taken);
55312958Sgabeblack@google.com
55412837Sgabeblack@google.com    ++fetchedBranches;
55512958Sgabeblack@google.com
55612958Sgabeblack@google.com    if (predict_taken) {
55712837Sgabeblack@google.com        ++predictedBranches;
55812837Sgabeblack@google.com    }
55912837Sgabeblack@google.com
56012958Sgabeblack@google.com    return predict_taken;
56112837Sgabeblack@google.com}
56212958Sgabeblack@google.com
56312958Sgabeblack@google.comtemplate <class Impl>
56412958Sgabeblack@google.combool
56512837Sgabeblack@google.comDefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, ThreadID tid)
56612837Sgabeblack@google.com{
56712837Sgabeblack@google.com    Fault fault = NoFault;
56812958Sgabeblack@google.com
56912837Sgabeblack@google.com    //AlphaDep
57012958Sgabeblack@google.com    if (cacheBlocked) {
57112958Sgabeblack@google.com        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
57212958Sgabeblack@google.com                tid);
57312837Sgabeblack@google.com        return false;
57412837Sgabeblack@google.com    } else if (isSwitchedOut()) {
57512837Sgabeblack@google.com        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
57612958Sgabeblack@google.com                tid);
57712837Sgabeblack@google.com        return false;
57812958Sgabeblack@google.com    } else if (interruptPending && !(fetch_PC & 0x3)) {
57912958Sgabeblack@google.com        // Hold off fetch from getting new instructions when:
58012958Sgabeblack@google.com        // Cache is blocked, or
58112837Sgabeblack@google.com        // while an interrupt is pending and we're not in PAL mode, or
58212837Sgabeblack@google.com        // fetch is switched out.
58312837Sgabeblack@google.com        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
58412958Sgabeblack@google.com                tid);
58512837Sgabeblack@google.com        return false;
58612958Sgabeblack@google.com    }
58712958Sgabeblack@google.com
58812958Sgabeblack@google.com    // Align the fetch PC so it's at the start of a cache block.
58912837Sgabeblack@google.com    Addr block_PC = icacheBlockAlignPC(fetch_PC);
59012837Sgabeblack@google.com
59112837Sgabeblack@google.com    // If we've already got the block, no need to try to fetch it again.
59212951Sgabeblack@google.com    if (cacheDataValid[tid] && block_PC == cacheDataPC[tid]) {
59312837Sgabeblack@google.com        return true;
59412951Sgabeblack@google.com    }
59512837Sgabeblack@google.com
59612837Sgabeblack@google.com    // Setup the memReq to do a read of the first instruction's address.
59712837Sgabeblack@google.com    // Set the appropriate read size and flags as well.
59812958Sgabeblack@google.com    // Build request here.
59912837Sgabeblack@google.com    RequestPtr mem_req =
60012958Sgabeblack@google.com        new Request(tid, block_PC, cacheBlkSize, Request::INST_FETCH,
60112958Sgabeblack@google.com                    fetch_PC, cpu->thread[tid]->contextId(), tid);
60212958Sgabeblack@google.com
60312837Sgabeblack@google.com    memReq[tid] = mem_req;
60412837Sgabeblack@google.com
60512837Sgabeblack@google.com    // Translate the instruction request.
60612951Sgabeblack@google.com    fault = cpu->itb->translateAtomic(mem_req, cpu->thread[tid]->getTC(),
60712837Sgabeblack@google.com                                      BaseTLB::Execute);
60812951Sgabeblack@google.com
60912837Sgabeblack@google.com    // In the case of faults, the fetch stage may need to stall and wait
61012837Sgabeblack@google.com    // for the ITB miss to be handled.
61112837Sgabeblack@google.com
61212958Sgabeblack@google.com    // If translation was successful, attempt to read the first
61312837Sgabeblack@google.com    // instruction.
61412958Sgabeblack@google.com    if (fault == NoFault) {
61512958Sgabeblack@google.com#if 0
61612958Sgabeblack@google.com        if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
61712958Sgabeblack@google.com            memReq[tid]->isUncacheable()) {
61812837Sgabeblack@google.com            DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
61912837Sgabeblack@google.com                    "misspeculating path)!",
62012837Sgabeblack@google.com                    memReq[tid]->paddr);
62112951Sgabeblack@google.com            ret_fault = TheISA::genMachineCheckFault();
62212837Sgabeblack@google.com            return false;
62312951Sgabeblack@google.com        }
62412837Sgabeblack@google.com#endif
62512837Sgabeblack@google.com
62612837Sgabeblack@google.com        // Build packet here.
62712958Sgabeblack@google.com        PacketPtr data_pkt = new Packet(mem_req,
62812837Sgabeblack@google.com                                        MemCmd::ReadReq, Packet::Broadcast);
62912958Sgabeblack@google.com        data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
63012958Sgabeblack@google.com
63112958Sgabeblack@google.com        cacheDataPC[tid] = block_PC;
63212958Sgabeblack@google.com        cacheDataValid[tid] = false;
63312837Sgabeblack@google.com
63412837Sgabeblack@google.com        DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
63512837Sgabeblack@google.com
63612951Sgabeblack@google.com        fetchedCacheLines++;
63712837Sgabeblack@google.com
63812951Sgabeblack@google.com        // Now do the timing access to see whether or not the instruction
63912837Sgabeblack@google.com        // exists within the cache.
64012837Sgabeblack@google.com        if (!icachePort->sendTiming(data_pkt)) {
64112909Sgabeblack@google.com            assert(retryPkt == NULL);
64212909Sgabeblack@google.com            assert(retryTid == InvalidThreadID);
64312909Sgabeblack@google.com            DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
64412909Sgabeblack@google.com            fetchStatus[tid] = IcacheWaitRetry;
64512909Sgabeblack@google.com            retryPkt = data_pkt;
64612909Sgabeblack@google.com            retryTid = tid;
64712914Sgabeblack@google.com            cacheBlocked = true;
64812914Sgabeblack@google.com            return false;
64912914Sgabeblack@google.com        }
65012914Sgabeblack@google.com
65112914Sgabeblack@google.com        DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
65212914Sgabeblack@google.com
65312914Sgabeblack@google.com        lastIcacheStall[tid] = curTick;
65412914Sgabeblack@google.com
65512914Sgabeblack@google.com        DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
65612914Sgabeblack@google.com                "response.\n", tid);
65712914Sgabeblack@google.com
65812914Sgabeblack@google.com        fetchStatus[tid] = IcacheWaitResponse;
65912914Sgabeblack@google.com    } else {
66012914Sgabeblack@google.com        delete mem_req;
66112914Sgabeblack@google.com        memReq[tid] = NULL;
66212914Sgabeblack@google.com    }
66312914Sgabeblack@google.com
66412914Sgabeblack@google.com    ret_fault = fault;
66512914Sgabeblack@google.com    return true;
66612914Sgabeblack@google.com}
66712914Sgabeblack@google.com
66812914Sgabeblack@google.comtemplate <class Impl>
66912914Sgabeblack@google.cominline void
67012914Sgabeblack@google.comDefaultFetch<Impl>::doSquash(const Addr &new_PC,
67112837Sgabeblack@google.com        const Addr &new_NPC, const Addr &new_microPC, ThreadID tid)
67213035Sgabeblack@google.com{
67312837Sgabeblack@google.com    DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x, NPC to: %#x.\n",
67413035Sgabeblack@google.com            tid, new_PC, new_NPC);
67513035Sgabeblack@google.com
67613035Sgabeblack@google.com    PC[tid] = new_PC;
67712837Sgabeblack@google.com    nextPC[tid] = new_NPC;
67812837Sgabeblack@google.com    microPC[tid] = new_microPC;
67912837Sgabeblack@google.com
68012930Sgabeblack@google.com    // Clear the icache miss if it's outstanding.
68112930Sgabeblack@google.com    if (fetchStatus[tid] == IcacheWaitResponse) {
68212930Sgabeblack@google.com        DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
68312930Sgabeblack@google.com                tid);
68412930Sgabeblack@google.com        memReq[tid] = NULL;
68512930Sgabeblack@google.com    }
68612930Sgabeblack@google.com
68712837Sgabeblack@google.com    // Get rid of the retrying packet if it was from this thread.
68812837Sgabeblack@google.com    if (retryTid == tid) {
68912982Sgabeblack@google.com        assert(cacheBlocked);
69012837Sgabeblack@google.com        if (retryPkt) {
69112837Sgabeblack@google.com            delete retryPkt->req;
69212837Sgabeblack@google.com            delete retryPkt;
69312837Sgabeblack@google.com        }
69412837Sgabeblack@google.com        retryPkt = NULL;
69512982Sgabeblack@google.com        retryTid = InvalidThreadID;
69612837Sgabeblack@google.com    }
69712837Sgabeblack@google.com
69812901Sgabeblack@google.com    fetchStatus[tid] = Squashing;
69912901Sgabeblack@google.com
70012901Sgabeblack@google.com    ++fetchSquashCycles;
70112901Sgabeblack@google.com}
70212901Sgabeblack@google.com
70312901Sgabeblack@google.comtemplate<class Impl>
70412901Sgabeblack@google.comvoid
70512901Sgabeblack@google.comDefaultFetch<Impl>::squashFromDecode(const Addr &new_PC, const Addr &new_NPC,
70612837Sgabeblack@google.com                                     const Addr &new_MicroPC,
707                                     const InstSeqNum &seq_num, ThreadID tid)
708{
709    DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
710
711    doSquash(new_PC, new_NPC, new_MicroPC, tid);
712
713    // Tell the CPU to remove any instructions that are in flight between
714    // fetch and decode.
715    cpu->removeInstsUntil(seq_num, tid);
716}
717
718template<class Impl>
719bool
720DefaultFetch<Impl>::checkStall(ThreadID tid) const
721{
722    bool ret_val = false;
723
724    if (cpu->contextSwitch) {
725        DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
726        ret_val = true;
727    } else if (stalls[tid].decode) {
728        DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
729        ret_val = true;
730    } else if (stalls[tid].rename) {
731        DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
732        ret_val = true;
733    } else if (stalls[tid].iew) {
734        DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
735        ret_val = true;
736    } else if (stalls[tid].commit) {
737        DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
738        ret_val = true;
739    }
740
741    return ret_val;
742}
743
744template<class Impl>
745typename DefaultFetch<Impl>::FetchStatus
746DefaultFetch<Impl>::updateFetchStatus()
747{
748    //Check Running
749    list<ThreadID>::iterator threads = activeThreads->begin();
750    list<ThreadID>::iterator end = activeThreads->end();
751
752    while (threads != end) {
753        ThreadID tid = *threads++;
754
755        if (fetchStatus[tid] == Running ||
756            fetchStatus[tid] == Squashing ||
757            fetchStatus[tid] == IcacheAccessComplete) {
758
759            if (_status == Inactive) {
760                DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
761
762                if (fetchStatus[tid] == IcacheAccessComplete) {
763                    DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
764                            "completion\n",tid);
765                }
766
767                cpu->activateStage(O3CPU::FetchIdx);
768            }
769
770            return Active;
771        }
772    }
773
774    // Stage is switching from active to inactive, notify CPU of it.
775    if (_status == Active) {
776        DPRINTF(Activity, "Deactivating stage.\n");
777
778        cpu->deactivateStage(O3CPU::FetchIdx);
779    }
780
781    return Inactive;
782}
783
784template <class Impl>
785void
786DefaultFetch<Impl>::squash(const Addr &new_PC, const Addr &new_NPC,
787                           const Addr &new_MicroPC,
788                           const InstSeqNum &seq_num, ThreadID tid)
789{
790    DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
791
792    doSquash(new_PC, new_NPC, new_MicroPC, tid);
793
794    // Tell the CPU to remove any instructions that are not in the ROB.
795    cpu->removeInstsNotInROB(tid);
796}
797
798template <class Impl>
799void
800DefaultFetch<Impl>::tick()
801{
802    list<ThreadID>::iterator threads = activeThreads->begin();
803    list<ThreadID>::iterator end = activeThreads->end();
804    bool status_change = false;
805
806    wroteToTimeBuffer = false;
807
808    while (threads != end) {
809        ThreadID tid = *threads++;
810
811        // Check the signals for each thread to determine the proper status
812        // for each thread.
813        bool updated_status = checkSignalsAndUpdate(tid);
814        status_change =  status_change || updated_status;
815    }
816
817    DPRINTF(Fetch, "Running stage.\n");
818
819    // Reset the number of the instruction we're fetching.
820    numInst = 0;
821
822#if FULL_SYSTEM
823    if (fromCommit->commitInfo[0].interruptPending) {
824        interruptPending = true;
825    }
826
827    if (fromCommit->commitInfo[0].clearInterrupt) {
828        interruptPending = false;
829    }
830#endif
831
832    for (threadFetched = 0; threadFetched < numFetchingThreads;
833         threadFetched++) {
834        // Fetch each of the actively fetching threads.
835        fetch(status_change);
836    }
837
838    // Record number of instructions fetched this cycle for distribution.
839    fetchNisnDist.sample(numInst);
840
841    if (status_change) {
842        // Change the fetch stage status if there was a status change.
843        _status = updateFetchStatus();
844    }
845
846    // If there was activity this cycle, inform the CPU of it.
847    if (wroteToTimeBuffer || cpu->contextSwitch) {
848        DPRINTF(Activity, "Activity this cycle.\n");
849
850        cpu->activityThisCycle();
851    }
852}
853
854template <class Impl>
855bool
856DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
857{
858    // Update the per thread stall statuses.
859    if (fromDecode->decodeBlock[tid]) {
860        stalls[tid].decode = true;
861    }
862
863    if (fromDecode->decodeUnblock[tid]) {
864        assert(stalls[tid].decode);
865        assert(!fromDecode->decodeBlock[tid]);
866        stalls[tid].decode = false;
867    }
868
869    if (fromRename->renameBlock[tid]) {
870        stalls[tid].rename = true;
871    }
872
873    if (fromRename->renameUnblock[tid]) {
874        assert(stalls[tid].rename);
875        assert(!fromRename->renameBlock[tid]);
876        stalls[tid].rename = false;
877    }
878
879    if (fromIEW->iewBlock[tid]) {
880        stalls[tid].iew = true;
881    }
882
883    if (fromIEW->iewUnblock[tid]) {
884        assert(stalls[tid].iew);
885        assert(!fromIEW->iewBlock[tid]);
886        stalls[tid].iew = false;
887    }
888
889    if (fromCommit->commitBlock[tid]) {
890        stalls[tid].commit = true;
891    }
892
893    if (fromCommit->commitUnblock[tid]) {
894        assert(stalls[tid].commit);
895        assert(!fromCommit->commitBlock[tid]);
896        stalls[tid].commit = false;
897    }
898
899    // Check squash signals from commit.
900    if (fromCommit->commitInfo[tid].squash) {
901
902        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
903                "from commit.\n",tid);
904        // In any case, squash.
905        squash(fromCommit->commitInfo[tid].nextPC,
906               fromCommit->commitInfo[tid].nextNPC,
907               fromCommit->commitInfo[tid].nextMicroPC,
908               fromCommit->commitInfo[tid].doneSeqNum,
909               tid);
910
911        // Also check if there's a mispredict that happened.
912        if (fromCommit->commitInfo[tid].branchMispredict) {
913            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
914                              fromCommit->commitInfo[tid].nextPC,
915                              fromCommit->commitInfo[tid].branchTaken,
916                              tid);
917        } else {
918            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
919                              tid);
920        }
921
922        return true;
923    } else if (fromCommit->commitInfo[tid].doneSeqNum) {
924        // Update the branch predictor if it wasn't a squashed instruction
925        // that was broadcasted.
926        branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
927    }
928
929    // Check ROB squash signals from commit.
930    if (fromCommit->commitInfo[tid].robSquashing) {
931        DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
932
933        // Continue to squash.
934        fetchStatus[tid] = Squashing;
935
936        return true;
937    }
938
939    // Check squash signals from decode.
940    if (fromDecode->decodeInfo[tid].squash) {
941        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
942                "from decode.\n",tid);
943
944        // Update the branch predictor.
945        if (fromDecode->decodeInfo[tid].branchMispredict) {
946            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
947                              fromDecode->decodeInfo[tid].nextPC,
948                              fromDecode->decodeInfo[tid].branchTaken,
949                              tid);
950        } else {
951            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
952                              tid);
953        }
954
955        if (fetchStatus[tid] != Squashing) {
956
957            DPRINTF(Fetch, "Squashing from decode with PC = %#x, NPC = %#x\n",
958                    fromDecode->decodeInfo[tid].nextPC,
959                    fromDecode->decodeInfo[tid].nextNPC);
960            // Squash unless we're already squashing
961            squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
962                             fromDecode->decodeInfo[tid].nextNPC,
963                             fromDecode->decodeInfo[tid].nextMicroPC,
964                             fromDecode->decodeInfo[tid].doneSeqNum,
965                             tid);
966
967            return true;
968        }
969    }
970
971    if (checkStall(tid) &&
972        fetchStatus[tid] != IcacheWaitResponse &&
973        fetchStatus[tid] != IcacheWaitRetry) {
974        DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
975
976        fetchStatus[tid] = Blocked;
977
978        return true;
979    }
980
981    if (fetchStatus[tid] == Blocked ||
982        fetchStatus[tid] == Squashing) {
983        // Switch status to running if fetch isn't being told to block or
984        // squash this cycle.
985        DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
986                tid);
987
988        fetchStatus[tid] = Running;
989
990        return true;
991    }
992
993    // If we've reached this point, we have not gotten any signals that
994    // cause fetch to change its status.  Fetch remains the same as before.
995    return false;
996}
997
998template<class Impl>
999void
1000DefaultFetch<Impl>::fetch(bool &status_change)
1001{
1002    //////////////////////////////////////////
1003    // Start actual fetch
1004    //////////////////////////////////////////
1005    ThreadID tid = getFetchingThread(fetchPolicy);
1006
1007    if (tid == InvalidThreadID || drainPending) {
1008        DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1009
1010        // Breaks looping condition in tick()
1011        threadFetched = numFetchingThreads;
1012        return;
1013    }
1014
1015    DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1016
1017    // The current PC.
1018    Addr fetch_PC = PC[tid];
1019    Addr fetch_NPC = nextPC[tid];
1020    Addr fetch_MicroPC = microPC[tid];
1021
1022    // Fault code for memory access.
1023    Fault fault = NoFault;
1024
1025    // If returning from the delay of a cache miss, then update the status
1026    // to running, otherwise do the cache access.  Possibly move this up
1027    // to tick() function.
1028    if (fetchStatus[tid] == IcacheAccessComplete) {
1029        DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
1030                tid);
1031
1032        fetchStatus[tid] = Running;
1033        status_change = true;
1034    } else if (fetchStatus[tid] == Running) {
1035        DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1036                "instruction, starting at PC %08p.\n",
1037                tid, fetch_PC);
1038
1039        bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
1040        if (!fetch_success) {
1041            if (cacheBlocked) {
1042                ++icacheStallCycles;
1043            } else {
1044                ++fetchMiscStallCycles;
1045            }
1046            return;
1047        }
1048    } else {
1049        if (fetchStatus[tid] == Idle) {
1050            ++fetchIdleCycles;
1051            DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1052        } else if (fetchStatus[tid] == Blocked) {
1053            ++fetchBlockedCycles;
1054            DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1055        } else if (fetchStatus[tid] == Squashing) {
1056            ++fetchSquashCycles;
1057            DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1058        } else if (fetchStatus[tid] == IcacheWaitResponse) {
1059            ++icacheStallCycles;
1060            DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", tid);
1061        }
1062
1063        // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
1064        // fetch should do nothing.
1065        return;
1066    }
1067
1068    ++fetchCycles;
1069
1070    // If we had a stall due to an icache miss, then return.
1071    if (fetchStatus[tid] == IcacheWaitResponse) {
1072        ++icacheStallCycles;
1073        status_change = true;
1074        return;
1075    }
1076
1077    Addr next_PC = fetch_PC;
1078    Addr next_NPC = fetch_NPC;
1079    Addr next_MicroPC = fetch_MicroPC;
1080
1081    InstSeqNum inst_seq;
1082    MachInst inst;
1083    ExtMachInst ext_inst;
1084    // @todo: Fix this hack.
1085    unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
1086
1087    StaticInstPtr staticInst = NULL;
1088    StaticInstPtr macroop = NULL;
1089
1090    if (fault == NoFault) {
1091        // If the read of the first instruction was successful, then grab the
1092        // instructions from the rest of the cache line and put them into the
1093        // queue heading to decode.
1094
1095        DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1096                "decode.\n",tid);
1097
1098        // Need to keep track of whether or not a predicted branch
1099        // ended this fetch block.
1100        bool predicted_branch = false;
1101
1102        while (offset < cacheBlkSize &&
1103               numInst < fetchWidth &&
1104               !predicted_branch) {
1105
1106            // If we're branching after this instruction, quite fetching
1107            // from the same block then.
1108            predicted_branch =
1109                (fetch_PC + sizeof(TheISA::MachInst) != fetch_NPC);
1110            if (predicted_branch) {
1111                DPRINTF(Fetch, "Branch detected with PC = %#x, NPC = %#x\n",
1112                        fetch_PC, fetch_NPC);
1113            }
1114
1115            // Make sure this is a valid index.
1116            assert(offset <= cacheBlkSize - instSize);
1117
1118            if (!macroop) {
1119                // Get the instruction from the array of the cache line.
1120                inst = TheISA::gtoh(*reinterpret_cast<TheISA::MachInst *>
1121                            (&cacheData[tid][offset]));
1122
1123                predecoder.setTC(cpu->thread[tid]->getTC());
1124                predecoder.moreBytes(fetch_PC, fetch_PC, inst);
1125
1126                ext_inst = predecoder.getExtMachInst();
1127                staticInst = StaticInstPtr(ext_inst, fetch_PC);
1128                if (staticInst->isMacroop())
1129                    macroop = staticInst;
1130            }
1131            do {
1132                if (macroop) {
1133                    staticInst = macroop->fetchMicroop(fetch_MicroPC);
1134                    if (staticInst->isLastMicroop())
1135                        macroop = NULL;
1136                }
1137
1138                // Get a sequence number.
1139                inst_seq = cpu->getAndIncrementInstSeq();
1140
1141                // Create a new DynInst from the instruction fetched.
1142                DynInstPtr instruction = new DynInst(staticInst,
1143                                                     fetch_PC, fetch_NPC, fetch_MicroPC,
1144                                                     next_PC, next_NPC, next_MicroPC,
1145                                                     inst_seq, cpu);
1146                instruction->setTid(tid);
1147
1148                instruction->setASID(tid);
1149
1150                instruction->setThreadState(cpu->thread[tid]);
1151
1152                DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1153                        "[sn:%lli]\n",
1154                        tid, instruction->readPC(), inst_seq);
1155
1156                //DPRINTF(Fetch, "[tid:%i]: MachInst is %#x\n", tid, ext_inst);
1157
1158                DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1159                        tid, instruction->staticInst->disassemble(fetch_PC));
1160
1161#if TRACING_ON
1162                instruction->traceData =
1163                    cpu->getTracer()->getInstRecord(curTick, cpu->tcBase(tid),
1164                            instruction->staticInst, instruction->readPC());
1165#else
1166                instruction->traceData = NULL;
1167#endif
1168
1169                ///FIXME This needs to be more robust in dealing with delay slots
1170                predicted_branch |=
1171                    lookupAndUpdateNextPC(instruction, next_PC, next_NPC, next_MicroPC);
1172
1173                // Add instruction to the CPU's list of instructions.
1174                instruction->setInstListIt(cpu->addInst(instruction));
1175
1176                // Write the instruction to the first slot in the queue
1177                // that heads to decode.
1178                toDecode->insts[numInst] = instruction;
1179
1180                toDecode->size++;
1181
1182                // Increment stat of fetched instructions.
1183                ++fetchedInsts;
1184
1185                // Move to the next instruction, unless we have a branch.
1186                fetch_PC = next_PC;
1187                fetch_NPC = next_NPC;
1188                fetch_MicroPC = next_MicroPC;
1189
1190                if (instruction->isQuiesce()) {
1191                    DPRINTF(Fetch, "Quiesce instruction encountered, halting fetch!",
1192                            curTick);
1193                    fetchStatus[tid] = QuiescePending;
1194                    ++numInst;
1195                    status_change = true;
1196                    break;
1197                }
1198
1199                ++numInst;
1200            } while (staticInst->isMicroop() &&
1201                     !staticInst->isLastMicroop() &&
1202                     numInst < fetchWidth);
1203            offset += instSize;
1204        }
1205
1206        if (predicted_branch) {
1207            DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1208                    "instruction encountered.\n", tid);
1209        } else if (numInst >= fetchWidth) {
1210            DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1211                    "for this cycle.\n", tid);
1212        } else if (offset >= cacheBlkSize) {
1213            DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1214                    "block.\n", tid);
1215        }
1216    }
1217
1218    if (numInst > 0) {
1219        wroteToTimeBuffer = true;
1220    }
1221
1222    // Now that fetching is completed, update the PC to signify what the next
1223    // cycle will be.
1224    if (fault == NoFault) {
1225        PC[tid] = next_PC;
1226        nextPC[tid] = next_NPC;
1227        microPC[tid] = next_MicroPC;
1228        DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, next_PC);
1229    } else {
1230        // We shouldn't be in an icache miss and also have a fault (an ITB
1231        // miss)
1232        if (fetchStatus[tid] == IcacheWaitResponse) {
1233            panic("Fetch should have exited prior to this!");
1234        }
1235
1236        // Send the fault to commit.  This thread will not do anything
1237        // until commit handles the fault.  The only other way it can
1238        // wake up is if a squash comes along and changes the PC.
1239        assert(numInst < fetchWidth);
1240        // Get a sequence number.
1241        inst_seq = cpu->getAndIncrementInstSeq();
1242        // We will use a nop in order to carry the fault.
1243        ext_inst = TheISA::NoopMachInst;
1244
1245        // Create a new DynInst from the dummy nop.
1246        DynInstPtr instruction = new DynInst(ext_inst,
1247                                             fetch_PC, fetch_NPC, fetch_MicroPC,
1248                                             next_PC, next_NPC, next_MicroPC,
1249                                             inst_seq, cpu);
1250        instruction->setPredTarg(next_NPC, next_NPC + instSize, 0);
1251        instruction->setTid(tid);
1252
1253        instruction->setASID(tid);
1254
1255        instruction->setThreadState(cpu->thread[tid]);
1256
1257        instruction->traceData = NULL;
1258
1259        instruction->setInstListIt(cpu->addInst(instruction));
1260
1261        instruction->fault = fault;
1262
1263        toDecode->insts[numInst] = instruction;
1264        toDecode->size++;
1265
1266        DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1267
1268        fetchStatus[tid] = TrapPending;
1269        status_change = true;
1270
1271        DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %08p",
1272                tid, fault->name(), PC[tid]);
1273    }
1274}
1275
1276template<class Impl>
1277void
1278DefaultFetch<Impl>::recvRetry()
1279{
1280    if (retryPkt != NULL) {
1281        assert(cacheBlocked);
1282        assert(retryTid != InvalidThreadID);
1283        assert(fetchStatus[retryTid] == IcacheWaitRetry);
1284
1285        if (icachePort->sendTiming(retryPkt)) {
1286            fetchStatus[retryTid] = IcacheWaitResponse;
1287            retryPkt = NULL;
1288            retryTid = InvalidThreadID;
1289            cacheBlocked = false;
1290        }
1291    } else {
1292        assert(retryTid == InvalidThreadID);
1293        // Access has been squashed since it was sent out.  Just clear
1294        // the cache being blocked.
1295        cacheBlocked = false;
1296    }
1297}
1298
1299///////////////////////////////////////
1300//                                   //
1301//  SMT FETCH POLICY MAINTAINED HERE //
1302//                                   //
1303///////////////////////////////////////
1304template<class Impl>
1305ThreadID
1306DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1307{
1308    if (numThreads > 1) {
1309        switch (fetch_priority) {
1310
1311          case SingleThread:
1312            return 0;
1313
1314          case RoundRobin:
1315            return roundRobin();
1316
1317          case IQ:
1318            return iqCount();
1319
1320          case LSQ:
1321            return lsqCount();
1322
1323          case Branch:
1324            return branchCount();
1325
1326          default:
1327            return InvalidThreadID;
1328        }
1329    } else {
1330        list<ThreadID>::iterator thread = activeThreads->begin();
1331        if (thread == activeThreads->end()) {
1332            return InvalidThreadID;
1333        }
1334
1335        ThreadID tid = *thread;
1336
1337        if (fetchStatus[tid] == Running ||
1338            fetchStatus[tid] == IcacheAccessComplete ||
1339            fetchStatus[tid] == Idle) {
1340            return tid;
1341        } else {
1342            return InvalidThreadID;
1343        }
1344    }
1345}
1346
1347
1348template<class Impl>
1349ThreadID
1350DefaultFetch<Impl>::roundRobin()
1351{
1352    list<ThreadID>::iterator pri_iter = priorityList.begin();
1353    list<ThreadID>::iterator end      = priorityList.end();
1354
1355    ThreadID high_pri;
1356
1357    while (pri_iter != end) {
1358        high_pri = *pri_iter;
1359
1360        assert(high_pri <= numThreads);
1361
1362        if (fetchStatus[high_pri] == Running ||
1363            fetchStatus[high_pri] == IcacheAccessComplete ||
1364            fetchStatus[high_pri] == Idle) {
1365
1366            priorityList.erase(pri_iter);
1367            priorityList.push_back(high_pri);
1368
1369            return high_pri;
1370        }
1371
1372        pri_iter++;
1373    }
1374
1375    return InvalidThreadID;
1376}
1377
1378template<class Impl>
1379ThreadID
1380DefaultFetch<Impl>::iqCount()
1381{
1382    std::priority_queue<ThreadID> PQ;
1383
1384    list<ThreadID>::iterator threads = activeThreads->begin();
1385    list<ThreadID>::iterator end = activeThreads->end();
1386
1387    while (threads != end) {
1388        ThreadID tid = *threads++;
1389
1390        PQ.push(fromIEW->iewInfo[tid].iqCount);
1391    }
1392
1393    while (!PQ.empty()) {
1394        ThreadID high_pri = PQ.top();
1395
1396        if (fetchStatus[high_pri] == Running ||
1397            fetchStatus[high_pri] == IcacheAccessComplete ||
1398            fetchStatus[high_pri] == Idle)
1399            return high_pri;
1400        else
1401            PQ.pop();
1402
1403    }
1404
1405    return InvalidThreadID;
1406}
1407
1408template<class Impl>
1409ThreadID
1410DefaultFetch<Impl>::lsqCount()
1411{
1412    std::priority_queue<ThreadID> PQ;
1413
1414    list<ThreadID>::iterator threads = activeThreads->begin();
1415    list<ThreadID>::iterator end = activeThreads->end();
1416
1417    while (threads != end) {
1418        ThreadID tid = *threads++;
1419
1420        PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1421    }
1422
1423    while (!PQ.empty()) {
1424        ThreadID high_pri = PQ.top();
1425
1426        if (fetchStatus[high_pri] == Running ||
1427            fetchStatus[high_pri] == IcacheAccessComplete ||
1428            fetchStatus[high_pri] == Idle)
1429            return high_pri;
1430        else
1431            PQ.pop();
1432    }
1433
1434    return InvalidThreadID;
1435}
1436
1437template<class Impl>
1438ThreadID
1439DefaultFetch<Impl>::branchCount()
1440{
1441#if 0
1442    list<ThreadID>::iterator thread = activeThreads->begin();
1443    assert(thread != activeThreads->end());
1444    ThreadID tid = *thread;
1445#endif
1446
1447    panic("Branch Count Fetch policy unimplemented\n");
1448    return InvalidThreadID;
1449}
1450