Logo AND Algorithmique Numérique Distribuée

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