Logo AND Algorithmique Numérique Distribuée

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