Logo AND Algorithmique Numérique Distribuée

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