system.hh revision 11146
12SN/A/*
21762SN/A * Copyright (c) 2012, 2014 ARM Limited
32SN/A * All rights reserved
42SN/A *
52SN/A * The license below extends only to copyright in the software and shall
62SN/A * not be construed as granting a license to any other intellectual
72SN/A * property including but not limited to intellectual property relating
82SN/A * to a hardware implementation of the functionality of the software
92SN/A * licensed hereunder.  You may use the software subject to the license
102SN/A * terms below provided that you ensure that this notice is replicated
112SN/A * unmodified and in its entirety in all distributions of the software,
122SN/A * modified or unmodified, in source code or in binary form.
132SN/A *
142SN/A * Copyright (c) 2002-2005 The Regents of The University of Michigan
152SN/A * Copyright (c) 2011 Regents of the University of California
162SN/A * All rights reserved.
172SN/A *
182SN/A * Redistribution and use in source and binary forms, with or without
192SN/A * modification, are permitted provided that the following conditions are
202SN/A * met: redistributions of source code must retain the above copyright
212SN/A * notice, this list of conditions and the following disclaimer;
222SN/A * redistributions in binary form must reproduce the above copyright
232SN/A * notice, this list of conditions and the following disclaimer in the
242SN/A * documentation and/or other materials provided with the distribution;
252SN/A * neither the name of the copyright holders nor the names of its
262SN/A * contributors may be used to endorse or promote products derived from
272665Ssaidi@eecs.umich.edu * this software without specific prior written permission.
282665Ssaidi@eecs.umich.edu *
292665Ssaidi@eecs.umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
302SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
312SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
322SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
332SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
342SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
352520SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
362207SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
372207SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3812334Sgabeblack@google.com * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
396214Snate@binkert.org * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
402SN/A *
418706Sandreas.hansson@arm.com * Authors: Steve Reinhardt
422SN/A *          Lisa Hsu
432SN/A *          Nathan Binkert
442SN/A *          Rick Strong
452SN/A */
46360SN/A
47360SN/A#ifndef __SYSTEM_HH__
48360SN/A#define __SYSTEM_HH__
49360SN/A
502207SN/A#include <string>
514111Sgblack@eecs.umich.edu#include <utility>
524111Sgblack@eecs.umich.edu#include <vector>
534155Sgblack@eecs.umich.edu
545874Sgblack@eecs.umich.edu#include "arch/isa_traits.hh"
555874Sgblack@eecs.umich.edu#include "base/loader/symtab.hh"
5610037SARM gem5 Developers#include "base/misc.hh"
576691Stjones1@inf.ed.ac.uk#include "base/statistics.hh"
587095Sgblack@eecs.umich.edu#include "config/the_isa.hh"
5911723Sar4jc@virginia.edu#include "enums/MemoryMode.hh"
6011723Sar4jc@virginia.edu#include "mem/mem_object.hh"
61360SN/A#include "mem/port.hh"
62360SN/A#include "mem/port_proxy.hh"
63360SN/A#include "mem/physical.hh"
64360SN/A#include "params/System.hh"
65360SN/A
662207SN/A/**
676392Ssaidi@eecs.umich.edu * To avoid linking errors with LTO, only include the header if we
6810810Sbr@bsdpad.com * actually have the definition.
6910810Sbr@bsdpad.com */
70360SN/A#if THE_ISA != NULL_ISA
71360SN/A#include "cpu/pc_event.hh"
722SN/A#endif
7312SN/A
7412SN/Aclass BaseCPU;
752SN/Aclass BaseRemoteGDB;
762SN/Aclass GDBListener;
7711906SBrandon.Potter@amd.comclass ObjectFile;
78360SN/Aclass Platform;
79360SN/Aclass ThreadContext;
8010880SCurtis.Dunham@arm.com
81360SN/Aclass System : public MemObject
8212SN/A{
832SN/A  private:
842SN/A
852SN/A    /**
8611392Sbrandon.potter@amd.com     * Private class for the system port which is only used as a
8711392Sbrandon.potter@amd.com     * master for debug access and for non-structural entities that do
8811392Sbrandon.potter@amd.com     * not have a port of their own.
8911392Sbrandon.potter@amd.com     */
9011392Sbrandon.potter@amd.com    class SystemPort : public MasterPort
9111392Sbrandon.potter@amd.com    {
9211392Sbrandon.potter@amd.com      public:
9311392Sbrandon.potter@amd.com
9411392Sbrandon.potter@amd.com        /**
9511392Sbrandon.potter@amd.com         * Create a system port with a name and an owner.
9611392Sbrandon.potter@amd.com         */
9711392Sbrandon.potter@amd.com        SystemPort(const std::string &_name, MemObject *_owner)
9811392Sbrandon.potter@amd.com            : MasterPort(_name, _owner)
999641Sguodeyuan@tsinghua.org.cn        { }
1002SN/A        bool recvTimingResp(PacketPtr pkt)
10111389Sbrandon.potter@amd.com        { panic("SystemPort does not receive timing!\n"); return false; }
10211389Sbrandon.potter@amd.com        void recvReqRetry()
10311389Sbrandon.potter@amd.com        { panic("SystemPort does not expect retry!\n"); }
10411389Sbrandon.potter@amd.com    };
10511389Sbrandon.potter@amd.com
10611389Sbrandon.potter@amd.com    SystemPort _systemPort;
10711389Sbrandon.potter@amd.com
10811389Sbrandon.potter@amd.com  public:
1095070Ssaidi@eecs.umich.edu
1103917Ssaidi@eecs.umich.edu    /**
111360SN/A     * After all objects have been created and all ports are
112360SN/A     * connected, check that the system port is connected.
113360SN/A     */
1142SN/A    virtual void init();
1152SN/A
11612SN/A    /**
11711906SBrandon.Potter@amd.com     * Get a reference to the system port that can be used by
1182420SN/A     * non-structural simulation objects like processes or threads, or
11911906SBrandon.Potter@amd.com     * external entities like loaders and debuggers, etc, to access
12012SN/A     * the memory system.
12112SN/A     *
12212SN/A     * @return a reference to the system port we own
12312SN/A     */
12412SN/A    MasterPort& getSystemPort() { return _systemPort; }
12512SN/A
12612SN/A    /**
12712SN/A     * Additional function to return the Port of a memory object.
1282SN/A     */
12911392Sbrandon.potter@amd.com    BaseMasterPort& getMasterPort(const std::string &if_name,
13010037SARM gem5 Developers                                  PortID idx = InvalidPortID);
1312472SN/A
1322420SN/A    /** @{ */
1332SN/A    /**
13412SN/A     * Is the system in atomic mode?
1352472SN/A     *
13612SN/A     * There are currently two different atomic memory modes:
1372SN/A     * 'atomic', which supports caches; and 'atomic_noncaching', which
13812SN/A     * bypasses caches. The latter is used by hardware virtualized
13912SN/A     * CPUs. SimObjects are expected to use Port::sendAtomic() and
14012SN/A     * Port::recvAtomic() when accessing memory in this mode.
14112SN/A     */
14212SN/A    bool isAtomicMode() const {
14312SN/A        return memoryMode == Enums::atomic ||
14412SN/A            memoryMode == Enums::atomic_noncaching;
1453584Ssaidi@eecs.umich.edu    }
1469261Sdam.sunwoo@arm.com
1479261Sdam.sunwoo@arm.com    /**
1489261Sdam.sunwoo@arm.com     * Is the system in timing mode?
1499261Sdam.sunwoo@arm.com     *
1509261Sdam.sunwoo@arm.com     * SimObjects are expected to use Port::sendTiming() and
1513584Ssaidi@eecs.umich.edu     * Port::recvTiming() when accessing memory in this mode.
1522SN/A     */
1532SN/A    bool isTimingMode() const {
1543584Ssaidi@eecs.umich.edu        return memoryMode == Enums::timing;
1552SN/A    }
1562SN/A
1572SN/A    /**
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    const bool multiThread;
200
201    ThreadContext *getThreadContext(ContextID tid)
202    {
203        return threadContexts[tid];
204    }
205
206    int numContexts()
207    {
208        assert(_numContexts == (int)threadContexts.size());
209        return _numContexts;
210    }
211
212    /** Return number of running (non-halted) thread contexts in
213     * system.  These threads could be Active or Suspended. */
214    int numRunningContexts();
215
216    Addr pagePtr;
217
218    uint64_t init_param;
219
220    /** Port to physical memory used for writing object files into ram at
221     * boot.*/
222    PortProxy physProxy;
223
224    /** kernel symbol table */
225    SymbolTable *kernelSymtab;
226
227    /** Object pointer for the kernel code */
228    ObjectFile *kernel;
229
230    /** Begining of kernel code */
231    Addr kernelStart;
232
233    /** End of kernel code */
234    Addr kernelEnd;
235
236    /** Entry point in the kernel to start at */
237    Addr kernelEntry;
238
239    /** Mask that should be anded for binary/symbol loading.
240     * This allows one two different OS requirements for the same ISA to be
241     * handled.  Some OSes are compiled for a virtual address and need to be
242     * loaded into physical memory that starts at address 0, while other
243     * bare metal tools generate images that start at address 0.
244     */
245    Addr loadAddrMask;
246
247    /** Offset that should be used for binary/symbol loading.
248     * This further allows more flexibily than the loadAddrMask allows alone in
249     * loading kernels and similar. The loadAddrOffset is applied after the
250     * loadAddrMask.
251     */
252    Addr loadAddrOffset;
253
254  protected:
255    uint64_t nextPID;
256
257  public:
258    uint64_t allocatePID()
259    {
260        return nextPID++;
261    }
262
263    /** Get a pointer to access the physical memory of the system */
264    PhysicalMemory& getPhysMem() { return physmem; }
265
266    /** Amount of physical memory that is still free */
267    Addr freeMemSize() const;
268
269    /** Amount of physical memory that exists */
270    Addr memSize() const;
271
272    /**
273     * Check if a physical address is within a range of a memory that
274     * is part of the global address map.
275     *
276     * @param addr A physical address
277     * @return Whether the address corresponds to a memory
278     */
279    bool isMemAddr(Addr addr) const;
280
281    /**
282     * Get the architecture.
283     */
284    Arch getArch() const { return Arch::TheISA; }
285
286     /**
287     * Get the page bytes for the ISA.
288     */
289    Addr getPageBytes() const { return TheISA::PageBytes; }
290
291    /**
292     * Get the number of bits worth of in-page adress for the ISA.
293     */
294    Addr getPageShift() const { return TheISA::PageShift; }
295
296  protected:
297
298    PhysicalMemory physmem;
299
300    Enums::MemoryMode memoryMode;
301
302    const unsigned int _cacheLineSize;
303
304    uint64_t workItemsBegin;
305    uint64_t workItemsEnd;
306    uint32_t numWorkIds;
307    std::vector<bool> activeCpus;
308
309    /** This array is a per-sytem list of all devices capable of issuing a
310     * memory system request and an associated string for each master id.
311     * It's used to uniquely id any master in the system by name for things
312     * like cache statistics.
313     */
314    std::vector<std::string> masterIds;
315
316  public:
317
318    /** Request an id used to create a request object in the system. All objects
319     * that intend to issues requests into the memory system must request an id
320     * in the init() phase of startup. All master ids must be fixed by the
321     * regStats() phase that immediately preceeds it. This allows objects in the
322     * memory system to understand how many masters may exist and
323     * appropriately name the bins of their per-master stats before the stats
324     * are finalized
325     */
326    MasterID getMasterId(std::string req_name);
327
328    /** Get the name of an object for a given request id.
329     */
330    std::string getMasterName(MasterID master_id);
331
332    /** Get the number of masters registered in the system */
333    MasterID maxMasters()
334    {
335        return masterIds.size();
336    }
337
338    virtual void regStats();
339    /**
340     * Called by pseudo_inst to track the number of work items started by this
341     * system.
342     */
343    uint64_t
344    incWorkItemsBegin()
345    {
346        return ++workItemsBegin;
347    }
348
349    /**
350     * Called by pseudo_inst to track the number of work items completed by
351     * this system.
352     */
353    uint64_t
354    incWorkItemsEnd()
355    {
356        return ++workItemsEnd;
357    }
358
359    /**
360     * Called by pseudo_inst to mark the cpus actively executing work items.
361     * Returns the total number of cpus that have executed work item begin or
362     * ends.
363     */
364    int
365    markWorkItem(int index)
366    {
367        int count = 0;
368        assert(index < activeCpus.size());
369        activeCpus[index] = true;
370        for (std::vector<bool>::iterator i = activeCpus.begin();
371             i < activeCpus.end(); i++) {
372            if (*i) count++;
373        }
374        return count;
375    }
376
377    inline void workItemBegin(uint32_t tid, uint32_t workid)
378    {
379        std::pair<uint32_t,uint32_t> p(tid, workid);
380        lastWorkItemStarted[p] = curTick();
381    }
382
383    void workItemEnd(uint32_t tid, uint32_t workid);
384
385    /**
386     * Fix up an address used to match PCs for hooking simulator
387     * events on to target function executions.  See comment in
388     * system.cc for details.
389     */
390    virtual Addr fixFuncEventAddr(Addr addr)
391    {
392        panic("Base fixFuncEventAddr not implemented.\n");
393    }
394
395    /** @{ */
396    /**
397     * Add a function-based event to the given function, to be looked
398     * up in the specified symbol table.
399     *
400     * The ...OrPanic flavor of the method causes the simulator to
401     * panic if the symbol can't be found.
402     *
403     * @param symtab Symbol table to use for look up.
404     * @param lbl Function to hook the event to.
405     * @param desc Description to be passed to the event.
406     * @param args Arguments to be forwarded to the event constructor.
407     */
408    template <class T, typename... Args>
409    T *addFuncEvent(const SymbolTable *symtab, const char *lbl,
410                    const std::string &desc, Args... args)
411    {
412        Addr addr M5_VAR_USED = 0; // initialize only to avoid compiler warning
413
414#if THE_ISA != NULL_ISA
415        if (symtab->findAddress(lbl, addr)) {
416            T *ev = new T(&pcEventQueue, desc, fixFuncEventAddr(addr),
417                          std::forward<Args>(args)...);
418            return ev;
419        }
420#endif
421
422        return NULL;
423    }
424
425    template <class T>
426    T *addFuncEvent(const SymbolTable *symtab, const char *lbl)
427    {
428        return addFuncEvent<T>(symtab, lbl, lbl);
429    }
430
431    template <class T, typename... Args>
432    T *addFuncEventOrPanic(const SymbolTable *symtab, const char *lbl,
433                           Args... args)
434    {
435        T *e(addFuncEvent<T>(symtab, lbl, std::forward<Args>(args)...));
436        if (!e)
437            panic("Failed to find symbol '%s'", lbl);
438        return e;
439    }
440    /** @} */
441
442    /** @{ */
443    /**
444     * Add a function-based event to a kernel symbol.
445     *
446     * These functions work like their addFuncEvent() and
447     * addFuncEventOrPanic() counterparts. The only difference is that
448     * they automatically use the kernel symbol table. All arguments
449     * are forwarded to the underlying method.
450     *
451     * @see addFuncEvent()
452     * @see addFuncEventOrPanic()
453     *
454     * @param lbl Function to hook the event to.
455     * @param args Arguments to be passed to addFuncEvent
456     */
457    template <class T, typename... Args>
458    T *addKernelFuncEvent(const char *lbl, Args... args)
459    {
460        return addFuncEvent<T>(kernelSymtab, lbl,
461                               std::forward<Args>(args)...);
462    }
463
464    template <class T, typename... Args>
465    T *addKernelFuncEventOrPanic(const char *lbl, Args... args)
466    {
467        T *e(addFuncEvent<T>(kernelSymtab, lbl,
468                             std::forward<Args>(args)...));
469        if (!e)
470            panic("Failed to find kernel symbol '%s'", lbl);
471        return e;
472    }
473    /** @} */
474
475  public:
476    std::vector<BaseRemoteGDB *> remoteGDB;
477    std::vector<GDBListener *> gdbListen;
478    bool breakpoint();
479
480  public:
481    typedef SystemParams Params;
482
483  protected:
484    Params *_params;
485
486  public:
487    System(Params *p);
488    ~System();
489
490    void initState();
491
492    const Params *params() const { return (const Params *)_params; }
493
494  public:
495
496    /**
497     * Returns the addess the kernel starts at.
498     * @return address the kernel starts at
499     */
500    Addr getKernelStart() const { return kernelStart; }
501
502    /**
503     * Returns the addess the kernel ends at.
504     * @return address the kernel ends at
505     */
506    Addr getKernelEnd() const { return kernelEnd; }
507
508    /**
509     * Returns the addess the entry point to the kernel code.
510     * @return entry point of the kernel code
511     */
512    Addr getKernelEntry() const { return kernelEntry; }
513
514    /// Allocate npages contiguous unused physical pages
515    /// @return Starting address of first page
516    Addr allocPhysPages(int npages);
517
518    ContextID registerThreadContext(ThreadContext *tc,
519                                    ContextID assigned = InvalidContextID);
520    void replaceThreadContext(ThreadContext *tc, ContextID context_id);
521
522    void serialize(CheckpointOut &cp) const M5_ATTR_OVERRIDE;
523    void unserialize(CheckpointIn &cp) M5_ATTR_OVERRIDE;
524
525    void drainResume() M5_ATTR_OVERRIDE;
526
527  public:
528    Counter totalNumInsts;
529    EventQueue instEventQueue;
530    std::map<std::pair<uint32_t,uint32_t>, Tick>  lastWorkItemStarted;
531    std::map<uint32_t, Stats::Histogram*> workItemStats;
532
533    ////////////////////////////////////////////
534    //
535    // STATIC GLOBAL SYSTEM LIST
536    //
537    ////////////////////////////////////////////
538
539    static std::vector<System *> systemList;
540    static int numSystemsRunning;
541
542    static void printSystems();
543
544    // For futex system call
545    std::map<uint64_t, std::list<ThreadContext *> * > futexMap;
546
547  protected:
548
549    /**
550     * If needed, serialize additional symbol table entries for a
551     * specific subclass of this sytem. Currently this is used by
552     * Alpha and MIPS.
553     *
554     * @param os stream to serialize to
555     */
556    virtual void serializeSymtab(CheckpointOut &os) const {}
557
558    /**
559     * If needed, unserialize additional symbol table entries for a
560     * specific subclass of this system.
561     *
562     * @param cp checkpoint to unserialize from
563     * @param section relevant section in the checkpoint
564     */
565    virtual void unserializeSymtab(CheckpointIn &cp) {}
566
567};
568
569void printSystems();
570
571#endif // __SYSTEM_HH__
572