Logo AND Algorithmique Numérique Distribuée

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