Logo AND Algorithmique Numérique Distribuée

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