Logo AND Algorithmique Numérique Distribuée

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