Logo AND Algorithmique Numérique Distribuée

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