Logo AND Algorithmique Numérique Distribuée

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