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