Logo AND Algorithmique Numérique Distribuée

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