xref: /linux/kernel/sched/core.c (revision 2a52ca7c98960aafb0eca9ef96b2d0c932171357)
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 
5520 	rq_unlock(rq, &rf);
5521 
5522 	if (sched_feat(LATENCY_WARN) && resched_latency)
5523 		resched_latency_warn(cpu, resched_latency);
5524 
5525 	perf_event_task_tick();
5526 
5527 	if (curr->flags & PF_WQ_WORKER)
5528 		wq_worker_tick(curr);
5529 
5530 #ifdef CONFIG_SMP
5531 	if (!scx_switched_all()) {
5532 		rq->idle_balance = idle_cpu(cpu);
5533 		sched_balance_trigger(rq);
5534 	}
5535 #endif
5536 }
5537 
5538 #ifdef CONFIG_NO_HZ_FULL
5539 
5540 struct tick_work {
5541 	int			cpu;
5542 	atomic_t		state;
5543 	struct delayed_work	work;
5544 };
5545 /* Values for ->state, see diagram below. */
5546 #define TICK_SCHED_REMOTE_OFFLINE	0
5547 #define TICK_SCHED_REMOTE_OFFLINING	1
5548 #define TICK_SCHED_REMOTE_RUNNING	2
5549 
5550 /*
5551  * State diagram for ->state:
5552  *
5553  *
5554  *          TICK_SCHED_REMOTE_OFFLINE
5555  *                    |   ^
5556  *                    |   |
5557  *                    |   | sched_tick_remote()
5558  *                    |   |
5559  *                    |   |
5560  *                    +--TICK_SCHED_REMOTE_OFFLINING
5561  *                    |   ^
5562  *                    |   |
5563  * sched_tick_start() |   | sched_tick_stop()
5564  *                    |   |
5565  *                    V   |
5566  *          TICK_SCHED_REMOTE_RUNNING
5567  *
5568  *
5569  * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
5570  * and sched_tick_start() are happy to leave the state in RUNNING.
5571  */
5572 
5573 static struct tick_work __percpu *tick_work_cpu;
5574 
5575 static void sched_tick_remote(struct work_struct *work)
5576 {
5577 	struct delayed_work *dwork = to_delayed_work(work);
5578 	struct tick_work *twork = container_of(dwork, struct tick_work, work);
5579 	int cpu = twork->cpu;
5580 	struct rq *rq = cpu_rq(cpu);
5581 	int os;
5582 
5583 	/*
5584 	 * Handle the tick only if it appears the remote CPU is running in full
5585 	 * dynticks mode. The check is racy by nature, but missing a tick or
5586 	 * having one too much is no big deal because the scheduler tick updates
5587 	 * statistics and checks timeslices in a time-independent way, regardless
5588 	 * of when exactly it is running.
5589 	 */
5590 	if (tick_nohz_tick_stopped_cpu(cpu)) {
5591 		guard(rq_lock_irq)(rq);
5592 		struct task_struct *curr = rq->curr;
5593 
5594 		if (cpu_online(cpu)) {
5595 			update_rq_clock(rq);
5596 
5597 			if (!is_idle_task(curr)) {
5598 				/*
5599 				 * Make sure the next tick runs within a
5600 				 * reasonable amount of time.
5601 				 */
5602 				u64 delta = rq_clock_task(rq) - curr->se.exec_start;
5603 				WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
5604 			}
5605 			curr->sched_class->task_tick(rq, curr, 0);
5606 
5607 			calc_load_nohz_remote(rq);
5608 		}
5609 	}
5610 
5611 	/*
5612 	 * Run the remote tick once per second (1Hz). This arbitrary
5613 	 * frequency is large enough to avoid overload but short enough
5614 	 * to keep scheduler internal stats reasonably up to date.  But
5615 	 * first update state to reflect hotplug activity if required.
5616 	 */
5617 	os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
5618 	WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
5619 	if (os == TICK_SCHED_REMOTE_RUNNING)
5620 		queue_delayed_work(system_unbound_wq, dwork, HZ);
5621 }
5622 
5623 static void sched_tick_start(int cpu)
5624 {
5625 	int os;
5626 	struct tick_work *twork;
5627 
5628 	if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5629 		return;
5630 
5631 	WARN_ON_ONCE(!tick_work_cpu);
5632 
5633 	twork = per_cpu_ptr(tick_work_cpu, cpu);
5634 	os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
5635 	WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
5636 	if (os == TICK_SCHED_REMOTE_OFFLINE) {
5637 		twork->cpu = cpu;
5638 		INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
5639 		queue_delayed_work(system_unbound_wq, &twork->work, HZ);
5640 	}
5641 }
5642 
5643 #ifdef CONFIG_HOTPLUG_CPU
5644 static void sched_tick_stop(int cpu)
5645 {
5646 	struct tick_work *twork;
5647 	int os;
5648 
5649 	if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5650 		return;
5651 
5652 	WARN_ON_ONCE(!tick_work_cpu);
5653 
5654 	twork = per_cpu_ptr(tick_work_cpu, cpu);
5655 	/* There cannot be competing actions, but don't rely on stop-machine. */
5656 	os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
5657 	WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
5658 	/* Don't cancel, as this would mess up the state machine. */
5659 }
5660 #endif /* CONFIG_HOTPLUG_CPU */
5661 
5662 int __init sched_tick_offload_init(void)
5663 {
5664 	tick_work_cpu = alloc_percpu(struct tick_work);
5665 	BUG_ON(!tick_work_cpu);
5666 	return 0;
5667 }
5668 
5669 #else /* !CONFIG_NO_HZ_FULL */
5670 static inline void sched_tick_start(int cpu) { }
5671 static inline void sched_tick_stop(int cpu) { }
5672 #endif
5673 
5674 #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
5675 				defined(CONFIG_TRACE_PREEMPT_TOGGLE))
5676 /*
5677  * If the value passed in is equal to the current preempt count
5678  * then we just disabled preemption. Start timing the latency.
5679  */
5680 static inline void preempt_latency_start(int val)
5681 {
5682 	if (preempt_count() == val) {
5683 		unsigned long ip = get_lock_parent_ip();
5684 #ifdef CONFIG_DEBUG_PREEMPT
5685 		current->preempt_disable_ip = ip;
5686 #endif
5687 		trace_preempt_off(CALLER_ADDR0, ip);
5688 	}
5689 }
5690 
5691 void preempt_count_add(int val)
5692 {
5693 #ifdef CONFIG_DEBUG_PREEMPT
5694 	/*
5695 	 * Underflow?
5696 	 */
5697 	if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5698 		return;
5699 #endif
5700 	__preempt_count_add(val);
5701 #ifdef CONFIG_DEBUG_PREEMPT
5702 	/*
5703 	 * Spinlock count overflowing soon?
5704 	 */
5705 	DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5706 				PREEMPT_MASK - 10);
5707 #endif
5708 	preempt_latency_start(val);
5709 }
5710 EXPORT_SYMBOL(preempt_count_add);
5711 NOKPROBE_SYMBOL(preempt_count_add);
5712 
5713 /*
5714  * If the value passed in equals to the current preempt count
5715  * then we just enabled preemption. Stop timing the latency.
5716  */
5717 static inline void preempt_latency_stop(int val)
5718 {
5719 	if (preempt_count() == val)
5720 		trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
5721 }
5722 
5723 void preempt_count_sub(int val)
5724 {
5725 #ifdef CONFIG_DEBUG_PREEMPT
5726 	/*
5727 	 * Underflow?
5728 	 */
5729 	if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
5730 		return;
5731 	/*
5732 	 * Is the spinlock portion underflowing?
5733 	 */
5734 	if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
5735 			!(preempt_count() & PREEMPT_MASK)))
5736 		return;
5737 #endif
5738 
5739 	preempt_latency_stop(val);
5740 	__preempt_count_sub(val);
5741 }
5742 EXPORT_SYMBOL(preempt_count_sub);
5743 NOKPROBE_SYMBOL(preempt_count_sub);
5744 
5745 #else
5746 static inline void preempt_latency_start(int val) { }
5747 static inline void preempt_latency_stop(int val) { }
5748 #endif
5749 
5750 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
5751 {
5752 #ifdef CONFIG_DEBUG_PREEMPT
5753 	return p->preempt_disable_ip;
5754 #else
5755 	return 0;
5756 #endif
5757 }
5758 
5759 /*
5760  * Print scheduling while atomic bug:
5761  */
5762 static noinline void __schedule_bug(struct task_struct *prev)
5763 {
5764 	/* Save this before calling printk(), since that will clobber it */
5765 	unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
5766 
5767 	if (oops_in_progress)
5768 		return;
5769 
5770 	printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
5771 		prev->comm, prev->pid, preempt_count());
5772 
5773 	debug_show_held_locks(prev);
5774 	print_modules();
5775 	if (irqs_disabled())
5776 		print_irqtrace_events(prev);
5777 	if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) {
5778 		pr_err("Preemption disabled at:");
5779 		print_ip_sym(KERN_ERR, preempt_disable_ip);
5780 	}
5781 	check_panic_on_warn("scheduling while atomic");
5782 
5783 	dump_stack();
5784 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
5785 }
5786 
5787 /*
5788  * Various schedule()-time debugging checks and statistics:
5789  */
5790 static inline void schedule_debug(struct task_struct *prev, bool preempt)
5791 {
5792 #ifdef CONFIG_SCHED_STACK_END_CHECK
5793 	if (task_stack_end_corrupted(prev))
5794 		panic("corrupted stack end detected inside scheduler\n");
5795 
5796 	if (task_scs_end_corrupted(prev))
5797 		panic("corrupted shadow stack detected inside scheduler\n");
5798 #endif
5799 
5800 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
5801 	if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) {
5802 		printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
5803 			prev->comm, prev->pid, prev->non_block_count);
5804 		dump_stack();
5805 		add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
5806 	}
5807 #endif
5808 
5809 	if (unlikely(in_atomic_preempt_off())) {
5810 		__schedule_bug(prev);
5811 		preempt_count_set(PREEMPT_DISABLED);
5812 	}
5813 	rcu_sleep_check();
5814 	SCHED_WARN_ON(ct_state() == CONTEXT_USER);
5815 
5816 	profile_hit(SCHED_PROFILING, __builtin_return_address(0));
5817 
5818 	schedstat_inc(this_rq()->sched_count);
5819 }
5820 
5821 static void put_prev_task_balance(struct rq *rq, struct task_struct *prev,
5822 				  struct rq_flags *rf)
5823 {
5824 #ifdef CONFIG_SMP
5825 	const struct sched_class *class;
5826 	/*
5827 	 * We must do the balancing pass before put_prev_task(), such
5828 	 * that when we release the rq->lock the task is in the same
5829 	 * state as before we took rq->lock.
5830 	 *
5831 	 * We can terminate the balance pass as soon as we know there is
5832 	 * a runnable task of @class priority or higher.
5833 	 */
5834 	for_balance_class_range(class, prev->sched_class, &idle_sched_class) {
5835 		if (class->balance(rq, prev, rf))
5836 			break;
5837 	}
5838 #endif
5839 
5840 	put_prev_task(rq, prev);
5841 }
5842 
5843 /*
5844  * Pick up the highest-prio task:
5845  */
5846 static inline struct task_struct *
5847 __pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
5848 {
5849 	const struct sched_class *class;
5850 	struct task_struct *p;
5851 
5852 	if (scx_enabled())
5853 		goto restart;
5854 
5855 	/*
5856 	 * Optimization: we know that if all tasks are in the fair class we can
5857 	 * call that function directly, but only if the @prev task wasn't of a
5858 	 * higher scheduling class, because otherwise those lose the
5859 	 * opportunity to pull in more work from other CPUs.
5860 	 */
5861 	if (likely(!sched_class_above(prev->sched_class, &fair_sched_class) &&
5862 		   rq->nr_running == rq->cfs.h_nr_running)) {
5863 
5864 		p = pick_next_task_fair(rq, prev, rf);
5865 		if (unlikely(p == RETRY_TASK))
5866 			goto restart;
5867 
5868 		/* Assume the next prioritized class is idle_sched_class */
5869 		if (!p) {
5870 			put_prev_task(rq, prev);
5871 			p = pick_next_task_idle(rq);
5872 		}
5873 
5874 		/*
5875 		 * This is the fast path; it cannot be a DL server pick;
5876 		 * therefore even if @p == @prev, ->dl_server must be NULL.
5877 		 */
5878 		if (p->dl_server)
5879 			p->dl_server = NULL;
5880 
5881 		return p;
5882 	}
5883 
5884 restart:
5885 	put_prev_task_balance(rq, prev, rf);
5886 
5887 	/*
5888 	 * We've updated @prev and no longer need the server link, clear it.
5889 	 * Must be done before ->pick_next_task() because that can (re)set
5890 	 * ->dl_server.
5891 	 */
5892 	if (prev->dl_server)
5893 		prev->dl_server = NULL;
5894 
5895 	for_each_active_class(class) {
5896 		p = class->pick_next_task(rq);
5897 		if (p)
5898 			return p;
5899 	}
5900 
5901 	BUG(); /* The idle class should always have a runnable task. */
5902 }
5903 
5904 #ifdef CONFIG_SCHED_CORE
5905 static inline bool is_task_rq_idle(struct task_struct *t)
5906 {
5907 	return (task_rq(t)->idle == t);
5908 }
5909 
5910 static inline bool cookie_equals(struct task_struct *a, unsigned long cookie)
5911 {
5912 	return is_task_rq_idle(a) || (a->core_cookie == cookie);
5913 }
5914 
5915 static inline bool cookie_match(struct task_struct *a, struct task_struct *b)
5916 {
5917 	if (is_task_rq_idle(a) || is_task_rq_idle(b))
5918 		return true;
5919 
5920 	return a->core_cookie == b->core_cookie;
5921 }
5922 
5923 static inline struct task_struct *pick_task(struct rq *rq)
5924 {
5925 	const struct sched_class *class;
5926 	struct task_struct *p;
5927 
5928 	for_each_active_class(class) {
5929 		p = class->pick_task(rq);
5930 		if (p)
5931 			return p;
5932 	}
5933 
5934 	BUG(); /* The idle class should always have a runnable task. */
5935 }
5936 
5937 extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi);
5938 
5939 static void queue_core_balance(struct rq *rq);
5940 
5941 static struct task_struct *
5942 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
5943 {
5944 	struct task_struct *next, *p, *max = NULL;
5945 	const struct cpumask *smt_mask;
5946 	bool fi_before = false;
5947 	bool core_clock_updated = (rq == rq->core);
5948 	unsigned long cookie;
5949 	int i, cpu, occ = 0;
5950 	struct rq *rq_i;
5951 	bool need_sync;
5952 
5953 	if (!sched_core_enabled(rq))
5954 		return __pick_next_task(rq, prev, rf);
5955 
5956 	cpu = cpu_of(rq);
5957 
5958 	/* Stopper task is switching into idle, no need core-wide selection. */
5959 	if (cpu_is_offline(cpu)) {
5960 		/*
5961 		 * Reset core_pick so that we don't enter the fastpath when
5962 		 * coming online. core_pick would already be migrated to
5963 		 * another cpu during offline.
5964 		 */
5965 		rq->core_pick = NULL;
5966 		return __pick_next_task(rq, prev, rf);
5967 	}
5968 
5969 	/*
5970 	 * If there were no {en,de}queues since we picked (IOW, the task
5971 	 * pointers are all still valid), and we haven't scheduled the last
5972 	 * pick yet, do so now.
5973 	 *
5974 	 * rq->core_pick can be NULL if no selection was made for a CPU because
5975 	 * it was either offline or went offline during a sibling's core-wide
5976 	 * selection. In this case, do a core-wide selection.
5977 	 */
5978 	if (rq->core->core_pick_seq == rq->core->core_task_seq &&
5979 	    rq->core->core_pick_seq != rq->core_sched_seq &&
5980 	    rq->core_pick) {
5981 		WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq);
5982 
5983 		next = rq->core_pick;
5984 		if (next != prev) {
5985 			put_prev_task(rq, prev);
5986 			set_next_task(rq, next);
5987 		}
5988 
5989 		rq->core_pick = NULL;
5990 		goto out;
5991 	}
5992 
5993 	put_prev_task_balance(rq, prev, rf);
5994 
5995 	smt_mask = cpu_smt_mask(cpu);
5996 	need_sync = !!rq->core->core_cookie;
5997 
5998 	/* reset state */
5999 	rq->core->core_cookie = 0UL;
6000 	if (rq->core->core_forceidle_count) {
6001 		if (!core_clock_updated) {
6002 			update_rq_clock(rq->core);
6003 			core_clock_updated = true;
6004 		}
6005 		sched_core_account_forceidle(rq);
6006 		/* reset after accounting force idle */
6007 		rq->core->core_forceidle_start = 0;
6008 		rq->core->core_forceidle_count = 0;
6009 		rq->core->core_forceidle_occupation = 0;
6010 		need_sync = true;
6011 		fi_before = true;
6012 	}
6013 
6014 	/*
6015 	 * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq
6016 	 *
6017 	 * @task_seq guards the task state ({en,de}queues)
6018 	 * @pick_seq is the @task_seq we did a selection on
6019 	 * @sched_seq is the @pick_seq we scheduled
6020 	 *
6021 	 * However, preemptions can cause multiple picks on the same task set.
6022 	 * 'Fix' this by also increasing @task_seq for every pick.
6023 	 */
6024 	rq->core->core_task_seq++;
6025 
6026 	/*
6027 	 * Optimize for common case where this CPU has no cookies
6028 	 * and there are no cookied tasks running on siblings.
6029 	 */
6030 	if (!need_sync) {
6031 		next = pick_task(rq);
6032 		if (!next->core_cookie) {
6033 			rq->core_pick = NULL;
6034 			/*
6035 			 * For robustness, update the min_vruntime_fi for
6036 			 * unconstrained picks as well.
6037 			 */
6038 			WARN_ON_ONCE(fi_before);
6039 			task_vruntime_update(rq, next, false);
6040 			goto out_set_next;
6041 		}
6042 	}
6043 
6044 	/*
6045 	 * For each thread: do the regular task pick and find the max prio task
6046 	 * amongst them.
6047 	 *
6048 	 * Tie-break prio towards the current CPU
6049 	 */
6050 	for_each_cpu_wrap(i, smt_mask, cpu) {
6051 		rq_i = cpu_rq(i);
6052 
6053 		/*
6054 		 * Current cpu always has its clock updated on entrance to
6055 		 * pick_next_task(). If the current cpu is not the core,
6056 		 * the core may also have been updated above.
6057 		 */
6058 		if (i != cpu && (rq_i != rq->core || !core_clock_updated))
6059 			update_rq_clock(rq_i);
6060 
6061 		p = rq_i->core_pick = pick_task(rq_i);
6062 		if (!max || prio_less(max, p, fi_before))
6063 			max = p;
6064 	}
6065 
6066 	cookie = rq->core->core_cookie = max->core_cookie;
6067 
6068 	/*
6069 	 * For each thread: try and find a runnable task that matches @max or
6070 	 * force idle.
6071 	 */
6072 	for_each_cpu(i, smt_mask) {
6073 		rq_i = cpu_rq(i);
6074 		p = rq_i->core_pick;
6075 
6076 		if (!cookie_equals(p, cookie)) {
6077 			p = NULL;
6078 			if (cookie)
6079 				p = sched_core_find(rq_i, cookie);
6080 			if (!p)
6081 				p = idle_sched_class.pick_task(rq_i);
6082 		}
6083 
6084 		rq_i->core_pick = p;
6085 
6086 		if (p == rq_i->idle) {
6087 			if (rq_i->nr_running) {
6088 				rq->core->core_forceidle_count++;
6089 				if (!fi_before)
6090 					rq->core->core_forceidle_seq++;
6091 			}
6092 		} else {
6093 			occ++;
6094 		}
6095 	}
6096 
6097 	if (schedstat_enabled() && rq->core->core_forceidle_count) {
6098 		rq->core->core_forceidle_start = rq_clock(rq->core);
6099 		rq->core->core_forceidle_occupation = occ;
6100 	}
6101 
6102 	rq->core->core_pick_seq = rq->core->core_task_seq;
6103 	next = rq->core_pick;
6104 	rq->core_sched_seq = rq->core->core_pick_seq;
6105 
6106 	/* Something should have been selected for current CPU */
6107 	WARN_ON_ONCE(!next);
6108 
6109 	/*
6110 	 * Reschedule siblings
6111 	 *
6112 	 * NOTE: L1TF -- at this point we're no longer running the old task and
6113 	 * sending an IPI (below) ensures the sibling will no longer be running
6114 	 * their task. This ensures there is no inter-sibling overlap between
6115 	 * non-matching user state.
6116 	 */
6117 	for_each_cpu(i, smt_mask) {
6118 		rq_i = cpu_rq(i);
6119 
6120 		/*
6121 		 * An online sibling might have gone offline before a task
6122 		 * could be picked for it, or it might be offline but later
6123 		 * happen to come online, but its too late and nothing was
6124 		 * picked for it.  That's Ok - it will pick tasks for itself,
6125 		 * so ignore it.
6126 		 */
6127 		if (!rq_i->core_pick)
6128 			continue;
6129 
6130 		/*
6131 		 * Update for new !FI->FI transitions, or if continuing to be in !FI:
6132 		 * fi_before     fi      update?
6133 		 *  0            0       1
6134 		 *  0            1       1
6135 		 *  1            0       1
6136 		 *  1            1       0
6137 		 */
6138 		if (!(fi_before && rq->core->core_forceidle_count))
6139 			task_vruntime_update(rq_i, rq_i->core_pick, !!rq->core->core_forceidle_count);
6140 
6141 		rq_i->core_pick->core_occupation = occ;
6142 
6143 		if (i == cpu) {
6144 			rq_i->core_pick = NULL;
6145 			continue;
6146 		}
6147 
6148 		/* Did we break L1TF mitigation requirements? */
6149 		WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick));
6150 
6151 		if (rq_i->curr == rq_i->core_pick) {
6152 			rq_i->core_pick = NULL;
6153 			continue;
6154 		}
6155 
6156 		resched_curr(rq_i);
6157 	}
6158 
6159 out_set_next:
6160 	set_next_task(rq, next);
6161 out:
6162 	if (rq->core->core_forceidle_count && next == rq->idle)
6163 		queue_core_balance(rq);
6164 
6165 	return next;
6166 }
6167 
6168 static bool try_steal_cookie(int this, int that)
6169 {
6170 	struct rq *dst = cpu_rq(this), *src = cpu_rq(that);
6171 	struct task_struct *p;
6172 	unsigned long cookie;
6173 	bool success = false;
6174 
6175 	guard(irq)();
6176 	guard(double_rq_lock)(dst, src);
6177 
6178 	cookie = dst->core->core_cookie;
6179 	if (!cookie)
6180 		return false;
6181 
6182 	if (dst->curr != dst->idle)
6183 		return false;
6184 
6185 	p = sched_core_find(src, cookie);
6186 	if (!p)
6187 		return false;
6188 
6189 	do {
6190 		if (p == src->core_pick || p == src->curr)
6191 			goto next;
6192 
6193 		if (!is_cpu_allowed(p, this))
6194 			goto next;
6195 
6196 		if (p->core_occupation > dst->idle->core_occupation)
6197 			goto next;
6198 		/*
6199 		 * sched_core_find() and sched_core_next() will ensure
6200 		 * that task @p is not throttled now, we also need to
6201 		 * check whether the runqueue of the destination CPU is
6202 		 * being throttled.
6203 		 */
6204 		if (sched_task_is_throttled(p, this))
6205 			goto next;
6206 
6207 		deactivate_task(src, p, 0);
6208 		set_task_cpu(p, this);
6209 		activate_task(dst, p, 0);
6210 
6211 		resched_curr(dst);
6212 
6213 		success = true;
6214 		break;
6215 
6216 next:
6217 		p = sched_core_next(p, cookie);
6218 	} while (p);
6219 
6220 	return success;
6221 }
6222 
6223 static bool steal_cookie_task(int cpu, struct sched_domain *sd)
6224 {
6225 	int i;
6226 
6227 	for_each_cpu_wrap(i, sched_domain_span(sd), cpu + 1) {
6228 		if (i == cpu)
6229 			continue;
6230 
6231 		if (need_resched())
6232 			break;
6233 
6234 		if (try_steal_cookie(cpu, i))
6235 			return true;
6236 	}
6237 
6238 	return false;
6239 }
6240 
6241 static void sched_core_balance(struct rq *rq)
6242 {
6243 	struct sched_domain *sd;
6244 	int cpu = cpu_of(rq);
6245 
6246 	guard(preempt)();
6247 	guard(rcu)();
6248 
6249 	raw_spin_rq_unlock_irq(rq);
6250 	for_each_domain(cpu, sd) {
6251 		if (need_resched())
6252 			break;
6253 
6254 		if (steal_cookie_task(cpu, sd))
6255 			break;
6256 	}
6257 	raw_spin_rq_lock_irq(rq);
6258 }
6259 
6260 static DEFINE_PER_CPU(struct balance_callback, core_balance_head);
6261 
6262 static void queue_core_balance(struct rq *rq)
6263 {
6264 	if (!sched_core_enabled(rq))
6265 		return;
6266 
6267 	if (!rq->core->core_cookie)
6268 		return;
6269 
6270 	if (!rq->nr_running) /* not forced idle */
6271 		return;
6272 
6273 	queue_balance_callback(rq, &per_cpu(core_balance_head, rq->cpu), sched_core_balance);
6274 }
6275 
6276 DEFINE_LOCK_GUARD_1(core_lock, int,
6277 		    sched_core_lock(*_T->lock, &_T->flags),
6278 		    sched_core_unlock(*_T->lock, &_T->flags),
6279 		    unsigned long flags)
6280 
6281 static void sched_core_cpu_starting(unsigned int cpu)
6282 {
6283 	const struct cpumask *smt_mask = cpu_smt_mask(cpu);
6284 	struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6285 	int t;
6286 
6287 	guard(core_lock)(&cpu);
6288 
6289 	WARN_ON_ONCE(rq->core != rq);
6290 
6291 	/* if we're the first, we'll be our own leader */
6292 	if (cpumask_weight(smt_mask) == 1)
6293 		return;
6294 
6295 	/* find the leader */
6296 	for_each_cpu(t, smt_mask) {
6297 		if (t == cpu)
6298 			continue;
6299 		rq = cpu_rq(t);
6300 		if (rq->core == rq) {
6301 			core_rq = rq;
6302 			break;
6303 		}
6304 	}
6305 
6306 	if (WARN_ON_ONCE(!core_rq)) /* whoopsie */
6307 		return;
6308 
6309 	/* install and validate core_rq */
6310 	for_each_cpu(t, smt_mask) {
6311 		rq = cpu_rq(t);
6312 
6313 		if (t == cpu)
6314 			rq->core = core_rq;
6315 
6316 		WARN_ON_ONCE(rq->core != core_rq);
6317 	}
6318 }
6319 
6320 static void sched_core_cpu_deactivate(unsigned int cpu)
6321 {
6322 	const struct cpumask *smt_mask = cpu_smt_mask(cpu);
6323 	struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6324 	int t;
6325 
6326 	guard(core_lock)(&cpu);
6327 
6328 	/* if we're the last man standing, nothing to do */
6329 	if (cpumask_weight(smt_mask) == 1) {
6330 		WARN_ON_ONCE(rq->core != rq);
6331 		return;
6332 	}
6333 
6334 	/* if we're not the leader, nothing to do */
6335 	if (rq->core != rq)
6336 		return;
6337 
6338 	/* find a new leader */
6339 	for_each_cpu(t, smt_mask) {
6340 		if (t == cpu)
6341 			continue;
6342 		core_rq = cpu_rq(t);
6343 		break;
6344 	}
6345 
6346 	if (WARN_ON_ONCE(!core_rq)) /* impossible */
6347 		return;
6348 
6349 	/* copy the shared state to the new leader */
6350 	core_rq->core_task_seq             = rq->core_task_seq;
6351 	core_rq->core_pick_seq             = rq->core_pick_seq;
6352 	core_rq->core_cookie               = rq->core_cookie;
6353 	core_rq->core_forceidle_count      = rq->core_forceidle_count;
6354 	core_rq->core_forceidle_seq        = rq->core_forceidle_seq;
6355 	core_rq->core_forceidle_occupation = rq->core_forceidle_occupation;
6356 
6357 	/*
6358 	 * Accounting edge for forced idle is handled in pick_next_task().
6359 	 * Don't need another one here, since the hotplug thread shouldn't
6360 	 * have a cookie.
6361 	 */
6362 	core_rq->core_forceidle_start = 0;
6363 
6364 	/* install new leader */
6365 	for_each_cpu(t, smt_mask) {
6366 		rq = cpu_rq(t);
6367 		rq->core = core_rq;
6368 	}
6369 }
6370 
6371 static inline void sched_core_cpu_dying(unsigned int cpu)
6372 {
6373 	struct rq *rq = cpu_rq(cpu);
6374 
6375 	if (rq->core != rq)
6376 		rq->core = rq;
6377 }
6378 
6379 #else /* !CONFIG_SCHED_CORE */
6380 
6381 static inline void sched_core_cpu_starting(unsigned int cpu) {}
6382 static inline void sched_core_cpu_deactivate(unsigned int cpu) {}
6383 static inline void sched_core_cpu_dying(unsigned int cpu) {}
6384 
6385 static struct task_struct *
6386 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6387 {
6388 	return __pick_next_task(rq, prev, rf);
6389 }
6390 
6391 #endif /* CONFIG_SCHED_CORE */
6392 
6393 /*
6394  * Constants for the sched_mode argument of __schedule().
6395  *
6396  * The mode argument allows RT enabled kernels to differentiate a
6397  * preemption from blocking on an 'sleeping' spin/rwlock. Note that
6398  * SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to
6399  * optimize the AND operation out and just check for zero.
6400  */
6401 #define SM_NONE			0x0
6402 #define SM_PREEMPT		0x1
6403 #define SM_RTLOCK_WAIT		0x2
6404 
6405 #ifndef CONFIG_PREEMPT_RT
6406 # define SM_MASK_PREEMPT	(~0U)
6407 #else
6408 # define SM_MASK_PREEMPT	SM_PREEMPT
6409 #endif
6410 
6411 /*
6412  * __schedule() is the main scheduler function.
6413  *
6414  * The main means of driving the scheduler and thus entering this function are:
6415  *
6416  *   1. Explicit blocking: mutex, semaphore, waitqueue, etc.
6417  *
6418  *   2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
6419  *      paths. For example, see arch/x86/entry_64.S.
6420  *
6421  *      To drive preemption between tasks, the scheduler sets the flag in timer
6422  *      interrupt handler sched_tick().
6423  *
6424  *   3. Wakeups don't really cause entry into schedule(). They add a
6425  *      task to the run-queue and that's it.
6426  *
6427  *      Now, if the new task added to the run-queue preempts the current
6428  *      task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
6429  *      called on the nearest possible occasion:
6430  *
6431  *       - If the kernel is preemptible (CONFIG_PREEMPTION=y):
6432  *
6433  *         - in syscall or exception context, at the next outmost
6434  *           preempt_enable(). (this might be as soon as the wake_up()'s
6435  *           spin_unlock()!)
6436  *
6437  *         - in IRQ context, return from interrupt-handler to
6438  *           preemptible context
6439  *
6440  *       - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
6441  *         then at the next:
6442  *
6443  *          - cond_resched() call
6444  *          - explicit schedule() call
6445  *          - return from syscall or exception to user-space
6446  *          - return from interrupt-handler to user-space
6447  *
6448  * WARNING: must be called with preemption disabled!
6449  */
6450 static void __sched notrace __schedule(unsigned int sched_mode)
6451 {
6452 	struct task_struct *prev, *next;
6453 	unsigned long *switch_count;
6454 	unsigned long prev_state;
6455 	struct rq_flags rf;
6456 	struct rq *rq;
6457 	int cpu;
6458 
6459 	cpu = smp_processor_id();
6460 	rq = cpu_rq(cpu);
6461 	prev = rq->curr;
6462 
6463 	schedule_debug(prev, !!sched_mode);
6464 
6465 	if (sched_feat(HRTICK) || sched_feat(HRTICK_DL))
6466 		hrtick_clear(rq);
6467 
6468 	local_irq_disable();
6469 	rcu_note_context_switch(!!sched_mode);
6470 
6471 	/*
6472 	 * Make sure that signal_pending_state()->signal_pending() below
6473 	 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
6474 	 * done by the caller to avoid the race with signal_wake_up():
6475 	 *
6476 	 * __set_current_state(@state)		signal_wake_up()
6477 	 * schedule()				  set_tsk_thread_flag(p, TIF_SIGPENDING)
6478 	 *					  wake_up_state(p, state)
6479 	 *   LOCK rq->lock			    LOCK p->pi_state
6480 	 *   smp_mb__after_spinlock()		    smp_mb__after_spinlock()
6481 	 *     if (signal_pending_state())	    if (p->state & @state)
6482 	 *
6483 	 * Also, the membarrier system call requires a full memory barrier
6484 	 * after coming from user-space, before storing to rq->curr; this
6485 	 * barrier matches a full barrier in the proximity of the membarrier
6486 	 * system call exit.
6487 	 */
6488 	rq_lock(rq, &rf);
6489 	smp_mb__after_spinlock();
6490 
6491 	/* Promote REQ to ACT */
6492 	rq->clock_update_flags <<= 1;
6493 	update_rq_clock(rq);
6494 	rq->clock_update_flags = RQCF_UPDATED;
6495 
6496 	switch_count = &prev->nivcsw;
6497 
6498 	/*
6499 	 * We must load prev->state once (task_struct::state is volatile), such
6500 	 * that we form a control dependency vs deactivate_task() below.
6501 	 */
6502 	prev_state = READ_ONCE(prev->__state);
6503 	if (!(sched_mode & SM_MASK_PREEMPT) && prev_state) {
6504 		if (signal_pending_state(prev_state, prev)) {
6505 			WRITE_ONCE(prev->__state, TASK_RUNNING);
6506 		} else {
6507 			prev->sched_contributes_to_load =
6508 				(prev_state & TASK_UNINTERRUPTIBLE) &&
6509 				!(prev_state & TASK_NOLOAD) &&
6510 				!(prev_state & TASK_FROZEN);
6511 
6512 			if (prev->sched_contributes_to_load)
6513 				rq->nr_uninterruptible++;
6514 
6515 			/*
6516 			 * __schedule()			ttwu()
6517 			 *   prev_state = prev->state;    if (p->on_rq && ...)
6518 			 *   if (prev_state)		    goto out;
6519 			 *     p->on_rq = 0;		  smp_acquire__after_ctrl_dep();
6520 			 *				  p->state = TASK_WAKING
6521 			 *
6522 			 * Where __schedule() and ttwu() have matching control dependencies.
6523 			 *
6524 			 * After this, schedule() must not care about p->state any more.
6525 			 */
6526 			deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
6527 
6528 			if (prev->in_iowait) {
6529 				atomic_inc(&rq->nr_iowait);
6530 				delayacct_blkio_start();
6531 			}
6532 		}
6533 		switch_count = &prev->nvcsw;
6534 	}
6535 
6536 	next = pick_next_task(rq, prev, &rf);
6537 	clear_tsk_need_resched(prev);
6538 	clear_preempt_need_resched();
6539 #ifdef CONFIG_SCHED_DEBUG
6540 	rq->last_seen_need_resched_ns = 0;
6541 #endif
6542 
6543 	if (likely(prev != next)) {
6544 		rq->nr_switches++;
6545 		/*
6546 		 * RCU users of rcu_dereference(rq->curr) may not see
6547 		 * changes to task_struct made by pick_next_task().
6548 		 */
6549 		RCU_INIT_POINTER(rq->curr, next);
6550 		/*
6551 		 * The membarrier system call requires each architecture
6552 		 * to have a full memory barrier after updating
6553 		 * rq->curr, before returning to user-space.
6554 		 *
6555 		 * Here are the schemes providing that barrier on the
6556 		 * various architectures:
6557 		 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC,
6558 		 *   RISC-V.  switch_mm() relies on membarrier_arch_switch_mm()
6559 		 *   on PowerPC and on RISC-V.
6560 		 * - finish_lock_switch() for weakly-ordered
6561 		 *   architectures where spin_unlock is a full barrier,
6562 		 * - switch_to() for arm64 (weakly-ordered, spin_unlock
6563 		 *   is a RELEASE barrier),
6564 		 *
6565 		 * The barrier matches a full barrier in the proximity of
6566 		 * the membarrier system call entry.
6567 		 *
6568 		 * On RISC-V, this barrier pairing is also needed for the
6569 		 * SYNC_CORE command when switching between processes, cf.
6570 		 * the inline comments in membarrier_arch_switch_mm().
6571 		 */
6572 		++*switch_count;
6573 
6574 		migrate_disable_switch(rq, prev);
6575 		psi_sched_switch(prev, next, !task_on_rq_queued(prev));
6576 
6577 		trace_sched_switch(sched_mode & SM_MASK_PREEMPT, prev, next, prev_state);
6578 
6579 		/* Also unlocks the rq: */
6580 		rq = context_switch(rq, prev, next, &rf);
6581 	} else {
6582 		rq_unpin_lock(rq, &rf);
6583 		__balance_callbacks(rq);
6584 		raw_spin_rq_unlock_irq(rq);
6585 	}
6586 }
6587 
6588 void __noreturn do_task_dead(void)
6589 {
6590 	/* Causes final put_task_struct in finish_task_switch(): */
6591 	set_special_state(TASK_DEAD);
6592 
6593 	/* Tell freezer to ignore us: */
6594 	current->flags |= PF_NOFREEZE;
6595 
6596 	__schedule(SM_NONE);
6597 	BUG();
6598 
6599 	/* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
6600 	for (;;)
6601 		cpu_relax();
6602 }
6603 
6604 static inline void sched_submit_work(struct task_struct *tsk)
6605 {
6606 	static DEFINE_WAIT_OVERRIDE_MAP(sched_map, LD_WAIT_CONFIG);
6607 	unsigned int task_flags;
6608 
6609 	/*
6610 	 * Establish LD_WAIT_CONFIG context to ensure none of the code called
6611 	 * will use a blocking primitive -- which would lead to recursion.
6612 	 */
6613 	lock_map_acquire_try(&sched_map);
6614 
6615 	task_flags = tsk->flags;
6616 	/*
6617 	 * If a worker goes to sleep, notify and ask workqueue whether it
6618 	 * wants to wake up a task to maintain concurrency.
6619 	 */
6620 	if (task_flags & PF_WQ_WORKER)
6621 		wq_worker_sleeping(tsk);
6622 	else if (task_flags & PF_IO_WORKER)
6623 		io_wq_worker_sleeping(tsk);
6624 
6625 	/*
6626 	 * spinlock and rwlock must not flush block requests.  This will
6627 	 * deadlock if the callback attempts to acquire a lock which is
6628 	 * already acquired.
6629 	 */
6630 	SCHED_WARN_ON(current->__state & TASK_RTLOCK_WAIT);
6631 
6632 	/*
6633 	 * If we are going to sleep and we have plugged IO queued,
6634 	 * make sure to submit it to avoid deadlocks.
6635 	 */
6636 	blk_flush_plug(tsk->plug, true);
6637 
6638 	lock_map_release(&sched_map);
6639 }
6640 
6641 static void sched_update_worker(struct task_struct *tsk)
6642 {
6643 	if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER | PF_BLOCK_TS)) {
6644 		if (tsk->flags & PF_BLOCK_TS)
6645 			blk_plug_invalidate_ts(tsk);
6646 		if (tsk->flags & PF_WQ_WORKER)
6647 			wq_worker_running(tsk);
6648 		else if (tsk->flags & PF_IO_WORKER)
6649 			io_wq_worker_running(tsk);
6650 	}
6651 }
6652 
6653 static __always_inline void __schedule_loop(unsigned int sched_mode)
6654 {
6655 	do {
6656 		preempt_disable();
6657 		__schedule(sched_mode);
6658 		sched_preempt_enable_no_resched();
6659 	} while (need_resched());
6660 }
6661 
6662 asmlinkage __visible void __sched schedule(void)
6663 {
6664 	struct task_struct *tsk = current;
6665 
6666 #ifdef CONFIG_RT_MUTEXES
6667 	lockdep_assert(!tsk->sched_rt_mutex);
6668 #endif
6669 
6670 	if (!task_is_running(tsk))
6671 		sched_submit_work(tsk);
6672 	__schedule_loop(SM_NONE);
6673 	sched_update_worker(tsk);
6674 }
6675 EXPORT_SYMBOL(schedule);
6676 
6677 /*
6678  * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
6679  * state (have scheduled out non-voluntarily) by making sure that all
6680  * tasks have either left the run queue or have gone into user space.
6681  * As idle tasks do not do either, they must not ever be preempted
6682  * (schedule out non-voluntarily).
6683  *
6684  * schedule_idle() is similar to schedule_preempt_disable() except that it
6685  * never enables preemption because it does not call sched_submit_work().
6686  */
6687 void __sched schedule_idle(void)
6688 {
6689 	/*
6690 	 * As this skips calling sched_submit_work(), which the idle task does
6691 	 * regardless because that function is a NOP when the task is in a
6692 	 * TASK_RUNNING state, make sure this isn't used someplace that the
6693 	 * current task can be in any other state. Note, idle is always in the
6694 	 * TASK_RUNNING state.
6695 	 */
6696 	WARN_ON_ONCE(current->__state);
6697 	do {
6698 		__schedule(SM_NONE);
6699 	} while (need_resched());
6700 }
6701 
6702 #if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK)
6703 asmlinkage __visible void __sched schedule_user(void)
6704 {
6705 	/*
6706 	 * If we come here after a random call to set_need_resched(),
6707 	 * or we have been woken up remotely but the IPI has not yet arrived,
6708 	 * we haven't yet exited the RCU idle mode. Do it here manually until
6709 	 * we find a better solution.
6710 	 *
6711 	 * NB: There are buggy callers of this function.  Ideally we
6712 	 * should warn if prev_state != CONTEXT_USER, but that will trigger
6713 	 * too frequently to make sense yet.
6714 	 */
6715 	enum ctx_state prev_state = exception_enter();
6716 	schedule();
6717 	exception_exit(prev_state);
6718 }
6719 #endif
6720 
6721 /**
6722  * schedule_preempt_disabled - called with preemption disabled
6723  *
6724  * Returns with preemption disabled. Note: preempt_count must be 1
6725  */
6726 void __sched schedule_preempt_disabled(void)
6727 {
6728 	sched_preempt_enable_no_resched();
6729 	schedule();
6730 	preempt_disable();
6731 }
6732 
6733 #ifdef CONFIG_PREEMPT_RT
6734 void __sched notrace schedule_rtlock(void)
6735 {
6736 	__schedule_loop(SM_RTLOCK_WAIT);
6737 }
6738 NOKPROBE_SYMBOL(schedule_rtlock);
6739 #endif
6740 
6741 static void __sched notrace preempt_schedule_common(void)
6742 {
6743 	do {
6744 		/*
6745 		 * Because the function tracer can trace preempt_count_sub()
6746 		 * and it also uses preempt_enable/disable_notrace(), if
6747 		 * NEED_RESCHED is set, the preempt_enable_notrace() called
6748 		 * by the function tracer will call this function again and
6749 		 * cause infinite recursion.
6750 		 *
6751 		 * Preemption must be disabled here before the function
6752 		 * tracer can trace. Break up preempt_disable() into two
6753 		 * calls. One to disable preemption without fear of being
6754 		 * traced. The other to still record the preemption latency,
6755 		 * which can also be traced by the function tracer.
6756 		 */
6757 		preempt_disable_notrace();
6758 		preempt_latency_start(1);
6759 		__schedule(SM_PREEMPT);
6760 		preempt_latency_stop(1);
6761 		preempt_enable_no_resched_notrace();
6762 
6763 		/*
6764 		 * Check again in case we missed a preemption opportunity
6765 		 * between schedule and now.
6766 		 */
6767 	} while (need_resched());
6768 }
6769 
6770 #ifdef CONFIG_PREEMPTION
6771 /*
6772  * This is the entry point to schedule() from in-kernel preemption
6773  * off of preempt_enable.
6774  */
6775 asmlinkage __visible void __sched notrace preempt_schedule(void)
6776 {
6777 	/*
6778 	 * If there is a non-zero preempt_count or interrupts are disabled,
6779 	 * we do not want to preempt the current task. Just return..
6780 	 */
6781 	if (likely(!preemptible()))
6782 		return;
6783 	preempt_schedule_common();
6784 }
6785 NOKPROBE_SYMBOL(preempt_schedule);
6786 EXPORT_SYMBOL(preempt_schedule);
6787 
6788 #ifdef CONFIG_PREEMPT_DYNAMIC
6789 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
6790 #ifndef preempt_schedule_dynamic_enabled
6791 #define preempt_schedule_dynamic_enabled	preempt_schedule
6792 #define preempt_schedule_dynamic_disabled	NULL
6793 #endif
6794 DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled);
6795 EXPORT_STATIC_CALL_TRAMP(preempt_schedule);
6796 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
6797 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule);
6798 void __sched notrace dynamic_preempt_schedule(void)
6799 {
6800 	if (!static_branch_unlikely(&sk_dynamic_preempt_schedule))
6801 		return;
6802 	preempt_schedule();
6803 }
6804 NOKPROBE_SYMBOL(dynamic_preempt_schedule);
6805 EXPORT_SYMBOL(dynamic_preempt_schedule);
6806 #endif
6807 #endif
6808 
6809 /**
6810  * preempt_schedule_notrace - preempt_schedule called by tracing
6811  *
6812  * The tracing infrastructure uses preempt_enable_notrace to prevent
6813  * recursion and tracing preempt enabling caused by the tracing
6814  * infrastructure itself. But as tracing can happen in areas coming
6815  * from userspace or just about to enter userspace, a preempt enable
6816  * can occur before user_exit() is called. This will cause the scheduler
6817  * to be called when the system is still in usermode.
6818  *
6819  * To prevent this, the preempt_enable_notrace will use this function
6820  * instead of preempt_schedule() to exit user context if needed before
6821  * calling the scheduler.
6822  */
6823 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
6824 {
6825 	enum ctx_state prev_ctx;
6826 
6827 	if (likely(!preemptible()))
6828 		return;
6829 
6830 	do {
6831 		/*
6832 		 * Because the function tracer can trace preempt_count_sub()
6833 		 * and it also uses preempt_enable/disable_notrace(), if
6834 		 * NEED_RESCHED is set, the preempt_enable_notrace() called
6835 		 * by the function tracer will call this function again and
6836 		 * cause infinite recursion.
6837 		 *
6838 		 * Preemption must be disabled here before the function
6839 		 * tracer can trace. Break up preempt_disable() into two
6840 		 * calls. One to disable preemption without fear of being
6841 		 * traced. The other to still record the preemption latency,
6842 		 * which can also be traced by the function tracer.
6843 		 */
6844 		preempt_disable_notrace();
6845 		preempt_latency_start(1);
6846 		/*
6847 		 * Needs preempt disabled in case user_exit() is traced
6848 		 * and the tracer calls preempt_enable_notrace() causing
6849 		 * an infinite recursion.
6850 		 */
6851 		prev_ctx = exception_enter();
6852 		__schedule(SM_PREEMPT);
6853 		exception_exit(prev_ctx);
6854 
6855 		preempt_latency_stop(1);
6856 		preempt_enable_no_resched_notrace();
6857 	} while (need_resched());
6858 }
6859 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
6860 
6861 #ifdef CONFIG_PREEMPT_DYNAMIC
6862 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
6863 #ifndef preempt_schedule_notrace_dynamic_enabled
6864 #define preempt_schedule_notrace_dynamic_enabled	preempt_schedule_notrace
6865 #define preempt_schedule_notrace_dynamic_disabled	NULL
6866 #endif
6867 DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled);
6868 EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace);
6869 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
6870 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace);
6871 void __sched notrace dynamic_preempt_schedule_notrace(void)
6872 {
6873 	if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace))
6874 		return;
6875 	preempt_schedule_notrace();
6876 }
6877 NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace);
6878 EXPORT_SYMBOL(dynamic_preempt_schedule_notrace);
6879 #endif
6880 #endif
6881 
6882 #endif /* CONFIG_PREEMPTION */
6883 
6884 /*
6885  * This is the entry point to schedule() from kernel preemption
6886  * off of IRQ context.
6887  * Note, that this is called and return with IRQs disabled. This will
6888  * protect us against recursive calling from IRQ contexts.
6889  */
6890 asmlinkage __visible void __sched preempt_schedule_irq(void)
6891 {
6892 	enum ctx_state prev_state;
6893 
6894 	/* Catch callers which need to be fixed */
6895 	BUG_ON(preempt_count() || !irqs_disabled());
6896 
6897 	prev_state = exception_enter();
6898 
6899 	do {
6900 		preempt_disable();
6901 		local_irq_enable();
6902 		__schedule(SM_PREEMPT);
6903 		local_irq_disable();
6904 		sched_preempt_enable_no_resched();
6905 	} while (need_resched());
6906 
6907 	exception_exit(prev_state);
6908 }
6909 
6910 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
6911 			  void *key)
6912 {
6913 	WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~(WF_SYNC|WF_CURRENT_CPU));
6914 	return try_to_wake_up(curr->private, mode, wake_flags);
6915 }
6916 EXPORT_SYMBOL(default_wake_function);
6917 
6918 void __setscheduler_prio(struct task_struct *p, int prio)
6919 {
6920 	if (dl_prio(prio))
6921 		p->sched_class = &dl_sched_class;
6922 	else if (rt_prio(prio))
6923 		p->sched_class = &rt_sched_class;
6924 #ifdef CONFIG_SCHED_CLASS_EXT
6925 	else if (task_should_scx(p))
6926 		p->sched_class = &ext_sched_class;
6927 #endif
6928 	else
6929 		p->sched_class = &fair_sched_class;
6930 
6931 	p->prio = prio;
6932 }
6933 
6934 #ifdef CONFIG_RT_MUTEXES
6935 
6936 /*
6937  * Would be more useful with typeof()/auto_type but they don't mix with
6938  * bit-fields. Since it's a local thing, use int. Keep the generic sounding
6939  * name such that if someone were to implement this function we get to compare
6940  * notes.
6941  */
6942 #define fetch_and_set(x, v) ({ int _x = (x); (x) = (v); _x; })
6943 
6944 void rt_mutex_pre_schedule(void)
6945 {
6946 	lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1));
6947 	sched_submit_work(current);
6948 }
6949 
6950 void rt_mutex_schedule(void)
6951 {
6952 	lockdep_assert(current->sched_rt_mutex);
6953 	__schedule_loop(SM_NONE);
6954 }
6955 
6956 void rt_mutex_post_schedule(void)
6957 {
6958 	sched_update_worker(current);
6959 	lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0));
6960 }
6961 
6962 /*
6963  * rt_mutex_setprio - set the current priority of a task
6964  * @p: task to boost
6965  * @pi_task: donor task
6966  *
6967  * This function changes the 'effective' priority of a task. It does
6968  * not touch ->normal_prio like __setscheduler().
6969  *
6970  * Used by the rt_mutex code to implement priority inheritance
6971  * logic. Call site only calls if the priority of the task changed.
6972  */
6973 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
6974 {
6975 	int prio, oldprio, queued, running, queue_flag =
6976 		DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
6977 	const struct sched_class *prev_class;
6978 	struct rq_flags rf;
6979 	struct rq *rq;
6980 
6981 	/* XXX used to be waiter->prio, not waiter->task->prio */
6982 	prio = __rt_effective_prio(pi_task, p->normal_prio);
6983 
6984 	/*
6985 	 * If nothing changed; bail early.
6986 	 */
6987 	if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
6988 		return;
6989 
6990 	rq = __task_rq_lock(p, &rf);
6991 	update_rq_clock(rq);
6992 	/*
6993 	 * Set under pi_lock && rq->lock, such that the value can be used under
6994 	 * either lock.
6995 	 *
6996 	 * Note that there is loads of tricky to make this pointer cache work
6997 	 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
6998 	 * ensure a task is de-boosted (pi_task is set to NULL) before the
6999 	 * task is allowed to run again (and can exit). This ensures the pointer
7000 	 * points to a blocked task -- which guarantees the task is present.
7001 	 */
7002 	p->pi_top_task = pi_task;
7003 
7004 	/*
7005 	 * For FIFO/RR we only need to set prio, if that matches we're done.
7006 	 */
7007 	if (prio == p->prio && !dl_prio(prio))
7008 		goto out_unlock;
7009 
7010 	/*
7011 	 * Idle task boosting is a no-no in general. There is one
7012 	 * exception, when PREEMPT_RT and NOHZ is active:
7013 	 *
7014 	 * The idle task calls get_next_timer_interrupt() and holds
7015 	 * the timer wheel base->lock on the CPU and another CPU wants
7016 	 * to access the timer (probably to cancel it). We can safely
7017 	 * ignore the boosting request, as the idle CPU runs this code
7018 	 * with interrupts disabled and will complete the lock
7019 	 * protected section without being interrupted. So there is no
7020 	 * real need to boost.
7021 	 */
7022 	if (unlikely(p == rq->idle)) {
7023 		WARN_ON(p != rq->curr);
7024 		WARN_ON(p->pi_blocked_on);
7025 		goto out_unlock;
7026 	}
7027 
7028 	trace_sched_pi_setprio(p, pi_task);
7029 	oldprio = p->prio;
7030 
7031 	if (oldprio == prio)
7032 		queue_flag &= ~DEQUEUE_MOVE;
7033 
7034 	prev_class = p->sched_class;
7035 	queued = task_on_rq_queued(p);
7036 	running = task_current(rq, p);
7037 	if (queued)
7038 		dequeue_task(rq, p, queue_flag);
7039 	if (running)
7040 		put_prev_task(rq, p);
7041 
7042 	/*
7043 	 * Boosting condition are:
7044 	 * 1. -rt task is running and holds mutex A
7045 	 *      --> -dl task blocks on mutex A
7046 	 *
7047 	 * 2. -dl task is running and holds mutex A
7048 	 *      --> -dl task blocks on mutex A and could preempt the
7049 	 *          running task
7050 	 */
7051 	if (dl_prio(prio)) {
7052 		if (!dl_prio(p->normal_prio) ||
7053 		    (pi_task && dl_prio(pi_task->prio) &&
7054 		     dl_entity_preempt(&pi_task->dl, &p->dl))) {
7055 			p->dl.pi_se = pi_task->dl.pi_se;
7056 			queue_flag |= ENQUEUE_REPLENISH;
7057 		} else {
7058 			p->dl.pi_se = &p->dl;
7059 		}
7060 	} else if (rt_prio(prio)) {
7061 		if (dl_prio(oldprio))
7062 			p->dl.pi_se = &p->dl;
7063 		if (oldprio < prio)
7064 			queue_flag |= ENQUEUE_HEAD;
7065 	} else {
7066 		if (dl_prio(oldprio))
7067 			p->dl.pi_se = &p->dl;
7068 		if (rt_prio(oldprio))
7069 			p->rt.timeout = 0;
7070 	}
7071 
7072 	__setscheduler_prio(p, prio);
7073 	check_class_changing(rq, p, prev_class);
7074 
7075 	if (queued)
7076 		enqueue_task(rq, p, queue_flag);
7077 	if (running)
7078 		set_next_task(rq, p);
7079 
7080 	check_class_changed(rq, p, prev_class, oldprio);
7081 out_unlock:
7082 	/* Avoid rq from going away on us: */
7083 	preempt_disable();
7084 
7085 	rq_unpin_lock(rq, &rf);
7086 	__balance_callbacks(rq);
7087 	raw_spin_rq_unlock(rq);
7088 
7089 	preempt_enable();
7090 }
7091 #endif
7092 
7093 #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
7094 int __sched __cond_resched(void)
7095 {
7096 	if (should_resched(0)) {
7097 		preempt_schedule_common();
7098 		return 1;
7099 	}
7100 	/*
7101 	 * In preemptible kernels, ->rcu_read_lock_nesting tells the tick
7102 	 * whether the current CPU is in an RCU read-side critical section,
7103 	 * so the tick can report quiescent states even for CPUs looping
7104 	 * in kernel context.  In contrast, in non-preemptible kernels,
7105 	 * RCU readers leave no in-memory hints, which means that CPU-bound
7106 	 * processes executing in kernel context might never report an
7107 	 * RCU quiescent state.  Therefore, the following code causes
7108 	 * cond_resched() to report a quiescent state, but only when RCU
7109 	 * is in urgent need of one.
7110 	 */
7111 #ifndef CONFIG_PREEMPT_RCU
7112 	rcu_all_qs();
7113 #endif
7114 	return 0;
7115 }
7116 EXPORT_SYMBOL(__cond_resched);
7117 #endif
7118 
7119 #ifdef CONFIG_PREEMPT_DYNAMIC
7120 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
7121 #define cond_resched_dynamic_enabled	__cond_resched
7122 #define cond_resched_dynamic_disabled	((void *)&__static_call_return0)
7123 DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched);
7124 EXPORT_STATIC_CALL_TRAMP(cond_resched);
7125 
7126 #define might_resched_dynamic_enabled	__cond_resched
7127 #define might_resched_dynamic_disabled	((void *)&__static_call_return0)
7128 DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched);
7129 EXPORT_STATIC_CALL_TRAMP(might_resched);
7130 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
7131 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched);
7132 int __sched dynamic_cond_resched(void)
7133 {
7134 	klp_sched_try_switch();
7135 	if (!static_branch_unlikely(&sk_dynamic_cond_resched))
7136 		return 0;
7137 	return __cond_resched();
7138 }
7139 EXPORT_SYMBOL(dynamic_cond_resched);
7140 
7141 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched);
7142 int __sched dynamic_might_resched(void)
7143 {
7144 	if (!static_branch_unlikely(&sk_dynamic_might_resched))
7145 		return 0;
7146 	return __cond_resched();
7147 }
7148 EXPORT_SYMBOL(dynamic_might_resched);
7149 #endif
7150 #endif
7151 
7152 /*
7153  * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
7154  * call schedule, and on return reacquire the lock.
7155  *
7156  * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
7157  * operations here to prevent schedule() from being called twice (once via
7158  * spin_unlock(), once by hand).
7159  */
7160 int __cond_resched_lock(spinlock_t *lock)
7161 {
7162 	int resched = should_resched(PREEMPT_LOCK_OFFSET);
7163 	int ret = 0;
7164 
7165 	lockdep_assert_held(lock);
7166 
7167 	if (spin_needbreak(lock) || resched) {
7168 		spin_unlock(lock);
7169 		if (!_cond_resched())
7170 			cpu_relax();
7171 		ret = 1;
7172 		spin_lock(lock);
7173 	}
7174 	return ret;
7175 }
7176 EXPORT_SYMBOL(__cond_resched_lock);
7177 
7178 int __cond_resched_rwlock_read(rwlock_t *lock)
7179 {
7180 	int resched = should_resched(PREEMPT_LOCK_OFFSET);
7181 	int ret = 0;
7182 
7183 	lockdep_assert_held_read(lock);
7184 
7185 	if (rwlock_needbreak(lock) || resched) {
7186 		read_unlock(lock);
7187 		if (!_cond_resched())
7188 			cpu_relax();
7189 		ret = 1;
7190 		read_lock(lock);
7191 	}
7192 	return ret;
7193 }
7194 EXPORT_SYMBOL(__cond_resched_rwlock_read);
7195 
7196 int __cond_resched_rwlock_write(rwlock_t *lock)
7197 {
7198 	int resched = should_resched(PREEMPT_LOCK_OFFSET);
7199 	int ret = 0;
7200 
7201 	lockdep_assert_held_write(lock);
7202 
7203 	if (rwlock_needbreak(lock) || resched) {
7204 		write_unlock(lock);
7205 		if (!_cond_resched())
7206 			cpu_relax();
7207 		ret = 1;
7208 		write_lock(lock);
7209 	}
7210 	return ret;
7211 }
7212 EXPORT_SYMBOL(__cond_resched_rwlock_write);
7213 
7214 #ifdef CONFIG_PREEMPT_DYNAMIC
7215 
7216 #ifdef CONFIG_GENERIC_ENTRY
7217 #include <linux/entry-common.h>
7218 #endif
7219 
7220 /*
7221  * SC:cond_resched
7222  * SC:might_resched
7223  * SC:preempt_schedule
7224  * SC:preempt_schedule_notrace
7225  * SC:irqentry_exit_cond_resched
7226  *
7227  *
7228  * NONE:
7229  *   cond_resched               <- __cond_resched
7230  *   might_resched              <- RET0
7231  *   preempt_schedule           <- NOP
7232  *   preempt_schedule_notrace   <- NOP
7233  *   irqentry_exit_cond_resched <- NOP
7234  *
7235  * VOLUNTARY:
7236  *   cond_resched               <- __cond_resched
7237  *   might_resched              <- __cond_resched
7238  *   preempt_schedule           <- NOP
7239  *   preempt_schedule_notrace   <- NOP
7240  *   irqentry_exit_cond_resched <- NOP
7241  *
7242  * FULL:
7243  *   cond_resched               <- RET0
7244  *   might_resched              <- RET0
7245  *   preempt_schedule           <- preempt_schedule
7246  *   preempt_schedule_notrace   <- preempt_schedule_notrace
7247  *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched
7248  */
7249 
7250 enum {
7251 	preempt_dynamic_undefined = -1,
7252 	preempt_dynamic_none,
7253 	preempt_dynamic_voluntary,
7254 	preempt_dynamic_full,
7255 };
7256 
7257 int preempt_dynamic_mode = preempt_dynamic_undefined;
7258 
7259 int sched_dynamic_mode(const char *str)
7260 {
7261 	if (!strcmp(str, "none"))
7262 		return preempt_dynamic_none;
7263 
7264 	if (!strcmp(str, "voluntary"))
7265 		return preempt_dynamic_voluntary;
7266 
7267 	if (!strcmp(str, "full"))
7268 		return preempt_dynamic_full;
7269 
7270 	return -EINVAL;
7271 }
7272 
7273 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
7274 #define preempt_dynamic_enable(f)	static_call_update(f, f##_dynamic_enabled)
7275 #define preempt_dynamic_disable(f)	static_call_update(f, f##_dynamic_disabled)
7276 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
7277 #define preempt_dynamic_enable(f)	static_key_enable(&sk_dynamic_##f.key)
7278 #define preempt_dynamic_disable(f)	static_key_disable(&sk_dynamic_##f.key)
7279 #else
7280 #error "Unsupported PREEMPT_DYNAMIC mechanism"
7281 #endif
7282 
7283 static DEFINE_MUTEX(sched_dynamic_mutex);
7284 static bool klp_override;
7285 
7286 static void __sched_dynamic_update(int mode)
7287 {
7288 	/*
7289 	 * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in
7290 	 * the ZERO state, which is invalid.
7291 	 */
7292 	if (!klp_override)
7293 		preempt_dynamic_enable(cond_resched);
7294 	preempt_dynamic_enable(might_resched);
7295 	preempt_dynamic_enable(preempt_schedule);
7296 	preempt_dynamic_enable(preempt_schedule_notrace);
7297 	preempt_dynamic_enable(irqentry_exit_cond_resched);
7298 
7299 	switch (mode) {
7300 	case preempt_dynamic_none:
7301 		if (!klp_override)
7302 			preempt_dynamic_enable(cond_resched);
7303 		preempt_dynamic_disable(might_resched);
7304 		preempt_dynamic_disable(preempt_schedule);
7305 		preempt_dynamic_disable(preempt_schedule_notrace);
7306 		preempt_dynamic_disable(irqentry_exit_cond_resched);
7307 		if (mode != preempt_dynamic_mode)
7308 			pr_info("Dynamic Preempt: none\n");
7309 		break;
7310 
7311 	case preempt_dynamic_voluntary:
7312 		if (!klp_override)
7313 			preempt_dynamic_enable(cond_resched);
7314 		preempt_dynamic_enable(might_resched);
7315 		preempt_dynamic_disable(preempt_schedule);
7316 		preempt_dynamic_disable(preempt_schedule_notrace);
7317 		preempt_dynamic_disable(irqentry_exit_cond_resched);
7318 		if (mode != preempt_dynamic_mode)
7319 			pr_info("Dynamic Preempt: voluntary\n");
7320 		break;
7321 
7322 	case preempt_dynamic_full:
7323 		if (!klp_override)
7324 			preempt_dynamic_disable(cond_resched);
7325 		preempt_dynamic_disable(might_resched);
7326 		preempt_dynamic_enable(preempt_schedule);
7327 		preempt_dynamic_enable(preempt_schedule_notrace);
7328 		preempt_dynamic_enable(irqentry_exit_cond_resched);
7329 		if (mode != preempt_dynamic_mode)
7330 			pr_info("Dynamic Preempt: full\n");
7331 		break;
7332 	}
7333 
7334 	preempt_dynamic_mode = mode;
7335 }
7336 
7337 void sched_dynamic_update(int mode)
7338 {
7339 	mutex_lock(&sched_dynamic_mutex);
7340 	__sched_dynamic_update(mode);
7341 	mutex_unlock(&sched_dynamic_mutex);
7342 }
7343 
7344 #ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL
7345 
7346 static int klp_cond_resched(void)
7347 {
7348 	__klp_sched_try_switch();
7349 	return __cond_resched();
7350 }
7351 
7352 void sched_dynamic_klp_enable(void)
7353 {
7354 	mutex_lock(&sched_dynamic_mutex);
7355 
7356 	klp_override = true;
7357 	static_call_update(cond_resched, klp_cond_resched);
7358 
7359 	mutex_unlock(&sched_dynamic_mutex);
7360 }
7361 
7362 void sched_dynamic_klp_disable(void)
7363 {
7364 	mutex_lock(&sched_dynamic_mutex);
7365 
7366 	klp_override = false;
7367 	__sched_dynamic_update(preempt_dynamic_mode);
7368 
7369 	mutex_unlock(&sched_dynamic_mutex);
7370 }
7371 
7372 #endif /* CONFIG_HAVE_PREEMPT_DYNAMIC_CALL */
7373 
7374 static int __init setup_preempt_mode(char *str)
7375 {
7376 	int mode = sched_dynamic_mode(str);
7377 	if (mode < 0) {
7378 		pr_warn("Dynamic Preempt: unsupported mode: %s\n", str);
7379 		return 0;
7380 	}
7381 
7382 	sched_dynamic_update(mode);
7383 	return 1;
7384 }
7385 __setup("preempt=", setup_preempt_mode);
7386 
7387 static void __init preempt_dynamic_init(void)
7388 {
7389 	if (preempt_dynamic_mode == preempt_dynamic_undefined) {
7390 		if (IS_ENABLED(CONFIG_PREEMPT_NONE)) {
7391 			sched_dynamic_update(preempt_dynamic_none);
7392 		} else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) {
7393 			sched_dynamic_update(preempt_dynamic_voluntary);
7394 		} else {
7395 			/* Default static call setting, nothing to do */
7396 			WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT));
7397 			preempt_dynamic_mode = preempt_dynamic_full;
7398 			pr_info("Dynamic Preempt: full\n");
7399 		}
7400 	}
7401 }
7402 
7403 #define PREEMPT_MODEL_ACCESSOR(mode) \
7404 	bool preempt_model_##mode(void)						 \
7405 	{									 \
7406 		WARN_ON_ONCE(preempt_dynamic_mode == preempt_dynamic_undefined); \
7407 		return preempt_dynamic_mode == preempt_dynamic_##mode;		 \
7408 	}									 \
7409 	EXPORT_SYMBOL_GPL(preempt_model_##mode)
7410 
7411 PREEMPT_MODEL_ACCESSOR(none);
7412 PREEMPT_MODEL_ACCESSOR(voluntary);
7413 PREEMPT_MODEL_ACCESSOR(full);
7414 
7415 #else /* !CONFIG_PREEMPT_DYNAMIC: */
7416 
7417 static inline void preempt_dynamic_init(void) { }
7418 
7419 #endif /* CONFIG_PREEMPT_DYNAMIC */
7420 
7421 int io_schedule_prepare(void)
7422 {
7423 	int old_iowait = current->in_iowait;
7424 
7425 	current->in_iowait = 1;
7426 	blk_flush_plug(current->plug, true);
7427 	return old_iowait;
7428 }
7429 
7430 void io_schedule_finish(int token)
7431 {
7432 	current->in_iowait = token;
7433 }
7434 
7435 /*
7436  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
7437  * that process accounting knows that this is a task in IO wait state.
7438  */
7439 long __sched io_schedule_timeout(long timeout)
7440 {
7441 	int token;
7442 	long ret;
7443 
7444 	token = io_schedule_prepare();
7445 	ret = schedule_timeout(timeout);
7446 	io_schedule_finish(token);
7447 
7448 	return ret;
7449 }
7450 EXPORT_SYMBOL(io_schedule_timeout);
7451 
7452 void __sched io_schedule(void)
7453 {
7454 	int token;
7455 
7456 	token = io_schedule_prepare();
7457 	schedule();
7458 	io_schedule_finish(token);
7459 }
7460 EXPORT_SYMBOL(io_schedule);
7461 
7462 void sched_show_task(struct task_struct *p)
7463 {
7464 	unsigned long free = 0;
7465 	int ppid;
7466 
7467 	if (!try_get_task_stack(p))
7468 		return;
7469 
7470 	pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
7471 
7472 	if (task_is_running(p))
7473 		pr_cont("  running task    ");
7474 #ifdef CONFIG_DEBUG_STACK_USAGE
7475 	free = stack_not_used(p);
7476 #endif
7477 	ppid = 0;
7478 	rcu_read_lock();
7479 	if (pid_alive(p))
7480 		ppid = task_pid_nr(rcu_dereference(p->real_parent));
7481 	rcu_read_unlock();
7482 	pr_cont(" stack:%-5lu pid:%-5d tgid:%-5d ppid:%-6d flags:0x%08lx\n",
7483 		free, task_pid_nr(p), task_tgid_nr(p),
7484 		ppid, read_task_thread_flags(p));
7485 
7486 	print_worker_info(KERN_INFO, p);
7487 	print_stop_info(KERN_INFO, p);
7488 	show_stack(p, NULL, KERN_INFO);
7489 	put_task_stack(p);
7490 }
7491 EXPORT_SYMBOL_GPL(sched_show_task);
7492 
7493 static inline bool
7494 state_filter_match(unsigned long state_filter, struct task_struct *p)
7495 {
7496 	unsigned int state = READ_ONCE(p->__state);
7497 
7498 	/* no filter, everything matches */
7499 	if (!state_filter)
7500 		return true;
7501 
7502 	/* filter, but doesn't match */
7503 	if (!(state & state_filter))
7504 		return false;
7505 
7506 	/*
7507 	 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
7508 	 * TASK_KILLABLE).
7509 	 */
7510 	if (state_filter == TASK_UNINTERRUPTIBLE && (state & TASK_NOLOAD))
7511 		return false;
7512 
7513 	return true;
7514 }
7515 
7516 
7517 void show_state_filter(unsigned int state_filter)
7518 {
7519 	struct task_struct *g, *p;
7520 
7521 	rcu_read_lock();
7522 	for_each_process_thread(g, p) {
7523 		/*
7524 		 * reset the NMI-timeout, listing all files on a slow
7525 		 * console might take a lot of time:
7526 		 * Also, reset softlockup watchdogs on all CPUs, because
7527 		 * another CPU might be blocked waiting for us to process
7528 		 * an IPI.
7529 		 */
7530 		touch_nmi_watchdog();
7531 		touch_all_softlockup_watchdogs();
7532 		if (state_filter_match(state_filter, p))
7533 			sched_show_task(p);
7534 	}
7535 
7536 #ifdef CONFIG_SCHED_DEBUG
7537 	if (!state_filter)
7538 		sysrq_sched_debug_show();
7539 #endif
7540 	rcu_read_unlock();
7541 	/*
7542 	 * Only show locks if all tasks are dumped:
7543 	 */
7544 	if (!state_filter)
7545 		debug_show_all_locks();
7546 }
7547 
7548 /**
7549  * init_idle - set up an idle thread for a given CPU
7550  * @idle: task in question
7551  * @cpu: CPU the idle task belongs to
7552  *
7553  * NOTE: this function does not set the idle thread's NEED_RESCHED
7554  * flag, to make booting more robust.
7555  */
7556 void __init init_idle(struct task_struct *idle, int cpu)
7557 {
7558 #ifdef CONFIG_SMP
7559 	struct affinity_context ac = (struct affinity_context) {
7560 		.new_mask  = cpumask_of(cpu),
7561 		.flags     = 0,
7562 	};
7563 #endif
7564 	struct rq *rq = cpu_rq(cpu);
7565 	unsigned long flags;
7566 
7567 	__sched_fork(0, idle);
7568 
7569 	raw_spin_lock_irqsave(&idle->pi_lock, flags);
7570 	raw_spin_rq_lock(rq);
7571 
7572 	idle->__state = TASK_RUNNING;
7573 	idle->se.exec_start = sched_clock();
7574 	/*
7575 	 * PF_KTHREAD should already be set at this point; regardless, make it
7576 	 * look like a proper per-CPU kthread.
7577 	 */
7578 	idle->flags |= PF_KTHREAD | PF_NO_SETAFFINITY;
7579 	kthread_set_per_cpu(idle, cpu);
7580 
7581 #ifdef CONFIG_SMP
7582 	/*
7583 	 * It's possible that init_idle() gets called multiple times on a task,
7584 	 * in that case do_set_cpus_allowed() will not do the right thing.
7585 	 *
7586 	 * And since this is boot we can forgo the serialization.
7587 	 */
7588 	set_cpus_allowed_common(idle, &ac);
7589 #endif
7590 	/*
7591 	 * We're having a chicken and egg problem, even though we are
7592 	 * holding rq->lock, the CPU isn't yet set to this CPU so the
7593 	 * lockdep check in task_group() will fail.
7594 	 *
7595 	 * Similar case to sched_fork(). / Alternatively we could
7596 	 * use task_rq_lock() here and obtain the other rq->lock.
7597 	 *
7598 	 * Silence PROVE_RCU
7599 	 */
7600 	rcu_read_lock();
7601 	__set_task_cpu(idle, cpu);
7602 	rcu_read_unlock();
7603 
7604 	rq->idle = idle;
7605 	rcu_assign_pointer(rq->curr, idle);
7606 	idle->on_rq = TASK_ON_RQ_QUEUED;
7607 #ifdef CONFIG_SMP
7608 	idle->on_cpu = 1;
7609 #endif
7610 	raw_spin_rq_unlock(rq);
7611 	raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
7612 
7613 	/* Set the preempt count _outside_ the spinlocks! */
7614 	init_idle_preempt_count(idle, cpu);
7615 
7616 	/*
7617 	 * The idle tasks have their own, simple scheduling class:
7618 	 */
7619 	idle->sched_class = &idle_sched_class;
7620 	ftrace_graph_init_idle_task(idle, cpu);
7621 	vtime_init_idle(idle, cpu);
7622 #ifdef CONFIG_SMP
7623 	sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
7624 #endif
7625 }
7626 
7627 #ifdef CONFIG_SMP
7628 
7629 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
7630 			      const struct cpumask *trial)
7631 {
7632 	int ret = 1;
7633 
7634 	if (cpumask_empty(cur))
7635 		return ret;
7636 
7637 	ret = dl_cpuset_cpumask_can_shrink(cur, trial);
7638 
7639 	return ret;
7640 }
7641 
7642 int task_can_attach(struct task_struct *p)
7643 {
7644 	int ret = 0;
7645 
7646 	/*
7647 	 * Kthreads which disallow setaffinity shouldn't be moved
7648 	 * to a new cpuset; we don't want to change their CPU
7649 	 * affinity and isolating such threads by their set of
7650 	 * allowed nodes is unnecessary.  Thus, cpusets are not
7651 	 * applicable for such threads.  This prevents checking for
7652 	 * success of set_cpus_allowed_ptr() on all attached tasks
7653 	 * before cpus_mask may be changed.
7654 	 */
7655 	if (p->flags & PF_NO_SETAFFINITY)
7656 		ret = -EINVAL;
7657 
7658 	return ret;
7659 }
7660 
7661 bool sched_smp_initialized __read_mostly;
7662 
7663 #ifdef CONFIG_NUMA_BALANCING
7664 /* Migrate current task p to target_cpu */
7665 int migrate_task_to(struct task_struct *p, int target_cpu)
7666 {
7667 	struct migration_arg arg = { p, target_cpu };
7668 	int curr_cpu = task_cpu(p);
7669 
7670 	if (curr_cpu == target_cpu)
7671 		return 0;
7672 
7673 	if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
7674 		return -EINVAL;
7675 
7676 	/* TODO: This is not properly updating schedstats */
7677 
7678 	trace_sched_move_numa(p, curr_cpu, target_cpu);
7679 	return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
7680 }
7681 
7682 /*
7683  * Requeue a task on a given node and accurately track the number of NUMA
7684  * tasks on the runqueues
7685  */
7686 void sched_setnuma(struct task_struct *p, int nid)
7687 {
7688 	bool queued, running;
7689 	struct rq_flags rf;
7690 	struct rq *rq;
7691 
7692 	rq = task_rq_lock(p, &rf);
7693 	queued = task_on_rq_queued(p);
7694 	running = task_current(rq, p);
7695 
7696 	if (queued)
7697 		dequeue_task(rq, p, DEQUEUE_SAVE);
7698 	if (running)
7699 		put_prev_task(rq, p);
7700 
7701 	p->numa_preferred_nid = nid;
7702 
7703 	if (queued)
7704 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
7705 	if (running)
7706 		set_next_task(rq, p);
7707 	task_rq_unlock(rq, p, &rf);
7708 }
7709 #endif /* CONFIG_NUMA_BALANCING */
7710 
7711 #ifdef CONFIG_HOTPLUG_CPU
7712 /*
7713  * Ensure that the idle task is using init_mm right before its CPU goes
7714  * offline.
7715  */
7716 void idle_task_exit(void)
7717 {
7718 	struct mm_struct *mm = current->active_mm;
7719 
7720 	BUG_ON(cpu_online(smp_processor_id()));
7721 	BUG_ON(current != this_rq()->idle);
7722 
7723 	if (mm != &init_mm) {
7724 		switch_mm(mm, &init_mm, current);
7725 		finish_arch_post_lock_switch();
7726 	}
7727 
7728 	/* finish_cpu(), as ran on the BP, will clean up the active_mm state */
7729 }
7730 
7731 static int __balance_push_cpu_stop(void *arg)
7732 {
7733 	struct task_struct *p = arg;
7734 	struct rq *rq = this_rq();
7735 	struct rq_flags rf;
7736 	int cpu;
7737 
7738 	raw_spin_lock_irq(&p->pi_lock);
7739 	rq_lock(rq, &rf);
7740 
7741 	update_rq_clock(rq);
7742 
7743 	if (task_rq(p) == rq && task_on_rq_queued(p)) {
7744 		cpu = select_fallback_rq(rq->cpu, p);
7745 		rq = __migrate_task(rq, &rf, p, cpu);
7746 	}
7747 
7748 	rq_unlock(rq, &rf);
7749 	raw_spin_unlock_irq(&p->pi_lock);
7750 
7751 	put_task_struct(p);
7752 
7753 	return 0;
7754 }
7755 
7756 static DEFINE_PER_CPU(struct cpu_stop_work, push_work);
7757 
7758 /*
7759  * Ensure we only run per-cpu kthreads once the CPU goes !active.
7760  *
7761  * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only
7762  * effective when the hotplug motion is down.
7763  */
7764 static void balance_push(struct rq *rq)
7765 {
7766 	struct task_struct *push_task = rq->curr;
7767 
7768 	lockdep_assert_rq_held(rq);
7769 
7770 	/*
7771 	 * Ensure the thing is persistent until balance_push_set(.on = false);
7772 	 */
7773 	rq->balance_callback = &balance_push_callback;
7774 
7775 	/*
7776 	 * Only active while going offline and when invoked on the outgoing
7777 	 * CPU.
7778 	 */
7779 	if (!cpu_dying(rq->cpu) || rq != this_rq())
7780 		return;
7781 
7782 	/*
7783 	 * Both the cpu-hotplug and stop task are in this case and are
7784 	 * required to complete the hotplug process.
7785 	 */
7786 	if (kthread_is_per_cpu(push_task) ||
7787 	    is_migration_disabled(push_task)) {
7788 
7789 		/*
7790 		 * If this is the idle task on the outgoing CPU try to wake
7791 		 * up the hotplug control thread which might wait for the
7792 		 * last task to vanish. The rcuwait_active() check is
7793 		 * accurate here because the waiter is pinned on this CPU
7794 		 * and can't obviously be running in parallel.
7795 		 *
7796 		 * On RT kernels this also has to check whether there are
7797 		 * pinned and scheduled out tasks on the runqueue. They
7798 		 * need to leave the migrate disabled section first.
7799 		 */
7800 		if (!rq->nr_running && !rq_has_pinned_tasks(rq) &&
7801 		    rcuwait_active(&rq->hotplug_wait)) {
7802 			raw_spin_rq_unlock(rq);
7803 			rcuwait_wake_up(&rq->hotplug_wait);
7804 			raw_spin_rq_lock(rq);
7805 		}
7806 		return;
7807 	}
7808 
7809 	get_task_struct(push_task);
7810 	/*
7811 	 * Temporarily drop rq->lock such that we can wake-up the stop task.
7812 	 * Both preemption and IRQs are still disabled.
7813 	 */
7814 	preempt_disable();
7815 	raw_spin_rq_unlock(rq);
7816 	stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task,
7817 			    this_cpu_ptr(&push_work));
7818 	preempt_enable();
7819 	/*
7820 	 * At this point need_resched() is true and we'll take the loop in
7821 	 * schedule(). The next pick is obviously going to be the stop task
7822 	 * which kthread_is_per_cpu() and will push this task away.
7823 	 */
7824 	raw_spin_rq_lock(rq);
7825 }
7826 
7827 static void balance_push_set(int cpu, bool on)
7828 {
7829 	struct rq *rq = cpu_rq(cpu);
7830 	struct rq_flags rf;
7831 
7832 	rq_lock_irqsave(rq, &rf);
7833 	if (on) {
7834 		WARN_ON_ONCE(rq->balance_callback);
7835 		rq->balance_callback = &balance_push_callback;
7836 	} else if (rq->balance_callback == &balance_push_callback) {
7837 		rq->balance_callback = NULL;
7838 	}
7839 	rq_unlock_irqrestore(rq, &rf);
7840 }
7841 
7842 /*
7843  * Invoked from a CPUs hotplug control thread after the CPU has been marked
7844  * inactive. All tasks which are not per CPU kernel threads are either
7845  * pushed off this CPU now via balance_push() or placed on a different CPU
7846  * during wakeup. Wait until the CPU is quiescent.
7847  */
7848 static void balance_hotplug_wait(void)
7849 {
7850 	struct rq *rq = this_rq();
7851 
7852 	rcuwait_wait_event(&rq->hotplug_wait,
7853 			   rq->nr_running == 1 && !rq_has_pinned_tasks(rq),
7854 			   TASK_UNINTERRUPTIBLE);
7855 }
7856 
7857 #else
7858 
7859 static inline void balance_push(struct rq *rq)
7860 {
7861 }
7862 
7863 static inline void balance_push_set(int cpu, bool on)
7864 {
7865 }
7866 
7867 static inline void balance_hotplug_wait(void)
7868 {
7869 }
7870 
7871 #endif /* CONFIG_HOTPLUG_CPU */
7872 
7873 void set_rq_online(struct rq *rq)
7874 {
7875 	if (!rq->online) {
7876 		const struct sched_class *class;
7877 
7878 		cpumask_set_cpu(rq->cpu, rq->rd->online);
7879 		rq->online = 1;
7880 
7881 		for_each_class(class) {
7882 			if (class->rq_online)
7883 				class->rq_online(rq);
7884 		}
7885 	}
7886 }
7887 
7888 void set_rq_offline(struct rq *rq)
7889 {
7890 	if (rq->online) {
7891 		const struct sched_class *class;
7892 
7893 		update_rq_clock(rq);
7894 		for_each_class(class) {
7895 			if (class->rq_offline)
7896 				class->rq_offline(rq);
7897 		}
7898 
7899 		cpumask_clear_cpu(rq->cpu, rq->rd->online);
7900 		rq->online = 0;
7901 	}
7902 }
7903 
7904 /*
7905  * used to mark begin/end of suspend/resume:
7906  */
7907 static int num_cpus_frozen;
7908 
7909 /*
7910  * Update cpusets according to cpu_active mask.  If cpusets are
7911  * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7912  * around partition_sched_domains().
7913  *
7914  * If we come here as part of a suspend/resume, don't touch cpusets because we
7915  * want to restore it back to its original state upon resume anyway.
7916  */
7917 static void cpuset_cpu_active(void)
7918 {
7919 	if (cpuhp_tasks_frozen) {
7920 		/*
7921 		 * num_cpus_frozen tracks how many CPUs are involved in suspend
7922 		 * resume sequence. As long as this is not the last online
7923 		 * operation in the resume sequence, just build a single sched
7924 		 * domain, ignoring cpusets.
7925 		 */
7926 		partition_sched_domains(1, NULL, NULL);
7927 		if (--num_cpus_frozen)
7928 			return;
7929 		/*
7930 		 * This is the last CPU online operation. So fall through and
7931 		 * restore the original sched domains by considering the
7932 		 * cpuset configurations.
7933 		 */
7934 		cpuset_force_rebuild();
7935 	}
7936 	cpuset_update_active_cpus();
7937 }
7938 
7939 static int cpuset_cpu_inactive(unsigned int cpu)
7940 {
7941 	if (!cpuhp_tasks_frozen) {
7942 		int ret = dl_bw_check_overflow(cpu);
7943 
7944 		if (ret)
7945 			return ret;
7946 		cpuset_update_active_cpus();
7947 	} else {
7948 		num_cpus_frozen++;
7949 		partition_sched_domains(1, NULL, NULL);
7950 	}
7951 	return 0;
7952 }
7953 
7954 int sched_cpu_activate(unsigned int cpu)
7955 {
7956 	struct rq *rq = cpu_rq(cpu);
7957 	struct rq_flags rf;
7958 
7959 	/*
7960 	 * Clear the balance_push callback and prepare to schedule
7961 	 * regular tasks.
7962 	 */
7963 	balance_push_set(cpu, false);
7964 
7965 #ifdef CONFIG_SCHED_SMT
7966 	/*
7967 	 * When going up, increment the number of cores with SMT present.
7968 	 */
7969 	if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
7970 		static_branch_inc_cpuslocked(&sched_smt_present);
7971 #endif
7972 	set_cpu_active(cpu, true);
7973 
7974 	if (sched_smp_initialized) {
7975 		sched_update_numa(cpu, true);
7976 		sched_domains_numa_masks_set(cpu);
7977 		cpuset_cpu_active();
7978 	}
7979 
7980 	/*
7981 	 * Put the rq online, if not already. This happens:
7982 	 *
7983 	 * 1) In the early boot process, because we build the real domains
7984 	 *    after all CPUs have been brought up.
7985 	 *
7986 	 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
7987 	 *    domains.
7988 	 */
7989 	rq_lock_irqsave(rq, &rf);
7990 	if (rq->rd) {
7991 		BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7992 		set_rq_online(rq);
7993 	}
7994 	rq_unlock_irqrestore(rq, &rf);
7995 
7996 	return 0;
7997 }
7998 
7999 int sched_cpu_deactivate(unsigned int cpu)
8000 {
8001 	struct rq *rq = cpu_rq(cpu);
8002 	struct rq_flags rf;
8003 	int ret;
8004 
8005 	/*
8006 	 * Remove CPU from nohz.idle_cpus_mask to prevent participating in
8007 	 * load balancing when not active
8008 	 */
8009 	nohz_balance_exit_idle(rq);
8010 
8011 	set_cpu_active(cpu, false);
8012 
8013 	/*
8014 	 * From this point forward, this CPU will refuse to run any task that
8015 	 * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively
8016 	 * push those tasks away until this gets cleared, see
8017 	 * sched_cpu_dying().
8018 	 */
8019 	balance_push_set(cpu, true);
8020 
8021 	/*
8022 	 * We've cleared cpu_active_mask / set balance_push, wait for all
8023 	 * preempt-disabled and RCU users of this state to go away such that
8024 	 * all new such users will observe it.
8025 	 *
8026 	 * Specifically, we rely on ttwu to no longer target this CPU, see
8027 	 * ttwu_queue_cond() and is_cpu_allowed().
8028 	 *
8029 	 * Do sync before park smpboot threads to take care the RCU boost case.
8030 	 */
8031 	synchronize_rcu();
8032 
8033 	rq_lock_irqsave(rq, &rf);
8034 	if (rq->rd) {
8035 		BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
8036 		set_rq_offline(rq);
8037 	}
8038 	rq_unlock_irqrestore(rq, &rf);
8039 
8040 #ifdef CONFIG_SCHED_SMT
8041 	/*
8042 	 * When going down, decrement the number of cores with SMT present.
8043 	 */
8044 	if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
8045 		static_branch_dec_cpuslocked(&sched_smt_present);
8046 
8047 	sched_core_cpu_deactivate(cpu);
8048 #endif
8049 
8050 	if (!sched_smp_initialized)
8051 		return 0;
8052 
8053 	sched_update_numa(cpu, false);
8054 	ret = cpuset_cpu_inactive(cpu);
8055 	if (ret) {
8056 		balance_push_set(cpu, false);
8057 		set_cpu_active(cpu, true);
8058 		sched_update_numa(cpu, true);
8059 		return ret;
8060 	}
8061 	sched_domains_numa_masks_clear(cpu);
8062 	return 0;
8063 }
8064 
8065 static void sched_rq_cpu_starting(unsigned int cpu)
8066 {
8067 	struct rq *rq = cpu_rq(cpu);
8068 
8069 	rq->calc_load_update = calc_load_update;
8070 	update_max_interval();
8071 }
8072 
8073 int sched_cpu_starting(unsigned int cpu)
8074 {
8075 	sched_core_cpu_starting(cpu);
8076 	sched_rq_cpu_starting(cpu);
8077 	sched_tick_start(cpu);
8078 	return 0;
8079 }
8080 
8081 #ifdef CONFIG_HOTPLUG_CPU
8082 
8083 /*
8084  * Invoked immediately before the stopper thread is invoked to bring the
8085  * CPU down completely. At this point all per CPU kthreads except the
8086  * hotplug thread (current) and the stopper thread (inactive) have been
8087  * either parked or have been unbound from the outgoing CPU. Ensure that
8088  * any of those which might be on the way out are gone.
8089  *
8090  * If after this point a bound task is being woken on this CPU then the
8091  * responsible hotplug callback has failed to do it's job.
8092  * sched_cpu_dying() will catch it with the appropriate fireworks.
8093  */
8094 int sched_cpu_wait_empty(unsigned int cpu)
8095 {
8096 	balance_hotplug_wait();
8097 	return 0;
8098 }
8099 
8100 /*
8101  * Since this CPU is going 'away' for a while, fold any nr_active delta we
8102  * might have. Called from the CPU stopper task after ensuring that the
8103  * stopper is the last running task on the CPU, so nr_active count is
8104  * stable. We need to take the tear-down thread which is calling this into
8105  * account, so we hand in adjust = 1 to the load calculation.
8106  *
8107  * Also see the comment "Global load-average calculations".
8108  */
8109 static void calc_load_migrate(struct rq *rq)
8110 {
8111 	long delta = calc_load_fold_active(rq, 1);
8112 
8113 	if (delta)
8114 		atomic_long_add(delta, &calc_load_tasks);
8115 }
8116 
8117 static void dump_rq_tasks(struct rq *rq, const char *loglvl)
8118 {
8119 	struct task_struct *g, *p;
8120 	int cpu = cpu_of(rq);
8121 
8122 	lockdep_assert_rq_held(rq);
8123 
8124 	printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running);
8125 	for_each_process_thread(g, p) {
8126 		if (task_cpu(p) != cpu)
8127 			continue;
8128 
8129 		if (!task_on_rq_queued(p))
8130 			continue;
8131 
8132 		printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm);
8133 	}
8134 }
8135 
8136 int sched_cpu_dying(unsigned int cpu)
8137 {
8138 	struct rq *rq = cpu_rq(cpu);
8139 	struct rq_flags rf;
8140 
8141 	/* Handle pending wakeups and then migrate everything off */
8142 	sched_tick_stop(cpu);
8143 
8144 	rq_lock_irqsave(rq, &rf);
8145 	if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) {
8146 		WARN(true, "Dying CPU not properly vacated!");
8147 		dump_rq_tasks(rq, KERN_WARNING);
8148 	}
8149 	rq_unlock_irqrestore(rq, &rf);
8150 
8151 	calc_load_migrate(rq);
8152 	update_max_interval();
8153 	hrtick_clear(rq);
8154 	sched_core_cpu_dying(cpu);
8155 	return 0;
8156 }
8157 #endif
8158 
8159 void __init sched_init_smp(void)
8160 {
8161 	sched_init_numa(NUMA_NO_NODE);
8162 
8163 	/*
8164 	 * There's no userspace yet to cause hotplug operations; hence all the
8165 	 * CPU masks are stable and all blatant races in the below code cannot
8166 	 * happen.
8167 	 */
8168 	mutex_lock(&sched_domains_mutex);
8169 	sched_init_domains(cpu_active_mask);
8170 	mutex_unlock(&sched_domains_mutex);
8171 
8172 	/* Move init over to a non-isolated CPU */
8173 	if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0)
8174 		BUG();
8175 	current->flags &= ~PF_NO_SETAFFINITY;
8176 	sched_init_granularity();
8177 
8178 	init_sched_rt_class();
8179 	init_sched_dl_class();
8180 
8181 	sched_smp_initialized = true;
8182 }
8183 
8184 static int __init migration_init(void)
8185 {
8186 	sched_cpu_starting(smp_processor_id());
8187 	return 0;
8188 }
8189 early_initcall(migration_init);
8190 
8191 #else
8192 void __init sched_init_smp(void)
8193 {
8194 	sched_init_granularity();
8195 }
8196 #endif /* CONFIG_SMP */
8197 
8198 int in_sched_functions(unsigned long addr)
8199 {
8200 	return in_lock_functions(addr) ||
8201 		(addr >= (unsigned long)__sched_text_start
8202 		&& addr < (unsigned long)__sched_text_end);
8203 }
8204 
8205 #ifdef CONFIG_CGROUP_SCHED
8206 /*
8207  * Default task group.
8208  * Every task in system belongs to this group at bootup.
8209  */
8210 struct task_group root_task_group;
8211 LIST_HEAD(task_groups);
8212 
8213 /* Cacheline aligned slab cache for task_group */
8214 static struct kmem_cache *task_group_cache __ro_after_init;
8215 #endif
8216 
8217 void __init sched_init(void)
8218 {
8219 	unsigned long ptr = 0;
8220 	int i;
8221 
8222 	/* Make sure the linker didn't screw up */
8223 #ifdef CONFIG_SMP
8224 	BUG_ON(!sched_class_above(&stop_sched_class, &dl_sched_class));
8225 #endif
8226 	BUG_ON(!sched_class_above(&dl_sched_class, &rt_sched_class));
8227 	BUG_ON(!sched_class_above(&rt_sched_class, &fair_sched_class));
8228 	BUG_ON(!sched_class_above(&fair_sched_class, &idle_sched_class));
8229 #ifdef CONFIG_SCHED_CLASS_EXT
8230 	BUG_ON(!sched_class_above(&fair_sched_class, &ext_sched_class));
8231 	BUG_ON(!sched_class_above(&ext_sched_class, &idle_sched_class));
8232 #endif
8233 
8234 	wait_bit_init();
8235 
8236 #ifdef CONFIG_FAIR_GROUP_SCHED
8237 	ptr += 2 * nr_cpu_ids * sizeof(void **);
8238 #endif
8239 #ifdef CONFIG_RT_GROUP_SCHED
8240 	ptr += 2 * nr_cpu_ids * sizeof(void **);
8241 #endif
8242 	if (ptr) {
8243 		ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
8244 
8245 #ifdef CONFIG_FAIR_GROUP_SCHED
8246 		root_task_group.se = (struct sched_entity **)ptr;
8247 		ptr += nr_cpu_ids * sizeof(void **);
8248 
8249 		root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8250 		ptr += nr_cpu_ids * sizeof(void **);
8251 
8252 		root_task_group.shares = ROOT_TASK_GROUP_LOAD;
8253 		init_cfs_bandwidth(&root_task_group.cfs_bandwidth, NULL);
8254 #endif /* CONFIG_FAIR_GROUP_SCHED */
8255 #ifdef CONFIG_RT_GROUP_SCHED
8256 		root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8257 		ptr += nr_cpu_ids * sizeof(void **);
8258 
8259 		root_task_group.rt_rq = (struct rt_rq **)ptr;
8260 		ptr += nr_cpu_ids * sizeof(void **);
8261 
8262 #endif /* CONFIG_RT_GROUP_SCHED */
8263 	}
8264 
8265 	init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
8266 
8267 #ifdef CONFIG_SMP
8268 	init_defrootdomain();
8269 #endif
8270 
8271 #ifdef CONFIG_RT_GROUP_SCHED
8272 	init_rt_bandwidth(&root_task_group.rt_bandwidth,
8273 			global_rt_period(), global_rt_runtime());
8274 #endif /* CONFIG_RT_GROUP_SCHED */
8275 
8276 #ifdef CONFIG_CGROUP_SCHED
8277 	task_group_cache = KMEM_CACHE(task_group, 0);
8278 
8279 	list_add(&root_task_group.list, &task_groups);
8280 	INIT_LIST_HEAD(&root_task_group.children);
8281 	INIT_LIST_HEAD(&root_task_group.siblings);
8282 	autogroup_init(&init_task);
8283 #endif /* CONFIG_CGROUP_SCHED */
8284 
8285 	for_each_possible_cpu(i) {
8286 		struct rq *rq;
8287 
8288 		rq = cpu_rq(i);
8289 		raw_spin_lock_init(&rq->__lock);
8290 		rq->nr_running = 0;
8291 		rq->calc_load_active = 0;
8292 		rq->calc_load_update = jiffies + LOAD_FREQ;
8293 		init_cfs_rq(&rq->cfs);
8294 		init_rt_rq(&rq->rt);
8295 		init_dl_rq(&rq->dl);
8296 #ifdef CONFIG_FAIR_GROUP_SCHED
8297 		INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8298 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
8299 		/*
8300 		 * How much CPU bandwidth does root_task_group get?
8301 		 *
8302 		 * In case of task-groups formed through the cgroup filesystem, it
8303 		 * gets 100% of the CPU resources in the system. This overall
8304 		 * system CPU resource is divided among the tasks of
8305 		 * root_task_group and its child task-groups in a fair manner,
8306 		 * based on each entity's (task or task-group's) weight
8307 		 * (se->load.weight).
8308 		 *
8309 		 * In other words, if root_task_group has 10 tasks of weight
8310 		 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8311 		 * then A0's share of the CPU resource is:
8312 		 *
8313 		 *	A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8314 		 *
8315 		 * We achieve this by letting root_task_group's tasks sit
8316 		 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
8317 		 */
8318 		init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
8319 #endif /* CONFIG_FAIR_GROUP_SCHED */
8320 
8321 		rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8322 #ifdef CONFIG_RT_GROUP_SCHED
8323 		init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
8324 #endif
8325 #ifdef CONFIG_SMP
8326 		rq->sd = NULL;
8327 		rq->rd = NULL;
8328 		rq->cpu_capacity = SCHED_CAPACITY_SCALE;
8329 		rq->balance_callback = &balance_push_callback;
8330 		rq->active_balance = 0;
8331 		rq->next_balance = jiffies;
8332 		rq->push_cpu = 0;
8333 		rq->cpu = i;
8334 		rq->online = 0;
8335 		rq->idle_stamp = 0;
8336 		rq->avg_idle = 2*sysctl_sched_migration_cost;
8337 		rq->max_idle_balance_cost = sysctl_sched_migration_cost;
8338 
8339 		INIT_LIST_HEAD(&rq->cfs_tasks);
8340 
8341 		rq_attach_root(rq, &def_root_domain);
8342 #ifdef CONFIG_NO_HZ_COMMON
8343 		rq->last_blocked_load_update_tick = jiffies;
8344 		atomic_set(&rq->nohz_flags, 0);
8345 
8346 		INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq);
8347 #endif
8348 #ifdef CONFIG_HOTPLUG_CPU
8349 		rcuwait_init(&rq->hotplug_wait);
8350 #endif
8351 #endif /* CONFIG_SMP */
8352 		hrtick_rq_init(rq);
8353 		atomic_set(&rq->nr_iowait, 0);
8354 
8355 #ifdef CONFIG_SCHED_CORE
8356 		rq->core = rq;
8357 		rq->core_pick = NULL;
8358 		rq->core_enabled = 0;
8359 		rq->core_tree = RB_ROOT;
8360 		rq->core_forceidle_count = 0;
8361 		rq->core_forceidle_occupation = 0;
8362 		rq->core_forceidle_start = 0;
8363 
8364 		rq->core_cookie = 0UL;
8365 #endif
8366 		zalloc_cpumask_var_node(&rq->scratch_mask, GFP_KERNEL, cpu_to_node(i));
8367 	}
8368 
8369 	set_load_weight(&init_task, false);
8370 
8371 	/*
8372 	 * The boot idle thread does lazy MMU switching as well:
8373 	 */
8374 	mmgrab_lazy_tlb(&init_mm);
8375 	enter_lazy_tlb(&init_mm, current);
8376 
8377 	/*
8378 	 * The idle task doesn't need the kthread struct to function, but it
8379 	 * is dressed up as a per-CPU kthread and thus needs to play the part
8380 	 * if we want to avoid special-casing it in code that deals with per-CPU
8381 	 * kthreads.
8382 	 */
8383 	WARN_ON(!set_kthread_struct(current));
8384 
8385 	/*
8386 	 * Make us the idle thread. Technically, schedule() should not be
8387 	 * called from this thread, however somewhere below it might be,
8388 	 * but because we are the idle thread, we just pick up running again
8389 	 * when this runqueue becomes "idle".
8390 	 */
8391 	init_idle(current, smp_processor_id());
8392 
8393 	calc_load_update = jiffies + LOAD_FREQ;
8394 
8395 #ifdef CONFIG_SMP
8396 	idle_thread_set_boot_cpu();
8397 	balance_push_set(smp_processor_id(), false);
8398 #endif
8399 	init_sched_fair_class();
8400 	init_sched_ext_class();
8401 
8402 	psi_init();
8403 
8404 	init_uclamp();
8405 
8406 	preempt_dynamic_init();
8407 
8408 	scheduler_running = 1;
8409 }
8410 
8411 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
8412 
8413 void __might_sleep(const char *file, int line)
8414 {
8415 	unsigned int state = get_current_state();
8416 	/*
8417 	 * Blocking primitives will set (and therefore destroy) current->state,
8418 	 * since we will exit with TASK_RUNNING make sure we enter with it,
8419 	 * otherwise we will destroy state.
8420 	 */
8421 	WARN_ONCE(state != TASK_RUNNING && current->task_state_change,
8422 			"do not call blocking ops when !TASK_RUNNING; "
8423 			"state=%x set at [<%p>] %pS\n", state,
8424 			(void *)current->task_state_change,
8425 			(void *)current->task_state_change);
8426 
8427 	__might_resched(file, line, 0);
8428 }
8429 EXPORT_SYMBOL(__might_sleep);
8430 
8431 static void print_preempt_disable_ip(int preempt_offset, unsigned long ip)
8432 {
8433 	if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT))
8434 		return;
8435 
8436 	if (preempt_count() == preempt_offset)
8437 		return;
8438 
8439 	pr_err("Preemption disabled at:");
8440 	print_ip_sym(KERN_ERR, ip);
8441 }
8442 
8443 static inline bool resched_offsets_ok(unsigned int offsets)
8444 {
8445 	unsigned int nested = preempt_count();
8446 
8447 	nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT;
8448 
8449 	return nested == offsets;
8450 }
8451 
8452 void __might_resched(const char *file, int line, unsigned int offsets)
8453 {
8454 	/* Ratelimiting timestamp: */
8455 	static unsigned long prev_jiffy;
8456 
8457 	unsigned long preempt_disable_ip;
8458 
8459 	/* WARN_ON_ONCE() by default, no rate limit required: */
8460 	rcu_sleep_check();
8461 
8462 	if ((resched_offsets_ok(offsets) && !irqs_disabled() &&
8463 	     !is_idle_task(current) && !current->non_block_count) ||
8464 	    system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
8465 	    oops_in_progress)
8466 		return;
8467 
8468 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8469 		return;
8470 	prev_jiffy = jiffies;
8471 
8472 	/* Save this before calling printk(), since that will clobber it: */
8473 	preempt_disable_ip = get_preempt_disable_ip(current);
8474 
8475 	pr_err("BUG: sleeping function called from invalid context at %s:%d\n",
8476 	       file, line);
8477 	pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
8478 	       in_atomic(), irqs_disabled(), current->non_block_count,
8479 	       current->pid, current->comm);
8480 	pr_err("preempt_count: %x, expected: %x\n", preempt_count(),
8481 	       offsets & MIGHT_RESCHED_PREEMPT_MASK);
8482 
8483 	if (IS_ENABLED(CONFIG_PREEMPT_RCU)) {
8484 		pr_err("RCU nest depth: %d, expected: %u\n",
8485 		       rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT);
8486 	}
8487 
8488 	if (task_stack_end_corrupted(current))
8489 		pr_emerg("Thread overran stack, or stack corrupted\n");
8490 
8491 	debug_show_held_locks(current);
8492 	if (irqs_disabled())
8493 		print_irqtrace_events(current);
8494 
8495 	print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK,
8496 				 preempt_disable_ip);
8497 
8498 	dump_stack();
8499 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
8500 }
8501 EXPORT_SYMBOL(__might_resched);
8502 
8503 void __cant_sleep(const char *file, int line, int preempt_offset)
8504 {
8505 	static unsigned long prev_jiffy;
8506 
8507 	if (irqs_disabled())
8508 		return;
8509 
8510 	if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
8511 		return;
8512 
8513 	if (preempt_count() > preempt_offset)
8514 		return;
8515 
8516 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8517 		return;
8518 	prev_jiffy = jiffies;
8519 
8520 	printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
8521 	printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
8522 			in_atomic(), irqs_disabled(),
8523 			current->pid, current->comm);
8524 
8525 	debug_show_held_locks(current);
8526 	dump_stack();
8527 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
8528 }
8529 EXPORT_SYMBOL_GPL(__cant_sleep);
8530 
8531 #ifdef CONFIG_SMP
8532 void __cant_migrate(const char *file, int line)
8533 {
8534 	static unsigned long prev_jiffy;
8535 
8536 	if (irqs_disabled())
8537 		return;
8538 
8539 	if (is_migration_disabled(current))
8540 		return;
8541 
8542 	if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
8543 		return;
8544 
8545 	if (preempt_count() > 0)
8546 		return;
8547 
8548 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8549 		return;
8550 	prev_jiffy = jiffies;
8551 
8552 	pr_err("BUG: assuming non migratable context at %s:%d\n", file, line);
8553 	pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n",
8554 	       in_atomic(), irqs_disabled(), is_migration_disabled(current),
8555 	       current->pid, current->comm);
8556 
8557 	debug_show_held_locks(current);
8558 	dump_stack();
8559 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
8560 }
8561 EXPORT_SYMBOL_GPL(__cant_migrate);
8562 #endif
8563 #endif
8564 
8565 #ifdef CONFIG_MAGIC_SYSRQ
8566 void normalize_rt_tasks(void)
8567 {
8568 	struct task_struct *g, *p;
8569 	struct sched_attr attr = {
8570 		.sched_policy = SCHED_NORMAL,
8571 	};
8572 
8573 	read_lock(&tasklist_lock);
8574 	for_each_process_thread(g, p) {
8575 		/*
8576 		 * Only normalize user tasks:
8577 		 */
8578 		if (p->flags & PF_KTHREAD)
8579 			continue;
8580 
8581 		p->se.exec_start = 0;
8582 		schedstat_set(p->stats.wait_start,  0);
8583 		schedstat_set(p->stats.sleep_start, 0);
8584 		schedstat_set(p->stats.block_start, 0);
8585 
8586 		if (!dl_task(p) && !rt_task(p)) {
8587 			/*
8588 			 * Renice negative nice level userspace
8589 			 * tasks back to 0:
8590 			 */
8591 			if (task_nice(p) < 0)
8592 				set_user_nice(p, 0);
8593 			continue;
8594 		}
8595 
8596 		__sched_setscheduler(p, &attr, false, false);
8597 	}
8598 	read_unlock(&tasklist_lock);
8599 }
8600 
8601 #endif /* CONFIG_MAGIC_SYSRQ */
8602 
8603 #if defined(CONFIG_KGDB_KDB)
8604 /*
8605  * These functions are only useful for KDB.
8606  *
8607  * They can only be called when the whole system has been
8608  * stopped - every CPU needs to be quiescent, and no scheduling
8609  * activity can take place. Using them for anything else would
8610  * be a serious bug, and as a result, they aren't even visible
8611  * under any other configuration.
8612  */
8613 
8614 /**
8615  * curr_task - return the current task for a given CPU.
8616  * @cpu: the processor in question.
8617  *
8618  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8619  *
8620  * Return: The current task for @cpu.
8621  */
8622 struct task_struct *curr_task(int cpu)
8623 {
8624 	return cpu_curr(cpu);
8625 }
8626 
8627 #endif /* defined(CONFIG_KGDB_KDB) */
8628 
8629 #ifdef CONFIG_CGROUP_SCHED
8630 /* task_group_lock serializes the addition/removal of task groups */
8631 static DEFINE_SPINLOCK(task_group_lock);
8632 
8633 static inline void alloc_uclamp_sched_group(struct task_group *tg,
8634 					    struct task_group *parent)
8635 {
8636 #ifdef CONFIG_UCLAMP_TASK_GROUP
8637 	enum uclamp_id clamp_id;
8638 
8639 	for_each_clamp_id(clamp_id) {
8640 		uclamp_se_set(&tg->uclamp_req[clamp_id],
8641 			      uclamp_none(clamp_id), false);
8642 		tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
8643 	}
8644 #endif
8645 }
8646 
8647 static void sched_free_group(struct task_group *tg)
8648 {
8649 	free_fair_sched_group(tg);
8650 	free_rt_sched_group(tg);
8651 	autogroup_free(tg);
8652 	kmem_cache_free(task_group_cache, tg);
8653 }
8654 
8655 static void sched_free_group_rcu(struct rcu_head *rcu)
8656 {
8657 	sched_free_group(container_of(rcu, struct task_group, rcu));
8658 }
8659 
8660 static void sched_unregister_group(struct task_group *tg)
8661 {
8662 	unregister_fair_sched_group(tg);
8663 	unregister_rt_sched_group(tg);
8664 	/*
8665 	 * We have to wait for yet another RCU grace period to expire, as
8666 	 * print_cfs_stats() might run concurrently.
8667 	 */
8668 	call_rcu(&tg->rcu, sched_free_group_rcu);
8669 }
8670 
8671 /* allocate runqueue etc for a new task group */
8672 struct task_group *sched_create_group(struct task_group *parent)
8673 {
8674 	struct task_group *tg;
8675 
8676 	tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
8677 	if (!tg)
8678 		return ERR_PTR(-ENOMEM);
8679 
8680 	if (!alloc_fair_sched_group(tg, parent))
8681 		goto err;
8682 
8683 	if (!alloc_rt_sched_group(tg, parent))
8684 		goto err;
8685 
8686 	alloc_uclamp_sched_group(tg, parent);
8687 
8688 	return tg;
8689 
8690 err:
8691 	sched_free_group(tg);
8692 	return ERR_PTR(-ENOMEM);
8693 }
8694 
8695 void sched_online_group(struct task_group *tg, struct task_group *parent)
8696 {
8697 	unsigned long flags;
8698 
8699 	spin_lock_irqsave(&task_group_lock, flags);
8700 	list_add_rcu(&tg->list, &task_groups);
8701 
8702 	/* Root should already exist: */
8703 	WARN_ON(!parent);
8704 
8705 	tg->parent = parent;
8706 	INIT_LIST_HEAD(&tg->children);
8707 	list_add_rcu(&tg->siblings, &parent->children);
8708 	spin_unlock_irqrestore(&task_group_lock, flags);
8709 
8710 	online_fair_sched_group(tg);
8711 }
8712 
8713 /* RCU callback to free various structures associated with a task group */
8714 static void sched_unregister_group_rcu(struct rcu_head *rhp)
8715 {
8716 	/* Now it should be safe to free those cfs_rqs: */
8717 	sched_unregister_group(container_of(rhp, struct task_group, rcu));
8718 }
8719 
8720 void sched_destroy_group(struct task_group *tg)
8721 {
8722 	/* Wait for possible concurrent references to cfs_rqs complete: */
8723 	call_rcu(&tg->rcu, sched_unregister_group_rcu);
8724 }
8725 
8726 void sched_release_group(struct task_group *tg)
8727 {
8728 	unsigned long flags;
8729 
8730 	/*
8731 	 * Unlink first, to avoid walk_tg_tree_from() from finding us (via
8732 	 * sched_cfs_period_timer()).
8733 	 *
8734 	 * For this to be effective, we have to wait for all pending users of
8735 	 * this task group to leave their RCU critical section to ensure no new
8736 	 * user will see our dying task group any more. Specifically ensure
8737 	 * that tg_unthrottle_up() won't add decayed cfs_rq's to it.
8738 	 *
8739 	 * We therefore defer calling unregister_fair_sched_group() to
8740 	 * sched_unregister_group() which is guarantied to get called only after the
8741 	 * current RCU grace period has expired.
8742 	 */
8743 	spin_lock_irqsave(&task_group_lock, flags);
8744 	list_del_rcu(&tg->list);
8745 	list_del_rcu(&tg->siblings);
8746 	spin_unlock_irqrestore(&task_group_lock, flags);
8747 }
8748 
8749 static struct task_group *sched_get_task_group(struct task_struct *tsk)
8750 {
8751 	struct task_group *tg;
8752 
8753 	/*
8754 	 * All callers are synchronized by task_rq_lock(); we do not use RCU
8755 	 * which is pointless here. Thus, we pass "true" to task_css_check()
8756 	 * to prevent lockdep warnings.
8757 	 */
8758 	tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
8759 			  struct task_group, css);
8760 	tg = autogroup_task_group(tsk, tg);
8761 
8762 	return tg;
8763 }
8764 
8765 static void sched_change_group(struct task_struct *tsk, struct task_group *group)
8766 {
8767 	tsk->sched_task_group = group;
8768 
8769 #ifdef CONFIG_FAIR_GROUP_SCHED
8770 	if (tsk->sched_class->task_change_group)
8771 		tsk->sched_class->task_change_group(tsk);
8772 	else
8773 #endif
8774 		set_task_rq(tsk, task_cpu(tsk));
8775 }
8776 
8777 /*
8778  * Change task's runqueue when it moves between groups.
8779  *
8780  * The caller of this function should have put the task in its new group by
8781  * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
8782  * its new group.
8783  */
8784 void sched_move_task(struct task_struct *tsk)
8785 {
8786 	int queued, running, queue_flags =
8787 		DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
8788 	struct task_group *group;
8789 	struct rq *rq;
8790 
8791 	CLASS(task_rq_lock, rq_guard)(tsk);
8792 	rq = rq_guard.rq;
8793 
8794 	/*
8795 	 * Esp. with SCHED_AUTOGROUP enabled it is possible to get superfluous
8796 	 * group changes.
8797 	 */
8798 	group = sched_get_task_group(tsk);
8799 	if (group == tsk->sched_task_group)
8800 		return;
8801 
8802 	update_rq_clock(rq);
8803 
8804 	running = task_current(rq, tsk);
8805 	queued = task_on_rq_queued(tsk);
8806 
8807 	if (queued)
8808 		dequeue_task(rq, tsk, queue_flags);
8809 	if (running)
8810 		put_prev_task(rq, tsk);
8811 
8812 	sched_change_group(tsk, group);
8813 
8814 	if (queued)
8815 		enqueue_task(rq, tsk, queue_flags);
8816 	if (running) {
8817 		set_next_task(rq, tsk);
8818 		/*
8819 		 * After changing group, the running task may have joined a
8820 		 * throttled one but it's still the running task. Trigger a
8821 		 * resched to make sure that task can still run.
8822 		 */
8823 		resched_curr(rq);
8824 	}
8825 }
8826 
8827 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
8828 {
8829 	return css ? container_of(css, struct task_group, css) : NULL;
8830 }
8831 
8832 static struct cgroup_subsys_state *
8833 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8834 {
8835 	struct task_group *parent = css_tg(parent_css);
8836 	struct task_group *tg;
8837 
8838 	if (!parent) {
8839 		/* This is early initialization for the top cgroup */
8840 		return &root_task_group.css;
8841 	}
8842 
8843 	tg = sched_create_group(parent);
8844 	if (IS_ERR(tg))
8845 		return ERR_PTR(-ENOMEM);
8846 
8847 	return &tg->css;
8848 }
8849 
8850 /* Expose task group only after completing cgroup initialization */
8851 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
8852 {
8853 	struct task_group *tg = css_tg(css);
8854 	struct task_group *parent = css_tg(css->parent);
8855 
8856 	if (parent)
8857 		sched_online_group(tg, parent);
8858 
8859 #ifdef CONFIG_UCLAMP_TASK_GROUP
8860 	/* Propagate the effective uclamp value for the new group */
8861 	guard(mutex)(&uclamp_mutex);
8862 	guard(rcu)();
8863 	cpu_util_update_eff(css);
8864 #endif
8865 
8866 	return 0;
8867 }
8868 
8869 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
8870 {
8871 	struct task_group *tg = css_tg(css);
8872 
8873 	sched_release_group(tg);
8874 }
8875 
8876 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
8877 {
8878 	struct task_group *tg = css_tg(css);
8879 
8880 	/*
8881 	 * Relies on the RCU grace period between css_released() and this.
8882 	 */
8883 	sched_unregister_group(tg);
8884 }
8885 
8886 #ifdef CONFIG_RT_GROUP_SCHED
8887 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
8888 {
8889 	struct task_struct *task;
8890 	struct cgroup_subsys_state *css;
8891 
8892 	cgroup_taskset_for_each(task, css, tset) {
8893 		if (!sched_rt_can_attach(css_tg(css), task))
8894 			return -EINVAL;
8895 	}
8896 	return 0;
8897 }
8898 #endif
8899 
8900 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
8901 {
8902 	struct task_struct *task;
8903 	struct cgroup_subsys_state *css;
8904 
8905 	cgroup_taskset_for_each(task, css, tset)
8906 		sched_move_task(task);
8907 }
8908 
8909 #ifdef CONFIG_UCLAMP_TASK_GROUP
8910 static void cpu_util_update_eff(struct cgroup_subsys_state *css)
8911 {
8912 	struct cgroup_subsys_state *top_css = css;
8913 	struct uclamp_se *uc_parent = NULL;
8914 	struct uclamp_se *uc_se = NULL;
8915 	unsigned int eff[UCLAMP_CNT];
8916 	enum uclamp_id clamp_id;
8917 	unsigned int clamps;
8918 
8919 	lockdep_assert_held(&uclamp_mutex);
8920 	SCHED_WARN_ON(!rcu_read_lock_held());
8921 
8922 	css_for_each_descendant_pre(css, top_css) {
8923 		uc_parent = css_tg(css)->parent
8924 			? css_tg(css)->parent->uclamp : NULL;
8925 
8926 		for_each_clamp_id(clamp_id) {
8927 			/* Assume effective clamps matches requested clamps */
8928 			eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
8929 			/* Cap effective clamps with parent's effective clamps */
8930 			if (uc_parent &&
8931 			    eff[clamp_id] > uc_parent[clamp_id].value) {
8932 				eff[clamp_id] = uc_parent[clamp_id].value;
8933 			}
8934 		}
8935 		/* Ensure protection is always capped by limit */
8936 		eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
8937 
8938 		/* Propagate most restrictive effective clamps */
8939 		clamps = 0x0;
8940 		uc_se = css_tg(css)->uclamp;
8941 		for_each_clamp_id(clamp_id) {
8942 			if (eff[clamp_id] == uc_se[clamp_id].value)
8943 				continue;
8944 			uc_se[clamp_id].value = eff[clamp_id];
8945 			uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
8946 			clamps |= (0x1 << clamp_id);
8947 		}
8948 		if (!clamps) {
8949 			css = css_rightmost_descendant(css);
8950 			continue;
8951 		}
8952 
8953 		/* Immediately update descendants RUNNABLE tasks */
8954 		uclamp_update_active_tasks(css);
8955 	}
8956 }
8957 
8958 /*
8959  * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
8960  * C expression. Since there is no way to convert a macro argument (N) into a
8961  * character constant, use two levels of macros.
8962  */
8963 #define _POW10(exp) ((unsigned int)1e##exp)
8964 #define POW10(exp) _POW10(exp)
8965 
8966 struct uclamp_request {
8967 #define UCLAMP_PERCENT_SHIFT	2
8968 #define UCLAMP_PERCENT_SCALE	(100 * POW10(UCLAMP_PERCENT_SHIFT))
8969 	s64 percent;
8970 	u64 util;
8971 	int ret;
8972 };
8973 
8974 static inline struct uclamp_request
8975 capacity_from_percent(char *buf)
8976 {
8977 	struct uclamp_request req = {
8978 		.percent = UCLAMP_PERCENT_SCALE,
8979 		.util = SCHED_CAPACITY_SCALE,
8980 		.ret = 0,
8981 	};
8982 
8983 	buf = strim(buf);
8984 	if (strcmp(buf, "max")) {
8985 		req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
8986 					     &req.percent);
8987 		if (req.ret)
8988 			return req;
8989 		if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
8990 			req.ret = -ERANGE;
8991 			return req;
8992 		}
8993 
8994 		req.util = req.percent << SCHED_CAPACITY_SHIFT;
8995 		req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
8996 	}
8997 
8998 	return req;
8999 }
9000 
9001 static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
9002 				size_t nbytes, loff_t off,
9003 				enum uclamp_id clamp_id)
9004 {
9005 	struct uclamp_request req;
9006 	struct task_group *tg;
9007 
9008 	req = capacity_from_percent(buf);
9009 	if (req.ret)
9010 		return req.ret;
9011 
9012 	static_branch_enable(&sched_uclamp_used);
9013 
9014 	guard(mutex)(&uclamp_mutex);
9015 	guard(rcu)();
9016 
9017 	tg = css_tg(of_css(of));
9018 	if (tg->uclamp_req[clamp_id].value != req.util)
9019 		uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
9020 
9021 	/*
9022 	 * Because of not recoverable conversion rounding we keep track of the
9023 	 * exact requested value
9024 	 */
9025 	tg->uclamp_pct[clamp_id] = req.percent;
9026 
9027 	/* Update effective clamps to track the most restrictive value */
9028 	cpu_util_update_eff(of_css(of));
9029 
9030 	return nbytes;
9031 }
9032 
9033 static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
9034 				    char *buf, size_t nbytes,
9035 				    loff_t off)
9036 {
9037 	return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
9038 }
9039 
9040 static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
9041 				    char *buf, size_t nbytes,
9042 				    loff_t off)
9043 {
9044 	return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
9045 }
9046 
9047 static inline void cpu_uclamp_print(struct seq_file *sf,
9048 				    enum uclamp_id clamp_id)
9049 {
9050 	struct task_group *tg;
9051 	u64 util_clamp;
9052 	u64 percent;
9053 	u32 rem;
9054 
9055 	scoped_guard (rcu) {
9056 		tg = css_tg(seq_css(sf));
9057 		util_clamp = tg->uclamp_req[clamp_id].value;
9058 	}
9059 
9060 	if (util_clamp == SCHED_CAPACITY_SCALE) {
9061 		seq_puts(sf, "max\n");
9062 		return;
9063 	}
9064 
9065 	percent = tg->uclamp_pct[clamp_id];
9066 	percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
9067 	seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
9068 }
9069 
9070 static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
9071 {
9072 	cpu_uclamp_print(sf, UCLAMP_MIN);
9073 	return 0;
9074 }
9075 
9076 static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
9077 {
9078 	cpu_uclamp_print(sf, UCLAMP_MAX);
9079 	return 0;
9080 }
9081 #endif /* CONFIG_UCLAMP_TASK_GROUP */
9082 
9083 #ifdef CONFIG_FAIR_GROUP_SCHED
9084 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
9085 				struct cftype *cftype, u64 shareval)
9086 {
9087 	if (shareval > scale_load_down(ULONG_MAX))
9088 		shareval = MAX_SHARES;
9089 	return sched_group_set_shares(css_tg(css), scale_load(shareval));
9090 }
9091 
9092 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
9093 			       struct cftype *cft)
9094 {
9095 	struct task_group *tg = css_tg(css);
9096 
9097 	return (u64) scale_load_down(tg->shares);
9098 }
9099 
9100 #ifdef CONFIG_CFS_BANDWIDTH
9101 static DEFINE_MUTEX(cfs_constraints_mutex);
9102 
9103 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
9104 static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
9105 /* More than 203 days if BW_SHIFT equals 20. */
9106 static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
9107 
9108 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
9109 
9110 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota,
9111 				u64 burst)
9112 {
9113 	int i, ret = 0, runtime_enabled, runtime_was_enabled;
9114 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
9115 
9116 	if (tg == &root_task_group)
9117 		return -EINVAL;
9118 
9119 	/*
9120 	 * Ensure we have at some amount of bandwidth every period.  This is
9121 	 * to prevent reaching a state of large arrears when throttled via
9122 	 * entity_tick() resulting in prolonged exit starvation.
9123 	 */
9124 	if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
9125 		return -EINVAL;
9126 
9127 	/*
9128 	 * Likewise, bound things on the other side by preventing insane quota
9129 	 * periods.  This also allows us to normalize in computing quota
9130 	 * feasibility.
9131 	 */
9132 	if (period > max_cfs_quota_period)
9133 		return -EINVAL;
9134 
9135 	/*
9136 	 * Bound quota to defend quota against overflow during bandwidth shift.
9137 	 */
9138 	if (quota != RUNTIME_INF && quota > max_cfs_runtime)
9139 		return -EINVAL;
9140 
9141 	if (quota != RUNTIME_INF && (burst > quota ||
9142 				     burst + quota > max_cfs_runtime))
9143 		return -EINVAL;
9144 
9145 	/*
9146 	 * Prevent race between setting of cfs_rq->runtime_enabled and
9147 	 * unthrottle_offline_cfs_rqs().
9148 	 */
9149 	guard(cpus_read_lock)();
9150 	guard(mutex)(&cfs_constraints_mutex);
9151 
9152 	ret = __cfs_schedulable(tg, period, quota);
9153 	if (ret)
9154 		return ret;
9155 
9156 	runtime_enabled = quota != RUNTIME_INF;
9157 	runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
9158 	/*
9159 	 * If we need to toggle cfs_bandwidth_used, off->on must occur
9160 	 * before making related changes, and on->off must occur afterwards
9161 	 */
9162 	if (runtime_enabled && !runtime_was_enabled)
9163 		cfs_bandwidth_usage_inc();
9164 
9165 	scoped_guard (raw_spinlock_irq, &cfs_b->lock) {
9166 		cfs_b->period = ns_to_ktime(period);
9167 		cfs_b->quota = quota;
9168 		cfs_b->burst = burst;
9169 
9170 		__refill_cfs_bandwidth_runtime(cfs_b);
9171 
9172 		/*
9173 		 * Restart the period timer (if active) to handle new
9174 		 * period expiry:
9175 		 */
9176 		if (runtime_enabled)
9177 			start_cfs_bandwidth(cfs_b);
9178 	}
9179 
9180 	for_each_online_cpu(i) {
9181 		struct cfs_rq *cfs_rq = tg->cfs_rq[i];
9182 		struct rq *rq = cfs_rq->rq;
9183 
9184 		guard(rq_lock_irq)(rq);
9185 		cfs_rq->runtime_enabled = runtime_enabled;
9186 		cfs_rq->runtime_remaining = 0;
9187 
9188 		if (cfs_rq->throttled)
9189 			unthrottle_cfs_rq(cfs_rq);
9190 	}
9191 
9192 	if (runtime_was_enabled && !runtime_enabled)
9193 		cfs_bandwidth_usage_dec();
9194 
9195 	return 0;
9196 }
9197 
9198 static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
9199 {
9200 	u64 quota, period, burst;
9201 
9202 	period = ktime_to_ns(tg->cfs_bandwidth.period);
9203 	burst = tg->cfs_bandwidth.burst;
9204 	if (cfs_quota_us < 0)
9205 		quota = RUNTIME_INF;
9206 	else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
9207 		quota = (u64)cfs_quota_us * NSEC_PER_USEC;
9208 	else
9209 		return -EINVAL;
9210 
9211 	return tg_set_cfs_bandwidth(tg, period, quota, burst);
9212 }
9213 
9214 static long tg_get_cfs_quota(struct task_group *tg)
9215 {
9216 	u64 quota_us;
9217 
9218 	if (tg->cfs_bandwidth.quota == RUNTIME_INF)
9219 		return -1;
9220 
9221 	quota_us = tg->cfs_bandwidth.quota;
9222 	do_div(quota_us, NSEC_PER_USEC);
9223 
9224 	return quota_us;
9225 }
9226 
9227 static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
9228 {
9229 	u64 quota, period, burst;
9230 
9231 	if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
9232 		return -EINVAL;
9233 
9234 	period = (u64)cfs_period_us * NSEC_PER_USEC;
9235 	quota = tg->cfs_bandwidth.quota;
9236 	burst = tg->cfs_bandwidth.burst;
9237 
9238 	return tg_set_cfs_bandwidth(tg, period, quota, burst);
9239 }
9240 
9241 static long tg_get_cfs_period(struct task_group *tg)
9242 {
9243 	u64 cfs_period_us;
9244 
9245 	cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
9246 	do_div(cfs_period_us, NSEC_PER_USEC);
9247 
9248 	return cfs_period_us;
9249 }
9250 
9251 static int tg_set_cfs_burst(struct task_group *tg, long cfs_burst_us)
9252 {
9253 	u64 quota, period, burst;
9254 
9255 	if ((u64)cfs_burst_us > U64_MAX / NSEC_PER_USEC)
9256 		return -EINVAL;
9257 
9258 	burst = (u64)cfs_burst_us * NSEC_PER_USEC;
9259 	period = ktime_to_ns(tg->cfs_bandwidth.period);
9260 	quota = tg->cfs_bandwidth.quota;
9261 
9262 	return tg_set_cfs_bandwidth(tg, period, quota, burst);
9263 }
9264 
9265 static long tg_get_cfs_burst(struct task_group *tg)
9266 {
9267 	u64 burst_us;
9268 
9269 	burst_us = tg->cfs_bandwidth.burst;
9270 	do_div(burst_us, NSEC_PER_USEC);
9271 
9272 	return burst_us;
9273 }
9274 
9275 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
9276 				  struct cftype *cft)
9277 {
9278 	return tg_get_cfs_quota(css_tg(css));
9279 }
9280 
9281 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
9282 				   struct cftype *cftype, s64 cfs_quota_us)
9283 {
9284 	return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
9285 }
9286 
9287 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
9288 				   struct cftype *cft)
9289 {
9290 	return tg_get_cfs_period(css_tg(css));
9291 }
9292 
9293 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
9294 				    struct cftype *cftype, u64 cfs_period_us)
9295 {
9296 	return tg_set_cfs_period(css_tg(css), cfs_period_us);
9297 }
9298 
9299 static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css,
9300 				  struct cftype *cft)
9301 {
9302 	return tg_get_cfs_burst(css_tg(css));
9303 }
9304 
9305 static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css,
9306 				   struct cftype *cftype, u64 cfs_burst_us)
9307 {
9308 	return tg_set_cfs_burst(css_tg(css), cfs_burst_us);
9309 }
9310 
9311 struct cfs_schedulable_data {
9312 	struct task_group *tg;
9313 	u64 period, quota;
9314 };
9315 
9316 /*
9317  * normalize group quota/period to be quota/max_period
9318  * note: units are usecs
9319  */
9320 static u64 normalize_cfs_quota(struct task_group *tg,
9321 			       struct cfs_schedulable_data *d)
9322 {
9323 	u64 quota, period;
9324 
9325 	if (tg == d->tg) {
9326 		period = d->period;
9327 		quota = d->quota;
9328 	} else {
9329 		period = tg_get_cfs_period(tg);
9330 		quota = tg_get_cfs_quota(tg);
9331 	}
9332 
9333 	/* note: these should typically be equivalent */
9334 	if (quota == RUNTIME_INF || quota == -1)
9335 		return RUNTIME_INF;
9336 
9337 	return to_ratio(period, quota);
9338 }
9339 
9340 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
9341 {
9342 	struct cfs_schedulable_data *d = data;
9343 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
9344 	s64 quota = 0, parent_quota = -1;
9345 
9346 	if (!tg->parent) {
9347 		quota = RUNTIME_INF;
9348 	} else {
9349 		struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
9350 
9351 		quota = normalize_cfs_quota(tg, d);
9352 		parent_quota = parent_b->hierarchical_quota;
9353 
9354 		/*
9355 		 * Ensure max(child_quota) <= parent_quota.  On cgroup2,
9356 		 * always take the non-RUNTIME_INF min.  On cgroup1, only
9357 		 * inherit when no limit is set. In both cases this is used
9358 		 * by the scheduler to determine if a given CFS task has a
9359 		 * bandwidth constraint at some higher level.
9360 		 */
9361 		if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
9362 			if (quota == RUNTIME_INF)
9363 				quota = parent_quota;
9364 			else if (parent_quota != RUNTIME_INF)
9365 				quota = min(quota, parent_quota);
9366 		} else {
9367 			if (quota == RUNTIME_INF)
9368 				quota = parent_quota;
9369 			else if (parent_quota != RUNTIME_INF && quota > parent_quota)
9370 				return -EINVAL;
9371 		}
9372 	}
9373 	cfs_b->hierarchical_quota = quota;
9374 
9375 	return 0;
9376 }
9377 
9378 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
9379 {
9380 	struct cfs_schedulable_data data = {
9381 		.tg = tg,
9382 		.period = period,
9383 		.quota = quota,
9384 	};
9385 
9386 	if (quota != RUNTIME_INF) {
9387 		do_div(data.period, NSEC_PER_USEC);
9388 		do_div(data.quota, NSEC_PER_USEC);
9389 	}
9390 
9391 	guard(rcu)();
9392 	return walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
9393 }
9394 
9395 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
9396 {
9397 	struct task_group *tg = css_tg(seq_css(sf));
9398 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
9399 
9400 	seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
9401 	seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
9402 	seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
9403 
9404 	if (schedstat_enabled() && tg != &root_task_group) {
9405 		struct sched_statistics *stats;
9406 		u64 ws = 0;
9407 		int i;
9408 
9409 		for_each_possible_cpu(i) {
9410 			stats = __schedstats_from_se(tg->se[i]);
9411 			ws += schedstat_val(stats->wait_sum);
9412 		}
9413 
9414 		seq_printf(sf, "wait_sum %llu\n", ws);
9415 	}
9416 
9417 	seq_printf(sf, "nr_bursts %d\n", cfs_b->nr_burst);
9418 	seq_printf(sf, "burst_time %llu\n", cfs_b->burst_time);
9419 
9420 	return 0;
9421 }
9422 
9423 static u64 throttled_time_self(struct task_group *tg)
9424 {
9425 	int i;
9426 	u64 total = 0;
9427 
9428 	for_each_possible_cpu(i) {
9429 		total += READ_ONCE(tg->cfs_rq[i]->throttled_clock_self_time);
9430 	}
9431 
9432 	return total;
9433 }
9434 
9435 static int cpu_cfs_local_stat_show(struct seq_file *sf, void *v)
9436 {
9437 	struct task_group *tg = css_tg(seq_css(sf));
9438 
9439 	seq_printf(sf, "throttled_time %llu\n", throttled_time_self(tg));
9440 
9441 	return 0;
9442 }
9443 #endif /* CONFIG_CFS_BANDWIDTH */
9444 #endif /* CONFIG_FAIR_GROUP_SCHED */
9445 
9446 #ifdef CONFIG_RT_GROUP_SCHED
9447 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
9448 				struct cftype *cft, s64 val)
9449 {
9450 	return sched_group_set_rt_runtime(css_tg(css), val);
9451 }
9452 
9453 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
9454 			       struct cftype *cft)
9455 {
9456 	return sched_group_rt_runtime(css_tg(css));
9457 }
9458 
9459 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
9460 				    struct cftype *cftype, u64 rt_period_us)
9461 {
9462 	return sched_group_set_rt_period(css_tg(css), rt_period_us);
9463 }
9464 
9465 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
9466 				   struct cftype *cft)
9467 {
9468 	return sched_group_rt_period(css_tg(css));
9469 }
9470 #endif /* CONFIG_RT_GROUP_SCHED */
9471 
9472 #ifdef CONFIG_FAIR_GROUP_SCHED
9473 static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css,
9474 			       struct cftype *cft)
9475 {
9476 	return css_tg(css)->idle;
9477 }
9478 
9479 static int cpu_idle_write_s64(struct cgroup_subsys_state *css,
9480 				struct cftype *cft, s64 idle)
9481 {
9482 	return sched_group_set_idle(css_tg(css), idle);
9483 }
9484 #endif
9485 
9486 static struct cftype cpu_legacy_files[] = {
9487 #ifdef CONFIG_FAIR_GROUP_SCHED
9488 	{
9489 		.name = "shares",
9490 		.read_u64 = cpu_shares_read_u64,
9491 		.write_u64 = cpu_shares_write_u64,
9492 	},
9493 	{
9494 		.name = "idle",
9495 		.read_s64 = cpu_idle_read_s64,
9496 		.write_s64 = cpu_idle_write_s64,
9497 	},
9498 #endif
9499 #ifdef CONFIG_CFS_BANDWIDTH
9500 	{
9501 		.name = "cfs_quota_us",
9502 		.read_s64 = cpu_cfs_quota_read_s64,
9503 		.write_s64 = cpu_cfs_quota_write_s64,
9504 	},
9505 	{
9506 		.name = "cfs_period_us",
9507 		.read_u64 = cpu_cfs_period_read_u64,
9508 		.write_u64 = cpu_cfs_period_write_u64,
9509 	},
9510 	{
9511 		.name = "cfs_burst_us",
9512 		.read_u64 = cpu_cfs_burst_read_u64,
9513 		.write_u64 = cpu_cfs_burst_write_u64,
9514 	},
9515 	{
9516 		.name = "stat",
9517 		.seq_show = cpu_cfs_stat_show,
9518 	},
9519 	{
9520 		.name = "stat.local",
9521 		.seq_show = cpu_cfs_local_stat_show,
9522 	},
9523 #endif
9524 #ifdef CONFIG_RT_GROUP_SCHED
9525 	{
9526 		.name = "rt_runtime_us",
9527 		.read_s64 = cpu_rt_runtime_read,
9528 		.write_s64 = cpu_rt_runtime_write,
9529 	},
9530 	{
9531 		.name = "rt_period_us",
9532 		.read_u64 = cpu_rt_period_read_uint,
9533 		.write_u64 = cpu_rt_period_write_uint,
9534 	},
9535 #endif
9536 #ifdef CONFIG_UCLAMP_TASK_GROUP
9537 	{
9538 		.name = "uclamp.min",
9539 		.flags = CFTYPE_NOT_ON_ROOT,
9540 		.seq_show = cpu_uclamp_min_show,
9541 		.write = cpu_uclamp_min_write,
9542 	},
9543 	{
9544 		.name = "uclamp.max",
9545 		.flags = CFTYPE_NOT_ON_ROOT,
9546 		.seq_show = cpu_uclamp_max_show,
9547 		.write = cpu_uclamp_max_write,
9548 	},
9549 #endif
9550 	{ }	/* Terminate */
9551 };
9552 
9553 static int cpu_extra_stat_show(struct seq_file *sf,
9554 			       struct cgroup_subsys_state *css)
9555 {
9556 #ifdef CONFIG_CFS_BANDWIDTH
9557 	{
9558 		struct task_group *tg = css_tg(css);
9559 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
9560 		u64 throttled_usec, burst_usec;
9561 
9562 		throttled_usec = cfs_b->throttled_time;
9563 		do_div(throttled_usec, NSEC_PER_USEC);
9564 		burst_usec = cfs_b->burst_time;
9565 		do_div(burst_usec, NSEC_PER_USEC);
9566 
9567 		seq_printf(sf, "nr_periods %d\n"
9568 			   "nr_throttled %d\n"
9569 			   "throttled_usec %llu\n"
9570 			   "nr_bursts %d\n"
9571 			   "burst_usec %llu\n",
9572 			   cfs_b->nr_periods, cfs_b->nr_throttled,
9573 			   throttled_usec, cfs_b->nr_burst, burst_usec);
9574 	}
9575 #endif
9576 	return 0;
9577 }
9578 
9579 static int cpu_local_stat_show(struct seq_file *sf,
9580 			       struct cgroup_subsys_state *css)
9581 {
9582 #ifdef CONFIG_CFS_BANDWIDTH
9583 	{
9584 		struct task_group *tg = css_tg(css);
9585 		u64 throttled_self_usec;
9586 
9587 		throttled_self_usec = throttled_time_self(tg);
9588 		do_div(throttled_self_usec, NSEC_PER_USEC);
9589 
9590 		seq_printf(sf, "throttled_usec %llu\n",
9591 			   throttled_self_usec);
9592 	}
9593 #endif
9594 	return 0;
9595 }
9596 
9597 #ifdef CONFIG_FAIR_GROUP_SCHED
9598 
9599 static unsigned long tg_weight(struct task_group *tg)
9600 {
9601 	return scale_load_down(tg->shares);
9602 }
9603 
9604 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
9605 			       struct cftype *cft)
9606 {
9607 	return sched_weight_to_cgroup(tg_weight(css_tg(css)));
9608 }
9609 
9610 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
9611 				struct cftype *cft, u64 cgrp_weight)
9612 {
9613 	unsigned long weight;
9614 
9615 	if (cgrp_weight < CGROUP_WEIGHT_MIN || cgrp_weight > CGROUP_WEIGHT_MAX)
9616 		return -ERANGE;
9617 
9618 	weight = sched_weight_from_cgroup(cgrp_weight);
9619 
9620 	return sched_group_set_shares(css_tg(css), scale_load(weight));
9621 }
9622 
9623 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
9624 				    struct cftype *cft)
9625 {
9626 	unsigned long weight = tg_weight(css_tg(css));
9627 	int last_delta = INT_MAX;
9628 	int prio, delta;
9629 
9630 	/* find the closest nice value to the current weight */
9631 	for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
9632 		delta = abs(sched_prio_to_weight[prio] - weight);
9633 		if (delta >= last_delta)
9634 			break;
9635 		last_delta = delta;
9636 	}
9637 
9638 	return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
9639 }
9640 
9641 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
9642 				     struct cftype *cft, s64 nice)
9643 {
9644 	unsigned long weight;
9645 	int idx;
9646 
9647 	if (nice < MIN_NICE || nice > MAX_NICE)
9648 		return -ERANGE;
9649 
9650 	idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
9651 	idx = array_index_nospec(idx, 40);
9652 	weight = sched_prio_to_weight[idx];
9653 
9654 	return sched_group_set_shares(css_tg(css), scale_load(weight));
9655 }
9656 #endif
9657 
9658 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
9659 						  long period, long quota)
9660 {
9661 	if (quota < 0)
9662 		seq_puts(sf, "max");
9663 	else
9664 		seq_printf(sf, "%ld", quota);
9665 
9666 	seq_printf(sf, " %ld\n", period);
9667 }
9668 
9669 /* caller should put the current value in *@periodp before calling */
9670 static int __maybe_unused cpu_period_quota_parse(char *buf,
9671 						 u64 *periodp, u64 *quotap)
9672 {
9673 	char tok[21];	/* U64_MAX */
9674 
9675 	if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
9676 		return -EINVAL;
9677 
9678 	*periodp *= NSEC_PER_USEC;
9679 
9680 	if (sscanf(tok, "%llu", quotap))
9681 		*quotap *= NSEC_PER_USEC;
9682 	else if (!strcmp(tok, "max"))
9683 		*quotap = RUNTIME_INF;
9684 	else
9685 		return -EINVAL;
9686 
9687 	return 0;
9688 }
9689 
9690 #ifdef CONFIG_CFS_BANDWIDTH
9691 static int cpu_max_show(struct seq_file *sf, void *v)
9692 {
9693 	struct task_group *tg = css_tg(seq_css(sf));
9694 
9695 	cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
9696 	return 0;
9697 }
9698 
9699 static ssize_t cpu_max_write(struct kernfs_open_file *of,
9700 			     char *buf, size_t nbytes, loff_t off)
9701 {
9702 	struct task_group *tg = css_tg(of_css(of));
9703 	u64 period = tg_get_cfs_period(tg);
9704 	u64 burst = tg->cfs_bandwidth.burst;
9705 	u64 quota;
9706 	int ret;
9707 
9708 	ret = cpu_period_quota_parse(buf, &period, &quota);
9709 	if (!ret)
9710 		ret = tg_set_cfs_bandwidth(tg, period, quota, burst);
9711 	return ret ?: nbytes;
9712 }
9713 #endif
9714 
9715 static struct cftype cpu_files[] = {
9716 #ifdef CONFIG_FAIR_GROUP_SCHED
9717 	{
9718 		.name = "weight",
9719 		.flags = CFTYPE_NOT_ON_ROOT,
9720 		.read_u64 = cpu_weight_read_u64,
9721 		.write_u64 = cpu_weight_write_u64,
9722 	},
9723 	{
9724 		.name = "weight.nice",
9725 		.flags = CFTYPE_NOT_ON_ROOT,
9726 		.read_s64 = cpu_weight_nice_read_s64,
9727 		.write_s64 = cpu_weight_nice_write_s64,
9728 	},
9729 	{
9730 		.name = "idle",
9731 		.flags = CFTYPE_NOT_ON_ROOT,
9732 		.read_s64 = cpu_idle_read_s64,
9733 		.write_s64 = cpu_idle_write_s64,
9734 	},
9735 #endif
9736 #ifdef CONFIG_CFS_BANDWIDTH
9737 	{
9738 		.name = "max",
9739 		.flags = CFTYPE_NOT_ON_ROOT,
9740 		.seq_show = cpu_max_show,
9741 		.write = cpu_max_write,
9742 	},
9743 	{
9744 		.name = "max.burst",
9745 		.flags = CFTYPE_NOT_ON_ROOT,
9746 		.read_u64 = cpu_cfs_burst_read_u64,
9747 		.write_u64 = cpu_cfs_burst_write_u64,
9748 	},
9749 #endif
9750 #ifdef CONFIG_UCLAMP_TASK_GROUP
9751 	{
9752 		.name = "uclamp.min",
9753 		.flags = CFTYPE_NOT_ON_ROOT,
9754 		.seq_show = cpu_uclamp_min_show,
9755 		.write = cpu_uclamp_min_write,
9756 	},
9757 	{
9758 		.name = "uclamp.max",
9759 		.flags = CFTYPE_NOT_ON_ROOT,
9760 		.seq_show = cpu_uclamp_max_show,
9761 		.write = cpu_uclamp_max_write,
9762 	},
9763 #endif
9764 	{ }	/* terminate */
9765 };
9766 
9767 struct cgroup_subsys cpu_cgrp_subsys = {
9768 	.css_alloc	= cpu_cgroup_css_alloc,
9769 	.css_online	= cpu_cgroup_css_online,
9770 	.css_released	= cpu_cgroup_css_released,
9771 	.css_free	= cpu_cgroup_css_free,
9772 	.css_extra_stat_show = cpu_extra_stat_show,
9773 	.css_local_stat_show = cpu_local_stat_show,
9774 #ifdef CONFIG_RT_GROUP_SCHED
9775 	.can_attach	= cpu_cgroup_can_attach,
9776 #endif
9777 	.attach		= cpu_cgroup_attach,
9778 	.legacy_cftypes	= cpu_legacy_files,
9779 	.dfl_cftypes	= cpu_files,
9780 	.early_init	= true,
9781 	.threaded	= true,
9782 };
9783 
9784 #endif	/* CONFIG_CGROUP_SCHED */
9785 
9786 void dump_cpu_task(int cpu)
9787 {
9788 	if (cpu == smp_processor_id() && in_hardirq()) {
9789 		struct pt_regs *regs;
9790 
9791 		regs = get_irq_regs();
9792 		if (regs) {
9793 			show_regs(regs);
9794 			return;
9795 		}
9796 	}
9797 
9798 	if (trigger_single_cpu_backtrace(cpu))
9799 		return;
9800 
9801 	pr_info("Task dump for CPU %d:\n", cpu);
9802 	sched_show_task(cpu_curr(cpu));
9803 }
9804 
9805 /*
9806  * Nice levels are multiplicative, with a gentle 10% change for every
9807  * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
9808  * nice 1, it will get ~10% less CPU time than another CPU-bound task
9809  * that remained on nice 0.
9810  *
9811  * The "10% effect" is relative and cumulative: from _any_ nice level,
9812  * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
9813  * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
9814  * If a task goes up by ~10% and another task goes down by ~10% then
9815  * the relative distance between them is ~25%.)
9816  */
9817 const int sched_prio_to_weight[40] = {
9818  /* -20 */     88761,     71755,     56483,     46273,     36291,
9819  /* -15 */     29154,     23254,     18705,     14949,     11916,
9820  /* -10 */      9548,      7620,      6100,      4904,      3906,
9821  /*  -5 */      3121,      2501,      1991,      1586,      1277,
9822  /*   0 */      1024,       820,       655,       526,       423,
9823  /*   5 */       335,       272,       215,       172,       137,
9824  /*  10 */       110,        87,        70,        56,        45,
9825  /*  15 */        36,        29,        23,        18,        15,
9826 };
9827 
9828 /*
9829  * Inverse (2^32/x) values of the sched_prio_to_weight[] array, pre-calculated.
9830  *
9831  * In cases where the weight does not change often, we can use the
9832  * pre-calculated inverse to speed up arithmetics by turning divisions
9833  * into multiplications:
9834  */
9835 const u32 sched_prio_to_wmult[40] = {
9836  /* -20 */     48388,     59856,     76040,     92818,    118348,
9837  /* -15 */    147320,    184698,    229616,    287308,    360437,
9838  /* -10 */    449829,    563644,    704093,    875809,   1099582,
9839  /*  -5 */   1376151,   1717300,   2157191,   2708050,   3363326,
9840  /*   0 */   4194304,   5237765,   6557202,   8165337,  10153587,
9841  /*   5 */  12820798,  15790321,  19976592,  24970740,  31350126,
9842  /*  10 */  39045157,  49367440,  61356676,  76695844,  95443717,
9843  /*  15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
9844 };
9845 
9846 void call_trace_sched_update_nr_running(struct rq *rq, int count)
9847 {
9848         trace_sched_update_nr_running_tp(rq, count);
9849 }
9850 
9851 #ifdef CONFIG_SCHED_MM_CID
9852 
9853 /*
9854  * @cid_lock: Guarantee forward-progress of cid allocation.
9855  *
9856  * Concurrency ID allocation within a bitmap is mostly lock-free. The cid_lock
9857  * is only used when contention is detected by the lock-free allocation so
9858  * forward progress can be guaranteed.
9859  */
9860 DEFINE_RAW_SPINLOCK(cid_lock);
9861 
9862 /*
9863  * @use_cid_lock: Select cid allocation behavior: lock-free vs spinlock.
9864  *
9865  * When @use_cid_lock is 0, the cid allocation is lock-free. When contention is
9866  * detected, it is set to 1 to ensure that all newly coming allocations are
9867  * serialized by @cid_lock until the allocation which detected contention
9868  * completes and sets @use_cid_lock back to 0. This guarantees forward progress
9869  * of a cid allocation.
9870  */
9871 int use_cid_lock;
9872 
9873 /*
9874  * mm_cid remote-clear implements a lock-free algorithm to clear per-mm/cpu cid
9875  * concurrently with respect to the execution of the source runqueue context
9876  * switch.
9877  *
9878  * There is one basic properties we want to guarantee here:
9879  *
9880  * (1) Remote-clear should _never_ mark a per-cpu cid UNSET when it is actively
9881  * used by a task. That would lead to concurrent allocation of the cid and
9882  * userspace corruption.
9883  *
9884  * Provide this guarantee by introducing a Dekker memory ordering to guarantee
9885  * that a pair of loads observe at least one of a pair of stores, which can be
9886  * shown as:
9887  *
9888  *      X = Y = 0
9889  *
9890  *      w[X]=1          w[Y]=1
9891  *      MB              MB
9892  *      r[Y]=y          r[X]=x
9893  *
9894  * Which guarantees that x==0 && y==0 is impossible. But rather than using
9895  * values 0 and 1, this algorithm cares about specific state transitions of the
9896  * runqueue current task (as updated by the scheduler context switch), and the
9897  * per-mm/cpu cid value.
9898  *
9899  * Let's introduce task (Y) which has task->mm == mm and task (N) which has
9900  * task->mm != mm for the rest of the discussion. There are two scheduler state
9901  * transitions on context switch we care about:
9902  *
9903  * (TSA) Store to rq->curr with transition from (N) to (Y)
9904  *
9905  * (TSB) Store to rq->curr with transition from (Y) to (N)
9906  *
9907  * On the remote-clear side, there is one transition we care about:
9908  *
9909  * (TMA) cmpxchg to *pcpu_cid to set the LAZY flag
9910  *
9911  * There is also a transition to UNSET state which can be performed from all
9912  * sides (scheduler, remote-clear). It is always performed with a cmpxchg which
9913  * guarantees that only a single thread will succeed:
9914  *
9915  * (TMB) cmpxchg to *pcpu_cid to mark UNSET
9916  *
9917  * Just to be clear, what we do _not_ want to happen is a transition to UNSET
9918  * when a thread is actively using the cid (property (1)).
9919  *
9920  * Let's looks at the relevant combinations of TSA/TSB, and TMA transitions.
9921  *
9922  * Scenario A) (TSA)+(TMA) (from next task perspective)
9923  *
9924  * CPU0                                      CPU1
9925  *
9926  * Context switch CS-1                       Remote-clear
9927  *   - store to rq->curr: (N)->(Y) (TSA)     - cmpxchg to *pcpu_id to LAZY (TMA)
9928  *                                             (implied barrier after cmpxchg)
9929  *   - switch_mm_cid()
9930  *     - memory barrier (see switch_mm_cid()
9931  *       comment explaining how this barrier
9932  *       is combined with other scheduler
9933  *       barriers)
9934  *     - mm_cid_get (next)
9935  *       - READ_ONCE(*pcpu_cid)              - rcu_dereference(src_rq->curr)
9936  *
9937  * This Dekker ensures that either task (Y) is observed by the
9938  * rcu_dereference() or the LAZY flag is observed by READ_ONCE(), or both are
9939  * observed.
9940  *
9941  * If task (Y) store is observed by rcu_dereference(), it means that there is
9942  * still an active task on the cpu. Remote-clear will therefore not transition
9943  * to UNSET, which fulfills property (1).
9944  *
9945  * If task (Y) is not observed, but the lazy flag is observed by READ_ONCE(),
9946  * it will move its state to UNSET, which clears the percpu cid perhaps
9947  * uselessly (which is not an issue for correctness). Because task (Y) is not
9948  * observed, CPU1 can move ahead to set the state to UNSET. Because moving
9949  * state to UNSET is done with a cmpxchg expecting that the old state has the
9950  * LAZY flag set, only one thread will successfully UNSET.
9951  *
9952  * If both states (LAZY flag and task (Y)) are observed, the thread on CPU0
9953  * will observe the LAZY flag and transition to UNSET (perhaps uselessly), and
9954  * CPU1 will observe task (Y) and do nothing more, which is fine.
9955  *
9956  * What we are effectively preventing with this Dekker is a scenario where
9957  * neither LAZY flag nor store (Y) are observed, which would fail property (1)
9958  * because this would UNSET a cid which is actively used.
9959  */
9960 
9961 void sched_mm_cid_migrate_from(struct task_struct *t)
9962 {
9963 	t->migrate_from_cpu = task_cpu(t);
9964 }
9965 
9966 static
9967 int __sched_mm_cid_migrate_from_fetch_cid(struct rq *src_rq,
9968 					  struct task_struct *t,
9969 					  struct mm_cid *src_pcpu_cid)
9970 {
9971 	struct mm_struct *mm = t->mm;
9972 	struct task_struct *src_task;
9973 	int src_cid, last_mm_cid;
9974 
9975 	if (!mm)
9976 		return -1;
9977 
9978 	last_mm_cid = t->last_mm_cid;
9979 	/*
9980 	 * If the migrated task has no last cid, or if the current
9981 	 * task on src rq uses the cid, it means the source cid does not need
9982 	 * to be moved to the destination cpu.
9983 	 */
9984 	if (last_mm_cid == -1)
9985 		return -1;
9986 	src_cid = READ_ONCE(src_pcpu_cid->cid);
9987 	if (!mm_cid_is_valid(src_cid) || last_mm_cid != src_cid)
9988 		return -1;
9989 
9990 	/*
9991 	 * If we observe an active task using the mm on this rq, it means we
9992 	 * are not the last task to be migrated from this cpu for this mm, so
9993 	 * there is no need to move src_cid to the destination cpu.
9994 	 */
9995 	guard(rcu)();
9996 	src_task = rcu_dereference(src_rq->curr);
9997 	if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
9998 		t->last_mm_cid = -1;
9999 		return -1;
10000 	}
10001 
10002 	return src_cid;
10003 }
10004 
10005 static
10006 int __sched_mm_cid_migrate_from_try_steal_cid(struct rq *src_rq,
10007 					      struct task_struct *t,
10008 					      struct mm_cid *src_pcpu_cid,
10009 					      int src_cid)
10010 {
10011 	struct task_struct *src_task;
10012 	struct mm_struct *mm = t->mm;
10013 	int lazy_cid;
10014 
10015 	if (src_cid == -1)
10016 		return -1;
10017 
10018 	/*
10019 	 * Attempt to clear the source cpu cid to move it to the destination
10020 	 * cpu.
10021 	 */
10022 	lazy_cid = mm_cid_set_lazy_put(src_cid);
10023 	if (!try_cmpxchg(&src_pcpu_cid->cid, &src_cid, lazy_cid))
10024 		return -1;
10025 
10026 	/*
10027 	 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
10028 	 * rq->curr->mm matches the scheduler barrier in context_switch()
10029 	 * between store to rq->curr and load of prev and next task's
10030 	 * per-mm/cpu cid.
10031 	 *
10032 	 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
10033 	 * rq->curr->mm_cid_active matches the barrier in
10034 	 * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
10035 	 * sched_mm_cid_after_execve() between store to t->mm_cid_active and
10036 	 * load of per-mm/cpu cid.
10037 	 */
10038 
10039 	/*
10040 	 * If we observe an active task using the mm on this rq after setting
10041 	 * the lazy-put flag, this task will be responsible for transitioning
10042 	 * from lazy-put flag set to MM_CID_UNSET.
10043 	 */
10044 	scoped_guard (rcu) {
10045 		src_task = rcu_dereference(src_rq->curr);
10046 		if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
10047 			/*
10048 			 * We observed an active task for this mm, there is therefore
10049 			 * no point in moving this cid to the destination cpu.
10050 			 */
10051 			t->last_mm_cid = -1;
10052 			return -1;
10053 		}
10054 	}
10055 
10056 	/*
10057 	 * The src_cid is unused, so it can be unset.
10058 	 */
10059 	if (!try_cmpxchg(&src_pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
10060 		return -1;
10061 	return src_cid;
10062 }
10063 
10064 /*
10065  * Migration to dst cpu. Called with dst_rq lock held.
10066  * Interrupts are disabled, which keeps the window of cid ownership without the
10067  * source rq lock held small.
10068  */
10069 void sched_mm_cid_migrate_to(struct rq *dst_rq, struct task_struct *t)
10070 {
10071 	struct mm_cid *src_pcpu_cid, *dst_pcpu_cid;
10072 	struct mm_struct *mm = t->mm;
10073 	int src_cid, dst_cid, src_cpu;
10074 	struct rq *src_rq;
10075 
10076 	lockdep_assert_rq_held(dst_rq);
10077 
10078 	if (!mm)
10079 		return;
10080 	src_cpu = t->migrate_from_cpu;
10081 	if (src_cpu == -1) {
10082 		t->last_mm_cid = -1;
10083 		return;
10084 	}
10085 	/*
10086 	 * Move the src cid if the dst cid is unset. This keeps id
10087 	 * allocation closest to 0 in cases where few threads migrate around
10088 	 * many CPUs.
10089 	 *
10090 	 * If destination cid is already set, we may have to just clear
10091 	 * the src cid to ensure compactness in frequent migrations
10092 	 * scenarios.
10093 	 *
10094 	 * It is not useful to clear the src cid when the number of threads is
10095 	 * greater or equal to the number of allowed CPUs, because user-space
10096 	 * can expect that the number of allowed cids can reach the number of
10097 	 * allowed CPUs.
10098 	 */
10099 	dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
10100 	dst_cid = READ_ONCE(dst_pcpu_cid->cid);
10101 	if (!mm_cid_is_unset(dst_cid) &&
10102 	    atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
10103 		return;
10104 	src_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, src_cpu);
10105 	src_rq = cpu_rq(src_cpu);
10106 	src_cid = __sched_mm_cid_migrate_from_fetch_cid(src_rq, t, src_pcpu_cid);
10107 	if (src_cid == -1)
10108 		return;
10109 	src_cid = __sched_mm_cid_migrate_from_try_steal_cid(src_rq, t, src_pcpu_cid,
10110 							    src_cid);
10111 	if (src_cid == -1)
10112 		return;
10113 	if (!mm_cid_is_unset(dst_cid)) {
10114 		__mm_cid_put(mm, src_cid);
10115 		return;
10116 	}
10117 	/* Move src_cid to dst cpu. */
10118 	mm_cid_snapshot_time(dst_rq, mm);
10119 	WRITE_ONCE(dst_pcpu_cid->cid, src_cid);
10120 }
10121 
10122 static void sched_mm_cid_remote_clear(struct mm_struct *mm, struct mm_cid *pcpu_cid,
10123 				      int cpu)
10124 {
10125 	struct rq *rq = cpu_rq(cpu);
10126 	struct task_struct *t;
10127 	int cid, lazy_cid;
10128 
10129 	cid = READ_ONCE(pcpu_cid->cid);
10130 	if (!mm_cid_is_valid(cid))
10131 		return;
10132 
10133 	/*
10134 	 * Clear the cpu cid if it is set to keep cid allocation compact.  If
10135 	 * there happens to be other tasks left on the source cpu using this
10136 	 * mm, the next task using this mm will reallocate its cid on context
10137 	 * switch.
10138 	 */
10139 	lazy_cid = mm_cid_set_lazy_put(cid);
10140 	if (!try_cmpxchg(&pcpu_cid->cid, &cid, lazy_cid))
10141 		return;
10142 
10143 	/*
10144 	 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
10145 	 * rq->curr->mm matches the scheduler barrier in context_switch()
10146 	 * between store to rq->curr and load of prev and next task's
10147 	 * per-mm/cpu cid.
10148 	 *
10149 	 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
10150 	 * rq->curr->mm_cid_active matches the barrier in
10151 	 * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
10152 	 * sched_mm_cid_after_execve() between store to t->mm_cid_active and
10153 	 * load of per-mm/cpu cid.
10154 	 */
10155 
10156 	/*
10157 	 * If we observe an active task using the mm on this rq after setting
10158 	 * the lazy-put flag, that task will be responsible for transitioning
10159 	 * from lazy-put flag set to MM_CID_UNSET.
10160 	 */
10161 	scoped_guard (rcu) {
10162 		t = rcu_dereference(rq->curr);
10163 		if (READ_ONCE(t->mm_cid_active) && t->mm == mm)
10164 			return;
10165 	}
10166 
10167 	/*
10168 	 * The cid is unused, so it can be unset.
10169 	 * Disable interrupts to keep the window of cid ownership without rq
10170 	 * lock small.
10171 	 */
10172 	scoped_guard (irqsave) {
10173 		if (try_cmpxchg(&pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
10174 			__mm_cid_put(mm, cid);
10175 	}
10176 }
10177 
10178 static void sched_mm_cid_remote_clear_old(struct mm_struct *mm, int cpu)
10179 {
10180 	struct rq *rq = cpu_rq(cpu);
10181 	struct mm_cid *pcpu_cid;
10182 	struct task_struct *curr;
10183 	u64 rq_clock;
10184 
10185 	/*
10186 	 * rq->clock load is racy on 32-bit but one spurious clear once in a
10187 	 * while is irrelevant.
10188 	 */
10189 	rq_clock = READ_ONCE(rq->clock);
10190 	pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
10191 
10192 	/*
10193 	 * In order to take care of infrequently scheduled tasks, bump the time
10194 	 * snapshot associated with this cid if an active task using the mm is
10195 	 * observed on this rq.
10196 	 */
10197 	scoped_guard (rcu) {
10198 		curr = rcu_dereference(rq->curr);
10199 		if (READ_ONCE(curr->mm_cid_active) && curr->mm == mm) {
10200 			WRITE_ONCE(pcpu_cid->time, rq_clock);
10201 			return;
10202 		}
10203 	}
10204 
10205 	if (rq_clock < pcpu_cid->time + SCHED_MM_CID_PERIOD_NS)
10206 		return;
10207 	sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
10208 }
10209 
10210 static void sched_mm_cid_remote_clear_weight(struct mm_struct *mm, int cpu,
10211 					     int weight)
10212 {
10213 	struct mm_cid *pcpu_cid;
10214 	int cid;
10215 
10216 	pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
10217 	cid = READ_ONCE(pcpu_cid->cid);
10218 	if (!mm_cid_is_valid(cid) || cid < weight)
10219 		return;
10220 	sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
10221 }
10222 
10223 static void task_mm_cid_work(struct callback_head *work)
10224 {
10225 	unsigned long now = jiffies, old_scan, next_scan;
10226 	struct task_struct *t = current;
10227 	struct cpumask *cidmask;
10228 	struct mm_struct *mm;
10229 	int weight, cpu;
10230 
10231 	SCHED_WARN_ON(t != container_of(work, struct task_struct, cid_work));
10232 
10233 	work->next = work;	/* Prevent double-add */
10234 	if (t->flags & PF_EXITING)
10235 		return;
10236 	mm = t->mm;
10237 	if (!mm)
10238 		return;
10239 	old_scan = READ_ONCE(mm->mm_cid_next_scan);
10240 	next_scan = now + msecs_to_jiffies(MM_CID_SCAN_DELAY);
10241 	if (!old_scan) {
10242 		unsigned long res;
10243 
10244 		res = cmpxchg(&mm->mm_cid_next_scan, old_scan, next_scan);
10245 		if (res != old_scan)
10246 			old_scan = res;
10247 		else
10248 			old_scan = next_scan;
10249 	}
10250 	if (time_before(now, old_scan))
10251 		return;
10252 	if (!try_cmpxchg(&mm->mm_cid_next_scan, &old_scan, next_scan))
10253 		return;
10254 	cidmask = mm_cidmask(mm);
10255 	/* Clear cids that were not recently used. */
10256 	for_each_possible_cpu(cpu)
10257 		sched_mm_cid_remote_clear_old(mm, cpu);
10258 	weight = cpumask_weight(cidmask);
10259 	/*
10260 	 * Clear cids that are greater or equal to the cidmask weight to
10261 	 * recompact it.
10262 	 */
10263 	for_each_possible_cpu(cpu)
10264 		sched_mm_cid_remote_clear_weight(mm, cpu, weight);
10265 }
10266 
10267 void init_sched_mm_cid(struct task_struct *t)
10268 {
10269 	struct mm_struct *mm = t->mm;
10270 	int mm_users = 0;
10271 
10272 	if (mm) {
10273 		mm_users = atomic_read(&mm->mm_users);
10274 		if (mm_users == 1)
10275 			mm->mm_cid_next_scan = jiffies + msecs_to_jiffies(MM_CID_SCAN_DELAY);
10276 	}
10277 	t->cid_work.next = &t->cid_work;	/* Protect against double add */
10278 	init_task_work(&t->cid_work, task_mm_cid_work);
10279 }
10280 
10281 void task_tick_mm_cid(struct rq *rq, struct task_struct *curr)
10282 {
10283 	struct callback_head *work = &curr->cid_work;
10284 	unsigned long now = jiffies;
10285 
10286 	if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) ||
10287 	    work->next != work)
10288 		return;
10289 	if (time_before(now, READ_ONCE(curr->mm->mm_cid_next_scan)))
10290 		return;
10291 	task_work_add(curr, work, TWA_RESUME);
10292 }
10293 
10294 void sched_mm_cid_exit_signals(struct task_struct *t)
10295 {
10296 	struct mm_struct *mm = t->mm;
10297 	struct rq *rq;
10298 
10299 	if (!mm)
10300 		return;
10301 
10302 	preempt_disable();
10303 	rq = this_rq();
10304 	guard(rq_lock_irqsave)(rq);
10305 	preempt_enable_no_resched();	/* holding spinlock */
10306 	WRITE_ONCE(t->mm_cid_active, 0);
10307 	/*
10308 	 * Store t->mm_cid_active before loading per-mm/cpu cid.
10309 	 * Matches barrier in sched_mm_cid_remote_clear_old().
10310 	 */
10311 	smp_mb();
10312 	mm_cid_put(mm);
10313 	t->last_mm_cid = t->mm_cid = -1;
10314 }
10315 
10316 void sched_mm_cid_before_execve(struct task_struct *t)
10317 {
10318 	struct mm_struct *mm = t->mm;
10319 	struct rq *rq;
10320 
10321 	if (!mm)
10322 		return;
10323 
10324 	preempt_disable();
10325 	rq = this_rq();
10326 	guard(rq_lock_irqsave)(rq);
10327 	preempt_enable_no_resched();	/* holding spinlock */
10328 	WRITE_ONCE(t->mm_cid_active, 0);
10329 	/*
10330 	 * Store t->mm_cid_active before loading per-mm/cpu cid.
10331 	 * Matches barrier in sched_mm_cid_remote_clear_old().
10332 	 */
10333 	smp_mb();
10334 	mm_cid_put(mm);
10335 	t->last_mm_cid = t->mm_cid = -1;
10336 }
10337 
10338 void sched_mm_cid_after_execve(struct task_struct *t)
10339 {
10340 	struct mm_struct *mm = t->mm;
10341 	struct rq *rq;
10342 
10343 	if (!mm)
10344 		return;
10345 
10346 	preempt_disable();
10347 	rq = this_rq();
10348 	scoped_guard (rq_lock_irqsave, rq) {
10349 		preempt_enable_no_resched();	/* holding spinlock */
10350 		WRITE_ONCE(t->mm_cid_active, 1);
10351 		/*
10352 		 * Store t->mm_cid_active before loading per-mm/cpu cid.
10353 		 * Matches barrier in sched_mm_cid_remote_clear_old().
10354 		 */
10355 		smp_mb();
10356 		t->last_mm_cid = t->mm_cid = mm_cid_get(rq, mm);
10357 	}
10358 	rseq_set_notify_resume(t);
10359 }
10360 
10361 void sched_mm_cid_fork(struct task_struct *t)
10362 {
10363 	WARN_ON_ONCE(!t->mm || t->mm_cid != -1);
10364 	t->mm_cid_active = 1;
10365 }
10366 #endif
10367 
10368 #ifdef CONFIG_SCHED_CLASS_EXT
10369 void sched_deq_and_put_task(struct task_struct *p, int queue_flags,
10370 			    struct sched_enq_and_set_ctx *ctx)
10371 {
10372 	struct rq *rq = task_rq(p);
10373 
10374 	lockdep_assert_rq_held(rq);
10375 
10376 	*ctx = (struct sched_enq_and_set_ctx){
10377 		.p = p,
10378 		.queue_flags = queue_flags,
10379 		.queued = task_on_rq_queued(p),
10380 		.running = task_current(rq, p),
10381 	};
10382 
10383 	update_rq_clock(rq);
10384 	if (ctx->queued)
10385 		dequeue_task(rq, p, queue_flags | DEQUEUE_NOCLOCK);
10386 	if (ctx->running)
10387 		put_prev_task(rq, p);
10388 }
10389 
10390 void sched_enq_and_set_task(struct sched_enq_and_set_ctx *ctx)
10391 {
10392 	struct rq *rq = task_rq(ctx->p);
10393 
10394 	lockdep_assert_rq_held(rq);
10395 
10396 	if (ctx->queued)
10397 		enqueue_task(rq, ctx->p, ctx->queue_flags | ENQUEUE_NOCLOCK);
10398 	if (ctx->running)
10399 		set_next_task(rq, ctx->p);
10400 }
10401 #endif	/* CONFIG_SCHED_CLASS_EXT */
10402