Logo AND Algorithmique Numérique Distribuée

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