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