Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
c6f3a65ed2000eaee615dbba8eaa524d3300a179
[simgrid.git] / src / simdag / sd_task.cpp
1 /* Copyright (c) 2006-2016. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "src/surf/HostImpl.hpp"
8 #include "src/surf/surf_interface.hpp"
9 #include "src/simdag/simdag_private.h"
10
11 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(sd_task, sd, "Logging specific to SimDag (task)");
12
13 /* Destroys the data memorized by SD_task_schedule. Task state must be SD_SCHEDULED or SD_RUNNABLE. */
14 static void __SD_task_destroy_scheduling_data(SD_task_t task)
15 {
16   if (task->state != SD_SCHEDULED && task->state != SD_RUNNABLE)
17     THROWF(arg_error, 0, "Task '%s' must be SD_SCHEDULED or SD_RUNNABLE", SD_task_get_name(task));
18
19   xbt_free(task->flops_amount);
20   xbt_free(task->bytes_amount);
21   task->bytes_amount = nullptr;
22   task->flops_amount = nullptr;
23 }
24
25 void* SD_task_new_f()
26 {
27   SD_task_t task = xbt_new0(s_SD_task_t, 1);
28
29   task->inputs = new std::set<SD_task_t>();
30   task->outputs = new std::set<SD_task_t>();
31   task->predecessors = new std::set<SD_task_t>();
32   task->successors = new std::set<SD_task_t>();
33   return task;
34 }
35
36 void SD_task_recycle_f(void *t)
37 {
38   SD_task_t task = static_cast<SD_task_t>(t);
39
40   /* Reset the content */
41   task->kind = SD_TASK_NOT_TYPED;
42   task->state= SD_NOT_SCHEDULED;
43   sd_global->initial_tasks->insert(task);
44
45   task->marked = 0;
46
47   task->start_time = -1.0;
48   task->finish_time = -1.0;
49   task->surf_action = nullptr;
50   task->watch_points = 0;
51
52   /* dependencies */
53   task->inputs->clear();
54   task->outputs->clear();
55   task->predecessors->clear();
56   task->successors->clear();
57
58   /* scheduling parameters */
59   task->flops_amount = nullptr;
60   task->bytes_amount = nullptr;
61   task->rate = -1;
62 }
63
64 void SD_task_free_f(void *t)
65 {
66   SD_task_t task = static_cast<SD_task_t>(t);
67
68   delete task->inputs;
69   delete task->outputs;
70   delete task->predecessors;
71   delete task->successors;
72   xbt_free(task);
73 }
74
75 /**
76  * \brief Creates a new task.
77  *
78  * \param name the name of the task (can be \c nullptr)
79  * \param data the user data you want to associate with the task (can be \c nullptr)
80  * \param amount amount of the task
81  * \return the new task
82  * \see SD_task_destroy()
83  */
84 SD_task_t SD_task_create(const char *name, void *data, double amount)
85 {
86   SD_task_t task = static_cast<SD_task_t>(xbt_mallocator_get(sd_global->task_mallocator));
87
88   task->data = data;
89   task->name = xbt_strdup(name);
90   task->amount = amount;
91   task->remains = amount;
92   task->allocation = new std::vector<sg_host_t>();
93   return task;
94 }
95
96 static inline SD_task_t SD_task_create_sized(const char *name, void *data, double amount, int count)
97 {
98   SD_task_t task = SD_task_create(name, data, amount);
99   task->bytes_amount = xbt_new0(double, count * count);
100   task->flops_amount = xbt_new0(double, count);
101   return task;
102 }
103
104 /** @brief create a end-to-end communication task that can then be auto-scheduled
105  *
106  * Auto-scheduling mean that the task can be used with SD_task_schedulev(). This allows to specify the task costs at
107  * creation, and decouple them from the scheduling process where you just specify which resource should deliver the
108  * mandatory power.
109  *
110  * A end-to-end communication must be scheduled on 2 hosts, and the amount specified at creation is sent from hosts[0]
111  * to hosts[1].
112  */
113 SD_task_t SD_task_create_comm_e2e(const char *name, void *data, double amount)
114 {
115   SD_task_t res = SD_task_create_sized(name, data, amount, 2);
116   res->bytes_amount[2] = amount;
117   res->kind = SD_TASK_COMM_E2E;
118
119   return res;
120 }
121
122 /** @brief create a sequential computation task that can then be auto-scheduled
123  *
124  * Auto-scheduling mean that the task can be used with SD_task_schedulev(). This allows to specify the task costs at
125  * creation, and decouple them from the scheduling process where you just specify which resource should deliver the
126  * mandatory power.
127  *
128  * A sequential computation must be scheduled on 1 host, and the amount specified at creation to be run on hosts[0].
129  *
130  * \param name the name of the task (can be \c nullptr)
131  * \param data the user data you want to associate with the task (can be \c nullptr)
132  * \param flops_amount amount of compute work to be done by the task
133  * \return the new SD_TASK_COMP_SEQ typed task
134  */
135 SD_task_t SD_task_create_comp_seq(const char *name, void *data, double flops_amount)
136 {
137   SD_task_t res = SD_task_create_sized(name, data, flops_amount, 1);
138   res->flops_amount[0] = flops_amount;
139   res->kind = SD_TASK_COMP_SEQ;
140
141   return res;
142 }
143
144 /** @brief create a parallel computation task that can then be auto-scheduled
145  *
146  * Auto-scheduling mean that the task can be used with SD_task_schedulev(). This allows to specify the task costs at
147  * creation, and decouple them from the scheduling process where you just specify which resource should deliver the
148  * mandatory power.
149  *
150  * A parallel computation can be scheduled on any number of host.
151  * The underlying speedup model is Amdahl's law.
152  * To be auto-scheduled, \see SD_task_distribute_comp_amdahl has to be called first.
153  * \param name the name of the task (can be \c nullptr)
154  * \param data the user data you want to associate with the task (can be \c nullptr)
155  * \param flops_amount amount of compute work to be done by the task
156  * \param alpha purely serial fraction of the work to be done (in [0.;1.[)
157  * \return the new task
158  */
159 SD_task_t SD_task_create_comp_par_amdahl(const char *name, void *data, double flops_amount, double alpha)
160 {
161   xbt_assert(alpha < 1. && alpha >= 0., "Invalid parameter: alpha must be in [0.;1.[");
162
163   SD_task_t res = SD_task_create(name, data, flops_amount);
164   res->alpha = alpha;
165   res->kind = SD_TASK_COMP_PAR_AMDAHL;
166
167   return res;
168 }
169
170 /** @brief create a complex data redistribution task that can then be  auto-scheduled
171  *
172  * Auto-scheduling mean that the task can be used with SD_task_schedulev(). 
173  * This allows to specify the task costs at creation, and decouple them from the scheduling process where you just
174  * specify which resource should communicate.
175  *
176  * A data redistribution can be scheduled on any number of host.
177  * The assumed distribution is a 1D block distribution. Each host owns the same share of the \see amount.
178  * To be auto-scheduled, \see SD_task_distribute_comm_mxn_1d_block has to be  called first.
179  * \param name the name of the task (can be \c nullptr)
180  * \param data the user data you want to associate with the task (can be \c nullptr)
181  * \param amount amount of data to redistribute by the task
182  * \return the new task
183  */
184 SD_task_t SD_task_create_comm_par_mxn_1d_block(const char *name, void *data, double amount)
185 {
186   SD_task_t res = SD_task_create(name, data, amount);
187   res->kind = SD_TASK_COMM_PAR_MXN_1D_BLOCK;
188
189   return res;
190 }
191
192 /**
193  * \brief Destroys a task.
194  *
195  * The user data (if any) should have been destroyed first.
196  *
197  * \param task the task you want to destroy
198  * \see SD_task_create()
199  */
200 void SD_task_destroy(SD_task_t task)
201 {
202   XBT_DEBUG("Destroying task %s...", SD_task_get_name(task));
203
204   /* First Remove all dependencies associated with the task. */
205   while (!task->predecessors->empty())
206     SD_task_dependency_remove(*(task->predecessors->begin()), task);
207   while (!task->inputs->empty())
208     SD_task_dependency_remove(*(task->inputs->begin()), task);
209   while (!task->successors->empty())
210     SD_task_dependency_remove(task, *(task->successors->begin()));
211   while (!task->outputs->empty())
212    SD_task_dependency_remove(task, *(task->outputs->begin()));
213
214   if (task->state == SD_SCHEDULED || task->state == SD_RUNNABLE)
215     __SD_task_destroy_scheduling_data(task);
216
217   int idx = xbt_dynar_search_or_negative(sd_global->return_set, &task);
218   if (idx >=0) {
219     xbt_dynar_remove_at(sd_global->return_set, idx, nullptr);
220   }
221
222   xbt_free(task->name);
223
224   if (task->surf_action != nullptr)
225     task->surf_action->unref();
226
227   delete task->allocation;
228   xbt_free(task->bytes_amount);
229   xbt_free(task->flops_amount);
230
231   xbt_mallocator_release(sd_global->task_mallocator,task);
232
233   XBT_DEBUG("Task destroyed.");
234 }
235
236 /**
237  * \brief Returns the user data of a task
238  *
239  * \param task a task
240  * \return the user data associated with this task (can be \c nullptr)
241  * \see SD_task_set_data()
242  */
243 void *SD_task_get_data(SD_task_t task)
244 {
245   return task->data;
246 }
247
248 /**
249  * \brief Sets the user data of a task
250  *
251  * The new data can be \c nullptr. The old data should have been freed first, if it was not \c nullptr.
252  *
253  * \param task a task
254  * \param data the new data you want to associate with this task
255  * \see SD_task_get_data()
256  */
257 void SD_task_set_data(SD_task_t task, void *data)
258 {
259   task->data = data;
260 }
261
262 /**
263  * \brief Sets the rate of a task
264  *
265  * This will change the network bandwidth a task can use. This rate  cannot be dynamically changed. Once the task has
266  * started, this call is ineffective. This rate depends on both the nominal bandwidth on the route onto which the task
267  * is scheduled (\see SD_task_get_current_bandwidth) and the amount of data to transfer.
268  *
269  * To divide the nominal bandwidth by 2, the rate then has to be :
270  *    rate = bandwidth/(2*amount)
271  *
272  * \param task a \see SD_TASK_COMM_E2E task (end-to-end communication)
273  * \param rate the new rate you want to associate with this task.
274  */
275 void SD_task_set_rate(SD_task_t task, double rate)
276 {
277   xbt_assert(task->kind == SD_TASK_COMM_E2E, "The rate can be modified for end-to-end communications only.");
278   if(task->state < SD_RUNNING) {
279     task->rate = rate;
280   } else {
281     XBT_WARN("Task %p has started. Changing rate is ineffective.", task);
282   }
283 }
284
285 /**
286  * \brief Returns the state of a task
287  *
288  * \param task a task
289  * \return the current \ref e_SD_task_state_t "state" of this task:
290  * #SD_NOT_SCHEDULED, #SD_SCHEDULED, #SD_RUNNABLE, #SD_RUNNING, #SD_DONE or #SD_FAILED
291  * \see e_SD_task_state_t
292  */
293 e_SD_task_state_t SD_task_get_state(SD_task_t task)
294 {
295   return task->state;
296 }
297
298 /* Changes the state of a task. Updates the sd_global->watch_point_reached flag.
299  */
300 void SD_task_set_state(SD_task_t task, e_SD_task_state_t new_state)
301 {
302   std::set<SD_task_t>::iterator idx;
303   XBT_DEBUG("Set state of '%s' to %d", task->name, new_state);
304   if ((new_state == SD_NOT_SCHEDULED || new_state == SD_SCHEDULABLE) && task->state == SD_FAILED){
305     sd_global->completed_tasks->erase(task);
306     sd_global->initial_tasks->insert(task);
307   }
308
309   if (new_state == SD_SCHEDULED && task->state == SD_RUNNABLE){
310     sd_global->initial_tasks->insert(task);
311     sd_global->runnable_tasks->erase(task);
312   }
313
314   if (new_state == SD_RUNNABLE){
315     idx = sd_global->initial_tasks->find(task);
316     if (idx != sd_global->initial_tasks->end()) {
317       sd_global->runnable_tasks->insert(*idx);
318       sd_global->initial_tasks->erase(idx);
319     }
320   }
321
322   if (new_state == SD_RUNNING)
323     sd_global->runnable_tasks->erase(task);
324
325   if (new_state == SD_DONE || new_state == SD_FAILED){
326     sd_global->completed_tasks->insert(task);
327     task->start_time = task->surf_action->getStartTime();
328     if (new_state == SD_DONE){
329       task->finish_time = task->surf_action->getFinishTime();
330       task->remains = 0;
331 #if HAVE_JEDULE
332       jedule_log_sd_event(task);
333 #endif
334     } else
335       task->finish_time = surf_get_clock();
336     task->surf_action->unref();
337     task->surf_action = nullptr;
338     task->allocation->clear();
339   }
340
341   task->state = new_state;
342
343   if (task->watch_points & new_state) {
344     XBT_VERB("Watch point reached with task '%s'!", task->name);
345     sd_global->watch_point_reached = true;
346     SD_task_unwatch(task, new_state);   /* remove the watch point */
347   }
348 }
349
350 /**
351  * \brief Returns the name of a task
352  *
353  * \param task a task
354  * \return the name of this task (can be \c nullptr)
355  */
356 const char *SD_task_get_name(SD_task_t task)
357 {
358   return task->name;
359 }
360
361 /** @brief Allows to change the name of a task */
362 void SD_task_set_name(SD_task_t task, const char *name)
363 {
364   xbt_free(task->name);
365   task->name = xbt_strdup(name);
366 }
367
368 /** @brief Returns the dynar of the parents of a task
369  *
370  * \param task a task
371  * \return a newly allocated dynar comprising the parents of this task
372  */
373
374 xbt_dynar_t SD_task_get_parents(SD_task_t task)
375 {
376   xbt_dynar_t parents = xbt_dynar_new(sizeof(SD_task_t), nullptr);
377
378   for (auto it : *task->predecessors)
379     xbt_dynar_push(parents, &it);
380   for (auto it : *task->inputs)
381     xbt_dynar_push(parents, &it);
382
383   return parents;
384 }
385
386 /** @brief Returns the dynar of the parents of a task
387  *
388  * \param task a task
389  * \return a newly allocated dynar comprising the parents of this task
390  */
391 xbt_dynar_t SD_task_get_children(SD_task_t task)
392 {
393   xbt_dynar_t children = xbt_dynar_new(sizeof(SD_task_t), nullptr);
394
395   for (auto it : *task->successors)
396     xbt_dynar_push(children, &it);
397   for (auto it : *task->outputs)
398     xbt_dynar_push(children, &it);
399
400   return children;
401 }
402
403 /**
404  * \brief Returns the number of workstations involved in a task
405  *
406  * Only call this on already scheduled tasks!
407  * \param task a task
408  */
409 int SD_task_get_workstation_count(SD_task_t task)
410 {
411   return task->allocation->size();
412 }
413
414 /**
415  * \brief Returns the list of workstations involved in a task
416  *
417  * Only call this on already scheduled tasks!
418  * \param task a task
419  */
420 sg_host_t *SD_task_get_workstation_list(SD_task_t task)
421 {
422   return &(*(task->allocation))[0];
423 }
424
425 /**
426  * \brief Returns the total amount of work contained in a task
427  *
428  * \param task a task
429  * \return the total amount of work (computation or data transfer) for this task
430  * \see SD_task_get_remaining_amount()
431  */
432 double SD_task_get_amount(SD_task_t task)
433 {
434   return task->amount;
435 }
436
437 /** @brief Sets the total amount of work of a task
438  * For sequential typed tasks (COMP_SEQ and COMM_E2E), it also sets the appropriate values in the flops_amount and
439  * bytes_amount arrays respectively. Nothing more than modifying task->amount is done for parallel  typed tasks
440  * (COMP_PAR_AMDAHL and COMM_PAR_MXN_1D_BLOCK) as the distribution of the amount of work is done at scheduling time.
441  *
442  * \param task a task
443  * \param amount the new amount of work to execute
444  */
445 void SD_task_set_amount(SD_task_t task, double amount)
446 {
447   task->amount = amount;
448   if (task->kind == SD_TASK_COMP_SEQ)
449     task->flops_amount[0] = amount;
450   if (task->kind == SD_TASK_COMM_E2E)
451     task->bytes_amount[2] = amount;
452 }
453
454 /**
455  * \brief Returns the alpha parameter of a SD_TASK_COMP_PAR_AMDAHL task
456  *
457  * \param task a parallel task assuming Amdahl's law as speedup model
458  * \return the alpha parameter (serial part of a task in percent) for this task
459  */
460 double SD_task_get_alpha(SD_task_t task)
461 {
462   xbt_assert(SD_task_get_kind(task) == SD_TASK_COMP_PAR_AMDAHL, "Alpha parameter is not defined for this kind of task");
463   return task->alpha;
464 }
465
466 /**
467  * \brief Returns the remaining amount work to do till the completion of a task
468  *
469  * \param task a task
470  * \return the remaining amount of work (computation or data transfer) of this task
471  * \see SD_task_get_amount()
472  */
473 double SD_task_get_remaining_amount(SD_task_t task)
474 {
475   if (task->surf_action)
476     return task->surf_action->getRemains();
477   else
478     return task->remains;
479 }
480
481 e_SD_task_kind_t SD_task_get_kind(SD_task_t task)
482 {
483   return task->kind;
484 }
485
486 /** @brief Displays debugging information about a task */
487 void SD_task_dump(SD_task_t task)
488 {
489   XBT_INFO("Displaying task %s", SD_task_get_name(task));
490   char *statename = bprintf("%s%s%s%s%s%s%s",
491                       (task->state == SD_NOT_SCHEDULED ? " not scheduled" : ""),
492                       (task->state == SD_SCHEDULABLE ? " schedulable" : ""),
493                       (task->state == SD_SCHEDULED ? " scheduled" : ""),
494                       (task->state == SD_RUNNABLE ? " runnable" : " not runnable"),
495                       (task->state == SD_RUNNING ? " running" : ""),
496                       (task->state == SD_DONE ? " done" : ""),
497                       (task->state == SD_FAILED ? " failed" : ""));
498   XBT_INFO("  - state:%s", statename);
499   free(statename);
500
501   if (task->kind != 0) {
502     switch (task->kind) {
503     case SD_TASK_COMM_E2E:
504       XBT_INFO("  - kind: end-to-end communication");
505       break;
506     case SD_TASK_COMP_SEQ:
507       XBT_INFO("  - kind: sequential computation");
508       break;
509     case SD_TASK_COMP_PAR_AMDAHL:
510       XBT_INFO("  - kind: parallel computation following Amdahl's law");
511       break;
512     case SD_TASK_COMM_PAR_MXN_1D_BLOCK:
513       XBT_INFO("  - kind: MxN data redistribution assuming 1D block distribution");
514       break;
515     default:
516       XBT_INFO("  - (unknown kind %d)", task->kind);
517     }
518   }
519
520   XBT_INFO("  - amount: %.0f", SD_task_get_amount(task));
521   if (task->kind == SD_TASK_COMP_PAR_AMDAHL)
522     XBT_INFO("  - alpha: %.2f", task->alpha);
523   XBT_INFO("  - Dependencies to satisfy: %zu", task->inputs->size()+ task->predecessors->size());
524   if ((task->inputs->size()+ task->predecessors->size()) > 0) {
525     XBT_INFO("  - pre-dependencies:");
526     for (auto it : *task->predecessors)
527       XBT_INFO("    %s", it->name);
528
529     for (auto it: *task->inputs)
530       XBT_INFO("    %s", it->name);
531   }
532   if ((task->outputs->size() + task->successors->size()) > 0) {
533     XBT_INFO("  - post-dependencies:");
534
535     for (auto it : *task->successors)
536       XBT_INFO("    %s", it->name);
537     for (auto it : *task->outputs)
538       XBT_INFO("    %s", it->name);
539   }
540 }
541
542 /** @brief Dumps the task in dotty formalism into the FILE* passed as second argument */
543 void SD_task_dotty(SD_task_t task, void *out)
544 {
545   FILE *fout = static_cast<FILE*>(out);
546   fprintf(fout, "  T%p [label=\"%.20s\"", task, task->name);
547   switch (task->kind) {
548   case SD_TASK_COMM_E2E:
549   case SD_TASK_COMM_PAR_MXN_1D_BLOCK:
550     fprintf(fout, ", shape=box");
551     break;
552   case SD_TASK_COMP_SEQ:
553   case SD_TASK_COMP_PAR_AMDAHL:
554     fprintf(fout, ", shape=circle");
555     break;
556   default:
557     xbt_die("Unknown task type!");
558   }
559   fprintf(fout, "];\n");
560   for (auto it : *task->predecessors)
561     fprintf(fout, " T%p -> T%p;\n", it, task);
562   for (auto it : *task->inputs)
563     fprintf(fout, " T%p -> T%p;\n", it, task);
564 }
565
566 /**
567  * \brief Adds a dependency between two tasks
568  *
569  * \a dst will depend on \a src, ie \a dst will not start before \a src is finished.
570  * Their \ref e_SD_task_state_t "state" must be #SD_NOT_SCHEDULED, #SD_SCHEDULED or #SD_RUNNABLE.
571  *
572  * \param name the name of the new dependency (can be \c nullptr)
573  * \param data the user data you want to associate with this dependency (can be \c nullptr)
574  * \param src the task which must be executed first
575  * \param dst the task you want to make depend on \a src
576  * \see SD_task_dependency_remove()
577  */
578 void SD_task_dependency_add(const char *name, void *data, SD_task_t src, SD_task_t dst)
579 {
580   if (src == dst)
581     THROWF(arg_error, 0, "Cannot add a dependency between task '%s' and itself", SD_task_get_name(src));
582
583   if (src->state == SD_DONE || src->state == SD_FAILED)
584     THROWF(arg_error, 0, "Task '%s' must be SD_NOT_SCHEDULED, SD_SCHEDULABLE, SD_SCHEDULED, SD_RUNNABLE, or SD_RUNNING",
585            src->name);
586
587   if (dst->state == SD_DONE || dst->state == SD_FAILED || dst->state == SD_RUNNING)
588     THROWF(arg_error, 0, "Task '%s' must be SD_NOT_SCHEDULED, SD_SCHEDULABLE, SD_SCHEDULED, or SD_RUNNABLE",
589            dst->name);
590
591   if (dst->inputs->find(src) != dst->inputs->end() || src->outputs->find(dst) != src->outputs->end() ||
592       src->successors->find(dst) != src->successors->end() || dst->predecessors->find(src) != dst->predecessors->end())
593     THROWF(arg_error, 0, "A dependency already exists between task '%s' and task '%s'", src->name, dst->name);
594
595   XBT_DEBUG("SD_task_dependency_add: src = %s, dst = %s", src->name, dst->name);
596
597   if (src->kind == SD_TASK_COMM_E2E || src->kind == SD_TASK_COMM_PAR_MXN_1D_BLOCK){
598     if (dst->kind == SD_TASK_COMP_SEQ || dst->kind == SD_TASK_COMP_PAR_AMDAHL)
599         dst->inputs->insert(src);
600     else
601       dst->predecessors->insert(src);
602     src->successors->insert(dst);
603   } else {
604     if (dst->kind == SD_TASK_COMM_E2E|| dst->kind == SD_TASK_COMM_PAR_MXN_1D_BLOCK)
605       src->outputs->insert(dst);
606     else
607       src->successors->insert(dst);
608     dst->predecessors->insert(src);
609   }
610
611   /* if the task was runnable, the task goes back to SD_SCHEDULED because of the new dependency*/
612   if (dst->state == SD_RUNNABLE) {
613     XBT_DEBUG("SD_task_dependency_add: %s was runnable and becomes scheduled!", dst->name);
614     SD_task_set_state(dst, SD_SCHEDULED);
615   }
616 }
617
618 /**
619  * \brief Indicates whether there is a dependency between two tasks.
620  *
621  * \param src a task
622  * \param dst a task depending on \a src
623  *
624  * If src is nullptr, checks whether dst has any pre-dependency.
625  * If dst is nullptr, checks whether src has any post-dependency.
626  */
627 int SD_task_dependency_exists(SD_task_t src, SD_task_t dst)
628 {
629   xbt_assert(src != nullptr || dst != nullptr, "Invalid parameter: both src and dst are nullptr");
630
631   if (src) {
632     if (dst) {
633       return (src->successors->find(dst) != src->successors->end() || src->outputs->find(dst) != src->outputs->end());
634     } else {
635       return src->successors->size() + src->outputs->size();
636     }
637   } else {
638     return dst->predecessors->size() + dst->inputs->size();
639   }
640   return 0;
641 }
642
643 /**
644  * \brief Remove a dependency between two tasks
645  *
646  * \param src a task
647  * \param dst a task depending on \a src
648  * \see SD_task_dependency_add()
649  */
650 void SD_task_dependency_remove(SD_task_t src, SD_task_t dst)
651 {
652   XBT_DEBUG("SD_task_dependency_remove: src = %s, dst = %s", SD_task_get_name(src), SD_task_get_name(dst));
653
654   if (src->successors->find(dst) == src->successors->end() && src->outputs->find(dst) == src->outputs->end())
655     THROWF(arg_error, 0, "No dependency found between task '%s' and '%s': task '%s' is not a successor of task '%s'",
656            src->name, dst->name, dst->name, src->name);
657
658   if (src->kind == SD_TASK_COMM_E2E || src->kind == SD_TASK_COMM_PAR_MXN_1D_BLOCK){
659     if (dst->kind == SD_TASK_COMP_SEQ || dst->kind == SD_TASK_COMP_PAR_AMDAHL)
660       dst->inputs->erase(src);
661     else
662       dst->predecessors->erase(src);
663     src->successors->erase(dst);
664   } else {
665     if (dst->kind == SD_TASK_COMM_E2E|| dst->kind == SD_TASK_COMM_PAR_MXN_1D_BLOCK)
666       src->outputs->erase(dst);
667     else
668       src->successors->erase(dst);
669     dst->predecessors->erase(src);
670   }
671
672   /* if the task was scheduled and dependencies are satisfied, we can make it runnable */
673   if (dst->predecessors->empty() && dst->inputs->empty() && dst->state == SD_SCHEDULED)
674     SD_task_set_state(dst, SD_RUNNABLE);
675 }
676
677 /**
678  * \brief Adds a watch point to a task
679  *
680  * SD_simulate() will stop as soon as the \ref e_SD_task_state_t "state" of this task becomes the one given in argument.
681  * The watch point is then automatically removed.
682  *
683  * \param task a task
684  * \param state the \ref e_SD_task_state_t "state" you want to watch (cannot be #SD_NOT_SCHEDULED)
685  * \see SD_task_unwatch()
686  */
687 void SD_task_watch(SD_task_t task, e_SD_task_state_t state)
688 {
689   if (state & SD_NOT_SCHEDULED)
690     THROWF(arg_error, 0, "Cannot add a watch point for state SD_NOT_SCHEDULED");
691
692   task->watch_points = task->watch_points | state;
693 }
694
695 /**
696  * \brief Removes a watch point from a task
697  *
698  * \param task a task
699  * \param state the \ref e_SD_task_state_t "state" you no longer want to watch
700  * \see SD_task_watch()
701  */
702 void SD_task_unwatch(SD_task_t task, e_SD_task_state_t state)
703 {
704   xbt_assert(state != SD_NOT_SCHEDULED, "SimDag error: Cannot have a watch point for state SD_NOT_SCHEDULED");
705   task->watch_points = task->watch_points & ~state;
706 }
707
708 /**
709  * \brief Returns an approximative estimation of the execution time of a task.
710  *
711  * The estimation is very approximative because the value returned is the time the task would take if it was executed
712  * now and if it was the only task.
713  *
714  * \param task the task to evaluate
715  * \param host_count number of hosts on which the task would be executed
716  * \param host_list the hosts on which the task would be executed
717  * \param flops_amount computation amount for each host(i.e., an array of host_count doubles)
718  * \param bytes_amount communication amount between each pair of hosts (i.e., a matrix of host_count*host_count doubles)
719  * \see SD_schedule()
720  */
721 double SD_task_get_execution_time(SD_task_t task, int host_count, const sg_host_t *host_list,
722                                   const double *flops_amount, const double *bytes_amount)
723 {
724   xbt_assert(host_count > 0, "Invalid parameter");
725   double max_time = 0.0;
726
727   /* the task execution time is the maximum execution time of the parallel tasks */
728   for (int i = 0; i < host_count; i++) {
729     double time = 0.0;
730     if (flops_amount != nullptr)
731       time = flops_amount[i] / host_list[i]->speed();
732
733     if (bytes_amount != nullptr)
734       for (int j = 0; j < host_count; j++)
735         if (bytes_amount[i * host_count + j] != 0)
736           time += (SD_route_get_latency(host_list[i], host_list[j]) +
737                    bytes_amount[i * host_count + j] / SD_route_get_bandwidth(host_list[i], host_list[j]));
738
739     if (time > max_time)
740       max_time = time;
741   }
742   return max_time;
743 }
744
745 static inline void SD_task_do_schedule(SD_task_t task)
746 {
747   if (SD_task_get_state(task) > SD_SCHEDULABLE)
748     THROWF(arg_error, 0, "Task '%s' has already been scheduled", SD_task_get_name(task));
749
750   if (task->predecessors->empty() && task->inputs->empty())
751     SD_task_set_state(task, SD_RUNNABLE);
752   else
753     SD_task_set_state(task, SD_SCHEDULED);
754 }
755
756 /**
757  * \brief Schedules a task
758  *
759  * The task state must be #SD_NOT_SCHEDULED.
760  * Once scheduled, a task is executed as soon as possible in \see SD_simulate, i.e. when its dependencies are satisfied.
761  *
762  * \param task the task you want to schedule
763  * \param host_count number of hosts on which the task will be executed
764  * \param workstation_list the hosts on which the task will be executed
765  * \param flops_amount computation amount for each hosts (i.e., an array of host_count doubles)
766  * \param bytes_amount communication amount between each pair of hosts (i.e., a matrix of host_count*host_count doubles)
767  * \param rate task execution speed rate
768  * \see SD_task_unschedule()
769  */
770 void SD_task_schedule(SD_task_t task, int host_count, const sg_host_t * host_list,
771                       const double *flops_amount, const double *bytes_amount, double rate)
772 {
773   xbt_assert(host_count > 0, "host_count must be positive");
774
775   task->rate = rate;
776
777   if (flops_amount) {
778     task->flops_amount = static_cast<double*>(xbt_realloc(task->flops_amount, sizeof(double) * host_count));
779     memcpy(task->flops_amount, flops_amount, sizeof(double) * host_count);
780   } else {
781     xbt_free(task->flops_amount);
782     task->flops_amount = nullptr;
783   }
784
785   int communication_nb = host_count * host_count;
786   if (bytes_amount) {
787     task->bytes_amount = static_cast<double*>(xbt_realloc(task->bytes_amount, sizeof(double) * communication_nb));
788     memcpy(task->bytes_amount, bytes_amount, sizeof(double) * communication_nb);
789   } else {
790     xbt_free(task->bytes_amount);
791     task->bytes_amount = nullptr;
792   }
793
794   for(int i =0; i<host_count; i++)
795     task->allocation->push_back(host_list[i]);
796
797   SD_task_do_schedule(task);
798 }
799
800 /**
801  * \brief Unschedules a task
802  *
803  * The task state must be #SD_SCHEDULED, #SD_RUNNABLE, #SD_RUNNING or #SD_FAILED.
804  * If you call this function, the task state becomes #SD_NOT_SCHEDULED.
805  * Call SD_task_schedule() to schedule it again.
806  *
807  * \param task the task you want to unschedule
808  * \see SD_task_schedule()
809  */
810 void SD_task_unschedule(SD_task_t task)
811 {
812   if (task->state == SD_NOT_SCHEDULED || task->state == SD_SCHEDULABLE)
813     THROWF(arg_error, 0, "Task %s: the state must be SD_SCHEDULED, SD_RUNNABLE, SD_RUNNING or SD_FAILED", task->name);
814
815   if ((task->state == SD_SCHEDULED || task->state == SD_RUNNABLE) /* if the task is scheduled or runnable */
816       && ((task->kind == SD_TASK_COMP_PAR_AMDAHL) || (task->kind == SD_TASK_COMM_PAR_MXN_1D_BLOCK))) {
817           /* Don't free scheduling data for typed tasks */
818     __SD_task_destroy_scheduling_data(task);
819     task->allocation->clear();
820   }
821
822   if (SD_task_get_state(task) == SD_RUNNING)
823     /* the task should become SD_FAILED */
824     task->surf_action->cancel();
825   else {
826     if (task->predecessors->empty() && task->inputs->empty())
827       SD_task_set_state(task, SD_SCHEDULABLE);
828     else
829       SD_task_set_state(task, SD_NOT_SCHEDULED);
830   }
831   task->remains = task->amount;
832   task->start_time = -1.0;
833 }
834
835 /* Runs a task. */
836 void SD_task_run(SD_task_t task)
837 {
838   xbt_assert(task->state == SD_RUNNABLE, "Task '%s' is not runnable! Task state: %d", task->name, (int) task->state);
839   xbt_assert(task->allocation != nullptr, "Task '%s': host_list is nullptr!", task->name);
840
841   XBT_VERB("Executing task '%s'", task->name);
842
843   /* Copy the elements of the task into the action */
844   int host_nb = task->allocation->size();
845   XBT_DEBUG("%d", host_nb);
846   sg_host_t *hosts = xbt_new(sg_host_t, host_nb);
847   int i =0;
848   for (auto host: *task->allocation)
849     hosts[i++] = host;
850
851   double *flops_amount = xbt_new0(double, host_nb);
852   double *bytes_amount = xbt_new0(double, host_nb * host_nb);
853
854   if(task->flops_amount)
855     memcpy(flops_amount, task->flops_amount, sizeof(double) * host_nb);
856   if(task->bytes_amount)
857     memcpy(bytes_amount, task->bytes_amount, sizeof(double) * host_nb * host_nb);
858
859   task->surf_action = surf_host_model->executeParallelTask(host_nb, hosts, flops_amount, bytes_amount, task->rate);
860
861   task->surf_action->setData(task);
862
863   XBT_DEBUG("surf_action = %p", task->surf_action);
864
865   __SD_task_destroy_scheduling_data(task);      /* now the scheduling data are not useful anymore */
866   SD_task_set_state(task, SD_RUNNING);
867   xbt_dynar_push(sd_global->return_set, &task);
868 }
869
870 /**
871  * \brief Returns the start time of a task
872  *
873  * The task state must be SD_RUNNING, SD_DONE or SD_FAILED.
874  *
875  * \param task: a task
876  * \return the start time of this task
877  */
878 double SD_task_get_start_time(SD_task_t task)
879 {
880   if (task->surf_action)
881     return task->surf_action->getStartTime();
882   else
883     return task->start_time;
884 }
885
886 /**
887  * \brief Returns the finish time of a task
888  *
889  * The task state must be SD_RUNNING, SD_DONE or SD_FAILED.
890  * If the state is not completed yet, the returned value is an estimation of the task finish time. This value can
891  * vary until the task is completed.
892  *
893  * \param task: a task
894  * \return the start time of this task
895  */
896 double SD_task_get_finish_time(SD_task_t task)
897 {
898   if (task->surf_action)        /* should never happen as actions are destroyed right after their completion */
899     return task->surf_action->getFinishTime();
900   else
901     return task->finish_time;
902 }
903
904 void SD_task_distribute_comp_amdahl(SD_task_t task, int count)
905 {
906   xbt_assert(task->kind == SD_TASK_COMP_PAR_AMDAHL, "Task %s is not a SD_TASK_COMP_PAR_AMDAHL typed task."
907               "Cannot use this function.", task->name);
908   task->flops_amount = xbt_new0(double, count);
909   task->bytes_amount = xbt_new0(double, count * count);
910
911   for (int i=0; i<count; i++){
912     task->flops_amount[i] = (task->alpha + (1 - task->alpha)/count) * task->amount;
913   }
914 }
915
916 /** @brief Auto-schedules a task.
917  *
918  * Auto-scheduling mean that the task can be used with SD_task_schedulev(). This allows to specify the task costs at
919  * creation, and decouple them from the scheduling process where you just specify which resource should deliver the
920  * mandatory power.
921  *
922  * To be auto-schedulable, a task must be type and created with one of the specialized creation functions.
923  *
924  * @todo
925  * We should create tasks kind for the following categories:
926  *  - Point to point communication (done)
927  *  - Sequential computation       (done)
928  *  - group communication (redistribution, several kinds)
929  *  - parallel tasks with no internal communication (one kind per speedup  model such as Amdahl)
930  *  - idem+ internal communication. Task type not enough since we cannot store comm cost alongside to comp one)
931  */
932 void SD_task_schedulev(SD_task_t task, int count, const sg_host_t * list)
933 {
934   xbt_assert(task->kind != 0, "Task %s is not typed. Cannot automatically schedule it.", SD_task_get_name(task));
935
936   for(int i =0; i<count; i++)
937     task->allocation->push_back(list[i]);
938
939   if (task->kind == SD_TASK_COMP_SEQ) {
940     if (!task->flops_amount){
941       /*This task has failed and is rescheduled. Reset the flops_amount*/
942       task->flops_amount = xbt_new0(double, 1);
943       task->flops_amount[0] = task->remains;
944     }
945     XBT_VERB("Schedule computation task %s on %s. It costs %.f flops", task->name,
946              sg_host_get_name(task->allocation->at(0)), task->flops_amount[0]);
947     SD_task_do_schedule(task);
948
949     /* Iterate over all inputs and outputs to say where I am located (and start them if runnable) */
950     for (auto input : *task->inputs){
951       input->allocation->push_back(task->allocation->front());
952       if (input->allocation->size () == 2) {
953         SD_task_do_schedule(input);
954         XBT_VERB ("Auto-Schedule comm task %s between %s -> %s. It costs %.f bytes", SD_task_get_name(input),
955                   sg_host_get_name(input->allocation->at(0)), sg_host_get_name(input->allocation->at(1)),
956                   input->bytes_amount[2]);
957       }
958     }
959
960     for (auto output : *task->outputs){
961       output->allocation->insert(output->allocation->begin(),task->allocation->front());
962       if (output->allocation->size() == 2) {
963         SD_task_do_schedule(output);
964         XBT_VERB ("Auto-Schedule comm task %s between %s -> %s. It costs %.f bytes", SD_task_get_name(output),
965                   sg_host_get_name(output->allocation->at(0)), sg_host_get_name(output->allocation->at(1)),
966                   output->bytes_amount[2]);
967       }
968     }
969   }
970
971   if (task->kind == SD_TASK_COMP_PAR_AMDAHL) {
972     SD_task_distribute_comp_amdahl(task, count);
973     XBT_VERB("Schedule computation task %s on %zu workstations. %.f flops will be distributed following Amdahl's Law",
974              task->name, task->allocation->size(), task->flops_amount[0]);
975     SD_task_do_schedule(task);
976
977     /* Iterate over all inputs and outputs to say where I am located (and start them if runnable) */
978     for (auto input : *task->inputs){
979       if (input->allocation->empty()){
980         XBT_VERB("Sender side of Task %s is not scheduled yet", input->name);
981         XBT_VERB("Fill the workstation list with list of Task '%s'", task->name);
982         for (int i=0; i<count;i++)
983           input->allocation->push_back(task->allocation->at(i));
984       } else {
985         XBT_VERB("Build communication matrix for task '%s'", input->name);
986         int src_nb = input->allocation->size();
987         int dst_nb = count;
988         for (int i=0; i<count;i++)
989           input->allocation->push_back(task->allocation->at(i));
990         xbt_free(input->flops_amount);
991         xbt_free(input->bytes_amount);
992         input->flops_amount = xbt_new0(double, input->allocation->size());
993         input->bytes_amount = xbt_new0(double, input->allocation->size() * input->allocation->size());
994
995         for (int i=0; i<src_nb; i++) {
996           double src_start = i*input->amount/src_nb;
997           double src_end = src_start + input->amount/src_nb;
998           for (int j=0; j<dst_nb; j++) {
999             double dst_start = j*input->amount/dst_nb;
1000             double dst_end = dst_start + input->amount/dst_nb;
1001             XBT_VERB("(%s->%s): (%.2f, %.2f)-> (%.2f, %.2f)", sg_host_get_name(input->allocation->at(i)),
1002                 sg_host_get_name(input->allocation->at(src_nb+j)), src_start, src_end, dst_start, dst_end);
1003             if ((src_end <= dst_start) || (dst_end <= src_start)) {
1004               input->bytes_amount[i*(src_nb+dst_nb)+src_nb+j]=0.0;
1005             } else {
1006               input->bytes_amount[i*(src_nb+dst_nb)+src_nb+j] = MIN(src_end, dst_end) - MAX(src_start, dst_start);
1007             }
1008             XBT_VERB("==> %.2f", input->bytes_amount[i*(src_nb+dst_nb)+src_nb+j]);
1009           }
1010         }
1011
1012         if (SD_task_get_state(input)< SD_SCHEDULED) {
1013           SD_task_do_schedule(input);
1014           XBT_VERB ("Auto-Schedule redistribution task %s. Send %.f bytes from %d hosts to %d hosts.",
1015                     input->name,input->amount, src_nb, dst_nb);
1016         }
1017       }
1018     }
1019
1020     for (auto output : *task->outputs) {
1021       if (output->allocation->empty()){
1022         XBT_VERB("Receiver side of Task '%s' is not scheduled yet", SD_task_get_name(output));
1023         XBT_VERB("Fill the workstation list with list of Task '%s'", SD_task_get_name(task));
1024         for (int i=0; i<count;i++)
1025           output->allocation->push_back(task->allocation->at(i));
1026       } else {
1027         double src_start, src_end, dst_start, dst_end;
1028         int src_nb = count;
1029         int dst_nb = output->allocation->size();
1030         for (int i=0; i<count;i++)
1031           output->allocation->insert(output->allocation->begin()+i, task->allocation->at(i));
1032         xbt_free(output->flops_amount);
1033         xbt_free(output->bytes_amount);
1034
1035         output->flops_amount = xbt_new0(double, output->allocation->size());
1036         output->bytes_amount = xbt_new0(double, output->allocation->size() * output->allocation->size());
1037
1038         for (int i=0; i<src_nb; i++) {
1039           src_start = i*output->amount/src_nb;
1040           src_end = src_start + output->amount/src_nb;
1041           for (int j=0; j<dst_nb; j++) {
1042             dst_start = j*output->amount/dst_nb;
1043             dst_end = dst_start + output->amount/dst_nb;
1044             XBT_VERB("(%d->%d): (%.2f, %.2f)-> (%.2f, %.2f)", i, j, src_start, src_end, dst_start, dst_end);
1045             if ((src_end <= dst_start) || (dst_end <= src_start)) {
1046               output->bytes_amount[i*(src_nb+dst_nb)+src_nb+j]=0.0;
1047             } else {
1048               output->bytes_amount[i*(src_nb+dst_nb)+src_nb+j] = MIN(src_end, dst_end)- MAX(src_start, dst_start);
1049             }
1050             XBT_VERB("==> %.2f", output->bytes_amount[i*(src_nb+dst_nb)+src_nb+j]);
1051           }
1052         }
1053
1054         if (SD_task_get_state(output)< SD_SCHEDULED) {
1055           SD_task_do_schedule(output);
1056           XBT_VERB ("Auto-Schedule redistribution task %s. Send %.f bytes from %d hosts to %d hosts.",
1057               output->name, output->amount, src_nb, dst_nb);
1058         }
1059       }
1060     }
1061   }
1062 }
1063
1064 /** @brief autoschedule a task on a list of workstations
1065  *
1066  * This function is very similar to SD_task_schedulev(), but takes the list of workstations to schedule onto as
1067  * separate parameters.
1068  * It builds a proper vector of workstations and then call SD_task_schedulev()
1069  */
1070 void SD_task_schedulel(SD_task_t task, int count, ...)
1071 {
1072   va_list ap;
1073   sg_host_t *list = xbt_new(sg_host_t, count);
1074   va_start(ap, count);
1075   for (int i=0; i<count; i++)
1076     list[i] = va_arg(ap, sg_host_t);
1077
1078   va_end(ap);
1079   SD_task_schedulev(task, count, list);
1080   xbt_free(list);
1081 }