Logo AND Algorithmique Numérique Distribuée

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