Logo AND Algorithmique Numérique Distribuée

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