Logo AND Algorithmique Numérique Distribuée

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