Logo AND Algorithmique Numérique Distribuée

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