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