xref: /linux/kernel/sched/sched.h (revision 5bdb4078e1efba9650c03753616866192d680718)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Scheduler internal types and methods:
4  */
5 #ifndef _KERNEL_SCHED_SCHED_H
6 #define _KERNEL_SCHED_SCHED_H
7 
8 #include <linux/prandom.h>
9 #include <linux/sched/affinity.h>
10 #include <linux/sched/autogroup.h>
11 #include <linux/sched/cpufreq.h>
12 #include <linux/sched/deadline.h>
13 #include <linux/sched.h>
14 #include <linux/sched/loadavg.h>
15 #include <linux/sched/mm.h>
16 #include <linux/sched/rseq_api.h>
17 #include <linux/sched/signal.h>
18 #include <linux/sched/smt.h>
19 #include <linux/sched/stat.h>
20 #include <linux/sched/sysctl.h>
21 #include <linux/sched/task_flags.h>
22 #include <linux/sched/task.h>
23 #include <linux/sched/topology.h>
24 #include <linux/atomic.h>
25 #include <linux/bitmap.h>
26 #include <linux/bug.h>
27 #include <linux/capability.h>
28 #include <linux/cgroup_api.h>
29 #include <linux/cgroup.h>
30 #include <linux/context_tracking.h>
31 #include <linux/cpufreq.h>
32 #include <linux/cpumask_api.h>
33 #include <linux/cpuset.h>
34 #include <linux/ctype.h>
35 #include <linux/file.h>
36 #include <linux/fs_api.h>
37 #include <linux/hrtimer_api.h>
38 #include <linux/interrupt.h>
39 #include <linux/irq_work.h>
40 #include <linux/jiffies.h>
41 #include <linux/kref_api.h>
42 #include <linux/kthread.h>
43 #include <linux/ktime_api.h>
44 #include <linux/lockdep_api.h>
45 #include <linux/lockdep.h>
46 #include <linux/memblock.h>
47 #include <linux/memcontrol.h>
48 #include <linux/minmax.h>
49 #include <linux/mm.h>
50 #include <linux/module.h>
51 #include <linux/mutex_api.h>
52 #include <linux/plist.h>
53 #include <linux/poll.h>
54 #include <linux/proc_fs.h>
55 #include <linux/profile.h>
56 #include <linux/psi.h>
57 #include <linux/rcupdate.h>
58 #include <linux/seq_file.h>
59 #include <linux/seqlock.h>
60 #include <linux/softirq.h>
61 #include <linux/spinlock_api.h>
62 #include <linux/static_key.h>
63 #include <linux/stop_machine.h>
64 #include <linux/syscalls_api.h>
65 #include <linux/syscalls.h>
66 #include <linux/tick.h>
67 #include <linux/topology.h>
68 #include <linux/types.h>
69 #include <linux/u64_stats_sync_api.h>
70 #include <linux/uaccess.h>
71 #include <linux/vmstat.h>
72 #include <linux/wait_api.h>
73 #include <linux/wait_bit.h>
74 #include <linux/workqueue_api.h>
75 #include <linux/delayacct.h>
76 #include <linux/mmu_context.h>
77 
78 #include <trace/events/power.h>
79 #include <trace/events/sched.h>
80 
81 #include "../workqueue_internal.h"
82 
83 struct rq;
84 struct cfs_rq;
85 struct rt_rq;
86 struct sched_group;
87 struct cpuidle_state;
88 
89 #if defined(CONFIG_PARAVIRT) && !defined(CONFIG_HAVE_PV_STEAL_CLOCK_GEN)
90 # include <asm/paravirt.h>
91 #endif
92 
93 #include <asm/barrier.h>
94 
95 #include "cpupri.h"
96 #include "cpudeadline.h"
97 
98 /* task_struct::on_rq states: */
99 #define TASK_ON_RQ_QUEUED	1
100 #define TASK_ON_RQ_MIGRATING	2
101 
102 extern __read_mostly int scheduler_running;
103 
104 extern unsigned long calc_load_update;
105 extern atomic_long_t calc_load_tasks;
106 
107 extern void calc_global_load_tick(struct rq *this_rq);
108 extern long calc_load_fold_active(struct rq *this_rq, long adjust);
109 
110 extern void call_trace_sched_update_nr_running(struct rq *rq, int count);
111 
112 extern int sysctl_sched_rt_period;
113 extern int sysctl_sched_rt_runtime;
114 extern int sched_rr_timeslice;
115 
116 /*
117  * Asymmetric CPU capacity bits
118  */
119 struct asym_cap_data {
120 	struct list_head link;
121 	struct rcu_head rcu;
122 	unsigned long capacity;
123 	unsigned long cpus[];
124 };
125 
126 extern struct list_head asym_cap_list;
127 
128 #define cpu_capacity_span(asym_data) to_cpumask((asym_data)->cpus)
129 
130 /*
131  * Helpers for converting nanosecond timing to jiffy resolution
132  */
133 #define NS_TO_JIFFIES(time)	((unsigned long)(time) / (NSEC_PER_SEC/HZ))
134 
135 /*
136  * Increase resolution of nice-level calculations for 64-bit architectures.
137  * The extra resolution improves shares distribution and load balancing of
138  * low-weight task groups (eg. nice +19 on an autogroup), deeper task-group
139  * hierarchies, especially on larger systems. This is not a user-visible change
140  * and does not change the user-interface for setting shares/weights.
141  *
142  * We increase resolution only if we have enough bits to allow this increased
143  * resolution (i.e. 64-bit). The costs for increasing resolution when 32-bit
144  * are pretty high and the returns do not justify the increased costs.
145  *
146  * Really only required when CONFIG_FAIR_GROUP_SCHED=y is also set, but to
147  * increase coverage and consistency always enable it on 64-bit platforms.
148  */
149 #ifdef CONFIG_64BIT
150 # define NICE_0_LOAD_SHIFT	(SCHED_FIXEDPOINT_SHIFT + SCHED_FIXEDPOINT_SHIFT)
151 # define scale_load(w)		((w) << SCHED_FIXEDPOINT_SHIFT)
152 # define scale_load_down(w)					\
153 ({								\
154 	unsigned long __w = (w);				\
155 								\
156 	if (__w)						\
157 		__w = max(2UL, __w >> SCHED_FIXEDPOINT_SHIFT);	\
158 	__w;							\
159 })
160 #else
161 # define NICE_0_LOAD_SHIFT	(SCHED_FIXEDPOINT_SHIFT)
162 # define scale_load(w)		(w)
163 # define scale_load_down(w)	(w)
164 #endif
165 
166 /*
167  * Task weight (visible to users) and its load (invisible to users) have
168  * independent resolution, but they should be well calibrated. We use
169  * scale_load() and scale_load_down(w) to convert between them. The
170  * following must be true:
171  *
172  *  scale_load(sched_prio_to_weight[NICE_TO_PRIO(0)-MAX_RT_PRIO]) == NICE_0_LOAD
173  *
174  */
175 #define NICE_0_LOAD		(1L << NICE_0_LOAD_SHIFT)
176 
177 /*
178  * Single value that decides SCHED_DEADLINE internal math precision.
179  * 10 -> just above 1us
180  * 9  -> just above 0.5us
181  */
182 #define DL_SCALE		10
183 
184 /*
185  * Single value that denotes runtime == period, ie unlimited time.
186  */
187 #define RUNTIME_INF		((u64)~0ULL)
188 
idle_policy(int policy)189 static inline int idle_policy(int policy)
190 {
191 	return policy == SCHED_IDLE;
192 }
193 
normal_policy(int policy)194 static inline int normal_policy(int policy)
195 {
196 #ifdef CONFIG_SCHED_CLASS_EXT
197 	if (policy == SCHED_EXT)
198 		return true;
199 #endif
200 	return policy == SCHED_NORMAL;
201 }
202 
fair_policy(int policy)203 static inline int fair_policy(int policy)
204 {
205 	return normal_policy(policy) || policy == SCHED_BATCH;
206 }
207 
rt_policy(int policy)208 static inline int rt_policy(int policy)
209 {
210 	return policy == SCHED_FIFO || policy == SCHED_RR;
211 }
212 
dl_policy(int policy)213 static inline int dl_policy(int policy)
214 {
215 	return policy == SCHED_DEADLINE;
216 }
217 
valid_policy(int policy)218 static inline bool valid_policy(int policy)
219 {
220 	return idle_policy(policy) || fair_policy(policy) ||
221 		rt_policy(policy) || dl_policy(policy);
222 }
223 
task_has_idle_policy(struct task_struct * p)224 static inline int task_has_idle_policy(struct task_struct *p)
225 {
226 	return idle_policy(p->policy);
227 }
228 
task_has_rt_policy(struct task_struct * p)229 static inline int task_has_rt_policy(struct task_struct *p)
230 {
231 	return rt_policy(p->policy);
232 }
233 
task_has_dl_policy(struct task_struct * p)234 static inline int task_has_dl_policy(struct task_struct *p)
235 {
236 	return dl_policy(p->policy);
237 }
238 
239 #define cap_scale(v, s)		((v)*(s) >> SCHED_CAPACITY_SHIFT)
240 
update_avg(u64 * avg,u64 sample)241 static inline void update_avg(u64 *avg, u64 sample)
242 {
243 	s64 diff = sample - *avg;
244 
245 	*avg += diff / 8;
246 }
247 
248 /*
249  * Shifting a value by an exponent greater *or equal* to the size of said value
250  * is UB; cap at size-1.
251  */
252 #define shr_bound(val, shift)							\
253 	(val >> min_t(typeof(shift), shift, BITS_PER_TYPE(typeof(val)) - 1))
254 
255 /*
256  * cgroup weight knobs should use the common MIN, DFL and MAX values which are
257  * 1, 100 and 10000 respectively. While it loses a bit of range on both ends, it
258  * maps pretty well onto the shares value used by scheduler and the round-trip
259  * conversions preserve the original value over the entire range.
260  */
sched_weight_from_cgroup(unsigned long cgrp_weight)261 static inline unsigned long sched_weight_from_cgroup(unsigned long cgrp_weight)
262 {
263 	return DIV_ROUND_CLOSEST_ULL(cgrp_weight * 1024, CGROUP_WEIGHT_DFL);
264 }
265 
sched_weight_to_cgroup(unsigned long weight)266 static inline unsigned long sched_weight_to_cgroup(unsigned long weight)
267 {
268 	return clamp_t(unsigned long,
269 		       DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024),
270 		       CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
271 }
272 
273 /*
274  * !! For sched_setattr_nocheck() (kernel) only !!
275  *
276  * This is actually gross. :(
277  *
278  * It is used to make schedutil kworker(s) higher priority than SCHED_DEADLINE
279  * tasks, but still be able to sleep. We need this on platforms that cannot
280  * atomically change clock frequency. Remove once fast switching will be
281  * available on such platforms.
282  *
283  * SUGOV stands for SchedUtil GOVernor.
284  */
285 #define SCHED_FLAG_SUGOV	0x10000000
286 
287 #define SCHED_DL_FLAGS		(SCHED_FLAG_RECLAIM | SCHED_FLAG_DL_OVERRUN | SCHED_FLAG_SUGOV)
288 
dl_entity_is_special(const struct sched_dl_entity * dl_se)289 static inline bool dl_entity_is_special(const struct sched_dl_entity *dl_se)
290 {
291 #ifdef CONFIG_CPU_FREQ_GOV_SCHEDUTIL
292 	return unlikely(dl_se->flags & SCHED_FLAG_SUGOV);
293 #else
294 	return false;
295 #endif
296 }
297 
298 /*
299  * Tells if entity @a should preempt entity @b.
300  */
dl_entity_preempt(const struct sched_dl_entity * a,const struct sched_dl_entity * b)301 static inline bool dl_entity_preempt(const struct sched_dl_entity *a,
302 				     const struct sched_dl_entity *b)
303 {
304 	return dl_entity_is_special(a) ||
305 	       dl_time_before(a->deadline, b->deadline);
306 }
307 
308 /*
309  * This is the priority-queue data structure of the RT scheduling class:
310  */
311 struct rt_prio_array {
312 	DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
313 	struct list_head queue[MAX_RT_PRIO];
314 };
315 
316 struct rt_bandwidth {
317 	/* nests inside the rq lock: */
318 	raw_spinlock_t		rt_runtime_lock;
319 	ktime_t			rt_period;
320 	u64			rt_runtime;
321 	struct hrtimer		rt_period_timer;
322 	unsigned int		rt_period_active;
323 };
324 
dl_bandwidth_enabled(void)325 static inline int dl_bandwidth_enabled(void)
326 {
327 	return sysctl_sched_rt_runtime >= 0;
328 }
329 
330 /*
331  * To keep the bandwidth of -deadline tasks under control
332  * we need some place where:
333  *  - store the maximum -deadline bandwidth of each cpu;
334  *  - cache the fraction of bandwidth that is currently allocated in
335  *    each root domain;
336  *
337  * This is all done in the data structure below. It is similar to the
338  * one used for RT-throttling (rt_bandwidth), with the main difference
339  * that, since here we are only interested in admission control, we
340  * do not decrease any runtime while the group "executes", neither we
341  * need a timer to replenish it.
342  *
343  * With respect to SMP, bandwidth is given on a per root domain basis,
344  * meaning that:
345  *  - bw (< 100%) is the deadline bandwidth of each CPU;
346  *  - total_bw is the currently allocated bandwidth in each root domain;
347  */
348 struct dl_bw {
349 	raw_spinlock_t		lock;
350 	u64			bw;
351 	u64			total_bw;
352 };
353 
354 extern void init_dl_bw(struct dl_bw *dl_b);
355 extern int  sched_dl_global_validate(void);
356 extern void sched_dl_do_global(void);
357 extern int  sched_dl_overflow(struct task_struct *p, int policy, const struct sched_attr *attr);
358 extern void __setparam_dl(struct task_struct *p, const struct sched_attr *attr);
359 extern void __getparam_dl(struct task_struct *p, struct sched_attr *attr, unsigned int flags);
360 extern bool __checkparam_dl(const struct sched_attr *attr);
361 extern bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr);
362 extern int  dl_cpuset_cpumask_can_shrink(const struct cpumask *cur, const struct cpumask *trial);
363 extern int  dl_bw_deactivate(int cpu);
364 extern s64 dl_scaled_delta_exec(struct rq *rq, struct sched_dl_entity *dl_se, s64 delta_exec);
365 /*
366  * SCHED_DEADLINE supports servers (nested scheduling) with the following
367  * interface:
368  *
369  *   dl_se::rq -- runqueue we belong to.
370  *
371  *   dl_se::server_pick() -- nested pick_next_task(); we yield the period if this
372  *                           returns NULL.
373  *
374  *   dl_server_update() -- called from update_curr_common(), propagates runtime
375  *                         to the server.
376  *
377  *   dl_server_start() -- start the server when it has tasks; it will stop
378  *			  automatically when there are no more tasks, per
379  *			  dl_se::server_pick() returning NULL.
380  *
381  *   dl_server_stop() -- (force) stop the server; use when updating
382  *                       parameters.
383  *
384  *   dl_server_init() -- initializes the server.
385  *
386  * When started the dl_server will (per dl_defer) schedule a timer for its
387  * zero-laxity point -- that is, unlike regular EDF tasks which run ASAP, a
388  * server will run at the very end of its period.
389  *
390  * This is done such that any runtime from the target class can be accounted
391  * against the server -- through dl_server_update() above -- such that when it
392  * becomes time to run, it might already be out of runtime and get deferred
393  * until the next period. In this case dl_server_timer() will alternate
394  * between defer and replenish but never actually enqueue the server.
395  *
396  * Only when the target class does not manage to exhaust the server's runtime
397  * (there's actualy starvation in the given period), will the dl_server get on
398  * the runqueue. Once queued it will pick tasks from the target class and run
399  * them until either its runtime is exhaused, at which point its back to
400  * dl_server_timer, or until there are no more tasks to run, at which point
401  * the dl_server stops itself.
402  *
403  * By stopping at this point the dl_server retains bandwidth, which, if a new
404  * task wakes up imminently (starting the server again), can be used --
405  * subject to CBS wakeup rules -- without having to wait for the next period.
406  *
407  * Additionally, because of the dl_defer behaviour the start/stop behaviour is
408  * naturally thottled to once per period, avoiding high context switch
409  * workloads from spamming the hrtimer program/cancel paths.
410  */
411 extern void dl_server_update_idle(struct sched_dl_entity *dl_se, s64 delta_exec);
412 extern void dl_server_update(struct sched_dl_entity *dl_se, s64 delta_exec);
413 extern void dl_server_start(struct sched_dl_entity *dl_se);
414 extern void dl_server_stop(struct sched_dl_entity *dl_se);
415 extern void dl_server_init(struct sched_dl_entity *dl_se, struct rq *rq,
416 		    dl_server_pick_f pick_task);
417 extern void sched_init_dl_servers(void);
418 
419 extern void fair_server_init(struct rq *rq);
420 extern void ext_server_init(struct rq *rq);
421 extern void __dl_server_attach_root(struct sched_dl_entity *dl_se, struct rq *rq);
422 extern int dl_server_apply_params(struct sched_dl_entity *dl_se,
423 		    u64 runtime, u64 period, bool init);
424 
dl_server_active(struct sched_dl_entity * dl_se)425 static inline bool dl_server_active(struct sched_dl_entity *dl_se)
426 {
427 	return dl_se->dl_server_active;
428 }
429 
430 #ifdef CONFIG_CGROUP_SCHED
431 
432 extern struct list_head task_groups;
433 
434 #ifdef CONFIG_GROUP_SCHED_BANDWIDTH
435 extern const u64 max_bw_quota_period_us;
436 
437 /*
438  * default period for group bandwidth.
439  * default: 0.1s, units: microseconds
440  */
default_bw_period_us(void)441 static inline u64 default_bw_period_us(void)
442 {
443 	return 100000ULL;
444 }
445 #endif /* CONFIG_GROUP_SCHED_BANDWIDTH */
446 
447 struct cfs_bandwidth {
448 #ifdef CONFIG_CFS_BANDWIDTH
449 	raw_spinlock_t		lock;
450 	ktime_t			period;
451 	u64			quota;
452 	u64			runtime;
453 	u64			burst;
454 	u64			runtime_snap;
455 	s64			hierarchical_quota;
456 
457 	u8			idle;
458 	u8			period_active;
459 	u8			slack_started;
460 	struct hrtimer		period_timer;
461 	struct hrtimer		slack_timer;
462 	struct list_head	throttled_cfs_rq;
463 
464 	/* Statistics: */
465 	int			nr_periods;
466 	int			nr_throttled;
467 	int			nr_burst;
468 	u64			throttled_time;
469 	u64			burst_time;
470 #endif /* CONFIG_CFS_BANDWIDTH */
471 };
472 
473 /* Task group related information */
474 struct task_group {
475 	struct cgroup_subsys_state css;
476 
477 #ifdef CONFIG_GROUP_SCHED_WEIGHT
478 	/* A positive value indicates that this is a SCHED_IDLE group. */
479 	int			idle;
480 #endif
481 
482 #ifdef CONFIG_FAIR_GROUP_SCHED
483 	/* schedulable entities of this group on each CPU */
484 	struct sched_entity	**se;
485 	/* runqueue "owned" by this group on each CPU */
486 	struct cfs_rq		**cfs_rq;
487 	unsigned long		shares;
488 	/*
489 	 * load_avg can be heavily contended at clock tick time, so put
490 	 * it in its own cache-line separated from the fields above which
491 	 * will also be accessed at each tick.
492 	 */
493 	atomic_long_t		load_avg ____cacheline_aligned;
494 #endif /* CONFIG_FAIR_GROUP_SCHED */
495 
496 #ifdef CONFIG_RT_GROUP_SCHED
497 	struct sched_rt_entity	**rt_se;
498 	struct rt_rq		**rt_rq;
499 
500 	struct rt_bandwidth	rt_bandwidth;
501 #endif
502 
503 	struct scx_task_group	scx;
504 
505 	struct rcu_head		rcu;
506 	struct list_head	list;
507 
508 	struct task_group	*parent;
509 	struct list_head	siblings;
510 	struct list_head	children;
511 
512 #ifdef CONFIG_SCHED_AUTOGROUP
513 	struct autogroup	*autogroup;
514 #endif
515 
516 	struct cfs_bandwidth	cfs_bandwidth;
517 
518 #ifdef CONFIG_UCLAMP_TASK_GROUP
519 	/* The two decimal precision [%] value requested from user-space */
520 	unsigned int		uclamp_pct[UCLAMP_CNT];
521 	/* Clamp values requested for a task group */
522 	struct uclamp_se	uclamp_req[UCLAMP_CNT];
523 	/* Effective clamp values used for a task group */
524 	struct uclamp_se	uclamp[UCLAMP_CNT];
525 #endif
526 
527 };
528 
529 #ifdef CONFIG_GROUP_SCHED_WEIGHT
530 #define ROOT_TASK_GROUP_LOAD	NICE_0_LOAD
531 
532 /*
533  * A weight of 0 or 1 can cause arithmetics problems.
534  * A weight of a cfs_rq is the sum of weights of which entities
535  * are queued on this cfs_rq, so a weight of a entity should not be
536  * too large, so as the shares value of a task group.
537  * (The default weight is 1024 - so there's no practical
538  *  limitation from this.)
539  */
540 #define MIN_SHARES		(1UL <<  1)
541 #define MAX_SHARES		(1UL << 18)
542 #endif
543 
544 typedef int (*tg_visitor)(struct task_group *, void *);
545 
546 extern int walk_tg_tree_from(struct task_group *from,
547 			     tg_visitor down, tg_visitor up, void *data);
548 
549 /*
550  * Iterate the full tree, calling @down when first entering a node and @up when
551  * leaving it for the final time.
552  *
553  * Caller must hold rcu_lock or sufficient equivalent.
554  */
walk_tg_tree(tg_visitor down,tg_visitor up,void * data)555 static inline int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
556 {
557 	return walk_tg_tree_from(&root_task_group, down, up, data);
558 }
559 
css_tg(struct cgroup_subsys_state * css)560 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
561 {
562 	return css ? container_of(css, struct task_group, css) : NULL;
563 }
564 
565 extern int tg_nop(struct task_group *tg, void *data);
566 
567 #ifdef CONFIG_FAIR_GROUP_SCHED
568 extern void free_fair_sched_group(struct task_group *tg);
569 extern int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent);
570 extern void online_fair_sched_group(struct task_group *tg);
571 extern void unregister_fair_sched_group(struct task_group *tg);
572 #else /* !CONFIG_FAIR_GROUP_SCHED: */
free_fair_sched_group(struct task_group * tg)573 static inline void free_fair_sched_group(struct task_group *tg) { }
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)574 static inline int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
575 {
576        return 1;
577 }
online_fair_sched_group(struct task_group * tg)578 static inline void online_fair_sched_group(struct task_group *tg) { }
unregister_fair_sched_group(struct task_group * tg)579 static inline void unregister_fair_sched_group(struct task_group *tg) { }
580 #endif /* !CONFIG_FAIR_GROUP_SCHED */
581 
582 extern void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
583 			struct sched_entity *se, int cpu,
584 			struct sched_entity *parent);
585 extern void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent);
586 
587 extern void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b);
588 extern void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b);
589 extern void unthrottle_cfs_rq(struct cfs_rq *cfs_rq);
590 extern bool cfs_task_bw_constrained(struct task_struct *p);
591 
592 extern void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
593 		struct sched_rt_entity *rt_se, int cpu,
594 		struct sched_rt_entity *parent);
595 extern int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us);
596 extern int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us);
597 extern long sched_group_rt_runtime(struct task_group *tg);
598 extern long sched_group_rt_period(struct task_group *tg);
599 extern int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk);
600 
601 extern struct task_group *sched_create_group(struct task_group *parent);
602 extern void sched_online_group(struct task_group *tg,
603 			       struct task_group *parent);
604 extern void sched_destroy_group(struct task_group *tg);
605 extern void sched_release_group(struct task_group *tg);
606 
607 extern void sched_move_task(struct task_struct *tsk, bool for_autogroup);
608 
609 #ifdef CONFIG_FAIR_GROUP_SCHED
610 extern int sched_group_set_shares(struct task_group *tg, unsigned long shares);
611 
612 extern int sched_group_set_idle(struct task_group *tg, long idle);
613 
614 extern void set_task_rq_fair(struct sched_entity *se,
615 			     struct cfs_rq *prev, struct cfs_rq *next);
616 #else /* !CONFIG_FAIR_GROUP_SCHED: */
sched_group_set_shares(struct task_group * tg,unsigned long shares)617 static inline int sched_group_set_shares(struct task_group *tg, unsigned long shares) { return 0; }
sched_group_set_idle(struct task_group * tg,long idle)618 static inline int sched_group_set_idle(struct task_group *tg, long idle) { return 0; }
619 #endif /* !CONFIG_FAIR_GROUP_SCHED */
620 
621 #else /* !CONFIG_CGROUP_SCHED: */
622 
623 struct cfs_bandwidth { };
624 
cfs_task_bw_constrained(struct task_struct * p)625 static inline bool cfs_task_bw_constrained(struct task_struct *p) { return false; }
626 
627 #endif /* !CONFIG_CGROUP_SCHED */
628 
629 extern void unregister_rt_sched_group(struct task_group *tg);
630 extern void free_rt_sched_group(struct task_group *tg);
631 extern int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent);
632 
633 /*
634  * u64_u32_load/u64_u32_store
635  *
636  * Use a copy of a u64 value to protect against data race. This is only
637  * applicable for 32-bits architectures.
638  */
639 #ifdef CONFIG_64BIT
640 # define u64_u32_load_copy(var, copy)		var
641 # define u64_u32_store_copy(var, copy, val)	(var = val)
642 #else
643 # define u64_u32_load_copy(var, copy)					\
644 ({									\
645 	u64 __val, __val_copy;						\
646 	do {								\
647 		__val_copy = copy;					\
648 		/*							\
649 		 * paired with u64_u32_store_copy(), ordering access	\
650 		 * to var and copy.					\
651 		 */							\
652 		smp_rmb();						\
653 		__val = var;						\
654 	} while (__val != __val_copy);					\
655 	__val;								\
656 })
657 # define u64_u32_store_copy(var, copy, val)				\
658 do {									\
659 	typeof(val) __val = (val);					\
660 	var = __val;							\
661 	/*								\
662 	 * paired with u64_u32_load_copy(), ordering access to var and	\
663 	 * copy.							\
664 	 */								\
665 	smp_wmb();							\
666 	copy = __val;							\
667 } while (0)
668 #endif
669 # define u64_u32_load(var)		u64_u32_load_copy(var, var##_copy)
670 # define u64_u32_store(var, val)	u64_u32_store_copy(var, var##_copy, val)
671 
672 struct balance_callback {
673 	struct balance_callback *next;
674 	void (*func)(struct rq *rq);
675 };
676 
677 /* Fair scheduling SCHED_{NORMAL,BATCH,IDLE} related fields in a runqueue: */
678 struct cfs_rq {
679 	struct load_weight	load;
680 	unsigned int		nr_queued;
681 	unsigned int		h_nr_queued;		/* SCHED_{NORMAL,BATCH,IDLE} */
682 	unsigned int		h_nr_runnable;		/* SCHED_{NORMAL,BATCH,IDLE} */
683 	unsigned int		h_nr_idle;		/* SCHED_IDLE */
684 
685 	s64			sum_w_vruntime;
686 	u64			sum_weight;
687 	u64			zero_vruntime;
688 	unsigned int		sum_shift;
689 
690 #ifdef CONFIG_SCHED_CORE
691 	unsigned int		forceidle_seq;
692 	u64			zero_vruntime_fi;
693 #endif
694 
695 	struct rb_root_cached	tasks_timeline;
696 
697 	/*
698 	 * 'curr' points to the currently running entity on this cfs_rq.
699 	 * It is set to NULL otherwise (i.e when none are currently running).
700 	 */
701 	struct sched_entity	*curr;
702 	struct sched_entity	*next;
703 
704 	/*
705 	 * CFS load tracking
706 	 */
707 	struct sched_avg	avg;
708 #ifndef CONFIG_64BIT
709 	u64			last_update_time_copy;
710 #endif
711 	struct {
712 		raw_spinlock_t	lock ____cacheline_aligned;
713 		int		nr;
714 		unsigned long	load_avg;
715 		unsigned long	util_avg;
716 		unsigned long	runnable_avg;
717 	} removed;
718 
719 #ifdef CONFIG_FAIR_GROUP_SCHED
720 	u64			last_update_tg_load_avg;
721 	unsigned long		tg_load_avg_contrib;
722 	long			propagate;
723 	long			prop_runnable_sum;
724 
725 	/*
726 	 *   h_load = weight * f(tg)
727 	 *
728 	 * Where f(tg) is the recursive weight fraction assigned to
729 	 * this group.
730 	 */
731 	unsigned long		h_load;
732 	u64			last_h_load_update;
733 	struct sched_entity	*h_load_next;
734 
735 	struct rq		*rq;	/* CPU runqueue to which this cfs_rq is attached */
736 
737 	/*
738 	 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
739 	 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
740 	 * (like users, containers etc.)
741 	 *
742 	 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a CPU.
743 	 * This list is used during load balance.
744 	 */
745 	int			on_list;
746 	struct list_head	leaf_cfs_rq_list;
747 	struct task_group	*tg;	/* Group that "owns" this runqueue */
748 
749 	/* Locally cached copy of our task_group's idle value */
750 	int			idle;
751 
752 # ifdef CONFIG_CFS_BANDWIDTH
753 	int			runtime_enabled;
754 	s64			runtime_remaining;
755 
756 	u64			throttled_pelt_idle;
757 #  ifndef CONFIG_64BIT
758 	u64                     throttled_pelt_idle_copy;
759 #  endif
760 	u64			throttled_clock;
761 	u64			throttled_clock_pelt;
762 	u64			throttled_clock_pelt_time;
763 	u64			throttled_clock_self;
764 	u64			throttled_clock_self_time;
765 	bool			throttled:1;
766 	bool			pelt_clock_throttled:1;
767 	int			throttle_count;
768 	struct list_head	throttled_list;
769 	struct list_head	throttled_csd_list;
770 	struct list_head        throttled_limbo_list;
771 # endif /* CONFIG_CFS_BANDWIDTH */
772 #endif /* CONFIG_FAIR_GROUP_SCHED */
773 };
774 
775 #ifdef CONFIG_SCHED_CLASS_EXT
776 /* scx_rq->flags, protected by the rq lock */
777 enum scx_rq_flags {
778 	/*
779 	 * A hotplugged CPU starts scheduling before rq_online_scx(). Track
780 	 * ops.cpu_on/offline() state so that ops.enqueue/dispatch() are called
781 	 * only while the BPF scheduler considers the CPU to be online.
782 	 */
783 	SCX_RQ_ONLINE		= 1 << 0,
784 	SCX_RQ_CAN_STOP_TICK	= 1 << 1,
785 	SCX_RQ_BAL_KEEP		= 1 << 3, /* balance decided to keep current */
786 	SCX_RQ_CLK_VALID	= 1 << 5, /* RQ clock is fresh and valid */
787 	SCX_RQ_BAL_CB_PENDING	= 1 << 6, /* must queue a cb after dispatching */
788 
789 	SCX_RQ_IN_WAKEUP	= 1 << 16,
790 	SCX_RQ_IN_BALANCE	= 1 << 17,
791 };
792 
793 struct scx_rq {
794 	struct scx_dispatch_q	local_dsq;
795 	struct list_head	runnable_list;		/* runnable tasks on this rq */
796 	struct list_head	ddsp_deferred_locals;	/* deferred ddsps from enq */
797 	unsigned long		ops_qseq;
798 	u64			extra_enq_flags;	/* see move_task_to_local_dsq() */
799 	u32			nr_running;
800 	u32			cpuperf_target;		/* [0, SCHED_CAPACITY_SCALE] */
801 	bool			in_select_cpu;
802 	bool			cpu_released;
803 	u32			flags;
804 	u32			nr_immed;		/* ENQ_IMMED tasks on local_dsq */
805 	u64			clock;			/* current per-rq clock -- see scx_bpf_now() */
806 	cpumask_var_t		cpus_to_kick;
807 	cpumask_var_t		cpus_to_kick_if_idle;
808 	cpumask_var_t		cpus_to_preempt;
809 	cpumask_var_t		cpus_to_wait;
810 	cpumask_var_t		cpus_to_sync;
811 	bool			kick_sync_pending;
812 	unsigned long		kick_sync;
813 
814 	struct task_struct	*sub_dispatch_prev;
815 
816 	raw_spinlock_t		deferred_reenq_lock;
817 	u64			deferred_reenq_locals_seq;
818 	struct list_head	deferred_reenq_locals;	/* scheds requesting reenq of local DSQ */
819 	struct list_head	deferred_reenq_users;	/* user DSQs requesting reenq */
820 	struct balance_callback	deferred_bal_cb;
821 	struct balance_callback	kick_sync_bal_cb;
822 	struct irq_work		deferred_irq_work;
823 	struct irq_work		kick_cpus_irq_work;
824 };
825 #endif /* CONFIG_SCHED_CLASS_EXT */
826 
rt_bandwidth_enabled(void)827 static inline int rt_bandwidth_enabled(void)
828 {
829 	return sysctl_sched_rt_runtime >= 0;
830 }
831 
832 /* RT IPI pull logic requires IRQ_WORK */
833 #if defined(CONFIG_IRQ_WORK) && defined(CONFIG_SMP)
834 # define HAVE_RT_PUSH_IPI
835 #endif
836 
837 /* Real-Time classes' related field in a runqueue: */
838 struct rt_rq {
839 	struct rt_prio_array	active;
840 	unsigned int		rt_nr_running;
841 	unsigned int		rr_nr_running;
842 	struct {
843 		int		curr; /* highest queued rt task prio */
844 		int		next; /* next highest */
845 	} highest_prio;
846 	bool			overloaded;
847 	struct plist_head	pushable_tasks;
848 
849 	int			rt_queued;
850 
851 #ifdef CONFIG_RT_GROUP_SCHED
852 	int			rt_throttled;
853 	u64			rt_time; /* consumed RT time, goes up in update_curr_rt */
854 	u64			rt_runtime; /* allotted RT time, "slice" from rt_bandwidth, RT sharing/balancing */
855 	/* Nests inside the rq lock: */
856 	raw_spinlock_t		rt_runtime_lock;
857 
858 	unsigned int		rt_nr_boosted;
859 
860 	struct rq		*rq; /* this is always top-level rq, cache? */
861 #endif
862 #ifdef CONFIG_CGROUP_SCHED
863 	struct task_group	*tg; /* this tg has "this" rt_rq on given CPU for runnable entities */
864 #endif
865 };
866 
rt_rq_is_runnable(struct rt_rq * rt_rq)867 static inline bool rt_rq_is_runnable(struct rt_rq *rt_rq)
868 {
869 	return rt_rq->rt_queued && rt_rq->rt_nr_running;
870 }
871 
872 /* Deadline class' related fields in a runqueue */
873 struct dl_rq {
874 	/* runqueue is an rbtree, ordered by deadline */
875 	struct rb_root_cached	root;
876 
877 	unsigned int		dl_nr_running;
878 
879 	/*
880 	 * Deadline values of the currently executing and the
881 	 * earliest ready task on this rq. Caching these facilitates
882 	 * the decision whether or not a ready but not running task
883 	 * should migrate somewhere else.
884 	 */
885 	struct {
886 		u64		curr;
887 		u64		next;
888 	} earliest_dl;
889 
890 	bool			overloaded;
891 
892 	/*
893 	 * Tasks on this rq that can be pushed away. They are kept in
894 	 * an rb-tree, ordered by tasks' deadlines, with caching
895 	 * of the leftmost (earliest deadline) element.
896 	 */
897 	struct rb_root_cached	pushable_dl_tasks_root;
898 
899 	/*
900 	 * "Active utilization" for this runqueue: increased when a
901 	 * task wakes up (becomes TASK_RUNNING) and decreased when a
902 	 * task blocks
903 	 */
904 	u64			running_bw;
905 
906 	/*
907 	 * Utilization of the tasks "assigned" to this runqueue (including
908 	 * the tasks that are in runqueue and the tasks that executed on this
909 	 * CPU and blocked). Increased when a task moves to this runqueue, and
910 	 * decreased when the task moves away (migrates, changes scheduling
911 	 * policy, or terminates).
912 	 * This is needed to compute the "inactive utilization" for the
913 	 * runqueue (inactive utilization = this_bw - running_bw).
914 	 */
915 	u64			this_bw;
916 	u64			extra_bw;
917 
918 	/*
919 	 * Maximum available bandwidth for reclaiming by SCHED_FLAG_RECLAIM
920 	 * tasks of this rq. Used in calculation of reclaimable bandwidth(GRUB).
921 	 */
922 	u64			max_bw;
923 
924 	/*
925 	 * Inverse of the fraction of CPU utilization that can be reclaimed
926 	 * by the GRUB algorithm.
927 	 */
928 	u64			bw_ratio;
929 };
930 
931 #ifdef CONFIG_FAIR_GROUP_SCHED
932 
933 /* An entity is a task if it doesn't "own" a runqueue */
934 #define entity_is_task(se)	(!se->my_q)
935 
se_update_runnable(struct sched_entity * se)936 static inline void se_update_runnable(struct sched_entity *se)
937 {
938 	if (!entity_is_task(se))
939 		se->runnable_weight = se->my_q->h_nr_runnable;
940 }
941 
se_runnable(struct sched_entity * se)942 static inline long se_runnable(struct sched_entity *se)
943 {
944 	if (se->sched_delayed)
945 		return false;
946 
947 	if (entity_is_task(se))
948 		return !!se->on_rq;
949 	else
950 		return se->runnable_weight;
951 }
952 
953 #else /* !CONFIG_FAIR_GROUP_SCHED: */
954 
955 #define entity_is_task(se)	1
956 
se_update_runnable(struct sched_entity * se)957 static inline void se_update_runnable(struct sched_entity *se) { }
958 
se_runnable(struct sched_entity * se)959 static inline long se_runnable(struct sched_entity *se)
960 {
961 	if (se->sched_delayed)
962 		return false;
963 
964 	return !!se->on_rq;
965 }
966 
967 #endif /* !CONFIG_FAIR_GROUP_SCHED */
968 
969 /*
970  * XXX we want to get rid of these helpers and use the full load resolution.
971  */
se_weight(struct sched_entity * se)972 static inline long se_weight(struct sched_entity *se)
973 {
974 	return scale_load_down(se->load.weight);
975 }
976 
977 
sched_asym_prefer(int a,int b)978 static inline bool sched_asym_prefer(int a, int b)
979 {
980 	return arch_asym_cpu_priority(a) > arch_asym_cpu_priority(b);
981 }
982 
983 struct perf_domain {
984 	struct em_perf_domain *em_pd;
985 	struct perf_domain *next;
986 	struct rcu_head rcu;
987 };
988 
989 /*
990  * We add the notion of a root-domain which will be used to define per-domain
991  * variables. Each exclusive cpuset essentially defines an island domain by
992  * fully partitioning the member CPUs from any other cpuset. Whenever a new
993  * exclusive cpuset is created, we also create and attach a new root-domain
994  * object.
995  *
996  */
997 struct root_domain {
998 	atomic_t		refcount;
999 	atomic_t		rto_count;
1000 	struct rcu_head		rcu;
1001 	cpumask_var_t		span;
1002 	cpumask_var_t		online;
1003 
1004 	/*
1005 	 * Indicate pullable load on at least one CPU, e.g:
1006 	 * - More than one runnable task
1007 	 * - Running task is misfit
1008 	 */
1009 	bool			overloaded;
1010 
1011 	/* Indicate one or more CPUs over-utilized (tipping point) */
1012 	bool			overutilized;
1013 
1014 	/*
1015 	 * The bit corresponding to a CPU gets set here if such CPU has more
1016 	 * than one runnable -deadline task (as it is below for RT tasks).
1017 	 */
1018 	cpumask_var_t		dlo_mask;
1019 	atomic_t		dlo_count;
1020 	struct dl_bw		dl_bw;
1021 	struct cpudl		cpudl;
1022 
1023 	/*
1024 	 * Indicate whether a root_domain's dl_bw has been checked or
1025 	 * updated. It's monotonously increasing value.
1026 	 *
1027 	 * Also, some corner cases, like 'wrap around' is dangerous, but given
1028 	 * that u64 is 'big enough'. So that shouldn't be a concern.
1029 	 */
1030 	u64 visit_cookie;
1031 
1032 #ifdef HAVE_RT_PUSH_IPI
1033 	/*
1034 	 * For IPI pull requests, loop across the rto_mask.
1035 	 */
1036 	struct irq_work		rto_push_work;
1037 	raw_spinlock_t		rto_lock;
1038 	/* These are only updated and read within rto_lock */
1039 	int			rto_loop;
1040 	int			rto_cpu;
1041 	/* These atomics are updated outside of a lock */
1042 	atomic_t		rto_loop_next;
1043 	atomic_t		rto_loop_start;
1044 #endif /* HAVE_RT_PUSH_IPI */
1045 	/*
1046 	 * The "RT overload" flag: it gets set if a CPU has more than
1047 	 * one runnable RT task.
1048 	 */
1049 	cpumask_var_t		rto_mask;
1050 	struct cpupri		cpupri;
1051 
1052 	/*
1053 	 * NULL-terminated list of performance domains intersecting with the
1054 	 * CPUs of the rd. Protected by RCU.
1055 	 */
1056 	struct perf_domain __rcu *pd;
1057 };
1058 
1059 extern void init_defrootdomain(void);
1060 extern int sched_init_domains(const struct cpumask *cpu_map);
1061 extern void rq_attach_root(struct rq *rq, struct root_domain *rd);
1062 extern void sched_get_rd(struct root_domain *rd);
1063 extern void sched_put_rd(struct root_domain *rd);
1064 
get_rd_overloaded(struct root_domain * rd)1065 static inline int get_rd_overloaded(struct root_domain *rd)
1066 {
1067 	return READ_ONCE(rd->overloaded);
1068 }
1069 
set_rd_overloaded(struct root_domain * rd,int status)1070 static inline void set_rd_overloaded(struct root_domain *rd, int status)
1071 {
1072 	if (get_rd_overloaded(rd) != status)
1073 		WRITE_ONCE(rd->overloaded, status);
1074 }
1075 
1076 #ifdef HAVE_RT_PUSH_IPI
1077 extern void rto_push_irq_work_func(struct irq_work *work);
1078 #endif
1079 
1080 #ifdef CONFIG_UCLAMP_TASK
1081 /*
1082  * struct uclamp_bucket - Utilization clamp bucket
1083  * @value: utilization clamp value for tasks on this clamp bucket
1084  * @tasks: number of RUNNABLE tasks on this clamp bucket
1085  *
1086  * Keep track of how many tasks are RUNNABLE for a given utilization
1087  * clamp value.
1088  */
1089 struct uclamp_bucket {
1090 	unsigned long value : bits_per(SCHED_CAPACITY_SCALE);
1091 	unsigned long tasks : BITS_PER_LONG - bits_per(SCHED_CAPACITY_SCALE);
1092 };
1093 
1094 /*
1095  * struct uclamp_rq - rq's utilization clamp
1096  * @value: currently active clamp values for a rq
1097  * @bucket: utilization clamp buckets affecting a rq
1098  *
1099  * Keep track of RUNNABLE tasks on a rq to aggregate their clamp values.
1100  * A clamp value is affecting a rq when there is at least one task RUNNABLE
1101  * (or actually running) with that value.
1102  *
1103  * There are up to UCLAMP_CNT possible different clamp values, currently there
1104  * are only two: minimum utilization and maximum utilization.
1105  *
1106  * All utilization clamping values are MAX aggregated, since:
1107  * - for util_min: we want to run the CPU at least at the max of the minimum
1108  *   utilization required by its currently RUNNABLE tasks.
1109  * - for util_max: we want to allow the CPU to run up to the max of the
1110  *   maximum utilization allowed by its currently RUNNABLE tasks.
1111  *
1112  * Since on each system we expect only a limited number of different
1113  * utilization clamp values (UCLAMP_BUCKETS), use a simple array to track
1114  * the metrics required to compute all the per-rq utilization clamp values.
1115  */
1116 struct uclamp_rq {
1117 	unsigned int value;
1118 	struct uclamp_bucket bucket[UCLAMP_BUCKETS];
1119 };
1120 
1121 DECLARE_STATIC_KEY_FALSE(sched_uclamp_used);
1122 #endif /* CONFIG_UCLAMP_TASK */
1123 
1124 /*
1125  * This is the main, per-CPU runqueue data structure.
1126  *
1127  * Locking rule: those places that want to lock multiple runqueues
1128  * (such as the load balancing or the thread migration code), lock
1129  * acquire operations must be ordered by ascending &runqueue.
1130  */
1131 struct rq {
1132 	/*
1133 	 * The following members are loaded together, without holding the
1134 	 * rq->lock, in an extremely hot loop in update_sg_lb_stats()
1135 	 * (called from pick_next_task()). To reduce cache pollution from
1136 	 * this operation, they are placed together on this dedicated cache
1137 	 * line. Even though some of them are frequently modified, they are
1138 	 * loaded much more frequently than they are stored.
1139 	 */
1140 	unsigned int		nr_running;
1141 #ifdef CONFIG_NUMA_BALANCING
1142 	unsigned int		nr_numa_running;
1143 	unsigned int		nr_preferred_running;
1144 #endif
1145 	unsigned int		ttwu_pending;
1146 	unsigned long		cpu_capacity;
1147 #ifdef CONFIG_SCHED_PROXY_EXEC
1148 	struct task_struct __rcu	*donor;  /* Scheduling context */
1149 	struct task_struct __rcu	*curr;   /* Execution context */
1150 #else
1151 	union {
1152 		struct task_struct __rcu *donor; /* Scheduler context */
1153 		struct task_struct __rcu *curr;  /* Execution context */
1154 	};
1155 #endif
1156 	struct task_struct	*idle;
1157 	/* padding left here deliberately */
1158 
1159 	/*
1160 	 * The next cacheline holds the (hot) runqueue lock, as well as
1161 	 * some other less performance-critical fields.
1162 	 */
1163 	u64			nr_switches	____cacheline_aligned;
1164 
1165 	/* runqueue lock: */
1166 	raw_spinlock_t		__lock;
1167 
1168 #ifdef CONFIG_NO_HZ_COMMON
1169 	unsigned int		nohz_tick_stopped;
1170 	atomic_t		nohz_flags;
1171 	unsigned int		has_blocked_load;
1172 	unsigned long		last_blocked_load_update_tick;
1173 	call_single_data_t	nohz_csd;
1174 #endif /* CONFIG_NO_HZ_COMMON */
1175 
1176 #ifdef CONFIG_UCLAMP_TASK
1177 	/* Utilization clamp values based on CPU's RUNNABLE tasks */
1178 	struct uclamp_rq	uclamp[UCLAMP_CNT] ____cacheline_aligned;
1179 	unsigned int		uclamp_flags;
1180 #define UCLAMP_FLAG_IDLE 0x01
1181 #endif
1182 
1183 	struct cfs_rq		cfs;
1184 	struct rt_rq		rt;
1185 	struct dl_rq		dl;
1186 #ifdef CONFIG_SCHED_CLASS_EXT
1187 	struct scx_rq		scx;
1188 	struct sched_dl_entity	ext_server;
1189 #endif
1190 
1191 	struct sched_dl_entity	fair_server;
1192 
1193 #ifdef CONFIG_FAIR_GROUP_SCHED
1194 	/* list of leaf cfs_rq on this CPU: */
1195 	struct list_head	leaf_cfs_rq_list;
1196 	struct list_head	*tmp_alone_branch;
1197 #endif /* CONFIG_FAIR_GROUP_SCHED */
1198 
1199 #ifdef CONFIG_NUMA_BALANCING
1200 	unsigned int		numa_migrate_on;
1201 #endif
1202 	/*
1203 	 * This is part of a global counter where only the total sum
1204 	 * over all CPUs matters. A task can increase this counter on
1205 	 * one CPU and if it got migrated afterwards it may decrease
1206 	 * it on another CPU. Always updated under the runqueue lock:
1207 	 */
1208 	unsigned long		nr_uninterruptible;
1209 
1210 	struct sched_dl_entity	*dl_server;
1211 	struct task_struct	*stop;
1212 	const struct sched_class *next_class;
1213 	unsigned long		next_balance;
1214 	struct mm_struct	*prev_mm;
1215 
1216 	/*
1217 	 * The following fields of clock data are frequently referenced
1218 	 * and updated together, and should go on their own cache line.
1219 	 */
1220 	u64			clock_task ____cacheline_aligned;
1221 	u64			clock_pelt;
1222 	u64			clock;
1223 	unsigned long		lost_idle_time;
1224 	unsigned int		clock_update_flags;
1225 	u64			clock_pelt_idle;
1226 	u64			clock_idle;
1227 
1228 #ifndef CONFIG_64BIT
1229 	u64			clock_pelt_idle_copy;
1230 	u64			clock_idle_copy;
1231 #endif
1232 
1233 	u64 last_seen_need_resched_ns;
1234 	int ticks_without_resched;
1235 
1236 #ifdef CONFIG_MEMBARRIER
1237 	int membarrier_state;
1238 #endif
1239 
1240 	struct root_domain		*rd;
1241 	struct sched_domain __rcu	*sd;
1242 
1243 	struct balance_callback *balance_callback;
1244 
1245 	unsigned char		nohz_idle_balance;
1246 	unsigned char		idle_balance;
1247 
1248 	unsigned long		misfit_task_load;
1249 
1250 	/* For active balancing */
1251 	int			active_balance;
1252 	int			push_cpu;
1253 	struct cpu_stop_work	active_balance_work;
1254 
1255 	/* CPU of this runqueue: */
1256 	int			cpu;
1257 	int			online;
1258 
1259 	struct list_head cfs_tasks;
1260 
1261 	struct sched_avg	avg_rt;
1262 	struct sched_avg	avg_dl;
1263 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
1264 	struct sched_avg	avg_irq;
1265 #endif
1266 #ifdef CONFIG_SCHED_HW_PRESSURE
1267 	struct sched_avg	avg_hw;
1268 #endif
1269 	u64			idle_stamp;
1270 	u64			avg_idle;
1271 
1272 	/* This is used to determine avg_idle's max value */
1273 	u64			max_idle_balance_cost;
1274 
1275 #ifdef CONFIG_HOTPLUG_CPU
1276 	struct rcuwait		hotplug_wait;
1277 #endif
1278 
1279 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
1280 	u64			prev_irq_time;
1281 	u64			psi_irq_time;
1282 #endif
1283 #ifdef CONFIG_PARAVIRT
1284 	u64			prev_steal_time;
1285 #endif
1286 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
1287 	u64			prev_steal_time_rq;
1288 #endif
1289 
1290 	/* calc_load related fields */
1291 	unsigned long		calc_load_update;
1292 	long			calc_load_active;
1293 
1294 #ifdef CONFIG_SCHED_HRTICK
1295 	call_single_data_t	hrtick_csd;
1296 	struct hrtimer		hrtick_timer;
1297 	ktime_t			hrtick_time;
1298 	ktime_t			hrtick_delay;
1299 	unsigned int		hrtick_sched;
1300 #endif
1301 
1302 #ifdef CONFIG_SCHEDSTATS
1303 	/* latency stats */
1304 	struct sched_info	rq_sched_info;
1305 	unsigned long long	rq_cpu_time;
1306 
1307 	/* sys_sched_yield() stats */
1308 	unsigned int		yld_count;
1309 
1310 	/* schedule() stats */
1311 	unsigned int		sched_count;
1312 	unsigned int		sched_goidle;
1313 
1314 	/* try_to_wake_up() stats */
1315 	unsigned int		ttwu_count;
1316 	unsigned int		ttwu_local;
1317 #endif
1318 
1319 #ifdef CONFIG_CPU_IDLE
1320 	/* Must be inspected within a RCU lock section */
1321 	struct cpuidle_state	*idle_state;
1322 #endif
1323 
1324 	unsigned int		nr_pinned;
1325 	unsigned int		push_busy;
1326 	struct cpu_stop_work	push_work;
1327 
1328 #ifdef CONFIG_SCHED_CORE
1329 	/* per rq */
1330 	struct rq		*core;
1331 	struct task_struct	*core_pick;
1332 	struct sched_dl_entity	*core_dl_server;
1333 	unsigned int		core_enabled;
1334 	unsigned int		core_sched_seq;
1335 	struct rb_root		core_tree;
1336 
1337 	/* shared state -- careful with sched_core_cpu_deactivate() */
1338 	unsigned int		core_task_seq;
1339 	unsigned int		core_pick_seq;
1340 	unsigned long		core_cookie;
1341 	unsigned int		core_forceidle_count;
1342 	unsigned int		core_forceidle_seq;
1343 	unsigned int		core_forceidle_occupation;
1344 	u64			core_forceidle_start;
1345 #endif /* CONFIG_SCHED_CORE */
1346 
1347 	/* Scratch cpumask to be temporarily used under rq_lock */
1348 	cpumask_var_t		scratch_mask;
1349 
1350 #ifdef CONFIG_CFS_BANDWIDTH
1351 	call_single_data_t	cfsb_csd;
1352 	struct list_head	cfsb_csd_list;
1353 #endif
1354 
1355 	atomic_t		nr_iowait;
1356 } __no_randomize_layout;
1357 
1358 #ifdef CONFIG_FAIR_GROUP_SCHED
1359 
1360 /* CPU runqueue to which this cfs_rq is attached */
rq_of(struct cfs_rq * cfs_rq)1361 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
1362 {
1363 	return cfs_rq->rq;
1364 }
1365 
1366 #else /* !CONFIG_FAIR_GROUP_SCHED: */
1367 
rq_of(struct cfs_rq * cfs_rq)1368 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
1369 {
1370 	return container_of(cfs_rq, struct rq, cfs);
1371 }
1372 #endif /* !CONFIG_FAIR_GROUP_SCHED */
1373 
cpu_of(struct rq * rq)1374 static inline int cpu_of(struct rq *rq)
1375 {
1376 	return rq->cpu;
1377 }
1378 
1379 #define MDF_PUSH		0x01
1380 
is_migration_disabled(struct task_struct * p)1381 static inline bool is_migration_disabled(struct task_struct *p)
1382 {
1383 	return p->migration_disabled;
1384 }
1385 
1386 DECLARE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
1387 DECLARE_PER_CPU(struct rnd_state, sched_rnd_state);
1388 
sched_rng(void)1389 static inline u32 sched_rng(void)
1390 {
1391 	return prandom_u32_state(this_cpu_ptr(&sched_rnd_state));
1392 }
1393 
__this_rq(void)1394 static __always_inline struct rq *__this_rq(void)
1395 {
1396 	return this_cpu_ptr(&runqueues);
1397 }
1398 
1399 #define cpu_rq(cpu)		(&per_cpu(runqueues, (cpu)))
1400 #define this_rq()		__this_rq()
1401 #define task_rq(p)		cpu_rq(task_cpu(p))
1402 #define cpu_curr(cpu)		(cpu_rq(cpu)->curr)
1403 #define raw_rq()		raw_cpu_ptr(&runqueues)
1404 
idle_rq(struct rq * rq)1405 static inline bool idle_rq(struct rq *rq)
1406 {
1407 	return rq->curr == rq->idle && !rq->nr_running && !rq->ttwu_pending;
1408 }
1409 
1410 /**
1411  * available_idle_cpu - is a given CPU idle for enqueuing work.
1412  * @cpu: the CPU in question.
1413  *
1414  * Return: 1 if the CPU is currently idle. 0 otherwise.
1415  */
available_idle_cpu(int cpu)1416 static inline bool available_idle_cpu(int cpu)
1417 {
1418 	if (!idle_rq(cpu_rq(cpu)))
1419 		return 0;
1420 
1421 	if (vcpu_is_preempted(cpu))
1422 		return 0;
1423 
1424 	return 1;
1425 }
1426 
1427 #ifdef CONFIG_SCHED_PROXY_EXEC
rq_set_donor(struct rq * rq,struct task_struct * t)1428 static inline void rq_set_donor(struct rq *rq, struct task_struct *t)
1429 {
1430 	rcu_assign_pointer(rq->donor, t);
1431 }
1432 #else
rq_set_donor(struct rq * rq,struct task_struct * t)1433 static inline void rq_set_donor(struct rq *rq, struct task_struct *t)
1434 {
1435 	/* Do nothing */
1436 }
1437 #endif
1438 
1439 #ifdef CONFIG_SCHED_CORE
1440 static inline struct cpumask *sched_group_span(struct sched_group *sg);
1441 
1442 DECLARE_STATIC_KEY_FALSE(__sched_core_enabled);
1443 
sched_core_enabled(struct rq * rq)1444 static inline bool sched_core_enabled(struct rq *rq)
1445 {
1446 	return static_branch_unlikely(&__sched_core_enabled) && rq->core_enabled;
1447 }
1448 
sched_core_disabled(void)1449 static inline bool sched_core_disabled(void)
1450 {
1451 	return !static_branch_unlikely(&__sched_core_enabled);
1452 }
1453 
1454 /*
1455  * Be careful with this function; not for general use. The return value isn't
1456  * stable unless you actually hold a relevant rq->__lock.
1457  */
rq_lockp(struct rq * rq)1458 static inline raw_spinlock_t *rq_lockp(struct rq *rq)
1459 {
1460 	if (sched_core_enabled(rq))
1461 		return &rq->core->__lock;
1462 
1463 	return &rq->__lock;
1464 }
1465 
__rq_lockp(struct rq * rq)1466 static inline raw_spinlock_t *__rq_lockp(struct rq *rq)
1467 	__returns_ctx_lock(rq_lockp(rq)) /* alias them */
1468 {
1469 	if (rq->core_enabled)
1470 		return &rq->core->__lock;
1471 
1472 	return &rq->__lock;
1473 }
1474 
1475 extern bool
1476 cfs_prio_less(const struct task_struct *a, const struct task_struct *b, bool fi);
1477 
1478 extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi);
1479 
1480 /*
1481  * Helpers to check if the CPU's core cookie matches with the task's cookie
1482  * when core scheduling is enabled.
1483  * A special case is that the task's cookie always matches with CPU's core
1484  * cookie if the CPU is in an idle core.
1485  */
sched_cpu_cookie_match(struct rq * rq,struct task_struct * p)1486 static inline bool sched_cpu_cookie_match(struct rq *rq, struct task_struct *p)
1487 {
1488 	/* Ignore cookie match if core scheduler is not enabled on the CPU. */
1489 	if (!sched_core_enabled(rq))
1490 		return true;
1491 
1492 	return rq->core->core_cookie == p->core_cookie;
1493 }
1494 
sched_core_cookie_match(struct rq * rq,struct task_struct * p)1495 static inline bool sched_core_cookie_match(struct rq *rq, struct task_struct *p)
1496 {
1497 	bool idle_core = true;
1498 	int cpu;
1499 
1500 	/* Ignore cookie match if core scheduler is not enabled on the CPU. */
1501 	if (!sched_core_enabled(rq))
1502 		return true;
1503 
1504 	if (rq->core->core_cookie == p->core_cookie)
1505 		return true;
1506 
1507 	for_each_cpu(cpu, cpu_smt_mask(cpu_of(rq))) {
1508 		if (!available_idle_cpu(cpu)) {
1509 			idle_core = false;
1510 			break;
1511 		}
1512 	}
1513 
1514 	/*
1515 	 * A CPU in an idle core is always the best choice for tasks with
1516 	 * cookies.
1517 	 */
1518 	return idle_core;
1519 }
1520 
sched_group_cookie_match(struct rq * rq,struct task_struct * p,struct sched_group * group)1521 static inline bool sched_group_cookie_match(struct rq *rq,
1522 					    struct task_struct *p,
1523 					    struct sched_group *group)
1524 {
1525 	int cpu;
1526 
1527 	/* Ignore cookie match if core scheduler is not enabled on the CPU. */
1528 	if (!sched_core_enabled(rq))
1529 		return true;
1530 
1531 	for_each_cpu_and(cpu, sched_group_span(group), p->cpus_ptr) {
1532 		if (sched_core_cookie_match(cpu_rq(cpu), p))
1533 			return true;
1534 	}
1535 	return false;
1536 }
1537 
sched_core_enqueued(struct task_struct * p)1538 static inline bool sched_core_enqueued(struct task_struct *p)
1539 {
1540 	return !RB_EMPTY_NODE(&p->core_node);
1541 }
1542 
1543 extern void sched_core_enqueue(struct rq *rq, struct task_struct *p);
1544 extern void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags);
1545 
1546 extern void sched_core_get(void);
1547 extern void sched_core_put(void);
1548 
1549 #else /* !CONFIG_SCHED_CORE: */
1550 
sched_core_enabled(struct rq * rq)1551 static inline bool sched_core_enabled(struct rq *rq)
1552 {
1553 	return false;
1554 }
1555 
sched_core_disabled(void)1556 static inline bool sched_core_disabled(void)
1557 {
1558 	return true;
1559 }
1560 
rq_lockp(struct rq * rq)1561 static inline raw_spinlock_t *rq_lockp(struct rq *rq)
1562 {
1563 	return &rq->__lock;
1564 }
1565 
__rq_lockp(struct rq * rq)1566 static inline raw_spinlock_t *__rq_lockp(struct rq *rq)
1567 	__returns_ctx_lock(rq_lockp(rq)) /* alias them */
1568 {
1569 	return &rq->__lock;
1570 }
1571 
sched_cpu_cookie_match(struct rq * rq,struct task_struct * p)1572 static inline bool sched_cpu_cookie_match(struct rq *rq, struct task_struct *p)
1573 {
1574 	return true;
1575 }
1576 
sched_core_cookie_match(struct rq * rq,struct task_struct * p)1577 static inline bool sched_core_cookie_match(struct rq *rq, struct task_struct *p)
1578 {
1579 	return true;
1580 }
1581 
sched_group_cookie_match(struct rq * rq,struct task_struct * p,struct sched_group * group)1582 static inline bool sched_group_cookie_match(struct rq *rq,
1583 					    struct task_struct *p,
1584 					    struct sched_group *group)
1585 {
1586 	return true;
1587 }
1588 
1589 #endif /* !CONFIG_SCHED_CORE */
1590 
1591 #ifdef CONFIG_RT_GROUP_SCHED
1592 # ifdef CONFIG_RT_GROUP_SCHED_DEFAULT_DISABLED
1593 DECLARE_STATIC_KEY_FALSE(rt_group_sched);
rt_group_sched_enabled(void)1594 static inline bool rt_group_sched_enabled(void)
1595 {
1596 	return static_branch_unlikely(&rt_group_sched);
1597 }
1598 # else /* !CONFIG_RT_GROUP_SCHED_DEFAULT_DISABLED: */
1599 DECLARE_STATIC_KEY_TRUE(rt_group_sched);
rt_group_sched_enabled(void)1600 static inline bool rt_group_sched_enabled(void)
1601 {
1602 	return static_branch_likely(&rt_group_sched);
1603 }
1604 # endif /* !CONFIG_RT_GROUP_SCHED_DEFAULT_DISABLED */
1605 #else /* !CONFIG_RT_GROUP_SCHED: */
1606 # define rt_group_sched_enabled()	false
1607 #endif /* !CONFIG_RT_GROUP_SCHED */
1608 
lockdep_assert_rq_held(struct rq * rq)1609 static inline void lockdep_assert_rq_held(struct rq *rq)
1610 	__assumes_ctx_lock(__rq_lockp(rq))
1611 {
1612 	lockdep_assert_held(__rq_lockp(rq));
1613 }
1614 
1615 extern void raw_spin_rq_lock_nested(struct rq *rq, int subclass)
1616 	__acquires(__rq_lockp(rq));
1617 
1618 extern bool raw_spin_rq_trylock(struct rq *rq)
1619 	__cond_acquires(true, __rq_lockp(rq));
1620 
raw_spin_rq_lock(struct rq * rq)1621 static inline void raw_spin_rq_lock(struct rq *rq)
1622 	__acquires(__rq_lockp(rq))
1623 {
1624 	raw_spin_rq_lock_nested(rq, 0);
1625 }
1626 
raw_spin_rq_unlock(struct rq * rq)1627 static inline void raw_spin_rq_unlock(struct rq *rq)
1628 	__releases(__rq_lockp(rq))
1629 {
1630 	raw_spin_unlock(rq_lockp(rq));
1631 }
1632 
raw_spin_rq_lock_irq(struct rq * rq)1633 static inline void raw_spin_rq_lock_irq(struct rq *rq)
1634 	__acquires(__rq_lockp(rq))
1635 {
1636 	local_irq_disable();
1637 	raw_spin_rq_lock(rq);
1638 }
1639 
raw_spin_rq_unlock_irq(struct rq * rq)1640 static inline void raw_spin_rq_unlock_irq(struct rq *rq)
1641 	__releases(__rq_lockp(rq))
1642 {
1643 	raw_spin_rq_unlock(rq);
1644 	local_irq_enable();
1645 }
1646 
_raw_spin_rq_lock_irqsave(struct rq * rq)1647 static inline unsigned long _raw_spin_rq_lock_irqsave(struct rq *rq)
1648 	__acquires(__rq_lockp(rq))
1649 {
1650 	unsigned long flags;
1651 
1652 	local_irq_save(flags);
1653 	raw_spin_rq_lock(rq);
1654 
1655 	return flags;
1656 }
1657 
raw_spin_rq_unlock_irqrestore(struct rq * rq,unsigned long flags)1658 static inline void raw_spin_rq_unlock_irqrestore(struct rq *rq, unsigned long flags)
1659 	__releases(__rq_lockp(rq))
1660 {
1661 	raw_spin_rq_unlock(rq);
1662 	local_irq_restore(flags);
1663 }
1664 
1665 #define raw_spin_rq_lock_irqsave(rq, flags)	\
1666 do {						\
1667 	flags = _raw_spin_rq_lock_irqsave(rq);	\
1668 } while (0)
1669 
1670 #ifdef CONFIG_SCHED_SMT
1671 extern void __update_idle_core(struct rq *rq);
1672 
update_idle_core(struct rq * rq)1673 static inline void update_idle_core(struct rq *rq)
1674 {
1675 	if (static_branch_unlikely(&sched_smt_present))
1676 		__update_idle_core(rq);
1677 }
1678 
1679 #else /* !CONFIG_SCHED_SMT: */
update_idle_core(struct rq * rq)1680 static inline void update_idle_core(struct rq *rq) { }
1681 #endif /* !CONFIG_SCHED_SMT */
1682 
1683 #ifdef CONFIG_FAIR_GROUP_SCHED
1684 
task_of(struct sched_entity * se)1685 static inline struct task_struct *task_of(struct sched_entity *se)
1686 {
1687 	WARN_ON_ONCE(!entity_is_task(se));
1688 	return container_of(se, struct task_struct, se);
1689 }
1690 
task_cfs_rq(struct task_struct * p)1691 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
1692 {
1693 	return p->se.cfs_rq;
1694 }
1695 
1696 /* runqueue on which this entity is (to be) queued */
cfs_rq_of(const struct sched_entity * se)1697 static inline struct cfs_rq *cfs_rq_of(const struct sched_entity *se)
1698 {
1699 	return se->cfs_rq;
1700 }
1701 
1702 /* runqueue "owned" by this group */
group_cfs_rq(struct sched_entity * grp)1703 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
1704 {
1705 	return grp->my_q;
1706 }
1707 
1708 #else /* !CONFIG_FAIR_GROUP_SCHED: */
1709 
1710 #define task_of(_se)		container_of(_se, struct task_struct, se)
1711 
task_cfs_rq(const struct task_struct * p)1712 static inline struct cfs_rq *task_cfs_rq(const struct task_struct *p)
1713 {
1714 	return &task_rq(p)->cfs;
1715 }
1716 
cfs_rq_of(const struct sched_entity * se)1717 static inline struct cfs_rq *cfs_rq_of(const struct sched_entity *se)
1718 {
1719 	const struct task_struct *p = task_of(se);
1720 	struct rq *rq = task_rq(p);
1721 
1722 	return &rq->cfs;
1723 }
1724 
1725 /* runqueue "owned" by this group */
group_cfs_rq(struct sched_entity * grp)1726 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
1727 {
1728 	return NULL;
1729 }
1730 
1731 #endif /* !CONFIG_FAIR_GROUP_SCHED */
1732 
1733 extern void update_rq_avg_idle(struct rq *rq);
1734 extern void update_rq_clock(struct rq *rq);
1735 
1736 /*
1737  * rq::clock_update_flags bits
1738  *
1739  * %RQCF_REQ_SKIP - will request skipping of clock update on the next
1740  *  call to __schedule(). This is an optimisation to avoid
1741  *  neighbouring rq clock updates.
1742  *
1743  * %RQCF_ACT_SKIP - is set from inside of __schedule() when skipping is
1744  *  in effect and calls to update_rq_clock() are being ignored.
1745  *
1746  * %RQCF_UPDATED - is a debug flag that indicates whether a call has been
1747  *  made to update_rq_clock() since the last time rq::lock was pinned.
1748  *
1749  * If inside of __schedule(), clock_update_flags will have been
1750  * shifted left (a left shift is a cheap operation for the fast path
1751  * to promote %RQCF_REQ_SKIP to %RQCF_ACT_SKIP), so you must use,
1752  *
1753  *	if (rq-clock_update_flags >= RQCF_UPDATED)
1754  *
1755  * to check if %RQCF_UPDATED is set. It'll never be shifted more than
1756  * one position though, because the next rq_unpin_lock() will shift it
1757  * back.
1758  */
1759 #define RQCF_REQ_SKIP		0x01
1760 #define RQCF_ACT_SKIP		0x02
1761 #define RQCF_UPDATED		0x04
1762 
assert_clock_updated(struct rq * rq)1763 static inline void assert_clock_updated(struct rq *rq)
1764 {
1765 	/*
1766 	 * The only reason for not seeing a clock update since the
1767 	 * last rq_pin_lock() is if we're currently skipping updates.
1768 	 */
1769 	WARN_ON_ONCE(rq->clock_update_flags < RQCF_ACT_SKIP);
1770 }
1771 
rq_clock(struct rq * rq)1772 static inline u64 rq_clock(struct rq *rq)
1773 {
1774 	lockdep_assert_rq_held(rq);
1775 	assert_clock_updated(rq);
1776 
1777 	return rq->clock;
1778 }
1779 
rq_clock_task(struct rq * rq)1780 static inline u64 rq_clock_task(struct rq *rq)
1781 {
1782 	lockdep_assert_rq_held(rq);
1783 	assert_clock_updated(rq);
1784 
1785 	return rq->clock_task;
1786 }
1787 
rq_clock_skip_update(struct rq * rq)1788 static inline void rq_clock_skip_update(struct rq *rq)
1789 {
1790 	lockdep_assert_rq_held(rq);
1791 	rq->clock_update_flags |= RQCF_REQ_SKIP;
1792 }
1793 
1794 /*
1795  * See rt task throttling, which is the only time a skip
1796  * request is canceled.
1797  */
rq_clock_cancel_skipupdate(struct rq * rq)1798 static inline void rq_clock_cancel_skipupdate(struct rq *rq)
1799 {
1800 	lockdep_assert_rq_held(rq);
1801 	rq->clock_update_flags &= ~RQCF_REQ_SKIP;
1802 }
1803 
1804 /*
1805  * During cpu offlining and rq wide unthrottling, we can trigger
1806  * an update_rq_clock() for several cfs and rt runqueues (Typically
1807  * when using list_for_each_entry_*)
1808  * rq_clock_start_loop_update() can be called after updating the clock
1809  * once and before iterating over the list to prevent multiple update.
1810  * After the iterative traversal, we need to call rq_clock_stop_loop_update()
1811  * to clear RQCF_ACT_SKIP of rq->clock_update_flags.
1812  */
rq_clock_start_loop_update(struct rq * rq)1813 static inline void rq_clock_start_loop_update(struct rq *rq)
1814 {
1815 	lockdep_assert_rq_held(rq);
1816 	WARN_ON_ONCE(rq->clock_update_flags & RQCF_ACT_SKIP);
1817 	rq->clock_update_flags |= RQCF_ACT_SKIP;
1818 }
1819 
rq_clock_stop_loop_update(struct rq * rq)1820 static inline void rq_clock_stop_loop_update(struct rq *rq)
1821 {
1822 	lockdep_assert_rq_held(rq);
1823 	rq->clock_update_flags &= ~RQCF_ACT_SKIP;
1824 }
1825 
1826 struct rq_flags {
1827 	unsigned long flags;
1828 	struct pin_cookie cookie;
1829 	/*
1830 	 * A copy of (rq::clock_update_flags & RQCF_UPDATED) for the
1831 	 * current pin context is stashed here in case it needs to be
1832 	 * restored in rq_repin_lock().
1833 	 */
1834 	unsigned int clock_update_flags;
1835 };
1836 
1837 extern struct balance_callback balance_push_callback;
1838 
1839 #ifdef CONFIG_SCHED_CLASS_EXT
1840 extern const struct sched_class ext_sched_class;
1841 
1842 DECLARE_STATIC_KEY_FALSE(__scx_enabled);	/* SCX BPF scheduler loaded */
1843 DECLARE_STATIC_KEY_FALSE(__scx_switched_all);	/* all fair class tasks on SCX */
1844 
1845 #define scx_enabled()		static_branch_unlikely(&__scx_enabled)
1846 #define scx_switched_all()	static_branch_unlikely(&__scx_switched_all)
1847 
scx_rq_clock_update(struct rq * rq,u64 clock)1848 static inline void scx_rq_clock_update(struct rq *rq, u64 clock)
1849 {
1850 	if (!scx_enabled())
1851 		return;
1852 	WRITE_ONCE(rq->scx.clock, clock);
1853 	smp_store_release(&rq->scx.flags, rq->scx.flags | SCX_RQ_CLK_VALID);
1854 }
1855 
scx_rq_clock_invalidate(struct rq * rq)1856 static inline void scx_rq_clock_invalidate(struct rq *rq)
1857 {
1858 	if (!scx_enabled())
1859 		return;
1860 	WRITE_ONCE(rq->scx.flags, rq->scx.flags & ~SCX_RQ_CLK_VALID);
1861 }
1862 
1863 #else /* !CONFIG_SCHED_CLASS_EXT: */
1864 #define scx_enabled()		false
1865 #define scx_switched_all()	false
1866 
scx_rq_clock_update(struct rq * rq,u64 clock)1867 static inline void scx_rq_clock_update(struct rq *rq, u64 clock) {}
scx_rq_clock_invalidate(struct rq * rq)1868 static inline void scx_rq_clock_invalidate(struct rq *rq) {}
1869 #endif /* !CONFIG_SCHED_CLASS_EXT */
1870 
assert_balance_callbacks_empty(struct rq * rq)1871 static inline void assert_balance_callbacks_empty(struct rq *rq)
1872 {
1873 	WARN_ON_ONCE(IS_ENABLED(CONFIG_PROVE_LOCKING) &&
1874 		     rq->balance_callback &&
1875 		     rq->balance_callback != &balance_push_callback);
1876 }
1877 
1878 /*
1879  * Lockdep annotation that avoids accidental unlocks; it's like a
1880  * sticky/continuous lockdep_assert_held().
1881  *
1882  * This avoids code that has access to 'struct rq *rq' (basically everything in
1883  * the scheduler) from accidentally unlocking the rq if they do not also have a
1884  * copy of the (on-stack) 'struct rq_flags rf'.
1885  *
1886  * Also see Documentation/locking/lockdep-design.rst.
1887  */
rq_pin_lock(struct rq * rq,struct rq_flags * rf)1888 static inline void rq_pin_lock(struct rq *rq, struct rq_flags *rf)
1889 {
1890 	rf->cookie = lockdep_pin_lock(__rq_lockp(rq));
1891 
1892 	rq->clock_update_flags &= (RQCF_REQ_SKIP|RQCF_ACT_SKIP);
1893 	rf->clock_update_flags = 0;
1894 	assert_balance_callbacks_empty(rq);
1895 }
1896 
rq_unpin_lock(struct rq * rq,struct rq_flags * rf)1897 static inline void rq_unpin_lock(struct rq *rq, struct rq_flags *rf)
1898 {
1899 	if (rq->clock_update_flags > RQCF_ACT_SKIP)
1900 		rf->clock_update_flags = RQCF_UPDATED;
1901 
1902 	scx_rq_clock_invalidate(rq);
1903 	lockdep_unpin_lock(__rq_lockp(rq), rf->cookie);
1904 }
1905 
rq_repin_lock(struct rq * rq,struct rq_flags * rf)1906 static inline void rq_repin_lock(struct rq *rq, struct rq_flags *rf)
1907 {
1908 	lockdep_repin_lock(__rq_lockp(rq), rf->cookie);
1909 
1910 	/*
1911 	 * Restore the value we stashed in @rf for this pin context.
1912 	 */
1913 	rq->clock_update_flags |= rf->clock_update_flags;
1914 }
1915 
1916 #define __task_rq_lock(...) __acquire_ret(___task_rq_lock(__VA_ARGS__), __rq_lockp(__ret))
1917 extern struct rq *___task_rq_lock(struct task_struct *p, struct rq_flags *rf) __acquires_ret;
1918 
1919 #define task_rq_lock(...) __acquire_ret(_task_rq_lock(__VA_ARGS__), __rq_lockp(__ret))
1920 extern struct rq *_task_rq_lock(struct task_struct *p, struct rq_flags *rf)
1921 	__acquires(&p->pi_lock) __acquires_ret;
1922 
1923 static inline void
__task_rq_unlock(struct rq * rq,struct task_struct * p,struct rq_flags * rf)1924 __task_rq_unlock(struct rq *rq, struct task_struct *p, struct rq_flags *rf)
1925 	__releases(__rq_lockp(rq))
1926 {
1927 	rq_unpin_lock(rq, rf);
1928 	raw_spin_rq_unlock(rq);
1929 }
1930 
1931 static inline void
task_rq_unlock(struct rq * rq,struct task_struct * p,struct rq_flags * rf)1932 task_rq_unlock(struct rq *rq, struct task_struct *p, struct rq_flags *rf)
1933 	__releases(__rq_lockp(rq), &p->pi_lock)
1934 {
1935 	__task_rq_unlock(rq, p, rf);
1936 	raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
1937 }
1938 
1939 DEFINE_LOCK_GUARD_1(task_rq_lock, struct task_struct,
1940 		    _T->rq = task_rq_lock(_T->lock, &_T->rf),
1941 		    task_rq_unlock(_T->rq, _T->lock, &_T->rf),
1942 		    struct rq *rq; struct rq_flags rf)
1943 DECLARE_LOCK_GUARD_1_ATTRS(task_rq_lock, __acquires(_T->pi_lock), __releases((*(struct task_struct **)_T)->pi_lock))
1944 #define class_task_rq_lock_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(task_rq_lock, _T)
1945 
1946 DEFINE_LOCK_GUARD_1(__task_rq_lock, struct task_struct,
1947 		    _T->rq = __task_rq_lock(_T->lock, &_T->rf),
1948 		    __task_rq_unlock(_T->rq, _T->lock, &_T->rf),
1949 		    struct rq *rq; struct rq_flags rf)
1950 
rq_lock_irqsave(struct rq * rq,struct rq_flags * rf)1951 static inline void rq_lock_irqsave(struct rq *rq, struct rq_flags *rf)
1952 	__acquires(__rq_lockp(rq))
1953 {
1954 	raw_spin_rq_lock_irqsave(rq, rf->flags);
1955 	rq_pin_lock(rq, rf);
1956 }
1957 
rq_lock_irq(struct rq * rq,struct rq_flags * rf)1958 static inline void rq_lock_irq(struct rq *rq, struct rq_flags *rf)
1959 	__acquires(__rq_lockp(rq))
1960 {
1961 	raw_spin_rq_lock_irq(rq);
1962 	rq_pin_lock(rq, rf);
1963 }
1964 
rq_lock(struct rq * rq,struct rq_flags * rf)1965 static inline void rq_lock(struct rq *rq, struct rq_flags *rf)
1966 	__acquires(__rq_lockp(rq))
1967 {
1968 	raw_spin_rq_lock(rq);
1969 	rq_pin_lock(rq, rf);
1970 }
1971 
rq_unlock_irqrestore(struct rq * rq,struct rq_flags * rf)1972 static inline void rq_unlock_irqrestore(struct rq *rq, struct rq_flags *rf)
1973 	__releases(__rq_lockp(rq))
1974 {
1975 	rq_unpin_lock(rq, rf);
1976 	raw_spin_rq_unlock_irqrestore(rq, rf->flags);
1977 }
1978 
rq_unlock_irq(struct rq * rq,struct rq_flags * rf)1979 static inline void rq_unlock_irq(struct rq *rq, struct rq_flags *rf)
1980 	__releases(__rq_lockp(rq))
1981 {
1982 	rq_unpin_lock(rq, rf);
1983 	raw_spin_rq_unlock_irq(rq);
1984 }
1985 
rq_unlock(struct rq * rq,struct rq_flags * rf)1986 static inline void rq_unlock(struct rq *rq, struct rq_flags *rf)
1987 	__releases(__rq_lockp(rq))
1988 {
1989 	rq_unpin_lock(rq, rf);
1990 	raw_spin_rq_unlock(rq);
1991 }
1992 
1993 DEFINE_LOCK_GUARD_1(rq_lock, struct rq,
1994 		    rq_lock(_T->lock, &_T->rf),
1995 		    rq_unlock(_T->lock, &_T->rf),
1996 		    struct rq_flags rf)
1997 
1998 DECLARE_LOCK_GUARD_1_ATTRS(rq_lock, __acquires(__rq_lockp(_T)), __releases(__rq_lockp(*(struct rq **)_T)));
1999 #define class_rq_lock_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(rq_lock, _T)
2000 
2001 DEFINE_LOCK_GUARD_1(rq_lock_irq, struct rq,
2002 		    rq_lock_irq(_T->lock, &_T->rf),
2003 		    rq_unlock_irq(_T->lock, &_T->rf),
2004 		    struct rq_flags rf)
2005 
2006 DECLARE_LOCK_GUARD_1_ATTRS(rq_lock_irq, __acquires(__rq_lockp(_T)), __releases(__rq_lockp(*(struct rq **)_T)));
2007 #define class_rq_lock_irq_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(rq_lock_irq, _T)
2008 
2009 DEFINE_LOCK_GUARD_1(rq_lock_irqsave, struct rq,
2010 		    rq_lock_irqsave(_T->lock, &_T->rf),
2011 		    rq_unlock_irqrestore(_T->lock, &_T->rf),
2012 		    struct rq_flags rf)
2013 
2014 DECLARE_LOCK_GUARD_1_ATTRS(rq_lock_irqsave, __acquires(__rq_lockp(_T)), __releases(__rq_lockp(*(struct rq **)_T)));
2015 #define class_rq_lock_irqsave_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(rq_lock_irqsave, _T)
2016 
2017 #define this_rq_lock_irq(...) __acquire_ret(_this_rq_lock_irq(__VA_ARGS__), __rq_lockp(__ret))
_this_rq_lock_irq(struct rq_flags * rf)2018 static inline struct rq *_this_rq_lock_irq(struct rq_flags *rf) __acquires_ret
2019 {
2020 	struct rq *rq;
2021 
2022 	local_irq_disable();
2023 	rq = this_rq();
2024 	rq_lock(rq, rf);
2025 
2026 	return rq;
2027 }
2028 
2029 #ifdef CONFIG_NUMA
2030 
2031 enum numa_topology_type {
2032 	NUMA_DIRECT,
2033 	NUMA_GLUELESS_MESH,
2034 	NUMA_BACKPLANE,
2035 };
2036 
2037 extern enum numa_topology_type sched_numa_topology_type;
2038 extern int sched_max_numa_distance;
2039 extern bool find_numa_distance(int distance);
2040 extern void sched_init_numa(int offline_node);
2041 extern void sched_update_numa(int cpu, bool online);
2042 extern void sched_domains_numa_masks_set(unsigned int cpu);
2043 extern void sched_domains_numa_masks_clear(unsigned int cpu);
2044 extern int sched_numa_find_closest(const struct cpumask *cpus, int cpu);
2045 
2046 #else /* !CONFIG_NUMA: */
2047 
sched_init_numa(int offline_node)2048 static inline void sched_init_numa(int offline_node) { }
sched_update_numa(int cpu,bool online)2049 static inline void sched_update_numa(int cpu, bool online) { }
sched_domains_numa_masks_set(unsigned int cpu)2050 static inline void sched_domains_numa_masks_set(unsigned int cpu) { }
sched_domains_numa_masks_clear(unsigned int cpu)2051 static inline void sched_domains_numa_masks_clear(unsigned int cpu) { }
2052 
sched_numa_find_closest(const struct cpumask * cpus,int cpu)2053 static inline int sched_numa_find_closest(const struct cpumask *cpus, int cpu)
2054 {
2055 	return nr_cpu_ids;
2056 }
2057 
2058 #endif /* !CONFIG_NUMA */
2059 
2060 #ifdef CONFIG_NUMA_BALANCING
2061 
2062 /* The regions in numa_faults array from task_struct */
2063 enum numa_faults_stats {
2064 	NUMA_MEM = 0,
2065 	NUMA_CPU,
2066 	NUMA_MEMBUF,
2067 	NUMA_CPUBUF
2068 };
2069 
2070 extern void sched_setnuma(struct task_struct *p, int node);
2071 extern int migrate_task_to(struct task_struct *p, int cpu);
2072 extern int migrate_swap(struct task_struct *p, struct task_struct *t,
2073 			int cpu, int scpu);
2074 extern void init_numa_balancing(u64 clone_flags, struct task_struct *p);
2075 
2076 #else /* !CONFIG_NUMA_BALANCING: */
2077 
2078 static inline void
init_numa_balancing(u64 clone_flags,struct task_struct * p)2079 init_numa_balancing(u64 clone_flags, struct task_struct *p)
2080 {
2081 }
2082 
2083 #endif /* !CONFIG_NUMA_BALANCING */
2084 
2085 static inline void
queue_balance_callback(struct rq * rq,struct balance_callback * head,void (* func)(struct rq * rq))2086 queue_balance_callback(struct rq *rq,
2087 		       struct balance_callback *head,
2088 		       void (*func)(struct rq *rq))
2089 {
2090 	lockdep_assert_rq_held(rq);
2091 
2092 	/*
2093 	 * Don't (re)queue an already queued item; nor queue anything when
2094 	 * balance_push() is active, see the comment with
2095 	 * balance_push_callback.
2096 	 */
2097 	if (unlikely(head->next || rq->balance_callback == &balance_push_callback))
2098 		return;
2099 
2100 	head->func = func;
2101 	head->next = rq->balance_callback;
2102 	rq->balance_callback = head;
2103 }
2104 
2105 #define rcu_dereference_sched_domain(p) \
2106 	rcu_dereference_all_check((p), lockdep_is_held(&sched_domains_mutex))
2107 
2108 /*
2109  * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
2110  * See destroy_sched_domains: call_rcu for details.
2111  *
2112  * The domain tree of any CPU may only be accessed from within
2113  * preempt-disabled sections.
2114  */
2115 #define for_each_domain(cpu, __sd) \
2116 	for (__sd = rcu_dereference_sched_domain(cpu_rq(cpu)->sd); \
2117 			__sd; __sd = __sd->parent)
2118 
2119 /* A mask of all the SD flags that have the SDF_SHARED_CHILD metaflag */
2120 #define SD_FLAG(name, mflags) (name * !!((mflags) & SDF_SHARED_CHILD)) |
2121 static const unsigned int SD_SHARED_CHILD_MASK =
2122 #include <linux/sched/sd_flags.h>
2123 0;
2124 #undef SD_FLAG
2125 
2126 /**
2127  * highest_flag_domain - Return highest sched_domain containing flag.
2128  * @cpu:	The CPU whose highest level of sched domain is to
2129  *		be returned.
2130  * @flag:	The flag to check for the highest sched_domain
2131  *		for the given CPU.
2132  *
2133  * Returns the highest sched_domain of a CPU which contains @flag. If @flag has
2134  * the SDF_SHARED_CHILD metaflag, all the children domains also have @flag.
2135  */
highest_flag_domain(int cpu,int flag)2136 static inline struct sched_domain *highest_flag_domain(int cpu, int flag)
2137 {
2138 	struct sched_domain *sd, *hsd = NULL;
2139 
2140 	for_each_domain(cpu, sd) {
2141 		if (sd->flags & flag) {
2142 			hsd = sd;
2143 			continue;
2144 		}
2145 
2146 		/*
2147 		 * Stop the search if @flag is known to be shared at lower
2148 		 * levels. It will not be found further up.
2149 		 */
2150 		if (flag & SD_SHARED_CHILD_MASK)
2151 			break;
2152 	}
2153 
2154 	return hsd;
2155 }
2156 
lowest_flag_domain(int cpu,int flag)2157 static inline struct sched_domain *lowest_flag_domain(int cpu, int flag)
2158 {
2159 	struct sched_domain *sd;
2160 
2161 	for_each_domain(cpu, sd) {
2162 		if (sd->flags & flag)
2163 			break;
2164 	}
2165 
2166 	return sd;
2167 }
2168 
2169 DECLARE_PER_CPU(struct sched_domain __rcu *, sd_llc);
2170 DECLARE_PER_CPU(int, sd_llc_size);
2171 DECLARE_PER_CPU(int, sd_llc_id);
2172 DECLARE_PER_CPU(int, sd_share_id);
2173 DECLARE_PER_CPU(struct sched_domain_shared __rcu *, sd_llc_shared);
2174 DECLARE_PER_CPU(struct sched_domain __rcu *, sd_numa);
2175 DECLARE_PER_CPU(struct sched_domain __rcu *, sd_asym_packing);
2176 DECLARE_PER_CPU(struct sched_domain __rcu *, sd_asym_cpucapacity);
2177 
2178 extern struct static_key_false sched_asym_cpucapacity;
2179 extern struct static_key_false sched_cluster_active;
2180 
sched_asym_cpucap_active(void)2181 static __always_inline bool sched_asym_cpucap_active(void)
2182 {
2183 	return static_branch_unlikely(&sched_asym_cpucapacity);
2184 }
2185 
2186 struct sched_group_capacity {
2187 	atomic_t		ref;
2188 	/*
2189 	 * CPU capacity of this group, SCHED_CAPACITY_SCALE being max capacity
2190 	 * for a single CPU.
2191 	 */
2192 	unsigned long		capacity;
2193 	unsigned long		min_capacity;		/* Min per-CPU capacity in group */
2194 	unsigned long		max_capacity;		/* Max per-CPU capacity in group */
2195 	unsigned long		next_update;
2196 	int			imbalance;		/* XXX unrelated to capacity but shared group state */
2197 
2198 	int			id;
2199 
2200 	unsigned long		cpumask[];		/* Balance mask */
2201 };
2202 
2203 struct sched_group {
2204 	struct sched_group	*next;			/* Must be a circular list */
2205 	atomic_t		ref;
2206 
2207 	unsigned int		group_weight;
2208 	unsigned int		cores;
2209 	struct sched_group_capacity *sgc;
2210 	int			asym_prefer_cpu;	/* CPU of highest priority in group */
2211 	int			flags;
2212 
2213 	/*
2214 	 * The CPUs this group covers.
2215 	 *
2216 	 * NOTE: this field is variable length. (Allocated dynamically
2217 	 * by attaching extra space to the end of the structure,
2218 	 * depending on how many CPUs the kernel has booted up with)
2219 	 */
2220 	unsigned long		cpumask[];
2221 };
2222 
sched_group_span(struct sched_group * sg)2223 static inline struct cpumask *sched_group_span(struct sched_group *sg)
2224 {
2225 	return to_cpumask(sg->cpumask);
2226 }
2227 
2228 /*
2229  * See build_balance_mask().
2230  */
group_balance_mask(struct sched_group * sg)2231 static inline struct cpumask *group_balance_mask(struct sched_group *sg)
2232 {
2233 	return to_cpumask(sg->sgc->cpumask);
2234 }
2235 
2236 extern int group_balance_cpu(struct sched_group *sg);
2237 
2238 extern void update_sched_domain_debugfs(void);
2239 extern void dirty_sched_domain_sysctl(int cpu);
2240 
2241 extern int sched_update_scaling(void);
2242 
task_user_cpus(struct task_struct * p)2243 static inline const struct cpumask *task_user_cpus(struct task_struct *p)
2244 {
2245 	if (!p->user_cpus_ptr)
2246 		return cpu_possible_mask; /* &init_task.cpus_mask */
2247 	return p->user_cpus_ptr;
2248 }
2249 
2250 #ifdef CONFIG_CGROUP_SCHED
2251 
2252 /*
2253  * Return the group to which this tasks belongs.
2254  *
2255  * We cannot use task_css() and friends because the cgroup subsystem
2256  * changes that value before the cgroup_subsys::attach() method is called,
2257  * therefore we cannot pin it and might observe the wrong value.
2258  *
2259  * The same is true for autogroup's p->signal->autogroup->tg, the autogroup
2260  * core changes this before calling sched_move_task().
2261  *
2262  * Instead we use a 'copy' which is updated from sched_move_task() while
2263  * holding both task_struct::pi_lock and rq::lock.
2264  */
task_group(struct task_struct * p)2265 static inline struct task_group *task_group(struct task_struct *p)
2266 {
2267 	return p->sched_task_group;
2268 }
2269 
2270 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
set_task_rq(struct task_struct * p,unsigned int cpu)2271 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
2272 {
2273 #if defined(CONFIG_FAIR_GROUP_SCHED) || defined(CONFIG_RT_GROUP_SCHED)
2274 	struct task_group *tg = task_group(p);
2275 #endif
2276 
2277 #ifdef CONFIG_FAIR_GROUP_SCHED
2278 	set_task_rq_fair(&p->se, p->se.cfs_rq, tg->cfs_rq[cpu]);
2279 	p->se.cfs_rq = tg->cfs_rq[cpu];
2280 	p->se.parent = tg->se[cpu];
2281 	p->se.depth = tg->se[cpu] ? tg->se[cpu]->depth + 1 : 0;
2282 #endif
2283 
2284 #ifdef CONFIG_RT_GROUP_SCHED
2285 	/*
2286 	 * p->rt.rt_rq is NULL initially and it is easier to assign
2287 	 * root_task_group's rt_rq than switching in rt_rq_of_se()
2288 	 * Clobbers tg(!)
2289 	 */
2290 	if (!rt_group_sched_enabled())
2291 		tg = &root_task_group;
2292 	p->rt.rt_rq  = tg->rt_rq[cpu];
2293 	p->rt.parent = tg->rt_se[cpu];
2294 #endif /* CONFIG_RT_GROUP_SCHED */
2295 }
2296 
2297 #else /* !CONFIG_CGROUP_SCHED: */
2298 
set_task_rq(struct task_struct * p,unsigned int cpu)2299 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
2300 
task_group(struct task_struct * p)2301 static inline struct task_group *task_group(struct task_struct *p)
2302 {
2303 	return NULL;
2304 }
2305 
2306 #endif /* !CONFIG_CGROUP_SCHED */
2307 
__set_task_cpu(struct task_struct * p,unsigned int cpu)2308 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
2309 {
2310 	set_task_rq(p, cpu);
2311 #ifdef CONFIG_SMP
2312 	/*
2313 	 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
2314 	 * successfully executed on another CPU. We must ensure that updates of
2315 	 * per-task data have been completed by this moment.
2316 	 */
2317 	smp_wmb();
2318 	WRITE_ONCE(task_thread_info(p)->cpu, cpu);
2319 	p->wake_cpu = cpu;
2320 	rseq_sched_set_ids_changed(p);
2321 #endif /* CONFIG_SMP */
2322 }
2323 
2324 /*
2325  * Tunables:
2326  */
2327 
2328 #define SCHED_FEAT(name, enabled)	\
2329 	__SCHED_FEAT_##name ,
2330 
2331 enum {
2332 #include "features.h"
2333 	__SCHED_FEAT_NR,
2334 };
2335 
2336 #undef SCHED_FEAT
2337 
2338 /*
2339  * To support run-time toggling of sched features, all the translation units
2340  * (but core.c) reference the sysctl_sched_features defined in core.c.
2341  */
2342 extern __read_mostly unsigned int sysctl_sched_features;
2343 
2344 #ifdef CONFIG_JUMP_LABEL
2345 
2346 #define SCHED_FEAT(name, enabled)					\
2347 static __always_inline bool static_branch_##name(struct static_key *key) \
2348 {									\
2349 	return static_key_##enabled(key);				\
2350 }
2351 
2352 #include "features.h"
2353 #undef SCHED_FEAT
2354 
2355 extern struct static_key sched_feat_keys[__SCHED_FEAT_NR];
2356 #define sched_feat(x) (static_branch_##x(&sched_feat_keys[__SCHED_FEAT_##x]))
2357 
2358 #else /* !CONFIG_JUMP_LABEL: */
2359 
2360 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
2361 
2362 #endif /* !CONFIG_JUMP_LABEL */
2363 
2364 extern struct static_key_false sched_numa_balancing;
2365 extern struct static_key_false sched_schedstats;
2366 
global_rt_period(void)2367 static inline u64 global_rt_period(void)
2368 {
2369 	return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
2370 }
2371 
global_rt_runtime(void)2372 static inline u64 global_rt_runtime(void)
2373 {
2374 	if (sysctl_sched_rt_runtime < 0)
2375 		return RUNTIME_INF;
2376 
2377 	return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
2378 }
2379 
2380 /*
2381  * Is p the current execution context?
2382  */
task_current(struct rq * rq,struct task_struct * p)2383 static inline int task_current(struct rq *rq, struct task_struct *p)
2384 {
2385 	return rq->curr == p;
2386 }
2387 
2388 /*
2389  * Is p the current scheduling context?
2390  *
2391  * Note that it might be the current execution context at the same time if
2392  * rq->curr == rq->donor == p.
2393  */
task_current_donor(struct rq * rq,struct task_struct * p)2394 static inline int task_current_donor(struct rq *rq, struct task_struct *p)
2395 {
2396 	return rq->donor == p;
2397 }
2398 
task_is_blocked(struct task_struct * p)2399 static inline bool task_is_blocked(struct task_struct *p)
2400 {
2401 	if (!sched_proxy_exec())
2402 		return false;
2403 
2404 	return !!p->blocked_on;
2405 }
2406 
task_on_cpu(struct rq * rq,struct task_struct * p)2407 static inline int task_on_cpu(struct rq *rq, struct task_struct *p)
2408 {
2409 	return p->on_cpu;
2410 }
2411 
task_on_rq_queued(struct task_struct * p)2412 static inline int task_on_rq_queued(struct task_struct *p)
2413 {
2414 	return READ_ONCE(p->on_rq) == TASK_ON_RQ_QUEUED;
2415 }
2416 
task_on_rq_migrating(struct task_struct * p)2417 static inline int task_on_rq_migrating(struct task_struct *p)
2418 {
2419 	return READ_ONCE(p->on_rq) == TASK_ON_RQ_MIGRATING;
2420 }
2421 
2422 /* Wake flags. The first three directly map to some SD flag value */
2423 #define WF_EXEC			0x02 /* Wakeup after exec; maps to SD_BALANCE_EXEC */
2424 #define WF_FORK			0x04 /* Wakeup after fork; maps to SD_BALANCE_FORK */
2425 #define WF_TTWU			0x08 /* Wakeup;            maps to SD_BALANCE_WAKE */
2426 
2427 #define WF_SYNC			0x10 /* Waker goes to sleep after wakeup */
2428 #define WF_MIGRATED		0x20 /* Internal use, task got migrated */
2429 #define WF_CURRENT_CPU		0x40 /* Prefer to move the wakee to the current CPU. */
2430 #define WF_RQ_SELECTED		0x80 /* ->select_task_rq() was called */
2431 
2432 static_assert(WF_EXEC == SD_BALANCE_EXEC);
2433 static_assert(WF_FORK == SD_BALANCE_FORK);
2434 static_assert(WF_TTWU == SD_BALANCE_WAKE);
2435 
2436 /*
2437  * To aid in avoiding the subversion of "niceness" due to uneven distribution
2438  * of tasks with abnormal "nice" values across CPUs the contribution that
2439  * each task makes to its run queue's load is weighted according to its
2440  * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
2441  * scaled version of the new time slice allocation that they receive on time
2442  * slice expiry etc.
2443  */
2444 
2445 #define WEIGHT_IDLEPRIO		3
2446 #define WMULT_IDLEPRIO		1431655765
2447 
2448 extern const int		sched_prio_to_weight[40];
2449 extern const u32		sched_prio_to_wmult[40];
2450 
2451 /*
2452  * {de,en}queue flags:
2453  *
2454  * SLEEP/WAKEUP - task is no-longer/just-became runnable
2455  *
2456  * SAVE/RESTORE - an otherwise spurious dequeue/enqueue, done to ensure tasks
2457  *                are in a known state which allows modification. Such pairs
2458  *                should preserve as much state as possible.
2459  *
2460  * MOVE - paired with SAVE/RESTORE, explicitly does not preserve the location
2461  *        in the runqueue. IOW the priority is allowed to change. Callers
2462  *        must expect to deal with balance callbacks.
2463  *
2464  * NOCLOCK - skip the update_rq_clock() (avoids double updates)
2465  *
2466  * MIGRATION - p->on_rq == TASK_ON_RQ_MIGRATING (used for DEADLINE)
2467  *
2468  * DELAYED - de/re-queue a sched_delayed task
2469  *
2470  * CLASS - going to update p->sched_class; makes sched_change call the
2471  *         various switch methods.
2472  *
2473  * ENQUEUE_HEAD      - place at front of runqueue (tail if not specified)
2474  * ENQUEUE_REPLENISH - CBS (replenish runtime and postpone deadline)
2475  * ENQUEUE_MIGRATED  - the task was migrated during wakeup
2476  * ENQUEUE_RQ_SELECTED - ->select_task_rq() was called
2477  *
2478  * XXX SAVE/RESTORE in combination with CLASS doesn't really make sense, but
2479  * SCHED_DEADLINE seems to rely on this for now.
2480  */
2481 
2482 #define DEQUEUE_SLEEP		0x0001 /* Matches ENQUEUE_WAKEUP */
2483 #define DEQUEUE_SAVE		0x0002 /* Matches ENQUEUE_RESTORE */
2484 #define DEQUEUE_MOVE		0x0004 /* Matches ENQUEUE_MOVE */
2485 #define DEQUEUE_NOCLOCK		0x0008 /* Matches ENQUEUE_NOCLOCK */
2486 
2487 #define DEQUEUE_MIGRATING	0x0010 /* Matches ENQUEUE_MIGRATING */
2488 #define DEQUEUE_DELAYED		0x0020 /* Matches ENQUEUE_DELAYED */
2489 #define DEQUEUE_CLASS		0x0040 /* Matches ENQUEUE_CLASS */
2490 
2491 #define DEQUEUE_SPECIAL		0x00010000
2492 #define DEQUEUE_THROTTLE	0x00020000
2493 
2494 #define ENQUEUE_WAKEUP		0x0001
2495 #define ENQUEUE_RESTORE		0x0002
2496 #define ENQUEUE_MOVE		0x0004
2497 #define ENQUEUE_NOCLOCK		0x0008
2498 
2499 #define ENQUEUE_MIGRATING	0x0010
2500 #define ENQUEUE_DELAYED		0x0020
2501 #define ENQUEUE_CLASS		0x0040
2502 
2503 #define ENQUEUE_HEAD		0x00010000
2504 #define ENQUEUE_REPLENISH	0x00020000
2505 #define ENQUEUE_MIGRATED	0x00040000
2506 #define ENQUEUE_INITIAL		0x00080000
2507 #define ENQUEUE_RQ_SELECTED	0x00100000
2508 
2509 #define RETRY_TASK		((void *)-1UL)
2510 
2511 struct affinity_context {
2512 	const struct cpumask	*new_mask;
2513 	struct cpumask		*user_mask;
2514 	unsigned int		flags;
2515 };
2516 
2517 extern s64 update_curr_common(struct rq *rq);
2518 
2519 struct sched_class {
2520 
2521 #ifdef CONFIG_UCLAMP_TASK
2522 	int uclamp_enabled;
2523 #endif
2524 
2525 	/*
2526 	 * move_queued_task/activate_task/enqueue_task: rq->lock
2527 	 * ttwu_do_activate/activate_task/enqueue_task: rq->lock
2528 	 * wake_up_new_task/activate_task/enqueue_task: task_rq_lock
2529 	 * ttwu_runnable/enqueue_task: task_rq_lock
2530 	 * proxy_task_current: rq->lock
2531 	 * sched_change_end
2532 	 */
2533 	void (*enqueue_task) (struct rq *rq, struct task_struct *p, int flags);
2534 	/*
2535 	 * move_queued_task/deactivate_task/dequeue_task: rq->lock
2536 	 * __schedule/block_task/dequeue_task: rq->lock
2537 	 * proxy_task_current: rq->lock
2538 	 * wait_task_inactive: task_rq_lock
2539 	 * sched_change_begin
2540 	 */
2541 	bool (*dequeue_task) (struct rq *rq, struct task_struct *p, int flags);
2542 
2543 	/*
2544 	 * do_sched_yield: rq->lock
2545 	 */
2546 	void (*yield_task)   (struct rq *rq);
2547 	/*
2548 	 * yield_to: rq->lock (double)
2549 	 */
2550 	bool (*yield_to_task)(struct rq *rq, struct task_struct *p);
2551 
2552 	/*
2553 	 * move_queued_task: rq->lock
2554 	 * __migrate_swap_task: rq->lock
2555 	 * ttwu_do_activate: rq->lock
2556 	 * ttwu_runnable: task_rq_lock
2557 	 * wake_up_new_task: task_rq_lock
2558 	 */
2559 	void (*wakeup_preempt)(struct rq *rq, struct task_struct *p, int flags);
2560 
2561 	/*
2562 	 * schedule/pick_next_task/prev_balance: rq->lock
2563 	 */
2564 	int (*balance)(struct rq *rq, struct task_struct *prev, struct rq_flags *rf);
2565 
2566 	/*
2567 	 * schedule/pick_next_task: rq->lock
2568 	 */
2569 	struct task_struct *(*pick_task)(struct rq *rq, struct rq_flags *rf);
2570 	/*
2571 	 * Optional! When implemented pick_next_task() should be equivalent to:
2572 	 *
2573 	 *   next = pick_task();
2574 	 *   if (next) {
2575 	 *       put_prev_task(prev);
2576 	 *       set_next_task_first(next);
2577 	 *   }
2578 	 */
2579 	struct task_struct *(*pick_next_task)(struct rq *rq, struct task_struct *prev,
2580 					      struct rq_flags *rf);
2581 
2582 	/*
2583 	 * sched_change:
2584 	 * __schedule: rq->lock
2585 	 */
2586 	void (*put_prev_task)(struct rq *rq, struct task_struct *p, struct task_struct *next);
2587 	void (*set_next_task)(struct rq *rq, struct task_struct *p, bool first);
2588 
2589 	/*
2590 	 * select_task_rq: p->pi_lock
2591 	 * sched_exec: p->pi_lock
2592 	 */
2593 	int  (*select_task_rq)(struct task_struct *p, int task_cpu, int flags);
2594 
2595 	/*
2596 	 * set_task_cpu: p->pi_lock || rq->lock (ttwu like)
2597 	 */
2598 	void (*migrate_task_rq)(struct task_struct *p, int new_cpu);
2599 
2600 	/*
2601 	 * ttwu_do_activate: rq->lock
2602 	 * wake_up_new_task: task_rq_lock
2603 	 */
2604 	void (*task_woken)(struct rq *this_rq, struct task_struct *task);
2605 
2606 	/*
2607 	 * do_set_cpus_allowed: task_rq_lock + sched_change
2608 	 */
2609 	void (*set_cpus_allowed)(struct task_struct *p, struct affinity_context *ctx);
2610 
2611 	/*
2612 	 * sched_set_rq_{on,off}line: rq->lock
2613 	 */
2614 	void (*rq_online)(struct rq *rq);
2615 	void (*rq_offline)(struct rq *rq);
2616 
2617 	/*
2618 	 * push_cpu_stop: p->pi_lock && rq->lock
2619 	 */
2620 	struct rq *(*find_lock_rq)(struct task_struct *p, struct rq *rq);
2621 
2622 	/*
2623 	 * hrtick: rq->lock
2624 	 * sched_tick: rq->lock
2625 	 * sched_tick_remote: rq->lock
2626 	 */
2627 	void (*task_tick)(struct rq *rq, struct task_struct *p, int queued);
2628 	/*
2629 	 * sched_cgroup_fork: p->pi_lock
2630 	 */
2631 	void (*task_fork)(struct task_struct *p);
2632 	/*
2633 	 * finish_task_switch: no locks
2634 	 */
2635 	void (*task_dead)(struct task_struct *p);
2636 
2637 	/*
2638 	 * sched_change
2639 	 */
2640 	void (*switching_from)(struct rq *this_rq, struct task_struct *task);
2641 	void (*switched_from) (struct rq *this_rq, struct task_struct *task);
2642 	void (*switching_to)  (struct rq *this_rq, struct task_struct *task);
2643 	void (*switched_to)   (struct rq *this_rq, struct task_struct *task);
2644 	u64  (*get_prio)     (struct rq *this_rq, struct task_struct *task);
2645 	void (*prio_changed) (struct rq *this_rq, struct task_struct *task,
2646 			      u64 oldprio);
2647 
2648 	/*
2649 	 * set_load_weight: task_rq_lock + sched_change
2650 	 * __setscheduler_parms: task_rq_lock + sched_change
2651 	 */
2652 	void (*reweight_task)(struct rq *this_rq, struct task_struct *task,
2653 			      const struct load_weight *lw);
2654 
2655 	/*
2656 	 * sched_rr_get_interval: task_rq_lock
2657 	 */
2658 	unsigned int (*get_rr_interval)(struct rq *rq,
2659 					struct task_struct *task);
2660 
2661 	/*
2662 	 * task_sched_runtime: task_rq_lock
2663 	 */
2664 	void (*update_curr)(struct rq *rq);
2665 
2666 #ifdef CONFIG_FAIR_GROUP_SCHED
2667 	/*
2668 	 * sched_change_group: task_rq_lock + sched_change
2669 	 */
2670 	void (*task_change_group)(struct task_struct *p);
2671 #endif
2672 
2673 #ifdef CONFIG_SCHED_CORE
2674 	/*
2675 	 * pick_next_task: rq->lock
2676 	 * try_steal_cookie: rq->lock (double)
2677 	 */
2678 	int (*task_is_throttled)(struct task_struct *p, int cpu);
2679 #endif
2680 };
2681 
put_prev_task(struct rq * rq,struct task_struct * prev)2682 static inline void put_prev_task(struct rq *rq, struct task_struct *prev)
2683 {
2684 	WARN_ON_ONCE(rq->donor != prev);
2685 	prev->sched_class->put_prev_task(rq, prev, NULL);
2686 }
2687 
set_next_task(struct rq * rq,struct task_struct * next)2688 static inline void set_next_task(struct rq *rq, struct task_struct *next)
2689 {
2690 	next->sched_class->set_next_task(rq, next, false);
2691 }
2692 
2693 static inline void
__put_prev_set_next_dl_server(struct rq * rq,struct task_struct * prev,struct task_struct * next)2694 __put_prev_set_next_dl_server(struct rq *rq,
2695 			      struct task_struct *prev,
2696 			      struct task_struct *next)
2697 {
2698 	prev->dl_server = NULL;
2699 	next->dl_server = rq->dl_server;
2700 	rq->dl_server = NULL;
2701 }
2702 
put_prev_set_next_task(struct rq * rq,struct task_struct * prev,struct task_struct * next)2703 static inline void put_prev_set_next_task(struct rq *rq,
2704 					  struct task_struct *prev,
2705 					  struct task_struct *next)
2706 {
2707 	WARN_ON_ONCE(rq->donor != prev);
2708 
2709 	__put_prev_set_next_dl_server(rq, prev, next);
2710 
2711 	if (next == prev)
2712 		return;
2713 
2714 	prev->sched_class->put_prev_task(rq, prev, next);
2715 	next->sched_class->set_next_task(rq, next, true);
2716 }
2717 
2718 /*
2719  * Helper to define a sched_class instance; each one is placed in a separate
2720  * section which is ordered by the linker script:
2721  *
2722  *   include/asm-generic/vmlinux.lds.h
2723  *
2724  * *CAREFUL* they are laid out in *REVERSE* order!!!
2725  *
2726  * Also enforce alignment on the instance, not the type, to guarantee layout.
2727  */
2728 #define DEFINE_SCHED_CLASS(name) \
2729 const struct sched_class name##_sched_class \
2730 	__aligned(__alignof__(struct sched_class)) \
2731 	__section("__" #name "_sched_class")
2732 
2733 /* Defined in include/asm-generic/vmlinux.lds.h */
2734 extern struct sched_class __sched_class_highest[];
2735 extern struct sched_class __sched_class_lowest[];
2736 
2737 extern const struct sched_class stop_sched_class;
2738 extern const struct sched_class dl_sched_class;
2739 extern const struct sched_class rt_sched_class;
2740 extern const struct sched_class fair_sched_class;
2741 extern const struct sched_class idle_sched_class;
2742 
2743 /*
2744  * Iterate only active classes. SCX can take over all fair tasks or be
2745  * completely disabled. If the former, skip fair. If the latter, skip SCX.
2746  */
next_active_class(const struct sched_class * class)2747 static inline const struct sched_class *next_active_class(const struct sched_class *class)
2748 {
2749 	class++;
2750 #ifdef CONFIG_SCHED_CLASS_EXT
2751 	if (scx_switched_all() && class == &fair_sched_class)
2752 		class++;
2753 	if (!scx_enabled() && class == &ext_sched_class)
2754 		class++;
2755 #endif
2756 	return class;
2757 }
2758 
2759 #define for_class_range(class, _from, _to) \
2760 	for (class = (_from); class < (_to); class++)
2761 
2762 #define for_each_class(class) \
2763 	for_class_range(class, __sched_class_highest, __sched_class_lowest)
2764 
2765 #define for_active_class_range(class, _from, _to)				\
2766 	for (class = (_from); class != (_to); class = next_active_class(class))
2767 
2768 #define for_each_active_class(class)						\
2769 	for_active_class_range(class, __sched_class_highest, __sched_class_lowest)
2770 
2771 #define sched_class_above(_a, _b)	((_a) < (_b))
2772 
rq_modified_begin(struct rq * rq,const struct sched_class * class)2773 static inline void rq_modified_begin(struct rq *rq, const struct sched_class *class)
2774 {
2775 	if (sched_class_above(rq->next_class, class))
2776 		rq->next_class = class;
2777 }
2778 
rq_modified_above(struct rq * rq,const struct sched_class * class)2779 static inline bool rq_modified_above(struct rq *rq, const struct sched_class *class)
2780 {
2781 	return sched_class_above(rq->next_class, class);
2782 }
2783 
sched_stop_runnable(struct rq * rq)2784 static inline bool sched_stop_runnable(struct rq *rq)
2785 {
2786 	return rq->stop && task_on_rq_queued(rq->stop);
2787 }
2788 
sched_dl_runnable(struct rq * rq)2789 static inline bool sched_dl_runnable(struct rq *rq)
2790 {
2791 	return rq->dl.dl_nr_running > 0;
2792 }
2793 
sched_rt_runnable(struct rq * rq)2794 static inline bool sched_rt_runnable(struct rq *rq)
2795 {
2796 	return rq->rt.rt_queued > 0;
2797 }
2798 
sched_fair_runnable(struct rq * rq)2799 static inline bool sched_fair_runnable(struct rq *rq)
2800 {
2801 	return rq->cfs.nr_queued > 0;
2802 }
2803 
2804 extern struct task_struct *pick_next_task_fair(struct rq *rq, struct task_struct *prev,
2805 					       struct rq_flags *rf);
2806 extern struct task_struct *pick_task_idle(struct rq *rq, struct rq_flags *rf);
2807 
2808 #define SCA_CHECK		0x01
2809 #define SCA_MIGRATE_DISABLE	0x02
2810 #define SCA_MIGRATE_ENABLE	0x04
2811 #define SCA_USER		0x08
2812 
2813 extern void update_group_capacity(struct sched_domain *sd, int cpu);
2814 
2815 extern void sched_balance_trigger(struct rq *rq);
2816 
2817 extern int __set_cpus_allowed_ptr(struct task_struct *p, struct affinity_context *ctx);
2818 extern void set_cpus_allowed_common(struct task_struct *p, struct affinity_context *ctx);
2819 
task_allowed_on_cpu(struct task_struct * p,int cpu)2820 static inline bool task_allowed_on_cpu(struct task_struct *p, int cpu)
2821 {
2822 	/* When not in the task's cpumask, no point in looking further. */
2823 	if (!cpumask_test_cpu(cpu, p->cpus_ptr))
2824 		return false;
2825 
2826 	/* Can @cpu run a user thread? */
2827 	if (!(p->flags & PF_KTHREAD) && !task_cpu_possible(cpu, p))
2828 		return false;
2829 
2830 	return true;
2831 }
2832 
alloc_user_cpus_ptr(int node)2833 static inline cpumask_t *alloc_user_cpus_ptr(int node)
2834 {
2835 	/*
2836 	 * See set_cpus_allowed_force() above for the rcu_head usage.
2837 	 */
2838 	int size = max_t(int, cpumask_size(), sizeof(struct rcu_head));
2839 
2840 	return kmalloc_node(size, GFP_KERNEL, node);
2841 }
2842 
get_push_task(struct rq * rq)2843 static inline struct task_struct *get_push_task(struct rq *rq)
2844 {
2845 	struct task_struct *p = rq->donor;
2846 
2847 	lockdep_assert_rq_held(rq);
2848 
2849 	if (rq->push_busy)
2850 		return NULL;
2851 
2852 	if (p->nr_cpus_allowed == 1)
2853 		return NULL;
2854 
2855 	if (p->migration_disabled)
2856 		return NULL;
2857 
2858 	rq->push_busy = true;
2859 	return get_task_struct(p);
2860 }
2861 
2862 extern int push_cpu_stop(void *arg);
2863 
2864 #ifdef CONFIG_CPU_IDLE
2865 
idle_set_state(struct rq * rq,struct cpuidle_state * idle_state)2866 static inline void idle_set_state(struct rq *rq,
2867 				  struct cpuidle_state *idle_state)
2868 {
2869 	rq->idle_state = idle_state;
2870 }
2871 
idle_get_state(struct rq * rq)2872 static inline struct cpuidle_state *idle_get_state(struct rq *rq)
2873 {
2874 	lockdep_assert(rcu_read_lock_any_held());
2875 
2876 	return rq->idle_state;
2877 }
2878 
2879 #else /* !CONFIG_CPU_IDLE: */
2880 
idle_set_state(struct rq * rq,struct cpuidle_state * idle_state)2881 static inline void idle_set_state(struct rq *rq,
2882 				  struct cpuidle_state *idle_state)
2883 {
2884 }
2885 
idle_get_state(struct rq * rq)2886 static inline struct cpuidle_state *idle_get_state(struct rq *rq)
2887 {
2888 	return NULL;
2889 }
2890 
2891 #endif /* !CONFIG_CPU_IDLE */
2892 
2893 extern void schedule_idle(void);
2894 asmlinkage void schedule_user(void);
2895 
2896 extern void sysrq_sched_debug_show(void);
2897 extern void sched_init_granularity(void);
2898 extern void update_max_interval(void);
2899 
2900 extern void init_sched_dl_class(void);
2901 extern void init_sched_rt_class(void);
2902 extern void init_sched_fair_class(void);
2903 
2904 extern void resched_curr(struct rq *rq);
2905 extern void resched_curr_lazy(struct rq *rq);
2906 extern void resched_cpu(int cpu);
2907 
2908 extern void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime);
2909 extern bool sched_rt_bandwidth_account(struct rt_rq *rt_rq);
2910 
2911 extern void init_dl_entity(struct sched_dl_entity *dl_se);
2912 
2913 extern void init_cfs_throttle_work(struct task_struct *p);
2914 
2915 #define BW_SHIFT		20
2916 #define BW_UNIT			(1 << BW_SHIFT)
2917 #define RATIO_SHIFT		8
2918 #define MAX_BW_BITS		(64 - BW_SHIFT)
2919 #define MAX_BW			((1ULL << MAX_BW_BITS) - 1)
2920 
2921 extern u64 to_ratio(u64 period, u64 runtime);
2922 
2923 extern void init_entity_runnable_average(struct sched_entity *se);
2924 extern void post_init_entity_util_avg(struct task_struct *p);
2925 
2926 #ifdef CONFIG_NO_HZ_FULL
2927 extern bool sched_can_stop_tick(struct rq *rq);
2928 extern int __init sched_tick_offload_init(void);
2929 
2930 /*
2931  * Tick may be needed by tasks in the runqueue depending on their policy and
2932  * requirements. If tick is needed, lets send the target an IPI to kick it out of
2933  * nohz mode if necessary.
2934  */
sched_update_tick_dependency(struct rq * rq)2935 static inline void sched_update_tick_dependency(struct rq *rq)
2936 {
2937 	int cpu = cpu_of(rq);
2938 
2939 	if (!tick_nohz_full_cpu(cpu))
2940 		return;
2941 
2942 	if (sched_can_stop_tick(rq))
2943 		tick_nohz_dep_clear_cpu(cpu, TICK_DEP_BIT_SCHED);
2944 	else
2945 		tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
2946 }
2947 #else /* !CONFIG_NO_HZ_FULL: */
sched_tick_offload_init(void)2948 static inline int sched_tick_offload_init(void) { return 0; }
sched_update_tick_dependency(struct rq * rq)2949 static inline void sched_update_tick_dependency(struct rq *rq) { }
2950 #endif /* !CONFIG_NO_HZ_FULL */
2951 
add_nr_running(struct rq * rq,unsigned count)2952 static inline void add_nr_running(struct rq *rq, unsigned count)
2953 {
2954 	unsigned prev_nr = rq->nr_running;
2955 
2956 	rq->nr_running = prev_nr + count;
2957 	if (trace_sched_update_nr_running_tp_enabled()) {
2958 		call_trace_sched_update_nr_running(rq, count);
2959 	}
2960 
2961 	if (prev_nr < 2 && rq->nr_running >= 2)
2962 		set_rd_overloaded(rq->rd, 1);
2963 
2964 	sched_update_tick_dependency(rq);
2965 }
2966 
sub_nr_running(struct rq * rq,unsigned count)2967 static inline void sub_nr_running(struct rq *rq, unsigned count)
2968 {
2969 	rq->nr_running -= count;
2970 	if (trace_sched_update_nr_running_tp_enabled()) {
2971 		call_trace_sched_update_nr_running(rq, -count);
2972 	}
2973 
2974 	/* Check if we still need preemption */
2975 	sched_update_tick_dependency(rq);
2976 }
2977 
__block_task(struct rq * rq,struct task_struct * p)2978 static inline void __block_task(struct rq *rq, struct task_struct *p)
2979 {
2980 	if (p->sched_contributes_to_load)
2981 		rq->nr_uninterruptible++;
2982 
2983 	if (p->in_iowait) {
2984 		atomic_inc(&rq->nr_iowait);
2985 		delayacct_blkio_start();
2986 	}
2987 
2988 	ASSERT_EXCLUSIVE_WRITER(p->on_rq);
2989 
2990 	/*
2991 	 * The moment this write goes through, ttwu() can swoop in and migrate
2992 	 * this task, rendering our rq->__lock ineffective.
2993 	 *
2994 	 * __schedule()				try_to_wake_up()
2995 	 *   LOCK rq->__lock			  LOCK p->pi_lock
2996 	 *   pick_next_task()
2997 	 *     pick_next_task_fair()
2998 	 *       pick_next_entity()
2999 	 *         dequeue_entities()
3000 	 *           __block_task()
3001 	 *             RELEASE p->on_rq = 0	  if (p->on_rq && ...)
3002 	 *					    break;
3003 	 *
3004 	 *					  ACQUIRE (after ctrl-dep)
3005 	 *
3006 	 *					  cpu = select_task_rq();
3007 	 *					  set_task_cpu(p, cpu);
3008 	 *					  ttwu_queue()
3009 	 *					    ttwu_do_activate()
3010 	 *					      LOCK rq->__lock
3011 	 *					      activate_task()
3012 	 *					        STORE p->on_rq = 1
3013 	 *   UNLOCK rq->__lock
3014 	 *
3015 	 * Callers must ensure to not reference @p after this -- we no longer
3016 	 * own it.
3017 	 */
3018 	smp_store_release(&p->on_rq, 0);
3019 }
3020 
3021 extern void activate_task(struct rq *rq, struct task_struct *p, int flags);
3022 extern void deactivate_task(struct rq *rq, struct task_struct *p, int flags);
3023 
3024 extern void wakeup_preempt(struct rq *rq, struct task_struct *p, int flags);
3025 
3026 /*
3027  * attach_task() -- attach the task detached by detach_task() to its new rq.
3028  */
attach_task(struct rq * rq,struct task_struct * p)3029 static inline void attach_task(struct rq *rq, struct task_struct *p)
3030 {
3031 	lockdep_assert_rq_held(rq);
3032 
3033 	WARN_ON_ONCE(task_rq(p) != rq);
3034 	activate_task(rq, p, ENQUEUE_NOCLOCK);
3035 	wakeup_preempt(rq, p, 0);
3036 }
3037 
3038 /*
3039  * attach_one_task() -- attaches the task returned from detach_one_task() to
3040  * its new rq.
3041  */
attach_one_task(struct rq * rq,struct task_struct * p)3042 static inline void attach_one_task(struct rq *rq, struct task_struct *p)
3043 {
3044 	guard(rq_lock)(rq);
3045 	update_rq_clock(rq);
3046 	attach_task(rq, p);
3047 }
3048 
3049 #ifdef CONFIG_PREEMPT_RT
3050 # define SCHED_NR_MIGRATE_BREAK 8
3051 #else
3052 # define SCHED_NR_MIGRATE_BREAK 32
3053 #endif
3054 
3055 extern __read_mostly unsigned int sysctl_sched_nr_migrate;
3056 extern __read_mostly unsigned int sysctl_sched_migration_cost;
3057 
3058 extern unsigned int sysctl_sched_base_slice;
3059 
3060 extern int sysctl_resched_latency_warn_ms;
3061 extern int sysctl_resched_latency_warn_once;
3062 
3063 extern unsigned int sysctl_sched_tunable_scaling;
3064 
3065 extern unsigned int sysctl_numa_balancing_scan_delay;
3066 extern unsigned int sysctl_numa_balancing_scan_period_min;
3067 extern unsigned int sysctl_numa_balancing_scan_period_max;
3068 extern unsigned int sysctl_numa_balancing_scan_size;
3069 extern unsigned int sysctl_numa_balancing_hot_threshold;
3070 
3071 #ifdef CONFIG_SCHED_HRTICK
3072 
3073 /*
3074  * Use hrtick when:
3075  *  - enabled by features
3076  *  - hrtimer is actually high res
3077  */
hrtick_enabled(struct rq * rq)3078 static inline bool hrtick_enabled(struct rq *rq)
3079 {
3080 	return cpu_active(cpu_of(rq)) && hrtimer_highres_enabled();
3081 }
3082 
hrtick_enabled_fair(struct rq * rq)3083 static inline bool hrtick_enabled_fair(struct rq *rq)
3084 {
3085 	return sched_feat(HRTICK) && hrtick_enabled(rq);
3086 }
3087 
hrtick_enabled_dl(struct rq * rq)3088 static inline bool hrtick_enabled_dl(struct rq *rq)
3089 {
3090 	return sched_feat(HRTICK_DL) && hrtick_enabled(rq);
3091 }
3092 
3093 extern void hrtick_start(struct rq *rq, u64 delay);
hrtick_active(struct rq * rq)3094 static inline bool hrtick_active(struct rq *rq)
3095 {
3096 	return hrtimer_active(&rq->hrtick_timer);
3097 }
3098 
3099 #else /* !CONFIG_SCHED_HRTICK: */
hrtick_enabled_fair(struct rq * rq)3100 static inline bool hrtick_enabled_fair(struct rq *rq) { return false; }
hrtick_enabled_dl(struct rq * rq)3101 static inline bool hrtick_enabled_dl(struct rq *rq) { return false; }
hrtick_enabled(struct rq * rq)3102 static inline bool hrtick_enabled(struct rq *rq) { return false; }
3103 #endif /* !CONFIG_SCHED_HRTICK */
3104 
3105 #ifndef arch_scale_freq_tick
arch_scale_freq_tick(void)3106 static __always_inline void arch_scale_freq_tick(void) { }
3107 #endif
3108 
3109 #ifndef arch_scale_freq_capacity
3110 /**
3111  * arch_scale_freq_capacity - get the frequency scale factor of a given CPU.
3112  * @cpu: the CPU in question.
3113  *
3114  * Return: the frequency scale factor normalized against SCHED_CAPACITY_SCALE, i.e.
3115  *
3116  *     f_curr
3117  *     ------ * SCHED_CAPACITY_SCALE
3118  *     f_max
3119  */
3120 static __always_inline
arch_scale_freq_capacity(int cpu)3121 unsigned long arch_scale_freq_capacity(int cpu)
3122 {
3123 	return SCHED_CAPACITY_SCALE;
3124 }
3125 #endif
3126 
3127 /*
3128  * In double_lock_balance()/double_rq_lock(), we use raw_spin_rq_lock() to
3129  * acquire rq lock instead of rq_lock(). So at the end of these two functions
3130  * we need to call double_rq_clock_clear_update() to clear RQCF_UPDATED of
3131  * rq->clock_update_flags to avoid the WARN_DOUBLE_CLOCK warning.
3132  */
double_rq_clock_clear_update(struct rq * rq1,struct rq * rq2)3133 static inline void double_rq_clock_clear_update(struct rq *rq1, struct rq *rq2)
3134 {
3135 	rq1->clock_update_flags &= (RQCF_REQ_SKIP|RQCF_ACT_SKIP);
3136 	rq2->clock_update_flags &= (RQCF_REQ_SKIP|RQCF_ACT_SKIP);
3137 }
3138 
3139 #define DEFINE_LOCK_GUARD_2(name, type, _lock, _unlock, ...)				\
3140 __DEFINE_UNLOCK_GUARD(name, type, _unlock, type *lock2; __VA_ARGS__)			\
3141 static inline class_##name##_t class_##name##_constructor(type *lock, type *lock2)	\
3142 	__no_context_analysis								\
3143 { class_##name##_t _t = { .lock = lock, .lock2 = lock2 }, *_T = &_t;			\
3144   _lock; return _t; }
3145 #define DECLARE_LOCK_GUARD_2_ATTRS(_name, _lock, _unlock1, _unlock2)			\
3146 static inline class_##_name##_t class_##_name##_constructor(lock_##_name##_t *_T1,	\
3147 							    lock_##_name##_t *_T2) _lock; \
3148 static __always_inline void __class_##_name##_cleanup_ctx1(class_##_name##_t **_T1)	\
3149 	__no_context_analysis _unlock1 { }						\
3150 static __always_inline void __class_##_name##_cleanup_ctx2(class_##_name##_t **_T2)	\
3151 	__no_context_analysis _unlock2 { }
3152 #define WITH_LOCK_GUARD_2_ATTRS(_name, _T1, _T2)					\
3153 	class_##_name##_constructor(_T1, _T2),						\
3154 	*__UNIQUE_ID(unlock1) __cleanup(__class_##_name##_cleanup_ctx1) = (void *)(_T1),\
3155 	*__UNIQUE_ID(unlock2) __cleanup(__class_##_name##_cleanup_ctx2) = (void *)(_T2)
3156 
rq_order_less(struct rq * rq1,struct rq * rq2)3157 static inline bool rq_order_less(struct rq *rq1, struct rq *rq2)
3158 {
3159 #ifdef CONFIG_SCHED_CORE
3160 	/*
3161 	 * In order to not have {0,2},{1,3} turn into into an AB-BA,
3162 	 * order by core-id first and cpu-id second.
3163 	 *
3164 	 * Notably:
3165 	 *
3166 	 *	double_rq_lock(0,3); will take core-0, core-1 lock
3167 	 *	double_rq_lock(1,2); will take core-1, core-0 lock
3168 	 *
3169 	 * when only cpu-id is considered.
3170 	 */
3171 	if (rq1->core->cpu < rq2->core->cpu)
3172 		return true;
3173 	if (rq1->core->cpu > rq2->core->cpu)
3174 		return false;
3175 
3176 	/*
3177 	 * __sched_core_flip() relies on SMT having cpu-id lock order.
3178 	 */
3179 #endif /* CONFIG_SCHED_CORE */
3180 	return rq1->cpu < rq2->cpu;
3181 }
3182 
3183 extern void double_rq_lock(struct rq *rq1, struct rq *rq2)
3184 	__acquires(__rq_lockp(rq1), __rq_lockp(rq2));
3185 
3186 #ifdef CONFIG_PREEMPTION
3187 
3188 /*
3189  * fair double_lock_balance: Safely acquires both rq->locks in a fair
3190  * way at the expense of forcing extra atomic operations in all
3191  * invocations.  This assures that the double_lock is acquired using the
3192  * same underlying policy as the spinlock_t on this architecture, which
3193  * reduces latency compared to the unfair variant below.  However, it
3194  * also adds more overhead and therefore may reduce throughput.
3195  */
_double_lock_balance(struct rq * this_rq,struct rq * busiest)3196 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
3197 	__must_hold(__rq_lockp(this_rq))
3198 	__acquires(__rq_lockp(busiest))
3199 {
3200 	raw_spin_rq_unlock(this_rq);
3201 	double_rq_lock(this_rq, busiest);
3202 
3203 	return 1;
3204 }
3205 
3206 #else /* !CONFIG_PREEMPTION: */
3207 /*
3208  * Unfair double_lock_balance: Optimizes throughput at the expense of
3209  * latency by eliminating extra atomic operations when the locks are
3210  * already in proper order on entry.  This favors lower CPU-ids and will
3211  * grant the double lock to lower CPUs over higher ids under contention,
3212  * regardless of entry order into the function.
3213  */
_double_lock_balance(struct rq * this_rq,struct rq * busiest)3214 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
3215 	__must_hold(__rq_lockp(this_rq))
3216 	__acquires(__rq_lockp(busiest))
3217 {
3218 	if (__rq_lockp(this_rq) == __rq_lockp(busiest)) {
3219 		__acquire(__rq_lockp(busiest)); /* already held */
3220 		double_rq_clock_clear_update(this_rq, busiest);
3221 		return 0;
3222 	}
3223 
3224 	if (likely(raw_spin_rq_trylock(busiest))) {
3225 		double_rq_clock_clear_update(this_rq, busiest);
3226 		return 0;
3227 	}
3228 
3229 	if (rq_order_less(this_rq, busiest)) {
3230 		raw_spin_rq_lock_nested(busiest, SINGLE_DEPTH_NESTING);
3231 		double_rq_clock_clear_update(this_rq, busiest);
3232 		return 0;
3233 	}
3234 
3235 	raw_spin_rq_unlock(this_rq);
3236 	double_rq_lock(this_rq, busiest);
3237 
3238 	return 1;
3239 }
3240 
3241 #endif /* !CONFIG_PREEMPTION */
3242 
3243 /*
3244  * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
3245  */
double_lock_balance(struct rq * this_rq,struct rq * busiest)3246 static inline int double_lock_balance(struct rq *this_rq, struct rq *busiest)
3247 	__must_hold(__rq_lockp(this_rq))
3248 	__acquires(__rq_lockp(busiest))
3249 {
3250 	lockdep_assert_irqs_disabled();
3251 
3252 	return _double_lock_balance(this_rq, busiest);
3253 }
3254 
double_unlock_balance(struct rq * this_rq,struct rq * busiest)3255 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
3256 	__releases(__rq_lockp(busiest))
3257 {
3258 	if (__rq_lockp(this_rq) != __rq_lockp(busiest))
3259 		raw_spin_rq_unlock(busiest);
3260 	else
3261 		__release(__rq_lockp(busiest)); /* fake release */
3262 	lock_set_subclass(&__rq_lockp(this_rq)->dep_map, 0, _RET_IP_);
3263 }
3264 
double_lock(spinlock_t * l1,spinlock_t * l2)3265 static inline void double_lock(spinlock_t *l1, spinlock_t *l2)
3266 	__acquires(l1, l2)
3267 {
3268 	if (l1 > l2)
3269 		swap(l1, l2);
3270 
3271 	spin_lock(l1);
3272 	spin_lock_nested(l2, SINGLE_DEPTH_NESTING);
3273 }
3274 
double_lock_irq(spinlock_t * l1,spinlock_t * l2)3275 static inline void double_lock_irq(spinlock_t *l1, spinlock_t *l2)
3276 	__acquires(l1, l2)
3277 {
3278 	if (l1 > l2)
3279 		swap(l1, l2);
3280 
3281 	spin_lock_irq(l1);
3282 	spin_lock_nested(l2, SINGLE_DEPTH_NESTING);
3283 }
3284 
double_raw_lock(raw_spinlock_t * l1,raw_spinlock_t * l2)3285 static inline void double_raw_lock(raw_spinlock_t *l1, raw_spinlock_t *l2)
3286 	__acquires(l1, l2)
3287 {
3288 	if (l1 > l2)
3289 		swap(l1, l2);
3290 
3291 	raw_spin_lock(l1);
3292 	raw_spin_lock_nested(l2, SINGLE_DEPTH_NESTING);
3293 }
3294 
double_raw_unlock(raw_spinlock_t * l1,raw_spinlock_t * l2)3295 static inline void double_raw_unlock(raw_spinlock_t *l1, raw_spinlock_t *l2)
3296 	__releases(l1, l2)
3297 {
3298 	raw_spin_unlock(l1);
3299 	raw_spin_unlock(l2);
3300 }
3301 
3302 DEFINE_LOCK_GUARD_2(double_raw_spinlock, raw_spinlock_t,
3303 		    double_raw_lock(_T->lock, _T->lock2),
3304 		    double_raw_unlock(_T->lock, _T->lock2))
3305 
3306 DECLARE_LOCK_GUARD_2_ATTRS(double_raw_spinlock,
3307 			   __acquires(_T1, _T2),
3308 			   __releases(*(raw_spinlock_t **)_T1),
3309 			   __releases(*(raw_spinlock_t **)_T2));
3310 #define class_double_raw_spinlock_constructor(_T1, _T2) \
3311 	WITH_LOCK_GUARD_2_ATTRS(double_raw_spinlock, _T1, _T2)
3312 
3313 /*
3314  * double_rq_unlock - safely unlock two runqueues
3315  *
3316  * Note this does not restore interrupts like task_rq_unlock,
3317  * you need to do so manually after calling.
3318  */
double_rq_unlock(struct rq * rq1,struct rq * rq2)3319 static inline void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3320 	__releases(__rq_lockp(rq1), __rq_lockp(rq2))
3321 {
3322 	if (__rq_lockp(rq1) != __rq_lockp(rq2))
3323 		raw_spin_rq_unlock(rq2);
3324 	else
3325 		__release(__rq_lockp(rq2)); /* fake release */
3326 	raw_spin_rq_unlock(rq1);
3327 }
3328 
3329 extern void set_rq_online (struct rq *rq);
3330 extern void set_rq_offline(struct rq *rq);
3331 
3332 extern bool sched_smp_initialized;
3333 
3334 DEFINE_LOCK_GUARD_2(double_rq_lock, struct rq,
3335 		    double_rq_lock(_T->lock, _T->lock2),
3336 		    double_rq_unlock(_T->lock, _T->lock2))
3337 
3338 extern struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq);
3339 extern struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq);
3340 extern struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq);
3341 
3342 extern bool sched_debug_verbose;
3343 
3344 extern void print_cfs_stats(struct seq_file *m, int cpu);
3345 extern void print_rt_stats(struct seq_file *m, int cpu);
3346 extern void print_dl_stats(struct seq_file *m, int cpu);
3347 extern void print_cfs_rq(struct seq_file *m, int cpu, struct cfs_rq *cfs_rq);
3348 extern void print_rt_rq(struct seq_file *m, int cpu, struct rt_rq *rt_rq);
3349 extern void print_dl_rq(struct seq_file *m, int cpu, struct dl_rq *dl_rq);
3350 
3351 extern void resched_latency_warn(int cpu, u64 latency);
3352 
3353 #ifdef CONFIG_NUMA_BALANCING
3354 extern void show_numa_stats(struct task_struct *p, struct seq_file *m);
3355 extern void
3356 print_numa_stats(struct seq_file *m, int node, unsigned long tsf,
3357 		 unsigned long tpf, unsigned long gsf, unsigned long gpf);
3358 #endif /* CONFIG_NUMA_BALANCING */
3359 
3360 extern void init_cfs_rq(struct cfs_rq *cfs_rq);
3361 extern void init_rt_rq(struct rt_rq *rt_rq);
3362 extern void init_dl_rq(struct dl_rq *dl_rq);
3363 
3364 extern void cfs_bandwidth_usage_inc(void);
3365 extern void cfs_bandwidth_usage_dec(void);
3366 
3367 #ifdef CONFIG_NO_HZ_COMMON
3368 
3369 #define NOHZ_BALANCE_KICK_BIT	0
3370 #define NOHZ_STATS_KICK_BIT	1
3371 #define NOHZ_NEWILB_KICK_BIT	2
3372 #define NOHZ_NEXT_KICK_BIT	3
3373 
3374 /* Run sched_balance_domains() */
3375 #define NOHZ_BALANCE_KICK	BIT(NOHZ_BALANCE_KICK_BIT)
3376 /* Update blocked load */
3377 #define NOHZ_STATS_KICK		BIT(NOHZ_STATS_KICK_BIT)
3378 /* Update blocked load when entering idle */
3379 #define NOHZ_NEWILB_KICK	BIT(NOHZ_NEWILB_KICK_BIT)
3380 /* Update nohz.next_balance */
3381 #define NOHZ_NEXT_KICK		BIT(NOHZ_NEXT_KICK_BIT)
3382 
3383 #define NOHZ_KICK_MASK		(NOHZ_BALANCE_KICK | NOHZ_STATS_KICK | NOHZ_NEXT_KICK)
3384 
3385 #define nohz_flags(cpu)		(&cpu_rq(cpu)->nohz_flags)
3386 
3387 extern void nohz_balance_exit_idle(struct rq *rq);
3388 #else /* !CONFIG_NO_HZ_COMMON: */
nohz_balance_exit_idle(struct rq * rq)3389 static inline void nohz_balance_exit_idle(struct rq *rq) { }
3390 #endif /* !CONFIG_NO_HZ_COMMON */
3391 
3392 #ifdef CONFIG_NO_HZ_COMMON
3393 extern void nohz_run_idle_balance(int cpu);
3394 #else
nohz_run_idle_balance(int cpu)3395 static inline void nohz_run_idle_balance(int cpu) { }
3396 #endif
3397 
3398 #include "stats.h"
3399 
3400 #if defined(CONFIG_SCHED_CORE) && defined(CONFIG_SCHEDSTATS)
3401 
3402 extern void __sched_core_account_forceidle(struct rq *rq);
3403 
sched_core_account_forceidle(struct rq * rq)3404 static inline void sched_core_account_forceidle(struct rq *rq)
3405 {
3406 	if (schedstat_enabled())
3407 		__sched_core_account_forceidle(rq);
3408 }
3409 
3410 extern void __sched_core_tick(struct rq *rq);
3411 
sched_core_tick(struct rq * rq)3412 static inline void sched_core_tick(struct rq *rq)
3413 {
3414 	if (sched_core_enabled(rq) && schedstat_enabled())
3415 		__sched_core_tick(rq);
3416 }
3417 
3418 #else /* !(CONFIG_SCHED_CORE && CONFIG_SCHEDSTATS): */
3419 
sched_core_account_forceidle(struct rq * rq)3420 static inline void sched_core_account_forceidle(struct rq *rq) { }
3421 
sched_core_tick(struct rq * rq)3422 static inline void sched_core_tick(struct rq *rq) { }
3423 
3424 #endif /* !(CONFIG_SCHED_CORE && CONFIG_SCHEDSTATS) */
3425 
3426 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
3427 
3428 struct irqtime {
3429 	u64			total;
3430 	u64			tick_delta;
3431 	u64			irq_start_time;
3432 	struct u64_stats_sync	sync;
3433 };
3434 
3435 DECLARE_PER_CPU(struct irqtime, cpu_irqtime);
3436 DECLARE_STATIC_KEY_FALSE(sched_clock_irqtime);
3437 
irqtime_enabled(void)3438 static inline int irqtime_enabled(void)
3439 {
3440 	return static_branch_likely(&sched_clock_irqtime);
3441 }
3442 
3443 /*
3444  * Returns the irqtime minus the softirq time computed by ksoftirqd.
3445  * Otherwise ksoftirqd's sum_exec_runtime is subtracted its own runtime
3446  * and never move forward.
3447  */
irq_time_read(int cpu)3448 static inline u64 irq_time_read(int cpu)
3449 {
3450 	struct irqtime *irqtime = &per_cpu(cpu_irqtime, cpu);
3451 	unsigned int seq;
3452 	u64 total;
3453 
3454 	do {
3455 		seq = __u64_stats_fetch_begin(&irqtime->sync);
3456 		total = irqtime->total;
3457 	} while (__u64_stats_fetch_retry(&irqtime->sync, seq));
3458 
3459 	return total;
3460 }
3461 
3462 #else /* !CONFIG_IRQ_TIME_ACCOUNTING: */
3463 
irqtime_enabled(void)3464 static inline int irqtime_enabled(void)
3465 {
3466 	return 0;
3467 }
3468 
3469 #endif /* !CONFIG_IRQ_TIME_ACCOUNTING */
3470 
3471 #ifdef CONFIG_CPU_FREQ
3472 
3473 DECLARE_PER_CPU(struct update_util_data __rcu *, cpufreq_update_util_data);
3474 
3475 /**
3476  * cpufreq_update_util - Take a note about CPU utilization changes.
3477  * @rq: Runqueue to carry out the update for.
3478  * @flags: Update reason flags.
3479  *
3480  * This function is called by the scheduler on the CPU whose utilization is
3481  * being updated.
3482  *
3483  * It can only be called from RCU-sched read-side critical sections.
3484  *
3485  * The way cpufreq is currently arranged requires it to evaluate the CPU
3486  * performance state (frequency/voltage) on a regular basis to prevent it from
3487  * being stuck in a completely inadequate performance level for too long.
3488  * That is not guaranteed to happen if the updates are only triggered from CFS
3489  * and DL, though, because they may not be coming in if only RT tasks are
3490  * active all the time (or there are RT tasks only).
3491  *
3492  * As a workaround for that issue, this function is called periodically by the
3493  * RT sched class to trigger extra cpufreq updates to prevent it from stalling,
3494  * but that really is a band-aid.  Going forward it should be replaced with
3495  * solutions targeted more specifically at RT tasks.
3496  */
cpufreq_update_util(struct rq * rq,unsigned int flags)3497 static inline void cpufreq_update_util(struct rq *rq, unsigned int flags)
3498 {
3499 	struct update_util_data *data;
3500 
3501 	data = rcu_dereference_sched(*per_cpu_ptr(&cpufreq_update_util_data,
3502 						  cpu_of(rq)));
3503 	if (data)
3504 		data->func(data, rq_clock(rq), flags);
3505 }
3506 #else /* !CONFIG_CPU_FREQ: */
cpufreq_update_util(struct rq * rq,unsigned int flags)3507 static inline void cpufreq_update_util(struct rq *rq, unsigned int flags) { }
3508 #endif /* !CONFIG_CPU_FREQ */
3509 
3510 #ifdef arch_scale_freq_capacity
3511 # ifndef arch_scale_freq_invariant
3512 #  define arch_scale_freq_invariant()	true
3513 # endif
3514 #else
3515 # define arch_scale_freq_invariant()	false
3516 #endif
3517 
3518 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
3519 				 unsigned long *min,
3520 				 unsigned long *max);
3521 
3522 unsigned long sugov_effective_cpu_perf(int cpu, unsigned long actual,
3523 				 unsigned long min,
3524 				 unsigned long max);
3525 
3526 
3527 /*
3528  * Verify the fitness of task @p to run on @cpu taking into account the
3529  * CPU original capacity and the runtime/deadline ratio of the task.
3530  *
3531  * The function will return true if the original capacity of @cpu is
3532  * greater than or equal to task's deadline density right shifted by
3533  * (BW_SHIFT - SCHED_CAPACITY_SHIFT) and false otherwise.
3534  */
dl_task_fits_capacity(struct task_struct * p,int cpu)3535 static inline bool dl_task_fits_capacity(struct task_struct *p, int cpu)
3536 {
3537 	unsigned long cap = arch_scale_cpu_capacity(cpu);
3538 
3539 	return cap >= p->dl.dl_density >> (BW_SHIFT - SCHED_CAPACITY_SHIFT);
3540 }
3541 
cpu_bw_dl(struct rq * rq)3542 static inline unsigned long cpu_bw_dl(struct rq *rq)
3543 {
3544 	return (rq->dl.running_bw * SCHED_CAPACITY_SCALE) >> BW_SHIFT;
3545 }
3546 
cpu_util_dl(struct rq * rq)3547 static inline unsigned long cpu_util_dl(struct rq *rq)
3548 {
3549 	return READ_ONCE(rq->avg_dl.util_avg);
3550 }
3551 
3552 
3553 extern unsigned long cpu_util_cfs(int cpu);
3554 extern unsigned long cpu_util_cfs_boost(int cpu);
3555 
cpu_util_rt(struct rq * rq)3556 static inline unsigned long cpu_util_rt(struct rq *rq)
3557 {
3558 	return READ_ONCE(rq->avg_rt.util_avg);
3559 }
3560 
3561 #ifdef CONFIG_UCLAMP_TASK
3562 
3563 unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id);
3564 
3565 /*
3566  * When uclamp is compiled in, the aggregation at rq level is 'turned off'
3567  * by default in the fast path and only gets turned on once userspace performs
3568  * an operation that requires it.
3569  *
3570  * Returns true if userspace opted-in to use uclamp and aggregation at rq level
3571  * hence is active.
3572  */
uclamp_is_used(void)3573 static inline bool uclamp_is_used(void)
3574 {
3575 	return static_branch_likely(&sched_uclamp_used);
3576 }
3577 
3578 /*
3579  * Enabling static branches would get the cpus_read_lock(),
3580  * check whether uclamp_is_used before enable it to avoid always
3581  * calling cpus_read_lock(). Because we never disable this
3582  * static key once enable it.
3583  */
sched_uclamp_enable(void)3584 static inline void sched_uclamp_enable(void)
3585 {
3586 	if (!uclamp_is_used())
3587 		static_branch_enable(&sched_uclamp_used);
3588 }
3589 
uclamp_rq_get(struct rq * rq,enum uclamp_id clamp_id)3590 static inline unsigned long uclamp_rq_get(struct rq *rq,
3591 					  enum uclamp_id clamp_id)
3592 {
3593 	return READ_ONCE(rq->uclamp[clamp_id].value);
3594 }
3595 
uclamp_rq_set(struct rq * rq,enum uclamp_id clamp_id,unsigned int value)3596 static inline void uclamp_rq_set(struct rq *rq, enum uclamp_id clamp_id,
3597 				 unsigned int value)
3598 {
3599 	WRITE_ONCE(rq->uclamp[clamp_id].value, value);
3600 }
3601 
uclamp_rq_is_idle(struct rq * rq)3602 static inline bool uclamp_rq_is_idle(struct rq *rq)
3603 {
3604 	return rq->uclamp_flags & UCLAMP_FLAG_IDLE;
3605 }
3606 
3607 /* Is the rq being capped/throttled by uclamp_max? */
uclamp_rq_is_capped(struct rq * rq)3608 static inline bool uclamp_rq_is_capped(struct rq *rq)
3609 {
3610 	unsigned long rq_util;
3611 	unsigned long max_util;
3612 
3613 	if (!uclamp_is_used())
3614 		return false;
3615 
3616 	rq_util = cpu_util_cfs(cpu_of(rq)) + cpu_util_rt(rq);
3617 	max_util = READ_ONCE(rq->uclamp[UCLAMP_MAX].value);
3618 
3619 	return max_util != SCHED_CAPACITY_SCALE && rq_util >= max_util;
3620 }
3621 
3622 #define for_each_clamp_id(clamp_id) \
3623 	for ((clamp_id) = 0; (clamp_id) < UCLAMP_CNT; (clamp_id)++)
3624 
3625 extern unsigned int sysctl_sched_uclamp_util_min_rt_default;
3626 
3627 
uclamp_none(enum uclamp_id clamp_id)3628 static inline unsigned int uclamp_none(enum uclamp_id clamp_id)
3629 {
3630 	if (clamp_id == UCLAMP_MIN)
3631 		return 0;
3632 	return SCHED_CAPACITY_SCALE;
3633 }
3634 
3635 /* Integer rounded range for each bucket */
3636 #define UCLAMP_BUCKET_DELTA DIV_ROUND_CLOSEST(SCHED_CAPACITY_SCALE, UCLAMP_BUCKETS)
3637 
uclamp_bucket_id(unsigned int clamp_value)3638 static inline unsigned int uclamp_bucket_id(unsigned int clamp_value)
3639 {
3640 	return min_t(unsigned int, clamp_value / UCLAMP_BUCKET_DELTA, UCLAMP_BUCKETS - 1);
3641 }
3642 
3643 static inline void
uclamp_se_set(struct uclamp_se * uc_se,unsigned int value,bool user_defined)3644 uclamp_se_set(struct uclamp_se *uc_se, unsigned int value, bool user_defined)
3645 {
3646 	uc_se->value = value;
3647 	uc_se->bucket_id = uclamp_bucket_id(value);
3648 	uc_se->user_defined = user_defined;
3649 }
3650 
3651 #else /* !CONFIG_UCLAMP_TASK: */
3652 
3653 static inline unsigned long
uclamp_eff_value(struct task_struct * p,enum uclamp_id clamp_id)3654 uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
3655 {
3656 	if (clamp_id == UCLAMP_MIN)
3657 		return 0;
3658 
3659 	return SCHED_CAPACITY_SCALE;
3660 }
3661 
uclamp_rq_is_capped(struct rq * rq)3662 static inline bool uclamp_rq_is_capped(struct rq *rq) { return false; }
3663 
uclamp_is_used(void)3664 static inline bool uclamp_is_used(void)
3665 {
3666 	return false;
3667 }
3668 
sched_uclamp_enable(void)3669 static inline void sched_uclamp_enable(void) {}
3670 
3671 static inline unsigned long
uclamp_rq_get(struct rq * rq,enum uclamp_id clamp_id)3672 uclamp_rq_get(struct rq *rq, enum uclamp_id clamp_id)
3673 {
3674 	if (clamp_id == UCLAMP_MIN)
3675 		return 0;
3676 
3677 	return SCHED_CAPACITY_SCALE;
3678 }
3679 
3680 static inline void
uclamp_rq_set(struct rq * rq,enum uclamp_id clamp_id,unsigned int value)3681 uclamp_rq_set(struct rq *rq, enum uclamp_id clamp_id, unsigned int value)
3682 {
3683 }
3684 
uclamp_rq_is_idle(struct rq * rq)3685 static inline bool uclamp_rq_is_idle(struct rq *rq)
3686 {
3687 	return false;
3688 }
3689 
3690 #endif /* !CONFIG_UCLAMP_TASK */
3691 
3692 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
3693 
cpu_util_irq(struct rq * rq)3694 static inline unsigned long cpu_util_irq(struct rq *rq)
3695 {
3696 	return READ_ONCE(rq->avg_irq.util_avg);
3697 }
3698 
3699 static inline
scale_irq_capacity(unsigned long util,unsigned long irq,unsigned long max)3700 unsigned long scale_irq_capacity(unsigned long util, unsigned long irq, unsigned long max)
3701 {
3702 	util *= (max - irq);
3703 	util /= max;
3704 
3705 	return util;
3706 
3707 }
3708 
3709 #else /* !CONFIG_HAVE_SCHED_AVG_IRQ: */
3710 
cpu_util_irq(struct rq * rq)3711 static inline unsigned long cpu_util_irq(struct rq *rq)
3712 {
3713 	return 0;
3714 }
3715 
3716 static inline
scale_irq_capacity(unsigned long util,unsigned long irq,unsigned long max)3717 unsigned long scale_irq_capacity(unsigned long util, unsigned long irq, unsigned long max)
3718 {
3719 	return util;
3720 }
3721 
3722 #endif /* !CONFIG_HAVE_SCHED_AVG_IRQ */
3723 
3724 extern void __setparam_fair(struct task_struct *p, const struct sched_attr *attr);
3725 
3726 #if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_CPU_FREQ_GOV_SCHEDUTIL)
3727 
3728 #define perf_domain_span(pd) (to_cpumask(((pd)->em_pd->cpus)))
3729 
3730 DECLARE_STATIC_KEY_FALSE(sched_energy_present);
3731 
sched_energy_enabled(void)3732 static inline bool sched_energy_enabled(void)
3733 {
3734 	return static_branch_unlikely(&sched_energy_present);
3735 }
3736 
3737 #else /* !(CONFIG_ENERGY_MODEL && CONFIG_CPU_FREQ_GOV_SCHEDUTIL): */
3738 
3739 #define perf_domain_span(pd) NULL
3740 
sched_energy_enabled(void)3741 static inline bool sched_energy_enabled(void) { return false; }
3742 
3743 #endif /* !(CONFIG_ENERGY_MODEL && CONFIG_CPU_FREQ_GOV_SCHEDUTIL) */
3744 
3745 #ifdef CONFIG_MEMBARRIER
3746 
3747 /*
3748  * The scheduler provides memory barriers required by membarrier between:
3749  * - prior user-space memory accesses and store to rq->membarrier_state,
3750  * - store to rq->membarrier_state and following user-space memory accesses.
3751  * In the same way it provides those guarantees around store to rq->curr.
3752  */
membarrier_switch_mm(struct rq * rq,struct mm_struct * prev_mm,struct mm_struct * next_mm)3753 static inline void membarrier_switch_mm(struct rq *rq,
3754 					struct mm_struct *prev_mm,
3755 					struct mm_struct *next_mm)
3756 {
3757 	int membarrier_state;
3758 
3759 	if (prev_mm == next_mm)
3760 		return;
3761 
3762 	membarrier_state = atomic_read(&next_mm->membarrier_state);
3763 	if (READ_ONCE(rq->membarrier_state) == membarrier_state)
3764 		return;
3765 
3766 	WRITE_ONCE(rq->membarrier_state, membarrier_state);
3767 }
3768 
3769 #else /* !CONFIG_MEMBARRIER: */
3770 
membarrier_switch_mm(struct rq * rq,struct mm_struct * prev_mm,struct mm_struct * next_mm)3771 static inline void membarrier_switch_mm(struct rq *rq,
3772 					struct mm_struct *prev_mm,
3773 					struct mm_struct *next_mm)
3774 {
3775 }
3776 
3777 #endif /* !CONFIG_MEMBARRIER */
3778 
is_per_cpu_kthread(struct task_struct * p)3779 static inline bool is_per_cpu_kthread(struct task_struct *p)
3780 {
3781 	if (!(p->flags & PF_KTHREAD))
3782 		return false;
3783 
3784 	if (p->nr_cpus_allowed != 1)
3785 		return false;
3786 
3787 	return true;
3788 }
3789 
3790 extern void swake_up_all_locked(struct swait_queue_head *q);
3791 extern void __prepare_to_swait(struct swait_queue_head *q, struct swait_queue *wait);
3792 
3793 extern int try_to_wake_up(struct task_struct *tsk, unsigned int state, int wake_flags);
3794 
3795 #ifdef CONFIG_PREEMPT_DYNAMIC
3796 extern int preempt_dynamic_mode;
3797 extern int sched_dynamic_mode(const char *str);
3798 extern void sched_dynamic_update(int mode);
3799 #endif
3800 extern const char *preempt_modes[];
3801 
3802 #ifdef CONFIG_SCHED_MM_CID
3803 
cid_on_cpu(unsigned int cid)3804 static __always_inline bool cid_on_cpu(unsigned int cid)
3805 {
3806 	return cid & MM_CID_ONCPU;
3807 }
3808 
cid_in_transit(unsigned int cid)3809 static __always_inline bool cid_in_transit(unsigned int cid)
3810 {
3811 	return cid & MM_CID_TRANSIT;
3812 }
3813 
cpu_cid_to_cid(unsigned int cid)3814 static __always_inline unsigned int cpu_cid_to_cid(unsigned int cid)
3815 {
3816 	return cid & ~MM_CID_ONCPU;
3817 }
3818 
cid_to_cpu_cid(unsigned int cid)3819 static __always_inline unsigned int cid_to_cpu_cid(unsigned int cid)
3820 {
3821 	return cid | MM_CID_ONCPU;
3822 }
3823 
cid_to_transit_cid(unsigned int cid)3824 static __always_inline unsigned int cid_to_transit_cid(unsigned int cid)
3825 {
3826 	return cid | MM_CID_TRANSIT;
3827 }
3828 
cid_from_transit_cid(unsigned int cid)3829 static __always_inline unsigned int cid_from_transit_cid(unsigned int cid)
3830 {
3831 	return cid & ~MM_CID_TRANSIT;
3832 }
3833 
cid_on_task(unsigned int cid)3834 static __always_inline bool cid_on_task(unsigned int cid)
3835 {
3836 	/* True if none of the MM_CID_ONCPU, MM_CID_TRANSIT, MM_CID_UNSET bits is set */
3837 	return cid < MM_CID_TRANSIT;
3838 }
3839 
mm_drop_cid(struct mm_struct * mm,unsigned int cid)3840 static __always_inline void mm_drop_cid(struct mm_struct *mm, unsigned int cid)
3841 {
3842 	clear_bit(cid, mm_cidmask(mm));
3843 }
3844 
mm_unset_cid_on_task(struct task_struct * t)3845 static __always_inline void mm_unset_cid_on_task(struct task_struct *t)
3846 {
3847 	unsigned int cid = t->mm_cid.cid;
3848 
3849 	t->mm_cid.cid = MM_CID_UNSET;
3850 	if (cid_on_task(cid))
3851 		mm_drop_cid(t->mm, cid);
3852 }
3853 
mm_drop_cid_on_cpu(struct mm_struct * mm,struct mm_cid_pcpu * pcp)3854 static __always_inline void mm_drop_cid_on_cpu(struct mm_struct *mm, struct mm_cid_pcpu *pcp)
3855 {
3856 	/* Clear the ONCPU bit, but do not set UNSET in the per CPU storage */
3857 	if (cid_on_cpu(pcp->cid)) {
3858 		pcp->cid = cpu_cid_to_cid(pcp->cid);
3859 		mm_drop_cid(mm, pcp->cid);
3860 	}
3861 }
3862 
__mm_get_cid(struct mm_struct * mm,unsigned int max_cids)3863 static inline unsigned int __mm_get_cid(struct mm_struct *mm, unsigned int max_cids)
3864 {
3865 	unsigned int cid = find_first_zero_bit(mm_cidmask(mm), max_cids);
3866 
3867 	if (cid >= max_cids)
3868 		return MM_CID_UNSET;
3869 	if (test_and_set_bit(cid, mm_cidmask(mm)))
3870 		return MM_CID_UNSET;
3871 	return cid;
3872 }
3873 
mm_get_cid(struct mm_struct * mm)3874 static inline unsigned int mm_get_cid(struct mm_struct *mm)
3875 {
3876 	unsigned int cid = __mm_get_cid(mm, READ_ONCE(mm->mm_cid.max_cids));
3877 
3878 	while (cid == MM_CID_UNSET) {
3879 		cpu_relax();
3880 		cid = __mm_get_cid(mm, num_possible_cpus());
3881 	}
3882 	return cid;
3883 }
3884 
mm_cid_converge(struct mm_struct * mm,unsigned int orig_cid,unsigned int max_cids)3885 static inline unsigned int mm_cid_converge(struct mm_struct *mm, unsigned int orig_cid,
3886 					   unsigned int max_cids)
3887 {
3888 	unsigned int new_cid, cid = cpu_cid_to_cid(orig_cid);
3889 
3890 	/* Is it in the optimal CID space? */
3891 	if (likely(cid < max_cids))
3892 		return orig_cid;
3893 
3894 	/* Try to find one in the optimal space. Otherwise keep the provided. */
3895 	new_cid = __mm_get_cid(mm, max_cids);
3896 	if (new_cid != MM_CID_UNSET) {
3897 		mm_drop_cid(mm, cid);
3898 		/* Preserve the ONCPU mode of the original CID */
3899 		return new_cid | (orig_cid & MM_CID_ONCPU);
3900 	}
3901 	return orig_cid;
3902 }
3903 
mm_cid_update_task_cid(struct task_struct * t,unsigned int cid)3904 static __always_inline void mm_cid_update_task_cid(struct task_struct *t, unsigned int cid)
3905 {
3906 	if (t->mm_cid.cid != cid) {
3907 		t->mm_cid.cid = cid;
3908 		rseq_sched_set_ids_changed(t);
3909 	}
3910 }
3911 
mm_cid_update_pcpu_cid(struct mm_struct * mm,unsigned int cid)3912 static __always_inline void mm_cid_update_pcpu_cid(struct mm_struct *mm, unsigned int cid)
3913 {
3914 	__this_cpu_write(mm->mm_cid.pcpu->cid, cid);
3915 }
3916 
mm_cid_from_cpu(struct task_struct * t,unsigned int cpu_cid,unsigned int mode)3917 static __always_inline void mm_cid_from_cpu(struct task_struct *t, unsigned int cpu_cid,
3918 					    unsigned int mode)
3919 {
3920 	unsigned int max_cids, tcid = t->mm_cid.cid;
3921 	struct mm_struct *mm = t->mm;
3922 
3923 	max_cids = READ_ONCE(mm->mm_cid.max_cids);
3924 	/* Optimize for the common case where both have the ONCPU bit set */
3925 	if (likely(cid_on_cpu(cpu_cid & tcid))) {
3926 		if (likely(cpu_cid_to_cid(cpu_cid) < max_cids)) {
3927 			mm_cid_update_task_cid(t, cpu_cid);
3928 			return;
3929 		}
3930 		/* Try to converge into the optimal CID space */
3931 		cpu_cid = mm_cid_converge(mm, cpu_cid, max_cids);
3932 	} else {
3933 		/* Hand over or drop the task owned CID */
3934 		if (cid_on_task(tcid)) {
3935 			if (cid_on_cpu(cpu_cid))
3936 				mm_unset_cid_on_task(t);
3937 			else
3938 				cpu_cid = cid_to_cpu_cid(tcid);
3939 		}
3940 		/* Still nothing, allocate a new one */
3941 		if (!cid_on_cpu(cpu_cid))
3942 			cpu_cid = cid_to_cpu_cid(mm_get_cid(mm));
3943 
3944 		/* Handle the transition mode flag if required */
3945 		if (mode & MM_CID_TRANSIT)
3946 			cpu_cid = cpu_cid_to_cid(cpu_cid) | MM_CID_TRANSIT;
3947 	}
3948 	mm_cid_update_pcpu_cid(mm, cpu_cid);
3949 	mm_cid_update_task_cid(t, cpu_cid);
3950 }
3951 
mm_cid_from_task(struct task_struct * t,unsigned int cpu_cid,unsigned int mode)3952 static __always_inline void mm_cid_from_task(struct task_struct *t, unsigned int cpu_cid,
3953 					     unsigned int mode)
3954 {
3955 	unsigned int max_cids, tcid = t->mm_cid.cid;
3956 	struct mm_struct *mm = t->mm;
3957 
3958 	max_cids = READ_ONCE(mm->mm_cid.max_cids);
3959 	/* Optimize for the common case, where both have the ONCPU bit clear */
3960 	if (likely(cid_on_task(tcid | cpu_cid))) {
3961 		if (likely(tcid < max_cids)) {
3962 			mm_cid_update_pcpu_cid(mm, tcid);
3963 			return;
3964 		}
3965 		/* Try to converge into the optimal CID space */
3966 		tcid = mm_cid_converge(mm, tcid, max_cids);
3967 	} else {
3968 		/* Hand over or drop the CPU owned CID */
3969 		if (cid_on_cpu(cpu_cid)) {
3970 			if (cid_on_task(tcid))
3971 				mm_drop_cid_on_cpu(mm, this_cpu_ptr(mm->mm_cid.pcpu));
3972 			else
3973 				tcid = cpu_cid_to_cid(cpu_cid);
3974 		}
3975 		/* Still nothing, allocate a new one */
3976 		if (!cid_on_task(tcid))
3977 			tcid = mm_get_cid(mm);
3978 		/* Set the transition mode flag if required */
3979 		tcid |= mode & MM_CID_TRANSIT;
3980 	}
3981 	mm_cid_update_pcpu_cid(mm, tcid);
3982 	mm_cid_update_task_cid(t, tcid);
3983 }
3984 
mm_cid_schedin(struct task_struct * next)3985 static __always_inline void mm_cid_schedin(struct task_struct *next)
3986 {
3987 	struct mm_struct *mm = next->mm;
3988 	unsigned int cpu_cid, mode;
3989 
3990 	if (!next->mm_cid.active)
3991 		return;
3992 
3993 	cpu_cid = __this_cpu_read(mm->mm_cid.pcpu->cid);
3994 	mode = READ_ONCE(mm->mm_cid.mode);
3995 	if (likely(!cid_on_cpu(mode)))
3996 		mm_cid_from_task(next, cpu_cid, mode);
3997 	else
3998 		mm_cid_from_cpu(next, cpu_cid, mode);
3999 }
4000 
mm_cid_schedout(struct task_struct * prev)4001 static __always_inline void mm_cid_schedout(struct task_struct *prev)
4002 {
4003 	struct mm_struct *mm = prev->mm;
4004 	unsigned int mode, cid;
4005 
4006 	/* During mode transitions CIDs are temporary and need to be dropped */
4007 	if (likely(!cid_in_transit(prev->mm_cid.cid)))
4008 		return;
4009 
4010 	mode = READ_ONCE(mm->mm_cid.mode);
4011 	cid = cid_from_transit_cid(prev->mm_cid.cid);
4012 
4013 	/*
4014 	 * If transition mode is done, transfer ownership when the CID is
4015 	 * within the convergence range to optimize the next schedule in.
4016 	 */
4017 	if (!cid_in_transit(mode) && cid < READ_ONCE(mm->mm_cid.max_cids)) {
4018 		if (cid_on_cpu(mode))
4019 			cid = cid_to_cpu_cid(cid);
4020 
4021 		/* Update both so that the next schedule in goes into the fast path */
4022 		mm_cid_update_pcpu_cid(mm, cid);
4023 		prev->mm_cid.cid = cid;
4024 	} else {
4025 		mm_drop_cid(mm, cid);
4026 		prev->mm_cid.cid = MM_CID_UNSET;
4027 	}
4028 }
4029 
mm_cid_switch_to(struct task_struct * prev,struct task_struct * next)4030 static inline void mm_cid_switch_to(struct task_struct *prev, struct task_struct *next)
4031 {
4032 	mm_cid_schedout(prev);
4033 	mm_cid_schedin(next);
4034 }
4035 
4036 #else /* !CONFIG_SCHED_MM_CID: */
mm_cid_switch_to(struct task_struct * prev,struct task_struct * next)4037 static inline void mm_cid_switch_to(struct task_struct *prev, struct task_struct *next) { }
4038 #endif /* !CONFIG_SCHED_MM_CID */
4039 
4040 extern u64 avg_vruntime(struct cfs_rq *cfs_rq);
4041 extern int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se);
4042 static inline
move_queued_task_locked(struct rq * src_rq,struct rq * dst_rq,struct task_struct * task)4043 void move_queued_task_locked(struct rq *src_rq, struct rq *dst_rq, struct task_struct *task)
4044 {
4045 	lockdep_assert_rq_held(src_rq);
4046 	lockdep_assert_rq_held(dst_rq);
4047 
4048 	deactivate_task(src_rq, task, 0);
4049 	set_task_cpu(task, dst_rq->cpu);
4050 	activate_task(dst_rq, task, 0);
4051 	wakeup_preempt(dst_rq, task, 0);
4052 }
4053 
4054 static inline
task_is_pushable(struct rq * rq,struct task_struct * p,int cpu)4055 bool task_is_pushable(struct rq *rq, struct task_struct *p, int cpu)
4056 {
4057 	if (!task_on_cpu(rq, p) &&
4058 	    cpumask_test_cpu(cpu, &p->cpus_mask))
4059 		return true;
4060 
4061 	return false;
4062 }
4063 
4064 #ifdef CONFIG_RT_MUTEXES
4065 
__rt_effective_prio(struct task_struct * pi_task,int prio)4066 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
4067 {
4068 	if (pi_task)
4069 		prio = min(prio, pi_task->prio);
4070 
4071 	return prio;
4072 }
4073 
rt_effective_prio(struct task_struct * p,int prio)4074 static inline int rt_effective_prio(struct task_struct *p, int prio)
4075 {
4076 	struct task_struct *pi_task = rt_mutex_get_top_task(p);
4077 
4078 	return __rt_effective_prio(pi_task, prio);
4079 }
4080 
4081 #else /* !CONFIG_RT_MUTEXES: */
4082 
rt_effective_prio(struct task_struct * p,int prio)4083 static inline int rt_effective_prio(struct task_struct *p, int prio)
4084 {
4085 	return prio;
4086 }
4087 
4088 #endif /* !CONFIG_RT_MUTEXES */
4089 
4090 extern int __sched_setscheduler(struct task_struct *p, const struct sched_attr *attr, bool user, bool pi);
4091 extern int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx);
4092 extern const struct sched_class *__setscheduler_class(int policy, int prio);
4093 extern void set_load_weight(struct task_struct *p, bool update_load);
4094 extern void enqueue_task(struct rq *rq, struct task_struct *p, int flags);
4095 extern bool dequeue_task(struct rq *rq, struct task_struct *p, int flags);
4096 
4097 extern struct balance_callback *splice_balance_callbacks(struct rq *rq);
4098 
4099 extern void __balance_callbacks(struct rq *rq, struct rq_flags *rf);
4100 extern void balance_callbacks(struct rq *rq, struct balance_callback *head);
4101 
4102 /*
4103  * The 'sched_change' pattern is the safe, easy and slow way of changing a
4104  * task's scheduling properties. It dequeues a task, such that the scheduler
4105  * is fully unaware of it; at which point its properties can be modified;
4106  * after which it is enqueued again.
4107  *
4108  * Typically this must be called while holding task_rq_lock, since most/all
4109  * properties are serialized under those locks. There is currently one
4110  * exception to this rule in sched/ext which only holds rq->lock.
4111  */
4112 
4113 /*
4114  * This structure is a temporary, used to preserve/convey the queueing state
4115  * of the task between sched_change_begin() and sched_change_end(). Ensuring
4116  * the task's queueing state is idempotent across the operation.
4117  */
4118 struct sched_change_ctx {
4119 	u64			prio;
4120 	struct task_struct	*p;
4121 	const struct sched_class *class;
4122 	int			flags;
4123 	bool			queued;
4124 	bool			running;
4125 };
4126 
4127 struct sched_change_ctx *sched_change_begin(struct task_struct *p, unsigned int flags);
4128 void sched_change_end(struct sched_change_ctx *ctx);
4129 
4130 DEFINE_CLASS(sched_change, struct sched_change_ctx *,
4131 	     sched_change_end(_T),
4132 	     sched_change_begin(p, flags),
4133 	     struct task_struct *p, unsigned int flags)
4134 
4135 DEFINE_CLASS_IS_UNCONDITIONAL(sched_change)
4136 
4137 #include "ext.h"
4138 
4139 #endif /* _KERNEL_SCHED_SCHED_H */
4140