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