Logo AND Algorithmique Numérique Distribuée

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