2 * Copyright (c) 2011-2013 ARM Limited
3 * Copyright (c) 2013 Advanced Micro Devices, Inc.
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.
15 * Copyright (c) 2004-2005 The Regents of The University of Michigan
16 * Copyright (c) 2011 Regents of the University of California
17 * All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions are
21 * met: redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer;
23 * redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution;
26 * neither the name of the copyright holders nor the names of its
27 * contributors may be used to endorse or promote products derived from
28 * this software without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
33 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
34 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
36 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
40 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 #ifndef __CPU_O3_CPU_HH__
48 #define __CPU_O3_CPU_HH__
56 #include "arch/types.hh"
57 #include "base/statistics.hh"
58 #include "config/the_isa.hh"
59 #include "cpu/o3/comm.hh"
60 #include "cpu/o3/cpu_policy.hh"
61 #include "cpu/o3/scoreboard.hh"
62 #include "cpu/o3/thread_state.hh"
63 #include "cpu/activity.hh"
64 #include "cpu/base.hh"
65 #include "cpu/simple_thread.hh"
66 #include "cpu/timebuf.hh"
67 //#include "cpu/o3/thread_context.hh"
68 #include "params/DerivO3CPU.hh"
69 #include "sim/process.hh"
75 class O3ThreadContext;
83 class BaseO3CPU : public BaseCPU
85 //Stuff that's pretty ISA independent will go here.
87 BaseO3CPU(BaseCPUParams *params);
93 * FullO3CPU class, has each of the stages (fetch through commit)
94 * within it, as well as all of the time buffers between stages. The
95 * tick() function for the CPU is defined here.
98 class FullO3CPU : public BaseO3CPU
101 // Typedefs from the Impl here.
102 typedef typename Impl::CPUPol CPUPolicy;
103 typedef typename Impl::DynInstPtr DynInstPtr;
104 typedef typename Impl::O3CPU O3CPU;
106 typedef O3ThreadState<Impl> ImplState;
107 typedef O3ThreadState<Impl> Thread;
109 typedef typename std::list<DynInstPtr>::iterator ListIt;
111 friend class O3ThreadContext<Impl>;
125 /** Overall CPU status. */
131 * IcachePort class for instruction fetch.
133 class IcachePort : public MasterPort
136 /** Pointer to fetch. */
137 DefaultFetch<Impl> *fetch;
140 /** Default constructor. */
141 IcachePort(DefaultFetch<Impl> *_fetch, FullO3CPU<Impl>* _cpu)
142 : MasterPort(_cpu->name() + ".icache_port", _cpu), fetch(_fetch)
147 /** Timing version of receive. Handles setting fetch to the
148 * proper status to start fetching. */
149 virtual bool recvTimingResp(PacketPtr pkt);
150 virtual void recvTimingSnoopReq(PacketPtr pkt) { }
152 /** Handles doing a retry of a failed fetch. */
153 virtual void recvReqRetry();
157 * DcachePort class for the load/store queue.
159 class DcachePort : public MasterPort
163 /** Pointer to LSQ. */
165 FullO3CPU<Impl> *cpu;
168 /** Default constructor. */
169 DcachePort(LSQ<Impl> *_lsq, FullO3CPU<Impl>* _cpu)
170 : MasterPort(_cpu->name() + ".dcache_port", _cpu), lsq(_lsq),
176 /** Timing version of receive. Handles writing back and
177 * completing the load or store that has returned from
179 virtual bool recvTimingResp(PacketPtr pkt);
180 virtual void recvTimingSnoopReq(PacketPtr pkt);
182 virtual void recvFunctionalSnoop(PacketPtr pkt)
184 // @todo: Is there a need for potential invalidation here?
187 /** Handles doing a retry of the previous send. */
188 virtual void recvReqRetry();
191 * As this CPU requires snooping to maintain the load store queue
192 * change the behaviour from the base CPU port.
194 * @return true since we have to snoop
196 virtual bool isSnooping() const { return true; }
199 class TickEvent : public Event
202 /** Pointer to the CPU. */
203 FullO3CPU<Impl> *cpu;
206 /** Constructs a tick event. */
207 TickEvent(FullO3CPU<Impl> *c);
209 /** Processes a tick event, calling tick() on the CPU. */
211 /** Returns the description of the tick event. */
212 const char *description() const;
215 /** The tick event used for scheduling CPU ticks. */
218 /** Schedule tick event, regardless of its current state. */
219 void scheduleTickEvent(Cycles delay)
221 if (tickEvent.squashed())
222 reschedule(tickEvent, clockEdge(delay));
223 else if (!tickEvent.scheduled())
224 schedule(tickEvent, clockEdge(delay));
227 /** Unschedule tick event, regardless of its current state. */
228 void unscheduleTickEvent()
230 if (tickEvent.scheduled())
235 * Check if the pipeline has drained and signal drain done.
237 * This method checks if a drain has been requested and if the CPU
238 * has drained successfully (i.e., there are no instructions in
239 * the pipeline). If the CPU has drained, it deschedules the tick
240 * event and signals the drain manager.
242 * @return False if a drain hasn't been requested or the CPU
243 * hasn't drained, true otherwise.
248 * Perform sanity checks after a drain.
250 * This method is called from drain() when it has determined that
251 * the CPU is fully drained when gem5 is compiled with the NDEBUG
252 * macro undefined. The intention of this method is to do more
253 * extensive tests than the isDrained() method to weed out any
256 void drainSanityCheck() const;
258 /** Check if a system is in a drained state. */
259 bool isDrained() const;
262 /** Constructs a CPU with the given parameters. */
263 FullO3CPU(DerivO3CPUParams *params);
267 /** Registers statistics. */
268 void regStats() override;
270 ProbePointArg<PacketPtr> *ppInstAccessComplete;
271 ProbePointArg<std::pair<DynInstPtr, PacketPtr> > *ppDataAccessComplete;
273 /** Register probe points. */
274 void regProbePoints() override;
276 void demapPage(Addr vaddr, uint64_t asn)
278 this->itb->demapPage(vaddr, asn);
279 this->dtb->demapPage(vaddr, asn);
282 void demapInstPage(Addr vaddr, uint64_t asn)
284 this->itb->demapPage(vaddr, asn);
287 void demapDataPage(Addr vaddr, uint64_t asn)
289 this->dtb->demapPage(vaddr, asn);
292 /** Ticks CPU, calling tick() on each stage, and checking the overall
293 * activity to see if the CPU should deschedule itself.
297 /** Initialize the CPU */
298 void init() override;
300 void startup() override;
302 /** Returns the Number of Active Threads in the CPU */
303 int numActiveThreads()
304 { return activeThreads.size(); }
306 /** Add Thread to Active Threads List */
307 void activateThread(ThreadID tid);
309 /** Remove Thread from Active Threads List */
310 void deactivateThread(ThreadID tid);
312 /** Setup CPU to insert a thread's context */
313 void insertThread(ThreadID tid);
315 /** Remove all of a thread's context from CPU */
316 void removeThread(ThreadID tid);
318 /** Count the Total Instructions Committed in the CPU. */
319 Counter totalInsts() const override;
321 /** Count the Total Ops (including micro ops) committed in the CPU. */
322 Counter totalOps() const override;
324 /** Add Thread to Active Threads List. */
325 void activateContext(ThreadID tid) override;
327 /** Remove Thread from Active Threads List */
328 void suspendContext(ThreadID tid) override;
330 /** Remove Thread from Active Threads List &&
331 * Remove Thread Context from CPU.
333 void haltContext(ThreadID tid) override;
335 /** Update The Order In Which We Process Threads. */
336 void updateThreadPriority();
338 /** Is the CPU draining? */
339 bool isDraining() const { return drainState() == DrainState::Draining; }
341 void serializeThread(CheckpointOut &cp, ThreadID tid) const override;
342 void unserializeThread(CheckpointIn &cp, ThreadID tid) override;
345 /** Executes a syscall.
346 * @todo: Determine if this needs to be virtual.
348 void syscall(int64_t callnum, ThreadID tid);
350 /** Starts draining the CPU's pipeline of all instructions in
351 * order to stop all memory accesses. */
352 DrainState drain() override;
354 /** Resumes execution after a drain. */
355 void drainResume() override;
358 * Commit has reached a safe point to drain a thread.
360 * Commit calls this method to inform the pipeline that it has
361 * reached a point where it is not executed microcode and is about
362 * to squash uncommitted instructions to fully drain the pipeline.
364 void commitDrained(ThreadID tid);
366 /** Switches out this CPU. */
367 void switchOut() override;
369 /** Takes over from another CPU. */
370 void takeOverFrom(BaseCPU *oldCPU) override;
372 void verifyMemoryMode() const override;
374 /** Get the current instruction sequence number, and increment it. */
375 InstSeqNum getAndIncrementInstSeq()
376 { return globalSeqNum++; }
378 /** Traps to handle given fault. */
379 void trap(const Fault &fault, ThreadID tid, const StaticInstPtr &inst);
381 /** HW return from error interrupt. */
382 Fault hwrei(ThreadID tid);
384 bool simPalCheck(int palFunc, ThreadID tid);
386 /** Returns the Fault for any valid interrupt. */
387 Fault getInterrupts();
389 /** Processes any an interrupt fault. */
390 void processInterrupts(const Fault &interrupt);
392 /** Halts the CPU. */
393 void halt() { panic("Halt not implemented!\n"); }
395 /** Register accessors. Index refers to the physical register index. */
397 /** Reads a miscellaneous register. */
398 TheISA::MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid) const;
400 /** Reads a misc. register, including any side effects the read
401 * might have as defined by the architecture.
403 TheISA::MiscReg readMiscReg(int misc_reg, ThreadID tid);
405 /** Sets a miscellaneous register. */
406 void setMiscRegNoEffect(int misc_reg, const TheISA::MiscReg &val,
409 /** Sets a misc. register, including any side effects the write
410 * might have as defined by the architecture.
412 void setMiscReg(int misc_reg, const TheISA::MiscReg &val,
415 uint64_t readIntReg(int reg_idx);
417 TheISA::FloatReg readFloatReg(int reg_idx);
419 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
421 TheISA::CCReg readCCReg(int reg_idx);
423 void setIntReg(int reg_idx, uint64_t val);
425 void setFloatReg(int reg_idx, TheISA::FloatReg val);
427 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
429 void setCCReg(int reg_idx, TheISA::CCReg val);
431 uint64_t readArchIntReg(int reg_idx, ThreadID tid);
433 float readArchFloatReg(int reg_idx, ThreadID tid);
435 uint64_t readArchFloatRegInt(int reg_idx, ThreadID tid);
437 TheISA::CCReg readArchCCReg(int reg_idx, ThreadID tid);
439 /** Architectural register accessors. Looks up in the commit
440 * rename table to obtain the true physical index of the
441 * architected register first, then accesses that physical
444 void setArchIntReg(int reg_idx, uint64_t val, ThreadID tid);
446 void setArchFloatReg(int reg_idx, float val, ThreadID tid);
448 void setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid);
450 void setArchCCReg(int reg_idx, TheISA::CCReg val, ThreadID tid);
452 /** Sets the commit PC state of a specific thread. */
453 void pcState(const TheISA::PCState &newPCState, ThreadID tid);
455 /** Reads the commit PC state of a specific thread. */
456 TheISA::PCState pcState(ThreadID tid);
458 /** Reads the commit PC of a specific thread. */
459 Addr instAddr(ThreadID tid);
461 /** Reads the commit micro PC of a specific thread. */
462 MicroPC microPC(ThreadID tid);
464 /** Reads the next PC of a specific thread. */
465 Addr nextInstAddr(ThreadID tid);
467 /** Initiates a squash of all in-flight instructions for a given
468 * thread. The source of the squash is an external update of
469 * state through the TC.
471 void squashFromTC(ThreadID tid);
473 /** Function to add instruction onto the head of the list of the
474 * instructions. Used when new instructions are fetched.
476 ListIt addInst(DynInstPtr &inst);
478 /** Function to tell the CPU that an instruction has completed. */
479 void instDone(ThreadID tid, DynInstPtr &inst);
481 /** Remove an instruction from the front end of the list. There's
482 * no restriction on location of the instruction.
484 void removeFrontInst(DynInstPtr &inst);
486 /** Remove all instructions that are not currently in the ROB.
487 * There's also an option to not squash delay slot instructions.*/
488 void removeInstsNotInROB(ThreadID tid);
490 /** Remove all instructions younger than the given sequence number. */
491 void removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid);
493 /** Removes the instruction pointed to by the iterator. */
494 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
496 /** Cleans up all instructions on the remove list. */
497 void cleanUpRemovedInsts();
499 /** Debug function to print all instructions on the list. */
504 /** Count of total number of dynamic instructions in flight. */
508 /** List of all the instructions in flight. */
509 std::list<DynInstPtr> instList;
511 /** List of all the instructions that will be removed at the end of this
514 std::queue<ListIt> removeList;
517 /** Debug structure to keep track of the sequence numbers still in
520 std::set<InstSeqNum> snList;
523 /** Records if instructions need to be removed this cycle due to
524 * being retired or squashed.
526 bool removeInstsThisCycle;
529 /** The fetch stage. */
530 typename CPUPolicy::Fetch fetch;
532 /** The decode stage. */
533 typename CPUPolicy::Decode decode;
535 /** The dispatch stage. */
536 typename CPUPolicy::Rename rename;
538 /** The issue/execute/writeback stages. */
539 typename CPUPolicy::IEW iew;
541 /** The commit stage. */
542 typename CPUPolicy::Commit commit;
544 /** The register file. */
547 /** The free list. */
548 typename CPUPolicy::FreeList freeList;
550 /** The rename map. */
551 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
553 /** The commit rename map. */
554 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
556 /** The re-order buffer. */
557 typename CPUPolicy::ROB rob;
559 /** Active Threads List */
560 std::list<ThreadID> activeThreads;
562 /** Integer Register Scoreboard */
563 Scoreboard scoreboard;
565 std::vector<TheISA::ISA *> isa;
567 /** Instruction port. Note that it has to appear after the fetch stage. */
568 IcachePort icachePort;
570 /** Data port. Note that it has to appear after the iew stages */
571 DcachePort dcachePort;
574 /** Enum to give each stage a specific index, so when calling
575 * activateStage() or deactivateStage(), they can specify which stage
576 * is being activated/deactivated.
586 /** Typedefs from the Impl to get the structs that each of the
587 * time buffers should use.
589 typedef typename CPUPolicy::TimeStruct TimeStruct;
591 typedef typename CPUPolicy::FetchStruct FetchStruct;
593 typedef typename CPUPolicy::DecodeStruct DecodeStruct;
595 typedef typename CPUPolicy::RenameStruct RenameStruct;
597 typedef typename CPUPolicy::IEWStruct IEWStruct;
599 /** The main time buffer to do backwards communication. */
600 TimeBuffer<TimeStruct> timeBuffer;
602 /** The fetch stage's instruction queue. */
603 TimeBuffer<FetchStruct> fetchQueue;
605 /** The decode stage's instruction queue. */
606 TimeBuffer<DecodeStruct> decodeQueue;
608 /** The rename stage's instruction queue. */
609 TimeBuffer<RenameStruct> renameQueue;
611 /** The IEW stage's instruction queue. */
612 TimeBuffer<IEWStruct> iewQueue;
615 /** The activity recorder; used to tell if the CPU has any
616 * activity remaining or if it can go to idle and deschedule
619 ActivityRecorder activityRec;
622 /** Records that there was time buffer activity this cycle. */
623 void activityThisCycle() { activityRec.activity(); }
625 /** Changes a stage's status to active within the activity recorder. */
626 void activateStage(const StageIdx idx)
627 { activityRec.activateStage(idx); }
629 /** Changes a stage's status to inactive within the activity recorder. */
630 void deactivateStage(const StageIdx idx)
631 { activityRec.deactivateStage(idx); }
633 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
636 virtual void wakeup(ThreadID tid) override;
638 /** Gets a free thread id. Use if thread ids change across system. */
639 ThreadID getFreeTid();
642 /** Returns a pointer to a thread context. */
646 return thread[tid]->getTC();
649 /** The global sequence number counter. */
650 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
652 /** Pointer to the checker, which can dynamically verify
653 * instruction results at run time. This can be set to NULL if it
656 Checker<Impl> *checker;
658 /** Pointer to the system. */
661 /** Pointers to all of the threads in the CPU. */
662 std::vector<Thread *> thread;
664 /** Threads Scheduled to Enter CPU */
665 std::list<int> cpuWaitList;
667 /** The cycle that the CPU was last running, used for statistics. */
668 Cycles lastRunningCycle;
670 /** The cycle that the CPU was last activated by a new thread*/
671 Tick lastActivatedCycle;
673 /** Mapping for system thread id to cpu id */
674 std::map<ThreadID, unsigned> threadMap;
676 /** Available thread ids in the cpu*/
677 std::vector<ThreadID> tids;
679 /** CPU read function, forwards read to LSQ. */
680 Fault read(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
681 uint8_t *data, int load_idx)
683 return this->iew.ldstQueue.read(req, sreqLow, sreqHigh,
687 /** CPU write function, forwards write to LSQ. */
688 Fault write(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
689 uint8_t *data, int store_idx)
691 return this->iew.ldstQueue.write(req, sreqLow, sreqHigh,
695 /** Used by the fetch unit to get a hold of the instruction port. */
696 MasterPort &getInstPort() override { return icachePort; }
698 /** Get the dcache port (used to find block size for translations). */
699 MasterPort &getDataPort() override { return dcachePort; }
701 /** Stat for total number of times the CPU is descheduled. */
702 Stats::Scalar timesIdled;
703 /** Stat for total number of cycles the CPU spends descheduled. */
704 Stats::Scalar idleCycles;
705 /** Stat for total number of cycles the CPU spends descheduled due to a
706 * quiesce operation or waiting for an interrupt. */
707 Stats::Scalar quiesceCycles;
708 /** Stat for the number of committed instructions per thread. */
709 Stats::Vector committedInsts;
710 /** Stat for the number of committed ops (including micro ops) per thread. */
711 Stats::Vector committedOps;
712 /** Stat for the CPI per thread. */
714 /** Stat for the total CPI. */
715 Stats::Formula totalCpi;
716 /** Stat for the IPC per thread. */
718 /** Stat for the total IPC. */
719 Stats::Formula totalIpc;
721 //number of integer register file accesses
722 Stats::Scalar intRegfileReads;
723 Stats::Scalar intRegfileWrites;
724 //number of float register file accesses
725 Stats::Scalar fpRegfileReads;
726 Stats::Scalar fpRegfileWrites;
727 //number of CC register file accesses
728 Stats::Scalar ccRegfileReads;
729 Stats::Scalar ccRegfileWrites;
731 Stats::Scalar miscRegfileReads;
732 Stats::Scalar miscRegfileWrites;
735 #endif // __CPU_O3_CPU_HH__