Logo AND Algorithmique Numérique Distribuée

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