Logo AND Algorithmique Numérique Distribuée

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