Logo AND Algorithmique Numérique Distribuée

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