system.hh revision 11838:0b311345ac72
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    /** Beginning 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 flexibility than the loadAddrMask allows alone
246     * in loading kernels and similar. The loadAddrOffset is applied after the
247     * loadAddrMask.
248     */
249    Addr loadAddrOffset;
250
251  public:
252    /** Get a pointer to access the physical memory of the system */
253    PhysicalMemory& getPhysMem() { return physmem; }
254
255    /** Amount of physical memory that is still free */
256    Addr freeMemSize() const;
257
258    /** Amount of physical memory that exists */
259    Addr memSize() const;
260
261    /**
262     * Check if a physical address is within a range of a memory that
263     * is part of the global address map.
264     *
265     * @param addr A physical address
266     * @return Whether the address corresponds to a memory
267     */
268    bool isMemAddr(Addr addr) const;
269
270    /**
271     * Get the architecture.
272     */
273    Arch getArch() const { return Arch::TheISA; }
274
275     /**
276     * Get the page bytes for the ISA.
277     */
278    Addr getPageBytes() const { return TheISA::PageBytes; }
279
280    /**
281     * Get the number of bits worth of in-page address for the ISA.
282     */
283    Addr getPageShift() const { return TheISA::PageShift; }
284
285    /**
286     * The thermal model used for this system (if any).
287     */
288    ThermalModel * getThermalModel() const { return thermalModel; }
289
290  protected:
291
292    PhysicalMemory physmem;
293
294    Enums::MemoryMode memoryMode;
295
296    const unsigned int _cacheLineSize;
297
298    uint64_t workItemsBegin;
299    uint64_t workItemsEnd;
300    uint32_t numWorkIds;
301    std::vector<bool> activeCpus;
302
303    /** This array is a per-system list of all devices capable of issuing a
304     * memory system request and an associated string for each master id.
305     * It's used to uniquely id any master in the system by name for things
306     * like cache statistics.
307     */
308    std::vector<std::string> masterIds;
309
310    ThermalModel * thermalModel;
311
312  public:
313
314    /** Request an id used to create a request object in the system. All objects
315     * that intend to issues requests into the memory system must request an id
316     * in the init() phase of startup. All master ids must be fixed by the
317     * regStats() phase that immediately precedes it. This allows objects in
318     * the memory system to understand how many masters may exist and
319     * appropriately name the bins of their per-master stats before the stats
320     * are finalized
321     */
322    MasterID getMasterId(std::string req_name);
323
324    /** Get the name of an object for a given request id.
325     */
326    std::string getMasterName(MasterID master_id);
327
328    /** Get the number of masters registered in the system */
329    MasterID maxMasters()
330    {
331        return masterIds.size();
332    }
333
334    void regStats() override;
335    /**
336     * Called by pseudo_inst to track the number of work items started by this
337     * system.
338     */
339    uint64_t
340    incWorkItemsBegin()
341    {
342        return ++workItemsBegin;
343    }
344
345    /**
346     * Called by pseudo_inst to track the number of work items completed by
347     * this system.
348     */
349    uint64_t
350    incWorkItemsEnd()
351    {
352        return ++workItemsEnd;
353    }
354
355    /**
356     * Called by pseudo_inst to mark the cpus actively executing work items.
357     * Returns the total number of cpus that have executed work item begin or
358     * ends.
359     */
360    int
361    markWorkItem(int index)
362    {
363        int count = 0;
364        assert(index < activeCpus.size());
365        activeCpus[index] = true;
366        for (std::vector<bool>::iterator i = activeCpus.begin();
367             i < activeCpus.end(); i++) {
368            if (*i) count++;
369        }
370        return count;
371    }
372
373    inline void workItemBegin(uint32_t tid, uint32_t workid)
374    {
375        std::pair<uint32_t,uint32_t> p(tid, workid);
376        lastWorkItemStarted[p] = curTick();
377    }
378
379    void workItemEnd(uint32_t tid, uint32_t workid);
380
381    /**
382     * Fix up an address used to match PCs for hooking simulator
383     * events on to target function executions.  See comment in
384     * system.cc for details.
385     */
386    virtual Addr fixFuncEventAddr(Addr addr)
387    {
388        panic("Base fixFuncEventAddr not implemented.\n");
389    }
390
391    /** @{ */
392    /**
393     * Add a function-based event to the given function, to be looked
394     * up in the specified symbol table.
395     *
396     * The ...OrPanic flavor of the method causes the simulator to
397     * panic if the symbol can't be found.
398     *
399     * @param symtab Symbol table to use for look up.
400     * @param lbl Function to hook the event to.
401     * @param desc Description to be passed to the event.
402     * @param args Arguments to be forwarded to the event constructor.
403     */
404    template <class T, typename... Args>
405    T *addFuncEvent(const SymbolTable *symtab, const char *lbl,
406                    const std::string &desc, Args... args)
407    {
408        Addr addr M5_VAR_USED = 0; // initialize only to avoid compiler warning
409
410#if THE_ISA != NULL_ISA
411        if (symtab->findAddress(lbl, addr)) {
412            T *ev = new T(&pcEventQueue, desc, fixFuncEventAddr(addr),
413                          std::forward<Args>(args)...);
414            return ev;
415        }
416#endif
417
418        return NULL;
419    }
420
421    template <class T>
422    T *addFuncEvent(const SymbolTable *symtab, const char *lbl)
423    {
424        return addFuncEvent<T>(symtab, lbl, lbl);
425    }
426
427    template <class T, typename... Args>
428    T *addFuncEventOrPanic(const SymbolTable *symtab, const char *lbl,
429                           Args... args)
430    {
431        T *e(addFuncEvent<T>(symtab, lbl, std::forward<Args>(args)...));
432        if (!e)
433            panic("Failed to find symbol '%s'", lbl);
434        return e;
435    }
436    /** @} */
437
438    /** @{ */
439    /**
440     * Add a function-based event to a kernel symbol.
441     *
442     * These functions work like their addFuncEvent() and
443     * addFuncEventOrPanic() counterparts. The only difference is that
444     * they automatically use the kernel symbol table. All arguments
445     * are forwarded to the underlying method.
446     *
447     * @see addFuncEvent()
448     * @see addFuncEventOrPanic()
449     *
450     * @param lbl Function to hook the event to.
451     * @param args Arguments to be passed to addFuncEvent
452     */
453    template <class T, typename... Args>
454    T *addKernelFuncEvent(const char *lbl, Args... args)
455    {
456        return addFuncEvent<T>(kernelSymtab, lbl,
457                               std::forward<Args>(args)...);
458    }
459
460    template <class T, typename... Args>
461    T *addKernelFuncEventOrPanic(const char *lbl, Args... args)
462    {
463        T *e(addFuncEvent<T>(kernelSymtab, lbl,
464                             std::forward<Args>(args)...));
465        if (!e)
466            panic("Failed to find kernel symbol '%s'", lbl);
467        return e;
468    }
469    /** @} */
470
471  public:
472    std::vector<BaseRemoteGDB *> remoteGDB;
473    std::vector<GDBListener *> gdbListen;
474    bool breakpoint();
475
476  public:
477    typedef SystemParams Params;
478
479  protected:
480    Params *_params;
481
482  public:
483    System(Params *p);
484    ~System();
485
486    void initState() override;
487
488    const Params *params() const { return (const Params *)_params; }
489
490  public:
491
492    /**
493     * Returns the address the kernel starts at.
494     * @return address the kernel starts at
495     */
496    Addr getKernelStart() const { return kernelStart; }
497
498    /**
499     * Returns the address the kernel ends at.
500     * @return address the kernel ends at
501     */
502    Addr getKernelEnd() const { return kernelEnd; }
503
504    /**
505     * Returns the address the entry point to the kernel code.
506     * @return entry point of the kernel code
507     */
508    Addr getKernelEntry() const { return kernelEntry; }
509
510    /// Allocate npages contiguous unused physical pages
511    /// @return Starting address of first page
512    Addr allocPhysPages(int npages);
513
514    ContextID registerThreadContext(ThreadContext *tc,
515                                    ContextID assigned = InvalidContextID);
516    void replaceThreadContext(ThreadContext *tc, ContextID context_id);
517
518    void serialize(CheckpointOut &cp) const override;
519    void unserialize(CheckpointIn &cp) override;
520
521    void drainResume() override;
522
523  public:
524    Counter totalNumInsts;
525    EventQueue instEventQueue;
526    std::map<std::pair<uint32_t,uint32_t>, Tick>  lastWorkItemStarted;
527    std::map<uint32_t, Stats::Histogram*> workItemStats;
528
529    ////////////////////////////////////////////
530    //
531    // STATIC GLOBAL SYSTEM LIST
532    //
533    ////////////////////////////////////////////
534
535    static std::vector<System *> systemList;
536    static int numSystemsRunning;
537
538    static void printSystems();
539
540    // For futex system call
541    std::map<uint64_t, std::list<ThreadContext *> * > futexMap;
542
543  protected:
544
545    /**
546     * If needed, serialize additional symbol table entries for a
547     * specific subclass of this system. Currently this is used by
548     * Alpha and MIPS.
549     *
550     * @param os stream to serialize to
551     */
552    virtual void serializeSymtab(CheckpointOut &os) const {}
553
554    /**
555     * If needed, unserialize additional symbol table entries for a
556     * specific subclass of this system.
557     *
558     * @param cp checkpoint to unserialize from
559     * @param section relevant section in the checkpoint
560     */
561    virtual void unserializeSymtab(CheckpointIn &cp) {}
562
563};
564
565void printSystems();
566
567#endif // __SYSTEM_HH__
568