Logo AND Algorithmique Numérique Distribuée

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