Logo AND Algorithmique Numérique Distribuée

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