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);
100 /** Type of core that this is */
101 std::string coreType;
103 // Only need for SE MODE
110 ThreadModel threadModel;
112 int readCpuId() { return cpu_id; }
114 void setCpuId(int val) { cpu_id = val; }
127 /** Overall CPU status. */
130 /** Define TickEvent for the CPU */
131 class TickEvent : public Event
134 /** Pointer to the CPU. */
138 /** Constructs a tick event. */
139 TickEvent(InOrderCPU *c);
141 /** Processes a tick event, calling tick() on the CPU. */
144 /** Returns the description of the tick event. */
145 const char *description();
148 /** The tick event used for scheduling CPU ticks. */
151 /** Schedule tick event, regardless of its current state. */
152 void scheduleTickEvent(int delay)
154 if (tickEvent.squashed())
155 mainEventQueue.reschedule(&tickEvent,
156 nextCycle(curTick + ticks(delay)));
157 else if (!tickEvent.scheduled())
158 mainEventQueue.schedule(&tickEvent,
159 nextCycle(curTick + ticks(delay)));
162 /** Unschedule tick event, regardless of its current state. */
163 void unscheduleTickEvent()
165 if (tickEvent.scheduled())
170 // List of Events That can be scheduled from
172 // NOTE(1): The Resource Pool also uses this event list
173 // to schedule events broadcast to all resources interfaces
174 // NOTE(2): CPU Events usually need to schedule a corresponding resource
178 ActivateNextReadyThread,
189 static std::string eventNames[NumCPUEvents];
191 /** Define CPU Event */
192 class CPUEvent : public Event
198 CPUEventType cpuEventType;
205 /** Constructs a CPU event. */
206 CPUEvent(InOrderCPU *_cpu, CPUEventType e_type, Fault fault,
207 ThreadID _tid, DynInstPtr inst, unsigned event_pri_offset);
209 /** Set Type of Event To Be Scheduled */
210 void setEvent(CPUEventType e_type, Fault _fault, ThreadID _tid,
214 cpuEventType = e_type;
220 /** Processes a resource event. */
221 virtual void process();
223 /** Returns the description of the resource event. */
224 const char *description();
226 /** Schedule Event */
227 void scheduleEvent(int delay);
229 /** Unschedule This Event */
230 void unscheduleEvent();
233 /** Schedule a CPU Event */
234 void scheduleCpuEvent(CPUEventType cpu_event, Fault fault, ThreadID tid,
235 DynInstPtr inst, unsigned delay = 0,
236 unsigned event_pri_offset = 0);
239 /** Interface between the CPU and CPU resources. */
240 ResourcePool *resPool;
242 /** Instruction used to signify that there is no *real* instruction in
244 DynInstPtr dummyInst;
246 /** Used by resources to signify a denied access to a resource. */
247 ResourceRequest *dummyReq;
249 /** Identifies the resource id that identifies a fetch
252 unsigned fetchPortIdx;
254 /** Identifies the resource id that identifies a ITB */
257 /** Identifies the resource id that identifies a data
260 unsigned dataPortIdx;
262 /** Identifies the resource id that identifies a DTB */
265 /** The Pipeline Stages for the CPU */
266 PipelineStage *pipelineStage[ThePipeline::NumStages];
268 /** Program Counters */
269 TheISA::IntReg PC[ThePipeline::MaxThreads];
270 TheISA::IntReg nextPC[ThePipeline::MaxThreads];
271 TheISA::IntReg nextNPC[ThePipeline::MaxThreads];
273 /** The Register File for the CPU */
275 FloatReg f[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
276 FloatRegBits i[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
278 TheISA::IntReg intRegs[ThePipeline::MaxThreads][TheISA::NumIntRegs];
281 TheISA::ISA isa[ThePipeline::MaxThreads];
283 /** Dependency Tracker for Integer & Floating Point Regs */
284 RegDepMap archRegDepMap[ThePipeline::MaxThreads];
286 /** Global communication structure */
287 TimeBuffer<TimeStruct> timeBuffer;
289 /** Communication structure that sits in between pipeline stages */
290 StageQueue *stageQueue[ThePipeline::NumStages-1];
292 TheISA::TLB *getITBPtr();
293 TheISA::TLB *getDTBPtr();
297 /** Registers statistics. */
300 /** Ticks CPU, calling tick() on each stage, and checking the overall
301 * activity to see if the CPU should deschedule itself.
305 /** Initialize the CPU */
308 /** Reset State in the CPU */
311 /** Get a Memory Port */
312 Port* getPort(const std::string &if_name, int idx = 0);
315 /** HW return from error interrupt. */
316 Fault hwrei(ThreadID tid);
318 bool simPalCheck(int palFunc, ThreadID tid);
320 /** Returns the Fault for any valid interrupt. */
321 Fault getInterrupts();
323 /** Processes any an interrupt fault. */
324 void processInterrupts(Fault interrupt);
326 /** Halts the CPU. */
327 void halt() { panic("Halt not implemented!\n"); }
329 /** Update the Virt and Phys ports of all ThreadContexts to
330 * reflect change in memory connections. */
331 void updateMemPorts();
333 /** Check if this address is a valid instruction address. */
334 bool validInstAddr(Addr addr) { return true; }
336 /** Check if this address is a valid data address. */
337 bool validDataAddr(Addr addr) { return true; }
340 /** trap() - sets up a trap event on the cpuTraps to handle given fault.
341 * trapCPU() - Traps to handle given fault
343 void trap(Fault fault, ThreadID tid, int delay = 0);
344 void trapCPU(Fault fault, ThreadID tid);
346 /** Add Thread to Active Threads List. */
347 void activateContext(ThreadID tid, int delay = 0);
348 void activateThread(ThreadID tid);
349 void activateThreadInPipeline(ThreadID tid);
351 /** Add Thread to Active Threads List. */
352 void activateNextReadyContext(int delay = 0);
353 void activateNextReadyThread();
355 /** Remove from Active Thread List */
356 void deactivateContext(ThreadID tid, int delay = 0);
357 void deactivateThread(ThreadID tid);
359 /** Suspend Thread, Remove from Active Threads List, Add to Suspend List */
360 void suspendContext(ThreadID tid, int delay = 0);
361 void suspendThread(ThreadID tid);
363 /** Halt Thread, Remove from Active Thread List, Place Thread on Halted
366 void haltContext(ThreadID tid, int delay = 0);
367 void haltThread(ThreadID tid);
369 /** squashFromMemStall() - sets up a squash event
370 * squashDueToMemStall() - squashes pipeline
371 * @note: maybe squashContext/squashThread would be better?
373 void squashFromMemStall(DynInstPtr inst, ThreadID tid, int delay = 0);
374 void squashDueToMemStall(int stage_num, InstSeqNum seq_num, ThreadID tid);
376 void removePipelineStalls(ThreadID tid);
377 void squashThreadInPipeline(ThreadID tid);
378 void squashBehindMemStall(int stage_num, InstSeqNum seq_num, ThreadID tid);
380 PipelineStage* getPipeStage(int stage_num);
385 hack_once("return a bogus context id");
389 /** Update The Order In Which We Process Threads. */
390 void updateThreadPriority();
392 /** Switches a Pipeline Stage to Active. (Unused currently) */
393 void switchToActive(int stage_idx)
394 { /*pipelineStage[stage_idx]->switchToActive();*/ }
396 /** Get the current instruction sequence number, and increment it. */
397 InstSeqNum getAndIncrementInstSeq(ThreadID tid)
398 { return globalSeqNum[tid]++; }
400 /** Get the current instruction sequence number, and increment it. */
401 InstSeqNum nextInstSeqNum(ThreadID tid)
402 { return globalSeqNum[tid]; }
404 /** Increment Instruction Sequence Number */
405 void incrInstSeqNum(ThreadID tid)
406 { globalSeqNum[tid]++; }
408 /** Set Instruction Sequence Number */
409 void setInstSeqNum(ThreadID tid, InstSeqNum seq_num)
411 globalSeqNum[tid] = seq_num;
414 /** Get & Update Next Event Number */
415 InstSeqNum getNextEventNum()
418 return cpuEventNum++;
424 /** Register file accessors */
425 uint64_t readIntReg(int reg_idx, ThreadID tid);
427 FloatReg readFloatReg(int reg_idx, ThreadID tid);
429 FloatRegBits readFloatRegBits(int reg_idx, ThreadID tid);
431 void setIntReg(int reg_idx, uint64_t val, ThreadID tid);
433 void setFloatReg(int reg_idx, FloatReg val, ThreadID tid);
435 void setFloatRegBits(int reg_idx, FloatRegBits val, ThreadID tid);
437 /** Reads a miscellaneous register. */
438 MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid = 0);
440 /** Reads a misc. register, including any side effects the read
441 * might have as defined by the architecture.
443 MiscReg readMiscReg(int misc_reg, ThreadID tid = 0);
445 /** Sets a miscellaneous register. */
446 void setMiscRegNoEffect(int misc_reg, const MiscReg &val,
449 /** Sets a misc. register, including any side effects the write
450 * might have as defined by the architecture.
452 void setMiscReg(int misc_reg, const MiscReg &val, ThreadID tid = 0);
454 /** Reads a int/fp/misc reg. from another thread depending on ISA-defined
457 uint64_t readRegOtherThread(unsigned misc_reg,
458 ThreadID tid = InvalidThreadID);
460 /** Sets a int/fp/misc reg. from another thread depending on an ISA-defined
463 void setRegOtherThread(unsigned misc_reg, const MiscReg &val,
466 /** Reads the commit PC of a specific thread. */
467 uint64_t readPC(ThreadID tid);
469 /** Sets the commit PC of a specific thread. */
470 void setPC(Addr new_PC, ThreadID tid);
472 /** Reads the next PC of a specific thread. */
473 uint64_t readNextPC(ThreadID tid);
475 /** Sets the next PC of a specific thread. */
476 void setNextPC(uint64_t val, ThreadID tid);
478 /** Reads the next NPC of a specific thread. */
479 uint64_t readNextNPC(ThreadID tid);
481 /** Sets the next NPC of a specific thread. */
482 void setNextNPC(uint64_t val, ThreadID tid);
484 /** Function to add instruction onto the head of the list of the
485 * instructions. Used when new instructions are fetched.
487 ListIt addInst(DynInstPtr &inst);
489 /** Function to tell the CPU that an instruction has completed. */
490 void instDone(DynInstPtr inst, ThreadID tid);
492 /** Add Instructions to the CPU Remove List*/
493 void addToRemoveList(DynInstPtr &inst);
495 /** Remove an instruction from CPU */
496 void removeInst(DynInstPtr &inst);
498 /** Remove all instructions younger than the given sequence number. */
499 void removeInstsUntil(const InstSeqNum &seq_num,ThreadID tid);
501 /** Removes the instruction pointed to by the iterator. */
502 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
504 /** Cleans up all instructions on the instruction remove list. */
505 void cleanUpRemovedInsts();
507 /** Cleans up all instructions on the request remove list. */
508 void cleanUpRemovedReqs();
510 /** Cleans up all instructions on the CPU event remove list. */
511 void cleanUpRemovedEvents();
513 /** Debug function to print all instructions on the list. */
516 /** Forwards an instruction read to the appropriate data
517 * resource (indexes into Resource Pool thru "dataPortIdx")
520 Fault read(DynInstPtr inst, Addr addr, T &data, unsigned flags);
522 /** Forwards an instruction write. to the appropriate data
523 * resource (indexes into Resource Pool thru "dataPortIdx")
526 Fault write(DynInstPtr inst, T data, Addr addr, unsigned flags,
527 uint64_t *write_res = NULL);
529 /** Forwards an instruction prefetch to the appropriate data
530 * resource (indexes into Resource Pool thru "dataPortIdx")
532 void prefetch(DynInstPtr inst);
534 /** Forwards an instruction writeHint to the appropriate data
535 * resource (indexes into Resource Pool thru "dataPortIdx")
537 void writeHint(DynInstPtr inst);
539 /** Executes a syscall.*/
540 void syscall(int64_t callnum, ThreadID 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
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;
561 /** Records if instructions need to be removed this cycle due to
562 * being retired or squashed.
564 bool removeInstsThisCycle;
566 /** True if there is non-speculative Inst Active In Pipeline. Lets any
567 * execution unit know, NOT to execute while the instruction is active.
569 bool nonSpecInstActive[ThePipeline::MaxThreads];
571 /** Instruction Seq. Num of current non-speculative instruction. */
572 InstSeqNum nonSpecSeqNum[ThePipeline::MaxThreads];
574 /** Instruction Seq. Num of last instruction squashed in pipeline */
575 InstSeqNum squashSeqNum[ThePipeline::MaxThreads];
577 /** Last Cycle that the CPU squashed instruction end. */
578 Tick lastSquashCycle[ThePipeline::MaxThreads];
580 std::list<ThreadID> fetchPriorityList;
583 /** Active Threads List */
584 std::list<ThreadID> activeThreads;
586 /** Ready Threads List */
587 std::list<ThreadID> readyThreads;
589 /** Suspended Threads List */
590 std::list<ThreadID> suspendedThreads;
592 /** Halted Threads List */
593 std::list<ThreadID> haltedThreads;
595 /** Thread Status Functions */
596 bool isThreadActive(ThreadID tid);
597 bool isThreadReady(ThreadID tid);
598 bool isThreadSuspended(ThreadID tid);
601 /** The activity recorder; used to tell if the CPU has any
602 * activity remaining or if it can go to idle and deschedule
605 ActivityRecorder activityRec;
608 /** Number of Active Threads in the CPU */
609 ThreadID numActiveThreads() { return activeThreads.size(); }
611 /** Thread id of active thread
612 * Only used for SwitchOnCacheMiss model.
613 * Assumes only 1 thread active
615 ThreadID activeThreadId()
617 if (numActiveThreads() > 0)
618 return activeThreads.front();
620 return InvalidThreadID;
624 /** Records that there was time buffer activity this cycle. */
625 void activityThisCycle() { activityRec.activity(); }
627 /** Changes a stage's status to active within the activity recorder. */
628 void activateStage(const int idx)
629 { activityRec.activateStage(idx); }
631 /** Changes a stage's status to inactive within the activity recorder. */
632 void deactivateStage(const int idx)
633 { activityRec.deactivateStage(idx); }
635 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
639 virtual void wakeup();
642 // LL/SC debug functionality
643 unsigned stCondFails;
645 unsigned readStCondFailures()
646 { return stCondFails; }
648 unsigned setStCondFailures(unsigned st_fails)
649 { return stCondFails = st_fails; }
651 /** Returns a pointer to a thread context. */
652 ThreadContext *tcBase(ThreadID tid = 0)
654 return thread[tid]->getTC();
657 /** Count the Total Instructions Committed in the CPU. */
658 virtual Counter totalInstructions() const
662 for (ThreadID tid = 0; tid < (ThreadID)thread.size(); tid++)
663 total += thread[tid]->numInst;
669 /** Pointer to the system. */
672 /** Pointer to physical memory. */
673 PhysicalMemory *physmem;
676 /** The global sequence number counter. */
677 InstSeqNum globalSeqNum[ThePipeline::MaxThreads];
680 /** The global event number counter. */
681 InstSeqNum cpuEventNum;
683 /** Number of resource requests active in CPU **/
684 unsigned resReqCount;
686 Stats::Scalar maxResReqCount;
689 /** Counter of how many stages have completed switching out. */
692 /** Pointers to all of the threads in the CPU. */
693 std::vector<Thread *> thread;
695 /** Pointer to the icache interface. */
696 MemInterface *icacheInterface;
698 /** Pointer to the dcache interface. */
699 MemInterface *dcacheInterface;
701 /** Whether or not the CPU should defer its registration. */
702 bool deferRegistration;
704 /** Per-Stage Instruction Tracing */
707 /** The cycle that the CPU was last running, used for statistics. */
708 Tick lastRunningCycle;
710 void updateContextSwitchStats();
711 unsigned instsPerSwitch;
712 Stats::Average instsPerCtxtSwitch;
713 Stats::Scalar numCtxtSwitches;
715 /** Update Thread , used for statistic purposes*/
716 inline void tickThreadStats();
718 /** Per-Thread Tick */
719 Stats::Vector threadCycles;
722 Stats::Scalar smtCycles;
724 /** Stat for total number of times the CPU is descheduled. */
725 Stats::Scalar timesIdled;
727 /** Stat for total number of cycles the CPU spends descheduled. */
728 Stats::Scalar idleCycles;
730 /** Stat for the number of committed instructions per thread. */
731 Stats::Vector committedInsts;
733 /** Stat for the number of committed instructions per thread. */
734 Stats::Vector smtCommittedInsts;
736 /** Stat for the total number of committed instructions. */
737 Stats::Scalar totalCommittedInsts;
739 /** Stat for the CPI per thread. */
742 /** Stat for the SMT-CPI per thread. */
743 Stats::Formula smtCpi;
745 /** Stat for the total CPI. */
746 Stats::Formula totalCpi;
748 /** Stat for the IPC per thread. */
751 /** Stat for the total IPC. */
752 Stats::Formula smtIpc;
754 /** Stat for the total IPC. */
755 Stats::Formula totalIpc;
758 #endif // __CPU_O3_CPU_HH__