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