Logo AND Algorithmique Numérique Distribuée

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