Logo AND Algorithmique Numérique Distribuée

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