Logo AND Algorithmique Numérique Distribuée

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