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