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