Logo AND Algorithmique Numérique Distribuée

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