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