Logo AND Algorithmique Numérique Distribuée

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