xref: /linux/tools/sched_ext/include/scx/common.bpf.h (revision b3768d058c98d4e8114a246d3267d7dae1c123fb)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
4  * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
5  * Copyright (c) 2022 David Vernet <dvernet@meta.com>
6  */
7 #ifndef __SCX_COMMON_BPF_H
8 #define __SCX_COMMON_BPF_H
9 
10 /*
11  * The generated kfunc prototypes in vmlinux.h are missing address space
12  * attributes which cause build failures. For now, suppress the generated
13  * prototypes. See https://github.com/sched-ext/scx/issues/1111.
14  */
15 #define BPF_NO_KFUNC_PROTOTYPES
16 
17 #ifdef LSP
18 #define __bpf__
19 #include "../vmlinux.h"
20 #else
21 #include "vmlinux.h"
22 #endif
23 
24 #include <bpf/bpf_helpers.h>
25 #include <bpf/bpf_tracing.h>
26 #include <asm-generic/errno.h>
27 #include "user_exit_info.bpf.h"
28 #include "enum_defs.autogen.h"
29 #include "bpf_arena_common.bpf.h"
30 #include "const-defs.h"
31 
32 #define PF_IDLE				0x00000002	/* I am an IDLE thread */
33 #define PF_IO_WORKER			0x00000010	/* Task is an IO worker */
34 #define PF_WQ_WORKER			0x00000020	/* I'm a workqueue worker */
35 #define PF_KCOMPACTD			0x00010000      /* I am kcompactd */
36 #define PF_KSWAPD			0x00020000      /* I am kswapd */
37 #define PF_KTHREAD			0x00200000	/* I am a kernel thread */
38 #define PF_EXITING			0x00000004
39 #define CLOCK_MONOTONIC			1
40 
41 #ifndef NR_CPUS
42 #define NR_CPUS 1024
43 #endif
44 
45 #ifndef NUMA_NO_NODE
46 #define	NUMA_NO_NODE	(-1)
47 #endif
48 
49 extern int LINUX_KERNEL_VERSION __kconfig;
50 extern const char CONFIG_CC_VERSION_TEXT[64] __kconfig __weak;
51 extern const char CONFIG_LOCALVERSION[64] __kconfig __weak;
52 extern bool CONFIG_PREEMPT_RCU __kconfig __weak;
53 
54 /*
55  * Earlier versions of clang/pahole lost upper 32bits in 64bit enums which can
56  * lead to really confusing misbehaviors. Let's trigger a build failure.
57  */
58 static inline void ___vmlinux_h_sanity_check___(void)
59 {
60 	_Static_assert(SCX_DSQ_FLAG_BUILTIN,
61 		       "bpftool generated vmlinux.h is missing high bits for 64bit enums, upgrade clang and pahole");
62 }
63 
64 s32 scx_bpf_create_dsq(u64 dsq_id, s32 node) __ksym;
65 s32 scx_bpf_select_cpu_dfl(struct task_struct *p, s32 prev_cpu, u64 wake_flags, bool *is_idle) __ksym;
66 s32 __scx_bpf_select_cpu_and(struct task_struct *p, const struct cpumask *cpus_allowed,
67 			     struct scx_bpf_select_cpu_and_args *args) __ksym __weak;
68 bool __scx_bpf_dsq_insert_vtime(struct task_struct *p, struct scx_bpf_dsq_insert_vtime_args *args) __ksym __weak;
69 u32 scx_bpf_dispatch_nr_slots(void) __ksym;
70 void scx_bpf_dispatch_cancel(void) __ksym;
71 void scx_bpf_kick_cpu(s32 cpu, u64 flags) __ksym;
72 s32 scx_bpf_dsq_nr_queued(u64 dsq_id) __ksym;
73 void scx_bpf_destroy_dsq(u64 dsq_id) __ksym;
74 struct task_struct *scx_bpf_dsq_peek(u64 dsq_id) __ksym __weak;
75 int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id, u64 flags) __ksym __weak;
76 struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it) __ksym __weak;
77 void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it) __ksym __weak;
78 bool scx_bpf_dsq_reenq_task(struct bpf_iter_scx_dsq *it, struct task_struct *p) __ksym __weak;
79 void scx_bpf_exit_bstr(s64 exit_code, char *fmt, unsigned long long *data, u32 data__sz) __ksym __weak;
80 void scx_bpf_error_bstr(char *fmt, unsigned long long *data, u32 data_len) __ksym;
81 void scx_bpf_dump_bstr(char *fmt, unsigned long long *data, u32 data_len) __ksym __weak;
82 u32 scx_bpf_cpuperf_cap(s32 cpu) __ksym __weak;
83 u32 scx_bpf_cpuperf_cur(s32 cpu) __ksym __weak;
84 void scx_bpf_cpuperf_set(s32 cpu, u32 perf) __ksym __weak;
85 u32 scx_bpf_nr_node_ids(void) __ksym __weak;
86 u32 scx_bpf_nr_cpu_ids(void) __ksym __weak;
87 int scx_bpf_cpu_node(s32 cpu) __ksym __weak;
88 const struct cpumask *scx_bpf_get_possible_cpumask(void) __ksym __weak;
89 const struct cpumask *scx_bpf_get_online_cpumask(void) __ksym __weak;
90 void scx_bpf_put_cpumask(const struct cpumask *cpumask) __ksym __weak;
91 const struct cpumask *scx_bpf_get_idle_cpumask_node(int node) __ksym __weak;
92 const struct cpumask *scx_bpf_get_idle_cpumask(void) __ksym;
93 const struct cpumask *scx_bpf_get_idle_smtmask_node(int node) __ksym __weak;
94 const struct cpumask *scx_bpf_get_idle_smtmask(void) __ksym;
95 void scx_bpf_put_idle_cpumask(const struct cpumask *cpumask) __ksym;
96 bool scx_bpf_test_and_clear_cpu_idle(s32 cpu) __ksym;
97 s32 scx_bpf_pick_idle_cpu_node(const cpumask_t *cpus_allowed, int node, u64 flags) __ksym __weak;
98 s32 scx_bpf_pick_idle_cpu(const cpumask_t *cpus_allowed, u64 flags) __ksym;
99 s32 scx_bpf_pick_any_cpu_node(const cpumask_t *cpus_allowed, int node, u64 flags) __ksym __weak;
100 s32 scx_bpf_pick_any_cpu(const cpumask_t *cpus_allowed, u64 flags) __ksym;
101 bool scx_bpf_task_running(const struct task_struct *p) __ksym;
102 s32 scx_bpf_task_cpu(const struct task_struct *p) __ksym;
103 struct rq *scx_bpf_cpu_rq(s32 cpu) __ksym __weak;
104 struct rq *scx_bpf_locked_rq(void) __ksym;
105 struct task_struct *scx_bpf_cpu_curr(s32 cpu) __ksym __weak;
106 struct task_struct *scx_bpf_tid_to_task(u64 tid) __ksym __weak;
107 u64 scx_bpf_now(void) __ksym __weak;
108 void scx_bpf_events(struct scx_event_stats *events, size_t events__sz) __ksym __weak;
109 u32 scx_bpf_cgroup_nr_cpus(struct cgroup *cgrp) __ksym __weak;
110 s32 scx_bpf_cpu_to_cid(s32 cpu) __ksym __weak;
111 s32 scx_bpf_cid_to_cpu(s32 cid) __ksym __weak;
112 s32 scx_bpf_cid_node(s32 cid) __ksym __weak;
113 /* scx_bpf_cid_topo() and scx_bpf_kick_cid() are declared in compat.bpf.h */
114 s32 scx_bpf_task_cid(const struct task_struct *p) __ksym __weak;
115 s32 scx_bpf_this_cid(void) __ksym __weak;
116 struct task_struct *scx_bpf_cid_curr(s32 cid) __ksym __weak;
117 u32 scx_bpf_nr_cids(void) __ksym __weak;
118 u32 scx_bpf_nr_online_cids(void) __ksym __weak;
119 const void __arena *scx_bpf_online_cmask(void) __ksym __weak;
120 u32 scx_bpf_cidperf_cap(s32 cid) __ksym __weak;
121 u32 scx_bpf_cidperf_cur(s32 cid) __ksym __weak;
122 /* scx_bpf_cidperf_set() is declared in compat.bpf.h */
123 
124 /* sub-scheduler cap control, scx_bpf_sub_caps() cgroup_id 0 == self */
125 s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps, const struct scx_cmask __arena *cmask__arena, struct scx_cmask __arena *denied_out__arena__nullable) __ksym __weak;
126 void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps, const struct scx_cmask __arena *cmask__arena) __ksym __weak;
127 s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask __arena *out__arena) __ksym __weak;
128 s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt, unsigned long long *data, u32 data__sz) __ksym __weak;
129 
130 /*
131  * Use the following as @it__iter when calling scx_bpf_dsq_move[_vtime]() from
132  * within bpf_for_each() loops.
133  */
134 #define BPF_FOR_EACH_ITER	(&___it)
135 
136 #define scx_read_event(e, name)							\
137 	(bpf_core_field_exists((e)->name) ? (e)->name : 0)
138 
139 static inline __attribute__((format(printf, 1, 2)))
140 void ___scx_bpf_bstr_format_checker(const char *fmt, ...) {}
141 
142 #define SCX_STRINGIFY(x) #x
143 #define SCX_TOSTRING(x) SCX_STRINGIFY(x)
144 
145 /*
146  * Helper macro for initializing the fmt and variadic argument inputs to both
147  * bstr exit kfuncs. Callers to this function should use ___fmt and ___param to
148  * refer to the initialized list of inputs to the bstr kfunc.
149  */
150 #define scx_bpf_bstr_preamble(fmt, args...)					\
151 	static char ___fmt[] = fmt;						\
152 	/*									\
153 	 * Note that __param[] must have at least one				\
154 	 * element to keep the verifier happy.					\
155 	 */									\
156 	unsigned long long ___param[___bpf_narg(args) ?: 1] = {};		\
157 										\
158 	_Pragma("GCC diagnostic push")						\
159 	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")			\
160 	___bpf_fill(___param, args);						\
161 	_Pragma("GCC diagnostic pop")
162 
163 /*
164  * scx_bpf_exit() wraps the scx_bpf_exit_bstr() kfunc with variadic arguments
165  * instead of an array of u64. Using this macro will cause the scheduler to
166  * exit cleanly with the specified exit code being passed to user space.
167  */
168 #define scx_bpf_exit(code, fmt, args...)					\
169 ({										\
170 	scx_bpf_bstr_preamble(fmt, args)					\
171 	scx_bpf_exit_bstr(code, ___fmt, ___param, sizeof(___param));		\
172 	___scx_bpf_bstr_format_checker(fmt, ##args);				\
173 })
174 
175 /*
176  * scx_bpf_sub_kill() wraps the scx_bpf_sub_kill_bstr() kfunc with variadic
177  * arguments instead of an array of u64. It kills the direct child sub-scheduler
178  * @cgid, passing the formatted reason to its user space, and evaluates to the
179  * kfunc's return value. On a kernel without sub-scheduler support the kfunc is
180  * absent and it returns -EOPNOTSUPP.
181  */
182 #define scx_bpf_sub_kill(cgid, fmt, args...)					\
183 ({										\
184 	scx_bpf_bstr_preamble(fmt, args)					\
185 	___scx_bpf_bstr_format_checker(fmt, ##args);				\
186 	bpf_ksym_exists(scx_bpf_sub_kill_bstr) ?				\
187 		scx_bpf_sub_kill_bstr((cgid), ___fmt, ___param,			\
188 				      sizeof(___param)) : -EOPNOTSUPP;		\
189 })
190 
191 /*
192  * scx_bpf_error() wraps the scx_bpf_error_bstr() kfunc with variadic arguments
193  * instead of an array of u64. Invoking this macro will cause the scheduler to
194  * exit in an erroneous state, with diagnostic information being passed to the
195  * user. It appends the file and line number to aid debugging.
196  */
197 #define scx_bpf_error(fmt, args...)						\
198 ({										\
199 	scx_bpf_bstr_preamble(							\
200 		__FILE__ ":" SCX_TOSTRING(__LINE__) ": " fmt, ##args)		\
201 	scx_bpf_error_bstr(___fmt, ___param, sizeof(___param));			\
202 	___scx_bpf_bstr_format_checker(						\
203 		__FILE__ ":" SCX_TOSTRING(__LINE__) ": " fmt, ##args);		\
204 })
205 
206 /*
207  * scx_bpf_dump() wraps the scx_bpf_dump_bstr() kfunc with variadic arguments
208  * instead of an array of u64. To be used from ops.dump() and friends.
209  */
210 #define scx_bpf_dump(fmt, args...)						\
211 ({										\
212 	scx_bpf_bstr_preamble(fmt, args)					\
213 	scx_bpf_dump_bstr(___fmt, ___param, sizeof(___param));			\
214 	___scx_bpf_bstr_format_checker(fmt, ##args);				\
215 })
216 
217 /*
218  * scx_bpf_dump_header() is a wrapper around scx_bpf_dump that adds a header
219  * of system information for debugging.
220  */
221 #define scx_bpf_dump_header()							\
222 ({										\
223 	scx_bpf_dump("kernel: %d.%d.%d %s\ncc: %s\n",				\
224 		     LINUX_KERNEL_VERSION >> 16,				\
225 		     LINUX_KERNEL_VERSION >> 8 & 0xFF,				\
226 		     LINUX_KERNEL_VERSION & 0xFF,				\
227 		     CONFIG_LOCALVERSION,					\
228 		     CONFIG_CC_VERSION_TEXT);					\
229 })
230 
231 #define BPF_STRUCT_OPS(name, args...)						\
232 SEC("struct_ops/"#name)								\
233 BPF_PROG(name, ##args)
234 
235 #define BPF_STRUCT_OPS_SLEEPABLE(name, args...)					\
236 SEC("struct_ops.s/"#name)							\
237 BPF_PROG(name, ##args)
238 
239 /**
240  * RESIZABLE_ARRAY - Generates annotations for an array that may be resized
241  * @elfsec: the data section of the BPF program in which to place the array
242  * @arr: the name of the array
243  *
244  * libbpf has an API for setting map value sizes. Since data sections (i.e.
245  * bss, data, rodata) themselves are maps, a data section can be resized. If
246  * a data section has an array as its last element, the BTF info for that
247  * array will be adjusted so that length of the array is extended to meet the
248  * new length of the data section. This macro annotates an array to have an
249  * element count of one with the assumption that this array can be resized
250  * within the userspace program. It also annotates the section specifier so
251  * this array exists in a custom sub data section which can be resized
252  * independently.
253  *
254  * See RESIZE_ARRAY() for the userspace convenience macro for resizing an
255  * array declared with RESIZABLE_ARRAY().
256  */
257 #define RESIZABLE_ARRAY(elfsec, arr) arr[1] SEC("."#elfsec"."#arr)
258 
259 /**
260  * MEMBER_VPTR - Obtain the verified pointer to a struct or array member
261  * @base: struct or array to index
262  * @member: dereferenced member (e.g. .field, [idx0][idx1], .field[idx0] ...)
263  *
264  * The verifier often gets confused by the instruction sequence the compiler
265  * generates for indexing struct fields or arrays. This macro forces the
266  * compiler to generate a code sequence which first calculates the byte offset,
267  * checks it against the struct or array size and add that byte offset to
268  * generate the pointer to the member to help the verifier.
269  *
270  * Ideally, we want to abort if the calculated offset is out-of-bounds. However,
271  * BPF currently doesn't support abort, so evaluate to %NULL instead. The caller
272  * must check for %NULL and take appropriate action to appease the verifier. To
273  * avoid confusing the verifier, it's best to check for %NULL and dereference
274  * immediately.
275  *
276  *	vptr = MEMBER_VPTR(my_array, [i][j]);
277  *	if (!vptr)
278  *		return error;
279  *	*vptr = new_value;
280  *
281  * sizeof(@base) should encompass the memory area to be accessed and thus can't
282  * be a pointer to the area. Use `MEMBER_VPTR(*ptr, .member)` instead of
283  * `MEMBER_VPTR(ptr, ->member)`.
284  */
285 #ifndef MEMBER_VPTR
286 #define MEMBER_VPTR(base, member) (typeof((base) member) *)			\
287 ({										\
288 	u64 __base = (u64)&(base);						\
289 	u64 __addr = (u64)&((base) member) - __base;				\
290 	_Static_assert(sizeof(base) >= sizeof((base) member),			\
291 		       "@base is smaller than @member, is @base a pointer?");	\
292 	asm volatile (								\
293 		"if %0 <= %[max] goto +2\n"					\
294 		"%0 = 0\n"							\
295 		"goto +1\n"							\
296 		"%0 += %1\n"							\
297 		: "+r"(__addr)							\
298 		: "r"(__base),							\
299 		  [max]"i"(sizeof(base) - sizeof((base) member)));		\
300 	__addr;									\
301 })
302 #endif /* MEMBER_VPTR */
303 
304 /**
305  * ARRAY_ELEM_PTR - Obtain the verified pointer to an array element
306  * @arr: array to index into
307  * @i: array index
308  * @n: number of elements in array
309  *
310  * Similar to MEMBER_VPTR() but is intended for use with arrays where the
311  * element count needs to be explicit.
312  * It can be used in cases where a global array is defined with an initial
313  * size but is intended to be resized before loading the BPF program.
314  * Without this version of the macro, MEMBER_VPTR() will use the compile time
315  * size of the array to compute the max, which will result in rejection by
316  * the verifier.
317  */
318 #ifndef ARRAY_ELEM_PTR
319 #define ARRAY_ELEM_PTR(arr, i, n) (typeof(arr[i]) *)				\
320 ({										\
321 	u64 __base = (u64)arr;							\
322 	u64 __addr = (u64)&(arr[i]) - __base;					\
323 	asm volatile (								\
324 		"if %0 <= %[max] goto +2\n"					\
325 		"%0 = 0\n"							\
326 		"goto +1\n"							\
327 		"%0 += %1\n"							\
328 		: "+r"(__addr)							\
329 		: "r"(__base),							\
330 		  [max]"r"(sizeof(arr[0]) * ((n) - 1)));			\
331 	__addr;									\
332 })
333 #endif /* ARRAY_ELEM_PTR */
334 
335 /**
336  * __sink - Hide @expr's value from the compiler and BPF verifier
337  * @expr: The expression whose value should be opacified
338  *
339  * No-op at runtime. The empty inline assembly with a read-write constraint
340  * ("+g") has two effects at compile/verify time:
341  *
342  * 1. Compiler: treats @expr as both read and written, preventing dead-code
343  *    elimination and keeping @expr (and any side effects that produced it)
344  *    alive.
345  *
346  * 2. BPF verifier: forgets the precise value/range of @expr ("makes it
347  *    imprecise"). The verifier normally tracks exact ranges for every register
348  *    and stack slot. While useful, precision means each distinct value creates a
349  *    separate verifier state. Inside loops this leads to state explosion - each
350  *    iteration carries different precise values so states never merge and the
351  *    verifier explores every iteration individually.
352  *
353  * Example - preventing loop state explosion::
354  *
355  *     u32 nr_intersects = 0, nr_covered = 0;
356  *     __sink(nr_intersects);
357  *     __sink(nr_covered);
358  *     bpf_for(i, 0, nr_nodes) {
359  *         if (intersects(cpumask, node_mask[i]))
360  *             nr_intersects++;
361  *         if (covers(cpumask, node_mask[i]))
362  *             nr_covered++;
363  *     }
364  *
365  * Without __sink(), the verifier tracks every possible (nr_intersects,
366  * nr_covered) pair across iterations, causing "BPF program is too large". With
367  * __sink(), the values become unknown scalars so all iterations collapse into
368  * one reusable state.
369  *
370  * Example - keeping a reference alive::
371  *
372  *     struct task_struct *t = bpf_task_acquire(task);
373  *     __sink(t);
374  *
375  * Follows the convention from BPF selftests (bpf_misc.h).
376  */
377 #define __sink(expr) asm volatile ("" : "+g"(expr))
378 
379 /*
380  * BPF declarations and helpers
381  */
382 
383 /* list and rbtree */
384 #define __contains(name, node) __attribute__((btf_decl_tag("contains:" #name ":" #node)))
385 #define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
386 
387 void *bpf_obj_new_impl(__u64 local_type_id, void *meta) __ksym;
388 void bpf_obj_drop_impl(void *kptr, void *meta) __ksym;
389 
390 #define bpf_obj_new(type) ((type *)bpf_obj_new_impl(bpf_core_type_id_local(type), NULL))
391 #define bpf_obj_drop(kptr) bpf_obj_drop_impl(kptr, NULL)
392 
393 int bpf_list_push_front_impl(struct bpf_list_head *head,
394 				    struct bpf_list_node *node,
395 				    void *meta, __u64 off) __ksym;
396 #define bpf_list_push_front(head, node) bpf_list_push_front_impl(head, node, NULL, 0)
397 
398 int bpf_list_push_back_impl(struct bpf_list_head *head,
399 				   struct bpf_list_node *node,
400 				   void *meta, __u64 off) __ksym;
401 #define bpf_list_push_back(head, node) bpf_list_push_back_impl(head, node, NULL, 0)
402 
403 struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head) __ksym;
404 struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head) __ksym;
405 struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
406 				      struct bpf_rb_node *node) __ksym;
407 int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
408 			bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
409 			void *meta, __u64 off) __ksym;
410 #define bpf_rbtree_add(head, node, less) bpf_rbtree_add_impl(head, node, less, NULL, 0)
411 
412 struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root) __ksym;
413 
414 void *bpf_refcount_acquire_impl(void *kptr, void *meta) __ksym;
415 #define bpf_refcount_acquire(kptr) bpf_refcount_acquire_impl(kptr, NULL)
416 
417 /* task */
418 struct task_struct *bpf_task_from_pid(s32 pid) __ksym;
419 struct task_struct *bpf_task_acquire(struct task_struct *p) __ksym;
420 void bpf_task_release(struct task_struct *p) __ksym;
421 
422 /* cgroup */
423 struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level) __ksym;
424 struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp) __ksym;
425 void bpf_cgroup_release(struct cgroup *cgrp) __ksym;
426 struct cgroup *bpf_cgroup_from_id(u64 cgid) __ksym;
427 
428 /* css iteration */
429 struct bpf_iter_css;
430 struct cgroup_subsys_state;
431 extern int bpf_iter_css_new(struct bpf_iter_css *it,
432 			    struct cgroup_subsys_state *start,
433 			    unsigned int flags) __weak __ksym;
434 extern struct cgroup_subsys_state *
435 bpf_iter_css_next(struct bpf_iter_css *it) __weak __ksym;
436 extern void bpf_iter_css_destroy(struct bpf_iter_css *it) __weak __ksym;
437 
438 /* cpumask */
439 struct bpf_cpumask *bpf_cpumask_create(void) __ksym;
440 struct bpf_cpumask *bpf_cpumask_acquire(struct bpf_cpumask *cpumask) __ksym;
441 void bpf_cpumask_release(struct bpf_cpumask *cpumask) __ksym;
442 u32 bpf_cpumask_first(const struct cpumask *cpumask) __ksym;
443 u32 bpf_cpumask_first_zero(const struct cpumask *cpumask) __ksym;
444 void bpf_cpumask_set_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;
445 void bpf_cpumask_clear_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;
446 bool bpf_cpumask_test_cpu(u32 cpu, const struct cpumask *cpumask) __ksym;
447 bool bpf_cpumask_test_and_set_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;
448 bool bpf_cpumask_test_and_clear_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;
449 void bpf_cpumask_setall(struct bpf_cpumask *cpumask) __ksym;
450 void bpf_cpumask_clear(struct bpf_cpumask *cpumask) __ksym;
451 bool bpf_cpumask_and(struct bpf_cpumask *dst, const struct cpumask *src1,
452 		     const struct cpumask *src2) __ksym;
453 void bpf_cpumask_or(struct bpf_cpumask *dst, const struct cpumask *src1,
454 		    const struct cpumask *src2) __ksym;
455 void bpf_cpumask_xor(struct bpf_cpumask *dst, const struct cpumask *src1,
456 		     const struct cpumask *src2) __ksym;
457 bool bpf_cpumask_equal(const struct cpumask *src1, const struct cpumask *src2) __ksym;
458 bool bpf_cpumask_intersects(const struct cpumask *src1, const struct cpumask *src2) __ksym;
459 bool bpf_cpumask_subset(const struct cpumask *src1, const struct cpumask *src2) __ksym;
460 bool bpf_cpumask_empty(const struct cpumask *cpumask) __ksym;
461 bool bpf_cpumask_full(const struct cpumask *cpumask) __ksym;
462 void bpf_cpumask_copy(struct bpf_cpumask *dst, const struct cpumask *src) __ksym;
463 u32 bpf_cpumask_any_distribute(const struct cpumask *cpumask) __ksym;
464 u32 bpf_cpumask_any_and_distribute(const struct cpumask *src1,
465 				   const struct cpumask *src2) __ksym;
466 u32 bpf_cpumask_weight(const struct cpumask *cpumask) __ksym;
467 
468 int bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_words) __ksym;
469 int *bpf_iter_bits_next(struct bpf_iter_bits *it) __ksym;
470 void bpf_iter_bits_destroy(struct bpf_iter_bits *it) __ksym;
471 
472 #define def_iter_struct(name)							\
473 struct bpf_iter_##name {							\
474     struct bpf_iter_bits it;							\
475     const struct cpumask *bitmap;						\
476 };
477 
478 #define def_iter_new(name)							\
479 static inline int bpf_iter_##name##_new(					\
480 	struct bpf_iter_##name *it, const u64 *unsafe_ptr__ign, u32 nr_words)	\
481 {										\
482 	it->bitmap = scx_bpf_get_##name##_cpumask();				\
483 	return bpf_iter_bits_new(&it->it, (const u64 *)it->bitmap,		\
484 				 sizeof(struct cpumask) / 8);			\
485 }
486 
487 #define def_iter_next(name)							\
488 static inline int *bpf_iter_##name##_next(struct bpf_iter_##name *it) {		\
489 	return bpf_iter_bits_next(&it->it);					\
490 }
491 
492 #define def_iter_destroy(name)							\
493 static inline void bpf_iter_##name##_destroy(struct bpf_iter_##name *it) {	\
494 	scx_bpf_put_cpumask(it->bitmap);					\
495 	bpf_iter_bits_destroy(&it->it);						\
496 }
497 #define def_for_each_cpu(cpu, name) for_each_##name##_cpu(cpu)
498 
499 /// Provides iterator for possible and online cpus.
500 ///
501 /// # Example
502 ///
503 /// ```
504 /// static inline void example_use() {
505 ///     int *cpu;
506 ///
507 ///     for_each_possible_cpu(cpu){
508 ///         bpf_printk("CPU %d is possible", *cpu);
509 ///     }
510 ///
511 ///     for_each_online_cpu(cpu){
512 ///         bpf_printk("CPU %d is online", *cpu);
513 ///     }
514 /// }
515 /// ```
516 def_iter_struct(possible);
517 def_iter_new(possible);
518 def_iter_next(possible);
519 def_iter_destroy(possible);
520 #define for_each_possible_cpu(cpu) bpf_for_each(possible, cpu, NULL, 0)
521 
522 def_iter_struct(online);
523 def_iter_new(online);
524 def_iter_next(online);
525 def_iter_destroy(online);
526 #define for_each_online_cpu(cpu) bpf_for_each(online, cpu, NULL, 0)
527 
528 /*
529  * Access a cpumask in read-only mode (typically to check bits).
530  */
531 static __always_inline const struct cpumask *cast_mask(struct bpf_cpumask *mask)
532 {
533 	return (const struct cpumask *)mask;
534 }
535 
536 /*
537  * True if the non-sleepable BPF trampoline prolog (__bpf_prog_enter) calls
538  * migrate_disable() for the current task. Recorded once by
539  * scx_lib_init_probe, an fentry program that fires during the natural
540  * scheduler-attach call chain (auto-attached by scx_ops_attach!).
541  *
542  * Defaults to false (conservative). Over-reporting in is_migration_disabled()
543  * causes local-only dispatch, which is safe. Under-reporting can crash the
544  * scheduler, so we err high if the probe somehow fails to run.
545  */
546 bool __scx_prolog_disables_migration __weak = false;
547 
548 /*
549  * scx_lib_init_probe - non-sleepable prolog probe.
550  *
551  * Attached to bpf_scx_reg(), the .reg callback in bpf_sched_ext_ops
552  * (kernel/sched/ext.c). The kernel's struct_ops machinery invokes
553  * bpf_scx_reg when userspace creates the scheduler link, before
554  * ops.init() fires. Its address is taken in the vtable, so the symbol
555  * is non-inlinable and has been stable since introduction.
556  *
557  * A cid-form scheduler registers through bpf_scx_reg_cid(), the .reg
558  * callback of bpf_sched_ext_ops_cid, and so never enters bpf_scx_reg().
559  * The cid-form open paths (SCX_OPS_CID_OPEN(), scx_ops_cid_open!())
560  * therefore repoint this program at bpf_scx_reg_cid(). Repointing rather
561  * than adding a second program keeps the object loadable on kernels
562  * predating the cid form, where bpf_scx_reg_cid() has no BTF entry.
563  *
564  * Entering via fentry runs us through __bpf_prog_enter -- the
565  * non-sleepable prolog that consumers of is_migration_disabled() live
566  * under.
567  *
568  * Loud warning: the prolog adds at most 1 to migration_disabled.
569  * Reading > 1 means something upstream in the
570  * bpf_struct_ops_link_create -> .reg path disabled migration
571  * before the prolog ran, invalidating the probe; audit and adjust.
572  */
573 SEC("fentry/bpf_scx_reg") __weak
574 int scx_lib_init_probe(void *ctx)
575 {
576 	if (bpf_core_field_exists(((struct task_struct *)0)->migration_disabled)) {
577 		const struct task_struct *p = bpf_get_current_task_btf();
578 		unsigned int md = p->migration_disabled;
579 
580 		if (md > 1)
581 			bpf_printk("scx_lib_init_probe: unexpected migration_disabled=%u "
582 				   "upstream of BPF prolog; probe result unreliable",
583 				   md);
584 
585 		__scx_prolog_disables_migration = md > 0;
586 	}
587 	return 0;
588 }
589 
590 /*
591  * Return true if task @p cannot migrate to a different CPU, false
592  * otherwise.
593  *
594  * IMPORTANT: designed for NON-SLEEPABLE BPF contexts only. Sleepable
595  * contexts (BPF_STRUCT_OPS_SLEEPABLE, SEC("syscall"),
596  * SEC("fentry.s/...")) enter via __bpf_prog_enter_sleepable() or
597  * __bpf_prog_enter_sleepable_recur(), both of which unconditionally
598  * call migrate_disable(); this helper can yield a false negative for
599  * p == current there, which can crash the scheduler.
600  */
601 static inline bool is_migration_disabled(const struct task_struct *p)
602 {
603 	/*
604 	 * Testing p->migration_disabled in BPF is tricky because the BPF prolog
605 	 * (__bpf_prog_enter) may call migrate_disable() for the current task,
606 	 * making migration_disabled == 1 even for tasks that are not truly
607 	 * migration-disabled.
608 	 *
609 	 * Since commit 8e4f0b1ebcf2 ("bpf: use rcu_read_lock_dont_migrate() for
610 	 * trampoline.c"), the BPF prolog calls migrate_disable() only when
611 	 * CONFIG_PREEMPT_RCU is enabled. Two fast paths cover the common cases:
612 	 *
613 	 *   1) CONFIG_PREEMPT_RCU: prolog always calls migrate_disable(), so
614 	 *      migration_disabled == 1 for the current task is ambiguous.
615 	 *      Disambiguate by checking p == current.
616 	 *
617 	 *   2) v6.18+ without CONFIG_PREEMPT_RCU: prolog never calls
618 	 *      migrate_disable(), so migration_disabled == 1 is unambiguously
619 	 *      a real migrate_disable() call.
620 	 *
621 	 * A slow path handles pre-v6.18 kernels without CONFIG_PREEMPT_RCU,
622 	 * where the prolog historically called migrate_disable() unconditionally
623 	 * but a cherry-picked downstream kernel may not. The runtime-probed flag
624 	 * __scx_prolog_disables_migration (set by scx_lib_init_probe) distinguishes
625 	 * the two cases without relying on the kernel version alone.
626 	 */
627 	if (bpf_core_field_exists(p->migration_disabled)) {
628 		if (p->migration_disabled == 1) {
629 			/* Fast path: prolog always disables migration */
630 			if (CONFIG_PREEMPT_RCU)
631 				return bpf_get_current_task_btf() != p;
632 			/* Fast path: prolog never disables migration */
633 			if (LINUX_KERNEL_VERSION >= KERNEL_VERSION(6, 18, 0))
634 				return true;
635 			/* Slow path: pre-v6.18, !PREEMPT_RCU - use runtime flag */
636 			return __scx_prolog_disables_migration ?
637 			       bpf_get_current_task_btf() != p : true;
638 		}
639 		return p->migration_disabled;
640 	}
641 	return false;
642 }
643 
644 /* rcu */
645 void bpf_rcu_read_lock(void) __ksym;
646 void bpf_rcu_read_unlock(void) __ksym;
647 
648 /* resilient qspinlock */
649 int bpf_res_spin_lock(struct bpf_res_spin_lock *lock) __ksym __weak;
650 void bpf_res_spin_unlock(struct bpf_res_spin_lock *lock) __ksym __weak;
651 
652 /*
653  * Time helpers, most of which are from jiffies.h.
654  */
655 
656 /**
657  * time_delta - Calculate the delta between new and old time stamp
658  * @after: first comparable as u64
659  * @before: second comparable as u64
660  *
661  * Return: the time difference, which is >= 0
662  */
663 static inline s64 time_delta(u64 after, u64 before)
664 {
665 	return (s64)(after - before) > 0 ? (s64)(after - before) : 0;
666 }
667 
668 /**
669  * time_after - returns true if the time a is after time b.
670  * @a: first comparable as u64
671  * @b: second comparable as u64
672  *
673  * Do this with "<0" and ">=0" to only test the sign of the result. A
674  * good compiler would generate better code (and a really good compiler
675  * wouldn't care). Gcc is currently neither.
676  *
677  * Return: %true is time a is after time b, otherwise %false.
678  */
679 static inline bool time_after(u64 a, u64 b)
680 {
681 	return (s64)(b - a) < 0;
682 }
683 
684 /**
685  * time_before - returns true if the time a is before time b.
686  * @a: first comparable as u64
687  * @b: second comparable as u64
688  *
689  * Return: %true is time a is before time b, otherwise %false.
690  */
691 static inline bool time_before(u64 a, u64 b)
692 {
693 	return time_after(b, a);
694 }
695 
696 /**
697  * time_after_eq - returns true if the time a is after or the same as time b.
698  * @a: first comparable as u64
699  * @b: second comparable as u64
700  *
701  * Return: %true is time a is after or the same as time b, otherwise %false.
702  */
703 static inline bool time_after_eq(u64 a, u64 b)
704 {
705 	return (s64)(a - b) >= 0;
706 }
707 
708 /**
709  * time_before_eq - returns true if the time a is before or the same as time b.
710  * @a: first comparable as u64
711  * @b: second comparable as u64
712  *
713  * Return: %true is time a is before or the same as time b, otherwise %false.
714  */
715 static inline bool time_before_eq(u64 a, u64 b)
716 {
717 	return time_after_eq(b, a);
718 }
719 
720 /**
721  * time_in_range - Calculate whether a is in the range of [b, c].
722  * @a: time to test
723  * @b: beginning of the range
724  * @c: end of the range
725  *
726  * Return: %true is time a is in the range [b, c], otherwise %false.
727  */
728 static inline bool time_in_range(u64 a, u64 b, u64 c)
729 {
730 	return time_after_eq(a, b) && time_before_eq(a, c);
731 }
732 
733 /**
734  * time_in_range_open - Calculate whether a is in the range of [b, c).
735  * @a: time to test
736  * @b: beginning of the range
737  * @c: end of the range
738  *
739  * Return: %true is time a is in the range [b, c), otherwise %false.
740  */
741 static inline bool time_in_range_open(u64 a, u64 b, u64 c)
742 {
743 	return time_after_eq(a, b) && time_before(a, c);
744 }
745 
746 
747 /*
748  * Other helpers
749  */
750 
751 /* useful compiler attributes */
752 #ifndef likely
753 #define likely(x) __builtin_expect(!!(x), 1)
754 #endif
755 #ifndef unlikely
756 #define unlikely(x) __builtin_expect(!!(x), 0)
757 #endif
758 #ifndef __maybe_unused
759 #define __maybe_unused __attribute__((__unused__))
760 #endif
761 
762 /*
763  * READ/WRITE_ONCE() are from kernel (include/asm-generic/rwonce.h). They
764  * prevent compiler from caching, redoing or reordering reads or writes.
765  */
766 typedef __u8  __attribute__((__may_alias__))  __u8_alias_t;
767 typedef __u16 __attribute__((__may_alias__)) __u16_alias_t;
768 typedef __u32 __attribute__((__may_alias__)) __u32_alias_t;
769 typedef __u64 __attribute__((__may_alias__)) __u64_alias_t;
770 
771 static __always_inline void __read_once_size(const volatile void *p, void *res, int size)
772 {
773 	switch (size) {
774 	case 1: *(__u8_alias_t  *) res = *(volatile __u8_alias_t  *) p; break;
775 	case 2: *(__u16_alias_t *) res = *(volatile __u16_alias_t *) p; break;
776 	case 4: *(__u32_alias_t *) res = *(volatile __u32_alias_t *) p; break;
777 	case 8: *(__u64_alias_t *) res = *(volatile __u64_alias_t *) p; break;
778 	default:
779 		barrier();
780 		__builtin_memcpy((void *)res, (const void *)p, size);
781 		barrier();
782 	}
783 }
784 
785 static __always_inline void __write_once_size(volatile void *p, void *res, int size)
786 {
787 	switch (size) {
788 	case 1: *(volatile  __u8_alias_t *) p = *(__u8_alias_t  *) res; break;
789 	case 2: *(volatile __u16_alias_t *) p = *(__u16_alias_t *) res; break;
790 	case 4: *(volatile __u32_alias_t *) p = *(__u32_alias_t *) res; break;
791 	case 8: *(volatile __u64_alias_t *) p = *(__u64_alias_t *) res; break;
792 	default:
793 		barrier();
794 		__builtin_memcpy((void *)p, (const void *)res, size);
795 		barrier();
796 	}
797 }
798 
799 /*
800  * __unqual_typeof(x) - Declare an unqualified scalar type, leaving
801  *			non-scalar types unchanged,
802  *
803  * Prefer C11 _Generic for better compile-times and simpler code. Note: 'char'
804  * is not type-compatible with 'signed char', and we define a separate case.
805  *
806  * This is copied verbatim from kernel's include/linux/compiler_types.h, but
807  * with default expression (for pointers) changed from (x) to (typeof(x)0).
808  *
809  * This is because LLVM has a bug where for lvalue (x), it does not get rid of
810  * an extra address_space qualifier, but does in case of rvalue (typeof(x)0).
811  * Hence, for pointers, we need to create an rvalue expression to get the
812  * desired type. See https://github.com/llvm/llvm-project/issues/53400.
813  */
814 #define __scalar_type_to_expr_cases(type) \
815 	unsigned type : (unsigned type)0, signed type : (signed type)0
816 
817 #define __unqual_typeof(x)                              \
818 	typeof(_Generic((x),                            \
819 		char: (char)0,                          \
820 		__scalar_type_to_expr_cases(char),      \
821 		__scalar_type_to_expr_cases(short),     \
822 		__scalar_type_to_expr_cases(int),       \
823 		__scalar_type_to_expr_cases(long),      \
824 		__scalar_type_to_expr_cases(long long), \
825 		default: (typeof(x))0))
826 
827 #define READ_ONCE(x)								\
828 ({										\
829 	union { __unqual_typeof(x) __val; char __c[1]; } __u =			\
830 		{ .__c = { 0 } };						\
831 	__read_once_size((__unqual_typeof(x) *)&(x), __u.__c, sizeof(x));	\
832 	__u.__val;								\
833 })
834 
835 #define WRITE_ONCE(x, val)							\
836 ({										\
837 	union { __unqual_typeof(x) __val; char __c[1]; } __u =			\
838 		{ .__val = (val) }; 						\
839 	__write_once_size((__unqual_typeof(x) *)&(x), __u.__c, sizeof(x));	\
840 	__u.__val;								\
841 })
842 
843 /*
844  * __calc_avg - Calculate exponential weighted moving average (EWMA) with
845  * @old and @new values. @decay represents how large the @old value remains.
846  * With a larger @decay value, the moving average changes slowly, exhibiting
847  * fewer fluctuations.
848  */
849 #define __calc_avg(old, new, decay) ({						\
850 	typeof(decay) thr = 1 << (decay);					\
851 	typeof(old) ret;							\
852 	if (((old) < thr) || ((new) < thr)) {					\
853 		if (((old) == 1) && ((new) == 0))				\
854 			ret = 0;						\
855 		else								\
856 			ret = ((old) - ((old) >> 1)) + ((new) >> 1);		\
857 	} else {								\
858 		ret = ((old) - ((old) >> (decay))) + ((new) >> (decay));	\
859 	}									\
860 	ret;									\
861 })
862 
863 /*
864  * log2_u32 - Compute the base 2 logarithm of a 32-bit exponential value.
865  * @v: The value for which we're computing the base 2 logarithm.
866  */
867 static inline u32 log2_u32(u32 v)
868 {
869         u32 r;
870         u32 shift;
871 
872         r = (v > 0xFFFF) << 4; v >>= r;
873         shift = (v > 0xFF) << 3; v >>= shift; r |= shift;
874         shift = (v > 0xF) << 2; v >>= shift; r |= shift;
875         shift = (v > 0x3) << 1; v >>= shift; r |= shift;
876         r |= (v >> 1);
877         return r;
878 }
879 
880 /*
881  * log2_u64 - Compute the base 2 logarithm of a 64-bit exponential value.
882  * @v: The value for which we're computing the base 2 logarithm.
883  */
884 static inline u32 log2_u64(u64 v)
885 {
886         u32 hi = v >> 32;
887         if (hi)
888                 return log2_u32(hi) + 32 + 1;
889         else
890                 return log2_u32(v) + 1;
891 }
892 
893 /*
894  * sqrt_u64 - Calculate the square root of value @x using Newton's method.
895  */
896 static inline u64 __sqrt_u64(u64 x)
897 {
898 	if (x == 0 || x == 1)
899 		return x;
900 
901 	u64 r = ((1ULL << 32) > x) ? x : (1ULL << 32);
902 
903 	for (int i = 0; i < 8; ++i) {
904 		u64 q = x / r;
905 		if (r <= q)
906 			break;
907 		r = (r + q) >> 1;
908 	}
909 	return r;
910 }
911 
912 /*
913  * ctzll -- Counts trailing zeros in an unsigned long long. If the input value
914  * is zero, the return value is undefined.
915  */
916 static inline int ctzll(u64 v)
917 {
918 #if (!defined(__BPF__) && defined(__SCX_TARGET_ARCH_x86)) || \
919 	(defined(__BPF__) && defined(__clang_major__) && __clang_major__ >= 19)
920 	/*
921 	 * Use the ctz builtin when: (1) building for native x86, or
922 	 * (2) building for BPF with clang >= 19 (BPF backend supports
923 	 * the intrinsic from clang 19 onward; earlier versions hit
924 	 * "unimplemented opcode" in the backend).
925 	 */
926 	return __builtin_ctzll(v);
927 #else
928 	/*
929 	 * If neither the target architecture nor the toolchains support ctzll,
930 	 * use software-based emulation. Let's use the De Bruijn sequence-based
931 	 * approach to find LSB fastly. See the details of De Bruijn sequence:
932 	 *
933 	 * https://en.wikipedia.org/wiki/De_Bruijn_sequence
934 	 * https://www.chessprogramming.org/BitScan#De_Bruijn_Multiplication
935 	 */
936 	const int lookup_table[64] = {
937 		 0,  1, 48,  2, 57, 49, 28,  3, 61, 58, 50, 42, 38, 29, 17,  4,
938 		62, 55, 59, 36, 53, 51, 43, 22, 45, 39, 33, 30, 24, 18, 12,  5,
939 		63, 47, 56, 27, 60, 41, 37, 16, 54, 35, 52, 21, 44, 32, 23, 11,
940 		46, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19,  9, 13,  8,  7,  6,
941 	};
942 	const u64 DEBRUIJN_CONSTANT = 0x03f79d71b4cb0a89ULL;
943 	unsigned int index;
944 	u64 lowest_bit;
945 	const int *lt;
946 
947 	if (v == 0)
948 		return -1;
949 
950 	/*
951 	 * Isolate the least significant bit (LSB).
952 	 * For example, if v = 0b...10100, then v & -v = 0b...00100
953 	 */
954 	lowest_bit = v & -v;
955 
956 	/*
957 	 * Each isolated bit produces a unique 6-bit value, guaranteed by the
958 	 * De Bruijn property. Calculate a unique index into the lookup table
959 	 * using the magic constant and a right shift.
960 	 *
961 	 * Multiplying by the 64-bit constant "spreads out" that 1-bit into a
962 	 * unique pattern in the top 6 bits. This uniqueness property is
963 	 * exactly what a De Bruijn sequence guarantees: Every possible 6-bit
964 	 * pattern (in top bits) occurs exactly once for each LSB position. So,
965 	 * the constant 0x03f79d71b4cb0a89ULL is carefully chosen to be a
966 	 * De Bruijn sequence, ensuring no collisions in the table index.
967 	 */
968 	index = (lowest_bit * DEBRUIJN_CONSTANT) >> 58;
969 
970 	/*
971 	 * Lookup in a precomputed table. No collision is guaranteed by the
972 	 * De Bruijn property.
973 	 */
974 	lt = MEMBER_VPTR(lookup_table, [index]);
975 	return (lt)? *lt : -1;
976 #endif
977 }
978 
979 /*
980  * Return a value proportionally scaled to the task's weight.
981  */
982 static inline u64 scale_by_task_weight(const struct task_struct *p, u64 value)
983 {
984 	return (value * p->scx.weight) / 100;
985 }
986 
987 /*
988  * Return a value inversely proportional to the task's weight.
989  */
990 static inline u64 scale_by_task_weight_inverse(const struct task_struct *p, u64 value)
991 {
992 	return value * 100 / p->scx.weight;
993 }
994 
995 
996 /*
997  * Get a random u64 from the kernel's pseudo-random generator.
998  */
999 static inline u64 get_prandom_u64()
1000 {
1001 	return ((u64)bpf_get_prandom_u32() << 32) | bpf_get_prandom_u32();
1002 }
1003 
1004 /*
1005  * Define the shadow structure to avoid a compilation error when
1006  * vmlinux.h does not enable necessary kernel configs. The ___local
1007  * suffix is a CO-RE convention that tells the loader to match this
1008  * against the base struct rq in the kernel. The attribute
1009  * preserve_access_index tells the compiler to generate a CO-RE
1010  * relocation for these fields.
1011  */
1012 struct rq___local {
1013 	/*
1014 	 * A monotonically increasing clock per CPU. It is rq->clock minus
1015 	 * cumulative IRQ time and hypervisor steal time. Unlike rq->clock,
1016 	 * it does not advance during IRQ processing or hypervisor preemption.
1017 	 * It does advance during idle (the idle task counts as a running task
1018 	 * for this purpose).
1019 	 */
1020 	u64		clock_task;
1021 	/*
1022 	 * Invariant version of clock_task scaled by CPU capacity and
1023 	 * frequency. For example, clock_pelt advances 2x slower on a CPU
1024 	 * with half the capacity.
1025 	 *
1026 	 * At idle exit, rq->clock_pelt jumps forward to resync with
1027 	 * clock_task. The kernel's rq_clock_pelt() corrects for this jump
1028 	 * by subtracting lost_idle_time, yielding a clock that appears
1029 	 * continuous across idle transitions. scx_clock_pelt() mirrors
1030 	 * rq_clock_pelt() by performing the same subtraction.
1031 	 */
1032 	u64		clock_pelt;
1033 	/*
1034 	 * Accumulates the magnitude of each clock_pelt jump at idle exit.
1035 	 * Subtracting this from clock_pelt gives rq_clock_pelt(): a
1036 	 * continuous, capacity-invariant clock suitable for both task
1037 	 * execution time stamping and cross-idle measurements.
1038 	 */
1039 	unsigned long	lost_idle_time;
1040 	/*
1041 	 * Shadow of paravirt_steal_clock() (the hypervisor's cumulative
1042 	 * stolen time counter). Stays frozen while the hypervisor preempts
1043 	 * the vCPU; catches up the next time update_rq_clock_task() is
1044 	 * called. The delta is the stolen time not yet subtracted from
1045 	 * clock_task.
1046 	 *
1047 	 * Unlike irqtime->total (a plain kernel-side field), the live stolen
1048 	 * time counter lives in hypervisor-specific shared memory and has no
1049 	 * kernel-side equivalent readable from BPF in a hypervisor-agnostic
1050 	 * way. This field is therefore the only portable BPF-accessible
1051 	 * approximation of cumulative steal time.
1052 	 *
1053 	 * Available only when CONFIG_PARAVIRT_TIME_ACCOUNTING is on.
1054 	 */
1055 	u64		prev_steal_time_rq;
1056 } __attribute__((preserve_access_index));
1057 
1058 extern struct rq runqueues __ksym;
1059 
1060 /*
1061  * Define the shadow structure to avoid a compilation error when
1062  * vmlinux.h does not enable necessary kernel configs.
1063  */
1064 struct irqtime___local {
1065 	/*
1066 	 * Cumulative IRQ time counter for this CPU, in nanoseconds. Advances
1067 	 * immediately at the exit of every hardirq and non-ksoftirqd softirq
1068 	 * via irqtime_account_irq(). ksoftirqd time is counted as normal
1069 	 * task time and is NOT included. NMI time is also NOT included.
1070 	 *
1071 	 * The companion field irqtime->sync (struct u64_stats_sync) protects
1072 	 * against 64-bit tearing on 32-bit architectures. On 64-bit kernels,
1073 	 * u64_stats_sync is an empty struct and all seqcount operations are
1074 	 * no-ops, so a plain BPF_CORE_READ of this field is safe.
1075 	 *
1076 	 * Available only when CONFIG_IRQ_TIME_ACCOUNTING is on.
1077 	 */
1078 	u64		total;
1079 } __attribute__((preserve_access_index));
1080 
1081 /*
1082  * cpu_irqtime is a per-CPU variable defined only when
1083  * CONFIG_IRQ_TIME_ACCOUNTING is on. Declare it as __weak so the BPF
1084  * loader sets its address to 0 (rather than failing) when the symbol
1085  * is absent from the running kernel.
1086  */
1087 extern struct irqtime___local cpu_irqtime __ksym __weak;
1088 
1089 static inline struct rq___local *get_current_rq(u32 cpu)
1090 {
1091 	/*
1092 	 * This is a workaround to get an rq pointer now that
1093 	 * scx_bpf_cpu_rq() has been removed.
1094 	 *
1095 	 * WARNING: The caller must hold the rq lock for @cpu. This is
1096 	 * guaranteed when called from scheduling callbacks (ops.running,
1097 	 * ops.stopping, ops.enqueue, ops.dequeue, ops.dispatch, etc.).
1098 	 * There is no runtime check available in BPF for kernel spinlock
1099 	 * state — correctness is enforced by calling context only.
1100 	 */
1101 	return (void *)bpf_per_cpu_ptr(&runqueues, cpu);
1102 }
1103 
1104 static inline u64 scx_clock_task(u32 cpu)
1105 {
1106 	struct rq___local *rq = get_current_rq(cpu);
1107 
1108 	/*
1109 	 * Equivalent to the kernel's rq_clock_task(): wall-clock time minus
1110 	 * cumulative IRQ time (CONFIG_IRQ_TIME_ACCOUNTING) and hypervisor
1111 	 * steal time (CONFIG_PARAVIRT_TIME_ACCOUNTING). Without those configs,
1112 	 * it equals rq->clock.
1113 	 *
1114 	 * Conceptually this clock advances during idle (the idle task counts
1115 	 * as a running task), but rq->clock_task is only updated on scheduling
1116 	 * events. With NO_HZ_IDLE (the default), the periodic tick is stopped
1117 	 * on idle CPUs, so rq->clock_task is not refreshed while a CPU is
1118 	 * idle. Reading this clock for a remote idle CPU from a BPF timer
1119 	 * callback returns the value from when the CPU last went idle, making
1120 	 * the delta over an idle interval effectively zero.
1121 	 */
1122 	return rq ? rq->clock_task : 0;
1123 }
1124 
1125 static inline u64 scx_clock_pelt(u32 cpu)
1126 {
1127 	struct rq___local *rq = get_current_rq(cpu);
1128 
1129 	/*
1130 	 * Equivalent to the kernel's rq_clock_pelt(): subtracts
1131 	 * lost_idle_time from clock_pelt to absorb the jump that occurs
1132 	 * when clock_pelt resyncs with clock_task at idle exit. The intent
1133 	 * is a continuous, capacity- and frequency-invariant clock that is
1134 	 * frozen during idle, IRQ, and hypervisor steal.
1135 	 *
1136 	 * However, like scx_clock_task(), this clock has a stale-read issue
1137 	 * for remote idle CPUs with NO_HZ_IDLE (the default). clock_pelt
1138 	 * itself advances at wall-clock rate (hardware-clock based), but
1139 	 * lost_idle_time is only updated via update_rq_clock_pelt(), which
1140 	 * requires update_rq_clock() to be called. With NO_HZ_IDLE, the
1141 	 * periodic tick is stopped on idle CPUs, so lost_idle_time is not
1142 	 * refreshed during idle. Reading this clock for a remote idle CPU
1143 	 * from a BPF timer callback therefore returns a value that drifts
1144 	 * at wall-clock rate -- the same stale behaviour as scx_clock_task().
1145 	 *
1146 	 * Without NO_HZ_IDLE, periodic ticks keep lost_idle_time nearly in
1147 	 * sync (stale by at most one tick period, ~1 ms), so the result is
1148 	 * accurate.
1149 	 */
1150 	return rq ? (rq->clock_pelt - rq->lost_idle_time) : 0;
1151 }
1152 
1153 static inline u64 scx_clock_virt(u32 cpu)
1154 {
1155 	struct rq___local *rq;
1156 
1157 	/*
1158 	 * Check field existence before calling get_current_rq() so we avoid
1159 	 * the per_cpu lookup entirely on kernels built without
1160 	 * CONFIG_PARAVIRT_TIME_ACCOUNTING.
1161 	 */
1162 	if (!bpf_core_field_exists(((struct rq___local *)0)->prev_steal_time_rq))
1163 		return 0;
1164 
1165 	/* Lagging shadow of the kernel's paravirt_steal_clock(). */
1166 	rq = get_current_rq(cpu);
1167 	return rq ? BPF_CORE_READ(rq, prev_steal_time_rq) : 0;
1168 }
1169 
1170 static inline u64 scx_clock_irq(u32 cpu)
1171 {
1172 	struct irqtime___local *irqt;
1173 
1174 	/*
1175 	 * bpf_core_type_exists() resolves at load time: if struct irqtime is
1176 	 * absent from kernel BTF (CONFIG_IRQ_TIME_ACCOUNTING off), the loader
1177 	 * patches this into an unconditional return 0, making the
1178 	 * bpf_per_cpu_ptr() call below dead code that the verifier never sees.
1179 	 */
1180 	if (!bpf_core_type_exists(struct irqtime___local))
1181 		return 0;
1182 
1183 	/* Equivalent to the kernel's irq_time_read(). */
1184 	irqt = bpf_per_cpu_ptr(&cpu_irqtime, cpu);
1185 	return irqt ? BPF_CORE_READ(irqt, total) : 0;
1186 }
1187 
1188 /* Abbreviated forms of <linux/overflow.h>'s struct_size() family. */
1189 #define flex_array_size(p, member, count)	\
1190 	((count) * sizeof(*(p)->member))
1191 
1192 #define struct_size(p, member, count)		\
1193 	(offsetof(typeof(*(p)), member) + flex_array_size(p, member, count))
1194 
1195 #define struct_size_t(type, member, count)	\
1196 	struct_size((type *)NULL, member, count)
1197 
1198 /*
1199  * <linux/stddef.h>'s TRAILING_OVERLAP(): embed a struct that ends in a flexible
1200  * array member together with its storage. @NAME is a complete @TYPE and the
1201  * @MEMBERS declared after the array reserve the space the array grows into.
1202  * Unlike the kernel's, the padding is named after @NAME so that one struct can
1203  * embed several, and it is sized with __builtin_offsetof() because
1204  * bpf_helpers.h redefines offsetof() as a pointer cast, which is not a constant
1205  * expression.
1206  */
1207 #define __TRAILING_OVERLAP(TYPE, NAME, FAM, ATTRS, MEMBERS)			\
1208 	union {									\
1209 		TYPE NAME;							\
1210 		struct {							\
1211 			unsigned char __offset_to_##NAME[__builtin_offsetof(TYPE, FAM)]; \
1212 			MEMBERS							\
1213 		} ATTRS;							\
1214 	}
1215 
1216 #define TRAILING_OVERLAP(TYPE, NAME, FAM, MEMBERS)				\
1217 	__TRAILING_OVERLAP(TYPE, NAME, FAM, /* no attrs */, MEMBERS)
1218 
1219 /*
1220  * Loop counters the verifier cannot see through.
1221  *
1222  * A may_goto loop converges when the state at its head is within the state
1223  * of a previous iteration. A counter tracked as a precise constant prevents
1224  * that convergence: every iteration creates a new state, and the verifier
1225  * unrolls the loop until it runs out of budget whenever the counter feeds an
1226  * operation that requires precision.
1227  *
1228  * Loading a writable global gives the verifier an unknown scalar while its
1229  * runtime value remains one. Using it as the step makes the counter unknown
1230  * after the first iteration, and the load on every increment keeps the loop
1231  * body from making it precise again. volatile is required to keep the compiler
1232  * from hoisting or eliminating the loads, and the value must remain non-const
1233  * so the verifier cannot resolve it. The variable is weak so the objects linked
1234  * into a scheduler share one copy. Its runtime value must never be changed from
1235  * one.
1236  *
1237  * bpf_for() avoids this verifier behavior too, but calls bpf_iter_num_next()
1238  * on every iteration. bpf_arena_for() is intended for hot scheduler walks
1239  * where that cost matters. @var must be no wider than u32, and @start and
1240  * @end must be representable as u32.
1241  */
1242 volatile u32 bpf_arena_loop_one __weak = 1;
1243 
1244 /*
1245  * A loop-carried accumulator that a caller later compares is kept precise, and
1246  * a precise scalar whose range grows every iteration keeps a may_goto loop from
1247  * converging. Initializing it from this zero makes it unknown from the first
1248  * iteration, so every pass through the loop head looks the same.
1249  */
1250 volatile u32 bpf_arena_loop_zero __weak = 0;
1251 
1252 #define __bpf_arena_loop_start(var, start)				\
1253 	({								\
1254 		_Static_assert(sizeof(var) <= sizeof(u32),		\
1255 			       "bpf_arena_for() index must fit in u32");	\
1256 		(start);						\
1257 	})
1258 
1259 #define bpf_arena_for(var, start, end)					\
1260 	for (var = __bpf_arena_loop_start(var, start);			\
1261 	     var < (end) && can_loop;					\
1262 	     var += bpf_arena_loop_one)
1263 
1264 #include "compat.bpf.h"
1265 #include "enums.bpf.h"
1266 #include "features.bpf.h"
1267 #include "cid.bpf.h"
1268 
1269 #endif	/* __SCX_COMMON_BPF_H */
1270