Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of git+ssh://scm.gforge.inria.fr//gitroot/simgrid/simgrid
[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   if(smpi_iprobe_sleep > 0)  
784     simcall_process_sleep(nsleeps*smpi_iprobe_sleep);
785   // behave like a receive, but don't do it
786   smx_mailbox_t mailbox;
787
788   print_request("New iprobe", request);
789   // We have to test both mailboxes as we don't know if we will receive one one or another
790   if (xbt_cfg_get_int("smpi/async-small-thresh") > 0){
791       mailbox = smpi_process_mailbox_small();
792       XBT_DEBUG("Trying to probe the perm recv mailbox");
793       request->action = simcall_comm_iprobe(mailbox, 0, request->src, request->tag, &match_recv,
794                                             static_cast<void*>(request));
795   }
796
797   if (request->action == nullptr){
798     mailbox = smpi_process_mailbox();
799     XBT_DEBUG("trying to probe the other mailbox");
800     request->action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv,
801                                           static_cast<void*>(request));
802   }
803
804   if (request->action != nullptr){
805     simgrid::kernel::activity::Comm *sync_comm = static_cast<simgrid::kernel::activity::Comm*>(request->action);
806     MPI_Request req                            = static_cast<MPI_Request>(sync_comm->src_data);
807     *flag = 1;
808     if(status != MPI_STATUS_IGNORE && (req->flags & PREPARED) == 0) {
809       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(comm), req->src);
810       status->MPI_TAG    = req->tag;
811       status->MPI_ERROR  = MPI_SUCCESS;
812       status->count      = req->real_size;
813     }
814     nsleeps = 1;//reset the number of sleeps we will do next time
815   }
816   else {
817     *flag = 0;
818     if (xbt_cfg_get_boolean("smpi/grow-injected-times"))
819       nsleeps++;
820   }
821   smpi_mpi_request_free(&request);
822 }
823
824 void smpi_mpi_wait(MPI_Request * request, MPI_Status * status)
825 {
826   print_request("Waiting", *request);
827   if ((*request)->flags & PREPARED) {
828     smpi_empty_status(status);
829     return;
830   }
831
832   if ((*request)->action != nullptr)
833     // this is not a detached send
834     simcall_comm_wait((*request)->action, -1.0);
835
836   finish_wait(request, status);
837   if (*request != MPI_REQUEST_NULL && (((*request)->flags & NON_PERSISTENT)!=0))
838     *request = MPI_REQUEST_NULL;
839 }
840
841 static int sort_accumulates(MPI_Request a, MPI_Request b)
842 {
843   return (a->tag < b->tag);
844 }
845
846 int smpi_mpi_waitany(int count, MPI_Request requests[], MPI_Status * status)
847 {
848   s_xbt_dynar_t comms; // Keep it on stack to save some extra mallocs
849   int i;
850   int size = 0;
851   int index = MPI_UNDEFINED;
852   int *map;
853
854   if(count > 0) {
855     // Wait for a request to complete
856     xbt_dynar_init(&comms, sizeof(smx_activity_t), nullptr);
857     map = xbt_new(int, count);
858     XBT_DEBUG("Wait for one of %d", count);
859     for(i = 0; i < count; i++) {
860       if (requests[i] != MPI_REQUEST_NULL && !(requests[i]->flags & PREPARED) && !(requests[i]->flags & FINISHED)) {
861         if (requests[i]->action != nullptr) {
862           XBT_DEBUG("Waiting any %p ", requests[i]);
863           xbt_dynar_push(&comms, &requests[i]->action);
864           map[size] = i;
865           size++;
866         } else {
867           // This is a finished detached request, let's return this one
868           size  = 0; // so we free the dynar but don't do the waitany call
869           index = i;
870           finish_wait(&requests[i], status); // cleanup if refcount = 0
871           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
872             requests[i] = MPI_REQUEST_NULL; // set to null
873           break;
874         }
875       }
876     }
877     if(size > 0) {
878       i = simcall_comm_waitany(&comms, -1);
879
880       // not MPI_UNDEFINED, as this is a simix return code
881       if (i != -1) {
882         index = map[i];
883         //in case of an accumulate, we have to wait the end of all requests to apply the operation, ordered correctly.
884         if ((requests[index] == MPI_REQUEST_NULL)
885              ||  (!((requests[index]->flags & ACCUMULATE) && (requests[index]->flags & RECV)))){
886           finish_wait(&requests[index], status);
887           if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
888             requests[index] = MPI_REQUEST_NULL;
889         }else{
890             XBT_WARN("huu?");
891         }
892       }
893     }
894
895     xbt_dynar_free_data(&comms);
896     xbt_free(map);
897   }
898
899   if (index==MPI_UNDEFINED)
900     smpi_empty_status(status);
901
902   return index;
903 }
904
905 int smpi_mpi_waitall(int count, MPI_Request requests[], MPI_Status status[])
906 {
907   std::vector<MPI_Request> accumulates;
908   int index;
909   MPI_Status stat;
910   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
911   int retvalue = MPI_SUCCESS;
912   //tag invalid requests in the set
913   if (status != MPI_STATUSES_IGNORE) {
914     for (int c = 0; c < count; c++) {
915       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst == MPI_PROC_NULL || (requests[c]->flags & PREPARED)) {
916         smpi_empty_status(&status[c]);
917       } else if (requests[c]->src == MPI_PROC_NULL) {
918         smpi_empty_status(&status[c]);
919         status[c].MPI_SOURCE = MPI_PROC_NULL;
920       }
921     }
922   }
923   for (int c = 0; c < count; c++) {
924     if (MC_is_active() || MC_record_replay_is_active()) {
925       smpi_mpi_wait(&requests[c], pstat);
926       index = c;
927     } else {
928       index = smpi_mpi_waitany(count, requests, pstat);
929       if (index == MPI_UNDEFINED)
930         break;
931
932       if (requests[index] != MPI_REQUEST_NULL
933            && (requests[index]->flags & RECV)
934            && (requests[index]->flags & ACCUMULATE))
935         accumulates.push_back(requests[index]);
936       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
937         requests[index] = MPI_REQUEST_NULL;
938     }
939     if (status != MPI_STATUSES_IGNORE) {
940       status[index] = *pstat;
941       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
942         retvalue = MPI_ERR_IN_STATUS;
943     }
944   }
945
946   if (!accumulates.empty()) {
947     std::sort(accumulates.begin(), accumulates.end(), sort_accumulates);
948     for (auto req : accumulates) {
949       finish_wait(&req, status);
950     }
951   }
952
953   return retvalue;
954 }
955
956 int smpi_mpi_waitsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
957 {
958   int i;
959   int count = 0;
960   int index;
961   MPI_Status stat;
962   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
963
964   for(i = 0; i < incount; i++)
965   {
966     index=smpi_mpi_waitany(incount, requests, pstat);
967     if(index!=MPI_UNDEFINED){
968       indices[count] = index;
969       count++;
970       if(status != MPI_STATUSES_IGNORE) {
971         status[index] = *pstat;
972       }
973      if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
974      requests[index]=MPI_REQUEST_NULL;
975     }else{
976       return MPI_UNDEFINED;
977     }
978   }
979   return count;
980 }
981
982 int smpi_mpi_testsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
983 {
984   int i;
985   int count = 0;
986   int count_dead = 0;
987   MPI_Status stat;
988   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
989
990   for(i = 0; i < incount; i++) {
991     if((requests[i] != MPI_REQUEST_NULL)) {
992       if(smpi_mpi_test(&requests[i], pstat)) {
993          indices[i] = 1;
994          count++;
995          if(status != MPI_STATUSES_IGNORE) {
996            status[i] = *pstat;
997          }
998          if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->flags & NON_PERSISTENT)
999          requests[i]=MPI_REQUEST_NULL;
1000       }
1001     }else{
1002       count_dead++;
1003     }
1004   }
1005   if(count_dead==incount)
1006     return MPI_UNDEFINED;
1007   else return count;
1008 }
1009
1010 void smpi_mpi_bcast(void *buf, int count, MPI_Datatype datatype, int root, MPI_Comm comm)
1011 {
1012   smpi_coll_tuned_bcast_binomial_tree(buf, count, datatype, root, comm);
1013 }
1014
1015 void smpi_mpi_barrier(MPI_Comm comm)
1016 {
1017   smpi_coll_tuned_barrier_ompi_basic_linear(comm);
1018 }
1019
1020 void smpi_mpi_gather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1021                      void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm)
1022 {
1023   int system_tag = COLL_TAG_GATHER;
1024   MPI_Aint lb = 0;
1025   MPI_Aint recvext = 0;
1026
1027   int rank = smpi_comm_rank(comm);
1028   int size = smpi_comm_size(comm);
1029   if(rank != root) {
1030     // Send buffer to root
1031     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1032   } else {
1033     smpi_datatype_extent(recvtype, &lb, &recvext);
1034     // Local copy from root
1035     smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char*>(recvbuf) + root * recvcount * recvext,
1036                        recvcount, recvtype);
1037     // Receive buffers from senders
1038     MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1039     int index = 0;
1040     for (int src = 0; src < size; src++) {
1041       if(src != root) {
1042         requests[index] = smpi_irecv_init(static_cast<char*>(recvbuf) + src * recvcount * recvext, recvcount, recvtype,
1043                                           src, system_tag, comm);
1044         index++;
1045       }
1046     }
1047     // Wait for completion of irecv's.
1048     smpi_mpi_startall(size - 1, requests);
1049     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1050     for (int src = 0; src < size-1; src++) {
1051       smpi_mpi_request_free(&requests[src]);
1052     }
1053     xbt_free(requests);
1054   }
1055 }
1056
1057 void smpi_mpi_reduce_scatter(void *sendbuf, void *recvbuf, int *recvcounts, MPI_Datatype datatype, MPI_Op op,
1058                              MPI_Comm comm)
1059 {
1060   int rank = smpi_comm_rank(comm);
1061
1062   /* arbitrarily choose root as rank 0 */
1063   int size = smpi_comm_size(comm);
1064   int count = 0;
1065   int *displs = xbt_new(int, size);
1066   for (int i = 0; i < size; i++) {
1067     displs[i] = count;
1068     count += recvcounts[i];
1069   }
1070   void *tmpbuf = static_cast<void*>(smpi_get_tmp_sendbuffer(count*smpi_datatype_get_extent(datatype)));
1071
1072   mpi_coll_reduce_fun(sendbuf, tmpbuf, count, datatype, op, 0, comm);
1073   smpi_mpi_scatterv(tmpbuf, recvcounts, displs, datatype, recvbuf, recvcounts[rank], datatype, 0, comm);
1074   xbt_free(displs);
1075   smpi_free_tmp_buffer(tmpbuf);
1076 }
1077
1078 void smpi_mpi_gatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int *recvcounts, int *displs,
1079                       MPI_Datatype recvtype, int root, MPI_Comm comm)
1080 {
1081   int system_tag = COLL_TAG_GATHERV;
1082   MPI_Aint lb = 0;
1083   MPI_Aint recvext = 0;
1084
1085   int rank = smpi_comm_rank(comm);
1086   int size = smpi_comm_size(comm);
1087   if (rank != root) {
1088     // Send buffer to root
1089     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1090   } else {
1091     smpi_datatype_extent(recvtype, &lb, &recvext);
1092     // Local copy from root
1093     smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char*>(recvbuf) + displs[root] * recvext,
1094                        recvcounts[root], recvtype);
1095     // Receive buffers from senders
1096     MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1097     int index = 0;
1098     for (int src = 0; src < size; src++) {
1099       if(src != root) {
1100         requests[index] = smpi_irecv_init(static_cast<char*>(recvbuf) + displs[src] * recvext,
1101                           recvcounts[src], recvtype, src, system_tag, comm);
1102         index++;
1103       }
1104     }
1105     // Wait for completion of irecv's.
1106     smpi_mpi_startall(size - 1, requests);
1107     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1108     for (int src = 0; src < size-1; src++) {
1109       smpi_mpi_request_free(&requests[src]);
1110     }
1111     xbt_free(requests);
1112   }
1113 }
1114
1115 void smpi_mpi_allgather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1116                         void *recvbuf,int recvcount, MPI_Datatype recvtype, MPI_Comm comm)
1117 {
1118   int system_tag = COLL_TAG_ALLGATHER;
1119   MPI_Aint lb = 0;
1120   MPI_Aint recvext = 0;
1121   MPI_Request *requests;
1122
1123   int rank = smpi_comm_rank(comm);
1124   int size = smpi_comm_size(comm);
1125   // FIXME: check for errors
1126   smpi_datatype_extent(recvtype, &lb, &recvext);
1127   // Local copy from self
1128   smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char *>(recvbuf) + rank * recvcount * recvext, recvcount,
1129                      recvtype);
1130   // Send/Recv buffers to/from others;
1131   requests = xbt_new(MPI_Request, 2 * (size - 1));
1132   int index = 0;
1133   for (int other = 0; other < size; other++) {
1134     if(other != rank) {
1135       requests[index] = smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,comm);
1136       index++;
1137       requests[index] = smpi_irecv_init(static_cast<char *>(recvbuf) + other * recvcount * recvext, recvcount, recvtype,
1138                                         other, system_tag, comm);
1139       index++;
1140     }
1141   }
1142   // Wait for completion of all comms.
1143   smpi_mpi_startall(2 * (size - 1), requests);
1144   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1145   for (int other = 0; other < 2*(size-1); other++) {
1146     smpi_mpi_request_free(&requests[other]);
1147   }
1148   xbt_free(requests);
1149 }
1150
1151 void smpi_mpi_allgatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf,
1152                          int *recvcounts, int *displs, MPI_Datatype recvtype, MPI_Comm comm)
1153 {
1154   int system_tag = COLL_TAG_ALLGATHERV;
1155   MPI_Aint lb = 0;
1156   MPI_Aint recvext = 0;
1157
1158   int rank = smpi_comm_rank(comm);
1159   int size = smpi_comm_size(comm);
1160   smpi_datatype_extent(recvtype, &lb, &recvext);
1161   // Local copy from self
1162   smpi_datatype_copy(sendbuf, sendcount, sendtype,
1163                      static_cast<char *>(recvbuf) + displs[rank] * recvext,recvcounts[rank], recvtype);
1164   // Send buffers to others;
1165   MPI_Request *requests = xbt_new(MPI_Request, 2 * (size - 1));
1166   int index = 0;
1167   for (int other = 0; other < size; other++) {
1168     if(other != rank) {
1169       requests[index] =
1170         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag, comm);
1171       index++;
1172       requests[index] = smpi_irecv_init(static_cast<char *>(recvbuf) + displs[other] * recvext, recvcounts[other],
1173                           recvtype, other, system_tag, comm);
1174       index++;
1175     }
1176   }
1177   // Wait for completion of all comms.
1178   smpi_mpi_startall(2 * (size - 1), requests);
1179   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1180   for (int other = 0; other < 2*(size-1); other++) {
1181     smpi_mpi_request_free(&requests[other]);
1182   }
1183   xbt_free(requests);
1184 }
1185
1186 void smpi_mpi_scatter(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1187                       void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm)
1188 {
1189   int system_tag = COLL_TAG_SCATTER;
1190   MPI_Aint lb = 0;
1191   MPI_Aint sendext = 0;
1192   MPI_Request *requests;
1193
1194   int rank = smpi_comm_rank(comm);
1195   int size = smpi_comm_size(comm);
1196   if(rank != root) {
1197     // Recv buffer from root
1198     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm, MPI_STATUS_IGNORE);
1199   } else {
1200     smpi_datatype_extent(sendtype, &lb, &sendext);
1201     // Local copy from root
1202     if(recvbuf!=MPI_IN_PLACE){
1203         smpi_datatype_copy(static_cast<char *>(sendbuf) + root * sendcount * sendext,
1204                            sendcount, sendtype, recvbuf, recvcount, recvtype);
1205     }
1206     // Send buffers to receivers
1207     requests = xbt_new(MPI_Request, size - 1);
1208     int index = 0;
1209     for(int dst = 0; dst < size; dst++) {
1210       if(dst != root) {
1211         requests[index] = smpi_isend_init(static_cast<char *>(sendbuf) + dst * sendcount * sendext, sendcount, sendtype,
1212                                           dst, system_tag, comm);
1213         index++;
1214       }
1215     }
1216     // Wait for completion of isend's.
1217     smpi_mpi_startall(size - 1, requests);
1218     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1219     for (int dst = 0; dst < size-1; dst++) {
1220       smpi_mpi_request_free(&requests[dst]);
1221     }
1222     xbt_free(requests);
1223   }
1224 }
1225
1226 void smpi_mpi_scatterv(void *sendbuf, int *sendcounts, int *displs, MPI_Datatype sendtype, void *recvbuf, int recvcount,
1227                        MPI_Datatype recvtype, int root, MPI_Comm comm)
1228 {
1229   int system_tag = COLL_TAG_SCATTERV;
1230   MPI_Aint lb = 0;
1231   MPI_Aint sendext = 0;
1232
1233   int rank = smpi_comm_rank(comm);
1234   int size = smpi_comm_size(comm);
1235   if(rank != root) {
1236     // Recv buffer from root
1237     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm, MPI_STATUS_IGNORE);
1238   } else {
1239     smpi_datatype_extent(sendtype, &lb, &sendext);
1240     // Local copy from root
1241     if(recvbuf!=MPI_IN_PLACE){
1242       smpi_datatype_copy(static_cast<char *>(sendbuf) + displs[root] * sendext, sendcounts[root],
1243                        sendtype, recvbuf, recvcount, recvtype);
1244     }
1245     // Send buffers to receivers
1246     MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1247     int index = 0;
1248     for (int dst = 0; dst < size; dst++) {
1249       if (dst != root) {
1250         requests[index] = smpi_isend_init(static_cast<char *>(sendbuf) + displs[dst] * sendext, sendcounts[dst],
1251                             sendtype, dst, system_tag, comm);
1252         index++;
1253       }
1254     }
1255     // Wait for completion of isend's.
1256     smpi_mpi_startall(size - 1, requests);
1257     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1258     for (int dst = 0; dst < size-1; dst++) {
1259       smpi_mpi_request_free(&requests[dst]);
1260     }
1261     xbt_free(requests);
1262   }
1263 }
1264
1265 void smpi_mpi_reduce(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root,
1266                      MPI_Comm comm)
1267 {
1268   int system_tag = COLL_TAG_REDUCE;
1269   MPI_Aint lb = 0;
1270   MPI_Aint dataext = 0;
1271
1272   char* sendtmpbuf = static_cast<char *>(sendbuf);
1273
1274   int rank = smpi_comm_rank(comm);
1275   int size = smpi_comm_size(comm);
1276   //non commutative case, use a working algo from openmpi
1277   if(!smpi_op_is_commute(op)){
1278     smpi_coll_tuned_reduce_ompi_basic_linear(sendtmpbuf, recvbuf, count, datatype, op, root, comm);
1279     return;
1280   }
1281
1282   if( sendbuf == MPI_IN_PLACE ) {
1283     sendtmpbuf = static_cast<char *>(smpi_get_tmp_sendbuffer(count*smpi_datatype_get_extent(datatype)));
1284     smpi_datatype_copy(recvbuf, count, datatype,sendtmpbuf, count, datatype);
1285   }
1286   
1287   if(rank != root) {
1288     // Send buffer to root
1289     smpi_mpi_send(sendtmpbuf, count, datatype, root, system_tag, comm);
1290   } else {
1291     smpi_datatype_extent(datatype, &lb, &dataext);
1292     // Local copy from root
1293     if (sendtmpbuf != nullptr && recvbuf != nullptr)
1294       smpi_datatype_copy(sendtmpbuf, count, datatype, recvbuf, count, datatype);
1295     // Receive buffers from senders
1296     MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1297     void **tmpbufs = xbt_new(void *, size - 1);
1298     int index = 0;
1299     for (int src = 0; src < size; src++) {
1300       if (src != root) {
1301          if (!smpi_process_get_replaying())
1302           tmpbufs[index] = xbt_malloc(count * dataext);
1303          else
1304            tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1305         requests[index] =
1306           smpi_irecv_init(tmpbufs[index], count, datatype, src, system_tag, comm);
1307         index++;
1308       }
1309     }
1310     // Wait for completion of irecv's.
1311     smpi_mpi_startall(size - 1, requests);
1312     for (int src = 0; src < size - 1; src++) {
1313       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1314       XBT_DEBUG("finished waiting any request with index %d", index);
1315       if(index == MPI_UNDEFINED) {
1316         break;
1317       }else{
1318         smpi_mpi_request_free(&requests[index]);
1319       }
1320       if(op) /* op can be MPI_OP_NULL that does nothing */
1321         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1322     }
1323       for(index = 0; index < size - 1; index++) {
1324         smpi_free_tmp_buffer(tmpbufs[index]);
1325       }
1326     xbt_free(tmpbufs);
1327     xbt_free(requests);
1328
1329   }
1330   if( sendbuf == MPI_IN_PLACE ) {
1331     smpi_free_tmp_buffer(sendtmpbuf);
1332   }
1333 }
1334
1335 void smpi_mpi_allreduce(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1336 {
1337   smpi_mpi_reduce(sendbuf, recvbuf, count, datatype, op, 0, comm);
1338   smpi_mpi_bcast(recvbuf, count, datatype, 0, comm);
1339 }
1340
1341 void smpi_mpi_scan(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1342 {
1343   int system_tag = -888;
1344   MPI_Aint lb      = 0;
1345   MPI_Aint dataext = 0;
1346
1347   int rank = smpi_comm_rank(comm);
1348   int size = smpi_comm_size(comm);
1349
1350   smpi_datatype_extent(datatype, &lb, &dataext);
1351
1352   // Local copy from self
1353   smpi_datatype_copy(sendbuf, count, datatype, recvbuf, count, datatype);
1354
1355   // Send/Recv buffers to/from others;
1356   MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1357   void **tmpbufs = xbt_new(void *, rank);
1358   int index = 0;
1359   for (int other = 0; other < rank; other++) {
1360     tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1361     requests[index] = smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag, comm);
1362     index++;
1363   }
1364   for (int other = rank + 1; other < size; other++) {
1365     requests[index] = smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1366     index++;
1367   }
1368   // Wait for completion of all comms.
1369   smpi_mpi_startall(size - 1, requests);
1370
1371   if(smpi_op_is_commute(op)){
1372     for (int other = 0; other < size - 1; other++) {
1373       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1374       if(index == MPI_UNDEFINED) {
1375         break;
1376       }
1377       if(index < rank) {
1378         // #Request is below rank: it's a irecv
1379         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1380       }
1381     }
1382   }else{
1383     //non commutative case, wait in order
1384     for (int other = 0; other < size - 1; other++) {
1385       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1386       if(index < rank) {
1387         smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1388       }
1389     }
1390   }
1391   for(index = 0; index < rank; index++) {
1392     smpi_free_tmp_buffer(tmpbufs[index]);
1393   }
1394   for(index = 0; index < size-1; index++) {
1395     smpi_mpi_request_free(&requests[index]);
1396   }
1397   xbt_free(tmpbufs);
1398   xbt_free(requests);
1399 }
1400
1401 void smpi_mpi_exscan(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1402 {
1403   int system_tag = -888;
1404   MPI_Aint lb         = 0;
1405   MPI_Aint dataext    = 0;
1406   int recvbuf_is_empty=1;
1407   int rank = smpi_comm_rank(comm);
1408   int size = smpi_comm_size(comm);
1409
1410   smpi_datatype_extent(datatype, &lb, &dataext);
1411
1412   // Send/Recv buffers to/from others;
1413   MPI_Request *requests = xbt_new(MPI_Request, size - 1);
1414   void **tmpbufs = xbt_new(void *, rank);
1415   int index = 0;
1416   for (int other = 0; other < rank; other++) {
1417     tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1418     requests[index] = smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag, comm);
1419     index++;
1420   }
1421   for (int other = rank + 1; other < size; other++) {
1422     requests[index] = smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1423     index++;
1424   }
1425   // Wait for completion of all comms.
1426   smpi_mpi_startall(size - 1, requests);
1427
1428   if(smpi_op_is_commute(op)){
1429     for (int other = 0; other < size - 1; other++) {
1430       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1431       if(index == MPI_UNDEFINED) {
1432         break;
1433       }
1434       if(index < rank) {
1435         if(recvbuf_is_empty){
1436           smpi_datatype_copy(tmpbufs[index], count, datatype, recvbuf, count, datatype);
1437           recvbuf_is_empty=0;
1438         } else
1439           // #Request is below rank: it's a irecv
1440           smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1441       }
1442     }
1443   }else{
1444     //non commutative case, wait in order
1445     for (int other = 0; other < size - 1; other++) {
1446       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1447       if(index < rank) {
1448         if (recvbuf_is_empty) {
1449           smpi_datatype_copy(tmpbufs[other], count, datatype, recvbuf, count, datatype);
1450           recvbuf_is_empty = 0;
1451         } else
1452           smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1453       }
1454     }
1455   }
1456   for(index = 0; index < rank; index++) {
1457     smpi_free_tmp_buffer(tmpbufs[index]);
1458   }
1459   for(index = 0; index < size-1; index++) {
1460     smpi_mpi_request_free(&requests[index]);
1461   }
1462   xbt_free(tmpbufs);
1463   xbt_free(requests);
1464 }