Logo AND Algorithmique Numérique Distribuée

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