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