Logo AND Algorithmique Numérique Distribuée

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