Logo AND Algorithmique Numérique Distribuée

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