Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
ff80213f39d075d14cf685a6c36190dcadfc873f
[simgrid.git] / src / kernel / activity / CommImpl.cpp
1 /* Copyright (c) 2007-2019. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "src/kernel/activity/CommImpl.hpp"
7 #include "simgrid/Exception.hpp"
8 #include "simgrid/kernel/resource/Action.hpp"
9 #include "simgrid/modelchecker.h"
10 #include "simgrid/s4u/Host.hpp"
11 #include "src/kernel/activity/MailboxImpl.hpp"
12 #include "src/kernel/context/Context.hpp"
13 #include "src/mc/mc_replay.hpp"
14 #include "src/surf/cpu_interface.hpp"
15 #include "src/surf/network_interface.hpp"
16 #include "src/surf/surf_interface.hpp"
17
18 #include <boost/range/algorithm.hpp>
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_network, simix, "SIMIX network-related synchronization");
20
21 XBT_PRIVATE void simcall_HANDLER_comm_send(smx_simcall_t simcall, smx_actor_t src, smx_mailbox_t mbox, double task_size,
22                                            double rate, void* src_buff, size_t src_buff_size,
23                                            int (*match_fun)(void*, void*, simgrid::kernel::activity::CommImpl*),
24                                            void (*copy_data_fun)(smx_activity_t, void*, size_t), void* data,
25                                            double timeout)
26 {
27   smx_activity_t comm = simcall_HANDLER_comm_isend(simcall, src, mbox, task_size, rate, src_buff, src_buff_size,
28                                                    match_fun, nullptr, copy_data_fun, data, 0);
29   SIMCALL_SET_MC_VALUE(simcall, 0);
30   simcall_HANDLER_comm_wait(simcall, comm, timeout);
31 }
32
33 XBT_PRIVATE smx_activity_t simcall_HANDLER_comm_isend(
34     smx_simcall_t /*simcall*/, smx_actor_t src_proc, smx_mailbox_t mbox, double task_size, double rate, void* src_buff,
35     size_t src_buff_size, int (*match_fun)(void*, void*, simgrid::kernel::activity::CommImpl*),
36     void (*clean_fun)(void*), // used to free the synchro in case of problem after a detached send
37     void (*copy_data_fun)(smx_activity_t, void*, size_t), // used to copy data if not default one
38     void* data, int detached)
39 {
40   XBT_DEBUG("send from mailbox %p", mbox);
41
42   /* Prepare a synchro describing us, so that it gets passed to the user-provided filter of other side */
43   simgrid::kernel::activity::CommImplPtr this_comm = simgrid::kernel::activity::CommImplPtr(
44       new simgrid::kernel::activity::CommImpl(simgrid::kernel::activity::CommImpl::Type::SEND));
45
46   /* Look for communication synchro matching our needs. We also provide a description of
47    * ourself so that the other side also gets a chance of choosing if it wants to match with us.
48    *
49    * If it is not found then push our communication into the rendez-vous point */
50   simgrid::kernel::activity::CommImplPtr other_comm =
51       mbox->find_matching_comm(simgrid::kernel::activity::CommImpl::Type::RECEIVE, match_fun, data, this_comm,
52                                /*done*/ false, /*remove_matching*/ true);
53
54   if (not other_comm) {
55     other_comm = std::move(this_comm);
56
57     if (mbox->permanent_receiver_ != nullptr) {
58       // this mailbox is for small messages, which have to be sent right now
59       other_comm->state_     = SIMIX_READY;
60       other_comm->dst_actor_ = mbox->permanent_receiver_.get();
61       mbox->done_comm_queue_.push_back(other_comm);
62       XBT_DEBUG("pushing a message into the permanent receive list %p, comm %p", mbox, other_comm.get());
63
64     } else {
65       mbox->push(other_comm);
66     }
67   } else {
68     XBT_DEBUG("Receive already pushed");
69
70     other_comm->state_ = SIMIX_READY;
71     other_comm->type   = simgrid::kernel::activity::CommImpl::Type::READY;
72   }
73   src_proc->comms.push_back(other_comm);
74
75   if (detached) {
76     other_comm->detached  = true;
77     other_comm->clean_fun = clean_fun;
78   } else {
79     other_comm->clean_fun = nullptr;
80   }
81
82   /* Setup the communication synchro */
83   other_comm->src_actor_     = src_proc;
84   other_comm->task_size_     = task_size;
85   other_comm->rate_          = rate;
86   other_comm->src_buff_      = src_buff;
87   other_comm->src_buff_size_ = src_buff_size;
88   other_comm->src_data_      = data;
89
90   other_comm->match_fun     = match_fun;
91   other_comm->copy_data_fun = copy_data_fun;
92
93   if (MC_is_active() || MC_record_replay_is_active()) {
94     other_comm->state_ = SIMIX_RUNNING;
95     return (detached ? nullptr : other_comm);
96   }
97
98   other_comm->start();
99
100   return (detached ? nullptr : other_comm);
101 }
102
103 XBT_PRIVATE void simcall_HANDLER_comm_recv(smx_simcall_t simcall, smx_actor_t receiver, smx_mailbox_t mbox,
104                                            void* dst_buff, size_t* dst_buff_size,
105                                            int (*match_fun)(void*, void*, simgrid::kernel::activity::CommImpl*),
106                                            void (*copy_data_fun)(smx_activity_t, void*, size_t), void* data,
107                                            double timeout, double rate)
108 {
109   smx_activity_t comm = simcall_HANDLER_comm_irecv(simcall, receiver, mbox, dst_buff, dst_buff_size, match_fun,
110                                                    copy_data_fun, data, rate);
111   SIMCALL_SET_MC_VALUE(simcall, 0);
112   simcall_HANDLER_comm_wait(simcall, comm, timeout);
113 }
114
115 XBT_PRIVATE smx_activity_t simcall_HANDLER_comm_irecv(smx_simcall_t /*simcall*/, smx_actor_t receiver,
116                                                       smx_mailbox_t mbox, void* dst_buff, size_t* dst_buff_size,
117                                                       simix_match_func_t match_fun,
118                                                       void (*copy_data_fun)(smx_activity_t, void*, size_t), void* data,
119                                                       double rate)
120 {
121   simgrid::kernel::activity::CommImplPtr this_synchro = simgrid::kernel::activity::CommImplPtr(
122       new simgrid::kernel::activity::CommImpl(simgrid::kernel::activity::CommImpl::Type::RECEIVE));
123   XBT_DEBUG("recv from mbox %p. this_synchro=%p", mbox, this_synchro.get());
124
125   simgrid::kernel::activity::CommImplPtr other_comm;
126   // communication already done, get it inside the list of completed comms
127   if (mbox->permanent_receiver_ != nullptr && not mbox->done_comm_queue_.empty()) {
128
129     XBT_DEBUG("We have a comm that has probably already been received, trying to match it, to skip the communication");
130     // find a match in the list of already received comms
131     other_comm = mbox->find_matching_comm(simgrid::kernel::activity::CommImpl::Type::SEND, match_fun, data,
132                                           this_synchro, /*done*/ true,
133                                           /*remove_matching*/ true);
134     // if not found, assume the receiver came first, register it to the mailbox in the classical way
135     if (not other_comm) {
136       XBT_DEBUG("We have messages in the permanent receive list, but not the one we are looking for, pushing request "
137                 "into list");
138       other_comm = std::move(this_synchro);
139       mbox->push(other_comm);
140     } else {
141       if (other_comm->surf_action_ && other_comm->remains() < 1e-12) {
142         XBT_DEBUG("comm %p has been already sent, and is finished, destroy it", other_comm.get());
143         other_comm->state_ = SIMIX_DONE;
144         other_comm->type   = simgrid::kernel::activity::CommImpl::Type::DONE;
145         other_comm->mbox   = nullptr;
146       }
147     }
148   } else {
149     /* Prepare a comm describing us, so that it gets passed to the user-provided filter of other side */
150
151     /* Look for communication activity matching our needs. We also provide a description of
152      * ourself so that the other side also gets a chance of choosing if it wants to match with us.
153      *
154      * If it is not found then push our communication into the rendez-vous point */
155     other_comm = mbox->find_matching_comm(simgrid::kernel::activity::CommImpl::Type::SEND, match_fun, data,
156                                           this_synchro, /*done*/ false,
157                                           /*remove_matching*/ true);
158
159     if (other_comm == nullptr) {
160       XBT_DEBUG("Receive pushed first (%zu comm enqueued so far)", mbox->comm_queue_.size());
161       other_comm = std::move(this_synchro);
162       mbox->push(other_comm);
163     } else {
164       XBT_DEBUG("Match my %p with the existing %p", this_synchro.get(), other_comm.get());
165
166       other_comm->state_ = SIMIX_READY;
167       other_comm->type   = simgrid::kernel::activity::CommImpl::Type::READY;
168     }
169     receiver->comms.push_back(other_comm);
170   }
171
172   /* Setup communication synchro */
173   other_comm->dst_actor_     = receiver;
174   other_comm->dst_buff_      = dst_buff;
175   other_comm->dst_buff_size_ = dst_buff_size;
176   other_comm->dst_data_      = data;
177
178   if (rate > -1.0 && (other_comm->rate_ < 0.0 || rate < other_comm->rate_))
179     other_comm->rate_ = rate;
180
181   other_comm->match_fun     = match_fun;
182   other_comm->copy_data_fun = copy_data_fun;
183
184   if (MC_is_active() || MC_record_replay_is_active()) {
185     other_comm->state_ = SIMIX_RUNNING;
186     return other_comm;
187   }
188   other_comm->start();
189   return other_comm;
190 }
191
192 void simcall_HANDLER_comm_wait(smx_simcall_t simcall, smx_activity_t synchro, double timeout)
193 {
194   /* Associate this simcall to the wait synchro */
195   XBT_DEBUG("simcall_HANDLER_comm_wait, %p", synchro.get());
196
197   synchro->simcalls_.push_back(simcall);
198   simcall->issuer->waiting_synchro = synchro;
199
200   if (MC_is_active() || MC_record_replay_is_active()) {
201     int idx = SIMCALL_GET_MC_VALUE(simcall);
202     if (idx == 0) {
203       synchro->state_ = SIMIX_DONE;
204     } else {
205       /* If we reached this point, the wait simcall must have a timeout */
206       /* Otherwise it shouldn't be enabled and executed by the MC */
207       if (timeout < 0.0)
208         THROW_IMPOSSIBLE;
209
210       simgrid::kernel::activity::CommImplPtr comm =
211           boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro);
212       if (comm->src_actor_ == simcall->issuer)
213         comm->state_ = SIMIX_SRC_TIMEOUT;
214       else
215         comm->state_ = SIMIX_DST_TIMEOUT;
216     }
217
218     boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro)->finish();
219     return;
220   }
221
222   /* If the synchro has already finish perform the error handling, */
223   /* otherwise set up a waiting timeout on the right side          */
224   if (synchro->state_ != SIMIX_WAITING && synchro->state_ != SIMIX_RUNNING) {
225     boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro)->finish();
226   } else { /* we need a sleep action (even when there is no timeout) to be notified of host failures */
227     simgrid::kernel::resource::Action* sleep = simcall->issuer->get_host()->pimpl_cpu->sleep(timeout);
228     sleep->set_data(synchro.get());
229
230     simgrid::kernel::activity::CommImplPtr comm =
231         boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro);
232     if (simcall->issuer == comm->src_actor_)
233       comm->src_timeout_ = sleep;
234     else
235       comm->dst_timeout_ = sleep;
236   }
237 }
238
239 void simcall_HANDLER_comm_test(smx_simcall_t simcall, smx_activity_t synchro)
240 {
241   simgrid::kernel::activity::CommImplPtr comm =
242       boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro);
243
244   int res;
245
246   if (MC_is_active() || MC_record_replay_is_active()) {
247     res = comm->src_actor_ && comm->dst_actor_;
248     if (res)
249       synchro->state_ = SIMIX_DONE;
250   } else {
251     res = synchro->state_ != SIMIX_WAITING && synchro->state_ != SIMIX_RUNNING;
252   }
253
254   simcall_comm_test__set__result(simcall, res);
255   if (simcall_comm_test__get__result(simcall)) {
256     synchro->simcalls_.push_back(simcall);
257     boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro)->finish();
258   } else {
259     SIMIX_simcall_answer(simcall);
260   }
261 }
262
263 void simcall_HANDLER_comm_testany(smx_simcall_t simcall, simgrid::kernel::activity::ActivityImplPtr comms[],
264                                   size_t count)
265 {
266   // The default result is -1 -- this means, "nothing is ready".
267   // It can be changed below, but only if something matches.
268   simcall_comm_testany__set__result(simcall, -1);
269
270   if (MC_is_active() || MC_record_replay_is_active()) {
271     int idx = SIMCALL_GET_MC_VALUE(simcall);
272     if (idx == -1) {
273       SIMIX_simcall_answer(simcall);
274     } else {
275       simgrid::kernel::activity::ActivityImplPtr synchro = comms[idx];
276       simcall_comm_testany__set__result(simcall, idx);
277       synchro->simcalls_.push_back(simcall);
278       synchro->state_ = SIMIX_DONE;
279       boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro)->finish();
280     }
281     return;
282   }
283
284   for (std::size_t i = 0; i != count; ++i) {
285     simgrid::kernel::activity::ActivityImplPtr synchro = comms[i];
286     if (synchro->state_ != SIMIX_WAITING && synchro->state_ != SIMIX_RUNNING) {
287       simcall_comm_testany__set__result(simcall, i);
288       synchro->simcalls_.push_back(simcall);
289       boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro)->finish();
290       return;
291     }
292   }
293   SIMIX_simcall_answer(simcall);
294 }
295
296 static void SIMIX_waitany_remove_simcall_from_actions(smx_simcall_t simcall)
297 {
298   unsigned int cursor  = 0;
299   xbt_dynar_t synchros = simcall_comm_waitany__get__comms(simcall);
300
301   simgrid::kernel::activity::ActivityImpl* ptr;
302   xbt_dynar_foreach (synchros, cursor, ptr) {
303     smx_activity_t synchro = simgrid::kernel::activity::ActivityImplPtr(ptr);
304
305     // Remove the first occurence of simcall:
306     auto i = boost::range::find(synchro->simcalls_, simcall);
307     if (i != synchro->simcalls_.end())
308       synchro->simcalls_.erase(i);
309   }
310 }
311 void simcall_HANDLER_comm_waitany(smx_simcall_t simcall, xbt_dynar_t synchros, double timeout)
312 {
313   if (MC_is_active() || MC_record_replay_is_active()) {
314     if (timeout > 0.0)
315       xbt_die("Timeout not implemented for waitany in the model-checker");
316     int idx                = SIMCALL_GET_MC_VALUE(simcall);
317     smx_activity_t synchro = xbt_dynar_get_as(synchros, idx, smx_activity_t);
318     synchro->simcalls_.push_back(simcall);
319     simcall_comm_waitany__set__result(simcall, idx);
320     synchro->state_ = SIMIX_DONE;
321     boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro)->finish();
322     return;
323   }
324
325   if (timeout < 0.0) {
326     simcall->timer = NULL;
327   } else {
328     simcall->timer = simgrid::simix::Timer::set(SIMIX_get_clock() + timeout, [simcall]() {
329       SIMIX_waitany_remove_simcall_from_actions(simcall);
330       simcall_comm_waitany__set__result(simcall, -1);
331       SIMIX_simcall_answer(simcall);
332     });
333   }
334
335   unsigned int cursor;
336   simgrid::kernel::activity::ActivityImpl* ptr;
337   xbt_dynar_foreach (synchros, cursor, ptr) {
338     smx_activity_t synchro = simgrid::kernel::activity::ActivityImplPtr(ptr);
339     /* associate this simcall to the the synchro */
340     synchro->simcalls_.push_back(simcall);
341
342     /* see if the synchro is already finished */
343     if (synchro->state_ != SIMIX_WAITING && synchro->state_ != SIMIX_RUNNING) {
344       boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro)->finish();
345       break;
346     }
347   }
348 }
349
350 /******************************************************************************/
351 /*                    SIMIX_comm_copy_data callbacks                       */
352 /******************************************************************************/
353 static void (*SIMIX_comm_copy_data_callback)(smx_activity_t, void*, size_t) = &SIMIX_comm_copy_pointer_callback;
354
355 void SIMIX_comm_copy_buffer_callback(smx_activity_t synchro, void* buff, size_t buff_size)
356 {
357   simgrid::kernel::activity::CommImplPtr comm =
358       boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro);
359
360   XBT_DEBUG("Copy the data over");
361   memcpy(comm->dst_buff_, buff, buff_size);
362   if (comm->detached) { // if this is a detached send, the source buffer was duplicated by SMPI sender to make the
363                         // original buffer available to the application ASAP
364     xbt_free(buff);
365     comm->src_buff_ = nullptr;
366   }
367 }
368
369 void SIMIX_comm_set_copy_data_callback(void (*callback)(smx_activity_t, void*, size_t))
370 {
371   SIMIX_comm_copy_data_callback = callback;
372 }
373
374 void SIMIX_comm_copy_pointer_callback(smx_activity_t synchro, void* buff, size_t buff_size)
375 {
376   simgrid::kernel::activity::CommImplPtr comm =
377       boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro);
378
379   xbt_assert((buff_size == sizeof(void*)), "Cannot copy %zu bytes: must be sizeof(void*)", buff_size);
380   *(void**)(comm->dst_buff_) = buff;
381 }
382
383 namespace simgrid {
384 namespace kernel {
385 namespace activity {
386
387 CommImpl::CommImpl(CommImpl::Type type) : type(type)
388 {
389   state_   = SIMIX_WAITING;
390   src_data_ = nullptr;
391   dst_data_ = nullptr;
392   XBT_DEBUG("Create comm activity %p", this);
393 }
394
395 CommImpl::~CommImpl()
396 {
397   XBT_DEBUG("Really free communication %p", this);
398
399   cleanupSurf();
400
401   if (detached && state_ != SIMIX_DONE) {
402     /* the communication has failed and was detached:
403      * we have to free the buffer */
404     if (clean_fun)
405       clean_fun(src_buff_);
406     src_buff_ = nullptr;
407   }
408
409   if (mbox)
410     mbox->remove(this);
411 }
412
413 /**  @brief Starts the simulation of a communication synchro. */
414 void CommImpl::start()
415 {
416   /* If both the sender and the receiver are already there, start the communication */
417   if (state_ == SIMIX_READY) {
418
419     s4u::Host* sender   = src_actor_->get_host();
420     s4u::Host* receiver = dst_actor_->get_host();
421
422     surf_action_ = surf_network_model->communicate(sender, receiver, task_size_, rate_);
423     surf_action_->set_data(this);
424     state_ = SIMIX_RUNNING;
425
426     XBT_DEBUG("Starting communication %p from '%s' to '%s' (surf_action: %p)", this, sender->get_cname(),
427               receiver->get_cname(), surf_action_);
428
429     /* If a link is failed, detect it immediately */
430     if (surf_action_->get_state() == resource::Action::State::FAILED) {
431       XBT_DEBUG("Communication from '%s' to '%s' failed to start because of a link failure", sender->get_cname(),
432                 receiver->get_cname());
433       state_ = SIMIX_LINK_FAILURE;
434       cleanupSurf();
435
436     } else if (src_actor_->is_suspended() || dst_actor_->is_suspended()) {
437       /* If any of the process is suspended, create the synchro but stop its execution,
438          it will be restarted when the sender process resume */
439       if (src_actor_->is_suspended())
440         XBT_DEBUG("The communication is suspended on startup because src (%s@%s) was suspended since it initiated the "
441                   "communication",
442                   src_actor_->get_cname(), src_actor_->get_host()->get_cname());
443       else
444         XBT_DEBUG("The communication is suspended on startup because dst (%s@%s) was suspended since it initiated the "
445                   "communication",
446                   dst_actor_->get_cname(), dst_actor_->get_host()->get_cname());
447
448       surf_action_->suspend();
449     }
450   }
451 }
452
453 /** @brief Copy the communication data from the sender's buffer to the receiver's one  */
454 void CommImpl::copy_data()
455 {
456   size_t buff_size = src_buff_size_;
457   /* If there is no data to copy then return */
458   if (not src_buff_ || not dst_buff_ || copied)
459     return;
460
461   XBT_DEBUG("Copying comm %p data from %s (%p) -> %s (%p) (%zu bytes)", this,
462             src_actor_ ? src_actor_->get_host()->get_cname() : "a finished process", src_buff_,
463             dst_actor_ ? dst_actor_->get_host()->get_cname() : "a finished process", dst_buff_, buff_size);
464
465   /* Copy at most dst_buff_size bytes of the message to receiver's buffer */
466   if (dst_buff_size_)
467     buff_size = std::min(buff_size, *(dst_buff_size_));
468
469   /* Update the receiver's buffer size to the copied amount */
470   if (dst_buff_size_)
471     *dst_buff_size_ = buff_size;
472
473   if (buff_size > 0) {
474     if (copy_data_fun)
475       copy_data_fun(this, src_buff_, buff_size);
476     else
477       SIMIX_comm_copy_data_callback(this, src_buff_, buff_size);
478   }
479
480   /* Set the copied flag so we copy data only once */
481   /* (this function might be called from both communication ends) */
482   copied = true;
483 }
484
485 void CommImpl::suspend()
486 {
487   /* FIXME: shall we suspend also the timeout synchro? */
488   if (surf_action_)
489     surf_action_->suspend();
490   /* if not created yet, the action will be suspended on creation, in CommImpl::start() */
491 }
492
493 void CommImpl::resume()
494 {
495   /*FIXME: check what happen with the timeouts */
496   if (surf_action_)
497     surf_action_->resume();
498   /* in the other case, the synchro were not really suspended yet, see CommImpl::suspend() and CommImpl::start() */
499 }
500
501 void CommImpl::cancel()
502 {
503   /* if the synchro is a waiting state means that it is still in a mbox so remove from it and delete it */
504   if (state_ == SIMIX_WAITING) {
505     mbox->remove(this);
506     state_ = SIMIX_CANCELED;
507   } else if (not MC_is_active() /* when running the MC there are no surf actions */
508              && not MC_record_replay_is_active() && (state_ == SIMIX_READY || state_ == SIMIX_RUNNING)) {
509     surf_action_->cancel();
510   }
511 }
512
513 /**  @brief get the amount remaining from the communication */
514 double CommImpl::remains()
515 {
516   return surf_action_->get_remains();
517 }
518
519 /** @brief This is part of the cleanup process, probably an internal command */
520 void CommImpl::cleanupSurf()
521 {
522   if (surf_action_) {
523     surf_action_->unref();
524     surf_action_ = nullptr;
525   }
526
527   if (src_timeout_) {
528     src_timeout_->unref();
529     src_timeout_ = nullptr;
530   }
531
532   if (dst_timeout_) {
533     dst_timeout_->unref();
534     dst_timeout_ = nullptr;
535   }
536 }
537
538 void CommImpl::post()
539 {
540   /* Update synchro state */
541   if (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FINISHED)
542     state_ = SIMIX_SRC_TIMEOUT;
543   else if (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FINISHED)
544     state_ = SIMIX_DST_TIMEOUT;
545   else if (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FAILED)
546     state_ = SIMIX_SRC_HOST_FAILURE;
547   else if (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FAILED)
548     state_ = SIMIX_DST_HOST_FAILURE;
549   else if (surf_action_ && surf_action_->get_state() == resource::Action::State::FAILED) {
550     state_ = SIMIX_LINK_FAILURE;
551   } else
552     state_ = SIMIX_DONE;
553
554   XBT_DEBUG("SIMIX_post_comm: comm %p, state %d, src_proc %p, dst_proc %p, detached: %d", this, (int)state_,
555             src_actor_.get(), dst_actor_.get(), detached);
556
557   /* destroy the surf actions associated with the Simix communication */
558   cleanupSurf();
559
560   /* if there are simcalls associated with the synchro, then answer them */
561   if (not simcalls_.empty()) {
562     finish();
563   }
564 }
565
566 void CommImpl::finish()
567 {
568   smx_activity_t synchro = this;
569   while (not simcalls_.empty()) {
570     smx_simcall_t simcall = simcalls_.front();
571     simcalls_.pop_front();
572
573     /* If a waitany simcall is waiting for this synchro to finish, then remove it from the other synchros in the waitany
574      * list. Afterwards, get the position of the actual synchro in the waitany dynar and return it as the result of the
575      * simcall */
576
577     if (simcall->call == SIMCALL_NONE) // FIXME: maybe a better way to handle this case
578       continue;                        // if process handling comm is killed
579     if (simcall->call == SIMCALL_COMM_WAITANY) {
580       SIMIX_waitany_remove_simcall_from_actions(simcall);
581       if (simcall->timer) {
582         simcall->timer->remove();
583         simcall->timer = nullptr;
584       }
585       if (not MC_is_active() && not MC_record_replay_is_active())
586         simcall_comm_waitany__set__result(simcall,
587                                           xbt_dynar_search(simcall_comm_waitany__get__comms(simcall), &synchro));
588     }
589
590     /* If the synchro is still in a rendez-vous point then remove from it */
591     if (mbox)
592       mbox->remove(this);
593
594     XBT_DEBUG("CommImpl::finish(): synchro state = %d", static_cast<int>(state_));
595
596     /* Check out for errors */
597
598     if (not simcall->issuer->get_host()->is_on()) {
599       simcall->issuer->context_->iwannadie = true;
600       simcall->issuer->exception_ =
601           std::make_exception_ptr(simgrid::HostFailureException(XBT_THROW_POINT, "Host failed"));
602     } else {
603       switch (state_) {
604
605         case SIMIX_DONE:
606           XBT_DEBUG("Communication %p complete!", this);
607           copy_data();
608           break;
609
610         case SIMIX_SRC_TIMEOUT:
611           simcall->issuer->exception_ = std::make_exception_ptr(
612               simgrid::TimeoutError(XBT_THROW_POINT, "Communication timeouted because of the sender"));
613           break;
614
615         case SIMIX_DST_TIMEOUT:
616           simcall->issuer->exception_ = std::make_exception_ptr(
617               simgrid::TimeoutError(XBT_THROW_POINT, "Communication timeouted because of the receiver"));
618           break;
619
620         case SIMIX_SRC_HOST_FAILURE:
621           if (simcall->issuer == src_actor_)
622             simcall->issuer->context_->iwannadie = true;
623           else
624             simcall->issuer->exception_ =
625                 std::make_exception_ptr(simgrid::NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
626           break;
627
628         case SIMIX_DST_HOST_FAILURE:
629           if (simcall->issuer == dst_actor_)
630             simcall->issuer->context_->iwannadie = true;
631           else
632             simcall->issuer->exception_ =
633                 std::make_exception_ptr(simgrid::NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
634           break;
635
636         case SIMIX_LINK_FAILURE:
637           XBT_DEBUG("Link failure in synchro %p between '%s' and '%s': posting an exception to the issuer: %s (%p) "
638                     "detached:%d",
639                     this, src_actor_ ? src_actor_->get_host()->get_cname() : nullptr,
640                     dst_actor_ ? dst_actor_->get_host()->get_cname() : nullptr, simcall->issuer->get_cname(),
641                     simcall->issuer, detached);
642           if (src_actor_ == simcall->issuer) {
643             XBT_DEBUG("I'm source");
644           } else if (dst_actor_ == simcall->issuer) {
645             XBT_DEBUG("I'm dest");
646           } else {
647             XBT_DEBUG("I'm neither source nor dest");
648           }
649           simcall->issuer->throw_exception(
650               std::make_exception_ptr(simgrid::NetworkFailureException(XBT_THROW_POINT, "Link failure")));
651           break;
652
653         case SIMIX_CANCELED:
654           if (simcall->issuer == dst_actor_)
655             simcall->issuer->exception_ = std::make_exception_ptr(
656                 simgrid::CancelException(XBT_THROW_POINT, "Communication canceled by the sender"));
657           else
658             simcall->issuer->exception_ = std::make_exception_ptr(
659                 simgrid::CancelException(XBT_THROW_POINT, "Communication canceled by the receiver"));
660           break;
661
662         default:
663           xbt_die("Unexpected synchro state in CommImpl::finish: %d", static_cast<int>(state_));
664       }
665     }
666
667     /* if there is an exception during a waitany or a testany, indicate the position of the failed communication */
668     if (simcall->issuer->exception_ &&
669         (simcall->call == SIMCALL_COMM_WAITANY || simcall->call == SIMCALL_COMM_TESTANY)) {
670       // First retrieve the rank of our failing synchro
671       int rank = -1;
672       if (simcall->call == SIMCALL_COMM_WAITANY) {
673         rank = xbt_dynar_search(simcall_comm_waitany__get__comms(simcall), &synchro);
674       } else if (simcall->call == SIMCALL_COMM_TESTANY) {
675         rank         = -1;
676         auto* comms  = simcall_comm_testany__get__comms(simcall);
677         auto count   = simcall_comm_testany__get__count(simcall);
678         auto element = std::find(comms, comms + count, this);
679         if (element == comms + count)
680           rank = -1;
681         else
682           rank = element - comms;
683       }
684
685       // In order to modify the exception we have to rethrow it:
686       try {
687         std::rethrow_exception(simcall->issuer->exception_);
688       } catch (simgrid::TimeoutError& e) {
689         e.value                     = rank;
690         simcall->issuer->exception_ = std::make_exception_ptr(e);
691       } catch (simgrid::NetworkFailureException& e) {
692         e.value                     = rank;
693         simcall->issuer->exception_ = std::make_exception_ptr(e);
694       } catch (simgrid::CancelException& e) {
695         e.value                     = rank;
696         simcall->issuer->exception_ = std::make_exception_ptr(e);
697       }
698     }
699
700     simcall->issuer->waiting_synchro = nullptr;
701     simcall->issuer->comms.remove(this);
702     if (detached) {
703       if (simcall->issuer == src_actor_) {
704         if (dst_actor_)
705           dst_actor_->comms.remove(this);
706       } else if (simcall->issuer == dst_actor_) {
707         if (src_actor_)
708           src_actor_->comms.remove(this);
709       } else {
710         dst_actor_->comms.remove(this);
711         src_actor_->comms.remove(this);
712       }
713     }
714
715     if (simcall->issuer->get_host()->is_on())
716       SIMIX_simcall_answer(simcall);
717     else
718       simcall->issuer->context_->iwannadie = true;
719   }
720 }
721
722 } // namespace activity
723 } // namespace kernel
724 } // namespace simgrid