Logo AND Algorithmique Numérique Distribuée

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