Logo AND Algorithmique Numérique Distribuée

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