Logo AND Algorithmique Numérique Distribuée

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