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