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