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 "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"
19 #include <float.h> /* DBL_MAX */
28 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_kernel, smpi, "Logging specific to SMPI (kernel)");
29 #include <boost/tokenizer.hpp>
30 #include <boost/algorithm/string.hpp> /* trim_right / trim_left */
34 const char* papi_default_config_name = "default";
36 struct papi_process_data {
37 papi_counter_t counter_data;
42 std::unordered_map<std::string, double> location2speedup;
44 Process **process_data = nullptr;
45 int process_count = 0;
46 int smpi_universe_size = 0;
47 int* index_to_process_data = nullptr;
48 extern double smpi_total_benched_time;
49 xbt_os_timer_t global_timer;
50 MPI_Comm MPI_COMM_WORLD = MPI_COMM_UNINITIALIZED;
51 MPI_Errhandler *MPI_ERRORS_RETURN = nullptr;
52 MPI_Errhandler *MPI_ERRORS_ARE_FATAL = nullptr;
53 MPI_Errhandler *MPI_ERRHANDLER_NULL = nullptr;
55 void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t) = &smpi_comm_copy_buffer_callback;
59 int smpi_process_count()
64 Process* smpi_process()
66 simgrid::MsgActorExt* msgExt = static_cast<simgrid::MsgActorExt*>(SIMIX_process_self()->data);
67 return static_cast<Process*>(msgExt->data);
70 Process* smpi_process_remote(int index)
72 return process_data[index_to_process_data[index]];
75 MPI_Comm smpi_process_comm_self(){
76 return smpi_process()->comm_self();
79 void smpi_process_init(int *argc, char ***argv){
80 Process::init(argc, argv);
83 int smpi_process_index(){
84 return smpi_process()->index();
88 int smpi_global_size()
90 char *value = getenv("SMPI_GLOBAL_SIZE");
91 xbt_assert(value,"Please set env var SMPI_GLOBAL_SIZE to the expected number of processes.");
93 return xbt_str_parse_int(value, "SMPI_GLOBAL_SIZE contains a non-numerical value: %s");
96 void smpi_comm_set_copy_data_callback(void (*callback) (smx_activity_t, void*, size_t))
98 smpi_comm_copy_data_callback = callback;
101 void smpi_comm_copy_buffer_callback(smx_activity_t synchro, void *buff, size_t buff_size)
103 XBT_DEBUG("Copy the data over");
105 simgrid::kernel::activity::Comm *comm = dynamic_cast<simgrid::kernel::activity::Comm*>(synchro);
107 if((smpi_privatize_global_variables) && (static_cast<char*>(buff) >= smpi_start_data_exe)
108 && (static_cast<char*>(buff) < smpi_start_data_exe + smpi_size_data_exe )
110 XBT_DEBUG("Privatization : We are copying from a zone inside global memory... Saving data to temp buffer !");
112 smpi_switch_data_segment(
113 (static_cast<Process*>((static_cast<simgrid::MsgActorExt*>(comm->src_proc->data)->data))->index()));
114 tmpbuff = static_cast<void*>(xbt_malloc(buff_size));
115 memcpy(tmpbuff, buff, buff_size);
118 if((smpi_privatize_global_variables) && ((char*)comm->dst_buff >= smpi_start_data_exe)
119 && ((char*)comm->dst_buff < smpi_start_data_exe + smpi_size_data_exe )){
120 XBT_DEBUG("Privatization : We are copying to a zone inside global memory - Switch data segment");
121 smpi_switch_data_segment(
122 (static_cast<Process*>((static_cast<simgrid::MsgActorExt*>(comm->dst_proc->data)->data))->index()));
125 memcpy(comm->dst_buff, tmpbuff, buff_size);
126 if (comm->detached) {
127 // if this is a detached send, the source buffer was duplicated by SMPI
128 // sender to make the original buffer available to the application ASAP
130 //It seems that the request is used after the call there this should be free somewhere else but where???
131 //xbt_free(comm->comm.src_data);// inside SMPI the request is kept inside the user data and should be free
132 comm->src_buff = nullptr;
135 if(tmpbuff!=buff)xbt_free(tmpbuff);
138 void smpi_comm_null_copy_buffer_callback(smx_activity_t comm, void *buff, size_t buff_size)
140 /* nothing done in this version */
143 static void smpi_check_options(){
144 //check correctness of MPI parameters
146 xbt_assert(xbt_cfg_get_int("smpi/async-small-thresh") <= xbt_cfg_get_int("smpi/send-is-detached-thresh"));
148 if (xbt_cfg_is_default_value("smpi/host-speed")) {
149 XBT_INFO("You did not set the power of the host running the simulation. "
150 "The timings will certainly not be accurate. "
151 "Use the option \"--cfg=smpi/host-speed:<flops>\" to set its value."
152 "Check http://simgrid.org/simgrid/latest/doc/options.html#options_smpi_bench for more information.");
155 xbt_assert(xbt_cfg_get_double("smpi/cpu-threshold") >=0,
156 "The 'smpi/cpu-threshold' option cannot have negative values [anymore]. If you want to discard "
157 "the simulation of any computation, please use 'smpi/simulate-computation:no' instead.");
161 return process_data != nullptr;
164 void smpi_global_init()
170 if (!MC_is_active()) {
171 global_timer = xbt_os_timer_new();
172 xbt_os_walltimer_start(global_timer);
175 if (xbt_cfg_get_string("smpi/comp-adjustment-file")[0] != '\0') {
176 std::string filename {xbt_cfg_get_string("smpi/comp-adjustment-file")};
177 std::ifstream fstream(filename);
178 if (!fstream.is_open()) {
179 xbt_die("Could not open file %s. Does it exist?", filename.c_str());
183 typedef boost::tokenizer< boost::escaped_list_separator<char>> Tokenizer;
184 std::getline(fstream, line); // Skip the header line
185 while (std::getline(fstream, line)) {
187 Tokenizer::iterator it = tok.begin();
188 Tokenizer::iterator end = std::next(tok.begin());
190 std::string location = *it;
191 boost::trim(location);
192 location2speedup.insert(std::pair<std::string, double>(location, std::stod(*end)));
197 // This map holds for each computation unit (such as "default" or "process1" etc.)
198 // the configuration as given by the user (counter data as a pair of (counter_name, counter_counter))
199 // and the (computed) event_set.
200 std::map</* computation unit name */ std::string, papi_process_data> units2papi_setup;
202 if (xbt_cfg_get_string("smpi/papi-events")[0] != '\0') {
203 if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
204 XBT_ERROR("Could not initialize PAPI library; is it correctly installed and linked?"
205 " Expected version is %i",
208 typedef boost::tokenizer<boost::char_separator<char>> Tokenizer;
209 boost::char_separator<char> separator_units(";");
210 std::string str = std::string(xbt_cfg_get_string("smpi/papi-events"));
211 Tokenizer tokens(str, separator_units);
213 // Iterate over all the computational units. This could be
214 // processes, hosts, threads, ranks... You name it. I'm not exactly
215 // sure what we will support eventually, so I'll leave it at the
216 // general term "units".
217 for (auto& unit_it : tokens) {
218 boost::char_separator<char> separator_events(":");
219 Tokenizer event_tokens(unit_it, separator_events);
221 int event_set = PAPI_NULL;
222 if (PAPI_create_eventset(&event_set) != PAPI_OK) {
223 // TODO: Should this let the whole simulation die?
224 XBT_CRITICAL("Could not create PAPI event set during init.");
227 // NOTE: We cannot use a map here, as we must obey the order of the counters
228 // This is important for PAPI: We need to map the values of counters back
229 // to the event_names (so, when PAPI_read() has finished)!
230 papi_counter_t counters2values;
232 // Iterate over all counters that were specified for this specific
234 // Note that we need to remove the name of the unit
235 // (that could also be the "default" value), which always comes first.
236 // Hence, we start at ++(events.begin())!
237 for (Tokenizer::iterator events_it = ++(event_tokens.begin()); events_it != event_tokens.end(); events_it++) {
239 int event_code = PAPI_NULL;
240 char* event_name = const_cast<char*>((*events_it).c_str());
241 if (PAPI_event_name_to_code(event_name, &event_code) == PAPI_OK) {
242 if (PAPI_add_event(event_set, event_code) != PAPI_OK) {
243 XBT_ERROR("Could not add PAPI event '%s'. Skipping.", event_name);
246 XBT_DEBUG("Successfully added PAPI event '%s' to the event set.", event_name);
249 XBT_CRITICAL("Could not find PAPI event '%s'. Skipping.", event_name);
253 counters2values.push_back(
254 // We cannot just pass *events_it, as this is of type const basic_string
255 std::make_pair<std::string, long long>(std::string(*events_it), 0));
258 std::string unit_name = *(event_tokens.begin());
259 papi_process_data config = {.counter_data = std::move(counters2values), .event_set = event_set};
261 units2papi_setup.insert(std::make_pair(unit_name, std::move(config)));
265 if (process_count == 0){
266 process_count = SIMIX_process_count();
269 smpi_universe_size = process_count;
270 process_data = new Process*[process_count];
271 for (i = 0; i < process_count; i++) {
272 process_data[i] = new Process(i);
274 //if the process was launched through smpirun script we generate a global mpi_comm_world
275 //if not, we let MPI_COMM_NULL, and the comm world will be private to each mpi instance
277 group = new Group(process_count);
278 MPI_COMM_WORLD = new Comm(group, nullptr);
279 MPI_Attr_put(MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, reinterpret_cast<void *>(process_count));
280 msg_bar_t bar = MSG_barrier_init(process_count);
282 for (i = 0; i < process_count; i++) {
283 group->set_mapping(i, i);
284 process_data[i]->set_finalization_barrier(bar);
289 void smpi_global_destroy()
291 int count = smpi_process_count();
293 smpi_bench_destroy();
294 if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
295 delete MPI_COMM_WORLD->group();
296 MSG_barrier_destroy(process_data[0]->finalization_barrier());
298 smpi_deployment_cleanup_instances();
300 for (int i = 0; i < count; i++) {
301 if(process_data[i]->comm_self()!=MPI_COMM_NULL){
302 Comm::destroy(process_data[i]->comm_self());
304 if(process_data[i]->comm_intra()!=MPI_COMM_NULL){
305 Comm::destroy(process_data[i]->comm_intra());
307 xbt_os_timer_free(process_data[i]->timer());
308 xbt_mutex_destroy(process_data[i]->mailboxes_mutex());
309 delete process_data[i];
311 delete[] process_data;
312 process_data = nullptr;
314 if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
315 MPI_COMM_WORLD->cleanup_smp();
316 MPI_COMM_WORLD->cleanup_attr<Comm>();
317 if(Colls::smpi_coll_cleanup_callback!=nullptr)
318 Colls::smpi_coll_cleanup_callback();
319 delete MPI_COMM_WORLD;
322 MPI_COMM_WORLD = MPI_COMM_NULL;
324 if (!MC_is_active()) {
325 xbt_os_timer_free(global_timer);
328 xbt_free(index_to_process_data);
329 if(smpi_privatize_global_variables)
330 smpi_destroy_global_memory_segments();
338 void __attribute__ ((weak)) user_main_()
340 xbt_die("Should not be in this smpi_simulated_main");
343 int __attribute__ ((weak)) smpi_simulated_main_(int argc, char **argv)
345 Process::init(&argc, &argv);
350 inline static int smpi_main_wrapper(int argc, char **argv){
351 int ret = smpi_simulated_main_(argc,argv);
353 XBT_WARN("SMPI process did not return 0. Return value : %d", ret);
354 smpi_process()->set_return_value(ret);
359 int __attribute__ ((weak)) main(int argc, char **argv)
361 return smpi_main(smpi_main_wrapper, argc, argv);
366 static void smpi_init_logs(){
368 /* Connect log categories. See xbt/log.c */
370 XBT_LOG_CONNECT(smpi); /* Keep this line as soon as possible in this function: xbt_log_appender_file.c depends on it
371 DO NOT connect this in XBT or so, or it will be useless to xbt_log_appender_file.c */
372 XBT_LOG_CONNECT(instr_smpi);
373 XBT_LOG_CONNECT(smpi_base);
374 XBT_LOG_CONNECT(smpi_bench);
375 XBT_LOG_CONNECT(smpi_coll);
376 XBT_LOG_CONNECT(smpi_colls);
377 XBT_LOG_CONNECT(smpi_comm);
378 XBT_LOG_CONNECT(smpi_datatype);
379 XBT_LOG_CONNECT(smpi_dvfs);
380 XBT_LOG_CONNECT(smpi_group);
381 XBT_LOG_CONNECT(smpi_kernel);
382 XBT_LOG_CONNECT(smpi_mpi);
383 XBT_LOG_CONNECT(smpi_memory);
384 XBT_LOG_CONNECT(smpi_op);
385 XBT_LOG_CONNECT(smpi_pmpi);
386 XBT_LOG_CONNECT(smpi_request);
387 XBT_LOG_CONNECT(smpi_replay);
388 XBT_LOG_CONNECT(smpi_rma);
389 XBT_LOG_CONNECT(smpi_utils);
393 static void smpi_init_options(){
395 Colls::set_collectives();
396 Colls::smpi_coll_cleanup_callback=nullptr;
397 smpi_cpu_threshold = xbt_cfg_get_double("smpi/cpu-threshold");
398 smpi_host_speed = xbt_cfg_get_double("smpi/host-speed");
399 smpi_privatize_global_variables = xbt_cfg_get_boolean("smpi/privatize-global-variables");
400 if (smpi_cpu_threshold < 0)
401 smpi_cpu_threshold = DBL_MAX;
403 char* val = xbt_cfg_get_string("smpi/shared-malloc");
404 if (!strcasecmp(val, "yes") || !strcmp(val, "1") || !strcasecmp(val, "on") || !strcasecmp(val, "global")) {
405 smpi_cfg_shared_malloc = shmalloc_global;
406 } else if (!strcasecmp(val, "local")) {
407 smpi_cfg_shared_malloc = shmalloc_local;
408 } else if (!strcasecmp(val, "no") || !strcmp(val, "0") || !strcasecmp(val, "off")) {
409 smpi_cfg_shared_malloc = shmalloc_none;
411 xbt_die("Invalid value '%s' for option smpi/shared-malloc. Possible values: 'on' or 'global', 'local', 'off'",
416 int smpi_main(int (*realmain) (int argc, char *argv[]), int argc, char *argv[])
418 srand(SMPI_RAND_SEED);
420 if (getenv("SMPI_PRETEND_CC") != nullptr) {
421 /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
422 * configuration tools */
427 TRACE_global_init(&argc, argv);
428 TRACE_add_start_function(TRACE_smpi_alloc);
429 TRACE_add_end_function(TRACE_smpi_release);
431 SIMIX_global_init(&argc, argv);
432 MSG_init(&argc,argv);
434 SMPI_switch_data_segment = &smpi_switch_data_segment;
438 // parse the platform file: get the host list
439 SIMIX_create_environment(argv[1]);
440 SIMIX_comm_set_copy_data_callback(smpi_comm_copy_data_callback);
441 SIMIX_function_register_default(realmain);
442 SIMIX_launch_application(argv[2]);
446 smpi_check_options();
448 if(smpi_privatize_global_variables)
449 smpi_initialize_global_memory_segments();
451 /* Clean IO before the run */
455 if (MC_is_active()) {
461 xbt_os_walltimer_stop(global_timer);
462 if (xbt_cfg_get_boolean("smpi/display-timing")){
463 double global_time = xbt_os_timer_elapsed(global_timer);
464 XBT_INFO("Simulated time: %g seconds. \n\n"
465 "The simulation took %g seconds (after parsing and platform setup)\n"
466 "%g seconds were actual computation of the application",
467 SIMIX_get_clock(), global_time , smpi_total_benched_time);
469 if (smpi_total_benched_time/global_time>=0.75)
470 XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
471 "You may want to use sampling functions or trace replay to reduce this.");
474 int count = smpi_process_count();
476 for (i = 0; i < count; i++) {
477 if(process_data[i]->return_value()!=0){
478 ret=process_data[i]->return_value();//return first non 0 value
482 smpi_global_destroy();
489 // This function can be called from extern file, to initialize logs, options, and processes of smpi
490 // without the need of smpirun
495 smpi_check_options();
496 if (TRACE_is_enabled() && TRACE_is_configured())
498 if(smpi_privatize_global_variables)
499 smpi_initialize_global_memory_segments();
502 void SMPI_finalize(){
503 smpi_global_destroy();