Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
e0aa0d1b35ff9979f2ada29f0f4a461a7cb00025
[simgrid.git] / src / smpi / smpi_shared.cpp
1 /* Copyright (c) 2007, 2009-2017. The SimGrid Team. All rights reserved.    */
2
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. */
5
6 /* Shared allocations are handled through shared memory segments.
7  * Associated data and metadata are used as follows:
8  *
9  *                                                                    mmap #1
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  *                    --------------------    |   ^                           |
17  *                                            |   |                           |
18  *                                            |   |   `allocs_metadata' dict  |
19  *                                            |   |   ----------------------  |
20  *                                            |   `-- | <addr of mmap #1>  |<-'
21  *                                            |   .-- | <addr of mmap #2>  |<-.
22  *                                            |   |   ----------------------  |
23  *                                            |   |                           |
24  *                                            |   |                           |
25  *                                            |   |                           |
26  *                                            |   |                   mmap #2 |
27  *                                            |   v                     ---- -'
28  *                                            |   shared_metadata_t   / |  |
29  *                                            |   -----------------   | |  |
30  *                                            |   | size of mmap  | --| |  |
31  *                                            `-- | data          |   | |  |
32  *                                                -----------------   | |  |
33  *                                                                    \ |  |
34  *                                                                      ----
35  */
36 #include <cstring>
37
38 #include <unordered_map>
39 #include <utility>
40
41 #include "src/internal_config.h"
42 #include "private.h"
43 #include "private.hpp"
44 #include <xbt/ex.hpp>
45 #include "xbt/dict.h"
46 //#include "xbt/sysdep.h"
47 //#include "xbt/ex.h"
48 #include "surf/surf.h"
49 #include "simgrid/sg_config.h"
50 //#include "simgrid/modelchecker.h"
51 //#include "src/mc/mc_replay.h"
52
53 #include <sys/types.h>
54 #ifndef WIN32
55 #include <sys/mman.h>
56 #endif
57 #include <sys/stat.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 //#include <math.h> // sqrt
61 #include <unistd.h>
62 #include <string.h>
63 #include <stdio.h>
64
65 #ifndef MAP_ANONYMOUS
66 #define MAP_ANONYMOUS MAP_ANON
67 #endif
68
69 #ifndef MAP_POPULATE
70 #define MAP_POPULATE 0
71 #endif
72
73 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_shared, smpi, "Logging specific to SMPI (shared memory macros)");
74
75 #define PTR_STRLEN (2 + 2 * sizeof(void*) + 1)
76
77 namespace{
78 /** Some location in the source code
79  *
80  *  This information is used by SMPI_SHARED_MALLOC to allocate  some shared memory for all simulated processes.
81  */
82
83 class smpi_source_location {
84 public:
85   smpi_source_location(const char* filename, int line)
86       : filename(xbt_strdup(filename)), filename_length(strlen(filename)), line(line)
87   {
88   }
89
90   /** Pointer to a static string containing the file name */
91   char* filename      = nullptr;
92   int filename_length = 0;
93   int line            = 0;
94
95   bool operator==(smpi_source_location const& that) const
96   {
97     return filename_length == that.filename_length && line == that.line &&
98            std::memcmp(filename, that.filename, filename_length) == 0;
99   }
100   bool operator!=(smpi_source_location const& that) const { return !(*this == that); }
101 };
102 }
103
104 namespace std {
105
106 template <> class hash<smpi_source_location> {
107 public:
108   typedef smpi_source_location argument_type;
109   typedef std::size_t result_type;
110   result_type operator()(smpi_source_location const& loc) const
111   {
112     return xbt_str_hash_ext(loc.filename, loc.filename_length) ^
113            xbt_str_hash_ext((const char*)&loc.line, sizeof(loc.line));
114   }
115 };
116 }
117
118 namespace{
119
120 typedef struct {
121   int fd    = -1;
122   int count = 0;
123 } shared_data_t;
124
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;
127
128 typedef struct {
129   size_t size;
130   shared_data_key_type* data;
131 } shared_metadata_t;
132
133 std::unordered_map<void*, shared_metadata_t> allocs_metadata;
134 xbt_dict_t calls = nullptr;           /* Allocated on first use */
135 #ifndef WIN32
136 static int smpi_shared_malloc_bogusfile           = -1;
137 static unsigned long smpi_shared_malloc_blocksize = 1UL << 20;
138 #endif
139 }
140
141
142 void smpi_shared_destroy()
143 {
144   allocs.clear();
145   allocs_metadata.clear();
146   xbt_dict_free(&calls);
147 }
148
149 static size_t shm_size(int fd) {
150   struct stat st;
151
152   if(fstat(fd, &st) < 0) {
153     xbt_die("Could not stat fd %d: %s", fd, strerror(errno));
154   }
155   return static_cast<size_t>(st.st_size);
156 }
157
158 #ifndef WIN32
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;
162
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));
165   }
166
167   void* mem = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
168   if(mem == MAP_FAILED) {
169     xbt_die(
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));
175   }
176   snprintf(loc, PTR_STRLEN, "%p", mem);
177   meta.size = size;
178   meta.data = data;
179   allocs_metadata[mem] = meta;
180   XBT_DEBUG("MMAP %zu to %p", size, mem);
181   return mem;
182 }
183
184 void *smpi_shared_malloc(size_t size, const char *file, int line)
185 {
186   void* mem;
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;
191     if (res.second) {
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);
197       if (fd < 0) {
198         if (errno == EEXIST)
199           xbt_die("Please cleanup /dev/shm/%s", shmname);
200         else
201           xbt_die("An unhandled error occurred while opening %s. shm_open: %s", shmname, strerror(errno));
202       }
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));
208       }
209       XBT_DEBUG("Mapping %s at %p through %d", shmname, mem, fd);
210     } else {
211       mem = shm_map(data->second.fd, size, &*data);
212       data->second.count++;
213     }
214     XBT_DEBUG("Shared malloc %zu in %p (metadata at %p)", size, mem, &*data);
215
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);
219
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));
223
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);
230       unlink(name);
231       xbt_free(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);
234       if(err<0)
235         xbt_die("Could not write bogus file for shared malloc");
236       xbt_free(dumb);
237     }
238
239     /* Map the bogus file in place of the anonymous memory */
240     unsigned int i;
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?",
247                  strerror(errno));
248     }
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?",
255                  strerror(errno));
256     }
257
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;
263     newmeta.size = size;
264     newmeta.data = data;
265     allocs_metadata[mem] = newmeta;
266   } else {
267     mem = xbt_malloc(size);
268     XBT_DEBUG("Classic malloc %zu in %p", size, mem);
269   }
270
271   return mem;
272 }
273
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) 
277      return 1;
278     for(auto it : allocs_metadata){
279       if (ptr >= it.first && ptr < (char*)it.first + it.second.size)
280         return 1;
281     }
282       return 0;
283   } else {
284     return 0;
285   }
286 }
287
288 void smpi_shared_free(void *ptr)
289 {
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);
296       return;
297     }
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));
301     }
302     data->count--;
303     if (data->count <= 0) {
304       close(data->fd);
305       allocs.erase(allocs.find(meta->second.data->first));
306       allocs_metadata.erase(ptr);
307       XBT_DEBUG("Shared free - with removal - of %p", ptr);
308     } else {
309       XBT_DEBUG("Shared free - no removal - of %p, count = %d", ptr, data->count);
310     }
311
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);
318     }
319
320     munmap(ptr, 0); // the POSIX says that I should not give 0 as a length, but it seems to work OK
321   } else {
322     XBT_DEBUG("Classic free of %p", ptr);
323     xbt_free(ptr);
324   }
325 }
326 #endif
327
328 int smpi_shared_known_call(const char* func, const char* input)
329 {
330   char* loc = bprintf("%s:%s", func, input);
331   int known = 0;
332
333   if (calls==nullptr) {
334     calls = xbt_dict_new_homogeneous(nullptr);
335   }
336   try {
337     xbt_dict_get(calls, loc); /* Succeed or throw */
338     known = 1;
339     xbt_free(loc);
340   }
341   catch (xbt_ex& ex) {
342     xbt_free(loc);
343     if (ex.category != not_found_error)
344       throw;
345   }
346   catch(...) {
347     xbt_free(loc);
348     throw;
349   }
350   return known;
351 }
352
353 void* smpi_shared_get_call(const char* func, const char* input) {
354   char* loc = bprintf("%s:%s", func, input);
355
356   if (calls == nullptr)
357     calls    = xbt_dict_new_homogeneous(nullptr);
358   void* data = xbt_dict_get(calls, loc);
359   xbt_free(loc);
360   return data;
361 }
362
363 void* smpi_shared_set_call(const char* func, const char* input, void* data) {
364   char* loc = bprintf("%s:%s", func, input);
365
366   if (calls == nullptr)
367     calls = xbt_dict_new_homogeneous(nullptr);
368   xbt_dict_set(calls, loc, data, nullptr);
369   xbt_free(loc);
370   return data;
371 }
372