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