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);
101 ThreadID asid[ThePipeline::MaxThreads];
103 /** Type of core that this is */
104 std::string coreType;
106 // Only need for SE MODE
113 ThreadModel threadModel;
115 int readCpuId() { return cpu_id; }
117 void setCpuId(int val) { cpu_id = val; }
130 /** Overall CPU status. */
133 /** Define TickEvent for the CPU */
134 class TickEvent : public Event
137 /** Pointer to the CPU. */
141 /** Constructs a tick event. */
142 TickEvent(InOrderCPU *c);
144 /** Processes a tick event, calling tick() on the CPU. */
147 /** Returns the description of the tick event. */
148 const char *description();
151 /** The tick event used for scheduling CPU ticks. */
154 /** Schedule tick event, regardless of its current state. */
155 void scheduleTickEvent(int delay)
157 if (tickEvent.squashed())
158 mainEventQueue.reschedule(&tickEvent,
159 nextCycle(curTick + ticks(delay)));
160 else if (!tickEvent.scheduled())
161 mainEventQueue.schedule(&tickEvent,
162 nextCycle(curTick + ticks(delay)));
165 /** Unschedule tick event, regardless of its current state. */
166 void unscheduleTickEvent()
168 if (tickEvent.scheduled())
173 // List of Events That can be scheduled from
175 // NOTE(1): The Resource Pool also uses this event list
176 // to schedule events broadcast to all resources interfaces
177 // NOTE(2): CPU Events usually need to schedule a corresponding resource
181 ActivateNextReadyThread,
192 static std::string eventNames[NumCPUEvents];
194 /** Define CPU Event */
195 class CPUEvent : public Event
201 CPUEventType cpuEventType;
208 /** Constructs a CPU event. */
209 CPUEvent(InOrderCPU *_cpu, CPUEventType e_type, Fault fault,
210 ThreadID _tid, DynInstPtr inst, unsigned event_pri_offset);
212 /** Set Type of Event To Be Scheduled */
213 void setEvent(CPUEventType e_type, Fault _fault, ThreadID _tid,
217 cpuEventType = e_type;
223 /** Processes a resource event. */
224 virtual void process();
226 /** Returns the description of the resource event. */
227 const char *description();
229 /** Schedule Event */
230 void scheduleEvent(int delay);
232 /** Unschedule This Event */
233 void unscheduleEvent();
236 /** Schedule a CPU Event */
237 void scheduleCpuEvent(CPUEventType cpu_event, Fault fault, ThreadID tid,
238 DynInstPtr inst, unsigned delay = 0,
239 unsigned event_pri_offset = 0);
242 /** Interface between the CPU and CPU resources. */
243 ResourcePool *resPool;
245 /** Instruction used to signify that there is no *real* instruction in
247 DynInstPtr dummyInst[ThePipeline::MaxThreads];
249 /** Used by resources to signify a denied access to a resource. */
250 ResourceRequest *dummyReq[ThePipeline::MaxThreads];
252 /** Identifies the resource id that identifies a fetch
255 unsigned fetchPortIdx;
257 /** Identifies the resource id that identifies a ITB */
260 /** Identifies the resource id that identifies a data
263 unsigned dataPortIdx;
265 /** Identifies the resource id that identifies a DTB */
268 /** The Pipeline Stages for the CPU */
269 PipelineStage *pipelineStage[ThePipeline::NumStages];
271 /** Program Counters */
272 TheISA::IntReg PC[ThePipeline::MaxThreads];
273 TheISA::IntReg nextPC[ThePipeline::MaxThreads];
274 TheISA::IntReg nextNPC[ThePipeline::MaxThreads];
276 /** The Register File for the CPU */
278 FloatReg f[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
279 FloatRegBits i[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
281 TheISA::IntReg intRegs[ThePipeline::MaxThreads][TheISA::NumIntRegs];
284 TheISA::ISA isa[ThePipeline::MaxThreads];
286 /** Dependency Tracker for Integer & Floating Point Regs */
287 RegDepMap archRegDepMap[ThePipeline::MaxThreads];
289 /** Global communication structure */
290 TimeBuffer<TimeStruct> timeBuffer;
292 /** Communication structure that sits in between pipeline stages */
293 StageQueue *stageQueue[ThePipeline::NumStages-1];
295 TheISA::TLB *getITBPtr();
296 TheISA::TLB *getDTBPtr();
300 /** Registers statistics. */
303 /** Ticks CPU, calling tick() on each stage, and checking the overall
304 * activity to see if the CPU should deschedule itself.
308 /** Initialize the CPU */
311 /** Reset State in the CPU */
314 /** Get a Memory Port */
315 Port* getPort(const std::string &if_name, int idx = 0);
318 /** HW return from error interrupt. */
319 Fault hwrei(ThreadID tid);
321 bool simPalCheck(int palFunc, ThreadID tid);
323 /** Returns the Fault for any valid interrupt. */
324 Fault getInterrupts();
326 /** Processes any an interrupt fault. */
327 void processInterrupts(Fault interrupt);
329 /** Halts the CPU. */
330 void halt() { panic("Halt not implemented!\n"); }
332 /** Update the Virt and Phys ports of all ThreadContexts to
333 * reflect change in memory connections. */
334 void updateMemPorts();
336 /** Check if this address is a valid instruction address. */
337 bool validInstAddr(Addr addr) { return true; }
339 /** Check if this address is a valid data address. */
340 bool validDataAddr(Addr addr) { return true; }
343 /** trap() - sets up a trap event on the cpuTraps to handle given fault.
344 * trapCPU() - Traps to handle given fault
346 void trap(Fault fault, ThreadID tid, int delay = 0);
347 void trapCPU(Fault fault, ThreadID tid);
349 /** Add Thread to Active Threads List. */
350 void activateContext(ThreadID tid, int delay = 0);
351 void activateThread(ThreadID tid);
352 void activateThreadInPipeline(ThreadID tid);
354 /** Add Thread to Active Threads List. */
355 void activateNextReadyContext(int delay = 0);
356 void activateNextReadyThread();
358 /** Remove from Active Thread List */
359 void deactivateContext(ThreadID tid, int delay = 0);
360 void deactivateThread(ThreadID tid);
362 /** Suspend Thread, Remove from Active Threads List, Add to Suspend List */
363 void suspendContext(ThreadID tid, int delay = 0);
364 void suspendThread(ThreadID tid);
366 /** Halt Thread, Remove from Active Thread List, Place Thread on Halted
369 void haltContext(ThreadID tid, int delay = 0);
370 void haltThread(ThreadID tid);
372 /** squashFromMemStall() - sets up a squash event
373 * squashDueToMemStall() - squashes pipeline
374 * @note: maybe squashContext/squashThread would be better?
376 void squashFromMemStall(DynInstPtr inst, ThreadID tid, int delay = 0);
377 void squashDueToMemStall(int stage_num, InstSeqNum seq_num, ThreadID tid);
379 void removePipelineStalls(ThreadID tid);
380 void squashThreadInPipeline(ThreadID tid);
381 void squashBehindMemStall(int stage_num, InstSeqNum seq_num, ThreadID tid);
383 PipelineStage* getPipeStage(int stage_num);
388 hack_once("return a bogus context id");
392 /** Update The Order In Which We Process Threads. */
393 void updateThreadPriority();
395 /** Switches a Pipeline Stage to Active. (Unused currently) */
396 void switchToActive(int stage_idx)
397 { /*pipelineStage[stage_idx]->switchToActive();*/ }
399 /** Get the current instruction sequence number, and increment it. */
400 InstSeqNum getAndIncrementInstSeq(ThreadID tid)
401 { return globalSeqNum[tid]++; }
403 /** Get the current instruction sequence number, and increment it. */
404 InstSeqNum nextInstSeqNum(ThreadID tid)
405 { return globalSeqNum[tid]; }
407 /** Increment Instruction Sequence Number */
408 void incrInstSeqNum(ThreadID tid)
409 { globalSeqNum[tid]++; }
411 /** Set Instruction Sequence Number */
412 void setInstSeqNum(ThreadID tid, InstSeqNum seq_num)
414 globalSeqNum[tid] = seq_num;
417 /** Get & Update Next Event Number */
418 InstSeqNum getNextEventNum()
421 return cpuEventNum++;
427 /** Register file accessors */
428 uint64_t readIntReg(int reg_idx, ThreadID tid);
430 FloatReg readFloatReg(int reg_idx, ThreadID tid);
432 FloatRegBits readFloatRegBits(int reg_idx, ThreadID tid);
434 void setIntReg(int reg_idx, uint64_t val, ThreadID tid);
436 void setFloatReg(int reg_idx, FloatReg val, ThreadID tid);
438 void setFloatRegBits(int reg_idx, FloatRegBits val, ThreadID tid);
440 /** Reads a miscellaneous register. */
441 MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid = 0);
443 /** Reads a misc. register, including any side effects the read
444 * might have as defined by the architecture.
446 MiscReg readMiscReg(int misc_reg, ThreadID tid = 0);
448 /** Sets a miscellaneous register. */
449 void setMiscRegNoEffect(int misc_reg, const MiscReg &val,
452 /** Sets a misc. register, including any side effects the write
453 * might have as defined by the architecture.
455 void setMiscReg(int misc_reg, const MiscReg &val, ThreadID tid = 0);
457 /** Reads a int/fp/misc reg. from another thread depending on ISA-defined
460 uint64_t readRegOtherThread(unsigned misc_reg,
461 ThreadID tid = InvalidThreadID);
463 /** Sets a int/fp/misc reg. from another thread depending on an ISA-defined
466 void setRegOtherThread(unsigned misc_reg, const MiscReg &val,
469 /** Reads the commit PC of a specific thread. */
470 uint64_t readPC(ThreadID tid);
472 /** Sets the commit PC of a specific thread. */
473 void setPC(Addr new_PC, ThreadID tid);
475 /** Reads the next PC of a specific thread. */
476 uint64_t readNextPC(ThreadID tid);
478 /** Sets the next PC of a specific thread. */
479 void setNextPC(uint64_t val, ThreadID tid);
481 /** Reads the next NPC of a specific thread. */
482 uint64_t readNextNPC(ThreadID tid);
484 /** Sets the next NPC of a specific thread. */
485 void setNextNPC(uint64_t val, ThreadID tid);
487 /** Function to add instruction onto the head of the list of the
488 * instructions. Used when new instructions are fetched.
490 ListIt addInst(DynInstPtr &inst);
492 /** Function to tell the CPU that an instruction has completed. */
493 void instDone(DynInstPtr inst, ThreadID tid);
495 /** Add Instructions to the CPU Remove List*/
496 void addToRemoveList(DynInstPtr &inst);
498 /** Remove an instruction from CPU */
499 void removeInst(DynInstPtr &inst);
501 /** Remove all instructions younger than the given sequence number. */
502 void removeInstsUntil(const InstSeqNum &seq_num,ThreadID tid);
504 /** Removes the instruction pointed to by the iterator. */
505 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
507 /** Cleans up all instructions on the instruction remove list. */
508 void cleanUpRemovedInsts();
510 /** Cleans up all instructions on the request remove list. */
511 void cleanUpRemovedReqs();
513 /** Cleans up all instructions on the CPU event remove list. */
514 void cleanUpRemovedEvents();
516 /** Debug function to print all instructions on the list. */
519 /** Forwards an instruction read to the appropriate data
520 * resource (indexes into Resource Pool thru "dataPortIdx")
523 Fault read(DynInstPtr inst, Addr addr, T &data, unsigned flags);
525 /** Forwards an instruction write. to the appropriate data
526 * resource (indexes into Resource Pool thru "dataPortIdx")
529 Fault write(DynInstPtr inst, T data, Addr addr, unsigned flags,
530 uint64_t *write_res = NULL);
532 /** Forwards an instruction prefetch to the appropriate data
533 * resource (indexes into Resource Pool thru "dataPortIdx")
535 void prefetch(DynInstPtr inst);
537 /** Forwards an instruction writeHint to the appropriate data
538 * resource (indexes into Resource Pool thru "dataPortIdx")
540 void writeHint(DynInstPtr inst);
542 /** Executes a syscall.*/
543 void syscall(int64_t callnum, ThreadID tid);
546 /** Per-Thread List of all the instructions in flight. */
547 std::list<DynInstPtr> instList[ThePipeline::MaxThreads];
549 /** List of all the instructions that will be removed at the end of this
552 std::queue<ListIt> removeList;
554 /** List of all the resource requests that will be removed at the end
557 std::queue<ResourceRequest*> reqRemoveList;
559 /** List of all the cpu event requests that will be removed at the end of
562 std::queue<Event*> cpuEventRemoveList;
564 /** Records if instructions need to be removed this cycle due to
565 * being retired or squashed.
567 bool removeInstsThisCycle;
569 /** True if there is non-speculative Inst Active In Pipeline. Lets any
570 * execution unit know, NOT to execute while the instruction is active.
572 bool nonSpecInstActive[ThePipeline::MaxThreads];
574 /** Instruction Seq. Num of current non-speculative instruction. */
575 InstSeqNum nonSpecSeqNum[ThePipeline::MaxThreads];
577 /** Instruction Seq. Num of last instruction squashed in pipeline */
578 InstSeqNum squashSeqNum[ThePipeline::MaxThreads];
580 /** Last Cycle that the CPU squashed instruction end. */
581 Tick lastSquashCycle[ThePipeline::MaxThreads];
583 std::list<ThreadID> fetchPriorityList;
586 /** Active Threads List */
587 std::list<ThreadID> activeThreads;
589 /** Ready Threads List */
590 std::list<ThreadID> readyThreads;
592 /** Suspended Threads List */
593 std::list<ThreadID> suspendedThreads;
595 /** Halted Threads List */
596 std::list<ThreadID> haltedThreads;
598 /** Thread Status Functions */
599 bool isThreadActive(ThreadID tid);
600 bool isThreadReady(ThreadID tid);
601 bool isThreadSuspended(ThreadID tid);
604 /** The activity recorder; used to tell if the CPU has any
605 * activity remaining or if it can go to idle and deschedule
608 ActivityRecorder activityRec;
611 /** Number of Active Threads in the CPU */
612 ThreadID numActiveThreads() { return activeThreads.size(); }
614 /** Thread id of active thread
615 * Only used for SwitchOnCacheMiss model.
616 * Assumes only 1 thread active
618 ThreadID activeThreadId()
620 if (numActiveThreads() > 0)
621 return activeThreads.front();
623 return InvalidThreadID;
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. */
642 virtual void wakeup();
645 // LL/SC debug functionality
646 unsigned stCondFails;
648 unsigned readStCondFailures()
649 { return stCondFails; }
651 unsigned setStCondFailures(unsigned st_fails)
652 { return stCondFails = st_fails; }
654 /** Returns a pointer to a thread context. */
655 ThreadContext *tcBase(ThreadID tid = 0)
657 return thread[tid]->getTC();
660 /** Count the Total Instructions Committed in the CPU. */
661 virtual Counter totalInstructions() const
665 for (ThreadID tid = 0; tid < (ThreadID)thread.size(); tid++)
666 total += thread[tid]->numInst;
672 /** Pointer to the system. */
675 /** Pointer to physical memory. */
676 PhysicalMemory *physmem;
679 /** The global sequence number counter. */
680 InstSeqNum globalSeqNum[ThePipeline::MaxThreads];
683 /** The global event number counter. */
684 InstSeqNum cpuEventNum;
686 /** Number of resource requests active in CPU **/
687 unsigned resReqCount;
689 Stats::Scalar maxResReqCount;
692 /** Counter of how many stages have completed switching out. */
695 /** Pointers to all of the threads in the CPU. */
696 std::vector<Thread *> thread;
698 /** Pointer to the icache interface. */
699 MemInterface *icacheInterface;
701 /** Pointer to the dcache interface. */
702 MemInterface *dcacheInterface;
704 /** Whether or not the CPU should defer its registration. */
705 bool deferRegistration;
707 /** Per-Stage Instruction Tracing */
710 /** The cycle that the CPU was last running, used for statistics. */
711 Tick lastRunningCycle;
713 void updateContextSwitchStats();
714 unsigned instsPerSwitch;
715 Stats::Average instsPerCtxtSwitch;
716 Stats::Scalar numCtxtSwitches;
718 /** Update Thread , used for statistic purposes*/
719 inline void tickThreadStats();
721 /** Per-Thread Tick */
722 Stats::Vector threadCycles;
725 Stats::Scalar smtCycles;
727 /** Stat for total number of times the CPU is descheduled. */
728 Stats::Scalar timesIdled;
730 /** Stat for total number of cycles the CPU spends descheduled. */
731 Stats::Scalar idleCycles;
733 /** Stat for the number of committed instructions per thread. */
734 Stats::Vector committedInsts;
736 /** Stat for the number of committed instructions per thread. */
737 Stats::Vector smtCommittedInsts;
739 /** Stat for the total number of committed instructions. */
740 Stats::Scalar totalCommittedInsts;
742 /** Stat for the CPI per thread. */
745 /** Stat for the SMT-CPI per thread. */
746 Stats::Formula smtCpi;
748 /** Stat for the total CPI. */
749 Stats::Formula totalCpi;
751 /** Stat for the IPC per thread. */
754 /** Stat for the total IPC. */
755 Stats::Formula smtIpc;
757 /** Stat for the total IPC. */
758 Stats::Formula totalIpc;
761 #endif // __CPU_O3_CPU_HH__