Logo AND Algorithmique Numérique Distribuée

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