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