cpu.hh revision 2834
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    /** Returns the Number of Active Threads in the CPU */
218    int numActiveThreads()
219    { return activeThreads.size(); }
220
221    /** Add Thread to Active Threads List */
222    void activateThread(unsigned int tid);
223
224    /** Setup CPU to insert a thread's context */
225    void insertThread(unsigned tid);
226
227    /** Remove all of a thread's context from CPU */
228    void removeThread(unsigned tid);
229
230    /** Count the Total Instructions Committed in the CPU. */
231    virtual Counter totalInstructions() const
232    {
233        Counter total(0);
234
235        for (int i=0; i < thread.size(); i++)
236            total += thread[i]->numInst;
237
238        return total;
239    }
240
241    /** Add Thread to Active Threads List. */
242    void activateContext(int tid, int delay);
243
244    /** Remove Thread from Active Threads List */
245    void suspendContext(int tid);
246
247    /** Remove Thread from Active Threads List &&
248     *  Remove Thread Context from CPU.
249     */
250    void deallocateContext(int tid);
251
252    /** Remove Thread from Active Threads List &&
253     *  Remove Thread Context from CPU.
254     */
255    void haltContext(int tid);
256
257    /** Activate a Thread When CPU Resources are Available. */
258    void activateWhenReady(int tid);
259
260    /** Add or Remove a Thread Context in the CPU. */
261    void doContextSwitch();
262
263    /** Update The Order In Which We Process Threads. */
264    void updateThreadPriority();
265
266    /** Executes a syscall on this cycle.
267     *  ---------------------------------------
268     *  Note: this is a virtual function. CPU-Specific
269     *  functionality defined in derived classes
270     */
271    virtual void syscall(int tid) { panic("Unimplemented!"); }
272
273    /** Switches out this CPU. */
274    void switchOut(Sampler *sampler);
275
276    /** Signals to this CPU that a stage has completed switching out. */
277    void signalSwitched();
278
279    /** Takes over from another CPU. */
280    void takeOverFrom(BaseCPU *oldCPU);
281
282    /** Get the current instruction sequence number, and increment it. */
283    InstSeqNum getAndIncrementInstSeq()
284    { return globalSeqNum++; }
285
286#if FULL_SYSTEM
287    /** Check if this address is a valid instruction address. */
288    bool validInstAddr(Addr addr) { return true; }
289
290    /** Check if this address is a valid data address. */
291    bool validDataAddr(Addr addr) { return true; }
292
293    /** Get instruction asid. */
294    int getInstAsid(unsigned tid)
295    { return regFile.miscRegs[tid].getInstAsid(); }
296
297    /** Get data asid. */
298    int getDataAsid(unsigned tid)
299    { return regFile.miscRegs[tid].getDataAsid(); }
300#else
301    /** Get instruction asid. */
302    int getInstAsid(unsigned tid)
303    { return thread[tid]->getInstAsid(); }
304
305    /** Get data asid. */
306    int getDataAsid(unsigned tid)
307    { return thread[tid]->getDataAsid(); }
308
309#endif
310
311    /** Register accessors.  Index refers to the physical register index. */
312    uint64_t readIntReg(int reg_idx);
313
314    FloatReg readFloatReg(int reg_idx);
315
316    FloatReg readFloatReg(int reg_idx, int width);
317
318    FloatRegBits readFloatRegBits(int reg_idx);
319
320    FloatRegBits readFloatRegBits(int reg_idx, int width);
321
322    void setIntReg(int reg_idx, uint64_t val);
323
324    void setFloatReg(int reg_idx, FloatReg val);
325
326    void setFloatReg(int reg_idx, FloatReg val, int width);
327
328    void setFloatRegBits(int reg_idx, FloatRegBits val);
329
330    void setFloatRegBits(int reg_idx, FloatRegBits val, int width);
331
332    uint64_t readArchIntReg(int reg_idx, unsigned tid);
333
334    float readArchFloatRegSingle(int reg_idx, unsigned tid);
335
336    double readArchFloatRegDouble(int reg_idx, unsigned tid);
337
338    uint64_t readArchFloatRegInt(int reg_idx, unsigned tid);
339
340    /** Architectural register accessors.  Looks up in the commit
341     * rename table to obtain the true physical index of the
342     * architected register first, then accesses that physical
343     * register.
344     */
345    void setArchIntReg(int reg_idx, uint64_t val, unsigned tid);
346
347    void setArchFloatRegSingle(int reg_idx, float val, unsigned tid);
348
349    void setArchFloatRegDouble(int reg_idx, double val, unsigned tid);
350
351    void setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid);
352
353    /** Reads the commit PC of a specific thread. */
354    uint64_t readPC(unsigned tid);
355
356    /** Sets the commit PC of a specific thread. */
357    void setPC(Addr new_PC, unsigned tid);
358
359    /** Reads the next PC of a specific thread. */
360    uint64_t readNextPC(unsigned tid);
361
362    /** Sets the next PC of a specific thread. */
363    void setNextPC(uint64_t val, unsigned tid);
364
365    /** Reads the next NPC of a specific thread. */
366    uint64_t readNextNPC(unsigned tid);
367
368    /** Sets the next NPC of a specific thread. */
369    void setNextNPC(uint64_t val, unsigned tid);
370
371    /** Function to add instruction onto the head of the list of the
372     *  instructions.  Used when new instructions are fetched.
373     */
374    ListIt addInst(DynInstPtr &inst);
375
376    /** Function to tell the CPU that an instruction has completed. */
377    void instDone(unsigned tid);
378
379    /** Add Instructions to the CPU Remove List*/
380    void addToRemoveList(DynInstPtr &inst);
381
382    /** Remove an instruction from the front end of the list.  There's
383     *  no restriction on location of the instruction.
384     */
385    void removeFrontInst(DynInstPtr &inst);
386
387    /** Remove all instructions that are not currently in the ROB. */
388    void removeInstsNotInROB(unsigned tid);
389
390    /** Remove all instructions younger than the given sequence number. */
391    void removeInstsUntil(const InstSeqNum &seq_num,unsigned tid);
392
393    /** Removes the instruction pointed to by the iterator. */
394    inline void squashInstIt(const ListIt &instIt, const unsigned &tid);
395
396    /** Cleans up all instructions on the remove list. */
397    void cleanUpRemovedInsts();
398
399    /** Debug function to print all instructions on the list. */
400    void dumpInsts();
401
402  public:
403    /** List of all the instructions in flight. */
404    std::list<DynInstPtr> instList;
405
406    /** List of all the instructions that will be removed at the end of this
407     *  cycle.
408     */
409    std::queue<ListIt> removeList;
410
411#ifdef DEBUG
412    /** Debug structure to keep track of the sequence numbers still in
413     * flight.
414     */
415    std::set<InstSeqNum> snList;
416#endif
417
418    /** Records if instructions need to be removed this cycle due to
419     *  being retired or squashed.
420     */
421    bool removeInstsThisCycle;
422
423  protected:
424    /** The fetch stage. */
425    typename CPUPolicy::Fetch fetch;
426
427    /** The decode stage. */
428    typename CPUPolicy::Decode decode;
429
430    /** The dispatch stage. */
431    typename CPUPolicy::Rename rename;
432
433    /** The issue/execute/writeback stages. */
434    typename CPUPolicy::IEW iew;
435
436    /** The commit stage. */
437    typename CPUPolicy::Commit commit;
438
439    /** The register file. */
440    typename CPUPolicy::RegFile regFile;
441
442    /** The free list. */
443    typename CPUPolicy::FreeList freeList;
444
445    /** The rename map. */
446    typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
447
448    /** The commit rename map. */
449    typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
450
451    /** The re-order buffer. */
452    typename CPUPolicy::ROB rob;
453
454    /** Active Threads List */
455    std::list<unsigned> activeThreads;
456
457    /** Integer Register Scoreboard */
458    Scoreboard scoreboard;
459
460  public:
461    /** Enum to give each stage a specific index, so when calling
462     *  activateStage() or deactivateStage(), they can specify which stage
463     *  is being activated/deactivated.
464     */
465    enum StageIdx {
466        FetchIdx,
467        DecodeIdx,
468        RenameIdx,
469        IEWIdx,
470        CommitIdx,
471        NumStages };
472
473    /** Typedefs from the Impl to get the structs that each of the
474     *  time buffers should use.
475     */
476    typedef typename CPUPolicy::TimeStruct TimeStruct;
477
478    typedef typename CPUPolicy::FetchStruct FetchStruct;
479
480    typedef typename CPUPolicy::DecodeStruct DecodeStruct;
481
482    typedef typename CPUPolicy::RenameStruct RenameStruct;
483
484    typedef typename CPUPolicy::IEWStruct IEWStruct;
485
486    /** The main time buffer to do backwards communication. */
487    TimeBuffer<TimeStruct> timeBuffer;
488
489    /** The fetch stage's instruction queue. */
490    TimeBuffer<FetchStruct> fetchQueue;
491
492    /** The decode stage's instruction queue. */
493    TimeBuffer<DecodeStruct> decodeQueue;
494
495    /** The rename stage's instruction queue. */
496    TimeBuffer<RenameStruct> renameQueue;
497
498    /** The IEW stage's instruction queue. */
499    TimeBuffer<IEWStruct> iewQueue;
500
501  private:
502    /** The activity recorder; used to tell if the CPU has any
503     * activity remaining or if it can go to idle and deschedule
504     * itself.
505     */
506    ActivityRecorder activityRec;
507
508  public:
509    /** Records that there was time buffer activity this cycle. */
510    void activityThisCycle() { activityRec.activity(); }
511
512    /** Changes a stage's status to active within the activity recorder. */
513    void activateStage(const StageIdx idx)
514    { activityRec.activateStage(idx); }
515
516    /** Changes a stage's status to inactive within the activity recorder. */
517    void deactivateStage(const StageIdx idx)
518    { activityRec.deactivateStage(idx); }
519
520    /** Wakes the CPU, rescheduling the CPU if it's not already active. */
521    void wakeCPU();
522
523    /** Gets a free thread id. Use if thread ids change across system. */
524    int getFreeTid();
525
526  public:
527    /** Returns a pointer to a thread context. */
528    ThreadContext *tcBase(unsigned tid)
529    {
530        return thread[tid]->getTC();
531    }
532
533    /** The global sequence number counter. */
534    InstSeqNum globalSeqNum;
535
536    /** Pointer to the checker, which can dynamically verify
537     * instruction results at run time.  This can be set to NULL if it
538     * is not being used.
539     */
540    Checker<DynInstPtr> *checker;
541
542#if FULL_SYSTEM
543    /** Pointer to the system. */
544    System *system;
545
546    /** Pointer to physical memory. */
547    PhysicalMemory *physmem;
548#endif
549
550    /** Pointer to memory. */
551    MemObject *mem;
552
553    /** Pointer to the sampler */
554    Sampler *sampler;
555
556    /** Counter of how many stages have completed switching out. */
557    int switchCount;
558
559    /** Pointers to all of the threads in the CPU. */
560    std::vector<Thread *> thread;
561
562    /** Pointer to the icache interface. */
563    MemInterface *icacheInterface;
564    /** Pointer to the dcache interface. */
565    MemInterface *dcacheInterface;
566
567    /** Whether or not the CPU should defer its registration. */
568    bool deferRegistration;
569
570    /** Is there a context switch pending? */
571    bool contextSwitch;
572
573    /** Threads Scheduled to Enter CPU */
574    std::list<int> cpuWaitList;
575
576    /** The cycle that the CPU was last running, used for statistics. */
577    Tick lastRunningCycle;
578
579    /** The cycle that the CPU was last activated by a new thread*/
580    Tick lastActivatedCycle;
581
582    /** Number of Threads CPU can process */
583    unsigned numThreads;
584
585    /** Mapping for system thread id to cpu id */
586    std::map<unsigned,unsigned> threadMap;
587
588    /** Available thread ids in the cpu*/
589    std::vector<unsigned> tids;
590
591    /** Stat for total number of times the CPU is descheduled. */
592    Stats::Scalar<> timesIdled;
593    /** Stat for total number of cycles the CPU spends descheduled. */
594    Stats::Scalar<> idleCycles;
595    /** Stat for the number of committed instructions per thread. */
596    Stats::Vector<> committedInsts;
597    /** Stat for the total number of committed instructions. */
598    Stats::Scalar<> totalCommittedInsts;
599    /** Stat for the CPI per thread. */
600    Stats::Formula cpi;
601    /** Stat for the total CPI. */
602    Stats::Formula totalCpi;
603    /** Stat for the IPC per thread. */
604    Stats::Formula ipc;
605    /** Stat for the total IPC. */
606    Stats::Formula totalIpc;
607};
608
609#endif // __CPU_O3_CPU_HH__
610