1 /* Copyright (c) 2007-2017. The SimGrid Team. All rights reserved. */
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. */
9 #include <sys/sendfile.h>
11 #include <sys/types.h>
16 #include "private.hpp"
17 #include "simgrid/s4u/Mailbox.hpp"
18 #include "simgrid/sg_config.h"
19 #include "src/kernel/activity/SynchroComm.hpp"
20 #include "src/mc/mc_record.h"
21 #include "src/mc/mc_replay.h"
22 #include "src/msg/msg_private.h"
23 #include "src/simix/smx_private.h"
24 #include "src/surf/surf_interface.hpp"
25 #include "surf/surf.h"
26 #include "xbt/replay.hpp"
27 #include <xbt/config.hpp>
29 #include <float.h> /* DBL_MAX */
40 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_kernel, smpi, "Logging specific to SMPI (kernel)");
41 #include <boost/tokenizer.hpp>
42 #include <boost/algorithm/string.hpp> /* trim_right / trim_left */
45 /* RTLD_DEEPBIND is a bad idea of GNU ld that obviously does not exist on other platforms
46 * See https://www.akkadia.org/drepper/dsohowto.pdf
47 * and https://lists.freebsd.org/pipermail/freebsd-current/2016-March/060284.html
49 #define RTLD_DEEPBIND 0
52 /* Mac OSX does not have any header file providing that definition so we have to duplicate it here. Bummers. */
53 extern char** environ; /* we use it in posix_spawnp below */
57 const char* papi_default_config_name = "default";
59 struct papi_process_data {
60 papi_counter_t counter_data;
65 std::unordered_map<std::string, double> location2speedup;
67 simgrid::smpi::Process **process_data = nullptr;
68 int process_count = 0;
69 int smpi_universe_size = 0;
70 int* index_to_process_data = nullptr;
71 extern double smpi_total_benched_time;
72 xbt_os_timer_t global_timer;
73 MPI_Comm MPI_COMM_WORLD = MPI_COMM_UNINITIALIZED;
74 MPI_Errhandler *MPI_ERRORS_RETURN = nullptr;
75 MPI_Errhandler *MPI_ERRORS_ARE_FATAL = nullptr;
76 MPI_Errhandler *MPI_ERRHANDLER_NULL = nullptr;
77 static simgrid::config::Flag<double> smpi_wtime_sleep(
78 "smpi/wtime", "Minimum time to inject inside a call to MPI_Wtime", 0.0);
79 static simgrid::config::Flag<double> smpi_init_sleep(
80 "smpi/init", "Time to inject inside a call to MPI_Init", 0.0);
82 void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t) = &smpi_comm_copy_buffer_callback;
86 int smpi_process_count()
91 simgrid::smpi::Process* smpi_process()
93 simgrid::MsgActorExt* msgExt = static_cast<simgrid::MsgActorExt*>(SIMIX_process_self()->data);
94 return static_cast<simgrid::smpi::Process*>(msgExt->data);
97 simgrid::smpi::Process* smpi_process_remote(int index)
99 return process_data[index_to_process_data[index]];
102 MPI_Comm smpi_process_comm_self(){
103 return smpi_process()->comm_self();
106 void smpi_process_init(int *argc, char ***argv){
107 simgrid::smpi::Process::init(argc, argv);
110 int smpi_process_index(){
111 return smpi_process()->index();
115 int smpi_global_size()
117 char *value = getenv("SMPI_GLOBAL_SIZE");
118 xbt_assert(value,"Please set env var SMPI_GLOBAL_SIZE to the expected number of processes.");
120 return xbt_str_parse_int(value, "SMPI_GLOBAL_SIZE contains a non-numerical value: %s");
123 void smpi_comm_set_copy_data_callback(void (*callback) (smx_activity_t, void*, size_t))
125 smpi_comm_copy_data_callback = callback;
128 void smpi_comm_copy_buffer_callback(smx_activity_t synchro, void *buff, size_t buff_size)
131 simgrid::kernel::activity::Comm *comm = dynamic_cast<simgrid::kernel::activity::Comm*>(synchro);
133 XBT_DEBUG("Copy the data over");
134 if(smpi_is_shared(buff)){
135 XBT_DEBUG("Sender %p is shared. Let's ignore it.", buff);
136 }else if(smpi_is_shared((char*)comm->dst_buff)){
137 XBT_DEBUG("Receiver %p is shared. Let's ignore it.", (char*)comm->dst_buff);
140 if((smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) && (static_cast<char*>(buff) >= smpi_start_data_exe)
141 && (static_cast<char*>(buff) < smpi_start_data_exe + smpi_size_data_exe )
143 XBT_DEBUG("Privatization : We are copying from a zone inside global memory... Saving data to temp buffer !");
145 smpi_switch_data_segment(
146 (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->src_proc->data)->data))->index()));
147 tmpbuff = static_cast<void*>(xbt_malloc(buff_size));
148 memcpy(tmpbuff, buff, buff_size);
151 if((smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) && ((char*)comm->dst_buff >= smpi_start_data_exe)
152 && ((char*)comm->dst_buff < smpi_start_data_exe + smpi_size_data_exe )){
153 XBT_DEBUG("Privatization : We are copying to a zone inside global memory - Switch data segment");
154 smpi_switch_data_segment(
155 (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->dst_proc->data)->data))->index()));
158 XBT_DEBUG("Copying %zu bytes from %p to %p", buff_size, tmpbuff,comm->dst_buff);
159 memcpy(comm->dst_buff, tmpbuff, buff_size);
161 if (comm->detached) {
162 // if this is a detached send, the source buffer was duplicated by SMPI
163 // sender to make the original buffer available to the application ASAP
165 //It seems that the request is used after the call there this should be free somewhere else but where???
166 //xbt_free(comm->comm.src_data);// inside SMPI the request is kept inside the user data and should be free
167 comm->src_buff = nullptr;
169 if(tmpbuff!=buff)xbt_free(tmpbuff);
174 void smpi_comm_null_copy_buffer_callback(smx_activity_t comm, void *buff, size_t buff_size)
176 /* nothing done in this version */
179 static void smpi_check_options(){
180 //check correctness of MPI parameters
182 xbt_assert(xbt_cfg_get_int("smpi/async-small-thresh") <= xbt_cfg_get_int("smpi/send-is-detached-thresh"));
184 if (xbt_cfg_is_default_value("smpi/host-speed")) {
185 XBT_INFO("You did not set the power of the host running the simulation. "
186 "The timings will certainly not be accurate. "
187 "Use the option \"--cfg=smpi/host-speed:<flops>\" to set its value."
188 "Check http://simgrid.org/simgrid/latest/doc/options.html#options_smpi_bench for more information.");
191 xbt_assert(xbt_cfg_get_double("smpi/cpu-threshold") >=0,
192 "The 'smpi/cpu-threshold' option cannot have negative values [anymore]. If you want to discard "
193 "the simulation of any computation, please use 'smpi/simulate-computation:no' instead.");
197 return process_data != nullptr;
200 void smpi_global_init()
204 if (!MC_is_active()) {
205 global_timer = xbt_os_timer_new();
206 xbt_os_walltimer_start(global_timer);
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());
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)) {
221 Tokenizer::iterator it = tok.begin();
222 Tokenizer::iterator end = std::next(tok.begin());
224 std::string location = *it;
225 boost::trim(location);
226 location2speedup.insert(std::pair<std::string, double>(location, std::stod(*end)));
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;
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",
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);
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);
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.");
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;
266 // Iterate over all counters that were specified for this specific
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++) {
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);
280 XBT_DEBUG("Successfully added PAPI event '%s' to the event set.", event_name);
283 XBT_CRITICAL("Could not find PAPI event '%s'. Skipping.", event_name);
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));
292 std::string unit_name = *(event_tokens.begin());
293 papi_process_data config = {.counter_data = std::move(counters2values), .event_set = event_set};
295 units2papi_setup.insert(std::make_pair(unit_name, std::move(config)));
301 msg_bar_t finalization_barrier = nullptr;
302 if (process_count == 0){
303 process_count = SIMIX_process_count();
305 finalization_barrier = MSG_barrier_init(process_count);
307 smpi_universe_size = process_count;
308 process_data = new simgrid::smpi::Process*[process_count];
309 for (int i = 0; i < process_count; i++) {
310 process_data[i] = new simgrid::smpi::Process(i, finalization_barrier);
312 //if the process was launched through smpirun script we generate a global mpi_comm_world
313 //if not, we let MPI_COMM_NULL, and the comm world will be private to each mpi instance
315 group = new simgrid::smpi::Group(process_count);
316 MPI_COMM_WORLD = new simgrid::smpi::Comm(group, nullptr);
317 MPI_Attr_put(MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, reinterpret_cast<void *>(process_count));
319 for (int i = 0; i < process_count; i++)
320 group->set_mapping(i, i);
324 void smpi_global_destroy()
326 int count = smpi_process_count();
328 smpi_bench_destroy();
329 smpi_shared_destroy();
330 if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
331 delete MPI_COMM_WORLD->group();
332 MSG_barrier_destroy(process_data[0]->finalization_barrier());
334 smpi_deployment_cleanup_instances();
336 for (int i = 0; i < count; i++) {
337 if(process_data[i]->comm_self()!=MPI_COMM_NULL){
338 simgrid::smpi::Comm::destroy(process_data[i]->comm_self());
340 if(process_data[i]->comm_intra()!=MPI_COMM_NULL){
341 simgrid::smpi::Comm::destroy(process_data[i]->comm_intra());
343 xbt_os_timer_free(process_data[i]->timer());
344 xbt_mutex_destroy(process_data[i]->mailboxes_mutex());
345 delete process_data[i];
347 delete[] process_data;
348 process_data = nullptr;
350 if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
351 MPI_COMM_WORLD->cleanup_smp();
352 MPI_COMM_WORLD->cleanup_attr<simgrid::smpi::Comm>();
353 if(simgrid::smpi::Colls::smpi_coll_cleanup_callback!=nullptr)
354 simgrid::smpi::Colls::smpi_coll_cleanup_callback();
355 delete MPI_COMM_WORLD;
358 MPI_COMM_WORLD = MPI_COMM_NULL;
360 if (!MC_is_active()) {
361 xbt_os_timer_free(global_timer);
364 xbt_free(index_to_process_data);
365 if(smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP)
366 smpi_destroy_global_memory_segments();
372 static void smpi_init_logs(){
374 /* Connect log categories. See xbt/log.c */
376 XBT_LOG_CONNECT(smpi); /* Keep this line as soon as possible in this function: xbt_log_appender_file.c depends on it
377 DO NOT connect this in XBT or so, or it will be useless to xbt_log_appender_file.c */
378 XBT_LOG_CONNECT(instr_smpi);
379 XBT_LOG_CONNECT(smpi_bench);
380 XBT_LOG_CONNECT(smpi_coll);
381 XBT_LOG_CONNECT(smpi_colls);
382 XBT_LOG_CONNECT(smpi_comm);
383 XBT_LOG_CONNECT(smpi_datatype);
384 XBT_LOG_CONNECT(smpi_dvfs);
385 XBT_LOG_CONNECT(smpi_group);
386 XBT_LOG_CONNECT(smpi_kernel);
387 XBT_LOG_CONNECT(smpi_mpi);
388 XBT_LOG_CONNECT(smpi_memory);
389 XBT_LOG_CONNECT(smpi_op);
390 XBT_LOG_CONNECT(smpi_pmpi);
391 XBT_LOG_CONNECT(smpi_request);
392 XBT_LOG_CONNECT(smpi_replay);
393 XBT_LOG_CONNECT(smpi_rma);
394 XBT_LOG_CONNECT(smpi_shared);
395 XBT_LOG_CONNECT(smpi_utils);
399 static void smpi_init_options(){
401 simgrid::smpi::Colls::set_collectives();
402 simgrid::smpi::Colls::smpi_coll_cleanup_callback=nullptr;
403 smpi_cpu_threshold = xbt_cfg_get_double("smpi/cpu-threshold");
404 smpi_host_speed = xbt_cfg_get_double("smpi/host-speed");
405 const char* smpi_privatize_option = xbt_cfg_get_string("smpi/privatize-global-variables");
406 if (std::strcmp(smpi_privatize_option, "no") == 0)
407 smpi_privatize_global_variables = SMPI_PRIVATIZE_NONE;
408 else if (std::strcmp(smpi_privatize_option, "yes") == 0)
409 smpi_privatize_global_variables = SMPI_PRIVATIZE_DEFAULT;
410 else if (std::strcmp(smpi_privatize_option, "mmap") == 0)
411 smpi_privatize_global_variables = SMPI_PRIVATIZE_MMAP;
412 else if (std::strcmp(smpi_privatize_option, "dlopen") == 0)
413 smpi_privatize_global_variables = SMPI_PRIVATIZE_DLOPEN;
415 // Some compatibility stuff:
416 else if (std::strcmp(smpi_privatize_option, "1") == 0)
417 smpi_privatize_global_variables = SMPI_PRIVATIZE_DEFAULT;
418 else if (std::strcmp(smpi_privatize_option, "0") == 0)
419 smpi_privatize_global_variables = SMPI_PRIVATIZE_NONE;
422 xbt_die("Invalid value for smpi/privatize-global-variables: %s",
423 smpi_privatize_option);
425 if (smpi_cpu_threshold < 0)
426 smpi_cpu_threshold = DBL_MAX;
428 char* val = xbt_cfg_get_string("smpi/shared-malloc");
429 if (!strcasecmp(val, "yes") || !strcmp(val, "1") || !strcasecmp(val, "on") || !strcasecmp(val, "global")) {
430 smpi_cfg_shared_malloc = shmalloc_global;
431 } else if (!strcasecmp(val, "local")) {
432 smpi_cfg_shared_malloc = shmalloc_local;
433 } else if (!strcasecmp(val, "no") || !strcmp(val, "0") || !strcasecmp(val, "off")) {
434 smpi_cfg_shared_malloc = shmalloc_none;
436 xbt_die("Invalid value '%s' for option smpi/shared-malloc. Possible values: 'on' or 'global', 'local', 'off'",
441 static int execute_command(const char * const argv[])
445 if (posix_spawnp(&pid, argv[0], nullptr, nullptr, (char* const*) argv, environ) != 0)
447 if (waitpid(pid, &status, 0) != pid)
452 typedef std::function<int(int argc, char *argv[])> smpi_entry_point_type;
453 typedef int (* smpi_c_entry_point_type)(int argc, char **argv);
454 typedef void (* smpi_fortran_entry_point_type)(void);
456 static int smpi_run_entry_point(smpi_entry_point_type entry_point, std::vector<std::string> args)
458 const int argc = args.size();
459 std::unique_ptr<char*[]> argv(new char*[argc + 1]);
460 for (int i = 0; i != argc; ++i)
461 argv[i] = args[i].empty() ? const_cast<char*>(""): &args[i].front();
462 argv[argc] = nullptr;
464 int res = entry_point(argc, argv.get());
466 XBT_WARN("SMPI process did not return 0. Return value : %d", res);
467 smpi_process()->set_return_value(res);
472 // TODO, remove the number of functions involved here
473 static smpi_entry_point_type smpi_resolve_function(void* handle)
475 smpi_fortran_entry_point_type entry_point2 =
476 (smpi_fortran_entry_point_type) dlsym(handle, "user_main_");
477 if (entry_point2 != nullptr) {
478 // fprintf(stderr, "EP user_main_=%p\n", entry_point2);
479 return [entry_point2](int argc, char** argv) {
480 smpi_process_init(&argc, &argv);
486 smpi_c_entry_point_type entry_point = (smpi_c_entry_point_type) dlsym(handle, "main");
487 if (entry_point != nullptr) {
488 // fprintf(stderr, "EP main=%p\n", entry_point);
492 return smpi_entry_point_type();
495 int smpi_main(const char* executable, int argc, char *argv[])
497 srand(SMPI_RAND_SEED);
499 if (getenv("SMPI_PRETEND_CC") != nullptr) {
500 /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
501 * configuration tools */
505 TRACE_global_init(&argc, argv);
507 SIMIX_global_init(&argc, argv);
508 MSG_init(&argc,argv);
510 SMPI_switch_data_segment = &smpi_switch_data_segment;
512 // parse the platform file: get the host list
513 SIMIX_create_environment(argv[1]);
514 SIMIX_comm_set_copy_data_callback(smpi_comm_copy_buffer_callback);
516 static std::size_t rank = 0;
518 if (smpi_privatize_global_variables == SMPI_PRIVATIZE_DLOPEN) {
520 std::string executable_copy = executable;
522 // Prepare the copy of the binary (open the file and get its size)
523 // (fdin will remain open for the whole process execution. That's a sort of leak but we can live with it)
524 int fdin = open(executable_copy.c_str(), O_RDONLY);
525 xbt_assert(fdin >= 0, "Cannot read from %s", executable_copy.c_str());
526 struct stat fdin_stat;
527 fstat(fdin, &fdin_stat);
528 off_t fdin_size = fdin_stat.st_size;
530 simix_global->default_function = [executable_copy, fdin, fdin_size](std::vector<std::string> args) {
531 return std::function<void()>([executable_copy, fdin, fdin_size, args] {
533 // Copy the dynamic library:
534 std::string target_executable = executable_copy
535 + "_" + std::to_string(getpid())
536 + "_" + std::to_string(rank++) + ".so";
538 int fdout = open(target_executable.c_str(), O_WRONLY);
539 xbt_assert(fdout >= 0, "Cannot write into %s", target_executable.c_str());
541 sendfile(fdout, fdin, NULL, fdin_size);
544 // Load the copy and resolve the entry point:
545 void* handle = dlopen(target_executable.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
546 unlink(target_executable.c_str());
547 if (handle == nullptr)
548 xbt_die("dlopen failed");
549 smpi_entry_point_type entry_point = smpi_resolve_function(handle);
551 xbt_die("Could not resolve entry point");
553 smpi_run_entry_point(entry_point, args);
560 // Load the dynamic library and resolve the entry point:
561 void* handle = dlopen(executable, RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
562 if (handle == nullptr)
563 xbt_die("dlopen failed for %s", executable);
564 smpi_entry_point_type entry_point = smpi_resolve_function(handle);
566 xbt_die("main not found in %s", executable);
567 // TODO, register the executable for SMPI privatization
569 // Execute the same entry point for each simulated process:
570 simix_global->default_function = [entry_point](std::vector<std::string> args) {
571 return std::function<void()>([entry_point, args] {
572 smpi_run_entry_point(entry_point, args);
578 SIMIX_launch_application(argv[2]);
582 /* Clean IO before the run */
586 if (MC_is_active()) {
592 xbt_os_walltimer_stop(global_timer);
593 if (xbt_cfg_get_boolean("smpi/display-timing")){
594 double global_time = xbt_os_timer_elapsed(global_timer);
595 XBT_INFO("Simulated time: %g seconds. \n\n"
596 "The simulation took %g seconds (after parsing and platform setup)\n"
597 "%g seconds were actual computation of the application",
598 SIMIX_get_clock(), global_time , smpi_total_benched_time);
600 if (smpi_total_benched_time/global_time>=0.75)
601 XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
602 "You may want to use sampling functions or trace replay to reduce this.");
605 int count = smpi_process_count();
607 for (i = 0; i < count; i++) {
608 if(process_data[i]->return_value()!=0){
609 ret=process_data[i]->return_value();//return first non 0 value
613 smpi_global_destroy();
620 // Called either directly from the user code, or from the code called by smpirun
625 smpi_check_options();
627 simgrid::surf::surfExitCallbacks.connect(TRACE_smpi_release);
628 if(smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP)
629 smpi_initialize_global_memory_segments();
632 void SMPI_finalize(){
633 smpi_global_destroy();
636 void smpi_mpi_init() {
637 if(smpi_init_sleep > 0)
638 simcall_process_sleep(smpi_init_sleep);
641 double smpi_mpi_wtime(){
643 if (smpi_process()->initialized() != 0 && smpi_process()->finalized() == 0 && smpi_process()->sampling() == 0) {
645 time = SIMIX_get_clock();
646 // to avoid deadlocks if used as a break condition, such as
647 // while (MPI_Wtime(...) < time_limit) {
650 // because the time will not normally advance when only calls to MPI_Wtime
651 // are made -> deadlock (MPI_Wtime never reaches the time limit)
652 if(smpi_wtime_sleep > 0)
653 simcall_process_sleep(smpi_wtime_sleep);
656 time = SIMIX_get_clock();