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