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