Logo AND Algorithmique Numérique Distribuée

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