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.
41 * Authors: Steve Reinhardt
48 #include "sim/system.hh"
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"
60 #include "cpu/kvm/base.hh"
61 #include "cpu/kvm/vm.hh"
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"
76 * To avoid linking errors with LTO, only include the header if we
77 * actually have a definition.
79 #if THE_ISA != NULL_ISA
80 #include "kern/kernel_stats.hh"
85 using namespace TheISA
;
87 vector
<System
*> System::systemList
;
89 int System::numSystemsRunning
= 0;
91 System::System(Params
*p
)
92 : SimObject(p
), _systemPort("system_port", this),
93 multiThread(p
->multi_thread
),
95 init_param(p
->init_param
),
96 physProxy(_systemPort
, p
->cache_line_size
),
97 kernelSymtab(nullptr),
99 loadAddrMask(p
->load_addr_mask
),
100 loadAddrOffset(p
->load_offset
),
106 physmem(name() + ".physmem", p
->memories
, p
->mmap_using_noreserve
),
107 memoryMode(p
->mem_mode
),
108 _cacheLineSize(p
->cache_line_size
),
111 numWorkIds(p
->num_work_ids
),
112 thermalModel(p
->thermal_model
),
114 _m5opRange(p
->m5ops_base
?
115 RangeSize(p
->m5ops_base
, 0x10000) :
116 AddrRange(1, 0)), // Create an empty range if disabled
118 redirectPaths(p
->redirect_paths
)
121 // add self to global system list
122 systemList
.push_back(this);
126 kvmVM
->setSystem(this);
131 kernelSymtab
= new SymbolTable
;
132 if (!debugSymbolTable
)
133 debugSymbolTable
= new SymbolTable
;
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");
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
);
151 if (params()->kernel
== "") {
152 inform("No kernel set for full system simulation. "
153 "Assuming you know what you're doing\n");
155 // Get the kernel code
156 kernel
= createObjectFile(params()->kernel
);
157 inform("kernel located at: %s", params()->kernel
);
160 fatal("Could not load kernel file %s", params()->kernel
);
162 kernelImage
= kernel
->buildImage();
164 // setup entry points
165 kernelStart
= kernelImage
.minAddr();
166 kernelEnd
= kernelImage
.maxAddr();
167 kernelEntry
= kernel
->entryPoint();
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;
177 kernelImage
.move([this](Addr a
) {
178 return (a
& loadAddrMask
) + loadAddrOffset
;
182 if (!kernel
->loadGlobalSymbols(kernelSymtab
))
183 fatal("could not load kernel symbols\n");
185 if (!kernel
->loadLocalSymbols(kernelSymtab
))
186 fatal("could not load kernel local symbols\n");
188 if (!kernel
->loadGlobalSymbols(debugSymbolTable
))
189 fatal("could not load kernel symbols\n");
191 if (!kernel
->loadLocalSymbols(debugSymbolTable
))
192 fatal("could not load kernel local symbols\n");
194 // Loading only needs to happen once and after memory system is
195 // connected so it will happen in initState()
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",
208 kernelExtras
.push_back(obj
);
212 // increment the number of running systems
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);
225 for (uint32_t j
= 0; j
< numWorkIds
; j
++)
226 delete workItemStats
[j
];
232 // check that the system port is connected
233 if (!_systemPort
.isConnected())
234 panic("System port on %s is not connected.\n", name());
238 System::getPort(const std::string
&if_name
, PortID idx
)
240 // no need to distinguish at the moment (besides checking)
245 System::setMemoryMode(Enums::MemoryMode mode
)
247 assert(drainState() == DrainState::Drained
);
251 bool System::breakpoint()
253 if (remoteGDB
.size())
254 return remoteGDB
[0]->breakpoint();
259 System::registerThreadContext(ThreadContext
*tc
, ContextID assigned
)
262 if (id
== InvalidContextID
) {
263 // Find an unused context ID for this thread.
265 while (id
< threadContexts
.size() && threadContexts
[id
])
269 if (threadContexts
.size() <= id
)
270 threadContexts
.resize(id
+ 1);
272 fatal_if(threadContexts
[id
],
273 "Cannot have two CPUs with the same id (%d)\n", id
);
275 threadContexts
[id
] = tc
;
276 for (auto *e
: liveEvents
)
279 #if THE_ISA != NULL_ISA
280 int port
= getRemoteGDBPort();
282 RemoteGDB
*rgdb
= new RemoteGDB(this, tc
, port
+ id
);
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());
292 if (remoteGDB
.size() <= id
) {
293 remoteGDB
.resize(id
+ 1);
296 remoteGDB
[id
] = rgdb
;
300 activeCpus
.push_back(false);
306 System::findFreeContext()
308 for (auto &it
: threadContexts
) {
309 if (ThreadContext::Halted
== it
->status())
316 System::schedule(PCEvent
*event
)
319 liveEvents
.push_back(event
);
320 for (auto *tc
: threadContexts
)
321 all
= tc
->schedule(event
) && all
;
326 System::remove(PCEvent
*event
)
329 liveEvents
.remove(event
);
330 for (auto *tc
: threadContexts
)
331 all
= tc
->remove(event
) && all
;
336 System::numRunningContexts()
338 return std::count_if(
339 threadContexts
.cbegin(),
340 threadContexts
.cend(),
341 [] (ThreadContext
* tc
) {
342 return ((tc
->status() != ThreadContext::Halted
) &&
343 (tc
->status() != ThreadContext::Halting
));
352 for (auto *tc
: threadContexts
) {
353 TheISA::initCPU(tc
, tc
->contextId());
354 TheISA::startupCPU(tc
, tc
->contextId());
356 // Moved from the constructor to here since it relies on the
357 // address map being resolved in the interconnect
359 * Load the kernel code into memory
361 auto mapper
= [this](Addr a
) {
362 return (a
& loadAddrMask
) + loadAddrOffset
;
364 if (params()->kernel
!= "") {
365 if (params()->kernel_addr_check
) {
366 // Validate kernel mapping before loading binary
367 if (!isMemAddr(mapper(kernelStart
)) ||
368 !isMemAddr(mapper(kernelEnd
))) {
369 fatal("Kernel is mapped to invalid location (not memory). "
370 "kernelStart 0x(%x) - kernelEnd 0x(%x) %#x:%#x\n",
371 kernelStart
, kernelEnd
,
372 mapper(kernelStart
), mapper(kernelEnd
));
375 // Load program sections into memory
376 kernelImage
.write(physProxy
);
378 DPRINTF(Loader
, "Kernel start = %#x\n", kernelStart
);
379 DPRINTF(Loader
, "Kernel end = %#x\n", kernelEnd
);
380 DPRINTF(Loader
, "Kernel entry = %#x\n", kernelEntry
);
381 DPRINTF(Loader
, "Kernel loaded...\n");
383 std::function
<Addr(Addr
)> extra_mapper
;
384 for (auto ker_idx
= 0; ker_idx
< kernelExtras
.size(); ker_idx
++) {
385 const Addr load_addr
= params()->kernel_extras_addrs
[ker_idx
];
386 auto image
= kernelExtras
[ker_idx
]->buildImage();
387 if (load_addr
!= MaxAddr
)
388 image
= image
.offset(load_addr
);
390 image
= image
.move(mapper
);
391 image
.write(physProxy
);
397 System::replaceThreadContext(ThreadContext
*tc
, ContextID context_id
)
399 if (context_id
>= threadContexts
.size()) {
400 panic("replaceThreadContext: bad id, %d >= %d\n",
401 context_id
, threadContexts
.size());
404 for (auto *e
: liveEvents
) {
405 threadContexts
[context_id
]->remove(e
);
408 threadContexts
[context_id
] = tc
;
409 if (context_id
< remoteGDB
.size())
410 remoteGDB
[context_id
]->replaceThreadContext(tc
);
414 System::validKvmEnvironment() const
417 if (threadContexts
.empty())
420 for (auto tc
: threadContexts
) {
421 if (dynamic_cast<BaseKvmCPU
*>(tc
->getCpuPtr()) == nullptr) {
432 System::allocPhysPages(int npages
)
434 Addr return_addr
= pagePtr
<< PageShift
;
437 Addr next_return_addr
= pagePtr
<< PageShift
;
439 AddrRange
m5opRange(0xffff0000, 0x100000000);
440 if (m5opRange
.contains(next_return_addr
)) {
441 warn("Reached m5ops MMIO region\n");
442 return_addr
= 0xffffffff;
443 pagePtr
= 0xffffffff >> PageShift
;
446 if ((pagePtr
<< PageShift
) > physmem
.totalSize())
447 fatal("Out of memory, please increase size of physical memory.");
452 System::memSize() const
454 return physmem
.totalSize();
458 System::freeMemSize() const
460 return physmem
.totalSize() - (pagePtr
<< PageShift
);
464 System::isMemAddr(Addr addr
) const
466 return physmem
.isMemAddr(addr
);
470 System::drainResume()
476 System::serialize(CheckpointOut
&cp
) const
479 kernelSymtab
->serialize("kernel_symtab", cp
);
480 SERIALIZE_SCALAR(pagePtr
);
483 // also serialize the memories in the system
484 physmem
.serializeSection(cp
, "physmem");
489 System::unserialize(CheckpointIn
&cp
)
492 kernelSymtab
->unserialize("kernel_symtab", cp
);
493 UNSERIALIZE_SCALAR(pagePtr
);
494 unserializeSymtab(cp
);
496 // also unserialize the memories in the system
497 physmem
.unserializeSection(cp
, "physmem");
503 SimObject::regStats();
505 for (uint32_t j
= 0; j
< numWorkIds
; j
++) {
506 workItemStats
[j
] = new Stats::Histogram();
507 stringstream namestr
;
508 ccprintf(namestr
, "work_item_type%d", j
);
509 workItemStats
[j
]->init(20)
510 .name(name() + "." + namestr
.str())
511 .desc("Run time stat for" + namestr
.str())
512 .prereq(*workItemStats
[j
]);
517 System::workItemEnd(uint32_t tid
, uint32_t workid
)
519 std::pair
<uint32_t,uint32_t> p(tid
, workid
);
520 if (!lastWorkItemStarted
.count(p
))
523 Tick samp
= curTick() - lastWorkItemStarted
[p
];
524 DPRINTF(WorkItems
, "Work item end: %d\t%d\t%lld\n", tid
, workid
, samp
);
526 if (workid
>= numWorkIds
)
527 fatal("Got workid greater than specified in system configuration\n");
529 workItemStats
[workid
]->sample(samp
);
530 lastWorkItemStarted
.erase(p
);
534 System::printSystems()
536 ios::fmtflags
flags(cerr
.flags());
538 vector
<System
*>::iterator i
= systemList
.begin();
539 vector
<System
*>::iterator end
= systemList
.end();
540 for (; i
!= end
; ++i
) {
542 cerr
<< "System " << sys
->name() << ": " << hex
<< sys
<< endl
;
551 System::printSystems();
555 System::stripSystemName(const std::string
& master_name
) const
557 if (startswith(master_name
, name())) {
558 return master_name
.substr(name().size());
565 System::lookupMasterId(const SimObject
* obj
) const
567 MasterID id
= Request::invldMasterId
;
569 // number of occurrences of the SimObject pointer
570 // in the master list.
573 for (int i
= 0; i
< masters
.size(); i
++) {
574 if (masters
[i
].obj
== obj
) {
580 fatal_if(obj_number
> 1,
581 "Cannot lookup MasterID by SimObject pointer: "
582 "More than one master is sharing the same SimObject\n");
588 System::lookupMasterId(const std::string
& master_name
) const
590 std::string name
= stripSystemName(master_name
);
592 for (int i
= 0; i
< masters
.size(); i
++) {
593 if (masters
[i
].masterName
== name
) {
598 return Request::invldMasterId
;
602 System::getGlobalMasterId(const std::string
& master_name
)
604 return _getMasterId(nullptr, master_name
);
608 System::getMasterId(const SimObject
* master
, std::string submaster
)
610 auto master_name
= leafMasterName(master
, submaster
);
611 return _getMasterId(master
, master_name
);
615 System::_getMasterId(const SimObject
* master
, const std::string
& master_name
)
617 std::string name
= stripSystemName(master_name
);
619 // CPUs in switch_cpus ask for ids again after switching
620 for (int i
= 0; i
< masters
.size(); i
++) {
621 if (masters
[i
].masterName
== name
) {
626 // Verify that the statistics haven't been enabled yet
627 // Otherwise objects will have sized their stat buckets and
628 // they will be too small
630 if (Stats::enabled()) {
631 fatal("Can't request a masterId after regStats(). "
632 "You must do so in init().\n");
635 // Generate a new MasterID incrementally
636 MasterID master_id
= masters
.size();
638 // Append the new Master metadata to the group of system Masters.
639 masters
.emplace_back(master
, name
, master_id
);
641 return masters
.back().masterId
;
645 System::leafMasterName(const SimObject
* master
, const std::string
& submaster
)
647 if (submaster
.empty()) {
648 return master
->name();
650 // Get the full master name by appending the submaster name to
651 // the root SimObject master name
652 return master
->name() + "." + submaster
;
657 System::getMasterName(MasterID master_id
)
659 if (master_id
>= masters
.size())
660 fatal("Invalid master_id passed to getMasterName()\n");
662 const auto& master_info
= masters
[master_id
];
663 return master_info
.masterName
;
667 SystemParams::create()
669 return new System(this);