Logo AND Algorithmique Numérique Distribuée

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