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