Logo AND Algorithmique Numérique Distribuée

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