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