Logo AND Algorithmique Numérique Distribuée

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