Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fix last issues
[simgrid.git] / src / msg / msg_gos.cpp
1 /* Copyright (c) 2004-2019. 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 <cmath>
8
9 #include "simgrid/s4u/Comm.hpp"
10 #include "simgrid/s4u/Mailbox.hpp"
11 #include "src/instr/instr_private.hpp"
12 #include "src/kernel/activity/ExecImpl.hpp"
13 #include "src/msg/msg_private.hpp"
14 #include "src/simix/smx_private.hpp" /* MSG_task_listen looks inside the rdv directly. Not clean. */
15
16 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(msg_gos, msg, "Logging specific to MSG (gos)");
17
18 /**
19  * @brief Executes a task and waits for its termination.
20  *
21  * This function is used for describing the behavior of a process. It takes only one parameter.
22  * @param task a #msg_task_t to execute on the location on which the process is running.
23  * @return #MSG_OK if the task was successfully completed, #MSG_TASK_CANCELED or #MSG_HOST_FAILURE otherwise
24  */
25 msg_error_t MSG_task_execute(msg_task_t task)
26 {
27   return MSG_parallel_task_execute(task);
28 }
29
30 /**
31  * @brief Executes a parallel task and waits for its termination.
32  *
33  * @param task a #msg_task_t to execute on the location on which the process is running.
34  *
35  * @return #MSG_OK if the task was successfully completed, #MSG_TASK_CANCELED
36  * or #MSG_HOST_FAILURE otherwise
37  */
38 msg_error_t MSG_parallel_task_execute(msg_task_t task)
39 {
40   return MSG_parallel_task_execute_with_timeout(task, -1);
41 }
42
43 msg_error_t MSG_parallel_task_execute_with_timeout(msg_task_t task, double timeout)
44 {
45   e_smx_state_t comp_state;
46   msg_error_t status = MSG_OK;
47
48   xbt_assert((not task->compute) && not task->is_used, "This task is executed somewhere else. Go fix your code!");
49
50   XBT_DEBUG("Computing on %s", MSG_process_get_name(MSG_process_self()));
51
52   if (task->flops_amount <= 0.0 && not task->host_nb) {
53     return MSG_OK;
54   }
55
56   if (TRACE_actor_is_enabled())
57     simgrid::instr::Container::by_name(instr_pid(MSG_process_self()))->get_state("ACTOR_STATE")->push_event("execute");
58
59   try {
60     task->set_used();
61
62     if (task->host_nb > 0) {
63       task->compute = boost::static_pointer_cast<simgrid::kernel::activity::ExecImpl>(
64           simcall_execution_parallel_start(std::move(task->get_name()), task->host_nb, task->host_list,
65                                            task->flops_parallel_amount, task->bytes_parallel_amount, -1.0, timeout));
66       XBT_DEBUG("Parallel execution action created: %p", task->compute.get());
67       if (task->has_tracing_category())
68         simgrid::simix::simcall([task] { task->compute->set_category(std::move(task->get_tracing_category())); });
69     } else {
70       sg_host_t host   = MSG_process_get_host(MSG_process_self());
71       task->compute    = simgrid::simix::simcall([task, host] {
72         return simgrid::kernel::activity::ExecImplPtr(new simgrid::kernel::activity::ExecImpl(
73             std::move(task->get_name()), std::move(task->get_tracing_category()), host));
74       });
75       /* checking for infinite values */
76       xbt_assert(std::isfinite(task->flops_amount), "flops_amount is not finite!");
77       xbt_assert(std::isfinite(task->priority), "priority is not finite!");
78
79       task->compute->start(task->flops_amount, task->priority, task->bound);
80     }
81
82     comp_state = simcall_execution_wait(task->compute);
83
84     task->set_not_used();
85
86     XBT_DEBUG("Execution task '%s' finished in state %d", task->get_cname(), (int)comp_state);
87   } catch (simgrid::HostFailureException& e) {
88     status = MSG_HOST_FAILURE;
89   } catch (simgrid::TimeoutError& e) {
90     status = MSG_TIMEOUT;
91   } catch (simgrid::CancelException& e) {
92     status = MSG_TASK_CANCELED;
93   }
94
95   /* action ended, set comm and compute = nullptr, the actions is already destroyed in the main function */
96   task->flops_amount = 0.0;
97   task->comm         = nullptr;
98   task->compute      = nullptr;
99
100   if (TRACE_actor_is_enabled())
101     simgrid::instr::Container::by_name(instr_pid(MSG_process_self()))->get_state("ACTOR_STATE")->pop_event();
102
103   return status;
104 }
105
106 /**
107  * @brief Receives a task from a mailbox.
108  *
109  * This is a blocking function, the execution flow will be blocked until the task is received. See #MSG_task_irecv
110  * for receiving tasks asynchronously.
111  *
112  * @param task a memory location for storing a #msg_task_t.
113  * @param alias name of the mailbox to receive the task from
114  *
115  * @return Returns
116  * #MSG_OK if the task was successfully received,
117  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE otherwise.
118  */
119 msg_error_t MSG_task_receive(msg_task_t * task, const char *alias)
120 {
121   return MSG_task_receive_with_timeout(task, alias, -1);
122 }
123
124 /**
125  * @brief Receives a task from a mailbox at a given rate.
126  *
127  * @param task a memory location for storing a #msg_task_t.
128  * @param alias name of the mailbox to receive the task from
129  * @param rate limit the reception to rate bandwidth (byte/sec)
130  *
131  * The rate parameter can be used to receive a task with a limited
132  * bandwidth (smaller than the physical available value). Use
133  * MSG_task_receive() if you don't limit the rate (or pass -1 as a
134  * rate value do disable this feature).
135  *
136  * @return Returns
137  * #MSG_OK if the task was successfully received,
138  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE otherwise.
139  */
140 msg_error_t MSG_task_receive_bounded(msg_task_t * task, const char *alias, double rate)
141 {
142   return MSG_task_receive_with_timeout_bounded(task, alias, -1, rate);
143 }
144
145 /**
146  * @brief Receives a task from a mailbox with a given timeout.
147  *
148  * This is a blocking function with a timeout, the execution flow will be blocked until the task is received or the
149  * timeout is achieved. See #MSG_task_irecv for receiving tasks asynchronously.  You can provide a -1 timeout
150  * to obtain an infinite timeout.
151  *
152  * @param task a memory location for storing a #msg_task_t.
153  * @param alias name of the mailbox to receive the task from
154  * @param timeout is the maximum wait time for completion (if -1, this call is the same as #MSG_task_receive)
155  *
156  * @return Returns
157  * #MSG_OK if the task was successfully received,
158  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE, or #MSG_TIMEOUT otherwise.
159  */
160 msg_error_t MSG_task_receive_with_timeout(msg_task_t * task, const char *alias, double timeout)
161 {
162   return MSG_task_receive_ext(task, alias, timeout, nullptr);
163 }
164
165 /**
166  * @brief Receives a task from a mailbox with a given timeout and at a given rate.
167  *
168  * @param task a memory location for storing a #msg_task_t.
169  * @param alias name of the mailbox to receive the task from
170  * @param timeout is the maximum wait time for completion (if -1, this call is the same as #MSG_task_receive)
171  * @param rate limit the reception to rate bandwidth (byte/sec)
172  *
173  * The rate parameter can be used to send a task with a limited
174  * bandwidth (smaller than the physical available value). Use
175  * MSG_task_receive() if you don't limit the rate (or pass -1 as a
176  * rate value do disable this feature).
177  *
178  * @return Returns
179  * #MSG_OK if the task was successfully received,
180  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE, or #MSG_TIMEOUT otherwise.
181  */
182 msg_error_t MSG_task_receive_with_timeout_bounded(msg_task_t * task, const char *alias, double timeout,double rate)
183 {
184   return MSG_task_receive_ext_bounded(task, alias, timeout, nullptr, rate);
185 }
186
187 /**
188  * @brief Receives a task from a mailbox from a specific host with a given timeout.
189  *
190  * This is a blocking function with a timeout, the execution flow will be blocked until the task is received or the
191  * timeout is achieved. See #MSG_task_irecv for receiving tasks asynchronously. You can provide a -1 timeout
192  * to obtain an infinite timeout.
193  *
194  * @param task a memory location for storing a #msg_task_t.
195  * @param alias name of the mailbox to receive the task from
196  * @param timeout is the maximum wait time for completion (provide -1 for no timeout)
197  * @param host a #msg_host_t host from where the task was sent
198  *
199  * @return Returns
200  * #MSG_OK if the task was successfully received,
201  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE, or #MSG_TIMEOUT otherwise.
202  */
203 msg_error_t MSG_task_receive_ext(msg_task_t * task, const char *alias, double timeout, msg_host_t host)
204 {
205   XBT_DEBUG("MSG_task_receive_ext: Trying to receive a message on mailbox '%s'", alias);
206   return MSG_task_receive_ext_bounded(task, alias, timeout, host, -1.0);
207 }
208
209 /**
210  * @brief Receives a task from a mailbox from a specific host with a given timeout  and at a given rate.
211  *
212  * @param task a memory location for storing a #msg_task_t.
213  * @param alias name of the mailbox to receive the task from
214  * @param timeout is the maximum wait time for completion (provide -1 for no timeout)
215  * @param host a #msg_host_t host from where the task was sent
216  * @param rate limit the reception to rate bandwidth (byte/sec)
217  *
218  * The rate parameter can be used to receive a task with a limited
219  * bandwidth (smaller than the physical available value). Use
220  * MSG_task_receive_ext() if you don't limit the rate (or pass -1 as a
221  * rate value do disable this feature).
222  *
223  * @return Returns
224  * #MSG_OK if the task was successfully received,
225  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE, or #MSG_TIMEOUT otherwise.
226  */
227 msg_error_t MSG_task_receive_ext_bounded(msg_task_t * task, const char *alias, double timeout, msg_host_t host,
228                                          double rate)
229 {
230   XBT_DEBUG("MSG_task_receive_ext: Trying to receive a message on mailbox '%s'", alias);
231   msg_error_t ret = MSG_OK;
232   /* We no longer support getting a task from a specific host */
233   if (host)
234     THROW_UNIMPLEMENTED;
235
236   /* Sanity check */
237   xbt_assert(task, "Null pointer for the task storage");
238
239   if (*task)
240     XBT_WARN("Asked to write the received task in a non empty struct -- proceeding.");
241
242   /* Try to receive it by calling SIMIX network layer */
243   try {
244     void* payload;
245     simgrid::s4u::Mailbox::by_name(alias)
246         ->get_init()
247         ->set_dst_data(&payload, sizeof(msg_task_t*))
248         ->set_rate(rate)
249         ->wait_for(timeout);
250     *task = static_cast<msg_task_t>(payload);
251     XBT_DEBUG("Got task %s from %s", (*task)->get_cname(), alias);
252     (*task)->set_not_used();
253   } catch (simgrid::HostFailureException& e) {
254     ret = MSG_HOST_FAILURE;
255   } catch (simgrid::TimeoutError& e) {
256     ret = MSG_TIMEOUT;
257   } catch (simgrid::CancelException& e) {
258     ret = MSG_TASK_CANCELED;
259   } catch (xbt_ex& e) {
260     if (e.category == network_error)
261       ret = MSG_TRANSFER_FAILURE;
262     else
263       throw;
264   }
265
266   if (TRACE_actor_is_enabled() && ret != MSG_HOST_FAILURE && ret != MSG_TRANSFER_FAILURE && ret != MSG_TIMEOUT) {
267     container_t process_container = simgrid::instr::Container::by_name(instr_pid(MSG_process_self()));
268
269     std::string key = std::string("p") + std::to_string((*task)->get_id());
270     simgrid::instr::Container::get_root()->get_link("ACTOR_TASK_LINK")->end_event(process_container, "SR", key);
271   }
272   return ret;
273 }
274
275 /* Internal function used to factorize code between MSG_task_isend(), MSG_task_isend_bounded(), and MSG_task_dsend(). */
276 static inline msg_comm_t MSG_task_isend_internal(msg_task_t task, const char* alias, void_f_pvoid_t cleanup,
277                                                  bool detached)
278 {
279   msg_process_t myself = MSG_process_self();
280   simgrid::s4u::MailboxPtr mailbox = simgrid::s4u::Mailbox::by_name(alias);
281   TRACE_msg_task_put_start(task);
282
283   /* Prepare the task to send */
284   task->sender = myself;
285   task->set_used();
286   task->comm = nullptr;
287   msg_global->sent_msg++;
288
289   simgrid::s4u::CommPtr comm = mailbox->put_init(task, task->bytes_amount)->set_rate(task->rate);
290   task->comm                 = comm;
291   if (detached)
292     comm->detach(cleanup);
293   else
294     comm->start();
295
296   msg_comm_t msg_comm = nullptr;
297   if (not detached) {
298     msg_comm = new simgrid::msg::Comm(task, nullptr, comm);
299   }
300
301   if (TRACE_is_enabled() && task->has_tracing_category())
302     simgrid::simix::simcall([comm, task] { comm->get_impl()->set_category(std::move(task->get_tracing_category())); });
303
304   return msg_comm;
305 }
306
307 /**
308  * @brief Sends a task on a mailbox.
309  *
310  * This is a non blocking function: use MSG_comm_wait() or MSG_comm_test() to end the communication.
311  *
312  * @param task a #msg_task_t to send on another location.
313  * @param alias name of the mailbox to sent the task to
314  * @return the msg_comm_t communication created
315  */
316 msg_comm_t MSG_task_isend(msg_task_t task, const char *alias)
317 {
318   return MSG_task_isend_internal(task, alias, nullptr, false);
319 }
320
321 /**
322  * @brief Sends a task on a mailbox with a maximum rate
323  *
324  * This is a non blocking function: use MSG_comm_wait() or MSG_comm_test() to end the communication. The maxrate
325  * parameter allows the application to limit the bandwidth utilization of network links when sending the task.
326  *
327  * @param task a #msg_task_t to send on another location.
328  * @param alias name of the mailbox to sent the task to
329  * @param maxrate the maximum communication rate for sending this task (byte/sec).
330  * @return the msg_comm_t communication created
331  */
332 msg_comm_t MSG_task_isend_bounded(msg_task_t task, const char *alias, double maxrate)
333 {
334   task->rate = maxrate;
335   return MSG_task_isend_internal(task, alias, nullptr, false);
336 }
337
338 /**
339  * @brief Sends a task on a mailbox.
340  *
341  * This is a non blocking detached send function.
342  * Think of it as a best effort send. Keep in mind that the third parameter is only called if the communication fails.
343  * If the communication does work, it is responsibility of the receiver code to free anything related to the task, as
344  * usual. More details on this can be obtained on
345  * <a href="http://lists.gforge.inria.fr/pipermail/simgrid-user/2011-November/002649.html">this thread</a>
346  * in the SimGrid-user mailing list archive.
347  *
348  * @param task a #msg_task_t to send on another location.
349  * @param alias name of the mailbox to sent the task to
350  * @param cleanup a function to destroy the task if the communication fails, e.g. MSG_task_destroy
351  * (if nullptr, no function will be called)
352  */
353 void MSG_task_dsend(msg_task_t task, const char *alias, void_f_pvoid_t cleanup)
354 {
355   msg_comm_t XBT_ATTRIB_UNUSED comm = MSG_task_isend_internal(task, alias, cleanup, true);
356   xbt_assert(comm == nullptr);
357 }
358
359 /**
360  * @brief Sends a task on a mailbox with a maximal rate.
361  *
362  * This is a non blocking detached send function.
363  * Think of it as a best effort send. Keep in mind that the third parameter is only called if the communication fails.
364  * If the communication does work, it is responsibility of the receiver code to free anything related to the task, as
365  * usual. More details on this can be obtained on
366  * <a href="http://lists.gforge.inria.fr/pipermail/simgrid-user/2011-November/002649.html">this thread</a>
367  * in the SimGrid-user mailing list archive.
368  *
369  * The rate parameter can be used to send a task with a limited
370  * bandwidth (smaller than the physical available value). Use
371  * MSG_task_dsend() if you don't limit the rate (or pass -1 as a rate
372  * value do disable this feature).
373  *
374  * @param task a #msg_task_t to send on another location.
375  * @param alias name of the mailbox to sent the task to
376  * @param cleanup a function to destroy the task if the
377  * communication fails, e.g. MSG_task_destroy
378  * (if nullptr, no function will be called)
379  * @param maxrate the maximum communication rate for sending this task (byte/sec)
380  *
381  */
382 void MSG_task_dsend_bounded(msg_task_t task, const char *alias, void_f_pvoid_t cleanup, double maxrate)
383 {
384   task->rate = maxrate;
385   MSG_task_dsend(task, alias, cleanup);
386 }
387
388 /**
389  * @brief Starts listening for receiving a task from an asynchronous communication.
390  *
391  * This is a non blocking function: use MSG_comm_wait() or MSG_comm_test() to end the communication.
392  *
393  * @param task a memory location for storing a #msg_task_t. has to be valid until the end of the communication.
394  * @param name of the mailbox to receive the task on
395  * @return the msg_comm_t communication created
396  */
397 msg_comm_t MSG_task_irecv(msg_task_t *task, const char *name)
398 {
399   return MSG_task_irecv_bounded(task, name, -1.0);
400 }
401
402 /**
403  * @brief Starts listening for receiving a task from an asynchronous communication at a given rate.
404  *
405  * The rate parameter can be used to receive a task with a limited
406  * bandwidth (smaller than the physical available value). Use
407  * MSG_task_irecv() if you don't limit the rate (or pass -1 as a rate
408  * value do disable this feature).
409  *
410  * @param task a memory location for storing a #msg_task_t. has to be valid until the end of the communication.
411  * @param name of the mailbox to receive the task on
412  * @param rate limit the bandwidth to the given rate (byte/sec)
413  * @return the msg_comm_t communication created
414  */
415 msg_comm_t MSG_task_irecv_bounded(msg_task_t *task, const char *name, double rate)
416 {
417   simgrid::s4u::MailboxPtr mbox = simgrid::s4u::Mailbox::by_name(name);
418
419   /* FIXME: these functions are not traceable */
420   /* Sanity check */
421   xbt_assert(task, "Null pointer for the task storage");
422
423   if (*task)
424     XBT_CRITICAL("MSG_task_irecv() was asked to write in a non empty task struct.");
425
426   /* Try to receive it by calling SIMIX network layer */
427   msg_comm_t comm = new simgrid::msg::Comm(
428       nullptr, task, mbox->get_init()->set_dst_data((void**)task, sizeof(msg_task_t*))->set_rate(rate)->start());
429
430   return comm;
431 }
432
433 /**
434  * @brief Checks whether a communication is done, and if yes, finalizes it.
435  * @param comm the communication to test
436  * @return 'true' if the communication is finished
437  * (but it may have failed, use MSG_comm_get_status() to know its status)
438  * or 'false' if the communication is not finished yet
439  * If the status is 'false', don't forget to use MSG_process_sleep() after the test.
440  */
441 int MSG_comm_test(msg_comm_t comm)
442 {
443   bool finished = false;
444
445   try {
446     finished = comm->s_comm->test();
447     if (finished && comm->task_received != nullptr) {
448       /* I am the receiver */
449       (*comm->task_received)->set_not_used();
450     }
451   } catch (simgrid::TimeoutError& e) {
452     comm->status = MSG_TIMEOUT;
453     finished     = true;
454   } catch (simgrid::CancelException& e) {
455     comm->status = MSG_TASK_CANCELED;
456     finished     = true;
457   }
458   catch (xbt_ex& e) {
459     if (e.category == network_error) {
460       comm->status = MSG_TRANSFER_FAILURE;
461       finished     = true;
462     } else {
463       throw;
464     }
465   }
466
467   return finished;
468 }
469
470 /**
471  * @brief This function checks if a communication is finished.
472  * @param comms a vector of communications
473  * @return the position of the finished communication if any
474  * (but it may have failed, use MSG_comm_get_status() to know its status),
475  * or -1 if none is finished
476  */
477 int MSG_comm_testany(xbt_dynar_t comms)
478 {
479   int finished_index = -1;
480
481   /* Create the equivalent array with SIMIX objects: */
482   std::vector<simgrid::kernel::activity::CommImpl*> s_comms;
483   s_comms.reserve(xbt_dynar_length(comms));
484   msg_comm_t comm;
485   unsigned int cursor;
486   xbt_dynar_foreach(comms, cursor, comm) {
487     s_comms.push_back(static_cast<simgrid::kernel::activity::CommImpl*>(comm->s_comm->get_impl().get()));
488   }
489
490   msg_error_t status = MSG_OK;
491   try {
492     finished_index = simcall_comm_testany(s_comms.data(), s_comms.size());
493   } catch (simgrid::TimeoutError& e) {
494     finished_index = e.value;
495     status         = MSG_TIMEOUT;
496   } catch (simgrid::CancelException& e) {
497     finished_index = e.value;
498     status         = MSG_TASK_CANCELED;
499   }
500   catch (xbt_ex& e) {
501     if (e.category != network_error)
502       throw;
503     finished_index = e.value;
504     status         = MSG_TRANSFER_FAILURE;
505   }
506
507   if (finished_index != -1) {
508     comm = xbt_dynar_get_as(comms, finished_index, msg_comm_t);
509     /* the communication is finished */
510     comm->status = status;
511
512     if (status == MSG_OK && comm->task_received != nullptr) {
513       /* I am the receiver */
514       (*comm->task_received)->set_not_used();
515     }
516   }
517
518   return finished_index;
519 }
520
521 /** @brief Destroys the provided communication. */
522 void MSG_comm_destroy(msg_comm_t comm)
523 {
524   delete comm;
525 }
526
527 /** @brief Wait for the completion of a communication.
528  *
529  * It takes two parameters.
530  * @param comm the communication to wait.
531  * @param timeout Wait until the communication terminates or the timeout occurs.
532  *                You can provide a -1 timeout to obtain an infinite timeout.
533  * @return msg_error_t
534  */
535 msg_error_t MSG_comm_wait(msg_comm_t comm, double timeout)
536 {
537   try {
538     comm->s_comm->wait_for(timeout);
539
540     if (comm->task_received != nullptr) {
541       /* I am the receiver */
542       (*comm->task_received)->set_not_used();
543     }
544
545     /* FIXME: these functions are not traceable */
546   } catch (simgrid::TimeoutError& e) {
547     comm->status = MSG_TIMEOUT;
548   } catch (simgrid::CancelException& e) {
549     comm->status = MSG_TASK_CANCELED;
550   }
551   catch (xbt_ex& e) {
552     if (e.category == network_error)
553       comm->status = MSG_TRANSFER_FAILURE;
554     else
555       throw;
556   }
557
558   return comm->status;
559 }
560
561 /** @brief This function is called by a sender and permit to wait for each communication
562  *
563  * @param comm a vector of communication
564  * @param nb_elem is the size of the comm vector
565  * @param timeout for each call of MSG_comm_wait
566  */
567 void MSG_comm_waitall(msg_comm_t * comm, int nb_elem, double timeout)
568 {
569   for (int i = 0; i < nb_elem; i++)
570     MSG_comm_wait(comm[i], timeout);
571 }
572
573 /** @brief This function waits for the first communication finished in a list.
574  * @param comms a vector of communications
575  * @return the position of the first finished communication
576  * (but it may have failed, use MSG_comm_get_status() to know its status)
577  */
578 int MSG_comm_waitany(xbt_dynar_t comms)
579 {
580   int finished_index = -1;
581
582   /* Create the equivalent array with SIMIX objects: */
583   std::vector<simgrid::kernel::activity::CommImpl*> s_comms;
584   s_comms.reserve(xbt_dynar_length(comms));
585   msg_comm_t comm;
586   unsigned int cursor;
587   xbt_dynar_foreach(comms, cursor, comm) {
588     s_comms.push_back(static_cast<simgrid::kernel::activity::CommImpl*>(comm->s_comm->get_impl().get()));
589   }
590
591   msg_error_t status = MSG_OK;
592   try {
593     finished_index = simcall_comm_waitany(s_comms.data(), s_comms.size(), -1);
594   } catch (simgrid::TimeoutError& e) {
595     finished_index = e.value;
596     status         = MSG_TIMEOUT;
597   } catch (simgrid::CancelException& e) {
598     finished_index = e.value;
599     status         = MSG_TASK_CANCELED;
600   }
601   catch(xbt_ex& e) {
602     if (e.category == network_error) {
603       finished_index = e.value;
604       status         = MSG_TRANSFER_FAILURE;
605     } else {
606       throw;
607     }
608   }
609
610   xbt_assert(finished_index != -1, "WaitAny returned -1");
611
612   comm = xbt_dynar_get_as(comms, finished_index, msg_comm_t);
613   /* the communication is finished */
614   comm->status = status;
615
616   if (comm->task_received != nullptr) {
617     /* I am the receiver */
618     (*comm->task_received)->set_not_used();
619   }
620
621   return finished_index;
622 }
623
624 /**
625  * @brief Returns the error (if any) that occurred during a finished communication.
626  * @param comm a finished communication
627  * @return the status of the communication, or #MSG_OK if no error occurred
628  * during the communication
629  */
630 msg_error_t MSG_comm_get_status(msg_comm_t comm) {
631
632   return comm->status;
633 }
634
635 /** @brief Get a task (#msg_task_t) from a communication
636  *
637  * @param comm the communication where to get the task
638  * @return the task from the communication
639  */
640 msg_task_t MSG_comm_get_task(msg_comm_t comm)
641 {
642   xbt_assert(comm, "Invalid parameter");
643
644   return comm->task_received ? *comm->task_received : comm->task_sent;
645 }
646
647 /**
648  * @brief This function is called by SIMIX in kernel mode to copy the data of a comm.
649  * @param comm the comm
650  * @param buff the data copied
651  * @param buff_size size of the buffer
652  */
653 void MSG_comm_copy_data_from_SIMIX(simgrid::kernel::activity::CommImpl* comm, void* buff, size_t buff_size)
654 {
655   SIMIX_comm_copy_pointer_callback(comm, buff, buff_size);
656
657   // notify the user callback if any
658   if (msg_global->task_copy_callback) {
659     msg_task_t task = static_cast<msg_task_t>(buff);
660     msg_global->task_copy_callback(task, comm->src_actor_->ciface(), comm->dst_actor_->ciface());
661   }
662 }
663
664 /**
665  * @brief Sends a task to a mailbox
666  *
667  * This is a blocking function, the execution flow will be blocked until the task is sent (and received on the other
668  * side if #MSG_task_receive is used).
669  * See #MSG_task_isend for sending tasks asynchronously.
670  *
671  * @param task the task to be sent
672  * @param alias the mailbox name to where the task is sent
673  *
674  * @return Returns #MSG_OK if the task was successfully sent,
675  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE otherwise.
676  */
677 msg_error_t MSG_task_send(msg_task_t task, const char *alias)
678 {
679   XBT_DEBUG("MSG_task_send: Trying to send a message on mailbox '%s'", alias);
680   return MSG_task_send_with_timeout(task, alias, -1);
681 }
682
683 /**
684  * @brief Sends a task to a mailbox with a maximum rate
685  *
686  * This is a blocking function, the execution flow will be blocked until the task is sent. The maxrate parameter allows
687  * the application to limit the bandwidth utilization of network links when sending the task.
688  *
689  * The maxrate parameter can be used to send a task with a limited
690  * bandwidth (smaller than the physical available value). Use
691  * MSG_task_send() if you don't limit the rate (or pass -1 as a rate
692  * value do disable this feature).
693  *
694  * @param task the task to be sent
695  * @param alias the mailbox name to where the task is sent
696  * @param maxrate the maximum communication rate for sending this task (byte/sec)
697  *
698  * @return Returns #MSG_OK if the task was successfully sent,
699  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE otherwise.
700  */
701 msg_error_t MSG_task_send_bounded(msg_task_t task, const char *alias, double maxrate)
702 {
703   task->rate = maxrate;
704   return MSG_task_send(task, alias);
705 }
706
707 /**
708  * @brief Sends a task to a mailbox with a timeout
709  *
710  * This is a blocking function, the execution flow will be blocked until the task is sent or the timeout is achieved.
711  *
712  * @param task the task to be sent
713  * @param alias the mailbox name to where the task is sent
714  * @param timeout is the maximum wait time for completion (if -1, this call is the same as #MSG_task_send)
715  *
716  * @return Returns #MSG_OK if the task was successfully sent,
717  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE, or #MSG_TIMEOUT otherwise.
718  */
719 msg_error_t MSG_task_send_with_timeout(msg_task_t task, const char *alias, double timeout)
720 {
721   msg_error_t ret = MSG_OK;
722
723   TRACE_msg_task_put_start(task);
724
725   /* Prepare the task to send */
726   task->sender = MSG_process_self();
727   task->set_used();
728
729   msg_global->sent_msg++;
730
731   /* Try to send it */
732   try {
733     simgrid::s4u::CommPtr comm =
734         simgrid::s4u::Mailbox::by_name(alias)->put_init(task, task->bytes_amount)->set_rate(task->rate);
735     task->comm = comm;
736     comm->start();
737     if (TRACE_is_enabled() && task->has_tracing_category())
738       simgrid::simix::simcall(
739           [comm, task] { comm->get_impl()->set_category(std::move(task->get_tracing_category())); });
740     comm->wait_for(timeout);
741   } catch (simgrid::TimeoutError& e) {
742     ret = MSG_TIMEOUT;
743   } catch (simgrid::CancelException& e) {
744     ret = MSG_HOST_FAILURE;
745   } catch (xbt_ex& e) {
746     if (e.category == network_error)
747       ret = MSG_TRANSFER_FAILURE;
748     else
749       throw;
750
751     /* If the send failed, it is not used anymore */
752     task->set_not_used();
753   }
754
755   return ret;
756 }
757
758 /**
759  * @brief Sends a task to a mailbox with a timeout and with a maximum rate
760  *
761  * This is a blocking function, the execution flow will be blocked until the task is sent or the timeout is achieved.
762  *
763  * The maxrate parameter can be used to send a task with a limited
764  * bandwidth (smaller than the physical available value). Use
765  * MSG_task_send_with_timeout() if you don't limit the rate (or pass -1 as a rate
766  * value do disable this feature).
767  *
768  * @param task the task to be sent
769  * @param alias the mailbox name to where the task is sent
770  * @param timeout is the maximum wait time for completion (if -1, this call is the same as #MSG_task_send)
771  * @param maxrate the maximum communication rate for sending this task (byte/sec)
772  *
773  * @return Returns #MSG_OK if the task was successfully sent,
774  * #MSG_HOST_FAILURE, or #MSG_TRANSFER_FAILURE, or #MSG_TIMEOUT otherwise.
775  */
776 msg_error_t MSG_task_send_with_timeout_bounded(msg_task_t task, const char *alias, double timeout, double maxrate)
777 {
778   task->rate = maxrate;
779   return MSG_task_send_with_timeout(task, alias, timeout);
780 }
781
782 /**
783  * @brief Look if there is a communication on a mailbox and return the PID of the sender process.
784  *
785  * @param alias the name of the mailbox to be considered
786  *
787  * @return Returns the PID of sender process,
788  * -1 if there is no communication in the mailbox.
789  */
790 int MSG_task_listen_from(const char *alias)
791 {
792   simgrid::kernel::activity::CommImplPtr comm = simgrid::s4u::Mailbox::by_name(alias)->front();
793
794   return comm ? MSG_process_get_PID(static_cast<msg_task_t>(comm->src_buff_)->sender) : -1;
795 }
796
797 /**
798  * @brief Sets the tracing category of a task.
799  *
800  * This function should be called after the creation of a MSG task, to define the category of that task. The
801  * first parameter task must contain a task that was  created with the function #MSG_task_create. The second
802  * parameter category must contain a category that was previously declared with the function #TRACE_category
803  * (or with #TRACE_category_with_color).
804  *
805  * See @ref outcomes_vizu for details on how to trace the (categorized) resource utilization.
806  *
807  * @param task the task that is going to be categorized
808  * @param category the name of the category to be associated to the task
809  *
810  * @see MSG_task_get_category, TRACE_category, TRACE_category_with_color
811  */
812 void MSG_task_set_category (msg_task_t task, const char *category)
813 {
814   xbt_assert(not task->has_tracing_category(), "Task %p(%s) already has a category (%s).", task, task->get_cname(),
815              task->get_tracing_category().c_str());
816
817   // if user provides a nullptr category, task is no longer traced
818   if (category == nullptr) {
819     task->set_tracing_category("");
820     XBT_DEBUG("MSG task %p(%s), category removed", task, task->get_cname());
821   } else {
822     // set task category
823     task->set_tracing_category(category);
824     XBT_DEBUG("MSG task %p(%s), category %s", task, task->get_cname(), task->get_tracing_category().c_str());
825   }
826 }
827
828 /**
829  * @brief Gets the current tracing category of a task.
830  *
831  * @param task the task to be considered
832  *
833  * @see MSG_task_set_category
834  *
835  * @return Returns the name of the tracing category of the given task, nullptr otherwise
836  */
837 const char *MSG_task_get_category (msg_task_t task)
838 {
839   return task->get_tracing_category().c_str();
840 }