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);
350 /** Add Thread to Active Threads List. */
351 void activateNextReadyContext(int delay = 0);
352 void activateNextReadyThread();
354 /** Remove from Active Thread List */
355 void deactivateContext(ThreadID tid, int delay = 0);
356 void deactivateThread(ThreadID tid);
358 /** Suspend Thread, Remove from Active Threads List, Add to Suspend List */
359 void haltContext(ThreadID tid, int delay = 0);
360 void suspendContext(ThreadID tid, int delay = 0);
361 void suspendThread(ThreadID tid);
363 /** Remove Thread from Active Threads List, Remove Any Loaded Thread State */
364 void deallocateContext(ThreadID tid, int delay = 0);
365 void deallocateThread(ThreadID tid);
367 /** squashFromMemStall() - sets up a squash event
368 * squashDueToMemStall() - squashes pipeline
370 void squashFromMemStall(DynInstPtr inst, ThreadID tid, int delay = 0);
371 void squashDueToMemStall(int stage_num, InstSeqNum seq_num, ThreadID tid);
373 void removePipelineStalls(ThreadID tid);
374 void squashThreadInPipeline(ThreadID tid);
375 void squashBehindMemStall(int stage_num, InstSeqNum seq_num, ThreadID tid);
377 PipelineStage* getPipeStage(int stage_num);
382 hack_once("return a bogus context id");
386 /** Update The Order In Which We Process Threads. */
387 void updateThreadPriority();
389 /** Switches a Pipeline Stage to Active. (Unused currently) */
390 void switchToActive(int stage_idx)
391 { /*pipelineStage[stage_idx]->switchToActive();*/ }
393 /** Get the current instruction sequence number, and increment it. */
394 InstSeqNum getAndIncrementInstSeq(ThreadID tid)
395 { return globalSeqNum[tid]++; }
397 /** Get the current instruction sequence number, and increment it. */
398 InstSeqNum nextInstSeqNum(ThreadID tid)
399 { return globalSeqNum[tid]; }
401 /** Increment Instruction Sequence Number */
402 void incrInstSeqNum(ThreadID tid)
403 { globalSeqNum[tid]++; }
405 /** Set Instruction Sequence Number */
406 void setInstSeqNum(ThreadID tid, InstSeqNum seq_num)
408 globalSeqNum[tid] = seq_num;
411 /** Get & Update Next Event Number */
412 InstSeqNum getNextEventNum()
415 return cpuEventNum++;
421 /** Register file accessors */
422 uint64_t readIntReg(int reg_idx, ThreadID tid);
424 FloatReg readFloatReg(int reg_idx, ThreadID tid);
426 FloatRegBits readFloatRegBits(int reg_idx, ThreadID tid);
428 void setIntReg(int reg_idx, uint64_t val, ThreadID tid);
430 void setFloatReg(int reg_idx, FloatReg val, ThreadID tid);
432 void setFloatRegBits(int reg_idx, FloatRegBits val, ThreadID tid);
434 /** Reads a miscellaneous register. */
435 MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid = 0);
437 /** Reads a misc. register, including any side effects the read
438 * might have as defined by the architecture.
440 MiscReg readMiscReg(int misc_reg, ThreadID tid = 0);
442 /** Sets a miscellaneous register. */
443 void setMiscRegNoEffect(int misc_reg, const MiscReg &val,
446 /** Sets a misc. register, including any side effects the write
447 * might have as defined by the architecture.
449 void setMiscReg(int misc_reg, const MiscReg &val, ThreadID tid = 0);
451 /** Reads a int/fp/misc reg. from another thread depending on ISA-defined
454 uint64_t readRegOtherThread(unsigned misc_reg,
455 ThreadID tid = InvalidThreadID);
457 /** Sets a int/fp/misc reg. from another thread depending on an ISA-defined
460 void setRegOtherThread(unsigned misc_reg, const MiscReg &val,
463 /** Reads the commit PC of a specific thread. */
464 uint64_t readPC(ThreadID tid);
466 /** Sets the commit PC of a specific thread. */
467 void setPC(Addr new_PC, ThreadID tid);
469 /** Reads the next PC of a specific thread. */
470 uint64_t readNextPC(ThreadID tid);
472 /** Sets the next PC of a specific thread. */
473 void setNextPC(uint64_t val, ThreadID tid);
475 /** Reads the next NPC of a specific thread. */
476 uint64_t readNextNPC(ThreadID tid);
478 /** Sets the next NPC of a specific thread. */
479 void setNextNPC(uint64_t val, ThreadID tid);
481 /** Function to add instruction onto the head of the list of the
482 * instructions. Used when new instructions are fetched.
484 ListIt addInst(DynInstPtr &inst);
486 /** Function to tell the CPU that an instruction has completed. */
487 void instDone(DynInstPtr inst, ThreadID tid);
489 /** Add Instructions to the CPU Remove List*/
490 void addToRemoveList(DynInstPtr &inst);
492 /** Remove an instruction from CPU */
493 void removeInst(DynInstPtr &inst);
495 /** Remove all instructions younger than the given sequence number. */
496 void removeInstsUntil(const InstSeqNum &seq_num,ThreadID tid);
498 /** Removes the instruction pointed to by the iterator. */
499 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
501 /** Cleans up all instructions on the instruction remove list. */
502 void cleanUpRemovedInsts();
504 /** Cleans up all instructions on the request remove list. */
505 void cleanUpRemovedReqs();
507 /** Cleans up all instructions on the CPU event remove list. */
508 void cleanUpRemovedEvents();
510 /** Debug function to print all instructions on the list. */
513 /** Forwards an instruction read to the appropriate data
514 * resource (indexes into Resource Pool thru "dataPortIdx")
517 Fault read(DynInstPtr inst, Addr addr, T &data, unsigned flags);
519 /** Forwards an instruction write. to the appropriate data
520 * resource (indexes into Resource Pool thru "dataPortIdx")
523 Fault write(DynInstPtr inst, T data, Addr addr, unsigned flags,
524 uint64_t *write_res = NULL);
526 /** Forwards an instruction prefetch to the appropriate data
527 * resource (indexes into Resource Pool thru "dataPortIdx")
529 void prefetch(DynInstPtr inst);
531 /** Forwards an instruction writeHint to the appropriate data
532 * resource (indexes into Resource Pool thru "dataPortIdx")
534 void writeHint(DynInstPtr inst);
536 /** Executes a syscall.*/
537 void syscall(int64_t callnum, ThreadID tid);
540 /** Per-Thread List of all the instructions in flight. */
541 std::list<DynInstPtr> instList[ThePipeline::MaxThreads];
543 /** List of all the instructions that will be removed at the end of this
546 std::queue<ListIt> removeList;
548 /** List of all the resource requests that will be removed at the end
551 std::queue<ResourceRequest*> reqRemoveList;
553 /** List of all the cpu event requests that will be removed at the end of
556 std::queue<Event*> cpuEventRemoveList;
558 /** Records if instructions need to be removed this cycle due to
559 * being retired or squashed.
561 bool removeInstsThisCycle;
563 /** True if there is non-speculative Inst Active In Pipeline. Lets any
564 * execution unit know, NOT to execute while the instruction is active.
566 bool nonSpecInstActive[ThePipeline::MaxThreads];
568 /** Instruction Seq. Num of current non-speculative instruction. */
569 InstSeqNum nonSpecSeqNum[ThePipeline::MaxThreads];
571 /** Instruction Seq. Num of last instruction squashed in pipeline */
572 InstSeqNum squashSeqNum[ThePipeline::MaxThreads];
574 /** Last Cycle that the CPU squashed instruction end. */
575 Tick lastSquashCycle[ThePipeline::MaxThreads];
577 std::list<ThreadID> fetchPriorityList;
580 /** Active Threads List */
581 std::list<ThreadID> activeThreads;
583 /** Ready Threads List */
584 std::list<ThreadID> readyThreads;
586 /** Suspended Threads List */
587 std::list<ThreadID> suspendedThreads;
589 /** Thread Status Functions */
590 bool isThreadActive(ThreadID tid);
591 bool isThreadSuspended(ThreadID tid);
594 /** The activity recorder; used to tell if the CPU has any
595 * activity remaining or if it can go to idle and deschedule
598 ActivityRecorder activityRec;
601 /** Number of Active Threads in the CPU */
602 ThreadID numActiveThreads() { return activeThreads.size(); }
604 /** Thread id of active thread
605 * Only used for SwitchOnCacheMiss model.
606 * Assumes only 1 thread active
608 ThreadID activeThreadId()
610 if (numActiveThreads() > 0)
611 return activeThreads.front();
617 /** Records that there was time buffer activity this cycle. */
618 void activityThisCycle() { activityRec.activity(); }
620 /** Changes a stage's status to active within the activity recorder. */
621 void activateStage(const int idx)
622 { activityRec.activateStage(idx); }
624 /** Changes a stage's status to inactive within the activity recorder. */
625 void deactivateStage(const int idx)
626 { activityRec.deactivateStage(idx); }
628 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
632 virtual void wakeup();
635 // LL/SC debug functionality
636 unsigned stCondFails;
638 unsigned readStCondFailures()
639 { return stCondFails; }
641 unsigned setStCondFailures(unsigned st_fails)
642 { return stCondFails = st_fails; }
644 /** Returns a pointer to a thread context. */
645 ThreadContext *tcBase(ThreadID tid = 0)
647 return thread[tid]->getTC();
650 /** Count the Total Instructions Committed in the CPU. */
651 virtual Counter totalInstructions() const
655 for (ThreadID tid = 0; tid < (ThreadID)thread.size(); tid++)
656 total += thread[tid]->numInst;
662 /** Pointer to the system. */
665 /** Pointer to physical memory. */
666 PhysicalMemory *physmem;
669 /** The global sequence number counter. */
670 InstSeqNum globalSeqNum[ThePipeline::MaxThreads];
673 /** The global event number counter. */
674 InstSeqNum cpuEventNum;
676 /** Number of resource requests active in CPU **/
677 unsigned resReqCount;
679 Stats::Scalar maxResReqCount;
682 /** Counter of how many stages have completed switching out. */
685 /** Pointers to all of the threads in the CPU. */
686 std::vector<Thread *> thread;
688 /** Pointer to the icache interface. */
689 MemInterface *icacheInterface;
691 /** Pointer to the dcache interface. */
692 MemInterface *dcacheInterface;
694 /** Whether or not the CPU should defer its registration. */
695 bool deferRegistration;
697 /** Per-Stage Instruction Tracing */
700 /** The cycle that the CPU was last running, used for statistics. */
701 Tick lastRunningCycle;
703 /** Update Thread , used for statistic purposes*/
704 inline void tickThreadStats();
706 /** Per-Thread Tick */
707 Stats::Vector threadCycles;
710 Stats::Scalar smtCycles;
712 /** Stat for total number of times the CPU is descheduled. */
713 Stats::Scalar timesIdled;
715 /** Stat for total number of cycles the CPU spends descheduled. */
716 Stats::Scalar idleCycles;
718 /** Stat for the number of committed instructions per thread. */
719 Stats::Vector committedInsts;
721 /** Stat for the number of committed instructions per thread. */
722 Stats::Vector smtCommittedInsts;
724 /** Stat for the total number of committed instructions. */
725 Stats::Scalar totalCommittedInsts;
727 /** Stat for the CPI per thread. */
730 /** Stat for the SMT-CPI per thread. */
731 Stats::Formula smtCpi;
733 /** Stat for the total CPI. */
734 Stats::Formula totalCpi;
736 /** Stat for the IPC per thread. */
739 /** Stat for the total IPC. */
740 Stats::Formula smtIpc;
742 /** Stat for the total IPC. */
743 Stats::Formula totalIpc;
746 #endif // __CPU_O3_CPU_HH__