Logo AND Algorithmique Numérique Distribuée

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