Logo AND Algorithmique Numérique Distribuée

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