Logo AND Algorithmique Numérique Distribuée

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