Logo AND Algorithmique Numérique Distribuée

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