Logo AND Algorithmique Numérique Distribuée

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