Logo AND Algorithmique Numérique Distribuée

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