Logo AND Algorithmique Numérique Distribuée

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