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