Path: blob/master/tools/sched_ext/include/scx/common.bpf.h
48893 views
/* SPDX-License-Identifier: GPL-2.0 */1/*2* Copyright (c) 2022 Meta Platforms, Inc. and affiliates.3* Copyright (c) 2022 Tejun Heo <[email protected]>4* Copyright (c) 2022 David Vernet <[email protected]>5*/6#ifndef __SCX_COMMON_BPF_H7#define __SCX_COMMON_BPF_H89/*10* The generated kfunc prototypes in vmlinux.h are missing address space11* attributes which cause build failures. For now, suppress the generated12* prototypes. See https://github.com/sched-ext/scx/issues/1111.13*/14#define BPF_NO_KFUNC_PROTOTYPES1516#ifdef LSP17#define __bpf__18#include "../vmlinux.h"19#else20#include "vmlinux.h"21#endif2223#include <bpf/bpf_helpers.h>24#include <bpf/bpf_tracing.h>25#include <asm-generic/errno.h>26#include "user_exit_info.bpf.h"27#include "enum_defs.autogen.h"2829#define PF_IDLE 0x00000002 /* I am an IDLE thread */30#define PF_IO_WORKER 0x00000010 /* Task is an IO worker */31#define PF_WQ_WORKER 0x00000020 /* I'm a workqueue worker */32#define PF_KCOMPACTD 0x00010000 /* I am kcompactd */33#define PF_KSWAPD 0x00020000 /* I am kswapd */34#define PF_KTHREAD 0x00200000 /* I am a kernel thread */35#define PF_EXITING 0x0000000436#define CLOCK_MONOTONIC 13738#ifndef NR_CPUS39#define NR_CPUS 102440#endif4142#ifndef NUMA_NO_NODE43#define NUMA_NO_NODE (-1)44#endif4546extern int LINUX_KERNEL_VERSION __kconfig;47extern const char CONFIG_CC_VERSION_TEXT[64] __kconfig __weak;48extern const char CONFIG_LOCALVERSION[64] __kconfig __weak;4950/*51* Earlier versions of clang/pahole lost upper 32bits in 64bit enums which can52* lead to really confusing misbehaviors. Let's trigger a build failure.53*/54static inline void ___vmlinux_h_sanity_check___(void)55{56_Static_assert(SCX_DSQ_FLAG_BUILTIN,57"bpftool generated vmlinux.h is missing high bits for 64bit enums, upgrade clang and pahole");58}5960s32 scx_bpf_create_dsq(u64 dsq_id, s32 node) __ksym;61s32 scx_bpf_select_cpu_dfl(struct task_struct *p, s32 prev_cpu, u64 wake_flags, bool *is_idle) __ksym;62s32 __scx_bpf_select_cpu_and(struct task_struct *p, const struct cpumask *cpus_allowed,63struct scx_bpf_select_cpu_and_args *args) __ksym __weak;64bool __scx_bpf_dsq_insert_vtime(struct task_struct *p, struct scx_bpf_dsq_insert_vtime_args *args) __ksym __weak;65u32 scx_bpf_dispatch_nr_slots(void) __ksym;66void scx_bpf_dispatch_cancel(void) __ksym;67void scx_bpf_kick_cpu(s32 cpu, u64 flags) __ksym;68s32 scx_bpf_dsq_nr_queued(u64 dsq_id) __ksym;69void scx_bpf_destroy_dsq(u64 dsq_id) __ksym;70struct task_struct *scx_bpf_dsq_peek(u64 dsq_id) __ksym __weak;71int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id, u64 flags) __ksym __weak;72struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it) __ksym __weak;73void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it) __ksym __weak;74void scx_bpf_exit_bstr(s64 exit_code, char *fmt, unsigned long long *data, u32 data__sz) __ksym __weak;75void scx_bpf_error_bstr(char *fmt, unsigned long long *data, u32 data_len) __ksym;76void scx_bpf_dump_bstr(char *fmt, unsigned long long *data, u32 data_len) __ksym __weak;77u32 scx_bpf_cpuperf_cap(s32 cpu) __ksym __weak;78u32 scx_bpf_cpuperf_cur(s32 cpu) __ksym __weak;79void scx_bpf_cpuperf_set(s32 cpu, u32 perf) __ksym __weak;80u32 scx_bpf_nr_node_ids(void) __ksym __weak;81u32 scx_bpf_nr_cpu_ids(void) __ksym __weak;82int scx_bpf_cpu_node(s32 cpu) __ksym __weak;83const struct cpumask *scx_bpf_get_possible_cpumask(void) __ksym __weak;84const struct cpumask *scx_bpf_get_online_cpumask(void) __ksym __weak;85void scx_bpf_put_cpumask(const struct cpumask *cpumask) __ksym __weak;86const struct cpumask *scx_bpf_get_idle_cpumask_node(int node) __ksym __weak;87const struct cpumask *scx_bpf_get_idle_cpumask(void) __ksym;88const struct cpumask *scx_bpf_get_idle_smtmask_node(int node) __ksym __weak;89const struct cpumask *scx_bpf_get_idle_smtmask(void) __ksym;90void scx_bpf_put_idle_cpumask(const struct cpumask *cpumask) __ksym;91bool scx_bpf_test_and_clear_cpu_idle(s32 cpu) __ksym;92s32 scx_bpf_pick_idle_cpu_node(const cpumask_t *cpus_allowed, int node, u64 flags) __ksym __weak;93s32 scx_bpf_pick_idle_cpu(const cpumask_t *cpus_allowed, u64 flags) __ksym;94s32 scx_bpf_pick_any_cpu_node(const cpumask_t *cpus_allowed, int node, u64 flags) __ksym __weak;95s32 scx_bpf_pick_any_cpu(const cpumask_t *cpus_allowed, u64 flags) __ksym;96bool scx_bpf_task_running(const struct task_struct *p) __ksym;97s32 scx_bpf_task_cpu(const struct task_struct *p) __ksym;98struct rq *scx_bpf_cpu_rq(s32 cpu) __ksym;99struct rq *scx_bpf_locked_rq(void) __ksym;100struct task_struct *scx_bpf_cpu_curr(s32 cpu) __ksym __weak;101u64 scx_bpf_now(void) __ksym __weak;102void scx_bpf_events(struct scx_event_stats *events, size_t events__sz) __ksym __weak;103104/*105* Use the following as @it__iter when calling scx_bpf_dsq_move[_vtime]() from106* within bpf_for_each() loops.107*/108#define BPF_FOR_EACH_ITER (&___it)109110#define scx_read_event(e, name) \111(bpf_core_field_exists((e)->name) ? (e)->name : 0)112113static inline __attribute__((format(printf, 1, 2)))114void ___scx_bpf_bstr_format_checker(const char *fmt, ...) {}115116#define SCX_STRINGIFY(x) #x117#define SCX_TOSTRING(x) SCX_STRINGIFY(x)118119/*120* Helper macro for initializing the fmt and variadic argument inputs to both121* bstr exit kfuncs. Callers to this function should use ___fmt and ___param to122* refer to the initialized list of inputs to the bstr kfunc.123*/124#define scx_bpf_bstr_preamble(fmt, args...) \125static char ___fmt[] = fmt; \126/* \127* Note that __param[] must have at least one \128* element to keep the verifier happy. \129*/ \130unsigned long long ___param[___bpf_narg(args) ?: 1] = {}; \131\132_Pragma("GCC diagnostic push") \133_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \134___bpf_fill(___param, args); \135_Pragma("GCC diagnostic pop")136137/*138* scx_bpf_exit() wraps the scx_bpf_exit_bstr() kfunc with variadic arguments139* instead of an array of u64. Using this macro will cause the scheduler to140* exit cleanly with the specified exit code being passed to user space.141*/142#define scx_bpf_exit(code, fmt, args...) \143({ \144scx_bpf_bstr_preamble(fmt, args) \145scx_bpf_exit_bstr(code, ___fmt, ___param, sizeof(___param)); \146___scx_bpf_bstr_format_checker(fmt, ##args); \147})148149/*150* scx_bpf_error() wraps the scx_bpf_error_bstr() kfunc with variadic arguments151* instead of an array of u64. Invoking this macro will cause the scheduler to152* exit in an erroneous state, with diagnostic information being passed to the153* user. It appends the file and line number to aid debugging.154*/155#define scx_bpf_error(fmt, args...) \156({ \157scx_bpf_bstr_preamble( \158__FILE__ ":" SCX_TOSTRING(__LINE__) ": " fmt, ##args) \159scx_bpf_error_bstr(___fmt, ___param, sizeof(___param)); \160___scx_bpf_bstr_format_checker( \161__FILE__ ":" SCX_TOSTRING(__LINE__) ": " fmt, ##args); \162})163164/*165* scx_bpf_dump() wraps the scx_bpf_dump_bstr() kfunc with variadic arguments166* instead of an array of u64. To be used from ops.dump() and friends.167*/168#define scx_bpf_dump(fmt, args...) \169({ \170scx_bpf_bstr_preamble(fmt, args) \171scx_bpf_dump_bstr(___fmt, ___param, sizeof(___param)); \172___scx_bpf_bstr_format_checker(fmt, ##args); \173})174175/*176* scx_bpf_dump_header() is a wrapper around scx_bpf_dump that adds a header177* of system information for debugging.178*/179#define scx_bpf_dump_header() \180({ \181scx_bpf_dump("kernel: %d.%d.%d %s\ncc: %s\n", \182LINUX_KERNEL_VERSION >> 16, \183LINUX_KERNEL_VERSION >> 8 & 0xFF, \184LINUX_KERNEL_VERSION & 0xFF, \185CONFIG_LOCALVERSION, \186CONFIG_CC_VERSION_TEXT); \187})188189#define BPF_STRUCT_OPS(name, args...) \190SEC("struct_ops/"#name) \191BPF_PROG(name, ##args)192193#define BPF_STRUCT_OPS_SLEEPABLE(name, args...) \194SEC("struct_ops.s/"#name) \195BPF_PROG(name, ##args)196197/**198* RESIZABLE_ARRAY - Generates annotations for an array that may be resized199* @elfsec: the data section of the BPF program in which to place the array200* @arr: the name of the array201*202* libbpf has an API for setting map value sizes. Since data sections (i.e.203* bss, data, rodata) themselves are maps, a data section can be resized. If204* a data section has an array as its last element, the BTF info for that205* array will be adjusted so that length of the array is extended to meet the206* new length of the data section. This macro annotates an array to have an207* element count of one with the assumption that this array can be resized208* within the userspace program. It also annotates the section specifier so209* this array exists in a custom sub data section which can be resized210* independently.211*212* See RESIZE_ARRAY() for the userspace convenience macro for resizing an213* array declared with RESIZABLE_ARRAY().214*/215#define RESIZABLE_ARRAY(elfsec, arr) arr[1] SEC("."#elfsec"."#arr)216217/**218* MEMBER_VPTR - Obtain the verified pointer to a struct or array member219* @base: struct or array to index220* @member: dereferenced member (e.g. .field, [idx0][idx1], .field[idx0] ...)221*222* The verifier often gets confused by the instruction sequence the compiler223* generates for indexing struct fields or arrays. This macro forces the224* compiler to generate a code sequence which first calculates the byte offset,225* checks it against the struct or array size and add that byte offset to226* generate the pointer to the member to help the verifier.227*228* Ideally, we want to abort if the calculated offset is out-of-bounds. However,229* BPF currently doesn't support abort, so evaluate to %NULL instead. The caller230* must check for %NULL and take appropriate action to appease the verifier. To231* avoid confusing the verifier, it's best to check for %NULL and dereference232* immediately.233*234* vptr = MEMBER_VPTR(my_array, [i][j]);235* if (!vptr)236* return error;237* *vptr = new_value;238*239* sizeof(@base) should encompass the memory area to be accessed and thus can't240* be a pointer to the area. Use `MEMBER_VPTR(*ptr, .member)` instead of241* `MEMBER_VPTR(ptr, ->member)`.242*/243#ifndef MEMBER_VPTR244#define MEMBER_VPTR(base, member) (typeof((base) member) *) \245({ \246u64 __base = (u64)&(base); \247u64 __addr = (u64)&((base) member) - __base; \248_Static_assert(sizeof(base) >= sizeof((base) member), \249"@base is smaller than @member, is @base a pointer?"); \250asm volatile ( \251"if %0 <= %[max] goto +2\n" \252"%0 = 0\n" \253"goto +1\n" \254"%0 += %1\n" \255: "+r"(__addr) \256: "r"(__base), \257[max]"i"(sizeof(base) - sizeof((base) member))); \258__addr; \259})260#endif /* MEMBER_VPTR */261262/**263* ARRAY_ELEM_PTR - Obtain the verified pointer to an array element264* @arr: array to index into265* @i: array index266* @n: number of elements in array267*268* Similar to MEMBER_VPTR() but is intended for use with arrays where the269* element count needs to be explicit.270* It can be used in cases where a global array is defined with an initial271* size but is intended to be be resized before loading the BPF program.272* Without this version of the macro, MEMBER_VPTR() will use the compile time273* size of the array to compute the max, which will result in rejection by274* the verifier.275*/276#ifndef ARRAY_ELEM_PTR277#define ARRAY_ELEM_PTR(arr, i, n) (typeof(arr[i]) *) \278({ \279u64 __base = (u64)arr; \280u64 __addr = (u64)&(arr[i]) - __base; \281asm volatile ( \282"if %0 <= %[max] goto +2\n" \283"%0 = 0\n" \284"goto +1\n" \285"%0 += %1\n" \286: "+r"(__addr) \287: "r"(__base), \288[max]"r"(sizeof(arr[0]) * ((n) - 1))); \289__addr; \290})291#endif /* ARRAY_ELEM_PTR */292293/*294* BPF declarations and helpers295*/296297/* list and rbtree */298#define __contains(name, node) __attribute__((btf_decl_tag("contains:" #name ":" #node)))299#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))300301void *bpf_obj_new_impl(__u64 local_type_id, void *meta) __ksym;302void bpf_obj_drop_impl(void *kptr, void *meta) __ksym;303304#define bpf_obj_new(type) ((type *)bpf_obj_new_impl(bpf_core_type_id_local(type), NULL))305#define bpf_obj_drop(kptr) bpf_obj_drop_impl(kptr, NULL)306307int bpf_list_push_front_impl(struct bpf_list_head *head,308struct bpf_list_node *node,309void *meta, __u64 off) __ksym;310#define bpf_list_push_front(head, node) bpf_list_push_front_impl(head, node, NULL, 0)311312int bpf_list_push_back_impl(struct bpf_list_head *head,313struct bpf_list_node *node,314void *meta, __u64 off) __ksym;315#define bpf_list_push_back(head, node) bpf_list_push_back_impl(head, node, NULL, 0)316317struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head) __ksym;318struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head) __ksym;319struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,320struct bpf_rb_node *node) __ksym;321int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,322bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),323void *meta, __u64 off) __ksym;324#define bpf_rbtree_add(head, node, less) bpf_rbtree_add_impl(head, node, less, NULL, 0)325326struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root) __ksym;327328void *bpf_refcount_acquire_impl(void *kptr, void *meta) __ksym;329#define bpf_refcount_acquire(kptr) bpf_refcount_acquire_impl(kptr, NULL)330331/* task */332struct task_struct *bpf_task_from_pid(s32 pid) __ksym;333struct task_struct *bpf_task_acquire(struct task_struct *p) __ksym;334void bpf_task_release(struct task_struct *p) __ksym;335336/* cgroup */337struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level) __ksym;338void bpf_cgroup_release(struct cgroup *cgrp) __ksym;339struct cgroup *bpf_cgroup_from_id(u64 cgid) __ksym;340341/* css iteration */342struct bpf_iter_css;343struct cgroup_subsys_state;344extern int bpf_iter_css_new(struct bpf_iter_css *it,345struct cgroup_subsys_state *start,346unsigned int flags) __weak __ksym;347extern struct cgroup_subsys_state *348bpf_iter_css_next(struct bpf_iter_css *it) __weak __ksym;349extern void bpf_iter_css_destroy(struct bpf_iter_css *it) __weak __ksym;350351/* cpumask */352struct bpf_cpumask *bpf_cpumask_create(void) __ksym;353struct bpf_cpumask *bpf_cpumask_acquire(struct bpf_cpumask *cpumask) __ksym;354void bpf_cpumask_release(struct bpf_cpumask *cpumask) __ksym;355u32 bpf_cpumask_first(const struct cpumask *cpumask) __ksym;356u32 bpf_cpumask_first_zero(const struct cpumask *cpumask) __ksym;357void bpf_cpumask_set_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;358void bpf_cpumask_clear_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;359bool bpf_cpumask_test_cpu(u32 cpu, const struct cpumask *cpumask) __ksym;360bool bpf_cpumask_test_and_set_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;361bool bpf_cpumask_test_and_clear_cpu(u32 cpu, struct bpf_cpumask *cpumask) __ksym;362void bpf_cpumask_setall(struct bpf_cpumask *cpumask) __ksym;363void bpf_cpumask_clear(struct bpf_cpumask *cpumask) __ksym;364bool bpf_cpumask_and(struct bpf_cpumask *dst, const struct cpumask *src1,365const struct cpumask *src2) __ksym;366void bpf_cpumask_or(struct bpf_cpumask *dst, const struct cpumask *src1,367const struct cpumask *src2) __ksym;368void bpf_cpumask_xor(struct bpf_cpumask *dst, const struct cpumask *src1,369const struct cpumask *src2) __ksym;370bool bpf_cpumask_equal(const struct cpumask *src1, const struct cpumask *src2) __ksym;371bool bpf_cpumask_intersects(const struct cpumask *src1, const struct cpumask *src2) __ksym;372bool bpf_cpumask_subset(const struct cpumask *src1, const struct cpumask *src2) __ksym;373bool bpf_cpumask_empty(const struct cpumask *cpumask) __ksym;374bool bpf_cpumask_full(const struct cpumask *cpumask) __ksym;375void bpf_cpumask_copy(struct bpf_cpumask *dst, const struct cpumask *src) __ksym;376u32 bpf_cpumask_any_distribute(const struct cpumask *cpumask) __ksym;377u32 bpf_cpumask_any_and_distribute(const struct cpumask *src1,378const struct cpumask *src2) __ksym;379u32 bpf_cpumask_weight(const struct cpumask *cpumask) __ksym;380381int bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_words) __ksym;382int *bpf_iter_bits_next(struct bpf_iter_bits *it) __ksym;383void bpf_iter_bits_destroy(struct bpf_iter_bits *it) __ksym;384385#define def_iter_struct(name) \386struct bpf_iter_##name { \387struct bpf_iter_bits it; \388const struct cpumask *bitmap; \389};390391#define def_iter_new(name) \392static inline int bpf_iter_##name##_new( \393struct bpf_iter_##name *it, const u64 *unsafe_ptr__ign, u32 nr_words) \394{ \395it->bitmap = scx_bpf_get_##name##_cpumask(); \396return bpf_iter_bits_new(&it->it, (const u64 *)it->bitmap, \397sizeof(struct cpumask) / 8); \398}399400#define def_iter_next(name) \401static inline int *bpf_iter_##name##_next(struct bpf_iter_##name *it) { \402return bpf_iter_bits_next(&it->it); \403}404405#define def_iter_destroy(name) \406static inline void bpf_iter_##name##_destroy(struct bpf_iter_##name *it) { \407scx_bpf_put_cpumask(it->bitmap); \408bpf_iter_bits_destroy(&it->it); \409}410#define def_for_each_cpu(cpu, name) for_each_##name##_cpu(cpu)411412/// Provides iterator for possible and online cpus.413///414/// # Example415///416/// ```417/// static inline void example_use() {418/// int *cpu;419///420/// for_each_possible_cpu(cpu){421/// bpf_printk("CPU %d is possible", *cpu);422/// }423///424/// for_each_online_cpu(cpu){425/// bpf_printk("CPU %d is online", *cpu);426/// }427/// }428/// ```429def_iter_struct(possible);430def_iter_new(possible);431def_iter_next(possible);432def_iter_destroy(possible);433#define for_each_possible_cpu(cpu) bpf_for_each(possible, cpu, NULL, 0)434435def_iter_struct(online);436def_iter_new(online);437def_iter_next(online);438def_iter_destroy(online);439#define for_each_online_cpu(cpu) bpf_for_each(online, cpu, NULL, 0)440441/*442* Access a cpumask in read-only mode (typically to check bits).443*/444static __always_inline const struct cpumask *cast_mask(struct bpf_cpumask *mask)445{446return (const struct cpumask *)mask;447}448449/*450* Return true if task @p cannot migrate to a different CPU, false451* otherwise.452*/453static inline bool is_migration_disabled(const struct task_struct *p)454{455/*456* Testing p->migration_disabled in a BPF code is tricky because the457* migration is _always_ disabled while running the BPF code.458* The prolog (__bpf_prog_enter) and epilog (__bpf_prog_exit) for BPF459* code execution disable and re-enable the migration of the current460* task, respectively. So, the _current_ task of the sched_ext ops is461* always migration-disabled. Moreover, p->migration_disabled could be462* two or greater when a sched_ext ops BPF code (e.g., ops.tick) is463* executed in the middle of the other BPF code execution.464*465* Therefore, we should decide that the _current_ task is466* migration-disabled only when its migration_disabled count is greater467* than one. In other words, when p->migration_disabled == 1, there is468* an ambiguity, so we should check if @p is the current task or not.469*/470if (bpf_core_field_exists(p->migration_disabled)) {471if (p->migration_disabled == 1)472return bpf_get_current_task_btf() != p;473else474return p->migration_disabled;475}476return false;477}478479/* rcu */480void bpf_rcu_read_lock(void) __ksym;481void bpf_rcu_read_unlock(void) __ksym;482483/*484* Time helpers, most of which are from jiffies.h.485*/486487/**488* time_delta - Calculate the delta between new and old time stamp489* @after: first comparable as u64490* @before: second comparable as u64491*492* Return: the time difference, which is >= 0493*/494static inline s64 time_delta(u64 after, u64 before)495{496return (s64)(after - before) > 0 ? (s64)(after - before) : 0;497}498499/**500* time_after - returns true if the time a is after time b.501* @a: first comparable as u64502* @b: second comparable as u64503*504* Do this with "<0" and ">=0" to only test the sign of the result. A505* good compiler would generate better code (and a really good compiler506* wouldn't care). Gcc is currently neither.507*508* Return: %true is time a is after time b, otherwise %false.509*/510static inline bool time_after(u64 a, u64 b)511{512return (s64)(b - a) < 0;513}514515/**516* time_before - returns true if the time a is before time b.517* @a: first comparable as u64518* @b: second comparable as u64519*520* Return: %true is time a is before time b, otherwise %false.521*/522static inline bool time_before(u64 a, u64 b)523{524return time_after(b, a);525}526527/**528* time_after_eq - returns true if the time a is after or the same as time b.529* @a: first comparable as u64530* @b: second comparable as u64531*532* Return: %true is time a is after or the same as time b, otherwise %false.533*/534static inline bool time_after_eq(u64 a, u64 b)535{536return (s64)(a - b) >= 0;537}538539/**540* time_before_eq - returns true if the time a is before or the same as time b.541* @a: first comparable as u64542* @b: second comparable as u64543*544* Return: %true is time a is before or the same as time b, otherwise %false.545*/546static inline bool time_before_eq(u64 a, u64 b)547{548return time_after_eq(b, a);549}550551/**552* time_in_range - Calculate whether a is in the range of [b, c].553* @a: time to test554* @b: beginning of the range555* @c: end of the range556*557* Return: %true is time a is in the range [b, c], otherwise %false.558*/559static inline bool time_in_range(u64 a, u64 b, u64 c)560{561return time_after_eq(a, b) && time_before_eq(a, c);562}563564/**565* time_in_range_open - Calculate whether a is in the range of [b, c).566* @a: time to test567* @b: beginning of the range568* @c: end of the range569*570* Return: %true is time a is in the range [b, c), otherwise %false.571*/572static inline bool time_in_range_open(u64 a, u64 b, u64 c)573{574return time_after_eq(a, b) && time_before(a, c);575}576577578/*579* Other helpers580*/581582/* useful compiler attributes */583#ifndef likely584#define likely(x) __builtin_expect(!!(x), 1)585#endif586#ifndef unlikely587#define unlikely(x) __builtin_expect(!!(x), 0)588#endif589#ifndef __maybe_unused590#define __maybe_unused __attribute__((__unused__))591#endif592593/*594* READ/WRITE_ONCE() are from kernel (include/asm-generic/rwonce.h). They595* prevent compiler from caching, redoing or reordering reads or writes.596*/597typedef __u8 __attribute__((__may_alias__)) __u8_alias_t;598typedef __u16 __attribute__((__may_alias__)) __u16_alias_t;599typedef __u32 __attribute__((__may_alias__)) __u32_alias_t;600typedef __u64 __attribute__((__may_alias__)) __u64_alias_t;601602static __always_inline void __read_once_size(const volatile void *p, void *res, int size)603{604switch (size) {605case 1: *(__u8_alias_t *) res = *(volatile __u8_alias_t *) p; break;606case 2: *(__u16_alias_t *) res = *(volatile __u16_alias_t *) p; break;607case 4: *(__u32_alias_t *) res = *(volatile __u32_alias_t *) p; break;608case 8: *(__u64_alias_t *) res = *(volatile __u64_alias_t *) p; break;609default:610barrier();611__builtin_memcpy((void *)res, (const void *)p, size);612barrier();613}614}615616static __always_inline void __write_once_size(volatile void *p, void *res, int size)617{618switch (size) {619case 1: *(volatile __u8_alias_t *) p = *(__u8_alias_t *) res; break;620case 2: *(volatile __u16_alias_t *) p = *(__u16_alias_t *) res; break;621case 4: *(volatile __u32_alias_t *) p = *(__u32_alias_t *) res; break;622case 8: *(volatile __u64_alias_t *) p = *(__u64_alias_t *) res; break;623default:624barrier();625__builtin_memcpy((void *)p, (const void *)res, size);626barrier();627}628}629630/*631* __unqual_typeof(x) - Declare an unqualified scalar type, leaving632* non-scalar types unchanged,633*634* Prefer C11 _Generic for better compile-times and simpler code. Note: 'char'635* is not type-compatible with 'signed char', and we define a separate case.636*637* This is copied verbatim from kernel's include/linux/compiler_types.h, but638* with default expression (for pointers) changed from (x) to (typeof(x)0).639*640* This is because LLVM has a bug where for lvalue (x), it does not get rid of641* an extra address_space qualifier, but does in case of rvalue (typeof(x)0).642* Hence, for pointers, we need to create an rvalue expression to get the643* desired type. See https://github.com/llvm/llvm-project/issues/53400.644*/645#define __scalar_type_to_expr_cases(type) \646unsigned type : (unsigned type)0, signed type : (signed type)0647648#define __unqual_typeof(x) \649typeof(_Generic((x), \650char: (char)0, \651__scalar_type_to_expr_cases(char), \652__scalar_type_to_expr_cases(short), \653__scalar_type_to_expr_cases(int), \654__scalar_type_to_expr_cases(long), \655__scalar_type_to_expr_cases(long long), \656default: (typeof(x))0))657658#define READ_ONCE(x) \659({ \660union { __unqual_typeof(x) __val; char __c[1]; } __u = \661{ .__c = { 0 } }; \662__read_once_size((__unqual_typeof(x) *)&(x), __u.__c, sizeof(x)); \663__u.__val; \664})665666#define WRITE_ONCE(x, val) \667({ \668union { __unqual_typeof(x) __val; char __c[1]; } __u = \669{ .__val = (val) }; \670__write_once_size((__unqual_typeof(x) *)&(x), __u.__c, sizeof(x)); \671__u.__val; \672})673674/*675* __calc_avg - Calculate exponential weighted moving average (EWMA) with676* @old and @new values. @decay represents how large the @old value remains.677* With a larger @decay value, the moving average changes slowly, exhibiting678* fewer fluctuations.679*/680#define __calc_avg(old, new, decay) ({ \681typeof(decay) thr = 1 << (decay); \682typeof(old) ret; \683if (((old) < thr) || ((new) < thr)) { \684if (((old) == 1) && ((new) == 0)) \685ret = 0; \686else \687ret = ((old) - ((old) >> 1)) + ((new) >> 1); \688} else { \689ret = ((old) - ((old) >> (decay))) + ((new) >> (decay)); \690} \691ret; \692})693694/*695* log2_u32 - Compute the base 2 logarithm of a 32-bit exponential value.696* @v: The value for which we're computing the base 2 logarithm.697*/698static inline u32 log2_u32(u32 v)699{700u32 r;701u32 shift;702703r = (v > 0xFFFF) << 4; v >>= r;704shift = (v > 0xFF) << 3; v >>= shift; r |= shift;705shift = (v > 0xF) << 2; v >>= shift; r |= shift;706shift = (v > 0x3) << 1; v >>= shift; r |= shift;707r |= (v >> 1);708return r;709}710711/*712* log2_u64 - Compute the base 2 logarithm of a 64-bit exponential value.713* @v: The value for which we're computing the base 2 logarithm.714*/715static inline u32 log2_u64(u64 v)716{717u32 hi = v >> 32;718if (hi)719return log2_u32(hi) + 32 + 1;720else721return log2_u32(v) + 1;722}723724/*725* sqrt_u64 - Calculate the square root of value @x using Newton's method.726*/727static inline u64 __sqrt_u64(u64 x)728{729if (x == 0 || x == 1)730return x;731732u64 r = ((1ULL << 32) > x) ? x : (1ULL << 32);733734for (int i = 0; i < 8; ++i) {735u64 q = x / r;736if (r <= q)737break;738r = (r + q) >> 1;739}740return r;741}742743/*744* Return a value proportionally scaled to the task's weight.745*/746static inline u64 scale_by_task_weight(const struct task_struct *p, u64 value)747{748return (value * p->scx.weight) / 100;749}750751/*752* Return a value inversely proportional to the task's weight.753*/754static inline u64 scale_by_task_weight_inverse(const struct task_struct *p, u64 value)755{756return value * 100 / p->scx.weight;757}758759760#include "compat.bpf.h"761#include "enums.bpf.h"762763#endif /* __SCX_COMMON_BPF_H */764765766