Logo AND Algorithmique Numérique Distribuée

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