• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  kernel/sched/core.c
4  *
5  *  Core kernel scheduler code and related syscalls
6  *
7  *  Copyright (C) 1991-2002  Linus Torvalds
8  */
9 #include <linux/highmem.h>
10 #include <linux/hrtimer_api.h>
11 #include <linux/ktime_api.h>
12 #include <linux/sched/signal.h>
13 #include <linux/syscalls_api.h>
14 #include <linux/debug_locks.h>
15 #include <linux/prefetch.h>
16 #include <linux/capability.h>
17 #include <linux/pgtable_api.h>
18 #include <linux/wait_bit.h>
19 #include <linux/jiffies.h>
20 #include <linux/spinlock_api.h>
21 #include <linux/cpumask_api.h>
22 #include <linux/lockdep_api.h>
23 #include <linux/hardirq.h>
24 #include <linux/softirq.h>
25 #include <linux/refcount_api.h>
26 #include <linux/topology.h>
27 #include <linux/sched/clock.h>
28 #include <linux/sched/cond_resched.h>
29 #include <linux/sched/cputime.h>
30 #include <linux/sched/debug.h>
31 #include <linux/sched/hotplug.h>
32 #include <linux/sched/init.h>
33 #include <linux/sched/isolation.h>
34 #include <linux/sched/loadavg.h>
35 #include <linux/sched/mm.h>
36 #include <linux/sched/nohz.h>
37 #include <linux/sched/rseq_api.h>
38 #include <linux/sched/rt.h>
39 
40 #include <linux/blkdev.h>
41 #include <linux/context_tracking.h>
42 #include <linux/cpuset.h>
43 #include <linux/delayacct.h>
44 #include <linux/init_task.h>
45 #include <linux/interrupt.h>
46 #include <linux/ioprio.h>
47 #include <linux/kallsyms.h>
48 #include <linux/kcov.h>
49 #include <linux/kprobes.h>
50 #include <linux/llist_api.h>
51 #include <linux/mmu_context.h>
52 #include <linux/mmzone.h>
53 #include <linux/mutex_api.h>
54 #include <linux/nmi.h>
55 #include <linux/nospec.h>
56 #include <linux/perf_event_api.h>
57 #include <linux/profile.h>
58 #include <linux/psi.h>
59 #include <linux/rcuwait_api.h>
60 #include <linux/sched/wake_q.h>
61 #include <linux/scs.h>
62 #include <linux/slab.h>
63 #include <linux/syscalls.h>
64 #include <linux/vtime.h>
65 #include <linux/wait_api.h>
66 #include <linux/workqueue_api.h>
67 
68 #ifdef CONFIG_PREEMPT_DYNAMIC
69 # ifdef CONFIG_GENERIC_ENTRY
70 #  include <linux/entry-common.h>
71 # endif
72 #endif
73 
74 #include <uapi/linux/sched/types.h>
75 
76 #include <asm/irq_regs.h>
77 #include <asm/switch_to.h>
78 #include <asm/tlb.h>
79 
80 #define CREATE_TRACE_POINTS
81 #include <linux/sched/rseq_api.h>
82 #include <trace/events/sched.h>
83 #include <trace/events/ipi.h>
84 #undef CREATE_TRACE_POINTS
85 
86 #include "sched.h"
87 #include "stats.h"
88 #include "autogroup.h"
89 
90 #include "autogroup.h"
91 #include "pelt.h"
92 #include "smp.h"
93 #include "stats.h"
94 
95 #include "../workqueue_internal.h"
96 #include "../../io_uring/io-wq.h"
97 #include "../smpboot.h"
98 
99 #include <trace/hooks/sched.h>
100 #include <trace/hooks/cgroup.h>
101 #include <trace/hooks/dtask.h>
102 
103 EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpu);
104 EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpumask);
105 
106 /*
107  * Export tracepoints that act as a bare tracehook (ie: have no trace event
108  * associated with them) to allow external modules to probe them.
109  */
110 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp);
111 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp);
112 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp);
113 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp);
114 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp);
115 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_thermal_tp);
116 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp);
117 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp);
118 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp);
119 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp);
120 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp);
121 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_switch);
122 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_waking);
123 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_wakeup);
124 #if defined(CONFIG_SCHEDSTATS)
125 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_stat_sleep);
126 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_stat_wait);
127 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_stat_iowait);
128 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_stat_blocked);
129 #endif
130 
131 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
132 EXPORT_SYMBOL_GPL(runqueues);
133 
134 #ifdef CONFIG_SCHED_DEBUG
135 /*
136  * Debugging: various feature bits
137  *
138  * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
139  * sysctl_sched_features, defined in sched.h, to allow constants propagation
140  * at compile time and compiler optimization based on features default.
141  */
142 #define SCHED_FEAT(name, enabled)	\
143 	(1UL << __SCHED_FEAT_##name) * enabled |
144 const_debug unsigned int sysctl_sched_features =
145 #include "features.h"
146 	0;
147 EXPORT_SYMBOL_GPL(sysctl_sched_features);
148 #undef SCHED_FEAT
149 
150 /*
151  * Print a warning if need_resched is set for the given duration (if
152  * LATENCY_WARN is enabled).
153  *
154  * If sysctl_resched_latency_warn_once is set, only one warning will be shown
155  * per boot.
156  */
157 __read_mostly int sysctl_resched_latency_warn_ms = 100;
158 __read_mostly int sysctl_resched_latency_warn_once = 1;
159 #endif /* CONFIG_SCHED_DEBUG */
160 
161 /*
162  * Number of tasks to iterate in a single balance run.
163  * Limited because this is done with IRQs disabled.
164  */
165 const_debug unsigned int sysctl_sched_nr_migrate = SCHED_NR_MIGRATE_BREAK;
166 
167 __read_mostly int scheduler_running;
168 
169 #ifdef CONFIG_SCHED_CORE
170 
171 DEFINE_STATIC_KEY_FALSE(__sched_core_enabled);
172 
173 /* kernel prio, less is more */
__task_prio(const struct task_struct * p)174 static inline int __task_prio(const struct task_struct *p)
175 {
176 	if (p->sched_class == &stop_sched_class) /* trumps deadline */
177 		return -2;
178 
179 	if (rt_prio(p->prio)) /* includes deadline */
180 		return p->prio; /* [-1, 99] */
181 
182 	if (p->sched_class == &idle_sched_class)
183 		return MAX_RT_PRIO + NICE_WIDTH; /* 140 */
184 
185 	return MAX_RT_PRIO + MAX_NICE; /* 120, squash fair */
186 }
187 
188 /*
189  * l(a,b)
190  * le(a,b) := !l(b,a)
191  * g(a,b)  := l(b,a)
192  * ge(a,b) := !l(a,b)
193  */
194 
195 /* real prio, less is less */
prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)196 static inline bool prio_less(const struct task_struct *a,
197 			     const struct task_struct *b, bool in_fi)
198 {
199 
200 	int pa = __task_prio(a), pb = __task_prio(b);
201 
202 	if (-pa < -pb)
203 		return true;
204 
205 	if (-pb < -pa)
206 		return false;
207 
208 	if (pa == -1) /* dl_prio() doesn't work because of stop_class above */
209 		return !dl_time_before(a->dl.deadline, b->dl.deadline);
210 
211 	if (pa == MAX_RT_PRIO + MAX_NICE)	/* fair */
212 		return cfs_prio_less(a, b, in_fi);
213 
214 	return false;
215 }
216 
__sched_core_less(const struct task_struct * a,const struct task_struct * b)217 static inline bool __sched_core_less(const struct task_struct *a,
218 				     const struct task_struct *b)
219 {
220 	if (a->core_cookie < b->core_cookie)
221 		return true;
222 
223 	if (a->core_cookie > b->core_cookie)
224 		return false;
225 
226 	/* flip prio, so high prio is leftmost */
227 	if (prio_less(b, a, !!task_rq(a)->core->core_forceidle_count))
228 		return true;
229 
230 	return false;
231 }
232 
233 #define __node_2_sc(node) rb_entry((node), struct task_struct, core_node)
234 
rb_sched_core_less(struct rb_node * a,const struct rb_node * b)235 static inline bool rb_sched_core_less(struct rb_node *a, const struct rb_node *b)
236 {
237 	return __sched_core_less(__node_2_sc(a), __node_2_sc(b));
238 }
239 
rb_sched_core_cmp(const void * key,const struct rb_node * node)240 static inline int rb_sched_core_cmp(const void *key, const struct rb_node *node)
241 {
242 	const struct task_struct *p = __node_2_sc(node);
243 	unsigned long cookie = (unsigned long)key;
244 
245 	if (cookie < p->core_cookie)
246 		return -1;
247 
248 	if (cookie > p->core_cookie)
249 		return 1;
250 
251 	return 0;
252 }
253 
sched_core_enqueue(struct rq * rq,struct task_struct * p)254 void sched_core_enqueue(struct rq *rq, struct task_struct *p)
255 {
256 	rq->core->core_task_seq++;
257 
258 	if (!p->core_cookie)
259 		return;
260 
261 	rb_add(&p->core_node, &rq->core_tree, rb_sched_core_less);
262 }
263 
sched_core_dequeue(struct rq * rq,struct task_struct * p,int flags)264 void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags)
265 {
266 	rq->core->core_task_seq++;
267 
268 	if (sched_core_enqueued(p)) {
269 		rb_erase(&p->core_node, &rq->core_tree);
270 		RB_CLEAR_NODE(&p->core_node);
271 	}
272 
273 	/*
274 	 * Migrating the last task off the cpu, with the cpu in forced idle
275 	 * state. Reschedule to create an accounting edge for forced idle,
276 	 * and re-examine whether the core is still in forced idle state.
277 	 */
278 	if (!(flags & DEQUEUE_SAVE) && rq->nr_running == 1 &&
279 	    rq->core->core_forceidle_count && rq->curr == rq->idle)
280 		resched_curr(rq);
281 }
282 
sched_task_is_throttled(struct task_struct * p,int cpu)283 static int sched_task_is_throttled(struct task_struct *p, int cpu)
284 {
285 	if (p->sched_class->task_is_throttled)
286 		return p->sched_class->task_is_throttled(p, cpu);
287 
288 	return 0;
289 }
290 
sched_core_next(struct task_struct * p,unsigned long cookie)291 static struct task_struct *sched_core_next(struct task_struct *p, unsigned long cookie)
292 {
293 	struct rb_node *node = &p->core_node;
294 	int cpu = task_cpu(p);
295 
296 	do {
297 		node = rb_next(node);
298 		if (!node)
299 			return NULL;
300 
301 		p = __node_2_sc(node);
302 		if (p->core_cookie != cookie)
303 			return NULL;
304 
305 	} while (sched_task_is_throttled(p, cpu));
306 
307 	return p;
308 }
309 
310 /*
311  * Find left-most (aka, highest priority) and unthrottled task matching @cookie.
312  * If no suitable task is found, NULL will be returned.
313  */
sched_core_find(struct rq * rq,unsigned long cookie)314 static struct task_struct *sched_core_find(struct rq *rq, unsigned long cookie)
315 {
316 	struct task_struct *p;
317 	struct rb_node *node;
318 
319 	node = rb_find_first((void *)cookie, &rq->core_tree, rb_sched_core_cmp);
320 	if (!node)
321 		return NULL;
322 
323 	p = __node_2_sc(node);
324 	if (!sched_task_is_throttled(p, rq->cpu))
325 		return p;
326 
327 	return sched_core_next(p, cookie);
328 }
329 
330 /*
331  * Magic required such that:
332  *
333  *	raw_spin_rq_lock(rq);
334  *	...
335  *	raw_spin_rq_unlock(rq);
336  *
337  * ends up locking and unlocking the _same_ lock, and all CPUs
338  * always agree on what rq has what lock.
339  *
340  * XXX entirely possible to selectively enable cores, don't bother for now.
341  */
342 
343 static DEFINE_MUTEX(sched_core_mutex);
344 static atomic_t sched_core_count;
345 static struct cpumask sched_core_mask;
346 
sched_core_lock(int cpu,unsigned long * flags)347 static void sched_core_lock(int cpu, unsigned long *flags)
348 {
349 	const struct cpumask *smt_mask = cpu_smt_mask(cpu);
350 	int t, i = 0;
351 
352 	local_irq_save(*flags);
353 	for_each_cpu(t, smt_mask)
354 		raw_spin_lock_nested(&cpu_rq(t)->__lock, i++);
355 }
356 
sched_core_unlock(int cpu,unsigned long * flags)357 static void sched_core_unlock(int cpu, unsigned long *flags)
358 {
359 	const struct cpumask *smt_mask = cpu_smt_mask(cpu);
360 	int t;
361 
362 	for_each_cpu(t, smt_mask)
363 		raw_spin_unlock(&cpu_rq(t)->__lock);
364 	local_irq_restore(*flags);
365 }
366 
__sched_core_flip(bool enabled)367 static void __sched_core_flip(bool enabled)
368 {
369 	unsigned long flags;
370 	int cpu, t;
371 
372 	cpus_read_lock();
373 
374 	/*
375 	 * Toggle the online cores, one by one.
376 	 */
377 	cpumask_copy(&sched_core_mask, cpu_online_mask);
378 	for_each_cpu(cpu, &sched_core_mask) {
379 		const struct cpumask *smt_mask = cpu_smt_mask(cpu);
380 
381 		sched_core_lock(cpu, &flags);
382 
383 		for_each_cpu(t, smt_mask)
384 			cpu_rq(t)->core_enabled = enabled;
385 
386 		cpu_rq(cpu)->core->core_forceidle_start = 0;
387 
388 		sched_core_unlock(cpu, &flags);
389 
390 		cpumask_andnot(&sched_core_mask, &sched_core_mask, smt_mask);
391 	}
392 
393 	/*
394 	 * Toggle the offline CPUs.
395 	 */
396 	for_each_cpu_andnot(cpu, cpu_possible_mask, cpu_online_mask)
397 		cpu_rq(cpu)->core_enabled = enabled;
398 
399 	cpus_read_unlock();
400 }
401 
sched_core_assert_empty(void)402 static void sched_core_assert_empty(void)
403 {
404 	int cpu;
405 
406 	for_each_possible_cpu(cpu)
407 		WARN_ON_ONCE(!RB_EMPTY_ROOT(&cpu_rq(cpu)->core_tree));
408 }
409 
__sched_core_enable(void)410 static void __sched_core_enable(void)
411 {
412 	static_branch_enable(&__sched_core_enabled);
413 	/*
414 	 * Ensure all previous instances of raw_spin_rq_*lock() have finished
415 	 * and future ones will observe !sched_core_disabled().
416 	 */
417 	synchronize_rcu();
418 	__sched_core_flip(true);
419 	sched_core_assert_empty();
420 }
421 
__sched_core_disable(void)422 static void __sched_core_disable(void)
423 {
424 	sched_core_assert_empty();
425 	__sched_core_flip(false);
426 	static_branch_disable(&__sched_core_enabled);
427 }
428 
sched_core_get(void)429 void sched_core_get(void)
430 {
431 	if (atomic_inc_not_zero(&sched_core_count))
432 		return;
433 
434 	mutex_lock(&sched_core_mutex);
435 	if (!atomic_read(&sched_core_count))
436 		__sched_core_enable();
437 
438 	smp_mb__before_atomic();
439 	atomic_inc(&sched_core_count);
440 	mutex_unlock(&sched_core_mutex);
441 }
442 
__sched_core_put(struct work_struct * work)443 static void __sched_core_put(struct work_struct *work)
444 {
445 	if (atomic_dec_and_mutex_lock(&sched_core_count, &sched_core_mutex)) {
446 		__sched_core_disable();
447 		mutex_unlock(&sched_core_mutex);
448 	}
449 }
450 
sched_core_put(void)451 void sched_core_put(void)
452 {
453 	static DECLARE_WORK(_work, __sched_core_put);
454 
455 	/*
456 	 * "There can be only one"
457 	 *
458 	 * Either this is the last one, or we don't actually need to do any
459 	 * 'work'. If it is the last *again*, we rely on
460 	 * WORK_STRUCT_PENDING_BIT.
461 	 */
462 	if (!atomic_add_unless(&sched_core_count, -1, 1))
463 		schedule_work(&_work);
464 }
465 
466 #else /* !CONFIG_SCHED_CORE */
467 
sched_core_enqueue(struct rq * rq,struct task_struct * p)468 static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { }
469 static inline void
sched_core_dequeue(struct rq * rq,struct task_struct * p,int flags)470 sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { }
471 
472 #endif /* CONFIG_SCHED_CORE */
473 
474 /*
475  * Serialization rules:
476  *
477  * Lock order:
478  *
479  *   p->pi_lock
480  *     rq->lock
481  *       hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
482  *
483  *  rq1->lock
484  *    rq2->lock  where: rq1 < rq2
485  *
486  * Regular state:
487  *
488  * Normal scheduling state is serialized by rq->lock. __schedule() takes the
489  * local CPU's rq->lock, it optionally removes the task from the runqueue and
490  * always looks at the local rq data structures to find the most eligible task
491  * to run next.
492  *
493  * Task enqueue is also under rq->lock, possibly taken from another CPU.
494  * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
495  * the local CPU to avoid bouncing the runqueue state around [ see
496  * ttwu_queue_wakelist() ]
497  *
498  * Task wakeup, specifically wakeups that involve migration, are horribly
499  * complicated to avoid having to take two rq->locks.
500  *
501  * Special state:
502  *
503  * System-calls and anything external will use task_rq_lock() which acquires
504  * both p->pi_lock and rq->lock. As a consequence the state they change is
505  * stable while holding either lock:
506  *
507  *  - sched_setaffinity()/
508  *    set_cpus_allowed_ptr():	p->cpus_ptr, p->nr_cpus_allowed
509  *  - set_user_nice():		p->se.load, p->*prio
510  *  - __sched_setscheduler():	p->sched_class, p->policy, p->*prio,
511  *				p->se.load, p->rt_priority,
512  *				p->dl.dl_{runtime, deadline, period, flags, bw, density}
513  *  - sched_setnuma():		p->numa_preferred_nid
514  *  - sched_move_task():	p->sched_task_group
515  *  - uclamp_update_active()	p->uclamp*
516  *
517  * p->state <- TASK_*:
518  *
519  *   is changed locklessly using set_current_state(), __set_current_state() or
520  *   set_special_state(), see their respective comments, or by
521  *   try_to_wake_up(). This latter uses p->pi_lock to serialize against
522  *   concurrent self.
523  *
524  * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
525  *
526  *   is set by activate_task() and cleared by deactivate_task(), under
527  *   rq->lock. Non-zero indicates the task is runnable, the special
528  *   ON_RQ_MIGRATING state is used for migration without holding both
529  *   rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
530  *
531  * p->on_cpu <- { 0, 1 }:
532  *
533  *   is set by prepare_task() and cleared by finish_task() such that it will be
534  *   set before p is scheduled-in and cleared after p is scheduled-out, both
535  *   under rq->lock. Non-zero indicates the task is running on its CPU.
536  *
537  *   [ The astute reader will observe that it is possible for two tasks on one
538  *     CPU to have ->on_cpu = 1 at the same time. ]
539  *
540  * task_cpu(p): is changed by set_task_cpu(), the rules are:
541  *
542  *  - Don't call set_task_cpu() on a blocked task:
543  *
544  *    We don't care what CPU we're not running on, this simplifies hotplug,
545  *    the CPU assignment of blocked tasks isn't required to be valid.
546  *
547  *  - for try_to_wake_up(), called under p->pi_lock:
548  *
549  *    This allows try_to_wake_up() to only take one rq->lock, see its comment.
550  *
551  *  - for migration called under rq->lock:
552  *    [ see task_on_rq_migrating() in task_rq_lock() ]
553  *
554  *    o move_queued_task()
555  *    o detach_task()
556  *
557  *  - for migration called under double_rq_lock():
558  *
559  *    o __migrate_swap_task()
560  *    o push_rt_task() / pull_rt_task()
561  *    o push_dl_task() / pull_dl_task()
562  *    o dl_task_offline_migration()
563  *
564  */
565 
raw_spin_rq_lock_nested(struct rq * rq,int subclass)566 void raw_spin_rq_lock_nested(struct rq *rq, int subclass)
567 {
568 	raw_spinlock_t *lock;
569 
570 	/* Matches synchronize_rcu() in __sched_core_enable() */
571 	preempt_disable();
572 	if (sched_core_disabled()) {
573 		raw_spin_lock_nested(&rq->__lock, subclass);
574 		/* preempt_count *MUST* be > 1 */
575 		preempt_enable_no_resched();
576 		return;
577 	}
578 
579 	for (;;) {
580 		lock = __rq_lockp(rq);
581 		raw_spin_lock_nested(lock, subclass);
582 		if (likely(lock == __rq_lockp(rq))) {
583 			/* preempt_count *MUST* be > 1 */
584 			preempt_enable_no_resched();
585 			return;
586 		}
587 		raw_spin_unlock(lock);
588 	}
589 }
590 EXPORT_SYMBOL_GPL(raw_spin_rq_lock_nested);
591 
raw_spin_rq_trylock(struct rq * rq)592 bool raw_spin_rq_trylock(struct rq *rq)
593 {
594 	raw_spinlock_t *lock;
595 	bool ret;
596 
597 	/* Matches synchronize_rcu() in __sched_core_enable() */
598 	preempt_disable();
599 	if (sched_core_disabled()) {
600 		ret = raw_spin_trylock(&rq->__lock);
601 		preempt_enable();
602 		return ret;
603 	}
604 
605 	for (;;) {
606 		lock = __rq_lockp(rq);
607 		ret = raw_spin_trylock(lock);
608 		if (!ret || (likely(lock == __rq_lockp(rq)))) {
609 			preempt_enable();
610 			return ret;
611 		}
612 		raw_spin_unlock(lock);
613 	}
614 }
615 
raw_spin_rq_unlock(struct rq * rq)616 void raw_spin_rq_unlock(struct rq *rq)
617 {
618 	raw_spin_unlock(rq_lockp(rq));
619 }
620 EXPORT_SYMBOL_GPL(raw_spin_rq_unlock);
621 
622 #ifdef CONFIG_SMP
623 /*
624  * double_rq_lock - safely lock two runqueues
625  */
double_rq_lock(struct rq * rq1,struct rq * rq2)626 void double_rq_lock(struct rq *rq1, struct rq *rq2)
627 {
628 	lockdep_assert_irqs_disabled();
629 
630 	if (rq_order_less(rq2, rq1))
631 		swap(rq1, rq2);
632 
633 	raw_spin_rq_lock(rq1);
634 	if (__rq_lockp(rq1) != __rq_lockp(rq2))
635 		raw_spin_rq_lock_nested(rq2, SINGLE_DEPTH_NESTING);
636 
637 	double_rq_clock_clear_update(rq1, rq2);
638 }
639 EXPORT_SYMBOL_GPL(double_rq_lock);
640 #endif
641 
642 /*
643  * __task_rq_lock - lock the rq @p resides on.
644  */
__task_rq_lock(struct task_struct * p,struct rq_flags * rf)645 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
646 	__acquires(rq->lock)
647 {
648 	struct rq *rq;
649 
650 	lockdep_assert_held(&p->pi_lock);
651 
652 	for (;;) {
653 		rq = task_rq(p);
654 		raw_spin_rq_lock(rq);
655 		if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
656 			rq_pin_lock(rq, rf);
657 			return rq;
658 		}
659 		raw_spin_rq_unlock(rq);
660 
661 		while (unlikely(task_on_rq_migrating(p)))
662 			cpu_relax();
663 	}
664 }
665 EXPORT_SYMBOL_GPL(__task_rq_lock);
666 
667 /*
668  * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
669  */
task_rq_lock(struct task_struct * p,struct rq_flags * rf)670 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
671 	__acquires(p->pi_lock)
672 	__acquires(rq->lock)
673 {
674 	struct rq *rq;
675 
676 	for (;;) {
677 		raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
678 		rq = task_rq(p);
679 		raw_spin_rq_lock(rq);
680 		/*
681 		 *	move_queued_task()		task_rq_lock()
682 		 *
683 		 *	ACQUIRE (rq->lock)
684 		 *	[S] ->on_rq = MIGRATING		[L] rq = task_rq()
685 		 *	WMB (__set_task_cpu())		ACQUIRE (rq->lock);
686 		 *	[S] ->cpu = new_cpu		[L] task_rq()
687 		 *					[L] ->on_rq
688 		 *	RELEASE (rq->lock)
689 		 *
690 		 * If we observe the old CPU in task_rq_lock(), the acquire of
691 		 * the old rq->lock will fully serialize against the stores.
692 		 *
693 		 * If we observe the new CPU in task_rq_lock(), the address
694 		 * dependency headed by '[L] rq = task_rq()' and the acquire
695 		 * will pair with the WMB to ensure we then also see migrating.
696 		 */
697 		if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
698 			rq_pin_lock(rq, rf);
699 			return rq;
700 		}
701 		raw_spin_rq_unlock(rq);
702 		raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
703 
704 		while (unlikely(task_on_rq_migrating(p)))
705 			cpu_relax();
706 	}
707 }
708 EXPORT_SYMBOL_GPL(task_rq_lock);
709 
710 /*
711  * RQ-clock updating methods:
712  */
713 
update_rq_clock_task(struct rq * rq,s64 delta)714 static void update_rq_clock_task(struct rq *rq, s64 delta)
715 {
716 /*
717  * In theory, the compile should just see 0 here, and optimize out the call
718  * to sched_rt_avg_update. But I don't trust it...
719  */
720 	s64 __maybe_unused steal = 0, irq_delta = 0;
721 
722 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
723 	irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
724 
725 	/*
726 	 * Since irq_time is only updated on {soft,}irq_exit, we might run into
727 	 * this case when a previous update_rq_clock() happened inside a
728 	 * {soft,}irq region.
729 	 *
730 	 * When this happens, we stop ->clock_task and only update the
731 	 * prev_irq_time stamp to account for the part that fit, so that a next
732 	 * update will consume the rest. This ensures ->clock_task is
733 	 * monotonic.
734 	 *
735 	 * It does however cause some slight miss-attribution of {soft,}irq
736 	 * time, a more accurate solution would be to update the irq_time using
737 	 * the current rq->clock timestamp, except that would require using
738 	 * atomic ops.
739 	 */
740 	if (irq_delta > delta)
741 		irq_delta = delta;
742 
743 	rq->prev_irq_time += irq_delta;
744 	delta -= irq_delta;
745 	delayacct_irq(rq->curr, irq_delta);
746 #endif
747 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
748 	if (static_key_false((&paravirt_steal_rq_enabled))) {
749 		steal = paravirt_steal_clock(cpu_of(rq));
750 		steal -= rq->prev_steal_time_rq;
751 
752 		if (unlikely(steal > delta))
753 			steal = delta;
754 
755 		rq->prev_steal_time_rq += steal;
756 		delta -= steal;
757 	}
758 #endif
759 
760 	rq->clock_task += delta;
761 
762 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
763 	if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
764 		update_irq_load_avg(rq, irq_delta + steal);
765 #endif
766 	update_rq_clock_task_mult(rq, delta);
767 }
768 
update_rq_clock(struct rq * rq)769 void update_rq_clock(struct rq *rq)
770 {
771 	s64 delta;
772 
773 	lockdep_assert_rq_held(rq);
774 
775 	if (rq->clock_update_flags & RQCF_ACT_SKIP)
776 		return;
777 
778 #ifdef CONFIG_SCHED_DEBUG
779 	if (sched_feat(WARN_DOUBLE_CLOCK))
780 		SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
781 	rq->clock_update_flags |= RQCF_UPDATED;
782 #endif
783 
784 	delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
785 	if (delta < 0)
786 		return;
787 	rq->clock += delta;
788 	update_rq_clock_task(rq, delta);
789 }
790 EXPORT_SYMBOL_GPL(update_rq_clock);
791 
792 #ifdef CONFIG_SCHED_HRTICK
793 /*
794  * Use HR-timers to deliver accurate preemption points.
795  */
796 
hrtick_clear(struct rq * rq)797 static void hrtick_clear(struct rq *rq)
798 {
799 	if (hrtimer_active(&rq->hrtick_timer))
800 		hrtimer_cancel(&rq->hrtick_timer);
801 }
802 
803 /*
804  * High-resolution timer tick.
805  * Runs from hardirq context with interrupts disabled.
806  */
hrtick(struct hrtimer * timer)807 static enum hrtimer_restart hrtick(struct hrtimer *timer)
808 {
809 	struct rq *rq = container_of(timer, struct rq, hrtick_timer);
810 	struct rq_flags rf;
811 
812 	WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
813 
814 	rq_lock(rq, &rf);
815 	update_rq_clock(rq);
816 	rq->curr->sched_class->task_tick(rq, rq->curr, 1);
817 	rq_unlock(rq, &rf);
818 
819 	return HRTIMER_NORESTART;
820 }
821 
822 #ifdef CONFIG_SMP
823 
__hrtick_restart(struct rq * rq)824 static void __hrtick_restart(struct rq *rq)
825 {
826 	struct hrtimer *timer = &rq->hrtick_timer;
827 	ktime_t time = rq->hrtick_time;
828 
829 	hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD);
830 }
831 
832 /*
833  * called from hardirq (IPI) context
834  */
__hrtick_start(void * arg)835 static void __hrtick_start(void *arg)
836 {
837 	struct rq *rq = arg;
838 	struct rq_flags rf;
839 
840 	rq_lock(rq, &rf);
841 	__hrtick_restart(rq);
842 	rq_unlock(rq, &rf);
843 }
844 
845 /*
846  * Called to set the hrtick timer state.
847  *
848  * called with rq->lock held and irqs disabled
849  */
hrtick_start(struct rq * rq,u64 delay)850 void hrtick_start(struct rq *rq, u64 delay)
851 {
852 	struct hrtimer *timer = &rq->hrtick_timer;
853 	s64 delta;
854 
855 	/*
856 	 * Don't schedule slices shorter than 10000ns, that just
857 	 * doesn't make sense and can cause timer DoS.
858 	 */
859 	delta = max_t(s64, delay, 10000LL);
860 	rq->hrtick_time = ktime_add_ns(timer->base->get_time(), delta);
861 
862 	if (rq == this_rq())
863 		__hrtick_restart(rq);
864 	else
865 		smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
866 }
867 
868 #else
869 /*
870  * Called to set the hrtick timer state.
871  *
872  * called with rq->lock held and irqs disabled
873  */
hrtick_start(struct rq * rq,u64 delay)874 void hrtick_start(struct rq *rq, u64 delay)
875 {
876 	/*
877 	 * Don't schedule slices shorter than 10000ns, that just
878 	 * doesn't make sense. Rely on vruntime for fairness.
879 	 */
880 	delay = max_t(u64, delay, 10000LL);
881 	hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
882 		      HRTIMER_MODE_REL_PINNED_HARD);
883 }
884 
885 #endif /* CONFIG_SMP */
886 
hrtick_rq_init(struct rq * rq)887 static void hrtick_rq_init(struct rq *rq)
888 {
889 #ifdef CONFIG_SMP
890 	INIT_CSD(&rq->hrtick_csd, __hrtick_start, rq);
891 #endif
892 	hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
893 	rq->hrtick_timer.function = hrtick;
894 }
895 #else	/* CONFIG_SCHED_HRTICK */
hrtick_clear(struct rq * rq)896 static inline void hrtick_clear(struct rq *rq)
897 {
898 }
899 
hrtick_rq_init(struct rq * rq)900 static inline void hrtick_rq_init(struct rq *rq)
901 {
902 }
903 #endif	/* CONFIG_SCHED_HRTICK */
904 
905 /*
906  * cmpxchg based fetch_or, macro so it works for different integer types
907  */
908 #define fetch_or(ptr, mask)						\
909 	({								\
910 		typeof(ptr) _ptr = (ptr);				\
911 		typeof(mask) _mask = (mask);				\
912 		typeof(*_ptr) _val = *_ptr;				\
913 									\
914 		do {							\
915 		} while (!try_cmpxchg(_ptr, &_val, _val | _mask));	\
916 	_val;								\
917 })
918 
919 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
920 /*
921  * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
922  * this avoids any races wrt polling state changes and thereby avoids
923  * spurious IPIs.
924  */
set_nr_and_not_polling(struct task_struct * p)925 static inline bool set_nr_and_not_polling(struct task_struct *p)
926 {
927 	struct thread_info *ti = task_thread_info(p);
928 	return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
929 }
930 
931 /*
932  * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
933  *
934  * If this returns true, then the idle task promises to call
935  * sched_ttwu_pending() and reschedule soon.
936  */
set_nr_if_polling(struct task_struct * p)937 static bool set_nr_if_polling(struct task_struct *p)
938 {
939 	struct thread_info *ti = task_thread_info(p);
940 	typeof(ti->flags) val = READ_ONCE(ti->flags);
941 
942 	for (;;) {
943 		if (!(val & _TIF_POLLING_NRFLAG))
944 			return false;
945 		if (val & _TIF_NEED_RESCHED)
946 			return true;
947 		if (try_cmpxchg(&ti->flags, &val, val | _TIF_NEED_RESCHED))
948 			break;
949 	}
950 	return true;
951 }
952 
953 #else
set_nr_and_not_polling(struct task_struct * p)954 static inline bool set_nr_and_not_polling(struct task_struct *p)
955 {
956 	set_tsk_need_resched(p);
957 	return true;
958 }
959 
960 #ifdef CONFIG_SMP
set_nr_if_polling(struct task_struct * p)961 static inline bool set_nr_if_polling(struct task_struct *p)
962 {
963 	return false;
964 }
965 #endif
966 #endif
967 
__wake_q_add(struct wake_q_head * head,struct task_struct * task)968 static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
969 {
970 	struct wake_q_node *node = &task->wake_q;
971 
972 	/*
973 	 * Atomically grab the task, if ->wake_q is !nil already it means
974 	 * it's already queued (either by us or someone else) and will get the
975 	 * wakeup due to that.
976 	 *
977 	 * In order to ensure that a pending wakeup will observe our pending
978 	 * state, even in the failed case, an explicit smp_mb() must be used.
979 	 */
980 	smp_mb__before_atomic();
981 	if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
982 		return false;
983 
984 	/*
985 	 * The head is context local, there can be no concurrency.
986 	 */
987 	*head->lastp = node;
988 	head->lastp = &node->next;
989 	head->count++;
990 	return true;
991 }
992 
993 /**
994  * wake_q_add() - queue a wakeup for 'later' waking.
995  * @head: the wake_q_head to add @task to
996  * @task: the task to queue for 'later' wakeup
997  *
998  * Queue a task for later wakeup, most likely by the wake_up_q() call in the
999  * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
1000  * instantly.
1001  *
1002  * This function must be used as-if it were wake_up_process(); IOW the task
1003  * must be ready to be woken at this location.
1004  */
wake_q_add(struct wake_q_head * head,struct task_struct * task)1005 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
1006 {
1007 	if (__wake_q_add(head, task))
1008 		get_task_struct(task);
1009 }
1010 
1011 /**
1012  * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
1013  * @head: the wake_q_head to add @task to
1014  * @task: the task to queue for 'later' wakeup
1015  *
1016  * Queue a task for later wakeup, most likely by the wake_up_q() call in the
1017  * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
1018  * instantly.
1019  *
1020  * This function must be used as-if it were wake_up_process(); IOW the task
1021  * must be ready to be woken at this location.
1022  *
1023  * This function is essentially a task-safe equivalent to wake_q_add(). Callers
1024  * that already hold reference to @task can call the 'safe' version and trust
1025  * wake_q to do the right thing depending whether or not the @task is already
1026  * queued for wakeup.
1027  */
wake_q_add_safe(struct wake_q_head * head,struct task_struct * task)1028 void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
1029 {
1030 	if (!__wake_q_add(head, task))
1031 		put_task_struct(task);
1032 }
1033 
wake_up_q(struct wake_q_head * head)1034 void wake_up_q(struct wake_q_head *head)
1035 {
1036 	struct wake_q_node *node = head->first;
1037 
1038 	while (node != WAKE_Q_TAIL) {
1039 		struct task_struct *task;
1040 
1041 		task = container_of(node, struct task_struct, wake_q);
1042 		/* Task can safely be re-inserted now: */
1043 		node = node->next;
1044 		task->wake_q.next = NULL;
1045 		task->wake_q_count = head->count;
1046 
1047 		/*
1048 		 * wake_up_process() executes a full barrier, which pairs with
1049 		 * the queueing in wake_q_add() so as not to miss wakeups.
1050 		 */
1051 		wake_up_process(task);
1052 		task->wake_q_count = 0;
1053 		put_task_struct(task);
1054 	}
1055 }
1056 
1057 /*
1058  * resched_curr - mark rq's current task 'to be rescheduled now'.
1059  *
1060  * On UP this means the setting of the need_resched flag, on SMP it
1061  * might also involve a cross-CPU call to trigger the scheduler on
1062  * the target CPU.
1063  */
resched_curr(struct rq * rq)1064 void resched_curr(struct rq *rq)
1065 {
1066 	struct task_struct *curr = rq->curr;
1067 	int cpu, need_lazy = 0;
1068 
1069 	lockdep_assert_rq_held(rq);
1070 
1071 	if (test_tsk_need_resched(curr))
1072 		return;
1073 
1074 	trace_android_vh_set_tsk_need_resched_lazy(curr, rq, &need_lazy);
1075 	if (need_lazy)
1076 		return;
1077 
1078 	cpu = cpu_of(rq);
1079 
1080 	if (cpu == smp_processor_id()) {
1081 		set_tsk_need_resched(curr);
1082 		set_preempt_need_resched();
1083 		return;
1084 	}
1085 
1086 	if (set_nr_and_not_polling(curr))
1087 		smp_send_reschedule(cpu);
1088 	else
1089 		trace_sched_wake_idle_without_ipi(cpu);
1090 }
1091 EXPORT_SYMBOL_GPL(resched_curr);
1092 
resched_cpu(int cpu)1093 void resched_cpu(int cpu)
1094 {
1095 	struct rq *rq = cpu_rq(cpu);
1096 	unsigned long flags;
1097 
1098 	raw_spin_rq_lock_irqsave(rq, flags);
1099 	if (cpu_online(cpu) || cpu == smp_processor_id())
1100 		resched_curr(rq);
1101 	raw_spin_rq_unlock_irqrestore(rq, flags);
1102 }
1103 
1104 #ifdef CONFIG_SMP
1105 #ifdef CONFIG_NO_HZ_COMMON
1106 /*
1107  * In the semi idle case, use the nearest busy CPU for migrating timers
1108  * from an idle CPU.  This is good for power-savings.
1109  *
1110  * We don't do similar optimization for completely idle system, as
1111  * selecting an idle CPU will add more delays to the timers than intended
1112  * (as that CPU's timer base may not be uptodate wrt jiffies etc).
1113  */
get_nohz_timer_target(void)1114 int get_nohz_timer_target(void)
1115 {
1116 	int i, cpu = smp_processor_id(), default_cpu = -1;
1117 	struct sched_domain *sd;
1118 	const struct cpumask *hk_mask;
1119 	bool done = false;
1120 
1121 	trace_android_rvh_get_nohz_timer_target(&cpu, &done);
1122 	if (done)
1123 		return cpu;
1124 
1125 	if (housekeeping_cpu(cpu, HK_TYPE_TIMER)) {
1126 		if (!idle_cpu(cpu))
1127 			return cpu;
1128 		default_cpu = cpu;
1129 	}
1130 
1131 	hk_mask = housekeeping_cpumask(HK_TYPE_TIMER);
1132 
1133 	guard(rcu)();
1134 
1135 	for_each_domain(cpu, sd) {
1136 		for_each_cpu_and(i, sched_domain_span(sd), hk_mask) {
1137 			if (cpu == i)
1138 				continue;
1139 
1140 			if (!idle_cpu(i))
1141 				return i;
1142 		}
1143 	}
1144 
1145 	if (default_cpu == -1)
1146 		default_cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
1147 
1148 	return default_cpu;
1149 }
1150 
1151 /*
1152  * When add_timer_on() enqueues a timer into the timer wheel of an
1153  * idle CPU then this timer might expire before the next timer event
1154  * which is scheduled to wake up that CPU. In case of a completely
1155  * idle system the next event might even be infinite time into the
1156  * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1157  * leaves the inner idle loop so the newly added timer is taken into
1158  * account when the CPU goes back to idle and evaluates the timer
1159  * wheel for the next timer event.
1160  */
wake_up_idle_cpu(int cpu)1161 static void wake_up_idle_cpu(int cpu)
1162 {
1163 	struct rq *rq = cpu_rq(cpu);
1164 
1165 	if (cpu == smp_processor_id())
1166 		return;
1167 
1168 	if (set_nr_and_not_polling(rq->idle))
1169 		smp_send_reschedule(cpu);
1170 	else
1171 		trace_sched_wake_idle_without_ipi(cpu);
1172 }
1173 
wake_up_full_nohz_cpu(int cpu)1174 static bool wake_up_full_nohz_cpu(int cpu)
1175 {
1176 	/*
1177 	 * We just need the target to call irq_exit() and re-evaluate
1178 	 * the next tick. The nohz full kick at least implies that.
1179 	 * If needed we can still optimize that later with an
1180 	 * empty IRQ.
1181 	 */
1182 	if (cpu_is_offline(cpu))
1183 		return true;  /* Don't try to wake offline CPUs. */
1184 	if (tick_nohz_full_cpu(cpu)) {
1185 		if (cpu != smp_processor_id() ||
1186 		    tick_nohz_tick_stopped())
1187 			tick_nohz_full_kick_cpu(cpu);
1188 		return true;
1189 	}
1190 
1191 	return false;
1192 }
1193 
1194 /*
1195  * Wake up the specified CPU.  If the CPU is going offline, it is the
1196  * caller's responsibility to deal with the lost wakeup, for example,
1197  * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
1198  */
wake_up_nohz_cpu(int cpu)1199 void wake_up_nohz_cpu(int cpu)
1200 {
1201 	if (!wake_up_full_nohz_cpu(cpu))
1202 		wake_up_idle_cpu(cpu);
1203 }
1204 
nohz_csd_func(void * info)1205 static void nohz_csd_func(void *info)
1206 {
1207 	struct rq *rq = info;
1208 	int cpu = cpu_of(rq);
1209 	unsigned int flags;
1210 
1211 	/*
1212 	 * Release the rq::nohz_csd.
1213 	 */
1214 	flags = atomic_fetch_andnot(NOHZ_KICK_MASK | NOHZ_NEWILB_KICK, nohz_flags(cpu));
1215 	WARN_ON(!(flags & NOHZ_KICK_MASK));
1216 
1217 	rq->idle_balance = idle_cpu(cpu);
1218 	if (rq->idle_balance && !need_resched()) {
1219 		rq->nohz_idle_balance = flags;
1220 		raise_softirq_irqoff(SCHED_SOFTIRQ);
1221 	}
1222 }
1223 
1224 #endif /* CONFIG_NO_HZ_COMMON */
1225 
1226 #ifdef CONFIG_NO_HZ_FULL
__need_bw_check(struct rq * rq,struct task_struct * p)1227 static inline bool __need_bw_check(struct rq *rq, struct task_struct *p)
1228 {
1229 	if (rq->nr_running != 1)
1230 		return false;
1231 
1232 	if (p->sched_class != &fair_sched_class)
1233 		return false;
1234 
1235 	if (!task_on_rq_queued(p))
1236 		return false;
1237 
1238 	return true;
1239 }
1240 
sched_can_stop_tick(struct rq * rq)1241 bool sched_can_stop_tick(struct rq *rq)
1242 {
1243 	int fifo_nr_running;
1244 
1245 	/* Deadline tasks, even if single, need the tick */
1246 	if (rq->dl.dl_nr_running)
1247 		return false;
1248 
1249 	/*
1250 	 * If there are more than one RR tasks, we need the tick to affect the
1251 	 * actual RR behaviour.
1252 	 */
1253 	if (rq->rt.rr_nr_running) {
1254 		if (rq->rt.rr_nr_running == 1)
1255 			return true;
1256 		else
1257 			return false;
1258 	}
1259 
1260 	/*
1261 	 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
1262 	 * forced preemption between FIFO tasks.
1263 	 */
1264 	fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
1265 	if (fifo_nr_running)
1266 		return true;
1267 
1268 	/*
1269 	 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
1270 	 * if there's more than one we need the tick for involuntary
1271 	 * preemption.
1272 	 */
1273 	if (rq->nr_running > 1)
1274 		return false;
1275 
1276 	/*
1277 	 * If there is one task and it has CFS runtime bandwidth constraints
1278 	 * and it's on the cpu now we don't want to stop the tick.
1279 	 * This check prevents clearing the bit if a newly enqueued task here is
1280 	 * dequeued by migrating while the constrained task continues to run.
1281 	 * E.g. going from 2->1 without going through pick_next_task().
1282 	 */
1283 	if (sched_feat(HZ_BW) && __need_bw_check(rq, rq->curr)) {
1284 		if (cfs_task_bw_constrained(rq->curr))
1285 			return false;
1286 	}
1287 
1288 	return true;
1289 }
1290 #endif /* CONFIG_NO_HZ_FULL */
1291 #endif /* CONFIG_SMP */
1292 
1293 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
1294 			(defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
1295 /*
1296  * Iterate task_group tree rooted at *from, calling @down when first entering a
1297  * node and @up when leaving it for the final time.
1298  *
1299  * Caller must hold rcu_lock or sufficient equivalent.
1300  */
walk_tg_tree_from(struct task_group * from,tg_visitor down,tg_visitor up,void * data)1301 int walk_tg_tree_from(struct task_group *from,
1302 			     tg_visitor down, tg_visitor up, void *data)
1303 {
1304 	struct task_group *parent, *child;
1305 	int ret;
1306 
1307 	parent = from;
1308 
1309 down:
1310 	ret = (*down)(parent, data);
1311 	if (ret)
1312 		goto out;
1313 	list_for_each_entry_rcu(child, &parent->children, siblings) {
1314 		parent = child;
1315 		goto down;
1316 
1317 up:
1318 		continue;
1319 	}
1320 	ret = (*up)(parent, data);
1321 	if (ret || parent == from)
1322 		goto out;
1323 
1324 	child = parent;
1325 	parent = parent->parent;
1326 	if (parent)
1327 		goto up;
1328 out:
1329 	return ret;
1330 }
1331 
tg_nop(struct task_group * tg,void * data)1332 int tg_nop(struct task_group *tg, void *data)
1333 {
1334 	return 0;
1335 }
1336 #endif
1337 
set_load_weight(struct task_struct * p,bool update_load)1338 static void set_load_weight(struct task_struct *p, bool update_load)
1339 {
1340 	int prio = p->static_prio - MAX_RT_PRIO;
1341 	struct load_weight *load = &p->se.load;
1342 
1343 	/*
1344 	 * SCHED_IDLE tasks get minimal weight:
1345 	 */
1346 	if (task_has_idle_policy(p)) {
1347 		load->weight = scale_load(WEIGHT_IDLEPRIO);
1348 		load->inv_weight = WMULT_IDLEPRIO;
1349 		return;
1350 	}
1351 
1352 	/*
1353 	 * SCHED_OTHER tasks have to update their load when changing their
1354 	 * weight
1355 	 */
1356 	if (update_load && p->sched_class == &fair_sched_class) {
1357 		reweight_task(p, prio);
1358 	} else {
1359 		load->weight = scale_load(sched_prio_to_weight[prio]);
1360 		load->inv_weight = sched_prio_to_wmult[prio];
1361 	}
1362 }
1363 
1364 #ifdef CONFIG_UCLAMP_TASK
1365 /*
1366  * Serializes updates of utilization clamp values
1367  *
1368  * The (slow-path) user-space triggers utilization clamp value updates which
1369  * can require updates on (fast-path) scheduler's data structures used to
1370  * support enqueue/dequeue operations.
1371  * While the per-CPU rq lock protects fast-path update operations, user-space
1372  * requests are serialized using a mutex to reduce the risk of conflicting
1373  * updates or API abuses.
1374  */
1375 static DEFINE_MUTEX(uclamp_mutex);
1376 
1377 /* Max allowed minimum utilization */
1378 static unsigned int __maybe_unused sysctl_sched_uclamp_util_min = SCHED_CAPACITY_SCALE;
1379 
1380 /* Max allowed maximum utilization */
1381 static unsigned int __maybe_unused sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
1382 
1383 /*
1384  * By default RT tasks run at the maximum performance point/capacity of the
1385  * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
1386  * SCHED_CAPACITY_SCALE.
1387  *
1388  * This knob allows admins to change the default behavior when uclamp is being
1389  * used. In battery powered devices, particularly, running at the maximum
1390  * capacity and frequency will increase energy consumption and shorten the
1391  * battery life.
1392  *
1393  * This knob only affects RT tasks that their uclamp_se->user_defined == false.
1394  *
1395  * This knob will not override the system default sched_util_clamp_min defined
1396  * above.
1397  */
1398 static unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE;
1399 
1400 /* All clamps are required to be less or equal than these values */
1401 static struct uclamp_se uclamp_default[UCLAMP_CNT];
1402 
1403 /*
1404  * This static key is used to reduce the uclamp overhead in the fast path. It
1405  * primarily disables the call to uclamp_rq_{inc, dec}() in
1406  * enqueue/dequeue_task().
1407  *
1408  * This allows users to continue to enable uclamp in their kernel config with
1409  * minimum uclamp overhead in the fast path.
1410  *
1411  * As soon as userspace modifies any of the uclamp knobs, the static key is
1412  * enabled, since we have an actual users that make use of uclamp
1413  * functionality.
1414  *
1415  * The knobs that would enable this static key are:
1416  *
1417  *   * A task modifying its uclamp value with sched_setattr().
1418  *   * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
1419  *   * An admin modifying the cgroup cpu.uclamp.{min, max}
1420  */
1421 DEFINE_STATIC_KEY_FALSE(sched_uclamp_used);
1422 EXPORT_SYMBOL_GPL(sched_uclamp_used);
1423 
1424 /* Integer rounded range for each bucket */
1425 #define UCLAMP_BUCKET_DELTA DIV_ROUND_CLOSEST(SCHED_CAPACITY_SCALE, UCLAMP_BUCKETS)
1426 
1427 #define for_each_clamp_id(clamp_id) \
1428 	for ((clamp_id) = 0; (clamp_id) < UCLAMP_CNT; (clamp_id)++)
1429 
uclamp_bucket_id(unsigned int clamp_value)1430 static inline unsigned int uclamp_bucket_id(unsigned int clamp_value)
1431 {
1432 	return min_t(unsigned int, clamp_value / UCLAMP_BUCKET_DELTA, UCLAMP_BUCKETS - 1);
1433 }
1434 
uclamp_none(enum uclamp_id clamp_id)1435 static inline unsigned int uclamp_none(enum uclamp_id clamp_id)
1436 {
1437 	if (clamp_id == UCLAMP_MIN)
1438 		return 0;
1439 	return SCHED_CAPACITY_SCALE;
1440 }
1441 
uclamp_se_set(struct uclamp_se * uc_se,unsigned int value,bool user_defined)1442 static inline void uclamp_se_set(struct uclamp_se *uc_se,
1443 				 unsigned int value, bool user_defined)
1444 {
1445 	uc_se->value = value;
1446 	uc_se->bucket_id = uclamp_bucket_id(value);
1447 	uc_se->user_defined = user_defined;
1448 }
1449 
1450 static inline unsigned int
uclamp_idle_value(struct rq * rq,enum uclamp_id clamp_id,unsigned int clamp_value)1451 uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id,
1452 		  unsigned int clamp_value)
1453 {
1454 	/*
1455 	 * Avoid blocked utilization pushing up the frequency when we go
1456 	 * idle (which drops the max-clamp) by retaining the last known
1457 	 * max-clamp.
1458 	 */
1459 	if (clamp_id == UCLAMP_MAX) {
1460 		rq->uclamp_flags |= UCLAMP_FLAG_IDLE;
1461 		return clamp_value;
1462 	}
1463 
1464 	return uclamp_none(UCLAMP_MIN);
1465 }
1466 
uclamp_idle_reset(struct rq * rq,enum uclamp_id clamp_id,unsigned int clamp_value)1467 static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id,
1468 				     unsigned int clamp_value)
1469 {
1470 	/* Reset max-clamp retention only on idle exit */
1471 	if (!(rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1472 		return;
1473 
1474 	uclamp_rq_set(rq, clamp_id, clamp_value);
1475 }
1476 
1477 static inline
uclamp_rq_max_value(struct rq * rq,enum uclamp_id clamp_id,unsigned int clamp_value)1478 unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id,
1479 				   unsigned int clamp_value)
1480 {
1481 	struct uclamp_bucket *bucket = rq->uclamp[clamp_id].bucket;
1482 	int bucket_id = UCLAMP_BUCKETS - 1;
1483 
1484 	/*
1485 	 * Since both min and max clamps are max aggregated, find the
1486 	 * top most bucket with tasks in.
1487 	 */
1488 	for ( ; bucket_id >= 0; bucket_id--) {
1489 		if (!bucket[bucket_id].tasks)
1490 			continue;
1491 		return bucket[bucket_id].value;
1492 	}
1493 
1494 	/* No tasks -- default clamp values */
1495 	return uclamp_idle_value(rq, clamp_id, clamp_value);
1496 }
1497 
__uclamp_update_util_min_rt_default(struct task_struct * p)1498 static void __uclamp_update_util_min_rt_default(struct task_struct *p)
1499 {
1500 	unsigned int default_util_min;
1501 	struct uclamp_se *uc_se;
1502 
1503 	lockdep_assert_held(&p->pi_lock);
1504 
1505 	uc_se = &p->uclamp_req[UCLAMP_MIN];
1506 
1507 	/* Only sync if user didn't override the default */
1508 	if (uc_se->user_defined)
1509 		return;
1510 
1511 	default_util_min = sysctl_sched_uclamp_util_min_rt_default;
1512 	uclamp_se_set(uc_se, default_util_min, false);
1513 }
1514 
uclamp_update_util_min_rt_default(struct task_struct * p)1515 static void uclamp_update_util_min_rt_default(struct task_struct *p)
1516 {
1517 	struct rq_flags rf;
1518 	struct rq *rq;
1519 
1520 	if (!rt_task(p))
1521 		return;
1522 
1523 	/* Protect updates to p->uclamp_* */
1524 	rq = task_rq_lock(p, &rf);
1525 	__uclamp_update_util_min_rt_default(p);
1526 	task_rq_unlock(rq, p, &rf);
1527 }
1528 
1529 static inline struct uclamp_se
uclamp_tg_restrict(struct task_struct * p,enum uclamp_id clamp_id)1530 uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id)
1531 {
1532 	/* Copy by value as we could modify it */
1533 	struct uclamp_se uc_req = p->uclamp_req[clamp_id];
1534 #ifdef CONFIG_UCLAMP_TASK_GROUP
1535 	unsigned int tg_min, tg_max, value;
1536 
1537 	/*
1538 	 * Tasks in autogroups or root task group will be
1539 	 * restricted by system defaults.
1540 	 */
1541 	if (task_group_is_autogroup(task_group(p)))
1542 		return uc_req;
1543 	if (task_group(p) == &root_task_group)
1544 		return uc_req;
1545 
1546 	tg_min = task_group(p)->uclamp[UCLAMP_MIN].value;
1547 	tg_max = task_group(p)->uclamp[UCLAMP_MAX].value;
1548 	value = uc_req.value;
1549 	value = clamp(value, tg_min, tg_max);
1550 	uclamp_se_set(&uc_req, value, false);
1551 #endif
1552 
1553 	return uc_req;
1554 }
1555 
1556 /*
1557  * The effective clamp bucket index of a task depends on, by increasing
1558  * priority:
1559  * - the task specific clamp value, when explicitly requested from userspace
1560  * - the task group effective clamp value, for tasks not either in the root
1561  *   group or in an autogroup
1562  * - the system default clamp value, defined by the sysadmin
1563  */
1564 static inline struct uclamp_se
uclamp_eff_get(struct task_struct * p,enum uclamp_id clamp_id)1565 uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id)
1566 {
1567 	struct uclamp_se uc_req = uclamp_tg_restrict(p, clamp_id);
1568 	struct uclamp_se uc_max = uclamp_default[clamp_id];
1569 	struct uclamp_se uc_eff;
1570 	int ret = 0;
1571 
1572 	trace_android_rvh_uclamp_eff_get(p, clamp_id, &uc_max, &uc_eff, &ret);
1573 	if (ret)
1574 		return uc_eff;
1575 
1576 	/* System default restrictions always apply */
1577 	if (unlikely(uc_req.value > uc_max.value))
1578 		return uc_max;
1579 
1580 	return uc_req;
1581 }
1582 
uclamp_eff_value(struct task_struct * p,enum uclamp_id clamp_id)1583 unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
1584 {
1585 	struct uclamp_se uc_eff;
1586 
1587 	/* Task currently refcounted: use back-annotated (effective) value */
1588 	if (p->uclamp[clamp_id].active)
1589 		return (unsigned long)p->uclamp[clamp_id].value;
1590 
1591 	uc_eff = uclamp_eff_get(p, clamp_id);
1592 
1593 	return (unsigned long)uc_eff.value;
1594 }
1595 EXPORT_SYMBOL_GPL(uclamp_eff_value);
1596 
1597 /*
1598  * When a task is enqueued on a rq, the clamp bucket currently defined by the
1599  * task's uclamp::bucket_id is refcounted on that rq. This also immediately
1600  * updates the rq's clamp value if required.
1601  *
1602  * Tasks can have a task-specific value requested from user-space, track
1603  * within each bucket the maximum value for tasks refcounted in it.
1604  * This "local max aggregation" allows to track the exact "requested" value
1605  * for each bucket when all its RUNNABLE tasks require the same clamp.
1606  */
uclamp_rq_inc_id(struct rq * rq,struct task_struct * p,enum uclamp_id clamp_id)1607 static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p,
1608 				    enum uclamp_id clamp_id)
1609 {
1610 	struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1611 	struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1612 	struct uclamp_bucket *bucket;
1613 
1614 	lockdep_assert_rq_held(rq);
1615 
1616 	/* Update task effective clamp */
1617 	p->uclamp[clamp_id] = uclamp_eff_get(p, clamp_id);
1618 
1619 	bucket = &uc_rq->bucket[uc_se->bucket_id];
1620 	bucket->tasks++;
1621 	uc_se->active = true;
1622 
1623 	uclamp_idle_reset(rq, clamp_id, uc_se->value);
1624 
1625 	/*
1626 	 * Local max aggregation: rq buckets always track the max
1627 	 * "requested" clamp value of its RUNNABLE tasks.
1628 	 */
1629 	if (bucket->tasks == 1 || uc_se->value > bucket->value)
1630 		bucket->value = uc_se->value;
1631 
1632 	if (uc_se->value > uclamp_rq_get(rq, clamp_id))
1633 		uclamp_rq_set(rq, clamp_id, uc_se->value);
1634 }
1635 
1636 /*
1637  * When a task is dequeued from a rq, the clamp bucket refcounted by the task
1638  * is released. If this is the last task reference counting the rq's max
1639  * active clamp value, then the rq's clamp value is updated.
1640  *
1641  * Both refcounted tasks and rq's cached clamp values are expected to be
1642  * always valid. If it's detected they are not, as defensive programming,
1643  * enforce the expected state and warn.
1644  */
uclamp_rq_dec_id(struct rq * rq,struct task_struct * p,enum uclamp_id clamp_id)1645 static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p,
1646 				    enum uclamp_id clamp_id)
1647 {
1648 	struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1649 	struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1650 	struct uclamp_bucket *bucket;
1651 	unsigned int bkt_clamp;
1652 	unsigned int rq_clamp;
1653 
1654 	lockdep_assert_rq_held(rq);
1655 
1656 	/*
1657 	 * If sched_uclamp_used was enabled after task @p was enqueued,
1658 	 * we could end up with unbalanced call to uclamp_rq_dec_id().
1659 	 *
1660 	 * In this case the uc_se->active flag should be false since no uclamp
1661 	 * accounting was performed at enqueue time and we can just return
1662 	 * here.
1663 	 *
1664 	 * Need to be careful of the following enqueue/dequeue ordering
1665 	 * problem too
1666 	 *
1667 	 *	enqueue(taskA)
1668 	 *	// sched_uclamp_used gets enabled
1669 	 *	enqueue(taskB)
1670 	 *	dequeue(taskA)
1671 	 *	// Must not decrement bucket->tasks here
1672 	 *	dequeue(taskB)
1673 	 *
1674 	 * where we could end up with stale data in uc_se and
1675 	 * bucket[uc_se->bucket_id].
1676 	 *
1677 	 * The following check here eliminates the possibility of such race.
1678 	 */
1679 	if (unlikely(!uc_se->active))
1680 		return;
1681 
1682 	bucket = &uc_rq->bucket[uc_se->bucket_id];
1683 
1684 	SCHED_WARN_ON(!bucket->tasks);
1685 	if (likely(bucket->tasks))
1686 		bucket->tasks--;
1687 
1688 	uc_se->active = false;
1689 
1690 	/*
1691 	 * Keep "local max aggregation" simple and accept to (possibly)
1692 	 * overboost some RUNNABLE tasks in the same bucket.
1693 	 * The rq clamp bucket value is reset to its base value whenever
1694 	 * there are no more RUNNABLE tasks refcounting it.
1695 	 */
1696 	if (likely(bucket->tasks))
1697 		return;
1698 
1699 	rq_clamp = uclamp_rq_get(rq, clamp_id);
1700 	/*
1701 	 * Defensive programming: this should never happen. If it happens,
1702 	 * e.g. due to future modification, warn and fixup the expected value.
1703 	 */
1704 	SCHED_WARN_ON(bucket->value > rq_clamp);
1705 	if (bucket->value >= rq_clamp) {
1706 		bkt_clamp = uclamp_rq_max_value(rq, clamp_id, uc_se->value);
1707 		uclamp_rq_set(rq, clamp_id, bkt_clamp);
1708 	}
1709 }
1710 
uclamp_rq_inc(struct rq * rq,struct task_struct * p)1711 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p)
1712 {
1713 	enum uclamp_id clamp_id;
1714 
1715 	/*
1716 	 * Avoid any overhead until uclamp is actually used by the userspace.
1717 	 *
1718 	 * The condition is constructed such that a NOP is generated when
1719 	 * sched_uclamp_used is disabled.
1720 	 */
1721 	if (!static_branch_unlikely(&sched_uclamp_used))
1722 		return;
1723 
1724 	if (unlikely(!p->sched_class->uclamp_enabled))
1725 		return;
1726 
1727 	for_each_clamp_id(clamp_id)
1728 		uclamp_rq_inc_id(rq, p, clamp_id);
1729 
1730 	/* Reset clamp idle holding when there is one RUNNABLE task */
1731 	if (rq->uclamp_flags & UCLAMP_FLAG_IDLE)
1732 		rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1733 }
1734 
uclamp_rq_dec(struct rq * rq,struct task_struct * p)1735 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p)
1736 {
1737 	enum uclamp_id clamp_id;
1738 
1739 	/*
1740 	 * Avoid any overhead until uclamp is actually used by the userspace.
1741 	 *
1742 	 * The condition is constructed such that a NOP is generated when
1743 	 * sched_uclamp_used is disabled.
1744 	 */
1745 	if (!static_branch_unlikely(&sched_uclamp_used))
1746 		return;
1747 
1748 	if (unlikely(!p->sched_class->uclamp_enabled))
1749 		return;
1750 
1751 	for_each_clamp_id(clamp_id)
1752 		uclamp_rq_dec_id(rq, p, clamp_id);
1753 }
1754 
uclamp_rq_reinc_id(struct rq * rq,struct task_struct * p,enum uclamp_id clamp_id)1755 static inline void uclamp_rq_reinc_id(struct rq *rq, struct task_struct *p,
1756 				      enum uclamp_id clamp_id)
1757 {
1758 	if (!p->uclamp[clamp_id].active)
1759 		return;
1760 
1761 	uclamp_rq_dec_id(rq, p, clamp_id);
1762 	uclamp_rq_inc_id(rq, p, clamp_id);
1763 
1764 	/*
1765 	 * Make sure to clear the idle flag if we've transiently reached 0
1766 	 * active tasks on rq.
1767 	 */
1768 	if (clamp_id == UCLAMP_MAX && (rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1769 		rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1770 }
1771 
1772 static inline void
uclamp_update_active(struct task_struct * p)1773 uclamp_update_active(struct task_struct *p)
1774 {
1775 	enum uclamp_id clamp_id;
1776 	struct rq_flags rf;
1777 	struct rq *rq;
1778 
1779 	/*
1780 	 * Lock the task and the rq where the task is (or was) queued.
1781 	 *
1782 	 * We might lock the (previous) rq of a !RUNNABLE task, but that's the
1783 	 * price to pay to safely serialize util_{min,max} updates with
1784 	 * enqueues, dequeues and migration operations.
1785 	 * This is the same locking schema used by __set_cpus_allowed_ptr().
1786 	 */
1787 	rq = task_rq_lock(p, &rf);
1788 
1789 	/*
1790 	 * Setting the clamp bucket is serialized by task_rq_lock().
1791 	 * If the task is not yet RUNNABLE and its task_struct is not
1792 	 * affecting a valid clamp bucket, the next time it's enqueued,
1793 	 * it will already see the updated clamp bucket value.
1794 	 */
1795 	for_each_clamp_id(clamp_id)
1796 		uclamp_rq_reinc_id(rq, p, clamp_id);
1797 
1798 	task_rq_unlock(rq, p, &rf);
1799 }
1800 
1801 #ifdef CONFIG_UCLAMP_TASK_GROUP
1802 static inline void
uclamp_update_active_tasks(struct cgroup_subsys_state * css)1803 uclamp_update_active_tasks(struct cgroup_subsys_state *css)
1804 {
1805 	struct css_task_iter it;
1806 	struct task_struct *p;
1807 
1808 	css_task_iter_start(css, 0, &it);
1809 	while ((p = css_task_iter_next(&it)))
1810 		uclamp_update_active(p);
1811 	css_task_iter_end(&it);
1812 }
1813 
1814 static void cpu_util_update_eff(struct cgroup_subsys_state *css);
1815 #endif
1816 
1817 #ifdef CONFIG_SYSCTL
1818 #ifdef CONFIG_UCLAMP_TASK
1819 #ifdef CONFIG_UCLAMP_TASK_GROUP
uclamp_update_root_tg(void)1820 static void uclamp_update_root_tg(void)
1821 {
1822 	struct task_group *tg = &root_task_group;
1823 
1824 	uclamp_se_set(&tg->uclamp_req[UCLAMP_MIN],
1825 		      sysctl_sched_uclamp_util_min, false);
1826 	uclamp_se_set(&tg->uclamp_req[UCLAMP_MAX],
1827 		      sysctl_sched_uclamp_util_max, false);
1828 
1829 	rcu_read_lock();
1830 	cpu_util_update_eff(&root_task_group.css);
1831 	rcu_read_unlock();
1832 }
1833 #else
uclamp_update_root_tg(void)1834 static void uclamp_update_root_tg(void) { }
1835 #endif
1836 
uclamp_sync_util_min_rt_default(void)1837 static void uclamp_sync_util_min_rt_default(void)
1838 {
1839 	struct task_struct *g, *p;
1840 
1841 	/*
1842 	 * copy_process()			sysctl_uclamp
1843 	 *					  uclamp_min_rt = X;
1844 	 *   write_lock(&tasklist_lock)		  read_lock(&tasklist_lock)
1845 	 *   // link thread			  smp_mb__after_spinlock()
1846 	 *   write_unlock(&tasklist_lock)	  read_unlock(&tasklist_lock);
1847 	 *   sched_post_fork()			  for_each_process_thread()
1848 	 *     __uclamp_sync_rt()		    __uclamp_sync_rt()
1849 	 *
1850 	 * Ensures that either sched_post_fork() will observe the new
1851 	 * uclamp_min_rt or for_each_process_thread() will observe the new
1852 	 * task.
1853 	 */
1854 	read_lock(&tasklist_lock);
1855 	smp_mb__after_spinlock();
1856 	read_unlock(&tasklist_lock);
1857 
1858 	rcu_read_lock();
1859 	for_each_process_thread(g, p)
1860 		uclamp_update_util_min_rt_default(p);
1861 	rcu_read_unlock();
1862 }
1863 
sysctl_sched_uclamp_handler(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)1864 static int sysctl_sched_uclamp_handler(struct ctl_table *table, int write,
1865 				void *buffer, size_t *lenp, loff_t *ppos)
1866 {
1867 	bool update_root_tg = false;
1868 	int old_min, old_max, old_min_rt;
1869 	int result;
1870 
1871 	guard(mutex)(&uclamp_mutex);
1872 
1873 	old_min = sysctl_sched_uclamp_util_min;
1874 	old_max = sysctl_sched_uclamp_util_max;
1875 	old_min_rt = sysctl_sched_uclamp_util_min_rt_default;
1876 
1877 	result = proc_dointvec(table, write, buffer, lenp, ppos);
1878 	if (result)
1879 		goto undo;
1880 	if (!write)
1881 		return 0;
1882 
1883 	if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
1884 	    sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE	||
1885 	    sysctl_sched_uclamp_util_min_rt_default > SCHED_CAPACITY_SCALE) {
1886 
1887 		result = -EINVAL;
1888 		goto undo;
1889 	}
1890 
1891 	if (old_min != sysctl_sched_uclamp_util_min) {
1892 		uclamp_se_set(&uclamp_default[UCLAMP_MIN],
1893 			      sysctl_sched_uclamp_util_min, false);
1894 		update_root_tg = true;
1895 	}
1896 	if (old_max != sysctl_sched_uclamp_util_max) {
1897 		uclamp_se_set(&uclamp_default[UCLAMP_MAX],
1898 			      sysctl_sched_uclamp_util_max, false);
1899 		update_root_tg = true;
1900 	}
1901 
1902 	if (update_root_tg) {
1903 		static_branch_enable(&sched_uclamp_used);
1904 		uclamp_update_root_tg();
1905 	}
1906 
1907 	if (old_min_rt != sysctl_sched_uclamp_util_min_rt_default) {
1908 		static_branch_enable(&sched_uclamp_used);
1909 		uclamp_sync_util_min_rt_default();
1910 	}
1911 
1912 	/*
1913 	 * We update all RUNNABLE tasks only when task groups are in use.
1914 	 * Otherwise, keep it simple and do just a lazy update at each next
1915 	 * task enqueue time.
1916 	 */
1917 	return 0;
1918 
1919 undo:
1920 	sysctl_sched_uclamp_util_min = old_min;
1921 	sysctl_sched_uclamp_util_max = old_max;
1922 	sysctl_sched_uclamp_util_min_rt_default = old_min_rt;
1923 	return result;
1924 }
1925 #endif
1926 #endif
1927 
uclamp_validate(struct task_struct * p,const struct sched_attr * attr)1928 static int uclamp_validate(struct task_struct *p,
1929 			   const struct sched_attr *attr)
1930 {
1931 	int util_min = p->uclamp_req[UCLAMP_MIN].value;
1932 	int util_max = p->uclamp_req[UCLAMP_MAX].value;
1933 	bool done = false;
1934 	int ret = 0;
1935 
1936 	trace_android_vh_uclamp_validate(p, attr, &ret, &done);
1937 	if (done)
1938 		return ret;
1939 
1940 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) {
1941 		util_min = attr->sched_util_min;
1942 
1943 		if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)
1944 			return -EINVAL;
1945 	}
1946 
1947 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX) {
1948 		util_max = attr->sched_util_max;
1949 
1950 		if (util_max + 1 > SCHED_CAPACITY_SCALE + 1)
1951 			return -EINVAL;
1952 	}
1953 
1954 	if (util_min != -1 && util_max != -1 && util_min > util_max)
1955 		return -EINVAL;
1956 
1957 	/*
1958 	 * We have valid uclamp attributes; make sure uclamp is enabled.
1959 	 *
1960 	 * We need to do that here, because enabling static branches is a
1961 	 * blocking operation which obviously cannot be done while holding
1962 	 * scheduler locks.
1963 	 */
1964 	static_branch_enable(&sched_uclamp_used);
1965 
1966 	return 0;
1967 }
1968 
uclamp_reset(const struct sched_attr * attr,enum uclamp_id clamp_id,struct uclamp_se * uc_se)1969 static bool uclamp_reset(const struct sched_attr *attr,
1970 			 enum uclamp_id clamp_id,
1971 			 struct uclamp_se *uc_se)
1972 {
1973 	/* Reset on sched class change for a non user-defined clamp value. */
1974 	if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)) &&
1975 	    !uc_se->user_defined)
1976 		return true;
1977 
1978 	/* Reset on sched_util_{min,max} == -1. */
1979 	if (clamp_id == UCLAMP_MIN &&
1980 	    attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
1981 	    attr->sched_util_min == -1) {
1982 		return true;
1983 	}
1984 
1985 	if (clamp_id == UCLAMP_MAX &&
1986 	    attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
1987 	    attr->sched_util_max == -1) {
1988 		return true;
1989 	}
1990 
1991 	return false;
1992 }
1993 
__setscheduler_uclamp(struct task_struct * p,const struct sched_attr * attr)1994 static void __setscheduler_uclamp(struct task_struct *p,
1995 				  const struct sched_attr *attr)
1996 {
1997 	enum uclamp_id clamp_id;
1998 
1999 	for_each_clamp_id(clamp_id) {
2000 		struct uclamp_se *uc_se = &p->uclamp_req[clamp_id];
2001 		unsigned int value;
2002 
2003 		if (!uclamp_reset(attr, clamp_id, uc_se))
2004 			continue;
2005 
2006 		/*
2007 		 * RT by default have a 100% boost value that could be modified
2008 		 * at runtime.
2009 		 */
2010 		if (unlikely(rt_task(p) && clamp_id == UCLAMP_MIN))
2011 			value = sysctl_sched_uclamp_util_min_rt_default;
2012 		else
2013 			value = uclamp_none(clamp_id);
2014 
2015 		uclamp_se_set(uc_se, value, false);
2016 
2017 	}
2018 
2019 	if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)))
2020 		return;
2021 
2022 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
2023 	    attr->sched_util_min != -1) {
2024 		uclamp_se_set(&p->uclamp_req[UCLAMP_MIN],
2025 			      attr->sched_util_min, true);
2026 		trace_android_vh_setscheduler_uclamp(p, UCLAMP_MIN, attr->sched_util_min);
2027 	}
2028 
2029 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
2030 	    attr->sched_util_max != -1) {
2031 		uclamp_se_set(&p->uclamp_req[UCLAMP_MAX],
2032 			      attr->sched_util_max, true);
2033 		trace_android_vh_setscheduler_uclamp(p, UCLAMP_MAX, attr->sched_util_max);
2034 	}
2035 }
2036 
uclamp_fork(struct task_struct * p)2037 static void uclamp_fork(struct task_struct *p)
2038 {
2039 	enum uclamp_id clamp_id;
2040 
2041 	/*
2042 	 * We don't need to hold task_rq_lock() when updating p->uclamp_* here
2043 	 * as the task is still at its early fork stages.
2044 	 */
2045 	for_each_clamp_id(clamp_id)
2046 		p->uclamp[clamp_id].active = false;
2047 
2048 	if (likely(!p->sched_reset_on_fork))
2049 		return;
2050 
2051 	for_each_clamp_id(clamp_id) {
2052 		uclamp_se_set(&p->uclamp_req[clamp_id],
2053 			      uclamp_none(clamp_id), false);
2054 	}
2055 }
2056 
uclamp_post_fork(struct task_struct * p)2057 static void uclamp_post_fork(struct task_struct *p)
2058 {
2059 	uclamp_update_util_min_rt_default(p);
2060 }
2061 
init_uclamp_rq(struct rq * rq)2062 static void __init init_uclamp_rq(struct rq *rq)
2063 {
2064 	enum uclamp_id clamp_id;
2065 	struct uclamp_rq *uc_rq = rq->uclamp;
2066 
2067 	for_each_clamp_id(clamp_id) {
2068 		uc_rq[clamp_id] = (struct uclamp_rq) {
2069 			.value = uclamp_none(clamp_id)
2070 		};
2071 	}
2072 
2073 	rq->uclamp_flags = UCLAMP_FLAG_IDLE;
2074 }
2075 
init_uclamp(void)2076 static void __init init_uclamp(void)
2077 {
2078 	struct uclamp_se uc_max = {};
2079 	enum uclamp_id clamp_id;
2080 	int cpu;
2081 
2082 	for_each_possible_cpu(cpu)
2083 		init_uclamp_rq(cpu_rq(cpu));
2084 
2085 	for_each_clamp_id(clamp_id) {
2086 		uclamp_se_set(&init_task.uclamp_req[clamp_id],
2087 			      uclamp_none(clamp_id), false);
2088 	}
2089 
2090 	/* System defaults allow max clamp values for both indexes */
2091 	uclamp_se_set(&uc_max, uclamp_none(UCLAMP_MAX), false);
2092 	for_each_clamp_id(clamp_id) {
2093 		uclamp_default[clamp_id] = uc_max;
2094 #ifdef CONFIG_UCLAMP_TASK_GROUP
2095 		root_task_group.uclamp_req[clamp_id] = uc_max;
2096 		root_task_group.uclamp[clamp_id] = uc_max;
2097 #endif
2098 	}
2099 }
2100 
2101 #else /* CONFIG_UCLAMP_TASK */
uclamp_rq_inc(struct rq * rq,struct task_struct * p)2102 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { }
uclamp_rq_dec(struct rq * rq,struct task_struct * p)2103 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { }
uclamp_validate(struct task_struct * p,const struct sched_attr * attr)2104 static inline int uclamp_validate(struct task_struct *p,
2105 				  const struct sched_attr *attr)
2106 {
2107 	return -EOPNOTSUPP;
2108 }
__setscheduler_uclamp(struct task_struct * p,const struct sched_attr * attr)2109 static void __setscheduler_uclamp(struct task_struct *p,
2110 				  const struct sched_attr *attr) { }
uclamp_fork(struct task_struct * p)2111 static inline void uclamp_fork(struct task_struct *p) { }
uclamp_post_fork(struct task_struct * p)2112 static inline void uclamp_post_fork(struct task_struct *p) { }
init_uclamp(void)2113 static inline void init_uclamp(void) { }
2114 #endif /* CONFIG_UCLAMP_TASK */
2115 
sched_task_on_rq(struct task_struct * p)2116 bool sched_task_on_rq(struct task_struct *p)
2117 {
2118 	return task_on_rq_queued(p);
2119 }
2120 
get_wchan(struct task_struct * p)2121 unsigned long get_wchan(struct task_struct *p)
2122 {
2123 	unsigned long ip = 0;
2124 	unsigned int state;
2125 
2126 	if (!p || p == current)
2127 		return 0;
2128 
2129 	/* Only get wchan if task is blocked and we can keep it that way. */
2130 	raw_spin_lock_irq(&p->pi_lock);
2131 	state = READ_ONCE(p->__state);
2132 	smp_rmb(); /* see try_to_wake_up() */
2133 	if (state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq)
2134 		ip = __get_wchan(p);
2135 	raw_spin_unlock_irq(&p->pi_lock);
2136 
2137 	return ip;
2138 }
2139 EXPORT_SYMBOL_GPL(get_wchan);
2140 
enqueue_task(struct rq * rq,struct task_struct * p,int flags)2141 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
2142 {
2143 	if (!(flags & ENQUEUE_NOCLOCK))
2144 		update_rq_clock(rq);
2145 
2146 	if (!(flags & ENQUEUE_RESTORE)) {
2147 		sched_info_enqueue(rq, p);
2148 		psi_enqueue(p, (flags & ENQUEUE_WAKEUP) && !(flags & ENQUEUE_MIGRATED));
2149 	}
2150 
2151 	uclamp_rq_inc(rq, p);
2152 	trace_android_rvh_enqueue_task(rq, p, flags);
2153 	p->sched_class->enqueue_task(rq, p, flags);
2154 	trace_android_rvh_after_enqueue_task(rq, p, flags);
2155 
2156 	if (sched_core_enabled(rq))
2157 		sched_core_enqueue(rq, p);
2158 }
2159 
dequeue_task(struct rq * rq,struct task_struct * p,int flags)2160 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
2161 {
2162 	if (sched_core_enabled(rq))
2163 		sched_core_dequeue(rq, p, flags);
2164 
2165 	if (!(flags & DEQUEUE_NOCLOCK))
2166 		update_rq_clock(rq);
2167 
2168 	if (!(flags & DEQUEUE_SAVE)) {
2169 		sched_info_dequeue(rq, p);
2170 		psi_dequeue(p, flags & DEQUEUE_SLEEP);
2171 	}
2172 
2173 	uclamp_rq_dec(rq, p);
2174 	trace_android_rvh_dequeue_task(rq, p, flags);
2175 	p->sched_class->dequeue_task(rq, p, flags);
2176 	trace_android_rvh_after_dequeue_task(rq, p, flags);
2177 }
2178 
activate_task(struct rq * rq,struct task_struct * p,int flags)2179 void activate_task(struct rq *rq, struct task_struct *p, int flags)
2180 {
2181 	if (task_on_rq_migrating(p))
2182 		flags |= ENQUEUE_MIGRATED;
2183 	if (flags & ENQUEUE_MIGRATED)
2184 		sched_mm_cid_migrate_to(rq, p);
2185 
2186 	enqueue_task(rq, p, flags);
2187 
2188 	p->on_rq = TASK_ON_RQ_QUEUED;
2189 }
2190 EXPORT_SYMBOL_GPL(activate_task);
2191 
deactivate_task(struct rq * rq,struct task_struct * p,int flags)2192 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
2193 {
2194 	p->on_rq = (flags & DEQUEUE_SLEEP) ? 0 : TASK_ON_RQ_MIGRATING;
2195 
2196 	dequeue_task(rq, p, flags);
2197 }
2198 EXPORT_SYMBOL_GPL(deactivate_task);
2199 
__normal_prio(int policy,int rt_prio,int nice)2200 static inline int __normal_prio(int policy, int rt_prio, int nice)
2201 {
2202 	int prio;
2203 
2204 	if (dl_policy(policy))
2205 		prio = MAX_DL_PRIO - 1;
2206 	else if (rt_policy(policy))
2207 		prio = MAX_RT_PRIO - 1 - rt_prio;
2208 	else
2209 		prio = NICE_TO_PRIO(nice);
2210 
2211 	return prio;
2212 }
2213 
2214 /*
2215  * Calculate the expected normal priority: i.e. priority
2216  * without taking RT-inheritance into account. Might be
2217  * boosted by interactivity modifiers. Changes upon fork,
2218  * setprio syscalls, and whenever the interactivity
2219  * estimator recalculates.
2220  */
normal_prio(struct task_struct * p)2221 static inline int normal_prio(struct task_struct *p)
2222 {
2223 	return __normal_prio(p->policy, p->rt_priority, PRIO_TO_NICE(p->static_prio));
2224 }
2225 
2226 /*
2227  * Calculate the current priority, i.e. the priority
2228  * taken into account by the scheduler. This value might
2229  * be boosted by RT tasks, or might be boosted by
2230  * interactivity modifiers. Will be RT if the task got
2231  * RT-boosted. If not then it returns p->normal_prio.
2232  */
effective_prio(struct task_struct * p)2233 static int effective_prio(struct task_struct *p)
2234 {
2235 	p->normal_prio = normal_prio(p);
2236 	/*
2237 	 * If we are RT tasks or we were boosted to RT priority,
2238 	 * keep the priority unchanged. Otherwise, update priority
2239 	 * to the normal priority:
2240 	 */
2241 	if (!rt_prio(p->prio))
2242 		return p->normal_prio;
2243 	return p->prio;
2244 }
2245 
2246 /**
2247  * task_curr - is this task currently executing on a CPU?
2248  * @p: the task in question.
2249  *
2250  * Return: 1 if the task is currently executing. 0 otherwise.
2251  */
task_curr(const struct task_struct * p)2252 inline int task_curr(const struct task_struct *p)
2253 {
2254 	return cpu_curr(task_cpu(p)) == p;
2255 }
2256 
2257 /*
2258  * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
2259  * use the balance_callback list if you want balancing.
2260  *
2261  * this means any call to check_class_changed() must be followed by a call to
2262  * balance_callback().
2263  */
check_class_changed(struct rq * rq,struct task_struct * p,const struct sched_class * prev_class,int oldprio)2264 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2265 				       const struct sched_class *prev_class,
2266 				       int oldprio)
2267 {
2268 	if (prev_class != p->sched_class) {
2269 		if (prev_class->switched_from)
2270 			prev_class->switched_from(rq, p);
2271 
2272 		p->sched_class->switched_to(rq, p);
2273 	} else if (oldprio != p->prio || dl_task(p))
2274 		p->sched_class->prio_changed(rq, p, oldprio);
2275 }
2276 
check_preempt_curr(struct rq * rq,struct task_struct * p,int flags)2277 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
2278 {
2279 	if (p->sched_class == rq->curr->sched_class)
2280 		rq->curr->sched_class->check_preempt_curr(rq, p, flags);
2281 	else if (sched_class_above(p->sched_class, rq->curr->sched_class))
2282 		resched_curr(rq);
2283 
2284 	/*
2285 	 * A queue event has occurred, and we're going to schedule.  In
2286 	 * this case, we can save a useless back to back clock update.
2287 	 */
2288 	if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
2289 		rq_clock_skip_update(rq);
2290 }
2291 EXPORT_SYMBOL_GPL(check_preempt_curr);
2292 
2293 static __always_inline
__task_state_match(struct task_struct * p,unsigned int state)2294 int __task_state_match(struct task_struct *p, unsigned int state)
2295 {
2296 	if (READ_ONCE(p->__state) & state)
2297 		return 1;
2298 
2299 	if (READ_ONCE(p->saved_state) & state)
2300 		return -1;
2301 
2302 	return 0;
2303 }
2304 
2305 static __always_inline
task_state_match(struct task_struct * p,unsigned int state)2306 int task_state_match(struct task_struct *p, unsigned int state)
2307 {
2308 	int match;
2309 
2310 	/*
2311 	 * Serialize against current_save_and_set_rtlock_wait_state(),
2312 	 * current_restore_rtlock_saved_state(), and __refrigerator().
2313 	 */
2314 	raw_spin_lock_irq(&p->pi_lock);
2315 	match = __task_state_match(p, state);
2316 	raw_spin_unlock_irq(&p->pi_lock);
2317 
2318 	return match;
2319 }
2320 
2321 /*
2322  * wait_task_inactive - wait for a thread to unschedule.
2323  *
2324  * Wait for the thread to block in any of the states set in @match_state.
2325  * If it changes, i.e. @p might have woken up, then return zero.  When we
2326  * succeed in waiting for @p to be off its CPU, we return a positive number
2327  * (its total switch count).  If a second call a short while later returns the
2328  * same number, the caller can be sure that @p has remained unscheduled the
2329  * whole time.
2330  *
2331  * The caller must ensure that the task *will* unschedule sometime soon,
2332  * else this function might spin for a *long* time. This function can't
2333  * be called with interrupts off, or it may introduce deadlock with
2334  * smp_call_function() if an IPI is sent by the same process we are
2335  * waiting to become inactive.
2336  */
wait_task_inactive(struct task_struct * p,unsigned int match_state)2337 unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state)
2338 {
2339 	int running, queued, match;
2340 	struct rq_flags rf;
2341 	unsigned long ncsw;
2342 	struct rq *rq;
2343 
2344 	for (;;) {
2345 		/*
2346 		 * We do the initial early heuristics without holding
2347 		 * any task-queue locks at all. We'll only try to get
2348 		 * the runqueue lock when things look like they will
2349 		 * work out!
2350 		 */
2351 		rq = task_rq(p);
2352 
2353 		/*
2354 		 * If the task is actively running on another CPU
2355 		 * still, just relax and busy-wait without holding
2356 		 * any locks.
2357 		 *
2358 		 * NOTE! Since we don't hold any locks, it's not
2359 		 * even sure that "rq" stays as the right runqueue!
2360 		 * But we don't care, since "task_on_cpu()" will
2361 		 * return false if the runqueue has changed and p
2362 		 * is actually now running somewhere else!
2363 		 */
2364 		while (task_on_cpu(rq, p)) {
2365 			if (!task_state_match(p, match_state))
2366 				return 0;
2367 			cpu_relax();
2368 		}
2369 
2370 		/*
2371 		 * Ok, time to look more closely! We need the rq
2372 		 * lock now, to be *sure*. If we're wrong, we'll
2373 		 * just go back and repeat.
2374 		 */
2375 		rq = task_rq_lock(p, &rf);
2376 		trace_sched_wait_task(p);
2377 		running = task_on_cpu(rq, p);
2378 		queued = task_on_rq_queued(p);
2379 		ncsw = 0;
2380 		if ((match = __task_state_match(p, match_state))) {
2381 			/*
2382 			 * When matching on p->saved_state, consider this task
2383 			 * still queued so it will wait.
2384 			 */
2385 			if (match < 0)
2386 				queued = 1;
2387 			ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2388 		}
2389 		task_rq_unlock(rq, p, &rf);
2390 
2391 		/*
2392 		 * If it changed from the expected state, bail out now.
2393 		 */
2394 		if (unlikely(!ncsw))
2395 			break;
2396 
2397 		/*
2398 		 * Was it really running after all now that we
2399 		 * checked with the proper locks actually held?
2400 		 *
2401 		 * Oops. Go back and try again..
2402 		 */
2403 		if (unlikely(running)) {
2404 			cpu_relax();
2405 			continue;
2406 		}
2407 
2408 		/*
2409 		 * It's not enough that it's not actively running,
2410 		 * it must be off the runqueue _entirely_, and not
2411 		 * preempted!
2412 		 *
2413 		 * So if it was still runnable (but just not actively
2414 		 * running right now), it's preempted, and we should
2415 		 * yield - it could be a while.
2416 		 */
2417 		if (unlikely(queued)) {
2418 			ktime_t to = NSEC_PER_SEC / HZ;
2419 
2420 			set_current_state(TASK_UNINTERRUPTIBLE);
2421 			schedule_hrtimeout(&to, HRTIMER_MODE_REL_HARD);
2422 			continue;
2423 		}
2424 
2425 		/*
2426 		 * Ahh, all good. It wasn't running, and it wasn't
2427 		 * runnable, which means that it will never become
2428 		 * running in the future either. We're all done!
2429 		 */
2430 		break;
2431 	}
2432 
2433 	return ncsw;
2434 }
2435 
2436 #ifdef CONFIG_SMP
2437 
2438 static void
2439 __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx);
2440 
2441 static int __set_cpus_allowed_ptr(struct task_struct *p,
2442 				  struct affinity_context *ctx);
2443 
migrate_disable_switch(struct rq * rq,struct task_struct * p)2444 static void migrate_disable_switch(struct rq *rq, struct task_struct *p)
2445 {
2446 	struct affinity_context ac = {
2447 		.new_mask  = cpumask_of(rq->cpu),
2448 		.flags     = SCA_MIGRATE_DISABLE,
2449 	};
2450 
2451 	if (likely(!p->migration_disabled))
2452 		return;
2453 
2454 	if (p->cpus_ptr != &p->cpus_mask)
2455 		return;
2456 
2457 	/*
2458 	 * Violates locking rules! see comment in __do_set_cpus_allowed().
2459 	 */
2460 	__do_set_cpus_allowed(p, &ac);
2461 }
2462 
migrate_disable(void)2463 void migrate_disable(void)
2464 {
2465 	struct task_struct *p = current;
2466 
2467 	if (p->migration_disabled) {
2468 		p->migration_disabled++;
2469 		return;
2470 	}
2471 
2472 	preempt_disable();
2473 	this_rq()->nr_pinned++;
2474 	p->migration_disabled = 1;
2475 	preempt_enable();
2476 }
2477 EXPORT_SYMBOL_GPL(migrate_disable);
2478 
migrate_enable(void)2479 void migrate_enable(void)
2480 {
2481 	struct task_struct *p = current;
2482 	struct affinity_context ac = {
2483 		.new_mask  = &p->cpus_mask,
2484 		.flags     = SCA_MIGRATE_ENABLE,
2485 	};
2486 
2487 	if (p->migration_disabled > 1) {
2488 		p->migration_disabled--;
2489 		return;
2490 	}
2491 
2492 	if (WARN_ON_ONCE(!p->migration_disabled))
2493 		return;
2494 
2495 	/*
2496 	 * Ensure stop_task runs either before or after this, and that
2497 	 * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule().
2498 	 */
2499 	preempt_disable();
2500 	if (p->cpus_ptr != &p->cpus_mask)
2501 		__set_cpus_allowed_ptr(p, &ac);
2502 	/*
2503 	 * Mustn't clear migration_disabled() until cpus_ptr points back at the
2504 	 * regular cpus_mask, otherwise things that race (eg.
2505 	 * select_fallback_rq) get confused.
2506 	 */
2507 	barrier();
2508 	p->migration_disabled = 0;
2509 	this_rq()->nr_pinned--;
2510 	preempt_enable();
2511 }
2512 EXPORT_SYMBOL_GPL(migrate_enable);
2513 
rq_has_pinned_tasks(struct rq * rq)2514 static inline bool rq_has_pinned_tasks(struct rq *rq)
2515 {
2516 	return rq->nr_pinned;
2517 }
2518 
2519 /*
2520  * Per-CPU kthreads are allowed to run on !active && online CPUs, see
2521  * __set_cpus_allowed_ptr() and select_fallback_rq().
2522  */
is_cpu_allowed(struct task_struct * p,int cpu)2523 static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
2524 {
2525 	bool allowed = true;
2526 
2527 	/* When not in the task's cpumask, no point in looking further. */
2528 	if (!cpumask_test_cpu(cpu, p->cpus_ptr))
2529 		return false;
2530 
2531 	/* migrate_disabled() must be allowed to finish. */
2532 	if (is_migration_disabled(p))
2533 		return cpu_online(cpu);
2534 
2535 	/* check for all cases */
2536 	trace_android_rvh_is_cpu_allowed(p, cpu, &allowed);
2537 
2538 	/* Non kernel threads are not allowed during either online or offline. */
2539 	if (!(p->flags & PF_KTHREAD))
2540 		return cpu_active(cpu) && task_cpu_possible(cpu, p) && allowed;
2541 
2542 	/* KTHREAD_IS_PER_CPU is always allowed. */
2543 	if (kthread_is_per_cpu(p))
2544 		return cpu_online(cpu);
2545 
2546 	if (!allowed)
2547 		return false;
2548 
2549 	/* Regular kernel threads don't get to stay during offline. */
2550 	if (cpu_dying(cpu))
2551 		return false;
2552 
2553 	/* But are allowed during online. */
2554 	return cpu_online(cpu);
2555 }
2556 
2557 /*
2558  * This is how migration works:
2559  *
2560  * 1) we invoke migration_cpu_stop() on the target CPU using
2561  *    stop_one_cpu().
2562  * 2) stopper starts to run (implicitly forcing the migrated thread
2563  *    off the CPU)
2564  * 3) it checks whether the migrated task is still in the wrong runqueue.
2565  * 4) if it's in the wrong runqueue then the migration thread removes
2566  *    it and puts it into the right queue.
2567  * 5) stopper completes and stop_one_cpu() returns and the migration
2568  *    is done.
2569  */
2570 
2571 /*
2572  * move_queued_task - move a queued task to new rq.
2573  *
2574  * Returns (locked) new rq. Old rq's lock is released.
2575  */
move_queued_task(struct rq * rq,struct rq_flags * rf,struct task_struct * p,int new_cpu)2576 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
2577 				   struct task_struct *p, int new_cpu)
2578 {
2579 	int detached = 0;
2580 
2581 	lockdep_assert_rq_held(rq);
2582 
2583 	/*
2584 	 * The vendor hook may drop the lock temporarily, so
2585 	 * pass the rq flags to unpin lock. We expect the
2586 	 * rq lock to be held after return.
2587 	 */
2588 	trace_android_rvh_migrate_queued_task(rq, rf, p, new_cpu, &detached);
2589 	if (detached)
2590 		goto attach;
2591 
2592 	deactivate_task(rq, p, DEQUEUE_NOCLOCK);
2593 	set_task_cpu(p, new_cpu);
2594 
2595 attach:
2596 	rq_unlock(rq, rf);
2597 	rq = cpu_rq(new_cpu);
2598 
2599 	rq_lock(rq, rf);
2600 	WARN_ON_ONCE(task_cpu(p) != new_cpu);
2601 	activate_task(rq, p, 0);
2602 	check_preempt_curr(rq, p, 0);
2603 
2604 	return rq;
2605 }
2606 
2607 struct migration_arg {
2608 	struct task_struct		*task;
2609 	int				dest_cpu;
2610 	struct set_affinity_pending	*pending;
2611 };
2612 
2613 /*
2614  * @refs: number of wait_for_completion()
2615  * @stop_pending: is @stop_work in use
2616  */
2617 struct set_affinity_pending {
2618 	refcount_t		refs;
2619 	unsigned int		stop_pending;
2620 	struct completion	done;
2621 	struct cpu_stop_work	stop_work;
2622 	struct migration_arg	arg;
2623 };
2624 
2625 /*
2626  * Move (not current) task off this CPU, onto the destination CPU. We're doing
2627  * this because either it can't run here any more (set_cpus_allowed()
2628  * away from this CPU, or CPU going down), or because we're
2629  * attempting to rebalance this task on exec (sched_exec).
2630  *
2631  * So we race with normal scheduler movements, but that's OK, as long
2632  * as the task is no longer on this CPU.
2633  */
__migrate_task(struct rq * rq,struct rq_flags * rf,struct task_struct * p,int dest_cpu)2634 struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
2635 			  struct task_struct *p, int dest_cpu)
2636 {
2637 	/* Affinity changed (again). */
2638 	if (!is_cpu_allowed(p, dest_cpu))
2639 		return rq;
2640 
2641 	rq = move_queued_task(rq, rf, p, dest_cpu);
2642 
2643 	return rq;
2644 }
2645 EXPORT_SYMBOL_GPL(__migrate_task);
2646 
2647 /*
2648  * migration_cpu_stop - this will be executed by a highprio stopper thread
2649  * and performs thread migration by bumping thread off CPU then
2650  * 'pushing' onto another runqueue.
2651  */
migration_cpu_stop(void * data)2652 static int migration_cpu_stop(void *data)
2653 {
2654 	struct migration_arg *arg = data;
2655 	struct set_affinity_pending *pending = arg->pending;
2656 	struct task_struct *p = arg->task;
2657 	struct rq *rq = this_rq();
2658 	bool complete = false;
2659 	struct rq_flags rf;
2660 
2661 	/*
2662 	 * The original target CPU might have gone down and we might
2663 	 * be on another CPU but it doesn't matter.
2664 	 */
2665 	local_irq_save(rf.flags);
2666 	/*
2667 	 * We need to explicitly wake pending tasks before running
2668 	 * __migrate_task() such that we will not miss enforcing cpus_ptr
2669 	 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
2670 	 */
2671 	flush_smp_call_function_queue();
2672 
2673 	raw_spin_lock(&p->pi_lock);
2674 	rq_lock(rq, &rf);
2675 
2676 	/*
2677 	 * If we were passed a pending, then ->stop_pending was set, thus
2678 	 * p->migration_pending must have remained stable.
2679 	 */
2680 	WARN_ON_ONCE(pending && pending != p->migration_pending);
2681 
2682 	/*
2683 	 * If task_rq(p) != rq, it cannot be migrated here, because we're
2684 	 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
2685 	 * we're holding p->pi_lock.
2686 	 */
2687 	if (task_rq(p) == rq) {
2688 		if (is_migration_disabled(p))
2689 			goto out;
2690 
2691 		if (pending) {
2692 			p->migration_pending = NULL;
2693 			complete = true;
2694 
2695 			if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask))
2696 				goto out;
2697 		}
2698 
2699 		if (task_on_rq_queued(p)) {
2700 			update_rq_clock(rq);
2701 			rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
2702 		} else {
2703 			p->wake_cpu = arg->dest_cpu;
2704 		}
2705 
2706 		/*
2707 		 * XXX __migrate_task() can fail, at which point we might end
2708 		 * up running on a dodgy CPU, AFAICT this can only happen
2709 		 * during CPU hotplug, at which point we'll get pushed out
2710 		 * anyway, so it's probably not a big deal.
2711 		 */
2712 
2713 	} else if (pending) {
2714 		/*
2715 		 * This happens when we get migrated between migrate_enable()'s
2716 		 * preempt_enable() and scheduling the stopper task. At that
2717 		 * point we're a regular task again and not current anymore.
2718 		 *
2719 		 * A !PREEMPT kernel has a giant hole here, which makes it far
2720 		 * more likely.
2721 		 */
2722 
2723 		/*
2724 		 * The task moved before the stopper got to run. We're holding
2725 		 * ->pi_lock, so the allowed mask is stable - if it got
2726 		 * somewhere allowed, we're done.
2727 		 */
2728 		if (cpumask_test_cpu(task_cpu(p), p->cpus_ptr)) {
2729 			p->migration_pending = NULL;
2730 			complete = true;
2731 			goto out;
2732 		}
2733 
2734 		/*
2735 		 * When migrate_enable() hits a rq mis-match we can't reliably
2736 		 * determine is_migration_disabled() and so have to chase after
2737 		 * it.
2738 		 */
2739 		WARN_ON_ONCE(!pending->stop_pending);
2740 		preempt_disable();
2741 		task_rq_unlock(rq, p, &rf);
2742 		stop_one_cpu_nowait(task_cpu(p), migration_cpu_stop,
2743 				    &pending->arg, &pending->stop_work);
2744 		preempt_enable();
2745 		return 0;
2746 	}
2747 out:
2748 	if (pending)
2749 		pending->stop_pending = false;
2750 	task_rq_unlock(rq, p, &rf);
2751 
2752 	if (complete)
2753 		complete_all(&pending->done);
2754 
2755 	return 0;
2756 }
2757 
push_cpu_stop(void * arg)2758 int push_cpu_stop(void *arg)
2759 {
2760 	struct rq *lowest_rq = NULL, *rq = this_rq();
2761 	struct task_struct *p = arg;
2762 
2763 	raw_spin_lock_irq(&p->pi_lock);
2764 	raw_spin_rq_lock(rq);
2765 
2766 	if (task_rq(p) != rq)
2767 		goto out_unlock;
2768 
2769 	if (is_migration_disabled(p)) {
2770 		p->migration_flags |= MDF_PUSH;
2771 		goto out_unlock;
2772 	}
2773 
2774 	p->migration_flags &= ~MDF_PUSH;
2775 
2776 	if (p->sched_class->find_lock_rq)
2777 		lowest_rq = p->sched_class->find_lock_rq(p, rq);
2778 
2779 	if (!lowest_rq)
2780 		goto out_unlock;
2781 
2782 	// XXX validate p is still the highest prio task
2783 	if (task_rq(p) == rq) {
2784 		deactivate_task(rq, p, 0);
2785 		set_task_cpu(p, lowest_rq->cpu);
2786 		activate_task(lowest_rq, p, 0);
2787 		resched_curr(lowest_rq);
2788 	}
2789 
2790 	double_unlock_balance(rq, lowest_rq);
2791 
2792 out_unlock:
2793 	rq->push_busy = false;
2794 	raw_spin_rq_unlock(rq);
2795 	raw_spin_unlock_irq(&p->pi_lock);
2796 
2797 	put_task_struct(p);
2798 	return 0;
2799 }
2800 EXPORT_SYMBOL_GPL(push_cpu_stop);
2801 
2802 /*
2803  * sched_class::set_cpus_allowed must do the below, but is not required to
2804  * actually call this function.
2805  */
set_cpus_allowed_common(struct task_struct * p,struct affinity_context * ctx)2806 void set_cpus_allowed_common(struct task_struct *p, struct affinity_context *ctx)
2807 {
2808 	if (ctx->flags & (SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) {
2809 		p->cpus_ptr = ctx->new_mask;
2810 		return;
2811 	}
2812 
2813 	cpumask_copy(&p->cpus_mask, ctx->new_mask);
2814 	p->nr_cpus_allowed = cpumask_weight(ctx->new_mask);
2815 
2816 	/*
2817 	 * Swap in a new user_cpus_ptr if SCA_USER flag set
2818 	 */
2819 	if (ctx->flags & SCA_USER)
2820 		swap(p->user_cpus_ptr, ctx->user_mask);
2821 
2822 	trace_android_rvh_set_cpus_allowed_comm(p, ctx->new_mask);
2823 }
2824 
2825 static void
__do_set_cpus_allowed(struct task_struct * p,struct affinity_context * ctx)2826 __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx)
2827 {
2828 	struct rq *rq = task_rq(p);
2829 	bool queued, running;
2830 
2831 	/*
2832 	 * This here violates the locking rules for affinity, since we're only
2833 	 * supposed to change these variables while holding both rq->lock and
2834 	 * p->pi_lock.
2835 	 *
2836 	 * HOWEVER, it magically works, because ttwu() is the only code that
2837 	 * accesses these variables under p->pi_lock and only does so after
2838 	 * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule()
2839 	 * before finish_task().
2840 	 *
2841 	 * XXX do further audits, this smells like something putrid.
2842 	 */
2843 	if (ctx->flags & SCA_MIGRATE_DISABLE)
2844 		SCHED_WARN_ON(!p->on_cpu);
2845 	else
2846 		lockdep_assert_held(&p->pi_lock);
2847 
2848 	queued = task_on_rq_queued(p);
2849 	running = task_current(rq, p);
2850 
2851 	if (queued) {
2852 		/*
2853 		 * Because __kthread_bind() calls this on blocked tasks without
2854 		 * holding rq->lock.
2855 		 */
2856 		lockdep_assert_rq_held(rq);
2857 		dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
2858 	}
2859 	if (running)
2860 		put_prev_task(rq, p);
2861 
2862 	p->sched_class->set_cpus_allowed(p, ctx);
2863 
2864 	if (queued)
2865 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
2866 	if (running)
2867 		set_next_task(rq, p);
2868 }
2869 
2870 /*
2871  * Used for kthread_bind() and select_fallback_rq(), in both cases the user
2872  * affinity (if any) should be destroyed too.
2873  */
do_set_cpus_allowed(struct task_struct * p,const struct cpumask * new_mask)2874 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
2875 {
2876 	struct affinity_context ac = {
2877 		.new_mask  = new_mask,
2878 		.user_mask = NULL,
2879 		.flags     = SCA_USER,	/* clear the user requested mask */
2880 	};
2881 	union cpumask_rcuhead {
2882 		cpumask_t cpumask;
2883 		struct rcu_head rcu;
2884 	};
2885 
2886 	__do_set_cpus_allowed(p, &ac);
2887 
2888 	/*
2889 	 * Because this is called with p->pi_lock held, it is not possible
2890 	 * to use kfree() here (when PREEMPT_RT=y), therefore punt to using
2891 	 * kfree_rcu().
2892 	 */
2893 	kfree_rcu((union cpumask_rcuhead *)ac.user_mask, rcu);
2894 }
2895 
alloc_user_cpus_ptr(int node)2896 static cpumask_t *alloc_user_cpus_ptr(int node)
2897 {
2898 	/*
2899 	 * See do_set_cpus_allowed() above for the rcu_head usage.
2900 	 */
2901 	int size = max_t(int, cpumask_size(), sizeof(struct rcu_head));
2902 
2903 	return kmalloc_node(size, GFP_KERNEL, node);
2904 }
2905 
dup_user_cpus_ptr(struct task_struct * dst,struct task_struct * src,int node)2906 int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src,
2907 		      int node)
2908 {
2909 	cpumask_t *user_mask;
2910 	unsigned long flags;
2911 
2912 	/*
2913 	 * Always clear dst->user_cpus_ptr first as their user_cpus_ptr's
2914 	 * may differ by now due to racing.
2915 	 */
2916 	dst->user_cpus_ptr = NULL;
2917 
2918 	/*
2919 	 * This check is racy and losing the race is a valid situation.
2920 	 * It is not worth the extra overhead of taking the pi_lock on
2921 	 * every fork/clone.
2922 	 */
2923 	if (data_race(!src->user_cpus_ptr))
2924 		return 0;
2925 
2926 	user_mask = alloc_user_cpus_ptr(node);
2927 	if (!user_mask)
2928 		return -ENOMEM;
2929 
2930 	/*
2931 	 * Use pi_lock to protect content of user_cpus_ptr
2932 	 *
2933 	 * Though unlikely, user_cpus_ptr can be reset to NULL by a concurrent
2934 	 * do_set_cpus_allowed().
2935 	 */
2936 	raw_spin_lock_irqsave(&src->pi_lock, flags);
2937 	if (src->user_cpus_ptr) {
2938 		swap(dst->user_cpus_ptr, user_mask);
2939 		cpumask_copy(dst->user_cpus_ptr, src->user_cpus_ptr);
2940 	}
2941 	raw_spin_unlock_irqrestore(&src->pi_lock, flags);
2942 
2943 	if (unlikely(user_mask))
2944 		kfree(user_mask);
2945 
2946 	return 0;
2947 }
2948 
clear_user_cpus_ptr(struct task_struct * p)2949 static inline struct cpumask *clear_user_cpus_ptr(struct task_struct *p)
2950 {
2951 	struct cpumask *user_mask = NULL;
2952 
2953 	swap(p->user_cpus_ptr, user_mask);
2954 
2955 	return user_mask;
2956 }
2957 
release_user_cpus_ptr(struct task_struct * p)2958 void release_user_cpus_ptr(struct task_struct *p)
2959 {
2960 	kfree(clear_user_cpus_ptr(p));
2961 }
2962 
2963 /*
2964  * This function is wildly self concurrent; here be dragons.
2965  *
2966  *
2967  * When given a valid mask, __set_cpus_allowed_ptr() must block until the
2968  * designated task is enqueued on an allowed CPU. If that task is currently
2969  * running, we have to kick it out using the CPU stopper.
2970  *
2971  * Migrate-Disable comes along and tramples all over our nice sandcastle.
2972  * Consider:
2973  *
2974  *     Initial conditions: P0->cpus_mask = [0, 1]
2975  *
2976  *     P0@CPU0                  P1
2977  *
2978  *     migrate_disable();
2979  *     <preempted>
2980  *                              set_cpus_allowed_ptr(P0, [1]);
2981  *
2982  * P1 *cannot* return from this set_cpus_allowed_ptr() call until P0 executes
2983  * its outermost migrate_enable() (i.e. it exits its Migrate-Disable region).
2984  * This means we need the following scheme:
2985  *
2986  *     P0@CPU0                  P1
2987  *
2988  *     migrate_disable();
2989  *     <preempted>
2990  *                              set_cpus_allowed_ptr(P0, [1]);
2991  *                                <blocks>
2992  *     <resumes>
2993  *     migrate_enable();
2994  *       __set_cpus_allowed_ptr();
2995  *       <wakes local stopper>
2996  *                         `--> <woken on migration completion>
2997  *
2998  * Now the fun stuff: there may be several P1-like tasks, i.e. multiple
2999  * concurrent set_cpus_allowed_ptr(P0, [*]) calls. CPU affinity changes of any
3000  * task p are serialized by p->pi_lock, which we can leverage: the one that
3001  * should come into effect at the end of the Migrate-Disable region is the last
3002  * one. This means we only need to track a single cpumask (i.e. p->cpus_mask),
3003  * but we still need to properly signal those waiting tasks at the appropriate
3004  * moment.
3005  *
3006  * This is implemented using struct set_affinity_pending. The first
3007  * __set_cpus_allowed_ptr() caller within a given Migrate-Disable region will
3008  * setup an instance of that struct and install it on the targeted task_struct.
3009  * Any and all further callers will reuse that instance. Those then wait for
3010  * a completion signaled at the tail of the CPU stopper callback (1), triggered
3011  * on the end of the Migrate-Disable region (i.e. outermost migrate_enable()).
3012  *
3013  *
3014  * (1) In the cases covered above. There is one more where the completion is
3015  * signaled within affine_move_task() itself: when a subsequent affinity request
3016  * occurs after the stopper bailed out due to the targeted task still being
3017  * Migrate-Disable. Consider:
3018  *
3019  *     Initial conditions: P0->cpus_mask = [0, 1]
3020  *
3021  *     CPU0		  P1				P2
3022  *     <P0>
3023  *       migrate_disable();
3024  *       <preempted>
3025  *                        set_cpus_allowed_ptr(P0, [1]);
3026  *                          <blocks>
3027  *     <migration/0>
3028  *       migration_cpu_stop()
3029  *         is_migration_disabled()
3030  *           <bails>
3031  *                                                       set_cpus_allowed_ptr(P0, [0, 1]);
3032  *                                                         <signal completion>
3033  *                          <awakes>
3034  *
3035  * Note that the above is safe vs a concurrent migrate_enable(), as any
3036  * pending affinity completion is preceded by an uninstallation of
3037  * p->migration_pending done with p->pi_lock held.
3038  */
affine_move_task(struct rq * rq,struct task_struct * p,struct rq_flags * rf,int dest_cpu,unsigned int flags)3039 static int affine_move_task(struct rq *rq, struct task_struct *p, struct rq_flags *rf,
3040 			    int dest_cpu, unsigned int flags)
3041 	__releases(rq->lock)
3042 	__releases(p->pi_lock)
3043 {
3044 	struct set_affinity_pending my_pending = { }, *pending = NULL;
3045 	bool stop_pending, complete = false;
3046 
3047 	/* Can the task run on the task's current CPU? If so, we're done */
3048 	if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) {
3049 		struct task_struct *push_task = NULL;
3050 
3051 		if ((flags & SCA_MIGRATE_ENABLE) &&
3052 		    (p->migration_flags & MDF_PUSH) && !rq->push_busy) {
3053 			rq->push_busy = true;
3054 			push_task = get_task_struct(p);
3055 		}
3056 
3057 		/*
3058 		 * If there are pending waiters, but no pending stop_work,
3059 		 * then complete now.
3060 		 */
3061 		pending = p->migration_pending;
3062 		if (pending && !pending->stop_pending) {
3063 			p->migration_pending = NULL;
3064 			complete = true;
3065 		}
3066 
3067 		preempt_disable();
3068 		task_rq_unlock(rq, p, rf);
3069 		if (push_task) {
3070 			stop_one_cpu_nowait(rq->cpu, push_cpu_stop,
3071 					    p, &rq->push_work);
3072 		}
3073 		preempt_enable();
3074 
3075 		if (complete)
3076 			complete_all(&pending->done);
3077 
3078 		return 0;
3079 	}
3080 
3081 	if (!(flags & SCA_MIGRATE_ENABLE)) {
3082 		/* serialized by p->pi_lock */
3083 		if (!p->migration_pending) {
3084 			/* Install the request */
3085 			refcount_set(&my_pending.refs, 1);
3086 			init_completion(&my_pending.done);
3087 			my_pending.arg = (struct migration_arg) {
3088 				.task = p,
3089 				.dest_cpu = dest_cpu,
3090 				.pending = &my_pending,
3091 			};
3092 
3093 			p->migration_pending = &my_pending;
3094 		} else {
3095 			pending = p->migration_pending;
3096 			refcount_inc(&pending->refs);
3097 			/*
3098 			 * Affinity has changed, but we've already installed a
3099 			 * pending. migration_cpu_stop() *must* see this, else
3100 			 * we risk a completion of the pending despite having a
3101 			 * task on a disallowed CPU.
3102 			 *
3103 			 * Serialized by p->pi_lock, so this is safe.
3104 			 */
3105 			pending->arg.dest_cpu = dest_cpu;
3106 		}
3107 	}
3108 	pending = p->migration_pending;
3109 	/*
3110 	 * - !MIGRATE_ENABLE:
3111 	 *   we'll have installed a pending if there wasn't one already.
3112 	 *
3113 	 * - MIGRATE_ENABLE:
3114 	 *   we're here because the current CPU isn't matching anymore,
3115 	 *   the only way that can happen is because of a concurrent
3116 	 *   set_cpus_allowed_ptr() call, which should then still be
3117 	 *   pending completion.
3118 	 *
3119 	 * Either way, we really should have a @pending here.
3120 	 */
3121 	if (WARN_ON_ONCE(!pending)) {
3122 		task_rq_unlock(rq, p, rf);
3123 		return -EINVAL;
3124 	}
3125 
3126 	if (task_on_cpu(rq, p) || READ_ONCE(p->__state) == TASK_WAKING) {
3127 		/*
3128 		 * MIGRATE_ENABLE gets here because 'p == current', but for
3129 		 * anything else we cannot do is_migration_disabled(), punt
3130 		 * and have the stopper function handle it all race-free.
3131 		 */
3132 		stop_pending = pending->stop_pending;
3133 		if (!stop_pending)
3134 			pending->stop_pending = true;
3135 
3136 		if (flags & SCA_MIGRATE_ENABLE)
3137 			p->migration_flags &= ~MDF_PUSH;
3138 
3139 		preempt_disable();
3140 		task_rq_unlock(rq, p, rf);
3141 		if (!stop_pending) {
3142 			stop_one_cpu_nowait(cpu_of(rq), migration_cpu_stop,
3143 					    &pending->arg, &pending->stop_work);
3144 		}
3145 		preempt_enable();
3146 
3147 		if (flags & SCA_MIGRATE_ENABLE)
3148 			return 0;
3149 	} else {
3150 
3151 		if (!is_migration_disabled(p)) {
3152 			if (task_on_rq_queued(p))
3153 				rq = move_queued_task(rq, rf, p, dest_cpu);
3154 
3155 			if (!pending->stop_pending) {
3156 				p->migration_pending = NULL;
3157 				complete = true;
3158 			}
3159 		}
3160 		task_rq_unlock(rq, p, rf);
3161 
3162 		if (complete)
3163 			complete_all(&pending->done);
3164 	}
3165 
3166 	wait_for_completion(&pending->done);
3167 
3168 	if (refcount_dec_and_test(&pending->refs))
3169 		wake_up_var(&pending->refs); /* No UaF, just an address */
3170 
3171 	/*
3172 	 * Block the original owner of &pending until all subsequent callers
3173 	 * have seen the completion and decremented the refcount
3174 	 */
3175 	wait_var_event(&my_pending.refs, !refcount_read(&my_pending.refs));
3176 
3177 	/* ARGH */
3178 	WARN_ON_ONCE(my_pending.stop_pending);
3179 
3180 	return 0;
3181 }
3182 
3183 /*
3184  * Called with both p->pi_lock and rq->lock held; drops both before returning.
3185  */
__set_cpus_allowed_ptr_locked(struct task_struct * p,struct affinity_context * ctx,struct rq * rq,struct rq_flags * rf)3186 static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
3187 					 struct affinity_context *ctx,
3188 					 struct rq *rq,
3189 					 struct rq_flags *rf)
3190 	__releases(rq->lock)
3191 	__releases(p->pi_lock)
3192 {
3193 	const struct cpumask *cpu_allowed_mask = task_cpu_possible_mask(p);
3194 	const struct cpumask *cpu_valid_mask = cpu_active_mask;
3195 	bool kthread = p->flags & PF_KTHREAD;
3196 	unsigned int dest_cpu;
3197 	int ret = 0;
3198 
3199 	update_rq_clock(rq);
3200 
3201 	if (kthread || is_migration_disabled(p)) {
3202 		/*
3203 		 * Kernel threads are allowed on online && !active CPUs,
3204 		 * however, during cpu-hot-unplug, even these might get pushed
3205 		 * away if not KTHREAD_IS_PER_CPU.
3206 		 *
3207 		 * Specifically, migration_disabled() tasks must not fail the
3208 		 * cpumask_any_and_distribute() pick below, esp. so on
3209 		 * SCA_MIGRATE_ENABLE, otherwise we'll not call
3210 		 * set_cpus_allowed_common() and actually reset p->cpus_ptr.
3211 		 */
3212 		cpu_valid_mask = cpu_online_mask;
3213 	}
3214 
3215 	if (!kthread && !cpumask_subset(ctx->new_mask, cpu_allowed_mask)) {
3216 		ret = -EINVAL;
3217 		goto out;
3218 	}
3219 
3220 	/*
3221 	 * Must re-check here, to close a race against __kthread_bind(),
3222 	 * sched_setaffinity() is not guaranteed to observe the flag.
3223 	 */
3224 	if ((ctx->flags & SCA_CHECK) && (p->flags & PF_NO_SETAFFINITY)) {
3225 		ret = -EINVAL;
3226 		goto out;
3227 	}
3228 
3229 	if (!(ctx->flags & SCA_MIGRATE_ENABLE)) {
3230 		if (cpumask_equal(&p->cpus_mask, ctx->new_mask)) {
3231 			if (ctx->flags & SCA_USER)
3232 				swap(p->user_cpus_ptr, ctx->user_mask);
3233 			goto out;
3234 		}
3235 
3236 		if (WARN_ON_ONCE(p == current &&
3237 				 is_migration_disabled(p) &&
3238 				 !cpumask_test_cpu(task_cpu(p), ctx->new_mask))) {
3239 			ret = -EBUSY;
3240 			goto out;
3241 		}
3242 	}
3243 
3244 	/*
3245 	 * Picking a ~random cpu helps in cases where we are changing affinity
3246 	 * for groups of tasks (ie. cpuset), so that load balancing is not
3247 	 * immediately required to distribute the tasks within their new mask.
3248 	 */
3249 	dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, ctx->new_mask);
3250 	trace_android_rvh_set_cpus_allowed_by_task(cpu_valid_mask, ctx->new_mask, p, &dest_cpu);
3251 	if (dest_cpu >= nr_cpu_ids) {
3252 		ret = -EINVAL;
3253 		goto out;
3254 	}
3255 
3256 	__do_set_cpus_allowed(p, ctx);
3257 
3258 	return affine_move_task(rq, p, rf, dest_cpu, ctx->flags);
3259 
3260 out:
3261 	task_rq_unlock(rq, p, rf);
3262 
3263 	return ret;
3264 }
3265 
3266 /*
3267  * Change a given task's CPU affinity. Migrate the thread to a
3268  * proper CPU and schedule it away if the CPU it's executing on
3269  * is removed from the allowed bitmask.
3270  *
3271  * NOTE: the caller must have a valid reference to the task, the
3272  * task must not exit() & deallocate itself prematurely. The
3273  * call is not atomic; no spinlocks may be held.
3274  */
__set_cpus_allowed_ptr(struct task_struct * p,struct affinity_context * ctx)3275 static int __set_cpus_allowed_ptr(struct task_struct *p,
3276 				  struct affinity_context *ctx)
3277 {
3278 	struct rq_flags rf;
3279 	struct rq *rq;
3280 	bool skip_user_ptr = false;
3281 
3282 	trace_android_rvh_set_cpus_allowed_ptr(p, ctx, &skip_user_ptr);
3283 	rq = task_rq_lock(p, &rf);
3284 	/*
3285 	 * Masking should be skipped if SCA_USER or any of the SCA_MIGRATE_*
3286 	 * flags are set.
3287 	 */
3288 	if (!skip_user_ptr && p->user_cpus_ptr &&
3289 	    !(ctx->flags & (SCA_USER | SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) &&
3290 	    cpumask_and(rq->scratch_mask, ctx->new_mask, p->user_cpus_ptr))
3291 		ctx->new_mask = rq->scratch_mask;
3292 
3293 	return __set_cpus_allowed_ptr_locked(p, ctx, rq, &rf);
3294 }
3295 
set_cpus_allowed_ptr(struct task_struct * p,const struct cpumask * new_mask)3296 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
3297 {
3298 	struct affinity_context ac = {
3299 		.new_mask  = new_mask,
3300 		.flags     = 0,
3301 	};
3302 
3303 	return __set_cpus_allowed_ptr(p, &ac);
3304 }
3305 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
3306 
3307 /*
3308  * Change a given task's CPU affinity to the intersection of its current
3309  * affinity mask and @subset_mask, writing the resulting mask to @new_mask.
3310  * If user_cpus_ptr is defined, use it as the basis for restricting CPU
3311  * affinity or use cpu_online_mask instead.
3312  *
3313  * If the resulting mask is empty, leave the affinity unchanged and return
3314  * -EINVAL.
3315  */
restrict_cpus_allowed_ptr(struct task_struct * p,struct cpumask * new_mask,const struct cpumask * subset_mask)3316 static int restrict_cpus_allowed_ptr(struct task_struct *p,
3317 				     struct cpumask *new_mask,
3318 				     const struct cpumask *subset_mask)
3319 {
3320 	struct affinity_context ac = {
3321 		.new_mask  = new_mask,
3322 		.flags     = 0,
3323 	};
3324 	struct rq_flags rf;
3325 	struct rq *rq;
3326 	int err;
3327 
3328 	rq = task_rq_lock(p, &rf);
3329 
3330 	/*
3331 	 * Forcefully restricting the affinity of a deadline task is
3332 	 * likely to cause problems, so fail and noisily override the
3333 	 * mask entirely.
3334 	 */
3335 	if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
3336 		err = -EPERM;
3337 		goto err_unlock;
3338 	}
3339 
3340 	if (!cpumask_and(new_mask, task_user_cpus(p), subset_mask)) {
3341 		err = -EINVAL;
3342 		goto err_unlock;
3343 	}
3344 
3345 	return __set_cpus_allowed_ptr_locked(p, &ac, rq, &rf);
3346 
3347 err_unlock:
3348 	task_rq_unlock(rq, p, &rf);
3349 	return err;
3350 }
3351 
3352 /*
3353  * Restrict the CPU affinity of task @p so that it is a subset of
3354  * task_cpu_possible_mask() and point @p->user_cpus_ptr to a copy of the
3355  * old affinity mask. If the resulting mask is empty, we warn and walk
3356  * up the cpuset hierarchy until we find a suitable mask.
3357  */
force_compatible_cpus_allowed_ptr(struct task_struct * p)3358 void force_compatible_cpus_allowed_ptr(struct task_struct *p)
3359 {
3360 	cpumask_var_t new_mask;
3361 	const struct cpumask *override_mask = task_cpu_possible_mask(p);
3362 
3363 	alloc_cpumask_var(&new_mask, GFP_KERNEL);
3364 
3365 	/*
3366 	 * __migrate_task() can fail silently in the face of concurrent
3367 	 * offlining of the chosen destination CPU, so take the hotplug
3368 	 * lock to ensure that the migration succeeds.
3369 	 */
3370 	cpus_read_lock();
3371 	if (!cpumask_available(new_mask))
3372 		goto out_set_mask;
3373 
3374 	if (!restrict_cpus_allowed_ptr(p, new_mask, override_mask))
3375 		goto out_free_mask;
3376 
3377 	/*
3378 	 * We failed to find a valid subset of the affinity mask for the
3379 	 * task, so override it based on its cpuset hierarchy.
3380 	 */
3381 	cpuset_cpus_allowed(p, new_mask);
3382 	override_mask = new_mask;
3383 
3384 out_set_mask:
3385 	if (printk_ratelimit()) {
3386 		printk_deferred("Overriding affinity for process %d (%s) to CPUs %*pbl\n",
3387 				task_pid_nr(p), p->comm,
3388 				cpumask_pr_args(override_mask));
3389 	}
3390 
3391 	WARN_ON(set_cpus_allowed_ptr(p, override_mask));
3392 out_free_mask:
3393 	cpus_read_unlock();
3394 	free_cpumask_var(new_mask);
3395 }
3396 
3397 static int
3398 __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx);
3399 
3400 /*
3401  * Restore the affinity of a task @p which was previously restricted by a
3402  * call to force_compatible_cpus_allowed_ptr().
3403  *
3404  * It is the caller's responsibility to serialise this with any calls to
3405  * force_compatible_cpus_allowed_ptr(@p).
3406  */
relax_compatible_cpus_allowed_ptr(struct task_struct * p)3407 void relax_compatible_cpus_allowed_ptr(struct task_struct *p)
3408 {
3409 	struct affinity_context ac = {
3410 		.new_mask  = task_user_cpus(p),
3411 		.flags     = 0,
3412 	};
3413 	int ret;
3414 
3415 	/*
3416 	 * Try to restore the old affinity mask with __sched_setaffinity().
3417 	 * Cpuset masking will be done there too.
3418 	 */
3419 	ret = __sched_setaffinity(p, &ac);
3420 	WARN_ON_ONCE(ret);
3421 }
3422 
set_task_cpu(struct task_struct * p,unsigned int new_cpu)3423 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
3424 {
3425 #ifdef CONFIG_SCHED_DEBUG
3426 	unsigned int state = READ_ONCE(p->__state);
3427 
3428 	/*
3429 	 * We should never call set_task_cpu() on a blocked task,
3430 	 * ttwu() will sort out the placement.
3431 	 */
3432 	WARN_ON_ONCE(state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq);
3433 
3434 	/*
3435 	 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
3436 	 * because schedstat_wait_{start,end} rebase migrating task's wait_start
3437 	 * time relying on p->on_rq.
3438 	 */
3439 	WARN_ON_ONCE(state == TASK_RUNNING &&
3440 		     p->sched_class == &fair_sched_class &&
3441 		     (p->on_rq && !task_on_rq_migrating(p)));
3442 
3443 #ifdef CONFIG_LOCKDEP
3444 	/*
3445 	 * The caller should hold either p->pi_lock or rq->lock, when changing
3446 	 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
3447 	 *
3448 	 * sched_move_task() holds both and thus holding either pins the cgroup,
3449 	 * see task_group().
3450 	 *
3451 	 * Furthermore, all task_rq users should acquire both locks, see
3452 	 * task_rq_lock().
3453 	 */
3454 	WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
3455 				      lockdep_is_held(__rq_lockp(task_rq(p)))));
3456 #endif
3457 	/*
3458 	 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
3459 	 */
3460 	WARN_ON_ONCE(!cpu_online(new_cpu));
3461 
3462 	WARN_ON_ONCE(is_migration_disabled(p));
3463 #endif
3464 
3465 	trace_sched_migrate_task(p, new_cpu);
3466 
3467 	if (task_cpu(p) != new_cpu) {
3468 		if (p->sched_class->migrate_task_rq)
3469 			p->sched_class->migrate_task_rq(p, new_cpu);
3470 		p->se.nr_migrations++;
3471 		rseq_migrate(p);
3472 		sched_mm_cid_migrate_from(p);
3473 		perf_event_task_migrate(p);
3474 		trace_android_rvh_set_task_cpu(p, new_cpu);
3475 	}
3476 
3477 	__set_task_cpu(p, new_cpu);
3478 }
3479 EXPORT_SYMBOL_GPL(set_task_cpu);
3480 
__migrate_swap_task(struct task_struct * p,int cpu)3481 static void __migrate_swap_task(struct task_struct *p, int cpu)
3482 {
3483 	if (task_on_rq_queued(p)) {
3484 		struct rq *src_rq, *dst_rq;
3485 		struct rq_flags srf, drf;
3486 
3487 		src_rq = task_rq(p);
3488 		dst_rq = cpu_rq(cpu);
3489 
3490 		rq_pin_lock(src_rq, &srf);
3491 		rq_pin_lock(dst_rq, &drf);
3492 
3493 		deactivate_task(src_rq, p, 0);
3494 		set_task_cpu(p, cpu);
3495 		activate_task(dst_rq, p, 0);
3496 		check_preempt_curr(dst_rq, p, 0);
3497 
3498 		rq_unpin_lock(dst_rq, &drf);
3499 		rq_unpin_lock(src_rq, &srf);
3500 
3501 	} else {
3502 		/*
3503 		 * Task isn't running anymore; make it appear like we migrated
3504 		 * it before it went to sleep. This means on wakeup we make the
3505 		 * previous CPU our target instead of where it really is.
3506 		 */
3507 		p->wake_cpu = cpu;
3508 	}
3509 }
3510 
3511 struct migration_swap_arg {
3512 	struct task_struct *src_task, *dst_task;
3513 	int src_cpu, dst_cpu;
3514 };
3515 
migrate_swap_stop(void * data)3516 static int migrate_swap_stop(void *data)
3517 {
3518 	struct migration_swap_arg *arg = data;
3519 	struct rq *src_rq, *dst_rq;
3520 
3521 	if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
3522 		return -EAGAIN;
3523 
3524 	src_rq = cpu_rq(arg->src_cpu);
3525 	dst_rq = cpu_rq(arg->dst_cpu);
3526 
3527 	guard(double_raw_spinlock)(&arg->src_task->pi_lock, &arg->dst_task->pi_lock);
3528 	guard(double_rq_lock)(src_rq, dst_rq);
3529 
3530 	if (task_cpu(arg->dst_task) != arg->dst_cpu)
3531 		return -EAGAIN;
3532 
3533 	if (task_cpu(arg->src_task) != arg->src_cpu)
3534 		return -EAGAIN;
3535 
3536 	if (!cpumask_test_cpu(arg->dst_cpu, arg->src_task->cpus_ptr))
3537 		return -EAGAIN;
3538 
3539 	if (!cpumask_test_cpu(arg->src_cpu, arg->dst_task->cpus_ptr))
3540 		return -EAGAIN;
3541 
3542 	__migrate_swap_task(arg->src_task, arg->dst_cpu);
3543 	__migrate_swap_task(arg->dst_task, arg->src_cpu);
3544 
3545 	return 0;
3546 }
3547 
3548 /*
3549  * Cross migrate two tasks
3550  */
migrate_swap(struct task_struct * cur,struct task_struct * p,int target_cpu,int curr_cpu)3551 int migrate_swap(struct task_struct *cur, struct task_struct *p,
3552 		int target_cpu, int curr_cpu)
3553 {
3554 	struct migration_swap_arg arg;
3555 	int ret = -EINVAL;
3556 
3557 	arg = (struct migration_swap_arg){
3558 		.src_task = cur,
3559 		.src_cpu = curr_cpu,
3560 		.dst_task = p,
3561 		.dst_cpu = target_cpu,
3562 	};
3563 
3564 	if (arg.src_cpu == arg.dst_cpu)
3565 		goto out;
3566 
3567 	/*
3568 	 * These three tests are all lockless; this is OK since all of them
3569 	 * will be re-checked with proper locks held further down the line.
3570 	 */
3571 	if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
3572 		goto out;
3573 
3574 	if (!cpumask_test_cpu(arg.dst_cpu, arg.src_task->cpus_ptr))
3575 		goto out;
3576 
3577 	if (!cpumask_test_cpu(arg.src_cpu, arg.dst_task->cpus_ptr))
3578 		goto out;
3579 
3580 	trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
3581 	ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
3582 
3583 out:
3584 	return ret;
3585 }
3586 EXPORT_SYMBOL_GPL(migrate_swap);
3587 
3588 /***
3589  * kick_process - kick a running thread to enter/exit the kernel
3590  * @p: the to-be-kicked thread
3591  *
3592  * Cause a process which is running on another CPU to enter
3593  * kernel-mode, without any delay. (to get signals handled.)
3594  *
3595  * NOTE: this function doesn't have to take the runqueue lock,
3596  * because all it wants to ensure is that the remote task enters
3597  * the kernel. If the IPI races and the task has been migrated
3598  * to another CPU then no harm is done and the purpose has been
3599  * achieved as well.
3600  */
kick_process(struct task_struct * p)3601 void kick_process(struct task_struct *p)
3602 {
3603 	int cpu;
3604 
3605 	preempt_disable();
3606 	cpu = task_cpu(p);
3607 	if ((cpu != smp_processor_id()) && task_curr(p))
3608 		smp_send_reschedule(cpu);
3609 	preempt_enable();
3610 }
3611 EXPORT_SYMBOL_GPL(kick_process);
3612 
3613 /*
3614  * ->cpus_ptr is protected by both rq->lock and p->pi_lock
3615  *
3616  * A few notes on cpu_active vs cpu_online:
3617  *
3618  *  - cpu_active must be a subset of cpu_online
3619  *
3620  *  - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
3621  *    see __set_cpus_allowed_ptr(). At this point the newly online
3622  *    CPU isn't yet part of the sched domains, and balancing will not
3623  *    see it.
3624  *
3625  *  - on CPU-down we clear cpu_active() to mask the sched domains and
3626  *    avoid the load balancer to place new tasks on the to be removed
3627  *    CPU. Existing tasks will remain running there and will be taken
3628  *    off.
3629  *
3630  * This means that fallback selection must not select !active CPUs.
3631  * And can assume that any active CPU must be online. Conversely
3632  * select_task_rq() below may allow selection of !active CPUs in order
3633  * to satisfy the above rules.
3634  */
select_fallback_rq(int cpu,struct task_struct * p)3635 int select_fallback_rq(int cpu, struct task_struct *p)
3636 {
3637 	int nid = cpu_to_node(cpu);
3638 	const struct cpumask *nodemask = NULL;
3639 	enum { cpuset, possible, fail } state = cpuset;
3640 	int dest_cpu = -1;
3641 
3642 	trace_android_rvh_select_fallback_rq(cpu, p, &dest_cpu);
3643 	if (dest_cpu >= 0)
3644 		return dest_cpu;
3645 
3646 	/*
3647 	 * If the node that the CPU is on has been offlined, cpu_to_node()
3648 	 * will return -1. There is no CPU on the node, and we should
3649 	 * select the CPU on the other node.
3650 	 */
3651 	if (nid != -1) {
3652 		nodemask = cpumask_of_node(nid);
3653 
3654 		/* Look for allowed, online CPU in same node. */
3655 		for_each_cpu(dest_cpu, nodemask) {
3656 			if (is_cpu_allowed(p, dest_cpu))
3657 				return dest_cpu;
3658 		}
3659 	}
3660 
3661 	for (;;) {
3662 		/* Any allowed, online CPU? */
3663 		for_each_cpu(dest_cpu, p->cpus_ptr) {
3664 			if (!is_cpu_allowed(p, dest_cpu))
3665 				continue;
3666 
3667 			goto out;
3668 		}
3669 
3670 		/* No more Mr. Nice Guy. */
3671 		switch (state) {
3672 		case cpuset:
3673 			if (cpuset_cpus_allowed_fallback(p)) {
3674 				state = possible;
3675 				break;
3676 			}
3677 			fallthrough;
3678 		case possible:
3679 			/*
3680 			 * XXX When called from select_task_rq() we only
3681 			 * hold p->pi_lock and again violate locking order.
3682 			 *
3683 			 * More yuck to audit.
3684 			 */
3685 			do_set_cpus_allowed(p, task_cpu_possible_mask(p));
3686 			state = fail;
3687 			break;
3688 		case fail:
3689 			BUG();
3690 			break;
3691 		}
3692 	}
3693 
3694 out:
3695 	if (state != cpuset) {
3696 		/*
3697 		 * Don't tell them about moving exiting tasks or
3698 		 * kernel threads (both mm NULL), since they never
3699 		 * leave kernel.
3700 		 */
3701 		if (p->mm && printk_ratelimit()) {
3702 			printk_deferred("process %d (%s) no longer affine to cpu%d\n",
3703 					task_pid_nr(p), p->comm, cpu);
3704 		}
3705 	}
3706 
3707 	return dest_cpu;
3708 }
3709 EXPORT_SYMBOL_GPL(select_fallback_rq);
3710 
3711 /*
3712  * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
3713  */
3714 static inline
select_task_rq(struct task_struct * p,int cpu,int wake_flags)3715 int select_task_rq(struct task_struct *p, int cpu, int wake_flags)
3716 {
3717 	lockdep_assert_held(&p->pi_lock);
3718 
3719 	if (p->nr_cpus_allowed > 1 && !is_migration_disabled(p))
3720 		cpu = p->sched_class->select_task_rq(p, cpu, wake_flags);
3721 	else
3722 		cpu = cpumask_any(p->cpus_ptr);
3723 
3724 	/*
3725 	 * In order not to call set_task_cpu() on a blocking task we need
3726 	 * to rely on ttwu() to place the task on a valid ->cpus_ptr
3727 	 * CPU.
3728 	 *
3729 	 * Since this is common to all placement strategies, this lives here.
3730 	 *
3731 	 * [ this allows ->select_task() to simply return task_cpu(p) and
3732 	 *   not worry about this generic constraint ]
3733 	 */
3734 	if (unlikely(!is_cpu_allowed(p, cpu)))
3735 		cpu = select_fallback_rq(task_cpu(p), p);
3736 
3737 	return cpu;
3738 }
3739 
sched_set_stop_task(int cpu,struct task_struct * stop)3740 void sched_set_stop_task(int cpu, struct task_struct *stop)
3741 {
3742 	static struct lock_class_key stop_pi_lock;
3743 	struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
3744 	struct task_struct *old_stop = cpu_rq(cpu)->stop;
3745 
3746 	if (stop) {
3747 		/*
3748 		 * Make it appear like a SCHED_FIFO task, its something
3749 		 * userspace knows about and won't get confused about.
3750 		 *
3751 		 * Also, it will make PI more or less work without too
3752 		 * much confusion -- but then, stop work should not
3753 		 * rely on PI working anyway.
3754 		 */
3755 		sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
3756 
3757 		stop->sched_class = &stop_sched_class;
3758 
3759 		/*
3760 		 * The PI code calls rt_mutex_setprio() with ->pi_lock held to
3761 		 * adjust the effective priority of a task. As a result,
3762 		 * rt_mutex_setprio() can trigger (RT) balancing operations,
3763 		 * which can then trigger wakeups of the stop thread to push
3764 		 * around the current task.
3765 		 *
3766 		 * The stop task itself will never be part of the PI-chain, it
3767 		 * never blocks, therefore that ->pi_lock recursion is safe.
3768 		 * Tell lockdep about this by placing the stop->pi_lock in its
3769 		 * own class.
3770 		 */
3771 		lockdep_set_class(&stop->pi_lock, &stop_pi_lock);
3772 	}
3773 
3774 	cpu_rq(cpu)->stop = stop;
3775 
3776 	if (old_stop) {
3777 		/*
3778 		 * Reset it back to a normal scheduling class so that
3779 		 * it can die in pieces.
3780 		 */
3781 		old_stop->sched_class = &rt_sched_class;
3782 	}
3783 }
3784 
3785 #else /* CONFIG_SMP */
3786 
__set_cpus_allowed_ptr(struct task_struct * p,struct affinity_context * ctx)3787 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
3788 					 struct affinity_context *ctx)
3789 {
3790 	return set_cpus_allowed_ptr(p, ctx->new_mask);
3791 }
3792 
migrate_disable_switch(struct rq * rq,struct task_struct * p)3793 static inline void migrate_disable_switch(struct rq *rq, struct task_struct *p) { }
3794 
rq_has_pinned_tasks(struct rq * rq)3795 static inline bool rq_has_pinned_tasks(struct rq *rq)
3796 {
3797 	return false;
3798 }
3799 
alloc_user_cpus_ptr(int node)3800 static inline cpumask_t *alloc_user_cpus_ptr(int node)
3801 {
3802 	return NULL;
3803 }
3804 
3805 #endif /* !CONFIG_SMP */
3806 
3807 static void
ttwu_stat(struct task_struct * p,int cpu,int wake_flags)3808 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
3809 {
3810 	struct rq *rq;
3811 
3812 	if (!schedstat_enabled())
3813 		return;
3814 
3815 	rq = this_rq();
3816 
3817 #ifdef CONFIG_SMP
3818 	if (cpu == rq->cpu) {
3819 		__schedstat_inc(rq->ttwu_local);
3820 		__schedstat_inc(p->stats.nr_wakeups_local);
3821 	} else {
3822 		struct sched_domain *sd;
3823 
3824 		__schedstat_inc(p->stats.nr_wakeups_remote);
3825 
3826 		guard(rcu)();
3827 		for_each_domain(rq->cpu, sd) {
3828 			if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
3829 				__schedstat_inc(sd->ttwu_wake_remote);
3830 				break;
3831 			}
3832 		}
3833 	}
3834 
3835 	if (wake_flags & WF_MIGRATED)
3836 		__schedstat_inc(p->stats.nr_wakeups_migrate);
3837 #endif /* CONFIG_SMP */
3838 
3839 	__schedstat_inc(rq->ttwu_count);
3840 	__schedstat_inc(p->stats.nr_wakeups);
3841 
3842 	if (wake_flags & WF_SYNC)
3843 		__schedstat_inc(p->stats.nr_wakeups_sync);
3844 }
3845 
3846 /*
3847  * Mark the task runnable.
3848  */
ttwu_do_wakeup(struct task_struct * p)3849 static inline void ttwu_do_wakeup(struct task_struct *p)
3850 {
3851 	WRITE_ONCE(p->__state, TASK_RUNNING);
3852 	trace_sched_wakeup(p);
3853 }
3854 
3855 static void
ttwu_do_activate(struct rq * rq,struct task_struct * p,int wake_flags,struct rq_flags * rf)3856 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
3857 		 struct rq_flags *rf)
3858 {
3859 	int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
3860 
3861 	if (wake_flags & WF_SYNC)
3862 		en_flags |= ENQUEUE_WAKEUP_SYNC;
3863 
3864 	lockdep_assert_rq_held(rq);
3865 
3866 	if (p->sched_contributes_to_load)
3867 		rq->nr_uninterruptible--;
3868 
3869 #ifdef CONFIG_SMP
3870 	if (wake_flags & WF_MIGRATED)
3871 		en_flags |= ENQUEUE_MIGRATED;
3872 	else
3873 #endif
3874 	if (p->in_iowait) {
3875 		delayacct_blkio_end(p);
3876 		atomic_dec(&task_rq(p)->nr_iowait);
3877 	}
3878 
3879 	activate_task(rq, p, en_flags);
3880 	check_preempt_curr(rq, p, wake_flags);
3881 
3882 	ttwu_do_wakeup(p);
3883 
3884 #ifdef CONFIG_SMP
3885 	if (p->sched_class->task_woken) {
3886 		/*
3887 		 * Our task @p is fully woken up and running; so it's safe to
3888 		 * drop the rq->lock, hereafter rq is only used for statistics.
3889 		 */
3890 		rq_unpin_lock(rq, rf);
3891 		p->sched_class->task_woken(rq, p);
3892 		rq_repin_lock(rq, rf);
3893 	}
3894 
3895 	if (rq->idle_stamp) {
3896 		u64 delta = rq_clock(rq) - rq->idle_stamp;
3897 		u64 max = 2*rq->max_idle_balance_cost;
3898 
3899 		update_avg(&rq->avg_idle, delta);
3900 
3901 		if (rq->avg_idle > max)
3902 			rq->avg_idle = max;
3903 
3904 		rq->wake_stamp = jiffies;
3905 		rq->wake_avg_idle = rq->avg_idle / 2;
3906 
3907 		rq->idle_stamp = 0;
3908 	}
3909 #endif
3910 }
3911 
3912 /*
3913  * Consider @p being inside a wait loop:
3914  *
3915  *   for (;;) {
3916  *      set_current_state(TASK_UNINTERRUPTIBLE);
3917  *
3918  *      if (CONDITION)
3919  *         break;
3920  *
3921  *      schedule();
3922  *   }
3923  *   __set_current_state(TASK_RUNNING);
3924  *
3925  * between set_current_state() and schedule(). In this case @p is still
3926  * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
3927  * an atomic manner.
3928  *
3929  * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
3930  * then schedule() must still happen and p->state can be changed to
3931  * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
3932  * need to do a full wakeup with enqueue.
3933  *
3934  * Returns: %true when the wakeup is done,
3935  *          %false otherwise.
3936  */
ttwu_runnable(struct task_struct * p,int wake_flags)3937 static int ttwu_runnable(struct task_struct *p, int wake_flags)
3938 {
3939 	struct rq_flags rf;
3940 	struct rq *rq;
3941 	int ret = 0;
3942 
3943 	rq = __task_rq_lock(p, &rf);
3944 	if (task_on_rq_queued(p)) {
3945 		if (!task_on_cpu(rq, p)) {
3946 			/*
3947 			 * When on_rq && !on_cpu the task is preempted, see if
3948 			 * it should preempt the task that is current now.
3949 			 */
3950 			update_rq_clock(rq);
3951 			check_preempt_curr(rq, p, wake_flags);
3952 		}
3953 		ttwu_do_wakeup(p);
3954 		ret = 1;
3955 	}
3956 	__task_rq_unlock(rq, &rf);
3957 
3958 	return ret;
3959 }
3960 
3961 #ifdef CONFIG_SMP
sched_ttwu_pending(void * arg)3962 void sched_ttwu_pending(void *arg)
3963 {
3964 	struct llist_node *llist = arg;
3965 	struct rq *rq = this_rq();
3966 	struct task_struct *p, *t;
3967 	struct rq_flags rf;
3968 
3969 	if (!llist)
3970 		return;
3971 
3972 	rq_lock_irqsave(rq, &rf);
3973 	update_rq_clock(rq);
3974 
3975 	llist_for_each_entry_safe(p, t, llist, wake_entry.llist) {
3976 		if (WARN_ON_ONCE(p->on_cpu))
3977 			smp_cond_load_acquire(&p->on_cpu, !VAL);
3978 
3979 		if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq)))
3980 			set_task_cpu(p, cpu_of(rq));
3981 
3982 		ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
3983 	}
3984 
3985 	/*
3986 	 * Must be after enqueueing at least once task such that
3987 	 * idle_cpu() does not observe a false-negative -- if it does,
3988 	 * it is possible for select_idle_siblings() to stack a number
3989 	 * of tasks on this CPU during that window.
3990 	 *
3991 	 * It is ok to clear ttwu_pending when another task pending.
3992 	 * We will receive IPI after local irq enabled and then enqueue it.
3993 	 * Since now nr_running > 0, idle_cpu() will always get correct result.
3994 	 */
3995 	WRITE_ONCE(rq->ttwu_pending, 0);
3996 	rq_unlock_irqrestore(rq, &rf);
3997 }
3998 
3999 /*
4000  * Prepare the scene for sending an IPI for a remote smp_call
4001  *
4002  * Returns true if the caller can proceed with sending the IPI.
4003  * Returns false otherwise.
4004  */
call_function_single_prep_ipi(int cpu)4005 bool call_function_single_prep_ipi(int cpu)
4006 {
4007 	if (set_nr_if_polling(cpu_rq(cpu)->idle)) {
4008 		trace_sched_wake_idle_without_ipi(cpu);
4009 		return false;
4010 	}
4011 
4012 	return true;
4013 }
4014 
4015 /*
4016  * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
4017  * necessary. The wakee CPU on receipt of the IPI will queue the task
4018  * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
4019  * of the wakeup instead of the waker.
4020  */
__ttwu_queue_wakelist(struct task_struct * p,int cpu,int wake_flags)4021 static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
4022 {
4023 	struct rq *rq = cpu_rq(cpu);
4024 
4025 	p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
4026 
4027 	WRITE_ONCE(rq->ttwu_pending, 1);
4028 	__smp_call_single_queue(cpu, &p->wake_entry.llist);
4029 }
4030 
wake_up_if_idle(int cpu)4031 void wake_up_if_idle(int cpu)
4032 {
4033 	struct rq *rq = cpu_rq(cpu);
4034 
4035 	guard(rcu)();
4036 	if (is_idle_task(rcu_dereference(rq->curr))) {
4037 		guard(rq_lock_irqsave)(rq);
4038 		if (is_idle_task(rq->curr))
4039 			resched_curr(rq);
4040 	}
4041 }
4042 EXPORT_SYMBOL_GPL(wake_up_if_idle);
4043 
cpus_equal_capacity(int this_cpu,int that_cpu)4044 bool cpus_equal_capacity(int this_cpu, int that_cpu)
4045 {
4046 	if (!sched_asym_cpucap_active())
4047 		return true;
4048 
4049 	if (this_cpu == that_cpu)
4050 		return true;
4051 
4052 	return arch_scale_cpu_capacity(this_cpu) == arch_scale_cpu_capacity(that_cpu);
4053 }
4054 
cpus_share_cache(int this_cpu,int that_cpu)4055 bool cpus_share_cache(int this_cpu, int that_cpu)
4056 {
4057 	if (this_cpu == that_cpu)
4058 		return true;
4059 
4060 	return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
4061 }
4062 
ttwu_queue_cond(struct task_struct * p,int cpu)4063 static inline bool ttwu_queue_cond(struct task_struct *p, int cpu)
4064 {
4065 	/*
4066 	 * Do not complicate things with the async wake_list while the CPU is
4067 	 * in hotplug state.
4068 	 */
4069 	if (!cpu_active(cpu))
4070 		return false;
4071 
4072 	/* Ensure the task will still be allowed to run on the CPU. */
4073 	if (!cpumask_test_cpu(cpu, p->cpus_ptr))
4074 		return false;
4075 
4076 	/*
4077 	 * If the CPU does not share cache, then queue the task on the
4078 	 * remote rqs wakelist to avoid accessing remote data.
4079 	 */
4080 	if (!cpus_share_cache(smp_processor_id(), cpu))
4081 		return true;
4082 
4083 	if (cpu == smp_processor_id())
4084 		return false;
4085 
4086 	/*
4087 	 * If the wakee cpu is idle, or the task is descheduling and the
4088 	 * only running task on the CPU, then use the wakelist to offload
4089 	 * the task activation to the idle (or soon-to-be-idle) CPU as
4090 	 * the current CPU is likely busy. nr_running is checked to
4091 	 * avoid unnecessary task stacking.
4092 	 *
4093 	 * Note that we can only get here with (wakee) p->on_rq=0,
4094 	 * p->on_cpu can be whatever, we've done the dequeue, so
4095 	 * the wakee has been accounted out of ->nr_running.
4096 	 */
4097 	if (!cpu_rq(cpu)->nr_running)
4098 		return true;
4099 
4100 	return false;
4101 }
4102 
ttwu_queue_wakelist(struct task_struct * p,int cpu,int wake_flags)4103 static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
4104 {
4105 	bool cond = false;
4106 
4107 	trace_android_rvh_ttwu_cond(cpu, &cond);
4108 
4109 	if ((sched_feat(TTWU_QUEUE) && ttwu_queue_cond(p, cpu)) ||
4110 			cond) {
4111 		sched_clock_cpu(cpu); /* Sync clocks across CPUs */
4112 		__ttwu_queue_wakelist(p, cpu, wake_flags);
4113 		return true;
4114 	}
4115 
4116 	return false;
4117 }
4118 
4119 #else /* !CONFIG_SMP */
4120 
ttwu_queue_wakelist(struct task_struct * p,int cpu,int wake_flags)4121 static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
4122 {
4123 	return false;
4124 }
4125 
4126 #endif /* CONFIG_SMP */
4127 
ttwu_queue(struct task_struct * p,int cpu,int wake_flags)4128 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
4129 {
4130 	struct rq *rq = cpu_rq(cpu);
4131 	struct rq_flags rf;
4132 
4133 	if (ttwu_queue_wakelist(p, cpu, wake_flags))
4134 		return;
4135 
4136 	rq_lock(rq, &rf);
4137 	update_rq_clock(rq);
4138 	ttwu_do_activate(rq, p, wake_flags, &rf);
4139 	rq_unlock(rq, &rf);
4140 }
4141 
4142 /*
4143  * Invoked from try_to_wake_up() to check whether the task can be woken up.
4144  *
4145  * The caller holds p::pi_lock if p != current or has preemption
4146  * disabled when p == current.
4147  *
4148  * The rules of saved_state:
4149  *
4150  *   The related locking code always holds p::pi_lock when updating
4151  *   p::saved_state, which means the code is fully serialized in both cases.
4152  *
4153  *   For PREEMPT_RT, the lock wait and lock wakeups happen via TASK_RTLOCK_WAIT.
4154  *   No other bits set. This allows to distinguish all wakeup scenarios.
4155  *
4156  *   For FREEZER, the wakeup happens via TASK_FROZEN. No other bits set. This
4157  *   allows us to prevent early wakeup of tasks before they can be run on
4158  *   asymmetric ISA architectures (eg ARMv9).
4159  */
4160 static __always_inline
ttwu_state_match(struct task_struct * p,unsigned int state,int * success)4161 bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success)
4162 {
4163 	int match;
4164 
4165 	if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) {
4166 		WARN_ON_ONCE((state & TASK_RTLOCK_WAIT) &&
4167 			     state != TASK_RTLOCK_WAIT);
4168 	}
4169 
4170 	*success = !!(match = __task_state_match(p, state));
4171 
4172 	/*
4173 	 * Saved state preserves the task state across blocking on
4174 	 * an RT lock or TASK_FREEZABLE tasks.  If the state matches,
4175 	 * set p::saved_state to TASK_RUNNING, but do not wake the task
4176 	 * because it waits for a lock wakeup or __thaw_task(). Also
4177 	 * indicate success because from the regular waker's point of
4178 	 * view this has succeeded.
4179 	 *
4180 	 * After acquiring the lock the task will restore p::__state
4181 	 * from p::saved_state which ensures that the regular
4182 	 * wakeup is not lost. The restore will also set
4183 	 * p::saved_state to TASK_RUNNING so any further tests will
4184 	 * not result in false positives vs. @success
4185 	 */
4186 	if (match < 0)
4187 		p->saved_state = TASK_RUNNING;
4188 
4189 	return match > 0;
4190 }
4191 
4192 /*
4193  * Notes on Program-Order guarantees on SMP systems.
4194  *
4195  *  MIGRATION
4196  *
4197  * The basic program-order guarantee on SMP systems is that when a task [t]
4198  * migrates, all its activity on its old CPU [c0] happens-before any subsequent
4199  * execution on its new CPU [c1].
4200  *
4201  * For migration (of runnable tasks) this is provided by the following means:
4202  *
4203  *  A) UNLOCK of the rq(c0)->lock scheduling out task t
4204  *  B) migration for t is required to synchronize *both* rq(c0)->lock and
4205  *     rq(c1)->lock (if not at the same time, then in that order).
4206  *  C) LOCK of the rq(c1)->lock scheduling in task
4207  *
4208  * Release/acquire chaining guarantees that B happens after A and C after B.
4209  * Note: the CPU doing B need not be c0 or c1
4210  *
4211  * Example:
4212  *
4213  *   CPU0            CPU1            CPU2
4214  *
4215  *   LOCK rq(0)->lock
4216  *   sched-out X
4217  *   sched-in Y
4218  *   UNLOCK rq(0)->lock
4219  *
4220  *                                   LOCK rq(0)->lock // orders against CPU0
4221  *                                   dequeue X
4222  *                                   UNLOCK rq(0)->lock
4223  *
4224  *                                   LOCK rq(1)->lock
4225  *                                   enqueue X
4226  *                                   UNLOCK rq(1)->lock
4227  *
4228  *                   LOCK rq(1)->lock // orders against CPU2
4229  *                   sched-out Z
4230  *                   sched-in X
4231  *                   UNLOCK rq(1)->lock
4232  *
4233  *
4234  *  BLOCKING -- aka. SLEEP + WAKEUP
4235  *
4236  * For blocking we (obviously) need to provide the same guarantee as for
4237  * migration. However the means are completely different as there is no lock
4238  * chain to provide order. Instead we do:
4239  *
4240  *   1) smp_store_release(X->on_cpu, 0)   -- finish_task()
4241  *   2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
4242  *
4243  * Example:
4244  *
4245  *   CPU0 (schedule)  CPU1 (try_to_wake_up) CPU2 (schedule)
4246  *
4247  *   LOCK rq(0)->lock LOCK X->pi_lock
4248  *   dequeue X
4249  *   sched-out X
4250  *   smp_store_release(X->on_cpu, 0);
4251  *
4252  *                    smp_cond_load_acquire(&X->on_cpu, !VAL);
4253  *                    X->state = WAKING
4254  *                    set_task_cpu(X,2)
4255  *
4256  *                    LOCK rq(2)->lock
4257  *                    enqueue X
4258  *                    X->state = RUNNING
4259  *                    UNLOCK rq(2)->lock
4260  *
4261  *                                          LOCK rq(2)->lock // orders against CPU1
4262  *                                          sched-out Z
4263  *                                          sched-in X
4264  *                                          UNLOCK rq(2)->lock
4265  *
4266  *                    UNLOCK X->pi_lock
4267  *   UNLOCK rq(0)->lock
4268  *
4269  *
4270  * However, for wakeups there is a second guarantee we must provide, namely we
4271  * must ensure that CONDITION=1 done by the caller can not be reordered with
4272  * accesses to the task state; see try_to_wake_up() and set_current_state().
4273  */
4274 
4275 /**
4276  * try_to_wake_up - wake up a thread
4277  * @p: the thread to be awakened
4278  * @state: the mask of task states that can be woken
4279  * @wake_flags: wake modifier flags (WF_*)
4280  *
4281  * Conceptually does:
4282  *
4283  *   If (@state & @p->state) @p->state = TASK_RUNNING.
4284  *
4285  * If the task was not queued/runnable, also place it back on a runqueue.
4286  *
4287  * This function is atomic against schedule() which would dequeue the task.
4288  *
4289  * It issues a full memory barrier before accessing @p->state, see the comment
4290  * with set_current_state().
4291  *
4292  * Uses p->pi_lock to serialize against concurrent wake-ups.
4293  *
4294  * Relies on p->pi_lock stabilizing:
4295  *  - p->sched_class
4296  *  - p->cpus_ptr
4297  *  - p->sched_task_group
4298  * in order to do migration, see its use of select_task_rq()/set_task_cpu().
4299  *
4300  * Tries really hard to only take one task_rq(p)->lock for performance.
4301  * Takes rq->lock in:
4302  *  - ttwu_runnable()    -- old rq, unavoidable, see comment there;
4303  *  - ttwu_queue()       -- new rq, for enqueue of the task;
4304  *  - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
4305  *
4306  * As a consequence we race really badly with just about everything. See the
4307  * many memory barriers and their comments for details.
4308  *
4309  * Return: %true if @p->state changes (an actual wakeup was done),
4310  *	   %false otherwise.
4311  */
try_to_wake_up(struct task_struct * p,unsigned int state,int wake_flags)4312 int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
4313 {
4314 	guard(preempt)();
4315 	int cpu, success = 0;
4316 
4317 	if (p == current) {
4318 		/*
4319 		 * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
4320 		 * == smp_processor_id()'. Together this means we can special
4321 		 * case the whole 'p->on_rq && ttwu_runnable()' case below
4322 		 * without taking any locks.
4323 		 *
4324 		 * In particular:
4325 		 *  - we rely on Program-Order guarantees for all the ordering,
4326 		 *  - we're serialized against set_special_state() by virtue of
4327 		 *    it disabling IRQs (this allows not taking ->pi_lock).
4328 		 */
4329 		if (!ttwu_state_match(p, state, &success))
4330 			goto out;
4331 
4332 		trace_sched_waking(p);
4333 		ttwu_do_wakeup(p);
4334 		goto out;
4335 	}
4336 
4337 	/*
4338 	 * If we are going to wake up a thread waiting for CONDITION we
4339 	 * need to ensure that CONDITION=1 done by the caller can not be
4340 	 * reordered with p->state check below. This pairs with smp_store_mb()
4341 	 * in set_current_state() that the waiting thread does.
4342 	 */
4343 	scoped_guard (raw_spinlock_irqsave, &p->pi_lock) {
4344 		smp_mb__after_spinlock();
4345 		if (!ttwu_state_match(p, state, &success))
4346 			break;
4347 
4348 		trace_sched_waking(p);
4349 
4350 		/*
4351 		 * Ensure we load p->on_rq _after_ p->state, otherwise it would
4352 		 * be possible to, falsely, observe p->on_rq == 0 and get stuck
4353 		 * in smp_cond_load_acquire() below.
4354 		 *
4355 		 * sched_ttwu_pending()			try_to_wake_up()
4356 		 *   STORE p->on_rq = 1			  LOAD p->state
4357 		 *   UNLOCK rq->lock
4358 		 *
4359 		 * __schedule() (switch to task 'p')
4360 		 *   LOCK rq->lock			  smp_rmb();
4361 		 *   smp_mb__after_spinlock();
4362 		 *   UNLOCK rq->lock
4363 		 *
4364 		 * [task p]
4365 		 *   STORE p->state = UNINTERRUPTIBLE	  LOAD p->on_rq
4366 		 *
4367 		 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4368 		 * __schedule().  See the comment for smp_mb__after_spinlock().
4369 		 *
4370 		 * A similar smb_rmb() lives in try_invoke_on_locked_down_task().
4371 		 */
4372 		smp_rmb();
4373 		if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags))
4374 			break;
4375 
4376 	if (READ_ONCE(p->__state) & TASK_UNINTERRUPTIBLE)
4377 		trace_sched_blocked_reason(p);
4378 
4379 #ifdef CONFIG_SMP
4380 		/*
4381 		 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
4382 		 * possible to, falsely, observe p->on_cpu == 0.
4383 		 *
4384 		 * One must be running (->on_cpu == 1) in order to remove oneself
4385 		 * from the runqueue.
4386 		 *
4387 		 * __schedule() (switch to task 'p')	try_to_wake_up()
4388 		 *   STORE p->on_cpu = 1		  LOAD p->on_rq
4389 		 *   UNLOCK rq->lock
4390 		 *
4391 		 * __schedule() (put 'p' to sleep)
4392 		 *   LOCK rq->lock			  smp_rmb();
4393 		 *   smp_mb__after_spinlock();
4394 		 *   STORE p->on_rq = 0			  LOAD p->on_cpu
4395 		 *
4396 		 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4397 		 * __schedule().  See the comment for smp_mb__after_spinlock().
4398 		 *
4399 		 * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
4400 		 * schedule()'s deactivate_task() has 'happened' and p will no longer
4401 		 * care about it's own p->state. See the comment in __schedule().
4402 		 */
4403 		smp_acquire__after_ctrl_dep();
4404 
4405 		/*
4406 		 * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
4407 		 * == 0), which means we need to do an enqueue, change p->state to
4408 		 * TASK_WAKING such that we can unlock p->pi_lock before doing the
4409 		 * enqueue, such as ttwu_queue_wakelist().
4410 		 */
4411 		WRITE_ONCE(p->__state, TASK_WAKING);
4412 
4413 		/*
4414 		 * If the owning (remote) CPU is still in the middle of schedule() with
4415 		 * this task as prev, considering queueing p on the remote CPUs wake_list
4416 		 * which potentially sends an IPI instead of spinning on p->on_cpu to
4417 		 * let the waker make forward progress. This is safe because IRQs are
4418 		 * disabled and the IPI will deliver after on_cpu is cleared.
4419 		 *
4420 		 * Ensure we load task_cpu(p) after p->on_cpu:
4421 		 *
4422 		 * set_task_cpu(p, cpu);
4423 		 *   STORE p->cpu = @cpu
4424 		 * __schedule() (switch to task 'p')
4425 		 *   LOCK rq->lock
4426 		 *   smp_mb__after_spin_lock()		smp_cond_load_acquire(&p->on_cpu)
4427 		 *   STORE p->on_cpu = 1		LOAD p->cpu
4428 		 *
4429 		 * to ensure we observe the correct CPU on which the task is currently
4430 		 * scheduling.
4431 		 */
4432 		if (smp_load_acquire(&p->on_cpu) &&
4433 		    ttwu_queue_wakelist(p, task_cpu(p), wake_flags))
4434 			break;
4435 
4436 		/*
4437 		 * If the owning (remote) CPU is still in the middle of schedule() with
4438 		 * this task as prev, wait until it's done referencing the task.
4439 		 *
4440 		 * Pairs with the smp_store_release() in finish_task().
4441 		 *
4442 		 * This ensures that tasks getting woken will be fully ordered against
4443 		 * their previous state and preserve Program Order.
4444 		 */
4445 		smp_cond_load_acquire(&p->on_cpu, !VAL);
4446 
4447 		trace_android_rvh_try_to_wake_up(p);
4448 
4449 		cpu = select_task_rq(p, p->wake_cpu, wake_flags | WF_TTWU);
4450 		if (task_cpu(p) != cpu) {
4451 			if (p->in_iowait) {
4452 				delayacct_blkio_end(p);
4453 				atomic_dec(&task_rq(p)->nr_iowait);
4454 			}
4455 
4456 			wake_flags |= WF_MIGRATED;
4457 			psi_ttwu_dequeue(p);
4458 			set_task_cpu(p, cpu);
4459 		}
4460 #else
4461 		cpu = task_cpu(p);
4462 #endif /* CONFIG_SMP */
4463 
4464 		ttwu_queue(p, cpu, wake_flags);
4465 	}
4466 out:
4467 	if (success) {
4468 		trace_android_rvh_try_to_wake_up_success(p);
4469 		ttwu_stat(p, task_cpu(p), wake_flags);
4470 	}
4471 	return success;
4472 }
4473 
__task_needs_rq_lock(struct task_struct * p)4474 static bool __task_needs_rq_lock(struct task_struct *p)
4475 {
4476 	unsigned int state = READ_ONCE(p->__state);
4477 
4478 	/*
4479 	 * Since pi->lock blocks try_to_wake_up(), we don't need rq->lock when
4480 	 * the task is blocked. Make sure to check @state since ttwu() can drop
4481 	 * locks at the end, see ttwu_queue_wakelist().
4482 	 */
4483 	if (state == TASK_RUNNING || state == TASK_WAKING)
4484 		return true;
4485 
4486 	/*
4487 	 * Ensure we load p->on_rq after p->__state, otherwise it would be
4488 	 * possible to, falsely, observe p->on_rq == 0.
4489 	 *
4490 	 * See try_to_wake_up() for a longer comment.
4491 	 */
4492 	smp_rmb();
4493 	if (p->on_rq)
4494 		return true;
4495 
4496 #ifdef CONFIG_SMP
4497 	/*
4498 	 * Ensure the task has finished __schedule() and will not be referenced
4499 	 * anymore. Again, see try_to_wake_up() for a longer comment.
4500 	 */
4501 	smp_rmb();
4502 	smp_cond_load_acquire(&p->on_cpu, !VAL);
4503 #endif
4504 
4505 	return false;
4506 }
4507 
4508 /**
4509  * task_call_func - Invoke a function on task in fixed state
4510  * @p: Process for which the function is to be invoked, can be @current.
4511  * @func: Function to invoke.
4512  * @arg: Argument to function.
4513  *
4514  * Fix the task in it's current state by avoiding wakeups and or rq operations
4515  * and call @func(@arg) on it.  This function can use ->on_rq and task_curr()
4516  * to work out what the state is, if required.  Given that @func can be invoked
4517  * with a runqueue lock held, it had better be quite lightweight.
4518  *
4519  * Returns:
4520  *   Whatever @func returns
4521  */
task_call_func(struct task_struct * p,task_call_f func,void * arg)4522 int task_call_func(struct task_struct *p, task_call_f func, void *arg)
4523 {
4524 	struct rq *rq = NULL;
4525 	struct rq_flags rf;
4526 	int ret;
4527 
4528 	raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
4529 
4530 	if (__task_needs_rq_lock(p))
4531 		rq = __task_rq_lock(p, &rf);
4532 
4533 	/*
4534 	 * At this point the task is pinned; either:
4535 	 *  - blocked and we're holding off wakeups	 (pi->lock)
4536 	 *  - woken, and we're holding off enqueue	 (rq->lock)
4537 	 *  - queued, and we're holding off schedule	 (rq->lock)
4538 	 *  - running, and we're holding off de-schedule (rq->lock)
4539 	 *
4540 	 * The called function (@func) can use: task_curr(), p->on_rq and
4541 	 * p->__state to differentiate between these states.
4542 	 */
4543 	ret = func(p, arg);
4544 
4545 	if (rq)
4546 		rq_unlock(rq, &rf);
4547 
4548 	raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
4549 	return ret;
4550 }
4551 
4552 /**
4553  * cpu_curr_snapshot - Return a snapshot of the currently running task
4554  * @cpu: The CPU on which to snapshot the task.
4555  *
4556  * Returns the task_struct pointer of the task "currently" running on
4557  * the specified CPU.
4558  *
4559  * If the specified CPU was offline, the return value is whatever it
4560  * is, perhaps a pointer to the task_struct structure of that CPU's idle
4561  * task, but there is no guarantee.  Callers wishing a useful return
4562  * value must take some action to ensure that the specified CPU remains
4563  * online throughout.
4564  *
4565  * This function executes full memory barriers before and after fetching
4566  * the pointer, which permits the caller to confine this function's fetch
4567  * with respect to the caller's accesses to other shared variables.
4568  */
cpu_curr_snapshot(int cpu)4569 struct task_struct *cpu_curr_snapshot(int cpu)
4570 {
4571 	struct rq *rq = cpu_rq(cpu);
4572 	struct task_struct *t;
4573 	struct rq_flags rf;
4574 
4575 	rq_lock_irqsave(rq, &rf);
4576 	smp_mb__after_spinlock(); /* Pairing determined by caller's synchronization design. */
4577 	t = rcu_dereference(cpu_curr(cpu));
4578 	rq_unlock_irqrestore(rq, &rf);
4579 	smp_mb(); /* Pairing determined by caller's synchronization design. */
4580 
4581 	return t;
4582 }
4583 
4584 /**
4585  * wake_up_process - Wake up a specific process
4586  * @p: The process to be woken up.
4587  *
4588  * Attempt to wake up the nominated process and move it to the set of runnable
4589  * processes.
4590  *
4591  * Return: 1 if the process was woken up, 0 if it was already running.
4592  *
4593  * This function executes a full memory barrier before accessing the task state.
4594  */
wake_up_process(struct task_struct * p)4595 int wake_up_process(struct task_struct *p)
4596 {
4597 	return try_to_wake_up(p, TASK_NORMAL, 0);
4598 }
4599 EXPORT_SYMBOL(wake_up_process);
4600 
wake_up_state(struct task_struct * p,unsigned int state)4601 int wake_up_state(struct task_struct *p, unsigned int state)
4602 {
4603 	return try_to_wake_up(p, state, 0);
4604 }
4605 EXPORT_SYMBOL(wake_up_state);
4606 
4607 /*
4608  * Perform scheduler related setup for a newly forked process p.
4609  * p is forked by current.
4610  *
4611  * __sched_fork() is basic setup used by init_idle() too:
4612  */
__sched_fork(unsigned long clone_flags,struct task_struct * p)4613 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
4614 {
4615 	p->on_rq			= 0;
4616 
4617 	p->se.on_rq			= 0;
4618 	p->se.exec_start		= 0;
4619 	p->se.sum_exec_runtime		= 0;
4620 	p->se.prev_sum_exec_runtime	= 0;
4621 	p->se.nr_migrations		= 0;
4622 	p->se.vruntime			= 0;
4623 	p->se.vlag			= 0;
4624 	p->se.slice			= sysctl_sched_base_slice;
4625 	INIT_LIST_HEAD(&p->se.group_node);
4626 
4627 #ifdef CONFIG_FAIR_GROUP_SCHED
4628 	p->se.cfs_rq			= NULL;
4629 #endif
4630 
4631 	trace_android_rvh_sched_fork_init(p);
4632 
4633 #ifdef CONFIG_SCHEDSTATS
4634 	/* Even if schedstat is disabled, there should not be garbage */
4635 	memset(&p->stats, 0, sizeof(p->stats));
4636 #endif
4637 
4638 	RB_CLEAR_NODE(&p->dl.rb_node);
4639 	init_dl_task_timer(&p->dl);
4640 	init_dl_inactive_task_timer(&p->dl);
4641 	__dl_clear_params(p);
4642 
4643 	INIT_LIST_HEAD(&p->rt.run_list);
4644 	p->rt.timeout		= 0;
4645 	p->rt.time_slice	= sched_rr_timeslice;
4646 	p->rt.on_rq		= 0;
4647 	p->rt.on_list		= 0;
4648 
4649 #ifdef CONFIG_PREEMPT_NOTIFIERS
4650 	INIT_HLIST_HEAD(&p->preempt_notifiers);
4651 #endif
4652 
4653 #ifdef CONFIG_COMPACTION
4654 	p->capture_control = NULL;
4655 #endif
4656 	init_numa_balancing(clone_flags, p);
4657 #ifdef CONFIG_SMP
4658 	p->wake_entry.u_flags = CSD_TYPE_TTWU;
4659 	p->migration_pending = NULL;
4660 #endif
4661 	init_sched_mm_cid(p);
4662 }
4663 
4664 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
4665 
4666 #ifdef CONFIG_NUMA_BALANCING
4667 
4668 int sysctl_numa_balancing_mode;
4669 
__set_numabalancing_state(bool enabled)4670 static void __set_numabalancing_state(bool enabled)
4671 {
4672 	if (enabled)
4673 		static_branch_enable(&sched_numa_balancing);
4674 	else
4675 		static_branch_disable(&sched_numa_balancing);
4676 }
4677 
set_numabalancing_state(bool enabled)4678 void set_numabalancing_state(bool enabled)
4679 {
4680 	if (enabled)
4681 		sysctl_numa_balancing_mode = NUMA_BALANCING_NORMAL;
4682 	else
4683 		sysctl_numa_balancing_mode = NUMA_BALANCING_DISABLED;
4684 	__set_numabalancing_state(enabled);
4685 }
4686 
4687 #ifdef CONFIG_PROC_SYSCTL
reset_memory_tiering(void)4688 static void reset_memory_tiering(void)
4689 {
4690 	struct pglist_data *pgdat;
4691 
4692 	for_each_online_pgdat(pgdat) {
4693 		pgdat->nbp_threshold = 0;
4694 		pgdat->nbp_th_nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
4695 		pgdat->nbp_th_start = jiffies_to_msecs(jiffies);
4696 	}
4697 }
4698 
sysctl_numa_balancing(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)4699 static int sysctl_numa_balancing(struct ctl_table *table, int write,
4700 			  void *buffer, size_t *lenp, loff_t *ppos)
4701 {
4702 	struct ctl_table t;
4703 	int err;
4704 	int state = sysctl_numa_balancing_mode;
4705 
4706 	if (write && !capable(CAP_SYS_ADMIN))
4707 		return -EPERM;
4708 
4709 	t = *table;
4710 	t.data = &state;
4711 	err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
4712 	if (err < 0)
4713 		return err;
4714 	if (write) {
4715 		if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
4716 		    (state & NUMA_BALANCING_MEMORY_TIERING))
4717 			reset_memory_tiering();
4718 		sysctl_numa_balancing_mode = state;
4719 		__set_numabalancing_state(state);
4720 	}
4721 	return err;
4722 }
4723 #endif
4724 #endif
4725 
4726 #ifdef CONFIG_SCHEDSTATS
4727 
4728 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
4729 
set_schedstats(bool enabled)4730 static void set_schedstats(bool enabled)
4731 {
4732 	if (enabled)
4733 		static_branch_enable(&sched_schedstats);
4734 	else
4735 		static_branch_disable(&sched_schedstats);
4736 }
4737 
force_schedstat_enabled(void)4738 void force_schedstat_enabled(void)
4739 {
4740 	if (!schedstat_enabled()) {
4741 		pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
4742 		static_branch_enable(&sched_schedstats);
4743 	}
4744 }
4745 
setup_schedstats(char * str)4746 static int __init setup_schedstats(char *str)
4747 {
4748 	int ret = 0;
4749 	if (!str)
4750 		goto out;
4751 
4752 	if (!strcmp(str, "enable")) {
4753 		set_schedstats(true);
4754 		ret = 1;
4755 	} else if (!strcmp(str, "disable")) {
4756 		set_schedstats(false);
4757 		ret = 1;
4758 	}
4759 out:
4760 	if (!ret)
4761 		pr_warn("Unable to parse schedstats=\n");
4762 
4763 	return ret;
4764 }
4765 __setup("schedstats=", setup_schedstats);
4766 
4767 #ifdef CONFIG_PROC_SYSCTL
sysctl_schedstats(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)4768 static int sysctl_schedstats(struct ctl_table *table, int write, void *buffer,
4769 		size_t *lenp, loff_t *ppos)
4770 {
4771 	struct ctl_table t;
4772 	int err;
4773 	int state = static_branch_likely(&sched_schedstats);
4774 
4775 	if (write && !capable(CAP_SYS_ADMIN))
4776 		return -EPERM;
4777 
4778 	t = *table;
4779 	t.data = &state;
4780 	err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
4781 	if (err < 0)
4782 		return err;
4783 	if (write)
4784 		set_schedstats(state);
4785 	return err;
4786 }
4787 #endif /* CONFIG_PROC_SYSCTL */
4788 #endif /* CONFIG_SCHEDSTATS */
4789 
4790 #ifdef CONFIG_SYSCTL
4791 static struct ctl_table sched_core_sysctls[] = {
4792 #ifdef CONFIG_SCHEDSTATS
4793 	{
4794 		.procname       = "sched_schedstats",
4795 		.data           = NULL,
4796 		.maxlen         = sizeof(unsigned int),
4797 		.mode           = 0644,
4798 		.proc_handler   = sysctl_schedstats,
4799 		.extra1         = SYSCTL_ZERO,
4800 		.extra2         = SYSCTL_ONE,
4801 	},
4802 #endif /* CONFIG_SCHEDSTATS */
4803 #ifdef CONFIG_UCLAMP_TASK
4804 	{
4805 		.procname       = "sched_util_clamp_min",
4806 		.data           = &sysctl_sched_uclamp_util_min,
4807 		.maxlen         = sizeof(unsigned int),
4808 		.mode           = 0644,
4809 		.proc_handler   = sysctl_sched_uclamp_handler,
4810 	},
4811 	{
4812 		.procname       = "sched_util_clamp_max",
4813 		.data           = &sysctl_sched_uclamp_util_max,
4814 		.maxlen         = sizeof(unsigned int),
4815 		.mode           = 0644,
4816 		.proc_handler   = sysctl_sched_uclamp_handler,
4817 	},
4818 	{
4819 		.procname       = "sched_util_clamp_min_rt_default",
4820 		.data           = &sysctl_sched_uclamp_util_min_rt_default,
4821 		.maxlen         = sizeof(unsigned int),
4822 		.mode           = 0644,
4823 		.proc_handler   = sysctl_sched_uclamp_handler,
4824 	},
4825 #endif /* CONFIG_UCLAMP_TASK */
4826 #ifdef CONFIG_NUMA_BALANCING
4827 	{
4828 		.procname	= "numa_balancing",
4829 		.data		= NULL, /* filled in by handler */
4830 		.maxlen		= sizeof(unsigned int),
4831 		.mode		= 0644,
4832 		.proc_handler	= sysctl_numa_balancing,
4833 		.extra1		= SYSCTL_ZERO,
4834 		.extra2		= SYSCTL_FOUR,
4835 	},
4836 #endif /* CONFIG_NUMA_BALANCING */
4837 	{}
4838 };
sched_core_sysctl_init(void)4839 static int __init sched_core_sysctl_init(void)
4840 {
4841 	register_sysctl_init("kernel", sched_core_sysctls);
4842 	return 0;
4843 }
4844 late_initcall(sched_core_sysctl_init);
4845 #endif /* CONFIG_SYSCTL */
4846 
4847 /*
4848  * fork()/clone()-time setup:
4849  */
sched_fork(unsigned long clone_flags,struct task_struct * p)4850 int sched_fork(unsigned long clone_flags, struct task_struct *p)
4851 {
4852 	trace_android_rvh_sched_fork(p);
4853 
4854 	__sched_fork(clone_flags, p);
4855 	/*
4856 	 * We mark the process as NEW here. This guarantees that
4857 	 * nobody will actually run it, and a signal or other external
4858 	 * event cannot wake it up and insert it on the runqueue either.
4859 	 */
4860 	p->__state = TASK_NEW;
4861 
4862 	/*
4863 	 * Make sure we do not leak PI boosting priority to the child.
4864 	 */
4865 	p->prio = current->normal_prio;
4866 	trace_android_rvh_prepare_prio_fork(p);
4867 
4868 	uclamp_fork(p);
4869 
4870 	/*
4871 	 * Revert to default priority/policy on fork if requested.
4872 	 */
4873 	if (unlikely(p->sched_reset_on_fork)) {
4874 		if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
4875 			p->policy = SCHED_NORMAL;
4876 			p->static_prio = NICE_TO_PRIO(0);
4877 			p->rt_priority = 0;
4878 		} else if (PRIO_TO_NICE(p->static_prio) < 0)
4879 			p->static_prio = NICE_TO_PRIO(0);
4880 
4881 		p->prio = p->normal_prio = p->static_prio;
4882 		set_load_weight(p, false);
4883 
4884 		/*
4885 		 * We don't need the reset flag anymore after the fork. It has
4886 		 * fulfilled its duty:
4887 		 */
4888 		p->sched_reset_on_fork = 0;
4889 	}
4890 
4891 	if (dl_prio(p->prio))
4892 		return -EAGAIN;
4893 	else if (rt_prio(p->prio))
4894 		p->sched_class = &rt_sched_class;
4895 	else
4896 		p->sched_class = &fair_sched_class;
4897 
4898 	init_entity_runnable_average(&p->se);
4899 	trace_android_rvh_finish_prio_fork(p);
4900 
4901 
4902 #ifdef CONFIG_SCHED_INFO
4903 	if (likely(sched_info_on()))
4904 		memset(&p->sched_info, 0, sizeof(p->sched_info));
4905 #endif
4906 #if defined(CONFIG_SMP)
4907 	p->on_cpu = 0;
4908 #endif
4909 	init_task_preempt_count(p);
4910 #ifdef CONFIG_SMP
4911 	plist_node_init(&p->pushable_tasks, MAX_PRIO);
4912 	RB_CLEAR_NODE(&p->pushable_dl_tasks);
4913 #endif
4914 	return 0;
4915 }
4916 
sched_cgroup_fork(struct task_struct * p,struct kernel_clone_args * kargs)4917 void sched_cgroup_fork(struct task_struct *p, struct kernel_clone_args *kargs)
4918 {
4919 	unsigned long flags;
4920 
4921 	/*
4922 	 * Because we're not yet on the pid-hash, p->pi_lock isn't strictly
4923 	 * required yet, but lockdep gets upset if rules are violated.
4924 	 */
4925 	raw_spin_lock_irqsave(&p->pi_lock, flags);
4926 #ifdef CONFIG_CGROUP_SCHED
4927 	if (1) {
4928 		struct task_group *tg;
4929 		tg = container_of(kargs->cset->subsys[cpu_cgrp_id],
4930 				  struct task_group, css);
4931 		tg = autogroup_task_group(p, tg);
4932 		p->sched_task_group = tg;
4933 	}
4934 #endif
4935 	rseq_migrate(p);
4936 	/*
4937 	 * We're setting the CPU for the first time, we don't migrate,
4938 	 * so use __set_task_cpu().
4939 	 */
4940 	__set_task_cpu(p, smp_processor_id());
4941 	if (p->sched_class->task_fork)
4942 		p->sched_class->task_fork(p);
4943 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4944 }
4945 
sched_post_fork(struct task_struct * p)4946 void sched_post_fork(struct task_struct *p)
4947 {
4948 	uclamp_post_fork(p);
4949 }
4950 
to_ratio(u64 period,u64 runtime)4951 unsigned long to_ratio(u64 period, u64 runtime)
4952 {
4953 	if (runtime == RUNTIME_INF)
4954 		return BW_UNIT;
4955 
4956 	/*
4957 	 * Doing this here saves a lot of checks in all
4958 	 * the calling paths, and returning zero seems
4959 	 * safe for them anyway.
4960 	 */
4961 	if (period == 0)
4962 		return 0;
4963 
4964 	return div64_u64(runtime << BW_SHIFT, period);
4965 }
4966 
4967 /*
4968  * wake_up_new_task - wake up a newly created task for the first time.
4969  *
4970  * This function will do some initial scheduler statistics housekeeping
4971  * that must be done for every newly created context, then puts the task
4972  * on the runqueue and wakes it.
4973  */
wake_up_new_task(struct task_struct * p)4974 void wake_up_new_task(struct task_struct *p)
4975 {
4976 	struct rq_flags rf;
4977 	struct rq *rq;
4978 
4979 	trace_android_rvh_wake_up_new_task(p);
4980 
4981 	raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
4982 	WRITE_ONCE(p->__state, TASK_RUNNING);
4983 #ifdef CONFIG_SMP
4984 	/*
4985 	 * Fork balancing, do it here and not earlier because:
4986 	 *  - cpus_ptr can change in the fork path
4987 	 *  - any previously selected CPU might disappear through hotplug
4988 	 *
4989 	 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
4990 	 * as we're not fully set-up yet.
4991 	 */
4992 	p->recent_used_cpu = task_cpu(p);
4993 	rseq_migrate(p);
4994 	__set_task_cpu(p, select_task_rq(p, task_cpu(p), WF_FORK));
4995 #endif
4996 	rq = __task_rq_lock(p, &rf);
4997 	update_rq_clock(rq);
4998 	post_init_entity_util_avg(p);
4999 	trace_android_rvh_new_task_stats(p);
5000 
5001 	activate_task(rq, p, ENQUEUE_NOCLOCK);
5002 	trace_sched_wakeup_new(p);
5003 	check_preempt_curr(rq, p, WF_FORK);
5004 #ifdef CONFIG_SMP
5005 	if (p->sched_class->task_woken) {
5006 		/*
5007 		 * Nothing relies on rq->lock after this, so it's fine to
5008 		 * drop it.
5009 		 */
5010 		rq_unpin_lock(rq, &rf);
5011 		p->sched_class->task_woken(rq, p);
5012 		rq_repin_lock(rq, &rf);
5013 	}
5014 #endif
5015 	task_rq_unlock(rq, p, &rf);
5016 }
5017 
5018 #ifdef CONFIG_PREEMPT_NOTIFIERS
5019 
5020 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
5021 
preempt_notifier_inc(void)5022 void preempt_notifier_inc(void)
5023 {
5024 	static_branch_inc(&preempt_notifier_key);
5025 }
5026 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
5027 
preempt_notifier_dec(void)5028 void preempt_notifier_dec(void)
5029 {
5030 	static_branch_dec(&preempt_notifier_key);
5031 }
5032 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
5033 
5034 /**
5035  * preempt_notifier_register - tell me when current is being preempted & rescheduled
5036  * @notifier: notifier struct to register
5037  */
preempt_notifier_register(struct preempt_notifier * notifier)5038 void preempt_notifier_register(struct preempt_notifier *notifier)
5039 {
5040 	if (!static_branch_unlikely(&preempt_notifier_key))
5041 		WARN(1, "registering preempt_notifier while notifiers disabled\n");
5042 
5043 	hlist_add_head(&notifier->link, &current->preempt_notifiers);
5044 }
5045 EXPORT_SYMBOL_GPL(preempt_notifier_register);
5046 
5047 /**
5048  * preempt_notifier_unregister - no longer interested in preemption notifications
5049  * @notifier: notifier struct to unregister
5050  *
5051  * This is *not* safe to call from within a preemption notifier.
5052  */
preempt_notifier_unregister(struct preempt_notifier * notifier)5053 void preempt_notifier_unregister(struct preempt_notifier *notifier)
5054 {
5055 	hlist_del(&notifier->link);
5056 }
5057 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
5058 
__fire_sched_in_preempt_notifiers(struct task_struct * curr)5059 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
5060 {
5061 	struct preempt_notifier *notifier;
5062 
5063 	hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
5064 		notifier->ops->sched_in(notifier, raw_smp_processor_id());
5065 }
5066 
fire_sched_in_preempt_notifiers(struct task_struct * curr)5067 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
5068 {
5069 	if (static_branch_unlikely(&preempt_notifier_key))
5070 		__fire_sched_in_preempt_notifiers(curr);
5071 }
5072 
5073 static void
__fire_sched_out_preempt_notifiers(struct task_struct * curr,struct task_struct * next)5074 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
5075 				   struct task_struct *next)
5076 {
5077 	struct preempt_notifier *notifier;
5078 
5079 	hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
5080 		notifier->ops->sched_out(notifier, next);
5081 }
5082 
5083 static __always_inline void
fire_sched_out_preempt_notifiers(struct task_struct * curr,struct task_struct * next)5084 fire_sched_out_preempt_notifiers(struct task_struct *curr,
5085 				 struct task_struct *next)
5086 {
5087 	if (static_branch_unlikely(&preempt_notifier_key))
5088 		__fire_sched_out_preempt_notifiers(curr, next);
5089 }
5090 
5091 #else /* !CONFIG_PREEMPT_NOTIFIERS */
5092 
fire_sched_in_preempt_notifiers(struct task_struct * curr)5093 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
5094 {
5095 }
5096 
5097 static inline void
fire_sched_out_preempt_notifiers(struct task_struct * curr,struct task_struct * next)5098 fire_sched_out_preempt_notifiers(struct task_struct *curr,
5099 				 struct task_struct *next)
5100 {
5101 }
5102 
5103 #endif /* CONFIG_PREEMPT_NOTIFIERS */
5104 
prepare_task(struct task_struct * next)5105 static inline void prepare_task(struct task_struct *next)
5106 {
5107 #ifdef CONFIG_SMP
5108 	/*
5109 	 * Claim the task as running, we do this before switching to it
5110 	 * such that any running task will have this set.
5111 	 *
5112 	 * See the smp_load_acquire(&p->on_cpu) case in ttwu() and
5113 	 * its ordering comment.
5114 	 */
5115 	WRITE_ONCE(next->on_cpu, 1);
5116 #endif
5117 }
5118 
finish_task(struct task_struct * prev)5119 static inline void finish_task(struct task_struct *prev)
5120 {
5121 #ifdef CONFIG_SMP
5122 	/*
5123 	 * This must be the very last reference to @prev from this CPU. After
5124 	 * p->on_cpu is cleared, the task can be moved to a different CPU. We
5125 	 * must ensure this doesn't happen until the switch is completely
5126 	 * finished.
5127 	 *
5128 	 * In particular, the load of prev->state in finish_task_switch() must
5129 	 * happen before this.
5130 	 *
5131 	 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
5132 	 */
5133 	smp_store_release(&prev->on_cpu, 0);
5134 #endif
5135 }
5136 
5137 #ifdef CONFIG_SMP
5138 
do_balance_callbacks(struct rq * rq,struct balance_callback * head)5139 static void do_balance_callbacks(struct rq *rq, struct balance_callback *head)
5140 {
5141 	void (*func)(struct rq *rq);
5142 	struct balance_callback *next;
5143 
5144 	lockdep_assert_rq_held(rq);
5145 
5146 	while (head) {
5147 		func = (void (*)(struct rq *))head->func;
5148 		next = head->next;
5149 		head->next = NULL;
5150 		head = next;
5151 
5152 		func(rq);
5153 	}
5154 }
5155 
5156 static void balance_push(struct rq *rq);
5157 
5158 /*
5159  * balance_push_callback is a right abuse of the callback interface and plays
5160  * by significantly different rules.
5161  *
5162  * Where the normal balance_callback's purpose is to be ran in the same context
5163  * that queued it (only later, when it's safe to drop rq->lock again),
5164  * balance_push_callback is specifically targeted at __schedule().
5165  *
5166  * This abuse is tolerated because it places all the unlikely/odd cases behind
5167  * a single test, namely: rq->balance_callback == NULL.
5168  */
5169 struct balance_callback balance_push_callback = {
5170 	.next = NULL,
5171 	.func = balance_push,
5172 };
5173 EXPORT_SYMBOL_GPL(balance_push_callback);
5174 
5175 static inline struct balance_callback *
__splice_balance_callbacks(struct rq * rq,bool split)5176 __splice_balance_callbacks(struct rq *rq, bool split)
5177 {
5178 	struct balance_callback *head = rq->balance_callback;
5179 
5180 	if (likely(!head))
5181 		return NULL;
5182 
5183 	lockdep_assert_rq_held(rq);
5184 	/*
5185 	 * Must not take balance_push_callback off the list when
5186 	 * splice_balance_callbacks() and balance_callbacks() are not
5187 	 * in the same rq->lock section.
5188 	 *
5189 	 * In that case it would be possible for __schedule() to interleave
5190 	 * and observe the list empty.
5191 	 */
5192 	if (split && head == &balance_push_callback)
5193 		head = NULL;
5194 	else
5195 		rq->balance_callback = NULL;
5196 
5197 	return head;
5198 }
5199 
splice_balance_callbacks(struct rq * rq)5200 static inline struct balance_callback *splice_balance_callbacks(struct rq *rq)
5201 {
5202 	return __splice_balance_callbacks(rq, true);
5203 }
5204 
__balance_callbacks(struct rq * rq)5205 void __balance_callbacks(struct rq *rq)
5206 {
5207 	do_balance_callbacks(rq, __splice_balance_callbacks(rq, false));
5208 }
5209 EXPORT_SYMBOL_GPL(__balance_callbacks);
5210 
balance_callbacks(struct rq * rq,struct balance_callback * head)5211 static inline void balance_callbacks(struct rq *rq, struct balance_callback *head)
5212 {
5213 	unsigned long flags;
5214 
5215 	if (unlikely(head)) {
5216 		raw_spin_rq_lock_irqsave(rq, flags);
5217 		do_balance_callbacks(rq, head);
5218 		raw_spin_rq_unlock_irqrestore(rq, flags);
5219 	}
5220 }
5221 
5222 #else
5223 
__balance_callbacks(struct rq * rq)5224 static inline void __balance_callbacks(struct rq *rq)
5225 {
5226 }
5227 
splice_balance_callbacks(struct rq * rq)5228 static inline struct balance_callback *splice_balance_callbacks(struct rq *rq)
5229 {
5230 	return NULL;
5231 }
5232 
balance_callbacks(struct rq * rq,struct balance_callback * head)5233 static inline void balance_callbacks(struct rq *rq, struct balance_callback *head)
5234 {
5235 }
5236 
5237 #endif
5238 
5239 static inline void
prepare_lock_switch(struct rq * rq,struct task_struct * next,struct rq_flags * rf)5240 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
5241 {
5242 	/*
5243 	 * Since the runqueue lock will be released by the next
5244 	 * task (which is an invalid locking op but in the case
5245 	 * of the scheduler it's an obvious special-case), so we
5246 	 * do an early lockdep release here:
5247 	 */
5248 	rq_unpin_lock(rq, rf);
5249 	spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_);
5250 #ifdef CONFIG_DEBUG_SPINLOCK
5251 	/* this is a valid case when another task releases the spinlock */
5252 	rq_lockp(rq)->owner = next;
5253 #endif
5254 }
5255 
finish_lock_switch(struct rq * rq)5256 static inline void finish_lock_switch(struct rq *rq)
5257 {
5258 	/*
5259 	 * If we are tracking spinlock dependencies then we have to
5260 	 * fix up the runqueue lock - which gets 'carried over' from
5261 	 * prev into current:
5262 	 */
5263 	spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_);
5264 	__balance_callbacks(rq);
5265 	raw_spin_rq_unlock_irq(rq);
5266 }
5267 
5268 /*
5269  * NOP if the arch has not defined these:
5270  */
5271 
5272 #ifndef prepare_arch_switch
5273 # define prepare_arch_switch(next)	do { } while (0)
5274 #endif
5275 
5276 #ifndef finish_arch_post_lock_switch
5277 # define finish_arch_post_lock_switch()	do { } while (0)
5278 #endif
5279 
kmap_local_sched_out(void)5280 static inline void kmap_local_sched_out(void)
5281 {
5282 #ifdef CONFIG_KMAP_LOCAL
5283 	if (unlikely(current->kmap_ctrl.idx))
5284 		__kmap_local_sched_out();
5285 #endif
5286 }
5287 
kmap_local_sched_in(void)5288 static inline void kmap_local_sched_in(void)
5289 {
5290 #ifdef CONFIG_KMAP_LOCAL
5291 	if (unlikely(current->kmap_ctrl.idx))
5292 		__kmap_local_sched_in();
5293 #endif
5294 }
5295 
5296 /**
5297  * prepare_task_switch - prepare to switch tasks
5298  * @rq: the runqueue preparing to switch
5299  * @prev: the current task that is being switched out
5300  * @next: the task we are going to switch to.
5301  *
5302  * This is called with the rq lock held and interrupts off. It must
5303  * be paired with a subsequent finish_task_switch after the context
5304  * switch.
5305  *
5306  * prepare_task_switch sets up locking and calls architecture specific
5307  * hooks.
5308  */
5309 static inline void
prepare_task_switch(struct rq * rq,struct task_struct * prev,struct task_struct * next)5310 prepare_task_switch(struct rq *rq, struct task_struct *prev,
5311 		    struct task_struct *next)
5312 {
5313 	kcov_prepare_switch(prev);
5314 	sched_info_switch(rq, prev, next);
5315 	perf_event_task_sched_out(prev, next);
5316 	rseq_preempt(prev);
5317 	fire_sched_out_preempt_notifiers(prev, next);
5318 	kmap_local_sched_out();
5319 	prepare_task(next);
5320 	prepare_arch_switch(next);
5321 }
5322 
5323 /**
5324  * finish_task_switch - clean up after a task-switch
5325  * @prev: the thread we just switched away from.
5326  *
5327  * finish_task_switch must be called after the context switch, paired
5328  * with a prepare_task_switch call before the context switch.
5329  * finish_task_switch will reconcile locking set up by prepare_task_switch,
5330  * and do any other architecture-specific cleanup actions.
5331  *
5332  * Note that we may have delayed dropping an mm in context_switch(). If
5333  * so, we finish that here outside of the runqueue lock. (Doing it
5334  * with the lock held can cause deadlocks; see schedule() for
5335  * details.)
5336  *
5337  * The context switch have flipped the stack from under us and restored the
5338  * local variables which were saved when this task called schedule() in the
5339  * past. prev == current is still correct but we need to recalculate this_rq
5340  * because prev may have moved to another CPU.
5341  */
finish_task_switch(struct task_struct * prev)5342 static struct rq *finish_task_switch(struct task_struct *prev)
5343 	__releases(rq->lock)
5344 {
5345 	struct rq *rq = this_rq();
5346 	struct mm_struct *mm = rq->prev_mm;
5347 	unsigned int prev_state;
5348 
5349 	/*
5350 	 * The previous task will have left us with a preempt_count of 2
5351 	 * because it left us after:
5352 	 *
5353 	 *	schedule()
5354 	 *	  preempt_disable();			// 1
5355 	 *	  __schedule()
5356 	 *	    raw_spin_lock_irq(&rq->lock)	// 2
5357 	 *
5358 	 * Also, see FORK_PREEMPT_COUNT.
5359 	 */
5360 	if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
5361 		      "corrupted preempt_count: %s/%d/0x%x\n",
5362 		      current->comm, current->pid, preempt_count()))
5363 		preempt_count_set(FORK_PREEMPT_COUNT);
5364 
5365 	rq->prev_mm = NULL;
5366 
5367 	/*
5368 	 * A task struct has one reference for the use as "current".
5369 	 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
5370 	 * schedule one last time. The schedule call will never return, and
5371 	 * the scheduled task must drop that reference.
5372 	 *
5373 	 * We must observe prev->state before clearing prev->on_cpu (in
5374 	 * finish_task), otherwise a concurrent wakeup can get prev
5375 	 * running on another CPU and we could rave with its RUNNING -> DEAD
5376 	 * transition, resulting in a double drop.
5377 	 */
5378 	prev_state = READ_ONCE(prev->__state);
5379 	vtime_task_switch(prev);
5380 	perf_event_task_sched_in(prev, current);
5381 	finish_task(prev);
5382 	tick_nohz_task_switch();
5383 	finish_lock_switch(rq);
5384 	finish_arch_post_lock_switch();
5385 	kcov_finish_switch(current);
5386 	/*
5387 	 * kmap_local_sched_out() is invoked with rq::lock held and
5388 	 * interrupts disabled. There is no requirement for that, but the
5389 	 * sched out code does not have an interrupt enabled section.
5390 	 * Restoring the maps on sched in does not require interrupts being
5391 	 * disabled either.
5392 	 */
5393 	kmap_local_sched_in();
5394 
5395 	fire_sched_in_preempt_notifiers(current);
5396 	/*
5397 	 * When switching through a kernel thread, the loop in
5398 	 * membarrier_{private,global}_expedited() may have observed that
5399 	 * kernel thread and not issued an IPI. It is therefore possible to
5400 	 * schedule between user->kernel->user threads without passing though
5401 	 * switch_mm(). Membarrier requires a barrier after storing to
5402 	 * rq->curr, before returning to userspace, so provide them here:
5403 	 *
5404 	 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
5405 	 *   provided by mmdrop_lazy_tlb(),
5406 	 * - a sync_core for SYNC_CORE.
5407 	 */
5408 	if (mm) {
5409 		membarrier_mm_sync_core_before_usermode(mm);
5410 		mmdrop_lazy_tlb_sched(mm);
5411 	}
5412 
5413 	if (unlikely(prev_state == TASK_DEAD)) {
5414 		if (prev->sched_class->task_dead)
5415 			prev->sched_class->task_dead(prev);
5416 
5417 		trace_android_rvh_flush_task(prev);
5418 
5419 		/* Task is done with its stack. */
5420 		put_task_stack(prev);
5421 
5422 		put_task_struct_rcu_user(prev);
5423 	}
5424 
5425 	return rq;
5426 }
5427 
5428 /**
5429  * schedule_tail - first thing a freshly forked thread must call.
5430  * @prev: the thread we just switched away from.
5431  */
schedule_tail(struct task_struct * prev)5432 asmlinkage __visible void schedule_tail(struct task_struct *prev)
5433 	__releases(rq->lock)
5434 {
5435 	/*
5436 	 * New tasks start with FORK_PREEMPT_COUNT, see there and
5437 	 * finish_task_switch() for details.
5438 	 *
5439 	 * finish_task_switch() will drop rq->lock() and lower preempt_count
5440 	 * and the preempt_enable() will end up enabling preemption (on
5441 	 * PREEMPT_COUNT kernels).
5442 	 */
5443 
5444 	finish_task_switch(prev);
5445 	preempt_enable();
5446 
5447 	if (current->set_child_tid)
5448 		put_user(task_pid_vnr(current), current->set_child_tid);
5449 
5450 	calculate_sigpending();
5451 }
5452 
5453 /*
5454  * context_switch - switch to the new MM and the new thread's register state.
5455  */
5456 static __always_inline struct rq *
context_switch(struct rq * rq,struct task_struct * prev,struct task_struct * next,struct rq_flags * rf)5457 context_switch(struct rq *rq, struct task_struct *prev,
5458 	       struct task_struct *next, struct rq_flags *rf)
5459 {
5460 	prepare_task_switch(rq, prev, next);
5461 
5462 	/*
5463 	 * For paravirt, this is coupled with an exit in switch_to to
5464 	 * combine the page table reload and the switch backend into
5465 	 * one hypercall.
5466 	 */
5467 	arch_start_context_switch(prev);
5468 
5469 	/*
5470 	 * kernel -> kernel   lazy + transfer active
5471 	 *   user -> kernel   lazy + mmgrab_lazy_tlb() active
5472 	 *
5473 	 * kernel ->   user   switch + mmdrop_lazy_tlb() active
5474 	 *   user ->   user   switch
5475 	 *
5476 	 * switch_mm_cid() needs to be updated if the barriers provided
5477 	 * by context_switch() are modified.
5478 	 */
5479 	if (!next->mm) {                                // to kernel
5480 		enter_lazy_tlb(prev->active_mm, next);
5481 
5482 		next->active_mm = prev->active_mm;
5483 		if (prev->mm)                           // from user
5484 			mmgrab_lazy_tlb(prev->active_mm);
5485 		else
5486 			prev->active_mm = NULL;
5487 	} else {                                        // to user
5488 		membarrier_switch_mm(rq, prev->active_mm, next->mm);
5489 		/*
5490 		 * sys_membarrier() requires an smp_mb() between setting
5491 		 * rq->curr / membarrier_switch_mm() and returning to userspace.
5492 		 *
5493 		 * The below provides this either through switch_mm(), or in
5494 		 * case 'prev->active_mm == next->mm' through
5495 		 * finish_task_switch()'s mmdrop().
5496 		 */
5497 		switch_mm_irqs_off(prev->active_mm, next->mm, next);
5498 		lru_gen_use_mm(next->mm);
5499 
5500 		if (!prev->mm) {                        // from kernel
5501 			/* will mmdrop_lazy_tlb() in finish_task_switch(). */
5502 			rq->prev_mm = prev->active_mm;
5503 			prev->active_mm = NULL;
5504 		}
5505 	}
5506 
5507 	/* switch_mm_cid() requires the memory barriers above. */
5508 	switch_mm_cid(rq, prev, next);
5509 
5510 	prepare_lock_switch(rq, next, rf);
5511 
5512 	trace_android_rvh_context_switch(prev, next);
5513 	/* Here we just switch the register state and the stack. */
5514 	switch_to(prev, next, prev);
5515 	barrier();
5516 
5517 	return finish_task_switch(prev);
5518 }
5519 
5520 /*
5521  * nr_running and nr_context_switches:
5522  *
5523  * externally visible scheduler statistics: current number of runnable
5524  * threads, total number of context switches performed since bootup.
5525  */
nr_running(void)5526 unsigned int nr_running(void)
5527 {
5528 	unsigned int i, sum = 0;
5529 
5530 	for_each_online_cpu(i)
5531 		sum += cpu_rq(i)->nr_running;
5532 
5533 	return sum;
5534 }
5535 EXPORT_SYMBOL(nr_running);
5536 
5537 /*
5538  * Check if only the current task is running on the CPU.
5539  *
5540  * Caution: this function does not check that the caller has disabled
5541  * preemption, thus the result might have a time-of-check-to-time-of-use
5542  * race.  The caller is responsible to use it correctly, for example:
5543  *
5544  * - from a non-preemptible section (of course)
5545  *
5546  * - from a thread that is bound to a single CPU
5547  *
5548  * - in a loop with very short iterations (e.g. a polling loop)
5549  */
single_task_running(void)5550 bool single_task_running(void)
5551 {
5552 	return raw_rq()->nr_running == 1;
5553 }
5554 EXPORT_SYMBOL(single_task_running);
5555 
nr_context_switches_cpu(int cpu)5556 unsigned long long nr_context_switches_cpu(int cpu)
5557 {
5558 	return cpu_rq(cpu)->nr_switches;
5559 }
5560 
nr_context_switches(void)5561 unsigned long long nr_context_switches(void)
5562 {
5563 	int i;
5564 	unsigned long long sum = 0;
5565 
5566 	for_each_possible_cpu(i)
5567 		sum += cpu_rq(i)->nr_switches;
5568 
5569 	return sum;
5570 }
5571 
5572 /*
5573  * Consumers of these two interfaces, like for example the cpuidle menu
5574  * governor, are using nonsensical data. Preferring shallow idle state selection
5575  * for a CPU that has IO-wait which might not even end up running the task when
5576  * it does become runnable.
5577  */
5578 
nr_iowait_cpu(int cpu)5579 unsigned int nr_iowait_cpu(int cpu)
5580 {
5581 	return atomic_read(&cpu_rq(cpu)->nr_iowait);
5582 }
5583 
5584 /*
5585  * IO-wait accounting, and how it's mostly bollocks (on SMP).
5586  *
5587  * The idea behind IO-wait account is to account the idle time that we could
5588  * have spend running if it were not for IO. That is, if we were to improve the
5589  * storage performance, we'd have a proportional reduction in IO-wait time.
5590  *
5591  * This all works nicely on UP, where, when a task blocks on IO, we account
5592  * idle time as IO-wait, because if the storage were faster, it could've been
5593  * running and we'd not be idle.
5594  *
5595  * This has been extended to SMP, by doing the same for each CPU. This however
5596  * is broken.
5597  *
5598  * Imagine for instance the case where two tasks block on one CPU, only the one
5599  * CPU will have IO-wait accounted, while the other has regular idle. Even
5600  * though, if the storage were faster, both could've ran at the same time,
5601  * utilising both CPUs.
5602  *
5603  * This means, that when looking globally, the current IO-wait accounting on
5604  * SMP is a lower bound, by reason of under accounting.
5605  *
5606  * Worse, since the numbers are provided per CPU, they are sometimes
5607  * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
5608  * associated with any one particular CPU, it can wake to another CPU than it
5609  * blocked on. This means the per CPU IO-wait number is meaningless.
5610  *
5611  * Task CPU affinities can make all that even more 'interesting'.
5612  */
5613 
nr_iowait(void)5614 unsigned int nr_iowait(void)
5615 {
5616 	unsigned int i, sum = 0;
5617 
5618 	for_each_possible_cpu(i)
5619 		sum += nr_iowait_cpu(i);
5620 
5621 	return sum;
5622 }
5623 
5624 #ifdef CONFIG_SMP
5625 
5626 /*
5627  * sched_exec - execve() is a valuable balancing opportunity, because at
5628  * this point the task has the smallest effective memory and cache footprint.
5629  */
sched_exec(void)5630 void sched_exec(void)
5631 {
5632 	struct task_struct *p = current;
5633 	struct migration_arg arg;
5634 	int dest_cpu;
5635 	bool cond = false;
5636 
5637 	trace_android_rvh_sched_exec(&cond);
5638 	if (cond)
5639 		return;
5640 
5641 	scoped_guard (raw_spinlock_irqsave, &p->pi_lock) {
5642 		dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), WF_EXEC);
5643 		if (dest_cpu == smp_processor_id())
5644 			return;
5645 
5646 		if (unlikely(!cpu_active(dest_cpu)))
5647 			return;
5648 
5649 		arg = (struct migration_arg){ p, dest_cpu };
5650 	}
5651 	stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
5652 }
5653 
5654 #endif
5655 
5656 DEFINE_PER_CPU(struct kernel_stat, kstat);
5657 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
5658 
5659 EXPORT_PER_CPU_SYMBOL(kstat);
5660 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
5661 
5662 /*
5663  * The function fair_sched_class.update_curr accesses the struct curr
5664  * and its field curr->exec_start; when called from task_sched_runtime(),
5665  * we observe a high rate of cache misses in practice.
5666  * Prefetching this data results in improved performance.
5667  */
prefetch_curr_exec_start(struct task_struct * p)5668 static inline void prefetch_curr_exec_start(struct task_struct *p)
5669 {
5670 #ifdef CONFIG_FAIR_GROUP_SCHED
5671 	struct sched_entity *curr = (&p->se)->cfs_rq->curr;
5672 #else
5673 	struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
5674 #endif
5675 	prefetch(curr);
5676 	prefetch(&curr->exec_start);
5677 }
5678 
5679 /*
5680  * Return accounted runtime for the task.
5681  * In case the task is currently running, return the runtime plus current's
5682  * pending runtime that have not been accounted yet.
5683  */
task_sched_runtime(struct task_struct * p)5684 unsigned long long task_sched_runtime(struct task_struct *p)
5685 {
5686 	struct rq_flags rf;
5687 	struct rq *rq;
5688 	u64 ns;
5689 
5690 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
5691 	/*
5692 	 * 64-bit doesn't need locks to atomically read a 64-bit value.
5693 	 * So we have a optimization chance when the task's delta_exec is 0.
5694 	 * Reading ->on_cpu is racy, but this is ok.
5695 	 *
5696 	 * If we race with it leaving CPU, we'll take a lock. So we're correct.
5697 	 * If we race with it entering CPU, unaccounted time is 0. This is
5698 	 * indistinguishable from the read occurring a few cycles earlier.
5699 	 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
5700 	 * been accounted, so we're correct here as well.
5701 	 */
5702 	if (!p->on_cpu || !task_on_rq_queued(p))
5703 		return p->se.sum_exec_runtime;
5704 #endif
5705 
5706 	rq = task_rq_lock(p, &rf);
5707 	/*
5708 	 * Must be ->curr _and_ ->on_rq.  If dequeued, we would
5709 	 * project cycles that may never be accounted to this
5710 	 * thread, breaking clock_gettime().
5711 	 */
5712 	if (task_current(rq, p) && task_on_rq_queued(p)) {
5713 		prefetch_curr_exec_start(p);
5714 		update_rq_clock(rq);
5715 		p->sched_class->update_curr(rq);
5716 	}
5717 	ns = p->se.sum_exec_runtime;
5718 	task_rq_unlock(rq, p, &rf);
5719 
5720 	return ns;
5721 }
5722 EXPORT_SYMBOL_GPL(task_sched_runtime);
5723 
5724 #ifdef CONFIG_SCHED_DEBUG
cpu_resched_latency(struct rq * rq)5725 static u64 cpu_resched_latency(struct rq *rq)
5726 {
5727 	int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms);
5728 	u64 resched_latency, now = rq_clock(rq);
5729 	static bool warned_once;
5730 
5731 	if (sysctl_resched_latency_warn_once && warned_once)
5732 		return 0;
5733 
5734 	if (!need_resched() || !latency_warn_ms)
5735 		return 0;
5736 
5737 	if (system_state == SYSTEM_BOOTING)
5738 		return 0;
5739 
5740 	if (!rq->last_seen_need_resched_ns) {
5741 		rq->last_seen_need_resched_ns = now;
5742 		rq->ticks_without_resched = 0;
5743 		return 0;
5744 	}
5745 
5746 	rq->ticks_without_resched++;
5747 	resched_latency = now - rq->last_seen_need_resched_ns;
5748 	if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC)
5749 		return 0;
5750 
5751 	warned_once = true;
5752 
5753 	return resched_latency;
5754 }
5755 
setup_resched_latency_warn_ms(char * str)5756 static int __init setup_resched_latency_warn_ms(char *str)
5757 {
5758 	long val;
5759 
5760 	if ((kstrtol(str, 0, &val))) {
5761 		pr_warn("Unable to set resched_latency_warn_ms\n");
5762 		return 1;
5763 	}
5764 
5765 	sysctl_resched_latency_warn_ms = val;
5766 	return 1;
5767 }
5768 __setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms);
5769 #else
cpu_resched_latency(struct rq * rq)5770 static inline u64 cpu_resched_latency(struct rq *rq) { return 0; }
5771 #endif /* CONFIG_SCHED_DEBUG */
5772 
5773 /*
5774  * This function gets called by the timer code, with HZ frequency.
5775  * We call it with interrupts disabled.
5776  */
scheduler_tick(void)5777 void scheduler_tick(void)
5778 {
5779 	int cpu = smp_processor_id();
5780 	struct rq *rq = cpu_rq(cpu);
5781 	struct task_struct *curr;
5782 	struct rq_flags rf;
5783 	unsigned long thermal_pressure;
5784 	u64 resched_latency;
5785 
5786 	if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5787 		arch_scale_freq_tick();
5788 
5789 	sched_clock_tick();
5790 
5791 	rq_lock(rq, &rf);
5792 
5793 	curr = rq->curr;
5794 	psi_account_irqtime(rq, curr, NULL);
5795 
5796 	update_rq_clock(rq);
5797 	trace_android_rvh_tick_entry(rq);
5798 
5799 	thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
5800 	update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure);
5801 	curr->sched_class->task_tick(rq, curr, 0);
5802 	if (sched_feat(LATENCY_WARN))
5803 		resched_latency = cpu_resched_latency(rq);
5804 	calc_global_load_tick(rq);
5805 	sched_core_tick(rq);
5806 	task_tick_mm_cid(rq, curr);
5807 
5808 	rq_unlock(rq, &rf);
5809 
5810 	if (sched_feat(LATENCY_WARN) && resched_latency)
5811 		resched_latency_warn(cpu, resched_latency);
5812 
5813 	perf_event_task_tick();
5814 
5815 	if (curr->flags & PF_WQ_WORKER)
5816 		wq_worker_tick(curr);
5817 
5818 #ifdef CONFIG_SMP
5819 	rq->idle_balance = idle_cpu(cpu);
5820 	trigger_load_balance(rq);
5821 #endif
5822 
5823 	trace_android_vh_scheduler_tick(rq);
5824 }
5825 
5826 #ifdef CONFIG_NO_HZ_FULL
5827 
5828 struct tick_work {
5829 	int			cpu;
5830 	atomic_t		state;
5831 	struct delayed_work	work;
5832 };
5833 /* Values for ->state, see diagram below. */
5834 #define TICK_SCHED_REMOTE_OFFLINE	0
5835 #define TICK_SCHED_REMOTE_OFFLINING	1
5836 #define TICK_SCHED_REMOTE_RUNNING	2
5837 
5838 /*
5839  * State diagram for ->state:
5840  *
5841  *
5842  *          TICK_SCHED_REMOTE_OFFLINE
5843  *                    |   ^
5844  *                    |   |
5845  *                    |   | sched_tick_remote()
5846  *                    |   |
5847  *                    |   |
5848  *                    +--TICK_SCHED_REMOTE_OFFLINING
5849  *                    |   ^
5850  *                    |   |
5851  * sched_tick_start() |   | sched_tick_stop()
5852  *                    |   |
5853  *                    V   |
5854  *          TICK_SCHED_REMOTE_RUNNING
5855  *
5856  *
5857  * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
5858  * and sched_tick_start() are happy to leave the state in RUNNING.
5859  */
5860 
5861 static struct tick_work __percpu *tick_work_cpu;
5862 
sched_tick_remote(struct work_struct * work)5863 static void sched_tick_remote(struct work_struct *work)
5864 {
5865 	struct delayed_work *dwork = to_delayed_work(work);
5866 	struct tick_work *twork = container_of(dwork, struct tick_work, work);
5867 	int cpu = twork->cpu;
5868 	struct rq *rq = cpu_rq(cpu);
5869 	int os;
5870 
5871 	/*
5872 	 * Handle the tick only if it appears the remote CPU is running in full
5873 	 * dynticks mode. The check is racy by nature, but missing a tick or
5874 	 * having one too much is no big deal because the scheduler tick updates
5875 	 * statistics and checks timeslices in a time-independent way, regardless
5876 	 * of when exactly it is running.
5877 	 */
5878 	if (tick_nohz_tick_stopped_cpu(cpu)) {
5879 		guard(rq_lock_irq)(rq);
5880 		struct task_struct *curr = rq->curr;
5881 
5882 		if (cpu_online(cpu)) {
5883 			update_rq_clock(rq);
5884 
5885 			if (!is_idle_task(curr)) {
5886 				/*
5887 				 * Make sure the next tick runs within a
5888 				 * reasonable amount of time.
5889 				 */
5890 				u64 delta = rq_clock_task(rq) - curr->se.exec_start;
5891 				WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
5892 			}
5893 			curr->sched_class->task_tick(rq, curr, 0);
5894 
5895 			calc_load_nohz_remote(rq);
5896 		}
5897 	}
5898 
5899 	/*
5900 	 * Run the remote tick once per second (1Hz). This arbitrary
5901 	 * frequency is large enough to avoid overload but short enough
5902 	 * to keep scheduler internal stats reasonably up to date.  But
5903 	 * first update state to reflect hotplug activity if required.
5904 	 */
5905 	os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
5906 	WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
5907 	if (os == TICK_SCHED_REMOTE_RUNNING)
5908 		queue_delayed_work(system_unbound_wq, dwork, HZ);
5909 }
5910 
sched_tick_start(int cpu)5911 static void sched_tick_start(int cpu)
5912 {
5913 	int os;
5914 	struct tick_work *twork;
5915 
5916 	if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5917 		return;
5918 
5919 	WARN_ON_ONCE(!tick_work_cpu);
5920 
5921 	twork = per_cpu_ptr(tick_work_cpu, cpu);
5922 	os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
5923 	WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
5924 	if (os == TICK_SCHED_REMOTE_OFFLINE) {
5925 		twork->cpu = cpu;
5926 		INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
5927 		queue_delayed_work(system_unbound_wq, &twork->work, HZ);
5928 	}
5929 }
5930 
5931 #ifdef CONFIG_HOTPLUG_CPU
sched_tick_stop(int cpu)5932 static void sched_tick_stop(int cpu)
5933 {
5934 	struct tick_work *twork;
5935 	int os;
5936 
5937 	if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5938 		return;
5939 
5940 	WARN_ON_ONCE(!tick_work_cpu);
5941 
5942 	twork = per_cpu_ptr(tick_work_cpu, cpu);
5943 	/* There cannot be competing actions, but don't rely on stop-machine. */
5944 	os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
5945 	WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
5946 	/* Don't cancel, as this would mess up the state machine. */
5947 }
5948 #endif /* CONFIG_HOTPLUG_CPU */
5949 
sched_tick_offload_init(void)5950 int __init sched_tick_offload_init(void)
5951 {
5952 	tick_work_cpu = alloc_percpu(struct tick_work);
5953 	BUG_ON(!tick_work_cpu);
5954 	return 0;
5955 }
5956 
5957 #else /* !CONFIG_NO_HZ_FULL */
sched_tick_start(int cpu)5958 static inline void sched_tick_start(int cpu) { }
sched_tick_stop(int cpu)5959 static inline void sched_tick_stop(int cpu) { }
5960 #endif
5961 
5962 #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
5963 				defined(CONFIG_TRACE_PREEMPT_TOGGLE))
5964 /*
5965  * If the value passed in is equal to the current preempt count
5966  * then we just disabled preemption. Start timing the latency.
5967  */
preempt_latency_start(int val)5968 static inline void preempt_latency_start(int val)
5969 {
5970 	if (preempt_count() == val) {
5971 		unsigned long ip = get_lock_parent_ip();
5972 #ifdef CONFIG_DEBUG_PREEMPT
5973 		current->preempt_disable_ip = ip;
5974 #endif
5975 		trace_preempt_off(CALLER_ADDR0, ip);
5976 	}
5977 }
5978 
preempt_count_add(int val)5979 void preempt_count_add(int val)
5980 {
5981 #ifdef CONFIG_DEBUG_PREEMPT
5982 	/*
5983 	 * Underflow?
5984 	 */
5985 	if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5986 		return;
5987 #endif
5988 	__preempt_count_add(val);
5989 #ifdef CONFIG_DEBUG_PREEMPT
5990 	/*
5991 	 * Spinlock count overflowing soon?
5992 	 */
5993 	DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5994 				PREEMPT_MASK - 10);
5995 #endif
5996 	preempt_latency_start(val);
5997 }
5998 EXPORT_SYMBOL(preempt_count_add);
5999 NOKPROBE_SYMBOL(preempt_count_add);
6000 
6001 /*
6002  * If the value passed in equals to the current preempt count
6003  * then we just enabled preemption. Stop timing the latency.
6004  */
preempt_latency_stop(int val)6005 static inline void preempt_latency_stop(int val)
6006 {
6007 	if (preempt_count() == val)
6008 		trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
6009 }
6010 
preempt_count_sub(int val)6011 void preempt_count_sub(int val)
6012 {
6013 #ifdef CONFIG_DEBUG_PREEMPT
6014 	/*
6015 	 * Underflow?
6016 	 */
6017 	if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
6018 		return;
6019 	/*
6020 	 * Is the spinlock portion underflowing?
6021 	 */
6022 	if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
6023 			!(preempt_count() & PREEMPT_MASK)))
6024 		return;
6025 #endif
6026 
6027 	preempt_latency_stop(val);
6028 	__preempt_count_sub(val);
6029 }
6030 EXPORT_SYMBOL(preempt_count_sub);
6031 NOKPROBE_SYMBOL(preempt_count_sub);
6032 
6033 #else
preempt_latency_start(int val)6034 static inline void preempt_latency_start(int val) { }
preempt_latency_stop(int val)6035 static inline void preempt_latency_stop(int val) { }
6036 #endif
6037 
get_preempt_disable_ip(struct task_struct * p)6038 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
6039 {
6040 #ifdef CONFIG_DEBUG_PREEMPT
6041 	return p->preempt_disable_ip;
6042 #else
6043 	return 0;
6044 #endif
6045 }
6046 
6047 /*
6048  * Print scheduling while atomic bug:
6049  */
__schedule_bug(struct task_struct * prev)6050 static noinline void __schedule_bug(struct task_struct *prev)
6051 {
6052 	/* Save this before calling printk(), since that will clobber it */
6053 	unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
6054 
6055 	if (oops_in_progress)
6056 		return;
6057 
6058 	printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
6059 		prev->comm, prev->pid, preempt_count());
6060 
6061 	debug_show_held_locks(prev);
6062 	print_modules();
6063 	if (irqs_disabled())
6064 		print_irqtrace_events(prev);
6065 	if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
6066 	    && in_atomic_preempt_off()) {
6067 		pr_err("Preemption disabled at:");
6068 		print_ip_sym(KERN_ERR, preempt_disable_ip);
6069 	}
6070 	check_panic_on_warn("scheduling while atomic");
6071 
6072 	trace_android_rvh_schedule_bug(prev);
6073 
6074 	dump_stack();
6075 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
6076 }
6077 
6078 /*
6079  * Various schedule()-time debugging checks and statistics:
6080  */
schedule_debug(struct task_struct * prev,bool preempt)6081 static inline void schedule_debug(struct task_struct *prev, bool preempt)
6082 {
6083 #ifdef CONFIG_SCHED_STACK_END_CHECK
6084 	if (task_stack_end_corrupted(prev))
6085 		panic("corrupted stack end detected inside scheduler\n");
6086 
6087 	if (task_scs_end_corrupted(prev))
6088 		panic("corrupted shadow stack detected inside scheduler\n");
6089 #endif
6090 
6091 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
6092 	if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) {
6093 		printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
6094 			prev->comm, prev->pid, prev->non_block_count);
6095 		dump_stack();
6096 		add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
6097 	}
6098 #endif
6099 
6100 	if (unlikely(in_atomic_preempt_off())) {
6101 		__schedule_bug(prev);
6102 		preempt_count_set(PREEMPT_DISABLED);
6103 	}
6104 	rcu_sleep_check();
6105 	SCHED_WARN_ON(ct_state() == CONTEXT_USER);
6106 
6107 	profile_hit(SCHED_PROFILING, __builtin_return_address(0));
6108 
6109 	schedstat_inc(this_rq()->sched_count);
6110 }
6111 
put_prev_task_balance(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)6112 static void put_prev_task_balance(struct rq *rq, struct task_struct *prev,
6113 				  struct rq_flags *rf)
6114 {
6115 #ifdef CONFIG_SMP
6116 	const struct sched_class *class;
6117 	/*
6118 	 * We must do the balancing pass before put_prev_task(), such
6119 	 * that when we release the rq->lock the task is in the same
6120 	 * state as before we took rq->lock.
6121 	 *
6122 	 * We can terminate the balance pass as soon as we know there is
6123 	 * a runnable task of @class priority or higher.
6124 	 */
6125 	for_class_range(class, prev->sched_class, &idle_sched_class) {
6126 		if (class->balance(rq, prev, rf))
6127 			break;
6128 	}
6129 #endif
6130 
6131 	put_prev_task(rq, prev);
6132 }
6133 
6134 /*
6135  * Pick up the highest-prio task:
6136  */
6137 static inline struct task_struct *
__pick_next_task(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)6138 __pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6139 {
6140 	const struct sched_class *class;
6141 	struct task_struct *p;
6142 
6143 	/*
6144 	 * Optimization: we know that if all tasks are in the fair class we can
6145 	 * call that function directly, but only if the @prev task wasn't of a
6146 	 * higher scheduling class, because otherwise those lose the
6147 	 * opportunity to pull in more work from other CPUs.
6148 	 */
6149 	if (likely(!sched_class_above(prev->sched_class, &fair_sched_class) &&
6150 		   rq->nr_running == rq->cfs.h_nr_running)) {
6151 
6152 		p = pick_next_task_fair(rq, prev, rf);
6153 		if (unlikely(p == RETRY_TASK))
6154 			goto restart;
6155 
6156 		/* Assume the next prioritized class is idle_sched_class */
6157 		if (!p) {
6158 			put_prev_task(rq, prev);
6159 			p = pick_next_task_idle(rq);
6160 		}
6161 
6162 		return p;
6163 	}
6164 
6165 restart:
6166 	put_prev_task_balance(rq, prev, rf);
6167 
6168 	for_each_class(class) {
6169 		p = class->pick_next_task(rq);
6170 		if (p)
6171 			return p;
6172 	}
6173 
6174 	BUG(); /* The idle class should always have a runnable task. */
6175 }
6176 
6177 #ifdef CONFIG_SCHED_CORE
is_task_rq_idle(struct task_struct * t)6178 static inline bool is_task_rq_idle(struct task_struct *t)
6179 {
6180 	return (task_rq(t)->idle == t);
6181 }
6182 
cookie_equals(struct task_struct * a,unsigned long cookie)6183 static inline bool cookie_equals(struct task_struct *a, unsigned long cookie)
6184 {
6185 	return is_task_rq_idle(a) || (a->core_cookie == cookie);
6186 }
6187 
cookie_match(struct task_struct * a,struct task_struct * b)6188 static inline bool cookie_match(struct task_struct *a, struct task_struct *b)
6189 {
6190 	if (is_task_rq_idle(a) || is_task_rq_idle(b))
6191 		return true;
6192 
6193 	return a->core_cookie == b->core_cookie;
6194 }
6195 
pick_task(struct rq * rq)6196 static inline struct task_struct *pick_task(struct rq *rq)
6197 {
6198 	const struct sched_class *class;
6199 	struct task_struct *p;
6200 
6201 	for_each_class(class) {
6202 		p = class->pick_task(rq);
6203 		if (p)
6204 			return p;
6205 	}
6206 
6207 	BUG(); /* The idle class should always have a runnable task. */
6208 }
6209 
6210 extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi);
6211 
6212 static void queue_core_balance(struct rq *rq);
6213 
6214 static struct task_struct *
pick_next_task(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)6215 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6216 {
6217 	struct task_struct *next, *p, *max = NULL;
6218 	const struct cpumask *smt_mask;
6219 	bool fi_before = false;
6220 	bool core_clock_updated = (rq == rq->core);
6221 	unsigned long cookie;
6222 	int i, cpu, occ = 0;
6223 	struct rq *rq_i;
6224 	bool need_sync;
6225 
6226 	if (!sched_core_enabled(rq))
6227 		return __pick_next_task(rq, prev, rf);
6228 
6229 	cpu = cpu_of(rq);
6230 
6231 	/* Stopper task is switching into idle, no need core-wide selection. */
6232 	if (cpu_is_offline(cpu)) {
6233 		/*
6234 		 * Reset core_pick so that we don't enter the fastpath when
6235 		 * coming online. core_pick would already be migrated to
6236 		 * another cpu during offline.
6237 		 */
6238 		rq->core_pick = NULL;
6239 		return __pick_next_task(rq, prev, rf);
6240 	}
6241 
6242 	/*
6243 	 * If there were no {en,de}queues since we picked (IOW, the task
6244 	 * pointers are all still valid), and we haven't scheduled the last
6245 	 * pick yet, do so now.
6246 	 *
6247 	 * rq->core_pick can be NULL if no selection was made for a CPU because
6248 	 * it was either offline or went offline during a sibling's core-wide
6249 	 * selection. In this case, do a core-wide selection.
6250 	 */
6251 	if (rq->core->core_pick_seq == rq->core->core_task_seq &&
6252 	    rq->core->core_pick_seq != rq->core_sched_seq &&
6253 	    rq->core_pick) {
6254 		WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq);
6255 
6256 		next = rq->core_pick;
6257 		if (next != prev) {
6258 			put_prev_task(rq, prev);
6259 			set_next_task(rq, next);
6260 		}
6261 
6262 		rq->core_pick = NULL;
6263 		goto out;
6264 	}
6265 
6266 	put_prev_task_balance(rq, prev, rf);
6267 
6268 	smt_mask = cpu_smt_mask(cpu);
6269 	need_sync = !!rq->core->core_cookie;
6270 
6271 	/* reset state */
6272 	rq->core->core_cookie = 0UL;
6273 	if (rq->core->core_forceidle_count) {
6274 		if (!core_clock_updated) {
6275 			update_rq_clock(rq->core);
6276 			core_clock_updated = true;
6277 		}
6278 		sched_core_account_forceidle(rq);
6279 		/* reset after accounting force idle */
6280 		rq->core->core_forceidle_start = 0;
6281 		rq->core->core_forceidle_count = 0;
6282 		rq->core->core_forceidle_occupation = 0;
6283 		need_sync = true;
6284 		fi_before = true;
6285 	}
6286 
6287 	/*
6288 	 * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq
6289 	 *
6290 	 * @task_seq guards the task state ({en,de}queues)
6291 	 * @pick_seq is the @task_seq we did a selection on
6292 	 * @sched_seq is the @pick_seq we scheduled
6293 	 *
6294 	 * However, preemptions can cause multiple picks on the same task set.
6295 	 * 'Fix' this by also increasing @task_seq for every pick.
6296 	 */
6297 	rq->core->core_task_seq++;
6298 
6299 	/*
6300 	 * Optimize for common case where this CPU has no cookies
6301 	 * and there are no cookied tasks running on siblings.
6302 	 */
6303 	if (!need_sync) {
6304 		next = pick_task(rq);
6305 		if (!next->core_cookie) {
6306 			rq->core_pick = NULL;
6307 			/*
6308 			 * For robustness, update the min_vruntime_fi for
6309 			 * unconstrained picks as well.
6310 			 */
6311 			WARN_ON_ONCE(fi_before);
6312 			task_vruntime_update(rq, next, false);
6313 			goto out_set_next;
6314 		}
6315 	}
6316 
6317 	/*
6318 	 * For each thread: do the regular task pick and find the max prio task
6319 	 * amongst them.
6320 	 *
6321 	 * Tie-break prio towards the current CPU
6322 	 */
6323 	for_each_cpu_wrap(i, smt_mask, cpu) {
6324 		rq_i = cpu_rq(i);
6325 
6326 		/*
6327 		 * Current cpu always has its clock updated on entrance to
6328 		 * pick_next_task(). If the current cpu is not the core,
6329 		 * the core may also have been updated above.
6330 		 */
6331 		if (i != cpu && (rq_i != rq->core || !core_clock_updated))
6332 			update_rq_clock(rq_i);
6333 
6334 		p = rq_i->core_pick = pick_task(rq_i);
6335 		if (!max || prio_less(max, p, fi_before))
6336 			max = p;
6337 	}
6338 
6339 	cookie = rq->core->core_cookie = max->core_cookie;
6340 
6341 	/*
6342 	 * For each thread: try and find a runnable task that matches @max or
6343 	 * force idle.
6344 	 */
6345 	for_each_cpu(i, smt_mask) {
6346 		rq_i = cpu_rq(i);
6347 		p = rq_i->core_pick;
6348 
6349 		if (!cookie_equals(p, cookie)) {
6350 			p = NULL;
6351 			if (cookie)
6352 				p = sched_core_find(rq_i, cookie);
6353 			if (!p)
6354 				p = idle_sched_class.pick_task(rq_i);
6355 		}
6356 
6357 		rq_i->core_pick = p;
6358 
6359 		if (p == rq_i->idle) {
6360 			if (rq_i->nr_running) {
6361 				rq->core->core_forceidle_count++;
6362 				if (!fi_before)
6363 					rq->core->core_forceidle_seq++;
6364 			}
6365 		} else {
6366 			occ++;
6367 		}
6368 	}
6369 
6370 	if (schedstat_enabled() && rq->core->core_forceidle_count) {
6371 		rq->core->core_forceidle_start = rq_clock(rq->core);
6372 		rq->core->core_forceidle_occupation = occ;
6373 	}
6374 
6375 	rq->core->core_pick_seq = rq->core->core_task_seq;
6376 	next = rq->core_pick;
6377 	rq->core_sched_seq = rq->core->core_pick_seq;
6378 
6379 	/* Something should have been selected for current CPU */
6380 	WARN_ON_ONCE(!next);
6381 
6382 	/*
6383 	 * Reschedule siblings
6384 	 *
6385 	 * NOTE: L1TF -- at this point we're no longer running the old task and
6386 	 * sending an IPI (below) ensures the sibling will no longer be running
6387 	 * their task. This ensures there is no inter-sibling overlap between
6388 	 * non-matching user state.
6389 	 */
6390 	for_each_cpu(i, smt_mask) {
6391 		rq_i = cpu_rq(i);
6392 
6393 		/*
6394 		 * An online sibling might have gone offline before a task
6395 		 * could be picked for it, or it might be offline but later
6396 		 * happen to come online, but its too late and nothing was
6397 		 * picked for it.  That's Ok - it will pick tasks for itself,
6398 		 * so ignore it.
6399 		 */
6400 		if (!rq_i->core_pick)
6401 			continue;
6402 
6403 		/*
6404 		 * Update for new !FI->FI transitions, or if continuing to be in !FI:
6405 		 * fi_before     fi      update?
6406 		 *  0            0       1
6407 		 *  0            1       1
6408 		 *  1            0       1
6409 		 *  1            1       0
6410 		 */
6411 		if (!(fi_before && rq->core->core_forceidle_count))
6412 			task_vruntime_update(rq_i, rq_i->core_pick, !!rq->core->core_forceidle_count);
6413 
6414 		rq_i->core_pick->core_occupation = occ;
6415 
6416 		if (i == cpu) {
6417 			rq_i->core_pick = NULL;
6418 			continue;
6419 		}
6420 
6421 		/* Did we break L1TF mitigation requirements? */
6422 		WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick));
6423 
6424 		if (rq_i->curr == rq_i->core_pick) {
6425 			rq_i->core_pick = NULL;
6426 			continue;
6427 		}
6428 
6429 		resched_curr(rq_i);
6430 	}
6431 
6432 out_set_next:
6433 	set_next_task(rq, next);
6434 out:
6435 	if (rq->core->core_forceidle_count && next == rq->idle)
6436 		queue_core_balance(rq);
6437 
6438 	return next;
6439 }
6440 
try_steal_cookie(int this,int that)6441 static bool try_steal_cookie(int this, int that)
6442 {
6443 	struct rq *dst = cpu_rq(this), *src = cpu_rq(that);
6444 	struct task_struct *p;
6445 	unsigned long cookie;
6446 	bool success = false;
6447 
6448 	guard(irq)();
6449 	guard(double_rq_lock)(dst, src);
6450 
6451 	cookie = dst->core->core_cookie;
6452 	if (!cookie)
6453 		return false;
6454 
6455 	if (dst->curr != dst->idle)
6456 		return false;
6457 
6458 	p = sched_core_find(src, cookie);
6459 	if (!p)
6460 		return false;
6461 
6462 	do {
6463 		if (p == src->core_pick || p == src->curr)
6464 			goto next;
6465 
6466 		if (!is_cpu_allowed(p, this))
6467 			goto next;
6468 
6469 		if (p->core_occupation > dst->idle->core_occupation)
6470 			goto next;
6471 		/*
6472 		 * sched_core_find() and sched_core_next() will ensure
6473 		 * that task @p is not throttled now, we also need to
6474 		 * check whether the runqueue of the destination CPU is
6475 		 * being throttled.
6476 		 */
6477 		if (sched_task_is_throttled(p, this))
6478 			goto next;
6479 
6480 		deactivate_task(src, p, 0);
6481 		set_task_cpu(p, this);
6482 		activate_task(dst, p, 0);
6483 
6484 		resched_curr(dst);
6485 
6486 		success = true;
6487 		break;
6488 
6489 next:
6490 		p = sched_core_next(p, cookie);
6491 	} while (p);
6492 
6493 	return success;
6494 }
6495 
steal_cookie_task(int cpu,struct sched_domain * sd)6496 static bool steal_cookie_task(int cpu, struct sched_domain *sd)
6497 {
6498 	int i;
6499 
6500 	for_each_cpu_wrap(i, sched_domain_span(sd), cpu + 1) {
6501 		if (i == cpu)
6502 			continue;
6503 
6504 		if (need_resched())
6505 			break;
6506 
6507 		if (try_steal_cookie(cpu, i))
6508 			return true;
6509 	}
6510 
6511 	return false;
6512 }
6513 
sched_core_balance(struct rq * rq)6514 static void sched_core_balance(struct rq *rq)
6515 {
6516 	struct sched_domain *sd;
6517 	int cpu = cpu_of(rq);
6518 
6519 	preempt_disable();
6520 	rcu_read_lock();
6521 	raw_spin_rq_unlock_irq(rq);
6522 	for_each_domain(cpu, sd) {
6523 		if (need_resched())
6524 			break;
6525 
6526 		if (steal_cookie_task(cpu, sd))
6527 			break;
6528 	}
6529 	raw_spin_rq_lock_irq(rq);
6530 	rcu_read_unlock();
6531 	preempt_enable();
6532 }
6533 
6534 static DEFINE_PER_CPU(struct balance_callback, core_balance_head);
6535 
queue_core_balance(struct rq * rq)6536 static void queue_core_balance(struct rq *rq)
6537 {
6538 	if (!sched_core_enabled(rq))
6539 		return;
6540 
6541 	if (!rq->core->core_cookie)
6542 		return;
6543 
6544 	if (!rq->nr_running) /* not forced idle */
6545 		return;
6546 
6547 	queue_balance_callback(rq, &per_cpu(core_balance_head, rq->cpu), sched_core_balance);
6548 }
6549 
6550 DEFINE_LOCK_GUARD_1(core_lock, int,
6551 		    sched_core_lock(*_T->lock, &_T->flags),
6552 		    sched_core_unlock(*_T->lock, &_T->flags),
6553 		    unsigned long flags)
6554 
sched_core_cpu_starting(unsigned int cpu)6555 static void sched_core_cpu_starting(unsigned int cpu)
6556 {
6557 	const struct cpumask *smt_mask = cpu_smt_mask(cpu);
6558 	struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6559 	int t;
6560 
6561 	guard(core_lock)(&cpu);
6562 
6563 	WARN_ON_ONCE(rq->core != rq);
6564 
6565 	/* if we're the first, we'll be our own leader */
6566 	if (cpumask_weight(smt_mask) == 1)
6567 		return;
6568 
6569 	/* find the leader */
6570 	for_each_cpu(t, smt_mask) {
6571 		if (t == cpu)
6572 			continue;
6573 		rq = cpu_rq(t);
6574 		if (rq->core == rq) {
6575 			core_rq = rq;
6576 			break;
6577 		}
6578 	}
6579 
6580 	if (WARN_ON_ONCE(!core_rq)) /* whoopsie */
6581 		return;
6582 
6583 	/* install and validate core_rq */
6584 	for_each_cpu(t, smt_mask) {
6585 		rq = cpu_rq(t);
6586 
6587 		if (t == cpu)
6588 			rq->core = core_rq;
6589 
6590 		WARN_ON_ONCE(rq->core != core_rq);
6591 	}
6592 }
6593 
sched_core_cpu_deactivate(unsigned int cpu)6594 static void sched_core_cpu_deactivate(unsigned int cpu)
6595 {
6596 	const struct cpumask *smt_mask = cpu_smt_mask(cpu);
6597 	struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6598 	int t;
6599 
6600 	guard(core_lock)(&cpu);
6601 
6602 	/* if we're the last man standing, nothing to do */
6603 	if (cpumask_weight(smt_mask) == 1) {
6604 		WARN_ON_ONCE(rq->core != rq);
6605 		return;
6606 	}
6607 
6608 	/* if we're not the leader, nothing to do */
6609 	if (rq->core != rq)
6610 		return;
6611 
6612 	/* find a new leader */
6613 	for_each_cpu(t, smt_mask) {
6614 		if (t == cpu)
6615 			continue;
6616 		core_rq = cpu_rq(t);
6617 		break;
6618 	}
6619 
6620 	if (WARN_ON_ONCE(!core_rq)) /* impossible */
6621 		return;
6622 
6623 	/* copy the shared state to the new leader */
6624 	core_rq->core_task_seq             = rq->core_task_seq;
6625 	core_rq->core_pick_seq             = rq->core_pick_seq;
6626 	core_rq->core_cookie               = rq->core_cookie;
6627 	core_rq->core_forceidle_count      = rq->core_forceidle_count;
6628 	core_rq->core_forceidle_seq        = rq->core_forceidle_seq;
6629 	core_rq->core_forceidle_occupation = rq->core_forceidle_occupation;
6630 
6631 	/*
6632 	 * Accounting edge for forced idle is handled in pick_next_task().
6633 	 * Don't need another one here, since the hotplug thread shouldn't
6634 	 * have a cookie.
6635 	 */
6636 	core_rq->core_forceidle_start = 0;
6637 
6638 	/* install new leader */
6639 	for_each_cpu(t, smt_mask) {
6640 		rq = cpu_rq(t);
6641 		rq->core = core_rq;
6642 	}
6643 }
6644 
sched_core_cpu_dying(unsigned int cpu)6645 static inline void sched_core_cpu_dying(unsigned int cpu)
6646 {
6647 	struct rq *rq = cpu_rq(cpu);
6648 
6649 	if (rq->core != rq)
6650 		rq->core = rq;
6651 }
6652 
6653 #else /* !CONFIG_SCHED_CORE */
6654 
sched_core_cpu_starting(unsigned int cpu)6655 static inline void sched_core_cpu_starting(unsigned int cpu) {}
sched_core_cpu_deactivate(unsigned int cpu)6656 static inline void sched_core_cpu_deactivate(unsigned int cpu) {}
sched_core_cpu_dying(unsigned int cpu)6657 static inline void sched_core_cpu_dying(unsigned int cpu) {}
6658 
6659 static struct task_struct *
pick_next_task(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)6660 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6661 {
6662 	return __pick_next_task(rq, prev, rf);
6663 }
6664 
6665 #endif /* CONFIG_SCHED_CORE */
6666 
6667 /*
6668  * Constants for the sched_mode argument of __schedule().
6669  *
6670  * The mode argument allows RT enabled kernels to differentiate a
6671  * preemption from blocking on an 'sleeping' spin/rwlock. Note that
6672  * SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to
6673  * optimize the AND operation out and just check for zero.
6674  */
6675 #define SM_NONE			0x0
6676 #define SM_PREEMPT		0x1
6677 #define SM_RTLOCK_WAIT		0x2
6678 
6679 #ifndef CONFIG_PREEMPT_RT
6680 # define SM_MASK_PREEMPT	(~0U)
6681 #else
6682 # define SM_MASK_PREEMPT	SM_PREEMPT
6683 #endif
6684 
6685 /*
6686  * __schedule() is the main scheduler function.
6687  *
6688  * The main means of driving the scheduler and thus entering this function are:
6689  *
6690  *   1. Explicit blocking: mutex, semaphore, waitqueue, etc.
6691  *
6692  *   2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
6693  *      paths. For example, see arch/x86/entry_64.S.
6694  *
6695  *      To drive preemption between tasks, the scheduler sets the flag in timer
6696  *      interrupt handler scheduler_tick().
6697  *
6698  *   3. Wakeups don't really cause entry into schedule(). They add a
6699  *      task to the run-queue and that's it.
6700  *
6701  *      Now, if the new task added to the run-queue preempts the current
6702  *      task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
6703  *      called on the nearest possible occasion:
6704  *
6705  *       - If the kernel is preemptible (CONFIG_PREEMPTION=y):
6706  *
6707  *         - in syscall or exception context, at the next outmost
6708  *           preempt_enable(). (this might be as soon as the wake_up()'s
6709  *           spin_unlock()!)
6710  *
6711  *         - in IRQ context, return from interrupt-handler to
6712  *           preemptible context
6713  *
6714  *       - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
6715  *         then at the next:
6716  *
6717  *          - cond_resched() call
6718  *          - explicit schedule() call
6719  *          - return from syscall or exception to user-space
6720  *          - return from interrupt-handler to user-space
6721  *
6722  * WARNING: must be called with preemption disabled!
6723  */
__schedule(unsigned int sched_mode)6724 static void __sched notrace __schedule(unsigned int sched_mode)
6725 {
6726 	struct task_struct *prev, *next;
6727 	unsigned long *switch_count;
6728 	unsigned long prev_state;
6729 	struct rq_flags rf;
6730 	struct rq *rq;
6731 	int cpu;
6732 
6733 	cpu = smp_processor_id();
6734 	rq = cpu_rq(cpu);
6735 	prev = rq->curr;
6736 
6737 	schedule_debug(prev, !!sched_mode);
6738 
6739 	if (sched_feat(HRTICK) || sched_feat(HRTICK_DL))
6740 		hrtick_clear(rq);
6741 
6742 	local_irq_disable();
6743 	rcu_note_context_switch(!!sched_mode);
6744 
6745 	/*
6746 	 * Make sure that signal_pending_state()->signal_pending() below
6747 	 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
6748 	 * done by the caller to avoid the race with signal_wake_up():
6749 	 *
6750 	 * __set_current_state(@state)		signal_wake_up()
6751 	 * schedule()				  set_tsk_thread_flag(p, TIF_SIGPENDING)
6752 	 *					  wake_up_state(p, state)
6753 	 *   LOCK rq->lock			    LOCK p->pi_state
6754 	 *   smp_mb__after_spinlock()		    smp_mb__after_spinlock()
6755 	 *     if (signal_pending_state())	    if (p->state & @state)
6756 	 *
6757 	 * Also, the membarrier system call requires a full memory barrier
6758 	 * after coming from user-space, before storing to rq->curr.
6759 	 */
6760 	rq_lock(rq, &rf);
6761 	smp_mb__after_spinlock();
6762 
6763 	/* Promote REQ to ACT */
6764 	rq->clock_update_flags <<= 1;
6765 	update_rq_clock(rq);
6766 	rq->clock_update_flags = RQCF_UPDATED;
6767 
6768 	switch_count = &prev->nivcsw;
6769 
6770 	/*
6771 	 * We must load prev->state once (task_struct::state is volatile), such
6772 	 * that we form a control dependency vs deactivate_task() below.
6773 	 */
6774 	prev_state = READ_ONCE(prev->__state);
6775 	if (!(sched_mode & SM_MASK_PREEMPT) && prev_state) {
6776 		if (signal_pending_state(prev_state, prev)) {
6777 			WRITE_ONCE(prev->__state, TASK_RUNNING);
6778 		} else {
6779 			prev->sched_contributes_to_load =
6780 				(prev_state & TASK_UNINTERRUPTIBLE) &&
6781 				!(prev_state & TASK_NOLOAD) &&
6782 				!(prev_state & TASK_FROZEN);
6783 
6784 			if (prev->sched_contributes_to_load)
6785 				rq->nr_uninterruptible++;
6786 
6787 			/*
6788 			 * __schedule()			ttwu()
6789 			 *   prev_state = prev->state;    if (p->on_rq && ...)
6790 			 *   if (prev_state)		    goto out;
6791 			 *     p->on_rq = 0;		  smp_acquire__after_ctrl_dep();
6792 			 *				  p->state = TASK_WAKING
6793 			 *
6794 			 * Where __schedule() and ttwu() have matching control dependencies.
6795 			 *
6796 			 * After this, schedule() must not care about p->state any more.
6797 			 */
6798 			deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
6799 
6800 			if (prev->in_iowait) {
6801 				atomic_inc(&rq->nr_iowait);
6802 				delayacct_blkio_start();
6803 			}
6804 		}
6805 		switch_count = &prev->nvcsw;
6806 	}
6807 
6808 	next = pick_next_task(rq, prev, &rf);
6809 	clear_tsk_need_resched(prev);
6810 	clear_preempt_need_resched();
6811 #ifdef CONFIG_SCHED_DEBUG
6812 	rq->last_seen_need_resched_ns = 0;
6813 #endif
6814 
6815 	trace_android_rvh_schedule(prev, next, rq);
6816 	if (likely(prev != next)) {
6817 		rq->nr_switches++;
6818 		/*
6819 		 * RCU users of rcu_dereference(rq->curr) may not see
6820 		 * changes to task_struct made by pick_next_task().
6821 		 */
6822 		RCU_INIT_POINTER(rq->curr, next);
6823 		/*
6824 		 * The membarrier system call requires each architecture
6825 		 * to have a full memory barrier after updating
6826 		 * rq->curr, before returning to user-space.
6827 		 *
6828 		 * Here are the schemes providing that barrier on the
6829 		 * various architectures:
6830 		 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
6831 		 *   switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
6832 		 * - finish_lock_switch() for weakly-ordered
6833 		 *   architectures where spin_unlock is a full barrier,
6834 		 * - switch_to() for arm64 (weakly-ordered, spin_unlock
6835 		 *   is a RELEASE barrier),
6836 		 */
6837 		++*switch_count;
6838 
6839 		migrate_disable_switch(rq, prev);
6840 		psi_account_irqtime(rq, prev, next);
6841 		psi_sched_switch(prev, next, !task_on_rq_queued(prev));
6842 
6843 		trace_sched_switch(sched_mode & SM_MASK_PREEMPT, prev, next, prev_state);
6844 
6845 		/* Also unlocks the rq: */
6846 		rq = context_switch(rq, prev, next, &rf);
6847 	} else {
6848 		rq_unpin_lock(rq, &rf);
6849 		__balance_callbacks(rq);
6850 		raw_spin_rq_unlock_irq(rq);
6851 	}
6852 }
6853 
do_task_dead(void)6854 void __noreturn do_task_dead(void)
6855 {
6856 	/* Causes final put_task_struct in finish_task_switch(): */
6857 	set_special_state(TASK_DEAD);
6858 
6859 	/* Tell freezer to ignore us: */
6860 	current->flags |= PF_NOFREEZE;
6861 
6862 	__schedule(SM_NONE);
6863 	BUG();
6864 
6865 	/* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
6866 	for (;;)
6867 		cpu_relax();
6868 }
6869 
sched_submit_work(struct task_struct * tsk)6870 static inline void sched_submit_work(struct task_struct *tsk)
6871 {
6872 	unsigned int task_flags;
6873 
6874 	if (task_is_running(tsk))
6875 		return;
6876 
6877 	task_flags = tsk->flags;
6878 	/*
6879 	 * If a worker goes to sleep, notify and ask workqueue whether it
6880 	 * wants to wake up a task to maintain concurrency.
6881 	 */
6882 	if (task_flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
6883 		if (task_flags & PF_WQ_WORKER)
6884 			wq_worker_sleeping(tsk);
6885 		else
6886 			io_wq_worker_sleeping(tsk);
6887 	}
6888 
6889 	/*
6890 	 * spinlock and rwlock must not flush block requests.  This will
6891 	 * deadlock if the callback attempts to acquire a lock which is
6892 	 * already acquired.
6893 	 */
6894 	SCHED_WARN_ON(current->__state & TASK_RTLOCK_WAIT);
6895 
6896 	/*
6897 	 * If we are going to sleep and we have plugged IO queued,
6898 	 * make sure to submit it to avoid deadlocks.
6899 	 */
6900 	blk_flush_plug(tsk->plug, true);
6901 }
6902 
sched_update_worker(struct task_struct * tsk)6903 static void sched_update_worker(struct task_struct *tsk)
6904 {
6905 	if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
6906 		if (tsk->flags & PF_WQ_WORKER)
6907 			wq_worker_running(tsk);
6908 		else
6909 			io_wq_worker_running(tsk);
6910 	}
6911 }
6912 
schedule(void)6913 asmlinkage __visible void __sched schedule(void)
6914 {
6915 	struct task_struct *tsk = current;
6916 
6917 	sched_submit_work(tsk);
6918 	do {
6919 		preempt_disable();
6920 		__schedule(SM_NONE);
6921 		sched_preempt_enable_no_resched();
6922 	} while (need_resched());
6923 	sched_update_worker(tsk);
6924 }
6925 EXPORT_SYMBOL(schedule);
6926 
6927 /*
6928  * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
6929  * state (have scheduled out non-voluntarily) by making sure that all
6930  * tasks have either left the run queue or have gone into user space.
6931  * As idle tasks do not do either, they must not ever be preempted
6932  * (schedule out non-voluntarily).
6933  *
6934  * schedule_idle() is similar to schedule_preempt_disable() except that it
6935  * never enables preemption because it does not call sched_submit_work().
6936  */
schedule_idle(void)6937 void __sched schedule_idle(void)
6938 {
6939 	/*
6940 	 * As this skips calling sched_submit_work(), which the idle task does
6941 	 * regardless because that function is a nop when the task is in a
6942 	 * TASK_RUNNING state, make sure this isn't used someplace that the
6943 	 * current task can be in any other state. Note, idle is always in the
6944 	 * TASK_RUNNING state.
6945 	 */
6946 	WARN_ON_ONCE(current->__state);
6947 	do {
6948 		__schedule(SM_NONE);
6949 	} while (need_resched());
6950 }
6951 
6952 #if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK)
schedule_user(void)6953 asmlinkage __visible void __sched schedule_user(void)
6954 {
6955 	/*
6956 	 * If we come here after a random call to set_need_resched(),
6957 	 * or we have been woken up remotely but the IPI has not yet arrived,
6958 	 * we haven't yet exited the RCU idle mode. Do it here manually until
6959 	 * we find a better solution.
6960 	 *
6961 	 * NB: There are buggy callers of this function.  Ideally we
6962 	 * should warn if prev_state != CONTEXT_USER, but that will trigger
6963 	 * too frequently to make sense yet.
6964 	 */
6965 	enum ctx_state prev_state = exception_enter();
6966 	schedule();
6967 	exception_exit(prev_state);
6968 }
6969 #endif
6970 
6971 /**
6972  * schedule_preempt_disabled - called with preemption disabled
6973  *
6974  * Returns with preemption disabled. Note: preempt_count must be 1
6975  */
schedule_preempt_disabled(void)6976 void __sched schedule_preempt_disabled(void)
6977 {
6978 	sched_preempt_enable_no_resched();
6979 	schedule();
6980 	preempt_disable();
6981 }
6982 
6983 #ifdef CONFIG_PREEMPT_RT
schedule_rtlock(void)6984 void __sched notrace schedule_rtlock(void)
6985 {
6986 	do {
6987 		preempt_disable();
6988 		__schedule(SM_RTLOCK_WAIT);
6989 		sched_preempt_enable_no_resched();
6990 	} while (need_resched());
6991 }
6992 NOKPROBE_SYMBOL(schedule_rtlock);
6993 #endif
6994 
preempt_schedule_common(void)6995 static void __sched notrace preempt_schedule_common(void)
6996 {
6997 	do {
6998 		/*
6999 		 * Because the function tracer can trace preempt_count_sub()
7000 		 * and it also uses preempt_enable/disable_notrace(), if
7001 		 * NEED_RESCHED is set, the preempt_enable_notrace() called
7002 		 * by the function tracer will call this function again and
7003 		 * cause infinite recursion.
7004 		 *
7005 		 * Preemption must be disabled here before the function
7006 		 * tracer can trace. Break up preempt_disable() into two
7007 		 * calls. One to disable preemption without fear of being
7008 		 * traced. The other to still record the preemption latency,
7009 		 * which can also be traced by the function tracer.
7010 		 */
7011 		preempt_disable_notrace();
7012 		preempt_latency_start(1);
7013 		__schedule(SM_PREEMPT);
7014 		preempt_latency_stop(1);
7015 		preempt_enable_no_resched_notrace();
7016 
7017 		/*
7018 		 * Check again in case we missed a preemption opportunity
7019 		 * between schedule and now.
7020 		 */
7021 	} while (need_resched());
7022 }
7023 
7024 #ifdef CONFIG_PREEMPTION
7025 /*
7026  * This is the entry point to schedule() from in-kernel preemption
7027  * off of preempt_enable.
7028  */
preempt_schedule(void)7029 asmlinkage __visible void __sched notrace preempt_schedule(void)
7030 {
7031 	/*
7032 	 * If there is a non-zero preempt_count or interrupts are disabled,
7033 	 * we do not want to preempt the current task. Just return..
7034 	 */
7035 	if (likely(!preemptible()))
7036 		return;
7037 	preempt_schedule_common();
7038 }
7039 NOKPROBE_SYMBOL(preempt_schedule);
7040 EXPORT_SYMBOL(preempt_schedule);
7041 
7042 #ifdef CONFIG_PREEMPT_DYNAMIC
7043 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
7044 #ifndef preempt_schedule_dynamic_enabled
7045 #define preempt_schedule_dynamic_enabled	preempt_schedule
7046 #define preempt_schedule_dynamic_disabled	NULL
7047 #endif
7048 DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled);
7049 EXPORT_STATIC_CALL_TRAMP(preempt_schedule);
7050 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
7051 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule);
dynamic_preempt_schedule(void)7052 void __sched notrace dynamic_preempt_schedule(void)
7053 {
7054 	if (!static_branch_unlikely(&sk_dynamic_preempt_schedule))
7055 		return;
7056 	preempt_schedule();
7057 }
7058 NOKPROBE_SYMBOL(dynamic_preempt_schedule);
7059 EXPORT_SYMBOL(dynamic_preempt_schedule);
7060 #endif
7061 #endif
7062 
7063 /**
7064  * preempt_schedule_notrace - preempt_schedule called by tracing
7065  *
7066  * The tracing infrastructure uses preempt_enable_notrace to prevent
7067  * recursion and tracing preempt enabling caused by the tracing
7068  * infrastructure itself. But as tracing can happen in areas coming
7069  * from userspace or just about to enter userspace, a preempt enable
7070  * can occur before user_exit() is called. This will cause the scheduler
7071  * to be called when the system is still in usermode.
7072  *
7073  * To prevent this, the preempt_enable_notrace will use this function
7074  * instead of preempt_schedule() to exit user context if needed before
7075  * calling the scheduler.
7076  */
preempt_schedule_notrace(void)7077 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
7078 {
7079 	enum ctx_state prev_ctx;
7080 
7081 	if (likely(!preemptible()))
7082 		return;
7083 
7084 	do {
7085 		/*
7086 		 * Because the function tracer can trace preempt_count_sub()
7087 		 * and it also uses preempt_enable/disable_notrace(), if
7088 		 * NEED_RESCHED is set, the preempt_enable_notrace() called
7089 		 * by the function tracer will call this function again and
7090 		 * cause infinite recursion.
7091 		 *
7092 		 * Preemption must be disabled here before the function
7093 		 * tracer can trace. Break up preempt_disable() into two
7094 		 * calls. One to disable preemption without fear of being
7095 		 * traced. The other to still record the preemption latency,
7096 		 * which can also be traced by the function tracer.
7097 		 */
7098 		preempt_disable_notrace();
7099 		preempt_latency_start(1);
7100 		/*
7101 		 * Needs preempt disabled in case user_exit() is traced
7102 		 * and the tracer calls preempt_enable_notrace() causing
7103 		 * an infinite recursion.
7104 		 */
7105 		prev_ctx = exception_enter();
7106 		__schedule(SM_PREEMPT);
7107 		exception_exit(prev_ctx);
7108 
7109 		preempt_latency_stop(1);
7110 		preempt_enable_no_resched_notrace();
7111 	} while (need_resched());
7112 }
7113 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
7114 
7115 #ifdef CONFIG_PREEMPT_DYNAMIC
7116 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
7117 #ifndef preempt_schedule_notrace_dynamic_enabled
7118 #define preempt_schedule_notrace_dynamic_enabled	preempt_schedule_notrace
7119 #define preempt_schedule_notrace_dynamic_disabled	NULL
7120 #endif
7121 DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled);
7122 EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace);
7123 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
7124 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace);
dynamic_preempt_schedule_notrace(void)7125 void __sched notrace dynamic_preempt_schedule_notrace(void)
7126 {
7127 	if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace))
7128 		return;
7129 	preempt_schedule_notrace();
7130 }
7131 NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace);
7132 EXPORT_SYMBOL(dynamic_preempt_schedule_notrace);
7133 #endif
7134 #endif
7135 
7136 #endif /* CONFIG_PREEMPTION */
7137 
7138 /*
7139  * This is the entry point to schedule() from kernel preemption
7140  * off of irq context.
7141  * Note, that this is called and return with irqs disabled. This will
7142  * protect us against recursive calling from irq.
7143  */
preempt_schedule_irq(void)7144 asmlinkage __visible void __sched preempt_schedule_irq(void)
7145 {
7146 	enum ctx_state prev_state;
7147 
7148 	/* Catch callers which need to be fixed */
7149 	BUG_ON(preempt_count() || !irqs_disabled());
7150 
7151 	prev_state = exception_enter();
7152 
7153 	do {
7154 		preempt_disable();
7155 		local_irq_enable();
7156 		__schedule(SM_PREEMPT);
7157 		local_irq_disable();
7158 		sched_preempt_enable_no_resched();
7159 	} while (need_resched());
7160 
7161 	exception_exit(prev_state);
7162 }
7163 
default_wake_function(wait_queue_entry_t * curr,unsigned mode,int wake_flags,void * key)7164 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
7165 			  void *key)
7166 {
7167 	WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~(WF_SYNC|WF_CURRENT_CPU|WF_ANDROID_VENDOR));
7168 	return try_to_wake_up(curr->private, mode, wake_flags);
7169 }
7170 EXPORT_SYMBOL(default_wake_function);
7171 
__setscheduler_prio(struct task_struct * p,int prio)7172 static void __setscheduler_prio(struct task_struct *p, int prio)
7173 {
7174 	if (dl_prio(prio))
7175 		p->sched_class = &dl_sched_class;
7176 	else if (rt_prio(prio))
7177 		p->sched_class = &rt_sched_class;
7178 	else
7179 		p->sched_class = &fair_sched_class;
7180 
7181 	p->prio = prio;
7182 }
7183 
7184 #ifdef CONFIG_RT_MUTEXES
7185 
__rt_effective_prio(struct task_struct * pi_task,int prio)7186 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
7187 {
7188 	if (pi_task)
7189 		prio = min(prio, pi_task->prio);
7190 
7191 	return prio;
7192 }
7193 
rt_effective_prio(struct task_struct * p,int prio)7194 static inline int rt_effective_prio(struct task_struct *p, int prio)
7195 {
7196 	struct task_struct *pi_task = rt_mutex_get_top_task(p);
7197 
7198 	return __rt_effective_prio(pi_task, prio);
7199 }
7200 
7201 /*
7202  * rt_mutex_setprio - set the current priority of a task
7203  * @p: task to boost
7204  * @pi_task: donor task
7205  *
7206  * This function changes the 'effective' priority of a task. It does
7207  * not touch ->normal_prio like __setscheduler().
7208  *
7209  * Used by the rt_mutex code to implement priority inheritance
7210  * logic. Call site only calls if the priority of the task changed.
7211  */
rt_mutex_setprio(struct task_struct * p,struct task_struct * pi_task)7212 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
7213 {
7214 	int prio, oldprio, queued, running, queue_flag =
7215 		DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
7216 	const struct sched_class *prev_class;
7217 	struct rq_flags rf;
7218 	struct rq *rq;
7219 	int update = 0;
7220 
7221 	trace_android_rvh_rtmutex_prepare_setprio(p, pi_task);
7222 	/* XXX used to be waiter->prio, not waiter->task->prio */
7223 	prio = __rt_effective_prio(pi_task, p->normal_prio);
7224 
7225 	trace_android_rvh_rtmutex_force_update(p, pi_task, &update);
7226 	/*
7227 	 * If nothing changed; bail early.
7228 	 */
7229 	if (!update && p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
7230 		return;
7231 
7232 	rq = __task_rq_lock(p, &rf);
7233 	update_rq_clock(rq);
7234 	/*
7235 	 * Set under pi_lock && rq->lock, such that the value can be used under
7236 	 * either lock.
7237 	 *
7238 	 * Note that there is loads of tricky to make this pointer cache work
7239 	 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
7240 	 * ensure a task is de-boosted (pi_task is set to NULL) before the
7241 	 * task is allowed to run again (and can exit). This ensures the pointer
7242 	 * points to a blocked task -- which guarantees the task is present.
7243 	 */
7244 	p->pi_top_task = pi_task;
7245 
7246 	/*
7247 	 * For FIFO/RR we only need to set prio, if that matches we're done.
7248 	 */
7249 	if (!update && prio == p->prio && !dl_prio(prio))
7250 		goto out_unlock;
7251 
7252 	/*
7253 	 * Idle task boosting is a nono in general. There is one
7254 	 * exception, when PREEMPT_RT and NOHZ is active:
7255 	 *
7256 	 * The idle task calls get_next_timer_interrupt() and holds
7257 	 * the timer wheel base->lock on the CPU and another CPU wants
7258 	 * to access the timer (probably to cancel it). We can safely
7259 	 * ignore the boosting request, as the idle CPU runs this code
7260 	 * with interrupts disabled and will complete the lock
7261 	 * protected section without being interrupted. So there is no
7262 	 * real need to boost.
7263 	 */
7264 	if (unlikely(p == rq->idle)) {
7265 		WARN_ON(p != rq->curr);
7266 		WARN_ON(p->pi_blocked_on);
7267 		goto out_unlock;
7268 	}
7269 
7270 	trace_sched_pi_setprio(p, pi_task);
7271 	oldprio = p->prio;
7272 
7273 	if (oldprio == prio)
7274 		queue_flag &= ~DEQUEUE_MOVE;
7275 
7276 	prev_class = p->sched_class;
7277 	queued = task_on_rq_queued(p);
7278 	running = task_current(rq, p);
7279 	if (queued)
7280 		dequeue_task(rq, p, queue_flag);
7281 	if (running)
7282 		put_prev_task(rq, p);
7283 
7284 	/*
7285 	 * Boosting condition are:
7286 	 * 1. -rt task is running and holds mutex A
7287 	 *      --> -dl task blocks on mutex A
7288 	 *
7289 	 * 2. -dl task is running and holds mutex A
7290 	 *      --> -dl task blocks on mutex A and could preempt the
7291 	 *          running task
7292 	 */
7293 	if (dl_prio(prio)) {
7294 		if (!dl_prio(p->normal_prio) ||
7295 		    (pi_task && dl_prio(pi_task->prio) &&
7296 		     dl_entity_preempt(&pi_task->dl, &p->dl))) {
7297 			p->dl.pi_se = pi_task->dl.pi_se;
7298 			queue_flag |= ENQUEUE_REPLENISH;
7299 		} else {
7300 			p->dl.pi_se = &p->dl;
7301 		}
7302 	} else if (rt_prio(prio)) {
7303 		if (dl_prio(oldprio))
7304 			p->dl.pi_se = &p->dl;
7305 		if (oldprio < prio)
7306 			queue_flag |= ENQUEUE_HEAD;
7307 	} else {
7308 		if (dl_prio(oldprio))
7309 			p->dl.pi_se = &p->dl;
7310 		else if (rt_prio(oldprio))
7311 			p->rt.timeout = 0;
7312 		else if (!task_has_idle_policy(p))
7313 			reweight_task(p, prio - MAX_RT_PRIO);
7314 	}
7315 
7316 	__setscheduler_prio(p, prio);
7317 
7318 	if (queued)
7319 		enqueue_task(rq, p, queue_flag);
7320 	if (running)
7321 		set_next_task(rq, p);
7322 
7323 	check_class_changed(rq, p, prev_class, oldprio);
7324 out_unlock:
7325 	/* Avoid rq from going away on us: */
7326 	preempt_disable();
7327 
7328 	rq_unpin_lock(rq, &rf);
7329 	__balance_callbacks(rq);
7330 	raw_spin_rq_unlock(rq);
7331 
7332 	preempt_enable();
7333 }
7334 #else
rt_effective_prio(struct task_struct * p,int prio)7335 static inline int rt_effective_prio(struct task_struct *p, int prio)
7336 {
7337 	return prio;
7338 }
7339 #endif
7340 
set_user_nice(struct task_struct * p,long nice)7341 void set_user_nice(struct task_struct *p, long nice)
7342 {
7343 	bool queued, running, allowed = false;
7344 	int old_prio;
7345 	struct rq_flags rf;
7346 	struct rq *rq;
7347 
7348 	trace_android_rvh_set_user_nice(p, &nice, &allowed);
7349 	if ((task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE) && !allowed)
7350 		return;
7351 	/*
7352 	 * We have to be careful, if called from sys_setpriority(),
7353 	 * the task might be in the middle of scheduling on another CPU.
7354 	 */
7355 	rq = task_rq_lock(p, &rf);
7356 	update_rq_clock(rq);
7357 
7358 	trace_android_rvh_set_user_nice_locked(p, &nice);
7359 	if (task_nice(p) == nice)
7360 		goto out_unlock;
7361 
7362 	/*
7363 	 * The RT priorities are set via sched_setscheduler(), but we still
7364 	 * allow the 'normal' nice value to be set - but as expected
7365 	 * it won't have any effect on scheduling until the task is
7366 	 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
7367 	 */
7368 	if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
7369 		p->static_prio = NICE_TO_PRIO(nice);
7370 		goto out_unlock;
7371 	}
7372 	queued = task_on_rq_queued(p);
7373 	running = task_current(rq, p);
7374 	if (queued)
7375 		dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
7376 	if (running)
7377 		put_prev_task(rq, p);
7378 
7379 	p->static_prio = NICE_TO_PRIO(nice);
7380 	set_load_weight(p, true);
7381 	old_prio = p->prio;
7382 	p->prio = effective_prio(p);
7383 
7384 	if (queued)
7385 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
7386 	if (running)
7387 		set_next_task(rq, p);
7388 
7389 	/*
7390 	 * If the task increased its priority or is running and
7391 	 * lowered its priority, then reschedule its CPU:
7392 	 */
7393 	p->sched_class->prio_changed(rq, p, old_prio);
7394 
7395 out_unlock:
7396 	task_rq_unlock(rq, p, &rf);
7397 }
7398 EXPORT_SYMBOL(set_user_nice);
7399 
7400 /*
7401  * is_nice_reduction - check if nice value is an actual reduction
7402  *
7403  * Similar to can_nice() but does not perform a capability check.
7404  *
7405  * @p: task
7406  * @nice: nice value
7407  */
is_nice_reduction(const struct task_struct * p,const int nice)7408 static bool is_nice_reduction(const struct task_struct *p, const int nice)
7409 {
7410 	/* Convert nice value [19,-20] to rlimit style value [1,40]: */
7411 	int nice_rlim = nice_to_rlimit(nice);
7412 
7413 	return (nice_rlim <= task_rlimit(p, RLIMIT_NICE));
7414 }
7415 
7416 /*
7417  * can_nice - check if a task can reduce its nice value
7418  * @p: task
7419  * @nice: nice value
7420  */
can_nice(const struct task_struct * p,const int nice)7421 int can_nice(const struct task_struct *p, const int nice)
7422 {
7423 	return is_nice_reduction(p, nice) || capable(CAP_SYS_NICE);
7424 }
7425 
7426 #ifdef __ARCH_WANT_SYS_NICE
7427 
7428 /*
7429  * sys_nice - change the priority of the current process.
7430  * @increment: priority increment
7431  *
7432  * sys_setpriority is a more generic, but much slower function that
7433  * does similar things.
7434  */
SYSCALL_DEFINE1(nice,int,increment)7435 SYSCALL_DEFINE1(nice, int, increment)
7436 {
7437 	long nice, retval;
7438 
7439 	/*
7440 	 * Setpriority might change our priority at the same moment.
7441 	 * We don't have to worry. Conceptually one call occurs first
7442 	 * and we have a single winner.
7443 	 */
7444 	increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
7445 	nice = task_nice(current) + increment;
7446 
7447 	nice = clamp_val(nice, MIN_NICE, MAX_NICE);
7448 	if (increment < 0 && !can_nice(current, nice))
7449 		return -EPERM;
7450 
7451 	retval = security_task_setnice(current, nice);
7452 	if (retval)
7453 		return retval;
7454 
7455 	set_user_nice(current, nice);
7456 	return 0;
7457 }
7458 
7459 #endif
7460 
7461 /**
7462  * task_prio - return the priority value of a given task.
7463  * @p: the task in question.
7464  *
7465  * Return: The priority value as seen by users in /proc.
7466  *
7467  * sched policy         return value   kernel prio    user prio/nice
7468  *
7469  * normal, batch, idle     [0 ... 39]  [100 ... 139]          0/[-20 ... 19]
7470  * fifo, rr             [-2 ... -100]     [98 ... 0]  [1 ... 99]
7471  * deadline                     -101             -1           0
7472  */
task_prio(const struct task_struct * p)7473 int task_prio(const struct task_struct *p)
7474 {
7475 	return p->prio - MAX_RT_PRIO;
7476 }
7477 
7478 /**
7479  * idle_cpu - is a given CPU idle currently?
7480  * @cpu: the processor in question.
7481  *
7482  * Return: 1 if the CPU is currently idle. 0 otherwise.
7483  */
idle_cpu(int cpu)7484 int idle_cpu(int cpu)
7485 {
7486 	struct rq *rq = cpu_rq(cpu);
7487 
7488 	if (rq->curr != rq->idle)
7489 		return 0;
7490 
7491 	if (rq->nr_running)
7492 		return 0;
7493 
7494 #ifdef CONFIG_SMP
7495 	if (rq->ttwu_pending)
7496 		return 0;
7497 #endif
7498 
7499 	return 1;
7500 }
7501 
7502 /**
7503  * available_idle_cpu - is a given CPU idle for enqueuing work.
7504  * @cpu: the CPU in question.
7505  *
7506  * Return: 1 if the CPU is currently idle. 0 otherwise.
7507  */
available_idle_cpu(int cpu)7508 int available_idle_cpu(int cpu)
7509 {
7510 	if (!idle_cpu(cpu))
7511 		return 0;
7512 
7513 	if (vcpu_is_preempted(cpu))
7514 		return 0;
7515 
7516 	return 1;
7517 }
7518 EXPORT_SYMBOL_GPL(available_idle_cpu);
7519 
7520 /**
7521  * idle_task - return the idle task for a given CPU.
7522  * @cpu: the processor in question.
7523  *
7524  * Return: The idle task for the CPU @cpu.
7525  */
idle_task(int cpu)7526 struct task_struct *idle_task(int cpu)
7527 {
7528 	return cpu_rq(cpu)->idle;
7529 }
7530 
7531 #ifdef CONFIG_SCHED_CORE
sched_core_idle_cpu(int cpu)7532 int sched_core_idle_cpu(int cpu)
7533 {
7534 	struct rq *rq = cpu_rq(cpu);
7535 
7536 	if (sched_core_enabled(rq) && rq->curr == rq->idle)
7537 		return 1;
7538 
7539 	return idle_cpu(cpu);
7540 }
7541 
7542 #endif
7543 
7544 #ifdef CONFIG_SMP
7545 /*
7546  * This function computes an effective utilization for the given CPU, to be
7547  * used for frequency selection given the linear relation: f = u * f_max.
7548  *
7549  * The scheduler tracks the following metrics:
7550  *
7551  *   cpu_util_{cfs,rt,dl,irq}()
7552  *   cpu_bw_dl()
7553  *
7554  * Where the cfs,rt and dl util numbers are tracked with the same metric and
7555  * synchronized windows and are thus directly comparable.
7556  *
7557  * The cfs,rt,dl utilization are the running times measured with rq->clock_task
7558  * which excludes things like IRQ and steal-time. These latter are then accrued
7559  * in the irq utilization.
7560  *
7561  * The DL bandwidth number otoh is not a measured metric but a value computed
7562  * based on the task model parameters and gives the minimal utilization
7563  * required to meet deadlines.
7564  */
effective_cpu_util(int cpu,unsigned long util_cfs,enum cpu_util_type type,struct task_struct * p)7565 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
7566 				 enum cpu_util_type type,
7567 				 struct task_struct *p)
7568 {
7569 	unsigned long dl_util, util, irq, max;
7570 	struct rq *rq = cpu_rq(cpu);
7571 	unsigned long new_util = ULONG_MAX;
7572 
7573 	max = arch_scale_cpu_capacity(cpu);
7574 
7575 	trace_android_rvh_effective_cpu_util(cpu, util_cfs, max, type, p, &new_util);
7576 	if (new_util != ULONG_MAX)
7577 		return new_util;
7578 
7579 	if (!uclamp_is_used() &&
7580 	    type == FREQUENCY_UTIL && rt_rq_is_runnable(&rq->rt)) {
7581 		return max;
7582 	}
7583 
7584 	/*
7585 	 * Early check to see if IRQ/steal time saturates the CPU, can be
7586 	 * because of inaccuracies in how we track these -- see
7587 	 * update_irq_load_avg().
7588 	 */
7589 	irq = cpu_util_irq(rq);
7590 	if (unlikely(irq >= max))
7591 		return max;
7592 
7593 	/*
7594 	 * Because the time spend on RT/DL tasks is visible as 'lost' time to
7595 	 * CFS tasks and we use the same metric to track the effective
7596 	 * utilization (PELT windows are synchronized) we can directly add them
7597 	 * to obtain the CPU's actual utilization.
7598 	 *
7599 	 * CFS and RT utilization can be boosted or capped, depending on
7600 	 * utilization clamp constraints requested by currently RUNNABLE
7601 	 * tasks.
7602 	 * When there are no CFS RUNNABLE tasks, clamps are released and
7603 	 * frequency will be gracefully reduced with the utilization decay.
7604 	 */
7605 	util = util_cfs + cpu_util_rt(rq);
7606 	if (type == FREQUENCY_UTIL)
7607 		util = uclamp_rq_util_with(rq, util, p);
7608 
7609 	dl_util = cpu_util_dl(rq);
7610 
7611 	/*
7612 	 * For frequency selection we do not make cpu_util_dl() a permanent part
7613 	 * of this sum because we want to use cpu_bw_dl() later on, but we need
7614 	 * to check if the CFS+RT+DL sum is saturated (ie. no idle time) such
7615 	 * that we select f_max when there is no idle time.
7616 	 *
7617 	 * NOTE: numerical errors or stop class might cause us to not quite hit
7618 	 * saturation when we should -- something for later.
7619 	 */
7620 	if (util + dl_util >= max)
7621 		return max;
7622 
7623 	/*
7624 	 * OTOH, for energy computation we need the estimated running time, so
7625 	 * include util_dl and ignore dl_bw.
7626 	 */
7627 	if (type == ENERGY_UTIL)
7628 		util += dl_util;
7629 
7630 	/*
7631 	 * There is still idle time; further improve the number by using the
7632 	 * irq metric. Because IRQ/steal time is hidden from the task clock we
7633 	 * need to scale the task numbers:
7634 	 *
7635 	 *              max - irq
7636 	 *   U' = irq + --------- * U
7637 	 *                 max
7638 	 */
7639 	util = scale_irq_capacity(util, irq, max);
7640 	util += irq;
7641 
7642 	/*
7643 	 * Bandwidth required by DEADLINE must always be granted while, for
7644 	 * FAIR and RT, we use blocked utilization of IDLE CPUs as a mechanism
7645 	 * to gracefully reduce the frequency when no tasks show up for longer
7646 	 * periods of time.
7647 	 *
7648 	 * Ideally we would like to set bw_dl as min/guaranteed freq and util +
7649 	 * bw_dl as requested freq. However, cpufreq is not yet ready for such
7650 	 * an interface. So, we only do the latter for now.
7651 	 */
7652 	if (type == FREQUENCY_UTIL)
7653 		util += cpu_bw_dl(rq);
7654 
7655 	return min(max, util);
7656 }
7657 
sched_cpu_util(int cpu)7658 unsigned long sched_cpu_util(int cpu)
7659 {
7660 	return effective_cpu_util(cpu, cpu_util_cfs(cpu), ENERGY_UTIL, NULL);
7661 }
7662 #endif /* CONFIG_SMP */
7663 
7664 /**
7665  * find_process_by_pid - find a process with a matching PID value.
7666  * @pid: the pid in question.
7667  *
7668  * The task of @pid, if found. %NULL otherwise.
7669  */
find_process_by_pid(pid_t pid)7670 static struct task_struct *find_process_by_pid(pid_t pid)
7671 {
7672 	return pid ? find_task_by_vpid(pid) : current;
7673 }
7674 
7675 /*
7676  * sched_setparam() passes in -1 for its policy, to let the functions
7677  * it calls know not to change it.
7678  */
7679 #define SETPARAM_POLICY	-1
7680 
__setscheduler_params(struct task_struct * p,const struct sched_attr * attr)7681 static void __setscheduler_params(struct task_struct *p,
7682 		const struct sched_attr *attr)
7683 {
7684 	int policy = attr->sched_policy;
7685 
7686 	if (policy == SETPARAM_POLICY)
7687 		policy = p->policy;
7688 
7689 	p->policy = policy;
7690 
7691 	if (dl_policy(policy))
7692 		__setparam_dl(p, attr);
7693 	else if (fair_policy(policy))
7694 		p->static_prio = NICE_TO_PRIO(attr->sched_nice);
7695 
7696 	/*
7697 	 * __sched_setscheduler() ensures attr->sched_priority == 0 when
7698 	 * !rt_policy. Always setting this ensures that things like
7699 	 * getparam()/getattr() don't report silly values for !rt tasks.
7700 	 */
7701 	p->rt_priority = attr->sched_priority;
7702 	p->normal_prio = normal_prio(p);
7703 	set_load_weight(p, true);
7704 }
7705 
7706 /*
7707  * Check the target process has a UID that matches the current process's:
7708  */
check_same_owner(struct task_struct * p)7709 static bool check_same_owner(struct task_struct *p)
7710 {
7711 	const struct cred *cred = current_cred(), *pcred;
7712 	bool match;
7713 
7714 	rcu_read_lock();
7715 	pcred = __task_cred(p);
7716 	match = (uid_eq(cred->euid, pcred->euid) ||
7717 		 uid_eq(cred->euid, pcred->uid));
7718 	rcu_read_unlock();
7719 	return match;
7720 }
7721 
7722 /*
7723  * Allow unprivileged RT tasks to decrease priority.
7724  * Only issue a capable test if needed and only once to avoid an audit
7725  * event on permitted non-privileged operations:
7726  */
user_check_sched_setscheduler(struct task_struct * p,const struct sched_attr * attr,int policy,int reset_on_fork)7727 static int user_check_sched_setscheduler(struct task_struct *p,
7728 					 const struct sched_attr *attr,
7729 					 int policy, int reset_on_fork)
7730 {
7731 	if (fair_policy(policy)) {
7732 		if (attr->sched_nice < task_nice(p) &&
7733 		    !is_nice_reduction(p, attr->sched_nice))
7734 			goto req_priv;
7735 	}
7736 
7737 	if (rt_policy(policy)) {
7738 		unsigned long rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO);
7739 
7740 		/* Can't set/change the rt policy: */
7741 		if (policy != p->policy && !rlim_rtprio)
7742 			goto req_priv;
7743 
7744 		/* Can't increase priority: */
7745 		if (attr->sched_priority > p->rt_priority &&
7746 		    attr->sched_priority > rlim_rtprio)
7747 			goto req_priv;
7748 	}
7749 
7750 	/*
7751 	 * Can't set/change SCHED_DEADLINE policy at all for now
7752 	 * (safest behavior); in the future we would like to allow
7753 	 * unprivileged DL tasks to increase their relative deadline
7754 	 * or reduce their runtime (both ways reducing utilization)
7755 	 */
7756 	if (dl_policy(policy))
7757 		goto req_priv;
7758 
7759 	/*
7760 	 * Treat SCHED_IDLE as nice 20. Only allow a switch to
7761 	 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
7762 	 */
7763 	if (task_has_idle_policy(p) && !idle_policy(policy)) {
7764 		if (!is_nice_reduction(p, task_nice(p)))
7765 			goto req_priv;
7766 	}
7767 
7768 	/* Can't change other user's priorities: */
7769 	if (!check_same_owner(p))
7770 		goto req_priv;
7771 
7772 	/* Normal users shall not reset the sched_reset_on_fork flag: */
7773 	if (p->sched_reset_on_fork && !reset_on_fork)
7774 		goto req_priv;
7775 
7776 	return 0;
7777 
7778 req_priv:
7779 	if (!capable(CAP_SYS_NICE))
7780 		return -EPERM;
7781 
7782 	return 0;
7783 }
7784 
__sched_setscheduler(struct task_struct * p,const struct sched_attr * attr,bool user,bool pi)7785 static int __sched_setscheduler(struct task_struct *p,
7786 				const struct sched_attr *attr,
7787 				bool user, bool pi)
7788 {
7789 	int oldpolicy = -1, policy = attr->sched_policy;
7790 	int retval, oldprio, newprio, queued, running;
7791 	const struct sched_class *prev_class;
7792 	struct balance_callback *head;
7793 	struct rq_flags rf;
7794 	int reset_on_fork;
7795 	int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
7796 	struct rq *rq;
7797 	bool cpuset_locked = false;
7798 
7799 	/* The pi code expects interrupts enabled */
7800 	BUG_ON(pi && in_interrupt());
7801 recheck:
7802 	/* Double check policy once rq lock held: */
7803 	if (policy < 0) {
7804 		reset_on_fork = p->sched_reset_on_fork;
7805 		policy = oldpolicy = p->policy;
7806 	} else {
7807 		reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
7808 
7809 		if (!valid_policy(policy))
7810 			return -EINVAL;
7811 	}
7812 
7813 	if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
7814 		return -EINVAL;
7815 
7816 	/*
7817 	 * Valid priorities for SCHED_FIFO and SCHED_RR are
7818 	 * 1..MAX_RT_PRIO-1, valid priority for SCHED_NORMAL,
7819 	 * SCHED_BATCH and SCHED_IDLE is 0.
7820 	 */
7821 	if (attr->sched_priority > MAX_RT_PRIO-1)
7822 		return -EINVAL;
7823 	if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
7824 	    (rt_policy(policy) != (attr->sched_priority != 0)))
7825 		return -EINVAL;
7826 
7827 	if (user) {
7828 		retval = user_check_sched_setscheduler(p, attr, policy, reset_on_fork);
7829 		if (retval)
7830 			return retval;
7831 
7832 		if (attr->sched_flags & SCHED_FLAG_SUGOV)
7833 			return -EINVAL;
7834 
7835 		retval = security_task_setscheduler(p);
7836 		if (retval)
7837 			return retval;
7838 	}
7839 
7840 	/* Update task specific "requested" clamps */
7841 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) {
7842 		retval = uclamp_validate(p, attr);
7843 		if (retval)
7844 			return retval;
7845 	}
7846 
7847 	/*
7848 	 * SCHED_DEADLINE bandwidth accounting relies on stable cpusets
7849 	 * information.
7850 	 */
7851 	if (dl_policy(policy) || dl_policy(p->policy)) {
7852 		cpuset_locked = true;
7853 		cpuset_lock();
7854 	}
7855 
7856 	/*
7857 	 * Make sure no PI-waiters arrive (or leave) while we are
7858 	 * changing the priority of the task:
7859 	 *
7860 	 * To be able to change p->policy safely, the appropriate
7861 	 * runqueue lock must be held.
7862 	 */
7863 	rq = task_rq_lock(p, &rf);
7864 	update_rq_clock(rq);
7865 
7866 	/*
7867 	 * Changing the policy of the stop threads its a very bad idea:
7868 	 */
7869 	if (p == rq->stop) {
7870 		retval = -EINVAL;
7871 		goto unlock;
7872 	}
7873 
7874 	/*
7875 	 * If not changing anything there's no need to proceed further,
7876 	 * but store a possible modification of reset_on_fork.
7877 	 */
7878 	if (unlikely(policy == p->policy)) {
7879 		if (fair_policy(policy) && attr->sched_nice != task_nice(p))
7880 			goto change;
7881 		if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
7882 			goto change;
7883 		if (dl_policy(policy) && dl_param_changed(p, attr))
7884 			goto change;
7885 		if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)
7886 			goto change;
7887 
7888 		p->sched_reset_on_fork = reset_on_fork;
7889 		retval = 0;
7890 		goto unlock;
7891 	}
7892 change:
7893 
7894 	if (user) {
7895 #ifdef CONFIG_RT_GROUP_SCHED
7896 		/*
7897 		 * Do not allow realtime tasks into groups that have no runtime
7898 		 * assigned.
7899 		 */
7900 		if (rt_bandwidth_enabled() && rt_policy(policy) &&
7901 				task_group(p)->rt_bandwidth.rt_runtime == 0 &&
7902 				!task_group_is_autogroup(task_group(p))) {
7903 			retval = -EPERM;
7904 			goto unlock;
7905 		}
7906 #endif
7907 #ifdef CONFIG_SMP
7908 		if (dl_bandwidth_enabled() && dl_policy(policy) &&
7909 				!(attr->sched_flags & SCHED_FLAG_SUGOV)) {
7910 			cpumask_t *span = rq->rd->span;
7911 
7912 			/*
7913 			 * Don't allow tasks with an affinity mask smaller than
7914 			 * the entire root_domain to become SCHED_DEADLINE. We
7915 			 * will also fail if there's no bandwidth available.
7916 			 */
7917 			if (!cpumask_subset(span, p->cpus_ptr) ||
7918 			    rq->rd->dl_bw.bw == 0) {
7919 				retval = -EPERM;
7920 				goto unlock;
7921 			}
7922 		}
7923 #endif
7924 	}
7925 
7926 	/* Re-check policy now with rq lock held: */
7927 	if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
7928 		policy = oldpolicy = -1;
7929 		task_rq_unlock(rq, p, &rf);
7930 		if (cpuset_locked)
7931 			cpuset_unlock();
7932 		goto recheck;
7933 	}
7934 
7935 	/*
7936 	 * If setscheduling to SCHED_DEADLINE (or changing the parameters
7937 	 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
7938 	 * is available.
7939 	 */
7940 	if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
7941 		retval = -EBUSY;
7942 		goto unlock;
7943 	}
7944 
7945 	p->sched_reset_on_fork = reset_on_fork;
7946 	oldprio = p->prio;
7947 
7948 	newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice);
7949 	if (pi) {
7950 		/*
7951 		 * Take priority boosted tasks into account. If the new
7952 		 * effective priority is unchanged, we just store the new
7953 		 * normal parameters and do not touch the scheduler class and
7954 		 * the runqueue. This will be done when the task deboost
7955 		 * itself.
7956 		 */
7957 		newprio = rt_effective_prio(p, newprio);
7958 		if (newprio == oldprio)
7959 			queue_flags &= ~DEQUEUE_MOVE;
7960 	}
7961 
7962 	queued = task_on_rq_queued(p);
7963 	running = task_current(rq, p);
7964 	if (queued)
7965 		dequeue_task(rq, p, queue_flags);
7966 	if (running)
7967 		put_prev_task(rq, p);
7968 
7969 	prev_class = p->sched_class;
7970 
7971 	if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) {
7972 		__setscheduler_params(p, attr);
7973 		__setscheduler_prio(p, newprio);
7974 		trace_android_rvh_setscheduler(p);
7975 	}
7976 	__setscheduler_uclamp(p, attr);
7977 
7978 	if (queued) {
7979 		/*
7980 		 * We enqueue to tail when the priority of a task is
7981 		 * increased (user space view).
7982 		 */
7983 		if (oldprio < p->prio)
7984 			queue_flags |= ENQUEUE_HEAD;
7985 
7986 		enqueue_task(rq, p, queue_flags);
7987 	}
7988 	if (running)
7989 		set_next_task(rq, p);
7990 
7991 	check_class_changed(rq, p, prev_class, oldprio);
7992 
7993 	/* Avoid rq from going away on us: */
7994 	preempt_disable();
7995 	head = splice_balance_callbacks(rq);
7996 	task_rq_unlock(rq, p, &rf);
7997 
7998 	if (pi) {
7999 		if (cpuset_locked)
8000 			cpuset_unlock();
8001 		rt_mutex_adjust_pi(p);
8002 	}
8003 
8004 	/* Run balance callbacks after we've adjusted the PI chain: */
8005 	balance_callbacks(rq, head);
8006 	preempt_enable();
8007 
8008 	return 0;
8009 
8010 unlock:
8011 	task_rq_unlock(rq, p, &rf);
8012 	if (cpuset_locked)
8013 		cpuset_unlock();
8014 	return retval;
8015 }
8016 
_sched_setscheduler(struct task_struct * p,int policy,const struct sched_param * param,bool check)8017 static int _sched_setscheduler(struct task_struct *p, int policy,
8018 			       const struct sched_param *param, bool check)
8019 {
8020 	struct sched_attr attr = {
8021 		.sched_policy   = policy,
8022 		.sched_priority = param->sched_priority,
8023 		.sched_nice	= PRIO_TO_NICE(p->static_prio),
8024 	};
8025 
8026 	/* Fixup the legacy SCHED_RESET_ON_FORK hack. */
8027 	if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
8028 		attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
8029 		policy &= ~SCHED_RESET_ON_FORK;
8030 		attr.sched_policy = policy;
8031 	}
8032 
8033 	return __sched_setscheduler(p, &attr, check, true);
8034 }
8035 /**
8036  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
8037  * @p: the task in question.
8038  * @policy: new policy.
8039  * @param: structure containing the new RT priority.
8040  *
8041  * Use sched_set_fifo(), read its comment.
8042  *
8043  * Return: 0 on success. An error code otherwise.
8044  *
8045  * NOTE that the task may be already dead.
8046  */
sched_setscheduler(struct task_struct * p,int policy,const struct sched_param * param)8047 int sched_setscheduler(struct task_struct *p, int policy,
8048 		       const struct sched_param *param)
8049 {
8050 	return _sched_setscheduler(p, policy, param, true);
8051 }
8052 EXPORT_SYMBOL_GPL(sched_setscheduler);
8053 
sched_setattr(struct task_struct * p,const struct sched_attr * attr)8054 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
8055 {
8056 	return __sched_setscheduler(p, attr, true, true);
8057 }
8058 EXPORT_SYMBOL_GPL(sched_setattr);
8059 
sched_setattr_nocheck(struct task_struct * p,const struct sched_attr * attr)8060 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
8061 {
8062 	return __sched_setscheduler(p, attr, false, true);
8063 }
8064 EXPORT_SYMBOL_GPL(sched_setattr_nocheck);
8065 
8066 /**
8067  * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
8068  * @p: the task in question.
8069  * @policy: new policy.
8070  * @param: structure containing the new RT priority.
8071  *
8072  * Just like sched_setscheduler, only don't bother checking if the
8073  * current context has permission.  For example, this is needed in
8074  * stop_machine(): we create temporary high priority worker threads,
8075  * but our caller might not have that capability.
8076  *
8077  * Return: 0 on success. An error code otherwise.
8078  */
sched_setscheduler_nocheck(struct task_struct * p,int policy,const struct sched_param * param)8079 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
8080 			       const struct sched_param *param)
8081 {
8082 	return _sched_setscheduler(p, policy, param, false);
8083 }
8084 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
8085 
8086 /*
8087  * SCHED_FIFO is a broken scheduler model; that is, it is fundamentally
8088  * incapable of resource management, which is the one thing an OS really should
8089  * be doing.
8090  *
8091  * This is of course the reason it is limited to privileged users only.
8092  *
8093  * Worse still; it is fundamentally impossible to compose static priority
8094  * workloads. You cannot take two correctly working static prio workloads
8095  * and smash them together and still expect them to work.
8096  *
8097  * For this reason 'all' FIFO tasks the kernel creates are basically at:
8098  *
8099  *   MAX_RT_PRIO / 2
8100  *
8101  * The administrator _MUST_ configure the system, the kernel simply doesn't
8102  * know enough information to make a sensible choice.
8103  */
sched_set_fifo(struct task_struct * p)8104 void sched_set_fifo(struct task_struct *p)
8105 {
8106 	struct sched_param sp = { .sched_priority = MAX_RT_PRIO / 2 };
8107 	WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
8108 }
8109 EXPORT_SYMBOL_GPL(sched_set_fifo);
8110 
8111 /*
8112  * For when you don't much care about FIFO, but want to be above SCHED_NORMAL.
8113  */
sched_set_fifo_low(struct task_struct * p)8114 void sched_set_fifo_low(struct task_struct *p)
8115 {
8116 	struct sched_param sp = { .sched_priority = 1 };
8117 	WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
8118 }
8119 EXPORT_SYMBOL_GPL(sched_set_fifo_low);
8120 
sched_set_normal(struct task_struct * p,int nice)8121 void sched_set_normal(struct task_struct *p, int nice)
8122 {
8123 	struct sched_attr attr = {
8124 		.sched_policy = SCHED_NORMAL,
8125 		.sched_nice = nice,
8126 	};
8127 	WARN_ON_ONCE(sched_setattr_nocheck(p, &attr) != 0);
8128 }
8129 EXPORT_SYMBOL_GPL(sched_set_normal);
8130 
8131 static int
do_sched_setscheduler(pid_t pid,int policy,struct sched_param __user * param)8132 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
8133 {
8134 	struct sched_param lparam;
8135 	struct task_struct *p;
8136 	int retval;
8137 
8138 	if (!param || pid < 0)
8139 		return -EINVAL;
8140 	if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
8141 		return -EFAULT;
8142 
8143 	rcu_read_lock();
8144 	retval = -ESRCH;
8145 	p = find_process_by_pid(pid);
8146 	if (likely(p))
8147 		get_task_struct(p);
8148 	rcu_read_unlock();
8149 
8150 	if (likely(p)) {
8151 		retval = sched_setscheduler(p, policy, &lparam);
8152 		put_task_struct(p);
8153 	}
8154 
8155 	return retval;
8156 }
8157 
8158 /*
8159  * Mimics kernel/events/core.c perf_copy_attr().
8160  */
sched_copy_attr(struct sched_attr __user * uattr,struct sched_attr * attr)8161 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
8162 {
8163 	u32 size;
8164 	int ret;
8165 
8166 	/* Zero the full structure, so that a short copy will be nice: */
8167 	memset(attr, 0, sizeof(*attr));
8168 
8169 	ret = get_user(size, &uattr->size);
8170 	if (ret)
8171 		return ret;
8172 
8173 	/* ABI compatibility quirk: */
8174 	if (!size)
8175 		size = SCHED_ATTR_SIZE_VER0;
8176 	if (size < SCHED_ATTR_SIZE_VER0 || size > PAGE_SIZE)
8177 		goto err_size;
8178 
8179 	ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
8180 	if (ret) {
8181 		if (ret == -E2BIG)
8182 			goto err_size;
8183 		return ret;
8184 	}
8185 
8186 	if ((attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) &&
8187 	    size < SCHED_ATTR_SIZE_VER1)
8188 		return -EINVAL;
8189 
8190 	/*
8191 	 * XXX: Do we want to be lenient like existing syscalls; or do we want
8192 	 * to be strict and return an error on out-of-bounds values?
8193 	 */
8194 	attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
8195 
8196 	return 0;
8197 
8198 err_size:
8199 	put_user(sizeof(*attr), &uattr->size);
8200 	return -E2BIG;
8201 }
8202 
get_params(struct task_struct * p,struct sched_attr * attr)8203 static void get_params(struct task_struct *p, struct sched_attr *attr)
8204 {
8205 	if (task_has_dl_policy(p))
8206 		__getparam_dl(p, attr);
8207 	else if (task_has_rt_policy(p))
8208 		attr->sched_priority = p->rt_priority;
8209 	else
8210 		attr->sched_nice = task_nice(p);
8211 }
8212 
8213 /**
8214  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
8215  * @pid: the pid in question.
8216  * @policy: new policy.
8217  * @param: structure containing the new RT priority.
8218  *
8219  * Return: 0 on success. An error code otherwise.
8220  */
SYSCALL_DEFINE3(sched_setscheduler,pid_t,pid,int,policy,struct sched_param __user *,param)8221 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
8222 {
8223 	if (policy < 0)
8224 		return -EINVAL;
8225 
8226 	return do_sched_setscheduler(pid, policy, param);
8227 }
8228 
8229 /**
8230  * sys_sched_setparam - set/change the RT priority of a thread
8231  * @pid: the pid in question.
8232  * @param: structure containing the new RT priority.
8233  *
8234  * Return: 0 on success. An error code otherwise.
8235  */
SYSCALL_DEFINE2(sched_setparam,pid_t,pid,struct sched_param __user *,param)8236 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
8237 {
8238 	return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
8239 }
8240 
8241 /**
8242  * sys_sched_setattr - same as above, but with extended sched_attr
8243  * @pid: the pid in question.
8244  * @uattr: structure containing the extended parameters.
8245  * @flags: for future extension.
8246  */
SYSCALL_DEFINE3(sched_setattr,pid_t,pid,struct sched_attr __user *,uattr,unsigned int,flags)8247 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
8248 			       unsigned int, flags)
8249 {
8250 	struct sched_attr attr;
8251 	struct task_struct *p;
8252 	int retval;
8253 
8254 	if (!uattr || pid < 0 || flags)
8255 		return -EINVAL;
8256 
8257 	retval = sched_copy_attr(uattr, &attr);
8258 	if (retval)
8259 		return retval;
8260 
8261 	if ((int)attr.sched_policy < 0)
8262 		return -EINVAL;
8263 	if (attr.sched_flags & SCHED_FLAG_KEEP_POLICY)
8264 		attr.sched_policy = SETPARAM_POLICY;
8265 
8266 	rcu_read_lock();
8267 	retval = -ESRCH;
8268 	p = find_process_by_pid(pid);
8269 	if (likely(p))
8270 		get_task_struct(p);
8271 	rcu_read_unlock();
8272 
8273 	if (likely(p)) {
8274 		if (attr.sched_flags & SCHED_FLAG_KEEP_PARAMS)
8275 			get_params(p, &attr);
8276 		retval = sched_setattr(p, &attr);
8277 		put_task_struct(p);
8278 	}
8279 
8280 	return retval;
8281 }
8282 
8283 /**
8284  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
8285  * @pid: the pid in question.
8286  *
8287  * Return: On success, the policy of the thread. Otherwise, a negative error
8288  * code.
8289  */
SYSCALL_DEFINE1(sched_getscheduler,pid_t,pid)8290 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
8291 {
8292 	struct task_struct *p;
8293 	int retval;
8294 
8295 	if (pid < 0)
8296 		return -EINVAL;
8297 
8298 	retval = -ESRCH;
8299 	rcu_read_lock();
8300 	p = find_process_by_pid(pid);
8301 	if (p) {
8302 		retval = security_task_getscheduler(p);
8303 		if (!retval)
8304 			retval = p->policy
8305 				| (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
8306 	}
8307 	rcu_read_unlock();
8308 	return retval;
8309 }
8310 
8311 /**
8312  * sys_sched_getparam - get the RT priority of a thread
8313  * @pid: the pid in question.
8314  * @param: structure containing the RT priority.
8315  *
8316  * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
8317  * code.
8318  */
SYSCALL_DEFINE2(sched_getparam,pid_t,pid,struct sched_param __user *,param)8319 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
8320 {
8321 	struct sched_param lp = { .sched_priority = 0 };
8322 	struct task_struct *p;
8323 	int retval;
8324 
8325 	if (!param || pid < 0)
8326 		return -EINVAL;
8327 
8328 	rcu_read_lock();
8329 	p = find_process_by_pid(pid);
8330 	retval = -ESRCH;
8331 	if (!p)
8332 		goto out_unlock;
8333 
8334 	retval = security_task_getscheduler(p);
8335 	if (retval)
8336 		goto out_unlock;
8337 
8338 	if (task_has_rt_policy(p))
8339 		lp.sched_priority = p->rt_priority;
8340 	rcu_read_unlock();
8341 
8342 	/*
8343 	 * This one might sleep, we cannot do it with a spinlock held ...
8344 	 */
8345 	retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
8346 
8347 	return retval;
8348 
8349 out_unlock:
8350 	rcu_read_unlock();
8351 	return retval;
8352 }
8353 
8354 /*
8355  * Copy the kernel size attribute structure (which might be larger
8356  * than what user-space knows about) to user-space.
8357  *
8358  * Note that all cases are valid: user-space buffer can be larger or
8359  * smaller than the kernel-space buffer. The usual case is that both
8360  * have the same size.
8361  */
8362 static int
sched_attr_copy_to_user(struct sched_attr __user * uattr,struct sched_attr * kattr,unsigned int usize)8363 sched_attr_copy_to_user(struct sched_attr __user *uattr,
8364 			struct sched_attr *kattr,
8365 			unsigned int usize)
8366 {
8367 	unsigned int ksize = sizeof(*kattr);
8368 
8369 	if (!access_ok(uattr, usize))
8370 		return -EFAULT;
8371 
8372 	/*
8373 	 * sched_getattr() ABI forwards and backwards compatibility:
8374 	 *
8375 	 * If usize == ksize then we just copy everything to user-space and all is good.
8376 	 *
8377 	 * If usize < ksize then we only copy as much as user-space has space for,
8378 	 * this keeps ABI compatibility as well. We skip the rest.
8379 	 *
8380 	 * If usize > ksize then user-space is using a newer version of the ABI,
8381 	 * which part the kernel doesn't know about. Just ignore it - tooling can
8382 	 * detect the kernel's knowledge of attributes from the attr->size value
8383 	 * which is set to ksize in this case.
8384 	 */
8385 	kattr->size = min(usize, ksize);
8386 
8387 	if (copy_to_user(uattr, kattr, kattr->size))
8388 		return -EFAULT;
8389 
8390 	return 0;
8391 }
8392 
8393 /**
8394  * sys_sched_getattr - similar to sched_getparam, but with sched_attr
8395  * @pid: the pid in question.
8396  * @uattr: structure containing the extended parameters.
8397  * @usize: sizeof(attr) for fwd/bwd comp.
8398  * @flags: for future extension.
8399  */
SYSCALL_DEFINE4(sched_getattr,pid_t,pid,struct sched_attr __user *,uattr,unsigned int,usize,unsigned int,flags)8400 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
8401 		unsigned int, usize, unsigned int, flags)
8402 {
8403 	struct sched_attr kattr = { };
8404 	struct task_struct *p;
8405 	int retval;
8406 
8407 	if (!uattr || pid < 0 || usize > PAGE_SIZE ||
8408 	    usize < SCHED_ATTR_SIZE_VER0 || flags)
8409 		return -EINVAL;
8410 
8411 	rcu_read_lock();
8412 	p = find_process_by_pid(pid);
8413 	retval = -ESRCH;
8414 	if (!p)
8415 		goto out_unlock;
8416 
8417 	retval = security_task_getscheduler(p);
8418 	if (retval)
8419 		goto out_unlock;
8420 
8421 	kattr.sched_policy = p->policy;
8422 	if (p->sched_reset_on_fork)
8423 		kattr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
8424 	get_params(p, &kattr);
8425 	kattr.sched_flags &= SCHED_FLAG_ALL;
8426 
8427 #ifdef CONFIG_UCLAMP_TASK
8428 	/*
8429 	 * This could race with another potential updater, but this is fine
8430 	 * because it'll correctly read the old or the new value. We don't need
8431 	 * to guarantee who wins the race as long as it doesn't return garbage.
8432 	 */
8433 	kattr.sched_util_min = p->uclamp_req[UCLAMP_MIN].value;
8434 	kattr.sched_util_max = p->uclamp_req[UCLAMP_MAX].value;
8435 #endif
8436 
8437 	rcu_read_unlock();
8438 
8439 	return sched_attr_copy_to_user(uattr, &kattr, usize);
8440 
8441 out_unlock:
8442 	rcu_read_unlock();
8443 	return retval;
8444 }
8445 
8446 #ifdef CONFIG_SMP
dl_task_check_affinity(struct task_struct * p,const struct cpumask * mask)8447 int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
8448 {
8449 	int ret = 0;
8450 
8451 	/*
8452 	 * If the task isn't a deadline task or admission control is
8453 	 * disabled then we don't care about affinity changes.
8454 	 */
8455 	if (!task_has_dl_policy(p) || !dl_bandwidth_enabled())
8456 		return 0;
8457 
8458 	/*
8459 	 * Since bandwidth control happens on root_domain basis,
8460 	 * if admission test is enabled, we only admit -deadline
8461 	 * tasks allowed to run on all the CPUs in the task's
8462 	 * root_domain.
8463 	 */
8464 	rcu_read_lock();
8465 	if (!cpumask_subset(task_rq(p)->rd->span, mask))
8466 		ret = -EBUSY;
8467 	rcu_read_unlock();
8468 	return ret;
8469 }
8470 #endif
8471 
8472 static int
__sched_setaffinity(struct task_struct * p,struct affinity_context * ctx)8473 __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx)
8474 {
8475 	int retval;
8476 	cpumask_var_t cpus_allowed, new_mask;
8477 
8478 	if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL))
8479 		return -ENOMEM;
8480 
8481 	if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
8482 		retval = -ENOMEM;
8483 		goto out_free_cpus_allowed;
8484 	}
8485 
8486 	cpuset_cpus_allowed(p, cpus_allowed);
8487 	cpumask_and(new_mask, ctx->new_mask, cpus_allowed);
8488 
8489 	ctx->new_mask = new_mask;
8490 	ctx->flags |= SCA_CHECK;
8491 
8492 	retval = dl_task_check_affinity(p, new_mask);
8493 	if (retval)
8494 		goto out_free_new_mask;
8495 
8496 	retval = __set_cpus_allowed_ptr(p, ctx);
8497 	if (retval)
8498 		goto out_free_new_mask;
8499 
8500 	cpuset_cpus_allowed(p, cpus_allowed);
8501 	if (!cpumask_subset(new_mask, cpus_allowed)) {
8502 		/*
8503 		 * We must have raced with a concurrent cpuset update.
8504 		 * Just reset the cpumask to the cpuset's cpus_allowed.
8505 		 */
8506 		cpumask_copy(new_mask, cpus_allowed);
8507 
8508 		/*
8509 		 * If SCA_USER is set, a 2nd call to __set_cpus_allowed_ptr()
8510 		 * will restore the previous user_cpus_ptr value.
8511 		 *
8512 		 * In the unlikely event a previous user_cpus_ptr exists,
8513 		 * we need to further restrict the mask to what is allowed
8514 		 * by that old user_cpus_ptr.
8515 		 */
8516 		if (unlikely((ctx->flags & SCA_USER) && ctx->user_mask)) {
8517 			bool empty = !cpumask_and(new_mask, new_mask,
8518 						  ctx->user_mask);
8519 
8520 			if (WARN_ON_ONCE(empty))
8521 				cpumask_copy(new_mask, cpus_allowed);
8522 		}
8523 		__set_cpus_allowed_ptr(p, ctx);
8524 		retval = -EINVAL;
8525 	}
8526 
8527 out_free_new_mask:
8528 	free_cpumask_var(new_mask);
8529 out_free_cpus_allowed:
8530 	free_cpumask_var(cpus_allowed);
8531 	return retval;
8532 }
8533 
sched_setaffinity(pid_t pid,const struct cpumask * in_mask)8534 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
8535 {
8536 	struct affinity_context ac;
8537 	struct cpumask *user_mask;
8538 	struct task_struct *p;
8539 	int retval = 0;
8540 	bool skip = false;
8541 
8542 	rcu_read_lock();
8543 
8544 	p = find_process_by_pid(pid);
8545 	if (!p) {
8546 		rcu_read_unlock();
8547 		return -ESRCH;
8548 	}
8549 
8550 	/* Prevent p going away */
8551 	get_task_struct(p);
8552 	rcu_read_unlock();
8553 
8554 	if (p->flags & PF_NO_SETAFFINITY) {
8555 		retval = -EINVAL;
8556 		goto out_put_task;
8557 	}
8558 
8559 	if (!check_same_owner(p)) {
8560 		rcu_read_lock();
8561 		if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
8562 			rcu_read_unlock();
8563 			retval = -EPERM;
8564 			goto out_put_task;
8565 		}
8566 		rcu_read_unlock();
8567 	}
8568 
8569 	trace_android_vh_sched_setaffinity_early(p, in_mask, &skip);
8570 	if (skip)
8571 		goto out_put_task;
8572 	retval = security_task_setscheduler(p);
8573 	if (retval)
8574 		goto out_put_task;
8575 
8576 	/*
8577 	 * With non-SMP configs, user_cpus_ptr/user_mask isn't used and
8578 	 * alloc_user_cpus_ptr() returns NULL.
8579 	 */
8580 	user_mask = alloc_user_cpus_ptr(NUMA_NO_NODE);
8581 	if (user_mask) {
8582 		cpumask_copy(user_mask, in_mask);
8583 	} else if (IS_ENABLED(CONFIG_SMP)) {
8584 		retval = -ENOMEM;
8585 		goto out_put_task;
8586 	}
8587 
8588 	ac = (struct affinity_context){
8589 		.new_mask  = in_mask,
8590 		.user_mask = user_mask,
8591 		.flags     = SCA_USER,
8592 	};
8593 
8594 	retval = __sched_setaffinity(p, &ac);
8595 	trace_android_rvh_sched_setaffinity(p, in_mask, &retval);
8596 	kfree(ac.user_mask);
8597 
8598 out_put_task:
8599 	put_task_struct(p);
8600 	return retval;
8601 }
8602 
get_user_cpu_mask(unsigned long __user * user_mask_ptr,unsigned len,struct cpumask * new_mask)8603 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
8604 			     struct cpumask *new_mask)
8605 {
8606 	if (len < cpumask_size())
8607 		cpumask_clear(new_mask);
8608 	else if (len > cpumask_size())
8609 		len = cpumask_size();
8610 
8611 	return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
8612 }
8613 
8614 /**
8615  * sys_sched_setaffinity - set the CPU affinity of a process
8616  * @pid: pid of the process
8617  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
8618  * @user_mask_ptr: user-space pointer to the new CPU mask
8619  *
8620  * Return: 0 on success. An error code otherwise.
8621  */
SYSCALL_DEFINE3(sched_setaffinity,pid_t,pid,unsigned int,len,unsigned long __user *,user_mask_ptr)8622 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
8623 		unsigned long __user *, user_mask_ptr)
8624 {
8625 	cpumask_var_t new_mask;
8626 	int retval;
8627 
8628 	if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
8629 		return -ENOMEM;
8630 
8631 	retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
8632 	if (retval == 0)
8633 		retval = sched_setaffinity(pid, new_mask);
8634 	free_cpumask_var(new_mask);
8635 	return retval;
8636 }
8637 
sched_getaffinity(pid_t pid,struct cpumask * mask)8638 long sched_getaffinity(pid_t pid, struct cpumask *mask)
8639 {
8640 	struct task_struct *p;
8641 	unsigned long flags;
8642 	int retval;
8643 
8644 	rcu_read_lock();
8645 
8646 	retval = -ESRCH;
8647 	p = find_process_by_pid(pid);
8648 	if (!p)
8649 		goto out_unlock;
8650 
8651 	retval = security_task_getscheduler(p);
8652 	if (retval)
8653 		goto out_unlock;
8654 
8655 	raw_spin_lock_irqsave(&p->pi_lock, flags);
8656 	cpumask_and(mask, &p->cpus_mask, cpu_active_mask);
8657 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
8658 
8659 out_unlock:
8660 	rcu_read_unlock();
8661 
8662 	return retval;
8663 }
8664 
8665 /**
8666  * sys_sched_getaffinity - get the CPU affinity of a process
8667  * @pid: pid of the process
8668  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
8669  * @user_mask_ptr: user-space pointer to hold the current CPU mask
8670  *
8671  * Return: size of CPU mask copied to user_mask_ptr on success. An
8672  * error code otherwise.
8673  */
SYSCALL_DEFINE3(sched_getaffinity,pid_t,pid,unsigned int,len,unsigned long __user *,user_mask_ptr)8674 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
8675 		unsigned long __user *, user_mask_ptr)
8676 {
8677 	int ret;
8678 	cpumask_var_t mask;
8679 
8680 	if ((len * BITS_PER_BYTE) < nr_cpu_ids)
8681 		return -EINVAL;
8682 	if (len & (sizeof(unsigned long)-1))
8683 		return -EINVAL;
8684 
8685 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL))
8686 		return -ENOMEM;
8687 
8688 	ret = sched_getaffinity(pid, mask);
8689 	if (ret == 0) {
8690 		unsigned int retlen = min(len, cpumask_size());
8691 
8692 		if (copy_to_user(user_mask_ptr, cpumask_bits(mask), retlen))
8693 			ret = -EFAULT;
8694 		else
8695 			ret = retlen;
8696 	}
8697 	free_cpumask_var(mask);
8698 
8699 	return ret;
8700 }
8701 
do_sched_yield(void)8702 static void do_sched_yield(void)
8703 {
8704 	struct rq_flags rf;
8705 	struct rq *rq;
8706 	long skip = 0;
8707 
8708 	trace_android_rvh_before_do_sched_yield(&skip);
8709 	if (skip)
8710 		return;
8711 
8712 	rq = this_rq_lock_irq(&rf);
8713 
8714 	schedstat_inc(rq->yld_count);
8715 	current->sched_class->yield_task(rq);
8716 
8717 	trace_android_rvh_do_sched_yield(rq);
8718 
8719 	preempt_disable();
8720 	rq_unlock_irq(rq, &rf);
8721 	sched_preempt_enable_no_resched();
8722 
8723 	schedule();
8724 }
8725 
8726 /**
8727  * sys_sched_yield - yield the current processor to other threads.
8728  *
8729  * This function yields the current CPU to other tasks. If there are no
8730  * other threads running on this CPU then this function will return.
8731  *
8732  * Return: 0.
8733  */
SYSCALL_DEFINE0(sched_yield)8734 SYSCALL_DEFINE0(sched_yield)
8735 {
8736 	do_sched_yield();
8737 	return 0;
8738 }
8739 
8740 #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
__cond_resched(void)8741 int __sched __cond_resched(void)
8742 {
8743 	if (should_resched(0)) {
8744 		preempt_schedule_common();
8745 		return 1;
8746 	}
8747 	/*
8748 	 * In preemptible kernels, ->rcu_read_lock_nesting tells the tick
8749 	 * whether the current CPU is in an RCU read-side critical section,
8750 	 * so the tick can report quiescent states even for CPUs looping
8751 	 * in kernel context.  In contrast, in non-preemptible kernels,
8752 	 * RCU readers leave no in-memory hints, which means that CPU-bound
8753 	 * processes executing in kernel context might never report an
8754 	 * RCU quiescent state.  Therefore, the following code causes
8755 	 * cond_resched() to report a quiescent state, but only when RCU
8756 	 * is in urgent need of one.
8757 	 */
8758 #ifndef CONFIG_PREEMPT_RCU
8759 	rcu_all_qs();
8760 #endif
8761 	return 0;
8762 }
8763 EXPORT_SYMBOL(__cond_resched);
8764 #endif
8765 
8766 #ifdef CONFIG_PREEMPT_DYNAMIC
8767 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8768 #define cond_resched_dynamic_enabled	__cond_resched
8769 #define cond_resched_dynamic_disabled	((void *)&__static_call_return0)
8770 DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched);
8771 EXPORT_STATIC_CALL_TRAMP(cond_resched);
8772 
8773 #define might_resched_dynamic_enabled	__cond_resched
8774 #define might_resched_dynamic_disabled	((void *)&__static_call_return0)
8775 DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched);
8776 EXPORT_STATIC_CALL_TRAMP(might_resched);
8777 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
8778 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched);
dynamic_cond_resched(void)8779 int __sched dynamic_cond_resched(void)
8780 {
8781 	klp_sched_try_switch();
8782 	if (!static_branch_unlikely(&sk_dynamic_cond_resched))
8783 		return 0;
8784 	return __cond_resched();
8785 }
8786 EXPORT_SYMBOL(dynamic_cond_resched);
8787 
8788 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched);
dynamic_might_resched(void)8789 int __sched dynamic_might_resched(void)
8790 {
8791 	if (!static_branch_unlikely(&sk_dynamic_might_resched))
8792 		return 0;
8793 	return __cond_resched();
8794 }
8795 EXPORT_SYMBOL(dynamic_might_resched);
8796 #endif
8797 #endif
8798 
8799 /*
8800  * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
8801  * call schedule, and on return reacquire the lock.
8802  *
8803  * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
8804  * operations here to prevent schedule() from being called twice (once via
8805  * spin_unlock(), once by hand).
8806  */
__cond_resched_lock(spinlock_t * lock)8807 int __cond_resched_lock(spinlock_t *lock)
8808 {
8809 	int resched = should_resched(PREEMPT_LOCK_OFFSET);
8810 	int ret = 0;
8811 
8812 	lockdep_assert_held(lock);
8813 
8814 	if (spin_needbreak(lock) || resched) {
8815 		spin_unlock(lock);
8816 		if (!_cond_resched())
8817 			cpu_relax();
8818 		ret = 1;
8819 		spin_lock(lock);
8820 	}
8821 	return ret;
8822 }
8823 EXPORT_SYMBOL(__cond_resched_lock);
8824 
__cond_resched_rwlock_read(rwlock_t * lock)8825 int __cond_resched_rwlock_read(rwlock_t *lock)
8826 {
8827 	int resched = should_resched(PREEMPT_LOCK_OFFSET);
8828 	int ret = 0;
8829 
8830 	lockdep_assert_held_read(lock);
8831 
8832 	if (rwlock_needbreak(lock) || resched) {
8833 		read_unlock(lock);
8834 		if (!_cond_resched())
8835 			cpu_relax();
8836 		ret = 1;
8837 		read_lock(lock);
8838 	}
8839 	return ret;
8840 }
8841 EXPORT_SYMBOL(__cond_resched_rwlock_read);
8842 
__cond_resched_rwlock_write(rwlock_t * lock)8843 int __cond_resched_rwlock_write(rwlock_t *lock)
8844 {
8845 	int resched = should_resched(PREEMPT_LOCK_OFFSET);
8846 	int ret = 0;
8847 
8848 	lockdep_assert_held_write(lock);
8849 
8850 	if (rwlock_needbreak(lock) || resched) {
8851 		write_unlock(lock);
8852 		if (!_cond_resched())
8853 			cpu_relax();
8854 		ret = 1;
8855 		write_lock(lock);
8856 	}
8857 	return ret;
8858 }
8859 EXPORT_SYMBOL(__cond_resched_rwlock_write);
8860 
8861 #ifdef CONFIG_PREEMPT_DYNAMIC
8862 
8863 #ifdef CONFIG_GENERIC_ENTRY
8864 #include <linux/entry-common.h>
8865 #endif
8866 
8867 /*
8868  * SC:cond_resched
8869  * SC:might_resched
8870  * SC:preempt_schedule
8871  * SC:preempt_schedule_notrace
8872  * SC:irqentry_exit_cond_resched
8873  *
8874  *
8875  * NONE:
8876  *   cond_resched               <- __cond_resched
8877  *   might_resched              <- RET0
8878  *   preempt_schedule           <- NOP
8879  *   preempt_schedule_notrace   <- NOP
8880  *   irqentry_exit_cond_resched <- NOP
8881  *
8882  * VOLUNTARY:
8883  *   cond_resched               <- __cond_resched
8884  *   might_resched              <- __cond_resched
8885  *   preempt_schedule           <- NOP
8886  *   preempt_schedule_notrace   <- NOP
8887  *   irqentry_exit_cond_resched <- NOP
8888  *
8889  * FULL:
8890  *   cond_resched               <- RET0
8891  *   might_resched              <- RET0
8892  *   preempt_schedule           <- preempt_schedule
8893  *   preempt_schedule_notrace   <- preempt_schedule_notrace
8894  *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched
8895  */
8896 
8897 enum {
8898 	preempt_dynamic_undefined = -1,
8899 	preempt_dynamic_none,
8900 	preempt_dynamic_voluntary,
8901 	preempt_dynamic_full,
8902 };
8903 
8904 int preempt_dynamic_mode = preempt_dynamic_undefined;
8905 
sched_dynamic_mode(const char * str)8906 int sched_dynamic_mode(const char *str)
8907 {
8908 	if (!strcmp(str, "none"))
8909 		return preempt_dynamic_none;
8910 
8911 	if (!strcmp(str, "voluntary"))
8912 		return preempt_dynamic_voluntary;
8913 
8914 	if (!strcmp(str, "full"))
8915 		return preempt_dynamic_full;
8916 
8917 	return -EINVAL;
8918 }
8919 
8920 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8921 #define preempt_dynamic_enable(f)	static_call_update(f, f##_dynamic_enabled)
8922 #define preempt_dynamic_disable(f)	static_call_update(f, f##_dynamic_disabled)
8923 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
8924 #define preempt_dynamic_enable(f)	static_key_enable(&sk_dynamic_##f.key)
8925 #define preempt_dynamic_disable(f)	static_key_disable(&sk_dynamic_##f.key)
8926 #else
8927 #error "Unsupported PREEMPT_DYNAMIC mechanism"
8928 #endif
8929 
8930 static DEFINE_MUTEX(sched_dynamic_mutex);
8931 static bool klp_override;
8932 
__sched_dynamic_update(int mode)8933 static void __sched_dynamic_update(int mode)
8934 {
8935 	/*
8936 	 * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in
8937 	 * the ZERO state, which is invalid.
8938 	 */
8939 	if (!klp_override)
8940 		preempt_dynamic_enable(cond_resched);
8941 	preempt_dynamic_enable(might_resched);
8942 	preempt_dynamic_enable(preempt_schedule);
8943 	preempt_dynamic_enable(preempt_schedule_notrace);
8944 	preempt_dynamic_enable(irqentry_exit_cond_resched);
8945 
8946 	switch (mode) {
8947 	case preempt_dynamic_none:
8948 		if (!klp_override)
8949 			preempt_dynamic_enable(cond_resched);
8950 		preempt_dynamic_disable(might_resched);
8951 		preempt_dynamic_disable(preempt_schedule);
8952 		preempt_dynamic_disable(preempt_schedule_notrace);
8953 		preempt_dynamic_disable(irqentry_exit_cond_resched);
8954 		if (mode != preempt_dynamic_mode)
8955 			pr_info("Dynamic Preempt: none\n");
8956 		break;
8957 
8958 	case preempt_dynamic_voluntary:
8959 		if (!klp_override)
8960 			preempt_dynamic_enable(cond_resched);
8961 		preempt_dynamic_enable(might_resched);
8962 		preempt_dynamic_disable(preempt_schedule);
8963 		preempt_dynamic_disable(preempt_schedule_notrace);
8964 		preempt_dynamic_disable(irqentry_exit_cond_resched);
8965 		if (mode != preempt_dynamic_mode)
8966 			pr_info("Dynamic Preempt: voluntary\n");
8967 		break;
8968 
8969 	case preempt_dynamic_full:
8970 		if (!klp_override)
8971 			preempt_dynamic_disable(cond_resched);
8972 		preempt_dynamic_disable(might_resched);
8973 		preempt_dynamic_enable(preempt_schedule);
8974 		preempt_dynamic_enable(preempt_schedule_notrace);
8975 		preempt_dynamic_enable(irqentry_exit_cond_resched);
8976 		if (mode != preempt_dynamic_mode)
8977 			pr_info("Dynamic Preempt: full\n");
8978 		break;
8979 	}
8980 
8981 	preempt_dynamic_mode = mode;
8982 }
8983 
sched_dynamic_update(int mode)8984 void sched_dynamic_update(int mode)
8985 {
8986 	mutex_lock(&sched_dynamic_mutex);
8987 	__sched_dynamic_update(mode);
8988 	mutex_unlock(&sched_dynamic_mutex);
8989 }
8990 
8991 #ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL
8992 
klp_cond_resched(void)8993 static int klp_cond_resched(void)
8994 {
8995 	__klp_sched_try_switch();
8996 	return __cond_resched();
8997 }
8998 
sched_dynamic_klp_enable(void)8999 void sched_dynamic_klp_enable(void)
9000 {
9001 	mutex_lock(&sched_dynamic_mutex);
9002 
9003 	klp_override = true;
9004 	static_call_update(cond_resched, klp_cond_resched);
9005 
9006 	mutex_unlock(&sched_dynamic_mutex);
9007 }
9008 
sched_dynamic_klp_disable(void)9009 void sched_dynamic_klp_disable(void)
9010 {
9011 	mutex_lock(&sched_dynamic_mutex);
9012 
9013 	klp_override = false;
9014 	__sched_dynamic_update(preempt_dynamic_mode);
9015 
9016 	mutex_unlock(&sched_dynamic_mutex);
9017 }
9018 
9019 #endif /* CONFIG_HAVE_PREEMPT_DYNAMIC_CALL */
9020 
setup_preempt_mode(char * str)9021 static int __init setup_preempt_mode(char *str)
9022 {
9023 	int mode = sched_dynamic_mode(str);
9024 	if (mode < 0) {
9025 		pr_warn("Dynamic Preempt: unsupported mode: %s\n", str);
9026 		return 0;
9027 	}
9028 
9029 	sched_dynamic_update(mode);
9030 	return 1;
9031 }
9032 __setup("preempt=", setup_preempt_mode);
9033 
preempt_dynamic_init(void)9034 static void __init preempt_dynamic_init(void)
9035 {
9036 	if (preempt_dynamic_mode == preempt_dynamic_undefined) {
9037 		if (IS_ENABLED(CONFIG_PREEMPT_NONE)) {
9038 			sched_dynamic_update(preempt_dynamic_none);
9039 		} else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) {
9040 			sched_dynamic_update(preempt_dynamic_voluntary);
9041 		} else {
9042 			/* Default static call setting, nothing to do */
9043 			WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT));
9044 			preempt_dynamic_mode = preempt_dynamic_full;
9045 			pr_info("Dynamic Preempt: full\n");
9046 		}
9047 	}
9048 }
9049 
9050 #define PREEMPT_MODEL_ACCESSOR(mode) \
9051 	bool preempt_model_##mode(void)						 \
9052 	{									 \
9053 		WARN_ON_ONCE(preempt_dynamic_mode == preempt_dynamic_undefined); \
9054 		return preempt_dynamic_mode == preempt_dynamic_##mode;		 \
9055 	}									 \
9056 	EXPORT_SYMBOL_GPL(preempt_model_##mode)
9057 
9058 PREEMPT_MODEL_ACCESSOR(none);
9059 PREEMPT_MODEL_ACCESSOR(voluntary);
9060 PREEMPT_MODEL_ACCESSOR(full);
9061 
9062 #else /* !CONFIG_PREEMPT_DYNAMIC */
9063 
preempt_dynamic_init(void)9064 static inline void preempt_dynamic_init(void) { }
9065 
9066 #endif /* #ifdef CONFIG_PREEMPT_DYNAMIC */
9067 
9068 /**
9069  * yield - yield the current processor to other threads.
9070  *
9071  * Do not ever use this function, there's a 99% chance you're doing it wrong.
9072  *
9073  * The scheduler is at all times free to pick the calling task as the most
9074  * eligible task to run, if removing the yield() call from your code breaks
9075  * it, it's already broken.
9076  *
9077  * Typical broken usage is:
9078  *
9079  * while (!event)
9080  *	yield();
9081  *
9082  * where one assumes that yield() will let 'the other' process run that will
9083  * make event true. If the current task is a SCHED_FIFO task that will never
9084  * happen. Never use yield() as a progress guarantee!!
9085  *
9086  * If you want to use yield() to wait for something, use wait_event().
9087  * If you want to use yield() to be 'nice' for others, use cond_resched().
9088  * If you still want to use yield(), do not!
9089  */
yield(void)9090 void __sched yield(void)
9091 {
9092 	set_current_state(TASK_RUNNING);
9093 	do_sched_yield();
9094 }
9095 EXPORT_SYMBOL(yield);
9096 
9097 /**
9098  * yield_to - yield the current processor to another thread in
9099  * your thread group, or accelerate that thread toward the
9100  * processor it's on.
9101  * @p: target task
9102  * @preempt: whether task preemption is allowed or not
9103  *
9104  * It's the caller's job to ensure that the target task struct
9105  * can't go away on us before we can do any checks.
9106  *
9107  * Return:
9108  *	true (>0) if we indeed boosted the target task.
9109  *	false (0) if we failed to boost the target.
9110  *	-ESRCH if there's no task to yield to.
9111  */
yield_to(struct task_struct * p,bool preempt)9112 int __sched yield_to(struct task_struct *p, bool preempt)
9113 {
9114 	struct task_struct *curr = current;
9115 	struct rq *rq, *p_rq;
9116 	unsigned long flags;
9117 	int yielded = 0;
9118 
9119 	local_irq_save(flags);
9120 	rq = this_rq();
9121 
9122 again:
9123 	p_rq = task_rq(p);
9124 	/*
9125 	 * If we're the only runnable task on the rq and target rq also
9126 	 * has only one task, there's absolutely no point in yielding.
9127 	 */
9128 	if (rq->nr_running == 1 && p_rq->nr_running == 1) {
9129 		yielded = -ESRCH;
9130 		goto out_irq;
9131 	}
9132 
9133 	double_rq_lock(rq, p_rq);
9134 	if (task_rq(p) != p_rq) {
9135 		double_rq_unlock(rq, p_rq);
9136 		goto again;
9137 	}
9138 
9139 	if (!curr->sched_class->yield_to_task)
9140 		goto out_unlock;
9141 
9142 	if (curr->sched_class != p->sched_class)
9143 		goto out_unlock;
9144 
9145 	if (task_on_cpu(p_rq, p) || !task_is_running(p))
9146 		goto out_unlock;
9147 
9148 	yielded = curr->sched_class->yield_to_task(rq, p);
9149 	if (yielded) {
9150 		schedstat_inc(rq->yld_count);
9151 		/*
9152 		 * Make p's CPU reschedule; pick_next_entity takes care of
9153 		 * fairness.
9154 		 */
9155 		if (preempt && rq != p_rq)
9156 			resched_curr(p_rq);
9157 	}
9158 
9159 out_unlock:
9160 	double_rq_unlock(rq, p_rq);
9161 out_irq:
9162 	local_irq_restore(flags);
9163 
9164 	if (yielded > 0)
9165 		schedule();
9166 
9167 	return yielded;
9168 }
9169 EXPORT_SYMBOL_GPL(yield_to);
9170 
io_schedule_prepare(void)9171 int io_schedule_prepare(void)
9172 {
9173 	int old_iowait = current->in_iowait;
9174 
9175 	current->in_iowait = 1;
9176 	blk_flush_plug(current->plug, true);
9177 	return old_iowait;
9178 }
9179 
io_schedule_finish(int token)9180 void io_schedule_finish(int token)
9181 {
9182 	current->in_iowait = token;
9183 }
9184 
9185 /*
9186  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
9187  * that process accounting knows that this is a task in IO wait state.
9188  */
io_schedule_timeout(long timeout)9189 long __sched io_schedule_timeout(long timeout)
9190 {
9191 	int token;
9192 	long ret;
9193 
9194 	token = io_schedule_prepare();
9195 	ret = schedule_timeout(timeout);
9196 	io_schedule_finish(token);
9197 
9198 	return ret;
9199 }
9200 EXPORT_SYMBOL(io_schedule_timeout);
9201 
io_schedule(void)9202 void __sched io_schedule(void)
9203 {
9204 	int token;
9205 
9206 	token = io_schedule_prepare();
9207 	schedule();
9208 	io_schedule_finish(token);
9209 }
9210 EXPORT_SYMBOL(io_schedule);
9211 
9212 /**
9213  * sys_sched_get_priority_max - return maximum RT priority.
9214  * @policy: scheduling class.
9215  *
9216  * Return: On success, this syscall returns the maximum
9217  * rt_priority that can be used by a given scheduling class.
9218  * On failure, a negative error code is returned.
9219  */
SYSCALL_DEFINE1(sched_get_priority_max,int,policy)9220 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
9221 {
9222 	int ret = -EINVAL;
9223 
9224 	switch (policy) {
9225 	case SCHED_FIFO:
9226 	case SCHED_RR:
9227 		ret = MAX_RT_PRIO-1;
9228 		break;
9229 	case SCHED_DEADLINE:
9230 	case SCHED_NORMAL:
9231 	case SCHED_BATCH:
9232 	case SCHED_IDLE:
9233 		ret = 0;
9234 		break;
9235 	}
9236 	return ret;
9237 }
9238 
9239 /**
9240  * sys_sched_get_priority_min - return minimum RT priority.
9241  * @policy: scheduling class.
9242  *
9243  * Return: On success, this syscall returns the minimum
9244  * rt_priority that can be used by a given scheduling class.
9245  * On failure, a negative error code is returned.
9246  */
SYSCALL_DEFINE1(sched_get_priority_min,int,policy)9247 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
9248 {
9249 	int ret = -EINVAL;
9250 
9251 	switch (policy) {
9252 	case SCHED_FIFO:
9253 	case SCHED_RR:
9254 		ret = 1;
9255 		break;
9256 	case SCHED_DEADLINE:
9257 	case SCHED_NORMAL:
9258 	case SCHED_BATCH:
9259 	case SCHED_IDLE:
9260 		ret = 0;
9261 	}
9262 	return ret;
9263 }
9264 
sched_rr_get_interval(pid_t pid,struct timespec64 * t)9265 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
9266 {
9267 	struct task_struct *p;
9268 	unsigned int time_slice;
9269 	struct rq_flags rf;
9270 	struct rq *rq;
9271 	int retval;
9272 
9273 	if (pid < 0)
9274 		return -EINVAL;
9275 
9276 	retval = -ESRCH;
9277 	rcu_read_lock();
9278 	p = find_process_by_pid(pid);
9279 	if (!p)
9280 		goto out_unlock;
9281 
9282 	retval = security_task_getscheduler(p);
9283 	if (retval)
9284 		goto out_unlock;
9285 
9286 	rq = task_rq_lock(p, &rf);
9287 	time_slice = 0;
9288 	if (p->sched_class->get_rr_interval)
9289 		time_slice = p->sched_class->get_rr_interval(rq, p);
9290 	task_rq_unlock(rq, p, &rf);
9291 
9292 	rcu_read_unlock();
9293 	jiffies_to_timespec64(time_slice, t);
9294 	return 0;
9295 
9296 out_unlock:
9297 	rcu_read_unlock();
9298 	return retval;
9299 }
9300 
9301 /**
9302  * sys_sched_rr_get_interval - return the default timeslice of a process.
9303  * @pid: pid of the process.
9304  * @interval: userspace pointer to the timeslice value.
9305  *
9306  * this syscall writes the default timeslice value of a given process
9307  * into the user-space timespec buffer. A value of '0' means infinity.
9308  *
9309  * Return: On success, 0 and the timeslice is in @interval. Otherwise,
9310  * an error code.
9311  */
SYSCALL_DEFINE2(sched_rr_get_interval,pid_t,pid,struct __kernel_timespec __user *,interval)9312 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
9313 		struct __kernel_timespec __user *, interval)
9314 {
9315 	struct timespec64 t;
9316 	int retval = sched_rr_get_interval(pid, &t);
9317 
9318 	if (retval == 0)
9319 		retval = put_timespec64(&t, interval);
9320 
9321 	return retval;
9322 }
9323 
9324 #ifdef CONFIG_COMPAT_32BIT_TIME
SYSCALL_DEFINE2(sched_rr_get_interval_time32,pid_t,pid,struct old_timespec32 __user *,interval)9325 SYSCALL_DEFINE2(sched_rr_get_interval_time32, pid_t, pid,
9326 		struct old_timespec32 __user *, interval)
9327 {
9328 	struct timespec64 t;
9329 	int retval = sched_rr_get_interval(pid, &t);
9330 
9331 	if (retval == 0)
9332 		retval = put_old_timespec32(&t, interval);
9333 	return retval;
9334 }
9335 #endif
9336 
sched_show_task(struct task_struct * p)9337 void sched_show_task(struct task_struct *p)
9338 {
9339 	unsigned long free = 0;
9340 	int ppid;
9341 
9342 	if (!try_get_task_stack(p))
9343 		return;
9344 
9345 	pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
9346 
9347 	if (task_is_running(p))
9348 		pr_cont("  running task    ");
9349 #ifdef CONFIG_DEBUG_STACK_USAGE
9350 	free = stack_not_used(p);
9351 #endif
9352 	ppid = 0;
9353 	rcu_read_lock();
9354 	if (pid_alive(p))
9355 		ppid = task_pid_nr(rcu_dereference(p->real_parent));
9356 	rcu_read_unlock();
9357 	pr_cont(" stack:%-5lu pid:%-5d ppid:%-6d flags:0x%08lx\n",
9358 		free, task_pid_nr(p), ppid,
9359 		read_task_thread_flags(p));
9360 
9361 	print_worker_info(KERN_INFO, p);
9362 	print_stop_info(KERN_INFO, p);
9363 	trace_android_vh_sched_show_task(p);
9364 	show_stack(p, NULL, KERN_INFO);
9365 	put_task_stack(p);
9366 }
9367 EXPORT_SYMBOL_GPL(sched_show_task);
9368 
9369 static inline bool
state_filter_match(unsigned long state_filter,struct task_struct * p)9370 state_filter_match(unsigned long state_filter, struct task_struct *p)
9371 {
9372 	unsigned int state = READ_ONCE(p->__state);
9373 
9374 	/* no filter, everything matches */
9375 	if (!state_filter)
9376 		return true;
9377 
9378 	/* filter, but doesn't match */
9379 	if (!(state & state_filter))
9380 		return false;
9381 
9382 	/*
9383 	 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
9384 	 * TASK_KILLABLE).
9385 	 */
9386 	if (state_filter == TASK_UNINTERRUPTIBLE && (state & TASK_NOLOAD))
9387 		return false;
9388 
9389 	return true;
9390 }
9391 
9392 
show_state_filter(unsigned int state_filter)9393 void show_state_filter(unsigned int state_filter)
9394 {
9395 	struct task_struct *g, *p;
9396 
9397 	rcu_read_lock();
9398 	for_each_process_thread(g, p) {
9399 		/*
9400 		 * reset the NMI-timeout, listing all files on a slow
9401 		 * console might take a lot of time:
9402 		 * Also, reset softlockup watchdogs on all CPUs, because
9403 		 * another CPU might be blocked waiting for us to process
9404 		 * an IPI.
9405 		 */
9406 		touch_nmi_watchdog();
9407 		touch_all_softlockup_watchdogs();
9408 		if (state_filter_match(state_filter, p))
9409 			sched_show_task(p);
9410 	}
9411 
9412 #ifdef CONFIG_SCHED_DEBUG
9413 	if (!state_filter)
9414 		sysrq_sched_debug_show();
9415 #endif
9416 	rcu_read_unlock();
9417 	/*
9418 	 * Only show locks if all tasks are dumped:
9419 	 */
9420 	if (!state_filter)
9421 		debug_show_all_locks();
9422 }
9423 
9424 /**
9425  * init_idle - set up an idle thread for a given CPU
9426  * @idle: task in question
9427  * @cpu: CPU the idle task belongs to
9428  *
9429  * NOTE: this function does not set the idle thread's NEED_RESCHED
9430  * flag, to make booting more robust.
9431  */
init_idle(struct task_struct * idle,int cpu)9432 void __init init_idle(struct task_struct *idle, int cpu)
9433 {
9434 #ifdef CONFIG_SMP
9435 	struct affinity_context ac = (struct affinity_context) {
9436 		.new_mask  = cpumask_of(cpu),
9437 		.flags     = 0,
9438 	};
9439 #endif
9440 	struct rq *rq = cpu_rq(cpu);
9441 	unsigned long flags;
9442 
9443 	__sched_fork(0, idle);
9444 
9445 	raw_spin_lock_irqsave(&idle->pi_lock, flags);
9446 	raw_spin_rq_lock(rq);
9447 
9448 	idle->__state = TASK_RUNNING;
9449 	idle->se.exec_start = sched_clock();
9450 	/*
9451 	 * PF_KTHREAD should already be set at this point; regardless, make it
9452 	 * look like a proper per-CPU kthread.
9453 	 */
9454 	idle->flags |= PF_KTHREAD | PF_NO_SETAFFINITY;
9455 	kthread_set_per_cpu(idle, cpu);
9456 
9457 #ifdef CONFIG_SMP
9458 	/*
9459 	 * It's possible that init_idle() gets called multiple times on a task,
9460 	 * in that case do_set_cpus_allowed() will not do the right thing.
9461 	 *
9462 	 * And since this is boot we can forgo the serialization.
9463 	 */
9464 	set_cpus_allowed_common(idle, &ac);
9465 #endif
9466 	/*
9467 	 * We're having a chicken and egg problem, even though we are
9468 	 * holding rq->lock, the CPU isn't yet set to this CPU so the
9469 	 * lockdep check in task_group() will fail.
9470 	 *
9471 	 * Similar case to sched_fork(). / Alternatively we could
9472 	 * use task_rq_lock() here and obtain the other rq->lock.
9473 	 *
9474 	 * Silence PROVE_RCU
9475 	 */
9476 	rcu_read_lock();
9477 	__set_task_cpu(idle, cpu);
9478 	rcu_read_unlock();
9479 
9480 	rq->idle = idle;
9481 	rcu_assign_pointer(rq->curr, idle);
9482 	idle->on_rq = TASK_ON_RQ_QUEUED;
9483 #ifdef CONFIG_SMP
9484 	idle->on_cpu = 1;
9485 #endif
9486 	raw_spin_rq_unlock(rq);
9487 	raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
9488 
9489 	/* Set the preempt count _outside_ the spinlocks! */
9490 	init_idle_preempt_count(idle, cpu);
9491 
9492 	/*
9493 	 * The idle tasks have their own, simple scheduling class:
9494 	 */
9495 	idle->sched_class = &idle_sched_class;
9496 	ftrace_graph_init_idle_task(idle, cpu);
9497 	vtime_init_idle(idle, cpu);
9498 #ifdef CONFIG_SMP
9499 	sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
9500 #endif
9501 }
9502 
9503 #ifdef CONFIG_SMP
9504 
cpuset_cpumask_can_shrink(const struct cpumask * cur,const struct cpumask * trial)9505 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
9506 			      const struct cpumask *trial)
9507 {
9508 	int ret = 1;
9509 
9510 	if (cpumask_empty(cur))
9511 		return ret;
9512 
9513 	ret = dl_cpuset_cpumask_can_shrink(cur, trial);
9514 
9515 	return ret;
9516 }
9517 
task_can_attach(struct task_struct * p)9518 int task_can_attach(struct task_struct *p)
9519 {
9520 	int ret = 0;
9521 
9522 	/*
9523 	 * Kthreads which disallow setaffinity shouldn't be moved
9524 	 * to a new cpuset; we don't want to change their CPU
9525 	 * affinity and isolating such threads by their set of
9526 	 * allowed nodes is unnecessary.  Thus, cpusets are not
9527 	 * applicable for such threads.  This prevents checking for
9528 	 * success of set_cpus_allowed_ptr() on all attached tasks
9529 	 * before cpus_mask may be changed.
9530 	 */
9531 	if (p->flags & PF_NO_SETAFFINITY)
9532 		ret = -EINVAL;
9533 
9534 	return ret;
9535 }
9536 
9537 bool sched_smp_initialized __read_mostly;
9538 
9539 #ifdef CONFIG_NUMA_BALANCING
9540 /* Migrate current task p to target_cpu */
migrate_task_to(struct task_struct * p,int target_cpu)9541 int migrate_task_to(struct task_struct *p, int target_cpu)
9542 {
9543 	struct migration_arg arg = { p, target_cpu };
9544 	int curr_cpu = task_cpu(p);
9545 
9546 	if (curr_cpu == target_cpu)
9547 		return 0;
9548 
9549 	if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
9550 		return -EINVAL;
9551 
9552 	/* TODO: This is not properly updating schedstats */
9553 
9554 	trace_sched_move_numa(p, curr_cpu, target_cpu);
9555 	return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
9556 }
9557 
9558 /*
9559  * Requeue a task on a given node and accurately track the number of NUMA
9560  * tasks on the runqueues
9561  */
sched_setnuma(struct task_struct * p,int nid)9562 void sched_setnuma(struct task_struct *p, int nid)
9563 {
9564 	bool queued, running;
9565 	struct rq_flags rf;
9566 	struct rq *rq;
9567 
9568 	rq = task_rq_lock(p, &rf);
9569 	queued = task_on_rq_queued(p);
9570 	running = task_current(rq, p);
9571 
9572 	if (queued)
9573 		dequeue_task(rq, p, DEQUEUE_SAVE);
9574 	if (running)
9575 		put_prev_task(rq, p);
9576 
9577 	p->numa_preferred_nid = nid;
9578 
9579 	if (queued)
9580 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
9581 	if (running)
9582 		set_next_task(rq, p);
9583 	task_rq_unlock(rq, p, &rf);
9584 }
9585 #endif /* CONFIG_NUMA_BALANCING */
9586 
9587 #ifdef CONFIG_HOTPLUG_CPU
9588 /*
9589  * Ensure that the idle task is using init_mm right before its CPU goes
9590  * offline.
9591  */
idle_task_exit(void)9592 void idle_task_exit(void)
9593 {
9594 	struct mm_struct *mm = current->active_mm;
9595 
9596 	BUG_ON(cpu_online(smp_processor_id()));
9597 	BUG_ON(current != this_rq()->idle);
9598 
9599 	if (mm != &init_mm) {
9600 		switch_mm(mm, &init_mm, current);
9601 		finish_arch_post_lock_switch();
9602 	}
9603 
9604 	/* finish_cpu(), as ran on the BP, will clean up the active_mm state */
9605 }
9606 
pick_migrate_task(struct rq * rq)9607 struct task_struct *pick_migrate_task(struct rq *rq)
9608 {
9609 	const struct sched_class *class;
9610 	struct task_struct *next;
9611 
9612 	for_each_class(class) {
9613 		next = class->pick_next_task(rq);
9614 		if (next) {
9615 			next->sched_class->put_prev_task(rq, next);
9616 			return next;
9617 		}
9618 	}
9619 
9620 	/* The idle class should always have a runnable task */
9621 	BUG();
9622 }
9623 EXPORT_SYMBOL_GPL(pick_migrate_task);
9624 
__balance_push_cpu_stop(void * arg)9625 static int __balance_push_cpu_stop(void *arg)
9626 {
9627 	struct task_struct *p = arg;
9628 	struct rq *rq = this_rq();
9629 	struct rq_flags rf;
9630 	int cpu;
9631 
9632 	raw_spin_lock_irq(&p->pi_lock);
9633 	rq_lock(rq, &rf);
9634 
9635 	update_rq_clock(rq);
9636 
9637 	if (task_rq(p) == rq && task_on_rq_queued(p)) {
9638 		cpu = select_fallback_rq(rq->cpu, p);
9639 		rq = __migrate_task(rq, &rf, p, cpu);
9640 	}
9641 
9642 	rq_unlock(rq, &rf);
9643 	raw_spin_unlock_irq(&p->pi_lock);
9644 
9645 	put_task_struct(p);
9646 
9647 	return 0;
9648 }
9649 
9650 static DEFINE_PER_CPU(struct cpu_stop_work, push_work);
9651 
9652 /*
9653  * Ensure we only run per-cpu kthreads once the CPU goes !active.
9654  *
9655  * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only
9656  * effective when the hotplug motion is down.
9657  */
balance_push(struct rq * rq)9658 static void balance_push(struct rq *rq)
9659 {
9660 	struct task_struct *push_task = rq->curr;
9661 
9662 	lockdep_assert_rq_held(rq);
9663 
9664 	/*
9665 	 * Ensure the thing is persistent until balance_push_set(.on = false);
9666 	 */
9667 	rq->balance_callback = &balance_push_callback;
9668 
9669 	/*
9670 	 * Only active while going offline and when invoked on the outgoing
9671 	 * CPU.
9672 	 */
9673 	if (!cpu_dying(rq->cpu) || rq != this_rq())
9674 		return;
9675 
9676 	/*
9677 	 * Both the cpu-hotplug and stop task are in this case and are
9678 	 * required to complete the hotplug process.
9679 	 */
9680 	if (kthread_is_per_cpu(push_task) ||
9681 	    is_migration_disabled(push_task)) {
9682 
9683 		/*
9684 		 * If this is the idle task on the outgoing CPU try to wake
9685 		 * up the hotplug control thread which might wait for the
9686 		 * last task to vanish. The rcuwait_active() check is
9687 		 * accurate here because the waiter is pinned on this CPU
9688 		 * and can't obviously be running in parallel.
9689 		 *
9690 		 * On RT kernels this also has to check whether there are
9691 		 * pinned and scheduled out tasks on the runqueue. They
9692 		 * need to leave the migrate disabled section first.
9693 		 */
9694 		if (!rq->nr_running && !rq_has_pinned_tasks(rq) &&
9695 		    rcuwait_active(&rq->hotplug_wait)) {
9696 			raw_spin_rq_unlock(rq);
9697 			rcuwait_wake_up(&rq->hotplug_wait);
9698 			raw_spin_rq_lock(rq);
9699 		}
9700 		return;
9701 	}
9702 
9703 	get_task_struct(push_task);
9704 	/*
9705 	 * Temporarily drop rq->lock such that we can wake-up the stop task.
9706 	 * Both preemption and IRQs are still disabled.
9707 	 */
9708 	preempt_disable();
9709 	raw_spin_rq_unlock(rq);
9710 	stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task,
9711 			    this_cpu_ptr(&push_work));
9712 	preempt_enable();
9713 	/*
9714 	 * At this point need_resched() is true and we'll take the loop in
9715 	 * schedule(). The next pick is obviously going to be the stop task
9716 	 * which kthread_is_per_cpu() and will push this task away.
9717 	 */
9718 	raw_spin_rq_lock(rq);
9719 }
9720 
balance_push_set(int cpu,bool on)9721 static void balance_push_set(int cpu, bool on)
9722 {
9723 	struct rq *rq = cpu_rq(cpu);
9724 	struct rq_flags rf;
9725 
9726 	rq_lock_irqsave(rq, &rf);
9727 	if (on) {
9728 		WARN_ON_ONCE(rq->balance_callback);
9729 		rq->balance_callback = &balance_push_callback;
9730 	} else if (rq->balance_callback == &balance_push_callback) {
9731 		rq->balance_callback = NULL;
9732 	}
9733 	rq_unlock_irqrestore(rq, &rf);
9734 }
9735 
9736 /*
9737  * Invoked from a CPUs hotplug control thread after the CPU has been marked
9738  * inactive. All tasks which are not per CPU kernel threads are either
9739  * pushed off this CPU now via balance_push() or placed on a different CPU
9740  * during wakeup. Wait until the CPU is quiescent.
9741  */
balance_hotplug_wait(void)9742 static void balance_hotplug_wait(void)
9743 {
9744 	struct rq *rq = this_rq();
9745 
9746 	rcuwait_wait_event(&rq->hotplug_wait,
9747 			   rq->nr_running == 1 && !rq_has_pinned_tasks(rq),
9748 			   TASK_UNINTERRUPTIBLE);
9749 }
9750 
9751 #else
9752 
balance_push(struct rq * rq)9753 static inline void balance_push(struct rq *rq)
9754 {
9755 }
9756 
balance_push_set(int cpu,bool on)9757 static inline void balance_push_set(int cpu, bool on)
9758 {
9759 }
9760 
balance_hotplug_wait(void)9761 static inline void balance_hotplug_wait(void)
9762 {
9763 }
9764 
9765 #endif /* CONFIG_HOTPLUG_CPU */
9766 
set_rq_online(struct rq * rq)9767 void set_rq_online(struct rq *rq)
9768 {
9769 	if (!rq->online) {
9770 		const struct sched_class *class;
9771 
9772 		cpumask_set_cpu(rq->cpu, rq->rd->online);
9773 		rq->online = 1;
9774 
9775 		for_each_class(class) {
9776 			if (class->rq_online)
9777 				class->rq_online(rq);
9778 		}
9779 	}
9780 }
9781 
set_rq_offline(struct rq * rq)9782 void set_rq_offline(struct rq *rq)
9783 {
9784 	if (rq->online) {
9785 		const struct sched_class *class;
9786 
9787 		update_rq_clock(rq);
9788 		for_each_class(class) {
9789 			if (class->rq_offline)
9790 				class->rq_offline(rq);
9791 		}
9792 
9793 		cpumask_clear_cpu(rq->cpu, rq->rd->online);
9794 		rq->online = 0;
9795 	}
9796 }
9797 
sched_set_rq_online(struct rq * rq,int cpu)9798 static inline void sched_set_rq_online(struct rq *rq, int cpu)
9799 {
9800 	struct rq_flags rf;
9801 
9802 	rq_lock_irqsave(rq, &rf);
9803 	if (rq->rd) {
9804 		BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
9805 		set_rq_online(rq);
9806 	}
9807 	rq_unlock_irqrestore(rq, &rf);
9808 }
9809 
sched_set_rq_offline(struct rq * rq,int cpu)9810 static inline void sched_set_rq_offline(struct rq *rq, int cpu)
9811 {
9812 	struct rq_flags rf;
9813 
9814 	rq_lock_irqsave(rq, &rf);
9815 	if (rq->rd) {
9816 		BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
9817 		set_rq_offline(rq);
9818 	}
9819 	rq_unlock_irqrestore(rq, &rf);
9820 }
9821 
9822 /*
9823  * used to mark begin/end of suspend/resume:
9824  */
9825 static int num_cpus_frozen;
9826 
9827 /*
9828  * Update cpusets according to cpu_active mask.  If cpusets are
9829  * disabled, cpuset_update_active_cpus() becomes a simple wrapper
9830  * around partition_sched_domains().
9831  *
9832  * If we come here as part of a suspend/resume, don't touch cpusets because we
9833  * want to restore it back to its original state upon resume anyway.
9834  */
cpuset_cpu_active(void)9835 static void cpuset_cpu_active(void)
9836 {
9837 	if (cpuhp_tasks_frozen) {
9838 		/*
9839 		 * num_cpus_frozen tracks how many CPUs are involved in suspend
9840 		 * resume sequence. As long as this is not the last online
9841 		 * operation in the resume sequence, just build a single sched
9842 		 * domain, ignoring cpusets.
9843 		 */
9844 		partition_sched_domains(1, NULL, NULL);
9845 		if (--num_cpus_frozen)
9846 			return;
9847 		/*
9848 		 * This is the last CPU online operation. So fall through and
9849 		 * restore the original sched domains by considering the
9850 		 * cpuset configurations.
9851 		 */
9852 		cpuset_force_rebuild();
9853 	}
9854 	cpuset_update_active_cpus();
9855 }
9856 
cpuset_cpu_inactive(unsigned int cpu)9857 static int cpuset_cpu_inactive(unsigned int cpu)
9858 {
9859 	if (!cpuhp_tasks_frozen) {
9860 		int ret = dl_bw_check_overflow(cpu);
9861 
9862 		if (ret)
9863 			return ret;
9864 		cpuset_update_active_cpus();
9865 	} else {
9866 		num_cpus_frozen++;
9867 		partition_sched_domains(1, NULL, NULL);
9868 	}
9869 	return 0;
9870 }
9871 
sched_smt_present_inc(int cpu)9872 static inline void sched_smt_present_inc(int cpu)
9873 {
9874 #ifdef CONFIG_SCHED_SMT
9875 	if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
9876 		static_branch_inc_cpuslocked(&sched_smt_present);
9877 #endif
9878 }
9879 
sched_smt_present_dec(int cpu)9880 static inline void sched_smt_present_dec(int cpu)
9881 {
9882 #ifdef CONFIG_SCHED_SMT
9883 	if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
9884 		static_branch_dec_cpuslocked(&sched_smt_present);
9885 #endif
9886 }
9887 
sched_cpu_activate(unsigned int cpu)9888 int sched_cpu_activate(unsigned int cpu)
9889 {
9890 	struct rq *rq = cpu_rq(cpu);
9891 
9892 	/*
9893 	 * Clear the balance_push callback and prepare to schedule
9894 	 * regular tasks.
9895 	 */
9896 	balance_push_set(cpu, false);
9897 
9898 	/*
9899 	 * When going up, increment the number of cores with SMT present.
9900 	 */
9901 	sched_smt_present_inc(cpu);
9902 	set_cpu_active(cpu, true);
9903 
9904 	if (sched_smp_initialized) {
9905 		sched_update_numa(cpu, true);
9906 		sched_domains_numa_masks_set(cpu);
9907 		cpuset_cpu_active();
9908 	}
9909 
9910 	/*
9911 	 * Put the rq online, if not already. This happens:
9912 	 *
9913 	 * 1) In the early boot process, because we build the real domains
9914 	 *    after all CPUs have been brought up.
9915 	 *
9916 	 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
9917 	 *    domains.
9918 	 */
9919 	sched_set_rq_online(rq, cpu);
9920 
9921 	return 0;
9922 }
9923 
sched_cpu_deactivate(unsigned int cpu)9924 int sched_cpu_deactivate(unsigned int cpu)
9925 {
9926 	struct rq *rq = cpu_rq(cpu);
9927 	int ret;
9928 
9929 	/*
9930 	 * Remove CPU from nohz.idle_cpus_mask to prevent participating in
9931 	 * load balancing when not active
9932 	 */
9933 	nohz_balance_exit_idle(rq);
9934 
9935 	set_cpu_active(cpu, false);
9936 
9937 	/*
9938 	 * From this point forward, this CPU will refuse to run any task that
9939 	 * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively
9940 	 * push those tasks away until this gets cleared, see
9941 	 * sched_cpu_dying().
9942 	 */
9943 	balance_push_set(cpu, true);
9944 
9945 	/*
9946 	 * We've cleared cpu_active_mask / set balance_push, wait for all
9947 	 * preempt-disabled and RCU users of this state to go away such that
9948 	 * all new such users will observe it.
9949 	 *
9950 	 * Specifically, we rely on ttwu to no longer target this CPU, see
9951 	 * ttwu_queue_cond() and is_cpu_allowed().
9952 	 *
9953 	 * Do sync before park smpboot threads to take care the rcu boost case.
9954 	 */
9955 	synchronize_rcu();
9956 
9957 	sched_set_rq_offline(rq, cpu);
9958 
9959 	/*
9960 	 * When going down, decrement the number of cores with SMT present.
9961 	 */
9962 	sched_smt_present_dec(cpu);
9963 
9964 #ifdef CONFIG_SCHED_SMT
9965 	sched_core_cpu_deactivate(cpu);
9966 #endif
9967 
9968 	if (!sched_smp_initialized)
9969 		return 0;
9970 
9971 	sched_update_numa(cpu, false);
9972 	ret = cpuset_cpu_inactive(cpu);
9973 	if (ret) {
9974 		sched_smt_present_inc(cpu);
9975 		sched_set_rq_online(rq, cpu);
9976 		balance_push_set(cpu, false);
9977 		set_cpu_active(cpu, true);
9978 		sched_update_numa(cpu, true);
9979 		return ret;
9980 	}
9981 	sched_domains_numa_masks_clear(cpu);
9982 	return 0;
9983 }
9984 
sched_rq_cpu_starting(unsigned int cpu)9985 static void sched_rq_cpu_starting(unsigned int cpu)
9986 {
9987 	struct rq *rq = cpu_rq(cpu);
9988 
9989 	rq->calc_load_update = calc_load_update;
9990 	update_max_interval();
9991 }
9992 
sched_cpu_starting(unsigned int cpu)9993 int sched_cpu_starting(unsigned int cpu)
9994 {
9995 	sched_core_cpu_starting(cpu);
9996 	sched_rq_cpu_starting(cpu);
9997 	sched_tick_start(cpu);
9998 	trace_android_rvh_sched_cpu_starting(cpu);
9999 	return 0;
10000 }
10001 
10002 #ifdef CONFIG_HOTPLUG_CPU
10003 
10004 /*
10005  * Invoked immediately before the stopper thread is invoked to bring the
10006  * CPU down completely. At this point all per CPU kthreads except the
10007  * hotplug thread (current) and the stopper thread (inactive) have been
10008  * either parked or have been unbound from the outgoing CPU. Ensure that
10009  * any of those which might be on the way out are gone.
10010  *
10011  * If after this point a bound task is being woken on this CPU then the
10012  * responsible hotplug callback has failed to do it's job.
10013  * sched_cpu_dying() will catch it with the appropriate fireworks.
10014  */
sched_cpu_wait_empty(unsigned int cpu)10015 int sched_cpu_wait_empty(unsigned int cpu)
10016 {
10017 	balance_hotplug_wait();
10018 	return 0;
10019 }
10020 
10021 /*
10022  * Since this CPU is going 'away' for a while, fold any nr_active delta we
10023  * might have. Called from the CPU stopper task after ensuring that the
10024  * stopper is the last running task on the CPU, so nr_active count is
10025  * stable. We need to take the teardown thread which is calling this into
10026  * account, so we hand in adjust = 1 to the load calculation.
10027  *
10028  * Also see the comment "Global load-average calculations".
10029  */
calc_load_migrate(struct rq * rq)10030 static void calc_load_migrate(struct rq *rq)
10031 {
10032 	long delta = calc_load_fold_active(rq, 1);
10033 
10034 	if (delta)
10035 		atomic_long_add(delta, &calc_load_tasks);
10036 }
10037 
dump_rq_tasks(struct rq * rq,const char * loglvl)10038 static void dump_rq_tasks(struct rq *rq, const char *loglvl)
10039 {
10040 	struct task_struct *g, *p;
10041 	int cpu = cpu_of(rq);
10042 
10043 	lockdep_assert_rq_held(rq);
10044 
10045 	printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running);
10046 	for_each_process_thread(g, p) {
10047 		if (task_cpu(p) != cpu)
10048 			continue;
10049 
10050 		if (!task_on_rq_queued(p))
10051 			continue;
10052 
10053 		printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm);
10054 	}
10055 }
10056 
sched_cpu_dying(unsigned int cpu)10057 int sched_cpu_dying(unsigned int cpu)
10058 {
10059 	struct rq *rq = cpu_rq(cpu);
10060 	struct rq_flags rf;
10061 
10062 	/* Handle pending wakeups and then migrate everything off */
10063 	sched_tick_stop(cpu);
10064 
10065 	rq_lock_irqsave(rq, &rf);
10066 	if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) {
10067 		WARN(true, "Dying CPU not properly vacated!");
10068 		dump_rq_tasks(rq, KERN_WARNING);
10069 	}
10070 	rq_unlock_irqrestore(rq, &rf);
10071 
10072 	trace_android_rvh_sched_cpu_dying(cpu);
10073 
10074 	calc_load_migrate(rq);
10075 	update_max_interval();
10076 	hrtick_clear(rq);
10077 	sched_core_cpu_dying(cpu);
10078 	return 0;
10079 }
10080 #endif
10081 
sched_init_smp(void)10082 void __init sched_init_smp(void)
10083 {
10084 	sched_init_numa(NUMA_NO_NODE);
10085 
10086 	/*
10087 	 * There's no userspace yet to cause hotplug operations; hence all the
10088 	 * CPU masks are stable and all blatant races in the below code cannot
10089 	 * happen.
10090 	 */
10091 	mutex_lock(&sched_domains_mutex);
10092 	sched_init_domains(cpu_active_mask);
10093 	mutex_unlock(&sched_domains_mutex);
10094 
10095 	/* Move init over to a non-isolated CPU */
10096 	if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0)
10097 		BUG();
10098 	current->flags &= ~PF_NO_SETAFFINITY;
10099 	sched_init_granularity();
10100 
10101 	init_sched_rt_class();
10102 	init_sched_dl_class();
10103 
10104 	sched_smp_initialized = true;
10105 }
10106 
migration_init(void)10107 static int __init migration_init(void)
10108 {
10109 	sched_cpu_starting(smp_processor_id());
10110 	return 0;
10111 }
10112 early_initcall(migration_init);
10113 
10114 #else
sched_init_smp(void)10115 void __init sched_init_smp(void)
10116 {
10117 	sched_init_granularity();
10118 }
10119 #endif /* CONFIG_SMP */
10120 
in_sched_functions(unsigned long addr)10121 int in_sched_functions(unsigned long addr)
10122 {
10123 	return in_lock_functions(addr) ||
10124 		(addr >= (unsigned long)__sched_text_start
10125 		&& addr < (unsigned long)__sched_text_end);
10126 }
10127 
10128 #ifdef CONFIG_CGROUP_SCHED
10129 /*
10130  * Default task group.
10131  * Every task in system belongs to this group at bootup.
10132  */
10133 struct task_group root_task_group;
10134 EXPORT_SYMBOL_GPL(root_task_group);
10135 LIST_HEAD(task_groups);
10136 EXPORT_SYMBOL_GPL(task_groups);
10137 
10138 /* Cacheline aligned slab cache for task_group */
10139 static struct kmem_cache *task_group_cache __read_mostly;
10140 #endif
10141 
sched_init(void)10142 void __init sched_init(void)
10143 {
10144 	unsigned long ptr = 0;
10145 	int i;
10146 
10147 	/* Make sure the linker didn't screw up */
10148 	BUG_ON(&idle_sched_class != &fair_sched_class + 1 ||
10149 	       &fair_sched_class != &rt_sched_class + 1 ||
10150 	       &rt_sched_class   != &dl_sched_class + 1);
10151 #ifdef CONFIG_SMP
10152 	BUG_ON(&dl_sched_class != &stop_sched_class + 1);
10153 #endif
10154 
10155 	wait_bit_init();
10156 
10157 #ifdef CONFIG_FAIR_GROUP_SCHED
10158 	ptr += 2 * nr_cpu_ids * sizeof(void **);
10159 #endif
10160 #ifdef CONFIG_RT_GROUP_SCHED
10161 	ptr += 2 * nr_cpu_ids * sizeof(void **);
10162 #endif
10163 	if (ptr) {
10164 		ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
10165 
10166 #ifdef CONFIG_FAIR_GROUP_SCHED
10167 		root_task_group.se = (struct sched_entity **)ptr;
10168 		ptr += nr_cpu_ids * sizeof(void **);
10169 
10170 		root_task_group.cfs_rq = (struct cfs_rq **)ptr;
10171 		ptr += nr_cpu_ids * sizeof(void **);
10172 
10173 		root_task_group.shares = ROOT_TASK_GROUP_LOAD;
10174 		init_cfs_bandwidth(&root_task_group.cfs_bandwidth, NULL);
10175 #endif /* CONFIG_FAIR_GROUP_SCHED */
10176 #ifdef CONFIG_RT_GROUP_SCHED
10177 		root_task_group.rt_se = (struct sched_rt_entity **)ptr;
10178 		ptr += nr_cpu_ids * sizeof(void **);
10179 
10180 		root_task_group.rt_rq = (struct rt_rq **)ptr;
10181 		ptr += nr_cpu_ids * sizeof(void **);
10182 
10183 #endif /* CONFIG_RT_GROUP_SCHED */
10184 	}
10185 
10186 	init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
10187 
10188 #ifdef CONFIG_SMP
10189 	init_defrootdomain();
10190 #endif
10191 
10192 #ifdef CONFIG_RT_GROUP_SCHED
10193 	init_rt_bandwidth(&root_task_group.rt_bandwidth,
10194 			global_rt_period(), global_rt_runtime());
10195 #endif /* CONFIG_RT_GROUP_SCHED */
10196 
10197 #ifdef CONFIG_CGROUP_SCHED
10198 	task_group_cache = KMEM_CACHE(task_group, 0);
10199 
10200 	list_add(&root_task_group.list, &task_groups);
10201 	INIT_LIST_HEAD(&root_task_group.children);
10202 	INIT_LIST_HEAD(&root_task_group.siblings);
10203 	autogroup_init(&init_task);
10204 #endif /* CONFIG_CGROUP_SCHED */
10205 
10206 	for_each_possible_cpu(i) {
10207 		struct rq *rq;
10208 
10209 		rq = cpu_rq(i);
10210 		raw_spin_lock_init(&rq->__lock);
10211 		rq->nr_running = 0;
10212 		rq->calc_load_active = 0;
10213 		rq->calc_load_update = jiffies + LOAD_FREQ;
10214 		init_cfs_rq(&rq->cfs);
10215 		init_rt_rq(&rq->rt);
10216 		init_dl_rq(&rq->dl);
10217 #ifdef CONFIG_FAIR_GROUP_SCHED
10218 		INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
10219 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
10220 		/*
10221 		 * How much CPU bandwidth does root_task_group get?
10222 		 *
10223 		 * In case of task-groups formed thr' the cgroup filesystem, it
10224 		 * gets 100% of the CPU resources in the system. This overall
10225 		 * system CPU resource is divided among the tasks of
10226 		 * root_task_group and its child task-groups in a fair manner,
10227 		 * based on each entity's (task or task-group's) weight
10228 		 * (se->load.weight).
10229 		 *
10230 		 * In other words, if root_task_group has 10 tasks of weight
10231 		 * 1024) and two child groups A0 and A1 (of weight 1024 each),
10232 		 * then A0's share of the CPU resource is:
10233 		 *
10234 		 *	A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
10235 		 *
10236 		 * We achieve this by letting root_task_group's tasks sit
10237 		 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
10238 		 */
10239 		init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
10240 #endif /* CONFIG_FAIR_GROUP_SCHED */
10241 
10242 		rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
10243 #ifdef CONFIG_RT_GROUP_SCHED
10244 		init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
10245 #endif
10246 #ifdef CONFIG_SMP
10247 		rq->sd = NULL;
10248 		rq->rd = NULL;
10249 		rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
10250 		rq->balance_callback = &balance_push_callback;
10251 		rq->active_balance = 0;
10252 		rq->next_balance = jiffies;
10253 		rq->push_cpu = 0;
10254 		rq->cpu = i;
10255 		rq->online = 0;
10256 		rq->idle_stamp = 0;
10257 		rq->avg_idle = 2*sysctl_sched_migration_cost;
10258 		rq->wake_stamp = jiffies;
10259 		rq->wake_avg_idle = rq->avg_idle;
10260 		rq->max_idle_balance_cost = sysctl_sched_migration_cost;
10261 
10262 		INIT_LIST_HEAD(&rq->cfs_tasks);
10263 
10264 		rq_attach_root(rq, &def_root_domain);
10265 #ifdef CONFIG_NO_HZ_COMMON
10266 		rq->last_blocked_load_update_tick = jiffies;
10267 		atomic_set(&rq->nohz_flags, 0);
10268 
10269 		INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq);
10270 #endif
10271 #ifdef CONFIG_HOTPLUG_CPU
10272 		rcuwait_init(&rq->hotplug_wait);
10273 #endif
10274 #endif /* CONFIG_SMP */
10275 		hrtick_rq_init(rq);
10276 		atomic_set(&rq->nr_iowait, 0);
10277 
10278 #ifdef CONFIG_SCHED_CORE
10279 		rq->core = rq;
10280 		rq->core_pick = NULL;
10281 		rq->core_enabled = 0;
10282 		rq->core_tree = RB_ROOT;
10283 		rq->core_forceidle_count = 0;
10284 		rq->core_forceidle_occupation = 0;
10285 		rq->core_forceidle_start = 0;
10286 
10287 		rq->core_cookie = 0UL;
10288 #endif
10289 		zalloc_cpumask_var_node(&rq->scratch_mask, GFP_KERNEL, cpu_to_node(i));
10290 	}
10291 
10292 	set_load_weight(&init_task, false);
10293 
10294 	/*
10295 	 * The boot idle thread does lazy MMU switching as well:
10296 	 */
10297 	mmgrab_lazy_tlb(&init_mm);
10298 	enter_lazy_tlb(&init_mm, current);
10299 
10300 	/*
10301 	 * The idle task doesn't need the kthread struct to function, but it
10302 	 * is dressed up as a per-CPU kthread and thus needs to play the part
10303 	 * if we want to avoid special-casing it in code that deals with per-CPU
10304 	 * kthreads.
10305 	 */
10306 	WARN_ON(!set_kthread_struct(current));
10307 
10308 	/*
10309 	 * Make us the idle thread. Technically, schedule() should not be
10310 	 * called from this thread, however somewhere below it might be,
10311 	 * but because we are the idle thread, we just pick up running again
10312 	 * when this runqueue becomes "idle".
10313 	 */
10314 	init_idle(current, smp_processor_id());
10315 
10316 	calc_load_update = jiffies + LOAD_FREQ;
10317 
10318 #ifdef CONFIG_SMP
10319 	idle_thread_set_boot_cpu();
10320 	balance_push_set(smp_processor_id(), false);
10321 #endif
10322 	init_sched_fair_class();
10323 
10324 	psi_init();
10325 
10326 	init_uclamp();
10327 
10328 	preempt_dynamic_init();
10329 
10330 	scheduler_running = 1;
10331 }
10332 
10333 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
10334 
__might_sleep(const char * file,int line)10335 void __might_sleep(const char *file, int line)
10336 {
10337 	unsigned int state = get_current_state();
10338 	/*
10339 	 * Blocking primitives will set (and therefore destroy) current->state,
10340 	 * since we will exit with TASK_RUNNING make sure we enter with it,
10341 	 * otherwise we will destroy state.
10342 	 */
10343 	WARN_ONCE(state != TASK_RUNNING && current->task_state_change,
10344 			"do not call blocking ops when !TASK_RUNNING; "
10345 			"state=%x set at [<%p>] %pS\n", state,
10346 			(void *)current->task_state_change,
10347 			(void *)current->task_state_change);
10348 
10349 	__might_resched(file, line, 0);
10350 }
10351 EXPORT_SYMBOL(__might_sleep);
10352 
print_preempt_disable_ip(int preempt_offset,unsigned long ip)10353 static void print_preempt_disable_ip(int preempt_offset, unsigned long ip)
10354 {
10355 	if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT))
10356 		return;
10357 
10358 	if (preempt_count() == preempt_offset)
10359 		return;
10360 
10361 	pr_err("Preemption disabled at:");
10362 	print_ip_sym(KERN_ERR, ip);
10363 }
10364 
resched_offsets_ok(unsigned int offsets)10365 static inline bool resched_offsets_ok(unsigned int offsets)
10366 {
10367 	unsigned int nested = preempt_count();
10368 
10369 	nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT;
10370 
10371 	return nested == offsets;
10372 }
10373 
__might_resched(const char * file,int line,unsigned int offsets)10374 void __might_resched(const char *file, int line, unsigned int offsets)
10375 {
10376 	/* Ratelimiting timestamp: */
10377 	static unsigned long prev_jiffy;
10378 
10379 	unsigned long preempt_disable_ip;
10380 
10381 	/* WARN_ON_ONCE() by default, no rate limit required: */
10382 	rcu_sleep_check();
10383 
10384 	if ((resched_offsets_ok(offsets) && !irqs_disabled() &&
10385 	     !is_idle_task(current) && !current->non_block_count) ||
10386 	    system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
10387 	    oops_in_progress)
10388 		return;
10389 
10390 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
10391 		return;
10392 	prev_jiffy = jiffies;
10393 
10394 	/* Save this before calling printk(), since that will clobber it: */
10395 	preempt_disable_ip = get_preempt_disable_ip(current);
10396 
10397 	pr_err("BUG: sleeping function called from invalid context at %s:%d\n",
10398 	       file, line);
10399 	pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
10400 	       in_atomic(), irqs_disabled(), current->non_block_count,
10401 	       current->pid, current->comm);
10402 	pr_err("preempt_count: %x, expected: %x\n", preempt_count(),
10403 	       offsets & MIGHT_RESCHED_PREEMPT_MASK);
10404 
10405 	if (IS_ENABLED(CONFIG_PREEMPT_RCU)) {
10406 		pr_err("RCU nest depth: %d, expected: %u\n",
10407 		       rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT);
10408 	}
10409 
10410 	if (task_stack_end_corrupted(current))
10411 		pr_emerg("Thread overran stack, or stack corrupted\n");
10412 
10413 	debug_show_held_locks(current);
10414 	if (irqs_disabled())
10415 		print_irqtrace_events(current);
10416 
10417 	print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK,
10418 				 preempt_disable_ip);
10419 
10420 	trace_android_rvh_schedule_bug(NULL);
10421 
10422 	dump_stack();
10423 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
10424 }
10425 EXPORT_SYMBOL(__might_resched);
10426 
__cant_sleep(const char * file,int line,int preempt_offset)10427 void __cant_sleep(const char *file, int line, int preempt_offset)
10428 {
10429 	static unsigned long prev_jiffy;
10430 
10431 	if (irqs_disabled())
10432 		return;
10433 
10434 	if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
10435 		return;
10436 
10437 	if (preempt_count() > preempt_offset)
10438 		return;
10439 
10440 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
10441 		return;
10442 	prev_jiffy = jiffies;
10443 
10444 	printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
10445 	printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
10446 			in_atomic(), irqs_disabled(),
10447 			current->pid, current->comm);
10448 
10449 	debug_show_held_locks(current);
10450 	dump_stack();
10451 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
10452 }
10453 EXPORT_SYMBOL_GPL(__cant_sleep);
10454 
10455 #ifdef CONFIG_SMP
__cant_migrate(const char * file,int line)10456 void __cant_migrate(const char *file, int line)
10457 {
10458 	static unsigned long prev_jiffy;
10459 
10460 	if (irqs_disabled())
10461 		return;
10462 
10463 	if (is_migration_disabled(current))
10464 		return;
10465 
10466 	if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
10467 		return;
10468 
10469 	if (preempt_count() > 0)
10470 		return;
10471 
10472 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
10473 		return;
10474 	prev_jiffy = jiffies;
10475 
10476 	pr_err("BUG: assuming non migratable context at %s:%d\n", file, line);
10477 	pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n",
10478 	       in_atomic(), irqs_disabled(), is_migration_disabled(current),
10479 	       current->pid, current->comm);
10480 
10481 	debug_show_held_locks(current);
10482 	dump_stack();
10483 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
10484 }
10485 EXPORT_SYMBOL_GPL(__cant_migrate);
10486 #endif
10487 #endif
10488 
10489 #ifdef CONFIG_MAGIC_SYSRQ
normalize_rt_tasks(void)10490 void normalize_rt_tasks(void)
10491 {
10492 	struct task_struct *g, *p;
10493 	struct sched_attr attr = {
10494 		.sched_policy = SCHED_NORMAL,
10495 	};
10496 
10497 	read_lock(&tasklist_lock);
10498 	for_each_process_thread(g, p) {
10499 		/*
10500 		 * Only normalize user tasks:
10501 		 */
10502 		if (p->flags & PF_KTHREAD)
10503 			continue;
10504 
10505 		p->se.exec_start = 0;
10506 		schedstat_set(p->stats.wait_start,  0);
10507 		schedstat_set(p->stats.sleep_start, 0);
10508 		schedstat_set(p->stats.block_start, 0);
10509 
10510 		if (!dl_task(p) && !rt_task(p)) {
10511 			/*
10512 			 * Renice negative nice level userspace
10513 			 * tasks back to 0:
10514 			 */
10515 			if (task_nice(p) < 0)
10516 				set_user_nice(p, 0);
10517 			continue;
10518 		}
10519 
10520 		__sched_setscheduler(p, &attr, false, false);
10521 	}
10522 	read_unlock(&tasklist_lock);
10523 }
10524 
10525 #endif /* CONFIG_MAGIC_SYSRQ */
10526 
10527 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
10528 /*
10529  * These functions are only useful for the IA64 MCA handling, or kdb.
10530  *
10531  * They can only be called when the whole system has been
10532  * stopped - every CPU needs to be quiescent, and no scheduling
10533  * activity can take place. Using them for anything else would
10534  * be a serious bug, and as a result, they aren't even visible
10535  * under any other configuration.
10536  */
10537 
10538 /**
10539  * curr_task - return the current task for a given CPU.
10540  * @cpu: the processor in question.
10541  *
10542  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
10543  *
10544  * Return: The current task for @cpu.
10545  */
curr_task(int cpu)10546 struct task_struct *curr_task(int cpu)
10547 {
10548 	return cpu_curr(cpu);
10549 }
10550 
10551 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
10552 
10553 #ifdef CONFIG_IA64
10554 /**
10555  * ia64_set_curr_task - set the current task for a given CPU.
10556  * @cpu: the processor in question.
10557  * @p: the task pointer to set.
10558  *
10559  * Description: This function must only be used when non-maskable interrupts
10560  * are serviced on a separate stack. It allows the architecture to switch the
10561  * notion of the current task on a CPU in a non-blocking manner. This function
10562  * must be called with all CPU's synchronized, and interrupts disabled, the
10563  * and caller must save the original value of the current task (see
10564  * curr_task() above) and restore that value before reenabling interrupts and
10565  * re-starting the system.
10566  *
10567  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
10568  */
ia64_set_curr_task(int cpu,struct task_struct * p)10569 void ia64_set_curr_task(int cpu, struct task_struct *p)
10570 {
10571 	cpu_curr(cpu) = p;
10572 }
10573 
10574 #endif
10575 
10576 #ifdef CONFIG_CGROUP_SCHED
10577 /* task_group_lock serializes the addition/removal of task groups */
10578 static DEFINE_SPINLOCK(task_group_lock);
10579 
alloc_uclamp_sched_group(struct task_group * tg,struct task_group * parent)10580 static inline void alloc_uclamp_sched_group(struct task_group *tg,
10581 					    struct task_group *parent)
10582 {
10583 #ifdef CONFIG_UCLAMP_TASK_GROUP
10584 	enum uclamp_id clamp_id;
10585 
10586 	for_each_clamp_id(clamp_id) {
10587 		uclamp_se_set(&tg->uclamp_req[clamp_id],
10588 			      uclamp_none(clamp_id), false);
10589 		tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
10590 	}
10591 #endif
10592 }
10593 
sched_free_group(struct task_group * tg)10594 static void sched_free_group(struct task_group *tg)
10595 {
10596 	free_fair_sched_group(tg);
10597 	free_rt_sched_group(tg);
10598 	autogroup_free(tg);
10599 	kmem_cache_free(task_group_cache, tg);
10600 }
10601 
sched_free_group_rcu(struct rcu_head * rcu)10602 static void sched_free_group_rcu(struct rcu_head *rcu)
10603 {
10604 	sched_free_group(container_of(rcu, struct task_group, rcu));
10605 }
10606 
sched_unregister_group(struct task_group * tg)10607 static void sched_unregister_group(struct task_group *tg)
10608 {
10609 	unregister_fair_sched_group(tg);
10610 	unregister_rt_sched_group(tg);
10611 	/*
10612 	 * We have to wait for yet another RCU grace period to expire, as
10613 	 * print_cfs_stats() might run concurrently.
10614 	 */
10615 	call_rcu(&tg->rcu, sched_free_group_rcu);
10616 }
10617 
10618 /* allocate runqueue etc for a new task group */
sched_create_group(struct task_group * parent)10619 struct task_group *sched_create_group(struct task_group *parent)
10620 {
10621 	struct task_group *tg;
10622 
10623 	tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
10624 	if (!tg)
10625 		return ERR_PTR(-ENOMEM);
10626 
10627 	if (!alloc_fair_sched_group(tg, parent))
10628 		goto err;
10629 
10630 	if (!alloc_rt_sched_group(tg, parent))
10631 		goto err;
10632 
10633 	alloc_uclamp_sched_group(tg, parent);
10634 
10635 	return tg;
10636 
10637 err:
10638 	sched_free_group(tg);
10639 	return ERR_PTR(-ENOMEM);
10640 }
10641 
sched_online_group(struct task_group * tg,struct task_group * parent)10642 void sched_online_group(struct task_group *tg, struct task_group *parent)
10643 {
10644 	unsigned long flags;
10645 
10646 	spin_lock_irqsave(&task_group_lock, flags);
10647 	list_add_rcu(&tg->list, &task_groups);
10648 
10649 	/* Root should already exist: */
10650 	WARN_ON(!parent);
10651 
10652 	tg->parent = parent;
10653 	INIT_LIST_HEAD(&tg->children);
10654 	list_add_rcu(&tg->siblings, &parent->children);
10655 	spin_unlock_irqrestore(&task_group_lock, flags);
10656 
10657 	online_fair_sched_group(tg);
10658 }
10659 
10660 /* rcu callback to free various structures associated with a task group */
sched_unregister_group_rcu(struct rcu_head * rhp)10661 static void sched_unregister_group_rcu(struct rcu_head *rhp)
10662 {
10663 	/* Now it should be safe to free those cfs_rqs: */
10664 	sched_unregister_group(container_of(rhp, struct task_group, rcu));
10665 }
10666 
sched_destroy_group(struct task_group * tg)10667 void sched_destroy_group(struct task_group *tg)
10668 {
10669 	/* Wait for possible concurrent references to cfs_rqs complete: */
10670 	call_rcu(&tg->rcu, sched_unregister_group_rcu);
10671 }
10672 
sched_release_group(struct task_group * tg)10673 void sched_release_group(struct task_group *tg)
10674 {
10675 	unsigned long flags;
10676 
10677 	/*
10678 	 * Unlink first, to avoid walk_tg_tree_from() from finding us (via
10679 	 * sched_cfs_period_timer()).
10680 	 *
10681 	 * For this to be effective, we have to wait for all pending users of
10682 	 * this task group to leave their RCU critical section to ensure no new
10683 	 * user will see our dying task group any more. Specifically ensure
10684 	 * that tg_unthrottle_up() won't add decayed cfs_rq's to it.
10685 	 *
10686 	 * We therefore defer calling unregister_fair_sched_group() to
10687 	 * sched_unregister_group() which is guarantied to get called only after the
10688 	 * current RCU grace period has expired.
10689 	 */
10690 	spin_lock_irqsave(&task_group_lock, flags);
10691 	list_del_rcu(&tg->list);
10692 	list_del_rcu(&tg->siblings);
10693 	spin_unlock_irqrestore(&task_group_lock, flags);
10694 }
10695 
sched_get_task_group(struct task_struct * tsk)10696 static struct task_group *sched_get_task_group(struct task_struct *tsk)
10697 {
10698 	struct task_group *tg;
10699 
10700 	/*
10701 	 * All callers are synchronized by task_rq_lock(); we do not use RCU
10702 	 * which is pointless here. Thus, we pass "true" to task_css_check()
10703 	 * to prevent lockdep warnings.
10704 	 */
10705 	tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
10706 			  struct task_group, css);
10707 	tg = autogroup_task_group(tsk, tg);
10708 
10709 	return tg;
10710 }
10711 
sched_change_group(struct task_struct * tsk,struct task_group * group)10712 static void sched_change_group(struct task_struct *tsk, struct task_group *group)
10713 {
10714 	tsk->sched_task_group = group;
10715 
10716 #ifdef CONFIG_FAIR_GROUP_SCHED
10717 	if (tsk->sched_class->task_change_group)
10718 		tsk->sched_class->task_change_group(tsk);
10719 	else
10720 #endif
10721 		set_task_rq(tsk, task_cpu(tsk));
10722 }
10723 
10724 /*
10725  * Change task's runqueue when it moves between groups.
10726  *
10727  * The caller of this function should have put the task in its new group by
10728  * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
10729  * its new group.
10730  */
sched_move_task(struct task_struct * tsk)10731 void sched_move_task(struct task_struct *tsk)
10732 {
10733 	int queued, running, queue_flags =
10734 		DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
10735 	struct task_group *group;
10736 	struct rq_flags rf;
10737 	struct rq *rq;
10738 
10739 	trace_android_vh_sched_move_task(tsk);
10740 	rq = task_rq_lock(tsk, &rf);
10741 	/*
10742 	 * Esp. with SCHED_AUTOGROUP enabled it is possible to get superfluous
10743 	 * group changes.
10744 	 */
10745 	group = sched_get_task_group(tsk);
10746 	if (group == tsk->sched_task_group)
10747 		goto unlock;
10748 
10749 	update_rq_clock(rq);
10750 
10751 	running = task_current(rq, tsk);
10752 	queued = task_on_rq_queued(tsk);
10753 
10754 	if (queued)
10755 		dequeue_task(rq, tsk, queue_flags);
10756 	if (running)
10757 		put_prev_task(rq, tsk);
10758 
10759 	sched_change_group(tsk, group);
10760 
10761 	if (queued)
10762 		enqueue_task(rq, tsk, queue_flags);
10763 	if (running) {
10764 		set_next_task(rq, tsk);
10765 		/*
10766 		 * After changing group, the running task may have joined a
10767 		 * throttled one but it's still the running task. Trigger a
10768 		 * resched to make sure that task can still run.
10769 		 */
10770 		resched_curr(rq);
10771 	}
10772 
10773 unlock:
10774 	task_rq_unlock(rq, tsk, &rf);
10775 }
10776 
css_tg(struct cgroup_subsys_state * css)10777 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
10778 {
10779 	return css ? container_of(css, struct task_group, css) : NULL;
10780 }
10781 
10782 static struct cgroup_subsys_state *
cpu_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)10783 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
10784 {
10785 	struct task_group *parent = css_tg(parent_css);
10786 	struct task_group *tg;
10787 
10788 	if (!parent) {
10789 		trace_android_vh_cpu_cgroup_css_alloc_early(parent);
10790 		/* This is early initialization for the top cgroup */
10791 		return &root_task_group.css;
10792 	}
10793 
10794 	tg = sched_create_group(parent);
10795 	if (IS_ERR(tg))
10796 		return ERR_PTR(-ENOMEM);
10797 
10798 	trace_android_vh_cpu_cgroup_css_alloc(tg, parent_css);
10799 
10800 	return &tg->css;
10801 }
10802 
10803 /* Expose task group only after completing cgroup initialization */
cpu_cgroup_css_online(struct cgroup_subsys_state * css)10804 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
10805 {
10806 	struct task_group *tg = css_tg(css);
10807 	struct task_group *parent = css_tg(css->parent);
10808 
10809 	if (parent)
10810 		sched_online_group(tg, parent);
10811 
10812 #ifdef CONFIG_UCLAMP_TASK_GROUP
10813 	/* Propagate the effective uclamp value for the new group */
10814 	mutex_lock(&uclamp_mutex);
10815 	rcu_read_lock();
10816 	cpu_util_update_eff(css);
10817 	rcu_read_unlock();
10818 	mutex_unlock(&uclamp_mutex);
10819 #endif
10820 
10821 	trace_android_rvh_cpu_cgroup_online(css);
10822 	return 0;
10823 }
10824 
cpu_cgroup_css_released(struct cgroup_subsys_state * css)10825 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
10826 {
10827 	struct task_group *tg = css_tg(css);
10828 
10829 	sched_release_group(tg);
10830 }
10831 
cpu_cgroup_css_free(struct cgroup_subsys_state * css)10832 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
10833 {
10834 	struct task_group *tg = css_tg(css);
10835 
10836 	/*
10837 	 * Relies on the RCU grace period between css_released() and this.
10838 	 */
10839 	sched_unregister_group(tg);
10840 
10841 	trace_android_vh_cpu_cgroup_css_free(css);
10842 }
10843 
10844 #ifdef CONFIG_RT_GROUP_SCHED
cpu_cgroup_can_attach(struct cgroup_taskset * tset)10845 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
10846 {
10847 	struct task_struct *task;
10848 	struct cgroup_subsys_state *css;
10849 
10850 	cgroup_taskset_for_each(task, css, tset) {
10851 		if (!sched_rt_can_attach(css_tg(css), task))
10852 			return -EINVAL;
10853 	}
10854 	return 0;
10855 }
10856 #endif
10857 
cpu_cgroup_attach(struct cgroup_taskset * tset)10858 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
10859 {
10860 	struct task_struct *task;
10861 	struct cgroup_subsys_state *css;
10862 
10863 	cgroup_taskset_for_each(task, css, tset)
10864 		sched_move_task(task);
10865 
10866 	trace_android_rvh_cpu_cgroup_attach(tset);
10867 }
10868 
10869 #ifdef CONFIG_UCLAMP_TASK_GROUP
cpu_util_update_eff(struct cgroup_subsys_state * css)10870 static void cpu_util_update_eff(struct cgroup_subsys_state *css)
10871 {
10872 	struct cgroup_subsys_state *top_css = css;
10873 	struct uclamp_se *uc_parent = NULL;
10874 	struct uclamp_se *uc_se = NULL;
10875 	unsigned int eff[UCLAMP_CNT];
10876 	enum uclamp_id clamp_id;
10877 	unsigned int clamps;
10878 
10879 	lockdep_assert_held(&uclamp_mutex);
10880 	SCHED_WARN_ON(!rcu_read_lock_held());
10881 
10882 	css_for_each_descendant_pre(css, top_css) {
10883 		uc_parent = css_tg(css)->parent
10884 			? css_tg(css)->parent->uclamp : NULL;
10885 
10886 		for_each_clamp_id(clamp_id) {
10887 			/* Assume effective clamps matches requested clamps */
10888 			eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
10889 			/* Cap effective clamps with parent's effective clamps */
10890 			if (uc_parent &&
10891 			    eff[clamp_id] > uc_parent[clamp_id].value) {
10892 				eff[clamp_id] = uc_parent[clamp_id].value;
10893 			}
10894 		}
10895 		/* Ensure protection is always capped by limit */
10896 		eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
10897 
10898 		/* Propagate most restrictive effective clamps */
10899 		clamps = 0x0;
10900 		uc_se = css_tg(css)->uclamp;
10901 		for_each_clamp_id(clamp_id) {
10902 			if (eff[clamp_id] == uc_se[clamp_id].value)
10903 				continue;
10904 			uc_se[clamp_id].value = eff[clamp_id];
10905 			uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
10906 			clamps |= (0x1 << clamp_id);
10907 		}
10908 		if (!clamps) {
10909 			css = css_rightmost_descendant(css);
10910 			continue;
10911 		}
10912 
10913 		/* Immediately update descendants RUNNABLE tasks */
10914 		uclamp_update_active_tasks(css);
10915 	}
10916 }
10917 
10918 /*
10919  * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
10920  * C expression. Since there is no way to convert a macro argument (N) into a
10921  * character constant, use two levels of macros.
10922  */
10923 #define _POW10(exp) ((unsigned int)1e##exp)
10924 #define POW10(exp) _POW10(exp)
10925 
10926 struct uclamp_request {
10927 #define UCLAMP_PERCENT_SHIFT	2
10928 #define UCLAMP_PERCENT_SCALE	(100 * POW10(UCLAMP_PERCENT_SHIFT))
10929 	s64 percent;
10930 	u64 util;
10931 	int ret;
10932 };
10933 
10934 static inline struct uclamp_request
capacity_from_percent(char * buf)10935 capacity_from_percent(char *buf)
10936 {
10937 	struct uclamp_request req = {
10938 		.percent = UCLAMP_PERCENT_SCALE,
10939 		.util = SCHED_CAPACITY_SCALE,
10940 		.ret = 0,
10941 	};
10942 
10943 	buf = strim(buf);
10944 	if (strcmp(buf, "max")) {
10945 		req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
10946 					     &req.percent);
10947 		if (req.ret)
10948 			return req;
10949 		if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
10950 			req.ret = -ERANGE;
10951 			return req;
10952 		}
10953 
10954 		req.util = req.percent << SCHED_CAPACITY_SHIFT;
10955 		req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
10956 	}
10957 
10958 	return req;
10959 }
10960 
cpu_uclamp_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off,enum uclamp_id clamp_id)10961 static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
10962 				size_t nbytes, loff_t off,
10963 				enum uclamp_id clamp_id)
10964 {
10965 	struct uclamp_request req;
10966 	struct task_group *tg;
10967 
10968 	req = capacity_from_percent(buf);
10969 	if (req.ret)
10970 		return req.ret;
10971 
10972 	static_branch_enable(&sched_uclamp_used);
10973 
10974 	mutex_lock(&uclamp_mutex);
10975 	rcu_read_lock();
10976 
10977 	tg = css_tg(of_css(of));
10978 	if (tg->uclamp_req[clamp_id].value != req.util)
10979 		uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
10980 
10981 	/*
10982 	 * Because of not recoverable conversion rounding we keep track of the
10983 	 * exact requested value
10984 	 */
10985 	tg->uclamp_pct[clamp_id] = req.percent;
10986 
10987 	/* Update effective clamps to track the most restrictive value */
10988 	cpu_util_update_eff(of_css(of));
10989 
10990 	rcu_read_unlock();
10991 	mutex_unlock(&uclamp_mutex);
10992 
10993 	return nbytes;
10994 }
10995 
cpu_uclamp_min_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)10996 static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
10997 				    char *buf, size_t nbytes,
10998 				    loff_t off)
10999 {
11000 	return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
11001 }
11002 
cpu_uclamp_max_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)11003 static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
11004 				    char *buf, size_t nbytes,
11005 				    loff_t off)
11006 {
11007 	return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
11008 }
11009 
cpu_uclamp_print(struct seq_file * sf,enum uclamp_id clamp_id)11010 static inline void cpu_uclamp_print(struct seq_file *sf,
11011 				    enum uclamp_id clamp_id)
11012 {
11013 	struct task_group *tg;
11014 	u64 util_clamp;
11015 	u64 percent;
11016 	u32 rem;
11017 
11018 	rcu_read_lock();
11019 	tg = css_tg(seq_css(sf));
11020 	util_clamp = tg->uclamp_req[clamp_id].value;
11021 	rcu_read_unlock();
11022 
11023 	if (util_clamp == SCHED_CAPACITY_SCALE) {
11024 		seq_puts(sf, "max\n");
11025 		return;
11026 	}
11027 
11028 	percent = tg->uclamp_pct[clamp_id];
11029 	percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
11030 	seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
11031 }
11032 
cpu_uclamp_min_show(struct seq_file * sf,void * v)11033 static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
11034 {
11035 	cpu_uclamp_print(sf, UCLAMP_MIN);
11036 	return 0;
11037 }
11038 
cpu_uclamp_max_show(struct seq_file * sf,void * v)11039 static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
11040 {
11041 	cpu_uclamp_print(sf, UCLAMP_MAX);
11042 	return 0;
11043 }
11044 
cpu_uclamp_ls_write_u64(struct cgroup_subsys_state * css,struct cftype * cftype,u64 ls)11045 static int cpu_uclamp_ls_write_u64(struct cgroup_subsys_state *css,
11046 				   struct cftype *cftype, u64 ls)
11047 {
11048 	struct task_group *tg;
11049 
11050 	if (ls > 1)
11051 		return -EINVAL;
11052 	tg = css_tg(css);
11053 	tg->latency_sensitive = (unsigned int) ls;
11054 
11055 	return 0;
11056 }
11057 
cpu_uclamp_ls_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)11058 static u64 cpu_uclamp_ls_read_u64(struct cgroup_subsys_state *css,
11059 				  struct cftype *cft)
11060 {
11061 	struct task_group *tg = css_tg(css);
11062 
11063 	return (u64) tg->latency_sensitive;
11064 }
11065 #endif /* CONFIG_UCLAMP_TASK_GROUP */
11066 
11067 #ifdef CONFIG_FAIR_GROUP_SCHED
cpu_shares_write_u64(struct cgroup_subsys_state * css,struct cftype * cftype,u64 shareval)11068 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
11069 				struct cftype *cftype, u64 shareval)
11070 {
11071 	if (shareval > scale_load_down(ULONG_MAX))
11072 		shareval = MAX_SHARES;
11073 	return sched_group_set_shares(css_tg(css), scale_load(shareval));
11074 }
11075 
cpu_shares_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)11076 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
11077 			       struct cftype *cft)
11078 {
11079 	struct task_group *tg = css_tg(css);
11080 
11081 	return (u64) scale_load_down(tg->shares);
11082 }
11083 
11084 #ifdef CONFIG_CFS_BANDWIDTH
11085 static DEFINE_MUTEX(cfs_constraints_mutex);
11086 
11087 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
11088 static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
11089 /* More than 203 days if BW_SHIFT equals 20. */
11090 static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
11091 
11092 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
11093 
tg_set_cfs_bandwidth(struct task_group * tg,u64 period,u64 quota,u64 burst)11094 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota,
11095 				u64 burst)
11096 {
11097 	int i, ret = 0, runtime_enabled, runtime_was_enabled;
11098 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
11099 
11100 	if (tg == &root_task_group)
11101 		return -EINVAL;
11102 
11103 	/*
11104 	 * Ensure we have at some amount of bandwidth every period.  This is
11105 	 * to prevent reaching a state of large arrears when throttled via
11106 	 * entity_tick() resulting in prolonged exit starvation.
11107 	 */
11108 	if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
11109 		return -EINVAL;
11110 
11111 	/*
11112 	 * Likewise, bound things on the other side by preventing insane quota
11113 	 * periods.  This also allows us to normalize in computing quota
11114 	 * feasibility.
11115 	 */
11116 	if (period > max_cfs_quota_period)
11117 		return -EINVAL;
11118 
11119 	/*
11120 	 * Bound quota to defend quota against overflow during bandwidth shift.
11121 	 */
11122 	if (quota != RUNTIME_INF && quota > max_cfs_runtime)
11123 		return -EINVAL;
11124 
11125 	if (quota != RUNTIME_INF && (burst > quota ||
11126 				     burst + quota > max_cfs_runtime))
11127 		return -EINVAL;
11128 
11129 	/*
11130 	 * Prevent race between setting of cfs_rq->runtime_enabled and
11131 	 * unthrottle_offline_cfs_rqs().
11132 	 */
11133 	guard(cpus_read_lock)();
11134 	guard(mutex)(&cfs_constraints_mutex);
11135 
11136 	ret = __cfs_schedulable(tg, period, quota);
11137 	if (ret)
11138 		return ret;
11139 
11140 	runtime_enabled = quota != RUNTIME_INF;
11141 	runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
11142 	/*
11143 	 * If we need to toggle cfs_bandwidth_used, off->on must occur
11144 	 * before making related changes, and on->off must occur afterwards
11145 	 */
11146 	if (runtime_enabled && !runtime_was_enabled)
11147 		cfs_bandwidth_usage_inc();
11148 
11149 	scoped_guard (raw_spinlock_irq, &cfs_b->lock) {
11150 		cfs_b->period = ns_to_ktime(period);
11151 		cfs_b->quota = quota;
11152 		cfs_b->burst = burst;
11153 
11154 		__refill_cfs_bandwidth_runtime(cfs_b);
11155 
11156 		/*
11157 		 * Restart the period timer (if active) to handle new
11158 		 * period expiry:
11159 		 */
11160 		if (runtime_enabled)
11161 			start_cfs_bandwidth(cfs_b);
11162 	}
11163 
11164 	for_each_online_cpu(i) {
11165 		struct cfs_rq *cfs_rq = tg->cfs_rq[i];
11166 		struct rq *rq = cfs_rq->rq;
11167 
11168 		guard(rq_lock_irq)(rq);
11169 		cfs_rq->runtime_enabled = runtime_enabled;
11170 		cfs_rq->runtime_remaining = 0;
11171 
11172 		if (cfs_rq->throttled)
11173 			unthrottle_cfs_rq(cfs_rq);
11174 	}
11175 
11176 	if (runtime_was_enabled && !runtime_enabled)
11177 		cfs_bandwidth_usage_dec();
11178 
11179 	return 0;
11180 }
11181 
tg_set_cfs_quota(struct task_group * tg,long cfs_quota_us)11182 static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
11183 {
11184 	u64 quota, period, burst;
11185 
11186 	period = ktime_to_ns(tg->cfs_bandwidth.period);
11187 	burst = tg->cfs_bandwidth.burst;
11188 	if (cfs_quota_us < 0)
11189 		quota = RUNTIME_INF;
11190 	else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
11191 		quota = (u64)cfs_quota_us * NSEC_PER_USEC;
11192 	else
11193 		return -EINVAL;
11194 
11195 	return tg_set_cfs_bandwidth(tg, period, quota, burst);
11196 }
11197 
tg_get_cfs_quota(struct task_group * tg)11198 static long tg_get_cfs_quota(struct task_group *tg)
11199 {
11200 	u64 quota_us;
11201 
11202 	if (tg->cfs_bandwidth.quota == RUNTIME_INF)
11203 		return -1;
11204 
11205 	quota_us = tg->cfs_bandwidth.quota;
11206 	do_div(quota_us, NSEC_PER_USEC);
11207 
11208 	return quota_us;
11209 }
11210 
tg_set_cfs_period(struct task_group * tg,long cfs_period_us)11211 static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
11212 {
11213 	u64 quota, period, burst;
11214 
11215 	if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
11216 		return -EINVAL;
11217 
11218 	period = (u64)cfs_period_us * NSEC_PER_USEC;
11219 	quota = tg->cfs_bandwidth.quota;
11220 	burst = tg->cfs_bandwidth.burst;
11221 
11222 	return tg_set_cfs_bandwidth(tg, period, quota, burst);
11223 }
11224 
tg_get_cfs_period(struct task_group * tg)11225 static long tg_get_cfs_period(struct task_group *tg)
11226 {
11227 	u64 cfs_period_us;
11228 
11229 	cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
11230 	do_div(cfs_period_us, NSEC_PER_USEC);
11231 
11232 	return cfs_period_us;
11233 }
11234 
tg_set_cfs_burst(struct task_group * tg,long cfs_burst_us)11235 static int tg_set_cfs_burst(struct task_group *tg, long cfs_burst_us)
11236 {
11237 	u64 quota, period, burst;
11238 
11239 	if ((u64)cfs_burst_us > U64_MAX / NSEC_PER_USEC)
11240 		return -EINVAL;
11241 
11242 	burst = (u64)cfs_burst_us * NSEC_PER_USEC;
11243 	period = ktime_to_ns(tg->cfs_bandwidth.period);
11244 	quota = tg->cfs_bandwidth.quota;
11245 
11246 	return tg_set_cfs_bandwidth(tg, period, quota, burst);
11247 }
11248 
tg_get_cfs_burst(struct task_group * tg)11249 static long tg_get_cfs_burst(struct task_group *tg)
11250 {
11251 	u64 burst_us;
11252 
11253 	burst_us = tg->cfs_bandwidth.burst;
11254 	do_div(burst_us, NSEC_PER_USEC);
11255 
11256 	return burst_us;
11257 }
11258 
cpu_cfs_quota_read_s64(struct cgroup_subsys_state * css,struct cftype * cft)11259 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
11260 				  struct cftype *cft)
11261 {
11262 	return tg_get_cfs_quota(css_tg(css));
11263 }
11264 
cpu_cfs_quota_write_s64(struct cgroup_subsys_state * css,struct cftype * cftype,s64 cfs_quota_us)11265 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
11266 				   struct cftype *cftype, s64 cfs_quota_us)
11267 {
11268 	return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
11269 }
11270 
cpu_cfs_period_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)11271 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
11272 				   struct cftype *cft)
11273 {
11274 	return tg_get_cfs_period(css_tg(css));
11275 }
11276 
cpu_cfs_period_write_u64(struct cgroup_subsys_state * css,struct cftype * cftype,u64 cfs_period_us)11277 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
11278 				    struct cftype *cftype, u64 cfs_period_us)
11279 {
11280 	return tg_set_cfs_period(css_tg(css), cfs_period_us);
11281 }
11282 
cpu_cfs_burst_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)11283 static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css,
11284 				  struct cftype *cft)
11285 {
11286 	return tg_get_cfs_burst(css_tg(css));
11287 }
11288 
cpu_cfs_burst_write_u64(struct cgroup_subsys_state * css,struct cftype * cftype,u64 cfs_burst_us)11289 static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css,
11290 				   struct cftype *cftype, u64 cfs_burst_us)
11291 {
11292 	return tg_set_cfs_burst(css_tg(css), cfs_burst_us);
11293 }
11294 
11295 struct cfs_schedulable_data {
11296 	struct task_group *tg;
11297 	u64 period, quota;
11298 };
11299 
11300 /*
11301  * normalize group quota/period to be quota/max_period
11302  * note: units are usecs
11303  */
normalize_cfs_quota(struct task_group * tg,struct cfs_schedulable_data * d)11304 static u64 normalize_cfs_quota(struct task_group *tg,
11305 			       struct cfs_schedulable_data *d)
11306 {
11307 	u64 quota, period;
11308 
11309 	if (tg == d->tg) {
11310 		period = d->period;
11311 		quota = d->quota;
11312 	} else {
11313 		period = tg_get_cfs_period(tg);
11314 		quota = tg_get_cfs_quota(tg);
11315 	}
11316 
11317 	/* note: these should typically be equivalent */
11318 	if (quota == RUNTIME_INF || quota == -1)
11319 		return RUNTIME_INF;
11320 
11321 	return to_ratio(period, quota);
11322 }
11323 
tg_cfs_schedulable_down(struct task_group * tg,void * data)11324 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
11325 {
11326 	struct cfs_schedulable_data *d = data;
11327 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
11328 	s64 quota = 0, parent_quota = -1;
11329 
11330 	if (!tg->parent) {
11331 		quota = RUNTIME_INF;
11332 	} else {
11333 		struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
11334 
11335 		quota = normalize_cfs_quota(tg, d);
11336 		parent_quota = parent_b->hierarchical_quota;
11337 
11338 		/*
11339 		 * Ensure max(child_quota) <= parent_quota.  On cgroup2,
11340 		 * always take the non-RUNTIME_INF min.  On cgroup1, only
11341 		 * inherit when no limit is set. In both cases this is used
11342 		 * by the scheduler to determine if a given CFS task has a
11343 		 * bandwidth constraint at some higher level.
11344 		 */
11345 		if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
11346 			if (quota == RUNTIME_INF)
11347 				quota = parent_quota;
11348 			else if (parent_quota != RUNTIME_INF)
11349 				quota = min(quota, parent_quota);
11350 		} else {
11351 			if (quota == RUNTIME_INF)
11352 				quota = parent_quota;
11353 			else if (parent_quota != RUNTIME_INF && quota > parent_quota)
11354 				return -EINVAL;
11355 		}
11356 	}
11357 	cfs_b->hierarchical_quota = quota;
11358 
11359 	return 0;
11360 }
11361 
__cfs_schedulable(struct task_group * tg,u64 period,u64 quota)11362 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
11363 {
11364 	int ret;
11365 	struct cfs_schedulable_data data = {
11366 		.tg = tg,
11367 		.period = period,
11368 		.quota = quota,
11369 	};
11370 
11371 	if (quota != RUNTIME_INF) {
11372 		do_div(data.period, NSEC_PER_USEC);
11373 		do_div(data.quota, NSEC_PER_USEC);
11374 	}
11375 
11376 	rcu_read_lock();
11377 	ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
11378 	rcu_read_unlock();
11379 
11380 	return ret;
11381 }
11382 
cpu_cfs_stat_show(struct seq_file * sf,void * v)11383 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
11384 {
11385 	struct task_group *tg = css_tg(seq_css(sf));
11386 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
11387 
11388 	seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
11389 	seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
11390 	seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
11391 
11392 	if (schedstat_enabled() && tg != &root_task_group) {
11393 		struct sched_statistics *stats;
11394 		u64 ws = 0;
11395 		int i;
11396 
11397 		for_each_possible_cpu(i) {
11398 			stats = __schedstats_from_se(tg->se[i]);
11399 			ws += schedstat_val(stats->wait_sum);
11400 		}
11401 
11402 		seq_printf(sf, "wait_sum %llu\n", ws);
11403 	}
11404 
11405 	seq_printf(sf, "nr_bursts %d\n", cfs_b->nr_burst);
11406 	seq_printf(sf, "burst_time %llu\n", cfs_b->burst_time);
11407 
11408 	return 0;
11409 }
11410 
throttled_time_self(struct task_group * tg)11411 static u64 throttled_time_self(struct task_group *tg)
11412 {
11413 	int i;
11414 	u64 total = 0;
11415 
11416 	for_each_possible_cpu(i) {
11417 		total += READ_ONCE(tg->cfs_rq[i]->throttled_clock_self_time);
11418 	}
11419 
11420 	return total;
11421 }
11422 
cpu_cfs_local_stat_show(struct seq_file * sf,void * v)11423 static int cpu_cfs_local_stat_show(struct seq_file *sf, void *v)
11424 {
11425 	struct task_group *tg = css_tg(seq_css(sf));
11426 
11427 	seq_printf(sf, "throttled_time %llu\n", throttled_time_self(tg));
11428 
11429 	return 0;
11430 }
11431 #endif /* CONFIG_CFS_BANDWIDTH */
11432 #endif /* CONFIG_FAIR_GROUP_SCHED */
11433 
11434 #ifdef CONFIG_RT_GROUP_SCHED
cpu_rt_runtime_write(struct cgroup_subsys_state * css,struct cftype * cft,s64 val)11435 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
11436 				struct cftype *cft, s64 val)
11437 {
11438 	return sched_group_set_rt_runtime(css_tg(css), val);
11439 }
11440 
cpu_rt_runtime_read(struct cgroup_subsys_state * css,struct cftype * cft)11441 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
11442 			       struct cftype *cft)
11443 {
11444 	return sched_group_rt_runtime(css_tg(css));
11445 }
11446 
cpu_rt_period_write_uint(struct cgroup_subsys_state * css,struct cftype * cftype,u64 rt_period_us)11447 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
11448 				    struct cftype *cftype, u64 rt_period_us)
11449 {
11450 	return sched_group_set_rt_period(css_tg(css), rt_period_us);
11451 }
11452 
cpu_rt_period_read_uint(struct cgroup_subsys_state * css,struct cftype * cft)11453 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
11454 				   struct cftype *cft)
11455 {
11456 	return sched_group_rt_period(css_tg(css));
11457 }
11458 #endif /* CONFIG_RT_GROUP_SCHED */
11459 
11460 #ifdef CONFIG_FAIR_GROUP_SCHED
cpu_idle_read_s64(struct cgroup_subsys_state * css,struct cftype * cft)11461 static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css,
11462 			       struct cftype *cft)
11463 {
11464 	return css_tg(css)->idle;
11465 }
11466 
cpu_idle_write_s64(struct cgroup_subsys_state * css,struct cftype * cft,s64 idle)11467 static int cpu_idle_write_s64(struct cgroup_subsys_state *css,
11468 				struct cftype *cft, s64 idle)
11469 {
11470 	return sched_group_set_idle(css_tg(css), idle);
11471 }
11472 #endif
11473 
11474 static struct cftype cpu_legacy_files[] = {
11475 #ifdef CONFIG_FAIR_GROUP_SCHED
11476 	{
11477 		.name = "shares",
11478 		.read_u64 = cpu_shares_read_u64,
11479 		.write_u64 = cpu_shares_write_u64,
11480 	},
11481 	{
11482 		.name = "idle",
11483 		.read_s64 = cpu_idle_read_s64,
11484 		.write_s64 = cpu_idle_write_s64,
11485 	},
11486 #endif
11487 #ifdef CONFIG_CFS_BANDWIDTH
11488 	{
11489 		.name = "cfs_quota_us",
11490 		.read_s64 = cpu_cfs_quota_read_s64,
11491 		.write_s64 = cpu_cfs_quota_write_s64,
11492 	},
11493 	{
11494 		.name = "cfs_period_us",
11495 		.read_u64 = cpu_cfs_period_read_u64,
11496 		.write_u64 = cpu_cfs_period_write_u64,
11497 	},
11498 	{
11499 		.name = "cfs_burst_us",
11500 		.read_u64 = cpu_cfs_burst_read_u64,
11501 		.write_u64 = cpu_cfs_burst_write_u64,
11502 	},
11503 	{
11504 		.name = "stat",
11505 		.seq_show = cpu_cfs_stat_show,
11506 	},
11507 	{
11508 		.name = "stat.local",
11509 		.seq_show = cpu_cfs_local_stat_show,
11510 	},
11511 #endif
11512 #ifdef CONFIG_RT_GROUP_SCHED
11513 	{
11514 		.name = "rt_runtime_us",
11515 		.read_s64 = cpu_rt_runtime_read,
11516 		.write_s64 = cpu_rt_runtime_write,
11517 	},
11518 	{
11519 		.name = "rt_period_us",
11520 		.read_u64 = cpu_rt_period_read_uint,
11521 		.write_u64 = cpu_rt_period_write_uint,
11522 	},
11523 #endif
11524 #ifdef CONFIG_UCLAMP_TASK_GROUP
11525 	{
11526 		.name = "uclamp.min",
11527 		.flags = CFTYPE_NOT_ON_ROOT,
11528 		.seq_show = cpu_uclamp_min_show,
11529 		.write = cpu_uclamp_min_write,
11530 	},
11531 	{
11532 		.name = "uclamp.max",
11533 		.flags = CFTYPE_NOT_ON_ROOT,
11534 		.seq_show = cpu_uclamp_max_show,
11535 		.write = cpu_uclamp_max_write,
11536 	},
11537 	{
11538 		.name = "uclamp.latency_sensitive",
11539 		.flags = CFTYPE_NOT_ON_ROOT,
11540 		.read_u64 = cpu_uclamp_ls_read_u64,
11541 		.write_u64 = cpu_uclamp_ls_write_u64,
11542 	},
11543 #endif
11544 	{ }	/* Terminate */
11545 };
11546 
cpu_extra_stat_show(struct seq_file * sf,struct cgroup_subsys_state * css)11547 static int cpu_extra_stat_show(struct seq_file *sf,
11548 			       struct cgroup_subsys_state *css)
11549 {
11550 #ifdef CONFIG_CFS_BANDWIDTH
11551 	{
11552 		struct task_group *tg = css_tg(css);
11553 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
11554 		u64 throttled_usec, burst_usec;
11555 
11556 		throttled_usec = cfs_b->throttled_time;
11557 		do_div(throttled_usec, NSEC_PER_USEC);
11558 		burst_usec = cfs_b->burst_time;
11559 		do_div(burst_usec, NSEC_PER_USEC);
11560 
11561 		seq_printf(sf, "nr_periods %d\n"
11562 			   "nr_throttled %d\n"
11563 			   "throttled_usec %llu\n"
11564 			   "nr_bursts %d\n"
11565 			   "burst_usec %llu\n",
11566 			   cfs_b->nr_periods, cfs_b->nr_throttled,
11567 			   throttled_usec, cfs_b->nr_burst, burst_usec);
11568 	}
11569 #endif
11570 	return 0;
11571 }
11572 
cpu_local_stat_show(struct seq_file * sf,struct cgroup_subsys_state * css)11573 static int cpu_local_stat_show(struct seq_file *sf,
11574 			       struct cgroup_subsys_state *css)
11575 {
11576 #ifdef CONFIG_CFS_BANDWIDTH
11577 	{
11578 		struct task_group *tg = css_tg(css);
11579 		u64 throttled_self_usec;
11580 
11581 		throttled_self_usec = throttled_time_self(tg);
11582 		do_div(throttled_self_usec, NSEC_PER_USEC);
11583 
11584 		seq_printf(sf, "throttled_usec %llu\n",
11585 			   throttled_self_usec);
11586 	}
11587 #endif
11588 	return 0;
11589 }
11590 
11591 #ifdef CONFIG_FAIR_GROUP_SCHED
cpu_weight_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)11592 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
11593 			       struct cftype *cft)
11594 {
11595 	struct task_group *tg = css_tg(css);
11596 	u64 weight = scale_load_down(tg->shares);
11597 
11598 	return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
11599 }
11600 
cpu_weight_write_u64(struct cgroup_subsys_state * css,struct cftype * cft,u64 weight)11601 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
11602 				struct cftype *cft, u64 weight)
11603 {
11604 	/*
11605 	 * cgroup weight knobs should use the common MIN, DFL and MAX
11606 	 * values which are 1, 100 and 10000 respectively.  While it loses
11607 	 * a bit of range on both ends, it maps pretty well onto the shares
11608 	 * value used by scheduler and the round-trip conversions preserve
11609 	 * the original value over the entire range.
11610 	 */
11611 	if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
11612 		return -ERANGE;
11613 
11614 	weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
11615 
11616 	return sched_group_set_shares(css_tg(css), scale_load(weight));
11617 }
11618 
cpu_weight_nice_read_s64(struct cgroup_subsys_state * css,struct cftype * cft)11619 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
11620 				    struct cftype *cft)
11621 {
11622 	unsigned long weight = scale_load_down(css_tg(css)->shares);
11623 	int last_delta = INT_MAX;
11624 	int prio, delta;
11625 
11626 	/* find the closest nice value to the current weight */
11627 	for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
11628 		delta = abs(sched_prio_to_weight[prio] - weight);
11629 		if (delta >= last_delta)
11630 			break;
11631 		last_delta = delta;
11632 	}
11633 
11634 	return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
11635 }
11636 
cpu_weight_nice_write_s64(struct cgroup_subsys_state * css,struct cftype * cft,s64 nice)11637 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
11638 				     struct cftype *cft, s64 nice)
11639 {
11640 	unsigned long weight;
11641 	int idx;
11642 
11643 	if (nice < MIN_NICE || nice > MAX_NICE)
11644 		return -ERANGE;
11645 
11646 	idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
11647 	idx = array_index_nospec(idx, 40);
11648 	weight = sched_prio_to_weight[idx];
11649 
11650 	return sched_group_set_shares(css_tg(css), scale_load(weight));
11651 }
11652 #endif
11653 
cpu_period_quota_print(struct seq_file * sf,long period,long quota)11654 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
11655 						  long period, long quota)
11656 {
11657 	if (quota < 0)
11658 		seq_puts(sf, "max");
11659 	else
11660 		seq_printf(sf, "%ld", quota);
11661 
11662 	seq_printf(sf, " %ld\n", period);
11663 }
11664 
11665 /* caller should put the current value in *@periodp before calling */
cpu_period_quota_parse(char * buf,u64 * periodp,u64 * quotap)11666 static int __maybe_unused cpu_period_quota_parse(char *buf,
11667 						 u64 *periodp, u64 *quotap)
11668 {
11669 	char tok[21];	/* U64_MAX */
11670 
11671 	if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
11672 		return -EINVAL;
11673 
11674 	*periodp *= NSEC_PER_USEC;
11675 
11676 	if (sscanf(tok, "%llu", quotap))
11677 		*quotap *= NSEC_PER_USEC;
11678 	else if (!strcmp(tok, "max"))
11679 		*quotap = RUNTIME_INF;
11680 	else
11681 		return -EINVAL;
11682 
11683 	return 0;
11684 }
11685 
11686 #ifdef CONFIG_CFS_BANDWIDTH
cpu_max_show(struct seq_file * sf,void * v)11687 static int cpu_max_show(struct seq_file *sf, void *v)
11688 {
11689 	struct task_group *tg = css_tg(seq_css(sf));
11690 
11691 	cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
11692 	return 0;
11693 }
11694 
cpu_max_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)11695 static ssize_t cpu_max_write(struct kernfs_open_file *of,
11696 			     char *buf, size_t nbytes, loff_t off)
11697 {
11698 	struct task_group *tg = css_tg(of_css(of));
11699 	u64 period = tg_get_cfs_period(tg);
11700 	u64 burst = tg->cfs_bandwidth.burst;
11701 	u64 quota;
11702 	int ret;
11703 
11704 	ret = cpu_period_quota_parse(buf, &period, &quota);
11705 	if (!ret)
11706 		ret = tg_set_cfs_bandwidth(tg, period, quota, burst);
11707 	return ret ?: nbytes;
11708 }
11709 #endif
11710 
11711 static struct cftype cpu_files[] = {
11712 #ifdef CONFIG_FAIR_GROUP_SCHED
11713 	{
11714 		.name = "weight",
11715 		.flags = CFTYPE_NOT_ON_ROOT,
11716 		.read_u64 = cpu_weight_read_u64,
11717 		.write_u64 = cpu_weight_write_u64,
11718 	},
11719 	{
11720 		.name = "weight.nice",
11721 		.flags = CFTYPE_NOT_ON_ROOT,
11722 		.read_s64 = cpu_weight_nice_read_s64,
11723 		.write_s64 = cpu_weight_nice_write_s64,
11724 	},
11725 	{
11726 		.name = "idle",
11727 		.flags = CFTYPE_NOT_ON_ROOT,
11728 		.read_s64 = cpu_idle_read_s64,
11729 		.write_s64 = cpu_idle_write_s64,
11730 	},
11731 #endif
11732 #ifdef CONFIG_CFS_BANDWIDTH
11733 	{
11734 		.name = "max",
11735 		.flags = CFTYPE_NOT_ON_ROOT,
11736 		.seq_show = cpu_max_show,
11737 		.write = cpu_max_write,
11738 	},
11739 	{
11740 		.name = "max.burst",
11741 		.flags = CFTYPE_NOT_ON_ROOT,
11742 		.read_u64 = cpu_cfs_burst_read_u64,
11743 		.write_u64 = cpu_cfs_burst_write_u64,
11744 	},
11745 #endif
11746 #ifdef CONFIG_UCLAMP_TASK_GROUP
11747 	{
11748 		.name = "uclamp.min",
11749 		.flags = CFTYPE_NOT_ON_ROOT,
11750 		.seq_show = cpu_uclamp_min_show,
11751 		.write = cpu_uclamp_min_write,
11752 	},
11753 	{
11754 		.name = "uclamp.max",
11755 		.flags = CFTYPE_NOT_ON_ROOT,
11756 		.seq_show = cpu_uclamp_max_show,
11757 		.write = cpu_uclamp_max_write,
11758 	},
11759 	{
11760 		.name = "uclamp.latency_sensitive",
11761 		.flags = CFTYPE_NOT_ON_ROOT,
11762 		.read_u64 = cpu_uclamp_ls_read_u64,
11763 		.write_u64 = cpu_uclamp_ls_write_u64,
11764 	},
11765 #endif
11766 	{ }	/* terminate */
11767 };
11768 
11769 struct cgroup_subsys cpu_cgrp_subsys = {
11770 	.css_alloc	= cpu_cgroup_css_alloc,
11771 	.css_online	= cpu_cgroup_css_online,
11772 	.css_released	= cpu_cgroup_css_released,
11773 	.css_free	= cpu_cgroup_css_free,
11774 	.css_extra_stat_show = cpu_extra_stat_show,
11775 	.css_local_stat_show = cpu_local_stat_show,
11776 #ifdef CONFIG_RT_GROUP_SCHED
11777 	.can_attach	= cpu_cgroup_can_attach,
11778 #endif
11779 	.attach		= cpu_cgroup_attach,
11780 	.legacy_cftypes	= cpu_legacy_files,
11781 	.dfl_cftypes	= cpu_files,
11782 	.early_init	= true,
11783 	.threaded	= true,
11784 };
11785 EXPORT_SYMBOL_GPL(cpu_cgrp_subsys);
11786 #endif	/* CONFIG_CGROUP_SCHED */
11787 
dump_cpu_task(int cpu)11788 void dump_cpu_task(int cpu)
11789 {
11790 	if (cpu == smp_processor_id() && in_hardirq()) {
11791 		struct pt_regs *regs;
11792 
11793 		regs = get_irq_regs();
11794 		if (regs) {
11795 			show_regs(regs);
11796 			return;
11797 		}
11798 	}
11799 
11800 	if (trigger_single_cpu_backtrace(cpu))
11801 		return;
11802 
11803 	pr_info("Task dump for CPU %d:\n", cpu);
11804 	sched_show_task(cpu_curr(cpu));
11805 }
11806 
11807 /*
11808  * Nice levels are multiplicative, with a gentle 10% change for every
11809  * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
11810  * nice 1, it will get ~10% less CPU time than another CPU-bound task
11811  * that remained on nice 0.
11812  *
11813  * The "10% effect" is relative and cumulative: from _any_ nice level,
11814  * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
11815  * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
11816  * If a task goes up by ~10% and another task goes down by ~10% then
11817  * the relative distance between them is ~25%.)
11818  */
11819 const int sched_prio_to_weight[40] = {
11820  /* -20 */     88761,     71755,     56483,     46273,     36291,
11821  /* -15 */     29154,     23254,     18705,     14949,     11916,
11822  /* -10 */      9548,      7620,      6100,      4904,      3906,
11823  /*  -5 */      3121,      2501,      1991,      1586,      1277,
11824  /*   0 */      1024,       820,       655,       526,       423,
11825  /*   5 */       335,       272,       215,       172,       137,
11826  /*  10 */       110,        87,        70,        56,        45,
11827  /*  15 */        36,        29,        23,        18,        15,
11828 };
11829 
11830 /*
11831  * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
11832  *
11833  * In cases where the weight does not change often, we can use the
11834  * precalculated inverse to speed up arithmetics by turning divisions
11835  * into multiplications:
11836  */
11837 const u32 sched_prio_to_wmult[40] = {
11838  /* -20 */     48388,     59856,     76040,     92818,    118348,
11839  /* -15 */    147320,    184698,    229616,    287308,    360437,
11840  /* -10 */    449829,    563644,    704093,    875809,   1099582,
11841  /*  -5 */   1376151,   1717300,   2157191,   2708050,   3363326,
11842  /*   0 */   4194304,   5237765,   6557202,   8165337,  10153587,
11843  /*   5 */  12820798,  15790321,  19976592,  24970740,  31350126,
11844  /*  10 */  39045157,  49367440,  61356676,  76695844,  95443717,
11845  /*  15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
11846 };
11847 
call_trace_sched_update_nr_running(struct rq * rq,int count)11848 void call_trace_sched_update_nr_running(struct rq *rq, int count)
11849 {
11850         trace_sched_update_nr_running_tp(rq, count);
11851 }
11852 
11853 #ifdef CONFIG_SCHED_MM_CID
11854 
11855 /*
11856  * @cid_lock: Guarantee forward-progress of cid allocation.
11857  *
11858  * Concurrency ID allocation within a bitmap is mostly lock-free. The cid_lock
11859  * is only used when contention is detected by the lock-free allocation so
11860  * forward progress can be guaranteed.
11861  */
11862 DEFINE_RAW_SPINLOCK(cid_lock);
11863 
11864 /*
11865  * @use_cid_lock: Select cid allocation behavior: lock-free vs spinlock.
11866  *
11867  * When @use_cid_lock is 0, the cid allocation is lock-free. When contention is
11868  * detected, it is set to 1 to ensure that all newly coming allocations are
11869  * serialized by @cid_lock until the allocation which detected contention
11870  * completes and sets @use_cid_lock back to 0. This guarantees forward progress
11871  * of a cid allocation.
11872  */
11873 int use_cid_lock;
11874 
11875 /*
11876  * mm_cid remote-clear implements a lock-free algorithm to clear per-mm/cpu cid
11877  * concurrently with respect to the execution of the source runqueue context
11878  * switch.
11879  *
11880  * There is one basic properties we want to guarantee here:
11881  *
11882  * (1) Remote-clear should _never_ mark a per-cpu cid UNSET when it is actively
11883  * used by a task. That would lead to concurrent allocation of the cid and
11884  * userspace corruption.
11885  *
11886  * Provide this guarantee by introducing a Dekker memory ordering to guarantee
11887  * that a pair of loads observe at least one of a pair of stores, which can be
11888  * shown as:
11889  *
11890  *      X = Y = 0
11891  *
11892  *      w[X]=1          w[Y]=1
11893  *      MB              MB
11894  *      r[Y]=y          r[X]=x
11895  *
11896  * Which guarantees that x==0 && y==0 is impossible. But rather than using
11897  * values 0 and 1, this algorithm cares about specific state transitions of the
11898  * runqueue current task (as updated by the scheduler context switch), and the
11899  * per-mm/cpu cid value.
11900  *
11901  * Let's introduce task (Y) which has task->mm == mm and task (N) which has
11902  * task->mm != mm for the rest of the discussion. There are two scheduler state
11903  * transitions on context switch we care about:
11904  *
11905  * (TSA) Store to rq->curr with transition from (N) to (Y)
11906  *
11907  * (TSB) Store to rq->curr with transition from (Y) to (N)
11908  *
11909  * On the remote-clear side, there is one transition we care about:
11910  *
11911  * (TMA) cmpxchg to *pcpu_cid to set the LAZY flag
11912  *
11913  * There is also a transition to UNSET state which can be performed from all
11914  * sides (scheduler, remote-clear). It is always performed with a cmpxchg which
11915  * guarantees that only a single thread will succeed:
11916  *
11917  * (TMB) cmpxchg to *pcpu_cid to mark UNSET
11918  *
11919  * Just to be clear, what we do _not_ want to happen is a transition to UNSET
11920  * when a thread is actively using the cid (property (1)).
11921  *
11922  * Let's looks at the relevant combinations of TSA/TSB, and TMA transitions.
11923  *
11924  * Scenario A) (TSA)+(TMA) (from next task perspective)
11925  *
11926  * CPU0                                      CPU1
11927  *
11928  * Context switch CS-1                       Remote-clear
11929  *   - store to rq->curr: (N)->(Y) (TSA)     - cmpxchg to *pcpu_id to LAZY (TMA)
11930  *                                             (implied barrier after cmpxchg)
11931  *   - switch_mm_cid()
11932  *     - memory barrier (see switch_mm_cid()
11933  *       comment explaining how this barrier
11934  *       is combined with other scheduler
11935  *       barriers)
11936  *     - mm_cid_get (next)
11937  *       - READ_ONCE(*pcpu_cid)              - rcu_dereference(src_rq->curr)
11938  *
11939  * This Dekker ensures that either task (Y) is observed by the
11940  * rcu_dereference() or the LAZY flag is observed by READ_ONCE(), or both are
11941  * observed.
11942  *
11943  * If task (Y) store is observed by rcu_dereference(), it means that there is
11944  * still an active task on the cpu. Remote-clear will therefore not transition
11945  * to UNSET, which fulfills property (1).
11946  *
11947  * If task (Y) is not observed, but the lazy flag is observed by READ_ONCE(),
11948  * it will move its state to UNSET, which clears the percpu cid perhaps
11949  * uselessly (which is not an issue for correctness). Because task (Y) is not
11950  * observed, CPU1 can move ahead to set the state to UNSET. Because moving
11951  * state to UNSET is done with a cmpxchg expecting that the old state has the
11952  * LAZY flag set, only one thread will successfully UNSET.
11953  *
11954  * If both states (LAZY flag and task (Y)) are observed, the thread on CPU0
11955  * will observe the LAZY flag and transition to UNSET (perhaps uselessly), and
11956  * CPU1 will observe task (Y) and do nothing more, which is fine.
11957  *
11958  * What we are effectively preventing with this Dekker is a scenario where
11959  * neither LAZY flag nor store (Y) are observed, which would fail property (1)
11960  * because this would UNSET a cid which is actively used.
11961  */
11962 
sched_mm_cid_migrate_from(struct task_struct * t)11963 void sched_mm_cid_migrate_from(struct task_struct *t)
11964 {
11965 	t->migrate_from_cpu = task_cpu(t);
11966 }
11967 
11968 static
__sched_mm_cid_migrate_from_fetch_cid(struct rq * src_rq,struct task_struct * t,struct mm_cid * src_pcpu_cid)11969 int __sched_mm_cid_migrate_from_fetch_cid(struct rq *src_rq,
11970 					  struct task_struct *t,
11971 					  struct mm_cid *src_pcpu_cid)
11972 {
11973 	struct mm_struct *mm = t->mm;
11974 	struct task_struct *src_task;
11975 	int src_cid, last_mm_cid;
11976 
11977 	if (!mm)
11978 		return -1;
11979 
11980 	last_mm_cid = t->last_mm_cid;
11981 	/*
11982 	 * If the migrated task has no last cid, or if the current
11983 	 * task on src rq uses the cid, it means the source cid does not need
11984 	 * to be moved to the destination cpu.
11985 	 */
11986 	if (last_mm_cid == -1)
11987 		return -1;
11988 	src_cid = READ_ONCE(src_pcpu_cid->cid);
11989 	if (!mm_cid_is_valid(src_cid) || last_mm_cid != src_cid)
11990 		return -1;
11991 
11992 	/*
11993 	 * If we observe an active task using the mm on this rq, it means we
11994 	 * are not the last task to be migrated from this cpu for this mm, so
11995 	 * there is no need to move src_cid to the destination cpu.
11996 	 */
11997 	rcu_read_lock();
11998 	src_task = rcu_dereference(src_rq->curr);
11999 	if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
12000 		rcu_read_unlock();
12001 		t->last_mm_cid = -1;
12002 		return -1;
12003 	}
12004 	rcu_read_unlock();
12005 
12006 	return src_cid;
12007 }
12008 
12009 static
__sched_mm_cid_migrate_from_try_steal_cid(struct rq * src_rq,struct task_struct * t,struct mm_cid * src_pcpu_cid,int src_cid)12010 int __sched_mm_cid_migrate_from_try_steal_cid(struct rq *src_rq,
12011 					      struct task_struct *t,
12012 					      struct mm_cid *src_pcpu_cid,
12013 					      int src_cid)
12014 {
12015 	struct task_struct *src_task;
12016 	struct mm_struct *mm = t->mm;
12017 	int lazy_cid;
12018 
12019 	if (src_cid == -1)
12020 		return -1;
12021 
12022 	/*
12023 	 * Attempt to clear the source cpu cid to move it to the destination
12024 	 * cpu.
12025 	 */
12026 	lazy_cid = mm_cid_set_lazy_put(src_cid);
12027 	if (!try_cmpxchg(&src_pcpu_cid->cid, &src_cid, lazy_cid))
12028 		return -1;
12029 
12030 	/*
12031 	 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
12032 	 * rq->curr->mm matches the scheduler barrier in context_switch()
12033 	 * between store to rq->curr and load of prev and next task's
12034 	 * per-mm/cpu cid.
12035 	 *
12036 	 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
12037 	 * rq->curr->mm_cid_active matches the barrier in
12038 	 * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
12039 	 * sched_mm_cid_after_execve() between store to t->mm_cid_active and
12040 	 * load of per-mm/cpu cid.
12041 	 */
12042 
12043 	/*
12044 	 * If we observe an active task using the mm on this rq after setting
12045 	 * the lazy-put flag, this task will be responsible for transitioning
12046 	 * from lazy-put flag set to MM_CID_UNSET.
12047 	 */
12048 	rcu_read_lock();
12049 	src_task = rcu_dereference(src_rq->curr);
12050 	if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
12051 		rcu_read_unlock();
12052 		/*
12053 		 * We observed an active task for this mm, there is therefore
12054 		 * no point in moving this cid to the destination cpu.
12055 		 */
12056 		t->last_mm_cid = -1;
12057 		return -1;
12058 	}
12059 	rcu_read_unlock();
12060 
12061 	/*
12062 	 * The src_cid is unused, so it can be unset.
12063 	 */
12064 	if (!try_cmpxchg(&src_pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
12065 		return -1;
12066 	return src_cid;
12067 }
12068 
12069 /*
12070  * Migration to dst cpu. Called with dst_rq lock held.
12071  * Interrupts are disabled, which keeps the window of cid ownership without the
12072  * source rq lock held small.
12073  */
sched_mm_cid_migrate_to(struct rq * dst_rq,struct task_struct * t)12074 void sched_mm_cid_migrate_to(struct rq *dst_rq, struct task_struct *t)
12075 {
12076 	struct mm_cid *src_pcpu_cid, *dst_pcpu_cid;
12077 	struct mm_struct *mm = t->mm;
12078 	int src_cid, dst_cid, src_cpu;
12079 	struct rq *src_rq;
12080 
12081 	lockdep_assert_rq_held(dst_rq);
12082 
12083 	if (!mm)
12084 		return;
12085 	src_cpu = t->migrate_from_cpu;
12086 	if (src_cpu == -1) {
12087 		t->last_mm_cid = -1;
12088 		return;
12089 	}
12090 	/*
12091 	 * Move the src cid if the dst cid is unset. This keeps id
12092 	 * allocation closest to 0 in cases where few threads migrate around
12093 	 * many cpus.
12094 	 *
12095 	 * If destination cid is already set, we may have to just clear
12096 	 * the src cid to ensure compactness in frequent migrations
12097 	 * scenarios.
12098 	 *
12099 	 * It is not useful to clear the src cid when the number of threads is
12100 	 * greater or equal to the number of allowed cpus, because user-space
12101 	 * can expect that the number of allowed cids can reach the number of
12102 	 * allowed cpus.
12103 	 */
12104 	dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
12105 	dst_cid = READ_ONCE(dst_pcpu_cid->cid);
12106 	if (!mm_cid_is_unset(dst_cid) &&
12107 	    atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
12108 		return;
12109 	src_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, src_cpu);
12110 	src_rq = cpu_rq(src_cpu);
12111 	src_cid = __sched_mm_cid_migrate_from_fetch_cid(src_rq, t, src_pcpu_cid);
12112 	if (src_cid == -1)
12113 		return;
12114 	src_cid = __sched_mm_cid_migrate_from_try_steal_cid(src_rq, t, src_pcpu_cid,
12115 							    src_cid);
12116 	if (src_cid == -1)
12117 		return;
12118 	if (!mm_cid_is_unset(dst_cid)) {
12119 		__mm_cid_put(mm, src_cid);
12120 		return;
12121 	}
12122 	/* Move src_cid to dst cpu. */
12123 	mm_cid_snapshot_time(dst_rq, mm);
12124 	WRITE_ONCE(dst_pcpu_cid->cid, src_cid);
12125 }
12126 
sched_mm_cid_remote_clear(struct mm_struct * mm,struct mm_cid * pcpu_cid,int cpu)12127 static void sched_mm_cid_remote_clear(struct mm_struct *mm, struct mm_cid *pcpu_cid,
12128 				      int cpu)
12129 {
12130 	struct rq *rq = cpu_rq(cpu);
12131 	struct task_struct *t;
12132 	unsigned long flags;
12133 	int cid, lazy_cid;
12134 
12135 	cid = READ_ONCE(pcpu_cid->cid);
12136 	if (!mm_cid_is_valid(cid))
12137 		return;
12138 
12139 	/*
12140 	 * Clear the cpu cid if it is set to keep cid allocation compact.  If
12141 	 * there happens to be other tasks left on the source cpu using this
12142 	 * mm, the next task using this mm will reallocate its cid on context
12143 	 * switch.
12144 	 */
12145 	lazy_cid = mm_cid_set_lazy_put(cid);
12146 	if (!try_cmpxchg(&pcpu_cid->cid, &cid, lazy_cid))
12147 		return;
12148 
12149 	/*
12150 	 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
12151 	 * rq->curr->mm matches the scheduler barrier in context_switch()
12152 	 * between store to rq->curr and load of prev and next task's
12153 	 * per-mm/cpu cid.
12154 	 *
12155 	 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
12156 	 * rq->curr->mm_cid_active matches the barrier in
12157 	 * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
12158 	 * sched_mm_cid_after_execve() between store to t->mm_cid_active and
12159 	 * load of per-mm/cpu cid.
12160 	 */
12161 
12162 	/*
12163 	 * If we observe an active task using the mm on this rq after setting
12164 	 * the lazy-put flag, that task will be responsible for transitioning
12165 	 * from lazy-put flag set to MM_CID_UNSET.
12166 	 */
12167 	rcu_read_lock();
12168 	t = rcu_dereference(rq->curr);
12169 	if (READ_ONCE(t->mm_cid_active) && t->mm == mm) {
12170 		rcu_read_unlock();
12171 		return;
12172 	}
12173 	rcu_read_unlock();
12174 
12175 	/*
12176 	 * The cid is unused, so it can be unset.
12177 	 * Disable interrupts to keep the window of cid ownership without rq
12178 	 * lock small.
12179 	 */
12180 	local_irq_save(flags);
12181 	if (try_cmpxchg(&pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
12182 		__mm_cid_put(mm, cid);
12183 	local_irq_restore(flags);
12184 }
12185 
sched_mm_cid_remote_clear_old(struct mm_struct * mm,int cpu)12186 static void sched_mm_cid_remote_clear_old(struct mm_struct *mm, int cpu)
12187 {
12188 	struct rq *rq = cpu_rq(cpu);
12189 	struct mm_cid *pcpu_cid;
12190 	struct task_struct *curr;
12191 	u64 rq_clock;
12192 
12193 	/*
12194 	 * rq->clock load is racy on 32-bit but one spurious clear once in a
12195 	 * while is irrelevant.
12196 	 */
12197 	rq_clock = READ_ONCE(rq->clock);
12198 	pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
12199 
12200 	/*
12201 	 * In order to take care of infrequently scheduled tasks, bump the time
12202 	 * snapshot associated with this cid if an active task using the mm is
12203 	 * observed on this rq.
12204 	 */
12205 	rcu_read_lock();
12206 	curr = rcu_dereference(rq->curr);
12207 	if (READ_ONCE(curr->mm_cid_active) && curr->mm == mm) {
12208 		WRITE_ONCE(pcpu_cid->time, rq_clock);
12209 		rcu_read_unlock();
12210 		return;
12211 	}
12212 	rcu_read_unlock();
12213 
12214 	if (rq_clock < pcpu_cid->time + SCHED_MM_CID_PERIOD_NS)
12215 		return;
12216 	sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
12217 }
12218 
sched_mm_cid_remote_clear_weight(struct mm_struct * mm,int cpu,int weight)12219 static void sched_mm_cid_remote_clear_weight(struct mm_struct *mm, int cpu,
12220 					     int weight)
12221 {
12222 	struct mm_cid *pcpu_cid;
12223 	int cid;
12224 
12225 	pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
12226 	cid = READ_ONCE(pcpu_cid->cid);
12227 	if (!mm_cid_is_valid(cid) || cid < weight)
12228 		return;
12229 	sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
12230 }
12231 
task_mm_cid_work(struct callback_head * work)12232 static void task_mm_cid_work(struct callback_head *work)
12233 {
12234 	unsigned long now = jiffies, old_scan, next_scan;
12235 	struct task_struct *t = current;
12236 	struct cpumask *cidmask;
12237 	struct mm_struct *mm;
12238 	int weight, cpu;
12239 
12240 	SCHED_WARN_ON(t != container_of(work, struct task_struct, cid_work));
12241 
12242 	work->next = work;	/* Prevent double-add */
12243 	if (t->flags & PF_EXITING)
12244 		return;
12245 	mm = t->mm;
12246 	if (!mm)
12247 		return;
12248 	old_scan = READ_ONCE(mm->mm_cid_next_scan);
12249 	next_scan = now + msecs_to_jiffies(MM_CID_SCAN_DELAY);
12250 	if (!old_scan) {
12251 		unsigned long res;
12252 
12253 		res = cmpxchg(&mm->mm_cid_next_scan, old_scan, next_scan);
12254 		if (res != old_scan)
12255 			old_scan = res;
12256 		else
12257 			old_scan = next_scan;
12258 	}
12259 	if (time_before(now, old_scan))
12260 		return;
12261 	if (!try_cmpxchg(&mm->mm_cid_next_scan, &old_scan, next_scan))
12262 		return;
12263 	cidmask = mm_cidmask(mm);
12264 	/* Clear cids that were not recently used. */
12265 	for_each_possible_cpu(cpu)
12266 		sched_mm_cid_remote_clear_old(mm, cpu);
12267 	weight = cpumask_weight(cidmask);
12268 	/*
12269 	 * Clear cids that are greater or equal to the cidmask weight to
12270 	 * recompact it.
12271 	 */
12272 	for_each_possible_cpu(cpu)
12273 		sched_mm_cid_remote_clear_weight(mm, cpu, weight);
12274 }
12275 
init_sched_mm_cid(struct task_struct * t)12276 void init_sched_mm_cid(struct task_struct *t)
12277 {
12278 	struct mm_struct *mm = t->mm;
12279 	int mm_users = 0;
12280 
12281 	if (mm) {
12282 		mm_users = atomic_read(&mm->mm_users);
12283 		if (mm_users == 1)
12284 			mm->mm_cid_next_scan = jiffies + msecs_to_jiffies(MM_CID_SCAN_DELAY);
12285 	}
12286 	t->cid_work.next = &t->cid_work;	/* Protect against double add */
12287 	init_task_work(&t->cid_work, task_mm_cid_work);
12288 }
12289 
task_tick_mm_cid(struct rq * rq,struct task_struct * curr)12290 void task_tick_mm_cid(struct rq *rq, struct task_struct *curr)
12291 {
12292 	struct callback_head *work = &curr->cid_work;
12293 	unsigned long now = jiffies;
12294 
12295 	if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) ||
12296 	    work->next != work)
12297 		return;
12298 	if (time_before(now, READ_ONCE(curr->mm->mm_cid_next_scan)))
12299 		return;
12300 	task_work_add(curr, work, TWA_RESUME);
12301 }
12302 
sched_mm_cid_exit_signals(struct task_struct * t)12303 void sched_mm_cid_exit_signals(struct task_struct *t)
12304 {
12305 	struct mm_struct *mm = t->mm;
12306 	struct rq_flags rf;
12307 	struct rq *rq;
12308 
12309 	if (!mm)
12310 		return;
12311 
12312 	preempt_disable();
12313 	rq = this_rq();
12314 	rq_lock_irqsave(rq, &rf);
12315 	preempt_enable_no_resched();	/* holding spinlock */
12316 	WRITE_ONCE(t->mm_cid_active, 0);
12317 	/*
12318 	 * Store t->mm_cid_active before loading per-mm/cpu cid.
12319 	 * Matches barrier in sched_mm_cid_remote_clear_old().
12320 	 */
12321 	smp_mb();
12322 	mm_cid_put(mm);
12323 	t->last_mm_cid = t->mm_cid = -1;
12324 	rq_unlock_irqrestore(rq, &rf);
12325 }
12326 
sched_mm_cid_before_execve(struct task_struct * t)12327 void sched_mm_cid_before_execve(struct task_struct *t)
12328 {
12329 	struct mm_struct *mm = t->mm;
12330 	struct rq_flags rf;
12331 	struct rq *rq;
12332 
12333 	if (!mm)
12334 		return;
12335 
12336 	preempt_disable();
12337 	rq = this_rq();
12338 	rq_lock_irqsave(rq, &rf);
12339 	preempt_enable_no_resched();	/* holding spinlock */
12340 	WRITE_ONCE(t->mm_cid_active, 0);
12341 	/*
12342 	 * Store t->mm_cid_active before loading per-mm/cpu cid.
12343 	 * Matches barrier in sched_mm_cid_remote_clear_old().
12344 	 */
12345 	smp_mb();
12346 	mm_cid_put(mm);
12347 	t->last_mm_cid = t->mm_cid = -1;
12348 	rq_unlock_irqrestore(rq, &rf);
12349 }
12350 
sched_mm_cid_after_execve(struct task_struct * t)12351 void sched_mm_cid_after_execve(struct task_struct *t)
12352 {
12353 	struct mm_struct *mm = t->mm;
12354 	struct rq_flags rf;
12355 	struct rq *rq;
12356 
12357 	if (!mm)
12358 		return;
12359 
12360 	preempt_disable();
12361 	rq = this_rq();
12362 	rq_lock_irqsave(rq, &rf);
12363 	preempt_enable_no_resched();	/* holding spinlock */
12364 	WRITE_ONCE(t->mm_cid_active, 1);
12365 	/*
12366 	 * Store t->mm_cid_active before loading per-mm/cpu cid.
12367 	 * Matches barrier in sched_mm_cid_remote_clear_old().
12368 	 */
12369 	smp_mb();
12370 	t->last_mm_cid = t->mm_cid = mm_cid_get(rq, mm);
12371 	rq_unlock_irqrestore(rq, &rf);
12372 	rseq_set_notify_resume(t);
12373 }
12374 
sched_mm_cid_fork(struct task_struct * t)12375 void sched_mm_cid_fork(struct task_struct *t)
12376 {
12377 	WARN_ON_ONCE(!t->mm || t->mm_cid != -1);
12378 	t->mm_cid_active = 1;
12379 }
12380 #endif
12381