Logo AND Algorithmique Numérique Distribuée

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