Logo AND Algorithmique Numérique Distribuée

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