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);
151 /** Handles doing a retry of a failed fetch. */
152 virtual void recvReqRetry();
156 * DcachePort class for the load/store queue.
158 class DcachePort : public MasterPort
162 /** Pointer to LSQ. */
164 FullO3CPU<Impl> *cpu;
167 /** Default constructor. */
168 DcachePort(LSQ<Impl> *_lsq, FullO3CPU<Impl>* _cpu)
169 : MasterPort(_cpu->name() + ".dcache_port", _cpu), lsq(_lsq),
175 /** Timing version of receive. Handles writing back and
176 * completing the load or store that has returned from
178 virtual bool recvTimingResp(PacketPtr pkt);
179 virtual void recvTimingSnoopReq(PacketPtr pkt);
181 virtual void recvFunctionalSnoop(PacketPtr pkt)
183 // @todo: Is there a need for potential invalidation here?
186 /** Handles doing a retry of the previous send. */
187 virtual void recvReqRetry();
190 * As this CPU requires snooping to maintain the load store queue
191 * change the behaviour from the base CPU port.
193 * @return true since we have to snoop
195 virtual bool isSnooping() const { return true; }
198 class TickEvent : public Event
201 /** Pointer to the CPU. */
202 FullO3CPU<Impl> *cpu;
205 /** Constructs a tick event. */
206 TickEvent(FullO3CPU<Impl> *c);
208 /** Processes a tick event, calling tick() on the CPU. */
210 /** Returns the description of the tick event. */
211 const char *description() const;
214 /** The tick event used for scheduling CPU ticks. */
217 /** Schedule tick event, regardless of its current state. */
218 void scheduleTickEvent(Cycles delay)
220 if (tickEvent.squashed())
221 reschedule(tickEvent, clockEdge(delay));
222 else if (!tickEvent.scheduled())
223 schedule(tickEvent, clockEdge(delay));
226 /** Unschedule tick event, regardless of its current state. */
227 void unscheduleTickEvent()
229 if (tickEvent.scheduled())
234 * Check if the pipeline has drained and signal drain done.
236 * This method checks if a drain has been requested and if the CPU
237 * has drained successfully (i.e., there are no instructions in
238 * the pipeline). If the CPU has drained, it deschedules the tick
239 * event and signals the drain manager.
241 * @return False if a drain hasn't been requested or the CPU
242 * hasn't drained, true otherwise.
247 * Perform sanity checks after a drain.
249 * This method is called from drain() when it has determined that
250 * the CPU is fully drained when gem5 is compiled with the NDEBUG
251 * macro undefined. The intention of this method is to do more
252 * extensive tests than the isDrained() method to weed out any
255 void drainSanityCheck() const;
257 /** Check if a system is in a drained state. */
258 bool isDrained() const;
261 /** Constructs a CPU with the given parameters. */
262 FullO3CPU(DerivO3CPUParams *params);
266 /** Registers statistics. */
267 void regStats() override;
269 ProbePointArg<PacketPtr> *ppInstAccessComplete;
270 ProbePointArg<std::pair<DynInstPtr, PacketPtr> > *ppDataAccessComplete;
272 /** Register probe points. */
273 void regProbePoints() override;
275 void demapPage(Addr vaddr, uint64_t asn)
277 this->itb->demapPage(vaddr, asn);
278 this->dtb->demapPage(vaddr, asn);
281 void demapInstPage(Addr vaddr, uint64_t asn)
283 this->itb->demapPage(vaddr, asn);
286 void demapDataPage(Addr vaddr, uint64_t asn)
288 this->dtb->demapPage(vaddr, asn);
291 /** Ticks CPU, calling tick() on each stage, and checking the overall
292 * activity to see if the CPU should deschedule itself.
296 /** Initialize the CPU */
297 void init() override;
299 void startup() override;
301 /** Returns the Number of Active Threads in the CPU */
302 int numActiveThreads()
303 { return activeThreads.size(); }
305 /** Add Thread to Active Threads List */
306 void activateThread(ThreadID tid);
308 /** Remove Thread from Active Threads List */
309 void deactivateThread(ThreadID tid);
311 /** Setup CPU to insert a thread's context */
312 void insertThread(ThreadID tid);
314 /** Remove all of a thread's context from CPU */
315 void removeThread(ThreadID tid);
317 /** Count the Total Instructions Committed in the CPU. */
318 Counter totalInsts() const override;
320 /** Count the Total Ops (including micro ops) committed in the CPU. */
321 Counter totalOps() const override;
323 /** Add Thread to Active Threads List. */
324 void activateContext(ThreadID tid) override;
326 /** Remove Thread from Active Threads List */
327 void suspendContext(ThreadID tid) override;
329 /** Remove Thread from Active Threads List &&
330 * Remove Thread Context from CPU.
332 void haltContext(ThreadID tid) override;
334 /** Update The Order In Which We Process Threads. */
335 void updateThreadPriority();
337 /** Is the CPU draining? */
338 bool isDraining() const { return drainState() == DrainState::Draining; }
340 void serializeThread(CheckpointOut &cp, ThreadID tid) const override;
341 void unserializeThread(CheckpointIn &cp, ThreadID tid) override;
344 /** Executes a syscall.
345 * @todo: Determine if this needs to be virtual.
347 void syscall(int64_t callnum, ThreadID tid);
349 /** Starts draining the CPU's pipeline of all instructions in
350 * order to stop all memory accesses. */
351 DrainState drain() override;
353 /** Resumes execution after a drain. */
354 void drainResume() override;
357 * Commit has reached a safe point to drain a thread.
359 * Commit calls this method to inform the pipeline that it has
360 * reached a point where it is not executed microcode and is about
361 * to squash uncommitted instructions to fully drain the pipeline.
363 void commitDrained(ThreadID tid);
365 /** Switches out this CPU. */
366 void switchOut() override;
368 /** Takes over from another CPU. */
369 void takeOverFrom(BaseCPU *oldCPU) override;
371 void verifyMemoryMode() const override;
373 /** Get the current instruction sequence number, and increment it. */
374 InstSeqNum getAndIncrementInstSeq()
375 { return globalSeqNum++; }
377 /** Traps to handle given fault. */
378 void trap(const Fault &fault, ThreadID tid, const StaticInstPtr &inst);
380 /** HW return from error interrupt. */
381 Fault hwrei(ThreadID tid);
383 bool simPalCheck(int palFunc, ThreadID tid);
385 /** Returns the Fault for any valid interrupt. */
386 Fault getInterrupts();
388 /** Processes any an interrupt fault. */
389 void processInterrupts(const Fault &interrupt);
391 /** Halts the CPU. */
392 void halt() { panic("Halt not implemented!\n"); }
394 /** Register accessors. Index refers to the physical register index. */
396 /** Reads a miscellaneous register. */
397 TheISA::MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid) const;
399 /** Reads a misc. register, including any side effects the read
400 * might have as defined by the architecture.
402 TheISA::MiscReg readMiscReg(int misc_reg, ThreadID tid);
404 /** Sets a miscellaneous register. */
405 void setMiscRegNoEffect(int misc_reg, const TheISA::MiscReg &val,
408 /** Sets a misc. register, including any side effects the write
409 * might have as defined by the architecture.
411 void setMiscReg(int misc_reg, const TheISA::MiscReg &val,
414 uint64_t readIntReg(int reg_idx);
416 TheISA::FloatReg readFloatReg(int reg_idx);
418 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
420 TheISA::CCReg readCCReg(int reg_idx);
422 void setIntReg(int reg_idx, uint64_t val);
424 void setFloatReg(int reg_idx, TheISA::FloatReg val);
426 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
428 void setCCReg(int reg_idx, TheISA::CCReg val);
430 uint64_t readArchIntReg(int reg_idx, ThreadID tid);
432 float readArchFloatReg(int reg_idx, ThreadID tid);
434 uint64_t readArchFloatRegInt(int reg_idx, ThreadID tid);
436 TheISA::CCReg readArchCCReg(int reg_idx, ThreadID tid);
438 /** Architectural register accessors. Looks up in the commit
439 * rename table to obtain the true physical index of the
440 * architected register first, then accesses that physical
443 void setArchIntReg(int reg_idx, uint64_t val, ThreadID tid);
445 void setArchFloatReg(int reg_idx, float val, ThreadID tid);
447 void setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid);
449 void setArchCCReg(int reg_idx, TheISA::CCReg val, ThreadID tid);
451 /** Sets the commit PC state of a specific thread. */
452 void pcState(const TheISA::PCState &newPCState, ThreadID tid);
454 /** Reads the commit PC state of a specific thread. */
455 TheISA::PCState pcState(ThreadID tid);
457 /** Reads the commit PC of a specific thread. */
458 Addr instAddr(ThreadID tid);
460 /** Reads the commit micro PC of a specific thread. */
461 MicroPC microPC(ThreadID tid);
463 /** Reads the next PC of a specific thread. */
464 Addr nextInstAddr(ThreadID tid);
466 /** Initiates a squash of all in-flight instructions for a given
467 * thread. The source of the squash is an external update of
468 * state through the TC.
470 void squashFromTC(ThreadID tid);
472 /** Function to add instruction onto the head of the list of the
473 * instructions. Used when new instructions are fetched.
475 ListIt addInst(DynInstPtr &inst);
477 /** Function to tell the CPU that an instruction has completed. */
478 void instDone(ThreadID tid, DynInstPtr &inst);
480 /** Remove an instruction from the front end of the list. There's
481 * no restriction on location of the instruction.
483 void removeFrontInst(DynInstPtr &inst);
485 /** Remove all instructions that are not currently in the ROB.
486 * There's also an option to not squash delay slot instructions.*/
487 void removeInstsNotInROB(ThreadID tid);
489 /** Remove all instructions younger than the given sequence number. */
490 void removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid);
492 /** Removes the instruction pointed to by the iterator. */
493 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
495 /** Cleans up all instructions on the remove list. */
496 void cleanUpRemovedInsts();
498 /** Debug function to print all instructions on the list. */
503 /** Count of total number of dynamic instructions in flight. */
507 /** List of all the instructions in flight. */
508 std::list<DynInstPtr> instList;
510 /** List of all the instructions that will be removed at the end of this
513 std::queue<ListIt> removeList;
516 /** Debug structure to keep track of the sequence numbers still in
519 std::set<InstSeqNum> snList;
522 /** Records if instructions need to be removed this cycle due to
523 * being retired or squashed.
525 bool removeInstsThisCycle;
528 /** The fetch stage. */
529 typename CPUPolicy::Fetch fetch;
531 /** The decode stage. */
532 typename CPUPolicy::Decode decode;
534 /** The dispatch stage. */
535 typename CPUPolicy::Rename rename;
537 /** The issue/execute/writeback stages. */
538 typename CPUPolicy::IEW iew;
540 /** The commit stage. */
541 typename CPUPolicy::Commit commit;
543 /** The register file. */
546 /** The free list. */
547 typename CPUPolicy::FreeList freeList;
549 /** The rename map. */
550 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
552 /** The commit rename map. */
553 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
555 /** The re-order buffer. */
556 typename CPUPolicy::ROB rob;
558 /** Active Threads List */
559 std::list<ThreadID> activeThreads;
561 /** Integer Register Scoreboard */
562 Scoreboard scoreboard;
564 std::vector<TheISA::ISA *> isa;
566 /** Instruction port. Note that it has to appear after the fetch stage. */
567 IcachePort icachePort;
569 /** Data port. Note that it has to appear after the iew stages */
570 DcachePort dcachePort;
573 /** Enum to give each stage a specific index, so when calling
574 * activateStage() or deactivateStage(), they can specify which stage
575 * is being activated/deactivated.
585 /** Typedefs from the Impl to get the structs that each of the
586 * time buffers should use.
588 typedef typename CPUPolicy::TimeStruct TimeStruct;
590 typedef typename CPUPolicy::FetchStruct FetchStruct;
592 typedef typename CPUPolicy::DecodeStruct DecodeStruct;
594 typedef typename CPUPolicy::RenameStruct RenameStruct;
596 typedef typename CPUPolicy::IEWStruct IEWStruct;
598 /** The main time buffer to do backwards communication. */
599 TimeBuffer<TimeStruct> timeBuffer;
601 /** The fetch stage's instruction queue. */
602 TimeBuffer<FetchStruct> fetchQueue;
604 /** The decode stage's instruction queue. */
605 TimeBuffer<DecodeStruct> decodeQueue;
607 /** The rename stage's instruction queue. */
608 TimeBuffer<RenameStruct> renameQueue;
610 /** The IEW stage's instruction queue. */
611 TimeBuffer<IEWStruct> iewQueue;
614 /** The activity recorder; used to tell if the CPU has any
615 * activity remaining or if it can go to idle and deschedule
618 ActivityRecorder activityRec;
621 /** Records that there was time buffer activity this cycle. */
622 void activityThisCycle() { activityRec.activity(); }
624 /** Changes a stage's status to active within the activity recorder. */
625 void activateStage(const StageIdx idx)
626 { activityRec.activateStage(idx); }
628 /** Changes a stage's status to inactive within the activity recorder. */
629 void deactivateStage(const StageIdx idx)
630 { activityRec.deactivateStage(idx); }
632 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
635 virtual void wakeup(ThreadID tid) override;
637 /** Gets a free thread id. Use if thread ids change across system. */
638 ThreadID getFreeTid();
641 /** Returns a pointer to a thread context. */
645 return thread[tid]->getTC();
648 /** The global sequence number counter. */
649 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
651 /** Pointer to the checker, which can dynamically verify
652 * instruction results at run time. This can be set to NULL if it
655 Checker<Impl> *checker;
657 /** Pointer to the system. */
660 /** Pointers to all of the threads in the CPU. */
661 std::vector<Thread *> thread;
663 /** Threads Scheduled to Enter CPU */
664 std::list<int> cpuWaitList;
666 /** The cycle that the CPU was last running, used for statistics. */
667 Cycles lastRunningCycle;
669 /** The cycle that the CPU was last activated by a new thread*/
670 Tick lastActivatedCycle;
672 /** Mapping for system thread id to cpu id */
673 std::map<ThreadID, unsigned> threadMap;
675 /** Available thread ids in the cpu*/
676 std::vector<ThreadID> tids;
678 /** CPU read function, forwards read to LSQ. */
679 Fault read(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
682 return this->iew.ldstQueue.read(req, sreqLow, sreqHigh, load_idx);
685 /** CPU write function, forwards write to LSQ. */
686 Fault write(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
687 uint8_t *data, int store_idx)
689 return this->iew.ldstQueue.write(req, sreqLow, sreqHigh,
693 /** Used by the fetch unit to get a hold of the instruction port. */
694 MasterPort &getInstPort() override { return icachePort; }
696 /** Get the dcache port (used to find block size for translations). */
697 MasterPort &getDataPort() override { return dcachePort; }
699 /** Stat for total number of times the CPU is descheduled. */
700 Stats::Scalar timesIdled;
701 /** Stat for total number of cycles the CPU spends descheduled. */
702 Stats::Scalar idleCycles;
703 /** Stat for total number of cycles the CPU spends descheduled due to a
704 * quiesce operation or waiting for an interrupt. */
705 Stats::Scalar quiesceCycles;
706 /** Stat for the number of committed instructions per thread. */
707 Stats::Vector committedInsts;
708 /** Stat for the number of committed ops (including micro ops) per thread. */
709 Stats::Vector committedOps;
710 /** Stat for the CPI per thread. */
712 /** Stat for the total CPI. */
713 Stats::Formula totalCpi;
714 /** Stat for the IPC per thread. */
716 /** Stat for the total IPC. */
717 Stats::Formula totalIpc;
719 //number of integer register file accesses
720 Stats::Scalar intRegfileReads;
721 Stats::Scalar intRegfileWrites;
722 //number of float register file accesses
723 Stats::Scalar fpRegfileReads;
724 Stats::Scalar fpRegfileWrites;
725 //number of CC register file accesses
726 Stats::Scalar ccRegfileReads;
727 Stats::Scalar ccRegfileWrites;
729 Stats::Scalar miscRegfileReads;
730 Stats::Scalar miscRegfileWrites;
733 #endif // __CPU_O3_CPU_HH__