Logo AND Algorithmique Numérique Distribuée

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