fetch_impl.hh revision 12406:86bde4a026b5
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->req; 392 delete pkt; 393 return; 394 } 395 396 memcpy(fetchBuffer[tid], pkt->getConstPtr<uint8_t>(), fetchBufferSize); 397 fetchBufferValid[tid] = true; 398 399 // Wake up the CPU (if it went to sleep and was waiting on 400 // this completion event). 401 cpu->wakeCPU(); 402 403 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n", 404 tid); 405 406 switchToActive(); 407 408 // Only switch to IcacheAccessComplete if we're not stalled as well. 409 if (checkStall(tid)) { 410 fetchStatus[tid] = Blocked; 411 } else { 412 fetchStatus[tid] = IcacheAccessComplete; 413 } 414 415 pkt->req->setAccessLatency(); 416 cpu->ppInstAccessComplete->notify(pkt); 417 // Reset the mem req to NULL. 418 delete pkt->req; 419 delete pkt; 420 memReq[tid] = NULL; 421} 422 423template <class Impl> 424void 425DefaultFetch<Impl>::drainResume() 426{ 427 for (ThreadID i = 0; i < numThreads; ++i) { 428 stalls[i].decode = false; 429 stalls[i].drain = false; 430 } 431} 432 433template <class Impl> 434void 435DefaultFetch<Impl>::drainSanityCheck() const 436{ 437 assert(isDrained()); 438 assert(retryPkt == NULL); 439 assert(retryTid == InvalidThreadID); 440 assert(!cacheBlocked); 441 assert(!interruptPending); 442 443 for (ThreadID i = 0; i < numThreads; ++i) { 444 assert(!memReq[i]); 445 assert(fetchStatus[i] == Idle || stalls[i].drain); 446 } 447 448 branchPred->drainSanityCheck(); 449} 450 451template <class Impl> 452bool 453DefaultFetch<Impl>::isDrained() const 454{ 455 /* Make sure that threads are either idle of that the commit stage 456 * has signaled that draining has completed by setting the drain 457 * stall flag. This effectively forces the pipeline to be disabled 458 * until the whole system is drained (simulation may continue to 459 * drain other components). 460 */ 461 for (ThreadID i = 0; i < numThreads; ++i) { 462 // Verify fetch queues are drained 463 if (!fetchQueue[i].empty()) 464 return false; 465 466 // Return false if not idle or drain stalled 467 if (fetchStatus[i] != Idle) { 468 if (fetchStatus[i] == Blocked && stalls[i].drain) 469 continue; 470 else 471 return false; 472 } 473 } 474 475 /* The pipeline might start up again in the middle of the drain 476 * cycle if the finish translation event is scheduled, so make 477 * sure that's not the case. 478 */ 479 return !finishTranslationEvent.scheduled(); 480} 481 482template <class Impl> 483void 484DefaultFetch<Impl>::takeOverFrom() 485{ 486 assert(cpu->getInstPort().isConnected()); 487 resetStage(); 488 489} 490 491template <class Impl> 492void 493DefaultFetch<Impl>::drainStall(ThreadID tid) 494{ 495 assert(cpu->isDraining()); 496 assert(!stalls[tid].drain); 497 DPRINTF(Drain, "%i: Thread drained.\n", tid); 498 stalls[tid].drain = true; 499} 500 501template <class Impl> 502void 503DefaultFetch<Impl>::wakeFromQuiesce() 504{ 505 DPRINTF(Fetch, "Waking up from quiesce\n"); 506 // Hopefully this is safe 507 // @todo: Allow other threads to wake from quiesce. 508 fetchStatus[0] = Running; 509} 510 511template <class Impl> 512inline void 513DefaultFetch<Impl>::switchToActive() 514{ 515 if (_status == Inactive) { 516 DPRINTF(Activity, "Activating stage.\n"); 517 518 cpu->activateStage(O3CPU::FetchIdx); 519 520 _status = Active; 521 } 522} 523 524template <class Impl> 525inline void 526DefaultFetch<Impl>::switchToInactive() 527{ 528 if (_status == Active) { 529 DPRINTF(Activity, "Deactivating stage.\n"); 530 531 cpu->deactivateStage(O3CPU::FetchIdx); 532 533 _status = Inactive; 534 } 535} 536 537template <class Impl> 538void 539DefaultFetch<Impl>::deactivateThread(ThreadID tid) 540{ 541 // Update priority list 542 auto thread_it = std::find(priorityList.begin(), priorityList.end(), tid); 543 if (thread_it != priorityList.end()) { 544 priorityList.erase(thread_it); 545 } 546} 547 548template <class Impl> 549bool 550DefaultFetch<Impl>::lookupAndUpdateNextPC( 551 DynInstPtr &inst, TheISA::PCState &nextPC) 552{ 553 // Do branch prediction check here. 554 // A bit of a misnomer...next_PC is actually the current PC until 555 // this function updates it. 556 bool predict_taken; 557 558 if (!inst->isControl()) { 559 TheISA::advancePC(nextPC, inst->staticInst); 560 inst->setPredTarg(nextPC); 561 inst->setPredTaken(false); 562 return false; 563 } 564 565 ThreadID tid = inst->threadNumber; 566 predict_taken = branchPred->predict(inst->staticInst, inst->seqNum, 567 nextPC, tid); 568 569 if (predict_taken) { 570 DPRINTF(Fetch, "[tid:%i]: [sn:%i]: Branch predicted to be taken to %s.\n", 571 tid, inst->seqNum, nextPC); 572 } else { 573 DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n", 574 tid, inst->seqNum); 575 } 576 577 DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n", 578 tid, inst->seqNum, nextPC); 579 inst->setPredTarg(nextPC); 580 inst->setPredTaken(predict_taken); 581 582 ++fetchedBranches; 583 584 if (predict_taken) { 585 ++predictedBranches; 586 } 587 588 return predict_taken; 589} 590 591template <class Impl> 592bool 593DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc) 594{ 595 Fault fault = NoFault; 596 597 assert(!cpu->switchedOut()); 598 599 // @todo: not sure if these should block translation. 600 //AlphaDep 601 if (cacheBlocked) { 602 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n", 603 tid); 604 return false; 605 } else if (checkInterrupt(pc) && !delayedCommit[tid]) { 606 // Hold off fetch from getting new instructions when: 607 // Cache is blocked, or 608 // while an interrupt is pending and we're not in PAL mode, or 609 // fetch is switched out. 610 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n", 611 tid); 612 return false; 613 } 614 615 // Align the fetch address to the start of a fetch buffer segment. 616 Addr fetchBufferBlockPC = fetchBufferAlignPC(vaddr); 617 618 DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n", 619 tid, fetchBufferBlockPC, vaddr); 620 621 // Setup the memReq to do a read of the first instruction's address. 622 // Set the appropriate read size and flags as well. 623 // Build request here. 624 RequestPtr mem_req = 625 new Request(tid, fetchBufferBlockPC, fetchBufferSize, 626 Request::INST_FETCH, cpu->instMasterId(), pc, 627 cpu->thread[tid]->contextId()); 628 629 mem_req->taskId(cpu->taskId()); 630 631 memReq[tid] = mem_req; 632 633 // Initiate translation of the icache block 634 fetchStatus[tid] = ItlbWait; 635 FetchTranslation *trans = new FetchTranslation(this); 636 cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(), 637 trans, BaseTLB::Execute); 638 return true; 639} 640 641template <class Impl> 642void 643DefaultFetch<Impl>::finishTranslation(const Fault &fault, RequestPtr mem_req) 644{ 645 ThreadID tid = cpu->contextToThread(mem_req->contextId()); 646 Addr fetchBufferBlockPC = mem_req->getVaddr(); 647 648 assert(!cpu->switchedOut()); 649 650 // Wake up CPU if it was idle 651 cpu->wakeCPU(); 652 653 if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] || 654 mem_req->getVaddr() != memReq[tid]->getVaddr()) { 655 DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n", 656 tid); 657 ++fetchTlbSquashes; 658 delete mem_req; 659 return; 660 } 661 662 663 // If translation was successful, attempt to read the icache block. 664 if (fault == NoFault) { 665 // Check that we're not going off into random memory 666 // If we have, just wait around for commit to squash something and put 667 // us on the right track 668 if (!cpu->system->isMemAddr(mem_req->getPaddr())) { 669 warn("Address %#x is outside of physical memory, stopping fetch\n", 670 mem_req->getPaddr()); 671 fetchStatus[tid] = NoGoodAddr; 672 delete mem_req; 673 memReq[tid] = NULL; 674 return; 675 } 676 677 // Build packet here. 678 PacketPtr data_pkt = new Packet(mem_req, MemCmd::ReadReq); 679 data_pkt->dataDynamic(new uint8_t[fetchBufferSize]); 680 681 fetchBufferPC[tid] = fetchBufferBlockPC; 682 fetchBufferValid[tid] = false; 683 DPRINTF(Fetch, "Fetch: Doing instruction read.\n"); 684 685 fetchedCacheLines++; 686 687 // Access the cache. 688 if (!cpu->getInstPort().sendTimingReq(data_pkt)) { 689 assert(retryPkt == NULL); 690 assert(retryTid == InvalidThreadID); 691 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid); 692 693 fetchStatus[tid] = IcacheWaitRetry; 694 retryPkt = data_pkt; 695 retryTid = tid; 696 cacheBlocked = true; 697 } else { 698 DPRINTF(Fetch, "[tid:%i]: Doing Icache access.\n", tid); 699 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache " 700 "response.\n", tid); 701 lastIcacheStall[tid] = curTick(); 702 fetchStatus[tid] = IcacheWaitResponse; 703 // Notify Fetch Request probe when a packet containing a fetch 704 // request is successfully sent 705 ppFetchRequestSent->notify(mem_req); 706 } 707 } else { 708 // Don't send an instruction to decode if we can't handle it. 709 if (!(numInst < fetchWidth) || !(fetchQueue[tid].size() < fetchQueueSize)) { 710 assert(!finishTranslationEvent.scheduled()); 711 finishTranslationEvent.setFault(fault); 712 finishTranslationEvent.setReq(mem_req); 713 cpu->schedule(finishTranslationEvent, 714 cpu->clockEdge(Cycles(1))); 715 return; 716 } 717 DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected %#x\n", 718 tid, mem_req->getVaddr(), memReq[tid]->getVaddr()); 719 // Translation faulted, icache request won't be sent. 720 delete mem_req; 721 memReq[tid] = NULL; 722 723 // Send the fault to commit. This thread will not do anything 724 // until commit handles the fault. The only other way it can 725 // wake up is if a squash comes along and changes the PC. 726 TheISA::PCState fetchPC = pc[tid]; 727 728 DPRINTF(Fetch, "[tid:%i]: Translation faulted, building noop.\n", tid); 729 // We will use a nop in ordier to carry the fault. 730 DynInstPtr instruction = buildInst(tid, StaticInst::nopStaticInstPtr, 731 NULL, fetchPC, fetchPC, false); 732 733 instruction->setPredTarg(fetchPC); 734 instruction->fault = fault; 735 wroteToTimeBuffer = true; 736 737 DPRINTF(Activity, "Activity this cycle.\n"); 738 cpu->activityThisCycle(); 739 740 fetchStatus[tid] = TrapPending; 741 742 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n", tid); 743 DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %s.\n", 744 tid, fault->name(), pc[tid]); 745 } 746 _status = updateFetchStatus(); 747} 748 749template <class Impl> 750inline void 751DefaultFetch<Impl>::doSquash(const TheISA::PCState &newPC, 752 const DynInstPtr squashInst, ThreadID tid) 753{ 754 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %s.\n", 755 tid, newPC); 756 757 pc[tid] = newPC; 758 fetchOffset[tid] = 0; 759 if (squashInst && squashInst->pcState().instAddr() == newPC.instAddr()) 760 macroop[tid] = squashInst->macroop; 761 else 762 macroop[tid] = NULL; 763 decoder[tid]->reset(); 764 765 // Clear the icache miss if it's outstanding. 766 if (fetchStatus[tid] == IcacheWaitResponse) { 767 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n", 768 tid); 769 memReq[tid] = NULL; 770 } else if (fetchStatus[tid] == ItlbWait) { 771 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding ITLB miss.\n", 772 tid); 773 memReq[tid] = NULL; 774 } 775 776 // Get rid of the retrying packet if it was from this thread. 777 if (retryTid == tid) { 778 assert(cacheBlocked); 779 if (retryPkt) { 780 delete retryPkt->req; 781 delete retryPkt; 782 } 783 retryPkt = NULL; 784 retryTid = InvalidThreadID; 785 } 786 787 fetchStatus[tid] = Squashing; 788 789 // Empty fetch queue 790 fetchQueue[tid].clear(); 791 792 // microops are being squashed, it is not known wheather the 793 // youngest non-squashed microop was marked delayed commit 794 // or not. Setting the flag to true ensures that the 795 // interrupts are not handled when they cannot be, though 796 // some opportunities to handle interrupts may be missed. 797 delayedCommit[tid] = true; 798 799 ++fetchSquashCycles; 800} 801 802template<class Impl> 803void 804DefaultFetch<Impl>::squashFromDecode(const TheISA::PCState &newPC, 805 const DynInstPtr squashInst, 806 const InstSeqNum seq_num, ThreadID tid) 807{ 808 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n", tid); 809 810 doSquash(newPC, squashInst, tid); 811 812 // Tell the CPU to remove any instructions that are in flight between 813 // fetch and decode. 814 cpu->removeInstsUntil(seq_num, tid); 815} 816 817template<class Impl> 818bool 819DefaultFetch<Impl>::checkStall(ThreadID tid) const 820{ 821 bool ret_val = false; 822 823 if (stalls[tid].drain) { 824 assert(cpu->isDraining()); 825 DPRINTF(Fetch,"[tid:%i]: Drain stall detected.\n",tid); 826 ret_val = true; 827 } 828 829 return ret_val; 830} 831 832template<class Impl> 833typename DefaultFetch<Impl>::FetchStatus 834DefaultFetch<Impl>::updateFetchStatus() 835{ 836 //Check Running 837 list<ThreadID>::iterator threads = activeThreads->begin(); 838 list<ThreadID>::iterator end = activeThreads->end(); 839 840 while (threads != end) { 841 ThreadID tid = *threads++; 842 843 if (fetchStatus[tid] == Running || 844 fetchStatus[tid] == Squashing || 845 fetchStatus[tid] == IcacheAccessComplete) { 846 847 if (_status == Inactive) { 848 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid); 849 850 if (fetchStatus[tid] == IcacheAccessComplete) { 851 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache" 852 "completion\n",tid); 853 } 854 855 cpu->activateStage(O3CPU::FetchIdx); 856 } 857 858 return Active; 859 } 860 } 861 862 // Stage is switching from active to inactive, notify CPU of it. 863 if (_status == Active) { 864 DPRINTF(Activity, "Deactivating stage.\n"); 865 866 cpu->deactivateStage(O3CPU::FetchIdx); 867 } 868 869 return Inactive; 870} 871 872template <class Impl> 873void 874DefaultFetch<Impl>::squash(const TheISA::PCState &newPC, 875 const InstSeqNum seq_num, DynInstPtr squashInst, 876 ThreadID tid) 877{ 878 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid); 879 880 doSquash(newPC, squashInst, tid); 881 882 // Tell the CPU to remove any instructions that are not in the ROB. 883 cpu->removeInstsNotInROB(tid); 884} 885 886template <class Impl> 887void 888DefaultFetch<Impl>::tick() 889{ 890 list<ThreadID>::iterator threads = activeThreads->begin(); 891 list<ThreadID>::iterator end = activeThreads->end(); 892 bool status_change = false; 893 894 wroteToTimeBuffer = false; 895 896 for (ThreadID i = 0; i < numThreads; ++i) { 897 issuePipelinedIfetch[i] = false; 898 } 899 900 while (threads != end) { 901 ThreadID tid = *threads++; 902 903 // Check the signals for each thread to determine the proper status 904 // for each thread. 905 bool updated_status = checkSignalsAndUpdate(tid); 906 status_change = status_change || updated_status; 907 } 908 909 DPRINTF(Fetch, "Running stage.\n"); 910 911 if (FullSystem) { 912 if (fromCommit->commitInfo[0].interruptPending) { 913 interruptPending = true; 914 } 915 916 if (fromCommit->commitInfo[0].clearInterrupt) { 917 interruptPending = false; 918 } 919 } 920 921 for (threadFetched = 0; threadFetched < numFetchingThreads; 922 threadFetched++) { 923 // Fetch each of the actively fetching threads. 924 fetch(status_change); 925 } 926 927 // Record number of instructions fetched this cycle for distribution. 928 fetchNisnDist.sample(numInst); 929 930 if (status_change) { 931 // Change the fetch stage status if there was a status change. 932 _status = updateFetchStatus(); 933 } 934 935 // Issue the next I-cache request if possible. 936 for (ThreadID i = 0; i < numThreads; ++i) { 937 if (issuePipelinedIfetch[i]) { 938 pipelineIcacheAccesses(i); 939 } 940 } 941 942 // Send instructions enqueued into the fetch queue to decode. 943 // Limit rate by fetchWidth. Stall if decode is stalled. 944 unsigned insts_to_decode = 0; 945 unsigned available_insts = 0; 946 947 for (auto tid : *activeThreads) { 948 if (!stalls[tid].decode) { 949 available_insts += fetchQueue[tid].size(); 950 } 951 } 952 953 // Pick a random thread to start trying to grab instructions from 954 auto tid_itr = activeThreads->begin(); 955 std::advance(tid_itr, random_mt.random<uint8_t>(0, activeThreads->size() - 1)); 956 957 while (available_insts != 0 && insts_to_decode < decodeWidth) { 958 ThreadID tid = *tid_itr; 959 if (!stalls[tid].decode && !fetchQueue[tid].empty()) { 960 auto inst = fetchQueue[tid].front(); 961 toDecode->insts[toDecode->size++] = inst; 962 DPRINTF(Fetch, "[tid:%i][sn:%i]: Sending instruction to decode from " 963 "fetch queue. Fetch queue size: %i.\n", 964 tid, inst->seqNum, fetchQueue[tid].size()); 965 966 wroteToTimeBuffer = true; 967 fetchQueue[tid].pop_front(); 968 insts_to_decode++; 969 available_insts--; 970 } 971 972 tid_itr++; 973 // Wrap around if at end of active threads list 974 if (tid_itr == activeThreads->end()) 975 tid_itr = activeThreads->begin(); 976 } 977 978 // If there was activity this cycle, inform the CPU of it. 979 if (wroteToTimeBuffer) { 980 DPRINTF(Activity, "Activity this cycle.\n"); 981 cpu->activityThisCycle(); 982 } 983 984 // Reset the number of the instruction we've fetched. 985 numInst = 0; 986} 987 988template <class Impl> 989bool 990DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid) 991{ 992 // Update the per thread stall statuses. 993 if (fromDecode->decodeBlock[tid]) { 994 stalls[tid].decode = true; 995 } 996 997 if (fromDecode->decodeUnblock[tid]) { 998 assert(stalls[tid].decode); 999 assert(!fromDecode->decodeBlock[tid]); 1000 stalls[tid].decode = false; 1001 } 1002 1003 // Check squash signals from commit. 1004 if (fromCommit->commitInfo[tid].squash) { 1005 1006 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash " 1007 "from commit.\n",tid); 1008 // In any case, squash. 1009 squash(fromCommit->commitInfo[tid].pc, 1010 fromCommit->commitInfo[tid].doneSeqNum, 1011 fromCommit->commitInfo[tid].squashInst, tid); 1012 1013 // If it was a branch mispredict on a control instruction, update the 1014 // branch predictor with that instruction, otherwise just kill the 1015 // invalid state we generated in after sequence number 1016 if (fromCommit->commitInfo[tid].mispredictInst && 1017 fromCommit->commitInfo[tid].mispredictInst->isControl()) { 1018 branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum, 1019 fromCommit->commitInfo[tid].pc, 1020 fromCommit->commitInfo[tid].branchTaken, 1021 tid); 1022 } else { 1023 branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum, 1024 tid); 1025 } 1026 1027 return true; 1028 } else if (fromCommit->commitInfo[tid].doneSeqNum) { 1029 // Update the branch predictor if it wasn't a squashed instruction 1030 // that was broadcasted. 1031 branchPred->update(fromCommit->commitInfo[tid].doneSeqNum, tid); 1032 } 1033 1034 // Check squash signals from decode. 1035 if (fromDecode->decodeInfo[tid].squash) { 1036 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash " 1037 "from decode.\n",tid); 1038 1039 // Update the branch predictor. 1040 if (fromDecode->decodeInfo[tid].branchMispredict) { 1041 branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum, 1042 fromDecode->decodeInfo[tid].nextPC, 1043 fromDecode->decodeInfo[tid].branchTaken, 1044 tid); 1045 } else { 1046 branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum, 1047 tid); 1048 } 1049 1050 if (fetchStatus[tid] != Squashing) { 1051 1052 DPRINTF(Fetch, "Squashing from decode with PC = %s\n", 1053 fromDecode->decodeInfo[tid].nextPC); 1054 // Squash unless we're already squashing 1055 squashFromDecode(fromDecode->decodeInfo[tid].nextPC, 1056 fromDecode->decodeInfo[tid].squashInst, 1057 fromDecode->decodeInfo[tid].doneSeqNum, 1058 tid); 1059 1060 return true; 1061 } 1062 } 1063 1064 if (checkStall(tid) && 1065 fetchStatus[tid] != IcacheWaitResponse && 1066 fetchStatus[tid] != IcacheWaitRetry && 1067 fetchStatus[tid] != ItlbWait && 1068 fetchStatus[tid] != QuiescePending) { 1069 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid); 1070 1071 fetchStatus[tid] = Blocked; 1072 1073 return true; 1074 } 1075 1076 if (fetchStatus[tid] == Blocked || 1077 fetchStatus[tid] == Squashing) { 1078 // Switch status to running if fetch isn't being told to block or 1079 // squash this cycle. 1080 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n", 1081 tid); 1082 1083 fetchStatus[tid] = Running; 1084 1085 return true; 1086 } 1087 1088 // If we've reached this point, we have not gotten any signals that 1089 // cause fetch to change its status. Fetch remains the same as before. 1090 return false; 1091} 1092 1093template<class Impl> 1094typename Impl::DynInstPtr 1095DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst, 1096 StaticInstPtr curMacroop, TheISA::PCState thisPC, 1097 TheISA::PCState nextPC, bool trace) 1098{ 1099 // Get a sequence number. 1100 InstSeqNum seq = cpu->getAndIncrementInstSeq(); 1101 1102 // Create a new DynInst from the instruction fetched. 1103 DynInstPtr instruction = 1104 new DynInst(staticInst, curMacroop, thisPC, nextPC, seq, cpu); 1105 instruction->setTid(tid); 1106 1107 instruction->setASID(tid); 1108 1109 instruction->setThreadState(cpu->thread[tid]); 1110 1111 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created " 1112 "[sn:%lli].\n", tid, thisPC.instAddr(), 1113 thisPC.microPC(), seq); 1114 1115 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid, 1116 instruction->staticInst-> 1117 disassemble(thisPC.instAddr())); 1118 1119#if TRACING_ON 1120 if (trace) { 1121 instruction->traceData = 1122 cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid), 1123 instruction->staticInst, thisPC, curMacroop); 1124 } 1125#else 1126 instruction->traceData = NULL; 1127#endif 1128 1129 // Add instruction to the CPU's list of instructions. 1130 instruction->setInstListIt(cpu->addInst(instruction)); 1131 1132 // Write the instruction to the first slot in the queue 1133 // that heads to decode. 1134 assert(numInst < fetchWidth); 1135 fetchQueue[tid].push_back(instruction); 1136 assert(fetchQueue[tid].size() <= fetchQueueSize); 1137 DPRINTF(Fetch, "[tid:%i]: Fetch queue entry created (%i/%i).\n", 1138 tid, fetchQueue[tid].size(), fetchQueueSize); 1139 //toDecode->insts[toDecode->size++] = instruction; 1140 1141 // Keep track of if we can take an interrupt at this boundary 1142 delayedCommit[tid] = instruction->isDelayedCommit(); 1143 1144 return instruction; 1145} 1146 1147template<class Impl> 1148void 1149DefaultFetch<Impl>::fetch(bool &status_change) 1150{ 1151 ////////////////////////////////////////// 1152 // Start actual fetch 1153 ////////////////////////////////////////// 1154 ThreadID tid = getFetchingThread(fetchPolicy); 1155 1156 assert(!cpu->switchedOut()); 1157 1158 if (tid == InvalidThreadID) { 1159 // Breaks looping condition in tick() 1160 threadFetched = numFetchingThreads; 1161 1162 if (numThreads == 1) { // @todo Per-thread stats 1163 profileStall(0); 1164 } 1165 1166 return; 1167 } 1168 1169 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid); 1170 1171 // The current PC. 1172 TheISA::PCState thisPC = pc[tid]; 1173 1174 Addr pcOffset = fetchOffset[tid]; 1175 Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask; 1176 1177 bool inRom = isRomMicroPC(thisPC.microPC()); 1178 1179 // If returning from the delay of a cache miss, then update the status 1180 // to running, otherwise do the cache access. Possibly move this up 1181 // to tick() function. 1182 if (fetchStatus[tid] == IcacheAccessComplete) { 1183 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid); 1184 1185 fetchStatus[tid] = Running; 1186 status_change = true; 1187 } else if (fetchStatus[tid] == Running) { 1188 // Align the fetch PC so its at the start of a fetch buffer segment. 1189 Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr); 1190 1191 // If buffer is no longer valid or fetchAddr has moved to point 1192 // to the next cache block, AND we have no remaining ucode 1193 // from a macro-op, then start fetch from icache. 1194 if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid]) 1195 && !inRom && !macroop[tid]) { 1196 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read " 1197 "instruction, starting at PC %s.\n", tid, thisPC); 1198 1199 fetchCacheLine(fetchAddr, tid, thisPC.instAddr()); 1200 1201 if (fetchStatus[tid] == IcacheWaitResponse) 1202 ++icacheStallCycles; 1203 else if (fetchStatus[tid] == ItlbWait) 1204 ++fetchTlbCycles; 1205 else 1206 ++fetchMiscStallCycles; 1207 return; 1208 } else if ((checkInterrupt(thisPC.instAddr()) && !delayedCommit[tid])) { 1209 // Stall CPU if an interrupt is posted and we're not issuing 1210 // an delayed commit micro-op currently (delayed commit instructions 1211 // are not interruptable by interrupts, only faults) 1212 ++fetchMiscStallCycles; 1213 DPRINTF(Fetch, "[tid:%i]: Fetch is stalled!\n", tid); 1214 return; 1215 } 1216 } else { 1217 if (fetchStatus[tid] == Idle) { 1218 ++fetchIdleCycles; 1219 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid); 1220 } 1221 1222 // Status is Idle, so fetch should do nothing. 1223 return; 1224 } 1225 1226 ++fetchCycles; 1227 1228 TheISA::PCState nextPC = thisPC; 1229 1230 StaticInstPtr staticInst = NULL; 1231 StaticInstPtr curMacroop = macroop[tid]; 1232 1233 // If the read of the first instruction was successful, then grab the 1234 // instructions from the rest of the cache line and put them into the 1235 // queue heading to decode. 1236 1237 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to " 1238 "decode.\n", tid); 1239 1240 // Need to keep track of whether or not a predicted branch 1241 // ended this fetch block. 1242 bool predictedBranch = false; 1243 1244 // Need to halt fetch if quiesce instruction detected 1245 bool quiesce = false; 1246 1247 TheISA::MachInst *cacheInsts = 1248 reinterpret_cast<TheISA::MachInst *>(fetchBuffer[tid]); 1249 1250 const unsigned numInsts = fetchBufferSize / instSize; 1251 unsigned blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize; 1252 1253 // Loop through instruction memory from the cache. 1254 // Keep issuing while fetchWidth is available and branch is not 1255 // predicted taken 1256 while (numInst < fetchWidth && fetchQueue[tid].size() < fetchQueueSize 1257 && !predictedBranch && !quiesce) { 1258 // We need to process more memory if we aren't going to get a 1259 // StaticInst from the rom, the current macroop, or what's already 1260 // in the decoder. 1261 bool needMem = !inRom && !curMacroop && 1262 !decoder[tid]->instReady(); 1263 fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask; 1264 Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr); 1265 1266 if (needMem) { 1267 // If buffer is no longer valid or fetchAddr has moved to point 1268 // to the next cache block then start fetch from icache. 1269 if (!fetchBufferValid[tid] || 1270 fetchBufferBlockPC != fetchBufferPC[tid]) 1271 break; 1272 1273 if (blkOffset >= numInsts) { 1274 // We need to process more memory, but we've run out of the 1275 // current block. 1276 break; 1277 } 1278 1279 if (ISA_HAS_DELAY_SLOT && pcOffset == 0) { 1280 // Walk past any annulled delay slot instructions. 1281 Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask; 1282 while (fetchAddr != pcAddr && blkOffset < numInsts) { 1283 blkOffset++; 1284 fetchAddr += instSize; 1285 } 1286 if (blkOffset >= numInsts) 1287 break; 1288 } 1289 1290 MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]); 1291 decoder[tid]->moreBytes(thisPC, fetchAddr, inst); 1292 1293 if (decoder[tid]->needMoreBytes()) { 1294 blkOffset++; 1295 fetchAddr += instSize; 1296 pcOffset += instSize; 1297 } 1298 } 1299 1300 // Extract as many instructions and/or microops as we can from 1301 // the memory we've processed so far. 1302 do { 1303 if (!(curMacroop || inRom)) { 1304 if (decoder[tid]->instReady()) { 1305 staticInst = decoder[tid]->decode(thisPC); 1306 1307 // Increment stat of fetched instructions. 1308 ++fetchedInsts; 1309 1310 if (staticInst->isMacroop()) { 1311 curMacroop = staticInst; 1312 } else { 1313 pcOffset = 0; 1314 } 1315 } else { 1316 // We need more bytes for this instruction so blkOffset and 1317 // pcOffset will be updated 1318 break; 1319 } 1320 } 1321 // Whether we're moving to a new macroop because we're at the 1322 // end of the current one, or the branch predictor incorrectly 1323 // thinks we are... 1324 bool newMacro = false; 1325 if (curMacroop || inRom) { 1326 if (inRom) { 1327 staticInst = cpu->microcodeRom.fetchMicroop( 1328 thisPC.microPC(), curMacroop); 1329 } else { 1330 staticInst = curMacroop->fetchMicroop(thisPC.microPC()); 1331 } 1332 newMacro |= staticInst->isLastMicroop(); 1333 } 1334 1335 DynInstPtr instruction = 1336 buildInst(tid, staticInst, curMacroop, 1337 thisPC, nextPC, true); 1338 1339 ppFetch->notify(instruction); 1340 numInst++; 1341 1342#if TRACING_ON 1343 if (DTRACE(O3PipeView)) { 1344 instruction->fetchTick = curTick(); 1345 } 1346#endif 1347 1348 nextPC = thisPC; 1349 1350 // If we're branching after this instruction, quit fetching 1351 // from the same block. 1352 predictedBranch |= thisPC.branching(); 1353 predictedBranch |= 1354 lookupAndUpdateNextPC(instruction, nextPC); 1355 if (predictedBranch) { 1356 DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC); 1357 } 1358 1359 newMacro |= thisPC.instAddr() != nextPC.instAddr(); 1360 1361 // Move to the next instruction, unless we have a branch. 1362 thisPC = nextPC; 1363 inRom = isRomMicroPC(thisPC.microPC()); 1364 1365 if (newMacro) { 1366 fetchAddr = thisPC.instAddr() & BaseCPU::PCMask; 1367 blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize; 1368 pcOffset = 0; 1369 curMacroop = NULL; 1370 } 1371 1372 if (instruction->isQuiesce()) { 1373 DPRINTF(Fetch, 1374 "Quiesce instruction encountered, halting fetch!\n"); 1375 fetchStatus[tid] = QuiescePending; 1376 status_change = true; 1377 quiesce = true; 1378 break; 1379 } 1380 } while ((curMacroop || decoder[tid]->instReady()) && 1381 numInst < fetchWidth && 1382 fetchQueue[tid].size() < fetchQueueSize); 1383 1384 // Re-evaluate whether the next instruction to fetch is in micro-op ROM 1385 // or not. 1386 inRom = isRomMicroPC(thisPC.microPC()); 1387 } 1388 1389 if (predictedBranch) { 1390 DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch " 1391 "instruction encountered.\n", tid); 1392 } else if (numInst >= fetchWidth) { 1393 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth " 1394 "for this cycle.\n", tid); 1395 } else if (blkOffset >= fetchBufferSize) { 1396 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of the" 1397 "fetch buffer.\n", tid); 1398 } 1399 1400 macroop[tid] = curMacroop; 1401 fetchOffset[tid] = pcOffset; 1402 1403 if (numInst > 0) { 1404 wroteToTimeBuffer = true; 1405 } 1406 1407 pc[tid] = thisPC; 1408 1409 // pipeline a fetch if we're crossing a fetch buffer boundary and not in 1410 // a state that would preclude fetching 1411 fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask; 1412 Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr); 1413 issuePipelinedIfetch[tid] = fetchBufferBlockPC != fetchBufferPC[tid] && 1414 fetchStatus[tid] != IcacheWaitResponse && 1415 fetchStatus[tid] != ItlbWait && 1416 fetchStatus[tid] != IcacheWaitRetry && 1417 fetchStatus[tid] != QuiescePending && 1418 !curMacroop; 1419} 1420 1421template<class Impl> 1422void 1423DefaultFetch<Impl>::recvReqRetry() 1424{ 1425 if (retryPkt != NULL) { 1426 assert(cacheBlocked); 1427 assert(retryTid != InvalidThreadID); 1428 assert(fetchStatus[retryTid] == IcacheWaitRetry); 1429 1430 if (cpu->getInstPort().sendTimingReq(retryPkt)) { 1431 fetchStatus[retryTid] = IcacheWaitResponse; 1432 // Notify Fetch Request probe when a retryPkt is successfully sent. 1433 // Note that notify must be called before retryPkt is set to NULL. 1434 ppFetchRequestSent->notify(retryPkt->req); 1435 retryPkt = NULL; 1436 retryTid = InvalidThreadID; 1437 cacheBlocked = false; 1438 } 1439 } else { 1440 assert(retryTid == InvalidThreadID); 1441 // Access has been squashed since it was sent out. Just clear 1442 // the cache being blocked. 1443 cacheBlocked = false; 1444 } 1445} 1446 1447/////////////////////////////////////// 1448// // 1449// SMT FETCH POLICY MAINTAINED HERE // 1450// // 1451/////////////////////////////////////// 1452template<class Impl> 1453ThreadID 1454DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority) 1455{ 1456 if (numThreads > 1) { 1457 switch (fetch_priority) { 1458 1459 case SingleThread: 1460 return 0; 1461 1462 case RoundRobin: 1463 return roundRobin(); 1464 1465 case IQ: 1466 return iqCount(); 1467 1468 case LSQ: 1469 return lsqCount(); 1470 1471 case Branch: 1472 return branchCount(); 1473 1474 default: 1475 return InvalidThreadID; 1476 } 1477 } else { 1478 list<ThreadID>::iterator thread = activeThreads->begin(); 1479 if (thread == activeThreads->end()) { 1480 return InvalidThreadID; 1481 } 1482 1483 ThreadID tid = *thread; 1484 1485 if (fetchStatus[tid] == Running || 1486 fetchStatus[tid] == IcacheAccessComplete || 1487 fetchStatus[tid] == Idle) { 1488 return tid; 1489 } else { 1490 return InvalidThreadID; 1491 } 1492 } 1493} 1494 1495 1496template<class Impl> 1497ThreadID 1498DefaultFetch<Impl>::roundRobin() 1499{ 1500 list<ThreadID>::iterator pri_iter = priorityList.begin(); 1501 list<ThreadID>::iterator end = priorityList.end(); 1502 1503 ThreadID high_pri; 1504 1505 while (pri_iter != end) { 1506 high_pri = *pri_iter; 1507 1508 assert(high_pri <= numThreads); 1509 1510 if (fetchStatus[high_pri] == Running || 1511 fetchStatus[high_pri] == IcacheAccessComplete || 1512 fetchStatus[high_pri] == Idle) { 1513 1514 priorityList.erase(pri_iter); 1515 priorityList.push_back(high_pri); 1516 1517 return high_pri; 1518 } 1519 1520 pri_iter++; 1521 } 1522 1523 return InvalidThreadID; 1524} 1525 1526template<class Impl> 1527ThreadID 1528DefaultFetch<Impl>::iqCount() 1529{ 1530 //sorted from lowest->highest 1531 std::priority_queue<unsigned,vector<unsigned>, 1532 std::greater<unsigned> > PQ; 1533 std::map<unsigned, ThreadID> threadMap; 1534 1535 list<ThreadID>::iterator threads = activeThreads->begin(); 1536 list<ThreadID>::iterator end = activeThreads->end(); 1537 1538 while (threads != end) { 1539 ThreadID tid = *threads++; 1540 unsigned iqCount = fromIEW->iewInfo[tid].iqCount; 1541 1542 //we can potentially get tid collisions if two threads 1543 //have the same iqCount, but this should be rare. 1544 PQ.push(iqCount); 1545 threadMap[iqCount] = tid; 1546 } 1547 1548 while (!PQ.empty()) { 1549 ThreadID high_pri = threadMap[PQ.top()]; 1550 1551 if (fetchStatus[high_pri] == Running || 1552 fetchStatus[high_pri] == IcacheAccessComplete || 1553 fetchStatus[high_pri] == Idle) 1554 return high_pri; 1555 else 1556 PQ.pop(); 1557 1558 } 1559 1560 return InvalidThreadID; 1561} 1562 1563template<class Impl> 1564ThreadID 1565DefaultFetch<Impl>::lsqCount() 1566{ 1567 //sorted from lowest->highest 1568 std::priority_queue<unsigned,vector<unsigned>, 1569 std::greater<unsigned> > PQ; 1570 std::map<unsigned, ThreadID> threadMap; 1571 1572 list<ThreadID>::iterator threads = activeThreads->begin(); 1573 list<ThreadID>::iterator end = activeThreads->end(); 1574 1575 while (threads != end) { 1576 ThreadID tid = *threads++; 1577 unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount; 1578 1579 //we can potentially get tid collisions if two threads 1580 //have the same iqCount, but this should be rare. 1581 PQ.push(ldstqCount); 1582 threadMap[ldstqCount] = tid; 1583 } 1584 1585 while (!PQ.empty()) { 1586 ThreadID high_pri = threadMap[PQ.top()]; 1587 1588 if (fetchStatus[high_pri] == Running || 1589 fetchStatus[high_pri] == IcacheAccessComplete || 1590 fetchStatus[high_pri] == Idle) 1591 return high_pri; 1592 else 1593 PQ.pop(); 1594 } 1595 1596 return InvalidThreadID; 1597} 1598 1599template<class Impl> 1600ThreadID 1601DefaultFetch<Impl>::branchCount() 1602{ 1603#if 0 1604 list<ThreadID>::iterator thread = activeThreads->begin(); 1605 assert(thread != activeThreads->end()); 1606 ThreadID tid = *thread; 1607#endif 1608 1609 panic("Branch Count Fetch policy unimplemented\n"); 1610 return InvalidThreadID; 1611} 1612 1613template<class Impl> 1614void 1615DefaultFetch<Impl>::pipelineIcacheAccesses(ThreadID tid) 1616{ 1617 if (!issuePipelinedIfetch[tid]) { 1618 return; 1619 } 1620 1621 // The next PC to access. 1622 TheISA::PCState thisPC = pc[tid]; 1623 1624 if (isRomMicroPC(thisPC.microPC())) { 1625 return; 1626 } 1627 1628 Addr pcOffset = fetchOffset[tid]; 1629 Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask; 1630 1631 // Align the fetch PC so its at the start of a fetch buffer segment. 1632 Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr); 1633 1634 // Unless buffer already got the block, fetch it from icache. 1635 if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])) { 1636 DPRINTF(Fetch, "[tid:%i]: Issuing a pipelined I-cache access, " 1637 "starting at PC %s.\n", tid, thisPC); 1638 1639 fetchCacheLine(fetchAddr, tid, thisPC.instAddr()); 1640 } 1641} 1642 1643template<class Impl> 1644void 1645DefaultFetch<Impl>::profileStall(ThreadID tid) { 1646 DPRINTF(Fetch,"There are no more threads available to fetch from.\n"); 1647 1648 // @todo Per-thread stats 1649 1650 if (stalls[tid].drain) { 1651 ++fetchPendingDrainCycles; 1652 DPRINTF(Fetch, "Fetch is waiting for a drain!\n"); 1653 } else if (activeThreads->empty()) { 1654 ++fetchNoActiveThreadStallCycles; 1655 DPRINTF(Fetch, "Fetch has no active thread!\n"); 1656 } else if (fetchStatus[tid] == Blocked) { 1657 ++fetchBlockedCycles; 1658 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid); 1659 } else if (fetchStatus[tid] == Squashing) { 1660 ++fetchSquashCycles; 1661 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid); 1662 } else if (fetchStatus[tid] == IcacheWaitResponse) { 1663 ++icacheStallCycles; 1664 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", 1665 tid); 1666 } else if (fetchStatus[tid] == ItlbWait) { 1667 ++fetchTlbCycles; 1668 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to " 1669 "finish!\n", tid); 1670 } else if (fetchStatus[tid] == TrapPending) { 1671 ++fetchPendingTrapStallCycles; 1672 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap!\n", 1673 tid); 1674 } else if (fetchStatus[tid] == QuiescePending) { 1675 ++fetchPendingQuiesceStallCycles; 1676 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending quiesce " 1677 "instruction!\n", tid); 1678 } else if (fetchStatus[tid] == IcacheWaitRetry) { 1679 ++fetchIcacheWaitRetryStallCycles; 1680 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for an I-cache retry!\n", 1681 tid); 1682 } else if (fetchStatus[tid] == NoGoodAddr) { 1683 DPRINTF(Fetch, "[tid:%i]: Fetch predicted non-executable address\n", 1684 tid); 1685 } else { 1686 DPRINTF(Fetch, "[tid:%i]: Unexpected fetch stall reason (Status: %i).\n", 1687 tid, fetchStatus[tid]); 1688 } 1689} 1690 1691#endif//__CPU_O3_FETCH_IMPL_HH__ 1692