• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/drivers/cpufreq/cpufreq.c
4  *
5  *  Copyright (C) 2001 Russell King
6  *            (C) 2002 - 2003 Dominik Brodowski <linux@brodo.de>
7  *            (C) 2013 Viresh Kumar <viresh.kumar@linaro.org>
8  *
9  *  Oct 2005 - Ashok Raj <ashok.raj@intel.com>
10  *	Added handling for CPU hotplug
11  *  Feb 2006 - Jacob Shin <jacob.shin@amd.com>
12  *	Fix handling for CPU hotplug -- affected CPUs
13  */
14 
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 
17 #include <linux/cpu.h>
18 #include <linux/cpufreq.h>
19 #include <linux/cpufreq_times.h>
20 #include <linux/cpu_cooling.h>
21 #include <linux/delay.h>
22 #include <linux/device.h>
23 #include <linux/init.h>
24 #include <linux/kernel_stat.h>
25 #include <linux/module.h>
26 #include <linux/mutex.h>
27 #include <linux/pm_qos.h>
28 #include <linux/slab.h>
29 #include <linux/suspend.h>
30 #include <linux/syscore_ops.h>
31 #include <linux/tick.h>
32 #include <linux/units.h>
33 #include <trace/events/power.h>
34 #include <trace/hooks/cpufreq.h>
35 #include <trace/hooks/thermal.h>
36 
37 static LIST_HEAD(cpufreq_policy_list);
38 
39 /* Macros to iterate over CPU policies */
40 #define for_each_suitable_policy(__policy, __active)			 \
41 	list_for_each_entry(__policy, &cpufreq_policy_list, policy_list) \
42 		if ((__active) == !policy_is_inactive(__policy))
43 
44 #define for_each_active_policy(__policy)		\
45 	for_each_suitable_policy(__policy, true)
46 #define for_each_inactive_policy(__policy)		\
47 	for_each_suitable_policy(__policy, false)
48 
49 /* Iterate over governors */
50 static LIST_HEAD(cpufreq_governor_list);
51 #define for_each_governor(__governor)				\
52 	list_for_each_entry(__governor, &cpufreq_governor_list, governor_list)
53 
54 static char default_governor[CPUFREQ_NAME_LEN];
55 
56 /*
57  * The "cpufreq driver" - the arch- or hardware-dependent low
58  * level driver of CPUFreq support, and its spinlock. This lock
59  * also protects the cpufreq_cpu_data array.
60  */
61 static struct cpufreq_driver *cpufreq_driver;
62 static DEFINE_PER_CPU(struct cpufreq_policy *, cpufreq_cpu_data);
63 static DEFINE_RWLOCK(cpufreq_driver_lock);
64 
65 static DEFINE_STATIC_KEY_FALSE(cpufreq_freq_invariance);
cpufreq_supports_freq_invariance(void)66 bool cpufreq_supports_freq_invariance(void)
67 {
68 	return static_branch_likely(&cpufreq_freq_invariance);
69 }
70 
71 /* Flag to suspend/resume CPUFreq governors */
72 static bool cpufreq_suspended;
73 
has_target(void)74 static inline bool has_target(void)
75 {
76 	return cpufreq_driver->target_index || cpufreq_driver->target;
77 }
78 
79 /* internal prototypes */
80 static unsigned int __cpufreq_get(struct cpufreq_policy *policy);
81 static int cpufreq_init_governor(struct cpufreq_policy *policy);
82 static void cpufreq_exit_governor(struct cpufreq_policy *policy);
83 static void cpufreq_governor_limits(struct cpufreq_policy *policy);
84 static int cpufreq_set_policy(struct cpufreq_policy *policy,
85 			      struct cpufreq_governor *new_gov,
86 			      unsigned int new_pol);
87 
88 /*
89  * Two notifier lists: the "policy" list is involved in the
90  * validation process for a new CPU frequency policy; the
91  * "transition" list for kernel code that needs to handle
92  * changes to devices when the CPU clock speed changes.
93  * The mutex locks both lists.
94  */
95 static BLOCKING_NOTIFIER_HEAD(cpufreq_policy_notifier_list);
96 SRCU_NOTIFIER_HEAD_STATIC(cpufreq_transition_notifier_list);
97 
98 static int off __read_mostly;
cpufreq_disabled(void)99 static int cpufreq_disabled(void)
100 {
101 	return off;
102 }
disable_cpufreq(void)103 void disable_cpufreq(void)
104 {
105 	off = 1;
106 }
107 static DEFINE_MUTEX(cpufreq_governor_mutex);
108 
have_governor_per_policy(void)109 bool have_governor_per_policy(void)
110 {
111 	return !!(cpufreq_driver->flags & CPUFREQ_HAVE_GOVERNOR_PER_POLICY);
112 }
113 EXPORT_SYMBOL_GPL(have_governor_per_policy);
114 
115 static struct kobject *cpufreq_global_kobject;
116 
get_governor_parent_kobj(struct cpufreq_policy * policy)117 struct kobject *get_governor_parent_kobj(struct cpufreq_policy *policy)
118 {
119 	if (have_governor_per_policy())
120 		return &policy->kobj;
121 	else
122 		return cpufreq_global_kobject;
123 }
124 EXPORT_SYMBOL_GPL(get_governor_parent_kobj);
125 
get_cpu_idle_time_jiffy(unsigned int cpu,u64 * wall)126 static inline u64 get_cpu_idle_time_jiffy(unsigned int cpu, u64 *wall)
127 {
128 	struct kernel_cpustat kcpustat;
129 	u64 cur_wall_time;
130 	u64 idle_time;
131 	u64 busy_time;
132 
133 	cur_wall_time = jiffies64_to_nsecs(get_jiffies_64());
134 
135 	kcpustat_cpu_fetch(&kcpustat, cpu);
136 
137 	busy_time = kcpustat.cpustat[CPUTIME_USER];
138 	busy_time += kcpustat.cpustat[CPUTIME_SYSTEM];
139 	busy_time += kcpustat.cpustat[CPUTIME_IRQ];
140 	busy_time += kcpustat.cpustat[CPUTIME_SOFTIRQ];
141 	busy_time += kcpustat.cpustat[CPUTIME_STEAL];
142 	busy_time += kcpustat.cpustat[CPUTIME_NICE];
143 
144 	idle_time = cur_wall_time - busy_time;
145 	if (wall)
146 		*wall = div_u64(cur_wall_time, NSEC_PER_USEC);
147 
148 	return div_u64(idle_time, NSEC_PER_USEC);
149 }
150 
get_cpu_idle_time(unsigned int cpu,u64 * wall,int io_busy)151 u64 get_cpu_idle_time(unsigned int cpu, u64 *wall, int io_busy)
152 {
153 	u64 idle_time = get_cpu_idle_time_us(cpu, io_busy ? wall : NULL);
154 
155 	if (idle_time == -1ULL)
156 		return get_cpu_idle_time_jiffy(cpu, wall);
157 	else if (!io_busy)
158 		idle_time += get_cpu_iowait_time_us(cpu, wall);
159 
160 	return idle_time;
161 }
162 EXPORT_SYMBOL_GPL(get_cpu_idle_time);
163 
164 /*
165  * This is a generic cpufreq init() routine which can be used by cpufreq
166  * drivers of SMP systems. It will do following:
167  * - validate & show freq table passed
168  * - set policies transition latency
169  * - policy->cpus with all possible CPUs
170  */
cpufreq_generic_init(struct cpufreq_policy * policy,struct cpufreq_frequency_table * table,unsigned int transition_latency)171 void cpufreq_generic_init(struct cpufreq_policy *policy,
172 		struct cpufreq_frequency_table *table,
173 		unsigned int transition_latency)
174 {
175 	policy->freq_table = table;
176 	policy->cpuinfo.transition_latency = transition_latency;
177 
178 	/*
179 	 * The driver only supports the SMP configuration where all processors
180 	 * share the clock and voltage and clock.
181 	 */
182 	cpumask_setall(policy->cpus);
183 }
184 EXPORT_SYMBOL_GPL(cpufreq_generic_init);
185 
cpufreq_cpu_get_raw(unsigned int cpu)186 struct cpufreq_policy *cpufreq_cpu_get_raw(unsigned int cpu)
187 {
188 	struct cpufreq_policy *policy = per_cpu(cpufreq_cpu_data, cpu);
189 
190 	return policy && cpumask_test_cpu(cpu, policy->cpus) ? policy : NULL;
191 }
192 EXPORT_SYMBOL_GPL(cpufreq_cpu_get_raw);
193 
cpufreq_generic_get(unsigned int cpu)194 unsigned int cpufreq_generic_get(unsigned int cpu)
195 {
196 	struct cpufreq_policy *policy = cpufreq_cpu_get_raw(cpu);
197 
198 	if (!policy || IS_ERR(policy->clk)) {
199 		pr_err("%s: No %s associated to cpu: %d\n",
200 		       __func__, policy ? "clk" : "policy", cpu);
201 		return 0;
202 	}
203 
204 	return clk_get_rate(policy->clk) / 1000;
205 }
206 EXPORT_SYMBOL_GPL(cpufreq_generic_get);
207 
208 /**
209  * cpufreq_cpu_get - Return policy for a CPU and mark it as busy.
210  * @cpu: CPU to find the policy for.
211  *
212  * Call cpufreq_cpu_get_raw() to obtain a cpufreq policy for @cpu and increment
213  * the kobject reference counter of that policy.  Return a valid policy on
214  * success or NULL on failure.
215  *
216  * The policy returned by this function has to be released with the help of
217  * cpufreq_cpu_put() to balance its kobject reference counter properly.
218  */
cpufreq_cpu_get(unsigned int cpu)219 struct cpufreq_policy *cpufreq_cpu_get(unsigned int cpu)
220 {
221 	struct cpufreq_policy *policy = NULL;
222 	unsigned long flags;
223 
224 	if (WARN_ON(cpu >= nr_cpu_ids))
225 		return NULL;
226 
227 	/* get the cpufreq driver */
228 	read_lock_irqsave(&cpufreq_driver_lock, flags);
229 
230 	if (cpufreq_driver) {
231 		/* get the CPU */
232 		policy = cpufreq_cpu_get_raw(cpu);
233 		if (policy)
234 			kobject_get(&policy->kobj);
235 	}
236 
237 	read_unlock_irqrestore(&cpufreq_driver_lock, flags);
238 
239 	return policy;
240 }
241 EXPORT_SYMBOL_GPL(cpufreq_cpu_get);
242 
243 /**
244  * cpufreq_cpu_put - Decrement kobject usage counter for cpufreq policy.
245  * @policy: cpufreq policy returned by cpufreq_cpu_get().
246  */
cpufreq_cpu_put(struct cpufreq_policy * policy)247 void cpufreq_cpu_put(struct cpufreq_policy *policy)
248 {
249 	kobject_put(&policy->kobj);
250 }
251 EXPORT_SYMBOL_GPL(cpufreq_cpu_put);
252 
253 /**
254  * cpufreq_cpu_release - Unlock a policy and decrement its usage counter.
255  * @policy: cpufreq policy returned by cpufreq_cpu_acquire().
256  */
cpufreq_cpu_release(struct cpufreq_policy * policy)257 void cpufreq_cpu_release(struct cpufreq_policy *policy)
258 {
259 	if (WARN_ON(!policy))
260 		return;
261 
262 	lockdep_assert_held(&policy->rwsem);
263 
264 	up_write(&policy->rwsem);
265 
266 	cpufreq_cpu_put(policy);
267 }
268 
269 /**
270  * cpufreq_cpu_acquire - Find policy for a CPU, mark it as busy and lock it.
271  * @cpu: CPU to find the policy for.
272  *
273  * Call cpufreq_cpu_get() to get a reference on the cpufreq policy for @cpu and
274  * if the policy returned by it is not NULL, acquire its rwsem for writing.
275  * Return the policy if it is active or release it and return NULL otherwise.
276  *
277  * The policy returned by this function has to be released with the help of
278  * cpufreq_cpu_release() in order to release its rwsem and balance its usage
279  * counter properly.
280  */
cpufreq_cpu_acquire(unsigned int cpu)281 struct cpufreq_policy *cpufreq_cpu_acquire(unsigned int cpu)
282 {
283 	struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
284 
285 	if (!policy)
286 		return NULL;
287 
288 	down_write(&policy->rwsem);
289 
290 	if (policy_is_inactive(policy)) {
291 		cpufreq_cpu_release(policy);
292 		return NULL;
293 	}
294 
295 	return policy;
296 }
297 
298 /*********************************************************************
299  *            EXTERNALLY AFFECTING FREQUENCY CHANGES                 *
300  *********************************************************************/
301 
302 /**
303  * adjust_jiffies - Adjust the system "loops_per_jiffy".
304  * @val: CPUFREQ_PRECHANGE or CPUFREQ_POSTCHANGE.
305  * @ci: Frequency change information.
306  *
307  * This function alters the system "loops_per_jiffy" for the clock
308  * speed change. Note that loops_per_jiffy cannot be updated on SMP
309  * systems as each CPU might be scaled differently. So, use the arch
310  * per-CPU loops_per_jiffy value wherever possible.
311  */
adjust_jiffies(unsigned long val,struct cpufreq_freqs * ci)312 static void adjust_jiffies(unsigned long val, struct cpufreq_freqs *ci)
313 {
314 #ifndef CONFIG_SMP
315 	static unsigned long l_p_j_ref;
316 	static unsigned int l_p_j_ref_freq;
317 
318 	if (ci->flags & CPUFREQ_CONST_LOOPS)
319 		return;
320 
321 	if (!l_p_j_ref_freq) {
322 		l_p_j_ref = loops_per_jiffy;
323 		l_p_j_ref_freq = ci->old;
324 		pr_debug("saving %lu as reference value for loops_per_jiffy; freq is %u kHz\n",
325 			 l_p_j_ref, l_p_j_ref_freq);
326 	}
327 	if (val == CPUFREQ_POSTCHANGE && ci->old != ci->new) {
328 		loops_per_jiffy = cpufreq_scale(l_p_j_ref, l_p_j_ref_freq,
329 								ci->new);
330 		pr_debug("scaling loops_per_jiffy to %lu for frequency %u kHz\n",
331 			 loops_per_jiffy, ci->new);
332 	}
333 #endif
334 }
335 
336 /**
337  * cpufreq_notify_transition - Notify frequency transition and adjust jiffies.
338  * @policy: cpufreq policy to enable fast frequency switching for.
339  * @freqs: contain details of the frequency update.
340  * @state: set to CPUFREQ_PRECHANGE or CPUFREQ_POSTCHANGE.
341  *
342  * This function calls the transition notifiers and adjust_jiffies().
343  *
344  * It is called twice on all CPU frequency changes that have external effects.
345  */
cpufreq_notify_transition(struct cpufreq_policy * policy,struct cpufreq_freqs * freqs,unsigned int state)346 static void cpufreq_notify_transition(struct cpufreq_policy *policy,
347 				      struct cpufreq_freqs *freqs,
348 				      unsigned int state)
349 {
350 	int cpu;
351 
352 	BUG_ON(irqs_disabled());
353 
354 	if (cpufreq_disabled())
355 		return;
356 
357 	freqs->policy = policy;
358 	freqs->flags = cpufreq_driver->flags;
359 	pr_debug("notification %u of frequency transition to %u kHz\n",
360 		 state, freqs->new);
361 
362 	switch (state) {
363 	case CPUFREQ_PRECHANGE:
364 		/*
365 		 * Detect if the driver reported a value as "old frequency"
366 		 * which is not equal to what the cpufreq core thinks is
367 		 * "old frequency".
368 		 */
369 		if (policy->cur && policy->cur != freqs->old) {
370 			pr_debug("Warning: CPU frequency is %u, cpufreq assumed %u kHz\n",
371 				 freqs->old, policy->cur);
372 			freqs->old = policy->cur;
373 		}
374 
375 		srcu_notifier_call_chain(&cpufreq_transition_notifier_list,
376 					 CPUFREQ_PRECHANGE, freqs);
377 
378 		adjust_jiffies(CPUFREQ_PRECHANGE, freqs);
379 		break;
380 
381 	case CPUFREQ_POSTCHANGE:
382 		adjust_jiffies(CPUFREQ_POSTCHANGE, freqs);
383 		pr_debug("FREQ: %u - CPUs: %*pbl\n", freqs->new,
384 			 cpumask_pr_args(policy->cpus));
385 
386 		for_each_cpu(cpu, policy->cpus)
387 			trace_cpu_frequency(freqs->new, cpu);
388 
389 		srcu_notifier_call_chain(&cpufreq_transition_notifier_list,
390 					 CPUFREQ_POSTCHANGE, freqs);
391 
392 		cpufreq_stats_record_transition(policy, freqs->new);
393 		cpufreq_times_record_transition(policy, freqs->new);
394 		policy->cur = freqs->new;
395 		trace_android_rvh_cpufreq_transition(policy);
396 	}
397 }
398 
399 /* Do post notifications when there are chances that transition has failed */
cpufreq_notify_post_transition(struct cpufreq_policy * policy,struct cpufreq_freqs * freqs,int transition_failed)400 static void cpufreq_notify_post_transition(struct cpufreq_policy *policy,
401 		struct cpufreq_freqs *freqs, int transition_failed)
402 {
403 	cpufreq_notify_transition(policy, freqs, CPUFREQ_POSTCHANGE);
404 	if (!transition_failed)
405 		return;
406 
407 	swap(freqs->old, freqs->new);
408 	cpufreq_notify_transition(policy, freqs, CPUFREQ_PRECHANGE);
409 	cpufreq_notify_transition(policy, freqs, CPUFREQ_POSTCHANGE);
410 }
411 
cpufreq_freq_transition_begin(struct cpufreq_policy * policy,struct cpufreq_freqs * freqs)412 void cpufreq_freq_transition_begin(struct cpufreq_policy *policy,
413 		struct cpufreq_freqs *freqs)
414 {
415 
416 	/*
417 	 * Catch double invocations of _begin() which lead to self-deadlock.
418 	 * ASYNC_NOTIFICATION drivers are left out because the cpufreq core
419 	 * doesn't invoke _begin() on their behalf, and hence the chances of
420 	 * double invocations are very low. Moreover, there are scenarios
421 	 * where these checks can emit false-positive warnings in these
422 	 * drivers; so we avoid that by skipping them altogether.
423 	 */
424 	WARN_ON(!(cpufreq_driver->flags & CPUFREQ_ASYNC_NOTIFICATION)
425 				&& current == policy->transition_task);
426 
427 wait:
428 	wait_event(policy->transition_wait, !policy->transition_ongoing);
429 
430 	spin_lock(&policy->transition_lock);
431 
432 	if (unlikely(policy->transition_ongoing)) {
433 		spin_unlock(&policy->transition_lock);
434 		goto wait;
435 	}
436 
437 	policy->transition_ongoing = true;
438 	policy->transition_task = current;
439 
440 	spin_unlock(&policy->transition_lock);
441 
442 	cpufreq_notify_transition(policy, freqs, CPUFREQ_PRECHANGE);
443 }
444 EXPORT_SYMBOL_GPL(cpufreq_freq_transition_begin);
445 
cpufreq_freq_transition_end(struct cpufreq_policy * policy,struct cpufreq_freqs * freqs,int transition_failed)446 void cpufreq_freq_transition_end(struct cpufreq_policy *policy,
447 		struct cpufreq_freqs *freqs, int transition_failed)
448 {
449 	if (WARN_ON(!policy->transition_ongoing))
450 		return;
451 
452 	cpufreq_notify_post_transition(policy, freqs, transition_failed);
453 
454 	arch_set_freq_scale(policy->related_cpus,
455 			    policy->cur,
456 			    policy->cpuinfo.max_freq);
457 
458 	spin_lock(&policy->transition_lock);
459 	policy->transition_ongoing = false;
460 	policy->transition_task = NULL;
461 	spin_unlock(&policy->transition_lock);
462 
463 	wake_up(&policy->transition_wait);
464 }
465 EXPORT_SYMBOL_GPL(cpufreq_freq_transition_end);
466 
467 /*
468  * Fast frequency switching status count.  Positive means "enabled", negative
469  * means "disabled" and 0 means "not decided yet".
470  */
471 static int cpufreq_fast_switch_count;
472 static DEFINE_MUTEX(cpufreq_fast_switch_lock);
473 
cpufreq_list_transition_notifiers(void)474 static void cpufreq_list_transition_notifiers(void)
475 {
476 	struct notifier_block *nb;
477 
478 	pr_info("Registered transition notifiers:\n");
479 
480 	mutex_lock(&cpufreq_transition_notifier_list.mutex);
481 
482 	for (nb = cpufreq_transition_notifier_list.head; nb; nb = nb->next)
483 		pr_info("%pS\n", nb->notifier_call);
484 
485 	mutex_unlock(&cpufreq_transition_notifier_list.mutex);
486 }
487 
488 /**
489  * cpufreq_enable_fast_switch - Enable fast frequency switching for policy.
490  * @policy: cpufreq policy to enable fast frequency switching for.
491  *
492  * Try to enable fast frequency switching for @policy.
493  *
494  * The attempt will fail if there is at least one transition notifier registered
495  * at this point, as fast frequency switching is quite fundamentally at odds
496  * with transition notifiers.  Thus if successful, it will make registration of
497  * transition notifiers fail going forward.
498  */
cpufreq_enable_fast_switch(struct cpufreq_policy * policy)499 void cpufreq_enable_fast_switch(struct cpufreq_policy *policy)
500 {
501 	lockdep_assert_held(&policy->rwsem);
502 
503 	if (!policy->fast_switch_possible)
504 		return;
505 
506 	mutex_lock(&cpufreq_fast_switch_lock);
507 	if (cpufreq_fast_switch_count >= 0) {
508 		cpufreq_fast_switch_count++;
509 		policy->fast_switch_enabled = true;
510 	} else {
511 		pr_warn("CPU%u: Fast frequency switching not enabled\n",
512 			policy->cpu);
513 		cpufreq_list_transition_notifiers();
514 	}
515 	mutex_unlock(&cpufreq_fast_switch_lock);
516 }
517 EXPORT_SYMBOL_GPL(cpufreq_enable_fast_switch);
518 
519 /**
520  * cpufreq_disable_fast_switch - Disable fast frequency switching for policy.
521  * @policy: cpufreq policy to disable fast frequency switching for.
522  */
cpufreq_disable_fast_switch(struct cpufreq_policy * policy)523 void cpufreq_disable_fast_switch(struct cpufreq_policy *policy)
524 {
525 	mutex_lock(&cpufreq_fast_switch_lock);
526 	if (policy->fast_switch_enabled) {
527 		policy->fast_switch_enabled = false;
528 		if (!WARN_ON(cpufreq_fast_switch_count <= 0))
529 			cpufreq_fast_switch_count--;
530 	}
531 	mutex_unlock(&cpufreq_fast_switch_lock);
532 }
533 EXPORT_SYMBOL_GPL(cpufreq_disable_fast_switch);
534 
__resolve_freq(struct cpufreq_policy * policy,unsigned int target_freq,unsigned int relation)535 static unsigned int __resolve_freq(struct cpufreq_policy *policy,
536 		unsigned int target_freq, unsigned int relation)
537 {
538 	unsigned int idx;
539 	unsigned int old_target_freq = target_freq;
540 
541 	target_freq = clamp_val(target_freq, policy->min, policy->max);
542 	trace_android_vh_cpufreq_resolve_freq(policy, &target_freq, old_target_freq);
543 
544 	if (!policy->freq_table)
545 		return target_freq;
546 
547 	idx = cpufreq_frequency_table_target(policy, target_freq, relation);
548 	policy->cached_resolved_idx = idx;
549 	policy->cached_target_freq = target_freq;
550 	return policy->freq_table[idx].frequency;
551 }
552 
553 /**
554  * cpufreq_driver_resolve_freq - Map a target frequency to a driver-supported
555  * one.
556  * @policy: associated policy to interrogate
557  * @target_freq: target frequency to resolve.
558  *
559  * The target to driver frequency mapping is cached in the policy.
560  *
561  * Return: Lowest driver-supported frequency greater than or equal to the
562  * given target_freq, subject to policy (min/max) and driver limitations.
563  */
cpufreq_driver_resolve_freq(struct cpufreq_policy * policy,unsigned int target_freq)564 unsigned int cpufreq_driver_resolve_freq(struct cpufreq_policy *policy,
565 					 unsigned int target_freq)
566 {
567 	return __resolve_freq(policy, target_freq, CPUFREQ_RELATION_LE);
568 }
569 EXPORT_SYMBOL_GPL(cpufreq_driver_resolve_freq);
570 
cpufreq_policy_transition_delay_us(struct cpufreq_policy * policy)571 unsigned int cpufreq_policy_transition_delay_us(struct cpufreq_policy *policy)
572 {
573 	unsigned int latency;
574 
575 	if (policy->transition_delay_us)
576 		return policy->transition_delay_us;
577 
578 	latency = policy->cpuinfo.transition_latency / NSEC_PER_USEC;
579 	if (latency) {
580 		/*
581 		 * For platforms that can change the frequency very fast (< 10
582 		 * us), the above formula gives a decent transition delay. But
583 		 * for platforms where transition_latency is in milliseconds, it
584 		 * ends up giving unrealistic values.
585 		 *
586 		 * Cap the default transition delay to 10 ms, which seems to be
587 		 * a reasonable amount of time after which we should reevaluate
588 		 * the frequency.
589 		 */
590 		return min(latency * LATENCY_MULTIPLIER, (unsigned int)10000);
591 	}
592 
593 	return LATENCY_MULTIPLIER;
594 }
595 EXPORT_SYMBOL_GPL(cpufreq_policy_transition_delay_us);
596 
597 /*********************************************************************
598  *                          SYSFS INTERFACE                          *
599  *********************************************************************/
show_boost(struct kobject * kobj,struct kobj_attribute * attr,char * buf)600 static ssize_t show_boost(struct kobject *kobj,
601 			  struct kobj_attribute *attr, char *buf)
602 {
603 	return sprintf(buf, "%d\n", cpufreq_driver->boost_enabled);
604 }
605 
store_boost(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)606 static ssize_t store_boost(struct kobject *kobj, struct kobj_attribute *attr,
607 			   const char *buf, size_t count)
608 {
609 	int ret, enable;
610 
611 	ret = sscanf(buf, "%d", &enable);
612 	if (ret != 1 || enable < 0 || enable > 1)
613 		return -EINVAL;
614 
615 	if (cpufreq_boost_trigger_state(enable)) {
616 		pr_err("%s: Cannot %s BOOST!\n",
617 		       __func__, enable ? "enable" : "disable");
618 		return -EINVAL;
619 	}
620 
621 	pr_debug("%s: cpufreq BOOST %s\n",
622 		 __func__, enable ? "enabled" : "disabled");
623 
624 	return count;
625 }
626 define_one_global_rw(boost);
627 
find_governor(const char * str_governor)628 static struct cpufreq_governor *find_governor(const char *str_governor)
629 {
630 	struct cpufreq_governor *t;
631 
632 	for_each_governor(t)
633 		if (!strncasecmp(str_governor, t->name, CPUFREQ_NAME_LEN))
634 			return t;
635 
636 	return NULL;
637 }
638 
get_governor(const char * str_governor)639 static struct cpufreq_governor *get_governor(const char *str_governor)
640 {
641 	struct cpufreq_governor *t;
642 
643 	mutex_lock(&cpufreq_governor_mutex);
644 	t = find_governor(str_governor);
645 	if (!t)
646 		goto unlock;
647 
648 	if (!try_module_get(t->owner))
649 		t = NULL;
650 
651 unlock:
652 	mutex_unlock(&cpufreq_governor_mutex);
653 
654 	return t;
655 }
656 
cpufreq_parse_policy(char * str_governor)657 static unsigned int cpufreq_parse_policy(char *str_governor)
658 {
659 	if (!strncasecmp(str_governor, "performance", CPUFREQ_NAME_LEN))
660 		return CPUFREQ_POLICY_PERFORMANCE;
661 
662 	if (!strncasecmp(str_governor, "powersave", CPUFREQ_NAME_LEN))
663 		return CPUFREQ_POLICY_POWERSAVE;
664 
665 	return CPUFREQ_POLICY_UNKNOWN;
666 }
667 
668 /**
669  * cpufreq_parse_governor - parse a governor string only for has_target()
670  * @str_governor: Governor name.
671  */
cpufreq_parse_governor(char * str_governor)672 static struct cpufreq_governor *cpufreq_parse_governor(char *str_governor)
673 {
674 	struct cpufreq_governor *t;
675 
676 	t = get_governor(str_governor);
677 	if (t)
678 		return t;
679 
680 	if (request_module("cpufreq_%s", str_governor))
681 		return NULL;
682 
683 	return get_governor(str_governor);
684 }
685 
686 /*
687  * cpufreq_per_cpu_attr_read() / show_##file_name() -
688  * print out cpufreq information
689  *
690  * Write out information from cpufreq_driver->policy[cpu]; object must be
691  * "unsigned int".
692  */
693 
694 #define show_one(file_name, object)			\
695 static ssize_t show_##file_name				\
696 (struct cpufreq_policy *policy, char *buf)		\
697 {							\
698 	return sprintf(buf, "%u\n", policy->object);	\
699 }
700 
show_cpuinfo_max_freq(struct cpufreq_policy * policy,char * buf)701 static ssize_t show_cpuinfo_max_freq(struct cpufreq_policy *policy, char *buf)
702 {
703 	unsigned int max_freq = policy->cpuinfo.max_freq;
704 
705 	trace_android_rvh_show_max_freq(policy, &max_freq);
706 	return sprintf(buf, "%u\n", max_freq);
707 }
708 
709 show_one(cpuinfo_min_freq, cpuinfo.min_freq);
710 show_one(cpuinfo_transition_latency, cpuinfo.transition_latency);
711 show_one(scaling_min_freq, min);
712 show_one(scaling_max_freq, max);
713 
arch_freq_get_on_cpu(int cpu)714 __weak unsigned int arch_freq_get_on_cpu(int cpu)
715 {
716 	return 0;
717 }
718 
show_scaling_cur_freq(struct cpufreq_policy * policy,char * buf)719 static ssize_t show_scaling_cur_freq(struct cpufreq_policy *policy, char *buf)
720 {
721 	ssize_t ret;
722 	unsigned int freq;
723 
724 	freq = arch_freq_get_on_cpu(policy->cpu);
725 	if (freq)
726 		ret = sprintf(buf, "%u\n", freq);
727 	else if (cpufreq_driver->setpolicy && cpufreq_driver->get)
728 		ret = sprintf(buf, "%u\n", cpufreq_driver->get(policy->cpu));
729 	else
730 		ret = sprintf(buf, "%u\n", policy->cur);
731 	return ret;
732 }
733 
734 /*
735  * cpufreq_per_cpu_attr_write() / store_##file_name() - sysfs write access
736  */
737 #define store_one(file_name, object)			\
738 static ssize_t store_##file_name					\
739 (struct cpufreq_policy *policy, const char *buf, size_t count)		\
740 {									\
741 	unsigned long val;						\
742 	int ret;							\
743 									\
744 	ret = sscanf(buf, "%lu", &val);					\
745 	if (ret != 1)							\
746 		return -EINVAL;						\
747 									\
748 	ret = freq_qos_update_request(policy->object##_freq_req, val);\
749 	return ret >= 0 ? count : ret;					\
750 }
751 
752 store_one(scaling_min_freq, min);
753 store_one(scaling_max_freq, max);
754 
755 /*
756  * show_cpuinfo_cur_freq - current CPU frequency as detected by hardware
757  */
show_cpuinfo_cur_freq(struct cpufreq_policy * policy,char * buf)758 static ssize_t show_cpuinfo_cur_freq(struct cpufreq_policy *policy,
759 					char *buf)
760 {
761 	unsigned int cur_freq = __cpufreq_get(policy);
762 
763 	if (cur_freq)
764 		return sprintf(buf, "%u\n", cur_freq);
765 
766 	return sprintf(buf, "<unknown>\n");
767 }
768 
769 /*
770  * show_scaling_governor - show the current policy for the specified CPU
771  */
show_scaling_governor(struct cpufreq_policy * policy,char * buf)772 static ssize_t show_scaling_governor(struct cpufreq_policy *policy, char *buf)
773 {
774 	if (policy->policy == CPUFREQ_POLICY_POWERSAVE)
775 		return sprintf(buf, "powersave\n");
776 	else if (policy->policy == CPUFREQ_POLICY_PERFORMANCE)
777 		return sprintf(buf, "performance\n");
778 	else if (policy->governor)
779 		return scnprintf(buf, CPUFREQ_NAME_PLEN, "%s\n",
780 				policy->governor->name);
781 	return -EINVAL;
782 }
783 
784 /*
785  * store_scaling_governor - store policy for the specified CPU
786  */
store_scaling_governor(struct cpufreq_policy * policy,const char * buf,size_t count)787 static ssize_t store_scaling_governor(struct cpufreq_policy *policy,
788 					const char *buf, size_t count)
789 {
790 	char str_governor[16];
791 	int ret;
792 
793 	ret = sscanf(buf, "%15s", str_governor);
794 	if (ret != 1)
795 		return -EINVAL;
796 
797 	if (cpufreq_driver->setpolicy) {
798 		unsigned int new_pol;
799 
800 		new_pol = cpufreq_parse_policy(str_governor);
801 		if (!new_pol)
802 			return -EINVAL;
803 
804 		ret = cpufreq_set_policy(policy, NULL, new_pol);
805 	} else {
806 		struct cpufreq_governor *new_gov;
807 
808 		new_gov = cpufreq_parse_governor(str_governor);
809 		if (!new_gov)
810 			return -EINVAL;
811 
812 		ret = cpufreq_set_policy(policy, new_gov,
813 					 CPUFREQ_POLICY_UNKNOWN);
814 
815 		module_put(new_gov->owner);
816 	}
817 
818 	return ret ? ret : count;
819 }
820 
821 /*
822  * show_scaling_driver - show the cpufreq driver currently loaded
823  */
show_scaling_driver(struct cpufreq_policy * policy,char * buf)824 static ssize_t show_scaling_driver(struct cpufreq_policy *policy, char *buf)
825 {
826 	return scnprintf(buf, CPUFREQ_NAME_PLEN, "%s\n", cpufreq_driver->name);
827 }
828 
829 /*
830  * show_scaling_available_governors - show the available CPUfreq governors
831  */
show_scaling_available_governors(struct cpufreq_policy * policy,char * buf)832 static ssize_t show_scaling_available_governors(struct cpufreq_policy *policy,
833 						char *buf)
834 {
835 	ssize_t i = 0;
836 	struct cpufreq_governor *t;
837 
838 	if (!has_target()) {
839 		i += sprintf(buf, "performance powersave");
840 		goto out;
841 	}
842 
843 	mutex_lock(&cpufreq_governor_mutex);
844 	for_each_governor(t) {
845 		if (i >= (ssize_t) ((PAGE_SIZE / sizeof(char))
846 		    - (CPUFREQ_NAME_LEN + 2)))
847 			break;
848 		i += scnprintf(&buf[i], CPUFREQ_NAME_PLEN, "%s ", t->name);
849 	}
850 	mutex_unlock(&cpufreq_governor_mutex);
851 out:
852 	i += sprintf(&buf[i], "\n");
853 	return i;
854 }
855 
cpufreq_show_cpus(const struct cpumask * mask,char * buf)856 ssize_t cpufreq_show_cpus(const struct cpumask *mask, char *buf)
857 {
858 	ssize_t i = 0;
859 	unsigned int cpu;
860 
861 	for_each_cpu(cpu, mask) {
862 		i += scnprintf(&buf[i], (PAGE_SIZE - i - 2), "%u ", cpu);
863 		if (i >= (PAGE_SIZE - 5))
864 			break;
865 	}
866 
867 	/* Remove the extra space at the end */
868 	i--;
869 
870 	i += sprintf(&buf[i], "\n");
871 	return i;
872 }
873 EXPORT_SYMBOL_GPL(cpufreq_show_cpus);
874 
875 /*
876  * show_related_cpus - show the CPUs affected by each transition even if
877  * hw coordination is in use
878  */
show_related_cpus(struct cpufreq_policy * policy,char * buf)879 static ssize_t show_related_cpus(struct cpufreq_policy *policy, char *buf)
880 {
881 	return cpufreq_show_cpus(policy->related_cpus, buf);
882 }
883 
884 /*
885  * show_affected_cpus - show the CPUs affected by each transition
886  */
show_affected_cpus(struct cpufreq_policy * policy,char * buf)887 static ssize_t show_affected_cpus(struct cpufreq_policy *policy, char *buf)
888 {
889 	return cpufreq_show_cpus(policy->cpus, buf);
890 }
891 
store_scaling_setspeed(struct cpufreq_policy * policy,const char * buf,size_t count)892 static ssize_t store_scaling_setspeed(struct cpufreq_policy *policy,
893 					const char *buf, size_t count)
894 {
895 	unsigned int freq = 0;
896 	unsigned int ret;
897 
898 	if (!policy->governor || !policy->governor->store_setspeed)
899 		return -EINVAL;
900 
901 	ret = sscanf(buf, "%u", &freq);
902 	if (ret != 1)
903 		return -EINVAL;
904 
905 	policy->governor->store_setspeed(policy, freq);
906 
907 	return count;
908 }
909 
show_scaling_setspeed(struct cpufreq_policy * policy,char * buf)910 static ssize_t show_scaling_setspeed(struct cpufreq_policy *policy, char *buf)
911 {
912 	if (!policy->governor || !policy->governor->show_setspeed)
913 		return sprintf(buf, "<unsupported>\n");
914 
915 	return policy->governor->show_setspeed(policy, buf);
916 }
917 
918 /*
919  * show_bios_limit - show the current cpufreq HW/BIOS limitation
920  */
show_bios_limit(struct cpufreq_policy * policy,char * buf)921 static ssize_t show_bios_limit(struct cpufreq_policy *policy, char *buf)
922 {
923 	unsigned int limit;
924 	int ret;
925 	ret = cpufreq_driver->bios_limit(policy->cpu, &limit);
926 	if (!ret)
927 		return sprintf(buf, "%u\n", limit);
928 	return sprintf(buf, "%u\n", policy->cpuinfo.max_freq);
929 }
930 
931 cpufreq_freq_attr_ro_perm(cpuinfo_cur_freq, 0400);
932 cpufreq_freq_attr_ro(cpuinfo_min_freq);
933 cpufreq_freq_attr_ro(cpuinfo_max_freq);
934 cpufreq_freq_attr_ro(cpuinfo_transition_latency);
935 cpufreq_freq_attr_ro(scaling_available_governors);
936 cpufreq_freq_attr_ro(scaling_driver);
937 cpufreq_freq_attr_ro(scaling_cur_freq);
938 cpufreq_freq_attr_ro(bios_limit);
939 cpufreq_freq_attr_ro(related_cpus);
940 cpufreq_freq_attr_ro(affected_cpus);
941 cpufreq_freq_attr_rw(scaling_min_freq);
942 cpufreq_freq_attr_rw(scaling_max_freq);
943 cpufreq_freq_attr_rw(scaling_governor);
944 cpufreq_freq_attr_rw(scaling_setspeed);
945 
946 static struct attribute *cpufreq_attrs[] = {
947 	&cpuinfo_min_freq.attr,
948 	&cpuinfo_max_freq.attr,
949 	&cpuinfo_transition_latency.attr,
950 	&scaling_min_freq.attr,
951 	&scaling_max_freq.attr,
952 	&affected_cpus.attr,
953 	&related_cpus.attr,
954 	&scaling_governor.attr,
955 	&scaling_driver.attr,
956 	&scaling_available_governors.attr,
957 	&scaling_setspeed.attr,
958 	NULL
959 };
960 ATTRIBUTE_GROUPS(cpufreq);
961 
962 #define to_policy(k) container_of(k, struct cpufreq_policy, kobj)
963 #define to_attr(a) container_of(a, struct freq_attr, attr)
964 
show(struct kobject * kobj,struct attribute * attr,char * buf)965 static ssize_t show(struct kobject *kobj, struct attribute *attr, char *buf)
966 {
967 	struct cpufreq_policy *policy = to_policy(kobj);
968 	struct freq_attr *fattr = to_attr(attr);
969 	ssize_t ret = -EBUSY;
970 
971 	if (!fattr->show)
972 		return -EIO;
973 
974 	down_read(&policy->rwsem);
975 	if (likely(!policy_is_inactive(policy)))
976 		ret = fattr->show(policy, buf);
977 	up_read(&policy->rwsem);
978 
979 	return ret;
980 }
981 
store(struct kobject * kobj,struct attribute * attr,const char * buf,size_t count)982 static ssize_t store(struct kobject *kobj, struct attribute *attr,
983 		     const char *buf, size_t count)
984 {
985 	struct cpufreq_policy *policy = to_policy(kobj);
986 	struct freq_attr *fattr = to_attr(attr);
987 	ssize_t ret = -EBUSY;
988 
989 	if (!fattr->store)
990 		return -EIO;
991 
992 	down_write(&policy->rwsem);
993 	if (likely(!policy_is_inactive(policy)))
994 		ret = fattr->store(policy, buf, count);
995 	up_write(&policy->rwsem);
996 
997 	return ret;
998 }
999 
cpufreq_sysfs_release(struct kobject * kobj)1000 static void cpufreq_sysfs_release(struct kobject *kobj)
1001 {
1002 	struct cpufreq_policy *policy = to_policy(kobj);
1003 	pr_debug("last reference is dropped\n");
1004 	complete(&policy->kobj_unregister);
1005 }
1006 
1007 static const struct sysfs_ops sysfs_ops = {
1008 	.show	= show,
1009 	.store	= store,
1010 };
1011 
1012 static struct kobj_type ktype_cpufreq = {
1013 	.sysfs_ops	= &sysfs_ops,
1014 	.default_groups	= cpufreq_groups,
1015 	.release	= cpufreq_sysfs_release,
1016 };
1017 
add_cpu_dev_symlink(struct cpufreq_policy * policy,unsigned int cpu,struct device * dev)1018 static void add_cpu_dev_symlink(struct cpufreq_policy *policy, unsigned int cpu,
1019 				struct device *dev)
1020 {
1021 	if (unlikely(!dev))
1022 		return;
1023 
1024 	if (cpumask_test_and_set_cpu(cpu, policy->real_cpus))
1025 		return;
1026 
1027 	dev_dbg(dev, "%s: Adding symlink\n", __func__);
1028 	if (sysfs_create_link(&dev->kobj, &policy->kobj, "cpufreq"))
1029 		dev_err(dev, "cpufreq symlink creation failed\n");
1030 }
1031 
remove_cpu_dev_symlink(struct cpufreq_policy * policy,int cpu,struct device * dev)1032 static void remove_cpu_dev_symlink(struct cpufreq_policy *policy, int cpu,
1033 				   struct device *dev)
1034 {
1035 	dev_dbg(dev, "%s: Removing symlink\n", __func__);
1036 	sysfs_remove_link(&dev->kobj, "cpufreq");
1037 	cpumask_clear_cpu(cpu, policy->real_cpus);
1038 }
1039 
cpufreq_add_dev_interface(struct cpufreq_policy * policy)1040 static int cpufreq_add_dev_interface(struct cpufreq_policy *policy)
1041 {
1042 	struct freq_attr **drv_attr;
1043 	int ret = 0;
1044 
1045 	/* set up files for this cpu device */
1046 	drv_attr = cpufreq_driver->attr;
1047 	while (drv_attr && *drv_attr) {
1048 		ret = sysfs_create_file(&policy->kobj, &((*drv_attr)->attr));
1049 		if (ret)
1050 			return ret;
1051 		drv_attr++;
1052 	}
1053 	if (cpufreq_driver->get) {
1054 		ret = sysfs_create_file(&policy->kobj, &cpuinfo_cur_freq.attr);
1055 		if (ret)
1056 			return ret;
1057 	}
1058 
1059 	ret = sysfs_create_file(&policy->kobj, &scaling_cur_freq.attr);
1060 	if (ret)
1061 		return ret;
1062 
1063 	if (cpufreq_driver->bios_limit) {
1064 		ret = sysfs_create_file(&policy->kobj, &bios_limit.attr);
1065 		if (ret)
1066 			return ret;
1067 	}
1068 
1069 	return 0;
1070 }
1071 
cpufreq_init_policy(struct cpufreq_policy * policy)1072 static int cpufreq_init_policy(struct cpufreq_policy *policy)
1073 {
1074 	struct cpufreq_governor *gov = NULL;
1075 	unsigned int pol = CPUFREQ_POLICY_UNKNOWN;
1076 	int ret;
1077 
1078 	if (has_target()) {
1079 		/* Update policy governor to the one used before hotplug. */
1080 		gov = get_governor(policy->last_governor);
1081 		if (gov) {
1082 			pr_debug("Restoring governor %s for cpu %d\n",
1083 				 gov->name, policy->cpu);
1084 		} else {
1085 			gov = get_governor(default_governor);
1086 		}
1087 
1088 		if (!gov) {
1089 			gov = cpufreq_default_governor();
1090 			__module_get(gov->owner);
1091 		}
1092 
1093 	} else {
1094 
1095 		/* Use the default policy if there is no last_policy. */
1096 		if (policy->last_policy) {
1097 			pol = policy->last_policy;
1098 		} else {
1099 			pol = cpufreq_parse_policy(default_governor);
1100 			/*
1101 			 * In case the default governor is neither "performance"
1102 			 * nor "powersave", fall back to the initial policy
1103 			 * value set by the driver.
1104 			 */
1105 			if (pol == CPUFREQ_POLICY_UNKNOWN)
1106 				pol = policy->policy;
1107 		}
1108 		if (pol != CPUFREQ_POLICY_PERFORMANCE &&
1109 		    pol != CPUFREQ_POLICY_POWERSAVE)
1110 			return -ENODATA;
1111 	}
1112 
1113 	ret = cpufreq_set_policy(policy, gov, pol);
1114 	if (gov)
1115 		module_put(gov->owner);
1116 
1117 	return ret;
1118 }
1119 
cpufreq_add_policy_cpu(struct cpufreq_policy * policy,unsigned int cpu)1120 static int cpufreq_add_policy_cpu(struct cpufreq_policy *policy, unsigned int cpu)
1121 {
1122 	int ret = 0;
1123 
1124 	/* Has this CPU been taken care of already? */
1125 	if (cpumask_test_cpu(cpu, policy->cpus))
1126 		return 0;
1127 
1128 	down_write(&policy->rwsem);
1129 	if (has_target())
1130 		cpufreq_stop_governor(policy);
1131 
1132 	cpumask_set_cpu(cpu, policy->cpus);
1133 
1134 	if (has_target()) {
1135 		ret = cpufreq_start_governor(policy);
1136 		if (ret)
1137 			pr_err("%s: Failed to start governor\n", __func__);
1138 	}
1139 	up_write(&policy->rwsem);
1140 	return ret;
1141 }
1142 
refresh_frequency_limits(struct cpufreq_policy * policy)1143 void refresh_frequency_limits(struct cpufreq_policy *policy)
1144 {
1145 	if (!policy_is_inactive(policy)) {
1146 		pr_debug("updating policy for CPU %u\n", policy->cpu);
1147 
1148 		cpufreq_set_policy(policy, policy->governor, policy->policy);
1149 	}
1150 }
1151 EXPORT_SYMBOL(refresh_frequency_limits);
1152 
handle_update(struct work_struct * work)1153 static void handle_update(struct work_struct *work)
1154 {
1155 	struct cpufreq_policy *policy =
1156 		container_of(work, struct cpufreq_policy, update);
1157 
1158 	pr_debug("handle_update for cpu %u called\n", policy->cpu);
1159 	down_write(&policy->rwsem);
1160 	refresh_frequency_limits(policy);
1161 	up_write(&policy->rwsem);
1162 }
1163 
cpufreq_notifier_min(struct notifier_block * nb,unsigned long freq,void * data)1164 static int cpufreq_notifier_min(struct notifier_block *nb, unsigned long freq,
1165 				void *data)
1166 {
1167 	struct cpufreq_policy *policy = container_of(nb, struct cpufreq_policy, nb_min);
1168 
1169 	schedule_work(&policy->update);
1170 	return 0;
1171 }
1172 
cpufreq_notifier_max(struct notifier_block * nb,unsigned long freq,void * data)1173 static int cpufreq_notifier_max(struct notifier_block *nb, unsigned long freq,
1174 				void *data)
1175 {
1176 	struct cpufreq_policy *policy = container_of(nb, struct cpufreq_policy, nb_max);
1177 
1178 	schedule_work(&policy->update);
1179 	return 0;
1180 }
1181 
cpufreq_policy_put_kobj(struct cpufreq_policy * policy)1182 static void cpufreq_policy_put_kobj(struct cpufreq_policy *policy)
1183 {
1184 	struct kobject *kobj;
1185 	struct completion *cmp;
1186 
1187 	down_write(&policy->rwsem);
1188 	cpufreq_stats_free_table(policy);
1189 	kobj = &policy->kobj;
1190 	cmp = &policy->kobj_unregister;
1191 	up_write(&policy->rwsem);
1192 	kobject_put(kobj);
1193 
1194 	/*
1195 	 * We need to make sure that the underlying kobj is
1196 	 * actually not referenced anymore by anybody before we
1197 	 * proceed with unloading.
1198 	 */
1199 	pr_debug("waiting for dropping of refcount\n");
1200 	wait_for_completion(cmp);
1201 	pr_debug("wait complete\n");
1202 }
1203 
cpufreq_policy_alloc(unsigned int cpu)1204 static struct cpufreq_policy *cpufreq_policy_alloc(unsigned int cpu)
1205 {
1206 	struct cpufreq_policy *policy;
1207 	struct device *dev = get_cpu_device(cpu);
1208 	int ret;
1209 
1210 	if (!dev)
1211 		return NULL;
1212 
1213 	policy = kzalloc(sizeof(*policy), GFP_KERNEL);
1214 	if (!policy)
1215 		return NULL;
1216 
1217 	if (!alloc_cpumask_var(&policy->cpus, GFP_KERNEL))
1218 		goto err_free_policy;
1219 
1220 	if (!zalloc_cpumask_var(&policy->related_cpus, GFP_KERNEL))
1221 		goto err_free_cpumask;
1222 
1223 	if (!zalloc_cpumask_var(&policy->real_cpus, GFP_KERNEL))
1224 		goto err_free_rcpumask;
1225 
1226 	init_completion(&policy->kobj_unregister);
1227 	ret = kobject_init_and_add(&policy->kobj, &ktype_cpufreq,
1228 				   cpufreq_global_kobject, "policy%u", cpu);
1229 	if (ret) {
1230 		dev_err(dev, "%s: failed to init policy->kobj: %d\n", __func__, ret);
1231 		/*
1232 		 * The entire policy object will be freed below, but the extra
1233 		 * memory allocated for the kobject name needs to be freed by
1234 		 * releasing the kobject.
1235 		 */
1236 		kobject_put(&policy->kobj);
1237 		goto err_free_real_cpus;
1238 	}
1239 
1240 	freq_constraints_init(&policy->constraints);
1241 
1242 	policy->nb_min.notifier_call = cpufreq_notifier_min;
1243 	policy->nb_max.notifier_call = cpufreq_notifier_max;
1244 
1245 	ret = freq_qos_add_notifier(&policy->constraints, FREQ_QOS_MIN,
1246 				    &policy->nb_min);
1247 	if (ret) {
1248 		dev_err(dev, "Failed to register MIN QoS notifier: %d (%*pbl)\n",
1249 			ret, cpumask_pr_args(policy->cpus));
1250 		goto err_kobj_remove;
1251 	}
1252 
1253 	ret = freq_qos_add_notifier(&policy->constraints, FREQ_QOS_MAX,
1254 				    &policy->nb_max);
1255 	if (ret) {
1256 		dev_err(dev, "Failed to register MAX QoS notifier: %d (%*pbl)\n",
1257 			ret, cpumask_pr_args(policy->cpus));
1258 		goto err_min_qos_notifier;
1259 	}
1260 
1261 	INIT_LIST_HEAD(&policy->policy_list);
1262 	init_rwsem(&policy->rwsem);
1263 	spin_lock_init(&policy->transition_lock);
1264 	init_waitqueue_head(&policy->transition_wait);
1265 	INIT_WORK(&policy->update, handle_update);
1266 
1267 	policy->cpu = cpu;
1268 	return policy;
1269 
1270 err_min_qos_notifier:
1271 	freq_qos_remove_notifier(&policy->constraints, FREQ_QOS_MIN,
1272 				 &policy->nb_min);
1273 err_kobj_remove:
1274 	cpufreq_policy_put_kobj(policy);
1275 err_free_real_cpus:
1276 	free_cpumask_var(policy->real_cpus);
1277 err_free_rcpumask:
1278 	free_cpumask_var(policy->related_cpus);
1279 err_free_cpumask:
1280 	free_cpumask_var(policy->cpus);
1281 err_free_policy:
1282 	kfree(policy);
1283 
1284 	return NULL;
1285 }
1286 
cpufreq_policy_free(struct cpufreq_policy * policy)1287 static void cpufreq_policy_free(struct cpufreq_policy *policy)
1288 {
1289 	unsigned long flags;
1290 	int cpu;
1291 
1292 	/*
1293 	 * The callers must ensure the policy is inactive by now, to avoid any
1294 	 * races with show()/store() callbacks.
1295 	 */
1296 	if (unlikely(!policy_is_inactive(policy)))
1297 		pr_warn("%s: Freeing active policy\n", __func__);
1298 
1299 	/* Remove policy from list */
1300 	write_lock_irqsave(&cpufreq_driver_lock, flags);
1301 	list_del(&policy->policy_list);
1302 
1303 	for_each_cpu(cpu, policy->related_cpus)
1304 		per_cpu(cpufreq_cpu_data, cpu) = NULL;
1305 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
1306 
1307 	freq_qos_remove_notifier(&policy->constraints, FREQ_QOS_MAX,
1308 				 &policy->nb_max);
1309 	freq_qos_remove_notifier(&policy->constraints, FREQ_QOS_MIN,
1310 				 &policy->nb_min);
1311 
1312 	/* Cancel any pending policy->update work before freeing the policy. */
1313 	cancel_work_sync(&policy->update);
1314 
1315 	if (policy->max_freq_req) {
1316 		/*
1317 		 * Remove max_freq_req after sending CPUFREQ_REMOVE_POLICY
1318 		 * notification, since CPUFREQ_CREATE_POLICY notification was
1319 		 * sent after adding max_freq_req earlier.
1320 		 */
1321 		blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
1322 					     CPUFREQ_REMOVE_POLICY, policy);
1323 		freq_qos_remove_request(policy->max_freq_req);
1324 	}
1325 
1326 	freq_qos_remove_request(policy->min_freq_req);
1327 	kfree(policy->min_freq_req);
1328 
1329 	cpufreq_policy_put_kobj(policy);
1330 	free_cpumask_var(policy->real_cpus);
1331 	free_cpumask_var(policy->related_cpus);
1332 	free_cpumask_var(policy->cpus);
1333 	kfree(policy);
1334 }
1335 
cpufreq_online(unsigned int cpu)1336 static int cpufreq_online(unsigned int cpu)
1337 {
1338 	struct cpufreq_policy *policy;
1339 	bool new_policy;
1340 	unsigned long flags;
1341 	unsigned int j;
1342 	int ret;
1343 
1344 	pr_debug("%s: bringing CPU%u online\n", __func__, cpu);
1345 
1346 	/* Check if this CPU already has a policy to manage it */
1347 	policy = per_cpu(cpufreq_cpu_data, cpu);
1348 	if (policy) {
1349 		WARN_ON(!cpumask_test_cpu(cpu, policy->related_cpus));
1350 		if (!policy_is_inactive(policy))
1351 			return cpufreq_add_policy_cpu(policy, cpu);
1352 
1353 		/* This is the only online CPU for the policy.  Start over. */
1354 		new_policy = false;
1355 		down_write(&policy->rwsem);
1356 		policy->cpu = cpu;
1357 		policy->governor = NULL;
1358 	} else {
1359 		new_policy = true;
1360 		policy = cpufreq_policy_alloc(cpu);
1361 		if (!policy)
1362 			return -ENOMEM;
1363 		down_write(&policy->rwsem);
1364 	}
1365 
1366 	if (!new_policy && cpufreq_driver->online) {
1367 		/* Recover policy->cpus using related_cpus */
1368 		cpumask_copy(policy->cpus, policy->related_cpus);
1369 
1370 		ret = cpufreq_driver->online(policy);
1371 		if (ret) {
1372 			pr_debug("%s: %d: initialization failed\n", __func__,
1373 				 __LINE__);
1374 			goto out_exit_policy;
1375 		}
1376 	} else {
1377 		cpumask_copy(policy->cpus, cpumask_of(cpu));
1378 
1379 		/*
1380 		 * Call driver. From then on the cpufreq must be able
1381 		 * to accept all calls to ->verify and ->setpolicy for this CPU.
1382 		 */
1383 		ret = cpufreq_driver->init(policy);
1384 		if (ret) {
1385 			pr_debug("%s: %d: initialization failed\n", __func__,
1386 				 __LINE__);
1387 			goto out_free_policy;
1388 		}
1389 
1390 		/*
1391 		 * The initialization has succeeded and the policy is online.
1392 		 * If there is a problem with its frequency table, take it
1393 		 * offline and drop it.
1394 		 */
1395 		ret = cpufreq_table_validate_and_sort(policy);
1396 		if (ret)
1397 			goto out_offline_policy;
1398 
1399 		/* related_cpus should at least include policy->cpus. */
1400 		cpumask_copy(policy->related_cpus, policy->cpus);
1401 	}
1402 
1403 	/*
1404 	 * affected cpus must always be the one, which are online. We aren't
1405 	 * managing offline cpus here.
1406 	 */
1407 	cpumask_and(policy->cpus, policy->cpus, cpu_online_mask);
1408 
1409 	if (new_policy) {
1410 		for_each_cpu(j, policy->related_cpus) {
1411 			per_cpu(cpufreq_cpu_data, j) = policy;
1412 			add_cpu_dev_symlink(policy, j, get_cpu_device(j));
1413 		}
1414 
1415 		policy->min_freq_req = kzalloc(2 * sizeof(*policy->min_freq_req),
1416 					       GFP_KERNEL);
1417 		if (!policy->min_freq_req) {
1418 			ret = -ENOMEM;
1419 			goto out_destroy_policy;
1420 		}
1421 
1422 		ret = freq_qos_add_request(&policy->constraints,
1423 					   policy->min_freq_req, FREQ_QOS_MIN,
1424 					   FREQ_QOS_MIN_DEFAULT_VALUE);
1425 		if (ret < 0) {
1426 			/*
1427 			 * So we don't call freq_qos_remove_request() for an
1428 			 * uninitialized request.
1429 			 */
1430 			kfree(policy->min_freq_req);
1431 			policy->min_freq_req = NULL;
1432 			goto out_destroy_policy;
1433 		}
1434 
1435 		/*
1436 		 * This must be initialized right here to avoid calling
1437 		 * freq_qos_remove_request() on uninitialized request in case
1438 		 * of errors.
1439 		 */
1440 		policy->max_freq_req = policy->min_freq_req + 1;
1441 
1442 		ret = freq_qos_add_request(&policy->constraints,
1443 					   policy->max_freq_req, FREQ_QOS_MAX,
1444 					   FREQ_QOS_MAX_DEFAULT_VALUE);
1445 		if (ret < 0) {
1446 			policy->max_freq_req = NULL;
1447 			goto out_destroy_policy;
1448 		}
1449 
1450 		blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
1451 				CPUFREQ_CREATE_POLICY, policy);
1452 	}
1453 
1454 	if (cpufreq_driver->get && has_target()) {
1455 		policy->cur = cpufreq_driver->get(policy->cpu);
1456 		if (!policy->cur) {
1457 			ret = -EIO;
1458 			pr_err("%s: ->get() failed\n", __func__);
1459 			goto out_destroy_policy;
1460 		}
1461 	}
1462 
1463 	/*
1464 	 * Sometimes boot loaders set CPU frequency to a value outside of
1465 	 * frequency table present with cpufreq core. In such cases CPU might be
1466 	 * unstable if it has to run on that frequency for long duration of time
1467 	 * and so its better to set it to a frequency which is specified in
1468 	 * freq-table. This also makes cpufreq stats inconsistent as
1469 	 * cpufreq-stats would fail to register because current frequency of CPU
1470 	 * isn't found in freq-table.
1471 	 *
1472 	 * Because we don't want this change to effect boot process badly, we go
1473 	 * for the next freq which is >= policy->cur ('cur' must be set by now,
1474 	 * otherwise we will end up setting freq to lowest of the table as 'cur'
1475 	 * is initialized to zero).
1476 	 *
1477 	 * We are passing target-freq as "policy->cur - 1" otherwise
1478 	 * __cpufreq_driver_target() would simply fail, as policy->cur will be
1479 	 * equal to target-freq.
1480 	 */
1481 	if ((cpufreq_driver->flags & CPUFREQ_NEED_INITIAL_FREQ_CHECK)
1482 	    && has_target()) {
1483 		unsigned int old_freq = policy->cur;
1484 
1485 		/* Are we running at unknown frequency ? */
1486 		ret = cpufreq_frequency_table_get_index(policy, old_freq);
1487 		if (ret == -EINVAL) {
1488 			ret = __cpufreq_driver_target(policy, old_freq - 1,
1489 						      CPUFREQ_RELATION_L);
1490 
1491 			/*
1492 			 * Reaching here after boot in a few seconds may not
1493 			 * mean that system will remain stable at "unknown"
1494 			 * frequency for longer duration. Hence, a BUG_ON().
1495 			 */
1496 			BUG_ON(ret);
1497 			pr_info("%s: CPU%d: Running at unlisted initial frequency: %u KHz, changing to: %u KHz\n",
1498 				__func__, policy->cpu, old_freq, policy->cur);
1499 		}
1500 	}
1501 
1502 	if (new_policy) {
1503 		ret = cpufreq_add_dev_interface(policy);
1504 		if (ret)
1505 			goto out_destroy_policy;
1506 
1507 		cpufreq_stats_create_table(policy);
1508 		cpufreq_times_create_policy(policy);
1509 
1510 		write_lock_irqsave(&cpufreq_driver_lock, flags);
1511 		list_add(&policy->policy_list, &cpufreq_policy_list);
1512 		write_unlock_irqrestore(&cpufreq_driver_lock, flags);
1513 
1514 		/*
1515 		 * Register with the energy model before
1516 		 * sched_cpufreq_governor_change() is called, which will result
1517 		 * in rebuilding of the sched domains, which should only be done
1518 		 * once the energy model is properly initialized for the policy
1519 		 * first.
1520 		 *
1521 		 * Also, this should be called before the policy is registered
1522 		 * with cooling framework.
1523 		 */
1524 		if (cpufreq_driver->register_em)
1525 			cpufreq_driver->register_em(policy);
1526 	}
1527 
1528 	ret = cpufreq_init_policy(policy);
1529 	if (ret) {
1530 		pr_err("%s: Failed to initialize policy for cpu: %d (%d)\n",
1531 		       __func__, cpu, ret);
1532 		goto out_destroy_policy;
1533 	}
1534 
1535 	up_write(&policy->rwsem);
1536 
1537 	kobject_uevent(&policy->kobj, KOBJ_ADD);
1538 
1539 	/* Callback for handling stuff after policy is ready */
1540 	if (cpufreq_driver->ready)
1541 		cpufreq_driver->ready(policy);
1542 
1543 	/* Register cpufreq cooling only for a new policy */
1544 	if (new_policy && cpufreq_thermal_control_enabled(cpufreq_driver)) {
1545 		policy->cdev = of_cpufreq_cooling_register(policy);
1546 		trace_android_vh_thermal_register(policy);
1547 	}
1548 
1549 	pr_debug("initialization complete\n");
1550 
1551 	return 0;
1552 
1553 out_destroy_policy:
1554 	for_each_cpu(j, policy->real_cpus)
1555 		remove_cpu_dev_symlink(policy, j, get_cpu_device(j));
1556 
1557 out_offline_policy:
1558 	if (cpufreq_driver->offline)
1559 		cpufreq_driver->offline(policy);
1560 
1561 out_exit_policy:
1562 	if (cpufreq_driver->exit)
1563 		cpufreq_driver->exit(policy);
1564 
1565 out_free_policy:
1566 	cpumask_clear(policy->cpus);
1567 	up_write(&policy->rwsem);
1568 
1569 	cpufreq_policy_free(policy);
1570 	return ret;
1571 }
1572 
1573 /**
1574  * cpufreq_add_dev - the cpufreq interface for a CPU device.
1575  * @dev: CPU device.
1576  * @sif: Subsystem interface structure pointer (not used)
1577  */
cpufreq_add_dev(struct device * dev,struct subsys_interface * sif)1578 static int cpufreq_add_dev(struct device *dev, struct subsys_interface *sif)
1579 {
1580 	struct cpufreq_policy *policy;
1581 	unsigned cpu = dev->id;
1582 	int ret;
1583 
1584 	dev_dbg(dev, "%s: adding CPU%u\n", __func__, cpu);
1585 
1586 	if (cpu_online(cpu)) {
1587 		ret = cpufreq_online(cpu);
1588 		if (ret)
1589 			return ret;
1590 	}
1591 
1592 	/* Create sysfs link on CPU registration */
1593 	policy = per_cpu(cpufreq_cpu_data, cpu);
1594 	if (policy)
1595 		add_cpu_dev_symlink(policy, cpu, dev);
1596 
1597 	return 0;
1598 }
1599 
__cpufreq_offline(unsigned int cpu,struct cpufreq_policy * policy)1600 static void __cpufreq_offline(unsigned int cpu, struct cpufreq_policy *policy)
1601 {
1602 	int ret;
1603 
1604 	if (has_target())
1605 		cpufreq_stop_governor(policy);
1606 
1607 	cpumask_clear_cpu(cpu, policy->cpus);
1608 
1609 	if (!policy_is_inactive(policy)) {
1610 		/* Nominate a new CPU if necessary. */
1611 		if (cpu == policy->cpu)
1612 			policy->cpu = cpumask_any(policy->cpus);
1613 
1614 		/* Start the governor again for the active policy. */
1615 		if (has_target()) {
1616 			ret = cpufreq_start_governor(policy);
1617 			if (ret)
1618 				pr_err("%s: Failed to start governor\n", __func__);
1619 		}
1620 
1621 		return;
1622 	}
1623 
1624 	if (has_target())
1625 		strncpy(policy->last_governor, policy->governor->name,
1626 			CPUFREQ_NAME_LEN);
1627 	else
1628 		policy->last_policy = policy->policy;
1629 
1630 	if (has_target())
1631 		cpufreq_exit_governor(policy);
1632 
1633 	/*
1634 	 * Perform the ->offline() during light-weight tear-down, as
1635 	 * that allows fast recovery when the CPU comes back.
1636 	 */
1637 	if (cpufreq_driver->offline) {
1638 		cpufreq_driver->offline(policy);
1639 	} else if (cpufreq_driver->exit) {
1640 		cpufreq_driver->exit(policy);
1641 		policy->freq_table = NULL;
1642 	}
1643 }
1644 
cpufreq_offline(unsigned int cpu)1645 static int cpufreq_offline(unsigned int cpu)
1646 {
1647 	struct cpufreq_policy *policy;
1648 
1649 	pr_debug("%s: unregistering CPU %u\n", __func__, cpu);
1650 
1651 	policy = cpufreq_cpu_get_raw(cpu);
1652 	if (!policy) {
1653 		pr_debug("%s: No cpu_data found\n", __func__);
1654 		return 0;
1655 	}
1656 
1657 	down_write(&policy->rwsem);
1658 
1659 	__cpufreq_offline(cpu, policy);
1660 
1661 	up_write(&policy->rwsem);
1662 	return 0;
1663 }
1664 
1665 /*
1666  * cpufreq_remove_dev - remove a CPU device
1667  *
1668  * Removes the cpufreq interface for a CPU device.
1669  */
cpufreq_remove_dev(struct device * dev,struct subsys_interface * sif)1670 static void cpufreq_remove_dev(struct device *dev, struct subsys_interface *sif)
1671 {
1672 	unsigned int cpu = dev->id;
1673 	struct cpufreq_policy *policy = per_cpu(cpufreq_cpu_data, cpu);
1674 
1675 	if (!policy)
1676 		return;
1677 
1678 	down_write(&policy->rwsem);
1679 
1680 	if (cpu_online(cpu))
1681 		__cpufreq_offline(cpu, policy);
1682 
1683 	remove_cpu_dev_symlink(policy, cpu, dev);
1684 
1685 	if (!cpumask_empty(policy->real_cpus)) {
1686 		up_write(&policy->rwsem);
1687 		return;
1688 	}
1689 
1690 	/*
1691 	 * Unregister cpufreq cooling once all the CPUs of the policy are
1692 	 * removed.
1693 	 */
1694 	if (cpufreq_thermal_control_enabled(cpufreq_driver)) {
1695 		cpufreq_cooling_unregister(policy->cdev);
1696 		trace_android_vh_thermal_unregister(policy);
1697 		policy->cdev = NULL;
1698 	}
1699 
1700 	/* We did light-weight exit earlier, do full tear down now */
1701 	if (cpufreq_driver->offline)
1702 		cpufreq_driver->exit(policy);
1703 
1704 	up_write(&policy->rwsem);
1705 
1706 	cpufreq_policy_free(policy);
1707 }
1708 
1709 /**
1710  * cpufreq_out_of_sync - Fix up actual and saved CPU frequency difference.
1711  * @policy: Policy managing CPUs.
1712  * @new_freq: New CPU frequency.
1713  *
1714  * Adjust to the current frequency first and clean up later by either calling
1715  * cpufreq_update_policy(), or scheduling handle_update().
1716  */
cpufreq_out_of_sync(struct cpufreq_policy * policy,unsigned int new_freq)1717 static void cpufreq_out_of_sync(struct cpufreq_policy *policy,
1718 				unsigned int new_freq)
1719 {
1720 	struct cpufreq_freqs freqs;
1721 
1722 	pr_debug("Warning: CPU frequency out of sync: cpufreq and timing core thinks of %u, is %u kHz\n",
1723 		 policy->cur, new_freq);
1724 
1725 	freqs.old = policy->cur;
1726 	freqs.new = new_freq;
1727 
1728 	cpufreq_freq_transition_begin(policy, &freqs);
1729 	cpufreq_freq_transition_end(policy, &freqs, 0);
1730 }
1731 
cpufreq_verify_current_freq(struct cpufreq_policy * policy,bool update)1732 static unsigned int cpufreq_verify_current_freq(struct cpufreq_policy *policy, bool update)
1733 {
1734 	unsigned int new_freq;
1735 
1736 	new_freq = cpufreq_driver->get(policy->cpu);
1737 	if (!new_freq)
1738 		return 0;
1739 
1740 	/*
1741 	 * If fast frequency switching is used with the given policy, the check
1742 	 * against policy->cur is pointless, so skip it in that case.
1743 	 */
1744 	if (policy->fast_switch_enabled || !has_target())
1745 		return new_freq;
1746 
1747 	if (policy->cur != new_freq) {
1748 		/*
1749 		 * For some platforms, the frequency returned by hardware may be
1750 		 * slightly different from what is provided in the frequency
1751 		 * table, for example hardware may return 499 MHz instead of 500
1752 		 * MHz. In such cases it is better to avoid getting into
1753 		 * unnecessary frequency updates.
1754 		 */
1755 		if (abs(policy->cur - new_freq) < KHZ_PER_MHZ)
1756 			return policy->cur;
1757 
1758 		cpufreq_out_of_sync(policy, new_freq);
1759 		if (update)
1760 			schedule_work(&policy->update);
1761 	}
1762 
1763 	return new_freq;
1764 }
1765 
1766 /**
1767  * cpufreq_quick_get - get the CPU frequency (in kHz) from policy->cur
1768  * @cpu: CPU number
1769  *
1770  * This is the last known freq, without actually getting it from the driver.
1771  * Return value will be same as what is shown in scaling_cur_freq in sysfs.
1772  */
cpufreq_quick_get(unsigned int cpu)1773 unsigned int cpufreq_quick_get(unsigned int cpu)
1774 {
1775 	struct cpufreq_policy *policy;
1776 	unsigned int ret_freq = 0;
1777 	unsigned long flags;
1778 
1779 	read_lock_irqsave(&cpufreq_driver_lock, flags);
1780 
1781 	if (cpufreq_driver && cpufreq_driver->setpolicy && cpufreq_driver->get) {
1782 		ret_freq = cpufreq_driver->get(cpu);
1783 		read_unlock_irqrestore(&cpufreq_driver_lock, flags);
1784 		return ret_freq;
1785 	}
1786 
1787 	read_unlock_irqrestore(&cpufreq_driver_lock, flags);
1788 
1789 	policy = cpufreq_cpu_get(cpu);
1790 	if (policy) {
1791 		ret_freq = policy->cur;
1792 		cpufreq_cpu_put(policy);
1793 	}
1794 
1795 	return ret_freq;
1796 }
1797 EXPORT_SYMBOL(cpufreq_quick_get);
1798 
1799 /**
1800  * cpufreq_quick_get_max - get the max reported CPU frequency for this CPU
1801  * @cpu: CPU number
1802  *
1803  * Just return the max possible frequency for a given CPU.
1804  */
cpufreq_quick_get_max(unsigned int cpu)1805 unsigned int cpufreq_quick_get_max(unsigned int cpu)
1806 {
1807 	struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
1808 	unsigned int ret_freq = 0;
1809 
1810 	if (policy) {
1811 		ret_freq = policy->max;
1812 		cpufreq_cpu_put(policy);
1813 	}
1814 
1815 	return ret_freq;
1816 }
1817 EXPORT_SYMBOL(cpufreq_quick_get_max);
1818 
1819 /**
1820  * cpufreq_get_hw_max_freq - get the max hardware frequency of the CPU
1821  * @cpu: CPU number
1822  *
1823  * The default return value is the max_freq field of cpuinfo.
1824  */
cpufreq_get_hw_max_freq(unsigned int cpu)1825 __weak unsigned int cpufreq_get_hw_max_freq(unsigned int cpu)
1826 {
1827 	struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
1828 	unsigned int ret_freq = 0;
1829 
1830 	if (policy) {
1831 		ret_freq = policy->cpuinfo.max_freq;
1832 		cpufreq_cpu_put(policy);
1833 	}
1834 
1835 	return ret_freq;
1836 }
1837 EXPORT_SYMBOL(cpufreq_get_hw_max_freq);
1838 
__cpufreq_get(struct cpufreq_policy * policy)1839 static unsigned int __cpufreq_get(struct cpufreq_policy *policy)
1840 {
1841 	if (unlikely(policy_is_inactive(policy)))
1842 		return 0;
1843 
1844 	return cpufreq_verify_current_freq(policy, true);
1845 }
1846 
1847 /**
1848  * cpufreq_get - get the current CPU frequency (in kHz)
1849  * @cpu: CPU number
1850  *
1851  * Get the CPU current (static) CPU frequency
1852  */
cpufreq_get(unsigned int cpu)1853 unsigned int cpufreq_get(unsigned int cpu)
1854 {
1855 	struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
1856 	unsigned int ret_freq = 0;
1857 
1858 	if (policy) {
1859 		down_read(&policy->rwsem);
1860 		if (cpufreq_driver->get)
1861 			ret_freq = __cpufreq_get(policy);
1862 		up_read(&policy->rwsem);
1863 
1864 		cpufreq_cpu_put(policy);
1865 	}
1866 
1867 	return ret_freq;
1868 }
1869 EXPORT_SYMBOL(cpufreq_get);
1870 
1871 static struct subsys_interface cpufreq_interface = {
1872 	.name		= "cpufreq",
1873 	.subsys		= &cpu_subsys,
1874 	.add_dev	= cpufreq_add_dev,
1875 	.remove_dev	= cpufreq_remove_dev,
1876 };
1877 
1878 /*
1879  * In case platform wants some specific frequency to be configured
1880  * during suspend..
1881  */
cpufreq_generic_suspend(struct cpufreq_policy * policy)1882 int cpufreq_generic_suspend(struct cpufreq_policy *policy)
1883 {
1884 	int ret;
1885 
1886 	if (!policy->suspend_freq) {
1887 		pr_debug("%s: suspend_freq not defined\n", __func__);
1888 		return 0;
1889 	}
1890 
1891 	pr_debug("%s: Setting suspend-freq: %u\n", __func__,
1892 			policy->suspend_freq);
1893 
1894 	ret = __cpufreq_driver_target(policy, policy->suspend_freq,
1895 			CPUFREQ_RELATION_H);
1896 	if (ret)
1897 		pr_err("%s: unable to set suspend-freq: %u. err: %d\n",
1898 				__func__, policy->suspend_freq, ret);
1899 
1900 	return ret;
1901 }
1902 EXPORT_SYMBOL(cpufreq_generic_suspend);
1903 
1904 /**
1905  * cpufreq_suspend() - Suspend CPUFreq governors.
1906  *
1907  * Called during system wide Suspend/Hibernate cycles for suspending governors
1908  * as some platforms can't change frequency after this point in suspend cycle.
1909  * Because some of the devices (like: i2c, regulators, etc) they use for
1910  * changing frequency are suspended quickly after this point.
1911  */
cpufreq_suspend(void)1912 void cpufreq_suspend(void)
1913 {
1914 	struct cpufreq_policy *policy;
1915 
1916 	if (!cpufreq_driver)
1917 		return;
1918 
1919 	if (!has_target() && !cpufreq_driver->suspend)
1920 		goto suspend;
1921 
1922 	pr_debug("%s: Suspending Governors\n", __func__);
1923 
1924 	for_each_active_policy(policy) {
1925 		if (has_target()) {
1926 			down_write(&policy->rwsem);
1927 			cpufreq_stop_governor(policy);
1928 			up_write(&policy->rwsem);
1929 		}
1930 
1931 		if (cpufreq_driver->suspend && cpufreq_driver->suspend(policy))
1932 			pr_err("%s: Failed to suspend driver: %s\n", __func__,
1933 				cpufreq_driver->name);
1934 	}
1935 
1936 suspend:
1937 	cpufreq_suspended = true;
1938 }
1939 
1940 /**
1941  * cpufreq_resume() - Resume CPUFreq governors.
1942  *
1943  * Called during system wide Suspend/Hibernate cycle for resuming governors that
1944  * are suspended with cpufreq_suspend().
1945  */
cpufreq_resume(void)1946 void cpufreq_resume(void)
1947 {
1948 	struct cpufreq_policy *policy;
1949 	int ret;
1950 
1951 	if (!cpufreq_driver)
1952 		return;
1953 
1954 	if (unlikely(!cpufreq_suspended))
1955 		return;
1956 
1957 	cpufreq_suspended = false;
1958 
1959 	if (!has_target() && !cpufreq_driver->resume)
1960 		return;
1961 
1962 	pr_debug("%s: Resuming Governors\n", __func__);
1963 
1964 	for_each_active_policy(policy) {
1965 		if (cpufreq_driver->resume && cpufreq_driver->resume(policy)) {
1966 			pr_err("%s: Failed to resume driver: %p\n", __func__,
1967 				policy);
1968 		} else if (has_target()) {
1969 			down_write(&policy->rwsem);
1970 			ret = cpufreq_start_governor(policy);
1971 			up_write(&policy->rwsem);
1972 
1973 			if (ret)
1974 				pr_err("%s: Failed to start governor for policy: %p\n",
1975 				       __func__, policy);
1976 		}
1977 	}
1978 }
1979 
1980 /**
1981  * cpufreq_driver_test_flags - Test cpufreq driver's flags against given ones.
1982  * @flags: Flags to test against the current cpufreq driver's flags.
1983  *
1984  * Assumes that the driver is there, so callers must ensure that this is the
1985  * case.
1986  */
cpufreq_driver_test_flags(u16 flags)1987 bool cpufreq_driver_test_flags(u16 flags)
1988 {
1989 	return !!(cpufreq_driver->flags & flags);
1990 }
1991 EXPORT_SYMBOL_GPL(cpufreq_driver_test_flags);
1992 
1993 /**
1994  * cpufreq_get_current_driver - Return the current driver's name.
1995  *
1996  * Return the name string of the currently registered cpufreq driver or NULL if
1997  * none.
1998  */
cpufreq_get_current_driver(void)1999 const char *cpufreq_get_current_driver(void)
2000 {
2001 	if (cpufreq_driver)
2002 		return cpufreq_driver->name;
2003 
2004 	return NULL;
2005 }
2006 EXPORT_SYMBOL_GPL(cpufreq_get_current_driver);
2007 
2008 /**
2009  * cpufreq_get_driver_data - Return current driver data.
2010  *
2011  * Return the private data of the currently registered cpufreq driver, or NULL
2012  * if no cpufreq driver has been registered.
2013  */
cpufreq_get_driver_data(void)2014 void *cpufreq_get_driver_data(void)
2015 {
2016 	if (cpufreq_driver)
2017 		return cpufreq_driver->driver_data;
2018 
2019 	return NULL;
2020 }
2021 EXPORT_SYMBOL_GPL(cpufreq_get_driver_data);
2022 
2023 /*********************************************************************
2024  *                     NOTIFIER LISTS INTERFACE                      *
2025  *********************************************************************/
2026 
2027 /**
2028  * cpufreq_register_notifier - Register a notifier with cpufreq.
2029  * @nb: notifier function to register.
2030  * @list: CPUFREQ_TRANSITION_NOTIFIER or CPUFREQ_POLICY_NOTIFIER.
2031  *
2032  * Add a notifier to one of two lists: either a list of notifiers that run on
2033  * clock rate changes (once before and once after every transition), or a list
2034  * of notifiers that ron on cpufreq policy changes.
2035  *
2036  * This function may sleep and it has the same return values as
2037  * blocking_notifier_chain_register().
2038  */
cpufreq_register_notifier(struct notifier_block * nb,unsigned int list)2039 int cpufreq_register_notifier(struct notifier_block *nb, unsigned int list)
2040 {
2041 	int ret;
2042 
2043 	if (cpufreq_disabled())
2044 		return -EINVAL;
2045 
2046 	switch (list) {
2047 	case CPUFREQ_TRANSITION_NOTIFIER:
2048 		mutex_lock(&cpufreq_fast_switch_lock);
2049 
2050 		if (cpufreq_fast_switch_count > 0) {
2051 			mutex_unlock(&cpufreq_fast_switch_lock);
2052 			return -EBUSY;
2053 		}
2054 		ret = srcu_notifier_chain_register(
2055 				&cpufreq_transition_notifier_list, nb);
2056 		if (!ret)
2057 			cpufreq_fast_switch_count--;
2058 
2059 		mutex_unlock(&cpufreq_fast_switch_lock);
2060 		break;
2061 	case CPUFREQ_POLICY_NOTIFIER:
2062 		ret = blocking_notifier_chain_register(
2063 				&cpufreq_policy_notifier_list, nb);
2064 		break;
2065 	default:
2066 		ret = -EINVAL;
2067 	}
2068 
2069 	return ret;
2070 }
2071 EXPORT_SYMBOL(cpufreq_register_notifier);
2072 
2073 /**
2074  * cpufreq_unregister_notifier - Unregister a notifier from cpufreq.
2075  * @nb: notifier block to be unregistered.
2076  * @list: CPUFREQ_TRANSITION_NOTIFIER or CPUFREQ_POLICY_NOTIFIER.
2077  *
2078  * Remove a notifier from one of the cpufreq notifier lists.
2079  *
2080  * This function may sleep and it has the same return values as
2081  * blocking_notifier_chain_unregister().
2082  */
cpufreq_unregister_notifier(struct notifier_block * nb,unsigned int list)2083 int cpufreq_unregister_notifier(struct notifier_block *nb, unsigned int list)
2084 {
2085 	int ret;
2086 
2087 	if (cpufreq_disabled())
2088 		return -EINVAL;
2089 
2090 	switch (list) {
2091 	case CPUFREQ_TRANSITION_NOTIFIER:
2092 		mutex_lock(&cpufreq_fast_switch_lock);
2093 
2094 		ret = srcu_notifier_chain_unregister(
2095 				&cpufreq_transition_notifier_list, nb);
2096 		if (!ret && !WARN_ON(cpufreq_fast_switch_count >= 0))
2097 			cpufreq_fast_switch_count++;
2098 
2099 		mutex_unlock(&cpufreq_fast_switch_lock);
2100 		break;
2101 	case CPUFREQ_POLICY_NOTIFIER:
2102 		ret = blocking_notifier_chain_unregister(
2103 				&cpufreq_policy_notifier_list, nb);
2104 		break;
2105 	default:
2106 		ret = -EINVAL;
2107 	}
2108 
2109 	return ret;
2110 }
2111 EXPORT_SYMBOL(cpufreq_unregister_notifier);
2112 
2113 
2114 /*********************************************************************
2115  *                              GOVERNORS                            *
2116  *********************************************************************/
2117 
2118 /**
2119  * cpufreq_driver_fast_switch - Carry out a fast CPU frequency switch.
2120  * @policy: cpufreq policy to switch the frequency for.
2121  * @target_freq: New frequency to set (may be approximate).
2122  *
2123  * Carry out a fast frequency switch without sleeping.
2124  *
2125  * The driver's ->fast_switch() callback invoked by this function must be
2126  * suitable for being called from within RCU-sched read-side critical sections
2127  * and it is expected to select the minimum available frequency greater than or
2128  * equal to @target_freq (CPUFREQ_RELATION_L).
2129  *
2130  * This function must not be called if policy->fast_switch_enabled is unset.
2131  *
2132  * Governors calling this function must guarantee that it will never be invoked
2133  * twice in parallel for the same policy and that it will never be called in
2134  * parallel with either ->target() or ->target_index() for the same policy.
2135  *
2136  * Returns the actual frequency set for the CPU.
2137  *
2138  * If 0 is returned by the driver's ->fast_switch() callback to indicate an
2139  * error condition, the hardware configuration must be preserved.
2140  */
cpufreq_driver_fast_switch(struct cpufreq_policy * policy,unsigned int target_freq)2141 unsigned int cpufreq_driver_fast_switch(struct cpufreq_policy *policy,
2142 					unsigned int target_freq)
2143 {
2144 	unsigned int freq;
2145 	unsigned int old_target_freq = target_freq;
2146 	int cpu;
2147 
2148 	target_freq = clamp_val(target_freq, policy->min, policy->max);
2149 	trace_android_vh_cpufreq_fast_switch(policy, &target_freq, old_target_freq);
2150 	freq = cpufreq_driver->fast_switch(policy, target_freq);
2151 
2152 	if (!freq)
2153 		return 0;
2154 
2155 	policy->cur = freq;
2156 	arch_set_freq_scale(policy->related_cpus, freq,
2157 			    policy->cpuinfo.max_freq);
2158 	cpufreq_stats_record_transition(policy, freq);
2159 	cpufreq_times_record_transition(policy, freq);
2160 	trace_android_rvh_cpufreq_transition(policy);
2161 
2162 	if (trace_cpu_frequency_enabled()) {
2163 		for_each_cpu(cpu, policy->cpus)
2164 			trace_cpu_frequency(freq, cpu);
2165 	}
2166 
2167 	return freq;
2168 }
2169 EXPORT_SYMBOL_GPL(cpufreq_driver_fast_switch);
2170 
2171 /**
2172  * cpufreq_driver_adjust_perf - Adjust CPU performance level in one go.
2173  * @cpu: Target CPU.
2174  * @min_perf: Minimum (required) performance level (units of @capacity).
2175  * @target_perf: Target (desired) performance level (units of @capacity).
2176  * @capacity: Capacity of the target CPU.
2177  *
2178  * Carry out a fast performance level switch of @cpu without sleeping.
2179  *
2180  * The driver's ->adjust_perf() callback invoked by this function must be
2181  * suitable for being called from within RCU-sched read-side critical sections
2182  * and it is expected to select a suitable performance level equal to or above
2183  * @min_perf and preferably equal to or below @target_perf.
2184  *
2185  * This function must not be called if policy->fast_switch_enabled is unset.
2186  *
2187  * Governors calling this function must guarantee that it will never be invoked
2188  * twice in parallel for the same CPU and that it will never be called in
2189  * parallel with either ->target() or ->target_index() or ->fast_switch() for
2190  * the same CPU.
2191  */
cpufreq_driver_adjust_perf(unsigned int cpu,unsigned long min_perf,unsigned long target_perf,unsigned long capacity)2192 void cpufreq_driver_adjust_perf(unsigned int cpu,
2193 				 unsigned long min_perf,
2194 				 unsigned long target_perf,
2195 				 unsigned long capacity)
2196 {
2197 	cpufreq_driver->adjust_perf(cpu, min_perf, target_perf, capacity);
2198 }
2199 
2200 /**
2201  * cpufreq_driver_has_adjust_perf - Check "direct fast switch" callback.
2202  *
2203  * Return 'true' if the ->adjust_perf callback is present for the
2204  * current driver or 'false' otherwise.
2205  */
cpufreq_driver_has_adjust_perf(void)2206 bool cpufreq_driver_has_adjust_perf(void)
2207 {
2208 	return !!cpufreq_driver->adjust_perf;
2209 }
2210 
2211 /* Must set freqs->new to intermediate frequency */
__target_intermediate(struct cpufreq_policy * policy,struct cpufreq_freqs * freqs,int index)2212 static int __target_intermediate(struct cpufreq_policy *policy,
2213 				 struct cpufreq_freqs *freqs, int index)
2214 {
2215 	int ret;
2216 
2217 	freqs->new = cpufreq_driver->get_intermediate(policy, index);
2218 
2219 	/* We don't need to switch to intermediate freq */
2220 	if (!freqs->new)
2221 		return 0;
2222 
2223 	pr_debug("%s: cpu: %d, switching to intermediate freq: oldfreq: %u, intermediate freq: %u\n",
2224 		 __func__, policy->cpu, freqs->old, freqs->new);
2225 
2226 	cpufreq_freq_transition_begin(policy, freqs);
2227 	ret = cpufreq_driver->target_intermediate(policy, index);
2228 	cpufreq_freq_transition_end(policy, freqs, ret);
2229 
2230 	if (ret)
2231 		pr_err("%s: Failed to change to intermediate frequency: %d\n",
2232 		       __func__, ret);
2233 
2234 	return ret;
2235 }
2236 
__target_index(struct cpufreq_policy * policy,int index)2237 static int __target_index(struct cpufreq_policy *policy, int index)
2238 {
2239 	struct cpufreq_freqs freqs = {.old = policy->cur, .flags = 0};
2240 	unsigned int restore_freq, intermediate_freq = 0;
2241 	unsigned int newfreq = policy->freq_table[index].frequency;
2242 	int retval = -EINVAL;
2243 	bool notify;
2244 
2245 	if (newfreq == policy->cur)
2246 		return 0;
2247 
2248 	/* Save last value to restore later on errors */
2249 	restore_freq = policy->cur;
2250 
2251 	notify = !(cpufreq_driver->flags & CPUFREQ_ASYNC_NOTIFICATION);
2252 	if (notify) {
2253 		/* Handle switching to intermediate frequency */
2254 		if (cpufreq_driver->get_intermediate) {
2255 			retval = __target_intermediate(policy, &freqs, index);
2256 			if (retval)
2257 				return retval;
2258 
2259 			intermediate_freq = freqs.new;
2260 			/* Set old freq to intermediate */
2261 			if (intermediate_freq)
2262 				freqs.old = freqs.new;
2263 		}
2264 
2265 		freqs.new = newfreq;
2266 		pr_debug("%s: cpu: %d, oldfreq: %u, new freq: %u\n",
2267 			 __func__, policy->cpu, freqs.old, freqs.new);
2268 
2269 		cpufreq_freq_transition_begin(policy, &freqs);
2270 	}
2271 
2272 	retval = cpufreq_driver->target_index(policy, index);
2273 	if (retval)
2274 		pr_err("%s: Failed to change cpu frequency: %d\n", __func__,
2275 		       retval);
2276 
2277 	if (notify) {
2278 		cpufreq_freq_transition_end(policy, &freqs, retval);
2279 
2280 		/*
2281 		 * Failed after setting to intermediate freq? Driver should have
2282 		 * reverted back to initial frequency and so should we. Check
2283 		 * here for intermediate_freq instead of get_intermediate, in
2284 		 * case we haven't switched to intermediate freq at all.
2285 		 */
2286 		if (unlikely(retval && intermediate_freq)) {
2287 			freqs.old = intermediate_freq;
2288 			freqs.new = restore_freq;
2289 			cpufreq_freq_transition_begin(policy, &freqs);
2290 			cpufreq_freq_transition_end(policy, &freqs, 0);
2291 		}
2292 	}
2293 
2294 	return retval;
2295 }
2296 
__cpufreq_driver_target(struct cpufreq_policy * policy,unsigned int target_freq,unsigned int relation)2297 int __cpufreq_driver_target(struct cpufreq_policy *policy,
2298 			    unsigned int target_freq,
2299 			    unsigned int relation)
2300 {
2301 	unsigned int old_target_freq = target_freq;
2302 
2303 	if (cpufreq_disabled())
2304 		return -ENODEV;
2305 
2306 	target_freq = __resolve_freq(policy, target_freq, relation);
2307 
2308 	trace_android_vh_cpufreq_target(policy, &target_freq, old_target_freq);
2309 
2310 	pr_debug("target for CPU %u: %u kHz, relation %u, requested %u kHz\n",
2311 		 policy->cpu, target_freq, relation, old_target_freq);
2312 
2313 	/*
2314 	 * This might look like a redundant call as we are checking it again
2315 	 * after finding index. But it is left intentionally for cases where
2316 	 * exactly same freq is called again and so we can save on few function
2317 	 * calls.
2318 	 */
2319 	if (target_freq == policy->cur &&
2320 	    !(cpufreq_driver->flags & CPUFREQ_NEED_UPDATE_LIMITS))
2321 		return 0;
2322 
2323 	if (cpufreq_driver->target) {
2324 		/*
2325 		 * If the driver hasn't setup a single inefficient frequency,
2326 		 * it's unlikely it knows how to decode CPUFREQ_RELATION_E.
2327 		 */
2328 		if (!policy->efficiencies_available)
2329 			relation &= ~CPUFREQ_RELATION_E;
2330 
2331 		return cpufreq_driver->target(policy, target_freq, relation);
2332 	}
2333 
2334 	if (!cpufreq_driver->target_index)
2335 		return -EINVAL;
2336 
2337 	return __target_index(policy, policy->cached_resolved_idx);
2338 }
2339 EXPORT_SYMBOL_GPL(__cpufreq_driver_target);
2340 
cpufreq_driver_target(struct cpufreq_policy * policy,unsigned int target_freq,unsigned int relation)2341 int cpufreq_driver_target(struct cpufreq_policy *policy,
2342 			  unsigned int target_freq,
2343 			  unsigned int relation)
2344 {
2345 	int ret;
2346 
2347 	down_write(&policy->rwsem);
2348 
2349 	ret = __cpufreq_driver_target(policy, target_freq, relation);
2350 
2351 	up_write(&policy->rwsem);
2352 
2353 	return ret;
2354 }
2355 EXPORT_SYMBOL_GPL(cpufreq_driver_target);
2356 
cpufreq_fallback_governor(void)2357 __weak struct cpufreq_governor *cpufreq_fallback_governor(void)
2358 {
2359 	return NULL;
2360 }
2361 
cpufreq_init_governor(struct cpufreq_policy * policy)2362 static int cpufreq_init_governor(struct cpufreq_policy *policy)
2363 {
2364 	int ret;
2365 
2366 	/* Don't start any governor operations if we are entering suspend */
2367 	if (cpufreq_suspended)
2368 		return 0;
2369 	/*
2370 	 * Governor might not be initiated here if ACPI _PPC changed
2371 	 * notification happened, so check it.
2372 	 */
2373 	if (!policy->governor)
2374 		return -EINVAL;
2375 
2376 	/* Platform doesn't want dynamic frequency switching ? */
2377 	if (policy->governor->flags & CPUFREQ_GOV_DYNAMIC_SWITCHING &&
2378 	    cpufreq_driver->flags & CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING) {
2379 		struct cpufreq_governor *gov = cpufreq_fallback_governor();
2380 
2381 		if (gov) {
2382 			pr_warn("Can't use %s governor as dynamic switching is disallowed. Fallback to %s governor\n",
2383 				policy->governor->name, gov->name);
2384 			policy->governor = gov;
2385 		} else {
2386 			return -EINVAL;
2387 		}
2388 	}
2389 
2390 	if (!try_module_get(policy->governor->owner))
2391 		return -EINVAL;
2392 
2393 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2394 
2395 	if (policy->governor->init) {
2396 		ret = policy->governor->init(policy);
2397 		if (ret) {
2398 			module_put(policy->governor->owner);
2399 			return ret;
2400 		}
2401 	}
2402 
2403 	policy->strict_target = !!(policy->governor->flags & CPUFREQ_GOV_STRICT_TARGET);
2404 
2405 	return 0;
2406 }
2407 
cpufreq_exit_governor(struct cpufreq_policy * policy)2408 static void cpufreq_exit_governor(struct cpufreq_policy *policy)
2409 {
2410 	if (cpufreq_suspended || !policy->governor)
2411 		return;
2412 
2413 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2414 
2415 	if (policy->governor->exit)
2416 		policy->governor->exit(policy);
2417 
2418 	module_put(policy->governor->owner);
2419 }
2420 
cpufreq_start_governor(struct cpufreq_policy * policy)2421 int cpufreq_start_governor(struct cpufreq_policy *policy)
2422 {
2423 	int ret;
2424 
2425 	if (cpufreq_suspended)
2426 		return 0;
2427 
2428 	if (!policy->governor)
2429 		return -EINVAL;
2430 
2431 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2432 
2433 	if (cpufreq_driver->get)
2434 		cpufreq_verify_current_freq(policy, false);
2435 
2436 	if (policy->governor->start) {
2437 		ret = policy->governor->start(policy);
2438 		if (ret)
2439 			return ret;
2440 	}
2441 
2442 	if (policy->governor->limits)
2443 		policy->governor->limits(policy);
2444 
2445 	return 0;
2446 }
2447 
cpufreq_stop_governor(struct cpufreq_policy * policy)2448 void cpufreq_stop_governor(struct cpufreq_policy *policy)
2449 {
2450 	if (cpufreq_suspended || !policy->governor)
2451 		return;
2452 
2453 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2454 
2455 	if (policy->governor->stop)
2456 		policy->governor->stop(policy);
2457 }
2458 
cpufreq_governor_limits(struct cpufreq_policy * policy)2459 static void cpufreq_governor_limits(struct cpufreq_policy *policy)
2460 {
2461 	if (cpufreq_suspended || !policy->governor)
2462 		return;
2463 
2464 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2465 
2466 	if (policy->governor->limits)
2467 		policy->governor->limits(policy);
2468 }
2469 
cpufreq_register_governor(struct cpufreq_governor * governor)2470 int cpufreq_register_governor(struct cpufreq_governor *governor)
2471 {
2472 	int err;
2473 
2474 	if (!governor)
2475 		return -EINVAL;
2476 
2477 	if (cpufreq_disabled())
2478 		return -ENODEV;
2479 
2480 	mutex_lock(&cpufreq_governor_mutex);
2481 
2482 	err = -EBUSY;
2483 	if (!find_governor(governor->name)) {
2484 		err = 0;
2485 		list_add(&governor->governor_list, &cpufreq_governor_list);
2486 	}
2487 
2488 	mutex_unlock(&cpufreq_governor_mutex);
2489 	return err;
2490 }
2491 EXPORT_SYMBOL_GPL(cpufreq_register_governor);
2492 
cpufreq_unregister_governor(struct cpufreq_governor * governor)2493 void cpufreq_unregister_governor(struct cpufreq_governor *governor)
2494 {
2495 	struct cpufreq_policy *policy;
2496 	unsigned long flags;
2497 
2498 	if (!governor)
2499 		return;
2500 
2501 	if (cpufreq_disabled())
2502 		return;
2503 
2504 	/* clear last_governor for all inactive policies */
2505 	read_lock_irqsave(&cpufreq_driver_lock, flags);
2506 	for_each_inactive_policy(policy) {
2507 		if (!strcmp(policy->last_governor, governor->name)) {
2508 			policy->governor = NULL;
2509 			strcpy(policy->last_governor, "\0");
2510 		}
2511 	}
2512 	read_unlock_irqrestore(&cpufreq_driver_lock, flags);
2513 
2514 	mutex_lock(&cpufreq_governor_mutex);
2515 	list_del(&governor->governor_list);
2516 	mutex_unlock(&cpufreq_governor_mutex);
2517 }
2518 EXPORT_SYMBOL_GPL(cpufreq_unregister_governor);
2519 
2520 
2521 /*********************************************************************
2522  *                          POLICY INTERFACE                         *
2523  *********************************************************************/
2524 
2525 /**
2526  * cpufreq_get_policy - get the current cpufreq_policy
2527  * @policy: struct cpufreq_policy into which the current cpufreq_policy
2528  *	is written
2529  * @cpu: CPU to find the policy for
2530  *
2531  * Reads the current cpufreq policy.
2532  */
cpufreq_get_policy(struct cpufreq_policy * policy,unsigned int cpu)2533 int cpufreq_get_policy(struct cpufreq_policy *policy, unsigned int cpu)
2534 {
2535 	struct cpufreq_policy *cpu_policy;
2536 	if (!policy)
2537 		return -EINVAL;
2538 
2539 	cpu_policy = cpufreq_cpu_get(cpu);
2540 	if (!cpu_policy)
2541 		return -EINVAL;
2542 
2543 	memcpy(policy, cpu_policy, sizeof(*policy));
2544 
2545 	cpufreq_cpu_put(cpu_policy);
2546 	return 0;
2547 }
2548 EXPORT_SYMBOL(cpufreq_get_policy);
2549 
2550 /**
2551  * cpufreq_set_policy - Modify cpufreq policy parameters.
2552  * @policy: Policy object to modify.
2553  * @new_gov: Policy governor pointer.
2554  * @new_pol: Policy value (for drivers with built-in governors).
2555  *
2556  * Invoke the cpufreq driver's ->verify() callback to sanity-check the frequency
2557  * limits to be set for the policy, update @policy with the verified limits
2558  * values and either invoke the driver's ->setpolicy() callback (if present) or
2559  * carry out a governor update for @policy.  That is, run the current governor's
2560  * ->limits() callback (if @new_gov points to the same object as the one in
2561  * @policy) or replace the governor for @policy with @new_gov.
2562  *
2563  * The cpuinfo part of @policy is not updated by this function.
2564  */
cpufreq_set_policy(struct cpufreq_policy * policy,struct cpufreq_governor * new_gov,unsigned int new_pol)2565 static int cpufreq_set_policy(struct cpufreq_policy *policy,
2566 			      struct cpufreq_governor *new_gov,
2567 			      unsigned int new_pol)
2568 {
2569 	struct cpufreq_policy_data new_data;
2570 	struct cpufreq_governor *old_gov;
2571 	int ret;
2572 
2573 	memcpy(&new_data.cpuinfo, &policy->cpuinfo, sizeof(policy->cpuinfo));
2574 	new_data.freq_table = policy->freq_table;
2575 	new_data.cpu = policy->cpu;
2576 	/*
2577 	 * PM QoS framework collects all the requests from users and provide us
2578 	 * the final aggregated value here.
2579 	 */
2580 	new_data.min = freq_qos_read_value(&policy->constraints, FREQ_QOS_MIN);
2581 	new_data.max = freq_qos_read_value(&policy->constraints, FREQ_QOS_MAX);
2582 
2583 	pr_debug("setting new policy for CPU %u: %u - %u kHz\n",
2584 		 new_data.cpu, new_data.min, new_data.max);
2585 
2586 	/*
2587 	 * Verify that the CPU speed can be set within these limits and make sure
2588 	 * that min <= max.
2589 	 */
2590 	ret = cpufreq_driver->verify(&new_data);
2591 	if (ret)
2592 		return ret;
2593 
2594 	/*
2595 	 * Resolve policy min/max to available frequencies. It ensures
2596 	 * no frequency resolution will neither overshoot the requested maximum
2597 	 * nor undershoot the requested minimum.
2598 	 */
2599 	policy->min = new_data.min;
2600 	policy->max = new_data.max;
2601 	policy->min = __resolve_freq(policy, policy->min, CPUFREQ_RELATION_L);
2602 	policy->max = __resolve_freq(policy, policy->max, CPUFREQ_RELATION_H);
2603 	trace_cpu_frequency_limits(policy);
2604 
2605 	policy->cached_target_freq = UINT_MAX;
2606 
2607 	pr_debug("new min and max freqs are %u - %u kHz\n",
2608 		 policy->min, policy->max);
2609 
2610 	if (cpufreq_driver->setpolicy) {
2611 		policy->policy = new_pol;
2612 		pr_debug("setting range\n");
2613 		return cpufreq_driver->setpolicy(policy);
2614 	}
2615 
2616 	if (new_gov == policy->governor) {
2617 		pr_debug("governor limits update\n");
2618 		cpufreq_governor_limits(policy);
2619 		return 0;
2620 	}
2621 
2622 	pr_debug("governor switch\n");
2623 
2624 	/* save old, working values */
2625 	old_gov = policy->governor;
2626 	/* end old governor */
2627 	if (old_gov) {
2628 		cpufreq_stop_governor(policy);
2629 		cpufreq_exit_governor(policy);
2630 	}
2631 
2632 	/* start new governor */
2633 	policy->governor = new_gov;
2634 	ret = cpufreq_init_governor(policy);
2635 	if (!ret) {
2636 		ret = cpufreq_start_governor(policy);
2637 		if (!ret) {
2638 			pr_debug("governor change\n");
2639 			return 0;
2640 		}
2641 		cpufreq_exit_governor(policy);
2642 	}
2643 
2644 	/* new governor failed, so re-start old one */
2645 	pr_debug("starting governor %s failed\n", policy->governor->name);
2646 	if (old_gov) {
2647 		policy->governor = old_gov;
2648 		if (cpufreq_init_governor(policy))
2649 			policy->governor = NULL;
2650 		else
2651 			cpufreq_start_governor(policy);
2652 	}
2653 
2654 	return ret;
2655 }
2656 EXPORT_TRACEPOINT_SYMBOL_GPL(cpu_frequency_limits);
2657 
2658 /**
2659  * cpufreq_update_policy - Re-evaluate an existing cpufreq policy.
2660  * @cpu: CPU to re-evaluate the policy for.
2661  *
2662  * Update the current frequency for the cpufreq policy of @cpu and use
2663  * cpufreq_set_policy() to re-apply the min and max limits, which triggers the
2664  * evaluation of policy notifiers and the cpufreq driver's ->verify() callback
2665  * for the policy in question, among other things.
2666  */
cpufreq_update_policy(unsigned int cpu)2667 void cpufreq_update_policy(unsigned int cpu)
2668 {
2669 	struct cpufreq_policy *policy = cpufreq_cpu_acquire(cpu);
2670 
2671 	if (!policy)
2672 		return;
2673 
2674 	/*
2675 	 * BIOS might change freq behind our back
2676 	 * -> ask driver for current freq and notify governors about a change
2677 	 */
2678 	if (cpufreq_driver->get && has_target() &&
2679 	    (cpufreq_suspended || WARN_ON(!cpufreq_verify_current_freq(policy, false))))
2680 		goto unlock;
2681 
2682 	refresh_frequency_limits(policy);
2683 
2684 unlock:
2685 	cpufreq_cpu_release(policy);
2686 }
2687 EXPORT_SYMBOL(cpufreq_update_policy);
2688 
2689 /**
2690  * cpufreq_update_limits - Update policy limits for a given CPU.
2691  * @cpu: CPU to update the policy limits for.
2692  *
2693  * Invoke the driver's ->update_limits callback if present or call
2694  * cpufreq_update_policy() for @cpu.
2695  */
cpufreq_update_limits(unsigned int cpu)2696 void cpufreq_update_limits(unsigned int cpu)
2697 {
2698 	if (cpufreq_driver->update_limits)
2699 		cpufreq_driver->update_limits(cpu);
2700 	else
2701 		cpufreq_update_policy(cpu);
2702 }
2703 EXPORT_SYMBOL_GPL(cpufreq_update_limits);
2704 
2705 /*********************************************************************
2706  *               BOOST						     *
2707  *********************************************************************/
cpufreq_boost_set_sw(struct cpufreq_policy * policy,int state)2708 static int cpufreq_boost_set_sw(struct cpufreq_policy *policy, int state)
2709 {
2710 	int ret;
2711 
2712 	if (!policy->freq_table)
2713 		return -ENXIO;
2714 
2715 	ret = cpufreq_frequency_table_cpuinfo(policy, policy->freq_table);
2716 	if (ret) {
2717 		pr_err("%s: Policy frequency update failed\n", __func__);
2718 		return ret;
2719 	}
2720 
2721 	ret = freq_qos_update_request(policy->max_freq_req, policy->max);
2722 	if (ret < 0)
2723 		return ret;
2724 
2725 	return 0;
2726 }
2727 
cpufreq_boost_trigger_state(int state)2728 int cpufreq_boost_trigger_state(int state)
2729 {
2730 	struct cpufreq_policy *policy;
2731 	unsigned long flags;
2732 	int ret = 0;
2733 
2734 	if (cpufreq_driver->boost_enabled == state)
2735 		return 0;
2736 
2737 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2738 	cpufreq_driver->boost_enabled = state;
2739 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2740 
2741 	cpus_read_lock();
2742 	for_each_active_policy(policy) {
2743 		ret = cpufreq_driver->set_boost(policy, state);
2744 		if (ret)
2745 			goto err_reset_state;
2746 	}
2747 	cpus_read_unlock();
2748 
2749 	return 0;
2750 
2751 err_reset_state:
2752 	cpus_read_unlock();
2753 
2754 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2755 	cpufreq_driver->boost_enabled = !state;
2756 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2757 
2758 	pr_err("%s: Cannot %s BOOST\n",
2759 	       __func__, state ? "enable" : "disable");
2760 
2761 	return ret;
2762 }
2763 
cpufreq_boost_supported(void)2764 static bool cpufreq_boost_supported(void)
2765 {
2766 	return cpufreq_driver->set_boost;
2767 }
2768 
create_boost_sysfs_file(void)2769 static int create_boost_sysfs_file(void)
2770 {
2771 	int ret;
2772 
2773 	ret = sysfs_create_file(cpufreq_global_kobject, &boost.attr);
2774 	if (ret)
2775 		pr_err("%s: cannot register global BOOST sysfs file\n",
2776 		       __func__);
2777 
2778 	return ret;
2779 }
2780 
remove_boost_sysfs_file(void)2781 static void remove_boost_sysfs_file(void)
2782 {
2783 	if (cpufreq_boost_supported())
2784 		sysfs_remove_file(cpufreq_global_kobject, &boost.attr);
2785 }
2786 
cpufreq_enable_boost_support(void)2787 int cpufreq_enable_boost_support(void)
2788 {
2789 	if (!cpufreq_driver)
2790 		return -EINVAL;
2791 
2792 	if (cpufreq_boost_supported())
2793 		return 0;
2794 
2795 	cpufreq_driver->set_boost = cpufreq_boost_set_sw;
2796 
2797 	/* This will get removed on driver unregister */
2798 	return create_boost_sysfs_file();
2799 }
2800 EXPORT_SYMBOL_GPL(cpufreq_enable_boost_support);
2801 
cpufreq_boost_enabled(void)2802 int cpufreq_boost_enabled(void)
2803 {
2804 	return cpufreq_driver->boost_enabled;
2805 }
2806 EXPORT_SYMBOL_GPL(cpufreq_boost_enabled);
2807 
2808 /*********************************************************************
2809  *               REGISTER / UNREGISTER CPUFREQ DRIVER                *
2810  *********************************************************************/
2811 static enum cpuhp_state hp_online;
2812 
cpuhp_cpufreq_online(unsigned int cpu)2813 static int cpuhp_cpufreq_online(unsigned int cpu)
2814 {
2815 	cpufreq_online(cpu);
2816 
2817 	return 0;
2818 }
2819 
cpuhp_cpufreq_offline(unsigned int cpu)2820 static int cpuhp_cpufreq_offline(unsigned int cpu)
2821 {
2822 	cpufreq_offline(cpu);
2823 
2824 	return 0;
2825 }
2826 
2827 /**
2828  * cpufreq_register_driver - register a CPU Frequency driver
2829  * @driver_data: A struct cpufreq_driver containing the values#
2830  * submitted by the CPU Frequency driver.
2831  *
2832  * Registers a CPU Frequency driver to this core code. This code
2833  * returns zero on success, -EEXIST when another driver got here first
2834  * (and isn't unregistered in the meantime).
2835  *
2836  */
cpufreq_register_driver(struct cpufreq_driver * driver_data)2837 int cpufreq_register_driver(struct cpufreq_driver *driver_data)
2838 {
2839 	unsigned long flags;
2840 	int ret;
2841 
2842 	if (cpufreq_disabled())
2843 		return -ENODEV;
2844 
2845 	/*
2846 	 * The cpufreq core depends heavily on the availability of device
2847 	 * structure, make sure they are available before proceeding further.
2848 	 */
2849 	if (!get_cpu_device(0))
2850 		return -EPROBE_DEFER;
2851 
2852 	if (!driver_data || !driver_data->verify || !driver_data->init ||
2853 	    !(driver_data->setpolicy || driver_data->target_index ||
2854 		    driver_data->target) ||
2855 	     (driver_data->setpolicy && (driver_data->target_index ||
2856 		    driver_data->target)) ||
2857 	     (!driver_data->get_intermediate != !driver_data->target_intermediate) ||
2858 	     (!driver_data->online != !driver_data->offline))
2859 		return -EINVAL;
2860 
2861 	pr_debug("trying to register driver %s\n", driver_data->name);
2862 
2863 	/* Protect against concurrent CPU online/offline. */
2864 	cpus_read_lock();
2865 
2866 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2867 	if (cpufreq_driver) {
2868 		write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2869 		ret = -EEXIST;
2870 		goto out;
2871 	}
2872 	cpufreq_driver = driver_data;
2873 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2874 
2875 	/*
2876 	 * Mark support for the scheduler's frequency invariance engine for
2877 	 * drivers that implement target(), target_index() or fast_switch().
2878 	 */
2879 	if (!cpufreq_driver->setpolicy) {
2880 		static_branch_enable_cpuslocked(&cpufreq_freq_invariance);
2881 		pr_debug("supports frequency invariance");
2882 	}
2883 
2884 	if (driver_data->setpolicy)
2885 		driver_data->flags |= CPUFREQ_CONST_LOOPS;
2886 
2887 	if (cpufreq_boost_supported()) {
2888 		ret = create_boost_sysfs_file();
2889 		if (ret)
2890 			goto err_null_driver;
2891 	}
2892 
2893 	ret = subsys_interface_register(&cpufreq_interface);
2894 	if (ret)
2895 		goto err_boost_unreg;
2896 
2897 	if (unlikely(list_empty(&cpufreq_policy_list))) {
2898 		/* if all ->init() calls failed, unregister */
2899 		ret = -ENODEV;
2900 		pr_debug("%s: No CPU initialized for driver %s\n", __func__,
2901 			 driver_data->name);
2902 		goto err_if_unreg;
2903 	}
2904 
2905 	ret = cpuhp_setup_state_nocalls_cpuslocked(CPUHP_AP_ONLINE_DYN,
2906 						   "cpufreq:online",
2907 						   cpuhp_cpufreq_online,
2908 						   cpuhp_cpufreq_offline);
2909 	if (ret < 0)
2910 		goto err_if_unreg;
2911 	hp_online = ret;
2912 	ret = 0;
2913 
2914 	pr_debug("driver %s up and running\n", driver_data->name);
2915 	goto out;
2916 
2917 err_if_unreg:
2918 	subsys_interface_unregister(&cpufreq_interface);
2919 err_boost_unreg:
2920 	remove_boost_sysfs_file();
2921 err_null_driver:
2922 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2923 	cpufreq_driver = NULL;
2924 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2925 out:
2926 	cpus_read_unlock();
2927 	return ret;
2928 }
2929 EXPORT_SYMBOL_GPL(cpufreq_register_driver);
2930 
2931 /*
2932  * cpufreq_unregister_driver - unregister the current CPUFreq driver
2933  *
2934  * Unregister the current CPUFreq driver. Only call this if you have
2935  * the right to do so, i.e. if you have succeeded in initialising before!
2936  * Returns zero if successful, and -EINVAL if the cpufreq_driver is
2937  * currently not initialised.
2938  */
cpufreq_unregister_driver(struct cpufreq_driver * driver)2939 int cpufreq_unregister_driver(struct cpufreq_driver *driver)
2940 {
2941 	unsigned long flags;
2942 
2943 	if (!cpufreq_driver || (driver != cpufreq_driver))
2944 		return -EINVAL;
2945 
2946 	pr_debug("unregistering driver %s\n", driver->name);
2947 
2948 	/* Protect against concurrent cpu hotplug */
2949 	cpus_read_lock();
2950 	subsys_interface_unregister(&cpufreq_interface);
2951 	remove_boost_sysfs_file();
2952 	static_branch_disable_cpuslocked(&cpufreq_freq_invariance);
2953 	cpuhp_remove_state_nocalls_cpuslocked(hp_online);
2954 
2955 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2956 
2957 	cpufreq_driver = NULL;
2958 
2959 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2960 	cpus_read_unlock();
2961 
2962 	return 0;
2963 }
2964 EXPORT_SYMBOL_GPL(cpufreq_unregister_driver);
2965 
cpufreq_core_init(void)2966 static int __init cpufreq_core_init(void)
2967 {
2968 	struct cpufreq_governor *gov = cpufreq_default_governor();
2969 
2970 	if (cpufreq_disabled())
2971 		return -ENODEV;
2972 
2973 	cpufreq_global_kobject = kobject_create_and_add("cpufreq", &cpu_subsys.dev_root->kobj);
2974 	BUG_ON(!cpufreq_global_kobject);
2975 
2976 	if (!strlen(default_governor))
2977 		strncpy(default_governor, gov->name, CPUFREQ_NAME_LEN);
2978 
2979 	return 0;
2980 }
2981 module_param(off, int, 0444);
2982 module_param_string(default_governor, default_governor, CPUFREQ_NAME_LEN, 0444);
2983 core_initcall(cpufreq_core_init);
2984