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