Logo AND Algorithmique Numérique Distribuée

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