Logo AND Algorithmique Numérique Distribuée

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