merge
[gem5.git] / src / cpu / inorder / cpu.hh
1 /*
2 * Copyright (c) 2007 MIPS Technologies, Inc.
3 * All rights reserved.
4 *
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.
15 *
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.
27 *
28 * Authors: Korey Sewell
29 *
30 */
31
32 #ifndef __CPU_INORDER_CPU_HH__
33 #define __CPU_INORDER_CPU_HH__
34
35 #include <iostream>
36 #include <list>
37 #include <queue>
38 #include <set>
39 #include <vector>
40
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"
62
63 class ThreadContext;
64 class MemInterface;
65 class MemObject;
66 class Process;
67 class ResourcePool;
68
69 class InOrderCPU : public BaseCPU
70 {
71
72 protected:
73 typedef ThePipeline::Params Params;
74 typedef InOrderThreadState Thread;
75
76 //ISA TypeDefs
77 typedef TheISA::IntReg IntReg;
78 typedef TheISA::FloatReg FloatReg;
79 typedef TheISA::FloatRegBits FloatRegBits;
80 typedef TheISA::MiscReg MiscReg;
81
82 //DynInstPtr TypeDefs
83 typedef ThePipeline::DynInstPtr DynInstPtr;
84 typedef std::list<DynInstPtr>::iterator ListIt;
85
86 //TimeBuffer TypeDefs
87 typedef TimeBuffer<InterStageStruct> StageQueue;
88
89 friend class Resource;
90
91 public:
92 /** Constructs a CPU with the given parameters. */
93 InOrderCPU(Params *params);
94
95 /** CPU ID */
96 int cpu_id;
97
98 /** Type of core that this is */
99 std::string coreType;
100
101 int readCpuId() { return cpu_id; }
102
103 void setCpuId(int val) { cpu_id = val; }
104
105 Params *cpu_params;
106
107 public:
108 enum Status {
109 Running,
110 Idle,
111 Halted,
112 Blocked,
113 SwitchedOut
114 };
115
116 /** Overall CPU status. */
117 Status _status;
118
119 private:
120 /** Define TickEvent for the CPU */
121 class TickEvent : public Event
122 {
123 private:
124 /** Pointer to the CPU. */
125 InOrderCPU *cpu;
126
127 public:
128 /** Constructs a tick event. */
129 TickEvent(InOrderCPU *c);
130
131 /** Processes a tick event, calling tick() on the CPU. */
132 void process();
133
134 /** Returns the description of the tick event. */
135 const char *description();
136 };
137
138 /** The tick event used for scheduling CPU ticks. */
139 TickEvent tickEvent;
140
141 /** Schedule tick event, regardless of its current state. */
142 void scheduleTickEvent(int delay)
143 {
144 if (tickEvent.squashed())
145 mainEventQueue.reschedule(&tickEvent, nextCycle(curTick + ticks(delay)));
146 else if (!tickEvent.scheduled())
147 mainEventQueue.schedule(&tickEvent, nextCycle(curTick + ticks(delay)));
148 }
149
150 /** Unschedule tick event, regardless of its current state. */
151 void unscheduleTickEvent()
152 {
153 if (tickEvent.scheduled())
154 tickEvent.squash();
155 }
156
157 public:
158 // List of Events That can be scheduled from
159 // within the CPU.
160 // NOTE(1): The Resource Pool also uses this event list
161 // to schedule events broadcast to all resources interfaces
162 // NOTE(2): CPU Events usually need to schedule a corresponding resource
163 // pool event.
164 enum CPUEventType {
165 ActivateThread,
166 DeallocateThread,
167 SuspendThread,
168 DisableThreads,
169 EnableThreads,
170 DisableVPEs,
171 EnableVPEs,
172 Trap,
173 InstGraduated,
174 SquashAll,
175 UpdatePCs,
176 NumCPUEvents
177 };
178
179 static std::string eventNames[NumCPUEvents];
180
181 /** Define CPU Event */
182 class CPUEvent : public Event
183 {
184 protected:
185 InOrderCPU *cpu;
186
187 public:
188 CPUEventType cpuEventType;
189 ThreadID tid;
190 unsigned vpe;
191 Fault fault;
192
193 public:
194 /** Constructs a CPU event. */
195 CPUEvent(InOrderCPU *_cpu, CPUEventType e_type, Fault fault,
196 ThreadID _tid, unsigned _vpe);
197
198 /** Set Type of Event To Be Scheduled */
199 void setEvent(CPUEventType e_type, Fault _fault, ThreadID _tid,
200 unsigned _vpe)
201 {
202 fault = _fault;
203 cpuEventType = e_type;
204 tid = _tid;
205 vpe = _vpe;
206 }
207
208 /** Processes a resource event. */
209 virtual void process();
210
211 /** Returns the description of the resource event. */
212 const char *description();
213
214 /** Schedule Event */
215 void scheduleEvent(int delay);
216
217 /** Unschedule This Event */
218 void unscheduleEvent();
219 };
220
221 /** Schedule a CPU Event */
222 void scheduleCpuEvent(CPUEventType cpu_event, Fault fault, ThreadID tid,
223 unsigned vpe, unsigned delay = 0);
224
225 public:
226 /** Interface between the CPU and CPU resources. */
227 ResourcePool *resPool;
228
229 /** Instruction used to signify that there is no *real* instruction in buffer slot */
230 DynInstPtr dummyBufferInst;
231
232 /** Used by resources to signify a denied access to a resource. */
233 ResourceRequest *dummyReq;
234
235 /** Identifies the resource id that identifies a fetch
236 * access unit.
237 */
238 unsigned fetchPortIdx;
239
240 /** Identifies the resource id that identifies a ITB */
241 unsigned itbIdx;
242
243 /** Identifies the resource id that identifies a data
244 * access unit.
245 */
246 unsigned dataPortIdx;
247
248 /** Identifies the resource id that identifies a DTB */
249 unsigned dtbIdx;
250
251 /** The Pipeline Stages for the CPU */
252 PipelineStage *pipelineStage[ThePipeline::NumStages];
253
254 /** Program Counters */
255 TheISA::IntReg PC[ThePipeline::MaxThreads];
256 TheISA::IntReg nextPC[ThePipeline::MaxThreads];
257 TheISA::IntReg nextNPC[ThePipeline::MaxThreads];
258
259 /** The Register File for the CPU */
260 union {
261 FloatReg f[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
262 FloatRegBits i[ThePipeline::MaxThreads][TheISA::NumFloatRegs];
263 } floatRegs;
264 TheISA::IntReg intRegs[ThePipeline::MaxThreads][TheISA::NumIntRegs];
265
266 /** ISA state */
267 TheISA::ISA isa[ThePipeline::MaxThreads];
268
269 /** Dependency Tracker for Integer & Floating Point Regs */
270 RegDepMap archRegDepMap[ThePipeline::MaxThreads];
271
272 /** Global communication structure */
273 TimeBuffer<TimeStruct> timeBuffer;
274
275 /** Communication structure that sits in between pipeline stages */
276 StageQueue *stageQueue[ThePipeline::NumStages-1];
277
278 TheISA::TLB *getITBPtr();
279 TheISA::TLB *getDTBPtr();
280
281 public:
282
283 /** Registers statistics. */
284 void regStats();
285
286 /** Ticks CPU, calling tick() on each stage, and checking the overall
287 * activity to see if the CPU should deschedule itself.
288 */
289 void tick();
290
291 /** Initialize the CPU */
292 void init();
293
294 /** Reset State in the CPU */
295 void reset();
296
297 /** Get a Memory Port */
298 Port* getPort(const std::string &if_name, int idx = 0);
299
300 /** trap() - sets up a trap event on the cpuTraps to handle given fault.
301 * trapCPU() - Traps to handle given fault
302 */
303 void trap(Fault fault, ThreadID tid, int delay = 0);
304 void trapCPU(Fault fault, ThreadID tid);
305
306 /** Setup CPU to insert a thread's context */
307 void insertThread(ThreadID tid);
308
309 /** Remove all of a thread's context from CPU */
310 void removeThread(ThreadID tid);
311
312 /** Add Thread to Active Threads List. */
313 void activateContext(ThreadID tid, int delay = 0);
314 void activateThread(ThreadID tid);
315
316 /** Remove Thread from Active Threads List */
317 void suspendContext(ThreadID tid, int delay = 0);
318 void suspendThread(ThreadID tid);
319
320 /** Remove Thread from Active Threads List &&
321 * Remove Thread Context from CPU.
322 */
323 void deallocateContext(ThreadID tid, int delay = 0);
324 void deallocateThread(ThreadID tid);
325 void deactivateThread(ThreadID tid);
326
327 PipelineStage* getPipeStage(int stage_num);
328
329 int
330 contextId()
331 {
332 hack_once("return a bogus context id");
333 return 0;
334 }
335
336 /** Remove Thread from Active Threads List &&
337 * Remove Thread Context from CPU.
338 */
339 void haltContext(ThreadID tid, int delay = 0);
340
341 void removePipelineStalls(ThreadID tid);
342
343 void squashThreadInPipeline(ThreadID tid);
344
345 /// Notify the CPU to enable a virtual processor element.
346 virtual void enableVirtProcElement(unsigned vpe);
347 void enableVPEs(unsigned vpe);
348
349 /// Notify the CPU to disable a virtual processor element.
350 virtual void disableVirtProcElement(ThreadID tid, unsigned vpe);
351 void disableVPEs(ThreadID tid, unsigned vpe);
352
353 /// Notify the CPU that multithreading is enabled.
354 virtual void enableMultiThreading(unsigned vpe);
355 void enableThreads(unsigned vpe);
356
357 /// Notify the CPU that multithreading is disabled.
358 virtual void disableMultiThreading(ThreadID tid, unsigned vpe);
359 void disableThreads(ThreadID tid, unsigned vpe);
360
361 /** Activate a Thread When CPU Resources are Available. */
362 void activateWhenReady(ThreadID tid);
363
364 /** Add or Remove a Thread Context in the CPU. */
365 void doContextSwitch();
366
367 /** Update The Order In Which We Process Threads. */
368 void updateThreadPriority();
369
370 /** Switches a Pipeline Stage to Active. (Unused currently) */
371 void switchToActive(int stage_idx)
372 { /*pipelineStage[stage_idx]->switchToActive();*/ }
373
374 /** Get the current instruction sequence number, and increment it. */
375 InstSeqNum getAndIncrementInstSeq(ThreadID tid)
376 { return globalSeqNum[tid]++; }
377
378 /** Get the current instruction sequence number, and increment it. */
379 InstSeqNum nextInstSeqNum(ThreadID tid)
380 { return globalSeqNum[tid]; }
381
382 /** Increment Instruction Sequence Number */
383 void incrInstSeqNum(ThreadID tid)
384 { globalSeqNum[tid]++; }
385
386 /** Set Instruction Sequence Number */
387 void setInstSeqNum(ThreadID tid, InstSeqNum seq_num)
388 {
389 globalSeqNum[tid] = seq_num;
390 }
391
392 /** Get & Update Next Event Number */
393 InstSeqNum getNextEventNum()
394 {
395 return cpuEventNum++;
396 }
397
398 /** Register file accessors */
399 uint64_t readIntReg(int reg_idx, ThreadID tid);
400
401 FloatReg readFloatReg(int reg_idx, ThreadID tid);
402
403 FloatRegBits readFloatRegBits(int reg_idx, ThreadID tid);
404
405 void setIntReg(int reg_idx, uint64_t val, ThreadID tid);
406
407 void setFloatReg(int reg_idx, FloatReg val, ThreadID tid);
408
409 void setFloatRegBits(int reg_idx, FloatRegBits val, ThreadID tid);
410
411 /** Reads a miscellaneous register. */
412 MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid = 0);
413
414 /** Reads a misc. register, including any side effects the read
415 * might have as defined by the architecture.
416 */
417 MiscReg readMiscReg(int misc_reg, ThreadID tid = 0);
418
419 /** Sets a miscellaneous register. */
420 void setMiscRegNoEffect(int misc_reg, const MiscReg &val,
421 ThreadID tid = 0);
422
423 /** Sets a misc. register, including any side effects the write
424 * might have as defined by the architecture.
425 */
426 void setMiscReg(int misc_reg, const MiscReg &val, ThreadID tid = 0);
427
428 /** Reads a int/fp/misc reg. from another thread depending on ISA-defined
429 * target thread
430 */
431 uint64_t readRegOtherThread(unsigned misc_reg,
432 ThreadID tid = InvalidThreadID);
433
434 /** Sets a int/fp/misc reg. from another thread depending on an ISA-defined
435 * target thread
436 */
437 void setRegOtherThread(unsigned misc_reg, const MiscReg &val,
438 ThreadID tid);
439
440 /** Reads the commit PC of a specific thread. */
441 uint64_t readPC(ThreadID tid);
442
443 /** Sets the commit PC of a specific thread. */
444 void setPC(Addr new_PC, ThreadID tid);
445
446 /** Reads the next PC of a specific thread. */
447 uint64_t readNextPC(ThreadID tid);
448
449 /** Sets the next PC of a specific thread. */
450 void setNextPC(uint64_t val, ThreadID tid);
451
452 /** Reads the next NPC of a specific thread. */
453 uint64_t readNextNPC(ThreadID tid);
454
455 /** Sets the next NPC of a specific thread. */
456 void setNextNPC(uint64_t val, ThreadID tid);
457
458 /** Function to add instruction onto the head of the list of the
459 * instructions. Used when new instructions are fetched.
460 */
461 ListIt addInst(DynInstPtr &inst);
462
463 /** Function to tell the CPU that an instruction has completed. */
464 void instDone(DynInstPtr inst, ThreadID tid);
465
466 /** Add Instructions to the CPU Remove List*/
467 void addToRemoveList(DynInstPtr &inst);
468
469 /** Remove an instruction from CPU */
470 void removeInst(DynInstPtr &inst);
471
472 /** Remove all instructions younger than the given sequence number. */
473 void removeInstsUntil(const InstSeqNum &seq_num,ThreadID tid);
474
475 /** Removes the instruction pointed to by the iterator. */
476 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
477
478 /** Cleans up all instructions on the instruction remove list. */
479 void cleanUpRemovedInsts();
480
481 /** Cleans up all instructions on the request remove list. */
482 void cleanUpRemovedReqs();
483
484 /** Cleans up all instructions on the CPU event remove list. */
485 void cleanUpRemovedEvents();
486
487 /** Debug function to print all instructions on the list. */
488 void dumpInsts();
489
490 /** Forwards an instruction read to the appropriate data
491 * resource (indexes into Resource Pool thru "dataPortIdx")
492 */
493 template <class T>
494 Fault read(DynInstPtr inst, Addr addr, T &data, unsigned flags);
495
496 /** Forwards an instruction write. to the appropriate data
497 * resource (indexes into Resource Pool thru "dataPortIdx")
498 */
499 template <class T>
500 Fault write(DynInstPtr inst, T data, Addr addr, unsigned flags,
501 uint64_t *write_res = NULL);
502
503 /** Forwards an instruction prefetch to the appropriate data
504 * resource (indexes into Resource Pool thru "dataPortIdx")
505 */
506 void prefetch(DynInstPtr inst);
507
508 /** Forwards an instruction writeHint to the appropriate data
509 * resource (indexes into Resource Pool thru "dataPortIdx")
510 */
511 void writeHint(DynInstPtr inst);
512
513 /** Executes a syscall.*/
514 void syscall(int64_t callnum, ThreadID tid);
515
516 public:
517 /** Per-Thread List of all the instructions in flight. */
518 std::list<DynInstPtr> instList[ThePipeline::MaxThreads];
519
520 /** List of all the instructions that will be removed at the end of this
521 * cycle.
522 */
523 std::queue<ListIt> removeList;
524
525 /** List of all the resource requests that will be removed at the end of this
526 * cycle.
527 */
528 std::queue<ResourceRequest*> reqRemoveList;
529
530 /** List of all the cpu event requests that will be removed at the end of
531 * the current cycle.
532 */
533 std::queue<Event*> cpuEventRemoveList;
534
535 /** Records if instructions need to be removed this cycle due to
536 * being retired or squashed.
537 */
538 bool removeInstsThisCycle;
539
540 /** True if there is non-speculative Inst Active In Pipeline. Lets any
541 * execution unit know, NOT to execute while the instruction is active.
542 */
543 bool nonSpecInstActive[ThePipeline::MaxThreads];
544
545 /** Instruction Seq. Num of current non-speculative instruction. */
546 InstSeqNum nonSpecSeqNum[ThePipeline::MaxThreads];
547
548 /** Instruction Seq. Num of last instruction squashed in pipeline */
549 InstSeqNum squashSeqNum[ThePipeline::MaxThreads];
550
551 /** Last Cycle that the CPU squashed instruction end. */
552 Tick lastSquashCycle[ThePipeline::MaxThreads];
553
554 std::list<ThreadID> fetchPriorityList;
555
556 protected:
557 /** Active Threads List */
558 std::list<ThreadID> activeThreads;
559
560 /** Current Threads List */
561 std::list<ThreadID> currentThreads;
562
563 /** Suspended Threads List */
564 std::list<ThreadID> suspendedThreads;
565
566 /** Thread Status Functions (Unused Currently) */
567 bool isThreadInCPU(ThreadID tid);
568 bool isThreadActive(ThreadID tid);
569 bool isThreadSuspended(ThreadID tid);
570 void addToCurrentThreads(ThreadID tid);
571 void removeFromCurrentThreads(ThreadID tid);
572
573 private:
574 /** The activity recorder; used to tell if the CPU has any
575 * activity remaining or if it can go to idle and deschedule
576 * itself.
577 */
578 ActivityRecorder activityRec;
579
580 public:
581 void readFunctional(Addr addr, uint32_t &buffer);
582
583 /** Number of Active Threads in the CPU */
584 ThreadID numActiveThreads() { return activeThreads.size(); }
585
586 /** Records that there was time buffer activity this cycle. */
587 void activityThisCycle() { activityRec.activity(); }
588
589 /** Changes a stage's status to active within the activity recorder. */
590 void activateStage(const int idx)
591 { activityRec.activateStage(idx); }
592
593 /** Changes a stage's status to inactive within the activity recorder. */
594 void deactivateStage(const int idx)
595 { activityRec.deactivateStage(idx); }
596
597 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
598 void wakeCPU();
599
600 /** Gets a free thread id. Use if thread ids change across system. */
601 ThreadID getFreeTid();
602
603 // LL/SC debug functionality
604 unsigned stCondFails;
605 unsigned readStCondFailures() { return stCondFails; }
606 unsigned setStCondFailures(unsigned st_fails) { return stCondFails = st_fails; }
607
608 /** Returns a pointer to a thread context. */
609 ThreadContext *tcBase(ThreadID tid = 0)
610 {
611 return thread[tid]->getTC();
612 }
613
614 /** Count the Total Instructions Committed in the CPU. */
615 virtual Counter totalInstructions() const
616 {
617 Counter total(0);
618
619 for (ThreadID tid = 0; tid < (ThreadID)thread.size(); tid++)
620 total += thread[tid]->numInst;
621
622 return total;
623 }
624
625 /** The global sequence number counter. */
626 InstSeqNum globalSeqNum[ThePipeline::MaxThreads];
627
628 /** The global event number counter. */
629 InstSeqNum cpuEventNum;
630
631 /** Counter of how many stages have completed switching out. */
632 int switchCount;
633
634 /** Pointers to all of the threads in the CPU. */
635 std::vector<Thread *> thread;
636
637 /** Pointer to the icache interface. */
638 MemInterface *icacheInterface;
639
640 /** Pointer to the dcache interface. */
641 MemInterface *dcacheInterface;
642
643 /** Whether or not the CPU should defer its registration. */
644 bool deferRegistration;
645
646 /** Per-Stage Instruction Tracing */
647 bool stageTracing;
648
649 /** Is there a context switch pending? */
650 bool contextSwitch;
651
652 /** Threads Scheduled to Enter CPU */
653 std::list<int> cpuWaitList;
654
655 /** The cycle that the CPU was last running, used for statistics. */
656 Tick lastRunningCycle;
657
658 /** Number of Virtual Processors the CPU can process */
659 unsigned numVirtProcs;
660
661 /** Update Thread , used for statistic purposes*/
662 inline void tickThreadStats();
663
664 /** Per-Thread Tick */
665 Stats::Vector threadCycles;
666
667 /** Tick for SMT */
668 Stats::Scalar smtCycles;
669
670 /** Stat for total number of times the CPU is descheduled. */
671 Stats::Scalar timesIdled;
672
673 /** Stat for total number of cycles the CPU spends descheduled. */
674 Stats::Scalar idleCycles;
675
676 /** Stat for the number of committed instructions per thread. */
677 Stats::Vector committedInsts;
678
679 /** Stat for the number of committed instructions per thread. */
680 Stats::Vector smtCommittedInsts;
681
682 /** Stat for the total number of committed instructions. */
683 Stats::Scalar totalCommittedInsts;
684
685 /** Stat for the CPI per thread. */
686 Stats::Formula cpi;
687
688 /** Stat for the SMT-CPI per thread. */
689 Stats::Formula smtCpi;
690
691 /** Stat for the total CPI. */
692 Stats::Formula totalCpi;
693
694 /** Stat for the IPC per thread. */
695 Stats::Formula ipc;
696
697 /** Stat for the total IPC. */
698 Stats::Formula smtIpc;
699
700 /** Stat for the total IPC. */
701 Stats::Formula totalIpc;
702 };
703
704 #endif // __CPU_O3_CPU_HH__