1 /* Copyright (c) 2015-2023. 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. */
7 #include "src/internal_config.h"
8 #include "src/kernel/EngineImpl.hpp"
9 #include "src/smpi/include/smpi_actor.hpp"
10 #include "src/xbt/memory_map.hpp"
23 #include <sys/types.h>
27 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_memory, smpi, "Memory layout support for SMPI");
29 static char* smpi_data_exe_start = nullptr; // start of the data+bss segment of the executable
30 static size_t smpi_data_exe_size = 0; // size of the data+bss segment of the executable
31 static SmpiPrivStrategies smpi_privatize_global_variables;
32 static void* smpi_data_exe_copy;
34 // Initialized by smpi_prepare_global_memory_segment().
35 static std::vector<simgrid::xbt::VmMap> initial_vm_map;
37 // We keep a copy of all the privatization regions: We can then delete everything easily by iterating over this
38 // collection and nothing can be leaked. We could also iterate over all actors but we would have to be diligent when two
39 // actors use the same privatization region (so, smart pointers would have to be used etc.)
40 // Use a std::deque so that pointers remain valid after push_back().
41 static std::deque<s_smpi_privatization_region_t> smpi_privatization_regions;
43 static constexpr int PROT_RWX = PROT_READ | PROT_WRITE | PROT_EXEC;
44 static constexpr int PROT_RW = PROT_READ | PROT_WRITE;
46 /** Take a snapshot of the process' memory map.
48 void smpi_prepare_global_memory_segment()
50 initial_vm_map = simgrid::xbt::get_memory_map(getpid());
53 static void smpi_get_executable_global_size()
55 const auto* binary_name = simgrid::kernel::EngineImpl::get_instance()->get_cmdline().front().c_str();
56 char* buffer = realpath(binary_name, nullptr);
57 xbt_assert(buffer != nullptr, "Could not resolve real path of binary file '%s'", binary_name);
58 std::string full_name = buffer;
61 std::vector<simgrid::xbt::VmMap> map = simgrid::xbt::get_memory_map(getpid());
62 for (auto i = map.begin(); i != map.end() ; ++i) {
63 // TODO, In practice, this implementation would not detect a completely
64 // anonymous data segment. This does not happen in practice, however.
66 // File backed RW entry:
67 if (i->pathname == full_name && (i->prot & PROT_RWX) == PROT_RW) {
68 smpi_data_exe_start = (char*)i->start_addr;
69 smpi_data_exe_size = i->end_addr - i->start_addr;
70 /* Here we are making the assumption that a suitable empty region
71 following the rw- area is the end of the data segment. It would
72 be better to check with the size of the data segment. */
73 if (auto j = i + 1; j != map.end() && j->pathname.empty() && (j->prot & PROT_RWX) == PROT_RW &&
74 (char*)j->start_addr == smpi_data_exe_start + smpi_data_exe_size) {
75 // Only count the portion of this region not present in the initial map.
76 auto found = std::find_if(initial_vm_map.begin(), initial_vm_map.end(), [&j](const simgrid::xbt::VmMap& m) {
77 return j->start_addr <= m.start_addr && m.start_addr < j->end_addr;
79 auto end_addr = (found == initial_vm_map.end() ? j->end_addr : found->start_addr);
80 smpi_data_exe_size = (char*)end_addr - smpi_data_exe_start;
85 xbt_die("Did not find my data segment.");
88 #if HAVE_SANITIZER_ADDRESS
89 #include <sanitizer/asan_interface.h>
90 static void* asan_safe_memcpy(void* dest, void* src, size_t n)
92 char* psrc = static_cast<char*>(src);
93 char* pdest = static_cast<char*>(dest);
94 for (size_t i = 0; i < n;) {
95 while (i < n && __asan_address_is_poisoned(psrc + i))
98 const char* p = static_cast<char*>(__asan_region_is_poisoned(psrc + i, n - i));
99 size_t j = p ? (p - psrc) : n;
100 memcpy(pdest + i, psrc + i, j - i);
107 #define asan_safe_memcpy(dest, src, n) memcpy((dest), (src), (n))
111 * @brief Uses shm_open to get a temporary shm, and returns its file descriptor.
113 int smpi_temp_shm_get()
115 constexpr unsigned INDEX_MASK = 0xffffffffUL;
116 static unsigned index = INDEX_MASK;
117 char shmname[32]; // cannot be longer than PSHMNAMLEN = 31 on macOS (shm_open raises ENAMETOOLONG otherwise)
120 unsigned limit = index;
122 index = (index + 1) & INDEX_MASK;
123 snprintf(shmname, sizeof(shmname), "/smpi-buffer-%016x", index);
124 fd = shm_open(shmname, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
125 } while (fd == -1 && errno == EEXIST && index != limit);
128 if (errno == EMFILE) {
129 xbt_die("Impossible to create temporary file for memory mapping: %s\n\
130 The shm_open() system call failed with the EMFILE error code (too many files). \n\n\
131 This means that you reached the system limits concerning the amount of files per process. \
132 This is not a surprise if you are trying to virtualize many processes on top of SMPI. \
133 Don't panic -- you should simply increase your system limits and try again. \n\n\
134 First, check what your limits are:\n\
135 cat /proc/sys/fs/file-max # Gives you the system-wide limit\n\
136 ulimit -Hn # Gives you the per process hard limit\n\
137 ulimit -Sn # Gives you the per process soft limit\n\
138 cat /proc/self/limits # Displays any per-process limitation (including the one given above)\n\n\
139 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. \
140 Ask the Internet about tutorials on how to increase the files limit such as: https://rtcamp.com/tutorials/linux/increase-open-files-limit/",
143 xbt_die("Impossible to create temporary file for memory mapping. shm_open: %s", strerror(errno));
145 XBT_DEBUG("Got temporary shm %s (fd = %d)", shmname, fd);
146 if (shm_unlink(shmname) < 0)
147 XBT_WARN("Could not early unlink %s. shm_unlink: %s", shmname, strerror(errno));
152 * @brief Mmap a region of size bytes from temporary shm with file descriptor fd.
154 void* smpi_temp_shm_mmap(int fd, size_t size)
157 xbt_assert(fstat(fd, &st) == 0, "Could not stat fd %d: %s", fd, strerror(errno));
158 xbt_assert(static_cast<off_t>(size) <= st.st_size || ftruncate(fd, static_cast<off_t>(size)) == 0,
159 "Could not truncate fd %d to %zu: %s", fd, size, strerror(errno));
160 void* mem = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
163 "Failed to map fd %d with size %zu: %s\n"
164 "If you are running a lot of ranks, you may be exceeding the amount of mappings allowed per process.\n"
165 "On Linux systems, change this value with sudo sysctl -w vm.max_map_count=newvalue (default value: 65536)\n"
166 "Please see https://simgrid.org/doc/latest/Configuring_SimGrid.html#configuring-the-user-code-virtualization for "
168 fd, size, strerror(errno));
172 /** Map a given SMPI privatization segment (make an SMPI process active)
174 * When doing a state restoration, the state of the restored variables might not be consistent with the state of the
175 * virtual memory. In this case, we have to change the data segment.
177 * If 'addr' is not null, only switch if it's an address from the data segment.
179 * Returns 'true' if the segment has to be switched (mmap privatization and 'addr' in data segment).
181 bool smpi_switch_data_segment(simgrid::s4u::ActorPtr actor, const void* addr)
183 if (smpi_cfg_privatization() != SmpiPrivStrategies::MMAP || smpi_data_exe_size == 0)
184 return false; // no need to switch
186 if (addr != nullptr &&
187 not(static_cast<const char*>(addr) >= smpi_data_exe_start &&
188 static_cast<const char*>(addr) < smpi_data_exe_start + smpi_data_exe_size))
189 return false; // no need to switch, addr is not concerned
191 static aid_t smpi_loaded_page = -1;
192 if (smpi_loaded_page == actor->get_pid()) // no need to switch, we've already loaded the one we want
193 return true; // return 'true' anyway
195 #if HAVE_PRIVATIZATION
196 // FIXME, cross-process support (mmap across process when necessary)
197 XBT_DEBUG("Switching data frame to the one of process %ld", actor->get_pid());
198 const simgrid::smpi::ActorExt* process = smpi_process_remote(actor);
199 int current = process->privatized_region()->file_descriptor;
200 xbt_assert(mmap(TOPAGE(smpi_data_exe_start), smpi_data_exe_size, PROT_RW, MAP_FIXED | MAP_SHARED, current, 0) ==
201 TOPAGE(smpi_data_exe_start),
202 "Couldn't map the new region (errno %d): %s", errno, strerror(errno));
203 smpi_loaded_page = actor->get_pid();
210 * @brief Makes a backup of the segment in memory that stores the global variables of a process.
211 * This backup is then used to initialize the global variables for every single
212 * process that is added, regardless of the progress of the simulation.
214 void smpi_backup_global_memory_segment()
216 #if HAVE_PRIVATIZATION
217 smpi_get_executable_global_size();
218 initial_vm_map.clear();
219 initial_vm_map.shrink_to_fit();
221 XBT_DEBUG("bss+data segment found : size %zu starting at %p", smpi_data_exe_size, smpi_data_exe_start);
223 if (smpi_data_exe_size == 0) { // no need to do anything as global variables don't exist
224 smpi_privatize_global_variables = SmpiPrivStrategies::NONE;
228 smpi_data_exe_copy = ::operator new(smpi_data_exe_size);
229 // Make a copy of the data segment. This clean copy is retained over the whole runtime
230 // of the simulation and can be used to initialize a dynamically added, new process.
231 asan_safe_memcpy(smpi_data_exe_copy, TOPAGE(smpi_data_exe_start), smpi_data_exe_size);
232 #else /* ! HAVE_PRIVATIZATION */
233 xbt_die("You are trying to use privatization on a system that does not support it. Don't.");
237 // Initializes the memory mapping for a single process and returns the privatization region
238 smpi_privatization_region_t smpi_init_global_memory_segment_process()
240 int file_descriptor = smpi_temp_shm_get();
242 // ask for a free region
243 void* address = smpi_temp_shm_mmap(file_descriptor, smpi_data_exe_size);
245 // initialize the values
246 asan_safe_memcpy(address, smpi_data_exe_copy, smpi_data_exe_size);
248 // store the address of the mapping for further switches
249 smpi_privatization_regions.emplace_back(s_smpi_privatization_region_t{address, file_descriptor});
251 return &smpi_privatization_regions.back();
254 void smpi_destroy_global_memory_segments(){
255 if (smpi_data_exe_size == 0) // no need to switch
257 #if HAVE_PRIVATIZATION
258 for (auto const& region : smpi_privatization_regions) {
259 if (munmap(region.address, smpi_data_exe_size) < 0)
260 XBT_WARN("Unmapping of fd %d failed: %s", region.file_descriptor, strerror(errno));
261 close(region.file_descriptor);
263 smpi_privatization_regions.clear();
264 ::operator delete(smpi_data_exe_copy);
268 static std::vector<unsigned char> sendbuffer;
269 static std::vector<unsigned char> recvbuffer;
271 //allocate a single buffer for all sends, growing it if needed
272 unsigned char* smpi_get_tmp_sendbuffer(size_t size)
274 if (not smpi_process()->replaying())
275 return new unsigned char[size];
276 // FIXME: a resize() may invalidate a previous pointer. Maybe we need to handle a queue of buffers with a reference
277 // counter. The same holds for smpi_get_tmp_recvbuffer.
278 if (sendbuffer.size() < size)
279 sendbuffer.resize(size);
280 return sendbuffer.data();
283 //allocate a single buffer for all recv
284 unsigned char* smpi_get_tmp_recvbuffer(size_t size)
286 if (not smpi_process()->replaying())
287 return new unsigned char[size];
288 if (recvbuffer.size() < size)
289 recvbuffer.resize(size);
290 return recvbuffer.data();
293 void smpi_free_tmp_buffer(const unsigned char* buf)
295 if (not smpi_process()->replaying())
299 void smpi_free_replay_tmp_buffers()
301 std::vector<unsigned char>().swap(sendbuffer);
302 std::vector<unsigned char>().swap(recvbuffer);