• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Energy Model of devices
4  *
5  * Copyright (c) 2018-2021, Arm ltd.
6  * Written by: Quentin Perret, Arm ltd.
7  * Improvements provided by: Lukasz Luba, Arm ltd.
8  */
9 
10 #define pr_fmt(fmt) "energy_model: " fmt
11 
12 #include <linux/cpu.h>
13 #include <linux/cpufreq.h>
14 #include <linux/cpumask.h>
15 #include <linux/debugfs.h>
16 #include <linux/energy_model.h>
17 #include <linux/sched/topology.h>
18 #include <linux/slab.h>
19 
20 /*
21  * Mutex serializing the registrations of performance domains and letting
22  * callbacks defined by drivers sleep.
23  */
24 static DEFINE_MUTEX(em_pd_mutex);
25 
26 static void em_cpufreq_update_efficiencies(struct device *dev,
27 					   struct em_perf_state *table);
28 static void em_check_capacity_update(void);
29 static void em_update_workfn(struct work_struct *work);
30 static DECLARE_DELAYED_WORK(em_update_work, em_update_workfn);
31 
_is_cpu_device(struct device * dev)32 static bool _is_cpu_device(struct device *dev)
33 {
34 	return (dev->bus == &cpu_subsys);
35 }
36 
37 #ifdef CONFIG_DEBUG_FS
38 static struct dentry *rootdir;
39 
40 struct em_dbg_info {
41 	struct em_perf_domain *pd;
42 	int ps_id;
43 };
44 
45 #define DEFINE_EM_DBG_SHOW(name, fname)					\
46 static int em_debug_##fname##_show(struct seq_file *s, void *unused)	\
47 {									\
48 	struct em_dbg_info *em_dbg = s->private;			\
49 	struct em_perf_state *table;					\
50 	unsigned long val;						\
51 									\
52 	rcu_read_lock();						\
53 	table = em_perf_state_from_pd(em_dbg->pd);			\
54 	val = table[em_dbg->ps_id].name;				\
55 	rcu_read_unlock();						\
56 									\
57 	seq_printf(s, "%lu\n", val);					\
58 	return 0;							\
59 }									\
60 DEFINE_SHOW_ATTRIBUTE(em_debug_##fname)
61 
62 DEFINE_EM_DBG_SHOW(frequency, frequency);
63 DEFINE_EM_DBG_SHOW(power, power);
64 DEFINE_EM_DBG_SHOW(cost, cost);
65 DEFINE_EM_DBG_SHOW(performance, performance);
66 DEFINE_EM_DBG_SHOW(flags, inefficiency);
67 
em_debug_create_ps(struct em_perf_domain * em_pd,struct em_dbg_info * em_dbg,int i,struct dentry * pd)68 static void em_debug_create_ps(struct em_perf_domain *em_pd,
69 			       struct em_dbg_info *em_dbg, int i,
70 			       struct dentry *pd)
71 {
72 	struct em_perf_state *table;
73 	unsigned long freq;
74 	struct dentry *d;
75 	char name[24];
76 
77 	em_dbg[i].pd = em_pd;
78 	em_dbg[i].ps_id = i;
79 
80 	rcu_read_lock();
81 	table = em_perf_state_from_pd(em_pd);
82 	freq = table[i].frequency;
83 	rcu_read_unlock();
84 
85 	snprintf(name, sizeof(name), "ps:%lu", freq);
86 
87 	/* Create per-ps directory */
88 	d = debugfs_create_dir(name, pd);
89 	debugfs_create_file("frequency", 0444, d, &em_dbg[i],
90 			    &em_debug_frequency_fops);
91 	debugfs_create_file("power", 0444, d, &em_dbg[i],
92 			    &em_debug_power_fops);
93 	debugfs_create_file("cost", 0444, d, &em_dbg[i],
94 			    &em_debug_cost_fops);
95 	debugfs_create_file("performance", 0444, d, &em_dbg[i],
96 			    &em_debug_performance_fops);
97 	debugfs_create_file("inefficient", 0444, d, &em_dbg[i],
98 			    &em_debug_inefficiency_fops);
99 }
100 
em_debug_cpus_show(struct seq_file * s,void * unused)101 static int em_debug_cpus_show(struct seq_file *s, void *unused)
102 {
103 	seq_printf(s, "%*pbl\n", cpumask_pr_args(to_cpumask(s->private)));
104 
105 	return 0;
106 }
107 DEFINE_SHOW_ATTRIBUTE(em_debug_cpus);
108 
em_debug_flags_show(struct seq_file * s,void * unused)109 static int em_debug_flags_show(struct seq_file *s, void *unused)
110 {
111 	struct em_perf_domain *pd = s->private;
112 
113 	seq_printf(s, "%#lx\n", pd->flags);
114 
115 	return 0;
116 }
117 DEFINE_SHOW_ATTRIBUTE(em_debug_flags);
118 
em_debug_create_pd(struct device * dev)119 static void em_debug_create_pd(struct device *dev)
120 {
121 	struct em_dbg_info *em_dbg;
122 	struct dentry *d;
123 	int i;
124 
125 	/* Create the directory of the performance domain */
126 	d = debugfs_create_dir(dev_name(dev), rootdir);
127 
128 	if (_is_cpu_device(dev))
129 		debugfs_create_file("cpus", 0444, d, dev->em_pd->cpus,
130 				    &em_debug_cpus_fops);
131 
132 	debugfs_create_file("flags", 0444, d, dev->em_pd,
133 			    &em_debug_flags_fops);
134 
135 	em_dbg = devm_kcalloc(dev, dev->em_pd->nr_perf_states,
136 			      sizeof(*em_dbg), GFP_KERNEL);
137 	if (!em_dbg)
138 		return;
139 
140 	/* Create a sub-directory for each performance state */
141 	for (i = 0; i < dev->em_pd->nr_perf_states; i++)
142 		em_debug_create_ps(dev->em_pd, em_dbg, i, d);
143 
144 }
145 
em_debug_remove_pd(struct device * dev)146 static void em_debug_remove_pd(struct device *dev)
147 {
148 	debugfs_lookup_and_remove(dev_name(dev), rootdir);
149 }
150 
em_debug_init(void)151 static int __init em_debug_init(void)
152 {
153 	/* Create /sys/kernel/debug/energy_model directory */
154 	rootdir = debugfs_create_dir("energy_model", NULL);
155 
156 	return 0;
157 }
158 fs_initcall(em_debug_init);
159 #else /* CONFIG_DEBUG_FS */
em_debug_create_pd(struct device * dev)160 static void em_debug_create_pd(struct device *dev) {}
em_debug_remove_pd(struct device * dev)161 static void em_debug_remove_pd(struct device *dev) {}
162 #endif
163 
em_release_table_kref(struct kref * kref)164 static void em_release_table_kref(struct kref *kref)
165 {
166 	/* It was the last owner of this table so we can free */
167 	kfree_rcu(container_of(kref, struct em_perf_table, kref), rcu);
168 }
169 
170 /**
171  * em_table_free() - Handles safe free of the EM table when needed
172  * @table : EM table which is going to be freed
173  *
174  * No return values.
175  */
em_table_free(struct em_perf_table * table)176 void em_table_free(struct em_perf_table *table)
177 {
178 	kref_put(&table->kref, em_release_table_kref);
179 }
180 
181 /**
182  * em_table_alloc() - Allocate a new EM table
183  * @pd		: EM performance domain for which this must be done
184  *
185  * Allocate a new EM table and initialize its kref to indicate that it
186  * has a user.
187  * Returns allocated table or NULL.
188  */
em_table_alloc(struct em_perf_domain * pd)189 struct em_perf_table *em_table_alloc(struct em_perf_domain *pd)
190 {
191 	struct em_perf_table *table;
192 	int table_size;
193 
194 	table_size = sizeof(struct em_perf_state) * pd->nr_perf_states;
195 
196 	table = kzalloc(sizeof(*table) + table_size, GFP_KERNEL);
197 	if (!table)
198 		return NULL;
199 
200 	kref_init(&table->kref);
201 
202 	return table;
203 }
204 
em_init_performance(struct device * dev,struct em_perf_domain * pd,struct em_perf_state * table,int nr_states)205 static void em_init_performance(struct device *dev, struct em_perf_domain *pd,
206 				struct em_perf_state *table, int nr_states)
207 {
208 	u64 fmax, max_cap;
209 	int i, cpu;
210 
211 	/* This is needed only for CPUs and EAS skip other devices */
212 	if (!_is_cpu_device(dev))
213 		return;
214 
215 	cpu = cpumask_first(em_span_cpus(pd));
216 
217 	/*
218 	 * Calculate the performance value for each frequency with
219 	 * linear relationship. The final CPU capacity might not be ready at
220 	 * boot time, but the EM will be updated a bit later with correct one.
221 	 */
222 	fmax = (u64) table[nr_states - 1].frequency;
223 	max_cap = (u64) arch_scale_cpu_capacity(cpu);
224 	for (i = 0; i < nr_states; i++)
225 		table[i].performance = div64_u64(max_cap * table[i].frequency,
226 						 fmax);
227 }
228 
em_compute_costs(struct device * dev,struct em_perf_state * table,struct em_data_callback * cb,int nr_states,unsigned long flags)229 static int em_compute_costs(struct device *dev, struct em_perf_state *table,
230 			    struct em_data_callback *cb, int nr_states,
231 			    unsigned long flags)
232 {
233 	unsigned long prev_cost = ULONG_MAX;
234 	int i, ret;
235 
236 	/* This is needed only for CPUs and EAS skip other devices */
237 	if (!_is_cpu_device(dev))
238 		return 0;
239 
240 	/* Compute the cost of each performance state. */
241 	for (i = nr_states - 1; i >= 0; i--) {
242 		unsigned long power_res, cost;
243 
244 		if ((flags & EM_PERF_DOMAIN_ARTIFICIAL) && cb->get_cost) {
245 			ret = cb->get_cost(dev, table[i].frequency, &cost);
246 			if (ret || !cost || cost > EM_MAX_POWER) {
247 				dev_err(dev, "EM: invalid cost %lu %d\n",
248 					cost, ret);
249 				return -EINVAL;
250 			}
251 		} else {
252 			/* increase resolution of 'cost' precision */
253 			power_res = table[i].power * 10;
254 			cost = power_res / table[i].performance;
255 		}
256 
257 		table[i].cost = cost;
258 
259 		if (table[i].cost >= prev_cost) {
260 			table[i].flags = EM_PERF_STATE_INEFFICIENT;
261 			dev_dbg(dev, "EM: OPP:%lu is inefficient\n",
262 				table[i].frequency);
263 		} else {
264 			prev_cost = table[i].cost;
265 		}
266 	}
267 
268 	return 0;
269 }
270 
271 /**
272  * em_dev_compute_costs() - Calculate cost values for new runtime EM table
273  * @dev		: Device for which the EM table is to be updated
274  * @table	: The new EM table that is going to get the costs calculated
275  * @nr_states	: Number of performance states
276  *
277  * Calculate the em_perf_state::cost values for new runtime EM table. The
278  * values are used for EAS during task placement. It also calculates and sets
279  * the efficiency flag for each performance state. When the function finish
280  * successfully the EM table is ready to be updated and used by EAS.
281  *
282  * Return 0 on success or a proper error in case of failure.
283  */
em_dev_compute_costs(struct device * dev,struct em_perf_state * table,int nr_states)284 int em_dev_compute_costs(struct device *dev, struct em_perf_state *table,
285 			 int nr_states)
286 {
287 	return em_compute_costs(dev, table, NULL, nr_states, 0);
288 }
289 
290 /**
291  * em_dev_update_perf_domain() - Update runtime EM table for a device
292  * @dev		: Device for which the EM is to be updated
293  * @new_table	: The new EM table that is going to be used from now
294  *
295  * Update EM runtime modifiable table for the @dev using the provided @table.
296  *
297  * This function uses a mutex to serialize writers, so it must not be called
298  * from a non-sleeping context.
299  *
300  * Return 0 on success or an error code on failure.
301  */
em_dev_update_perf_domain(struct device * dev,struct em_perf_table * new_table)302 int em_dev_update_perf_domain(struct device *dev,
303 			      struct em_perf_table *new_table)
304 {
305 	struct em_perf_table *old_table;
306 	struct em_perf_domain *pd;
307 
308 	if (!dev)
309 		return -EINVAL;
310 
311 	/* Serialize update/unregister or concurrent updates */
312 	mutex_lock(&em_pd_mutex);
313 
314 	if (!dev->em_pd) {
315 		mutex_unlock(&em_pd_mutex);
316 		return -EINVAL;
317 	}
318 	pd = dev->em_pd;
319 
320 	kref_get(&new_table->kref);
321 
322 	old_table = rcu_dereference_protected(pd->em_table,
323 					      lockdep_is_held(&em_pd_mutex));
324 	rcu_assign_pointer(pd->em_table, new_table);
325 
326 	em_cpufreq_update_efficiencies(dev, new_table->state);
327 
328 	em_table_free(old_table);
329 
330 	mutex_unlock(&em_pd_mutex);
331 	return 0;
332 }
333 EXPORT_SYMBOL_GPL(em_dev_update_perf_domain);
334 
em_create_perf_table(struct device * dev,struct em_perf_domain * pd,struct em_perf_state * table,struct em_data_callback * cb,unsigned long flags)335 static int em_create_perf_table(struct device *dev, struct em_perf_domain *pd,
336 				struct em_perf_state *table,
337 				struct em_data_callback *cb,
338 				unsigned long flags)
339 {
340 	unsigned long power, freq, prev_freq = 0;
341 	int nr_states = pd->nr_perf_states;
342 	int i, ret;
343 
344 	/* Build the list of performance states for this performance domain */
345 	for (i = 0, freq = 0; i < nr_states; i++, freq++) {
346 		/*
347 		 * active_power() is a driver callback which ceils 'freq' to
348 		 * lowest performance state of 'dev' above 'freq' and updates
349 		 * 'power' and 'freq' accordingly.
350 		 */
351 		ret = cb->active_power(dev, &power, &freq);
352 		if (ret) {
353 			dev_err(dev, "EM: invalid perf. state: %d\n",
354 				ret);
355 			return -EINVAL;
356 		}
357 
358 		/*
359 		 * We expect the driver callback to increase the frequency for
360 		 * higher performance states.
361 		 */
362 		if (freq <= prev_freq) {
363 			dev_err(dev, "EM: non-increasing freq: %lu\n",
364 				freq);
365 			return -EINVAL;
366 		}
367 
368 		/*
369 		 * The power returned by active_state() is expected to be
370 		 * positive and be in range.
371 		 */
372 		if (!power || power > EM_MAX_POWER) {
373 			dev_err(dev, "EM: invalid power: %lu\n",
374 				power);
375 			return -EINVAL;
376 		}
377 
378 		table[i].power = power;
379 		table[i].frequency = prev_freq = freq;
380 	}
381 
382 	em_init_performance(dev, pd, table, nr_states);
383 
384 	ret = em_compute_costs(dev, table, cb, nr_states, flags);
385 	if (ret)
386 		return -EINVAL;
387 
388 	return 0;
389 }
390 
em_create_pd(struct device * dev,int nr_states,struct em_data_callback * cb,cpumask_t * cpus,unsigned long flags)391 static int em_create_pd(struct device *dev, int nr_states,
392 			struct em_data_callback *cb, cpumask_t *cpus,
393 			unsigned long flags)
394 {
395 	struct em_perf_table *em_table;
396 	struct em_perf_domain *pd;
397 	struct device *cpu_dev;
398 	int cpu, ret, num_cpus;
399 
400 	if (_is_cpu_device(dev)) {
401 		num_cpus = cpumask_weight(cpus);
402 
403 		/* Prevent max possible energy calculation to not overflow */
404 		if (num_cpus > EM_MAX_NUM_CPUS) {
405 			dev_err(dev, "EM: too many CPUs, overflow possible\n");
406 			return -EINVAL;
407 		}
408 
409 		pd = kzalloc(sizeof(*pd) + cpumask_size(), GFP_KERNEL);
410 		if (!pd)
411 			return -ENOMEM;
412 
413 		cpumask_copy(em_span_cpus(pd), cpus);
414 	} else {
415 		pd = kzalloc(sizeof(*pd), GFP_KERNEL);
416 		if (!pd)
417 			return -ENOMEM;
418 	}
419 
420 	pd->nr_perf_states = nr_states;
421 
422 	em_table = em_table_alloc(pd);
423 	if (!em_table)
424 		goto free_pd;
425 
426 	ret = em_create_perf_table(dev, pd, em_table->state, cb, flags);
427 	if (ret)
428 		goto free_pd_table;
429 
430 	rcu_assign_pointer(pd->em_table, em_table);
431 
432 	if (_is_cpu_device(dev))
433 		for_each_cpu(cpu, cpus) {
434 			cpu_dev = get_cpu_device(cpu);
435 			cpu_dev->em_pd = pd;
436 		}
437 
438 	dev->em_pd = pd;
439 
440 	return 0;
441 
442 free_pd_table:
443 	kfree(em_table);
444 free_pd:
445 	kfree(pd);
446 	return -EINVAL;
447 }
448 
449 static void
em_cpufreq_update_efficiencies(struct device * dev,struct em_perf_state * table)450 em_cpufreq_update_efficiencies(struct device *dev, struct em_perf_state *table)
451 {
452 	struct em_perf_domain *pd = dev->em_pd;
453 	struct cpufreq_policy *policy;
454 	int found = 0;
455 	int i, cpu;
456 
457 	if (!_is_cpu_device(dev))
458 		return;
459 
460 	/* Try to get a CPU which is active and in this PD */
461 	cpu = cpumask_first_and(em_span_cpus(pd), cpu_active_mask);
462 	if (cpu >= nr_cpu_ids) {
463 		dev_warn(dev, "EM: No online CPU for CPUFreq policy\n");
464 		return;
465 	}
466 
467 	policy = cpufreq_cpu_get(cpu);
468 	if (!policy) {
469 		dev_warn(dev, "EM: Access to CPUFreq policy failed\n");
470 		return;
471 	}
472 
473 	for (i = 0; i < pd->nr_perf_states; i++) {
474 		if (!(table[i].flags & EM_PERF_STATE_INEFFICIENT))
475 			continue;
476 
477 		if (!cpufreq_table_set_inefficient(policy, table[i].frequency))
478 			found++;
479 	}
480 
481 	cpufreq_cpu_put(policy);
482 
483 	if (!found)
484 		return;
485 
486 	/*
487 	 * Efficiencies have been installed in CPUFreq, inefficient frequencies
488 	 * will be skipped. The EM can do the same.
489 	 */
490 	pd->flags |= EM_PERF_DOMAIN_SKIP_INEFFICIENCIES;
491 }
492 
493 /**
494  * em_pd_get() - Return the performance domain for a device
495  * @dev : Device to find the performance domain for
496  *
497  * Returns the performance domain to which @dev belongs, or NULL if it doesn't
498  * exist.
499  */
em_pd_get(struct device * dev)500 struct em_perf_domain *em_pd_get(struct device *dev)
501 {
502 	if (IS_ERR_OR_NULL(dev))
503 		return NULL;
504 
505 	return dev->em_pd;
506 }
507 EXPORT_SYMBOL_GPL(em_pd_get);
508 
509 /**
510  * em_cpu_get() - Return the performance domain for a CPU
511  * @cpu : CPU to find the performance domain for
512  *
513  * Returns the performance domain to which @cpu belongs, or NULL if it doesn't
514  * exist.
515  */
em_cpu_get(int cpu)516 struct em_perf_domain *em_cpu_get(int cpu)
517 {
518 	struct device *cpu_dev;
519 
520 	cpu_dev = get_cpu_device(cpu);
521 	if (!cpu_dev)
522 		return NULL;
523 
524 	return em_pd_get(cpu_dev);
525 }
526 EXPORT_SYMBOL_GPL(em_cpu_get);
527 
528 /**
529  * em_dev_register_perf_domain() - Register the Energy Model (EM) for a device
530  * @dev		: Device for which the EM is to register
531  * @nr_states	: Number of performance states to register
532  * @cb		: Callback functions providing the data of the Energy Model
533  * @cpus	: Pointer to cpumask_t, which in case of a CPU device is
534  *		obligatory. It can be taken from i.e. 'policy->cpus'. For other
535  *		type of devices this should be set to NULL.
536  * @microwatts	: Flag indicating that the power values are in micro-Watts or
537  *		in some other scale. It must be set properly.
538  *
539  * Create Energy Model tables for a performance domain using the callbacks
540  * defined in cb.
541  *
542  * The @microwatts is important to set with correct value. Some kernel
543  * sub-systems might rely on this flag and check if all devices in the EM are
544  * using the same scale.
545  *
546  * If multiple clients register the same performance domain, all but the first
547  * registration will be ignored.
548  *
549  * Return 0 on success
550  */
em_dev_register_perf_domain(struct device * dev,unsigned int nr_states,struct em_data_callback * cb,cpumask_t * cpus,bool microwatts)551 int em_dev_register_perf_domain(struct device *dev, unsigned int nr_states,
552 				struct em_data_callback *cb, cpumask_t *cpus,
553 				bool microwatts)
554 {
555 	struct em_perf_table *em_table;
556 	unsigned long cap, prev_cap = 0;
557 	unsigned long flags = 0;
558 	int cpu, ret;
559 
560 	if (!dev || !nr_states || !cb)
561 		return -EINVAL;
562 
563 	/*
564 	 * Use a mutex to serialize the registration of performance domains and
565 	 * let the driver-defined callback functions sleep.
566 	 */
567 	mutex_lock(&em_pd_mutex);
568 
569 	if (dev->em_pd) {
570 		ret = -EEXIST;
571 		goto unlock;
572 	}
573 
574 	if (_is_cpu_device(dev)) {
575 		if (!cpus) {
576 			dev_err(dev, "EM: invalid CPU mask\n");
577 			ret = -EINVAL;
578 			goto unlock;
579 		}
580 
581 		for_each_cpu(cpu, cpus) {
582 			if (em_cpu_get(cpu)) {
583 				dev_err(dev, "EM: exists for CPU%d\n", cpu);
584 				ret = -EEXIST;
585 				goto unlock;
586 			}
587 			/*
588 			 * All CPUs of a domain must have the same
589 			 * micro-architecture since they all share the same
590 			 * table.
591 			 */
592 			cap = arch_scale_cpu_capacity(cpu);
593 			if (prev_cap && prev_cap != cap) {
594 				dev_err(dev, "EM: CPUs of %*pbl must have the same capacity\n",
595 					cpumask_pr_args(cpus));
596 
597 				ret = -EINVAL;
598 				goto unlock;
599 			}
600 			prev_cap = cap;
601 		}
602 	}
603 
604 	if (microwatts)
605 		flags |= EM_PERF_DOMAIN_MICROWATTS;
606 	else if (cb->get_cost)
607 		flags |= EM_PERF_DOMAIN_ARTIFICIAL;
608 
609 	/*
610 	 * EM only supports uW (exception is artificial EM).
611 	 * Therefore, check and force the drivers to provide
612 	 * power in uW.
613 	 */
614 	if (!microwatts && !(flags & EM_PERF_DOMAIN_ARTIFICIAL)) {
615 		dev_err(dev, "EM: only supports uW power values\n");
616 		ret = -EINVAL;
617 		goto unlock;
618 	}
619 
620 	ret = em_create_pd(dev, nr_states, cb, cpus, flags);
621 	if (ret)
622 		goto unlock;
623 
624 	dev->em_pd->flags |= flags;
625 	dev->em_pd->min_perf_state = 0;
626 	dev->em_pd->max_perf_state = nr_states - 1;
627 
628 	em_table = rcu_dereference_protected(dev->em_pd->em_table,
629 					     lockdep_is_held(&em_pd_mutex));
630 	em_cpufreq_update_efficiencies(dev, em_table->state);
631 
632 	em_debug_create_pd(dev);
633 	dev_info(dev, "EM: created perf domain\n");
634 
635 unlock:
636 	mutex_unlock(&em_pd_mutex);
637 
638 	if (_is_cpu_device(dev))
639 		em_check_capacity_update();
640 
641 	return ret;
642 }
643 EXPORT_SYMBOL_GPL(em_dev_register_perf_domain);
644 
645 /**
646  * em_dev_unregister_perf_domain() - Unregister Energy Model (EM) for a device
647  * @dev		: Device for which the EM is registered
648  *
649  * Unregister the EM for the specified @dev (but not a CPU device).
650  */
em_dev_unregister_perf_domain(struct device * dev)651 void em_dev_unregister_perf_domain(struct device *dev)
652 {
653 	if (IS_ERR_OR_NULL(dev) || !dev->em_pd)
654 		return;
655 
656 	if (_is_cpu_device(dev))
657 		return;
658 
659 	/*
660 	 * The mutex separates all register/unregister requests and protects
661 	 * from potential clean-up/setup issues in the debugfs directories.
662 	 * The debugfs directory name is the same as device's name.
663 	 */
664 	mutex_lock(&em_pd_mutex);
665 	em_debug_remove_pd(dev);
666 
667 	em_table_free(rcu_dereference_protected(dev->em_pd->em_table,
668 						lockdep_is_held(&em_pd_mutex)));
669 
670 	kfree(dev->em_pd);
671 	dev->em_pd = NULL;
672 	mutex_unlock(&em_pd_mutex);
673 }
674 EXPORT_SYMBOL_GPL(em_dev_unregister_perf_domain);
675 
em_table_dup(struct em_perf_domain * pd)676 static struct em_perf_table *em_table_dup(struct em_perf_domain *pd)
677 {
678 	struct em_perf_table *em_table;
679 	struct em_perf_state *ps, *new_ps;
680 	int ps_size;
681 
682 	em_table = em_table_alloc(pd);
683 	if (!em_table)
684 		return NULL;
685 
686 	new_ps = em_table->state;
687 
688 	rcu_read_lock();
689 	ps = em_perf_state_from_pd(pd);
690 	/* Initialize data based on old table */
691 	ps_size = sizeof(struct em_perf_state) * pd->nr_perf_states;
692 	memcpy(new_ps, ps, ps_size);
693 
694 	rcu_read_unlock();
695 
696 	return em_table;
697 }
698 
em_recalc_and_update(struct device * dev,struct em_perf_domain * pd,struct em_perf_table * em_table)699 static int em_recalc_and_update(struct device *dev, struct em_perf_domain *pd,
700 				struct em_perf_table *em_table)
701 {
702 	int ret;
703 
704 	ret = em_compute_costs(dev, em_table->state, NULL, pd->nr_perf_states,
705 			       pd->flags);
706 	if (ret)
707 		goto free_em_table;
708 
709 	ret = em_dev_update_perf_domain(dev, em_table);
710 	if (ret)
711 		goto free_em_table;
712 
713 	/*
714 	 * This is one-time-update, so give up the ownership in this updater.
715 	 * The EM framework has incremented the usage counter and from now
716 	 * will keep the reference (then free the memory when needed).
717 	 */
718 free_em_table:
719 	em_table_free(em_table);
720 	return ret;
721 }
722 
723 /*
724  * Adjustment of CPU performance values after boot, when all CPUs capacites
725  * are correctly calculated.
726  */
em_adjust_new_capacity(struct device * dev,struct em_perf_domain * pd,u64 max_cap)727 static void em_adjust_new_capacity(struct device *dev,
728 				   struct em_perf_domain *pd,
729 				   u64 max_cap)
730 {
731 	struct em_perf_table *em_table;
732 
733 	em_table = em_table_dup(pd);
734 	if (!em_table) {
735 		dev_warn(dev, "EM: allocation failed\n");
736 		return;
737 	}
738 
739 	em_init_performance(dev, pd, em_table->state, pd->nr_perf_states);
740 
741 	em_recalc_and_update(dev, pd, em_table);
742 }
743 
em_check_capacity_update(void)744 static void em_check_capacity_update(void)
745 {
746 	cpumask_var_t cpu_done_mask;
747 	struct em_perf_state *table;
748 	struct em_perf_domain *pd;
749 	unsigned long cpu_capacity;
750 	int cpu;
751 
752 	if (!zalloc_cpumask_var(&cpu_done_mask, GFP_KERNEL)) {
753 		pr_warn("no free memory\n");
754 		return;
755 	}
756 
757 	/* Check if CPUs capacity has changed than update EM */
758 	for_each_possible_cpu(cpu) {
759 		struct cpufreq_policy *policy;
760 		unsigned long em_max_perf;
761 		struct device *dev;
762 
763 		if (cpumask_test_cpu(cpu, cpu_done_mask))
764 			continue;
765 
766 		policy = cpufreq_cpu_get(cpu);
767 		if (!policy) {
768 			pr_debug("Accessing cpu%d policy failed\n", cpu);
769 			schedule_delayed_work(&em_update_work,
770 					      msecs_to_jiffies(1000));
771 			break;
772 		}
773 		cpufreq_cpu_put(policy);
774 
775 		pd = em_cpu_get(cpu);
776 		if (!pd || em_is_artificial(pd))
777 			continue;
778 
779 		cpumask_or(cpu_done_mask, cpu_done_mask,
780 			   em_span_cpus(pd));
781 
782 		cpu_capacity = arch_scale_cpu_capacity(cpu);
783 
784 		rcu_read_lock();
785 		table = em_perf_state_from_pd(pd);
786 		em_max_perf = table[pd->nr_perf_states - 1].performance;
787 		rcu_read_unlock();
788 
789 		/*
790 		 * Check if the CPU capacity has been adjusted during boot
791 		 * and trigger the update for new performance values.
792 		 */
793 		if (em_max_perf == cpu_capacity)
794 			continue;
795 
796 		pr_debug("updating cpu%d cpu_cap=%lu old capacity=%lu\n",
797 			 cpu, cpu_capacity, em_max_perf);
798 
799 		dev = get_cpu_device(cpu);
800 		em_adjust_new_capacity(dev, pd, cpu_capacity);
801 	}
802 
803 	free_cpumask_var(cpu_done_mask);
804 }
805 
em_update_workfn(struct work_struct * work)806 static void em_update_workfn(struct work_struct *work)
807 {
808 	em_check_capacity_update();
809 }
810 
811 /**
812  * em_dev_update_chip_binning() - Update Energy Model after the new voltage
813  *				information is present in the OPPs.
814  * @dev		: Device for which the Energy Model has to be updated.
815  *
816  * This function allows to update easily the EM with new values available in
817  * the OPP framework and DT. It can be used after the chip has been properly
818  * verified by device drivers and the voltages adjusted for the 'chip binning'.
819  */
em_dev_update_chip_binning(struct device * dev)820 int em_dev_update_chip_binning(struct device *dev)
821 {
822 	struct em_perf_table *em_table;
823 	struct em_perf_domain *pd;
824 	int i, ret;
825 
826 	if (IS_ERR_OR_NULL(dev))
827 		return -EINVAL;
828 
829 	pd = em_pd_get(dev);
830 	if (!pd) {
831 		dev_warn(dev, "Couldn't find Energy Model\n");
832 		return -EINVAL;
833 	}
834 
835 	em_table = em_table_dup(pd);
836 	if (!em_table) {
837 		dev_warn(dev, "EM: allocation failed\n");
838 		return -ENOMEM;
839 	}
840 
841 	/* Update power values which might change due to new voltage in OPPs */
842 	for (i = 0; i < pd->nr_perf_states; i++) {
843 		unsigned long freq = em_table->state[i].frequency;
844 		unsigned long power;
845 
846 		ret = dev_pm_opp_calc_power(dev, &power, &freq);
847 		if (ret) {
848 			em_table_free(em_table);
849 			return ret;
850 		}
851 
852 		em_table->state[i].power = power;
853 	}
854 
855 	return em_recalc_and_update(dev, pd, em_table);
856 }
857 EXPORT_SYMBOL_GPL(em_dev_update_chip_binning);
858 
859 
860 /**
861  * em_update_performance_limits() - Update Energy Model with performance
862  *				limits information.
863  * @pd			: Performance Domain with EM that has to be updated.
864  * @freq_min_khz	: New minimum allowed frequency for this device.
865  * @freq_max_khz	: New maximum allowed frequency for this device.
866  *
867  * This function allows to update the EM with information about available
868  * performance levels. It takes the minimum and maximum frequency in kHz
869  * and does internal translation to performance levels.
870  * Returns 0 on success or -EINVAL when failed.
871  */
em_update_performance_limits(struct em_perf_domain * pd,unsigned long freq_min_khz,unsigned long freq_max_khz)872 int em_update_performance_limits(struct em_perf_domain *pd,
873 		unsigned long freq_min_khz, unsigned long freq_max_khz)
874 {
875 	struct em_perf_state *table;
876 	int min_ps = -1;
877 	int max_ps = -1;
878 	int i;
879 
880 	if (!pd)
881 		return -EINVAL;
882 
883 	rcu_read_lock();
884 	table = em_perf_state_from_pd(pd);
885 
886 	for (i = 0; i < pd->nr_perf_states; i++) {
887 		if (freq_min_khz == table[i].frequency)
888 			min_ps = i;
889 		if (freq_max_khz == table[i].frequency)
890 			max_ps = i;
891 	}
892 	rcu_read_unlock();
893 
894 	/* Only update when both are found and sane */
895 	if (min_ps < 0 || max_ps < 0 || max_ps < min_ps)
896 		return -EINVAL;
897 
898 
899 	/* Guard simultaneous updates and make them atomic */
900 	mutex_lock(&em_pd_mutex);
901 	pd->min_perf_state = min_ps;
902 	pd->max_perf_state = max_ps;
903 	mutex_unlock(&em_pd_mutex);
904 
905 	return 0;
906 }
907 EXPORT_SYMBOL_GPL(em_update_performance_limits);
908