2 * Copyright (c) 2012, 2014, 2018 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 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are
16 * met: redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer;
18 * redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution;
21 * neither the name of the copyright holders nor the names of its
22 * contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include "mem/physical.hh"
42 #include <sys/types.h>
53 #include "base/trace.hh"
54 #include "debug/AddrRanges.hh"
55 #include "debug/Checkpoint.hh"
56 #include "mem/abstract_mem.hh"
57 #include "sim/serialize.hh"
60 * On Linux, MAP_NORESERVE allow us to simulate a very large memory
61 * without committing to actually providing the swap space on the
62 * host. On FreeBSD or OSX the MAP_NORESERVE flag does not exist,
63 * so simply make it 0.
65 #if defined(__APPLE__) || defined(__FreeBSD__)
67 #define MAP_NORESERVE 0
71 PhysicalMemory::PhysicalMemory(const std::string
& _name
,
72 const std::vector
<AbstractMemory
*>& _memories
,
73 bool mmap_using_noreserve
,
74 const std::string
& shared_backstore
) :
75 _name(_name
), size(0), mmapUsingNoReserve(mmap_using_noreserve
),
76 sharedBackstore(shared_backstore
)
78 if (mmap_using_noreserve
)
79 warn("Not reserving swap space. May cause SIGSEGV on actual usage\n");
81 // add the memories from the system to the address map as
83 for (const auto& m
: _memories
) {
84 // only add the memory if it is part of the global address map
85 if (m
->isInAddrMap()) {
86 memories
.push_back(m
);
88 // calculate the total size once and for all
91 // add the range to our interval tree and make sure it does not
92 // intersect an existing range
93 fatal_if(addrMap
.insert(m
->getAddrRange(), m
) == addrMap
.end(),
94 "Memory address range for %s is overlapping\n",
97 // this type of memory is used e.g. as reference memory by
98 // Ruby, and they also needs a backing store, but should
99 // not be part of the global address map
101 "Skipping memory %s that is not in global address map\n",
105 fatal_if(m
->getAddrRange().interleaved(),
106 "Memory %s that is not in the global address map cannot "
107 "be interleaved\n", m
->name());
109 // simply do it independently, also note that this kind of
110 // memories are allowed to overlap in the logic address
112 std::vector
<AbstractMemory
*> unmapped_mems
{m
};
113 createBackingStore(m
->getAddrRange(), unmapped_mems
,
114 m
->isConfReported(), m
->isInAddrMap(),
119 // iterate over the increasing addresses and chunks of contiguous
120 // space to be mapped to backing store, create it and inform the
122 std::vector
<AddrRange
> intlv_ranges
;
123 std::vector
<AbstractMemory
*> curr_memories
;
124 for (const auto& r
: addrMap
) {
125 // simply skip past all memories that are null and hence do
126 // not need any backing store
127 if (!r
.second
->isNull()) {
128 // if the range is interleaved then save it for now
129 if (r
.first
.interleaved()) {
130 // if we already got interleaved ranges that are not
131 // part of the same range, then first do a merge
132 // before we add the new one
133 if (!intlv_ranges
.empty() &&
134 !intlv_ranges
.back().mergesWith(r
.first
)) {
135 AddrRange
merged_range(intlv_ranges
);
137 AbstractMemory
*f
= curr_memories
.front();
138 for (const auto& c
: curr_memories
)
139 if (f
->isConfReported() != c
->isConfReported() ||
140 f
->isInAddrMap() != c
->isInAddrMap() ||
141 f
->isKvmMap() != c
->isKvmMap())
142 fatal("Inconsistent flags in an interleaved "
145 createBackingStore(merged_range
, curr_memories
,
146 f
->isConfReported(), f
->isInAddrMap(),
149 intlv_ranges
.clear();
150 curr_memories
.clear();
152 intlv_ranges
.push_back(r
.first
);
153 curr_memories
.push_back(r
.second
);
155 std::vector
<AbstractMemory
*> single_memory
{r
.second
};
156 createBackingStore(r
.first
, single_memory
,
157 r
.second
->isConfReported(),
158 r
.second
->isInAddrMap(),
159 r
.second
->isKvmMap());
164 // if there is still interleaved ranges waiting to be merged, go
166 if (!intlv_ranges
.empty()) {
167 AddrRange
merged_range(intlv_ranges
);
169 AbstractMemory
*f
= curr_memories
.front();
170 for (const auto& c
: curr_memories
)
171 if (f
->isConfReported() != c
->isConfReported() ||
172 f
->isInAddrMap() != c
->isInAddrMap() ||
173 f
->isKvmMap() != c
->isKvmMap())
174 fatal("Inconsistent flags in an interleaved "
177 createBackingStore(merged_range
, curr_memories
,
178 f
->isConfReported(), f
->isInAddrMap(),
184 PhysicalMemory::createBackingStore(
185 AddrRange range
, const std::vector
<AbstractMemory
*>& _memories
,
186 bool conf_table_reported
, bool in_addr_map
, bool kvm_map
)
188 panic_if(range
.interleaved(),
189 "Cannot create backing store for interleaved range %s\n",
192 // perform the actual mmap
193 DPRINTF(AddrRanges
, "Creating backing store for range %s with size %d\n",
194 range
.to_string(), range
.size());
199 if (sharedBackstore
.empty()) {
201 map_flags
= MAP_ANON
| MAP_PRIVATE
;
203 DPRINTF(AddrRanges
, "Sharing backing store as %s\n",
204 sharedBackstore
.c_str());
205 shm_fd
= shm_open(sharedBackstore
.c_str(), O_CREAT
| O_RDWR
, 0666);
207 panic("Shared memory failed");
208 if (ftruncate(shm_fd
, range
.size()))
209 panic("Setting size of shared memory failed");
210 map_flags
= MAP_SHARED
;
213 // to be able to simulate very large memories, the user can opt to
214 // pass noreserve to mmap
215 if (mmapUsingNoReserve
) {
216 map_flags
|= MAP_NORESERVE
;
219 uint8_t* pmem
= (uint8_t*) mmap(NULL
, range
.size(),
220 PROT_READ
| PROT_WRITE
,
221 map_flags
, shm_fd
, 0);
223 if (pmem
== (uint8_t*) MAP_FAILED
) {
225 fatal("Could not mmap %d bytes for range %s!\n", range
.size(),
229 // remember this backing store so we can checkpoint it and unmap
231 backingStore
.emplace_back(range
, pmem
,
232 conf_table_reported
, in_addr_map
, kvm_map
);
234 // point the memories to their backing store
235 for (const auto& m
: _memories
) {
236 DPRINTF(AddrRanges
, "Mapping memory %s to backing store\n",
238 m
->setBackingStore(pmem
);
242 PhysicalMemory::~PhysicalMemory()
244 // unmap the backing store
245 for (auto& s
: backingStore
)
246 munmap((char*)s
.pmem
, s
.range
.size());
250 PhysicalMemory::isMemAddr(Addr addr
) const
252 return addrMap
.contains(addr
) != addrMap
.end();
256 PhysicalMemory::getConfAddrRanges() const
258 // this could be done once in the constructor, but since it is unlikely to
259 // be called more than once the iteration should not be a problem
260 AddrRangeList ranges
;
261 std::vector
<AddrRange
> intlv_ranges
;
262 for (const auto& r
: addrMap
) {
263 if (r
.second
->isConfReported()) {
264 // if the range is interleaved then save it for now
265 if (r
.first
.interleaved()) {
266 // if we already got interleaved ranges that are not
267 // part of the same range, then first do a merge
268 // before we add the new one
269 if (!intlv_ranges
.empty() &&
270 !intlv_ranges
.back().mergesWith(r
.first
)) {
271 ranges
.push_back(AddrRange(intlv_ranges
));
272 intlv_ranges
.clear();
274 intlv_ranges
.push_back(r
.first
);
276 // keep the current range
277 ranges
.push_back(r
.first
);
282 // if there is still interleaved ranges waiting to be merged,
283 // go ahead and do it
284 if (!intlv_ranges
.empty()) {
285 ranges
.push_back(AddrRange(intlv_ranges
));
292 PhysicalMemory::access(PacketPtr pkt
)
294 assert(pkt
->isRequest());
295 const auto& m
= addrMap
.contains(pkt
->getAddrRange());
296 assert(m
!= addrMap
.end());
297 m
->second
->access(pkt
);
301 PhysicalMemory::functionalAccess(PacketPtr pkt
)
303 assert(pkt
->isRequest());
304 const auto& m
= addrMap
.contains(pkt
->getAddrRange());
305 assert(m
!= addrMap
.end());
306 m
->second
->functionalAccess(pkt
);
310 PhysicalMemory::serialize(CheckpointOut
&cp
) const
312 // serialize all the locked addresses and their context ids
313 std::vector
<Addr
> lal_addr
;
314 std::vector
<ContextID
> lal_cid
;
316 for (auto& m
: memories
) {
317 const std::list
<LockedAddr
>& locked_addrs
= m
->getLockedAddrList();
318 for (const auto& l
: locked_addrs
) {
319 lal_addr
.push_back(l
.addr
);
320 lal_cid
.push_back(l
.contextId
);
324 SERIALIZE_CONTAINER(lal_addr
);
325 SERIALIZE_CONTAINER(lal_cid
);
327 // serialize the backing stores
328 unsigned int nbr_of_stores
= backingStore
.size();
329 SERIALIZE_SCALAR(nbr_of_stores
);
331 unsigned int store_id
= 0;
332 // store each backing store memory segment in a file
333 for (auto& s
: backingStore
) {
334 ScopedCheckpointSection
sec(cp
, csprintf("store%d", store_id
));
335 serializeStore(cp
, store_id
++, s
.range
, s
.pmem
);
340 PhysicalMemory::serializeStore(CheckpointOut
&cp
, unsigned int store_id
,
341 AddrRange range
, uint8_t* pmem
) const
343 // we cannot use the address range for the name as the
344 // memories that are not part of the address map can overlap
345 std::string filename
=
346 name() + ".store" + std::to_string(store_id
) + ".pmem";
347 long range_size
= range
.size();
349 DPRINTF(Checkpoint
, "Serializing physical memory %s with size %d\n",
350 filename
, range_size
);
352 SERIALIZE_SCALAR(store_id
);
353 SERIALIZE_SCALAR(filename
);
354 SERIALIZE_SCALAR(range_size
);
357 std::string filepath
= CheckpointIn::dir() + "/" + filename
.c_str();
358 gzFile compressed_mem
= gzopen(filepath
.c_str(), "wb");
359 if (compressed_mem
== NULL
)
360 fatal("Can't open physical memory checkpoint file '%s'\n",
363 uint64_t pass_size
= 0;
365 // gzwrite fails if (int)len < 0 (gzwrite returns int)
366 for (uint64_t written
= 0; written
< range
.size();
367 written
+= pass_size
) {
368 pass_size
= (uint64_t)INT_MAX
< (range
.size() - written
) ?
369 (uint64_t)INT_MAX
: (range
.size() - written
);
371 if (gzwrite(compressed_mem
, pmem
+ written
,
372 (unsigned int) pass_size
) != (int) pass_size
) {
373 fatal("Write failed on physical memory checkpoint file '%s'\n",
378 // close the compressed stream and check that the exit status
380 if (gzclose(compressed_mem
))
381 fatal("Close failed on physical memory checkpoint file '%s'\n",
387 PhysicalMemory::unserialize(CheckpointIn
&cp
)
389 // unserialize the locked addresses and map them to the
390 // appropriate memory controller
391 std::vector
<Addr
> lal_addr
;
392 std::vector
<ContextID
> lal_cid
;
393 UNSERIALIZE_CONTAINER(lal_addr
);
394 UNSERIALIZE_CONTAINER(lal_cid
);
395 for (size_t i
= 0; i
< lal_addr
.size(); ++i
) {
396 const auto& m
= addrMap
.contains(lal_addr
[i
]);
397 m
->second
->addLockedAddr(LockedAddr(lal_addr
[i
], lal_cid
[i
]));
400 // unserialize the backing stores
401 unsigned int nbr_of_stores
;
402 UNSERIALIZE_SCALAR(nbr_of_stores
);
404 for (unsigned int i
= 0; i
< nbr_of_stores
; ++i
) {
405 ScopedCheckpointSection
sec(cp
, csprintf("store%d", i
));
406 unserializeStore(cp
);
412 PhysicalMemory::unserializeStore(CheckpointIn
&cp
)
414 const uint32_t chunk_size
= 16384;
416 unsigned int store_id
;
417 UNSERIALIZE_SCALAR(store_id
);
419 std::string filename
;
420 UNSERIALIZE_SCALAR(filename
);
421 std::string filepath
= cp
.getCptDir() + "/" + filename
;
424 gzFile compressed_mem
= gzopen(filepath
.c_str(), "rb");
425 if (compressed_mem
== NULL
)
426 fatal("Can't open physical memory checkpoint file '%s'", filename
);
428 // we've already got the actual backing store mapped
429 uint8_t* pmem
= backingStore
[store_id
].pmem
;
430 AddrRange range
= backingStore
[store_id
].range
;
433 UNSERIALIZE_SCALAR(range_size
);
435 DPRINTF(Checkpoint
, "Unserializing physical memory %s with size %d\n",
436 filename
, range_size
);
438 if (range_size
!= range
.size())
439 fatal("Memory range size has changed! Saw %lld, expected %lld\n",
440 range_size
, range
.size());
442 uint64_t curr_size
= 0;
443 long* temp_page
= new long[chunk_size
];
446 while (curr_size
< range
.size()) {
447 bytes_read
= gzread(compressed_mem
, temp_page
, chunk_size
);
451 assert(bytes_read
% sizeof(long) == 0);
453 for (uint32_t x
= 0; x
< bytes_read
/ sizeof(long); x
++) {
454 // Only copy bytes that are non-zero, so we don't give
455 // the VM system hell
456 if (*(temp_page
+ x
) != 0) {
457 pmem_current
= (long*)(pmem
+ curr_size
+ x
* sizeof(long));
458 *pmem_current
= *(temp_page
+ x
);
461 curr_size
+= bytes_read
;
466 if (gzclose(compressed_mem
))
467 fatal("Close failed on physical memory checkpoint file '%s'\n",