Logo AND Algorithmique Numérique Distribuée

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