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 "base/statistics.hh"
44 #include "base/timebuf.hh"
45 #include "base/types.hh"
46 #include "config/full_system.hh"
47 #include "cpu/activity.hh"
48 #include "cpu/base.hh"
49 #include "cpu/simple_thread.hh"
50 #include "cpu/inorder/inorder_dyn_inst.hh"
51 #include "cpu/inorder/pipeline_traits.hh"
52 #include "cpu/inorder/pipeline_stage.hh"
53 #include "cpu/inorder/thread_state.hh"
54 #include "cpu/inorder/reg_dep_map.hh"
55 #include "cpu/o3/dep_graph.hh"
56 #include "cpu/o3/rename_map.hh"
57 #include "mem/packet.hh"
58 #include "mem/port.hh"
59 #include "mem/request.hh"
60 #include "sim/eventq.hh"
61 #include "sim/process.hh"
69 class InOrderCPU : public BaseCPU
73 typedef ThePipeline::Params Params;
74 typedef InOrderThreadState Thread;
77 typedef TheISA::IntReg IntReg;
78 typedef TheISA::FloatReg FloatReg;
79 typedef TheISA::FloatRegBits FloatRegBits;
80 typedef TheISA::RegFile RegFile;
81 typedef TheISA::MiscReg MiscReg;
84 typedef ThePipeline::DynInstPtr DynInstPtr;
85 typedef std::list<DynInstPtr>::iterator ListIt;
88 typedef TimeBuffer<InterStageStruct> StageQueue;
90 friend class Resource;
93 /** Constructs a CPU with the given parameters. */
94 InOrderCPU(Params *params);
99 /** Type of core that this is */
100 std::string coreType;
102 int readCpuId() { return cpu_id; }
104 void setCpuId(int val) { cpu_id = val; }
117 /** Overall CPU status. */
121 /** Define TickEvent for the CPU */
122 class TickEvent : public Event
125 /** Pointer to the CPU. */
129 /** Constructs a tick event. */
130 TickEvent(InOrderCPU *c);
132 /** Processes a tick event, calling tick() on the CPU. */
135 /** Returns the description of the tick event. */
136 const char *description();
139 /** The tick event used for scheduling CPU ticks. */
142 /** Schedule tick event, regardless of its current state. */
143 void scheduleTickEvent(int delay)
145 if (tickEvent.squashed())
146 mainEventQueue.reschedule(&tickEvent, nextCycle(curTick + ticks(delay)));
147 else if (!tickEvent.scheduled())
148 mainEventQueue.schedule(&tickEvent, nextCycle(curTick + ticks(delay)));
151 /** Unschedule tick event, regardless of its current state. */
152 void unscheduleTickEvent()
154 if (tickEvent.scheduled())
159 // List of Events That can be scheduled from
161 // NOTE(1): The Resource Pool also uses this event list
162 // to schedule events broadcast to all resources interfaces
163 // NOTE(2): CPU Events usually need to schedule a corresponding resource
180 static std::string eventNames[NumCPUEvents];
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 ThreadID _tid, unsigned _vpe);
199 /** Set Type of Event To Be Scheduled */
200 void setEvent(CPUEventType e_type, Fault _fault, ThreadID _tid,
204 cpuEventType = e_type;
209 /** Processes a resource event. */
210 virtual void process();
212 /** Returns the description of the resource event. */
213 const char *description();
215 /** Schedule Event */
216 void scheduleEvent(int delay);
218 /** Unschedule This Event */
219 void unscheduleEvent();
222 /** Schedule a CPU Event */
223 void scheduleCpuEvent(CPUEventType cpu_event, Fault fault, ThreadID tid,
224 unsigned vpe, unsigned delay = 0);
227 /** Interface between the CPU and CPU resources. */
228 ResourcePool *resPool;
230 /** Instruction used to signify that there is no *real* instruction in buffer slot */
231 DynInstPtr dummyBufferInst;
233 /** Used by resources to signify a denied access to a resource. */
234 ResourceRequest *dummyReq;
236 /** Identifies the resource id that identifies a fetch
239 unsigned fetchPortIdx;
241 /** Identifies the resource id that identifies a ITB */
244 /** Identifies the resource id that identifies a data
247 unsigned dataPortIdx;
249 /** Identifies the resource id that identifies a DTB */
252 /** The Pipeline Stages for the CPU */
253 PipelineStage *pipelineStage[ThePipeline::NumStages];
255 /** Program Counters */
256 TheISA::IntReg PC[ThePipeline::MaxThreads];
257 TheISA::IntReg nextPC[ThePipeline::MaxThreads];
258 TheISA::IntReg nextNPC[ThePipeline::MaxThreads];
260 /** The Register File for the CPU */
262 FloatReg f[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
263 FloatRegBits i[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
265 TheISA::IntReg intRegs[ThePipeline::MaxThreads][TheISA::NumIntRegs];
268 TheISA::ISA isa[ThePipeline::MaxThreads];
270 /** Dependency Tracker for Integer & Floating Point Regs */
271 RegDepMap archRegDepMap[ThePipeline::MaxThreads];
273 /** Global communication structure */
274 TimeBuffer<TimeStruct> timeBuffer;
276 /** Communication structure that sits in between pipeline stages */
277 StageQueue *stageQueue[ThePipeline::NumStages-1];
279 TheISA::TLB *getITBPtr();
280 TheISA::TLB *getDTBPtr();
284 /** Registers statistics. */
287 /** Ticks CPU, calling tick() on each stage, and checking the overall
288 * activity to see if the CPU should deschedule itself.
292 /** Initialize the CPU */
295 /** Reset State in the CPU */
298 /** Get a Memory Port */
299 Port* getPort(const std::string &if_name, int idx = 0);
301 /** trap() - sets up a trap event on the cpuTraps to handle given fault.
302 * trapCPU() - Traps to handle given fault
304 void trap(Fault fault, ThreadID tid, int delay = 0);
305 void trapCPU(Fault fault, ThreadID tid);
307 /** Setup CPU to insert a thread's context */
308 void insertThread(ThreadID tid);
310 /** Remove all of a thread's context from CPU */
311 void removeThread(ThreadID tid);
313 /** Add Thread to Active Threads List. */
314 void activateContext(ThreadID tid, int delay = 0);
315 void activateThread(ThreadID tid);
317 /** Remove Thread from Active Threads List */
318 void suspendContext(ThreadID tid, int delay = 0);
319 void suspendThread(ThreadID tid);
321 /** Remove Thread from Active Threads List &&
322 * Remove Thread Context from CPU.
324 void deallocateContext(ThreadID tid, int delay = 0);
325 void deallocateThread(ThreadID tid);
326 void deactivateThread(ThreadID tid);
328 PipelineStage* getPipeStage(int stage_num);
333 hack_once("return a bogus context id");
337 /** Remove Thread from Active Threads List &&
338 * Remove Thread Context from CPU.
340 void haltContext(ThreadID tid, int delay = 0);
342 void removePipelineStalls(ThreadID tid);
344 void squashThreadInPipeline(ThreadID tid);
346 /// Notify the CPU to enable a virtual processor element.
347 virtual void enableVirtProcElement(unsigned vpe);
348 void enableVPEs(unsigned vpe);
350 /// Notify the CPU to disable a virtual processor element.
351 virtual void disableVirtProcElement(ThreadID tid, unsigned vpe);
352 void disableVPEs(ThreadID tid, unsigned vpe);
354 /// Notify the CPU that multithreading is enabled.
355 virtual void enableMultiThreading(unsigned vpe);
356 void enableThreads(unsigned vpe);
358 /// Notify the CPU that multithreading is disabled.
359 virtual void disableMultiThreading(ThreadID tid, unsigned vpe);
360 void disableThreads(ThreadID tid, unsigned vpe);
362 /** Activate a Thread When CPU Resources are Available. */
363 void activateWhenReady(ThreadID tid);
365 /** Add or Remove a Thread Context in the CPU. */
366 void doContextSwitch();
368 /** Update The Order In Which We Process Threads. */
369 void updateThreadPriority();
371 /** Switches a Pipeline Stage to Active. (Unused currently) */
372 void switchToActive(int stage_idx)
373 { /*pipelineStage[stage_idx]->switchToActive();*/ }
375 /** Get the current instruction sequence number, and increment it. */
376 InstSeqNum getAndIncrementInstSeq(ThreadID tid)
377 { return globalSeqNum[tid]++; }
379 /** Get the current instruction sequence number, and increment it. */
380 InstSeqNum nextInstSeqNum(ThreadID tid)
381 { return globalSeqNum[tid]; }
383 /** Increment Instruction Sequence Number */
384 void incrInstSeqNum(ThreadID tid)
385 { globalSeqNum[tid]++; }
387 /** Set Instruction Sequence Number */
388 void setInstSeqNum(ThreadID tid, InstSeqNum seq_num)
390 globalSeqNum[tid] = seq_num;
393 /** Get & Update Next Event Number */
394 InstSeqNum getNextEventNum()
396 return cpuEventNum++;
399 /** Get instruction asid. */
400 int getInstAsid(ThreadID tid)
401 { return thread[tid]->getInstAsid(); }
403 /** Get data asid. */
404 int getDataAsid(ThreadID tid)
405 { return thread[tid]->getDataAsid(); }
407 /** Register file accessors */
408 uint64_t readIntReg(int reg_idx, ThreadID tid);
410 FloatReg readFloatReg(int reg_idx, ThreadID tid);
412 FloatRegBits readFloatRegBits(int reg_idx, ThreadID tid);
414 void setIntReg(int reg_idx, uint64_t val, ThreadID tid);
416 void setFloatReg(int reg_idx, FloatReg val, ThreadID tid);
418 void setFloatRegBits(int reg_idx, FloatRegBits val, ThreadID tid);
420 /** Reads a miscellaneous register. */
421 MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid = 0);
423 /** Reads a misc. register, including any side effects the read
424 * might have as defined by the architecture.
426 MiscReg readMiscReg(int misc_reg, ThreadID tid = 0);
428 /** Sets a miscellaneous register. */
429 void setMiscRegNoEffect(int misc_reg, const MiscReg &val,
432 /** Sets a misc. register, including any side effects the write
433 * might have as defined by the architecture.
435 void setMiscReg(int misc_reg, const MiscReg &val, ThreadID tid = 0);
437 /** Reads a int/fp/misc reg. from another thread depending on ISA-defined
440 uint64_t readRegOtherThread(unsigned misc_reg,
441 ThreadID tid = InvalidThreadID);
443 /** Sets a int/fp/misc reg. from another thread depending on an ISA-defined
446 void setRegOtherThread(unsigned misc_reg, const MiscReg &val,
449 /** Reads the commit PC of a specific thread. */
450 uint64_t readPC(ThreadID tid);
452 /** Sets the commit PC of a specific thread. */
453 void setPC(Addr new_PC, ThreadID tid);
455 /** Reads the next PC of a specific thread. */
456 uint64_t readNextPC(ThreadID tid);
458 /** Sets the next PC of a specific thread. */
459 void setNextPC(uint64_t val, ThreadID tid);
461 /** Reads the next NPC of a specific thread. */
462 uint64_t readNextNPC(ThreadID tid);
464 /** Sets the next NPC of a specific thread. */
465 void setNextNPC(uint64_t val, ThreadID tid);
467 /** Function to add instruction onto the head of the list of the
468 * instructions. Used when new instructions are fetched.
470 ListIt addInst(DynInstPtr &inst);
472 /** Function to tell the CPU that an instruction has completed. */
473 void instDone(DynInstPtr inst, ThreadID tid);
475 /** Add Instructions to the CPU Remove List*/
476 void addToRemoveList(DynInstPtr &inst);
478 /** Remove an instruction from CPU */
479 void removeInst(DynInstPtr &inst);
481 /** Remove all instructions younger than the given sequence number. */
482 void removeInstsUntil(const InstSeqNum &seq_num,ThreadID tid);
484 /** Removes the instruction pointed to by the iterator. */
485 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
487 /** Cleans up all instructions on the instruction remove list. */
488 void cleanUpRemovedInsts();
490 /** Cleans up all instructions on the request remove list. */
491 void cleanUpRemovedReqs();
493 /** Cleans up all instructions on the CPU event remove list. */
494 void cleanUpRemovedEvents();
496 /** Debug function to print all instructions on the list. */
499 /** Forwards an instruction read to the appropriate data
500 * resource (indexes into Resource Pool thru "dataPortIdx")
503 Fault read(DynInstPtr inst, Addr addr, T &data, unsigned flags);
505 /** Forwards an instruction write. to the appropriate data
506 * resource (indexes into Resource Pool thru "dataPortIdx")
509 Fault write(DynInstPtr inst, T data, Addr addr, unsigned flags,
510 uint64_t *write_res = NULL);
512 /** Forwards an instruction prefetch to the appropriate data
513 * resource (indexes into Resource Pool thru "dataPortIdx")
515 void prefetch(DynInstPtr inst);
517 /** Forwards an instruction writeHint to the appropriate data
518 * resource (indexes into Resource Pool thru "dataPortIdx")
520 void writeHint(DynInstPtr inst);
522 /** Executes a syscall.*/
523 void syscall(int64_t callnum, ThreadID tid);
526 /** Per-Thread List of all the instructions in flight. */
527 std::list<DynInstPtr> instList[ThePipeline::MaxThreads];
529 /** List of all the instructions that will be removed at the end of this
532 std::queue<ListIt> removeList;
534 /** List of all the resource requests that will be removed at the end of this
537 std::queue<ResourceRequest*> reqRemoveList;
539 /** List of all the cpu event requests that will be removed at the end of
542 std::queue<Event*> cpuEventRemoveList;
544 /** Records if instructions need to be removed this cycle due to
545 * being retired or squashed.
547 bool removeInstsThisCycle;
549 /** True if there is non-speculative Inst Active In Pipeline. Lets any
550 * execution unit know, NOT to execute while the instruction is active.
552 bool nonSpecInstActive[ThePipeline::MaxThreads];
554 /** Instruction Seq. Num of current non-speculative instruction. */
555 InstSeqNum nonSpecSeqNum[ThePipeline::MaxThreads];
557 /** Instruction Seq. Num of last instruction squashed in pipeline */
558 InstSeqNum squashSeqNum[ThePipeline::MaxThreads];
560 /** Last Cycle that the CPU squashed instruction end. */
561 Tick lastSquashCycle[ThePipeline::MaxThreads];
563 std::list<ThreadID> fetchPriorityList;
566 /** Active Threads List */
567 std::list<ThreadID> activeThreads;
569 /** Current Threads List */
570 std::list<ThreadID> currentThreads;
572 /** Suspended Threads List */
573 std::list<ThreadID> suspendedThreads;
575 /** Thread Status Functions (Unused Currently) */
576 bool isThreadInCPU(ThreadID tid);
577 bool isThreadActive(ThreadID tid);
578 bool isThreadSuspended(ThreadID tid);
579 void addToCurrentThreads(ThreadID tid);
580 void removeFromCurrentThreads(ThreadID tid);
583 /** The activity recorder; used to tell if the CPU has any
584 * activity remaining or if it can go to idle and deschedule
587 ActivityRecorder activityRec;
590 void readFunctional(Addr addr, uint32_t &buffer);
592 /** Number of Active Threads in the CPU */
593 ThreadID numActiveThreads() { return activeThreads.size(); }
595 /** Records that there was time buffer activity this cycle. */
596 void activityThisCycle() { activityRec.activity(); }
598 /** Changes a stage's status to active within the activity recorder. */
599 void activateStage(const int idx)
600 { activityRec.activateStage(idx); }
602 /** Changes a stage's status to inactive within the activity recorder. */
603 void deactivateStage(const int idx)
604 { activityRec.deactivateStage(idx); }
606 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
609 /** Gets a free thread id. Use if thread ids change across system. */
610 ThreadID getFreeTid();
612 // LL/SC debug functionality
613 unsigned stCondFails;
614 unsigned readStCondFailures() { return stCondFails; }
615 unsigned setStCondFailures(unsigned st_fails) { return stCondFails = st_fails; }
617 /** Returns a pointer to a thread context. */
618 ThreadContext *tcBase(ThreadID tid = 0)
620 return thread[tid]->getTC();
623 /** Count the Total Instructions Committed in the CPU. */
624 virtual Counter totalInstructions() const
628 for (ThreadID tid = 0; tid < (ThreadID)thread.size(); tid++)
629 total += thread[tid]->numInst;
634 /** The global sequence number counter. */
635 InstSeqNum globalSeqNum[ThePipeline::MaxThreads];
637 /** The global event number counter. */
638 InstSeqNum cpuEventNum;
640 /** Counter of how many stages have completed switching out. */
643 /** Pointers to all of the threads in the CPU. */
644 std::vector<Thread *> thread;
646 /** Pointer to the icache interface. */
647 MemInterface *icacheInterface;
649 /** Pointer to the dcache interface. */
650 MemInterface *dcacheInterface;
652 /** Whether or not the CPU should defer its registration. */
653 bool deferRegistration;
655 /** Per-Stage Instruction Tracing */
658 /** Is there a context switch pending? */
661 /** Threads Scheduled to Enter CPU */
662 std::list<int> cpuWaitList;
664 /** The cycle that the CPU was last running, used for statistics. */
665 Tick lastRunningCycle;
667 /** Number of Virtual Processors the CPU can process */
668 unsigned numVirtProcs;
670 /** Update Thread , used for statistic purposes*/
671 inline void tickThreadStats();
673 /** Per-Thread Tick */
674 Stats::Vector threadCycles;
677 Stats::Scalar smtCycles;
679 /** Stat for total number of times the CPU is descheduled. */
680 Stats::Scalar timesIdled;
682 /** Stat for total number of cycles the CPU spends descheduled. */
683 Stats::Scalar idleCycles;
685 /** Stat for the number of committed instructions per thread. */
686 Stats::Vector committedInsts;
688 /** Stat for the number of committed instructions per thread. */
689 Stats::Vector smtCommittedInsts;
691 /** Stat for the total number of committed instructions. */
692 Stats::Scalar totalCommittedInsts;
694 /** Stat for the CPI per thread. */
697 /** Stat for the SMT-CPI per thread. */
698 Stats::Formula smtCpi;
700 /** Stat for the total CPI. */
701 Stats::Formula totalCpi;
703 /** Stat for the IPC per thread. */
706 /** Stat for the total IPC. */
707 Stats::Formula smtIpc;
709 /** Stat for the total IPC. */
710 Stats::Formula totalIpc;
713 #endif // __CPU_O3_CPU_HH__