Logo AND Algorithmique Numérique Distribuée

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