system.hh revision 13784:1941dc118243
1/*
2 * Copyright (c) 2012, 2014, 2018 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_master.hh"
61#include "mem/mem_object.hh"
62#include "mem/physical.hh"
63#include "mem/port.hh"
64#include "mem/port_proxy.hh"
65#include "params/System.hh"
66#include "sim/futex_map.hh"
67#include "sim/se_signal.hh"
68
69/**
70 * To avoid linking errors with LTO, only include the header if we
71 * actually have the definition.
72 */
73#if THE_ISA != NULL_ISA
74#include "cpu/pc_event.hh"
75
76#endif
77
78class BaseRemoteGDB;
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    Port &getPort(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    const bool multiThread;
201
202    ThreadContext *getThreadContext(ContextID tid)
203    {
204        return threadContexts[tid];
205    }
206
207    unsigned numContexts() const { return threadContexts.size(); }
208
209    /** Return number of running (non-halted) thread contexts in
210     * system.  These threads could be Active or Suspended. */
211    int numRunningContexts();
212
213    Addr pagePtr;
214
215    uint64_t init_param;
216
217    /** Port to physical memory used for writing object files into ram at
218     * boot.*/
219    PortProxy physProxy;
220
221    /** kernel symbol table */
222    SymbolTable *kernelSymtab;
223
224    /** Object pointer for the kernel code */
225    ObjectFile *kernel;
226
227    /** Additional object files */
228    std::vector<ObjectFile *> kernelExtras;
229
230    /** Beginning of kernel code */
231    Addr kernelStart;
232
233    /** End of kernel code */
234    Addr kernelEnd;
235
236    /** Entry point in the kernel to start at */
237    Addr kernelEntry;
238
239    /** Mask that should be anded for binary/symbol loading.
240     * This allows one two different OS requirements for the same ISA to be
241     * handled.  Some OSes are compiled for a virtual address and need to be
242     * loaded into physical memory that starts at address 0, while other
243     * bare metal tools generate images that start at address 0.
244     */
245    Addr loadAddrMask;
246
247    /** Offset that should be used for binary/symbol loading.
248     * This further allows more flexibility than the loadAddrMask allows alone
249     * in loading kernels and similar. The loadAddrOffset is applied after the
250     * loadAddrMask.
251     */
252    Addr loadAddrOffset;
253
254  public:
255    /**
256     * Get a pointer to the Kernel Virtual Machine (KVM) SimObject,
257     * if present.
258     */
259    KvmVM* getKvmVM() {
260        return kvmVM;
261    }
262
263    /** Verify gem5 configuration will support KVM emulation */
264    bool validKvmEnvironment() const;
265
266    /** Get a pointer to access the physical memory of the system */
267    PhysicalMemory& getPhysMem() { return physmem; }
268
269    /** Amount of physical memory that is still free */
270    Addr freeMemSize() const;
271
272    /** Amount of physical memory that exists */
273    Addr memSize() const;
274
275    /**
276     * Check if a physical address is within a range of a memory that
277     * is part of the global address map.
278     *
279     * @param addr A physical address
280     * @return Whether the address corresponds to a memory
281     */
282    bool isMemAddr(Addr addr) const;
283
284    /**
285     * Get the architecture.
286     */
287    Arch getArch() const { return Arch::TheISA; }
288
289     /**
290     * Get the page bytes for the ISA.
291     */
292    Addr getPageBytes() const { return TheISA::PageBytes; }
293
294    /**
295     * Get the number of bits worth of in-page address for the ISA.
296     */
297    Addr getPageShift() const { return TheISA::PageShift; }
298
299    /**
300     * The thermal model used for this system (if any).
301     */
302    ThermalModel * getThermalModel() const { return thermalModel; }
303
304  protected:
305
306    KvmVM *const kvmVM;
307
308    PhysicalMemory physmem;
309
310    Enums::MemoryMode memoryMode;
311
312    const unsigned int _cacheLineSize;
313
314    uint64_t workItemsBegin;
315    uint64_t workItemsEnd;
316    uint32_t numWorkIds;
317    std::vector<bool> activeCpus;
318
319    /** This array is a per-system list of all devices capable of issuing a
320     * memory system request and an associated string for each master id.
321     * It's used to uniquely id any master in the system by name for things
322     * like cache statistics.
323     */
324    std::vector<MasterInfo> masters;
325
326    ThermalModel * thermalModel;
327
328  protected:
329    /**
330     * Strips off the system name from a master name
331     */
332    std::string stripSystemName(const std::string& master_name) const;
333
334  public:
335
336    /**
337     * Request an id used to create a request object in the system. All objects
338     * that intend to issues requests into the memory system must request an id
339     * in the init() phase of startup. All master ids must be fixed by the
340     * regStats() phase that immediately precedes it. This allows objects in
341     * the memory system to understand how many masters may exist and
342     * appropriately name the bins of their per-master stats before the stats
343     * are finalized.
344     *
345     * Registers a MasterID:
346     * This method takes two parameters, one of which is optional.
347     * The first one is the master object, and it is compulsory; in case
348     * a object has multiple (sub)masters, a second parameter must be
349     * provided and it contains the name of the submaster. The method will
350     * create a master's name by concatenating the SimObject name with the
351     * eventual submaster string, separated by a dot.
352     *
353     * As an example:
354     * For a cpu having two masters: a data master and an instruction master,
355     * the method must be called twice:
356     *
357     * instMasterId = getMasterId(cpu, "inst");
358     * dataMasterId = getMasterId(cpu, "data");
359     *
360     * and the masters' names will be:
361     * - "cpu.inst"
362     * - "cpu.data"
363     *
364     * @param master SimObject related to the master
365     * @param submaster String containing the submaster's name
366     * @return the master's ID.
367     */
368    MasterID getMasterId(const SimObject* master,
369                         std::string submaster = std::string());
370
371    /**
372     * Registers a GLOBAL MasterID, which is a MasterID not related
373     * to any particular SimObject; since no SimObject is passed,
374     * the master gets registered by providing the full master name.
375     *
376     * @param masterName full name of the master
377     * @return the master's ID.
378     */
379    MasterID getGlobalMasterId(const std::string& master_name);
380
381    /**
382     * Get the name of an object for a given request id.
383     */
384    std::string getMasterName(MasterID master_id);
385
386    /**
387     * Looks up the MasterID for a given SimObject
388     * returns an invalid MasterID (invldMasterId) if not found.
389     */
390    MasterID lookupMasterId(const SimObject* obj) const;
391
392    /**
393     * Looks up the MasterID for a given object name string
394     * returns an invalid MasterID (invldMasterId) if not found.
395     */
396    MasterID lookupMasterId(const std::string& name) const;
397
398    /** Get the number of masters registered in the system */
399    MasterID maxMasters() { return masters.size(); }
400
401  protected:
402    /** helper function for getMasterId */
403    MasterID _getMasterId(const SimObject* master,
404                          const std::string& master_name);
405
406    /**
407     * Helper function for constructing the full (sub)master name
408     * by providing the root master and the relative submaster name.
409     */
410    std::string leafMasterName(const SimObject* master,
411                               const std::string& submaster);
412
413  public:
414
415    void regStats() override;
416    /**
417     * Called by pseudo_inst to track the number of work items started by this
418     * system.
419     */
420    uint64_t
421    incWorkItemsBegin()
422    {
423        return ++workItemsBegin;
424    }
425
426    /**
427     * Called by pseudo_inst to track the number of work items completed by
428     * this system.
429     */
430    uint64_t
431    incWorkItemsEnd()
432    {
433        return ++workItemsEnd;
434    }
435
436    /**
437     * Called by pseudo_inst to mark the cpus actively executing work items.
438     * Returns the total number of cpus that have executed work item begin or
439     * ends.
440     */
441    int
442    markWorkItem(int index)
443    {
444        int count = 0;
445        assert(index < activeCpus.size());
446        activeCpus[index] = true;
447        for (std::vector<bool>::iterator i = activeCpus.begin();
448             i < activeCpus.end(); i++) {
449            if (*i) count++;
450        }
451        return count;
452    }
453
454    inline void workItemBegin(uint32_t tid, uint32_t workid)
455    {
456        std::pair<uint32_t,uint32_t> p(tid, workid);
457        lastWorkItemStarted[p] = curTick();
458    }
459
460    void workItemEnd(uint32_t tid, uint32_t workid);
461
462    /**
463     * Fix up an address used to match PCs for hooking simulator
464     * events on to target function executions.  See comment in
465     * system.cc for details.
466     */
467    virtual Addr fixFuncEventAddr(Addr addr)
468    {
469        panic("Base fixFuncEventAddr not implemented.\n");
470    }
471
472    /** @{ */
473    /**
474     * Add a function-based event to the given function, to be looked
475     * up in the specified symbol table.
476     *
477     * The ...OrPanic flavor of the method causes the simulator to
478     * panic if the symbol can't be found.
479     *
480     * @param symtab Symbol table to use for look up.
481     * @param lbl Function to hook the event to.
482     * @param desc Description to be passed to the event.
483     * @param args Arguments to be forwarded to the event constructor.
484     */
485    template <class T, typename... Args>
486    T *addFuncEvent(const SymbolTable *symtab, const char *lbl,
487                    const std::string &desc, Args... args)
488    {
489        Addr addr M5_VAR_USED = 0; // initialize only to avoid compiler warning
490
491#if THE_ISA != NULL_ISA
492        if (symtab->findAddress(lbl, addr)) {
493            T *ev = new T(&pcEventQueue, desc, fixFuncEventAddr(addr),
494                          std::forward<Args>(args)...);
495            return ev;
496        }
497#endif
498
499        return NULL;
500    }
501
502    template <class T>
503    T *addFuncEvent(const SymbolTable *symtab, const char *lbl)
504    {
505        return addFuncEvent<T>(symtab, lbl, lbl);
506    }
507
508    template <class T, typename... Args>
509    T *addFuncEventOrPanic(const SymbolTable *symtab, const char *lbl,
510                           Args... args)
511    {
512        T *e(addFuncEvent<T>(symtab, lbl, std::forward<Args>(args)...));
513        if (!e)
514            panic("Failed to find symbol '%s'", lbl);
515        return e;
516    }
517    /** @} */
518
519    /** @{ */
520    /**
521     * Add a function-based event to a kernel symbol.
522     *
523     * These functions work like their addFuncEvent() and
524     * addFuncEventOrPanic() counterparts. The only difference is that
525     * they automatically use the kernel symbol table. All arguments
526     * are forwarded to the underlying method.
527     *
528     * @see addFuncEvent()
529     * @see addFuncEventOrPanic()
530     *
531     * @param lbl Function to hook the event to.
532     * @param args Arguments to be passed to addFuncEvent
533     */
534    template <class T, typename... Args>
535    T *addKernelFuncEvent(const char *lbl, Args... args)
536    {
537        return addFuncEvent<T>(kernelSymtab, lbl,
538                               std::forward<Args>(args)...);
539    }
540
541    template <class T, typename... Args>
542    T *addKernelFuncEventOrPanic(const char *lbl, Args... args)
543    {
544        T *e(addFuncEvent<T>(kernelSymtab, lbl,
545                             std::forward<Args>(args)...));
546        if (!e)
547            panic("Failed to find kernel symbol '%s'", lbl);
548        return e;
549    }
550    /** @} */
551
552  public:
553    std::vector<BaseRemoteGDB *> remoteGDB;
554    bool breakpoint();
555
556  public:
557    typedef SystemParams Params;
558
559  protected:
560    Params *_params;
561
562  public:
563    System(Params *p);
564    ~System();
565
566    void initState() override;
567
568    const Params *params() const { return (const Params *)_params; }
569
570  public:
571
572    /**
573     * Returns the address the kernel starts at.
574     * @return address the kernel starts at
575     */
576    Addr getKernelStart() const { return kernelStart; }
577
578    /**
579     * Returns the address the kernel ends at.
580     * @return address the kernel ends at
581     */
582    Addr getKernelEnd() const { return kernelEnd; }
583
584    /**
585     * Returns the address the entry point to the kernel code.
586     * @return entry point of the kernel code
587     */
588    Addr getKernelEntry() const { return kernelEntry; }
589
590    /// Allocate npages contiguous unused physical pages
591    /// @return Starting address of first page
592    Addr allocPhysPages(int npages);
593
594    ContextID registerThreadContext(ThreadContext *tc,
595                                    ContextID assigned = InvalidContextID);
596    void replaceThreadContext(ThreadContext *tc, ContextID context_id);
597
598    void serialize(CheckpointOut &cp) const override;
599    void unserialize(CheckpointIn &cp) override;
600
601    void drainResume() override;
602
603  public:
604    Counter totalNumInsts;
605    EventQueue instEventQueue;
606    std::map<std::pair<uint32_t,uint32_t>, Tick>  lastWorkItemStarted;
607    std::map<uint32_t, Stats::Histogram*> workItemStats;
608
609    ////////////////////////////////////////////
610    //
611    // STATIC GLOBAL SYSTEM LIST
612    //
613    ////////////////////////////////////////////
614
615    static std::vector<System *> systemList;
616    static int numSystemsRunning;
617
618    static void printSystems();
619
620    FutexMap futexMap;
621
622    static const int maxPID = 32768;
623
624    /** Process set to track which PIDs have already been allocated */
625    std::set<int> PIDs;
626
627    // By convention, all signals are owned by the receiving process. The
628    // receiver will delete the signal upon reception.
629    std::list<BasicSignal> signalList;
630
631  protected:
632
633    /**
634     * If needed, serialize additional symbol table entries for a
635     * specific subclass of this system. Currently this is used by
636     * Alpha and MIPS.
637     *
638     * @param os stream to serialize to
639     */
640    virtual void serializeSymtab(CheckpointOut &os) const {}
641
642    /**
643     * If needed, unserialize additional symbol table entries for a
644     * specific subclass of this system.
645     *
646     * @param cp checkpoint to unserialize from
647     * @param section relevant section in the checkpoint
648     */
649    virtual void unserializeSymtab(CheckpointIn &cp) {}
650
651};
652
653void printSystems();
654
655#endif // __SYSTEM_HH__
656