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