Logo AND Algorithmique Numérique Distribuée

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