Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of https://framagit.org/simgrid/simgrid
[simgrid.git] / src / smpi / internals / smpi_global.cpp
1 /* Copyright (c) 2007-2021. 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 "mc/mc.h"
7 #include "simgrid/s4u/Engine.hpp"
8 #include "simgrid/plugins/file_system.h"
9 #include "smpi_coll.hpp"
10 #include "smpi_f2c.hpp"
11 #include "smpi_host.hpp"
12 #include "smpi_config.hpp"
13 #include "src/kernel/activity/CommImpl.hpp"
14 #include "src/simix/smx_private.hpp"
15 #include "src/smpi/include/smpi_actor.hpp"
16 #include "xbt/config.hpp"
17 #include "xbt/file.hpp"
18
19 #include <algorithm>
20 #include <array>
21 #include <boost/algorithm/string.hpp> /* split */
22 #include <boost/tokenizer.hpp>
23 #include <cerrno>
24 #include <cinttypes>
25 #include <cstdint> /* intmax_t */
26 #include <cstring> /* strerror */
27 #include <dlfcn.h>
28 #include <fcntl.h>
29 #include <fstream>
30 #include <sys/stat.h>
31
32 #if SG_HAVE_SENDFILE
33 #include <sys/sendfile.h>
34 #endif
35
36 #if HAVE_PAPI
37 #include "papi.h"
38 #endif
39
40 #if not defined(__APPLE__) && not defined(__HAIKU__)
41 #include <link.h>
42 #endif
43
44 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_kernel, smpi, "Logging specific to SMPI (kernel)");
45
46 #if SMPI_IFORT
47   extern "C" void for_rtl_init_ (int *, char **);
48   extern "C" void for_rtl_finish_ ();
49 #elif SMPI_FLANG
50   extern "C" void __io_set_argc(int);
51   extern "C" void __io_set_argv(char **);
52 #elif SMPI_GFORTRAN
53   extern "C" void _gfortran_set_args(int, char **);
54 #endif
55
56 /* RTLD_DEEPBIND is a bad idea of GNU ld that obviously does not exist on other platforms
57  * See https://www.akkadia.org/drepper/dsohowto.pdf
58  * and https://lists.freebsd.org/pipermail/freebsd-current/2016-March/060284.html
59 */
60 #if !RTLD_DEEPBIND || HAVE_SANITIZER_ADDRESS || HAVE_SANITIZER_THREAD
61 #define WANT_RTLD_DEEPBIND 0
62 #else
63 #define WANT_RTLD_DEEPBIND RTLD_DEEPBIND
64 #endif
65
66 #if HAVE_PAPI
67 std::string papi_default_config_name = "default";
68 std::map</* computation unit name */ std::string, papi_process_data, std::less<>> units2papi_setup;
69 #endif
70
71 std::unordered_map<std::string, double> location2speedup;
72
73 static int smpi_exit_status = 0;
74 extern double smpi_total_benched_time;
75 xbt_os_timer_t global_timer;
76 static std::vector<std::string> privatize_libs_paths;
77 /**
78  * Setting MPI_COMM_WORLD to MPI_COMM_UNINITIALIZED (it's a variable)
79  * is important because the implementation of MPI_Comm checks
80  * "this == MPI_COMM_UNINITIALIZED"? If yes, it uses smpi_process()->comm_world()
81  * instead of "this".
82  * This is basically how we only have one global variable but all processes have
83  * different communicators (the one their SMPI instance uses).
84  *
85  * See smpi_comm.cpp and the functions therein for details.
86  */
87 MPI_Comm MPI_COMM_WORLD = MPI_COMM_UNINITIALIZED;
88 // No instance gets manually created; check also the smpirun.in script as
89 // this default name is used there as well (when the <actor> tag is generated).
90 static const std::string smpi_default_instance_name("smpirun");
91 static simgrid::config::Flag<double> smpi_init_sleep(
92   "smpi/init", "Time to inject inside a call to MPI_Init", 0.0);
93
94 void (*smpi_comm_copy_data_callback)(simgrid::kernel::activity::CommImpl*, void*,
95                                      size_t) = &smpi_comm_copy_buffer_callback;
96
97 simgrid::smpi::ActorExt* smpi_process()
98 {
99   simgrid::s4u::ActorPtr me = simgrid::s4u::Actor::self();
100
101   if (me == nullptr) // This happens sometimes (eg, when linking against NS3 because it pulls openMPI...)
102     return nullptr;
103
104   return me->extension<simgrid::smpi::ActorExt>();
105 }
106
107 simgrid::smpi::ActorExt* smpi_process_remote(simgrid::s4u::ActorPtr actor)
108 {
109   if (actor.get() == nullptr)
110     return nullptr;
111   return actor->extension<simgrid::smpi::ActorExt>();
112 }
113
114 MPI_Comm smpi_process_comm_self(){
115   return smpi_process()->comm_self();
116 }
117
118 MPI_Info smpi_process_info_env(){
119   return smpi_process()->info_env();
120 }
121
122 void * smpi_process_get_user_data(){
123   return simgrid::s4u::Actor::self()->get_data();
124 }
125
126 void smpi_process_set_user_data(void *data){
127   simgrid::s4u::Actor::self()->set_data(data);
128 }
129
130 void smpi_comm_set_copy_data_callback(void (*callback) (smx_activity_t, void*, size_t))
131 {
132   static void (*saved_callback)(smx_activity_t, void*, size_t);
133   saved_callback               = callback;
134   smpi_comm_copy_data_callback = [](simgrid::kernel::activity::CommImpl* comm, void* buff, size_t size) {
135     saved_callback(comm, buff, size);
136   };
137 }
138
139 static void memcpy_private(void* dest, const void* src, const std::vector<std::pair<size_t, size_t>>& private_blocks)
140 {
141   for (auto const& block : private_blocks)
142     memcpy((uint8_t*)dest+block.first, (uint8_t*)src+block.first, block.second-block.first);
143 }
144
145 static void check_blocks(const std::vector<std::pair<size_t, size_t>>& private_blocks, size_t buff_size)
146 {
147   for (auto const& block : private_blocks)
148     xbt_assert(block.first <= block.second && block.second <= buff_size, "Oops, bug in shared malloc.");
149 }
150
151 static void smpi_cleanup_comm_after_copy(simgrid::kernel::activity::CommImpl* comm, void* buff){
152   if (comm->detached()) {
153     // if this is a detached send, the source buffer was duplicated by SMPI
154     // sender to make the original buffer available to the application ASAP
155     xbt_free(buff);
156     //It seems that the request is used after the call there this should be free somewhere else but where???
157     //xbt_free(comm->comm.src_data);// inside SMPI the request is kept inside the user data and should be free
158     comm->src_buff_ = nullptr;
159   }
160 }
161
162 void smpi_comm_copy_buffer_callback(simgrid::kernel::activity::CommImpl* comm, void* buff, size_t buff_size)
163 {
164   size_t src_offset                     = 0;
165   size_t dst_offset                     = 0;
166   std::vector<std::pair<size_t, size_t>> src_private_blocks;
167   std::vector<std::pair<size_t, size_t>> dst_private_blocks;
168   XBT_DEBUG("Copy the data over");
169   if(smpi_is_shared(buff, src_private_blocks, &src_offset)) {
170     src_private_blocks = shift_and_frame_private_blocks(src_private_blocks, src_offset, buff_size);
171     if (src_private_blocks.empty()) { // simple shared malloc ... return.
172       XBT_VERB("Sender is shared. Let's ignore it.");
173       smpi_cleanup_comm_after_copy(comm, buff);
174       return;
175     }
176   }
177   else {
178     src_private_blocks.clear();
179     src_private_blocks.emplace_back(0, buff_size);
180   }
181   if (smpi_is_shared((char*)comm->dst_buff_, dst_private_blocks, &dst_offset)) {
182     dst_private_blocks = shift_and_frame_private_blocks(dst_private_blocks, dst_offset, buff_size);
183     if (dst_private_blocks.empty()) { // simple shared malloc ... return.
184       XBT_VERB("Receiver is shared. Let's ignore it.");
185       smpi_cleanup_comm_after_copy(comm, buff);
186       return;
187     }
188   }
189   else {
190     dst_private_blocks.clear();
191     dst_private_blocks.emplace_back(0, buff_size);
192   }
193   check_blocks(src_private_blocks, buff_size);
194   check_blocks(dst_private_blocks, buff_size);
195   auto private_blocks = merge_private_blocks(src_private_blocks, dst_private_blocks);
196   check_blocks(private_blocks, buff_size);
197   void* tmpbuff=buff;
198   if ((smpi_cfg_privatization() == SmpiPrivStrategies::MMAP) &&
199       (static_cast<char*>(buff) >= smpi_data_exe_start) &&
200       (static_cast<char*>(buff) < smpi_data_exe_start + smpi_data_exe_size)) {
201     XBT_DEBUG("Privatization : We are copying from a zone inside global memory... Saving data to temp buffer !");
202     smpi_switch_data_segment(comm->src_actor_->get_iface());
203     tmpbuff = xbt_malloc(buff_size);
204     memcpy_private(tmpbuff, buff, private_blocks);
205   }
206
207   if ((smpi_cfg_privatization() == SmpiPrivStrategies::MMAP) &&
208       ((char*)comm->dst_buff_ >= smpi_data_exe_start) &&
209       ((char*)comm->dst_buff_ < smpi_data_exe_start + smpi_data_exe_size)) {
210     XBT_DEBUG("Privatization : We are copying to a zone inside global memory - Switch data segment");
211     smpi_switch_data_segment(comm->dst_actor_->get_iface());
212   }
213   XBT_DEBUG("Copying %zu bytes from %p to %p", buff_size, tmpbuff, comm->dst_buff_);
214   memcpy_private(comm->dst_buff_, tmpbuff, private_blocks);
215
216   smpi_cleanup_comm_after_copy(comm,buff);
217   if (tmpbuff != buff)
218     xbt_free(tmpbuff);
219 }
220
221 void smpi_comm_null_copy_buffer_callback(simgrid::kernel::activity::CommImpl*, void*, size_t)
222 {
223   /* nothing done in this version */
224 }
225
226 int smpi_enabled() {
227   return MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED;
228 }
229
230 static void smpi_init_papi()
231 {
232 #if HAVE_PAPI
233   // This map holds for each computation unit (such as "default" or "process1" etc.)
234   // the configuration as given by the user (counter data as a pair of (counter_name, counter_counter))
235   // and the (computed) event_set.
236
237   if (not smpi_cfg_papi_events_file().empty()) {
238     if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
239       XBT_ERROR("Could not initialize PAPI library; is it correctly installed and linked?"
240                 " Expected version is %u", PAPI_VER_CURRENT);
241
242     using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
243     boost::char_separator<char> separator_units(";");
244     std::string str = smpi_cfg_papi_events_file();
245     Tokenizer tokens(str, separator_units);
246
247     // Iterate over all the computational units. This could be processes, hosts, threads, ranks... You name it.
248     // I'm not exactly sure what we will support eventually, so I'll leave it at the general term "units".
249     for (auto const& unit_it : tokens) {
250       boost::char_separator<char> separator_events(":");
251       Tokenizer event_tokens(unit_it, separator_events);
252
253       int event_set = PAPI_NULL;
254       if (PAPI_create_eventset(&event_set) != PAPI_OK) {
255         // TODO: Should this let the whole simulation die?
256         XBT_CRITICAL("Could not create PAPI event set during init.");
257       }
258
259       // NOTE: We cannot use a map here, as we must obey the order of the counters
260       // This is important for PAPI: We need to map the values of counters back to the event_names (so, when PAPI_read()
261       // has finished)!
262       papi_counter_t counters2values;
263
264       // Iterate over all counters that were specified for this specific unit.
265       // Note that we need to remove the name of the unit (that could also be the "default" value), which always comes
266       // first. Hence, we start at ++(events.begin())!
267       for (Tokenizer::iterator events_it = ++(event_tokens.begin()); events_it != event_tokens.end(); ++events_it) {
268         int event_code   = PAPI_NULL;
269         auto* event_name = const_cast<char*>((*events_it).c_str());
270         if (PAPI_event_name_to_code(event_name, &event_code) != PAPI_OK) {
271           XBT_CRITICAL("Could not find PAPI event '%s'. Skipping.", event_name);
272           continue;
273         }
274         if (PAPI_add_event(event_set, event_code) != PAPI_OK) {
275           XBT_ERROR("Could not add PAPI event '%s'. Skipping.", event_name);
276           continue;
277         }
278         XBT_DEBUG("Successfully added PAPI event '%s' to the event set.", event_name);
279
280         counters2values.emplace_back(*events_it, 0LL);
281       }
282
283       std::string unit_name    = *(event_tokens.begin());
284       papi_process_data config = {.counter_data = std::move(counters2values), .event_set = event_set};
285
286       units2papi_setup.insert(std::make_pair(unit_name, std::move(config)));
287     }
288   }
289 #endif
290 }
291
292 using smpi_entry_point_type         = std::function<int(int argc, char* argv[])>;
293 using smpi_c_entry_point_type       = int (*)(int argc, char** argv);
294 using smpi_fortran_entry_point_type = void (*)();
295
296 template <typename F>
297 static int smpi_run_entry_point(const F& entry_point, const std::string& executable_path, std::vector<std::string> args)
298 {
299   // copy C strings, we need them writable
300   auto* args4argv = new std::vector<char*>(args.size());
301   std::transform(begin(args), end(args), begin(*args4argv), [](const std::string& s) { return xbt_strdup(s.c_str()); });
302
303   // set argv[0] to executable_path
304   xbt_free((*args4argv)[0]);
305   (*args4argv)[0] = xbt_strdup(executable_path.c_str());
306
307 #if !SMPI_IFORT
308   // take a copy of args4argv to keep reference of the allocated strings
309   const std::vector<char*> args2str(*args4argv);
310 #endif
311   int argc = args4argv->size();
312   args4argv->push_back(nullptr);
313   char** argv = args4argv->data();
314
315 #if SMPI_IFORT
316   for_rtl_init_ (&argc, argv);
317 #elif SMPI_FLANG
318   __io_set_argc(argc);
319   __io_set_argv(argv);
320 #elif SMPI_GFORTRAN
321   _gfortran_set_args(argc, argv);
322 #endif 
323   int res = entry_point(argc, argv);
324
325 #if SMPI_IFORT
326   for_rtl_finish_ ();
327 #else
328   for (char* s : args2str)
329     xbt_free(s);
330   delete args4argv;
331 #endif
332
333   if (res != 0){
334     XBT_WARN("SMPI process did not return 0. Return value : %d", res);
335     if (smpi_exit_status == 0)
336       smpi_exit_status = res;
337   }
338   return 0;
339 }
340
341
342 // TODO, remove the number of functions involved here
343 static smpi_entry_point_type smpi_resolve_function(void* handle)
344 {
345   auto* entry_point_fortran = reinterpret_cast<smpi_fortran_entry_point_type>(dlsym(handle, "user_main_"));
346   if (entry_point_fortran != nullptr) {
347     return [entry_point_fortran](int, char**) {
348       entry_point_fortran();
349       return 0;
350     };
351   }
352
353   auto* entry_point = reinterpret_cast<smpi_c_entry_point_type>(dlsym(handle, "main"));
354   if (entry_point != nullptr) {
355     return entry_point;
356   }
357
358   return smpi_entry_point_type();
359 }
360
361 static void smpi_copy_file(const std::string& src, const std::string& target, off_t fdin_size)
362 {
363   int fdin = open(src.c_str(), O_RDONLY);
364   xbt_assert(fdin >= 0, "Cannot read from %s. Please make sure that the file exists and is executable.", src.c_str());
365   XBT_ATTRIB_UNUSED int unlink_status = unlink(target.c_str());
366   xbt_assert(unlink_status == 0 || errno == ENOENT, "Failed to unlink file %s: %s", target.c_str(), strerror(errno));
367   int fdout = open(target.c_str(), O_CREAT | O_RDWR | O_EXCL, S_IRWXU);
368   xbt_assert(fdout >= 0, "Cannot write into %s: %s", target.c_str(), strerror(errno));
369
370   XBT_DEBUG("Copy %" PRIdMAX " bytes into %s", static_cast<intmax_t>(fdin_size), target.c_str());
371 #if SG_HAVE_SENDFILE
372   ssize_t sent_size = sendfile(fdout, fdin, nullptr, fdin_size);
373   if (sent_size == fdin_size) {
374     close(fdin);
375     close(fdout);
376     return;
377   } else if (sent_size != -1 || errno != ENOSYS) {
378     xbt_die("Error while copying %s: only %zd bytes copied instead of %" PRIdMAX " (errno: %d -- %s)", target.c_str(),
379             sent_size, static_cast<intmax_t>(fdin_size), errno, strerror(errno));
380   }
381 #endif
382   // If this point is reached, sendfile() actually is not available.  Copy file by hand.
383   std::vector<unsigned char> buf(1024 * 1024 * 4);
384   while (ssize_t got = read(fdin, buf.data(), buf.size())) {
385     if (got == -1) {
386       xbt_assert(errno == EINTR, "Cannot read from %s", src.c_str());
387     } else {
388       const unsigned char* p = buf.data();
389       ssize_t todo           = got;
390       while (ssize_t done = write(fdout, p, todo)) {
391         if (done == -1) {
392           xbt_assert(errno == EINTR, "Cannot write into %s", target.c_str());
393         } else {
394           p += done;
395           todo -= done;
396         }
397       }
398     }
399   }
400   close(fdin);
401   close(fdout);
402 }
403
404 #if not defined(__APPLE__) && not defined(__HAIKU__)
405 static int visit_libs(struct dl_phdr_info* info, size_t, void* data)
406 {
407   auto* libname    = static_cast<std::string*>(data);
408   std::string path = info->dlpi_name;
409   if (path.find(*libname) != std::string::npos) {
410     *libname = std::move(path);
411     return 1;
412   }
413   return 0;
414 }
415 #endif
416
417 static void smpi_init_privatization_dlopen(const std::string& executable)
418 {
419   // Prepare the copy of the binary (get its size)
420   struct stat fdin_stat;
421   stat(executable.c_str(), &fdin_stat);
422   off_t fdin_size         = fdin_stat.st_size;
423
424   std::string libnames = simgrid::config::get_value<std::string>("smpi/privatize-libs");
425   if (not libnames.empty()) {
426     // split option
427     std::vector<std::string> privatize_libs;
428     boost::split(privatize_libs, libnames, boost::is_any_of(";"));
429
430     for (auto const& libname : privatize_libs) {
431       // load the library once to add it to the local libs, to get the absolute path
432       void* libhandle = dlopen(libname.c_str(), RTLD_LAZY);
433       xbt_assert(libhandle != nullptr, 
434                       "Cannot dlopen %s - check your settings in smpi/privatize-libs", libname.c_str());
435       // get library name from path
436       std::string fullpath = libname;
437 #if not defined(__APPLE__) && not defined(__HAIKU__)
438       XBT_ATTRIB_UNUSED int dl_iterate_res = dl_iterate_phdr(visit_libs, &fullpath);
439       xbt_assert(dl_iterate_res != 0, "Can't find a linked %s - check your settings in smpi/privatize-libs",
440                  fullpath.c_str());
441       XBT_DEBUG("Extra lib to privatize '%s' found", fullpath.c_str());
442 #else
443       xbt_die("smpi/privatize-libs is not (yet) compatible with OSX nor with Haiku");
444 #endif
445       privatize_libs_paths.emplace_back(std::move(fullpath));
446       dlclose(libhandle);
447     }
448   }
449
450   simgrid::s4u::Engine::get_instance()->register_default([executable, fdin_size](std::vector<std::string> args) {
451     return std::function<void()>([executable, fdin_size, args] {
452       static std::size_t rank = 0;
453       // Copy the dynamic library:
454       simgrid::xbt::Path path(executable);
455       std::string target_executable = simgrid::config::get_value<std::string>("smpi/tmpdir") + "/" +
456           path.get_base_name() + "_" + std::to_string(getpid()) + "_" + std::to_string(rank) + ".so";
457
458       smpi_copy_file(executable, target_executable, fdin_size);
459       // if smpi/privatize-libs is set, duplicate pointed lib and link each executable copy to a different one.
460       std::vector<std::string> target_libs;
461       for (auto const& libpath : privatize_libs_paths) {
462         // if we were given a full path, strip it
463         size_t index = libpath.find_last_of("/\\");
464         std::string libname;
465         if (index != std::string::npos)
466           libname = libpath.substr(index + 1);
467
468         if (not libname.empty()) {
469           // load the library to add it to the local libs, to get the absolute path
470           struct stat fdin_stat2;
471           stat(libpath.c_str(), &fdin_stat2);
472           off_t fdin_size2 = fdin_stat2.st_size;
473
474           // Copy the dynamic library, the new name must be the same length as the old one
475           // just replace the name with 7 digits for the rank and the rest of the name.
476           auto pad                   = std::min<unsigned>(7, libname.length());
477           std::string target_libname = std::string(pad - std::to_string(rank).length(), '0') + std::to_string(rank) + libname.substr(pad);
478           std::string target_lib = simgrid::config::get_value<std::string>("smpi/tmpdir") + "/" + target_libname;
479           target_libs.push_back(target_lib);
480           XBT_DEBUG("copy lib %s to %s, with size %lld", libpath.c_str(), target_lib.c_str(), (long long)fdin_size2);
481           smpi_copy_file(libpath, target_lib, fdin_size2);
482
483           std::string sedcommand = "sed -i -e 's/" + libname + "/" + target_libname + "/g' " + target_executable;
484           int status             = system(sedcommand.c_str());
485           xbt_assert(status == 0, "error while applying sed command %s \n", sedcommand.c_str());
486         }
487       }
488
489       rank++;
490       // Load the copy and resolve the entry point:
491       void* handle    = dlopen(target_executable.c_str(), RTLD_LAZY | RTLD_LOCAL | WANT_RTLD_DEEPBIND);
492       int saved_errno = errno;
493       if (not simgrid::config::get_value<bool>("smpi/keep-temps")) {
494         unlink(target_executable.c_str());
495         for (const std::string& target_lib : target_libs)
496           unlink(target_lib.c_str());
497       }
498       xbt_assert(handle != nullptr,
499                  "dlopen failed: %s (errno: %d -- %s).\nError: Did you compile the program with a SMPI-specific "
500                  "compiler (spmicc or friends)?",
501                  dlerror(), saved_errno, strerror(saved_errno));
502
503       smpi_entry_point_type entry_point = smpi_resolve_function(handle);
504       xbt_assert(entry_point, "Could not resolve entry point");
505       smpi_run_entry_point(entry_point, executable, args);
506     });
507   });
508 }
509
510 static void smpi_init_privatization_no_dlopen(const std::string& executable)
511 {
512   if (smpi_cfg_privatization() == SmpiPrivStrategies::MMAP)
513     smpi_prepare_global_memory_segment();
514
515   // Load the dynamic library and resolve the entry point:
516   void* handle = dlopen(executable.c_str(), RTLD_LAZY | RTLD_LOCAL);
517   xbt_assert(handle != nullptr, "dlopen failed for %s: %s (errno: %d -- %s)", executable.c_str(), dlerror(), errno,
518              strerror(errno));
519   smpi_entry_point_type entry_point = smpi_resolve_function(handle);
520   xbt_assert(entry_point, "main not found in %s", executable.c_str());
521
522   if (smpi_cfg_privatization() == SmpiPrivStrategies::MMAP)
523     smpi_backup_global_memory_segment();
524
525   // Execute the same entry point for each simulated process:
526   simgrid::s4u::Engine::get_instance()->register_default([entry_point, executable](std::vector<std::string> args) {
527     return std::function<void()>(
528         [entry_point, executable, args] { smpi_run_entry_point(entry_point, executable, args); });
529   });
530 }
531
532 int smpi_main(const char* executable, int argc, char* argv[])
533 {
534   if (getenv("SMPI_PRETEND_CC") != nullptr) {
535     /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
536      * configuration tools */
537     return 0;
538   }
539   
540   SMPI_switch_data_segment = &smpi_switch_data_segment;
541   smpi_init_options();
542   simgrid::instr::init();
543   SIMIX_global_init(&argc, argv);
544
545   auto engine              = simgrid::s4u::Engine::get_instance();
546
547   sg_storage_file_system_init();
548   // parse the platform file: get the host list
549   engine->load_platform(argv[1]);
550   SIMIX_comm_set_copy_data_callback(smpi_comm_copy_buffer_callback);
551
552   if (smpi_cfg_privatization() == SmpiPrivStrategies::DLOPEN)
553     smpi_init_privatization_dlopen(executable);
554   else
555     smpi_init_privatization_no_dlopen(executable);
556
557   simgrid::smpi::colls::set_collectives();
558   simgrid::smpi::colls::smpi_coll_cleanup_callback = nullptr;
559   
560   SMPI_init();
561
562   /* This is a ... heavy way to count the MPI ranks */
563   int rank_counts = 0;
564   simgrid::s4u::Actor::on_creation.connect([&rank_counts](const simgrid::s4u::Actor& actor) {
565     if (not actor.is_daemon())
566       rank_counts++;
567   });
568   engine->load_deployment(argv[2]);
569
570   SMPI_app_instance_register(smpi_default_instance_name.c_str(), nullptr, rank_counts);
571   MPI_COMM_WORLD = *smpi_deployment_comm_world(smpi_default_instance_name);
572
573   /* Clean IO before the run */
574   fflush(stdout);
575   fflush(stderr);
576
577   if (MC_is_active()) {
578     MC_run();
579   } else {
580     SIMIX_run();
581
582     xbt_os_walltimer_stop(global_timer);
583     if (simgrid::config::get_value<bool>("smpi/display-timing")) {
584       double global_time = xbt_os_timer_elapsed(global_timer);
585       XBT_INFO("Simulated time: %g seconds. \n\n"
586           "The simulation took %g seconds (after parsing and platform setup)\n"
587           "%g seconds were actual computation of the application",
588           SIMIX_get_clock(), global_time , smpi_total_benched_time);
589
590       if (smpi_total_benched_time/global_time>=0.75)
591       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
592       "You may want to use sampling functions or trace replay to reduce this.");
593     }
594   }
595   SMPI_finalize();
596
597   return smpi_exit_status;
598 }
599
600 // Called either directly from the user code, or from the code called by smpirun
601 void SMPI_init(){
602   smpi_init_options();
603   simgrid::s4u::Actor::on_creation.connect([](simgrid::s4u::Actor& actor) {
604     if (not actor.is_daemon())
605       actor.extension_set<simgrid::smpi::ActorExt>(new simgrid::smpi::ActorExt(&actor));
606   });
607   simgrid::s4u::Host::on_creation.connect(
608       [](simgrid::s4u::Host& host) { host.extension_set(new simgrid::smpi::Host(&host)); });
609   for (auto const& host : simgrid::s4u::Engine::get_instance()->get_all_hosts())
610     host->extension_set(new simgrid::smpi::Host(host));
611
612   if (not MC_is_active()) {
613     global_timer = xbt_os_timer_new();
614     xbt_os_walltimer_start(global_timer);
615   }
616   smpi_init_papi();
617   smpi_check_options();
618 }
619
620 void SMPI_finalize()
621 {
622   smpi_bench_destroy();
623   smpi_shared_destroy();
624   smpi_deployment_cleanup_instances();
625
626   if (simgrid::smpi::colls::smpi_coll_cleanup_callback != nullptr)
627     simgrid::smpi::colls::smpi_coll_cleanup_callback();
628
629   MPI_COMM_WORLD = MPI_COMM_NULL;
630
631   if (not MC_is_active()) {
632     xbt_os_timer_free(global_timer);
633   }
634
635   if (smpi_cfg_privatization() == SmpiPrivStrategies::MMAP)
636     smpi_destroy_global_memory_segments();
637   if (simgrid::smpi::F2C::lookup() != nullptr)
638     simgrid::smpi::F2C::delete_lookup();
639 }
640
641 void smpi_mpi_init() {
642   smpi_init_fortran_types();
643   if(smpi_init_sleep > 0)
644     simgrid::s4u::this_actor::sleep_for(smpi_init_sleep);
645 }
646
647 void SMPI_thread_create() {
648   TRACE_smpi_init(simgrid::s4u::this_actor::get_pid(), __func__);
649 }