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