Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2022.
[simgrid.git] / src / smpi / mpi / smpi_comm.cpp
1 /* Copyright (c) 2010-2022. 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 "smpi_comm.hpp"
7 #include "smpi_coll.hpp"
8 #include "smpi_datatype.hpp"
9 #include "smpi_request.hpp"
10 #include "smpi_win.hpp"
11 #include "smpi_info.hpp"
12 #include "src/smpi/include/smpi_actor.hpp"
13 #include "src/surf/HostImpl.hpp"
14
15 #include <limits>
16
17 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_comm, smpi, "Logging specific to SMPI (comm)");
18
19 simgrid::smpi::Comm smpi_MPI_COMM_UNINITIALIZED;
20 MPI_Comm MPI_COMM_UNINITIALIZED=&smpi_MPI_COMM_UNINITIALIZED;
21 /**
22  * Setting MPI_COMM_WORLD to MPI_COMM_UNINITIALIZED (it's a variable)
23  * is important because the implementation of MPI_Comm checks
24  * "this == MPI_COMM_UNINITIALIZED"? If yes, it uses smpi_process()->comm_world()
25  * instead of "this".
26  * This is basically how we only have one global variable but all processes have
27  * different communicators (the one their SMPI instance uses).
28  *
29  */
30 MPI_Comm MPI_COMM_WORLD = MPI_COMM_UNINITIALIZED;
31
32 /* Support for cartesian topology was added, but there are 2 other types of topology, graph et dist graph. In order to
33  * support them, we have to add a field SMPI_Topo_type, and replace the MPI_Topology field by an union. */
34
35 namespace simgrid{
36 namespace smpi{
37
38 std::unordered_map<int, smpi_key_elem> Comm::keyvals_;
39 int Comm::keyval_id_=0;
40
41 Comm::Comm(MPI_Group group, MPI_Topology topo, bool smp, int in_id)
42     : group_(group), topo_(topo), is_smp_comm_(smp), id_(in_id)
43 {
44   errhandler_->ref();
45   //First creation of comm is done before SIMIX_run, so only do comms for others
46   if(in_id==MPI_UNDEFINED && smp==0 && this->rank()!=MPI_UNDEFINED ){
47     this->add_f();
48     group->c2f();
49     int id;
50     if(this->rank()==0){
51       static int global_id_ = 0;
52       id=global_id_;
53       global_id_++;
54     }
55     colls::bcast(&id, 1, MPI_INT, 0, this);
56     XBT_DEBUG("Communicator %p has id %d", this, id);
57     id_=id;//only set here, as we don't want to change it in the middle of the bcast
58     colls::barrier(this);
59   }
60 }
61
62 void Comm::destroy(Comm* comm)
63 {
64   if (comm == MPI_COMM_UNINITIALIZED){
65     Comm::destroy(smpi_process()->comm_world());
66     return;
67   }
68   if (comm != MPI_COMM_WORLD && not comm->deleted()) {
69     comm->cleanup_attr<Comm>();
70     comm->mark_as_deleted();
71   }
72   Comm::unref(comm);
73 }
74
75 int Comm::dup(MPI_Comm* newcomm){
76   // we need to switch as the called function may silently touch global variables
77   smpi_switch_data_segment(s4u::Actor::self());
78
79   auto* cp     = new Group(this->group());
80   (*newcomm)   = new  Comm(cp, this->topo());
81
82   for (auto const& it : attributes()) {
83     auto elem_it = keyvals_.find(it.first);
84     xbt_assert(elem_it != keyvals_.end(), "Keyval not found for Comm: %d", it.first);
85
86     smpi_key_elem& elem = elem_it->second;
87     int ret             = MPI_SUCCESS;
88     int flag            = 0;
89     void* value_out     = nullptr;
90     if (elem.copy_fn.comm_copy_fn == MPI_COMM_DUP_FN) {
91       value_out = it.second;
92       flag      = 1;
93     } else if (elem.copy_fn.comm_copy_fn != MPI_NULL_COPY_FN) {
94       ret = elem.copy_fn.comm_copy_fn(this, it.first, elem.extra_state, it.second, &value_out, &flag);
95     }
96     if (elem.copy_fn.comm_copy_fn_fort != MPI_NULL_COPY_FN) {
97       value_out = xbt_new(int, 1);
98       if (*(int*)*elem.copy_fn.comm_copy_fn_fort == 1) { // MPI_COMM_DUP_FN
99         memcpy(value_out, it.second, sizeof(int));
100         flag = 1;
101       } else { // not null, nor dup
102         elem.copy_fn.comm_copy_fn_fort(this, it.first, elem.extra_state, it.second, value_out, &flag, &ret);
103       }
104       if (ret != MPI_SUCCESS)
105         xbt_free(value_out);
106     }
107     if (ret != MPI_SUCCESS) {
108       Comm::destroy(*newcomm);
109       *newcomm = MPI_COMM_NULL;
110       return ret;
111     }
112     if (flag) {
113       elem.refcount++;
114       (*newcomm)->attributes().emplace(it.first, value_out);
115     }
116   }
117   //duplicate info if present
118   if(info_!=MPI_INFO_NULL)
119     (*newcomm)->info_ = new simgrid::smpi::Info(info_);
120   //duplicate errhandler
121   if (errhandlers_ != nullptr)//MPI_COMM_WORLD, only grab our own
122     (*newcomm)->set_errhandler(errhandlers_[this->rank()]);
123   else
124     (*newcomm)->set_errhandler(errhandler_);
125   return MPI_SUCCESS;
126 }
127
128 int Comm::dup_with_info(MPI_Info info, MPI_Comm* newcomm){
129   int ret = dup(newcomm);
130   if(ret != MPI_SUCCESS)
131     return ret;
132   if((*newcomm)->info_!=MPI_INFO_NULL){
133     simgrid::smpi::Info::unref((*newcomm)->info_);
134     (*newcomm)->info_=MPI_INFO_NULL;
135   }
136   if(info != MPI_INFO_NULL){
137     info->ref();
138     (*newcomm)->info_=info;
139   }
140   return ret;
141 }
142
143 MPI_Group Comm::group()
144 {
145   if (this == MPI_COMM_UNINITIALIZED)
146     return smpi_process()->comm_world()->group();
147   return group_;
148 }
149
150 int Comm::size() const
151 {
152   if (this == MPI_COMM_UNINITIALIZED)
153     return smpi_process()->comm_world()->size();
154   return group_->size();
155 }
156
157 int Comm::rank() const
158 {
159   if (this == MPI_COMM_UNINITIALIZED)
160     return smpi_process()->comm_world()->rank();
161   return group_->rank(s4u::this_actor::get_pid());
162 }
163
164 int Comm::id() const
165 {
166   return id_;
167 }
168
169 void Comm::get_name(char* name, int* len) const
170 {
171   if (this == MPI_COMM_UNINITIALIZED){
172     smpi_process()->comm_world()->get_name(name, len);
173     return;
174   }
175   if(this == MPI_COMM_WORLD && name_.empty()) {
176     strncpy(name, "MPI_COMM_WORLD", 15);
177     *len = 14;
178   } else {
179     *len = snprintf(name, MPI_MAX_NAME_STRING+1, "%s", name_.c_str());
180   }
181 }
182
183 std::string Comm::name() const
184 {
185   int size;
186   std::array<char, MPI_MAX_NAME_STRING + 1> name;
187   this->get_name(name.data(), &size);
188   if (name[0]=='\0')
189     return std::string("MPI_Comm");
190   else
191     return std::string(name.data());
192 }
193
194
195 void Comm::set_name (const char* name)
196 {
197   if (this == MPI_COMM_UNINITIALIZED){
198     smpi_process()->comm_world()->set_name(name);
199     return;
200   }
201   name_.replace (0, MPI_MAX_NAME_STRING+1, name);
202 }
203
204
205 void Comm::set_leaders_comm(MPI_Comm leaders){
206   if (this == MPI_COMM_UNINITIALIZED){
207     smpi_process()->comm_world()->set_leaders_comm(leaders);
208     return;
209   }
210   leaders_comm_=leaders;
211 }
212
213 int* Comm::get_non_uniform_map() const
214 {
215   if (this == MPI_COMM_UNINITIALIZED)
216     return smpi_process()->comm_world()->get_non_uniform_map();
217   return non_uniform_map_;
218 }
219
220 int* Comm::get_leaders_map() const
221 {
222   if (this == MPI_COMM_UNINITIALIZED)
223     return smpi_process()->comm_world()->get_leaders_map();
224   return leaders_map_;
225 }
226
227 MPI_Comm Comm::get_leaders_comm() const
228 {
229   if (this == MPI_COMM_UNINITIALIZED)
230     return smpi_process()->comm_world()->get_leaders_comm();
231   return leaders_comm_;
232 }
233
234 MPI_Comm Comm::get_intra_comm() const
235 {
236   if (this == MPI_COMM_UNINITIALIZED || this==MPI_COMM_WORLD)
237     return smpi_process()->comm_intra();
238   else return intra_comm_;
239 }
240
241 bool Comm::is_uniform() const
242 {
243   if (this == MPI_COMM_UNINITIALIZED)
244     return smpi_process()->comm_world()->is_uniform();
245   return is_uniform_ != 0;
246 }
247
248 bool Comm::is_blocked() const
249 {
250   if (this == MPI_COMM_UNINITIALIZED)
251     return smpi_process()->comm_world()->is_blocked();
252   return is_blocked_ != 0;
253 }
254
255 bool Comm::is_smp_comm() const
256 {
257   if (this == MPI_COMM_UNINITIALIZED)
258     return smpi_process()->comm_world()->is_smp_comm();
259   return is_smp_comm_;
260 }
261
262 MPI_Comm Comm::split(int color, int key)
263 {
264   if (this == MPI_COMM_UNINITIALIZED)
265     return smpi_process()->comm_world()->split(color, key);
266   int system_tag = -123;
267
268   MPI_Group group_root = nullptr;
269   MPI_Group group_out  = nullptr;
270   const Group* group   = this->group();
271   int myrank           = this->rank();
272   int size             = this->size();
273   /* Gather all colors and keys on rank 0 */
274   const std::array<int, 2> sendbuf = {{color, key}};
275   std::vector<int> recvbuf;
276   if (myrank == 0)
277     recvbuf.resize(2 * size);
278   gather__default(sendbuf.data(), 2, MPI_INT, recvbuf.data(), 2, MPI_INT, 0, this);
279   /* Do the actual job */
280   if (myrank == 0) {
281     std::vector<MPI_Group> group_snd(size);
282     std::vector<std::pair<int, int>> rankmap;
283     rankmap.reserve(size);
284     for (int i = 0; i < size; i++) {
285       if (recvbuf[2 * i] != MPI_UNDEFINED) {
286         rankmap.clear();
287         for (int j = i + 1; j < size; j++) {
288           if(recvbuf[2 * i] == recvbuf[2 * j]) {
289             recvbuf[2 * j] = MPI_UNDEFINED;
290             rankmap.emplace_back(recvbuf[2 * j + 1], j);
291           }
292         }
293         /* Add self in the group */
294         recvbuf[2 * i] = MPI_UNDEFINED;
295         rankmap.emplace_back(recvbuf[2 * i + 1], i);
296         std::sort(begin(rankmap), end(rankmap));
297         group_out = new Group(rankmap.size());
298         if (i == 0) {
299           group_root = group_out; /* Save root's group */
300         }
301         for (unsigned j = 0; j < rankmap.size(); j++) {
302           aid_t actor = group->actor(rankmap[j].second);
303           group_out->set_mapping(actor, j);
304         }
305         std::vector<MPI_Request> requests(rankmap.size());
306         int reqs              = 0;
307         for (auto const& rank : rankmap) {
308           if (rank.second != 0) {
309             group_snd[reqs]=new  Group(group_out);
310             requests[reqs] = Request::isend(&(group_snd[reqs]), 1, MPI_PTR, rank.second, system_tag, this);
311             reqs++;
312           }
313         }
314         if(i != 0 && group_out != MPI_COMM_WORLD->group() && group_out != MPI_GROUP_EMPTY)
315           Group::unref(group_out);
316
317         Request::waitall(reqs, requests.data(), MPI_STATUS_IGNORE);
318       }
319     }
320     group_out = group_root; /* exit with root's group */
321   } else {
322     if(color != MPI_UNDEFINED) {
323       Request::recv(&group_out, 1, MPI_PTR, 0, system_tag, this, MPI_STATUS_IGNORE);
324     } /* otherwise, exit with group_out == nullptr */
325   }
326   return group_out!=nullptr ? new  Comm(group_out, topo_) : MPI_COMM_NULL;
327 }
328
329 void Comm::ref(){
330   if (this == MPI_COMM_UNINITIALIZED){
331     smpi_process()->comm_world()->ref();
332     return;
333   }
334   group_->ref();
335   refcount_++;
336 }
337
338 void Comm::cleanup_smp(){
339   if (intra_comm_ != MPI_COMM_NULL)
340     Comm::unref(intra_comm_);
341   if (leaders_comm_ != MPI_COMM_NULL)
342     Comm::unref(leaders_comm_);
343   xbt_free(non_uniform_map_);
344   delete[] leaders_map_;
345 }
346
347 void Comm::unref(Comm* comm){
348   if (comm == MPI_COMM_UNINITIALIZED){
349     Comm::unref(smpi_process()->comm_world());
350     return;
351   }
352   comm->refcount_--;
353
354   if(comm->refcount_==0){
355     if(simgrid::smpi::F2C::lookup() != nullptr)
356       F2C::free_f(comm->f2c_id());
357     comm->cleanup_smp();
358     comm->cleanup_attr<Comm>();
359     if (comm->info_ != MPI_INFO_NULL)
360       simgrid::smpi::Info::unref(comm->info_);
361     if(comm->errhandlers_!=nullptr){
362       for (int i=0; i<comm->size(); i++)
363         if (comm->errhandlers_[i]!=MPI_ERRHANDLER_NULL)
364           simgrid::smpi::Errhandler::unref(comm->errhandlers_[i]);
365       delete[] comm->errhandlers_;
366     } else if (comm->errhandler_ != MPI_ERRHANDLER_NULL)
367       simgrid::smpi::Errhandler::unref(comm->errhandler_);
368   }
369   Group::unref(comm->group_);
370   if(comm->refcount_==0)
371     delete comm;
372 }
373
374 MPI_Comm Comm::find_intra_comm(int * leader){
375   //get the indices of all processes sharing the same simix host
376   int intra_comm_size     = 0;
377   aid_t min_index         = std::numeric_limits<aid_t>::max(); // the minimum index will be the leader
378   sg_host_self()->get_impl()->foreach_actor([this, &intra_comm_size, &min_index](auto& actor) {
379     aid_t index = actor.get_pid();
380     if (this->group()->rank(index) != MPI_UNDEFINED) { // Is this process in the current group?
381       intra_comm_size++;
382       if (index < min_index)
383         min_index = index;
384     }
385   });
386   XBT_DEBUG("number of processes deployed on my node : %d", intra_comm_size);
387   auto* group_intra = new Group(intra_comm_size);
388   int i = 0;
389   sg_host_self()->get_impl()->foreach_actor([this, group_intra, &i](auto& actor) {
390     if (this->group()->rank(actor.get_pid()) != MPI_UNDEFINED) {
391       group_intra->set_mapping(actor.get_pid(), i);
392       i++;
393     }
394   });
395   *leader=min_index;
396   return new Comm(group_intra, nullptr, true);
397 }
398
399 void Comm::init_smp(){
400   int leader = -1;
401   int i = 0;
402   if (this == MPI_COMM_UNINITIALIZED)
403     smpi_process()->comm_world()->init_smp();
404
405   int comm_size = this->size();
406
407   // If we are in replay - perform an ugly hack
408   // tell SimGrid we are not in replay for a while, because we need the buffers to be copied for the following calls
409   bool replaying = false; //cache data to set it back again after
410   if(smpi_process()->replaying()){
411     replaying = true;
412     smpi_process()->set_replaying(false);
413   }
414
415   // we need to switch as the called function may silently touch global variables
416   smpi_switch_data_segment(s4u::Actor::self());
417
418   // identify neighbors in comm
419   MPI_Comm comm_intra = find_intra_comm(&leader);
420
421   auto* leaders_map = new int[comm_size];
422   auto* leader_list = new int[comm_size];
423   std::fill_n(leaders_map, comm_size, 0);
424   std::fill_n(leader_list, comm_size, -1);
425
426   allgather__ring(&leader, 1, MPI_INT , leaders_map, 1, MPI_INT, this);
427
428   if(leaders_map_==nullptr){
429     leaders_map_= leaders_map;
430   }else{
431     delete[] leaders_map;
432   }
433   int leader_group_size = 0;
434   for(i=0; i<comm_size; i++){
435     int already_done = 0;
436     for (int j = 0; j < leader_group_size; j++) {
437       if (leaders_map_[i] == leader_list[j]) {
438         already_done = 1;
439       }
440     }
441     if (already_done == 0) {
442       leader_list[leader_group_size] = leaders_map_[i];
443       leader_group_size++;
444     }
445   }
446   xbt_assert(leader_group_size > 0);
447   std::sort(leader_list, leader_list + leader_group_size);
448
449   auto* leaders_group = new Group(leader_group_size);
450
451   MPI_Comm leader_comm = MPI_COMM_NULL;
452   if(MPI_COMM_WORLD!=MPI_COMM_UNINITIALIZED && this!=MPI_COMM_WORLD){
453     //create leader_communicator
454     for (i=0; i< leader_group_size;i++)
455       leaders_group->set_mapping(leader_list[i], i);
456     leader_comm = new Comm(leaders_group, nullptr, true);
457     this->set_leaders_comm(leader_comm);
458     this->set_intra_comm(comm_intra);
459
460     // create intracommunicator
461   }else{
462     for (i=0; i< leader_group_size;i++)
463       leaders_group->set_mapping(leader_list[i], i);
464
465     if(this->get_leaders_comm()==MPI_COMM_NULL){
466       leader_comm = new Comm(leaders_group, nullptr, true);
467       this->set_leaders_comm(leader_comm);
468     }else{
469       leader_comm=this->get_leaders_comm();
470       Group::unref(leaders_group);
471     }
472     smpi_process()->set_comm_intra(comm_intra);
473   }
474
475   // Are the nodes uniform ? = same number of process/node
476   int my_local_size=comm_intra->size();
477   if(comm_intra->rank()==0) {
478     int is_uniform       = 1;
479     auto* non_uniform_map = xbt_new0(int, leader_group_size);
480     allgather__ring(&my_local_size, 1, MPI_INT,
481         non_uniform_map, 1, MPI_INT, leader_comm);
482     for(i=0; i < leader_group_size; i++) {
483       if(non_uniform_map[0] != non_uniform_map[i]) {
484         is_uniform = 0;
485         break;
486       }
487     }
488     if (is_uniform == 0 && this->is_uniform()) {
489       non_uniform_map_ = non_uniform_map;
490     }else{
491       xbt_free(non_uniform_map);
492     }
493     is_uniform_=is_uniform;
494   }
495   bcast__scatter_LR_allgather(&is_uniform_, 1, MPI_INT, 0, comm_intra);
496
497   // we need to switch as the called function may silently touch global variables
498   smpi_switch_data_segment(s4u::Actor::self());
499
500   // Are the ranks blocked ? = allocated contiguously on the SMP nodes
501   int is_blocked=1;
502   int prev      = this->group()->rank(comm_intra->group()->actor(0));
503   for (i = 1; i < my_local_size; i++) {
504     int that = this->group()->rank(comm_intra->group()->actor(i));
505     if (that != prev + 1) {
506       is_blocked = 0;
507       break;
508     }
509     prev = that;
510   }
511
512   int global_blocked;
513   allreduce__default(&is_blocked, &global_blocked, 1, MPI_INT, MPI_LAND, this);
514
515   if(MPI_COMM_WORLD==MPI_COMM_UNINITIALIZED || this==MPI_COMM_WORLD){
516     if(this->rank()==0){
517       is_blocked_ = global_blocked;
518     }
519   }else{
520     is_blocked_=global_blocked;
521   }
522   delete[] leader_list;
523
524   if(replaying)
525     smpi_process()->set_replaying(true);
526 }
527
528 MPI_Comm Comm::f2c(int id) {
529   if(id == -2) {
530     return MPI_COMM_SELF;
531   } else if(id==0){
532     return MPI_COMM_WORLD;
533   } else if (F2C::lookup() != nullptr && id >= 0) {
534     const auto& lookup = F2C::lookup();
535     auto comm          = lookup->find(id);
536     return comm == lookup->end() ? MPI_COMM_NULL : static_cast<MPI_Comm>(comm->second);
537   } else {
538     return MPI_COMM_NULL;
539   }
540 }
541
542 void Comm::free_f(int id) {
543   F2C::lookup()->erase(id);
544 }
545
546 void Comm::add_rma_win(MPI_Win win){
547   rma_wins_.push_back(win);
548 }
549
550 void Comm::remove_rma_win(MPI_Win win){
551   rma_wins_.remove(win);
552 }
553
554 void Comm::finish_rma_calls() const
555 {
556   const int myrank = rank();
557   for (auto const& it : rma_wins_) {
558     if (it->rank() == myrank) { // is it ours (for MPI_COMM_WORLD)?
559       int finished = it->finish_comms();
560       XBT_DEBUG("Barrier for rank %d - Finished %d RMA calls", myrank, finished);
561     }
562   }
563 }
564
565 MPI_Info Comm::info()
566 {
567   return info_;
568 }
569
570 void Comm::set_info(MPI_Info info)
571 {
572   if (info_ != MPI_INFO_NULL)
573     simgrid::smpi::Info::unref(info);
574   info_ = info;
575   if (info_ != MPI_INFO_NULL)
576     info->ref();
577 }
578
579 MPI_Errhandler Comm::errhandler()
580 {
581   if (this != MPI_COMM_WORLD){
582     if (errhandler_ != MPI_ERRHANDLER_NULL)
583       errhandler_->ref();
584     return errhandler_;
585   } else {
586     if(errhandlers_==nullptr){
587       if (_smpi_cfg_default_errhandler_is_error)
588         return MPI_ERRORS_ARE_FATAL;
589       else
590         return MPI_ERRORS_RETURN;
591     } else {
592       if(errhandlers_[this->rank()] != MPI_ERRHANDLER_NULL)
593         errhandlers_[this->rank()]->ref();
594       return errhandlers_[this->rank()];
595     }
596   }
597 }
598
599 void Comm::set_errhandler(MPI_Errhandler errhandler)
600 {
601   if(this != MPI_COMM_WORLD){
602     if (errhandler_ != MPI_ERRHANDLER_NULL)
603       simgrid::smpi::Errhandler::unref(errhandler_);
604     errhandler_ = errhandler;
605   }else{
606     if(errhandlers_==nullptr)
607       errhandlers_= new MPI_Errhandler[this->size()]{MPI_ERRHANDLER_NULL};
608     if(errhandlers_[this->rank()] != MPI_ERRHANDLER_NULL)
609       simgrid::smpi::Errhandler::unref(errhandlers_[this->rank()]);
610     errhandlers_[this->rank()]=errhandler;
611   }
612   if (errhandler != MPI_ERRHANDLER_NULL)
613     errhandler->ref();
614 }
615
616 MPI_Comm Comm::split_type(int type, int /*key*/, const Info*)
617 {
618   //MPI_UNDEFINED can be given to some nodes... but we need them to still perform the smp part which is collective
619   if(type != MPI_COMM_TYPE_SHARED && type != MPI_UNDEFINED){
620     return MPI_COMM_NULL;
621   }
622   int leader=0;
623   MPI_Comm res= this->find_intra_comm(&leader);
624   if(type != MPI_UNDEFINED)
625     return res;
626   else{
627     xbt_assert(res->refcount_ == 1); // ensure the next call to Comm::destroy really frees the comm
628     Comm::destroy(res);
629     return MPI_COMM_NULL;
630   }
631 }
632
633 } // namespace smpi
634 } // namespace simgrid