Logo AND Algorithmique Numérique Distribuée

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