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