Logo AND Algorithmique Numérique Distribuée

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