Logo AND Algorithmique Numérique Distribuée

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