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