Logo AND Algorithmique Numérique Distribuée

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