Logo AND Algorithmique Numérique Distribuée

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