Logo AND Algorithmique Numérique Distribuée

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