Logo AND Algorithmique Numérique Distribuée

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