Logo AND Algorithmique Numérique Distribuée

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