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>;
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();
269 /** Translates instruction requestion. */
270 Fault translateInstReq(RequestPtr &req, Thread *thread)
272 return this->itb->translate(req, thread->getTC());
275 /** Translates data read request. */
276 Fault translateDataReadReq(RequestPtr &req, Thread *thread)
278 return this->dtb->translate(req, thread->getTC(), false);
281 /** Translates data write request. */
282 Fault translateDataWriteReq(RequestPtr &req, Thread *thread)
284 return this->dtb->translate(req, thread->getTC(), true);
288 /** Translates instruction requestion in syscall emulation mode. */
289 Fault translateInstReq(RequestPtr &req, Thread *thread)
291 return thread->getProcessPtr()->pTable->translate(req);
294 /** Translates data read request in syscall emulation mode. */
295 Fault translateDataReadReq(RequestPtr &req, Thread *thread)
297 return thread->getProcessPtr()->pTable->translate(req);
300 /** Translates data write request in syscall emulation mode. */
301 Fault translateDataWriteReq(RequestPtr &req, Thread *thread)
303 return thread->getProcessPtr()->pTable->translate(req);
308 /** Returns a specific port. */
309 Port *getPort(const std::string &if_name, int idx);
311 /** Ticks CPU, calling tick() on each stage, and checking the overall
312 * activity to see if the CPU should deschedule itself.
316 /** Initialize the CPU */
319 /** Returns the Number of Active Threads in the CPU */
320 int numActiveThreads()
321 { return activeThreads.size(); }
323 /** Add Thread to Active Threads List */
324 void activateThread(unsigned tid);
326 /** Remove Thread from Active Threads List */
327 void deactivateThread(unsigned tid);
329 /** Setup CPU to insert a thread's context */
330 void insertThread(unsigned tid);
332 /** Remove all of a thread's context from CPU */
333 void removeThread(unsigned tid);
335 /** Count the Total Instructions Committed in the CPU. */
336 virtual Counter totalInstructions() const
340 for (int i=0; i < thread.size(); i++)
341 total += thread[i]->numInst;
346 /** Add Thread to Active Threads List. */
347 void activateContext(int tid, int delay);
349 /** Remove Thread from Active Threads List */
350 void suspendContext(int tid);
352 /** Remove Thread from Active Threads List &&
353 * Possibly Remove Thread Context from CPU.
355 bool deallocateContext(int tid, bool remove, int delay = 1);
357 /** Remove Thread from Active Threads List &&
358 * Remove Thread Context from CPU.
360 void haltContext(int tid);
362 /** Activate a Thread When CPU Resources are Available. */
363 void activateWhenReady(int tid);
365 /** Add or Remove a Thread Context in the CPU. */
366 void doContextSwitch();
368 /** Update The Order In Which We Process Threads. */
369 void updateThreadPriority();
371 /** Serialize state. */
372 virtual void serialize(std::ostream &os);
374 /** Unserialize from a checkpoint. */
375 virtual void unserialize(Checkpoint *cp, const std::string §ion);
378 /** Executes a syscall on this cycle.
379 * ---------------------------------------
380 * Note: this is a virtual function. CPU-Specific
381 * functionality defined in derived classes
383 virtual void syscall(int tid) { panic("Unimplemented!"); }
385 /** Starts draining the CPU's pipeline of all instructions in
386 * order to stop all memory accesses. */
387 virtual unsigned int drain(Event *drain_event);
389 /** Resumes execution after a drain. */
390 virtual void resume();
392 /** Signals to this CPU that a stage has completed switching out. */
393 void signalDrained();
395 /** Switches out this CPU. */
396 virtual void switchOut();
398 /** Takes over from another CPU. */
399 virtual void takeOverFrom(BaseCPU *oldCPU);
401 /** Get the current instruction sequence number, and increment it. */
402 InstSeqNum getAndIncrementInstSeq()
403 { return globalSeqNum++; }
406 /** Update the Virt and Phys ports of all ThreadContexts to
407 * reflect change in memory connections. */
408 void updateMemPorts();
410 /** Check if this address is a valid instruction address. */
411 bool validInstAddr(Addr addr) { return true; }
413 /** Check if this address is a valid data address. */
414 bool validDataAddr(Addr addr) { return true; }
416 /** Get instruction asid. */
417 int getInstAsid(unsigned tid)
418 { return regFile.miscRegs[tid].getInstAsid(); }
420 /** Get data asid. */
421 int getDataAsid(unsigned tid)
422 { return regFile.miscRegs[tid].getDataAsid(); }
424 /** Get instruction asid. */
425 int getInstAsid(unsigned tid)
426 { return thread[tid]->getInstAsid(); }
428 /** Get data asid. */
429 int getDataAsid(unsigned tid)
430 { return thread[tid]->getDataAsid(); }
434 /** Register accessors. Index refers to the physical register index. */
435 uint64_t readIntReg(int reg_idx);
437 TheISA::FloatReg readFloatReg(int reg_idx);
439 TheISA::FloatReg readFloatReg(int reg_idx, int width);
441 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
443 TheISA::FloatRegBits readFloatRegBits(int reg_idx, int width);
445 void setIntReg(int reg_idx, uint64_t val);
447 void setFloatReg(int reg_idx, TheISA::FloatReg val);
449 void setFloatReg(int reg_idx, TheISA::FloatReg val, int width);
451 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
453 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val, int width);
455 uint64_t readArchIntReg(int reg_idx, unsigned tid);
457 float readArchFloatRegSingle(int reg_idx, unsigned tid);
459 double readArchFloatRegDouble(int reg_idx, unsigned tid);
461 uint64_t readArchFloatRegInt(int reg_idx, unsigned tid);
463 /** Architectural register accessors. Looks up in the commit
464 * rename table to obtain the true physical index of the
465 * architected register first, then accesses that physical
468 void setArchIntReg(int reg_idx, uint64_t val, unsigned tid);
470 void setArchFloatRegSingle(int reg_idx, float val, unsigned tid);
472 void setArchFloatRegDouble(int reg_idx, double val, unsigned tid);
474 void setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid);
476 /** Reads the commit PC of a specific thread. */
477 Addr readPC(unsigned tid);
479 /** Sets the commit PC of a specific thread. */
480 void setPC(Addr new_PC, unsigned tid);
482 /** Reads the commit micro PC of a specific thread. */
483 Addr readMicroPC(unsigned tid);
485 /** Sets the commmit micro PC of a specific thread. */
486 void setMicroPC(Addr new_microPC, unsigned tid);
488 /** Reads the next PC of a specific thread. */
489 Addr readNextPC(unsigned tid);
491 /** Sets the next PC of a specific thread. */
492 void setNextPC(Addr val, unsigned tid);
494 /** Reads the next NPC of a specific thread. */
495 Addr readNextNPC(unsigned tid);
497 /** Sets the next NPC of a specific thread. */
498 void setNextNPC(Addr val, unsigned tid);
500 /** Reads the commit next micro PC of a specific thread. */
501 Addr readNextMicroPC(unsigned tid);
503 /** Sets the commit next micro PC of a specific thread. */
504 void setNextMicroPC(Addr val, unsigned tid);
506 /** Function to add instruction onto the head of the list of the
507 * instructions. Used when new instructions are fetched.
509 ListIt addInst(DynInstPtr &inst);
511 /** Function to tell the CPU that an instruction has completed. */
512 void instDone(unsigned tid);
514 /** Add Instructions to the CPU Remove List*/
515 void addToRemoveList(DynInstPtr &inst);
517 /** Remove an instruction from the front end of the list. There's
518 * no restriction on location of the instruction.
520 void removeFrontInst(DynInstPtr &inst);
522 /** Remove all instructions that are not currently in the ROB.
523 * There's also an option to not squash delay slot instructions.*/
524 void removeInstsNotInROB(unsigned tid);
526 /** Remove all instructions younger than the given sequence number. */
527 void removeInstsUntil(const InstSeqNum &seq_num,unsigned tid);
529 /** Removes the instruction pointed to by the iterator. */
530 inline void squashInstIt(const ListIt &instIt, const unsigned &tid);
532 /** Cleans up all instructions on the remove list. */
533 void cleanUpRemovedInsts();
535 /** Debug function to print all instructions on the list. */
539 /** List of all the instructions in flight. */
540 std::list<DynInstPtr> instList;
542 /** List of all the instructions that will be removed at the end of this
545 std::queue<ListIt> removeList;
548 /** Debug structure to keep track of the sequence numbers still in
551 std::set<InstSeqNum> snList;
554 /** Records if instructions need to be removed this cycle due to
555 * being retired or squashed.
557 bool removeInstsThisCycle;
560 /** The fetch stage. */
561 typename CPUPolicy::Fetch fetch;
563 /** The decode stage. */
564 typename CPUPolicy::Decode decode;
566 /** The dispatch stage. */
567 typename CPUPolicy::Rename rename;
569 /** The issue/execute/writeback stages. */
570 typename CPUPolicy::IEW iew;
572 /** The commit stage. */
573 typename CPUPolicy::Commit commit;
575 /** The register file. */
576 typename CPUPolicy::RegFile regFile;
578 /** The free list. */
579 typename CPUPolicy::FreeList freeList;
581 /** The rename map. */
582 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
584 /** The commit rename map. */
585 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
587 /** The re-order buffer. */
588 typename CPUPolicy::ROB rob;
590 /** Active Threads List */
591 std::list<unsigned> activeThreads;
593 /** Integer Register Scoreboard */
594 Scoreboard scoreboard;
597 /** Enum to give each stage a specific index, so when calling
598 * activateStage() or deactivateStage(), they can specify which stage
599 * is being activated/deactivated.
609 /** Typedefs from the Impl to get the structs that each of the
610 * time buffers should use.
612 typedef typename CPUPolicy::TimeStruct TimeStruct;
614 typedef typename CPUPolicy::FetchStruct FetchStruct;
616 typedef typename CPUPolicy::DecodeStruct DecodeStruct;
618 typedef typename CPUPolicy::RenameStruct RenameStruct;
620 typedef typename CPUPolicy::IEWStruct IEWStruct;
622 /** The main time buffer to do backwards communication. */
623 TimeBuffer<TimeStruct> timeBuffer;
625 /** The fetch stage's instruction queue. */
626 TimeBuffer<FetchStruct> fetchQueue;
628 /** The decode stage's instruction queue. */
629 TimeBuffer<DecodeStruct> decodeQueue;
631 /** The rename stage's instruction queue. */
632 TimeBuffer<RenameStruct> renameQueue;
634 /** The IEW stage's instruction queue. */
635 TimeBuffer<IEWStruct> iewQueue;
638 /** The activity recorder; used to tell if the CPU has any
639 * activity remaining or if it can go to idle and deschedule
642 ActivityRecorder activityRec;
645 /** Records that there was time buffer activity this cycle. */
646 void activityThisCycle() { activityRec.activity(); }
648 /** Changes a stage's status to active within the activity recorder. */
649 void activateStage(const StageIdx idx)
650 { activityRec.activateStage(idx); }
652 /** Changes a stage's status to inactive within the activity recorder. */
653 void deactivateStage(const StageIdx idx)
654 { activityRec.deactivateStage(idx); }
656 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
659 /** Gets a free thread id. Use if thread ids change across system. */
663 /** Returns a pointer to a thread context. */
664 ThreadContext *tcBase(unsigned tid)
666 return thread[tid]->getTC();
669 /** The global sequence number counter. */
670 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
673 /** Pointer to the checker, which can dynamically verify
674 * instruction results at run time. This can be set to NULL if it
677 Checker<DynInstPtr> *checker;
681 /** Pointer to the system. */
684 /** Pointer to physical memory. */
685 PhysicalMemory *physmem;
688 /** Event to call process() on once draining has completed. */
691 /** Counter of how many stages have completed draining. */
694 /** Pointers to all of the threads in the CPU. */
695 std::vector<Thread *> thread;
697 /** Whether or not the CPU should defer its registration. */
698 bool deferRegistration;
700 /** Is there a context switch pending? */
703 /** Threads Scheduled to Enter CPU */
704 std::list<int> cpuWaitList;
706 /** The cycle that the CPU was last running, used for statistics. */
707 Tick lastRunningCycle;
709 /** The cycle that the CPU was last activated by a new thread*/
710 Tick lastActivatedCycle;
712 /** Number of Threads CPU can process */
715 /** Mapping for system thread id to cpu id */
716 std::map<unsigned,unsigned> threadMap;
718 /** Available thread ids in the cpu*/
719 std::vector<unsigned> tids;
721 /** Stat for total number of times the CPU is descheduled. */
722 Stats::Scalar<> timesIdled;
723 /** Stat for total number of cycles the CPU spends descheduled. */
724 Stats::Scalar<> idleCycles;
725 /** Stat for the number of committed instructions per thread. */
726 Stats::Vector<> committedInsts;
727 /** Stat for the total number of committed instructions. */
728 Stats::Scalar<> totalCommittedInsts;
729 /** Stat for the CPI per thread. */
731 /** Stat for the total CPI. */
732 Stats::Formula totalCpi;
733 /** Stat for the IPC per thread. */
735 /** Stat for the total IPC. */
736 Stats::Formula totalIpc;
739 #endif // __CPU_O3_CPU_HH__