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