Logo AND Algorithmique Numérique Distribuée

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