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