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