• 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 	trace_android_rvh_show_max_freq(policy, &max_freq);
706 	return sprintf(buf, "%u\n", max_freq);
707 }
708 
709 show_one(cpuinfo_min_freq, cpuinfo.min_freq);
710 show_one(cpuinfo_transition_latency, cpuinfo.transition_latency);
711 show_one(scaling_min_freq, min);
712 show_one(scaling_max_freq, max);
713 
arch_freq_get_on_cpu(int cpu)714 __weak unsigned int arch_freq_get_on_cpu(int cpu)
715 {
716 	return 0;
717 }
718 
show_scaling_cur_freq(struct cpufreq_policy * policy,char * buf)719 static ssize_t show_scaling_cur_freq(struct cpufreq_policy *policy, char *buf)
720 {
721 	ssize_t ret;
722 	unsigned int freq;
723 
724 	freq = arch_freq_get_on_cpu(policy->cpu);
725 	if (freq)
726 		ret = sprintf(buf, "%u\n", freq);
727 	else if (cpufreq_driver->setpolicy && cpufreq_driver->get)
728 		ret = sprintf(buf, "%u\n", cpufreq_driver->get(policy->cpu));
729 	else
730 		ret = sprintf(buf, "%u\n", policy->cur);
731 	return ret;
732 }
733 
734 /*
735  * cpufreq_per_cpu_attr_write() / store_##file_name() - sysfs write access
736  */
737 #define store_one(file_name, object)			\
738 static ssize_t store_##file_name					\
739 (struct cpufreq_policy *policy, const char *buf, size_t count)		\
740 {									\
741 	unsigned long val;						\
742 	int ret;							\
743 									\
744 	ret = sscanf(buf, "%lu", &val);					\
745 	if (ret != 1)							\
746 		return -EINVAL;						\
747 									\
748 	ret = freq_qos_update_request(policy->object##_freq_req, val);\
749 	return ret >= 0 ? count : ret;					\
750 }
751 
752 store_one(scaling_min_freq, min);
753 store_one(scaling_max_freq, max);
754 
755 /*
756  * show_cpuinfo_cur_freq - current CPU frequency as detected by hardware
757  */
show_cpuinfo_cur_freq(struct cpufreq_policy * policy,char * buf)758 static ssize_t show_cpuinfo_cur_freq(struct cpufreq_policy *policy,
759 					char *buf)
760 {
761 	unsigned int cur_freq = __cpufreq_get(policy);
762 
763 	if (cur_freq)
764 		return sprintf(buf, "%u\n", cur_freq);
765 
766 	return sprintf(buf, "<unknown>\n");
767 }
768 
769 /*
770  * show_scaling_governor - show the current policy for the specified CPU
771  */
show_scaling_governor(struct cpufreq_policy * policy,char * buf)772 static ssize_t show_scaling_governor(struct cpufreq_policy *policy, char *buf)
773 {
774 	if (policy->policy == CPUFREQ_POLICY_POWERSAVE)
775 		return sprintf(buf, "powersave\n");
776 	else if (policy->policy == CPUFREQ_POLICY_PERFORMANCE)
777 		return sprintf(buf, "performance\n");
778 	else if (policy->governor)
779 		return scnprintf(buf, CPUFREQ_NAME_PLEN, "%s\n",
780 				policy->governor->name);
781 	return -EINVAL;
782 }
783 
784 /*
785  * store_scaling_governor - store policy for the specified CPU
786  */
store_scaling_governor(struct cpufreq_policy * policy,const char * buf,size_t count)787 static ssize_t store_scaling_governor(struct cpufreq_policy *policy,
788 					const char *buf, size_t count)
789 {
790 	char str_governor[16];
791 	int ret;
792 
793 	ret = sscanf(buf, "%15s", str_governor);
794 	if (ret != 1)
795 		return -EINVAL;
796 
797 	if (cpufreq_driver->setpolicy) {
798 		unsigned int new_pol;
799 
800 		new_pol = cpufreq_parse_policy(str_governor);
801 		if (!new_pol)
802 			return -EINVAL;
803 
804 		ret = cpufreq_set_policy(policy, NULL, new_pol);
805 	} else {
806 		struct cpufreq_governor *new_gov;
807 
808 		new_gov = cpufreq_parse_governor(str_governor);
809 		if (!new_gov)
810 			return -EINVAL;
811 
812 		ret = cpufreq_set_policy(policy, new_gov,
813 					 CPUFREQ_POLICY_UNKNOWN);
814 
815 		module_put(new_gov->owner);
816 	}
817 
818 	return ret ? ret : count;
819 }
820 
821 /*
822  * show_scaling_driver - show the cpufreq driver currently loaded
823  */
show_scaling_driver(struct cpufreq_policy * policy,char * buf)824 static ssize_t show_scaling_driver(struct cpufreq_policy *policy, char *buf)
825 {
826 	return scnprintf(buf, CPUFREQ_NAME_PLEN, "%s\n", cpufreq_driver->name);
827 }
828 
829 /*
830  * show_scaling_available_governors - show the available CPUfreq governors
831  */
show_scaling_available_governors(struct cpufreq_policy * policy,char * buf)832 static ssize_t show_scaling_available_governors(struct cpufreq_policy *policy,
833 						char *buf)
834 {
835 	ssize_t i = 0;
836 	struct cpufreq_governor *t;
837 
838 	if (!has_target()) {
839 		i += sprintf(buf, "performance powersave");
840 		goto out;
841 	}
842 
843 	mutex_lock(&cpufreq_governor_mutex);
844 	for_each_governor(t) {
845 		if (i >= (ssize_t) ((PAGE_SIZE / sizeof(char))
846 		    - (CPUFREQ_NAME_LEN + 2)))
847 			break;
848 		i += scnprintf(&buf[i], CPUFREQ_NAME_PLEN, "%s ", t->name);
849 	}
850 	mutex_unlock(&cpufreq_governor_mutex);
851 out:
852 	i += sprintf(&buf[i], "\n");
853 	return i;
854 }
855 
cpufreq_show_cpus(const struct cpumask * mask,char * buf)856 ssize_t cpufreq_show_cpus(const struct cpumask *mask, char *buf)
857 {
858 	ssize_t i = 0;
859 	unsigned int cpu;
860 
861 	for_each_cpu(cpu, mask) {
862 		if (i)
863 			i += scnprintf(&buf[i], (PAGE_SIZE - i - 2), " ");
864 		i += scnprintf(&buf[i], (PAGE_SIZE - i - 2), "%u", cpu);
865 		if (i >= (PAGE_SIZE - 5))
866 			break;
867 	}
868 	i += sprintf(&buf[i], "\n");
869 	return i;
870 }
871 EXPORT_SYMBOL_GPL(cpufreq_show_cpus);
872 
873 /*
874  * show_related_cpus - show the CPUs affected by each transition even if
875  * hw coordination is in use
876  */
show_related_cpus(struct cpufreq_policy * policy,char * buf)877 static ssize_t show_related_cpus(struct cpufreq_policy *policy, char *buf)
878 {
879 	return cpufreq_show_cpus(policy->related_cpus, buf);
880 }
881 
882 /*
883  * show_affected_cpus - show the CPUs affected by each transition
884  */
show_affected_cpus(struct cpufreq_policy * policy,char * buf)885 static ssize_t show_affected_cpus(struct cpufreq_policy *policy, char *buf)
886 {
887 	return cpufreq_show_cpus(policy->cpus, buf);
888 }
889 
store_scaling_setspeed(struct cpufreq_policy * policy,const char * buf,size_t count)890 static ssize_t store_scaling_setspeed(struct cpufreq_policy *policy,
891 					const char *buf, size_t count)
892 {
893 	unsigned int freq = 0;
894 	unsigned int ret;
895 
896 	if (!policy->governor || !policy->governor->store_setspeed)
897 		return -EINVAL;
898 
899 	ret = sscanf(buf, "%u", &freq);
900 	if (ret != 1)
901 		return -EINVAL;
902 
903 	policy->governor->store_setspeed(policy, freq);
904 
905 	return count;
906 }
907 
show_scaling_setspeed(struct cpufreq_policy * policy,char * buf)908 static ssize_t show_scaling_setspeed(struct cpufreq_policy *policy, char *buf)
909 {
910 	if (!policy->governor || !policy->governor->show_setspeed)
911 		return sprintf(buf, "<unsupported>\n");
912 
913 	return policy->governor->show_setspeed(policy, buf);
914 }
915 
916 /*
917  * show_bios_limit - show the current cpufreq HW/BIOS limitation
918  */
show_bios_limit(struct cpufreq_policy * policy,char * buf)919 static ssize_t show_bios_limit(struct cpufreq_policy *policy, char *buf)
920 {
921 	unsigned int limit;
922 	int ret;
923 	ret = cpufreq_driver->bios_limit(policy->cpu, &limit);
924 	if (!ret)
925 		return sprintf(buf, "%u\n", limit);
926 	return sprintf(buf, "%u\n", policy->cpuinfo.max_freq);
927 }
928 
929 cpufreq_freq_attr_ro_perm(cpuinfo_cur_freq, 0400);
930 cpufreq_freq_attr_ro(cpuinfo_min_freq);
931 cpufreq_freq_attr_ro(cpuinfo_max_freq);
932 cpufreq_freq_attr_ro(cpuinfo_transition_latency);
933 cpufreq_freq_attr_ro(scaling_available_governors);
934 cpufreq_freq_attr_ro(scaling_driver);
935 cpufreq_freq_attr_ro(scaling_cur_freq);
936 cpufreq_freq_attr_ro(bios_limit);
937 cpufreq_freq_attr_ro(related_cpus);
938 cpufreq_freq_attr_ro(affected_cpus);
939 cpufreq_freq_attr_rw(scaling_min_freq);
940 cpufreq_freq_attr_rw(scaling_max_freq);
941 cpufreq_freq_attr_rw(scaling_governor);
942 cpufreq_freq_attr_rw(scaling_setspeed);
943 
944 static struct attribute *default_attrs[] = {
945 	&cpuinfo_min_freq.attr,
946 	&cpuinfo_max_freq.attr,
947 	&cpuinfo_transition_latency.attr,
948 	&scaling_min_freq.attr,
949 	&scaling_max_freq.attr,
950 	&affected_cpus.attr,
951 	&related_cpus.attr,
952 	&scaling_governor.attr,
953 	&scaling_driver.attr,
954 	&scaling_available_governors.attr,
955 	&scaling_setspeed.attr,
956 	NULL
957 };
958 
959 #define to_policy(k) container_of(k, struct cpufreq_policy, kobj)
960 #define to_attr(a) container_of(a, struct freq_attr, attr)
961 
show(struct kobject * kobj,struct attribute * attr,char * buf)962 static ssize_t show(struct kobject *kobj, struct attribute *attr, char *buf)
963 {
964 	struct cpufreq_policy *policy = to_policy(kobj);
965 	struct freq_attr *fattr = to_attr(attr);
966 	ssize_t ret;
967 
968 	if (!fattr->show)
969 		return -EIO;
970 
971 	down_read(&policy->rwsem);
972 	ret = fattr->show(policy, buf);
973 	up_read(&policy->rwsem);
974 
975 	return ret;
976 }
977 
store(struct kobject * kobj,struct attribute * attr,const char * buf,size_t count)978 static ssize_t store(struct kobject *kobj, struct attribute *attr,
979 		     const char *buf, size_t count)
980 {
981 	struct cpufreq_policy *policy = to_policy(kobj);
982 	struct freq_attr *fattr = to_attr(attr);
983 	ssize_t ret = -EINVAL;
984 
985 	if (!fattr->store)
986 		return -EIO;
987 
988 	/*
989 	 * cpus_read_trylock() is used here to work around a circular lock
990 	 * dependency problem with respect to the cpufreq_register_driver().
991 	 */
992 	if (!cpus_read_trylock())
993 		return -EBUSY;
994 
995 	if (cpu_online(policy->cpu)) {
996 		down_write(&policy->rwsem);
997 		ret = fattr->store(policy, buf, count);
998 		up_write(&policy->rwsem);
999 	}
1000 
1001 	cpus_read_unlock();
1002 
1003 	return ret;
1004 }
1005 
cpufreq_sysfs_release(struct kobject * kobj)1006 static void cpufreq_sysfs_release(struct kobject *kobj)
1007 {
1008 	struct cpufreq_policy *policy = to_policy(kobj);
1009 	pr_debug("last reference is dropped\n");
1010 	complete(&policy->kobj_unregister);
1011 }
1012 
1013 static const struct sysfs_ops sysfs_ops = {
1014 	.show	= show,
1015 	.store	= store,
1016 };
1017 
1018 static struct kobj_type ktype_cpufreq = {
1019 	.sysfs_ops	= &sysfs_ops,
1020 	.default_attrs	= default_attrs,
1021 	.release	= cpufreq_sysfs_release,
1022 };
1023 
add_cpu_dev_symlink(struct cpufreq_policy * policy,unsigned int cpu,struct device * dev)1024 static void add_cpu_dev_symlink(struct cpufreq_policy *policy, unsigned int cpu,
1025 				struct device *dev)
1026 {
1027 	if (unlikely(!dev))
1028 		return;
1029 
1030 	if (cpumask_test_and_set_cpu(cpu, policy->real_cpus))
1031 		return;
1032 
1033 	dev_dbg(dev, "%s: Adding symlink\n", __func__);
1034 	if (sysfs_create_link(&dev->kobj, &policy->kobj, "cpufreq"))
1035 		dev_err(dev, "cpufreq symlink creation failed\n");
1036 }
1037 
remove_cpu_dev_symlink(struct cpufreq_policy * policy,struct device * dev)1038 static void remove_cpu_dev_symlink(struct cpufreq_policy *policy,
1039 				   struct device *dev)
1040 {
1041 	dev_dbg(dev, "%s: Removing symlink\n", __func__);
1042 	sysfs_remove_link(&dev->kobj, "cpufreq");
1043 }
1044 
cpufreq_add_dev_interface(struct cpufreq_policy * policy)1045 static int cpufreq_add_dev_interface(struct cpufreq_policy *policy)
1046 {
1047 	struct freq_attr **drv_attr;
1048 	int ret = 0;
1049 
1050 	/* set up files for this cpu device */
1051 	drv_attr = cpufreq_driver->attr;
1052 	while (drv_attr && *drv_attr) {
1053 		ret = sysfs_create_file(&policy->kobj, &((*drv_attr)->attr));
1054 		if (ret)
1055 			return ret;
1056 		drv_attr++;
1057 	}
1058 	if (cpufreq_driver->get) {
1059 		ret = sysfs_create_file(&policy->kobj, &cpuinfo_cur_freq.attr);
1060 		if (ret)
1061 			return ret;
1062 	}
1063 
1064 	ret = sysfs_create_file(&policy->kobj, &scaling_cur_freq.attr);
1065 	if (ret)
1066 		return ret;
1067 
1068 	if (cpufreq_driver->bios_limit) {
1069 		ret = sysfs_create_file(&policy->kobj, &bios_limit.attr);
1070 		if (ret)
1071 			return ret;
1072 	}
1073 
1074 	return 0;
1075 }
1076 
cpufreq_init_policy(struct cpufreq_policy * policy)1077 static int cpufreq_init_policy(struct cpufreq_policy *policy)
1078 {
1079 	struct cpufreq_governor *gov = NULL;
1080 	unsigned int pol = CPUFREQ_POLICY_UNKNOWN;
1081 	int ret;
1082 
1083 	if (has_target()) {
1084 		/* Update policy governor to the one used before hotplug. */
1085 		gov = get_governor(policy->last_governor);
1086 		if (gov) {
1087 			pr_debug("Restoring governor %s for cpu %d\n",
1088 				 gov->name, policy->cpu);
1089 		} else {
1090 			gov = get_governor(default_governor);
1091 		}
1092 
1093 		if (!gov) {
1094 			gov = cpufreq_default_governor();
1095 			__module_get(gov->owner);
1096 		}
1097 
1098 	} else {
1099 
1100 		/* Use the default policy if there is no last_policy. */
1101 		if (policy->last_policy) {
1102 			pol = policy->last_policy;
1103 		} else {
1104 			pol = cpufreq_parse_policy(default_governor);
1105 			/*
1106 			 * In case the default governor is neither "performance"
1107 			 * nor "powersave", fall back to the initial policy
1108 			 * value set by the driver.
1109 			 */
1110 			if (pol == CPUFREQ_POLICY_UNKNOWN)
1111 				pol = policy->policy;
1112 		}
1113 		if (pol != CPUFREQ_POLICY_PERFORMANCE &&
1114 		    pol != CPUFREQ_POLICY_POWERSAVE)
1115 			return -ENODATA;
1116 	}
1117 
1118 	ret = cpufreq_set_policy(policy, gov, pol);
1119 	if (gov)
1120 		module_put(gov->owner);
1121 
1122 	return ret;
1123 }
1124 
cpufreq_add_policy_cpu(struct cpufreq_policy * policy,unsigned int cpu)1125 static int cpufreq_add_policy_cpu(struct cpufreq_policy *policy, unsigned int cpu)
1126 {
1127 	int ret = 0;
1128 
1129 	/* Has this CPU been taken care of already? */
1130 	if (cpumask_test_cpu(cpu, policy->cpus))
1131 		return 0;
1132 
1133 	down_write(&policy->rwsem);
1134 	if (has_target())
1135 		cpufreq_stop_governor(policy);
1136 
1137 	cpumask_set_cpu(cpu, policy->cpus);
1138 
1139 	if (has_target()) {
1140 		ret = cpufreq_start_governor(policy);
1141 		if (ret)
1142 			pr_err("%s: Failed to start governor\n", __func__);
1143 	}
1144 	up_write(&policy->rwsem);
1145 	return ret;
1146 }
1147 
refresh_frequency_limits(struct cpufreq_policy * policy)1148 void refresh_frequency_limits(struct cpufreq_policy *policy)
1149 {
1150 	if (!policy_is_inactive(policy)) {
1151 		pr_debug("updating policy for CPU %u\n", policy->cpu);
1152 
1153 		cpufreq_set_policy(policy, policy->governor, policy->policy);
1154 	}
1155 }
1156 EXPORT_SYMBOL(refresh_frequency_limits);
1157 
handle_update(struct work_struct * work)1158 static void handle_update(struct work_struct *work)
1159 {
1160 	struct cpufreq_policy *policy =
1161 		container_of(work, struct cpufreq_policy, update);
1162 
1163 	pr_debug("handle_update for cpu %u called\n", policy->cpu);
1164 	down_write(&policy->rwsem);
1165 	refresh_frequency_limits(policy);
1166 	up_write(&policy->rwsem);
1167 }
1168 
cpufreq_notifier_min(struct notifier_block * nb,unsigned long freq,void * data)1169 static int cpufreq_notifier_min(struct notifier_block *nb, unsigned long freq,
1170 				void *data)
1171 {
1172 	struct cpufreq_policy *policy = container_of(nb, struct cpufreq_policy, nb_min);
1173 
1174 	schedule_work(&policy->update);
1175 	return 0;
1176 }
1177 
cpufreq_notifier_max(struct notifier_block * nb,unsigned long freq,void * data)1178 static int cpufreq_notifier_max(struct notifier_block *nb, unsigned long freq,
1179 				void *data)
1180 {
1181 	struct cpufreq_policy *policy = container_of(nb, struct cpufreq_policy, nb_max);
1182 
1183 	schedule_work(&policy->update);
1184 	return 0;
1185 }
1186 
cpufreq_policy_put_kobj(struct cpufreq_policy * policy)1187 static void cpufreq_policy_put_kobj(struct cpufreq_policy *policy)
1188 {
1189 	struct kobject *kobj;
1190 	struct completion *cmp;
1191 
1192 	down_write(&policy->rwsem);
1193 	cpufreq_stats_free_table(policy);
1194 	kobj = &policy->kobj;
1195 	cmp = &policy->kobj_unregister;
1196 	up_write(&policy->rwsem);
1197 	kobject_put(kobj);
1198 
1199 	/*
1200 	 * We need to make sure that the underlying kobj is
1201 	 * actually not referenced anymore by anybody before we
1202 	 * proceed with unloading.
1203 	 */
1204 	pr_debug("waiting for dropping of refcount\n");
1205 	wait_for_completion(cmp);
1206 	pr_debug("wait complete\n");
1207 }
1208 
cpufreq_policy_alloc(unsigned int cpu)1209 static struct cpufreq_policy *cpufreq_policy_alloc(unsigned int cpu)
1210 {
1211 	struct cpufreq_policy *policy;
1212 	struct device *dev = get_cpu_device(cpu);
1213 	int ret;
1214 
1215 	if (!dev)
1216 		return NULL;
1217 
1218 	policy = kzalloc(sizeof(*policy), GFP_KERNEL);
1219 	if (!policy)
1220 		return NULL;
1221 
1222 	if (!alloc_cpumask_var(&policy->cpus, GFP_KERNEL))
1223 		goto err_free_policy;
1224 
1225 	if (!zalloc_cpumask_var(&policy->related_cpus, GFP_KERNEL))
1226 		goto err_free_cpumask;
1227 
1228 	if (!zalloc_cpumask_var(&policy->real_cpus, GFP_KERNEL))
1229 		goto err_free_rcpumask;
1230 
1231 	init_completion(&policy->kobj_unregister);
1232 	ret = kobject_init_and_add(&policy->kobj, &ktype_cpufreq,
1233 				   cpufreq_global_kobject, "policy%u", cpu);
1234 	if (ret) {
1235 		dev_err(dev, "%s: failed to init policy->kobj: %d\n", __func__, ret);
1236 		/*
1237 		 * The entire policy object will be freed below, but the extra
1238 		 * memory allocated for the kobject name needs to be freed by
1239 		 * releasing the kobject.
1240 		 */
1241 		kobject_put(&policy->kobj);
1242 		goto err_free_real_cpus;
1243 	}
1244 
1245 	freq_constraints_init(&policy->constraints);
1246 
1247 	policy->nb_min.notifier_call = cpufreq_notifier_min;
1248 	policy->nb_max.notifier_call = cpufreq_notifier_max;
1249 
1250 	ret = freq_qos_add_notifier(&policy->constraints, FREQ_QOS_MIN,
1251 				    &policy->nb_min);
1252 	if (ret) {
1253 		dev_err(dev, "Failed to register MIN QoS notifier: %d (%*pbl)\n",
1254 			ret, cpumask_pr_args(policy->cpus));
1255 		goto err_kobj_remove;
1256 	}
1257 
1258 	ret = freq_qos_add_notifier(&policy->constraints, FREQ_QOS_MAX,
1259 				    &policy->nb_max);
1260 	if (ret) {
1261 		dev_err(dev, "Failed to register MAX QoS notifier: %d (%*pbl)\n",
1262 			ret, cpumask_pr_args(policy->cpus));
1263 		goto err_min_qos_notifier;
1264 	}
1265 
1266 	INIT_LIST_HEAD(&policy->policy_list);
1267 	init_rwsem(&policy->rwsem);
1268 	spin_lock_init(&policy->transition_lock);
1269 	init_waitqueue_head(&policy->transition_wait);
1270 	INIT_WORK(&policy->update, handle_update);
1271 
1272 	policy->cpu = cpu;
1273 	return policy;
1274 
1275 err_min_qos_notifier:
1276 	freq_qos_remove_notifier(&policy->constraints, FREQ_QOS_MIN,
1277 				 &policy->nb_min);
1278 err_kobj_remove:
1279 	cpufreq_policy_put_kobj(policy);
1280 err_free_real_cpus:
1281 	free_cpumask_var(policy->real_cpus);
1282 err_free_rcpumask:
1283 	free_cpumask_var(policy->related_cpus);
1284 err_free_cpumask:
1285 	free_cpumask_var(policy->cpus);
1286 err_free_policy:
1287 	kfree(policy);
1288 
1289 	return NULL;
1290 }
1291 
cpufreq_policy_free(struct cpufreq_policy * policy)1292 static void cpufreq_policy_free(struct cpufreq_policy *policy)
1293 {
1294 	unsigned long flags;
1295 	int cpu;
1296 
1297 	/* Remove policy from list */
1298 	write_lock_irqsave(&cpufreq_driver_lock, flags);
1299 	list_del(&policy->policy_list);
1300 
1301 	for_each_cpu(cpu, policy->related_cpus)
1302 		per_cpu(cpufreq_cpu_data, cpu) = NULL;
1303 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
1304 
1305 	freq_qos_remove_notifier(&policy->constraints, FREQ_QOS_MAX,
1306 				 &policy->nb_max);
1307 	freq_qos_remove_notifier(&policy->constraints, FREQ_QOS_MIN,
1308 				 &policy->nb_min);
1309 
1310 	/* Cancel any pending policy->update work before freeing the policy. */
1311 	cancel_work_sync(&policy->update);
1312 
1313 	if (policy->max_freq_req) {
1314 		/*
1315 		 * CPUFREQ_CREATE_POLICY notification is sent only after
1316 		 * successfully adding max_freq_req request.
1317 		 */
1318 		blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
1319 					     CPUFREQ_REMOVE_POLICY, policy);
1320 		freq_qos_remove_request(policy->max_freq_req);
1321 	}
1322 
1323 	freq_qos_remove_request(policy->min_freq_req);
1324 	kfree(policy->min_freq_req);
1325 
1326 	cpufreq_policy_put_kobj(policy);
1327 	free_cpumask_var(policy->real_cpus);
1328 	free_cpumask_var(policy->related_cpus);
1329 	free_cpumask_var(policy->cpus);
1330 	kfree(policy);
1331 }
1332 
cpufreq_online(unsigned int cpu)1333 static int cpufreq_online(unsigned int cpu)
1334 {
1335 	struct cpufreq_policy *policy;
1336 	bool new_policy;
1337 	unsigned long flags;
1338 	unsigned int j;
1339 	int ret;
1340 
1341 	pr_debug("%s: bringing CPU%u online\n", __func__, cpu);
1342 
1343 	/* Check if this CPU already has a policy to manage it */
1344 	policy = per_cpu(cpufreq_cpu_data, cpu);
1345 	if (policy) {
1346 		WARN_ON(!cpumask_test_cpu(cpu, policy->related_cpus));
1347 		if (!policy_is_inactive(policy))
1348 			return cpufreq_add_policy_cpu(policy, cpu);
1349 
1350 		/* This is the only online CPU for the policy.  Start over. */
1351 		new_policy = false;
1352 		down_write(&policy->rwsem);
1353 		policy->cpu = cpu;
1354 		policy->governor = NULL;
1355 		up_write(&policy->rwsem);
1356 	} else {
1357 		new_policy = true;
1358 		policy = cpufreq_policy_alloc(cpu);
1359 		if (!policy)
1360 			return -ENOMEM;
1361 	}
1362 
1363 	if (!new_policy && cpufreq_driver->online) {
1364 		ret = cpufreq_driver->online(policy);
1365 		if (ret) {
1366 			pr_debug("%s: %d: initialization failed\n", __func__,
1367 				 __LINE__);
1368 			goto out_exit_policy;
1369 		}
1370 
1371 		/* Recover policy->cpus using related_cpus */
1372 		cpumask_copy(policy->cpus, policy->related_cpus);
1373 	} else {
1374 		cpumask_copy(policy->cpus, cpumask_of(cpu));
1375 
1376 		/*
1377 		 * Call driver. From then on the cpufreq must be able
1378 		 * to accept all calls to ->verify and ->setpolicy for this CPU.
1379 		 */
1380 		ret = cpufreq_driver->init(policy);
1381 		if (ret) {
1382 			pr_debug("%s: %d: initialization failed\n", __func__,
1383 				 __LINE__);
1384 			goto out_free_policy;
1385 		}
1386 
1387 		/*
1388 		 * The initialization has succeeded and the policy is online.
1389 		 * If there is a problem with its frequency table, take it
1390 		 * offline and drop it.
1391 		 */
1392 		ret = cpufreq_table_validate_and_sort(policy);
1393 		if (ret)
1394 			goto out_offline_policy;
1395 
1396 		/* related_cpus should at least include policy->cpus. */
1397 		cpumask_copy(policy->related_cpus, policy->cpus);
1398 	}
1399 
1400 	down_write(&policy->rwsem);
1401 	/*
1402 	 * affected cpus must always be the one, which are online. We aren't
1403 	 * managing offline cpus here.
1404 	 */
1405 	cpumask_and(policy->cpus, policy->cpus, cpu_online_mask);
1406 
1407 	if (new_policy) {
1408 		for_each_cpu(j, policy->related_cpus) {
1409 			per_cpu(cpufreq_cpu_data, j) = policy;
1410 			add_cpu_dev_symlink(policy, j, get_cpu_device(j));
1411 		}
1412 
1413 		policy->min_freq_req = kzalloc(2 * sizeof(*policy->min_freq_req),
1414 					       GFP_KERNEL);
1415 		if (!policy->min_freq_req)
1416 			goto out_destroy_policy;
1417 
1418 		ret = freq_qos_add_request(&policy->constraints,
1419 					   policy->min_freq_req, FREQ_QOS_MIN,
1420 					   FREQ_QOS_MIN_DEFAULT_VALUE);
1421 		if (ret < 0) {
1422 			/*
1423 			 * So we don't call freq_qos_remove_request() for an
1424 			 * uninitialized request.
1425 			 */
1426 			kfree(policy->min_freq_req);
1427 			policy->min_freq_req = NULL;
1428 			goto out_destroy_policy;
1429 		}
1430 
1431 		/*
1432 		 * This must be initialized right here to avoid calling
1433 		 * freq_qos_remove_request() on uninitialized request in case
1434 		 * of errors.
1435 		 */
1436 		policy->max_freq_req = policy->min_freq_req + 1;
1437 
1438 		ret = freq_qos_add_request(&policy->constraints,
1439 					   policy->max_freq_req, FREQ_QOS_MAX,
1440 					   FREQ_QOS_MAX_DEFAULT_VALUE);
1441 		if (ret < 0) {
1442 			policy->max_freq_req = NULL;
1443 			goto out_destroy_policy;
1444 		}
1445 
1446 		blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
1447 				CPUFREQ_CREATE_POLICY, policy);
1448 	}
1449 
1450 	if (cpufreq_driver->get && has_target()) {
1451 		policy->cur = cpufreq_driver->get(policy->cpu);
1452 		if (!policy->cur) {
1453 			pr_err("%s: ->get() failed\n", __func__);
1454 			goto out_destroy_policy;
1455 		}
1456 	}
1457 
1458 	/*
1459 	 * Sometimes boot loaders set CPU frequency to a value outside of
1460 	 * frequency table present with cpufreq core. In such cases CPU might be
1461 	 * unstable if it has to run on that frequency for long duration of time
1462 	 * and so its better to set it to a frequency which is specified in
1463 	 * freq-table. This also makes cpufreq stats inconsistent as
1464 	 * cpufreq-stats would fail to register because current frequency of CPU
1465 	 * isn't found in freq-table.
1466 	 *
1467 	 * Because we don't want this change to effect boot process badly, we go
1468 	 * for the next freq which is >= policy->cur ('cur' must be set by now,
1469 	 * otherwise we will end up setting freq to lowest of the table as 'cur'
1470 	 * is initialized to zero).
1471 	 *
1472 	 * We are passing target-freq as "policy->cur - 1" otherwise
1473 	 * __cpufreq_driver_target() would simply fail, as policy->cur will be
1474 	 * equal to target-freq.
1475 	 */
1476 	if ((cpufreq_driver->flags & CPUFREQ_NEED_INITIAL_FREQ_CHECK)
1477 	    && has_target()) {
1478 		unsigned int old_freq = policy->cur;
1479 
1480 		/* Are we running at unknown frequency ? */
1481 		ret = cpufreq_frequency_table_get_index(policy, old_freq);
1482 		if (ret == -EINVAL) {
1483 			ret = __cpufreq_driver_target(policy, old_freq - 1,
1484 						      CPUFREQ_RELATION_L);
1485 
1486 			/*
1487 			 * Reaching here after boot in a few seconds may not
1488 			 * mean that system will remain stable at "unknown"
1489 			 * frequency for longer duration. Hence, a BUG_ON().
1490 			 */
1491 			BUG_ON(ret);
1492 			pr_info("%s: CPU%d: Running at unlisted initial frequency: %u KHz, changing to: %u KHz\n",
1493 				__func__, policy->cpu, old_freq, policy->cur);
1494 		}
1495 	}
1496 
1497 	if (new_policy) {
1498 		ret = cpufreq_add_dev_interface(policy);
1499 		if (ret)
1500 			goto out_destroy_policy;
1501 
1502 		cpufreq_stats_create_table(policy);
1503 		cpufreq_times_create_policy(policy);
1504 
1505 		write_lock_irqsave(&cpufreq_driver_lock, flags);
1506 		list_add(&policy->policy_list, &cpufreq_policy_list);
1507 		write_unlock_irqrestore(&cpufreq_driver_lock, flags);
1508 	}
1509 
1510 	ret = cpufreq_init_policy(policy);
1511 	if (ret) {
1512 		pr_err("%s: Failed to initialize policy for cpu: %d (%d)\n",
1513 		       __func__, cpu, ret);
1514 		goto out_destroy_policy;
1515 	}
1516 
1517 	up_write(&policy->rwsem);
1518 
1519 	kobject_uevent(&policy->kobj, KOBJ_ADD);
1520 
1521 	/* Callback for handling stuff after policy is ready */
1522 	if (cpufreq_driver->ready)
1523 		cpufreq_driver->ready(policy);
1524 
1525 	if (cpufreq_thermal_control_enabled(cpufreq_driver))
1526 		policy->cdev = of_cpufreq_cooling_register(policy);
1527 
1528 	pr_debug("initialization complete\n");
1529 
1530 	return 0;
1531 
1532 out_destroy_policy:
1533 	for_each_cpu(j, policy->real_cpus)
1534 		remove_cpu_dev_symlink(policy, get_cpu_device(j));
1535 
1536 	up_write(&policy->rwsem);
1537 
1538 out_offline_policy:
1539 	if (cpufreq_driver->offline)
1540 		cpufreq_driver->offline(policy);
1541 
1542 out_exit_policy:
1543 	if (cpufreq_driver->exit)
1544 		cpufreq_driver->exit(policy);
1545 
1546 out_free_policy:
1547 	cpufreq_policy_free(policy);
1548 	return ret;
1549 }
1550 
1551 /**
1552  * cpufreq_add_dev - the cpufreq interface for a CPU device.
1553  * @dev: CPU device.
1554  * @sif: Subsystem interface structure pointer (not used)
1555  */
cpufreq_add_dev(struct device * dev,struct subsys_interface * sif)1556 static int cpufreq_add_dev(struct device *dev, struct subsys_interface *sif)
1557 {
1558 	struct cpufreq_policy *policy;
1559 	unsigned cpu = dev->id;
1560 	int ret;
1561 
1562 	dev_dbg(dev, "%s: adding CPU%u\n", __func__, cpu);
1563 
1564 	if (cpu_online(cpu)) {
1565 		ret = cpufreq_online(cpu);
1566 		if (ret)
1567 			return ret;
1568 	}
1569 
1570 	/* Create sysfs link on CPU registration */
1571 	policy = per_cpu(cpufreq_cpu_data, cpu);
1572 	if (policy)
1573 		add_cpu_dev_symlink(policy, cpu, dev);
1574 
1575 	return 0;
1576 }
1577 
cpufreq_offline(unsigned int cpu)1578 static int cpufreq_offline(unsigned int cpu)
1579 {
1580 	struct cpufreq_policy *policy;
1581 	int ret;
1582 
1583 	pr_debug("%s: unregistering CPU %u\n", __func__, cpu);
1584 
1585 	policy = cpufreq_cpu_get_raw(cpu);
1586 	if (!policy) {
1587 		pr_debug("%s: No cpu_data found\n", __func__);
1588 		return 0;
1589 	}
1590 
1591 	down_write(&policy->rwsem);
1592 	if (has_target())
1593 		cpufreq_stop_governor(policy);
1594 
1595 	cpumask_clear_cpu(cpu, policy->cpus);
1596 
1597 	if (policy_is_inactive(policy)) {
1598 		if (has_target())
1599 			strncpy(policy->last_governor, policy->governor->name,
1600 				CPUFREQ_NAME_LEN);
1601 		else
1602 			policy->last_policy = policy->policy;
1603 	} else if (cpu == policy->cpu) {
1604 		/* Nominate new CPU */
1605 		policy->cpu = cpumask_any(policy->cpus);
1606 	}
1607 
1608 	/* Start governor again for active policy */
1609 	if (!policy_is_inactive(policy)) {
1610 		if (has_target()) {
1611 			ret = cpufreq_start_governor(policy);
1612 			if (ret)
1613 				pr_err("%s: Failed to start governor\n", __func__);
1614 		}
1615 
1616 		goto unlock;
1617 	}
1618 
1619 	if (cpufreq_thermal_control_enabled(cpufreq_driver)) {
1620 		cpufreq_cooling_unregister(policy->cdev);
1621 		policy->cdev = NULL;
1622 	}
1623 
1624 	if (cpufreq_driver->stop_cpu)
1625 		cpufreq_driver->stop_cpu(policy);
1626 
1627 	if (has_target())
1628 		cpufreq_exit_governor(policy);
1629 
1630 	/*
1631 	 * Perform the ->offline() during light-weight tear-down, as
1632 	 * that allows fast recovery when the CPU comes back.
1633 	 */
1634 	if (cpufreq_driver->offline) {
1635 		cpufreq_driver->offline(policy);
1636 	} else if (cpufreq_driver->exit) {
1637 		cpufreq_driver->exit(policy);
1638 		policy->freq_table = NULL;
1639 	}
1640 
1641 unlock:
1642 	up_write(&policy->rwsem);
1643 	return 0;
1644 }
1645 
1646 /*
1647  * cpufreq_remove_dev - remove a CPU device
1648  *
1649  * Removes the cpufreq interface for a CPU device.
1650  */
cpufreq_remove_dev(struct device * dev,struct subsys_interface * sif)1651 static void cpufreq_remove_dev(struct device *dev, struct subsys_interface *sif)
1652 {
1653 	unsigned int cpu = dev->id;
1654 	struct cpufreq_policy *policy = per_cpu(cpufreq_cpu_data, cpu);
1655 
1656 	if (!policy)
1657 		return;
1658 
1659 	if (cpu_online(cpu))
1660 		cpufreq_offline(cpu);
1661 
1662 	cpumask_clear_cpu(cpu, policy->real_cpus);
1663 	remove_cpu_dev_symlink(policy, dev);
1664 
1665 	if (cpumask_empty(policy->real_cpus)) {
1666 		/* We did light-weight exit earlier, do full tear down now */
1667 		if (cpufreq_driver->offline)
1668 			cpufreq_driver->exit(policy);
1669 
1670 		cpufreq_policy_free(policy);
1671 	}
1672 }
1673 
1674 /**
1675  *	cpufreq_out_of_sync - If actual and saved CPU frequency differs, we're
1676  *	in deep trouble.
1677  *	@policy: policy managing CPUs
1678  *	@new_freq: CPU frequency the CPU actually runs at
1679  *
1680  *	We adjust to current frequency first, and need to clean up later.
1681  *	So either call to cpufreq_update_policy() or schedule handle_update()).
1682  */
cpufreq_out_of_sync(struct cpufreq_policy * policy,unsigned int new_freq)1683 static void cpufreq_out_of_sync(struct cpufreq_policy *policy,
1684 				unsigned int new_freq)
1685 {
1686 	struct cpufreq_freqs freqs;
1687 
1688 	pr_debug("Warning: CPU frequency out of sync: cpufreq and timing core thinks of %u, is %u kHz\n",
1689 		 policy->cur, new_freq);
1690 
1691 	freqs.old = policy->cur;
1692 	freqs.new = new_freq;
1693 
1694 	cpufreq_freq_transition_begin(policy, &freqs);
1695 	cpufreq_freq_transition_end(policy, &freqs, 0);
1696 }
1697 
cpufreq_verify_current_freq(struct cpufreq_policy * policy,bool update)1698 static unsigned int cpufreq_verify_current_freq(struct cpufreq_policy *policy, bool update)
1699 {
1700 	unsigned int new_freq;
1701 
1702 	new_freq = cpufreq_driver->get(policy->cpu);
1703 	if (!new_freq)
1704 		return 0;
1705 
1706 	/*
1707 	 * If fast frequency switching is used with the given policy, the check
1708 	 * against policy->cur is pointless, so skip it in that case.
1709 	 */
1710 	if (policy->fast_switch_enabled || !has_target())
1711 		return new_freq;
1712 
1713 	if (policy->cur != new_freq) {
1714 		cpufreq_out_of_sync(policy, new_freq);
1715 		if (update)
1716 			schedule_work(&policy->update);
1717 	}
1718 
1719 	return new_freq;
1720 }
1721 
1722 /**
1723  * cpufreq_quick_get - get the CPU frequency (in kHz) from policy->cur
1724  * @cpu: CPU number
1725  *
1726  * This is the last known freq, without actually getting it from the driver.
1727  * Return value will be same as what is shown in scaling_cur_freq in sysfs.
1728  */
cpufreq_quick_get(unsigned int cpu)1729 unsigned int cpufreq_quick_get(unsigned int cpu)
1730 {
1731 	struct cpufreq_policy *policy;
1732 	unsigned int ret_freq = 0;
1733 	unsigned long flags;
1734 
1735 	read_lock_irqsave(&cpufreq_driver_lock, flags);
1736 
1737 	if (cpufreq_driver && cpufreq_driver->setpolicy && cpufreq_driver->get) {
1738 		ret_freq = cpufreq_driver->get(cpu);
1739 		read_unlock_irqrestore(&cpufreq_driver_lock, flags);
1740 		return ret_freq;
1741 	}
1742 
1743 	read_unlock_irqrestore(&cpufreq_driver_lock, flags);
1744 
1745 	policy = cpufreq_cpu_get(cpu);
1746 	if (policy) {
1747 		ret_freq = policy->cur;
1748 		cpufreq_cpu_put(policy);
1749 	}
1750 
1751 	return ret_freq;
1752 }
1753 EXPORT_SYMBOL(cpufreq_quick_get);
1754 
1755 /**
1756  * cpufreq_quick_get_max - get the max reported CPU frequency for this CPU
1757  * @cpu: CPU number
1758  *
1759  * Just return the max possible frequency for a given CPU.
1760  */
cpufreq_quick_get_max(unsigned int cpu)1761 unsigned int cpufreq_quick_get_max(unsigned int cpu)
1762 {
1763 	struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
1764 	unsigned int ret_freq = 0;
1765 
1766 	if (policy) {
1767 		ret_freq = policy->max;
1768 		cpufreq_cpu_put(policy);
1769 	}
1770 
1771 	return ret_freq;
1772 }
1773 EXPORT_SYMBOL(cpufreq_quick_get_max);
1774 
1775 /**
1776  * cpufreq_get_hw_max_freq - get the max hardware frequency of the CPU
1777  * @cpu: CPU number
1778  *
1779  * The default return value is the max_freq field of cpuinfo.
1780  */
cpufreq_get_hw_max_freq(unsigned int cpu)1781 __weak unsigned int cpufreq_get_hw_max_freq(unsigned int cpu)
1782 {
1783 	struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
1784 	unsigned int ret_freq = 0;
1785 
1786 	if (policy) {
1787 		ret_freq = policy->cpuinfo.max_freq;
1788 		cpufreq_cpu_put(policy);
1789 	}
1790 
1791 	return ret_freq;
1792 }
1793 EXPORT_SYMBOL(cpufreq_get_hw_max_freq);
1794 
__cpufreq_get(struct cpufreq_policy * policy)1795 static unsigned int __cpufreq_get(struct cpufreq_policy *policy)
1796 {
1797 	if (unlikely(policy_is_inactive(policy)))
1798 		return 0;
1799 
1800 	return cpufreq_verify_current_freq(policy, true);
1801 }
1802 
1803 /**
1804  * cpufreq_get - get the current CPU frequency (in kHz)
1805  * @cpu: CPU number
1806  *
1807  * Get the CPU current (static) CPU frequency
1808  */
cpufreq_get(unsigned int cpu)1809 unsigned int cpufreq_get(unsigned int cpu)
1810 {
1811 	struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
1812 	unsigned int ret_freq = 0;
1813 
1814 	if (policy) {
1815 		down_read(&policy->rwsem);
1816 		if (cpufreq_driver->get)
1817 			ret_freq = __cpufreq_get(policy);
1818 		up_read(&policy->rwsem);
1819 
1820 		cpufreq_cpu_put(policy);
1821 	}
1822 
1823 	return ret_freq;
1824 }
1825 EXPORT_SYMBOL(cpufreq_get);
1826 
1827 static struct subsys_interface cpufreq_interface = {
1828 	.name		= "cpufreq",
1829 	.subsys		= &cpu_subsys,
1830 	.add_dev	= cpufreq_add_dev,
1831 	.remove_dev	= cpufreq_remove_dev,
1832 };
1833 
1834 /*
1835  * In case platform wants some specific frequency to be configured
1836  * during suspend..
1837  */
cpufreq_generic_suspend(struct cpufreq_policy * policy)1838 int cpufreq_generic_suspend(struct cpufreq_policy *policy)
1839 {
1840 	int ret;
1841 
1842 	if (!policy->suspend_freq) {
1843 		pr_debug("%s: suspend_freq not defined\n", __func__);
1844 		return 0;
1845 	}
1846 
1847 	pr_debug("%s: Setting suspend-freq: %u\n", __func__,
1848 			policy->suspend_freq);
1849 
1850 	ret = __cpufreq_driver_target(policy, policy->suspend_freq,
1851 			CPUFREQ_RELATION_H);
1852 	if (ret)
1853 		pr_err("%s: unable to set suspend-freq: %u. err: %d\n",
1854 				__func__, policy->suspend_freq, ret);
1855 
1856 	return ret;
1857 }
1858 EXPORT_SYMBOL(cpufreq_generic_suspend);
1859 
1860 /**
1861  * cpufreq_suspend() - Suspend CPUFreq governors
1862  *
1863  * Called during system wide Suspend/Hibernate cycles for suspending governors
1864  * as some platforms can't change frequency after this point in suspend cycle.
1865  * Because some of the devices (like: i2c, regulators, etc) they use for
1866  * changing frequency are suspended quickly after this point.
1867  */
cpufreq_suspend(void)1868 void cpufreq_suspend(void)
1869 {
1870 	struct cpufreq_policy *policy;
1871 
1872 	if (!cpufreq_driver)
1873 		return;
1874 
1875 	if (!has_target() && !cpufreq_driver->suspend)
1876 		goto suspend;
1877 
1878 	pr_debug("%s: Suspending Governors\n", __func__);
1879 
1880 	for_each_active_policy(policy) {
1881 		if (has_target()) {
1882 			down_write(&policy->rwsem);
1883 			cpufreq_stop_governor(policy);
1884 			up_write(&policy->rwsem);
1885 		}
1886 
1887 		if (cpufreq_driver->suspend && cpufreq_driver->suspend(policy))
1888 			pr_err("%s: Failed to suspend driver: %s\n", __func__,
1889 				cpufreq_driver->name);
1890 	}
1891 
1892 suspend:
1893 	cpufreq_suspended = true;
1894 }
1895 
1896 /**
1897  * cpufreq_resume() - Resume CPUFreq governors
1898  *
1899  * Called during system wide Suspend/Hibernate cycle for resuming governors that
1900  * are suspended with cpufreq_suspend().
1901  */
cpufreq_resume(void)1902 void cpufreq_resume(void)
1903 {
1904 	struct cpufreq_policy *policy;
1905 	int ret;
1906 
1907 	if (!cpufreq_driver)
1908 		return;
1909 
1910 	if (unlikely(!cpufreq_suspended))
1911 		return;
1912 
1913 	cpufreq_suspended = false;
1914 
1915 	if (!has_target() && !cpufreq_driver->resume)
1916 		return;
1917 
1918 	pr_debug("%s: Resuming Governors\n", __func__);
1919 
1920 	for_each_active_policy(policy) {
1921 		if (cpufreq_driver->resume && cpufreq_driver->resume(policy)) {
1922 			pr_err("%s: Failed to resume driver: %p\n", __func__,
1923 				policy);
1924 		} else if (has_target()) {
1925 			down_write(&policy->rwsem);
1926 			ret = cpufreq_start_governor(policy);
1927 			up_write(&policy->rwsem);
1928 
1929 			if (ret)
1930 				pr_err("%s: Failed to start governor for policy: %p\n",
1931 				       __func__, policy);
1932 		}
1933 	}
1934 }
1935 
1936 /**
1937  * cpufreq_driver_test_flags - Test cpufreq driver's flags against given ones.
1938  * @flags: Flags to test against the current cpufreq driver's flags.
1939  *
1940  * Assumes that the driver is there, so callers must ensure that this is the
1941  * case.
1942  */
cpufreq_driver_test_flags(u16 flags)1943 bool cpufreq_driver_test_flags(u16 flags)
1944 {
1945 	return !!(cpufreq_driver->flags & flags);
1946 }
1947 
1948 /**
1949  *	cpufreq_get_current_driver - return current driver's name
1950  *
1951  *	Return the name string of the currently loaded cpufreq driver
1952  *	or NULL, if none.
1953  */
cpufreq_get_current_driver(void)1954 const char *cpufreq_get_current_driver(void)
1955 {
1956 	if (cpufreq_driver)
1957 		return cpufreq_driver->name;
1958 
1959 	return NULL;
1960 }
1961 EXPORT_SYMBOL_GPL(cpufreq_get_current_driver);
1962 
1963 /**
1964  *	cpufreq_get_driver_data - return current driver data
1965  *
1966  *	Return the private data of the currently loaded cpufreq
1967  *	driver, or NULL if no cpufreq driver is loaded.
1968  */
cpufreq_get_driver_data(void)1969 void *cpufreq_get_driver_data(void)
1970 {
1971 	if (cpufreq_driver)
1972 		return cpufreq_driver->driver_data;
1973 
1974 	return NULL;
1975 }
1976 EXPORT_SYMBOL_GPL(cpufreq_get_driver_data);
1977 
1978 /*********************************************************************
1979  *                     NOTIFIER LISTS INTERFACE                      *
1980  *********************************************************************/
1981 
1982 /**
1983  *	cpufreq_register_notifier - register a driver with cpufreq
1984  *	@nb: notifier function to register
1985  *      @list: CPUFREQ_TRANSITION_NOTIFIER or CPUFREQ_POLICY_NOTIFIER
1986  *
1987  *	Add a driver to one of two lists: either a list of drivers that
1988  *      are notified about clock rate changes (once before and once after
1989  *      the transition), or a list of drivers that are notified about
1990  *      changes in cpufreq policy.
1991  *
1992  *	This function may sleep, and has the same return conditions as
1993  *	blocking_notifier_chain_register.
1994  */
cpufreq_register_notifier(struct notifier_block * nb,unsigned int list)1995 int cpufreq_register_notifier(struct notifier_block *nb, unsigned int list)
1996 {
1997 	int ret;
1998 
1999 	if (cpufreq_disabled())
2000 		return -EINVAL;
2001 
2002 	switch (list) {
2003 	case CPUFREQ_TRANSITION_NOTIFIER:
2004 		mutex_lock(&cpufreq_fast_switch_lock);
2005 
2006 		if (cpufreq_fast_switch_count > 0) {
2007 			mutex_unlock(&cpufreq_fast_switch_lock);
2008 			return -EBUSY;
2009 		}
2010 		ret = srcu_notifier_chain_register(
2011 				&cpufreq_transition_notifier_list, nb);
2012 		if (!ret)
2013 			cpufreq_fast_switch_count--;
2014 
2015 		mutex_unlock(&cpufreq_fast_switch_lock);
2016 		break;
2017 	case CPUFREQ_POLICY_NOTIFIER:
2018 		ret = blocking_notifier_chain_register(
2019 				&cpufreq_policy_notifier_list, nb);
2020 		break;
2021 	default:
2022 		ret = -EINVAL;
2023 	}
2024 
2025 	return ret;
2026 }
2027 EXPORT_SYMBOL(cpufreq_register_notifier);
2028 
2029 /**
2030  *	cpufreq_unregister_notifier - unregister a driver with cpufreq
2031  *	@nb: notifier block to be unregistered
2032  *	@list: CPUFREQ_TRANSITION_NOTIFIER or CPUFREQ_POLICY_NOTIFIER
2033  *
2034  *	Remove a driver from the CPU frequency notifier list.
2035  *
2036  *	This function may sleep, and has the same return conditions as
2037  *	blocking_notifier_chain_unregister.
2038  */
cpufreq_unregister_notifier(struct notifier_block * nb,unsigned int list)2039 int cpufreq_unregister_notifier(struct notifier_block *nb, unsigned int list)
2040 {
2041 	int ret;
2042 
2043 	if (cpufreq_disabled())
2044 		return -EINVAL;
2045 
2046 	switch (list) {
2047 	case CPUFREQ_TRANSITION_NOTIFIER:
2048 		mutex_lock(&cpufreq_fast_switch_lock);
2049 
2050 		ret = srcu_notifier_chain_unregister(
2051 				&cpufreq_transition_notifier_list, nb);
2052 		if (!ret && !WARN_ON(cpufreq_fast_switch_count >= 0))
2053 			cpufreq_fast_switch_count++;
2054 
2055 		mutex_unlock(&cpufreq_fast_switch_lock);
2056 		break;
2057 	case CPUFREQ_POLICY_NOTIFIER:
2058 		ret = blocking_notifier_chain_unregister(
2059 				&cpufreq_policy_notifier_list, nb);
2060 		break;
2061 	default:
2062 		ret = -EINVAL;
2063 	}
2064 
2065 	return ret;
2066 }
2067 EXPORT_SYMBOL(cpufreq_unregister_notifier);
2068 
2069 
2070 /*********************************************************************
2071  *                              GOVERNORS                            *
2072  *********************************************************************/
2073 
2074 /**
2075  * cpufreq_driver_fast_switch - Carry out a fast CPU frequency switch.
2076  * @policy: cpufreq policy to switch the frequency for.
2077  * @target_freq: New frequency to set (may be approximate).
2078  *
2079  * Carry out a fast frequency switch without sleeping.
2080  *
2081  * The driver's ->fast_switch() callback invoked by this function must be
2082  * suitable for being called from within RCU-sched read-side critical sections
2083  * and it is expected to select the minimum available frequency greater than or
2084  * equal to @target_freq (CPUFREQ_RELATION_L).
2085  *
2086  * This function must not be called if policy->fast_switch_enabled is unset.
2087  *
2088  * Governors calling this function must guarantee that it will never be invoked
2089  * twice in parallel for the same policy and that it will never be called in
2090  * parallel with either ->target() or ->target_index() for the same policy.
2091  *
2092  * Returns the actual frequency set for the CPU.
2093  *
2094  * If 0 is returned by the driver's ->fast_switch() callback to indicate an
2095  * error condition, the hardware configuration must be preserved.
2096  */
cpufreq_driver_fast_switch(struct cpufreq_policy * policy,unsigned int target_freq)2097 unsigned int cpufreq_driver_fast_switch(struct cpufreq_policy *policy,
2098 					unsigned int target_freq)
2099 {
2100 	unsigned int freq;
2101 	unsigned int old_target_freq = target_freq;
2102 	int cpu;
2103 
2104 	target_freq = clamp_val(target_freq, policy->min, policy->max);
2105 	trace_android_vh_cpufreq_fast_switch(policy, target_freq, old_target_freq);
2106 	freq = cpufreq_driver->fast_switch(policy, target_freq);
2107 
2108 	if (!freq)
2109 		return 0;
2110 
2111 	policy->cur = freq;
2112 	arch_set_freq_scale(policy->related_cpus, freq,
2113 			    policy->cpuinfo.max_freq);
2114 	cpufreq_stats_record_transition(policy, freq);
2115 	cpufreq_times_record_transition(policy, freq);
2116 	trace_android_rvh_cpufreq_transition(policy);
2117 
2118 	if (trace_cpu_frequency_enabled()) {
2119 		for_each_cpu(cpu, policy->cpus)
2120 			trace_cpu_frequency(freq, cpu);
2121 	}
2122 
2123 	return freq;
2124 }
2125 EXPORT_SYMBOL_GPL(cpufreq_driver_fast_switch);
2126 
2127 /* Must set freqs->new to intermediate frequency */
__target_intermediate(struct cpufreq_policy * policy,struct cpufreq_freqs * freqs,int index)2128 static int __target_intermediate(struct cpufreq_policy *policy,
2129 				 struct cpufreq_freqs *freqs, int index)
2130 {
2131 	int ret;
2132 
2133 	freqs->new = cpufreq_driver->get_intermediate(policy, index);
2134 
2135 	/* We don't need to switch to intermediate freq */
2136 	if (!freqs->new)
2137 		return 0;
2138 
2139 	pr_debug("%s: cpu: %d, switching to intermediate freq: oldfreq: %u, intermediate freq: %u\n",
2140 		 __func__, policy->cpu, freqs->old, freqs->new);
2141 
2142 	cpufreq_freq_transition_begin(policy, freqs);
2143 	ret = cpufreq_driver->target_intermediate(policy, index);
2144 	cpufreq_freq_transition_end(policy, freqs, ret);
2145 
2146 	if (ret)
2147 		pr_err("%s: Failed to change to intermediate frequency: %d\n",
2148 		       __func__, ret);
2149 
2150 	return ret;
2151 }
2152 
__target_index(struct cpufreq_policy * policy,int index)2153 static int __target_index(struct cpufreq_policy *policy, int index)
2154 {
2155 	struct cpufreq_freqs freqs = {.old = policy->cur, .flags = 0};
2156 	unsigned int intermediate_freq = 0;
2157 	unsigned int newfreq = policy->freq_table[index].frequency;
2158 	int retval = -EINVAL;
2159 	bool notify;
2160 
2161 	if (newfreq == policy->cur)
2162 		return 0;
2163 
2164 	notify = !(cpufreq_driver->flags & CPUFREQ_ASYNC_NOTIFICATION);
2165 	if (notify) {
2166 		/* Handle switching to intermediate frequency */
2167 		if (cpufreq_driver->get_intermediate) {
2168 			retval = __target_intermediate(policy, &freqs, index);
2169 			if (retval)
2170 				return retval;
2171 
2172 			intermediate_freq = freqs.new;
2173 			/* Set old freq to intermediate */
2174 			if (intermediate_freq)
2175 				freqs.old = freqs.new;
2176 		}
2177 
2178 		freqs.new = newfreq;
2179 		pr_debug("%s: cpu: %d, oldfreq: %u, new freq: %u\n",
2180 			 __func__, policy->cpu, freqs.old, freqs.new);
2181 
2182 		cpufreq_freq_transition_begin(policy, &freqs);
2183 	}
2184 
2185 	retval = cpufreq_driver->target_index(policy, index);
2186 	if (retval)
2187 		pr_err("%s: Failed to change cpu frequency: %d\n", __func__,
2188 		       retval);
2189 
2190 	if (notify) {
2191 		cpufreq_freq_transition_end(policy, &freqs, retval);
2192 
2193 		/*
2194 		 * Failed after setting to intermediate freq? Driver should have
2195 		 * reverted back to initial frequency and so should we. Check
2196 		 * here for intermediate_freq instead of get_intermediate, in
2197 		 * case we haven't switched to intermediate freq at all.
2198 		 */
2199 		if (unlikely(retval && intermediate_freq)) {
2200 			freqs.old = intermediate_freq;
2201 			freqs.new = policy->restore_freq;
2202 			cpufreq_freq_transition_begin(policy, &freqs);
2203 			cpufreq_freq_transition_end(policy, &freqs, 0);
2204 		}
2205 	}
2206 
2207 	return retval;
2208 }
2209 
__cpufreq_driver_target(struct cpufreq_policy * policy,unsigned int target_freq,unsigned int relation)2210 int __cpufreq_driver_target(struct cpufreq_policy *policy,
2211 			    unsigned int target_freq,
2212 			    unsigned int relation)
2213 {
2214 	unsigned int old_target_freq = target_freq;
2215 	int index;
2216 
2217 	if (cpufreq_disabled())
2218 		return -ENODEV;
2219 
2220 	/* Make sure that target_freq is within supported range */
2221 	target_freq = clamp_val(target_freq, policy->min, policy->max);
2222 	trace_android_vh_cpufreq_target(policy, target_freq, old_target_freq);
2223 
2224 	pr_debug("target for CPU %u: %u kHz, relation %u, requested %u kHz\n",
2225 		 policy->cpu, target_freq, relation, old_target_freq);
2226 
2227 	/*
2228 	 * This might look like a redundant call as we are checking it again
2229 	 * after finding index. But it is left intentionally for cases where
2230 	 * exactly same freq is called again and so we can save on few function
2231 	 * calls.
2232 	 */
2233 	if (target_freq == policy->cur &&
2234 	    !(cpufreq_driver->flags & CPUFREQ_NEED_UPDATE_LIMITS))
2235 		return 0;
2236 
2237 	/* Save last value to restore later on errors */
2238 	policy->restore_freq = policy->cur;
2239 
2240 	if (cpufreq_driver->target)
2241 		return cpufreq_driver->target(policy, target_freq, relation);
2242 
2243 	if (!cpufreq_driver->target_index)
2244 		return -EINVAL;
2245 
2246 	index = cpufreq_frequency_table_target(policy, target_freq, relation);
2247 
2248 	return __target_index(policy, index);
2249 }
2250 EXPORT_SYMBOL_GPL(__cpufreq_driver_target);
2251 
cpufreq_driver_target(struct cpufreq_policy * policy,unsigned int target_freq,unsigned int relation)2252 int cpufreq_driver_target(struct cpufreq_policy *policy,
2253 			  unsigned int target_freq,
2254 			  unsigned int relation)
2255 {
2256 	int ret;
2257 
2258 	down_write(&policy->rwsem);
2259 
2260 	ret = __cpufreq_driver_target(policy, target_freq, relation);
2261 
2262 	up_write(&policy->rwsem);
2263 
2264 	return ret;
2265 }
2266 EXPORT_SYMBOL_GPL(cpufreq_driver_target);
2267 
cpufreq_fallback_governor(void)2268 __weak struct cpufreq_governor *cpufreq_fallback_governor(void)
2269 {
2270 	return NULL;
2271 }
2272 
cpufreq_init_governor(struct cpufreq_policy * policy)2273 static int cpufreq_init_governor(struct cpufreq_policy *policy)
2274 {
2275 	int ret;
2276 
2277 	/* Don't start any governor operations if we are entering suspend */
2278 	if (cpufreq_suspended)
2279 		return 0;
2280 	/*
2281 	 * Governor might not be initiated here if ACPI _PPC changed
2282 	 * notification happened, so check it.
2283 	 */
2284 	if (!policy->governor)
2285 		return -EINVAL;
2286 
2287 	/* Platform doesn't want dynamic frequency switching ? */
2288 	if (policy->governor->flags & CPUFREQ_GOV_DYNAMIC_SWITCHING &&
2289 	    cpufreq_driver->flags & CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING) {
2290 		struct cpufreq_governor *gov = cpufreq_fallback_governor();
2291 
2292 		if (gov) {
2293 			pr_warn("Can't use %s governor as dynamic switching is disallowed. Fallback to %s governor\n",
2294 				policy->governor->name, gov->name);
2295 			policy->governor = gov;
2296 		} else {
2297 			return -EINVAL;
2298 		}
2299 	}
2300 
2301 	if (!try_module_get(policy->governor->owner))
2302 		return -EINVAL;
2303 
2304 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2305 
2306 	if (policy->governor->init) {
2307 		ret = policy->governor->init(policy);
2308 		if (ret) {
2309 			module_put(policy->governor->owner);
2310 			return ret;
2311 		}
2312 	}
2313 
2314 	policy->strict_target = !!(policy->governor->flags & CPUFREQ_GOV_STRICT_TARGET);
2315 
2316 	return 0;
2317 }
2318 
cpufreq_exit_governor(struct cpufreq_policy * policy)2319 static void cpufreq_exit_governor(struct cpufreq_policy *policy)
2320 {
2321 	if (cpufreq_suspended || !policy->governor)
2322 		return;
2323 
2324 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2325 
2326 	if (policy->governor->exit)
2327 		policy->governor->exit(policy);
2328 
2329 	module_put(policy->governor->owner);
2330 }
2331 
cpufreq_start_governor(struct cpufreq_policy * policy)2332 int cpufreq_start_governor(struct cpufreq_policy *policy)
2333 {
2334 	int ret;
2335 
2336 	if (cpufreq_suspended)
2337 		return 0;
2338 
2339 	if (!policy->governor)
2340 		return -EINVAL;
2341 
2342 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2343 
2344 	if (cpufreq_driver->get)
2345 		cpufreq_verify_current_freq(policy, false);
2346 
2347 	if (policy->governor->start) {
2348 		ret = policy->governor->start(policy);
2349 		if (ret)
2350 			return ret;
2351 	}
2352 
2353 	if (policy->governor->limits)
2354 		policy->governor->limits(policy);
2355 
2356 	return 0;
2357 }
2358 
cpufreq_stop_governor(struct cpufreq_policy * policy)2359 void cpufreq_stop_governor(struct cpufreq_policy *policy)
2360 {
2361 	if (cpufreq_suspended || !policy->governor)
2362 		return;
2363 
2364 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2365 
2366 	if (policy->governor->stop)
2367 		policy->governor->stop(policy);
2368 }
2369 
cpufreq_governor_limits(struct cpufreq_policy * policy)2370 static void cpufreq_governor_limits(struct cpufreq_policy *policy)
2371 {
2372 	if (cpufreq_suspended || !policy->governor)
2373 		return;
2374 
2375 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
2376 
2377 	if (policy->governor->limits)
2378 		policy->governor->limits(policy);
2379 }
2380 
cpufreq_register_governor(struct cpufreq_governor * governor)2381 int cpufreq_register_governor(struct cpufreq_governor *governor)
2382 {
2383 	int err;
2384 
2385 	if (!governor)
2386 		return -EINVAL;
2387 
2388 	if (cpufreq_disabled())
2389 		return -ENODEV;
2390 
2391 	mutex_lock(&cpufreq_governor_mutex);
2392 
2393 	err = -EBUSY;
2394 	if (!find_governor(governor->name)) {
2395 		err = 0;
2396 		list_add(&governor->governor_list, &cpufreq_governor_list);
2397 	}
2398 
2399 	mutex_unlock(&cpufreq_governor_mutex);
2400 	return err;
2401 }
2402 EXPORT_SYMBOL_GPL(cpufreq_register_governor);
2403 
cpufreq_unregister_governor(struct cpufreq_governor * governor)2404 void cpufreq_unregister_governor(struct cpufreq_governor *governor)
2405 {
2406 	struct cpufreq_policy *policy;
2407 	unsigned long flags;
2408 
2409 	if (!governor)
2410 		return;
2411 
2412 	if (cpufreq_disabled())
2413 		return;
2414 
2415 	/* clear last_governor for all inactive policies */
2416 	read_lock_irqsave(&cpufreq_driver_lock, flags);
2417 	for_each_inactive_policy(policy) {
2418 		if (!strcmp(policy->last_governor, governor->name)) {
2419 			policy->governor = NULL;
2420 			strcpy(policy->last_governor, "\0");
2421 		}
2422 	}
2423 	read_unlock_irqrestore(&cpufreq_driver_lock, flags);
2424 
2425 	mutex_lock(&cpufreq_governor_mutex);
2426 	list_del(&governor->governor_list);
2427 	mutex_unlock(&cpufreq_governor_mutex);
2428 }
2429 EXPORT_SYMBOL_GPL(cpufreq_unregister_governor);
2430 
2431 
2432 /*********************************************************************
2433  *                          POLICY INTERFACE                         *
2434  *********************************************************************/
2435 
2436 /**
2437  * cpufreq_get_policy - get the current cpufreq_policy
2438  * @policy: struct cpufreq_policy into which the current cpufreq_policy
2439  *	is written
2440  * @cpu: CPU to find the policy for
2441  *
2442  * Reads the current cpufreq policy.
2443  */
cpufreq_get_policy(struct cpufreq_policy * policy,unsigned int cpu)2444 int cpufreq_get_policy(struct cpufreq_policy *policy, unsigned int cpu)
2445 {
2446 	struct cpufreq_policy *cpu_policy;
2447 	if (!policy)
2448 		return -EINVAL;
2449 
2450 	cpu_policy = cpufreq_cpu_get(cpu);
2451 	if (!cpu_policy)
2452 		return -EINVAL;
2453 
2454 	memcpy(policy, cpu_policy, sizeof(*policy));
2455 
2456 	cpufreq_cpu_put(cpu_policy);
2457 	return 0;
2458 }
2459 EXPORT_SYMBOL(cpufreq_get_policy);
2460 
2461 /**
2462  * cpufreq_set_policy - Modify cpufreq policy parameters.
2463  * @policy: Policy object to modify.
2464  * @new_gov: Policy governor pointer.
2465  * @new_pol: Policy value (for drivers with built-in governors).
2466  *
2467  * Invoke the cpufreq driver's ->verify() callback to sanity-check the frequency
2468  * limits to be set for the policy, update @policy with the verified limits
2469  * values and either invoke the driver's ->setpolicy() callback (if present) or
2470  * carry out a governor update for @policy.  That is, run the current governor's
2471  * ->limits() callback (if @new_gov points to the same object as the one in
2472  * @policy) or replace the governor for @policy with @new_gov.
2473  *
2474  * The cpuinfo part of @policy is not updated by this function.
2475  */
cpufreq_set_policy(struct cpufreq_policy * policy,struct cpufreq_governor * new_gov,unsigned int new_pol)2476 static int cpufreq_set_policy(struct cpufreq_policy *policy,
2477 			      struct cpufreq_governor *new_gov,
2478 			      unsigned int new_pol)
2479 {
2480 	struct cpufreq_policy_data new_data;
2481 	struct cpufreq_governor *old_gov;
2482 	int ret;
2483 
2484 	memcpy(&new_data.cpuinfo, &policy->cpuinfo, sizeof(policy->cpuinfo));
2485 	new_data.freq_table = policy->freq_table;
2486 	new_data.cpu = policy->cpu;
2487 	/*
2488 	 * PM QoS framework collects all the requests from users and provide us
2489 	 * the final aggregated value here.
2490 	 */
2491 	new_data.min = freq_qos_read_value(&policy->constraints, FREQ_QOS_MIN);
2492 	new_data.max = freq_qos_read_value(&policy->constraints, FREQ_QOS_MAX);
2493 
2494 	pr_debug("setting new policy for CPU %u: %u - %u kHz\n",
2495 		 new_data.cpu, new_data.min, new_data.max);
2496 
2497 	/*
2498 	 * Verify that the CPU speed can be set within these limits and make sure
2499 	 * that min <= max.
2500 	 */
2501 	ret = cpufreq_driver->verify(&new_data);
2502 	if (ret)
2503 		return ret;
2504 
2505 	policy->min = new_data.min;
2506 	policy->max = new_data.max;
2507 	trace_cpu_frequency_limits(policy);
2508 
2509 	policy->cached_target_freq = UINT_MAX;
2510 
2511 	pr_debug("new min and max freqs are %u - %u kHz\n",
2512 		 policy->min, policy->max);
2513 
2514 	if (cpufreq_driver->setpolicy) {
2515 		policy->policy = new_pol;
2516 		pr_debug("setting range\n");
2517 		return cpufreq_driver->setpolicy(policy);
2518 	}
2519 
2520 	if (new_gov == policy->governor) {
2521 		pr_debug("governor limits update\n");
2522 		cpufreq_governor_limits(policy);
2523 		return 0;
2524 	}
2525 
2526 	pr_debug("governor switch\n");
2527 
2528 	/* save old, working values */
2529 	old_gov = policy->governor;
2530 	/* end old governor */
2531 	if (old_gov) {
2532 		cpufreq_stop_governor(policy);
2533 		cpufreq_exit_governor(policy);
2534 	}
2535 
2536 	/* start new governor */
2537 	policy->governor = new_gov;
2538 	ret = cpufreq_init_governor(policy);
2539 	if (!ret) {
2540 		ret = cpufreq_start_governor(policy);
2541 		if (!ret) {
2542 			pr_debug("governor change\n");
2543 			return 0;
2544 		}
2545 		cpufreq_exit_governor(policy);
2546 	}
2547 
2548 	/* new governor failed, so re-start old one */
2549 	pr_debug("starting governor %s failed\n", policy->governor->name);
2550 	if (old_gov) {
2551 		policy->governor = old_gov;
2552 		if (cpufreq_init_governor(policy))
2553 			policy->governor = NULL;
2554 		else
2555 			cpufreq_start_governor(policy);
2556 	}
2557 
2558 	return ret;
2559 }
2560 EXPORT_TRACEPOINT_SYMBOL_GPL(cpu_frequency_limits);
2561 
2562 /**
2563  * cpufreq_update_policy - Re-evaluate an existing cpufreq policy.
2564  * @cpu: CPU to re-evaluate the policy for.
2565  *
2566  * Update the current frequency for the cpufreq policy of @cpu and use
2567  * cpufreq_set_policy() to re-apply the min and max limits, which triggers the
2568  * evaluation of policy notifiers and the cpufreq driver's ->verify() callback
2569  * for the policy in question, among other things.
2570  */
cpufreq_update_policy(unsigned int cpu)2571 void cpufreq_update_policy(unsigned int cpu)
2572 {
2573 	struct cpufreq_policy *policy = cpufreq_cpu_acquire(cpu);
2574 
2575 	if (!policy)
2576 		return;
2577 
2578 	/*
2579 	 * BIOS might change freq behind our back
2580 	 * -> ask driver for current freq and notify governors about a change
2581 	 */
2582 	if (cpufreq_driver->get && has_target() &&
2583 	    (cpufreq_suspended || WARN_ON(!cpufreq_verify_current_freq(policy, false))))
2584 		goto unlock;
2585 
2586 	refresh_frequency_limits(policy);
2587 
2588 unlock:
2589 	cpufreq_cpu_release(policy);
2590 }
2591 EXPORT_SYMBOL(cpufreq_update_policy);
2592 
2593 /**
2594  * cpufreq_update_limits - Update policy limits for a given CPU.
2595  * @cpu: CPU to update the policy limits for.
2596  *
2597  * Invoke the driver's ->update_limits callback if present or call
2598  * cpufreq_update_policy() for @cpu.
2599  */
cpufreq_update_limits(unsigned int cpu)2600 void cpufreq_update_limits(unsigned int cpu)
2601 {
2602 	if (cpufreq_driver->update_limits)
2603 		cpufreq_driver->update_limits(cpu);
2604 	else
2605 		cpufreq_update_policy(cpu);
2606 }
2607 EXPORT_SYMBOL_GPL(cpufreq_update_limits);
2608 
2609 /*********************************************************************
2610  *               BOOST						     *
2611  *********************************************************************/
cpufreq_boost_set_sw(struct cpufreq_policy * policy,int state)2612 static int cpufreq_boost_set_sw(struct cpufreq_policy *policy, int state)
2613 {
2614 	int ret;
2615 
2616 	if (!policy->freq_table)
2617 		return -ENXIO;
2618 
2619 	ret = cpufreq_frequency_table_cpuinfo(policy, policy->freq_table);
2620 	if (ret) {
2621 		pr_err("%s: Policy frequency update failed\n", __func__);
2622 		return ret;
2623 	}
2624 
2625 	ret = freq_qos_update_request(policy->max_freq_req, policy->max);
2626 	if (ret < 0)
2627 		return ret;
2628 
2629 	return 0;
2630 }
2631 
cpufreq_boost_trigger_state(int state)2632 int cpufreq_boost_trigger_state(int state)
2633 {
2634 	struct cpufreq_policy *policy;
2635 	unsigned long flags;
2636 	int ret = 0;
2637 
2638 	if (cpufreq_driver->boost_enabled == state)
2639 		return 0;
2640 
2641 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2642 	cpufreq_driver->boost_enabled = state;
2643 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2644 
2645 	get_online_cpus();
2646 	for_each_active_policy(policy) {
2647 		ret = cpufreq_driver->set_boost(policy, state);
2648 		if (ret)
2649 			goto err_reset_state;
2650 	}
2651 	put_online_cpus();
2652 
2653 	return 0;
2654 
2655 err_reset_state:
2656 	put_online_cpus();
2657 
2658 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2659 	cpufreq_driver->boost_enabled = !state;
2660 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2661 
2662 	pr_err("%s: Cannot %s BOOST\n",
2663 	       __func__, state ? "enable" : "disable");
2664 
2665 	return ret;
2666 }
2667 
cpufreq_boost_supported(void)2668 static bool cpufreq_boost_supported(void)
2669 {
2670 	return cpufreq_driver->set_boost;
2671 }
2672 
create_boost_sysfs_file(void)2673 static int create_boost_sysfs_file(void)
2674 {
2675 	int ret;
2676 
2677 	ret = sysfs_create_file(cpufreq_global_kobject, &boost.attr);
2678 	if (ret)
2679 		pr_err("%s: cannot register global BOOST sysfs file\n",
2680 		       __func__);
2681 
2682 	return ret;
2683 }
2684 
remove_boost_sysfs_file(void)2685 static void remove_boost_sysfs_file(void)
2686 {
2687 	if (cpufreq_boost_supported())
2688 		sysfs_remove_file(cpufreq_global_kobject, &boost.attr);
2689 }
2690 
cpufreq_enable_boost_support(void)2691 int cpufreq_enable_boost_support(void)
2692 {
2693 	if (!cpufreq_driver)
2694 		return -EINVAL;
2695 
2696 	if (cpufreq_boost_supported())
2697 		return 0;
2698 
2699 	cpufreq_driver->set_boost = cpufreq_boost_set_sw;
2700 
2701 	/* This will get removed on driver unregister */
2702 	return create_boost_sysfs_file();
2703 }
2704 EXPORT_SYMBOL_GPL(cpufreq_enable_boost_support);
2705 
cpufreq_boost_enabled(void)2706 int cpufreq_boost_enabled(void)
2707 {
2708 	return cpufreq_driver->boost_enabled;
2709 }
2710 EXPORT_SYMBOL_GPL(cpufreq_boost_enabled);
2711 
2712 /*********************************************************************
2713  *               REGISTER / UNREGISTER CPUFREQ DRIVER                *
2714  *********************************************************************/
2715 static enum cpuhp_state hp_online;
2716 
cpuhp_cpufreq_online(unsigned int cpu)2717 static int cpuhp_cpufreq_online(unsigned int cpu)
2718 {
2719 	cpufreq_online(cpu);
2720 
2721 	return 0;
2722 }
2723 
cpuhp_cpufreq_offline(unsigned int cpu)2724 static int cpuhp_cpufreq_offline(unsigned int cpu)
2725 {
2726 	cpufreq_offline(cpu);
2727 
2728 	return 0;
2729 }
2730 
2731 /**
2732  * cpufreq_register_driver - register a CPU Frequency driver
2733  * @driver_data: A struct cpufreq_driver containing the values#
2734  * submitted by the CPU Frequency driver.
2735  *
2736  * Registers a CPU Frequency driver to this core code. This code
2737  * returns zero on success, -EEXIST when another driver got here first
2738  * (and isn't unregistered in the meantime).
2739  *
2740  */
cpufreq_register_driver(struct cpufreq_driver * driver_data)2741 int cpufreq_register_driver(struct cpufreq_driver *driver_data)
2742 {
2743 	unsigned long flags;
2744 	int ret;
2745 
2746 	if (cpufreq_disabled())
2747 		return -ENODEV;
2748 
2749 	/*
2750 	 * The cpufreq core depends heavily on the availability of device
2751 	 * structure, make sure they are available before proceeding further.
2752 	 */
2753 	if (!get_cpu_device(0))
2754 		return -EPROBE_DEFER;
2755 
2756 	if (!driver_data || !driver_data->verify || !driver_data->init ||
2757 	    !(driver_data->setpolicy || driver_data->target_index ||
2758 		    driver_data->target) ||
2759 	     (driver_data->setpolicy && (driver_data->target_index ||
2760 		    driver_data->target)) ||
2761 	     (!driver_data->get_intermediate != !driver_data->target_intermediate) ||
2762 	     (!driver_data->online != !driver_data->offline))
2763 		return -EINVAL;
2764 
2765 	pr_debug("trying to register driver %s\n", driver_data->name);
2766 
2767 	/* Protect against concurrent CPU online/offline. */
2768 	cpus_read_lock();
2769 
2770 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2771 	if (cpufreq_driver) {
2772 		write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2773 		ret = -EEXIST;
2774 		goto out;
2775 	}
2776 	cpufreq_driver = driver_data;
2777 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2778 
2779 	/*
2780 	 * Mark support for the scheduler's frequency invariance engine for
2781 	 * drivers that implement target(), target_index() or fast_switch().
2782 	 */
2783 	if (!cpufreq_driver->setpolicy) {
2784 		static_branch_enable_cpuslocked(&cpufreq_freq_invariance);
2785 		pr_debug("supports frequency invariance");
2786 	}
2787 
2788 	if (driver_data->setpolicy)
2789 		driver_data->flags |= CPUFREQ_CONST_LOOPS;
2790 
2791 	if (cpufreq_boost_supported()) {
2792 		ret = create_boost_sysfs_file();
2793 		if (ret)
2794 			goto err_null_driver;
2795 	}
2796 
2797 	ret = subsys_interface_register(&cpufreq_interface);
2798 	if (ret)
2799 		goto err_boost_unreg;
2800 
2801 	if (!(cpufreq_driver->flags & CPUFREQ_STICKY) &&
2802 	    list_empty(&cpufreq_policy_list)) {
2803 		/* if all ->init() calls failed, unregister */
2804 		ret = -ENODEV;
2805 		pr_debug("%s: No CPU initialized for driver %s\n", __func__,
2806 			 driver_data->name);
2807 		goto err_if_unreg;
2808 	}
2809 
2810 	ret = cpuhp_setup_state_nocalls_cpuslocked(CPUHP_AP_ONLINE_DYN,
2811 						   "cpufreq:online",
2812 						   cpuhp_cpufreq_online,
2813 						   cpuhp_cpufreq_offline);
2814 	if (ret < 0)
2815 		goto err_if_unreg;
2816 	hp_online = ret;
2817 	ret = 0;
2818 
2819 	pr_debug("driver %s up and running\n", driver_data->name);
2820 	goto out;
2821 
2822 err_if_unreg:
2823 	subsys_interface_unregister(&cpufreq_interface);
2824 err_boost_unreg:
2825 	remove_boost_sysfs_file();
2826 err_null_driver:
2827 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2828 	cpufreq_driver = NULL;
2829 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2830 out:
2831 	cpus_read_unlock();
2832 	return ret;
2833 }
2834 EXPORT_SYMBOL_GPL(cpufreq_register_driver);
2835 
2836 /*
2837  * cpufreq_unregister_driver - unregister the current CPUFreq driver
2838  *
2839  * Unregister the current CPUFreq driver. Only call this if you have
2840  * the right to do so, i.e. if you have succeeded in initialising before!
2841  * Returns zero if successful, and -EINVAL if the cpufreq_driver is
2842  * currently not initialised.
2843  */
cpufreq_unregister_driver(struct cpufreq_driver * driver)2844 int cpufreq_unregister_driver(struct cpufreq_driver *driver)
2845 {
2846 	unsigned long flags;
2847 
2848 	if (!cpufreq_driver || (driver != cpufreq_driver))
2849 		return -EINVAL;
2850 
2851 	pr_debug("unregistering driver %s\n", driver->name);
2852 
2853 	/* Protect against concurrent cpu hotplug */
2854 	cpus_read_lock();
2855 	subsys_interface_unregister(&cpufreq_interface);
2856 	remove_boost_sysfs_file();
2857 	static_branch_disable_cpuslocked(&cpufreq_freq_invariance);
2858 	cpuhp_remove_state_nocalls_cpuslocked(hp_online);
2859 
2860 	write_lock_irqsave(&cpufreq_driver_lock, flags);
2861 
2862 	cpufreq_driver = NULL;
2863 
2864 	write_unlock_irqrestore(&cpufreq_driver_lock, flags);
2865 	cpus_read_unlock();
2866 
2867 	return 0;
2868 }
2869 EXPORT_SYMBOL_GPL(cpufreq_unregister_driver);
2870 
cpufreq_core_init(void)2871 static int __init cpufreq_core_init(void)
2872 {
2873 	struct cpufreq_governor *gov = cpufreq_default_governor();
2874 
2875 	if (cpufreq_disabled())
2876 		return -ENODEV;
2877 
2878 	cpufreq_global_kobject = kobject_create_and_add("cpufreq", &cpu_subsys.dev_root->kobj);
2879 	BUG_ON(!cpufreq_global_kobject);
2880 
2881 	if (!strlen(default_governor))
2882 		strncpy(default_governor, gov->name, CPUFREQ_NAME_LEN);
2883 
2884 	return 0;
2885 }
2886 module_param(off, int, 0444);
2887 module_param_string(default_governor, default_governor, CPUFREQ_NAME_LEN, 0444);
2888 core_initcall(cpufreq_core_init);
2889