Logo AND Algorithmique Numérique Distribuée

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