Logo AND Algorithmique Numérique Distribuée

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