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