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