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/the_isa.hh"
46 #include "config/use_checker.hh"
47 #include "cpu/activity.hh"
48 #include "cpu/base.hh"
49 #include "cpu/simple_thread.hh"
50 #include "cpu/o3/comm.hh"
51 #include "cpu/o3/cpu_policy.hh"
52 #include "cpu/o3/scoreboard.hh"
53 #include "cpu/o3/thread_state.hh"
54 //#include "cpu/o3/thread_context.hh"
55 #include "sim/process.hh"
57 #include "params/DerivO3CPU.hh"
63 class O3ThreadContext;
71 class BaseO3CPU : public BaseCPU
73 //Stuff that's pretty ISA independent will go here.
75 BaseO3CPU(BaseCPUParams *params);
81 * FullO3CPU class, has each of the stages (fetch through commit)
82 * within it, as well as all of the time buffers between stages. The
83 * tick() function for the CPU is defined here.
86 class FullO3CPU : public BaseO3CPU
89 // Typedefs from the Impl here.
90 typedef typename Impl::CPUPol CPUPolicy;
91 typedef typename Impl::DynInstPtr DynInstPtr;
92 typedef typename Impl::O3CPU O3CPU;
94 typedef O3ThreadState<Impl> ImplState;
95 typedef O3ThreadState<Impl> Thread;
97 typedef typename std::list<DynInstPtr>::iterator ListIt;
99 friend class O3ThreadContext<Impl>;
113 /** Overall CPU status. */
116 /** Per-thread status in CPU, used for SMT. */
117 Status _threadStatus[Impl::MaxThreads];
120 class TickEvent : public Event
123 /** Pointer to the CPU. */
124 FullO3CPU<Impl> *cpu;
127 /** Constructs a tick event. */
128 TickEvent(FullO3CPU<Impl> *c);
130 /** Processes a tick event, calling tick() on the CPU. */
132 /** Returns the description of the tick event. */
133 const char *description() const;
136 /** The tick event used for scheduling CPU ticks. */
139 /** Schedule tick event, regardless of its current state. */
140 void scheduleTickEvent(int delay)
142 if (tickEvent.squashed())
143 reschedule(tickEvent, nextCycle(curTick + ticks(delay)));
144 else if (!tickEvent.scheduled())
145 schedule(tickEvent, nextCycle(curTick + ticks(delay)));
148 /** Unschedule tick event, regardless of its current state. */
149 void unscheduleTickEvent()
151 if (tickEvent.scheduled())
155 class ActivateThreadEvent : public Event
158 /** Number of Thread to Activate */
161 /** Pointer to the CPU. */
162 FullO3CPU<Impl> *cpu;
165 /** Constructs the event. */
166 ActivateThreadEvent();
168 /** Initialize Event */
169 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
171 /** Processes the event, calling activateThread() on the CPU. */
174 /** Returns the description of the event. */
175 const char *description() const;
178 /** Schedule thread to activate , regardless of its current state. */
180 scheduleActivateThreadEvent(ThreadID tid, int delay)
182 // Schedule thread to activate, regardless of its current state.
183 if (activateThreadEvent[tid].squashed())
184 reschedule(activateThreadEvent[tid],
185 nextCycle(curTick + ticks(delay)));
186 else if (!activateThreadEvent[tid].scheduled())
187 schedule(activateThreadEvent[tid],
188 nextCycle(curTick + ticks(delay)));
191 /** Unschedule actiavte thread event, regardless of its current state. */
193 unscheduleActivateThreadEvent(ThreadID tid)
195 if (activateThreadEvent[tid].scheduled())
196 activateThreadEvent[tid].squash();
199 /** The tick event used for scheduling CPU ticks. */
200 ActivateThreadEvent activateThreadEvent[Impl::MaxThreads];
202 class DeallocateContextEvent : public Event
205 /** Number of Thread to deactivate */
208 /** Should the thread be removed from the CPU? */
211 /** Pointer to the CPU. */
212 FullO3CPU<Impl> *cpu;
215 /** Constructs the event. */
216 DeallocateContextEvent();
218 /** Initialize Event */
219 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
221 /** Processes the event, calling activateThread() on the CPU. */
224 /** Sets whether the thread should also be removed from the CPU. */
225 void setRemove(bool _remove) { remove = _remove; }
227 /** Returns the description of the event. */
228 const char *description() const;
231 /** Schedule cpu to deallocate thread context.*/
233 scheduleDeallocateContextEvent(ThreadID tid, bool remove, int delay)
235 // Schedule thread to activate, regardless of its current state.
236 if (deallocateContextEvent[tid].squashed())
237 reschedule(deallocateContextEvent[tid],
238 nextCycle(curTick + ticks(delay)));
239 else if (!deallocateContextEvent[tid].scheduled())
240 schedule(deallocateContextEvent[tid],
241 nextCycle(curTick + ticks(delay)));
244 /** Unschedule thread deallocation in CPU */
246 unscheduleDeallocateContextEvent(ThreadID tid)
248 if (deallocateContextEvent[tid].scheduled())
249 deallocateContextEvent[tid].squash();
252 /** The tick event used for scheduling CPU ticks. */
253 DeallocateContextEvent deallocateContextEvent[Impl::MaxThreads];
256 /** Constructs a CPU with the given parameters. */
257 FullO3CPU(DerivO3CPUParams *params);
261 /** Registers statistics. */
264 void demapPage(Addr vaddr, uint64_t asn)
266 this->itb->demapPage(vaddr, asn);
267 this->dtb->demapPage(vaddr, asn);
270 void demapInstPage(Addr vaddr, uint64_t asn)
272 this->itb->demapPage(vaddr, asn);
275 void demapDataPage(Addr vaddr, uint64_t asn)
277 this->dtb->demapPage(vaddr, asn);
280 /** Returns a specific port. */
281 Port *getPort(const std::string &if_name, int idx);
283 /** Ticks CPU, calling tick() on each stage, and checking the overall
284 * activity to see if the CPU should deschedule itself.
288 /** Initialize the CPU */
291 /** Returns the Number of Active Threads in the CPU */
292 int numActiveThreads()
293 { return activeThreads.size(); }
295 /** Add Thread to Active Threads List */
296 void activateThread(ThreadID tid);
298 /** Remove Thread from Active Threads List */
299 void deactivateThread(ThreadID tid);
301 /** Setup CPU to insert a thread's context */
302 void insertThread(ThreadID tid);
304 /** Remove all of a thread's context from CPU */
305 void removeThread(ThreadID tid);
307 /** Count the Total Instructions Committed in the CPU. */
308 virtual Counter totalInstructions() const;
310 /** Add Thread to Active Threads List. */
311 void activateContext(ThreadID tid, int delay);
313 /** Remove Thread from Active Threads List */
314 void suspendContext(ThreadID tid);
316 /** Remove Thread from Active Threads List &&
317 * Possibly Remove Thread Context from CPU.
319 bool deallocateContext(ThreadID tid, bool remove, int delay = 1);
321 /** Remove Thread from Active Threads List &&
322 * Remove Thread Context from CPU.
324 void haltContext(ThreadID tid);
326 /** Activate a Thread When CPU Resources are Available. */
327 void activateWhenReady(ThreadID tid);
329 /** Add or Remove a Thread Context in the CPU. */
330 void doContextSwitch();
332 /** Update The Order In Which We Process Threads. */
333 void updateThreadPriority();
335 /** Serialize state. */
336 virtual void serialize(std::ostream &os);
338 /** Unserialize from a checkpoint. */
339 virtual void unserialize(Checkpoint *cp, const std::string §ion);
343 /** Executes a syscall.
344 * @todo: Determine if this needs to be virtual.
346 void syscall(int64_t callnum, ThreadID tid);
349 /** Starts draining the CPU's pipeline of all instructions in
350 * order to stop all memory accesses. */
351 virtual unsigned int drain(Event *drain_event);
353 /** Resumes execution after a drain. */
354 virtual void resume();
356 /** Signals to this CPU that a stage has completed switching out. */
357 void signalDrained();
359 /** Switches out this CPU. */
360 virtual void switchOut();
362 /** Takes over from another CPU. */
363 virtual void takeOverFrom(BaseCPU *oldCPU);
365 /** Get the current instruction sequence number, and increment it. */
366 InstSeqNum getAndIncrementInstSeq()
367 { return globalSeqNum++; }
369 /** Traps to handle given fault. */
370 void trap(Fault fault, ThreadID tid);
373 /** HW return from error interrupt. */
374 Fault hwrei(ThreadID tid);
376 bool simPalCheck(int palFunc, ThreadID tid);
378 /** Returns the Fault for any valid interrupt. */
379 Fault getInterrupts();
381 /** Processes any an interrupt fault. */
382 void processInterrupts(Fault interrupt);
384 /** Halts the CPU. */
385 void halt() { panic("Halt not implemented!\n"); }
387 /** Update the Virt and Phys ports of all ThreadContexts to
388 * reflect change in memory connections. */
389 void updateMemPorts();
391 /** Check if this address is a valid instruction address. */
392 bool validInstAddr(Addr addr) { return true; }
394 /** Check if this address is a valid data address. */
395 bool validDataAddr(Addr addr) { return true; }
398 /** Register accessors. Index refers to the physical register index. */
400 /** Reads a miscellaneous register. */
401 TheISA::MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid);
403 /** Reads a misc. register, including any side effects the read
404 * might have as defined by the architecture.
406 TheISA::MiscReg readMiscReg(int misc_reg, ThreadID tid);
408 /** Sets a miscellaneous register. */
409 void setMiscRegNoEffect(int misc_reg, const TheISA::MiscReg &val,
412 /** Sets a misc. register, including any side effects the write
413 * might have as defined by the architecture.
415 void setMiscReg(int misc_reg, const TheISA::MiscReg &val,
418 uint64_t readIntReg(int reg_idx);
420 TheISA::FloatReg readFloatReg(int reg_idx);
422 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
424 void setIntReg(int reg_idx, uint64_t val);
426 void setFloatReg(int reg_idx, TheISA::FloatReg val);
428 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
430 uint64_t readArchIntReg(int reg_idx, ThreadID tid);
432 float readArchFloatReg(int reg_idx, ThreadID tid);
434 uint64_t readArchFloatRegInt(int reg_idx, ThreadID tid);
436 /** Architectural register accessors. Looks up in the commit
437 * rename table to obtain the true physical index of the
438 * architected register first, then accesses that physical
441 void setArchIntReg(int reg_idx, uint64_t val, ThreadID tid);
443 void setArchFloatReg(int reg_idx, float val, ThreadID tid);
445 void setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid);
447 /** Reads the commit PC of a specific thread. */
448 Addr readPC(ThreadID tid);
450 /** Sets the commit PC of a specific thread. */
451 void setPC(Addr new_PC, ThreadID tid);
453 /** Reads the commit micro PC of a specific thread. */
454 Addr readMicroPC(ThreadID tid);
456 /** Sets the commmit micro PC of a specific thread. */
457 void setMicroPC(Addr new_microPC, ThreadID tid);
459 /** Reads the next PC of a specific thread. */
460 Addr readNextPC(ThreadID tid);
462 /** Sets the next PC of a specific thread. */
463 void setNextPC(Addr val, ThreadID tid);
465 /** Reads the next NPC of a specific thread. */
466 Addr readNextNPC(ThreadID tid);
468 /** Sets the next NPC of a specific thread. */
469 void setNextNPC(Addr val, ThreadID tid);
471 /** Reads the commit next micro PC of a specific thread. */
472 Addr readNextMicroPC(ThreadID tid);
474 /** Sets the commit next micro PC of a specific thread. */
475 void setNextMicroPC(Addr val, ThreadID tid);
477 /** Initiates a squash of all in-flight instructions for a given
478 * thread. The source of the squash is an external update of
479 * state through the TC.
481 void squashFromTC(ThreadID tid);
483 /** Function to add instruction onto the head of the list of the
484 * instructions. Used when new instructions are fetched.
486 ListIt addInst(DynInstPtr &inst);
488 /** Function to tell the CPU that an instruction has completed. */
489 void instDone(ThreadID tid);
491 /** Add Instructions to the CPU Remove List*/
492 void addToRemoveList(DynInstPtr &inst);
494 /** Remove an instruction from the front end of the list. There's
495 * no restriction on location of the instruction.
497 void removeFrontInst(DynInstPtr &inst);
499 /** Remove all instructions that are not currently in the ROB.
500 * There's also an option to not squash delay slot instructions.*/
501 void removeInstsNotInROB(ThreadID tid);
503 /** Remove all instructions younger than the given sequence number. */
504 void removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid);
506 /** Removes the instruction pointed to by the iterator. */
507 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
509 /** Cleans up all instructions on the remove list. */
510 void cleanUpRemovedInsts();
512 /** Debug function to print all instructions on the list. */
517 /** Count of total number of dynamic instructions in flight. */
521 /** List of all the instructions in flight. */
522 std::list<DynInstPtr> instList;
524 /** List of all the instructions that will be removed at the end of this
527 std::queue<ListIt> removeList;
530 /** Debug structure to keep track of the sequence numbers still in
533 std::set<InstSeqNum> snList;
536 /** Records if instructions need to be removed this cycle due to
537 * being retired or squashed.
539 bool removeInstsThisCycle;
542 /** The fetch stage. */
543 typename CPUPolicy::Fetch fetch;
545 /** The decode stage. */
546 typename CPUPolicy::Decode decode;
548 /** The dispatch stage. */
549 typename CPUPolicy::Rename rename;
551 /** The issue/execute/writeback stages. */
552 typename CPUPolicy::IEW iew;
554 /** The commit stage. */
555 typename CPUPolicy::Commit commit;
557 /** The register file. */
558 typename CPUPolicy::RegFile regFile;
560 /** The free list. */
561 typename CPUPolicy::FreeList freeList;
563 /** The rename map. */
564 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
566 /** The commit rename map. */
567 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
569 /** The re-order buffer. */
570 typename CPUPolicy::ROB rob;
572 /** Active Threads List */
573 std::list<ThreadID> activeThreads;
575 /** Integer Register Scoreboard */
576 Scoreboard scoreboard;
578 TheISA::ISA isa[Impl::MaxThreads];
581 /** Enum to give each stage a specific index, so when calling
582 * activateStage() or deactivateStage(), they can specify which stage
583 * is being activated/deactivated.
593 /** Typedefs from the Impl to get the structs that each of the
594 * time buffers should use.
596 typedef typename CPUPolicy::TimeStruct TimeStruct;
598 typedef typename CPUPolicy::FetchStruct FetchStruct;
600 typedef typename CPUPolicy::DecodeStruct DecodeStruct;
602 typedef typename CPUPolicy::RenameStruct RenameStruct;
604 typedef typename CPUPolicy::IEWStruct IEWStruct;
606 /** The main time buffer to do backwards communication. */
607 TimeBuffer<TimeStruct> timeBuffer;
609 /** The fetch stage's instruction queue. */
610 TimeBuffer<FetchStruct> fetchQueue;
612 /** The decode stage's instruction queue. */
613 TimeBuffer<DecodeStruct> decodeQueue;
615 /** The rename stage's instruction queue. */
616 TimeBuffer<RenameStruct> renameQueue;
618 /** The IEW stage's instruction queue. */
619 TimeBuffer<IEWStruct> iewQueue;
622 /** The activity recorder; used to tell if the CPU has any
623 * activity remaining or if it can go to idle and deschedule
626 ActivityRecorder activityRec;
629 /** Records that there was time buffer activity this cycle. */
630 void activityThisCycle() { activityRec.activity(); }
632 /** Changes a stage's status to active within the activity recorder. */
633 void activateStage(const StageIdx idx)
634 { activityRec.activateStage(idx); }
636 /** Changes a stage's status to inactive within the activity recorder. */
637 void deactivateStage(const StageIdx idx)
638 { activityRec.deactivateStage(idx); }
640 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
644 virtual void wakeup();
647 /** Gets a free thread id. Use if thread ids change across system. */
648 ThreadID getFreeTid();
651 /** Returns a pointer to a thread context. */
655 return thread[tid]->getTC();
658 /** The global sequence number counter. */
659 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
662 /** Pointer to the checker, which can dynamically verify
663 * instruction results at run time. This can be set to NULL if it
666 Checker<DynInstPtr> *checker;
670 /** Pointer to the system. */
674 /** Event to call process() on once draining has completed. */
677 /** Counter of how many stages have completed draining. */
680 /** Pointers to all of the threads in the CPU. */
681 std::vector<Thread *> thread;
683 /** Whether or not the CPU should defer its registration. */
684 bool deferRegistration;
686 /** Is there a context switch pending? */
689 /** Threads Scheduled to Enter CPU */
690 std::list<int> cpuWaitList;
692 /** The cycle that the CPU was last running, used for statistics. */
693 Tick lastRunningCycle;
695 /** The cycle that the CPU was last activated by a new thread*/
696 Tick lastActivatedCycle;
698 /** Mapping for system thread id to cpu id */
699 std::map<ThreadID, unsigned> threadMap;
701 /** Available thread ids in the cpu*/
702 std::vector<ThreadID> tids;
704 /** CPU read function, forwards read to LSQ. */
705 Fault read(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
706 uint8_t *data, int load_idx)
708 return this->iew.ldstQueue.read(req, sreqLow, sreqHigh,
712 /** CPU write function, forwards write to LSQ. */
713 Fault write(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
714 uint8_t *data, int store_idx)
716 return this->iew.ldstQueue.write(req, sreqLow, sreqHigh,
720 /** Get the dcache port (used to find block size for translations). */
721 Port *getDcachePort() { return this->iew.ldstQueue.getDcachePort(); }
725 /** Temporary fix for the lock flag, works in the UP case. */
728 /** Stat for total number of times the CPU is descheduled. */
729 Stats::Scalar timesIdled;
730 /** Stat for total number of cycles the CPU spends descheduled. */
731 Stats::Scalar idleCycles;
732 /** Stat for the number of committed instructions per thread. */
733 Stats::Vector committedInsts;
734 /** Stat for the total number of committed instructions. */
735 Stats::Scalar totalCommittedInsts;
736 /** Stat for the CPI per thread. */
738 /** Stat for the total CPI. */
739 Stats::Formula totalCpi;
740 /** Stat for the IPC per thread. */
742 /** Stat for the total IPC. */
743 Stats::Formula totalIpc;
746 #endif // __CPU_O3_CPU_HH__