Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
e084657416151ae5f59bbeae520bb45204a3296b
[simgrid.git] / src / surf / cpu_interface.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 <xbt/dynar.h>
8 #include "cpu_interface.hpp"
9 #include "plugins/energy.hpp"
10 #include "src/instr/instr_private.h" // TRACE_is_enabled(). FIXME: remove by subscribing tracing to the surf signals
11
12 XBT_LOG_EXTERNAL_CATEGORY(surf_kernel);
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu, surf,
14                                 "Logging specific to the SURF cpu module");
15
16 int autoload_surf_cpu_model = 1;
17 void_f_void_t surf_cpu_model_init_preparse = NULL;
18
19 simgrid::surf::CpuModel *surf_cpu_model_pm;
20 simgrid::surf::CpuModel *surf_cpu_model_vm;
21
22 namespace simgrid {
23 namespace surf {
24
25 /*************
26  * Callbacks *
27  *************/
28
29 Cpu *getActionCpu(CpuAction *action) {
30   return static_cast<Cpu*>(lmm_constraint_id(lmm_get_cnst_from_var
31                        (action->getModel()->getMaxminSystem(),
32                        action->getVariable(), 0)));
33 }
34
35 simgrid::xbt::signal<void(CpuAction*, e_surf_action_state_t, e_surf_action_state_t)> cpuActionStateChangedCallbacks;
36
37 /*********
38  * Model *
39  *********/
40
41 void CpuModel::updateActionsStateLazy(double now, double /*delta*/)
42 {
43   CpuAction *action;
44   while ((xbt_heap_size(getActionHeap()) > 0)
45          && (double_equals(xbt_heap_maxkey(getActionHeap()), now, sg_surf_precision))) {
46     action = static_cast<CpuAction*>(xbt_heap_pop(getActionHeap()));
47     XBT_CDEBUG(surf_kernel, "Something happened to action %p", action);
48     if (TRACE_is_enabled()) {
49       Cpu *cpu = static_cast<Cpu*>(lmm_constraint_id(lmm_get_cnst_from_var(getMaxminSystem(), action->getVariable(), 0)));
50       TRACE_surf_host_set_utilization(cpu->getName(), action->getCategory(),
51                                       lmm_variable_getvalue(action->getVariable()),
52                                       action->getLastUpdate(),
53                                       now - action->getLastUpdate());
54     }
55
56     action->finish();
57     XBT_CDEBUG(surf_kernel, "Action %p finished", action);
58
59     /* set the remains to 0 due to precision problems when updating the remaining amount */
60     action->setRemains(0);
61     action->setState(SURF_ACTION_DONE);
62     action->heapRemove(getActionHeap()); //FIXME: strange call since action was already popped
63   }
64   if (TRACE_is_enabled()) {
65     //defining the last timestamp that we can safely dump to trace file
66     //without losing the event ascending order (considering all CPU's)
67     double smaller = -1;
68     ActionList *actionSet = getRunningActionSet();
69     for(ActionList::iterator it(actionSet->begin()), itend(actionSet->end())
70        ; it != itend ; ++it) {
71       action = static_cast<CpuAction*>(&*it);
72         if (smaller < 0) {
73           smaller = action->getLastUpdate();
74           continue;
75         }
76         if (action->getLastUpdate() < smaller) {
77           smaller = action->getLastUpdate();
78         }
79     }
80     if (smaller > 0) {
81       TRACE_last_timestamp_to_dump = smaller;
82     }
83   }
84   return;
85 }
86
87 void CpuModel::updateActionsStateFull(double now, double delta)
88 {
89   CpuAction *action = NULL;
90   ActionList *running_actions = getRunningActionSet();
91
92   for(ActionList::iterator it(running_actions->begin()), itNext=it, itend(running_actions->end())
93      ; it != itend ; it=itNext) {
94   ++itNext;
95     action = static_cast<CpuAction*>(&*it);
96     if (TRACE_is_enabled()) {
97       Cpu *x = static_cast<Cpu*> (lmm_constraint_id(lmm_get_cnst_from_var(getMaxminSystem(), action->getVariable(), 0)) );
98
99       TRACE_surf_host_set_utilization(x->getName(),
100                                       action->getCategory(),
101                                       lmm_variable_getvalue(action->getVariable()),
102                                       now - delta,
103                                       delta);
104       TRACE_last_timestamp_to_dump = now - delta;
105     }
106
107     action->updateRemains(lmm_variable_getvalue(action->getVariable()) * delta);
108
109
110     if (action->getMaxDuration() != NO_MAX_DURATION)
111       action->updateMaxDuration(delta);
112
113
114     if ((action->getRemainsNoUpdate() <= 0) &&
115         (lmm_get_variable_weight(action->getVariable()) > 0)) {
116       action->finish();
117       action->setState(SURF_ACTION_DONE);
118     } else if ((action->getMaxDuration() != NO_MAX_DURATION) &&
119                (action->getMaxDuration() <= 0)) {
120       action->finish();
121       action->setState(SURF_ACTION_DONE);
122     }
123   }
124
125   return;
126 }
127
128 /************
129  * Resource *
130  ************/
131 Cpu::Cpu(Model *model, simgrid::s4u::Host *host,
132     xbt_dynar_t speedPeakList, int core, double speedPeak)
133  : Cpu(model, host, NULL/*constraint*/, speedPeakList, core, speedPeak)
134 {
135 }
136
137 Cpu::Cpu(Model *model, simgrid::s4u::Host *host, lmm_constraint_t constraint,
138     xbt_dynar_t speedPeakList, int core, double speedPeak)
139  : Resource(model, host->name().c_str(), constraint)
140  , coresAmount_(core)
141  , host_(host)
142 {
143   speed_.peak = speedPeak;
144   speed_.scale = 1;
145   host->pimpl_cpu = this;
146   xbt_assert(speed_.scale > 0, "Available speed has to be >0");
147
148   // Copy the power peak array:
149   speedPeakList_ = xbt_dynar_new(sizeof(double), nullptr);
150   unsigned long n = xbt_dynar_length(speedPeakList);
151   for (unsigned long i = 0; i != n; ++i) {
152     double value = xbt_dynar_get_as(speedPeakList, i, double);
153     xbt_dynar_push(speedPeakList_, &value);
154   }
155
156   /* Currently, we assume that a VM does not have a multicore CPU. */
157   if (core > 1)
158     xbt_assert(model == surf_cpu_model_pm);
159
160   if (model->getUpdateMechanism() != UM_UNDEFINED) {
161   p_constraintCore = xbt_new(lmm_constraint_t, core);
162   p_constraintCoreId = xbt_new(void*, core);
163
164     int i;
165     for (i = 0; i < core; i++) {
166       /* just for a unique id, never used as a string. */
167       p_constraintCoreId[i] = bprintf("%s:%i", host->name().c_str(), i);
168       p_constraintCore[i] = lmm_constraint_new(model->getMaxminSystem(), p_constraintCoreId[i], speed_.scale * speed_.peak);
169     }
170   }
171 }
172
173 Cpu::~Cpu()
174 {
175   if (p_constraintCoreId){
176     for (int i = 0; i < coresAmount_; i++) {
177     xbt_free(p_constraintCoreId[i]);
178     }
179     xbt_free(p_constraintCore);
180   }
181   if (p_constraintCoreId)
182     xbt_free(p_constraintCoreId);
183   if (speedPeakList_)
184     xbt_dynar_free(&speedPeakList_);
185 }
186
187 double Cpu::getCurrentPowerPeak()
188 {
189   return speed_.peak;
190 }
191
192 int Cpu::getNbPStates()
193 {
194   return xbt_dynar_length(speedPeakList_);
195 }
196
197 void Cpu::setPState(int pstate_index)
198 {
199   xbt_dynar_t plist = speedPeakList_;
200   xbt_assert(pstate_index <= (int)xbt_dynar_length(plist),
201       "Invalid parameters for CPU %s (pstate %d > length of pstates %d)", getName(), pstate_index, (int)xbt_dynar_length(plist));
202
203   double new_peak_speed = xbt_dynar_get_as(plist, pstate_index, double);
204   pstate_ = pstate_index;
205   speed_.peak = new_peak_speed;
206
207   onSpeedChange();
208 }
209
210 int Cpu::getPState()
211 {
212   return pstate_;
213 }
214
215 double Cpu::getPowerPeakAt(int pstate_index)
216 {
217   xbt_dynar_t plist = speedPeakList_;
218   xbt_assert((pstate_index <= (int)xbt_dynar_length(plist)), "Invalid parameters (pstate index out of bounds)");
219
220   return xbt_dynar_get_as(plist, pstate_index, double);
221 }
222
223 double Cpu::getSpeed(double load)
224 {
225   return load * speed_.peak;
226 }
227
228 double Cpu::getAvailableSpeed()
229 {
230 /* number between 0 and 1 */
231   return speed_.scale;
232 }
233
234 void Cpu::onSpeedChange() {
235   TRACE_surf_host_set_speed(surf_get_clock(), getName(),
236       coresAmount_ * speed_.scale * speed_.peak);
237 }
238
239
240 int Cpu::getCore()
241 {
242   return coresAmount_;
243 }
244
245 void Cpu::setStateTrace(tmgr_trace_t trace)
246 {
247   xbt_assert(stateEvent_==NULL,"Cannot set a second state trace to Host %s", host_->name().c_str());
248
249   stateEvent_ = future_evt_set->add_trace(trace, 0.0, this);
250 }
251 void Cpu::setSpeedTrace(tmgr_trace_t trace)
252 {
253   xbt_assert(speed_.event==NULL,"Cannot set a second speed trace to Host %s", host_->name().c_str());
254
255   speed_.event = future_evt_set->add_trace(trace, 0.0, this);
256 }
257
258
259 /**********
260  * Action *
261  **********/
262
263 void CpuAction::updateRemainingLazy(double now)
264 {
265   double delta = 0.0;
266
267   xbt_assert(getStateSet() == getModel()->getRunningActionSet(),
268       "You're updating an action that is not running.");
269
270   /* bogus priority, skip it */
271   xbt_assert(getPriority() > 0,
272       "You're updating an action that seems suspended.");
273
274   delta = now - m_lastUpdate;
275
276   if (m_remains > 0) {
277     XBT_CDEBUG(surf_kernel, "Updating action(%p): remains was %f, last_update was: %f", this, m_remains, m_lastUpdate);
278     double_update(&(m_remains), m_lastValue * delta, sg_maxmin_precision*sg_surf_precision);
279
280     if (TRACE_is_enabled()) {
281       Cpu *cpu = static_cast<Cpu*>(lmm_constraint_id(lmm_get_cnst_from_var(getModel()->getMaxminSystem(), getVariable(), 0)));
282       TRACE_surf_host_set_utilization(cpu->getName(), getCategory(), m_lastValue, m_lastUpdate, now - m_lastUpdate);
283     }
284     XBT_CDEBUG(surf_kernel, "Updating action(%p): remains is now %f", this, m_remains);
285   }
286
287   m_lastUpdate = now;
288   m_lastValue = lmm_variable_getvalue(getVariable());
289 }
290
291 /*
292  *
293  * This function formulates a constraint problem that pins a given task to
294  * particular cores. Currently, it is possible to pin a task to an exactly one
295  * specific core. The system links the variable object of the task to the
296  * per-core constraint object.
297  *
298  * But, the taskset command on Linux takes a mask value specifying a CPU
299  * affinity setting of a given task. If the mask value is 0x03, the given task
300  * will be executed on the first core (CPU0) or the second core (CPU1) on the
301  * given PM. The schedular will determine appropriate placements of tasks,
302  * considering given CPU affinities and task activities.
303  *
304  * How should the system formulate constraint problems for an affinity to
305  * multiple cores?
306  *
307  * The cpu argument must be the host where the task is being executed. The
308  * action object does not have the information about the location where the
309  * action is being executed.
310  */
311 void CpuAction::setAffinity(Cpu *cpu, unsigned long mask)
312 {
313   lmm_variable_t var_obj = getVariable();
314   XBT_IN("(%p,%lx)", this, mask);
315
316   {
317     unsigned long nbits = 0;
318
319     /* FIXME: There is much faster algorithms doing this. */
320     for (int i = 0; i < cpu->coresAmount_; i++) {
321       unsigned long has_affinity = (1UL << i) & mask;
322       if (has_affinity)
323         nbits += 1;
324     }
325
326     if (nbits > 1) {
327       XBT_CRITICAL("Do not specify multiple cores for an affinity mask.");
328       XBT_CRITICAL("See the comment in cpu_action_set_affinity().");
329       DIE_IMPOSSIBLE;
330     }
331   }
332
333   for (int i = 0; i < cpu->coresAmount_; i++) {
334     XBT_DEBUG("clear affinity %p to cpu-%d@%s", this, i,  cpu->getName());
335     lmm_shrink(cpu->getModel()->getMaxminSystem(), cpu->p_constraintCore[i], var_obj);
336
337     unsigned long has_affinity = (1UL << i) & mask;
338     if (has_affinity) {
339       /* This function only accepts an affinity setting on the host where the
340        * task is now running. In future, a task might move to another host.
341        * But, at this moment, this function cannot take an affinity setting on
342        * that future host.
343        *
344        * It might be possible to extend the code to allow this function to
345        * accept affinity settings on a future host. We might be able to assign
346        * zero to elem->value to maintain such inactive affinity settings in the
347        * system. But, this will make the system complex. */
348       XBT_DEBUG("set affinity %p to cpu-%d@%s", this, i, cpu->getName());
349       lmm_expand(cpu->getModel()->getMaxminSystem(), cpu->p_constraintCore[i], var_obj, 1.0);
350     }
351   }
352
353   if (cpu->getModel()->getUpdateMechanism() == UM_LAZY) {
354     /* FIXME (hypervisor): Do we need to do something for the LAZY mode? */
355   }
356   XBT_OUT();
357 }
358
359 simgrid::xbt::signal<void(simgrid::surf::CpuAction*, e_surf_action_state_t)> CpuAction::onStateChange;
360
361 void CpuAction::setState(e_surf_action_state_t state){
362   e_surf_action_state_t previous = getState();
363   Action::setState(state);
364   onStateChange(this, previous);
365 }
366
367 }
368 }