Logo AND Algorithmique Numérique Distribuée

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