Logo AND Algorithmique Numérique Distribuée

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