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