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