Logo AND Algorithmique Numérique Distribuée

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