Logo AND Algorithmique Numérique Distribuée

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