Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Further cleanups in SMPI includes
[simgrid.git] / src / smpi / smpi_global.cpp
1 /* Copyright (c) 2007-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 #include "mc/mc.h"
7 #include "simgrid/s4u/Mailbox.hpp"
8 #include "simgrid/s4u/Host.hpp"
9 #include "src/msg/msg_private.h"
10 #include "src/simix/smx_private.h"
11 #include "src/surf/surf_interface.hpp"
12 #include "src/smpi/SmpiHost.hpp"
13 #include "xbt/config.hpp"
14 #include "src/smpi/private.h"
15 #include "smpi/smpi_shared_malloc.hpp"
16 #include "src/smpi/smpi_coll.hpp"
17 #include "src/smpi/smpi_comm.hpp"
18 #include "src/smpi/smpi_group.hpp"
19 #include "src/smpi/smpi_info.hpp"
20 #include "src/smpi/smpi_process.hpp"
21
22 #include <dlfcn.h>
23 #include <fcntl.h>
24 #include <sys/stat.h>
25 #include <float.h> /* DBL_MAX */
26 #include <fstream>
27
28 #if HAVE_SENDFILE
29 #include <sys/sendfile.h>
30 #endif
31
32 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_kernel, smpi, "Logging specific to SMPI (kernel)");
33 #include <boost/tokenizer.hpp>
34 #include <boost/algorithm/string.hpp> /* trim_right / trim_left */
35
36 #ifndef RTLD_DEEPBIND
37 /* RTLD_DEEPBIND is a bad idea of GNU ld that obviously does not exist on other platforms
38  * See https://www.akkadia.org/drepper/dsohowto.pdf
39  * and https://lists.freebsd.org/pipermail/freebsd-current/2016-March/060284.html
40 */
41 #define RTLD_DEEPBIND 0
42 #endif
43
44 #if HAVE_PAPI
45 #include "papi.h"
46 const char* papi_default_config_name = "default";
47
48 struct papi_process_data {
49   papi_counter_t counter_data;
50   int event_set;
51 };
52
53 #endif
54 std::unordered_map<std::string, double> location2speedup;
55
56 simgrid::smpi::Process **process_data = nullptr;
57 int process_count = 0;
58 int smpi_universe_size = 0;
59 int* index_to_process_data = nullptr;
60 extern double smpi_total_benched_time;
61 xbt_os_timer_t global_timer;
62 MPI_Comm MPI_COMM_WORLD = MPI_COMM_UNINITIALIZED;
63 MPI_Errhandler *MPI_ERRORS_RETURN = nullptr;
64 MPI_Errhandler *MPI_ERRORS_ARE_FATAL = nullptr;
65 MPI_Errhandler *MPI_ERRHANDLER_NULL = nullptr;
66 static simgrid::config::Flag<double> smpi_wtime_sleep(
67   "smpi/wtime", "Minimum time to inject inside a call to MPI_Wtime", 0.0);
68 static simgrid::config::Flag<double> smpi_init_sleep(
69   "smpi/init", "Time to inject inside a call to MPI_Init", 0.0);
70
71 void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t) = &smpi_comm_copy_buffer_callback;
72
73 int smpi_process_count()
74 {
75   return process_count;
76 }
77
78 simgrid::smpi::Process* smpi_process()
79 {
80   smx_actor_t me = SIMIX_process_self();
81   if (me == nullptr) // This happens sometimes (eg, when linking against NS3 because it pulls openMPI...)
82     return nullptr;
83   simgrid::MsgActorExt* msgExt = static_cast<simgrid::MsgActorExt*>(me->data);
84   return static_cast<simgrid::smpi::Process*>(msgExt->data);
85 }
86
87 simgrid::smpi::Process* smpi_process_remote(int index)
88 {
89   return process_data[index_to_process_data[index]];
90 }
91
92 MPI_Comm smpi_process_comm_self(){
93   return smpi_process()->comm_self();
94 }
95
96 void smpi_process_init(int *argc, char ***argv){
97   simgrid::smpi::Process::init(argc, argv);
98 }
99
100 int smpi_process_index(){
101   return smpi_process()->index();
102 }
103
104 void * smpi_process_get_user_data(){
105   return smpi_process()->get_user_data();
106 }
107
108 void smpi_process_set_user_data(void *data){
109   return smpi_process()->set_user_data(data);
110 }
111
112
113 int smpi_global_size()
114 {
115   char *value = getenv("SMPI_GLOBAL_SIZE");
116   xbt_assert(value,"Please set env var SMPI_GLOBAL_SIZE to the expected number of processes.");
117
118   return xbt_str_parse_int(value, "SMPI_GLOBAL_SIZE contains a non-numerical value: %s");
119 }
120
121 void smpi_comm_set_copy_data_callback(void (*callback) (smx_activity_t, void*, size_t))
122 {
123   smpi_comm_copy_data_callback = callback;
124 }
125
126 static void print(std::vector<std::pair<size_t, size_t>> vec) {
127   std::fprintf(stderr, "{");
128   for (auto elt : vec) {
129     std::fprintf(stderr, "(0x%zx, 0x%zx),", elt.first, elt.second);
130     }
131     std::fprintf(stderr, "}\n");
132 }
133 static void memcpy_private(void* dest, const void* src, std::vector<std::pair<size_t, size_t>>& private_blocks)
134 {
135   for(auto block : private_blocks) {
136     memcpy((uint8_t*)dest+block.first, (uint8_t*)src+block.first, block.second-block.first);
137   }
138 }
139
140 static void check_blocks(std::vector<std::pair<size_t, size_t>> &private_blocks, size_t buff_size) {
141   for(auto block : private_blocks) {
142     xbt_assert(block.first <= block.second && block.second <= buff_size, "Oops, bug in shared malloc.");
143   }
144 }
145
146 void smpi_comm_copy_buffer_callback(smx_activity_t synchro, void *buff, size_t buff_size)
147 {
148   simgrid::kernel::activity::Comm *comm = dynamic_cast<simgrid::kernel::activity::Comm*>(synchro);
149   int src_shared                        = 0;
150   int dst_shared                        = 0;
151   size_t src_offset                     = 0;
152   size_t dst_offset                     = 0;
153   std::vector<std::pair<size_t, size_t>> src_private_blocks;
154   std::vector<std::pair<size_t, size_t>> dst_private_blocks;
155   XBT_DEBUG("Copy the data over");
156   if((src_shared=smpi_is_shared(buff, src_private_blocks, &src_offset))) {
157     XBT_DEBUG("Sender %p is shared. Let's ignore it.", buff);
158     src_private_blocks = shift_and_frame_private_blocks(src_private_blocks, src_offset, buff_size);
159   }
160   else {
161     src_private_blocks.clear();
162     src_private_blocks.push_back(std::make_pair(0, buff_size));
163   }
164   if((dst_shared=smpi_is_shared((char*)comm->dst_buff, dst_private_blocks, &dst_offset))) {
165     XBT_DEBUG("Receiver %p is shared. Let's ignore it.", (char*)comm->dst_buff);
166     dst_private_blocks = shift_and_frame_private_blocks(dst_private_blocks, dst_offset, buff_size);
167   }
168   else {
169     dst_private_blocks.clear();
170     dst_private_blocks.push_back(std::make_pair(0, buff_size));
171   }
172   check_blocks(src_private_blocks, buff_size);
173   check_blocks(dst_private_blocks, buff_size);
174   auto private_blocks = merge_private_blocks(src_private_blocks, dst_private_blocks);
175   check_blocks(private_blocks, buff_size);
176   void* tmpbuff=buff;
177   if((smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) && (static_cast<char*>(buff) >= smpi_start_data_exe)
178       && (static_cast<char*>(buff) < smpi_start_data_exe + smpi_size_data_exe )
179     ){
180        XBT_DEBUG("Privatization : We are copying from a zone inside global memory... Saving data to temp buffer !");
181
182        smpi_switch_data_segment(
183            (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->src_proc->data)->data))->index()));
184        tmpbuff = static_cast<void*>(xbt_malloc(buff_size));
185        memcpy_private(tmpbuff, buff, private_blocks);
186   }
187
188   if((smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) && ((char*)comm->dst_buff >= smpi_start_data_exe)
189       && ((char*)comm->dst_buff < smpi_start_data_exe + smpi_size_data_exe )){
190        XBT_DEBUG("Privatization : We are copying to a zone inside global memory - Switch data segment");
191        smpi_switch_data_segment(
192            (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->dst_proc->data)->data))->index()));
193   }
194   XBT_DEBUG("Copying %zu bytes from %p to %p", buff_size, tmpbuff,comm->dst_buff);
195   memcpy_private(comm->dst_buff, tmpbuff, private_blocks);
196
197   if (comm->detached) {
198     // if this is a detached send, the source buffer was duplicated by SMPI
199     // sender to make the original buffer available to the application ASAP
200     xbt_free(buff);
201     //It seems that the request is used after the call there this should be free somewhere else but where???
202     //xbt_free(comm->comm.src_data);// inside SMPI the request is kept inside the user data and should be free
203     comm->src_buff = nullptr;
204   }
205   if(tmpbuff!=buff)xbt_free(tmpbuff);
206
207 }
208
209 void smpi_comm_null_copy_buffer_callback(smx_activity_t comm, void *buff, size_t buff_size)
210 {
211   /* nothing done in this version */
212 }
213
214 static void smpi_check_options(){
215   //check correctness of MPI parameters
216
217    xbt_assert(xbt_cfg_get_int("smpi/async-small-thresh") <= xbt_cfg_get_int("smpi/send-is-detached-thresh"));
218
219    if (xbt_cfg_is_default_value("smpi/host-speed")) {
220      XBT_INFO("You did not set the power of the host running the simulation.  "
221               "The timings will certainly not be accurate.  "
222               "Use the option \"--cfg=smpi/host-speed:<flops>\" to set its value."
223               "Check http://simgrid.org/simgrid/latest/doc/options.html#options_smpi_bench for more information.");
224    }
225
226    xbt_assert(xbt_cfg_get_double("smpi/cpu-threshold") >=0,
227        "The 'smpi/cpu-threshold' option cannot have negative values [anymore]. If you want to discard "
228        "the simulation of any computation, please use 'smpi/simulate-computation:no' instead.");
229 }
230
231 int smpi_enabled() {
232   return process_data != nullptr;
233 }
234
235 void smpi_global_init()
236 {
237   MPI_Group group;
238
239   if (!MC_is_active()) {
240     global_timer = xbt_os_timer_new();
241     xbt_os_walltimer_start(global_timer);
242   }
243
244   if (xbt_cfg_get_string("smpi/comp-adjustment-file")[0] != '\0') { 
245     std::string filename {xbt_cfg_get_string("smpi/comp-adjustment-file")};
246     std::ifstream fstream(filename);
247     if (!fstream.is_open()) {
248       xbt_die("Could not open file %s. Does it exist?", filename.c_str());
249     }
250
251     std::string line;
252     typedef boost::tokenizer< boost::escaped_list_separator<char>> Tokenizer;
253     std::getline(fstream, line); // Skip the header line
254     while (std::getline(fstream, line)) {
255       Tokenizer tok(line);
256       Tokenizer::iterator it  = tok.begin();
257       Tokenizer::iterator end = std::next(tok.begin());
258
259       std::string location = *it;
260       boost::trim(location);
261       location2speedup.insert(std::pair<std::string, double>(location, std::stod(*end)));
262     }
263   }
264
265 #if HAVE_PAPI
266   // This map holds for each computation unit (such as "default" or "process1" etc.)
267   // the configuration as given by the user (counter data as a pair of (counter_name, counter_counter))
268   // and the (computed) event_set.
269   std::map</* computation unit name */ std::string, papi_process_data> units2papi_setup;
270
271   if (xbt_cfg_get_string("smpi/papi-events")[0] != '\0') {
272     if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
273       XBT_ERROR("Could not initialize PAPI library; is it correctly installed and linked?"
274                 " Expected version is %i",
275                 PAPI_VER_CURRENT);
276
277     typedef boost::tokenizer<boost::char_separator<char>> Tokenizer;
278     boost::char_separator<char> separator_units(";");
279     std::string str = std::string(xbt_cfg_get_string("smpi/papi-events"));
280     Tokenizer tokens(str, separator_units);
281
282     // Iterate over all the computational units. This could be
283     // processes, hosts, threads, ranks... You name it. I'm not exactly
284     // sure what we will support eventually, so I'll leave it at the
285     // general term "units".
286     for (auto& unit_it : tokens) {
287       boost::char_separator<char> separator_events(":");
288       Tokenizer event_tokens(unit_it, separator_events);
289
290       int event_set = PAPI_NULL;
291       if (PAPI_create_eventset(&event_set) != PAPI_OK) {
292         // TODO: Should this let the whole simulation die?
293         XBT_CRITICAL("Could not create PAPI event set during init.");
294       }
295
296       // NOTE: We cannot use a map here, as we must obey the order of the counters
297       // This is important for PAPI: We need to map the values of counters back
298       // to the event_names (so, when PAPI_read() has finished)!
299       papi_counter_t counters2values;
300
301       // Iterate over all counters that were specified for this specific
302       // unit.
303       // Note that we need to remove the name of the unit
304       // (that could also be the "default" value), which always comes first.
305       // Hence, we start at ++(events.begin())!
306       for (Tokenizer::iterator events_it = ++(event_tokens.begin()); events_it != event_tokens.end(); events_it++) {
307
308         int event_code   = PAPI_NULL;
309         char* event_name = const_cast<char*>((*events_it).c_str());
310         if (PAPI_event_name_to_code(event_name, &event_code) == PAPI_OK) {
311           if (PAPI_add_event(event_set, event_code) != PAPI_OK) {
312             XBT_ERROR("Could not add PAPI event '%s'. Skipping.", event_name);
313             continue;
314           } else {
315             XBT_DEBUG("Successfully added PAPI event '%s' to the event set.", event_name);
316           }
317         } else {
318           XBT_CRITICAL("Could not find PAPI event '%s'. Skipping.", event_name);
319           continue;
320         }
321
322         counters2values.push_back(
323             // We cannot just pass *events_it, as this is of type const basic_string
324             std::make_pair<std::string, long long>(std::string(*events_it), 0));
325       }
326
327       std::string unit_name    = *(event_tokens.begin());
328       papi_process_data config = {.counter_data = std::move(counters2values), .event_set = event_set};
329
330       units2papi_setup.insert(std::make_pair(unit_name, std::move(config)));
331     }
332   }
333 #endif
334
335   int smpirun = 0;
336   msg_bar_t finalization_barrier = nullptr;
337   if (process_count == 0){
338     process_count = SIMIX_process_count();
339     smpirun=1;
340     finalization_barrier = MSG_barrier_init(process_count);
341   }
342   smpi_universe_size = process_count;
343   process_data       = new simgrid::smpi::Process*[process_count];
344   for (int i = 0; i < process_count; i++) {
345     process_data[i] = new simgrid::smpi::Process(i, finalization_barrier);
346   }
347   //if the process was launched through smpirun script we generate a global mpi_comm_world
348   //if not, we let MPI_COMM_NULL, and the comm world will be private to each mpi instance
349   if (smpirun) {
350     group = new  simgrid::smpi::Group(process_count);
351     MPI_COMM_WORLD = new  simgrid::smpi::Comm(group, nullptr);
352     MPI_Attr_put(MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, reinterpret_cast<void *>(process_count));
353
354     for (int i = 0; i < process_count; i++)
355       group->set_mapping(i, i);
356   }
357 }
358
359 void smpi_global_destroy()
360 {
361   int count = smpi_process_count();
362
363   smpi_bench_destroy();
364   smpi_shared_destroy();
365   if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
366       delete MPI_COMM_WORLD->group();
367       MSG_barrier_destroy(process_data[0]->finalization_barrier());
368   }else{
369       smpi_deployment_cleanup_instances();
370   }
371   for (int i = 0; i < count; i++) {
372     if(process_data[i]->comm_self()!=MPI_COMM_NULL){
373       simgrid::smpi::Comm::destroy(process_data[i]->comm_self());
374     }
375     if(process_data[i]->comm_intra()!=MPI_COMM_NULL){
376       simgrid::smpi::Comm::destroy(process_data[i]->comm_intra());
377     }
378     xbt_os_timer_free(process_data[i]->timer());
379     xbt_mutex_destroy(process_data[i]->mailboxes_mutex());
380     delete process_data[i];
381   }
382   delete[] process_data;
383   process_data = nullptr;
384
385   if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
386     MPI_COMM_WORLD->cleanup_smp();
387     MPI_COMM_WORLD->cleanup_attr<simgrid::smpi::Comm>();
388     if(simgrid::smpi::Colls::smpi_coll_cleanup_callback!=nullptr)
389       simgrid::smpi::Colls::smpi_coll_cleanup_callback();
390     delete MPI_COMM_WORLD;
391   }
392
393   MPI_COMM_WORLD = MPI_COMM_NULL;
394
395   if (!MC_is_active()) {
396     xbt_os_timer_free(global_timer);
397   }
398
399   xbt_free(index_to_process_data);
400   if(smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP)
401     smpi_destroy_global_memory_segments();
402   smpi_free_static();
403 }
404
405 extern "C" {
406
407 static void smpi_init_logs(){
408
409   /* Connect log categories.  See xbt/log.c */
410
411   XBT_LOG_CONNECT(smpi);  /* Keep this line as soon as possible in this function: xbt_log_appender_file.c depends on it
412                              DO NOT connect this in XBT or so, or it will be useless to xbt_log_appender_file.c */
413   XBT_LOG_CONNECT(instr_smpi);
414   XBT_LOG_CONNECT(smpi_bench);
415   XBT_LOG_CONNECT(smpi_coll);
416   XBT_LOG_CONNECT(smpi_colls);
417   XBT_LOG_CONNECT(smpi_comm);
418   XBT_LOG_CONNECT(smpi_datatype);
419   XBT_LOG_CONNECT(smpi_dvfs);
420   XBT_LOG_CONNECT(smpi_group);
421   XBT_LOG_CONNECT(smpi_kernel);
422   XBT_LOG_CONNECT(smpi_mpi);
423   XBT_LOG_CONNECT(smpi_memory);
424   XBT_LOG_CONNECT(smpi_op);
425   XBT_LOG_CONNECT(smpi_pmpi);
426   XBT_LOG_CONNECT(smpi_request);
427   XBT_LOG_CONNECT(smpi_replay);
428   XBT_LOG_CONNECT(smpi_rma);
429   XBT_LOG_CONNECT(smpi_shared);
430   XBT_LOG_CONNECT(smpi_utils);
431 }
432 }
433
434 static void smpi_init_options(){
435     //return if already called
436     if (smpi_cpu_threshold > -1)
437       return;
438     simgrid::smpi::Colls::set_collectives();
439     simgrid::smpi::Colls::smpi_coll_cleanup_callback=nullptr;
440     smpi_cpu_threshold = xbt_cfg_get_double("smpi/cpu-threshold");
441     smpi_host_speed = xbt_cfg_get_double("smpi/host-speed");
442     const char* smpi_privatize_option               = xbt_cfg_get_string("smpi/privatization");
443     if (std::strcmp(smpi_privatize_option, "no") == 0)
444       smpi_privatize_global_variables = SMPI_PRIVATIZE_NONE;
445     else if (std::strcmp(smpi_privatize_option, "yes") == 0)
446       smpi_privatize_global_variables = SMPI_PRIVATIZE_DEFAULT;
447     else if (std::strcmp(smpi_privatize_option, "mmap") == 0)
448       smpi_privatize_global_variables = SMPI_PRIVATIZE_MMAP;
449     else if (std::strcmp(smpi_privatize_option, "dlopen") == 0)
450       smpi_privatize_global_variables = SMPI_PRIVATIZE_DLOPEN;
451
452     // Some compatibility stuff:
453     else if (std::strcmp(smpi_privatize_option, "1") == 0)
454       smpi_privatize_global_variables = SMPI_PRIVATIZE_DEFAULT;
455     else if (std::strcmp(smpi_privatize_option, "0") == 0)
456       smpi_privatize_global_variables = SMPI_PRIVATIZE_NONE;
457
458     else
459       xbt_die("Invalid value for smpi/privatization: '%s'", smpi_privatize_option);
460
461 #if defined(__FreeBSD__)
462     if (smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) {
463       XBT_INFO("Mixing mmap privatization is broken on FreeBSD, switching to dlopen privatization instead.");
464       smpi_privatize_global_variables = SMPI_PRIVATIZE_DLOPEN;
465     }
466 #endif
467
468     if (smpi_cpu_threshold < 0)
469       smpi_cpu_threshold = DBL_MAX;
470
471     char* val = xbt_cfg_get_string("smpi/shared-malloc");
472     if (!strcasecmp(val, "yes") || !strcmp(val, "1") || !strcasecmp(val, "on") || !strcasecmp(val, "global")) {
473       smpi_cfg_shared_malloc = shmalloc_global;
474     } else if (!strcasecmp(val, "local")) {
475       smpi_cfg_shared_malloc = shmalloc_local;
476     } else if (!strcasecmp(val, "no") || !strcmp(val, "0") || !strcasecmp(val, "off")) {
477       smpi_cfg_shared_malloc = shmalloc_none;
478     } else {
479       xbt_die("Invalid value '%s' for option smpi/shared-malloc. Possible values: 'on' or 'global', 'local', 'off'",
480               val);
481     }
482 }
483
484 typedef std::function<int(int argc, char *argv[])> smpi_entry_point_type;
485 typedef int (* smpi_c_entry_point_type)(int argc, char **argv);
486 typedef void (*smpi_fortran_entry_point_type)();
487
488 static int smpi_run_entry_point(smpi_entry_point_type entry_point, std::vector<std::string> args)
489 {
490   const int argc = args.size();
491   std::unique_ptr<char*[]> argv(new char*[argc + 1]);
492   for (int i = 0; i != argc; ++i)
493     argv[i] = args[i].empty() ? const_cast<char*>(""): &args[i].front();
494   argv[argc] = nullptr;
495
496   int res = entry_point(argc, argv.get());
497   if (res != 0){
498     XBT_WARN("SMPI process did not return 0. Return value : %d", res);
499     smpi_process()->set_return_value(res);
500   }
501   return 0;
502 }
503
504 // TODO, remove the number of functions involved here
505 static smpi_entry_point_type smpi_resolve_function(void* handle)
506 {
507   smpi_fortran_entry_point_type entry_point_fortran = (smpi_fortran_entry_point_type)dlsym(handle, "user_main_");
508   if (entry_point_fortran != nullptr) {
509     return [entry_point_fortran](int argc, char** argv) {
510       smpi_process_init(&argc, &argv);
511       entry_point_fortran();
512       return 0;
513     };
514   }
515
516   smpi_c_entry_point_type entry_point = (smpi_c_entry_point_type)dlsym(handle, "main");
517   if (entry_point != nullptr) {
518     return entry_point;
519   }
520
521   return smpi_entry_point_type();
522 }
523
524 int smpi_main(const char* executable, int argc, char *argv[])
525 {
526   srand(SMPI_RAND_SEED);
527
528   if (getenv("SMPI_PRETEND_CC") != nullptr) {
529     /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
530      * configuration tools */
531     return 0;
532   }
533
534   TRACE_global_init(&argc, argv);
535
536   SIMIX_global_init(&argc, argv);
537   MSG_init(&argc,argv);
538
539   SMPI_switch_data_segment = &smpi_switch_data_segment;
540
541   simgrid::s4u::Host::onCreation.connect([](simgrid::s4u::Host& host) {
542     host.extension_set(new simgrid::smpi::SmpiHost(&host));
543   });
544
545   // parse the platform file: get the host list
546   SIMIX_create_environment(argv[1]);
547   SIMIX_comm_set_copy_data_callback(smpi_comm_copy_buffer_callback);
548
549   static std::size_t rank = 0;
550
551   smpi_init_options();
552
553   if (smpi_privatize_global_variables == SMPI_PRIVATIZE_DLOPEN) {
554
555     std::string executable_copy = executable;
556
557     // Prepare the copy of the binary (get its size)
558     struct stat fdin_stat;
559     stat(executable_copy.c_str(), &fdin_stat);
560     off_t fdin_size = fdin_stat.st_size;
561
562     simix_global->default_function = [executable_copy, fdin_size](std::vector<std::string> args) {
563       return std::function<void()>([executable_copy, fdin_size, args] {
564
565         // Copy the dynamic library:
566         std::string target_executable = executable_copy
567           + "_" + std::to_string(getpid())
568           + "_" + std::to_string(rank++) + ".so";
569
570         int fdin = open(executable_copy.c_str(), O_RDONLY);
571         xbt_assert(fdin >= 0, "Cannot read from %s", executable_copy.c_str());
572         int fdout = open(target_executable.c_str(), O_CREAT | O_RDWR, S_IRWXU);
573         xbt_assert(fdout >= 0, "Cannot write into %s", target_executable.c_str());
574
575 #if HAVE_SENDFILE
576         ssize_t sent_size = sendfile(fdout, fdin, NULL, fdin_size);
577         xbt_assert(sent_size == fdin_size,
578                    "Error while copying %s: only %zd bytes copied instead of %ld (errno: %d -- %s)",
579                    target_executable.c_str(), sent_size, fdin_size, errno, strerror(errno));
580 #else
581         XBT_VERB("Copy %d bytes into %s", static_cast<int>(fdin_size), target_executable.c_str());
582         const int bufsize = 1024 * 1024 * 4;
583         char buf[bufsize];
584         while (int got = read(fdin, buf, bufsize)) {
585           if (got == -1) {
586             xbt_assert(errno == EINTR, "Cannot read from %s", executable_copy.c_str());
587           } else {
588             char* p  = buf;
589             int todo = got;
590             while (int done = write(fdout, p, todo)) {
591               if (done == -1) {
592                 xbt_assert(errno == EINTR, "Cannot write into %s", target_executable.c_str());
593               } else {
594                 p += done;
595                 todo -= done;
596               }
597             }
598           }
599         }
600 #endif
601         close(fdin);
602         close(fdout);
603
604         // Load the copy and resolve the entry point:
605         void* handle = dlopen(target_executable.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
606         if (xbt_cfg_get_boolean("smpi/keep-temps") == false)
607           unlink(target_executable.c_str());
608         if (handle == nullptr)
609           xbt_die("dlopen failed: %s (errno: %d -- %s)", dlerror(), errno, strerror(errno));
610         smpi_entry_point_type entry_point = smpi_resolve_function(handle);
611         if (!entry_point)
612           xbt_die("Could not resolve entry point");
613
614         smpi_run_entry_point(entry_point, args);
615       });
616     };
617
618   }
619   else {
620
621     // Load the dynamic library and resolve the entry point:
622     void* handle = dlopen(executable, RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
623     if (handle == nullptr)
624       xbt_die("dlopen failed for %s: %s (errno: %d -- %s)", executable, dlerror(), errno, strerror(errno));
625     smpi_entry_point_type entry_point = smpi_resolve_function(handle);
626     if (!entry_point)
627       xbt_die("main not found in %s", executable);
628     // TODO, register the executable for SMPI privatization
629
630     // Execute the same entry point for each simulated process:
631     simix_global->default_function = [entry_point](std::vector<std::string> args) {
632       return std::function<void()>([entry_point, args] {
633         smpi_run_entry_point(entry_point, args);
634       });
635     };
636
637   }
638
639   SIMIX_launch_application(argv[2]);
640
641   SMPI_init();
642
643   /* Clean IO before the run */
644   fflush(stdout);
645   fflush(stderr);
646
647   if (MC_is_active()) {
648     MC_run();
649   } else {
650   
651     SIMIX_run();
652
653     xbt_os_walltimer_stop(global_timer);
654     if (xbt_cfg_get_boolean("smpi/display-timing")){
655       double global_time = xbt_os_timer_elapsed(global_timer);
656       XBT_INFO("Simulated time: %g seconds. \n\n"
657           "The simulation took %g seconds (after parsing and platform setup)\n"
658           "%g seconds were actual computation of the application",
659           SIMIX_get_clock(), global_time , smpi_total_benched_time);
660           
661       if (smpi_total_benched_time/global_time>=0.75)
662       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
663       "You may want to use sampling functions or trace replay to reduce this.");
664     }
665   }
666   int count = smpi_process_count();
667   int i, ret=0;
668   for (i = 0; i < count; i++) {
669     if(process_data[i]->return_value()!=0){
670       ret=process_data[i]->return_value();//return first non 0 value
671       break;
672     }
673   }
674   smpi_global_destroy();
675
676   TRACE_end();
677
678   return ret;
679 }
680
681 // Called either directly from the user code, or from the code called by smpirun
682 void SMPI_init(){
683   smpi_init_logs();
684   smpi_init_options();
685   smpi_global_init();
686   smpi_check_options();
687   TRACE_smpi_alloc();
688   simgrid::surf::surfExitCallbacks.connect(TRACE_smpi_release);
689   if(smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP)
690     smpi_initialize_global_memory_segments();
691 }
692
693 void SMPI_finalize(){
694   smpi_global_destroy();
695 }
696
697 void smpi_mpi_init() {
698   if(smpi_init_sleep > 0) 
699     simcall_process_sleep(smpi_init_sleep);
700 }
701
702 double smpi_mpi_wtime(){
703   double time;
704   if (smpi_process()->initialized() != 0 && smpi_process()->finalized() == 0 && smpi_process()->sampling() == 0) {
705     smpi_bench_end();
706     time = SIMIX_get_clock();
707     // to avoid deadlocks if used as a break condition, such as
708     //     while (MPI_Wtime(...) < time_limit) {
709     //       ....
710     //     }
711     // because the time will not normally advance when only calls to MPI_Wtime
712     // are made -> deadlock (MPI_Wtime never reaches the time limit)
713     if(smpi_wtime_sleep > 0) 
714       simcall_process_sleep(smpi_wtime_sleep);
715     smpi_bench_begin();
716   } else {
717     time = SIMIX_get_clock();
718   }
719   return time;
720 }
721