Logo AND Algorithmique Numérique Distribuée

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