Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
c26d0fd3023f0944b6c617d0ce674270b58515c1
[simgrid.git] / src / smpi / smpi_base.cpp
1 /* Copyright (c) 2007-2015. 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 <xbt/config.hpp>
8
9 #include "private.h"
10 #include "xbt/virtu.h"
11 #include "mc/mc.h"
12 #include "src/mc/mc_replay.h"
13 #include "xbt/replay.h"
14 #include <errno.h>
15 #include "src/simix/smx_private.h"
16 #include "surf/surf.h"
17 #include "simgrid/sg_config.h"
18 #include "colls/colls.h"
19
20 #include "src/simix/SynchroComm.hpp"
21
22 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_base, smpi, "Logging specific to SMPI (base)");
23
24 static int match_recv(void* a, void* b, smx_synchro_t ignored) {
25    MPI_Request ref = static_cast<MPI_Request>(a);
26    MPI_Request req = static_cast<MPI_Request>(b);
27    XBT_DEBUG("Trying to match a recv of src %d against %d, tag %d against %d",ref->src,req->src, ref->tag, req->tag);
28
29   xbt_assert(ref, "Cannot match recv against null reference");
30   xbt_assert(req, "Cannot match recv against null request");
31   if((ref->src == MPI_ANY_SOURCE || req->src == ref->src)
32     && ((ref->tag == MPI_ANY_TAG && req->tag >=0) || req->tag == ref->tag)){
33     //we match, we can transfer some values
34     if(ref->src == MPI_ANY_SOURCE)
35         ref->real_src = req->src;
36     if(ref->tag == MPI_ANY_TAG)
37         ref->real_tag = req->tag;
38     if(ref->real_size < req->real_size) 
39         ref->truncated = 1;
40     if(req->detached==1)
41         ref->detached_sender=req; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
42     XBT_DEBUG("match succeeded");
43     return 1;
44   }else return 0;
45 }
46
47 static int match_send(void* a, void* b,smx_synchro_t ignored) {
48    MPI_Request ref = static_cast<MPI_Request>(a);
49    MPI_Request req = static_cast<MPI_Request>(b);
50    XBT_DEBUG("Trying to match a send of src %d against %d, tag %d against %d",ref->src,req->src, ref->tag, req->tag);
51    xbt_assert(ref, "Cannot match send against null reference");
52    xbt_assert(req, "Cannot match send against null request");
53
54    if((req->src == MPI_ANY_SOURCE || req->src == ref->src)
55              && ((req->tag == MPI_ANY_TAG && ref->tag >=0)|| req->tag == ref->tag))
56    {
57      if(req->src == MPI_ANY_SOURCE)
58         req->real_src = ref->src;
59      if(req->tag == MPI_ANY_TAG)
60         req->real_tag = ref->tag;
61      if(req->real_size < ref->real_size) 
62         req->truncated = 1;
63      if(ref->detached==1)
64          req->detached_sender=ref; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
65      XBT_DEBUG("match succeeded");
66      return 1;
67    } else return 0;
68 }
69
70 // Methods used to parse and store the values for timing injections in smpi
71 // These are taken from surf/network.c and generalized to have more values for each factor
72 typedef struct s_smpi_factor_multival *smpi_os_factor_multival_t;
73 typedef struct s_smpi_factor_multival { // FIXME: this should be merged (deduplicated) with s_smpi_factor defined in network_smpi.c
74   long factor;
75   int nb_values;
76   double values[4];//arbitrary set to 4
77 } s_smpi_factor_multival_t;
78
79 xbt_dynar_t smpi_os_values  = nullptr;
80 xbt_dynar_t smpi_or_values  = nullptr;
81 xbt_dynar_t smpi_ois_values = nullptr;
82
83 static simgrid::config::Flag<double> smpi_wtime_sleep(
84   "smpi/wtime", "Minimum time to inject inside a call to MPI_Wtime", 0.0);
85 static simgrid::config::Flag<double> smpi_init_sleep(
86   "smpi/init", "Time to inject inside a call to MPI_Init", 0.0);
87 static simgrid::config::Flag<double> smpi_iprobe_sleep(
88   "smpi/iprobe", "Minimum time to inject inside a call to MPI_Iprobe", 1e-4);
89 static simgrid::config::Flag<double> smpi_test_sleep(
90   "smpi/test", "Minimum time to inject inside a call to MPI_Test", 1e-4);
91
92 static int factor_cmp(const void *pa, const void *pb)
93 {
94   return ((static_cast<const s_smpi_factor_multival_t*>(pa))->factor > (static_cast<const s_smpi_factor_multival_t*>(pb))->factor) ? 1 :
95          ((static_cast<const s_smpi_factor_multival_t*>(pa))->factor < (static_cast<const s_smpi_factor_multival_t*>(pb))->factor) ? -1 : 0;
96 }
97
98 static xbt_dynar_t parse_factor(const char *smpi_coef_string)
99 {
100   char *value = NULL;
101   unsigned int iter = 0;
102   s_smpi_factor_multival_t fact;
103   fact.nb_values=0;
104   unsigned int i=0;
105   xbt_dynar_t radical_elements2 = NULL;
106
107   xbt_dynar_t smpi_factor = xbt_dynar_new(sizeof(s_smpi_factor_multival_t), NULL);
108   xbt_dynar_t radical_elements = xbt_str_split(smpi_coef_string, ";");
109   xbt_dynar_foreach(radical_elements, iter, value) {
110     memset(&fact, 0, sizeof(s_smpi_factor_multival_t));
111     radical_elements2 = xbt_str_split(value, ":");
112     if (xbt_dynar_length(radical_elements2) <2 || xbt_dynar_length(radical_elements2) > 5)
113       xbt_die("Malformed radical for smpi factor: '%s'", smpi_coef_string);
114     for(i =0; i<xbt_dynar_length(radical_elements2);i++ ){
115       char *errmsg;
116       if (i==0) {
117         errmsg = bprintf("Invalid factor in chunk #%d: %%s", iter+1);
118         fact.factor = xbt_str_parse_int(xbt_dynar_get_as(radical_elements2, i, char *), errmsg);
119       } else {
120         errmsg = bprintf("Invalid factor value %d in chunk #%d: %%s", i, iter+1);
121         fact.values[fact.nb_values] = xbt_str_parse_double(xbt_dynar_get_as(radical_elements2, i, char *), errmsg);
122         fact.nb_values++;
123       }
124       xbt_free(errmsg);
125     }
126
127     xbt_dynar_push_as(smpi_factor, s_smpi_factor_multival_t, fact);
128     XBT_DEBUG("smpi_factor:\t%ld : %d values, first: %f", fact.factor, fact.nb_values ,fact.values[0]);
129     xbt_dynar_free(&radical_elements2);
130   }
131   xbt_dynar_free(&radical_elements);
132   xbt_dynar_sort(smpi_factor, &factor_cmp);
133   xbt_dynar_foreach(smpi_factor, iter, fact) {
134     XBT_DEBUG("smpi_factor:\t%ld : %d values, first: %f", fact.factor, fact.nb_values ,fact.values[0]);
135   }
136   return smpi_factor;
137 }
138
139 static double smpi_os(double size)
140 {
141   if (smpi_os_values == nullptr) {
142     smpi_os_values = parse_factor(xbt_cfg_get_string("smpi/os"));
143     smpi_register_static(smpi_os_values, xbt_dynar_free_voidp);
144   }
145   unsigned int iter = 0;
146   s_smpi_factor_multival_t fact;
147   double current=0.0;
148   // Iterate over all the sections that were specified and find the right
149   // value. (fact.factor represents the interval sizes; we want to find the
150   // section that has fact.factor <= size and no other such fact.factor <= size)
151   // Note: parse_factor() (used before) already sorts the dynar we iterate over!
152   xbt_dynar_foreach(smpi_os_values, iter, fact) {
153     if (size <= fact.factor) { // Values already too large, use the previously
154                                // computed value of current!
155         XBT_DEBUG("os : %f <= %ld return %f", size, fact.factor, current);
156       return current;
157     }else{
158       // If the next section is too large, the current section must be used.
159       // Hence, save the cost, as we might have to use it.
160       current = fact.values[0]+fact.values[1]*size;
161     }
162   }
163   XBT_DEBUG("os : %f > %ld return %f", size, fact.factor, current);
164
165   return current;
166 }
167
168 static double smpi_ois(double size)
169 {
170   if (smpi_ois_values == nullptr) {
171     smpi_ois_values = parse_factor(xbt_cfg_get_string("smpi/ois"));
172     smpi_register_static(smpi_ois_values, xbt_dynar_free_voidp);
173   }
174   unsigned int iter = 0;
175   s_smpi_factor_multival_t fact;
176   double current=0.0;
177   // Iterate over all the sections that were specified and find the right value. (fact.factor represents the interval
178   // sizes; we want to find the section that has fact.factor <= size and no other such fact.factor <= size)
179   // Note: parse_factor() (used before) already sorts the dynar we iterate over!
180   xbt_dynar_foreach(smpi_ois_values, iter, fact) {
181     if (size <= fact.factor) { // Values already too large, use the previously  computed value of current!
182         XBT_DEBUG("ois : %f <= %ld return %f", size, fact.factor, current);
183       return current;
184     }else{
185       // If the next section is too large, the current section must be used.
186       // Hence, save the cost, as we might have to use it.
187       current = fact.values[0]+fact.values[1]*size;
188     }
189   }
190   XBT_DEBUG("ois : %f > %ld return %f", size, fact.factor, current);
191
192   return current;
193 }
194
195 static double smpi_or(double size)
196 {
197   if (smpi_or_values == nullptr) {
198     smpi_or_values = parse_factor(xbt_cfg_get_string("smpi/or"));
199     smpi_register_static(smpi_or_values, xbt_dynar_free_voidp);
200   }
201   unsigned int iter = 0;
202   s_smpi_factor_multival_t fact;
203   double current=0.0;
204   // Iterate over all the sections that were specified and find the right value. (fact.factor represents the interval
205   // sizes; we want to find the section that has fact.factor <= size and no other such fact.factor <= size)
206   // Note: parse_factor() (used before) already sorts the dynar we iterate over!
207   xbt_dynar_foreach(smpi_or_values, iter, fact) {
208     if (size <= fact.factor) { // Values already too large, use the previously
209                                // computed value of current!
210         XBT_DEBUG("or : %f <= %ld return %f", size, fact.factor, current);
211       return current;
212     } else {
213       // If the next section is too large, the current section must be used.
214       // Hence, save the cost, as we might have to use it.
215       current=fact.values[0]+fact.values[1]*size;
216     }
217   }
218   XBT_DEBUG("or : %f > %ld return %f", size, fact.factor, current);
219
220   return current;
221 }
222
223 void smpi_mpi_init() {
224   if(smpi_init_sleep > 0) 
225     simcall_process_sleep(smpi_init_sleep);
226 }
227
228 double smpi_mpi_wtime(){
229   double time;
230   if (smpi_process_initialized() != 0 && 
231       smpi_process_finalized() == 0 && 
232       smpi_process_get_sampling() == 0) {
233     smpi_bench_end();
234     time = SIMIX_get_clock();
235     // to avoid deadlocks if used as a break condition, such as
236     //     while (MPI_Wtime(...) < time_limit) {
237     //       ....
238     //     }
239     // because the time will not normally advance when only calls to MPI_Wtime
240     // are made -> deadlock (MPI_Wtime never reaches the time limit)
241     if(smpi_wtime_sleep > 0) 
242       simcall_process_sleep(smpi_wtime_sleep);
243     smpi_bench_begin();
244   } else {
245     time = SIMIX_get_clock();
246   }
247   return time;
248 }
249
250 static MPI_Request build_request(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
251                                  unsigned flags)
252 {
253   MPI_Request request = NULL;
254
255   void *old_buf = NULL;
256
257   request = xbt_new(s_smpi_mpi_request_t, 1);
258
259   s_smpi_subtype_t *subtype = static_cast<s_smpi_subtype_t*>(datatype->substruct);
260
261   if((((flags & RECV) != 0) && ((flags & ACCUMULATE) !=0)) || (datatype->sizeof_substruct != 0)){
262     // This part handles the problem of non-contiguous memory
263     old_buf = buf;
264     buf = count==0 ? NULL : xbt_malloc(count*smpi_datatype_size(datatype));
265     if ((datatype->sizeof_substruct != 0) && ((flags & SEND) != 0)) {
266       subtype->serialize(old_buf, buf, count, datatype->substruct);
267     }
268   }
269
270   request->buf      = buf;
271   // This part handles the problem of non-contiguous memory (for the unserialisation at the reception)
272   request->old_buf  = old_buf;
273   request->old_type = datatype;
274
275   request->size = smpi_datatype_size(datatype) * count;
276   smpi_datatype_use(datatype);
277   request->src  = src;
278   request->dst  = dst;
279   request->tag  = tag;
280   request->comm = comm;
281   smpi_comm_use(request->comm);
282   request->action          = nullptr;
283   request->flags           = flags;
284   request->detached        = 0;
285   request->detached_sender = nullptr;
286   request->real_src        = 0;
287   request->truncated       = 0;
288   request->real_size       = 0;
289   request->real_tag        = 0;
290   if (flags & PERSISTENT)
291     request->refcount = 1;
292   else
293     request->refcount = 0;
294   request->op   = MPI_REPLACE;
295   request->send = 0;
296   request->recv = 0;
297
298   return request;
299 }
300
301 void smpi_empty_status(MPI_Status * status)
302 {
303   if(status != MPI_STATUS_IGNORE) {
304     status->MPI_SOURCE = MPI_ANY_SOURCE;
305     status->MPI_TAG = MPI_ANY_TAG;
306     status->MPI_ERROR = MPI_SUCCESS;
307     status->count=0;
308   }
309 }
310
311 static void smpi_mpi_request_free_voidp(void* request)
312 {
313   MPI_Request req = static_cast<MPI_Request>(request);
314   smpi_mpi_request_free(&req);
315 }
316
317 /* MPI Low level calls */
318 MPI_Request smpi_mpi_send_init(void *buf, int count, MPI_Datatype datatype,
319                                int dst, int tag, MPI_Comm comm)
320 {
321   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
322   request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype, smpi_process_index(),
323                           smpi_group_index(smpi_comm_group(comm), dst), tag, comm, PERSISTENT | SEND | PREPARED);
324   return request;
325 }
326
327 MPI_Request smpi_mpi_ssend_init(void *buf, int count, MPI_Datatype datatype,
328                                int dst, int tag, MPI_Comm comm)
329 {
330   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
331   request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype, smpi_process_index(),
332                         smpi_group_index(smpi_comm_group(comm), dst), tag, comm, PERSISTENT | SSEND | SEND | PREPARED);
333   return request;
334 }
335
336 MPI_Request smpi_mpi_recv_init(void *buf, int count, MPI_Datatype datatype,
337                                int src, int tag, MPI_Comm comm)
338 {
339   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
340   request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype,
341                           src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : smpi_group_index(smpi_comm_group(comm), src),
342                           smpi_process_index(), tag, comm, PERSISTENT | RECV | PREPARED);
343   return request;
344 }
345
346 void smpi_mpi_start(MPI_Request request)
347 {
348   smx_mailbox_t mailbox;
349
350   xbt_assert(request->action == nullptr, "Cannot (re-)start unfinished communication");
351   request->flags &= ~PREPARED;
352   request->flags &= ~FINISHED;
353   request->refcount++;
354
355   if ((request->flags & RECV) != 0) {
356     print_request("New recv", request);
357
358     int async_small_thresh = xbt_cfg_get_int("smpi/async-small-thresh");
359
360     xbt_mutex_t mut = smpi_process_mailboxes_mutex();
361     if (async_small_thresh != 0 || (request->flags & RMA) != 0)
362       xbt_mutex_acquire(mut);
363
364     if (async_small_thresh == 0 && (request->flags & RMA) == 0 ) {
365       mailbox = smpi_process_mailbox();
366     } 
367     else if (((request->flags & RMA) != 0) || static_cast<int>(request->size) < async_small_thresh) {
368       //We have to check both mailboxes (because SSEND messages are sent to the large mbox).
369       //begin with the more appropriate one : the small one.
370       mailbox = smpi_process_mailbox_small();
371       XBT_DEBUG("Is there a corresponding send already posted in the small mailbox %p (in case of SSEND)?", mailbox);
372       smx_synchro_t action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv, static_cast<void*>(request));
373     
374       if (action == nullptr) {
375         mailbox = smpi_process_mailbox();
376         XBT_DEBUG("No, nothing in the small mailbox test the other one : %p", mailbox);
377         action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv, static_cast<void*>(request));
378         if (action == nullptr) {
379           XBT_DEBUG("Still nothing, switch back to the small mailbox : %p", mailbox);
380           mailbox = smpi_process_mailbox_small();
381         }
382       }
383       else {
384         XBT_DEBUG("yes there was something for us in the large mailbox");
385       }
386     }
387     else {
388       mailbox = smpi_process_mailbox_small();
389       XBT_DEBUG("Is there a corresponding send already posted the small mailbox?");
390       smx_synchro_t action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv, (void*)request);
391     
392       if (action == nullptr) {
393         XBT_DEBUG("No, nothing in the permanent receive mailbox");
394         mailbox = smpi_process_mailbox();
395       }
396       else {
397         XBT_DEBUG("yes there was something for us in the small mailbox");
398       }
399     }
400
401     //integrate pseudo-timing for buffering of small messages, do not bother to execute the simcall if 0
402     double sleeptime = (request->detached != 0) ? smpi_or(request->size) : 0.0;
403     if(sleeptime > 0.0){
404         simcall_process_sleep(sleeptime);
405         XBT_DEBUG("receiving size of %zu : sleep %f ", request->size, smpi_or(request->size));
406     }
407
408     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
409     request->real_size=request->size;
410     request->action = simcall_comm_irecv(SIMIX_process_self(), mailbox, request->buf, &request->real_size, &match_recv,
411                                          ! smpi_process_get_replaying()? &smpi_comm_copy_buffer_callback
412                                          : &smpi_comm_null_copy_buffer_callback, request, -1.0);
413         XBT_DEBUG("recv simcall posted");
414
415     if (async_small_thresh != 0 || (request->flags & RMA) != 0 )
416       xbt_mutex_release(mut);
417   }
418   else { /* the RECV flag was not set, so this is a send */
419     int receiver = request->dst;
420
421     int rank = request->src;
422     if (TRACE_smpi_view_internals()) {
423       TRACE_smpi_send(rank, rank, receiver,request->size);
424     }
425     print_request("New send", request);
426
427     void* buf = request->buf;
428     if ( (request->flags & SSEND) == 0 
429         && ( (request->flags & RMA) != 0 || static_cast<int>(request->size) < xbt_cfg_get_int("smpi/send-is-detached-thresh") ) ) {
430       void *oldbuf = NULL;
431       request->detached = 1;
432       XBT_DEBUG("Send request %p is detached", request);
433       request->refcount++;
434       if(request->old_type->sizeof_substruct == 0){
435         oldbuf = request->buf;
436         if (!smpi_process_get_replaying() && oldbuf != NULL && request->size!=0){
437           if((smpi_privatize_global_variables != 0)
438             && (static_cast<char*>(request->buf) >= smpi_start_data_exe)
439             && (static_cast<char*>(request->buf) < smpi_start_data_exe + smpi_size_data_exe )){
440             XBT_DEBUG("Privatization : We are sending from a zone inside global memory. Switch data segment ");
441             smpi_switch_data_segment(request->src);
442           }
443           buf = xbt_malloc(request->size);
444           memcpy(buf,oldbuf,request->size);
445           XBT_DEBUG("buf %p copied into %p",oldbuf,buf);
446         }
447       }
448     }
449
450     //if we are giving back the control to the user without waiting for completion, we have to inject timings
451     double sleeptime = 0.0;
452     if(request->detached != 0 || ((request->flags & (ISEND|SSEND)) != 0)){// issend should be treated as isend
453       //isend and send timings may be different
454       sleeptime = ((request->flags & ISEND) != 0) ? smpi_ois(request->size) : smpi_os(request->size);
455     }
456
457     if(sleeptime > 0.0){
458         simcall_process_sleep(sleeptime);
459         XBT_DEBUG("sending size of %zu : sleep %f ", request->size, sleeptime);
460     } 
461
462     int async_small_thresh = xbt_cfg_get_int("smpi/async-small-thresh");
463
464     xbt_mutex_t mut=smpi_process_remote_mailboxes_mutex(receiver);
465
466     if (async_small_thresh != 0 || (request->flags & RMA) != 0)
467       xbt_mutex_acquire(mut);
468
469     if (!(async_small_thresh != 0 || (request->flags & RMA) !=0)) {
470       mailbox = smpi_process_remote_mailbox(receiver);
471     }
472     else if (((request->flags & RMA) != 0) || static_cast<int>(request->size) < async_small_thresh) { // eager mode
473       mailbox = smpi_process_remote_mailbox(receiver);
474       XBT_DEBUG("Is there a corresponding recv already posted in the large mailbox %p?", mailbox);
475       smx_synchro_t action = simcall_comm_iprobe(mailbox, 1,request->dst, request->tag, &match_send, static_cast<void*>(request));
476       if (action == nullptr) {
477         if ((request->flags & SSEND) == 0){
478           mailbox = smpi_process_remote_mailbox_small(receiver);
479           XBT_DEBUG("No, nothing in the large mailbox, message is to be sent on the small one %p", mailbox);
480         } 
481         else {
482           mailbox = smpi_process_remote_mailbox_small(receiver);
483           XBT_DEBUG("SSEND : Is there a corresponding recv already posted in the small mailbox %p?", mailbox);
484           action = simcall_comm_iprobe(mailbox, 1,request->dst, request->tag, &match_send, static_cast<void*>(request));
485           if (action == nullptr) {
486             XBT_DEBUG("No, we are first, send to large mailbox");
487             mailbox = smpi_process_remote_mailbox(receiver);
488           }
489         }
490       }
491       else {
492         XBT_DEBUG("Yes there was something for us in the large mailbox");
493       }
494     }
495     else {
496       mailbox = smpi_process_remote_mailbox(receiver);
497       XBT_DEBUG("Send request %p is in the large mailbox %p (buf: %p)",mailbox, request,request->buf);
498     }
499
500     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
501     request->real_size=request->size;
502     request->action = simcall_comm_isend(SIMIX_process_from_PID(request->src+1), mailbox, request->size, -1.0,
503                                          buf, request->real_size, &match_send,
504                          &xbt_free_f, // how to free the userdata if a detached send fails
505                          !smpi_process_get_replaying() ? &smpi_comm_copy_buffer_callback
506                          : &smpi_comm_null_copy_buffer_callback, request,
507                          // detach if msg size < eager/rdv switch limit
508                          request->detached);
509     XBT_DEBUG("send simcall posted");
510
511     /* FIXME: detached sends are not traceable (request->action == nullptr) */
512     if (request->action != nullptr)
513       simcall_set_category(request->action, TRACE_internal_smpi_get_category());
514
515     if (async_small_thresh != 0 || ((request->flags & RMA)!=0))
516       xbt_mutex_release(mut);
517   }
518 }
519
520 void smpi_mpi_startall(int count, MPI_Request * requests)
521 {
522   if(requests== nullptr) 
523     return;
524
525   for(int i = 0; i < count; i++) {
526     smpi_mpi_start(requests[i]);
527   }
528 }
529
530 void smpi_mpi_request_free(MPI_Request * request)
531 {
532   if((*request) != MPI_REQUEST_NULL){
533     (*request)->refcount--;
534     if((*request)->refcount<0) xbt_die("wrong refcount");
535
536     if((*request)->refcount==0){
537         smpi_datatype_unuse((*request)->old_type);
538         smpi_comm_unuse((*request)->comm);
539         print_request("Destroying", (*request));
540         xbt_free(*request);
541         *request = MPI_REQUEST_NULL;
542     }else{
543         print_request("Decrementing", (*request));
544     }
545   }else{
546       xbt_die("freeing an already free request");
547   }
548 }
549
550 MPI_Request smpi_rma_send_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
551                                MPI_Op op)
552 {
553   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
554   if(op==MPI_OP_NULL){
555     request = build_request(buf==MPI_BOTTOM ? NULL : buf , count, datatype, src, dst, tag,
556                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED);
557   }else{
558     request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype,  src, dst, tag,
559                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED | ACCUMULATE);
560     request->op = op;
561   }
562   return request;
563 }
564
565 MPI_Request smpi_rma_recv_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
566                                MPI_Op op)
567 {
568   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
569   if(op==MPI_OP_NULL){
570     request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype,  src, dst, tag,
571                             comm, RMA | NON_PERSISTENT | RECV | PREPARED);
572   }else{
573     request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype,  src, dst, tag,
574                             comm, RMA | NON_PERSISTENT | RECV | PREPARED | ACCUMULATE);
575     request->op = op;
576   }
577   return request;
578 }
579
580 MPI_Request smpi_isend_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
581 {
582   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
583   request = build_request(buf==MPI_BOTTOM ? NULL : buf , count, datatype, smpi_process_index(),
584                           smpi_group_index(smpi_comm_group(comm), dst), tag,comm, PERSISTENT | ISEND | SEND | PREPARED);
585   return request;
586 }
587
588 MPI_Request smpi_mpi_isend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
589 {
590   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
591   request =  build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype, smpi_process_index(),
592                            smpi_group_index(smpi_comm_group(comm), dst), tag, comm, NON_PERSISTENT | ISEND | SEND);
593   smpi_mpi_start(request);
594   return request;
595 }
596
597 MPI_Request smpi_mpi_issend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
598 {
599   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
600   request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype, smpi_process_index(),
601                         smpi_group_index(smpi_comm_group(comm), dst), tag,comm, NON_PERSISTENT | ISEND | SSEND | SEND);
602   smpi_mpi_start(request);
603   return request;
604 }
605
606 MPI_Request smpi_irecv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
607 {
608   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
609   request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype, src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
610                           smpi_group_index(smpi_comm_group(comm), src), smpi_process_index(), tag,
611                           comm, PERSISTENT | RECV | PREPARED);
612   return request;
613 }
614
615 MPI_Request smpi_mpi_irecv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
616 {
617   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
618   request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype, src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
619                           smpi_group_index(smpi_comm_group(comm), src), smpi_process_index(), tag, comm,
620                           NON_PERSISTENT | RECV);
621   smpi_mpi_start(request);
622   return request;
623 }
624
625 void smpi_mpi_recv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm, MPI_Status * status)
626 {
627   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
628   request = smpi_mpi_irecv(buf, count, datatype, src, tag, comm);
629   smpi_mpi_wait(&request, status);
630   request = NULL;
631 }
632
633 void smpi_mpi_send(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
634 {
635   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
636   request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype, smpi_process_index(),
637                           smpi_group_index(smpi_comm_group(comm), dst), tag, comm, NON_PERSISTENT | SEND);
638
639   smpi_mpi_start(request);
640   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
641   request = NULL;
642 }
643
644 void smpi_mpi_ssend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
645 {
646   MPI_Request request = NULL; /* MC needs the comm to be set to NULL during the call */
647   request = build_request(buf==MPI_BOTTOM ? NULL : buf, count, datatype, smpi_process_index(),
648                           smpi_group_index(smpi_comm_group(comm), dst), tag, comm, NON_PERSISTENT | SSEND | SEND);
649
650   smpi_mpi_start(request);
651   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
652   request = NULL;
653 }
654
655 void smpi_mpi_sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,int dst, int sendtag,
656                        void *recvbuf, int recvcount, MPI_Datatype recvtype, int src, int recvtag,
657                        MPI_Comm comm, MPI_Status * status)
658 {
659   MPI_Request requests[2];
660   MPI_Status stats[2];
661   int myid=smpi_process_index();
662   if ((smpi_group_index(smpi_comm_group(comm), dst) == myid) && (smpi_group_index(smpi_comm_group(comm), src) == myid)){
663       smpi_datatype_copy(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype);
664       return;
665   }
666   requests[0] = smpi_isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
667   requests[1] = smpi_irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
668   smpi_mpi_startall(2, requests);
669   smpi_mpi_waitall(2, requests, stats);
670   smpi_mpi_request_free(&requests[0]);
671   smpi_mpi_request_free(&requests[1]);
672   if(status != MPI_STATUS_IGNORE) {
673     // Copy receive status
674     *status = stats[1];
675   }
676 }
677
678 int smpi_mpi_get_count(MPI_Status * status, MPI_Datatype datatype)
679 {
680   return status->count / smpi_datatype_size(datatype);
681 }
682
683 static void finish_wait(MPI_Request * request, MPI_Status * status)
684 {
685   MPI_Request req = *request;
686   smpi_empty_status(status);
687
688   if(!((req->detached != 0) && ((req->flags & SEND) != 0)) && ((req->flags & PREPARED) == 0)){
689     if(status != MPI_STATUS_IGNORE) {
690       int src = req->src == MPI_ANY_SOURCE ? req->real_src : req->src;
691       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(req->comm), src);
692       status->MPI_TAG = req->tag == MPI_ANY_TAG ? req->real_tag : req->tag;
693       status->MPI_ERROR = req->truncated != 0 ? MPI_ERR_TRUNCATE : MPI_SUCCESS;
694       // this handles the case were size in receive differs from size in send
695       status->count = req->real_size;
696     }
697
698     print_request("Finishing", req);
699     MPI_Datatype datatype = req->old_type;
700
701     if(((req->flags & ACCUMULATE) != 0) || (datatype->sizeof_substruct != 0)){
702       if (!smpi_process_get_replaying()){
703         if( smpi_privatize_global_variables != 0 && (static_cast<char*>(req->old_buf) >= smpi_start_data_exe)
704             && ((char*)req->old_buf < smpi_start_data_exe + smpi_size_data_exe )){
705             XBT_VERB("Privatization : We are unserializing to a zone in global memory - Switch data segment ");
706             smpi_switch_data_segment(smpi_process_index());
707         }
708       }
709
710       if(datatype->sizeof_substruct != 0){
711         // This part handles the problem of non-contignous memory the unserialization at the reception
712         s_smpi_subtype_t *subtype = static_cast<s_smpi_subtype_t*>(datatype->substruct);
713         if(req->flags & RECV)
714           subtype->unserialize(req->buf, req->old_buf, req->real_size/smpi_datatype_size(datatype) ,
715                                datatype->substruct, req->op);
716         xbt_free(req->buf);
717       }else if(req->flags & RECV){//apply op on contiguous buffer for accumulate
718           int n =req->real_size/smpi_datatype_size(datatype);
719           smpi_op_apply(req->op, req->buf, req->old_buf, &n, &datatype);
720           xbt_free(req->buf);
721       }
722     }
723   }
724
725   if (TRACE_smpi_view_internals() && ((req->flags & RECV) != 0)){
726     int rank = smpi_process_index();
727     int src_traced = (req->src == MPI_ANY_SOURCE ? req->real_src : req->src);
728     TRACE_smpi_recv(rank, src_traced, rank);
729   }
730
731   if(req->detached_sender!=NULL){
732     smpi_mpi_request_free(&(req->detached_sender));
733   }
734   if(req->flags & PERSISTENT)
735     req->action = NULL;
736   req->flags |= FINISHED;
737
738   smpi_mpi_request_free(request);
739 }
740
741 int smpi_mpi_test(MPI_Request * request, MPI_Status * status) {
742   //assume that request is not MPI_REQUEST_NULL (filtered in PMPI_Test or smpi_mpi_testall before)
743
744   // to avoid deadlocks if used as a break condition, such as
745   //     while (MPI_Test(request, flag, status) && flag) {
746   //     }
747   // because the time will not normally advance when only calls to MPI_Test are made -> deadlock
748   // multiplier to the sleeptime, to increase speed of execution, each failed test will increase it
749   static int nsleeps = 1;
750   if(smpi_test_sleep > 0)  
751     simcall_process_sleep(nsleeps*smpi_test_sleep);
752
753   smpi_empty_status(status);
754   int flag = 1;
755   if (((*request)->flags & PREPARED) == 0) {
756     if ((*request)->action != NULL)
757       flag = simcall_comm_test((*request)->action);
758     if (flag) {
759       finish_wait(request, status);
760       nsleeps=1;//reset the number of sleeps we will do next time
761       if (*request != MPI_REQUEST_NULL && ((*request)->flags & PERSISTENT)==0)
762       *request = MPI_REQUEST_NULL;
763     }else{
764       nsleeps++;
765     }
766   }
767   return flag;
768 }
769
770 int smpi_mpi_testany(int count, MPI_Request requests[], int *index, MPI_Status * status)
771 {
772   xbt_dynar_t comms;
773   int i;
774   int* map;
775   int flag = 0;
776   int size = 0;
777
778   *index = MPI_UNDEFINED;
779   comms = xbt_dynar_new(sizeof(smx_synchro_t), NULL);
780   map = xbt_new(int, count);
781   for(i = 0; i < count; i++) {
782     if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->action && !(requests[i]->flags & PREPARED)) {
783        xbt_dynar_push(comms, &requests[i]->action);
784        map[size] = i;
785        size++;
786     }
787   }
788   if(size > 0) {
789     //multiplier to the sleeptime, to increase speed of execution, each failed testany will increase it
790     static int nsleeps = 1;
791     if(smpi_test_sleep > 0) 
792       simcall_process_sleep(nsleeps*smpi_test_sleep);
793
794     i = simcall_comm_testany(comms);
795     // not MPI_UNDEFINED, as this is a simix return code
796     if(i != -1) {
797       *index = map[i];
798       finish_wait(&requests[*index], status);
799       if (requests[*index] != MPI_REQUEST_NULL && (requests[*index]->flags & NON_PERSISTENT))
800       requests[*index] = MPI_REQUEST_NULL;
801       flag = 1;
802       nsleeps=1;
803     }else{
804       nsleeps++;
805     }
806   }else{
807       //all requests are null or inactive, return true
808       flag=1;
809       smpi_empty_status(status);
810   }
811   xbt_free(map);
812   xbt_dynar_free(&comms);
813
814   return flag;
815 }
816
817 int smpi_mpi_testall(int count, MPI_Request requests[], MPI_Status status[])
818 {
819   MPI_Status stat;
820   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
821   int flag=1;
822   int i;
823   for(i=0; i<count; i++){
824     if (requests[i] != MPI_REQUEST_NULL && !(requests[i]->flags & PREPARED)) {
825       if (smpi_mpi_test(&requests[i], pstat)!=1){
826         flag=0;
827       }else{
828           requests[i]=MPI_REQUEST_NULL;
829       }
830     }else{
831       smpi_empty_status(pstat);
832     }
833     if(status != MPI_STATUSES_IGNORE) {
834       status[i] = *pstat;
835     }
836   }
837   return flag;
838 }
839
840 void smpi_mpi_probe(int source, int tag, MPI_Comm comm, MPI_Status* status){
841   int flag=0;
842   //FIXME find another way to avoid busy waiting ?
843   // the issue here is that we have to wait on a nonexistent comm
844   while(flag==0){
845     smpi_mpi_iprobe(source, tag, comm, &flag, status);
846     XBT_DEBUG("Busy Waiting on probing : %d", flag);
847   }
848 }
849
850 void smpi_mpi_iprobe(int source, int tag, MPI_Comm comm, int* flag, MPI_Status* status){
851
852   MPI_Request request = build_request(NULL, 0, MPI_CHAR, source == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
853                  smpi_group_index(smpi_comm_group(comm), source), smpi_comm_rank(comm), tag, comm, PERSISTENT | RECV);
854
855   // to avoid deadlock, we have to sleep some time here, or the timer won't advance and we will only do iprobe simcalls
856   // (especially when used as a break condition, such as while(MPI_Iprobe(...)) ... )
857   // multiplier to the sleeptime, to increase speed of execution, each failed iprobe will increase it
858   static int nsleeps = 1;
859   if(smpi_iprobe_sleep > 0)  
860     simcall_process_sleep(nsleeps*smpi_iprobe_sleep);
861   // behave like a receive, but don't do it
862   smx_mailbox_t mailbox;
863
864   print_request("New iprobe", request);
865   // We have to test both mailboxes as we don't know if we will receive one one or another
866   if (xbt_cfg_get_int("smpi/async-small-thresh") > 0){
867       mailbox = smpi_process_mailbox_small();
868       XBT_DEBUG("Trying to probe the perm recv mailbox");
869       request->action = simcall_comm_iprobe(mailbox, 0, request->src, request->tag, &match_recv, static_cast<void*>(request));
870   }
871
872   if (request->action == nullptr){
873     mailbox = smpi_process_mailbox();
874     XBT_DEBUG("trying to probe the other mailbox");
875     request->action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv, static_cast<void*>(request));
876   }
877
878   if (request->action != nullptr){
879     simgrid::simix::Comm *sync_comm = static_cast<simgrid::simix::Comm*>(request->action);
880     MPI_Request req                 = static_cast<MPI_Request>(sync_comm->src_data);
881     *flag = 1;
882     if(status != MPI_STATUS_IGNORE && (req->flags & PREPARED) == 0) {
883       status->MPI_SOURCE = smpi_group_rank(smpi_comm_group(comm), req->src);
884       status->MPI_TAG    = req->tag;
885       status->MPI_ERROR  = MPI_SUCCESS;
886       status->count      = req->real_size;
887     }
888     nsleeps = 1;//reset the number of sleeps we will do next time
889   }
890   else {
891     *flag = 0;
892     nsleeps++;
893   }
894   smpi_mpi_request_free(&request);
895
896   return;
897 }
898
899 void smpi_mpi_wait(MPI_Request * request, MPI_Status * status)
900 {
901   print_request("Waiting", *request);
902   if ((*request)->flags & PREPARED) {
903     smpi_empty_status(status);
904     return;
905   }
906
907   if ((*request)->action != NULL)
908     // this is not a detached send
909     simcall_comm_wait((*request)->action, -1.0);
910
911   finish_wait(request, status);
912   if (*request != MPI_REQUEST_NULL && (((*request)->flags & NON_PERSISTENT)!=0))
913       *request = MPI_REQUEST_NULL;
914 }
915
916 int smpi_mpi_waitany(int count, MPI_Request requests[], MPI_Status * status)
917 {
918   xbt_dynar_t comms;
919   int i;
920   int size = 0;
921   int index = MPI_UNDEFINED;
922   int *map;
923
924   if(count > 0) {
925     // Wait for a request to complete
926     comms = xbt_dynar_new(sizeof(smx_synchro_t), NULL);
927     map = xbt_new(int, count);
928     XBT_DEBUG("Wait for one of %d", count);
929     for(i = 0; i < count; i++) {
930       if (requests[i] != MPI_REQUEST_NULL && !(requests[i]->flags & PREPARED) && !(requests[i]->flags & FINISHED)) {
931         if (requests[i]->action != NULL) {
932           XBT_DEBUG("Waiting any %p ", requests[i]);
933           xbt_dynar_push(comms, &requests[i]->action);
934           map[size] = i;
935           size++;
936         }else{
937          //This is a finished detached request, let's return this one
938          size=0;//so we free the dynar but don't do the waitany call
939          index=i;
940          finish_wait(&requests[i], status);//cleanup if refcount = 0
941          if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
942          requests[i]=MPI_REQUEST_NULL;//set to null
943          break;
944          }
945       }
946     }
947     if(size > 0) {
948       i = simcall_comm_waitany(comms);
949
950       // not MPI_UNDEFINED, as this is a simix return code
951       if (i != -1) {
952         index = map[i];
953         finish_wait(&requests[index], status);
954         if (requests[i] != MPI_REQUEST_NULL && (requests[i]->flags & NON_PERSISTENT))
955         requests[index] = MPI_REQUEST_NULL;
956       }
957     }
958     xbt_free(map);
959     xbt_dynar_free(&comms);
960   }
961
962   if (index==MPI_UNDEFINED)
963     smpi_empty_status(status);
964
965   return index;
966 }
967
968 int smpi_mpi_waitall(int count, MPI_Request requests[], MPI_Status status[])
969 {
970   int  index, c;
971   MPI_Status stat;
972   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
973   int retvalue = MPI_SUCCESS;
974   //tag invalid requests in the set
975   if (status != MPI_STATUSES_IGNORE) {
976     for (c = 0; c < count; c++) {
977       if (requests[c] == MPI_REQUEST_NULL || requests[c]->dst == MPI_PROC_NULL || (requests[c]->flags & PREPARED)) {
978         smpi_empty_status(&status[c]);
979       } else if (requests[c]->src == MPI_PROC_NULL) {
980         smpi_empty_status(&status[c]);
981         status[c].MPI_SOURCE = MPI_PROC_NULL;
982       }
983     }
984   }
985   for(c = 0; c < count; c++) {
986
987     if (MC_is_active() || MC_record_replay_is_active()) {
988       smpi_mpi_wait(&requests[c], pstat);
989       index = c;
990     } else {
991       index = smpi_mpi_waitany(count, requests, pstat);
992       if (index == MPI_UNDEFINED)
993         break;
994       if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
995       requests[index]=MPI_REQUEST_NULL;
996     }
997     if (status != MPI_STATUSES_IGNORE) {
998       status[index] = *pstat;
999       if (status[index].MPI_ERROR == MPI_ERR_TRUNCATE)
1000         retvalue = MPI_ERR_IN_STATUS;
1001     }
1002   }
1003
1004   return retvalue;
1005 }
1006
1007 int smpi_mpi_waitsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
1008 {
1009   int i;
1010   int count = 0;
1011   int index;
1012   MPI_Status stat;
1013   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
1014
1015   for(i = 0; i < incount; i++)
1016   {
1017     index=smpi_mpi_waitany(incount, requests, pstat);
1018     if(index!=MPI_UNDEFINED){
1019       indices[count] = index;
1020       count++;
1021       if(status != MPI_STATUSES_IGNORE) {
1022         status[index] = *pstat;
1023       }
1024      if (requests[index] != MPI_REQUEST_NULL && (requests[index]->flags & NON_PERSISTENT))
1025      requests[index]=MPI_REQUEST_NULL;
1026     }else{
1027       return MPI_UNDEFINED;
1028     }
1029   }
1030   return count;
1031 }
1032
1033 int smpi_mpi_testsome(int incount, MPI_Request requests[], int *indices, MPI_Status status[])
1034 {
1035   int i;
1036   int count = 0;
1037   int count_dead = 0;
1038   MPI_Status stat;
1039   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
1040
1041   for(i = 0; i < incount; i++) {
1042     if((requests[i] != MPI_REQUEST_NULL)) {
1043       if(smpi_mpi_test(&requests[i], pstat)) {
1044          indices[i] = 1;
1045          count++;
1046          if(status != MPI_STATUSES_IGNORE) {
1047            status[i] = *pstat;
1048          }
1049          if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->flags & NON_PERSISTENT)
1050          requests[i]=MPI_REQUEST_NULL;
1051       }
1052     }else{
1053       count_dead++;
1054     }
1055   }
1056   if(count_dead==incount)
1057     return MPI_UNDEFINED;
1058   else return count;
1059 }
1060
1061 void smpi_mpi_bcast(void *buf, int count, MPI_Datatype datatype, int root, MPI_Comm comm)
1062 {
1063     smpi_coll_tuned_bcast_binomial_tree(buf, count, datatype, root, comm);
1064 }
1065
1066 void smpi_mpi_barrier(MPI_Comm comm)
1067 {
1068     smpi_coll_tuned_barrier_ompi_basic_linear(comm);
1069 }
1070
1071 void smpi_mpi_gather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1072                      void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm)
1073 {
1074   int system_tag = COLL_TAG_GATHER;
1075   int rank, size, src, index;
1076   MPI_Aint lb = 0, recvext = 0;
1077   MPI_Request *requests;
1078
1079   rank = smpi_comm_rank(comm);
1080   size = smpi_comm_size(comm);
1081   if(rank != root) {
1082     // Send buffer to root
1083     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1084   } else {
1085     smpi_datatype_extent(recvtype, &lb, &recvext);
1086     // Local copy from root
1087     smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char*>(recvbuf) + root * recvcount * recvext, recvcount, recvtype);
1088     // Receive buffers from senders
1089     requests = xbt_new(MPI_Request, size - 1);
1090     index = 0;
1091     for(src = 0; src < size; src++) {
1092       if(src != root) {
1093         requests[index] = smpi_irecv_init(static_cast<char*>(recvbuf) + src * recvcount * recvext, recvcount, recvtype,
1094                                           src, system_tag, comm);
1095         index++;
1096       }
1097     }
1098     // Wait for completion of irecv's.
1099     smpi_mpi_startall(size - 1, requests);
1100     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1101     for(src = 0; src < size-1; src++) {
1102       smpi_mpi_request_free(&requests[src]);
1103     }
1104     xbt_free(requests);
1105   }
1106 }
1107
1108 void smpi_mpi_reduce_scatter(void *sendbuf, void *recvbuf, int *recvcounts, MPI_Datatype datatype, MPI_Op op,
1109                              MPI_Comm comm)
1110 {
1111     int i, size, count;
1112     int *displs;
1113     int rank = smpi_comm_rank(comm);
1114     void *tmpbuf;
1115
1116     /* arbitrarily choose root as rank 0 */
1117     size = smpi_comm_size(comm);
1118     count = 0;
1119     displs = xbt_new(int, size);
1120     for (i = 0; i < size; i++) {
1121       displs[i] = count;
1122       count += recvcounts[i];
1123     }
1124     tmpbuf=static_cast<void*>(smpi_get_tmp_sendbuffer(count*smpi_datatype_get_extent(datatype)));
1125
1126     mpi_coll_reduce_fun(sendbuf, tmpbuf, count, datatype, op, 0, comm);
1127     smpi_mpi_scatterv(tmpbuf, recvcounts, displs, datatype, recvbuf, recvcounts[rank], datatype, 0, comm);
1128     xbt_free(displs);
1129     smpi_free_tmp_buffer(tmpbuf);
1130 }
1131
1132 void smpi_mpi_gatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int *recvcounts, int *displs,
1133                       MPI_Datatype recvtype, int root, MPI_Comm comm)
1134 {
1135   int system_tag = COLL_TAG_GATHERV;
1136   int rank, size, src, index;
1137   MPI_Aint lb = 0, recvext = 0;
1138   MPI_Request *requests;
1139
1140   rank = smpi_comm_rank(comm);
1141   size = smpi_comm_size(comm);
1142   if(rank != root) {
1143     // Send buffer to root
1144     smpi_mpi_send(sendbuf, sendcount, sendtype, root, system_tag, comm);
1145   } else {
1146     smpi_datatype_extent(recvtype, &lb, &recvext);
1147     // Local copy from root
1148     smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char*>(recvbuf) + displs[root] * recvext,
1149                        recvcounts[root], recvtype);
1150     // Receive buffers from senders
1151     requests = xbt_new(MPI_Request, size - 1);
1152     index = 0;
1153     for(src = 0; src < size; src++) {
1154       if(src != root) {
1155         requests[index] = smpi_irecv_init(static_cast<char*>(recvbuf) + displs[src] * recvext,
1156                           recvcounts[src], recvtype, src, system_tag, comm);
1157         index++;
1158       }
1159     }
1160     // Wait for completion of irecv's.
1161     smpi_mpi_startall(size - 1, requests);
1162     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1163     for(src = 0; src < size-1; src++) {
1164       smpi_mpi_request_free(&requests[src]);
1165     }
1166     xbt_free(requests);
1167   }
1168 }
1169
1170 void smpi_mpi_allgather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1171                         void *recvbuf,int recvcount, MPI_Datatype recvtype, MPI_Comm comm)
1172 {
1173   int system_tag = COLL_TAG_ALLGATHER;
1174   int rank, size, other, index;
1175   MPI_Aint lb = 0, recvext = 0;
1176   MPI_Request *requests;
1177
1178   rank = smpi_comm_rank(comm);
1179   size = smpi_comm_size(comm);
1180   // FIXME: check for errors
1181   smpi_datatype_extent(recvtype, &lb, &recvext);
1182   // Local copy from self
1183   smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char *>(recvbuf) + rank * recvcount * recvext, recvcount, recvtype);
1184   // Send/Recv buffers to/from others;
1185   requests = xbt_new(MPI_Request, 2 * (size - 1));
1186   index = 0;
1187   for(other = 0; other < size; other++) {
1188     if(other != rank) {
1189       requests[index] = smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag,comm);
1190       index++;
1191       requests[index] = smpi_irecv_init(static_cast<char *>(recvbuf) + other * recvcount * recvext, recvcount, recvtype, other,
1192                                         system_tag, comm);
1193       index++;
1194     }
1195   }
1196   // Wait for completion of all comms.
1197   smpi_mpi_startall(2 * (size - 1), requests);
1198   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1199   for(other = 0; other < 2*(size-1); other++) {
1200     smpi_mpi_request_free(&requests[other]);
1201   }
1202   xbt_free(requests);
1203 }
1204
1205 void smpi_mpi_allgatherv(void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf,
1206                          int *recvcounts, int *displs, MPI_Datatype recvtype, MPI_Comm comm)
1207 {
1208   int system_tag = COLL_TAG_ALLGATHERV;
1209   int rank, size, other, index;
1210   MPI_Aint lb = 0, recvext = 0;
1211   MPI_Request *requests;
1212
1213   rank = smpi_comm_rank(comm);
1214   size = smpi_comm_size(comm);
1215   smpi_datatype_extent(recvtype, &lb, &recvext);
1216   // Local copy from self
1217   smpi_datatype_copy(sendbuf, sendcount, sendtype, static_cast<char *>(recvbuf) + displs[rank] * recvext,recvcounts[rank], recvtype);
1218   // Send buffers to others;
1219   requests = xbt_new(MPI_Request, 2 * (size - 1));
1220   index = 0;
1221   for(other = 0; other < size; other++) {
1222     if(other != rank) {
1223       requests[index] =
1224         smpi_isend_init(sendbuf, sendcount, sendtype, other, system_tag, comm);
1225       index++;
1226       requests[index] = smpi_irecv_init(static_cast<char *>(recvbuf) + displs[other] * recvext, recvcounts[other],
1227                           recvtype, other, system_tag, comm);
1228       index++;
1229     }
1230   }
1231   // Wait for completion of all comms.
1232   smpi_mpi_startall(2 * (size - 1), requests);
1233   smpi_mpi_waitall(2 * (size - 1), requests, MPI_STATUS_IGNORE);
1234   for(other = 0; other < 2*(size-1); other++) {
1235     smpi_mpi_request_free(&requests[other]);
1236   }
1237   xbt_free(requests);
1238 }
1239
1240 void smpi_mpi_scatter(void *sendbuf, int sendcount, MPI_Datatype sendtype,
1241                       void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm)
1242 {
1243   int system_tag = COLL_TAG_SCATTER;
1244   int rank, size, dst, index;
1245   MPI_Aint lb = 0, sendext = 0;
1246   MPI_Request *requests;
1247
1248   rank = smpi_comm_rank(comm);
1249   size = smpi_comm_size(comm);
1250   if(rank != root) {
1251     // Recv buffer from root
1252     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm, MPI_STATUS_IGNORE);
1253   } else {
1254     smpi_datatype_extent(sendtype, &lb, &sendext);
1255     // Local copy from root
1256     if(recvbuf!=MPI_IN_PLACE){
1257         smpi_datatype_copy(static_cast<char *>(sendbuf) + root * sendcount * sendext,
1258                            sendcount, sendtype, recvbuf, recvcount, recvtype);
1259     }
1260     // Send buffers to receivers
1261     requests = xbt_new(MPI_Request, size - 1);
1262     index = 0;
1263     for(dst = 0; dst < size; dst++) {
1264       if(dst != root) {
1265         requests[index] = smpi_isend_init(static_cast<char *>(sendbuf) + dst * sendcount * sendext, sendcount, sendtype, dst,
1266                                           system_tag, comm);
1267         index++;
1268       }
1269     }
1270     // Wait for completion of isend's.
1271     smpi_mpi_startall(size - 1, requests);
1272     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1273     for(dst = 0; dst < size-1; dst++) {
1274       smpi_mpi_request_free(&requests[dst]);
1275     }
1276     xbt_free(requests);
1277   }
1278 }
1279
1280 void smpi_mpi_scatterv(void *sendbuf, int *sendcounts, int *displs, MPI_Datatype sendtype, void *recvbuf, int recvcount,
1281                        MPI_Datatype recvtype, int root, MPI_Comm comm)
1282 {
1283   int system_tag = COLL_TAG_SCATTERV;
1284   int rank, size, dst, index;
1285   MPI_Aint lb = 0, sendext = 0;
1286   MPI_Request *requests;
1287
1288   rank = smpi_comm_rank(comm);
1289   size = smpi_comm_size(comm);
1290   if(rank != root) {
1291     // Recv buffer from root
1292     smpi_mpi_recv(recvbuf, recvcount, recvtype, root, system_tag, comm, MPI_STATUS_IGNORE);
1293   } else {
1294     smpi_datatype_extent(sendtype, &lb, &sendext);
1295     // Local copy from root
1296     if(recvbuf!=MPI_IN_PLACE){
1297       smpi_datatype_copy(static_cast<char *>(sendbuf) + displs[root] * sendext, sendcounts[root],
1298                        sendtype, recvbuf, recvcount, recvtype);
1299     }
1300     // Send buffers to receivers
1301     requests = xbt_new(MPI_Request, size - 1);
1302     index = 0;
1303     for(dst = 0; dst < size; dst++) {
1304       if(dst != root) {
1305         requests[index] = smpi_isend_init(static_cast<char *>(sendbuf) + displs[dst] * sendext, sendcounts[dst],
1306                             sendtype, dst, system_tag, comm);
1307         index++;
1308       }
1309     }
1310     // Wait for completion of isend's.
1311     smpi_mpi_startall(size - 1, requests);
1312     smpi_mpi_waitall(size - 1, requests, MPI_STATUS_IGNORE);
1313     for(dst = 0; dst < size-1; dst++) {
1314       smpi_mpi_request_free(&requests[dst]);
1315     }
1316     xbt_free(requests);
1317   }
1318 }
1319
1320 void smpi_mpi_reduce(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root,
1321                      MPI_Comm comm)
1322 {
1323   int system_tag = COLL_TAG_REDUCE;
1324   int rank, size, src, index;
1325   MPI_Aint lb = 0, dataext = 0;
1326   MPI_Request *requests;
1327   void **tmpbufs;
1328
1329   char* sendtmpbuf = static_cast<char *>(sendbuf);
1330
1331
1332   rank = smpi_comm_rank(comm);
1333   size = smpi_comm_size(comm);
1334   //non commutative case, use a working algo from openmpi
1335   if(!smpi_op_is_commute(op)){
1336     smpi_coll_tuned_reduce_ompi_basic_linear(sendtmpbuf, recvbuf, count, datatype, op, root, comm);
1337     return;
1338   }
1339
1340   if( sendbuf == MPI_IN_PLACE ) {
1341     sendtmpbuf = static_cast<char *>(smpi_get_tmp_sendbuffer(count*smpi_datatype_get_extent(datatype)));
1342     smpi_datatype_copy(recvbuf, count, datatype,sendtmpbuf, count, datatype);
1343   }
1344   
1345   if(rank != root) {
1346     // Send buffer to root
1347     smpi_mpi_send(sendtmpbuf, count, datatype, root, system_tag, comm);
1348   } else {
1349     smpi_datatype_extent(datatype, &lb, &dataext);
1350     // Local copy from root
1351     if (sendtmpbuf != NULL && recvbuf != NULL)
1352       smpi_datatype_copy(sendtmpbuf, count, datatype, recvbuf, count, datatype);
1353     // Receive buffers from senders
1354     requests = xbt_new(MPI_Request, size - 1);
1355     tmpbufs = xbt_new(void *, size - 1);
1356     index = 0;
1357     for(src = 0; src < size; src++) {
1358       if(src != root) {
1359          if (!smpi_process_get_replaying())
1360           tmpbufs[index] = xbt_malloc(count * dataext);
1361          else
1362            tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1363         requests[index] =
1364           smpi_irecv_init(tmpbufs[index], count, datatype, src, system_tag, comm);
1365         index++;
1366       }
1367     }
1368     // Wait for completion of irecv's.
1369     smpi_mpi_startall(size - 1, requests);
1370     for(src = 0; src < size - 1; src++) {
1371       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1372       XBT_DEBUG("finished waiting any request with index %d", index);
1373       if(index == MPI_UNDEFINED) {
1374         break;
1375       }else{
1376         smpi_mpi_request_free(&requests[index]);
1377       }
1378       if(op) /* op can be MPI_OP_NULL that does nothing */
1379         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1380     }
1381       for(index = 0; index < size - 1; index++) {
1382         smpi_free_tmp_buffer(tmpbufs[index]);
1383       }
1384     xbt_free(tmpbufs);
1385     xbt_free(requests);
1386
1387   }
1388   if( sendbuf == MPI_IN_PLACE ) {
1389     smpi_free_tmp_buffer(sendtmpbuf);
1390   }
1391 }
1392
1393 void smpi_mpi_allreduce(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1394 {
1395   smpi_mpi_reduce(sendbuf, recvbuf, count, datatype, op, 0, comm);
1396   smpi_mpi_bcast(recvbuf, count, datatype, 0, comm);
1397 }
1398
1399 void smpi_mpi_scan(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1400 {
1401   int system_tag = -888;
1402   int rank, size, other, index;
1403   MPI_Aint lb = 0, dataext = 0;
1404   MPI_Request *requests;
1405   void **tmpbufs;
1406
1407   rank = smpi_comm_rank(comm);
1408   size = smpi_comm_size(comm);
1409
1410   smpi_datatype_extent(datatype, &lb, &dataext);
1411
1412   // Local copy from self
1413   smpi_datatype_copy(sendbuf, count, datatype, recvbuf, count, datatype);
1414
1415   // Send/Recv buffers to/from others;
1416   requests = xbt_new(MPI_Request, size - 1);
1417   tmpbufs = xbt_new(void *, rank);
1418   index = 0;
1419   for(other = 0; other < rank; other++) {
1420     tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1421     requests[index] = smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag, comm);
1422     index++;
1423   }
1424   for(other = rank + 1; other < size; other++) {
1425     requests[index] = smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1426     index++;
1427   }
1428   // Wait for completion of all comms.
1429   smpi_mpi_startall(size - 1, requests);
1430
1431   if(smpi_op_is_commute(op)){
1432     for(other = 0; other < size - 1; other++) {
1433       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1434       if(index == MPI_UNDEFINED) {
1435         break;
1436       }
1437       if(index < rank) {
1438         // #Request is below rank: it's a irecv
1439         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1440       }
1441     }
1442   }else{
1443     //non commutative case, wait in order
1444     for(other = 0; other < size - 1; other++) {
1445       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1446       if(index < rank) {
1447         smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1448       }
1449     }
1450   }
1451   for(index = 0; index < rank; index++) {
1452     smpi_free_tmp_buffer(tmpbufs[index]);
1453   }
1454   for(index = 0; index < size-1; index++) {
1455     smpi_mpi_request_free(&requests[index]);
1456   }
1457   xbt_free(tmpbufs);
1458   xbt_free(requests);
1459 }
1460
1461 void smpi_mpi_exscan(void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
1462 {
1463   int system_tag = -888;
1464   int rank, size, other, index;
1465   MPI_Aint lb = 0, dataext = 0;
1466   MPI_Request *requests;
1467   void **tmpbufs;
1468   int recvbuf_is_empty=1;
1469   rank = smpi_comm_rank(comm);
1470   size = smpi_comm_size(comm);
1471
1472   smpi_datatype_extent(datatype, &lb, &dataext);
1473
1474   // Send/Recv buffers to/from others;
1475   requests = xbt_new(MPI_Request, size - 1);
1476   tmpbufs = xbt_new(void *, rank);
1477   index = 0;
1478   for(other = 0; other < rank; other++) {
1479     tmpbufs[index] = smpi_get_tmp_sendbuffer(count * dataext);
1480     requests[index] =
1481       smpi_irecv_init(tmpbufs[index], count, datatype, other, system_tag, comm);
1482     index++;
1483   }
1484   for(other = rank + 1; other < size; other++) {
1485     requests[index] =
1486       smpi_isend_init(sendbuf, count, datatype, other, system_tag, comm);
1487     index++;
1488   }
1489   // Wait for completion of all comms.
1490   smpi_mpi_startall(size - 1, requests);
1491   if(smpi_op_is_commute(op)){
1492     for(other = 0; other < size - 1; other++) {
1493       index = smpi_mpi_waitany(size - 1, requests, MPI_STATUS_IGNORE);
1494       if(index == MPI_UNDEFINED) {
1495         break;
1496       }
1497       if(index < rank) {
1498         if(recvbuf_is_empty){
1499           smpi_datatype_copy(tmpbufs[index], count, datatype, recvbuf, count, datatype);
1500           recvbuf_is_empty=0;
1501         }else
1502         // #Request is below rank: it's a irecv
1503         smpi_op_apply(op, tmpbufs[index], recvbuf, &count, &datatype);
1504       }
1505     }
1506   }else{
1507     //non commutative case, wait in order
1508     for(other = 0; other < size - 1; other++) {
1509       smpi_mpi_wait(&(requests[other]), MPI_STATUS_IGNORE);
1510       if(index < rank) {
1511           if(recvbuf_is_empty){
1512             smpi_datatype_copy(tmpbufs[other], count, datatype, recvbuf, count, datatype);
1513             recvbuf_is_empty=0;
1514           }else smpi_op_apply(op, tmpbufs[other], recvbuf, &count, &datatype);
1515       }
1516     }
1517   }
1518   for(index = 0; index < rank; index++) {
1519     smpi_free_tmp_buffer(tmpbufs[index]);
1520   }
1521   for(index = 0; index < size-1; index++) {
1522     smpi_mpi_request_free(&requests[index]);
1523   }
1524   xbt_free(tmpbufs);
1525   xbt_free(requests);
1526 }