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