Logo AND Algorithmique Numérique Distribuée

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