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