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