Logo AND Algorithmique Numérique Distribuée

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