Logo AND Algorithmique Numérique Distribuée

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