Logo AND Algorithmique Numérique Distribuée

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