Logo AND Algorithmique Numérique Distribuée

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