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