cpu.hh revision 5358:e9acb84bbafb
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/types.hh"
42#include "base/statistics.hh"
43#include "base/timebuf.hh"
44#include "config/full_system.hh"
45#include "config/use_checker.hh"
46#include "cpu/activity.hh"
47#include "cpu/base.hh"
48#include "cpu/simple_thread.hh"
49#include "cpu/o3/comm.hh"
50#include "cpu/o3/cpu_policy.hh"
51#include "cpu/o3/scoreboard.hh"
52#include "cpu/o3/thread_state.hh"
53//#include "cpu/o3/thread_context.hh"
54#include "sim/process.hh"
55
56template <class>
57class Checker;
58class ThreadContext;
59template <class>
60class O3ThreadContext;
61
62class Checkpoint;
63class MemObject;
64class Process;
65
66class BaseO3CPU : public BaseCPU
67{
68    //Stuff that's pretty ISA independent will go here.
69  public:
70    typedef BaseCPU::Params Params;
71
72    BaseO3CPU(Params *params);
73
74    void regStats();
75
76    /** Sets this CPU's ID. */
77    void setCpuId(int id) { cpu_id = id; }
78
79    /** Reads this CPU's ID. */
80    int readCpuId() { return cpu_id; }
81
82  protected:
83    int cpu_id;
84};
85
86/**
87 * FullO3CPU class, has each of the stages (fetch through commit)
88 * within it, as well as all of the time buffers between stages.  The
89 * tick() function for the CPU is defined here.
90 */
91template <class Impl>
92class FullO3CPU : public BaseO3CPU
93{
94  public:
95    // Typedefs from the Impl here.
96    typedef typename Impl::CPUPol CPUPolicy;
97    typedef typename Impl::DynInstPtr DynInstPtr;
98    typedef typename Impl::O3CPU O3CPU;
99    typedef typename Impl::Params Params;
100
101    typedef O3ThreadState<Impl> Thread;
102
103    typedef typename std::list<DynInstPtr>::iterator ListIt;
104
105    friend class O3ThreadContext<Impl>;
106
107  public:
108    enum Status {
109        Running,
110        Idle,
111        Halted,
112        Blocked,
113        SwitchedOut
114    };
115
116    TheISA::ITB * itb;
117    TheISA::DTB * dtb;
118
119    /** Overall CPU status. */
120    Status _status;
121
122    /** Per-thread status in CPU, used for SMT.  */
123    Status _threadStatus[Impl::MaxThreads];
124
125  private:
126    class TickEvent : public Event
127    {
128      private:
129        /** Pointer to the CPU. */
130        FullO3CPU<Impl> *cpu;
131
132      public:
133        /** Constructs a tick event. */
134        TickEvent(FullO3CPU<Impl> *c);
135
136        /** Processes a tick event, calling tick() on the CPU. */
137        void process();
138        /** Returns the description of the tick event. */
139        const char *description() const;
140    };
141
142    /** The tick event used for scheduling CPU ticks. */
143    TickEvent tickEvent;
144
145    /** Schedule tick event, regardless of its current state. */
146    void scheduleTickEvent(int delay)
147    {
148        if (tickEvent.squashed())
149            tickEvent.reschedule(nextCycle(curTick + ticks(delay)));
150        else if (!tickEvent.scheduled())
151            tickEvent.schedule(nextCycle(curTick + ticks(delay)));
152    }
153
154    /** Unschedule tick event, regardless of its current state. */
155    void unscheduleTickEvent()
156    {
157        if (tickEvent.scheduled())
158            tickEvent.squash();
159    }
160
161    class ActivateThreadEvent : public Event
162    {
163      private:
164        /** Number of Thread to Activate */
165        int tid;
166
167        /** Pointer to the CPU. */
168        FullO3CPU<Impl> *cpu;
169
170      public:
171        /** Constructs the event. */
172        ActivateThreadEvent();
173
174        /** Initialize Event */
175        void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
176
177        /** Processes the event, calling activateThread() on the CPU. */
178        void process();
179
180        /** Returns the description of the event. */
181        const char *description() const;
182    };
183
184    /** Schedule thread to activate , regardless of its current state. */
185    void scheduleActivateThreadEvent(int tid, int delay)
186    {
187        // Schedule thread to activate, regardless of its current state.
188        if (activateThreadEvent[tid].squashed())
189            activateThreadEvent[tid].
190                reschedule(nextCycle(curTick + ticks(delay)));
191        else if (!activateThreadEvent[tid].scheduled())
192            activateThreadEvent[tid].
193                schedule(nextCycle(curTick + ticks(delay)));
194    }
195
196    /** Unschedule actiavte thread event, regardless of its current state. */
197    void unscheduleActivateThreadEvent(int tid)
198    {
199        if (activateThreadEvent[tid].scheduled())
200            activateThreadEvent[tid].squash();
201    }
202
203    /** The tick event used for scheduling CPU ticks. */
204    ActivateThreadEvent activateThreadEvent[Impl::MaxThreads];
205
206    class DeallocateContextEvent : public Event
207    {
208      private:
209        /** Number of Thread to deactivate */
210        int tid;
211
212        /** Should the thread be removed from the CPU? */
213        bool remove;
214
215        /** Pointer to the CPU. */
216        FullO3CPU<Impl> *cpu;
217
218      public:
219        /** Constructs the event. */
220        DeallocateContextEvent();
221
222        /** Initialize Event */
223        void init(int thread_num, FullO3CPU<Impl> *thread_cpu);
224
225        /** Processes the event, calling activateThread() on the CPU. */
226        void process();
227
228        /** Sets whether the thread should also be removed from the CPU. */
229        void setRemove(bool _remove) { remove = _remove; }
230
231        /** Returns the description of the event. */
232        const char *description() const;
233    };
234
235    /** Schedule cpu to deallocate thread context.*/
236    void scheduleDeallocateContextEvent(int tid, bool remove, int delay)
237    {
238        // Schedule thread to activate, regardless of its current state.
239        if (deallocateContextEvent[tid].squashed())
240            deallocateContextEvent[tid].
241                reschedule(nextCycle(curTick + ticks(delay)));
242        else if (!deallocateContextEvent[tid].scheduled())
243            deallocateContextEvent[tid].
244                schedule(nextCycle(curTick + ticks(delay)));
245    }
246
247    /** Unschedule thread deallocation in CPU */
248    void unscheduleDeallocateContextEvent(int tid)
249    {
250        if (deallocateContextEvent[tid].scheduled())
251            deallocateContextEvent[tid].squash();
252    }
253
254    /** The tick event used for scheduling CPU ticks. */
255    DeallocateContextEvent deallocateContextEvent[Impl::MaxThreads];
256
257  public:
258    /** Constructs a CPU with the given parameters. */
259    FullO3CPU(O3CPU *o3_cpu, Params *params);
260    /** Destructor. */
261    ~FullO3CPU();
262
263    /** Registers statistics. */
264    void fullCPURegStats();
265
266    void demapPage(Addr vaddr, uint64_t asn)
267    {
268        this->itb->demapPage(vaddr, asn);
269        this->dtb->demapPage(vaddr, asn);
270    }
271
272    void demapInstPage(Addr vaddr, uint64_t asn)
273    {
274        this->itb->demapPage(vaddr, asn);
275    }
276
277    void demapDataPage(Addr vaddr, uint64_t asn)
278    {
279        this->dtb->demapPage(vaddr, asn);
280    }
281
282    /** Translates instruction requestion. */
283    Fault translateInstReq(RequestPtr &req, Thread *thread)
284    {
285        return this->itb->translate(req, thread->getTC());
286    }
287
288    /** Translates data read request. */
289    Fault translateDataReadReq(RequestPtr &req, Thread *thread)
290    {
291        return this->dtb->translate(req, thread->getTC(), false);
292    }
293
294    /** Translates data write request. */
295    Fault translateDataWriteReq(RequestPtr &req, Thread *thread)
296    {
297        return this->dtb->translate(req, thread->getTC(), true);
298    }
299
300    /** Returns a specific port. */
301    Port *getPort(const std::string &if_name, int idx);
302
303    /** Ticks CPU, calling tick() on each stage, and checking the overall
304     *  activity to see if the CPU should deschedule itself.
305     */
306    void tick();
307
308    /** Initialize the CPU */
309    void init();
310
311    /** Returns the Number of Active Threads in the CPU */
312    int numActiveThreads()
313    { return activeThreads.size(); }
314
315    /** Add Thread to Active Threads List */
316    void activateThread(unsigned tid);
317
318    /** Remove Thread from Active Threads List */
319    void deactivateThread(unsigned tid);
320
321    /** Setup CPU to insert a thread's context */
322    void insertThread(unsigned tid);
323
324    /** Remove all of a thread's context from CPU */
325    void removeThread(unsigned tid);
326
327    /** Count the Total Instructions Committed in the CPU. */
328    virtual Counter totalInstructions() const
329    {
330        Counter total(0);
331
332        for (int i=0; i < thread.size(); i++)
333            total += thread[i]->numInst;
334
335        return total;
336    }
337
338    /** Add Thread to Active Threads List. */
339    void activateContext(int tid, int delay);
340
341    /** Remove Thread from Active Threads List */
342    void suspendContext(int tid);
343
344    /** Remove Thread from Active Threads List &&
345     *  Possibly Remove Thread Context from CPU.
346     */
347    bool deallocateContext(int tid, bool remove, int delay = 1);
348
349    /** Remove Thread from Active Threads List &&
350     *  Remove Thread Context from CPU.
351     */
352    void haltContext(int tid);
353
354    /** Activate a Thread When CPU Resources are Available. */
355    void activateWhenReady(int tid);
356
357    /** Add or Remove a Thread Context in the CPU. */
358    void doContextSwitch();
359
360    /** Update The Order In Which We Process Threads. */
361    void updateThreadPriority();
362
363    /** Serialize state. */
364    virtual void serialize(std::ostream &os);
365
366    /** Unserialize from a checkpoint. */
367    virtual void unserialize(Checkpoint *cp, const std::string &section);
368
369  public:
370    /** Executes a syscall on this cycle.
371     *  ---------------------------------------
372     *  Note: this is a virtual function. CPU-Specific
373     *  functionality defined in derived classes
374     */
375    virtual void syscall(int tid) { panic("Unimplemented!"); }
376
377    /** Starts draining the CPU's pipeline of all instructions in
378     * order to stop all memory accesses. */
379    virtual unsigned int drain(Event *drain_event);
380
381    /** Resumes execution after a drain. */
382    virtual void resume();
383
384    /** Signals to this CPU that a stage has completed switching out. */
385    void signalDrained();
386
387    /** Switches out this CPU. */
388    virtual void switchOut();
389
390    /** Takes over from another CPU. */
391    virtual void takeOverFrom(BaseCPU *oldCPU);
392
393    /** Get the current instruction sequence number, and increment it. */
394    InstSeqNum getAndIncrementInstSeq()
395    { return globalSeqNum++; }
396
397#if FULL_SYSTEM
398    /** Update the Virt and Phys ports of all ThreadContexts to
399     * reflect change in memory connections. */
400    void updateMemPorts();
401
402    /** Check if this address is a valid instruction address. */
403    bool validInstAddr(Addr addr) { return true; }
404
405    /** Check if this address is a valid data address. */
406    bool validDataAddr(Addr addr) { return true; }
407
408    /** Get instruction asid. */
409    int getInstAsid(unsigned tid)
410    { return regFile.miscRegs[tid].getInstAsid(); }
411
412    /** Get data asid. */
413    int getDataAsid(unsigned tid)
414    { return regFile.miscRegs[tid].getDataAsid(); }
415#else
416    /** Get instruction asid. */
417    int getInstAsid(unsigned tid)
418    { return thread[tid]->getInstAsid(); }
419
420    /** Get data asid. */
421    int getDataAsid(unsigned tid)
422    { return thread[tid]->getDataAsid(); }
423
424#endif
425
426    /** Register accessors.  Index refers to the physical register index. */
427    uint64_t readIntReg(int reg_idx);
428
429    TheISA::FloatReg readFloatReg(int reg_idx);
430
431    TheISA::FloatReg readFloatReg(int reg_idx, int width);
432
433    TheISA::FloatRegBits readFloatRegBits(int reg_idx);
434
435    TheISA::FloatRegBits readFloatRegBits(int reg_idx, int width);
436
437    void setIntReg(int reg_idx, uint64_t val);
438
439    void setFloatReg(int reg_idx, TheISA::FloatReg val);
440
441    void setFloatReg(int reg_idx, TheISA::FloatReg val, int width);
442
443    void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);
444
445    void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val, int width);
446
447    uint64_t readArchIntReg(int reg_idx, unsigned tid);
448
449    float readArchFloatRegSingle(int reg_idx, unsigned tid);
450
451    double readArchFloatRegDouble(int reg_idx, unsigned tid);
452
453    uint64_t readArchFloatRegInt(int reg_idx, unsigned tid);
454
455    /** Architectural register accessors.  Looks up in the commit
456     * rename table to obtain the true physical index of the
457     * architected register first, then accesses that physical
458     * register.
459     */
460    void setArchIntReg(int reg_idx, uint64_t val, unsigned tid);
461
462    void setArchFloatRegSingle(int reg_idx, float val, unsigned tid);
463
464    void setArchFloatRegDouble(int reg_idx, double val, unsigned tid);
465
466    void setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid);
467
468    /** Reads the commit PC of a specific thread. */
469    Addr readPC(unsigned tid);
470
471    /** Sets the commit PC of a specific thread. */
472    void setPC(Addr new_PC, unsigned tid);
473
474    /** Reads the commit micro PC of a specific thread. */
475    Addr readMicroPC(unsigned tid);
476
477    /** Sets the commmit micro PC of a specific thread. */
478    void setMicroPC(Addr new_microPC, unsigned tid);
479
480    /** Reads the next PC of a specific thread. */
481    Addr readNextPC(unsigned tid);
482
483    /** Sets the next PC of a specific thread. */
484    void setNextPC(Addr val, unsigned tid);
485
486    /** Reads the next NPC of a specific thread. */
487    Addr readNextNPC(unsigned tid);
488
489    /** Sets the next NPC of a specific thread. */
490    void setNextNPC(Addr val, unsigned tid);
491
492    /** Reads the commit next micro PC of a specific thread. */
493    Addr readNextMicroPC(unsigned tid);
494
495    /** Sets the commit next micro PC of a specific thread. */
496    void setNextMicroPC(Addr val, unsigned tid);
497
498    /** Function to add instruction onto the head of the list of the
499     *  instructions.  Used when new instructions are fetched.
500     */
501    ListIt addInst(DynInstPtr &inst);
502
503    /** Function to tell the CPU that an instruction has completed. */
504    void instDone(unsigned tid);
505
506    /** Add Instructions to the CPU Remove List*/
507    void addToRemoveList(DynInstPtr &inst);
508
509    /** Remove an instruction from the front end of the list.  There's
510     *  no restriction on location of the instruction.
511     */
512    void removeFrontInst(DynInstPtr &inst);
513
514    /** Remove all instructions that are not currently in the ROB.
515     *  There's also an option to not squash delay slot instructions.*/
516    void removeInstsNotInROB(unsigned tid);
517
518    /** Remove all instructions younger than the given sequence number. */
519    void removeInstsUntil(const InstSeqNum &seq_num,unsigned tid);
520
521    /** Removes the instruction pointed to by the iterator. */
522    inline void squashInstIt(const ListIt &instIt, const unsigned &tid);
523
524    /** Cleans up all instructions on the remove list. */
525    void cleanUpRemovedInsts();
526
527    /** Debug function to print all instructions on the list. */
528    void dumpInsts();
529
530  public:
531    /** List of all the instructions in flight. */
532    std::list<DynInstPtr> instList;
533
534    /** List of all the instructions that will be removed at the end of this
535     *  cycle.
536     */
537    std::queue<ListIt> removeList;
538
539#ifdef DEBUG
540    /** Debug structure to keep track of the sequence numbers still in
541     * flight.
542     */
543    std::set<InstSeqNum> snList;
544#endif
545
546    /** Records if instructions need to be removed this cycle due to
547     *  being retired or squashed.
548     */
549    bool removeInstsThisCycle;
550
551  protected:
552    /** The fetch stage. */
553    typename CPUPolicy::Fetch fetch;
554
555    /** The decode stage. */
556    typename CPUPolicy::Decode decode;
557
558    /** The dispatch stage. */
559    typename CPUPolicy::Rename rename;
560
561    /** The issue/execute/writeback stages. */
562    typename CPUPolicy::IEW iew;
563
564    /** The commit stage. */
565    typename CPUPolicy::Commit commit;
566
567    /** The register file. */
568    typename CPUPolicy::RegFile regFile;
569
570    /** The free list. */
571    typename CPUPolicy::FreeList freeList;
572
573    /** The rename map. */
574    typename CPUPolicy::RenameMap renameMap[Impl::MaxThreads];
575
576    /** The commit rename map. */
577    typename CPUPolicy::RenameMap commitRenameMap[Impl::MaxThreads];
578
579    /** The re-order buffer. */
580    typename CPUPolicy::ROB rob;
581
582    /** Active Threads List */
583    std::list<unsigned> activeThreads;
584
585    /** Integer Register Scoreboard */
586    Scoreboard scoreboard;
587
588  public:
589    /** Enum to give each stage a specific index, so when calling
590     *  activateStage() or deactivateStage(), they can specify which stage
591     *  is being activated/deactivated.
592     */
593    enum StageIdx {
594        FetchIdx,
595        DecodeIdx,
596        RenameIdx,
597        IEWIdx,
598        CommitIdx,
599        NumStages };
600
601    /** Typedefs from the Impl to get the structs that each of the
602     *  time buffers should use.
603     */
604    typedef typename CPUPolicy::TimeStruct TimeStruct;
605
606    typedef typename CPUPolicy::FetchStruct FetchStruct;
607
608    typedef typename CPUPolicy::DecodeStruct DecodeStruct;
609
610    typedef typename CPUPolicy::RenameStruct RenameStruct;
611
612    typedef typename CPUPolicy::IEWStruct IEWStruct;
613
614    /** The main time buffer to do backwards communication. */
615    TimeBuffer<TimeStruct> timeBuffer;
616
617    /** The fetch stage's instruction queue. */
618    TimeBuffer<FetchStruct> fetchQueue;
619
620    /** The decode stage's instruction queue. */
621    TimeBuffer<DecodeStruct> decodeQueue;
622
623    /** The rename stage's instruction queue. */
624    TimeBuffer<RenameStruct> renameQueue;
625
626    /** The IEW stage's instruction queue. */
627    TimeBuffer<IEWStruct> iewQueue;
628
629  private:
630    /** The activity recorder; used to tell if the CPU has any
631     * activity remaining or if it can go to idle and deschedule
632     * itself.
633     */
634    ActivityRecorder activityRec;
635
636  public:
637    /** Records that there was time buffer activity this cycle. */
638    void activityThisCycle() { activityRec.activity(); }
639
640    /** Changes a stage's status to active within the activity recorder. */
641    void activateStage(const StageIdx idx)
642    { activityRec.activateStage(idx); }
643
644    /** Changes a stage's status to inactive within the activity recorder. */
645    void deactivateStage(const StageIdx idx)
646    { activityRec.deactivateStage(idx); }
647
648    /** Wakes the CPU, rescheduling the CPU if it's not already active. */
649    void wakeCPU();
650
651    /** Gets a free thread id. Use if thread ids change across system. */
652    int getFreeTid();
653
654  public:
655    /** Returns a pointer to a thread context. */
656    ThreadContext *tcBase(unsigned tid)
657    {
658        return thread[tid]->getTC();
659    }
660
661    /** The global sequence number counter. */
662    InstSeqNum globalSeqNum;//[Impl::MaxThreads];
663
664#if USE_CHECKER
665    /** Pointer to the checker, which can dynamically verify
666     * instruction results at run time.  This can be set to NULL if it
667     * is not being used.
668     */
669    Checker<DynInstPtr> *checker;
670#endif
671
672#if FULL_SYSTEM
673    /** Pointer to the system. */
674    System *system;
675
676    /** Pointer to physical memory. */
677    PhysicalMemory *physmem;
678#endif
679
680    /** Event to call process() on once draining has completed. */
681    Event *drainEvent;
682
683    /** Counter of how many stages have completed draining. */
684    int drainCount;
685
686    /** Pointers to all of the threads in the CPU. */
687    std::vector<Thread *> thread;
688
689    /** Whether or not the CPU should defer its registration. */
690    bool deferRegistration;
691
692    /** Is there a context switch pending? */
693    bool contextSwitch;
694
695    /** Threads Scheduled to Enter CPU */
696    std::list<int> cpuWaitList;
697
698    /** The cycle that the CPU was last running, used for statistics. */
699    Tick lastRunningCycle;
700
701    /** The cycle that the CPU was last activated by a new thread*/
702    Tick lastActivatedCycle;
703
704    /** Number of Threads CPU can process */
705    unsigned numThreads;
706
707    /** Mapping for system thread id to cpu id */
708    std::map<unsigned,unsigned> threadMap;
709
710    /** Available thread ids in the cpu*/
711    std::vector<unsigned> tids;
712
713    /** Stat for total number of times the CPU is descheduled. */
714    Stats::Scalar<> timesIdled;
715    /** Stat for total number of cycles the CPU spends descheduled. */
716    Stats::Scalar<> idleCycles;
717    /** Stat for the number of committed instructions per thread. */
718    Stats::Vector<> committedInsts;
719    /** Stat for the total number of committed instructions. */
720    Stats::Scalar<> totalCommittedInsts;
721    /** Stat for the CPI per thread. */
722    Stats::Formula cpi;
723    /** Stat for the total CPI. */
724    Stats::Formula totalCpi;
725    /** Stat for the IPC per thread. */
726    Stats::Formula ipc;
727    /** Stat for the total IPC. */
728    Stats::Formula totalIpc;
729};
730
731#endif // __CPU_O3_CPU_HH__
732