Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
use get_unique_data()
[simgrid.git] / src / kernel / activity / CommImpl.cpp
1 /* Copyright (c) 2007-2023. 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 <simgrid/Exception.hpp>
7 #include <simgrid/kernel/routing/NetPoint.hpp>
8 #include <simgrid/modelchecker.h>
9 #include <simgrid/s4u/Host.hpp>
10
11 #include "src/kernel/EngineImpl.hpp"
12 #include "src/kernel/activity/CommImpl.hpp"
13 #include "src/kernel/activity/MailboxImpl.hpp"
14 #include "src/kernel/actor/SimcallObserver.hpp"
15 #include "src/kernel/resource/CpuImpl.hpp"
16 #include "src/kernel/resource/NetworkModel.hpp"
17 #include "src/kernel/resource/StandardLinkImpl.hpp"
18 #include "src/mc/mc_replay.hpp"
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_network, kernel, "Kernel network-related synchronization");
21
22 namespace simgrid::kernel::activity {
23
24 std::function<void(CommImpl*, void*, size_t)> CommImpl::copy_data_callback_ = [](kernel::activity::CommImpl* comm,
25                                                                                  void* buff, size_t buff_size) {
26   xbt_assert((buff_size == sizeof(void*)), "Cannot copy %zu bytes: must be sizeof(void*)", buff_size);
27   *(void**)(comm->dst_buff_) = buff;
28 };
29
30 void CommImpl::set_copy_data_callback(const std::function<void(CommImpl*, void*, size_t)>& callback)
31 {
32   copy_data_callback_ = callback;
33 }
34
35 CommImpl& CommImpl::set_type(CommImplType type)
36 {
37   type_ = type;
38   return *this;
39 }
40
41 CommImpl& CommImpl::set_source(s4u::Host* from)
42 {
43   xbt_assert( from_ == nullptr );
44   from_ = from;
45   add_host(from);
46   return *this;
47 }
48
49 CommImpl& CommImpl::set_destination(s4u::Host* to)
50 {
51   xbt_assert( to_ == nullptr );
52   to_ = to;
53   add_host(to_);
54   return *this;
55 }
56
57 CommImpl& CommImpl::set_size(double size)
58 {
59   size_ = size;
60   return *this;
61 }
62
63 CommImpl& CommImpl::set_rate(double rate)
64 {
65   rate_ = rate;
66   return *this;
67 }
68 CommImpl& CommImpl::set_mailbox(MailboxImpl* mbox)
69 {
70   if (mbox != nullptr)
71     mbox_id_ = mbox->get_id();
72   mbox_ = mbox;
73   return *this;
74 }
75
76 CommImpl& CommImpl::set_src_buff(unsigned char* buff, size_t size)
77 {
78   src_buff_      = buff;
79   src_buff_size_ = size;
80   return *this;
81 }
82
83 CommImpl& CommImpl::set_dst_buff(unsigned char* buff, size_t* size)
84 {
85   dst_buff_      = buff;
86   dst_buff_size_ = size;
87   return *this;
88 }
89
90 CommImpl& CommImpl::detach()
91 {
92   detached_ = true;
93   EngineImpl::get_instance()->get_maestro()->activities_.insert(this);
94   return *this;
95 }
96
97 CommImpl::~CommImpl()
98 {
99   XBT_DEBUG("Really free communication %p in state %s (detached = %d)", this, get_state_str(), detached_);
100
101   clean_action();
102
103   if (detached_ && get_state() != State::DONE) {
104     /* the communication has failed and was detached:
105      * we have to free the buffer */
106     if (clean_fun)
107       clean_fun(src_buff_);
108     src_buff_ = nullptr;
109   } else if (mbox_) {
110     mbox_->remove(this);
111   }
112 }
113
114 /**  @brief Starts the simulation of a communication synchro. */
115 CommImpl* CommImpl::start()
116 {
117   /* If both the sender and the receiver are already there, start the communication */
118   if (get_state() == State::READY) {
119     from_ = from_ != nullptr ? from_ : src_actor_->get_host();
120     xbt_assert(from_->is_on());
121     to_   = to_ != nullptr ? to_ : dst_actor_->get_host();
122     xbt_assert(to_->is_on());
123
124     /* Getting the network_model from the origin host
125      * Valid while we have a single network model, otherwise we would need to change this function to first get the
126      * routes and later create the respective model actions */
127     auto net_model = from_->get_netpoint()->get_englobing_zone()->get_network_model();
128
129     model_action_ = net_model->communicate(from_, to_, size_, rate_, false);
130     model_action_->set_activity(this);
131     model_action_->set_category(get_tracing_category());
132     set_start_time(model_action_->get_start_time());
133     set_state(State::RUNNING);
134
135     XBT_DEBUG("Starting communication %p from '%s' to '%s' (model action: %p; state: %s)", this, from_->get_cname(),
136               to_->get_cname(), model_action_, get_state_str());
137
138     /* If a link is failed, detect it immediately */
139     if (model_action_->get_state() == resource::Action::State::FAILED) {
140       XBT_DEBUG("Communication from '%s' to '%s' failed to start because of a link failure", from_->get_cname(),
141                 to_->get_cname());
142       set_state(State::LINK_FAILURE);
143       finish();
144
145     } else if ((src_actor_ != nullptr && src_actor_->is_suspended()) ||
146                (dst_actor_ != nullptr && dst_actor_->is_suspended())) {
147       /* If any of the actor is suspended, create the synchro but stop its execution,
148          it will be restarted when the sender actor resumes */
149       if (src_actor_->is_suspended())
150         XBT_DEBUG("The communication is suspended on startup because src (%s@%s) was suspended since it initiated the "
151                   "communication",
152                   src_actor_->get_cname(), src_actor_->get_host()->get_cname());
153       else
154         XBT_DEBUG("The communication is suspended on startup because dst (%s@%s) was suspended since it initiated the "
155                   "communication",
156                   dst_actor_->get_cname(), dst_actor_->get_host()->get_cname());
157
158       model_action_->suspend();
159     }
160   }
161
162   return this;
163 }
164
165 std::vector<s4u::Link*> CommImpl::get_traversed_links() const
166 {
167   xbt_assert(get_state() != State::WAITING, "You cannot use %s() if your communication is not ready (%s)", __FUNCTION__,
168              get_state_str());
169   std::vector<s4u::Link*> vlinks;
170   XBT_ATTRIB_UNUSED double res = 0;
171   from_->route_to(to_, vlinks, &res);
172   return vlinks;
173 }
174
175 /** @brief Copy the communication data from the sender's buffer to the receiver's one  */
176 void CommImpl::copy_data()
177 {
178   size_t buff_size = src_buff_size_;
179   /* If there is no data to copy then return */
180   if (not src_buff_ || not dst_buff_ || copied_)
181     return;
182
183   XBT_DEBUG("Copying comm %p data from %s (%p) -> %s (%p) (%zu bytes)", this,
184             src_actor_ ? src_actor_->get_host()->get_cname() : "a finished actor", src_buff_,
185             dst_actor_ ? dst_actor_->get_host()->get_cname() : "a finished actor", dst_buff_, buff_size);
186
187   /* Copy at most dst_buff_size bytes of the message to receiver's buffer */
188   if (dst_buff_size_) {
189     buff_size = std::min(buff_size, *dst_buff_size_);
190
191     /* Update the receiver's buffer size to the copied amount */
192     *dst_buff_size_ = buff_size;
193   }
194
195   if (buff_size > 0) {
196     if (copy_data_fun)
197       copy_data_fun(this, src_buff_, buff_size);
198     else
199       copy_data_callback_(this, src_buff_, buff_size);
200   }
201
202   /* Set the copied flag so we copy data only once */
203   /* (this function might be called from both communication ends) */
204   copied_ = true;
205 }
206
207 ActivityImplPtr CommImpl::isend(actor::CommIsendSimcall* observer)
208 {
209   auto* mbox = observer->get_mailbox();
210   XBT_DEBUG("send from mailbox %p", mbox);
211
212   /* Prepare a synchro describing us, so that it gets passed to the user-provided filter of other side */
213   CommImplPtr this_comm(new CommImpl());
214   this_comm->set_type(CommImplType::SEND);
215
216   /* Look for communication synchro matching our needs. We also provide a description of
217    * ourself so that the other side also gets a chance of choosing if it wants to match with us.
218    *
219    * If it is not found then push our communication into the rendez-vous point */
220   CommImplPtr other_comm =
221       mbox->find_matching_comm(CommImplType::RECEIVE, observer->get_match_fun(), observer->get_payload(), this_comm,
222                                /*done*/ false, /*remove_matching*/ true);
223
224   if (not other_comm) {
225     other_comm = std::move(this_comm);
226
227     if (mbox->is_permanent()) {
228       // this mailbox is for small messages, which have to be sent right now
229       other_comm->set_state(State::READY);
230       other_comm->dst_actor_ = mbox->get_permanent_receiver().get();
231       mbox->push_done(other_comm);
232       XBT_DEBUG("pushing a message into the permanent receive list %p, comm %p", mbox, other_comm.get());
233
234     } else {
235       mbox->push(other_comm);
236     }
237   } else {
238     XBT_DEBUG("Receive already pushed");
239
240     other_comm->set_state(State::READY);
241   }
242   observer->set_comm(other_comm.get());
243
244   if (observer->is_detached()) {
245     other_comm->detach();
246     other_comm->clean_fun = observer->get_clean_fun();
247   } else {
248     other_comm->clean_fun = nullptr;
249     observer->get_issuer()->activities_.insert(other_comm);
250   }
251
252   /* Setup the communication synchro */
253   other_comm->src_actor_ = observer->get_issuer();
254   other_comm->src_data_  = observer->get_payload();
255   (*other_comm)
256       .set_src_buff(observer->get_src_buff(), observer->get_src_buff_size())
257       .set_size(observer->get_payload_size())
258       .set_rate(observer->get_rate());
259
260   other_comm->match_fun     = observer->get_match_fun();
261   other_comm->copy_data_fun = observer->get_copy_data_fun();
262
263   if (MC_is_active() || MC_record_replay_is_active())
264     other_comm->set_state(simgrid::kernel::activity::State::RUNNING);
265   else
266     other_comm->start();
267
268   return (observer->is_detached() ? nullptr : other_comm);
269 }
270
271 ActivityImplPtr CommImpl::irecv(actor::CommIrecvSimcall* observer)
272 {
273   CommImplPtr this_synchro(new CommImpl());
274   this_synchro->set_type(CommImplType::RECEIVE);
275
276   auto* mbox = observer->get_mailbox();
277   XBT_DEBUG("recv from mbox %p. this_synchro=%p", mbox, this_synchro.get());
278
279   CommImplPtr other_comm;
280   // communication already done, get it inside the list of completed comms
281   if (mbox->is_permanent() && mbox->has_some_done_comm()) {
282     XBT_DEBUG("We have a comm that has probably already been received, trying to match it, to skip the communication");
283     // find a match in the list of already received comms
284     other_comm = mbox->find_matching_comm(CommImplType::SEND, observer->get_match_fun(), observer->get_payload(),
285                                           this_synchro, /*done*/ true, /*remove_matching*/ true);
286     if (other_comm && other_comm->model_action_ && other_comm->get_remaining() < 1e-12) {
287       XBT_DEBUG("comm %p has been already sent, and is finished, destroy it", other_comm.get());
288       other_comm->set_state(State::DONE);
289       other_comm->set_mailbox(nullptr);
290     } else {
291       // if not found, assume the receiver came first, register it to the mailbox in the classical way
292       if (not other_comm) {
293         XBT_DEBUG("We have messages in the permanent receive list, but not the one we are looking for, pushing request "
294                   "into list");
295         other_comm = std::move(this_synchro);
296         mbox->push(other_comm);
297       }
298       observer->get_issuer()->activities_.insert(other_comm);
299     }
300   } else {
301     /* Prepare a comm describing us, so that it gets passed to the user-provided filter of other side */
302
303     /* Look for communication activity matching our needs. We also provide a description of
304      * ourself so that the other side also gets a chance of choosing if it wants to match with us.
305      *
306      * If it is not found then push our communication into the rendez-vous point */
307     other_comm = mbox->find_matching_comm(CommImplType::SEND, observer->get_match_fun(), observer->get_payload(),
308                                           this_synchro, /*done*/ false, /*remove_matching*/ true);
309
310     if (other_comm == nullptr) {
311       XBT_DEBUG("Receive pushed first (%zu comm enqueued so far)", mbox->size());
312       other_comm = std::move(this_synchro);
313       mbox->push(other_comm);
314     } else {
315       XBT_DEBUG("Match my %p with the existing %p", this_synchro.get(), other_comm.get());
316
317       other_comm->set_state(simgrid::kernel::activity::State::READY);
318     }
319     observer->get_issuer()->activities_.insert(other_comm);
320   }
321   observer->set_comm(other_comm.get());
322
323   /* Setup communication synchro */
324   other_comm->dst_actor_ = observer->get_issuer();
325   other_comm->dst_data_  = observer->get_payload();
326   other_comm->set_dst_buff(observer->get_dst_buff(), observer->get_dst_buff_size());
327
328   if (observer->get_rate() > -1.0 && (other_comm->get_rate() < 0.0 || observer->get_rate() < other_comm->get_rate()))
329     other_comm->set_rate(observer->get_rate());
330
331   other_comm->match_fun     = observer->get_match_fun();
332   other_comm->copy_data_fun = observer->get_copy_data_fun();
333
334   if (MC_is_active() || MC_record_replay_is_active()) {
335     other_comm->set_state(State::RUNNING);
336     return other_comm;
337   }
338   other_comm->start();
339
340   return other_comm;
341 }
342
343 bool CommImpl::test(actor::ActorImpl* issuer)
344 {
345   if ((MC_is_active() || MC_record_replay_is_active()) && src_actor_ && dst_actor_)
346     set_state(State::DONE);
347   return ActivityImpl::test(issuer);
348 }
349
350 void CommImpl::wait_for(actor::ActorImpl* issuer, double timeout)
351 {
352   XBT_DEBUG("CommImpl::wait_for(%g), %p, state %s", timeout, this, get_state_str());
353
354   /* Associate this simcall to the wait synchro */
355   register_simcall(&issuer->simcall_);
356   if (MC_is_active() || MC_record_replay_is_active()) {
357     // FIXME: what about timeouts?
358     set_state(State::DONE);
359     finish();
360     return;
361   }
362   ActivityImpl::wait_for(issuer, timeout);
363 }
364
365 void CommImpl::wait_any_for(actor::ActorImpl* issuer, const std::vector<CommImpl*>& comms, double timeout)
366 {
367   std::vector<ActivityImpl*> activities(comms.begin(), comms.end());
368   ActivityImpl::wait_any_for(issuer, activities, timeout);
369 }
370
371 void CommImpl::suspend()
372 {
373   /* FIXME: shall we suspend also the timeout synchro? */
374   if (model_action_)
375     model_action_->suspend();
376   /* if not created yet, the action will be suspended on creation, in CommImpl::start() */
377 }
378
379 void CommImpl::resume()
380 {
381   /*FIXME: check what happen with the timeouts */
382   if (model_action_)
383     model_action_->resume();
384   /* in the other case, the synchro were not really suspended yet, see CommImpl::suspend() and CommImpl::start() */
385 }
386
387 void CommImpl::cancel()
388 {
389   /* if the synchro is a waiting state means that it is still in a mbox so remove from it and delete it */
390   if (get_state() == State::WAITING) {
391     if (not detached_) {
392       mbox_->remove(this);
393       set_state(State::CANCELED);
394     }
395   } else if (not MC_is_active() /* when running the MC there are no model actions */
396              && not MC_record_replay_is_active() && (get_state() == State::READY || get_state() == State::RUNNING)) {
397     model_action_->cancel();
398   }
399 }
400
401 void CommImpl::set_exception(actor::ActorImpl* issuer)
402 {
403   switch (get_state()) {
404     case State::FAILED:
405       issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
406       break;
407     case State::SRC_TIMEOUT:
408       issuer->exception_ =
409           std::make_exception_ptr(TimeoutException(XBT_THROW_POINT, "Communication timeouted because of the sender"));
410       break;
411
412     case State::DST_TIMEOUT:
413       issuer->exception_ =
414           std::make_exception_ptr(TimeoutException(XBT_THROW_POINT, "Communication timeouted because of the receiver"));
415       break;
416
417     case State::SRC_HOST_FAILURE:
418       if (issuer == src_actor_)
419         issuer->set_wannadie();
420       else {
421         set_state(State::FAILED);
422         issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
423       }
424       break;
425
426     case State::DST_HOST_FAILURE:
427       if (issuer == dst_actor_)
428         issuer->set_wannadie();
429       else {
430         set_state(State::FAILED);
431         issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
432       }
433       break;
434
435     case State::LINK_FAILURE:
436       XBT_DEBUG("Link failure in synchro %p between '%s' and '%s': posting an exception to the issuer: %s (%p) "
437                 "detached:%d",
438                 this, src_actor_ ? src_actor_->get_host()->get_cname() : nullptr,
439                 dst_actor_ ? dst_actor_->get_host()->get_cname() : nullptr, issuer->get_cname(), issuer, detached_);
440       if (src_actor_ == issuer) {
441         XBT_DEBUG("I'm source");
442       } else if (dst_actor_ == issuer) {
443         XBT_DEBUG("I'm dest");
444       } else {
445         XBT_DEBUG("I'm neither source nor dest");
446       }
447       set_state(State::FAILED);
448       issuer->throw_exception(std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Link failure")));
449       break;
450
451     case State::CANCELED:
452       if (issuer == dst_actor_)
453         issuer->exception_ =
454             std::make_exception_ptr(CancelException(XBT_THROW_POINT, "Communication canceled by the sender"));
455       else
456         issuer->exception_ =
457             std::make_exception_ptr(CancelException(XBT_THROW_POINT, "Communication canceled by the receiver"));
458       break;
459
460     default:
461       xbt_assert(get_state() == State::DONE, "Internal error in CommImpl::finish(): unexpected synchro state %s",
462                  get_state_str());
463   }
464 }
465
466 void CommImpl::finish()
467 {
468   XBT_DEBUG("CommImpl::finish() comm %p, state %s, src_proc %p, dst_proc %p, detached: %d", this, get_state_str(),
469             src_actor_.get(), dst_actor_.get(), detached_);
470
471   if (get_iface()) {
472     const auto& piface = static_cast<const s4u::Comm&>(*get_iface());
473     set_iface(nullptr); // reset iface to protect against multiple trigger of the on_completion signals
474     s4u::Comm::on_completion(piface);
475     piface.on_this_completion(piface);
476   }
477
478   /* Update synchro state */
479   if (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FINISHED)
480     set_state(State::SRC_TIMEOUT);
481   else if (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FINISHED)
482     set_state(State::DST_TIMEOUT);
483   else if ((from_ && not from_->is_on()) ||
484            (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FAILED))
485     set_state(State::SRC_HOST_FAILURE);
486   else if ((to_ && not to_->is_on()) || (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FAILED))
487     set_state(State::DST_HOST_FAILURE);
488   else if (model_action_ && model_action_->get_state() == resource::Action::State::FAILED) {
489     set_state(State::LINK_FAILURE);
490   } else if (get_state() == State::RUNNING) {
491     xbt_assert(from_ && from_->is_on());
492     xbt_assert(to_ && to_->is_on());
493     set_state(State::DONE);
494   }
495   src_timeout_ = nullptr;
496   dst_timeout_ = nullptr;
497
498   /* destroy the model actions associated with the communication activity */
499   clean_action();
500
501   /* If the synchro is still in a rendez-vous point then remove from it */
502   if (mbox_)
503     mbox_->remove(this);
504
505   if (get_state() == State::DONE)
506     copy_data();
507
508   if (detached_)
509     EngineImpl::get_instance()->get_maestro()->activities_.erase(this);
510
511   while (not simcalls_.empty()) {
512     actor::Simcall* simcall = simcalls_.front();
513     simcalls_.pop_front();
514
515     /* If a waitany simcall is waiting for this synchro to finish, then remove it from the other synchros in the waitany
516      * list. Afterwards, get the position of the actual synchro in the waitany list and return it as the result of the
517      * simcall */
518
519     if (simcall->call_ == actor::Simcall::Type::NONE) // FIXME: maybe a better way to handle this case
520       continue;                                       // if actor handling comm is killed
521
522     handle_activity_waitany(simcall);
523
524     /* Check out for errors */
525
526     if (not simcall->issuer_->get_host()->is_on()) {
527       simcall->issuer_->set_wannadie();
528     } else {
529       // Do not answer to dying actors
530       if (not simcall->issuer_->wannadie()) {
531         set_exception(simcall->issuer_);
532         simcall->issuer_->simcall_answer();
533       }
534     }
535
536     simcall->issuer_->waiting_synchro_ = nullptr;
537     simcall->issuer_->activities_.erase(this);
538     if (detached_) {
539       if (simcall->issuer_ != dst_actor_ && dst_actor_ != nullptr)
540         dst_actor_->activities_.erase(this);
541       if (simcall->issuer_ != src_actor_ && src_actor_ != nullptr)
542         src_actor_->activities_.erase(this);
543     }
544   }
545 }
546
547 } // namespace simgrid::kernel::activity