Logo AND Algorithmique Numérique Distribuée

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