Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[SMPI] Introduced smpi/iprobe-cpu-usage option.
[simgrid.git] / src / smpi / smpi_base.cpp
1 /* Copyright (c) 2007-2015. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include <xbt/config.hpp>
8 #include <algorithm>
9
10 #include "private.h"
11 #include "xbt/virtu.h"
12 #include "mc/mc.h"
13 #include "src/mc/mc_replay.h"
14 #include "xbt/replay.h"
15 #include <errno.h>
16 #include "src/simix/smx_private.h"
17 #include "surf/surf.h"
18 #include "simgrid/sg_config.h"
19 #include "smpi/smpi_utils.hpp"
20 #include "colls/colls.h"
21
22 #include "src/kernel/activity/SynchroComm.hpp"
23
24 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_base, smpi, "Logging specific to SMPI (base)");
25
26 extern void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t);
27
28
29 static int match_recv(void* a, void* b, smx_activity_t ignored) {
30   MPI_Request ref = static_cast<MPI_Request>(a);
31   MPI_Request req = static_cast<MPI_Request>(b);
32   XBT_DEBUG("Trying to match a recv of src %d against %d, tag %d against %d",ref->src,req->src, ref->tag, req->tag);
33
34   xbt_assert(ref, "Cannot match recv against null reference");
35   xbt_assert(req, "Cannot match recv against null request");
36   if((ref->src == MPI_ANY_SOURCE || req->src == ref->src)
37     && ((ref->tag == MPI_ANY_TAG && req->tag >=0) || req->tag == ref->tag)){
38     //we match, we can transfer some values
39     if(ref->src == MPI_ANY_SOURCE)
40       ref->real_src = req->src;
41     if(ref->tag == MPI_ANY_TAG)
42       ref->real_tag = req->tag;
43     if(ref->real_size < req->real_size) 
44       ref->truncated = 1;
45     if(req->detached==1)
46       ref->detached_sender=req; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
47     XBT_DEBUG("match succeeded");
48     return 1;
49   }else return 0;
50 }
51
52 static int match_send(void* a, void* b,smx_activity_t ignored) {
53   MPI_Request ref = static_cast<MPI_Request>(a);
54   MPI_Request req = static_cast<MPI_Request>(b);
55   XBT_DEBUG("Trying to match a send of src %d against %d, tag %d against %d",ref->src,req->src, ref->tag, req->tag);
56   xbt_assert(ref, "Cannot match send against null reference");
57   xbt_assert(req, "Cannot match send against null request");
58
59   if((req->src == MPI_ANY_SOURCE || req->src == ref->src)
60       && ((req->tag == MPI_ANY_TAG && ref->tag >=0)|| req->tag == ref->tag)){
61     if(req->src == MPI_ANY_SOURCE)
62       req->real_src = ref->src;
63     if(req->tag == MPI_ANY_TAG)
64       req->real_tag = ref->tag;
65     if(req->real_size < ref->real_size)
66       req->truncated = 1;
67     if(ref->detached==1)
68       req->detached_sender=ref; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
69     XBT_DEBUG("match succeeded");
70     return 1;
71   } else
72     return 0;
73 }
74
75 std::vector<s_smpi_factor_t> smpi_os_values;
76 std::vector<s_smpi_factor_t> smpi_or_values;
77 std::vector<s_smpi_factor_t> smpi_ois_values;
78
79 static simgrid::config::Flag<double> smpi_wtime_sleep(
80   "smpi/wtime", "Minimum time to inject inside a call to MPI_Wtime", 0.0);
81 static simgrid::config::Flag<double> smpi_init_sleep(
82   "smpi/init", "Time to inject inside a call to MPI_Init", 0.0);
83 static simgrid::config::Flag<double> smpi_iprobe_sleep(
84   "smpi/iprobe", "Minimum time to inject inside a call to MPI_Iprobe", 1e-4);
85 static simgrid::config::Flag<double> smpi_test_sleep(
86   "smpi/test", "Minimum time to inject inside a call to MPI_Test", 1e-4);
87
88
89 static double smpi_os(size_t size)
90 {
91   if (smpi_os_values.empty()) {
92     smpi_os_values = parse_factor(xbt_cfg_get_string("smpi/os"));
93   }
94   double current=smpi_os_values.empty()?0.0:smpi_os_values[0].values[0]+smpi_os_values[0].values[1]*size;
95   // Iterate over all the sections that were specified and find the right
96   // value. (fact.factor represents the interval sizes; we want to find the
97   // section that has fact.factor <= size and no other such fact.factor <= size)
98   // Note: parse_factor() (used before) already sorts the vector we iterate over!
99   for (auto& fact : smpi_os_values) {
100     if (size <= fact.factor) { // Values already too large, use the previously computed value of current!
101       XBT_DEBUG("os : %zu <= %zu return %.10f", size, fact.factor, current);
102       return current;
103     }else{
104       // If the next section is too large, the current section must be used.
105       // Hence, save the cost, as we might have to use it.
106       current = fact.values[0]+fact.values[1]*size;
107     }
108   }
109   XBT_DEBUG("Searching for smpi/os: %zu is larger than the largest boundary, return %.10f", size, current);
110
111   return current;
112 }
113
114 static double smpi_ois(size_t size)
115 {
116   if (smpi_ois_values.empty()) {
117     smpi_ois_values = parse_factor(xbt_cfg_get_string("smpi/ois"));
118   }
119   double current=smpi_ois_values.empty()?0.0:smpi_ois_values[0].values[0]+smpi_ois_values[0].values[1]*size;
120   // Iterate over all the sections that were specified and find the right value. (fact.factor represents the interval
121   // sizes; we want to find the section that has fact.factor <= size and no other such fact.factor <= size)
122   // Note: parse_factor() (used before) already sorts the vector we iterate over!
123   for (auto& fact : smpi_ois_values) {
124     if (size <= fact.factor) { // Values already too large, use the previously  computed value of current!
125       XBT_DEBUG("ois : %zu <= %zu return %.10f", size, fact.factor, current);
126       return current;
127     }else{
128       // If the next section is too large, the current section must be used.
129       // Hence, save the cost, as we might have to use it.
130       current = fact.values[0]+fact.values[1]*size;
131     }
132   }
133   XBT_DEBUG("Searching for smpi/ois: %zu is larger than the largest boundary, return %.10f", size, current);
134
135   return current;
136 }
137
138 static double smpi_or(size_t size)
139 {
140   if (smpi_or_values.empty()) {
141     smpi_or_values = parse_factor(xbt_cfg_get_string("smpi/or"));
142   }
143   
144   double current=smpi_or_values.empty()?0.0:smpi_or_values.front().values[0]+smpi_or_values.front().values[1]*size;
145
146   // Iterate over all the sections that were specified and find the right value. (fact.factor represents the interval
147   // sizes; we want to find the section that has fact.factor <= size and no other such fact.factor <= size)
148   // Note: parse_factor() (used before) already sorts the vector we iterate over!
149   for (auto fact : smpi_or_values) {
150     if (size <= fact.factor) { // Values already too large, use the previously computed value of current!
151       XBT_DEBUG("or : %zu <= %zu return %.10f", size, fact.factor, current);
152       return current;
153     } else {
154       // If the next section is too large, the current section must be used.
155       // Hence, save the cost, as we might have to use it.
156       current=fact.values[0]+fact.values[1]*size;
157     }
158   }
159   XBT_DEBUG("smpi_or: %zu is larger than largest boundary, return %.10f", size, current);
160
161   return current;
162 }
163
164 void smpi_mpi_init() {
165   if(smpi_init_sleep > 0) 
166     simcall_process_sleep(smpi_init_sleep);
167 }
168
169 double smpi_mpi_wtime(){
170   double time;
171   if (smpi_process_initialized() != 0 && smpi_process_finalized() == 0 && smpi_process_get_sampling() == 0) {
172     smpi_bench_end();
173     time = SIMIX_get_clock();
174     // to avoid deadlocks if used as a break condition, such as
175     //     while (MPI_Wtime(...) < time_limit) {
176     //       ....
177     //     }
178     // because the time will not normally advance when only calls to MPI_Wtime
179     // are made -> deadlock (MPI_Wtime never reaches the time limit)
180     if(smpi_wtime_sleep > 0) 
181       simcall_process_sleep(smpi_wtime_sleep);
182     smpi_bench_begin();
183   } else {
184     time = SIMIX_get_clock();
185   }
186   return time;
187 }
188
189 static MPI_Request build_request(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
190                                  unsigned flags)
191 {
192   MPI_Request request = nullptr;
193
194   void *old_buf = nullptr;
195
196   request = xbt_new(s_smpi_mpi_request_t, 1);
197
198   s_smpi_subtype_t *subtype = static_cast<s_smpi_subtype_t*>(datatype->substruct);
199
200   if((((flags & RECV) != 0) && ((flags & ACCUMULATE) !=0)) || (datatype->sizeof_substruct != 0)){
201     // This part handles the problem of non-contiguous memory
202     old_buf = buf;
203     buf = count==0 ? nullptr : xbt_malloc(count*smpi_datatype_size(datatype));
204     if ((datatype->sizeof_substruct != 0) && ((flags & SEND) != 0)) {
205       subtype->serialize(old_buf, buf, count, datatype->substruct);
206     }
207   }
208
209   request->buf      = buf;
210   // This part handles the problem of non-contiguous memory (for the unserialisation at the reception)
211   request->old_buf  = old_buf;
212   request->old_type = datatype;
213
214   request->size = smpi_datatype_size(datatype) * count;
215   smpi_datatype_use(datatype);
216   request->src  = src;
217   request->dst  = dst;
218   request->tag  = tag;
219   request->comm = comm;
220   smpi_comm_use(request->comm);
221   request->action          = nullptr;
222   request->flags           = flags;
223   request->detached        = 0;
224   request->detached_sender = nullptr;
225   request->real_src        = 0;
226   request->truncated       = 0;
227   request->real_size       = 0;
228   request->real_tag        = 0;
229   if (flags & PERSISTENT)
230     request->refcount = 1;
231   else
232     request->refcount = 0;
233   request->op   = MPI_REPLACE;
234   request->send = 0;
235   request->recv = 0;
236
237   return request;
238 }
239
240 void smpi_empty_status(MPI_Status * status)
241 {
242   if(status != MPI_STATUS_IGNORE) {
243     status->MPI_SOURCE = MPI_ANY_SOURCE;
244     status->MPI_TAG = MPI_ANY_TAG;
245     status->MPI_ERROR = MPI_SUCCESS;
246     status->count=0;
247   }
248 }
249
250 static void smpi_mpi_request_free_voidp(void* request)
251 {
252   MPI_Request req = static_cast<MPI_Request>(request);
253   smpi_mpi_request_free(&req);
254 }
255
256 /* MPI Low level calls */
257 MPI_Request smpi_mpi_send_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
258 {
259   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
260   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
261                           smpi_group_index(smpi_comm_group(comm), dst), tag, comm, PERSISTENT | SEND | PREPARED);
262   return request;
263 }
264
265 MPI_Request smpi_mpi_ssend_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
266 {
267   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
268   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
269                         smpi_group_index(smpi_comm_group(comm), dst), tag, comm, PERSISTENT | SSEND | SEND | PREPARED);
270   return request;
271 }
272
273 MPI_Request smpi_mpi_recv_init(void *buf, int count, MPI_Datatype datatype, int src, 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 = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,
277                           src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : smpi_group_index(smpi_comm_group(comm), src),
278                           smpi_process_index(), tag, comm, PERSISTENT | RECV | PREPARED);
279   return request;
280 }
281
282 void smpi_mpi_start(MPI_Request request)
283 {
284   smx_mailbox_t mailbox;
285
286   xbt_assert(request->action == nullptr, "Cannot (re-)start unfinished communication");
287   request->flags &= ~PREPARED;
288   request->flags &= ~FINISHED;
289   request->refcount++;
290
291   if ((request->flags & RECV) != 0) {
292     print_request("New recv", request);
293
294     int async_small_thresh = xbt_cfg_get_int("smpi/async-small-thresh");
295
296     xbt_mutex_t mut = smpi_process_mailboxes_mutex();
297     if (async_small_thresh != 0 || (request->flags & RMA) != 0)
298       xbt_mutex_acquire(mut);
299
300     if (async_small_thresh == 0 && (request->flags & RMA) == 0 ) {
301       mailbox = smpi_process_mailbox();
302     } 
303     else if (((request->flags & RMA) != 0) || static_cast<int>(request->size) < async_small_thresh) {
304       //We have to check both mailboxes (because SSEND messages are sent to the large mbox).
305       //begin with the more appropriate one : the small one.
306       mailbox = smpi_process_mailbox_small();
307       XBT_DEBUG("Is there a corresponding send already posted in the small mailbox %p (in case of SSEND)?", mailbox);
308       smx_activity_t action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv,
309                                                   static_cast<void*>(request));
310
311       if (action == nullptr) {
312         mailbox = smpi_process_mailbox();
313         XBT_DEBUG("No, nothing in the small mailbox test the other one : %p", mailbox);
314         action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv, static_cast<void*>(request));
315         if (action == nullptr) {
316           XBT_DEBUG("Still nothing, switch back to the small mailbox : %p", mailbox);
317           mailbox = smpi_process_mailbox_small();
318         }
319       } else {
320         XBT_DEBUG("yes there was something for us in the large mailbox");
321       }
322     } else {
323       mailbox = smpi_process_mailbox_small();
324       XBT_DEBUG("Is there a corresponding send already posted the small mailbox?");
325       smx_activity_t action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv, (void*)request);
326
327       if (action == nullptr) {
328         XBT_DEBUG("No, nothing in the permanent receive mailbox");
329         mailbox = smpi_process_mailbox();
330       } else {
331         XBT_DEBUG("yes there was something for us in the small mailbox");
332       }
333     }
334
335     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
336     request->real_size=request->size;
337     request->action = simcall_comm_irecv(SIMIX_process_self(), mailbox, request->buf, &request->real_size, &match_recv,
338                                          ! smpi_process_get_replaying()? smpi_comm_copy_data_callback
339                                          : &smpi_comm_null_copy_buffer_callback, request, -1.0);
340     XBT_DEBUG("recv simcall posted");
341
342     if (async_small_thresh != 0 || (request->flags & RMA) != 0 )
343       xbt_mutex_release(mut);
344   } else { /* the RECV flag was not set, so this is a send */
345     int receiver = request->dst;
346
347     int rank = request->src;
348     if (TRACE_smpi_view_internals()) {
349       TRACE_smpi_send(rank, rank, receiver, request->tag, request->size);
350     }
351     print_request("New send", request);
352
353     void* buf = request->buf;
354     if ((request->flags & SSEND) == 0 && ( (request->flags & RMA) != 0
355         || static_cast<int>(request->size) < xbt_cfg_get_int("smpi/send-is-detached-thresh") ) ) {
356       void *oldbuf = nullptr;
357       request->detached = 1;
358       XBT_DEBUG("Send request %p is detached", request);
359       request->refcount++;
360       if(request->old_type->sizeof_substruct == 0){
361         oldbuf = request->buf;
362         if (!smpi_process_get_replaying() && oldbuf != nullptr && request->size!=0){
363           if((smpi_privatize_global_variables != 0)
364             && (static_cast<char*>(request->buf) >= smpi_start_data_exe)
365             && (static_cast<char*>(request->buf) < smpi_start_data_exe + smpi_size_data_exe )){
366             XBT_DEBUG("Privatization : We are sending from a zone inside global memory. Switch data segment ");
367             smpi_switch_data_segment(request->src);
368           }
369           buf = xbt_malloc(request->size);
370           memcpy(buf,oldbuf,request->size);
371           XBT_DEBUG("buf %p copied into %p",oldbuf,buf);
372         }
373       }
374     }
375
376     //if we are giving back the control to the user without waiting for completion, we have to inject timings
377     double sleeptime = 0.0;
378     if(request->detached != 0 || ((request->flags & (ISEND|SSEND)) != 0)){// issend should be treated as isend
379       //isend and send timings may be different
380       sleeptime = ((request->flags & ISEND) != 0) ? smpi_ois(request->size) : smpi_os(request->size);
381     }
382
383     if(sleeptime > 0.0){
384       simcall_process_sleep(sleeptime);
385       XBT_DEBUG("sending size of %zu : sleep %f ", request->size, sleeptime);
386     }
387
388     int async_small_thresh = xbt_cfg_get_int("smpi/async-small-thresh");
389
390     xbt_mutex_t mut=smpi_process_remote_mailboxes_mutex(receiver);
391
392     if (async_small_thresh != 0 || (request->flags & RMA) != 0)
393       xbt_mutex_acquire(mut);
394
395     if (!(async_small_thresh != 0 || (request->flags & RMA) !=0)) {
396       mailbox = smpi_process_remote_mailbox(receiver);
397     } else if (((request->flags & RMA) != 0) || static_cast<int>(request->size) < async_small_thresh) { // eager mode
398       mailbox = smpi_process_remote_mailbox(receiver);
399       XBT_DEBUG("Is there a corresponding recv already posted in the large mailbox %p?", mailbox);
400       smx_activity_t action = simcall_comm_iprobe(mailbox, 1,request->dst, request->tag, &match_send,
401                                                   static_cast<void*>(request));
402       if (action == nullptr) {
403         if ((request->flags & SSEND) == 0){
404           mailbox = smpi_process_remote_mailbox_small(receiver);
405           XBT_DEBUG("No, nothing in the large mailbox, message is to be sent on the small one %p", mailbox);
406         } else {
407           mailbox = smpi_process_remote_mailbox_small(receiver);
408           XBT_DEBUG("SSEND : Is there a corresponding recv already posted in the small mailbox %p?", mailbox);
409           action = simcall_comm_iprobe(mailbox, 1,request->dst, request->tag, &match_send, static_cast<void*>(request));
410           if (action == nullptr) {
411             XBT_DEBUG("No, we are first, send to large mailbox");
412             mailbox = smpi_process_remote_mailbox(receiver);
413           }
414         }
415       } else {
416         XBT_DEBUG("Yes there was something for us in the large mailbox");
417       }
418     } else {
419       mailbox = smpi_process_remote_mailbox(receiver);
420       XBT_DEBUG("Send request %p is in the large mailbox %p (buf: %p)",mailbox, request,request->buf);
421     }
422
423     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
424     request->real_size=request->size;
425     request->action = simcall_comm_isend(SIMIX_process_from_PID(request->src+1), mailbox, request->size, -1.0,
426                                          buf, request->real_size, &match_send,
427                          &xbt_free_f, // how to free the userdata if a detached send fails
428                          !smpi_process_get_replaying() ? smpi_comm_copy_data_callback
429                          : &smpi_comm_null_copy_buffer_callback, request,
430                          // detach if msg size < eager/rdv switch limit
431                          request->detached);
432     XBT_DEBUG("send simcall posted");
433
434     /* FIXME: detached sends are not traceable (request->action == nullptr) */
435     if (request->action != nullptr)
436       simcall_set_category(request->action, TRACE_internal_smpi_get_category());
437
438     if (async_small_thresh != 0 || ((request->flags & RMA)!=0))
439       xbt_mutex_release(mut);
440   }
441 }
442
443 void smpi_mpi_startall(int count, MPI_Request * requests)
444 {
445   if(requests== nullptr) 
446     return;
447
448   for(int i = 0; i < count; i++) {
449     smpi_mpi_start(requests[i]);
450   }
451 }
452
453 void smpi_mpi_request_free(MPI_Request * request)
454 {
455   if((*request) != MPI_REQUEST_NULL){
456     (*request)->refcount--;
457     if((*request)->refcount<0) xbt_die("wrong refcount");
458
459     if((*request)->refcount==0){
460         smpi_datatype_unuse((*request)->old_type);
461         smpi_comm_unuse((*request)->comm);
462         print_request("Destroying", (*request));
463         xbt_free(*request);
464         *request = MPI_REQUEST_NULL;
465     }else{
466       print_request("Decrementing", (*request));
467     }
468   }else{
469     xbt_die("freeing an already free request");
470   }
471 }
472
473 MPI_Request smpi_rma_send_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
474                                MPI_Op op)
475 {
476   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
477   if(op==MPI_OP_NULL){
478     request = build_request(buf==MPI_BOTTOM ? nullptr : buf , count, datatype, src, dst, tag,
479                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED);
480   }else{
481     request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,  src, dst, tag,
482                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED | ACCUMULATE);
483     request->op = op;
484   }
485   return request;
486 }
487
488 MPI_Request smpi_rma_recv_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
489                                MPI_Op op)
490 {
491   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
492   if(op==MPI_OP_NULL){
493     request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,  src, dst, tag,
494                             comm, RMA | NON_PERSISTENT | RECV | PREPARED);
495   }else{
496     request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,  src, dst, tag,
497                             comm, RMA | NON_PERSISTENT | RECV | PREPARED | ACCUMULATE);
498     request->op = op;
499   }
500   return request;
501 }
502
503 MPI_Request smpi_isend_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
504 {
505   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
506   request = build_request(buf==MPI_BOTTOM ? nullptr : buf , count, datatype, smpi_process_index(),
507                           smpi_group_index(smpi_comm_group(comm), dst), tag,comm, PERSISTENT | ISEND | SEND | PREPARED);
508   return request;
509 }
510
511 MPI_Request smpi_mpi_isend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
512 {
513   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
514   request =  build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
515                            smpi_group_index(smpi_comm_group(comm), dst), tag, comm, NON_PERSISTENT | ISEND | SEND);
516   smpi_mpi_start(request);
517   return request;
518 }
519
520 MPI_Request smpi_mpi_issend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
521 {
522   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
523   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
524                         smpi_group_index(smpi_comm_group(comm), dst), tag,comm, NON_PERSISTENT | ISEND | SSEND | SEND);
525   smpi_mpi_start(request);
526   return request;
527 }
528
529 MPI_Request smpi_irecv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
530 {
531   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
532   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
533                           smpi_group_index(smpi_comm_group(comm), src), smpi_process_index(), tag,
534                           comm, PERSISTENT | RECV | PREPARED);
535   return request;
536 }
537
538 MPI_Request smpi_mpi_irecv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
539 {
540   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
541   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
542                           smpi_group_index(smpi_comm_group(comm), src), smpi_process_index(), tag, comm,
543                           NON_PERSISTENT | RECV);
544   smpi_mpi_start(request);
545   return request;
546 }
547
548 void smpi_mpi_recv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm, MPI_Status * status)
549 {
550   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
551   request = smpi_mpi_irecv(buf, count, datatype, src, tag, comm);
552   smpi_mpi_wait(&request, status);
553   request = nullptr;
554 }
555
556 void smpi_mpi_send(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
557 {
558   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
559   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
560                           smpi_group_index(smpi_comm_group(comm), dst), tag, comm, NON_PERSISTENT | SEND);
561
562   smpi_mpi_start(request);
563   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
564   request = nullptr;
565 }
566
567 void smpi_mpi_ssend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
568 {
569   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
570   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
571                           smpi_group_index(smpi_comm_group(comm), dst), tag, comm, NON_PERSISTENT | SSEND | SEND);
572
573   smpi_mpi_start(request);
574   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
575   request = nullptr;
576 }
577
578 void smpi_mpi_sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,int dst, int sendtag,
579                        void *recvbuf, int recvcount, MPI_Datatype recvtype, int src, int recvtag,
580                        MPI_Comm comm, MPI_Status * status)
581 {
582   MPI_Request requests[2];
583   MPI_Status stats[2];
584   int myid=smpi_process_index();
585   if ((smpi_group_index(smpi_comm_group(comm), dst) == myid) && (smpi_group_index(smpi_comm_group(comm), src) == myid)){
586       smpi_datatype_copy(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype);
587       return;
588   }
589   requests[0] = smpi_isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
590   requests[1] = smpi_irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
591   smpi_mpi_startall(2, requests);
592   smpi_mpi_waitall(2, requests, stats);
593   smpi_mpi_request_free(&requests[0]);
594   smpi_mpi_request_free(&requests[1]);
595   if(status != MPI_STATUS_IGNORE) {
596     // Copy receive status
597     *status = stats[1];
598   }
599 }
600
601 int smpi_mpi_get_count(MPI_Status * status, MPI_Datatype datatype)
602 {
603   return status->count / smpi_datatype_size(datatype);
604 }
605
606 static void finish_wait(MPI_Request * request, MPI_Status * status)
607 {
608   MPI_Request req = *request;
609   smpi_empty_status(status);
610
611   if(!((req->detached != 0) && ((req->flags & SEND) != 0)) && ((req->flags & PREPARED) == 0)){
612     if(status != MPI_STATUS_IGNORE) {
613       int src = req->src == MPI_ANY_SOURCE ? req->real_src : req->src;
614       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(req->comm), src);
615       status->MPI_TAG = req->tag == MPI_ANY_TAG ? req->real_tag : req->tag;
616       status->MPI_ERROR = req->truncated != 0 ? MPI_ERR_TRUNCATE : MPI_SUCCESS;
617       // this handles the case were size in receive differs from size in send
618       status->count = req->real_size;
619     }
620
621     print_request("Finishing", req);
622     MPI_Datatype datatype = req->old_type;
623
624     if(((req->flags & ACCUMULATE) != 0) || (datatype->sizeof_substruct != 0)){
625       if (!smpi_process_get_replaying()){
626         if( smpi_privatize_global_variables != 0 && (static_cast<char*>(req->old_buf) >= smpi_start_data_exe)
627             && ((char*)req->old_buf < smpi_start_data_exe + smpi_size_data_exe )){
628             XBT_VERB("Privatization : We are unserializing to a zone in global memory - Switch data segment ");
629             smpi_switch_data_segment(smpi_process_index());
630         }
631       }
632
633       if(datatype->sizeof_substruct != 0){
634         // This part handles the problem of non-contignous memory the unserialization at the reception
635         s_smpi_subtype_t *subtype = static_cast<s_smpi_subtype_t*>(datatype->substruct);
636         if(req->flags & RECV)
637           subtype->unserialize(req->buf, req->old_buf, req->real_size/smpi_datatype_size(datatype) ,
638                                datatype->substruct, req->op);
639         xbt_free(req->buf);
640       }else if(req->flags & RECV){//apply op on contiguous buffer for accumulate
641           int n =req->real_size/smpi_datatype_size(datatype);
642           smpi_op_apply(req->op, req->buf, req->old_buf, &n, &datatype);
643           xbt_free(req->buf);
644       }
645     }
646   }
647
648   if (TRACE_smpi_view_internals() && ((req->flags & RECV) != 0)){
649     int rank = smpi_process_index();
650     int src_traced = (req->src == MPI_ANY_SOURCE ? req->real_src : req->src);
651     TRACE_smpi_recv(rank, src_traced, rank,req->tag);
652   }
653
654   if(req->detached_sender != nullptr){
655     //integrate pseudo-timing for buffering of small messages, do not bother to execute the simcall if 0
656     double sleeptime = smpi_or(req->real_size);
657     if(sleeptime > 0.0){
658       simcall_process_sleep(sleeptime);
659       XBT_DEBUG("receiving size of %zu : sleep %f ", req->real_size, sleeptime);
660     }
661     smpi_mpi_request_free(&(req->detached_sender));
662   }
663   if(req->flags & PERSISTENT)
664     req->action = nullptr;
665   req->flags |= FINISHED;
666
667   smpi_mpi_request_free(request);
668 }
669
670 int smpi_mpi_test(MPI_Request * request, MPI_Status * status) {
671   //assume that request is not MPI_REQUEST_NULL (filtered in PMPI_Test or smpi_mpi_testall before)
672
673   // to avoid deadlocks if used as a break condition, such as
674   //     while (MPI_Test(request, flag, status) && flag) {
675   //     }
676   // because the time will not normally advance when only calls to MPI_Test are made -> deadlock
677   // multiplier to the sleeptime, to increase speed of execution, each failed test will increase it
678   static int nsleeps = 1;
679   if(smpi_test_sleep > 0)  
680     simcall_process_sleep(nsleeps*smpi_test_sleep);
681
682   smpi_empty_status(status);
683   int flag = 1;
684   if (((*request)->flags & PREPARED) == 0) {
685     if ((*request)->action != nullptr)
686       flag = simcall_comm_test((*request)->action);
687     if (flag) {
688       finish_wait(request, status);
689       nsleeps=1;//reset the number of sleeps we will do next time
690       if (*request != MPI_REQUEST_NULL && ((*request)->flags & PERSISTENT)==0)
691       *request = MPI_REQUEST_NULL;
692     } else if (xbt_cfg_get_boolean("smpi/grow-injected-times")){
693       nsleeps++;
694     }
695   }
696   return flag;
697 }
698
699 int smpi_mpi_testany(int count, MPI_Request requests[], int *index, MPI_Status * status)
700 {
701   std::vector<simgrid::kernel::activity::ActivityImpl*> comms;
702   comms.reserve(count);
703
704   int i;
705   int flag = 0;
706
707   *index = MPI_UNDEFINED;
708
709   std::vector<int> map; /** Maps all matching comms back to their location in requests **/
710   for(i = 0; i < count; i++) {
711     if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->action && !(requests[i]->flags & PREPARED)) {
712        comms.push_back(requests[i]->action);
713        map.push_back(i);
714     }
715   }
716   if(!map.empty()) {
717     //multiplier to the sleeptime, to increase speed of execution, each failed testany will increase it
718     static int nsleeps = 1;
719     if(smpi_test_sleep > 0) 
720       simcall_process_sleep(nsleeps*smpi_test_sleep);
721
722     i = simcall_comm_testany(comms.data(), comms.size()); // The i-th element in comms matches!
723     if (i != -1) { // -1 is not MPI_UNDEFINED but a SIMIX return code. (nothing matches)
724       *index = map[i]; 
725       finish_wait(&requests[*index], status);
726       flag             = 1;
727       nsleeps          = 1;
728       if (requests[*index] != MPI_REQUEST_NULL && (requests[*index]->flags & NON_PERSISTENT)) {
729         requests[*index] = MPI_REQUEST_NULL;
730       }
731     } else {
732       nsleeps++;
733     }
734   } else {
735       //all requests are null or inactive, return true
736       flag = 1;
737       smpi_empty_status(status);
738   }
739
740   return flag;
741 }
742
743 int smpi_mpi_testall(int count, MPI_Request requests[], MPI_Status status[])
744 {
745   MPI_Status stat;
746   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
747   int flag=1;
748   for(int i=0; i<count; i++){
749     if (requests[i] != MPI_REQUEST_NULL && !(requests[i]->flags & PREPARED)) {
750       if (smpi_mpi_test(&requests[i], pstat)!=1){
751         flag=0;
752       }else{
753           requests[i]=MPI_REQUEST_NULL;
754       }
755     }else{
756       smpi_empty_status(pstat);
757     }
758     if(status != MPI_STATUSES_IGNORE) {
759       status[i] = *pstat;
760     }
761   }
762   return flag;
763 }
764
765 void smpi_mpi_probe(int source, int tag, MPI_Comm comm, MPI_Status* status){
766   int flag=0;
767   //FIXME find another way to avoid busy waiting ?
768   // the issue here is that we have to wait on a nonexistent comm
769   while(flag==0){
770     smpi_mpi_iprobe(source, tag, comm, &flag, status);
771     XBT_DEBUG("Busy Waiting on probing : %d", flag);
772   }
773 }
774
775 void smpi_mpi_iprobe(int source, int tag, MPI_Comm comm, int* flag, MPI_Status* status){
776   MPI_Request request = build_request(nullptr, 0, MPI_CHAR, source == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
777                  smpi_group_index(smpi_comm_group(comm), source), smpi_comm_rank(comm), tag, comm, PERSISTENT | RECV);
778
779   // to avoid deadlock, we have to sleep some time here, or the timer won't advance and we will only do iprobe simcalls
780   // (especially when used as a break condition, such as while(MPI_Iprobe(...)) ... )
781   // multiplier to the sleeptime, to increase speed of execution, each failed iprobe will increase it
782   static int nsleeps = 1;
783   double speed = simgrid::s4u::Actor::self()->getHost()->speed();
784   double maxrate = xbt_cfg_get_double("smpi/iprobe-cpu-usage");
785   if (smpi_iprobe_sleep > 0) {
786     smx_activity_t iprobe_sleep = simcall_execution_start("iprobe", /* flops to executek*/nsleeps*smpi_iprobe_sleep*speed*maxrate, /* priority */1.0, /* performance bound */maxrate*speed);
787     simcall_execution_wait(iprobe_sleep);
788   }
789   // behave like a receive, but don't do it
790   smx_mailbox_t mailbox;
791
792   print_request("New iprobe", request);
793   // We have to test both mailboxes as we don't know if we will receive one one or another
794   if (xbt_cfg_get_int("smpi/async-small-thresh") > 0){
795       mailbox = smpi_process_mailbox_small();
796       XBT_DEBUG("Trying to probe the perm recv mailbox");
797       request->action = simcall_comm_iprobe(mailbox, 0, request->src, request->tag, &match_recv,
798                                             static_cast<void*>(request));
799   }
800
801   if (request->action == nullptr){
802     mailbox = smpi_process_mailbox();
803     XBT_DEBUG("trying to probe the other mailbox");
804     request->action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv,
805                                           static_cast<void*>(request));
806   }
807
808   if (request->action != nullptr){
809     simgrid::kernel::activity::Comm *sync_comm = static_cast<simgrid::kernel::activity::Comm*>(request->action);
810     MPI_Request req                            = static_cast<MPI_Request>(sync_comm->src_data);
811     *flag = 1;
812     if(status != MPI_STATUS_IGNORE && (req->flags & PREPARED) == 0) {
813       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(comm), req->src);
814       status->MPI_TAG    = req->tag;
815       status->MPI_ERROR  = MPI_SUCCESS;
816       status->count      = req->real_size;
817     }
818     nsleeps = 1;//reset the number of sleeps we will do next time
819   }
820   else {
821     *flag = 0;
822     if (xbt_cfg_get_boolean("smpi/grow-injected-times"))
823       nsleeps++;
824   }
825   smpi_mpi_request_free(&request);
826 }
827
828 void smpi_mpi_wait(MPI_Request * request, MPI_Status * status)
829 {
830   print_request("Waiting", *request);
831   if ((*request)->flags & PREPARED) {
832     smpi_empty_status(status);
833     return;
834   }
835
836   if ((*request)->action != nullptr)
837     // this is not a detached send
838     simcall_comm_wait((*request)->action, -1.0);
839
840   finish_wait(request, status);
841   if (*request != MPI_REQUEST_NULL && (((*request)->flags & NON_PERSISTENT)!=0))
842     *request = MPI_REQUEST_NULL;
843 }
844
845 static int sort_accumulates(MPI_Request a, MPI_Request b)
846 {
847   return (a->tag < b->tag);
848 }
849
850 int smpi_mpi_waitany(int count, MPI_Request requests[], MPI_Status * status)
851 {
852   s_xbt_dynar_t comms; // Keep it on stack to save some extra mallocs
853   int i;
854   int size = 0;
855   int index = MPI_UNDEFINED;
856   int *map;
857
858   if(count > 0) {
859     // Wait for a request to complete
860     xbt_dynar_init(&comms, sizeof(smx_activity_t), nullptr);
861     map = xbt_new(int, count);
862     XBT_DEBUG("Wait for one of %d", count);
863     for(i = 0; i < count; i++) {
864       if (requests[i] != MPI_REQUEST_NULL && !(requests[i]->flags & PREPARED) && !(requests[i]->flags & FINISHED)) {
865         if (requests[i]->action != nullptr) {
866           XBT_DEBUG("Waiting any %p ", requests[i]);
867           xbt_dynar_push(&comms, &requests[i]->action);
868           map[size] = i;
869           size++;
870         } else {
871           // This is a finished detached request, let's return this one
872           size  = 0; // so we free the dynar but don't do the waitany call
873           index = i;
874           finish_wait(&requests[i], status); // cleanup if refcount = 0
875           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
876             requests[i] = MPI_REQUEST_NULL; // set to null
877           break;
878         }
879       }
880     }
881     if(size > 0) {
882       i = simcall_comm_waitany(&comms, -1);
883
884       // not MPI_UNDEFINED, as this is a simix return code
885       if (i != -1) {
886         index = map[i];
887         //in case of an accumulate, we have to wait the end of all requests to apply the operation, ordered correctly.
888         if ((requests[index] == MPI_REQUEST_NULL)
889              ||  (!((requests[index]->flags & ACCUMULATE) && (requests[index]->flags & RECV)))){
890           finish_wait(&requests[index], status);
891           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
892             requests[index] = MPI_REQUEST_NULL;
893         }else{
894             XBT_WARN("huu?");
895         }
896       }
897     }
898
899     xbt_dynar_free_data(&comms);
900     xbt_free(map);
901   }
902
903   if (index==MPI_UNDEFINED)
904     smpi_empty_status(status);
905
906   return index;
907 }
908
909 int smpi_mpi_waitall(int count, MPI_Request requests[], MPI_Status status[])
910 {
911   std::vector<MPI_Request> accumulates;
912   int index;
913   MPI_Status stat;
914   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
915   int retvalue = MPI_SUCCESS;
916   //tag invalid requests in the set
917   if (status != MPI_STATUSES_IGNORE) {
918     for (int c = 0; c < count; c++) {
919       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst == MPI_PROC_NULL || (requests[c]->flags & PREPARED)) {
920         smpi_empty_status(&status[c]);
921       } else if (requests[c]->src == MPI_PROC_NULL) {
922         smpi_empty_status(&status[c]);
923         status[c].MPI_SOURCE = MPI_PROC_NULL;
924       }
925     }
926   }
927   for (int c = 0; c < count; c++) {
928     if (MC_is_active() || MC_record_replay_is_active()) {
929       smpi_mpi_wait(&requests[c], pstat);
930       index = c;
931     } else {
932       index = smpi_mpi_waitany(count, requests, pstat);
933       if (index == MPI_UNDEFINED)
934         break;
935
936       if (requests[index] != MPI_REQUEST_NULL
937            && (requests[index]->flags & RECV)
938            && (requests[index]->flags & ACCUMULATE))
939         accumulates.push_back(requests[index]);
940       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
941         requests[index] = MPI_REQUEST_NULL;
942     }
943     if (status != MPI_STATUSES_IGNORE) {
944       status[index] = *pstat;
945       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
946         retvalue = MPI_ERR_IN_STATUS;
947     }
948   }
949
950   if (!accumulates.empty()) {
951     std::sort(accumulates.begin(), accumulates.end(), sort_accumulates);
952     for (auto req : accumulates) {
953       finish_wait(&req, status);
954     }
955   }
956
957   return retvalue;
958 }
959
960 int smpi_mpi_waitsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
961 {
962   int i;
963   int count = 0;
964   int index;
965   MPI_Status stat;
966   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
967
968   for(i = 0; i < incount; i++)
969   {
970     index=smpi_mpi_waitany(incount, requests, pstat);
971     if(index!=MPI_UNDEFINED){
972       indices[count] = index;
973       count++;
974       if(status != MPI_STATUSES_IGNORE) {
975         status[index] = *pstat;
976       }
977      if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
978      requests[index]=MPI_REQUEST_NULL;
979     }else{
980       return MPI_UNDEFINED;
981     }
982   }
983   return count;
984 }
985
986 int smpi_mpi_testsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
987 {
988   int i;
989   int count = 0;
990   int count_dead = 0;
991   MPI_Status stat;
992   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
993
994   for(i = 0; i < incount; i++) {
995     if((requests[i] != MPI_REQUEST_NULL)) {
996       if(smpi_mpi_test(&requests[i], pstat)) {
997          indices[i] = 1;
998          count++;
999          if(status != MPI_STATUSES_IGNORE) {
1000            status[i] = *pstat;
1001          }
1002          if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->flags & NON_PERSISTENT)
1003          requests[i]=MPI_REQUEST_NULL;
1004       }
1005     }else{
1006       count_dead++;
1007     }
1008   }
1009   if(count_dead==incount)
1010     return MPI_UNDEFINED;
1011   else return count;
1012 }
1013
1014 void smpi_mpi_bcast(void *buf, int count, MPI_Datatype datatype, int root, MPI_Comm comm)
1015 {
1016   smpi_coll_tuned_bcast_binomial_tree(buf, count, datatype, root, comm);
1017 }
1018
1019 void smpi_mpi_barrier(MPI_Comm comm)
1020 {
1021   smpi_coll_tuned_barrier_ompi_basic_linear(comm);
1022 }
1023
1024 void smpi_mpi_gather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1025                      void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm)
1026 {
1027   int system_tag = COLL_TAG_GATHER;
1028   MPI_Aint lb = 0;
1029   MPI_Aint recvext = 0;
1030
1031   int rank = smpi_comm_rank(comm);
1032   int size = smpi_comm_size(comm);
1033   if(rank != root) {
1034     // Send buffer to root
1035     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1036   } else {
1037     smpi_datatype_extent(recvtype, &lb, &recvext);
1038     // Local copy from root
1039     smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char*>(recvbuf) + root * recvcount * recvext,
1040                        recvcount, recvtype);
1041     // Receive buffers from senders
1042     MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1043     int index = 0;
1044     for (int src = 0; src < size; src++) {
1045       if(src != root) {
1046         requests[index] = smpi_irecv_init(static_cast<char*>(recvbuf) + src * recvcount * recvext, recvcount, recvtype,
1047                                           src, system_tag, comm);
1048         index++;
1049       }
1050     }
1051     // Wait for completion of irecv's.
1052     smpi_mpi_startall(size - 1, requests);
1053     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1054     for (int src = 0; src < size-1; src++) {
1055       smpi_mpi_request_free(&requests[src]);
1056     }
1057     xbt_free(requests);
1058   }
1059 }
1060
1061 void smpi_mpi_reduce_scatter(void *sendbuf, void *recvbuf, int *recvcounts, MPI_Datatype datatype, MPI_Op op,
1062                              MPI_Comm comm)
1063 {
1064   int rank = smpi_comm_rank(comm);
1065
1066   /* arbitrarily choose root as rank 0 */
1067   int size = smpi_comm_size(comm);
1068   int count = 0;
1069   int *displs = xbt_new(int, size);
1070   for (int i = 0; i < size; i++) {
1071     displs[i] = count;
1072     count += recvcounts[i];
1073   }
1074   void *tmpbuf = static_cast<void*>(smpi_get_tmp_sendbuffer(count*smpi_datatype_get_extent(datatype)));
1075
1076   mpi_coll_reduce_fun(sendbuf, tmpbuf, count, datatype, op, 0, comm);
1077   smpi_mpi_scatterv(tmpbuf, recvcounts, displs, datatype, recvbuf, recvcounts[rank], datatype, 0, comm);
1078   xbt_free(displs);
1079   smpi_free_tmp_buffer(tmpbuf);
1080 }
1081
1082 void smpi_mpi_gatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int *recvcounts, int *displs,
1083                       MPI_Datatype recvtype, int root, MPI_Comm comm)
1084 {
1085   int system_tag = COLL_TAG_GATHERV;
1086   MPI_Aint lb = 0;
1087   MPI_Aint recvext = 0;
1088
1089   int rank = smpi_comm_rank(comm);
1090   int size = smpi_comm_size(comm);
1091   if (rank != root) {
1092     // Send buffer to root
1093     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1094   } else {
1095     smpi_datatype_extent(recvtype, &lb, &recvext);
1096     // Local copy from root
1097     smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char*>(recvbuf) + displs[root] * recvext,
1098                        recvcounts[root], recvtype);
1099     // Receive buffers from senders
1100     MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1101     int index = 0;
1102     for (int src = 0; src < size; src++) {
1103       if(src != root) {
1104         requests[index] = smpi_irecv_init(static_cast<char*>(recvbuf) + displs[src] * recvext,
1105                           recvcounts[src], recvtype, src, system_tag, comm);
1106         index++;
1107       }
1108     }
1109     // Wait for completion of irecv's.
1110     smpi_mpi_startall(size - 1, requests);
1111     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1112     for (int src = 0; src < size-1; src++) {
1113       smpi_mpi_request_free(&requests[src]);
1114     }
1115     xbt_free(requests);
1116   }
1117 }
1118
1119 void smpi_mpi_allgather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1120                         void *recvbuf,int recvcount, MPI_Datatype recvtype, MPI_Comm comm)
1121 {
1122   int system_tag = COLL_TAG_ALLGATHER;
1123   MPI_Aint lb = 0;
1124   MPI_Aint recvext = 0;
1125   MPI_Request *requests;
1126
1127   int rank = smpi_comm_rank(comm);
1128   int size = smpi_comm_size(comm);
1129   // FIXME: check for errors
1130   smpi_datatype_extent(recvtype, &lb, &recvext);
1131   // Local copy from self
1132   smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char *>(recvbuf) + rank * recvcount * recvext, recvcount,
1133                      recvtype);
1134   // Send/Recv buffers to/from others;
1135   requests = xbt_new(MPI_Request, 2 * (size - 1));
1136   int index = 0;
1137   for (int other = 0; other < size; other++) {
1138     if(other != rank) {
1139       requests[index] = smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,comm);
1140       index++;
1141       requests[index] = smpi_irecv_init(static_cast<char *>(recvbuf) + other * recvcount * recvext, recvcount, recvtype,
1142                                         other, system_tag, comm);
1143       index++;
1144     }
1145   }
1146   // Wait for completion of all comms.
1147   smpi_mpi_startall(2 * (size - 1), requests);
1148   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1149   for (int other = 0; other < 2*(size-1); other++) {
1150     smpi_mpi_request_free(&requests[other]);
1151   }
1152   xbt_free(requests);
1153 }
1154
1155 void smpi_mpi_allgatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf,
1156                          int *recvcounts, int *displs, MPI_Datatype recvtype, MPI_Comm comm)
1157 {
1158   int system_tag = COLL_TAG_ALLGATHERV;
1159   MPI_Aint lb = 0;
1160   MPI_Aint recvext = 0;
1161
1162   int rank = smpi_comm_rank(comm);
1163   int size = smpi_comm_size(comm);
1164   smpi_datatype_extent(recvtype, &lb, &recvext);
1165   // Local copy from self
1166   smpi_datatype_copy(sendbuf, sendcount, sendtype,
1167                      static_cast<char *>(recvbuf) + displs[rank] * recvext,recvcounts[rank], recvtype);
1168   // Send buffers to others;
1169   MPI_Request *requests = xbt_new(MPI_Request, 2 * (size - 1));
1170   int index = 0;
1171   for (int other = 0; other < size; other++) {
1172     if(other != rank) {
1173       requests[index] =
1174         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag, comm);
1175       index++;
1176       requests[index] = smpi_irecv_init(static_cast<char *>(recvbuf) + displs[other] * recvext, recvcounts[other],
1177                           recvtype, other, system_tag, comm);
1178       index++;
1179     }
1180   }
1181   // Wait for completion of all comms.
1182   smpi_mpi_startall(2 * (size - 1), requests);
1183   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1184   for (int other = 0; other < 2*(size-1); other++) {
1185     smpi_mpi_request_free(&requests[other]);
1186   }
1187   xbt_free(requests);
1188 }
1189
1190 void smpi_mpi_scatter(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1191                       void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm)
1192 {
1193   int system_tag = COLL_TAG_SCATTER;
1194   MPI_Aint lb = 0;
1195   MPI_Aint sendext = 0;
1196   MPI_Request *requests;
1197
1198   int rank = smpi_comm_rank(comm);
1199   int size = smpi_comm_size(comm);
1200   if(rank != root) {
1201     // Recv buffer from root
1202     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm, MPI_STATUS_IGNORE);
1203   } else {
1204     smpi_datatype_extent(sendtype, &lb, &sendext);
1205     // Local copy from root
1206     if(recvbuf!=MPI_IN_PLACE){
1207         smpi_datatype_copy(static_cast<char *>(sendbuf) + root * sendcount * sendext,
1208                            sendcount, sendtype, recvbuf, recvcount, recvtype);
1209     }
1210     // Send buffers to receivers
1211     requests = xbt_new(MPI_Request, size - 1);
1212     int index = 0;
1213     for(int dst = 0; dst < size; dst++) {
1214       if(dst != root) {
1215         requests[index] = smpi_isend_init(static_cast<char *>(sendbuf) + dst * sendcount * sendext, sendcount, sendtype,
1216                                           dst, system_tag, comm);
1217         index++;
1218       }
1219     }
1220     // Wait for completion of isend's.
1221     smpi_mpi_startall(size - 1, requests);
1222     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1223     for (int dst = 0; dst < size-1; dst++) {
1224       smpi_mpi_request_free(&requests[dst]);
1225     }
1226     xbt_free(requests);
1227   }
1228 }
1229
1230 void smpi_mpi_scatterv(void *sendbuf, int *sendcounts, int *displs, MPI_Datatype sendtype, void *recvbuf, int recvcount,
1231                        MPI_Datatype recvtype, int root, MPI_Comm comm)
1232 {
1233   int system_tag = COLL_TAG_SCATTERV;
1234   MPI_Aint lb = 0;
1235   MPI_Aint sendext = 0;
1236
1237   int rank = smpi_comm_rank(comm);
1238   int size = smpi_comm_size(comm);
1239   if(rank != root) {
1240     // Recv buffer from root
1241     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm, MPI_STATUS_IGNORE);
1242   } else {
1243     smpi_datatype_extent(sendtype, &lb, &sendext);
1244     // Local copy from root
1245     if(recvbuf!=MPI_IN_PLACE){
1246       smpi_datatype_copy(static_cast<char *>(sendbuf) + displs[root] * sendext, sendcounts[root],
1247                        sendtype, recvbuf, recvcount, recvtype);
1248     }
1249     // Send buffers to receivers
1250     MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1251     int index = 0;
1252     for (int dst = 0; dst < size; dst++) {
1253       if (dst != root) {
1254         requests[index] = smpi_isend_init(static_cast<char *>(sendbuf) + displs[dst] * sendext, sendcounts[dst],
1255                             sendtype, dst, system_tag, comm);
1256         index++;
1257       }
1258     }
1259     // Wait for completion of isend's.
1260     smpi_mpi_startall(size - 1, requests);
1261     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1262     for (int dst = 0; dst < size-1; dst++) {
1263       smpi_mpi_request_free(&requests[dst]);
1264     }
1265     xbt_free(requests);
1266   }
1267 }
1268
1269 void smpi_mpi_reduce(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root,
1270                      MPI_Comm comm)
1271 {
1272   int system_tag = COLL_TAG_REDUCE;
1273   MPI_Aint lb = 0;
1274   MPI_Aint dataext = 0;
1275
1276   char* sendtmpbuf = static_cast<char *>(sendbuf);
1277
1278   int rank = smpi_comm_rank(comm);
1279   int size = smpi_comm_size(comm);
1280   //non commutative case, use a working algo from openmpi
1281   if(!smpi_op_is_commute(op)){
1282     smpi_coll_tuned_reduce_ompi_basic_linear(sendtmpbuf, recvbuf, count, datatype, op, root, comm);
1283     return;
1284   }
1285
1286   if( sendbuf == MPI_IN_PLACE ) {
1287     sendtmpbuf = static_cast<char *>(smpi_get_tmp_sendbuffer(count*smpi_datatype_get_extent(datatype)));
1288     smpi_datatype_copy(recvbuf, count, datatype,sendtmpbuf, count, datatype);
1289   }
1290   
1291   if(rank != root) {
1292     // Send buffer to root
1293     smpi_mpi_send(sendtmpbuf, count, datatype, root, system_tag, comm);
1294   } else {
1295     smpi_datatype_extent(datatype, &lb, &dataext);
1296     // Local copy from root
1297     if (sendtmpbuf != nullptr && recvbuf != nullptr)
1298       smpi_datatype_copy(sendtmpbuf, count, datatype, recvbuf, count, datatype);
1299     // Receive buffers from senders
1300     MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1301     void **tmpbufs = xbt_new(void *, size - 1);
1302     int index = 0;
1303     for (int src = 0; src < size; src++) {
1304       if (src != root) {
1305          if (!smpi_process_get_replaying())
1306           tmpbufs[index] = xbt_malloc(count * dataext);
1307          else
1308            tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1309         requests[index] =
1310           smpi_irecv_init(tmpbufs[index], count, datatype, src, system_tag, comm);
1311         index++;
1312       }
1313     }
1314     // Wait for completion of irecv's.
1315     smpi_mpi_startall(size - 1, requests);
1316     for (int src = 0; src < size - 1; src++) {
1317       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1318       XBT_DEBUG("finished waiting any request with index %d", index);
1319       if(index == MPI_UNDEFINED) {
1320         break;
1321       }else{
1322         smpi_mpi_request_free(&requests[index]);
1323       }
1324       if(op) /* op can be MPI_OP_NULL that does nothing */
1325         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1326     }
1327       for(index = 0; index < size - 1; index++) {
1328         smpi_free_tmp_buffer(tmpbufs[index]);
1329       }
1330     xbt_free(tmpbufs);
1331     xbt_free(requests);
1332
1333   }
1334   if( sendbuf == MPI_IN_PLACE ) {
1335     smpi_free_tmp_buffer(sendtmpbuf);
1336   }
1337 }
1338
1339 void smpi_mpi_allreduce(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1340 {
1341   smpi_mpi_reduce(sendbuf, recvbuf, count, datatype, op, 0, comm);
1342   smpi_mpi_bcast(recvbuf, count, datatype, 0, comm);
1343 }
1344
1345 void smpi_mpi_scan(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1346 {
1347   int system_tag = -888;
1348   MPI_Aint lb      = 0;
1349   MPI_Aint dataext = 0;
1350
1351   int rank = smpi_comm_rank(comm);
1352   int size = smpi_comm_size(comm);
1353
1354   smpi_datatype_extent(datatype, &lb, &dataext);
1355
1356   // Local copy from self
1357   smpi_datatype_copy(sendbuf, count, datatype, recvbuf, count, datatype);
1358
1359   // Send/Recv buffers to/from others;
1360   MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1361   void **tmpbufs = xbt_new(void *, rank);
1362   int index = 0;
1363   for (int other = 0; other < rank; other++) {
1364     tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1365     requests[index] = smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag, comm);
1366     index++;
1367   }
1368   for (int other = rank + 1; other < size; other++) {
1369     requests[index] = smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1370     index++;
1371   }
1372   // Wait for completion of all comms.
1373   smpi_mpi_startall(size - 1, requests);
1374
1375   if(smpi_op_is_commute(op)){
1376     for (int other = 0; other < size - 1; other++) {
1377       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1378       if(index == MPI_UNDEFINED) {
1379         break;
1380       }
1381       if(index < rank) {
1382         // #Request is below rank: it's a irecv
1383         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1384       }
1385     }
1386   }else{
1387     //non commutative case, wait in order
1388     for (int other = 0; other < size - 1; other++) {
1389       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1390       if(index < rank) {
1391         smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1392       }
1393     }
1394   }
1395   for(index = 0; index < rank; index++) {
1396     smpi_free_tmp_buffer(tmpbufs[index]);
1397   }
1398   for(index = 0; index < size-1; index++) {
1399     smpi_mpi_request_free(&requests[index]);
1400   }
1401   xbt_free(tmpbufs);
1402   xbt_free(requests);
1403 }
1404
1405 void smpi_mpi_exscan(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1406 {
1407   int system_tag = -888;
1408   MPI_Aint lb         = 0;
1409   MPI_Aint dataext    = 0;
1410   int recvbuf_is_empty=1;
1411   int rank = smpi_comm_rank(comm);
1412   int size = smpi_comm_size(comm);
1413
1414   smpi_datatype_extent(datatype, &lb, &dataext);
1415
1416   // Send/Recv buffers to/from others;
1417   MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1418   void **tmpbufs = xbt_new(void *, rank);
1419   int index = 0;
1420   for (int other = 0; other < rank; other++) {
1421     tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1422     requests[index] = smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag, comm);
1423     index++;
1424   }
1425   for (int other = rank + 1; other < size; other++) {
1426     requests[index] = smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1427     index++;
1428   }
1429   // Wait for completion of all comms.
1430   smpi_mpi_startall(size - 1, requests);
1431
1432   if(smpi_op_is_commute(op)){
1433     for (int other = 0; other < size - 1; other++) {
1434       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1435       if(index == MPI_UNDEFINED) {
1436         break;
1437       }
1438       if(index < rank) {
1439         if(recvbuf_is_empty){
1440           smpi_datatype_copy(tmpbufs[index], count, datatype, recvbuf, count, datatype);
1441           recvbuf_is_empty=0;
1442         } else
1443           // #Request is below rank: it's a irecv
1444           smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1445       }
1446     }
1447   }else{
1448     //non commutative case, wait in order
1449     for (int other = 0; other < size - 1; other++) {
1450       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1451       if(index < rank) {
1452         if (recvbuf_is_empty) {
1453           smpi_datatype_copy(tmpbufs[other], count, datatype, recvbuf, count, datatype);
1454           recvbuf_is_empty = 0;
1455         } else
1456           smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1457       }
1458     }
1459   }
1460   for(index = 0; index < rank; index++) {
1461     smpi_free_tmp_buffer(tmpbufs[index]);
1462   }
1463   for(index = 0; index < size-1; index++) {
1464     smpi_mpi_request_free(&requests[index]);
1465   }
1466   xbt_free(tmpbufs);
1467   xbt_free(requests);
1468 }