fetch.hh revision 8229:78bf55f23338
1/* 2 * Copyright (c) 2010 ARM Limited 3 * All rights reserved 4 * 5 * The license below extends only to copyright in the software and shall 6 * not be construed as granting a license to any other intellectual 7 * property including but not limited to intellectual property relating 8 * to a hardware implementation of the functionality of the software 9 * licensed hereunder. You may use the software subject to the license 10 * terms below provided that you ensure that this notice is replicated 11 * unmodified and in its entirety in all distributions of the software, 12 * modified or unmodified, in source code or in binary form. 13 * 14 * Copyright (c) 2004-2006 The Regents of The University of Michigan 15 * All rights reserved. 16 * 17 * Redistribution and use in source and binary forms, with or without 18 * modification, are permitted provided that the following conditions are 19 * met: redistributions of source code must retain the above copyright 20 * notice, this list of conditions and the following disclaimer; 21 * redistributions in binary form must reproduce the above copyright 22 * notice, this list of conditions and the following disclaimer in the 23 * documentation and/or other materials provided with the distribution; 24 * neither the name of the copyright holders nor the names of its 25 * contributors may be used to endorse or promote products derived from 26 * this software without specific prior written permission. 27 * 28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 39 * 40 * Authors: Kevin Lim 41 * Korey Sewell 42 */ 43 44#ifndef __CPU_O3_FETCH_HH__ 45#define __CPU_O3_FETCH_HH__ 46 47#include "arch/predecoder.hh" 48#include "arch/utility.hh" 49#include "base/statistics.hh" 50#include "config/the_isa.hh" 51#include "cpu/pc_event.hh" 52#include "cpu/timebuf.hh" 53#include "cpu/translation.hh" 54#include "mem/packet.hh" 55#include "mem/port.hh" 56#include "sim/eventq.hh" 57 58class DerivO3CPUParams; 59 60/** 61 * DefaultFetch class handles both single threaded and SMT fetch. Its 62 * width is specified by the parameters; each cycle it tries to fetch 63 * that many instructions. It supports using a branch predictor to 64 * predict direction and targets. 65 * It supports the idling functionality of the CPU by indicating to 66 * the CPU when it is active and inactive. 67 */ 68template <class Impl> 69class DefaultFetch 70{ 71 public: 72 /** Typedefs from Impl. */ 73 typedef typename Impl::CPUPol CPUPol; 74 typedef typename Impl::DynInst DynInst; 75 typedef typename Impl::DynInstPtr DynInstPtr; 76 typedef typename Impl::O3CPU O3CPU; 77 78 /** Typedefs from the CPU policy. */ 79 typedef typename CPUPol::BPredUnit BPredUnit; 80 typedef typename CPUPol::FetchStruct FetchStruct; 81 typedef typename CPUPol::TimeStruct TimeStruct; 82 83 /** Typedefs from ISA. */ 84 typedef TheISA::MachInst MachInst; 85 typedef TheISA::ExtMachInst ExtMachInst; 86 87 /** IcachePort class for DefaultFetch. Handles doing the 88 * communication with the cache/memory. 89 */ 90 class IcachePort : public Port 91 { 92 protected: 93 /** Pointer to fetch. */ 94 DefaultFetch<Impl> *fetch; 95 96 public: 97 /** Default constructor. */ 98 IcachePort(DefaultFetch<Impl> *_fetch) 99 : Port(_fetch->name() + "-iport", _fetch->cpu), fetch(_fetch) 100 { } 101 102 bool snoopRangeSent; 103 104 virtual void setPeer(Port *port); 105 106 protected: 107 /** Atomic version of receive. Panics. */ 108 virtual Tick recvAtomic(PacketPtr pkt); 109 110 /** Functional version of receive. Panics. */ 111 virtual void recvFunctional(PacketPtr pkt); 112 113 /** Receives status change. Other than range changing, panics. */ 114 virtual void recvStatusChange(Status status); 115 116 /** Returns the address ranges of this device. */ 117 virtual void getDeviceAddressRanges(AddrRangeList &resp, 118 bool &snoop) 119 { resp.clear(); snoop = true; } 120 121 /** Timing version of receive. Handles setting fetch to the 122 * proper status to start fetching. */ 123 virtual bool recvTiming(PacketPtr pkt); 124 125 /** Handles doing a retry of a failed fetch. */ 126 virtual void recvRetry(); 127 }; 128 129 class FetchTranslation : public BaseTLB::Translation 130 { 131 protected: 132 DefaultFetch<Impl> *fetch; 133 134 public: 135 FetchTranslation(DefaultFetch<Impl> *_fetch) 136 : fetch(_fetch) 137 {} 138 139 void 140 markDelayed() 141 {} 142 143 void 144 finish(Fault fault, RequestPtr req, ThreadContext *tc, 145 BaseTLB::Mode mode) 146 { 147 assert(mode == BaseTLB::Execute); 148 fetch->finishTranslation(fault, req); 149 delete this; 150 } 151 }; 152 153 public: 154 /** Overall fetch status. Used to determine if the CPU can 155 * deschedule itsef due to a lack of activity. 156 */ 157 enum FetchStatus { 158 Active, 159 Inactive 160 }; 161 162 /** Individual thread status. */ 163 enum ThreadStatus { 164 Running, 165 Idle, 166 Squashing, 167 Blocked, 168 Fetching, 169 TrapPending, 170 QuiescePending, 171 SwitchOut, 172 ItlbWait, 173 IcacheWaitResponse, 174 IcacheWaitRetry, 175 IcacheAccessComplete 176 }; 177 178 /** Fetching Policy, Add new policies here.*/ 179 enum FetchPriority { 180 SingleThread, 181 RoundRobin, 182 Branch, 183 IQ, 184 LSQ 185 }; 186 187 private: 188 /** Fetch status. */ 189 FetchStatus _status; 190 191 /** Per-thread status. */ 192 ThreadStatus fetchStatus[Impl::MaxThreads]; 193 194 /** Fetch policy. */ 195 FetchPriority fetchPolicy; 196 197 /** List that has the threads organized by priority. */ 198 std::list<ThreadID> priorityList; 199 200 public: 201 /** DefaultFetch constructor. */ 202 DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params); 203 204 /** Returns the name of fetch. */ 205 std::string name() const; 206 207 /** Registers statistics. */ 208 void regStats(); 209 210 /** Returns the icache port. */ 211 Port *getIcachePort() { return icachePort; } 212 213 /** Sets the main backwards communication time buffer pointer. */ 214 void setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer); 215 216 /** Sets pointer to list of active threads. */ 217 void setActiveThreads(std::list<ThreadID> *at_ptr); 218 219 /** Sets pointer to time buffer used to communicate to the next stage. */ 220 void setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr); 221 222 /** Initialize stage. */ 223 void initStage(); 224 225 /** Tells the fetch stage that the Icache is set. */ 226 void setIcache(); 227 228 /** Processes cache completion event. */ 229 void processCacheCompletion(PacketPtr pkt); 230 231 /** Begins the drain of the fetch stage. */ 232 bool drain(); 233 234 /** Resumes execution after a drain. */ 235 void resume(); 236 237 /** Tells fetch stage to prepare to be switched out. */ 238 void switchOut(); 239 240 /** Takes over from another CPU's thread. */ 241 void takeOverFrom(); 242 243 /** Checks if the fetch stage is switched out. */ 244 bool isSwitchedOut() { return switchedOut; } 245 246 /** Tells fetch to wake up from a quiesce instruction. */ 247 void wakeFromQuiesce(); 248 249 private: 250 /** Changes the status of this stage to active, and indicates this 251 * to the CPU. 252 */ 253 inline void switchToActive(); 254 255 /** Changes the status of this stage to inactive, and indicates 256 * this to the CPU. 257 */ 258 inline void switchToInactive(); 259 260 /** 261 * Looks up in the branch predictor to see if the next PC should be 262 * either next PC+=MachInst or a branch target. 263 * @param next_PC Next PC variable passed in by reference. It is 264 * expected to be set to the current PC; it will be updated with what 265 * the next PC will be. 266 * @param next_NPC Used for ISAs which use delay slots. 267 * @return Whether or not a branch was predicted as taken. 268 */ 269 bool lookupAndUpdateNextPC(DynInstPtr &inst, TheISA::PCState &pc); 270 271 /** 272 * Fetches the cache line that contains fetch_PC. Returns any 273 * fault that happened. Puts the data into the class variable 274 * cacheData. 275 * @param vaddr The memory address that is being fetched from. 276 * @param ret_fault The fault reference that will be set to the result of 277 * the icache access. 278 * @param tid Thread id. 279 * @param pc The actual PC of the current instruction. 280 * @return Any fault that occured. 281 */ 282 bool fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc); 283 void finishTranslation(Fault fault, RequestPtr mem_req); 284 285 286 /** Check if an interrupt is pending and that we need to handle 287 */ 288 bool 289 checkInterrupt(Addr pc) 290 { 291 return (interruptPending && (THE_ISA != ALPHA_ISA || !(pc & 0x3))); 292 } 293 294 /** Squashes a specific thread and resets the PC. */ 295 inline void doSquash(const TheISA::PCState &newPC, ThreadID tid); 296 297 /** Squashes a specific thread and resets the PC. Also tells the CPU to 298 * remove any instructions between fetch and decode that should be sqaushed. 299 */ 300 void squashFromDecode(const TheISA::PCState &newPC, 301 const InstSeqNum &seq_num, ThreadID tid); 302 303 /** Checks if a thread is stalled. */ 304 bool checkStall(ThreadID tid) const; 305 306 /** Updates overall fetch stage status; to be called at the end of each 307 * cycle. */ 308 FetchStatus updateFetchStatus(); 309 310 public: 311 /** Squashes a specific thread and resets the PC. Also tells the CPU to 312 * remove any instructions that are not in the ROB. The source of this 313 * squash should be the commit stage. 314 */ 315 void squash(const TheISA::PCState &newPC, const InstSeqNum &seq_num, 316 DynInstPtr &squashInst, ThreadID tid); 317 318 /** Ticks the fetch stage, processing all inputs signals and fetching 319 * as many instructions as possible. 320 */ 321 void tick(); 322 323 /** Checks all input signals and updates the status as necessary. 324 * @return: Returns if the status has changed due to input signals. 325 */ 326 bool checkSignalsAndUpdate(ThreadID tid); 327 328 /** Does the actual fetching of instructions and passing them on to the 329 * next stage. 330 * @param status_change fetch() sets this variable if there was a status 331 * change (ie switching to IcacheMissStall). 332 */ 333 void fetch(bool &status_change); 334 335 /** Align a PC to the start of an I-cache block. */ 336 Addr icacheBlockAlignPC(Addr addr) 337 { 338 return (addr & ~(cacheBlkMask)); 339 } 340 341 private: 342 DynInstPtr buildInst(ThreadID tid, StaticInstPtr staticInst, 343 StaticInstPtr curMacroop, TheISA::PCState thisPC, 344 TheISA::PCState nextPC, bool trace); 345 346 /** Handles retrying the fetch access. */ 347 void recvRetry(); 348 349 /** Returns the appropriate thread to fetch, given the fetch policy. */ 350 ThreadID getFetchingThread(FetchPriority &fetch_priority); 351 352 /** Returns the appropriate thread to fetch using a round robin policy. */ 353 ThreadID roundRobin(); 354 355 /** Returns the appropriate thread to fetch using the IQ count policy. */ 356 ThreadID iqCount(); 357 358 /** Returns the appropriate thread to fetch using the LSQ count policy. */ 359 ThreadID lsqCount(); 360 361 /** Returns the appropriate thread to fetch using the branch count 362 * policy. */ 363 ThreadID branchCount(); 364 365 private: 366 /** Pointer to the O3CPU. */ 367 O3CPU *cpu; 368 369 /** Time buffer interface. */ 370 TimeBuffer<TimeStruct> *timeBuffer; 371 372 /** Wire to get decode's information from backwards time buffer. */ 373 typename TimeBuffer<TimeStruct>::wire fromDecode; 374 375 /** Wire to get rename's information from backwards time buffer. */ 376 typename TimeBuffer<TimeStruct>::wire fromRename; 377 378 /** Wire to get iew's information from backwards time buffer. */ 379 typename TimeBuffer<TimeStruct>::wire fromIEW; 380 381 /** Wire to get commit's information from backwards time buffer. */ 382 typename TimeBuffer<TimeStruct>::wire fromCommit; 383 384 /** Internal fetch instruction queue. */ 385 TimeBuffer<FetchStruct> *fetchQueue; 386 387 //Might be annoying how this name is different than the queue. 388 /** Wire used to write any information heading to decode. */ 389 typename TimeBuffer<FetchStruct>::wire toDecode; 390 391 /** Icache interface. */ 392 IcachePort *icachePort; 393 394 /** BPredUnit. */ 395 BPredUnit branchPred; 396 397 /** Predecoder. */ 398 TheISA::Predecoder predecoder; 399 400 TheISA::PCState pc[Impl::MaxThreads]; 401 402 Addr fetchOffset[Impl::MaxThreads]; 403 404 StaticInstPtr macroop[Impl::MaxThreads]; 405 406 /** Memory request used to access cache. */ 407 RequestPtr memReq[Impl::MaxThreads]; 408 409 /** Variable that tracks if fetch has written to the time buffer this 410 * cycle. Used to tell CPU if there is activity this cycle. 411 */ 412 bool wroteToTimeBuffer; 413 414 /** Tracks how many instructions has been fetched this cycle. */ 415 int numInst; 416 417 /** Source of possible stalls. */ 418 struct Stalls { 419 bool decode; 420 bool rename; 421 bool iew; 422 bool commit; 423 }; 424 425 /** Tracks which stages are telling fetch to stall. */ 426 Stalls stalls[Impl::MaxThreads]; 427 428 /** Decode to fetch delay, in ticks. */ 429 unsigned decodeToFetchDelay; 430 431 /** Rename to fetch delay, in ticks. */ 432 unsigned renameToFetchDelay; 433 434 /** IEW to fetch delay, in ticks. */ 435 unsigned iewToFetchDelay; 436 437 /** Commit to fetch delay, in ticks. */ 438 unsigned commitToFetchDelay; 439 440 /** The width of fetch in instructions. */ 441 unsigned fetchWidth; 442 443 /** Is the cache blocked? If so no threads can access it. */ 444 bool cacheBlocked; 445 446 /** The packet that is waiting to be retried. */ 447 PacketPtr retryPkt; 448 449 /** The thread that is waiting on the cache to tell fetch to retry. */ 450 ThreadID retryTid; 451 452 /** Cache block size. */ 453 int cacheBlkSize; 454 455 /** Mask to get a cache block's address. */ 456 Addr cacheBlkMask; 457 458 /** The cache line being fetched. */ 459 uint8_t *cacheData[Impl::MaxThreads]; 460 461 /** The PC of the cacheline that has been loaded. */ 462 Addr cacheDataPC[Impl::MaxThreads]; 463 464 /** Whether or not the cache data is valid. */ 465 bool cacheDataValid[Impl::MaxThreads]; 466 467 /** Size of instructions. */ 468 int instSize; 469 470 /** Icache stall statistics. */ 471 Counter lastIcacheStall[Impl::MaxThreads]; 472 473 /** List of Active Threads */ 474 std::list<ThreadID> *activeThreads; 475 476 /** Number of threads. */ 477 ThreadID numThreads; 478 479 /** Number of threads that are actively fetching. */ 480 ThreadID numFetchingThreads; 481 482 /** Thread ID being fetched. */ 483 ThreadID threadFetched; 484 485 /** Checks if there is an interrupt pending. If there is, fetch 486 * must stop once it is not fetching PAL instructions. 487 */ 488 bool interruptPending; 489 490 /** Is there a drain pending. */ 491 bool drainPending; 492 493 /** Records if fetch is switched out. */ 494 bool switchedOut; 495 496 // @todo: Consider making these vectors and tracking on a per thread basis. 497 /** Stat for total number of cycles stalled due to an icache miss. */ 498 Stats::Scalar icacheStallCycles; 499 /** Stat for total number of fetched instructions. */ 500 Stats::Scalar fetchedInsts; 501 /** Total number of fetched branches. */ 502 Stats::Scalar fetchedBranches; 503 /** Stat for total number of predicted branches. */ 504 Stats::Scalar predictedBranches; 505 /** Stat for total number of cycles spent fetching. */ 506 Stats::Scalar fetchCycles; 507 /** Stat for total number of cycles spent squashing. */ 508 Stats::Scalar fetchSquashCycles; 509 /** Stat for total number of cycles spent waiting for translation */ 510 Stats::Scalar fetchTlbCycles; 511 /** Stat for total number of cycles spent blocked due to other stages in 512 * the pipeline. 513 */ 514 Stats::Scalar fetchIdleCycles; 515 /** Total number of cycles spent blocked. */ 516 Stats::Scalar fetchBlockedCycles; 517 /** Total number of cycles spent in any other state. */ 518 Stats::Scalar fetchMiscStallCycles; 519 /** Stat for total number of fetched cache lines. */ 520 Stats::Scalar fetchedCacheLines; 521 /** Total number of outstanding icache accesses that were dropped 522 * due to a squash. 523 */ 524 Stats::Scalar fetchIcacheSquashes; 525 /** Total number of outstanding tlb accesses that were dropped 526 * due to a squash. 527 */ 528 Stats::Scalar fetchTlbSquashes; 529 /** Distribution of number of instructions fetched each cycle. */ 530 Stats::Distribution fetchNisnDist; 531 /** Rate of how often fetch was idle. */ 532 Stats::Formula idleRate; 533 /** Number of branch fetches per cycle. */ 534 Stats::Formula branchRate; 535 /** Number of instruction fetched per cycle. */ 536 Stats::Formula fetchRate; 537}; 538 539#endif //__CPU_O3_FETCH_HH__ 540