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