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