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