Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6a1eaeeb464509cadca02580241ecab1b4002d28
[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   cpu_ti_action_heap = xbt_heap_new(8, NULL);
387   xbt_heap_set_update_callback(cpu_ti_action_heap,
388                                cpu_ti_action_update_index_heap);
389
390   /* Define callbacks */
391   //TODO sg_platf_host_add_cb(parse_cpu_ti_init);
392   //TODO sg_platf_postparse_add_cb(add_traces_cpu_ti);
393
394   xbt_dynar_push(model_list, &surf_cpu_model);
395 }
396
397 CpuTiModel::~CpuTiModel()
398 {
399   void **cpu;
400   xbt_lib_cursor_t cursor;
401   char *key;
402
403   xbt_lib_foreach(host_lib, cursor, key, cpu){
404     if(cpu[SURF_CPU_LEVEL])
405     {
406         CpuTiPtr CPU = (CpuTiPtr) cpu[SURF_CPU_LEVEL];
407         xbt_swag_free(CPU->p_actionSet);
408         delete CPU->p_availTrace;
409     }
410   }
411
412   delete surf_cpu_model;
413   surf_cpu_model = NULL;
414
415   xbt_swag_free
416       (cpu_ti_running_action_set_that_does_not_need_being_checked);
417   xbt_swag_free(cpu_ti_modified_cpu);
418   cpu_ti_running_action_set_that_does_not_need_being_checked = NULL;
419   xbt_heap_free(cpu_ti_action_heap);
420 }
421
422 void CpuTiModel::parseInit(sg_platf_host_cbarg_t host)
423 {
424   createResource(host->id,
425         host->power_peak,
426         host->power_scale,
427         host->power_trace,
428         host->core_amount,
429         host->initial_state,
430         host->state_trace,
431         host->properties);
432 }
433
434 CpuTiPtr CpuTiModel::createResource(const char *name,
435                            double powerPeak,
436                            double powerScale,
437                            tmgr_trace_t powerTrace,
438                            int core,
439                            e_surf_resource_state_t stateInitial,
440                            tmgr_trace_t stateTrace,
441                            xbt_dict_t cpuProperties)
442 {
443   tmgr_trace_t empty_trace;
444   s_tmgr_event_t val;
445   CpuTiActionPtr cpuAction;
446   xbt_assert(core==1,"Multi-core not handled with this model yet");
447   xbt_assert(!surf_cpu_resource_priv(surf_cpu_resource_by_name(name)),
448               "Host '%s' declared several times in the platform file",
449               name);
450   CpuTiPtr cpu = new CpuTi(this, name, powerPeak, powerScale, powerTrace,
451                            core, stateInitial, stateTrace, cpuProperties);
452   xbt_lib_set(host_lib, name, SURF_CPU_LEVEL, cpu);
453   return (CpuTiPtr) xbt_lib_get_elm_or_null(host_lib, name);
454 }
455
456 CpuTiActionPtr CpuTiModel::createAction(double cost, bool failed)
457 {
458   return NULL;//new CpuTiAction(this, cost, failed);
459 }
460
461 double CpuTiModel::shareResources(double now)
462 {
463   void *_cpu, *_cpu_next;
464   double min_action_duration = -1;
465
466 /* iterates over modified cpus to update share resources */
467   xbt_swag_foreach_safe(_cpu, _cpu_next, cpu_ti_modified_cpu) {
468     ((CpuTiPtr)_cpu)->updateActionFinishDate(now);
469   }
470 /* get the min next event if heap not empty */
471   if (xbt_heap_size(cpu_ti_action_heap) > 0)
472     min_action_duration = xbt_heap_maxkey(cpu_ti_action_heap) - now;
473
474   XBT_DEBUG("Share resources, min next event date: %lf", 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(cpu_ti_action_heap) > 0)
482          && (xbt_heap_maxkey(cpu_ti_action_heap) <= now)) {
483     CpuTiActionPtr action = (CpuTiActionPtr) xbt_heap_pop(cpu_ti_action_heap);
484     XBT_DEBUG("Action %p: finish", action);
485     action->m_finish = surf_get_clock();
486     /* set the remains to 0 due to precision problems when updating the remaining amount */
487     action->m_remains = 0;
488     action->setState(SURF_ACTION_DONE);
489     /* update remaining amout of all actions */
490     action->p_cpu->updateRemainingAmount(surf_get_clock());
491   }
492 }
493
494
495 /************
496  * Resource *
497  ************/
498 CpuTi::CpuTi(CpuTiModelPtr model, const char *name, double powerPeak,
499         double powerScale, tmgr_trace_t powerTrace, int core,
500         e_surf_resource_state_t stateInitial, tmgr_trace_t stateTrace,
501         xbt_dict_t properties) :
502         Cpu(model, name, properties), m_powerPeak(powerPeak), m_powerScale(powerScale),
503         p_stateCurrent(stateInitial) {
504   tmgr_trace_t empty_trace;             
505   s_tmgr_event_t val;           
506   xbt_assert(core==1,"Multi-core not handled with this model yet");
507   XBT_DEBUG("power scale %lf", powerScale);
508   p_availTrace = new CpuTiTgmr(powerTrace, powerScale);
509   if (stateTrace)
510     p_stateEvent = tmgr_history_add_trace(history, stateTrace, 0.0, 0, this);
511   if (powerTrace && xbt_dynar_length(powerTrace->s_list.event_list) > 1) {
512     // add a fake trace event if periodicity == 0 
513     xbt_dynar_get_cpy(powerTrace->s_list.event_list,
514                       xbt_dynar_length(powerTrace->s_list.event_list) - 1, &val);
515     if (val.delta == 0) {
516       empty_trace = tmgr_empty_trace_new();
517        p_powerEvent =
518         tmgr_history_add_trace(history, empty_trace,
519                                p_availTrace->m_lastTime, 0, this);
520     }
521   }
522 };
523
524 void CpuTi::updateState(tmgr_trace_event_t event_type,
525                         double value, double date)
526 {
527   void *_action;
528   CpuTiActionPtr action;
529
530   surf_watched_hosts();
531
532   if (event_type == p_powerEvent) {
533     tmgr_trace_t power_trace;
534     CpuTiTgmrPtr trace;
535     s_tmgr_event_t val;
536
537     XBT_DEBUG("Finish trace date: %lf value %lf date %lf", surf_get_clock(),
538            value, date);
539     /* update remaining of actions and put in modified cpu swag */
540     updateRemainingAmount(date);
541     xbt_swag_insert(this, cpu_ti_modified_cpu);
542
543     power_trace = p_availTrace->p_powerTrace;
544     xbt_dynar_get_cpy(power_trace->s_list.event_list,
545                       xbt_dynar_length(power_trace->s_list.event_list) - 1, &val);
546     /* free old trace */
547     delete p_availTrace;
548     m_powerScale = val.value;
549
550     trace = new CpuTiTgmr(TRACE_FIXED, val.value);
551     XBT_DEBUG("value %lf", val.value);
552
553     p_availTrace = trace;
554
555     if (tmgr_trace_event_free(event_type))
556       p_powerEvent = NULL;
557
558   } else if (event_type == p_stateEvent) {
559     if (value > 0)
560       p_stateCurrent = SURF_RESOURCE_ON;
561     else {
562       p_stateCurrent = SURF_RESOURCE_OFF;
563
564       /* put all action running on cpu to failed */
565       xbt_swag_foreach(_action, p_actionSet) {
566         action = (CpuTiActionPtr) _action;
567         if (action->getState() == SURF_ACTION_RUNNING
568          || action->getState() == SURF_ACTION_READY
569          || action->getState() == SURF_ACTION_NOT_IN_THE_SYSTEM) {
570           action->m_finish = date;
571           action->setState(SURF_ACTION_FAILED);
572           if (action->m_indexHeap >= 0) {
573             CpuTiActionPtr heap_act = (CpuTiActionPtr)
574                 xbt_heap_remove(cpu_ti_action_heap, action->m_indexHeap);
575             if (heap_act != action)
576               DIE_IMPOSSIBLE;
577           }
578         }
579       }
580     }
581     if (tmgr_trace_event_free(event_type))
582       p_stateEvent = NULL;
583   } else {
584     XBT_CRITICAL("Unknown event ! \n");
585     xbt_abort();
586   }
587
588   return;
589 }
590
591 void CpuTi::updateActionFinishDate(double now)
592 {
593   void *_action;
594   CpuTiActionPtr action;
595   double sum_priority = 0.0, total_area, min_finish = -1;
596
597 /* update remaning amount of actions */
598 updateRemainingAmount(now);
599
600   xbt_swag_foreach(_action, p_actionSet) {
601     action = (CpuTiActionPtr) _action;
602     /* action not running, skip it */
603     if (action->p_stateSet !=
604         surf_cpu_model->p_runningActionSet)
605       continue;
606
607     /* bogus priority, skip it */
608     if (action->m_priority <= 0)
609       continue;
610
611     /* action suspended, skip it */
612     if (action->m_suspended != 0)
613       continue;
614
615     sum_priority += 1.0 / action->m_priority;
616   }
617   m_sumPriority = sum_priority;
618
619   xbt_swag_foreach(_action, p_actionSet) {
620     action = (CpuTiActionPtr) _action;
621     min_finish = -1;
622     /* action not running, skip it */
623     if (action->p_stateSet !=
624         surf_cpu_model->p_runningActionSet)
625       continue;
626
627     /* verify if the action is really running on cpu */
628     if (action->m_suspended == 0 && action->m_priority > 0) {
629       /* total area needed to finish the action. Used in trace integration */
630       total_area =
631           (action->m_remains) * sum_priority *
632            action->m_priority;
633
634       total_area /= m_powerPeak;
635
636       action->m_finish = p_availTrace->solve(now, total_area);
637       /* verify which event will happen before (max_duration or finish time) */
638       if (action->m_maxDuration != NO_MAX_DURATION &&
639           action->m_start + action->m_maxDuration < action->m_finish)
640         min_finish = action->m_start + action->m_maxDuration;
641       else
642         min_finish = action->m_finish;
643     } else {
644       /* put the max duration time on heap */
645       if (action->m_maxDuration != NO_MAX_DURATION)
646         min_finish = action->m_start + action->m_maxDuration;
647     }
648     /* add in action heap */
649     XBT_DEBUG("action(%p) index %d", action, action->m_indexHeap);
650     if (action->m_indexHeap >= 0) {
651       CpuTiActionPtr heap_act = (CpuTiActionPtr)
652           xbt_heap_remove(cpu_ti_action_heap, action->m_indexHeap);
653       if (heap_act != action)
654         DIE_IMPOSSIBLE;
655     }
656     if (min_finish != NO_MAX_DURATION)
657       xbt_heap_push(cpu_ti_action_heap, action, min_finish);
658
659     XBT_DEBUG
660         ("Update finish time: Cpu(%s) Action: %p, Start Time: %lf Finish Time: %lf Max duration %lf",
661          m_name, action, action->m_start,
662          action->m_finish,
663          action->m_maxDuration);
664   }
665 /* remove from modified cpu */
666   xbt_swag_remove(this, cpu_ti_modified_cpu);
667 }
668
669 CpuTiModelPtr CpuTi::getModel()
670 {
671   return static_cast<CpuTiModelPtr>(p_model);
672 }; 
673
674 bool CpuTi::isUsed()
675 {
676   return xbt_swag_size(p_actionSet);
677 }
678
679 e_surf_resource_state_t CpuTi::getState()
680 {
681   return m_stateCurrent;
682 }
683
684 double CpuTi::getSpeed(double load)
685 {
686   return load * m_powerPeak;
687 }
688
689 double CpuTi::getAvailableSpeed()
690 {
691   m_powerScale = p_availTrace->getPowerScale(surf_get_clock());
692 /* number between 0 and 1 */
693   return m_powerScale;
694 }
695
696 void CpuTi::addTraces()
697 {
698   xbt_dict_cursor_t cursor = NULL;
699   char *trace_name, *elm;
700
701   static int called = 0;
702
703   if (called)
704     return;
705   called = 1;
706
707 /* connect all traces relative to hosts */
708   xbt_dict_foreach(trace_connect_list_host_avail, cursor, trace_name, elm) {
709     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
710     CpuTiPtr cpu = (CpuTiPtr) surf_cpu_resource_priv(surf_cpu_resource_by_name(elm));
711
712     xbt_assert(cpu, "Host %s undefined", elm);
713     xbt_assert(trace, "Trace %s undefined", trace_name);
714
715     if (cpu->p_stateEvent) {
716       XBT_DEBUG("Trace already configured for this CPU(%s), ignoring it",
717              elm);
718       continue;
719     }
720     XBT_DEBUG("Add state trace: %s to CPU(%s)", trace_name, elm);
721     cpu->p_stateEvent = tmgr_history_add_trace(history, trace, 0.0, 0, cpu);
722   }
723
724   xbt_dict_foreach(trace_connect_list_power, cursor, trace_name, elm) {
725     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
726     CpuTiPtr cpu = (CpuTiPtr) surf_cpu_resource_priv(surf_cpu_resource_by_name(elm));
727
728     xbt_assert(cpu, "Host %s undefined", elm);
729     xbt_assert(trace, "Trace %s undefined", trace_name);
730
731     XBT_DEBUG("Add power trace: %s to CPU(%s)", trace_name, elm);
732     if (cpu->p_availTrace)
733       delete cpu->p_availTrace;
734
735     cpu->p_availTrace = new CpuTiTgmr(trace, cpu->m_powerScale);
736
737     /* add a fake trace event if periodicity == 0 */
738     if (trace && xbt_dynar_length(trace->s_list.event_list) > 1) {
739       s_tmgr_event_t val;
740       xbt_dynar_get_cpy(trace->s_list.event_list,
741                         xbt_dynar_length(trace->s_list.event_list) - 1, &val);
742       if (val.delta == 0) {
743         tmgr_trace_t empty_trace;
744         empty_trace = tmgr_empty_trace_new();
745         cpu->p_powerEvent =
746             tmgr_history_add_trace(history, empty_trace,
747                                    cpu->p_availTrace->m_lastTime, 0, cpu);
748       }
749     }
750   }
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