system.hh revision 11839
1/*
2 * Copyright (c) 2012, 2014 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 *          Lisa Hsu
43 *          Nathan Binkert
44 *          Rick Strong
45 */
46
47#ifndef __SYSTEM_HH__
48#define __SYSTEM_HH__
49
50#include <string>
51#include <utility>
52#include <vector>
53
54#include "arch/isa_traits.hh"
55#include "base/loader/symtab.hh"
56#include "base/statistics.hh"
57#include "config/the_isa.hh"
58#include "enums/MemoryMode.hh"
59#include "mem/mem_object.hh"
60#include "mem/port.hh"
61#include "mem/port_proxy.hh"
62#include "mem/physical.hh"
63#include "params/System.hh"
64
65/**
66 * To avoid linking errors with LTO, only include the header if we
67 * actually have the definition.
68 */
69#if THE_ISA != NULL_ISA
70#include "cpu/pc_event.hh"
71#endif
72
73class BaseRemoteGDB;
74class GDBListener;
75class KvmVM;
76class ObjectFile;
77class ThreadContext;
78
79class System : public MemObject
80{
81  private:
82
83    /**
84     * Private class for the system port which is only used as a
85     * master for debug access and for non-structural entities that do
86     * not have a port of their own.
87     */
88    class SystemPort : public MasterPort
89    {
90      public:
91
92        /**
93         * Create a system port with a name and an owner.
94         */
95        SystemPort(const std::string &_name, MemObject *_owner)
96            : MasterPort(_name, _owner)
97        { }
98        bool recvTimingResp(PacketPtr pkt) override
99        { panic("SystemPort does not receive timing!\n"); return false; }
100        void recvReqRetry() override
101        { panic("SystemPort does not expect retry!\n"); }
102    };
103
104    SystemPort _systemPort;
105
106  public:
107
108    /**
109     * After all objects have been created and all ports are
110     * connected, check that the system port is connected.
111     */
112    void init() override;
113
114    /**
115     * Get a reference to the system port that can be used by
116     * non-structural simulation objects like processes or threads, or
117     * external entities like loaders and debuggers, etc, to access
118     * the memory system.
119     *
120     * @return a reference to the system port we own
121     */
122    MasterPort& getSystemPort() { return _systemPort; }
123
124    /**
125     * Additional function to return the Port of a memory object.
126     */
127    BaseMasterPort& getMasterPort(const std::string &if_name,
128                                  PortID idx = InvalidPortID) override;
129
130    /** @{ */
131    /**
132     * Is the system in atomic mode?
133     *
134     * There are currently two different atomic memory modes:
135     * 'atomic', which supports caches; and 'atomic_noncaching', which
136     * bypasses caches. The latter is used by hardware virtualized
137     * CPUs. SimObjects are expected to use Port::sendAtomic() and
138     * Port::recvAtomic() when accessing memory in this mode.
139     */
140    bool isAtomicMode() const {
141        return memoryMode == Enums::atomic ||
142            memoryMode == Enums::atomic_noncaching;
143    }
144
145    /**
146     * Is the system in timing mode?
147     *
148     * SimObjects are expected to use Port::sendTiming() and
149     * Port::recvTiming() when accessing memory in this mode.
150     */
151    bool isTimingMode() const {
152        return memoryMode == Enums::timing;
153    }
154
155    /**
156     * Should caches be bypassed?
157     *
158     * Some CPUs need to bypass caches to allow direct memory
159     * accesses, which is required for hardware virtualization.
160     */
161    bool bypassCaches() const {
162        return memoryMode == Enums::atomic_noncaching;
163    }
164    /** @} */
165
166    /** @{ */
167    /**
168     * Get the memory mode of the system.
169     *
170     * \warn This should only be used by the Python world. The C++
171     * world should use one of the query functions above
172     * (isAtomicMode(), isTimingMode(), bypassCaches()).
173     */
174    Enums::MemoryMode getMemoryMode() const { return memoryMode; }
175
176    /**
177     * Change the memory mode of the system.
178     *
179     * \warn This should only be called by the Python!
180     *
181     * @param mode Mode to change to (atomic/timing/...)
182     */
183    void setMemoryMode(Enums::MemoryMode mode);
184    /** @} */
185
186    /**
187     * Get the cache line size of the system.
188     */
189    unsigned int cacheLineSize() const { return _cacheLineSize; }
190
191#if THE_ISA != NULL_ISA
192    PCEventQueue pcEventQueue;
193#endif
194
195    std::vector<ThreadContext *> threadContexts;
196    int _numContexts;
197    const bool multiThread;
198
199    ThreadContext *getThreadContext(ContextID tid)
200    {
201        return threadContexts[tid];
202    }
203
204    int numContexts()
205    {
206        assert(_numContexts == (int)threadContexts.size());
207        return _numContexts;
208    }
209
210    /** Return number of running (non-halted) thread contexts in
211     * system.  These threads could be Active or Suspended. */
212    int numRunningContexts();
213
214    Addr pagePtr;
215
216    uint64_t init_param;
217
218    /** Port to physical memory used for writing object files into ram at
219     * boot.*/
220    PortProxy physProxy;
221
222    /** kernel symbol table */
223    SymbolTable *kernelSymtab;
224
225    /** Object pointer for the kernel code */
226    ObjectFile *kernel;
227
228    /** Beginning of kernel code */
229    Addr kernelStart;
230
231    /** End of kernel code */
232    Addr kernelEnd;
233
234    /** Entry point in the kernel to start at */
235    Addr kernelEntry;
236
237    /** Mask that should be anded for binary/symbol loading.
238     * This allows one two different OS requirements for the same ISA to be
239     * handled.  Some OSes are compiled for a virtual address and need to be
240     * loaded into physical memory that starts at address 0, while other
241     * bare metal tools generate images that start at address 0.
242     */
243    Addr loadAddrMask;
244
245    /** Offset that should be used for binary/symbol loading.
246     * This further allows more flexibility than the loadAddrMask allows alone
247     * in loading kernels and similar. The loadAddrOffset is applied after the
248     * loadAddrMask.
249     */
250    Addr loadAddrOffset;
251
252  public:
253    /**
254     * Get a pointer to the Kernel Virtual Machine (KVM) SimObject,
255     * if present.
256     */
257    KvmVM* getKvmVM() {
258        return kvmVM;
259    }
260
261    /** Get a pointer to access the physical memory of the system */
262    PhysicalMemory& getPhysMem() { return physmem; }
263
264    /** Amount of physical memory that is still free */
265    Addr freeMemSize() const;
266
267    /** Amount of physical memory that exists */
268    Addr memSize() const;
269
270    /**
271     * Check if a physical address is within a range of a memory that
272     * is part of the global address map.
273     *
274     * @param addr A physical address
275     * @return Whether the address corresponds to a memory
276     */
277    bool isMemAddr(Addr addr) const;
278
279    /**
280     * Get the architecture.
281     */
282    Arch getArch() const { return Arch::TheISA; }
283
284     /**
285     * Get the page bytes for the ISA.
286     */
287    Addr getPageBytes() const { return TheISA::PageBytes; }
288
289    /**
290     * Get the number of bits worth of in-page address for the ISA.
291     */
292    Addr getPageShift() const { return TheISA::PageShift; }
293
294    /**
295     * The thermal model used for this system (if any).
296     */
297    ThermalModel * getThermalModel() const { return thermalModel; }
298
299  protected:
300
301    KvmVM *const kvmVM;
302
303    PhysicalMemory physmem;
304
305    Enums::MemoryMode memoryMode;
306
307    const unsigned int _cacheLineSize;
308
309    uint64_t workItemsBegin;
310    uint64_t workItemsEnd;
311    uint32_t numWorkIds;
312    std::vector<bool> activeCpus;
313
314    /** This array is a per-system list of all devices capable of issuing a
315     * memory system request and an associated string for each master id.
316     * It's used to uniquely id any master in the system by name for things
317     * like cache statistics.
318     */
319    std::vector<std::string> masterIds;
320
321    ThermalModel * thermalModel;
322
323  public:
324
325    /** Request an id used to create a request object in the system. All objects
326     * that intend to issues requests into the memory system must request an id
327     * in the init() phase of startup. All master ids must be fixed by the
328     * regStats() phase that immediately precedes it. This allows objects in
329     * the memory system to understand how many masters may exist and
330     * appropriately name the bins of their per-master stats before the stats
331     * are finalized
332     */
333    MasterID getMasterId(std::string req_name);
334
335    /** Get the name of an object for a given request id.
336     */
337    std::string getMasterName(MasterID master_id);
338
339    /** Get the number of masters registered in the system */
340    MasterID maxMasters()
341    {
342        return masterIds.size();
343    }
344
345    void regStats() override;
346    /**
347     * Called by pseudo_inst to track the number of work items started by this
348     * system.
349     */
350    uint64_t
351    incWorkItemsBegin()
352    {
353        return ++workItemsBegin;
354    }
355
356    /**
357     * Called by pseudo_inst to track the number of work items completed by
358     * this system.
359     */
360    uint64_t
361    incWorkItemsEnd()
362    {
363        return ++workItemsEnd;
364    }
365
366    /**
367     * Called by pseudo_inst to mark the cpus actively executing work items.
368     * Returns the total number of cpus that have executed work item begin or
369     * ends.
370     */
371    int
372    markWorkItem(int index)
373    {
374        int count = 0;
375        assert(index < activeCpus.size());
376        activeCpus[index] = true;
377        for (std::vector<bool>::iterator i = activeCpus.begin();
378             i < activeCpus.end(); i++) {
379            if (*i) count++;
380        }
381        return count;
382    }
383
384    inline void workItemBegin(uint32_t tid, uint32_t workid)
385    {
386        std::pair<uint32_t,uint32_t> p(tid, workid);
387        lastWorkItemStarted[p] = curTick();
388    }
389
390    void workItemEnd(uint32_t tid, uint32_t workid);
391
392    /**
393     * Fix up an address used to match PCs for hooking simulator
394     * events on to target function executions.  See comment in
395     * system.cc for details.
396     */
397    virtual Addr fixFuncEventAddr(Addr addr)
398    {
399        panic("Base fixFuncEventAddr not implemented.\n");
400    }
401
402    /** @{ */
403    /**
404     * Add a function-based event to the given function, to be looked
405     * up in the specified symbol table.
406     *
407     * The ...OrPanic flavor of the method causes the simulator to
408     * panic if the symbol can't be found.
409     *
410     * @param symtab Symbol table to use for look up.
411     * @param lbl Function to hook the event to.
412     * @param desc Description to be passed to the event.
413     * @param args Arguments to be forwarded to the event constructor.
414     */
415    template <class T, typename... Args>
416    T *addFuncEvent(const SymbolTable *symtab, const char *lbl,
417                    const std::string &desc, Args... args)
418    {
419        Addr addr M5_VAR_USED = 0; // initialize only to avoid compiler warning
420
421#if THE_ISA != NULL_ISA
422        if (symtab->findAddress(lbl, addr)) {
423            T *ev = new T(&pcEventQueue, desc, fixFuncEventAddr(addr),
424                          std::forward<Args>(args)...);
425            return ev;
426        }
427#endif
428
429        return NULL;
430    }
431
432    template <class T>
433    T *addFuncEvent(const SymbolTable *symtab, const char *lbl)
434    {
435        return addFuncEvent<T>(symtab, lbl, lbl);
436    }
437
438    template <class T, typename... Args>
439    T *addFuncEventOrPanic(const SymbolTable *symtab, const char *lbl,
440                           Args... args)
441    {
442        T *e(addFuncEvent<T>(symtab, lbl, std::forward<Args>(args)...));
443        if (!e)
444            panic("Failed to find symbol '%s'", lbl);
445        return e;
446    }
447    /** @} */
448
449    /** @{ */
450    /**
451     * Add a function-based event to a kernel symbol.
452     *
453     * These functions work like their addFuncEvent() and
454     * addFuncEventOrPanic() counterparts. The only difference is that
455     * they automatically use the kernel symbol table. All arguments
456     * are forwarded to the underlying method.
457     *
458     * @see addFuncEvent()
459     * @see addFuncEventOrPanic()
460     *
461     * @param lbl Function to hook the event to.
462     * @param args Arguments to be passed to addFuncEvent
463     */
464    template <class T, typename... Args>
465    T *addKernelFuncEvent(const char *lbl, Args... args)
466    {
467        return addFuncEvent<T>(kernelSymtab, lbl,
468                               std::forward<Args>(args)...);
469    }
470
471    template <class T, typename... Args>
472    T *addKernelFuncEventOrPanic(const char *lbl, Args... args)
473    {
474        T *e(addFuncEvent<T>(kernelSymtab, lbl,
475                             std::forward<Args>(args)...));
476        if (!e)
477            panic("Failed to find kernel symbol '%s'", lbl);
478        return e;
479    }
480    /** @} */
481
482  public:
483    std::vector<BaseRemoteGDB *> remoteGDB;
484    std::vector<GDBListener *> gdbListen;
485    bool breakpoint();
486
487  public:
488    typedef SystemParams Params;
489
490  protected:
491    Params *_params;
492
493  public:
494    System(Params *p);
495    ~System();
496
497    void initState() override;
498
499    const Params *params() const { return (const Params *)_params; }
500
501  public:
502
503    /**
504     * Returns the address the kernel starts at.
505     * @return address the kernel starts at
506     */
507    Addr getKernelStart() const { return kernelStart; }
508
509    /**
510     * Returns the address the kernel ends at.
511     * @return address the kernel ends at
512     */
513    Addr getKernelEnd() const { return kernelEnd; }
514
515    /**
516     * Returns the address the entry point to the kernel code.
517     * @return entry point of the kernel code
518     */
519    Addr getKernelEntry() const { return kernelEntry; }
520
521    /// Allocate npages contiguous unused physical pages
522    /// @return Starting address of first page
523    Addr allocPhysPages(int npages);
524
525    ContextID registerThreadContext(ThreadContext *tc,
526                                    ContextID assigned = InvalidContextID);
527    void replaceThreadContext(ThreadContext *tc, ContextID context_id);
528
529    void serialize(CheckpointOut &cp) const override;
530    void unserialize(CheckpointIn &cp) override;
531
532    void drainResume() override;
533
534  public:
535    Counter totalNumInsts;
536    EventQueue instEventQueue;
537    std::map<std::pair<uint32_t,uint32_t>, Tick>  lastWorkItemStarted;
538    std::map<uint32_t, Stats::Histogram*> workItemStats;
539
540    ////////////////////////////////////////////
541    //
542    // STATIC GLOBAL SYSTEM LIST
543    //
544    ////////////////////////////////////////////
545
546    static std::vector<System *> systemList;
547    static int numSystemsRunning;
548
549    static void printSystems();
550
551    // For futex system call
552    std::map<uint64_t, std::list<ThreadContext *> * > futexMap;
553
554  protected:
555
556    /**
557     * If needed, serialize additional symbol table entries for a
558     * specific subclass of this system. Currently this is used by
559     * Alpha and MIPS.
560     *
561     * @param os stream to serialize to
562     */
563    virtual void serializeSymtab(CheckpointOut &os) const {}
564
565    /**
566     * If needed, unserialize additional symbol table entries for a
567     * specific subclass of this system.
568     *
569     * @param cp checkpoint to unserialize from
570     * @param section relevant section in the checkpoint
571     */
572    virtual void unserializeSymtab(CheckpointIn &cp) {}
573
574};
575
576void printSystems();
577
578#endif // __SYSTEM_HH__
579