Logo AND Algorithmique Numérique Distribuée

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