Logo AND Algorithmique Numérique Distribuée

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