xref: /linux/kernel/sched/cpufreq_schedutil.c (revision f4cdf7ca9a1fdcca413157df19753f388a5a224e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * CPUFreq governor based on scheduler-provided CPU utilization data.
4  *
5  * Copyright (C) 2016, Intel Corporation
6  * Author: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
7  */
8 #include <uapi/linux/sched/types.h>
9 #include "sched.h"
10 
11 #define IOWAIT_BOOST_MIN	(SCHED_CAPACITY_SCALE / 8)
12 
13 struct sugov_tunables {
14 	struct gov_attr_set	attr_set;
15 	unsigned int		rate_limit_us;
16 };
17 
18 struct sugov_policy {
19 	struct cpufreq_policy	*policy;
20 
21 	struct sugov_tunables	*tunables;
22 	struct list_head	tunables_hook;
23 
24 	raw_spinlock_t		update_lock;
25 	u64			last_freq_update_time;
26 	s64			freq_update_delay_ns;
27 	unsigned int		next_freq;
28 	unsigned int		cached_raw_freq;
29 
30 	/* The next fields are only needed if fast switch cannot be used: */
31 	struct			irq_work irq_work;
32 	struct			kthread_work work;
33 	struct			mutex work_lock;
34 	struct			kthread_worker worker;
35 	struct task_struct	*thread;
36 	bool			work_in_progress;
37 
38 	bool			limits_changed;
39 	bool			need_freq_update;
40 };
41 
42 struct sugov_cpu {
43 	struct update_util_data	update_util;
44 	struct sugov_policy	*sg_policy;
45 	unsigned int		cpu;
46 
47 	bool			iowait_boost_pending;
48 	unsigned int		iowait_boost;
49 	u64			last_update;
50 
51 	unsigned long		util;
52 	unsigned long		bw_min;
53 	unsigned long		bw_max;
54 
55 	/* The field below is for single-CPU policies only: */
56 #ifdef CONFIG_NO_HZ_COMMON
57 	unsigned long		saved_idle_calls;
58 #endif
59 };
60 
61 static DEFINE_PER_CPU(struct sugov_cpu, sugov_cpu);
62 
63 /************************ Governor internals ***********************/
64 
65 static bool sugov_should_update_freq(struct sugov_policy *sg_policy, u64 time)
66 {
67 	s64 delta_ns;
68 
69 	/*
70 	 * Since cpufreq_update_util() is called with rq->lock held for
71 	 * the @target_cpu, our per-CPU data is fully serialized.
72 	 *
73 	 * However, drivers cannot in general deal with cross-CPU
74 	 * requests, so while get_next_freq() will work, our
75 	 * sugov_update_commit() call may not for the fast switching platforms.
76 	 *
77 	 * Hence stop here for remote requests if they aren't supported
78 	 * by the hardware, as calculating the frequency is pointless if
79 	 * we cannot in fact act on it.
80 	 *
81 	 * This is needed on the slow switching platforms too to prevent CPUs
82 	 * going offline from leaving stale IRQ work items behind.
83 	 */
84 	if (!cpufreq_this_cpu_can_update(sg_policy->policy))
85 		return false;
86 
87 	if (unlikely(READ_ONCE(sg_policy->limits_changed))) {
88 		WRITE_ONCE(sg_policy->limits_changed, false);
89 		sg_policy->need_freq_update = true;
90 
91 		/*
92 		 * The above limits_changed update must occur before the reads
93 		 * of policy limits in cpufreq_driver_resolve_freq() or a policy
94 		 * limits update might be missed, so use a memory barrier to
95 		 * ensure it.
96 		 *
97 		 * This pairs with the write memory barrier in sugov_limits().
98 		 */
99 		smp_mb();
100 
101 		return true;
102 	} else if (sg_policy->need_freq_update) {
103 		/* ignore_dl_rate_limit() wants a new frequency to be found. */
104 		return true;
105 	}
106 
107 	delta_ns = time - sg_policy->last_freq_update_time;
108 
109 	return delta_ns >= sg_policy->freq_update_delay_ns;
110 }
111 
112 static bool sugov_update_next_freq(struct sugov_policy *sg_policy, u64 time,
113 				   unsigned int next_freq)
114 {
115 	if (sg_policy->need_freq_update) {
116 		sg_policy->need_freq_update = false;
117 		/*
118 		 * The policy limits have changed, but if the return value of
119 		 * cpufreq_driver_resolve_freq() after applying the new limits
120 		 * is still equal to the previously selected frequency, the
121 		 * driver callback need not be invoked unless the driver
122 		 * specifically wants that to happen on every update of the
123 		 * policy limits.
124 		 */
125 		if (sg_policy->next_freq == next_freq &&
126 		    !cpufreq_driver_test_flags(CPUFREQ_NEED_UPDATE_LIMITS))
127 			return false;
128 	} else if (sg_policy->next_freq == next_freq) {
129 		return false;
130 	}
131 
132 	sg_policy->next_freq = next_freq;
133 	sg_policy->last_freq_update_time = time;
134 
135 	return true;
136 }
137 
138 static void sugov_deferred_update(struct sugov_policy *sg_policy)
139 {
140 	if (!sg_policy->work_in_progress) {
141 		sg_policy->work_in_progress = true;
142 		irq_work_queue(&sg_policy->irq_work);
143 	}
144 }
145 
146 /**
147  * get_capacity_ref_freq - get the reference frequency that has been used to
148  * correlate frequency and compute capacity for a given cpufreq policy. We use
149  * the CPU managing it for the arch_scale_freq_ref() call in the function.
150  * @policy: the cpufreq policy of the CPU in question.
151  *
152  * Return: the reference CPU frequency to compute a capacity.
153  */
154 static __always_inline
155 unsigned long get_capacity_ref_freq(struct cpufreq_policy *policy)
156 {
157 	unsigned int freq = arch_scale_freq_ref(policy->cpu);
158 
159 	if (freq)
160 		return freq;
161 
162 	if (arch_scale_freq_invariant())
163 		return policy->cpuinfo.max_freq;
164 
165 	/*
166 	 * Apply a 25% margin so that we select a higher frequency than
167 	 * the current one before the CPU is fully busy:
168 	 */
169 	return policy->cur + (policy->cur >> 2);
170 }
171 
172 /**
173  * get_next_freq - Compute a new frequency for a given cpufreq policy.
174  * @sg_policy: schedutil policy object to compute the new frequency for.
175  * @util: Current CPU utilization.
176  * @max: CPU capacity.
177  *
178  * If the utilization is frequency-invariant, choose the new frequency to be
179  * proportional to it, that is
180  *
181  * next_freq = C * max_freq * util / max
182  *
183  * Otherwise, approximate the would-be frequency-invariant utilization by
184  * util_raw * (curr_freq / max_freq) which leads to
185  *
186  * next_freq = C * curr_freq * util_raw / max
187  *
188  * Take C = 1.25 for the frequency tipping point at (util / max) = 0.8.
189  *
190  * The lowest driver-supported frequency which is equal or greater than the raw
191  * next_freq (as calculated above) is returned, subject to policy min/max and
192  * cpufreq driver limitations.
193  */
194 static unsigned int get_next_freq(struct sugov_policy *sg_policy,
195 				  unsigned long util, unsigned long max)
196 {
197 	struct cpufreq_policy *policy = sg_policy->policy;
198 	unsigned int freq;
199 
200 	freq = get_capacity_ref_freq(policy);
201 	freq = map_util_freq(util, freq, max);
202 
203 	if (freq == sg_policy->cached_raw_freq && !sg_policy->need_freq_update)
204 		return sg_policy->next_freq;
205 
206 	sg_policy->cached_raw_freq = freq;
207 	return cpufreq_driver_resolve_freq(policy, freq);
208 }
209 
210 unsigned long sugov_effective_cpu_perf(int cpu, unsigned long actual,
211 				 unsigned long min,
212 				 unsigned long max)
213 {
214 	/* Add dvfs headroom to actual utilization */
215 	actual = map_util_perf(actual);
216 	/* Actually we don't need to target the max performance */
217 	if (actual < max)
218 		max = actual;
219 
220 	/*
221 	 * Ensure at least minimum performance while providing more compute
222 	 * capacity when possible.
223 	 */
224 	return max(min, max);
225 }
226 
227 static void sugov_get_util(struct sugov_cpu *sg_cpu, unsigned long boost)
228 {
229 	unsigned long min, max, util = scx_cpuperf_target(sg_cpu->cpu);
230 
231 	if (!scx_switched_all())
232 		util += cpu_util_cfs_boost(sg_cpu->cpu);
233 	util = effective_cpu_util(sg_cpu->cpu, util, &min, &max);
234 	util = max(util, boost);
235 	sg_cpu->bw_min = min;
236 	sg_cpu->bw_max = max;
237 	sg_cpu->util = sugov_effective_cpu_perf(sg_cpu->cpu, util, min, max);
238 }
239 
240 /**
241  * sugov_iowait_reset() - Reset the IO boost status of a CPU.
242  * @sg_cpu: the sugov data for the CPU to boost
243  * @time: the update time from the caller
244  * @set_iowait_boost: true if an IO boost has been requested
245  *
246  * The IO wait boost of a task is disabled after a tick since the last update
247  * of a CPU. If a new IO wait boost is requested after more then a tick, then
248  * we enable the boost starting from IOWAIT_BOOST_MIN, which improves energy
249  * efficiency by ignoring sporadic wakeups from IO.
250  */
251 static bool sugov_iowait_reset(struct sugov_cpu *sg_cpu, u64 time,
252 			       bool set_iowait_boost)
253 {
254 	s64 delta_ns = time - sg_cpu->last_update;
255 
256 	/* Reset boost only if a tick has elapsed since last request */
257 	if (delta_ns <= TICK_NSEC)
258 		return false;
259 
260 	sg_cpu->iowait_boost = set_iowait_boost ? IOWAIT_BOOST_MIN : 0;
261 	sg_cpu->iowait_boost_pending = set_iowait_boost;
262 
263 	return true;
264 }
265 
266 /**
267  * sugov_iowait_boost() - Updates the IO boost status of a CPU.
268  * @sg_cpu: the sugov data for the CPU to boost
269  * @time: the update time from the caller
270  * @flags: SCHED_CPUFREQ_IOWAIT if the task is waking up after an IO wait
271  *
272  * Each time a task wakes up after an IO operation, the CPU utilization can be
273  * boosted to a certain utilization which doubles at each "frequent and
274  * successive" wakeup from IO, ranging from IOWAIT_BOOST_MIN to the utilization
275  * of the maximum OPP.
276  *
277  * To keep doubling, an IO boost has to be requested at least once per tick,
278  * otherwise we restart from the utilization of the minimum OPP.
279  */
280 static void sugov_iowait_boost(struct sugov_cpu *sg_cpu, u64 time,
281 			       unsigned int flags)
282 {
283 	bool set_iowait_boost = flags & SCHED_CPUFREQ_IOWAIT;
284 
285 	/* Reset boost if the CPU appears to have been idle enough */
286 	if (sg_cpu->iowait_boost &&
287 	    sugov_iowait_reset(sg_cpu, time, set_iowait_boost))
288 		return;
289 
290 	/* Boost only tasks waking up after IO */
291 	if (!set_iowait_boost)
292 		return;
293 
294 	/* Ensure boost doubles only one time at each request */
295 	if (sg_cpu->iowait_boost_pending)
296 		return;
297 	sg_cpu->iowait_boost_pending = true;
298 
299 	/* Double the boost at each request */
300 	if (sg_cpu->iowait_boost) {
301 		sg_cpu->iowait_boost =
302 			min_t(unsigned int, sg_cpu->iowait_boost << 1, SCHED_CAPACITY_SCALE);
303 		return;
304 	}
305 
306 	/* First wakeup after IO: start with minimum boost */
307 	sg_cpu->iowait_boost = IOWAIT_BOOST_MIN;
308 }
309 
310 /**
311  * sugov_iowait_apply() - Apply the IO boost to a CPU.
312  * @sg_cpu: the sugov data for the cpu to boost
313  * @time: the update time from the caller
314  * @max_cap: the max CPU capacity
315  *
316  * A CPU running a task which woken up after an IO operation can have its
317  * utilization boosted to speed up the completion of those IO operations.
318  * The IO boost value is increased each time a task wakes up from IO, in
319  * sugov_iowait_boost(), and it's instead decreased by this function,
320  * each time an increase has not been requested (!iowait_boost_pending).
321  *
322  * A CPU which also appears to have been idle for at least one tick has also
323  * its IO boost utilization reset.
324  *
325  * This mechanism is designed to boost high frequently IO waiting tasks, while
326  * being more conservative on tasks which does sporadic IO operations.
327  */
328 static unsigned long sugov_iowait_apply(struct sugov_cpu *sg_cpu, u64 time,
329 			       unsigned long max_cap)
330 {
331 	/* No boost currently required */
332 	if (!sg_cpu->iowait_boost)
333 		return 0;
334 
335 	/* Reset boost if the CPU appears to have been idle enough */
336 	if (sugov_iowait_reset(sg_cpu, time, false))
337 		return 0;
338 
339 	if (!sg_cpu->iowait_boost_pending) {
340 		/*
341 		 * No boost pending; reduce the boost value.
342 		 */
343 		sg_cpu->iowait_boost >>= 1;
344 		if (sg_cpu->iowait_boost < IOWAIT_BOOST_MIN) {
345 			sg_cpu->iowait_boost = 0;
346 			return 0;
347 		}
348 	}
349 
350 	sg_cpu->iowait_boost_pending = false;
351 
352 	/*
353 	 * sg_cpu->util is already in capacity scale; convert iowait_boost
354 	 * into the same scale so we can compare.
355 	 */
356 	return (sg_cpu->iowait_boost * max_cap) >> SCHED_CAPACITY_SHIFT;
357 }
358 
359 #ifdef CONFIG_NO_HZ_COMMON
360 static bool sugov_hold_freq(struct sugov_cpu *sg_cpu)
361 {
362 	unsigned long idle_calls;
363 	bool ret;
364 
365 	/*
366 	 * The heuristics in this function is for the fair class. For SCX, the
367 	 * performance target comes directly from the BPF scheduler. Let's just
368 	 * follow it.
369 	 */
370 	if (scx_switched_all())
371 		return false;
372 
373 	/* if capped by uclamp_max, always update to be in compliance */
374 	if (uclamp_rq_is_capped(cpu_rq(sg_cpu->cpu)))
375 		return false;
376 
377 	/*
378 	 * Maintain the frequency if the CPU has not been idle recently, as
379 	 * reduction is likely to be premature.
380 	 */
381 	idle_calls = tick_nohz_get_idle_calls_cpu(sg_cpu->cpu);
382 	ret = idle_calls == sg_cpu->saved_idle_calls;
383 
384 	sg_cpu->saved_idle_calls = idle_calls;
385 	return ret;
386 }
387 #else /* !CONFIG_NO_HZ_COMMON: */
388 static inline bool sugov_hold_freq(struct sugov_cpu *sg_cpu) { return false; }
389 #endif /* !CONFIG_NO_HZ_COMMON */
390 
391 /*
392  * Make sugov_should_update_freq() ignore the rate limit when DL
393  * has increased the utilization.
394  */
395 static inline void ignore_dl_rate_limit(struct sugov_cpu *sg_cpu)
396 {
397 	if (cpu_bw_dl(cpu_rq(sg_cpu->cpu)) > sg_cpu->bw_min)
398 		sg_cpu->sg_policy->need_freq_update = true;
399 }
400 
401 static inline bool sugov_update_single_common(struct sugov_cpu *sg_cpu,
402 					      u64 time, unsigned long max_cap,
403 					      unsigned int flags)
404 {
405 	unsigned long boost;
406 
407 	sugov_iowait_boost(sg_cpu, time, flags);
408 	sg_cpu->last_update = time;
409 
410 	ignore_dl_rate_limit(sg_cpu);
411 
412 	if (!sugov_should_update_freq(sg_cpu->sg_policy, time))
413 		return false;
414 
415 	boost = sugov_iowait_apply(sg_cpu, time, max_cap);
416 	sugov_get_util(sg_cpu, boost);
417 
418 	return true;
419 }
420 
421 static void sugov_update_single_freq(struct update_util_data *hook, u64 time,
422 				     unsigned int flags)
423 {
424 	struct sugov_cpu *sg_cpu = container_of(hook, struct sugov_cpu, update_util);
425 	struct sugov_policy *sg_policy = sg_cpu->sg_policy;
426 	unsigned int cached_freq = sg_policy->cached_raw_freq;
427 	unsigned long max_cap;
428 	unsigned int next_f;
429 
430 	max_cap = arch_scale_cpu_capacity(sg_cpu->cpu);
431 
432 	if (!sugov_update_single_common(sg_cpu, time, max_cap, flags))
433 		return;
434 
435 	next_f = get_next_freq(sg_policy, sg_cpu->util, max_cap);
436 
437 	if (sugov_hold_freq(sg_cpu) && next_f < sg_policy->next_freq &&
438 	    !sg_policy->need_freq_update) {
439 		next_f = sg_policy->next_freq;
440 
441 		/* Restore cached freq as next_freq has changed */
442 		sg_policy->cached_raw_freq = cached_freq;
443 	}
444 
445 	if (!sugov_update_next_freq(sg_policy, time, next_f))
446 		return;
447 
448 	/*
449 	 * This code runs under rq->lock for the target CPU, so it won't run
450 	 * concurrently on two different CPUs for the same target and it is not
451 	 * necessary to acquire the lock in the fast switch case.
452 	 */
453 	if (sg_policy->policy->fast_switch_enabled) {
454 		cpufreq_driver_fast_switch(sg_policy->policy, next_f);
455 	} else {
456 		raw_spin_lock(&sg_policy->update_lock);
457 		sugov_deferred_update(sg_policy);
458 		raw_spin_unlock(&sg_policy->update_lock);
459 	}
460 }
461 
462 static void sugov_update_single_perf(struct update_util_data *hook, u64 time,
463 				     unsigned int flags)
464 {
465 	struct sugov_cpu *sg_cpu = container_of(hook, struct sugov_cpu, update_util);
466 	struct sugov_policy *sg_policy = sg_cpu->sg_policy;
467 	unsigned long prev_util = sg_cpu->util;
468 	unsigned long max_cap;
469 
470 	/*
471 	 * Fall back to the "frequency" path if frequency invariance is not
472 	 * supported, because the direct mapping between the utilization and
473 	 * the performance levels depends on the frequency invariance.
474 	 */
475 	if (!arch_scale_freq_invariant()) {
476 		sugov_update_single_freq(hook, time, flags);
477 		return;
478 	}
479 
480 	max_cap = arch_scale_cpu_capacity(sg_cpu->cpu);
481 
482 	if (!sugov_update_single_common(sg_cpu, time, max_cap, flags))
483 		return;
484 
485 	if (sugov_hold_freq(sg_cpu) && sg_cpu->util < prev_util)
486 		sg_cpu->util = prev_util;
487 
488 	cpufreq_driver_adjust_perf(sg_policy->policy, sg_cpu->bw_min,
489 				   sg_cpu->util, sg_cpu->bw_max, max_cap);
490 
491 	sg_policy->need_freq_update = false;
492 	sg_policy->last_freq_update_time = time;
493 }
494 
495 static unsigned int sugov_next_freq_shared(struct sugov_cpu *sg_cpu, u64 time)
496 {
497 	struct sugov_policy *sg_policy = sg_cpu->sg_policy;
498 	struct cpufreq_policy *policy = sg_policy->policy;
499 	unsigned long util = 0, max_cap;
500 	unsigned int j;
501 
502 	max_cap = arch_scale_cpu_capacity(sg_cpu->cpu);
503 
504 	for_each_cpu(j, policy->cpus) {
505 		struct sugov_cpu *j_sg_cpu = &per_cpu(sugov_cpu, j);
506 		unsigned long boost;
507 
508 		boost = sugov_iowait_apply(j_sg_cpu, time, max_cap);
509 		sugov_get_util(j_sg_cpu, boost);
510 
511 		util = max(j_sg_cpu->util, util);
512 	}
513 
514 	return get_next_freq(sg_policy, util, max_cap);
515 }
516 
517 static void
518 sugov_update_shared(struct update_util_data *hook, u64 time, unsigned int flags)
519 {
520 	struct sugov_cpu *sg_cpu = container_of(hook, struct sugov_cpu, update_util);
521 	struct sugov_policy *sg_policy = sg_cpu->sg_policy;
522 	unsigned int next_f;
523 
524 	raw_spin_lock(&sg_policy->update_lock);
525 
526 	sugov_iowait_boost(sg_cpu, time, flags);
527 	sg_cpu->last_update = time;
528 
529 	ignore_dl_rate_limit(sg_cpu);
530 
531 	if (sugov_should_update_freq(sg_policy, time)) {
532 		next_f = sugov_next_freq_shared(sg_cpu, time);
533 
534 		if (!sugov_update_next_freq(sg_policy, time, next_f))
535 			goto unlock;
536 
537 		if (sg_policy->policy->fast_switch_enabled)
538 			cpufreq_driver_fast_switch(sg_policy->policy, next_f);
539 		else
540 			sugov_deferred_update(sg_policy);
541 	}
542 unlock:
543 	raw_spin_unlock(&sg_policy->update_lock);
544 }
545 
546 static void sugov_work(struct kthread_work *work)
547 {
548 	struct sugov_policy *sg_policy = container_of(work, struct sugov_policy, work);
549 	unsigned int freq;
550 	unsigned long flags;
551 
552 	/*
553 	 * Hold sg_policy->update_lock shortly to handle the case where:
554 	 * in case sg_policy->next_freq is read here, and then updated by
555 	 * sugov_deferred_update() just before work_in_progress is set to false
556 	 * here, we may miss queueing the new update.
557 	 *
558 	 * Note: If a work was queued after the update_lock is released,
559 	 * sugov_work() will just be called again by kthread_work code; and the
560 	 * request will be proceed before the sugov thread sleeps.
561 	 */
562 	raw_spin_lock_irqsave(&sg_policy->update_lock, flags);
563 	freq = sg_policy->next_freq;
564 	sg_policy->work_in_progress = false;
565 	raw_spin_unlock_irqrestore(&sg_policy->update_lock, flags);
566 
567 	mutex_lock(&sg_policy->work_lock);
568 	__cpufreq_driver_target(sg_policy->policy, freq, CPUFREQ_RELATION_L);
569 	mutex_unlock(&sg_policy->work_lock);
570 }
571 
572 static void sugov_irq_work(struct irq_work *irq_work)
573 {
574 	struct sugov_policy *sg_policy;
575 
576 	sg_policy = container_of(irq_work, struct sugov_policy, irq_work);
577 
578 	kthread_queue_work(&sg_policy->worker, &sg_policy->work);
579 }
580 
581 /************************** sysfs interface ************************/
582 
583 static struct sugov_tunables *global_tunables;
584 static DEFINE_MUTEX(global_tunables_lock);
585 
586 static inline struct sugov_tunables *to_sugov_tunables(struct gov_attr_set *attr_set)
587 {
588 	return container_of(attr_set, struct sugov_tunables, attr_set);
589 }
590 
591 static ssize_t rate_limit_us_show(struct gov_attr_set *attr_set, char *buf)
592 {
593 	struct sugov_tunables *tunables = to_sugov_tunables(attr_set);
594 
595 	return sysfs_emit(buf, "%u\n", tunables->rate_limit_us);
596 }
597 
598 static ssize_t
599 rate_limit_us_store(struct gov_attr_set *attr_set, const char *buf, size_t count)
600 {
601 	struct sugov_tunables *tunables = to_sugov_tunables(attr_set);
602 	struct sugov_policy *sg_policy;
603 	unsigned int rate_limit_us;
604 
605 	if (kstrtouint(buf, 10, &rate_limit_us))
606 		return -EINVAL;
607 
608 	tunables->rate_limit_us = rate_limit_us;
609 
610 	list_for_each_entry(sg_policy, &attr_set->policy_list, tunables_hook)
611 		sg_policy->freq_update_delay_ns = rate_limit_us * NSEC_PER_USEC;
612 
613 	return count;
614 }
615 
616 static struct governor_attr rate_limit_us = __ATTR_RW(rate_limit_us);
617 
618 static struct attribute *sugov_attrs[] = {
619 	&rate_limit_us.attr,
620 	NULL
621 };
622 ATTRIBUTE_GROUPS(sugov);
623 
624 static void sugov_tunables_free(struct kobject *kobj)
625 {
626 	struct gov_attr_set *attr_set = to_gov_attr_set(kobj);
627 
628 	kfree(to_sugov_tunables(attr_set));
629 }
630 
631 static const struct kobj_type sugov_tunables_ktype = {
632 	.default_groups = sugov_groups,
633 	.sysfs_ops = &governor_sysfs_ops,
634 	.release = &sugov_tunables_free,
635 };
636 
637 /********************** cpufreq governor interface *********************/
638 
639 static struct cpufreq_governor schedutil_gov;
640 
641 static struct sugov_policy *sugov_policy_alloc(struct cpufreq_policy *policy)
642 {
643 	struct sugov_policy *sg_policy;
644 
645 	sg_policy = kzalloc_obj(*sg_policy);
646 	if (!sg_policy)
647 		return NULL;
648 
649 	sg_policy->policy = policy;
650 	raw_spin_lock_init(&sg_policy->update_lock);
651 	return sg_policy;
652 }
653 
654 static void sugov_policy_free(struct sugov_policy *sg_policy)
655 {
656 	kfree(sg_policy);
657 }
658 
659 static int sugov_kthread_create(struct sugov_policy *sg_policy)
660 {
661 	struct task_struct *thread;
662 	struct sched_attr attr = {
663 		.size		= sizeof(struct sched_attr),
664 		.sched_policy	= SCHED_DEADLINE,
665 		.sched_flags	= SCHED_FLAG_SUGOV,
666 		.sched_nice	= 0,
667 		.sched_priority	= 0,
668 		/*
669 		 * Fake (unused) bandwidth; workaround to "fix"
670 		 * priority inheritance.
671 		 */
672 		.sched_runtime	= NSEC_PER_MSEC,
673 		.sched_deadline = 10 * NSEC_PER_MSEC,
674 		.sched_period	= 10 * NSEC_PER_MSEC,
675 	};
676 	struct cpufreq_policy *policy = sg_policy->policy;
677 	int ret;
678 
679 	/* kthread only required for slow path */
680 	if (policy->fast_switch_enabled)
681 		return 0;
682 
683 	kthread_init_work(&sg_policy->work, sugov_work);
684 	kthread_init_worker(&sg_policy->worker);
685 	thread = kthread_create(kthread_worker_fn, &sg_policy->worker,
686 				"sugov:%d",
687 				cpumask_first(policy->related_cpus));
688 	if (IS_ERR(thread)) {
689 		pr_err("failed to create sugov thread: %pe\n", thread);
690 		return PTR_ERR(thread);
691 	}
692 
693 	ret = sched_setattr_nocheck(thread, &attr);
694 	if (ret) {
695 		kthread_stop(thread);
696 		pr_warn("%s: failed to set SCHED_DEADLINE\n", __func__);
697 		return ret;
698 	}
699 
700 	sg_policy->thread = thread;
701 	if (policy->dvfs_possible_from_any_cpu)
702 		set_cpus_allowed_ptr(thread, policy->related_cpus);
703 	else
704 		kthread_bind_mask(thread, policy->related_cpus);
705 
706 	init_irq_work(&sg_policy->irq_work, sugov_irq_work);
707 	mutex_init(&sg_policy->work_lock);
708 
709 	wake_up_process(thread);
710 
711 	return 0;
712 }
713 
714 static void sugov_kthread_stop(struct sugov_policy *sg_policy)
715 {
716 	/* kthread only required for slow path */
717 	if (sg_policy->policy->fast_switch_enabled)
718 		return;
719 
720 	kthread_flush_worker(&sg_policy->worker);
721 	kthread_stop(sg_policy->thread);
722 	mutex_destroy(&sg_policy->work_lock);
723 }
724 
725 static struct sugov_tunables *sugov_tunables_alloc(struct sugov_policy *sg_policy)
726 {
727 	struct sugov_tunables *tunables;
728 
729 	tunables = kzalloc_obj(*tunables);
730 	if (tunables) {
731 		gov_attr_set_init(&tunables->attr_set, &sg_policy->tunables_hook);
732 		if (!have_governor_per_policy())
733 			global_tunables = tunables;
734 	}
735 	return tunables;
736 }
737 
738 static void sugov_clear_global_tunables(void)
739 {
740 	if (!have_governor_per_policy())
741 		global_tunables = NULL;
742 }
743 
744 static int sugov_init(struct cpufreq_policy *policy)
745 {
746 	struct sugov_policy *sg_policy;
747 	struct sugov_tunables *tunables;
748 	int ret = 0;
749 
750 	/* State should be equivalent to EXIT */
751 	if (policy->governor_data)
752 		return -EBUSY;
753 
754 	cpufreq_enable_fast_switch(policy);
755 
756 	sg_policy = sugov_policy_alloc(policy);
757 	if (!sg_policy) {
758 		ret = -ENOMEM;
759 		goto disable_fast_switch;
760 	}
761 
762 	ret = sugov_kthread_create(sg_policy);
763 	if (ret)
764 		goto free_sg_policy;
765 
766 	mutex_lock(&global_tunables_lock);
767 
768 	if (global_tunables) {
769 		if (WARN_ON(have_governor_per_policy())) {
770 			ret = -EINVAL;
771 			goto stop_kthread;
772 		}
773 		policy->governor_data = sg_policy;
774 		sg_policy->tunables = global_tunables;
775 
776 		gov_attr_set_get(&global_tunables->attr_set, &sg_policy->tunables_hook);
777 		goto out;
778 	}
779 
780 	tunables = sugov_tunables_alloc(sg_policy);
781 	if (!tunables) {
782 		ret = -ENOMEM;
783 		goto stop_kthread;
784 	}
785 
786 	tunables->rate_limit_us = cpufreq_policy_transition_delay_us(policy);
787 
788 	policy->governor_data = sg_policy;
789 	sg_policy->tunables = tunables;
790 
791 	ret = kobject_init_and_add(&tunables->attr_set.kobj, &sugov_tunables_ktype,
792 				   get_governor_parent_kobj(policy), "%s",
793 				   schedutil_gov.name);
794 	if (ret)
795 		goto fail;
796 
797 out:
798 	/*
799 	 * Schedutil is the preferred governor for EAS, so rebuild sched domains
800 	 * on governor changes to make sure the scheduler knows about them.
801 	 */
802 	em_rebuild_sched_domains();
803 	mutex_unlock(&global_tunables_lock);
804 	return 0;
805 
806 fail:
807 	kobject_put(&tunables->attr_set.kobj);
808 	policy->governor_data = NULL;
809 	sugov_clear_global_tunables();
810 
811 stop_kthread:
812 	sugov_kthread_stop(sg_policy);
813 	mutex_unlock(&global_tunables_lock);
814 
815 free_sg_policy:
816 	sugov_policy_free(sg_policy);
817 
818 disable_fast_switch:
819 	cpufreq_disable_fast_switch(policy);
820 
821 	pr_err("initialization failed (error %d)\n", ret);
822 	return ret;
823 }
824 
825 static void sugov_exit(struct cpufreq_policy *policy)
826 {
827 	struct sugov_policy *sg_policy = policy->governor_data;
828 	struct sugov_tunables *tunables = sg_policy->tunables;
829 	unsigned int count;
830 
831 	mutex_lock(&global_tunables_lock);
832 
833 	count = gov_attr_set_put(&tunables->attr_set, &sg_policy->tunables_hook);
834 	policy->governor_data = NULL;
835 	if (!count)
836 		sugov_clear_global_tunables();
837 
838 	mutex_unlock(&global_tunables_lock);
839 
840 	sugov_kthread_stop(sg_policy);
841 	sugov_policy_free(sg_policy);
842 	cpufreq_disable_fast_switch(policy);
843 
844 	em_rebuild_sched_domains();
845 }
846 
847 static int sugov_start(struct cpufreq_policy *policy)
848 {
849 	struct sugov_policy *sg_policy = policy->governor_data;
850 	void (*uu)(struct update_util_data *data, u64 time, unsigned int flags);
851 	unsigned int cpu;
852 
853 	sg_policy->freq_update_delay_ns	= sg_policy->tunables->rate_limit_us * NSEC_PER_USEC;
854 	sg_policy->last_freq_update_time	= 0;
855 	sg_policy->next_freq			= 0;
856 	sg_policy->work_in_progress		= false;
857 	sg_policy->limits_changed		= false;
858 	sg_policy->cached_raw_freq		= 0;
859 
860 	sg_policy->need_freq_update = cpufreq_driver_test_flags(CPUFREQ_NEED_UPDATE_LIMITS);
861 
862 	if (policy_is_shared(policy))
863 		uu = sugov_update_shared;
864 	else if (policy->fast_switch_enabled && cpufreq_driver_has_adjust_perf())
865 		uu = sugov_update_single_perf;
866 	else
867 		uu = sugov_update_single_freq;
868 
869 	for_each_cpu(cpu, policy->cpus) {
870 		struct sugov_cpu *sg_cpu = &per_cpu(sugov_cpu, cpu);
871 
872 		memset(sg_cpu, 0, sizeof(*sg_cpu));
873 		sg_cpu->cpu = cpu;
874 		sg_cpu->sg_policy = sg_policy;
875 	}
876 
877 	/*
878 	 * Publish the hooks only after all per-CPU data is initialized, so a
879 	 * shared policy's sugov_update_shared() never reads an uninitialized
880 	 * sibling sugov_cpu.
881 	 */
882 	for_each_cpu(cpu, policy->cpus) {
883 		struct sugov_cpu *sg_cpu = &per_cpu(sugov_cpu, cpu);
884 
885 		cpufreq_add_update_util_hook(cpu, &sg_cpu->update_util, uu);
886 	}
887 
888 	return 0;
889 }
890 
891 static void sugov_stop(struct cpufreq_policy *policy)
892 {
893 	struct sugov_policy *sg_policy = policy->governor_data;
894 	unsigned int cpu;
895 
896 	for_each_cpu(cpu, policy->cpus)
897 		cpufreq_remove_update_util_hook(cpu);
898 
899 	synchronize_rcu();
900 
901 	if (!policy->fast_switch_enabled) {
902 		irq_work_sync(&sg_policy->irq_work);
903 		kthread_cancel_work_sync(&sg_policy->work);
904 	}
905 }
906 
907 static void sugov_limits(struct cpufreq_policy *policy)
908 {
909 	struct sugov_policy *sg_policy = policy->governor_data;
910 
911 	if (!policy->fast_switch_enabled) {
912 		mutex_lock(&sg_policy->work_lock);
913 		cpufreq_policy_apply_limits(policy);
914 		mutex_unlock(&sg_policy->work_lock);
915 	}
916 
917 	/*
918 	 * The limits_changed update below must take place before the updates
919 	 * of policy limits in cpufreq_set_policy() or a policy limits update
920 	 * might be missed, so use a memory barrier to ensure it.
921 	 *
922 	 * This pairs with the memory barrier in sugov_should_update_freq().
923 	 */
924 	smp_wmb();
925 
926 	WRITE_ONCE(sg_policy->limits_changed, true);
927 }
928 
929 static struct cpufreq_governor schedutil_gov = {
930 	.name			= "schedutil",
931 	.owner			= THIS_MODULE,
932 	.flags			= CPUFREQ_GOV_DYNAMIC_SWITCHING,
933 	.init			= sugov_init,
934 	.exit			= sugov_exit,
935 	.start			= sugov_start,
936 	.stop			= sugov_stop,
937 	.limits			= sugov_limits,
938 };
939 
940 #ifdef CONFIG_CPU_FREQ_DEFAULT_GOV_SCHEDUTIL
941 struct cpufreq_governor *cpufreq_default_governor(void)
942 {
943 	return &schedutil_gov;
944 }
945 #endif
946 
947 bool sugov_is_governor(struct cpufreq_policy *policy)
948 {
949 	return policy->governor == &schedutil_gov;
950 }
951 
952 cpufreq_governor_init(schedutil_gov);
953