Logo AND Algorithmique Numérique Distribuée

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