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"
60 class O3ThreadContext;
66 class BaseO3CPU : public BaseCPU
68 //Stuff that's pretty ISA independent will go here.
70 typedef BaseCPU::Params Params;
72 BaseO3CPU(Params *params);
76 /** Sets this CPU's ID. */
77 void setCpuId(int id) { cpu_id = id; }
79 /** Reads this CPU's ID. */
80 int readCpuId() { return cpu_id; }
87 * FullO3CPU class, has each of the stages (fetch through commit)
88 * within it, as well as all of the time buffers between stages. The
89 * tick() function for the CPU is defined here.
92 class FullO3CPU : public BaseO3CPU
95 // Typedefs from the Impl here.
96 typedef typename Impl::CPUPol CPUPolicy;
97 typedef typename Impl::DynInstPtr DynInstPtr;
98 typedef typename Impl::O3CPU O3CPU;
99 typedef typename Impl::Params Params;
101 typedef O3ThreadState<Impl> Thread;
103 typedef typename std::list<DynInstPtr>::iterator ListIt;
105 friend class O3ThreadContext<Impl>;
119 /** Overall CPU status. */
122 /** Per-thread status in CPU, used for SMT. */
123 Status _threadStatus[Impl::MaxThreads];
126 class TickEvent : public Event
129 /** Pointer to the CPU. */
130 FullO3CPU<Impl> *cpu;
133 /** Constructs a tick event. */
134 TickEvent(FullO3CPU<Impl> *c);
136 /** Processes a tick event, calling tick() on the CPU. */
138 /** Returns the description of the tick event. */
139 const char *description() const;
142 /** The tick event used for scheduling CPU ticks. */
145 /** Schedule tick event, regardless of its current state. */
146 void scheduleTickEvent(int delay)
148 if (tickEvent.squashed())
149 tickEvent.reschedule(nextCycle(curTick + ticks(delay)));
150 else if (!tickEvent.scheduled())
151 tickEvent.schedule(nextCycle(curTick + ticks(delay)));
154 /** Unschedule tick event, regardless of its current state. */
155 void unscheduleTickEvent()
157 if (tickEvent.scheduled())
161 class ActivateThreadEvent : public Event
164 /** Number of Thread to Activate */
167 /** Pointer to the CPU. */
168 FullO3CPU<Impl> *cpu;
171 /** Constructs the event. */
172 ActivateThreadEvent();
174 /** Initialize Event */
175 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
177 /** Processes the event, calling activateThread() on the CPU. */
180 /** Returns the description of the event. */
181 const char *description() const;
184 /** Schedule thread to activate , regardless of its current state. */
185 void scheduleActivateThreadEvent(int tid, int delay)
187 // Schedule thread to activate, regardless of its current state.
188 if (activateThreadEvent[tid].squashed())
189 activateThreadEvent[tid].
190 reschedule(nextCycle(curTick + ticks(delay)));
191 else if (!activateThreadEvent[tid].scheduled())
192 activateThreadEvent[tid].
193 schedule(nextCycle(curTick + ticks(delay)));
196 /** Unschedule actiavte thread event, regardless of its current state. */
197 void unscheduleActivateThreadEvent(int tid)
199 if (activateThreadEvent[tid].scheduled())
200 activateThreadEvent[tid].squash();
203 /** The tick event used for scheduling CPU ticks. */
204 ActivateThreadEvent activateThreadEvent[Impl::MaxThreads];
206 class DeallocateContextEvent : public Event
209 /** Number of Thread to deactivate */
212 /** Should the thread be removed from the CPU? */
215 /** Pointer to the CPU. */
216 FullO3CPU<Impl> *cpu;
219 /** Constructs the event. */
220 DeallocateContextEvent();
222 /** Initialize Event */
223 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
225 /** Processes the event, calling activateThread() on the CPU. */
228 /** Sets whether the thread should also be removed from the CPU. */
229 void setRemove(bool _remove) { remove = _remove; }
231 /** Returns the description of the event. */
232 const char *description() const;
235 /** Schedule cpu to deallocate thread context.*/
236 void scheduleDeallocateContextEvent(int tid, bool remove, int delay)
238 // Schedule thread to activate, regardless of its current state.
239 if (deallocateContextEvent[tid].squashed())
240 deallocateContextEvent[tid].
241 reschedule(nextCycle(curTick + ticks(delay)));
242 else if (!deallocateContextEvent[tid].scheduled())
243 deallocateContextEvent[tid].
244 schedule(nextCycle(curTick + ticks(delay)));
247 /** Unschedule thread deallocation in CPU */
248 void unscheduleDeallocateContextEvent(int tid)
250 if (deallocateContextEvent[tid].scheduled())
251 deallocateContextEvent[tid].squash();
254 /** The tick event used for scheduling CPU ticks. */
255 DeallocateContextEvent deallocateContextEvent[Impl::MaxThreads];
258 /** Constructs a CPU with the given parameters. */
259 FullO3CPU(O3CPU *o3_cpu, Params *params);
263 /** Registers statistics. */
264 void fullCPURegStats();
266 /** Translates instruction requestion. */
267 Fault translateInstReq(RequestPtr &req, Thread *thread)
269 return this->itb->translate(req, thread->getTC());
272 /** Translates data read request. */
273 Fault translateDataReadReq(RequestPtr &req, Thread *thread)
275 return this->dtb->translate(req, thread->getTC(), false);
278 /** Translates data write request. */
279 Fault translateDataWriteReq(RequestPtr &req, Thread *thread)
281 return this->dtb->translate(req, thread->getTC(), true);
284 /** Returns a specific port. */
285 Port *getPort(const std::string &if_name, int idx);
287 /** Ticks CPU, calling tick() on each stage, and checking the overall
288 * activity to see if the CPU should deschedule itself.
292 /** Initialize the CPU */
295 /** Returns the Number of Active Threads in the CPU */
296 int numActiveThreads()
297 { return activeThreads.size(); }
299 /** Add Thread to Active Threads List */
300 void activateThread(unsigned tid);
302 /** Remove Thread from Active Threads List */
303 void deactivateThread(unsigned tid);
305 /** Setup CPU to insert a thread's context */
306 void insertThread(unsigned tid);
308 /** Remove all of a thread's context from CPU */
309 void removeThread(unsigned tid);
311 /** Count the Total Instructions Committed in the CPU. */
312 virtual Counter totalInstructions() const
316 for (int i=0; i < thread.size(); i++)
317 total += thread[i]->numInst;
322 /** Add Thread to Active Threads List. */
323 void activateContext(int tid, int delay);
325 /** Remove Thread from Active Threads List */
326 void suspendContext(int tid);
328 /** Remove Thread from Active Threads List &&
329 * Possibly Remove Thread Context from CPU.
331 bool deallocateContext(int tid, bool remove, int delay = 1);
333 /** Remove Thread from Active Threads List &&
334 * Remove Thread Context from CPU.
336 void haltContext(int tid);
338 /** Activate a Thread When CPU Resources are Available. */
339 void activateWhenReady(int tid);
341 /** Add or Remove a Thread Context in the CPU. */
342 void doContextSwitch();
344 /** Update The Order In Which We Process Threads. */
345 void updateThreadPriority();
347 /** Serialize state. */
348 virtual void serialize(std::ostream &os);
350 /** Unserialize from a checkpoint. */
351 virtual void unserialize(Checkpoint *cp, const std::string §ion);
354 /** Executes a syscall on this cycle.
355 * ---------------------------------------
356 * Note: this is a virtual function. CPU-Specific
357 * functionality defined in derived classes
359 virtual void syscall(int tid) { panic("Unimplemented!"); }
361 /** Starts draining the CPU's pipeline of all instructions in
362 * order to stop all memory accesses. */
363 virtual unsigned int drain(Event *drain_event);
365 /** Resumes execution after a drain. */
366 virtual void resume();
368 /** Signals to this CPU that a stage has completed switching out. */
369 void signalDrained();
371 /** Switches out this CPU. */
372 virtual void switchOut();
374 /** Takes over from another CPU. */
375 virtual void takeOverFrom(BaseCPU *oldCPU);
377 /** Get the current instruction sequence number, and increment it. */
378 InstSeqNum getAndIncrementInstSeq()
379 { return globalSeqNum++; }
382 /** Update the Virt and Phys ports of all ThreadContexts to
383 * reflect change in memory connections. */
384 void updateMemPorts();
386 /** Check if this address is a valid instruction address. */
387 bool validInstAddr(Addr addr) { return true; }
389 /** Check if this address is a valid data address. */
390 bool validDataAddr(Addr addr) { return true; }
392 /** Get instruction asid. */
393 int getInstAsid(unsigned tid)
394 { return regFile.miscRegs[tid].getInstAsid(); }
396 /** Get data asid. */
397 int getDataAsid(unsigned tid)
398 { return regFile.miscRegs[tid].getDataAsid(); }
400 /** Get instruction asid. */
401 int getInstAsid(unsigned tid)
402 { return thread[tid]->getInstAsid(); }
404 /** Get data asid. */
405 int getDataAsid(unsigned tid)
406 { return thread[tid]->getDataAsid(); }
410 /** Register accessors. Index refers to the physical register index. */
411 uint64_t readIntReg(int reg_idx);
413 TheISA::FloatReg readFloatReg(int reg_idx);
415 TheISA::FloatReg readFloatReg(int reg_idx, int width);
417 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
419 TheISA::FloatRegBits readFloatRegBits(int reg_idx, int width);
421 void setIntReg(int reg_idx, uint64_t val);
423 void setFloatReg(int reg_idx, TheISA::FloatReg val);
425 void setFloatReg(int reg_idx, TheISA::FloatReg val, int width);
427 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
429 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val, int width);
431 uint64_t readArchIntReg(int reg_idx, unsigned tid);
433 float readArchFloatRegSingle(int reg_idx, unsigned tid);
435 double readArchFloatRegDouble(int reg_idx, unsigned tid);
437 uint64_t readArchFloatRegInt(int reg_idx, unsigned 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, unsigned tid);
446 void setArchFloatRegSingle(int reg_idx, float val, unsigned tid);
448 void setArchFloatRegDouble(int reg_idx, double val, unsigned tid);
450 void setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid);
452 /** Reads the commit PC of a specific thread. */
453 Addr readPC(unsigned tid);
455 /** Sets the commit PC of a specific thread. */
456 void setPC(Addr new_PC, unsigned tid);
458 /** Reads the commit micro PC of a specific thread. */
459 Addr readMicroPC(unsigned tid);
461 /** Sets the commmit micro PC of a specific thread. */
462 void setMicroPC(Addr new_microPC, unsigned tid);
464 /** Reads the next PC of a specific thread. */
465 Addr readNextPC(unsigned tid);
467 /** Sets the next PC of a specific thread. */
468 void setNextPC(Addr val, unsigned tid);
470 /** Reads the next NPC of a specific thread. */
471 Addr readNextNPC(unsigned tid);
473 /** Sets the next NPC of a specific thread. */
474 void setNextNPC(Addr val, unsigned tid);
476 /** Reads the commit next micro PC of a specific thread. */
477 Addr readNextMicroPC(unsigned tid);
479 /** Sets the commit next micro PC of a specific thread. */
480 void setNextMicroPC(Addr val, unsigned tid);
482 /** Function to add instruction onto the head of the list of the
483 * instructions. Used when new instructions are fetched.
485 ListIt addInst(DynInstPtr &inst);
487 /** Function to tell the CPU that an instruction has completed. */
488 void instDone(unsigned tid);
490 /** Add Instructions to the CPU Remove List*/
491 void addToRemoveList(DynInstPtr &inst);
493 /** Remove an instruction from the front end of the list. There's
494 * no restriction on location of the instruction.
496 void removeFrontInst(DynInstPtr &inst);
498 /** Remove all instructions that are not currently in the ROB.
499 * There's also an option to not squash delay slot instructions.*/
500 void removeInstsNotInROB(unsigned tid);
502 /** Remove all instructions younger than the given sequence number. */
503 void removeInstsUntil(const InstSeqNum &seq_num,unsigned tid);
505 /** Removes the instruction pointed to by the iterator. */
506 inline void squashInstIt(const ListIt &instIt, const unsigned &tid);
508 /** Cleans up all instructions on the remove list. */
509 void cleanUpRemovedInsts();
511 /** Debug function to print all instructions on the list. */
515 /** List of all the instructions in flight. */
516 std::list<DynInstPtr> instList;
518 /** List of all the instructions that will be removed at the end of this
521 std::queue<ListIt> removeList;
524 /** Debug structure to keep track of the sequence numbers still in
527 std::set<InstSeqNum> snList;
530 /** Records if instructions need to be removed this cycle due to
531 * being retired or squashed.
533 bool removeInstsThisCycle;
536 /** The fetch stage. */
537 typename CPUPolicy::Fetch fetch;
539 /** The decode stage. */
540 typename CPUPolicy::Decode decode;
542 /** The dispatch stage. */
543 typename CPUPolicy::Rename rename;
545 /** The issue/execute/writeback stages. */
546 typename CPUPolicy::IEW iew;
548 /** The commit stage. */
549 typename CPUPolicy::Commit commit;
551 /** The register file. */
552 typename CPUPolicy::RegFile regFile;
554 /** The free list. */
555 typename CPUPolicy::FreeList freeList;
557 /** The rename map. */
558 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
560 /** The commit rename map. */
561 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
563 /** The re-order buffer. */
564 typename CPUPolicy::ROB rob;
566 /** Active Threads List */
567 std::list<unsigned> activeThreads;
569 /** Integer Register Scoreboard */
570 Scoreboard scoreboard;
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 /** Gets a free thread id. Use if thread ids change across system. */
639 /** Returns a pointer to a thread context. */
640 ThreadContext *tcBase(unsigned tid)
642 return thread[tid]->getTC();
645 /** The global sequence number counter. */
646 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
649 /** Pointer to the checker, which can dynamically verify
650 * instruction results at run time. This can be set to NULL if it
653 Checker<DynInstPtr> *checker;
657 /** Pointer to the system. */
660 /** Pointer to physical memory. */
661 PhysicalMemory *physmem;
664 /** Event to call process() on once draining has completed. */
667 /** Counter of how many stages have completed draining. */
670 /** Pointers to all of the threads in the CPU. */
671 std::vector<Thread *> thread;
673 /** Whether or not the CPU should defer its registration. */
674 bool deferRegistration;
676 /** Is there a context switch pending? */
679 /** Threads Scheduled to Enter CPU */
680 std::list<int> cpuWaitList;
682 /** The cycle that the CPU was last running, used for statistics. */
683 Tick lastRunningCycle;
685 /** The cycle that the CPU was last activated by a new thread*/
686 Tick lastActivatedCycle;
688 /** Number of Threads CPU can process */
691 /** Mapping for system thread id to cpu id */
692 std::map<unsigned,unsigned> threadMap;
694 /** Available thread ids in the cpu*/
695 std::vector<unsigned> tids;
697 /** Stat for total number of times the CPU is descheduled. */
698 Stats::Scalar<> timesIdled;
699 /** Stat for total number of cycles the CPU spends descheduled. */
700 Stats::Scalar<> idleCycles;
701 /** Stat for the number of committed instructions per thread. */
702 Stats::Vector<> committedInsts;
703 /** Stat for the total number of committed instructions. */
704 Stats::Scalar<> totalCommittedInsts;
705 /** Stat for the CPI per thread. */
707 /** Stat for the total CPI. */
708 Stats::Formula totalCpi;
709 /** Stat for the IPC per thread. */
711 /** Stat for the total IPC. */
712 Stats::Formula totalIpc;
715 #endif // __CPU_O3_CPU_HH__