Logo AND Algorithmique Numérique Distribuée

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