Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Empty status in any case (plus slight reindent).
[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   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 = NULL;
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   request->real_src = 0;
223
224   request->truncated = 0;
225   request->real_size = 0;
226   request->real_tag = 0;
227
228   request->refcount=1;
229 #ifdef HAVE_TRACING
230   request->send = 0;
231   request->recv = 0;
232 #endif
233   if (flags & SEND) smpi_datatype_unuse(datatype);
234
235   return request;
236 }
237
238
239 void smpi_empty_status(MPI_Status * status)
240 {
241   if(status != MPI_STATUS_IGNORE) {
242     status->MPI_SOURCE = MPI_ANY_SOURCE;
243     status->MPI_TAG = MPI_ANY_TAG;
244     status->MPI_ERROR = MPI_SUCCESS;
245     status->count=0;
246   }
247 }
248
249 void smpi_action_trace_run(char *path)
250 {
251   char *name;
252   xbt_dynar_t todo;
253   xbt_dict_cursor_t cursor;
254
255   action_fp=NULL;
256   if (path) {
257     action_fp = fopen(path, "r");
258     xbt_assert(action_fp != NULL, "Cannot open %s: %s", path,
259                strerror(errno));
260   }
261
262   if (!xbt_dict_is_empty(action_queues)) {
263     XBT_WARN
264       ("Not all actions got consumed. If the simulation ended successfully (without deadlock), you may want to add new processes to your deployment file.");
265
266
267     xbt_dict_foreach(action_queues, cursor, name, todo) {
268       XBT_WARN("Still %lu actions for %s", xbt_dynar_length(todo), name);
269     }
270   }
271
272   if (path)
273     fclose(action_fp);
274   xbt_dict_free(&action_queues);
275   action_queues = xbt_dict_new_homogeneous(NULL);
276 }
277
278 static void smpi_mpi_request_free_voidp(void* request)
279 {
280   MPI_Request req = request;
281   smpi_mpi_request_free(&req);
282 }
283
284 /* MPI Low level calls */
285 MPI_Request smpi_mpi_send_init(void *buf, int count, MPI_Datatype datatype,
286                                int dst, int tag, MPI_Comm comm)
287 {
288   MPI_Request request = NULL;
289   request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf, count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
290                           comm, PERSISTENT | SEND | PREPARED);
291   request->refcount++;
292   return request;
293 }
294
295 MPI_Request smpi_mpi_ssend_init(void *buf, int count, MPI_Datatype datatype,
296                                int dst, int tag, MPI_Comm comm)
297 {
298   MPI_Request request = NULL;
299   request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf, count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
300                           comm, PERSISTENT | SSEND | SEND | PREPARED);
301   request->refcount++;
302   return request;
303 }
304
305 MPI_Request smpi_mpi_recv_init(void *buf, int count, MPI_Datatype datatype,
306                                int src, int tag, MPI_Comm comm)
307 {
308   MPI_Request request = NULL;
309   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,
310                           comm, PERSISTENT | RECV | PREPARED);
311   request->refcount++;
312   return request;
313 }
314
315 void smpi_mpi_start(MPI_Request request)
316 {
317   smx_rdv_t mailbox;
318
319   xbt_assert(!request->action,
320              "Cannot (re)start a non-finished communication");
321   if(request->flags & PREPARED)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 %lf ", 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 %lf ", 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
419   for(i = 0; i < count; i++) {
420     smpi_mpi_start(requests[i]);
421   }
422 }
423
424 void smpi_mpi_request_free(MPI_Request * request)
425 {
426   if((*request) != MPI_REQUEST_NULL){
427     (*request)->refcount--;
428     if((*request)->refcount<0) xbt_die("wrong refcount");
429
430     if((*request)->refcount==0){
431         print_request("Destroying", (*request));
432         xbt_free(*request);
433         *request = MPI_REQUEST_NULL;
434     }else{
435         print_request("Decrementing", (*request));
436
437     }
438   }else{
439       xbt_die("freeing an already free request");
440   }
441 }
442
443 MPI_Request smpi_isend_init(void *buf, int count, MPI_Datatype datatype,
444                             int dst, int tag, MPI_Comm comm)
445 {
446   MPI_Request request = NULL;
447   request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf , count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
448                           comm, NON_PERSISTENT | ISEND | SEND | PREPARED);
449   return request;
450 }
451
452 MPI_Request smpi_mpi_isend(void *buf, int count, MPI_Datatype datatype,
453                            int dst, int tag, MPI_Comm comm)
454 {
455   MPI_Request request = NULL;
456   request =  build_request(buf==MPI_BOTTOM?(void*)0:buf, count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
457                            comm, NON_PERSISTENT | ISEND | SEND);
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 = NULL;
466   request = 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 = NULL;
478   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,
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 = NULL;
487   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,
488                           comm, NON_PERSISTENT | RECV);
489   smpi_mpi_start(request);
490   return request;
491 }
492
493 void smpi_mpi_recv(void *buf, int count, MPI_Datatype datatype, int src,
494                    int tag, MPI_Comm comm, MPI_Status * status)
495 {
496   MPI_Request request = NULL;
497   request = smpi_mpi_irecv(buf, count, datatype, src, tag, comm);
498   smpi_mpi_wait(&request, status);
499   request = NULL;
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 = NULL;
508   request = 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
511   smpi_mpi_start(request);
512   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
513   request = NULL;
514 }
515
516 void smpi_mpi_ssend(void *buf, int count, MPI_Datatype datatype,
517                            int dst, int tag, MPI_Comm comm)
518 {
519   MPI_Request request = NULL;
520   request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf, count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
521                 comm, NON_PERSISTENT | SSEND | SEND);
522
523   smpi_mpi_start(request);
524   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
525   request = NULL;
526 }
527
528 void smpi_mpi_sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,
529                        int dst, int sendtag, void *recvbuf, int recvcount,
530                        MPI_Datatype recvtype, int src, int recvtag,
531                        MPI_Comm comm, MPI_Status * status)
532 {
533   MPI_Request requests[2];
534   MPI_Status stats[2];
535   int myid=smpi_process_index();
536   if ((smpi_group_index(smpi_comm_group(comm), dst) == myid) && (smpi_group_index(smpi_comm_group(comm), src) == myid)) {
537       smpi_datatype_copy(sendbuf, sendcount, sendtype,
538                                      recvbuf, recvcount, recvtype);
539       return;
540   }
541   requests[0] =
542     smpi_isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
543   requests[1] =
544     smpi_irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
545   smpi_mpi_startall(2, requests);
546   smpi_mpi_waitall(2, requests, stats);
547   if(status != MPI_STATUS_IGNORE) {
548     // Copy receive status
549     *status = stats[1];
550   }
551 }
552
553 int smpi_mpi_get_count(MPI_Status * status, MPI_Datatype datatype)
554 {
555   return status->count / smpi_datatype_size(datatype);
556 }
557
558 static void finish_wait(MPI_Request * request, MPI_Status * status)
559 {
560   MPI_Request req = *request;
561   smpi_empty_status(status);
562
563   if(!(req->detached && req->flags & SEND) && !(req->flags & PREPARED)){
564     if(status != MPI_STATUS_IGNORE) {
565       int src = req->src == MPI_ANY_SOURCE ? req->real_src : req->src;
566       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(req->comm), src);
567       status->MPI_TAG = req->tag == MPI_ANY_TAG ? req->real_tag : req->tag;
568       status->MPI_ERROR = req->truncated ? MPI_ERR_TRUNCATE : MPI_SUCCESS;
569       // this handles the case were size in receive differs from size in send
570       // FIXME: really this should just contain the count of receive-type blocks,
571       // right?
572       status->count = req->real_size;
573     }
574
575     print_request("Finishing", req);
576     MPI_Datatype datatype = req->old_type;
577
578     if(datatype->has_subtype == 1){
579       // This part handles the problem of non-contignous memory
580       // the unserialization at the reception
581       s_smpi_subtype_t *subtype = datatype->substruct;
582       if(req->flags & RECV) {
583         subtype->unserialize(req->buf, req->old_buf, req->real_size/smpi_datatype_size(datatype) , datatype->substruct);
584       }
585       if(req->detached == 0) free(req->buf);
586     }
587     smpi_comm_unuse(req->comm);
588     smpi_datatype_unuse(datatype);
589
590   }
591
592 #ifdef HAVE_TRACING
593   if (TRACE_smpi_view_internals()) {
594     if(req->flags & RECV){
595       int rank = smpi_process_index();
596       int src_traced = (req->src == MPI_ANY_SOURCE ? req->real_src : req->src);
597       TRACE_smpi_recv(rank, src_traced, rank);
598     }
599   }
600 #endif
601
602   if(req->detached_sender!=NULL){
603     smpi_mpi_request_free(&(req->detached_sender));
604   }
605
606   if(req->flags & NON_PERSISTENT) {
607     smpi_mpi_request_free(request);
608   } else {
609     req->action = NULL;
610   }
611 }
612
613 int smpi_mpi_test(MPI_Request * request, MPI_Status * status) {
614   int flag;
615
616   //assume that request is not MPI_REQUEST_NULL (filtered in PMPI_Test or smpi_mpi_testall before)
617   if ((*request)->action == NULL)
618     flag = 1;
619   else
620     flag = simcall_comm_test((*request)->action);
621   if(flag) {
622     finish_wait(request, status);
623     *request = MPI_REQUEST_NULL;
624   }else{
625     smpi_empty_status(status);
626   }
627   return flag;
628 }
629
630 int smpi_mpi_testany(int count, MPI_Request requests[], int *index,
631                      MPI_Status * status)
632 {
633   xbt_dynar_t comms;
634   int i, flag, size;
635   int* map;
636
637   *index = MPI_UNDEFINED;
638   flag = 0;
639   comms = xbt_dynar_new(sizeof(smx_action_t), NULL);
640   map = xbt_new(int, count);
641   size = 0;
642   for(i = 0; i < count; i++) {
643     if((requests[i]!=MPI_REQUEST_NULL) && requests[i]->action) {
644        xbt_dynar_push(comms, &requests[i]->action);
645        map[size] = i;
646        size++;
647     }
648   }
649   if(size > 0) {
650     i = simcall_comm_testany(comms);
651     // not MPI_UNDEFINED, as this is a simix return code
652     if(i != -1) {
653       *index = map[i];
654       finish_wait(&requests[*index], status);
655       flag = 1;
656     }
657   }else{
658       //all requests are null or inactive, return true
659       flag=1;
660       smpi_empty_status(status);
661   }
662   xbt_free(map);
663   xbt_dynar_free(&comms);
664
665   return flag;
666 }
667
668
669 int smpi_mpi_testall(int count, MPI_Request requests[],
670                      MPI_Status status[])
671 {
672   MPI_Status stat;
673   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
674   int flag=1;
675   int i;
676   for(i=0; i<count; i++){
677     if(requests[i]!= MPI_REQUEST_NULL){
678       if (smpi_mpi_test(&requests[i], pstat)!=1){
679         flag=0;
680       }else{
681           requests[i]=MPI_REQUEST_NULL;
682       }
683     }else{
684       smpi_empty_status(pstat);
685     }
686     if(status != MPI_STATUSES_IGNORE) {
687       status[i] = *pstat;
688     }
689   }
690   return flag;
691 }
692
693 void smpi_mpi_probe(int source, int tag, MPI_Comm comm, MPI_Status* status){
694   int flag=0;
695   //FIXME find another wait to avoid busy waiting ?
696   // the issue here is that we have to wait on a nonexistent comm
697   while(flag==0){
698     smpi_mpi_iprobe(source, tag, comm, &flag, status);
699     XBT_DEBUG("Busy Waiting on probing : %d", flag);
700   }
701 }
702
703 void smpi_mpi_iprobe(int source, int tag, MPI_Comm comm, int* flag, MPI_Status* status){
704
705   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,
706             comm, NON_PERSISTENT | RECV);
707
708   //to avoid deadlock, we have to sleep some time here, or the timer won't advance and we will only do iprobe simcalls
709   double sleeptime= sg_cfg_get_double("smpi/iprobe");
710   //multiplier to the sleeptime, to increase speed of execution, each failed iprobe will increase it
711   static int nsleeps = 1;
712
713   simcall_process_sleep(sleeptime);
714
715   // behave like a receive, but don't do it
716   smx_rdv_t mailbox;
717
718   print_request("New iprobe", request);
719   // We have to test both mailboxes as we don't know if we will receive one one or another
720     if (sg_cfg_get_int("smpi/async_small_thres")>0){
721         mailbox = smpi_process_mailbox_small();
722         XBT_DEBUG("trying to probe the perm recv mailbox");
723         request->action = simcall_comm_iprobe(mailbox, request->src, request->tag, &match_recv, (void*)request);
724     }
725     if (request->action==NULL){
726         mailbox = smpi_process_mailbox();
727         XBT_DEBUG("trying to probe the other mailbox");
728         request->action = simcall_comm_iprobe(mailbox, request->src, request->tag, &match_recv, (void*)request);
729     }
730
731   if(request->action){
732     MPI_Request req = (MPI_Request)SIMIX_comm_get_src_data(request->action);
733     *flag = 1;
734     if(status != MPI_STATUS_IGNORE && !(req->flags & PREPARED)) {
735       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(comm), req->src);
736       status->MPI_TAG = req->tag;
737       status->MPI_ERROR = MPI_SUCCESS;
738       status->count = req->real_size;
739     }
740     nsleeps=1;//reset the number of sleeps we will do next time
741   }
742   else {
743       *flag = 0;
744       nsleeps++;
745   }
746   smpi_mpi_request_free(&request);
747
748   return;
749 }
750
751 void smpi_mpi_wait(MPI_Request * request, MPI_Status * status)
752 {
753   print_request("Waiting", *request);
754   if ((*request)->action != NULL) { // this is not a detached send
755     simcall_comm_wait((*request)->action, -1.0);
756   }
757
758 #ifdef HAVE_MC
759   if(MC_is_active())
760     (*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
761 #endif
762
763   finish_wait(request, status);
764   *request = MPI_REQUEST_NULL;
765   // FIXME for a detached send, finish_wait is not called:
766 }
767
768 int smpi_mpi_waitany(int count, MPI_Request requests[],
769                      MPI_Status * status)
770 {
771   xbt_dynar_t comms;
772   int i, size, index;
773   int *map;
774
775   index = MPI_UNDEFINED;
776   if(count > 0) {
777     // Wait for a request to complete
778     comms = xbt_dynar_new(sizeof(smx_action_t), NULL);
779     map = xbt_new(int, count);
780     size = 0;
781     XBT_DEBUG("Wait for one of %d", count);
782     for(i = 0; i < count; i++) {
783       if(requests[i] != MPI_REQUEST_NULL) {
784         if (requests[i]->action != NULL) {
785           XBT_DEBUG("Waiting any %p ", requests[i]);
786           xbt_dynar_push(comms, &requests[i]->action);
787           map[size] = i;
788           size++;
789         }else{
790          //This is a finished detached request, let's return this one
791          size=0;//so we free the dynar but don't do the waitany call
792          index=i;
793          finish_wait(&requests[i], status);//cleanup if refcount = 0
794          requests[i]=MPI_REQUEST_NULL;//set to null
795          break;
796          }
797       }
798     }
799     if(size > 0) {
800       i = simcall_comm_waitany(comms);
801
802       // not MPI_UNDEFINED, as this is a simix return code
803       if (i != -1) {
804         index = map[i];
805         finish_wait(&requests[index], status);
806       }
807     }
808     xbt_free(map);
809     xbt_dynar_free(&comms);
810   }
811
812   if (index==MPI_UNDEFINED)
813     smpi_empty_status(status);
814
815   return index;
816 }
817
818 int smpi_mpi_waitall(int count, MPI_Request requests[],
819                       MPI_Status status[])
820 {
821   int  index, c;
822   MPI_Status stat;
823   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
824   int retvalue = MPI_SUCCESS;
825   //tag invalid requests in the set
826   if (status != MPI_STATUSES_IGNORE) {
827     for (c = 0; c < count; c++) {
828       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst == MPI_PROC_NULL) {
829         smpi_empty_status(&status[c]);
830       } else if (requests[c]->src == MPI_PROC_NULL) {
831         smpi_empty_status(&status[c]);
832         status[c].MPI_SOURCE = MPI_PROC_NULL;
833       }
834     }
835   }
836   for(c = 0; c < count; c++) {
837     if (MC_is_active()) {
838       smpi_mpi_wait(&requests[c], pstat);
839       index = c;
840     } else {
841       index = smpi_mpi_waitany(count, requests, pstat);
842       if (index == MPI_UNDEFINED)
843         break;
844       requests[index]=MPI_REQUEST_NULL;
845     }
846     if (status != MPI_STATUSES_IGNORE) {
847       status[index] = *pstat;
848       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
849         retvalue = MPI_ERR_IN_STATUS;
850     }
851   }
852
853   return retvalue;
854 }
855
856 int smpi_mpi_waitsome(int incount, MPI_Request requests[], int *indices,
857                       MPI_Status status[])
858 {
859   int i, count, index;
860   MPI_Status stat;
861   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
862
863   count = 0;
864   for(i = 0; i < incount; i++)
865   {
866     index=smpi_mpi_waitany(incount, requests, pstat);
867     if(index!=MPI_UNDEFINED){
868       indices[count] = index;
869       count++;
870       if(status != MPI_STATUSES_IGNORE) {
871         status[index] = *pstat;
872       }
873      requests[index]=MPI_REQUEST_NULL;
874     }else{
875       return MPI_UNDEFINED;
876     }
877   }
878   return count;
879 }
880
881 int smpi_mpi_testsome(int incount, MPI_Request requests[], int *indices,
882                       MPI_Status status[])
883 {
884   int i, count, count_dead;
885   MPI_Status stat;
886   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
887
888   count = 0;
889   count_dead = 0;
890   for(i = 0; i < incount; i++) {
891     if((requests[i] != MPI_REQUEST_NULL)) {
892       if(smpi_mpi_test(&requests[i], pstat)) {
893          indices[i] = 1;
894          count++;
895          if(status != MPI_STATUSES_IGNORE) {
896            status[i] = *pstat;
897          }
898          requests[i]=MPI_REQUEST_NULL;
899
900       }
901     }else{
902       count_dead++;
903     }
904   }
905   if(count_dead==incount)return MPI_UNDEFINED;
906   else return count;
907 }
908
909 void smpi_mpi_bcast(void *buf, int count, MPI_Datatype datatype, int root,
910                     MPI_Comm comm)
911 {
912   // arity=2: a binary tree, arity=4 seem to be a good setting (see P2P-MPI))
913   nary_tree_bcast(buf, count, datatype, root, comm, 4);
914 }
915
916 void smpi_mpi_barrier(MPI_Comm comm)
917 {
918   // arity=2: a binary tree, arity=4 seem to be a good setting (see P2P-MPI))
919   nary_tree_barrier(comm, 4);
920 }
921
922 void smpi_mpi_gather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
923                      void *recvbuf, int recvcount, MPI_Datatype recvtype,
924                      int root, MPI_Comm comm)
925 {
926   int system_tag = COLL_TAG_GATHER;
927   int rank, size, src, index;
928   MPI_Aint lb = 0, recvext = 0;
929   MPI_Request *requests;
930
931   rank = smpi_comm_rank(comm);
932   size = smpi_comm_size(comm);
933   if(rank != root) {
934     // Send buffer to root
935     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
936   } else {
937     // FIXME: check for errors
938     smpi_datatype_extent(recvtype, &lb, &recvext);
939     // Local copy from root
940     smpi_datatype_copy(sendbuf, sendcount, sendtype,
941                        (char *)recvbuf + root * recvcount * recvext, recvcount, recvtype);
942     // Receive buffers from senders
943     requests = xbt_new(MPI_Request, size - 1);
944     index = 0;
945     for(src = 0; src < size; src++) {
946       if(src != root) {
947         requests[index] = smpi_irecv_init((char *)recvbuf + src * recvcount * recvext,
948                                           recvcount, recvtype,
949                                           src, system_tag, comm);
950         index++;
951       }
952     }
953     // Wait for completion of irecv's.
954     smpi_mpi_startall(size - 1, requests);
955     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
956     xbt_free(requests);
957   }
958 }
959
960
961 void smpi_mpi_reduce_scatter(void *sendbuf, void *recvbuf, int *recvcounts,
962                        MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
963 {
964     int i, size, count;
965     int *displs;
966     int rank = smpi_process_index();
967     void *tmpbuf;
968
969     /* arbitrarily choose root as rank 0 */
970     size = smpi_comm_size(comm);
971     count = 0;
972     displs = xbt_new(int, size);
973     for (i = 0; i < size; i++) {
974       displs[i] = count;
975       count += recvcounts[i];
976     }
977     tmpbuf=(void*)xbt_malloc(count*smpi_datatype_get_extent(datatype));
978     mpi_coll_reduce_fun(sendbuf, tmpbuf, count, datatype, op, 0, comm);
979     smpi_mpi_scatterv(tmpbuf, recvcounts, displs, datatype, recvbuf,
980                       recvcounts[rank], datatype, 0, comm);
981     xbt_free(displs);
982     xbt_free(tmpbuf);
983 }
984
985 void smpi_mpi_gatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype,
986                       void *recvbuf, int *recvcounts, int *displs,
987                       MPI_Datatype recvtype, int root, MPI_Comm comm)
988 {
989   int system_tag = COLL_TAG_GATHERV;
990   int rank, size, src, index;
991   MPI_Aint lb = 0, recvext = 0;
992   MPI_Request *requests;
993
994   rank = smpi_comm_rank(comm);
995   size = smpi_comm_size(comm);
996   if(rank != root) {
997     // Send buffer to root
998     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
999   } else {
1000     // FIXME: check for errors
1001     smpi_datatype_extent(recvtype, &lb, &recvext);
1002     // Local copy from root
1003     smpi_datatype_copy(sendbuf, sendcount, sendtype,
1004                        (char *)recvbuf + displs[root] * recvext,
1005                        recvcounts[root], recvtype);
1006     // Receive buffers from senders
1007     requests = xbt_new(MPI_Request, size - 1);
1008     index = 0;
1009     for(src = 0; src < size; src++) {
1010       if(src != root) {
1011         requests[index] =
1012           smpi_irecv_init((char *)recvbuf + displs[src] * recvext,
1013                           recvcounts[src], recvtype, src, system_tag, comm);
1014         index++;
1015       }
1016     }
1017     // Wait for completion of irecv's.
1018     smpi_mpi_startall(size - 1, requests);
1019     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1020     xbt_free(requests);
1021   }
1022 }
1023
1024 void smpi_mpi_allgather(void *sendbuf, int sendcount,
1025                         MPI_Datatype sendtype, void *recvbuf,
1026                         int recvcount, MPI_Datatype recvtype,
1027                         MPI_Comm comm)
1028 {
1029   int system_tag = COLL_TAG_ALLGATHER;
1030   int rank, size, other, index;
1031   MPI_Aint lb = 0, recvext = 0;
1032   MPI_Request *requests;
1033
1034   rank = smpi_comm_rank(comm);
1035   size = smpi_comm_size(comm);
1036   // FIXME: check for errors
1037   smpi_datatype_extent(recvtype, &lb, &recvext);
1038   // Local copy from self
1039   smpi_datatype_copy(sendbuf, sendcount, sendtype,
1040                      (char *)recvbuf + rank * recvcount * recvext, recvcount,
1041                      recvtype);
1042   // Send/Recv buffers to/from others;
1043   requests = xbt_new(MPI_Request, 2 * (size - 1));
1044   index = 0;
1045   for(other = 0; other < size; other++) {
1046     if(other != rank) {
1047       requests[index] =
1048         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,
1049                         comm);
1050       index++;
1051       requests[index] = smpi_irecv_init((char *)recvbuf + other * recvcount * recvext,
1052                                         recvcount, recvtype, other,
1053                                         system_tag, comm);
1054       index++;
1055     }
1056   }
1057   // Wait for completion of all comms.
1058   smpi_mpi_startall(2 * (size - 1), requests);
1059   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1060   xbt_free(requests);
1061 }
1062
1063 void smpi_mpi_allgatherv(void *sendbuf, int sendcount,
1064                          MPI_Datatype sendtype, void *recvbuf,
1065                          int *recvcounts, int *displs,
1066                          MPI_Datatype recvtype, MPI_Comm comm)
1067 {
1068   int system_tag = COLL_TAG_ALLGATHERV;
1069   int rank, size, other, index;
1070   MPI_Aint lb = 0, recvext = 0;
1071   MPI_Request *requests;
1072
1073   rank = smpi_comm_rank(comm);
1074   size = smpi_comm_size(comm);
1075   // FIXME: check for errors
1076   smpi_datatype_extent(recvtype, &lb, &recvext);
1077   // Local copy from self
1078   smpi_datatype_copy(sendbuf, sendcount, sendtype,
1079                      (char *)recvbuf + displs[rank] * recvext,
1080                      recvcounts[rank], recvtype);
1081   // Send buffers to others;
1082   requests = xbt_new(MPI_Request, 2 * (size - 1));
1083   index = 0;
1084   for(other = 0; other < size; other++) {
1085     if(other != rank) {
1086       requests[index] =
1087         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,
1088                         comm);
1089       index++;
1090       requests[index] =
1091         smpi_irecv_init((char *)recvbuf + displs[other] * recvext, recvcounts[other],
1092                         recvtype, other, system_tag, comm);
1093       index++;
1094     }
1095   }
1096   // Wait for completion of all comms.
1097   smpi_mpi_startall(2 * (size - 1), requests);
1098   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1099   xbt_free(requests);
1100 }
1101
1102 void smpi_mpi_scatter(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1103                       void *recvbuf, int recvcount, MPI_Datatype recvtype,
1104                       int root, MPI_Comm comm)
1105 {
1106   int system_tag = COLL_TAG_SCATTER;
1107   int rank, size, dst, index;
1108   MPI_Aint lb = 0, sendext = 0;
1109   MPI_Request *requests;
1110
1111   rank = smpi_comm_rank(comm);
1112   size = smpi_comm_size(comm);
1113   if(rank != root) {
1114     // Recv buffer from root
1115     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm,
1116                   MPI_STATUS_IGNORE);
1117   } else {
1118     // FIXME: check for errors
1119     smpi_datatype_extent(sendtype, &lb, &sendext);
1120     // Local copy from root
1121     if(recvbuf!=MPI_IN_PLACE){
1122         smpi_datatype_copy((char *)sendbuf + root * sendcount * sendext,
1123                            sendcount, sendtype, recvbuf, recvcount, recvtype);
1124     }
1125     // Send buffers to receivers
1126     requests = xbt_new(MPI_Request, size - 1);
1127     index = 0;
1128     for(dst = 0; dst < size; dst++) {
1129       if(dst != root) {
1130         requests[index] = smpi_isend_init((char *)sendbuf + dst * sendcount * sendext,
1131                                           sendcount, sendtype, dst,
1132                                           system_tag, comm);
1133         index++;
1134       }
1135     }
1136     // Wait for completion of isend's.
1137     smpi_mpi_startall(size - 1, requests);
1138     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1139     xbt_free(requests);
1140   }
1141 }
1142
1143 void smpi_mpi_scatterv(void *sendbuf, int *sendcounts, int *displs,
1144                        MPI_Datatype sendtype, void *recvbuf, int recvcount,
1145                        MPI_Datatype recvtype, int root, MPI_Comm comm)
1146 {
1147   int system_tag = COLL_TAG_SCATTERV;
1148   int rank, size, dst, index;
1149   MPI_Aint lb = 0, sendext = 0;
1150   MPI_Request *requests;
1151
1152   rank = smpi_comm_rank(comm);
1153   size = smpi_comm_size(comm);
1154   if(rank != root) {
1155     // Recv buffer from root
1156     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm,
1157                   MPI_STATUS_IGNORE);
1158   } else {
1159     // FIXME: check for errors
1160     smpi_datatype_extent(sendtype, &lb, &sendext);
1161     // Local copy from root
1162     if(recvbuf!=MPI_IN_PLACE){
1163       smpi_datatype_copy((char *)sendbuf + displs[root] * sendext, sendcounts[root],
1164                        sendtype, recvbuf, recvcount, recvtype);
1165     }
1166     // Send buffers to receivers
1167     requests = xbt_new(MPI_Request, size - 1);
1168     index = 0;
1169     for(dst = 0; dst < size; dst++) {
1170       if(dst != root) {
1171         requests[index] =
1172           smpi_isend_init((char *)sendbuf + displs[dst] * sendext, sendcounts[dst],
1173                           sendtype, dst, system_tag, comm);
1174         index++;
1175       }
1176     }
1177     // Wait for completion of isend's.
1178     smpi_mpi_startall(size - 1, requests);
1179     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1180     xbt_free(requests);
1181   }
1182 }
1183
1184 void smpi_mpi_reduce(void *sendbuf, void *recvbuf, int count,
1185                      MPI_Datatype datatype, MPI_Op op, int root,
1186                      MPI_Comm comm)
1187 {
1188   int system_tag = COLL_TAG_REDUCE;
1189   int rank, size, src, index;
1190   MPI_Aint lb = 0, dataext = 0;
1191   MPI_Request *requests;
1192   void **tmpbufs;
1193
1194
1195   char* sendtmpbuf = (char*) sendbuf;
1196   if( sendbuf == MPI_IN_PLACE ) {
1197     sendtmpbuf = (char *)xbt_malloc(count*smpi_datatype_get_extent(datatype));
1198     smpi_datatype_copy(recvbuf, count, datatype,sendtmpbuf, count, datatype);
1199   }
1200
1201   rank = smpi_comm_rank(comm);
1202   size = smpi_comm_size(comm);
1203   //non commutative case, use a working algo from openmpi
1204   if(!smpi_op_is_commute(op)){
1205     smpi_coll_tuned_reduce_ompi_basic_linear(sendtmpbuf, recvbuf, count,
1206                      datatype, op, root, comm);
1207     return;
1208   }
1209   
1210   if(rank != root) {
1211     // Send buffer to root
1212     smpi_mpi_send(sendtmpbuf, count, datatype, root, system_tag, comm);
1213   } else {
1214     // FIXME: check for errors
1215     smpi_datatype_extent(datatype, &lb, &dataext);
1216     // Local copy from root
1217     if (sendtmpbuf && recvbuf)
1218       smpi_datatype_copy(sendtmpbuf, count, datatype, recvbuf, count, datatype);
1219     // Receive buffers from senders
1220     //TODO: make a MPI_barrier here ?
1221     requests = xbt_new(MPI_Request, size - 1);
1222     tmpbufs = xbt_new(void *, size - 1);
1223     index = 0;
1224     for(src = 0; src < size; src++) {
1225       if(src != root) {
1226         // FIXME: possibly overkill we we have contiguous/noncontiguous data
1227         //  mapping...
1228         tmpbufs[index] = xbt_malloc(count * dataext);
1229         requests[index] =
1230           smpi_irecv_init(tmpbufs[index], count, datatype, src,
1231                           system_tag, comm);
1232         index++;
1233       }
1234     }
1235     // Wait for completion of irecv's.
1236     smpi_mpi_startall(size - 1, requests);
1237     for(src = 0; src < size - 1; src++) {
1238       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1239       XBT_DEBUG("finished waiting any request with index %d", index);
1240       if(index == MPI_UNDEFINED) {
1241         break;
1242       }
1243       if(op) /* op can be MPI_OP_NULL that does nothing */
1244         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1245     }
1246     for(index = 0; index < size - 1; index++) {
1247       xbt_free(tmpbufs[index]);
1248     }
1249     xbt_free(tmpbufs);
1250     xbt_free(requests);
1251
1252     if( sendbuf == MPI_IN_PLACE ) {
1253       xbt_free(sendtmpbuf);
1254     }
1255   }
1256 }
1257
1258 void smpi_mpi_allreduce(void *sendbuf, void *recvbuf, int count,
1259                         MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1260 {
1261   smpi_mpi_reduce(sendbuf, recvbuf, count, datatype, op, 0, comm);
1262   smpi_mpi_bcast(recvbuf, count, datatype, 0, comm);
1263 }
1264
1265 void smpi_mpi_scan(void *sendbuf, void *recvbuf, int count,
1266                    MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1267 {
1268   int system_tag = -888;
1269   int rank, size, other, index;
1270   MPI_Aint lb = 0, dataext = 0;
1271   MPI_Request *requests;
1272   void **tmpbufs;
1273
1274   rank = smpi_comm_rank(comm);
1275   size = smpi_comm_size(comm);
1276
1277   // FIXME: check for errors
1278   smpi_datatype_extent(datatype, &lb, &dataext);
1279
1280   // Local copy from self
1281   smpi_datatype_copy(sendbuf, count, datatype, recvbuf, count, datatype);
1282
1283   // Send/Recv buffers to/from others;
1284   requests = xbt_new(MPI_Request, size - 1);
1285   tmpbufs = xbt_new(void *, rank);
1286   index = 0;
1287   for(other = 0; other < rank; other++) {
1288     // FIXME: possibly overkill we we have contiguous/noncontiguous data
1289     // mapping...
1290     tmpbufs[index] = xbt_malloc(count * dataext);
1291     requests[index] =
1292       smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag,
1293                       comm);
1294     index++;
1295   }
1296   for(other = rank + 1; other < size; other++) {
1297     requests[index] =
1298       smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1299     index++;
1300   }
1301   // Wait for completion of all comms.
1302   smpi_mpi_startall(size - 1, requests);
1303
1304   if(smpi_op_is_commute(op)){
1305     for(other = 0; other < size - 1; other++) {
1306       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1307       if(index == MPI_UNDEFINED) {
1308         break;
1309       }
1310       if(index < rank) {
1311         // #Request is below rank: it's a irecv
1312         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1313       }
1314     }
1315   }else{
1316     //non commutative case, wait in order
1317     for(other = 0; other < size - 1; other++) {
1318       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1319       if(index < rank) {
1320         smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1321       }
1322     }
1323   }
1324   for(index = 0; index < rank; index++) {
1325     xbt_free(tmpbufs[index]);
1326   }
1327   xbt_free(tmpbufs);
1328   xbt_free(requests);
1329 }
1330
1331 void smpi_mpi_exscan(void *sendbuf, void *recvbuf, int count,
1332                    MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1333 {
1334   int system_tag = -888;
1335   int rank, size, other, index;
1336   MPI_Aint lb = 0, dataext = 0;
1337   MPI_Request *requests;
1338   void **tmpbufs;
1339   int recvbuf_is_empty=1;
1340   rank = smpi_comm_rank(comm);
1341   size = smpi_comm_size(comm);
1342
1343   // FIXME: check for errors
1344   smpi_datatype_extent(datatype, &lb, &dataext);
1345
1346   // Send/Recv buffers to/from others;
1347   requests = xbt_new(MPI_Request, size - 1);
1348   tmpbufs = xbt_new(void *, rank);
1349   index = 0;
1350   for(other = 0; other < rank; other++) {
1351     // FIXME: possibly overkill we we have contiguous/noncontiguous data
1352     // mapping...
1353     tmpbufs[index] = xbt_malloc(count * dataext);
1354     requests[index] =
1355       smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag,
1356                       comm);
1357     index++;
1358   }
1359   for(other = rank + 1; other < size; other++) {
1360     requests[index] =
1361       smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1362     index++;
1363   }
1364   // Wait for completion of all comms.
1365   smpi_mpi_startall(size - 1, requests);
1366   if(smpi_op_is_commute(op)){
1367     for(other = 0; other < size - 1; other++) {
1368       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1369       if(index == MPI_UNDEFINED) {
1370         break;
1371       }
1372       if(index < rank) {
1373         if(recvbuf_is_empty){
1374           smpi_datatype_copy(tmpbufs[index], count, datatype, recvbuf, count, datatype);
1375           recvbuf_is_empty=0;
1376         }else
1377         // #Request is below rank: it's a irecv
1378         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1379       }
1380     }
1381   }else{
1382     //non commutative case, wait in order
1383     for(other = 0; other < size - 1; other++) {
1384       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1385       if(index < rank) {
1386           if(recvbuf_is_empty){
1387             smpi_datatype_copy(tmpbufs[other], count, datatype, recvbuf, count, datatype);
1388             recvbuf_is_empty=0;
1389           }else smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1390       }
1391     }
1392   }
1393   for(index = 0; index < rank; index++) {
1394     xbt_free(tmpbufs[index]);
1395   }
1396   xbt_free(tmpbufs);
1397   xbt_free(requests);
1398 }