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