Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6ea015287d39c291ddf5447057c1035d8d6c8653
[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(simgrid::Host *host,
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 {
447   xbt_assert(core==1,"Multi-core not handled with this model yet");
448   xbt_assert(xbt_dynar_getfirst_as(speedPeak, double) > 0.0,
449       "Speed has to be >0.0. Did you forget to specify the mandatory speed attribute?");
450   CpuTi *cpu = new CpuTi(this, host, speedPeak, pstate, speedScale, speedTrace,
451                            core, stateInitial, stateTrace);
452   return cpu;
453 }
454
455 double CpuTiModel::shareResources(double now)
456 {
457   double min_action_duration = -1;
458
459 /* iterates over modified cpus to update share resources */
460   for(CpuTiList::iterator it(p_modifiedCpu->begin()), itend(p_modifiedCpu->end())
461      ; it != itend ;) {
462     CpuTi *ti = &*it;
463     ++it;
464     ti->updateActionsFinishTime(now);
465   }
466
467 /* get the min next event if heap not empty */
468   if (xbt_heap_size(p_tiActionHeap) > 0)
469     min_action_duration = xbt_heap_maxkey(p_tiActionHeap) - now;
470
471   XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
472
473   return min_action_duration;
474 }
475
476 void CpuTiModel::updateActionsState(double now, double /*delta*/)
477 {
478   while ((xbt_heap_size(p_tiActionHeap) > 0)
479          && (xbt_heap_maxkey(p_tiActionHeap) <= now)) {
480     CpuTiAction *action = (CpuTiAction*) xbt_heap_pop(p_tiActionHeap);
481     XBT_DEBUG("Action %p: finish", action);
482     action->finish();
483     /* set the remains to 0 due to precision problems when updating the remaining amount */
484     action->setRemains(0);
485     action->setState(SURF_ACTION_DONE);
486     /* update remaining amount of all actions */
487     action->p_cpu->updateRemainingAmount(surf_get_clock());
488   }
489 }
490
491 void CpuTiModel::addTraces()
492 {
493   xbt_dict_cursor_t cursor = NULL;
494   char *trace_name, *elm;
495
496   static int called = 0;
497
498   if (called)
499     return;
500   called = 1;
501
502 /* connect all traces relative to hosts */
503   xbt_dict_foreach(trace_connect_list_host_avail, cursor, trace_name, elm) {
504     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
505     CpuTi *cpu = static_cast<CpuTi*>(sg_host_surfcpu(sg_host_by_name(elm)));
506
507     xbt_assert(cpu, "Host %s undefined", elm);
508     xbt_assert(trace, "Trace %s undefined", trace_name);
509
510     if (cpu->p_stateEvent) {
511       XBT_DEBUG("Trace already configured for this CPU(%s), ignoring it",
512              elm);
513       continue;
514     }
515     XBT_DEBUG("Add state trace: %s to CPU(%s)", trace_name, elm);
516     cpu->p_stateEvent = tmgr_history_add_trace(history, trace, 0.0, 0, cpu);
517   }
518
519   xbt_dict_foreach(trace_connect_list_power, cursor, trace_name, elm) {
520     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
521     CpuTi *cpu = static_cast<CpuTi*>(sg_host_surfcpu(sg_host_by_name(elm)));
522
523     xbt_assert(cpu, "Host %s undefined", elm);
524     xbt_assert(trace, "Trace %s undefined", trace_name);
525
526     XBT_DEBUG("Add speed trace: %s to CPU(%s)", trace_name, elm);
527     if (cpu->p_availTrace)
528       delete cpu->p_availTrace;
529
530     cpu->p_availTrace = new CpuTiTgmr(trace, cpu->m_speedScale);
531
532     /* add a fake trace event if periodicity == 0 */
533     if (trace && xbt_dynar_length(trace->s_list.event_list) > 1) {
534       s_tmgr_event_t val;
535       xbt_dynar_get_cpy(trace->s_list.event_list,
536                         xbt_dynar_length(trace->s_list.event_list) - 1, &val);
537       if (val.delta == 0) {
538         tmgr_trace_t empty_trace;
539         empty_trace = tmgr_empty_trace_new();
540         cpu->p_speedEvent =
541             tmgr_history_add_trace(history, empty_trace,
542                                    cpu->p_availTrace->m_lastTime, 0, cpu);
543       }
544     }
545   }
546 }
547
548 /************
549  * Resource *
550  ************/
551 CpuTi::CpuTi(CpuTiModel *model, simgrid::Host *host, xbt_dynar_t speedPeak,
552         int pstate, double speedScale, tmgr_trace_t speedTrace, int core,
553         e_surf_resource_state_t stateInitial, tmgr_trace_t stateTrace)
554   : Cpu(model, host, NULL, pstate, core, 0, speedScale, stateInitial)
555 {
556   p_speedEvent = NULL;
557   m_speedScale = speedScale;
558   m_core = core;
559   tmgr_trace_t empty_trace;
560   s_tmgr_event_t val;
561   xbt_assert(core==1,"Multi-core not handled with this model yet");
562   XBT_DEBUG("speed scale %f", speedScale);
563   p_availTrace = new CpuTiTgmr(speedTrace, speedScale);
564
565   p_actionSet = new ActionTiList();
566
567   m_lastUpdate = 0;
568
569   xbt_dynar_get_cpy(speedPeak, 0, &m_speedPeak);
570   XBT_DEBUG("CPU create: peak=%f", m_speedPeak);
571
572   if (stateTrace)
573     p_stateEvent = tmgr_history_add_trace(history, stateTrace, 0.0, 0, this);
574   if (speedTrace && xbt_dynar_length(speedTrace->s_list.event_list) > 1) {
575     // add a fake trace event if periodicity == 0
576     xbt_dynar_get_cpy(speedTrace->s_list.event_list,
577                       xbt_dynar_length(speedTrace->s_list.event_list) - 1, &val);
578     if (val.delta == 0) {
579       empty_trace = tmgr_empty_trace_new();
580       p_speedEvent =
581         tmgr_history_add_trace(history, empty_trace,
582                                p_availTrace->m_lastTime, 0, this);
583     }
584   }
585 };
586
587 CpuTi::~CpuTi()
588 {
589   modified(false);
590   delete p_availTrace;
591   delete p_actionSet;
592 }
593
594 void CpuTi::updateState(tmgr_trace_event_t event_type,
595                         double value, double date)
596 {
597   CpuTiAction *action;
598
599   if (event_type == p_speedEvent) {
600     tmgr_trace_t speedTrace;
601     CpuTiTgmr *trace;
602     s_tmgr_event_t val;
603
604     XBT_DEBUG("Finish trace date: %f value %f date %f", surf_get_clock(),
605            value, date);
606     /* update remaining of actions and put in modified cpu swag */
607     updateRemainingAmount(date);
608
609     modified(true);
610
611     speedTrace = p_availTrace->p_speedTrace;
612     xbt_dynar_get_cpy(speedTrace->s_list.event_list,
613                       xbt_dynar_length(speedTrace->s_list.event_list) - 1, &val);
614     /* free old trace */
615     delete p_availTrace;
616     m_speedScale = val.value;
617
618     trace = new CpuTiTgmr(TRACE_FIXED, val.value);
619     XBT_DEBUG("value %f", val.value);
620
621     p_availTrace = trace;
622
623     if (tmgr_trace_event_free(event_type))
624       p_speedEvent = NULL;
625
626   } else if (event_type == p_stateEvent) {
627     if (value > 0) {
628       if(getState() == SURF_RESOURCE_OFF)
629         xbt_dynar_push_as(host_that_restart, char*, (char *)getName());
630       setState(SURF_RESOURCE_ON);
631     } else {
632       setState(SURF_RESOURCE_OFF);
633
634       /* put all action running on cpu to failed */
635       for(ActionTiList::iterator it(p_actionSet->begin()), itend(p_actionSet->end())
636           ; it != itend ; ++it) {
637               action = &*it;
638         if (action->getState() == SURF_ACTION_RUNNING
639          || action->getState() == SURF_ACTION_READY
640          || action->getState() == SURF_ACTION_NOT_IN_THE_SYSTEM) {
641           action->setFinishTime(date);
642           action->setState(SURF_ACTION_FAILED);
643           if (action->m_indexHeap >= 0) {
644             CpuTiAction *heap_act = (CpuTiAction*)
645                 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->p_tiActionHeap, action->m_indexHeap);
646             if (heap_act != action)
647               DIE_IMPOSSIBLE;
648           }
649         }
650       }
651     }
652     if (tmgr_trace_event_free(event_type))
653       p_stateEvent = NULL;
654   } else {
655     XBT_CRITICAL("Unknown event ! \n");
656     xbt_abort();
657   }
658
659   return;
660 }
661
662 void CpuTi::updateActionsFinishTime(double now)
663 {
664   CpuTiAction *action;
665   double sum_priority = 0.0, total_area, min_finish = -1;
666
667 /* update remaning amount of actions */
668 updateRemainingAmount(now);
669
670   for(ActionTiList::iterator it(p_actionSet->begin()), itend(p_actionSet->end())
671       ; it != itend ; ++it) {
672     action = &*it;
673     /* action not running, skip it */
674     if (action->getStateSet() !=
675         surf_cpu_model_pm->getRunningActionSet())
676       continue;
677
678     /* bogus priority, skip it */
679     if (action->getPriority() <= 0)
680       continue;
681
682     /* action suspended, skip it */
683     if (action->m_suspended != 0)
684       continue;
685
686     sum_priority += 1.0 / action->getPriority();
687   }
688   m_sumPriority = sum_priority;
689
690   for(ActionTiList::iterator it(p_actionSet->begin()), itend(p_actionSet->end())
691      ; it != itend ; ++it) {
692     action = &*it;
693     min_finish = -1;
694     /* action not running, skip it */
695     if (action->getStateSet() !=
696         surf_cpu_model_pm->getRunningActionSet())
697       continue;
698
699     /* verify if the action is really running on cpu */
700     if (action->m_suspended == 0 && action->getPriority() > 0) {
701       /* total area needed to finish the action. Used in trace integration */
702       total_area =
703           (action->getRemains()) * sum_priority *
704            action->getPriority();
705
706       total_area /= m_speedPeak;
707
708       action->setFinishTime(p_availTrace->solve(now, total_area));
709       /* verify which event will happen before (max_duration or finish time) */
710       if (action->getMaxDuration() != NO_MAX_DURATION &&
711           action->getStartTime() + action->getMaxDuration() < action->m_finish)
712         min_finish = action->getStartTime() + action->getMaxDuration();
713       else
714         min_finish = action->m_finish;
715     } else {
716       /* put the max duration time on heap */
717       if (action->getMaxDuration() != NO_MAX_DURATION)
718         min_finish = action->getStartTime() + action->getMaxDuration();
719     }
720     /* add in action heap */
721     XBT_DEBUG("action(%p) index %d", action, action->m_indexHeap);
722     if (action->m_indexHeap >= 0) {
723       CpuTiAction *heap_act = (CpuTiAction*)
724           xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->p_tiActionHeap, action->m_indexHeap);
725       if (heap_act != action)
726         DIE_IMPOSSIBLE;
727     }
728     if (min_finish != NO_MAX_DURATION)
729       xbt_heap_push(static_cast<CpuTiModel*>(getModel())->p_tiActionHeap, action, min_finish);
730
731     XBT_DEBUG
732         ("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f",
733          getName(), action, action->getStartTime(),
734          action->m_finish,
735          action->getMaxDuration());
736   }
737 /* remove from modified cpu */
738   modified(false);
739 }
740
741 bool CpuTi::isUsed()
742 {
743   return !p_actionSet->empty();
744 }
745
746 double CpuTi::getAvailableSpeed()
747 {
748   m_speedScale = p_availTrace->getPowerScale(surf_get_clock());
749   return Cpu::getAvailableSpeed();
750 }
751
752 /**
753 * \brief Update the remaining amount of actions
754 *
755 * \param  now    Current time
756 */
757 void CpuTi::updateRemainingAmount(double now)
758 {
759   double area_total;
760   CpuTiAction *action;
761
762   /* already updated */
763   if (m_lastUpdate >= now)
764     return;
765
766 /* calcule the surface */
767   area_total = p_availTrace->integrate(m_lastUpdate, now) * m_speedPeak;
768   XBT_DEBUG("Flops total: %f, Last update %f", area_total,
769          m_lastUpdate);
770
771   for(ActionTiList::iterator it(p_actionSet->begin()), itend(p_actionSet->end())
772      ; it != itend ; ++it) {
773     action = &*it;
774     /* action not running, skip it */
775     if (action->getStateSet() !=
776         getModel()->getRunningActionSet())
777       continue;
778
779     /* bogus priority, skip it */
780     if (action->getPriority() <= 0)
781       continue;
782
783     /* action suspended, skip it */
784     if (action->m_suspended != 0)
785       continue;
786
787     /* action don't need update */
788     if (action->getStartTime() >= now)
789       continue;
790
791     /* skip action that are finishing now */
792     if (action->m_finish >= 0
793         && action->m_finish <= now)
794       continue;
795
796     /* update remaining */
797     action->updateRemains(area_total / (m_sumPriority * action->getPriority()));
798     XBT_DEBUG("Update remaining action(%p) remaining %f", action,
799            action->m_remains);
800   }
801   m_lastUpdate = now;
802 }
803
804 CpuAction *CpuTi::execute(double size)
805 {
806   XBT_IN("(%s,%g)", getName(), size);
807   CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), size, getState() != SURF_RESOURCE_ON, this);
808
809   p_actionSet->push_back(*action);
810
811   XBT_OUT();
812   return action;
813 }
814
815
816 CpuAction *CpuTi::sleep(double duration)
817 {
818   if (duration > 0)
819     duration = MAX(duration, sg_surf_precision);
820
821   XBT_IN("(%s,%g)", getName(), duration);
822   CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), 1.0, getState() != SURF_RESOURCE_ON, this);
823
824   action->m_maxDuration = duration;
825   action->m_suspended = 2;
826   if (duration == NO_MAX_DURATION) {
827    /* Move to the *end* of the corresponding action set. This convention
828       is used to speed up update_resource_state  */
829         action->getStateSet()->erase(action->getStateSet()->iterator_to(*action));
830     action->p_stateSet = static_cast<CpuTiModel*>(getModel())->p_runningActionSetThatDoesNotNeedBeingChecked;
831     action->getStateSet()->push_back(*action);
832   }
833
834   p_actionSet->push_back(*action);
835
836   XBT_OUT();
837   return action;
838 }
839
840 void CpuTi::modified(bool modified){
841   CpuTiList *modifiedCpu = static_cast<CpuTiModel*>(getModel())->p_modifiedCpu;
842   if (modified) {
843     if (!cpu_ti_hook.is_linked()) {
844       modifiedCpu->push_back(*this);
845     }
846   } else {
847     if (cpu_ti_hook.is_linked()) {
848       modifiedCpu->erase(modifiedCpu->iterator_to(*this));
849     }
850   }
851 }
852
853 /**********
854  * Action *
855  **********/
856
857 CpuTiAction::CpuTiAction(CpuTiModel *model_, double cost, bool failed,
858                                  CpuTi *cpu)
859  : CpuAction(model_, cost, failed)
860 {
861   m_suspended = 0;        /* Should be useless because of the
862                                  calloc but it seems to help valgrind... */
863   p_cpu = cpu;
864   m_indexHeap = -1;
865   p_cpu->modified(true);
866 }
867
868 void CpuTiAction::updateIndexHeap(int i)
869 {
870   m_indexHeap = i;
871 }
872
873 void CpuTiAction::setState(e_surf_action_state_t state)
874 {
875   CpuAction::setState(state);
876   p_cpu->modified(true);
877 }
878
879 int CpuTiAction::unref()
880 {
881   m_refcount--;
882   if (!m_refcount) {
883         if (action_hook.is_linked())
884           getStateSet()->erase(getStateSet()->iterator_to(*this));
885     /* remove from action_set */
886     if (action_ti_hook.is_linked())
887       p_cpu->p_actionSet->erase(p_cpu->p_actionSet->iterator_to(*this));
888     /* remove from heap */
889     xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->p_tiActionHeap, this->m_indexHeap);
890     p_cpu->modified(true);
891     delete this;
892     return 1;
893   }
894   return 0;
895 }
896
897 void CpuTiAction::cancel()
898 {
899   this->setState(SURF_ACTION_FAILED);
900   xbt_heap_remove(getModel()->getActionHeap(), this->m_indexHeap);
901   p_cpu->modified(true);
902   return;
903 }
904
905 void CpuTiAction::suspend()
906 {
907   XBT_IN("(%p)", this);
908   if (m_suspended != 2) {
909     m_suspended = 1;
910     xbt_heap_remove(getModel()->getActionHeap(), m_indexHeap);
911     p_cpu->modified(true);
912   }
913   XBT_OUT();
914 }
915
916 void CpuTiAction::resume()
917 {
918   XBT_IN("(%p)", this);
919   if (m_suspended != 2) {
920     m_suspended = 0;
921     p_cpu->modified(true);
922   }
923   XBT_OUT();
924 }
925
926 bool CpuTiAction::isSuspended()
927 {
928   return m_suspended == 1;
929 }
930
931 void CpuTiAction::setMaxDuration(double duration)
932 {
933   double min_finish;
934
935   XBT_IN("(%p,%g)", this, duration);
936
937   m_maxDuration = duration;
938
939   if (duration >= 0)
940     min_finish = (getStartTime() + getMaxDuration()) < getFinishTime() ?
941                  (getStartTime() + getMaxDuration()) : getFinishTime();
942   else
943     min_finish = getFinishTime();
944
945 /* add in action heap */
946   if (m_indexHeap >= 0) {
947     CpuTiAction *heap_act = (CpuTiAction*)
948         xbt_heap_remove(getModel()->getActionHeap(), m_indexHeap);
949     if (heap_act != this)
950       DIE_IMPOSSIBLE;
951   }
952   xbt_heap_push(getModel()->getActionHeap(), this, min_finish);
953
954   XBT_OUT();
955 }
956
957 void CpuTiAction::setPriority(double priority)
958 {
959   XBT_IN("(%p,%g)", this, priority);
960   m_priority = priority;
961   p_cpu->modified(true);
962   XBT_OUT();
963 }
964
965 double CpuTiAction::getRemains()
966 {
967   XBT_IN("(%p)", this);
968   p_cpu->updateRemainingAmount(surf_get_clock());
969   XBT_OUT();
970   return m_remains;
971 }
972
973 }
974 }
975
976 #endif /* SURF_MODEL_CPUTI_H_ */