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