Logo AND Algorithmique Numérique Distribuée

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