xref: /linux/tools/sched_ext/include/scx/common.bpf.h (revision cded46d971597ecfe505ba92a54253c0f5e1f2e4)
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 
30 #define PF_IDLE				0x00000002	/* I am an IDLE thread */
31 #define PF_IO_WORKER			0x00000010	/* Task is an IO worker */
32 #define PF_WQ_WORKER			0x00000020	/* I'm a workqueue worker */
33 #define PF_KCOMPACTD			0x00010000      /* I am kcompactd */
34 #define PF_KSWAPD			0x00020000      /* I am kswapd */
35 #define PF_KTHREAD			0x00200000	/* I am a kernel thread */
36 #define PF_EXITING			0x00000004
37 #define CLOCK_MONOTONIC			1
38 
39 #ifndef NR_CPUS
40 #define NR_CPUS 1024
41 #endif
42 
43 #ifndef NUMA_NO_NODE
44 #define	NUMA_NO_NODE	(-1)
45 #endif
46 
47 extern int LINUX_KERNEL_VERSION __kconfig;
48 extern const char CONFIG_CC_VERSION_TEXT[64] __kconfig __weak;
49 extern const char CONFIG_LOCALVERSION[64] __kconfig __weak;
50 
51 /*
52  * Earlier versions of clang/pahole lost upper 32bits in 64bit enums which can
53  * lead to really confusing misbehaviors. Let's trigger a build failure.
54  */
55 static inline void ___vmlinux_h_sanity_check___(void)
56 {
57 	_Static_assert(SCX_DSQ_FLAG_BUILTIN,
58 		       "bpftool generated vmlinux.h is missing high bits for 64bit enums, upgrade clang and pahole");
59 }
60 
61 s32 scx_bpf_create_dsq(u64 dsq_id, s32 node) __ksym;
62 s32 scx_bpf_select_cpu_dfl(struct task_struct *p, s32 prev_cpu, u64 wake_flags, bool *is_idle) __ksym;
63 s32 __scx_bpf_select_cpu_and(struct task_struct *p, const struct cpumask *cpus_allowed,
64 			     struct scx_bpf_select_cpu_and_args *args) __ksym __weak;
65 bool __scx_bpf_dsq_insert_vtime(struct task_struct *p, struct scx_bpf_dsq_insert_vtime_args *args) __ksym __weak;
66 u32 scx_bpf_dispatch_nr_slots(void) __ksym;
67 void scx_bpf_dispatch_cancel(void) __ksym;
68 bool scx_bpf_dsq_move_to_local(u64 dsq_id) __ksym __weak;
69 void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter, u64 slice) __ksym __weak;
70 void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter, u64 vtime) __ksym __weak;
71 bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter, struct task_struct *p, u64 dsq_id, u64 enq_flags) __ksym __weak;
72 bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter, struct task_struct *p, u64 dsq_id, u64 enq_flags) __ksym __weak;
73 u32 scx_bpf_reenqueue_local(void) __ksym;
74 void scx_bpf_kick_cpu(s32 cpu, u64 flags) __ksym;
75 s32 scx_bpf_dsq_nr_queued(u64 dsq_id) __ksym;
76 void scx_bpf_destroy_dsq(u64 dsq_id) __ksym;
77 int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id, u64 flags) __ksym __weak;
78 struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it) __ksym __weak;
79 void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it) __ksym __weak;
80 void scx_bpf_exit_bstr(s64 exit_code, char *fmt, unsigned long long *data, u32 data__sz) __ksym __weak;
81 void scx_bpf_error_bstr(char *fmt, unsigned long long *data, u32 data_len) __ksym;
82 void scx_bpf_dump_bstr(char *fmt, unsigned long long *data, u32 data_len) __ksym __weak;
83 u32 scx_bpf_cpuperf_cap(s32 cpu) __ksym __weak;
84 u32 scx_bpf_cpuperf_cur(s32 cpu) __ksym __weak;
85 void scx_bpf_cpuperf_set(s32 cpu, u32 perf) __ksym __weak;
86 u32 scx_bpf_nr_node_ids(void) __ksym __weak;
87 u32 scx_bpf_nr_cpu_ids(void) __ksym __weak;
88 int scx_bpf_cpu_node(s32 cpu) __ksym __weak;
89 const struct cpumask *scx_bpf_get_possible_cpumask(void) __ksym __weak;
90 const struct cpumask *scx_bpf_get_online_cpumask(void) __ksym __weak;
91 void scx_bpf_put_cpumask(const struct cpumask *cpumask) __ksym __weak;
92 const struct cpumask *scx_bpf_get_idle_cpumask_node(int node) __ksym __weak;
93 const struct cpumask *scx_bpf_get_idle_cpumask(void) __ksym;
94 const struct cpumask *scx_bpf_get_idle_smtmask_node(int node) __ksym __weak;
95 const struct cpumask *scx_bpf_get_idle_smtmask(void) __ksym;
96 void scx_bpf_put_idle_cpumask(const struct cpumask *cpumask) __ksym;
97 bool scx_bpf_test_and_clear_cpu_idle(s32 cpu) __ksym;
98 s32 scx_bpf_pick_idle_cpu_node(const cpumask_t *cpus_allowed, int node, u64 flags) __ksym __weak;
99 s32 scx_bpf_pick_idle_cpu(const cpumask_t *cpus_allowed, u64 flags) __ksym;
100 s32 scx_bpf_pick_any_cpu_node(const cpumask_t *cpus_allowed, int node, u64 flags) __ksym __weak;
101 s32 scx_bpf_pick_any_cpu(const cpumask_t *cpus_allowed, u64 flags) __ksym;
102 bool scx_bpf_task_running(const struct task_struct *p) __ksym;
103 s32 scx_bpf_task_cpu(const struct task_struct *p) __ksym;
104 bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice) __ksym __weak;
105 bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime) __ksym __weak;
106 struct rq *scx_bpf_cpu_rq(s32 cpu) __ksym;
107 struct rq *scx_bpf_locked_rq(void) __ksym;
108 struct task_struct *scx_bpf_cpu_curr(s32 cpu) __ksym __weak;
109 struct cgroup *scx_bpf_task_cgroup(struct task_struct *p) __ksym __weak;
110 u64 scx_bpf_now(void) __ksym __weak;
111 void scx_bpf_events(struct scx_event_stats *events, size_t events__sz) __ksym __weak;
112 
113 /*
114  * Use the following as @it__iter when calling scx_bpf_dsq_move[_vtime]() from
115  * within bpf_for_each() loops.
116  */
117 #define BPF_FOR_EACH_ITER	(&___it)
118 
119 #define scx_read_event(e, name)							\
120 	(bpf_core_field_exists((e)->name) ? (e)->name : 0)
121 
122 static inline __attribute__((format(printf, 1, 2)))
123 void ___scx_bpf_bstr_format_checker(const char *fmt, ...) {}
124 
125 #define SCX_STRINGIFY(x) #x
126 #define SCX_TOSTRING(x) SCX_STRINGIFY(x)
127 
128 /*
129  * Helper macro for initializing the fmt and variadic argument inputs to both
130  * bstr exit kfuncs. Callers to this function should use ___fmt and ___param to
131  * refer to the initialized list of inputs to the bstr kfunc.
132  */
133 #define scx_bpf_bstr_preamble(fmt, args...)					\
134 	static char ___fmt[] = fmt;						\
135 	/*									\
136 	 * Note that __param[] must have at least one				\
137 	 * element to keep the verifier happy.					\
138 	 */									\
139 	unsigned long long ___param[___bpf_narg(args) ?: 1] = {};		\
140 										\
141 	_Pragma("GCC diagnostic push")						\
142 	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")			\
143 	___bpf_fill(___param, args);						\
144 	_Pragma("GCC diagnostic pop")
145 
146 /*
147  * scx_bpf_exit() wraps the scx_bpf_exit_bstr() kfunc with variadic arguments
148  * instead of an array of u64. Using this macro will cause the scheduler to
149  * exit cleanly with the specified exit code being passed to user space.
150  */
151 #define scx_bpf_exit(code, fmt, args...)					\
152 ({										\
153 	scx_bpf_bstr_preamble(fmt, args)					\
154 	scx_bpf_exit_bstr(code, ___fmt, ___param, sizeof(___param));		\
155 	___scx_bpf_bstr_format_checker(fmt, ##args);				\
156 })
157 
158 /*
159  * scx_bpf_error() wraps the scx_bpf_error_bstr() kfunc with variadic arguments
160  * instead of an array of u64. Invoking this macro will cause the scheduler to
161  * exit in an erroneous state, with diagnostic information being passed to the
162  * user. It appends the file and line number to aid debugging.
163  */
164 #define scx_bpf_error(fmt, args...)						\
165 ({										\
166 	scx_bpf_bstr_preamble(							\
167 		__FILE__ ":" SCX_TOSTRING(__LINE__) ": " fmt, ##args)		\
168 	scx_bpf_error_bstr(___fmt, ___param, sizeof(___param));			\
169 	___scx_bpf_bstr_format_checker(						\
170 		__FILE__ ":" SCX_TOSTRING(__LINE__) ": " fmt, ##args);		\
171 })
172 
173 /*
174  * scx_bpf_dump() wraps the scx_bpf_dump_bstr() kfunc with variadic arguments
175  * instead of an array of u64. To be used from ops.dump() and friends.
176  */
177 #define scx_bpf_dump(fmt, args...)						\
178 ({										\
179 	scx_bpf_bstr_preamble(fmt, args)					\
180 	scx_bpf_dump_bstr(___fmt, ___param, sizeof(___param));			\
181 	___scx_bpf_bstr_format_checker(fmt, ##args);				\
182 })
183 
184 /*
185  * scx_bpf_dump_header() is a wrapper around scx_bpf_dump that adds a header
186  * of system information for debugging.
187  */
188 #define scx_bpf_dump_header()							\
189 ({										\
190 	scx_bpf_dump("kernel: %d.%d.%d %s\ncc: %s\n",				\
191 		     LINUX_KERNEL_VERSION >> 16,				\
192 		     LINUX_KERNEL_VERSION >> 8 & 0xFF,				\
193 		     LINUX_KERNEL_VERSION & 0xFF,				\
194 		     CONFIG_LOCALVERSION,					\
195 		     CONFIG_CC_VERSION_TEXT);					\
196 })
197 
198 #define BPF_STRUCT_OPS(name, args...)						\
199 SEC("struct_ops/"#name)								\
200 BPF_PROG(name, ##args)
201 
202 #define BPF_STRUCT_OPS_SLEEPABLE(name, args...)					\
203 SEC("struct_ops.s/"#name)							\
204 BPF_PROG(name, ##args)
205 
206 /**
207  * RESIZABLE_ARRAY - Generates annotations for an array that may be resized
208  * @elfsec: the data section of the BPF program in which to place the array
209  * @arr: the name of the array
210  *
211  * libbpf has an API for setting map value sizes. Since data sections (i.e.
212  * bss, data, rodata) themselves are maps, a data section can be resized. If
213  * a data section has an array as its last element, the BTF info for that
214  * array will be adjusted so that length of the array is extended to meet the
215  * new length of the data section. This macro annotates an array to have an
216  * element count of one with the assumption that this array can be resized
217  * within the userspace program. It also annotates the section specifier so
218  * this array exists in a custom sub data section which can be resized
219  * independently.
220  *
221  * See RESIZE_ARRAY() for the userspace convenience macro for resizing an
222  * array declared with RESIZABLE_ARRAY().
223  */
224 #define RESIZABLE_ARRAY(elfsec, arr) arr[1] SEC("."#elfsec"."#arr)
225 
226 /**
227  * MEMBER_VPTR - Obtain the verified pointer to a struct or array member
228  * @base: struct or array to index
229  * @member: dereferenced member (e.g. .field, [idx0][idx1], .field[idx0] ...)
230  *
231  * The verifier often gets confused by the instruction sequence the compiler
232  * generates for indexing struct fields or arrays. This macro forces the
233  * compiler to generate a code sequence which first calculates the byte offset,
234  * checks it against the struct or array size and add that byte offset to
235  * generate the pointer to the member to help the verifier.
236  *
237  * Ideally, we want to abort if the calculated offset is out-of-bounds. However,
238  * BPF currently doesn't support abort, so evaluate to %NULL instead. The caller
239  * must check for %NULL and take appropriate action to appease the verifier. To
240  * avoid confusing the verifier, it's best to check for %NULL and dereference
241  * immediately.
242  *
243  *	vptr = MEMBER_VPTR(my_array, [i][j]);
244  *	if (!vptr)
245  *		return error;
246  *	*vptr = new_value;
247  *
248  * sizeof(@base) should encompass the memory area to be accessed and thus can't
249  * be a pointer to the area. Use `MEMBER_VPTR(*ptr, .member)` instead of
250  * `MEMBER_VPTR(ptr, ->member)`.
251  */
252 #ifndef MEMBER_VPTR
253 #define MEMBER_VPTR(base, member) (typeof((base) member) *)			\
254 ({										\
255 	u64 __base = (u64)&(base);						\
256 	u64 __addr = (u64)&((base) member) - __base;				\
257 	_Static_assert(sizeof(base) >= sizeof((base) member),			\
258 		       "@base is smaller than @member, is @base a pointer?");	\
259 	asm volatile (								\
260 		"if %0 <= %[max] goto +2\n"					\
261 		"%0 = 0\n"							\
262 		"goto +1\n"							\
263 		"%0 += %1\n"							\
264 		: "+r"(__addr)							\
265 		: "r"(__base),							\
266 		  [max]"i"(sizeof(base) - sizeof((base) member)));		\
267 	__addr;									\
268 })
269 #endif /* MEMBER_VPTR */
270 
271 /**
272  * ARRAY_ELEM_PTR - Obtain the verified pointer to an array element
273  * @arr: array to index into
274  * @i: array index
275  * @n: number of elements in array
276  *
277  * Similar to MEMBER_VPTR() but is intended for use with arrays where the
278  * element count needs to be explicit.
279  * It can be used in cases where a global array is defined with an initial
280  * size but is intended to be be resized before loading the BPF program.
281  * Without this version of the macro, MEMBER_VPTR() will use the compile time
282  * size of the array to compute the max, which will result in rejection by
283  * the verifier.
284  */
285 #ifndef ARRAY_ELEM_PTR
286 #define ARRAY_ELEM_PTR(arr, i, n) (typeof(arr[i]) *)				\
287 ({										\
288 	u64 __base = (u64)arr;							\
289 	u64 __addr = (u64)&(arr[i]) - __base;					\
290 	asm volatile (								\
291 		"if %0 <= %[max] goto +2\n"					\
292 		"%0 = 0\n"							\
293 		"goto +1\n"							\
294 		"%0 += %1\n"							\
295 		: "+r"(__addr)							\
296 		: "r"(__base),							\
297 		  [max]"r"(sizeof(arr[0]) * ((n) - 1)));			\
298 	__addr;									\
299 })
300 #endif /* ARRAY_ELEM_PTR */
301 
302 /*
303  * BPF declarations and helpers
304  */
305 
306 /* list and rbtree */
307 #define __contains(name, node) __attribute__((btf_decl_tag("contains:" #name ":" #node)))
308 #define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
309 
310 void *bpf_obj_new_impl(__u64 local_type_id, void *meta) __ksym;
311 void bpf_obj_drop_impl(void *kptr, void *meta) __ksym;
312 
313 #define bpf_obj_new(type) ((type *)bpf_obj_new_impl(bpf_core_type_id_local(type), NULL))
314 #define bpf_obj_drop(kptr) bpf_obj_drop_impl(kptr, NULL)
315 
316 int bpf_list_push_front_impl(struct bpf_list_head *head,
317 				    struct bpf_list_node *node,
318 				    void *meta, __u64 off) __ksym;
319 #define bpf_list_push_front(head, node) bpf_list_push_front_impl(head, node, NULL, 0)
320 
321 int bpf_list_push_back_impl(struct bpf_list_head *head,
322 				   struct bpf_list_node *node,
323 				   void *meta, __u64 off) __ksym;
324 #define bpf_list_push_back(head, node) bpf_list_push_back_impl(head, node, NULL, 0)
325 
326 struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head) __ksym;
327 struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head) __ksym;
328 struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
329 				      struct bpf_rb_node *node) __ksym;
330 int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
331 			bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
332 			void *meta, __u64 off) __ksym;
333 #define bpf_rbtree_add(head, node, less) bpf_rbtree_add_impl(head, node, less, NULL, 0)
334 
335 struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root) __ksym;
336 
337 void *bpf_refcount_acquire_impl(void *kptr, void *meta) __ksym;
338 #define bpf_refcount_acquire(kptr) bpf_refcount_acquire_impl(kptr, NULL)
339 
340 /* task */
341 struct task_struct *bpf_task_from_pid(s32 pid) __ksym;
342 struct task_struct *bpf_task_acquire(struct task_struct *p) __ksym;
343 void bpf_task_release(struct task_struct *p) __ksym;
344 
345 /* cgroup */
346 struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level) __ksym;
347 void bpf_cgroup_release(struct cgroup *cgrp) __ksym;
348 struct cgroup *bpf_cgroup_from_id(u64 cgid) __ksym;
349 
350 /* css iteration */
351 struct bpf_iter_css;
352 struct cgroup_subsys_state;
353 extern int bpf_iter_css_new(struct bpf_iter_css *it,
354 			    struct cgroup_subsys_state *start,
355 			    unsigned int flags) __weak __ksym;
356 extern struct cgroup_subsys_state *
357 bpf_iter_css_next(struct bpf_iter_css *it) __weak __ksym;
358 extern void bpf_iter_css_destroy(struct bpf_iter_css *it) __weak __ksym;
359 
360 /* cpumask */
361 struct bpf_cpumask *bpf_cpumask_create(void) __ksym;
362 struct bpf_cpumask *bpf_cpumask_acquire(struct bpf_cpumask *cpumask) __ksym;
363 void bpf_cpumask_release(struct bpf_cpumask *cpumask) __ksym;
364 u32 bpf_cpumask_first(const struct cpumask *cpumask) __ksym;
365 u32 bpf_cpumask_first_zero(const struct cpumask *cpumask) __ksym;
366 void bpf_cpumask_set_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;
367 void bpf_cpumask_clear_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;
368 bool bpf_cpumask_test_cpu(u32 cpu, const struct cpumask *cpumask) __ksym;
369 bool bpf_cpumask_test_and_set_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;
370 bool bpf_cpumask_test_and_clear_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;
371 void bpf_cpumask_setall(struct bpf_cpumask *cpumask) __ksym;
372 void bpf_cpumask_clear(struct bpf_cpumask *cpumask) __ksym;
373 bool bpf_cpumask_and(struct bpf_cpumask *dst, const struct cpumask *src1,
374 		     const struct cpumask *src2) __ksym;
375 void bpf_cpumask_or(struct bpf_cpumask *dst, const struct cpumask *src1,
376 		    const struct cpumask *src2) __ksym;
377 void bpf_cpumask_xor(struct bpf_cpumask *dst, const struct cpumask *src1,
378 		     const struct cpumask *src2) __ksym;
379 bool bpf_cpumask_equal(const struct cpumask *src1, const struct cpumask *src2) __ksym;
380 bool bpf_cpumask_intersects(const struct cpumask *src1, const struct cpumask *src2) __ksym;
381 bool bpf_cpumask_subset(const struct cpumask *src1, const struct cpumask *src2) __ksym;
382 bool bpf_cpumask_empty(const struct cpumask *cpumask) __ksym;
383 bool bpf_cpumask_full(const struct cpumask *cpumask) __ksym;
384 void bpf_cpumask_copy(struct bpf_cpumask *dst, const struct cpumask *src) __ksym;
385 u32 bpf_cpumask_any_distribute(const struct cpumask *cpumask) __ksym;
386 u32 bpf_cpumask_any_and_distribute(const struct cpumask *src1,
387 				   const struct cpumask *src2) __ksym;
388 u32 bpf_cpumask_weight(const struct cpumask *cpumask) __ksym;
389 
390 int bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_words) __ksym;
391 int *bpf_iter_bits_next(struct bpf_iter_bits *it) __ksym;
392 void bpf_iter_bits_destroy(struct bpf_iter_bits *it) __ksym;
393 
394 #define def_iter_struct(name)							\
395 struct bpf_iter_##name {							\
396     struct bpf_iter_bits it;							\
397     const struct cpumask *bitmap;						\
398 };
399 
400 #define def_iter_new(name)							\
401 static inline int bpf_iter_##name##_new(					\
402 	struct bpf_iter_##name *it, const u64 *unsafe_ptr__ign, u32 nr_words)	\
403 {										\
404 	it->bitmap = scx_bpf_get_##name##_cpumask();				\
405 	return bpf_iter_bits_new(&it->it, (const u64 *)it->bitmap,		\
406 				 sizeof(struct cpumask) / 8);			\
407 }
408 
409 #define def_iter_next(name)							\
410 static inline int *bpf_iter_##name##_next(struct bpf_iter_##name *it) {		\
411 	return bpf_iter_bits_next(&it->it);					\
412 }
413 
414 #define def_iter_destroy(name)							\
415 static inline void bpf_iter_##name##_destroy(struct bpf_iter_##name *it) {	\
416 	scx_bpf_put_cpumask(it->bitmap);					\
417 	bpf_iter_bits_destroy(&it->it);						\
418 }
419 #define def_for_each_cpu(cpu, name) for_each_##name##_cpu(cpu)
420 
421 /// Provides iterator for possible and online cpus.
422 ///
423 /// # Example
424 ///
425 /// ```
426 /// static inline void example_use() {
427 ///     int *cpu;
428 ///
429 ///     for_each_possible_cpu(cpu){
430 ///         bpf_printk("CPU %d is possible", *cpu);
431 ///     }
432 ///
433 ///     for_each_online_cpu(cpu){
434 ///         bpf_printk("CPU %d is online", *cpu);
435 ///     }
436 /// }
437 /// ```
438 def_iter_struct(possible);
439 def_iter_new(possible);
440 def_iter_next(possible);
441 def_iter_destroy(possible);
442 #define for_each_possible_cpu(cpu) bpf_for_each(possible, cpu, NULL, 0)
443 
444 def_iter_struct(online);
445 def_iter_new(online);
446 def_iter_next(online);
447 def_iter_destroy(online);
448 #define for_each_online_cpu(cpu) bpf_for_each(online, cpu, NULL, 0)
449 
450 /*
451  * Access a cpumask in read-only mode (typically to check bits).
452  */
453 static __always_inline const struct cpumask *cast_mask(struct bpf_cpumask *mask)
454 {
455 	return (const struct cpumask *)mask;
456 }
457 
458 /*
459  * Return true if task @p cannot migrate to a different CPU, false
460  * otherwise.
461  */
462 static inline bool is_migration_disabled(const struct task_struct *p)
463 {
464 	/*
465 	 * Testing p->migration_disabled in a BPF code is tricky because the
466 	 * migration is _always_ disabled while running the BPF code.
467 	 * The prolog (__bpf_prog_enter) and epilog (__bpf_prog_exit) for BPF
468 	 * code execution disable and re-enable the migration of the current
469 	 * task, respectively. So, the _current_ task of the sched_ext ops is
470 	 * always migration-disabled. Moreover, p->migration_disabled could be
471 	 * two or greater when a sched_ext ops BPF code (e.g., ops.tick) is
472 	 * executed in the middle of the other BPF code execution.
473 	 *
474 	 * Therefore, we should decide that the _current_ task is
475 	 * migration-disabled only when its migration_disabled count is greater
476 	 * than one. In other words, when  p->migration_disabled == 1, there is
477 	 * an ambiguity, so we should check if @p is the current task or not.
478 	 */
479 	if (bpf_core_field_exists(p->migration_disabled)) {
480 		if (p->migration_disabled == 1)
481 			return bpf_get_current_task_btf() != p;
482 		else
483 			return p->migration_disabled;
484 	}
485 	return false;
486 }
487 
488 /* rcu */
489 void bpf_rcu_read_lock(void) __ksym;
490 void bpf_rcu_read_unlock(void) __ksym;
491 
492 /*
493  * Time helpers, most of which are from jiffies.h.
494  */
495 
496 /**
497  * time_delta - Calculate the delta between new and old time stamp
498  * @after: first comparable as u64
499  * @before: second comparable as u64
500  *
501  * Return: the time difference, which is >= 0
502  */
503 static inline s64 time_delta(u64 after, u64 before)
504 {
505 	return (s64)(after - before) > 0 ? (s64)(after - before) : 0;
506 }
507 
508 /**
509  * time_after - returns true if the time a is after time b.
510  * @a: first comparable as u64
511  * @b: second comparable as u64
512  *
513  * Do this with "<0" and ">=0" to only test the sign of the result. A
514  * good compiler would generate better code (and a really good compiler
515  * wouldn't care). Gcc is currently neither.
516  *
517  * Return: %true is time a is after time b, otherwise %false.
518  */
519 static inline bool time_after(u64 a, u64 b)
520 {
521 	return (s64)(b - a) < 0;
522 }
523 
524 /**
525  * time_before - returns true if the time a is before time b.
526  * @a: first comparable as u64
527  * @b: second comparable as u64
528  *
529  * Return: %true is time a is before time b, otherwise %false.
530  */
531 static inline bool time_before(u64 a, u64 b)
532 {
533 	return time_after(b, a);
534 }
535 
536 /**
537  * time_after_eq - returns true if the time a is after or the same as time b.
538  * @a: first comparable as u64
539  * @b: second comparable as u64
540  *
541  * Return: %true is time a is after or the same as time b, otherwise %false.
542  */
543 static inline bool time_after_eq(u64 a, u64 b)
544 {
545 	return (s64)(a - b) >= 0;
546 }
547 
548 /**
549  * time_before_eq - returns true if the time a is before or the same as time b.
550  * @a: first comparable as u64
551  * @b: second comparable as u64
552  *
553  * Return: %true is time a is before or the same as time b, otherwise %false.
554  */
555 static inline bool time_before_eq(u64 a, u64 b)
556 {
557 	return time_after_eq(b, a);
558 }
559 
560 /**
561  * time_in_range - Calculate whether a is in the range of [b, c].
562  * @a: time to test
563  * @b: beginning of the range
564  * @c: end of the range
565  *
566  * Return: %true is time a is in the range [b, c], otherwise %false.
567  */
568 static inline bool time_in_range(u64 a, u64 b, u64 c)
569 {
570 	return time_after_eq(a, b) && time_before_eq(a, c);
571 }
572 
573 /**
574  * time_in_range_open - Calculate whether a is in the range of [b, c).
575  * @a: time to test
576  * @b: beginning of the range
577  * @c: end of the range
578  *
579  * Return: %true is time a is in the range [b, c), otherwise %false.
580  */
581 static inline bool time_in_range_open(u64 a, u64 b, u64 c)
582 {
583 	return time_after_eq(a, b) && time_before(a, c);
584 }
585 
586 
587 /*
588  * Other helpers
589  */
590 
591 /* useful compiler attributes */
592 #ifndef likely
593 #define likely(x) __builtin_expect(!!(x), 1)
594 #endif
595 #ifndef unlikely
596 #define unlikely(x) __builtin_expect(!!(x), 0)
597 #endif
598 #ifndef __maybe_unused
599 #define __maybe_unused __attribute__((__unused__))
600 #endif
601 
602 /*
603  * READ/WRITE_ONCE() are from kernel (include/asm-generic/rwonce.h). They
604  * prevent compiler from caching, redoing or reordering reads or writes.
605  */
606 typedef __u8  __attribute__((__may_alias__))  __u8_alias_t;
607 typedef __u16 __attribute__((__may_alias__)) __u16_alias_t;
608 typedef __u32 __attribute__((__may_alias__)) __u32_alias_t;
609 typedef __u64 __attribute__((__may_alias__)) __u64_alias_t;
610 
611 static __always_inline void __read_once_size(const volatile void *p, void *res, int size)
612 {
613 	switch (size) {
614 	case 1: *(__u8_alias_t  *) res = *(volatile __u8_alias_t  *) p; break;
615 	case 2: *(__u16_alias_t *) res = *(volatile __u16_alias_t *) p; break;
616 	case 4: *(__u32_alias_t *) res = *(volatile __u32_alias_t *) p; break;
617 	case 8: *(__u64_alias_t *) res = *(volatile __u64_alias_t *) p; break;
618 	default:
619 		barrier();
620 		__builtin_memcpy((void *)res, (const void *)p, size);
621 		barrier();
622 	}
623 }
624 
625 static __always_inline void __write_once_size(volatile void *p, void *res, int size)
626 {
627 	switch (size) {
628 	case 1: *(volatile  __u8_alias_t *) p = *(__u8_alias_t  *) res; break;
629 	case 2: *(volatile __u16_alias_t *) p = *(__u16_alias_t *) res; break;
630 	case 4: *(volatile __u32_alias_t *) p = *(__u32_alias_t *) res; break;
631 	case 8: *(volatile __u64_alias_t *) p = *(__u64_alias_t *) res; break;
632 	default:
633 		barrier();
634 		__builtin_memcpy((void *)p, (const void *)res, size);
635 		barrier();
636 	}
637 }
638 
639 /*
640  * __unqual_typeof(x) - Declare an unqualified scalar type, leaving
641  *			non-scalar types unchanged,
642  *
643  * Prefer C11 _Generic for better compile-times and simpler code. Note: 'char'
644  * is not type-compatible with 'signed char', and we define a separate case.
645  *
646  * This is copied verbatim from kernel's include/linux/compiler_types.h, but
647  * with default expression (for pointers) changed from (x) to (typeof(x)0).
648  *
649  * This is because LLVM has a bug where for lvalue (x), it does not get rid of
650  * an extra address_space qualifier, but does in case of rvalue (typeof(x)0).
651  * Hence, for pointers, we need to create an rvalue expression to get the
652  * desired type. See https://github.com/llvm/llvm-project/issues/53400.
653  */
654 #define __scalar_type_to_expr_cases(type) \
655 	unsigned type : (unsigned type)0, signed type : (signed type)0
656 
657 #define __unqual_typeof(x)                              \
658 	typeof(_Generic((x),                            \
659 		char: (char)0,                          \
660 		__scalar_type_to_expr_cases(char),      \
661 		__scalar_type_to_expr_cases(short),     \
662 		__scalar_type_to_expr_cases(int),       \
663 		__scalar_type_to_expr_cases(long),      \
664 		__scalar_type_to_expr_cases(long long), \
665 		default: (typeof(x))0))
666 
667 #define READ_ONCE(x)								\
668 ({										\
669 	union { __unqual_typeof(x) __val; char __c[1]; } __u =			\
670 		{ .__c = { 0 } };						\
671 	__read_once_size((__unqual_typeof(x) *)&(x), __u.__c, sizeof(x));	\
672 	__u.__val;								\
673 })
674 
675 #define WRITE_ONCE(x, val)							\
676 ({										\
677 	union { __unqual_typeof(x) __val; char __c[1]; } __u =			\
678 		{ .__val = (val) }; 						\
679 	__write_once_size((__unqual_typeof(x) *)&(x), __u.__c, sizeof(x));	\
680 	__u.__val;								\
681 })
682 
683 /*
684  * __calc_avg - Calculate exponential weighted moving average (EWMA) with
685  * @old and @new values. @decay represents how large the @old value remains.
686  * With a larger @decay value, the moving average changes slowly, exhibiting
687  * fewer fluctuations.
688  */
689 #define __calc_avg(old, new, decay) ({						\
690 	typeof(decay) thr = 1 << (decay);					\
691 	typeof(old) ret;							\
692 	if (((old) < thr) || ((new) < thr)) {					\
693 		if (((old) == 1) && ((new) == 0))				\
694 			ret = 0;						\
695 		else								\
696 			ret = ((old) - ((old) >> 1)) + ((new) >> 1);		\
697 	} else {								\
698 		ret = ((old) - ((old) >> (decay))) + ((new) >> (decay));	\
699 	}									\
700 	ret;									\
701 })
702 
703 /*
704  * log2_u32 - Compute the base 2 logarithm of a 32-bit exponential value.
705  * @v: The value for which we're computing the base 2 logarithm.
706  */
707 static inline u32 log2_u32(u32 v)
708 {
709         u32 r;
710         u32 shift;
711 
712         r = (v > 0xFFFF) << 4; v >>= r;
713         shift = (v > 0xFF) << 3; v >>= shift; r |= shift;
714         shift = (v > 0xF) << 2; v >>= shift; r |= shift;
715         shift = (v > 0x3) << 1; v >>= shift; r |= shift;
716         r |= (v >> 1);
717         return r;
718 }
719 
720 /*
721  * log2_u64 - Compute the base 2 logarithm of a 64-bit exponential value.
722  * @v: The value for which we're computing the base 2 logarithm.
723  */
724 static inline u32 log2_u64(u64 v)
725 {
726         u32 hi = v >> 32;
727         if (hi)
728                 return log2_u32(hi) + 32 + 1;
729         else
730                 return log2_u32(v) + 1;
731 }
732 
733 /*
734  * sqrt_u64 - Calculate the square root of value @x using Newton's method.
735  */
736 static inline u64 __sqrt_u64(u64 x)
737 {
738 	if (x == 0 || x == 1)
739 		return x;
740 
741 	u64 r = ((1ULL << 32) > x) ? x : (1ULL << 32);
742 
743 	for (int i = 0; i < 8; ++i) {
744 		u64 q = x / r;
745 		if (r <= q)
746 			break;
747 		r = (r + q) >> 1;
748 	}
749 	return r;
750 }
751 
752 /*
753  * Return a value proportionally scaled to the task's weight.
754  */
755 static inline u64 scale_by_task_weight(const struct task_struct *p, u64 value)
756 {
757 	return (value * p->scx.weight) / 100;
758 }
759 
760 /*
761  * Return a value inversely proportional to the task's weight.
762  */
763 static inline u64 scale_by_task_weight_inverse(const struct task_struct *p, u64 value)
764 {
765 	return value * 100 / p->scx.weight;
766 }
767 
768 
769 #include "compat.bpf.h"
770 #include "enums.bpf.h"
771 
772 #endif	/* __SCX_COMMON_BPF_H */
773