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