Logo AND Algorithmique Numérique Distribuée

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