Logo AND Algorithmique Numérique Distribuée

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