Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines with new year.
[simgrid.git] / src / smpi / internals / smpi_memory.cpp
1 /* Copyright (c) 2015-2020. 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 #include <algorithm>
7 #include <cerrno>
8 #include <climits>
9 #include <cstdint>
10 #include <cstdio>
11 #include <cstdlib>
12 #include <cstring>
13 #include <deque>
14 #include <fcntl.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include <vector>
18
19 #ifndef WIN32
20 #include <sys/mman.h>
21 #include <unistd.h>
22
23 #include "src/internal_config.h"
24 #include "src/xbt/memory_map.hpp"
25
26 #include "private.hpp"
27 #include "src/smpi/include/smpi_actor.hpp"
28
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_memory, smpi, "Memory layout support for SMPI");
30
31 int smpi_loaded_page      = -1;
32 char* smpi_data_exe_start = nullptr;
33 int smpi_data_exe_size    = 0;
34 SmpiPrivStrategies smpi_privatize_global_variables;
35 static void* smpi_data_exe_copy;
36
37 // Initialized by smpi_prepare_global_memory_segment().
38 static std::vector<simgrid::xbt::VmMap> initial_vm_map;
39
40 // We keep a copy of all the privatization regions: We can then delete everything easily by iterating over this
41 // collection and nothing can be leaked. We could also iterate over all actors but we would have to be diligent when two
42 // actors use the same privatization region (so, smart pointers would have to be used etc.)
43 // Use a std::deque so that pointers remain valid after push_back().
44 static std::deque<s_smpi_privatization_region_t> smpi_privatization_regions;
45
46 static constexpr int PROT_RWX = PROT_READ | PROT_WRITE | PROT_EXEC;
47 static constexpr int PROT_RW  = PROT_READ | PROT_WRITE;
48
49 /** Take a snapshot of the process' memory map.
50  */
51 void smpi_prepare_global_memory_segment()
52 {
53   initial_vm_map = simgrid::xbt::get_memory_map(getpid());
54 }
55
56 static void smpi_get_executable_global_size()
57 {
58   char buffer[PATH_MAX];
59   const char* full_name = realpath(simgrid::xbt::binary_name.c_str(), buffer);
60   xbt_assert(full_name != nullptr, "Could not resolve real path of binary file '%s'",
61              simgrid::xbt::binary_name.c_str());
62
63   std::vector<simgrid::xbt::VmMap> map = simgrid::xbt::get_memory_map(getpid());
64   for (auto i = map.begin(); i != map.end() ; ++i) {
65     // TODO, In practice, this implementation would not detect a completely
66     // anonymous data segment. This does not happen in practice, however.
67
68     // File backed RW entry:
69     if (i->pathname == full_name && (i->prot & PROT_RWX) == PROT_RW) {
70       smpi_data_exe_start = (char*)i->start_addr;
71       smpi_data_exe_size  = i->end_addr - i->start_addr;
72       /* Here we are making the assumption that a suitable empty region
73          following the rw- area is the end of the data segment. It would
74          be better to check with the size of the data segment. */
75       ++i;
76       if (i != map.end() && i->pathname.empty() && (i->prot & PROT_RWX) == PROT_RW &&
77           (char*)i->start_addr == smpi_data_exe_start + smpi_data_exe_size) {
78         // Only count the portion of this region not present in the initial map.
79         auto found = std::find_if(initial_vm_map.begin(), initial_vm_map.end(), [&i](const simgrid::xbt::VmMap& m) {
80           return i->start_addr <= m.start_addr && m.start_addr < i->end_addr;
81         });
82         auto end_addr      = (found == initial_vm_map.end() ? i->end_addr : found->start_addr);
83         smpi_data_exe_size = (char*)end_addr - smpi_data_exe_start;
84       }
85       return;
86     }
87   }
88   xbt_die("Did not find my data segment.");
89 }
90 #endif
91
92 #if HAVE_SANITIZER_ADDRESS
93 #include <sanitizer/asan_interface.h>
94 static void* asan_safe_memcpy(void* dest, void* src, size_t n)
95 {
96   char* psrc  = static_cast<char*>(src);
97   char* pdest = static_cast<char*>(dest);
98   for (size_t i = 0; i < n;) {
99     while (i < n && __asan_address_is_poisoned(psrc + i))
100       ++i;
101     if (i < n) {
102       char* p  = static_cast<char*>(__asan_region_is_poisoned(psrc + i, n - i));
103       size_t j = p ? (p - psrc) : n;
104       memcpy(pdest + i, psrc + i, j - i);
105       i = j;
106     }
107   }
108   return dest;
109 }
110 #else
111 #define asan_safe_memcpy(dest, src, n) memcpy((dest), (src), (n))
112 #endif
113
114 /**
115  * @brief Uses shm_open to get a temporary shm, and returns its file descriptor.
116  */
117 int smpi_temp_shm_get()
118 {
119   constexpr unsigned VAL_MASK = 0xffffffffUL;
120   static unsigned prev_val    = VAL_MASK;
121   char shmname[32]; // cannot be longer than PSHMNAMLEN = 31 on macOS (shm_open raises ENAMETOOLONG otherwise)
122   int fd;
123
124   for (unsigned i = (prev_val + 1) & VAL_MASK; i != prev_val; i = (i + 1) & VAL_MASK) {
125     snprintf(shmname, sizeof(shmname), "/smpi-buffer-%016x", i);
126     fd = shm_open(shmname, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
127     if (fd != -1 || errno != EEXIST) {
128       prev_val = i;
129       break;
130     }
131   }
132   if (fd < 0) {
133     if (errno == EMFILE) {
134       xbt_die("Impossible to create temporary file for memory mapping: %s\n\
135 The shm_open() system call failed with the EMFILE error code (too many files). \n\n\
136 This means that you reached the system limits concerning the amount of files per process. \
137 This is not a surprise if you are trying to virtualize many processes on top of SMPI. \
138 Don't panic -- you should simply increase your system limits and try again. \n\n\
139 First, check what your limits are:\n\
140   cat /proc/sys/fs/file-max # Gives you the system-wide limit\n\
141   ulimit -Hn                # Gives you the per process hard limit\n\
142   ulimit -Sn                # Gives you the per process soft limit\n\
143   cat /proc/self/limits     # Displays any per-process limitation (including the one given above)\n\n\
144 If one of these values is less than the amount of MPI processes that you try to run, then you got the explanation of this error. \
145 Ask the Internet about tutorials on how to increase the files limit such as: https://rtcamp.com/tutorials/linux/increase-open-files-limit/",
146               strerror(errno));
147     }
148     xbt_die("Impossible to create temporary file for memory mapping. shm_open: %s", strerror(errno));
149   }
150   XBT_DEBUG("Got temporary shm %s (fd = %d)", shmname, fd);
151   if (shm_unlink(shmname) < 0)
152     XBT_WARN("Could not early unlink %s. shm_unlink: %s", shmname, strerror(errno));
153   return fd;
154 }
155
156 /**
157  * @brief Mmap a region of size bytes from temporary shm with file descriptor fd.
158  */
159 void* smpi_temp_shm_mmap(int fd, size_t size)
160 {
161   struct stat st;
162   if (fstat(fd, &st) != 0)
163     xbt_die("Could not stat fd %d: %s", fd, strerror(errno));
164   if (static_cast<off_t>(size) > st.st_size && ftruncate(fd, static_cast<off_t>(size)) != 0)
165     xbt_die("Could not truncate fd %d to %zu: %s", fd, size, strerror(errno));
166   void* mem = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
167   if (mem == MAP_FAILED) {
168     xbt_die("Failed to map fd %d with size %zu: %s\n"
169             "If you are running a lot of ranks, you may be exceeding the amount of mappings allowed per process.\n"
170             "On Linux systems, change this value with sudo sysctl -w vm.max_map_count=newvalue (default value: 65536)\n"
171             "Please see "
172             "https://simgrid.org/doc/latest/Configuring_SimGrid.html#configuring-the-user-code-virtualization for more "
173             "information.",
174             fd, size, strerror(errno));
175   }
176   return mem;
177 }
178
179 /** Map a given SMPI privatization segment (make a SMPI process active)
180  *
181  *  When doing a state restoration, the state of the restored variables  might not be consistent with the state of the
182  *  virtual memory. In this case, we to change the data segment.
183  */
184 void smpi_switch_data_segment(simgrid::s4u::ActorPtr actor)
185 {
186   if (smpi_loaded_page == actor->get_pid()) // no need to switch, we've already loaded the one we want
187     return;
188
189   if (smpi_data_exe_size == 0) // no need to switch
190     return;
191
192 #if HAVE_PRIVATIZATION
193   // FIXME, cross-process support (mmap across process when necessary)
194   XBT_DEBUG("Switching data frame to the one of process %ld", actor->get_pid());
195   simgrid::smpi::ActorExt* process = smpi_process_remote(actor);
196   int current                     = process->privatized_region()->file_descriptor;
197   const void* tmp = mmap(TOPAGE(smpi_data_exe_start), smpi_data_exe_size, PROT_RW, MAP_FIXED | MAP_SHARED, current, 0);
198   if (tmp != TOPAGE(smpi_data_exe_start))
199     xbt_die("Couldn't map the new region (errno %d): %s", errno, strerror(errno));
200   smpi_loaded_page = actor->get_pid();
201 #endif
202 }
203
204 /**
205  * @brief Makes a backup of the segment in memory that stores the global variables of a process.
206  *        This backup is then used to initialize the global variables for every single
207  *        process that is added, regardless of the progress of the simulation.
208  */
209 void smpi_backup_global_memory_segment()
210 {
211 #if HAVE_PRIVATIZATION
212   smpi_get_executable_global_size();
213   initial_vm_map.clear();
214   initial_vm_map.shrink_to_fit();
215
216   XBT_DEBUG("bss+data segment found : size %d starting at %p", smpi_data_exe_size, smpi_data_exe_start);
217
218   if (smpi_data_exe_size == 0) { // no need to do anything as global variables don't exist
219     smpi_privatize_global_variables = SmpiPrivStrategies::NONE;
220     return;
221   }
222
223   smpi_data_exe_copy = ::operator new(smpi_data_exe_size);
224   // Make a copy of the data segment. This clean copy is retained over the whole runtime
225   // of the simulation and can be used to initialize a dynamically added, new process.
226   asan_safe_memcpy(smpi_data_exe_copy, TOPAGE(smpi_data_exe_start), smpi_data_exe_size);
227 #else /* ! HAVE_PRIVATIZATION */
228   xbt_die("You are trying to use privatization on a system that does not support it. Don't.");
229 #endif
230 }
231
232 // Initializes the memory mapping for a single process and returns the privatization region
233 smpi_privatization_region_t smpi_init_global_memory_segment_process()
234 {
235   int file_descriptor = smpi_temp_shm_get();
236
237   // ask for a free region
238   void* address = smpi_temp_shm_mmap(file_descriptor, smpi_data_exe_size);
239
240   // initialize the values
241   asan_safe_memcpy(address, smpi_data_exe_copy, smpi_data_exe_size);
242
243   // store the address of the mapping for further switches
244   smpi_privatization_regions.emplace_back(s_smpi_privatization_region_t{address, file_descriptor});
245
246   return &smpi_privatization_regions.back();
247 }
248
249 void smpi_destroy_global_memory_segments(){
250   if (smpi_data_exe_size == 0) // no need to switch
251     return;
252 #if HAVE_PRIVATIZATION
253   for (auto const& region : smpi_privatization_regions) {
254     if (munmap(region.address, smpi_data_exe_size) < 0)
255       XBT_WARN("Unmapping of fd %d failed: %s", region.file_descriptor, strerror(errno));
256     close(region.file_descriptor);
257   }
258   smpi_privatization_regions.clear();
259   ::operator delete(smpi_data_exe_copy);
260 #endif
261 }
262
263 static std::vector<unsigned char> sendbuffer;
264 static std::vector<unsigned char> recvbuffer;
265
266 //allocate a single buffer for all sends, growing it if needed
267 unsigned char* smpi_get_tmp_sendbuffer(size_t size)
268 {
269   if (not smpi_process()->replaying())
270     return new unsigned char[size];
271   // FIXME: a resize() may invalidate a previous pointer. Maybe we need to handle a queue of buffers with a reference
272   // counter. The same holds for smpi_get_tmp_recvbuffer.
273   if (sendbuffer.size() < size)
274     sendbuffer.resize(size);
275   return sendbuffer.data();
276 }
277
278 //allocate a single buffer for all recv
279 unsigned char* smpi_get_tmp_recvbuffer(size_t size)
280 {
281   if (not smpi_process()->replaying())
282     return new unsigned char[size];
283   if (recvbuffer.size() < size)
284     recvbuffer.resize(size);
285   return recvbuffer.data();
286 }
287
288 void smpi_free_tmp_buffer(const unsigned char* buf)
289 {
290   if (not smpi_process()->replaying())
291     delete[] buf;
292 }
293
294 void smpi_free_replay_tmp_buffers()
295 {
296   std::vector<unsigned char>().swap(sendbuffer);
297   std::vector<unsigned char>().swap(recvbuffer);
298 }