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 "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>
21 #include <float.h> /* DBL_MAX */
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 */
36 const char* papi_default_config_name = "default";
38 struct papi_process_data {
39 papi_counter_t counter_data;
44 std::unordered_map<std::string, double> location2speedup;
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);
61 void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t) = &smpi_comm_copy_buffer_callback;
65 int smpi_process_count()
70 simgrid::smpi::Process* smpi_process()
72 simgrid::MsgActorExt* msgExt = static_cast<simgrid::MsgActorExt*>(SIMIX_process_self()->data);
73 return static_cast<simgrid::smpi::Process*>(msgExt->data);
76 simgrid::smpi::Process* smpi_process_remote(int index)
78 return process_data[index_to_process_data[index]];
81 MPI_Comm smpi_process_comm_self(){
82 return smpi_process()->comm_self();
85 void smpi_process_init(int *argc, char ***argv){
86 simgrid::smpi::Process::init(argc, argv);
89 int smpi_process_index(){
90 return smpi_process()->index();
94 int smpi_global_size()
96 char *value = getenv("SMPI_GLOBAL_SIZE");
97 xbt_assert(value,"Please set env var SMPI_GLOBAL_SIZE to the expected number of processes.");
99 return xbt_str_parse_int(value, "SMPI_GLOBAL_SIZE contains a non-numerical value: %s");
102 void smpi_comm_set_copy_data_callback(void (*callback) (smx_activity_t, void*, size_t))
104 smpi_comm_copy_data_callback = callback;
107 void print(std::vector<std::pair<int, int>> vec) {
108 fprintf(stderr, "{");
110 fprintf(stderr, "(0x%x, 0x%x),", elt.first, elt.second);
112 stderr, fprintf(stderr, "}\n");
114 void memcpy_private(void *dest, const void *src, size_t n, std::vector<std::pair<int, int>> &private_blocks) {
115 for(auto block : private_blocks) {
116 memcpy((uint8_t*)dest+block.first, (uint8_t*)src+block.first, block.second-block.first);
120 void smpi_comm_copy_buffer_callback(smx_activity_t synchro, void *buff, size_t buff_size)
122 simgrid::kernel::activity::Comm *comm = dynamic_cast<simgrid::kernel::activity::Comm*>(synchro);
123 int src_shared=0, dst_shared=0;
124 int src_offset, dst_offset;
125 std::vector<std::pair<int, int>> src_private_blocks;
126 std::vector<std::pair<int, int>> dst_private_blocks;
127 XBT_DEBUG("Copy the data over");
128 if(src_shared=smpi_is_shared(buff, src_private_blocks, &src_offset)) {
129 XBT_DEBUG("Sender %p is shared. Let's ignore it.", buff);
130 src_private_blocks = shift_private_blocks(src_private_blocks, src_offset);
133 src_private_blocks.clear();
134 src_private_blocks.push_back(std::make_pair(0, buff_size));
136 if(dst_shared=smpi_is_shared((char*)comm->dst_buff, dst_private_blocks, &dst_offset)) {
137 XBT_DEBUG("Receiver %p is shared. Let's ignore it.", (char*)comm->dst_buff);
138 dst_private_blocks = shift_private_blocks(dst_private_blocks, dst_offset);
141 dst_private_blocks.clear();
142 dst_private_blocks.push_back(std::make_pair(0, buff_size));
144 auto private_blocks = merge_private_blocks(src_private_blocks, dst_private_blocks);
146 if((smpi_privatize_global_variables) && (static_cast<char*>(buff) >= smpi_start_data_exe)
147 && (static_cast<char*>(buff) < smpi_start_data_exe + smpi_size_data_exe )
149 XBT_DEBUG("Privatization : We are copying from a zone inside global memory... Saving data to temp buffer !");
151 smpi_switch_data_segment(
152 (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->src_proc->data)->data))->index()));
153 tmpbuff = static_cast<void*>(xbt_malloc(buff_size));
154 memcpy_private(tmpbuff, buff, buff_size, private_blocks);
157 if((smpi_privatize_global_variables) && ((char*)comm->dst_buff >= smpi_start_data_exe)
158 && ((char*)comm->dst_buff < smpi_start_data_exe + smpi_size_data_exe )){
159 XBT_DEBUG("Privatization : We are copying to a zone inside global memory - Switch data segment");
160 smpi_switch_data_segment(
161 (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->dst_proc->data)->data))->index()));
164 XBT_DEBUG("Copying %zu bytes from %p to %p", buff_size, tmpbuff,comm->dst_buff);
165 memcpy_private(comm->dst_buff, tmpbuff, buff_size, private_blocks);
167 if (comm->detached) {
168 // if this is a detached send, the source buffer was duplicated by SMPI
169 // sender to make the original buffer available to the application ASAP
171 //It seems that the request is used after the call there this should be free somewhere else but where???
172 //xbt_free(comm->comm.src_data);// inside SMPI the request is kept inside the user data and should be free
173 comm->src_buff = nullptr;
175 if(tmpbuff!=buff)xbt_free(tmpbuff);
179 void smpi_comm_null_copy_buffer_callback(smx_activity_t comm, void *buff, size_t buff_size)
181 /* nothing done in this version */
184 static void smpi_check_options(){
185 //check correctness of MPI parameters
187 xbt_assert(xbt_cfg_get_int("smpi/async-small-thresh") <= xbt_cfg_get_int("smpi/send-is-detached-thresh"));
189 if (xbt_cfg_is_default_value("smpi/host-speed")) {
190 XBT_INFO("You did not set the power of the host running the simulation. "
191 "The timings will certainly not be accurate. "
192 "Use the option \"--cfg=smpi/host-speed:<flops>\" to set its value."
193 "Check http://simgrid.org/simgrid/latest/doc/options.html#options_smpi_bench for more information.");
196 xbt_assert(xbt_cfg_get_double("smpi/cpu-threshold") >=0,
197 "The 'smpi/cpu-threshold' option cannot have negative values [anymore]. If you want to discard "
198 "the simulation of any computation, please use 'smpi/simulate-computation:no' instead.");
202 return process_data != nullptr;
205 void smpi_global_init()
211 if (!MC_is_active()) {
212 global_timer = xbt_os_timer_new();
213 xbt_os_walltimer_start(global_timer);
216 if (xbt_cfg_get_string("smpi/comp-adjustment-file")[0] != '\0') {
217 std::string filename {xbt_cfg_get_string("smpi/comp-adjustment-file")};
218 std::ifstream fstream(filename);
219 if (!fstream.is_open()) {
220 xbt_die("Could not open file %s. Does it exist?", filename.c_str());
224 typedef boost::tokenizer< boost::escaped_list_separator<char>> Tokenizer;
225 std::getline(fstream, line); // Skip the header line
226 while (std::getline(fstream, line)) {
228 Tokenizer::iterator it = tok.begin();
229 Tokenizer::iterator end = std::next(tok.begin());
231 std::string location = *it;
232 boost::trim(location);
233 location2speedup.insert(std::pair<std::string, double>(location, std::stod(*end)));
238 // This map holds for each computation unit (such as "default" or "process1" etc.)
239 // the configuration as given by the user (counter data as a pair of (counter_name, counter_counter))
240 // and the (computed) event_set.
241 std::map</* computation unit name */ std::string, papi_process_data> units2papi_setup;
243 if (xbt_cfg_get_string("smpi/papi-events")[0] != '\0') {
244 if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
245 XBT_ERROR("Could not initialize PAPI library; is it correctly installed and linked?"
246 " Expected version is %i",
249 typedef boost::tokenizer<boost::char_separator<char>> Tokenizer;
250 boost::char_separator<char> separator_units(";");
251 std::string str = std::string(xbt_cfg_get_string("smpi/papi-events"));
252 Tokenizer tokens(str, separator_units);
254 // Iterate over all the computational units. This could be
255 // processes, hosts, threads, ranks... You name it. I'm not exactly
256 // sure what we will support eventually, so I'll leave it at the
257 // general term "units".
258 for (auto& unit_it : tokens) {
259 boost::char_separator<char> separator_events(":");
260 Tokenizer event_tokens(unit_it, separator_events);
262 int event_set = PAPI_NULL;
263 if (PAPI_create_eventset(&event_set) != PAPI_OK) {
264 // TODO: Should this let the whole simulation die?
265 XBT_CRITICAL("Could not create PAPI event set during init.");
268 // NOTE: We cannot use a map here, as we must obey the order of the counters
269 // This is important for PAPI: We need to map the values of counters back
270 // to the event_names (so, when PAPI_read() has finished)!
271 papi_counter_t counters2values;
273 // Iterate over all counters that were specified for this specific
275 // Note that we need to remove the name of the unit
276 // (that could also be the "default" value), which always comes first.
277 // Hence, we start at ++(events.begin())!
278 for (Tokenizer::iterator events_it = ++(event_tokens.begin()); events_it != event_tokens.end(); events_it++) {
280 int event_code = PAPI_NULL;
281 char* event_name = const_cast<char*>((*events_it).c_str());
282 if (PAPI_event_name_to_code(event_name, &event_code) == PAPI_OK) {
283 if (PAPI_add_event(event_set, event_code) != PAPI_OK) {
284 XBT_ERROR("Could not add PAPI event '%s'. Skipping.", event_name);
287 XBT_DEBUG("Successfully added PAPI event '%s' to the event set.", event_name);
290 XBT_CRITICAL("Could not find PAPI event '%s'. Skipping.", event_name);
294 counters2values.push_back(
295 // We cannot just pass *events_it, as this is of type const basic_string
296 std::make_pair<std::string, long long>(std::string(*events_it), 0));
299 std::string unit_name = *(event_tokens.begin());
300 papi_process_data config = {.counter_data = std::move(counters2values), .event_set = event_set};
302 units2papi_setup.insert(std::make_pair(unit_name, std::move(config)));
306 if (process_count == 0){
307 process_count = SIMIX_process_count();
310 smpi_universe_size = process_count;
311 process_data = new simgrid::smpi::Process*[process_count];
312 for (i = 0; i < process_count; i++) {
313 process_data[i] = new simgrid::smpi::Process(i);
315 //if the process was launched through smpirun script we generate a global mpi_comm_world
316 //if not, we let MPI_COMM_NULL, and the comm world will be private to each mpi instance
318 group = new simgrid::smpi::Group(process_count);
319 MPI_COMM_WORLD = new simgrid::smpi::Comm(group, nullptr);
320 MPI_Attr_put(MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, reinterpret_cast<void *>(process_count));
321 msg_bar_t bar = MSG_barrier_init(process_count);
323 for (i = 0; i < process_count; i++) {
324 group->set_mapping(i, i);
325 process_data[i]->set_finalization_barrier(bar);
330 void smpi_global_destroy()
332 int count = smpi_process_count();
334 smpi_bench_destroy();
335 smpi_shared_destroy();
336 if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
337 delete MPI_COMM_WORLD->group();
338 MSG_barrier_destroy(process_data[0]->finalization_barrier());
340 smpi_deployment_cleanup_instances();
342 for (int i = 0; i < count; i++) {
343 if(process_data[i]->comm_self()!=MPI_COMM_NULL){
344 simgrid::smpi::Comm::destroy(process_data[i]->comm_self());
346 if(process_data[i]->comm_intra()!=MPI_COMM_NULL){
347 simgrid::smpi::Comm::destroy(process_data[i]->comm_intra());
349 xbt_os_timer_free(process_data[i]->timer());
350 xbt_mutex_destroy(process_data[i]->mailboxes_mutex());
351 delete process_data[i];
353 delete[] process_data;
354 process_data = nullptr;
356 if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
357 MPI_COMM_WORLD->cleanup_smp();
358 MPI_COMM_WORLD->cleanup_attr<simgrid::smpi::Comm>();
359 if(simgrid::smpi::Colls::smpi_coll_cleanup_callback!=nullptr)
360 simgrid::smpi::Colls::smpi_coll_cleanup_callback();
361 delete MPI_COMM_WORLD;
364 MPI_COMM_WORLD = MPI_COMM_NULL;
366 if (!MC_is_active()) {
367 xbt_os_timer_free(global_timer);
370 xbt_free(index_to_process_data);
371 if(smpi_privatize_global_variables)
372 smpi_destroy_global_memory_segments();
380 void __attribute__ ((weak)) user_main_()
382 xbt_die("Should not be in this smpi_simulated_main");
385 int __attribute__ ((weak)) smpi_simulated_main_(int argc, char **argv)
387 simgrid::smpi::Process::init(&argc, &argv);
392 inline static int smpi_main_wrapper(int argc, char **argv){
393 int ret = smpi_simulated_main_(argc,argv);
395 XBT_WARN("SMPI process did not return 0. Return value : %d", ret);
396 smpi_process()->set_return_value(ret);
401 int __attribute__ ((weak)) main(int argc, char **argv)
403 return smpi_main(smpi_main_wrapper, argc, argv);
408 static void smpi_init_logs(){
410 /* Connect log categories. See xbt/log.c */
412 XBT_LOG_CONNECT(smpi); /* Keep this line as soon as possible in this function: xbt_log_appender_file.c depends on it
413 DO NOT connect this in XBT or so, or it will be useless to xbt_log_appender_file.c */
414 XBT_LOG_CONNECT(instr_smpi);
415 XBT_LOG_CONNECT(smpi_bench);
416 XBT_LOG_CONNECT(smpi_coll);
417 XBT_LOG_CONNECT(smpi_colls);
418 XBT_LOG_CONNECT(smpi_comm);
419 XBT_LOG_CONNECT(smpi_datatype);
420 XBT_LOG_CONNECT(smpi_dvfs);
421 XBT_LOG_CONNECT(smpi_group);
422 XBT_LOG_CONNECT(smpi_kernel);
423 XBT_LOG_CONNECT(smpi_mpi);
424 XBT_LOG_CONNECT(smpi_memory);
425 XBT_LOG_CONNECT(smpi_op);
426 XBT_LOG_CONNECT(smpi_pmpi);
427 XBT_LOG_CONNECT(smpi_request);
428 XBT_LOG_CONNECT(smpi_replay);
429 XBT_LOG_CONNECT(smpi_rma);
430 XBT_LOG_CONNECT(smpi_shared);
431 XBT_LOG_CONNECT(smpi_utils);
435 static void smpi_init_options(){
437 simgrid::smpi::Colls::set_collectives();
438 simgrid::smpi::Colls::smpi_coll_cleanup_callback=nullptr;
439 smpi_cpu_threshold = xbt_cfg_get_double("smpi/cpu-threshold");
440 smpi_host_speed = xbt_cfg_get_double("smpi/host-speed");
441 smpi_privatize_global_variables = xbt_cfg_get_boolean("smpi/privatize-global-variables");
442 if (smpi_cpu_threshold < 0)
443 smpi_cpu_threshold = DBL_MAX;
445 char* val = xbt_cfg_get_string("smpi/shared-malloc");
446 if (!strcasecmp(val, "yes") || !strcmp(val, "1") || !strcasecmp(val, "on") || !strcasecmp(val, "global")) {
447 smpi_cfg_shared_malloc = shmalloc_global;
448 } else if (!strcasecmp(val, "local")) {
449 smpi_cfg_shared_malloc = shmalloc_local;
450 } else if (!strcasecmp(val, "no") || !strcmp(val, "0") || !strcasecmp(val, "off")) {
451 smpi_cfg_shared_malloc = shmalloc_none;
453 xbt_die("Invalid value '%s' for option smpi/shared-malloc. Possible values: 'on' or 'global', 'local', 'off'",
458 int smpi_main(int (*realmain) (int argc, char *argv[]), int argc, char *argv[])
460 srand(SMPI_RAND_SEED);
462 if (getenv("SMPI_PRETEND_CC") != nullptr) {
463 /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
464 * configuration tools */
469 TRACE_global_init(&argc, argv);
470 TRACE_add_start_function(TRACE_smpi_alloc);
471 TRACE_add_end_function(TRACE_smpi_release);
473 SIMIX_global_init(&argc, argv);
474 MSG_init(&argc,argv);
476 SMPI_switch_data_segment = &smpi_switch_data_segment;
480 // parse the platform file: get the host list
481 SIMIX_create_environment(argv[1]);
482 SIMIX_comm_set_copy_data_callback(smpi_comm_copy_data_callback);
483 SIMIX_function_register_default(realmain);
484 SIMIX_launch_application(argv[2]);
488 smpi_check_options();
490 if(smpi_privatize_global_variables)
491 smpi_initialize_global_memory_segments();
493 /* Clean IO before the run */
497 if (MC_is_active()) {
503 xbt_os_walltimer_stop(global_timer);
504 if (xbt_cfg_get_boolean("smpi/display-timing")){
505 double global_time = xbt_os_timer_elapsed(global_timer);
506 XBT_INFO("Simulated time: %g seconds. \n\n"
507 "The simulation took %g seconds (after parsing and platform setup)\n"
508 "%g seconds were actual computation of the application",
509 SIMIX_get_clock(), global_time , smpi_total_benched_time);
511 if (smpi_total_benched_time/global_time>=0.75)
512 XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
513 "You may want to use sampling functions or trace replay to reduce this.");
516 int count = smpi_process_count();
518 for (i = 0; i < count; i++) {
519 if(process_data[i]->return_value()!=0){
520 ret=process_data[i]->return_value();//return first non 0 value
524 smpi_global_destroy();
531 // This function can be called from extern file, to initialize logs, options, and processes of smpi
532 // without the need of smpirun
537 smpi_check_options();
538 if (TRACE_is_enabled() && TRACE_is_configured())
540 if(smpi_privatize_global_variables)
541 smpi_initialize_global_memory_segments();
544 void SMPI_finalize(){
545 smpi_global_destroy();
548 void smpi_mpi_init() {
549 if(smpi_init_sleep > 0)
550 simcall_process_sleep(smpi_init_sleep);
553 double smpi_mpi_wtime(){
555 if (smpi_process()->initialized() != 0 && smpi_process()->finalized() == 0 && smpi_process()->sampling() == 0) {
557 time = SIMIX_get_clock();
558 // to avoid deadlocks if used as a break condition, such as
559 // while (MPI_Wtime(...) < time_limit) {
562 // because the time will not normally advance when only calls to MPI_Wtime
563 // are made -> deadlock (MPI_Wtime never reaches the time limit)
564 if(smpi_wtime_sleep > 0)
565 simcall_process_sleep(smpi_wtime_sleep);
568 time = SIMIX_get_clock();