Logo AND Algorithmique Numérique Distribuée

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