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