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