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