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