2 * Copyright (c) 2011 ARM Limited
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.
14 * Copyright (c) 2004-2005 The Regents of The University of Michigan
15 * Copyright (c) 2011 Regents of the University of California
16 * All rights reserved.
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.
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.
46 #ifndef __CPU_O3_CPU_HH__
47 #define __CPU_O3_CPU_HH__
55 #include "arch/types.hh"
56 #include "base/statistics.hh"
57 #include "config/the_isa.hh"
58 #include "config/use_checker.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. */
128 /** Per-thread status in CPU, used for SMT. */
129 Status _threadStatus[Impl::MaxThreads];
134 * IcachePort class for instruction fetch.
136 class IcachePort : public CpuPort
139 /** Pointer to fetch. */
140 DefaultFetch<Impl> *fetch;
143 /** Default constructor. */
144 IcachePort(DefaultFetch<Impl> *_fetch, FullO3CPU<Impl>* _cpu)
145 : CpuPort(_fetch->name() + "-iport", _cpu), fetch(_fetch)
150 /** Timing version of receive. Handles setting fetch to the
151 * proper status to start fetching. */
152 virtual bool recvTiming(PacketPtr pkt);
154 /** Handles doing a retry of a failed fetch. */
155 virtual void recvRetry();
159 * DcachePort class for the load/store queue.
161 class DcachePort : public CpuPort
165 /** Pointer to LSQ. */
169 /** Default constructor. */
170 DcachePort(LSQ<Impl> *_lsq, FullO3CPU<Impl>* _cpu)
171 : CpuPort(_lsq->name() + "-dport", _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 recvTiming(PacketPtr pkt);
181 /** Handles doing a retry of the previous send. */
182 virtual void recvRetry();
185 * As this CPU requires snooping to maintain the load store queue
186 * change the behaviour from the base CPU port.
188 * @return true since we have to snoop
190 virtual bool isSnooping()
194 class TickEvent : public Event
197 /** Pointer to the CPU. */
198 FullO3CPU<Impl> *cpu;
201 /** Constructs a tick event. */
202 TickEvent(FullO3CPU<Impl> *c);
204 /** Processes a tick event, calling tick() on the CPU. */
206 /** Returns the description of the tick event. */
207 const char *description() const;
210 /** The tick event used for scheduling CPU ticks. */
213 /** Schedule tick event, regardless of its current state. */
214 void scheduleTickEvent(int delay)
216 if (tickEvent.squashed())
217 reschedule(tickEvent, nextCycle(curTick() + ticks(delay)));
218 else if (!tickEvent.scheduled())
219 schedule(tickEvent, nextCycle(curTick() + ticks(delay)));
222 /** Unschedule tick event, regardless of its current state. */
223 void unscheduleTickEvent()
225 if (tickEvent.scheduled())
229 class ActivateThreadEvent : public Event
232 /** Number of Thread to Activate */
235 /** Pointer to the CPU. */
236 FullO3CPU<Impl> *cpu;
239 /** Constructs the event. */
240 ActivateThreadEvent();
242 /** Initialize Event */
243 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
245 /** Processes the event, calling activateThread() on the CPU. */
248 /** Returns the description of the event. */
249 const char *description() const;
252 /** Schedule thread to activate , regardless of its current state. */
254 scheduleActivateThreadEvent(ThreadID tid, int delay)
256 // Schedule thread to activate, regardless of its current state.
257 if (activateThreadEvent[tid].squashed())
258 reschedule(activateThreadEvent[tid],
259 nextCycle(curTick() + ticks(delay)));
260 else if (!activateThreadEvent[tid].scheduled()) {
261 Tick when = nextCycle(curTick() + ticks(delay));
263 // Check if the deallocateEvent is also scheduled, and make
264 // sure they do not happen at same time causing a sleep that
265 // is never woken from.
266 if (deallocateContextEvent[tid].scheduled() &&
267 deallocateContextEvent[tid].when() == when) {
271 schedule(activateThreadEvent[tid], when);
275 /** Unschedule actiavte thread event, regardless of its current state. */
277 unscheduleActivateThreadEvent(ThreadID tid)
279 if (activateThreadEvent[tid].scheduled())
280 activateThreadEvent[tid].squash();
283 /** The tick event used for scheduling CPU ticks. */
284 ActivateThreadEvent activateThreadEvent[Impl::MaxThreads];
286 class DeallocateContextEvent : public Event
289 /** Number of Thread to deactivate */
292 /** Should the thread be removed from the CPU? */
295 /** Pointer to the CPU. */
296 FullO3CPU<Impl> *cpu;
299 /** Constructs the event. */
300 DeallocateContextEvent();
302 /** Initialize Event */
303 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
305 /** Processes the event, calling activateThread() on the CPU. */
308 /** Sets whether the thread should also be removed from the CPU. */
309 void setRemove(bool _remove) { remove = _remove; }
311 /** Returns the description of the event. */
312 const char *description() const;
315 /** Schedule cpu to deallocate thread context.*/
317 scheduleDeallocateContextEvent(ThreadID tid, bool remove, int delay)
319 // Schedule thread to activate, regardless of its current state.
320 if (deallocateContextEvent[tid].squashed())
321 reschedule(deallocateContextEvent[tid],
322 nextCycle(curTick() + ticks(delay)));
323 else if (!deallocateContextEvent[tid].scheduled())
324 schedule(deallocateContextEvent[tid],
325 nextCycle(curTick() + ticks(delay)));
328 /** Unschedule thread deallocation in CPU */
330 unscheduleDeallocateContextEvent(ThreadID tid)
332 if (deallocateContextEvent[tid].scheduled())
333 deallocateContextEvent[tid].squash();
336 /** The tick event used for scheduling CPU ticks. */
337 DeallocateContextEvent deallocateContextEvent[Impl::MaxThreads];
340 /** Constructs a CPU with the given parameters. */
341 FullO3CPU(DerivO3CPUParams *params);
345 /** Registers statistics. */
348 void demapPage(Addr vaddr, uint64_t asn)
350 this->itb->demapPage(vaddr, asn);
351 this->dtb->demapPage(vaddr, asn);
354 void demapInstPage(Addr vaddr, uint64_t asn)
356 this->itb->demapPage(vaddr, asn);
359 void demapDataPage(Addr vaddr, uint64_t asn)
361 this->dtb->demapPage(vaddr, asn);
364 /** Returns a specific port. */
365 Port *getPort(const std::string &if_name, int idx);
367 /** Ticks CPU, calling tick() on each stage, and checking the overall
368 * activity to see if the CPU should deschedule itself.
372 /** Initialize the CPU */
375 /** Returns the Number of Active Threads in the CPU */
376 int numActiveThreads()
377 { return activeThreads.size(); }
379 /** Add Thread to Active Threads List */
380 void activateThread(ThreadID tid);
382 /** Remove Thread from Active Threads List */
383 void deactivateThread(ThreadID tid);
385 /** Setup CPU to insert a thread's context */
386 void insertThread(ThreadID tid);
388 /** Remove all of a thread's context from CPU */
389 void removeThread(ThreadID tid);
391 /** Count the Total Instructions Committed in the CPU. */
392 virtual Counter totalInstructions() const;
394 /** Add Thread to Active Threads List. */
395 void activateContext(ThreadID tid, int delay);
397 /** Remove Thread from Active Threads List */
398 void suspendContext(ThreadID tid);
400 /** Remove Thread from Active Threads List &&
401 * Possibly Remove Thread Context from CPU.
403 bool scheduleDeallocateContext(ThreadID tid, bool remove, int delay = 1);
405 /** Remove Thread from Active Threads List &&
406 * Remove Thread Context from CPU.
408 void haltContext(ThreadID tid);
410 /** Activate a Thread When CPU Resources are Available. */
411 void activateWhenReady(ThreadID tid);
413 /** Add or Remove a Thread Context in the CPU. */
414 void doContextSwitch();
416 /** Update The Order In Which We Process Threads. */
417 void updateThreadPriority();
419 /** Serialize state. */
420 virtual void serialize(std::ostream &os);
422 /** Unserialize from a checkpoint. */
423 virtual void unserialize(Checkpoint *cp, const std::string §ion);
426 /** Executes a syscall.
427 * @todo: Determine if this needs to be virtual.
429 void syscall(int64_t callnum, ThreadID tid);
431 /** Starts draining the CPU's pipeline of all instructions in
432 * order to stop all memory accesses. */
433 virtual unsigned int drain(Event *drain_event);
435 /** Resumes execution after a drain. */
436 virtual void resume();
438 /** Signals to this CPU that a stage has completed switching out. */
439 void signalDrained();
441 /** Switches out this CPU. */
442 virtual void switchOut();
444 /** Takes over from another CPU. */
445 virtual void takeOverFrom(BaseCPU *oldCPU);
447 /** Get the current instruction sequence number, and increment it. */
448 InstSeqNum getAndIncrementInstSeq()
449 { return globalSeqNum++; }
451 /** Traps to handle given fault. */
452 void trap(Fault fault, ThreadID tid, StaticInstPtr inst);
454 /** HW return from error interrupt. */
455 Fault hwrei(ThreadID tid);
457 bool simPalCheck(int palFunc, ThreadID tid);
459 /** Returns the Fault for any valid interrupt. */
460 Fault getInterrupts();
462 /** Processes any an interrupt fault. */
463 void processInterrupts(Fault interrupt);
465 /** Halts the CPU. */
466 void halt() { panic("Halt not implemented!\n"); }
468 /** Check if this address is a valid instruction address. */
469 bool validInstAddr(Addr addr) { return true; }
471 /** Check if this address is a valid data address. */
472 bool validDataAddr(Addr addr) { return true; }
474 /** Register accessors. Index refers to the physical register index. */
476 /** Reads a miscellaneous register. */
477 TheISA::MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid);
479 /** Reads a misc. register, including any side effects the read
480 * might have as defined by the architecture.
482 TheISA::MiscReg readMiscReg(int misc_reg, ThreadID tid);
484 /** Sets a miscellaneous register. */
485 void setMiscRegNoEffect(int misc_reg, const TheISA::MiscReg &val,
488 /** Sets a misc. register, including any side effects the write
489 * might have as defined by the architecture.
491 void setMiscReg(int misc_reg, const TheISA::MiscReg &val,
494 uint64_t readIntReg(int reg_idx);
496 TheISA::FloatReg readFloatReg(int reg_idx);
498 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
500 void setIntReg(int reg_idx, uint64_t val);
502 void setFloatReg(int reg_idx, TheISA::FloatReg val);
504 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
506 uint64_t readArchIntReg(int reg_idx, ThreadID tid);
508 float readArchFloatReg(int reg_idx, ThreadID tid);
510 uint64_t readArchFloatRegInt(int reg_idx, ThreadID tid);
512 /** Architectural register accessors. Looks up in the commit
513 * rename table to obtain the true physical index of the
514 * architected register first, then accesses that physical
517 void setArchIntReg(int reg_idx, uint64_t val, ThreadID tid);
519 void setArchFloatReg(int reg_idx, float val, ThreadID tid);
521 void setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid);
523 /** Sets the commit PC state of a specific thread. */
524 void pcState(const TheISA::PCState &newPCState, ThreadID tid);
526 /** Reads the commit PC state of a specific thread. */
527 TheISA::PCState pcState(ThreadID tid);
529 /** Reads the commit PC of a specific thread. */
530 Addr instAddr(ThreadID tid);
532 /** Reads the commit micro PC of a specific thread. */
533 MicroPC microPC(ThreadID tid);
535 /** Reads the next PC of a specific thread. */
536 Addr nextInstAddr(ThreadID tid);
538 /** Initiates a squash of all in-flight instructions for a given
539 * thread. The source of the squash is an external update of
540 * state through the TC.
542 void squashFromTC(ThreadID tid);
544 /** Function to add instruction onto the head of the list of the
545 * instructions. Used when new instructions are fetched.
547 ListIt addInst(DynInstPtr &inst);
549 /** Function to tell the CPU that an instruction has completed. */
550 void instDone(ThreadID tid);
552 /** Remove an instruction from the front end of the list. There's
553 * no restriction on location of the instruction.
555 void removeFrontInst(DynInstPtr &inst);
557 /** Remove all instructions that are not currently in the ROB.
558 * There's also an option to not squash delay slot instructions.*/
559 void removeInstsNotInROB(ThreadID tid);
561 /** Remove all instructions younger than the given sequence number. */
562 void removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid);
564 /** Removes the instruction pointed to by the iterator. */
565 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
567 /** Cleans up all instructions on the remove list. */
568 void cleanUpRemovedInsts();
570 /** Debug function to print all instructions on the list. */
575 /** Count of total number of dynamic instructions in flight. */
579 /** List of all the instructions in flight. */
580 std::list<DynInstPtr> instList;
582 /** List of all the instructions that will be removed at the end of this
585 std::queue<ListIt> removeList;
588 /** Debug structure to keep track of the sequence numbers still in
591 std::set<InstSeqNum> snList;
594 /** Records if instructions need to be removed this cycle due to
595 * being retired or squashed.
597 bool removeInstsThisCycle;
600 /** The fetch stage. */
601 typename CPUPolicy::Fetch fetch;
603 /** The decode stage. */
604 typename CPUPolicy::Decode decode;
606 /** The dispatch stage. */
607 typename CPUPolicy::Rename rename;
609 /** The issue/execute/writeback stages. */
610 typename CPUPolicy::IEW iew;
612 /** The commit stage. */
613 typename CPUPolicy::Commit commit;
615 /** The register file. */
616 typename CPUPolicy::RegFile regFile;
618 /** The free list. */
619 typename CPUPolicy::FreeList freeList;
621 /** The rename map. */
622 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
624 /** The commit rename map. */
625 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
627 /** The re-order buffer. */
628 typename CPUPolicy::ROB rob;
630 /** Active Threads List */
631 std::list<ThreadID> activeThreads;
633 /** Integer Register Scoreboard */
634 Scoreboard scoreboard;
636 TheISA::ISA isa[Impl::MaxThreads];
638 /** Instruction port. Note that it has to appear after the fetch stage. */
639 IcachePort icachePort;
641 /** Data port. Note that it has to appear after the iew stages */
642 DcachePort dcachePort;
645 /** Enum to give each stage a specific index, so when calling
646 * activateStage() or deactivateStage(), they can specify which stage
647 * is being activated/deactivated.
657 /** Typedefs from the Impl to get the structs that each of the
658 * time buffers should use.
660 typedef typename CPUPolicy::TimeStruct TimeStruct;
662 typedef typename CPUPolicy::FetchStruct FetchStruct;
664 typedef typename CPUPolicy::DecodeStruct DecodeStruct;
666 typedef typename CPUPolicy::RenameStruct RenameStruct;
668 typedef typename CPUPolicy::IEWStruct IEWStruct;
670 /** The main time buffer to do backwards communication. */
671 TimeBuffer<TimeStruct> timeBuffer;
673 /** The fetch stage's instruction queue. */
674 TimeBuffer<FetchStruct> fetchQueue;
676 /** The decode stage's instruction queue. */
677 TimeBuffer<DecodeStruct> decodeQueue;
679 /** The rename stage's instruction queue. */
680 TimeBuffer<RenameStruct> renameQueue;
682 /** The IEW stage's instruction queue. */
683 TimeBuffer<IEWStruct> iewQueue;
686 /** The activity recorder; used to tell if the CPU has any
687 * activity remaining or if it can go to idle and deschedule
690 ActivityRecorder activityRec;
693 /** Records that there was time buffer activity this cycle. */
694 void activityThisCycle() { activityRec.activity(); }
696 /** Changes a stage's status to active within the activity recorder. */
697 void activateStage(const StageIdx idx)
698 { activityRec.activateStage(idx); }
700 /** Changes a stage's status to inactive within the activity recorder. */
701 void deactivateStage(const StageIdx idx)
702 { activityRec.deactivateStage(idx); }
704 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
707 virtual void wakeup();
709 /** Gets a free thread id. Use if thread ids change across system. */
710 ThreadID getFreeTid();
713 /** Returns a pointer to a thread context. */
717 return thread[tid]->getTC();
720 /** The global sequence number counter. */
721 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
724 /** Pointer to the checker, which can dynamically verify
725 * instruction results at run time. This can be set to NULL if it
728 Checker<Impl> *checker;
731 /** Pointer to the system. */
734 /** Event to call process() on once draining has completed. */
737 /** Counter of how many stages have completed draining. */
740 /** Pointers to all of the threads in the CPU. */
741 std::vector<Thread *> thread;
743 /** Whether or not the CPU should defer its registration. */
744 bool deferRegistration;
746 /** Is there a context switch pending? */
749 /** Threads Scheduled to Enter CPU */
750 std::list<int> cpuWaitList;
752 /** The cycle that the CPU was last running, used for statistics. */
753 Tick lastRunningCycle;
755 /** The cycle that the CPU was last activated by a new thread*/
756 Tick lastActivatedCycle;
758 /** Mapping for system thread id to cpu id */
759 std::map<ThreadID, unsigned> threadMap;
761 /** Available thread ids in the cpu*/
762 std::vector<ThreadID> tids;
764 /** CPU read function, forwards read to LSQ. */
765 Fault read(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
766 uint8_t *data, int load_idx)
768 return this->iew.ldstQueue.read(req, sreqLow, sreqHigh,
772 /** CPU write function, forwards write to LSQ. */
773 Fault write(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
774 uint8_t *data, int store_idx)
776 return this->iew.ldstQueue.write(req, sreqLow, sreqHigh,
780 /** Used by the fetch unit to get a hold of the instruction port. */
781 Port* getIcachePort() { return &icachePort; }
783 /** Get the dcache port (used to find block size for translations). */
784 Port* getDcachePort() { return &dcachePort; }
788 /** Temporary fix for the lock flag, works in the UP case. */
791 /** Stat for total number of times the CPU is descheduled. */
792 Stats::Scalar timesIdled;
793 /** Stat for total number of cycles the CPU spends descheduled. */
794 Stats::Scalar idleCycles;
795 /** Stat for total number of cycles the CPU spends descheduled due to a
796 * quiesce operation or waiting for an interrupt. */
797 Stats::Scalar quiesceCycles;
798 /** Stat for the number of committed instructions per thread. */
799 Stats::Vector committedInsts;
800 /** Stat for the total number of committed instructions. */
801 Stats::Scalar totalCommittedInsts;
802 /** Stat for the CPI per thread. */
804 /** Stat for the total CPI. */
805 Stats::Formula totalCpi;
806 /** Stat for the IPC per thread. */
808 /** Stat for the total IPC. */
809 Stats::Formula totalIpc;
811 //number of integer register file accesses
812 Stats::Scalar intRegfileReads;
813 Stats::Scalar intRegfileWrites;
814 //number of float register file accesses
815 Stats::Scalar fpRegfileReads;
816 Stats::Scalar fpRegfileWrites;
818 Stats::Scalar miscRegfileReads;
819 Stats::Scalar miscRegfileWrites;
822 #endif // __CPU_O3_CPU_HH__