Logo AND Algorithmique Numérique Distribuée

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