Logo AND Algorithmique Numérique Distribuée

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