Logo AND Algorithmique Numérique Distribuée

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