Logo AND Algorithmique Numérique Distribuée

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