2 * Copyright (c) 2012, 2014 ARM Limited
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.
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.
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.
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.
41 * Authors: Steve Reinhardt
51 #include <unordered_map>
55 #include "arch/isa_traits.hh"
56 #include "base/loader/symtab.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/physical.hh"
62 #include "mem/port.hh"
63 #include "mem/port_proxy.hh"
64 #include "params/System.hh"
65 #include "sim/futex_map.hh"
66 #include "sim/se_signal.hh"
69 * To avoid linking errors with LTO, only include the header if we
70 * actually have the definition.
72 #if THE_ISA != NULL_ISA
73 #include "cpu/pc_event.hh"
82 class System : public MemObject
87 * Private class for the system port which is only used as a
88 * master for debug access and for non-structural entities that do
89 * not have a port of their own.
91 class SystemPort : public MasterPort
96 * Create a system port with a name and an owner.
98 SystemPort(const std::string &_name, MemObject *_owner)
99 : MasterPort(_name, _owner)
101 bool recvTimingResp(PacketPtr pkt) override
102 { panic("SystemPort does not receive timing!\n"); return false; }
103 void recvReqRetry() override
104 { panic("SystemPort does not expect retry!\n"); }
107 SystemPort _systemPort;
112 * After all objects have been created and all ports are
113 * connected, check that the system port is connected.
115 void init() override;
118 * Get a reference to the system port that can be used by
119 * non-structural simulation objects like processes or threads, or
120 * external entities like loaders and debuggers, etc, to access
123 * @return a reference to the system port we own
125 MasterPort& getSystemPort() { return _systemPort; }
128 * Additional function to return the Port of a memory object.
130 BaseMasterPort& getMasterPort(const std::string &if_name,
131 PortID idx = InvalidPortID) override;
135 * Is the system in atomic mode?
137 * There are currently two different atomic memory modes:
138 * 'atomic', which supports caches; and 'atomic_noncaching', which
139 * bypasses caches. The latter is used by hardware virtualized
140 * CPUs. SimObjects are expected to use Port::sendAtomic() and
141 * Port::recvAtomic() when accessing memory in this mode.
143 bool isAtomicMode() const {
144 return memoryMode == Enums::atomic ||
145 memoryMode == Enums::atomic_noncaching;
149 * Is the system in timing mode?
151 * SimObjects are expected to use Port::sendTiming() and
152 * Port::recvTiming() when accessing memory in this mode.
154 bool isTimingMode() const {
155 return memoryMode == Enums::timing;
159 * Should caches be bypassed?
161 * Some CPUs need to bypass caches to allow direct memory
162 * accesses, which is required for hardware virtualization.
164 bool bypassCaches() const {
165 return memoryMode == Enums::atomic_noncaching;
171 * Get the memory mode of the system.
173 * \warn This should only be used by the Python world. The C++
174 * world should use one of the query functions above
175 * (isAtomicMode(), isTimingMode(), bypassCaches()).
177 Enums::MemoryMode getMemoryMode() const { return memoryMode; }
180 * Change the memory mode of the system.
182 * \warn This should only be called by the Python!
184 * @param mode Mode to change to (atomic/timing/...)
186 void setMemoryMode(Enums::MemoryMode mode);
190 * Get the cache line size of the system.
192 unsigned int cacheLineSize() const { return _cacheLineSize; }
194 #if THE_ISA != NULL_ISA
195 PCEventQueue pcEventQueue;
198 std::vector<ThreadContext *> threadContexts;
200 const bool multiThread;
202 ThreadContext *getThreadContext(ContextID tid)
204 return threadContexts[tid];
209 assert(_numContexts == (int)threadContexts.size());
213 /** Return number of running (non-halted) thread contexts in
214 * system. These threads could be Active or Suspended. */
215 int numRunningContexts();
221 /** Port to physical memory used for writing object files into ram at
225 /** kernel symbol table */
226 SymbolTable *kernelSymtab;
228 /** Object pointer for the kernel code */
231 /** Additional object files */
232 std::vector<ObjectFile *> kernelExtras;
234 /** Beginning of kernel code */
237 /** End of kernel code */
240 /** Entry point in the kernel to start at */
243 /** Mask that should be anded for binary/symbol loading.
244 * This allows one two different OS requirements for the same ISA to be
245 * handled. Some OSes are compiled for a virtual address and need to be
246 * loaded into physical memory that starts at address 0, while other
247 * bare metal tools generate images that start at address 0.
251 /** Offset that should be used for binary/symbol loading.
252 * This further allows more flexibility than the loadAddrMask allows alone
253 * in loading kernels and similar. The loadAddrOffset is applied after the
260 * Get a pointer to the Kernel Virtual Machine (KVM) SimObject,
267 /** Verify gem5 configuration will support KVM emulation */
268 bool validKvmEnvironment() const;
270 /** Get a pointer to access the physical memory of the system */
271 PhysicalMemory& getPhysMem() { return physmem; }
273 /** Amount of physical memory that is still free */
274 Addr freeMemSize() const;
276 /** Amount of physical memory that exists */
277 Addr memSize() const;
280 * Check if a physical address is within a range of a memory that
281 * is part of the global address map.
283 * @param addr A physical address
284 * @return Whether the address corresponds to a memory
286 bool isMemAddr(Addr addr) const;
289 * Get the architecture.
291 Arch getArch() const { return Arch::TheISA; }
294 * Get the page bytes for the ISA.
296 Addr getPageBytes() const { return TheISA::PageBytes; }
299 * Get the number of bits worth of in-page address for the ISA.
301 Addr getPageShift() const { return TheISA::PageShift; }
304 * The thermal model used for this system (if any).
306 ThermalModel * getThermalModel() const { return thermalModel; }
312 PhysicalMemory physmem;
314 Enums::MemoryMode memoryMode;
316 const unsigned int _cacheLineSize;
318 uint64_t workItemsBegin;
319 uint64_t workItemsEnd;
321 std::vector<bool> activeCpus;
323 /** This array is a per-system list of all devices capable of issuing a
324 * memory system request and an associated string for each master id.
325 * It's used to uniquely id any master in the system by name for things
326 * like cache statistics.
328 std::vector<std::string> masterIds;
330 ThermalModel * thermalModel;
334 /** Request an id used to create a request object in the system. All objects
335 * that intend to issues requests into the memory system must request an id
336 * in the init() phase of startup. All master ids must be fixed by the
337 * regStats() phase that immediately precedes it. This allows objects in
338 * the memory system to understand how many masters may exist and
339 * appropriately name the bins of their per-master stats before the stats
342 MasterID getMasterId(std::string req_name);
344 /** Get the name of an object for a given request id.
346 std::string getMasterName(MasterID master_id);
348 /** Get the number of masters registered in the system */
349 MasterID maxMasters()
351 return masterIds.size();
354 void regStats() override;
356 * Called by pseudo_inst to track the number of work items started by this
362 return ++workItemsBegin;
366 * Called by pseudo_inst to track the number of work items completed by
372 return ++workItemsEnd;
376 * Called by pseudo_inst to mark the cpus actively executing work items.
377 * Returns the total number of cpus that have executed work item begin or
381 markWorkItem(int index)
384 assert(index < activeCpus.size());
385 activeCpus[index] = true;
386 for (std::vector<bool>::iterator i = activeCpus.begin();
387 i < activeCpus.end(); i++) {
393 inline void workItemBegin(uint32_t tid, uint32_t workid)
395 std::pair<uint32_t,uint32_t> p(tid, workid);
396 lastWorkItemStarted[p] = curTick();
399 void workItemEnd(uint32_t tid, uint32_t workid);
402 * Fix up an address used to match PCs for hooking simulator
403 * events on to target function executions. See comment in
404 * system.cc for details.
406 virtual Addr fixFuncEventAddr(Addr addr)
408 panic("Base fixFuncEventAddr not implemented.\n");
413 * Add a function-based event to the given function, to be looked
414 * up in the specified symbol table.
416 * The ...OrPanic flavor of the method causes the simulator to
417 * panic if the symbol can't be found.
419 * @param symtab Symbol table to use for look up.
420 * @param lbl Function to hook the event to.
421 * @param desc Description to be passed to the event.
422 * @param args Arguments to be forwarded to the event constructor.
424 template <class T, typename... Args>
425 T *addFuncEvent(const SymbolTable *symtab, const char *lbl,
426 const std::string &desc, Args... args)
428 Addr addr M5_VAR_USED = 0; // initialize only to avoid compiler warning
430 #if THE_ISA != NULL_ISA
431 if (symtab->findAddress(lbl, addr)) {
432 T *ev = new T(&pcEventQueue, desc, fixFuncEventAddr(addr),
433 std::forward<Args>(args)...);
442 T *addFuncEvent(const SymbolTable *symtab, const char *lbl)
444 return addFuncEvent<T>(symtab, lbl, lbl);
447 template <class T, typename... Args>
448 T *addFuncEventOrPanic(const SymbolTable *symtab, const char *lbl,
451 T *e(addFuncEvent<T>(symtab, lbl, std::forward<Args>(args)...));
453 panic("Failed to find symbol '%s'", lbl);
460 * Add a function-based event to a kernel symbol.
462 * These functions work like their addFuncEvent() and
463 * addFuncEventOrPanic() counterparts. The only difference is that
464 * they automatically use the kernel symbol table. All arguments
465 * are forwarded to the underlying method.
467 * @see addFuncEvent()
468 * @see addFuncEventOrPanic()
470 * @param lbl Function to hook the event to.
471 * @param args Arguments to be passed to addFuncEvent
473 template <class T, typename... Args>
474 T *addKernelFuncEvent(const char *lbl, Args... args)
476 return addFuncEvent<T>(kernelSymtab, lbl,
477 std::forward<Args>(args)...);
480 template <class T, typename... Args>
481 T *addKernelFuncEventOrPanic(const char *lbl, Args... args)
483 T *e(addFuncEvent<T>(kernelSymtab, lbl,
484 std::forward<Args>(args)...));
486 panic("Failed to find kernel symbol '%s'", lbl);
492 std::vector<BaseRemoteGDB *> remoteGDB;
496 typedef SystemParams Params;
505 void initState() override;
507 const Params *params() const { return (const Params *)_params; }
512 * Returns the address the kernel starts at.
513 * @return address the kernel starts at
515 Addr getKernelStart() const { return kernelStart; }
518 * Returns the address the kernel ends at.
519 * @return address the kernel ends at
521 Addr getKernelEnd() const { return kernelEnd; }
524 * Returns the address the entry point to the kernel code.
525 * @return entry point of the kernel code
527 Addr getKernelEntry() const { return kernelEntry; }
529 /// Allocate npages contiguous unused physical pages
530 /// @return Starting address of first page
531 Addr allocPhysPages(int npages);
533 ContextID registerThreadContext(ThreadContext *tc,
534 ContextID assigned = InvalidContextID);
535 void replaceThreadContext(ThreadContext *tc, ContextID context_id);
537 void serialize(CheckpointOut &cp) const override;
538 void unserialize(CheckpointIn &cp) override;
540 void drainResume() override;
543 Counter totalNumInsts;
544 EventQueue instEventQueue;
545 std::map<std::pair<uint32_t,uint32_t>, Tick> lastWorkItemStarted;
546 std::map<uint32_t, Stats::Histogram*> workItemStats;
548 ////////////////////////////////////////////
550 // STATIC GLOBAL SYSTEM LIST
552 ////////////////////////////////////////////
554 static std::vector<System *> systemList;
555 static int numSystemsRunning;
557 static void printSystems();
561 static const int maxPID = 32768;
563 /** Process set to track which PIDs have already been allocated */
566 // By convention, all signals are owned by the receiving process. The
567 // receiver will delete the signal upon reception.
568 std::list<BasicSignal> signalList;
573 * If needed, serialize additional symbol table entries for a
574 * specific subclass of this system. Currently this is used by
577 * @param os stream to serialize to
579 virtual void serializeSymtab(CheckpointOut &os) const {}
582 * If needed, unserialize additional symbol table entries for a
583 * specific subclass of this system.
585 * @param cp checkpoint to unserialize from
586 * @param section relevant section in the checkpoint
588 virtual void unserializeSymtab(CheckpointIn &cp) {}
594 #endif // __SYSTEM_HH__