Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of git+ssh://scm.gforge.inria.fr//gitroot/simgrid/simgrid
[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 "private.h"
8 #include "private.hpp"
9 #include "simgrid/s4u/Mailbox.hpp"
10 #include "simgrid/sg_config.h"
11 #include "src/kernel/activity/SynchroComm.hpp"
12 #include "src/mc/mc_record.h"
13 #include "src/mc/mc_replay.h"
14 #include "src/msg/msg_private.h"
15 #include "src/simix/smx_private.h"
16 #include "surf/surf.h"
17 #include "xbt/replay.hpp"
18
19 #include <float.h> /* DBL_MAX */
20 #include <fstream>
21 #include <map>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string>
26 #include <vector>
27
28 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_kernel, smpi, "Logging specific to SMPI (kernel)");
29 #include <boost/tokenizer.hpp>
30 #include <boost/algorithm/string.hpp> /* trim_right / trim_left */
31
32 #if HAVE_PAPI
33 #include "papi.h"
34 const char* papi_default_config_name = "default";
35
36 struct papi_process_data {
37   papi_counter_t counter_data;
38   int event_set;
39 };
40
41 #endif
42 std::unordered_map<std::string, double> location2speedup;
43
44 typedef struct s_smpi_process_data {
45   double simulated;
46   int *argc;
47   char ***argv;
48   simgrid::s4u::MailboxPtr mailbox;
49   simgrid::s4u::MailboxPtr mailbox_small;
50   xbt_mutex_t mailboxes_mutex;
51   xbt_os_timer_t timer;
52   MPI_Comm comm_self;
53   MPI_Comm comm_intra;
54   MPI_Comm* comm_world;
55   void *data;                   /* user data */
56   int index;
57   char state;
58   int sampling;                 /* inside an SMPI_SAMPLE_ block? */
59   char* instance_id;
60   bool replaying;                /* is the process replaying a trace */
61   msg_bar_t finalization_barrier;
62   int return_value;
63   smpi_trace_call_location_t trace_call_loc;
64 #if HAVE_PAPI
65   /** Contains hardware data as read by PAPI **/
66   int papi_event_set;
67   papi_counter_t papi_counter_data;
68 #endif
69 } s_smpi_process_data_t;
70
71 static smpi_process_data_t *process_data = nullptr;
72 int process_count = 0;
73 int smpi_universe_size = 0;
74 int* index_to_process_data = nullptr;
75 extern double smpi_total_benched_time;
76 xbt_os_timer_t global_timer;
77 MPI_Comm MPI_COMM_WORLD = MPI_COMM_UNINITIALIZED;
78 MPI_Errhandler *MPI_ERRORS_RETURN = nullptr;
79 MPI_Errhandler *MPI_ERRORS_ARE_FATAL = nullptr;
80 MPI_Errhandler *MPI_ERRHANDLER_NULL = nullptr;
81
82 void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t) = &smpi_comm_copy_buffer_callback;
83
84 #define MAILBOX_NAME_MAXLEN (5 + sizeof(int) * 2 + 1)
85
86 static char *get_mailbox_name(char *str, int index)
87 {
88   snprintf(str, MAILBOX_NAME_MAXLEN, "SMPI-%0*x", static_cast<int> (sizeof(int) * 2), index);
89   return str;
90 }
91
92 static char *get_mailbox_name_small(char *str, int index)
93 {
94   snprintf(str, MAILBOX_NAME_MAXLEN, "small%0*x", static_cast<int> (sizeof(int) * 2), index);
95   return str;
96 }
97
98 void smpi_process_init(int *argc, char ***argv)
99 {
100
101   if (process_data == nullptr){
102     printf("SimGrid was not initialized properly before entering MPI_Init. Aborting, please check compilation process and use smpirun\n");
103     exit(1);
104   }
105   if (argc != nullptr && argv != nullptr) {
106     smx_actor_t proc = SIMIX_process_self();
107     proc->context->set_cleanup(&MSG_process_cleanup_from_SIMIX);
108     char* instance_id = (*argv)[1];
109     int rank = xbt_str_parse_int((*argv)[2], "Invalid rank: %s");
110     int index = smpi_process_index_of_smx_process(proc);
111
112     if(index_to_process_data == nullptr){
113       index_to_process_data=static_cast<int*>(xbt_malloc(SIMIX_process_count()*sizeof(int)));
114     }
115
116     if(smpi_privatize_global_variables){
117       /* Now using segment index of the process  */
118       index = proc->segment_index;
119       /* Done at the process's creation */
120       SMPI_switch_data_segment(index);
121     }
122
123     MPI_Comm* temp_comm_world;
124     msg_bar_t temp_bar;
125     smpi_deployment_register_process(instance_id, rank, index, &temp_comm_world, &temp_bar);
126     smpi_process_data_t data = smpi_process_remote_data(index);
127     data->comm_world         = temp_comm_world;
128     if(temp_bar != nullptr) 
129       data->finalization_barrier = temp_bar;
130     data->index       = index;
131     data->instance_id = instance_id;
132     data->replaying   = false;
133
134     static_cast<simgrid::MsgActorExt*>(proc->data)->data = data;
135
136     if (*argc > 3) {
137       memmove(&(*argv)[0], &(*argv)[2], sizeof(char *) * (*argc - 2));
138       (*argv)[(*argc) - 1] = nullptr;
139       (*argv)[(*argc) - 2] = nullptr;
140     }
141     (*argc)-=2;
142     data->argc = argc;
143     data->argv = argv;
144     // set the process attached to the mailbox
145     data->mailbox_small->setReceiver(simgrid::s4u::Actor::self());
146     XBT_DEBUG("<%d> New process in the game: %p", index, proc);
147   }
148   xbt_assert(smpi_process_data(),
149       "smpi_process_data() returned nullptr. You probably gave a nullptr parameter to MPI_Init. "
150       "Although it's required by MPI-2, this is currently not supported by SMPI.");
151 }
152
153 void smpi_process_destroy()
154 {
155   int index = smpi_process_index();
156   if(smpi_privatize_global_variables){
157     smpi_switch_data_segment(index);
158   }
159   process_data[index_to_process_data[index]]->state = SMPI_FINALIZED;
160   XBT_DEBUG("<%d> Process left the game", index);
161 }
162
163 /** @brief Prepares the current process for termination. */
164 void smpi_process_finalize()
165 {
166     // This leads to an explosion of the search graph which cannot be reduced:
167     if(MC_is_active() || MC_record_replay_is_active())
168       return;
169
170     int index = smpi_process_index();
171     // wait for all pending asynchronous comms to finish
172     MSG_barrier_wait(process_data[index_to_process_data[index]]->finalization_barrier);
173 }
174
175 /** @brief Check if a process is finalized */
176 int smpi_process_finalized()
177 {
178   int index = smpi_process_index();
179     if (index != MPI_UNDEFINED)
180       return (process_data[index_to_process_data[index]]->state == SMPI_FINALIZED);
181     else
182       return 0;
183 }
184
185 /** @brief Check if a process is initialized */
186 int smpi_process_initialized()
187 {
188   if (index_to_process_data == nullptr){
189     return false;
190   } else{
191     int index = smpi_process_index();
192     return ((index != MPI_UNDEFINED) && (process_data[index_to_process_data[index]]->state == SMPI_INITIALIZED));
193   }
194 }
195
196 /** @brief Mark a process as initialized (=MPI_Init called) */
197 void smpi_process_mark_as_initialized()
198 {
199   int index = smpi_process_index();
200   if ((index != MPI_UNDEFINED) && (process_data[index_to_process_data[index]]->state != SMPI_FINALIZED))
201     process_data[index_to_process_data[index]]->state = SMPI_INITIALIZED;
202 }
203
204 void smpi_process_set_replaying(bool value){
205   int index = smpi_process_index();
206   if ((index != MPI_UNDEFINED) && (process_data[index_to_process_data[index]]->state != SMPI_FINALIZED))
207     process_data[index_to_process_data[index]]->replaying = value;
208 }
209
210 bool smpi_process_get_replaying(){
211   int index = smpi_process_index();
212   if (index != MPI_UNDEFINED)
213     return process_data[index_to_process_data[index]]->replaying;
214   else
215     return !simgrid::xbt::replay_is_active();
216 }
217
218 int smpi_global_size()
219 {
220   char *value = getenv("SMPI_GLOBAL_SIZE");
221   xbt_assert(value,"Please set env var SMPI_GLOBAL_SIZE to the expected number of processes.");
222
223   return xbt_str_parse_int(value, "SMPI_GLOBAL_SIZE contains a non-numerical value: %s");
224 }
225
226 smpi_process_data_t smpi_process_data()
227 {
228   simgrid::MsgActorExt* msgExt = static_cast<simgrid::MsgActorExt*>(SIMIX_process_self()->data);
229   return static_cast<smpi_process_data_t>(msgExt->data);
230 }
231
232 smpi_process_data_t smpi_process_remote_data(int index)
233 {
234   return process_data[index_to_process_data[index]];
235 }
236
237 void smpi_process_set_user_data(void *data)
238 {
239   smpi_process_data_t process_data = smpi_process_data();
240   process_data->data = data;
241 }
242
243 void *smpi_process_get_user_data()
244 {
245   smpi_process_data_t process_data = smpi_process_data();
246   return process_data->data;
247 }
248
249 int smpi_process_count()
250 {
251   return process_count;
252 }
253
254 /**
255  * \brief Returns a structure that stores the location (filename + linenumber)
256  *        of the last calls to MPI_* functions.
257  *
258  * \see smpi_trace_set_call_location
259  */
260 smpi_trace_call_location_t* smpi_process_get_call_location()
261 {
262   smpi_process_data_t process_data = smpi_process_data();
263   return &process_data->trace_call_loc;
264 }
265
266 int smpi_process_index()
267 {
268   smpi_process_data_t data = smpi_process_data();
269   //return -1 if not initialized
270   return data != nullptr ? data->index : MPI_UNDEFINED;
271 }
272
273 MPI_Comm smpi_process_comm_world()
274 {
275   smpi_process_data_t data = smpi_process_data();
276   //return MPI_COMM_NULL if not initialized
277   return data != nullptr ? *data->comm_world : MPI_COMM_NULL;
278 }
279
280 smx_mailbox_t smpi_process_mailbox()
281 {
282   smpi_process_data_t data = smpi_process_data();
283   return data->mailbox->getImpl();
284 }
285
286 smx_mailbox_t smpi_process_mailbox_small()
287 {
288   smpi_process_data_t data = smpi_process_data();
289   return data->mailbox_small->getImpl();
290 }
291
292 xbt_mutex_t smpi_process_mailboxes_mutex()
293 {
294   smpi_process_data_t data = smpi_process_data();
295   return data->mailboxes_mutex;
296 }
297
298 smx_mailbox_t smpi_process_remote_mailbox(int index)
299 {
300   smpi_process_data_t data = smpi_process_remote_data(index);
301   return data->mailbox->getImpl();
302 }
303
304 smx_mailbox_t smpi_process_remote_mailbox_small(int index)
305 {
306   smpi_process_data_t data = smpi_process_remote_data(index);
307   return data->mailbox_small->getImpl();
308 }
309
310 xbt_mutex_t smpi_process_remote_mailboxes_mutex(int index)
311 {
312   smpi_process_data_t data = smpi_process_remote_data(index);
313   return data->mailboxes_mutex;
314 }
315
316 #if HAVE_PAPI
317 int smpi_process_papi_event_set(void)
318 {
319   smpi_process_data_t data = smpi_process_data();
320   return data->papi_event_set;
321 }
322
323 papi_counter_t& smpi_process_papi_counters(void)
324 {
325   smpi_process_data_t data = smpi_process_data();
326   return data->papi_counter_data;
327 }
328 #endif
329
330 xbt_os_timer_t smpi_process_timer()
331 {
332   smpi_process_data_t data = smpi_process_data();
333   return data->timer;
334 }
335
336 void smpi_process_simulated_start()
337 {
338   smpi_process_data_t data = smpi_process_data();
339   data->simulated = SIMIX_get_clock();
340 }
341
342 double smpi_process_simulated_elapsed()
343 {
344   smpi_process_data_t data = smpi_process_data();
345   return SIMIX_get_clock() - data->simulated;
346 }
347
348 MPI_Comm smpi_process_comm_self()
349 {
350   smpi_process_data_t data = smpi_process_data();
351   if(data->comm_self==MPI_COMM_NULL){
352     MPI_Group group = new  Group(1);
353     data->comm_self = new  Comm(group, nullptr);
354     group->set_mapping(smpi_process_index(), 0);
355   }
356
357   return data->comm_self;
358 }
359
360 MPI_Comm smpi_process_get_comm_intra()
361 {
362   smpi_process_data_t data = smpi_process_data();
363   return data->comm_intra;
364 }
365
366 void smpi_process_set_comm_intra(MPI_Comm comm)
367 {
368   smpi_process_data_t data = smpi_process_data();
369   data->comm_intra = comm;
370 }
371
372 void smpi_process_set_sampling(int s)
373 {
374   smpi_process_data_t data = smpi_process_data();
375   data->sampling = s;
376 }
377
378 int smpi_process_get_sampling()
379 {
380   smpi_process_data_t data = smpi_process_data();
381   return data->sampling;
382 }
383
384 void smpi_comm_set_copy_data_callback(void (*callback) (smx_activity_t, void*, size_t))
385 {
386   smpi_comm_copy_data_callback = callback;
387 }
388
389 void smpi_comm_copy_buffer_callback(smx_activity_t synchro, void *buff, size_t buff_size)
390 {
391   XBT_DEBUG("Copy the data over");
392   void* tmpbuff=buff;
393   simgrid::kernel::activity::Comm *comm = dynamic_cast<simgrid::kernel::activity::Comm*>(synchro);
394
395   if((smpi_privatize_global_variables) && (static_cast<char*>(buff) >= smpi_start_data_exe)
396       && (static_cast<char*>(buff) < smpi_start_data_exe + smpi_size_data_exe )
397     ){
398        XBT_DEBUG("Privatization : We are copying from a zone inside global memory... Saving data to temp buffer !");
399
400        smpi_switch_data_segment(
401            (static_cast<smpi_process_data_t>((static_cast<simgrid::MsgActorExt*>(comm->src_proc->data)->data))->index));
402        tmpbuff = static_cast<void*>(xbt_malloc(buff_size));
403        memcpy(tmpbuff, buff, buff_size);
404   }
405
406   if((smpi_privatize_global_variables) && ((char*)comm->dst_buff >= smpi_start_data_exe)
407       && ((char*)comm->dst_buff < smpi_start_data_exe + smpi_size_data_exe )){
408        XBT_DEBUG("Privatization : We are copying to a zone inside global memory - Switch data segment");
409        smpi_switch_data_segment(
410            (static_cast<smpi_process_data_t>((static_cast<simgrid::MsgActorExt*>(comm->dst_proc->data)->data))->index));
411   }
412
413   memcpy(comm->dst_buff, tmpbuff, buff_size);
414   if (comm->detached) {
415     // if this is a detached send, the source buffer was duplicated by SMPI
416     // sender to make the original buffer available to the application ASAP
417     xbt_free(buff);
418     //It seems that the request is used after the call there this should be free somewhere else but where???
419     //xbt_free(comm->comm.src_data);// inside SMPI the request is kept inside the user data and should be free
420     comm->src_buff = nullptr;
421   }
422
423   if(tmpbuff!=buff)xbt_free(tmpbuff);
424 }
425
426 void smpi_comm_null_copy_buffer_callback(smx_activity_t comm, void *buff, size_t buff_size)
427 {
428   /* nothing done in this version */
429 }
430
431 static void smpi_check_options(){
432   //check correctness of MPI parameters
433
434    xbt_assert(xbt_cfg_get_int("smpi/async-small-thresh") <= xbt_cfg_get_int("smpi/send-is-detached-thresh"));
435
436    if (xbt_cfg_is_default_value("smpi/host-speed")) {
437      XBT_INFO("You did not set the power of the host running the simulation.  "
438               "The timings will certainly not be accurate.  "
439               "Use the option \"--cfg=smpi/host-speed:<flops>\" to set its value."
440               "Check http://simgrid.org/simgrid/latest/doc/options.html#options_smpi_bench for more information.");
441    }
442
443    xbt_assert(xbt_cfg_get_double("smpi/cpu-threshold") >=0,
444        "The 'smpi/cpu-threshold' option cannot have negative values [anymore]. If you want to discard "
445        "the simulation of any computation, please use 'smpi/simulate-computation:no' instead.");
446 }
447
448 int smpi_enabled() {
449   return process_data != nullptr;
450 }
451
452 void smpi_global_init()
453 {
454   int i;
455   MPI_Group group;
456   char name[MAILBOX_NAME_MAXLEN];
457   int smpirun=0;
458
459   if (!MC_is_active()) {
460     global_timer = xbt_os_timer_new();
461     xbt_os_walltimer_start(global_timer);
462   }
463
464   if (xbt_cfg_get_string("smpi/comp-adjustment-file")[0] != '\0') { 
465     std::string filename {xbt_cfg_get_string("smpi/comp-adjustment-file")};
466     std::ifstream fstream(filename);
467     if (!fstream.is_open()) {
468       xbt_die("Could not open file %s. Does it exist?", filename.c_str());
469     }
470
471     std::string line;
472     typedef boost::tokenizer< boost::escaped_list_separator<char>> Tokenizer;
473     std::getline(fstream, line); // Skip the header line
474     while (std::getline(fstream, line)) {
475       Tokenizer tok(line);
476       Tokenizer::iterator it  = tok.begin();
477       Tokenizer::iterator end = std::next(tok.begin());
478
479       std::string location = *it;
480       boost::trim(location);
481       location2speedup.insert(std::pair<std::string, double>(location, std::stod(*end)));
482     }
483   }
484
485 #if HAVE_PAPI
486   // This map holds for each computation unit (such as "default" or "process1" etc.)
487   // the configuration as given by the user (counter data as a pair of (counter_name, counter_counter))
488   // and the (computed) event_set.
489   std::map</* computation unit name */ std::string, papi_process_data> units2papi_setup;
490
491   if (xbt_cfg_get_string("smpi/papi-events")[0] != '\0') {
492     if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
493       XBT_ERROR("Could not initialize PAPI library; is it correctly installed and linked?"
494                 " Expected version is %i",
495                 PAPI_VER_CURRENT);
496
497     typedef boost::tokenizer<boost::char_separator<char>> Tokenizer;
498     boost::char_separator<char> separator_units(";");
499     std::string str = std::string(xbt_cfg_get_string("smpi/papi-events"));
500     Tokenizer tokens(str, separator_units);
501
502     // Iterate over all the computational units. This could be
503     // processes, hosts, threads, ranks... You name it. I'm not exactly
504     // sure what we will support eventually, so I'll leave it at the
505     // general term "units".
506     for (auto& unit_it : tokens) {
507       boost::char_separator<char> separator_events(":");
508       Tokenizer event_tokens(unit_it, separator_events);
509
510       int event_set = PAPI_NULL;
511       if (PAPI_create_eventset(&event_set) != PAPI_OK) {
512         // TODO: Should this let the whole simulation die?
513         XBT_CRITICAL("Could not create PAPI event set during init.");
514       }
515
516       // NOTE: We cannot use a map here, as we must obey the order of the counters
517       // This is important for PAPI: We need to map the values of counters back
518       // to the event_names (so, when PAPI_read() has finished)!
519       papi_counter_t counters2values;
520
521       // Iterate over all counters that were specified for this specific
522       // unit.
523       // Note that we need to remove the name of the unit
524       // (that could also be the "default" value), which always comes first.
525       // Hence, we start at ++(events.begin())!
526       for (Tokenizer::iterator events_it = ++(event_tokens.begin()); events_it != event_tokens.end(); events_it++) {
527
528         int event_code   = PAPI_NULL;
529         char* event_name = const_cast<char*>((*events_it).c_str());
530         if (PAPI_event_name_to_code(event_name, &event_code) == PAPI_OK) {
531           if (PAPI_add_event(event_set, event_code) != PAPI_OK) {
532             XBT_ERROR("Could not add PAPI event '%s'. Skipping.", event_name);
533             continue;
534           } else {
535             XBT_DEBUG("Successfully added PAPI event '%s' to the event set.", event_name);
536           }
537         } else {
538           XBT_CRITICAL("Could not find PAPI event '%s'. Skipping.", event_name);
539           continue;
540         }
541
542         counters2values.push_back(
543             // We cannot just pass *events_it, as this is of type const basic_string
544             std::make_pair<std::string, long long>(std::string(*events_it), 0));
545       }
546
547       std::string unit_name    = *(event_tokens.begin());
548       papi_process_data config = {.counter_data = std::move(counters2values), .event_set = event_set};
549
550       units2papi_setup.insert(std::make_pair(unit_name, std::move(config)));
551     }
552   }
553 #endif
554   if (process_count == 0){
555     process_count = SIMIX_process_count();
556     smpirun=1;
557   }
558   smpi_universe_size = process_count;
559   process_data       = new smpi_process_data_t[process_count];
560   for (i = 0; i < process_count; i++) {
561     process_data[i]                       = new s_smpi_process_data_t;
562     process_data[i]->argc                 = nullptr;
563     process_data[i]->argv                 = nullptr;
564     process_data[i]->mailbox              = simgrid::s4u::Mailbox::byName(get_mailbox_name(name, i));
565     process_data[i]->mailbox_small        = simgrid::s4u::Mailbox::byName(get_mailbox_name_small(name, i));
566     process_data[i]->mailboxes_mutex      = xbt_mutex_init();
567     process_data[i]->timer                = xbt_os_timer_new();
568     if (MC_is_active())
569       MC_ignore_heap(process_data[i]->timer, xbt_os_timer_size());
570     process_data[i]->comm_self            = MPI_COMM_NULL;
571     process_data[i]->comm_intra           = MPI_COMM_NULL;
572     process_data[i]->comm_world           = nullptr;
573     process_data[i]->state                = SMPI_UNINITIALIZED;
574     process_data[i]->sampling             = 0;
575     process_data[i]->finalization_barrier = nullptr;
576     process_data[i]->return_value         = 0;
577
578 #if HAVE_PAPI
579     if (xbt_cfg_get_string("smpi/papi-events")[0] != '\0') {
580       // TODO: Implement host/process/thread based counters. This implementation
581       // just always takes the values passed via "default", like this:
582       // "default:COUNTER1:COUNTER2:COUNTER3;".
583       auto it = units2papi_setup.find(papi_default_config_name);
584       if (it != units2papi_setup.end()) {
585         process_data[i]->papi_event_set    = it->second.event_set;
586         process_data[i]->papi_counter_data = it->second.counter_data;
587         XBT_DEBUG("Setting PAPI set for process %i", i);
588       } else {
589         process_data[i]->papi_event_set = PAPI_NULL;
590         XBT_DEBUG("No PAPI set for process %i", i);
591       }
592     }
593 #endif
594   }
595   //if the process was launched through smpirun script we generate a global mpi_comm_world
596   //if not, we let MPI_COMM_NULL, and the comm world will be private to each mpi instance
597   if(smpirun){
598     group = new  Group(process_count);
599     MPI_COMM_WORLD = new  Comm(group, nullptr);
600     MPI_Attr_put(MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, reinterpret_cast<void *>(process_count));
601     msg_bar_t bar = MSG_barrier_init(process_count);
602
603     for (i = 0; i < process_count; i++) {
604       group->set_mapping(i, i);
605       process_data[i]->finalization_barrier = bar;
606     }
607   }
608 }
609
610 void smpi_global_destroy()
611 {
612   int count = smpi_process_count();
613
614   smpi_bench_destroy();
615   if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
616       delete MPI_COMM_WORLD->group();
617       MSG_barrier_destroy(process_data[0]->finalization_barrier);
618   }else{
619       smpi_deployment_cleanup_instances();
620   }
621   for (int i = 0; i < count; i++) {
622     if(process_data[i]->comm_self!=MPI_COMM_NULL){
623       Comm::destroy(process_data[i]->comm_self);
624     }
625     if(process_data[i]->comm_intra!=MPI_COMM_NULL){
626       Comm::destroy(process_data[i]->comm_intra);
627     }
628     xbt_os_timer_free(process_data[i]->timer);
629     xbt_mutex_destroy(process_data[i]->mailboxes_mutex);
630     delete process_data[i];
631   }
632   delete[] process_data;
633   process_data = nullptr;
634
635   if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
636     MPI_COMM_WORLD->cleanup_smp();
637     MPI_COMM_WORLD->cleanup_attr<Comm>();
638     if(Colls::smpi_coll_cleanup_callback!=nullptr)
639       Colls::smpi_coll_cleanup_callback();
640     delete MPI_COMM_WORLD;
641   }
642
643   MPI_COMM_WORLD = MPI_COMM_NULL;
644
645   if (!MC_is_active()) {
646     xbt_os_timer_free(global_timer);
647   }
648
649   xbt_free(index_to_process_data);
650   if(smpi_privatize_global_variables)
651     smpi_destroy_global_memory_segments();
652   smpi_free_static();
653 }
654
655 extern "C" {
656
657 #ifndef WIN32
658
659 void __attribute__ ((weak)) user_main_()
660 {
661   xbt_die("Should not be in this smpi_simulated_main");
662 }
663
664 int __attribute__ ((weak)) smpi_simulated_main_(int argc, char **argv)
665 {
666   smpi_process_init(&argc, &argv);
667   user_main_();
668   return 0;
669 }
670
671 inline static int smpi_main_wrapper(int argc, char **argv){
672   int ret = smpi_simulated_main_(argc,argv);
673   if(ret !=0){
674     XBT_WARN("SMPI process did not return 0. Return value : %d", ret);
675     smpi_process_data()->return_value=ret;
676   }
677   return 0;
678 }
679
680 int __attribute__ ((weak)) main(int argc, char **argv)
681 {
682   return smpi_main(smpi_main_wrapper, argc, argv);
683 }
684
685 #endif
686
687 static void smpi_init_logs(){
688
689   /* Connect log categories.  See xbt/log.c */
690
691   XBT_LOG_CONNECT(smpi);  /* Keep this line as soon as possible in this function: xbt_log_appender_file.c depends on it
692                              DO NOT connect this in XBT or so, or it will be useless to xbt_log_appender_file.c */
693   XBT_LOG_CONNECT(instr_smpi);
694   XBT_LOG_CONNECT(smpi_base);
695   XBT_LOG_CONNECT(smpi_bench);
696   XBT_LOG_CONNECT(smpi_coll);
697   XBT_LOG_CONNECT(smpi_colls);
698   XBT_LOG_CONNECT(smpi_comm);
699   XBT_LOG_CONNECT(smpi_datatype);
700   XBT_LOG_CONNECT(smpi_dvfs);
701   XBT_LOG_CONNECT(smpi_group);
702   XBT_LOG_CONNECT(smpi_kernel);
703   XBT_LOG_CONNECT(smpi_mpi);
704   XBT_LOG_CONNECT(smpi_memory);
705   XBT_LOG_CONNECT(smpi_op);
706   XBT_LOG_CONNECT(smpi_pmpi);
707   XBT_LOG_CONNECT(smpi_request);
708   XBT_LOG_CONNECT(smpi_replay);
709   XBT_LOG_CONNECT(smpi_rma);
710   XBT_LOG_CONNECT(smpi_utils);
711 }
712 }
713
714 static void smpi_init_options(){
715
716     Colls::set_collectives();
717     Colls::smpi_coll_cleanup_callback=nullptr;
718     smpi_cpu_threshold = xbt_cfg_get_double("smpi/cpu-threshold");
719     smpi_host_speed = xbt_cfg_get_double("smpi/host-speed");
720     smpi_privatize_global_variables = xbt_cfg_get_boolean("smpi/privatize-global-variables");
721     if (smpi_cpu_threshold < 0)
722       smpi_cpu_threshold = DBL_MAX;
723
724     char* val = xbt_cfg_get_string("smpi/shared-malloc");
725     if (!strcasecmp(val, "yes") || !strcmp(val, "1") || !strcasecmp(val, "on") || !strcasecmp(val, "global")) {
726       smpi_cfg_shared_malloc = shmalloc_global;
727     } else if (!strcasecmp(val, "local")) {
728       smpi_cfg_shared_malloc = shmalloc_local;
729     } else if (!strcasecmp(val, "no") || !strcmp(val, "0") || !strcasecmp(val, "off")) {
730       smpi_cfg_shared_malloc = shmalloc_none;
731     } else {
732       xbt_die("Invalid value '%s' for option smpi/shared-malloc. Possible values: 'on' or 'global', 'local', 'off'",
733               val);
734     }
735 }
736
737 int smpi_main(int (*realmain) (int argc, char *argv[]), int argc, char *argv[])
738 {
739   srand(SMPI_RAND_SEED);
740
741   if (getenv("SMPI_PRETEND_CC") != nullptr) {
742     /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
743      * configuration tools */
744     return 0;
745   }
746   smpi_init_logs();
747
748   TRACE_global_init(&argc, argv);
749   TRACE_add_start_function(TRACE_smpi_alloc);
750   TRACE_add_end_function(TRACE_smpi_release);
751
752   SIMIX_global_init(&argc, argv);
753   MSG_init(&argc,argv);
754
755   SMPI_switch_data_segment = &smpi_switch_data_segment;
756
757   smpi_init_options();
758
759   // parse the platform file: get the host list
760   SIMIX_create_environment(argv[1]);
761   SIMIX_comm_set_copy_data_callback(smpi_comm_copy_data_callback);
762   SIMIX_function_register_default(realmain);
763   SIMIX_launch_application(argv[2]);
764
765   smpi_global_init();
766
767   smpi_check_options();
768
769   if(smpi_privatize_global_variables)
770     smpi_initialize_global_memory_segments();
771
772   /* Clean IO before the run */
773   fflush(stdout);
774   fflush(stderr);
775
776   if (MC_is_active()) {
777     MC_run();
778   } else {
779   
780     SIMIX_run();
781
782     xbt_os_walltimer_stop(global_timer);
783     if (xbt_cfg_get_boolean("smpi/display-timing")){
784       double global_time = xbt_os_timer_elapsed(global_timer);
785       XBT_INFO("Simulated time: %g seconds. \n\n"
786           "The simulation took %g seconds (after parsing and platform setup)\n"
787           "%g seconds were actual computation of the application",
788           SIMIX_get_clock(), global_time , smpi_total_benched_time);
789           
790       if (smpi_total_benched_time/global_time>=0.75)
791       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
792       "You may want to use sampling functions or trace replay to reduce this.");
793     }
794   }
795   int count = smpi_process_count();
796   int i, ret=0;
797   for (i = 0; i < count; i++) {
798     if(process_data[i]->return_value!=0){
799       ret=process_data[i]->return_value;//return first non 0 value
800       break;
801     }
802   }
803   smpi_global_destroy();
804
805   TRACE_end();
806
807   return ret;
808 }
809
810 // This function can be called from extern file, to initialize logs, options, and processes of smpi
811 // without the need of smpirun
812 void SMPI_init(){
813   smpi_init_logs();
814   smpi_init_options();
815   smpi_global_init();
816   smpi_check_options();
817   if (TRACE_is_enabled() && TRACE_is_configured())
818     TRACE_smpi_alloc();
819   if(smpi_privatize_global_variables)
820     smpi_initialize_global_memory_segments();
821 }
822
823 void SMPI_finalize(){
824   smpi_global_destroy();
825 }