Logo AND Algorithmique Numérique Distribuée

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