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