Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
88b1ae8e378d214642570bb117deffb2b7c6c02b
[simgrid.git] / src / smpi / internals / smpi_memory.cpp
1 /* Copyright (c) 2015-2018. 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 <cerrno>
7 #include <climits>
8 #include <cstdint>
9 #include <cstdio>
10 #include <cstdlib>
11 #include <cstring>
12 #include <deque>
13 #include <fcntl.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include <vector>
17
18 #ifndef WIN32
19 #include <sys/mman.h>
20 #include <unistd.h>
21
22 #include "src/internal_config.h"
23 #include "src/xbt/memory_map.hpp"
24
25 #include "private.hpp"
26 #include "smpi_process.hpp"
27
28 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_memory, smpi, "Memory layout support for SMPI");
29
30 int smpi_loaded_page      = -1;
31 char* smpi_data_exe_start = nullptr;
32 int smpi_data_exe_size    = 0;
33 SmpiPrivStrategies smpi_privatize_global_variables;
34 static void* smpi_data_exe_copy;
35
36 // We keep a copy of all the privatization regions: We can then delete everything easily by iterating over this
37 // collection and nothing can be leaked. We could also iterate over all actors but we would have to be diligent when two
38 // actors use the same privatization region (so, smart pointers would have to be used etc.)
39 // Use a std::deque so that pointers remain valid after push_back().
40 static std::deque<s_smpi_privatization_region_t> smpi_privatization_regions;
41
42 static constexpr int PROT_RWX = PROT_READ | PROT_WRITE | PROT_EXEC;
43 static constexpr int PROT_RW  = PROT_READ | PROT_WRITE;
44
45 static void smpi_get_executable_global_size()
46 {
47   char buffer[PATH_MAX];
48   char* full_name = realpath(xbt_binary_name, buffer);
49   if (full_name == nullptr)
50     xbt_die("Could not resolve binary file name");
51
52   std::vector<simgrid::xbt::VmMap> map = simgrid::xbt::get_memory_map(getpid());
53   for (auto i = map.begin(); i != map.end() ; ++i) {
54     // TODO, In practice, this implementation would not detect a completely
55     // anonymous data segment. This does not happen in practice, however.
56
57     // File backed RW entry:
58     if (i->pathname == full_name && (i->prot & PROT_RWX) == PROT_RW) {
59       smpi_data_exe_start = (char*)i->start_addr;
60       smpi_data_exe_size  = i->end_addr - i->start_addr;
61       ++i;
62       /* Here we are making the assumption that a suitable empty region
63          following the rw- area is the end of the data segment. It would
64          be better to check with the size of the data segment. */
65       if (i != map.end() && i->pathname.empty() && (i->prot & PROT_RWX) == PROT_RW &&
66           (char*)i->start_addr == smpi_data_exe_start + smpi_data_exe_size) {
67         smpi_data_exe_size = (char*)i->end_addr - smpi_data_exe_start;
68       }
69       return;
70     }
71   }
72   xbt_die("Did not find my data segment.");
73 }
74 #endif
75
76 #if HAVE_SANITIZE_ADDRESS
77 #include <sanitizer/asan_interface.h>
78 static void* asan_safe_memcpy(void* dest, void* src, size_t n)
79 {
80   char* psrc  = static_cast<char*>(src);
81   char* pdest = static_cast<char*>(dest);
82   for (size_t i = 0; i < n;) {
83     while (i < n && __asan_address_is_poisoned(psrc + i))
84       ++i;
85     if (i < n) {
86       char* p  = static_cast<char*>(__asan_region_is_poisoned(psrc + i, n - i));
87       size_t j = p ? (p - psrc) : n;
88       memcpy(pdest + i, psrc + i, j - i);
89       i = j;
90     }
91   }
92   return dest;
93 }
94 #else
95 #define asan_safe_memcpy(dest, src, n) memcpy(dest, src, n)
96 #endif
97
98 /** Map a given SMPI privatization segment (make a SMPI process active) */
99 void smpi_switch_data_segment(simgrid::s4u::ActorPtr actor)
100 {
101   if (smpi_loaded_page == actor->get_pid()) // no need to switch, we've already loaded the one we want
102     return;
103
104   // So the job:
105   smpi_really_switch_data_segment(actor);
106 }
107
108 /** Map a given SMPI privatization segment (make a SMPI process active)  even if SMPI thinks it is already active
109  *
110  *  When doing a state restoration, the state of the restored variables  might not be consistent with the state of the
111  *  virtual memory. In this case, we to change the data segment.
112  */
113 void smpi_really_switch_data_segment(simgrid::s4u::ActorPtr actor)
114 {
115   if (smpi_data_exe_size == 0) // no need to switch
116     return;
117
118 #if HAVE_PRIVATIZATION
119   // FIXME, cross-process support (mmap across process when necessary)
120   XBT_DEBUG("Switching data frame to the one of process %ld", actor->get_pid());
121   simgrid::smpi::Process* process = smpi_process_remote(actor);
122   int current                     = process->privatized_region()->file_descriptor;
123   void* tmp = mmap(TOPAGE(smpi_data_exe_start), smpi_data_exe_size, PROT_RW, MAP_FIXED | MAP_SHARED, current, 0);
124   if (tmp != TOPAGE(smpi_data_exe_start))
125     xbt_die("Couldn't map the new region (errno %d): %s", errno, strerror(errno));
126   smpi_loaded_page = actor->get_pid();
127 #endif
128 }
129
130 int smpi_is_privatization_file(char* file)
131 {
132   const std::string buffer_path("/dev/shm/my-buffer-");
133   return buffer_path.compare(0, std::string::npos, file, buffer_path.length()) == 0;
134 }
135
136 /**
137  * @brief Makes a backup of the segment in memory that stores the global variables of a process.
138  *        This backup is then used to initialize the global variables for every single
139  *        process that is added, regardless of the progress of the simulation.
140  */
141 void smpi_backup_global_memory_segment()
142 {
143   xbt_assert(HAVE_PRIVATIZATION, "You are trying to use privatization on a system that does not support it. Don't.");
144   smpi_get_executable_global_size();
145
146   XBT_DEBUG("bss+data segment found : size %d starting at %p", smpi_data_exe_size, smpi_data_exe_start);
147
148   if (smpi_data_exe_size == 0) { // no need to do anything as global variables don't exist
149     smpi_privatize_global_variables = SmpiPrivStrategies::None;
150     return;
151   }
152
153   smpi_data_exe_copy = ::operator new(smpi_data_exe_size);
154   // Make a copy of the data segment. This clean copy is retained over the whole runtime
155   // of the simulation and can be used to initialize a dynamically added, new process.
156   asan_safe_memcpy(smpi_data_exe_copy, TOPAGE(smpi_data_exe_start), smpi_data_exe_size);
157 }
158
159 // Initializes the memory mapping for a single process and returns the privatization region
160 smpi_privatization_region_t smpi_init_global_memory_segment_process()
161 {
162   int file_descriptor;
163   void* address = nullptr;
164   char path[24];
165   int status;
166
167   do {
168     snprintf(path, sizeof(path), "/smpi-buffer-%06x", rand() % 0xffffffU);
169     file_descriptor = shm_open(path, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
170   } while (file_descriptor == -1 && errno == EEXIST);
171   if (file_descriptor < 0) {
172     if (errno == EMFILE) {
173       xbt_die("Impossible to create temporary file for memory mapping: %s\n\
174 The open() system call failed with the EMFILE error code (too many files). \n\n\
175 This means that you reached the system limits concerning the amount of files per process. \
176 This is not a surprise if you are trying to virtualize many processes on top of SMPI. \
177 Don't panic -- you should simply increase your system limits and try again. \n\n\
178 First, check what your limits are:\n\
179   cat /proc/sys/fs/file-max # Gives you the system-wide limit\n\
180   ulimit -Hn                # Gives you the per process hard limit\n\
181   ulimit -Sn                # Gives you the per process soft limit\n\
182   cat /proc/self/limits     # Displays any per-process limitation (including the one given above)\n\n\
183 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. \
184 Ask the Internet about tutorials on how to increase the files limit such as: https://rtcamp.com/tutorials/linux/increase-open-files-limit/",
185               strerror(errno));
186     }
187     xbt_die("Impossible to create temporary file for memory mapping: %s", strerror(errno));
188   }
189
190   status = ftruncate(file_descriptor, smpi_data_exe_size);
191   if (status)
192     xbt_die("Impossible to set the size of the temporary file for memory mapping");
193
194   /* Ask for a free region */
195   address = mmap(nullptr, smpi_data_exe_size, PROT_RW, MAP_SHARED, file_descriptor, 0);
196   if (address == MAP_FAILED)
197     xbt_die("Couldn't find a free region for memory mapping");
198
199   status = shm_unlink(path);
200   if (status)
201     xbt_die("Impossible to unlink temporary file for memory mapping");
202
203   // initialize the values
204   asan_safe_memcpy(address, smpi_data_exe_copy, smpi_data_exe_size);
205
206   // store the address of the mapping for further switches
207   smpi_privatization_regions.emplace_back(s_smpi_privatization_region_t{address, file_descriptor});
208
209   return &smpi_privatization_regions.back();
210 }
211
212 void smpi_destroy_global_memory_segments(){
213   if (smpi_data_exe_size == 0) // no need to switch
214     return;
215 #if HAVE_PRIVATIZATION
216   for (auto const& region : smpi_privatization_regions) {
217     if (munmap(region.address, smpi_data_exe_size) < 0)
218       XBT_WARN("Unmapping of fd %d failed: %s", region.file_descriptor, strerror(errno));
219     close(region.file_descriptor);
220   }
221   smpi_privatization_regions.clear();
222   ::operator delete(smpi_data_exe_copy);
223 #endif
224 }
225
226 static int sendbuffer_size = 0;
227 static char* sendbuffer    = nullptr;
228 static int recvbuffer_size = 0;
229 static char* recvbuffer    = nullptr;
230
231 //allocate a single buffer for all sends, growing it if needed
232 void* smpi_get_tmp_sendbuffer(int size)
233 {
234   if (not smpi_process()->replaying())
235     return xbt_malloc(size);
236   if (sendbuffer_size<size){
237     sendbuffer=static_cast<char*>(xbt_realloc(sendbuffer,size));
238     sendbuffer_size=size;
239   }
240   return sendbuffer;
241 }
242
243 //allocate a single buffer for all recv
244 void* smpi_get_tmp_recvbuffer(int size){
245   if (not smpi_process()->replaying())
246     return xbt_malloc(size);
247   if (recvbuffer_size<size){
248     recvbuffer=static_cast<char*>(xbt_realloc(recvbuffer,size));
249     recvbuffer_size=size;
250   }
251   return recvbuffer;
252 }
253
254 void smpi_free_tmp_buffer(void* buf){
255   if (not smpi_process()->replaying())
256     xbt_free(buf);
257 }
258
259 void smpi_free_replay_tmp_buffers(){
260   xbt_free(sendbuffer);
261   xbt_free(recvbuffer);
262 }