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