Logo AND Algorithmique Numérique Distribuée

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