fetch_impl.hh (2831:0a42b294727c) fetch_impl.hh (2843:19c4c6c2b5b1)
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Kevin Lim
29 * Korey Sewell
30 */
31
32#include "config/use_checker.hh"
33
34#include "arch/isa_traits.hh"
35#include "arch/utility.hh"
36#include "cpu/checker/cpu.hh"
37#include "cpu/exetrace.hh"
38#include "cpu/o3/fetch.hh"
39#include "mem/packet.hh"
40#include "mem/request.hh"
41#include "sim/byteswap.hh"
42#include "sim/host.hh"
43#include "sim/root.hh"
44
45#if FULL_SYSTEM
46#include "arch/tlb.hh"
47#include "arch/vtophys.hh"
48#include "base/remote_gdb.hh"
49#include "sim/system.hh"
50#endif // FULL_SYSTEM
51
52#include <algorithm>
53
54using namespace std;
55using namespace TheISA;
56
57template<class Impl>
58Tick
59DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
60{
61 panic("DefaultFetch doesn't expect recvAtomic callback!");
62 return curTick;
63}
64
65template<class Impl>
66void
67DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
68{
69 panic("DefaultFetch doesn't expect recvFunctional callback!");
70}
71
72template<class Impl>
73void
74DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
75{
76 if (status == RangeChange)
77 return;
78
79 panic("DefaultFetch doesn't expect recvStatusChange callback!");
80}
81
82template<class Impl>
83bool
84DefaultFetch<Impl>::IcachePort::recvTiming(Packet *pkt)
85{
86 fetch->processCacheCompletion(pkt);
87 return true;
88}
89
90template<class Impl>
91void
92DefaultFetch<Impl>::IcachePort::recvRetry()
93{
94 fetch->recvRetry();
95}
96
97template<class Impl>
98DefaultFetch<Impl>::DefaultFetch(Params *params)
99 : mem(params->mem),
100 branchPred(params),
101 decodeToFetchDelay(params->decodeToFetchDelay),
102 renameToFetchDelay(params->renameToFetchDelay),
103 iewToFetchDelay(params->iewToFetchDelay),
104 commitToFetchDelay(params->commitToFetchDelay),
105 fetchWidth(params->fetchWidth),
106 cacheBlocked(false),
107 retryPkt(NULL),
108 retryTid(-1),
109 numThreads(params->numberOfThreads),
110 numFetchingThreads(params->smtNumFetchingThreads),
111 interruptPending(false),
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Kevin Lim
29 * Korey Sewell
30 */
31
32#include "config/use_checker.hh"
33
34#include "arch/isa_traits.hh"
35#include "arch/utility.hh"
36#include "cpu/checker/cpu.hh"
37#include "cpu/exetrace.hh"
38#include "cpu/o3/fetch.hh"
39#include "mem/packet.hh"
40#include "mem/request.hh"
41#include "sim/byteswap.hh"
42#include "sim/host.hh"
43#include "sim/root.hh"
44
45#if FULL_SYSTEM
46#include "arch/tlb.hh"
47#include "arch/vtophys.hh"
48#include "base/remote_gdb.hh"
49#include "sim/system.hh"
50#endif // FULL_SYSTEM
51
52#include <algorithm>
53
54using namespace std;
55using namespace TheISA;
56
57template<class Impl>
58Tick
59DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
60{
61 panic("DefaultFetch doesn't expect recvAtomic callback!");
62 return curTick;
63}
64
65template<class Impl>
66void
67DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
68{
69 panic("DefaultFetch doesn't expect recvFunctional callback!");
70}
71
72template<class Impl>
73void
74DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
75{
76 if (status == RangeChange)
77 return;
78
79 panic("DefaultFetch doesn't expect recvStatusChange callback!");
80}
81
82template<class Impl>
83bool
84DefaultFetch<Impl>::IcachePort::recvTiming(Packet *pkt)
85{
86 fetch->processCacheCompletion(pkt);
87 return true;
88}
89
90template<class Impl>
91void
92DefaultFetch<Impl>::IcachePort::recvRetry()
93{
94 fetch->recvRetry();
95}
96
97template<class Impl>
98DefaultFetch<Impl>::DefaultFetch(Params *params)
99 : mem(params->mem),
100 branchPred(params),
101 decodeToFetchDelay(params->decodeToFetchDelay),
102 renameToFetchDelay(params->renameToFetchDelay),
103 iewToFetchDelay(params->iewToFetchDelay),
104 commitToFetchDelay(params->commitToFetchDelay),
105 fetchWidth(params->fetchWidth),
106 cacheBlocked(false),
107 retryPkt(NULL),
108 retryTid(-1),
109 numThreads(params->numberOfThreads),
110 numFetchingThreads(params->smtNumFetchingThreads),
111 interruptPending(false),
112 drainPending(false),
112 switchedOut(false)
113{
114 if (numThreads > Impl::MaxThreads)
115 fatal("numThreads is not a valid value\n");
116
117 // Set fetch stage's status to inactive.
118 _status = Inactive;
119
120 string policy = params->smtFetchPolicy;
121
122 // Convert string to lowercase
123 std::transform(policy.begin(), policy.end(), policy.begin(),
124 (int(*)(int)) tolower);
125
126 // Figure out fetch policy
127 if (policy == "singlethread") {
128 fetchPolicy = SingleThread;
129 if (numThreads > 1)
130 panic("Invalid Fetch Policy for a SMT workload.");
131 } else if (policy == "roundrobin") {
132 fetchPolicy = RoundRobin;
133 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
134 } else if (policy == "branch") {
135 fetchPolicy = Branch;
136 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
137 } else if (policy == "iqcount") {
138 fetchPolicy = IQ;
139 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
140 } else if (policy == "lsqcount") {
141 fetchPolicy = LSQ;
142 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
143 } else {
144 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
145 " RoundRobin,LSQcount,IQcount}\n");
146 }
147
148 // Size of cache block.
149 cacheBlkSize = 64;
150
151 // Create mask to get rid of offset bits.
152 cacheBlkMask = (cacheBlkSize - 1);
153
154 for (int tid=0; tid < numThreads; tid++) {
155
156 fetchStatus[tid] = Running;
157
158 priorityList.push_back(tid);
159
160 memReq[tid] = NULL;
161
162 // Create space to store a cache line.
163 cacheData[tid] = new uint8_t[cacheBlkSize];
164
165 stalls[tid].decode = 0;
166 stalls[tid].rename = 0;
167 stalls[tid].iew = 0;
168 stalls[tid].commit = 0;
169 }
170
171 // Get the size of an instruction.
172 instSize = sizeof(MachInst);
173}
174
175template <class Impl>
176std::string
177DefaultFetch<Impl>::name() const
178{
179 return cpu->name() + ".fetch";
180}
181
182template <class Impl>
183void
184DefaultFetch<Impl>::regStats()
185{
186 icacheStallCycles
187 .name(name() + ".icacheStallCycles")
188 .desc("Number of cycles fetch is stalled on an Icache miss")
189 .prereq(icacheStallCycles);
190
191 fetchedInsts
192 .name(name() + ".Insts")
193 .desc("Number of instructions fetch has processed")
194 .prereq(fetchedInsts);
195
196 fetchedBranches
197 .name(name() + ".Branches")
198 .desc("Number of branches that fetch encountered")
199 .prereq(fetchedBranches);
200
201 predictedBranches
202 .name(name() + ".predictedBranches")
203 .desc("Number of branches that fetch has predicted taken")
204 .prereq(predictedBranches);
205
206 fetchCycles
207 .name(name() + ".Cycles")
208 .desc("Number of cycles fetch has run and was not squashing or"
209 " blocked")
210 .prereq(fetchCycles);
211
212 fetchSquashCycles
213 .name(name() + ".SquashCycles")
214 .desc("Number of cycles fetch has spent squashing")
215 .prereq(fetchSquashCycles);
216
217 fetchIdleCycles
218 .name(name() + ".IdleCycles")
219 .desc("Number of cycles fetch was idle")
220 .prereq(fetchIdleCycles);
221
222 fetchBlockedCycles
223 .name(name() + ".BlockedCycles")
224 .desc("Number of cycles fetch has spent blocked")
225 .prereq(fetchBlockedCycles);
226
227 fetchedCacheLines
228 .name(name() + ".CacheLines")
229 .desc("Number of cache lines fetched")
230 .prereq(fetchedCacheLines);
231
232 fetchMiscStallCycles
233 .name(name() + ".MiscStallCycles")
234 .desc("Number of cycles fetch has spent waiting on interrupts, or "
235 "bad addresses, or out of MSHRs")
236 .prereq(fetchMiscStallCycles);
237
238 fetchIcacheSquashes
239 .name(name() + ".IcacheSquashes")
240 .desc("Number of outstanding Icache misses that were squashed")
241 .prereq(fetchIcacheSquashes);
242
243 fetchNisnDist
244 .init(/* base value */ 0,
245 /* last value */ fetchWidth,
246 /* bucket size */ 1)
247 .name(name() + ".rateDist")
248 .desc("Number of instructions fetched each cycle (Total)")
249 .flags(Stats::pdf);
250
251 idleRate
252 .name(name() + ".idleRate")
253 .desc("Percent of cycles fetch was idle")
254 .prereq(idleRate);
255 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
256
257 branchRate
258 .name(name() + ".branchRate")
259 .desc("Number of branch fetches per cycle")
260 .flags(Stats::total);
261 branchRate = fetchedBranches / cpu->numCycles;
262
263 fetchRate
264 .name(name() + ".rate")
265 .desc("Number of inst fetches per cycle")
266 .flags(Stats::total);
267 fetchRate = fetchedInsts / cpu->numCycles;
268
269 branchPred.regStats();
270}
271
272template<class Impl>
273void
274DefaultFetch<Impl>::setCPU(O3CPU *cpu_ptr)
275{
276 DPRINTF(Fetch, "Setting the CPU pointer.\n");
277 cpu = cpu_ptr;
278
279 // Name is finally available, so create the port.
280 icachePort = new IcachePort(this);
281
282 Port *mem_dport = mem->getPort("");
283 icachePort->setPeer(mem_dport);
284 mem_dport->setPeer(icachePort);
285
286#if USE_CHECKER
287 if (cpu->checker) {
288 cpu->checker->setIcachePort(icachePort);
289 }
290#endif
291
292 // Fetch needs to start fetching instructions at the very beginning,
293 // so it must start up in active state.
294 switchToActive();
295}
296
297template<class Impl>
298void
299DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
300{
301 DPRINTF(Fetch, "Setting the time buffer pointer.\n");
302 timeBuffer = time_buffer;
303
304 // Create wires to get information from proper places in time buffer.
305 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
306 fromRename = timeBuffer->getWire(-renameToFetchDelay);
307 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
308 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
309}
310
311template<class Impl>
312void
313DefaultFetch<Impl>::setActiveThreads(list<unsigned> *at_ptr)
314{
315 DPRINTF(Fetch, "Setting active threads list pointer.\n");
316 activeThreads = at_ptr;
317}
318
319template<class Impl>
320void
321DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
322{
323 DPRINTF(Fetch, "Setting the fetch queue pointer.\n");
324 fetchQueue = fq_ptr;
325
326 // Create wire to write information to proper place in fetch queue.
327 toDecode = fetchQueue->getWire(0);
328}
329
330template<class Impl>
331void
332DefaultFetch<Impl>::initStage()
333{
334 // Setup PC and nextPC with initial state.
335 for (int tid = 0; tid < numThreads; tid++) {
336 PC[tid] = cpu->readPC(tid);
337 nextPC[tid] = cpu->readNextPC(tid);
338#if THE_ISA != ALPHA_ISA
339 nextNPC[tid] = cpu->readNextNPC(tid);
340#endif
341 }
342}
343
344template<class Impl>
345void
346DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
347{
348 unsigned tid = pkt->req->getThreadNum();
349
350 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
351
352 // Only change the status if it's still waiting on the icache access
353 // to return.
354 if (fetchStatus[tid] != IcacheWaitResponse ||
355 pkt->req != memReq[tid] ||
113 switchedOut(false)
114{
115 if (numThreads > Impl::MaxThreads)
116 fatal("numThreads is not a valid value\n");
117
118 // Set fetch stage's status to inactive.
119 _status = Inactive;
120
121 string policy = params->smtFetchPolicy;
122
123 // Convert string to lowercase
124 std::transform(policy.begin(), policy.end(), policy.begin(),
125 (int(*)(int)) tolower);
126
127 // Figure out fetch policy
128 if (policy == "singlethread") {
129 fetchPolicy = SingleThread;
130 if (numThreads > 1)
131 panic("Invalid Fetch Policy for a SMT workload.");
132 } else if (policy == "roundrobin") {
133 fetchPolicy = RoundRobin;
134 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
135 } else if (policy == "branch") {
136 fetchPolicy = Branch;
137 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
138 } else if (policy == "iqcount") {
139 fetchPolicy = IQ;
140 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
141 } else if (policy == "lsqcount") {
142 fetchPolicy = LSQ;
143 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
144 } else {
145 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
146 " RoundRobin,LSQcount,IQcount}\n");
147 }
148
149 // Size of cache block.
150 cacheBlkSize = 64;
151
152 // Create mask to get rid of offset bits.
153 cacheBlkMask = (cacheBlkSize - 1);
154
155 for (int tid=0; tid < numThreads; tid++) {
156
157 fetchStatus[tid] = Running;
158
159 priorityList.push_back(tid);
160
161 memReq[tid] = NULL;
162
163 // Create space to store a cache line.
164 cacheData[tid] = new uint8_t[cacheBlkSize];
165
166 stalls[tid].decode = 0;
167 stalls[tid].rename = 0;
168 stalls[tid].iew = 0;
169 stalls[tid].commit = 0;
170 }
171
172 // Get the size of an instruction.
173 instSize = sizeof(MachInst);
174}
175
176template <class Impl>
177std::string
178DefaultFetch<Impl>::name() const
179{
180 return cpu->name() + ".fetch";
181}
182
183template <class Impl>
184void
185DefaultFetch<Impl>::regStats()
186{
187 icacheStallCycles
188 .name(name() + ".icacheStallCycles")
189 .desc("Number of cycles fetch is stalled on an Icache miss")
190 .prereq(icacheStallCycles);
191
192 fetchedInsts
193 .name(name() + ".Insts")
194 .desc("Number of instructions fetch has processed")
195 .prereq(fetchedInsts);
196
197 fetchedBranches
198 .name(name() + ".Branches")
199 .desc("Number of branches that fetch encountered")
200 .prereq(fetchedBranches);
201
202 predictedBranches
203 .name(name() + ".predictedBranches")
204 .desc("Number of branches that fetch has predicted taken")
205 .prereq(predictedBranches);
206
207 fetchCycles
208 .name(name() + ".Cycles")
209 .desc("Number of cycles fetch has run and was not squashing or"
210 " blocked")
211 .prereq(fetchCycles);
212
213 fetchSquashCycles
214 .name(name() + ".SquashCycles")
215 .desc("Number of cycles fetch has spent squashing")
216 .prereq(fetchSquashCycles);
217
218 fetchIdleCycles
219 .name(name() + ".IdleCycles")
220 .desc("Number of cycles fetch was idle")
221 .prereq(fetchIdleCycles);
222
223 fetchBlockedCycles
224 .name(name() + ".BlockedCycles")
225 .desc("Number of cycles fetch has spent blocked")
226 .prereq(fetchBlockedCycles);
227
228 fetchedCacheLines
229 .name(name() + ".CacheLines")
230 .desc("Number of cache lines fetched")
231 .prereq(fetchedCacheLines);
232
233 fetchMiscStallCycles
234 .name(name() + ".MiscStallCycles")
235 .desc("Number of cycles fetch has spent waiting on interrupts, or "
236 "bad addresses, or out of MSHRs")
237 .prereq(fetchMiscStallCycles);
238
239 fetchIcacheSquashes
240 .name(name() + ".IcacheSquashes")
241 .desc("Number of outstanding Icache misses that were squashed")
242 .prereq(fetchIcacheSquashes);
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>::setCPU(O3CPU *cpu_ptr)
276{
277 DPRINTF(Fetch, "Setting the CPU pointer.\n");
278 cpu = cpu_ptr;
279
280 // Name is finally available, so create the port.
281 icachePort = new IcachePort(this);
282
283 Port *mem_dport = mem->getPort("");
284 icachePort->setPeer(mem_dport);
285 mem_dport->setPeer(icachePort);
286
287#if USE_CHECKER
288 if (cpu->checker) {
289 cpu->checker->setIcachePort(icachePort);
290 }
291#endif
292
293 // Fetch needs to start fetching instructions at the very beginning,
294 // so it must start up in active state.
295 switchToActive();
296}
297
298template<class Impl>
299void
300DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
301{
302 DPRINTF(Fetch, "Setting the time buffer pointer.\n");
303 timeBuffer = time_buffer;
304
305 // Create wires to get information from proper places in time buffer.
306 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
307 fromRename = timeBuffer->getWire(-renameToFetchDelay);
308 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
309 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
310}
311
312template<class Impl>
313void
314DefaultFetch<Impl>::setActiveThreads(list<unsigned> *at_ptr)
315{
316 DPRINTF(Fetch, "Setting active threads list pointer.\n");
317 activeThreads = at_ptr;
318}
319
320template<class Impl>
321void
322DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
323{
324 DPRINTF(Fetch, "Setting the fetch queue pointer.\n");
325 fetchQueue = fq_ptr;
326
327 // Create wire to write information to proper place in fetch queue.
328 toDecode = fetchQueue->getWire(0);
329}
330
331template<class Impl>
332void
333DefaultFetch<Impl>::initStage()
334{
335 // Setup PC and nextPC with initial state.
336 for (int tid = 0; tid < numThreads; tid++) {
337 PC[tid] = cpu->readPC(tid);
338 nextPC[tid] = cpu->readNextPC(tid);
339#if THE_ISA != ALPHA_ISA
340 nextNPC[tid] = cpu->readNextNPC(tid);
341#endif
342 }
343}
344
345template<class Impl>
346void
347DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
348{
349 unsigned tid = pkt->req->getThreadNum();
350
351 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
352
353 // Only change the status if it's still waiting on the icache access
354 // to return.
355 if (fetchStatus[tid] != IcacheWaitResponse ||
356 pkt->req != memReq[tid] ||
356 isSwitchedOut()) {
357 isSwitchedOut() ||
358 drainPending) {
357 ++fetchIcacheSquashes;
358 delete pkt->req;
359 delete pkt;
360 return;
361 }
362
363 // Wake up the CPU (if it went to sleep and was waiting on this completion
364 // event).
365 cpu->wakeCPU();
366
367 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
368 tid);
369
370 switchToActive();
371
372 // Only switch to IcacheAccessComplete if we're not stalled as well.
373 if (checkStall(tid)) {
374 fetchStatus[tid] = Blocked;
375 } else {
376 fetchStatus[tid] = IcacheAccessComplete;
377 }
378
379 // Reset the mem req to NULL.
380 delete pkt->req;
381 delete pkt;
382 memReq[tid] = NULL;
383}
384
385template <class Impl>
386void
359 ++fetchIcacheSquashes;
360 delete pkt->req;
361 delete pkt;
362 return;
363 }
364
365 // Wake up the CPU (if it went to sleep and was waiting on this completion
366 // event).
367 cpu->wakeCPU();
368
369 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
370 tid);
371
372 switchToActive();
373
374 // Only switch to IcacheAccessComplete if we're not stalled as well.
375 if (checkStall(tid)) {
376 fetchStatus[tid] = Blocked;
377 } else {
378 fetchStatus[tid] = IcacheAccessComplete;
379 }
380
381 // Reset the mem req to NULL.
382 delete pkt->req;
383 delete pkt;
384 memReq[tid] = NULL;
385}
386
387template <class Impl>
388void
387DefaultFetch<Impl>::switchOut()
389DefaultFetch<Impl>::drain()
388{
390{
389 // Fetch is ready to switch out at any time.
390 switchedOut = true;
391 cpu->signalSwitched();
391 // Fetch is ready to drain at any time.
392 cpu->signalDrained();
393 drainPending = true;
392}
393
394template <class Impl>
395void
394}
395
396template <class Impl>
397void
396DefaultFetch<Impl>::doSwitchOut()
398DefaultFetch<Impl>::resume()
397{
399{
400 drainPending = false;
401}
402
403template <class Impl>
404void
405DefaultFetch<Impl>::switchOut()
406{
407 switchedOut = true;
398 // Branch predictor needs to have its state cleared.
399 branchPred.switchOut();
400}
401
402template <class Impl>
403void
404DefaultFetch<Impl>::takeOverFrom()
405{
406 // Reset all state
407 for (int i = 0; i < Impl::MaxThreads; ++i) {
408 stalls[i].decode = 0;
409 stalls[i].rename = 0;
410 stalls[i].iew = 0;
411 stalls[i].commit = 0;
412 PC[i] = cpu->readPC(i);
413 nextPC[i] = cpu->readNextPC(i);
414#if THE_ISA != ALPHA_ISA
415 nextNPC[i] = cpu->readNextNPC(i);
416#endif
417 fetchStatus[i] = Running;
418 }
419 numInst = 0;
420 wroteToTimeBuffer = false;
421 _status = Inactive;
422 switchedOut = false;
423 branchPred.takeOverFrom();
424}
425
426template <class Impl>
427void
428DefaultFetch<Impl>::wakeFromQuiesce()
429{
430 DPRINTF(Fetch, "Waking up from quiesce\n");
431 // Hopefully this is safe
432 // @todo: Allow other threads to wake from quiesce.
433 fetchStatus[0] = Running;
434}
435
436template <class Impl>
437inline void
438DefaultFetch<Impl>::switchToActive()
439{
440 if (_status == Inactive) {
441 DPRINTF(Activity, "Activating stage.\n");
442
443 cpu->activateStage(O3CPU::FetchIdx);
444
445 _status = Active;
446 }
447}
448
449template <class Impl>
450inline void
451DefaultFetch<Impl>::switchToInactive()
452{
453 if (_status == Active) {
454 DPRINTF(Activity, "Deactivating stage.\n");
455
456 cpu->deactivateStage(O3CPU::FetchIdx);
457
458 _status = Inactive;
459 }
460}
461
462template <class Impl>
463bool
464DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC)
465{
466 // Do branch prediction check here.
467 // A bit of a misnomer...next_PC is actually the current PC until
468 // this function updates it.
469 bool predict_taken;
470
471 if (!inst->isControl()) {
472 next_PC = next_PC + instSize;
473 inst->setPredTarg(next_PC);
474 return false;
475 }
476
477 predict_taken = branchPred.predict(inst, next_PC, inst->threadNumber);
478
479 ++fetchedBranches;
480
481 if (predict_taken) {
482 ++predictedBranches;
483 }
484
485 return predict_taken;
486}
487
488template <class Impl>
489bool
490DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
491{
492 Fault fault = NoFault;
493
494#if FULL_SYSTEM
495 // Flag to say whether or not address is physical addr.
496 unsigned flags = cpu->inPalMode(fetch_PC) ? PHYSICAL : 0;
497#else
498 unsigned flags = 0;
499#endif // FULL_SYSTEM
500
408 // Branch predictor needs to have its state cleared.
409 branchPred.switchOut();
410}
411
412template <class Impl>
413void
414DefaultFetch<Impl>::takeOverFrom()
415{
416 // Reset all state
417 for (int i = 0; i < Impl::MaxThreads; ++i) {
418 stalls[i].decode = 0;
419 stalls[i].rename = 0;
420 stalls[i].iew = 0;
421 stalls[i].commit = 0;
422 PC[i] = cpu->readPC(i);
423 nextPC[i] = cpu->readNextPC(i);
424#if THE_ISA != ALPHA_ISA
425 nextNPC[i] = cpu->readNextNPC(i);
426#endif
427 fetchStatus[i] = Running;
428 }
429 numInst = 0;
430 wroteToTimeBuffer = false;
431 _status = Inactive;
432 switchedOut = false;
433 branchPred.takeOverFrom();
434}
435
436template <class Impl>
437void
438DefaultFetch<Impl>::wakeFromQuiesce()
439{
440 DPRINTF(Fetch, "Waking up from quiesce\n");
441 // Hopefully this is safe
442 // @todo: Allow other threads to wake from quiesce.
443 fetchStatus[0] = Running;
444}
445
446template <class Impl>
447inline void
448DefaultFetch<Impl>::switchToActive()
449{
450 if (_status == Inactive) {
451 DPRINTF(Activity, "Activating stage.\n");
452
453 cpu->activateStage(O3CPU::FetchIdx);
454
455 _status = Active;
456 }
457}
458
459template <class Impl>
460inline void
461DefaultFetch<Impl>::switchToInactive()
462{
463 if (_status == Active) {
464 DPRINTF(Activity, "Deactivating stage.\n");
465
466 cpu->deactivateStage(O3CPU::FetchIdx);
467
468 _status = Inactive;
469 }
470}
471
472template <class Impl>
473bool
474DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC)
475{
476 // Do branch prediction check here.
477 // A bit of a misnomer...next_PC is actually the current PC until
478 // this function updates it.
479 bool predict_taken;
480
481 if (!inst->isControl()) {
482 next_PC = next_PC + instSize;
483 inst->setPredTarg(next_PC);
484 return false;
485 }
486
487 predict_taken = branchPred.predict(inst, next_PC, inst->threadNumber);
488
489 ++fetchedBranches;
490
491 if (predict_taken) {
492 ++predictedBranches;
493 }
494
495 return predict_taken;
496}
497
498template <class Impl>
499bool
500DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
501{
502 Fault fault = NoFault;
503
504#if FULL_SYSTEM
505 // Flag to say whether or not address is physical addr.
506 unsigned flags = cpu->inPalMode(fetch_PC) ? PHYSICAL : 0;
507#else
508 unsigned flags = 0;
509#endif // FULL_SYSTEM
510
501 if (cacheBlocked || (interruptPending && flags == 0) || switchedOut) {
511 if (cacheBlocked || (interruptPending && flags == 0) || drainPending) {
502 // Hold off fetch from getting new instructions when:
503 // Cache is blocked, or
504 // while an interrupt is pending and we're not in PAL mode, or
505 // fetch is switched out.
506 return false;
507 }
508
509 // Align the fetch PC so it's at the start of a cache block.
510 fetch_PC = icacheBlockAlignPC(fetch_PC);
511
512 // Setup the memReq to do a read of the first instruction's address.
513 // Set the appropriate read size and flags as well.
514 // Build request here.
515 RequestPtr mem_req = new Request(tid, fetch_PC, cacheBlkSize, flags,
516 fetch_PC, cpu->readCpuId(), tid);
517
518 memReq[tid] = mem_req;
519
520 // Translate the instruction request.
521 fault = cpu->translateInstReq(mem_req, cpu->thread[tid]);
522
523 // In the case of faults, the fetch stage may need to stall and wait
524 // for the ITB miss to be handled.
525
526 // If translation was successful, attempt to read the first
527 // instruction.
528 if (fault == NoFault) {
529#if 0
530 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
531 memReq[tid]->flags & UNCACHEABLE) {
532 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
533 "misspeculating path)!",
534 memReq[tid]->paddr);
535 ret_fault = TheISA::genMachineCheckFault();
536 return false;
537 }
538#endif
539
540 // Build packet here.
541 PacketPtr data_pkt = new Packet(mem_req,
542 Packet::ReadReq, Packet::Broadcast);
543 data_pkt->dataStatic(cacheData[tid]);
544
545 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
546
547 fetchedCacheLines++;
548
549 // Now do the timing access to see whether or not the instruction
550 // exists within the cache.
551 if (!icachePort->sendTiming(data_pkt)) {
552 assert(retryPkt == NULL);
553 assert(retryTid == -1);
554 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
555 fetchStatus[tid] = IcacheWaitRetry;
556 retryPkt = data_pkt;
557 retryTid = tid;
558 cacheBlocked = true;
559 return false;
560 }
561
562 DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
563
564 lastIcacheStall[tid] = curTick;
565
566 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
567 "response.\n", tid);
568
569 fetchStatus[tid] = IcacheWaitResponse;
570 } else {
571 delete mem_req;
572 memReq[tid] = NULL;
573 }
574
575 ret_fault = fault;
576 return true;
577}
578
579template <class Impl>
580inline void
581DefaultFetch<Impl>::doSquash(const Addr &new_PC, unsigned tid)
582{
583 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x.\n",
584 tid, new_PC);
585
586 PC[tid] = new_PC;
587 nextPC[tid] = new_PC + instSize;
588
589 // Clear the icache miss if it's outstanding.
590 if (fetchStatus[tid] == IcacheWaitResponse) {
591 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
592 tid);
593 memReq[tid] = NULL;
594 }
595
596 // Get rid of the retrying packet if it was from this thread.
597 if (retryTid == tid) {
598 assert(cacheBlocked);
599 cacheBlocked = false;
600 retryTid = -1;
601 retryPkt = NULL;
602 delete retryPkt->req;
603 delete retryPkt;
604 }
605
606 fetchStatus[tid] = Squashing;
607
608 ++fetchSquashCycles;
609}
610
611template<class Impl>
612void
613DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC,
614 const InstSeqNum &seq_num,
615 unsigned tid)
616{
617 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
618
619 doSquash(new_PC, tid);
620
621 // Tell the CPU to remove any instructions that are in flight between
622 // fetch and decode.
623 cpu->removeInstsUntil(seq_num, tid);
624}
625
626template<class Impl>
627bool
628DefaultFetch<Impl>::checkStall(unsigned tid) const
629{
630 bool ret_val = false;
631
632 if (cpu->contextSwitch) {
633 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
634 ret_val = true;
635 } else if (stalls[tid].decode) {
636 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
637 ret_val = true;
638 } else if (stalls[tid].rename) {
639 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
640 ret_val = true;
641 } else if (stalls[tid].iew) {
642 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
643 ret_val = true;
644 } else if (stalls[tid].commit) {
645 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
646 ret_val = true;
647 }
648
649 return ret_val;
650}
651
652template<class Impl>
653typename DefaultFetch<Impl>::FetchStatus
654DefaultFetch<Impl>::updateFetchStatus()
655{
656 //Check Running
657 list<unsigned>::iterator threads = (*activeThreads).begin();
658
659 while (threads != (*activeThreads).end()) {
660
661 unsigned tid = *threads++;
662
663 if (fetchStatus[tid] == Running ||
664 fetchStatus[tid] == Squashing ||
665 fetchStatus[tid] == IcacheAccessComplete) {
666
667 if (_status == Inactive) {
668 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
669
670 if (fetchStatus[tid] == IcacheAccessComplete) {
671 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
672 "completion\n",tid);
673 }
674
675 cpu->activateStage(O3CPU::FetchIdx);
676 }
677
678 return Active;
679 }
680 }
681
682 // Stage is switching from active to inactive, notify CPU of it.
683 if (_status == Active) {
684 DPRINTF(Activity, "Deactivating stage.\n");
685
686 cpu->deactivateStage(O3CPU::FetchIdx);
687 }
688
689 return Inactive;
690}
691
692template <class Impl>
693void
694DefaultFetch<Impl>::squash(const Addr &new_PC, unsigned tid)
695{
696 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
697
698 doSquash(new_PC, tid);
699
700 // Tell the CPU to remove any instructions that are not in the ROB.
701 cpu->removeInstsNotInROB(tid);
702}
703
704template <class Impl>
705void
706DefaultFetch<Impl>::tick()
707{
708 list<unsigned>::iterator threads = (*activeThreads).begin();
709 bool status_change = false;
710
711 wroteToTimeBuffer = false;
712
713 while (threads != (*activeThreads).end()) {
714 unsigned tid = *threads++;
715
716 // Check the signals for each thread to determine the proper status
717 // for each thread.
718 bool updated_status = checkSignalsAndUpdate(tid);
719 status_change = status_change || updated_status;
720 }
721
722 DPRINTF(Fetch, "Running stage.\n");
723
724 // Reset the number of the instruction we're fetching.
725 numInst = 0;
726
727#if FULL_SYSTEM
728 if (fromCommit->commitInfo[0].interruptPending) {
729 interruptPending = true;
730 }
731
732 if (fromCommit->commitInfo[0].clearInterrupt) {
733 interruptPending = false;
734 }
735#endif
736
737 for (threadFetched = 0; threadFetched < numFetchingThreads;
738 threadFetched++) {
739 // Fetch each of the actively fetching threads.
740 fetch(status_change);
741 }
742
743 // Record number of instructions fetched this cycle for distribution.
744 fetchNisnDist.sample(numInst);
745
746 if (status_change) {
747 // Change the fetch stage status if there was a status change.
748 _status = updateFetchStatus();
749 }
750
751 // If there was activity this cycle, inform the CPU of it.
752 if (wroteToTimeBuffer || cpu->contextSwitch) {
753 DPRINTF(Activity, "Activity this cycle.\n");
754
755 cpu->activityThisCycle();
756 }
757}
758
759template <class Impl>
760bool
761DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
762{
763 // Update the per thread stall statuses.
764 if (fromDecode->decodeBlock[tid]) {
765 stalls[tid].decode = true;
766 }
767
768 if (fromDecode->decodeUnblock[tid]) {
769 assert(stalls[tid].decode);
770 assert(!fromDecode->decodeBlock[tid]);
771 stalls[tid].decode = false;
772 }
773
774 if (fromRename->renameBlock[tid]) {
775 stalls[tid].rename = true;
776 }
777
778 if (fromRename->renameUnblock[tid]) {
779 assert(stalls[tid].rename);
780 assert(!fromRename->renameBlock[tid]);
781 stalls[tid].rename = false;
782 }
783
784 if (fromIEW->iewBlock[tid]) {
785 stalls[tid].iew = true;
786 }
787
788 if (fromIEW->iewUnblock[tid]) {
789 assert(stalls[tid].iew);
790 assert(!fromIEW->iewBlock[tid]);
791 stalls[tid].iew = false;
792 }
793
794 if (fromCommit->commitBlock[tid]) {
795 stalls[tid].commit = true;
796 }
797
798 if (fromCommit->commitUnblock[tid]) {
799 assert(stalls[tid].commit);
800 assert(!fromCommit->commitBlock[tid]);
801 stalls[tid].commit = false;
802 }
803
804 // Check squash signals from commit.
805 if (fromCommit->commitInfo[tid].squash) {
806
807 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
808 "from commit.\n",tid);
809
810 // In any case, squash.
811 squash(fromCommit->commitInfo[tid].nextPC,tid);
812
813 // Also check if there's a mispredict that happened.
814 if (fromCommit->commitInfo[tid].branchMispredict) {
815 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
816 fromCommit->commitInfo[tid].nextPC,
817 fromCommit->commitInfo[tid].branchTaken,
818 tid);
819 } else {
820 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
821 tid);
822 }
823
824 return true;
825 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
826 // Update the branch predictor if it wasn't a squashed instruction
827 // that was broadcasted.
828 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
829 }
830
831 // Check ROB squash signals from commit.
832 if (fromCommit->commitInfo[tid].robSquashing) {
833 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
834
835 // Continue to squash.
836 fetchStatus[tid] = Squashing;
837
838 return true;
839 }
840
841 // Check squash signals from decode.
842 if (fromDecode->decodeInfo[tid].squash) {
843 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
844 "from decode.\n",tid);
845
846 // Update the branch predictor.
847 if (fromDecode->decodeInfo[tid].branchMispredict) {
848 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
849 fromDecode->decodeInfo[tid].nextPC,
850 fromDecode->decodeInfo[tid].branchTaken,
851 tid);
852 } else {
853 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
854 tid);
855 }
856
857 if (fetchStatus[tid] != Squashing) {
858 // Squash unless we're already squashing
859 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
860 fromDecode->decodeInfo[tid].doneSeqNum,
861 tid);
862
863 return true;
864 }
865 }
866
867 if (checkStall(tid) && fetchStatus[tid] != IcacheWaitResponse) {
868 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
869
870 fetchStatus[tid] = Blocked;
871
872 return true;
873 }
874
875 if (fetchStatus[tid] == Blocked ||
876 fetchStatus[tid] == Squashing) {
877 // Switch status to running if fetch isn't being told to block or
878 // squash this cycle.
879 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
880 tid);
881
882 fetchStatus[tid] = Running;
883
884 return true;
885 }
886
887 // If we've reached this point, we have not gotten any signals that
888 // cause fetch to change its status. Fetch remains the same as before.
889 return false;
890}
891
892template<class Impl>
893void
894DefaultFetch<Impl>::fetch(bool &status_change)
895{
896 //////////////////////////////////////////
897 // Start actual fetch
898 //////////////////////////////////////////
899 int tid = getFetchingThread(fetchPolicy);
900
901 if (tid == -1) {
902 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
903
904 // Breaks looping condition in tick()
905 threadFetched = numFetchingThreads;
906 return;
907 }
908
909 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
910
911 // The current PC.
912 Addr &fetch_PC = PC[tid];
913
914 // Fault code for memory access.
915 Fault fault = NoFault;
916
917 // If returning from the delay of a cache miss, then update the status
918 // to running, otherwise do the cache access. Possibly move this up
919 // to tick() function.
920 if (fetchStatus[tid] == IcacheAccessComplete) {
921 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
922 tid);
923
924 fetchStatus[tid] = Running;
925 status_change = true;
926 } else if (fetchStatus[tid] == Running) {
927 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
928 "instruction, starting at PC %08p.\n",
929 tid, fetch_PC);
930
931 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
932 if (!fetch_success) {
933 if (cacheBlocked) {
934 ++icacheStallCycles;
935 } else {
936 ++fetchMiscStallCycles;
937 }
938 return;
939 }
940 } else {
941 if (fetchStatus[tid] == Idle) {
942 ++fetchIdleCycles;
943 } else if (fetchStatus[tid] == Blocked) {
944 ++fetchBlockedCycles;
945 } else if (fetchStatus[tid] == Squashing) {
946 ++fetchSquashCycles;
947 } else if (fetchStatus[tid] == IcacheWaitResponse) {
948 ++icacheStallCycles;
949 }
950
951 // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
952 // fetch should do nothing.
953 return;
954 }
955
956 ++fetchCycles;
957
958 // If we had a stall due to an icache miss, then return.
959 if (fetchStatus[tid] == IcacheWaitResponse) {
960 ++icacheStallCycles;
961 status_change = true;
962 return;
963 }
964
965 Addr next_PC = fetch_PC;
966 InstSeqNum inst_seq;
967 MachInst inst;
968 ExtMachInst ext_inst;
969 // @todo: Fix this hack.
970 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
971
972 if (fault == NoFault) {
973 // If the read of the first instruction was successful, then grab the
974 // instructions from the rest of the cache line and put them into the
975 // queue heading to decode.
976
977 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
978 "decode.\n",tid);
979
980 // Need to keep track of whether or not a predicted branch
981 // ended this fetch block.
982 bool predicted_branch = false;
983
984 for (;
985 offset < cacheBlkSize &&
986 numInst < fetchWidth &&
987 !predicted_branch;
988 ++numInst) {
989
990 // Get a sequence number.
991 inst_seq = cpu->getAndIncrementInstSeq();
992
993 // Make sure this is a valid index.
994 assert(offset <= cacheBlkSize - instSize);
995
996 // Get the instruction from the array of the cache line.
997 inst = gtoh(*reinterpret_cast<MachInst *>
998 (&cacheData[tid][offset]));
999
1000 ext_inst = TheISA::makeExtMI(inst, fetch_PC);
1001
1002 // Create a new DynInst from the instruction fetched.
1003 DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
1004 next_PC,
1005 inst_seq, cpu);
1006 instruction->setTid(tid);
1007
1008 instruction->setASID(tid);
1009
1010 instruction->setThreadState(cpu->thread[tid]);
1011
1012 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1013 "[sn:%lli]\n",
1014 tid, instruction->readPC(), inst_seq);
1015
1016 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1017 tid, instruction->staticInst->disassemble(fetch_PC));
1018
1019 instruction->traceData =
1020 Trace::getInstRecord(curTick, cpu->tcBase(tid), cpu,
1021 instruction->staticInst,
1022 instruction->readPC(),tid);
1023
1024 predicted_branch = lookupAndUpdateNextPC(instruction, next_PC);
1025
1026 // Add instruction to the CPU's list of instructions.
1027 instruction->setInstListIt(cpu->addInst(instruction));
1028
1029 // Write the instruction to the first slot in the queue
1030 // that heads to decode.
1031 toDecode->insts[numInst] = instruction;
1032
1033 toDecode->size++;
1034
1035 // Increment stat of fetched instructions.
1036 ++fetchedInsts;
1037
1038 // Move to the next instruction, unless we have a branch.
1039 fetch_PC = next_PC;
1040
1041 if (instruction->isQuiesce()) {
1042 warn("cycle %lli: Quiesce instruction encountered, halting fetch!",
1043 curTick);
1044 fetchStatus[tid] = QuiescePending;
1045 ++numInst;
1046 status_change = true;
1047 break;
1048 }
1049
1050 offset+= instSize;
1051 }
1052 }
1053
1054 if (numInst > 0) {
1055 wroteToTimeBuffer = true;
1056 }
1057
1058 // Now that fetching is completed, update the PC to signify what the next
1059 // cycle will be.
1060 if (fault == NoFault) {
1061 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n",tid, next_PC);
1062
1063#if THE_ISA == ALPHA_ISA
1064 PC[tid] = next_PC;
1065 nextPC[tid] = next_PC + instSize;
1066#else
1067 PC[tid] = next_PC;
1068 nextPC[tid] = next_PC + instSize;
1069 nextPC[tid] = next_PC + instSize;
1070
1071 thread->setNextPC(thread->readNextNPC());
1072 thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));
1073#endif
1074 } else {
1075 // We shouldn't be in an icache miss and also have a fault (an ITB
1076 // miss)
1077 if (fetchStatus[tid] == IcacheWaitResponse) {
1078 panic("Fetch should have exited prior to this!");
1079 }
1080
1081 // Send the fault to commit. This thread will not do anything
1082 // until commit handles the fault. The only other way it can
1083 // wake up is if a squash comes along and changes the PC.
1084#if FULL_SYSTEM
1085 assert(numInst != fetchWidth);
1086 // Get a sequence number.
1087 inst_seq = cpu->getAndIncrementInstSeq();
1088 // We will use a nop in order to carry the fault.
1089 ext_inst = TheISA::NoopMachInst;
1090
1091 // Create a new DynInst from the dummy nop.
1092 DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
1093 next_PC,
1094 inst_seq, cpu);
1095 instruction->setPredTarg(next_PC + instSize);
1096 instruction->setTid(tid);
1097
1098 instruction->setASID(tid);
1099
1100 instruction->setThreadState(cpu->thread[tid]);
1101
1102 instruction->traceData = NULL;
1103
1104 instruction->setInstListIt(cpu->addInst(instruction));
1105
1106 instruction->fault = fault;
1107
1108 toDecode->insts[numInst] = instruction;
1109 toDecode->size++;
1110
1111 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1112
1113 fetchStatus[tid] = TrapPending;
1114 status_change = true;
1115
1116 warn("cycle %lli: fault (%d) detected @ PC %08p", curTick, fault, PC[tid]);
1117#else // !FULL_SYSTEM
1118 warn("cycle %lli: fault (%d) detected @ PC %08p", curTick, fault, PC[tid]);
1119#endif // FULL_SYSTEM
1120 }
1121}
1122
1123template<class Impl>
1124void
1125DefaultFetch<Impl>::recvRetry()
1126{
1127 assert(cacheBlocked);
1128 if (retryPkt != NULL) {
1129 assert(retryTid != -1);
1130 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1131
1132 if (icachePort->sendTiming(retryPkt)) {
1133 fetchStatus[retryTid] = IcacheWaitResponse;
1134 retryPkt = NULL;
1135 retryTid = -1;
1136 cacheBlocked = false;
1137 }
1138 } else {
1139 assert(retryTid == -1);
1140 // Access has been squashed since it was sent out. Just clear
1141 // the cache being blocked.
1142 cacheBlocked = false;
1143 }
1144}
1145
1146///////////////////////////////////////
1147// //
1148// SMT FETCH POLICY MAINTAINED HERE //
1149// //
1150///////////////////////////////////////
1151template<class Impl>
1152int
1153DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1154{
1155 if (numThreads > 1) {
1156 switch (fetch_priority) {
1157
1158 case SingleThread:
1159 return 0;
1160
1161 case RoundRobin:
1162 return roundRobin();
1163
1164 case IQ:
1165 return iqCount();
1166
1167 case LSQ:
1168 return lsqCount();
1169
1170 case Branch:
1171 return branchCount();
1172
1173 default:
1174 return -1;
1175 }
1176 } else {
1177 int tid = *((*activeThreads).begin());
1178
1179 if (fetchStatus[tid] == Running ||
1180 fetchStatus[tid] == IcacheAccessComplete ||
1181 fetchStatus[tid] == Idle) {
1182 return tid;
1183 } else {
1184 return -1;
1185 }
1186 }
1187
1188}
1189
1190
1191template<class Impl>
1192int
1193DefaultFetch<Impl>::roundRobin()
1194{
1195 list<unsigned>::iterator pri_iter = priorityList.begin();
1196 list<unsigned>::iterator end = priorityList.end();
1197
1198 int high_pri;
1199
1200 while (pri_iter != end) {
1201 high_pri = *pri_iter;
1202
1203 assert(high_pri <= numThreads);
1204
1205 if (fetchStatus[high_pri] == Running ||
1206 fetchStatus[high_pri] == IcacheAccessComplete ||
1207 fetchStatus[high_pri] == Idle) {
1208
1209 priorityList.erase(pri_iter);
1210 priorityList.push_back(high_pri);
1211
1212 return high_pri;
1213 }
1214
1215 pri_iter++;
1216 }
1217
1218 return -1;
1219}
1220
1221template<class Impl>
1222int
1223DefaultFetch<Impl>::iqCount()
1224{
1225 priority_queue<unsigned> PQ;
1226
1227 list<unsigned>::iterator threads = (*activeThreads).begin();
1228
1229 while (threads != (*activeThreads).end()) {
1230 unsigned tid = *threads++;
1231
1232 PQ.push(fromIEW->iewInfo[tid].iqCount);
1233 }
1234
1235 while (!PQ.empty()) {
1236
1237 unsigned high_pri = PQ.top();
1238
1239 if (fetchStatus[high_pri] == Running ||
1240 fetchStatus[high_pri] == IcacheAccessComplete ||
1241 fetchStatus[high_pri] == Idle)
1242 return high_pri;
1243 else
1244 PQ.pop();
1245
1246 }
1247
1248 return -1;
1249}
1250
1251template<class Impl>
1252int
1253DefaultFetch<Impl>::lsqCount()
1254{
1255 priority_queue<unsigned> PQ;
1256
1257
1258 list<unsigned>::iterator threads = (*activeThreads).begin();
1259
1260 while (threads != (*activeThreads).end()) {
1261 unsigned tid = *threads++;
1262
1263 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1264 }
1265
1266 while (!PQ.empty()) {
1267
1268 unsigned high_pri = PQ.top();
1269
1270 if (fetchStatus[high_pri] == Running ||
1271 fetchStatus[high_pri] == IcacheAccessComplete ||
1272 fetchStatus[high_pri] == Idle)
1273 return high_pri;
1274 else
1275 PQ.pop();
1276
1277 }
1278
1279 return -1;
1280}
1281
1282template<class Impl>
1283int
1284DefaultFetch<Impl>::branchCount()
1285{
1286 list<unsigned>::iterator threads = (*activeThreads).begin();
1287 panic("Branch Count Fetch policy unimplemented\n");
1288 return *threads;
1289}
512 // Hold off fetch from getting new instructions when:
513 // Cache is blocked, or
514 // while an interrupt is pending and we're not in PAL mode, or
515 // fetch is switched out.
516 return false;
517 }
518
519 // Align the fetch PC so it's at the start of a cache block.
520 fetch_PC = icacheBlockAlignPC(fetch_PC);
521
522 // Setup the memReq to do a read of the first instruction's address.
523 // Set the appropriate read size and flags as well.
524 // Build request here.
525 RequestPtr mem_req = new Request(tid, fetch_PC, cacheBlkSize, flags,
526 fetch_PC, cpu->readCpuId(), tid);
527
528 memReq[tid] = mem_req;
529
530 // Translate the instruction request.
531 fault = cpu->translateInstReq(mem_req, cpu->thread[tid]);
532
533 // In the case of faults, the fetch stage may need to stall and wait
534 // for the ITB miss to be handled.
535
536 // If translation was successful, attempt to read the first
537 // instruction.
538 if (fault == NoFault) {
539#if 0
540 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
541 memReq[tid]->flags & UNCACHEABLE) {
542 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
543 "misspeculating path)!",
544 memReq[tid]->paddr);
545 ret_fault = TheISA::genMachineCheckFault();
546 return false;
547 }
548#endif
549
550 // Build packet here.
551 PacketPtr data_pkt = new Packet(mem_req,
552 Packet::ReadReq, Packet::Broadcast);
553 data_pkt->dataStatic(cacheData[tid]);
554
555 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
556
557 fetchedCacheLines++;
558
559 // Now do the timing access to see whether or not the instruction
560 // exists within the cache.
561 if (!icachePort->sendTiming(data_pkt)) {
562 assert(retryPkt == NULL);
563 assert(retryTid == -1);
564 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
565 fetchStatus[tid] = IcacheWaitRetry;
566 retryPkt = data_pkt;
567 retryTid = tid;
568 cacheBlocked = true;
569 return false;
570 }
571
572 DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
573
574 lastIcacheStall[tid] = curTick;
575
576 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
577 "response.\n", tid);
578
579 fetchStatus[tid] = IcacheWaitResponse;
580 } else {
581 delete mem_req;
582 memReq[tid] = NULL;
583 }
584
585 ret_fault = fault;
586 return true;
587}
588
589template <class Impl>
590inline void
591DefaultFetch<Impl>::doSquash(const Addr &new_PC, unsigned tid)
592{
593 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x.\n",
594 tid, new_PC);
595
596 PC[tid] = new_PC;
597 nextPC[tid] = new_PC + instSize;
598
599 // Clear the icache miss if it's outstanding.
600 if (fetchStatus[tid] == IcacheWaitResponse) {
601 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
602 tid);
603 memReq[tid] = NULL;
604 }
605
606 // Get rid of the retrying packet if it was from this thread.
607 if (retryTid == tid) {
608 assert(cacheBlocked);
609 cacheBlocked = false;
610 retryTid = -1;
611 retryPkt = NULL;
612 delete retryPkt->req;
613 delete retryPkt;
614 }
615
616 fetchStatus[tid] = Squashing;
617
618 ++fetchSquashCycles;
619}
620
621template<class Impl>
622void
623DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC,
624 const InstSeqNum &seq_num,
625 unsigned tid)
626{
627 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
628
629 doSquash(new_PC, tid);
630
631 // Tell the CPU to remove any instructions that are in flight between
632 // fetch and decode.
633 cpu->removeInstsUntil(seq_num, tid);
634}
635
636template<class Impl>
637bool
638DefaultFetch<Impl>::checkStall(unsigned tid) const
639{
640 bool ret_val = false;
641
642 if (cpu->contextSwitch) {
643 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
644 ret_val = true;
645 } else if (stalls[tid].decode) {
646 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
647 ret_val = true;
648 } else if (stalls[tid].rename) {
649 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
650 ret_val = true;
651 } else if (stalls[tid].iew) {
652 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
653 ret_val = true;
654 } else if (stalls[tid].commit) {
655 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
656 ret_val = true;
657 }
658
659 return ret_val;
660}
661
662template<class Impl>
663typename DefaultFetch<Impl>::FetchStatus
664DefaultFetch<Impl>::updateFetchStatus()
665{
666 //Check Running
667 list<unsigned>::iterator threads = (*activeThreads).begin();
668
669 while (threads != (*activeThreads).end()) {
670
671 unsigned tid = *threads++;
672
673 if (fetchStatus[tid] == Running ||
674 fetchStatus[tid] == Squashing ||
675 fetchStatus[tid] == IcacheAccessComplete) {
676
677 if (_status == Inactive) {
678 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
679
680 if (fetchStatus[tid] == IcacheAccessComplete) {
681 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
682 "completion\n",tid);
683 }
684
685 cpu->activateStage(O3CPU::FetchIdx);
686 }
687
688 return Active;
689 }
690 }
691
692 // Stage is switching from active to inactive, notify CPU of it.
693 if (_status == Active) {
694 DPRINTF(Activity, "Deactivating stage.\n");
695
696 cpu->deactivateStage(O3CPU::FetchIdx);
697 }
698
699 return Inactive;
700}
701
702template <class Impl>
703void
704DefaultFetch<Impl>::squash(const Addr &new_PC, unsigned tid)
705{
706 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
707
708 doSquash(new_PC, tid);
709
710 // Tell the CPU to remove any instructions that are not in the ROB.
711 cpu->removeInstsNotInROB(tid);
712}
713
714template <class Impl>
715void
716DefaultFetch<Impl>::tick()
717{
718 list<unsigned>::iterator threads = (*activeThreads).begin();
719 bool status_change = false;
720
721 wroteToTimeBuffer = false;
722
723 while (threads != (*activeThreads).end()) {
724 unsigned tid = *threads++;
725
726 // Check the signals for each thread to determine the proper status
727 // for each thread.
728 bool updated_status = checkSignalsAndUpdate(tid);
729 status_change = status_change || updated_status;
730 }
731
732 DPRINTF(Fetch, "Running stage.\n");
733
734 // Reset the number of the instruction we're fetching.
735 numInst = 0;
736
737#if FULL_SYSTEM
738 if (fromCommit->commitInfo[0].interruptPending) {
739 interruptPending = true;
740 }
741
742 if (fromCommit->commitInfo[0].clearInterrupt) {
743 interruptPending = false;
744 }
745#endif
746
747 for (threadFetched = 0; threadFetched < numFetchingThreads;
748 threadFetched++) {
749 // Fetch each of the actively fetching threads.
750 fetch(status_change);
751 }
752
753 // Record number of instructions fetched this cycle for distribution.
754 fetchNisnDist.sample(numInst);
755
756 if (status_change) {
757 // Change the fetch stage status if there was a status change.
758 _status = updateFetchStatus();
759 }
760
761 // If there was activity this cycle, inform the CPU of it.
762 if (wroteToTimeBuffer || cpu->contextSwitch) {
763 DPRINTF(Activity, "Activity this cycle.\n");
764
765 cpu->activityThisCycle();
766 }
767}
768
769template <class Impl>
770bool
771DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
772{
773 // Update the per thread stall statuses.
774 if (fromDecode->decodeBlock[tid]) {
775 stalls[tid].decode = true;
776 }
777
778 if (fromDecode->decodeUnblock[tid]) {
779 assert(stalls[tid].decode);
780 assert(!fromDecode->decodeBlock[tid]);
781 stalls[tid].decode = false;
782 }
783
784 if (fromRename->renameBlock[tid]) {
785 stalls[tid].rename = true;
786 }
787
788 if (fromRename->renameUnblock[tid]) {
789 assert(stalls[tid].rename);
790 assert(!fromRename->renameBlock[tid]);
791 stalls[tid].rename = false;
792 }
793
794 if (fromIEW->iewBlock[tid]) {
795 stalls[tid].iew = true;
796 }
797
798 if (fromIEW->iewUnblock[tid]) {
799 assert(stalls[tid].iew);
800 assert(!fromIEW->iewBlock[tid]);
801 stalls[tid].iew = false;
802 }
803
804 if (fromCommit->commitBlock[tid]) {
805 stalls[tid].commit = true;
806 }
807
808 if (fromCommit->commitUnblock[tid]) {
809 assert(stalls[tid].commit);
810 assert(!fromCommit->commitBlock[tid]);
811 stalls[tid].commit = false;
812 }
813
814 // Check squash signals from commit.
815 if (fromCommit->commitInfo[tid].squash) {
816
817 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
818 "from commit.\n",tid);
819
820 // In any case, squash.
821 squash(fromCommit->commitInfo[tid].nextPC,tid);
822
823 // Also check if there's a mispredict that happened.
824 if (fromCommit->commitInfo[tid].branchMispredict) {
825 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
826 fromCommit->commitInfo[tid].nextPC,
827 fromCommit->commitInfo[tid].branchTaken,
828 tid);
829 } else {
830 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
831 tid);
832 }
833
834 return true;
835 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
836 // Update the branch predictor if it wasn't a squashed instruction
837 // that was broadcasted.
838 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
839 }
840
841 // Check ROB squash signals from commit.
842 if (fromCommit->commitInfo[tid].robSquashing) {
843 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
844
845 // Continue to squash.
846 fetchStatus[tid] = Squashing;
847
848 return true;
849 }
850
851 // Check squash signals from decode.
852 if (fromDecode->decodeInfo[tid].squash) {
853 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
854 "from decode.\n",tid);
855
856 // Update the branch predictor.
857 if (fromDecode->decodeInfo[tid].branchMispredict) {
858 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
859 fromDecode->decodeInfo[tid].nextPC,
860 fromDecode->decodeInfo[tid].branchTaken,
861 tid);
862 } else {
863 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
864 tid);
865 }
866
867 if (fetchStatus[tid] != Squashing) {
868 // Squash unless we're already squashing
869 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
870 fromDecode->decodeInfo[tid].doneSeqNum,
871 tid);
872
873 return true;
874 }
875 }
876
877 if (checkStall(tid) && fetchStatus[tid] != IcacheWaitResponse) {
878 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
879
880 fetchStatus[tid] = Blocked;
881
882 return true;
883 }
884
885 if (fetchStatus[tid] == Blocked ||
886 fetchStatus[tid] == Squashing) {
887 // Switch status to running if fetch isn't being told to block or
888 // squash this cycle.
889 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
890 tid);
891
892 fetchStatus[tid] = Running;
893
894 return true;
895 }
896
897 // If we've reached this point, we have not gotten any signals that
898 // cause fetch to change its status. Fetch remains the same as before.
899 return false;
900}
901
902template<class Impl>
903void
904DefaultFetch<Impl>::fetch(bool &status_change)
905{
906 //////////////////////////////////////////
907 // Start actual fetch
908 //////////////////////////////////////////
909 int tid = getFetchingThread(fetchPolicy);
910
911 if (tid == -1) {
912 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
913
914 // Breaks looping condition in tick()
915 threadFetched = numFetchingThreads;
916 return;
917 }
918
919 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
920
921 // The current PC.
922 Addr &fetch_PC = PC[tid];
923
924 // Fault code for memory access.
925 Fault fault = NoFault;
926
927 // If returning from the delay of a cache miss, then update the status
928 // to running, otherwise do the cache access. Possibly move this up
929 // to tick() function.
930 if (fetchStatus[tid] == IcacheAccessComplete) {
931 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
932 tid);
933
934 fetchStatus[tid] = Running;
935 status_change = true;
936 } else if (fetchStatus[tid] == Running) {
937 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
938 "instruction, starting at PC %08p.\n",
939 tid, fetch_PC);
940
941 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
942 if (!fetch_success) {
943 if (cacheBlocked) {
944 ++icacheStallCycles;
945 } else {
946 ++fetchMiscStallCycles;
947 }
948 return;
949 }
950 } else {
951 if (fetchStatus[tid] == Idle) {
952 ++fetchIdleCycles;
953 } else if (fetchStatus[tid] == Blocked) {
954 ++fetchBlockedCycles;
955 } else if (fetchStatus[tid] == Squashing) {
956 ++fetchSquashCycles;
957 } else if (fetchStatus[tid] == IcacheWaitResponse) {
958 ++icacheStallCycles;
959 }
960
961 // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
962 // fetch should do nothing.
963 return;
964 }
965
966 ++fetchCycles;
967
968 // If we had a stall due to an icache miss, then return.
969 if (fetchStatus[tid] == IcacheWaitResponse) {
970 ++icacheStallCycles;
971 status_change = true;
972 return;
973 }
974
975 Addr next_PC = fetch_PC;
976 InstSeqNum inst_seq;
977 MachInst inst;
978 ExtMachInst ext_inst;
979 // @todo: Fix this hack.
980 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
981
982 if (fault == NoFault) {
983 // If the read of the first instruction was successful, then grab the
984 // instructions from the rest of the cache line and put them into the
985 // queue heading to decode.
986
987 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
988 "decode.\n",tid);
989
990 // Need to keep track of whether or not a predicted branch
991 // ended this fetch block.
992 bool predicted_branch = false;
993
994 for (;
995 offset < cacheBlkSize &&
996 numInst < fetchWidth &&
997 !predicted_branch;
998 ++numInst) {
999
1000 // Get a sequence number.
1001 inst_seq = cpu->getAndIncrementInstSeq();
1002
1003 // Make sure this is a valid index.
1004 assert(offset <= cacheBlkSize - instSize);
1005
1006 // Get the instruction from the array of the cache line.
1007 inst = gtoh(*reinterpret_cast<MachInst *>
1008 (&cacheData[tid][offset]));
1009
1010 ext_inst = TheISA::makeExtMI(inst, fetch_PC);
1011
1012 // Create a new DynInst from the instruction fetched.
1013 DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
1014 next_PC,
1015 inst_seq, cpu);
1016 instruction->setTid(tid);
1017
1018 instruction->setASID(tid);
1019
1020 instruction->setThreadState(cpu->thread[tid]);
1021
1022 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1023 "[sn:%lli]\n",
1024 tid, instruction->readPC(), inst_seq);
1025
1026 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1027 tid, instruction->staticInst->disassemble(fetch_PC));
1028
1029 instruction->traceData =
1030 Trace::getInstRecord(curTick, cpu->tcBase(tid), cpu,
1031 instruction->staticInst,
1032 instruction->readPC(),tid);
1033
1034 predicted_branch = lookupAndUpdateNextPC(instruction, next_PC);
1035
1036 // Add instruction to the CPU's list of instructions.
1037 instruction->setInstListIt(cpu->addInst(instruction));
1038
1039 // Write the instruction to the first slot in the queue
1040 // that heads to decode.
1041 toDecode->insts[numInst] = instruction;
1042
1043 toDecode->size++;
1044
1045 // Increment stat of fetched instructions.
1046 ++fetchedInsts;
1047
1048 // Move to the next instruction, unless we have a branch.
1049 fetch_PC = next_PC;
1050
1051 if (instruction->isQuiesce()) {
1052 warn("cycle %lli: Quiesce instruction encountered, halting fetch!",
1053 curTick);
1054 fetchStatus[tid] = QuiescePending;
1055 ++numInst;
1056 status_change = true;
1057 break;
1058 }
1059
1060 offset+= instSize;
1061 }
1062 }
1063
1064 if (numInst > 0) {
1065 wroteToTimeBuffer = true;
1066 }
1067
1068 // Now that fetching is completed, update the PC to signify what the next
1069 // cycle will be.
1070 if (fault == NoFault) {
1071 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n",tid, next_PC);
1072
1073#if THE_ISA == ALPHA_ISA
1074 PC[tid] = next_PC;
1075 nextPC[tid] = next_PC + instSize;
1076#else
1077 PC[tid] = next_PC;
1078 nextPC[tid] = next_PC + instSize;
1079 nextPC[tid] = next_PC + instSize;
1080
1081 thread->setNextPC(thread->readNextNPC());
1082 thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));
1083#endif
1084 } else {
1085 // We shouldn't be in an icache miss and also have a fault (an ITB
1086 // miss)
1087 if (fetchStatus[tid] == IcacheWaitResponse) {
1088 panic("Fetch should have exited prior to this!");
1089 }
1090
1091 // Send the fault to commit. This thread will not do anything
1092 // until commit handles the fault. The only other way it can
1093 // wake up is if a squash comes along and changes the PC.
1094#if FULL_SYSTEM
1095 assert(numInst != fetchWidth);
1096 // Get a sequence number.
1097 inst_seq = cpu->getAndIncrementInstSeq();
1098 // We will use a nop in order to carry the fault.
1099 ext_inst = TheISA::NoopMachInst;
1100
1101 // Create a new DynInst from the dummy nop.
1102 DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
1103 next_PC,
1104 inst_seq, cpu);
1105 instruction->setPredTarg(next_PC + instSize);
1106 instruction->setTid(tid);
1107
1108 instruction->setASID(tid);
1109
1110 instruction->setThreadState(cpu->thread[tid]);
1111
1112 instruction->traceData = NULL;
1113
1114 instruction->setInstListIt(cpu->addInst(instruction));
1115
1116 instruction->fault = fault;
1117
1118 toDecode->insts[numInst] = instruction;
1119 toDecode->size++;
1120
1121 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1122
1123 fetchStatus[tid] = TrapPending;
1124 status_change = true;
1125
1126 warn("cycle %lli: fault (%d) detected @ PC %08p", curTick, fault, PC[tid]);
1127#else // !FULL_SYSTEM
1128 warn("cycle %lli: fault (%d) detected @ PC %08p", curTick, fault, PC[tid]);
1129#endif // FULL_SYSTEM
1130 }
1131}
1132
1133template<class Impl>
1134void
1135DefaultFetch<Impl>::recvRetry()
1136{
1137 assert(cacheBlocked);
1138 if (retryPkt != NULL) {
1139 assert(retryTid != -1);
1140 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1141
1142 if (icachePort->sendTiming(retryPkt)) {
1143 fetchStatus[retryTid] = IcacheWaitResponse;
1144 retryPkt = NULL;
1145 retryTid = -1;
1146 cacheBlocked = false;
1147 }
1148 } else {
1149 assert(retryTid == -1);
1150 // Access has been squashed since it was sent out. Just clear
1151 // the cache being blocked.
1152 cacheBlocked = false;
1153 }
1154}
1155
1156///////////////////////////////////////
1157// //
1158// SMT FETCH POLICY MAINTAINED HERE //
1159// //
1160///////////////////////////////////////
1161template<class Impl>
1162int
1163DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1164{
1165 if (numThreads > 1) {
1166 switch (fetch_priority) {
1167
1168 case SingleThread:
1169 return 0;
1170
1171 case RoundRobin:
1172 return roundRobin();
1173
1174 case IQ:
1175 return iqCount();
1176
1177 case LSQ:
1178 return lsqCount();
1179
1180 case Branch:
1181 return branchCount();
1182
1183 default:
1184 return -1;
1185 }
1186 } else {
1187 int tid = *((*activeThreads).begin());
1188
1189 if (fetchStatus[tid] == Running ||
1190 fetchStatus[tid] == IcacheAccessComplete ||
1191 fetchStatus[tid] == Idle) {
1192 return tid;
1193 } else {
1194 return -1;
1195 }
1196 }
1197
1198}
1199
1200
1201template<class Impl>
1202int
1203DefaultFetch<Impl>::roundRobin()
1204{
1205 list<unsigned>::iterator pri_iter = priorityList.begin();
1206 list<unsigned>::iterator end = priorityList.end();
1207
1208 int high_pri;
1209
1210 while (pri_iter != end) {
1211 high_pri = *pri_iter;
1212
1213 assert(high_pri <= numThreads);
1214
1215 if (fetchStatus[high_pri] == Running ||
1216 fetchStatus[high_pri] == IcacheAccessComplete ||
1217 fetchStatus[high_pri] == Idle) {
1218
1219 priorityList.erase(pri_iter);
1220 priorityList.push_back(high_pri);
1221
1222 return high_pri;
1223 }
1224
1225 pri_iter++;
1226 }
1227
1228 return -1;
1229}
1230
1231template<class Impl>
1232int
1233DefaultFetch<Impl>::iqCount()
1234{
1235 priority_queue<unsigned> PQ;
1236
1237 list<unsigned>::iterator threads = (*activeThreads).begin();
1238
1239 while (threads != (*activeThreads).end()) {
1240 unsigned tid = *threads++;
1241
1242 PQ.push(fromIEW->iewInfo[tid].iqCount);
1243 }
1244
1245 while (!PQ.empty()) {
1246
1247 unsigned high_pri = PQ.top();
1248
1249 if (fetchStatus[high_pri] == Running ||
1250 fetchStatus[high_pri] == IcacheAccessComplete ||
1251 fetchStatus[high_pri] == Idle)
1252 return high_pri;
1253 else
1254 PQ.pop();
1255
1256 }
1257
1258 return -1;
1259}
1260
1261template<class Impl>
1262int
1263DefaultFetch<Impl>::lsqCount()
1264{
1265 priority_queue<unsigned> PQ;
1266
1267
1268 list<unsigned>::iterator threads = (*activeThreads).begin();
1269
1270 while (threads != (*activeThreads).end()) {
1271 unsigned tid = *threads++;
1272
1273 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1274 }
1275
1276 while (!PQ.empty()) {
1277
1278 unsigned high_pri = PQ.top();
1279
1280 if (fetchStatus[high_pri] == Running ||
1281 fetchStatus[high_pri] == IcacheAccessComplete ||
1282 fetchStatus[high_pri] == Idle)
1283 return high_pri;
1284 else
1285 PQ.pop();
1286
1287 }
1288
1289 return -1;
1290}
1291
1292template<class Impl>
1293int
1294DefaultFetch<Impl>::branchCount()
1295{
1296 list<unsigned>::iterator threads = (*activeThreads).begin();
1297 panic("Branch Count Fetch policy unimplemented\n");
1298 return *threads;
1299}