Logo AND Algorithmique Numérique Distribuée

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