Logo AND Algorithmique Numérique Distribuée

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