Logo AND Algorithmique Numérique Distribuée

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