cpu,sim: Get rid of a bunch of conditional compilation for PCEvents.
[gem5.git] / src / sim / system.cc
1 /*
2 * Copyright (c) 2011-2014,2017-2018 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) 2003-2006 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 * Ali Saidi
45 * Rick Strong
46 */
47
48 #include "sim/system.hh"
49
50 #include <algorithm>
51
52 #include "arch/remote_gdb.hh"
53 #include "arch/utility.hh"
54 #include "base/loader/object_file.hh"
55 #include "base/loader/symtab.hh"
56 #include "base/str.hh"
57 #include "base/trace.hh"
58 #include "config/use_kvm.hh"
59 #if USE_KVM
60 #include "cpu/kvm/base.hh"
61 #include "cpu/kvm/vm.hh"
62 #endif
63 #include "cpu/base.hh"
64 #include "cpu/thread_context.hh"
65 #include "debug/Loader.hh"
66 #include "debug/WorkItems.hh"
67 #include "mem/abstract_mem.hh"
68 #include "mem/physical.hh"
69 #include "params/System.hh"
70 #include "sim/byteswap.hh"
71 #include "sim/debug.hh"
72 #include "sim/full_system.hh"
73 #include "sim/redirect_path.hh"
74
75 /**
76 * To avoid linking errors with LTO, only include the header if we
77 * actually have a definition.
78 */
79 #if THE_ISA != NULL_ISA
80 #include "kern/kernel_stats.hh"
81
82 #endif
83
84 using namespace std;
85 using namespace TheISA;
86
87 vector<System *> System::systemList;
88
89 int System::numSystemsRunning = 0;
90
91 System::System(Params *p)
92 : SimObject(p), _systemPort("system_port", this),
93 multiThread(p->multi_thread),
94 pagePtr(0),
95 init_param(p->init_param),
96 physProxy(_systemPort, p->cache_line_size),
97 kernelSymtab(nullptr),
98 kernel(nullptr),
99 loadAddrMask(p->load_addr_mask),
100 loadAddrOffset(p->load_offset),
101 #if USE_KVM
102 kvmVM(p->kvm_vm),
103 #else
104 kvmVM(nullptr),
105 #endif
106 physmem(name() + ".physmem", p->memories, p->mmap_using_noreserve),
107 memoryMode(p->mem_mode),
108 _cacheLineSize(p->cache_line_size),
109 workItemsBegin(0),
110 workItemsEnd(0),
111 numWorkIds(p->num_work_ids),
112 thermalModel(p->thermal_model),
113 _params(p),
114 totalNumInsts(0),
115 redirectPaths(p->redirect_paths)
116 {
117
118 // add self to global system list
119 systemList.push_back(this);
120
121 #if USE_KVM
122 if (kvmVM) {
123 kvmVM->setSystem(this);
124 }
125 #endif
126
127 if (FullSystem) {
128 kernelSymtab = new SymbolTable;
129 if (!debugSymbolTable)
130 debugSymbolTable = new SymbolTable;
131 }
132
133 // check if the cache line size is a value known to work
134 if (!(_cacheLineSize == 16 || _cacheLineSize == 32 ||
135 _cacheLineSize == 64 || _cacheLineSize == 128))
136 warn_once("Cache line size is neither 16, 32, 64 nor 128 bytes.\n");
137
138 // Get the generic system master IDs
139 MasterID tmp_id M5_VAR_USED;
140 tmp_id = getMasterId(this, "writebacks");
141 assert(tmp_id == Request::wbMasterId);
142 tmp_id = getMasterId(this, "functional");
143 assert(tmp_id == Request::funcMasterId);
144 tmp_id = getMasterId(this, "interrupt");
145 assert(tmp_id == Request::intMasterId);
146
147 if (FullSystem) {
148 if (params()->kernel == "") {
149 inform("No kernel set for full system simulation. "
150 "Assuming you know what you're doing\n");
151 } else {
152 // Get the kernel code
153 kernel = createObjectFile(params()->kernel);
154 inform("kernel located at: %s", params()->kernel);
155
156 if (kernel == NULL)
157 fatal("Could not load kernel file %s", params()->kernel);
158
159 kernelImage = kernel->buildImage();
160
161 // setup entry points
162 kernelStart = kernelImage.minAddr();
163 kernelEnd = kernelImage.maxAddr();
164 kernelEntry = kernel->entryPoint();
165
166 // If load_addr_mask is set to 0x0, then auto-calculate
167 // the smallest mask to cover all kernel addresses so gem5
168 // can relocate the kernel to a new offset.
169 if (loadAddrMask == 0) {
170 Addr shift_amt = findMsbSet(kernelEnd - kernelStart) + 1;
171 loadAddrMask = ((Addr)1 << shift_amt) - 1;
172 }
173
174 kernelImage.move([this](Addr a) {
175 return (a & loadAddrMask) + loadAddrOffset;
176 });
177
178 // load symbols
179 if (!kernel->loadGlobalSymbols(kernelSymtab))
180 fatal("could not load kernel symbols\n");
181
182 if (!kernel->loadLocalSymbols(kernelSymtab))
183 fatal("could not load kernel local symbols\n");
184
185 if (!kernel->loadGlobalSymbols(debugSymbolTable))
186 fatal("could not load kernel symbols\n");
187
188 if (!kernel->loadLocalSymbols(debugSymbolTable))
189 fatal("could not load kernel local symbols\n");
190
191 // Loading only needs to happen once and after memory system is
192 // connected so it will happen in initState()
193 }
194
195 for (const auto &obj_name : p->kernel_extras) {
196 inform("Loading additional kernel object: %s", obj_name);
197 ObjectFile *obj = createObjectFile(obj_name);
198 fatal_if(!obj, "Failed to additional kernel object '%s'.\n",
199 obj_name);
200 kernelExtras.push_back(obj);
201 }
202 }
203
204 // increment the number of running systems
205 numSystemsRunning++;
206
207 // Set back pointers to the system in all memories
208 for (int x = 0; x < params()->memories.size(); x++)
209 params()->memories[x]->system(this);
210 }
211
212 System::~System()
213 {
214 delete kernelSymtab;
215 delete kernel;
216
217 for (uint32_t j = 0; j < numWorkIds; j++)
218 delete workItemStats[j];
219 }
220
221 void
222 System::init()
223 {
224 // check that the system port is connected
225 if (!_systemPort.isConnected())
226 panic("System port on %s is not connected.\n", name());
227 }
228
229 Port &
230 System::getPort(const std::string &if_name, PortID idx)
231 {
232 // no need to distinguish at the moment (besides checking)
233 return _systemPort;
234 }
235
236 void
237 System::setMemoryMode(Enums::MemoryMode mode)
238 {
239 assert(drainState() == DrainState::Drained);
240 memoryMode = mode;
241 }
242
243 bool System::breakpoint()
244 {
245 if (remoteGDB.size())
246 return remoteGDB[0]->breakpoint();
247 return false;
248 }
249
250 ContextID
251 System::registerThreadContext(ThreadContext *tc, ContextID assigned)
252 {
253 int id = assigned;
254 if (id == InvalidContextID) {
255 // Find an unused context ID for this thread.
256 id = 0;
257 while (id < threadContexts.size() && threadContexts[id])
258 id++;
259 }
260
261 if (threadContexts.size() <= id)
262 threadContexts.resize(id + 1);
263
264 fatal_if(threadContexts[id],
265 "Cannot have two CPUs with the same id (%d)\n", id);
266
267 threadContexts[id] = tc;
268
269 #if THE_ISA != NULL_ISA
270 int port = getRemoteGDBPort();
271 if (port) {
272 RemoteGDB *rgdb = new RemoteGDB(this, tc, port + id);
273 rgdb->listen();
274
275 BaseCPU *cpu = tc->getCpuPtr();
276 if (cpu->waitForRemoteGDB()) {
277 inform("%s: Waiting for a remote GDB connection on port %d.\n",
278 cpu->name(), rgdb->port());
279
280 rgdb->connect();
281 }
282 if (remoteGDB.size() <= id) {
283 remoteGDB.resize(id + 1);
284 }
285
286 remoteGDB[id] = rgdb;
287 }
288 #endif
289
290 activeCpus.push_back(false);
291
292 return id;
293 }
294
295 bool
296 System::schedule(PCEvent *event)
297 {
298 return pcEventQueue.schedule(event);
299 }
300
301 bool
302 System::remove(PCEvent *event)
303 {
304 return pcEventQueue.remove(event);
305 }
306
307 int
308 System::numRunningContexts()
309 {
310 return std::count_if(
311 threadContexts.cbegin(),
312 threadContexts.cend(),
313 [] (ThreadContext* tc) {
314 return ((tc->status() != ThreadContext::Halted) &&
315 (tc->status() != ThreadContext::Halting));
316 }
317 );
318 }
319
320 void
321 System::initState()
322 {
323 if (FullSystem) {
324 for (int i = 0; i < threadContexts.size(); i++)
325 TheISA::startupCPU(threadContexts[i], i);
326 // Moved from the constructor to here since it relies on the
327 // address map being resolved in the interconnect
328 /**
329 * Load the kernel code into memory
330 */
331 auto mapper = [this](Addr a) {
332 return (a & loadAddrMask) + loadAddrOffset;
333 };
334 if (params()->kernel != "") {
335 if (params()->kernel_addr_check) {
336 // Validate kernel mapping before loading binary
337 if (!isMemAddr(mapper(kernelStart)) ||
338 !isMemAddr(mapper(kernelEnd))) {
339 fatal("Kernel is mapped to invalid location (not memory). "
340 "kernelStart 0x(%x) - kernelEnd 0x(%x) %#x:%#x\n",
341 kernelStart, kernelEnd,
342 mapper(kernelStart), mapper(kernelEnd));
343 }
344 }
345 // Load program sections into memory
346 kernelImage.write(physProxy);
347 for (const auto &extra_kernel : kernelExtras)
348 extra_kernel->buildImage().move(mapper).write(physProxy);
349
350 DPRINTF(Loader, "Kernel start = %#x\n", kernelStart);
351 DPRINTF(Loader, "Kernel end = %#x\n", kernelEnd);
352 DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry);
353 DPRINTF(Loader, "Kernel loaded...\n");
354 }
355 }
356 }
357
358 void
359 System::replaceThreadContext(ThreadContext *tc, ContextID context_id)
360 {
361 if (context_id >= threadContexts.size()) {
362 panic("replaceThreadContext: bad id, %d >= %d\n",
363 context_id, threadContexts.size());
364 }
365
366 threadContexts[context_id] = tc;
367 if (context_id < remoteGDB.size())
368 remoteGDB[context_id]->replaceThreadContext(tc);
369 }
370
371 bool
372 System::validKvmEnvironment() const
373 {
374 #if USE_KVM
375 if (threadContexts.empty())
376 return false;
377
378 for (auto tc : threadContexts) {
379 if (dynamic_cast<BaseKvmCPU*>(tc->getCpuPtr()) == nullptr) {
380 return false;
381 }
382 }
383 return true;
384 #else
385 return false;
386 #endif
387 }
388
389 Addr
390 System::allocPhysPages(int npages)
391 {
392 Addr return_addr = pagePtr << PageShift;
393 pagePtr += npages;
394
395 Addr next_return_addr = pagePtr << PageShift;
396
397 AddrRange m5opRange(0xffff0000, 0xffffffff);
398 if (m5opRange.contains(next_return_addr)) {
399 warn("Reached m5ops MMIO region\n");
400 return_addr = 0xffffffff;
401 pagePtr = 0xffffffff >> PageShift;
402 }
403
404 if ((pagePtr << PageShift) > physmem.totalSize())
405 fatal("Out of memory, please increase size of physical memory.");
406 return return_addr;
407 }
408
409 Addr
410 System::memSize() const
411 {
412 return physmem.totalSize();
413 }
414
415 Addr
416 System::freeMemSize() const
417 {
418 return physmem.totalSize() - (pagePtr << PageShift);
419 }
420
421 bool
422 System::isMemAddr(Addr addr) const
423 {
424 return physmem.isMemAddr(addr);
425 }
426
427 void
428 System::drainResume()
429 {
430 totalNumInsts = 0;
431 }
432
433 void
434 System::serialize(CheckpointOut &cp) const
435 {
436 if (FullSystem)
437 kernelSymtab->serialize("kernel_symtab", cp);
438 SERIALIZE_SCALAR(pagePtr);
439 serializeSymtab(cp);
440
441 // also serialize the memories in the system
442 physmem.serializeSection(cp, "physmem");
443 }
444
445
446 void
447 System::unserialize(CheckpointIn &cp)
448 {
449 if (FullSystem)
450 kernelSymtab->unserialize("kernel_symtab", cp);
451 UNSERIALIZE_SCALAR(pagePtr);
452 unserializeSymtab(cp);
453
454 // also unserialize the memories in the system
455 physmem.unserializeSection(cp, "physmem");
456 }
457
458 void
459 System::regStats()
460 {
461 SimObject::regStats();
462
463 for (uint32_t j = 0; j < numWorkIds ; j++) {
464 workItemStats[j] = new Stats::Histogram();
465 stringstream namestr;
466 ccprintf(namestr, "work_item_type%d", j);
467 workItemStats[j]->init(20)
468 .name(name() + "." + namestr.str())
469 .desc("Run time stat for" + namestr.str())
470 .prereq(*workItemStats[j]);
471 }
472 }
473
474 void
475 System::workItemEnd(uint32_t tid, uint32_t workid)
476 {
477 std::pair<uint32_t,uint32_t> p(tid, workid);
478 if (!lastWorkItemStarted.count(p))
479 return;
480
481 Tick samp = curTick() - lastWorkItemStarted[p];
482 DPRINTF(WorkItems, "Work item end: %d\t%d\t%lld\n", tid, workid, samp);
483
484 if (workid >= numWorkIds)
485 fatal("Got workid greater than specified in system configuration\n");
486
487 workItemStats[workid]->sample(samp);
488 lastWorkItemStarted.erase(p);
489 }
490
491 void
492 System::printSystems()
493 {
494 ios::fmtflags flags(cerr.flags());
495
496 vector<System *>::iterator i = systemList.begin();
497 vector<System *>::iterator end = systemList.end();
498 for (; i != end; ++i) {
499 System *sys = *i;
500 cerr << "System " << sys->name() << ": " << hex << sys << endl;
501 }
502
503 cerr.flags(flags);
504 }
505
506 void
507 printSystems()
508 {
509 System::printSystems();
510 }
511
512 std::string
513 System::stripSystemName(const std::string& master_name) const
514 {
515 if (startswith(master_name, name())) {
516 return master_name.substr(name().size());
517 } else {
518 return master_name;
519 }
520 }
521
522 MasterID
523 System::lookupMasterId(const SimObject* obj) const
524 {
525 MasterID id = Request::invldMasterId;
526
527 // number of occurrences of the SimObject pointer
528 // in the master list.
529 auto obj_number = 0;
530
531 for (int i = 0; i < masters.size(); i++) {
532 if (masters[i].obj == obj) {
533 id = i;
534 obj_number++;
535 }
536 }
537
538 fatal_if(obj_number > 1,
539 "Cannot lookup MasterID by SimObject pointer: "
540 "More than one master is sharing the same SimObject\n");
541
542 return id;
543 }
544
545 MasterID
546 System::lookupMasterId(const std::string& master_name) const
547 {
548 std::string name = stripSystemName(master_name);
549
550 for (int i = 0; i < masters.size(); i++) {
551 if (masters[i].masterName == name) {
552 return i;
553 }
554 }
555
556 return Request::invldMasterId;
557 }
558
559 MasterID
560 System::getGlobalMasterId(const std::string& master_name)
561 {
562 return _getMasterId(nullptr, master_name);
563 }
564
565 MasterID
566 System::getMasterId(const SimObject* master, std::string submaster)
567 {
568 auto master_name = leafMasterName(master, submaster);
569 return _getMasterId(master, master_name);
570 }
571
572 MasterID
573 System::_getMasterId(const SimObject* master, const std::string& master_name)
574 {
575 std::string name = stripSystemName(master_name);
576
577 // CPUs in switch_cpus ask for ids again after switching
578 for (int i = 0; i < masters.size(); i++) {
579 if (masters[i].masterName == name) {
580 return i;
581 }
582 }
583
584 // Verify that the statistics haven't been enabled yet
585 // Otherwise objects will have sized their stat buckets and
586 // they will be too small
587
588 if (Stats::enabled()) {
589 fatal("Can't request a masterId after regStats(). "
590 "You must do so in init().\n");
591 }
592
593 // Generate a new MasterID incrementally
594 MasterID master_id = masters.size();
595
596 // Append the new Master metadata to the group of system Masters.
597 masters.emplace_back(master, name, master_id);
598
599 return masters.back().masterId;
600 }
601
602 std::string
603 System::leafMasterName(const SimObject* master, const std::string& submaster)
604 {
605 if (submaster.empty()) {
606 return master->name();
607 } else {
608 // Get the full master name by appending the submaster name to
609 // the root SimObject master name
610 return master->name() + "." + submaster;
611 }
612 }
613
614 std::string
615 System::getMasterName(MasterID master_id)
616 {
617 if (master_id >= masters.size())
618 fatal("Invalid master_id passed to getMasterName()\n");
619
620 const auto& master_info = masters[master_id];
621 return master_info.masterName;
622 }
623
624 System *
625 SystemParams::create()
626 {
627 return new System(this);
628 }