Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Cleanup.
[simgrid.git] / src / surf / cpu_ti.cpp
1 /* Copyright (c) 2013-2014. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "cpu_ti.hpp"
8 #include "trace_mgr_private.h"
9 #include "xbt/heap.h"
10
11 #ifndef SURF_MODEL_CPUTI_H_
12 #define SURF_MODEL_CPUTI_H_
13
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf_cpu,
15                                 "Logging specific to the SURF CPU TRACE INTEGRATION module");
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 = %f", 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 %f, last_time %f ",
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   xbt_assert(!surf_cpu_model_vm,"CPU model already initialized. This should not happen.");
404
405   surf_cpu_model_pm = new CpuTiModel();
406   surf_cpu_model_vm  = new CpuTiModel();
407
408   cpu_ti_define_callbacks();
409   ModelPtr model_pm = static_cast<ModelPtr>(surf_cpu_model_pm);
410   ModelPtr model_vm = static_cast<ModelPtr>(surf_cpu_model_vm);
411   xbt_dynar_push(model_list, &model_pm);
412   xbt_dynar_push(model_list, &model_vm);
413 }
414
415 CpuTiModel::CpuTiModel() : CpuModel("cpu_ti")
416 {
417   CpuTiPtr cpu = NULL;
418
419   p_runningActionSetThatDoesNotNeedBeingChecked = new ActionList();
420
421   p_modifiedCpu =
422       xbt_swag_new(xbt_swag_offset(*cpu, p_modifiedCpuHookup));
423
424   p_tiActionHeap = xbt_heap_new(8, NULL);
425   xbt_heap_set_update_callback(p_tiActionHeap,
426                                cpu_ti_action_update_index_heap);
427 }
428
429 CpuTiModel::~CpuTiModel()
430 {
431   surf_cpu_model_pm = NULL;
432
433   delete p_runningActionSetThatDoesNotNeedBeingChecked;
434   xbt_swag_free(p_modifiedCpu);
435   xbt_heap_free(p_tiActionHeap);
436 }
437
438 void CpuTiModel::parseInit(sg_platf_host_cbarg_t host)
439 {
440   createResource(host->id,
441         host->power_peak,
442         host->pstate,
443         host->power_scale,
444         host->power_trace,
445         host->core_amount,
446         host->initial_state,
447         host->state_trace,
448         host->properties);
449 }
450
451 CpuTiPtr CpuTiModel::createResource(const char *name,
452                                xbt_dynar_t powerPeak,
453                                int pstate,
454                            double powerScale,
455                            tmgr_trace_t powerTrace,
456                            int core,
457                            e_surf_resource_state_t stateInitial,
458                            tmgr_trace_t stateTrace,
459                            xbt_dict_t cpuProperties)
460 {
461   xbt_assert(core==1,"Multi-core not handled with this model yet");
462   xbt_assert(!surf_cpu_resource_priv(surf_cpu_resource_by_name(name)),
463               "Host '%s' declared several times in the platform file",
464               name);
465   CpuTiPtr cpu = new CpuTi(this, name, powerPeak, pstate, powerScale, powerTrace,
466                            core, stateInitial, stateTrace, cpuProperties);
467   xbt_lib_set(host_lib, name, SURF_CPU_LEVEL, static_cast<ResourcePtr>(cpu));
468   return cpu;
469 }
470
471 CpuTiActionPtr CpuTiModel::createAction(double /*cost*/, bool /*failed*/)
472 {
473   return NULL;//new CpuTiAction(this, cost, failed);
474 }
475
476 double CpuTiModel::shareResources(double now)
477 {
478   void *_cpu, *_cpu_next;
479   double min_action_duration = -1;
480
481 /* iterates over modified cpus to update share resources */
482   xbt_swag_foreach_safe(_cpu, _cpu_next, p_modifiedCpu) {
483     static_cast<CpuTiPtr>(_cpu)->updateActionsFinishTime(now);
484   }
485 /* get the min next event if heap not empty */
486   if (xbt_heap_size(p_tiActionHeap) > 0)
487     min_action_duration = xbt_heap_maxkey(p_tiActionHeap) - now;
488
489   XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
490
491   return min_action_duration;
492 }
493
494 void CpuTiModel::updateActionsState(double now, double /*delta*/)
495 {
496   while ((xbt_heap_size(p_tiActionHeap) > 0)
497          && (xbt_heap_maxkey(p_tiActionHeap) <= now)) {
498     CpuTiActionPtr action = (CpuTiActionPtr) xbt_heap_pop(p_tiActionHeap);
499     XBT_DEBUG("Action %p: finish", action);
500     action->finish();
501     /* set the remains to 0 due to precision problems when updating the remaining amount */
502     action->setRemains(0);
503     action->setState(SURF_ACTION_DONE);
504     /* update remaining amount of all actions */
505     action->p_cpu->updateRemainingAmount(surf_get_clock());
506   }
507 }
508
509 void CpuTiModel::addTraces()
510 {
511   xbt_dict_cursor_t cursor = NULL;
512   char *trace_name, *elm;
513
514   static int called = 0;
515
516   if (called)
517     return;
518   called = 1;
519
520 /* connect all traces relative to hosts */
521   xbt_dict_foreach(trace_connect_list_host_avail, cursor, trace_name, elm) {
522     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
523     CpuTiPtr cpu = static_cast<CpuTiPtr>(surf_cpu_resource_priv(surf_cpu_resource_by_name(elm)));
524
525     xbt_assert(cpu, "Host %s undefined", elm);
526     xbt_assert(trace, "Trace %s undefined", trace_name);
527
528     if (cpu->p_stateEvent) {
529       XBT_DEBUG("Trace already configured for this CPU(%s), ignoring it",
530              elm);
531       continue;
532     }
533     XBT_DEBUG("Add state trace: %s to CPU(%s)", trace_name, elm);
534     cpu->p_stateEvent = tmgr_history_add_trace(history, trace, 0.0, 0, static_cast<ResourcePtr>(cpu));
535   }
536
537   xbt_dict_foreach(trace_connect_list_power, cursor, trace_name, elm) {
538     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
539     CpuTiPtr cpu = static_cast<CpuTiPtr>(surf_cpu_resource_priv(surf_cpu_resource_by_name(elm)));
540
541     xbt_assert(cpu, "Host %s undefined", elm);
542     xbt_assert(trace, "Trace %s undefined", trace_name);
543
544     XBT_DEBUG("Add power trace: %s to CPU(%s)", trace_name, elm);
545     if (cpu->p_availTrace)
546       delete cpu->p_availTrace;
547
548     cpu->p_availTrace = new CpuTiTgmr(trace, cpu->m_powerScale);
549
550     /* add a fake trace event if periodicity == 0 */
551     if (trace && xbt_dynar_length(trace->s_list.event_list) > 1) {
552       s_tmgr_event_t val;
553       xbt_dynar_get_cpy(trace->s_list.event_list,
554                         xbt_dynar_length(trace->s_list.event_list) - 1, &val);
555       if (val.delta == 0) {
556         tmgr_trace_t empty_trace;
557         empty_trace = tmgr_empty_trace_new();
558         cpu->p_powerEvent =
559             tmgr_history_add_trace(history, empty_trace,
560                                    cpu->p_availTrace->m_lastTime, 0, static_cast<ResourcePtr>(cpu));
561       }
562     }
563   }
564 }
565
566 /************
567  * Resource *
568  ************/
569 CpuTi::CpuTi(CpuTiModelPtr model, const char *name, xbt_dynar_t powerPeak,
570         int pstate, double powerScale, tmgr_trace_t powerTrace, int core,
571         e_surf_resource_state_t stateInitial, tmgr_trace_t stateTrace,
572         xbt_dict_t properties)
573 : Cpu(model, name, properties, core, 0, powerScale)
574 {
575   p_powerEvent = NULL;
576   setState(stateInitial);
577   m_powerScale = powerScale;
578   m_core = core;
579   tmgr_trace_t empty_trace;             
580   s_tmgr_event_t val;           
581   xbt_assert(core==1,"Multi-core not handled with this model yet");
582   XBT_DEBUG("power scale %f", powerScale);
583   p_availTrace = new CpuTiTgmr(powerTrace, powerScale);
584
585   CpuTiActionPtr action = NULL;
586   p_actionSet = xbt_swag_new(xbt_swag_offset(*action, p_cpuListHookup));
587
588   m_lastUpdate = 0;
589
590   xbt_dynar_get_cpy(powerPeak, 0, &m_powerPeak);
591   xbt_dynar_free(&powerPeak);  /* kill memory leak */
592   m_pstate = pstate;
593   XBT_DEBUG("CPU create: peak=%f, pstate=%d", m_powerPeak, m_pstate);
594
595   p_modifiedCpuHookup.prev = 0;
596   p_modifiedCpuHookup.next = 0;
597
598   if (stateTrace)
599     p_stateEvent = tmgr_history_add_trace(history, stateTrace, 0.0, 0, static_cast<ResourcePtr>(this));
600   if (powerTrace && xbt_dynar_length(powerTrace->s_list.event_list) > 1) {
601     // add a fake trace event if periodicity == 0 
602     xbt_dynar_get_cpy(powerTrace->s_list.event_list,
603                       xbt_dynar_length(powerTrace->s_list.event_list) - 1, &val);
604     if (val.delta == 0) {
605       empty_trace = tmgr_empty_trace_new();
606       p_powerEvent =
607         tmgr_history_add_trace(history, empty_trace,
608                                p_availTrace->m_lastTime, 0, static_cast<ResourcePtr>(this));
609     }
610   }
611 };
612
613 CpuTi::~CpuTi(){
614 delete p_availTrace;
615 xbt_swag_free(p_actionSet);
616 }
617
618 void CpuTi::updateState(tmgr_trace_event_t event_type,
619                         double value, double date)
620 {
621   void *_action;
622   CpuTiActionPtr action;
623
624   if (event_type == p_powerEvent) {
625     tmgr_trace_t power_trace;
626     CpuTiTgmrPtr trace;
627     s_tmgr_event_t val;
628
629     XBT_DEBUG("Finish trace date: %f value %f date %f", surf_get_clock(),
630            value, date);
631     /* update remaining of actions and put in modified cpu swag */
632     updateRemainingAmount(date);
633     xbt_swag_insert(this, reinterpret_cast<CpuTiModelPtr>(getModel())->p_modifiedCpu);
634
635     power_trace = p_availTrace->p_powerTrace;
636     xbt_dynar_get_cpy(power_trace->s_list.event_list,
637                       xbt_dynar_length(power_trace->s_list.event_list) - 1, &val);
638     /* free old trace */
639     delete p_availTrace;
640     m_powerScale = val.value;
641
642     trace = new CpuTiTgmr(TRACE_FIXED, val.value);
643     XBT_DEBUG("value %f", val.value);
644
645     p_availTrace = trace;
646
647     if (tmgr_trace_event_free(event_type))
648       p_powerEvent = NULL;
649
650   } else if (event_type == p_stateEvent) {
651     if (value > 0) {
652       if(getState() == SURF_RESOURCE_OFF)
653         xbt_dynar_push_as(host_that_restart, char*, (char *)getName());
654       setState(SURF_RESOURCE_ON);
655     } else {
656       setState(SURF_RESOURCE_OFF);
657
658       /* put all action running on cpu to failed */
659       xbt_swag_foreach(_action, p_actionSet) {
660         action = static_cast<CpuTiActionPtr>(_action);
661         if (action->getState() == SURF_ACTION_RUNNING
662          || action->getState() == SURF_ACTION_READY
663          || action->getState() == SURF_ACTION_NOT_IN_THE_SYSTEM) {
664           action->setFinishTime(date);
665           action->setState(SURF_ACTION_FAILED);
666           if (action->m_indexHeap >= 0) {
667             CpuTiActionPtr heap_act = (CpuTiActionPtr)
668                 xbt_heap_remove(reinterpret_cast<CpuTiModelPtr>(getModel())->p_tiActionHeap, action->m_indexHeap);
669             if (heap_act != action)
670               DIE_IMPOSSIBLE;
671           }
672         }
673       }
674     }
675     if (tmgr_trace_event_free(event_type))
676       p_stateEvent = NULL;
677   } else {
678     XBT_CRITICAL("Unknown event ! \n");
679     xbt_abort();
680   }
681
682   return;
683 }
684
685 void CpuTi::updateActionsFinishTime(double now)
686 {
687   void *_action;
688   CpuTiActionPtr action;
689   double sum_priority = 0.0, total_area, min_finish = -1;
690
691 /* update remaning amount of actions */
692 updateRemainingAmount(now);
693
694   xbt_swag_foreach(_action, p_actionSet) {
695     action = static_cast<CpuTiActionPtr>(_action);
696     /* action not running, skip it */
697     if (action->getStateSet() !=
698         surf_cpu_model_pm->getRunningActionSet())
699       continue;
700
701     /* bogus priority, skip it */
702     if (action->getPriority() <= 0)
703       continue;
704
705     /* action suspended, skip it */
706     if (action->m_suspended != 0)
707       continue;
708
709     sum_priority += 1.0 / action->getPriority();
710   }
711   m_sumPriority = sum_priority;
712
713   xbt_swag_foreach(_action, p_actionSet) {
714     action = static_cast<CpuTiActionPtr>(_action);
715     min_finish = -1;
716     /* action not running, skip it */
717     if (action->getStateSet() !=
718         surf_cpu_model_pm->getRunningActionSet())
719       continue;
720
721     /* verify if the action is really running on cpu */
722     if (action->m_suspended == 0 && action->getPriority() > 0) {
723       /* total area needed to finish the action. Used in trace integration */
724       total_area =
725           (action->getRemains()) * sum_priority *
726            action->getPriority();
727
728       total_area /= m_powerPeak;
729
730       action->setFinishTime(p_availTrace->solve(now, total_area));
731       /* verify which event will happen before (max_duration or finish time) */
732       if (action->getMaxDuration() != NO_MAX_DURATION &&
733           action->getStartTime() + action->getMaxDuration() < action->m_finish)
734         min_finish = action->getStartTime() + action->getMaxDuration();
735       else
736         min_finish = action->m_finish;
737     } else {
738       /* put the max duration time on heap */
739       if (action->getMaxDuration() != NO_MAX_DURATION)
740         min_finish = action->getStartTime() + action->getMaxDuration();
741     }
742     /* add in action heap */
743     XBT_DEBUG("action(%p) index %d", action, action->m_indexHeap);
744     if (action->m_indexHeap >= 0) {
745       CpuTiActionPtr heap_act = (CpuTiActionPtr)
746           xbt_heap_remove(reinterpret_cast<CpuTiModelPtr>(getModel())->p_tiActionHeap, action->m_indexHeap);
747       if (heap_act != action)
748         DIE_IMPOSSIBLE;
749     }
750     if (min_finish != NO_MAX_DURATION)
751       xbt_heap_push(reinterpret_cast<CpuTiModelPtr>(getModel())->p_tiActionHeap, action, min_finish);
752
753     XBT_DEBUG
754         ("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f",
755          getName(), action, action->getStartTime(),
756          action->m_finish,
757          action->getMaxDuration());
758   }
759 /* remove from modified cpu */
760   xbt_swag_remove(this, reinterpret_cast<CpuTiModelPtr>(getModel())->p_modifiedCpu);
761 }
762
763 bool CpuTi::isUsed()
764 {
765   return xbt_swag_size(p_actionSet);
766 }
767
768
769
770 double CpuTi::getAvailableSpeed()
771 {
772   m_powerScale = p_availTrace->getPowerScale(surf_get_clock());
773   return Cpu::getAvailableSpeed();
774 }
775
776 /**
777 * \brief Update the remaining amount of actions
778 *
779 * \param  now    Current time
780 */
781 void CpuTi::updateRemainingAmount(double now)
782 {
783   double area_total;
784   void* _action;
785   CpuTiActionPtr action;
786
787   /* already updated */
788   if (m_lastUpdate >= now)
789     return;
790
791 /* calcule the surface */
792   area_total = p_availTrace->integrate(m_lastUpdate, now) * m_powerPeak;
793   XBT_DEBUG("Flops total: %f, Last update %f", area_total,
794          m_lastUpdate);
795
796   xbt_swag_foreach(_action, p_actionSet) {
797     action = static_cast<CpuTiActionPtr>(_action);
798     /* action not running, skip it */
799     if (action->getStateSet() !=
800         getModel()->getRunningActionSet())
801       continue;
802
803     /* bogus priority, skip it */
804     if (action->getPriority() <= 0)
805       continue;
806
807     /* action suspended, skip it */
808     if (action->m_suspended != 0)
809       continue;
810
811     /* action don't need update */
812     if (action->getStartTime() >= now)
813       continue;
814
815     /* skip action that are finishing now */
816     if (action->m_finish >= 0
817         && action->m_finish <= now)
818       continue;
819
820     /* update remaining */
821     action->updateRemains(area_total / (m_sumPriority * action->getPriority()));
822     XBT_DEBUG("Update remaining action(%p) remaining %f", action,
823            action->m_remains);
824   }
825   m_lastUpdate = now;
826 }
827
828 CpuActionPtr CpuTi::execute(double size)
829 {
830   XBT_IN("(%s,%g)", getName(), size);
831   CpuTiActionPtr action = new CpuTiAction(static_cast<CpuTiModelPtr>(getModel()), size, getState() != SURF_RESOURCE_ON, this);
832
833   xbt_swag_insert(action, p_actionSet);
834
835   XBT_OUT();
836   return action;
837 }
838
839
840 CpuActionPtr CpuTi::sleep(double duration)
841 {
842   if (duration > 0)
843     duration = MAX(duration, MAXMIN_PRECISION);
844
845   XBT_IN("(%s,%g)", getName(), duration);
846   CpuTiActionPtr action = new CpuTiAction(static_cast<CpuTiModelPtr>(getModel()), 1.0, getState() != SURF_RESOURCE_ON, this);
847
848   action->m_maxDuration = duration;
849   action->m_suspended = 2;
850   if (duration == NO_MAX_DURATION) {
851    /* Move to the *end* of the corresponding action set. This convention
852       is used to speed up update_resource_state  */
853         action->getStateSet()->erase(action->getStateSet()->iterator_to(*action));
854     action->p_stateSet = reinterpret_cast<CpuTiModelPtr>(getModel())->p_runningActionSetThatDoesNotNeedBeingChecked;
855     action->getStateSet()->push_back(*static_cast<ActionPtr>(action));
856   }
857
858   xbt_swag_insert(action, p_actionSet);
859
860   XBT_OUT();
861   return action;
862 }
863
864 /**********
865  * Action *
866  **********/
867
868 static void cpu_ti_action_update_index_heap(void *action, int i)
869 {
870 ((CpuTiActionPtr)action)->updateIndexHeap(i);
871 }
872
873 CpuTiAction::CpuTiAction(CpuTiModelPtr model_, double cost, bool failed,
874                                  CpuTiPtr cpu)
875  : CpuAction(model_, cost, failed)
876 {
877   p_cpuListHookup.next = 0;
878   p_cpuListHookup.prev = 0;
879
880   m_suspended = 0;        /* Should be useless because of the
881                                  calloc but it seems to help valgrind... */
882   p_cpu = cpu;
883   m_indexHeap = -1;
884   xbt_swag_insert(cpu, reinterpret_cast<CpuTiModelPtr>(getModel())->p_modifiedCpu);
885 }
886
887 void CpuTiAction::updateIndexHeap(int i)
888 {
889   m_indexHeap = i;
890 }
891
892 void CpuTiAction::setState(e_surf_action_state_t state)
893 {
894   Action::setState(state);
895   xbt_swag_insert(p_cpu, reinterpret_cast<CpuTiModelPtr>(getModel())->p_modifiedCpu);
896 }
897
898 int CpuTiAction::unref()
899 {
900   m_refcount--;
901   if (!m_refcount) {
902         if (actionHook::is_linked())
903           getStateSet()->erase(getStateSet()->iterator_to(*this));
904     /* remove from action_set */
905     xbt_swag_remove(this, p_cpu->p_actionSet);
906     /* remove from heap */
907     xbt_heap_remove(reinterpret_cast<CpuTiModelPtr>(getModel())->p_tiActionHeap, this->m_indexHeap);
908     xbt_swag_insert(p_cpu, reinterpret_cast<CpuTiModelPtr>(getModel())->p_modifiedCpu);
909     delete this;
910     return 1;
911   }
912   return 0;
913 }
914
915 void CpuTiAction::cancel()
916 {
917   this->setState(SURF_ACTION_FAILED);
918   xbt_heap_remove(getModel()->getActionHeap(), this->m_indexHeap);
919   xbt_swag_insert(p_cpu, reinterpret_cast<CpuTiModelPtr>(getModel())->p_modifiedCpu);
920   return;
921 }
922
923 void CpuTiAction::recycle()
924 {
925   DIE_IMPOSSIBLE;
926 }
927
928 void CpuTiAction::suspend()
929 {
930   XBT_IN("(%p)", this);
931   if (m_suspended != 2) {
932     m_suspended = 1;
933     xbt_heap_remove(getModel()->getActionHeap(), m_indexHeap);
934     xbt_swag_insert(p_cpu, reinterpret_cast<CpuTiModelPtr>(getModel())->p_modifiedCpu);
935   }
936   XBT_OUT();
937 }
938
939 void CpuTiAction::resume()
940 {
941   XBT_IN("(%p)", this);
942   if (m_suspended != 2) {
943     m_suspended = 0;
944     xbt_swag_insert(p_cpu, reinterpret_cast<CpuTiModelPtr>(getModel())->p_modifiedCpu);
945   }
946   XBT_OUT();
947 }
948
949 bool CpuTiAction::isSuspended()
950 {
951   return m_suspended == 1;
952 }
953
954 void CpuTiAction::setMaxDuration(double duration)
955 {
956   double min_finish;
957
958   XBT_IN("(%p,%g)", this, duration);
959
960   m_maxDuration = duration;
961
962   if (duration >= 0)
963     min_finish = (getStartTime() + getMaxDuration()) < getFinishTime() ?
964                  (getStartTime() + getMaxDuration()) : getFinishTime();
965   else
966     min_finish = getFinishTime();
967
968 /* add in action heap */
969   if (m_indexHeap >= 0) {
970     CpuTiActionPtr heap_act = (CpuTiActionPtr)
971         xbt_heap_remove(getModel()->getActionHeap(), m_indexHeap);
972     if (heap_act != this)
973       DIE_IMPOSSIBLE;
974   }
975   xbt_heap_push(getModel()->getActionHeap(), this, min_finish);
976
977   XBT_OUT();
978 }
979
980 void CpuTiAction::setPriority(double priority)
981 {
982   XBT_IN("(%p,%g)", this, priority);
983   m_priority = priority;
984   xbt_swag_insert(p_cpu, reinterpret_cast<CpuTiModelPtr>(getModel())->p_modifiedCpu);
985   XBT_OUT();
986 }
987
988 double CpuTiAction::getRemains()
989 {
990   XBT_IN("(%p)", this);
991   p_cpu->updateRemainingAmount(surf_get_clock());
992   XBT_OUT();
993   return m_remains;
994 }
995
996 #endif /* SURF_MODEL_CPUTI_H_ */
997