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