Logo AND Algorithmique Numérique Distribuée

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