Logo AND Algorithmique Numérique Distribuée

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