Logo AND Algorithmique Numérique Distribuée

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