Logo AND Algorithmique Numérique Distribuée

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