Logo AND Algorithmique Numérique Distribuée

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