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