Logo AND Algorithmique Numérique Distribuée

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