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