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