Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
complete s4u::Storage interface, what a mess...
[simgrid.git] / src / smpi / smpi_global.cpp
1 /* Copyright (c) 2007-2017. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "mc/mc.h"
7 #include "private.h"
8 #include "private.hpp"
9 #include "simgrid/s4u/Mailbox.hpp"
10 #include "simgrid/sg_config.h"
11 #include "src/kernel/activity/SynchroComm.hpp"
12 #include "src/mc/mc_record.h"
13 #include "src/mc/mc_replay.h"
14 #include "src/msg/msg_private.h"
15 #include "src/simix/smx_private.h"
16 #include "surf/surf.h"
17 #include "xbt/replay.hpp"
18 #include <xbt/config.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 simgrid::smpi::Process **process_data = nullptr;
46 int process_count = 0;
47 int smpi_universe_size = 0;
48 int* index_to_process_data = nullptr;
49 extern double smpi_total_benched_time;
50 xbt_os_timer_t global_timer;
51 MPI_Comm MPI_COMM_WORLD = MPI_COMM_UNINITIALIZED;
52 MPI_Errhandler *MPI_ERRORS_RETURN = nullptr;
53 MPI_Errhandler *MPI_ERRORS_ARE_FATAL = nullptr;
54 MPI_Errhandler *MPI_ERRHANDLER_NULL = nullptr;
55 static simgrid::config::Flag<double> smpi_wtime_sleep(
56   "smpi/wtime", "Minimum time to inject inside a call to MPI_Wtime", 0.0);
57 static simgrid::config::Flag<double> smpi_init_sleep(
58   "smpi/init", "Time to inject inside a call to MPI_Init", 0.0);
59
60 void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t) = &smpi_comm_copy_buffer_callback;
61
62
63
64 int smpi_process_count()
65 {
66   return process_count;
67 }
68
69 simgrid::smpi::Process* smpi_process()
70 {
71   simgrid::MsgActorExt* msgExt = static_cast<simgrid::MsgActorExt*>(SIMIX_process_self()->data);
72   return static_cast<simgrid::smpi::Process*>(msgExt->data);
73 }
74
75 simgrid::smpi::Process* smpi_process_remote(int index)
76 {
77   return process_data[index_to_process_data[index]];
78 }
79
80 MPI_Comm smpi_process_comm_self(){
81   return smpi_process()->comm_self();
82 }
83
84 void smpi_process_init(int *argc, char ***argv){
85   simgrid::smpi::Process::init(argc, argv);
86 }
87
88 int smpi_process_index(){
89   return smpi_process()->index();
90 }
91
92
93 int smpi_global_size()
94 {
95   char *value = getenv("SMPI_GLOBAL_SIZE");
96   xbt_assert(value,"Please set env var SMPI_GLOBAL_SIZE to the expected number of processes.");
97
98   return xbt_str_parse_int(value, "SMPI_GLOBAL_SIZE contains a non-numerical value: %s");
99 }
100
101 void smpi_comm_set_copy_data_callback(void (*callback) (smx_activity_t, void*, size_t))
102 {
103   smpi_comm_copy_data_callback = callback;
104 }
105
106 void smpi_comm_copy_buffer_callback(smx_activity_t synchro, void *buff, size_t buff_size)
107 {
108   void* tmpbuff=buff;
109   simgrid::kernel::activity::Comm *comm = dynamic_cast<simgrid::kernel::activity::Comm*>(synchro);
110
111   XBT_DEBUG("Copy the data over");
112   if(smpi_is_shared(buff)){
113     XBT_DEBUG("Sender %p is shared. Let's ignore it.", buff);
114   }else if(smpi_is_shared((char*)comm->dst_buff)){
115     XBT_DEBUG("Receiver %p is shared. Let's ignore it.", (char*)comm->dst_buff);
116   }else{
117
118     if((smpi_privatize_global_variables) && (static_cast<char*>(buff) >= smpi_start_data_exe)
119         && (static_cast<char*>(buff) < smpi_start_data_exe + smpi_size_data_exe )
120       ){
121          XBT_DEBUG("Privatization : We are copying from a zone inside global memory... Saving data to temp buffer !");
122
123          smpi_switch_data_segment(
124              (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->src_proc->data)->data))->index()));
125          tmpbuff = static_cast<void*>(xbt_malloc(buff_size));
126          memcpy(tmpbuff, buff, buff_size);
127     }
128
129     if((smpi_privatize_global_variables) && ((char*)comm->dst_buff >= smpi_start_data_exe)
130         && ((char*)comm->dst_buff < smpi_start_data_exe + smpi_size_data_exe )){
131          XBT_DEBUG("Privatization : We are copying to a zone inside global memory - Switch data segment");
132          smpi_switch_data_segment(
133              (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->dst_proc->data)->data))->index()));
134     }
135
136     XBT_DEBUG("Copying %zu bytes from %p to %p", buff_size, tmpbuff,comm->dst_buff);
137     memcpy(comm->dst_buff, tmpbuff, buff_size);
138   }
139   if (comm->detached) {
140     // if this is a detached send, the source buffer was duplicated by SMPI
141     // sender to make the original buffer available to the application ASAP
142     xbt_free(buff);
143     //It seems that the request is used after the call there this should be free somewhere else but where???
144     //xbt_free(comm->comm.src_data);// inside SMPI the request is kept inside the user data and should be free
145     comm->src_buff = nullptr;
146   }
147
148   if(tmpbuff!=buff)xbt_free(tmpbuff);
149 }
150
151 void smpi_comm_null_copy_buffer_callback(smx_activity_t comm, void *buff, size_t buff_size)
152 {
153   /* nothing done in this version */
154 }
155
156 static void smpi_check_options(){
157   //check correctness of MPI parameters
158
159    xbt_assert(xbt_cfg_get_int("smpi/async-small-thresh") <= xbt_cfg_get_int("smpi/send-is-detached-thresh"));
160
161    if (xbt_cfg_is_default_value("smpi/host-speed")) {
162      XBT_INFO("You did not set the power of the host running the simulation.  "
163               "The timings will certainly not be accurate.  "
164               "Use the option \"--cfg=smpi/host-speed:<flops>\" to set its value."
165               "Check http://simgrid.org/simgrid/latest/doc/options.html#options_smpi_bench for more information.");
166    }
167
168    xbt_assert(xbt_cfg_get_double("smpi/cpu-threshold") >=0,
169        "The 'smpi/cpu-threshold' option cannot have negative values [anymore]. If you want to discard "
170        "the simulation of any computation, please use 'smpi/simulate-computation:no' instead.");
171 }
172
173 int smpi_enabled() {
174   return process_data != nullptr;
175 }
176
177 void smpi_global_init()
178 {
179   int i;
180   MPI_Group group;
181   int smpirun=0;
182
183   if (!MC_is_active()) {
184     global_timer = xbt_os_timer_new();
185     xbt_os_walltimer_start(global_timer);
186   }
187
188   if (xbt_cfg_get_string("smpi/comp-adjustment-file")[0] != '\0') { 
189     std::string filename {xbt_cfg_get_string("smpi/comp-adjustment-file")};
190     std::ifstream fstream(filename);
191     if (!fstream.is_open()) {
192       xbt_die("Could not open file %s. Does it exist?", filename.c_str());
193     }
194
195     std::string line;
196     typedef boost::tokenizer< boost::escaped_list_separator<char>> Tokenizer;
197     std::getline(fstream, line); // Skip the header line
198     while (std::getline(fstream, line)) {
199       Tokenizer tok(line);
200       Tokenizer::iterator it  = tok.begin();
201       Tokenizer::iterator end = std::next(tok.begin());
202
203       std::string location = *it;
204       boost::trim(location);
205       location2speedup.insert(std::pair<std::string, double>(location, std::stod(*end)));
206     }
207   }
208
209 #if HAVE_PAPI
210   // This map holds for each computation unit (such as "default" or "process1" etc.)
211   // the configuration as given by the user (counter data as a pair of (counter_name, counter_counter))
212   // and the (computed) event_set.
213   std::map</* computation unit name */ std::string, papi_process_data> units2papi_setup;
214
215   if (xbt_cfg_get_string("smpi/papi-events")[0] != '\0') {
216     if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
217       XBT_ERROR("Could not initialize PAPI library; is it correctly installed and linked?"
218                 " Expected version is %i",
219                 PAPI_VER_CURRENT);
220
221     typedef boost::tokenizer<boost::char_separator<char>> Tokenizer;
222     boost::char_separator<char> separator_units(";");
223     std::string str = std::string(xbt_cfg_get_string("smpi/papi-events"));
224     Tokenizer tokens(str, separator_units);
225
226     // Iterate over all the computational units. This could be
227     // processes, hosts, threads, ranks... You name it. I'm not exactly
228     // sure what we will support eventually, so I'll leave it at the
229     // general term "units".
230     for (auto& unit_it : tokens) {
231       boost::char_separator<char> separator_events(":");
232       Tokenizer event_tokens(unit_it, separator_events);
233
234       int event_set = PAPI_NULL;
235       if (PAPI_create_eventset(&event_set) != PAPI_OK) {
236         // TODO: Should this let the whole simulation die?
237         XBT_CRITICAL("Could not create PAPI event set during init.");
238       }
239
240       // NOTE: We cannot use a map here, as we must obey the order of the counters
241       // This is important for PAPI: We need to map the values of counters back
242       // to the event_names (so, when PAPI_read() has finished)!
243       papi_counter_t counters2values;
244
245       // Iterate over all counters that were specified for this specific
246       // unit.
247       // Note that we need to remove the name of the unit
248       // (that could also be the "default" value), which always comes first.
249       // Hence, we start at ++(events.begin())!
250       for (Tokenizer::iterator events_it = ++(event_tokens.begin()); events_it != event_tokens.end(); events_it++) {
251
252         int event_code   = PAPI_NULL;
253         char* event_name = const_cast<char*>((*events_it).c_str());
254         if (PAPI_event_name_to_code(event_name, &event_code) == PAPI_OK) {
255           if (PAPI_add_event(event_set, event_code) != PAPI_OK) {
256             XBT_ERROR("Could not add PAPI event '%s'. Skipping.", event_name);
257             continue;
258           } else {
259             XBT_DEBUG("Successfully added PAPI event '%s' to the event set.", event_name);
260           }
261         } else {
262           XBT_CRITICAL("Could not find PAPI event '%s'. Skipping.", event_name);
263           continue;
264         }
265
266         counters2values.push_back(
267             // We cannot just pass *events_it, as this is of type const basic_string
268             std::make_pair<std::string, long long>(std::string(*events_it), 0));
269       }
270
271       std::string unit_name    = *(event_tokens.begin());
272       papi_process_data config = {.counter_data = std::move(counters2values), .event_set = event_set};
273
274       units2papi_setup.insert(std::make_pair(unit_name, std::move(config)));
275     }
276   }
277 #endif
278   if (process_count == 0){
279     process_count = SIMIX_process_count();
280     smpirun=1;
281   }
282   smpi_universe_size = process_count;
283   process_data       = new simgrid::smpi::Process*[process_count];
284   for (i = 0; i < process_count; i++) {
285     process_data[i]                       = new simgrid::smpi::Process(i);
286   }
287   //if the process was launched through smpirun script we generate a global mpi_comm_world
288   //if not, we let MPI_COMM_NULL, and the comm world will be private to each mpi instance
289   if(smpirun){
290     group = new  simgrid::smpi::Group(process_count);
291     MPI_COMM_WORLD = new  simgrid::smpi::Comm(group, nullptr);
292     MPI_Attr_put(MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, reinterpret_cast<void *>(process_count));
293     msg_bar_t bar = MSG_barrier_init(process_count);
294
295     for (i = 0; i < process_count; i++) {
296       group->set_mapping(i, i);
297       process_data[i]->set_finalization_barrier(bar);
298     }
299   }
300 }
301
302 void smpi_global_destroy()
303 {
304   int count = smpi_process_count();
305
306   smpi_bench_destroy();
307   smpi_shared_destroy();
308   if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
309       delete MPI_COMM_WORLD->group();
310       MSG_barrier_destroy(process_data[0]->finalization_barrier());
311   }else{
312       smpi_deployment_cleanup_instances();
313   }
314   for (int i = 0; i < count; i++) {
315     if(process_data[i]->comm_self()!=MPI_COMM_NULL){
316       simgrid::smpi::Comm::destroy(process_data[i]->comm_self());
317     }
318     if(process_data[i]->comm_intra()!=MPI_COMM_NULL){
319       simgrid::smpi::Comm::destroy(process_data[i]->comm_intra());
320     }
321     xbt_os_timer_free(process_data[i]->timer());
322     xbt_mutex_destroy(process_data[i]->mailboxes_mutex());
323     delete process_data[i];
324   }
325   delete[] process_data;
326   process_data = nullptr;
327
328   if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
329     MPI_COMM_WORLD->cleanup_smp();
330     MPI_COMM_WORLD->cleanup_attr<simgrid::smpi::Comm>();
331     if(simgrid::smpi::Colls::smpi_coll_cleanup_callback!=nullptr)
332       simgrid::smpi::Colls::smpi_coll_cleanup_callback();
333     delete MPI_COMM_WORLD;
334   }
335
336   MPI_COMM_WORLD = MPI_COMM_NULL;
337
338   if (!MC_is_active()) {
339     xbt_os_timer_free(global_timer);
340   }
341
342   xbt_free(index_to_process_data);
343   if(smpi_privatize_global_variables)
344     smpi_destroy_global_memory_segments();
345   smpi_free_static();
346 }
347
348 extern "C" {
349
350 #ifndef WIN32
351
352 void __attribute__ ((weak)) user_main_()
353 {
354   xbt_die("Should not be in this smpi_simulated_main");
355 }
356
357 int __attribute__ ((weak)) smpi_simulated_main_(int argc, char **argv)
358 {
359   simgrid::smpi::Process::init(&argc, &argv);
360   user_main_();
361   return 0;
362 }
363
364 inline static int smpi_main_wrapper(int argc, char **argv){
365   int ret = smpi_simulated_main_(argc,argv);
366   if(ret !=0){
367     XBT_WARN("SMPI process did not return 0. Return value : %d", ret);
368     smpi_process()->set_return_value(ret);
369   }
370   return 0;
371 }
372
373 int __attribute__ ((weak)) main(int argc, char **argv)
374 {
375   return smpi_main(smpi_main_wrapper, argc, argv);
376 }
377
378 #endif
379
380 static void smpi_init_logs(){
381
382   /* Connect log categories.  See xbt/log.c */
383
384   XBT_LOG_CONNECT(smpi);  /* Keep this line as soon as possible in this function: xbt_log_appender_file.c depends on it
385                              DO NOT connect this in XBT or so, or it will be useless to xbt_log_appender_file.c */
386   XBT_LOG_CONNECT(instr_smpi);
387   XBT_LOG_CONNECT(smpi_bench);
388   XBT_LOG_CONNECT(smpi_coll);
389   XBT_LOG_CONNECT(smpi_colls);
390   XBT_LOG_CONNECT(smpi_comm);
391   XBT_LOG_CONNECT(smpi_datatype);
392   XBT_LOG_CONNECT(smpi_dvfs);
393   XBT_LOG_CONNECT(smpi_group);
394   XBT_LOG_CONNECT(smpi_kernel);
395   XBT_LOG_CONNECT(smpi_mpi);
396   XBT_LOG_CONNECT(smpi_memory);
397   XBT_LOG_CONNECT(smpi_op);
398   XBT_LOG_CONNECT(smpi_pmpi);
399   XBT_LOG_CONNECT(smpi_request);
400   XBT_LOG_CONNECT(smpi_replay);
401   XBT_LOG_CONNECT(smpi_rma);
402   XBT_LOG_CONNECT(smpi_utils);
403 }
404 }
405
406 static void smpi_init_options(){
407
408     simgrid::smpi::Colls::set_collectives();
409     simgrid::smpi::Colls::smpi_coll_cleanup_callback=nullptr;
410     smpi_cpu_threshold = xbt_cfg_get_double("smpi/cpu-threshold");
411     smpi_host_speed = xbt_cfg_get_double("smpi/host-speed");
412     smpi_privatize_global_variables = xbt_cfg_get_boolean("smpi/privatize-global-variables");
413     if (smpi_cpu_threshold < 0)
414       smpi_cpu_threshold = DBL_MAX;
415
416     char* val = xbt_cfg_get_string("smpi/shared-malloc");
417     if (!strcasecmp(val, "yes") || !strcmp(val, "1") || !strcasecmp(val, "on") || !strcasecmp(val, "global")) {
418       smpi_cfg_shared_malloc = shmalloc_global;
419     } else if (!strcasecmp(val, "local")) {
420       smpi_cfg_shared_malloc = shmalloc_local;
421     } else if (!strcasecmp(val, "no") || !strcmp(val, "0") || !strcasecmp(val, "off")) {
422       smpi_cfg_shared_malloc = shmalloc_none;
423     } else {
424       xbt_die("Invalid value '%s' for option smpi/shared-malloc. Possible values: 'on' or 'global', 'local', 'off'",
425               val);
426     }
427 }
428
429 int smpi_main(int (*realmain) (int argc, char *argv[]), int argc, char *argv[])
430 {
431   srand(SMPI_RAND_SEED);
432
433   if (getenv("SMPI_PRETEND_CC") != nullptr) {
434     /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
435      * configuration tools */
436     return 0;
437   }
438   smpi_init_logs();
439
440   TRACE_global_init(&argc, argv);
441   TRACE_add_start_function(TRACE_smpi_alloc);
442   TRACE_add_end_function(TRACE_smpi_release);
443
444   SIMIX_global_init(&argc, argv);
445   MSG_init(&argc,argv);
446
447   SMPI_switch_data_segment = &smpi_switch_data_segment;
448
449   smpi_init_options();
450
451   // parse the platform file: get the host list
452   SIMIX_create_environment(argv[1]);
453   SIMIX_comm_set_copy_data_callback(smpi_comm_copy_data_callback);
454   SIMIX_function_register_default(realmain);
455   SIMIX_launch_application(argv[2]);
456
457   smpi_global_init();
458
459   smpi_check_options();
460
461   if(smpi_privatize_global_variables)
462     smpi_initialize_global_memory_segments();
463
464   /* Clean IO before the run */
465   fflush(stdout);
466   fflush(stderr);
467
468   if (MC_is_active()) {
469     MC_run();
470   } else {
471   
472     SIMIX_run();
473
474     xbt_os_walltimer_stop(global_timer);
475     if (xbt_cfg_get_boolean("smpi/display-timing")){
476       double global_time = xbt_os_timer_elapsed(global_timer);
477       XBT_INFO("Simulated time: %g seconds. \n\n"
478           "The simulation took %g seconds (after parsing and platform setup)\n"
479           "%g seconds were actual computation of the application",
480           SIMIX_get_clock(), global_time , smpi_total_benched_time);
481           
482       if (smpi_total_benched_time/global_time>=0.75)
483       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
484       "You may want to use sampling functions or trace replay to reduce this.");
485     }
486   }
487   int count = smpi_process_count();
488   int i, ret=0;
489   for (i = 0; i < count; i++) {
490     if(process_data[i]->return_value()!=0){
491       ret=process_data[i]->return_value();//return first non 0 value
492       break;
493     }
494   }
495   smpi_global_destroy();
496
497   TRACE_end();
498
499   return ret;
500 }
501
502 // This function can be called from extern file, to initialize logs, options, and processes of smpi
503 // without the need of smpirun
504 void SMPI_init(){
505   smpi_init_logs();
506   smpi_init_options();
507   smpi_global_init();
508   smpi_check_options();
509   if (TRACE_is_enabled() && TRACE_is_configured())
510     TRACE_smpi_alloc();
511   if(smpi_privatize_global_variables)
512     smpi_initialize_global_memory_segments();
513 }
514
515 void SMPI_finalize(){
516   smpi_global_destroy();
517 }
518
519 void smpi_mpi_init() {
520   if(smpi_init_sleep > 0) 
521     simcall_process_sleep(smpi_init_sleep);
522 }
523
524 double smpi_mpi_wtime(){
525   double time;
526   if (smpi_process()->initialized() != 0 && smpi_process()->finalized() == 0 && smpi_process()->sampling() == 0) {
527     smpi_bench_end();
528     time = SIMIX_get_clock();
529     // to avoid deadlocks if used as a break condition, such as
530     //     while (MPI_Wtime(...) < time_limit) {
531     //       ....
532     //     }
533     // because the time will not normally advance when only calls to MPI_Wtime
534     // are made -> deadlock (MPI_Wtime never reaches the time limit)
535     if(smpi_wtime_sleep > 0) 
536       simcall_process_sleep(smpi_wtime_sleep);
537     smpi_bench_begin();
538   } else {
539     time = SIMIX_get_clock();
540   }
541   return time;
542 }
543