2 * Copyright (c) 2004-2005 The Regents of The University of Michigan
3 * Copyright (c) 2011 Regents of the University of California
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met: redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer;
10 * redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution;
13 * neither the name of the copyright holders nor the names of its
14 * contributors may be used to endorse or promote products derived from
15 * this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #ifndef __CPU_O3_CPU_HH__
35 #define __CPU_O3_CPU_HH__
43 #include "arch/types.hh"
44 #include "base/statistics.hh"
45 #include "config/the_isa.hh"
46 #include "config/use_checker.hh"
47 #include "cpu/o3/comm.hh"
48 #include "cpu/o3/cpu_policy.hh"
49 #include "cpu/o3/scoreboard.hh"
50 #include "cpu/o3/thread_state.hh"
51 #include "cpu/activity.hh"
52 #include "cpu/base.hh"
53 #include "cpu/simple_thread.hh"
54 #include "cpu/timebuf.hh"
55 //#include "cpu/o3/thread_context.hh"
56 #include "params/DerivO3CPU.hh"
57 #include "sim/process.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 Tick when = nextCycle(curTick() + ticks(delay));
189 // Check if the deallocateEvent is also scheduled, and make
190 // sure they do not happen at same time causing a sleep that
191 // is never woken from.
192 if (deallocateContextEvent[tid].scheduled() &&
193 deallocateContextEvent[tid].when() == when) {
197 schedule(activateThreadEvent[tid], when);
201 /** Unschedule actiavte thread event, regardless of its current state. */
203 unscheduleActivateThreadEvent(ThreadID tid)
205 if (activateThreadEvent[tid].scheduled())
206 activateThreadEvent[tid].squash();
209 /** The tick event used for scheduling CPU ticks. */
210 ActivateThreadEvent activateThreadEvent[Impl::MaxThreads];
212 class DeallocateContextEvent : public Event
215 /** Number of Thread to deactivate */
218 /** Should the thread be removed from the CPU? */
221 /** Pointer to the CPU. */
222 FullO3CPU<Impl> *cpu;
225 /** Constructs the event. */
226 DeallocateContextEvent();
228 /** Initialize Event */
229 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
231 /** Processes the event, calling activateThread() on the CPU. */
234 /** Sets whether the thread should also be removed from the CPU. */
235 void setRemove(bool _remove) { remove = _remove; }
237 /** Returns the description of the event. */
238 const char *description() const;
241 /** Schedule cpu to deallocate thread context.*/
243 scheduleDeallocateContextEvent(ThreadID tid, bool remove, int delay)
245 // Schedule thread to activate, regardless of its current state.
246 if (deallocateContextEvent[tid].squashed())
247 reschedule(deallocateContextEvent[tid],
248 nextCycle(curTick() + ticks(delay)));
249 else if (!deallocateContextEvent[tid].scheduled())
250 schedule(deallocateContextEvent[tid],
251 nextCycle(curTick() + ticks(delay)));
254 /** Unschedule thread deallocation in CPU */
256 unscheduleDeallocateContextEvent(ThreadID tid)
258 if (deallocateContextEvent[tid].scheduled())
259 deallocateContextEvent[tid].squash();
262 /** The tick event used for scheduling CPU ticks. */
263 DeallocateContextEvent deallocateContextEvent[Impl::MaxThreads];
266 /** Constructs a CPU with the given parameters. */
267 FullO3CPU(DerivO3CPUParams *params);
271 /** Registers statistics. */
274 void demapPage(Addr vaddr, uint64_t asn)
276 this->itb->demapPage(vaddr, asn);
277 this->dtb->demapPage(vaddr, asn);
280 void demapInstPage(Addr vaddr, uint64_t asn)
282 this->itb->demapPage(vaddr, asn);
285 void demapDataPage(Addr vaddr, uint64_t asn)
287 this->dtb->demapPage(vaddr, asn);
290 /** Returns a specific port. */
291 Port *getPort(const std::string &if_name, int idx);
293 /** Ticks CPU, calling tick() on each stage, and checking the overall
294 * activity to see if the CPU should deschedule itself.
298 /** Initialize the CPU */
301 /** Returns the Number of Active Threads in the CPU */
302 int numActiveThreads()
303 { return activeThreads.size(); }
305 /** Add Thread to Active Threads List */
306 void activateThread(ThreadID tid);
308 /** Remove Thread from Active Threads List */
309 void deactivateThread(ThreadID tid);
311 /** Setup CPU to insert a thread's context */
312 void insertThread(ThreadID tid);
314 /** Remove all of a thread's context from CPU */
315 void removeThread(ThreadID tid);
317 /** Count the Total Instructions Committed in the CPU. */
318 virtual Counter totalInstructions() const;
320 /** Add Thread to Active Threads List. */
321 void activateContext(ThreadID tid, int delay);
323 /** Remove Thread from Active Threads List */
324 void suspendContext(ThreadID tid);
326 /** Remove Thread from Active Threads List &&
327 * Possibly Remove Thread Context from CPU.
329 bool deallocateContext(ThreadID tid, bool remove, int delay = 1);
331 /** Remove Thread from Active Threads List &&
332 * Remove Thread Context from CPU.
334 void haltContext(ThreadID tid);
336 /** Activate a Thread When CPU Resources are Available. */
337 void activateWhenReady(ThreadID tid);
339 /** Add or Remove a Thread Context in the CPU. */
340 void doContextSwitch();
342 /** Update The Order In Which We Process Threads. */
343 void updateThreadPriority();
345 /** Serialize state. */
346 virtual void serialize(std::ostream &os);
348 /** Unserialize from a checkpoint. */
349 virtual void unserialize(Checkpoint *cp, const std::string §ion);
352 /** Executes a syscall.
353 * @todo: Determine if this needs to be virtual.
355 void syscall(int64_t callnum, ThreadID tid);
357 /** Starts draining the CPU's pipeline of all instructions in
358 * order to stop all memory accesses. */
359 virtual unsigned int drain(Event *drain_event);
361 /** Resumes execution after a drain. */
362 virtual void resume();
364 /** Signals to this CPU that a stage has completed switching out. */
365 void signalDrained();
367 /** Switches out this CPU. */
368 virtual void switchOut();
370 /** Takes over from another CPU. */
371 virtual void takeOverFrom(BaseCPU *oldCPU);
373 /** Get the current instruction sequence number, and increment it. */
374 InstSeqNum getAndIncrementInstSeq()
375 { return globalSeqNum++; }
377 /** Traps to handle given fault. */
378 void trap(Fault fault, ThreadID tid, StaticInstPtr inst);
380 /** HW return from error interrupt. */
381 Fault hwrei(ThreadID tid);
383 bool simPalCheck(int palFunc, ThreadID tid);
385 /** Returns the Fault for any valid interrupt. */
386 Fault getInterrupts();
388 /** Processes any an interrupt fault. */
389 void processInterrupts(Fault interrupt);
391 /** Halts the CPU. */
392 void halt() { panic("Halt not implemented!\n"); }
394 /** Update the Virt and Phys ports of all ThreadContexts to
395 * reflect change in memory connections. */
396 void updateMemPorts();
398 /** Check if this address is a valid instruction address. */
399 bool validInstAddr(Addr addr) { return true; }
401 /** Check if this address is a valid data address. */
402 bool validDataAddr(Addr addr) { return true; }
404 /** Register accessors. Index refers to the physical register index. */
406 /** Reads a miscellaneous register. */
407 TheISA::MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid);
409 /** Reads a misc. register, including any side effects the read
410 * might have as defined by the architecture.
412 TheISA::MiscReg readMiscReg(int misc_reg, ThreadID tid);
414 /** Sets a miscellaneous register. */
415 void setMiscRegNoEffect(int misc_reg, const TheISA::MiscReg &val,
418 /** Sets a misc. register, including any side effects the write
419 * might have as defined by the architecture.
421 void setMiscReg(int misc_reg, const TheISA::MiscReg &val,
424 uint64_t readIntReg(int reg_idx);
426 TheISA::FloatReg readFloatReg(int reg_idx);
428 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
430 void setIntReg(int reg_idx, uint64_t val);
432 void setFloatReg(int reg_idx, TheISA::FloatReg val);
434 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
436 uint64_t readArchIntReg(int reg_idx, ThreadID tid);
438 float readArchFloatReg(int reg_idx, ThreadID tid);
440 uint64_t readArchFloatRegInt(int reg_idx, ThreadID tid);
442 /** Architectural register accessors. Looks up in the commit
443 * rename table to obtain the true physical index of the
444 * architected register first, then accesses that physical
447 void setArchIntReg(int reg_idx, uint64_t val, ThreadID tid);
449 void setArchFloatReg(int reg_idx, float val, ThreadID tid);
451 void setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid);
453 /** Sets the commit PC state of a specific thread. */
454 void pcState(const TheISA::PCState &newPCState, ThreadID tid);
456 /** Reads the commit PC state of a specific thread. */
457 TheISA::PCState pcState(ThreadID tid);
459 /** Reads the commit PC of a specific thread. */
460 Addr instAddr(ThreadID tid);
462 /** Reads the commit micro PC of a specific thread. */
463 MicroPC microPC(ThreadID tid);
465 /** Reads the next PC of a specific thread. */
466 Addr nextInstAddr(ThreadID tid);
468 /** Initiates a squash of all in-flight instructions for a given
469 * thread. The source of the squash is an external update of
470 * state through the TC.
472 void squashFromTC(ThreadID tid);
474 /** Function to add instruction onto the head of the list of the
475 * instructions. Used when new instructions are fetched.
477 ListIt addInst(DynInstPtr &inst);
479 /** Function to tell the CPU that an instruction has completed. */
480 void instDone(ThreadID tid);
482 /** Remove an instruction from the front end of the list. There's
483 * no restriction on location of the instruction.
485 void removeFrontInst(DynInstPtr &inst);
487 /** Remove all instructions that are not currently in the ROB.
488 * There's also an option to not squash delay slot instructions.*/
489 void removeInstsNotInROB(ThreadID tid);
491 /** Remove all instructions younger than the given sequence number. */
492 void removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid);
494 /** Removes the instruction pointed to by the iterator. */
495 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
497 /** Cleans up all instructions on the remove list. */
498 void cleanUpRemovedInsts();
500 /** Debug function to print all instructions on the list. */
505 /** Count of total number of dynamic instructions in flight. */
509 /** List of all the instructions in flight. */
510 std::list<DynInstPtr> instList;
512 /** List of all the instructions that will be removed at the end of this
515 std::queue<ListIt> removeList;
518 /** Debug structure to keep track of the sequence numbers still in
521 std::set<InstSeqNum> snList;
524 /** Records if instructions need to be removed this cycle due to
525 * being retired or squashed.
527 bool removeInstsThisCycle;
530 /** The fetch stage. */
531 typename CPUPolicy::Fetch fetch;
533 /** The decode stage. */
534 typename CPUPolicy::Decode decode;
536 /** The dispatch stage. */
537 typename CPUPolicy::Rename rename;
539 /** The issue/execute/writeback stages. */
540 typename CPUPolicy::IEW iew;
542 /** The commit stage. */
543 typename CPUPolicy::Commit commit;
545 /** The register file. */
546 typename CPUPolicy::RegFile regFile;
548 /** The free list. */
549 typename CPUPolicy::FreeList freeList;
551 /** The rename map. */
552 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
554 /** The commit rename map. */
555 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
557 /** The re-order buffer. */
558 typename CPUPolicy::ROB rob;
560 /** Active Threads List */
561 std::list<ThreadID> activeThreads;
563 /** Integer Register Scoreboard */
564 Scoreboard scoreboard;
566 TheISA::ISA isa[Impl::MaxThreads];
569 /** Enum to give each stage a specific index, so when calling
570 * activateStage() or deactivateStage(), they can specify which stage
571 * is being activated/deactivated.
581 /** Typedefs from the Impl to get the structs that each of the
582 * time buffers should use.
584 typedef typename CPUPolicy::TimeStruct TimeStruct;
586 typedef typename CPUPolicy::FetchStruct FetchStruct;
588 typedef typename CPUPolicy::DecodeStruct DecodeStruct;
590 typedef typename CPUPolicy::RenameStruct RenameStruct;
592 typedef typename CPUPolicy::IEWStruct IEWStruct;
594 /** The main time buffer to do backwards communication. */
595 TimeBuffer<TimeStruct> timeBuffer;
597 /** The fetch stage's instruction queue. */
598 TimeBuffer<FetchStruct> fetchQueue;
600 /** The decode stage's instruction queue. */
601 TimeBuffer<DecodeStruct> decodeQueue;
603 /** The rename stage's instruction queue. */
604 TimeBuffer<RenameStruct> renameQueue;
606 /** The IEW stage's instruction queue. */
607 TimeBuffer<IEWStruct> iewQueue;
610 /** The activity recorder; used to tell if the CPU has any
611 * activity remaining or if it can go to idle and deschedule
614 ActivityRecorder activityRec;
617 /** Records that there was time buffer activity this cycle. */
618 void activityThisCycle() { activityRec.activity(); }
620 /** Changes a stage's status to active within the activity recorder. */
621 void activateStage(const StageIdx idx)
622 { activityRec.activateStage(idx); }
624 /** Changes a stage's status to inactive within the activity recorder. */
625 void deactivateStage(const StageIdx idx)
626 { activityRec.deactivateStage(idx); }
628 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
631 virtual void wakeup();
633 /** Gets a free thread id. Use if thread ids change across system. */
634 ThreadID getFreeTid();
637 /** Returns a pointer to a thread context. */
641 return thread[tid]->getTC();
644 /** The global sequence number counter. */
645 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
648 /** Pointer to the checker, which can dynamically verify
649 * instruction results at run time. This can be set to NULL if it
652 Checker<DynInstPtr> *checker;
655 /** Pointer to the system. */
658 /** Event to call process() on once draining has completed. */
661 /** Counter of how many stages have completed draining. */
664 /** Pointers to all of the threads in the CPU. */
665 std::vector<Thread *> thread;
667 /** Whether or not the CPU should defer its registration. */
668 bool deferRegistration;
670 /** Is there a context switch pending? */
673 /** Threads Scheduled to Enter CPU */
674 std::list<int> cpuWaitList;
676 /** The cycle that the CPU was last running, used for statistics. */
677 Tick lastRunningCycle;
679 /** The cycle that the CPU was last activated by a new thread*/
680 Tick lastActivatedCycle;
682 /** Mapping for system thread id to cpu id */
683 std::map<ThreadID, unsigned> threadMap;
685 /** Available thread ids in the cpu*/
686 std::vector<ThreadID> tids;
688 /** CPU read function, forwards read to LSQ. */
689 Fault read(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
690 uint8_t *data, int load_idx)
692 return this->iew.ldstQueue.read(req, sreqLow, sreqHigh,
696 /** CPU write function, forwards write to LSQ. */
697 Fault write(RequestPtr &req, RequestPtr &sreqLow, RequestPtr &sreqHigh,
698 uint8_t *data, int store_idx)
700 return this->iew.ldstQueue.write(req, sreqLow, sreqHigh,
704 /** Get the dcache port (used to find block size for translations). */
705 Port *getDcachePort() { return this->iew.ldstQueue.getDcachePort(); }
709 /** Temporary fix for the lock flag, works in the UP case. */
712 /** Stat for total number of times the CPU is descheduled. */
713 Stats::Scalar timesIdled;
714 /** Stat for total number of cycles the CPU spends descheduled. */
715 Stats::Scalar idleCycles;
716 /** Stat for total number of cycles the CPU spends descheduled due to a
717 * quiesce operation or waiting for an interrupt. */
718 Stats::Scalar quiesceCycles;
719 /** Stat for the number of committed instructions per thread. */
720 Stats::Vector committedInsts;
721 /** Stat for the total number of committed instructions. */
722 Stats::Scalar totalCommittedInsts;
723 /** Stat for the CPI per thread. */
725 /** Stat for the total CPI. */
726 Stats::Formula totalCpi;
727 /** Stat for the IPC per thread. */
729 /** Stat for the total IPC. */
730 Stats::Formula totalIpc;
732 //number of integer register file accesses
733 Stats::Scalar intRegfileReads;
734 Stats::Scalar intRegfileWrites;
735 //number of float register file accesses
736 Stats::Scalar fpRegfileReads;
737 Stats::Scalar fpRegfileWrites;
739 Stats::Scalar miscRegfileReads;
740 Stats::Scalar miscRegfileWrites;
743 #endif // __CPU_O3_CPU_HH__