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