Logo AND Algorithmique Numérique Distribuée

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