base.hh revision 8794:e2ac2b7164dd
1/*
2 * Copyright (c) 2002-2005 The Regents of The University of Michigan
3 * Copyright (c) 2011 Regents of the University of California
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met: redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer;
10 * redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution;
13 * neither the name of the copyright holders nor the names of its
14 * contributors may be used to endorse or promote products derived from
15 * this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 *
29 * Authors: Steve Reinhardt
30 *          Nathan Binkert
31 *          Rick Strong
32 */
33
34#ifndef __CPU_BASE_HH__
35#define __CPU_BASE_HH__
36
37#include <vector>
38
39#include "arch/interrupts.hh"
40#include "arch/isa_traits.hh"
41#include "arch/microcode_rom.hh"
42#include "base/statistics.hh"
43#include "config/the_isa.hh"
44#include "mem/mem_object.hh"
45#include "sim/eventq.hh"
46#include "sim/full_system.hh"
47#include "sim/insttracer.hh"
48
49class BaseCPUParams;
50class BranchPred;
51class CheckerCPU;
52class ThreadContext;
53class System;
54class Port;
55
56namespace TheISA
57{
58    class Predecoder;
59}
60
61class CPUProgressEvent : public Event
62{
63  protected:
64    Tick _interval;
65    Counter lastNumInst;
66    BaseCPU *cpu;
67    bool _repeatEvent;
68
69  public:
70    CPUProgressEvent(BaseCPU *_cpu, Tick ival = 0);
71
72    void process();
73
74    void interval(Tick ival) { _interval = ival; }
75    Tick interval() { return _interval; }
76
77    void repeatEvent(bool repeat) { _repeatEvent = repeat; }
78
79    virtual const char *description() const;
80};
81
82class BaseCPU : public MemObject
83{
84  protected:
85    // CPU's clock period in terms of the number of ticks of curTime.
86    Tick clock;
87    // @todo remove me after debugging with legion done
88    Tick instCnt;
89    // every cpu has an id, put it in the base cpu
90    // Set at initialization, only time a cpuId might change is during a
91    // takeover (which should be done from within the BaseCPU anyway,
92    // therefore no setCpuId() method is provided
93    int _cpuId;
94
95  public:
96    /** Reads this CPU's ID. */
97    int cpuId() { return _cpuId; }
98
99//    Tick currentTick;
100    inline Tick frequency() const { return SimClock::Frequency / clock; }
101    inline Tick ticks(int numCycles) const { return clock * numCycles; }
102    inline Tick curCycle() const { return curTick() / clock; }
103    inline Tick tickToCycles(Tick val) const { return val / clock; }
104    inline void workItemBegin() { numWorkItemsStarted++; }
105    inline void workItemEnd() { numWorkItemsCompleted++; }
106    // @todo remove me after debugging with legion done
107    Tick instCount() { return instCnt; }
108
109    /** The next cycle the CPU should be scheduled, given a cache
110     * access or quiesce event returning on this cycle.  This function
111     * may return curTick() if the CPU should run on the current cycle.
112     */
113    Tick nextCycle();
114
115    /** The next cycle the CPU should be scheduled, given a cache
116     * access or quiesce event returning on the given Tick.  This
117     * function may return curTick() if the CPU should run on the
118     * current cycle.
119     * @param begin_tick The tick that the event is completing on.
120     */
121    Tick nextCycle(Tick begin_tick);
122
123    TheISA::MicrocodeRom microcodeRom;
124
125  protected:
126    TheISA::Interrupts *interrupts;
127
128  public:
129    TheISA::Interrupts *
130    getInterruptController()
131    {
132        return interrupts;
133    }
134
135    virtual void wakeup() = 0;
136
137    void
138    postInterrupt(int int_num, int index)
139    {
140        interrupts->post(int_num, index);
141        if (FullSystem)
142            wakeup();
143    }
144
145    void
146    clearInterrupt(int int_num, int index)
147    {
148        interrupts->clear(int_num, index);
149    }
150
151    void
152    clearInterrupts()
153    {
154        interrupts->clearAll();
155    }
156
157    bool
158    checkInterrupts(ThreadContext *tc) const
159    {
160        return FullSystem && interrupts->checkInterrupts(tc);
161    }
162
163    class ProfileEvent : public Event
164    {
165      private:
166        BaseCPU *cpu;
167        Tick interval;
168
169      public:
170        ProfileEvent(BaseCPU *cpu, Tick interval);
171        void process();
172    };
173    ProfileEvent *profileEvent;
174
175  protected:
176    std::vector<ThreadContext *> threadContexts;
177    std::vector<TheISA::Predecoder *> predecoders;
178
179    Trace::InstTracer * tracer;
180
181  public:
182
183    // Mask to align PCs to MachInst sized boundaries
184    static const Addr PCMask = ~((Addr)sizeof(TheISA::MachInst) - 1);
185
186    /// Provide access to the tracer pointer
187    Trace::InstTracer * getTracer() { return tracer; }
188
189    /// Notify the CPU that the indicated context is now active.  The
190    /// delay parameter indicates the number of ticks to wait before
191    /// executing (typically 0 or 1).
192    virtual void activateContext(int thread_num, int delay) {}
193
194    /// Notify the CPU that the indicated context is now suspended.
195    virtual void suspendContext(int thread_num) {}
196
197    /// Notify the CPU that the indicated context is now deallocated.
198    virtual void deallocateContext(int thread_num) {}
199
200    /// Notify the CPU that the indicated context is now halted.
201    virtual void haltContext(int thread_num) {}
202
203   /// Given a Thread Context pointer return the thread num
204   int findContext(ThreadContext *tc);
205
206   /// Given a thread num get tho thread context for it
207   ThreadContext *getContext(int tn) { return threadContexts[tn]; }
208
209  public:
210    typedef BaseCPUParams Params;
211    const Params *params() const
212    { return reinterpret_cast<const Params *>(_params); }
213    BaseCPU(Params *params);
214    virtual ~BaseCPU();
215
216    virtual void init();
217    virtual void startup();
218    virtual void regStats();
219
220    virtual void activateWhenReady(ThreadID tid) {};
221
222    void registerThreadContexts();
223
224    /// Prepare for another CPU to take over execution.  When it is
225    /// is ready (drained pipe) it signals the sampler.
226    virtual void switchOut();
227
228    /// Take over execution from the given CPU.  Used for warm-up and
229    /// sampling.
230    virtual void takeOverFrom(BaseCPU *, Port *ic, Port *dc);
231
232    /**
233     *  Number of threads we're actually simulating (<= SMT_MAX_THREADS).
234     * This is a constant for the duration of the simulation.
235     */
236    ThreadID numThreads;
237
238    /**
239     * Vector of per-thread instruction-based event queues.  Used for
240     * scheduling events based on number of instructions committed by
241     * a particular thread.
242     */
243    EventQueue **comInstEventQueue;
244
245    /**
246     * Vector of per-thread load-based event queues.  Used for
247     * scheduling events based on number of loads committed by
248     *a particular thread.
249     */
250    EventQueue **comLoadEventQueue;
251
252    System *system;
253
254    Tick phase;
255
256    /**
257     * Serialize this object to the given output stream.
258     * @param os The stream to serialize to.
259     */
260    virtual void serialize(std::ostream &os);
261
262    /**
263     * Reconstruct the state of this object from a checkpoint.
264     * @param cp The checkpoint use.
265     * @param section The section name of this object
266     */
267    virtual void unserialize(Checkpoint *cp, const std::string &section);
268
269    /**
270     * Return pointer to CPU's branch predictor (NULL if none).
271     * @return Branch predictor pointer.
272     */
273    virtual BranchPred *getBranchPred() { return NULL; };
274
275    virtual Counter totalInstructions() const = 0;
276
277    // Function tracing
278  private:
279    bool functionTracingEnabled;
280    std::ostream *functionTraceStream;
281    Addr currentFunctionStart;
282    Addr currentFunctionEnd;
283    Tick functionEntryTick;
284    void enableFunctionTrace();
285    void traceFunctionsInternal(Addr pc);
286
287  protected:
288    void traceFunctions(Addr pc)
289    {
290        if (functionTracingEnabled)
291            traceFunctionsInternal(pc);
292    }
293
294  private:
295    static std::vector<BaseCPU *> cpuList;   //!< Static global cpu list
296
297  public:
298    static int numSimulatedCPUs() { return cpuList.size(); }
299    static Counter numSimulatedInstructions()
300    {
301        Counter total = 0;
302
303        int size = cpuList.size();
304        for (int i = 0; i < size; ++i)
305            total += cpuList[i]->totalInstructions();
306
307        return total;
308    }
309
310  public:
311    // Number of CPU cycles simulated
312    Stats::Scalar numCycles;
313    Stats::Scalar numWorkItemsStarted;
314    Stats::Scalar numWorkItemsCompleted;
315};
316
317#endif // __CPU_BASE_HH__
318