Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Change test to program ending to avoid infinite loop when using traces with periodici...
[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 #include "surf_private.h"
10 #include "trace_mgr_private.h"
11 #include "cpu_ti_private.h"
12 #include "xbt/heap.h"
13
14
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf,
16                                 "Logging specific to the SURF CPU TRACE INTEGRATION module");
17
18
19 static xbt_swag_t running_action_set_that_does_not_need_being_checked = NULL;
20 static xbt_swag_t modified_cpu = NULL;
21 static xbt_heap_t action_heap;
22
23 /* prototypes of new trace functions */
24 static double surf_cpu_integrate_trace(surf_cpu_ti_tgmr_t trace, double a,
25                                        double b);
26 static double surf_cpu_integrate_trace_simple(surf_cpu_ti_tgmr_t trace,
27                                               double a, double b);
28
29
30 static double surf_cpu_solve_trace(surf_cpu_ti_tgmr_t trace, double a,
31                                    double amount);
32 static double surf_cpu_solve_trace_somewhat_simple(surf_cpu_ti_tgmr_t trace,
33                                                    double a, double amount);
34 static double surf_cpu_solve_trace_simple(surf_cpu_ti_tgmr_t trace, double a,
35                                           double amount);
36
37 static void surf_cpu_free_trace(surf_cpu_ti_tgmr_t trace);
38 static void surf_cpu_free_time_series(surf_cpu_ti_timeSeries_t timeSeries);
39 /* end prototypes */
40
41 static void surf_cpu_free_time_series(surf_cpu_ti_timeSeries_t timeSeries)
42 {
43   xbt_free(timeSeries->values);
44   xbt_free(timeSeries);
45 }
46
47 static void surf_cpu_free_trace(surf_cpu_ti_tgmr_t trace)
48 {
49   int i;
50
51   for (i = 0; i < trace->nb_levels; i++)
52     surf_cpu_free_time_series(trace->levels[i]);
53
54   xbt_free(trace->levels);
55   xbt_free(trace);
56 }
57
58 static surf_cpu_ti_timeSeries_t surf_cpu_ti_time_series_new(tmgr_trace_t
59                                                             power_trace,
60                                                             double spacing)
61 {
62   surf_cpu_ti_timeSeries_t series;
63   double time = 0.0, value = 0.0, sum_delta = 0.0;
64   double previous_time = 0.0;
65   double old_time = 0.0;
66   int event_lost = 0;
67   unsigned int cpt;
68
69   s_tmgr_event_t val;
70   series = xbt_new0(s_surf_cpu_ti_timeSeries_t, 1);
71   series->spacing = spacing;
72
73   /* FIXME: it doesn't work with traces with only one point and periodicity = 0
74    * if the trace is always cyclic and periodicity must be > 0 it works */
75   xbt_dynar_foreach(power_trace->event_list, cpt, val) {
76     /* delta = the next trace event
77      * value = state until next event */
78     time += val.delta;
79
80     /* ignore events until next spacing */
81     if (time < (series->nb_points + 1) * spacing) {
82       value += val.value * val.delta;
83       sum_delta += val.delta;
84       old_time = time;
85       event_lost = 1;
86       continue;
87     }
88
89     /* update value and sum_delta with the space between last point in trace(old_time) and next spacing */
90     value += val.value * ((series->nb_points + 1) * spacing - old_time);
91     sum_delta += ((series->nb_points + 1) * spacing - old_time);
92     /* calcule the value to next spacing */
93     value /= sum_delta;
94
95     while (previous_time + spacing <= time) {
96       series->values = xbt_realloc(series->values,
97                                    (series->nb_points + 1) * sizeof(double));
98       /* update first spacing with mean of points
99        * others with the right value */
100       series->values[(series->nb_points)++] = event_lost ? value : val.value;
101       event_lost = 0;
102       previous_time += spacing;
103     }
104     /* update value and sum_delta, interval: [time, next spacing] */
105     value = (previous_time + spacing - time) * val.value;
106     sum_delta = (previous_time + spacing - time);
107     old_time = time;
108
109   }
110   /* last spacing */
111   if (old_time < (series->nb_points) * spacing) {
112     value /= sum_delta;
113     series->values = xbt_realloc(series->values,
114                                  (series->nb_points + 1) * sizeof(double));
115     series->values[(series->nb_points)++] = value;
116     previous_time += spacing;
117   }
118   return series;
119 }
120
121 /**
122  * \brief Create new levels of points.
123  *
124  * This function assumes that the input series is
125  * evenly spaces, starting at time 0. That is the sort
126  * of series produced by surf_cpu_ti_time_series_new()
127  *
128  * \param       original        Original timeSeries structure
129  * \param       factor          New factor to spacing
130  * \return                                      New timeSeries structure with spacing*factor
131  */
132 static surf_cpu_ti_timeSeries_t
133 surf_cpu_ti_time_series_coarsen(surf_cpu_ti_timeSeries_t original, int factor)
134 {
135   surf_cpu_ti_timeSeries_t series;
136   int j, i = 0;
137   double dfactor = (double) (factor);
138   double ave;
139
140   if (original->nb_points <= factor) {
141     DEBUG0("Warning: Not enough data points to coarsen time series");
142     return NULL;
143   }
144
145   series = xbt_new0(s_surf_cpu_ti_timeSeries_t, 1);
146   series->spacing = (original->spacing) * dfactor;
147
148   while (i + factor <= original->nb_points) {
149     /* Averaging */
150     ave = 0.0;
151     for (j = i; j < i + factor; j++) {
152       ave += original->values[j];
153     }
154     ave /= dfactor;
155     /* Updating */
156     series->values = xbt_realloc(series->values,
157                                  (series->nb_points + 1) * sizeof(double));
158     series->values[(series->nb_points)++] = ave;
159     i += factor;
160   }
161
162   return series;
163 }
164
165 /**
166  * \brief Create a new integration trace from a tmgr_trace_t
167  *
168  * \param       power_trace             CPU availability trace
169  * \param       value                                   Percentage of CPU power disponible (usefull to fixed tracing)
170  * \param       spacing                         Initial spacing
171  * \return      Integration trace structure
172  */
173 static surf_cpu_ti_tgmr_t cpu_ti_parse_trace(tmgr_trace_t power_trace,
174                                              double value)
175 {
176   surf_cpu_ti_tgmr_t trace;
177   surf_cpu_ti_timeSeries_t series;
178   int i;
179   trace = xbt_new0(s_surf_cpu_ti_tgmr_t, 1);
180
181   /* no availability file, fixed trace */
182   if (!power_trace) {
183     trace->type = TRACE_FIXED;
184     trace->value = value;
185     DEBUG1("No availabily trace. Constant value = %lf", value);
186     return trace;
187   }
188
189   DEBUG2("Value %lf, Spacing %lf", value, power_trace->timestep);
190   series = surf_cpu_ti_time_series_new(power_trace, power_trace->timestep);
191   if (!series)
192     return NULL;
193
194   trace->type = TRACE_DYNAMIC;
195
196   trace->levels = xbt_new0(surf_cpu_ti_timeSeries_t, 1);
197   trace->levels[(trace->nb_levels)++] = series;
198
199   /* Do the coarsening with some arbitrary factors */
200   for (i = 1; i < TRACE_NB_LEVELS; i++) {
201     series = surf_cpu_ti_time_series_coarsen(trace->levels[i - 1], 4 * i);
202
203     if (series) {               /* If coarsening was possible, add it */
204       trace->levels = xbt_realloc(trace->levels,
205                                   (trace->nb_levels +
206                                    1) * sizeof(s_surf_cpu_ti_timeSeries_t));
207       trace->levels[(trace->nb_levels)++] = series;
208     } else {                    /* otherwise stop */
209       break;
210     }
211   }
212
213   /* calcul of initial integrate */
214   trace->last_time =
215     power_trace->timestep * ((double) (trace->levels[0]->nb_points));
216   trace->total = surf_cpu_integrate_trace(trace, 0.0, trace->last_time);
217
218   DEBUG2("Total integral %lf, last_time %lf", trace->total, trace->last_time);
219
220   return trace;
221 }
222
223
224 static cpu_ti_t cpu_new(char *name, double power_peak,
225                         double power_scale,
226                         tmgr_trace_t power_trace,
227                         e_surf_resource_state_t state_initial,
228                         tmgr_trace_t state_trace, xbt_dict_t cpu_properties)
229 {
230   cpu_ti_t cpu = xbt_new0(s_cpu_ti_t, 1);
231   s_surf_action_cpu_ti_t ti_action;
232   xbt_assert1(!surf_model_resource_by_name(surf_cpu_model, name),
233               "Host '%s' declared several times in the platform file", name);
234   cpu->action_set = xbt_swag_new(xbt_swag_offset(ti_action, cpu_list_hookup));
235   cpu->generic_resource.model = surf_cpu_model;
236   cpu->generic_resource.name = name;
237   cpu->generic_resource.properties = cpu_properties;
238   cpu->power_peak = power_peak;
239   xbt_assert0(cpu->power_peak > 0, "Power has to be >0");
240   DEBUG1("power scale %lf", power_scale);
241   cpu->power_scale = power_scale;
242   cpu->avail_trace = cpu_ti_parse_trace(power_trace, power_scale);
243   cpu->state_current = state_initial;
244   if (state_trace)
245     cpu->state_event =
246       tmgr_history_add_trace(history, state_trace, 0.0, 0, cpu);
247
248   xbt_dict_set(surf_model_resource_set(surf_cpu_model), name, cpu,
249                surf_resource_free);
250
251   return cpu;
252 }
253
254
255 static void parse_cpu_init(void)
256 {
257   double power_peak = 0.0;
258   double power_scale = 0.0;
259   tmgr_trace_t power_trace = NULL;
260   e_surf_resource_state_t state_initial = SURF_RESOURCE_OFF;
261   tmgr_trace_t state_trace = NULL;
262
263   power_peak = get_cpu_power(A_surfxml_host_power);
264   surf_parse_get_double(&power_scale, A_surfxml_host_availability);
265   power_trace = tmgr_trace_new(A_surfxml_host_availability_file);
266
267   xbt_assert0((A_surfxml_host_state == A_surfxml_host_state_ON) ||
268               (A_surfxml_host_state == A_surfxml_host_state_OFF),
269               "Invalid state");
270   if (A_surfxml_host_state == A_surfxml_host_state_ON)
271     state_initial = SURF_RESOURCE_ON;
272   if (A_surfxml_host_state == A_surfxml_host_state_OFF)
273     state_initial = SURF_RESOURCE_OFF;
274   state_trace = tmgr_trace_new(A_surfxml_host_state_file);
275
276   current_property_set = xbt_dict_new();
277   cpu_new(xbt_strdup(A_surfxml_host_id), power_peak, power_scale,
278           power_trace, state_initial, state_trace, current_property_set);
279
280 }
281
282 static void add_traces_cpu(void)
283 {
284   xbt_dict_cursor_t cursor = NULL;
285   char *trace_name, *elm;
286
287   static int called = 0;
288
289   if (called)
290     return;
291   called = 1;
292
293   /* connect all traces relative to hosts */
294   xbt_dict_foreach(trace_connect_list_host_avail, cursor, trace_name, elm) {
295     tmgr_trace_t trace = xbt_dict_get_or_null(traces_set_list, trace_name);
296     cpu_ti_t cpu = surf_model_resource_by_name(surf_cpu_model, elm);
297
298     xbt_assert1(cpu, "Host %s undefined", elm);
299     xbt_assert1(trace, "Trace %s undefined", trace_name);
300
301     if (cpu->state_event) {
302       DEBUG1("Trace already configured for this CPU(%s), ignoring it", elm);
303       continue;
304     }
305     DEBUG2("Add state trace: %s to CPU(%s)", trace_name, elm);
306     cpu->state_event = tmgr_history_add_trace(history, trace, 0.0, 0, cpu);
307   }
308
309   xbt_dict_foreach(trace_connect_list_power, cursor, trace_name, elm) {
310     tmgr_trace_t trace = xbt_dict_get_or_null(traces_set_list, trace_name);
311     cpu_ti_t cpu = surf_model_resource_by_name(surf_cpu_model, elm);
312
313     xbt_assert1(cpu, "Host %s undefined", elm);
314     xbt_assert1(trace, "Trace %s undefined", trace_name);
315
316     DEBUG2("Add power trace: %s to CPU(%s)", trace_name, elm);
317     if (cpu->avail_trace)
318       surf_cpu_free_trace(cpu->avail_trace);
319
320     cpu->avail_trace = cpu_ti_parse_trace(trace, cpu->power_scale);
321   }
322 }
323
324 static void define_callbacks(const char *file)
325 {
326   surf_parse_reset_parser();
327   surfxml_add_callback(STag_surfxml_host_cb_list, parse_cpu_init);
328   surfxml_add_callback(ETag_surfxml_platform_cb_list, &add_traces_cpu);
329 }
330
331 static int resource_used(void *resource_id)
332 {
333   cpu_ti_t cpu = resource_id;
334   return xbt_swag_size(cpu->action_set);
335 }
336
337 static int action_unref(surf_action_t action)
338 {
339   action->refcount--;
340   if (!action->refcount) {
341     xbt_swag_remove(action, action->state_set);
342     /* remove from action_set */
343     xbt_swag_remove(action, ACTION_GET_CPU(action)->action_set);
344     /* remove from heap */
345     xbt_heap_remove(action_heap, ((surf_action_cpu_ti_t) action)->index_heap);
346     xbt_swag_insert(ACTION_GET_CPU(action), modified_cpu);
347     free(action);
348     return 1;
349   }
350   return 0;
351 }
352
353 static void action_cancel(surf_action_t action)
354 {
355   surf_action_state_set(action, SURF_ACTION_FAILED);
356   xbt_heap_remove(action_heap, ((surf_action_cpu_ti_t) action)->index_heap);
357   xbt_swag_insert(ACTION_GET_CPU(action), modified_cpu);
358   return;
359 }
360
361 static void cpu_action_state_set(surf_action_t action,
362                                  e_surf_action_state_t state)
363 {
364   surf_action_state_set(action, state);
365   xbt_swag_insert(ACTION_GET_CPU(action), modified_cpu);
366   return;
367 }
368
369 /**
370  * \brief Update the remaning amount of actions
371  *
372  * \param       cpu             Cpu on which the actions are running
373  * \param       now             Current time
374  */
375 static void cpu_update_remaining_amount(cpu_ti_t cpu, double now)
376 {
377 #define GENERIC_ACTION(action) action->generic_action
378   double area_total;
379   surf_action_cpu_ti_t action;
380
381   /* alrealdy updated */
382   if (cpu->last_update == now)
383     return;
384
385   /* calcule the surface */
386   area_total =
387     surf_cpu_integrate_trace(cpu->avail_trace, cpu->last_update,
388                              now) * cpu->power_peak;
389   DEBUG2("Flops total: %lf, Last update %lf", area_total, cpu->last_update);
390
391   xbt_swag_foreach(action, cpu->action_set) {
392     /* action not running, skip it */
393     if (GENERIC_ACTION(action).state_set !=
394         surf_cpu_model->states.running_action_set)
395       continue;
396
397     /* bogus priority, skip it */
398     if (GENERIC_ACTION(action).priority <= 0)
399       continue;
400
401     /* action suspended, skip it */
402     if (action->suspended != 0)
403       continue;
404
405     /* action don't need update */
406     if (GENERIC_ACTION(action).start >= now)
407       continue;
408
409     /* skip action that are finishing now */
410     if (GENERIC_ACTION(action).finish >= 0
411         && GENERIC_ACTION(action).finish <= now)
412       continue;
413
414     /* update remaining */
415     double_update(&(GENERIC_ACTION(action).remains),
416                   area_total / (cpu->sum_priority *
417                                 GENERIC_ACTION(action).priority));
418     DEBUG2("Update remaining action(%p) remaining %lf", action,
419            GENERIC_ACTION(action).remains);
420   }
421   cpu->last_update = now;
422 #undef GENERIC_ACTION
423 }
424
425 /**
426  * \brief Update the finish date of action if necessary
427  *
428  * \param       cpu             Cpu on which the actions are running
429  * \param       now             Current time
430  */
431 static void cpu_update_action_finish_date(cpu_ti_t cpu, double now)
432 {
433 #define GENERIC_ACTION(action) action->generic_action
434   surf_action_cpu_ti_t action;
435   double sum_priority = 0.0, total_area, min_finish = -1;
436
437   /* update remaning amount of actions */
438   cpu_update_remaining_amount(cpu, now);
439
440   xbt_swag_foreach(action, cpu->action_set) {
441     /* action not running, skip it */
442     if (GENERIC_ACTION(action).state_set !=
443         surf_cpu_model->states.running_action_set)
444       continue;
445
446     /* bogus priority, skip it */
447     if (GENERIC_ACTION(action).priority <= 0)
448       continue;
449
450     /* action suspended, skip it */
451     if (action->suspended != 0)
452       continue;
453
454     sum_priority += 1.0 / GENERIC_ACTION(action).priority;
455   }
456   cpu->sum_priority = sum_priority;
457
458   xbt_swag_foreach(action, cpu->action_set) {
459     /* action not running, skip it */
460     if (GENERIC_ACTION(action).state_set !=
461         surf_cpu_model->states.running_action_set)
462       continue;
463
464     /* verify if the action is really running on cpu */
465     if (action->suspended == 0 && GENERIC_ACTION(action).priority > 0) {
466       /* total area needed to finish the action. Used in trace integration */
467       total_area =
468         (GENERIC_ACTION(action).remains) * sum_priority *
469         GENERIC_ACTION(action).priority;
470
471       total_area /= cpu->power_peak;
472
473       GENERIC_ACTION(action).finish =
474         surf_cpu_solve_trace(cpu->avail_trace, now, total_area);
475       /* verify which event will happen before (max_duration or finish time) */
476       if ((GENERIC_ACTION(action).max_duration != NO_MAX_DURATION) &&
477           (GENERIC_ACTION(action).start +
478            GENERIC_ACTION(action).max_duration <
479            GENERIC_ACTION(action).finish))
480         min_finish = GENERIC_ACTION(action).start +
481           GENERIC_ACTION(action).max_duration;
482       else
483         min_finish = GENERIC_ACTION(action).finish;
484     } else {
485       /* put the max duration time on heap */
486       if (GENERIC_ACTION(action).max_duration != NO_MAX_DURATION)
487         min_finish =
488           (GENERIC_ACTION(action).start +
489            GENERIC_ACTION(action).max_duration);
490     }
491     /* add in action heap */
492     DEBUG2("action(%p) index %d", action, action->index_heap);
493     if (action->index_heap >= 0) {
494       surf_action_cpu_ti_t heap_act =
495         xbt_heap_remove(action_heap, action->index_heap);
496       if (heap_act != action)
497         DIE_IMPOSSIBLE;
498     }
499     if (min_finish != NO_MAX_DURATION)
500       xbt_heap_push(action_heap, action, min_finish);
501
502     DEBUG5
503       ("Update finish time: Cpu(%s) Action: %p, Start Time: %lf Finish Time: %lf Max duration %lf",
504        cpu->generic_resource.name, action, GENERIC_ACTION(action).start,
505        GENERIC_ACTION(action).finish, GENERIC_ACTION(action).max_duration);
506   }
507   /* remove from modified cpu */
508   xbt_swag_remove(cpu, modified_cpu);
509 #undef GENERIC_ACTION
510 }
511
512 static double share_resources(double now)
513 {
514   cpu_ti_t cpu, cpu_next;
515   double min_action_duration = -1;
516
517   /* iterates over modified cpus to update share resources */
518   xbt_swag_foreach_safe(cpu, cpu_next, modified_cpu) {
519     cpu_update_action_finish_date(cpu, now);
520   }
521   /* get the min next event if heap not empty */
522   if (xbt_heap_size(action_heap) > 0)
523     min_action_duration = xbt_heap_maxkey(action_heap) - now;
524
525   DEBUG1("Share resources, min next event date: %lf", min_action_duration);
526
527   return min_action_duration;
528 }
529
530 static void update_actions_state(double now, double delta)
531 {
532 #define GENERIC_ACTION(action) action->generic_action
533   surf_action_cpu_ti_t action;
534   while ((xbt_heap_size(action_heap) > 0)
535          && (xbt_heap_maxkey(action_heap) <= now)) {
536     DEBUG1("Action %p: finish", action);
537     action = xbt_heap_pop(action_heap);
538     GENERIC_ACTION(action).finish = surf_get_clock();
539     /* set the remains to 0 due to precision problems when updating the remaining amount */
540     GENERIC_ACTION(action).remains = 0;
541     cpu_action_state_set((surf_action_t) action, SURF_ACTION_DONE);
542     /* update remaining amout of all actions */
543     cpu_update_remaining_amount(action->cpu, surf_get_clock());
544   }
545 #undef GENERIC_ACTION
546 }
547
548 static void update_resource_state(void *id,
549                                   tmgr_trace_event_t event_type,
550                                   double value, double date)
551 {
552   cpu_ti_t cpu = id;
553   surf_action_cpu_ti_t action;
554   if (event_type == cpu->state_event) {
555     if (value > 0)
556       cpu->state_current = SURF_RESOURCE_ON;
557     else {
558       cpu->state_current = SURF_RESOURCE_OFF;
559
560       /* put all action running on cpu to failed */
561       xbt_swag_foreach(action, cpu->action_set) {
562         if (surf_action_state_get((surf_action_t) action) ==
563             SURF_ACTION_RUNNING
564             || surf_action_state_get((surf_action_t) action) ==
565             SURF_ACTION_READY
566             || surf_action_state_get((surf_action_t) action) ==
567             SURF_ACTION_NOT_IN_THE_SYSTEM) {
568           action->generic_action.finish = date;
569           cpu_action_state_set((surf_action_t) action, SURF_ACTION_FAILED);
570           if (action->index_heap >= 0) {
571             surf_action_cpu_ti_t heap_act =
572               xbt_heap_remove(action_heap, action->index_heap);
573             if (heap_act != action)
574               DIE_IMPOSSIBLE;
575           }
576         }
577       }
578     }
579     if (tmgr_trace_event_free(event_type))
580       cpu->state_event = NULL;
581   } else {
582     CRITICAL0("Unknown event ! \n");
583     xbt_abort();
584   }
585
586   return;
587 }
588
589 static surf_action_t execute(void *cpu, double size)
590 {
591   surf_action_cpu_ti_t action = NULL;
592   cpu_ti_t CPU = cpu;
593
594   XBT_IN2("(%s,%g)", surf_resource_name(CPU), size);
595   action =
596     surf_action_new(sizeof(s_surf_action_cpu_ti_t), size, surf_cpu_model,
597                     CPU->state_current != SURF_RESOURCE_ON);
598   action->cpu = cpu;
599   action->index_heap = -1;
600
601   xbt_swag_insert(CPU, modified_cpu);
602
603   xbt_swag_insert(action, CPU->action_set);
604
605   action->suspended = 0;        /* Should be useless because of the
606                                    calloc but it seems to help valgrind... */
607
608   XBT_OUT;
609   return (surf_action_t) action;
610 }
611
612 static void action_update_index_heap(void *action, int i)
613 {
614   ((surf_action_cpu_ti_t) action)->index_heap = i;
615 }
616
617 static surf_action_t action_sleep(void *cpu, double duration)
618 {
619   surf_action_cpu_ti_t action = NULL;
620
621   if (duration > 0)
622     duration = MAX(duration, MAXMIN_PRECISION);
623
624   XBT_IN2("(%s,%g)", surf_resource_name(cpu), duration);
625   action = (surf_action_cpu_ti_t) execute(cpu, 1.0);
626   action->generic_action.max_duration = duration;
627   action->suspended = 2;
628   if (duration == NO_MAX_DURATION) {
629     /* Move to the *end* of the corresponding action set. This convention
630        is used to speed up update_resource_state  */
631     xbt_swag_remove(action, ((surf_action_t) action)->state_set);
632     ((surf_action_t) action)->state_set =
633       running_action_set_that_does_not_need_being_checked;
634     xbt_swag_insert(action, ((surf_action_t) action)->state_set);
635   }
636   XBT_OUT;
637   return (surf_action_t) action;
638 }
639
640 static void action_suspend(surf_action_t action)
641 {
642   XBT_IN1("(%p)", action);
643   if (((surf_action_cpu_ti_t) action)->suspended != 2) {
644     ((surf_action_cpu_ti_t) action)->suspended = 1;
645     xbt_swag_insert(ACTION_GET_CPU(action), modified_cpu);
646   }
647   XBT_OUT;
648 }
649
650 static void action_resume(surf_action_t action)
651 {
652   XBT_IN1("(%p)", action);
653   if (((surf_action_cpu_ti_t) action)->suspended != 2) {
654     ((surf_action_cpu_ti_t) action)->suspended = 0;
655     xbt_swag_insert(ACTION_GET_CPU(action), modified_cpu);
656   }
657   XBT_OUT;
658 }
659
660 static int action_is_suspended(surf_action_t action)
661 {
662   return (((surf_action_cpu_ti_t) action)->suspended == 1);
663 }
664
665 static void action_set_max_duration(surf_action_t action, double duration)
666 {
667   surf_action_cpu_ti_t ACT = (surf_action_cpu_ti_t) action;
668   double min_finish;
669
670   XBT_IN2("(%p,%g)", action, duration);
671
672   action->max_duration = duration;
673
674   if (duration >= 0)
675     min_finish =
676       (action->start + action->max_duration) <
677       action->finish ? (action->start +
678                         action->max_duration) : action->finish;
679   else
680     min_finish = action->finish;
681
682   /* add in action heap */
683   if (ACT->index_heap >= 0) {
684     surf_action_cpu_ti_t heap_act =
685       xbt_heap_remove(action_heap, ACT->index_heap);
686     if (heap_act != ACT)
687       DIE_IMPOSSIBLE;
688   }
689   xbt_heap_push(action_heap, ACT, min_finish);
690
691   XBT_OUT;
692 }
693
694 static void action_set_priority(surf_action_t action, double priority)
695 {
696   XBT_IN2("(%p,%g)", action, priority);
697   action->priority = priority;
698   xbt_swag_insert(ACTION_GET_CPU(action), modified_cpu);
699   XBT_OUT;
700 }
701
702 static double action_get_remains(surf_action_t action)
703 {
704   XBT_IN1("(%p)", action);
705   cpu_update_remaining_amount((cpu_ti_t) ((surf_action_cpu_ti_t) action)->cpu,
706                               surf_get_clock());
707   return action->remains;
708   XBT_OUT;
709 }
710
711 static e_surf_resource_state_t get_state(void *cpu)
712 {
713   return ((cpu_ti_t) cpu)->state_current;
714 }
715
716 static double get_speed(void *cpu, double load)
717 {
718   return load * (((cpu_ti_t) cpu)->power_peak);
719 }
720
721 /**
722  * \brief Auxiliar function to update the cpu power scale.
723  *
724  *      This function uses the trace structure to return the power scale at the determined time a.
725  * \param trace         Trace structure to search the updated power scale
726  * \param a                             Time
727  * \return Cpu power scale
728 */
729 static double surf_cpu_get_power_scale(surf_cpu_ti_tgmr_t trace, double a)
730 {
731   double reduced_a;
732   int point;
733
734   reduced_a = a - floor(a / trace->last_time) * trace->last_time;
735   point = (int) (reduced_a / trace->levels[0]->spacing);
736   return trace->levels[0]->values[point];
737 }
738
739 static double get_available_speed(void *cpu)
740 {
741   cpu_ti_t CPU = cpu;
742   CPU->power_scale =
743     surf_cpu_get_power_scale(CPU->avail_trace, surf_get_clock());
744   /* number between 0 and 1 */
745   return CPU->power_scale;
746 }
747
748 static void finalize(void)
749 {
750   void *cpu;
751   xbt_dict_cursor_t cursor;
752   char *key;
753   xbt_dict_foreach(surf_model_resource_set(surf_cpu_model), cursor, key, cpu) {
754     cpu_ti_t CPU = cpu;
755     xbt_swag_free(CPU->action_set);
756     surf_cpu_free_trace(CPU->avail_trace);
757   }
758
759   surf_model_exit(surf_cpu_model);
760   surf_cpu_model = NULL;
761
762   xbt_swag_free(running_action_set_that_does_not_need_being_checked);
763   xbt_swag_free(modified_cpu);
764   running_action_set_that_does_not_need_being_checked = NULL;
765   xbt_heap_free(action_heap);
766 }
767
768 static void surf_cpu_model_init_internal(void)
769 {
770   s_surf_action_t action;
771   s_cpu_ti_t cpu;
772
773   surf_cpu_model = surf_model_init();
774
775   running_action_set_that_does_not_need_being_checked =
776     xbt_swag_new(xbt_swag_offset(action, state_hookup));
777
778   modified_cpu = xbt_swag_new(xbt_swag_offset(cpu, modified_cpu_hookup));
779
780   surf_cpu_model->name = "CPU_TI";
781
782   surf_cpu_model->action_unref = action_unref;
783   surf_cpu_model->action_cancel = action_cancel;
784   surf_cpu_model->action_state_set = cpu_action_state_set;
785
786   surf_cpu_model->model_private->resource_used = resource_used;
787   surf_cpu_model->model_private->share_resources = share_resources;
788   surf_cpu_model->model_private->update_actions_state = update_actions_state;
789   surf_cpu_model->model_private->update_resource_state =
790     update_resource_state;
791   surf_cpu_model->model_private->finalize = finalize;
792
793   surf_cpu_model->suspend = action_suspend;
794   surf_cpu_model->resume = action_resume;
795   surf_cpu_model->is_suspended = action_is_suspended;
796   surf_cpu_model->set_max_duration = action_set_max_duration;
797   surf_cpu_model->set_priority = action_set_priority;
798   surf_cpu_model->get_remains = action_get_remains;
799
800   surf_cpu_model->extension.cpu.execute = execute;
801   surf_cpu_model->extension.cpu.sleep = action_sleep;
802
803   surf_cpu_model->extension.cpu.get_state = get_state;
804   surf_cpu_model->extension.cpu.get_speed = get_speed;
805   surf_cpu_model->extension.cpu.get_available_speed = get_available_speed;
806
807   action_heap = xbt_heap_new(8, NULL);
808   xbt_heap_set_update_callback(action_heap, action_update_index_heap);
809
810 }
811
812 void surf_cpu_model_init_ti(const char *filename)
813 {
814   if (surf_cpu_model)
815     return;
816   surf_cpu_model_init_internal();
817   define_callbacks(filename);
818   xbt_dynar_push(model_list, &surf_cpu_model);
819 }
820
821
822 ///////////////// BEGIN INTEGRAL //////////////
823
824 /**
825  * \brief Integrate trace
826  *  
827  * Wrapper around surf_cpu_integrate_trace_simple() to get
828  * the cyclic effect.
829  *
830  * \param trace Trace structure.
831  * \param a                     Begin of interval
832  * \param b                     End of interval
833  * \return the integrate value. -1 if an error occurs.
834  */
835 static double surf_cpu_integrate_trace(surf_cpu_ti_tgmr_t trace, double a,
836                                        double b)
837 {
838   double first_chunk;
839   double middle_chunk;
840   double last_chunk;
841   int a_index, b_index;
842
843   if ((a < 0.0) || (a > b)) {
844     CRITICAL2
845       ("Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative computation amount. Check your code.",
846        a, b);
847     xbt_abort();
848   }
849   if (a == b)
850     return 0.0;
851
852   if (trace->type == TRACE_FIXED) {
853     return ((b - a) * trace->value);
854   }
855
856   if (ceil(a / trace->last_time) == a / trace->last_time)
857     a_index = 1 + (int) (ceil(a / trace->last_time));
858   else
859     a_index = (int) (ceil(a / trace->last_time));
860
861   b_index = (int) (floor(b / trace->last_time));
862
863   if (a_index > b_index) {      /* Same chunk */
864     return surf_cpu_integrate_trace_simple(trace,
865                                            a - (a_index -
866                                                 1) * trace->last_time,
867                                            b - (b_index) * trace->last_time);
868   }
869
870   first_chunk = surf_cpu_integrate_trace_simple(trace,
871                                                 a - (a_index -
872                                                      1) * trace->last_time,
873                                                 trace->last_time);
874   middle_chunk = (b_index - a_index) * trace->total;
875   last_chunk = surf_cpu_integrate_trace_simple(trace,
876                                                0.0,
877                                                b -
878                                                (b_index) * trace->last_time);
879
880   DEBUG3("first_chunk=%.2f  middle_chunk=%.2f  last_chunk=%.2f\n",
881          first_chunk, middle_chunk, last_chunk);
882
883   return (first_chunk + middle_chunk + last_chunk);
884 }
885
886 /**
887  * \brief Integrate the trace between a and b.
888  *
889  *  integrates without taking cyclic-traces into account.
890  *  [a,b] \subset [0,last_time]
891  *
892  * \param trace Trace structure.
893  * \param a                     Begin of interval
894  * \param b                     End of interval
895  * \return the integrate value. -1 if an error occurs.
896  */
897 static double surf_cpu_integrate_trace_simple(surf_cpu_ti_tgmr_t trace,
898                                               double a, double b)
899 {
900   double integral = 0.0;
901   int i;
902   long index;
903   int top_level = 0;
904   long l_bounds[TRACE_NB_LEVELS];
905   long u_bounds[TRACE_NB_LEVELS];
906   double a_divided_by_spacing;
907   double current_spacing;
908   DEBUG2("Computing simple integral on [%.2f , %.2f]\n", a, b);
909
910   /* Sanity checks */
911   if ((a < 0.0) || (b < a) || (a > trace->last_time)
912       || (b > trace->last_time)) {
913     CRITICAL2
914       ("Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative computation amount. Check your code.",
915        a, b);
916     xbt_abort();
917   }
918   if (b == a) {
919     return 0.0;
920   }
921
922   for (i = 0; i < trace->nb_levels; i++) {
923     a_divided_by_spacing = a / trace->levels[i]->spacing;
924     if (ceil(a_divided_by_spacing) == a_divided_by_spacing)
925       l_bounds[i] = 1 + (long) ceil(a_divided_by_spacing);
926     else
927       l_bounds[i] = (long) (ceil(a_divided_by_spacing));
928     if (b == trace->last_time) {
929       u_bounds[i] = (long) (floor(b / trace->levels[i]->spacing)) - 1;
930     } else {
931       u_bounds[i] = (long) (floor(b / trace->levels[i]->spacing));
932     }
933     DEBUG3("level %d: l%ld  u%ld\n", i, l_bounds[i], u_bounds[i]);
934
935     if (l_bounds[i] <= u_bounds[i])
936       top_level = i;
937   }
938   DEBUG1("top_level=%d\n", top_level);
939
940   /* Are a and b BOTH in the same chunk of level 0 ? */
941   if (l_bounds[0] > u_bounds[0]) {
942     return (b - a) * (trace->levels[0]->values[u_bounds[0]]);
943   }
944
945   /* first sub-level amount */
946   integral += ((l_bounds[0]) * (trace->levels[0]->spacing) - a) *
947     (trace->levels[0]->values[l_bounds[0] - 1]);
948
949   DEBUG1("Initial level 0 amount is %.2f\n", integral);
950
951   /* first n-1 levels */
952   for (i = 0; i < top_level; i++) {
953
954     if (l_bounds[i] >= u_bounds[i])
955       break;
956
957     current_spacing = trace->levels[i]->spacing;
958     index = l_bounds[i];
959
960     DEBUG1("L%d:", i);
961
962     while (double_positive
963            (l_bounds[i + 1] * trace->levels[i + 1]->spacing -
964             index * current_spacing)) {
965       integral += current_spacing * trace->levels[i]->values[index];
966       DEBUG2("%.2f->%.2f|",
967              index * (trace->levels[i]->spacing),
968              (index + 1) * (trace->levels[i]->spacing));
969       index++;
970     }
971
972     DEBUG0("\n");
973   }
974
975   DEBUG1("After going up: %.2f\n", integral);
976
977   /* n-th level */
978   current_spacing = trace->levels[top_level]->spacing;
979   index = l_bounds[top_level];
980
981   DEBUG1("L%d:", top_level);
982
983   while (index < u_bounds[top_level]) {
984     integral += current_spacing * trace->levels[top_level]->values[index];
985
986     DEBUG2("%.2f->%.2f|",
987            index * (trace->levels[top_level]->spacing),
988            (index + 1) * (trace->levels[top_level]->spacing));
989
990     index++;
991   }
992
993   DEBUG0("\n");
994   DEBUG1("After steady : %.2f\n", integral);
995
996   /* And going back down */
997   for (i = top_level - 1; i >= 0; i--) {
998     if (l_bounds[i] > u_bounds[i])
999       break;
1000
1001     current_spacing = trace->levels[i]->spacing;
1002     index = u_bounds[i + 1] * (trace->levels[i + 1]->spacing /
1003                                current_spacing);
1004     DEBUG1("L%d:", i);
1005     while (double_positive
1006            ((u_bounds[i]) * current_spacing - index * current_spacing)) {
1007       integral += current_spacing * trace->levels[i]->values[index];
1008       DEBUG2("%.2f->%.2f|",
1009              index * (trace->levels[i]->spacing),
1010              (index + 1) * (trace->levels[i]->spacing));
1011       index++;
1012     }
1013   }
1014
1015   DEBUG1("After going down : %.2f", integral);
1016
1017
1018   /* Little piece at the end */
1019   integral += (b - u_bounds[0] * (trace->levels[0]->spacing)) *
1020     (trace->levels[0]->values[u_bounds[0]]);
1021
1022   DEBUG1("After last bit : %.2f", integral);
1023
1024   return integral;
1025 }
1026
1027
1028 /**
1029  * \brief Calcul the time needed to execute "amount" on cpu.
1030  *
1031  * Here, amount can span multiple trace periods
1032  *
1033  * \param trace         CPU trace structure
1034  * \param a                             Initial time
1035  * \param amount        Amount of calcul to be executed
1036  * \return      End time
1037  */
1038 static double surf_cpu_solve_trace(surf_cpu_ti_tgmr_t trace, double a,
1039                                    double amount)
1040 {
1041   int quotient;
1042   double reduced_b;
1043   double reduced_amount;
1044   double reduced_a;
1045   double b;
1046
1047   /* Fix very small negative numbers */
1048   if ((a < 0.0) && (a > -EPSILON)) {
1049     a = 0.0;
1050   }
1051   if ((amount < 0.0) && (amount > -EPSILON)) {
1052     amount = 0.0;
1053   }
1054
1055   /* Sanity checks */
1056   if ((a < 0.0) || (amount < 0.0)) {
1057     CRITICAL2
1058       ("Error, invalid parameters [a = %.2f, amount = %.2f]. You probably have a task executing with negative computation amount. Check your code.",
1059        a, amount);
1060     xbt_abort();
1061   }
1062
1063   /* At this point, a and amount are positive */
1064
1065   if (amount < EPSILON)
1066     return a;
1067
1068   /* Is the trace fixed ? */
1069   if (trace->type == TRACE_FIXED) {
1070     return (a + (amount / trace->value));
1071   }
1072
1073   /* Reduce the problem to one where amount <= trace_total */
1074   quotient = (int) (floor(amount / trace->total));
1075   reduced_amount = (trace->total) * ((amount / trace->total) -
1076                                      floor(amount / trace->total));
1077   reduced_a = a - (trace->last_time) * (int) (floor(a / trace->last_time));
1078
1079   DEBUG3("Quotient: %d reduced_amount: %lf reduced_a: %lf", quotient,
1080          reduced_amount, reduced_a);
1081
1082   /* Now solve for new_amount which is <= trace_total */
1083   /*
1084      fprintf(stderr,"reduced_a = %.2f\n",reduced_a);
1085      fprintf(stderr,"reduced_amount = %.2f\n",reduced_amount);
1086    */
1087   reduced_b =
1088     surf_cpu_solve_trace_somewhat_simple(trace, reduced_a, reduced_amount);
1089
1090   /* Re-map to the original b and amount */
1091   b = (trace->last_time) * (int) (floor(a / trace->last_time)) +
1092     (quotient * trace->last_time) + reduced_b;
1093   return b;
1094 }
1095
1096 /**
1097  * \brief Auxiliar function to solve integral
1098  *
1099  * Here, amount is <= trace->total
1100  * and a <=trace->last_time
1101  *
1102  */
1103 static double surf_cpu_solve_trace_somewhat_simple(surf_cpu_ti_tgmr_t trace,
1104                                                    double a, double amount)
1105 {
1106   double amount_till_end;
1107   double b;
1108
1109   DEBUG2("Solve integral: [%.2f, amount=%.2f]", a, amount);
1110
1111   amount_till_end = surf_cpu_integrate_trace(trace, a, trace->last_time);
1112   /*
1113      fprintf(stderr,"amount_till_end=%.2f\n",amount_till_end);
1114    */
1115
1116   if (amount_till_end > amount) {
1117     b = surf_cpu_solve_trace_simple(trace, a, amount);
1118   } else {
1119     b = trace->last_time +
1120       surf_cpu_solve_trace_simple(trace, 0.0, amount - amount_till_end);
1121   }
1122
1123   return b;
1124 }
1125
1126 /**
1127  * \brief Auxiliar function to solve integral
1128  * surf_cpu_solve_trace_simple()
1129  *
1130  *  solve for the upper bound without taking 
1131  *  cyclic-traces into account.
1132  *
1133  *  [a,y] \subset [0,last_time]
1134  *  
1135  */
1136 static double surf_cpu_solve_trace_simple(surf_cpu_ti_tgmr_t trace, double a,
1137                                           double amount)
1138 {
1139   double next_chunk;
1140   double remains;
1141   int i;
1142   long index;
1143   int top_level;
1144   double b;
1145   int done;
1146   long l_bounds[TRACE_NB_LEVELS];       /* May be too bgi for this trace */
1147   double a_divided_by_spacing;
1148   double current_spacing;
1149
1150   DEBUG2("Solving simple integral [x=%.2f,amount=%.2f]", a, amount);
1151
1152   /* Sanity checks */
1153   if ((a < 0.0) || (amount < 0.0) || (a > trace->last_time)) {
1154     CRITICAL2
1155       ("Error, invalid parameters [a = %.2f, amount = %.2f]. You probably have a task executing with negative computation amount. Check your code.",
1156        a, amount);
1157     xbt_abort();
1158   }
1159   if (amount == 0.0) {
1160     /* fprintf(stderr,"Warning: trivial integral solve\n"); */
1161     return a;
1162   }
1163
1164   for (i = 0; i < trace->nb_levels; i++) {
1165     a_divided_by_spacing = a / trace->levels[i]->spacing;
1166     if (ceil(a_divided_by_spacing) == a_divided_by_spacing)
1167       l_bounds[i] = 1 + (long) ceil(a_divided_by_spacing);
1168     else
1169       l_bounds[i] = (long) (ceil(a_divided_by_spacing));
1170
1171     if ((l_bounds[i] + 1) * trace->levels[i]->spacing > trace->last_time)
1172       break;
1173
1174     DEBUG2("level %d: l%ld", i, l_bounds[i]);
1175   }
1176   if (i == trace->nb_levels)
1177     top_level = trace->nb_levels - 1;
1178   else {
1179     top_level = i;
1180   }
1181
1182   remains = amount;
1183   /* first sub-level amount */
1184   next_chunk = ((l_bounds[0]) * (trace->levels[0]->spacing) - a) *
1185     (trace->levels[0]->values[l_bounds[0] - 1]);
1186
1187   if (remains - next_chunk < 0.0) {
1188     b = a + (amount / trace->levels[0]->values[l_bounds[0] - 1]);
1189
1190     DEBUG1("Returning sub-level[0] result %.2f", b);
1191
1192     return b;
1193   } else {
1194     b = (l_bounds[0]) * (trace->levels[0]->spacing);
1195     remains -= next_chunk;
1196   }
1197   DEBUG2("After sub-0 stuff: remains %.2f (b=%.2f)", remains, b);
1198
1199   /* first n-1 levels */
1200   DEBUG0("Going up levels");
1201
1202   done = 0;
1203   for (i = 0; i < top_level; i++) {
1204
1205     current_spacing = trace->levels[i]->spacing;
1206     index = l_bounds[i];
1207
1208     DEBUG1("L%d:", i);
1209
1210     while (double_positive
1211            (l_bounds[i + 1] * trace->levels[i + 1]->spacing -
1212             index * current_spacing)
1213            && ((index + 1) * (current_spacing) < trace->last_time)) {
1214
1215       next_chunk = current_spacing * trace->levels[i]->values[index];
1216
1217       DEBUG3("%.2f next_chunk= %.2f remains=%.2f",
1218              (index + 1) * (trace->levels[i]->spacing), next_chunk, remains);
1219
1220       if (remains - next_chunk < 0.0) { /* Too far */
1221         done = 1;
1222         break;
1223       } else {                  /* Keep going */
1224         DEBUG2("%.2f->%.2f|",
1225                index * (trace->levels[i]->spacing),
1226                (index + 1) * (trace->levels[i]->spacing));
1227
1228         remains -= next_chunk;
1229         b = (index + 1) * (current_spacing);
1230       }
1231       index++;
1232     }
1233     if (done) {
1234       /* found chunk, fix the index to top level */
1235       i++;
1236       break;
1237     }
1238   }
1239
1240   DEBUG0("Steady");
1241   top_level = i;
1242
1243   /* n-th level */
1244   current_spacing = trace->levels[top_level]->spacing;
1245   index = l_bounds[top_level];
1246
1247   DEBUG1("L%d:", top_level);
1248
1249   /* iterate over the last level only if it hasn't found the chunk where the amount is */
1250   if (!done) {
1251     while (index < trace->levels[top_level]->nb_points) {
1252       next_chunk = current_spacing * trace->levels[top_level]->values[index];
1253       if (remains - next_chunk <= 0.0) {        /* Too far */
1254         break;
1255       } else {
1256         DEBUG2("%.2f->%.2f|",
1257                index * (trace->levels[top_level]->spacing),
1258                (index + 1) * (trace->levels[top_level]->spacing));
1259
1260         remains -= next_chunk;
1261         b = (index + 1) * (current_spacing);
1262       }
1263       index++;
1264     }
1265   }
1266   DEBUG2("remains = %.2f b=%.2f", remains, b);
1267
1268   /* And going back down */
1269   DEBUG0("Going back down");
1270   for (i = top_level - 1; i >= 0; i--) {
1271
1272     current_spacing = trace->levels[i]->spacing;
1273     index = b / (trace->levels[i]->spacing);
1274
1275     DEBUG1("L%d:", i);
1276
1277     while (index < trace->levels[i]->nb_points) {
1278       next_chunk = current_spacing * trace->levels[i]->values[index];
1279       if (remains - next_chunk <= 0.0) {        /* Too far */
1280         break;
1281       } else {
1282         DEBUG2("%.2f->%.2f|",
1283                index * (current_spacing), (index + 1) * (current_spacing));
1284
1285         remains -= next_chunk;
1286         b += current_spacing;
1287       }
1288       index++;
1289     }
1290   }
1291
1292   DEBUG2("remains = %.2f b=%.2f\n", remains, b);
1293   DEBUG1("Last bit index=%ld\n", index);
1294
1295   /* Little piece at the end */
1296   b += (remains) / (trace->levels[0]->values[index]);
1297
1298   return b;
1299 }
1300
1301 //////////// END INTEGRAL /////////////////