base.hh revision 9817:2492d7ccda7e
1/*
2 * Copyright (c) 2011-2013 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#include "sim/system.hh"
61
62struct BaseCPUParams;
63class CheckerCPU;
64class ThreadContext;
65
66class CPUProgressEvent : public Event
67{
68  protected:
69    Tick _interval;
70    Counter lastNumInst;
71    BaseCPU *cpu;
72    bool _repeatEvent;
73
74  public:
75    CPUProgressEvent(BaseCPU *_cpu, Tick ival = 0);
76
77    void process();
78
79    void interval(Tick ival) { _interval = ival; }
80    Tick interval() { return _interval; }
81
82    void repeatEvent(bool repeat) { _repeatEvent = repeat; }
83
84    virtual const char *description() const;
85};
86
87class BaseCPU : public MemObject
88{
89  protected:
90
91    // @todo remove me after debugging with legion done
92    Tick instCnt;
93    // every cpu has an id, put it in the base cpu
94    // Set at initialization, only time a cpuId might change is during a
95    // takeover (which should be done from within the BaseCPU anyway,
96    // therefore no setCpuId() method is provided
97    int _cpuId;
98
99    /** instruction side request id that must be placed in all requests */
100    MasterID _instMasterId;
101
102    /** data side request id that must be placed in all requests */
103    MasterID _dataMasterId;
104
105    /** An intrenal representation of a task identifier within gem5. This is
106     * used so the CPU can add which taskId (which is an internal representation
107     * of the OS process ID) to each request so components in the memory system
108     * can track which process IDs are ultimately interacting with them
109     */
110    uint32_t _taskId;
111
112    /** The current OS process ID that is executing on this processor. This is
113     * used to generate a taskId */
114    uint32_t _pid;
115
116    /** Is the CPU switched out or active? */
117    bool _switchedOut;
118
119    /** Cache the cache line size that we get from the system */
120    const unsigned int _cacheLineSize;
121
122  public:
123
124    /**
125     * Purely virtual method that returns a reference to the data
126     * port. All subclasses must implement this method.
127     *
128     * @return a reference to the data port
129     */
130    virtual MasterPort &getDataPort() = 0;
131
132    /**
133     * Purely virtual method that returns a reference to the instruction
134     * port. All subclasses must implement this method.
135     *
136     * @return a reference to the instruction port
137     */
138    virtual MasterPort &getInstPort() = 0;
139
140    /** Reads this CPU's ID. */
141    int cpuId() { return _cpuId; }
142
143    /** Reads this CPU's unique data requestor ID */
144    MasterID dataMasterId() { return _dataMasterId; }
145    /** Reads this CPU's unique instruction requestor ID */
146    MasterID instMasterId() { return _instMasterId; }
147
148    /**
149     * Get a master port on this CPU. All CPUs have a data and
150     * instruction port, and this method uses getDataPort and
151     * getInstPort of the subclasses to resolve the two ports.
152     *
153     * @param if_name the port name
154     * @param idx ignored index
155     *
156     * @return a reference to the port with the given name
157     */
158    BaseMasterPort &getMasterPort(const std::string &if_name,
159                                  PortID idx = InvalidPortID);
160
161    /** Get cpu task id */
162    uint32_t taskId() const { return _taskId; }
163    /** Set cpu task id */
164    void taskId(uint32_t id) { _taskId = id; }
165
166    uint32_t getPid() const { return _pid; }
167    void setPid(uint32_t pid) { _pid = pid; }
168
169    inline void workItemBegin() { numWorkItemsStarted++; }
170    inline void workItemEnd() { numWorkItemsCompleted++; }
171    // @todo remove me after debugging with legion done
172    Tick instCount() { return instCnt; }
173
174    TheISA::MicrocodeRom microcodeRom;
175
176  protected:
177    TheISA::Interrupts *interrupts;
178
179  public:
180    TheISA::Interrupts *
181    getInterruptController()
182    {
183        return interrupts;
184    }
185
186    virtual void wakeup() = 0;
187
188    void
189    postInterrupt(int int_num, int index)
190    {
191        interrupts->post(int_num, index);
192        if (FullSystem)
193            wakeup();
194    }
195
196    void
197    clearInterrupt(int int_num, int index)
198    {
199        interrupts->clear(int_num, index);
200    }
201
202    void
203    clearInterrupts()
204    {
205        interrupts->clearAll();
206    }
207
208    bool
209    checkInterrupts(ThreadContext *tc) const
210    {
211        return FullSystem && interrupts->checkInterrupts(tc);
212    }
213
214    class ProfileEvent : public Event
215    {
216      private:
217        BaseCPU *cpu;
218        Tick interval;
219
220      public:
221        ProfileEvent(BaseCPU *cpu, Tick interval);
222        void process();
223    };
224    ProfileEvent *profileEvent;
225
226  protected:
227    std::vector<ThreadContext *> threadContexts;
228
229    Trace::InstTracer * tracer;
230
231  public:
232
233    // Mask to align PCs to MachInst sized boundaries
234    static const Addr PCMask = ~((Addr)sizeof(TheISA::MachInst) - 1);
235
236    /// Provide access to the tracer pointer
237    Trace::InstTracer * getTracer() { return tracer; }
238
239    /// Notify the CPU that the indicated context is now active.  The
240    /// delay parameter indicates the number of ticks to wait before
241    /// executing (typically 0 or 1).
242    virtual void activateContext(ThreadID thread_num, Cycles delay) {}
243
244    /// Notify the CPU that the indicated context is now suspended.
245    virtual void suspendContext(ThreadID thread_num) {}
246
247    /// Notify the CPU that the indicated context is now deallocated.
248    virtual void deallocateContext(ThreadID thread_num) {}
249
250    /// Notify the CPU that the indicated context is now halted.
251    virtual void haltContext(ThreadID thread_num) {}
252
253   /// Given a Thread Context pointer return the thread num
254   int findContext(ThreadContext *tc);
255
256   /// Given a thread num get tho thread context for it
257   virtual ThreadContext *getContext(int tn) { return threadContexts[tn]; }
258
259  public:
260    typedef BaseCPUParams Params;
261    const Params *params() const
262    { return reinterpret_cast<const Params *>(_params); }
263    BaseCPU(Params *params, bool is_checker = false);
264    virtual ~BaseCPU();
265
266    virtual void init();
267    virtual void startup();
268    virtual void regStats();
269
270    virtual void activateWhenReady(ThreadID tid) {};
271
272    void registerThreadContexts();
273
274    /**
275     * Prepare for another CPU to take over execution.
276     *
277     * When this method exits, all internal state should have been
278     * flushed. After the method returns, the simulator calls
279     * takeOverFrom() on the new CPU with this CPU as its parameter.
280     */
281    virtual void switchOut();
282
283    /**
284     * Load the state of a CPU from the previous CPU object, invoked
285     * on all new CPUs that are about to be switched in.
286     *
287     * A CPU model implementing this method is expected to initialize
288     * its state from the old CPU and connect its memory (unless they
289     * are already connected) to the memories connected to the old
290     * CPU.
291     *
292     * @param cpu CPU to initialize read state from.
293     */
294    virtual void takeOverFrom(BaseCPU *cpu);
295
296    /**
297     * Flush all TLBs in the CPU.
298     *
299     * This method is mainly used to flush stale translations when
300     * switching CPUs. It is also exported to the Python world to
301     * allow it to request a TLB flush after draining the CPU to make
302     * it easier to compare traces when debugging
303     * handover/checkpointing.
304     */
305    void flushTLBs();
306
307    /**
308     * Determine if the CPU is switched out.
309     *
310     * @return True if the CPU is switched out, false otherwise.
311     */
312    bool switchedOut() const { return _switchedOut; }
313
314    /**
315     * Verify that the system is in a memory mode supported by the
316     * CPU.
317     *
318     * Implementations are expected to query the system for the
319     * current memory mode and ensure that it is what the CPU model
320     * expects. If the check fails, the implementation should
321     * terminate the simulation using fatal().
322     */
323    virtual void verifyMemoryMode() const { };
324
325    /**
326     *  Number of threads we're actually simulating (<= SMT_MAX_THREADS).
327     * This is a constant for the duration of the simulation.
328     */
329    ThreadID numThreads;
330
331    /**
332     * Vector of per-thread instruction-based event queues.  Used for
333     * scheduling events based on number of instructions committed by
334     * a particular thread.
335     */
336    EventQueue **comInstEventQueue;
337
338    /**
339     * Vector of per-thread load-based event queues.  Used for
340     * scheduling events based on number of loads committed by
341     *a particular thread.
342     */
343    EventQueue **comLoadEventQueue;
344
345    System *system;
346
347    /**
348     * Get the cache line size of the system.
349     */
350    inline unsigned int cacheLineSize() const { return _cacheLineSize; }
351
352    /**
353     * Serialize this object to the given output stream.
354     *
355     * @note CPU models should normally overload the serializeThread()
356     * method instead of the serialize() method as this provides a
357     * uniform data format for all CPU models and promotes better code
358     * reuse.
359     *
360     * @param os The stream to serialize to.
361     */
362    virtual void serialize(std::ostream &os);
363
364    /**
365     * Reconstruct the state of this object from a checkpoint.
366     *
367     * @note CPU models should normally overload the
368     * unserializeThread() method instead of the unserialize() method
369     * as this provides a uniform data format for all CPU models and
370     * promotes better code reuse.
371
372     * @param cp The checkpoint use.
373     * @param section The section name of this object.
374     */
375    virtual void unserialize(Checkpoint *cp, const std::string &section);
376
377    /**
378     * Serialize a single thread.
379     *
380     * @param os The stream to serialize to.
381     * @param tid ID of the current thread.
382     */
383    virtual void serializeThread(std::ostream &os, ThreadID tid) {};
384
385    /**
386     * Unserialize one thread.
387     *
388     * @param cp The checkpoint use.
389     * @param section The section name of this thread.
390     * @param tid ID of the current thread.
391     */
392    virtual void unserializeThread(Checkpoint *cp, const std::string &section,
393                                   ThreadID tid) {};
394
395    virtual Counter totalInsts() const = 0;
396
397    virtual Counter totalOps() const = 0;
398
399    /**
400     * Schedule an event that exits the simulation loops after a
401     * predefined number of instructions.
402     *
403     * This method is usually called from the configuration script to
404     * get an exit event some time in the future. It is typically used
405     * when the script wants to simulate for a specific number of
406     * instructions rather than ticks.
407     *
408     * @param tid Thread monitor.
409     * @param insts Number of instructions into the future.
410     * @param cause Cause to signal in the exit event.
411     */
412    void scheduleInstStop(ThreadID tid, Counter insts, const char *cause);
413
414    /**
415     * Schedule an event that exits the simulation loops after a
416     * predefined number of load operations.
417     *
418     * This method is usually called from the configuration script to
419     * get an exit event some time in the future. It is typically used
420     * when the script wants to simulate for a specific number of
421     * loads rather than ticks.
422     *
423     * @param tid Thread monitor.
424     * @param loads Number of load instructions into the future.
425     * @param cause Cause to signal in the exit event.
426     */
427    void scheduleLoadStop(ThreadID tid, Counter loads, const char *cause);
428
429    // Function tracing
430  private:
431    bool functionTracingEnabled;
432    std::ostream *functionTraceStream;
433    Addr currentFunctionStart;
434    Addr currentFunctionEnd;
435    Tick functionEntryTick;
436    void enableFunctionTrace();
437    void traceFunctionsInternal(Addr pc);
438
439  private:
440    static std::vector<BaseCPU *> cpuList;   //!< Static global cpu list
441
442  public:
443    void traceFunctions(Addr pc)
444    {
445        if (functionTracingEnabled)
446            traceFunctionsInternal(pc);
447    }
448
449    static int numSimulatedCPUs() { return cpuList.size(); }
450    static Counter numSimulatedInsts()
451    {
452        Counter total = 0;
453
454        int size = cpuList.size();
455        for (int i = 0; i < size; ++i)
456            total += cpuList[i]->totalInsts();
457
458        return total;
459    }
460
461    static Counter numSimulatedOps()
462    {
463        Counter total = 0;
464
465        int size = cpuList.size();
466        for (int i = 0; i < size; ++i)
467            total += cpuList[i]->totalOps();
468
469        return total;
470    }
471
472  public:
473    // Number of CPU cycles simulated
474    Stats::Scalar numCycles;
475    Stats::Scalar numWorkItemsStarted;
476    Stats::Scalar numWorkItemsCompleted;
477};
478
479#endif // __CPU_BASE_HH__
480