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