base.hh revision 9652
111420Sdavid.guillen@arm.com/*
211420Sdavid.guillen@arm.com * Copyright (c) 2011-2013 ARM Limited
311420Sdavid.guillen@arm.com * All rights reserved
411420Sdavid.guillen@arm.com *
511420Sdavid.guillen@arm.com * The license below extends only to copyright in the software and shall
611420Sdavid.guillen@arm.com * not be construed as granting a license to any other intellectual
711420Sdavid.guillen@arm.com * property including but not limited to intellectual property relating
811420Sdavid.guillen@arm.com * to a hardware implementation of the functionality of the software
911420Sdavid.guillen@arm.com * licensed hereunder.  You may use the software subject to the license
1011420Sdavid.guillen@arm.com * terms below provided that you ensure that this notice is replicated
1111420Sdavid.guillen@arm.com * unmodified and in its entirety in all distributions of the software,
1211420Sdavid.guillen@arm.com * modified or unmodified, in source code or in binary form.
1311420Sdavid.guillen@arm.com *
1411420Sdavid.guillen@arm.com * Copyright (c) 2002-2005 The Regents of The University of Michigan
1511420Sdavid.guillen@arm.com * Copyright (c) 2011 Regents of the University of California
1611420Sdavid.guillen@arm.com * All rights reserved.
1711420Sdavid.guillen@arm.com *
1811420Sdavid.guillen@arm.com * Redistribution and use in source and binary forms, with or without
1911420Sdavid.guillen@arm.com * modification, are permitted provided that the following conditions are
2011420Sdavid.guillen@arm.com * met: redistributions of source code must retain the above copyright
2111420Sdavid.guillen@arm.com * notice, this list of conditions and the following disclaimer;
2211420Sdavid.guillen@arm.com * redistributions in binary form must reproduce the above copyright
2311420Sdavid.guillen@arm.com * notice, this list of conditions and the following disclaimer in the
2411420Sdavid.guillen@arm.com * documentation and/or other materials provided with the distribution;
2511420Sdavid.guillen@arm.com * neither the name of the copyright holders nor the names of its
2611420Sdavid.guillen@arm.com * contributors may be used to endorse or promote products derived from
2711420Sdavid.guillen@arm.com * this software without specific prior written permission.
2811420Sdavid.guillen@arm.com *
2911420Sdavid.guillen@arm.com * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
3011420Sdavid.guillen@arm.com * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3111420Sdavid.guillen@arm.com * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3211420Sdavid.guillen@arm.com * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3311420Sdavid.guillen@arm.com * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3411420Sdavid.guillen@arm.com * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3511420Sdavid.guillen@arm.com * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3611420Sdavid.guillen@arm.com * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3711420Sdavid.guillen@arm.com * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3811420Sdavid.guillen@arm.com * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3911420Sdavid.guillen@arm.com * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4011420Sdavid.guillen@arm.com *
4111420Sdavid.guillen@arm.com * Authors: Steve Reinhardt
4211420Sdavid.guillen@arm.com *          Nathan Binkert
4311420Sdavid.guillen@arm.com *          Rick Strong
4411420Sdavid.guillen@arm.com */
4511420Sdavid.guillen@arm.com
4611420Sdavid.guillen@arm.com#ifndef __CPU_BASE_HH__
4711420Sdavid.guillen@arm.com#define __CPU_BASE_HH__
4811899Sandreas.sandberg@arm.com
4911420Sdavid.guillen@arm.com#include <vector>
5011899Sandreas.sandberg@arm.com
5111420Sdavid.guillen@arm.com#include "arch/interrupts.hh"
5211800Sbrandon.potter@amd.com#include "arch/isa_traits.hh"
5311420Sdavid.guillen@arm.com#include "arch/microcode_rom.hh"
5411420Sdavid.guillen@arm.com#include "base/statistics.hh"
5511420Sdavid.guillen@arm.com#include "config/the_isa.hh"
5611420Sdavid.guillen@arm.com#include "mem/mem_object.hh"
5711420Sdavid.guillen@arm.com#include "sim/eventq.hh"
5811420Sdavid.guillen@arm.com#include "sim/full_system.hh"
5911420Sdavid.guillen@arm.com#include "sim/insttracer.hh"
6011420Sdavid.guillen@arm.com
6111420Sdavid.guillen@arm.comstruct BaseCPUParams;
6211420Sdavid.guillen@arm.comclass BranchPred;
6311420Sdavid.guillen@arm.comclass CheckerCPU;
6411420Sdavid.guillen@arm.comclass ThreadContext;
6511420Sdavid.guillen@arm.comclass System;
6611420Sdavid.guillen@arm.com
6711420Sdavid.guillen@arm.comclass CPUProgressEvent : public Event
6811420Sdavid.guillen@arm.com{
6911420Sdavid.guillen@arm.com  protected:
7011420Sdavid.guillen@arm.com    Tick _interval;
7111420Sdavid.guillen@arm.com    Counter lastNumInst;
7211420Sdavid.guillen@arm.com    BaseCPU *cpu;
7311420Sdavid.guillen@arm.com    bool _repeatEvent;
7411420Sdavid.guillen@arm.com
7511420Sdavid.guillen@arm.com  public:
7611420Sdavid.guillen@arm.com    CPUProgressEvent(BaseCPU *_cpu, Tick ival = 0);
7711420Sdavid.guillen@arm.com
7811420Sdavid.guillen@arm.com    void process();
7911420Sdavid.guillen@arm.com
8011420Sdavid.guillen@arm.com    void interval(Tick ival) { _interval = ival; }
8111420Sdavid.guillen@arm.com    Tick interval() { return _interval; }
8211420Sdavid.guillen@arm.com
8311420Sdavid.guillen@arm.com    void repeatEvent(bool repeat) { _repeatEvent = repeat; }
8411420Sdavid.guillen@arm.com
8511420Sdavid.guillen@arm.com    virtual const char *description() const;
8611442Sandreas.hansson@arm.com};
8711420Sdavid.guillen@arm.com
8811420Sdavid.guillen@arm.comclass BaseCPU : public MemObject
8911420Sdavid.guillen@arm.com{
9011420Sdavid.guillen@arm.com  protected:
9111420Sdavid.guillen@arm.com
9211420Sdavid.guillen@arm.com    // @todo remove me after debugging with legion done
9311420Sdavid.guillen@arm.com    Tick instCnt;
9411420Sdavid.guillen@arm.com    // every cpu has an id, put it in the base cpu
9511420Sdavid.guillen@arm.com    // Set at initialization, only time a cpuId might change is during a
9611420Sdavid.guillen@arm.com    // takeover (which should be done from within the BaseCPU anyway,
9711420Sdavid.guillen@arm.com    // therefore no setCpuId() method is provided
9811442Sandreas.hansson@arm.com    int _cpuId;
9911420Sdavid.guillen@arm.com
10011420Sdavid.guillen@arm.com    /** instruction side request id that must be placed in all requests */
10111420Sdavid.guillen@arm.com    MasterID _instMasterId;
10211420Sdavid.guillen@arm.com
10311420Sdavid.guillen@arm.com    /** data side request id that must be placed in all requests */
10411420Sdavid.guillen@arm.com    MasterID _dataMasterId;
10511420Sdavid.guillen@arm.com
10611420Sdavid.guillen@arm.com    /** An intrenal representation of a task identifier within gem5. This is
10711420Sdavid.guillen@arm.com     * used so the CPU can add which taskId (which is an internal representation
10811420Sdavid.guillen@arm.com     * of the OS process ID) to each request so components in the memory system
10911420Sdavid.guillen@arm.com     * can track which process IDs are ultimately interacting with them
11011420Sdavid.guillen@arm.com     */
11111420Sdavid.guillen@arm.com    uint32_t _taskId;
11211420Sdavid.guillen@arm.com
11311420Sdavid.guillen@arm.com    /** The current OS process ID that is executing on this processor. This is
11411420Sdavid.guillen@arm.com     * used to generate a taskId */
11511420Sdavid.guillen@arm.com    uint32_t _pid;
116
117    /** Is the CPU switched out or active? */
118    bool _switchedOut;
119
120  public:
121
122    /**
123     * Purely virtual method that returns a reference to the data
124     * port. All subclasses must implement this method.
125     *
126     * @return a reference to the data port
127     */
128    virtual MasterPort &getDataPort() = 0;
129
130    /**
131     * Purely virtual method that returns a reference to the instruction
132     * port. All subclasses must implement this method.
133     *
134     * @return a reference to the instruction port
135     */
136    virtual MasterPort &getInstPort() = 0;
137
138    /** Reads this CPU's ID. */
139    int cpuId() { return _cpuId; }
140
141    /** Reads this CPU's unique data requestor ID */
142    MasterID dataMasterId() { return _dataMasterId; }
143    /** Reads this CPU's unique instruction requestor ID */
144    MasterID instMasterId() { return _instMasterId; }
145
146    /**
147     * Get a master port on this CPU. All CPUs have a data and
148     * instruction port, and this method uses getDataPort and
149     * getInstPort of the subclasses to resolve the two ports.
150     *
151     * @param if_name the port name
152     * @param idx ignored index
153     *
154     * @return a reference to the port with the given name
155     */
156    BaseMasterPort &getMasterPort(const std::string &if_name,
157                                  PortID idx = InvalidPortID);
158
159    /** Get cpu task id */
160    uint32_t taskId() const { return _taskId; }
161    /** Set cpu task id */
162    void taskId(uint32_t id) { _taskId = id; }
163
164    uint32_t getPid() const { return _pid; }
165    void setPid(uint32_t pid) { _pid = pid; }
166
167    inline void workItemBegin() { numWorkItemsStarted++; }
168    inline void workItemEnd() { numWorkItemsCompleted++; }
169    // @todo remove me after debugging with legion done
170    Tick instCount() { return instCnt; }
171
172    TheISA::MicrocodeRom microcodeRom;
173
174  protected:
175    TheISA::Interrupts *interrupts;
176
177  public:
178    TheISA::Interrupts *
179    getInterruptController()
180    {
181        return interrupts;
182    }
183
184    virtual void wakeup() = 0;
185
186    void
187    postInterrupt(int int_num, int index)
188    {
189        interrupts->post(int_num, index);
190        if (FullSystem)
191            wakeup();
192    }
193
194    void
195    clearInterrupt(int int_num, int index)
196    {
197        interrupts->clear(int_num, index);
198    }
199
200    void
201    clearInterrupts()
202    {
203        interrupts->clearAll();
204    }
205
206    bool
207    checkInterrupts(ThreadContext *tc) const
208    {
209        return FullSystem && interrupts->checkInterrupts(tc);
210    }
211
212    class ProfileEvent : public Event
213    {
214      private:
215        BaseCPU *cpu;
216        Tick interval;
217
218      public:
219        ProfileEvent(BaseCPU *cpu, Tick interval);
220        void process();
221    };
222    ProfileEvent *profileEvent;
223
224  protected:
225    std::vector<ThreadContext *> threadContexts;
226
227    Trace::InstTracer * tracer;
228
229  public:
230
231    // Mask to align PCs to MachInst sized boundaries
232    static const Addr PCMask = ~((Addr)sizeof(TheISA::MachInst) - 1);
233
234    /// Provide access to the tracer pointer
235    Trace::InstTracer * getTracer() { return tracer; }
236
237    /// Notify the CPU that the indicated context is now active.  The
238    /// delay parameter indicates the number of ticks to wait before
239    /// executing (typically 0 or 1).
240    virtual void activateContext(ThreadID thread_num, Cycles delay) {}
241
242    /// Notify the CPU that the indicated context is now suspended.
243    virtual void suspendContext(ThreadID thread_num) {}
244
245    /// Notify the CPU that the indicated context is now deallocated.
246    virtual void deallocateContext(ThreadID thread_num) {}
247
248    /// Notify the CPU that the indicated context is now halted.
249    virtual void haltContext(ThreadID thread_num) {}
250
251   /// Given a Thread Context pointer return the thread num
252   int findContext(ThreadContext *tc);
253
254   /// Given a thread num get tho thread context for it
255   virtual ThreadContext *getContext(int tn) { return threadContexts[tn]; }
256
257  public:
258    typedef BaseCPUParams Params;
259    const Params *params() const
260    { return reinterpret_cast<const Params *>(_params); }
261    BaseCPU(Params *params, bool is_checker = false);
262    virtual ~BaseCPU();
263
264    virtual void init();
265    virtual void startup();
266    virtual void regStats();
267
268    virtual void activateWhenReady(ThreadID tid) {};
269
270    void registerThreadContexts();
271
272    /**
273     * Prepare for another CPU to take over execution.
274     *
275     * When this method exits, all internal state should have been
276     * flushed. After the method returns, the simulator calls
277     * takeOverFrom() on the new CPU with this CPU as its parameter.
278     */
279    virtual void switchOut();
280
281    /**
282     * Load the state of a CPU from the previous CPU object, invoked
283     * on all new CPUs that are about to be switched in.
284     *
285     * A CPU model implementing this method is expected to initialize
286     * its state from the old CPU and connect its memory (unless they
287     * are already connected) to the memories connected to the old
288     * CPU.
289     *
290     * @param cpu CPU to initialize read state from.
291     */
292    virtual void takeOverFrom(BaseCPU *cpu);
293
294    /**
295     * Flush all TLBs in the CPU.
296     *
297     * This method is mainly used to flush stale translations when
298     * switching CPUs. It is also exported to the Python world to
299     * allow it to request a TLB flush after draining the CPU to make
300     * it easier to compare traces when debugging
301     * handover/checkpointing.
302     */
303    void flushTLBs();
304
305    /**
306     * Determine if the CPU is switched out.
307     *
308     * @return True if the CPU is switched out, false otherwise.
309     */
310    bool switchedOut() const { return _switchedOut; }
311
312    /**
313     * Verify that the system is in a memory mode supported by the
314     * CPU.
315     *
316     * Implementations are expected to query the system for the
317     * current memory mode and ensure that it is what the CPU model
318     * expects. If the check fails, the implementation should
319     * terminate the simulation using fatal().
320     */
321    virtual void verifyMemoryMode() const { };
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     *
348     * @note CPU models should normally overload the serializeThread()
349     * method instead of the serialize() method as this provides a
350     * uniform data format for all CPU models and promotes better code
351     * reuse.
352     *
353     * @param os The stream to serialize to.
354     */
355    virtual void serialize(std::ostream &os);
356
357    /**
358     * Reconstruct the state of this object from a checkpoint.
359     *
360     * @note CPU models should normally overload the
361     * unserializeThread() method instead of the unserialize() method
362     * as this provides a uniform data format for all CPU models and
363     * promotes better code reuse.
364
365     * @param cp The checkpoint use.
366     * @param section The section name of this object.
367     */
368    virtual void unserialize(Checkpoint *cp, const std::string &section);
369
370    /**
371     * Serialize a single thread.
372     *
373     * @param os The stream to serialize to.
374     * @param tid ID of the current thread.
375     */
376    virtual void serializeThread(std::ostream &os, ThreadID tid) {};
377
378    /**
379     * Unserialize one thread.
380     *
381     * @param cp The checkpoint use.
382     * @param section The section name of this thread.
383     * @param tid ID of the current thread.
384     */
385    virtual void unserializeThread(Checkpoint *cp, const std::string &section,
386                                   ThreadID tid) {};
387
388    /**
389     * Return pointer to CPU's branch predictor (NULL if none).
390     * @return Branch predictor pointer.
391     */
392    virtual BranchPred *getBranchPred() { return NULL; };
393
394    virtual Counter totalInsts() const = 0;
395
396    virtual Counter totalOps() const = 0;
397
398    // Function tracing
399  private:
400    bool functionTracingEnabled;
401    std::ostream *functionTraceStream;
402    Addr currentFunctionStart;
403    Addr currentFunctionEnd;
404    Tick functionEntryTick;
405    void enableFunctionTrace();
406    void traceFunctionsInternal(Addr pc);
407
408  private:
409    static std::vector<BaseCPU *> cpuList;   //!< Static global cpu list
410
411  public:
412    void traceFunctions(Addr pc)
413    {
414        if (functionTracingEnabled)
415            traceFunctionsInternal(pc);
416    }
417
418    static int numSimulatedCPUs() { return cpuList.size(); }
419    static Counter numSimulatedInsts()
420    {
421        Counter total = 0;
422
423        int size = cpuList.size();
424        for (int i = 0; i < size; ++i)
425            total += cpuList[i]->totalInsts();
426
427        return total;
428    }
429
430    static Counter numSimulatedOps()
431    {
432        Counter total = 0;
433
434        int size = cpuList.size();
435        for (int i = 0; i < size; ++i)
436            total += cpuList[i]->totalOps();
437
438        return total;
439    }
440
441  public:
442    // Number of CPU cycles simulated
443    Stats::Scalar numCycles;
444    Stats::Scalar numWorkItemsStarted;
445    Stats::Scalar numWorkItemsCompleted;
446};
447
448#endif // __CPU_BASE_HH__
449