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