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