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