Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
a9446205f5371c8ec667dfd40d48da335576426e
[simgrid.git] / src / surf / cpu_ti.cpp
1 #include "cpu_ti.hpp"
2 //#include "solver.hpp"
3 #include "trace_mgr_private.h"
4 #include "xbt/heap.h"
5
6 #ifndef SURF_MODEL_CPUTI_H_
7 #define SURF_MODEL_CPUTI_H_
8
9 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surfpp_cpu_tii, surfpp,
10                                 "Logging specific to the SURF CPU TRACE INTEGRATION module");
11
12 static xbt_swag_t cpu_ti_running_action_set_that_does_not_need_being_checked;
13 static xbt_swag_t cpu_ti_modified_cpu;
14 static xbt_heap_t cpu_ti_action_heap;
15
16 static CpuTiModelPtr surf_cpu_model = NULL;
17
18 static void cpu_ti_action_update_index_heap(void *action, int i);
19
20 /*********
21  * Trace *
22  *********/
23
24 CpuTiTrace::CpuTiTrace(tmgr_trace_t power_trace)
25 {
26   s_tmgr_event_t val;
27   unsigned int cpt;
28   double integral = 0;
29   double time = 0;
30   int i = 0;
31   p_timePoints = (double*) xbt_malloc0(sizeof(double) *
32                   (xbt_dynar_length(power_trace->s_list.event_list) + 1));
33   p_integral = (double*) xbt_malloc0(sizeof(double) *
34                   (xbt_dynar_length(power_trace->s_list.event_list) + 1));
35   m_nbPoints = xbt_dynar_length(power_trace->s_list.event_list);
36   xbt_dynar_foreach(power_trace->s_list.event_list, cpt, val) {
37     p_timePoints[i] = time;
38     p_integral[i] = integral;
39     integral += val.delta * val.value;
40     time += val.delta;
41     i++;
42   }
43   p_timePoints[i] = time;
44   p_integral[i] = integral;
45 }
46
47 CpuTiTrace::~CpuTiTrace()
48 {
49   xbt_free(p_timePoints);
50   xbt_free(p_integral);
51 }
52
53 CpuTiTgmr::~CpuTiTgmr()
54 {
55   if (p_trace)
56     delete p_trace;
57 }
58
59 /**
60 * \brief Integrate trace
61 *
62 * Wrapper around surf_cpu_integrate_trace_simple() to get
63 * the cyclic effect.
64 *
65 * \param trace Trace structure.
66 * \param a      Begin of interval
67 * \param b      End of interval
68 * \return the integrate value. -1 if an error occurs.
69 */
70 double CpuTiTgmr::integrate(double a, double b)
71 {
72   double first_chunk;
73   double middle_chunk;
74   double last_chunk;
75   int a_index, b_index;
76
77   if ((a < 0.0) || (a > b)) {
78     XBT_CRITICAL
79         ("Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative computation amount. Check your code.",
80          a, b);
81     xbt_abort();
82   }
83   if (a == b)
84     return 0.0;
85
86   if (m_type == TRACE_FIXED) {
87     return ((b - a) * m_value);
88   }
89
90   if (ceil(a / m_lastTime) == a / m_lastTime)
91     a_index = 1 + (int) (ceil(a / m_lastTime));
92   else
93     a_index = (int) (ceil(a / m_lastTime));
94
95   b_index = (int) (floor(b / m_lastTime));
96
97   if (a_index > b_index) {      /* Same chunk */
98     return p_trace->integrateSimple(a - (a_index -
99                                               1) * m_lastTime,
100                                          b -
101                                          (b_index) *
102                                          m_lastTime);
103   }
104
105   first_chunk = p_trace->integrateSimple(a - (a_index -
106                                                    1) *
107                                               m_lastTime,
108                                               m_lastTime);
109   middle_chunk = (b_index - a_index) * m_total;
110   last_chunk = p_trace->integrateSimple(0.0,
111                                              b -
112                                              (b_index) *
113                                              m_lastTime);
114
115   XBT_DEBUG("first_chunk=%.2f  middle_chunk=%.2f  last_chunk=%.2f\n",
116          first_chunk, middle_chunk, last_chunk);
117
118   return (first_chunk + middle_chunk + last_chunk);
119 }
120
121 /**
122  * \brief Auxiliary function to calculate the integral between a and b.
123  *     It simply calculates the integral at point a and b and returns the difference 
124  *   between them.
125  * \param trace    Trace structure
126  * \param a        Initial point
127  * \param b  Final point
128  * \return  Integral
129 */
130 double CpuTiTrace::integrateSimple(double a, double b)
131 {
132   return integrateSimplePoint(b) - integrateSimplePoint(a);
133 }
134
135 /**
136  * \brief Auxiliary function to calculate the integral at point a.
137  * \param trace    Trace structure
138  * \param a        point
139  * \return  Integral
140 */
141 double CpuTiTrace::integrateSimplePoint(double a)
142 {
143   double integral = 0;
144   int ind;
145   double a_aux = a;
146   ind = binarySearch(p_timePoints, a, 0, m_nbPoints - 1);
147   integral += p_integral[ind];
148   XBT_DEBUG
149       ("a %lf ind %d integral %lf ind + 1 %lf ind %lf time +1 %lf time %lf",
150        a, ind, integral, p_integral[ind + 1], p_integral[ind],
151        p_timePoints[ind + 1], p_timePoints[ind]);
152   double_update(&a_aux, p_timePoints[ind]);
153   if (a_aux > 0)
154     integral +=
155         ((p_integral[ind + 1] -
156           p_integral[ind]) / (p_timePoints[ind + 1] -
157                               p_timePoints[ind])) * (a - p_timePoints[ind]);
158   XBT_DEBUG("Integral a %lf = %lf", a, integral);
159
160   return integral;
161 }
162
163 /**
164 * \brief Calculate the time needed to execute "amount" on cpu.
165 *
166 * Here, amount can span multiple trace periods
167 *
168 * \param trace   CPU trace structure
169 * \param a        Initial time
170 * \param amount  Amount to be executed
171 * \return  End time
172 */
173 double CpuTiTgmr::solve(double a, double amount)
174 {
175   int quotient;
176   double reduced_b;
177   double reduced_amount;
178   double reduced_a;
179   double b;
180
181 /* Fix very small negative numbers */
182   if ((a < 0.0) && (a > -EPSILON)) {
183     a = 0.0;
184   }
185   if ((amount < 0.0) && (amount > -EPSILON)) {
186     amount = 0.0;
187   }
188
189 /* Sanity checks */
190   if ((a < 0.0) || (amount < 0.0)) {
191     XBT_CRITICAL
192         ("Error, invalid parameters [a = %.2f, amount = %.2f]. You probably have a task executing with negative computation amount. Check your code.",
193          a, amount);
194     xbt_abort();
195   }
196
197 /* At this point, a and amount are positive */
198
199   if (amount < EPSILON)
200     return a;
201
202 /* Is the trace fixed ? */
203   if (m_type == TRACE_FIXED) {
204     return (a + (amount / m_value));
205   }
206
207   XBT_DEBUG("amount %lf total %lf", amount, m_total);
208 /* Reduce the problem to one where amount <= trace_total */
209   quotient = (int) (floor(amount / m_total));
210   reduced_amount = (m_total) * ((amount / m_total) -
211                                      floor(amount / m_total));
212   reduced_a = a - (m_lastTime) * (int) (floor(a / m_lastTime));
213
214   XBT_DEBUG("Quotient: %d reduced_amount: %lf reduced_a: %lf", quotient,
215          reduced_amount, reduced_a);
216
217 /* Now solve for new_amount which is <= trace_total */
218 /*
219    fprintf(stderr,"reduced_a = %.2f\n",reduced_a);
220    fprintf(stderr,"reduced_amount = %.2f\n",reduced_amount);
221  */
222   reduced_b = solveSomewhatSimple(reduced_a, reduced_amount);
223
224 /* Re-map to the original b and amount */
225   b = (m_lastTime) * (int) (floor(a / m_lastTime)) +
226       (quotient * m_lastTime) + reduced_b;
227   return b;
228 }
229
230 /**
231 * \brief Auxiliary function to solve integral
232 *
233 * Here, amount is <= trace->total
234 * and a <=trace->last_time
235 *
236 */
237 double CpuTiTgmr::solveSomewhatSimple(double a, double amount)
238 {
239   double amount_till_end;
240   double b;
241
242   XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", a, amount);
243   amount_till_end = integrate(a, m_lastTime);
244 /*
245    fprintf(stderr,"amount_till_end=%.2f\n",amount_till_end);
246  */
247
248   if (amount_till_end > amount) {
249     b = p_trace->solveSimple(a, amount);
250   } else {
251     b = m_lastTime + p_trace->solveSimple(0.0, amount - amount_till_end);
252   }
253   return b;
254 }
255
256 /**
257  * \brief Auxiliary function to solve integral.
258  *  It returns the date when the requested amount of flops is available
259  * \param trace    Trace structure
260  * \param a        Initial point
261  * \param amount  Amount of flops 
262  * \return The date when amount is available.
263 */
264 double CpuTiTrace::solveSimple(double a, double amount)
265 {
266   double integral_a;
267   int ind;
268   double time;
269   integral_a = integrateSimplePoint(a);
270   ind = binarySearch(p_integral, integral_a + amount, 0, m_nbPoints - 1);
271   time = p_timePoints[ind];
272   time +=
273       (integral_a + amount -
274        p_integral[ind]) / ((p_integral[ind + 1] -
275                                  p_integral[ind]) /
276                                 (p_timePoints[ind + 1] -
277                                  p_timePoints[ind]));
278
279   return time;
280 }
281
282 /**
283 * \brief Auxiliary function to update the CPU power scale.
284 *
285 *  This function uses the trace structure to return the power scale at the determined time a.
286 * \param trace    Trace structure to search the updated power scale
287 * \param a        Time
288 * \return CPU power scale
289 */
290 double CpuTiTgmr::getPowerScale(double a)
291 {
292   double reduced_a;
293   int point;
294   s_tmgr_event_t val;
295
296   reduced_a = a - floor(a / m_lastTime) * m_lastTime;
297   point = p_trace->binarySearch(p_trace->p_timePoints, reduced_a, 0,
298                                 p_trace->m_nbPoints - 1);
299   xbt_dynar_get_cpy(p_powerTrace->s_list.event_list, point, &val);
300   return val.value;
301 }
302
303 /**
304 * \brief Creates a new integration trace from a tmgr_trace_t
305 *
306 * \param  power_trace    CPU availability trace
307 * \param  value          Percentage of CPU power available (useful to fixed tracing)
308 * \param  spacing        Initial spacing
309 * \return  Integration trace structure
310 */
311 CpuTiTgmr::CpuTiTgmr(tmgr_trace_t power_trace, double value)
312 {
313   double total_time = 0.0;
314   s_tmgr_event_t val;
315   unsigned int cpt;
316
317 /* no availability file, fixed trace */
318   if (!power_trace) {
319     m_type = TRACE_FIXED;
320     m_value = value;
321     XBT_DEBUG("No availabily trace. Constant value = %lf", value);
322     return;
323   }
324
325   /* only one point available, fixed trace */
326   if (xbt_dynar_length(power_trace->s_list.event_list) == 1) {
327     xbt_dynar_get_cpy(power_trace->s_list.event_list, 0, &val);
328     m_type = TRACE_FIXED;
329     m_value = val.value;
330     return;
331   }
332
333   m_type = TRACE_DYNAMIC;
334   p_powerTrace = power_trace;
335
336   /* count the total time of trace file */
337   xbt_dynar_foreach(power_trace->s_list.event_list, cpt, val) {
338     total_time += val.delta;
339   }
340   p_trace = new CpuTiTrace(power_trace);
341   m_lastTime = total_time;
342   m_total = p_trace->integrateSimple(0, total_time);
343
344   XBT_DEBUG("Total integral %lf, last_time %lf ",
345             m_total, m_lastTime);
346 }
347
348 /**
349  * \brief Binary search in array.
350  *  It returns the first point of the interval in which "a" is. 
351  * \param array    Array
352  * \param a        Value to search
353  * \param low     Low bound to search in array
354  * \param high    Upper bound to search in array
355  * \return Index of point
356 */
357 int CpuTiTrace::binarySearch(double *array, double a, int low, int high)
358 {
359   xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than"
360       " high (%d)", low, high);
361
362   int mid;
363   do {
364     mid = low + (high - low) / 2;
365     XBT_DEBUG("a %lf low %d high %d mid %d value %lf", a, low, high, mid,
366         array[mid]);
367
368     if (array[mid] > a)
369       high = mid;
370     else
371       low = mid;
372   }
373   while (low < high - 1);
374
375   return low;
376 }
377
378 /*********
379  * Model *
380  *********/
381
382 CpuTiModel::CpuTiModel() : CpuModel("cpu_ti")
383 {
384   xbt_assert(!surf_cpu_model,"CPU model already initialized. This should not happen.");
385   surf_cpu_model = this;
386   CpuTiAction action;
387   CpuTi cpu;
388
389   cpu_ti_running_action_set_that_does_not_need_being_checked =
390       xbt_swag_new(xbt_swag_offset(action, p_stateHookup));
391
392   cpu_ti_modified_cpu =
393       xbt_swag_new(xbt_swag_offset(cpu, p_modifiedCpuHookup));
394
395   cpu_ti_action_heap = xbt_heap_new(8, NULL);
396   xbt_heap_set_update_callback(cpu_ti_action_heap,
397                                cpu_ti_action_update_index_heap);
398   /* Define callbacks */
399   //TODO sg_platf_host_add_cb(parse_cpu_ti_init);
400   //TODO sg_platf_postparse_add_cb(add_traces_cpu_ti);
401
402   xbt_dynar_push(model_list, &surf_cpu_model);
403 }
404
405 CpuTiModel::~CpuTiModel()
406 {
407   void **cpu;
408   xbt_lib_cursor_t cursor;
409   char *key;
410
411   xbt_lib_foreach(host_lib, cursor, key, cpu){
412     if(cpu[SURF_CPU_LEVEL])
413     {
414         CpuTiPtr CPU = (CpuTiPtr) cpu[SURF_CPU_LEVEL];
415         xbt_swag_free(CPU->p_actionSet);
416         delete CPU->p_availTrace;
417     }
418   }
419
420   delete surf_cpu_model;
421   surf_cpu_model = NULL;
422
423   xbt_swag_free
424       (cpu_ti_running_action_set_that_does_not_need_being_checked);
425   xbt_swag_free(cpu_ti_modified_cpu);
426   cpu_ti_running_action_set_that_does_not_need_being_checked = NULL;
427   xbt_heap_free(cpu_ti_action_heap);
428 }
429
430 void CpuTiModel::parseInit(sg_platf_host_cbarg_t host)
431 {
432   createResource(host->id,
433         host->power_peak,
434         host->power_scale,
435         host->power_trace,
436         host->core_amount,
437         host->initial_state,
438         host->state_trace,
439         host->properties);
440 }
441
442 CpuTiPtr CpuTiModel::createResource(const char *name,
443                            double powerPeak,
444                            double powerScale,
445                            tmgr_trace_t powerTrace,
446                            int core,
447                            e_surf_resource_state_t stateInitial,
448                            tmgr_trace_t stateTrace,
449                            xbt_dict_t cpuProperties)
450 {
451   tmgr_trace_t empty_trace;
452   s_tmgr_event_t val;
453   CpuTiActionPtr cpuAction;
454   xbt_assert(core==1,"Multi-core not handled with this model yet");
455   xbt_assert(!surf_cpu_resource_priv(surf_cpu_resource_by_name(name)),
456               "Host '%s' declared several times in the platform file",
457               name);
458   CpuTiPtr cpu = new CpuTi(this, name, powerPeak, powerScale, powerTrace,
459                            core, stateInitial, stateTrace, cpuProperties);
460   xbt_lib_set(host_lib, name, SURF_CPU_LEVEL, cpu);
461   return (CpuTiPtr) xbt_lib_get_elm_or_null(host_lib, name);
462 }
463
464 CpuTiActionPtr CpuTiModel::createAction(double cost, bool failed)
465 {
466   return NULL;//new CpuTiAction(this, cost, failed);
467 }
468
469 double CpuTiModel::shareResources(double now)
470 {
471   void *_cpu, *_cpu_next;
472   double min_action_duration = -1;
473
474 /* iterates over modified cpus to update share resources */
475   xbt_swag_foreach_safe(_cpu, _cpu_next, cpu_ti_modified_cpu) {
476     ((CpuTiPtr)_cpu)->updateActionFinishDate(now);
477   }
478 /* get the min next event if heap not empty */
479   if (xbt_heap_size(cpu_ti_action_heap) > 0)
480     min_action_duration = xbt_heap_maxkey(cpu_ti_action_heap) - now;
481
482   XBT_DEBUG("Share resources, min next event date: %lf", min_action_duration);
483
484   return min_action_duration;
485 }
486
487 void CpuTiModel::updateActionsState(double now, double delta)
488 {
489   while ((xbt_heap_size(cpu_ti_action_heap) > 0)
490          && (xbt_heap_maxkey(cpu_ti_action_heap) <= now)) {
491     CpuTiActionPtr action = (CpuTiActionPtr) xbt_heap_pop(cpu_ti_action_heap);
492     XBT_DEBUG("Action %p: finish", action);
493     action->m_finish = surf_get_clock();
494     /* set the remains to 0 due to precision problems when updating the remaining amount */
495     action->m_remains = 0;
496     action->setState(SURF_ACTION_DONE);
497     /* update remaining amout of all actions */
498     action->p_cpu->updateRemainingAmount(surf_get_clock());
499   }
500 }
501
502 void CpuTiModel::addTraces()
503 {
504   xbt_dict_cursor_t cursor = NULL;
505   char *trace_name, *elm;
506
507   static int called = 0;
508
509   if (called)
510     return;
511   called = 1;
512
513 /* connect all traces relative to hosts */
514   xbt_dict_foreach(trace_connect_list_host_avail, cursor, trace_name, elm) {
515     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
516     CpuTiPtr cpu = (CpuTiPtr) surf_cpu_resource_priv(surf_cpu_resource_by_name(elm));
517
518     xbt_assert(cpu, "Host %s undefined", elm);
519     xbt_assert(trace, "Trace %s undefined", trace_name);
520
521     if (cpu->p_stateEvent) {
522       XBT_DEBUG("Trace already configured for this CPU(%s), ignoring it",
523              elm);
524       continue;
525     }
526     XBT_DEBUG("Add state trace: %s to CPU(%s)", trace_name, elm);
527     cpu->p_stateEvent = tmgr_history_add_trace(history, trace, 0.0, 0, cpu);
528   }
529
530   xbt_dict_foreach(trace_connect_list_power, cursor, trace_name, elm) {
531     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
532     CpuTiPtr cpu = (CpuTiPtr) surf_cpu_resource_priv(surf_cpu_resource_by_name(elm));
533
534     xbt_assert(cpu, "Host %s undefined", elm);
535     xbt_assert(trace, "Trace %s undefined", trace_name);
536
537     XBT_DEBUG("Add power trace: %s to CPU(%s)", trace_name, elm);
538     if (cpu->p_availTrace)
539       delete cpu->p_availTrace;
540
541     cpu->p_availTrace = new CpuTiTgmr(trace, cpu->m_powerScale);
542
543     /* add a fake trace event if periodicity == 0 */
544     if (trace && xbt_dynar_length(trace->s_list.event_list) > 1) {
545       s_tmgr_event_t val;
546       xbt_dynar_get_cpy(trace->s_list.event_list,
547                         xbt_dynar_length(trace->s_list.event_list) - 1, &val);
548       if (val.delta == 0) {
549         tmgr_trace_t empty_trace;
550         empty_trace = tmgr_empty_trace_new();
551         cpu->p_powerEvent =
552             tmgr_history_add_trace(history, empty_trace,
553                                    cpu->p_availTrace->m_lastTime, 0, cpu);
554       }
555     }
556   }
557 }
558
559 /************
560  * Resource *
561  ************/
562 CpuTi::CpuTi(CpuTiModelPtr model, const char *name, double powerPeak,
563         double powerScale, tmgr_trace_t powerTrace, int core,
564         e_surf_resource_state_t stateInitial, tmgr_trace_t stateTrace,
565         xbt_dict_t properties) :
566         Cpu(model, name, properties), p_stateCurrent(stateInitial) {
567   m_powerPeak = powerPeak;
568   m_powerScale = powerScale;
569   m_core = core;
570   tmgr_trace_t empty_trace;             
571   s_tmgr_event_t val;           
572   xbt_assert(core==1,"Multi-core not handled with this model yet");
573   XBT_DEBUG("power scale %lf", powerScale);
574   p_availTrace = new CpuTiTgmr(powerTrace, powerScale);
575   if (stateTrace)
576     p_stateEvent = tmgr_history_add_trace(history, stateTrace, 0.0, 0, this);
577   if (powerTrace && xbt_dynar_length(powerTrace->s_list.event_list) > 1) {
578     // add a fake trace event if periodicity == 0 
579     xbt_dynar_get_cpy(powerTrace->s_list.event_list,
580                       xbt_dynar_length(powerTrace->s_list.event_list) - 1, &val);
581     if (val.delta == 0) {
582       empty_trace = tmgr_empty_trace_new();
583        p_powerEvent =
584         tmgr_history_add_trace(history, empty_trace,
585                                p_availTrace->m_lastTime, 0, this);
586     }
587   }
588 };
589
590 void CpuTi::updateState(tmgr_trace_event_t event_type,
591                         double value, double date)
592 {
593   void *_action;
594   CpuTiActionPtr action;
595
596   surf_watched_hosts();
597
598   if (event_type == p_powerEvent) {
599     tmgr_trace_t power_trace;
600     CpuTiTgmrPtr trace;
601     s_tmgr_event_t val;
602
603     XBT_DEBUG("Finish trace date: %lf value %lf date %lf", surf_get_clock(),
604            value, date);
605     /* update remaining of actions and put in modified cpu swag */
606     updateRemainingAmount(date);
607     xbt_swag_insert(this, cpu_ti_modified_cpu);
608
609     power_trace = p_availTrace->p_powerTrace;
610     xbt_dynar_get_cpy(power_trace->s_list.event_list,
611                       xbt_dynar_length(power_trace->s_list.event_list) - 1, &val);
612     /* free old trace */
613     delete p_availTrace;
614     m_powerScale = val.value;
615
616     trace = new CpuTiTgmr(TRACE_FIXED, val.value);
617     XBT_DEBUG("value %lf", val.value);
618
619     p_availTrace = trace;
620
621     if (tmgr_trace_event_free(event_type))
622       p_powerEvent = NULL;
623
624   } else if (event_type == p_stateEvent) {
625     if (value > 0)
626       p_stateCurrent = SURF_RESOURCE_ON;
627     else {
628       p_stateCurrent = SURF_RESOURCE_OFF;
629
630       /* put all action running on cpu to failed */
631       xbt_swag_foreach(_action, p_actionSet) {
632         action = (CpuTiActionPtr) _action;
633         if (action->getState() == SURF_ACTION_RUNNING
634          || action->getState() == SURF_ACTION_READY
635          || action->getState() == SURF_ACTION_NOT_IN_THE_SYSTEM) {
636           action->m_finish = date;
637           action->setState(SURF_ACTION_FAILED);
638           if (action->m_indexHeap >= 0) {
639             CpuTiActionPtr heap_act = (CpuTiActionPtr)
640                 xbt_heap_remove(cpu_ti_action_heap, action->m_indexHeap);
641             if (heap_act != action)
642               DIE_IMPOSSIBLE;
643           }
644         }
645       }
646     }
647     if (tmgr_trace_event_free(event_type))
648       p_stateEvent = NULL;
649   } else {
650     XBT_CRITICAL("Unknown event ! \n");
651     xbt_abort();
652   }
653
654   return;
655 }
656
657 void CpuTi::updateActionFinishDate(double now)
658 {
659   void *_action;
660   CpuTiActionPtr action;
661   double sum_priority = 0.0, total_area, min_finish = -1;
662
663 /* update remaning amount of actions */
664 updateRemainingAmount(now);
665
666   xbt_swag_foreach(_action, p_actionSet) {
667     action = (CpuTiActionPtr) _action;
668     /* action not running, skip it */
669     if (action->p_stateSet !=
670         surf_cpu_model->p_runningActionSet)
671       continue;
672
673     /* bogus priority, skip it */
674     if (action->m_priority <= 0)
675       continue;
676
677     /* action suspended, skip it */
678     if (action->m_suspended != 0)
679       continue;
680
681     sum_priority += 1.0 / action->m_priority;
682   }
683   m_sumPriority = sum_priority;
684
685   xbt_swag_foreach(_action, p_actionSet) {
686     action = (CpuTiActionPtr) _action;
687     min_finish = -1;
688     /* action not running, skip it */
689     if (action->p_stateSet !=
690         surf_cpu_model->p_runningActionSet)
691       continue;
692
693     /* verify if the action is really running on cpu */
694     if (action->m_suspended == 0 && action->m_priority > 0) {
695       /* total area needed to finish the action. Used in trace integration */
696       total_area =
697           (action->m_remains) * sum_priority *
698            action->m_priority;
699
700       total_area /= m_powerPeak;
701
702       action->m_finish = p_availTrace->solve(now, total_area);
703       /* verify which event will happen before (max_duration or finish time) */
704       if (action->m_maxDuration != NO_MAX_DURATION &&
705           action->m_start + action->m_maxDuration < action->m_finish)
706         min_finish = action->m_start + action->m_maxDuration;
707       else
708         min_finish = action->m_finish;
709     } else {
710       /* put the max duration time on heap */
711       if (action->m_maxDuration != NO_MAX_DURATION)
712         min_finish = action->m_start + action->m_maxDuration;
713     }
714     /* add in action heap */
715     XBT_DEBUG("action(%p) index %d", action, action->m_indexHeap);
716     if (action->m_indexHeap >= 0) {
717       CpuTiActionPtr heap_act = (CpuTiActionPtr)
718           xbt_heap_remove(cpu_ti_action_heap, action->m_indexHeap);
719       if (heap_act != action)
720         DIE_IMPOSSIBLE;
721     }
722     if (min_finish != NO_MAX_DURATION)
723       xbt_heap_push(cpu_ti_action_heap, action, min_finish);
724
725     XBT_DEBUG
726         ("Update finish time: Cpu(%s) Action: %p, Start Time: %lf Finish Time: %lf Max duration %lf",
727          m_name, action, action->m_start,
728          action->m_finish,
729          action->m_maxDuration);
730   }
731 /* remove from modified cpu */
732   xbt_swag_remove(this, cpu_ti_modified_cpu);
733 }
734
735 CpuTiModelPtr CpuTi::getModel()
736 {
737   return static_cast<CpuTiModelPtr>(p_model);
738 }; 
739
740 bool CpuTi::isUsed()
741 {
742   return xbt_swag_size(p_actionSet);
743 }
744
745
746
747 double CpuTi::getAvailableSpeed()
748 {
749   m_powerScale = p_availTrace->getPowerScale(surf_get_clock());
750   return Cpu::getAvailableSpeed();
751 }
752
753 /**
754 * \brief Update the remaining amount of actions
755 *
756 * \param  now    Current time
757 */
758 void CpuTi::updateRemainingAmount(double now)
759 {
760   double area_total;
761   void* _action;
762   CpuTiActionPtr action;
763
764   /* already updated */
765   if (m_lastUpdate >= now)
766     return;
767
768 /* calcule the surface */
769   area_total = p_availTrace->integrate(m_lastUpdate, now) * m_powerPeak;
770   XBT_DEBUG("Flops total: %lf, Last update %lf", area_total,
771          m_lastUpdate);
772
773   xbt_swag_foreach(_action, p_actionSet) {
774     action = (CpuTiActionPtr) _action;
775     /* action not running, skip it */
776     if (action->p_stateSet !=
777         getModel()->p_runningActionSet)
778       continue;
779
780     /* bogus priority, skip it */
781     if (action->m_priority <= 0)
782       continue;
783
784     /* action suspended, skip it */
785     if (action->m_suspended != 0)
786       continue;
787
788     /* action don't need update */
789     if (action->m_start >= now)
790       continue;
791
792     /* skip action that are finishing now */
793     if (action->m_finish >= 0
794         && action->m_finish <= now)
795       continue;
796
797     /* update remaining */
798     double_update(&(action->m_remains),
799                   area_total / (m_sumPriority *
800                                 action->m_priority));
801     XBT_DEBUG("Update remaining action(%p) remaining %lf", action,
802            action->m_remains);
803   }
804   m_lastUpdate = now;
805 }
806
807 CpuActionPtr CpuTi::execute(double size)
808 {
809   XBT_IN("(%s,%g)", m_name, size);
810   CpuTiActionPtr action = new CpuTiAction(surf_cpu_model, size, p_stateCurrent != SURF_RESOURCE_ON);
811
812   action->p_cpu = this;
813   action->m_indexHeap = -1;
814
815   xbt_swag_insert(this, cpu_ti_modified_cpu);
816
817   xbt_swag_insert(action, p_actionSet);
818
819   action->m_suspended = 0;        /* Should be useless because of the
820                                    calloc but it seems to help valgrind... */
821
822   XBT_OUT();
823   return action;
824 }
825
826
827 CpuActionPtr CpuTi::sleep(double duration)
828 {
829   if (duration > 0)
830     duration = MAX(duration, MAXMIN_PRECISION);
831
832   XBT_IN("(%s,%g)", m_name, duration);
833   CpuActionPtr action = execute(1.0);
834   action->m_maxDuration = duration;
835   action->m_suspended = 2;
836   if (duration == NO_MAX_DURATION) {
837     /* Move to the *end* of the corresponding action set. This convention
838        is used to speed up update_resource_state  */
839     xbt_swag_remove(action, action->p_stateSet);
840     action->p_stateSet = cpu_ti_running_action_set_that_does_not_need_being_checked;
841     xbt_swag_insert(action, action->p_stateSet);
842   }
843   XBT_OUT();
844   return action;
845 }
846
847 void CpuTi::printCpuTiModel()
848 {
849   std::cout << getModel()->getName() << "<<plop"<< std::endl;
850 };
851
852 /**********
853  * Action *
854  **********/
855 static void cpu_ti_action_update_index_heap(void *action, int i)
856 {
857   ((CpuTiActionPtr)action)->updateIndexHeap(i); 
858 }
859 void CpuTiAction::updateIndexHeap(int i)
860 {
861   m_indexHeap = i;
862 }
863
864 void CpuTiAction::setState(e_surf_action_state_t state)
865 {
866   Action::setState(state);
867   xbt_swag_insert(surf_cpu_resource_priv(p_cpu), cpu_ti_modified_cpu);
868 }
869
870 int CpuTiAction::unref()
871 {
872   m_refcount--;
873   if (!m_refcount) {
874     xbt_swag_remove(this, p_stateSet);
875     /* remove from action_set */
876     xbt_swag_remove(this, ((CpuTiPtr)surf_cpu_resource_priv(p_cpu))->p_actionSet);
877     /* remove from heap */
878     xbt_heap_remove(cpu_ti_action_heap, this->m_indexHeap);
879     xbt_swag_insert(surf_cpu_resource_priv(p_cpu), cpu_ti_modified_cpu);
880     delete this;
881     return 1;
882   }
883   return 0;
884 }
885
886 void CpuTiAction::cancel()
887 {
888   this->setState(SURF_ACTION_FAILED);
889   xbt_heap_remove(cpu_ti_action_heap, this->m_indexHeap);
890   xbt_swag_insert(surf_cpu_resource_priv(p_cpu), cpu_ti_modified_cpu);
891   return;
892 }
893
894 void CpuTiAction::recycle()
895 {
896   DIE_IMPOSSIBLE;
897 }
898
899 void CpuTiAction::suspend()
900 {
901   XBT_IN("(%p)", this);
902   if (m_suspended != 2) {
903     m_suspended = 1;
904     xbt_heap_remove(cpu_ti_action_heap, m_indexHeap);
905     xbt_swag_insert(surf_cpu_resource_priv(p_cpu), cpu_ti_modified_cpu);
906   }
907   XBT_OUT();
908 }
909
910 void CpuTiAction::resume()
911 {
912   XBT_IN("(%p)", this);
913   if (m_suspended != 2) {
914     m_suspended = 0;
915     xbt_swag_insert(surf_cpu_resource_priv(p_cpu), cpu_ti_modified_cpu);
916   }
917   XBT_OUT();
918 }
919
920 bool CpuTiAction::isSuspended()
921 {
922   return m_suspended == 1;
923 }
924
925 void CpuTiAction::setMaxDuration(double duration)
926 {
927   double min_finish;
928
929   XBT_IN("(%p,%g)", this, duration);
930
931   m_maxDuration = duration;
932
933   if (duration >= 0)
934     min_finish = (m_start + m_maxDuration) < m_finish ?
935                  (m_start + m_maxDuration) : m_finish;
936   else
937     min_finish = m_finish;
938
939 /* add in action heap */
940   if (m_indexHeap >= 0) {
941     CpuTiActionPtr heap_act = (CpuTiActionPtr)
942         xbt_heap_remove(cpu_ti_action_heap, m_indexHeap);
943     if (heap_act != this)
944       DIE_IMPOSSIBLE;
945   }
946   xbt_heap_push(cpu_ti_action_heap, this, min_finish);
947
948   XBT_OUT();
949 }
950
951 void CpuTiAction::setPriority(double priority)
952 {
953   XBT_IN("(%p,%g)", this, priority);
954   m_priority = priority;
955   xbt_swag_insert(surf_cpu_resource_priv(p_cpu), cpu_ti_modified_cpu);
956   XBT_OUT();
957 }
958
959 double CpuTiAction::getRemains()
960 {
961   XBT_IN("(%p)", this);
962   ((CpuTiPtr)p_cpu)->updateRemainingAmount(surf_get_clock());
963   XBT_OUT();
964   return m_remains;
965 }
966
967 static void check() {
968   CpuTiActionPtr cupAction = new CpuTiAction(NULL, 0, true);
969 }
970
971 #endif /* SURF_MODEL_CPUTI_H_ */
972