2 * Copyright (c) 2011-2014,2017-2019 ARM Limited
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.
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.
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.
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.
42 #include "sim/system.hh"
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"
54 #include "cpu/kvm/base.hh"
55 #include "cpu/kvm/vm.hh"
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"
70 * To avoid linking errors with LTO, only include the header if we
71 * actually have a definition.
73 #if THE_ISA != NULL_ISA
74 #include "kern/kernel_stats.hh"
79 using namespace TheISA
;
81 vector
<System
*> System::systemList
;
83 int System::numSystemsRunning
= 0;
85 System::System(Params
*p
)
86 : SimObject(p
), _systemPort("system_port", this),
87 multiThread(p
->multi_thread
),
89 init_param(p
->init_param
),
90 physProxy(_systemPort
, p
->cache_line_size
),
91 kernelSymtab(nullptr),
93 loadAddrMask(p
->load_addr_mask
),
94 loadAddrOffset(p
->load_offset
),
100 physmem(name() + ".physmem", p
->memories
, p
->mmap_using_noreserve
),
101 memoryMode(p
->mem_mode
),
102 _cacheLineSize(p
->cache_line_size
),
105 numWorkIds(p
->num_work_ids
),
106 thermalModel(p
->thermal_model
),
108 _m5opRange(p
->m5ops_base
?
109 RangeSize(p
->m5ops_base
, 0x10000) :
110 AddrRange(1, 0)), // Create an empty range if disabled
112 redirectPaths(p
->redirect_paths
)
115 // add self to global system list
116 systemList
.push_back(this);
120 kvmVM
->setSystem(this);
125 kernelSymtab
= new SymbolTable
;
126 if (!debugSymbolTable
)
127 debugSymbolTable
= new SymbolTable
;
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");
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
);
145 if (params()->kernel
== "") {
146 inform("No kernel set for full system simulation. "
147 "Assuming you know what you're doing\n");
149 // Get the kernel code
150 kernel
= createObjectFile(params()->kernel
);
151 inform("kernel located at: %s", params()->kernel
);
154 fatal("Could not load kernel file %s", params()->kernel
);
156 kernelImage
= kernel
->buildImage();
158 // setup entry points
159 kernelStart
= kernelImage
.minAddr();
160 kernelEnd
= kernelImage
.maxAddr();
161 kernelEntry
= kernel
->entryPoint();
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;
171 kernelImage
.move([this](Addr a
) {
172 return (a
& loadAddrMask
) + loadAddrOffset
;
176 if (!kernel
->loadGlobalSymbols(kernelSymtab
))
177 fatal("could not load kernel symbols\n");
179 if (!kernel
->loadLocalSymbols(kernelSymtab
))
180 fatal("could not load kernel local symbols\n");
182 if (!kernel
->loadGlobalSymbols(debugSymbolTable
))
183 fatal("could not load kernel symbols\n");
185 if (!kernel
->loadLocalSymbols(debugSymbolTable
))
186 fatal("could not load kernel local symbols\n");
188 // Loading only needs to happen once and after memory system is
189 // connected so it will happen in initState()
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",
202 kernelExtras
.push_back(obj
);
206 // increment the number of running systems
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);
219 for (uint32_t j
= 0; j
< numWorkIds
; j
++)
220 delete workItemStats
[j
];
226 // check that the system port is connected
227 if (!_systemPort
.isConnected())
228 panic("System port on %s is not connected.\n", name());
234 SimObject::startup();
236 // Now that we're about to start simulation, wait for GDB connections if
238 #if THE_ISA != NULL_ISA
239 for (auto *tc
: threadContexts
) {
240 auto *cpu
= tc
->getCpuPtr();
241 auto id
= tc
->contextId();
242 if (remoteGDB
.size() <= id
)
244 auto *rgdb
= remoteGDB
[id
];
246 if (cpu
->waitForRemoteGDB()) {
247 inform("%s: Waiting for a remote GDB connection on port %d.\n",
248 cpu
->name(), rgdb
->port());
257 System::getPort(const std::string
&if_name
, PortID idx
)
259 // no need to distinguish at the moment (besides checking)
264 System::setMemoryMode(Enums::MemoryMode mode
)
266 assert(drainState() == DrainState::Drained
);
270 bool System::breakpoint()
272 if (remoteGDB
.size())
273 return remoteGDB
[0]->breakpoint();
278 System::registerThreadContext(ThreadContext
*tc
, ContextID assigned
)
281 if (id
== InvalidContextID
) {
282 // Find an unused context ID for this thread.
284 while (id
< threadContexts
.size() && threadContexts
[id
])
288 if (threadContexts
.size() <= id
)
289 threadContexts
.resize(id
+ 1);
291 fatal_if(threadContexts
[id
],
292 "Cannot have two CPUs with the same id (%d)\n", id
);
294 threadContexts
[id
] = tc
;
295 for (auto *e
: liveEvents
)
298 #if THE_ISA != NULL_ISA
299 int port
= getRemoteGDBPort();
301 RemoteGDB
*rgdb
= new RemoteGDB(this, tc
, port
+ id
);
304 if (remoteGDB
.size() <= id
)
305 remoteGDB
.resize(id
+ 1);
307 remoteGDB
[id
] = rgdb
;
311 activeCpus
.push_back(false);
317 System::findFreeContext()
319 for (auto &it
: threadContexts
) {
320 if (ThreadContext::Halted
== it
->status())
327 System::schedule(PCEvent
*event
)
330 liveEvents
.push_back(event
);
331 for (auto *tc
: threadContexts
)
332 all
= tc
->schedule(event
) && all
;
337 System::remove(PCEvent
*event
)
340 liveEvents
.remove(event
);
341 for (auto *tc
: threadContexts
)
342 all
= tc
->remove(event
) && all
;
347 System::numRunningContexts()
349 return std::count_if(
350 threadContexts
.cbegin(),
351 threadContexts
.cend(),
352 [] (ThreadContext
* tc
) {
353 return ((tc
->status() != ThreadContext::Halted
) &&
354 (tc
->status() != ThreadContext::Halting
));
363 // Moved from the constructor to here since it relies on the
364 // address map being resolved in the interconnect
366 * Load the kernel code into memory
368 auto mapper
= [this](Addr a
) {
369 return (a
& loadAddrMask
) + loadAddrOffset
;
371 if (params()->kernel
!= "") {
372 if (params()->kernel_addr_check
) {
373 // Validate kernel mapping before loading binary
374 if (!isMemAddr(mapper(kernelStart
)) ||
375 !isMemAddr(mapper(kernelEnd
))) {
376 fatal("Kernel is mapped to invalid location (not memory). "
377 "kernelStart 0x(%x) - kernelEnd 0x(%x) %#x:%#x\n",
378 kernelStart
, kernelEnd
,
379 mapper(kernelStart
), mapper(kernelEnd
));
382 // Load program sections into memory
383 kernelImage
.write(physProxy
);
385 DPRINTF(Loader
, "Kernel start = %#x\n", kernelStart
);
386 DPRINTF(Loader
, "Kernel end = %#x\n", kernelEnd
);
387 DPRINTF(Loader
, "Kernel entry = %#x\n", kernelEntry
);
388 DPRINTF(Loader
, "Kernel loaded...\n");
390 std::function
<Addr(Addr
)> extra_mapper
;
391 for (auto ker_idx
= 0; ker_idx
< kernelExtras
.size(); ker_idx
++) {
392 const Addr load_addr
= params()->kernel_extras_addrs
[ker_idx
];
393 auto image
= kernelExtras
[ker_idx
]->buildImage();
394 if (load_addr
!= MaxAddr
)
395 image
= image
.offset(load_addr
);
397 image
= image
.move(mapper
);
398 image
.write(physProxy
);
404 System::replaceThreadContext(ThreadContext
*tc
, ContextID context_id
)
406 if (context_id
>= threadContexts
.size()) {
407 panic("replaceThreadContext: bad id, %d >= %d\n",
408 context_id
, threadContexts
.size());
411 for (auto *e
: liveEvents
) {
412 threadContexts
[context_id
]->remove(e
);
415 threadContexts
[context_id
] = tc
;
416 if (context_id
< remoteGDB
.size())
417 remoteGDB
[context_id
]->replaceThreadContext(tc
);
421 System::validKvmEnvironment() const
424 if (threadContexts
.empty())
427 for (auto tc
: threadContexts
) {
428 if (dynamic_cast<BaseKvmCPU
*>(tc
->getCpuPtr()) == nullptr) {
439 System::allocPhysPages(int npages
)
441 Addr return_addr
= pagePtr
<< PageShift
;
444 Addr next_return_addr
= pagePtr
<< PageShift
;
446 if (_m5opRange
.contains(next_return_addr
)) {
447 warn("Reached m5ops MMIO region\n");
448 return_addr
= 0xffffffff;
449 pagePtr
= 0xffffffff >> PageShift
;
452 if ((pagePtr
<< PageShift
) > physmem
.totalSize())
453 fatal("Out of memory, please increase size of physical memory.");
458 System::memSize() const
460 return physmem
.totalSize();
464 System::freeMemSize() const
466 return physmem
.totalSize() - (pagePtr
<< PageShift
);
470 System::isMemAddr(Addr addr
) const
472 return physmem
.isMemAddr(addr
);
476 System::drainResume()
482 System::serialize(CheckpointOut
&cp
) const
485 kernelSymtab
->serialize("kernel_symtab", cp
);
486 SERIALIZE_SCALAR(pagePtr
);
489 // also serialize the memories in the system
490 physmem
.serializeSection(cp
, "physmem");
495 System::unserialize(CheckpointIn
&cp
)
498 kernelSymtab
->unserialize("kernel_symtab", cp
);
499 UNSERIALIZE_SCALAR(pagePtr
);
500 unserializeSymtab(cp
);
502 // also unserialize the memories in the system
503 physmem
.unserializeSection(cp
, "physmem");
509 SimObject::regStats();
511 for (uint32_t j
= 0; j
< numWorkIds
; j
++) {
512 workItemStats
[j
] = new Stats::Histogram();
513 stringstream namestr
;
514 ccprintf(namestr
, "work_item_type%d", j
);
515 workItemStats
[j
]->init(20)
516 .name(name() + "." + namestr
.str())
517 .desc("Run time stat for" + namestr
.str())
518 .prereq(*workItemStats
[j
]);
523 System::workItemEnd(uint32_t tid
, uint32_t workid
)
525 std::pair
<uint32_t,uint32_t> p(tid
, workid
);
526 if (!lastWorkItemStarted
.count(p
))
529 Tick samp
= curTick() - lastWorkItemStarted
[p
];
530 DPRINTF(WorkItems
, "Work item end: %d\t%d\t%lld\n", tid
, workid
, samp
);
532 if (workid
>= numWorkIds
)
533 fatal("Got workid greater than specified in system configuration\n");
535 workItemStats
[workid
]->sample(samp
);
536 lastWorkItemStarted
.erase(p
);
540 System::printSystems()
542 ios::fmtflags
flags(cerr
.flags());
544 vector
<System
*>::iterator i
= systemList
.begin();
545 vector
<System
*>::iterator end
= systemList
.end();
546 for (; i
!= end
; ++i
) {
548 cerr
<< "System " << sys
->name() << ": " << hex
<< sys
<< endl
;
557 System::printSystems();
561 System::stripSystemName(const std::string
& master_name
) const
563 if (startswith(master_name
, name())) {
564 return master_name
.substr(name().size());
571 System::lookupMasterId(const SimObject
* obj
) const
573 MasterID id
= Request::invldMasterId
;
575 // number of occurrences of the SimObject pointer
576 // in the master list.
579 for (int i
= 0; i
< masters
.size(); i
++) {
580 if (masters
[i
].obj
== obj
) {
586 fatal_if(obj_number
> 1,
587 "Cannot lookup MasterID by SimObject pointer: "
588 "More than one master is sharing the same SimObject\n");
594 System::lookupMasterId(const std::string
& master_name
) const
596 std::string name
= stripSystemName(master_name
);
598 for (int i
= 0; i
< masters
.size(); i
++) {
599 if (masters
[i
].masterName
== name
) {
604 return Request::invldMasterId
;
608 System::getGlobalMasterId(const std::string
& master_name
)
610 return _getMasterId(nullptr, master_name
);
614 System::getMasterId(const SimObject
* master
, std::string submaster
)
616 auto master_name
= leafMasterName(master
, submaster
);
617 return _getMasterId(master
, master_name
);
621 System::_getMasterId(const SimObject
* master
, const std::string
& master_name
)
623 std::string name
= stripSystemName(master_name
);
625 // CPUs in switch_cpus ask for ids again after switching
626 for (int i
= 0; i
< masters
.size(); i
++) {
627 if (masters
[i
].masterName
== name
) {
632 // Verify that the statistics haven't been enabled yet
633 // Otherwise objects will have sized their stat buckets and
634 // they will be too small
636 if (Stats::enabled()) {
637 fatal("Can't request a masterId after regStats(). "
638 "You must do so in init().\n");
641 // Generate a new MasterID incrementally
642 MasterID master_id
= masters
.size();
644 // Append the new Master metadata to the group of system Masters.
645 masters
.emplace_back(master
, name
, master_id
);
647 return masters
.back().masterId
;
651 System::leafMasterName(const SimObject
* master
, const std::string
& submaster
)
653 if (submaster
.empty()) {
654 return master
->name();
656 // Get the full master name by appending the submaster name to
657 // the root SimObject master name
658 return master
->name() + "." + submaster
;
663 System::getMasterName(MasterID master_id
)
665 if (master_id
>= masters
.size())
666 fatal("Invalid master_id passed to getMasterName()\n");
668 const auto& master_info
= masters
[master_id
];
669 return master_info
.masterName
;
673 SystemParams::create()
675 return new System(this);