Logo AND Algorithmique Numérique Distribuée

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