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::Params Params;
98 typedef typename Impl::DynInstPtr DynInstPtr;
99 typedef typename Impl::O3CPU O3CPU;
101 typedef O3ThreadState<Impl> Thread;
103 typedef typename std::list<DynInstPtr>::iterator ListIt;
105 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();
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 tickEvent.reschedule(nextCycle(curTick + cycles(delay)));
152 else if (!tickEvent.scheduled())
153 tickEvent.schedule(nextCycle(curTick + cycles(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();
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 activateThreadEvent[tid].
192 reschedule(nextCycle(curTick + cycles(delay)));
193 else if (!activateThreadEvent[tid].scheduled())
194 activateThreadEvent[tid].
195 schedule(nextCycle(curTick + cycles(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();
205 /** The tick event used for scheduling CPU ticks. */
206 ActivateThreadEvent activateThreadEvent[Impl::MaxThreads];
208 class DeallocateContextEvent : public Event
211 /** Number of Thread to deactivate */
214 /** Should the thread be removed from the CPU? */
217 /** Pointer to the CPU. */
218 FullO3CPU<Impl> *cpu;
221 /** Constructs the event. */
222 DeallocateContextEvent();
224 /** Initialize Event */
225 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
227 /** Processes the event, calling activateThread() on the CPU. */
230 /** Sets whether the thread should also be removed from the CPU. */
231 void setRemove(bool _remove) { remove = _remove; }
233 /** Returns the description of the event. */
234 const char *description();
237 /** Schedule cpu to deallocate thread context.*/
238 void scheduleDeallocateContextEvent(int tid, bool remove, int delay)
240 // Schedule thread to activate, regardless of its current state.
241 if (deallocateContextEvent[tid].squashed())
242 deallocateContextEvent[tid].
243 reschedule(nextCycle(curTick + cycles(delay)));
244 else if (!deallocateContextEvent[tid].scheduled())
245 deallocateContextEvent[tid].
246 schedule(nextCycle(curTick + cycles(delay)));
249 /** Unschedule thread deallocation in CPU */
250 void unscheduleDeallocateContextEvent(int tid)
252 if (deallocateContextEvent[tid].scheduled())
253 deallocateContextEvent[tid].squash();
256 /** The tick event used for scheduling CPU ticks. */
257 DeallocateContextEvent deallocateContextEvent[Impl::MaxThreads];
260 /** Constructs a CPU with the given parameters. */
261 FullO3CPU(O3CPU *o3_cpu, Params *params);
265 /** Registers statistics. */
266 void fullCPURegStats();
268 /** Returns a specific port. */
269 Port *getPort(const std::string &if_name, int idx);
271 /** Ticks CPU, calling tick() on each stage, and checking the overall
272 * activity to see if the CPU should deschedule itself.
276 /** Initialize the CPU */
279 /** Returns the Number of Active Threads in the CPU */
280 int numActiveThreads()
281 { return activeThreads.size(); }
283 /** Add Thread to Active Threads List */
284 void activateThread(unsigned tid);
286 /** Remove Thread from Active Threads List */
287 void deactivateThread(unsigned tid);
289 /** Setup CPU to insert a thread's context */
290 void insertThread(unsigned tid);
292 /** Remove all of a thread's context from CPU */
293 void removeThread(unsigned tid);
295 /** Count the Total Instructions Committed in the CPU. */
296 virtual Counter totalInstructions() const
300 for (int i=0; i < thread.size(); i++)
301 total += thread[i]->numInst;
306 /** Add Thread to Active Threads List. */
307 void activateContext(int tid, int delay);
309 /** Remove Thread from Active Threads List */
310 void suspendContext(int tid);
312 /** Remove Thread from Active Threads List &&
313 * Possibly Remove Thread Context from CPU.
315 bool deallocateContext(int tid, bool remove, int delay = 1);
317 /** Remove Thread from Active Threads List &&
318 * Remove Thread Context from CPU.
320 void haltContext(int tid);
322 /** Activate a Thread When CPU Resources are Available. */
323 void activateWhenReady(int tid);
325 /** Add or Remove a Thread Context in the CPU. */
326 void doContextSwitch();
328 /** Update The Order In Which We Process Threads. */
329 void updateThreadPriority();
331 /** Serialize state. */
332 virtual void serialize(std::ostream &os);
334 /** Unserialize from a checkpoint. */
335 virtual void unserialize(Checkpoint *cp, const std::string §ion);
338 /** Executes a syscall on this cycle.
339 * ---------------------------------------
340 * Note: this is a virtual function. CPU-Specific
341 * functionality defined in derived classes
343 virtual void syscall(int tid) { panic("Unimplemented!"); }
345 /** Starts draining the CPU's pipeline of all instructions in
346 * order to stop all memory accesses. */
347 virtual unsigned int drain(Event *drain_event);
349 /** Resumes execution after a drain. */
350 virtual void resume();
352 /** Signals to this CPU that a stage has completed switching out. */
353 void signalDrained();
355 /** Switches out this CPU. */
356 virtual void switchOut();
358 /** Takes over from another CPU. */
359 virtual void takeOverFrom(BaseCPU *oldCPU);
361 /** Get the current instruction sequence number, and increment it. */
362 InstSeqNum getAndIncrementInstSeq()
363 { return globalSeqNum++; }
366 /** Update the Virt and Phys ports of all ThreadContexts to
367 * reflect change in memory connections. */
368 void updateMemPorts();
370 /** Check if this address is a valid instruction address. */
371 bool validInstAddr(Addr addr) { return true; }
373 /** Check if this address is a valid data address. */
374 bool validDataAddr(Addr addr) { return true; }
376 /** Get instruction asid. */
377 int getInstAsid(unsigned tid)
378 { return regFile.miscRegs[tid].getInstAsid(); }
380 /** Get data asid. */
381 int getDataAsid(unsigned tid)
382 { return regFile.miscRegs[tid].getDataAsid(); }
384 /** Get instruction asid. */
385 int getInstAsid(unsigned tid)
386 { return thread[tid]->getInstAsid(); }
388 /** Get data asid. */
389 int getDataAsid(unsigned tid)
390 { return thread[tid]->getDataAsid(); }
394 /** Register accessors. Index refers to the physical register index. */
395 uint64_t readIntReg(int reg_idx);
397 TheISA::FloatReg readFloatReg(int reg_idx);
399 TheISA::FloatReg readFloatReg(int reg_idx, int width);
401 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
403 TheISA::FloatRegBits readFloatRegBits(int reg_idx, int width);
405 void setIntReg(int reg_idx, uint64_t val);
407 void setFloatReg(int reg_idx, TheISA::FloatReg val);
409 void setFloatReg(int reg_idx, TheISA::FloatReg val, int width);
411 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
413 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val, int width);
415 uint64_t readArchIntReg(int reg_idx, unsigned tid);
417 float readArchFloatRegSingle(int reg_idx, unsigned tid);
419 double readArchFloatRegDouble(int reg_idx, unsigned tid);
421 uint64_t readArchFloatRegInt(int reg_idx, unsigned tid);
423 /** Architectural register accessors. Looks up in the commit
424 * rename table to obtain the true physical index of the
425 * architected register first, then accesses that physical
428 void setArchIntReg(int reg_idx, uint64_t val, unsigned tid);
430 void setArchFloatRegSingle(int reg_idx, float val, unsigned tid);
432 void setArchFloatRegDouble(int reg_idx, double val, unsigned tid);
434 void setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid);
436 /** Reads the commit PC of a specific thread. */
437 Addr readPC(unsigned tid);
439 /** Sets the commit PC of a specific thread. */
440 void setPC(Addr new_PC, unsigned tid);
442 /** Reads the commit micro PC of a specific thread. */
443 Addr readMicroPC(unsigned tid);
445 /** Sets the commmit micro PC of a specific thread. */
446 void setMicroPC(Addr new_microPC, unsigned tid);
448 /** Reads the next PC of a specific thread. */
449 Addr readNextPC(unsigned tid);
451 /** Sets the next PC of a specific thread. */
452 void setNextPC(Addr val, unsigned tid);
454 /** Reads the next NPC of a specific thread. */
455 Addr readNextNPC(unsigned tid);
457 /** Sets the next NPC of a specific thread. */
458 void setNextNPC(Addr val, unsigned tid);
460 /** Reads the commit next micro PC of a specific thread. */
461 Addr readNextMicroPC(unsigned tid);
463 /** Sets the commit next micro PC of a specific thread. */
464 void setNextMicroPC(Addr val, unsigned tid);
466 /** Function to add instruction onto the head of the list of the
467 * instructions. Used when new instructions are fetched.
469 ListIt addInst(DynInstPtr &inst);
471 /** Function to tell the CPU that an instruction has completed. */
472 void instDone(unsigned tid);
474 /** Add Instructions to the CPU Remove List*/
475 void addToRemoveList(DynInstPtr &inst);
477 /** Remove an instruction from the front end of the list. There's
478 * no restriction on location of the instruction.
480 void removeFrontInst(DynInstPtr &inst);
482 /** Remove all instructions that are not currently in the ROB.
483 * There's also an option to not squash delay slot instructions.*/
484 void removeInstsNotInROB(unsigned tid);
486 /** Remove all instructions younger than the given sequence number. */
487 void removeInstsUntil(const InstSeqNum &seq_num,unsigned tid);
489 /** Removes the instruction pointed to by the iterator. */
490 inline void squashInstIt(const ListIt &instIt, const unsigned &tid);
492 /** Cleans up all instructions on the remove list. */
493 void cleanUpRemovedInsts();
495 /** Debug function to print all instructions on the list. */
499 /** List of all the instructions in flight. */
500 std::list<DynInstPtr> instList;
502 /** List of all the instructions that will be removed at the end of this
505 std::queue<ListIt> removeList;
508 /** Debug structure to keep track of the sequence numbers still in
511 std::set<InstSeqNum> snList;
514 /** Records if instructions need to be removed this cycle due to
515 * being retired or squashed.
517 bool removeInstsThisCycle;
520 /** The fetch stage. */
521 typename CPUPolicy::Fetch fetch;
523 /** The decode stage. */
524 typename CPUPolicy::Decode decode;
526 /** The dispatch stage. */
527 typename CPUPolicy::Rename rename;
529 /** The issue/execute/writeback stages. */
530 typename CPUPolicy::IEW iew;
532 /** The commit stage. */
533 typename CPUPolicy::Commit commit;
535 /** The register file. */
536 typename CPUPolicy::RegFile regFile;
538 /** The free list. */
539 typename CPUPolicy::FreeList freeList;
541 /** The rename map. */
542 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
544 /** The commit rename map. */
545 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
547 /** The re-order buffer. */
548 typename CPUPolicy::ROB rob;
550 /** Active Threads List */
551 std::list<unsigned> activeThreads;
553 /** Integer Register Scoreboard */
554 Scoreboard scoreboard;
557 /** Enum to give each stage a specific index, so when calling
558 * activateStage() or deactivateStage(), they can specify which stage
559 * is being activated/deactivated.
569 /** Typedefs from the Impl to get the structs that each of the
570 * time buffers should use.
572 typedef typename CPUPolicy::TimeStruct TimeStruct;
574 typedef typename CPUPolicy::FetchStruct FetchStruct;
576 typedef typename CPUPolicy::DecodeStruct DecodeStruct;
578 typedef typename CPUPolicy::RenameStruct RenameStruct;
580 typedef typename CPUPolicy::IEWStruct IEWStruct;
582 /** The main time buffer to do backwards communication. */
583 TimeBuffer<TimeStruct> timeBuffer;
585 /** The fetch stage's instruction queue. */
586 TimeBuffer<FetchStruct> fetchQueue;
588 /** The decode stage's instruction queue. */
589 TimeBuffer<DecodeStruct> decodeQueue;
591 /** The rename stage's instruction queue. */
592 TimeBuffer<RenameStruct> renameQueue;
594 /** The IEW stage's instruction queue. */
595 TimeBuffer<IEWStruct> iewQueue;
598 /** The activity recorder; used to tell if the CPU has any
599 * activity remaining or if it can go to idle and deschedule
602 ActivityRecorder activityRec;
605 /** Records that there was time buffer activity this cycle. */
606 void activityThisCycle() { activityRec.activity(); }
608 /** Changes a stage's status to active within the activity recorder. */
609 void activateStage(const StageIdx idx)
610 { activityRec.activateStage(idx); }
612 /** Changes a stage's status to inactive within the activity recorder. */
613 void deactivateStage(const StageIdx idx)
614 { activityRec.deactivateStage(idx); }
616 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
619 /** Gets a free thread id. Use if thread ids change across system. */
623 /** Returns a pointer to a thread context. */
624 ThreadContext *tcBase(unsigned tid)
626 return thread[tid]->getTC();
629 /** The global sequence number counter. */
630 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
633 /** Pointer to the checker, which can dynamically verify
634 * instruction results at run time. This can be set to NULL if it
637 Checker<DynInstPtr> *checker;
641 /** Pointer to the system. */
644 /** Pointer to physical memory. */
645 PhysicalMemory *physmem;
648 /** Event to call process() on once draining has completed. */
651 /** Counter of how many stages have completed draining. */
654 /** Pointers to all of the threads in the CPU. */
655 std::vector<Thread *> thread;
657 /** Whether or not the CPU should defer its registration. */
658 bool deferRegistration;
660 /** Is there a context switch pending? */
663 /** Threads Scheduled to Enter CPU */
664 std::list<int> cpuWaitList;
666 /** The cycle that the CPU was last running, used for statistics. */
667 Tick lastRunningCycle;
669 /** The cycle that the CPU was last activated by a new thread*/
670 Tick lastActivatedCycle;
672 /** Number of Threads CPU can process */
675 /** Mapping for system thread id to cpu id */
676 std::map<unsigned,unsigned> threadMap;
678 /** Available thread ids in the cpu*/
679 std::vector<unsigned> tids;
681 /** Stat for total number of times the CPU is descheduled. */
682 Stats::Scalar<> timesIdled;
683 /** Stat for total number of cycles the CPU spends descheduled. */
684 Stats::Scalar<> idleCycles;
685 /** Stat for the number of committed instructions per thread. */
686 Stats::Vector<> committedInsts;
687 /** Stat for the total number of committed instructions. */
688 Stats::Scalar<> totalCommittedInsts;
689 /** Stat for the CPI per thread. */
691 /** Stat for the total CPI. */
692 Stats::Formula totalCpi;
693 /** Stat for the IPC per thread. */
695 /** Stat for the total IPC. */
696 Stats::Formula totalIpc;
699 #endif // __CPU_O3_CPU_HH__