Logo AND Algorithmique Numérique Distribuée

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