1 /* Copyright (c) 2006-2022. 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. */
7 #include <simgrid/Exception.hpp>
8 #include <simgrid/comm.h>
9 #include <simgrid/s4u/Comm.hpp>
10 #include <simgrid/s4u/Engine.hpp>
11 #include <simgrid/s4u/Mailbox.hpp>
14 #include "src/kernel/activity/CommImpl.hpp"
15 #include "src/kernel/actor/ActorImpl.hpp"
16 #include "src/kernel/actor/SimcallObserver.hpp"
17 #include "src/mc/mc_replay.hpp"
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(s4u_comm, s4u_activity, "S4U asynchronous communications");
21 namespace simgrid::s4u {
22 xbt::signal<void(Comm const&)> Comm::on_send;
23 xbt::signal<void(Comm const&)> Comm::on_recv;
25 CommPtr Comm::set_copy_data_callback(const std::function<void(kernel::activity::CommImpl*, void*, size_t)>& callback)
27 copy_data_function_ = callback;
31 void Comm::copy_buffer_callback(kernel::activity::CommImpl* comm, void* buff, size_t buff_size)
33 XBT_DEBUG("Copy the data over");
34 memcpy(comm->dst_buff_, buff, buff_size);
35 if (comm->is_detached()) { // if this is a detached send, the source buffer was duplicated by SMPI sender to make the
36 // original buffer available to the application ASAP
38 comm->src_buff_ = nullptr;
42 void Comm::copy_pointer_callback(kernel::activity::CommImpl* comm, void* buff, size_t buff_size)
44 xbt_assert((buff_size == sizeof(void*)), "Cannot copy %zu bytes: must be sizeof(void*)", buff_size);
45 *(void**)(comm->dst_buff_) = buff;
50 if (state_ == State::STARTED && not detached_ &&
51 (pimpl_ == nullptr || pimpl_->get_state() == kernel::activity::State::RUNNING)) {
52 XBT_INFO("Comm %p freed before its completion. Did you forget to detach it? (state: %s)", this, get_state_str());
53 if (pimpl_ != nullptr)
54 XBT_INFO("pimpl_->state: %s", pimpl_->get_state_str());
56 XBT_INFO("pimpl_ is null");
57 xbt_backtrace_display_current();
61 void Comm::send(kernel::actor::ActorImpl* sender, const Mailbox* mbox, double task_size, double rate, void* src_buff,
63 const std::function<bool(void*, void*, simgrid::kernel::activity::CommImpl*)>& match_fun,
64 const std::function<void(simgrid::kernel::activity::CommImpl*, void*, size_t)>& copy_data_fun,
65 void* data, double timeout)
67 /* checking for infinite values */
68 xbt_assert(std::isfinite(task_size), "task_size is not finite!");
69 xbt_assert(std::isfinite(rate), "rate is not finite!");
70 xbt_assert(std::isfinite(timeout), "timeout is not finite!");
72 xbt_assert(mbox, "No rendez-vous point defined for send");
74 if (MC_is_active() || MC_record_replay_is_active()) {
75 /* the model-checker wants two separate simcalls, and wants comm to be nullptr during the simcall */
76 simgrid::kernel::activity::ActivityImplPtr comm = nullptr;
78 simgrid::kernel::actor::CommIsendSimcall send_observer{
79 sender, mbox->get_impl(), task_size, rate, static_cast<unsigned char*>(src_buff), src_buff_size, match_fun,
80 nullptr, copy_data_fun, data, false};
81 comm = simgrid::kernel::actor::simcall_answered(
82 [&send_observer] { return simgrid::kernel::activity::CommImpl::isend(&send_observer); }, &send_observer);
84 simgrid::kernel::actor::ActivityWaitSimcall wait_observer{sender, comm.get(), timeout};
85 if (simgrid::kernel::actor::simcall_blocking(
87 wait_observer.get_activity()->wait_for(wait_observer.get_issuer(), wait_observer.get_timeout());
90 throw simgrid::TimeoutException(XBT_THROW_POINT, "Timeouted");
94 simgrid::kernel::actor::CommIsendSimcall observer(sender, mbox->get_impl(), task_size, rate,
95 static_cast<unsigned char*>(src_buff), src_buff_size, match_fun,
96 nullptr, copy_data_fun, data, false);
97 simgrid::kernel::actor::simcall_blocking([&observer, timeout] {
98 simgrid::kernel::activity::ActivityImplPtr comm = simgrid::kernel::activity::CommImpl::isend(&observer);
99 comm->wait_for(observer.get_issuer(), timeout);
104 void Comm::recv(kernel::actor::ActorImpl* receiver, const Mailbox* mbox, void* dst_buff, size_t* dst_buff_size,
105 const std::function<bool(void*, void*, simgrid::kernel::activity::CommImpl*)>& match_fun,
106 const std::function<void(simgrid::kernel::activity::CommImpl*, void*, size_t)>& copy_data_fun,
107 void* data, double timeout, double rate)
109 xbt_assert(std::isfinite(timeout), "timeout is not finite!");
110 xbt_assert(mbox, "No rendez-vous point defined for recv");
112 if (MC_is_active() || MC_record_replay_is_active()) {
113 /* the model-checker wants two separate simcalls, and wants comm to be nullptr during the simcall */
114 simgrid::kernel::activity::ActivityImplPtr comm = nullptr;
116 simgrid::kernel::actor::CommIrecvSimcall observer{receiver,
118 static_cast<unsigned char*>(dst_buff),
124 comm = simgrid::kernel::actor::simcall_answered(
125 [&observer] { return simgrid::kernel::activity::CommImpl::irecv(&observer); }, &observer);
127 simgrid::kernel::actor::ActivityWaitSimcall wait_observer{receiver, comm.get(), timeout};
128 if (simgrid::kernel::actor::simcall_blocking(
130 wait_observer.get_activity()->wait_for(wait_observer.get_issuer(), wait_observer.get_timeout());
133 throw simgrid::TimeoutException(XBT_THROW_POINT, "Timeouted");
137 simgrid::kernel::actor::CommIrecvSimcall observer(receiver, mbox->get_impl(), static_cast<unsigned char*>(dst_buff),
138 dst_buff_size, match_fun, copy_data_fun, data, rate);
139 simgrid::kernel::actor::simcall_blocking([&observer, timeout] {
140 simgrid::kernel::activity::ActivityImplPtr comm = simgrid::kernel::activity::CommImpl::irecv(&observer);
141 comm->wait_for(observer.get_issuer(), timeout);
146 CommPtr Comm::sendto_init()
148 CommPtr res(new Comm());
149 res->pimpl_ = kernel::activity::CommImplPtr(new kernel::activity::CommImpl());
150 boost::static_pointer_cast<kernel::activity::CommImpl>(res->pimpl_)->detach();
151 res->sender_ = kernel::actor::ActorImpl::self();
155 CommPtr Comm::sendto_init(Host* from, Host* to)
157 auto res = Comm::sendto_init()->set_source(from)->set_destination(to);
158 res->set_state(State::STARTING);
162 CommPtr Comm::sendto_async(Host* from, Host* to, uint64_t simulated_size_in_bytes)
164 return Comm::sendto_init()->set_payload_size(simulated_size_in_bytes)->set_source(from)->set_destination(to);
167 void Comm::sendto(Host* from, Host* to, uint64_t simulated_size_in_bytes)
169 sendto_async(from, to, simulated_size_in_bytes)->wait();
172 CommPtr Comm::set_source(Host* from)
174 xbt_assert(state_ == State::INITED || state_ == State::STARTING,
175 "Cannot change the source of a Comm once it's started (state: %s)", to_c_str(state_));
176 boost::static_pointer_cast<kernel::activity::CommImpl>(pimpl_)->set_source(from);
177 // Setting 'source' may allow to start the activity, let's try
178 if (state_ == State::STARTING && remains_ <= 0)
179 XBT_DEBUG("This communication has a payload size of 0 byte. It cannot start yet");
185 Host* Comm::get_source() const
187 return pimpl_ ? boost::static_pointer_cast<kernel::activity::CommImpl>(pimpl_)->get_source() : nullptr;
190 CommPtr Comm::set_destination(Host* to)
192 xbt_assert(state_ == State::INITED || state_ == State::STARTING,
193 "Cannot change the destination of a Comm once it's started (state: %s)", to_c_str(state_));
194 boost::static_pointer_cast<kernel::activity::CommImpl>(pimpl_)->set_destination(to);
195 // Setting 'destination' may allow to start the activity, let's try
196 if (state_ == State::STARTING && remains_ <= 0)
197 XBT_DEBUG("This communication has a payload size of 0 byte. It cannot start yet");
204 Host* Comm::get_destination() const
206 return pimpl_ ? boost::static_pointer_cast<kernel::activity::CommImpl>(pimpl_)->get_destination() : nullptr;
209 CommPtr Comm::set_rate(double rate)
211 xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
217 CommPtr Comm::set_mailbox(Mailbox* mailbox)
219 xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
225 CommPtr Comm::set_src_data(void* buff)
227 xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
229 xbt_assert(dst_buff_ == nullptr, "Cannot set the src and dst buffers at the same time");
234 CommPtr Comm::set_src_data_size(size_t size)
236 xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
238 src_buff_size_ = size;
242 CommPtr Comm::set_src_data(void* buff, size_t size)
244 xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
247 xbt_assert(dst_buff_ == nullptr, "Cannot set the src and dst buffers at the same time");
249 src_buff_size_ = size;
253 CommPtr Comm::set_dst_data(void** buff)
255 xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
257 xbt_assert(src_buff_ == nullptr, "Cannot set the src and dst buffers at the same time");
262 CommPtr Comm::set_dst_data(void** buff, size_t size)
264 xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
267 xbt_assert(src_buff_ == nullptr, "Cannot set the src and dst buffers at the same time");
269 dst_buff_size_ = size;
273 CommPtr Comm::set_payload_size(uint64_t bytes)
275 Activity::set_remaining(bytes);
277 boost::static_pointer_cast<kernel::activity::CommImpl>(pimpl_)->set_size(bytes);
282 Actor* Comm::get_sender() const
284 kernel::actor::ActorImplPtr sender = nullptr;
286 sender = boost::static_pointer_cast<kernel::activity::CommImpl>(pimpl_)->src_actor_;
287 return sender ? sender->get_ciface() : nullptr;
290 bool Comm::is_assigned() const
292 return (pimpl_ && boost::static_pointer_cast<kernel::activity::CommImpl>(pimpl_)->is_assigned()) ||
298 xbt_assert(get_state() == State::INITED || get_state() == State::STARTING,
299 "You cannot use %s() once your communication started (not implemented)", __FUNCTION__);
300 if (get_source() != nullptr || get_destination() != nullptr) {
301 xbt_assert(is_assigned(), "When either from_ or to_ is specified, both must be.");
302 xbt_assert(src_buff_ == nullptr && dst_buff_ == nullptr,
303 "Direct host-to-host communications cannot carry any data.");
304 XBT_DEBUG("host-to-host Comm. Pimpl already created and set, just start it.");
305 kernel::actor::simcall_answered([this] {
306 pimpl_->set_state(kernel::activity::State::READY);
307 boost::static_pointer_cast<kernel::activity::CommImpl>(pimpl_)->start();
309 } else if (src_buff_ != nullptr) { // Sender side
311 kernel::actor::CommIsendSimcall observer{sender_,
312 mailbox_->get_impl(),
315 static_cast<unsigned char*>(src_buff_),
322 pimpl_ = kernel::actor::simcall_answered([&observer] { return kernel::activity::CommImpl::isend(&observer); },
324 } else if (dst_buff_ != nullptr) { // Receiver side
325 xbt_assert(not detached_, "Receive cannot be detached");
327 kernel::actor::CommIrecvSimcall observer{receiver_,
328 mailbox_->get_impl(),
329 static_cast<unsigned char*>(dst_buff_),
335 pimpl_ = kernel::actor::simcall_answered([&observer] { return kernel::activity::CommImpl::irecv(&observer); },
338 xbt_die("Cannot start a communication before specifying whether we are the sender or the receiver");
345 pimpl_->set_iface(this);
346 pimpl_->set_actor(sender_);
349 state_ = State::STARTED;
355 xbt_assert(state_ == State::INITED || state_ == State::STARTING,
356 "You cannot use %s() once your communication is %s (not implemented)", __FUNCTION__, get_state_str());
357 xbt_assert(dst_buff_ == nullptr && dst_buff_size_ == 0, "You can only detach sends, not recvs");
363 ssize_t Comm::test_any(const std::vector<CommPtr>& comms)
365 std::vector<ActivityPtr> activities;
366 for (const auto& comm : comms)
367 activities.push_back(boost::dynamic_pointer_cast<Activity>(comm));
368 return Activity::test_any(activities);
371 /** @brief Block the calling actor until the communication is finished, or until timeout
373 * On timeout, an exception is thrown and the communication is invalidated.
375 * @param timeout the amount of seconds to wait for the comm termination.
376 * Negative values denote infinite wait times. 0 as a timeout returns immediately. */
377 Comm* Comm::wait_for(double timeout)
379 XBT_DEBUG("Calling Comm::wait_for with state %s", get_state_str());
380 kernel::actor::ActorImpl* issuer = nullptr;
382 case State::FINISHED:
385 throw NetworkFailureException(XBT_THROW_POINT, "Cannot wait for a failed communication");
387 case State::STARTING: // It's not started yet. Do it in one simcall if it's a regular communication
388 if (get_source() != nullptr || get_destination() != nullptr) {
389 return vetoable_start()->wait_for(timeout); // In the case of host2host comm, do it in two simcalls
390 } else if (src_buff_ != nullptr) {
392 send(sender_, mailbox_, remains_, rate_, src_buff_, src_buff_size_, match_fun_, copy_data_function_,
393 get_data<void>(), timeout);
397 recv(receiver_, mailbox_, dst_buff_, &dst_buff_size_, match_fun_, copy_data_function_, get_data<void>(),
403 issuer = kernel::actor::ActorImpl::self();
404 kernel::actor::ActivityWaitSimcall observer{issuer, pimpl_.get(), timeout};
405 if (kernel::actor::simcall_blocking(
406 [&observer] { observer.get_activity()->wait_for(observer.get_issuer(), observer.get_timeout()); },
408 throw TimeoutException(XBT_THROW_POINT, "Timeouted");
410 } catch (const NetworkFailureException& e) {
411 issuer->simcall_.observer_ = nullptr; // Comm failed on network failure, reset the observer to nullptr
412 complete(State::FAILED);
413 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
417 case State::CANCELED:
418 throw CancelException(XBT_THROW_POINT, "Communication canceled");
423 complete(State::FINISHED);
427 ssize_t Comm::wait_any_for(const std::vector<CommPtr>& comms, double timeout)
429 std::vector<ActivityPtr> activities;
430 for (const auto& comm : comms)
431 activities.push_back(boost::dynamic_pointer_cast<Activity>(comm));
434 changed_pos = Activity::wait_any_for(activities, timeout);
435 } catch (const NetworkFailureException& e) {
437 for (auto c : comms) {
438 if (c->pimpl_->get_state() == kernel::activity::State::FAILED) {
439 c->complete(State::FAILED);
442 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
447 void Comm::wait_all(const std::vector<CommPtr>& comms)
449 // TODO: this should be a simcall or something
450 for (auto& comm : comms)
454 size_t Comm::wait_all_for(const std::vector<CommPtr>& comms, double timeout)
461 double deadline = Engine::get_clock() + timeout;
462 std::vector<CommPtr> waited_comm(1, nullptr);
463 for (size_t i = 0; i < comms.size(); i++) {
464 double wait_timeout = std::max(0.0, deadline - Engine::get_clock());
465 waited_comm[0] = comms[i];
466 // Using wait_any_for() here (and not wait_for) because we don't want comms to be invalidated on timeout
467 if (wait_any_for(waited_comm, wait_timeout) == -1) {
468 XBT_DEBUG("Timeout (%g): i = %zu", wait_timeout, i);
474 } // namespace simgrid::s4u
475 /* **************************** Public C interface *************************** */
476 void sg_comm_detach(sg_comm_t comm, void (*clean_function)(void*))
478 comm->detach(clean_function);
481 void sg_comm_unref(sg_comm_t comm)
485 int sg_comm_test(sg_comm_t comm)
487 bool finished = comm->test();
493 sg_error_t sg_comm_wait(sg_comm_t comm)
495 return sg_comm_wait_for(comm, -1);
498 sg_error_t sg_comm_wait_for(sg_comm_t comm, double timeout)
500 sg_error_t status = SG_OK;
502 simgrid::s4u::CommPtr s4u_comm(comm, false);
504 s4u_comm->wait_for(timeout);
505 } catch (const simgrid::TimeoutException&) {
506 status = SG_ERROR_TIMEOUT;
507 } catch (const simgrid::CancelException&) {
508 status = SG_ERROR_CANCELED;
509 } catch (const simgrid::NetworkFailureException&) {
510 status = SG_ERROR_NETWORK;
515 void sg_comm_wait_all(sg_comm_t* comms, size_t count)
517 sg_comm_wait_all_for(comms, count, -1);
520 size_t sg_comm_wait_all_for(sg_comm_t* comms, size_t count, double timeout)
522 std::vector<simgrid::s4u::CommPtr> s4u_comms;
523 for (size_t i = 0; i < count; i++)
524 s4u_comms.emplace_back(comms[i], false);
526 size_t pos = simgrid::s4u::Comm::wait_all_for(s4u_comms, timeout);
527 for (size_t i = pos; i < count; i++)
528 s4u_comms[i]->add_ref();
532 ssize_t sg_comm_wait_any(sg_comm_t* comms, size_t count)
534 return sg_comm_wait_any_for(comms, count, -1);
537 ssize_t sg_comm_wait_any_for(sg_comm_t* comms, size_t count, double timeout)
539 std::vector<simgrid::s4u::CommPtr> s4u_comms;
540 for (size_t i = 0; i < count; i++)
541 s4u_comms.emplace_back(comms[i], false);
543 ssize_t pos = simgrid::s4u::Comm::wait_any_for(s4u_comms, timeout);
544 for (size_t i = 0; i < count; i++) {
545 if (pos != -1 && static_cast<size_t>(pos) != i)
546 s4u_comms[i]->add_ref();