2 * Copyright (c) 2004-2005 The Regents of The University of Michigan
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #ifndef __CPU_O3_CPU_HH__
33 #define __CPU_O3_CPU_HH__
41 #include "arch/types.hh"
42 #include "base/statistics.hh"
43 #include "base/timebuf.hh"
44 #include "config/full_system.hh"
45 #include "config/use_checker.hh"
46 #include "cpu/activity.hh"
47 #include "cpu/base.hh"
48 #include "cpu/simple_thread.hh"
49 #include "cpu/o3/comm.hh"
50 #include "cpu/o3/cpu_policy.hh"
51 #include "cpu/o3/scoreboard.hh"
52 #include "cpu/o3/thread_state.hh"
53 //#include "cpu/o3/thread_context.hh"
54 #include "sim/process.hh"
56 #include "params/DerivO3CPU.hh"
62 class O3ThreadContext;
70 class BaseO3CPU : public BaseCPU
72 //Stuff that's pretty ISA independent will go here.
74 BaseO3CPU(BaseCPUParams *params);
78 /** Sets this CPU's ID. */
79 void setCpuId(int id) { cpu_id = id; }
81 /** Reads this CPU's ID. */
82 int readCpuId() { return cpu_id; }
89 * FullO3CPU class, has each of the stages (fetch through commit)
90 * within it, as well as all of the time buffers between stages. The
91 * tick() function for the CPU is defined here.
94 class FullO3CPU : public BaseO3CPU
97 // Typedefs from the Impl here.
98 typedef typename Impl::CPUPol CPUPolicy;
99 typedef typename Impl::DynInstPtr DynInstPtr;
100 typedef typename Impl::O3CPU O3CPU;
102 typedef O3ThreadState<Impl> ImplState;
103 typedef O3ThreadState<Impl> Thread;
105 typedef typename std::list<DynInstPtr>::iterator ListIt;
107 friend class O3ThreadContext<Impl>;
121 /** Overall CPU status. */
124 /** Per-thread status in CPU, used for SMT. */
125 Status _threadStatus[Impl::MaxThreads];
128 class TickEvent : public Event
131 /** Pointer to the CPU. */
132 FullO3CPU<Impl> *cpu;
135 /** Constructs a tick event. */
136 TickEvent(FullO3CPU<Impl> *c);
138 /** Processes a tick event, calling tick() on the CPU. */
140 /** Returns the description of the tick event. */
141 const char *description() const;
144 /** The tick event used for scheduling CPU ticks. */
147 /** Schedule tick event, regardless of its current state. */
148 void scheduleTickEvent(int delay)
150 if (tickEvent.squashed())
151 reschedule(tickEvent, nextCycle(curTick + ticks(delay)));
152 else if (!tickEvent.scheduled())
153 schedule(tickEvent, nextCycle(curTick + ticks(delay)));
156 /** Unschedule tick event, regardless of its current state. */
157 void unscheduleTickEvent()
159 if (tickEvent.scheduled())
163 class ActivateThreadEvent : public Event
166 /** Number of Thread to Activate */
169 /** Pointer to the CPU. */
170 FullO3CPU<Impl> *cpu;
173 /** Constructs the event. */
174 ActivateThreadEvent();
176 /** Initialize Event */
177 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
179 /** Processes the event, calling activateThread() on the CPU. */
182 /** Returns the description of the event. */
183 const char *description() const;
186 /** Schedule thread to activate , regardless of its current state. */
187 void scheduleActivateThreadEvent(int tid, int delay)
189 // Schedule thread to activate, regardless of its current state.
190 if (activateThreadEvent[tid].squashed())
191 reschedule(activateThreadEvent[tid],
192 nextCycle(curTick + ticks(delay)));
193 else if (!activateThreadEvent[tid].scheduled())
194 schedule(activateThreadEvent[tid],
195 nextCycle(curTick + ticks(delay)));
198 /** Unschedule actiavte thread event, regardless of its current state. */
199 void unscheduleActivateThreadEvent(int tid)
201 if (activateThreadEvent[tid].scheduled())
202 activateThreadEvent[tid].squash();
206 TheISA::IntReg getSyscallArg(int i, int tid);
208 /** Used to shift args for indirect syscall. */
209 void setSyscallArg(int i, TheISA::IntReg val, int tid);
212 /** The tick event used for scheduling CPU ticks. */
213 ActivateThreadEvent activateThreadEvent[Impl::MaxThreads];
215 class DeallocateContextEvent : public Event
218 /** Number of Thread to deactivate */
221 /** Should the thread be removed from the CPU? */
224 /** Pointer to the CPU. */
225 FullO3CPU<Impl> *cpu;
228 /** Constructs the event. */
229 DeallocateContextEvent();
231 /** Initialize Event */
232 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
234 /** Processes the event, calling activateThread() on the CPU. */
237 /** Sets whether the thread should also be removed from the CPU. */
238 void setRemove(bool _remove) { remove = _remove; }
240 /** Returns the description of the event. */
241 const char *description() const;
244 /** Schedule cpu to deallocate thread context.*/
245 void scheduleDeallocateContextEvent(int tid, bool remove, int delay)
247 // Schedule thread to activate, regardless of its current state.
248 if (deallocateContextEvent[tid].squashed())
249 reschedule(deallocateContextEvent[tid],
250 nextCycle(curTick + ticks(delay)));
251 else if (!deallocateContextEvent[tid].scheduled())
252 schedule(deallocateContextEvent[tid],
253 nextCycle(curTick + ticks(delay)));
256 /** Unschedule thread deallocation in CPU */
257 void unscheduleDeallocateContextEvent(int tid)
259 if (deallocateContextEvent[tid].scheduled())
260 deallocateContextEvent[tid].squash();
263 /** The tick event used for scheduling CPU ticks. */
264 DeallocateContextEvent deallocateContextEvent[Impl::MaxThreads];
267 /** Constructs a CPU with the given parameters. */
268 FullO3CPU(DerivO3CPUParams *params);
272 /** Registers statistics. */
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 /** Translates instruction requestion. */
292 Fault translateInstReq(RequestPtr &req, Thread *thread)
294 return this->itb->translate(req, thread->getTC());
297 /** Translates data read request. */
298 Fault translateDataReadReq(RequestPtr &req, Thread *thread)
300 return this->dtb->translate(req, thread->getTC(), false);
303 /** Translates data write request. */
304 Fault translateDataWriteReq(RequestPtr &req, Thread *thread)
306 return this->dtb->translate(req, thread->getTC(), true);
309 /** Returns a specific port. */
310 Port *getPort(const std::string &if_name, int idx);
312 /** Ticks CPU, calling tick() on each stage, and checking the overall
313 * activity to see if the CPU should deschedule itself.
317 /** Initialize the CPU */
320 /** Returns the Number of Active Threads in the CPU */
321 int numActiveThreads()
322 { return activeThreads.size(); }
324 /** Add Thread to Active Threads List */
325 void activateThread(unsigned tid);
327 /** Remove Thread from Active Threads List */
328 void deactivateThread(unsigned tid);
330 /** Setup CPU to insert a thread's context */
331 void insertThread(unsigned tid);
333 /** Remove all of a thread's context from CPU */
334 void removeThread(unsigned tid);
336 /** Count the Total Instructions Committed in the CPU. */
337 virtual Counter totalInstructions() const
341 for (int i=0; i < thread.size(); i++)
342 total += thread[i]->numInst;
347 /** Add Thread to Active Threads List. */
348 void activateContext(int tid, int delay);
350 /** Remove Thread from Active Threads List */
351 void suspendContext(int tid);
353 /** Remove Thread from Active Threads List &&
354 * Possibly Remove Thread Context from CPU.
356 bool deallocateContext(int tid, bool remove, int delay = 1);
358 /** Remove Thread from Active Threads List &&
359 * Remove Thread Context from CPU.
361 void haltContext(int tid);
363 /** Activate a Thread When CPU Resources are Available. */
364 void activateWhenReady(int tid);
366 /** Add or Remove a Thread Context in the CPU. */
367 void doContextSwitch();
369 /** Update The Order In Which We Process Threads. */
370 void updateThreadPriority();
372 /** Serialize state. */
373 virtual void serialize(std::ostream &os);
375 /** Unserialize from a checkpoint. */
376 virtual void unserialize(Checkpoint *cp, const std::string §ion);
380 /** Executes a syscall.
381 * @todo: Determine if this needs to be virtual.
383 void syscall(int64_t callnum, int tid);
385 /** Sets the return value of a syscall. */
386 void setSyscallReturn(SyscallReturn return_value, int tid);
390 /** Starts draining the CPU's pipeline of all instructions in
391 * order to stop all memory accesses. */
392 virtual unsigned int drain(Event *drain_event);
394 /** Resumes execution after a drain. */
395 virtual void resume();
397 /** Signals to this CPU that a stage has completed switching out. */
398 void signalDrained();
400 /** Switches out this CPU. */
401 virtual void switchOut();
403 /** Takes over from another CPU. */
404 virtual void takeOverFrom(BaseCPU *oldCPU);
406 /** Get the current instruction sequence number, and increment it. */
407 InstSeqNum getAndIncrementInstSeq()
408 { return globalSeqNum++; }
410 /** Traps to handle given fault. */
411 void trap(Fault fault, unsigned tid);
414 /** Posts an interrupt. */
415 void postInterrupt(int int_num, int index);
417 /** HW return from error interrupt. */
418 Fault hwrei(unsigned tid);
420 bool simPalCheck(int palFunc, unsigned tid);
422 /** Returns the Fault for any valid interrupt. */
423 Fault getInterrupts();
425 /** Processes any an interrupt fault. */
426 void processInterrupts(Fault interrupt);
428 /** Halts the CPU. */
429 void halt() { panic("Halt not implemented!\n"); }
431 /** Update the Virt and Phys ports of all ThreadContexts to
432 * reflect change in memory connections. */
433 void updateMemPorts();
435 /** Check if this address is a valid instruction address. */
436 bool validInstAddr(Addr addr) { return true; }
438 /** Check if this address is a valid data address. */
439 bool validDataAddr(Addr addr) { return true; }
441 /** Get instruction asid. */
442 int getInstAsid(unsigned tid)
443 { return regFile.miscRegs[tid].getInstAsid(); }
445 /** Get data asid. */
446 int getDataAsid(unsigned tid)
447 { return regFile.miscRegs[tid].getDataAsid(); }
449 /** Get instruction asid. */
450 int getInstAsid(unsigned tid)
451 { return thread[tid]->getInstAsid(); }
453 /** Get data asid. */
454 int getDataAsid(unsigned tid)
455 { return thread[tid]->getDataAsid(); }
459 /** Register accessors. Index refers to the physical register index. */
461 /** Reads a miscellaneous register. */
462 TheISA::MiscReg readMiscRegNoEffect(int misc_reg, unsigned tid);
464 /** Reads a misc. register, including any side effects the read
465 * might have as defined by the architecture.
467 TheISA::MiscReg readMiscReg(int misc_reg, unsigned tid);
469 /** Sets a miscellaneous register. */
470 void setMiscRegNoEffect(int misc_reg, const TheISA::MiscReg &val, unsigned tid);
472 /** Sets a misc. register, including any side effects the write
473 * might have as defined by the architecture.
475 void setMiscReg(int misc_reg, const TheISA::MiscReg &val,
478 uint64_t readIntReg(int reg_idx);
480 TheISA::FloatReg readFloatReg(int reg_idx);
482 TheISA::FloatReg readFloatReg(int reg_idx, int width);
484 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
486 TheISA::FloatRegBits readFloatRegBits(int reg_idx, int width);
488 void setIntReg(int reg_idx, uint64_t val);
490 void setFloatReg(int reg_idx, TheISA::FloatReg val);
492 void setFloatReg(int reg_idx, TheISA::FloatReg val, int width);
494 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
496 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val, int width);
498 uint64_t readArchIntReg(int reg_idx, unsigned tid);
500 float readArchFloatRegSingle(int reg_idx, unsigned tid);
502 double readArchFloatRegDouble(int reg_idx, unsigned tid);
504 uint64_t readArchFloatRegInt(int reg_idx, unsigned tid);
506 /** Architectural register accessors. Looks up in the commit
507 * rename table to obtain the true physical index of the
508 * architected register first, then accesses that physical
511 void setArchIntReg(int reg_idx, uint64_t val, unsigned tid);
513 void setArchFloatRegSingle(int reg_idx, float val, unsigned tid);
515 void setArchFloatRegDouble(int reg_idx, double val, unsigned tid);
517 void setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid);
519 /** Reads the commit PC of a specific thread. */
520 Addr readPC(unsigned tid);
522 /** Sets the commit PC of a specific thread. */
523 void setPC(Addr new_PC, unsigned tid);
525 /** Reads the commit micro PC of a specific thread. */
526 Addr readMicroPC(unsigned tid);
528 /** Sets the commmit micro PC of a specific thread. */
529 void setMicroPC(Addr new_microPC, unsigned tid);
531 /** Reads the next PC of a specific thread. */
532 Addr readNextPC(unsigned tid);
534 /** Sets the next PC of a specific thread. */
535 void setNextPC(Addr val, unsigned tid);
537 /** Reads the next NPC of a specific thread. */
538 Addr readNextNPC(unsigned tid);
540 /** Sets the next NPC of a specific thread. */
541 void setNextNPC(Addr val, unsigned tid);
543 /** Reads the commit next micro PC of a specific thread. */
544 Addr readNextMicroPC(unsigned tid);
546 /** Sets the commit next micro PC of a specific thread. */
547 void setNextMicroPC(Addr val, unsigned tid);
549 /** Initiates a squash of all in-flight instructions for a given
550 * thread. The source of the squash is an external update of
551 * state through the TC.
553 void squashFromTC(unsigned tid);
555 /** Function to add instruction onto the head of the list of the
556 * instructions. Used when new instructions are fetched.
558 ListIt addInst(DynInstPtr &inst);
560 /** Function to tell the CPU that an instruction has completed. */
561 void instDone(unsigned tid);
563 /** Add Instructions to the CPU Remove List*/
564 void addToRemoveList(DynInstPtr &inst);
566 /** Remove an instruction from the front end of the list. There's
567 * no restriction on location of the instruction.
569 void removeFrontInst(DynInstPtr &inst);
571 /** Remove all instructions that are not currently in the ROB.
572 * There's also an option to not squash delay slot instructions.*/
573 void removeInstsNotInROB(unsigned tid);
575 /** Remove all instructions younger than the given sequence number. */
576 void removeInstsUntil(const InstSeqNum &seq_num,unsigned tid);
578 /** Removes the instruction pointed to by the iterator. */
579 inline void squashInstIt(const ListIt &instIt, const unsigned &tid);
581 /** Cleans up all instructions on the remove list. */
582 void cleanUpRemovedInsts();
584 /** Debug function to print all instructions on the list. */
588 /** List of all the instructions in flight. */
589 std::list<DynInstPtr> instList;
591 /** List of all the instructions that will be removed at the end of this
594 std::queue<ListIt> removeList;
597 /** Debug structure to keep track of the sequence numbers still in
600 std::set<InstSeqNum> snList;
603 /** Records if instructions need to be removed this cycle due to
604 * being retired or squashed.
606 bool removeInstsThisCycle;
609 /** The fetch stage. */
610 typename CPUPolicy::Fetch fetch;
612 /** The decode stage. */
613 typename CPUPolicy::Decode decode;
615 /** The dispatch stage. */
616 typename CPUPolicy::Rename rename;
618 /** The issue/execute/writeback stages. */
619 typename CPUPolicy::IEW iew;
621 /** The commit stage. */
622 typename CPUPolicy::Commit commit;
624 /** The register file. */
625 typename CPUPolicy::RegFile regFile;
627 /** The free list. */
628 typename CPUPolicy::FreeList freeList;
630 /** The rename map. */
631 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
633 /** The commit rename map. */
634 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
636 /** The re-order buffer. */
637 typename CPUPolicy::ROB rob;
639 /** Active Threads List */
640 std::list<unsigned> activeThreads;
642 /** Integer Register Scoreboard */
643 Scoreboard scoreboard;
646 /** Enum to give each stage a specific index, so when calling
647 * activateStage() or deactivateStage(), they can specify which stage
648 * is being activated/deactivated.
658 /** Typedefs from the Impl to get the structs that each of the
659 * time buffers should use.
661 typedef typename CPUPolicy::TimeStruct TimeStruct;
663 typedef typename CPUPolicy::FetchStruct FetchStruct;
665 typedef typename CPUPolicy::DecodeStruct DecodeStruct;
667 typedef typename CPUPolicy::RenameStruct RenameStruct;
669 typedef typename CPUPolicy::IEWStruct IEWStruct;
671 /** The main time buffer to do backwards communication. */
672 TimeBuffer<TimeStruct> timeBuffer;
674 /** The fetch stage's instruction queue. */
675 TimeBuffer<FetchStruct> fetchQueue;
677 /** The decode stage's instruction queue. */
678 TimeBuffer<DecodeStruct> decodeQueue;
680 /** The rename stage's instruction queue. */
681 TimeBuffer<RenameStruct> renameQueue;
683 /** The IEW stage's instruction queue. */
684 TimeBuffer<IEWStruct> iewQueue;
687 /** The activity recorder; used to tell if the CPU has any
688 * activity remaining or if it can go to idle and deschedule
691 ActivityRecorder activityRec;
694 /** Records that there was time buffer activity this cycle. */
695 void activityThisCycle() { activityRec.activity(); }
697 /** Changes a stage's status to active within the activity recorder. */
698 void activateStage(const StageIdx idx)
699 { activityRec.activateStage(idx); }
701 /** Changes a stage's status to inactive within the activity recorder. */
702 void deactivateStage(const StageIdx idx)
703 { activityRec.deactivateStage(idx); }
705 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
708 /** Gets a free thread id. Use if thread ids change across system. */
712 /** Returns a pointer to a thread context. */
713 ThreadContext *tcBase(unsigned tid)
715 return thread[tid]->getTC();
718 /** The global sequence number counter. */
719 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
722 /** Pointer to the checker, which can dynamically verify
723 * instruction results at run time. This can be set to NULL if it
726 Checker<DynInstPtr> *checker;
730 /** Pointer to the system. */
733 /** Pointer to physical memory. */
734 PhysicalMemory *physmem;
737 /** Event to call process() on once draining has completed. */
740 /** Counter of how many stages have completed draining. */
743 /** Pointers to all of the threads in the CPU. */
744 std::vector<Thread *> thread;
746 /** Whether or not the CPU should defer its registration. */
747 bool deferRegistration;
749 /** Is there a context switch pending? */
752 /** Threads Scheduled to Enter CPU */
753 std::list<int> cpuWaitList;
755 /** The cycle that the CPU was last running, used for statistics. */
756 Tick lastRunningCycle;
758 /** The cycle that the CPU was last activated by a new thread*/
759 Tick lastActivatedCycle;
761 /** Number of Threads CPU can process */
764 /** Mapping for system thread id to cpu id */
765 std::map<unsigned,unsigned> threadMap;
767 /** Available thread ids in the cpu*/
768 std::vector<unsigned> tids;
770 /** CPU read function, forwards read to LSQ. */
772 Fault read(RequestPtr &req, T &data, int load_idx)
774 return this->iew.ldstQueue.read(req, data, load_idx);
777 /** CPU write function, forwards write to LSQ. */
779 Fault write(RequestPtr &req, T &data, int store_idx)
781 return this->iew.ldstQueue.write(req, data, store_idx);
786 /** Temporary fix for the lock flag, works in the UP case. */
789 /** Stat for total number of times the CPU is descheduled. */
790 Stats::Scalar<> timesIdled;
791 /** Stat for total number of cycles the CPU spends descheduled. */
792 Stats::Scalar<> idleCycles;
793 /** Stat for the number of committed instructions per thread. */
794 Stats::Vector<> committedInsts;
795 /** Stat for the total number of committed instructions. */
796 Stats::Scalar<> totalCommittedInsts;
797 /** Stat for the CPI per thread. */
799 /** Stat for the total CPI. */
800 Stats::Formula totalCpi;
801 /** Stat for the IPC per thread. */
803 /** Stat for the total IPC. */
804 Stats::Formula totalIpc;
807 #endif // __CPU_O3_CPU_HH__