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