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());
232 System::getPort(const std::string
&if_name
, PortID idx
)
234 // no need to distinguish at the moment (besides checking)
239 System::setMemoryMode(Enums::MemoryMode mode
)
241 assert(drainState() == DrainState::Drained
);
245 bool System::breakpoint()
247 if (remoteGDB
.size())
248 return remoteGDB
[0]->breakpoint();
253 System::registerThreadContext(ThreadContext
*tc
, ContextID assigned
)
256 if (id
== InvalidContextID
) {
257 // Find an unused context ID for this thread.
259 while (id
< threadContexts
.size() && threadContexts
[id
])
263 if (threadContexts
.size() <= id
)
264 threadContexts
.resize(id
+ 1);
266 fatal_if(threadContexts
[id
],
267 "Cannot have two CPUs with the same id (%d)\n", id
);
269 threadContexts
[id
] = tc
;
270 for (auto *e
: liveEvents
)
273 #if THE_ISA != NULL_ISA
274 int port
= getRemoteGDBPort();
276 RemoteGDB
*rgdb
= new RemoteGDB(this, tc
, port
+ id
);
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());
286 if (remoteGDB
.size() <= id
) {
287 remoteGDB
.resize(id
+ 1);
290 remoteGDB
[id
] = rgdb
;
294 activeCpus
.push_back(false);
300 System::findFreeContext()
302 for (auto &it
: threadContexts
) {
303 if (ThreadContext::Halted
== it
->status())
310 System::schedule(PCEvent
*event
)
313 liveEvents
.push_back(event
);
314 for (auto *tc
: threadContexts
)
315 all
= tc
->schedule(event
) && all
;
320 System::remove(PCEvent
*event
)
323 liveEvents
.remove(event
);
324 for (auto *tc
: threadContexts
)
325 all
= tc
->remove(event
) && all
;
330 System::numRunningContexts()
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
));
346 // Moved from the constructor to here since it relies on the
347 // address map being resolved in the interconnect
349 * Load the kernel code into memory
351 auto mapper
= [this](Addr a
) {
352 return (a
& loadAddrMask
) + loadAddrOffset
;
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
));
365 // Load program sections into memory
366 kernelImage
.write(physProxy
);
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");
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
);
380 image
= image
.move(mapper
);
381 image
.write(physProxy
);
387 System::replaceThreadContext(ThreadContext
*tc
, ContextID context_id
)
389 if (context_id
>= threadContexts
.size()) {
390 panic("replaceThreadContext: bad id, %d >= %d\n",
391 context_id
, threadContexts
.size());
394 for (auto *e
: liveEvents
) {
395 threadContexts
[context_id
]->remove(e
);
398 threadContexts
[context_id
] = tc
;
399 if (context_id
< remoteGDB
.size())
400 remoteGDB
[context_id
]->replaceThreadContext(tc
);
404 System::validKvmEnvironment() const
407 if (threadContexts
.empty())
410 for (auto tc
: threadContexts
) {
411 if (dynamic_cast<BaseKvmCPU
*>(tc
->getCpuPtr()) == nullptr) {
422 System::allocPhysPages(int npages
)
424 Addr return_addr
= pagePtr
<< PageShift
;
427 Addr next_return_addr
= pagePtr
<< PageShift
;
429 if (_m5opRange
.contains(next_return_addr
)) {
430 warn("Reached m5ops MMIO region\n");
431 return_addr
= 0xffffffff;
432 pagePtr
= 0xffffffff >> PageShift
;
435 if ((pagePtr
<< PageShift
) > physmem
.totalSize())
436 fatal("Out of memory, please increase size of physical memory.");
441 System::memSize() const
443 return physmem
.totalSize();
447 System::freeMemSize() const
449 return physmem
.totalSize() - (pagePtr
<< PageShift
);
453 System::isMemAddr(Addr addr
) const
455 return physmem
.isMemAddr(addr
);
459 System::drainResume()
465 System::serialize(CheckpointOut
&cp
) const
468 kernelSymtab
->serialize("kernel_symtab", cp
);
469 SERIALIZE_SCALAR(pagePtr
);
472 // also serialize the memories in the system
473 physmem
.serializeSection(cp
, "physmem");
478 System::unserialize(CheckpointIn
&cp
)
481 kernelSymtab
->unserialize("kernel_symtab", cp
);
482 UNSERIALIZE_SCALAR(pagePtr
);
483 unserializeSymtab(cp
);
485 // also unserialize the memories in the system
486 physmem
.unserializeSection(cp
, "physmem");
492 SimObject::regStats();
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
]);
506 System::workItemEnd(uint32_t tid
, uint32_t workid
)
508 std::pair
<uint32_t,uint32_t> p(tid
, workid
);
509 if (!lastWorkItemStarted
.count(p
))
512 Tick samp
= curTick() - lastWorkItemStarted
[p
];
513 DPRINTF(WorkItems
, "Work item end: %d\t%d\t%lld\n", tid
, workid
, samp
);
515 if (workid
>= numWorkIds
)
516 fatal("Got workid greater than specified in system configuration\n");
518 workItemStats
[workid
]->sample(samp
);
519 lastWorkItemStarted
.erase(p
);
523 System::printSystems()
525 ios::fmtflags
flags(cerr
.flags());
527 vector
<System
*>::iterator i
= systemList
.begin();
528 vector
<System
*>::iterator end
= systemList
.end();
529 for (; i
!= end
; ++i
) {
531 cerr
<< "System " << sys
->name() << ": " << hex
<< sys
<< endl
;
540 System::printSystems();
544 System::stripSystemName(const std::string
& master_name
) const
546 if (startswith(master_name
, name())) {
547 return master_name
.substr(name().size());
554 System::lookupMasterId(const SimObject
* obj
) const
556 MasterID id
= Request::invldMasterId
;
558 // number of occurrences of the SimObject pointer
559 // in the master list.
562 for (int i
= 0; i
< masters
.size(); i
++) {
563 if (masters
[i
].obj
== obj
) {
569 fatal_if(obj_number
> 1,
570 "Cannot lookup MasterID by SimObject pointer: "
571 "More than one master is sharing the same SimObject\n");
577 System::lookupMasterId(const std::string
& master_name
) const
579 std::string name
= stripSystemName(master_name
);
581 for (int i
= 0; i
< masters
.size(); i
++) {
582 if (masters
[i
].masterName
== name
) {
587 return Request::invldMasterId
;
591 System::getGlobalMasterId(const std::string
& master_name
)
593 return _getMasterId(nullptr, master_name
);
597 System::getMasterId(const SimObject
* master
, std::string submaster
)
599 auto master_name
= leafMasterName(master
, submaster
);
600 return _getMasterId(master
, master_name
);
604 System::_getMasterId(const SimObject
* master
, const std::string
& master_name
)
606 std::string name
= stripSystemName(master_name
);
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
) {
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
619 if (Stats::enabled()) {
620 fatal("Can't request a masterId after regStats(). "
621 "You must do so in init().\n");
624 // Generate a new MasterID incrementally
625 MasterID master_id
= masters
.size();
627 // Append the new Master metadata to the group of system Masters.
628 masters
.emplace_back(master
, name
, master_id
);
630 return masters
.back().masterId
;
634 System::leafMasterName(const SimObject
* master
, const std::string
& submaster
)
636 if (submaster
.empty()) {
637 return master
->name();
639 // Get the full master name by appending the submaster name to
640 // the root SimObject master name
641 return master
->name() + "." + submaster
;
646 System::getMasterName(MasterID master_id
)
648 if (master_id
>= masters
.size())
649 fatal("Invalid master_id passed to getMasterName()\n");
651 const auto& master_info
= masters
[master_id
];
652 return master_info
.masterName
;
656 SystemParams::create()
658 return new System(this);