Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6011cd72e6ecee086b8e0989aa99185bd2ee1202
[simgrid.git] / src / smpi / mpi / smpi_request.cpp
1 /* Copyright (c) 2007-2019. 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   void *old_buf = nullptr;
40 // FIXME Handle the case of a partial shared malloc.
41   if ((((flags & MPI_REQ_RECV) != 0) && ((flags & MPI_REQ_ACCUMULATE) != 0)) || (datatype->flags() & DT_FLAG_DERIVED)) {
42     // This part handles the problem of non-contiguous memory
43     old_buf = const_cast<void*>(buf);
44     if (count==0){
45       buf_ = nullptr;
46     }else {
47       buf_ = xbt_malloc(count*datatype->size());
48       if ((datatype->flags() & DT_FLAG_DERIVED) && ((flags & MPI_REQ_SEND) != 0)) {
49         datatype->serialize(old_buf, buf_, count);
50       }
51     }
52   }
53   // This part handles the problem of non-contiguous memory (for the unserialization at the reception)
54   old_buf_  = old_buf;
55   size_ = datatype->size() * count;
56   datatype->ref();
57   comm_->ref();
58   if(op != MPI_REPLACE && op != MPI_OP_NULL)
59     op_->ref();
60   action_          = nullptr;
61   detached_        = false;
62   detached_sender_ = nullptr;
63   real_src_        = 0;
64   truncated_       = false;
65   real_size_       = 0;
66   real_tag_        = 0;
67   if (flags & MPI_REQ_PERSISTENT)
68     refcount_ = 1;
69   else
70     refcount_ = 0;
71   cancelled_ = 0;
72   generalized_funcs=nullptr;
73   nbc_requests_=nullptr;
74   nbc_requests_size_=0;
75 }
76
77 void Request::ref(){
78   refcount_++;
79 }
80
81 void Request::unref(MPI_Request* request)
82 {
83   if((*request) != MPI_REQUEST_NULL){
84     (*request)->refcount_--;
85     if((*request)->refcount_ < 0) {
86       (*request)->print_request("wrong refcount");
87       xbt_die("Whoops, wrong refcount");
88     }
89     if((*request)->refcount_==0){
90       if ((*request)->flags_ & MPI_REQ_GENERALIZED){
91         ((*request)->generalized_funcs)->free_fn(((*request)->generalized_funcs)->extra_state);
92         delete (*request)->generalized_funcs;
93       }else{
94         Comm::unref((*request)->comm_);
95         Datatype::unref((*request)->old_type_);
96       }
97       if ((*request)->op_!=MPI_REPLACE && (*request)->op_!=MPI_OP_NULL)
98         Op::unref(&(*request)->op_);
99
100       (*request)->print_request("Destroying");
101       delete *request;
102       *request = MPI_REQUEST_NULL;
103     }else{
104       (*request)->print_request("Decrementing");
105     }
106   }else{
107     xbt_die("freeing an already free request");
108   }
109 }
110
111 bool Request::match_recv(void* a, void* b, simgrid::kernel::activity::CommImpl*)
112 {
113   MPI_Request ref = static_cast<MPI_Request>(a);
114   MPI_Request req = static_cast<MPI_Request>(b);
115   XBT_DEBUG("Trying to match a recv of src %d against %d, tag %d against %d, id %d against %d",ref->src_,req->src_, ref->tag_, req->tag_,ref->comm_->id(),req->comm_->id());
116
117   xbt_assert(ref, "Cannot match recv against null reference");
118   xbt_assert(req, "Cannot match recv against null request");
119   if((ref->comm_->id()==MPI_UNDEFINED || req->comm_->id() == MPI_UNDEFINED || (ref->comm_->id()==req->comm_->id()))
120     && ((ref->src_ == MPI_ANY_SOURCE  && (ref->comm_->group()->rank(req->src_) != MPI_UNDEFINED)) || req->src_ == ref->src_)
121     && ((ref->tag_ == MPI_ANY_TAG && req->tag_ >=0) || req->tag_ == ref->tag_)){
122     //we match, we can transfer some values
123     if(ref->src_ == MPI_ANY_SOURCE)
124       ref->real_src_ = req->src_;
125     if(ref->tag_ == MPI_ANY_TAG)
126       ref->real_tag_ = req->tag_;
127     if(ref->real_size_ < req->real_size_)
128       ref->truncated_ = true;
129     if (req->detached_)
130       ref->detached_sender_=req; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
131     if(req->cancelled_==0)
132       req->cancelled_ = -1; // mark as uncancelable
133     XBT_DEBUG("match succeeded");
134     return true;
135   }
136   return false;
137 }
138
139 bool Request::match_send(void* a, void* b, simgrid::kernel::activity::CommImpl*)
140 {
141   MPI_Request ref = static_cast<MPI_Request>(a);
142   MPI_Request req = static_cast<MPI_Request>(b);
143   XBT_DEBUG("Trying to match a send of src %d against %d, tag %d against %d, id %d against %d",ref->src_,req->src_, ref->tag_, req->tag_,ref->comm_->id(),req->comm_->id());
144   xbt_assert(ref, "Cannot match send against null reference");
145   xbt_assert(req, "Cannot match send against null request");
146
147   if((ref->comm_->id()==MPI_UNDEFINED || req->comm_->id() == MPI_UNDEFINED || (ref->comm_->id()==req->comm_->id()))
148       && ((req->src_ == MPI_ANY_SOURCE  && (req->comm_->group()->rank(ref->src_) != MPI_UNDEFINED)) || req->src_ == ref->src_)
149       && ((req->tag_ == MPI_ANY_TAG && ref->tag_ >=0)|| req->tag_ == ref->tag_)){
150     if(req->src_ == MPI_ANY_SOURCE)
151       req->real_src_ = ref->src_;
152     if(req->tag_ == MPI_ANY_TAG)
153       req->real_tag_ = ref->tag_;
154     if(req->real_size_ < ref->real_size_)
155       req->truncated_ = true;
156     if (ref->detached_)
157       req->detached_sender_=ref; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
158     if(req->cancelled_==0)
159       req->cancelled_ = -1; // mark as uncancelable
160     XBT_DEBUG("match succeeded");
161     return true;
162   }
163   return false;
164 }
165
166 void Request::print_request(const char *message)
167 {
168   XBT_VERB("%s  request %p  [buf = %p, size = %zu, src = %d, dst = %d, tag = %d, flags = %x]",
169        message, this, buf_, size_, src_, dst_, tag_, flags_);
170 }
171
172 /* factories, to hide the internal flags from the caller */
173 MPI_Request Request::bsend_init(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
174 {
175   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
176                      comm->group()->actor(dst)->get_pid(), tag, comm,
177                      MPI_REQ_PERSISTENT | MPI_REQ_SEND | MPI_REQ_PREPARED | MPI_REQ_BSEND);
178 }
179
180 MPI_Request Request::send_init(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
181 {
182   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
183                      comm->group()->actor(dst)->get_pid(), tag, comm,
184                      MPI_REQ_PERSISTENT | MPI_REQ_SEND | MPI_REQ_PREPARED);
185 }
186
187 MPI_Request Request::ssend_init(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
188 {
189   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
190                      comm->group()->actor(dst)->get_pid(), tag, comm,
191                      MPI_REQ_PERSISTENT | MPI_REQ_SSEND | MPI_REQ_SEND | MPI_REQ_PREPARED);
192 }
193
194 MPI_Request Request::isend_init(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
195 {
196   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
197                      comm->group()->actor(dst)->get_pid(), tag, comm,
198                      MPI_REQ_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_PREPARED);
199 }
200
201
202 MPI_Request Request::rma_send_init(const void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
203                                MPI_Op op)
204 {
205   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
206   if(op==MPI_OP_NULL){
207     request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src)->get_pid(),
208                           comm->group()->actor(dst)->get_pid(), tag, comm,
209                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_PREPARED);
210   }else{
211     request      = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src)->get_pid(),
212                           comm->group()->actor(dst)->get_pid(), tag, comm,
213                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_PREPARED |
214                               MPI_REQ_ACCUMULATE, op);
215   }
216   return request;
217 }
218
219 MPI_Request Request::recv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
220 {
221   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype,
222                      src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : comm->group()->actor(src)->get_pid(),
223                      simgrid::s4u::this_actor::get_pid(), tag, comm,
224                      MPI_REQ_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED);
225 }
226
227 MPI_Request Request::rma_recv_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
228                                MPI_Op op)
229 {
230   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
231   if(op==MPI_OP_NULL){
232     request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src)->get_pid(),
233                           comm->group()->actor(dst)->get_pid(), tag, comm,
234                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED);
235   }else{
236     request      = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src)->get_pid(),
237                           comm->group()->actor(dst)->get_pid(), tag, comm,
238                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED | MPI_REQ_ACCUMULATE, op);
239   }
240   return request;
241 }
242
243 MPI_Request Request::irecv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
244 {
245   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype,
246                      src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : comm->group()->actor(src)->get_pid(),
247                      simgrid::s4u::this_actor::get_pid(), tag, comm,
248                      MPI_REQ_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED);
249 }
250
251 MPI_Request Request::ibsend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
252 {
253   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
254   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
255                         comm->group()->actor(dst)->get_pid(), tag, comm,
256                         MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_BSEND);
257   request->start();
258   return request;
259 }
260
261 MPI_Request Request::isend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
262 {
263   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
264   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
265                         comm->group()->actor(dst)->get_pid(), tag, comm,
266                         MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND);
267   request->start();
268   return request;
269 }
270
271 MPI_Request Request::issend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
272 {
273   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
274   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
275                         comm->group()->actor(dst)->get_pid(), tag, comm,
276                         MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SSEND | MPI_REQ_SEND);
277   request->start();
278   return request;
279 }
280
281
282 MPI_Request Request::irecv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
283 {
284   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
285   request             = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype,
286                         src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : comm->group()->actor(src)->get_pid(),
287                         simgrid::s4u::this_actor::get_pid(), tag, comm, MPI_REQ_NON_PERSISTENT | MPI_REQ_RECV);
288   request->start();
289   return request;
290 }
291
292 void Request::recv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm, MPI_Status * status)
293 {
294   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
295   request = irecv(buf, count, datatype, src, tag, comm);
296   wait(&request,status);
297   request = nullptr;
298 }
299
300 void Request::bsend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
301 {
302   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
303   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
304                         comm->group()->actor(dst)->get_pid(), tag, comm, MPI_REQ_NON_PERSISTENT | MPI_REQ_SEND | MPI_REQ_BSEND);
305
306   request->start();
307   wait(&request, MPI_STATUS_IGNORE);
308   request = nullptr;
309 }
310
311 void Request::send(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
312 {
313   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
314   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
315                         comm->group()->actor(dst)->get_pid(), tag, comm, MPI_REQ_NON_PERSISTENT | MPI_REQ_SEND);
316
317   request->start();
318   wait(&request, MPI_STATUS_IGNORE);
319   request = nullptr;
320 }
321
322 void Request::ssend(const void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
323 {
324   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
325   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
326                         comm->group()->actor(dst)->get_pid(), tag, comm,
327                         MPI_REQ_NON_PERSISTENT | MPI_REQ_SSEND | MPI_REQ_SEND);
328
329   request->start();
330   wait(&request,MPI_STATUS_IGNORE);
331   request = nullptr;
332 }
333
334 void Request::sendrecv(const void *sendbuf, int sendcount, MPI_Datatype sendtype,int dst, int sendtag,
335                        void *recvbuf, int recvcount, MPI_Datatype recvtype, int src, int recvtag,
336                        MPI_Comm comm, MPI_Status * status)
337 {
338   MPI_Request requests[2];
339   MPI_Status stats[2];
340   int myid = simgrid::s4u::this_actor::get_pid();
341   if ((comm->group()->actor(dst)->get_pid() == myid) && (comm->group()->actor(src)->get_pid() == myid)) {
342     Datatype::copy(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype);
343     if (status != MPI_STATUS_IGNORE) {
344       status->MPI_SOURCE = src;
345       status->MPI_TAG    = recvtag;
346       status->MPI_ERROR  = MPI_SUCCESS;
347       status->count      = sendcount * sendtype->size();
348     }
349     return;
350   }
351   requests[0] = isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
352   requests[1] = irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
353   startall(2, requests);
354   waitall(2, requests, stats);
355   unref(&requests[0]);
356   unref(&requests[1]);
357   if(status != MPI_STATUS_IGNORE) {
358     // Copy receive status
359     *status = stats[1];
360   }
361 }
362
363 void Request::start()
364 {
365   s4u::Mailbox* mailbox;
366
367   xbt_assert(action_ == nullptr, "Cannot (re-)start unfinished communication");
368   flags_ &= ~MPI_REQ_PREPARED;
369   flags_ &= ~MPI_REQ_FINISHED;
370   this->ref();
371
372   if ((flags_ & MPI_REQ_RECV) != 0) {
373     this->print_request("New recv");
374
375     simgrid::smpi::ActorExt* process = smpi_process_remote(simgrid::s4u::Actor::by_pid(dst_));
376
377     simgrid::s4u::MutexPtr mut = process->mailboxes_mutex();
378     if (smpi_cfg_async_small_thresh() != 0 || (flags_ & MPI_REQ_RMA) != 0)
379       mut->lock();
380
381     if (smpi_cfg_async_small_thresh() == 0 && (flags_ & MPI_REQ_RMA) == 0) {
382       mailbox = process->mailbox();
383     } else if (((flags_ & MPI_REQ_RMA) != 0) || static_cast<int>(size_) < smpi_cfg_async_small_thresh()) {
384       //We have to check both mailboxes (because SSEND messages are sent to the large mbox).
385       //begin with the more appropriate one : the small one.
386       mailbox = process->mailbox_small();
387       XBT_DEBUG("Is there a corresponding send already posted in the small mailbox %s (in case of SSEND)?",
388                 mailbox->get_cname());
389       smx_activity_t action = mailbox->iprobe(0, &match_recv, static_cast<void*>(this));
390
391       if (action == nullptr) {
392         mailbox = process->mailbox();
393         XBT_DEBUG("No, nothing in the small mailbox test the other one : %s", mailbox->get_cname());
394         action = mailbox->iprobe(0, &match_recv, static_cast<void*>(this));
395         if (action == nullptr) {
396           XBT_DEBUG("Still nothing, switch back to the small mailbox : %s", mailbox->get_cname());
397           mailbox = process->mailbox_small();
398         }
399       } else {
400         XBT_DEBUG("yes there was something for us in the large mailbox");
401       }
402     } else {
403       mailbox = process->mailbox_small();
404       XBT_DEBUG("Is there a corresponding send already posted the small mailbox?");
405       smx_activity_t action = mailbox->iprobe(0, &match_recv, static_cast<void*>(this));
406
407       if (action == nullptr) {
408         XBT_DEBUG("No, nothing in the permanent receive mailbox");
409         mailbox = process->mailbox();
410       } else {
411         XBT_DEBUG("yes there was something for us in the small mailbox");
412       }
413     }
414
415     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
416     real_size_=size_;
417     action_   = simcall_comm_irecv(
418         process->get_actor()->get_impl(), mailbox->get_impl(), buf_, &real_size_, &match_recv,
419         process->replaying() ? &smpi_comm_null_copy_buffer_callback : smpi_comm_copy_data_callback, this, -1.0);
420     XBT_DEBUG("recv simcall posted");
421
422     if (smpi_cfg_async_small_thresh() != 0 || (flags_ & MPI_REQ_RMA) != 0)
423       mut->unlock();
424   } else { /* the RECV flag was not set, so this is a send */
425     simgrid::smpi::ActorExt* process = smpi_process_remote(simgrid::s4u::Actor::by_pid(dst_));
426     xbt_assert(process, "Actor pid=%d is gone??", dst_);
427     int rank = src_;
428     if (TRACE_smpi_view_internals()) {
429       TRACE_smpi_send(rank, rank, dst_, tag_, size_);
430     }
431     this->print_request("New send");
432
433     void* buf = buf_;
434     if ((flags_ & MPI_REQ_SSEND) == 0 &&
435         ((flags_ & MPI_REQ_RMA) != 0 || (flags_ & MPI_REQ_BSEND) != 0 ||
436          static_cast<int>(size_) < smpi_cfg_detached_send_thresh())) {
437       void *oldbuf = nullptr;
438       detached_    = true;
439       XBT_DEBUG("Send request %p is detached", this);
440       this->ref();
441       if (not(old_type_->flags() & DT_FLAG_DERIVED)) {
442         oldbuf = buf_;
443         if (not process->replaying() && oldbuf != nullptr && size_ != 0) {
444           if ((smpi_cfg_privatization() != SmpiPrivStrategies::NONE) &&
445               (static_cast<char*>(buf_) >= smpi_data_exe_start) &&
446               (static_cast<char*>(buf_) < smpi_data_exe_start + smpi_data_exe_size)) {
447             XBT_DEBUG("Privatization : We are sending from a zone inside global memory. Switch data segment ");
448             smpi_switch_data_segment(simgrid::s4u::Actor::by_pid(src_));
449           }
450           //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
451           //so actually ... don't use manually attached buffer space.
452           buf = xbt_malloc(size_);
453           memcpy(buf,oldbuf,size_);
454           XBT_DEBUG("buf %p copied into %p",oldbuf,buf);
455         }
456       }
457     }
458
459     //if we are giving back the control to the user without waiting for completion, we have to inject timings
460     double sleeptime = 0.0;
461     if (detached_ || ((flags_ & (MPI_REQ_ISEND | MPI_REQ_SSEND)) != 0)) { // issend should be treated as isend
462       // isend and send timings may be different
463       sleeptime = ((flags_ & MPI_REQ_ISEND) != 0)
464                       ? simgrid::s4u::Actor::self()->get_host()->extension<simgrid::smpi::Host>()->oisend(size_)
465                       : simgrid::s4u::Actor::self()->get_host()->extension<simgrid::smpi::Host>()->osend(size_);
466     }
467
468     if(sleeptime > 0.0){
469       simgrid::s4u::this_actor::sleep_for(sleeptime);
470       XBT_DEBUG("sending size of %zu : sleep %f ", size_, sleeptime);
471     }
472
473     simgrid::s4u::MutexPtr mut = process->mailboxes_mutex();
474
475     if (smpi_cfg_async_small_thresh() != 0 || (flags_ & MPI_REQ_RMA) != 0)
476       mut->lock();
477
478     if (not(smpi_cfg_async_small_thresh() != 0 || (flags_ & MPI_REQ_RMA) != 0)) {
479       mailbox = process->mailbox();
480     } else if (((flags_ & MPI_REQ_RMA) != 0) || static_cast<int>(size_) < smpi_cfg_async_small_thresh()) { // eager mode
481       mailbox = process->mailbox();
482       XBT_DEBUG("Is there a corresponding recv already posted in the large mailbox %s?", mailbox->get_cname());
483       smx_activity_t action = mailbox->iprobe(1, &match_send, static_cast<void*>(this));
484       if (action == nullptr) {
485         if ((flags_ & MPI_REQ_SSEND) == 0) {
486           mailbox = process->mailbox_small();
487           XBT_DEBUG("No, nothing in the large mailbox, message is to be sent on the small one %s",
488                     mailbox->get_cname());
489         } else {
490           mailbox = process->mailbox_small();
491           XBT_DEBUG("SSEND : Is there a corresponding recv already posted in the small mailbox %s?",
492                     mailbox->get_cname());
493           action = mailbox->iprobe(1, &match_send, static_cast<void*>(this));
494           if (action == nullptr) {
495             XBT_DEBUG("No, we are first, send to large mailbox");
496             mailbox = process->mailbox();
497           }
498         }
499       } else {
500         XBT_DEBUG("Yes there was something for us in the large mailbox");
501       }
502     } else {
503       mailbox = process->mailbox();
504       XBT_DEBUG("Send request %p is in the large mailbox %s (buf: %p)", this, mailbox->get_cname(), buf_);
505     }
506
507     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
508     real_size_=size_;
509     action_   = simcall_comm_isend(
510         simgrid::s4u::Actor::by_pid(src_)->get_impl(), mailbox->get_impl(), 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) == 0) {
573     if ((*request)->action_ != nullptr && (*request)->cancelled_ != 1){
574       try{
575         *flag = simcall_comm_test((*request)->action_);
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     MPI_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           xbt_free(req->buf_);
859         } else if (req->flags_ & MPI_REQ_RECV) { // apply op on contiguous buffer for accumulate
860           if (datatype->size() != 0) {
861             int n = req->real_size_ / datatype->size();
862             req->op_->apply(req->buf_, req->old_buf_, &n, datatype);
863           }
864           xbt_free(req->buf_);
865         }
866       }
867     }
868   }
869
870   if (TRACE_smpi_view_internals() && ((req->flags_ & MPI_REQ_RECV) != 0)) {
871     int rank       = simgrid::s4u::this_actor::get_pid();
872     int src_traced = (req->src_ == MPI_ANY_SOURCE ? req->real_src_ : req->src_);
873     TRACE_smpi_recv(src_traced, rank,req->tag_);
874   }
875   if(req->detached_sender_ != nullptr){
876     //integrate pseudo-timing for buffering of small messages, do not bother to execute the simcall if 0
877     double sleeptime =
878         simgrid::s4u::Actor::self()->get_host()->extension<simgrid::smpi::Host>()->orecv(req->real_size());
879     if (sleeptime > 0.0) {
880       simgrid::s4u::this_actor::sleep_for(sleeptime);
881       XBT_DEBUG("receiving size of %zu : sleep %f ", req->real_size_, sleeptime);
882     }
883     unref(&(req->detached_sender_));
884   }
885   if (req->flags_ & MPI_REQ_PERSISTENT)
886     req->action_ = nullptr;
887   req->flags_ |= MPI_REQ_FINISHED;
888   unref(request);
889 }
890
891 int Request::wait(MPI_Request * request, MPI_Status * status)
892 {
893   int ret=MPI_SUCCESS;
894   // Are we waiting on a request meant for non blocking collectives ?
895   // If so, wait for all the subrequests.
896   if ((*request)->nbc_requests_size_>0){
897     ret = waitall((*request)->nbc_requests_size_, (*request)->nbc_requests_, MPI_STATUSES_IGNORE);
898     for (int i = 0; i < (*request)->nbc_requests_size_; i++) {
899       if((*request)->buf_!=nullptr && (*request)->nbc_requests_[i]!=MPI_REQUEST_NULL){//reduce case
900         void * buf=(*request)->nbc_requests_[i]->buf_;
901         if((*request)->old_type_->flags() & DT_FLAG_DERIVED)
902           buf=(*request)->nbc_requests_[i]->old_buf_;
903         if((*request)->nbc_requests_[i]->flags_ & MPI_REQ_RECV ){
904           if((*request)->op_!=MPI_OP_NULL){
905             int count=(*request)->size_/ (*request)->old_type_->size();
906             (*request)->op_->apply(buf, (*request)->buf_, &count, (*request)->old_type_);
907           }
908           smpi_free_tmp_buffer(static_cast<unsigned char*>(buf));
909         }
910       }
911       if((*request)->nbc_requests_[i]!=MPI_REQUEST_NULL)
912         Request::unref(&((*request)->nbc_requests_[i]));
913     }
914     delete[] (*request)->nbc_requests_;
915     (*request)->nbc_requests_size_=0;
916     unref(request);
917     (*request)=MPI_REQUEST_NULL;
918     return ret;
919   }
920
921   (*request)->print_request("Waiting");
922   if ((*request)->flags_ & MPI_REQ_PREPARED) {
923     Status::empty(status);
924     return ret;
925   }
926
927   if ((*request)->action_ != nullptr){
928       try{
929         // this is not a detached send
930         simcall_comm_wait((*request)->action_, -1.0);
931       } catch (const Exception&) {
932         XBT_VERB("Request cancelled");
933       }
934   }
935
936   if (*request != MPI_REQUEST_NULL && ((*request)->flags_ & MPI_REQ_GENERALIZED)){
937     MPI_Status* mystatus;
938     if(!((*request)->flags_ & MPI_REQ_COMPLETE)){
939       ((*request)->generalized_funcs)->mutex->lock();
940       ((*request)->generalized_funcs)->cond->wait(((*request)->generalized_funcs)->mutex);
941       ((*request)->generalized_funcs)->mutex->unlock();
942       }
943     if(status==MPI_STATUS_IGNORE){
944       mystatus=new MPI_Status();
945       Status::empty(mystatus);
946     }else{
947       mystatus=status;
948     }
949     ret = ((*request)->generalized_funcs)->query_fn(((*request)->generalized_funcs)->extra_state, mystatus);
950     if(status==MPI_STATUS_IGNORE) 
951       delete mystatus;
952   }
953
954   finish_wait(request,status);
955   if (*request != MPI_REQUEST_NULL && (((*request)->flags_ & MPI_REQ_NON_PERSISTENT) != 0))
956     *request = MPI_REQUEST_NULL;
957   return ret;
958 }
959
960 int Request::waitany(int count, MPI_Request requests[], MPI_Status * status)
961 {
962   std::vector<simgrid::kernel::activity::CommImpl*> comms;
963   comms.reserve(count);
964   int index = MPI_UNDEFINED;
965
966   if(count > 0) {
967     // Wait for a request to complete
968     std::vector<int> map;
969     XBT_DEBUG("Wait for one of %d", count);
970     for(int i = 0; i < count; i++) {
971       if (requests[i] != MPI_REQUEST_NULL && not(requests[i]->flags_ & MPI_REQ_PREPARED) &&
972           not(requests[i]->flags_ & MPI_REQ_FINISHED)) {
973         if (requests[i]->action_ != nullptr) {
974           XBT_DEBUG("Waiting any %p ", requests[i]);
975           comms.push_back(static_cast<simgrid::kernel::activity::CommImpl*>(requests[i]->action_.get()));
976           map.push_back(i);
977         } else {
978           // This is a finished detached request, let's return this one
979           comms.clear(); // so we free don't do the waitany call
980           index = i;
981           finish_wait(&requests[i], status); // cleanup if refcount = 0
982           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags_ & MPI_REQ_NON_PERSISTENT))
983             requests[i] = MPI_REQUEST_NULL; // set to null
984           break;
985         }
986       }
987     }
988     if (not comms.empty()) {
989       XBT_DEBUG("Enter waitany for %zu comms", comms.size());
990       int i=MPI_UNDEFINED;
991       try{
992         // this is not a detached send
993         i = simcall_comm_waitany(comms.data(), comms.size(), -1);
994       } catch (const Exception&) {
995         XBT_INFO("request %d cancelled ", i);
996         return i;
997       }
998
999       // not MPI_UNDEFINED, as this is a simix return code
1000       if (i != -1) {
1001         index = map[i];
1002         //in case of an accumulate, we have to wait the end of all requests to apply the operation, ordered correctly.
1003         if ((requests[index] == MPI_REQUEST_NULL) ||
1004             (not((requests[index]->flags_ & MPI_REQ_ACCUMULATE) && (requests[index]->flags_ & MPI_REQ_RECV)))) {
1005           finish_wait(&requests[index],status);
1006           if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & MPI_REQ_NON_PERSISTENT))
1007             requests[index] = MPI_REQUEST_NULL;
1008         }
1009       }
1010     }
1011   }
1012
1013   if (index==MPI_UNDEFINED)
1014     Status::empty(status);
1015
1016   return index;
1017 }
1018
1019 static int sort_accumulates(MPI_Request a, MPI_Request b)
1020 {
1021   return (a->tag() > b->tag());
1022 }
1023
1024 int Request::waitall(int count, MPI_Request requests[], MPI_Status status[])
1025 {
1026   std::vector<MPI_Request> accumulates;
1027   int index;
1028   MPI_Status stat;
1029   MPI_Status *pstat = (status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat);
1030   int retvalue = MPI_SUCCESS;
1031   //tag invalid requests in the set
1032   if (status != MPI_STATUSES_IGNORE) {
1033     for (int c = 0; c < count; c++) {
1034       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst_ == MPI_PROC_NULL ||
1035           (requests[c]->flags_ & MPI_REQ_PREPARED)) {
1036         Status::empty(&status[c]);
1037       } else if (requests[c]->src_ == MPI_PROC_NULL) {
1038         Status::empty(&status[c]);
1039         status[c].MPI_SOURCE = MPI_PROC_NULL;
1040       }
1041     }
1042   }
1043   for (int c = 0; c < count; c++) {
1044     if (MC_is_active() || MC_record_replay_is_active()) {
1045       wait(&requests[c],pstat);
1046       index = c;
1047     } else {
1048       index = waitany(count, (MPI_Request*)requests, pstat);
1049       
1050       if (index == MPI_UNDEFINED)
1051         break;
1052
1053       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & MPI_REQ_RECV) &&
1054           (requests[index]->flags_ & MPI_REQ_ACCUMULATE))
1055         accumulates.push_back(requests[index]);
1056       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & MPI_REQ_NON_PERSISTENT))
1057         requests[index] = MPI_REQUEST_NULL;
1058     }
1059     if (status != MPI_STATUSES_IGNORE) {
1060       status[index] = *pstat;
1061       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
1062         retvalue = MPI_ERR_IN_STATUS;
1063     }
1064   }
1065
1066   if (not accumulates.empty()) {
1067     std::sort(accumulates.begin(), accumulates.end(), sort_accumulates);
1068     for (auto& req : accumulates) {
1069       finish_wait(&req, status);
1070     }
1071   }
1072
1073   return retvalue;
1074 }
1075
1076 int Request::waitsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
1077 {
1078   int count = 0;
1079   int flag = 0;
1080   int index = 0;
1081   MPI_Status stat;
1082   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
1083   index = waitany(incount, (MPI_Request*)requests, pstat);
1084   if(index==MPI_UNDEFINED) return MPI_UNDEFINED;
1085   if(status != MPI_STATUSES_IGNORE) {
1086     status[count] = *pstat;
1087   }
1088   indices[count] = index;
1089   count++;
1090   for (int i = 0; i < incount; i++) {
1091     if (i!=index && requests[i] != MPI_REQUEST_NULL 
1092         && not(requests[i]->flags_ & MPI_REQ_FINISHED)) {
1093       test(&requests[i], pstat,&flag);
1094       if (flag==1){
1095         indices[count] = i;
1096         if(status != MPI_STATUSES_IGNORE) {
1097           status[count] = *pstat;
1098         }
1099         if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags_ & MPI_REQ_NON_PERSISTENT))
1100           requests[i]=MPI_REQUEST_NULL;
1101         count++;
1102       }
1103     }
1104   }
1105   return count;
1106 }
1107
1108 MPI_Request Request::f2c(int id)
1109 {
1110   char key[KEY_SIZE];
1111   if(id==MPI_FORTRAN_REQUEST_NULL)
1112     return static_cast<MPI_Request>(MPI_REQUEST_NULL);
1113   return static_cast<MPI_Request>(F2C::f2c_lookup()->at(get_key(key,id)));
1114 }
1115
1116 void Request::free_f(int id)
1117 {
1118   if (id != MPI_FORTRAN_REQUEST_NULL) {
1119     char key[KEY_SIZE];
1120     F2C::f2c_lookup()->erase(get_key(key, id));
1121   }
1122 }
1123
1124 int Request::get_status(MPI_Request req, int* flag, MPI_Status* status)
1125 {
1126   *flag=0;
1127
1128   if(req != MPI_REQUEST_NULL && req->action_ != nullptr) {
1129     req->iprobe(req->src_, req->tag_, req->comm_, flag, status);
1130     if(*flag)
1131       return MPI_SUCCESS;
1132   }
1133   if (req != MPI_REQUEST_NULL && 
1134      (req->flags_ & MPI_REQ_GENERALIZED)
1135      && !(req->flags_ & MPI_REQ_COMPLETE)) {
1136      *flag=0;
1137     return MPI_SUCCESS;
1138   }
1139
1140   *flag=1;
1141   if(req != MPI_REQUEST_NULL &&
1142      status != MPI_STATUS_IGNORE) {
1143     int src = req->src_ == MPI_ANY_SOURCE ? req->real_src_ : req->src_;
1144     status->MPI_SOURCE = req->comm_->group()->rank(src);
1145     status->MPI_TAG = req->tag_ == MPI_ANY_TAG ? req->real_tag_ : req->tag_;
1146     status->MPI_ERROR = req->truncated_ ? MPI_ERR_TRUNCATE : MPI_SUCCESS;
1147     status->count = req->real_size_;
1148   }
1149   return MPI_SUCCESS;
1150 }
1151
1152 int Request::grequest_start(MPI_Grequest_query_function* query_fn, MPI_Grequest_free_function* free_fn,
1153                             MPI_Grequest_cancel_function* cancel_fn, void* extra_state, MPI_Request* request)
1154 {
1155   *request = new Request();
1156   (*request)->flags_ |= MPI_REQ_GENERALIZED;
1157   (*request)->flags_ |= MPI_REQ_PERSISTENT;
1158   (*request)->refcount_ = 1;
1159   ((*request)->generalized_funcs) = new s_smpi_mpi_generalized_request_funcs_t;
1160   ((*request)->generalized_funcs)->query_fn=query_fn;
1161   ((*request)->generalized_funcs)->free_fn=free_fn;
1162   ((*request)->generalized_funcs)->cancel_fn=cancel_fn;
1163   ((*request)->generalized_funcs)->extra_state=extra_state;
1164   ((*request)->generalized_funcs)->cond = simgrid::s4u::ConditionVariable::create();
1165   ((*request)->generalized_funcs)->mutex = simgrid::s4u::Mutex::create();
1166   return MPI_SUCCESS;
1167 }
1168
1169 int Request::grequest_complete(MPI_Request request)
1170 {
1171   if ((!(request->flags_ & MPI_REQ_GENERALIZED)) || request->generalized_funcs->mutex==NULL) 
1172     return MPI_ERR_REQUEST;
1173   request->generalized_funcs->mutex->lock();
1174   request->flags_ |= MPI_REQ_COMPLETE; // in case wait would be called after complete
1175   request->generalized_funcs->cond->notify_one();
1176   request->generalized_funcs->mutex->unlock();
1177   return MPI_SUCCESS;
1178 }
1179
1180 void Request::set_nbc_requests(MPI_Request* reqs, int size){
1181   nbc_requests_size_ = size;
1182   if (size > 0) {
1183     nbc_requests_ = reqs;
1184   } else {
1185     delete[] reqs;
1186     nbc_requests_ = nullptr;
1187   }
1188 }
1189
1190 int Request::get_nbc_requests_size(){
1191   return nbc_requests_size_;
1192 }
1193
1194 MPI_Request* Request::get_nbc_requests(){
1195   return nbc_requests_;
1196 }
1197
1198 }
1199 }