Logo AND Algorithmique Numérique Distribuée

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