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