fetch_impl.hh revision 10566:c99c8d2a7c31
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->getConstPtr<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 < numThreads; ++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(const 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->dataDynamic(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 (stalls[tid].drain) { 815 assert(cpu->isDraining()); 816 DPRINTF(Fetch,"[tid:%i]: Drain stall detected.\n",tid); 817 ret_val = true; 818 } 819 820 return ret_val; 821} 822 823template<class Impl> 824typename DefaultFetch<Impl>::FetchStatus 825DefaultFetch<Impl>::updateFetchStatus() 826{ 827 //Check Running 828 list<ThreadID>::iterator threads = activeThreads->begin(); 829 list<ThreadID>::iterator end = activeThreads->end(); 830 831 while (threads != end) { 832 ThreadID tid = *threads++; 833 834 if (fetchStatus[tid] == Running || 835 fetchStatus[tid] == Squashing || 836 fetchStatus[tid] == IcacheAccessComplete) { 837 838 if (_status == Inactive) { 839 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid); 840 841 if (fetchStatus[tid] == IcacheAccessComplete) { 842 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache" 843 "completion\n",tid); 844 } 845 846 cpu->activateStage(O3CPU::FetchIdx); 847 } 848 849 return Active; 850 } 851 } 852 853 // Stage is switching from active to inactive, notify CPU of it. 854 if (_status == Active) { 855 DPRINTF(Activity, "Deactivating stage.\n"); 856 857 cpu->deactivateStage(O3CPU::FetchIdx); 858 } 859 860 return Inactive; 861} 862 863template <class Impl> 864void 865DefaultFetch<Impl>::squash(const TheISA::PCState &newPC, 866 const InstSeqNum seq_num, DynInstPtr squashInst, 867 ThreadID tid) 868{ 869 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid); 870 871 doSquash(newPC, squashInst, tid); 872 873 // Tell the CPU to remove any instructions that are not in the ROB. 874 cpu->removeInstsNotInROB(tid); 875} 876 877template <class Impl> 878void 879DefaultFetch<Impl>::tick() 880{ 881 list<ThreadID>::iterator threads = activeThreads->begin(); 882 list<ThreadID>::iterator end = activeThreads->end(); 883 bool status_change = false; 884 885 wroteToTimeBuffer = false; 886 887 for (ThreadID i = 0; i < numThreads; ++i) { 888 issuePipelinedIfetch[i] = false; 889 } 890 891 while (threads != end) { 892 ThreadID tid = *threads++; 893 894 // Check the signals for each thread to determine the proper status 895 // for each thread. 896 bool updated_status = checkSignalsAndUpdate(tid); 897 status_change = status_change || updated_status; 898 } 899 900 DPRINTF(Fetch, "Running stage.\n"); 901 902 if (FullSystem) { 903 if (fromCommit->commitInfo[0].interruptPending) { 904 interruptPending = true; 905 } 906 907 if (fromCommit->commitInfo[0].clearInterrupt) { 908 interruptPending = false; 909 } 910 } 911 912 for (threadFetched = 0; threadFetched < numFetchingThreads; 913 threadFetched++) { 914 // Fetch each of the actively fetching threads. 915 fetch(status_change); 916 } 917 918 // Record number of instructions fetched this cycle for distribution. 919 fetchNisnDist.sample(numInst); 920 921 if (status_change) { 922 // Change the fetch stage status if there was a status change. 923 _status = updateFetchStatus(); 924 } 925 926 // Issue the next I-cache request if possible. 927 for (ThreadID i = 0; i < numThreads; ++i) { 928 if (issuePipelinedIfetch[i]) { 929 pipelineIcacheAccesses(i); 930 } 931 } 932 933 // Send instructions enqueued into the fetch queue to decode. 934 // Limit rate by fetchWidth. Stall if decode is stalled. 935 unsigned insts_to_decode = 0; 936 unsigned available_insts = 0; 937 938 for (auto tid : *activeThreads) { 939 if (!stalls[tid].decode) { 940 available_insts += fetchQueue[tid].size(); 941 } 942 } 943 944 // Pick a random thread to start trying to grab instructions from 945 auto tid_itr = activeThreads->begin(); 946 std::advance(tid_itr, random_mt.random<uint8_t>(0, activeThreads->size() - 1)); 947 948 while (available_insts != 0 && insts_to_decode < decodeWidth) { 949 ThreadID tid = *tid_itr; 950 if (!stalls[tid].decode && !fetchQueue[tid].empty()) { 951 auto inst = fetchQueue[tid].front(); 952 toDecode->insts[toDecode->size++] = inst; 953 DPRINTF(Fetch, "[tid:%i][sn:%i]: Sending instruction to decode from " 954 "fetch queue. Fetch queue size: %i.\n", 955 tid, inst->seqNum, fetchQueue[tid].size()); 956 957 wroteToTimeBuffer = true; 958 fetchQueue[tid].pop_front(); 959 insts_to_decode++; 960 available_insts--; 961 } 962 963 tid_itr++; 964 // Wrap around if at end of active threads list 965 if (tid_itr == activeThreads->end()) 966 tid_itr = activeThreads->begin(); 967 } 968 969 // If there was activity this cycle, inform the CPU of it. 970 if (wroteToTimeBuffer) { 971 DPRINTF(Activity, "Activity this cycle.\n"); 972 cpu->activityThisCycle(); 973 } 974 975 // Reset the number of the instruction we've fetched. 976 numInst = 0; 977} 978 979template <class Impl> 980bool 981DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid) 982{ 983 // Update the per thread stall statuses. 984 if (fromDecode->decodeBlock[tid]) { 985 stalls[tid].decode = true; 986 } 987 988 if (fromDecode->decodeUnblock[tid]) { 989 assert(stalls[tid].decode); 990 assert(!fromDecode->decodeBlock[tid]); 991 stalls[tid].decode = false; 992 } 993 994 // Check squash signals from commit. 995 if (fromCommit->commitInfo[tid].squash) { 996 997 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash " 998 "from commit.\n",tid); 999 // In any case, squash. 1000 squash(fromCommit->commitInfo[tid].pc, 1001 fromCommit->commitInfo[tid].doneSeqNum, 1002 fromCommit->commitInfo[tid].squashInst, tid); 1003 1004 // If it was a branch mispredict on a control instruction, update the 1005 // branch predictor with that instruction, otherwise just kill the 1006 // invalid state we generated in after sequence number 1007 if (fromCommit->commitInfo[tid].mispredictInst && 1008 fromCommit->commitInfo[tid].mispredictInst->isControl()) { 1009 branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum, 1010 fromCommit->commitInfo[tid].pc, 1011 fromCommit->commitInfo[tid].branchTaken, 1012 tid); 1013 } else { 1014 branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum, 1015 tid); 1016 } 1017 1018 return true; 1019 } else if (fromCommit->commitInfo[tid].doneSeqNum) { 1020 // Update the branch predictor if it wasn't a squashed instruction 1021 // that was broadcasted. 1022 branchPred->update(fromCommit->commitInfo[tid].doneSeqNum, tid); 1023 } 1024 1025 // Check squash signals from decode. 1026 if (fromDecode->decodeInfo[tid].squash) { 1027 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash " 1028 "from decode.\n",tid); 1029 1030 // Update the branch predictor. 1031 if (fromDecode->decodeInfo[tid].branchMispredict) { 1032 branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum, 1033 fromDecode->decodeInfo[tid].nextPC, 1034 fromDecode->decodeInfo[tid].branchTaken, 1035 tid); 1036 } else { 1037 branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum, 1038 tid); 1039 } 1040 1041 if (fetchStatus[tid] != Squashing) { 1042 1043 DPRINTF(Fetch, "Squashing from decode with PC = %s\n", 1044 fromDecode->decodeInfo[tid].nextPC); 1045 // Squash unless we're already squashing 1046 squashFromDecode(fromDecode->decodeInfo[tid].nextPC, 1047 fromDecode->decodeInfo[tid].squashInst, 1048 fromDecode->decodeInfo[tid].doneSeqNum, 1049 tid); 1050 1051 return true; 1052 } 1053 } 1054 1055 if (checkStall(tid) && 1056 fetchStatus[tid] != IcacheWaitResponse && 1057 fetchStatus[tid] != IcacheWaitRetry && 1058 fetchStatus[tid] != ItlbWait && 1059 fetchStatus[tid] != QuiescePending) { 1060 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid); 1061 1062 fetchStatus[tid] = Blocked; 1063 1064 return true; 1065 } 1066 1067 if (fetchStatus[tid] == Blocked || 1068 fetchStatus[tid] == Squashing) { 1069 // Switch status to running if fetch isn't being told to block or 1070 // squash this cycle. 1071 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n", 1072 tid); 1073 1074 fetchStatus[tid] = Running; 1075 1076 return true; 1077 } 1078 1079 // If we've reached this point, we have not gotten any signals that 1080 // cause fetch to change its status. Fetch remains the same as before. 1081 return false; 1082} 1083 1084template<class Impl> 1085typename Impl::DynInstPtr 1086DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst, 1087 StaticInstPtr curMacroop, TheISA::PCState thisPC, 1088 TheISA::PCState nextPC, bool trace) 1089{ 1090 // Get a sequence number. 1091 InstSeqNum seq = cpu->getAndIncrementInstSeq(); 1092 1093 // Create a new DynInst from the instruction fetched. 1094 DynInstPtr instruction = 1095 new DynInst(staticInst, curMacroop, thisPC, nextPC, seq, cpu); 1096 instruction->setTid(tid); 1097 1098 instruction->setASID(tid); 1099 1100 instruction->setThreadState(cpu->thread[tid]); 1101 1102 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created " 1103 "[sn:%lli].\n", tid, thisPC.instAddr(), 1104 thisPC.microPC(), seq); 1105 1106 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid, 1107 instruction->staticInst-> 1108 disassemble(thisPC.instAddr())); 1109 1110#if TRACING_ON 1111 if (trace) { 1112 instruction->traceData = 1113 cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid), 1114 instruction->staticInst, thisPC, curMacroop); 1115 } 1116#else 1117 instruction->traceData = NULL; 1118#endif 1119 1120 // Add instruction to the CPU's list of instructions. 1121 instruction->setInstListIt(cpu->addInst(instruction)); 1122 1123 // Write the instruction to the first slot in the queue 1124 // that heads to decode. 1125 assert(numInst < fetchWidth); 1126 fetchQueue[tid].push_back(instruction); 1127 assert(fetchQueue[tid].size() <= fetchQueueSize); 1128 DPRINTF(Fetch, "[tid:%i]: Fetch queue entry created (%i/%i).\n", 1129 tid, fetchQueue[tid].size(), fetchQueueSize); 1130 //toDecode->insts[toDecode->size++] = instruction; 1131 1132 // Keep track of if we can take an interrupt at this boundary 1133 delayedCommit[tid] = instruction->isDelayedCommit(); 1134 1135 return instruction; 1136} 1137 1138template<class Impl> 1139void 1140DefaultFetch<Impl>::fetch(bool &status_change) 1141{ 1142 ////////////////////////////////////////// 1143 // Start actual fetch 1144 ////////////////////////////////////////// 1145 ThreadID tid = getFetchingThread(fetchPolicy); 1146 1147 assert(!cpu->switchedOut()); 1148 1149 if (tid == InvalidThreadID) { 1150 // Breaks looping condition in tick() 1151 threadFetched = numFetchingThreads; 1152 1153 if (numThreads == 1) { // @todo Per-thread stats 1154 profileStall(0); 1155 } 1156 1157 return; 1158 } 1159 1160 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid); 1161 1162 // The current PC. 1163 TheISA::PCState thisPC = pc[tid]; 1164 1165 Addr pcOffset = fetchOffset[tid]; 1166 Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask; 1167 1168 bool inRom = isRomMicroPC(thisPC.microPC()); 1169 1170 // If returning from the delay of a cache miss, then update the status 1171 // to running, otherwise do the cache access. Possibly move this up 1172 // to tick() function. 1173 if (fetchStatus[tid] == IcacheAccessComplete) { 1174 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid); 1175 1176 fetchStatus[tid] = Running; 1177 status_change = true; 1178 } else if (fetchStatus[tid] == Running) { 1179 // Align the fetch PC so its at the start of a fetch buffer segment. 1180 Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr); 1181 1182 // If buffer is no longer valid or fetchAddr has moved to point 1183 // to the next cache block, AND we have no remaining ucode 1184 // from a macro-op, then start fetch from icache. 1185 if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid]) 1186 && !inRom && !macroop[tid]) { 1187 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read " 1188 "instruction, starting at PC %s.\n", tid, thisPC); 1189 1190 fetchCacheLine(fetchAddr, tid, thisPC.instAddr()); 1191 1192 if (fetchStatus[tid] == IcacheWaitResponse) 1193 ++icacheStallCycles; 1194 else if (fetchStatus[tid] == ItlbWait) 1195 ++fetchTlbCycles; 1196 else 1197 ++fetchMiscStallCycles; 1198 return; 1199 } else if ((checkInterrupt(thisPC.instAddr()) && !delayedCommit[tid])) { 1200 // Stall CPU if an interrupt is posted and we're not issuing 1201 // an delayed commit micro-op currently (delayed commit instructions 1202 // are not interruptable by interrupts, only faults) 1203 ++fetchMiscStallCycles; 1204 DPRINTF(Fetch, "[tid:%i]: Fetch is stalled!\n", tid); 1205 return; 1206 } 1207 } else { 1208 if (fetchStatus[tid] == Idle) { 1209 ++fetchIdleCycles; 1210 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid); 1211 } 1212 1213 // Status is Idle, so fetch should do nothing. 1214 return; 1215 } 1216 1217 ++fetchCycles; 1218 1219 TheISA::PCState nextPC = thisPC; 1220 1221 StaticInstPtr staticInst = NULL; 1222 StaticInstPtr curMacroop = macroop[tid]; 1223 1224 // If the read of the first instruction was successful, then grab the 1225 // instructions from the rest of the cache line and put them into the 1226 // queue heading to decode. 1227 1228 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to " 1229 "decode.\n", tid); 1230 1231 // Need to keep track of whether or not a predicted branch 1232 // ended this fetch block. 1233 bool predictedBranch = false; 1234 1235 // Need to halt fetch if quiesce instruction detected 1236 bool quiesce = false; 1237 1238 TheISA::MachInst *cacheInsts = 1239 reinterpret_cast<TheISA::MachInst *>(fetchBuffer[tid]); 1240 1241 const unsigned numInsts = fetchBufferSize / instSize; 1242 unsigned blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize; 1243 1244 // Loop through instruction memory from the cache. 1245 // Keep issuing while fetchWidth is available and branch is not 1246 // predicted taken 1247 while (numInst < fetchWidth && fetchQueue[tid].size() < fetchQueueSize 1248 && !predictedBranch && !quiesce) { 1249 // We need to process more memory if we aren't going to get a 1250 // StaticInst from the rom, the current macroop, or what's already 1251 // in the decoder. 1252 bool needMem = !inRom && !curMacroop && 1253 !decoder[tid]->instReady(); 1254 fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask; 1255 Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr); 1256 1257 if (needMem) { 1258 // If buffer is no longer valid or fetchAddr has moved to point 1259 // to the next cache block then start fetch from icache. 1260 if (!fetchBufferValid[tid] || 1261 fetchBufferBlockPC != fetchBufferPC[tid]) 1262 break; 1263 1264 if (blkOffset >= numInsts) { 1265 // We need to process more memory, but we've run out of the 1266 // current block. 1267 break; 1268 } 1269 1270 if (ISA_HAS_DELAY_SLOT && pcOffset == 0) { 1271 // Walk past any annulled delay slot instructions. 1272 Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask; 1273 while (fetchAddr != pcAddr && blkOffset < numInsts) { 1274 blkOffset++; 1275 fetchAddr += instSize; 1276 } 1277 if (blkOffset >= numInsts) 1278 break; 1279 } 1280 1281 MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]); 1282 decoder[tid]->moreBytes(thisPC, fetchAddr, inst); 1283 1284 if (decoder[tid]->needMoreBytes()) { 1285 blkOffset++; 1286 fetchAddr += instSize; 1287 pcOffset += instSize; 1288 } 1289 } 1290 1291 // Extract as many instructions and/or microops as we can from 1292 // the memory we've processed so far. 1293 do { 1294 if (!(curMacroop || inRom)) { 1295 if (decoder[tid]->instReady()) { 1296 staticInst = decoder[tid]->decode(thisPC); 1297 1298 // Increment stat of fetched instructions. 1299 ++fetchedInsts; 1300 1301 if (staticInst->isMacroop()) { 1302 curMacroop = staticInst; 1303 } else { 1304 pcOffset = 0; 1305 } 1306 } else { 1307 // We need more bytes for this instruction so blkOffset and 1308 // pcOffset will be updated 1309 break; 1310 } 1311 } 1312 // Whether we're moving to a new macroop because we're at the 1313 // end of the current one, or the branch predictor incorrectly 1314 // thinks we are... 1315 bool newMacro = false; 1316 if (curMacroop || inRom) { 1317 if (inRom) { 1318 staticInst = cpu->microcodeRom.fetchMicroop( 1319 thisPC.microPC(), curMacroop); 1320 } else { 1321 staticInst = curMacroop->fetchMicroop(thisPC.microPC()); 1322 } 1323 newMacro |= staticInst->isLastMicroop(); 1324 } 1325 1326 DynInstPtr instruction = 1327 buildInst(tid, staticInst, curMacroop, 1328 thisPC, nextPC, true); 1329 1330 ppFetch->notify(instruction); 1331 numInst++; 1332 1333#if TRACING_ON 1334 if (DTRACE(O3PipeView)) { 1335 instruction->fetchTick = curTick(); 1336 } 1337#endif 1338 1339 nextPC = thisPC; 1340 1341 // If we're branching after this instruction, quit fetching 1342 // from the same block. 1343 predictedBranch |= thisPC.branching(); 1344 predictedBranch |= 1345 lookupAndUpdateNextPC(instruction, nextPC); 1346 if (predictedBranch) { 1347 DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC); 1348 } 1349 1350 newMacro |= thisPC.instAddr() != nextPC.instAddr(); 1351 1352 // Move to the next instruction, unless we have a branch. 1353 thisPC = nextPC; 1354 inRom = isRomMicroPC(thisPC.microPC()); 1355 1356 if (newMacro) { 1357 fetchAddr = thisPC.instAddr() & BaseCPU::PCMask; 1358 blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize; 1359 pcOffset = 0; 1360 curMacroop = NULL; 1361 } 1362 1363 if (instruction->isQuiesce()) { 1364 DPRINTF(Fetch, 1365 "Quiesce instruction encountered, halting fetch!\n"); 1366 fetchStatus[tid] = QuiescePending; 1367 status_change = true; 1368 quiesce = 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 //sorted from lowest->highest 1515 std::priority_queue<unsigned,vector<unsigned>, 1516 std::greater<unsigned> > PQ; 1517 std::map<unsigned, ThreadID> threadMap; 1518 1519 list<ThreadID>::iterator threads = activeThreads->begin(); 1520 list<ThreadID>::iterator end = activeThreads->end(); 1521 1522 while (threads != end) { 1523 ThreadID tid = *threads++; 1524 unsigned iqCount = fromIEW->iewInfo[tid].iqCount; 1525 1526 //we can potentially get tid collisions if two threads 1527 //have the same iqCount, but this should be rare. 1528 PQ.push(iqCount); 1529 threadMap[iqCount] = tid; 1530 } 1531 1532 while (!PQ.empty()) { 1533 ThreadID high_pri = threadMap[PQ.top()]; 1534 1535 if (fetchStatus[high_pri] == Running || 1536 fetchStatus[high_pri] == IcacheAccessComplete || 1537 fetchStatus[high_pri] == Idle) 1538 return high_pri; 1539 else 1540 PQ.pop(); 1541 1542 } 1543 1544 return InvalidThreadID; 1545} 1546 1547template<class Impl> 1548ThreadID 1549DefaultFetch<Impl>::lsqCount() 1550{ 1551 //sorted from lowest->highest 1552 std::priority_queue<unsigned,vector<unsigned>, 1553 std::greater<unsigned> > PQ; 1554 std::map<unsigned, ThreadID> threadMap; 1555 1556 list<ThreadID>::iterator threads = activeThreads->begin(); 1557 list<ThreadID>::iterator end = activeThreads->end(); 1558 1559 while (threads != end) { 1560 ThreadID tid = *threads++; 1561 unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount; 1562 1563 //we can potentially get tid collisions if two threads 1564 //have the same iqCount, but this should be rare. 1565 PQ.push(ldstqCount); 1566 threadMap[ldstqCount] = tid; 1567 } 1568 1569 while (!PQ.empty()) { 1570 ThreadID high_pri = threadMap[PQ.top()]; 1571 1572 if (fetchStatus[high_pri] == Running || 1573 fetchStatus[high_pri] == IcacheAccessComplete || 1574 fetchStatus[high_pri] == Idle) 1575 return high_pri; 1576 else 1577 PQ.pop(); 1578 } 1579 1580 return InvalidThreadID; 1581} 1582 1583template<class Impl> 1584ThreadID 1585DefaultFetch<Impl>::branchCount() 1586{ 1587#if 0 1588 list<ThreadID>::iterator thread = activeThreads->begin(); 1589 assert(thread != activeThreads->end()); 1590 ThreadID tid = *thread; 1591#endif 1592 1593 panic("Branch Count Fetch policy unimplemented\n"); 1594 return InvalidThreadID; 1595} 1596 1597template<class Impl> 1598void 1599DefaultFetch<Impl>::pipelineIcacheAccesses(ThreadID tid) 1600{ 1601 if (!issuePipelinedIfetch[tid]) { 1602 return; 1603 } 1604 1605 // The next PC to access. 1606 TheISA::PCState thisPC = pc[tid]; 1607 1608 if (isRomMicroPC(thisPC.microPC())) { 1609 return; 1610 } 1611 1612 Addr pcOffset = fetchOffset[tid]; 1613 Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask; 1614 1615 // Align the fetch PC so its at the start of a fetch buffer segment. 1616 Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr); 1617 1618 // Unless buffer already got the block, fetch it from icache. 1619 if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])) { 1620 DPRINTF(Fetch, "[tid:%i]: Issuing a pipelined I-cache access, " 1621 "starting at PC %s.\n", tid, thisPC); 1622 1623 fetchCacheLine(fetchAddr, tid, thisPC.instAddr()); 1624 } 1625} 1626 1627template<class Impl> 1628void 1629DefaultFetch<Impl>::profileStall(ThreadID tid) { 1630 DPRINTF(Fetch,"There are no more threads available to fetch from.\n"); 1631 1632 // @todo Per-thread stats 1633 1634 if (stalls[tid].drain) { 1635 ++fetchPendingDrainCycles; 1636 DPRINTF(Fetch, "Fetch is waiting for a drain!\n"); 1637 } else if (activeThreads->empty()) { 1638 ++fetchNoActiveThreadStallCycles; 1639 DPRINTF(Fetch, "Fetch has no active thread!\n"); 1640 } else if (fetchStatus[tid] == Blocked) { 1641 ++fetchBlockedCycles; 1642 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid); 1643 } else if (fetchStatus[tid] == Squashing) { 1644 ++fetchSquashCycles; 1645 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid); 1646 } else if (fetchStatus[tid] == IcacheWaitResponse) { 1647 ++icacheStallCycles; 1648 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", 1649 tid); 1650 } else if (fetchStatus[tid] == ItlbWait) { 1651 ++fetchTlbCycles; 1652 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to " 1653 "finish!\n", tid); 1654 } else if (fetchStatus[tid] == TrapPending) { 1655 ++fetchPendingTrapStallCycles; 1656 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap!\n", 1657 tid); 1658 } else if (fetchStatus[tid] == QuiescePending) { 1659 ++fetchPendingQuiesceStallCycles; 1660 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending quiesce " 1661 "instruction!\n", tid); 1662 } else if (fetchStatus[tid] == IcacheWaitRetry) { 1663 ++fetchIcacheWaitRetryStallCycles; 1664 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for an I-cache retry!\n", 1665 tid); 1666 } else if (fetchStatus[tid] == NoGoodAddr) { 1667 DPRINTF(Fetch, "[tid:%i]: Fetch predicted non-executable address\n", 1668 tid); 1669 } else { 1670 DPRINTF(Fetch, "[tid:%i]: Unexpected fetch stall reason (Status: %i).\n", 1671 tid, fetchStatus[tid]); 1672 } 1673} 1674 1675#endif//__CPU_O3_FETCH_IMPL_HH__ 1676