Logo AND Algorithmique Numérique Distribuée

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