Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
add minloc and maxloc for long_long
[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 = request->src;
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       XBT_DEBUG("Send request %p is detached", request);
377       request->refcount++;
378       if(request->old_type->has_subtype == 0){
379         oldbuf = request->buf;
380         if (!_xbt_replay_is_active() && oldbuf && request->size!=0){
381           if((smpi_privatize_global_variables)
382               && ((char*)request->buf >= start_data_exe)
383               && ((char*)request->buf < start_data_exe + size_data_exe )){
384             XBT_DEBUG("Privatization : We are sending from a zone inside global memory. Switch data segment ");
385             switch_data_segment(request->src);
386           }
387           buf = xbt_malloc(request->size);
388           memcpy(buf,oldbuf,request->size);
389           XBT_DEBUG("buf %p copied into %p",oldbuf,buf);
390         }
391       }
392     }
393
394     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
395     request->real_size=request->size;
396     smpi_datatype_use(request->old_type);
397     smpi_comm_use(request->comm);
398
399     //if we are giving back the control to the user without waiting for completion, we have to inject timings
400     double sleeptime = 0.0;
401     if(request->detached || (request->flags & (ISEND|SSEND))){// issend should be treated as isend
402       //isend and send timings may be different
403       sleeptime = (request->flags & ISEND)? smpi_ois(request->size) : smpi_os(request->size);
404     }
405
406     if(sleeptime != 0.0){
407         simcall_process_sleep(sleeptime);
408         XBT_DEBUG("sending size of %zu : sleep %f ", request->size, smpi_os(request->size));
409     }
410     request->action =
411       simcall_comm_isend(SIMIX_process_from_PID(request->src+1), mailbox, request->size, -1.0,
412                          buf, request->real_size,
413                          &match_send,
414                          &xbt_free_f, // how to free the userdata if a detached send fails
415                          &smpi_comm_copy_buffer_callback,
416                          request,
417                          // detach if msg size < eager/rdv switch limit
418                          request->detached);
419
420 #ifdef HAVE_TRACING
421     /* FIXME: detached sends are not traceable (request->action == NULL) */
422     if (request->action)
423       simcall_set_category(request->action, TRACE_internal_smpi_get_category());
424
425 #endif
426
427   }
428
429 }
430
431 void smpi_mpi_startall(int count, MPI_Request * requests)
432 {
433   int i;
434   if(requests==NULL) return;
435
436   for(i = 0; i < count; i++) {
437     smpi_mpi_start(requests[i]);
438   }
439 }
440
441 void smpi_mpi_request_free(MPI_Request * request)
442 {
443   if((*request) != MPI_REQUEST_NULL){
444     (*request)->refcount--;
445     if((*request)->refcount<0) xbt_die("wrong refcount");
446
447     if((*request)->refcount==0){
448         print_request("Destroying", (*request));
449         xbt_free(*request);
450         *request = MPI_REQUEST_NULL;
451     }else{
452         print_request("Decrementing", (*request));
453     }
454   }else{
455       xbt_die("freeing an already free request");
456   }
457 }
458
459
460 MPI_Request smpi_rma_send_init(void *buf, int count, MPI_Datatype datatype,
461                             int src, int dst, int tag, MPI_Comm comm, MPI_Op op)
462 {
463   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
464   if(op==MPI_OP_NULL){
465     request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf , count, datatype, src, dst, tag,
466                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED);
467   }else{
468     request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf, count, datatype,  src, dst, tag,
469                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED | ACCUMULATE);
470     request->op = op;
471   }
472   return request;
473 }
474
475 MPI_Request smpi_rma_recv_init(void *buf, int count, MPI_Datatype datatype,
476                             int src, int dst, int tag, MPI_Comm comm, MPI_Op op)
477 {
478   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
479   if(op==MPI_OP_NULL){
480     request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf, count, datatype,  src, dst, tag,
481                             comm, RMA | NON_PERSISTENT | RECV | PREPARED);
482   }else{
483     request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf, count, datatype,  src, dst, tag,
484                             comm, RMA | NON_PERSISTENT | RECV | PREPARED | ACCUMULATE);
485     request->op = op;
486   }
487   return request;
488 }
489
490
491 MPI_Request smpi_isend_init(void *buf, int count, MPI_Datatype datatype,
492                             int dst, int tag, MPI_Comm comm)
493 {
494   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
495   request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf , count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
496                           comm, PERSISTENT | ISEND | SEND | PREPARED);
497   return request;
498 }
499
500 MPI_Request smpi_mpi_isend(void *buf, int count, MPI_Datatype datatype,
501                            int dst, int tag, MPI_Comm comm)
502 {
503   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
504   request =  build_request(buf==MPI_BOTTOM?(void*)0:buf, count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
505                            comm, NON_PERSISTENT | ISEND | SEND);
506   smpi_mpi_start(request);
507   return request;
508 }
509
510 MPI_Request smpi_mpi_issend(void *buf, int count, MPI_Datatype datatype,
511                            int dst, int tag, MPI_Comm comm)
512 {
513   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
514   request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf, count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
515                           comm, NON_PERSISTENT | ISEND | SSEND | SEND);
516   smpi_mpi_start(request);
517   return request;
518 }
519
520 MPI_Request smpi_irecv_init(void *buf, int count, MPI_Datatype datatype,
521                             int src, int tag, MPI_Comm comm)
522 {
523   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
524   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,
525                           comm, PERSISTENT | RECV | PREPARED);
526   return request;
527 }
528
529 MPI_Request smpi_mpi_irecv(void *buf, int count, MPI_Datatype datatype,
530                            int src, int tag, MPI_Comm comm)
531 {
532   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
533   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,
534                           comm, NON_PERSISTENT | RECV);
535   smpi_mpi_start(request);
536   return request;
537 }
538
539 void smpi_mpi_recv(void *buf, int count, MPI_Datatype datatype, int src,
540                    int tag, MPI_Comm comm, MPI_Status * status)
541 {
542   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
543   request = smpi_mpi_irecv(buf, count, datatype, src, tag, comm);
544   smpi_mpi_wait(&request, status);
545   request = NULL;
546 }
547
548
549
550 void smpi_mpi_send(void *buf, int count, MPI_Datatype datatype, int dst,
551                    int tag, MPI_Comm comm)
552 {
553   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
554   request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf, count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
555                           comm, NON_PERSISTENT | SEND);
556
557   smpi_mpi_start(request);
558   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
559   request = NULL;
560 }
561
562 void smpi_mpi_ssend(void *buf, int count, MPI_Datatype datatype,
563                            int dst, int tag, MPI_Comm comm)
564 {
565   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
566   request = build_request(buf==MPI_BOTTOM ? (void*)0 : buf, count, datatype, smpi_process_index(), smpi_group_index(smpi_comm_group(comm), dst), tag,
567                 comm, NON_PERSISTENT | SSEND | SEND);
568
569   smpi_mpi_start(request);
570   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
571   request = NULL;
572 }
573
574 void smpi_mpi_sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,
575                        int dst, int sendtag, void *recvbuf, int recvcount,
576                        MPI_Datatype recvtype, int src, int recvtag,
577                        MPI_Comm comm, MPI_Status * status)
578 {
579   MPI_Request requests[2];
580   MPI_Status stats[2];
581   int myid=smpi_process_index();
582   if ((smpi_group_index(smpi_comm_group(comm), dst) == myid) && (smpi_group_index(smpi_comm_group(comm), src) == myid)) {
583       smpi_datatype_copy(sendbuf, sendcount, sendtype,
584                                      recvbuf, recvcount, recvtype);
585       return;
586   }
587   requests[0] =
588     smpi_isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
589   requests[1] =
590     smpi_irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
591   smpi_mpi_startall(2, requests);
592   smpi_mpi_waitall(2, requests, stats);
593   smpi_mpi_request_free(&requests[0]);
594   smpi_mpi_request_free(&requests[1]);
595   if(status != MPI_STATUS_IGNORE) {
596     // Copy receive status
597     *status = stats[1];
598   }
599 }
600
601 int smpi_mpi_get_count(MPI_Status * status, MPI_Datatype datatype)
602 {
603   return status->count / smpi_datatype_size(datatype);
604 }
605
606 static void finish_wait(MPI_Request * request, MPI_Status * status)
607 {
608   MPI_Request req = *request;
609   smpi_empty_status(status);
610
611   if(!(req->detached && req->flags & SEND)
612       && !(req->flags & PREPARED)){
613     if(status != MPI_STATUS_IGNORE) {
614       int src = req->src == MPI_ANY_SOURCE ? req->real_src : req->src;
615       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(req->comm), src);
616       status->MPI_TAG = req->tag == MPI_ANY_TAG ? req->real_tag : req->tag;
617       status->MPI_ERROR = req->truncated ? MPI_ERR_TRUNCATE : MPI_SUCCESS;
618       // this handles the case were size in receive differs from size in send
619       // FIXME: really this should just contain the count of receive-type blocks,
620       // right?
621       status->count = req->real_size;
622     }
623
624     print_request("Finishing", req);
625     MPI_Datatype datatype = req->old_type;
626
627     if((req->flags & ACCUMULATE) || (datatype->has_subtype == 1)){
628       if (!_xbt_replay_is_active()){
629         if( smpi_privatize_global_variables
630             && ((char*)req->old_buf >= start_data_exe)
631             && ((char*)req->old_buf < start_data_exe + size_data_exe )
632         ){
633             XBT_VERB("Privatization : We are unserializing to a zone in global memory - Switch data segment ");
634             switch_data_segment(smpi_process_index());
635         }
636       }
637       if(req->flags & RECV) {
638
639         if(datatype->has_subtype == 1){
640           // This part handles the problem of non-contignous memory
641           // the unserialization at the reception
642           s_smpi_subtype_t *subtype = datatype->substruct;
643             subtype->unserialize(req->buf, req->old_buf, req->real_size/smpi_datatype_size(datatype) , datatype->substruct, req->op);
644           if(req->detached == 0) free(req->buf);
645         }else{//apply op on contiguous buffer for accumulate
646             int n =req->real_size/smpi_datatype_size(datatype);
647             smpi_op_apply(req->op, req->buf, req->old_buf, &n, &datatype);
648         }
649       }
650     }
651     smpi_comm_unuse(req->comm);
652     smpi_datatype_unuse(datatype);
653
654   }
655
656 #ifdef HAVE_TRACING
657   if (TRACE_smpi_view_internals()) {
658     if(req->flags & RECV){
659       int rank = smpi_process_index();
660       int src_traced = (req->src == MPI_ANY_SOURCE ? req->real_src : req->src);
661       TRACE_smpi_recv(rank, src_traced, rank);
662     }
663   }
664 #endif
665
666   if(req->detached_sender!=NULL){
667     smpi_mpi_request_free(&(req->detached_sender));
668   }
669   if(req->flags & PERSISTENT)
670     req->action = NULL;
671   req->flags |= FINISHED;
672
673   smpi_mpi_request_free(request);
674
675 }
676
677 int smpi_mpi_test(MPI_Request * request, MPI_Status * status) {
678   int flag;
679
680   //assume that request is not MPI_REQUEST_NULL (filtered in PMPI_Test or smpi_mpi_testall before)
681   smpi_empty_status(status);
682   flag = 1;
683   if (!((*request)->flags & PREPARED)) {
684     if ((*request)->action != NULL)
685       flag = simcall_comm_test((*request)->action);
686     if (flag) {
687       finish_wait(request, status);
688       if (*request != MPI_REQUEST_NULL && !((*request)->flags & PERSISTENT))
689       *request = MPI_REQUEST_NULL;
690     }
691   }
692   return flag;
693 }
694
695 int smpi_mpi_testany(int count, MPI_Request requests[], int *index,
696                      MPI_Status * status)
697 {
698   xbt_dynar_t comms;
699   int i, flag, size;
700   int* map;
701
702   *index = MPI_UNDEFINED;
703   flag = 0;
704   comms = xbt_dynar_new(sizeof(smx_action_t), NULL);
705   map = xbt_new(int, count);
706   size = 0;
707   for(i = 0; i < count; i++) {
708     if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->action &&
709         !(requests[i]->flags & PREPARED)) {
710        xbt_dynar_push(comms, &requests[i]->action);
711        map[size] = i;
712        size++;
713     }
714   }
715   if(size > 0) {
716     i = simcall_comm_testany(comms);
717     // not MPI_UNDEFINED, as this is a simix return code
718     if(i != -1) {
719       *index = map[i];
720       finish_wait(&requests[*index], status);
721       if (requests[*index] != MPI_REQUEST_NULL && (requests[*index]->flags & NON_PERSISTENT))
722       requests[*index] = MPI_REQUEST_NULL;
723       flag = 1;
724     }
725   }else{
726       //all requests are null or inactive, return true
727       flag=1;
728       smpi_empty_status(status);
729   }
730   xbt_free(map);
731   xbt_dynar_free(&comms);
732
733   return flag;
734 }
735
736
737 int smpi_mpi_testall(int count, MPI_Request requests[],
738                      MPI_Status status[])
739 {
740   MPI_Status stat;
741   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
742   int flag=1;
743   int i;
744   for(i=0; i<count; i++){
745     if (requests[i] != MPI_REQUEST_NULL && !(requests[i]->flags & PREPARED)) {
746       if (smpi_mpi_test(&requests[i], pstat)!=1){
747         flag=0;
748       }else{
749           requests[i]=MPI_REQUEST_NULL;
750       }
751     }else{
752       smpi_empty_status(pstat);
753     }
754     if(status != MPI_STATUSES_IGNORE) {
755       status[i] = *pstat;
756     }
757   }
758   return flag;
759 }
760
761 void smpi_mpi_probe(int source, int tag, MPI_Comm comm, MPI_Status* status){
762   int flag=0;
763   //FIXME find another wait to avoid busy waiting ?
764   // the issue here is that we have to wait on a nonexistent comm
765   while(flag==0){
766     smpi_mpi_iprobe(source, tag, comm, &flag, status);
767     XBT_DEBUG("Busy Waiting on probing : %d", flag);
768   }
769 }
770
771 void smpi_mpi_iprobe(int source, int tag, MPI_Comm comm, int* flag, MPI_Status* status){
772
773   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,
774             comm, PERSISTENT | RECV);
775
776   //to avoid deadlock, we have to sleep some time here, or the timer won't advance and we will only do iprobe simcalls
777   double sleeptime= sg_cfg_get_double("smpi/iprobe");
778   //multiplier to the sleeptime, to increase speed of execution, each failed iprobe will increase it
779   static int nsleeps = 1;
780
781   simcall_process_sleep(sleeptime);
782
783   // behave like a receive, but don't do it
784   smx_rdv_t mailbox;
785
786   print_request("New iprobe", request);
787   // We have to test both mailboxes as we don't know if we will receive one one or another
788     if (sg_cfg_get_int("smpi/async_small_thres")>0){
789         mailbox = smpi_process_mailbox_small();
790         XBT_DEBUG("trying to probe the perm recv mailbox");
791         request->action = simcall_comm_iprobe(mailbox, request->src, request->tag, &match_recv, (void*)request);
792     }
793     if (request->action==NULL){
794         mailbox = smpi_process_mailbox();
795         XBT_DEBUG("trying to probe the other mailbox");
796         request->action = simcall_comm_iprobe(mailbox, request->src, request->tag, &match_recv, (void*)request);
797     }
798
799   if(request->action){
800     MPI_Request req = (MPI_Request)SIMIX_comm_get_src_data(request->action);
801     *flag = 1;
802     if(status != MPI_STATUS_IGNORE && !(req->flags & PREPARED)) {
803       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(comm), req->src);
804       status->MPI_TAG = req->tag;
805       status->MPI_ERROR = MPI_SUCCESS;
806       status->count = req->real_size;
807     }
808     nsleeps=1;//reset the number of sleeps we will do next time
809   }
810   else {
811       *flag = 0;
812       nsleeps++;
813   }
814   smpi_mpi_request_free(&request);
815
816   return;
817 }
818
819 void smpi_mpi_wait(MPI_Request * request, MPI_Status * status)
820 {
821   print_request("Waiting", *request);
822   if ((*request)->flags & PREPARED) {
823     smpi_empty_status(status);
824     return;
825   }
826
827   if ((*request)->action != NULL) { // this is not a detached send
828     simcall_comm_wait((*request)->action, -1.0);
829 #ifdef HAVE_MC
830   if(MC_is_active() && (*request)->action)
831     (*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
832 #endif
833   }
834
835   finish_wait(request, status);
836   if (*request != MPI_REQUEST_NULL && ((*request)->flags & NON_PERSISTENT))
837       *request = MPI_REQUEST_NULL;
838   // FIXME for a detached send, finish_wait is not called:
839 }
840
841 int smpi_mpi_waitany(int count, MPI_Request requests[],
842                      MPI_Status * status)
843 {
844   xbt_dynar_t comms;
845   int i, size, index;
846   int *map;
847
848   index = MPI_UNDEFINED;
849   if(count > 0) {
850     // Wait for a request to complete
851     comms = xbt_dynar_new(sizeof(smx_action_t), NULL);
852     map = xbt_new(int, count);
853     size = 0;
854     XBT_DEBUG("Wait for one of %d", count);
855     for(i = 0; i < count; i++) {
856       if (requests[i] != MPI_REQUEST_NULL
857           && !(requests[i]->flags & PREPARED)
858           && !(requests[i]->flags & FINISHED)) {
859         if (requests[i]->action != NULL) {
860           XBT_DEBUG("Waiting any %p ", requests[i]);
861           xbt_dynar_push(comms, &requests[i]->action);
862           map[size] = i;
863           size++;
864         }else{
865          //This is a finished detached request, let's return this one
866          size=0;//so we free the dynar but don't do the waitany call
867          index=i;
868          finish_wait(&requests[i], status);//cleanup if refcount = 0
869          if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
870          requests[i]=MPI_REQUEST_NULL;//set to null
871          break;
872          }
873       }
874     }
875     if(size > 0) {
876       i = simcall_comm_waitany(comms);
877
878       // not MPI_UNDEFINED, as this is a simix return code
879       if (i != -1) {
880         index = map[i];
881         finish_wait(&requests[index], status);
882         if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
883         requests[index] = MPI_REQUEST_NULL;
884       }
885     }
886     xbt_free(map);
887     xbt_dynar_free(&comms);
888   }
889
890   if (index==MPI_UNDEFINED)
891     smpi_empty_status(status);
892
893   return index;
894 }
895
896 int smpi_mpi_waitall(int count, MPI_Request requests[],
897                       MPI_Status status[])
898 {
899   int  index, c;
900   MPI_Status stat;
901   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
902   int retvalue = MPI_SUCCESS;
903   //tag invalid requests in the set
904   if (status != MPI_STATUSES_IGNORE) {
905     for (c = 0; c < count; c++) {
906       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst == MPI_PROC_NULL ||
907           (requests[c]->flags & PREPARED)) {
908         smpi_empty_status(&status[c]);
909       } else if (requests[c]->src == MPI_PROC_NULL) {
910         smpi_empty_status(&status[c]);
911         status[c].MPI_SOURCE = MPI_PROC_NULL;
912       }
913     }
914   }
915   for(c = 0; c < count; c++) {
916
917     if (MC_is_active()) {
918       smpi_mpi_wait(&requests[c], pstat);
919       index = c;
920     } else {
921       index = smpi_mpi_waitany(count, requests, pstat);
922       if (index == MPI_UNDEFINED)
923         break;
924       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
925       requests[index]=MPI_REQUEST_NULL;
926     }
927     if (status != MPI_STATUSES_IGNORE) {
928       status[index] = *pstat;
929       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
930         retvalue = MPI_ERR_IN_STATUS;
931     }
932   }
933
934   return retvalue;
935 }
936
937 int smpi_mpi_waitsome(int incount, MPI_Request requests[], int *indices,
938                       MPI_Status status[])
939 {
940   int i, count, index;
941   MPI_Status stat;
942   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
943
944   count = 0;
945   for(i = 0; i < incount; i++)
946   {
947     index=smpi_mpi_waitany(incount, requests, pstat);
948     if(index!=MPI_UNDEFINED){
949       indices[count] = index;
950       count++;
951       if(status != MPI_STATUSES_IGNORE) {
952         status[index] = *pstat;
953       }
954      if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
955      requests[index]=MPI_REQUEST_NULL;
956     }else{
957       return MPI_UNDEFINED;
958     }
959   }
960   return count;
961 }
962
963 int smpi_mpi_testsome(int incount, MPI_Request requests[], int *indices,
964                       MPI_Status status[])
965 {
966   int i, count, count_dead;
967   MPI_Status stat;
968   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
969
970   count = 0;
971   count_dead = 0;
972   for(i = 0; i < incount; i++) {
973     if((requests[i] != MPI_REQUEST_NULL)) {
974       if(smpi_mpi_test(&requests[i], pstat)) {
975          indices[i] = 1;
976          count++;
977          if(status != MPI_STATUSES_IGNORE) {
978            status[i] = *pstat;
979          }
980          if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->flags & NON_PERSISTENT)
981          requests[i]=MPI_REQUEST_NULL;
982       }
983     }else{
984       count_dead++;
985     }
986   }
987   if(count_dead==incount)return MPI_UNDEFINED;
988   else return count;
989 }
990
991 void smpi_mpi_bcast(void *buf, int count, MPI_Datatype datatype, int root,
992                     MPI_Comm comm)
993 {
994   // arity=2: a binary tree, arity=4 seem to be a good setting (see P2P-MPI))
995   nary_tree_bcast(buf, count, datatype, root, comm, 4);
996 }
997
998 void smpi_mpi_barrier(MPI_Comm comm)
999 {
1000   // arity=2: a binary tree, arity=4 seem to be a good setting (see P2P-MPI))
1001   nary_tree_barrier(comm, 4);
1002 }
1003
1004 void smpi_mpi_gather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1005                      void *recvbuf, int recvcount, MPI_Datatype recvtype,
1006                      int root, MPI_Comm comm)
1007 {
1008   int system_tag = COLL_TAG_GATHER;
1009   int rank, size, src, index;
1010   MPI_Aint lb = 0, recvext = 0;
1011   MPI_Request *requests;
1012
1013   rank = smpi_comm_rank(comm);
1014   size = smpi_comm_size(comm);
1015   if(rank != root) {
1016     // Send buffer to root
1017     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1018   } else {
1019     // FIXME: check for errors
1020     smpi_datatype_extent(recvtype, &lb, &recvext);
1021     // Local copy from root
1022     smpi_datatype_copy(sendbuf, sendcount, sendtype,
1023                        (char *)recvbuf + root * recvcount * recvext, recvcount, recvtype);
1024     // Receive buffers from senders
1025     requests = xbt_new(MPI_Request, size - 1);
1026     index = 0;
1027     for(src = 0; src < size; src++) {
1028       if(src != root) {
1029         requests[index] = smpi_irecv_init((char *)recvbuf + src * recvcount * recvext,
1030                                           recvcount, recvtype,
1031                                           src, system_tag, comm);
1032         index++;
1033       }
1034     }
1035     // Wait for completion of irecv's.
1036     smpi_mpi_startall(size - 1, requests);
1037     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1038     for(src = 0; src < size-1; src++) {
1039       smpi_mpi_request_free(&requests[src]);
1040     }
1041     xbt_free(requests);
1042   }
1043 }
1044
1045
1046 void smpi_mpi_reduce_scatter(void *sendbuf, void *recvbuf, int *recvcounts,
1047                        MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1048 {
1049     int i, size, count;
1050     int *displs;
1051     int rank = smpi_process_index();
1052     void *tmpbuf;
1053
1054     /* arbitrarily choose root as rank 0 */
1055     size = smpi_comm_size(comm);
1056     count = 0;
1057     displs = xbt_new(int, size);
1058     for (i = 0; i < size; i++) {
1059       displs[i] = count;
1060       count += recvcounts[i];
1061     }
1062     tmpbuf=(void*)xbt_malloc(count*smpi_datatype_get_extent(datatype));
1063     mpi_coll_reduce_fun(sendbuf, tmpbuf, count, datatype, op, 0, comm);
1064     smpi_mpi_scatterv(tmpbuf, recvcounts, displs, datatype, recvbuf,
1065                       recvcounts[rank], datatype, 0, comm);
1066     xbt_free(displs);
1067     xbt_free(tmpbuf);
1068 }
1069
1070 void smpi_mpi_gatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1071                       void *recvbuf, int *recvcounts, int *displs,
1072                       MPI_Datatype recvtype, int root, MPI_Comm comm)
1073 {
1074   int system_tag = COLL_TAG_GATHERV;
1075   int rank, size, src, index;
1076   MPI_Aint lb = 0, recvext = 0;
1077   MPI_Request *requests;
1078
1079   rank = smpi_comm_rank(comm);
1080   size = smpi_comm_size(comm);
1081   if(rank != root) {
1082     // Send buffer to root
1083     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1084   } else {
1085     // FIXME: check for errors
1086     smpi_datatype_extent(recvtype, &lb, &recvext);
1087     // Local copy from root
1088     smpi_datatype_copy(sendbuf, sendcount, sendtype,
1089                        (char *)recvbuf + displs[root] * recvext,
1090                        recvcounts[root], recvtype);
1091     // Receive buffers from senders
1092     requests = xbt_new(MPI_Request, size - 1);
1093     index = 0;
1094     for(src = 0; src < size; src++) {
1095       if(src != root) {
1096         requests[index] =
1097           smpi_irecv_init((char *)recvbuf + displs[src] * recvext,
1098                           recvcounts[src], recvtype, src, system_tag, comm);
1099         index++;
1100       }
1101     }
1102     // Wait for completion of irecv's.
1103     smpi_mpi_startall(size - 1, requests);
1104     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1105     for(src = 0; src < size-1; src++) {
1106       smpi_mpi_request_free(&requests[src]);
1107     }
1108     xbt_free(requests);
1109   }
1110 }
1111
1112 void smpi_mpi_allgather(void *sendbuf, int sendcount,
1113                         MPI_Datatype sendtype, void *recvbuf,
1114                         int recvcount, MPI_Datatype recvtype,
1115                         MPI_Comm comm)
1116 {
1117   int system_tag = COLL_TAG_ALLGATHER;
1118   int rank, size, other, index;
1119   MPI_Aint lb = 0, recvext = 0;
1120   MPI_Request *requests;
1121
1122   rank = smpi_comm_rank(comm);
1123   size = smpi_comm_size(comm);
1124   // FIXME: check for errors
1125   smpi_datatype_extent(recvtype, &lb, &recvext);
1126   // Local copy from self
1127   smpi_datatype_copy(sendbuf, sendcount, sendtype,
1128                      (char *)recvbuf + rank * recvcount * recvext, recvcount,
1129                      recvtype);
1130   // Send/Recv buffers to/from others;
1131   requests = xbt_new(MPI_Request, 2 * (size - 1));
1132   index = 0;
1133   for(other = 0; other < size; other++) {
1134     if(other != rank) {
1135       requests[index] =
1136         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,
1137                         comm);
1138       index++;
1139       requests[index] = smpi_irecv_init((char *)recvbuf + other * recvcount * recvext,
1140                                         recvcount, recvtype, other,
1141                                         system_tag, comm);
1142       index++;
1143     }
1144   }
1145   // Wait for completion of all comms.
1146   smpi_mpi_startall(2 * (size - 1), requests);
1147   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1148   for(other = 0; other < 2*(size-1); other++) {
1149     smpi_mpi_request_free(&requests[other]);
1150   }
1151   xbt_free(requests);
1152 }
1153
1154 void smpi_mpi_allgatherv(void *sendbuf, int sendcount,
1155                          MPI_Datatype sendtype, void *recvbuf,
1156                          int *recvcounts, int *displs,
1157                          MPI_Datatype recvtype, MPI_Comm comm)
1158 {
1159   int system_tag = COLL_TAG_ALLGATHERV;
1160   int rank, size, other, index;
1161   MPI_Aint lb = 0, recvext = 0;
1162   MPI_Request *requests;
1163
1164   rank = smpi_comm_rank(comm);
1165   size = smpi_comm_size(comm);
1166   // FIXME: check for errors
1167   smpi_datatype_extent(recvtype, &lb, &recvext);
1168   // Local copy from self
1169   smpi_datatype_copy(sendbuf, sendcount, sendtype,
1170                      (char *)recvbuf + displs[rank] * recvext,
1171                      recvcounts[rank], recvtype);
1172   // Send buffers to others;
1173   requests = xbt_new(MPI_Request, 2 * (size - 1));
1174   index = 0;
1175   for(other = 0; other < size; other++) {
1176     if(other != rank) {
1177       requests[index] =
1178         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,
1179                         comm);
1180       index++;
1181       requests[index] =
1182         smpi_irecv_init((char *)recvbuf + displs[other] * recvext, recvcounts[other],
1183                         recvtype, other, system_tag, comm);
1184       index++;
1185     }
1186   }
1187   // Wait for completion of all comms.
1188   smpi_mpi_startall(2 * (size - 1), requests);
1189   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1190   for(other = 0; other < 2*(size-1); other++) {
1191     smpi_mpi_request_free(&requests[other]);
1192   }
1193   xbt_free(requests);
1194 }
1195
1196 void smpi_mpi_scatter(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1197                       void *recvbuf, int recvcount, MPI_Datatype recvtype,
1198                       int root, MPI_Comm comm)
1199 {
1200   int system_tag = COLL_TAG_SCATTER;
1201   int rank, size, dst, index;
1202   MPI_Aint lb = 0, sendext = 0;
1203   MPI_Request *requests;
1204
1205   rank = smpi_comm_rank(comm);
1206   size = smpi_comm_size(comm);
1207   if(rank != root) {
1208     // Recv buffer from root
1209     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm,
1210                   MPI_STATUS_IGNORE);
1211   } else {
1212     // FIXME: check for errors
1213     smpi_datatype_extent(sendtype, &lb, &sendext);
1214     // Local copy from root
1215     if(recvbuf!=MPI_IN_PLACE){
1216         smpi_datatype_copy((char *)sendbuf + root * sendcount * sendext,
1217                            sendcount, sendtype, recvbuf, recvcount, recvtype);
1218     }
1219     // Send buffers to receivers
1220     requests = xbt_new(MPI_Request, size - 1);
1221     index = 0;
1222     for(dst = 0; dst < size; dst++) {
1223       if(dst != root) {
1224         requests[index] = smpi_isend_init((char *)sendbuf + dst * sendcount * sendext,
1225                                           sendcount, sendtype, dst,
1226                                           system_tag, comm);
1227         index++;
1228       }
1229     }
1230     // Wait for completion of isend's.
1231     smpi_mpi_startall(size - 1, requests);
1232     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1233     for(dst = 0; dst < size-1; dst++) {
1234       smpi_mpi_request_free(&requests[dst]);
1235     }
1236     xbt_free(requests);
1237   }
1238 }
1239
1240 void smpi_mpi_scatterv(void *sendbuf, int *sendcounts, int *displs,
1241                        MPI_Datatype sendtype, void *recvbuf, int recvcount,
1242                        MPI_Datatype recvtype, int root, MPI_Comm comm)
1243 {
1244   int system_tag = COLL_TAG_SCATTERV;
1245   int rank, size, dst, index;
1246   MPI_Aint lb = 0, sendext = 0;
1247   MPI_Request *requests;
1248
1249   rank = smpi_comm_rank(comm);
1250   size = smpi_comm_size(comm);
1251   if(rank != root) {
1252     // Recv buffer from root
1253     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm,
1254                   MPI_STATUS_IGNORE);
1255   } else {
1256     // FIXME: check for errors
1257     smpi_datatype_extent(sendtype, &lb, &sendext);
1258     // Local copy from root
1259     if(recvbuf!=MPI_IN_PLACE){
1260       smpi_datatype_copy((char *)sendbuf + displs[root] * sendext, sendcounts[root],
1261                        sendtype, recvbuf, recvcount, recvtype);
1262     }
1263     // Send buffers to receivers
1264     requests = xbt_new(MPI_Request, size - 1);
1265     index = 0;
1266     for(dst = 0; dst < size; dst++) {
1267       if(dst != root) {
1268         requests[index] =
1269           smpi_isend_init((char *)sendbuf + displs[dst] * sendext, sendcounts[dst],
1270                           sendtype, dst, system_tag, comm);
1271         index++;
1272       }
1273     }
1274     // Wait for completion of isend's.
1275     smpi_mpi_startall(size - 1, requests);
1276     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1277     for(dst = 0; dst < size-1; dst++) {
1278       smpi_mpi_request_free(&requests[dst]);
1279     }
1280     xbt_free(requests);
1281   }
1282 }
1283
1284 void smpi_mpi_reduce(void *sendbuf, void *recvbuf, int count,
1285                      MPI_Datatype datatype, MPI_Op op, int root,
1286                      MPI_Comm comm)
1287 {
1288   int system_tag = COLL_TAG_REDUCE;
1289   int rank, size, src, index;
1290   MPI_Aint lb = 0, dataext = 0;
1291   MPI_Request *requests;
1292   void **tmpbufs;
1293
1294
1295   char* sendtmpbuf = (char*) sendbuf;
1296   if( sendbuf == MPI_IN_PLACE ) {
1297     sendtmpbuf = (char *)xbt_malloc(count*smpi_datatype_get_extent(datatype));
1298     smpi_datatype_copy(recvbuf, count, datatype,sendtmpbuf, count, datatype);
1299   }
1300
1301   rank = smpi_comm_rank(comm);
1302   size = smpi_comm_size(comm);
1303   //non commutative case, use a working algo from openmpi
1304   if(!smpi_op_is_commute(op)){
1305     smpi_coll_tuned_reduce_ompi_basic_linear(sendtmpbuf, recvbuf, count,
1306                      datatype, op, root, comm);
1307     return;
1308   }
1309   
1310   if(rank != root) {
1311     // Send buffer to root
1312     smpi_mpi_send(sendtmpbuf, count, datatype, root, system_tag, comm);
1313   } else {
1314     // FIXME: check for errors
1315     smpi_datatype_extent(datatype, &lb, &dataext);
1316     // Local copy from root
1317     if (sendtmpbuf && recvbuf)
1318       smpi_datatype_copy(sendtmpbuf, count, datatype, recvbuf, count, datatype);
1319     // Receive buffers from senders
1320     //TODO: make a MPI_barrier here ?
1321     requests = xbt_new(MPI_Request, size - 1);
1322     tmpbufs = xbt_new(void *, size - 1);
1323     index = 0;
1324     for(src = 0; src < size; src++) {
1325       if(src != root) {
1326         // FIXME: possibly overkill we we have contiguous/noncontiguous data
1327         //  mapping...
1328         tmpbufs[index] = xbt_malloc(count * dataext);
1329         requests[index] =
1330           smpi_irecv_init(tmpbufs[index], count, datatype, src,
1331                           system_tag, comm);
1332         index++;
1333       }
1334     }
1335     // Wait for completion of irecv's.
1336     smpi_mpi_startall(size - 1, requests);
1337     for(src = 0; src < size - 1; src++) {
1338       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1339       XBT_DEBUG("finished waiting any request with index %d", index);
1340       if(index == MPI_UNDEFINED) {
1341         break;
1342       }else{
1343         smpi_mpi_request_free(&requests[index]);
1344       }
1345       if(op) /* op can be MPI_OP_NULL that does nothing */
1346         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1347     }
1348     for(index = 0; index < size - 1; index++) {
1349       xbt_free(tmpbufs[index]);
1350     }
1351     xbt_free(tmpbufs);
1352     xbt_free(requests);
1353
1354     if( sendbuf == MPI_IN_PLACE ) {
1355       xbt_free(sendtmpbuf);
1356     }
1357   }
1358 }
1359
1360 void smpi_mpi_allreduce(void *sendbuf, void *recvbuf, int count,
1361                         MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1362 {
1363   smpi_mpi_reduce(sendbuf, recvbuf, count, datatype, op, 0, comm);
1364   smpi_mpi_bcast(recvbuf, count, datatype, 0, comm);
1365 }
1366
1367 void smpi_mpi_scan(void *sendbuf, void *recvbuf, int count,
1368                    MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1369 {
1370   int system_tag = -888;
1371   int rank, size, other, index;
1372   MPI_Aint lb = 0, dataext = 0;
1373   MPI_Request *requests;
1374   void **tmpbufs;
1375
1376   rank = smpi_comm_rank(comm);
1377   size = smpi_comm_size(comm);
1378
1379   // FIXME: check for errors
1380   smpi_datatype_extent(datatype, &lb, &dataext);
1381
1382   // Local copy from self
1383   smpi_datatype_copy(sendbuf, count, datatype, recvbuf, count, datatype);
1384
1385   // Send/Recv buffers to/from others;
1386   requests = xbt_new(MPI_Request, size - 1);
1387   tmpbufs = xbt_new(void *, rank);
1388   index = 0;
1389   for(other = 0; other < rank; other++) {
1390     // FIXME: possibly overkill we we have contiguous/noncontiguous data
1391     // mapping...
1392     tmpbufs[index] = xbt_malloc(count * dataext);
1393     requests[index] =
1394       smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag,
1395                       comm);
1396     index++;
1397   }
1398   for(other = rank + 1; other < size; other++) {
1399     requests[index] =
1400       smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1401     index++;
1402   }
1403   // Wait for completion of all comms.
1404   smpi_mpi_startall(size - 1, requests);
1405
1406   if(smpi_op_is_commute(op)){
1407     for(other = 0; other < size - 1; other++) {
1408       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1409       if(index == MPI_UNDEFINED) {
1410         break;
1411       }
1412       if(index < rank) {
1413         // #Request is below rank: it's a irecv
1414         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1415       }
1416     }
1417   }else{
1418     //non commutative case, wait in order
1419     for(other = 0; other < size - 1; other++) {
1420       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1421       if(index < rank) {
1422         smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1423       }
1424     }
1425   }
1426   for(index = 0; index < rank; index++) {
1427     xbt_free(tmpbufs[index]);
1428   }
1429   for(index = 0; index < size-1; index++) {
1430     smpi_mpi_request_free(&requests[index]);
1431   }
1432   xbt_free(tmpbufs);
1433   xbt_free(requests);
1434 }
1435
1436 void smpi_mpi_exscan(void *sendbuf, void *recvbuf, int count,
1437                    MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1438 {
1439   int system_tag = -888;
1440   int rank, size, other, index;
1441   MPI_Aint lb = 0, dataext = 0;
1442   MPI_Request *requests;
1443   void **tmpbufs;
1444   int recvbuf_is_empty=1;
1445   rank = smpi_comm_rank(comm);
1446   size = smpi_comm_size(comm);
1447
1448   // FIXME: check for errors
1449   smpi_datatype_extent(datatype, &lb, &dataext);
1450
1451   // Send/Recv buffers to/from others;
1452   requests = xbt_new(MPI_Request, size - 1);
1453   tmpbufs = xbt_new(void *, rank);
1454   index = 0;
1455   for(other = 0; other < rank; other++) {
1456     // FIXME: possibly overkill we we have contiguous/noncontiguous data
1457     // mapping...
1458     tmpbufs[index] = xbt_malloc(count * dataext);
1459     requests[index] =
1460       smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag,
1461                       comm);
1462     index++;
1463   }
1464   for(other = rank + 1; other < size; other++) {
1465     requests[index] =
1466       smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1467     index++;
1468   }
1469   // Wait for completion of all comms.
1470   smpi_mpi_startall(size - 1, requests);
1471   if(smpi_op_is_commute(op)){
1472     for(other = 0; other < size - 1; other++) {
1473       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1474       if(index == MPI_UNDEFINED) {
1475         break;
1476       }
1477       if(index < rank) {
1478         if(recvbuf_is_empty){
1479           smpi_datatype_copy(tmpbufs[index], count, datatype, recvbuf, count, datatype);
1480           recvbuf_is_empty=0;
1481         }else
1482         // #Request is below rank: it's a irecv
1483         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1484       }
1485     }
1486   }else{
1487     //non commutative case, wait in order
1488     for(other = 0; other < size - 1; other++) {
1489       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1490       if(index < rank) {
1491           if(recvbuf_is_empty){
1492             smpi_datatype_copy(tmpbufs[other], count, datatype, recvbuf, count, datatype);
1493             recvbuf_is_empty=0;
1494           }else smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1495       }
1496     }
1497   }
1498   for(index = 0; index < rank; index++) {
1499     xbt_free(tmpbufs[index]);
1500   }
1501   for(index = 0; index < size-1; index++) {
1502     smpi_mpi_request_free(&requests[index]);
1503   }
1504   xbt_free(tmpbufs);
1505   xbt_free(requests);
1506 }