Logo AND Algorithmique Numérique Distribuée

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