Logo AND Algorithmique Numérique Distribuée

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