Logo AND Algorithmique Numérique Distribuée

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