Logo AND Algorithmique Numérique Distribuée

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