Logo AND Algorithmique Numérique Distribuée

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