Logo AND Algorithmique Numérique Distribuée

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