Logo AND Algorithmique Numérique Distribuée

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