Logo AND Algorithmique Numérique Distribuée

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