Logo AND Algorithmique Numérique Distribuée

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