Logo AND Algorithmique Numérique Distribuée

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