Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
19cd933b8443dceb0114ee297b1861b3dad0ca14
[simgrid.git] / src / smpi / smpi_base.c
1 /* Copyright (c) 2007, 2008, 2009, 2010. 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
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 == 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     return 1;
38   }else return 0;
39 }
40
41 static int match_send(void* a, void* b,smx_action_t ignored) {
42    MPI_Request ref = (MPI_Request)a;
43    MPI_Request req = (MPI_Request)b;
44    XBT_DEBUG("Trying to match a send of src %d against %d, tag %d against %d",ref->src,req->src, ref->tag, req->tag);
45    xbt_assert(ref, "Cannot match send against null reference");
46    xbt_assert(req, "Cannot match send against null request");
47
48    if((req->src == MPI_ANY_SOURCE || req->src == ref->src)
49              && (req->tag == MPI_ANY_TAG || req->tag == ref->tag))
50    {
51      if(req->src == MPI_ANY_SOURCE)req->real_src = ref->src;
52      if(req->tag == MPI_ANY_TAG)req->real_tag = ref->tag;
53      if(req->real_size < ref->real_size) req->truncated = 1;
54      if(ref->detached==1){
55          req->detached_sender=ref; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
56      }
57
58      return 1;
59    } else return 0;
60 }
61
62
63 typedef struct s_smpi_factor *smpi_factor_t;
64 typedef struct s_smpi_factor {
65   long factor;
66   int nb_values;
67   double values[4];//arbitrary set to 4
68 } s_smpi_factor_t;
69 xbt_dynar_t smpi_os_values = NULL;
70 xbt_dynar_t smpi_or_values = NULL;
71
72
73 // Methods used to parse and store the values for timing injections in smpi
74 // These are taken from surf/network.c and generalized to have more factors
75 // These methods should be merged with those in surf/network.c (moved somewhere in xbt ?)
76
77 static int factor_cmp(const void *pa, const void *pb)
78 {
79   return (((s_smpi_factor_t*)pa)->factor > ((s_smpi_factor_t*)pb)->factor);
80 }
81
82
83 static xbt_dynar_t parse_factor(const char *smpi_coef_string)
84 {
85   char *value = NULL;
86   unsigned int iter = 0;
87   s_smpi_factor_t fact;
88   int i=0;
89   xbt_dynar_t smpi_factor, radical_elements, radical_elements2 = NULL;
90
91   smpi_factor = xbt_dynar_new(sizeof(s_smpi_factor_t), NULL);
92   radical_elements = xbt_str_split(smpi_coef_string, ";");
93   xbt_dynar_foreach(radical_elements, iter, value) {
94     fact.nb_values=0;
95     radical_elements2 = xbt_str_split(value, ":");
96     if (xbt_dynar_length(radical_elements2) <2 || xbt_dynar_length(radical_elements2) > 5)
97       xbt_die("Malformed radical for smpi factor!");
98     for(i =0; i<xbt_dynar_length(radical_elements2);i++ ){
99         if (i==0){
100            fact.factor = atol(xbt_dynar_get_as(radical_elements2, i, char *));
101         }else{
102            fact.values[fact.nb_values] = atof(xbt_dynar_get_as(radical_elements2, i, char *));
103            fact.nb_values++;
104         }
105     }
106
107     xbt_dynar_push_as(smpi_factor, s_smpi_factor_t, fact);
108     XBT_DEBUG("smpi_factor:\t%ld : %d values, first: %f", fact.factor, fact.nb_values ,fact.values[0]);
109     xbt_dynar_free(&radical_elements2);
110   }
111   xbt_dynar_free(&radical_elements);
112   iter=0;
113   xbt_dynar_sort(smpi_factor, &factor_cmp);
114   xbt_dynar_foreach(smpi_factor, iter, fact) {
115     XBT_DEBUG("smpi_factor:\t%ld : %d values, first: %f", fact.factor, fact.nb_values ,fact.values[0]);
116   }
117   return smpi_factor;
118 }
119
120 static double smpi_os(double size)
121 {
122   if (!smpi_os_values)
123     smpi_os_values =
124         parse_factor(sg_cfg_get_string("smpi/os"));
125
126   unsigned int iter = 0;
127   s_smpi_factor_t fact;
128   double current=0.0;
129   xbt_dynar_foreach(smpi_os_values, iter, fact) {
130     if (size <= fact.factor) {
131         XBT_DEBUG("os : %lf <= %ld return %f", size, fact.factor, current);
132       return current;
133     }else{
134       current=fact.values[0]+fact.values[1]*size;
135     }
136   }
137   XBT_DEBUG("os : %lf > %ld return %f", size, fact.factor, current);
138
139   return current;
140 }
141
142 static double smpi_or(double size)
143 {
144   if (!smpi_or_values)
145     smpi_or_values =
146         parse_factor(sg_cfg_get_string("smpi/or"));
147
148   unsigned int iter = 0;
149   s_smpi_factor_t fact;
150   double current=0.0;
151   xbt_dynar_foreach(smpi_or_values, iter, fact) {
152     if (size <= fact.factor) {
153         XBT_DEBUG("or : %lf <= %ld return %f", size, fact.factor, current);
154       return current;
155     }else
156       current=fact.values[0]+fact.values[1]*size;
157   }
158   XBT_DEBUG("or : %lf > %ld return %f", size, fact.factor, current);
159
160   return current;
161 }
162
163 static MPI_Request build_request(void *buf, int count,
164                                  MPI_Datatype datatype, int src, int dst,
165                                  int tag, MPI_Comm comm, unsigned flags)
166 {
167   MPI_Request request;
168
169   void *old_buf = NULL;
170
171   request = xbt_new(s_smpi_mpi_request_t, 1);
172
173   s_smpi_subtype_t *subtype = datatype->substruct;
174
175   if(datatype->has_subtype == 1){
176     // This part handles the problem of non-contiguous memory
177     old_buf = buf;
178     buf = xbt_malloc(count*smpi_datatype_size(datatype));
179     if (flags & SEND) {
180       subtype->serialize(old_buf, buf, count, datatype->substruct);
181     }
182   }
183
184   request->buf = buf;
185   // This part handles the problem of non-contiguous memory (for the
186   // unserialisation at the reception)
187   request->old_buf = old_buf;
188   request->old_type = datatype;
189
190   request->size = smpi_datatype_size(datatype) * count;
191   request->src = src;
192   request->dst = dst;
193   request->tag = tag;
194   request->comm = comm;
195   request->action = NULL;
196   request->flags = flags;
197   request->detached = 0;
198   request->detached_sender = NULL;
199
200   request->truncated = 0;
201   request->real_size = 0;
202   request->real_tag = 0;
203
204   request->refcount=1;
205 #ifdef HAVE_TRACING
206   request->send = 0;
207   request->recv = 0;
208 #endif
209   if (flags & SEND) smpi_datatype_unuse(datatype);
210
211   return request;
212 }
213
214
215 void smpi_empty_status(MPI_Status * status) {
216   if(status != MPI_STATUS_IGNORE) {
217       status->MPI_SOURCE=MPI_ANY_SOURCE;
218       status->MPI_TAG=MPI_ANY_TAG;
219       status->count=0;
220   }
221 }
222
223 void smpi_action_trace_run(char *path)
224 {
225   char *name;
226   xbt_dynar_t todo;
227   xbt_dict_cursor_t cursor;
228
229   action_fp=NULL;
230   if (path) {
231     action_fp = fopen(path, "r");
232     xbt_assert(action_fp != NULL, "Cannot open %s: %s", path,
233                strerror(errno));
234   }
235
236   if (!xbt_dict_is_empty(action_queues)) {
237     XBT_WARN
238       ("Not all actions got consumed. If the simulation ended successfully (without deadlock), you may want to add new processes to your deployment file.");
239
240
241     xbt_dict_foreach(action_queues, cursor, name, todo) {
242       XBT_WARN("Still %lu actions for %s", xbt_dynar_length(todo), name);
243     }
244   }
245
246   if (path)
247     fclose(action_fp);
248   xbt_dict_free(&action_queues);
249   action_queues = xbt_dict_new_homogeneous(NULL);
250 }
251
252 static void smpi_mpi_request_free_voidp(void* request)
253 {
254   MPI_Request req = request;
255   smpi_mpi_request_free(&req);
256 }
257
258 /* MPI Low level calls */
259 MPI_Request smpi_mpi_send_init(void *buf, int count, MPI_Datatype datatype,
260                                int dst, int tag, MPI_Comm comm)
261 {
262   MPI_Request request =
263     build_request(buf, count, datatype, smpi_comm_rank(comm), dst, tag,
264                   comm, PERSISTENT | SEND);
265   request->refcount++;
266   return request;
267 }
268
269 MPI_Request smpi_mpi_ssend_init(void *buf, int count, MPI_Datatype datatype,
270                                int dst, int tag, MPI_Comm comm)
271 {
272   MPI_Request request =
273     build_request(buf, count, datatype, smpi_comm_rank(comm), dst, tag,
274                   comm, PERSISTENT | SSEND | SEND);
275   request->refcount++;
276   return request;
277 }
278
279 MPI_Request smpi_mpi_recv_init(void *buf, int count, MPI_Datatype datatype,
280                                int src, int tag, MPI_Comm comm)
281 {
282   MPI_Request request =
283     build_request(buf, count, datatype, src, smpi_comm_rank(comm), tag,
284                   comm, PERSISTENT | RECV);
285   request->refcount++;
286   return request;
287 }
288
289 void smpi_mpi_start(MPI_Request request)
290 {
291   smx_rdv_t mailbox;
292
293   xbt_assert(!request->action,
294              "Cannot (re)start a non-finished communication");
295   if(request->flags & RECV) {
296     print_request("New recv", request);
297     if (request->size < sg_cfg_get_int("smpi/async_small_thres"))
298       mailbox = smpi_process_mailbox_small();
299     else
300       mailbox = smpi_process_mailbox();
301     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
302     request->real_size=request->size;
303     smpi_datatype_use(request->old_type);
304     request->action = simcall_comm_irecv(mailbox, request->buf, &request->real_size, &match_recv, request);
305
306     double sleeptime = smpi_or(request->size);
307     if(sleeptime!=0.0){
308         simcall_process_sleep(sleeptime);
309         XBT_DEBUG("receiving size of %zu : sleep %lf ", request->size, smpi_or(request->size));
310     }
311
312   } else {
313
314     int receiver = smpi_group_index(smpi_comm_group(request->comm), request->dst);
315 /*    if(receiver == MPI_UNDEFINED) {*/
316 /*      XBT_WARN("Trying to send a message to a wrong rank");*/
317 /*      return;*/
318 /*    }*/
319     print_request("New send", request);
320     if (request->size < sg_cfg_get_int("smpi/async_small_thres")) { // eager mode
321       mailbox = smpi_process_remote_mailbox_small(receiver);
322     }else{
323       XBT_DEBUG("Send request %p is not in the permanent receive mailbox (buf: %p)",request,request->buf);
324       mailbox = smpi_process_remote_mailbox(receiver);
325     }
326     if ( (! (request->flags & SSEND)) && (request->size < sg_cfg_get_int("smpi/send_is_detached_thres"))) {
327       void *oldbuf = NULL;
328       request->detached = 1;
329       request->refcount++;
330       if(request->old_type->has_subtype == 0){
331         oldbuf = request->buf;
332         if (oldbuf){
333           request->buf = xbt_malloc(request->size);
334           memcpy(request->buf,oldbuf,request->size);
335         }
336       }
337       XBT_DEBUG("Send request %p is detached; buf %p copied into %p",request,oldbuf,request->buf);
338     }
339     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
340     request->real_size=request->size;
341     smpi_datatype_use(request->old_type);
342     double sleeptime = smpi_os(request->size);
343     if(sleeptime!=0.0){
344         simcall_process_sleep(sleeptime);
345         XBT_DEBUG("sending size of %zu : sleep %lf ", request->size, smpi_os(request->size));
346     }
347     request->action =
348       simcall_comm_isend(mailbox, request->size, -1.0,
349                          request->buf, request->real_size,
350                          &match_send,
351                          &smpi_mpi_request_free_voidp, // how to free the userdata if a detached send fails
352                          request,
353                          // detach if msg size < eager/rdv switch limit
354                          request->detached);
355
356 #ifdef HAVE_TRACING
357     /* FIXME: detached sends are not traceable (request->action == NULL) */
358     if (request->action)
359       simcall_set_category(request->action, TRACE_internal_smpi_get_category());
360 #endif
361
362   }
363
364 }
365
366 void smpi_mpi_startall(int count, MPI_Request * requests)
367 {
368   int i;
369
370   for(i = 0; i < count; i++) {
371     smpi_mpi_start(requests[i]);
372   }
373 }
374
375 void smpi_mpi_request_free(MPI_Request * request)
376 {
377
378   if((*request) != MPI_REQUEST_NULL){
379     (*request)->refcount--;
380     if((*request)->refcount<0) xbt_die("wrong refcount");
381
382     if((*request)->refcount==0){
383         xbt_free(*request);
384         *request = MPI_REQUEST_NULL;
385     }
386   }else{
387       xbt_die("freeing an already free request");
388   }
389 }
390
391 MPI_Request smpi_isend_init(void *buf, int count, MPI_Datatype datatype,
392                             int dst, int tag, MPI_Comm comm)
393 {
394   MPI_Request request =
395     build_request(buf, count, datatype, smpi_comm_rank(comm), dst, tag,
396                   comm, NON_PERSISTENT | SEND);
397
398   return request;
399 }
400
401 MPI_Request smpi_mpi_isend(void *buf, int count, MPI_Datatype datatype,
402                            int dst, int tag, MPI_Comm comm)
403 {
404   MPI_Request request =
405       build_request(buf, count, datatype, smpi_comm_rank(comm), dst, tag,
406                     comm, NON_PERSISTENT | ISEND | SEND);
407
408   smpi_mpi_start(request);
409   return request;
410 }
411
412 MPI_Request smpi_mpi_issend(void *buf, int count, MPI_Datatype datatype,
413                            int dst, int tag, MPI_Comm comm)
414 {
415   MPI_Request request =
416       build_request(buf, count, datatype, smpi_comm_rank(comm), dst, tag,
417                     comm, NON_PERSISTENT | ISEND | SSEND | SEND);
418   smpi_mpi_start(request);
419   return request;
420 }
421
422 MPI_Request smpi_mpi_ssend(void *buf, int count, MPI_Datatype datatype,
423                            int dst, int tag, MPI_Comm comm)
424 {
425   MPI_Request request = smpi_mpi_issend(buf, count, datatype, dst, tag, comm);
426   smpi_mpi_start(request);
427   return request;
428 }
429
430 MPI_Request smpi_irecv_init(void *buf, int count, MPI_Datatype datatype,
431                             int src, int tag, MPI_Comm comm)
432 {
433   MPI_Request request =
434     build_request(buf, count, datatype, src, smpi_comm_rank(comm), tag,
435                   comm, NON_PERSISTENT | RECV);
436   return request;
437 }
438
439 MPI_Request smpi_mpi_irecv(void *buf, int count, MPI_Datatype datatype,
440                            int src, int tag, MPI_Comm comm)
441 {
442   MPI_Request request =
443       build_request(buf, count, datatype, src, smpi_comm_rank(comm), tag,
444                     comm, NON_PERSISTENT | RECV);
445
446   smpi_mpi_start(request);
447   return request;
448 }
449
450 void smpi_mpi_recv(void *buf, int count, MPI_Datatype datatype, int src,
451                    int tag, MPI_Comm comm, MPI_Status * status)
452 {
453   MPI_Request request;
454   request = smpi_mpi_irecv(buf, count, datatype, src, tag, comm);
455   smpi_mpi_wait(&request, status);
456 }
457
458
459
460 void smpi_mpi_send(void *buf, int count, MPI_Datatype datatype, int dst,
461                    int tag, MPI_Comm comm)
462 {
463   MPI_Request request;
464   request = smpi_mpi_isend(buf, count, datatype, dst, tag, comm);
465   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
466
467 }
468
469 void smpi_mpi_sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,
470                        int dst, int sendtag, void *recvbuf, int recvcount,
471                        MPI_Datatype recvtype, int src, int recvtag,
472                        MPI_Comm comm, MPI_Status * status)
473 {
474   MPI_Request requests[2];
475   MPI_Status stats[2];
476
477   requests[0] =
478     smpi_isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
479   requests[1] =
480     smpi_irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
481   smpi_mpi_startall(2, requests);
482   smpi_mpi_waitall(2, requests, stats);
483   if(status != MPI_STATUS_IGNORE) {
484     // Copy receive status
485     memcpy(status, &stats[1], sizeof(MPI_Status));
486   }
487 }
488
489 int smpi_mpi_get_count(MPI_Status * status, MPI_Datatype datatype)
490 {
491   return status->count / smpi_datatype_size(datatype);
492 }
493
494 static void finish_wait(MPI_Request * request, MPI_Status * status)
495 {
496   MPI_Request req = *request;
497   if(!(req->detached && req->flags & SEND)){
498     if(status != MPI_STATUS_IGNORE) {
499       status->MPI_SOURCE = req->src == MPI_ANY_SOURCE ? req->real_src : req->src;
500       status->MPI_TAG = req->tag == MPI_ANY_TAG ? req->real_tag : req->tag;
501       if(req->truncated)
502       status->MPI_ERROR = MPI_ERR_TRUNCATE;
503       else status->MPI_ERROR = MPI_SUCCESS ;
504       // this handles the case were size in receive differs from size in send
505       // FIXME: really this should just contain the count of receive-type blocks,
506       // right?
507       status->count = req->real_size;
508     }
509
510     print_request("Finishing", req);
511     MPI_Datatype datatype = req->old_type;
512
513     if(datatype->has_subtype == 1){
514         // This part handles the problem of non-contignous memory
515         // the unserialization at the reception
516       s_smpi_subtype_t *subtype = datatype->substruct;
517       if(req->flags & RECV) {
518         subtype->unserialize(req->buf, req->old_buf, req->real_size/smpi_datatype_size(datatype) , datatype->substruct);
519       }
520       if(req->detached == 0) free(req->buf);
521     }
522     smpi_datatype_unuse(datatype);
523   }
524
525   if(req->detached_sender!=NULL){
526     smpi_mpi_request_free(&(req->detached_sender));
527   }
528
529   if(req->flags & NON_PERSISTENT) {
530     smpi_mpi_request_free(request);
531   } else {
532     req->action = NULL;
533   }
534 }
535
536 int smpi_mpi_test(MPI_Request * request, MPI_Status * status) {
537   int flag;
538
539   //assume that request is not MPI_REQUEST_NULL (filtered in PMPI_Test or smpi_mpi_testall before)
540   if ((*request)->action == NULL)
541     flag = 1;
542   else
543     flag = simcall_comm_test((*request)->action);
544   if(flag) {
545     (*request)->refcount++;
546     finish_wait(request, status);
547   }else{
548     smpi_empty_status(status);
549   }
550   return flag;
551 }
552
553 int smpi_mpi_testany(int count, MPI_Request requests[], int *index,
554                      MPI_Status * status)
555 {
556   xbt_dynar_t comms;
557   int i, flag, size;
558   int* map;
559
560   *index = MPI_UNDEFINED;
561   flag = 0;
562   if(count > 0) {
563     comms = xbt_dynar_new(sizeof(smx_action_t), NULL);
564     map = xbt_new(int, count);
565     size = 0;
566     for(i = 0; i < count; i++) {
567       if((requests[i]!=MPI_REQUEST_NULL) && requests[i]->action) {
568          xbt_dynar_push(comms, &requests[i]->action);
569          map[size] = i;
570          size++;
571       }
572     }
573     if(size > 0) {
574       i = simcall_comm_testany(comms);
575       // not MPI_UNDEFINED, as this is a simix return code
576       if(i != -1) {
577         *index = map[i];
578         finish_wait(&requests[*index], status);
579         flag = 1;
580       }
581     }else{
582         //all requests are null or inactive, return true
583         flag=1;
584         smpi_empty_status(status);
585     }
586     xbt_free(map);
587     xbt_dynar_free(&comms);
588   }
589
590   return flag;
591 }
592
593
594 int smpi_mpi_testall(int count, MPI_Request requests[],
595                      MPI_Status status[])
596 {
597   MPI_Status stat;
598   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
599   int flag=1;
600   int i;
601   for(i=0; i<count; i++){
602     if(requests[i]!= MPI_REQUEST_NULL){
603       if (smpi_mpi_test(&requests[i], pstat)!=1){
604         flag=0;
605       }
606     }else{
607       smpi_empty_status(pstat);
608     }
609     if(status != MPI_STATUSES_IGNORE) {
610       memcpy(&status[i], pstat, sizeof(*pstat));
611     }
612   }
613   return flag;
614 }
615
616 void smpi_mpi_probe(int source, int tag, MPI_Comm comm, MPI_Status* status){
617   int flag=0;
618   //FIXME find another wait to avoid busy waiting ?
619   // the issue here is that we have to wait on a nonexistent comm
620   while(flag==0){
621     smpi_mpi_iprobe(source, tag, comm, &flag, status);
622     XBT_DEBUG("Busy Waiting on probing : %d", flag);
623     if(!flag) {
624       simcall_process_sleep(0.0001);
625     }
626   }
627 }
628
629 void smpi_mpi_iprobe(int source, int tag, MPI_Comm comm, int* flag, MPI_Status* status){
630   MPI_Request request =build_request(NULL, 0, MPI_CHAR, source, smpi_comm_rank(comm), tag,
631             comm, NON_PERSISTENT | RECV);
632
633   // behave like a receive, but don't do it
634   smx_rdv_t mailbox;
635
636   print_request("New iprobe", request);
637   // We have to test both mailboxes as we don't know if we will receive one one or another
638     if (sg_cfg_get_int("smpi/async_small_thres")>0){
639         mailbox = smpi_process_mailbox_small();
640         XBT_DEBUG("trying to probe the perm recv mailbox");
641         request->action = simcall_comm_iprobe(mailbox, request->src, request->tag, &match_recv, (void*)request);
642     }
643     if (request->action==NULL){
644         mailbox = smpi_process_mailbox();
645         XBT_DEBUG("trying to probe the other mailbox");
646         request->action = simcall_comm_iprobe(mailbox, request->src, request->tag, &match_recv, (void*)request);
647     }
648
649   if(request->action){
650     MPI_Request req = (MPI_Request)SIMIX_comm_get_src_data(request->action);
651     *flag = 1;
652     if(status != MPI_STATUS_IGNORE) {
653       status->MPI_SOURCE = req->src;
654       status->MPI_TAG = req->tag;
655       status->MPI_ERROR = MPI_SUCCESS;
656       status->count = req->real_size;
657     }
658   }
659   else *flag = 0;
660   smpi_mpi_request_free(&request);
661
662   return;
663 }
664
665 void smpi_mpi_wait(MPI_Request * request, MPI_Status * status)
666 {
667   print_request("Waiting", *request);
668   if ((*request)->action != NULL) { // this is not a detached send
669     simcall_comm_wait((*request)->action, -1.0);
670   }
671   finish_wait(request, status);
672
673   // FIXME for a detached send, finish_wait is not called:
674 }
675
676 int smpi_mpi_waitany(int count, MPI_Request requests[],
677                      MPI_Status * status)
678 {
679   xbt_dynar_t comms;
680   int i, size, index;
681   int *map;
682
683   index = MPI_UNDEFINED;
684   if(count > 0) {
685     // Wait for a request to complete
686     comms = xbt_dynar_new(sizeof(smx_action_t), NULL);
687     map = xbt_new(int, count);
688     size = 0;
689     XBT_DEBUG("Wait for one of %d", count);
690     for(i = 0; i < count; i++) {
691       if(requests[i] != MPI_REQUEST_NULL) {
692         if (requests[i]->action != NULL) {
693           XBT_DEBUG("Waiting any %p ", requests[i]);
694           xbt_dynar_push(comms, &requests[i]->action);
695           map[size] = i;
696           size++;
697         }else{
698          //This is a finished detached request, let's return this one
699          size=0;//so we free the dynar but don't do the waitany call
700          index=i;
701          finish_wait(&requests[i], status);//cleanup if refcount = 0
702          requests[i]=MPI_REQUEST_NULL;//set to null
703          break;
704          }
705       }
706     }
707     if(size > 0) {
708       i = simcall_comm_waitany(comms);
709
710       // not MPI_UNDEFINED, as this is a simix return code
711       if (i != -1) {
712         index = map[i];
713         finish_wait(&requests[index], status);
714       }
715     }
716     xbt_free(map);
717     xbt_dynar_free(&comms);
718   }
719
720   if (index==MPI_UNDEFINED)
721     smpi_empty_status(status);
722
723   return index;
724 }
725
726 int smpi_mpi_waitall(int count, MPI_Request requests[],
727                       MPI_Status status[])
728 {
729   int  index, c;
730   MPI_Status stat;
731   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
732   int retvalue=MPI_SUCCESS;
733   //tag invalid requests in the set
734   for(c = 0; c < count; c++) {
735     if(requests[c]==MPI_REQUEST_NULL || requests[c]->dst == MPI_PROC_NULL ){
736       if(status != MPI_STATUSES_IGNORE)
737         smpi_empty_status(&status[c]);
738     }else if(requests[c]->src == MPI_PROC_NULL ){
739       if(status != MPI_STATUSES_IGNORE) {
740         smpi_empty_status(&status[c]);
741         status[c].MPI_SOURCE=MPI_PROC_NULL;
742       }
743     }
744   }
745   for(c = 0; c < count; c++) {
746       if(MC_is_active()) {
747         smpi_mpi_wait(&requests[c], pstat);
748         index = c;
749       } else {
750         index = smpi_mpi_waitany(count, requests, pstat);
751         if(index == MPI_UNDEFINED) {
752           break;
753        }
754       if(status != MPI_STATUSES_IGNORE) {
755         memcpy(&status[index], pstat, sizeof(*pstat));
756         if(status[index].MPI_ERROR==MPI_ERR_TRUNCATE)retvalue=MPI_ERR_IN_STATUS;
757
758       }
759     }
760   }
761
762   return retvalue;
763 }
764
765 int smpi_mpi_waitsome(int incount, MPI_Request requests[], int *indices,
766                       MPI_Status status[])
767 {
768   int i, count, index;
769   MPI_Status stat;
770   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
771
772   count = 0;
773   for(i = 0; i < incount; i++)
774   {
775     index=smpi_mpi_waitany(incount, requests, pstat);
776     if(index!=MPI_UNDEFINED){
777       indices[count] = index;
778       count++;
779       if(status != MPI_STATUSES_IGNORE) {
780         memcpy(&status[index], pstat, sizeof(*pstat));
781       }
782     }else{
783       return MPI_UNDEFINED;
784     }
785   }
786   return count;
787 }
788
789 int smpi_mpi_testsome(int incount, MPI_Request requests[], int *indices,
790                       MPI_Status status[])
791 {
792   int i, count, count_dead;
793   MPI_Status stat;
794   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
795
796   count = 0;
797   count_dead = 0;
798   for(i = 0; i < incount; i++) {
799     if((requests[i] != MPI_REQUEST_NULL)) {
800       if(smpi_mpi_test(&requests[i], pstat)) {
801          indices[count] = i;
802          count++;
803          if(status != MPI_STATUSES_IGNORE) {
804             memcpy(&status[i], pstat, sizeof(*pstat));
805          }
806       }
807     }else{
808       count_dead++;
809     }
810   }
811   if(count_dead==incount)return MPI_UNDEFINED;
812   else return count;
813 }
814
815 void smpi_mpi_bcast(void *buf, int count, MPI_Datatype datatype, int root,
816                     MPI_Comm comm)
817 {
818   // arity=2: a binary tree, arity=4 seem to be a good setting (see P2P-MPI))
819   nary_tree_bcast(buf, count, datatype, root, comm, 4);
820 }
821
822 void smpi_mpi_barrier(MPI_Comm comm)
823 {
824   // arity=2: a binary tree, arity=4 seem to be a good setting (see P2P-MPI))
825   nary_tree_barrier(comm, 4);
826 }
827
828 void smpi_mpi_gather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
829                      void *recvbuf, int recvcount, MPI_Datatype recvtype,
830                      int root, MPI_Comm comm)
831 {
832   int system_tag = 666;
833   int rank, size, src, index;
834   MPI_Aint lb = 0, recvext = 0;
835   MPI_Request *requests;
836
837   rank = smpi_comm_rank(comm);
838   size = smpi_comm_size(comm);
839   if(rank != root) {
840     // Send buffer to root
841     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
842   } else {
843     // FIXME: check for errors
844     smpi_datatype_extent(recvtype, &lb, &recvext);
845     // Local copy from root
846     smpi_datatype_copy(sendbuf, sendcount, sendtype,
847                        (char *)recvbuf + root * recvcount * recvext, recvcount, recvtype);
848     // Receive buffers from senders
849     requests = xbt_new(MPI_Request, size - 1);
850     index = 0;
851     for(src = 0; src < size; src++) {
852       if(src != root) {
853         requests[index] = smpi_irecv_init((char *)recvbuf + src * recvcount * recvext,
854                                           recvcount, recvtype,
855                                           src, system_tag, comm);
856         index++;
857       }
858     }
859     // Wait for completion of irecv's.
860     smpi_mpi_startall(size - 1, requests);
861     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
862     xbt_free(requests);
863   }
864 }
865
866 void smpi_mpi_gatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype,
867                       void *recvbuf, int *recvcounts, int *displs,
868                       MPI_Datatype recvtype, int root, MPI_Comm comm)
869 {
870   int system_tag = 666;
871   int rank, size, src, index;
872   MPI_Aint lb = 0, recvext = 0;
873   MPI_Request *requests;
874
875   rank = smpi_comm_rank(comm);
876   size = smpi_comm_size(comm);
877   if(rank != root) {
878     // Send buffer to root
879     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
880   } else {
881     // FIXME: check for errors
882     smpi_datatype_extent(recvtype, &lb, &recvext);
883     // Local copy from root
884     smpi_datatype_copy(sendbuf, sendcount, sendtype,
885                        (char *)recvbuf + displs[root] * recvext,
886                        recvcounts[root], recvtype);
887     // Receive buffers from senders
888     requests = xbt_new(MPI_Request, size - 1);
889     index = 0;
890     for(src = 0; src < size; src++) {
891       if(src != root) {
892         requests[index] =
893           smpi_irecv_init((char *)recvbuf + displs[src] * recvext,
894                           recvcounts[src], recvtype, src, system_tag, comm);
895         index++;
896       }
897     }
898     // Wait for completion of irecv's.
899     smpi_mpi_startall(size - 1, requests);
900     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
901     xbt_free(requests);
902   }
903 }
904
905 void smpi_mpi_allgather(void *sendbuf, int sendcount,
906                         MPI_Datatype sendtype, void *recvbuf,
907                         int recvcount, MPI_Datatype recvtype,
908                         MPI_Comm comm)
909 {
910   int system_tag = 666;
911   int rank, size, other, index;
912   MPI_Aint lb = 0, recvext = 0;
913   MPI_Request *requests;
914
915   rank = smpi_comm_rank(comm);
916   size = smpi_comm_size(comm);
917   // FIXME: check for errors
918   smpi_datatype_extent(recvtype, &lb, &recvext);
919   // Local copy from self
920   smpi_datatype_copy(sendbuf, sendcount, sendtype,
921                      (char *)recvbuf + rank * recvcount * recvext, recvcount,
922                      recvtype);
923   // Send/Recv buffers to/from others;
924   requests = xbt_new(MPI_Request, 2 * (size - 1));
925   index = 0;
926   for(other = 0; other < size; other++) {
927     if(other != rank) {
928       requests[index] =
929         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,
930                         comm);
931       index++;
932       requests[index] = smpi_irecv_init((char *)recvbuf + other * recvcount * recvext,
933                                         recvcount, recvtype, other,
934                                         system_tag, comm);
935       index++;
936     }
937   }
938   // Wait for completion of all comms.
939   smpi_mpi_startall(2 * (size - 1), requests);
940   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
941   xbt_free(requests);
942 }
943
944 void smpi_mpi_allgatherv(void *sendbuf, int sendcount,
945                          MPI_Datatype sendtype, void *recvbuf,
946                          int *recvcounts, int *displs,
947                          MPI_Datatype recvtype, MPI_Comm comm)
948 {
949   int system_tag = 666;
950   int rank, size, other, index;
951   MPI_Aint lb = 0, recvext = 0;
952   MPI_Request *requests;
953
954   rank = smpi_comm_rank(comm);
955   size = smpi_comm_size(comm);
956   // FIXME: check for errors
957   smpi_datatype_extent(recvtype, &lb, &recvext);
958   // Local copy from self
959   smpi_datatype_copy(sendbuf, sendcount, sendtype,
960                      (char *)recvbuf + displs[rank] * recvext,
961                      recvcounts[rank], recvtype);
962   // Send buffers to others;
963   requests = xbt_new(MPI_Request, 2 * (size - 1));
964   index = 0;
965   for(other = 0; other < size; other++) {
966     if(other != rank) {
967       requests[index] =
968         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,
969                         comm);
970       index++;
971       requests[index] =
972         smpi_irecv_init((char *)recvbuf + displs[other] * recvext, recvcounts[other],
973                         recvtype, other, system_tag, comm);
974       index++;
975     }
976   }
977   // Wait for completion of all comms.
978   smpi_mpi_startall(2 * (size - 1), requests);
979   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
980   xbt_free(requests);
981 }
982
983 void smpi_mpi_scatter(void *sendbuf, int sendcount, MPI_Datatype sendtype,
984                       void *recvbuf, int recvcount, MPI_Datatype recvtype,
985                       int root, MPI_Comm comm)
986 {
987   int system_tag = 666;
988   int rank, size, dst, index;
989   MPI_Aint lb = 0, sendext = 0;
990   MPI_Request *requests;
991
992   rank = smpi_comm_rank(comm);
993   size = smpi_comm_size(comm);
994   if(rank != root) {
995     // Recv buffer from root
996     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm,
997                   MPI_STATUS_IGNORE);
998   } else {
999     // FIXME: check for errors
1000     smpi_datatype_extent(sendtype, &lb, &sendext);
1001     // Local copy from root
1002     smpi_datatype_copy((char *)sendbuf + root * sendcount * sendext,
1003                        sendcount, sendtype, recvbuf, recvcount, recvtype);
1004     // Send buffers to receivers
1005     requests = xbt_new(MPI_Request, size - 1);
1006     index = 0;
1007     for(dst = 0; dst < size; dst++) {
1008       if(dst != root) {
1009         requests[index] = smpi_isend_init((char *)sendbuf + dst * sendcount * sendext,
1010                                           sendcount, sendtype, dst,
1011                                           system_tag, comm);
1012         index++;
1013       }
1014     }
1015     // Wait for completion of isend's.
1016     smpi_mpi_startall(size - 1, requests);
1017     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1018     xbt_free(requests);
1019   }
1020 }
1021
1022 void smpi_mpi_scatterv(void *sendbuf, int *sendcounts, int *displs,
1023                        MPI_Datatype sendtype, void *recvbuf, int recvcount,
1024                        MPI_Datatype recvtype, int root, MPI_Comm comm)
1025 {
1026   int system_tag = 666;
1027   int rank, size, dst, index;
1028   MPI_Aint lb = 0, sendext = 0;
1029   MPI_Request *requests;
1030
1031   rank = smpi_comm_rank(comm);
1032   size = smpi_comm_size(comm);
1033   if(rank != root) {
1034     // Recv buffer from root
1035     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm,
1036                   MPI_STATUS_IGNORE);
1037   } else {
1038     // FIXME: check for errors
1039     smpi_datatype_extent(sendtype, &lb, &sendext);
1040     // Local copy from root
1041     smpi_datatype_copy((char *)sendbuf + displs[root] * sendext, sendcounts[root],
1042                        sendtype, recvbuf, recvcount, recvtype);
1043     // Send buffers to receivers
1044     requests = xbt_new(MPI_Request, size - 1);
1045     index = 0;
1046     for(dst = 0; dst < size; dst++) {
1047       if(dst != root) {
1048         requests[index] =
1049           smpi_isend_init((char *)sendbuf + displs[dst] * sendext, sendcounts[dst],
1050                           sendtype, dst, system_tag, comm);
1051         index++;
1052       }
1053     }
1054     // Wait for completion of isend's.
1055     smpi_mpi_startall(size - 1, requests);
1056     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1057     xbt_free(requests);
1058   }
1059 }
1060
1061 void smpi_mpi_reduce(void *sendbuf, void *recvbuf, int count,
1062                      MPI_Datatype datatype, MPI_Op op, int root,
1063                      MPI_Comm comm)
1064 {
1065   int system_tag = 666;
1066   int rank, size, src, index;
1067   MPI_Aint lb = 0, dataext = 0;
1068   MPI_Request *requests;
1069   void **tmpbufs;
1070
1071   rank = smpi_comm_rank(comm);
1072   size = smpi_comm_size(comm);
1073   if(rank != root) {
1074     // Send buffer to root
1075     smpi_mpi_send(sendbuf, count, datatype, root, system_tag, comm);
1076   } else {
1077     // FIXME: check for errors
1078     smpi_datatype_extent(datatype, &lb, &dataext);
1079     // Local copy from root
1080     if (sendbuf && recvbuf)
1081       smpi_datatype_copy(sendbuf, count, datatype, recvbuf, count, datatype);
1082     // Receive buffers from senders
1083     //TODO: make a MPI_barrier here ?
1084     requests = xbt_new(MPI_Request, size - 1);
1085     tmpbufs = xbt_new(void *, size - 1);
1086     index = 0;
1087     for(src = 0; src < size; src++) {
1088       if(src != root) {
1089         // FIXME: possibly overkill we we have contiguous/noncontiguous data
1090         //  mapping...
1091         tmpbufs[index] = xbt_malloc(count * dataext);
1092         requests[index] =
1093           smpi_irecv_init(tmpbufs[index], count, datatype, src,
1094                           system_tag, comm);
1095         index++;
1096       }
1097     }
1098     // Wait for completion of irecv's.
1099     smpi_mpi_startall(size - 1, requests);
1100     for(src = 0; src < size - 1; src++) {
1101       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1102       XBT_DEBUG("finished waiting any request with index %d", index);
1103       if(index == MPI_UNDEFINED) {
1104         break;
1105       }
1106       if(op) /* op can be MPI_OP_NULL that does nothing */
1107         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1108     }
1109     for(index = 0; index < size - 1; index++) {
1110       xbt_free(tmpbufs[index]);
1111     }
1112     xbt_free(tmpbufs);
1113     xbt_free(requests);
1114   }
1115 }
1116
1117 void smpi_mpi_allreduce(void *sendbuf, void *recvbuf, int count,
1118                         MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1119 {
1120   smpi_mpi_reduce(sendbuf, recvbuf, count, datatype, op, 0, comm);
1121   smpi_mpi_bcast(recvbuf, count, datatype, 0, comm);
1122 }
1123
1124 void smpi_mpi_scan(void *sendbuf, void *recvbuf, int count,
1125                    MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1126 {
1127   int system_tag = 666;
1128   int rank, size, other, index;
1129   MPI_Aint lb = 0, dataext = 0;
1130   MPI_Request *requests;
1131   void **tmpbufs;
1132
1133   rank = smpi_comm_rank(comm);
1134   size = smpi_comm_size(comm);
1135
1136   // FIXME: check for errors
1137   smpi_datatype_extent(datatype, &lb, &dataext);
1138
1139   // Local copy from self
1140   smpi_datatype_copy(sendbuf, count, datatype, recvbuf, count, datatype);
1141
1142   // Send/Recv buffers to/from others;
1143   requests = xbt_new(MPI_Request, size - 1);
1144   tmpbufs = xbt_new(void *, rank);
1145   index = 0;
1146   for(other = 0; other < rank; other++) {
1147     // FIXME: possibly overkill we we have contiguous/noncontiguous data
1148     // mapping...
1149     tmpbufs[index] = xbt_malloc(count * dataext);
1150     requests[index] =
1151       smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag,
1152                       comm);
1153     index++;
1154   }
1155   for(other = rank + 1; other < size; other++) {
1156     requests[index] =
1157       smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1158     index++;
1159   }
1160   // Wait for completion of all comms.
1161   smpi_mpi_startall(size - 1, requests);
1162   for(other = 0; other < size - 1; other++) {
1163     index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1164     if(index == MPI_UNDEFINED) {
1165       break;
1166     }
1167     if(index < rank) {
1168       // #Request is below rank: it's a irecv
1169       smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1170     }
1171   }
1172   for(index = 0; index < rank; index++) {
1173     xbt_free(tmpbufs[index]);
1174   }
1175   xbt_free(tmpbufs);
1176   xbt_free(requests);
1177 }