Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
try to get rid of a warning (without causing a dead store in infer?)
[simgrid.git] / src / s4u / s4u_Comm.cpp
1 /* Copyright (c) 2006-2022. 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/msg/msg_private.hpp"
7 //#include "xbt/log.h"
8
9 #include <simgrid/Exception.hpp>
10 #include <simgrid/comm.h>
11 #include <simgrid/s4u/Comm.hpp>
12 #include <simgrid/s4u/Engine.hpp>
13 #include <simgrid/s4u/Mailbox.hpp>
14
15 #include "src/kernel/activity/CommImpl.hpp"
16 #include "src/kernel/actor/ActorImpl.hpp"
17 #include "src/kernel/actor/SimcallObserver.hpp"
18
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(s4u_comm, s4u_activity, "S4U asynchronous communications");
20
21 namespace simgrid {
22 namespace s4u {
23 xbt::signal<void(Comm const&)> Comm::on_send;
24 xbt::signal<void(Comm const&)> Comm::on_recv;
25 xbt::signal<void(Comm const&)> Comm::on_completion;
26
27 Comm::~Comm()
28 {
29   if (state_ == State::STARTED && not detached_ &&
30       (pimpl_ == nullptr || pimpl_->get_state() == kernel::activity::State::RUNNING)) {
31     XBT_INFO("Comm %p freed before its completion. Did you forget to detach it? (state: %s)", this, get_state_str());
32     if (pimpl_ != nullptr)
33       XBT_INFO("pimpl_->state: %s", pimpl_->get_state_str());
34     else
35       XBT_INFO("pimpl_ is null");
36     xbt_backtrace_display_current();
37   }
38 }
39
40 ssize_t Comm::wait_any_for(const std::vector<CommPtr>& comms, double timeout)
41 {
42   std::vector<ActivityPtr> activities;
43   for (const auto& comm : comms)
44     activities.push_back(boost::dynamic_pointer_cast<Activity>(comm));
45   ssize_t changed_pos;
46   try {
47     changed_pos = Activity::wait_any_for(activities, timeout);
48   } catch (const NetworkFailureException& e) {
49     changed_pos = -1;
50     for (auto c : comms) {
51       if (c->pimpl_->get_state() == kernel::activity::State::FAILED) {
52         c->complete(State::FAILED);
53       }
54     }
55     e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
56   }
57   return changed_pos;
58 }
59
60 void Comm::wait_all(const std::vector<CommPtr>& comms)
61 {
62   // TODO: this should be a simcall or something
63   for (auto& comm : comms)
64     comm->wait();
65 }
66
67 size_t Comm::wait_all_for(const std::vector<CommPtr>& comms, double timeout)
68 {
69   if (timeout < 0.0) {
70     wait_all(comms);
71     return comms.size();
72   }
73
74   double deadline = Engine::get_clock() + timeout;
75   std::vector<CommPtr> waited_comm(1, nullptr);
76   for (size_t i = 0; i < comms.size(); i++) {
77     double wait_timeout = std::max(0.0, deadline - Engine::get_clock());
78     waited_comm[0]      = comms[i];
79     // Using wait_any_for() here (and not wait_for) because we don't want comms to be invalidated on timeout
80     if (wait_any_for(waited_comm, wait_timeout) == -1) {
81       XBT_DEBUG("Timeout (%g): i = %zu", wait_timeout, i);
82       return i;
83     }
84   }
85   return comms.size();
86 }
87
88 CommPtr Comm::set_source(Host* from)
89 {
90   xbt_assert(state_ == State::INITED || state_ == State::STARTING,
91              "Cannot change the source of a Comm once it's started (state: %s)", to_c_str(state_));
92   from_ = from;
93   // Setting 'from_' may allow to start the activity, let's try
94   vetoable_start();
95
96   return this;
97 }
98
99 CommPtr Comm::set_destination(Host* to)
100 {
101   xbt_assert(state_ == State::INITED || state_ == State::STARTING,
102              "Cannot change the destination of a Comm once it's started (state: %s)", to_c_str(state_));
103   to_ = to;
104   // Setting 'to_' may allow to start the activity, let's try
105   vetoable_start();
106
107   return this;
108 }
109
110 CommPtr Comm::set_rate(double rate)
111 {
112   xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
113              __FUNCTION__);
114   rate_ = rate;
115   return this;
116 }
117
118 CommPtr Comm::set_src_data(void* buff)
119 {
120   xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
121              __FUNCTION__);
122   xbt_assert(dst_buff_ == nullptr, "Cannot set the src and dst buffers at the same time");
123   src_buff_ = buff;
124   return this;
125 }
126
127 CommPtr Comm::set_src_data_size(size_t size)
128 {
129   xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
130              __FUNCTION__);
131   src_buff_size_ = size;
132   return this;
133 }
134
135 CommPtr Comm::set_src_data(void* buff, size_t size)
136 {
137   xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
138              __FUNCTION__);
139
140   xbt_assert(dst_buff_ == nullptr, "Cannot set the src and dst buffers at the same time");
141   src_buff_      = buff;
142   src_buff_size_ = size;
143   return this;
144 }
145
146 CommPtr Comm::set_dst_data(void** buff)
147 {
148   xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
149              __FUNCTION__);
150   xbt_assert(src_buff_ == nullptr, "Cannot set the src and dst buffers at the same time");
151   dst_buff_ = buff;
152   return this;
153 }
154 void* Comm::get_dst_data()
155 {
156   return dst_buff_;
157 }
158
159 size_t Comm::get_dst_data_size() const
160 {
161   return dst_buff_size_;
162 }
163 CommPtr Comm::set_dst_data(void** buff, size_t size)
164 {
165   xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication started (not implemented)",
166              __FUNCTION__);
167
168   xbt_assert(src_buff_ == nullptr, "Cannot set the src and dst buffers at the same time");
169   dst_buff_      = buff;
170   dst_buff_size_ = size;
171   return this;
172 }
173 CommPtr Comm::set_payload_size(uint64_t bytes)
174 {
175   Activity::set_remaining(bytes);
176   return this;
177 }
178
179 CommPtr Comm::sendto_init()
180 {
181   CommPtr res(new Comm());
182   res->sender_ = kernel::actor::ActorImpl::self();
183   return res;
184 }
185
186 CommPtr Comm::sendto_init(Host* from, Host* to)
187 {
188   auto res   = Comm::sendto_init();
189   res->from_ = from;
190   res->to_   = to;
191
192   return res;
193 }
194
195 CommPtr Comm::sendto_async(Host* from, Host* to, uint64_t simulated_size_in_bytes)
196 {
197   auto res = Comm::sendto_init(from, to)->set_payload_size(simulated_size_in_bytes);
198   res->vetoable_start();
199   return res;
200 }
201
202 void Comm::sendto(Host* from, Host* to, uint64_t simulated_size_in_bytes)
203 {
204   sendto_async(from, to, simulated_size_in_bytes)->wait();
205 }
206
207 Comm* Comm::start()
208 {
209   xbt_assert(get_state() == State::INITED || get_state() == State::STARTING,
210              "You cannot use %s() once your communication started (not implemented)", __FUNCTION__);
211   if (from_ != nullptr || to_ != nullptr) {
212     xbt_assert(from_ != nullptr && to_ != nullptr, "When either from_ or to_ is specified, both must be.");
213     xbt_assert(src_buff_ == nullptr && dst_buff_ == nullptr,
214                "Direct host-to-host communications cannot carry any data.");
215     pimpl_ = kernel::actor::simcall([this] {
216       kernel::activity::CommImplPtr res(new kernel::activity::CommImpl(this->from_, this->to_, this->get_remaining()));
217       res->start();
218       return res;
219     });
220
221   } else if (src_buff_ != nullptr) { // Sender side
222     on_send(*this);
223     kernel::actor::CommIsendSimcall observer{sender_,
224                                              mailbox_->get_impl(),
225                                              remains_,
226                                              rate_,
227                                              static_cast<unsigned char*>(src_buff_),
228                                              src_buff_size_,
229                                              match_fun_,
230                                              clean_fun_,
231                                              copy_data_function_,
232                                              get_data<void>(),
233                                              detached_};
234     pimpl_ = kernel::actor::simcall([&observer] { return kernel::activity::CommImpl::isend(&observer); }, &observer);
235   } else if (dst_buff_ != nullptr) { // Receiver side
236     xbt_assert(not detached_, "Receive cannot be detached");
237     on_recv(*this);
238     kernel::actor::CommIrecvSimcall observer{receiver_,
239                                              mailbox_->get_impl(),
240                                              static_cast<unsigned char*>(dst_buff_),
241                                              &dst_buff_size_,
242                                              match_fun_,
243                                              copy_data_function_,
244                                              get_data<void>(),
245                                              rate_};
246     pimpl_ = kernel::actor::simcall([&observer] { return kernel::activity::CommImpl::irecv(&observer); }, &observer);
247   } else {
248     xbt_die("Cannot start a communication before specifying whether we are the sender or the receiver");
249   }
250
251   if (suspended_)
252     pimpl_->suspend();
253
254   if (not detached_) {
255     pimpl_->set_iface(this);
256     pimpl_->set_actor(sender_);
257   }
258
259   state_ = State::STARTED;
260   return this;
261 }
262
263 /** @brief Block the calling actor until the communication is finished, or until timeout
264  *
265  * On timeout, an exception is thrown and the communication is invalidated.
266  *
267  * @param timeout the amount of seconds to wait for the comm termination.
268  *                Negative values denote infinite wait times. 0 as a timeout returns immediately. */
269 Comm* Comm::wait_for(double timeout)
270 {
271   XBT_DEBUG("Calling Comm::wait_for with state %s", get_state_str());
272   kernel::actor::ActorImpl* issuer = nullptr;
273   switch (state_) {
274     case State::FINISHED:
275       break;
276     case State::FAILED:
277       throw NetworkFailureException(XBT_THROW_POINT, "Cannot wait for a failed communication");
278     case State::INITED:
279     case State::STARTING: // It's not started yet. Do it in one simcall if it's a regular communication
280       if (from_ != nullptr || to_ != nullptr) {
281         return vetoable_start()->wait_for(timeout); // In the case of host2host comm, do it in two simcalls
282       } else if (src_buff_ != nullptr) {
283         on_send(*this);
284         simcall_comm_send(sender_, mailbox_->get_impl(), remains_, rate_, src_buff_, src_buff_size_, match_fun_,
285                           copy_data_function_, get_data<void>(), timeout);
286
287       } else { // Receiver
288         on_recv(*this);
289         simcall_comm_recv(receiver_, mailbox_->get_impl(), dst_buff_, &dst_buff_size_, match_fun_, copy_data_function_,
290                           get_data<void>(), timeout, rate_);
291       }
292       break;
293     case State::STARTED:
294       try {
295         issuer = kernel::actor::ActorImpl::self();
296         kernel::actor::ActivityWaitSimcall observer{issuer, pimpl_.get(), timeout};
297         if (kernel::actor::simcall_blocking(
298                 [&observer] { observer.get_activity()->wait_for(observer.get_issuer(), observer.get_timeout()); },
299                 &observer)) {
300           throw TimeoutException(XBT_THROW_POINT, "Timeouted");
301         }
302       } catch (const NetworkFailureException& e) {
303         issuer->simcall_.observer_ = nullptr; // Comm failed on network failure, reset the observer to nullptr
304         complete(State::FAILED);
305         e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
306       }
307       break;
308
309     case State::CANCELED:
310       throw CancelException(XBT_THROW_POINT, "Communication canceled");
311
312     default:
313       THROW_IMPOSSIBLE;
314   }
315   complete(State::FINISHED);
316   return this;
317 }
318
319 ssize_t Comm::test_any(const std::vector<CommPtr>& comms)
320 {
321   std::vector<ActivityPtr> activities;
322   for (const auto& comm : comms)
323     activities.push_back(boost::dynamic_pointer_cast<Activity>(comm));
324   return Activity::test_any(activities);
325 }
326
327 Comm* Comm::detach()
328 {
329   xbt_assert(state_ == State::INITED, "You cannot use %s() once your communication is %s (not implemented)",
330              __FUNCTION__, get_state_str());
331   xbt_assert(dst_buff_ == nullptr && dst_buff_size_ == 0, "You can only detach sends, not recvs");
332   detached_ = true;
333   vetoable_start();
334   return this;
335 }
336
337 Mailbox* Comm::get_mailbox() const
338 {
339   return mailbox_;
340 }
341
342 Actor* Comm::get_sender() const
343 {
344   kernel::actor::ActorImplPtr sender = nullptr;
345   if (pimpl_)
346     sender = boost::static_pointer_cast<kernel::activity::CommImpl>(pimpl_)->src_actor_;
347   return sender ? sender->get_ciface() : nullptr;
348 }
349
350 CommPtr Comm::set_copy_data_callback(void (*callback)(kernel::activity::CommImpl*, void*, size_t))
351 {
352   copy_data_function_ = callback;
353   return this;
354 }
355 void Comm::copy_buffer_callback(kernel::activity::CommImpl* comm, void* buff, size_t buff_size)
356 {
357   XBT_DEBUG("Copy the data over");
358   memcpy(comm->dst_buff_, buff, buff_size);
359   if (comm->detached()) { // if this is a detached send, the source buffer was duplicated by SMPI sender to make the
360                           // original buffer available to the application ASAP
361     xbt_free(buff);
362     comm->src_buff_ = nullptr;
363   }
364 }
365
366 void Comm::copy_pointer_callback(kernel::activity::CommImpl* comm, void* buff, size_t buff_size)
367 {
368   xbt_assert((buff_size == sizeof(void*)), "Cannot copy %zu bytes: must be sizeof(void*)", buff_size);
369   *(void**)(comm->dst_buff_) = buff;
370 }
371
372 } // namespace s4u
373 } // namespace simgrid
374 /* **************************** Public C interface *************************** */
375 void sg_comm_detach(sg_comm_t comm, void (*clean_function)(void*))
376 {
377   comm->detach(clean_function);
378   comm->unref();
379 }
380 void sg_comm_unref(sg_comm_t comm)
381 {
382   comm->unref();
383 }
384 int sg_comm_test(sg_comm_t comm)
385 {
386   bool finished = comm->test();
387   if (finished)
388     comm->unref();
389   return finished;
390 }
391
392 sg_error_t sg_comm_wait(sg_comm_t comm)
393 {
394   return sg_comm_wait_for(comm, -1);
395 }
396
397 sg_error_t sg_comm_wait_for(sg_comm_t comm, double timeout)
398 {
399   sg_error_t status = SG_OK;
400
401   simgrid::s4u::CommPtr s4u_comm(comm, false);
402   try {
403     s4u_comm->wait_for(timeout);
404   } catch (const simgrid::TimeoutException&) {
405     status = SG_ERROR_TIMEOUT;
406   } catch (const simgrid::CancelException&) {
407     status = SG_ERROR_CANCELED;
408   } catch (const simgrid::NetworkFailureException&) {
409     status = SG_ERROR_NETWORK;
410   }
411   return status;
412 }
413
414 void sg_comm_wait_all(sg_comm_t* comms, size_t count)
415 {
416   sg_comm_wait_all_for(comms, count, -1);
417 }
418
419 size_t sg_comm_wait_all_for(sg_comm_t* comms, size_t count, double timeout)
420 {
421   std::vector<simgrid::s4u::CommPtr> s4u_comms;
422   for (size_t i = 0; i < count; i++)
423     s4u_comms.emplace_back(comms[i], false);
424
425   size_t pos = simgrid::s4u::Comm::wait_all_for(s4u_comms, timeout);
426   for (size_t i = pos; i < count; i++)
427     s4u_comms[i]->add_ref();
428   return pos;
429 }
430
431 ssize_t sg_comm_wait_any(sg_comm_t* comms, size_t count)
432 {
433   return sg_comm_wait_any_for(comms, count, -1);
434 }
435
436 ssize_t sg_comm_wait_any_for(sg_comm_t* comms, size_t count, double timeout)
437 {
438   std::vector<simgrid::s4u::CommPtr> s4u_comms;
439   for (size_t i = 0; i < count; i++)
440     s4u_comms.emplace_back(comms[i], false);
441
442   ssize_t pos = simgrid::s4u::Comm::wait_any_for(s4u_comms, timeout);
443   for (size_t i = 0; i < count; i++) {
444     if (pos != -1 && static_cast<size_t>(pos) != i)
445       s4u_comms[i]->add_ref();
446   }
447   return pos;
448 }