Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
rename method
[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 "src/smpi/smpi_group.hpp"
21 #include "colls/colls.h"
22 #include <simgrid/s4u/host.hpp>
23
24 #include "src/kernel/activity/SynchroComm.hpp"
25
26 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_base, smpi, "Logging specific to SMPI (base)");
27
28 extern void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t);
29
30
31 static int match_recv(void* a, void* b, smx_activity_t ignored) {
32   MPI_Request ref = static_cast<MPI_Request>(a);
33   MPI_Request req = static_cast<MPI_Request>(b);
34   XBT_DEBUG("Trying to match a recv of src %d against %d, tag %d against %d",ref->src,req->src, ref->tag, req->tag);
35
36   xbt_assert(ref, "Cannot match recv against null reference");
37   xbt_assert(req, "Cannot match recv against null request");
38   if((ref->src == MPI_ANY_SOURCE || req->src == ref->src)
39     && ((ref->tag == MPI_ANY_TAG && req->tag >=0) || req->tag == ref->tag)){
40     //we match, we can transfer some values
41     if(ref->src == MPI_ANY_SOURCE)
42       ref->real_src = req->src;
43     if(ref->tag == MPI_ANY_TAG)
44       ref->real_tag = req->tag;
45     if(ref->real_size < req->real_size) 
46       ref->truncated = 1;
47     if(req->detached==1)
48       ref->detached_sender=req; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
49     XBT_DEBUG("match succeeded");
50     return 1;
51   }else return 0;
52 }
53
54 static int match_send(void* a, void* b,smx_activity_t ignored) {
55   MPI_Request ref = static_cast<MPI_Request>(a);
56   MPI_Request req = static_cast<MPI_Request>(b);
57   XBT_DEBUG("Trying to match a send of src %d against %d, tag %d against %d",ref->src,req->src, ref->tag, req->tag);
58   xbt_assert(ref, "Cannot match send against null reference");
59   xbt_assert(req, "Cannot match send against null request");
60
61   if((req->src == MPI_ANY_SOURCE || req->src == ref->src)
62       && ((req->tag == MPI_ANY_TAG && ref->tag >=0)|| req->tag == ref->tag)){
63     if(req->src == MPI_ANY_SOURCE)
64       req->real_src = ref->src;
65     if(req->tag == MPI_ANY_TAG)
66       req->real_tag = ref->tag;
67     if(req->real_size < ref->real_size)
68       req->truncated = 1;
69     if(ref->detached==1)
70       req->detached_sender=ref; //tie the sender to the receiver, as it is detached and has to be freed in the receiver
71     XBT_DEBUG("match succeeded");
72     return 1;
73   } else
74     return 0;
75 }
76
77 std::vector<s_smpi_factor_t> smpi_os_values;
78 std::vector<s_smpi_factor_t> smpi_or_values;
79 std::vector<s_smpi_factor_t> smpi_ois_values;
80
81 static simgrid::config::Flag<double> smpi_wtime_sleep(
82   "smpi/wtime", "Minimum time to inject inside a call to MPI_Wtime", 0.0);
83 static simgrid::config::Flag<double> smpi_init_sleep(
84   "smpi/init", "Time to inject inside a call to MPI_Init", 0.0);
85 static simgrid::config::Flag<double> smpi_iprobe_sleep(
86   "smpi/iprobe", "Minimum time to inject inside a call to MPI_Iprobe", 1e-4);
87 static simgrid::config::Flag<double> smpi_test_sleep(
88   "smpi/test", "Minimum time to inject inside a call to MPI_Test", 1e-4);
89
90
91 static double smpi_os(size_t size)
92 {
93   if (smpi_os_values.empty()) {
94     smpi_os_values = parse_factor(xbt_cfg_get_string("smpi/os"));
95   }
96   double current=smpi_os_values.empty()?0.0:smpi_os_values[0].values[0]+smpi_os_values[0].values[1]*size;
97   // Iterate over all the sections that were specified and find the right
98   // value. (fact.factor represents the interval sizes; we want to find the
99   // section that has fact.factor <= size and no other such fact.factor <= size)
100   // Note: parse_factor() (used before) already sorts the vector we iterate over!
101   for (auto& fact : smpi_os_values) {
102     if (size <= fact.factor) { // Values already too large, use the previously computed value of current!
103       XBT_DEBUG("os : %zu <= %zu return %.10f", size, fact.factor, current);
104       return current;
105     }else{
106       // If the next section is too large, the current section must be used.
107       // Hence, save the cost, as we might have to use it.
108       current = fact.values[0]+fact.values[1]*size;
109     }
110   }
111   XBT_DEBUG("Searching for smpi/os: %zu is larger than the largest boundary, return %.10f", size, current);
112
113   return current;
114 }
115
116 static double smpi_ois(size_t size)
117 {
118   if (smpi_ois_values.empty()) {
119     smpi_ois_values = parse_factor(xbt_cfg_get_string("smpi/ois"));
120   }
121   double current=smpi_ois_values.empty()?0.0:smpi_ois_values[0].values[0]+smpi_ois_values[0].values[1]*size;
122   // Iterate over all the sections that were specified and find the right value. (fact.factor represents the interval
123   // sizes; we want to find the section that has fact.factor <= size and no other such fact.factor <= size)
124   // Note: parse_factor() (used before) already sorts the vector we iterate over!
125   for (auto& fact : smpi_ois_values) {
126     if (size <= fact.factor) { // Values already too large, use the previously  computed value of current!
127       XBT_DEBUG("ois : %zu <= %zu return %.10f", size, fact.factor, current);
128       return current;
129     }else{
130       // If the next section is too large, the current section must be used.
131       // Hence, save the cost, as we might have to use it.
132       current = fact.values[0]+fact.values[1]*size;
133     }
134   }
135   XBT_DEBUG("Searching for smpi/ois: %zu is larger than the largest boundary, return %.10f", size, current);
136
137   return current;
138 }
139
140 static double smpi_or(size_t size)
141 {
142   if (smpi_or_values.empty()) {
143     smpi_or_values = parse_factor(xbt_cfg_get_string("smpi/or"));
144   }
145   
146   double current=smpi_or_values.empty()?0.0:smpi_or_values.front().values[0]+smpi_or_values.front().values[1]*size;
147
148   // Iterate over all the sections that were specified and find the right value. (fact.factor represents the interval
149   // sizes; we want to find the section that has fact.factor <= size and no other such fact.factor <= size)
150   // Note: parse_factor() (used before) already sorts the vector we iterate over!
151   for (auto fact : smpi_or_values) {
152     if (size <= fact.factor) { // Values already too large, use the previously computed value of current!
153       XBT_DEBUG("or : %zu <= %zu return %.10f", size, fact.factor, current);
154       return current;
155     } else {
156       // If the next section is too large, the current section must be used.
157       // Hence, save the cost, as we might have to use it.
158       current=fact.values[0]+fact.values[1]*size;
159     }
160   }
161   XBT_DEBUG("smpi_or: %zu is larger than largest boundary, return %.10f", size, current);
162
163   return current;
164 }
165
166 void smpi_mpi_init() {
167   if(smpi_init_sleep > 0) 
168     simcall_process_sleep(smpi_init_sleep);
169 }
170
171 double smpi_mpi_wtime(){
172   double time;
173   if (smpi_process_initialized() != 0 && smpi_process_finalized() == 0 && smpi_process_get_sampling() == 0) {
174     smpi_bench_end();
175     time = SIMIX_get_clock();
176     // to avoid deadlocks if used as a break condition, such as
177     //     while (MPI_Wtime(...) < time_limit) {
178     //       ....
179     //     }
180     // because the time will not normally advance when only calls to MPI_Wtime
181     // are made -> deadlock (MPI_Wtime never reaches the time limit)
182     if(smpi_wtime_sleep > 0) 
183       simcall_process_sleep(smpi_wtime_sleep);
184     smpi_bench_begin();
185   } else {
186     time = SIMIX_get_clock();
187   }
188   return time;
189 }
190
191 static MPI_Request build_request(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
192                                  unsigned flags)
193 {
194   MPI_Request request = nullptr;
195
196   void *old_buf = nullptr;
197
198   request = xbt_new(s_smpi_mpi_request_t, 1);
199
200   s_smpi_subtype_t *subtype = static_cast<s_smpi_subtype_t*>(datatype->substruct);
201
202   if((((flags & RECV) != 0) && ((flags & ACCUMULATE) !=0)) || (datatype->sizeof_substruct != 0)){
203     // This part handles the problem of non-contiguous memory
204     old_buf = buf;
205     buf = count==0 ? nullptr : xbt_malloc(count*smpi_datatype_size(datatype));
206     if ((datatype->sizeof_substruct != 0) && ((flags & SEND) != 0)) {
207       subtype->serialize(old_buf, buf, count, datatype->substruct);
208     }
209   }
210
211   request->buf      = buf;
212   // This part handles the problem of non-contiguous memory (for the unserialisation at the reception)
213   request->old_buf  = old_buf;
214   request->old_type = datatype;
215
216   request->size = smpi_datatype_size(datatype) * count;
217   smpi_datatype_use(datatype);
218   request->src  = src;
219   request->dst  = dst;
220   request->tag  = tag;
221   request->comm = comm;
222   smpi_comm_use(request->comm);
223   request->action          = nullptr;
224   request->flags           = flags;
225   request->detached        = 0;
226   request->detached_sender = nullptr;
227   request->real_src        = 0;
228   request->truncated       = 0;
229   request->real_size       = 0;
230   request->real_tag        = 0;
231   if (flags & PERSISTENT)
232     request->refcount = 1;
233   else
234     request->refcount = 0;
235   request->op   = MPI_REPLACE;
236   request->send = 0;
237   request->recv = 0;
238
239   return request;
240 }
241
242 void smpi_empty_status(MPI_Status * status)
243 {
244   if(status != MPI_STATUS_IGNORE) {
245     status->MPI_SOURCE = MPI_ANY_SOURCE;
246     status->MPI_TAG = MPI_ANY_TAG;
247     status->MPI_ERROR = MPI_SUCCESS;
248     status->count=0;
249   }
250 }
251
252 static void smpi_mpi_request_free_voidp(void* request)
253 {
254   MPI_Request req = static_cast<MPI_Request>(request);
255   smpi_mpi_request_free(&req);
256 }
257
258 /* MPI Low level calls */
259 MPI_Request smpi_mpi_send_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
260 {
261   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
262   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
263                           smpi_comm_group(comm)->index(dst), tag, comm, PERSISTENT | SEND | PREPARED);
264   return request;
265 }
266
267 MPI_Request smpi_mpi_ssend_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
268 {
269   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
270   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
271                         smpi_comm_group(comm)->index(dst), tag, comm, PERSISTENT | SSEND | SEND | PREPARED);
272   return request;
273 }
274
275 MPI_Request smpi_mpi_recv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
276 {
277   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
278   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,
279                           src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE : smpi_comm_group(comm)->index(src),
280                           smpi_process_index(), tag, comm, PERSISTENT | RECV | PREPARED);
281   return request;
282 }
283
284 void smpi_mpi_start(MPI_Request request)
285 {
286   smx_mailbox_t mailbox;
287
288   xbt_assert(request->action == nullptr, "Cannot (re-)start unfinished communication");
289   request->flags &= ~PREPARED;
290   request->flags &= ~FINISHED;
291   request->refcount++;
292
293   if ((request->flags & RECV) != 0) {
294     print_request("New recv", request);
295
296     int async_small_thresh = xbt_cfg_get_int("smpi/async-small-thresh");
297
298     xbt_mutex_t mut = smpi_process_mailboxes_mutex();
299     if (async_small_thresh != 0 || (request->flags & RMA) != 0)
300       xbt_mutex_acquire(mut);
301
302     if (async_small_thresh == 0 && (request->flags & RMA) == 0 ) {
303       mailbox = smpi_process_mailbox();
304     } 
305     else if (((request->flags & RMA) != 0) || static_cast<int>(request->size) < async_small_thresh) {
306       //We have to check both mailboxes (because SSEND messages are sent to the large mbox).
307       //begin with the more appropriate one : the small one.
308       mailbox = smpi_process_mailbox_small();
309       XBT_DEBUG("Is there a corresponding send already posted in the small mailbox %p (in case of SSEND)?", mailbox);
310       smx_activity_t action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv,
311                                                   static_cast<void*>(request));
312
313       if (action == nullptr) {
314         mailbox = smpi_process_mailbox();
315         XBT_DEBUG("No, nothing in the small mailbox test the other one : %p", mailbox);
316         action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv, static_cast<void*>(request));
317         if (action == nullptr) {
318           XBT_DEBUG("Still nothing, switch back to the small mailbox : %p", mailbox);
319           mailbox = smpi_process_mailbox_small();
320         }
321       } else {
322         XBT_DEBUG("yes there was something for us in the large mailbox");
323       }
324     } else {
325       mailbox = smpi_process_mailbox_small();
326       XBT_DEBUG("Is there a corresponding send already posted the small mailbox?");
327       smx_activity_t action = simcall_comm_iprobe(mailbox, 0, request->src,request->tag, &match_recv, (void*)request);
328
329       if (action == nullptr) {
330         XBT_DEBUG("No, nothing in the permanent receive mailbox");
331         mailbox = smpi_process_mailbox();
332       } else {
333         XBT_DEBUG("yes there was something for us in the small mailbox");
334       }
335     }
336
337     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
338     request->real_size=request->size;
339     request->action = simcall_comm_irecv(SIMIX_process_self(), mailbox, request->buf, &request->real_size, &match_recv,
340                                          ! smpi_process_get_replaying()? smpi_comm_copy_data_callback
341                                          : &smpi_comm_null_copy_buffer_callback, request, -1.0);
342     XBT_DEBUG("recv simcall posted");
343
344     if (async_small_thresh != 0 || (request->flags & RMA) != 0 )
345       xbt_mutex_release(mut);
346   } else { /* the RECV flag was not set, so this is a send */
347     int receiver = request->dst;
348
349     int rank = request->src;
350     if (TRACE_smpi_view_internals()) {
351       TRACE_smpi_send(rank, rank, receiver, request->tag, request->size);
352     }
353     print_request("New send", request);
354
355     void* buf = request->buf;
356     if ((request->flags & SSEND) == 0 && ( (request->flags & RMA) != 0
357         || static_cast<int>(request->size) < xbt_cfg_get_int("smpi/send-is-detached-thresh") ) ) {
358       void *oldbuf = nullptr;
359       request->detached = 1;
360       XBT_DEBUG("Send request %p is detached", request);
361       request->refcount++;
362       if(request->old_type->sizeof_substruct == 0){
363         oldbuf = request->buf;
364         if (!smpi_process_get_replaying() && oldbuf != nullptr && request->size!=0){
365           if((smpi_privatize_global_variables != 0)
366             && (static_cast<char*>(request->buf) >= smpi_start_data_exe)
367             && (static_cast<char*>(request->buf) < smpi_start_data_exe + smpi_size_data_exe )){
368             XBT_DEBUG("Privatization : We are sending from a zone inside global memory. Switch data segment ");
369             smpi_switch_data_segment(request->src);
370           }
371           buf = xbt_malloc(request->size);
372           memcpy(buf,oldbuf,request->size);
373           XBT_DEBUG("buf %p copied into %p",oldbuf,buf);
374         }
375       }
376     }
377
378     //if we are giving back the control to the user without waiting for completion, we have to inject timings
379     double sleeptime = 0.0;
380     if(request->detached != 0 || ((request->flags & (ISEND|SSEND)) != 0)){// issend should be treated as isend
381       //isend and send timings may be different
382       sleeptime = ((request->flags & ISEND) != 0) ? smpi_ois(request->size) : smpi_os(request->size);
383     }
384
385     if(sleeptime > 0.0){
386       simcall_process_sleep(sleeptime);
387       XBT_DEBUG("sending size of %zu : sleep %f ", request->size, sleeptime);
388     }
389
390     int async_small_thresh = xbt_cfg_get_int("smpi/async-small-thresh");
391
392     xbt_mutex_t mut=smpi_process_remote_mailboxes_mutex(receiver);
393
394     if (async_small_thresh != 0 || (request->flags & RMA) != 0)
395       xbt_mutex_acquire(mut);
396
397     if (!(async_small_thresh != 0 || (request->flags & RMA) !=0)) {
398       mailbox = smpi_process_remote_mailbox(receiver);
399     } else if (((request->flags & RMA) != 0) || static_cast<int>(request->size) < async_small_thresh) { // eager mode
400       mailbox = smpi_process_remote_mailbox(receiver);
401       XBT_DEBUG("Is there a corresponding recv already posted in the large mailbox %p?", mailbox);
402       smx_activity_t action = simcall_comm_iprobe(mailbox, 1,request->dst, request->tag, &match_send,
403                                                   static_cast<void*>(request));
404       if (action == nullptr) {
405         if ((request->flags & SSEND) == 0){
406           mailbox = smpi_process_remote_mailbox_small(receiver);
407           XBT_DEBUG("No, nothing in the large mailbox, message is to be sent on the small one %p", mailbox);
408         } else {
409           mailbox = smpi_process_remote_mailbox_small(receiver);
410           XBT_DEBUG("SSEND : Is there a corresponding recv already posted in the small mailbox %p?", mailbox);
411           action = simcall_comm_iprobe(mailbox, 1,request->dst, request->tag, &match_send, static_cast<void*>(request));
412           if (action == nullptr) {
413             XBT_DEBUG("No, we are first, send to large mailbox");
414             mailbox = smpi_process_remote_mailbox(receiver);
415           }
416         }
417       } else {
418         XBT_DEBUG("Yes there was something for us in the large mailbox");
419       }
420     } else {
421       mailbox = smpi_process_remote_mailbox(receiver);
422       XBT_DEBUG("Send request %p is in the large mailbox %p (buf: %p)",mailbox, request,request->buf);
423     }
424
425     // we make a copy here, as the size is modified by simix, and we may reuse the request in another receive later
426     request->real_size=request->size;
427     request->action = simcall_comm_isend(SIMIX_process_from_PID(request->src+1), mailbox, request->size, -1.0,
428                                          buf, request->real_size, &match_send,
429                          &xbt_free_f, // how to free the userdata if a detached send fails
430                          !smpi_process_get_replaying() ? smpi_comm_copy_data_callback
431                          : &smpi_comm_null_copy_buffer_callback, request,
432                          // detach if msg size < eager/rdv switch limit
433                          request->detached);
434     XBT_DEBUG("send simcall posted");
435
436     /* FIXME: detached sends are not traceable (request->action == nullptr) */
437     if (request->action != nullptr)
438       simcall_set_category(request->action, TRACE_internal_smpi_get_category());
439
440     if (async_small_thresh != 0 || ((request->flags & RMA)!=0))
441       xbt_mutex_release(mut);
442   }
443 }
444
445 void smpi_mpi_startall(int count, MPI_Request * requests)
446 {
447   if(requests== nullptr) 
448     return;
449
450   for(int i = 0; i < count; i++) {
451     smpi_mpi_start(requests[i]);
452   }
453 }
454
455 void smpi_mpi_request_free(MPI_Request * request)
456 {
457   if((*request) != MPI_REQUEST_NULL){
458     (*request)->refcount--;
459     if((*request)->refcount<0) xbt_die("wrong refcount");
460
461     if((*request)->refcount==0){
462         smpi_datatype_unuse((*request)->old_type);
463         smpi_comm_unuse((*request)->comm);
464         print_request("Destroying", (*request));
465         xbt_free(*request);
466         *request = MPI_REQUEST_NULL;
467     }else{
468       print_request("Decrementing", (*request));
469     }
470   }else{
471     xbt_die("freeing an already free request");
472   }
473 }
474
475 MPI_Request smpi_rma_send_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
476                                MPI_Op op)
477 {
478   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
479   if(op==MPI_OP_NULL){
480     request = build_request(buf==MPI_BOTTOM ? nullptr : buf , count, datatype, src, dst, tag,
481                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED);
482   }else{
483     request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,  src, dst, tag,
484                             comm, RMA | NON_PERSISTENT | ISEND | SEND | PREPARED | ACCUMULATE);
485     request->op = op;
486   }
487   return request;
488 }
489
490 MPI_Request smpi_rma_recv_init(void *buf, int count, MPI_Datatype datatype, int src, int dst, int tag, MPI_Comm comm,
491                                MPI_Op op)
492 {
493   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
494   if(op==MPI_OP_NULL){
495     request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,  src, dst, tag,
496                             comm, RMA | NON_PERSISTENT | RECV | PREPARED);
497   }else{
498     request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype,  src, dst, tag,
499                             comm, RMA | NON_PERSISTENT | RECV | PREPARED | ACCUMULATE);
500     request->op = op;
501   }
502   return request;
503 }
504
505 MPI_Request smpi_isend_init(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
506 {
507   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
508   request = build_request(buf==MPI_BOTTOM ? nullptr : buf , count, datatype, smpi_process_index(),
509                           smpi_comm_group(comm)->index(dst), tag,comm, PERSISTENT | ISEND | SEND | PREPARED);
510   return request;
511 }
512
513 MPI_Request smpi_mpi_isend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
514 {
515   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
516   request =  build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
517                            smpi_comm_group(comm)->index(dst), tag, comm, NON_PERSISTENT | ISEND | SEND);
518   smpi_mpi_start(request);
519   return request;
520 }
521
522 MPI_Request smpi_mpi_issend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
523 {
524   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
525   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
526                         smpi_comm_group(comm)->index(dst), tag,comm, NON_PERSISTENT | ISEND | SSEND | SEND);
527   smpi_mpi_start(request);
528   return request;
529 }
530
531 MPI_Request smpi_irecv_init(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
532 {
533   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
534   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
535                           smpi_comm_group(comm)->index(src), smpi_process_index(), tag,
536                           comm, PERSISTENT | RECV | PREPARED);
537   return request;
538 }
539
540 MPI_Request smpi_mpi_irecv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm)
541 {
542   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
543   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, src == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
544                           smpi_comm_group(comm)->index(src), smpi_process_index(), tag, comm,
545                           NON_PERSISTENT | RECV);
546   smpi_mpi_start(request);
547   return request;
548 }
549
550 void smpi_mpi_recv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm, MPI_Status * status)
551 {
552   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
553   request = smpi_mpi_irecv(buf, count, datatype, src, tag, comm);
554   smpi_mpi_wait(&request, status);
555   request = nullptr;
556 }
557
558 void smpi_mpi_send(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
559 {
560   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
561   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
562                           smpi_comm_group(comm)->index(dst), tag, comm, NON_PERSISTENT | SEND);
563
564   smpi_mpi_start(request);
565   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
566   request = nullptr;
567 }
568
569 void smpi_mpi_ssend(void *buf, int count, MPI_Datatype datatype, int dst, int tag, MPI_Comm comm)
570 {
571   MPI_Request request = nullptr; /* MC needs the comm to be set to nullptr during the call */
572   request = build_request(buf==MPI_BOTTOM ? nullptr : buf, count, datatype, smpi_process_index(),
573                           smpi_comm_group(comm)->index(dst), tag, comm, NON_PERSISTENT | SSEND | SEND);
574
575   smpi_mpi_start(request);
576   smpi_mpi_wait(&request, MPI_STATUS_IGNORE);
577   request = nullptr;
578 }
579
580 void smpi_mpi_sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,int dst, int sendtag,
581                        void *recvbuf, int recvcount, MPI_Datatype recvtype, int src, int recvtag,
582                        MPI_Comm comm, MPI_Status * status)
583 {
584   MPI_Request requests[2];
585   MPI_Status stats[2];
586   int myid=smpi_process_index();
587   if ((smpi_comm_group(comm)->index(dst) == myid) && (smpi_comm_group(comm)->index(src) == myid)){
588       smpi_datatype_copy(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype);
589       return;
590   }
591   requests[0] = smpi_isend_init(sendbuf, sendcount, sendtype, dst, sendtag, comm);
592   requests[1] = smpi_irecv_init(recvbuf, recvcount, recvtype, src, recvtag, comm);
593   smpi_mpi_startall(2, requests);
594   smpi_mpi_waitall(2, requests, stats);
595   smpi_mpi_request_free(&requests[0]);
596   smpi_mpi_request_free(&requests[1]);
597   if(status != MPI_STATUS_IGNORE) {
598     // Copy receive status
599     *status = stats[1];
600   }
601 }
602
603 int smpi_mpi_get_count(MPI_Status * status, MPI_Datatype datatype)
604 {
605   return status->count / smpi_datatype_size(datatype);
606 }
607
608 static void finish_wait(MPI_Request * request, MPI_Status * status)
609 {
610   MPI_Request req = *request;
611   smpi_empty_status(status);
612
613   if(!((req->detached != 0) && ((req->flags & SEND) != 0)) && ((req->flags & PREPARED) == 0)){
614     if(status != MPI_STATUS_IGNORE) {
615       int src = req->src == MPI_ANY_SOURCE ? req->real_src : req->src;
616       status->MPI_SOURCE = smpi_comm_group(req->comm)->rank(src);
617       status->MPI_TAG = req->tag == MPI_ANY_TAG ? req->real_tag : req->tag;
618       status->MPI_ERROR = req->truncated != 0 ? MPI_ERR_TRUNCATE : MPI_SUCCESS;
619       // this handles the case were size in receive differs from size in send
620       status->count = req->real_size;
621     }
622
623     print_request("Finishing", req);
624     MPI_Datatype datatype = req->old_type;
625
626     if(((req->flags & ACCUMULATE) != 0) || (datatype->sizeof_substruct != 0)){
627       if (!smpi_process_get_replaying()){
628         if( smpi_privatize_global_variables != 0 && (static_cast<char*>(req->old_buf) >= smpi_start_data_exe)
629             && ((char*)req->old_buf < smpi_start_data_exe + smpi_size_data_exe )){
630             XBT_VERB("Privatization : We are unserializing to a zone in global memory - Switch data segment ");
631             smpi_switch_data_segment(smpi_process_index());
632         }
633       }
634
635       if(datatype->sizeof_substruct != 0){
636         // This part handles the problem of non-contignous memory the unserialization at the reception
637         s_smpi_subtype_t *subtype = static_cast<s_smpi_subtype_t*>(datatype->substruct);
638         if(req->flags & RECV)
639           subtype->unserialize(req->buf, req->old_buf, req->real_size/smpi_datatype_size(datatype) ,
640                                datatype->substruct, req->op);
641         xbt_free(req->buf);
642       }else if(req->flags & RECV){//apply op on contiguous buffer for accumulate
643           int n =req->real_size/smpi_datatype_size(datatype);
644           smpi_op_apply(req->op, req->buf, req->old_buf, &n, &datatype);
645           xbt_free(req->buf);
646       }
647     }
648   }
649
650   if (TRACE_smpi_view_internals() && ((req->flags & RECV) != 0)){
651     int rank = smpi_process_index();
652     int src_traced = (req->src == MPI_ANY_SOURCE ? req->real_src : req->src);
653     TRACE_smpi_recv(rank, src_traced, rank,req->tag);
654   }
655
656   if(req->detached_sender != nullptr){
657     //integrate pseudo-timing for buffering of small messages, do not bother to execute the simcall if 0
658     double sleeptime = smpi_or(req->real_size);
659     if(sleeptime > 0.0){
660       simcall_process_sleep(sleeptime);
661       XBT_DEBUG("receiving size of %zu : sleep %f ", req->real_size, sleeptime);
662     }
663     smpi_mpi_request_free(&(req->detached_sender));
664   }
665   if(req->flags & PERSISTENT)
666     req->action = nullptr;
667   req->flags |= FINISHED;
668
669   smpi_mpi_request_free(request);
670 }
671
672 int smpi_mpi_test(MPI_Request * request, MPI_Status * status) {
673   //assume that request is not MPI_REQUEST_NULL (filtered in PMPI_Test or smpi_mpi_testall before)
674
675   // to avoid deadlocks if used as a break condition, such as
676   //     while (MPI_Test(request, flag, status) && flag) {
677   //     }
678   // because the time will not normally advance when only calls to MPI_Test are made -> deadlock
679   // multiplier to the sleeptime, to increase speed of execution, each failed test will increase it
680   static int nsleeps = 1;
681   if(smpi_test_sleep > 0)  
682     simcall_process_sleep(nsleeps*smpi_test_sleep);
683
684   smpi_empty_status(status);
685   int flag = 1;
686   if (((*request)->flags & PREPARED) == 0) {
687     if ((*request)->action != nullptr)
688       flag = simcall_comm_test((*request)->action);
689     if (flag) {
690       finish_wait(request, status);
691       nsleeps=1;//reset the number of sleeps we will do next time
692       if (*request != MPI_REQUEST_NULL && ((*request)->flags & PERSISTENT)==0)
693       *request = MPI_REQUEST_NULL;
694     } else if (xbt_cfg_get_boolean("smpi/grow-injected-times")){
695       nsleeps++;
696     }
697   }
698   return flag;
699 }
700
701 int smpi_mpi_testany(int count, MPI_Request requests[], int *index, MPI_Status * status)
702 {
703   std::vector<simgrid::kernel::activity::ActivityImpl*> comms;
704   comms.reserve(count);
705
706   int i;
707   int flag = 0;
708
709   *index = MPI_UNDEFINED;
710
711   std::vector<int> map; /** Maps all matching comms back to their location in requests **/
712   for(i = 0; i < count; i++) {
713     if ((requests[i] != MPI_REQUEST_NULL) && requests[i]->action && !(requests[i]->flags & PREPARED)) {
714        comms.push_back(requests[i]->action);
715        map.push_back(i);
716     }
717   }
718   if(!map.empty()) {
719     //multiplier to the sleeptime, to increase speed of execution, each failed testany will increase it
720     static int nsleeps = 1;
721     if(smpi_test_sleep > 0) 
722       simcall_process_sleep(nsleeps*smpi_test_sleep);
723
724     i = simcall_comm_testany(comms.data(), comms.size()); // The i-th element in comms matches!
725     if (i != -1) { // -1 is not MPI_UNDEFINED but a SIMIX return code. (nothing matches)
726       *index = map[i]; 
727       finish_wait(&requests[*index], status);
728       flag             = 1;
729       nsleeps          = 1;
730       if (requests[*index] != MPI_REQUEST_NULL && (requests[*index]->flags & NON_PERSISTENT)) {
731         requests[*index] = MPI_REQUEST_NULL;
732       }
733     } else {
734       nsleeps++;
735     }
736   } else {
737       //all requests are null or inactive, return true
738       flag = 1;
739       smpi_empty_status(status);
740   }
741
742   return flag;
743 }
744
745 int smpi_mpi_testall(int count, MPI_Request requests[], MPI_Status status[])
746 {
747   MPI_Status stat;
748   MPI_Status *pstat = status == MPI_STATUSES_IGNORE ? MPI_STATUS_IGNORE : &stat;
749   int flag=1;
750   for(int i=0; i<count; i++){
751     if (requests[i] != MPI_REQUEST_NULL && !(requests[i]->flags & PREPARED)) {
752       if (smpi_mpi_test(&requests[i], pstat)!=1){
753         flag=0;
754       }else{
755           requests[i]=MPI_REQUEST_NULL;
756       }
757     }else{
758       smpi_empty_status(pstat);
759     }
760     if(status != MPI_STATUSES_IGNORE) {
761       status[i] = *pstat;
762     }
763   }
764   return flag;
765 }
766
767 void smpi_mpi_probe(int source, int tag, MPI_Comm comm, MPI_Status* status){
768   int flag=0;
769   //FIXME find another way to avoid busy waiting ?
770   // the issue here is that we have to wait on a nonexistent comm
771   while(flag==0){
772     smpi_mpi_iprobe(source, tag, comm, &flag, status);
773     XBT_DEBUG("Busy Waiting on probing : %d", flag);
774   }
775 }
776
777 void smpi_mpi_iprobe(int source, int tag, MPI_Comm comm, int* flag, MPI_Status* status){
778   MPI_Request request = build_request(nullptr, 0, MPI_CHAR, source == MPI_ANY_SOURCE ? MPI_ANY_SOURCE :
779                  smpi_comm_group(comm)->index(source), smpi_comm_rank(comm), tag, comm, PERSISTENT | RECV);
780
781   // to avoid deadlock, we have to sleep some time here, or the timer won't advance and we will only do iprobe simcalls
782   // (especially when used as a break condition, such as while(MPI_Iprobe(...)) ... )
783   // multiplier to the sleeptime, to increase speed of execution, each failed iprobe will increase it
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 = smpi_comm_group(comm)->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 = smpi_comm_rank(comm);
1034   int size = smpi_comm_size(comm);
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 = smpi_comm_rank(comm);
1067
1068   /* arbitrarily choose root as rank 0 */
1069   int size = smpi_comm_size(comm);
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 = smpi_comm_rank(comm);
1092   int size = smpi_comm_size(comm);
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 = smpi_comm_rank(comm);
1130   int size = smpi_comm_size(comm);
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 = smpi_comm_rank(comm);
1165   int size = smpi_comm_size(comm);
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 = smpi_comm_rank(comm);
1201   int size = smpi_comm_size(comm);
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 = smpi_comm_rank(comm);
1240   int size = smpi_comm_size(comm);
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 = smpi_comm_rank(comm);
1281   int size = smpi_comm_size(comm);
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 = smpi_comm_rank(comm);
1354   int size = smpi_comm_size(comm);
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 = smpi_comm_rank(comm);
1414   int size = smpi_comm_size(comm);
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 }