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