Logo AND Algorithmique Numérique Distribuée

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