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