Logo AND Algorithmique Numérique Distribuée

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