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