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