Logo AND Algorithmique Numérique Distribuée

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