Logo AND Algorithmique Numérique Distribuée

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