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