]> AND Public Git Repository - simgrid.git/blob - src/smpi/mpi/smpi_request.cpp
Logo AND Algorithmique Numérique Distribuée

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