Logo AND Algorithmique Numérique Distribuée

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