Logo AND Algorithmique Numérique Distribuée

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