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 "arch/types.hh"
43 #include "arch/registers.hh"
44 #include "base/statistics.hh"
45 #include "base/timebuf.hh"
46 #include "base/types.hh"
47 #include "config/full_system.hh"
48 #include "config/the_isa.hh"
49 #include "cpu/activity.hh"
50 #include "cpu/base.hh"
51 #include "cpu/simple_thread.hh"
52 #include "cpu/inorder/inorder_dyn_inst.hh"
53 #include "cpu/inorder/pipeline_traits.hh"
54 #include "cpu/inorder/pipeline_stage.hh"
55 #include "cpu/inorder/thread_state.hh"
56 #include "cpu/inorder/reg_dep_map.hh"
57 #include "cpu/o3/dep_graph.hh"
58 #include "cpu/o3/rename_map.hh"
59 #include "mem/packet.hh"
60 #include "mem/port.hh"
61 #include "mem/request.hh"
62 #include "sim/eventq.hh"
63 #include "sim/process.hh"
71 class InOrderCPU : public BaseCPU
75 typedef ThePipeline::Params Params;
76 typedef InOrderThreadState Thread;
79 typedef TheISA::IntReg IntReg;
80 typedef TheISA::FloatReg FloatReg;
81 typedef TheISA::FloatRegBits FloatRegBits;
82 typedef TheISA::MiscReg MiscReg;
85 typedef ThePipeline::DynInstPtr DynInstPtr;
86 typedef std::list<DynInstPtr>::iterator ListIt;
89 typedef TimeBuffer<InterStageStruct> StageQueue;
91 friend class Resource;
94 /** Constructs a CPU with the given parameters. */
95 InOrderCPU(Params *params);
103 ThreadID asid[ThePipeline::MaxThreads];
105 /** Type of core that this is */
106 std::string coreType;
108 // Only need for SE MODE
115 ThreadModel threadModel;
117 int readCpuId() { return cpu_id; }
119 void setCpuId(int val) { cpu_id = val; }
132 /** Overall CPU status. */
135 /** Define TickEvent for the CPU */
136 class TickEvent : public Event
139 /** Pointer to the CPU. */
143 /** Constructs a tick event. */
144 TickEvent(InOrderCPU *c);
146 /** Processes a tick event, calling tick() on the CPU. */
149 /** Returns the description of the tick event. */
150 const char *description();
153 /** The tick event used for scheduling CPU ticks. */
156 /** Schedule tick event, regardless of its current state. */
157 void scheduleTickEvent(int delay)
159 if (tickEvent.squashed())
160 mainEventQueue.reschedule(&tickEvent,
161 nextCycle(curTick + ticks(delay)));
162 else if (!tickEvent.scheduled())
163 mainEventQueue.schedule(&tickEvent,
164 nextCycle(curTick + ticks(delay)));
167 /** Unschedule tick event, regardless of its current state. */
168 void unscheduleTickEvent()
170 if (tickEvent.scheduled())
175 // List of Events That can be scheduled from
177 // NOTE(1): The Resource Pool also uses this event list
178 // to schedule events broadcast to all resources interfaces
179 // NOTE(2): CPU Events usually need to schedule a corresponding resource
183 ActivateNextReadyThread,
194 static std::string eventNames[NumCPUEvents];
196 /** Define CPU Event */
197 class CPUEvent : public Event
203 CPUEventType cpuEventType;
210 /** Constructs a CPU event. */
211 CPUEvent(InOrderCPU *_cpu, CPUEventType e_type, Fault fault,
212 ThreadID _tid, DynInstPtr inst, unsigned event_pri_offset);
214 /** Set Type of Event To Be Scheduled */
215 void setEvent(CPUEventType e_type, Fault _fault, ThreadID _tid,
219 cpuEventType = e_type;
225 /** Processes a CPU event. */
228 /** Returns the description of the CPU event. */
229 const char *description();
231 /** Schedule Event */
232 void scheduleEvent(int delay);
234 /** Unschedule This Event */
235 void unscheduleEvent();
238 /** Schedule a CPU Event */
239 void scheduleCpuEvent(CPUEventType cpu_event, Fault fault, ThreadID tid,
240 DynInstPtr inst, unsigned delay = 0,
241 unsigned event_pri_offset = 0);
244 /** Interface between the CPU and CPU resources. */
245 ResourcePool *resPool;
247 /** Instruction used to signify that there is no *real* instruction in
249 DynInstPtr dummyInst[ThePipeline::MaxThreads];
250 DynInstPtr dummyBufferInst;
251 DynInstPtr dummyReqInst;
253 /** Used by resources to signify a denied access to a resource. */
254 ResourceRequest *dummyReq[ThePipeline::MaxThreads];
256 /** Identifies the resource id that identifies a fetch
259 unsigned fetchPortIdx;
261 /** Identifies the resource id that identifies a ITB */
264 /** Identifies the resource id that identifies a data
267 unsigned dataPortIdx;
269 /** Identifies the resource id that identifies a DTB */
272 /** The Pipeline Stages for the CPU */
273 PipelineStage *pipelineStage[ThePipeline::NumStages];
275 /** Program Counters */
276 TheISA::IntReg PC[ThePipeline::MaxThreads];
277 TheISA::IntReg nextPC[ThePipeline::MaxThreads];
278 TheISA::IntReg nextNPC[ThePipeline::MaxThreads];
280 /** The Register File for the CPU */
282 FloatReg f[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
283 FloatRegBits i[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
285 TheISA::IntReg intRegs[ThePipeline::MaxThreads][TheISA::NumIntRegs];
288 TheISA::ISA isa[ThePipeline::MaxThreads];
290 /** Dependency Tracker for Integer & Floating Point Regs */
291 RegDepMap archRegDepMap[ThePipeline::MaxThreads];
293 /** Global communication structure */
294 TimeBuffer<TimeStruct> timeBuffer;
296 /** Communication structure that sits in between pipeline stages */
297 StageQueue *stageQueue[ThePipeline::NumStages-1];
299 TheISA::TLB *getITBPtr();
300 TheISA::TLB *getDTBPtr();
304 /** Registers statistics. */
307 /** Ticks CPU, calling tick() on each stage, and checking the overall
308 * activity to see if the CPU should deschedule itself.
312 /** Initialize the CPU */
315 /** Reset State in the CPU */
318 /** Get a Memory Port */
319 Port* getPort(const std::string &if_name, int idx = 0);
322 /** HW return from error interrupt. */
323 Fault hwrei(ThreadID tid);
325 bool simPalCheck(int palFunc, ThreadID tid);
327 /** Returns the Fault for any valid interrupt. */
328 Fault getInterrupts();
330 /** Processes any an interrupt fault. */
331 void processInterrupts(Fault interrupt);
333 /** Halts the CPU. */
334 void halt() { panic("Halt not implemented!\n"); }
336 /** Update the Virt and Phys ports of all ThreadContexts to
337 * reflect change in memory connections. */
338 void updateMemPorts();
340 /** Check if this address is a valid instruction address. */
341 bool validInstAddr(Addr addr) { return true; }
343 /** Check if this address is a valid data address. */
344 bool validDataAddr(Addr addr) { return true; }
347 /** trap() - sets up a trap event on the cpuTraps to handle given fault.
348 * trapCPU() - Traps to handle given fault
350 void trap(Fault fault, ThreadID tid, int delay = 0);
351 void trapCPU(Fault fault, ThreadID tid);
353 /** Add Thread to Active Threads List. */
354 void activateContext(ThreadID tid, int delay = 0);
355 void activateThread(ThreadID tid);
356 void activateThreadInPipeline(ThreadID tid);
358 /** Add Thread to Active Threads List. */
359 void activateNextReadyContext(int delay = 0);
360 void activateNextReadyThread();
362 /** Remove from Active Thread List */
363 void deactivateContext(ThreadID tid, int delay = 0);
364 void deactivateThread(ThreadID tid);
366 /** Suspend Thread, Remove from Active Threads List, Add to Suspend List */
367 void suspendContext(ThreadID tid, int delay = 0);
368 void suspendThread(ThreadID tid);
370 /** Halt Thread, Remove from Active Thread List, Place Thread on Halted
373 void haltContext(ThreadID tid, int delay = 0);
374 void haltThread(ThreadID tid);
376 /** squashFromMemStall() - sets up a squash event
377 * squashDueToMemStall() - squashes pipeline
378 * @note: maybe squashContext/squashThread would be better?
380 void squashFromMemStall(DynInstPtr inst, ThreadID tid, int delay = 0);
381 void squashDueToMemStall(int stage_num, InstSeqNum seq_num, ThreadID tid);
383 void removePipelineStalls(ThreadID tid);
384 void squashThreadInPipeline(ThreadID tid);
385 void squashBehindMemStall(int stage_num, InstSeqNum seq_num, ThreadID tid);
387 PipelineStage* getPipeStage(int stage_num);
392 hack_once("return a bogus context id");
396 /** Update The Order In Which We Process Threads. */
397 void updateThreadPriority();
399 /** Switches a Pipeline Stage to Active. (Unused currently) */
400 void switchToActive(int stage_idx)
401 { /*pipelineStage[stage_idx]->switchToActive();*/ }
403 /** Get the current instruction sequence number, and increment it. */
404 InstSeqNum getAndIncrementInstSeq(ThreadID tid)
405 { return globalSeqNum[tid]++; }
407 /** Get the current instruction sequence number, and increment it. */
408 InstSeqNum nextInstSeqNum(ThreadID tid)
409 { return globalSeqNum[tid]; }
411 /** Increment Instruction Sequence Number */
412 void incrInstSeqNum(ThreadID tid)
413 { globalSeqNum[tid]++; }
415 /** Set Instruction Sequence Number */
416 void setInstSeqNum(ThreadID tid, InstSeqNum seq_num)
418 globalSeqNum[tid] = seq_num;
421 /** Get & Update Next Event Number */
422 InstSeqNum getNextEventNum()
425 return cpuEventNum++;
431 /** Register file accessors */
432 uint64_t readIntReg(int reg_idx, ThreadID tid);
434 FloatReg readFloatReg(int reg_idx, ThreadID tid);
436 FloatRegBits readFloatRegBits(int reg_idx, ThreadID tid);
438 void setIntReg(int reg_idx, uint64_t val, ThreadID tid);
440 void setFloatReg(int reg_idx, FloatReg val, ThreadID tid);
442 void setFloatRegBits(int reg_idx, FloatRegBits val, ThreadID tid);
444 /** Reads a miscellaneous register. */
445 MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid = 0);
447 /** Reads a misc. register, including any side effects the read
448 * might have as defined by the architecture.
450 MiscReg readMiscReg(int misc_reg, ThreadID tid = 0);
452 /** Sets a miscellaneous register. */
453 void setMiscRegNoEffect(int misc_reg, const MiscReg &val,
456 /** Sets a misc. register, including any side effects the write
457 * might have as defined by the architecture.
459 void setMiscReg(int misc_reg, const MiscReg &val, ThreadID tid = 0);
461 /** Reads a int/fp/misc reg. from another thread depending on ISA-defined
464 uint64_t readRegOtherThread(unsigned misc_reg,
465 ThreadID tid = InvalidThreadID);
467 /** Sets a int/fp/misc reg. from another thread depending on an ISA-defined
470 void setRegOtherThread(unsigned misc_reg, const MiscReg &val,
473 /** Reads the commit PC of a specific thread. */
474 uint64_t readPC(ThreadID tid);
476 /** Sets the commit PC of a specific thread. */
477 void setPC(Addr new_PC, ThreadID tid);
479 /** Reads the next PC of a specific thread. */
480 uint64_t readNextPC(ThreadID tid);
482 /** Sets the next PC of a specific thread. */
483 void setNextPC(uint64_t val, ThreadID tid);
485 /** Reads the next NPC of a specific thread. */
486 uint64_t readNextNPC(ThreadID tid);
488 /** Sets the next NPC of a specific thread. */
489 void setNextNPC(uint64_t val, ThreadID tid);
491 /** Function to add instruction onto the head of the list of the
492 * instructions. Used when new instructions are fetched.
494 ListIt addInst(DynInstPtr &inst);
496 /** Function to tell the CPU that an instruction has completed. */
497 void instDone(DynInstPtr inst, ThreadID tid);
499 /** Add Instructions to the CPU Remove List*/
500 void addToRemoveList(DynInstPtr &inst);
502 /** Remove an instruction from CPU */
503 void removeInst(DynInstPtr &inst);
505 /** Remove all instructions younger than the given sequence number. */
506 void removeInstsUntil(const InstSeqNum &seq_num,ThreadID tid);
508 /** Removes the instruction pointed to by the iterator. */
509 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
511 /** Cleans up all instructions on the instruction remove list. */
512 void cleanUpRemovedInsts();
514 /** Cleans up all instructions on the request remove list. */
515 void cleanUpRemovedReqs();
517 /** Cleans up all instructions on the CPU event remove list. */
518 void cleanUpRemovedEvents();
520 /** Debug function to print all instructions on the list. */
523 /** Forwards an instruction read to the appropriate data
524 * resource (indexes into Resource Pool thru "dataPortIdx")
527 Fault read(DynInstPtr inst, Addr addr, T &data, unsigned flags);
529 /** Forwards an instruction write. to the appropriate data
530 * resource (indexes into Resource Pool thru "dataPortIdx")
533 Fault write(DynInstPtr inst, T data, Addr addr, unsigned flags,
534 uint64_t *write_res = NULL);
536 /** Forwards an instruction prefetch to the appropriate data
537 * resource (indexes into Resource Pool thru "dataPortIdx")
539 void prefetch(DynInstPtr inst);
541 /** Forwards an instruction writeHint to the appropriate data
542 * resource (indexes into Resource Pool thru "dataPortIdx")
544 void writeHint(DynInstPtr inst);
546 /** Executes a syscall.*/
547 void syscall(int64_t callnum, ThreadID tid);
550 /** Per-Thread List of all the instructions in flight. */
551 std::list<DynInstPtr> instList[ThePipeline::MaxThreads];
553 /** List of all the instructions that will be removed at the end of this
556 std::queue<ListIt> removeList;
558 /** List of all the resource requests that will be removed at the end
561 std::queue<ResourceRequest*> reqRemoveList;
563 /** List of all the cpu event requests that will be removed at the end of
566 std::queue<Event*> cpuEventRemoveList;
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<ThreadID> fetchPriorityList;
590 /** Active Threads List */
591 std::list<ThreadID> activeThreads;
593 /** Ready Threads List */
594 std::list<ThreadID> readyThreads;
596 /** Suspended Threads List */
597 std::list<ThreadID> suspendedThreads;
599 /** Halted Threads List */
600 std::list<ThreadID> haltedThreads;
602 /** Thread Status Functions */
603 bool isThreadActive(ThreadID tid);
604 bool isThreadReady(ThreadID tid);
605 bool isThreadSuspended(ThreadID tid);
608 /** The activity recorder; used to tell if the CPU has any
609 * activity remaining or if it can go to idle and deschedule
612 ActivityRecorder activityRec;
615 /** Number of Active Threads in the CPU */
616 ThreadID numActiveThreads() { return activeThreads.size(); }
618 /** Thread id of active thread
619 * Only used for SwitchOnCacheMiss model.
620 * Assumes only 1 thread active
622 ThreadID activeThreadId()
624 if (numActiveThreads() > 0)
625 return activeThreads.front();
627 return InvalidThreadID;
631 /** Records that there was time buffer activity this cycle. */
632 void activityThisCycle() { activityRec.activity(); }
634 /** Changes a stage's status to active within the activity recorder. */
635 void activateStage(const int idx)
636 { activityRec.activateStage(idx); }
638 /** Changes a stage's status to inactive within the activity recorder. */
639 void deactivateStage(const int idx)
640 { activityRec.deactivateStage(idx); }
642 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
646 virtual void wakeup();
649 // LL/SC debug functionality
650 unsigned stCondFails;
652 unsigned readStCondFailures()
653 { return stCondFails; }
655 unsigned setStCondFailures(unsigned st_fails)
656 { return stCondFails = st_fails; }
658 /** Returns a pointer to a thread context. */
659 ThreadContext *tcBase(ThreadID tid = 0)
661 return thread[tid]->getTC();
664 /** Count the Total Instructions Committed in the CPU. */
665 virtual Counter totalInstructions() const
669 for (ThreadID tid = 0; tid < (ThreadID)thread.size(); tid++)
670 total += thread[tid]->numInst;
676 /** Pointer to the system. */
679 /** Pointer to physical memory. */
680 PhysicalMemory *physmem;
683 /** The global sequence number counter. */
684 InstSeqNum globalSeqNum[ThePipeline::MaxThreads];
687 /** The global event number counter. */
688 InstSeqNum cpuEventNum;
690 /** Number of resource requests active in CPU **/
691 unsigned resReqCount;
694 /** Counter of how many stages have completed switching out. */
697 /** Pointers to all of the threads in the CPU. */
698 std::vector<Thread *> thread;
700 /** Pointer to the icache interface. */
701 MemInterface *icacheInterface;
703 /** Pointer to the dcache interface. */
704 MemInterface *dcacheInterface;
706 /** Whether or not the CPU should defer its registration. */
707 bool deferRegistration;
709 /** Per-Stage Instruction Tracing */
712 /** The cycle that the CPU was last running, used for statistics. */
713 Tick lastRunningCycle;
715 void updateContextSwitchStats();
716 unsigned instsPerSwitch;
717 Stats::Average instsPerCtxtSwitch;
718 Stats::Scalar numCtxtSwitches;
720 /** Update Thread , used for statistic purposes*/
721 inline void tickThreadStats();
723 /** Per-Thread Tick */
724 Stats::Vector threadCycles;
727 Stats::Scalar smtCycles;
729 /** Stat for total number of times the CPU is descheduled. */
730 Stats::Scalar timesIdled;
732 /** Stat for total number of cycles the CPU spends descheduled or no
735 Stats::Scalar idleCycles;
737 /** Stat for total number of cycles the CPU is active. */
738 Stats::Scalar runCycles;
740 /** Percentage of cycles a stage was active */
741 Stats::Formula activity;
743 /** Instruction Mix Stats */
744 Stats::Scalar comLoads;
745 Stats::Scalar comStores;
746 Stats::Scalar comBranches;
747 Stats::Scalar comNops;
748 Stats::Scalar comNonSpec;
749 Stats::Scalar comInts;
750 Stats::Scalar comFloats;
752 /** Stat for the number of committed instructions per thread. */
753 Stats::Vector committedInsts;
755 /** Stat for the number of committed instructions per thread. */
756 Stats::Vector smtCommittedInsts;
758 /** Stat for the total number of committed instructions. */
759 Stats::Scalar totalCommittedInsts;
761 /** Stat for the CPI per thread. */
764 /** Stat for the SMT-CPI per thread. */
765 Stats::Formula smtCpi;
767 /** Stat for the total CPI. */
768 Stats::Formula totalCpi;
770 /** Stat for the IPC per thread. */
773 /** Stat for the total IPC. */
774 Stats::Formula smtIpc;
776 /** Stat for the total IPC. */
777 Stats::Formula totalIpc;
780 #endif // __CPU_O3_CPU_HH__