2 * Copyright (c) 2007 MIPS Technologies, Inc.
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.
28 * Authors: Korey Sewell
32 #ifndef __CPU_INORDER_CPU_HH__
33 #define __CPU_INORDER_CPU_HH__
41 #include "arch/isa_traits.hh"
42 #include "base/statistics.hh"
43 #include "base/timebuf.hh"
44 #include "config/full_system.hh"
45 #include "cpu/activity.hh"
46 #include "cpu/base.hh"
47 #include "cpu/simple_thread.hh"
48 #include "cpu/inorder/inorder_dyn_inst.hh"
49 #include "cpu/inorder/pipeline_traits.hh"
50 #include "cpu/inorder/pipeline_stage.hh"
51 #include "cpu/inorder/thread_state.hh"
52 #include "cpu/inorder/reg_dep_map.hh"
53 #include "cpu/o3/dep_graph.hh"
54 #include "cpu/o3/rename_map.hh"
55 #include "mem/packet.hh"
56 #include "mem/port.hh"
57 #include "mem/request.hh"
58 #include "sim/eventq.hh"
59 #include "sim/process.hh"
67 class InOrderCPU : public BaseCPU
71 typedef ThePipeline::Params Params;
72 typedef InOrderThreadState Thread;
75 typedef TheISA::IntReg IntReg;
76 typedef TheISA::FloatReg FloatReg;
77 typedef TheISA::FloatRegBits FloatRegBits;
78 typedef TheISA::MiscReg MiscReg;
79 typedef TheISA::RegFile RegFile;
80 typedef SimpleRenameMap RenameMap;
83 typedef ThePipeline::DynInstPtr DynInstPtr;
84 typedef std::list<DynInstPtr>::iterator ListIt;
87 typedef TimeBuffer<InterStageStruct> StageQueue;
89 friend class Resource;
92 /** Constructs a CPU with the given parameters. */
93 InOrderCPU(Params *params);
98 /** Type of core that this is */
101 int readCpuId() { return cpu_id; }
103 void setCpuId(int val) { cpu_id = val; }
119 /** Overall CPU status. */
123 /** Define TickEvent for the CPU */
124 class TickEvent : public Event
127 /** Pointer to the CPU. */
131 /** Constructs a tick event. */
132 TickEvent(InOrderCPU *c);
134 /** Processes a tick event, calling tick() on the CPU. */
137 /** Returns the description of the tick event. */
138 const char *description();
141 /** The tick event used for scheduling CPU ticks. */
144 /** Schedule tick event, regardless of its current state. */
145 void scheduleTickEvent(int delay)
147 if (tickEvent.squashed())
148 mainEventQueue.reschedule(&tickEvent, nextCycle(curTick + ticks(delay)));
149 else if (!tickEvent.scheduled())
150 mainEventQueue.schedule(&tickEvent, nextCycle(curTick + ticks(delay)));
153 /** Unschedule tick event, regardless of its current state. */
154 void unscheduleTickEvent()
156 if (tickEvent.scheduled())
161 // List of Events That can be scheduled from
163 // NOTE(1): The Resource Pool also uses this event list
164 // to schedule events broadcast to all resources interfaces
165 // NOTE(2): CPU Events usually need to schedule a corresponding resource
182 /** Define CPU Event */
183 class CPUEvent : public Event
189 CPUEventType cpuEventType;
195 /** Constructs a CPU event. */
196 CPUEvent(InOrderCPU *_cpu, CPUEventType e_type, Fault fault,
197 unsigned _tid, unsigned _vpe);
199 /** Set Type of Event To Be Scheduled */
200 void setEvent(CPUEventType e_type, Fault _fault, unsigned _tid, unsigned _vpe)
203 cpuEventType = e_type;
208 /** Processes a resource event. */
209 virtual void process();
211 /** Returns the description of the resource event. */
212 const char *description();
214 /** Schedule Event */
215 void scheduleEvent(int delay);
217 /** Unschedule This Event */
218 void unscheduleEvent();
221 /** Schedule a CPU Event */
222 void scheduleCpuEvent(CPUEventType cpu_event, Fault fault, unsigned tid,
223 unsigned vpe, unsigned delay = 0);
226 /** Interface between the CPU and CPU resources. */
227 ResourcePool *resPool;
229 /** Instruction used to signify that there is no *real* instruction in buffer slot */
230 DynInstPtr dummyBufferInst;
232 /** Used by resources to signify a denied access to a resource. */
233 ResourceRequest *dummyReq;
235 /** Identifies the resource id that identifies a fetch
238 unsigned fetchPortIdx;
240 /** Identifies the resource id that identifies a data
243 unsigned dataPortIdx;
245 /** The Pipeline Stages for the CPU */
246 PipelineStage *pipelineStage[ThePipeline::NumStages];
248 TheISA::IntReg PC[ThePipeline::MaxThreads];
249 TheISA::IntReg nextPC[ThePipeline::MaxThreads];
250 TheISA::IntReg nextNPC[ThePipeline::MaxThreads];
252 /** The Register File for the CPU */
253 /** @TODO: This regFile wont be a sufficient solution for out-of-order, add register
254 * files as a resource in order to handle ths problem
256 TheISA::IntRegFile intRegFile[ThePipeline::MaxThreads];;
257 TheISA::FloatRegFile floatRegFile[ThePipeline::MaxThreads];;
258 TheISA::MiscRegFile miscRegFile;
260 /** Dependency Tracker for Integer & Floating Point Regs */
261 RegDepMap archRegDepMap[ThePipeline::MaxThreads];
263 /** Global communication structure */
264 TimeBuffer<TimeStruct> timeBuffer;
266 /** Communication structure that sits in between pipeline stages */
267 StageQueue *stageQueue[ThePipeline::NumStages-1];
271 /** Registers statistics. */
274 /** Ticks CPU, calling tick() on each stage, and checking the overall
275 * activity to see if the CPU should deschedule itself.
279 /** Initialize the CPU */
282 /** Reset State in the CPU */
285 /** Get a Memory Port */
286 Port* getPort(const std::string &if_name, int idx = 0);
288 /** trap() - sets up a trap event on the cpuTraps to handle given fault.
289 * trapCPU() - Traps to handle given fault
291 void trap(Fault fault, unsigned tid, int delay = 0);
292 void trapCPU(Fault fault, unsigned tid);
294 /** Setup CPU to insert a thread's context */
295 void insertThread(unsigned tid);
297 /** Remove all of a thread's context from CPU */
298 void removeThread(unsigned tid);
300 /** Add Thread to Active Threads List. */
301 void activateContext(unsigned tid, int delay = 0);
302 void activateThread(unsigned tid);
304 /** Remove Thread from Active Threads List */
305 void suspendContext(unsigned tid, int delay = 0);
306 void suspendThread(unsigned tid);
308 /** Remove Thread from Active Threads List &&
309 * Remove Thread Context from CPU.
311 void deallocateContext(unsigned tid, int delay = 0);
312 void deallocateThread(unsigned tid);
313 void deactivateThread(unsigned tid);
318 hack_once("return a bogus context id");
322 /** Remove Thread from Active Threads List &&
323 * Remove Thread Context from CPU.
325 void haltContext(unsigned tid, int delay = 0);
327 void removePipelineStalls(unsigned tid);
329 void squashThreadInPipeline(unsigned tid);
331 /// Notify the CPU to enable a virtual processor element.
332 virtual void enableVirtProcElement(unsigned vpe);
333 void enableVPEs(unsigned vpe);
335 /// Notify the CPU to disable a virtual processor element.
336 virtual void disableVirtProcElement(unsigned tid, unsigned vpe);
337 void disableVPEs(unsigned tid, unsigned vpe);
339 /// Notify the CPU that multithreading is enabled.
340 virtual void enableMultiThreading(unsigned vpe);
341 void enableThreads(unsigned vpe);
343 /// Notify the CPU that multithreading is disabled.
344 virtual void disableMultiThreading(unsigned tid, unsigned vpe);
345 void disableThreads(unsigned tid, unsigned vpe);
347 // Sets a thread-rescheduling condition.
348 void setThreadRescheduleCondition(uint32_t tid)
350 //@TODO: IMPLEMENT ME
353 /** Activate a Thread When CPU Resources are Available. */
354 void activateWhenReady(int tid);
356 /** Add or Remove a Thread Context in the CPU. */
357 void doContextSwitch();
359 /** Update The Order In Which We Process Threads. */
360 void updateThreadPriority();
362 /** Switches a Pipeline Stage to Active. (Unused currently) */
363 void switchToActive(int stage_idx)
364 { /*pipelineStage[stage_idx]->switchToActive();*/ }
366 /** Switches out this CPU. (Unused currently) */
367 //void switchOut(Sampler *sampler);
369 /** Signals to this CPU that a stage has completed switching out. (Unused currently)*/
370 void signalSwitched();
372 /** Takes over from another CPU. (Unused currently)*/
373 void takeOverFrom(BaseCPU *oldCPU);
375 /** Get the current instruction sequence number, and increment it. */
376 InstSeqNum getAndIncrementInstSeq(unsigned tid)
377 { return globalSeqNum[tid]++; }
379 /** Get the current instruction sequence number, and increment it. */
380 InstSeqNum nextInstSeqNum(unsigned tid)
381 { return globalSeqNum[tid]; }
383 /** Increment Instruction Sequence Number */
384 void incrInstSeqNum(unsigned tid)
385 { globalSeqNum[tid]++; }
387 /** Set Instruction Sequence Number */
388 void setInstSeqNum(unsigned tid, InstSeqNum seq_num)
390 globalSeqNum[tid] = seq_num;
393 InstSeqNum getNextEventNum()
395 return cpuEventNum++;
398 /** Get instruction asid. */
399 int getInstAsid(unsigned tid)
400 { return thread[tid]->getInstAsid(); }
402 /** Get data asid. */
403 int getDataAsid(unsigned tid)
404 { return thread[tid]->getDataAsid(); }
406 /** Register file accessors */
407 uint64_t readIntReg(int reg_idx, unsigned tid);
409 FloatReg readFloatReg(int reg_idx, unsigned tid,
410 int width = TheISA::SingleWidth);
412 FloatRegBits readFloatRegBits(int reg_idx, unsigned tid,
413 int width = TheISA::SingleWidth);
415 void setIntReg(int reg_idx, uint64_t val, unsigned tid);
417 void setFloatReg(int reg_idx, FloatReg val, unsigned tid,
418 int width = TheISA::SingleWidth);
420 void setFloatRegBits(int reg_idx, FloatRegBits val, unsigned tid,
421 int width = TheISA::SingleWidth);
423 /** Reads a miscellaneous register. */
424 MiscReg readMiscRegNoEffect(int misc_reg, unsigned tid = 0);
426 /** Reads a misc. register, including any side effects the read
427 * might have as defined by the architecture.
429 MiscReg readMiscReg(int misc_reg, unsigned tid = 0);
431 /** Sets a miscellaneous register. */
432 void setMiscRegNoEffect(int misc_reg, const MiscReg &val, unsigned tid = 0);
434 /** Sets a misc. register, including any side effects the write
435 * might have as defined by the architecture.
437 void setMiscReg(int misc_reg, const MiscReg &val, unsigned tid = 0);
439 /** Reads a int/fp/misc reg. from another thread depending on ISA-defined
442 uint64_t readRegOtherThread(unsigned misc_reg, unsigned tid = -1);
444 /** Sets a int/fp/misc reg. from another thread depending on an ISA-defined
447 void setRegOtherThread(unsigned misc_reg, const MiscReg &val, unsigned tid);
449 /** Reads the commit PC of a specific thread. */
450 uint64_t readPC(unsigned tid);
452 /** Sets the commit PC of a specific thread. */
453 void setPC(Addr new_PC, unsigned tid);
455 /** Reads the next PC of a specific thread. */
456 uint64_t readNextPC(unsigned tid);
458 /** Sets the next PC of a specific thread. */
459 void setNextPC(uint64_t val, unsigned tid);
461 /** Reads the next NPC of a specific thread. */
462 uint64_t readNextNPC(unsigned tid);
464 /** Sets the next NPC of a specific thread. */
465 void setNextNPC(uint64_t val, unsigned tid);
467 /** Add Destination Register To Dependency Maps */
468 //void addToRegDepMap(DynInstPtr &inst);
470 /** Function to add instruction onto the head of the list of the
471 * instructions. Used when new instructions are fetched.
473 ListIt addInst(DynInstPtr &inst);
475 /** Function to tell the CPU that an instruction has completed. */
476 void instDone(DynInstPtr inst, unsigned tid);
478 /** Add Instructions to the CPU Remove List*/
479 void addToRemoveList(DynInstPtr &inst);
481 /** Remove an instruction from CPU */
482 void removeInst(DynInstPtr &inst);
484 /** Remove all instructions younger than the given sequence number. */
485 void removeInstsUntil(const InstSeqNum &seq_num,unsigned tid);
487 /** Removes the instruction pointed to by the iterator. */
488 inline void squashInstIt(const ListIt &instIt, const unsigned &tid);
490 /** Cleans up all instructions on the instruction remove list. */
491 void cleanUpRemovedInsts();
493 /** Cleans up all instructions on the request remove list. */
494 void cleanUpRemovedReqs();
496 /** Cleans up all instructions on the CPU event remove list. */
497 void cleanUpRemovedEvents();
499 /** Debug function to print all instructions on the list. */
502 /** Translates instruction requestion in syscall emulation mode. */
503 Fault translateInstReq(RequestPtr &req, Thread *thread)
505 return thread->getProcessPtr()->pTable->translate(req);
508 /** Translates data read request in syscall emulation mode. */
509 Fault translateDataReadReq(RequestPtr &req, Thread *thread)
511 return thread->getProcessPtr()->pTable->translate(req);
514 /** Translates data write request in syscall emulation mode. */
515 Fault translateDataWriteReq(RequestPtr &req, Thread *thread)
517 return thread->getProcessPtr()->pTable->translate(req);
520 /** Forwards an instruction read to the appropriate data
521 * resource (indexes into Resource Pool thru "dataPortIdx")
523 Fault read(DynInstPtr inst);
525 /** Forwards an instruction write. to the appropriate data
526 * resource (indexes into Resource Pool thru "dataPortIdx")
528 Fault write(DynInstPtr inst);
530 /** Executes a syscall.*/
531 void syscall(int64_t callnum, int tid);
533 /** Gets a syscall argument. */
534 IntReg getSyscallArg(int i, int tid);
536 /** Used to shift args for indirect syscall. */
537 void setSyscallArg(int i, IntReg val, int tid);
539 /** Sets the return value of a syscall. */
540 void setSyscallReturn(SyscallReturn return_value, int tid);
543 /** Per-Thread List of all the instructions in flight. */
544 std::list<DynInstPtr> instList[ThePipeline::MaxThreads];
546 /** List of all the instructions that will be removed at the end of this
549 std::queue<ListIt> removeList;
551 /** List of all the resource requests that will be removed at the end of this
554 std::queue<ResourceRequest*> reqRemoveList;
556 /** List of all the cpu event requests that will be removed at the end of
559 std::queue<Event*> cpuEventRemoveList;
562 /** Debug structure to keep track of the sequence numbers still in
565 std::set<InstSeqNum> snList;
568 /** Records if instructions need to be removed this cycle due to
569 * being retired or squashed.
571 bool removeInstsThisCycle;
573 /** True if there is non-speculative Inst Active In Pipeline. Lets any
574 * execution unit know, NOT to execute while the instruction is active.
576 bool nonSpecInstActive[ThePipeline::MaxThreads];
578 /** Instruction Seq. Num of current non-speculative instruction. */
579 InstSeqNum nonSpecSeqNum[ThePipeline::MaxThreads];
581 /** Instruction Seq. Num of last instruction squashed in pipeline */
582 InstSeqNum squashSeqNum[ThePipeline::MaxThreads];
584 /** Last Cycle that the CPU squashed instruction end. */
585 Tick lastSquashCycle[ThePipeline::MaxThreads];
587 std::list<unsigned> fetchPriorityList;
589 /** Rename Map for architectural-to-physical register mappings.
590 * In a In-order processor, the mapping is fixed
591 * (e.g. Thread 1: 0-31, Thread 1: 32-63, etc.)
592 * In a Out-of-Order processor, this is used to maintain
593 * sequential consistency (?right word here?).
595 RenameMap renameMap[ThePipeline::MaxThreads];
598 /** Active Threads List */
599 std::list<unsigned> activeThreads;
601 /** Current Threads List */
602 std::list<unsigned> currentThreads;
604 /** Suspended Threads List */
605 std::list<unsigned> suspendedThreads;
607 /** Thread Status Functions (Unused Currently) */
608 bool isThreadInCPU(unsigned tid);
609 bool isThreadActive(unsigned tid);
610 bool isThreadSuspended(unsigned tid);
611 void addToCurrentThreads(unsigned tid);
612 void removeFromCurrentThreads(unsigned tid);
615 /** The activity recorder; used to tell if the CPU has any
616 * activity remaining or if it can go to idle and deschedule
619 ActivityRecorder activityRec;
622 void readFunctional(Addr addr, uint32_t &buffer);
624 /** Number of Active Threads in the CPU */
625 int numActiveThreads() { return activeThreads.size(); }
627 /** Records that there was time buffer activity this cycle. */
628 void activityThisCycle() { activityRec.activity(); }
630 /** Changes a stage's status to active within the activity recorder. */
631 void activateStage(const int idx)
632 { activityRec.activateStage(idx); }
634 /** Changes a stage's status to inactive within the activity recorder. */
635 void deactivateStage(const int idx)
636 { activityRec.deactivateStage(idx); }
638 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
641 /** Gets a free thread id. Use if thread ids change across system. */
644 // LL/SC debug functionality
645 unsigned stCondFails;
646 unsigned readStCondFailures() { return stCondFails; }
647 unsigned setStCondFailures(unsigned st_fails) { return stCondFails = st_fails; }
650 /** Returns a pointer to a thread context. */
651 ThreadContext *tcBase(unsigned tid = 0)
653 return thread[tid]->getTC();
656 /** The global sequence number counter. */
657 InstSeqNum globalSeqNum[ThePipeline::MaxThreads];
659 /** The global event number counter. */
660 InstSeqNum cpuEventNum;
662 /** Counter of how many stages have completed switching out. */
665 /** Pointers to all of the threads in the CPU. */
666 std::vector<Thread *> thread;
668 /** Pointer to the icache interface. */
669 MemInterface *icacheInterface;
670 /** Pointer to the dcache interface. */
671 MemInterface *dcacheInterface;
673 /** Whether or not the CPU should defer its registration. */
674 bool deferRegistration;
676 /** Per-Stage Instruction Tracing */
679 /** Is there a context switch pending? */
682 /** Threads Scheduled to Enter CPU */
683 std::list<int> cpuWaitList;
685 /** The cycle that the CPU was last running, used for statistics. */
686 Tick lastRunningCycle;
688 /** Number of Threads the CPU can process */
691 /** Number of Virtual Processors the CPU can process */
692 unsigned numVirtProcs;
694 /** Update Thread , used for statistic purposes*/
695 inline void tickThreadStats();
697 /** Per-Thread Tick */
698 Stats::Vector<> threadCycles;
701 Stats::Scalar<> smtCycles;
703 /** Stat for total number of times the CPU is descheduled. */
704 Stats::Scalar<> timesIdled;
706 /** Stat for total number of cycles the CPU spends descheduled. */
707 Stats::Scalar<> idleCycles;
709 /** Stat for the number of committed instructions per thread. */
710 Stats::Vector<> committedInsts;
712 /** Stat for the number of committed instructions per thread. */
713 Stats::Vector<> smtCommittedInsts;
715 /** Stat for the total number of committed instructions. */
716 Stats::Scalar<> totalCommittedInsts;
718 /** Stat for the CPI per thread. */
721 /** Stat for the SMT-CPI per thread. */
722 Stats::Formula smtCpi;
724 /** Stat for the total CPI. */
725 Stats::Formula totalCpi;
727 /** Stat for the IPC per thread. */
730 /** Stat for the total IPC. */
731 Stats::Formula smtIpc;
733 /** Stat for the total IPC. */
734 Stats::Formula totalIpc;
737 #endif // __CPU_O3_CPU_HH__