Logo AND Algorithmique Numérique Distribuée

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