Logo AND Algorithmique Numérique Distribuée

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