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