Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fix an example of vm migration
[simgrid.git] / src / surf / cpu_cas01.cpp
1 /* Copyright (c) 2009-2011, 2013. 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_cas01.hpp"
8 #include "cpu_ti.hpp"
9 #include "maxmin_private.h"
10 #include "simgrid/sg_config.h"
11
12 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_cas, surf_cpu,
13                                 "Logging specific to the SURF CPU IMPROVED module");
14
15 /*************
16  * CallBacks *
17  *************/
18
19 static void parse_cpu_init(sg_platf_host_cbarg_t host){
20   ((CpuCas01ModelPtr)surf_cpu_model_pm)->parseInit(host);
21 }
22
23 static void cpu_add_traces_cpu(){
24   surf_cpu_model_pm->addTraces();
25 }
26
27 static void cpu_define_callbacks()
28 {
29   sg_platf_host_add_cb(parse_cpu_init);
30   sg_platf_postparse_add_cb(cpu_add_traces_cpu);
31 }
32
33 /*********
34  * Model *
35  *********/
36 void surf_cpu_model_init_Cas01()
37 {
38   char *optim = xbt_cfg_get_string(_sg_cfg_set, "cpu/optim");
39
40   xbt_assert(!surf_cpu_model_pm);
41   xbt_assert(!surf_cpu_model_vm);
42
43   if (!strcmp(optim, "TI")) {
44     surf_cpu_model_init_ti();
45     return;
46   }
47
48   surf_cpu_model_pm = new CpuCas01Model();
49   surf_cpu_model_vm  = new CpuCas01Model();
50
51   cpu_define_callbacks();
52   ModelPtr model_pm = static_cast<ModelPtr>(surf_cpu_model_pm);
53   ModelPtr model_vm = static_cast<ModelPtr>(surf_cpu_model_vm);
54   xbt_dynar_push(model_list, &model_pm);
55   xbt_dynar_push(model_list, &model_vm);
56 }
57
58 CpuCas01Model::CpuCas01Model() : CpuModel("cpu")
59 {
60   ActionPtr action = NULL;
61   ActionLmmPtr actionlmm = NULL;
62
63   char *optim = xbt_cfg_get_string(_sg_cfg_set, "cpu/optim");
64   int select = xbt_cfg_get_boolean(_sg_cfg_set, "cpu/maxmin_selective_update");
65
66   if (!strcmp(optim, "Full")) {
67     p_updateMechanism = UM_FULL;
68     m_selectiveUpdate = select;
69   } else if (!strcmp(optim, "Lazy")) {
70     p_updateMechanism = UM_LAZY;
71     m_selectiveUpdate = 1;
72     xbt_assert((select == 1)
73                ||
74                (xbt_cfg_is_default_value
75                 (_sg_cfg_set, "cpu/maxmin_selective_update")),
76                "Disabling selective update while using the lazy update mechanism is dumb!");
77   } else {
78     xbt_die("Unsupported optimization (%s) for this model", optim);
79   }
80
81   p_cpuRunningActionSetThatDoesNotNeedBeingChecked =
82       xbt_swag_new(xbt_swag_offset(*action, p_stateHookup));
83
84   if (getUpdateMechanism() == UM_LAZY) {
85         shareResources = &CpuCas01Model::shareResourcesLazy;
86         updateActionsState = &CpuCas01Model::updateActionsStateLazy;
87
88   } else if (getUpdateMechanism() == UM_FULL) {
89         shareResources = &CpuCas01Model::shareResourcesFull;
90         updateActionsState = &CpuCas01Model::updateActionsStateFull;
91   } else
92     xbt_die("Invalid cpu update mechanism!");
93
94   if (!p_maxminSystem) {
95     p_maxminSystem = lmm_system_new(m_selectiveUpdate);
96   }
97
98   if (getUpdateMechanism() == UM_LAZY) {
99     p_actionHeap = xbt_heap_new(8, NULL);
100     xbt_heap_set_update_callback(p_actionHeap,  surf_action_lmm_update_index_heap);
101     p_modifiedSet = xbt_swag_new(xbt_swag_offset(*actionlmm, p_actionListHookup));
102     p_maxminSystem->keep_track = p_modifiedSet;
103   }
104 }
105
106 CpuCas01Model::~CpuCas01Model()
107 {
108   lmm_system_free(p_maxminSystem);
109   p_maxminSystem = NULL;
110
111   if (p_actionHeap)
112     xbt_heap_free(p_actionHeap);
113   xbt_swag_free(p_modifiedSet);
114
115   surf_cpu_model_pm = NULL;
116
117   xbt_swag_free(p_cpuRunningActionSetThatDoesNotNeedBeingChecked);
118 }
119
120 void CpuCas01Model::parseInit(sg_platf_host_cbarg_t host)
121 {
122   createResource(host->id,
123         host->power_peak,
124         host->pstate,
125         host->power_scale,
126         host->power_trace,
127         host->core_amount,
128         host->initial_state,
129         host->state_trace,
130         host->properties);
131 }
132
133 CpuPtr CpuCas01Model::createResource(const char *name, xbt_dynar_t power_peak,
134                                   int pstate, double power_scale,
135                           tmgr_trace_t power_trace, int core,
136                           e_surf_resource_state_t state_initial,
137                           tmgr_trace_t state_trace,
138                           xbt_dict_t cpu_properties)
139 {
140   CpuPtr cpu = NULL;
141   xbt_assert(!surf_cpu_resource_priv(surf_cpu_resource_by_name(name)),
142              "Host '%s' declared several times in the platform file",
143              name);
144   xbt_assert(xbt_dynar_getfirst_as(power_peak, double) > 0.0,
145       "Power has to be >0.0");
146   xbt_assert(core > 0, "Invalid number of cores %d", core);
147
148   cpu = new CpuCas01Lmm(this, name, power_peak, pstate, power_scale, power_trace, core, state_initial, state_trace, cpu_properties);
149   xbt_lib_set(host_lib, name, SURF_CPU_LEVEL, static_cast<ResourcePtr>(cpu));
150
151   return cpu;
152 }
153
154 double CpuCas01Model::shareResourcesFull(double /*now*/)
155 {
156   return Model::shareResourcesMaxMin(getRunningActionSet(),
157                              p_maxminSystem, lmm_solve);
158 }
159
160 void CpuCas01Model::addTraces()
161 {
162   xbt_dict_cursor_t cursor = NULL;
163   char *trace_name, *elm;
164   static int called = 0;
165   if (called)
166     return;
167   called = 1;
168
169   /* connect all traces relative to hosts */
170   xbt_dict_foreach(trace_connect_list_host_avail, cursor, trace_name, elm) {
171     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
172     CpuCas01LmmPtr host = static_cast<CpuCas01LmmPtr>(surf_cpu_resource_priv(surf_cpu_resource_by_name(elm)));
173
174     xbt_assert(host, "Host %s undefined", elm);
175     xbt_assert(trace, "Trace %s undefined", trace_name);
176
177     host->p_stateEvent = tmgr_history_add_trace(history, trace, 0.0, 0, static_cast<ResourcePtr>(host));
178   }
179
180   xbt_dict_foreach(trace_connect_list_power, cursor, trace_name, elm) {
181     tmgr_trace_t trace = (tmgr_trace_t) xbt_dict_get_or_null(traces_set_list, trace_name);
182     CpuCas01LmmPtr host = dynamic_cast<CpuCas01LmmPtr>(static_cast<ResourcePtr>(surf_cpu_resource_priv(surf_cpu_resource_by_name(elm))));
183
184     xbt_assert(host, "Host %s undefined", elm);
185     xbt_assert(trace, "Trace %s undefined", trace_name);
186
187     host->p_powerEvent =
188         tmgr_history_add_trace(history, trace, 0.0, 0, static_cast<ResourcePtr>(host));
189   }
190 }
191
192 /************
193  * Resource *
194  ************/
195 CpuCas01Lmm::CpuCas01Lmm(CpuCas01ModelPtr model_, const char *name, xbt_dynar_t powerPeak,
196                          int pstate, double powerScale, tmgr_trace_t powerTrace, int core,
197                          e_surf_resource_state_t stateInitial, tmgr_trace_t stateTrace,
198                          xbt_dict_t properties)
199 : Resource(model_, name, properties)
200 , CpuLmm(lmm_constraint_new(getModel()->getMaxminSystem(), this, core * powerScale * xbt_dynar_get_as(powerPeak, pstate, double)),
201                  core, xbt_dynar_get_as(powerPeak, pstate, double), powerScale) {
202   p_powerEvent = NULL;
203   p_powerPeakList = powerPeak;
204   m_pstate = pstate;
205
206   p_energy = xbt_new(s_energy_cpu_cas01_t, 1);
207   p_energy->total_energy = 0;
208   p_energy->power_range_watts_list = getWattsRangeList();
209   p_energy->last_updated = surf_get_clock();
210
211   XBT_DEBUG("CPU create: peak=%f, pstate=%d", m_powerPeak, m_pstate);
212
213   m_core = core;
214   m_stateCurrent = stateInitial;
215   if (powerTrace)
216     p_powerEvent = tmgr_history_add_trace(history, powerTrace, 0.0, 0, static_cast<ResourcePtr>(this));
217
218   if (stateTrace)
219     p_stateEvent = tmgr_history_add_trace(history, stateTrace, 0.0, 0, static_cast<ResourcePtr>(this));
220 }
221
222 CpuCas01Lmm::~CpuCas01Lmm(){
223   unsigned int iter;
224   xbt_dynar_t power_tuple = NULL;
225   xbt_dynar_foreach(p_energy->power_range_watts_list, iter, power_tuple)
226     xbt_dynar_free(&power_tuple);
227   xbt_dynar_free(&p_energy->power_range_watts_list);
228   xbt_dynar_free(&p_powerPeakList);
229   xbt_free(p_energy);
230 }
231
232 bool CpuCas01Lmm::isUsed()
233 {
234   return lmm_constraint_used(getModel()->getMaxminSystem(), constraint());
235 }
236
237 void CpuCas01Lmm::updateState(tmgr_trace_event_t event_type, double value, double date)
238 {
239   lmm_variable_t var = NULL;
240   lmm_element_t elem = NULL;
241
242   if (event_type == p_powerEvent) {
243         /* TODO (Hypervisor): do the same thing for constraint_core[i] */
244         xbt_assert(m_core == 1, "FIXME: add power scaling code also for constraint_core[i]");
245
246     m_powerScale = value;
247     lmm_update_constraint_bound(surf_cpu_model_pm->getMaxminSystem(), constraint(),
248                                 m_core * m_powerScale *
249                                 m_powerPeak);
250 #ifdef HAVE_TRACING
251     TRACE_surf_host_set_power(date, getName(),
252                               m_core * m_powerScale *
253                               m_powerPeak);
254 #endif
255     while ((var = lmm_get_var_from_cnst
256             (surf_cpu_model_pm->getMaxminSystem(), constraint(), &elem))) {
257       CpuCas01ActionLmmPtr action = static_cast<CpuCas01ActionLmmPtr>(static_cast<ActionLmmPtr>(lmm_variable_id(var)));
258
259       lmm_update_variable_bound(surf_cpu_model_pm->getMaxminSystem(),
260                                 action->getVariable(),
261                                 m_powerScale * m_powerPeak);
262     }
263     if (tmgr_trace_event_free(event_type))
264       p_powerEvent = NULL;
265   } else if (event_type == p_stateEvent) {
266         /* TODO (Hypervisor): do the same thing for constraint_core[i] */
267     xbt_assert(m_core == 1, "FIXME: add state change code also for constraint_core[i]");
268
269     if (value > 0) {
270       if(m_stateCurrent == SURF_RESOURCE_OFF)
271         xbt_dynar_push_as(host_that_restart, char*, (char *)getName());
272       m_stateCurrent = SURF_RESOURCE_ON;
273     } else {
274       lmm_constraint_t cnst = constraint();
275
276       m_stateCurrent = SURF_RESOURCE_OFF;
277
278       while ((var = lmm_get_var_from_cnst(surf_cpu_model_pm->getMaxminSystem(), cnst, &elem))) {
279         ActionLmmPtr action = static_cast<ActionLmmPtr>(lmm_variable_id(var));
280
281         if (action->getState() == SURF_ACTION_RUNNING ||
282             action->getState() == SURF_ACTION_READY ||
283             action->getState() == SURF_ACTION_NOT_IN_THE_SYSTEM) {
284           action->setFinishTime(date);
285           action->setState(SURF_ACTION_FAILED);
286         }
287       }
288     }
289     if (tmgr_trace_event_free(event_type))
290       p_stateEvent = NULL;
291   } else {
292     XBT_CRITICAL("Unknown event ! \n");
293     xbt_abort();
294   }
295
296   return;
297 }
298
299 CpuActionPtr CpuCas01Lmm::execute(double size)
300 {
301
302   XBT_IN("(%s,%g)", getName(), size);
303   CpuCas01ActionLmmPtr action = new CpuCas01ActionLmm(surf_cpu_model_pm, size, m_stateCurrent != SURF_RESOURCE_ON,
304                                                               m_powerScale * m_powerPeak, constraint());
305
306   XBT_OUT();
307   return action;
308 }
309
310 CpuActionPtr CpuCas01Lmm::sleep(double duration)
311 {
312   if (duration > 0)
313     duration = MAX(duration, MAXMIN_PRECISION);
314
315   XBT_IN("(%s,%g)", getName(), duration);
316   CpuCas01ActionLmmPtr action = new CpuCas01ActionLmm(surf_cpu_model_pm, 1.0, m_stateCurrent != SURF_RESOURCE_ON,
317                                                       m_powerScale * m_powerPeak, constraint());
318
319
320   // FIXME: sleep variables should not consume 1.0 in lmm_expand
321   action->m_maxDuration = duration;
322   action->m_suspended = 2;
323   if (duration == NO_MAX_DURATION) {
324     /* Move to the *end* of the corresponding action set. This convention
325        is used to speed up update_resource_state  */
326     xbt_swag_remove(static_cast<ActionPtr>(action), action->getStateSet());
327     action->p_stateSet = static_cast<CpuCas01ModelPtr>(getModel())->p_cpuRunningActionSetThatDoesNotNeedBeingChecked;
328     xbt_swag_insert(static_cast<ActionPtr>(action), action->getStateSet());
329   }
330
331   lmm_update_variable_weight(surf_cpu_model_pm->getMaxminSystem(),
332                              action->getVariable(), 0.0);
333   if (surf_cpu_model_pm->getUpdateMechanism() == UM_LAZY) {     // remove action from the heap
334     action->heapRemove(surf_cpu_model_pm->getActionHeap());
335     // this is necessary for a variable with weight 0 since such
336     // variables are ignored in lmm and we need to set its max_duration
337     // correctly at the next call to share_resources
338     xbt_swag_insert_at_head(static_cast<ActionLmmPtr>(action), surf_cpu_model_pm->getModifiedSet());
339   }
340
341   XBT_OUT();
342   return action;
343 }
344
345 xbt_dynar_t CpuCas01Lmm::getWattsRangeList()
346 {
347         xbt_dynar_t power_range_list;
348         xbt_dynar_t power_tuple;
349         int i = 0, pstate_nb=0;
350         xbt_dynar_t current_power_values;
351         double min_power, max_power;
352
353         if (getProperties() == NULL)
354                 return NULL;
355
356         char* all_power_values_str = (char*)xbt_dict_get_or_null(getProperties(), "power_per_state");
357
358         if (all_power_values_str == NULL)
359                 return NULL;
360
361
362         power_range_list = xbt_dynar_new(sizeof(xbt_dynar_t), NULL);
363         xbt_dynar_t all_power_values = xbt_str_split(all_power_values_str, ",");
364
365         pstate_nb = xbt_dynar_length(all_power_values);
366         for (i=0; i< pstate_nb; i++)
367         {
368                 /* retrieve the power values associated with the current pstate */
369                 current_power_values = xbt_str_split(xbt_dynar_get_as(all_power_values, i, char*), ":");
370                 xbt_assert(xbt_dynar_length(current_power_values) > 1,
371                                 "Power properties incorrectly defined - could not retrieve min and max power values for host %s",
372                                 getName());
373
374                 /* min_power corresponds to the idle power (cpu load = 0) */
375                 /* max_power is the power consumed at 100% cpu load       */
376                 min_power = atof(xbt_dynar_get_as(current_power_values, 0, char*));
377                 max_power = atof(xbt_dynar_get_as(current_power_values, 1, char*));
378
379                 power_tuple = xbt_dynar_new(sizeof(double), NULL);
380                 xbt_dynar_push_as(power_tuple, double, min_power);
381                 xbt_dynar_push_as(power_tuple, double, max_power);
382
383                 xbt_dynar_push_as(power_range_list, xbt_dynar_t, power_tuple);
384                 xbt_dynar_free(&current_power_values);
385         }
386         xbt_dynar_free(&all_power_values);
387         return power_range_list;
388 }
389
390 /**
391  * Computes the power consumed by the host according to the current pstate and processor load
392  *
393  */
394 double CpuCas01Lmm::getCurrentWattsValue(double cpu_load)
395 {
396         xbt_dynar_t power_range_list = p_energy->power_range_watts_list;
397
398         if (power_range_list == NULL)
399         {
400                 XBT_DEBUG("No power range properties specified for host %s", getName());
401                 return 0;
402         }
403         xbt_assert(xbt_dynar_length(power_range_list) == xbt_dynar_length(p_powerPeakList),
404                                                 "The number of power ranges in the properties does not match the number of pstates for host %s",
405                                                 getName());
406
407     /* retrieve the power values associated with the current pstate */
408     xbt_dynar_t current_power_values = xbt_dynar_get_as(power_range_list, m_pstate, xbt_dynar_t);
409
410     /* min_power corresponds to the idle power (cpu load = 0) */
411     /* max_power is the power consumed at 100% cpu load       */
412     double min_power = xbt_dynar_get_as(current_power_values, 0, double);
413     double max_power = xbt_dynar_get_as(current_power_values, 1, double);
414     double power_slope = max_power - min_power;
415
416     double current_power = min_power + cpu_load * power_slope;
417
418         XBT_DEBUG("[get_current_watts] min_power=%f, max_power=%f, slope=%f", min_power, max_power, power_slope);
419     XBT_DEBUG("[get_current_watts] Current power (watts) = %f, load = %f", current_power, cpu_load);
420
421         return current_power;
422 }
423
424 /**
425  * Updates the total energy consumed as the sum of the current energy and
426  *                                               the energy consumed by the current action
427  */
428 void CpuCas01Lmm::updateEnergy(double cpu_load)
429 {
430   double start_time = p_energy->last_updated;
431   double finish_time = surf_get_clock();
432
433   XBT_DEBUG("[cpu_update_energy] action time interval=(%f-%f), current power peak=%f, current pstate=%d",
434                   start_time, finish_time, m_powerPeak, m_pstate);
435   double current_energy = p_energy->total_energy;
436   double action_energy = getCurrentWattsValue(cpu_load)*(finish_time-start_time);
437
438   p_energy->total_energy = current_energy + action_energy;
439   p_energy->last_updated = finish_time;
440
441   XBT_DEBUG("[cpu_update_energy] old_energy_value=%f, action_energy_value=%f", current_energy, action_energy);
442 }
443
444 double CpuCas01Lmm::getCurrentPowerPeak()
445 {
446   return m_powerPeak;
447 }
448
449 double CpuCas01Lmm::getPowerPeakAt(int pstate_index)
450 {
451   xbt_dynar_t plist = p_powerPeakList;
452   xbt_assert((pstate_index <= (int)xbt_dynar_length(plist)), "Invalid parameters (pstate index out of bounds)");
453
454   return xbt_dynar_get_as(plist, pstate_index, double);
455 }
456
457 int CpuCas01Lmm::getNbPstates()
458 {
459   return xbt_dynar_length(p_powerPeakList);
460 }
461
462 void CpuCas01Lmm::setPowerPeakAt(int pstate_index)
463 {
464   xbt_dynar_t plist = p_powerPeakList;
465   xbt_assert((pstate_index <= (int)xbt_dynar_length(plist)), "Invalid parameters (pstate index out of bounds)");
466
467   double new_power_peak = xbt_dynar_get_as(plist, pstate_index, double);
468   m_pstate = pstate_index;
469   m_powerPeak = new_power_peak;
470 }
471
472 double CpuCas01Lmm::getConsumedEnergy()
473 {
474   return p_energy->total_energy;
475 }
476
477 /**********
478  * Action *
479  **********/
480
481 CpuCas01ActionLmm::CpuCas01ActionLmm(ModelPtr model_, double cost, bool failed, double power, lmm_constraint_t constraint)
482  : Action(model_, cost, failed)
483  , CpuActionLmm(lmm_variable_new(getModel()->getMaxminSystem(), static_cast<ActionLmmPtr>(this),
484                         m_priority,
485                 power, 1))
486 {
487   m_suspended = 0;     /* Should be useless because of the
488                                                            calloc but it seems to help valgrind... */
489
490   if (getModel()->getUpdateMechanism() == UM_LAZY) {
491     m_indexHeap = -1;
492     m_lastUpdate = surf_get_clock();
493     m_lastValue = 0.0;
494   }
495   lmm_expand(getModel()->getMaxminSystem(), constraint, getVariable(), 1.0);
496 }
497
498
499 /**
500  * Update the CPU total energy for a finished action
501  *
502  */
503 void CpuCas01ActionLmm::updateEnergy()
504 {
505   CpuCas01LmmPtr cpu  = static_cast<CpuCas01LmmPtr>(lmm_constraint_id(lmm_get_cnst_from_var
506                                                                                   (getModel()->getMaxminSystem(),
507                                                                                                   getVariable(), 0)));
508
509   if(cpu->p_energy->last_updated < surf_get_clock()) {
510         double load = lmm_constraint_get_usage(cpu->constraint()) / cpu->m_powerPeak;
511     cpu->updateEnergy(load);
512   }
513 }