Logo AND Algorithmique Numérique Distribuée

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