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