Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use simgrid::Host instead of xbt_dictelt_t for root main object
[simgrid.git] / src / surf / cpu_ti.cpp
1 /* Copyright (c) 2013-2015. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "cpu_ti.hpp"
8 #include "trace_mgr_private.h"
9 #include "xbt/heap.h"
10
11 #ifndef SURF_MODEL_CPUTI_H_
12 #define SURF_MODEL_CPUTI_H_
13
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf_cpu,
15                                 "Logging specific to the SURF CPU TRACE INTEGRATION module");
16
17 namespace simgrid {
18 namespace surf {
19   
20 static inline
21 void cpu_ti_action_update_index_heap(void *action, int i)
22 {
23   ((simgrid::surf::CpuTiAction*)action)->updateIndexHeap(i);
24 }
25
26 /*********
27  * Trace *
28  *********/
29
30 CpuTiTrace::CpuTiTrace(tmgr_trace_t speedTrace)
31 {
32   s_tmgr_event_t val;
33   unsigned int cpt;
34   double integral = 0;
35   double time = 0;
36   int i = 0;
37   p_timePoints = (double*) xbt_malloc0(sizeof(double) *
38                   (xbt_dynar_length(speedTrace->s_list.event_list) + 1));
39   p_integral = (double*) xbt_malloc0(sizeof(double) *
40                   (xbt_dynar_length(speedTrace->s_list.event_list) + 1));
41   m_nbPoints = xbt_dynar_length(speedTrace->s_list.event_list) + 1;
42   xbt_dynar_foreach(speedTrace->s_list.event_list, cpt, val) {
43     p_timePoints[i] = time;
44     p_integral[i] = integral;
45     integral += val.delta * val.value;
46     time += val.delta;
47     i++;
48   }
49   p_timePoints[i] = time;
50   p_integral[i] = integral;
51 }
52
53 CpuTiTrace::~CpuTiTrace()
54 {
55   xbt_free(p_timePoints);
56   xbt_free(p_integral);
57 }
58
59 CpuTiTgmr::~CpuTiTgmr()
60 {
61   if (p_trace)
62     delete p_trace;
63 }
64
65 /**
66 * \brief Integrate trace
67 *
68 * Wrapper around surf_cpu_integrate_trace_simple() to get
69 * the cyclic effect.
70 *
71 * \param trace Trace structure.
72 * \param a      Begin of interval
73 * \param b      End of interval
74 * \return the integrate value. -1 if an error occurs.
75 */
76 double CpuTiTgmr::integrate(double a, double b)
77 {
78   double first_chunk;
79   double middle_chunk;
80   double last_chunk;
81   int a_index, b_index;
82
83   if ((a < 0.0) || (a > b)) {
84     XBT_CRITICAL
85         ("Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative computation amount. Check your code.",
86          a, b);
87     xbt_abort();
88   }
89   if (a == b)
90     return 0.0;
91
92   if (m_type == TRACE_FIXED) {
93     return ((b - a) * m_value);
94   }
95
96   if (ceil(a / m_lastTime) == a / m_lastTime)
97     a_index = 1 + (int) (ceil(a / m_lastTime));
98   else
99     a_index = (int) (ceil(a / m_lastTime));
100
101   b_index = (int) (floor(b / m_lastTime));
102
103   if (a_index > b_index) {      /* Same chunk */
104     return p_trace->integrateSimple(a - (a_index -
105                                               1) * m_lastTime,
106                                          b -
107                                          (b_index) *
108                                          m_lastTime);
109   }
110
111   first_chunk = p_trace->integrateSimple(a - (a_index -
112                                                    1) *
113                                               m_lastTime,
114                                               m_lastTime);
115   middle_chunk = (b_index - a_index) * m_total;
116   last_chunk = p_trace->integrateSimple(0.0,
117                                              b -
118                                              (b_index) *
119                                              m_lastTime);
120
121   XBT_DEBUG("first_chunk=%.2f  middle_chunk=%.2f  last_chunk=%.2f\n",
122          first_chunk, middle_chunk, last_chunk);
123
124   return (first_chunk + middle_chunk + last_chunk);
125 }
126
127 /**
128  * \brief Auxiliary function to calculate the integral between a and b.
129  *     It simply calculates the integral at point a and b and returns the difference
130  *   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 calculate 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 Calculate 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  * CallBacks *
390  *************/
391
392 static void cpu_ti_define_callbacks()
393 {
394   sg_platf_postparse_add_cb(simgrid::surf::cpu_add_traces);
395 }
396
397 /*********
398  * Model *
399  *********/
400
401 void surf_cpu_model_init_ti()
402 {
403   xbt_assert(!surf_cpu_model_pm,"CPU model already initialized. This should not happen.");
404   xbt_assert(!surf_cpu_model_vm,"CPU model already initialized. This should not happen.");
405
406   surf_cpu_model_pm = new simgrid::surf::CpuTiModel();
407   surf_cpu_model_vm = new simgrid::surf::CpuTiModel();
408
409   cpu_ti_define_callbacks();
410   simgrid::surf::Model *model_pm = static_cast<simgrid::surf::Model*>(surf_cpu_model_pm);
411   simgrid::surf::Model *model_vm = static_cast<simgrid::surf::Model*>(surf_cpu_model_vm);
412   xbt_dynar_push(all_existing_models, &model_pm);
413   xbt_dynar_push(all_existing_models, &model_vm);
414 }
415
416 namespace simgrid {
417 namespace surf {
418
419 CpuTiModel::CpuTiModel() : CpuModel()
420 {
421   p_runningActionSetThatDoesNotNeedBeingChecked = new ActionList();
422
423   p_modifiedCpu = new CpuTiList();
424
425   p_tiActionHeap = xbt_heap_new(8, NULL);
426   xbt_heap_set_update_callback(p_tiActionHeap,
427                                cpu_ti_action_update_index_heap);
428 }
429
430 CpuTiModel::~CpuTiModel()
431 {
432   surf_cpu_model_pm = NULL;
433   delete p_runningActionSetThatDoesNotNeedBeingChecked;
434   delete p_modifiedCpu;
435   xbt_heap_free(p_tiActionHeap);
436 }
437
438 Cpu *CpuTiModel::createCpu(const char *name,
439                                xbt_dynar_t speedPeak,
440                                int pstate,
441                            double speedScale,
442                            tmgr_trace_t speedTrace,
443                            int core,
444                            e_surf_resource_state_t stateInitial,
445                            tmgr_trace_t stateTrace,
446                            xbt_dict_t cpuProperties)
447 {
448   xbt_assert(core==1,"Multi-core not handled with this model yet");
449   sg_host_t host = sg_host_by_name(name);
450   xbt_assert(xbt_dynar_getfirst_as(speedPeak, double) > 0.0,
451       "Speed has to be >0.0. Did you forget to specify the mandatory speed attribute?");
452   CpuTi *cpu = new CpuTi(this, name, speedPeak, pstate, speedScale, speedTrace,
453                            core, stateInitial, stateTrace, cpuProperties);
454   sg_host_surfcpu_register(host, cpu);
455   return cpu;
456 }
457
458 double CpuTiModel::shareResources(double now)
459 {
460   double min_action_duration = -1;
461
462 /* iterates over modified cpus to update share resources */
463   for(CpuTiList::iterator it(p_modifiedCpu->begin()), itend(p_modifiedCpu->end())
464      ; it != itend ;) {
465     CpuTi *ti = &*it;
466     ++it;
467     ti->updateActionsFinishTime(now);
468   }
469
470 /* get the min next event if heap not empty */
471   if (xbt_heap_size(p_tiActionHeap) > 0)
472     min_action_duration = xbt_heap_maxkey(p_tiActionHeap) - now;
473
474   XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
475
476   return min_action_duration;
477 }
478
479 void CpuTiModel::updateActionsState(double now, double /*delta*/)
480 {
481   while ((xbt_heap_size(p_tiActionHeap) > 0)
482          && (xbt_heap_maxkey(p_tiActionHeap) <= now)) {
483     CpuTiAction *action = (CpuTiAction*) xbt_heap_pop(p_tiActionHeap);
484     XBT_DEBUG("Action %p: finish", action);
485     action->finish();
486     /* set the remains to 0 due to precision problems when updating the remaining amount */
487     action->setRemains(0);
488     action->setState(SURF_ACTION_DONE);
489     /* update remaining amount of all actions */
490     action->p_cpu->updateRemainingAmount(surf_get_clock());
491   }
492 }
493
494 void CpuTiModel::addTraces()
495 {
496   xbt_dict_cursor_t cursor = NULL;
497   char *trace_name, *elm;
498
499   static int called = 0;
500
501   if (called)
502     return;
503   called = 1;
504
505 /* connect all traces relative to hosts */
506   xbt_dict_foreach(trace_connect_list_host_avail, cursor, trace_name, elm) {
507     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
508     CpuTi *cpu = static_cast<CpuTi*>(sg_host_surfcpu(sg_host_by_name(elm)));
509
510     xbt_assert(cpu, "Host %s undefined", elm);
511     xbt_assert(trace, "Trace %s undefined", trace_name);
512
513     if (cpu->p_stateEvent) {
514       XBT_DEBUG("Trace already configured for this CPU(%s), ignoring it",
515              elm);
516       continue;
517     }
518     XBT_DEBUG("Add state trace: %s to CPU(%s)", trace_name, elm);
519     cpu->p_stateEvent = tmgr_history_add_trace(history, trace, 0.0, 0, cpu);
520   }
521
522   xbt_dict_foreach(trace_connect_list_power, cursor, trace_name, elm) {
523     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
524     CpuTi *cpu = static_cast<CpuTi*>(sg_host_surfcpu(sg_host_by_name(elm)));
525
526     xbt_assert(cpu, "Host %s undefined", elm);
527     xbt_assert(trace, "Trace %s undefined", trace_name);
528
529     XBT_DEBUG("Add speed trace: %s to CPU(%s)", trace_name, elm);
530     if (cpu->p_availTrace)
531       delete cpu->p_availTrace;
532
533     cpu->p_availTrace = new CpuTiTgmr(trace, cpu->m_speedScale);
534
535     /* add a fake trace event if periodicity == 0 */
536     if (trace && xbt_dynar_length(trace->s_list.event_list) > 1) {
537       s_tmgr_event_t val;
538       xbt_dynar_get_cpy(trace->s_list.event_list,
539                         xbt_dynar_length(trace->s_list.event_list) - 1, &val);
540       if (val.delta == 0) {
541         tmgr_trace_t empty_trace;
542         empty_trace = tmgr_empty_trace_new();
543         cpu->p_speedEvent =
544             tmgr_history_add_trace(history, empty_trace,
545                                    cpu->p_availTrace->m_lastTime, 0, cpu);
546       }
547     }
548   }
549 }
550
551 /************
552  * Resource *
553  ************/
554 CpuTi::CpuTi(CpuTiModel *model, const char *name, xbt_dynar_t speedPeak,
555         int pstate, double speedScale, tmgr_trace_t speedTrace, int core,
556         e_surf_resource_state_t stateInitial, tmgr_trace_t stateTrace,
557               xbt_dict_t properties)
558   : Cpu(model, name, properties, core, 0, speedScale, stateInitial)
559 {
560   p_speedEvent = NULL;
561   m_speedScale = speedScale;
562   m_core = core;
563   tmgr_trace_t empty_trace;
564   s_tmgr_event_t val;
565   xbt_assert(core==1,"Multi-core not handled with this model yet");
566   XBT_DEBUG("speed scale %f", speedScale);
567   p_availTrace = new CpuTiTgmr(speedTrace, speedScale);
568
569   p_actionSet = new ActionTiList();
570
571   m_lastUpdate = 0;
572
573   xbt_dynar_get_cpy(speedPeak, 0, &m_speedPeak);
574   XBT_DEBUG("CPU create: peak=%f", m_speedPeak);
575
576   if (stateTrace)
577     p_stateEvent = tmgr_history_add_trace(history, stateTrace, 0.0, 0, this);
578   if (speedTrace && xbt_dynar_length(speedTrace->s_list.event_list) > 1) {
579     // add a fake trace event if periodicity == 0
580     xbt_dynar_get_cpy(speedTrace->s_list.event_list,
581                       xbt_dynar_length(speedTrace->s_list.event_list) - 1, &val);
582     if (val.delta == 0) {
583       empty_trace = tmgr_empty_trace_new();
584       p_speedEvent =
585         tmgr_history_add_trace(history, empty_trace,
586                                p_availTrace->m_lastTime, 0, this);
587     }
588   }
589 };
590
591 CpuTi::~CpuTi(){
592   modified(false);
593   delete p_availTrace;
594   delete p_actionSet;
595 }
596
597 void CpuTi::updateState(tmgr_trace_event_t event_type,
598                         double value, double date)
599 {
600   CpuTiAction *action;
601
602   if (event_type == p_speedEvent) {
603     tmgr_trace_t speedTrace;
604     CpuTiTgmr *trace;
605     s_tmgr_event_t val;
606
607     XBT_DEBUG("Finish trace date: %f value %f date %f", surf_get_clock(),
608            value, date);
609     /* update remaining of actions and put in modified cpu swag */
610     updateRemainingAmount(date);
611
612     modified(true);
613
614     speedTrace = p_availTrace->p_speedTrace;
615     xbt_dynar_get_cpy(speedTrace->s_list.event_list,
616                       xbt_dynar_length(speedTrace->s_list.event_list) - 1, &val);
617     /* free old trace */
618     delete p_availTrace;
619     m_speedScale = val.value;
620
621     trace = new CpuTiTgmr(TRACE_FIXED, val.value);
622     XBT_DEBUG("value %f", val.value);
623
624     p_availTrace = trace;
625
626     if (tmgr_trace_event_free(event_type))
627       p_speedEvent = NULL;
628
629   } else if (event_type == p_stateEvent) {
630     if (value > 0) {
631       if(getState() == SURF_RESOURCE_OFF)
632         xbt_dynar_push_as(host_that_restart, char*, (char *)getName());
633       setState(SURF_RESOURCE_ON);
634     } else {
635       setState(SURF_RESOURCE_OFF);
636
637       /* put all action running on cpu to failed */
638       for(ActionTiList::iterator it(p_actionSet->begin()), itend(p_actionSet->end())
639           ; it != itend ; ++it) {
640               action = &*it;
641         if (action->getState() == SURF_ACTION_RUNNING
642          || action->getState() == SURF_ACTION_READY
643          || action->getState() == SURF_ACTION_NOT_IN_THE_SYSTEM) {
644           action->setFinishTime(date);
645           action->setState(SURF_ACTION_FAILED);
646           if (action->m_indexHeap >= 0) {
647             CpuTiAction *heap_act = (CpuTiAction*)
648                 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->p_tiActionHeap, action->m_indexHeap);
649             if (heap_act != action)
650               DIE_IMPOSSIBLE;
651           }
652         }
653       }
654     }
655     if (tmgr_trace_event_free(event_type))
656       p_stateEvent = NULL;
657   } else {
658     XBT_CRITICAL("Unknown event ! \n");
659     xbt_abort();
660   }
661
662   return;
663 }
664
665 void CpuTi::updateActionsFinishTime(double now)
666 {
667   CpuTiAction *action;
668   double sum_priority = 0.0, total_area, min_finish = -1;
669
670 /* update remaning amount of actions */
671 updateRemainingAmount(now);
672
673   for(ActionTiList::iterator it(p_actionSet->begin()), itend(p_actionSet->end())
674       ; it != itend ; ++it) {
675     action = &*it;
676     /* action not running, skip it */
677     if (action->getStateSet() !=
678         surf_cpu_model_pm->getRunningActionSet())
679       continue;
680
681     /* bogus priority, skip it */
682     if (action->getPriority() <= 0)
683       continue;
684
685     /* action suspended, skip it */
686     if (action->m_suspended != 0)
687       continue;
688
689     sum_priority += 1.0 / action->getPriority();
690   }
691   m_sumPriority = sum_priority;
692
693   for(ActionTiList::iterator it(p_actionSet->begin()), itend(p_actionSet->end())
694      ; it != itend ; ++it) {
695     action = &*it;
696     min_finish = -1;
697     /* action not running, skip it */
698     if (action->getStateSet() !=
699         surf_cpu_model_pm->getRunningActionSet())
700       continue;
701
702     /* verify if the action is really running on cpu */
703     if (action->m_suspended == 0 && action->getPriority() > 0) {
704       /* total area needed to finish the action. Used in trace integration */
705       total_area =
706           (action->getRemains()) * sum_priority *
707            action->getPriority();
708
709       total_area /= m_speedPeak;
710
711       action->setFinishTime(p_availTrace->solve(now, total_area));
712       /* verify which event will happen before (max_duration or finish time) */
713       if (action->getMaxDuration() != NO_MAX_DURATION &&
714           action->getStartTime() + action->getMaxDuration() < action->m_finish)
715         min_finish = action->getStartTime() + action->getMaxDuration();
716       else
717         min_finish = action->m_finish;
718     } else {
719       /* put the max duration time on heap */
720       if (action->getMaxDuration() != NO_MAX_DURATION)
721         min_finish = action->getStartTime() + action->getMaxDuration();
722     }
723     /* add in action heap */
724     XBT_DEBUG("action(%p) index %d", action, action->m_indexHeap);
725     if (action->m_indexHeap >= 0) {
726       CpuTiAction *heap_act = (CpuTiAction*)
727           xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->p_tiActionHeap, action->m_indexHeap);
728       if (heap_act != action)
729         DIE_IMPOSSIBLE;
730     }
731     if (min_finish != NO_MAX_DURATION)
732       xbt_heap_push(static_cast<CpuTiModel*>(getModel())->p_tiActionHeap, action, min_finish);
733
734     XBT_DEBUG
735         ("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f",
736          getName(), action, action->getStartTime(),
737          action->m_finish,
738          action->getMaxDuration());
739   }
740 /* remove from modified cpu */
741   modified(false);
742 }
743
744 bool CpuTi::isUsed()
745 {
746   return !p_actionSet->empty();
747 }
748
749 double CpuTi::getAvailableSpeed()
750 {
751   m_speedScale = p_availTrace->getPowerScale(surf_get_clock());
752   return Cpu::getAvailableSpeed();
753 }
754
755 /**
756 * \brief Update the remaining amount of actions
757 *
758 * \param  now    Current time
759 */
760 void CpuTi::updateRemainingAmount(double now)
761 {
762   double area_total;
763   CpuTiAction *action;
764
765   /* already updated */
766   if (m_lastUpdate >= now)
767     return;
768
769 /* calcule the surface */
770   area_total = p_availTrace->integrate(m_lastUpdate, now) * m_speedPeak;
771   XBT_DEBUG("Flops total: %f, Last update %f", area_total,
772          m_lastUpdate);
773
774   for(ActionTiList::iterator it(p_actionSet->begin()), itend(p_actionSet->end())
775      ; it != itend ; ++it) {
776     action = &*it;
777     /* action not running, skip it */
778     if (action->getStateSet() !=
779         getModel()->getRunningActionSet())
780       continue;
781
782     /* bogus priority, skip it */
783     if (action->getPriority() <= 0)
784       continue;
785
786     /* action suspended, skip it */
787     if (action->m_suspended != 0)
788       continue;
789
790     /* action don't need update */
791     if (action->getStartTime() >= now)
792       continue;
793
794     /* skip action that are finishing now */
795     if (action->m_finish >= 0
796         && action->m_finish <= now)
797       continue;
798
799     /* update remaining */
800     action->updateRemains(area_total / (m_sumPriority * action->getPriority()));
801     XBT_DEBUG("Update remaining action(%p) remaining %f", action,
802            action->m_remains);
803   }
804   m_lastUpdate = now;
805 }
806
807 CpuAction *CpuTi::execute(double size)
808 {
809   XBT_IN("(%s,%g)", getName(), size);
810   CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), size, getState() != SURF_RESOURCE_ON, this);
811
812   p_actionSet->push_back(*action);
813
814   XBT_OUT();
815   return action;
816 }
817
818
819 CpuAction *CpuTi::sleep(double duration)
820 {
821   if (duration > 0)
822     duration = MAX(duration, sg_surf_precision);
823
824   XBT_IN("(%s,%g)", getName(), duration);
825   CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), 1.0, getState() != SURF_RESOURCE_ON, this);
826
827   action->m_maxDuration = duration;
828   action->m_suspended = 2;
829   if (duration == NO_MAX_DURATION) {
830    /* Move to the *end* of the corresponding action set. This convention
831       is used to speed up update_resource_state  */
832         action->getStateSet()->erase(action->getStateSet()->iterator_to(*action));
833     action->p_stateSet = static_cast<CpuTiModel*>(getModel())->p_runningActionSetThatDoesNotNeedBeingChecked;
834     action->getStateSet()->push_back(*action);
835   }
836
837   p_actionSet->push_back(*action);
838
839   XBT_OUT();
840   return action;
841 }
842
843 void CpuTi::modified(bool modified){
844   CpuTiList *modifiedCpu = static_cast<CpuTiModel*>(getModel())->p_modifiedCpu;
845   if (modified) {
846     if (!cpu_ti_hook.is_linked()) {
847       modifiedCpu->push_back(*this);
848     }
849   } else {
850     if (cpu_ti_hook.is_linked()) {
851       modifiedCpu->erase(modifiedCpu->iterator_to(*this));
852     }
853   }
854 }
855
856 /**********
857  * Action *
858  **********/
859
860 CpuTiAction::CpuTiAction(CpuTiModel *model_, double cost, bool failed,
861                                  CpuTi *cpu)
862  : CpuAction(model_, cost, failed)
863 {
864   m_suspended = 0;        /* Should be useless because of the
865                                  calloc but it seems to help valgrind... */
866   p_cpu = cpu;
867   m_indexHeap = -1;
868   p_cpu->modified(true);
869 }
870
871 void CpuTiAction::updateIndexHeap(int i)
872 {
873   m_indexHeap = i;
874 }
875
876 void CpuTiAction::setState(e_surf_action_state_t state)
877 {
878   CpuAction::setState(state);
879   p_cpu->modified(true);
880 }
881
882 int CpuTiAction::unref()
883 {
884   m_refcount--;
885   if (!m_refcount) {
886         if (action_hook.is_linked())
887           getStateSet()->erase(getStateSet()->iterator_to(*this));
888     /* remove from action_set */
889     if (action_ti_hook.is_linked())
890       p_cpu->p_actionSet->erase(p_cpu->p_actionSet->iterator_to(*this));
891     /* remove from heap */
892     xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->p_tiActionHeap, this->m_indexHeap);
893     p_cpu->modified(true);
894     delete this;
895     return 1;
896   }
897   return 0;
898 }
899
900 void CpuTiAction::cancel()
901 {
902   this->setState(SURF_ACTION_FAILED);
903   xbt_heap_remove(getModel()->getActionHeap(), this->m_indexHeap);
904   p_cpu->modified(true);
905   return;
906 }
907
908 void CpuTiAction::suspend()
909 {
910   XBT_IN("(%p)", this);
911   if (m_suspended != 2) {
912     m_suspended = 1;
913     xbt_heap_remove(getModel()->getActionHeap(), m_indexHeap);
914     p_cpu->modified(true);
915   }
916   XBT_OUT();
917 }
918
919 void CpuTiAction::resume()
920 {
921   XBT_IN("(%p)", this);
922   if (m_suspended != 2) {
923     m_suspended = 0;
924     p_cpu->modified(true);
925   }
926   XBT_OUT();
927 }
928
929 bool CpuTiAction::isSuspended()
930 {
931   return m_suspended == 1;
932 }
933
934 void CpuTiAction::setMaxDuration(double duration)
935 {
936   double min_finish;
937
938   XBT_IN("(%p,%g)", this, duration);
939
940   m_maxDuration = duration;
941
942   if (duration >= 0)
943     min_finish = (getStartTime() + getMaxDuration()) < getFinishTime() ?
944                  (getStartTime() + getMaxDuration()) : getFinishTime();
945   else
946     min_finish = getFinishTime();
947
948 /* add in action heap */
949   if (m_indexHeap >= 0) {
950     CpuTiAction *heap_act = (CpuTiAction*)
951         xbt_heap_remove(getModel()->getActionHeap(), m_indexHeap);
952     if (heap_act != this)
953       DIE_IMPOSSIBLE;
954   }
955   xbt_heap_push(getModel()->getActionHeap(), this, min_finish);
956
957   XBT_OUT();
958 }
959
960 void CpuTiAction::setPriority(double priority)
961 {
962   XBT_IN("(%p,%g)", this, priority);
963   m_priority = priority;
964   p_cpu->modified(true);
965   XBT_OUT();
966 }
967
968 double CpuTiAction::getRemains()
969 {
970   XBT_IN("(%p)", this);
971   p_cpu->updateRemainingAmount(surf_get_clock());
972   XBT_OUT();
973   return m_remains;
974 }
975
976 }
977 }
978
979 #endif /* SURF_MODEL_CPUTI_H_ */
980