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