base.hh revision 8926:570b44fe6e04
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/interrupts.hh"
52#include "arch/isa_traits.hh"
53#include "arch/microcode_rom.hh"
54#include "base/statistics.hh"
55#include "config/the_isa.hh"
56#include "mem/mem_object.hh"
57#include "sim/eventq.hh"
58#include "sim/full_system.hh"
59#include "sim/insttracer.hh"
60
61struct BaseCPUParams;
62class BranchPred;
63class CheckerCPU;
64class ThreadContext;
65class System;
66
67namespace TheISA
68{
69    class Predecoder;
70}
71
72class CPUProgressEvent : public Event
73{
74  protected:
75    Tick _interval;
76    Counter lastNumInst;
77    BaseCPU *cpu;
78    bool _repeatEvent;
79
80  public:
81    CPUProgressEvent(BaseCPU *_cpu, Tick ival = 0);
82
83    void process();
84
85    void interval(Tick ival) { _interval = ival; }
86    Tick interval() { return _interval; }
87
88    void repeatEvent(bool repeat) { _repeatEvent = repeat; }
89
90    virtual const char *description() const;
91};
92
93class BaseCPU : public MemObject
94{
95  protected:
96    // CPU's clock period in terms of the number of ticks of curTime.
97    Tick clock;
98    // @todo remove me after debugging with legion done
99    Tick instCnt;
100    // every cpu has an id, put it in the base cpu
101    // Set at initialization, only time a cpuId might change is during a
102    // takeover (which should be done from within the BaseCPU anyway,
103    // therefore no setCpuId() method is provided
104    int _cpuId;
105
106    /** instruction side request id that must be placed in all requests */
107    MasterID _instMasterId;
108
109    /** data side request id that must be placed in all requests */
110    MasterID _dataMasterId;
111
112    /**
113     * Define a base class for the CPU ports (instruction and data)
114     * that is refined in the subclasses. This class handles the
115     * common cases, i.e. the functional accesses and the status
116     * changes and address range queries. The default behaviour for
117     * both atomic and timing access is to panic and the corresponding
118     * subclasses have to override these methods.
119     */
120    class CpuPort : public MasterPort
121    {
122      public:
123
124        /**
125         * Create a CPU port with a name and a structural owner.
126         *
127         * @param _name port name including the owner
128         * @param _name structural owner of this port
129         */
130        CpuPort(const std::string& _name, MemObject* _owner) :
131            MasterPort(_name, _owner)
132        { }
133
134      protected:
135
136        virtual bool recvTiming(PacketPtr pkt);
137
138        virtual Tick recvAtomic(PacketPtr pkt);
139
140        virtual void recvRetry();
141
142        void recvFunctional(PacketPtr pkt);
143
144    };
145
146  public:
147
148    /**
149     * Purely virtual method that returns a reference to the data
150     * port. All subclasses must implement this method.
151     *
152     * @return a reference to the data port
153     */
154    virtual CpuPort &getDataPort() = 0;
155
156    /**
157     * Purely virtual method that returns a reference to the instruction
158     * port. All subclasses must implement this method.
159     *
160     * @return a reference to the instruction port
161     */
162    virtual CpuPort &getInstPort() = 0;
163
164    /** Reads this CPU's ID. */
165    int cpuId() { return _cpuId; }
166
167    /** Reads this CPU's unique data requestor ID */
168    MasterID dataMasterId() { return _dataMasterId; }
169    /** Reads this CPU's unique instruction requestor ID */
170    MasterID instMasterId() { return _instMasterId; }
171
172    /**
173     * Get a master port on this CPU. All CPUs have a data and
174     * instruction port, and this method uses getDataPort and
175     * getInstPort of the subclasses to resolve the two ports.
176     *
177     * @param if_name the port name
178     * @param idx ignored index
179     *
180     * @return a reference to the port with the given name
181     */
182    MasterPort &getMasterPort(const std::string &if_name, int idx = -1);
183
184//    Tick currentTick;
185    inline Tick frequency() const { return SimClock::Frequency / clock; }
186    inline Tick ticks(int numCycles) const { return clock * numCycles; }
187    inline Tick curCycle() const { return curTick() / clock; }
188    inline Tick tickToCycles(Tick val) const { return val / clock; }
189    inline void workItemBegin() { numWorkItemsStarted++; }
190    inline void workItemEnd() { numWorkItemsCompleted++; }
191    // @todo remove me after debugging with legion done
192    Tick instCount() { return instCnt; }
193
194    /** The next cycle the CPU should be scheduled, given a cache
195     * access or quiesce event returning on this cycle.  This function
196     * may return curTick() if the CPU should run on the current cycle.
197     */
198    Tick nextCycle();
199
200    /** The next cycle the CPU should be scheduled, given a cache
201     * access or quiesce event returning on the given Tick.  This
202     * function may return curTick() if the CPU should run on the
203     * current cycle.
204     * @param begin_tick The tick that the event is completing on.
205     */
206    Tick nextCycle(Tick begin_tick);
207
208    TheISA::MicrocodeRom microcodeRom;
209
210  protected:
211    TheISA::Interrupts *interrupts;
212
213  public:
214    TheISA::Interrupts *
215    getInterruptController()
216    {
217        return interrupts;
218    }
219
220    virtual void wakeup() = 0;
221
222    void
223    postInterrupt(int int_num, int index)
224    {
225        interrupts->post(int_num, index);
226        if (FullSystem)
227            wakeup();
228    }
229
230    void
231    clearInterrupt(int int_num, int index)
232    {
233        interrupts->clear(int_num, index);
234    }
235
236    void
237    clearInterrupts()
238    {
239        interrupts->clearAll();
240    }
241
242    bool
243    checkInterrupts(ThreadContext *tc) const
244    {
245        return FullSystem && interrupts->checkInterrupts(tc);
246    }
247
248    class ProfileEvent : public Event
249    {
250      private:
251        BaseCPU *cpu;
252        Tick interval;
253
254      public:
255        ProfileEvent(BaseCPU *cpu, Tick interval);
256        void process();
257    };
258    ProfileEvent *profileEvent;
259
260  protected:
261    std::vector<ThreadContext *> threadContexts;
262    std::vector<TheISA::Predecoder *> predecoders;
263
264    Trace::InstTracer * tracer;
265
266  public:
267
268    // Mask to align PCs to MachInst sized boundaries
269    static const Addr PCMask = ~((Addr)sizeof(TheISA::MachInst) - 1);
270
271    /// Provide access to the tracer pointer
272    Trace::InstTracer * getTracer() { return tracer; }
273
274    /// Notify the CPU that the indicated context is now active.  The
275    /// delay parameter indicates the number of ticks to wait before
276    /// executing (typically 0 or 1).
277    virtual void activateContext(ThreadID thread_num, int delay) {}
278
279    /// Notify the CPU that the indicated context is now suspended.
280    virtual void suspendContext(ThreadID thread_num) {}
281
282    /// Notify the CPU that the indicated context is now deallocated.
283    virtual void deallocateContext(ThreadID thread_num) {}
284
285    /// Notify the CPU that the indicated context is now halted.
286    virtual void haltContext(ThreadID thread_num) {}
287
288   /// Given a Thread Context pointer return the thread num
289   int findContext(ThreadContext *tc);
290
291   /// Given a thread num get tho thread context for it
292   ThreadContext *getContext(int tn) { return threadContexts[tn]; }
293
294  public:
295    typedef BaseCPUParams Params;
296    const Params *params() const
297    { return reinterpret_cast<const Params *>(_params); }
298    BaseCPU(Params *params, bool is_checker = false);
299    virtual ~BaseCPU();
300
301    virtual void init();
302    virtual void startup();
303    virtual void regStats();
304
305    virtual void activateWhenReady(ThreadID tid) {};
306
307    void registerThreadContexts();
308
309    /// Prepare for another CPU to take over execution.  When it is
310    /// is ready (drained pipe) it signals the sampler.
311    virtual void switchOut();
312
313    /// Take over execution from the given CPU.  Used for warm-up and
314    /// sampling.
315    virtual void takeOverFrom(BaseCPU *);
316
317    /**
318     *  Number of threads we're actually simulating (<= SMT_MAX_THREADS).
319     * This is a constant for the duration of the simulation.
320     */
321    ThreadID numThreads;
322
323    /**
324     * Vector of per-thread instruction-based event queues.  Used for
325     * scheduling events based on number of instructions committed by
326     * a particular thread.
327     */
328    EventQueue **comInstEventQueue;
329
330    /**
331     * Vector of per-thread load-based event queues.  Used for
332     * scheduling events based on number of loads committed by
333     *a particular thread.
334     */
335    EventQueue **comLoadEventQueue;
336
337    System *system;
338
339    Tick phase;
340
341    /**
342     * Serialize this object to the given output stream.
343     * @param os The stream to serialize to.
344     */
345    virtual void serialize(std::ostream &os);
346
347    /**
348     * Reconstruct the state of this object from a checkpoint.
349     * @param cp The checkpoint use.
350     * @param section The section name of this object
351     */
352    virtual void unserialize(Checkpoint *cp, const std::string &section);
353
354    /**
355     * Return pointer to CPU's branch predictor (NULL if none).
356     * @return Branch predictor pointer.
357     */
358    virtual BranchPred *getBranchPred() { return NULL; };
359
360    virtual Counter totalInsts() const = 0;
361
362    virtual Counter totalOps() const = 0;
363
364    // Function tracing
365  private:
366    bool functionTracingEnabled;
367    std::ostream *functionTraceStream;
368    Addr currentFunctionStart;
369    Addr currentFunctionEnd;
370    Tick functionEntryTick;
371    void enableFunctionTrace();
372    void traceFunctionsInternal(Addr pc);
373
374  private:
375    static std::vector<BaseCPU *> cpuList;   //!< Static global cpu list
376
377  public:
378    void traceFunctions(Addr pc)
379    {
380        if (functionTracingEnabled)
381            traceFunctionsInternal(pc);
382    }
383
384    static int numSimulatedCPUs() { return cpuList.size(); }
385    static Counter numSimulatedInsts()
386    {
387        Counter total = 0;
388
389        int size = cpuList.size();
390        for (int i = 0; i < size; ++i)
391            total += cpuList[i]->totalInsts();
392
393        return total;
394    }
395
396    static Counter numSimulatedOps()
397    {
398        Counter total = 0;
399
400        int size = cpuList.size();
401        for (int i = 0; i < size; ++i)
402            total += cpuList[i]->totalOps();
403
404        return total;
405    }
406
407  public:
408    // Number of CPU cycles simulated
409    Stats::Scalar numCycles;
410    Stats::Scalar numWorkItemsStarted;
411    Stats::Scalar numWorkItemsCompleted;
412};
413
414#endif // __CPU_BASE_HH__
415