Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
613e09817e1e4d724a1946e91b15927c26ab7d7b
[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     MPI_Request req = (MPI_Request)SIMIX_comm_get_src_data(request->action);
860     *flag = 1;
861     if(status != MPI_STATUS_IGNORE && !(req->flags & PREPARED)) {
862       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(comm), req->src);
863       status->MPI_TAG    = req->tag;
864       status->MPI_ERROR  = MPI_SUCCESS;
865       status->count      = req->real_size;
866     }
867     nsleeps=1;//reset the number of sleeps we will do next time
868   }
869   else {
870     *flag = 0;
871     nsleeps++;
872   }
873   smpi_mpi_request_free(&request);
874
875   return;
876 }
877
878 void smpi_mpi_wait(MPI_Request * request, MPI_Status * status)
879 {
880   print_request("Waiting", *request);
881   if ((*request)->flags & PREPARED) {
882     smpi_empty_status(status);
883     return;
884   }
885
886   if ((*request)->action != NULL) { // this is not a detached send
887     simcall_comm_wait((*request)->action, -1.0);
888
889     if((MC_is_active() || MC_record_replay_is_active()) && (*request)->action) {
890       simgrid::simix::Comm *comm = dynamic_cast<simgrid::simix::Comm*>( (*request)->action );
891
892       comm->dst_data = NULL; // dangling pointer: dst_data is freed with a wait, need to set it to NULL for system state comparison
893     }
894   }
895
896   finish_wait(request, status);
897   if (*request != MPI_REQUEST_NULL && ((*request)->flags & NON_PERSISTENT))
898       *request = MPI_REQUEST_NULL;
899   // FIXME for a detached send, finish_wait is not called:
900 }
901
902 int smpi_mpi_waitany(int count, MPI_Request requests[], MPI_Status * status)
903 {
904   xbt_dynar_t comms;
905   int i, size, index;
906   int *map;
907
908   index = MPI_UNDEFINED;
909   if(count > 0) {
910     // Wait for a request to complete
911     comms = xbt_dynar_new(sizeof(smx_synchro_t), NULL);
912     map = xbt_new(int, count);
913     size = 0;
914     XBT_DEBUG("Wait for one of %d", count);
915     for(i = 0; i < count; i++) {
916       if (requests[i] != MPI_REQUEST_NULL && !(requests[i]->flags & PREPARED) && !(requests[i]->flags & FINISHED)) {
917         if (requests[i]->action != NULL) {
918           XBT_DEBUG("Waiting any %p ", requests[i]);
919           xbt_dynar_push(comms, &requests[i]->action);
920           map[size] = i;
921           size++;
922         }else{
923          //This is a finished detached request, let's return this one
924          size=0;//so we free the dynar but don't do the waitany call
925          index=i;
926          finish_wait(&requests[i], status);//cleanup if refcount = 0
927          if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
928          requests[i]=MPI_REQUEST_NULL;//set to null
929          break;
930          }
931       }
932     }
933     if(size > 0) {
934       i = simcall_comm_waitany(comms);
935
936       // not MPI_UNDEFINED, as this is a simix return code
937       if (i != -1) {
938         index = map[i];
939         finish_wait(&requests[index], status);
940         if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
941         requests[index] = MPI_REQUEST_NULL;
942       }
943     }
944     xbt_free(map);
945     xbt_dynar_free(&comms);
946   }
947
948   if (index==MPI_UNDEFINED)
949     smpi_empty_status(status);
950
951   return index;
952 }
953
954 int smpi_mpi_waitall(int count, MPI_Request requests[], MPI_Status status[])
955 {
956   int  index, c;
957   MPI_Status stat;
958   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
959   int retvalue = MPI_SUCCESS;
960   //tag invalid requests in the set
961   if (status != MPI_STATUSES_IGNORE) {
962     for (c = 0; c < count; c++) {
963       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst == MPI_PROC_NULL || (requests[c]->flags & PREPARED)) {
964         smpi_empty_status(&status[c]);
965       } else if (requests[c]->src == MPI_PROC_NULL) {
966         smpi_empty_status(&status[c]);
967         status[c].MPI_SOURCE = MPI_PROC_NULL;
968       }
969     }
970   }
971   for(c = 0; c < count; c++) {
972
973     if (MC_is_active() || MC_record_replay_is_active()) {
974       smpi_mpi_wait(&requests[c], pstat);
975       index = c;
976     } else {
977       index = smpi_mpi_waitany(count, requests, pstat);
978       if (index == MPI_UNDEFINED)
979         break;
980       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
981       requests[index]=MPI_REQUEST_NULL;
982     }
983     if (status != MPI_STATUSES_IGNORE) {
984       status[index] = *pstat;
985       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
986         retvalue = MPI_ERR_IN_STATUS;
987     }
988   }
989
990   return retvalue;
991 }
992
993 int smpi_mpi_waitsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
994 {
995   int i, count, index;
996   MPI_Status stat;
997   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
998
999   count = 0;
1000   for(i = 0; i < incount; i++)
1001   {
1002     index=smpi_mpi_waitany(incount, requests, pstat);
1003     if(index!=MPI_UNDEFINED){
1004       indices[count] = index;
1005       count++;
1006       if(status != MPI_STATUSES_IGNORE) {
1007         status[index] = *pstat;
1008       }
1009      if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
1010      requests[index]=MPI_REQUEST_NULL;
1011     }else{
1012       return MPI_UNDEFINED;
1013     }
1014   }
1015   return count;
1016 }
1017
1018 int smpi_mpi_testsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
1019 {
1020   int i, count, count_dead;
1021   MPI_Status stat;
1022   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
1023
1024   count = 0;
1025   count_dead = 0;
1026   for(i = 0; i < incount; i++) {
1027     if((requests[i] != MPI_REQUEST_NULL)) {
1028       if(smpi_mpi_test(&requests[i], pstat)) {
1029          indices[i] = 1;
1030          count++;
1031          if(status != MPI_STATUSES_IGNORE) {
1032            status[i] = *pstat;
1033          }
1034          if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->flags & NON_PERSISTENT)
1035          requests[i]=MPI_REQUEST_NULL;
1036       }
1037     }else{
1038       count_dead++;
1039     }
1040   }
1041   if(count_dead==incount)return MPI_UNDEFINED;
1042   else return count;
1043 }
1044
1045 void smpi_mpi_bcast(void *buf, int count, MPI_Datatype datatype, int root, MPI_Comm comm)
1046 {
1047     smpi_coll_tuned_bcast_binomial_tree(buf, count, datatype, root, comm);
1048 }
1049
1050 void smpi_mpi_barrier(MPI_Comm comm)
1051 {
1052     smpi_coll_tuned_barrier_ompi_basic_linear(comm);
1053 }
1054
1055 void smpi_mpi_gather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1056                      void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm)
1057 {
1058   int system_tag = COLL_TAG_GATHER;
1059   int rank, size, src, index;
1060   MPI_Aint lb = 0, recvext = 0;
1061   MPI_Request *requests;
1062
1063   rank = smpi_comm_rank(comm);
1064   size = smpi_comm_size(comm);
1065   if(rank != root) {
1066     // Send buffer to root
1067     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1068   } else {
1069     // FIXME: check for errors
1070     smpi_datatype_extent(recvtype, &lb, &recvext);
1071     // Local copy from root
1072     smpi_datatype_copy(sendbuf, sendcount, sendtype, (char *)recvbuf + root * recvcount * recvext, recvcount, recvtype);
1073     // Receive buffers from senders
1074     requests = xbt_new(MPI_Request, size - 1);
1075     index = 0;
1076     for(src = 0; src < size; src++) {
1077       if(src != root) {
1078         requests[index] = smpi_irecv_init((char *)recvbuf + src * recvcount * recvext, recvcount, recvtype,
1079                                           src, system_tag, comm);
1080         index++;
1081       }
1082     }
1083     // Wait for completion of irecv's.
1084     smpi_mpi_startall(size - 1, requests);
1085     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1086     for(src = 0; src < size-1; src++) {
1087       smpi_mpi_request_free(&requests[src]);
1088     }
1089     xbt_free(requests);
1090   }
1091 }
1092
1093 void smpi_mpi_reduce_scatter(void *sendbuf, void *recvbuf, int *recvcounts, MPI_Datatype datatype, MPI_Op op,
1094                              MPI_Comm comm)
1095 {
1096     int i, size, count;
1097     int *displs;
1098     int rank = smpi_comm_rank(comm);
1099     void *tmpbuf;
1100
1101     /* arbitrarily choose root as rank 0 */
1102     size = smpi_comm_size(comm);
1103     count = 0;
1104     displs = xbt_new(int, size);
1105     for (i = 0; i < size; i++) {
1106       displs[i] = count;
1107       count += recvcounts[i];
1108     }
1109     tmpbuf=(void*)smpi_get_tmp_sendbuffer(count*smpi_datatype_get_extent(datatype));
1110
1111     mpi_coll_reduce_fun(sendbuf, tmpbuf, count, datatype, op, 0, comm);
1112     smpi_mpi_scatterv(tmpbuf, recvcounts, displs, datatype, recvbuf, recvcounts[rank], datatype, 0, comm);
1113     xbt_free(displs);
1114     smpi_free_tmp_buffer(tmpbuf);
1115 }
1116
1117 void smpi_mpi_gatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int *recvcounts, int *displs,
1118                       MPI_Datatype recvtype, int root, MPI_Comm comm)
1119 {
1120   int system_tag = COLL_TAG_GATHERV;
1121   int rank, size, src, index;
1122   MPI_Aint lb = 0, recvext = 0;
1123   MPI_Request *requests;
1124
1125   rank = smpi_comm_rank(comm);
1126   size = smpi_comm_size(comm);
1127   if(rank != root) {
1128     // Send buffer to root
1129     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1130   } else {
1131     // FIXME: check for errors
1132     smpi_datatype_extent(recvtype, &lb, &recvext);
1133     // Local copy from root
1134     smpi_datatype_copy(sendbuf, sendcount, sendtype, (char *)recvbuf + displs[root] * recvext,
1135                        recvcounts[root], recvtype);
1136     // Receive buffers from senders
1137     requests = xbt_new(MPI_Request, size - 1);
1138     index = 0;
1139     for(src = 0; src < size; src++) {
1140       if(src != root) {
1141         requests[index] = smpi_irecv_init((char *)recvbuf + displs[src] * recvext,
1142                           recvcounts[src], recvtype, src, system_tag, comm);
1143         index++;
1144       }
1145     }
1146     // Wait for completion of irecv's.
1147     smpi_mpi_startall(size - 1, requests);
1148     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1149     for(src = 0; src < size-1; src++) {
1150       smpi_mpi_request_free(&requests[src]);
1151     }
1152     xbt_free(requests);
1153   }
1154 }
1155
1156 void smpi_mpi_allgather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1157                         void *recvbuf,int recvcount, MPI_Datatype recvtype, MPI_Comm comm)
1158 {
1159   int system_tag = COLL_TAG_ALLGATHER;
1160   int rank, size, other, index;
1161   MPI_Aint lb = 0, recvext = 0;
1162   MPI_Request *requests;
1163
1164   rank = smpi_comm_rank(comm);
1165   size = smpi_comm_size(comm);
1166   // FIXME: check for errors
1167   smpi_datatype_extent(recvtype, &lb, &recvext);
1168   // Local copy from self
1169   smpi_datatype_copy(sendbuf, sendcount, sendtype, (char *)recvbuf + rank * recvcount * recvext, recvcount, recvtype);
1170   // Send/Recv buffers to/from others;
1171   requests = xbt_new(MPI_Request, 2 * (size - 1));
1172   index = 0;
1173   for(other = 0; other < size; other++) {
1174     if(other != rank) {
1175       requests[index] = smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,comm);
1176       index++;
1177       requests[index] = smpi_irecv_init((char *)recvbuf + other * recvcount * recvext, recvcount, recvtype, other,
1178                                         system_tag, comm);
1179       index++;
1180     }
1181   }
1182   // Wait for completion of all comms.
1183   smpi_mpi_startall(2 * (size - 1), requests);
1184   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1185   for(other = 0; other < 2*(size-1); other++) {
1186     smpi_mpi_request_free(&requests[other]);
1187   }
1188   xbt_free(requests);
1189 }
1190
1191 void smpi_mpi_allgatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf,
1192                          int *recvcounts, int *displs, MPI_Datatype recvtype, MPI_Comm comm)
1193 {
1194   int system_tag = COLL_TAG_ALLGATHERV;
1195   int rank, size, other, index;
1196   MPI_Aint lb = 0, recvext = 0;
1197   MPI_Request *requests;
1198
1199   rank = smpi_comm_rank(comm);
1200   size = smpi_comm_size(comm);
1201   // FIXME: check for errors
1202   smpi_datatype_extent(recvtype, &lb, &recvext);
1203   // Local copy from self
1204   smpi_datatype_copy(sendbuf, sendcount, sendtype, (char *)recvbuf + displs[rank] * recvext,recvcounts[rank], recvtype);
1205   // Send buffers to others;
1206   requests = xbt_new(MPI_Request, 2 * (size - 1));
1207   index = 0;
1208   for(other = 0; other < size; other++) {
1209     if(other != rank) {
1210       requests[index] =
1211         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag, comm);
1212       index++;
1213       requests[index] = smpi_irecv_init((char *)recvbuf + displs[other] * recvext, recvcounts[other],
1214                           recvtype, other, system_tag, comm);
1215       index++;
1216     }
1217   }
1218   // Wait for completion of all comms.
1219   smpi_mpi_startall(2 * (size - 1), requests);
1220   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1221   for(other = 0; other < 2*(size-1); other++) {
1222     smpi_mpi_request_free(&requests[other]);
1223   }
1224   xbt_free(requests);
1225 }
1226
1227 void smpi_mpi_scatter(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1228                       void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm)
1229 {
1230   int system_tag = COLL_TAG_SCATTER;
1231   int rank, size, dst, index;
1232   MPI_Aint lb = 0, sendext = 0;
1233   MPI_Request *requests;
1234
1235   rank = smpi_comm_rank(comm);
1236   size = smpi_comm_size(comm);
1237   if(rank != root) {
1238     // Recv buffer from root
1239     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm, MPI_STATUS_IGNORE);
1240   } else {
1241     // FIXME: check for errors
1242     smpi_datatype_extent(sendtype, &lb, &sendext);
1243     // Local copy from root
1244     if(recvbuf!=MPI_IN_PLACE){
1245         smpi_datatype_copy((char *)sendbuf + root * sendcount * sendext,
1246                            sendcount, sendtype, recvbuf, recvcount, recvtype);
1247     }
1248     // Send buffers to receivers
1249     requests = xbt_new(MPI_Request, size - 1);
1250     index = 0;
1251     for(dst = 0; dst < size; dst++) {
1252       if(dst != root) {
1253         requests[index] = smpi_isend_init((char *)sendbuf + dst * sendcount * sendext, sendcount, sendtype, dst,
1254                                           system_tag, comm);
1255         index++;
1256       }
1257     }
1258     // Wait for completion of isend's.
1259     smpi_mpi_startall(size - 1, requests);
1260     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1261     for(dst = 0; dst < size-1; dst++) {
1262       smpi_mpi_request_free(&requests[dst]);
1263     }
1264     xbt_free(requests);
1265   }
1266 }
1267
1268 void smpi_mpi_scatterv(void *sendbuf, int *sendcounts, int *displs, MPI_Datatype sendtype, void *recvbuf, int recvcount,
1269                        MPI_Datatype recvtype, int root, MPI_Comm comm)
1270 {
1271   int system_tag = COLL_TAG_SCATTERV;
1272   int rank, size, dst, index;
1273   MPI_Aint lb = 0, sendext = 0;
1274   MPI_Request *requests;
1275
1276   rank = smpi_comm_rank(comm);
1277   size = smpi_comm_size(comm);
1278   if(rank != root) {
1279     // Recv buffer from root
1280     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm, MPI_STATUS_IGNORE);
1281   } else {
1282     // FIXME: check for errors
1283     smpi_datatype_extent(sendtype, &lb, &sendext);
1284     // Local copy from root
1285     if(recvbuf!=MPI_IN_PLACE){
1286       smpi_datatype_copy((char *)sendbuf + displs[root] * sendext, sendcounts[root],
1287                        sendtype, recvbuf, recvcount, recvtype);
1288     }
1289     // Send buffers to receivers
1290     requests = xbt_new(MPI_Request, size - 1);
1291     index = 0;
1292     for(dst = 0; dst < size; dst++) {
1293       if(dst != root) {
1294         requests[index] = smpi_isend_init((char *)sendbuf + displs[dst] * sendext, sendcounts[dst],
1295                             sendtype, dst, system_tag, comm);
1296         index++;
1297       }
1298     }
1299     // Wait for completion of isend's.
1300     smpi_mpi_startall(size - 1, requests);
1301     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1302     for(dst = 0; dst < size-1; dst++) {
1303       smpi_mpi_request_free(&requests[dst]);
1304     }
1305     xbt_free(requests);
1306   }
1307 }
1308
1309 void smpi_mpi_reduce(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root,
1310                      MPI_Comm comm)
1311 {
1312   int system_tag = COLL_TAG_REDUCE;
1313   int rank, size, src, index;
1314   MPI_Aint lb = 0, dataext = 0;
1315   MPI_Request *requests;
1316   void **tmpbufs;
1317
1318   char* sendtmpbuf = (char*) sendbuf;
1319
1320
1321   rank = smpi_comm_rank(comm);
1322   size = smpi_comm_size(comm);
1323   //non commutative case, use a working algo from openmpi
1324   if(!smpi_op_is_commute(op)){
1325     smpi_coll_tuned_reduce_ompi_basic_linear(sendtmpbuf, recvbuf, count, datatype, op, root, comm);
1326     return;
1327   }
1328
1329   if( sendbuf == MPI_IN_PLACE ) {
1330     sendtmpbuf = (char *)smpi_get_tmp_sendbuffer(count*smpi_datatype_get_extent(datatype));
1331     smpi_datatype_copy(recvbuf, count, datatype,sendtmpbuf, count, datatype);
1332   }
1333   
1334   if(rank != root) {
1335     // Send buffer to root
1336     smpi_mpi_send(sendtmpbuf, count, datatype, root, system_tag, comm);
1337   } else {
1338     // FIXME: check for errors
1339     smpi_datatype_extent(datatype, &lb, &dataext);
1340     // Local copy from root
1341     if (sendtmpbuf && recvbuf)
1342       smpi_datatype_copy(sendtmpbuf, count, datatype, recvbuf, count, datatype);
1343     // Receive buffers from senders
1344     //TODO: make a MPI_barrier here ?
1345     requests = xbt_new(MPI_Request, size - 1);
1346     tmpbufs = xbt_new(void *, size - 1);
1347     index = 0;
1348     for(src = 0; src < size; src++) {
1349       if(src != root) {
1350         // FIXME: possibly overkill we we have contiguous/noncontiguous data
1351         //  mapping...
1352          if (!smpi_process_get_replaying())
1353           tmpbufs[index] = xbt_malloc(count * dataext);
1354          else
1355            tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1356         requests[index] =
1357           smpi_irecv_init(tmpbufs[index], count, datatype, src, system_tag, comm);
1358         index++;
1359       }
1360     }
1361     // Wait for completion of irecv's.
1362     smpi_mpi_startall(size - 1, requests);
1363     for(src = 0; src < size - 1; src++) {
1364       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1365       XBT_DEBUG("finished waiting any request with index %d", index);
1366       if(index == MPI_UNDEFINED) {
1367         break;
1368       }else{
1369         smpi_mpi_request_free(&requests[index]);
1370       }
1371       if(op) /* op can be MPI_OP_NULL that does nothing */
1372         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1373     }
1374       for(index = 0; index < size - 1; index++) {
1375         smpi_free_tmp_buffer(tmpbufs[index]);
1376       }
1377     xbt_free(tmpbufs);
1378     xbt_free(requests);
1379
1380   }
1381   if( sendbuf == MPI_IN_PLACE ) {
1382     smpi_free_tmp_buffer(sendtmpbuf);
1383   }
1384 }
1385
1386 void smpi_mpi_allreduce(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1387 {
1388   smpi_mpi_reduce(sendbuf, recvbuf, count, datatype, op, 0, comm);
1389   smpi_mpi_bcast(recvbuf, count, datatype, 0, comm);
1390 }
1391
1392 void smpi_mpi_scan(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1393 {
1394   int system_tag = -888;
1395   int rank, size, other, index;
1396   MPI_Aint lb = 0, dataext = 0;
1397   MPI_Request *requests;
1398   void **tmpbufs;
1399
1400   rank = smpi_comm_rank(comm);
1401   size = smpi_comm_size(comm);
1402
1403   // FIXME: check for errors
1404   smpi_datatype_extent(datatype, &lb, &dataext);
1405
1406   // Local copy from self
1407   smpi_datatype_copy(sendbuf, count, datatype, recvbuf, count, datatype);
1408
1409   // Send/Recv buffers to/from others;
1410   requests = xbt_new(MPI_Request, size - 1);
1411   tmpbufs = xbt_new(void *, rank);
1412   index = 0;
1413   for(other = 0; other < rank; other++) {
1414     // FIXME: possibly overkill we we have contiguous/noncontiguous data
1415     // mapping...
1416     tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1417     requests[index] = smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag, comm);
1418     index++;
1419   }
1420   for(other = rank + 1; other < size; other++) {
1421     requests[index] = smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1422     index++;
1423   }
1424   // Wait for completion of all comms.
1425   smpi_mpi_startall(size - 1, requests);
1426
1427   if(smpi_op_is_commute(op)){
1428     for(other = 0; other < size - 1; other++) {
1429       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1430       if(index == MPI_UNDEFINED) {
1431         break;
1432       }
1433       if(index < rank) {
1434         // #Request is below rank: it's a irecv
1435         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1436       }
1437     }
1438   }else{
1439     //non commutative case, wait in order
1440     for(other = 0; other < size - 1; other++) {
1441       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1442       if(index < rank) {
1443         smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1444       }
1445     }
1446   }
1447   for(index = 0; index < rank; index++) {
1448     smpi_free_tmp_buffer(tmpbufs[index]);
1449   }
1450   for(index = 0; index < size-1; index++) {
1451     smpi_mpi_request_free(&requests[index]);
1452   }
1453   xbt_free(tmpbufs);
1454   xbt_free(requests);
1455 }
1456
1457 void smpi_mpi_exscan(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1458 {
1459   int system_tag = -888;
1460   int rank, size, other, index;
1461   MPI_Aint lb = 0, dataext = 0;
1462   MPI_Request *requests;
1463   void **tmpbufs;
1464   int recvbuf_is_empty=1;
1465   rank = smpi_comm_rank(comm);
1466   size = smpi_comm_size(comm);
1467
1468   // FIXME: check for errors
1469   smpi_datatype_extent(datatype, &lb, &dataext);
1470
1471   // Send/Recv buffers to/from others;
1472   requests = xbt_new(MPI_Request, size - 1);
1473   tmpbufs = xbt_new(void *, rank);
1474   index = 0;
1475   for(other = 0; other < rank; other++) {
1476     // FIXME: possibly overkill we we have contiguous/noncontiguous data
1477     // mapping...
1478     tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1479     requests[index] =
1480       smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag, comm);
1481     index++;
1482   }
1483   for(other = rank + 1; other < size; other++) {
1484     requests[index] =
1485       smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1486     index++;
1487   }
1488   // Wait for completion of all comms.
1489   smpi_mpi_startall(size - 1, requests);
1490   if(smpi_op_is_commute(op)){
1491     for(other = 0; other < size - 1; other++) {
1492       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1493       if(index == MPI_UNDEFINED) {
1494         break;
1495       }
1496       if(index < rank) {
1497         if(recvbuf_is_empty){
1498           smpi_datatype_copy(tmpbufs[index], count, datatype, recvbuf, count, datatype);
1499           recvbuf_is_empty=0;
1500         }else
1501         // #Request is below rank: it's a irecv
1502         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1503       }
1504     }
1505   }else{
1506     //non commutative case, wait in order
1507     for(other = 0; other < size - 1; other++) {
1508       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1509       if(index < rank) {
1510           if(recvbuf_is_empty){
1511             smpi_datatype_copy(tmpbufs[other], count, datatype, recvbuf, count, datatype);
1512             recvbuf_is_empty=0;
1513           }else smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1514       }
1515     }
1516   }
1517   for(index = 0; index < rank; index++) {
1518     smpi_free_tmp_buffer(tmpbufs[index]);
1519   }
1520   for(index = 0; index < size-1; index++) {
1521     smpi_mpi_request_free(&requests[index]);
1522   }
1523   xbt_free(tmpbufs);
1524   xbt_free(requests);
1525 }