Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge remote-tracking branch 'origin/libdw2'
[simgrid.git] / src / surf / cpu_ti.c
1
2 /* Copyright (c) 2009-2013. The SimGrid Team.
3  * All rights reserved.                                                     */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 /*
9   commit: e2d6799c4182f00443b3013aadb1c2412372460f
10   This commit retrieves the old implementation of CPU_TI with multi-levels.
11 */
12
13 #include "surf_private.h"
14 #include "trace_mgr_private.h"
15 #include "cpu_ti_private.h"
16 #include "xbt/heap.h"
17 #include "surf/surf_resource.h"
18
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf,
20                                 "Logging specific to the SURF CPU TRACE INTEGRATION module");
21
22
23 static xbt_swag_t
24     cpu_ti_running_action_set_that_does_not_need_being_checked = NULL;
25 static xbt_swag_t cpu_ti_modified_cpu = NULL;
26 static xbt_heap_t cpu_ti_action_heap;
27
28 /* prototypes of new trace functions */
29 static double surf_cpu_ti_integrate_trace(surf_cpu_ti_tgmr_t trace,
30                                           double a, double b);
31
32
33 static double surf_cpu_ti_solve_trace(surf_cpu_ti_tgmr_t trace, double a,
34                                       double amount);
35 static double surf_cpu_ti_solve_trace_somewhat_simple(surf_cpu_ti_tgmr_t
36                                                       trace, double a,
37                                                       double amount);
38
39 static void surf_cpu_ti_free_tmgr(surf_cpu_ti_tgmr_t trace);
40
41 static double surf_cpu_ti_integrate_trace_simple(surf_cpu_ti_trace_t trace,
42                                                  double a, double b);
43 static double surf_cpu_ti_integrate_trace_simple_point(surf_cpu_ti_trace_t
44                                                        trace, double a);
45 static double surf_cpu_ti_solve_trace_simple(surf_cpu_ti_trace_t trace,
46                                              double a, double amount);
47 static int surf_cpu_ti_binary_search(double *array, double a, int low,
48                                      int high);
49 /* end prototypes */
50
51 static void surf_cpu_ti_free_trace(surf_cpu_ti_trace_t trace)
52 {
53   xbt_free(trace->time_points);
54   xbt_free(trace->integral);
55   xbt_free(trace);
56 }
57
58 static void surf_cpu_ti_free_tmgr(surf_cpu_ti_tgmr_t trace)
59 {
60   if (trace->trace)
61     surf_cpu_ti_free_trace(trace->trace);
62   xbt_free(trace);
63 }
64
65 static surf_cpu_ti_trace_t surf_cpu_ti_trace_new(tmgr_trace_t power_trace)
66 {
67   surf_cpu_ti_trace_t trace;
68   s_tmgr_event_t val;
69   unsigned int cpt;
70   double integral = 0;
71   double time = 0;
72   int i = 0;
73   trace = xbt_new0(s_surf_cpu_ti_trace_t, 1);
74   trace->time_points =
75       xbt_malloc0(sizeof(double) *
76                   (xbt_dynar_length(power_trace->s_list.event_list) + 1));
77   trace->integral =
78       xbt_malloc0(sizeof(double) *
79                   (xbt_dynar_length(power_trace->s_list.event_list) + 1));
80   trace->nb_points = xbt_dynar_length(power_trace->s_list.event_list);
81   xbt_dynar_foreach(power_trace->s_list.event_list, cpt, val) {
82     trace->time_points[i] = time;
83     trace->integral[i] = integral;
84     integral += val.delta * val.value;
85     time += val.delta;
86     i++;
87   }
88   trace->time_points[i] = time;
89   trace->integral[i] = integral;
90   return trace;
91 }
92
93 /**
94 * \brief Creates a new integration trace from a tmgr_trace_t
95 *
96 * \param  power_trace    CPU availability trace
97 * \param  value          Percentage of CPU power available (useful to fixed tracing)
98 * \param  spacing        Initial spacing
99 * \return  Integration trace structure
100 */
101 static surf_cpu_ti_tgmr_t cpu_ti_parse_trace(tmgr_trace_t power_trace,
102                                              double value)
103 {
104   surf_cpu_ti_tgmr_t trace;
105   double total_time = 0.0;
106   s_tmgr_event_t val;
107   unsigned int cpt;
108   trace = xbt_new0(s_surf_cpu_ti_tgmr_t, 1);
109
110 /* no availability file, fixed trace */
111   if (!power_trace) {
112     trace->type = TRACE_FIXED;
113     trace->value = value;
114     XBT_DEBUG("No availability trace. Constant value = %f", value);
115     return trace;
116   }
117
118   /* only one point available, fixed trace */
119   if (xbt_dynar_length(power_trace->s_list.event_list) == 1) {
120     xbt_dynar_get_cpy(power_trace->s_list.event_list, 0, &val);
121     trace->type = TRACE_FIXED;
122     trace->value = val.value;
123     return trace;
124   }
125
126   trace->type = TRACE_DYNAMIC;
127   trace->power_trace = power_trace;
128
129   /* count the total time of trace file */
130   xbt_dynar_foreach(power_trace->s_list.event_list, cpt, val) {
131     total_time += val.delta;
132   }
133   trace->trace = surf_cpu_ti_trace_new(power_trace);
134   trace->last_time = total_time;
135   trace->total =
136       surf_cpu_ti_integrate_trace_simple(trace->trace, 0, total_time);
137
138   XBT_DEBUG("Total integral %f, last_time %f ",
139          trace->total, trace->last_time);
140
141   return trace;
142 }
143
144
145 static void* cpu_ti_create_resource(const char *name, xbt_dynar_t power_peak,
146                                                    int pstate,
147                            double power_scale,
148                            tmgr_trace_t power_trace,
149                            int core,
150                            e_surf_resource_state_t state_initial,
151                            tmgr_trace_t state_trace,
152                            xbt_dict_t cpu_properties)
153 {
154   tmgr_trace_t empty_trace;
155   s_tmgr_event_t val;
156   cpu_ti_t cpu = NULL;
157   s_surf_action_cpu_ti_t ti_action;
158   xbt_assert(core==1,"Multi-core not handled with this model yet");
159   xbt_assert(!surf_cpu_resource_priv(surf_cpu_resource_by_name(name)),
160               "Host '%s' declared several times in the platform file",
161               name);
162   xbt_assert(core==1,"Multi-core not handled with this model yet");
163   cpu = (cpu_ti_t) surf_resource_new(sizeof(s_cpu_ti_t),
164           surf_cpu_model, name,cpu_properties, NULL);
165   cpu->action_set =
166       xbt_swag_new(xbt_swag_offset(ti_action, cpu_list_hookup));
167
168   xbt_dynar_get_cpy(power_peak, 0, &cpu->power_peak);
169   xbt_dynar_free(&power_peak);  /* kill memory leak */
170   //cpu->power_peak = power_peak;
171   cpu->pstate = pstate;
172   XBT_DEBUG("CPU create: peak=%f, pstate=%d",cpu->power_peak, cpu->pstate);
173
174   xbt_assert(cpu->power_peak > 0, "Power has to be >0");
175   XBT_DEBUG("power scale %f", power_scale);
176   cpu->power_scale = power_scale;
177   cpu->avail_trace = cpu_ti_parse_trace(power_trace, power_scale);
178   cpu->state_current = state_initial;
179   if (state_trace)
180     cpu->state_event =
181         tmgr_history_add_trace(history, state_trace, 0.0, 0, cpu);
182   if (power_trace && xbt_dynar_length(power_trace->s_list.event_list) > 1) {
183     /* add a fake trace event if periodicity == 0 */
184     xbt_dynar_get_cpy(power_trace->s_list.event_list,
185                       xbt_dynar_length(power_trace->s_list.event_list) - 1, &val);
186     if (val.delta == 0) {
187       empty_trace = tmgr_empty_trace_new();
188       cpu->power_event =
189           tmgr_history_add_trace(history, empty_trace,
190                                  cpu->avail_trace->last_time, 0, cpu);
191     }
192   }
193   xbt_lib_set(host_lib, name, SURF_CPU_LEVEL, cpu);
194
195   return xbt_lib_get_elm_or_null(host_lib, name);
196 }
197
198
199 static void parse_cpu_ti_init(sg_platf_host_cbarg_t host)
200 {
201   cpu_ti_create_resource(host->id,
202         host->power_peak,
203         host->pstate,
204         host->power_scale,
205         host->power_trace,
206         host->core_amount,
207         host->initial_state,
208         host->state_trace,
209         host->properties);
210
211 }
212
213 static void add_traces_cpu_ti(void)
214 {
215   xbt_dict_cursor_t cursor = NULL;
216   char *trace_name, *elm;
217
218   static int called = 0;
219
220   if (called)
221     return;
222   called = 1;
223
224 /* connect all traces relative to hosts */
225   xbt_dict_foreach(trace_connect_list_host_avail, cursor, trace_name, elm) {
226     tmgr_trace_t trace = xbt_dict_get_or_null(traces_set_list, trace_name);
227     cpu_ti_t cpu = surf_cpu_resource_priv(surf_cpu_resource_by_name(elm));
228
229     xbt_assert(cpu, "Host %s undefined", elm);
230     xbt_assert(trace, "Trace %s undefined", trace_name);
231
232     if (cpu->state_event) {
233       XBT_DEBUG("Trace already configured for this CPU(%s), ignoring it",
234              elm);
235       continue;
236     }
237     XBT_DEBUG("Add state trace: %s to CPU(%s)", trace_name, elm);
238     cpu->state_event = tmgr_history_add_trace(history, trace, 0.0, 0, cpu);
239   }
240
241   xbt_dict_foreach(trace_connect_list_power, cursor, trace_name, elm) {
242     tmgr_trace_t trace = xbt_dict_get_or_null(traces_set_list, trace_name);
243     cpu_ti_t cpu = surf_cpu_resource_priv(surf_cpu_resource_by_name(elm));
244
245     xbt_assert(cpu, "Host %s undefined", elm);
246     xbt_assert(trace, "Trace %s undefined", trace_name);
247
248     XBT_DEBUG("Add power trace: %s to CPU(%s)", trace_name, elm);
249     if (cpu->avail_trace)
250       surf_cpu_ti_free_tmgr(cpu->avail_trace);
251
252     cpu->avail_trace = cpu_ti_parse_trace(trace, cpu->power_scale);
253
254     /* add a fake trace event if periodicity == 0 */
255     if (trace && xbt_dynar_length(trace->s_list.event_list) > 1) {
256       s_tmgr_event_t val;
257       xbt_dynar_get_cpy(trace->s_list.event_list,
258                         xbt_dynar_length(trace->s_list.event_list) - 1, &val);
259       if (val.delta == 0) {
260         tmgr_trace_t empty_trace;
261         empty_trace = tmgr_empty_trace_new();
262         cpu->power_event =
263             tmgr_history_add_trace(history, empty_trace,
264                                    cpu->avail_trace->last_time, 0, cpu);
265       }
266     }
267   }
268 }
269
270 static void cpu_ti_define_callbacks()
271 {
272   sg_platf_host_add_cb(parse_cpu_ti_init);
273   sg_platf_postparse_add_cb(add_traces_cpu_ti);
274 }
275
276 static int cpu_ti_resource_used(void *resource_id)
277 {
278   cpu_ti_t cpu = resource_id;
279   return xbt_swag_size(cpu->action_set);
280 }
281
282 static int cpu_ti_action_unref(surf_action_t action)
283 {
284   action->refcount--;
285   if (!action->refcount) {
286     xbt_swag_remove(action, action->state_set);
287     /* remove from action_set */
288     xbt_swag_remove(action, ((cpu_ti_t)surf_cpu_resource_priv(ACTION_GET_CPU(action)))->action_set);
289     /* remove from heap */
290     xbt_heap_remove(cpu_ti_action_heap,
291                     ((surf_action_cpu_ti_t) action)->index_heap);
292     xbt_swag_insert(((cpu_ti_t)surf_cpu_resource_priv(ACTION_GET_CPU(action))), cpu_ti_modified_cpu);
293     surf_action_free(&action);
294     return 1;
295   }
296   return 0;
297 }
298
299 static void cpu_ti_action_cancel(surf_action_t action)
300 {
301   surf_action_state_set(action, SURF_ACTION_FAILED);
302   xbt_heap_remove(cpu_ti_action_heap,
303                   ((surf_action_cpu_ti_t) action)->index_heap);
304   xbt_swag_insert(surf_cpu_resource_priv(ACTION_GET_CPU(action)), cpu_ti_modified_cpu);
305   return;
306 }
307
308 static void cpu_ti_action_state_set(surf_action_t action,
309                                     e_surf_action_state_t state)
310 {
311   surf_action_state_set(action, state);
312   xbt_swag_insert(surf_cpu_resource_priv(ACTION_GET_CPU(action)), cpu_ti_modified_cpu);
313   return;
314 }
315
316 /**
317 * \brief Update the remaining amount of actions
318 *
319 * \param  cpu    Cpu on which the actions are running
320 * \param  now    Current time
321 */
322 static void cpu_ti_update_remaining_amount(cpu_ti_t cpu, double now)
323 {
324   double area_total;
325   surf_action_cpu_ti_t action;
326
327 /* already updated */
328   if (cpu->last_update >= now)
329     return;
330
331 /* calcule the surface */
332   area_total =
333       surf_cpu_ti_integrate_trace(cpu->avail_trace, cpu->last_update,
334                                   now) * cpu->power_peak;
335   XBT_DEBUG("Flops total: %f, Last update %f", area_total,
336          cpu->last_update);
337
338   xbt_swag_foreach(action, cpu->action_set) {
339     surf_action_t generic = (surf_action_t)action;
340     /* action not running, skip it */
341     if (generic->state_set !=
342         surf_cpu_model->states.running_action_set)
343       continue;
344
345     /* bogus priority, skip it */
346     if (generic->priority <= 0)
347       continue;
348
349     /* action suspended, skip it */
350     if (action->suspended != 0)
351       continue;
352
353     /* action don't need update */
354     if (generic->start >= now)
355       continue;
356
357     /* skip action that are finishing now */
358     if (generic->finish >= 0
359         && generic->finish <= now)
360       continue;
361
362     /* update remaining */
363     double_update(&(generic->remains),
364                   area_total / (cpu->sum_priority *
365                                 generic->priority));
366     XBT_DEBUG("Update remaining action(%p) remaining %f", action,
367            generic->remains);
368   }
369   cpu->last_update = now;
370 #undef GENERIC_ACTION
371 }
372
373 /**
374 * \brief Update the finish date of action if necessary
375 *
376 * \param  cpu    Cpu on which the actions are running
377 * \param  now    Current time
378 */
379 static void cpu_ti_update_action_finish_date(cpu_ti_t cpu, double now)
380 {
381 #define GENERIC_ACTION(action) action->generic_action
382   surf_action_cpu_ti_t action;
383   double sum_priority = 0.0, total_area, min_finish = -1;
384
385 /* update remaning amount of actions */
386   cpu_ti_update_remaining_amount(cpu, now);
387
388   xbt_swag_foreach(action, cpu->action_set) {
389     /* action not running, skip it */
390     if (GENERIC_ACTION(action).state_set !=
391         surf_cpu_model->states.running_action_set)
392       continue;
393
394     /* bogus priority, skip it */
395     if (GENERIC_ACTION(action).priority <= 0)
396       continue;
397
398     /* action suspended, skip it */
399     if (action->suspended != 0)
400       continue;
401
402     sum_priority += 1.0 / GENERIC_ACTION(action).priority;
403   }
404   cpu->sum_priority = sum_priority;
405
406   xbt_swag_foreach(action, cpu->action_set) {
407     min_finish = -1;
408     /* action not running, skip it */
409     if (GENERIC_ACTION(action).state_set !=
410         surf_cpu_model->states.running_action_set)
411       continue;
412
413     /* verify if the action is really running on cpu */
414     if (action->suspended == 0 && GENERIC_ACTION(action).priority > 0) {
415       /* total area needed to finish the action. Used in trace integration */
416       total_area =
417           (GENERIC_ACTION(action).remains) * sum_priority *
418           GENERIC_ACTION(action).priority;
419
420       total_area /= cpu->power_peak;
421
422       GENERIC_ACTION(action).finish =
423           surf_cpu_ti_solve_trace(cpu->avail_trace, now, total_area);
424       /* verify which event will happen before (max_duration or finish time) */
425       if ((GENERIC_ACTION(action).max_duration != NO_MAX_DURATION) &&
426           (GENERIC_ACTION(action).start +
427            GENERIC_ACTION(action).max_duration <
428            GENERIC_ACTION(action).finish))
429         min_finish = GENERIC_ACTION(action).start +
430             GENERIC_ACTION(action).max_duration;
431       else
432         min_finish = GENERIC_ACTION(action).finish;
433     } else {
434       /* put the max duration time on heap */
435       if (GENERIC_ACTION(action).max_duration != NO_MAX_DURATION)
436         min_finish =
437             (GENERIC_ACTION(action).start +
438              GENERIC_ACTION(action).max_duration);
439     }
440     /* add in action heap */
441     XBT_DEBUG("action(%p) index %d", action, action->index_heap);
442     if (action->index_heap >= 0) {
443       surf_action_cpu_ti_t heap_act =
444           xbt_heap_remove(cpu_ti_action_heap, action->index_heap);
445       if (heap_act != action)
446         DIE_IMPOSSIBLE;
447     }
448     if (min_finish != NO_MAX_DURATION)
449       xbt_heap_push(cpu_ti_action_heap, action, min_finish);
450
451     XBT_DEBUG
452         ("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f",
453          cpu->generic_resource.name, action, GENERIC_ACTION(action).start,
454          GENERIC_ACTION(action).finish,
455          GENERIC_ACTION(action).max_duration);
456   }
457 /* remove from modified cpu */
458   xbt_swag_remove(cpu, cpu_ti_modified_cpu);
459 #undef GENERIC_ACTION
460 }
461
462 static double cpu_ti_share_resources(double now)
463 {
464   cpu_ti_t cpu, cpu_next;
465   double min_action_duration = -1;
466
467 /* iterates over modified cpus to update share resources */
468   xbt_swag_foreach_safe(cpu, cpu_next, cpu_ti_modified_cpu) {
469     cpu_ti_update_action_finish_date(cpu, now);
470   }
471 /* get the min next event if heap not empty */
472   if (xbt_heap_size(cpu_ti_action_heap) > 0)
473     min_action_duration = xbt_heap_maxkey(cpu_ti_action_heap) - now;
474
475   XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
476
477   return min_action_duration;
478 }
479
480 static void cpu_ti_update_actions_state(double now, double delta)
481 {
482 #define GENERIC_ACTION(action) action->generic_action
483   surf_action_cpu_ti_t action;
484   while ((xbt_heap_size(cpu_ti_action_heap) > 0)
485          && (xbt_heap_maxkey(cpu_ti_action_heap) <= now)) {
486     action = xbt_heap_pop(cpu_ti_action_heap);
487     XBT_DEBUG("Action %p: finish", action);
488     GENERIC_ACTION(action).finish = surf_get_clock();
489     /* set the remains to 0 due to precision problems when updating the remaining amount */
490     GENERIC_ACTION(action).remains = 0;
491     cpu_ti_action_state_set((surf_action_t) action, SURF_ACTION_DONE);
492     /* update remaining amount of all actions */
493     cpu_ti_update_remaining_amount(surf_cpu_resource_priv(action->cpu), surf_get_clock());
494   }
495 #undef GENERIC_ACTION
496 }
497
498 static void cpu_ti_update_resource_state(void *id,
499                                          tmgr_trace_event_t event_type,
500                                          double value, double date)
501 {
502   cpu_ti_t cpu = id;
503   surf_action_cpu_ti_t action;
504
505   if (event_type == cpu->power_event) {
506     tmgr_trace_t power_trace;
507     surf_cpu_ti_tgmr_t trace;
508     s_tmgr_event_t val;
509
510     XBT_DEBUG("Finish trace date: %f value %f date %f", surf_get_clock(),
511            value, date);
512     /* update remaining of actions and put in modified cpu swag */
513     cpu_ti_update_remaining_amount(cpu, date);
514     xbt_swag_insert(cpu, cpu_ti_modified_cpu);
515
516     power_trace = cpu->avail_trace->power_trace;
517     xbt_dynar_get_cpy(power_trace->s_list.event_list,
518                       xbt_dynar_length(power_trace->s_list.event_list) - 1, &val);
519     /* free old trace */
520     surf_cpu_ti_free_tmgr(cpu->avail_trace);
521     cpu->power_scale = val.value;
522
523     trace = xbt_new0(s_surf_cpu_ti_tgmr_t, 1);
524     trace->type = TRACE_FIXED;
525     trace->value = val.value;
526     XBT_DEBUG("value %f", val.value);
527
528     cpu->avail_trace = trace;
529
530     if (tmgr_trace_event_free(event_type))
531       cpu->power_event = NULL;
532
533   } else if (event_type == cpu->state_event) {
534     if (value > 0) {
535       if(cpu->state_current == SURF_RESOURCE_OFF)
536         xbt_dynar_push_as(host_that_restart, char*, (cpu->generic_resource.name));
537       cpu->state_current = SURF_RESOURCE_ON;
538     } else {
539       cpu->state_current = SURF_RESOURCE_OFF;
540
541       /* put all action running on cpu to failed */
542       xbt_swag_foreach(action, cpu->action_set) {
543         if (surf_action_state_get((surf_action_t) action) ==
544             SURF_ACTION_RUNNING
545             || surf_action_state_get((surf_action_t) action) ==
546             SURF_ACTION_READY
547             || surf_action_state_get((surf_action_t) action) ==
548             SURF_ACTION_NOT_IN_THE_SYSTEM) {
549           action->generic_action.finish = date;
550           cpu_ti_action_state_set((surf_action_t) action,
551                                   SURF_ACTION_FAILED);
552           if (action->index_heap >= 0) {
553             surf_action_cpu_ti_t heap_act =
554                 xbt_heap_remove(cpu_ti_action_heap, action->index_heap);
555             if (heap_act != action)
556               DIE_IMPOSSIBLE;
557           }
558         }
559       }
560     }
561     if (tmgr_trace_event_free(event_type))
562       cpu->state_event = NULL;
563   } else {
564     XBT_CRITICAL("Unknown event ! \n");
565     xbt_abort();
566   }
567
568   return;
569 }
570
571 static surf_action_t cpu_ti_execute(void *cpu, double size)
572 {
573   surf_action_cpu_ti_t action = NULL;
574   cpu_ti_t CPU = surf_cpu_resource_priv(cpu);
575
576   XBT_IN("(%s,%g)", surf_resource_name(CPU), size);
577   action =
578       surf_action_new(sizeof(s_surf_action_cpu_ti_t), size, surf_cpu_model,
579                       CPU->state_current != SURF_RESOURCE_ON);
580   action->cpu = cpu;
581   action->index_heap = -1;
582
583   xbt_swag_insert(CPU, cpu_ti_modified_cpu);
584
585   xbt_swag_insert(action, CPU->action_set);
586
587   action->suspended = 0;        /* Should be useless because of the
588                                    calloc but it seems to help valgrind... */
589
590   XBT_OUT();
591   return (surf_action_t) action;
592 }
593
594 static void cpu_ti_action_update_index_heap(void *action, int i)
595 {
596   ((surf_action_cpu_ti_t) action)->index_heap = i;
597 }
598
599 static surf_action_t cpu_ti_action_sleep(void *cpu, double duration)
600 {
601   surf_action_cpu_ti_t action = NULL;
602
603   if (duration > 0)
604     duration = MAX(duration, MAXMIN_PRECISION);
605
606   XBT_IN("(%s,%g)", surf_resource_name(surf_cpu_resource_priv(cpu)), duration);
607   action = (surf_action_cpu_ti_t) cpu_ti_execute(cpu, 1.0);
608   action->generic_action.max_duration = duration;
609   action->suspended = 2;
610   if (duration == NO_MAX_DURATION) {
611     /* Move to the *end* of the corresponding action set. This convention
612        is used to speed up update_resource_state  */
613     xbt_swag_remove(action, ((surf_action_t) action)->state_set);
614     ((surf_action_t) action)->state_set =
615         cpu_ti_running_action_set_that_does_not_need_being_checked;
616     xbt_swag_insert(action, ((surf_action_t) action)->state_set);
617   }
618   XBT_OUT();
619   return (surf_action_t) action;
620 }
621
622 static void cpu_ti_action_suspend(surf_action_t action)
623 {
624   XBT_IN("(%p)", action);
625   if (((surf_action_cpu_ti_t) action)->suspended != 2) {
626     ((surf_action_cpu_ti_t) action)->suspended = 1;
627     xbt_heap_remove(cpu_ti_action_heap,
628                     ((surf_action_cpu_ti_t) action)->index_heap);
629     xbt_swag_insert(surf_cpu_resource_priv(ACTION_GET_CPU(action)), cpu_ti_modified_cpu);
630   }
631   XBT_OUT();
632 }
633
634 static void cpu_ti_action_resume(surf_action_t action)
635 {
636   XBT_IN("(%p)", action);
637   if (((surf_action_cpu_ti_t) action)->suspended != 2) {
638     ((surf_action_cpu_ti_t) action)->suspended = 0;
639     xbt_swag_insert(surf_cpu_resource_priv(ACTION_GET_CPU(action)), cpu_ti_modified_cpu);
640   }
641   XBT_OUT();
642 }
643
644 static int cpu_ti_action_is_suspended(surf_action_t action)
645 {
646   return (((surf_action_cpu_ti_t) action)->suspended == 1);
647 }
648
649 static void cpu_ti_action_set_max_duration(surf_action_t action,
650                                            double duration)
651 {
652   surf_action_cpu_ti_t ACT = (surf_action_cpu_ti_t) action;
653   double min_finish;
654
655   XBT_IN("(%p,%g)", action, duration);
656
657   action->max_duration = duration;
658
659   if (duration >= 0)
660     min_finish =
661         (action->start + action->max_duration) <
662         action->finish ? (action->start +
663                           action->max_duration) : action->finish;
664   else
665     min_finish = action->finish;
666
667 /* add in action heap */
668   if (ACT->index_heap >= 0) {
669     surf_action_cpu_ti_t heap_act =
670         xbt_heap_remove(cpu_ti_action_heap, ACT->index_heap);
671     if (heap_act != ACT)
672       DIE_IMPOSSIBLE;
673   }
674   xbt_heap_push(cpu_ti_action_heap, ACT, min_finish);
675
676   XBT_OUT();
677 }
678
679 static void cpu_ti_action_set_priority(surf_action_t action,
680                                        double priority)
681 {
682   XBT_IN("(%p,%g)", action, priority);
683   action->priority = priority;
684   xbt_swag_insert(surf_cpu_resource_priv(ACTION_GET_CPU(action)), cpu_ti_modified_cpu);
685   XBT_OUT();
686 }
687
688 static double cpu_ti_action_get_remains(surf_action_t action)
689 {
690   XBT_IN("(%p)", action);
691   cpu_ti_update_remaining_amount((cpu_ti_t)
692                                  ((surf_action_cpu_ti_t) action)->cpu,
693                                  surf_get_clock());
694   XBT_OUT();
695   return action->remains;
696 }
697
698 static e_surf_resource_state_t cpu_ti_get_state(void *cpu)
699 {
700   return ((cpu_ti_t)surf_cpu_resource_priv(cpu))->state_current;
701 }
702
703 static double cpu_ti_get_speed(void *cpu, double load)
704 {
705   return load * ((cpu_ti_t)surf_cpu_resource_priv(cpu))->power_peak;
706 }
707
708 /**
709 * \brief Auxiliary function to update the CPU power scale.
710 *
711 *  This function uses the trace structure to return the power scale at the determined time a.
712 * \param trace    Trace structure to search the updated power scale
713 * \param a        Time
714 * \return CPU power scale
715 */
716 static double surf_cpu_ti_get_power_scale(surf_cpu_ti_tgmr_t trace,
717                                           double a)
718 {
719   double reduced_a;
720   int point;
721   s_tmgr_event_t val;
722
723   reduced_a = a - floor(a / trace->last_time) * trace->last_time;
724   point =
725       surf_cpu_ti_binary_search(trace->trace->time_points, reduced_a, 0,
726                                 trace->trace->nb_points - 1);
727   xbt_dynar_get_cpy(trace->power_trace->s_list.event_list, point, &val);
728   return val.value;
729 }
730
731 static double cpu_ti_get_available_speed(void *cpu)
732 {
733   cpu_ti_t CPU = surf_cpu_resource_priv(cpu);
734   CPU->power_scale =
735       surf_cpu_ti_get_power_scale(CPU->avail_trace, surf_get_clock());
736 /* number between 0 and 1 */
737   return CPU->power_scale;
738 }
739
740 static void cpu_ti_finalize(void)
741 {
742   void **cpu;
743   xbt_lib_cursor_t cursor;
744   char *key;
745
746   xbt_lib_foreach(host_lib, cursor, key, cpu){
747     if(cpu[SURF_CPU_LEVEL])
748     {
749         cpu_ti_t CPU = cpu[SURF_CPU_LEVEL];
750         xbt_swag_free(CPU->action_set);
751         surf_cpu_ti_free_tmgr(CPU->avail_trace);
752     }
753   }
754
755   surf_model_exit(surf_cpu_model);
756   surf_cpu_model = NULL;
757
758   xbt_swag_free
759       (cpu_ti_running_action_set_that_does_not_need_being_checked);
760   xbt_swag_free(cpu_ti_modified_cpu);
761   cpu_ti_running_action_set_that_does_not_need_being_checked = NULL;
762   xbt_heap_free(cpu_ti_action_heap);
763 }
764
765 static void surf_cpu_ti_model_init_internal(void)
766 {
767   s_surf_action_t action;
768   s_cpu_ti_t cpu;
769
770   surf_cpu_model = surf_model_init();
771
772   cpu_ti_running_action_set_that_does_not_need_being_checked =
773       xbt_swag_new(xbt_swag_offset(action, state_hookup));
774
775   cpu_ti_modified_cpu =
776       xbt_swag_new(xbt_swag_offset(cpu, modified_cpu_hookup));
777
778   surf_cpu_model->name = "cpu_ti";
779
780   surf_cpu_model->action_unref = cpu_ti_action_unref;
781   surf_cpu_model->action_cancel = cpu_ti_action_cancel;
782   surf_cpu_model->action_state_set = cpu_ti_action_state_set;
783
784   surf_cpu_model->model_private->resource_used = cpu_ti_resource_used;
785   surf_cpu_model->model_private->share_resources = cpu_ti_share_resources;
786   surf_cpu_model->model_private->update_actions_state =
787       cpu_ti_update_actions_state;
788   surf_cpu_model->model_private->update_resource_state =
789       cpu_ti_update_resource_state;
790   surf_cpu_model->model_private->finalize = cpu_ti_finalize;
791
792   surf_cpu_model->suspend = cpu_ti_action_suspend;
793   surf_cpu_model->resume = cpu_ti_action_resume;
794   surf_cpu_model->is_suspended = cpu_ti_action_is_suspended;
795   surf_cpu_model->set_max_duration = cpu_ti_action_set_max_duration;
796   surf_cpu_model->set_priority = cpu_ti_action_set_priority;
797   surf_cpu_model->get_remains = cpu_ti_action_get_remains;
798
799   surf_cpu_model->extension.cpu.execute = cpu_ti_execute;
800   surf_cpu_model->extension.cpu.sleep = cpu_ti_action_sleep;
801
802   surf_cpu_model->extension.cpu.get_state = cpu_ti_get_state;
803   surf_cpu_model->extension.cpu.get_speed = cpu_ti_get_speed;
804   surf_cpu_model->extension.cpu.get_available_speed =
805       cpu_ti_get_available_speed;
806   surf_cpu_model->extension.cpu.add_traces = add_traces_cpu_ti;
807
808   cpu_ti_action_heap = xbt_heap_new(8, NULL);
809   xbt_heap_set_update_callback(cpu_ti_action_heap,
810                                cpu_ti_action_update_index_heap);
811
812 }
813
814 void surf_cpu_model_init_ti()
815 {
816   xbt_assert(!surf_cpu_model,"CPU model already initialized. This should not happen.");
817   surf_cpu_ti_model_init_internal();
818   cpu_ti_define_callbacks();
819   xbt_dynar_push(model_list, &surf_cpu_model);
820 }
821
822
823 /**
824 * \brief Integrate trace
825 *
826 * Wrapper around surf_cpu_integrate_trace_simple() to get
827 * the cyclic effect.
828 *
829 * \param trace Trace structure.
830 * \param a      Begin of interval
831 * \param b      End of interval
832 * \return the integrate value. -1 if an error occurs.
833 */
834 static double surf_cpu_ti_integrate_trace(surf_cpu_ti_tgmr_t trace,
835                                           double a, double b)
836 {
837   double first_chunk;
838   double middle_chunk;
839   double last_chunk;
840   int a_index, b_index;
841
842   if ((a < 0.0) || (a > b)) {
843     XBT_CRITICAL
844         ("Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative computation amount. Check your code.",
845          a, b);
846     xbt_abort();
847   }
848   if (a == b)
849     return 0.0;
850
851   if (trace->type == TRACE_FIXED) {
852     return ((b - a) * trace->value);
853   }
854
855   if (ceil(a / trace->last_time) == a / trace->last_time)
856     a_index = 1 + (int) (ceil(a / trace->last_time));
857   else
858     a_index = (int) (ceil(a / trace->last_time));
859
860   b_index = (int) (floor(b / trace->last_time));
861
862   if (a_index > b_index) {      /* Same chunk */
863     return surf_cpu_ti_integrate_trace_simple(trace->trace,
864                                               a - (a_index -
865                                                    1) * trace->last_time,
866                                               b -
867                                               (b_index) *
868                                               trace->last_time);
869   }
870
871   first_chunk = surf_cpu_ti_integrate_trace_simple(trace->trace,
872                                                    a - (a_index -
873                                                         1) *
874                                                    trace->last_time,
875                                                    trace->last_time);
876   middle_chunk = (b_index - a_index) * trace->total;
877   last_chunk = surf_cpu_ti_integrate_trace_simple(trace->trace,
878                                                   0.0,
879                                                   b -
880                                                   (b_index) *
881                                                   trace->last_time);
882
883   XBT_DEBUG("first_chunk=%.2f  middle_chunk=%.2f  last_chunk=%.2f\n",
884          first_chunk, middle_chunk, last_chunk);
885
886   return (first_chunk + middle_chunk + last_chunk);
887 }
888
889 /**
890  * \brief Auxiliary function to calculate the integral between a and b.
891  *     It simply calculates the integral at point a and b and returns the difference 
892  *   between them.
893  * \param trace    Trace structure
894  * \param a        Initial point
895  * \param b  Final point
896  * \return  Integral
897 */
898 static double surf_cpu_ti_integrate_trace_simple(surf_cpu_ti_trace_t trace,
899                                                  double a, double b)
900 {
901   return surf_cpu_ti_integrate_trace_simple_point(trace,
902                                                   b) -
903       surf_cpu_ti_integrate_trace_simple_point(trace, a);
904 }
905
906 /**
907  * \brief Auxiliary function to calculate the integral at point a.
908  * \param trace    Trace structure
909  * \param a        point
910  * \return  Integral
911 */
912 static double surf_cpu_ti_integrate_trace_simple_point(surf_cpu_ti_trace_t
913                                                        trace, double a)
914 {
915   double integral = 0;
916   int ind;
917   double a_aux = a;
918   ind =
919       surf_cpu_ti_binary_search(trace->time_points, a, 0,
920                                 trace->nb_points - 1);
921   integral += trace->integral[ind];
922   XBT_DEBUG
923       ("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f",
924        a, ind, integral, trace->integral[ind + 1], trace->integral[ind],
925        trace->time_points[ind + 1], trace->time_points[ind]);
926   double_update(&a_aux, trace->time_points[ind]);
927   if (a_aux > 0)
928     integral +=
929         ((trace->integral[ind + 1] -
930           trace->integral[ind]) / (trace->time_points[ind + 1] -
931                                    trace->time_points[ind])) * (a -
932                                                                 trace->
933                                                                 time_points
934                                                                 [ind]);
935   XBT_DEBUG("Integral a %f = %f", a, integral);
936
937   return integral;
938 }
939
940 /**
941 * \brief Calculate the time needed to execute "amount" on cpu.
942 *
943 * Here, amount can span multiple trace periods
944 *
945 * \param trace   CPU trace structure
946 * \param a        Initial time
947 * \param amount  Amount to be executed
948 * \return  End time
949 */
950 static double surf_cpu_ti_solve_trace(surf_cpu_ti_tgmr_t trace, double a,
951                                       double amount)
952 {
953   int quotient;
954   double reduced_b;
955   double reduced_amount;
956   double reduced_a;
957   double b;
958
959 /* Fix very small negative numbers */
960   if ((a < 0.0) && (a > -EPSILON)) {
961     a = 0.0;
962   }
963   if ((amount < 0.0) && (amount > -EPSILON)) {
964     amount = 0.0;
965   }
966
967 /* Sanity checks */
968   if ((a < 0.0) || (amount < 0.0)) {
969     XBT_CRITICAL
970         ("Error, invalid parameters [a = %.2f, amount = %.2f]. You probably have a task executing with negative computation amount. Check your code.",
971          a, amount);
972     xbt_abort();
973   }
974
975 /* At this point, a and amount are positive */
976
977   if (amount < EPSILON)
978     return a;
979
980 /* Is the trace fixed ? */
981   if (trace->type == TRACE_FIXED) {
982     return (a + (amount / trace->value));
983   }
984
985   XBT_DEBUG("amount %f total %f", amount, trace->total);
986 /* Reduce the problem to one where amount <= trace_total */
987   quotient = (int) (floor(amount / trace->total));
988   reduced_amount = (trace->total) * ((amount / trace->total) -
989                                      floor(amount / trace->total));
990   reduced_a = a - (trace->last_time) * (int) (floor(a / trace->last_time));
991
992   XBT_DEBUG("Quotient: %d reduced_amount: %f reduced_a: %f", quotient,
993          reduced_amount, reduced_a);
994
995 /* Now solve for new_amount which is <= trace_total */
996 /*
997    fprintf(stderr,"reduced_a = %.2f\n",reduced_a);
998    fprintf(stderr,"reduced_amount = %.2f\n",reduced_amount);
999  */
1000   reduced_b =
1001       surf_cpu_ti_solve_trace_somewhat_simple(trace, reduced_a,
1002                                               reduced_amount);
1003
1004 /* Re-map to the original b and amount */
1005   b = (trace->last_time) * (int) (floor(a / trace->last_time)) +
1006       (quotient * trace->last_time) + reduced_b;
1007   return b;
1008 }
1009
1010 /**
1011 * \brief Auxiliary function to solve integral
1012 *
1013 * Here, amount is <= trace->total
1014 * and a <=trace->last_time
1015 *
1016 */
1017 static double surf_cpu_ti_solve_trace_somewhat_simple(surf_cpu_ti_tgmr_t
1018                                                       trace, double a,
1019                                                       double amount)
1020 {
1021   double amount_till_end;
1022   double b;
1023
1024   XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", a, amount);
1025   amount_till_end =
1026       surf_cpu_ti_integrate_trace(trace, a, trace->last_time);
1027 /*
1028    fprintf(stderr,"amount_till_end=%.2f\n",amount_till_end);
1029  */
1030
1031   if (amount_till_end > amount) {
1032     b = surf_cpu_ti_solve_trace_simple(trace->trace, a, amount);
1033   } else {
1034     b = trace->last_time +
1035         surf_cpu_ti_solve_trace_simple(trace->trace, 0.0,
1036                                        amount - amount_till_end);
1037   }
1038   return b;
1039 }
1040
1041 /**
1042  * \brief Auxiliary function to solve integral.
1043  *  It returns the date when the requested amount of flops is available
1044  * \param trace    Trace structure
1045  * \param a        Initial point
1046  * \param amount  Amount of flops 
1047  * \return The date when amount is available.
1048 */
1049 static double surf_cpu_ti_solve_trace_simple(surf_cpu_ti_trace_t trace,
1050                                              double a, double amount)
1051 {
1052   double integral_a;
1053   int ind;
1054   double time;
1055   integral_a = surf_cpu_ti_integrate_trace_simple_point(trace, a);
1056   ind =
1057       surf_cpu_ti_binary_search(trace->integral, integral_a + amount, 0,
1058                                 trace->nb_points - 1);
1059   time = trace->time_points[ind];
1060   time +=
1061       (integral_a + amount -
1062        trace->integral[ind]) / ((trace->integral[ind + 1] -
1063                                  trace->integral[ind]) /
1064                                 (trace->time_points[ind + 1] -
1065                                  trace->time_points[ind]));
1066
1067   return time;
1068 }
1069
1070 /**
1071  * \brief Binary search in array.
1072  *  It returns the first point of the interval in which "a" is. 
1073  * \param array    Array
1074  * \param a        Value to search
1075  * \param low     Low bound to search in array
1076  * \param high    Upper bound to search in array
1077  * \return Index of point
1078 */
1079 static int surf_cpu_ti_binary_search(double *array, double a, int low,
1080                                      int high)
1081 {
1082   xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than"
1083       " high (%d)", low, high);
1084
1085   int mid;
1086   do {
1087     mid = low + (high - low) / 2;
1088     XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid,
1089         array[mid]);
1090
1091     if (array[mid] > a)
1092       high = mid;
1093     else
1094       low = mid;
1095   }
1096   while (low < high - 1);
1097
1098   return low;
1099 }