Logo AND Algorithmique Numérique Distribuée

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