Logo AND Algorithmique Numérique Distribuée

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