Deleted Added
sdiff udiff text old ( 2654:9559cfa91b9d ) new ( 2665:a124942bacb8 )
full compact
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the

--- 8 unchanged lines hidden (view full) ---

19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include "arch/isa_traits.hh"
30#include "cpu/exetrace.hh"
31#include "cpu/o3/fetch.hh"
32#include "mem/base_mem.hh"
33#include "mem/mem_interface.hh"
34#include "mem/mem_req.hh"
35#include "sim/byteswap.hh"
36#include "sim/root.hh"
37
38#if FULL_SYSTEM
39#include "arch/tlb.hh"
40#include "arch/vtophys.hh"
41#include "base/remote_gdb.hh"
42#include "mem/functional/memory_control.hh"
43#include "mem/functional/physical.hh"
44#include "sim/system.hh"
45#else // !FULL_SYSTEM
46#include "mem/functional/functional.hh"
47#endif // FULL_SYSTEM
48
49#include <algorithm>
50
51using namespace std;
52
53template<class Impl>
54DefaultFetch<Impl>::CacheCompletionEvent::CacheCompletionEvent(MemReqPtr &_req,
55 DefaultFetch *_fetch)
56 : Event(&mainEventQueue, Delayed_Writeback_Pri),
57 req(_req),
58 fetch(_fetch)
59{
60 this->setFlags(Event::AutoDelete);
61}
62
63template<class Impl>
64void
65DefaultFetch<Impl>::CacheCompletionEvent::process()
66{
67 fetch->processCacheCompletion(req);
68}
69
70template<class Impl>
71const char *
72DefaultFetch<Impl>::CacheCompletionEvent::description()
73{
74 return "DefaultFetch cache completion event";
75}
76
77template<class Impl>
78DefaultFetch<Impl>::DefaultFetch(Params *params)
79 : icacheInterface(params->icacheInterface),
80 branchPred(params),
81 decodeToFetchDelay(params->decodeToFetchDelay),
82 renameToFetchDelay(params->renameToFetchDelay),
83 iewToFetchDelay(params->iewToFetchDelay),
84 commitToFetchDelay(params->commitToFetchDelay),
85 fetchWidth(params->fetchWidth),
86 numThreads(params->numberOfThreads),
87 numFetchingThreads(params->smtNumFetchingThreads),
88 interruptPending(false)
89{
90 if (numThreads > Impl::MaxThreads)
91 fatal("numThreads is not a valid value\n");
92
93 DPRINTF(Fetch, "Fetch constructor called\n");
94
95 // Set fetch stage's status to inactive.
96 _status = Inactive;
97
98 string policy = params->smtFetchPolicy;
99
100 // Convert string to lowercase
101 std::transform(policy.begin(), policy.end(), policy.begin(),
102 (int(*)(int)) tolower);
103
104 // Figure out fetch policy
105 if (policy == "singlethread") {
106 fetchPolicy = SingleThread;
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 // Size of cache block.
125 cacheBlkSize = icacheInterface ? icacheInterface->getBlockSize() : 64;
126
127 // Create mask to get rid of offset bits.
128 cacheBlkMask = (cacheBlkSize - 1);
129
130 for (int tid=0; tid < numThreads; tid++) {
131
132 fetchStatus[tid] = Running;
133
134 priorityList.push_back(tid);
135
136 // Create a new memory request.
137 memReq[tid] = NULL;
138
139 // Create space to store a cache line.
140 cacheData[tid] = new uint8_t[cacheBlkSize];
141
142 stalls[tid].decode = 0;
143 stalls[tid].rename = 0;
144 stalls[tid].iew = 0;
145 stalls[tid].commit = 0;
146 }
147
148 // Get the size of an instruction.
149 instSize = sizeof(MachInst);
150}
151
152template <class Impl>
153std::string
154DefaultFetch<Impl>::name() const
155{
156 return cpu->name() + ".fetch";
157}
158
159template <class Impl>
160void
161DefaultFetch<Impl>::regStats()
162{
163 icacheStallCycles
164 .name(name() + ".FETCH:icacheStallCycles")
165 .desc("Number of cycles fetch is stalled on an Icache miss")
166 .prereq(icacheStallCycles);
167
168 fetchedInsts
169 .name(name() + ".FETCH:Insts")
170 .desc("Number of instructions fetch has processed")
171 .prereq(fetchedInsts);
172
173 fetchedBranches
174 .name(name() + ".FETCH:Branches")
175 .desc("Number of branches that fetch encountered")
176 .prereq(fetchedBranches);
177
178 predictedBranches
179 .name(name() + ".FETCH:predictedBranches")
180 .desc("Number of branches that fetch has predicted taken")
181 .prereq(predictedBranches);
182
183 fetchCycles
184 .name(name() + ".FETCH:Cycles")
185 .desc("Number of cycles fetch has run and was not squashing or"
186 " blocked")
187 .prereq(fetchCycles);
188
189 fetchSquashCycles
190 .name(name() + ".FETCH:SquashCycles")
191 .desc("Number of cycles fetch has spent squashing")
192 .prereq(fetchSquashCycles);
193
194 fetchIdleCycles
195 .name(name() + ".FETCH:IdleCycles")
196 .desc("Number of cycles fetch was idle")
197 .prereq(fetchIdleCycles);
198
199 fetchBlockedCycles
200 .name(name() + ".FETCH:BlockedCycles")
201 .desc("Number of cycles fetch has spent blocked")
202 .prereq(fetchBlockedCycles);
203
204 fetchedCacheLines
205 .name(name() + ".FETCH:CacheLines")
206 .desc("Number of cache lines fetched")
207 .prereq(fetchedCacheLines);
208
209 fetchMiscStallCycles
210 .name(name() + ".FETCH:MiscStallCycles")
211 .desc("Number of cycles fetch has spent waiting on interrupts, or "
212 "bad addresses, or out of MSHRs")
213 .prereq(fetchMiscStallCycles);
214
215 fetchIcacheSquashes
216 .name(name() + ".FETCH:IcacheSquashes")
217 .desc("Number of outstanding Icache misses that were squashed")
218 .prereq(fetchIcacheSquashes);
219
220 fetchNisnDist
221 .init(/* base value */ 0,
222 /* last value */ fetchWidth,
223 /* bucket size */ 1)
224 .name(name() + ".FETCH:rateDist")
225 .desc("Number of instructions fetched each cycle (Total)")
226 .flags(Stats::pdf);
227
228 idleRate
229 .name(name() + ".FETCH:idleRate")
230 .desc("Percent of cycles fetch was idle")
231 .prereq(idleRate);
232 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
233
234 branchRate
235 .name(name() + ".FETCH:branchRate")
236 .desc("Number of branch fetches per cycle")
237 .flags(Stats::total);
238 branchRate = predictedBranches / cpu->numCycles;
239
240 fetchRate
241 .name(name() + ".FETCH:rate")
242 .desc("Number of inst fetches per cycle")
243 .flags(Stats::total);
244 fetchRate = fetchedInsts / cpu->numCycles;
245
246 branchPred.regStats();
247}
248
249template<class Impl>
250void
251DefaultFetch<Impl>::setCPU(FullCPU *cpu_ptr)
252{
253 DPRINTF(Fetch, "Setting the CPU pointer.\n");
254 cpu = cpu_ptr;
255
256 // Fetch needs to start fetching instructions at the very beginning,
257 // so it must start up in active state.
258 switchToActive();
259}
260
261template<class Impl>
262void
263DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
264{
265 DPRINTF(Fetch, "Setting the time buffer pointer.\n");
266 timeBuffer = time_buffer;
267
268 // Create wires to get information from proper places in time buffer.
269 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
270 fromRename = timeBuffer->getWire(-renameToFetchDelay);
271 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
272 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
273}
274
275template<class Impl>
276void
277DefaultFetch<Impl>::setActiveThreads(list<unsigned> *at_ptr)
278{
279 DPRINTF(Fetch, "Setting active threads list pointer.\n");
280 activeThreads = at_ptr;
281}
282
283template<class Impl>
284void
285DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
286{
287 DPRINTF(Fetch, "Setting the fetch queue pointer.\n");
288 fetchQueue = fq_ptr;
289
290 // Create wire to write information to proper place in fetch queue.
291 toDecode = fetchQueue->getWire(0);
292}
293
294#if 0
295template<class Impl>
296void
297DefaultFetch<Impl>::setPageTable(PageTable *pt_ptr)
298{
299 DPRINTF(Fetch, "Setting the page table pointer.\n");
300#if !FULL_SYSTEM
301 pTable = pt_ptr;
302#endif
303}
304#endif
305
306template<class Impl>
307void
308DefaultFetch<Impl>::initStage()
309{
310 for (int tid = 0; tid < numThreads; tid++) {
311 PC[tid] = cpu->readPC(tid);
312 nextPC[tid] = cpu->readNextPC(tid);
313 }
314}
315
316template<class Impl>
317void
318DefaultFetch<Impl>::processCacheCompletion(MemReqPtr &req)
319{
320 unsigned tid = req->thread_num;
321
322 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
323
324 // Only change the status if it's still waiting on the icache access
325 // to return.
326 // Can keep track of how many cache accesses go unused due to
327 // misspeculation here.
328 if (fetchStatus[tid] != IcacheMissStall ||
329 req != memReq[tid] ||
330 isSwitchedOut()) {
331 ++fetchIcacheSquashes;
332 return;
333 }
334
335 // Wake up the CPU (if it went to sleep and was waiting on this completion
336 // event).
337 cpu->wakeCPU();
338
339 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
340 tid);
341
342 switchToActive();
343
344 // Only switch to IcacheMissComplete if we're not stalled as well.
345 if (checkStall(tid)) {
346 fetchStatus[tid] = Blocked;
347 } else {
348 fetchStatus[tid] = IcacheMissComplete;
349 }
350
351// memcpy(cacheData[tid], memReq[tid]->data, memReq[tid]->size);
352
353 // Reset the mem req to NULL.
354 memReq[tid] = NULL;
355}
356
357template <class Impl>
358void
359DefaultFetch<Impl>::switchOut()
360{
361 switchedOut = true;
362 cpu->signalSwitched();
363}
364
365template <class Impl>
366void
367DefaultFetch<Impl>::doSwitchOut()
368{
369 branchPred.switchOut();
370}
371
372template <class Impl>
373void
374DefaultFetch<Impl>::takeOverFrom()
375{
376 // Reset all state
377 for (int i = 0; i < Impl::MaxThreads; ++i) {
378 stalls[i].decode = 0;
379 stalls[i].rename = 0;
380 stalls[i].iew = 0;
381 stalls[i].commit = 0;
382 PC[i] = cpu->readPC(i);
383 nextPC[i] = cpu->readNextPC(i);
384 fetchStatus[i] = Running;
385 }
386 numInst = 0;
387 wroteToTimeBuffer = false;
388 _status = Inactive;
389 switchedOut = false;
390 branchPred.takeOverFrom();
391}
392
393template <class Impl>
394void
395DefaultFetch<Impl>::wakeFromQuiesce()
396{
397 DPRINTF(Fetch, "Waking up from quiesce\n");
398 // Hopefully this is safe
399 fetchStatus[0] = Running;
400}
401
402template <class Impl>
403inline void
404DefaultFetch<Impl>::switchToActive()
405{
406 if (_status == Inactive) {
407 DPRINTF(Activity, "Activating stage.\n");
408
409 cpu->activateStage(FullCPU::FetchIdx);
410
411 _status = Active;
412 }
413}
414
415template <class Impl>
416inline void
417DefaultFetch<Impl>::switchToInactive()
418{
419 if (_status == Active) {
420 DPRINTF(Activity, "Deactivating stage.\n");
421
422 cpu->deactivateStage(FullCPU::FetchIdx);
423
424 _status = Inactive;
425 }
426}
427
428template <class Impl>
429bool
430DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC)
431{
432 // Do branch prediction check here.
433 // A bit of a misnomer...next_PC is actually the current PC until
434 // this function updates it.
435 bool predict_taken;
436
437 if (!inst->isControl()) {
438 next_PC = next_PC + instSize;
439 inst->setPredTarg(next_PC);
440 return false;
441 }
442
443 predict_taken = branchPred.predict(inst, next_PC, inst->threadNumber);
444
445 ++fetchedBranches;
446
447 if (predict_taken) {
448 ++predictedBranches;
449 }
450
451 return predict_taken;
452}
453
454template <class Impl>
455bool
456DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
457{
458 Fault fault = NoFault;
459
460#if FULL_SYSTEM
461 // Flag to say whether or not address is physical addr.
462 unsigned flags = cpu->inPalMode(fetch_PC) ? PHYSICAL : 0;
463#else
464 unsigned flags = 0;
465#endif // FULL_SYSTEM
466
467 if (interruptPending && flags == 0 || switchedOut) {
468 // Hold off fetch from getting new instructions while an interrupt
469 // is pending.
470 return false;
471 }
472
473 // Align the fetch PC so it's at the start of a cache block.
474 fetch_PC = icacheBlockAlignPC(fetch_PC);
475
476 // Setup the memReq to do a read of the first instruction's address.
477 // Set the appropriate read size and flags as well.
478 memReq[tid] = new MemReq();
479
480 memReq[tid]->asid = tid;
481 memReq[tid]->thread_num = tid;
482 memReq[tid]->data = new uint8_t[64];
483 memReq[tid]->xc = cpu->xcBase(tid);
484 memReq[tid]->cmd = Read;
485 memReq[tid]->reset(fetch_PC, cacheBlkSize, flags);
486
487 // Translate the instruction request.
488//#if FULL_SYSTEM
489 fault = cpu->translateInstReq(memReq[tid]);
490//#else
491// fault = pTable->translate(memReq[tid]);
492//#endif
493
494 // In the case of faults, the fetch stage may need to stall and wait
495 // for the ITB miss to be handled.
496
497 // If translation was successful, attempt to read the first
498 // instruction.
499 if (fault == NoFault) {
500#if FULL_SYSTEM
501 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
502 memReq[tid]->flags & UNCACHEABLE) {
503 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
504 "misspeculating path)!",
505 memReq[tid]->paddr);
506 ret_fault = TheISA::genMachineCheckFault();
507 return false;
508 }
509#endif
510
511 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
512 fault = cpu->mem->read(memReq[tid], cacheData[tid]);
513 // This read may change when the mem interface changes.
514
515 // Now do the timing access to see whether or not the instruction
516 // exists within the cache.
517 if (icacheInterface && !icacheInterface->isBlocked()) {
518 DPRINTF(Fetch, "Doing cache access.\n");
519
520 memReq[tid]->completionEvent = NULL;
521
522 memReq[tid]->time = curTick;
523
524 MemAccessResult result = icacheInterface->access(memReq[tid]);
525
526 fetchedCacheLines++;
527
528 // If the cache missed, then schedule an event to wake
529 // up this stage once the cache miss completes.
530 // @todo: Possibly allow for longer than 1 cycle cache hits.
531 if (result != MA_HIT && icacheInterface->doEvents()) {
532
533 memReq[tid]->completionEvent =
534 new CacheCompletionEvent(memReq[tid], this);
535
536 lastIcacheStall[tid] = curTick;
537
538 DPRINTF(Activity, "[tid:%i]: Activity: Stalling due to I-cache "
539 "miss.\n", tid);
540
541 fetchStatus[tid] = IcacheMissStall;
542 } else {
543 DPRINTF(Fetch, "[tid:%i]: I-Cache hit. Doing Instruction "
544 "read.\n", tid);
545
546// memcpy(cacheData[tid], memReq[tid]->data, memReq[tid]->size);
547 }
548 } else {
549 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
550 ret_fault = NoFault;
551 return false;
552 }
553 }
554
555 ret_fault = fault;
556 return true;
557}
558
559template <class Impl>
560inline void
561DefaultFetch<Impl>::doSquash(const Addr &new_PC, unsigned tid)
562{
563 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x.\n",
564 tid, new_PC);
565
566 PC[tid] = new_PC;
567 nextPC[tid] = new_PC + instSize;
568
569 // Clear the icache miss if it's outstanding.
570 if (fetchStatus[tid] == IcacheMissStall && icacheInterface) {
571 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
572 tid);
573 memReq[tid] = NULL;
574 }
575
576 fetchStatus[tid] = Squashing;
577
578 ++fetchSquashCycles;
579}
580
581template<class Impl>
582void
583DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC,
584 const InstSeqNum &seq_num,
585 unsigned tid)
586{
587 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
588
589 doSquash(new_PC, tid);
590
591 // Tell the CPU to remove any instructions that are in flight between
592 // fetch and decode.
593 cpu->removeInstsUntil(seq_num, tid);
594}
595
596template<class Impl>
597bool
598DefaultFetch<Impl>::checkStall(unsigned tid) const
599{
600 bool ret_val = false;
601
602 if (cpu->contextSwitch) {
603 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
604 ret_val = true;
605 } else if (stalls[tid].decode) {
606 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
607 ret_val = true;
608 } else if (stalls[tid].rename) {
609 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
610 ret_val = true;
611 } else if (stalls[tid].iew) {
612 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
613 ret_val = true;
614 } else if (stalls[tid].commit) {
615 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
616 ret_val = true;
617 }
618
619 return ret_val;
620}
621
622template<class Impl>
623typename DefaultFetch<Impl>::FetchStatus
624DefaultFetch<Impl>::updateFetchStatus()
625{
626 //Check Running
627 list<unsigned>::iterator threads = (*activeThreads).begin();
628
629 while (threads != (*activeThreads).end()) {
630
631 unsigned tid = *threads++;
632
633 if (fetchStatus[tid] == Running ||
634 fetchStatus[tid] == Squashing ||
635 fetchStatus[tid] == IcacheMissComplete) {
636
637 if (_status == Inactive) {
638 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
639
640 if (fetchStatus[tid] == IcacheMissComplete) {
641 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
642 "completion\n",tid);
643 }
644
645 cpu->activateStage(FullCPU::FetchIdx);
646 }
647
648 return Active;
649 }
650 }
651
652 // Stage is switching from active to inactive, notify CPU of it.
653 if (_status == Active) {
654 DPRINTF(Activity, "Deactivating stage.\n");
655
656 cpu->deactivateStage(FullCPU::FetchIdx);
657 }
658
659 return Inactive;
660}
661
662template <class Impl>
663void
664DefaultFetch<Impl>::squash(const Addr &new_PC, unsigned tid)
665{
666 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
667
668 doSquash(new_PC, tid);
669
670 // Tell the CPU to remove any instructions that are not in the ROB.
671 cpu->removeInstsNotInROB(tid);
672}
673
674template <class Impl>
675void
676DefaultFetch<Impl>::tick()
677{
678 list<unsigned>::iterator threads = (*activeThreads).begin();
679 bool status_change = false;
680
681 wroteToTimeBuffer = false;
682
683 while (threads != (*activeThreads).end()) {
684 unsigned tid = *threads++;
685
686 // Check the signals for each thread to determine the proper status
687 // for each thread.
688 bool updated_status = checkSignalsAndUpdate(tid);
689 status_change = status_change || updated_status;
690 }
691
692 DPRINTF(Fetch, "Running stage.\n");
693
694 // Reset the number of the instruction we're fetching.
695 numInst = 0;
696
697 if (fromCommit->commitInfo[0].interruptPending) {
698 interruptPending = true;
699 }
700 if (fromCommit->commitInfo[0].clearInterrupt) {
701 interruptPending = false;
702 }
703
704 for (threadFetched = 0; threadFetched < numFetchingThreads;
705 threadFetched++) {
706 // Fetch each of the actively fetching threads.
707 fetch(status_change);
708 }
709
710 // Record number of instructions fetched this cycle for distribution.
711 fetchNisnDist.sample(numInst);
712
713 if (status_change) {
714 // Change the fetch stage status if there was a status change.
715 _status = updateFetchStatus();
716 }
717
718 // If there was activity this cycle, inform the CPU of it.
719 if (wroteToTimeBuffer || cpu->contextSwitch) {
720 DPRINTF(Activity, "Activity this cycle.\n");
721
722 cpu->activityThisCycle();
723 }
724}
725
726template <class Impl>
727bool
728DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
729{
730 // Update the per thread stall statuses.
731 if (fromDecode->decodeBlock[tid]) {
732 stalls[tid].decode = true;
733 }
734
735 if (fromDecode->decodeUnblock[tid]) {
736 assert(stalls[tid].decode);
737 assert(!fromDecode->decodeBlock[tid]);
738 stalls[tid].decode = false;
739 }
740
741 if (fromRename->renameBlock[tid]) {
742 stalls[tid].rename = true;
743 }
744
745 if (fromRename->renameUnblock[tid]) {
746 assert(stalls[tid].rename);
747 assert(!fromRename->renameBlock[tid]);
748 stalls[tid].rename = false;
749 }
750
751 if (fromIEW->iewBlock[tid]) {
752 stalls[tid].iew = true;
753 }
754
755 if (fromIEW->iewUnblock[tid]) {
756 assert(stalls[tid].iew);
757 assert(!fromIEW->iewBlock[tid]);
758 stalls[tid].iew = false;
759 }
760
761 if (fromCommit->commitBlock[tid]) {
762 stalls[tid].commit = true;
763 }
764
765 if (fromCommit->commitUnblock[tid]) {
766 assert(stalls[tid].commit);
767 assert(!fromCommit->commitBlock[tid]);
768 stalls[tid].commit = false;
769 }
770
771 // Check squash signals from commit.
772 if (fromCommit->commitInfo[tid].squash) {
773
774 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
775 "from commit.\n",tid);
776
777 // In any case, squash.
778 squash(fromCommit->commitInfo[tid].nextPC,tid);
779
780 // Also check if there's a mispredict that happened.
781 if (fromCommit->commitInfo[tid].branchMispredict) {
782 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
783 fromCommit->commitInfo[tid].nextPC,
784 fromCommit->commitInfo[tid].branchTaken,
785 tid);
786 } else {
787 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
788 tid);
789 }
790
791 return true;
792 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
793 // Update the branch predictor if it wasn't a squashed instruction
794 // that was broadcasted.
795 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
796 }
797
798 // Check ROB squash signals from commit.
799 if (fromCommit->commitInfo[tid].robSquashing) {
800 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing Thread %u.\n", tid);
801
802 // Continue to squash.
803 fetchStatus[tid] = Squashing;
804
805 return true;
806 }
807
808 // Check squash signals from decode.
809 if (fromDecode->decodeInfo[tid].squash) {
810 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
811 "from decode.\n",tid);
812
813 // Update the branch predictor.
814 if (fromDecode->decodeInfo[tid].branchMispredict) {
815 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
816 fromDecode->decodeInfo[tid].nextPC,
817 fromDecode->decodeInfo[tid].branchTaken,
818 tid);
819 } else {
820 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
821 tid);
822 }
823
824 if (fetchStatus[tid] != Squashing) {
825 // Squash unless we're already squashing
826 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
827 fromDecode->decodeInfo[tid].doneSeqNum,
828 tid);
829
830 return true;
831 }
832 }
833
834 if (checkStall(tid) && fetchStatus[tid] != IcacheMissStall) {
835 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
836
837 fetchStatus[tid] = Blocked;
838
839 return true;
840 }
841
842 if (fetchStatus[tid] == Blocked ||
843 fetchStatus[tid] == Squashing) {
844 // Switch status to running if fetch isn't being told to block or
845 // squash this cycle.
846 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
847 tid);
848
849 fetchStatus[tid] = Running;
850
851 return true;
852 }
853
854 // If we've reached this point, we have not gotten any signals that
855 // cause fetch to change its status. Fetch remains the same as before.
856 return false;
857}
858
859template<class Impl>
860void
861DefaultFetch<Impl>::fetch(bool &status_change)
862{
863 //////////////////////////////////////////
864 // Start actual fetch
865 //////////////////////////////////////////
866 int tid = getFetchingThread(fetchPolicy);
867
868 if (tid == -1) {
869 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
870
871 // Breaks looping condition in tick()
872 threadFetched = numFetchingThreads;
873 return;
874 }
875
876 // The current PC.
877 Addr &fetch_PC = PC[tid];
878
879 // Fault code for memory access.
880 Fault fault = NoFault;
881
882 // If returning from the delay of a cache miss, then update the status
883 // to running, otherwise do the cache access. Possibly move this up
884 // to tick() function.
885 if (fetchStatus[tid] == IcacheMissComplete) {
886 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
887 tid);
888
889 fetchStatus[tid] = Running;
890 status_change = true;
891 } else if (fetchStatus[tid] == Running) {
892 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
893 "instruction, starting at PC %08p.\n",
894 tid, fetch_PC);
895
896 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
897 if (!fetch_success) {
898 ++fetchMiscStallCycles;
899 return;
900 }
901 } else {
902 if (fetchStatus[tid] == Idle) {
903 ++fetchIdleCycles;
904 } else if (fetchStatus[tid] == Blocked) {
905 ++fetchBlockedCycles;
906 } else if (fetchStatus[tid] == Squashing) {
907 ++fetchSquashCycles;
908 } else if (fetchStatus[tid] == IcacheMissStall) {
909 ++icacheStallCycles;
910 }
911
912 // Status is Idle, Squashing, Blocked, or IcacheMissStall, so
913 // fetch should do nothing.
914 return;
915 }
916
917 ++fetchCycles;
918
919 // If we had a stall due to an icache miss, then return.
920 if (fetchStatus[tid] == IcacheMissStall) {
921 ++icacheStallCycles;
922 status_change = true;
923 return;
924 }
925
926 Addr next_PC = fetch_PC;
927 InstSeqNum inst_seq;
928 MachInst inst;
929 ExtMachInst ext_inst;
930 // @todo: Fix this hack.
931 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
932
933 if (fault == NoFault) {
934 // If the read of the first instruction was successful, then grab the
935 // instructions from the rest of the cache line and put them into the
936 // queue heading to decode.
937
938 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
939 "decode.\n",tid);
940
941 // Need to keep track of whether or not a predicted branch
942 // ended this fetch block.
943 bool predicted_branch = false;
944
945 for (;
946 offset < cacheBlkSize &&
947 numInst < fetchWidth &&
948 !predicted_branch;
949 ++numInst) {
950
951 // Get a sequence number.
952 inst_seq = cpu->getAndIncrementInstSeq();
953
954 // Make sure this is a valid index.
955 assert(offset <= cacheBlkSize - instSize);
956
957 // Get the instruction from the array of the cache line.
958 inst = gtoh(*reinterpret_cast<MachInst *>
959 (&cacheData[tid][offset]));
960
961 ext_inst = TheISA::makeExtMI(inst, fetch_PC);
962
963 // Create a new DynInst from the instruction fetched.
964 DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
965 next_PC,
966 inst_seq, cpu);
967 instruction->setThread(tid);
968
969 instruction->setASID(tid);
970
971 instruction->setState(cpu->thread[tid]);
972
973 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
974 "[sn:%lli]\n",
975 tid, instruction->readPC(), inst_seq);
976
977 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
978 tid, instruction->staticInst->disassemble(fetch_PC));
979
980 instruction->traceData =
981 Trace::getInstRecord(curTick, cpu->xcBase(tid), cpu,
982 instruction->staticInst,
983 instruction->readPC(),tid);
984
985 predicted_branch = lookupAndUpdateNextPC(instruction, next_PC);
986
987 // Add instruction to the CPU's list of instructions.
988 instruction->setInstListIt(cpu->addInst(instruction));
989
990 // Write the instruction to the first slot in the queue
991 // that heads to decode.
992 toDecode->insts[numInst] = instruction;
993
994 toDecode->size++;
995
996 // Increment stat of fetched instructions.
997 ++fetchedInsts;
998
999 // Move to the next instruction, unless we have a branch.
1000 fetch_PC = next_PC;
1001
1002 if (instruction->isQuiesce()) {
1003 warn("%lli: Quiesce instruction encountered, halting fetch!",
1004 curTick);
1005 fetchStatus[tid] = QuiescePending;
1006 ++numInst;
1007 status_change = true;
1008 break;
1009 }
1010
1011 offset+= instSize;
1012 }
1013 }
1014
1015 if (numInst > 0) {
1016 wroteToTimeBuffer = true;
1017 }
1018
1019 // Now that fetching is completed, update the PC to signify what the next
1020 // cycle will be.
1021 if (fault == NoFault) {
1022 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n",tid, next_PC);
1023
1024 PC[tid] = next_PC;
1025 nextPC[tid] = next_PC + instSize;
1026 } else {
1027 // We shouldn't be in an icache miss and also have a fault (an ITB
1028 // miss)
1029 if (fetchStatus[tid] == IcacheMissStall) {
1030 panic("Fetch should have exited prior to this!");
1031 }
1032
1033 // Send the fault to commit. This thread will not do anything
1034 // until commit handles the fault. The only other way it can
1035 // wake up is if a squash comes along and changes the PC.
1036#if FULL_SYSTEM
1037 assert(numInst != fetchWidth);
1038 // Get a sequence number.
1039 inst_seq = cpu->getAndIncrementInstSeq();
1040 // We will use a nop in order to carry the fault.
1041 ext_inst = TheISA::NoopMachInst;
1042
1043 // Create a new DynInst from the dummy nop.
1044 DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
1045 next_PC,
1046 inst_seq, cpu);
1047 instruction->setPredTarg(next_PC + instSize);
1048 instruction->setThread(tid);
1049
1050 instruction->setASID(tid);
1051
1052 instruction->setState(cpu->thread[tid]);
1053
1054 instruction->traceData = NULL;
1055
1056 instruction->setInstListIt(cpu->addInst(instruction));
1057
1058 instruction->fault = fault;
1059
1060 toDecode->insts[numInst] = instruction;
1061 toDecode->size++;
1062
1063 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1064
1065 fetchStatus[tid] = TrapPending;
1066 status_change = true;
1067
1068 warn("%lli fault (%d) detected @ PC %08p", curTick, fault, PC[tid]);
1069#else // !FULL_SYSTEM
1070 fatal("fault (%d) detected @ PC %08p", fault, PC[tid]);
1071#endif // FULL_SYSTEM
1072 }
1073}
1074
1075
1076///////////////////////////////////////
1077// //
1078// SMT FETCH POLICY MAINTAINED HERE //
1079// //
1080///////////////////////////////////////
1081template<class Impl>
1082int
1083DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1084{
1085 if (numThreads > 1) {
1086 switch (fetch_priority) {
1087
1088 case SingleThread:
1089 return 0;
1090
1091 case RoundRobin:
1092 return roundRobin();
1093
1094 case IQ:
1095 return iqCount();
1096
1097 case LSQ:
1098 return lsqCount();
1099
1100 case Branch:
1101 return branchCount();
1102
1103 default:
1104 return -1;
1105 }
1106 } else {
1107 int tid = *((*activeThreads).begin());
1108
1109 if (fetchStatus[tid] == Running ||
1110 fetchStatus[tid] == IcacheMissComplete ||
1111 fetchStatus[tid] == Idle) {
1112 return tid;
1113 } else {
1114 return -1;
1115 }
1116 }
1117
1118}
1119
1120
1121template<class Impl>
1122int
1123DefaultFetch<Impl>::roundRobin()
1124{
1125 list<unsigned>::iterator pri_iter = priorityList.begin();
1126 list<unsigned>::iterator end = priorityList.end();
1127
1128 int high_pri;
1129
1130 while (pri_iter != end) {
1131 high_pri = *pri_iter;
1132
1133 assert(high_pri <= numThreads);
1134
1135 if (fetchStatus[high_pri] == Running ||
1136 fetchStatus[high_pri] == IcacheMissComplete ||
1137 fetchStatus[high_pri] == Idle) {
1138
1139 priorityList.erase(pri_iter);
1140 priorityList.push_back(high_pri);
1141
1142 return high_pri;
1143 }
1144
1145 pri_iter++;
1146 }
1147
1148 return -1;
1149}
1150
1151template<class Impl>
1152int
1153DefaultFetch<Impl>::iqCount()
1154{
1155 priority_queue<unsigned> PQ;
1156
1157 list<unsigned>::iterator threads = (*activeThreads).begin();
1158
1159 while (threads != (*activeThreads).end()) {
1160 unsigned tid = *threads++;
1161
1162 PQ.push(fromIEW->iewInfo[tid].iqCount);
1163 }
1164
1165 while (!PQ.empty()) {
1166
1167 unsigned high_pri = PQ.top();
1168
1169 if (fetchStatus[high_pri] == Running ||
1170 fetchStatus[high_pri] == IcacheMissComplete ||
1171 fetchStatus[high_pri] == Idle)
1172 return high_pri;
1173 else
1174 PQ.pop();
1175
1176 }
1177
1178 return -1;
1179}
1180
1181template<class Impl>
1182int
1183DefaultFetch<Impl>::lsqCount()
1184{
1185 priority_queue<unsigned> PQ;
1186
1187
1188 list<unsigned>::iterator threads = (*activeThreads).begin();
1189
1190 while (threads != (*activeThreads).end()) {
1191 unsigned tid = *threads++;
1192
1193 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1194 }
1195
1196 while (!PQ.empty()) {
1197
1198 unsigned high_pri = PQ.top();
1199
1200 if (fetchStatus[high_pri] == Running ||
1201 fetchStatus[high_pri] == IcacheMissComplete ||
1202 fetchStatus[high_pri] == Idle)
1203 return high_pri;
1204 else
1205 PQ.pop();
1206
1207 }
1208
1209 return -1;
1210}
1211
1212template<class Impl>
1213int
1214DefaultFetch<Impl>::branchCount()
1215{
1216 list<unsigned>::iterator threads = (*activeThreads).begin();
1217
1218 return *threads;
1219}