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