Logo AND Algorithmique Numérique Distribuée

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