Logo AND Algorithmique Numérique Distribuée

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