Logo AND Algorithmique Numérique Distribuée

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