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