Move the "translate" member functions back into the base o3 class.
[gem5.git] / src / cpu / o3 / cpu.hh
1 /*
2 * Copyright (c) 2004-2005 The Regents of The University of Michigan
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: Kevin Lim
29 * Korey Sewell
30 */
31
32 #ifndef __CPU_O3_CPU_HH__
33 #define __CPU_O3_CPU_HH__
34
35 #include <iostream>
36 #include <list>
37 #include <queue>
38 #include <set>
39 #include <vector>
40
41 #include "arch/types.hh"
42 #include "base/statistics.hh"
43 #include "base/timebuf.hh"
44 #include "config/full_system.hh"
45 #include "config/use_checker.hh"
46 #include "cpu/activity.hh"
47 #include "cpu/base.hh"
48 #include "cpu/simple_thread.hh"
49 #include "cpu/o3/comm.hh"
50 #include "cpu/o3/cpu_policy.hh"
51 #include "cpu/o3/scoreboard.hh"
52 #include "cpu/o3/thread_state.hh"
53 //#include "cpu/o3/thread_context.hh"
54 #include "sim/process.hh"
55
56 template <class>
57 class Checker;
58 class ThreadContext;
59 template <class>
60 class O3ThreadContext;
61
62 class Checkpoint;
63 class MemObject;
64 class Process;
65
66 class BaseO3CPU : public BaseCPU
67 {
68 //Stuff that's pretty ISA independent will go here.
69 public:
70 typedef BaseCPU::Params Params;
71
72 BaseO3CPU(Params *params);
73
74 void regStats();
75
76 /** Sets this CPU's ID. */
77 void setCpuId(int id) { cpu_id = id; }
78
79 /** Reads this CPU's ID. */
80 int readCpuId() { return cpu_id; }
81
82 protected:
83 int cpu_id;
84 };
85
86 /**
87 * FullO3CPU class, has each of the stages (fetch through commit)
88 * within it, as well as all of the time buffers between stages. The
89 * tick() function for the CPU is defined here.
90 */
91 template <class Impl>
92 class FullO3CPU : public BaseO3CPU
93 {
94 public:
95 // Typedefs from the Impl here.
96 typedef typename Impl::CPUPol CPUPolicy;
97 typedef typename Impl::DynInstPtr DynInstPtr;
98 typedef typename Impl::O3CPU O3CPU;
99 typedef typename Impl::Params Params;
100
101 typedef O3ThreadState<Impl> Thread;
102
103 typedef typename std::list<DynInstPtr>::iterator ListIt;
104
105 friend class O3ThreadContext<Impl>;
106
107 public:
108 enum Status {
109 Running,
110 Idle,
111 Halted,
112 Blocked,
113 SwitchedOut
114 };
115
116 #if FULL_SYSTEM
117 TheISA::ITB * itb;
118 TheISA::DTB * dtb;
119 #endif
120
121 /** Overall CPU status. */
122 Status _status;
123
124 /** Per-thread status in CPU, used for SMT. */
125 Status _threadStatus[Impl::MaxThreads];
126
127 private:
128 class TickEvent : public Event
129 {
130 private:
131 /** Pointer to the CPU. */
132 FullO3CPU<Impl> *cpu;
133
134 public:
135 /** Constructs a tick event. */
136 TickEvent(FullO3CPU<Impl> *c);
137
138 /** Processes a tick event, calling tick() on the CPU. */
139 void process();
140 /** Returns the description of the tick event. */
141 const char *description();
142 };
143
144 /** The tick event used for scheduling CPU ticks. */
145 TickEvent tickEvent;
146
147 /** Schedule tick event, regardless of its current state. */
148 void scheduleTickEvent(int delay)
149 {
150 if (tickEvent.squashed())
151 tickEvent.reschedule(nextCycle(curTick + cycles(delay)));
152 else if (!tickEvent.scheduled())
153 tickEvent.schedule(nextCycle(curTick + cycles(delay)));
154 }
155
156 /** Unschedule tick event, regardless of its current state. */
157 void unscheduleTickEvent()
158 {
159 if (tickEvent.scheduled())
160 tickEvent.squash();
161 }
162
163 class ActivateThreadEvent : public Event
164 {
165 private:
166 /** Number of Thread to Activate */
167 int tid;
168
169 /** Pointer to the CPU. */
170 FullO3CPU<Impl> *cpu;
171
172 public:
173 /** Constructs the event. */
174 ActivateThreadEvent();
175
176 /** Initialize Event */
177 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
178
179 /** Processes the event, calling activateThread() on the CPU. */
180 void process();
181
182 /** Returns the description of the event. */
183 const char *description();
184 };
185
186 /** Schedule thread to activate , regardless of its current state. */
187 void scheduleActivateThreadEvent(int tid, int delay)
188 {
189 // Schedule thread to activate, regardless of its current state.
190 if (activateThreadEvent[tid].squashed())
191 activateThreadEvent[tid].
192 reschedule(nextCycle(curTick + cycles(delay)));
193 else if (!activateThreadEvent[tid].scheduled())
194 activateThreadEvent[tid].
195 schedule(nextCycle(curTick + cycles(delay)));
196 }
197
198 /** Unschedule actiavte thread event, regardless of its current state. */
199 void unscheduleActivateThreadEvent(int tid)
200 {
201 if (activateThreadEvent[tid].scheduled())
202 activateThreadEvent[tid].squash();
203 }
204
205 /** The tick event used for scheduling CPU ticks. */
206 ActivateThreadEvent activateThreadEvent[Impl::MaxThreads];
207
208 class DeallocateContextEvent : public Event
209 {
210 private:
211 /** Number of Thread to deactivate */
212 int tid;
213
214 /** Should the thread be removed from the CPU? */
215 bool remove;
216
217 /** Pointer to the CPU. */
218 FullO3CPU<Impl> *cpu;
219
220 public:
221 /** Constructs the event. */
222 DeallocateContextEvent();
223
224 /** Initialize Event */
225 void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
226
227 /** Processes the event, calling activateThread() on the CPU. */
228 void process();
229
230 /** Sets whether the thread should also be removed from the CPU. */
231 void setRemove(bool _remove) { remove = _remove; }
232
233 /** Returns the description of the event. */
234 const char *description();
235 };
236
237 /** Schedule cpu to deallocate thread context.*/
238 void scheduleDeallocateContextEvent(int tid, bool remove, int delay)
239 {
240 // Schedule thread to activate, regardless of its current state.
241 if (deallocateContextEvent[tid].squashed())
242 deallocateContextEvent[tid].
243 reschedule(nextCycle(curTick + cycles(delay)));
244 else if (!deallocateContextEvent[tid].scheduled())
245 deallocateContextEvent[tid].
246 schedule(nextCycle(curTick + cycles(delay)));
247 }
248
249 /** Unschedule thread deallocation in CPU */
250 void unscheduleDeallocateContextEvent(int tid)
251 {
252 if (deallocateContextEvent[tid].scheduled())
253 deallocateContextEvent[tid].squash();
254 }
255
256 /** The tick event used for scheduling CPU ticks. */
257 DeallocateContextEvent deallocateContextEvent[Impl::MaxThreads];
258
259 public:
260 /** Constructs a CPU with the given parameters. */
261 FullO3CPU(O3CPU *o3_cpu, Params *params);
262 /** Destructor. */
263 ~FullO3CPU();
264
265 /** Registers statistics. */
266 void fullCPURegStats();
267
268 #if FULL_SYSTEM
269 /** Translates instruction requestion. */
270 Fault translateInstReq(RequestPtr &req, Thread *thread)
271 {
272 return this->itb->translate(req, thread->getTC());
273 }
274
275 /** Translates data read request. */
276 Fault translateDataReadReq(RequestPtr &req, Thread *thread)
277 {
278 return this->dtb->translate(req, thread->getTC(), false);
279 }
280
281 /** Translates data write request. */
282 Fault translateDataWriteReq(RequestPtr &req, Thread *thread)
283 {
284 return this->dtb->translate(req, thread->getTC(), true);
285 }
286
287 #else
288 /** Translates instruction requestion in syscall emulation mode. */
289 Fault translateInstReq(RequestPtr &req, Thread *thread)
290 {
291 return thread->getProcessPtr()->pTable->translate(req);
292 }
293
294 /** Translates data read request in syscall emulation mode. */
295 Fault translateDataReadReq(RequestPtr &req, Thread *thread)
296 {
297 return thread->getProcessPtr()->pTable->translate(req);
298 }
299
300 /** Translates data write request in syscall emulation mode. */
301 Fault translateDataWriteReq(RequestPtr &req, Thread *thread)
302 {
303 return thread->getProcessPtr()->pTable->translate(req);
304 }
305
306 #endif
307
308 /** Returns a specific port. */
309 Port *getPort(const std::string &if_name, int idx);
310
311 /** Ticks CPU, calling tick() on each stage, and checking the overall
312 * activity to see if the CPU should deschedule itself.
313 */
314 void tick();
315
316 /** Initialize the CPU */
317 void init();
318
319 /** Returns the Number of Active Threads in the CPU */
320 int numActiveThreads()
321 { return activeThreads.size(); }
322
323 /** Add Thread to Active Threads List */
324 void activateThread(unsigned tid);
325
326 /** Remove Thread from Active Threads List */
327 void deactivateThread(unsigned tid);
328
329 /** Setup CPU to insert a thread's context */
330 void insertThread(unsigned tid);
331
332 /** Remove all of a thread's context from CPU */
333 void removeThread(unsigned tid);
334
335 /** Count the Total Instructions Committed in the CPU. */
336 virtual Counter totalInstructions() const
337 {
338 Counter total(0);
339
340 for (int i=0; i < thread.size(); i++)
341 total += thread[i]->numInst;
342
343 return total;
344 }
345
346 /** Add Thread to Active Threads List. */
347 void activateContext(int tid, int delay);
348
349 /** Remove Thread from Active Threads List */
350 void suspendContext(int tid);
351
352 /** Remove Thread from Active Threads List &&
353 * Possibly Remove Thread Context from CPU.
354 */
355 bool deallocateContext(int tid, bool remove, int delay = 1);
356
357 /** Remove Thread from Active Threads List &&
358 * Remove Thread Context from CPU.
359 */
360 void haltContext(int tid);
361
362 /** Activate a Thread When CPU Resources are Available. */
363 void activateWhenReady(int tid);
364
365 /** Add or Remove a Thread Context in the CPU. */
366 void doContextSwitch();
367
368 /** Update The Order In Which We Process Threads. */
369 void updateThreadPriority();
370
371 /** Serialize state. */
372 virtual void serialize(std::ostream &os);
373
374 /** Unserialize from a checkpoint. */
375 virtual void unserialize(Checkpoint *cp, const std::string &section);
376
377 public:
378 /** Executes a syscall on this cycle.
379 * ---------------------------------------
380 * Note: this is a virtual function. CPU-Specific
381 * functionality defined in derived classes
382 */
383 virtual void syscall(int tid) { panic("Unimplemented!"); }
384
385 /** Starts draining the CPU's pipeline of all instructions in
386 * order to stop all memory accesses. */
387 virtual unsigned int drain(Event *drain_event);
388
389 /** Resumes execution after a drain. */
390 virtual void resume();
391
392 /** Signals to this CPU that a stage has completed switching out. */
393 void signalDrained();
394
395 /** Switches out this CPU. */
396 virtual void switchOut();
397
398 /** Takes over from another CPU. */
399 virtual void takeOverFrom(BaseCPU *oldCPU);
400
401 /** Get the current instruction sequence number, and increment it. */
402 InstSeqNum getAndIncrementInstSeq()
403 { return globalSeqNum++; }
404
405 #if FULL_SYSTEM
406 /** Update the Virt and Phys ports of all ThreadContexts to
407 * reflect change in memory connections. */
408 void updateMemPorts();
409
410 /** Check if this address is a valid instruction address. */
411 bool validInstAddr(Addr addr) { return true; }
412
413 /** Check if this address is a valid data address. */
414 bool validDataAddr(Addr addr) { return true; }
415
416 /** Get instruction asid. */
417 int getInstAsid(unsigned tid)
418 { return regFile.miscRegs[tid].getInstAsid(); }
419
420 /** Get data asid. */
421 int getDataAsid(unsigned tid)
422 { return regFile.miscRegs[tid].getDataAsid(); }
423 #else
424 /** Get instruction asid. */
425 int getInstAsid(unsigned tid)
426 { return thread[tid]->getInstAsid(); }
427
428 /** Get data asid. */
429 int getDataAsid(unsigned tid)
430 { return thread[tid]->getDataAsid(); }
431
432 #endif
433
434 /** Register accessors. Index refers to the physical register index. */
435 uint64_t readIntReg(int reg_idx);
436
437 TheISA::FloatReg readFloatReg(int reg_idx);
438
439 TheISA::FloatReg readFloatReg(int reg_idx, int width);
440
441 TheISA::FloatRegBits readFloatRegBits(int reg_idx);
442
443 TheISA::FloatRegBits readFloatRegBits(int reg_idx, int width);
444
445 void setIntReg(int reg_idx, uint64_t val);
446
447 void setFloatReg(int reg_idx, TheISA::FloatReg val);
448
449 void setFloatReg(int reg_idx, TheISA::FloatReg val, int width);
450
451 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
452
453 void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val, int width);
454
455 uint64_t readArchIntReg(int reg_idx, unsigned tid);
456
457 float readArchFloatRegSingle(int reg_idx, unsigned tid);
458
459 double readArchFloatRegDouble(int reg_idx, unsigned tid);
460
461 uint64_t readArchFloatRegInt(int reg_idx, unsigned tid);
462
463 /** Architectural register accessors. Looks up in the commit
464 * rename table to obtain the true physical index of the
465 * architected register first, then accesses that physical
466 * register.
467 */
468 void setArchIntReg(int reg_idx, uint64_t val, unsigned tid);
469
470 void setArchFloatRegSingle(int reg_idx, float val, unsigned tid);
471
472 void setArchFloatRegDouble(int reg_idx, double val, unsigned tid);
473
474 void setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid);
475
476 /** Reads the commit PC of a specific thread. */
477 Addr readPC(unsigned tid);
478
479 /** Sets the commit PC of a specific thread. */
480 void setPC(Addr new_PC, unsigned tid);
481
482 /** Reads the commit micro PC of a specific thread. */
483 Addr readMicroPC(unsigned tid);
484
485 /** Sets the commmit micro PC of a specific thread. */
486 void setMicroPC(Addr new_microPC, unsigned tid);
487
488 /** Reads the next PC of a specific thread. */
489 Addr readNextPC(unsigned tid);
490
491 /** Sets the next PC of a specific thread. */
492 void setNextPC(Addr val, unsigned tid);
493
494 /** Reads the next NPC of a specific thread. */
495 Addr readNextNPC(unsigned tid);
496
497 /** Sets the next NPC of a specific thread. */
498 void setNextNPC(Addr val, unsigned tid);
499
500 /** Reads the commit next micro PC of a specific thread. */
501 Addr readNextMicroPC(unsigned tid);
502
503 /** Sets the commit next micro PC of a specific thread. */
504 void setNextMicroPC(Addr val, unsigned tid);
505
506 /** Function to add instruction onto the head of the list of the
507 * instructions. Used when new instructions are fetched.
508 */
509 ListIt addInst(DynInstPtr &inst);
510
511 /** Function to tell the CPU that an instruction has completed. */
512 void instDone(unsigned tid);
513
514 /** Add Instructions to the CPU Remove List*/
515 void addToRemoveList(DynInstPtr &inst);
516
517 /** Remove an instruction from the front end of the list. There's
518 * no restriction on location of the instruction.
519 */
520 void removeFrontInst(DynInstPtr &inst);
521
522 /** Remove all instructions that are not currently in the ROB.
523 * There's also an option to not squash delay slot instructions.*/
524 void removeInstsNotInROB(unsigned tid);
525
526 /** Remove all instructions younger than the given sequence number. */
527 void removeInstsUntil(const InstSeqNum &seq_num,unsigned tid);
528
529 /** Removes the instruction pointed to by the iterator. */
530 inline void squashInstIt(const ListIt &instIt, const unsigned &tid);
531
532 /** Cleans up all instructions on the remove list. */
533 void cleanUpRemovedInsts();
534
535 /** Debug function to print all instructions on the list. */
536 void dumpInsts();
537
538 public:
539 /** List of all the instructions in flight. */
540 std::list<DynInstPtr> instList;
541
542 /** List of all the instructions that will be removed at the end of this
543 * cycle.
544 */
545 std::queue<ListIt> removeList;
546
547 #ifdef DEBUG
548 /** Debug structure to keep track of the sequence numbers still in
549 * flight.
550 */
551 std::set<InstSeqNum> snList;
552 #endif
553
554 /** Records if instructions need to be removed this cycle due to
555 * being retired or squashed.
556 */
557 bool removeInstsThisCycle;
558
559 protected:
560 /** The fetch stage. */
561 typename CPUPolicy::Fetch fetch;
562
563 /** The decode stage. */
564 typename CPUPolicy::Decode decode;
565
566 /** The dispatch stage. */
567 typename CPUPolicy::Rename rename;
568
569 /** The issue/execute/writeback stages. */
570 typename CPUPolicy::IEW iew;
571
572 /** The commit stage. */
573 typename CPUPolicy::Commit commit;
574
575 /** The register file. */
576 typename CPUPolicy::RegFile regFile;
577
578 /** The free list. */
579 typename CPUPolicy::FreeList freeList;
580
581 /** The rename map. */
582 typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
583
584 /** The commit rename map. */
585 typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
586
587 /** The re-order buffer. */
588 typename CPUPolicy::ROB rob;
589
590 /** Active Threads List */
591 std::list<unsigned> activeThreads;
592
593 /** Integer Register Scoreboard */
594 Scoreboard scoreboard;
595
596 public:
597 /** Enum to give each stage a specific index, so when calling
598 * activateStage() or deactivateStage(), they can specify which stage
599 * is being activated/deactivated.
600 */
601 enum StageIdx {
602 FetchIdx,
603 DecodeIdx,
604 RenameIdx,
605 IEWIdx,
606 CommitIdx,
607 NumStages };
608
609 /** Typedefs from the Impl to get the structs that each of the
610 * time buffers should use.
611 */
612 typedef typename CPUPolicy::TimeStruct TimeStruct;
613
614 typedef typename CPUPolicy::FetchStruct FetchStruct;
615
616 typedef typename CPUPolicy::DecodeStruct DecodeStruct;
617
618 typedef typename CPUPolicy::RenameStruct RenameStruct;
619
620 typedef typename CPUPolicy::IEWStruct IEWStruct;
621
622 /** The main time buffer to do backwards communication. */
623 TimeBuffer<TimeStruct> timeBuffer;
624
625 /** The fetch stage's instruction queue. */
626 TimeBuffer<FetchStruct> fetchQueue;
627
628 /** The decode stage's instruction queue. */
629 TimeBuffer<DecodeStruct> decodeQueue;
630
631 /** The rename stage's instruction queue. */
632 TimeBuffer<RenameStruct> renameQueue;
633
634 /** The IEW stage's instruction queue. */
635 TimeBuffer<IEWStruct> iewQueue;
636
637 private:
638 /** The activity recorder; used to tell if the CPU has any
639 * activity remaining or if it can go to idle and deschedule
640 * itself.
641 */
642 ActivityRecorder activityRec;
643
644 public:
645 /** Records that there was time buffer activity this cycle. */
646 void activityThisCycle() { activityRec.activity(); }
647
648 /** Changes a stage's status to active within the activity recorder. */
649 void activateStage(const StageIdx idx)
650 { activityRec.activateStage(idx); }
651
652 /** Changes a stage's status to inactive within the activity recorder. */
653 void deactivateStage(const StageIdx idx)
654 { activityRec.deactivateStage(idx); }
655
656 /** Wakes the CPU, rescheduling the CPU if it's not already active. */
657 void wakeCPU();
658
659 /** Gets a free thread id. Use if thread ids change across system. */
660 int getFreeTid();
661
662 public:
663 /** Returns a pointer to a thread context. */
664 ThreadContext *tcBase(unsigned tid)
665 {
666 return thread[tid]->getTC();
667 }
668
669 /** The global sequence number counter. */
670 InstSeqNum globalSeqNum;//[Impl::MaxThreads];
671
672 #if USE_CHECKER
673 /** Pointer to the checker, which can dynamically verify
674 * instruction results at run time. This can be set to NULL if it
675 * is not being used.
676 */
677 Checker<DynInstPtr> *checker;
678 #endif
679
680 #if FULL_SYSTEM
681 /** Pointer to the system. */
682 System *system;
683
684 /** Pointer to physical memory. */
685 PhysicalMemory *physmem;
686 #endif
687
688 /** Event to call process() on once draining has completed. */
689 Event *drainEvent;
690
691 /** Counter of how many stages have completed draining. */
692 int drainCount;
693
694 /** Pointers to all of the threads in the CPU. */
695 std::vector<Thread *> thread;
696
697 /** Whether or not the CPU should defer its registration. */
698 bool deferRegistration;
699
700 /** Is there a context switch pending? */
701 bool contextSwitch;
702
703 /** Threads Scheduled to Enter CPU */
704 std::list<int> cpuWaitList;
705
706 /** The cycle that the CPU was last running, used for statistics. */
707 Tick lastRunningCycle;
708
709 /** The cycle that the CPU was last activated by a new thread*/
710 Tick lastActivatedCycle;
711
712 /** Number of Threads CPU can process */
713 unsigned numThreads;
714
715 /** Mapping for system thread id to cpu id */
716 std::map<unsigned,unsigned> threadMap;
717
718 /** Available thread ids in the cpu*/
719 std::vector<unsigned> tids;
720
721 /** Stat for total number of times the CPU is descheduled. */
722 Stats::Scalar<> timesIdled;
723 /** Stat for total number of cycles the CPU spends descheduled. */
724 Stats::Scalar<> idleCycles;
725 /** Stat for the number of committed instructions per thread. */
726 Stats::Vector<> committedInsts;
727 /** Stat for the total number of committed instructions. */
728 Stats::Scalar<> totalCommittedInsts;
729 /** Stat for the CPI per thread. */
730 Stats::Formula cpi;
731 /** Stat for the total CPI. */
732 Stats::Formula totalCpi;
733 /** Stat for the IPC per thread. */
734 Stats::Formula ipc;
735 /** Stat for the total IPC. */
736 Stats::Formula totalIpc;
737 };
738
739 #endif // __CPU_O3_CPU_HH__