Logo AND Algorithmique Numérique Distribuée

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