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