Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
f29ae8a863b1e151de0f10117207fcf28ba31af4
[simgrid.git] / src / smpi / mpi / smpi_request.cpp
1 /* Copyright (c) 2007-2018. 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 "smpi_host.hpp"
9 #include "mc/mc.h"
10 #include "private.hpp"
11 #include "smpi_comm.hpp"
12 #include "smpi_datatype.hpp"
13 #include "smpi_op.hpp"
14 #include "smpi_process.hpp"
15 #include "src/kernel/activity/CommImpl.hpp"
16 #include "src/mc/mc_replay.hpp"
17 #include "src/simix/ActorImpl.hpp"
18 #include "xbt/config.hpp"
19 #include <xbt/ex.hpp>
20
21 #include <algorithm>
22
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_request, smpi, "Logging specific to SMPI (reques)");
24
25 static simgrid::config::Flag<double> smpi_iprobe_sleep(
26   "smpi/iprobe", "Minimum time to inject inside a call to MPI_Iprobe", 1e-4);
27 static simgrid::config::Flag<double> smpi_test_sleep(
28   "smpi/test", "Minimum time to inject inside a call to MPI_Test", 1e-4);
29
30 std::vector<s_smpi_factor_t> smpi_ois_values;
31
32 extern void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t);
33
34 namespace simgrid{
35 namespace smpi{
36
37 Request::Request(void* buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm, unsigned flags)
38     : buf_(buf), old_type_(datatype), src_(src), dst_(dst), tag_(tag), comm_(comm), flags_(flags)
39 {
40   void *old_buf = nullptr;
41 // FIXME Handle the case of a partial shared malloc.
42   if ((((flags & MPI_REQ_RECV) != 0) && ((flags & MPI_REQ_ACCUMULATE) != 0)) || (datatype->flags() & DT_FLAG_DERIVED)) {
43     // This part handles the problem of non-contiguous memory
44     old_buf = buf;
45     if (count==0){
46       buf_ = nullptr;
47     }else {
48       buf_ = xbt_malloc(count*datatype->size());
49       if ((datatype->flags() & DT_FLAG_DERIVED) && ((flags & MPI_REQ_SEND) != 0)) {
50         datatype->serialize(old_buf, buf_, count);
51       }
52     }
53   }
54   // This part handles the problem of non-contiguous memory (for the unserialisation at the reception)
55   old_buf_  = old_buf;
56   size_ = datatype->size() * count;
57   datatype->ref();
58   comm_->ref();
59   action_          = nullptr;
60   detached_        = 0;
61   detached_sender_ = nullptr;
62   real_src_        = 0;
63   truncated_       = 0;
64   real_size_       = 0;
65   real_tag_        = 0;
66   if (flags & MPI_REQ_PERSISTENT)
67     refcount_ = 1;
68   else
69     refcount_ = 0;
70   op_   = MPI_REPLACE;
71   cancelled_ = 0;
72 }
73
74 MPI_Comm Request::comm(){
75   return comm_;
76 }
77
78 int Request::src(){
79   return src_;
80 }
81
82 int Request::dst(){
83   return dst_;
84 }
85
86 int Request::tag(){
87   return tag_;
88 }
89
90 int Request::flags(){
91   return flags_;
92 }
93
94 int Request::detached(){
95   return detached_;
96 }
97
98 MPI_Datatype Request::type(){
99   return old_type_;
100 }
101
102 size_t Request::size(){
103   return size_;
104 }
105
106 size_t Request::real_size(){
107   return real_size_;
108 }
109
110 void Request::unref(MPI_Request* request)
111 {
112   if((*request) != MPI_REQUEST_NULL){
113     (*request)->refcount_--;
114     if((*request)->refcount_ < 0) {
115       (*request)->print_request("wrong refcount");
116       xbt_die("Whoops, wrong refcount");
117     }
118     if((*request)->refcount_==0){
119         Datatype::unref((*request)->old_type_);
120         Comm::unref((*request)->comm_);
121         (*request)->print_request("Destroying");
122         delete *request;
123         *request = MPI_REQUEST_NULL;
124     }else{
125       (*request)->print_request("Decrementing");
126     }
127   }else{
128     xbt_die("freeing an already free request");
129   }
130 }
131
132 int Request::match_recv(void* a, void* b, simgrid::kernel::activity::CommImpl* ignored)
133 {
134   MPI_Request ref = static_cast<MPI_Request>(a);
135   MPI_Request req = static_cast<MPI_Request>(b);
136   XBT_DEBUG("Trying to match a recv of src %d against %d, tag %d against %d",ref->src_,req->src_, ref->tag_, req->tag_);
137
138   xbt_assert(ref, "Cannot match recv against null reference");
139   xbt_assert(req, "Cannot match recv against null request");
140   if((ref->src_ == MPI_ANY_SOURCE || req->src_ == ref->src_)
141     && ((ref->tag_ == MPI_ANY_TAG && req->tag_ >=0) || req->tag_ == ref->tag_)){
142     //we match, we can transfer some values
143     if(ref->src_ == MPI_ANY_SOURCE)
144       ref->real_src_ = req->src_;
145     if(ref->tag_ == MPI_ANY_TAG)
146       ref->real_tag_ = req->tag_;
147     if(ref->real_size_ < req->real_size_)
148       ref->truncated_ = 1;
149     if(req->detached_==1)
150       ref->detached_sender_=req; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
151     if(req->cancelled_==0)
152       req->cancelled_=-1;//mark as uncancellable
153     XBT_DEBUG("match succeeded");
154     return 1;
155   }else return 0;
156 }
157
158 int Request::match_send(void* a, void* b, simgrid::kernel::activity::CommImpl* ignored)
159 {
160   MPI_Request ref = static_cast<MPI_Request>(a);
161   MPI_Request req = static_cast<MPI_Request>(b);
162   XBT_DEBUG("Trying to match a send of src %d against %d, tag %d against %d",ref->src_,req->src_, ref->tag_, req->tag_);
163   xbt_assert(ref, "Cannot match send against null reference");
164   xbt_assert(req, "Cannot match send against null request");
165
166   if((req->src_ == MPI_ANY_SOURCE || req->src_ == ref->src_)
167       && ((req->tag_ == MPI_ANY_TAG && ref->tag_ >=0)|| req->tag_ == ref->tag_)){
168     if(req->src_ == MPI_ANY_SOURCE)
169       req->real_src_ = ref->src_;
170     if(req->tag_ == MPI_ANY_TAG)
171       req->real_tag_ = ref->tag_;
172     if(req->real_size_ < ref->real_size_)
173       req->truncated_ = 1;
174     if(ref->detached_==1)
175       req->detached_sender_=ref; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
176     if(req->cancelled_==0)
177       req->cancelled_=-1;//mark as uncancellable
178     XBT_DEBUG("match succeeded");
179     return 1;
180   } else
181     return 0;
182 }
183
184 void Request::print_request(const char *message)
185 {
186   XBT_VERB("%s  request %p  [buf = %p, size = %zu, src = %d, dst = %d, tag = %d, flags = %x]",
187        message, this, buf_, size_, src_, dst_, tag_, flags_);
188 }
189
190
191 /* factories, to hide the internal flags from the caller */
192 MPI_Request Request::send_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
193 {
194
195   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
196                      comm->group()->actor(dst)->get_pid(), tag, comm,
197                      MPI_REQ_PERSISTENT | MPI_REQ_SEND | MPI_REQ_PREPARED);
198 }
199
200 MPI_Request Request::ssend_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
201 {
202   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
203                      comm->group()->actor(dst)->get_pid(), tag, comm,
204                      MPI_REQ_PERSISTENT | MPI_REQ_SSEND | MPI_REQ_SEND | MPI_REQ_PREPARED);
205 }
206
207 MPI_Request Request::isend_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
208 {
209   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
210                      comm->group()->actor(dst)->get_pid(), tag, comm,
211                      MPI_REQ_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_PREPARED);
212 }
213
214
215 MPI_Request Request::rma_send_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
216                                MPI_Op op)
217 {
218   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
219   if(op==MPI_OP_NULL){
220     request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src)->get_pid(),
221                           comm->group()->actor(dst)->get_pid(), tag, comm,
222                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_PREPARED);
223   }else{
224     request      = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src)->get_pid(),
225                           comm->group()->actor(dst)->get_pid(), tag, comm,
226                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND | MPI_REQ_PREPARED |
227                               MPI_REQ_ACCUMULATE);
228     request->op_ = op;
229   }
230   return request;
231 }
232
233 MPI_Request Request::recv_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::rma_recv_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
242                                MPI_Op op)
243 {
244   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
245   if(op==MPI_OP_NULL){
246     request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src)->get_pid(),
247                           comm->group()->actor(dst)->get_pid(), tag, comm,
248                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED);
249   }else{
250     request      = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, comm->group()->actor(src)->get_pid(),
251                           comm->group()->actor(dst)->get_pid(), tag, comm,
252                           MPI_REQ_RMA | MPI_REQ_NON_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED | MPI_REQ_ACCUMULATE);
253     request->op_ = op;
254   }
255   return request;
256 }
257
258 MPI_Request Request::irecv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
259 {
260   return new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype,
261                      src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : comm->group()->actor(src)->get_pid(),
262                      simgrid::s4u::this_actor::get_pid(), tag, comm,
263                      MPI_REQ_PERSISTENT | MPI_REQ_RECV | MPI_REQ_PREPARED);
264 }
265
266 MPI_Request Request::isend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
267 {
268   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
269   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
270                         comm->group()->actor(dst)->get_pid(), tag, comm,
271                         MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SEND);
272   request->start();
273   return request;
274 }
275
276 MPI_Request Request::issend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
277 {
278   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
279   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
280                         comm->group()->actor(dst)->get_pid(), tag, comm,
281                         MPI_REQ_NON_PERSISTENT | MPI_REQ_ISEND | MPI_REQ_SSEND | MPI_REQ_SEND);
282   request->start();
283   return request;
284 }
285
286
287 MPI_Request Request::irecv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
288 {
289   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
290   request             = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype,
291                         src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : comm->group()->actor(src)->get_pid(),
292                         simgrid::s4u::this_actor::get_pid(), tag, comm, MPI_REQ_NON_PERSISTENT | MPI_REQ_RECV);
293   request->start();
294   return request;
295 }
296
297 void Request::recv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm, MPI_Status * status)
298 {
299   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
300   request = irecv(buf, count, datatype, src, tag, comm);
301   wait(&request,status);
302   request = nullptr;
303 }
304
305 void Request::send(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
306 {
307   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
308   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
309                         comm->group()->actor(dst)->get_pid(), tag, comm, MPI_REQ_NON_PERSISTENT | MPI_REQ_SEND);
310
311   request->start();
312   wait(&request, MPI_STATUS_IGNORE);
313   request = nullptr;
314 }
315
316 void Request::ssend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
317 {
318   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
319   request = new Request(buf == MPI_BOTTOM ? nullptr : buf, count, datatype, simgrid::s4u::this_actor::get_pid(),
320                         comm->group()->actor(dst)->get_pid(), tag, comm,
321                         MPI_REQ_NON_PERSISTENT | MPI_REQ_SSEND | MPI_REQ_SEND);
322
323   request->start();
324   wait(&request,MPI_STATUS_IGNORE);
325   request = nullptr;
326 }
327
328 void Request::sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,int dst, int sendtag,
329                        void *recvbuf, int recvcount, MPI_Datatype recvtype, int src, int recvtag,
330                        MPI_Comm comm, MPI_Status * status)
331 {
332   MPI_Request requests[2];
333   MPI_Status stats[2];
334   int myid = simgrid::s4u::this_actor::get_pid();
335   if ((comm->group()->actor(dst)->get_pid() == myid) && (comm->group()->actor(src)->get_pid() == myid)) {
336     Datatype::copy(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype);
337     if (status != MPI_STATUS_IGNORE) {
338       status->MPI_SOURCE = src;
339       status->MPI_TAG    = recvtag;
340       status->MPI_ERROR  = MPI_SUCCESS;
341       status->count      = sendcount * sendtype->size();
342     }
343     return;
344   }
345   requests[0] = isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
346   requests[1] = irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
347   startall(2, requests);
348   waitall(2, requests, stats);
349   unref(&requests[0]);
350   unref(&requests[1]);
351   if(status != MPI_STATUS_IGNORE) {
352     // Copy receive status
353     *status = stats[1];
354   }
355 }
356
357 void Request::start()
358 {
359   smx_mailbox_t mailbox;
360
361   xbt_assert(action_ == nullptr, "Cannot (re-)start unfinished communication");
362   flags_ &= ~MPI_REQ_PREPARED;
363   flags_ &= ~MPI_REQ_FINISHED;
364   refcount_++;
365
366   if ((flags_ & MPI_REQ_RECV) != 0) {
367     this->print_request("New recv");
368
369     simgrid::smpi::Process* process = smpi_process_remote(simgrid::s4u::Actor::by_pid(dst_));
370
371     int async_small_thresh = simgrid::config::get_value<int>("smpi/async-small-thresh");
372
373     xbt_mutex_t mut = process->mailboxes_mutex();
374     if (async_small_thresh != 0 || (flags_ & MPI_REQ_RMA) != 0)
375       xbt_mutex_acquire(mut);
376
377     if (async_small_thresh == 0 && (flags_ & MPI_REQ_RMA) == 0) {
378       mailbox = process->mailbox();
379     } else if (((flags_ & MPI_REQ_RMA) != 0) || static_cast<int>(size_) < async_small_thresh) {
380       //We have to check both mailboxes (because SSEND messages are sent to the large mbox).
381       //begin with the more appropriate one : the small one.
382       mailbox = process->mailbox_small();
383       XBT_DEBUG("Is there a corresponding send already posted in the small mailbox %p (in case of SSEND)?", mailbox);
384       smx_activity_t action = simcall_comm_iprobe(mailbox, 0, &match_recv, static_cast<void*>(this));
385
386       if (action == nullptr) {
387         mailbox = process->mailbox();
388         XBT_DEBUG("No, nothing in the small mailbox test the other one : %p", mailbox);
389         action = simcall_comm_iprobe(mailbox, 0, &match_recv, static_cast<void*>(this));
390         if (action == nullptr) {
391           XBT_DEBUG("Still nothing, switch back to the small mailbox : %p", mailbox);
392           mailbox = process->mailbox_small();
393         }
394       } else {
395         XBT_DEBUG("yes there was something for us in the large mailbox");
396       }
397     } else {
398       mailbox = process->mailbox_small();
399       XBT_DEBUG("Is there a corresponding send already posted the small mailbox?");
400       smx_activity_t action = simcall_comm_iprobe(mailbox, 0, &match_recv, static_cast<void*>(this));
401
402       if (action == nullptr) {
403         XBT_DEBUG("No, nothing in the permanent receive mailbox");
404         mailbox = process->mailbox();
405       } else {
406         XBT_DEBUG("yes there was something for us in the small mailbox");
407       }
408     }
409
410     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
411     real_size_=size_;
412     action_   = simcall_comm_irecv(
413         process->get_actor()->get_impl(), mailbox, buf_, &real_size_, &match_recv,
414         process->replaying() ? &smpi_comm_null_copy_buffer_callback : smpi_comm_copy_data_callback, this, -1.0);
415     XBT_DEBUG("recv simcall posted");
416
417     if (async_small_thresh != 0 || (flags_ & MPI_REQ_RMA) != 0)
418       xbt_mutex_release(mut);
419   } else { /* the RECV flag was not set, so this is a send */
420     simgrid::smpi::Process* process = smpi_process_remote(simgrid::s4u::Actor::by_pid(dst_));
421     int rank = src_;
422     if (TRACE_smpi_view_internals()) {
423       TRACE_smpi_send(rank, rank, dst_, tag_, size_);
424     }
425     this->print_request("New send");
426
427     void* buf = buf_;
428     if ((flags_ & MPI_REQ_SSEND) == 0 &&
429         ((flags_ & MPI_REQ_RMA) != 0 ||
430          static_cast<int>(size_) < simgrid::config::get_value<int>("smpi/send-is-detached-thresh"))) {
431       void *oldbuf = nullptr;
432       detached_ = 1;
433       XBT_DEBUG("Send request %p is detached", this);
434       refcount_++;
435       if (not(old_type_->flags() & DT_FLAG_DERIVED)) {
436         oldbuf = buf_;
437         if (not process->replaying() && oldbuf != nullptr && size_ != 0) {
438           if ((smpi_privatize_global_variables != SmpiPrivStrategies::NONE) &&
439               (static_cast<char*>(buf_) >= smpi_data_exe_start) &&
440               (static_cast<char*>(buf_) < smpi_data_exe_start + smpi_data_exe_size)) {
441             XBT_DEBUG("Privatization : We are sending from a zone inside global memory. Switch data segment ");
442             smpi_switch_data_segment(simgrid::s4u::Actor::by_pid(src_));
443           }
444           buf = xbt_malloc(size_);
445           memcpy(buf,oldbuf,size_);
446           XBT_DEBUG("buf %p copied into %p",oldbuf,buf);
447         }
448       }
449     }
450
451     //if we are giving back the control to the user without waiting for completion, we have to inject timings
452     double sleeptime = 0.0;
453     if (detached_ != 0 || ((flags_ & (MPI_REQ_ISEND | MPI_REQ_SSEND)) != 0)) { // issend should be treated as isend
454       // isend and send timings may be different
455       sleeptime = ((flags_ & MPI_REQ_ISEND) != 0)
456                       ? simgrid::s4u::Actor::self()->get_host()->extension<simgrid::smpi::Host>()->oisend(size_)
457                       : simgrid::s4u::Actor::self()->get_host()->extension<simgrid::smpi::Host>()->osend(size_);
458     }
459
460     if(sleeptime > 0.0){
461       simcall_process_sleep(sleeptime);
462       XBT_DEBUG("sending size of %zu : sleep %f ", size_, sleeptime);
463     }
464
465     int async_small_thresh = simgrid::config::get_value<int>("smpi/async-small-thresh");
466
467     xbt_mutex_t mut=process->mailboxes_mutex();
468
469     if (async_small_thresh != 0 || (flags_ & MPI_REQ_RMA) != 0)
470       xbt_mutex_acquire(mut);
471
472     if (not(async_small_thresh != 0 || (flags_ & MPI_REQ_RMA) != 0)) {
473       mailbox = process->mailbox();
474     } else if (((flags_ & MPI_REQ_RMA) != 0) || static_cast<int>(size_) < async_small_thresh) { // eager mode
475       mailbox = process->mailbox();
476       XBT_DEBUG("Is there a corresponding recv already posted in the large mailbox %p?", mailbox);
477       smx_activity_t action = simcall_comm_iprobe(mailbox, 1, &match_send, static_cast<void*>(this));
478       if (action == nullptr) {
479         if ((flags_ & MPI_REQ_SSEND) == 0) {
480           mailbox = process->mailbox_small();
481           XBT_DEBUG("No, nothing in the large mailbox, message is to be sent on the small one %p", mailbox);
482         } else {
483           mailbox = process->mailbox_small();
484           XBT_DEBUG("SSEND : Is there a corresponding recv already posted in the small mailbox %p?", mailbox);
485           action = simcall_comm_iprobe(mailbox, 1, &match_send, static_cast<void*>(this));
486           if (action == nullptr) {
487             XBT_DEBUG("No, we are first, send to large mailbox");
488             mailbox = process->mailbox();
489           }
490         }
491       } else {
492         XBT_DEBUG("Yes there was something for us in the large mailbox");
493       }
494     } else {
495       mailbox = process->mailbox();
496       XBT_DEBUG("Send request %p is in the large mailbox %p (buf: %p)",mailbox, this,buf_);
497     }
498
499     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
500     real_size_=size_;
501     action_   = simcall_comm_isend(
502         simgrid::s4u::Actor::by_pid(src_)->get_impl(), mailbox, size_, -1.0, buf, real_size_, &match_send,
503         &xbt_free_f, // how to free the userdata if a detached send fails
504         not process->replaying() ? smpi_comm_copy_data_callback : &smpi_comm_null_copy_buffer_callback, this,
505         // detach if msg size < eager/rdv switch limit
506         detached_);
507     XBT_DEBUG("send simcall posted");
508
509     /* FIXME: detached sends are not traceable (action_ == nullptr) */
510     if (action_ != nullptr)
511       simcall_set_category(action_, TRACE_internal_smpi_get_category());
512     if (async_small_thresh != 0 || ((flags_ & MPI_REQ_RMA) != 0))
513       xbt_mutex_release(mut);
514   }
515 }
516
517 void Request::startall(int count, MPI_Request * requests)
518 {
519   if(requests== nullptr)
520     return;
521
522   for(int i = 0; i < count; i++) {
523     requests[i]->start();
524   }
525 }
526
527 void Request::cancel()
528 {
529   if(cancelled_!=-1)
530     cancelled_=1;
531   if (this->action_ != nullptr)
532     (boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(this->action_))->cancel();
533 }
534
535 int Request::test(MPI_Request * request, MPI_Status * status) {
536   //assume that request is not MPI_REQUEST_NULL (filtered in PMPI_Test or testall before)
537   // to avoid deadlocks if used as a break condition, such as
538   //     while (MPI_Test(request, flag, status) && flag) dostuff...
539   // because the time will not normally advance when only calls to MPI_Test are made -> deadlock
540   // multiplier to the sleeptime, to increase speed of execution, each failed test will increase it
541   static int nsleeps = 1;
542   if(smpi_test_sleep > 0)
543     simcall_process_sleep(nsleeps*smpi_test_sleep);
544
545   Status::empty(status);
546   int flag = 1;
547   if (((*request)->flags_ & MPI_REQ_PREPARED) == 0) {
548     if ((*request)->action_ != nullptr){
549       try{
550         flag = simcall_comm_test((*request)->action_);
551       }catch (xbt_ex& e) {
552         return 0;
553       }
554     }
555     if (flag) {
556       finish_wait(request,status);
557       nsleeps=1;//reset the number of sleeps we will do next time
558       if (*request != MPI_REQUEST_NULL && ((*request)->flags_ & MPI_REQ_PERSISTENT) == 0)
559         *request = MPI_REQUEST_NULL;
560     } else if (simgrid::config::get_value<bool>("smpi/grow-injected-times")) {
561       nsleeps++;
562     }
563   }
564   return flag;
565 }
566
567 int Request::testsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
568 {
569   int count = 0;
570   int count_dead = 0;
571   MPI_Status stat;
572   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
573
574   for (int i = 0; i < incount; i++) {
575     if (requests[i] != MPI_REQUEST_NULL) {
576       if (test(&requests[i], pstat)) {
577         indices[i] = 1;
578         count++;
579         if (status != MPI_STATUSES_IGNORE)
580           status[i] = *pstat;
581         if ((requests[i] != MPI_REQUEST_NULL) && (requests[i]->flags_ & MPI_REQ_NON_PERSISTENT))
582           requests[i] = MPI_REQUEST_NULL;
583       }
584     } else {
585       count_dead++;
586     }
587   }
588   if(count_dead==incount)
589     return MPI_UNDEFINED;
590   else return count;
591 }
592
593 int Request::testany(int count, MPI_Request requests[], int *index, MPI_Status * status)
594 {
595   std::vector<simgrid::kernel::activity::ActivityImplPtr> comms;
596   comms.reserve(count);
597
598   int i;
599   int flag = 0;
600
601   *index = MPI_UNDEFINED;
602
603   std::vector<int> map; /** Maps all matching comms back to their location in requests **/
604   for(i = 0; i < count; i++) {
605     if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->action_ && not(requests[i]->flags_ & MPI_REQ_PREPARED)) {
606       comms.push_back(requests[i]->action_);
607       map.push_back(i);
608     }
609   }
610   if (not map.empty()) {
611     //multiplier to the sleeptime, to increase speed of execution, each failed testany will increase it
612     static int nsleeps = 1;
613     if(smpi_test_sleep > 0)
614       simcall_process_sleep(nsleeps*smpi_test_sleep);
615     try{
616       i = simcall_comm_testany(comms.data(), comms.size()); // The i-th element in comms matches!
617     }catch (xbt_ex& e) {
618       return 0;
619     }
620     
621     if (i != -1) { // -1 is not MPI_UNDEFINED but a SIMIX return code. (nothing matches)
622       *index = map[i];
623       finish_wait(&requests[*index],status);
624       flag             = 1;
625       nsleeps          = 1;
626       if (requests[*index] != MPI_REQUEST_NULL && (requests[*index]->flags_ & MPI_REQ_NON_PERSISTENT)) {
627         requests[*index] = MPI_REQUEST_NULL;
628       }
629     } else {
630       nsleeps++;
631     }
632   } else {
633       //all requests are null or inactive, return true
634       flag = 1;
635       Status::empty(status);
636   }
637
638   return flag;
639 }
640
641 int Request::testall(int count, MPI_Request requests[], MPI_Status status[])
642 {
643   MPI_Status stat;
644   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
645   int flag=1;
646   for(int i=0; i<count; i++){
647     if (requests[i] != MPI_REQUEST_NULL && not(requests[i]->flags_ & MPI_REQ_PREPARED)) {
648       if (test(&requests[i], pstat)!=1){
649         flag=0;
650       }else{
651           requests[i]=MPI_REQUEST_NULL;
652       }
653     }else{
654       Status::empty(pstat);
655     }
656     if(status != MPI_STATUSES_IGNORE) {
657       status[i] = *pstat;
658     }
659   }
660   return flag;
661 }
662
663 void Request::probe(int source, int tag, MPI_Comm comm, MPI_Status* status){
664   int flag=0;
665   //FIXME find another way to avoid busy waiting ?
666   // the issue here is that we have to wait on a nonexistent comm
667   while(flag==0){
668     iprobe(source, tag, comm, &flag, status);
669     XBT_DEBUG("Busy Waiting on probing : %d", flag);
670   }
671 }
672
673 void Request::iprobe(int source, int tag, MPI_Comm comm, int* flag, MPI_Status* status){
674   // to avoid deadlock, we have to sleep some time here, or the timer won't advance and we will only do iprobe simcalls
675   // especially when used as a break condition, such as while (MPI_Iprobe(...)) dostuff...
676   // nsleeps is a multiplier to the sleeptime, to increase speed of execution, each failed iprobe will increase it
677   // This can speed up the execution of certain applications by an order of magnitude, such as HPL
678   static int nsleeps = 1;
679   double speed        = simgrid::s4u::Actor::self()->get_host()->getSpeed();
680   double maxrate      = simgrid::config::get_value<double>("smpi/iprobe-cpu-usage");
681   MPI_Request request = new Request(nullptr, 0, MPI_CHAR,
682                                     source == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : comm->group()->actor(source)->get_pid(),
683                                     simgrid::s4u::this_actor::get_pid(), tag, comm, MPI_REQ_PERSISTENT | MPI_REQ_RECV);
684   if (smpi_iprobe_sleep > 0) {
685     smx_activity_t iprobe_sleep = simcall_execution_start(
686         "iprobe", /* flops to executek*/ nsleeps * smpi_iprobe_sleep * speed * maxrate, /* priority */ 1.0,
687         /* performance bound */ maxrate * speed, smpi_process()->get_actor()->get_host());
688     simcall_execution_wait(iprobe_sleep);
689   }
690   // behave like a receive, but don't do it
691   smx_mailbox_t mailbox;
692
693   request->print_request("New iprobe");
694   // We have to test both mailboxes as we don't know if we will receive one one or another
695   if (simgrid::config::get_value<int>("smpi/async-small-thresh") > 0) {
696     mailbox = smpi_process()->mailbox_small();
697     XBT_DEBUG("Trying to probe the perm recv mailbox");
698     request->action_ = simcall_comm_iprobe(mailbox, 0, &match_recv, static_cast<void*>(request));
699   }
700
701   if (request->action_ == nullptr){
702     mailbox = smpi_process()->mailbox();
703     XBT_DEBUG("trying to probe the other mailbox");
704     request->action_ = simcall_comm_iprobe(mailbox, 0, &match_recv, static_cast<void*>(request));
705   }
706
707   if (request->action_ != nullptr){
708     simgrid::kernel::activity::CommImplPtr sync_comm =
709         boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(request->action_);
710     MPI_Request req                            = static_cast<MPI_Request>(sync_comm->src_data);
711     *flag = 1;
712     if (status != MPI_STATUS_IGNORE && (req->flags_ & MPI_REQ_PREPARED) == 0) {
713       status->MPI_SOURCE = comm->group()->rank(req->src_);
714       status->MPI_TAG    = req->tag_;
715       status->MPI_ERROR  = MPI_SUCCESS;
716       status->count      = req->real_size_;
717     }
718     nsleeps = 1;//reset the number of sleeps we will do next time
719   }
720   else {
721     *flag = 0;
722     if (simgrid::config::get_value<bool>("smpi/grow-injected-times"))
723       nsleeps++;
724   }
725   unref(&request);
726 }
727
728 void Request::finish_wait(MPI_Request* request, MPI_Status * status)
729 {
730   MPI_Request req = *request;
731   Status::empty(status);
732   
733   if (req->cancelled_==1){
734     if (status!=MPI_STATUS_IGNORE)
735       status->cancelled=1;
736     return;
737   }
738
739   if (not((req->detached_ != 0) && ((req->flags_ & MPI_REQ_SEND) != 0)) && ((req->flags_ & MPI_REQ_PREPARED) == 0)) {
740     if(status != MPI_STATUS_IGNORE) {
741       int src = req->src_ == MPI_ANY_SOURCE ? req->real_src_ : req->src_;
742       status->MPI_SOURCE = req->comm_->group()->rank(src);
743       status->MPI_TAG = req->tag_ == MPI_ANY_TAG ? req->real_tag_ : req->tag_;
744       status->MPI_ERROR = req->truncated_ != 0 ? MPI_ERR_TRUNCATE : MPI_SUCCESS;
745       // this handles the case were size in receive differs from size in send
746       status->count = req->real_size_;
747     }
748
749     req->print_request("Finishing");
750     MPI_Datatype datatype = req->old_type_;
751
752 // FIXME Handle the case of a partial shared malloc.
753     if (((req->flags_ & MPI_REQ_ACCUMULATE) != 0) ||
754         (datatype->flags() & DT_FLAG_DERIVED)) { // && (not smpi_is_shared(req->old_buf_))){
755
756       if (not smpi_process()->replaying() && smpi_privatize_global_variables != SmpiPrivStrategies::NONE &&
757           static_cast<char*>(req->old_buf_) >= smpi_data_exe_start &&
758           static_cast<char*>(req->old_buf_) < smpi_data_exe_start + smpi_data_exe_size) {
759         XBT_VERB("Privatization : We are unserializing to a zone in global memory  Switch data segment ");
760         smpi_switch_data_segment(simgrid::s4u::Actor::self());
761       }
762
763       if(datatype->flags() & DT_FLAG_DERIVED){
764         // This part handles the problem of non-contignous memory the unserialization at the reception
765         if ((req->flags_ & MPI_REQ_RECV) && datatype->size() != 0)
766           datatype->unserialize(req->buf_, req->old_buf_, req->real_size_/datatype->size() , req->op_);
767         xbt_free(req->buf_);
768       } else if (req->flags_ & MPI_REQ_RECV) { // apply op on contiguous buffer for accumulate
769         if (datatype->size() != 0) {
770           int n = req->real_size_ / datatype->size();
771           req->op_->apply(req->buf_, req->old_buf_, &n, datatype);
772         }
773         xbt_free(req->buf_);
774       }
775     }
776   }
777
778   if (TRACE_smpi_view_internals() && ((req->flags_ & MPI_REQ_RECV) != 0)) {
779     int rank       = simgrid::s4u::this_actor::get_pid();
780     int src_traced = (req->src_ == MPI_ANY_SOURCE ? req->real_src_ : req->src_);
781     TRACE_smpi_recv(src_traced, rank,req->tag_);
782   }
783   if(req->detached_sender_ != nullptr){
784     //integrate pseudo-timing for buffering of small messages, do not bother to execute the simcall if 0
785     double sleeptime =
786         simgrid::s4u::Actor::self()->get_host()->extension<simgrid::smpi::Host>()->orecv(req->real_size());
787     if(sleeptime > 0.0){
788       simcall_process_sleep(sleeptime);
789       XBT_DEBUG("receiving size of %zu : sleep %f ", req->real_size_, sleeptime);
790     }
791     unref(&(req->detached_sender_));
792   }
793   if (req->flags_ & MPI_REQ_PERSISTENT)
794     req->action_ = nullptr;
795   req->flags_ |= MPI_REQ_FINISHED;
796   unref(request);
797 }
798
799 void Request::wait(MPI_Request * request, MPI_Status * status)
800 {
801   (*request)->print_request("Waiting");
802   if ((*request)->flags_ & MPI_REQ_PREPARED) {
803     Status::empty(status);
804     return;
805   }
806
807   if ((*request)->action_ != nullptr){
808       try{
809         // this is not a detached send
810         simcall_comm_wait((*request)->action_, -1.0);
811       }catch (xbt_ex& e) {
812         XBT_VERB("Request cancelled");
813       }
814   }
815
816
817   finish_wait(request,status);
818   if (*request != MPI_REQUEST_NULL && (((*request)->flags_ & MPI_REQ_NON_PERSISTENT) != 0))
819     *request = MPI_REQUEST_NULL;
820 }
821
822 int Request::waitany(int count, MPI_Request requests[], MPI_Status * status)
823 {
824   s_xbt_dynar_t comms; // Keep it on stack to save some extra mallocs
825   int index = MPI_UNDEFINED;
826
827   if(count > 0) {
828     int size = 0;
829     // Wait for a request to complete
830     xbt_dynar_init(&comms, sizeof(smx_activity_t), [](void*ptr){
831       intrusive_ptr_release(*(simgrid::kernel::activity::ActivityImpl**)ptr);
832     });
833     int *map = xbt_new(int, count);
834     XBT_DEBUG("Wait for one of %d", count);
835     for(int i = 0; i < count; i++) {
836       if (requests[i] != MPI_REQUEST_NULL && not(requests[i]->flags_ & MPI_REQ_PREPARED) &&
837           not(requests[i]->flags_ & MPI_REQ_FINISHED)) {
838         if (requests[i]->action_ != nullptr) {
839           XBT_DEBUG("Waiting any %p ", requests[i]);
840           intrusive_ptr_add_ref(requests[i]->action_.get());
841           xbt_dynar_push_as(&comms, simgrid::kernel::activity::ActivityImpl*, requests[i]->action_.get());
842           map[size] = i;
843           size++;
844         } else {
845           // This is a finished detached request, let's return this one
846           size  = 0; // so we free the dynar but don't do the waitany call
847           index = i;
848           finish_wait(&requests[i], status); // cleanup if refcount = 0
849           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags_ & MPI_REQ_NON_PERSISTENT))
850             requests[i] = MPI_REQUEST_NULL; // set to null
851           break;
852         }
853       }
854     }
855     if (size > 0) {
856       XBT_DEBUG("Enter waitany for %lu comms", xbt_dynar_length(&comms));
857       int i=MPI_UNDEFINED;
858       try{
859         // this is not a detached send
860         i = simcall_comm_waitany(&comms, -1);
861       }catch (xbt_ex& e) {
862       XBT_INFO("request %d cancelled ",i);
863         return i;
864       }
865
866       // not MPI_UNDEFINED, as this is a simix return code
867       if (i != -1) {
868         index = map[i];
869         //in case of an accumulate, we have to wait the end of all requests to apply the operation, ordered correctly.
870         if ((requests[index] == MPI_REQUEST_NULL) ||
871             (not((requests[index]->flags_ & MPI_REQ_ACCUMULATE) && (requests[index]->flags_ & MPI_REQ_RECV)))) {
872           finish_wait(&requests[index],status);
873           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags_ & MPI_REQ_NON_PERSISTENT))
874             requests[index] = MPI_REQUEST_NULL;
875         }
876       }
877     }
878
879     xbt_dynar_free_data(&comms);
880     xbt_free(map);
881   }
882
883   if (index==MPI_UNDEFINED)
884     Status::empty(status);
885
886   return index;
887 }
888
889 static int sort_accumulates(MPI_Request a, MPI_Request b)
890 {
891   return (a->tag() > b->tag());
892 }
893
894 int Request::waitall(int count, MPI_Request requests[], MPI_Status status[])
895 {
896   std::vector<MPI_Request> accumulates;
897   int index;
898   MPI_Status stat;
899   MPI_Status *pstat = (status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat);
900   int retvalue = MPI_SUCCESS;
901   //tag invalid requests in the set
902   if (status != MPI_STATUSES_IGNORE) {
903     for (int c = 0; c < count; c++) {
904       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst_ == MPI_PROC_NULL ||
905           (requests[c]->flags_ & MPI_REQ_PREPARED)) {
906         Status::empty(&status[c]);
907       } else if (requests[c]->src_ == MPI_PROC_NULL) {
908         Status::empty(&status[c]);
909         status[c].MPI_SOURCE = MPI_PROC_NULL;
910       }
911     }
912   }
913   for (int c = 0; c < count; c++) {
914     if (MC_is_active() || MC_record_replay_is_active()) {
915       wait(&requests[c],pstat);
916       index = c;
917     } else {
918       index = waitany(count, (MPI_Request*)requests, pstat);
919       
920       if (index == MPI_UNDEFINED)
921         break;
922
923       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & MPI_REQ_RECV) &&
924           (requests[index]->flags_ & MPI_REQ_ACCUMULATE))
925         accumulates.push_back(requests[index]);
926       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & MPI_REQ_NON_PERSISTENT))
927         requests[index] = MPI_REQUEST_NULL;
928     }
929     if (status != MPI_STATUSES_IGNORE) {
930       status[index] = *pstat;
931       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
932         retvalue = MPI_ERR_IN_STATUS;
933     }
934   }
935
936   if (not accumulates.empty()) {
937     std::sort(accumulates.begin(), accumulates.end(), sort_accumulates);
938     for (auto& req : accumulates) {
939       finish_wait(&req, status);
940     }
941   }
942
943   return retvalue;
944 }
945
946 int Request::waitsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
947 {
948   int count = 0;
949   MPI_Status stat;
950   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
951
952   for (int i = 0; i < incount; i++) {
953     int index = waitany(incount, requests, pstat);
954     if(index!=MPI_UNDEFINED){
955       indices[count] = index;
956       count++;
957       if(status != MPI_STATUSES_IGNORE) {
958         status[index] = *pstat;
959       }
960       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & MPI_REQ_NON_PERSISTENT))
961         requests[index] = MPI_REQUEST_NULL;
962     }else{
963       return MPI_UNDEFINED;
964     }
965   }
966   return count;
967 }
968
969 MPI_Request Request::f2c(int id) {
970   char key[KEY_SIZE];
971   if(id==MPI_FORTRAN_REQUEST_NULL)
972     return static_cast<MPI_Request>(MPI_REQUEST_NULL);
973   return static_cast<MPI_Request>(F2C::f2c_lookup()->at(get_key_id(key, id)));
974 }
975
976 int Request::add_f()
977 {
978   if (F2C::f2c_lookup() == nullptr) {
979     F2C::set_f2c_lookup(new std::unordered_map<std::string, F2C*>);
980   }
981   char key[KEY_SIZE];
982   (*(F2C::f2c_lookup()))[get_key_id(key, F2C::f2c_id())] = this;
983   F2C::f2c_id_increment();
984   return F2C::f2c_id()-1;
985 }
986
987 void Request::free_f(int id)
988 {
989   if (id != MPI_FORTRAN_REQUEST_NULL) {
990     char key[KEY_SIZE];
991     F2C::f2c_lookup()->erase(get_key_id(key, id));
992   }
993 }
994
995 }
996 }