Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Potential crash --
[simgrid.git] / src / smpi / smpi_request.cpp
1 /* Copyright (c) 2007-2017. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <xbt/config.hpp>
7 #include <algorithm>
8 #include "private.h"
9 #include "mc/mc.h"
10 #include "src/mc/mc_replay.h"
11 #include "src/simix/smx_private.h"
12 #include "simgrid/sg_config.h"
13 #include "smpi/smpi_utils.hpp"
14 #include <simgrid/s4u/host.hpp>
15 #include "src/kernel/activity/SynchroComm.hpp"
16
17 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_request, smpi, "Logging specific to SMPI (reques)");
18
19 static simgrid::config::Flag<double> smpi_iprobe_sleep(
20   "smpi/iprobe", "Minimum time to inject inside a call to MPI_Iprobe", 1e-4);
21 static simgrid::config::Flag<double> smpi_test_sleep(
22   "smpi/test", "Minimum time to inject inside a call to MPI_Test", 1e-4);
23
24 std::vector<s_smpi_factor_t> smpi_os_values;
25 std::vector<s_smpi_factor_t> smpi_or_values;
26 std::vector<s_smpi_factor_t> smpi_ois_values;
27
28 extern void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t);
29
30 static double smpi_os(size_t size)
31 {
32   if (smpi_os_values.empty()) {
33     smpi_os_values = parse_factor(xbt_cfg_get_string("smpi/os"));
34   }
35   double current=smpi_os_values.empty()?0.0:smpi_os_values[0].values[0]+smpi_os_values[0].values[1]*size;
36   // Iterate over all the sections that were specified and find the right
37   // value. (fact.factor represents the interval sizes; we want to find the
38   // section that has fact.factor <= size and no other such fact.factor <= size)
39   // Note: parse_factor() (used before) already sorts the vector we iterate over!
40   for (auto& fact : smpi_os_values) {
41     if (size <= fact.factor) { // Values already too large, use the previously computed value of current!
42       XBT_DEBUG("os : %zu <= %zu return %.10f", size, fact.factor, current);
43       return current;
44     }else{
45       // If the next section is too large, the current section must be used.
46       // Hence, save the cost, as we might have to use it.
47       current = fact.values[0]+fact.values[1]*size;
48     }
49   }
50   XBT_DEBUG("Searching for smpi/os: %zu is larger than the largest boundary, return %.10f", size, current);
51
52   return current;
53 }
54
55 static double smpi_ois(size_t size)
56 {
57   if (smpi_ois_values.empty()) {
58     smpi_ois_values = parse_factor(xbt_cfg_get_string("smpi/ois"));
59   }
60   double current=smpi_ois_values.empty()?0.0:smpi_ois_values[0].values[0]+smpi_ois_values[0].values[1]*size;
61   // Iterate over all the sections that were specified and find the right value. (fact.factor represents the interval
62   // sizes; we want to find the section that has fact.factor <= size and no other such fact.factor <= size)
63   // Note: parse_factor() (used before) already sorts the vector we iterate over!
64   for (auto& fact : smpi_ois_values) {
65     if (size <= fact.factor) { // Values already too large, use the previously  computed value of current!
66       XBT_DEBUG("ois : %zu <= %zu return %.10f", size, fact.factor, current);
67       return current;
68     }else{
69       // If the next section is too large, the current section must be used.
70       // Hence, save the cost, as we might have to use it.
71       current = fact.values[0]+fact.values[1]*size;
72     }
73   }
74   XBT_DEBUG("Searching for smpi/ois: %zu is larger than the largest boundary, return %.10f", size, current);
75
76   return current;
77 }
78
79 static double smpi_or(size_t size)
80 {
81   if (smpi_or_values.empty()) {
82     smpi_or_values = parse_factor(xbt_cfg_get_string("smpi/or"));
83   }
84   
85   double current=smpi_or_values.empty()?0.0:smpi_or_values.front().values[0]+smpi_or_values.front().values[1]*size;
86
87   // Iterate over all the sections that were specified and find the right value. (fact.factor represents the interval
88   // sizes; we want to find the section that has fact.factor <= size and no other such fact.factor <= size)
89   // Note: parse_factor() (used before) already sorts the vector we iterate over!
90   for (auto fact : smpi_or_values) {
91     if (size <= fact.factor) { // Values already too large, use the previously computed value of current!
92       XBT_DEBUG("or : %zu <= %zu return %.10f", size, fact.factor, current);
93       return current;
94     } else {
95       // If the next section is too large, the current section must be used.
96       // Hence, save the cost, as we might have to use it.
97       current=fact.values[0]+fact.values[1]*size;
98     }
99   }
100   XBT_DEBUG("smpi_or: %zu is larger than largest boundary, return %.10f", size, current);
101
102   return current;
103 }
104
105 namespace simgrid{
106 namespace smpi{
107
108 Request::Request(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm, unsigned flags) : buf_(buf), old_type_(datatype), src_(src), dst_(dst), tag_(tag), comm_(comm), flags_(flags) 
109 {
110   void *old_buf = nullptr;
111   if(((((flags & RECV) != 0) && ((flags & ACCUMULATE) !=0)) || (datatype->flags() & DT_FLAG_DERIVED)) && (!smpi_is_shared(buf_))){
112     // This part handles the problem of non-contiguous memory
113     old_buf = buf;
114     buf_ = count==0 ? nullptr : xbt_malloc(count*datatype->size());
115     if ((datatype->flags() & DT_FLAG_DERIVED) && ((flags & SEND) != 0)) {
116       datatype->serialize(old_buf, buf_, count);
117     }
118   }
119   // This part handles the problem of non-contiguous memory (for the unserialisation at the reception)
120   old_buf_  = old_buf;
121   size_ = datatype->size() * count;
122   datatype->ref();
123   comm_->ref();
124   action_          = nullptr;
125   detached_        = 0;
126   detached_sender_ = nullptr;
127   real_src_        = 0;
128   truncated_       = 0;
129   real_size_       = 0;
130   real_tag_        = 0;
131   if (flags & PERSISTENT)
132     refcount_ = 1;
133   else
134     refcount_ = 0;
135   op_   = MPI_REPLACE;
136 }
137
138 MPI_Comm Request::comm(){
139   return comm_;
140 }
141
142 int Request::src(){
143   return src_;
144 }
145
146 int Request::dst(){
147   return dst_;
148 }
149
150 int Request::tag(){
151   return tag_;
152 }
153
154 int Request::flags(){
155   return flags_;
156 }
157
158 int Request::detached(){
159   return detached_;
160 }
161
162 size_t Request::size(){
163   return size_;
164 }
165
166 size_t Request::real_size(){
167   return real_size_;
168 }
169
170 void Request::unref(MPI_Request* request)
171 {
172   if((*request) != MPI_REQUEST_NULL){
173     (*request)->refcount_--;
174     if((*request)->refcount_<0) xbt_die("wrong refcount");
175     if((*request)->refcount_==0){
176         Datatype::unref((*request)->old_type_);
177         Comm::unref((*request)->comm_);
178         (*request)->print_request("Destroying");
179         delete *request;
180         *request = MPI_REQUEST_NULL;
181     }else{
182       (*request)->print_request("Decrementing");
183     }
184   }else{
185     xbt_die("freeing an already free request");
186   }
187 }
188
189 int Request::match_recv(void* a, void* b, smx_activity_t ignored) {
190   MPI_Request ref = static_cast<MPI_Request>(a);
191   MPI_Request req = static_cast<MPI_Request>(b);
192   XBT_DEBUG("Trying to match a recv of src %d against %d, tag %d against %d",ref->src_,req->src_, ref->tag_, req->tag_);
193
194   xbt_assert(ref, "Cannot match recv against null reference");
195   xbt_assert(req, "Cannot match recv against null request");
196   if((ref->src_ == MPI_ANY_SOURCE || req->src_ == ref->src_)
197     && ((ref->tag_ == MPI_ANY_TAG && req->tag_ >=0) || req->tag_ == ref->tag_)){
198     //we match, we can transfer some values
199     if(ref->src_ == MPI_ANY_SOURCE)
200       ref->real_src_ = req->src_;
201     if(ref->tag_ == MPI_ANY_TAG)
202       ref->real_tag_ = req->tag_;
203     if(ref->real_size_ < req->real_size_) 
204       ref->truncated_ = 1;
205     if(req->detached_==1)
206       ref->detached_sender_=req; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
207     XBT_DEBUG("match succeeded");
208     return 1;
209   }else return 0;
210 }
211
212 int Request::match_send(void* a, void* b,smx_activity_t ignored) {
213   MPI_Request ref = static_cast<MPI_Request>(a);
214   MPI_Request req = static_cast<MPI_Request>(b);
215   XBT_DEBUG("Trying to match a send of src %d against %d, tag %d against %d",ref->src_,req->src_, ref->tag_, req->tag_);
216   xbt_assert(ref, "Cannot match send against null reference");
217   xbt_assert(req, "Cannot match send against null request");
218
219   if((req->src_ == MPI_ANY_SOURCE || req->src_ == ref->src_)
220       && ((req->tag_ == MPI_ANY_TAG && ref->tag_ >=0)|| req->tag_ == ref->tag_)){
221     if(req->src_ == MPI_ANY_SOURCE)
222       req->real_src_ = ref->src_;
223     if(req->tag_ == MPI_ANY_TAG)
224       req->real_tag_ = ref->tag_;
225     if(req->real_size_ < ref->real_size_)
226       req->truncated_ = 1;
227     if(ref->detached_==1)
228       req->detached_sender_=ref; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
229     XBT_DEBUG("match succeeded");
230     return 1;
231   } else
232     return 0;
233 }
234
235 void Request::print_request(const char *message)
236 {
237   XBT_VERB("%s  request %p  [buf = %p, size = %zu, src = %d, dst = %d, tag = %d, flags = %x]",
238        message, this, buf_, size_, src_, dst_, tag_, flags_);
239 }
240
241
242 /* factories, to hide the internal flags from the caller */
243 MPI_Request Request::send_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
244 {
245
246   return new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process()->index(),
247                           comm->group()->index(dst), tag, comm, PERSISTENT | SEND | PREPARED);
248 }
249
250 MPI_Request Request::ssend_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
251 {
252   return new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process()->index(),
253                         comm->group()->index(dst), tag, comm, PERSISTENT | SSEND | SEND | PREPARED);
254 }
255
256 MPI_Request Request::isend_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
257 {
258   return new Request(buf==MPI_BOTTOM ? nullptr : buf , count, datatype, smpi_process()->index(),
259                           comm->group()->index(dst), tag,comm, PERSISTENT | ISEND | SEND | PREPARED);
260 }
261
262
263 MPI_Request Request::rma_send_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
264                                MPI_Op op)
265 {
266   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
267   if(op==MPI_OP_NULL){
268     request = new Request(buf==MPI_BOTTOM ? nullptr : buf , count, datatype, src, dst, tag,
269                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED);
270   }else{
271     request = new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,  src, dst, tag,
272                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED | ACCUMULATE);
273     request->op_ = op;
274   }
275   return request;
276 }
277
278 MPI_Request Request::recv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
279 {
280   return new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,
281                           src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : comm->group()->index(src),
282                           smpi_process()->index(), tag, comm, PERSISTENT | RECV | PREPARED);
283 }
284
285 MPI_Request Request::rma_recv_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
286                                MPI_Op op)
287 {
288   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
289   if(op==MPI_OP_NULL){
290     request = new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,  src, dst, tag,
291                             comm, RMA | NON_PERSISTENT | RECV | PREPARED);
292   }else{
293     request = new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,  src, dst, tag,
294                             comm, RMA | NON_PERSISTENT | RECV | PREPARED | ACCUMULATE);
295     request->op_ = op;
296   }
297   return request;
298 }
299
300 MPI_Request Request::irecv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
301 {
302   return new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
303                           comm->group()->index(src), smpi_process()->index(), tag,
304                           comm, PERSISTENT | RECV | PREPARED);
305 }
306
307 MPI_Request Request::isend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
308 {
309   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
310   request =  new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process()->index(),
311                            comm->group()->index(dst), tag, comm, NON_PERSISTENT | ISEND | SEND);
312   request->start();
313   return request;
314 }
315
316 MPI_Request Request::issend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
317 {
318   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
319   request = new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process()->index(),
320                         comm->group()->index(dst), tag,comm, NON_PERSISTENT | ISEND | SSEND | SEND);
321   request->start();
322   return request;
323 }
324
325
326 MPI_Request Request::irecv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
327 {
328   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
329   request = new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
330                           comm->group()->index(src), smpi_process()->index(), tag, comm,
331                           NON_PERSISTENT | RECV);
332   request->start();
333   return request;
334 }
335
336 void Request::recv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm, MPI_Status * status)
337 {
338   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
339   request = irecv(buf, count, datatype, src, tag, comm);
340   wait(&request,status);
341   request = nullptr;
342 }
343
344 void Request::send(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
345 {
346   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
347   request = new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process()->index(),
348                           comm->group()->index(dst), tag, comm, NON_PERSISTENT | SEND);
349
350   request->start();
351   wait(&request, MPI_STATUS_IGNORE);
352   request = nullptr;
353 }
354
355 void Request::ssend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
356 {
357   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
358   request = new Request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process()->index(),
359                           comm->group()->index(dst), tag, comm, NON_PERSISTENT | SSEND | SEND);
360
361   request->start();
362   wait(&request,MPI_STATUS_IGNORE);
363   request = nullptr;
364 }
365
366 void Request::sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,int dst, int sendtag,
367                        void *recvbuf, int recvcount, MPI_Datatype recvtype, int src, int recvtag,
368                        MPI_Comm comm, MPI_Status * status)
369 {
370   MPI_Request requests[2];
371   MPI_Status stats[2];
372   int myid=smpi_process()->index();
373   if ((comm->group()->index(dst) == myid) && (comm->group()->index(src) == myid)){
374       Datatype::copy(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype);
375       return;
376   }
377   requests[0] = isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
378   requests[1] = irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
379   startall(2, requests);
380   waitall(2, requests, stats);
381   unref(&requests[0]);
382   unref(&requests[1]);
383   if(status != MPI_STATUS_IGNORE) {
384     // Copy receive status
385     *status = stats[1];
386   }
387 }
388
389 void Request::start()
390 {
391   smx_mailbox_t mailbox;
392
393   xbt_assert(action_ == nullptr, "Cannot (re-)start unfinished communication");
394   flags_ &= ~PREPARED;
395   flags_ &= ~FINISHED;
396   refcount_++;
397
398   if ((flags_ & RECV) != 0) {
399     this->print_request("New recv");
400
401     simgrid::smpi::Process* process = smpi_process_remote(dst_);
402
403     int async_small_thresh = xbt_cfg_get_int("smpi/async-small-thresh");
404
405     xbt_mutex_t mut = process->mailboxes_mutex();
406     if (async_small_thresh != 0 || (flags_ & RMA) != 0)
407       xbt_mutex_acquire(mut);
408
409     if (async_small_thresh == 0 && (flags_ & RMA) == 0 ) {
410       mailbox = process->mailbox();
411     } 
412     else if (((flags_ & RMA) != 0) || static_cast<int>(size_) < async_small_thresh) {
413       //We have to check both mailboxes (because SSEND messages are sent to the large mbox).
414       //begin with the more appropriate one : the small one.
415       mailbox = process->mailbox_small();
416       XBT_DEBUG("Is there a corresponding send already posted in the small mailbox %p (in case of SSEND)?", mailbox);
417       smx_activity_t action = simcall_comm_iprobe(mailbox, 0, src_,tag_, &match_recv,
418                                                   static_cast<void*>(this));
419
420       if (action == nullptr) {
421         mailbox = process->mailbox();
422         XBT_DEBUG("No, nothing in the small mailbox test the other one : %p", mailbox);
423         action = simcall_comm_iprobe(mailbox, 0, src_,tag_, &match_recv, static_cast<void*>(this));
424         if (action == nullptr) {
425           XBT_DEBUG("Still nothing, switch back to the small mailbox : %p", mailbox);
426           mailbox = process->mailbox_small();
427         }
428       } else {
429         XBT_DEBUG("yes there was something for us in the large mailbox");
430       }
431     } else {
432       mailbox = process->mailbox_small();
433       XBT_DEBUG("Is there a corresponding send already posted the small mailbox?");
434       smx_activity_t action = simcall_comm_iprobe(mailbox, 0, src_,tag_, &match_recv, static_cast<void*>(this));
435
436       if (action == nullptr) {
437         XBT_DEBUG("No, nothing in the permanent receive mailbox");
438         mailbox = process->mailbox();
439       } else {
440         XBT_DEBUG("yes there was something for us in the small mailbox");
441       }
442     }
443
444     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
445     real_size_=size_;
446     action_ = simcall_comm_irecv(process->process(), mailbox, buf_, &real_size_, &match_recv,
447                                          ! process->replaying()? smpi_comm_copy_data_callback
448                                          : &smpi_comm_null_copy_buffer_callback, this, -1.0);
449     XBT_DEBUG("recv simcall posted");
450
451     if (async_small_thresh != 0 || (flags_ & RMA) != 0 )
452       xbt_mutex_release(mut);
453   } else { /* the RECV flag was not set, so this is a send */
454     simgrid::smpi::Process* process = smpi_process_remote(dst_);
455     int rank = src_;
456     if (TRACE_smpi_view_internals()) {
457       TRACE_smpi_send(rank, rank, dst_, 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 (!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=process->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 = process->mailbox();
505     } else if (((flags_ & RMA) != 0) || static_cast<int>(size_) < async_small_thresh) { // eager mode
506       mailbox = process->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 = process->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 = process->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 = process->mailbox();
521           }
522         }
523       } else {
524         XBT_DEBUG("Yes there was something for us in the large mailbox");
525       }
526     } else {
527       mailbox = process->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                          !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)) && (!smpi_is_shared(req->old_buf_))){
763
764       if (!smpi_process()->replaying()){
765         if( smpi_privatize_global_variables != 0 && (static_cast<char*>(req->old_buf_) >= smpi_start_data_exe)
766             && ((char*)req->old_buf_ < smpi_start_data_exe + smpi_size_data_exe )){
767             XBT_VERB("Privatization : We are unserializing to a zone in global memory  Switch data segment ");
768             smpi_switch_data_segment(smpi_process()->index());
769         }
770       }
771
772       if(datatype->flags() & DT_FLAG_DERIVED){
773         // This part handles the problem of non-contignous memory the unserialization at the reception
774         if((req->flags_ & RECV) && datatype->size()!=0)
775           datatype->unserialize(req->buf_, req->old_buf_, req->real_size_/datatype->size() , req->op_);
776         xbt_free(req->buf_);
777       }else if(req->flags_ & RECV){//apply op on contiguous buffer for accumulate
778           if(datatype->size()!=0){
779             int n =req->real_size_/datatype->size();
780             req->op_->apply(req->buf_, req->old_buf_, &n, datatype);
781           }
782           xbt_free(req->buf_);
783       }
784     }
785   }
786
787   if (TRACE_smpi_view_internals() && ((req->flags_ & RECV) != 0)){
788     int rank = smpi_process()->index();
789     int src_traced = (req->src_ == MPI_ANY_SOURCE ? req->real_src_ : req->src_);
790     TRACE_smpi_recv(rank, src_traced, rank,req->tag_);
791   }
792   if(req->detached_sender_ != nullptr){
793     //integrate pseudo-timing for buffering of small messages, do not bother to execute the simcall if 0
794     double sleeptime = smpi_or(req->real_size_);
795     if(sleeptime > 0.0){
796       simcall_process_sleep(sleeptime);
797       XBT_DEBUG("receiving size of %zu : sleep %f ", req->real_size_, sleeptime);
798     }
799     unref(&(req->detached_sender_));
800   }
801   if(req->flags_ & PERSISTENT)
802     req->action_ = nullptr;
803   req->flags_ |= FINISHED;
804   unref(request);
805 }
806
807 void Request::wait(MPI_Request * request, MPI_Status * status)
808 {
809   (*request)->print_request("Waiting");
810   if ((*request)->flags_ & PREPARED) {
811     Status::empty(status);
812     return;
813   }
814
815   if ((*request)->action_ != nullptr)
816     // this is not a detached send
817     simcall_comm_wait((*request)->action_, -1.0);
818
819   finish_wait(request,status);
820   if (*request != MPI_REQUEST_NULL && (((*request)->flags_ & NON_PERSISTENT)!=0))
821     *request = MPI_REQUEST_NULL;
822 }
823
824 int Request::waitany(int count, MPI_Request requests[], MPI_Status * status)
825 {
826   s_xbt_dynar_t comms; // Keep it on stack to save some extra mallocs
827   int i;
828   int size = 0;
829   int index = MPI_UNDEFINED;
830   int *map;
831
832   if(count > 0) {
833     // Wait for a request to complete
834     xbt_dynar_init(&comms, sizeof(smx_activity_t), nullptr);
835     map = xbt_new(int, count);
836     XBT_DEBUG("Wait for one of %d", count);
837     for(i = 0; i < count; i++) {
838       if (requests[i] != MPI_REQUEST_NULL && !(requests[i]->flags_ & PREPARED) && !(requests[i]->flags_ & FINISHED)) {
839         if (requests[i]->action_ != nullptr) {
840           XBT_DEBUG("Waiting any %p ", requests[i]);
841           xbt_dynar_push(&comms, &requests[i]->action_);
842           map[size] = i;
843           size++;
844         } else {
845           // This is a finished detached request, let's return this one
846           size  = 0; // so we free the dynar but don't do the waitany call
847           index = i;
848           finish_wait(&requests[i], status); // cleanup if refcount = 0
849           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags_ & NON_PERSISTENT))
850             requests[i] = MPI_REQUEST_NULL; // set to null
851           break;
852         }
853       }
854     }
855     if(size > 0) {
856       i = simcall_comm_waitany(&comms, -1);
857
858       // not MPI_UNDEFINED, as this is a simix return code
859       if (i != -1) {
860         index = map[i];
861         //in case of an accumulate, we have to wait the end of all requests to apply the operation, ordered correctly.
862         if ((requests[index] == MPI_REQUEST_NULL)
863              ||  (!((requests[index]->flags_ & ACCUMULATE) && (requests[index]->flags_ & RECV)))){
864           finish_wait(&requests[index],status);
865           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags_ & NON_PERSISTENT))
866             requests[index] = MPI_REQUEST_NULL;
867         }
868       }
869     }
870
871     xbt_dynar_free_data(&comms);
872     xbt_free(map);
873   }
874
875   if (index==MPI_UNDEFINED)
876     Status::empty(status);
877
878   return index;
879 }
880
881 static int sort_accumulates(MPI_Request a, MPI_Request b)
882 {
883   return (a->tag() > b->tag());
884 }
885
886 int Request::waitall(int count, MPI_Request requests[], MPI_Status status[])
887 {
888   std::vector<MPI_Request> accumulates;
889   int index;
890   MPI_Status stat;
891   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
892   int retvalue = MPI_SUCCESS;
893   //tag invalid requests in the set
894   if (status != MPI_STATUSES_IGNORE) {
895     for (int c = 0; c < count; c++) {
896       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst_ == MPI_PROC_NULL || (requests[c]->flags_ & PREPARED)) {
897         Status::empty(&status[c]);
898       } else if (requests[c]->src_ == MPI_PROC_NULL) {
899         Status::empty(&status[c]);
900         status[c].MPI_SOURCE = MPI_PROC_NULL;
901       }
902     }
903   }
904   for (int c = 0; c < count; c++) {
905     if (MC_is_active() || MC_record_replay_is_active()) {
906       wait(&requests[c],pstat);
907       index = c;
908     } else {
909       index = waitany(count, requests, pstat);
910       if (index == MPI_UNDEFINED)
911         break;
912
913       if (requests[index] != MPI_REQUEST_NULL
914            && (requests[index]->flags_ & RECV)
915            && (requests[index]->flags_ & ACCUMULATE))
916         accumulates.push_back(requests[index]);
917       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & NON_PERSISTENT))
918         requests[index] = MPI_REQUEST_NULL;
919     }
920     if (status != MPI_STATUSES_IGNORE) {
921       status[index] = *pstat;
922       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
923         retvalue = MPI_ERR_IN_STATUS;
924     }
925   }
926
927   if (!accumulates.empty()) {
928     std::sort(accumulates.begin(), accumulates.end(), sort_accumulates);
929     for (auto req : accumulates) {
930       finish_wait(&req, status);
931     }
932   }
933
934   return retvalue;
935 }
936
937 int Request::waitsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
938 {
939   int i;
940   int count = 0;
941   int index;
942   MPI_Status stat;
943   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
944
945   for(i = 0; i < incount; i++)
946   {
947     index=waitany(incount, requests, pstat);
948     if(index!=MPI_UNDEFINED){
949       indices[count] = index;
950       count++;
951       if(status != MPI_STATUSES_IGNORE) {
952         status[index] = *pstat;
953       }
954      if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags_ & NON_PERSISTENT))
955      requests[index]=MPI_REQUEST_NULL;
956     }else{
957       return MPI_UNDEFINED;
958     }
959   }
960   return count;
961 }
962
963 MPI_Request Request::f2c(int id) {
964   char key[KEY_SIZE];
965   if(id==MPI_FORTRAN_REQUEST_NULL)
966     return static_cast<MPI_Request>(MPI_REQUEST_NULL);
967   return static_cast<MPI_Request>(xbt_dict_get(F2C::f2c_lookup(), get_key_id(key, id)));
968 }
969
970 int Request::add_f() {
971   if(F2C::f2c_lookup()==nullptr){
972     F2C::set_f2c_lookup(xbt_dict_new_homogeneous(nullptr));
973   }
974   char key[KEY_SIZE];
975   xbt_dict_set(F2C::f2c_lookup(), get_key_id(key, F2C::f2c_id()), this, nullptr);
976   F2C::f2c_id_increment();
977   return F2C::f2c_id()-1;
978 }
979
980 void Request::free_f(int id) {
981   char key[KEY_SIZE];
982   if(id!=MPI_FORTRAN_REQUEST_NULL)
983     xbt_dict_remove(F2C::f2c_lookup(), get_key_id(key, id));
984 }
985
986 }
987 }
988
989
990