Logo AND Algorithmique Numérique Distribuée

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