Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Minimal change to support host on-off and permanent mailboxes
[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     xbt_assert(from_->is_on());
124     to_   = to_ != nullptr ? to_ : dst_actor_->get_host();
125     xbt_assert(to_->is_on());
126
127     /* Getting the network_model from the origin host
128      * Valid while we have a single network model, otherwise we would need to change this function to first get the
129      * routes and later create the respective surf actions */
130     auto net_model = from_->get_netpoint()->get_englobing_zone()->get_network_model();
131
132     surf_action_ = net_model->communicate(from_, to_, size_, rate_);
133     surf_action_->set_activity(this);
134     surf_action_->set_category(get_tracing_category());
135     set_start_time(surf_action_->get_start_time());
136     set_state(State::RUNNING);
137     on_start(*this);
138
139     XBT_DEBUG("Starting communication %p from '%s' to '%s' (surf_action: %p; state: %s)", this, from_->get_cname(),
140               to_->get_cname(), surf_action_, get_state_str());
141
142     /* If a link is failed, detect it immediately */
143     if (surf_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       post();
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 resume */
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       surf_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)", __FUNCTION__,
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_ || 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(CommImpl::Type::SEND));
218
219   /* Look for communication synchro matching our needs. We also provide a description of
220    * ourself so that the other side also gets a chance of choosing if it wants to match with us.
221    *
222    * If it is not found then push our communication into the rendez-vous point */
223   CommImplPtr other_comm =
224       mbox->find_matching_comm(CommImpl::Type::RECEIVE, observer->get_match_fun(), observer->get_payload(), this_comm,
225                                /*done*/ false, /*remove_matching*/ true);
226
227   if (not other_comm) {
228     other_comm = std::move(this_comm);
229
230     if (mbox->is_permanent()) {
231       // this mailbox is for small messages, which have to be sent right now
232       other_comm->set_state(State::READY);
233       other_comm->dst_actor_ = mbox->get_permanent_receiver().get();
234       mbox->push_done(other_comm);
235       XBT_DEBUG("pushing a message into the permanent receive list %p, comm %p", mbox, other_comm.get());
236
237     } else {
238       mbox->push(other_comm);
239     }
240   } else {
241     XBT_DEBUG("Receive already pushed");
242
243     other_comm->set_state(State::READY);
244   }
245   observer->set_comm(other_comm.get());
246
247   if (observer->is_detached()) {
248     other_comm->detach();
249     other_comm->clean_fun = observer->get_clean_fun();
250   } else {
251     other_comm->clean_fun = nullptr;
252     observer->get_issuer()->activities_.emplace_back(other_comm);
253   }
254
255   /* Setup the communication synchro */
256   other_comm->src_actor_ = observer->get_issuer();
257   other_comm->src_data_  = observer->get_payload();
258   (*other_comm)
259       .set_src_buff(observer->get_src_buff(), observer->get_src_buff_size())
260       .set_size(observer->get_payload_size())
261       .set_rate(observer->get_rate());
262
263   other_comm->match_fun     = observer->get_match_fun();
264   other_comm->copy_data_fun = observer->get_copy_data_fun();
265
266   if (MC_is_active() || MC_record_replay_is_active())
267     other_comm->set_state(simgrid::kernel::activity::State::RUNNING);
268   else
269     other_comm->start();
270
271   return (observer->is_detached() ? nullptr : other_comm);
272 }
273
274 ActivityImplPtr CommImpl::irecv(actor::CommIrecvSimcall* observer)
275 {
276   CommImplPtr this_synchro(new CommImpl(CommImpl::Type::RECEIVE));
277   auto* mbox = observer->get_mailbox();
278   XBT_DEBUG("recv from mbox %p. this_synchro=%p", mbox, this_synchro.get());
279
280   CommImplPtr other_comm;
281   // communication already done, get it inside the list of completed comms
282   if (mbox->is_permanent() && mbox->has_some_done_comm()) {
283     XBT_DEBUG("We have a comm that has probably already been received, trying to match it, to skip the communication");
284     // find a match in the list of already received comms
285     other_comm = mbox->find_matching_comm(CommImpl::Type::SEND, observer->get_match_fun(), observer->get_payload(),
286                                           this_synchro, /*done*/ true, /*remove_matching*/ true);
287     // if not found, assume the receiver came first, register it to the mailbox in the classical way
288     if (not other_comm) {
289       XBT_DEBUG("We have messages in the permanent receive list, but not the one we are looking for, pushing request "
290                 "into list");
291       other_comm = std::move(this_synchro);
292       mbox->push(other_comm);
293     } else {
294       if (other_comm->surf_action_ && other_comm->get_remaining() < 1e-12) {
295         XBT_DEBUG("comm %p has been already sent, and is finished, destroy it", other_comm.get());
296         other_comm->set_state(State::DONE);
297         other_comm->set_mailbox(nullptr);
298       }
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(CommImpl::Type::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_.emplace_back(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 (surf_action_)
375     surf_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 (surf_action_)
383     surf_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 surf actions */
396              && not MC_record_replay_is_active() && (get_state() == State::READY || get_state() == State::RUNNING)) {
397     surf_action_->cancel();
398   }
399 }
400
401 /** @brief This is part of the cleanup process, probably an internal command */
402 void CommImpl::cleanup_surf()
403 {
404   clean_action();
405
406   if (src_timeout_) {
407     src_timeout_->unref();
408     src_timeout_ = nullptr;
409   }
410
411   if (dst_timeout_) {
412     dst_timeout_->unref();
413     dst_timeout_ = nullptr;
414   }
415 }
416
417 void CommImpl::post()
418 {
419   on_completion(*this);
420
421   /* Update synchro state */
422   if (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FINISHED)
423     set_state(State::SRC_TIMEOUT);
424   else if (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FINISHED)
425     set_state(State::DST_TIMEOUT);
426   else if ((from_ && !from_->is_on()) || (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FAILED))
427     set_state(State::SRC_HOST_FAILURE);
428   else if ((to_ && !to_->is_on()) || (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FAILED))
429     set_state(State::DST_HOST_FAILURE);
430   else if (surf_action_ && surf_action_->get_state() == resource::Action::State::FAILED) {
431     set_state(State::LINK_FAILURE);
432   } else if(get_state() == State::RUNNING ) {
433     xbt_assert(from_ && from_->is_on());
434     xbt_assert(to_ && to_->is_on());
435     set_state(State::DONE);
436   }
437
438   XBT_DEBUG("CommImpl::post(): comm %p, state %s, src_proc %p, dst_proc %p, detached: %d", this, get_state_str(),
439             src_actor_.get(), dst_actor_.get(), detached_);
440
441   /* destroy the surf actions associated with the Simix communication */
442   cleanup_surf();
443
444   /* Answer all simcalls associated with the synchro */
445   finish();
446 }
447 void CommImpl::set_exception(actor::ActorImpl* issuer)
448 {
449   switch (get_state()) {
450     case State::FAILED:
451       issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
452       break;
453     case State::SRC_TIMEOUT:
454       issuer->exception_ =
455           std::make_exception_ptr(TimeoutException(XBT_THROW_POINT, "Communication timeouted because of the sender"));
456       break;
457
458     case State::DST_TIMEOUT:
459       issuer->exception_ =
460           std::make_exception_ptr(TimeoutException(XBT_THROW_POINT, "Communication timeouted because of the receiver"));
461       break;
462
463     case State::SRC_HOST_FAILURE:
464       if (issuer == src_actor_)
465         issuer->context_->set_wannadie();
466       else {
467         set_state(State::FAILED);
468         issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
469       }
470       break;
471
472     case State::DST_HOST_FAILURE:
473       if (issuer == dst_actor_)
474         issuer->context_->set_wannadie();
475       else {
476         set_state(State::FAILED);
477         issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
478       }
479       break;
480
481     case State::LINK_FAILURE:
482       XBT_DEBUG("Link failure in synchro %p between '%s' and '%s': posting an exception to the issuer: %s (%p) "
483                 "detached:%d",
484                 this, src_actor_ ? src_actor_->get_host()->get_cname() : nullptr,
485                 dst_actor_ ? dst_actor_->get_host()->get_cname() : nullptr, issuer->get_cname(), issuer, detached_);
486       if (src_actor_ == issuer) {
487         XBT_DEBUG("I'm source");
488       } else if (dst_actor_ == issuer) {
489         XBT_DEBUG("I'm dest");
490       } else {
491         XBT_DEBUG("I'm neither source nor dest");
492       }
493       set_state(State::FAILED);
494       issuer->throw_exception(std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Link failure")));
495       break;
496
497     case State::CANCELED:
498       if (issuer == dst_actor_)
499         issuer->exception_ =
500             std::make_exception_ptr(CancelException(XBT_THROW_POINT, "Communication canceled by the sender"));
501       else
502         issuer->exception_ =
503             std::make_exception_ptr(CancelException(XBT_THROW_POINT, "Communication canceled by the receiver"));
504       break;
505
506     default:
507       xbt_assert(get_state() == State::DONE, "Internal error in CommImpl::finish(): unexpected synchro state %s",
508                  get_state_str());
509   }
510 }
511
512 void CommImpl::finish()
513 {
514   XBT_DEBUG("CommImpl::finish() in state %s", get_state_str());
515   /* If the synchro is still in a rendez-vous point then remove from it */
516   if (mbox_)
517     mbox_->remove(this);
518
519   if (get_state() == State::DONE)
520     copy_data();
521
522   while (not simcalls_.empty()) {
523     smx_simcall_t simcall = simcalls_.front();
524     simcalls_.pop_front();
525
526     /* If a waitany simcall is waiting for this synchro to finish, then remove it from the other synchros in the waitany
527      * list. Afterwards, get the position of the actual synchro in the waitany list and return it as the result of the
528      * simcall */
529
530     if (simcall->call_ == simix::Simcall::NONE) // FIXME: maybe a better way to handle this case
531       continue;                                 // if actor handling comm is killed
532
533     handle_activity_waitany(simcall);
534
535     /* Check out for errors */
536
537     if (not simcall->issuer_->get_host()->is_on()) {
538       simcall->issuer_->context_->set_wannadie();
539     } else {
540       // Do not answer to dying actors
541       if (not simcall->issuer_->context_->wannadie()) {
542         set_exception(simcall->issuer_);
543         simcall->issuer_->simcall_answer();
544       }
545     }
546
547     simcall->issuer_->waiting_synchro_ = nullptr;
548     simcall->issuer_->activities_.remove(this);
549     if (detached_) {
550       if (simcall->issuer_ != dst_actor_ && dst_actor_ != nullptr)
551         dst_actor_->activities_.remove(this);
552       if (simcall->issuer_ != src_actor_ && src_actor_ != nullptr)
553         src_actor_->activities_.remove(this);
554     }
555   }
556 }
557
558 } // namespace activity
559 } // namespace kernel
560 } // namespace simgrid