Logo AND Algorithmique Numérique Distribuée

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