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