Logo AND Algorithmique Numérique Distribuée

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