Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2022.
[simgrid.git] / src / smpi / mpi / smpi_request.cpp
1 /* Copyright (c) 2007-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_request.hpp"
7
8 #include "mc/mc.h"
9 #include "private.hpp"
10 #include "simgrid/Exception.hpp"
11 #include "simgrid/s4u/Exec.hpp"
12 #include "simgrid/s4u/Mutex.hpp"
13 #include "simgrid/s4u/ConditionVariable.hpp"
14 #include "smpi_comm.hpp"
15 #include "smpi_datatype.hpp"
16 #include "smpi_host.hpp"
17 #include "smpi_op.hpp"
18 #include "src/kernel/activity/CommImpl.hpp"
19 #include "src/mc/mc_replay.hpp"
20 #include "src/smpi/include/smpi_actor.hpp"
21
22 #include <algorithm>
23 #include <array>
24
25 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_request, smpi, "Logging specific to SMPI (request)");
26
27 static simgrid::config::Flag<double> smpi_iprobe_sleep(
28   "smpi/iprobe", "Minimum time to inject inside a call to MPI_Iprobe", 1e-4);
29 static simgrid::config::Flag<double> smpi_test_sleep(
30   "smpi/test", "Minimum time to inject inside a call to MPI_Test", 1e-4);
31
32 std::vector<s_smpi_factor_t> smpi_ois_values;
33
34 extern void (*smpi_comm_copy_data_callback)(simgrid::kernel::activity::CommImpl*, void*, size_t);
35
36 namespace simgrid{
37 namespace smpi{
38
39 Request::Request(const void* buf, int count, MPI_Datatype datatype, aid_t src, aid_t dst, int tag, MPI_Comm comm,
40                  unsigned flags, MPI_Op op)
41     : buf_(const_cast<void*>(buf))
42     , old_buf_(buf_)
43     , type_(datatype)
44     , size_(datatype->size() * count)
45     , src_(src)
46     , dst_(dst)
47     , tag_(tag)
48     , comm_(comm)
49     , flags_(flags)
50     , op_(op)
51 {
52   datatype->ref();
53   comm_->ref();
54   if(op != MPI_REPLACE && op != MPI_OP_NULL)
55     op_->ref();
56   action_          = nullptr;
57   detached_        = false;
58   detached_sender_ = nullptr;
59   real_src_        = 0;
60   // get src_host if it's available (src is valid)
61   auto src_process = simgrid::s4u::Actor::by_pid(src);
62   if (src_process)
63     src_host_ = src_process->get_host();
64   truncated_       = false;
65   unmatched_types_ = false;
66   real_size_       = 0;
67   real_tag_        = 0;
68   if (flags & MPI_REQ_PERSISTENT)
69     refcount_ = 1;
70   else
71     refcount_ = 0;
72   init_buffer(count);
73   this->add_f();
74 }
75
76 void Request::ref(){
77   refcount_++;
78 }
79
80 void Request::unref(MPI_Request* request)
81 {
82   xbt_assert(*request != MPI_REQUEST_NULL, "freeing an already free request");
83
84   (*request)->refcount_--;
85   if ((*request)->refcount_ < 0) {
86     (*request)->print_request("wrong refcount");
87     xbt_die("Whoops, wrong refcount");
88   }
89   if ((*request)->refcount_ == 0) {
90     if ((*request)->flags_ & MPI_REQ_GENERALIZED) {
91       ((*request)->generalized_funcs)->free_fn(((*request)->generalized_funcs)->extra_state);
92     } else {
93       Comm::unref((*request)->comm_);
94       Datatype::unref((*request)->type_);
95     }
96     if ((*request)->op_ != MPI_REPLACE && (*request)->op_ != MPI_OP_NULL)
97       Op::unref(&(*request)->op_);
98
99     (*request)->print_request("Destroying");
100     F2C::free_f((*request)->f2c_id());
101     delete *request;
102     *request = MPI_REQUEST_NULL;
103   } else {
104     (*request)->print_request("Decrementing");
105   }
106 }
107
108 bool Request::match_types(MPI_Datatype stype, MPI_Datatype rtype){
109   bool match = false;
110   if ((stype == rtype) ||
111      //byte and packed always match with anything
112      (stype == MPI_PACKED || rtype == MPI_PACKED || stype == MPI_BYTE || rtype == MPI_BYTE) ||
113      //complex datatypes - we don't properly match these yet, as it would mean checking each subtype recursively.
114      (stype->flags() & DT_FLAG_DERIVED || rtype->flags() & DT_FLAG_DERIVED) ||
115      //duplicated datatypes, check if underlying is ok
116      (stype->duplicated_datatype()!=MPI_DATATYPE_NULL && match_types(stype->duplicated_datatype(), rtype)) ||
117      (rtype->duplicated_datatype()!=MPI_DATATYPE_NULL && match_types(stype, rtype->duplicated_datatype())))
118     match = true;
119   if (!match)
120     XBT_WARN("Mismatched datatypes : sending %s and receiving %s", stype->name().c_str(), rtype->name().c_str());
121   return match;
122 }
123
124
125 bool Request::match_common(MPI_Request req, MPI_Request sender, MPI_Request receiver)
126 {
127   xbt_assert(sender, "Cannot match against null sender");
128   xbt_assert(receiver, "Cannot match against null receiver");
129   XBT_DEBUG("Trying to match %s of sender src %ld against %ld, tag %d against %d, id %d against %d",
130             (req == receiver ? "send" : "recv"), sender->src_, receiver->src_, sender->tag_, receiver->tag_,
131             sender->comm_->id(), receiver->comm_->id());
132
133   if ((receiver->comm_->id() == MPI_UNDEFINED || sender->comm_->id() == MPI_UNDEFINED ||
134        receiver->comm_->id() == sender->comm_->id()) &&
135       ((receiver->src_ == MPI_ANY_SOURCE && (receiver->comm_->group()->rank(sender->src_) != MPI_UNDEFINED)) ||
136        receiver->src_ == sender->src_) &&
137       ((receiver->tag_ == MPI_ANY_TAG && sender->tag_ >= 0) || receiver->tag_ == sender->tag_)) {
138     // we match, we can transfer some values
139     if (receiver->src_ == MPI_ANY_SOURCE) {
140       receiver->real_src_ = sender->src_;
141       receiver->src_host_ = sender->src_host_;
142     }
143     if (receiver->tag_ == MPI_ANY_TAG)
144       receiver->real_tag_ = sender->tag_;
145     if ((receiver->flags_ & MPI_REQ_PROBE) == 0 ){
146       if (receiver->real_size_ < sender->real_size_){
147         XBT_DEBUG("Truncating message - should not happen: receiver size : %zu < sender size : %zu", receiver->real_size_, sender->real_size_);
148         receiver->truncated_ = true;
149       } else if (receiver->real_size_ > sender->real_size_){
150         receiver->real_size_=sender->real_size_;
151       }
152     }
153     //0-sized datatypes/counts should not interfere and match
154     if ( sender->real_size_ != 0 && receiver->real_size_ != 0 &&
155          !match_types(sender->type_, receiver->type_))
156       receiver->unmatched_types_ = true;
157     if (sender->detached_)
158       receiver->detached_sender_ = sender; // tie the sender to the receiver, as it is detached and has to be freed in
159                                            // the receiver
160     req->flags_ |= MPI_REQ_MATCHED; // mark as impossible to cancel anymore
161     XBT_DEBUG("match succeeded");
162     return true;
163   }
164   return false;
165 }
166
167 void Request::init_buffer(int count){
168 // FIXME Handle the case of a partial shared malloc.
169   // This part handles the problem of non-contiguous memory (for the unserialization at the reception)
170   if (not smpi_process()->replaying() &&
171      ((((flags_ & MPI_REQ_RECV) != 0) && ((flags_ & MPI_REQ_ACCUMULATE) != 0)) || (type_->flags() & DT_FLAG_DERIVED))) {
172     // This part handles the problem of non-contiguous memory
173     old_buf_ = buf_;
174     if (count==0){
175       buf_ = nullptr;
176     }else {
177       buf_ = xbt_malloc(count*type_->size());
178       if ((type_->flags() & DT_FLAG_DERIVED) && ((flags_ & MPI_REQ_SEND) != 0)) {
179         type_->serialize(old_buf_, buf_, count);
180       }
181     }
182   }
183 }
184
185 bool Request::match_recv(void* a, void* b, simgrid::kernel::activity::CommImpl*)
186 {
187   auto ref = static_cast<MPI_Request>(a);
188   auto req = static_cast<MPI_Request>(b);
189   return match_common(req, req, ref);
190 }
191
192 bool Request::match_send(void* a, void* b, simgrid::kernel::activity::CommImpl*)
193 {
194   auto ref = static_cast<MPI_Request>(a);
195   auto req = static_cast<MPI_Request>(b);
196   return match_common(req, ref, req);
197 }
198
199 void Request::print_request(const char* message) const
200 {
201   XBT_VERB("%s  request %p  [buf = %p, size = %zu, src = %ld, dst = %ld, tag = %d, flags = %x]", message, this, buf_,
202            size_, src_, dst_, tag_, flags_);
203 }
204
205 /* factories, to hide the internal flags from the caller */
206 MPI_Request Request::bsend_init(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
207 {
208   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
209                      dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
210                      MPI_REQ_PERSISTENT | MPI_REQ_SEND | MPI_REQ_PREPARED | MPI_REQ_BSEND);
211 }
212
213 MPI_Request Request::send_init(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
214 {
215   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
216                      dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
217                      MPI_REQ_PERSISTENT | MPI_REQ_SEND | MPI_REQ_PREPARED);
218 }
219
220 MPI_Request Request::ssend_init(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
221 {
222   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
223                      dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
224                      MPI_REQ_PERSISTENT | MPI_REQ_SSEND | MPI_REQ_SEND | MPI_REQ_PREPARED);
225 }
226
227 MPI_Request Request::isend_init(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
228 {
229   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
230                      dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
231                      MPI_REQ_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_PREPARED);
232 }
233
234 MPI_Request Request::rma_send_init(const void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
235                                MPI_Op op)
236 {
237   MPI_Request request;
238   if(op==MPI_OP_NULL){
239     request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src),
240                           dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
241                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_PREPARED);
242   }else{
243     request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src),
244                           dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
245                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_PREPARED |
246                               MPI_REQ_ACCUMULATE,
247                           op);
248   }
249   return request;
250 }
251
252 MPI_Request Request::recv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
253 {
254   aid_t source = MPI_PROC_NULL;
255   if (src == MPI_ANY_SOURCE)
256     source = MPI_ANY_SOURCE;
257   else if (src != MPI_PROC_NULL)
258     source = comm->group()->actor(src);
259   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype,
260                      source,
261                      simgrid::s4u::this_actor::get_pid(), tag, comm,
262                      MPI_REQ_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED);
263 }
264
265 MPI_Request Request::rma_recv_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
266                                MPI_Op op)
267 {
268   aid_t source        = MPI_PROC_NULL;
269   if (src == MPI_ANY_SOURCE)
270     source = MPI_ANY_SOURCE;
271   else if (src != MPI_PROC_NULL)
272     source = comm->group()->actor(src);
273   MPI_Request request;
274   if(op==MPI_OP_NULL){
275     request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, source,
276                           dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
277                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED);
278   }else{
279     request =
280         new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, source,
281                     dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
282                     MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED | MPI_REQ_ACCUMULATE, op);
283   }
284   return request;
285 }
286
287 MPI_Request Request::irecv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
288 {
289   aid_t source = MPI_PROC_NULL;
290   if (src == MPI_ANY_SOURCE)
291     source = MPI_ANY_SOURCE;
292   else if (src != MPI_PROC_NULL)
293     source = comm->group()->actor(src);
294   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype,
295                      source, simgrid::s4u::this_actor::get_pid(), tag, comm,
296                      MPI_REQ_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED);
297 }
298
299 MPI_Request Request::ibsend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
300 {
301   auto request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
302                              dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
303                              MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_BSEND);
304   if(dst != MPI_PROC_NULL)
305     request->start();
306   return request;
307 }
308
309 MPI_Request Request::isend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
310 {
311   auto request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
312                              dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
313                              MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND);
314   if(dst != MPI_PROC_NULL)
315     request->start();
316   return request;
317 }
318
319 MPI_Request Request::issend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
320 {
321   auto request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
322                              dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
323                              MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SSEND | MPI_REQ_SEND);
324   if(dst != MPI_PROC_NULL)
325     request->start();
326   return request;
327 }
328
329 MPI_Request Request::irecv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
330 {
331   aid_t source        = MPI_PROC_NULL;
332   if (src == MPI_ANY_SOURCE)
333     source = MPI_ANY_SOURCE;
334   else if (src != MPI_PROC_NULL)
335     source = comm->group()->actor(src);
336   auto request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, source,
337                              simgrid::s4u::this_actor::get_pid(), tag, comm, MPI_REQ_NON_PERSISTENT | MPI_REQ_RECV);
338   if(src != MPI_PROC_NULL)
339     request->start();
340   return request;
341 }
342
343 int Request::recv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm, MPI_Status * status)
344 {
345   MPI_Request request = irecv(buf, count, datatype, src, tag, comm);
346   int retval = wait(&request,status);
347   request = nullptr;
348   return retval;
349 }
350
351 void Request::bsend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
352 {
353   auto request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
354                              dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
355                              MPI_REQ_NON_PERSISTENT | MPI_REQ_SEND | MPI_REQ_BSEND);
356
357   if(dst != MPI_PROC_NULL)
358    request->start();
359   wait(&request, MPI_STATUS_IGNORE);
360   request = nullptr;
361 }
362
363 void Request::send(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
364 {
365   auto request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
366                              dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
367                              MPI_REQ_NON_PERSISTENT | MPI_REQ_SEND);
368   if(dst != MPI_PROC_NULL)
369    request->start();
370   wait(&request, MPI_STATUS_IGNORE);
371   request = nullptr;
372 }
373
374 void Request::ssend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
375 {
376   auto request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
377                              dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL, tag, comm,
378                              MPI_REQ_NON_PERSISTENT | MPI_REQ_SSEND | MPI_REQ_SEND);
379
380   if(dst != MPI_PROC_NULL)
381    request->start();
382   wait(&request,MPI_STATUS_IGNORE);
383   request = nullptr;
384 }
385
386 void Request::sendrecv(const void *sendbuf, int sendcount, MPI_Datatype sendtype,int dst, int sendtag,
387                        void *recvbuf, int recvcount, MPI_Datatype recvtype, int src, int recvtag,
388                        MPI_Comm comm, MPI_Status * status)
389 {
390   aid_t source = MPI_PROC_NULL;
391   if (src == MPI_ANY_SOURCE)
392     source = MPI_ANY_SOURCE;
393   else if (src != MPI_PROC_NULL)
394     source = comm->group()->actor(src);
395   aid_t destination = dst != MPI_PROC_NULL ? comm->group()->actor(dst) : MPI_PROC_NULL;
396
397   std::array<MPI_Request, 2> requests;
398   std::array<MPI_Status, 2> stats;
399   aid_t myid = simgrid::s4u::this_actor::get_pid();
400   if ((destination == myid) && (source == myid)) {
401     Datatype::copy(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype);
402     if (status != MPI_STATUS_IGNORE) {
403       status->MPI_SOURCE = source;
404       status->MPI_TAG    = recvtag;
405       status->MPI_ERROR  = MPI_SUCCESS;
406       status->count      = sendcount * sendtype->size();
407     }
408     return;
409   }
410   requests[0] = isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
411   requests[1] = irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
412   startall(2, requests.data());
413   waitall(2, requests.data(), stats.data());
414   unref(&requests[0]);
415   unref(&requests[1]);
416   if(status != MPI_STATUS_IGNORE) {
417     // Copy receive status
418     *status = stats[1];
419   }
420 }
421
422 void Request::start()
423 {
424   s4u::Mailbox* mailbox;
425
426   xbt_assert(action_ == nullptr, "Cannot (re-)start unfinished communication");
427   //reinitialize temporary buffer for persistent requests
428   if(real_size_ > 0 && flags_ & MPI_REQ_FINISHED){
429     buf_ = old_buf_;
430     init_buffer(real_size_/type_->size());
431   }
432   flags_ &= ~MPI_REQ_PREPARED;
433   flags_ &= ~MPI_REQ_FINISHED;
434   this->ref();
435
436   // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
437   real_size_=size_;
438   if ((flags_ & MPI_REQ_RECV) != 0) {
439     this->print_request("New recv");
440
441     simgrid::smpi::ActorExt* process = smpi_process_remote(simgrid::s4u::Actor::by_pid(dst_));
442
443     simgrid::s4u::MutexPtr mut = process->mailboxes_mutex();
444     if (smpi_cfg_async_small_thresh() != 0 || (flags_ & MPI_REQ_RMA) != 0)
445       mut->lock();
446
447     if (smpi_cfg_async_small_thresh() == 0 && (flags_ & MPI_REQ_RMA) == 0) {
448       mailbox = process->mailbox();
449     } else if (((flags_ & MPI_REQ_RMA) != 0) || static_cast<int>(size_) < smpi_cfg_async_small_thresh()) {
450       //We have to check both mailboxes (because SSEND messages are sent to the large mbox).
451       //begin with the more appropriate one : the small one.
452       mailbox = process->mailbox_small();
453       XBT_DEBUG("Is there a corresponding send already posted in the small mailbox %s (in case of SSEND)?",
454                 mailbox->get_cname());
455       simgrid::kernel::activity::ActivityImplPtr action = mailbox->iprobe(0, &match_recv, static_cast<void*>(this));
456
457       if (action == nullptr) {
458         mailbox = process->mailbox();
459         XBT_DEBUG("No, nothing in the small mailbox test the other one : %s", mailbox->get_cname());
460         action = mailbox->iprobe(0, &match_recv, static_cast<void*>(this));
461         if (action == nullptr) {
462           XBT_DEBUG("Still nothing, switch back to the small mailbox : %s", mailbox->get_cname());
463           mailbox = process->mailbox_small();
464         }
465       } else {
466         XBT_DEBUG("yes there was something for us in the large mailbox");
467       }
468     } else {
469       mailbox = process->mailbox_small();
470       XBT_DEBUG("Is there a corresponding send already posted the small mailbox?");
471       simgrid::kernel::activity::ActivityImplPtr action = mailbox->iprobe(0, &match_recv, static_cast<void*>(this));
472
473       if (action == nullptr) {
474         XBT_DEBUG("No, nothing in the permanent receive mailbox");
475         mailbox = process->mailbox();
476       } else {
477         XBT_DEBUG("yes there was something for us in the small mailbox");
478       }
479     }
480
481     action_   = simcall_comm_irecv(
482         process->get_actor()->get_impl(), mailbox->get_impl(), buf_, &real_size_, &match_recv,
483         process->replaying() ? &smpi_comm_null_copy_buffer_callback : smpi_comm_copy_data_callback, this, -1.0);
484     XBT_DEBUG("recv simcall posted");
485
486     if (smpi_cfg_async_small_thresh() != 0 || (flags_ & MPI_REQ_RMA) != 0)
487       mut->unlock();
488   } else { /* the RECV flag was not set, so this is a send */
489     const simgrid::smpi::ActorExt* process = smpi_process_remote(simgrid::s4u::Actor::by_pid(dst_));
490     xbt_assert(process, "Actor pid=%ld is gone??", dst_);
491     if (TRACE_smpi_view_internals())
492       TRACE_smpi_send(src_, src_, dst_, tag_, size_);
493     this->print_request("New send");
494
495     void* buf = buf_;
496     if ((flags_ & MPI_REQ_SSEND) == 0 &&
497         ((flags_ & MPI_REQ_RMA) != 0 || (flags_ & MPI_REQ_BSEND) != 0 ||
498          static_cast<int>(size_) < smpi_cfg_detached_send_thresh())) {
499       void *oldbuf = nullptr;
500       detached_    = true;
501       XBT_DEBUG("Send request %p is detached", this);
502       this->ref();
503       if (not(type_->flags() & DT_FLAG_DERIVED)) {
504         oldbuf = buf_;
505         if (not process->replaying() && oldbuf != nullptr && size_ != 0) {
506           if (smpi_switch_data_segment(simgrid::s4u::Actor::by_pid(src_), buf_))
507             XBT_DEBUG("Privatization : We are sending from a zone inside global memory. Switch data segment ");
508
509           //we need this temporary buffer even for bsend, as it will be released in the copy callback and we don't have a way to differentiate it
510           //so actually ... don't use manually attached buffer space.
511           buf = xbt_malloc(size_);
512           memcpy(buf,oldbuf,size_);
513           XBT_DEBUG("buf %p copied into %p",oldbuf,buf);
514         }
515       }
516     }
517
518     //if we are giving back the control to the user without waiting for completion, we have to inject timings
519     double sleeptime = 0.0;
520     if (detached_ || ((flags_ & (MPI_REQ_ISEND | MPI_REQ_SSEND)) != 0)) { // issend should be treated as isend
521       // isend and send timings may be different
522       sleeptime =
523           ((flags_ & MPI_REQ_ISEND) != 0)
524               ? simgrid::s4u::Actor::self()->get_host()->extension<simgrid::smpi::Host>()->oisend(
525                     size_, simgrid::s4u::Actor::by_pid(src_)->get_host(), simgrid::s4u::Actor::by_pid(dst_)->get_host())
526               : simgrid::s4u::Actor::self()->get_host()->extension<simgrid::smpi::Host>()->osend(
527                     size_, simgrid::s4u::Actor::by_pid(src_)->get_host(),
528                     simgrid::s4u::Actor::by_pid(dst_)->get_host());
529     }
530
531     if(sleeptime > 0.0){
532       simgrid::s4u::this_actor::sleep_for(sleeptime);
533       XBT_DEBUG("sending size of %zu : sleep %f ", size_, sleeptime);
534     }
535
536     simgrid::s4u::MutexPtr mut = process->mailboxes_mutex();
537
538     if (smpi_cfg_async_small_thresh() != 0 || (flags_ & MPI_REQ_RMA) != 0)
539       mut->lock();
540
541     if (not(smpi_cfg_async_small_thresh() != 0 || (flags_ & MPI_REQ_RMA) != 0)) {
542       mailbox = process->mailbox();
543     } else if (((flags_ & MPI_REQ_RMA) != 0) || static_cast<int>(size_) < smpi_cfg_async_small_thresh()) { // eager mode
544       mailbox = process->mailbox();
545       XBT_DEBUG("Is there a corresponding recv already posted in the large mailbox %s?", mailbox->get_cname());
546       simgrid::kernel::activity::ActivityImplPtr action = mailbox->iprobe(1, &match_send, static_cast<void*>(this));
547       if (action == nullptr) {
548         if ((flags_ & MPI_REQ_SSEND) == 0) {
549           mailbox = process->mailbox_small();
550           XBT_DEBUG("No, nothing in the large mailbox, message is to be sent on the small one %s",
551                     mailbox->get_cname());
552         } else {
553           mailbox = process->mailbox_small();
554           XBT_DEBUG("SSEND : Is there a corresponding recv already posted in the small mailbox %s?",
555                     mailbox->get_cname());
556           action = mailbox->iprobe(1, &match_send, static_cast<void*>(this));
557           if (action == nullptr) {
558             XBT_DEBUG("No, we are first, send to large mailbox");
559             mailbox = process->mailbox();
560           }
561         }
562       } else {
563         XBT_DEBUG("Yes there was something for us in the large mailbox");
564       }
565     } else {
566       mailbox = process->mailbox();
567       XBT_DEBUG("Send request %p is in the large mailbox %s (buf: %p)", this, mailbox->get_cname(), buf_);
568     }
569
570     size_t payload_size_ = size_ + 16;//MPI enveloppe size (tag+dest+communicator)
571     action_              = simcall_comm_isend(
572         simgrid::kernel::actor::ActorImpl::by_pid(src_), mailbox->get_impl(), payload_size_, -1.0, buf, real_size_,
573         &match_send,
574         &xbt_free_f, // how to free the userdata if a detached send fails
575         process->replaying() ? &smpi_comm_null_copy_buffer_callback : smpi_comm_copy_data_callback, this,
576         // detach if msg size < eager/rdv switch limit
577         detached_);
578     XBT_DEBUG("send simcall posted");
579
580     /* FIXME: detached sends are not traceable (action_ == nullptr) */
581     if (action_ != nullptr) {
582       boost::static_pointer_cast<kernel::activity::CommImpl>(action_)->set_tracing_category(
583           smpi_process()->get_tracing_category());
584     }
585
586     if (smpi_cfg_async_small_thresh() != 0 || ((flags_ & MPI_REQ_RMA) != 0))
587       mut->unlock();
588   }
589 }
590
591 void Request::startall(int count, MPI_Request * requests)
592 {
593   if(requests== nullptr)
594     return;
595
596   for(int i = 0; i < count; i++) {
597     if(requests[i]->src_ != MPI_PROC_NULL && requests[i]->dst_ != MPI_PROC_NULL)
598       requests[i]->start();
599   }
600 }
601
602 void Request::cancel()
603 {
604   this->flags_ |= MPI_REQ_CANCELLED;
605   if (this->action_ != nullptr)
606     (boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(this->action_))->cancel();
607 }
608
609 int Request::test(MPI_Request * request, MPI_Status * status, int* flag) {
610   // assume that *request is not MPI_REQUEST_NULL (filtered in PMPI_Test or testall before)
611   // to avoid deadlocks if used as a break condition, such as
612   //     while (MPI_Test(request, flag, status) && flag) dostuff...
613   // because the time will not normally advance when only calls to MPI_Test are made -> deadlock
614   // multiplier to the sleeptime, to increase speed of execution, each failed test will increase it
615   xbt_assert(*request != MPI_REQUEST_NULL);
616
617   static int nsleeps = 1;
618   int ret = MPI_SUCCESS;
619
620   if(smpi_test_sleep > 0)
621     simgrid::s4u::this_actor::sleep_for(nsleeps * smpi_test_sleep);
622
623   Status::empty(status);
624   *flag = 1;
625
626   if ((*request)->flags_ & MPI_REQ_NBC){
627     *flag = finish_nbc_requests(request, 1);
628   }
629
630   if (((*request)->flags_ & (MPI_REQ_PREPARED | MPI_REQ_FINISHED)) == 0) {
631     if ((*request)->action_ != nullptr && ((*request)->flags_ & MPI_REQ_CANCELLED) == 0){
632       try{
633         *flag = simcall_comm_test((*request)->action_.get());
634       } catch (const Exception&) {
635         *flag = 0;
636         return ret;
637       }
638     }
639     if (((*request)->flags_ & MPI_REQ_GENERALIZED) && not((*request)->flags_ & MPI_REQ_COMPLETE))
640       *flag=0;
641     if (*flag) {
642       finish_wait(request, status); // may invalidate *request
643       if (*request != MPI_REQUEST_NULL && ((*request)->flags_ & MPI_REQ_GENERALIZED)){
644         MPI_Status tmp_status;
645         MPI_Status* mystatus;
646         if (status == MPI_STATUS_IGNORE) {
647           mystatus = &tmp_status;
648           Status::empty(mystatus);
649         } else {
650           mystatus = status;
651         }
652         ret = ((*request)->generalized_funcs)->query_fn(((*request)->generalized_funcs)->extra_state, mystatus);
653       }
654       nsleeps=1;//reset the number of sleeps we will do next time
655       if (*request != MPI_REQUEST_NULL && ((*request)->flags_ & MPI_REQ_PERSISTENT) == 0)
656         *request = MPI_REQUEST_NULL;
657     } else if (smpi_cfg_grow_injected_times()) {
658       nsleeps++;
659     }
660   }
661   return ret;
662 }
663
664 int Request::testsome(int incount, MPI_Request requests[], int *count, int *indices, MPI_Status status[])
665 {
666   int error=0;
667   int count_dead = 0;
668   int flag = 0;
669   MPI_Status stat;
670   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
671
672   *count = 0;
673   for (int i = 0; i < incount; i++) {
674     if (requests[i] != MPI_REQUEST_NULL && not (requests[i]->flags_ & MPI_REQ_FINISHED)) {
675       int ret = test(&requests[i], pstat, &flag);
676       if(ret!=MPI_SUCCESS)
677         error = 1;
678       if(flag) {
679         indices[*count] = i;
680         if (status != MPI_STATUSES_IGNORE)
681           status[*count] = *pstat;
682         (*count)++;
683         if ((requests[i] != MPI_REQUEST_NULL) && (requests[i]->flags_ & MPI_REQ_NON_PERSISTENT))
684           requests[i] = MPI_REQUEST_NULL;
685       }
686     } else {
687       count_dead++;
688     }
689   }
690   if(count_dead==incount)*count=MPI_UNDEFINED;
691   if(error!=0)
692     return MPI_ERR_IN_STATUS;
693   else
694     return MPI_SUCCESS;
695 }
696
697 int Request::testany(int count, MPI_Request requests[], int *index, int* flag, MPI_Status * status)
698 {
699   std::vector<simgrid::kernel::activity::CommImpl*> comms;
700   comms.reserve(count);
701
702   *flag = 0;
703   int ret = MPI_SUCCESS;
704   *index = MPI_UNDEFINED;
705
706   std::vector<int> map; /** Maps all matching comms back to their location in requests **/
707   for (int i = 0; i < count; i++) {
708     if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->action_ && not(requests[i]->flags_ & MPI_REQ_PREPARED)) {
709       comms.push_back(static_cast<simgrid::kernel::activity::CommImpl*>(requests[i]->action_.get()));
710       map.push_back(i);
711     }
712   }
713   if (not map.empty()) {
714     //multiplier to the sleeptime, to increase speed of execution, each failed testany will increase it
715     static int nsleeps = 1;
716     if(smpi_test_sleep > 0)
717       simgrid::s4u::this_actor::sleep_for(nsleeps * smpi_test_sleep);
718     ssize_t i;
719     try{
720       i = simcall_comm_testany(comms.data(), comms.size()); // The i-th element in comms matches!
721     } catch (const Exception&) {
722       XBT_DEBUG("Exception in testany");
723       return 0;
724     }
725
726     if (i != -1) { // -1 is not MPI_UNDEFINED but a SIMIX return code. (nothing matches)
727       *index = map[i];
728       if (requests[*index] != MPI_REQUEST_NULL && (requests[*index]->flags_ & MPI_REQ_GENERALIZED) &&
729           not(requests[*index]->flags_ & MPI_REQ_COMPLETE)) {
730         *flag=0;
731       } else {
732         finish_wait(&requests[*index],status);
733       if (requests[*index] != MPI_REQUEST_NULL && (requests[*index]->flags_ & MPI_REQ_GENERALIZED)){
734         MPI_Status tmp_status;
735         MPI_Status* mystatus;
736         if (status == MPI_STATUS_IGNORE) {
737           mystatus = &tmp_status;
738           Status::empty(mystatus);
739         } else {
740           mystatus = status;
741         }
742         ret=(requests[*index]->generalized_funcs)->query_fn((requests[*index]->generalized_funcs)->extra_state, mystatus);
743       }
744
745       if (requests[*index] != MPI_REQUEST_NULL && requests[*index]->flags_ & MPI_REQ_NBC){
746         *flag = finish_nbc_requests(&requests[*index] , 1);
747       }
748
749       if (requests[*index] != MPI_REQUEST_NULL && (requests[*index]->flags_ & MPI_REQ_NON_PERSISTENT))
750           requests[*index] = MPI_REQUEST_NULL;
751         XBT_DEBUG("Testany - returning with index %d", *index);
752         *flag=1;
753       }
754       nsleeps = 1;
755     } else {
756       nsleeps++;
757     }
758   } else {
759       XBT_DEBUG("Testany on inactive handles, returning flag=1 but empty status");
760       //all requests are null or inactive, return true
761       *flag = 1;
762       *index = MPI_UNDEFINED;
763       Status::empty(status);
764   }
765
766   return ret;
767 }
768
769 int Request::testall(int count, MPI_Request requests[], int* outflag, MPI_Status status[])
770 {
771   MPI_Status stat;
772   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
773   int flag;
774   int error = 0;
775   *outflag = 1;
776   for(int i=0; i<count; i++){
777     if (requests[i] != MPI_REQUEST_NULL && not(requests[i]->flags_ & MPI_REQ_PREPARED)) {
778       int ret = test(&requests[i], pstat, &flag);
779       if (flag){
780         flag=0;
781       }else{
782         *outflag=0;
783       }
784       if (ret != MPI_SUCCESS)
785         error = 1;
786     }else{
787       Status::empty(pstat);
788     }
789     if(status != MPI_STATUSES_IGNORE) {
790       status[i] = *pstat;
791     }
792   }
793   if (error == 1)
794     return MPI_ERR_IN_STATUS;
795   else
796     return MPI_SUCCESS;
797 }
798
799 void Request::probe(int source, int tag, MPI_Comm comm, MPI_Status* status){
800   int flag=0;
801   //FIXME find another way to avoid busy waiting ?
802   // the issue here is that we have to wait on a nonexistent comm
803   while(flag==0){
804     iprobe(source, tag, comm, &flag, status);
805     XBT_DEBUG("Busy Waiting on probing : %d", flag);
806   }
807 }
808
809 void Request::iprobe(int source, int tag, MPI_Comm comm, int* flag, MPI_Status* status){
810   // to avoid deadlock, we have to sleep some time here, or the timer won't advance and we will only do iprobe simcalls
811   // especially when used as a break condition, such as while (MPI_Iprobe(...)) dostuff...
812   // nsleeps is a multiplier to the sleeptime, to increase speed of execution, each failed iprobe will increase it
813   // This can speed up the execution of certain applications by an order of magnitude, such as HPL
814   static int nsleeps = 1;
815   double speed        = s4u::this_actor::get_host()->get_speed();
816   double maxrate      = smpi_cfg_iprobe_cpu_usage();
817   auto request =
818       new Request(nullptr, 0, MPI_CHAR, source == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : comm->group()->actor(source),
819                   simgrid::s4u::this_actor::get_pid(), tag, comm, MPI_REQ_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PROBE);
820   if (smpi_iprobe_sleep > 0) {
821     /** Compute the number of flops we will sleep **/
822     s4u::this_actor::exec_init(/*nsleeps: See comment above */ nsleeps *
823                                /*(seconds * flop/s -> total flops)*/ smpi_iprobe_sleep * speed * maxrate)
824         ->set_name("iprobe")
825         /* Not the entire CPU can be used when iprobing: This is important for
826          * the energy consumption caused by polling with iprobes.
827          * Note also that the number of flops that was
828          * computed above contains a maxrate factor and is hence reduced (maxrate < 1)
829          */
830         ->set_bound(maxrate * speed)
831         ->start()
832         ->wait();
833   }
834   // behave like a receive, but don't do it
835   s4u::Mailbox* mailbox;
836
837   request->print_request("New iprobe");
838   // We have to test both mailboxes as we don't know if we will receive one or another
839   if (smpi_cfg_async_small_thresh() > 0) {
840     mailbox = smpi_process()->mailbox_small();
841     XBT_DEBUG("Trying to probe the perm recv mailbox");
842     request->action_ = mailbox->iprobe(0, &match_recv, static_cast<void*>(request));
843   }
844
845   if (request->action_ == nullptr){
846     mailbox = smpi_process()->mailbox();
847     XBT_DEBUG("trying to probe the other mailbox");
848     request->action_ = mailbox->iprobe(0, &match_recv, static_cast<void*>(request));
849   }
850
851   if (request->action_ != nullptr){
852     kernel::activity::CommImplPtr sync_comm = boost::static_pointer_cast<kernel::activity::CommImpl>(request->action_);
853     const Request* req                      = static_cast<MPI_Request>(sync_comm->src_data_);
854     *flag = 1;
855     if (status != MPI_STATUS_IGNORE && (req->flags_ & MPI_REQ_PREPARED) == 0) {
856       status->MPI_SOURCE = comm->group()->rank(req->src_);
857       status->MPI_TAG    = req->tag_;
858       status->MPI_ERROR  = MPI_SUCCESS;
859       status->count      = req->real_size_;
860     }
861     nsleeps = 1;//reset the number of sleeps we will do next time
862   }
863   else {
864     *flag = 0;
865     if (smpi_cfg_grow_injected_times())
866       nsleeps++;
867   }
868   unref(&request);
869   xbt_assert(request == MPI_REQUEST_NULL);
870 }
871
872 int Request::finish_nbc_requests(MPI_Request* request, int test){
873   int flag = 1;
874   int ret = 0;
875   if(test == 0)
876     ret = waitall((*request)->nbc_requests_.size(), (*request)->nbc_requests_.data(), MPI_STATUSES_IGNORE);
877   else{
878     ret = testall((*request)->nbc_requests_.size(), (*request)->nbc_requests_.data(), &flag, MPI_STATUSES_IGNORE);
879   }
880   if(ret!=MPI_SUCCESS)
881     xbt_die("Failure when waiting on non blocking collective sub-requests");
882   if(flag == 1){
883     XBT_DEBUG("Finishing non blocking collective request with %zu sub-requests", (*request)->nbc_requests_.size());
884     for(auto& req: (*request)->nbc_requests_){
885       if((*request)->buf_!=nullptr && req!=MPI_REQUEST_NULL){//reduce case
886         void * buf=req->buf_;
887         if((*request)->type_->flags() & DT_FLAG_DERIVED)
888           buf=req->old_buf_;
889         if(req->flags_ & MPI_REQ_RECV ){
890           if((*request)->op_!=MPI_OP_NULL){
891             int count=(*request)->size_/ (*request)->type_->size();
892             (*request)->op_->apply(buf, (*request)->buf_, &count, (*request)->type_);
893           }
894           smpi_free_tmp_buffer(static_cast<unsigned char*>(buf));
895         }
896       }
897       if(req!=MPI_REQUEST_NULL)
898         Request::unref(&req);
899     }
900     (*request)->nbc_requests_.clear();
901   }
902   return flag;
903 }
904
905 void Request::finish_wait(MPI_Request* request, MPI_Status * status)
906 {
907   MPI_Request req = *request;
908   Status::empty(status);
909   if((req->flags_ & MPI_REQ_CANCELLED) != 0 && (req->flags_ & MPI_REQ_MATCHED) == 0) {
910     if (status!=MPI_STATUS_IGNORE)
911       status->cancelled=1;
912     if(req->detached_sender_ != nullptr)
913       unref(&(req->detached_sender_));
914     unref(request);
915     return;
916   }
917
918   if ((req->flags_ & (MPI_REQ_PREPARED | MPI_REQ_GENERALIZED | MPI_REQ_FINISHED)) == 0) {
919     if (status != MPI_STATUS_IGNORE) {
920       if (req->src_== MPI_PROC_NULL || req->dst_== MPI_PROC_NULL){
921         Status::empty(status);
922         status->MPI_SOURCE = MPI_PROC_NULL;
923       } else {
924         aid_t src          = req->src_ == MPI_ANY_SOURCE ? req->real_src_ : req->src_;
925         status->MPI_SOURCE = req->comm_->group()->rank(src);
926         status->MPI_TAG = req->tag_ == MPI_ANY_TAG ? req->real_tag_ : req->tag_;
927         status->MPI_ERROR  = req->truncated_ ? MPI_ERR_TRUNCATE : MPI_SUCCESS;
928       }
929       // this handles the case were size in receive differs from size in send
930       status->count = req->real_size_;
931     }
932     //detached send will be finished at the other end
933     if (not(req->detached_ && ((req->flags_ & MPI_REQ_SEND) != 0))) {
934       req->print_request("Finishing");
935       MPI_Datatype datatype = req->type_;
936
937       // FIXME Handle the case of a partial shared malloc.
938       if (not smpi_process()->replaying() &&
939         (((req->flags_ & MPI_REQ_ACCUMULATE) != 0) || (datatype->flags() & DT_FLAG_DERIVED))) {
940         if (smpi_switch_data_segment(simgrid::s4u::Actor::self(), req->old_buf_))
941           XBT_VERB("Privatization : We are unserializing to a zone in global memory  Switch data segment ");
942
943         if(datatype->flags() & DT_FLAG_DERIVED){
944           // This part handles the problem of non-contiguous memory the unserialization at the reception
945           if ((req->flags_ & MPI_REQ_RECV) && datatype->size() != 0)
946             datatype->unserialize(req->buf_, req->old_buf_, req->real_size_/datatype->size() , req->op_);
947           xbt_free(req->buf_);
948           req->buf_=nullptr;
949         } else if (req->flags_ & MPI_REQ_RECV) { // apply op on contiguous buffer for accumulate
950           if (datatype->size() != 0) {
951             int n = req->real_size_ / datatype->size();
952             req->op_->apply(req->buf_, req->old_buf_, &n, datatype);
953           }
954           xbt_free(req->buf_);
955           req->buf_=nullptr;
956         }
957       }
958     }
959   }
960
961   if (TRACE_smpi_view_internals() && ((req->flags_ & MPI_REQ_RECV) != 0)) {
962     aid_t rank       = simgrid::s4u::this_actor::get_pid();
963     aid_t src_traced = (req->src_ == MPI_ANY_SOURCE ? req->real_src_ : req->src_);
964     TRACE_smpi_recv(src_traced, rank,req->tag_);
965   }
966   if(req->detached_sender_ != nullptr){
967     //integrate pseudo-timing for buffering of small messages, do not bother to execute the simcall if 0
968     simgrid::s4u::Host* dst_host = simgrid::s4u::Actor::by_pid(req->dst_)->get_host();
969     double sleeptime             = simgrid::s4u::Actor::self()->get_host()->extension<simgrid::smpi::Host>()->orecv(
970         req->real_size(), req->src_host_, dst_host);
971     if (sleeptime > 0.0) {
972       simgrid::s4u::this_actor::sleep_for(sleeptime);
973       XBT_DEBUG("receiving size of %zu : sleep %f ", req->real_size_, sleeptime);
974     }
975     unref(&(req->detached_sender_));
976   }
977   if (req->flags_ & MPI_REQ_PERSISTENT)
978     req->action_ = nullptr;
979   req->flags_ |= MPI_REQ_FINISHED;
980
981   if (req->truncated_ || req->unmatched_types_) {
982     char error_string[MPI_MAX_ERROR_STRING];
983     int error_size;
984     int errkind;
985     if(req->truncated_ )
986       errkind = MPI_ERR_TRUNCATE;
987     else
988       errkind = MPI_ERR_TYPE;
989     PMPI_Error_string(errkind, error_string, &error_size);
990     MPI_Errhandler err = (req->comm_) ? (req->comm_)->errhandler() : MPI_ERRHANDLER_NULL;
991     if (err == MPI_ERRHANDLER_NULL || err == MPI_ERRORS_RETURN)
992       XBT_WARN("recv - returned %.*s instead of MPI_SUCCESS", error_size, error_string);
993     else if (err == MPI_ERRORS_ARE_FATAL)
994       xbt_die("recv - returned %.*s instead of MPI_SUCCESS", error_size, error_string);
995     else
996       err->call((req->comm_), errkind);
997     if (err != MPI_ERRHANDLER_NULL)
998       simgrid::smpi::Errhandler::unref(err);
999     MC_assert(not MC_is_active()); /* Only fail in MC mode */
1000   }
1001   if(req->src_ != MPI_PROC_NULL && req->dst_ != MPI_PROC_NULL)
1002     unref(request);
1003 }
1004
1005 int Request::wait(MPI_Request * request, MPI_Status * status)
1006 {
1007   // assume that *request is not MPI_REQUEST_NULL (filtered in PMPI_Wait before)
1008   xbt_assert(*request != MPI_REQUEST_NULL);
1009
1010   int ret=MPI_SUCCESS;
1011
1012   if((*request)->src_ == MPI_PROC_NULL || (*request)->dst_ == MPI_PROC_NULL){
1013     if (status != MPI_STATUS_IGNORE) {
1014       Status::empty(status);
1015       status->MPI_SOURCE = MPI_PROC_NULL;
1016     }
1017     (*request)=MPI_REQUEST_NULL;
1018     return ret;
1019   }
1020
1021   (*request)->print_request("Waiting");
1022   if ((*request)->flags_ & (MPI_REQ_PREPARED | MPI_REQ_FINISHED)) {
1023     Status::empty(status);
1024     return ret;
1025   }
1026
1027   if ((*request)->action_ != nullptr){
1028       try{
1029         // this is not a detached send
1030         simcall_comm_wait((*request)->action_.get(), -1.0);
1031       } catch (const CancelException&) {
1032         XBT_VERB("Request cancelled");
1033       }
1034   }
1035
1036   if ((*request)->flags_ & MPI_REQ_GENERALIZED) {
1037     if (not((*request)->flags_ & MPI_REQ_COMPLETE)) {
1038       ((*request)->generalized_funcs)->mutex->lock();
1039       ((*request)->generalized_funcs)->cond->wait(((*request)->generalized_funcs)->mutex);
1040       ((*request)->generalized_funcs)->mutex->unlock();
1041     }
1042     MPI_Status tmp_status;
1043     MPI_Status* mystatus;
1044     if (status == MPI_STATUS_IGNORE) {
1045       mystatus = &tmp_status;
1046       Status::empty(mystatus);
1047     } else {
1048       mystatus = status;
1049     }
1050     ret = ((*request)->generalized_funcs)->query_fn(((*request)->generalized_funcs)->extra_state, mystatus);
1051   }
1052
1053   if ((*request)->truncated_)
1054     ret = MPI_ERR_TRUNCATE;
1055
1056   if ((*request)->flags_ & MPI_REQ_NBC)
1057     finish_nbc_requests(request, 0);
1058
1059   finish_wait(request, status); // may invalidate *request
1060   if (*request != MPI_REQUEST_NULL && (((*request)->flags_ & MPI_REQ_NON_PERSISTENT) != 0))
1061     *request = MPI_REQUEST_NULL;
1062   return ret;
1063 }
1064
1065 int Request::waitany(int count, MPI_Request requests[], MPI_Status * status)
1066 {
1067   int index = MPI_UNDEFINED;
1068
1069   if(count > 0) {
1070     // Wait for a request to complete
1071     std::vector<simgrid::kernel::activity::CommImpl*> comms;
1072     std::vector<int> map;
1073     XBT_DEBUG("Wait for one of %d", count);
1074     for(int i = 0; i < count; i++) {
1075       if (requests[i] != MPI_REQUEST_NULL && not(requests[i]->flags_ & MPI_REQ_PREPARED) &&
1076           not(requests[i]->flags_ & MPI_REQ_FINISHED)) {
1077         if (requests[i]->action_ != nullptr) {
1078           XBT_DEBUG("Waiting any %p ", requests[i]);
1079           comms.push_back(static_cast<simgrid::kernel::activity::CommImpl*>(requests[i]->action_.get()));
1080           map.push_back(i);
1081         } else {
1082           // This is a finished detached request, let's return this one
1083           comms.clear(); // don't do the waitany call afterwards
1084           index = i;
1085           if (requests[index]->flags_ & MPI_REQ_NBC)
1086             finish_nbc_requests(&requests[index], 0);
1087           finish_wait(&requests[i], status); // cleanup if refcount = 0
1088           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags_ & MPI_REQ_NON_PERSISTENT))
1089             requests[i] = MPI_REQUEST_NULL; // set to null
1090           break;
1091         }
1092       }
1093     }
1094     if (not comms.empty()) {
1095       XBT_DEBUG("Enter waitany for %zu comms", comms.size());
1096       ssize_t i;
1097       try{
1098         i = simcall_comm_waitany(comms.data(), comms.size(), -1);
1099       } catch (const CancelException&) {
1100         XBT_INFO("request cancelled");
1101         i = -1;
1102       }
1103
1104       // not MPI_UNDEFINED, as this is a simix return code
1105       if (i != -1) {
1106         index = map[i];
1107         //in case of an accumulate, we have to wait the end of all requests to apply the operation, ordered correctly.
1108         if ((requests[index] == MPI_REQUEST_NULL) ||
1109             (not((requests[index]->flags_ & MPI_REQ_ACCUMULATE) && (requests[index]->flags_ & MPI_REQ_RECV)))) {
1110           finish_wait(&requests[index],status);
1111           if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & MPI_REQ_NON_PERSISTENT))
1112             requests[index] = MPI_REQUEST_NULL;
1113         }
1114       }
1115     }
1116   }
1117
1118
1119   if (index==MPI_UNDEFINED)
1120     Status::empty(status);
1121
1122   return index;
1123 }
1124
1125 static int sort_accumulates(const Request* a, const Request* b)
1126 {
1127   return (a->tag() > b->tag());
1128 }
1129
1130 int Request::waitall(int count, MPI_Request requests[], MPI_Status status[])
1131 {
1132   std::vector<MPI_Request> accumulates;
1133   int index;
1134   MPI_Status stat;
1135   MPI_Status *pstat = (status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat);
1136   int retvalue = MPI_SUCCESS;
1137   //tag invalid requests in the set
1138   if (status != MPI_STATUSES_IGNORE) {
1139     for (int c = 0; c < count; c++) {
1140       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst_ == MPI_PROC_NULL ||
1141           (requests[c]->flags_ & MPI_REQ_PREPARED)) {
1142         Status::empty(&status[c]);
1143       } else if (requests[c]->src_ == MPI_PROC_NULL) {
1144         Status::empty(&status[c]);
1145         status[c].MPI_SOURCE = MPI_PROC_NULL;
1146       }
1147     }
1148   }
1149   for (int c = 0; c < count; c++) {
1150     if (MC_is_active() || MC_record_replay_is_active()) {
1151       wait(&requests[c],pstat);
1152       index = c;
1153     } else {
1154       index = waitany(count, requests, pstat);
1155
1156       if (index == MPI_UNDEFINED)
1157         break;
1158
1159       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & MPI_REQ_RECV) &&
1160           (requests[index]->flags_ & MPI_REQ_ACCUMULATE))
1161         accumulates.push_back(requests[index]);
1162       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & MPI_REQ_NON_PERSISTENT))
1163         requests[index] = MPI_REQUEST_NULL;
1164     }
1165     if (status != MPI_STATUSES_IGNORE) {
1166       status[index] = *pstat;
1167       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
1168         retvalue = MPI_ERR_IN_STATUS;
1169     }
1170   }
1171
1172   std::sort(accumulates.begin(), accumulates.end(), sort_accumulates);
1173   for (auto& req : accumulates)
1174     finish_wait(&req, status);
1175
1176   return retvalue;
1177 }
1178
1179 int Request::waitsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
1180 {
1181   int count = 0;
1182   int flag = 0;
1183   int index = 0;
1184   MPI_Status stat;
1185   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
1186   index             = waitany(incount, requests, pstat);
1187   if(index==MPI_UNDEFINED) return MPI_UNDEFINED;
1188   if(status != MPI_STATUSES_IGNORE) {
1189     status[count] = *pstat;
1190   }
1191   indices[count] = index;
1192   count++;
1193   for (int i = 0; i < incount; i++) {
1194     if (i != index && requests[i] != MPI_REQUEST_NULL && not(requests[i]->flags_ & MPI_REQ_FINISHED)) {
1195       test(&requests[i], pstat,&flag);
1196       if (flag==1){
1197         indices[count] = i;
1198         if(status != MPI_STATUSES_IGNORE) {
1199           status[count] = *pstat;
1200         }
1201         if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags_ & MPI_REQ_NON_PERSISTENT))
1202           requests[i]=MPI_REQUEST_NULL;
1203         count++;
1204       }
1205     }
1206   }
1207   return count;
1208 }
1209
1210 MPI_Request Request::f2c(int id)
1211 {
1212   if(id==MPI_FORTRAN_REQUEST_NULL)
1213     return MPI_REQUEST_NULL;
1214   return static_cast<MPI_Request>(F2C::lookup()->at(id));
1215 }
1216
1217 void Request::free_f(int id)
1218 {
1219   if (id != MPI_FORTRAN_REQUEST_NULL) {
1220     F2C::lookup()->erase(id);
1221   }
1222 }
1223
1224 int Request::get_status(const Request* req, int* flag, MPI_Status* status)
1225 {
1226   *flag=0;
1227
1228   if(req != MPI_REQUEST_NULL && req->action_ != nullptr) {
1229     req->iprobe(req->comm_->group()->rank(req->src_), req->tag_, req->comm_, flag, status);
1230     if(*flag)
1231       return MPI_SUCCESS;
1232   }
1233   if (req != MPI_REQUEST_NULL && (req->flags_ & MPI_REQ_GENERALIZED) && not(req->flags_ & MPI_REQ_COMPLETE)) {
1234     *flag = 0;
1235     return MPI_SUCCESS;
1236   }
1237
1238   *flag=1;
1239   if(req != MPI_REQUEST_NULL &&
1240      status != MPI_STATUS_IGNORE) {
1241     aid_t src          = req->src_ == MPI_ANY_SOURCE ? req->real_src_ : req->src_;
1242     status->MPI_SOURCE = req->comm_->group()->rank(src);
1243     status->MPI_TAG = req->tag_ == MPI_ANY_TAG ? req->real_tag_ : req->tag_;
1244     status->MPI_ERROR = req->truncated_ ? MPI_ERR_TRUNCATE : MPI_SUCCESS;
1245     status->count = req->real_size_;
1246   }
1247   return MPI_SUCCESS;
1248 }
1249
1250 int Request::grequest_start(MPI_Grequest_query_function* query_fn, MPI_Grequest_free_function* free_fn,
1251                             MPI_Grequest_cancel_function* cancel_fn, void* extra_state, MPI_Request* request)
1252 {
1253   *request = new Request();
1254   (*request)->flags_ |= MPI_REQ_GENERALIZED;
1255   (*request)->flags_ |= MPI_REQ_PERSISTENT;
1256   (*request)->refcount_ = 1;
1257   ((*request)->generalized_funcs)             = std::make_unique<smpi_mpi_generalized_request_funcs_t>();
1258   ((*request)->generalized_funcs)->query_fn=query_fn;
1259   ((*request)->generalized_funcs)->free_fn=free_fn;
1260   ((*request)->generalized_funcs)->cancel_fn=cancel_fn;
1261   ((*request)->generalized_funcs)->extra_state=extra_state;
1262   ((*request)->generalized_funcs)->cond = simgrid::s4u::ConditionVariable::create();
1263   ((*request)->generalized_funcs)->mutex = simgrid::s4u::Mutex::create();
1264   return MPI_SUCCESS;
1265 }
1266
1267 int Request::grequest_complete(MPI_Request request)
1268 {
1269   if ((not(request->flags_ & MPI_REQ_GENERALIZED)) || request->generalized_funcs->mutex == nullptr)
1270     return MPI_ERR_REQUEST;
1271   request->generalized_funcs->mutex->lock();
1272   request->flags_ |= MPI_REQ_COMPLETE; // in case wait would be called after complete
1273   request->generalized_funcs->cond->notify_one();
1274   request->generalized_funcs->mutex->unlock();
1275   return MPI_SUCCESS;
1276 }
1277
1278 void Request::start_nbc_requests(std::vector<MPI_Request> reqs){
1279   if (not reqs.empty()) {
1280     nbc_requests_ = reqs;
1281     Request::startall(reqs.size(), reqs.data());
1282   }
1283 }
1284
1285 std::vector<MPI_Request> Request::get_nbc_requests() const
1286 {
1287   return nbc_requests_;
1288 }
1289 }
1290 }