types: add a type for thread IDs and try to use it everywhere
[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 "base/statistics.hh"
43 #include "base/timebuf.hh"
44 #include "base/types.hh"
45 #include "config/full_system.hh"
46 #include "cpu/activity.hh"
47 #include "cpu/base.hh"
48 #include "cpu/simple_thread.hh"
49 #include "cpu/inorder/inorder_dyn_inst.hh"
50 #include "cpu/inorder/pipeline_traits.hh"
51 #include "cpu/inorder/pipeline_stage.hh"
52 #include "cpu/inorder/thread_state.hh"
53 #include "cpu/inorder/reg_dep_map.hh"
54 #include "cpu/o3/dep_graph.hh"
55 #include "cpu/o3/rename_map.hh"
56 #include "mem/packet.hh"
57 #include "mem/port.hh"
58 #include "mem/request.hh"
59 #include "sim/eventq.hh"
60 #include "sim/process.hh"
61
62 class ThreadContext;
63 class MemInterface;
64 class MemObject;
65 class Process;
66 class ResourcePool;
67
68 class InOrderCPU : public BaseCPU
69 {
70
71 protected:
72 typedef ThePipeline::Params Params;
73 typedef InOrderThreadState Thread;
74
75 //ISA TypeDefs
76 typedef TheISA::IntReg IntReg;
77 typedef TheISA::FloatReg FloatReg;
78 typedef TheISA::FloatRegBits FloatRegBits;
79 typedef TheISA::MiscReg MiscReg;
80 typedef TheISA::RegFile RegFile;
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 TheISA::IntRegFile intRegFile[ThePipeline::MaxThreads];;
261 TheISA::FloatRegFile floatRegFile[ThePipeline::MaxThreads];;
262 TheISA::MiscRegFile miscRegFile;
263
264 /** Dependency Tracker for Integer & Floating Point Regs */
265 RegDepMap archRegDepMap[ThePipeline::MaxThreads];
266
267 /** Global communication structure */
268 TimeBuffer<TimeStruct> timeBuffer;
269
270 /** Communication structure that sits in between pipeline stages */
271 StageQueue *stageQueue[ThePipeline::NumStages-1];
272
273 TheISA::TLB *getITBPtr();
274 TheISA::TLB *getDTBPtr();
275
276 public:
277
278 /** Registers statistics. */
279 void regStats();
280
281 /** Ticks CPU, calling tick() on each stage, and checking the overall
282 * activity to see if the CPU should deschedule itself.
283 */
284 void tick();
285
286 /** Initialize the CPU */
287 void init();
288
289 /** Reset State in the CPU */
290 void reset();
291
292 /** Get a Memory Port */
293 Port* getPort(const std::string &if_name, int idx = 0);
294
295 /** trap() - sets up a trap event on the cpuTraps to handle given fault.
296 * trapCPU() - Traps to handle given fault
297 */
298 void trap(Fault fault, ThreadID tid, int delay = 0);
299 void trapCPU(Fault fault, ThreadID tid);
300
301 /** Setup CPU to insert a thread's context */
302 void insertThread(ThreadID tid);
303
304 /** Remove all of a thread's context from CPU */
305 void removeThread(ThreadID tid);
306
307 /** Add Thread to Active Threads List. */
308 void activateContext(ThreadID tid, int delay = 0);
309 void activateThread(ThreadID tid);
310
311 /** Remove Thread from Active Threads List */
312 void suspendContext(ThreadID tid, int delay = 0);
313 void suspendThread(ThreadID tid);
314
315 /** Remove Thread from Active Threads List &&
316 * Remove Thread Context from CPU.
317 */
318 void deallocateContext(ThreadID tid, int delay = 0);
319 void deallocateThread(ThreadID tid);
320 void deactivateThread(ThreadID tid);
321
322 PipelineStage* getPipeStage(int stage_num);
323
324 int
325 contextId()
326 {
327 hack_once("return a bogus context id");
328 return 0;
329 }
330
331 /** Remove Thread from Active Threads List &&
332 * Remove Thread Context from CPU.
333 */
334 void haltContext(ThreadID tid, int delay = 0);
335
336 void removePipelineStalls(ThreadID tid);
337
338 void squashThreadInPipeline(ThreadID tid);
339
340 /// Notify the CPU to enable a virtual processor element.
341 virtual void enableVirtProcElement(unsigned vpe);
342 void enableVPEs(unsigned vpe);
343
344 /// Notify the CPU to disable a virtual processor element.
345 virtual void disableVirtProcElement(ThreadID tid, unsigned vpe);
346 void disableVPEs(ThreadID tid, unsigned vpe);
347
348 /// Notify the CPU that multithreading is enabled.
349 virtual void enableMultiThreading(unsigned vpe);
350 void enableThreads(unsigned vpe);
351
352 /// Notify the CPU that multithreading is disabled.
353 virtual void disableMultiThreading(ThreadID tid, unsigned vpe);
354 void disableThreads(ThreadID tid, unsigned vpe);
355
356 /** Activate a Thread When CPU Resources are Available. */
357 void activateWhenReady(ThreadID tid);
358
359 /** Add or Remove a Thread Context in the CPU. */
360 void doContextSwitch();
361
362 /** Update The Order In Which We Process Threads. */
363 void updateThreadPriority();
364
365 /** Switches a Pipeline Stage to Active. (Unused currently) */
366 void switchToActive(int stage_idx)
367 { /*pipelineStage[stage_idx]->switchToActive();*/ }
368
369 /** Get the current instruction sequence number, and increment it. */
370 InstSeqNum getAndIncrementInstSeq(ThreadID tid)
371 { return globalSeqNum[tid]++; }
372
373 /** Get the current instruction sequence number, and increment it. */
374 InstSeqNum nextInstSeqNum(ThreadID tid)
375 { return globalSeqNum[tid]; }
376
377 /** Increment Instruction Sequence Number */
378 void incrInstSeqNum(ThreadID tid)
379 { globalSeqNum[tid]++; }
380
381 /** Set Instruction Sequence Number */
382 void setInstSeqNum(ThreadID tid, InstSeqNum seq_num)
383 {
384 globalSeqNum[tid] = seq_num;
385 }
386
387 /** Get & Update Next Event Number */
388 InstSeqNum getNextEventNum()
389 {
390 return cpuEventNum++;
391 }
392
393 /** Get instruction asid. */
394 int getInstAsid(ThreadID tid)
395 { return thread[tid]->getInstAsid(); }
396
397 /** Get data asid. */
398 int getDataAsid(ThreadID tid)
399 { return thread[tid]->getDataAsid(); }
400
401 /** Register file accessors */
402 uint64_t readIntReg(int reg_idx, ThreadID tid);
403
404 FloatReg readFloatReg(int reg_idx, ThreadID tid,
405 int width = TheISA::SingleWidth);
406
407 FloatRegBits readFloatRegBits(int reg_idx, ThreadID tid,
408 int width = TheISA::SingleWidth);
409
410 void setIntReg(int reg_idx, uint64_t val, ThreadID tid);
411
412 void setFloatReg(int reg_idx, FloatReg val, ThreadID tid,
413 int width = TheISA::SingleWidth);
414
415 void setFloatRegBits(int reg_idx, FloatRegBits val, ThreadID tid,
416 int width = TheISA::SingleWidth);
417
418 /** Reads a miscellaneous register. */
419 MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid = 0);
420
421 /** Reads a misc. register, including any side effects the read
422 * might have as defined by the architecture.
423 */
424 MiscReg readMiscReg(int misc_reg, ThreadID tid = 0);
425
426 /** Sets a miscellaneous register. */
427 void setMiscRegNoEffect(int misc_reg, const MiscReg &val,
428 ThreadID tid = 0);
429
430 /** Sets a misc. register, including any side effects the write
431 * might have as defined by the architecture.
432 */
433 void setMiscReg(int misc_reg, const MiscReg &val, ThreadID tid = 0);
434
435 /** Reads a int/fp/misc reg. from another thread depending on ISA-defined
436 * target thread
437 */
438 uint64_t readRegOtherThread(unsigned misc_reg,
439 ThreadID tid = InvalidThreadID);
440
441 /** Sets a int/fp/misc reg. from another thread depending on an ISA-defined
442 * target thread
443 */
444 void setRegOtherThread(unsigned misc_reg, const MiscReg &val,
445 ThreadID tid);
446
447 /** Reads the commit PC of a specific thread. */
448 uint64_t readPC(ThreadID tid);
449
450 /** Sets the commit PC of a specific thread. */
451 void setPC(Addr new_PC, ThreadID tid);
452
453 /** Reads the next PC of a specific thread. */
454 uint64_t readNextPC(ThreadID tid);
455
456 /** Sets the next PC of a specific thread. */
457 void setNextPC(uint64_t val, ThreadID tid);
458
459 /** Reads the next NPC of a specific thread. */
460 uint64_t readNextNPC(ThreadID tid);
461
462 /** Sets the next NPC of a specific thread. */
463 void setNextNPC(uint64_t val, ThreadID tid);
464
465 /** Function to add instruction onto the head of the list of the
466 * instructions. Used when new instructions are fetched.
467 */
468 ListIt addInst(DynInstPtr &inst);
469
470 /** Function to tell the CPU that an instruction has completed. */
471 void instDone(DynInstPtr inst, ThreadID tid);
472
473 /** Add Instructions to the CPU Remove List*/
474 void addToRemoveList(DynInstPtr &inst);
475
476 /** Remove an instruction from CPU */
477 void removeInst(DynInstPtr &inst);
478
479 /** Remove all instructions younger than the given sequence number. */
480 void removeInstsUntil(const InstSeqNum &seq_num,ThreadID tid);
481
482 /** Removes the instruction pointed to by the iterator. */
483 inline void squashInstIt(const ListIt &instIt, ThreadID tid);
484
485 /** Cleans up all instructions on the instruction remove list. */
486 void cleanUpRemovedInsts();
487
488 /** Cleans up all instructions on the request remove list. */
489 void cleanUpRemovedReqs();
490
491 /** Cleans up all instructions on the CPU event remove list. */
492 void cleanUpRemovedEvents();
493
494 /** Debug function to print all instructions on the list. */
495 void dumpInsts();
496
497 /** Forwards an instruction read to the appropriate data
498 * resource (indexes into Resource Pool thru "dataPortIdx")
499 */
500 template <class T>
501 Fault read(DynInstPtr inst, Addr addr, T &data, unsigned flags);
502
503 /** Forwards an instruction write. to the appropriate data
504 * resource (indexes into Resource Pool thru "dataPortIdx")
505 */
506 template <class T>
507 Fault write(DynInstPtr inst, T data, Addr addr, unsigned flags,
508 uint64_t *write_res = NULL);
509
510 /** Forwards an instruction prefetch to the appropriate data
511 * resource (indexes into Resource Pool thru "dataPortIdx")
512 */
513 void prefetch(DynInstPtr inst);
514
515 /** Forwards an instruction writeHint to the appropriate data
516 * resource (indexes into Resource Pool thru "dataPortIdx")
517 */
518 void writeHint(DynInstPtr inst);
519
520 /** Executes a syscall.*/
521 void syscall(int64_t callnum, ThreadID tid);
522
523 public:
524 /** Per-Thread List of all the instructions in flight. */
525 std::list<DynInstPtr> instList[ThePipeline::MaxThreads];
526
527 /** List of all the instructions that will be removed at the end of this
528 * cycle.
529 */
530 std::queue<ListIt> removeList;
531
532 /** List of all the resource requests that will be removed at the end of this
533 * cycle.
534 */
535 std::queue<ResourceRequest*> reqRemoveList;
536
537 /** List of all the cpu event requests that will be removed at the end of
538 * the current cycle.
539 */
540 std::queue<Event*> cpuEventRemoveList;
541
542 /** Records if instructions need to be removed this cycle due to
543 * being retired or squashed.
544 */
545 bool removeInstsThisCycle;
546
547 /** True if there is non-speculative Inst Active In Pipeline. Lets any
548 * execution unit know, NOT to execute while the instruction is active.
549 */
550 bool nonSpecInstActive[ThePipeline::MaxThreads];
551
552 /** Instruction Seq. Num of current non-speculative instruction. */
553 InstSeqNum nonSpecSeqNum[ThePipeline::MaxThreads];
554
555 /** Instruction Seq. Num of last instruction squashed in pipeline */
556 InstSeqNum squashSeqNum[ThePipeline::MaxThreads];
557
558 /** Last Cycle that the CPU squashed instruction end. */
559 Tick lastSquashCycle[ThePipeline::MaxThreads];
560
561 std::list<ThreadID> fetchPriorityList;
562
563 protected:
564 /** Active Threads List */
565 std::list<ThreadID> activeThreads;
566
567 /** Current Threads List */
568 std::list<ThreadID> currentThreads;
569
570 /** Suspended Threads List */
571 std::list<ThreadID> suspendedThreads;
572
573 /** Thread Status Functions (Unused Currently) */
574 bool isThreadInCPU(ThreadID tid);
575 bool isThreadActive(ThreadID tid);
576 bool isThreadSuspended(ThreadID tid);
577 void addToCurrentThreads(ThreadID tid);
578 void removeFromCurrentThreads(ThreadID tid);
579
580 private:
581 /** The activity recorder; used to tell if the CPU has any
582 * activity remaining or if it can go to idle and deschedule
583 * itself.
584 */
585 ActivityRecorder activityRec;
586
587 public:
588 void readFunctional(Addr addr, uint32_t &buffer);
589
590 /** Number of Active Threads in the CPU */
591 ThreadID numActiveThreads() { return activeThreads.size(); }
592
593 /** Records that there was time buffer activity this cycle. */
594 void activityThisCycle() { activityRec.activity(); }
595
596 /** Changes a stage's status to active within the activity recorder. */
597 void activateStage(const int idx)
598 { activityRec.activateStage(idx); }
599
600 /** Changes a stage's status to inactive within the activity recorder. */
601 void deactivateStage(const int idx)
602 { activityRec.deactivateStage(idx); }
603
604 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
605 void wakeCPU();
606
607 /** Gets a free thread id. Use if thread ids change across system. */
608 ThreadID getFreeTid();
609
610 // LL/SC debug functionality
611 unsigned stCondFails;
612 unsigned readStCondFailures() { return stCondFails; }
613 unsigned setStCondFailures(unsigned st_fails) { return stCondFails = st_fails; }
614
615 /** Returns a pointer to a thread context. */
616 ThreadContext *tcBase(ThreadID tid = 0)
617 {
618 return thread[tid]->getTC();
619 }
620
621 /** Count the Total Instructions Committed in the CPU. */
622 virtual Counter totalInstructions() const
623 {
624 Counter total(0);
625
626 for (ThreadID tid = 0; tid < thread.size(); tid++)
627 total += thread[tid]->numInst;
628
629 return total;
630 }
631
632 /** The global sequence number counter. */
633 InstSeqNum globalSeqNum[ThePipeline::MaxThreads];
634
635 /** The global event number counter. */
636 InstSeqNum cpuEventNum;
637
638 /** Counter of how many stages have completed switching out. */
639 int switchCount;
640
641 /** Pointers to all of the threads in the CPU. */
642 std::vector<Thread *> thread;
643
644 /** Pointer to the icache interface. */
645 MemInterface *icacheInterface;
646
647 /** Pointer to the dcache interface. */
648 MemInterface *dcacheInterface;
649
650 /** Whether or not the CPU should defer its registration. */
651 bool deferRegistration;
652
653 /** Per-Stage Instruction Tracing */
654 bool stageTracing;
655
656 /** Is there a context switch pending? */
657 bool contextSwitch;
658
659 /** Threads Scheduled to Enter CPU */
660 std::list<int> cpuWaitList;
661
662 /** The cycle that the CPU was last running, used for statistics. */
663 Tick lastRunningCycle;
664
665 /** Number of Virtual Processors the CPU can process */
666 unsigned numVirtProcs;
667
668 /** Update Thread , used for statistic purposes*/
669 inline void tickThreadStats();
670
671 /** Per-Thread Tick */
672 Stats::Vector threadCycles;
673
674 /** Tick for SMT */
675 Stats::Scalar smtCycles;
676
677 /** Stat for total number of times the CPU is descheduled. */
678 Stats::Scalar timesIdled;
679
680 /** Stat for total number of cycles the CPU spends descheduled. */
681 Stats::Scalar idleCycles;
682
683 /** Stat for the number of committed instructions per thread. */
684 Stats::Vector committedInsts;
685
686 /** Stat for the number of committed instructions per thread. */
687 Stats::Vector smtCommittedInsts;
688
689 /** Stat for the total number of committed instructions. */
690 Stats::Scalar totalCommittedInsts;
691
692 /** Stat for the CPI per thread. */
693 Stats::Formula cpi;
694
695 /** Stat for the SMT-CPI per thread. */
696 Stats::Formula smtCpi;
697
698 /** Stat for the total CPI. */
699 Stats::Formula totalCpi;
700
701 /** Stat for the IPC per thread. */
702 Stats::Formula ipc;
703
704 /** Stat for the total IPC. */
705 Stats::Formula smtIpc;
706
707 /** Stat for the total IPC. */
708 Stats::Formula totalIpc;
709 };
710
711 #endif // __CPU_O3_CPU_HH__