Logo AND Algorithmique Numérique Distribuée

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