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