Logo AND Algorithmique Numérique Distribuée

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