Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Initialize another bunch of variables.
[simgrid.git] / src / surf / cpu_ti.cpp
1 #include "cpu_ti.hpp"
2 #include "trace_mgr_private.h"
3 #include "xbt/heap.h"
4
5 #ifndef SURF_MODEL_CPUTI_H_
6 #define SURF_MODEL_CPUTI_H_
7
8 extern "C" {
9 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf_cpu,
10                                 "Logging specific to the SURF CPU TRACE INTEGRATION module");
11 }
12
13 static xbt_swag_t cpu_ti_running_action_set_that_does_not_need_being_checked;
14 static xbt_swag_t cpu_ti_modified_cpu;
15 static xbt_heap_t cpu_ti_action_heap;
16
17 static void cpu_ti_action_update_index_heap(void *action, int i);
18
19 /*********
20  * Trace *
21  *********/
22
23 CpuTiTrace::CpuTiTrace(tmgr_trace_t power_trace)
24 {
25   s_tmgr_event_t val;
26   unsigned int cpt;
27   double integral = 0;
28   double time = 0;
29   int i = 0;
30   p_timePoints = (double*) xbt_malloc0(sizeof(double) *
31                   (xbt_dynar_length(power_trace->s_list.event_list) + 1));
32   p_integral = (double*) xbt_malloc0(sizeof(double) *
33                   (xbt_dynar_length(power_trace->s_list.event_list) + 1));
34   m_nbPoints = xbt_dynar_length(power_trace->s_list.event_list);
35   xbt_dynar_foreach(power_trace->s_list.event_list, cpt, val) {
36     p_timePoints[i] = time;
37     p_integral[i] = integral;
38     integral += val.delta * val.value;
39     time += val.delta;
40     i++;
41   }
42   p_timePoints[i] = time;
43   p_integral[i] = integral;
44 }
45
46 CpuTiTrace::~CpuTiTrace()
47 {
48   xbt_free(p_timePoints);
49   xbt_free(p_integral);
50 }
51
52 CpuTiTgmr::~CpuTiTgmr()
53 {
54   if (p_trace)
55     delete p_trace;
56 }
57
58 /**
59 * \brief Integrate trace
60 *
61 * Wrapper around surf_cpu_integrate_trace_simple() to get
62 * the cyclic effect.
63 *
64 * \param trace Trace structure.
65 * \param a      Begin of interval
66 * \param b      End of interval
67 * \return the integrate value. -1 if an error occurs.
68 */
69 double CpuTiTgmr::integrate(double a, double b)
70 {
71   double first_chunk;
72   double middle_chunk;
73   double last_chunk;
74   int a_index, b_index;
75
76   if ((a < 0.0) || (a > b)) {
77     XBT_CRITICAL
78         ("Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative computation amount. Check your code.",
79          a, b);
80     xbt_abort();
81   }
82   if (a == b)
83     return 0.0;
84
85   if (m_type == TRACE_FIXED) {
86     return ((b - a) * m_value);
87   }
88
89   if (ceil(a / m_lastTime) == a / m_lastTime)
90     a_index = 1 + (int) (ceil(a / m_lastTime));
91   else
92     a_index = (int) (ceil(a / m_lastTime));
93
94   b_index = (int) (floor(b / m_lastTime));
95
96   if (a_index > b_index) {      /* Same chunk */
97     return p_trace->integrateSimple(a - (a_index -
98                                               1) * m_lastTime,
99                                          b -
100                                          (b_index) *
101                                          m_lastTime);
102   }
103
104   first_chunk = p_trace->integrateSimple(a - (a_index -
105                                                    1) *
106                                               m_lastTime,
107                                               m_lastTime);
108   middle_chunk = (b_index - a_index) * m_total;
109   last_chunk = p_trace->integrateSimple(0.0,
110                                              b -
111                                              (b_index) *
112                                              m_lastTime);
113
114   XBT_DEBUG("first_chunk=%.2f  middle_chunk=%.2f  last_chunk=%.2f\n",
115          first_chunk, middle_chunk, last_chunk);
116
117   return (first_chunk + middle_chunk + last_chunk);
118 }
119
120 /**
121  * \brief Auxiliary function to calculate the integral between a and b.
122  *     It simply calculates the integral at point a and b and returns the difference 
123  *   between them.
124  * \param trace    Trace structure
125  * \param a        Initial point
126  * \param b  Final point
127  * \return  Integral
128 */
129 double CpuTiTrace::integrateSimple(double a, double b)
130 {
131   return integrateSimplePoint(b) - integrateSimplePoint(a);
132 }
133
134 /**
135  * \brief Auxiliary function to calculate the integral at point a.
136  * \param trace    Trace structure
137  * \param a        point
138  * \return  Integral
139 */
140 double CpuTiTrace::integrateSimplePoint(double a)
141 {
142   double integral = 0;
143   int ind;
144   double a_aux = a;
145   ind = binarySearch(p_timePoints, a, 0, m_nbPoints - 1);
146   integral += p_integral[ind];
147   XBT_DEBUG
148       ("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f",
149        a, ind, integral, p_integral[ind + 1], p_integral[ind],
150        p_timePoints[ind + 1], p_timePoints[ind]);
151   double_update(&a_aux, p_timePoints[ind]);
152   if (a_aux > 0)
153     integral +=
154         ((p_integral[ind + 1] -
155           p_integral[ind]) / (p_timePoints[ind + 1] -
156                               p_timePoints[ind])) * (a - p_timePoints[ind]);
157   XBT_DEBUG("Integral a %f = %f", a, integral);
158
159   return integral;
160 }
161
162 /**
163 * \brief Calculate the time needed to execute "amount" on cpu.
164 *
165 * Here, amount can span multiple trace periods
166 *
167 * \param trace   CPU trace structure
168 * \param a        Initial time
169 * \param amount  Amount to be executed
170 * \return  End time
171 */
172 double CpuTiTgmr::solve(double a, double amount)
173 {
174   int quotient;
175   double reduced_b;
176   double reduced_amount;
177   double reduced_a;
178   double b;
179
180 /* Fix very small negative numbers */
181   if ((a < 0.0) && (a > -EPSILON)) {
182     a = 0.0;
183   }
184   if ((amount < 0.0) && (amount > -EPSILON)) {
185     amount = 0.0;
186   }
187
188 /* Sanity checks */
189   if ((a < 0.0) || (amount < 0.0)) {
190     XBT_CRITICAL
191         ("Error, invalid parameters [a = %.2f, amount = %.2f]. You probably have a task executing with negative computation amount. Check your code.",
192          a, amount);
193     xbt_abort();
194   }
195
196 /* At this point, a and amount are positive */
197
198   if (amount < EPSILON)
199     return a;
200
201 /* Is the trace fixed ? */
202   if (m_type == TRACE_FIXED) {
203     return (a + (amount / m_value));
204   }
205
206   XBT_DEBUG("amount %f total %f", amount, m_total);
207 /* Reduce the problem to one where amount <= trace_total */
208   quotient = (int) (floor(amount / m_total));
209   reduced_amount = (m_total) * ((amount / m_total) -
210                                      floor(amount / m_total));
211   reduced_a = a - (m_lastTime) * (int) (floor(a / m_lastTime));
212
213   XBT_DEBUG("Quotient: %d reduced_amount: %f reduced_a: %f", quotient,
214          reduced_amount, reduced_a);
215
216 /* Now solve for new_amount which is <= trace_total */
217 /*
218    fprintf(stderr,"reduced_a = %.2f\n",reduced_a);
219    fprintf(stderr,"reduced_amount = %.2f\n",reduced_amount);
220  */
221   reduced_b = solveSomewhatSimple(reduced_a, reduced_amount);
222
223 /* Re-map to the original b and amount */
224   b = (m_lastTime) * (int) (floor(a / m_lastTime)) +
225       (quotient * m_lastTime) + reduced_b;
226   return b;
227 }
228
229 /**
230 * \brief Auxiliary function to solve integral
231 *
232 * Here, amount is <= trace->total
233 * and a <=trace->last_time
234 *
235 */
236 double CpuTiTgmr::solveSomewhatSimple(double a, double amount)
237 {
238   double amount_till_end;
239   double b;
240
241   XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", a, amount);
242   amount_till_end = integrate(a, m_lastTime);
243 /*
244    fprintf(stderr,"amount_till_end=%.2f\n",amount_till_end);
245  */
246
247   if (amount_till_end > amount) {
248     b = p_trace->solveSimple(a, amount);
249   } else {
250     b = m_lastTime + p_trace->solveSimple(0.0, amount - amount_till_end);
251   }
252   return b;
253 }
254
255 /**
256  * \brief Auxiliary function to solve integral.
257  *  It returns the date when the requested amount of flops is available
258  * \param trace    Trace structure
259  * \param a        Initial point
260  * \param amount  Amount of flops 
261  * \return The date when amount is available.
262 */
263 double CpuTiTrace::solveSimple(double a, double amount)
264 {
265   double integral_a;
266   int ind;
267   double time;
268   integral_a = integrateSimplePoint(a);
269   ind = binarySearch(p_integral, integral_a + amount, 0, m_nbPoints - 1);
270   time = p_timePoints[ind];
271   time +=
272       (integral_a + amount -
273        p_integral[ind]) / ((p_integral[ind + 1] -
274                                  p_integral[ind]) /
275                                 (p_timePoints[ind + 1] -
276                                  p_timePoints[ind]));
277
278   return time;
279 }
280
281 /**
282 * \brief Auxiliary function to update the CPU power scale.
283 *
284 *  This function uses the trace structure to return the power scale at the determined time a.
285 * \param trace    Trace structure to search the updated power scale
286 * \param a        Time
287 * \return CPU power scale
288 */
289 double CpuTiTgmr::getPowerScale(double a)
290 {
291   double reduced_a;
292   int point;
293   s_tmgr_event_t val;
294
295   reduced_a = a - floor(a / m_lastTime) * m_lastTime;
296   point = p_trace->binarySearch(p_trace->p_timePoints, reduced_a, 0,
297                                 p_trace->m_nbPoints - 1);
298   xbt_dynar_get_cpy(p_powerTrace->s_list.event_list, point, &val);
299   return val.value;
300 }
301
302 /**
303 * \brief Creates a new integration trace from a tmgr_trace_t
304 *
305 * \param  power_trace    CPU availability trace
306 * \param  value          Percentage of CPU power available (useful to fixed tracing)
307 * \param  spacing        Initial spacing
308 * \return  Integration trace structure
309 */
310 CpuTiTgmr::CpuTiTgmr(tmgr_trace_t power_trace, double value)
311 {
312   double total_time = 0.0;
313   s_tmgr_event_t val;
314   unsigned int cpt;
315   p_trace = 0;
316
317 /* no availability file, fixed trace */
318   if (!power_trace) {
319     m_type = TRACE_FIXED;
320     m_value = value;
321     XBT_DEBUG("No availability trace. Constant value = %lf", value);
322     return;
323   }
324
325   /* only one point available, fixed trace */
326   if (xbt_dynar_length(power_trace->s_list.event_list) == 1) {
327     xbt_dynar_get_cpy(power_trace->s_list.event_list, 0, &val);
328     m_type = TRACE_FIXED;
329     m_value = val.value;
330     return;
331   }
332
333   m_type = TRACE_DYNAMIC;
334   p_powerTrace = power_trace;
335
336   /* count the total time of trace file */
337   xbt_dynar_foreach(power_trace->s_list.event_list, cpt, val) {
338     total_time += val.delta;
339   }
340   p_trace = new CpuTiTrace(power_trace);
341   m_lastTime = total_time;
342   m_total = p_trace->integrateSimple(0, total_time);
343
344   XBT_DEBUG("Total integral %lf, last_time %lf ",
345             m_total, m_lastTime);
346 }
347
348 /**
349  * \brief Binary search in array.
350  *  It returns the first point of the interval in which "a" is. 
351  * \param array    Array
352  * \param a        Value to search
353  * \param low     Low bound to search in array
354  * \param high    Upper bound to search in array
355  * \return Index of point
356 */
357 int CpuTiTrace::binarySearch(double *array, double a, int low, int high)
358 {
359   xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than"
360       " high (%d)", low, high);
361
362   int mid;
363   do {
364     mid = low + (high - low) / 2;
365     XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid,
366         array[mid]);
367
368     if (array[mid] > a)
369       high = mid;
370     else
371       low = mid;
372   }
373   while (low < high - 1);
374
375   return low;
376 }
377
378 /*************
379  * CallBacks *
380  *************/
381
382 static void parse_cpu_ti_init(sg_platf_host_cbarg_t host){
383   ((CpuTiModelPtr)surf_cpu_model_pm)->parseInit(host);
384 }
385
386 static void add_traces_cpu_ti(){
387   surf_cpu_model_pm->addTraces();
388 }
389
390 static void cpu_ti_define_callbacks()
391 {
392   sg_platf_host_add_cb(parse_cpu_ti_init);
393   sg_platf_postparse_add_cb(add_traces_cpu_ti);
394 }
395
396 /*********
397  * Model *
398  *********/
399
400 void surf_cpu_model_init_ti()
401 {
402   xbt_assert(!surf_cpu_model_pm,"CPU model already initialized. This should not happen.");
403   surf_cpu_model_pm = new CpuTiModel();
404   cpu_ti_define_callbacks();
405   ModelPtr model = static_cast<ModelPtr>(surf_cpu_model_pm);
406   xbt_dynar_push(model_list, &model);
407 }
408
409 CpuTiModel::CpuTiModel() : CpuModel("cpu_ti")
410 {
411   xbt_assert(!surf_cpu_model_pm,"CPU model already initialized. This should not happen.");
412   ActionPtr action = NULL;
413   CpuTi cpu;
414
415   cpu_ti_running_action_set_that_does_not_need_being_checked =
416       xbt_swag_new(xbt_swag_offset(*action, p_stateHookup));
417
418   cpu_ti_modified_cpu =
419       xbt_swag_new(xbt_swag_offset(cpu, p_modifiedCpuHookup));
420
421   cpu_ti_action_heap = xbt_heap_new(8, NULL);
422   xbt_heap_set_update_callback(cpu_ti_action_heap,
423                                cpu_ti_action_update_index_heap);
424 }
425
426 CpuTiModel::~CpuTiModel()
427 {
428   void **cpu;
429   xbt_lib_cursor_t cursor;
430   char *key;
431
432   xbt_lib_foreach(host_lib, cursor, key, cpu){
433     if(cpu[SURF_CPU_LEVEL])
434     {
435         CpuTiPtr CPU = dynamic_cast<CpuTiPtr>(static_cast<ResourcePtr>(cpu[SURF_CPU_LEVEL]));
436         xbt_swag_free(CPU->p_actionSet);
437         delete CPU->p_availTrace;
438     }
439   }
440
441   surf_cpu_model_pm = NULL;
442
443   xbt_swag_free
444       (cpu_ti_running_action_set_that_does_not_need_being_checked);
445   xbt_swag_free(cpu_ti_modified_cpu);
446   cpu_ti_running_action_set_that_does_not_need_being_checked = NULL;
447   xbt_heap_free(cpu_ti_action_heap);
448 }
449
450 void CpuTiModel::parseInit(sg_platf_host_cbarg_t host)
451 {
452   createResource(host->id,
453         host->power_peak,
454         host->pstate,
455         host->power_scale,
456         host->power_trace,
457         host->core_amount,
458         host->initial_state,
459         host->state_trace,
460         host->properties);
461 }
462
463 CpuTiPtr CpuTiModel::createResource(const char *name,
464                                xbt_dynar_t powerPeak,
465                                int pstate,
466                            double powerScale,
467                            tmgr_trace_t powerTrace,
468                            int core,
469                            e_surf_resource_state_t stateInitial,
470                            tmgr_trace_t stateTrace,
471                            xbt_dict_t cpuProperties)
472 {
473   xbt_assert(core==1,"Multi-core not handled with this model yet");
474   xbt_assert(!surf_cpu_resource_priv(surf_cpu_resource_by_name(name)),
475               "Host '%s' declared several times in the platform file",
476               name);
477   CpuTiPtr cpu = new CpuTi(this, name, powerPeak, pstate, powerScale, powerTrace,
478                            core, stateInitial, stateTrace, cpuProperties);
479   xbt_lib_set(host_lib, name, SURF_CPU_LEVEL, static_cast<ResourcePtr>(cpu));
480   return (CpuTiPtr) xbt_lib_get_elm_or_null(host_lib, name);
481 }
482
483 CpuTiActionPtr CpuTiModel::createAction(double /*cost*/, bool /*failed*/)
484 {
485   return NULL;//new CpuTiAction(this, cost, failed);
486 }
487
488 double CpuTiModel::shareResources(double now)
489 {
490   void *_cpu, *_cpu_next;
491   double min_action_duration = -1;
492
493 /* iterates over modified cpus to update share resources */
494   xbt_swag_foreach_safe(_cpu, _cpu_next, cpu_ti_modified_cpu) {
495     static_cast<CpuTiPtr>(_cpu)->updateActionFinishDate(now);
496   }
497 /* get the min next event if heap not empty */
498   if (xbt_heap_size(cpu_ti_action_heap) > 0)
499     min_action_duration = xbt_heap_maxkey(cpu_ti_action_heap) - now;
500
501   XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
502
503   return min_action_duration;
504 }
505
506 void CpuTiModel::updateActionsState(double now, double /*delta*/)
507 {
508   while ((xbt_heap_size(cpu_ti_action_heap) > 0)
509          && (xbt_heap_maxkey(cpu_ti_action_heap) <= now)) {
510     CpuTiActionPtr action = (CpuTiActionPtr) xbt_heap_pop(cpu_ti_action_heap);
511     XBT_DEBUG("Action %p: finish", action);
512     action->m_finish = surf_get_clock();
513     /* set the remains to 0 due to precision problems when updating the remaining amount */
514     action->m_remains = 0;
515     action->setState(SURF_ACTION_DONE);
516     /* update remaining amount of all actions */
517     action->p_cpu->updateRemainingAmount(surf_get_clock());
518   }
519 }
520
521 void CpuTiModel::addTraces()
522 {
523   xbt_dict_cursor_t cursor = NULL;
524   char *trace_name, *elm;
525
526   static int called = 0;
527
528   if (called)
529     return;
530   called = 1;
531
532 /* connect all traces relative to hosts */
533   xbt_dict_foreach(trace_connect_list_host_avail, cursor, trace_name, elm) {
534     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
535     CpuTiPtr cpu = static_cast<CpuTiPtr>(surf_cpu_resource_priv(surf_cpu_resource_by_name(elm)));
536
537     xbt_assert(cpu, "Host %s undefined", elm);
538     xbt_assert(trace, "Trace %s undefined", trace_name);
539
540     if (cpu->p_stateEvent) {
541       XBT_DEBUG("Trace already configured for this CPU(%s), ignoring it",
542              elm);
543       continue;
544     }
545     XBT_DEBUG("Add state trace: %s to CPU(%s)", trace_name, elm);
546     cpu->p_stateEvent = tmgr_history_add_trace(history, trace, 0.0, 0, static_cast<ResourcePtr>(cpu));
547   }
548
549   xbt_dict_foreach(trace_connect_list_power, cursor, trace_name, elm) {
550     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
551     CpuTiPtr cpu = dynamic_cast<CpuTiPtr>(static_cast<ResourcePtr>(surf_cpu_resource_priv(surf_cpu_resource_by_name(elm))));
552
553     xbt_assert(cpu, "Host %s undefined", elm);
554     xbt_assert(trace, "Trace %s undefined", trace_name);
555
556     XBT_DEBUG("Add power trace: %s to CPU(%s)", trace_name, elm);
557     if (cpu->p_availTrace)
558       delete cpu->p_availTrace;
559
560     cpu->p_availTrace = new CpuTiTgmr(trace, cpu->m_powerScale);
561
562     /* add a fake trace event if periodicity == 0 */
563     if (trace && xbt_dynar_length(trace->s_list.event_list) > 1) {
564       s_tmgr_event_t val;
565       xbt_dynar_get_cpy(trace->s_list.event_list,
566                         xbt_dynar_length(trace->s_list.event_list) - 1, &val);
567       if (val.delta == 0) {
568         tmgr_trace_t empty_trace;
569         empty_trace = tmgr_empty_trace_new();
570         cpu->p_powerEvent =
571             tmgr_history_add_trace(history, empty_trace,
572                                    cpu->p_availTrace->m_lastTime, 0, static_cast<ResourcePtr>(cpu));
573       }
574     }
575   }
576 }
577
578 /************
579  * Resource *
580  ************/
581 CpuTi::CpuTi(CpuTiModelPtr model, const char *name, xbt_dynar_t powerPeak,
582         int pstate, double powerScale, tmgr_trace_t powerTrace, int core,
583         e_surf_resource_state_t stateInitial, tmgr_trace_t stateTrace,
584         xbt_dict_t properties) :
585         Resource(model, name, properties), Cpu(model, name, properties) {
586   p_powerEvent = NULL;
587   p_stateCurrent = stateInitial;
588   m_powerScale = powerScale;
589   m_core = core;
590   tmgr_trace_t empty_trace;             
591   s_tmgr_event_t val;           
592   xbt_assert(core==1,"Multi-core not handled with this model yet");
593   XBT_DEBUG("power scale %lf", powerScale);
594   p_availTrace = new CpuTiTgmr(powerTrace, powerScale);
595
596   CpuTiActionPtr action = NULL;
597   p_actionSet = xbt_swag_new(xbt_swag_offset(*action, p_cpuListHookup));
598
599   m_lastUpdate = 0;
600
601   xbt_dynar_get_cpy(powerPeak, 0, &m_powerPeak);
602   xbt_dynar_free(&powerPeak);  /* kill memory leak */
603   m_pstate = pstate;
604   XBT_DEBUG("CPU create: peak=%f, pstate=%d", m_powerPeak, m_pstate);
605
606   p_modifiedCpuHookup.prev = 0;
607   p_modifiedCpuHookup.next = 0;
608
609   if (stateTrace)
610     p_stateEvent = tmgr_history_add_trace(history, stateTrace, 0.0, 0, static_cast<ResourcePtr>(this));
611   if (powerTrace && xbt_dynar_length(powerTrace->s_list.event_list) > 1) {
612     // add a fake trace event if periodicity == 0 
613     xbt_dynar_get_cpy(powerTrace->s_list.event_list,
614                       xbt_dynar_length(powerTrace->s_list.event_list) - 1, &val);
615     if (val.delta == 0) {
616       empty_trace = tmgr_empty_trace_new();
617       p_powerEvent =
618         tmgr_history_add_trace(history, empty_trace,
619                                p_availTrace->m_lastTime, 0, static_cast<ResourcePtr>(this));
620     }
621   }
622 };
623
624 void CpuTi::updateState(tmgr_trace_event_t event_type,
625                         double value, double date)
626 {
627   void *_action;
628   CpuTiActionPtr action;
629
630   if (event_type == p_powerEvent) {
631     tmgr_trace_t power_trace;
632     CpuTiTgmrPtr trace;
633     s_tmgr_event_t val;
634
635     XBT_DEBUG("Finish trace date: %f value %lf date %f", surf_get_clock(),
636            value, date);
637     /* update remaining of actions and put in modified cpu swag */
638     updateRemainingAmount(date);
639     xbt_swag_insert(this, cpu_ti_modified_cpu);
640
641     power_trace = p_availTrace->p_powerTrace;
642     xbt_dynar_get_cpy(power_trace->s_list.event_list,
643                       xbt_dynar_length(power_trace->s_list.event_list) - 1, &val);
644     /* free old trace */
645     delete p_availTrace;
646     m_powerScale = val.value;
647
648     trace = new CpuTiTgmr(TRACE_FIXED, val.value);
649     XBT_DEBUG("value %f", val.value);
650
651     p_availTrace = trace;
652
653     if (tmgr_trace_event_free(event_type))
654       p_powerEvent = NULL;
655
656   } else if (event_type == p_stateEvent) {
657     if (value > 0) {
658       if(p_stateCurrent == SURF_RESOURCE_OFF)
659         xbt_dynar_push_as(host_that_restart, char*, (char *)m_name);
660       p_stateCurrent = SURF_RESOURCE_ON;
661     } else {
662       p_stateCurrent = SURF_RESOURCE_OFF;
663
664       /* put all action running on cpu to failed */
665       xbt_swag_foreach(_action, p_actionSet) {
666         action = static_cast<CpuTiActionPtr>(_action);
667         if (action->getState() == SURF_ACTION_RUNNING
668          || action->getState() == SURF_ACTION_READY
669          || action->getState() == SURF_ACTION_NOT_IN_THE_SYSTEM) {
670           action->m_finish = date;
671           action->setState(SURF_ACTION_FAILED);
672           if (action->m_indexHeap >= 0) {
673             CpuTiActionPtr heap_act = (CpuTiActionPtr)
674                 xbt_heap_remove(cpu_ti_action_heap, action->m_indexHeap);
675             if (heap_act != action)
676               DIE_IMPOSSIBLE;
677           }
678         }
679       }
680     }
681     if (tmgr_trace_event_free(event_type))
682       p_stateEvent = NULL;
683   } else {
684     XBT_CRITICAL("Unknown event ! \n");
685     xbt_abort();
686   }
687
688   return;
689 }
690
691 void CpuTi::updateActionFinishDate(double now)
692 {
693   void *_action;
694   CpuTiActionPtr action;
695   double sum_priority = 0.0, total_area, min_finish = -1;
696
697 /* update remaning amount of actions */
698 updateRemainingAmount(now);
699
700   xbt_swag_foreach(_action, p_actionSet) {
701     action = static_cast<CpuTiActionPtr>(_action);
702     /* action not running, skip it */
703     if (action->p_stateSet !=
704         surf_cpu_model_pm->p_runningActionSet)
705       continue;
706
707     /* bogus priority, skip it */
708     if (action->m_priority <= 0)
709       continue;
710
711     /* action suspended, skip it */
712     if (action->m_suspended != 0)
713       continue;
714
715     sum_priority += 1.0 / action->m_priority;
716   }
717   m_sumPriority = sum_priority;
718
719   xbt_swag_foreach(_action, p_actionSet) {
720     action = static_cast<CpuTiActionPtr>(_action);
721     min_finish = -1;
722     /* action not running, skip it */
723     if (action->p_stateSet !=
724         surf_cpu_model_pm->p_runningActionSet)
725       continue;
726
727     /* verify if the action is really running on cpu */
728     if (action->m_suspended == 0 && action->m_priority > 0) {
729       /* total area needed to finish the action. Used in trace integration */
730       total_area =
731           (action->m_remains) * sum_priority *
732            action->m_priority;
733
734       total_area /= m_powerPeak;
735
736       action->m_finish = p_availTrace->solve(now, total_area);
737       /* verify which event will happen before (max_duration or finish time) */
738       if (action->m_maxDuration != NO_MAX_DURATION &&
739           action->m_start + action->m_maxDuration < action->m_finish)
740         min_finish = action->m_start + action->m_maxDuration;
741       else
742         min_finish = action->m_finish;
743     } else {
744       /* put the max duration time on heap */
745       if (action->m_maxDuration != NO_MAX_DURATION)
746         min_finish = action->m_start + action->m_maxDuration;
747     }
748     /* add in action heap */
749     XBT_DEBUG("action(%p) index %d", action, action->m_indexHeap);
750     if (action->m_indexHeap >= 0) {
751       CpuTiActionPtr heap_act = (CpuTiActionPtr)
752           xbt_heap_remove(cpu_ti_action_heap, action->m_indexHeap);
753       if (heap_act != action)
754         DIE_IMPOSSIBLE;
755     }
756     if (min_finish != NO_MAX_DURATION)
757       xbt_heap_push(cpu_ti_action_heap, action, min_finish);
758
759     XBT_DEBUG
760         ("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f",
761          m_name, action, action->m_start,
762          action->m_finish,
763          action->m_maxDuration);
764   }
765 /* remove from modified cpu */
766   xbt_swag_remove(this, cpu_ti_modified_cpu);
767 }
768
769 bool CpuTi::isUsed()
770 {
771   return xbt_swag_size(p_actionSet);
772 }
773
774
775
776 double CpuTi::getAvailableSpeed()
777 {
778   m_powerScale = p_availTrace->getPowerScale(surf_get_clock());
779   return Cpu::getAvailableSpeed();
780 }
781
782 /**
783 * \brief Update the remaining amount of actions
784 *
785 * \param  now    Current time
786 */
787 void CpuTi::updateRemainingAmount(double now)
788 {
789   double area_total;
790   void* _action;
791   CpuTiActionPtr action;
792
793   /* already updated */
794   if (m_lastUpdate >= now)
795     return;
796
797 /* calcule the surface */
798   area_total = p_availTrace->integrate(m_lastUpdate, now) * m_powerPeak;
799   XBT_DEBUG("Flops total: %f, Last update %f", area_total,
800          m_lastUpdate);
801
802   xbt_swag_foreach(_action, p_actionSet) {
803     action = static_cast<CpuTiActionPtr>(_action);
804     /* action not running, skip it */
805     if (action->p_stateSet !=
806         getModel()->p_runningActionSet)
807       continue;
808
809     /* bogus priority, skip it */
810     if (action->m_priority <= 0)
811       continue;
812
813     /* action suspended, skip it */
814     if (action->m_suspended != 0)
815       continue;
816
817     /* action don't need update */
818     if (action->m_start >= now)
819       continue;
820
821     /* skip action that are finishing now */
822     if (action->m_finish >= 0
823         && action->m_finish <= now)
824       continue;
825
826     /* update remaining */
827     double_update(&(action->m_remains),
828                   area_total / (m_sumPriority *
829                                 action->m_priority));
830     XBT_DEBUG("Update remaining action(%p) remaining %f", action,
831            action->m_remains);
832   }
833   m_lastUpdate = now;
834 }
835
836 CpuActionPtr CpuTi::execute(double size)
837 {
838   return _execute(size);
839 }
840
841 CpuTiActionPtr CpuTi::_execute(double size)
842 {
843   XBT_IN("(%s,%g)", m_name, size);
844   CpuTiActionPtr action = new CpuTiAction(static_cast<CpuTiModelPtr>(p_model), size, p_stateCurrent != SURF_RESOURCE_ON);
845
846   action->p_cpu = this;
847   action->m_indexHeap = -1;
848
849   xbt_swag_insert(this, cpu_ti_modified_cpu);
850
851   xbt_swag_insert(action, p_actionSet);
852
853   action->m_suspended = 0;        /* Should be useless because of the
854               ยป                     calloc but it seems to help valgrind... */
855
856   XBT_OUT();
857   return action;
858 }
859
860
861 CpuActionPtr CpuTi::sleep(double duration)
862 {
863   if (duration > 0)
864     duration = MAX(duration, MAXMIN_PRECISION);
865
866   XBT_IN("(%s,%g)", m_name, duration);
867   CpuTiActionPtr action = _execute(1.0);
868   action->m_maxDuration = duration;
869   action->m_suspended = 2;
870   if (duration == NO_MAX_DURATION) {
871     /* Move to the *end* of the corresponding action set. This convention
872        is used to speed up update_resource_state  */
873     xbt_swag_remove(static_cast<ActionPtr>(action), action->p_stateSet);
874     action->p_stateSet = cpu_ti_running_action_set_that_does_not_need_being_checked;
875     xbt_swag_insert(static_cast<ActionPtr>(action), action->p_stateSet);
876   }
877   XBT_OUT();
878   return action;
879 }
880
881 void CpuTi::printCpuTiModel()
882 {
883   std::cout << getModel()->getName() << "<<plop"<< std::endl;
884 };
885
886 /**********
887  * Action *
888  **********/
889 static void cpu_ti_action_update_index_heap(void *action, int i)
890 {
891   ((CpuTiActionPtr)action)->updateIndexHeap(i); 
892 }
893 void CpuTiAction::updateIndexHeap(int i)
894 {
895   m_indexHeap = i;
896 }
897
898 void CpuTiAction::setState(e_surf_action_state_t state)
899 {
900   Action::setState(state);
901   xbt_swag_insert(p_cpu, cpu_ti_modified_cpu);
902 }
903
904 int CpuTiAction::unref()
905 {
906   m_refcount--;
907   if (!m_refcount) {
908     xbt_swag_remove(static_cast<ActionPtr>(this), p_stateSet);
909     /* remove from action_set */
910     xbt_swag_remove(this, p_cpu->p_actionSet);
911     /* remove from heap */
912     xbt_heap_remove(cpu_ti_action_heap, this->m_indexHeap);
913     xbt_swag_insert(p_cpu, cpu_ti_modified_cpu);
914     delete this;
915     return 1;
916   }
917   return 0;
918 }
919
920 void CpuTiAction::cancel()
921 {
922   this->setState(SURF_ACTION_FAILED);
923   xbt_heap_remove(cpu_ti_action_heap, this->m_indexHeap);
924   xbt_swag_insert(p_cpu, cpu_ti_modified_cpu);
925   return;
926 }
927
928 void CpuTiAction::recycle()
929 {
930   DIE_IMPOSSIBLE;
931 }
932
933 void CpuTiAction::suspend()
934 {
935   XBT_IN("(%p)", this);
936   if (m_suspended != 2) {
937     m_suspended = 1;
938     xbt_heap_remove(cpu_ti_action_heap, m_indexHeap);
939     xbt_swag_insert(p_cpu, cpu_ti_modified_cpu);
940   }
941   XBT_OUT();
942 }
943
944 void CpuTiAction::resume()
945 {
946   XBT_IN("(%p)", this);
947   if (m_suspended != 2) {
948     m_suspended = 0;
949     xbt_swag_insert(p_cpu, cpu_ti_modified_cpu);
950   }
951   XBT_OUT();
952 }
953
954 bool CpuTiAction::isSuspended()
955 {
956   return m_suspended == 1;
957 }
958
959 void CpuTiAction::setMaxDuration(double duration)
960 {
961   double min_finish;
962
963   XBT_IN("(%p,%g)", this, duration);
964
965   m_maxDuration = duration;
966
967   if (duration >= 0)
968     min_finish = (m_start + m_maxDuration) < m_finish ?
969                  (m_start + m_maxDuration) : m_finish;
970   else
971     min_finish = m_finish;
972
973 /* add in action heap */
974   if (m_indexHeap >= 0) {
975     CpuTiActionPtr heap_act = (CpuTiActionPtr)
976         xbt_heap_remove(cpu_ti_action_heap, m_indexHeap);
977     if (heap_act != this)
978       DIE_IMPOSSIBLE;
979   }
980   xbt_heap_push(cpu_ti_action_heap, this, min_finish);
981
982   XBT_OUT();
983 }
984
985 void CpuTiAction::setPriority(double priority)
986 {
987   XBT_IN("(%p,%g)", this, priority);
988   m_priority = priority;
989   xbt_swag_insert(p_cpu, cpu_ti_modified_cpu);
990   XBT_OUT();
991 }
992
993 double CpuTiAction::getRemains()
994 {
995   XBT_IN("(%p)", this);
996   p_cpu->updateRemainingAmount(surf_get_clock());
997   XBT_OUT();
998   return m_remains;
999 }
1000
1001 #endif /* SURF_MODEL_CPUTI_H_ */
1002