Logo AND Algorithmique Numérique Distribuée

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