Logo AND Algorithmique Numérique Distribuée

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