Logo AND Algorithmique Numérique Distribuée

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