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"
83 class System : public MemObject
88 * Private class for the system port which is only used as a
89 * master for debug access and for non-structural entities that do
90 * not have a port of their own.
92 class SystemPort : public MasterPort
97 * Create a system port with a name and an owner.
99 SystemPort(const std::string &_name, MemObject *_owner)
100 : MasterPort(_name, _owner)
102 bool recvTimingResp(PacketPtr pkt) override
103 { panic("SystemPort does not receive timing!\n"); return false; }
104 void recvReqRetry() override
105 { panic("SystemPort does not expect retry!\n"); }
108 SystemPort _systemPort;
113 * After all objects have been created and all ports are
114 * connected, check that the system port is connected.
116 void init() override;
119 * Get a reference to the system port that can be used by
120 * non-structural simulation objects like processes or threads, or
121 * external entities like loaders and debuggers, etc, to access
124 * @return a reference to the system port we own
126 MasterPort& getSystemPort() { return _systemPort; }
129 * Additional function to return the Port of a memory object.
131 BaseMasterPort& getMasterPort(const std::string &if_name,
132 PortID idx = InvalidPortID) override;
136 * Is the system in atomic mode?
138 * There are currently two different atomic memory modes:
139 * 'atomic', which supports caches; and 'atomic_noncaching', which
140 * bypasses caches. The latter is used by hardware virtualized
141 * CPUs. SimObjects are expected to use Port::sendAtomic() and
142 * Port::recvAtomic() when accessing memory in this mode.
144 bool isAtomicMode() const {
145 return memoryMode == Enums::atomic ||
146 memoryMode == Enums::atomic_noncaching;
150 * Is the system in timing mode?
152 * SimObjects are expected to use Port::sendTiming() and
153 * Port::recvTiming() when accessing memory in this mode.
155 bool isTimingMode() const {
156 return memoryMode == Enums::timing;
160 * Should caches be bypassed?
162 * Some CPUs need to bypass caches to allow direct memory
163 * accesses, which is required for hardware virtualization.
165 bool bypassCaches() const {
166 return memoryMode == Enums::atomic_noncaching;
172 * Get the memory mode of the system.
174 * \warn This should only be used by the Python world. The C++
175 * world should use one of the query functions above
176 * (isAtomicMode(), isTimingMode(), bypassCaches()).
178 Enums::MemoryMode getMemoryMode() const { return memoryMode; }
181 * Change the memory mode of the system.
183 * \warn This should only be called by the Python!
185 * @param mode Mode to change to (atomic/timing/...)
187 void setMemoryMode(Enums::MemoryMode mode);
191 * Get the cache line size of the system.
193 unsigned int cacheLineSize() const { return _cacheLineSize; }
195 #if THE_ISA != NULL_ISA
196 PCEventQueue pcEventQueue;
199 std::vector<ThreadContext *> threadContexts;
201 const bool multiThread;
203 ThreadContext *getThreadContext(ContextID tid)
205 return threadContexts[tid];
210 assert(_numContexts == (int)threadContexts.size());
214 /** Return number of running (non-halted) thread contexts in
215 * system. These threads could be Active or Suspended. */
216 int numRunningContexts();
222 /** Port to physical memory used for writing object files into ram at
226 /** kernel symbol table */
227 SymbolTable *kernelSymtab;
229 /** Object pointer for the kernel code */
232 /** Additional object files */
233 std::vector<ObjectFile *> kernelExtras;
235 /** Beginning of kernel code */
238 /** End of kernel code */
241 /** Entry point in the kernel to start at */
244 /** Mask that should be anded for binary/symbol loading.
245 * This allows one two different OS requirements for the same ISA to be
246 * handled. Some OSes are compiled for a virtual address and need to be
247 * loaded into physical memory that starts at address 0, while other
248 * bare metal tools generate images that start at address 0.
252 /** Offset that should be used for binary/symbol loading.
253 * This further allows more flexibility than the loadAddrMask allows alone
254 * in loading kernels and similar. The loadAddrOffset is applied after the
261 * Get a pointer to the Kernel Virtual Machine (KVM) SimObject,
268 /** Verify gem5 configuration will support KVM emulation */
269 bool validKvmEnvironment() const;
271 /** Get a pointer to access the physical memory of the system */
272 PhysicalMemory& getPhysMem() { return physmem; }
274 /** Amount of physical memory that is still free */
275 Addr freeMemSize() const;
277 /** Amount of physical memory that exists */
278 Addr memSize() const;
281 * Check if a physical address is within a range of a memory that
282 * is part of the global address map.
284 * @param addr A physical address
285 * @return Whether the address corresponds to a memory
287 bool isMemAddr(Addr addr) const;
290 * Get the architecture.
292 Arch getArch() const { return Arch::TheISA; }
295 * Get the page bytes for the ISA.
297 Addr getPageBytes() const { return TheISA::PageBytes; }
300 * Get the number of bits worth of in-page address for the ISA.
302 Addr getPageShift() const { return TheISA::PageShift; }
305 * The thermal model used for this system (if any).
307 ThermalModel * getThermalModel() const { return thermalModel; }
313 PhysicalMemory physmem;
315 Enums::MemoryMode memoryMode;
317 const unsigned int _cacheLineSize;
319 uint64_t workItemsBegin;
320 uint64_t workItemsEnd;
322 std::vector<bool> activeCpus;
324 /** This array is a per-system list of all devices capable of issuing a
325 * memory system request and an associated string for each master id.
326 * It's used to uniquely id any master in the system by name for things
327 * like cache statistics.
329 std::vector<std::string> masterIds;
331 ThermalModel * thermalModel;
335 /** Request an id used to create a request object in the system. All objects
336 * that intend to issues requests into the memory system must request an id
337 * in the init() phase of startup. All master ids must be fixed by the
338 * regStats() phase that immediately precedes it. This allows objects in
339 * the memory system to understand how many masters may exist and
340 * appropriately name the bins of their per-master stats before the stats
343 MasterID getMasterId(std::string req_name);
345 /** Get the name of an object for a given request id.
347 std::string getMasterName(MasterID master_id);
349 /** Get the number of masters registered in the system */
350 MasterID maxMasters()
352 return masterIds.size();
355 void regStats() override;
357 * Called by pseudo_inst to track the number of work items started by this
363 return ++workItemsBegin;
367 * Called by pseudo_inst to track the number of work items completed by
373 return ++workItemsEnd;
377 * Called by pseudo_inst to mark the cpus actively executing work items.
378 * Returns the total number of cpus that have executed work item begin or
382 markWorkItem(int index)
385 assert(index < activeCpus.size());
386 activeCpus[index] = true;
387 for (std::vector<bool>::iterator i = activeCpus.begin();
388 i < activeCpus.end(); i++) {
394 inline void workItemBegin(uint32_t tid, uint32_t workid)
396 std::pair<uint32_t,uint32_t> p(tid, workid);
397 lastWorkItemStarted[p] = curTick();
400 void workItemEnd(uint32_t tid, uint32_t workid);
403 * Fix up an address used to match PCs for hooking simulator
404 * events on to target function executions. See comment in
405 * system.cc for details.
407 virtual Addr fixFuncEventAddr(Addr addr)
409 panic("Base fixFuncEventAddr not implemented.\n");
414 * Add a function-based event to the given function, to be looked
415 * up in the specified symbol table.
417 * The ...OrPanic flavor of the method causes the simulator to
418 * panic if the symbol can't be found.
420 * @param symtab Symbol table to use for look up.
421 * @param lbl Function to hook the event to.
422 * @param desc Description to be passed to the event.
423 * @param args Arguments to be forwarded to the event constructor.
425 template <class T, typename... Args>
426 T *addFuncEvent(const SymbolTable *symtab, const char *lbl,
427 const std::string &desc, Args... args)
429 Addr addr M5_VAR_USED = 0; // initialize only to avoid compiler warning
431 #if THE_ISA != NULL_ISA
432 if (symtab->findAddress(lbl, addr)) {
433 T *ev = new T(&pcEventQueue, desc, fixFuncEventAddr(addr),
434 std::forward<Args>(args)...);
443 T *addFuncEvent(const SymbolTable *symtab, const char *lbl)
445 return addFuncEvent<T>(symtab, lbl, lbl);
448 template <class T, typename... Args>
449 T *addFuncEventOrPanic(const SymbolTable *symtab, const char *lbl,
452 T *e(addFuncEvent<T>(symtab, lbl, std::forward<Args>(args)...));
454 panic("Failed to find symbol '%s'", lbl);
461 * Add a function-based event to a kernel symbol.
463 * These functions work like their addFuncEvent() and
464 * addFuncEventOrPanic() counterparts. The only difference is that
465 * they automatically use the kernel symbol table. All arguments
466 * are forwarded to the underlying method.
468 * @see addFuncEvent()
469 * @see addFuncEventOrPanic()
471 * @param lbl Function to hook the event to.
472 * @param args Arguments to be passed to addFuncEvent
474 template <class T, typename... Args>
475 T *addKernelFuncEvent(const char *lbl, Args... args)
477 return addFuncEvent<T>(kernelSymtab, lbl,
478 std::forward<Args>(args)...);
481 template <class T, typename... Args>
482 T *addKernelFuncEventOrPanic(const char *lbl, Args... args)
484 T *e(addFuncEvent<T>(kernelSymtab, lbl,
485 std::forward<Args>(args)...));
487 panic("Failed to find kernel symbol '%s'", lbl);
493 std::vector<BaseRemoteGDB *> remoteGDB;
494 std::vector<GDBListener *> gdbListen;
498 typedef SystemParams Params;
507 void initState() override;
509 const Params *params() const { return (const Params *)_params; }
514 * Returns the address the kernel starts at.
515 * @return address the kernel starts at
517 Addr getKernelStart() const { return kernelStart; }
520 * Returns the address the kernel ends at.
521 * @return address the kernel ends at
523 Addr getKernelEnd() const { return kernelEnd; }
526 * Returns the address the entry point to the kernel code.
527 * @return entry point of the kernel code
529 Addr getKernelEntry() const { return kernelEntry; }
531 /// Allocate npages contiguous unused physical pages
532 /// @return Starting address of first page
533 Addr allocPhysPages(int npages);
535 ContextID registerThreadContext(ThreadContext *tc,
536 ContextID assigned = InvalidContextID);
537 void replaceThreadContext(ThreadContext *tc, ContextID context_id);
539 void serialize(CheckpointOut &cp) const override;
540 void unserialize(CheckpointIn &cp) override;
542 void drainResume() override;
545 Counter totalNumInsts;
546 EventQueue instEventQueue;
547 std::map<std::pair<uint32_t,uint32_t>, Tick> lastWorkItemStarted;
548 std::map<uint32_t, Stats::Histogram*> workItemStats;
550 ////////////////////////////////////////////
552 // STATIC GLOBAL SYSTEM LIST
554 ////////////////////////////////////////////
556 static std::vector<System *> systemList;
557 static int numSystemsRunning;
559 static void printSystems();
563 static const int maxPID = 32768;
565 /** Process set to track which PIDs have already been allocated */
568 // By convention, all signals are owned by the receiving process. The
569 // receiver will delete the signal upon reception.
570 std::list<BasicSignal> signalList;
575 * If needed, serialize additional symbol table entries for a
576 * specific subclass of this system. Currently this is used by
579 * @param os stream to serialize to
581 virtual void serializeSymtab(CheckpointOut &os) const {}
584 * If needed, unserialize additional symbol table entries for a
585 * specific subclass of this system.
587 * @param cp checkpoint to unserialize from
588 * @param section relevant section in the checkpoint
590 virtual void unserializeSymtab(CheckpointIn &cp) {}
596 #endif // __SYSTEM_HH__