Logo AND Algorithmique Numérique Distribuée

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