Logo AND Algorithmique Numérique Distribuée

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