Logo AND Algorithmique Numérique Distribuée

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