Logo AND Algorithmique Numérique Distribuée

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