Logo AND Algorithmique Numérique Distribuée

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