1 /* Copyright (c) 2007, 2009-2017. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 /* Shared allocations are handled through shared memory segments.
7 * Associated data and metadata are used as follows:
10 * `allocs' dict ---- -.
11 * ---------- shared_data_t shared_metadata_t / | | |
12 * .->| <name> | ---> -------------------- <--. ----------------- | | | |
13 * | ---------- | fd of <name> | | | size of mmap | --| | | |
14 * | | count (2) | |-- | data | \ | | |
15 * `----------------- | <name> | | ----------------- ---- |
16 * -------------------- | ^ |
18 * | | `allocs_metadata' dict |
19 * | | ---------------------- |
20 * | `-- | <addr of mmap #1> |<-'
21 * | .-- | <addr of mmap #2> |<-.
22 * | | ---------------------- |
28 * | shared_metadata_t / | |
29 * | ----------------- | | |
30 * | | size of mmap | --| | |
32 * ----------------- | | |
38 #include <unordered_map>
41 #include "src/internal_config.h"
43 #include "private.hpp"
46 //#include "xbt/sysdep.h"
48 #include "surf/surf.h"
49 #include "simgrid/sg_config.h"
50 //#include "simgrid/modelchecker.h"
51 //#include "src/mc/mc_replay.h"
53 #include <sys/types.h>
60 //#include <math.h> // sqrt
66 #define MAP_ANONYMOUS MAP_ANON
70 #define MAP_POPULATE 0
73 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_shared, smpi, "Logging specific to SMPI (shared memory macros)");
75 #define PTR_STRLEN (2 + 2 * sizeof(void*) + 1)
78 /** Some location in the source code
80 * This information is used by SMPI_SHARED_MALLOC to allocate some shared memory for all simulated processes.
83 class smpi_source_location {
85 smpi_source_location(const char* filename, int line)
86 : filename(xbt_strdup(filename)), filename_length(strlen(filename)), line(line)
90 /** Pointer to a static string containing the file name */
91 char* filename = nullptr;
92 int filename_length = 0;
95 bool operator==(smpi_source_location const& that) const
97 return filename_length == that.filename_length && line == that.line &&
98 std::memcmp(filename, that.filename, filename_length) == 0;
100 bool operator!=(smpi_source_location const& that) const { return !(*this == that); }
106 template <> class hash<smpi_source_location> {
108 typedef smpi_source_location argument_type;
109 typedef std::size_t result_type;
110 result_type operator()(smpi_source_location const& loc) const
112 return xbt_str_hash_ext(loc.filename, loc.filename_length) ^
113 xbt_str_hash_ext((const char*)&loc.line, sizeof(loc.line));
125 std::unordered_map<smpi_source_location, shared_data_t> allocs;
126 typedef std::unordered_map<smpi_source_location, shared_data_t>::value_type shared_data_key_type;
130 shared_data_key_type* data;
133 std::unordered_map<void*, shared_metadata_t> allocs_metadata;
134 xbt_dict_t calls = nullptr; /* Allocated on first use */
136 static int smpi_shared_malloc_bogusfile = -1;
137 static unsigned long smpi_shared_malloc_blocksize = 1UL << 20;
142 void smpi_shared_destroy()
145 allocs_metadata.clear();
146 xbt_dict_free(&calls);
149 static size_t shm_size(int fd) {
152 if(fstat(fd, &st) < 0) {
153 xbt_die("Could not stat fd %d: %s", fd, strerror(errno));
155 return static_cast<size_t>(st.st_size);
159 static void* shm_map(int fd, size_t size, shared_data_key_type* data) {
160 char loc[PTR_STRLEN];
161 shared_metadata_t meta;
163 if(size > shm_size(fd) && (ftruncate(fd, static_cast<off_t>(size)) < 0)) {
164 xbt_die("Could not truncate fd %d to %zu: %s", fd, size, strerror(errno));
167 void* mem = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
168 if(mem == MAP_FAILED) {
170 "Failed to map fd %d with size %zu: %s\n"
171 "If you are running a lot of ranks, you may be exceeding the amount of mappings allowed per process.\n"
172 "On Linux systems, change this value with sudo sysctl -w vm.max_map_count=newvalue (default value: 65536)\n"
173 "Please see http://simgrid.gforge.inria.fr/simgrid/latest/doc/html/options.html#options_virt for more info.",
174 fd, size, strerror(errno));
176 snprintf(loc, PTR_STRLEN, "%p", mem);
179 allocs_metadata[mem] = meta;
180 XBT_DEBUG("MMAP %zu to %p", size, mem);
184 void *smpi_shared_malloc(size_t size, const char *file, int line)
187 if (size > 0 && smpi_cfg_shared_malloc == shmalloc_local) {
188 smpi_source_location loc(file, line);
189 auto res = allocs.insert(std::make_pair(loc, shared_data_t()));
190 auto data = res.first;
192 // The insertion did not take place.
193 // Generate a shared memory name from the address of the shared_data:
194 char shmname[32]; // cannot be longer than PSHMNAMLEN = 31 on Mac OS X (shm_open raises ENAMETOOLONG otherwise)
195 snprintf(shmname, 31, "/shmalloc%p", &*data);
196 int fd = shm_open(shmname, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
199 xbt_die("Please cleanup /dev/shm/%s", shmname);
201 xbt_die("An unhandled error occurred while opening %s. shm_open: %s", shmname, strerror(errno));
203 data->second.fd = fd;
204 data->second.count = 1;
205 mem = shm_map(fd, size, &*data);
206 if (shm_unlink(shmname) < 0) {
207 XBT_WARN("Could not early unlink %s. shm_unlink: %s", shmname, strerror(errno));
209 XBT_DEBUG("Mapping %s at %p through %d", shmname, mem, fd);
211 mem = shm_map(data->second.fd, size, &*data);
212 data->second.count++;
214 XBT_DEBUG("Shared malloc %zu in %p (metadata at %p)", size, mem, &*data);
216 } else if (smpi_cfg_shared_malloc == shmalloc_global) {
217 /* First reserve memory area */
218 mem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
220 xbt_assert(mem != MAP_FAILED, "Failed to allocate %luMiB of memory. Run \"sysctl vm.overcommit_memory=1\" as root "
221 "to allow big allocations.\n",
222 (unsigned long)(size >> 20));
224 /* Create bogus file if not done already */
225 if (smpi_shared_malloc_bogusfile == -1) {
226 /* Create a fd to a new file on disk, make it smpi_shared_malloc_blocksize big, and unlink it.
227 * It still exists in memory but not in the file system (thus it cannot be leaked). */
228 char* name = xbt_strdup("/tmp/simgrid-shmalloc-XXXXXX");
229 smpi_shared_malloc_bogusfile = mkstemp(name);
232 char* dumb = (char*)calloc(1, smpi_shared_malloc_blocksize);
233 ssize_t err = write(smpi_shared_malloc_bogusfile, dumb, smpi_shared_malloc_blocksize);
235 xbt_die("Could not write bogus file for shared malloc");
239 /* Map the bogus file in place of the anonymous memory */
241 for (i = 0; i < size / smpi_shared_malloc_blocksize; i++) {
242 void* pos = (void*)((unsigned long)mem + i * smpi_shared_malloc_blocksize);
243 void* res = mmap(pos, smpi_shared_malloc_blocksize, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED | MAP_POPULATE,
244 smpi_shared_malloc_bogusfile, 0);
245 xbt_assert(res == pos, "Could not map folded virtual memory (%s). Do you perhaps need to increase the "
246 "STARPU_MALLOC_SIMULATION_FOLD environment variable or the sysctl vm.max_map_count?",
249 if (size % smpi_shared_malloc_blocksize) {
250 void* pos = (void*)((unsigned long)mem + i * smpi_shared_malloc_blocksize);
251 void* res = mmap(pos, size % smpi_shared_malloc_blocksize, PROT_READ | PROT_WRITE,
252 MAP_FIXED | MAP_SHARED | MAP_POPULATE, smpi_shared_malloc_bogusfile, 0);
253 xbt_assert(res == pos, "Could not map folded virtual memory (%s). Do you perhaps need to increase the "
254 "STARPU_MALLOC_SIMULATION_FOLD environment variable or the sysctl vm.max_map_count?",
258 shared_metadata_t newmeta;
259 //register metadata for memcpy avoidance
260 shared_data_key_type* data = (shared_data_key_type*)xbt_malloc(sizeof(shared_data_key_type));
261 data->second.fd = -1;
262 data->second.count = 1;
265 allocs_metadata[mem] = newmeta;
267 mem = xbt_malloc(size);
268 XBT_DEBUG("Classic malloc %zu in %p", size, mem);
274 int smpi_is_shared(void*ptr){
275 if ( smpi_cfg_shared_malloc == shmalloc_local || smpi_cfg_shared_malloc == shmalloc_global) {
276 if (allocs_metadata.count(ptr) != 0)
278 for(auto it : allocs_metadata){
279 if (ptr >= it.first && ptr < (char*)it.first + it.second.size)
288 void smpi_shared_free(void *ptr)
290 if (smpi_cfg_shared_malloc == shmalloc_local) {
291 char loc[PTR_STRLEN];
292 snprintf(loc, PTR_STRLEN, "%p", ptr);
293 auto meta = allocs_metadata.find(ptr);
294 if (meta == allocs_metadata.end()) {
295 XBT_WARN("Cannot free: %p was not shared-allocated by SMPI - maybe its size was 0?", ptr);
298 shared_data_t* data = &meta->second.data->second;
299 if (munmap(ptr, meta->second.size) < 0) {
300 XBT_WARN("Unmapping of fd %d failed: %s", data->fd, strerror(errno));
303 if (data->count <= 0) {
305 allocs.erase(allocs.find(meta->second.data->first));
306 allocs_metadata.erase(ptr);
307 XBT_DEBUG("Shared free - with removal - of %p", ptr);
309 XBT_DEBUG("Shared free - no removal - of %p, count = %d", ptr, data->count);
312 } else if (smpi_cfg_shared_malloc == shmalloc_global) {
313 auto meta = allocs_metadata.find(ptr);
314 if (meta != allocs_metadata.end()){
315 meta->second.data->second.count--;
316 if(meta->second.data->second.count==0)
317 xbt_free(meta->second.data);
320 munmap(ptr, 0); // the POSIX says that I should not give 0 as a length, but it seems to work OK
322 XBT_DEBUG("Classic free of %p", ptr);
328 int smpi_shared_known_call(const char* func, const char* input)
330 char* loc = bprintf("%s:%s", func, input);
333 if (calls==nullptr) {
334 calls = xbt_dict_new_homogeneous(nullptr);
337 xbt_dict_get(calls, loc); /* Succeed or throw */
343 if (ex.category != not_found_error)
353 void* smpi_shared_get_call(const char* func, const char* input) {
354 char* loc = bprintf("%s:%s", func, input);
356 if (calls == nullptr)
357 calls = xbt_dict_new_homogeneous(nullptr);
358 void* data = xbt_dict_get(calls, loc);
363 void* smpi_shared_set_call(const char* func, const char* input, void* data) {
364 char* loc = bprintf("%s:%s", func, input);
366 if (calls == nullptr)
367 calls = xbt_dict_new_homogeneous(nullptr);
368 xbt_dict_set(calls, loc, data, nullptr);