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