xref: /linux-6.15/include/linux/energy_model.h (revision ffcf9bce)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_ENERGY_MODEL_H
3 #define _LINUX_ENERGY_MODEL_H
4 #include <linux/cpumask.h>
5 #include <linux/device.h>
6 #include <linux/jump_label.h>
7 #include <linux/kobject.h>
8 #include <linux/kref.h>
9 #include <linux/rcupdate.h>
10 #include <linux/sched/cpufreq.h>
11 #include <linux/sched/topology.h>
12 #include <linux/types.h>
13 
14 /**
15  * struct em_perf_state - Performance state of a performance domain
16  * @frequency:	The frequency in KHz, for consistency with CPUFreq
17  * @power:	The power consumed at this level (by 1 CPU or by a registered
18  *		device). It can be a total power: static and dynamic.
19  * @cost:	The cost coefficient associated with this level, used during
20  *		energy calculation. Equal to: power * max_frequency / frequency
21  * @flags:	see "em_perf_state flags" description below.
22  */
23 struct em_perf_state {
24 	unsigned long frequency;
25 	unsigned long power;
26 	unsigned long cost;
27 	unsigned long flags;
28 };
29 
30 /*
31  * em_perf_state flags:
32  *
33  * EM_PERF_STATE_INEFFICIENT: The performance state is inefficient. There is
34  * in this em_perf_domain, another performance state with a higher frequency
35  * but a lower or equal power cost. Such inefficient states are ignored when
36  * using em_pd_get_efficient_*() functions.
37  */
38 #define EM_PERF_STATE_INEFFICIENT BIT(0)
39 
40 /**
41  * struct em_perf_table - Performance states table
42  * @rcu:	RCU used for safe access and destruction
43  * @kref:	Reference counter to track the users
44  * @state:	List of performance states, in ascending order
45  */
46 struct em_perf_table {
47 	struct rcu_head rcu;
48 	struct kref kref;
49 	struct em_perf_state state[];
50 };
51 
52 /**
53  * struct em_perf_domain - Performance domain
54  * @table:		List of performance states, in ascending order
55  * @em_table:		Pointer to the runtime modifiable em_perf_table
56  * @nr_perf_states:	Number of performance states
57  * @flags:		See "em_perf_domain flags"
58  * @cpus:		Cpumask covering the CPUs of the domain. It's here
59  *			for performance reasons to avoid potential cache
60  *			misses during energy calculations in the scheduler
61  *			and simplifies allocating/freeing that memory region.
62  *
63  * In case of CPU device, a "performance domain" represents a group of CPUs
64  * whose performance is scaled together. All CPUs of a performance domain
65  * must have the same micro-architecture. Performance domains often have
66  * a 1-to-1 mapping with CPUFreq policies. In case of other devices the @cpus
67  * field is unused.
68  */
69 struct em_perf_domain {
70 	struct em_perf_state *table;
71 	struct em_perf_table __rcu *em_table;
72 	int nr_perf_states;
73 	unsigned long flags;
74 	unsigned long cpus[];
75 };
76 
77 /*
78  *  em_perf_domain flags:
79  *
80  *  EM_PERF_DOMAIN_MICROWATTS: The power values are in micro-Watts or some
81  *  other scale.
82  *
83  *  EM_PERF_DOMAIN_SKIP_INEFFICIENCIES: Skip inefficient states when estimating
84  *  energy consumption.
85  *
86  *  EM_PERF_DOMAIN_ARTIFICIAL: The power values are artificial and might be
87  *  created by platform missing real power information
88  */
89 #define EM_PERF_DOMAIN_MICROWATTS BIT(0)
90 #define EM_PERF_DOMAIN_SKIP_INEFFICIENCIES BIT(1)
91 #define EM_PERF_DOMAIN_ARTIFICIAL BIT(2)
92 
93 #define em_span_cpus(em) (to_cpumask((em)->cpus))
94 #define em_is_artificial(em) ((em)->flags & EM_PERF_DOMAIN_ARTIFICIAL)
95 
96 #ifdef CONFIG_ENERGY_MODEL
97 /*
98  * The max power value in micro-Watts. The limit of 64 Watts is set as
99  * a safety net to not overflow multiplications on 32bit platforms. The
100  * 32bit value limit for total Perf Domain power implies a limit of
101  * maximum CPUs in such domain to 64.
102  */
103 #define EM_MAX_POWER (64000000) /* 64 Watts */
104 
105 /*
106  * To avoid possible energy estimation overflow on 32bit machines add
107  * limits to number of CPUs in the Perf. Domain.
108  * We are safe on 64bit machine, thus some big number.
109  */
110 #ifdef CONFIG_64BIT
111 #define EM_MAX_NUM_CPUS 4096
112 #else
113 #define EM_MAX_NUM_CPUS 16
114 #endif
115 
116 /*
117  * To avoid an overflow on 32bit machines while calculating the energy
118  * use a different order in the operation. First divide by the 'cpu_scale'
119  * which would reduce big value stored in the 'cost' field, then multiply by
120  * the 'sum_util'. This would allow to handle existing platforms, which have
121  * e.g. power ~1.3 Watt at max freq, so the 'cost' value > 1mln micro-Watts.
122  * In such scenario, where there are 4 CPUs in the Perf. Domain the 'sum_util'
123  * could be 4096, then multiplication: 'cost' * 'sum_util'  would overflow.
124  * This reordering of operations has some limitations, we lose small
125  * precision in the estimation (comparing to 64bit platform w/o reordering).
126  *
127  * We are safe on 64bit machine.
128  */
129 #ifdef CONFIG_64BIT
130 #define em_estimate_energy(cost, sum_util, scale_cpu) \
131 	(((cost) * (sum_util)) / (scale_cpu))
132 #else
133 #define em_estimate_energy(cost, sum_util, scale_cpu) \
134 	(((cost) / (scale_cpu)) * (sum_util))
135 #endif
136 
137 struct em_data_callback {
138 	/**
139 	 * active_power() - Provide power at the next performance state of
140 	 *		a device
141 	 * @dev		: Device for which we do this operation (can be a CPU)
142 	 * @power	: Active power at the performance state
143 	 *		(modified)
144 	 * @freq	: Frequency at the performance state in kHz
145 	 *		(modified)
146 	 *
147 	 * active_power() must find the lowest performance state of 'dev' above
148 	 * 'freq' and update 'power' and 'freq' to the matching active power
149 	 * and frequency.
150 	 *
151 	 * In case of CPUs, the power is the one of a single CPU in the domain,
152 	 * expressed in micro-Watts or an abstract scale. It is expected to
153 	 * fit in the [0, EM_MAX_POWER] range.
154 	 *
155 	 * Return 0 on success.
156 	 */
157 	int (*active_power)(struct device *dev, unsigned long *power,
158 			    unsigned long *freq);
159 
160 	/**
161 	 * get_cost() - Provide the cost at the given performance state of
162 	 *		a device
163 	 * @dev		: Device for which we do this operation (can be a CPU)
164 	 * @freq	: Frequency at the performance state in kHz
165 	 * @cost	: The cost value for the performance state
166 	 *		(modified)
167 	 *
168 	 * In case of CPUs, the cost is the one of a single CPU in the domain.
169 	 * It is expected to fit in the [0, EM_MAX_POWER] range due to internal
170 	 * usage in EAS calculation.
171 	 *
172 	 * Return 0 on success, or appropriate error value in case of failure.
173 	 */
174 	int (*get_cost)(struct device *dev, unsigned long freq,
175 			unsigned long *cost);
176 };
177 #define EM_SET_ACTIVE_POWER_CB(em_cb, cb) ((em_cb).active_power = cb)
178 #define EM_ADV_DATA_CB(_active_power_cb, _cost_cb)	\
179 	{ .active_power = _active_power_cb,		\
180 	  .get_cost = _cost_cb }
181 #define EM_DATA_CB(_active_power_cb)			\
182 		EM_ADV_DATA_CB(_active_power_cb, NULL)
183 
184 struct em_perf_domain *em_cpu_get(int cpu);
185 struct em_perf_domain *em_pd_get(struct device *dev);
186 int em_dev_register_perf_domain(struct device *dev, unsigned int nr_states,
187 				struct em_data_callback *cb, cpumask_t *span,
188 				bool microwatts);
189 void em_dev_unregister_perf_domain(struct device *dev);
190 struct em_perf_table __rcu *em_table_alloc(struct em_perf_domain *pd);
191 void em_table_free(struct em_perf_table __rcu *table);
192 
193 /**
194  * em_pd_get_efficient_state() - Get an efficient performance state from the EM
195  * @table:		List of performance states, in ascending order
196  * @nr_perf_states:	Number of performance states
197  * @freq:		Frequency to map with the EM
198  * @pd_flags:		Performance Domain flags
199  *
200  * It is called from the scheduler code quite frequently and as a consequence
201  * doesn't implement any check.
202  *
203  * Return: An efficient performance state id, high enough to meet @freq
204  * requirement.
205  */
206 static inline int
207 em_pd_get_efficient_state(struct em_perf_state *table, int nr_perf_states,
208 			  unsigned long freq, unsigned long pd_flags)
209 {
210 	struct em_perf_state *ps;
211 	int i;
212 
213 	for (i = 0; i < nr_perf_states; i++) {
214 		ps = &table[i];
215 		if (ps->frequency >= freq) {
216 			if (pd_flags & EM_PERF_DOMAIN_SKIP_INEFFICIENCIES &&
217 			    ps->flags & EM_PERF_STATE_INEFFICIENT)
218 				continue;
219 			return i;
220 		}
221 	}
222 
223 	return nr_perf_states - 1;
224 }
225 
226 /**
227  * em_cpu_energy() - Estimates the energy consumed by the CPUs of a
228  *		performance domain
229  * @pd		: performance domain for which energy has to be estimated
230  * @max_util	: highest utilization among CPUs of the domain
231  * @sum_util	: sum of the utilization of all CPUs in the domain
232  * @allowed_cpu_cap	: maximum allowed CPU capacity for the @pd, which
233  *			  might reflect reduced frequency (due to thermal)
234  *
235  * This function must be used only for CPU devices. There is no validation,
236  * i.e. if the EM is a CPU type and has cpumask allocated. It is called from
237  * the scheduler code quite frequently and that is why there is not checks.
238  *
239  * Return: the sum of the energy consumed by the CPUs of the domain assuming
240  * a capacity state satisfying the max utilization of the domain.
241  */
242 static inline unsigned long em_cpu_energy(struct em_perf_domain *pd,
243 				unsigned long max_util, unsigned long sum_util,
244 				unsigned long allowed_cpu_cap)
245 {
246 	unsigned long freq, ref_freq, scale_cpu;
247 	struct em_perf_table *em_table;
248 	struct em_perf_state *ps;
249 	int cpu, i;
250 
251 #ifdef CONFIG_SCHED_DEBUG
252 	WARN_ONCE(!rcu_read_lock_held(), "EM: rcu read lock needed\n");
253 #endif
254 
255 	if (!sum_util)
256 		return 0;
257 
258 	/*
259 	 * In order to predict the performance state, map the utilization of
260 	 * the most utilized CPU of the performance domain to a requested
261 	 * frequency, like schedutil. Take also into account that the real
262 	 * frequency might be set lower (due to thermal capping). Thus, clamp
263 	 * max utilization to the allowed CPU capacity before calculating
264 	 * effective frequency.
265 	 */
266 	cpu = cpumask_first(to_cpumask(pd->cpus));
267 	scale_cpu = arch_scale_cpu_capacity(cpu);
268 	ref_freq = arch_scale_freq_ref(cpu);
269 
270 	max_util = min(max_util, allowed_cpu_cap);
271 	freq = map_util_freq(max_util, ref_freq, scale_cpu);
272 
273 	/*
274 	 * Find the lowest performance state of the Energy Model above the
275 	 * requested frequency.
276 	 */
277 	em_table = rcu_dereference(pd->em_table);
278 	i = em_pd_get_efficient_state(em_table->state, pd->nr_perf_states,
279 				      freq, pd->flags);
280 	ps = &em_table->state[i];
281 
282 	/*
283 	 * The capacity of a CPU in the domain at the performance state (ps)
284 	 * can be computed as:
285 	 *
286 	 *             ps->freq * scale_cpu
287 	 *   ps->cap = --------------------                          (1)
288 	 *                 cpu_max_freq
289 	 *
290 	 * So, ignoring the costs of idle states (which are not available in
291 	 * the EM), the energy consumed by this CPU at that performance state
292 	 * is estimated as:
293 	 *
294 	 *             ps->power * cpu_util
295 	 *   cpu_nrg = --------------------                          (2)
296 	 *                   ps->cap
297 	 *
298 	 * since 'cpu_util / ps->cap' represents its percentage of busy time.
299 	 *
300 	 *   NOTE: Although the result of this computation actually is in
301 	 *         units of power, it can be manipulated as an energy value
302 	 *         over a scheduling period, since it is assumed to be
303 	 *         constant during that interval.
304 	 *
305 	 * By injecting (1) in (2), 'cpu_nrg' can be re-expressed as a product
306 	 * of two terms:
307 	 *
308 	 *             ps->power * cpu_max_freq   cpu_util
309 	 *   cpu_nrg = ------------------------ * ---------          (3)
310 	 *                    ps->freq            scale_cpu
311 	 *
312 	 * The first term is static, and is stored in the em_perf_state struct
313 	 * as 'ps->cost'.
314 	 *
315 	 * Since all CPUs of the domain have the same micro-architecture, they
316 	 * share the same 'ps->cost', and the same CPU capacity. Hence, the
317 	 * total energy of the domain (which is the simple sum of the energy of
318 	 * all of its CPUs) can be factorized as:
319 	 *
320 	 *            ps->cost * \Sum cpu_util
321 	 *   pd_nrg = ------------------------                       (4)
322 	 *                  scale_cpu
323 	 */
324 	return em_estimate_energy(ps->cost, sum_util, scale_cpu);
325 }
326 
327 /**
328  * em_pd_nr_perf_states() - Get the number of performance states of a perf.
329  *				domain
330  * @pd		: performance domain for which this must be done
331  *
332  * Return: the number of performance states in the performance domain table
333  */
334 static inline int em_pd_nr_perf_states(struct em_perf_domain *pd)
335 {
336 	return pd->nr_perf_states;
337 }
338 
339 #else
340 struct em_data_callback {};
341 #define EM_ADV_DATA_CB(_active_power_cb, _cost_cb) { }
342 #define EM_DATA_CB(_active_power_cb) { }
343 #define EM_SET_ACTIVE_POWER_CB(em_cb, cb) do { } while (0)
344 
345 static inline
346 int em_dev_register_perf_domain(struct device *dev, unsigned int nr_states,
347 				struct em_data_callback *cb, cpumask_t *span,
348 				bool microwatts)
349 {
350 	return -EINVAL;
351 }
352 static inline void em_dev_unregister_perf_domain(struct device *dev)
353 {
354 }
355 static inline struct em_perf_domain *em_cpu_get(int cpu)
356 {
357 	return NULL;
358 }
359 static inline struct em_perf_domain *em_pd_get(struct device *dev)
360 {
361 	return NULL;
362 }
363 static inline unsigned long em_cpu_energy(struct em_perf_domain *pd,
364 			unsigned long max_util, unsigned long sum_util,
365 			unsigned long allowed_cpu_cap)
366 {
367 	return 0;
368 }
369 static inline int em_pd_nr_perf_states(struct em_perf_domain *pd)
370 {
371 	return 0;
372 }
373 static inline
374 struct em_perf_table __rcu *em_table_alloc(struct em_perf_domain *pd)
375 {
376 	return NULL;
377 }
378 static inline void em_table_free(struct em_perf_table __rcu *table) {}
379 #endif
380 
381 #endif
382