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