1 /* Copyright (c) 2007-2023. The SimGrid Team. All rights reserved. */
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. */
6 #include <simgrid/Exception.hpp>
7 #include <simgrid/kernel/routing/NetPoint.hpp>
8 #include <simgrid/modelchecker.h>
9 #include <simgrid/s4u/Host.hpp>
11 #include "src/kernel/EngineImpl.hpp"
12 #include "src/kernel/activity/CommImpl.hpp"
13 #include "src/kernel/activity/MailboxImpl.hpp"
14 #include "src/kernel/actor/SimcallObserver.hpp"
15 #include "src/kernel/resource/CpuImpl.hpp"
16 #include "src/kernel/resource/NetworkModel.hpp"
17 #include "src/kernel/resource/StandardLinkImpl.hpp"
18 #include "src/mc/mc_replay.hpp"
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_network, kernel, "Kernel network-related synchronization");
22 namespace simgrid::kernel::activity {
24 unsigned CommImpl::next_id_ = 0;
26 /* In stateful MC, we need to ignore some private memory that is not relevant to the application state */
27 void CommImpl::setup_mc()
29 MC_ignore(&CommImpl::next_id_, sizeof(CommImpl::next_id_));
34 MC_ignore((void*)&id_, sizeof(id_));
37 std::function<void(CommImpl*, void*, size_t)> CommImpl::copy_data_callback_ = [](kernel::activity::CommImpl* comm,
38 void* buff, size_t buff_size) {
39 xbt_assert((buff_size == sizeof(void*)), "Cannot copy %zu bytes: must be sizeof(void*)", buff_size);
40 *(void**)(comm->dst_buff_) = buff;
43 void CommImpl::set_copy_data_callback(const std::function<void(CommImpl*, void*, size_t)>& callback)
45 copy_data_callback_ = callback;
48 CommImpl& CommImpl::set_type(CommImplType type)
54 CommImpl& CommImpl::set_source(s4u::Host* from)
56 xbt_assert( from_ == nullptr );
62 CommImpl& CommImpl::set_destination(s4u::Host* to)
64 xbt_assert( to_ == nullptr );
70 CommImpl& CommImpl::set_size(double size)
76 CommImpl& CommImpl::set_rate(double rate)
81 CommImpl& CommImpl::set_mailbox(MailboxImpl* mbox)
84 mbox_id_ = mbox->get_id();
89 CommImpl& CommImpl::set_src_buff(unsigned char* buff, size_t size)
92 src_buff_size_ = size;
96 CommImpl& CommImpl::set_dst_buff(unsigned char* buff, size_t* size)
99 dst_buff_size_ = size;
103 CommImpl& CommImpl::detach()
106 EngineImpl::get_instance()->get_maestro()->activities_.insert(this);
110 CommImpl::~CommImpl()
112 XBT_DEBUG("Really free communication %p in state %s (detached = %d)", this, get_state_str(), detached_);
116 if (detached_ && get_state() != State::DONE) {
117 /* the communication has failed and was detached:
118 * we have to free the buffer */
120 clean_fun(src_buff_);
126 MC_unignore((void*)&id_, sizeof(id_));
129 /** @brief Starts the simulation of a communication synchro. */
130 CommImpl* CommImpl::start()
132 /* If both the sender and the receiver are already there, start the communication */
133 if (get_state() == State::READY) {
134 from_ = from_ != nullptr ? from_ : src_actor_->get_host();
135 xbt_assert(from_->is_on());
136 to_ = to_ != nullptr ? to_ : dst_actor_->get_host();
137 xbt_assert(to_->is_on());
139 /* Getting the network_model from the origin host
140 * Valid while we have a single network model, otherwise we would need to change this function to first get the
141 * routes and later create the respective model actions */
142 auto net_model = from_->get_netpoint()->get_englobing_zone()->get_network_model();
144 model_action_ = net_model->communicate(from_, to_, size_, rate_, false);
145 model_action_->set_activity(this);
146 model_action_->set_category(get_tracing_category());
147 set_start_time(model_action_->get_start_time());
148 set_state(State::RUNNING);
150 XBT_DEBUG("Starting communication %p from '%s' to '%s' (model action: %p; state: %s)", this, from_->get_cname(),
151 to_->get_cname(), model_action_, get_state_str());
153 /* If a link is failed, detect it immediately */
154 if (model_action_->get_state() == resource::Action::State::FAILED) {
155 XBT_DEBUG("Communication from '%s' to '%s' failed to start because of a link failure", from_->get_cname(),
157 set_state(State::LINK_FAILURE);
160 } else if ((src_actor_ != nullptr && src_actor_->is_suspended()) ||
161 (dst_actor_ != nullptr && dst_actor_->is_suspended())) {
162 /* If any of the actor is suspended, create the synchro but stop its execution,
163 it will be restarted when the sender actor resumes */
164 if (src_actor_->is_suspended())
165 XBT_DEBUG("The communication is suspended on startup because src (%s@%s) was suspended since it initiated the "
167 src_actor_->get_cname(), src_actor_->get_host()->get_cname());
169 XBT_DEBUG("The communication is suspended on startup because dst (%s@%s) was suspended since it initiated the "
171 dst_actor_->get_cname(), dst_actor_->get_host()->get_cname());
173 model_action_->suspend();
180 std::vector<s4u::Link*> CommImpl::get_traversed_links() const
182 xbt_assert(get_state() != State::WAITING, "You cannot use %s() if your communication is not ready (%s)", __FUNCTION__,
184 std::vector<s4u::Link*> vlinks;
185 XBT_ATTRIB_UNUSED double res = 0;
186 from_->route_to(to_, vlinks, &res);
190 /** @brief Copy the communication data from the sender's buffer to the receiver's one */
191 void CommImpl::copy_data()
193 size_t buff_size = src_buff_size_;
194 /* If there is no data to copy then return */
195 if (not src_buff_ || not dst_buff_ || copied_)
198 XBT_DEBUG("Copying comm %p data from %s (%p) -> %s (%p) (%zu bytes)", this,
199 src_actor_ ? src_actor_->get_host()->get_cname() : "a finished actor", src_buff_,
200 dst_actor_ ? dst_actor_->get_host()->get_cname() : "a finished actor", dst_buff_, buff_size);
202 /* Copy at most dst_buff_size bytes of the message to receiver's buffer */
203 if (dst_buff_size_) {
204 buff_size = std::min(buff_size, *dst_buff_size_);
206 /* Update the receiver's buffer size to the copied amount */
207 *dst_buff_size_ = buff_size;
212 copy_data_fun(this, src_buff_, buff_size);
214 copy_data_callback_(this, src_buff_, buff_size);
217 /* Set the copied flag so we copy data only once */
218 /* (this function might be called from both communication ends) */
222 ActivityImplPtr CommImpl::isend(actor::CommIsendSimcall* observer)
224 auto* mbox = observer->get_mailbox();
225 XBT_DEBUG("send from mailbox %p", mbox);
227 /* Prepare a synchro describing us, so that it gets passed to the user-provided filter of other side */
228 CommImplPtr this_comm(new CommImpl());
229 this_comm->set_type(CommImplType::SEND);
231 /* Look for communication synchro matching our needs. We also provide a description of
232 * ourself so that the other side also gets a chance of choosing if it wants to match with us.
234 * If it is not found then push our communication into the rendez-vous point */
235 CommImplPtr other_comm =
236 mbox->find_matching_comm(CommImplType::RECEIVE, observer->get_match_fun(), observer->get_payload(), this_comm,
237 /*done*/ false, /*remove_matching*/ true);
239 if (not other_comm) {
240 other_comm = std::move(this_comm);
242 if (mbox->is_permanent()) {
243 // this mailbox is for small messages, which have to be sent right now
244 other_comm->set_state(State::READY);
245 other_comm->dst_actor_ = mbox->get_permanent_receiver().get();
246 mbox->push_done(other_comm);
247 XBT_DEBUG("pushing a message into the permanent receive list %p, comm %p", mbox, other_comm.get());
250 mbox->push(other_comm);
253 XBT_DEBUG("Receive already pushed");
255 other_comm->set_state(State::READY);
257 observer->set_comm(other_comm.get());
259 if (observer->is_detached()) {
260 other_comm->detach();
261 other_comm->clean_fun = observer->get_clean_fun();
263 other_comm->clean_fun = nullptr;
264 observer->get_issuer()->activities_.insert(other_comm);
267 /* Setup the communication synchro */
268 other_comm->src_actor_ = observer->get_issuer();
269 other_comm->src_data_ = observer->get_payload();
271 .set_src_buff(observer->get_src_buff(), observer->get_src_buff_size())
272 .set_size(observer->get_payload_size())
273 .set_rate(observer->get_rate());
275 other_comm->match_fun = observer->get_match_fun();
276 other_comm->copy_data_fun = observer->get_copy_data_fun();
278 if (MC_is_active() || MC_record_replay_is_active())
279 other_comm->set_state(simgrid::kernel::activity::State::RUNNING);
283 return (observer->is_detached() ? nullptr : other_comm);
286 ActivityImplPtr CommImpl::irecv(actor::CommIrecvSimcall* observer)
288 CommImplPtr this_synchro(new CommImpl());
289 this_synchro->set_type(CommImplType::RECEIVE);
291 auto* mbox = observer->get_mailbox();
292 XBT_DEBUG("recv from mbox %p. this_synchro=%p", mbox, this_synchro.get());
294 CommImplPtr other_comm;
295 // communication already done, get it inside the list of completed comms
296 if (mbox->is_permanent() && mbox->has_some_done_comm()) {
297 XBT_DEBUG("We have a comm that has probably already been received, trying to match it, to skip the communication");
298 // find a match in the list of already received comms
299 other_comm = mbox->find_matching_comm(CommImplType::SEND, observer->get_match_fun(), observer->get_payload(),
300 this_synchro, /*done*/ true, /*remove_matching*/ true);
301 if (other_comm && other_comm->model_action_ && other_comm->get_remaining() < 1e-12) {
302 XBT_DEBUG("comm %p has been already sent, and is finished, destroy it", other_comm.get());
303 other_comm->set_state(State::DONE);
304 other_comm->set_mailbox(nullptr);
306 // if not found, assume the receiver came first, register it to the mailbox in the classical way
307 if (not other_comm) {
308 XBT_DEBUG("We have messages in the permanent receive list, but not the one we are looking for, pushing request "
310 other_comm = std::move(this_synchro);
311 mbox->push(other_comm);
313 observer->get_issuer()->activities_.insert(other_comm);
316 /* Prepare a comm describing us, so that it gets passed to the user-provided filter of other side */
318 /* Look for communication activity matching our needs. We also provide a description of
319 * ourself so that the other side also gets a chance of choosing if it wants to match with us.
321 * If it is not found then push our communication into the rendez-vous point */
322 other_comm = mbox->find_matching_comm(CommImplType::SEND, observer->get_match_fun(), observer->get_payload(),
323 this_synchro, /*done*/ false, /*remove_matching*/ true);
325 if (other_comm == nullptr) {
326 XBT_DEBUG("Receive pushed first (%zu comm enqueued so far)", mbox->size());
327 other_comm = std::move(this_synchro);
328 mbox->push(other_comm);
330 XBT_DEBUG("Match my %p with the existing %p", this_synchro.get(), other_comm.get());
332 other_comm->set_state(simgrid::kernel::activity::State::READY);
334 observer->get_issuer()->activities_.insert(other_comm);
336 observer->set_comm(other_comm.get());
338 /* Setup communication synchro */
339 other_comm->dst_actor_ = observer->get_issuer();
340 other_comm->dst_data_ = observer->get_payload();
341 other_comm->set_dst_buff(observer->get_dst_buff(), observer->get_dst_buff_size());
343 if (observer->get_rate() > -1.0 && (other_comm->get_rate() < 0.0 || observer->get_rate() < other_comm->get_rate()))
344 other_comm->set_rate(observer->get_rate());
346 other_comm->match_fun = observer->get_match_fun();
347 other_comm->copy_data_fun = observer->get_copy_data_fun();
349 if (MC_is_active() || MC_record_replay_is_active()) {
350 other_comm->set_state(State::RUNNING);
358 bool CommImpl::test(actor::ActorImpl* issuer)
360 if ((MC_is_active() || MC_record_replay_is_active()) && src_actor_ && dst_actor_)
361 set_state(State::DONE);
362 return ActivityImpl::test(issuer);
365 void CommImpl::wait_for(actor::ActorImpl* issuer, double timeout)
367 XBT_DEBUG("CommImpl::wait_for(%g), %p, state %s", timeout, this, get_state_str());
369 /* Associate this simcall to the wait synchro */
370 register_simcall(&issuer->simcall_);
371 if (MC_is_active() || MC_record_replay_is_active()) {
372 // FIXME: what about timeouts?
373 set_state(State::DONE);
377 ActivityImpl::wait_for(issuer, timeout);
380 void CommImpl::wait_any_for(actor::ActorImpl* issuer, const std::vector<CommImpl*>& comms, double timeout)
382 std::vector<ActivityImpl*> activities(comms.begin(), comms.end());
383 ActivityImpl::wait_any_for(issuer, activities, timeout);
386 void CommImpl::suspend()
388 /* FIXME: shall we suspend also the timeout synchro? */
390 model_action_->suspend();
391 /* if not created yet, the action will be suspended on creation, in CommImpl::start() */
394 void CommImpl::resume()
396 /*FIXME: check what happen with the timeouts */
398 model_action_->resume();
399 /* in the other case, the synchro were not really suspended yet, see CommImpl::suspend() and CommImpl::start() */
402 void CommImpl::cancel()
404 /* if the synchro is a waiting state means that it is still in a mbox so remove from it and delete it */
405 if (get_state() == State::WAITING) {
408 set_state(State::CANCELED);
410 } else if (not MC_is_active() /* when running the MC there are no model actions */
411 && not MC_record_replay_is_active() && (get_state() == State::READY || get_state() == State::RUNNING)) {
412 model_action_->cancel();
416 void CommImpl::set_exception(actor::ActorImpl* issuer)
418 switch (get_state()) {
420 issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
422 case State::SRC_TIMEOUT:
424 std::make_exception_ptr(TimeoutException(XBT_THROW_POINT, "Communication timeouted because of the sender"));
427 case State::DST_TIMEOUT:
429 std::make_exception_ptr(TimeoutException(XBT_THROW_POINT, "Communication timeouted because of the receiver"));
432 case State::SRC_HOST_FAILURE:
433 if (issuer == src_actor_)
434 issuer->set_wannadie();
436 set_state(State::FAILED);
437 issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
441 case State::DST_HOST_FAILURE:
442 if (issuer == dst_actor_)
443 issuer->set_wannadie();
445 set_state(State::FAILED);
446 issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
450 case State::LINK_FAILURE:
451 XBT_DEBUG("Link failure in synchro %p between '%s' and '%s': posting an exception to the issuer: %s (%p) "
453 this, src_actor_ ? src_actor_->get_host()->get_cname() : nullptr,
454 dst_actor_ ? dst_actor_->get_host()->get_cname() : nullptr, issuer->get_cname(), issuer, detached_);
455 if (src_actor_ == issuer) {
456 XBT_DEBUG("I'm source");
457 } else if (dst_actor_ == issuer) {
458 XBT_DEBUG("I'm dest");
460 XBT_DEBUG("I'm neither source nor dest");
462 set_state(State::FAILED);
463 issuer->throw_exception(std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Link failure")));
466 case State::CANCELED:
467 if (issuer == dst_actor_)
469 std::make_exception_ptr(CancelException(XBT_THROW_POINT, "Communication canceled by the sender"));
472 std::make_exception_ptr(CancelException(XBT_THROW_POINT, "Communication canceled by the receiver"));
476 xbt_assert(get_state() == State::DONE, "Internal error in CommImpl::finish(): unexpected synchro state %s",
481 void CommImpl::finish()
483 XBT_DEBUG("CommImpl::finish() comm %p, state %s, src_proc %p, dst_proc %p, detached: %d", this, get_state_str(),
484 src_actor_.get(), dst_actor_.get(), detached_);
487 const auto& piface = static_cast<const s4u::Comm&>(*get_iface());
488 set_iface(nullptr); // reset iface to protect against multiple trigger of the on_completion signals
489 piface.fire_on_completion_for_real();
490 piface.fire_on_this_completion_for_real();
493 /* Update synchro state */
494 if (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FINISHED)
495 set_state(State::SRC_TIMEOUT);
496 else if (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FINISHED)
497 set_state(State::DST_TIMEOUT);
498 else if ((from_ && not from_->is_on()) ||
499 (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FAILED))
500 set_state(State::SRC_HOST_FAILURE);
501 else if ((to_ && not to_->is_on()) || (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FAILED))
502 set_state(State::DST_HOST_FAILURE);
503 else if (model_action_ && model_action_->get_state() == resource::Action::State::FAILED) {
504 set_state(State::LINK_FAILURE);
505 } else if (get_state() == State::RUNNING) {
506 xbt_assert(from_ && from_->is_on());
507 xbt_assert(to_ && to_->is_on());
508 set_state(State::DONE);
510 src_timeout_ = nullptr;
511 dst_timeout_ = nullptr;
513 /* destroy the model actions associated with the communication activity */
516 /* If the synchro is still in a rendez-vous point then remove from it */
520 if (get_state() == State::DONE)
524 EngineImpl::get_instance()->get_maestro()->activities_.erase(this);
526 while (not simcalls_.empty()) {
527 actor::Simcall* simcall = simcalls_.front();
528 simcalls_.pop_front();
530 /* If a waitany simcall is waiting for this synchro to finish, then remove it from the other synchros in the waitany
531 * list. Afterwards, get the position of the actual synchro in the waitany list and return it as the result of the
534 if (simcall->call_ == actor::Simcall::Type::NONE) // FIXME: maybe a better way to handle this case
535 continue; // if actor handling comm is killed
537 handle_activity_waitany(simcall);
539 /* Check out for errors */
541 if (not simcall->issuer_->get_host()->is_on()) {
542 simcall->issuer_->set_wannadie();
544 // Do not answer to dying actors
545 if (not simcall->issuer_->wannadie()) {
546 set_exception(simcall->issuer_);
547 simcall->issuer_->simcall_answer();
551 simcall->issuer_->waiting_synchro_ = nullptr;
552 simcall->issuer_->activities_.erase(this);
554 if (simcall->issuer_ != dst_actor_ && dst_actor_ != nullptr)
555 dst_actor_->activities_.erase(this);
556 if (simcall->issuer_ != src_actor_ && src_actor_ != nullptr)
557 src_actor_->activities_.erase(this);
562 } // namespace simgrid::kernel::activity