Logo AND Algorithmique Numérique Distribuée

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