1 // SPDX-License-Identifier: GPL-2.0
3 * Energy Model of devices
5 * Copyright (c) 2018-2021, Arm ltd.
6 * Written by: Quentin Perret, Arm ltd.
7 * Improvements provided by: Lukasz Luba, Arm ltd.
10 #define pr_fmt(fmt) "energy_model: " fmt
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>
21 * Mutex serializing the registrations of performance domains and letting
22 * callbacks defined by drivers sleep.
24 static DEFINE_MUTEX(em_pd_mutex);
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);
32 static bool _is_cpu_device(struct device *dev)
34 return (dev->bus == &cpu_subsys);
37 #ifdef CONFIG_DEBUG_FS
38 static struct dentry *rootdir;
41 struct em_perf_domain *pd;
45 #define DEFINE_EM_DBG_SHOW(name, fname) \
46 static int em_debug_##fname##_show(struct seq_file *s, void *unused) \
48 struct em_dbg_info *em_dbg = s->private; \
49 struct em_perf_state *table; \
53 table = em_perf_state_from_pd(em_dbg->pd); \
54 val = table[em_dbg->ps_id].name; \
57 seq_printf(s, "%lu\n", val); \
60 DEFINE_SHOW_ATTRIBUTE(em_debug_##fname)
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);
68 static void em_debug_create_ps(struct em_perf_domain *em_pd,
69 struct em_dbg_info *em_dbg, int i,
72 struct em_perf_state *table;
81 table = em_perf_state_from_pd(em_pd);
82 freq = table[i].frequency;
85 snprintf(name, sizeof(name), "ps:%lu", freq);
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],
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);
101 static int em_debug_cpus_show(struct seq_file *s, void *unused)
103 seq_printf(s, "%*pbl\n", cpumask_pr_args(to_cpumask(s->private)));
107 DEFINE_SHOW_ATTRIBUTE(em_debug_cpus);
109 static int em_debug_flags_show(struct seq_file *s, void *unused)
111 struct em_perf_domain *pd = s->private;
113 seq_printf(s, "%#lx\n", pd->flags);
117 DEFINE_SHOW_ATTRIBUTE(em_debug_flags);
119 static void em_debug_create_pd(struct device *dev)
121 struct em_dbg_info *em_dbg;
125 /* Create the directory of the performance domain */
126 d = debugfs_create_dir(dev_name(dev), rootdir);
128 if (_is_cpu_device(dev))
129 debugfs_create_file("cpus", 0444, d, dev->em_pd->cpus,
130 &em_debug_cpus_fops);
132 debugfs_create_file("flags", 0444, d, dev->em_pd,
133 &em_debug_flags_fops);
135 em_dbg = devm_kcalloc(dev, dev->em_pd->nr_perf_states,
136 sizeof(*em_dbg), GFP_KERNEL);
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);
146 static void em_debug_remove_pd(struct device *dev)
148 debugfs_lookup_and_remove(dev_name(dev), rootdir);
151 static int __init em_debug_init(void)
153 /* Create /sys/kernel/debug/energy_model directory */
154 rootdir = debugfs_create_dir("energy_model", NULL);
158 fs_initcall(em_debug_init);
159 #else /* CONFIG_DEBUG_FS */
160 static void em_debug_create_pd(struct device *dev) {}
161 static void em_debug_remove_pd(struct device *dev) {}
164 static void em_destroy_table_rcu(struct rcu_head *rp)
166 struct em_perf_table __rcu *table;
168 table = container_of(rp, struct em_perf_table, rcu);
172 static void em_release_table_kref(struct kref *kref)
174 struct em_perf_table __rcu *table;
176 /* It was the last owner of this table so we can free */
177 table = container_of(kref, struct em_perf_table, kref);
179 call_rcu(&table->rcu, em_destroy_table_rcu);
183 * em_table_free() - Handles safe free of the EM table when needed
184 * @table : EM table which is going to be freed
188 void em_table_free(struct em_perf_table __rcu *table)
190 kref_put(&table->kref, em_release_table_kref);
194 * em_table_alloc() - Allocate a new EM table
195 * @pd : EM performance domain for which this must be done
197 * Allocate a new EM table and initialize its kref to indicate that it
199 * Returns allocated table or NULL.
201 struct em_perf_table __rcu *em_table_alloc(struct em_perf_domain *pd)
203 struct em_perf_table __rcu *table;
206 table_size = sizeof(struct em_perf_state) * pd->nr_perf_states;
208 table = kzalloc(sizeof(*table) + table_size, GFP_KERNEL);
212 kref_init(&table->kref);
217 static void em_init_performance(struct device *dev, struct em_perf_domain *pd,
218 struct em_perf_state *table, int nr_states)
223 /* This is needed only for CPUs and EAS skip other devices */
224 if (!_is_cpu_device(dev))
227 cpu = cpumask_first(em_span_cpus(pd));
230 * Calculate the performance value for each frequency with
231 * linear relationship. The final CPU capacity might not be ready at
232 * boot time, but the EM will be updated a bit later with correct one.
234 fmax = (u64) table[nr_states - 1].frequency;
235 max_cap = (u64) arch_scale_cpu_capacity(cpu);
236 for (i = 0; i < nr_states; i++)
237 table[i].performance = div64_u64(max_cap * table[i].frequency,
241 static int em_compute_costs(struct device *dev, struct em_perf_state *table,
242 struct em_data_callback *cb, int nr_states,
245 unsigned long prev_cost = ULONG_MAX;
248 /* Compute the cost of each performance state. */
249 for (i = nr_states - 1; i >= 0; i--) {
250 unsigned long power_res, cost;
252 if ((flags & EM_PERF_DOMAIN_ARTIFICIAL) && cb->get_cost) {
253 ret = cb->get_cost(dev, table[i].frequency, &cost);
254 if (ret || !cost || cost > EM_MAX_POWER) {
255 dev_err(dev, "EM: invalid cost %lu %d\n",
260 /* increase resolution of 'cost' precision */
261 power_res = table[i].power * 10;
262 cost = power_res / table[i].performance;
265 table[i].cost = cost;
267 if (table[i].cost >= prev_cost) {
268 table[i].flags = EM_PERF_STATE_INEFFICIENT;
269 dev_dbg(dev, "EM: OPP:%lu is inefficient\n",
272 prev_cost = table[i].cost;
280 * em_dev_compute_costs() - Calculate cost values for new runtime EM table
281 * @dev : Device for which the EM table is to be updated
282 * @table : The new EM table that is going to get the costs calculated
283 * @nr_states : Number of performance states
285 * Calculate the em_perf_state::cost values for new runtime EM table. The
286 * values are used for EAS during task placement. It also calculates and sets
287 * the efficiency flag for each performance state. When the function finish
288 * successfully the EM table is ready to be updated and used by EAS.
290 * Return 0 on success or a proper error in case of failure.
292 int em_dev_compute_costs(struct device *dev, struct em_perf_state *table,
295 return em_compute_costs(dev, table, NULL, nr_states, 0);
299 * em_dev_update_perf_domain() - Update runtime EM table for a device
300 * @dev : Device for which the EM is to be updated
301 * @new_table : The new EM table that is going to be used from now
303 * Update EM runtime modifiable table for the @dev using the provided @table.
305 * This function uses a mutex to serialize writers, so it must not be called
306 * from a non-sleeping context.
308 * Return 0 on success or an error code on failure.
310 int em_dev_update_perf_domain(struct device *dev,
311 struct em_perf_table __rcu *new_table)
313 struct em_perf_table __rcu *old_table;
314 struct em_perf_domain *pd;
319 /* Serialize update/unregister or concurrent updates */
320 mutex_lock(&em_pd_mutex);
323 mutex_unlock(&em_pd_mutex);
328 kref_get(&new_table->kref);
330 old_table = pd->em_table;
331 rcu_assign_pointer(pd->em_table, new_table);
333 em_cpufreq_update_efficiencies(dev, new_table->state);
335 em_table_free(old_table);
337 mutex_unlock(&em_pd_mutex);
340 EXPORT_SYMBOL_GPL(em_dev_update_perf_domain);
342 static int em_create_perf_table(struct device *dev, struct em_perf_domain *pd,
343 struct em_perf_state *table,
344 struct em_data_callback *cb,
347 unsigned long power, freq, prev_freq = 0;
348 int nr_states = pd->nr_perf_states;
351 /* Build the list of performance states for this performance domain */
352 for (i = 0, freq = 0; i < nr_states; i++, freq++) {
354 * active_power() is a driver callback which ceils 'freq' to
355 * lowest performance state of 'dev' above 'freq' and updates
356 * 'power' and 'freq' accordingly.
358 ret = cb->active_power(dev, &power, &freq);
360 dev_err(dev, "EM: invalid perf. state: %d\n",
366 * We expect the driver callback to increase the frequency for
367 * higher performance states.
369 if (freq <= prev_freq) {
370 dev_err(dev, "EM: non-increasing freq: %lu\n",
376 * The power returned by active_state() is expected to be
377 * positive and be in range.
379 if (!power || power > EM_MAX_POWER) {
380 dev_err(dev, "EM: invalid power: %lu\n",
385 table[i].power = power;
386 table[i].frequency = prev_freq = freq;
389 em_init_performance(dev, pd, table, nr_states);
391 ret = em_compute_costs(dev, table, cb, nr_states, flags);
398 static int em_create_pd(struct device *dev, int nr_states,
399 struct em_data_callback *cb, cpumask_t *cpus,
402 struct em_perf_table __rcu *em_table;
403 struct em_perf_domain *pd;
404 struct device *cpu_dev;
405 int cpu, ret, num_cpus;
407 if (_is_cpu_device(dev)) {
408 num_cpus = cpumask_weight(cpus);
410 /* Prevent max possible energy calculation to not overflow */
411 if (num_cpus > EM_MAX_NUM_CPUS) {
412 dev_err(dev, "EM: too many CPUs, overflow possible\n");
416 pd = kzalloc(sizeof(*pd) + cpumask_size(), GFP_KERNEL);
420 cpumask_copy(em_span_cpus(pd), cpus);
422 pd = kzalloc(sizeof(*pd), GFP_KERNEL);
427 pd->nr_perf_states = nr_states;
429 em_table = em_table_alloc(pd);
433 ret = em_create_perf_table(dev, pd, em_table->state, cb, flags);
437 rcu_assign_pointer(pd->em_table, em_table);
439 if (_is_cpu_device(dev))
440 for_each_cpu(cpu, cpus) {
441 cpu_dev = get_cpu_device(cpu);
457 em_cpufreq_update_efficiencies(struct device *dev, struct em_perf_state *table)
459 struct em_perf_domain *pd = dev->em_pd;
460 struct cpufreq_policy *policy;
464 if (!_is_cpu_device(dev))
467 /* Try to get a CPU which is active and in this PD */
468 cpu = cpumask_first_and(em_span_cpus(pd), cpu_active_mask);
469 if (cpu >= nr_cpu_ids) {
470 dev_warn(dev, "EM: No online CPU for CPUFreq policy\n");
474 policy = cpufreq_cpu_get(cpu);
476 dev_warn(dev, "EM: Access to CPUFreq policy failed\n");
480 for (i = 0; i < pd->nr_perf_states; i++) {
481 if (!(table[i].flags & EM_PERF_STATE_INEFFICIENT))
484 if (!cpufreq_table_set_inefficient(policy, table[i].frequency))
488 cpufreq_cpu_put(policy);
494 * Efficiencies have been installed in CPUFreq, inefficient frequencies
495 * will be skipped. The EM can do the same.
497 pd->flags |= EM_PERF_DOMAIN_SKIP_INEFFICIENCIES;
501 * em_pd_get() - Return the performance domain for a device
502 * @dev : Device to find the performance domain for
504 * Returns the performance domain to which @dev belongs, or NULL if it doesn't
507 struct em_perf_domain *em_pd_get(struct device *dev)
509 if (IS_ERR_OR_NULL(dev))
514 EXPORT_SYMBOL_GPL(em_pd_get);
517 * em_cpu_get() - Return the performance domain for a CPU
518 * @cpu : CPU to find the performance domain for
520 * Returns the performance domain to which @cpu belongs, or NULL if it doesn't
523 struct em_perf_domain *em_cpu_get(int cpu)
525 struct device *cpu_dev;
527 cpu_dev = get_cpu_device(cpu);
531 return em_pd_get(cpu_dev);
533 EXPORT_SYMBOL_GPL(em_cpu_get);
536 * em_dev_register_perf_domain() - Register the Energy Model (EM) for a device
537 * @dev : Device for which the EM is to register
538 * @nr_states : Number of performance states to register
539 * @cb : Callback functions providing the data of the Energy Model
540 * @cpus : Pointer to cpumask_t, which in case of a CPU device is
541 * obligatory. It can be taken from i.e. 'policy->cpus'. For other
542 * type of devices this should be set to NULL.
543 * @microwatts : Flag indicating that the power values are in micro-Watts or
544 * in some other scale. It must be set properly.
546 * Create Energy Model tables for a performance domain using the callbacks
549 * The @microwatts is important to set with correct value. Some kernel
550 * sub-systems might rely on this flag and check if all devices in the EM are
551 * using the same scale.
553 * If multiple clients register the same performance domain, all but the first
554 * registration will be ignored.
556 * Return 0 on success
558 int em_dev_register_perf_domain(struct device *dev, unsigned int nr_states,
559 struct em_data_callback *cb, cpumask_t *cpus,
562 unsigned long cap, prev_cap = 0;
563 unsigned long flags = 0;
566 if (!dev || !nr_states || !cb)
570 * Use a mutex to serialize the registration of performance domains and
571 * let the driver-defined callback functions sleep.
573 mutex_lock(&em_pd_mutex);
580 if (_is_cpu_device(dev)) {
582 dev_err(dev, "EM: invalid CPU mask\n");
587 for_each_cpu(cpu, cpus) {
588 if (em_cpu_get(cpu)) {
589 dev_err(dev, "EM: exists for CPU%d\n", cpu);
594 * All CPUs of a domain must have the same
595 * micro-architecture since they all share the same
598 cap = arch_scale_cpu_capacity(cpu);
599 if (prev_cap && prev_cap != cap) {
600 dev_err(dev, "EM: CPUs of %*pbl must have the same capacity\n",
601 cpumask_pr_args(cpus));
611 flags |= EM_PERF_DOMAIN_MICROWATTS;
612 else if (cb->get_cost)
613 flags |= EM_PERF_DOMAIN_ARTIFICIAL;
616 * EM only supports uW (exception is artificial EM).
617 * Therefore, check and force the drivers to provide
620 if (!microwatts && !(flags & EM_PERF_DOMAIN_ARTIFICIAL)) {
621 dev_err(dev, "EM: only supports uW power values\n");
626 ret = em_create_pd(dev, nr_states, cb, cpus, flags);
630 dev->em_pd->flags |= flags;
632 em_cpufreq_update_efficiencies(dev, dev->em_pd->em_table->state);
634 em_debug_create_pd(dev);
635 dev_info(dev, "EM: created perf domain\n");
638 mutex_unlock(&em_pd_mutex);
640 if (_is_cpu_device(dev))
641 em_check_capacity_update();
645 EXPORT_SYMBOL_GPL(em_dev_register_perf_domain);
648 * em_dev_unregister_perf_domain() - Unregister Energy Model (EM) for a device
649 * @dev : Device for which the EM is registered
651 * Unregister the EM for the specified @dev (but not a CPU device).
653 void em_dev_unregister_perf_domain(struct device *dev)
655 if (IS_ERR_OR_NULL(dev) || !dev->em_pd)
658 if (_is_cpu_device(dev))
662 * The mutex separates all register/unregister requests and protects
663 * from potential clean-up/setup issues in the debugfs directories.
664 * The debugfs directory name is the same as device's name.
666 mutex_lock(&em_pd_mutex);
667 em_debug_remove_pd(dev);
669 em_table_free(dev->em_pd->em_table);
673 mutex_unlock(&em_pd_mutex);
675 EXPORT_SYMBOL_GPL(em_dev_unregister_perf_domain);
677 static struct em_perf_table __rcu *em_table_dup(struct em_perf_domain *pd)
679 struct em_perf_table __rcu *em_table;
680 struct em_perf_state *ps, *new_ps;
683 em_table = em_table_alloc(pd);
687 new_ps = em_table->state;
690 ps = em_perf_state_from_pd(pd);
691 /* Initialize data based on old table */
692 ps_size = sizeof(struct em_perf_state) * pd->nr_perf_states;
693 memcpy(new_ps, ps, ps_size);
700 static int em_recalc_and_update(struct device *dev, struct em_perf_domain *pd,
701 struct em_perf_table __rcu *em_table)
705 ret = em_compute_costs(dev, em_table->state, NULL, pd->nr_perf_states,
710 ret = em_dev_update_perf_domain(dev, em_table);
715 * This is one-time-update, so give up the ownership in this updater.
716 * The EM framework has incremented the usage counter and from now
717 * will keep the reference (then free the memory when needed).
720 em_table_free(em_table);
725 * Adjustment of CPU performance values after boot, when all CPUs capacites
726 * are correctly calculated.
728 static void em_adjust_new_capacity(struct device *dev,
729 struct em_perf_domain *pd,
732 struct em_perf_table __rcu *em_table;
734 em_table = em_table_dup(pd);
736 dev_warn(dev, "EM: allocation failed\n");
740 em_init_performance(dev, pd, em_table->state, pd->nr_perf_states);
742 em_recalc_and_update(dev, pd, em_table);
745 static void em_check_capacity_update(void)
747 cpumask_var_t cpu_done_mask;
748 struct em_perf_state *table;
749 struct em_perf_domain *pd;
750 unsigned long cpu_capacity;
753 if (!zalloc_cpumask_var(&cpu_done_mask, GFP_KERNEL)) {
754 pr_warn("no free memory\n");
758 /* Check if CPUs capacity has changed than update EM */
759 for_each_possible_cpu(cpu) {
760 struct cpufreq_policy *policy;
761 unsigned long em_max_perf;
764 if (cpumask_test_cpu(cpu, cpu_done_mask))
767 policy = cpufreq_cpu_get(cpu);
769 pr_debug("Accessing cpu%d policy failed\n", cpu);
770 schedule_delayed_work(&em_update_work,
771 msecs_to_jiffies(1000));
774 cpufreq_cpu_put(policy);
776 pd = em_cpu_get(cpu);
777 if (!pd || em_is_artificial(pd))
780 cpumask_or(cpu_done_mask, cpu_done_mask,
783 cpu_capacity = arch_scale_cpu_capacity(cpu);
786 table = em_perf_state_from_pd(pd);
787 em_max_perf = table[pd->nr_perf_states - 1].performance;
791 * Check if the CPU capacity has been adjusted during boot
792 * and trigger the update for new performance values.
794 if (em_max_perf == cpu_capacity)
797 pr_debug("updating cpu%d cpu_cap=%lu old capacity=%lu\n",
798 cpu, cpu_capacity, em_max_perf);
800 dev = get_cpu_device(cpu);
801 em_adjust_new_capacity(dev, pd, cpu_capacity);
804 free_cpumask_var(cpu_done_mask);
807 static void em_update_workfn(struct work_struct *work)
809 em_check_capacity_update();
813 * em_dev_update_chip_binning() - Update Energy Model after the new voltage
814 * information is present in the OPPs.
815 * @dev : Device for which the Energy Model has to be updated.
817 * This function allows to update easily the EM with new values available in
818 * the OPP framework and DT. It can be used after the chip has been properly
819 * verified by device drivers and the voltages adjusted for the 'chip binning'.
821 int em_dev_update_chip_binning(struct device *dev)
823 struct em_perf_table __rcu *em_table;
824 struct em_perf_domain *pd;
827 if (IS_ERR_OR_NULL(dev))
832 dev_warn(dev, "Couldn't find Energy Model\n");
836 em_table = em_table_dup(pd);
838 dev_warn(dev, "EM: allocation failed\n");
842 /* Update power values which might change due to new voltage in OPPs */
843 for (i = 0; i < pd->nr_perf_states; i++) {
844 unsigned long freq = em_table->state[i].frequency;
847 ret = dev_pm_opp_calc_power(dev, &power, &freq);
849 em_table_free(em_table);
853 em_table->state[i].power = power;
856 return em_recalc_and_update(dev, pd, em_table);
858 EXPORT_SYMBOL_GPL(em_dev_update_chip_binning);