Logo AND Algorithmique Numérique Distribuée

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