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