Logo AND Algorithmique Numérique Distribuée

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