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