Local kptrs, BPF linked lists
Subsystems (9)
Kumar Kartikeya Dwivedi
maintainercover Local kptrs, BPF linked lists
Hi, this is the non-RFC v1. This is mostly a major rewrite of the previous set, hence complete review of some of these patches is needed again. I have cut down the series to only the specific pieces needed to enable other work (like Dave's RB-Tree). The rest will come as a follow up to this.
--
This series introduces user defined BPF objects, by introducing the idea of local kptrs. These are kptrs (strongly typed pointers) that refer to objects of a user defined type, hence called "local" kptrs. This allows BPF programs to allocate their own objects, build their own object hierarchies, and use the basic building blocks provided by BPF runtime to build their own data structures flexibly.
Then, we introduce the support for single ownership BPF linked lists, which can be put inside BPF maps, or local kptrs, and hold such allocated local kptrs as elements. It works as an instrusive collection, which is done to allow making local kptrs part of multiple data structures at the same time in the future.
The eventual goal of this and future patches is to allow one to do some limited form of kernel style programming in BPF C, and allow programmers to build their own complex data structures flexibly out of basic building blocks.
The key difference will be that such programs are verified to be safe, preserve runtime integrity of the system, and are proven to be bug free as far as the invariants of BPF specific APIs are concerned.
One immediate use case that will be using the entire infrastructure this series is introducing will be managing percpu NMI safe linked lists inside BPF programs.
The other use case this will serve in the near future will be linking kernel structures like XDP frame and sk_buff directly into user data structures (rbtree, pifomap, etc.) for packet queueing. This will follow single ownership concept included in this series.
The user has complete control of the internal locking, and hence also the batching of operations for each critical section.
The features are:
- Local kptrs - User defined kernel objects.
- bpf_kptr_new, bpf_kptr_drop to allocate and free them.
- Single ownership BPF linked lists.
- Support for them in BPF maps.
- Support for them in local kptrs.
- Global spin locks.
- Spin locks inside local kptrs.
- Allow storing local kptrs in all BPF maps with support for kernel kptrs.
Some other notable things:
- Completely static verification of locking.
- Kfunc argument handling has been completely reworked.
- Argument rewriting support for kfuncs.
- Search pruning now understands non-size precise registers.
- A new bpf_experimental.h header as a dumping ground for these APIs.
Any functionality exposed in this series is NOT part of UAPI. It is only available through use of kfuncs, and structs that can be added to map value may also change their size or name in the future. Hence, every feature in this series must be considered experimental.
Follow-ups:
-----------
* Support for kptrs (local and kernel) in local storage and percpu maps + kptr tests
* Fixes that rebase on top of refactorings in this series for dynptrs and helper access checks (not included since unrelated, and this is too big already)
Next steps:
-----------
* NMI safe percpu single ownership linked lists (using local_t protection).
* Lockless linked lists.
* Allow RCU protected local kptrs. This then allows RCU protected list lookups, since spinlock protection for readers does not scale.
* Introduce explicit RCU read sections (using kfuncs).
* Introduce bpf_refcount for local kptrs, shared ownership.
* Introduce shared ownership linked lists.
* Documentation.
Notes:
------
* Dave's patch for libbpf sections is still needed for this to move forward.
Changelog:
----------
RFC v1 -> v1
RFC v1: https://lore.kernel.org/bpf/[email protected]
* Mostly a complete rewrite of BTF parsing, refactor existing code (Kartikeya)
* Rebase kfunc rewrite for bpf-next, add support for more changes
* Cache type metadata in BTF to avoid recomputation inside verifier (Kartikeya)
* Remove __kernel tag, make things similar to map values, reserve bpf_ prefix
* bpf_kptr_new, bpf_kptr_drop (Alexei)
* Rename precision state enum values (Alexei)
* Drop explicit constructor/destructor support (Alexei)
* Rewrite code for constructing/destructing objects and offload to runtime
* Minimize duplication in bpf_map_value_off_desc handling (Alexei)
* Expose global memory allocator (Alexei)
* Address other nits from Alexei
* Split out local kptrs in maps, more kptrs in maps support into a follow up
Links:
------
* Dave's BPF RB-Tree RFC series
v1 (Discussion thread)
https://lore.kernel.org/bpf/[email protected] v2 (With support for static locks) https://lore.kernel.org/bpf/[email protected]
* BPF Linked Lists Discussion
https://lore.kernel.org/bpf/CAP01T74U30+yeBHEgmgzTJ-XYxZ0zj71kqCDJtTH9YQNfTK+Xw@mail.gmail.com
* BPF Memory Allocator from Alexei
https://lore.kernel.org/bpf/[email protected]
* BPF Memory Allocator UAPI Discussion
https://lore.kernel.org/bpf/[email protected]
Dave Marchevsky (1):
libbpf: Add support for private BSS map section
Kumar Kartikeya Dwivedi (24):
bpf: Document UAPI details for special BPF types
bpf: Allow specifying volatile type modifier for kptrs
bpf: Clobber stack slot when writing over spilled PTR_TO_BTF_ID
bpf: Fix slot type check in check_stack_write_var_off
bpf: Drop reg_type_may_be_refcounted_or_null
bpf: Refactor kptr_off_tab into fields_tab
bpf: Consolidate spin_lock, timer management into fields_tab
bpf: Refactor map->off_arr handling
bpf: Support bpf_list_head in map values
bpf: Introduce local kptrs
bpf: Recognize bpf_{spin_lock,list_head,list_node} in local kptrs
bpf: Verify ownership relationships for owning types
bpf: Support locking bpf_spin_lock in local kptr
bpf: Allow locking bpf_spin_lock global variables
bpf: Rewrite kfunc argument handling
bpf: Drop kfunc bits from btf_check_func_arg_match
bpf: Support constant scalar arguments for kfuncs
bpf: Teach verifier about non-size constant arguments
bpf: Introduce bpf_kptr_new
bpf: Introduce bpf_kptr_drop
bpf: Permit NULL checking pointer with non-zero fixed offset
bpf: Introduce single ownership BPF linked list API selftests/bpf: Add __contains macro to bpf_experimental.h selftests/bpf: Add BPF linked list API tests
Documentation/bpf/bpf_design_QA.rst | 44 + Documentation/bpf/kfuncs.rst | 30 + include/linux/bpf.h | 238 ++- include/linux/bpf_verifier.h | 22 +- include/linux/btf.h | 76 +- include/linux/filter.h | 4 +- kernel/bpf/arraymap.c | 30 +- kernel/bpf/bpf_local_storage.c | 2 +- kernel/bpf/btf.c | 1204 +++++++------- kernel/bpf/core.c | 14 + kernel/bpf/hashtab.c | 40 +- kernel/bpf/helpers.c | 138 +- kernel/bpf/local_storage.c | 2 +- kernel/bpf/map_in_map.c | 18 +- kernel/bpf/syscall.c | 381 +++-- kernel/bpf/verifier.c | 1449 ++++++++++++++--- net/bpf/bpf_dummy_struct_ops.c | 3 +- net/core/bpf_sk_storage.c | 4 +- net/core/filter.c | 13 +- net/ipv4/bpf_tcp_ca.c | 3 +- net/netfilter/nf_conntrack_bpf.c | 1 + tools/lib/bpf/libbpf.c | 65 +- tools/testing/selftests/bpf/DENYLIST.s390x | 1 + .../testing/selftests/bpf/bpf_experimental.h | 85 + .../bpf/prog_tests/kfunc_dynptr_param.c | 2 +- .../selftests/bpf/prog_tests/linked_list.c | 88 + .../testing/selftests/bpf/progs/linked_list.c | 325 ++++ tools/testing/selftests/bpf/verifier/calls.c | 4 +- .../selftests/bpf/verifier/ref_tracking.c | 4 +- 29 files changed, 3145 insertions(+), 1145 deletions(-) create mode 100644 tools/testing/selftests/bpf/bpf_experimental.h create mode 100644 tools/testing/selftests/bpf/prog_tests/linked_list.c create mode 100644 tools/testing/selftests/bpf/progs/linked_list.c
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 1/25 bpf: Document UAPI details for special BPF types
The kernel recognizes some special BPF types in map values or local kptrs. Document that only bpf_spin_lock and bpf_timer will preserve backwards compatibility, and kptr will preserve backwards compatibility for the operations on the pointer, not the types supported for such kptrs.
For local kptrs, document that there are no stability guarantees at all.
Finally, document that 'bpf_' namespace is reserved for adding future special fields, hence BPF programs must not declare types with such names in their programs and still expect backwards compatibility.
--- Documentation/bpf/bpf_design_QA.rst | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+)
Documentation/bpf/bpf_design_QA.rst +44 -0
@@ -298,3 +298,47 @@ A: NO. The BTF_ID macro does not cause a function to become part of the ABI any more than does the EXPORT_SYMBOL_GPL macro. + +Q: What is the compatibility story for special BPF types in map values? +----------------------------------------------------------------------- +Q: Users are allowed to embed bpf_spin_lock, bpf_timer fields in their BPF map +values (when using BTF support for BPF maps). This allows to use helpers for +such objects on these fields inside map values. Users are also allowed to embed +pointers to some kernel types (with __kptr and __kptr_ref BTF tags). Will the +kernel preserve backwards compatibility for these features? + +A: It depends. For bpf_spin_lock, bpf_timer: YES, for kptr and everything else: +NO, but see below. + +For struct types that have been added already, like bpf_spin_lock and bpf_timer, +the kernel will preserve backwards compatibility, as they are part of UAPI. + +For kptrs, they are also part of UAPI, but only with respect to the kptr +mechanism. The types that you can use with a __kptr and __kptr_ref tagged +pointer in your struct is NOT part of the UAPI contract. The supported types +can and will change across kernel releases. However, operations like accessing +kptr fields and bpf_kptr_xchg() helper will continue to be supported across +kernel releases for the supported types. + +For any other supported struct type, unless explicitly stated in this document +and added to bpf.h UAPI header, such types can and will arbitrarily change their +size, type, and alignment, or any other user visible API or ABI detail across +kernel releases. The users must adapt their BPF programs to the new changes and +update them to make sure their programs continue to work correctly. + +NOTE: BPF subsystem specially reserves the 'bpf_' prefix for type names, in +order to introduce more special fields in the future. Hence, user programs must +avoid defining types with 'bpf_' prefix to not be broken in future releases. In +other words, no backwards compatibility is guaranteed if one using a type in BTF +with 'bpf_' prefix. + +Q: What is the compatibility story for special BPF types in local kptrs? +------------------------------------------------------------------------ +Q: Same as above, but for local kptrs (i.e. kptrs allocated using bpf_kptr_new +for user defined structures). Will the kernel preserve backwards compatibility +for these features? + +A: NO. + +Unlike map value types, there are no stability guarantees for this case. The +whole local kptr API itself is unstable (since it is exposed through kfuncs).
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 2/25 bpf: Allow specifying volatile type modifier for kptrs
In reply to Kumar Kartikeya DwivediThis is useful in particular to mark the pointer as volatile, so that compiler treats each load and store to the field as a volatile access. The alternative is having to define and use READ_ONCE and WRITE_ONCE in the BPF program.
--- include/linux/btf.h | 5 +++++ kernel/bpf/btf.c | 3 +++ 2 files changed, 8 insertions(+)
include/linux/btf.h +5 -0
@@ -288,6 +288,11 @@ static inline bool btf_type_is_typedef(const struct btf_type *t)return BTF_INFO_KIND (t->info) ==BTF_KIND_TYPEDEF ; } +static inline bool btf_type_is_volatile (const struct btf_type *t) +{ +return BTF_INFO_KIND (t->info) ==BTF_KIND_VOLATILE ; +} +static inline bool btf_type_is_func (const struct btf_type *t) {return BTF_INFO_KIND (t->info) ==BTF_KIND_FUNC ;
kernel/bpf/btf.c +3 -0
@@ -3225,6 +3225,9 @@ static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,enum bpf_kptr_type type;u32 res_id; +/* Permit modifiers on the pointer itself */ +if (btf_type_is_volatile (t)) + t =btf_type_by_id (btf, t->type);/* For PTR, sz is always == 8 */ if (!btf_type_is_ptr (t))return BTF_FIELD_IGNORE ;
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 3/25 bpf: Clobber stack slot when writing over spilled PTR_TO_BTF_ID
In reply to Kumar Kartikeya DwivediWhen support was added for spilled PTR_TO_BTF_ID to be accessed by helper memory access, the stack slot was not overwritten to STACK_MISC (and that too is only safe when env->allow_ptr_leaks is true).
This means that helpers who take ARG_PTR_TO_MEM and write to it may essentially overwrite the value while the verifier continues to track the slot for spilled register.
This can cause issues when PTR_TO_BTF_ID is spilled to stack, and then overwritten by helper write access, which can then be passed to BPF helpers or kfuncs.
Handle this by falling back to the case introduced in a later commit, which will also handle PTR_TO_BTF_ID along with other pointer types, i.e. cd17d38f8b28 ("bpf: Permits pointers on stack for helper calls").
Finally, include a comment on why REG_LIVE_WRITTEN is not being set when clobber is set to true. In short, the reason is that while when clobber is unset, we know that we won't be writing, when it is true, we *may* write to any of the stack slots in that range. It may be a partial or complete write, to just one or many stack slots.
We cannot be sure, hence to be conservative, we leave things as is and never set REG_LIVE_WRITTEN for any stack slot. However, clobber still needs to reset them to STACK_MISC assuming writes happened. However read marks still need to be propagated upwards from liveness point of view, as parent stack slot's contents may still continue to matter to child states.
--- kernel/bpf/verifier.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
kernel/bpf/verifier.c +5 -4
@@ -5154,10 +5154,6 @@ static int check_stack_range_initialized( goto mark; } -if (is_spilled_reg (&state->stack[spi]) && -base_type (state->stack[spi].spilled_ptr.type) ==PTR_TO_BTF_ID ) - goto mark; -if (is_spilled_reg (&state->stack[spi]) && (state->stack[spi].spilled_ptr.type ==SCALAR_VALUE || env->allow_ptr_leaks)) {
@@ -5188,6 +5184,11 @@ static int check_stack_range_initialized(mark_reg_read (env, &state->stack[spi].spilled_ptr, state->stack[spi].spilled_ptr.parent,REG_LIVE_READ64 ); +/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not +* be sure that whether stack slot is written to or not. Hence, +* we must still conservatively propagate reads upwards even if +* helper may write to the entire memory range. +*/ }return update_stack_depth (env, state, min_off); }
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 4/25 bpf: Fix slot type check in check_stack_write_var_off
In reply to Kumar Kartikeya DwivediFor the case where allow_ptr_leaks is false, code is checking whether slot type is STACK_INVALID and STACK_SPILL and rejecting other cases. This is a consequence of incorrectly checking for register type instead of the slot type (NOT_INIT and SCALAR_VALUE respectively). Fix the check.
--- kernel/bpf/verifier.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-)
kernel/bpf/verifier.c +11 -8
@@ -3181,14 +3181,17 @@ static int check_stack_write_var_off(struct bpf_verifier_env *env, stype = &state->stack[spi].slot_type[slot %BPF_REG_SIZE ];mark_stack_slot_scratched (env, spi); -if (!env->allow_ptr_leaks - && *stype !=NOT_INIT - && *stype !=SCALAR_VALUE ) { -/* Reject the write if there's are spilled pointers in -* range. If we didn't reject here, the ptr status -* would be erased below (even though not all slots are -* actually overwritten), possibly opening the door to -* leaks. +if (!env->allow_ptr_leaks && *stype !=STACK_MISC && *stype !=STACK_ZERO ) { +/* Reject the write if range we may write to has not +* been initialized beforehand. If we didn't reject +* here, the ptr status would be erased below (even +* though not all slots are actually overwritten), +* possibly opening the door to leaks. +* +* We do however catch STACK_INVALID case below, and +* only allow reading possibly uninitialized memory +* later for CAP_PERFMON, as the write may not happen to +* that slot. */ verbose (env,"spilled ptr in range of var-offset stack write; insn %d, ptr off: %d" , insn_idx, i);
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 5/25 bpf: Drop reg_type_may_be_refcounted_or_null
In reply to Kumar Kartikeya DwivediIt is not scalable to maintain a list of types that can have non-zero ref_obj_id. It is never set for scalars anyway, so just remove the conditional on register types and print it whenever it is non-zero.
--- kernel/bpf/verifier.c | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-)
kernel/bpf/verifier.c +1 -8
@@ -457,13 +457,6 @@ static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)map_value_has_spin_lock (reg->map_ptr); } -static bool reg_type_may_be_refcounted_or_null (enum bpf_reg_type type) -{ - type =base_type (type); -return type ==PTR_TO_SOCKET || type ==PTR_TO_TCP_SOCK || - type ==PTR_TO_MEM || type ==PTR_TO_BTF_ID ; -} -static bool type_is_rdonly_mem (u32 type) {return type &MEM_RDONLY ;
@@ -875,7 +868,7 @@ static void print_verifier_state(struct bpf_verifier_env *env,if (reg->id)verbose_a ("id=%d" , reg->id); -if (reg_type_may_be_refcounted_or_null (t) && reg->ref_obj_id) +if (reg->ref_obj_id)verbose_a ("ref_obj_id=%d" , reg->ref_obj_id);if (t !=SCALAR_VALUE )verbose_a ("off=%d" , reg->off);
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 6/25 bpf: Refactor kptr_off_tab into fields_tab
In reply to Kumar Kartikeya DwivediTo prepare the BPF verifier to handle special fields in both map values and program allocated types coming from program BTF, we need to refactor the kptr_off_tab handling code into something more generic and reusable across both cases to avoid code duplication.
Later patches also require passing this data to helpers at runtime, so that they can work on user defined types, initialize them, destruct them, etc.
The main observation is that both map values and such allocated types point to a type in program BTF, hence they can be handled similarly. We can prepare a field metadata table for both cases and store them in struct bpf_map or struct btf depending on the use case.
Hence, refactor the code into generic btf_type_fields and btf_field member structs. The btf_type_fields represents the fields of a specific btf_type in user BTF. The cnt indicates the number of special fields we successfully recognized, and field_mask is a bitmask of fields that were found, to enable quick determination of availability of a certain field.
Subsequently, refactor the rest of the code to work with these generic types, remove assumptions about kptr and kptr_off_tab, rename variables to more meaningful names, etc.
--- include/linux/bpf.h | 103 +++++++++++++------- include/linux/btf.h | 4 +- kernel/bpf/arraymap.c | 13 ++- kernel/bpf/btf.c | 64 ++++++------- kernel/bpf/hashtab.c | 14 ++- kernel/bpf/map_in_map.c | 13 ++- kernel/bpf/syscall.c | 203 +++++++++++++++++++++++----------------- kernel/bpf/verifier.c | 96 ++++++++++--------- 8 files changed, 289 insertions(+), 221 deletions(-)
include/linux/bpf.h +69 -34
@@ -164,35 +164,41 @@ struct bpf_map_ops { };enum { -/* Support at most 8 pointers in a BPF map value */ -BPF_MAP_VALUE_OFF_MAX =8 , -BPF_MAP_OFF_ARR_MAX =BPF_MAP_VALUE_OFF_MAX + +/* Support at most 8 pointers in a BTF type */ +BTF_FIELDS_MAX =8 , +BPF_MAP_OFF_ARR_MAX =BTF_FIELDS_MAX +1 +/* for bpf_spin_lock */ 1 ,/* for bpf_timer */ }; -enum bpf_kptr_type { -BPF_KPTR_UNREF , -BPF_KPTR_REF , +enum btf_field_type { +BPF_KPTR_UNREF = (1 <<2 ), +BPF_KPTR_REF = (1 <<3 ), +BPF_KPTR =BPF_KPTR_UNREF |BPF_KPTR_REF , }; -struct bpf_map_value_off_desc { +struct btf_field_kptr { +struct btf *btf; +struct module *module; +btf_dtor_kfunc_t dtor; +u32 btf_id; +}; + +struct btf_field {u32 offset; -enum bpf_kptr_type type; -struct { -struct btf *btf; -struct module *module; -btf_dtor_kfunc_t dtor; -u32 btf_id; - } kptr; +enum btf_field_type type; +union { +struct btf_field_kptr kptr; + }; }; -struct bpf_map_value_off { -u32 nr_off; -struct bpf_map_value_off_desc off[]; +struct btf_type_fields { +u32 cnt; +u32 field_mask; +struct btf_field fields[]; }; -struct bpf_map_off_arr { +struct btf_type_fields_off {u32 cnt;u32 field_off[BPF_MAP_OFF_ARR_MAX ];u8 field_sz[BPF_MAP_OFF_ARR_MAX ];
@@ -214,7 +220,7 @@ struct bpf_map {u64 map_extra;/* any per-map-type extra fields */ u32 map_flags;int spin_lock_off;/* >=0 valid offset, <0 error */ -struct bpf_map_value_off *kptr_off_tab; +struct btf_type_fields *fields_tab;int timer_off;/* >=0 valid offset, <0 error */ u32 id;int numa_node;
@@ -226,7 +232,7 @@ struct bpf_map {struct obj_cgroup *objcg;#endif char name[BPF_OBJ_NAME_LEN ]; -struct bpf_map_off_arr *off_arr; +struct btf_type_fields_off *off_arr;/* The 3rd and 4th cacheline with misc members to avoid false sharing * particularly with refcounting. */
@@ -250,6 +256,37 @@ struct bpf_map {bool frozen;/* write-once; write-protected by freeze_mutex */ }; +static inline u32 btf_field_type_size (enum btf_field_type type) +{ +switch (type) { +case BPF_KPTR_UNREF : +case BPF_KPTR_REF : +return sizeof (u64); +default : +WARN_ON_ONCE (1 ); +return 0 ; + } +} + +static inline u32 btf_field_type_align (enum btf_field_type type) +{ +switch (type) { +case BPF_KPTR_UNREF : +case BPF_KPTR_REF : +return __alignof__(u64 ); +default : +WARN_ON_ONCE (1 ); +return 0 ; + } +} + +static inline bool btf_type_fields_has_field (const struct btf_type_fields *tab,enum btf_field_type type) +{ +if (IS_ERR_OR_NULL (tab)) +return false; +return tab->field_mask & type; +} +static inline bool map_value_has_spin_lock (const struct bpf_map *map) {return map->spin_lock_off >=0 ;
@@ -260,23 +297,19 @@ static inline bool map_value_has_timer(const struct bpf_map *map)return map->timer_off >=0 ; } -static inline bool map_value_has_kptrs (const struct bpf_map *map) -{ -return !IS_ERR_OR_NULL (map->kptr_off_tab); -} -static inline void check_and_init_map_value (struct bpf_map *map,void *dst) {if (unlikely (map_value_has_spin_lock (map)))memset (dst + map->spin_lock_off,0 ,sizeof (struct bpf_spin_lock ));if (unlikely (map_value_has_timer (map)))memset (dst + map->timer_off,0 ,sizeof (struct bpf_timer )); -if (unlikely (map_value_has_kptrs (map))) { -struct bpf_map_value_off *tab = map->kptr_off_tab; +if (!IS_ERR_OR_NULL (map->fields_tab)) { +struct btf_field *fields = map->fields_tab->fields; +u32 cnt = map->fields_tab->cnt;int i; -for (i =0 ; i < tab->nr_off; i++) - *(u64 *)(dst + tab->off[i].offset) =0 ; +for (i =0 ; i < cnt; i++) +memset (dst + fields[i].offset,0 ,btf_field_type_size (fields[i].type)); } }
@@ -1691,11 +1724,13 @@ void bpf_prog_put(struct bpf_prog *prog);void bpf_prog_free_id (struct bpf_prog *prog,bool do_idr_lock);void bpf_map_free_id (struct bpf_map *map,bool do_idr_lock); -struct bpf_map_value_off_desc *bpf_map_kptr_off_contains (struct bpf_map *map,u32 offset); -void bpf_map_free_kptr_off_tab (struct bpf_map *map); -struct bpf_map_value_off *bpf_map_copy_kptr_off_tab (const struct bpf_map *map); -bool bpf_map_equal_kptr_off_tab (const struct bpf_map *map_a,const struct bpf_map *map_b); -void bpf_map_free_kptrs (struct bpf_map *map,void *map_value); +struct btf_field *btf_type_fields_find (const struct btf_type_fields *tab, +u32 offset,enum btf_field_type type); +void btf_type_fields_free (struct btf_type_fields *tab); +void bpf_map_free_fields_tab (struct bpf_map *map); +struct btf_type_fields *btf_type_fields_dup (const struct btf_type_fields *tab); +bool btf_type_fields_equal (const struct btf_type_fields *tab_a,const struct btf_type_fields *tab_b); +void bpf_obj_free_fields (const struct btf_type_fields *tab,void *obj);struct bpf_map *bpf_map_get (u32 ufd);struct bpf_map *bpf_map_get_with_uref (u32 ufd);
include/linux/btf.h +2 -2
@@ -163,8 +163,8 @@ bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s, u32 expected_offset, u32 expected_size);int btf_find_spin_lock (const struct btf *btf,const struct btf_type *t);int btf_find_timer (const struct btf *btf,const struct btf_type *t); -struct bpf_map_value_off *btf_parse_kptrs (const struct btf *btf, -const struct btf_type *t); +struct btf_type_fields *btf_parse_fields (const struct btf *btf, +const struct btf_type *t);bool btf_type_is_void (const struct btf_type *t);s32 btf_find_by_name_kind (const struct btf *btf,const char *name,u8 kind); const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
kernel/bpf/arraymap.c +6 -7
@@ -310,8 +310,7 @@ static void check_and_free_fields(struct bpf_array *arr, void *val) {if (map_value_has_timer (&arr->map))bpf_timer_cancel_and_free (val + arr->map.timer_off); -if (map_value_has_kptrs (&arr->map)) -bpf_map_free_kptrs (&arr->map, val); +bpf_obj_free_fields (arr->map.fields_tab, val); }/* Called from syscall or from eBPF program */
@@ -409,7 +408,7 @@ static void array_map_free_timers(struct bpf_map *map) struct bpf_array *array = container_of(map, struct bpf_array, map);int i; -/* We don't reset or free kptr on uref dropping to zero. */ +/* We don't reset or free fields other than timer on uref dropping to zero. */ if (!map_value_has_timer (map))return ;
@@ -423,22 +422,22 @@ static void array_map_free(struct bpf_map *map) struct bpf_array *array = container_of(map, struct bpf_array, map);int i; -if (map_value_has_kptrs (map)) { +if (!IS_ERR_OR_NULL (map->fields_tab)) {if (array->map.map_type ==BPF_MAP_TYPE_PERCPU_ARRAY ) {for (i =0 ; i < array->map.max_entries; i++) {void __percpu *pptr = array->pptrs[i & array->index_mask];int cpu;for_each_possible_cpu (cpu) { -bpf_map_free_kptrs (map,per_cpu_ptr (pptr, cpu)); +bpf_obj_free_fields (map->fields_tab,per_cpu_ptr (pptr, cpu));cond_resched (); } } }else {for (i =0 ; i < array->map.max_entries; i++) -bpf_map_free_kptrs (map,array_map_elem_ptr (array, i)); +bpf_obj_free_fields (map->fields_tab,array_map_elem_ptr (array, i)); } -bpf_map_free_kptr_off_tab (map); +bpf_map_free_fields_tab (map); }if (array->map.map_type ==BPF_MAP_TYPE_PERCPU_ARRAY )
kernel/bpf/btf.c +30 -34
151 lines not on this page · raw message
kernel/bpf/hashtab.c +6 -8
@@ -238,21 +238,20 @@ static void htab_free_prealloced_timers(struct bpf_htab *htab) } } -static void htab_free_prealloced_kptrs (struct bpf_htab *htab) +static void htab_free_prealloced_fields (struct bpf_htab *htab) {u32 num_entries = htab->map.max_entries;int i; -if (!map_value_has_kptrs (&htab->map)) +if (IS_ERR_OR_NULL (htab->map.fields_tab))return ;if (htab_has_extra_elems (htab)) num_entries +=num_possible_cpus (); -for (i =0 ; i < num_entries; i++) {struct htab_elem *elem; elem =get_htab_elem (htab, i); -bpf_map_free_kptrs (&htab->map, elem->key +round_up (htab->map.key_size,8 )); +bpf_obj_free_fields (htab->map.fields_tab, elem->key +round_up (htab->map.key_size,8 ));cond_resched (); } }
@@ -766,8 +765,7 @@ static void check_and_free_fields(struct bpf_htab *htab,if (map_value_has_timer (&htab->map))bpf_timer_cancel_and_free (map_value + htab->map.timer_off); -if (map_value_has_kptrs (&htab->map)) -bpf_map_free_kptrs (&htab->map, map_value); +bpf_obj_free_fields (htab->map.fields_tab, map_value); }/* It is called from the bpf_lru_list when the LRU needs to delete
@@ -1517,11 +1515,11 @@ static void htab_map_free(struct bpf_map *map)if (!htab_is_prealloc (htab)) {delete_all_elements (htab); }else { -htab_free_prealloced_kptrs (htab); +htab_free_prealloced_fields (htab);prealloc_destroy (htab); } -bpf_map_free_kptr_off_tab (map); +bpf_map_free_fields_tab (map);free_percpu (htab->extra_elems);bpf_map_area_free (htab->buckets);bpf_mem_alloc_destroy (&htab->pcpu_ma);
kernel/bpf/map_in_map.c +10 -3
@@ -52,7 +52,14 @@ struct bpf_map *bpf_map_meta_alloc(int inner_map_ufd) inner_map_meta->max_entries = inner_map->max_entries; inner_map_meta->spin_lock_off = inner_map->spin_lock_off; inner_map_meta->timer_off = inner_map->timer_off; - inner_map_meta->kptr_off_tab =bpf_map_copy_kptr_off_tab (inner_map); + inner_map_meta->fields_tab =btf_type_fields_dup (inner_map->fields_tab); +if (IS_ERR (inner_map_meta->fields_tab)) { +/* btf_type_fields returns NULL or valid pointer in case of +* invalid/empty/valid, but ERR_PTR in case of errors. +*/ +fdput (f); +return ERR_CAST (inner_map_meta->fields_tab); + }if (inner_map->btf) {btf_get (inner_map->btf); inner_map_meta->btf = inner_map->btf;
@@ -72,7 +79,7 @@ struct bpf_map *bpf_map_meta_alloc(int inner_map_ufd)void bpf_map_meta_free (struct bpf_map *map_meta) { -bpf_map_free_kptr_off_tab (map_meta); +bpf_map_free_fields_tab (map_meta);btf_put (map_meta->btf);kfree (map_meta); }
@@ -86,7 +93,7 @@ bool bpf_map_meta_equal(const struct bpf_map *meta0, meta0->value_size == meta1->value_size && meta0->timer_off == meta1->timer_off && meta0->map_flags == meta1->map_flags && -bpf_map_equal_kptr_off_tab (meta0, meta1); +btf_type_fields_equal (meta0->fields_tab, meta1->fields_tab); } void *bpf_map_fd_get_ptr(struct bpf_map *map,
kernel/bpf/syscall.c +119 -84
308 lines not on this page · raw message
kernel/bpf/verifier.c +47 -49
229 lines not on this page · raw message
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 7/25 bpf: Consolidate spin_lock, timer management into fields_tab
In reply to Kumar Kartikeya DwivediNow that kptr_off_tab has been refactored into fields_tab, and can hold more than one specific field type, accomodate bpf_spin_lock and bpf_timer as well.
While they don't require any more metadata than offset, having all special fields in one place allows us to share the same code for allocated user defined types and handle both map values and these allocated objects in a similar fashion.
As an optimization, we still keep spin_lock_off and timer_off offsets in the btf_type_fields structure, just to avoid having to find the btf_field struct each time their offset is needed. This is mostly needed to manipulate such objects in a map value at runtime. It's ok to hardcode just one offset as more than one field is disallowed.
--- include/linux/bpf.h | 53 +++--- include/linux/btf.h | 3 +- kernel/bpf/arraymap.c | 19 +- kernel/bpf/bpf_local_storage.c | 2 +- kernel/bpf/btf.c | 323 ++++++++++++++++++--------------- kernel/bpf/hashtab.c | 26 +-- kernel/bpf/helpers.c | 6 +- kernel/bpf/local_storage.c | 2 +- kernel/bpf/map_in_map.c | 5 +- kernel/bpf/syscall.c | 111 +++++------ kernel/bpf/verifier.c | 83 +++------ net/core/bpf_sk_storage.c | 4 +- 12 files changed, 308 insertions(+), 329 deletions(-)
include/linux/bpf.h +32 -21
@@ -165,13 +165,13 @@ struct bpf_map_ops {enum {/* Support at most 8 pointers in a BTF type */ -BTF_FIELDS_MAX =8 , -BPF_MAP_OFF_ARR_MAX =BTF_FIELDS_MAX + -1 +/* for bpf_spin_lock */ -1 ,/* for bpf_timer */ +BTF_FIELDS_MAX =10 , +BPF_MAP_OFF_ARR_MAX =BTF_FIELDS_MAX , };enum btf_field_type { +BPF_SPIN_LOCK = (1 <<0 ), +BPF_TIMER = (1 <<1 ),BPF_KPTR_UNREF = (1 <<2 ),BPF_KPTR_REF = (1 <<3 ),BPF_KPTR =BPF_KPTR_UNREF |BPF_KPTR_REF ,
@@ -195,6 +195,8 @@ struct btf_field {struct btf_type_fields {u32 cnt;u32 field_mask; +int spin_lock_off; +int timer_off;struct btf_field fields[]; };
@@ -219,10 +221,8 @@ struct bpf_map {u32 max_entries;u64 map_extra;/* any per-map-type extra fields */ u32 map_flags; -int spin_lock_off;/* >=0 valid offset, <0 error */ -struct btf_type_fields *fields_tab; -int timer_off;/* >=0 valid offset, <0 error */ u32 id; +struct btf_type_fields *fields_tab;int numa_node;u32 btf_key_type_id;u32 btf_value_type_id;
@@ -256,9 +256,29 @@ struct bpf_map {bool frozen;/* write-once; write-protected by freeze_mutex */ }; +static inline const char *btf_field_type_name (enum btf_field_type type) +{ +switch (type) { +case BPF_SPIN_LOCK : +return "bpf_spin_lock" ; +case BPF_TIMER : +return "bpf_timer" ; +case BPF_KPTR_UNREF : +case BPF_KPTR_REF : +return "kptr" ; +default : +WARN_ON_ONCE (1 ); +return "unknown" ; + } +} +static inline u32 btf_field_type_size (enum btf_field_type type) {switch (type) { +case BPF_SPIN_LOCK : +return sizeof (struct bpf_spin_lock ); +case BPF_TIMER : +return sizeof (struct bpf_timer );case BPF_KPTR_UNREF :case BPF_KPTR_REF :return sizeof (u64);
@@ -271,6 +291,10 @@ static inline u32 btf_field_type_size(enum btf_field_type type)static inline u32 btf_field_type_align (enum btf_field_type type) {switch (type) { +case BPF_SPIN_LOCK : +return __alignof__(struct bpf_spin_lock ); +case BPF_TIMER : +return __alignof__(struct bpf_timer );case BPF_KPTR_UNREF :case BPF_KPTR_REF :return __alignof__(u64 );
@@ -287,22 +311,8 @@ static inline bool btf_type_fields_has_field(const struct btf_type_fields *tab,return tab->field_mask & type; } -static inline bool map_value_has_spin_lock (const struct bpf_map *map) -{ -return map->spin_lock_off >=0 ; -} - -static inline bool map_value_has_timer (const struct bpf_map *map) -{ -return map->timer_off >=0 ; -} -static inline void check_and_init_map_value (struct bpf_map *map,void *dst) { -if (unlikely (map_value_has_spin_lock (map))) -memset (dst + map->spin_lock_off,0 ,sizeof (struct bpf_spin_lock )); -if (unlikely (map_value_has_timer (map))) -memset (dst + map->timer_off,0 ,sizeof (struct bpf_timer ));if (!IS_ERR_OR_NULL (map->fields_tab)) {struct btf_field *fields = map->fields_tab->fields;u32 cnt = map->fields_tab->cnt;
@@ -1730,6 +1740,7 @@ void btf_type_fields_free(struct btf_type_fields *tab);void bpf_map_free_fields_tab (struct bpf_map *map);struct btf_type_fields *btf_type_fields_dup (const struct btf_type_fields *tab);bool btf_type_fields_equal (const struct btf_type_fields *tab_a,const struct btf_type_fields *tab_b); +void bpf_obj_free_timer (const struct btf_type_fields *tab,void *obj);void bpf_obj_free_fields (const struct btf_type_fields *tab,void *obj);struct bpf_map *bpf_map_get (u32 ufd);
include/linux/btf.h +2 -1
@@ -164,7 +164,8 @@ bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,int btf_find_spin_lock (const struct btf *btf,const struct btf_type *t);int btf_find_timer (const struct btf *btf,const struct btf_type *t);struct btf_type_fields *btf_parse_fields (const struct btf *btf, -const struct btf_type *t); +const struct btf_type *t, +u32 field_mask,u32 value_size);bool btf_type_is_void (const struct btf_type *t);s32 btf_find_by_name_kind (const struct btf *btf,const char *name,u8 kind); const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
kernel/bpf/arraymap.c +6 -13
@@ -306,13 +306,6 @@ static int array_map_get_next_key(struct bpf_map *map, void *key, void *next_keyreturn 0 ; } -static void check_and_free_fields (struct bpf_array *arr,void *val) -{ -if (map_value_has_timer (&arr->map)) -bpf_timer_cancel_and_free (val + arr->map.timer_off); -bpf_obj_free_fields (arr->map.fields_tab, val); -} -/* Called from syscall or from eBPF program */ static int array_map_update_elem (struct bpf_map *map,void *key,void *value,u64 map_flags)
@@ -334,13 +327,13 @@ static int array_map_update_elem(struct bpf_map *map, void *key, void *value,return -EEXIST ;if (unlikely ((map_flags &BPF_F_LOCK ) && - !map_value_has_spin_lock (map))) + !btf_type_fields_has_field (map->fields_tab,BPF_SPIN_LOCK )))return -EINVAL ;if (array->map.map_type ==BPF_MAP_TYPE_PERCPU_ARRAY ) { val =this_cpu_ptr (array->pptrs[index & array->index_mask]);copy_map_value (map, val, value); -check_and_free_fields (array, val); +bpf_obj_free_fields (array->map.fields_tab, val); }else { val = array->value + (u64 )array->elem_size * (index & array->index_mask);
@@ -348,7 +341,7 @@ static int array_map_update_elem(struct bpf_map *map, void *key, void *value,copy_map_value_locked (map, val, value, false); elsecopy_map_value (map ,val ,value ); -check_and_free_fields (array, val); +bpf_obj_free_fields (array->map.fields_tab, val); }return 0 ; }
@@ -385,7 +378,7 @@ int bpf_percpu_array_update(struct bpf_map *map, void *key, void *value, pptr = array->pptrs[index & array->index_mask];for_each_possible_cpu (cpu) {copy_map_value_long (map,per_cpu_ptr (pptr, cpu), value + off); -check_and_free_fields (array,per_cpu_ptr (pptr, cpu)); +bpf_obj_free_fields (array->map.fields_tab,per_cpu_ptr (pptr, cpu)); off += size; }rcu_read_unlock ();
@@ -409,11 +402,11 @@ static void array_map_free_timers(struct bpf_map *map)int i;/* We don't reset or free fields other than timer on uref dropping to zero. */ -if (!map_value_has_timer (map)) +if (!btf_type_fields_has_field (map->fields_tab,BPF_TIMER ))return ;for (i =0 ; i < array->map.max_entries; i++) -bpf_timer_cancel_and_free (array_map_elem_ptr (array, i) + map->timer_off); +bpf_obj_free_timer (map->fields_tab,array_map_elem_ptr (array, i)); }/* Called when map->refcnt goes to zero, either from workqueue or from syscall */
kernel/bpf/bpf_local_storage.c +1 -1
@@ -372,7 +372,7 @@ bpf_local_storage_update(void *owner, struct bpf_local_storage_map *smap,if (unlikely ((map_flags & ~BPF_F_LOCK ) >BPF_EXIST ) ||/* BPF_F_LOCK can only be used in a value with spin_lock */ unlikely ((map_flags &BPF_F_LOCK ) && - !map_value_has_spin_lock (&smap->map))) + !btf_type_fields_has_field (smap->map.fields_tab,BPF_SPIN_LOCK )))return ERR_PTR (-EINVAL );if (gfp_flags ==GFP_KERNEL && (map_flags & ~BPF_F_LOCK ) !=BPF_NOEXIST )
kernel/bpf/btf.c +179 -144
435 lines not on this page · raw message
kernel/bpf/hashtab.c +10 -16
@@ -222,7 +222,7 @@ static void htab_free_prealloced_timers(struct bpf_htab *htab)u32 num_entries = htab->map.max_entries;int i; -if (!map_value_has_timer (&htab->map)) +if (!btf_type_fields_has_field (htab->map.fields_tab,BPF_TIMER ))return ;if (htab_has_extra_elems (htab)) num_entries +=num_possible_cpus ();
@@ -231,9 +231,8 @@ static void htab_free_prealloced_timers(struct bpf_htab *htab)struct htab_elem *elem; elem =get_htab_elem (htab, i); -bpf_timer_cancel_and_free (elem->key + -round_up (htab->map.key_size,8 ) + - htab->map.timer_off); +bpf_obj_free_timer (htab->map.fields_tab, elem->key + +round_up (htab->map.key_size,8 ));cond_resched (); } }
@@ -763,8 +762,6 @@ static void check_and_free_fields(struct bpf_htab *htab, {void *map_value = elem->key +round_up (htab->map.key_size,8 ); -if (map_value_has_timer (&htab->map)) -bpf_timer_cancel_and_free (map_value + htab->map.timer_off);bpf_obj_free_fields (htab->map.fields_tab, map_value); }
@@ -1089,7 +1086,7 @@ static int htab_map_update_elem(struct bpf_map *map, void *key, void *value, head = &b->head;if (unlikely (map_flags &BPF_F_LOCK )) { -if (unlikely (!map_value_has_spin_lock (map))) +if (unlikely (!btf_type_fields_has_field (map->fields_tab,BPF_SPIN_LOCK )))return -EINVAL ;/* find an element without taking the bucket lock */ l_old = lookup_nulls_elem_raw(head, hash, key, key_size,
@@ -1472,12 +1469,9 @@ static void htab_free_malloced_timers(struct bpf_htab *htab)struct htab_elem *l;hlist_nulls_for_each_entry (l, n, head, hash_node) { -/* We don't reset or free kptr on uref dropping to zero, -* hence just free timer. -*/ -bpf_timer_cancel_and_free (l->key + -round_up (htab->map.key_size,8 ) + - htab->map.timer_off); +/* We only free timer on uref dropping to zero */ +bpf_obj_free_timer (htab->map.fields_tab, l->key + +round_up (htab->map.key_size,8 )); }cond_resched_rcu (); }
@@ -1488,8 +1482,8 @@ static void htab_map_free_timers(struct bpf_map *map) { struct bpf_htab *htab = container_of(map, struct bpf_htab, map); -/* We don't reset or free kptr on uref dropping to zero. */ -if (!map_value_has_timer (&htab->map)) +/* We only free timer on uref dropping to zero */ +if (!btf_type_fields_has_field (htab->map.fields_tab,BPF_TIMER ))return ;if (!htab_is_prealloc (htab))htab_free_malloced_timers (htab);
@@ -1673,7 +1667,7 @@ __htab_map_lookup_and_delete_batch(struct bpf_map *map, elem_map_flags = attr->batch.elem_flags;if ((elem_map_flags & ~BPF_F_LOCK ) || - ((elem_map_flags &BPF_F_LOCK ) && !map_value_has_spin_lock (map))) + ((elem_map_flags &BPF_F_LOCK ) && !btf_type_fields_has_field (map->fields_tab,BPF_SPIN_LOCK )))return -EINVAL ; map_flags = attr->batch.flags;
kernel/bpf/helpers.c +3 -3
@@ -366,9 +366,9 @@ void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,struct bpf_spin_lock *lock;if (lock_src) - lock = src + map->spin_lock_off; + lock = src + map->fields_tab->spin_lock_off;else - lock = dst + map->spin_lock_off; + lock = dst + map->fields_tab->spin_lock_off;preempt_disable ();__bpf_spin_lock_irqsave (lock);copy_map_value (map, dst, src);
@@ -1169,7 +1169,7 @@ BPF_CALL_3(bpf_timer_init, struct bpf_timer_kern *, timer, struct bpf_map *, map ret = -ENOMEM ; goto out; } - t->value = (void *)timer - map->timer_off; + t->value = (void *)timer - map->fields_tab->timer_off; t->map = map; t->prog =NULL ;rcu_assign_pointer (t->callback_fn,NULL );
kernel/bpf/local_storage.c +1 -1
@@ -151,7 +151,7 @@ static int cgroup_storage_update_elem(struct bpf_map *map, void *key,return -EINVAL ;if (unlikely ((flags &BPF_F_LOCK ) && - !map_value_has_spin_lock (map))) + !btf_type_fields_has_field (map->fields_tab,BPF_SPIN_LOCK )))return -EINVAL ; storage = cgroup_storage_lookup((struct bpf_cgroup_storage_map *)map,
kernel/bpf/map_in_map.c +1 -4
@@ -29,7 +29,7 @@ struct bpf_map *bpf_map_meta_alloc(int inner_map_ufd)return ERR_PTR (-ENOTSUPP ); } -if (map_value_has_spin_lock (inner_map)) { +if (btf_type_fields_has_field (inner_map->fields_tab,BPF_SPIN_LOCK )) {fdput (f);return ERR_PTR (-ENOTSUPP ); }
@@ -50,8 +50,6 @@ struct bpf_map *bpf_map_meta_alloc(int inner_map_ufd) inner_map_meta->value_size = inner_map->value_size; inner_map_meta->map_flags = inner_map->map_flags; inner_map_meta->max_entries = inner_map->max_entries; - inner_map_meta->spin_lock_off = inner_map->spin_lock_off; - inner_map_meta->timer_off = inner_map->timer_off; inner_map_meta->fields_tab =btf_type_fields_dup (inner_map->fields_tab);if (IS_ERR (inner_map_meta->fields_tab)) {/* btf_type_fields returns NULL or valid pointer in case of
@@ -91,7 +89,6 @@ bool bpf_map_meta_equal(const struct bpf_map *meta0,return meta0->map_type == meta1->map_type && meta0->key_size == meta1->key_size && meta0->value_size == meta1->value_size && - meta0->timer_off == meta1->timer_off && meta0->map_flags == meta1->map_flags &&btf_type_fields_equal (meta0->fields_tab, meta1->fields_tab); }
kernel/bpf/syscall.c +49 -62
223 lines not on this page · raw message
kernel/bpf/verifier.c +22 -61
154 lines not on this page · raw message
net/core/bpf_sk_storage.c +2 -2
@@ -176,7 +176,7 @@ bpf_sk_storage_clone_elem(struct sock *newsk,if (!copy_selem)return NULL ; -if (map_value_has_spin_lock (&smap->map)) +if (btf_type_fields_has_field (smap->map.fields_tab,BPF_SPIN_LOCK ))copy_map_value_locked (&smap->map,SDATA (copy_selem)->data,SDATA (selem)->data, true);else
@@ -595,7 +595,7 @@ static int diag_get(struct bpf_local_storage_data *sdata, struct sk_buff *skb)if (!nla_value) goto errout; -if (map_value_has_spin_lock (&smap->map)) +if (btf_type_fields_has_field (smap->map.fields_tab,BPF_SPIN_LOCK ))copy_map_value_locked (&smap->map,nla_data (nla_value), sdata->data, true);else
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 8/25 bpf: Refactor map->off_arr handling
In reply to Kumar Kartikeya DwivediRefactor map->off_arr handling into generic functions that can work on their own without hardcoding map specific code. The btf_type_fields_off structure is now returned from btf_parse_fields_off, which can be reused later for types in program BTF.
All functions like copy_map_value, zero_map_value call generic underlying functions so that they can also be reused later for copying to values allocated in programs which encode specific fields.
Later, some helper functions will also require access to this off_arr structure to be able to skip over special fields at runtime.
--- include/linux/bpf.h | 41 ++++++++++++++----------- include/linux/btf.h | 1 + kernel/bpf/btf.c | 55 ++++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 71 +++++--------------------------------------- 4 files changed, 87 insertions(+), 81 deletions(-)
include/linux/bpf.h +24 -17
@@ -340,55 +340,62 @@ static inline void bpf_long_memcpy(void *dst, const void *src, u32 size) }/* copy everything but bpf_spin_lock, bpf_timer, and kptrs. There could be one of each. */ -static inline void __copy_map_value (struct bpf_map *map,void *dst,void *src,bool long_memcpy) +static inline void bpf_obj_memcpy (struct btf_type_fields_off *off_arr, +void *dst,void *src,u32 size, +bool long_memcpy) {u32 curr_off =0 ;int i; -if (likely (!map->off_arr)) { +if (likely (!off_arr)) {if (long_memcpy) -bpf_long_memcpy (dst, src,round_up (map->value_size,8 )); +bpf_long_memcpy (dst, src,round_up (size,8 ));else -memcpy (dst, src, map->value_size); +memcpy (dst, src, size);return ; } -for (i =0 ; i < map->off_arr->cnt; i++) { -u32 next_off = map->off_arr->field_off[i]; +for (i =0 ; i < off_arr->cnt; i++) { +u32 next_off = off_arr->field_off[i];memcpy (dst + curr_off, src + curr_off, next_off - curr_off); - curr_off += map->off_arr->field_sz[i]; + curr_off += off_arr->field_sz[i]; } -memcpy (dst + curr_off, src + curr_off, map->value_size - curr_off); +memcpy (dst + curr_off, src + curr_off, size - curr_off); }static inline void copy_map_value (struct bpf_map *map,void *dst,void *src) { -__copy_map_value (map, dst, src, false); +bpf_obj_memcpy (map->off_arr, dst, src, map->value_size, false); }static inline void copy_map_value_long (struct bpf_map *map,void *dst,void *src) { -__copy_map_value (map, dst, src, true); +bpf_obj_memcpy (map->off_arr, dst, src, map->value_size, true); } -static inline void zero_map_value (struct bpf_map *map,void *dst) +static inline void bpf_obj_memzero (struct btf_type_fields_off *off_arr,void *dst,u32 size) {u32 curr_off =0 ;int i; -if (likely (!map->off_arr)) { -memset (dst,0 , map->value_size); +if (likely (!off_arr)) { +memset (dst,0 , size);return ; } -for (i =0 ; i < map->off_arr->cnt; i++) { -u32 next_off = map->off_arr->field_off[i]; +for (i =0 ; i < off_arr->cnt; i++) { +u32 next_off = off_arr->field_off[i];memset (dst + curr_off,0 , next_off - curr_off); - curr_off += map->off_arr->field_sz[i]; + curr_off += off_arr->field_sz[i]; } -memset (dst + curr_off,0 , map->value_size - curr_off); +memset (dst + curr_off,0 , size - curr_off); +} + +static inline void zero_map_value (struct bpf_map *map,void *dst) +{ +bpf_obj_memzero (map->off_arr, dst, map->value_size); } void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
include/linux/btf.h +1 -0
@@ -166,6 +166,7 @@ int btf_find_timer(const struct btf *btf, const struct btf_type *t);struct btf_type_fields *btf_parse_fields (const struct btf *btf,const struct btf_type *t,u32 field_mask,u32 value_size); +struct btf_type_fields_off *btf_parse_fields_off (struct btf_type_fields *tab);bool btf_type_is_void (const struct btf_type *t);s32 btf_find_by_name_kind (const struct btf *btf,const char *name,u8 kind); const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
kernel/bpf/btf.c +55 -0
61 lines not on this page · raw message
kernel/bpf/syscall.c +7 -64
90 lines not on this page · raw message
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 9/25 bpf: Support bpf_list_head in map values
In reply to Kumar Kartikeya DwivediAdd the basic support on the map side to parse, recognize, verify, and build metadata table for a new special field of the type struct bpf_list_head. To parameterize the bpf_list_head for a certain value type and the list_node member it will accept in that value type, we use BTF declaration tags.
The definition of bpf_list_head in a map value will be done as follows:
struct foo {
struct bpf_list_node node;
int data;
};struct map_value {
struct bpf_list_head head __contains(foo, node);
};Then, the bpf_list_head only allows adding to the list 'head' using the bpf_list_node 'node' for the type struct foo.
The 'contains' annotation is a BTF declaration tag composed of four parts, "contains:kind:name:node" where the kind and name is then used to look up the type in the map BTF. The node defines name of the member in this type that has the type struct bpf_list_node, which is actually used for linking into the linked list. For now, 'kind' part is hardcoded as struct.
This allows building intrusive linked lists in BPF, using container_of to obtain pointer to entry, while being completely type safe from the perspective of the verifier. The verifier knows exactly the type of the nodes, and knows that list helpers return that type at some fixed offset where the bpf_list_node member used for this list exists. The verifier also uses this information to disallow adding types that are not accepted by a certain list.
For now, no elements can be added to such lists. Support for that is coming in future patches, hence draining and freeing items is done with a TODO that will be resolved in a future patch.
--- include/linux/bpf.h | 19 +++ kernel/bpf/btf.c | 147 +++++++++++++++++- kernel/bpf/helpers.c | 29 ++++ kernel/bpf/syscall.c | 22 ++- kernel/bpf/verifier.c | 7 + .../testing/selftests/bpf/bpf_experimental.h | 23 +++ 6 files changed, 243 insertions(+), 4 deletions(-) create mode 100644 tools/testing/selftests/bpf/bpf_experimental.h
include/linux/bpf.h +19 -0
@@ -27,6 +27,8 @@#include <linux/bpfptr.h> #include <linux/btf.h> #include <linux/rcupdate_trace.h> +/* Experimental BPF APIs header for type definitions */ +#include "../tools/testing/selftests/bpf/bpf_experimental.h" struct bpf_verifier_env ;struct bpf_verifier_log ;
@@ -175,6 +177,7 @@ enum btf_field_type {BPF_KPTR_UNREF = (1 <<2 ),BPF_KPTR_REF = (1 <<3 ),BPF_KPTR =BPF_KPTR_UNREF |BPF_KPTR_REF , + BPF_LIST_HEAD = (1 << 4), }; struct btf_field_kptr {
@@ -184,11 +187,18 @@ struct btf_field_kptr {u32 btf_id; }; +struct btf_field_list_head { +struct btf *btf; +u32 value_btf_id; +u32 node_offset; +}; +struct btf_field {u32 offset;enum btf_field_type type;union {struct btf_field_kptr kptr; +struct btf_field_list_head list_head; }; };
@@ -266,6 +276,8 @@ static inline const char *btf_field_type_name(enum btf_field_type type)case BPF_KPTR_UNREF :case BPF_KPTR_REF :return "kptr" ; +case BPF_LIST_HEAD : +return "bpf_list_head" ;default :WARN_ON_ONCE (1 );return "unknown" ;
@@ -282,6 +294,8 @@ static inline u32 btf_field_type_size(enum btf_field_type type)case BPF_KPTR_UNREF :case BPF_KPTR_REF :return sizeof (u64); +case BPF_LIST_HEAD : +return sizeof (struct bpf_list_head );default :WARN_ON_ONCE (1 );return 0 ;
@@ -298,6 +312,8 @@ static inline u32 btf_field_type_align(enum btf_field_type type)case BPF_KPTR_UNREF :case BPF_KPTR_REF :return __alignof__(u64 ); +case BPF_LIST_HEAD : +return __alignof__(struct bpf_list_head );default :WARN_ON_ONCE (1 );return 0 ;
@@ -401,6 +417,9 @@ static inline void zero_map_value(struct bpf_map *map, void *dst)void copy_map_value_locked (struct bpf_map *map,void *dst,void *src,bool lock_src);void bpf_timer_cancel_and_free (void *timer); +void bpf_list_head_free (const struct btf_field *field,void *list_head, +struct bpf_spin_lock *spin_lock); +int bpf_obj_name_cpy (char *dst,const char *src,unsigned int size);struct bpf_offload_dev ;
kernel/bpf/btf.c +144 -3
207 lines not on this page · raw message
kernel/bpf/helpers.c +29 -0
@@ -1700,6 +1700,35 @@ bpf_base_func_proto(enum bpf_func_id func_id) } } +void bpf_list_head_free (const struct btf_field *field,void *list_head, +struct bpf_spin_lock *spin_lock) +{ +struct list_head *head = list_head, *orig_head = head, cp_head; + +BUILD_BUG_ON (sizeof (struct bpf_list_head ) !=sizeof (struct list_head )); +BUILD_BUG_ON (__alignof__(struct bpf_list_head ) != __alignof__(struct list_head )); + +if (!head->next ||list_empty (head)) +return ; + +__bpf_spin_lock_irqsave (spin_lock); + cp_head = *head; +INIT_LIST_HEAD (head); +__bpf_spin_unlock_irqrestore (spin_lock); + + head = &cp_head; + head = head->next; +while (head != orig_head) { +void *obj = head; + + obj -= field->list_head.node_offset; + head = head->next; +/* TODO: Rework later */ +kfree (obj); + } +INIT_LIST_HEAD (orig_head); +} + BTF_SET8_START(tracing_btf_ids)#ifdef CONFIG_KEXEC_CORE BTF_ID_FLAGS (func, crash_kexec,KF_DESTRUCTIVE )
kernel/bpf/syscall.c +21 -1
@@ -536,6 +536,9 @@ void btf_type_fields_free(struct btf_type_fields *tab)module_put (tab->fields[i].kptr.module);btf_put (tab->fields[i].kptr.btf);break ; +case BPF_LIST_HEAD : +/* Nothing to release for bpf_list_head */ +break ;default :WARN_ON_ONCE (1 );continue ;
@@ -578,6 +581,9 @@ struct btf_type_fields *btf_type_fields_dup(const struct btf_type_fields *tab) goto free; }break ; +case BPF_LIST_HEAD : +/* Nothing to acquire for bpf_list_head */ +break ;default : ret = -EFAULT ;WARN_ON_ONCE (1 );
@@ -637,6 +643,11 @@ void bpf_obj_free_fields(const struct btf_type_fields *tab, void *obj)case BPF_KPTR_REF : field->kptr.dtor ((void *)xchg ((unsigned long *)field_ptr,0 ));break ; +case BPF_LIST_HEAD : +if (WARN_ON_ONCE (tab->spin_lock_off <0 )) +continue ; +bpf_list_head_free (field, field_ptr, obj + tab->spin_lock_off); +break ;default :WARN_ON_ONCE (1 );continue ;
@@ -965,7 +976,8 @@ static int map_check_btf(struct bpf_map *map, const struct btf *btf,if (!value_type || value_size != map->value_size)return -EINVAL ; - map->fields_tab =btf_parse_fields (btf, value_type,BPF_SPIN_LOCK |BPF_TIMER |BPF_KPTR , + map->fields_tab =btf_parse_fields (btf, value_type, +BPF_SPIN_LOCK |BPF_TIMER |BPF_KPTR |BPF_LIST_HEAD , map->value_size);if (!IS_ERR_OR_NULL (map->fields_tab)) {int i;
@@ -1011,6 +1023,14 @@ static int map_check_btf(struct bpf_map *map, const struct btf *btf, goto free_map_tab; }break ; +case BPF_LIST_HEAD : +if (map->map_type !=BPF_MAP_TYPE_HASH && + map->map_type !=BPF_MAP_TYPE_LRU_HASH && + map->map_type !=BPF_MAP_TYPE_ARRAY ) { + ret = -EOPNOTSUPP ; + goto free_map_tab; + } +break ;default :/* Fail if map_type checks are missing for a field type */ ret = -EOPNOTSUPP ;
kernel/bpf/verifier.c +7 -0
@@ -12643,6 +12643,13 @@ static int check_map_prog_compatibility(struct bpf_verifier_env *env, } } +if (btf_type_fields_has_field (map->fields_tab,BPF_LIST_HEAD )) { +if (is_tracing_prog_type (prog_type)) { +verbose (env,"tracing progs cannot use bpf_list_head yet\n" ); +return -EINVAL ; + } + } +if ((bpf_prog_is_dev_bound (prog->aux) ||bpf_map_is_dev_bound (map)) && !bpf_offload_prog_map_match (prog, map)) {verbose (env,"offload device mismatch between prog and map\n" );
tools/testing/selftests/bpf/bpf_experimental.h new file +23 -0
@@ -0,0 +1,23 @@ +#ifndef __KERNEL__ + +#include <vmlinux.h> +#include <bpf/bpf_tracing.h> +#include <bpf/bpf_helpers.h> +#include <bpf/bpf_core_read.h> + +#else + +struct bpf_list_head { +__u64 __a; +__u64 __b; +} __attribute__((aligned (8 ))); + +struct bpf_list_node { +__u64 __a; +__u64 __b; +} __attribute__((aligned (8 ))); + +#endif + +#ifndef __KERNEL__ +#endif
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 10/25 bpf: Introduce local kptrs
In reply to Kumar Kartikeya DwivediIntroduce the idea of local kptrs, i.e. PTR_TO_BTF_ID that point to a type in program BTF. This is indicated by the presence of MEM_TYPE_LOCAL type tag in reg->type to avoid having to check btf_is_kernel when trying to match argument types in helpers.
For now, these local kptrs will always be referenced in verifier context, hence ref_obj_id == 0 for them is a bug. It is allowed to write to such objects, as long fields that are special are not touched (support for which will be added in subsequent patches).
No PROBE_MEM handling is hence done since they can never be in an undefined state, and their lifetime will always be valid.
--- include/linux/bpf.h | 14 +++++++++++--- include/linux/filter.h | 4 +++- kernel/bpf/btf.c | 9 ++++++++- kernel/bpf/verifier.c | 15 ++++++++++----- net/bpf/bpf_dummy_struct_ops.c | 3 ++- net/core/filter.c | 13 ++++++++----- net/ipv4/bpf_tcp_ca.c | 3 ++- net/netfilter/nf_conntrack_bpf.c | 1 + 8 files changed, 45 insertions(+), 17 deletions(-)
include/linux/bpf.h +11 -3
@@ -526,6 +526,11 @@ enum bpf_type_flag {/* Size is known at compile time. */ MEM_FIXED_SIZE =BIT (10 +BPF_BASE_TYPE_BITS ), +/* MEM is of a type from program BTF, not kernel BTF. This is used to +* tag PTR_TO_BTF_ID allocated using bpf_kptr_alloc. +*/ +MEM_TYPE_LOCAL =BIT (11 +BPF_BASE_TYPE_BITS ), + __BPF_TYPE_FLAG_MAX, __BPF_TYPE_LAST_FLAG = __BPF_TYPE_FLAG_MAX - 1, };
@@ -774,6 +779,7 @@ struct bpf_prog_ops { union bpf_attr __user *uattr); }; +struct bpf_reg_state ;struct bpf_verifier_ops {/* return eBPF function prototype for verification */ const struct bpf_func_proto *
@@ -795,6 +801,7 @@ struct bpf_verifier_ops {struct bpf_insn *dst, struct bpf_prog *prog, u32 *target_size); int (*btf_struct_access)(struct bpf_verifier_log *log, + const struct bpf_reg_state *reg, const struct btf *btf, const struct btf_type *t, int off, int size, enum bpf_access_type atype,
@@ -2076,10 +2083,11 @@ static inline bool bpf_tracing_btf_ctx_access(int off, int size,return btf_ctx_access (off, size, type, prog, info); } -int btf_struct_access (struct bpf_verifier_log *log,const struct btf *btf, +int btf_struct_access (struct bpf_verifier_log *log, +const struct bpf_reg_state *reg,const struct btf *btf,const struct btf_type *t,int off,int size, -enum bpf_access_type atype, -u32 *next_btf_id,enum bpf_type_flag *flag); +enum bpf_access_type atype,u32 *next_btf_id, +enum bpf_type_flag *flag); bool btf_struct_ids_match(struct bpf_verifier_log *log, const struct btf *btf, u32 id, int off, const struct btf *need_btf, u32 need_type_id,
include/linux/filter.h +3 -1
@@ -568,7 +568,9 @@ struct sk_filter {DECLARE_STATIC_KEY_FALSE (bpf_stats_enabled_key);extern struct mutex nf_conn_btf_access_lock; -extern int (*nfct_btf_struct_access)(struct bpf_verifier_log *log,const struct btf *btf, +extern int (*nfct_btf_struct_access)(struct bpf_verifier_log *log, +const struct bpf_reg_state *reg, +const struct btf *btf,const struct btf_type *t,int off,int size,enum bpf_access_type atype,u32 *next_btf_id,enum bpf_type_flag *flag);
kernel/bpf/btf.c +8 -1
@@ -6019,11 +6019,13 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,return -EINVAL ; } -int btf_struct_access (struct bpf_verifier_log *log,const struct btf *btf, +int btf_struct_access (struct bpf_verifier_log *log, +const struct bpf_reg_state *reg,const struct btf *btf,const struct btf_type *t,int off,int size,enum bpf_access_type atype__maybe_unused ,u32 *next_btf_id,enum bpf_type_flag *flag) { +bool local_type = reg && (type_flag (reg->type) &MEM_TYPE_LOCAL );enum bpf_type_flag tmp_flag =0 ;int err;u32 id;
@@ -6033,6 +6035,11 @@ int btf_struct_access(struct bpf_verifier_log *log, const struct btf *btf,switch (err) {case WALK_PTR : +/* For local types, the destination register cannot +* become a pointer again. +*/ +if (local_type) +return SCALAR_VALUE ;/* If we found the pointer or scalar on t+off, * we're done. */
kernel/bpf/verifier.c +10 -5
@@ -4522,16 +4522,20 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,return -EACCES ; } -if (env->ops->btf_struct_access) { - ret = env->ops->btf_struct_access (&env->log, reg->btf, t, +if (env->ops->btf_struct_access && !(type_flag (reg->type) &MEM_TYPE_LOCAL )) { +WARN_ON_ONCE (!btf_is_kernel (reg->btf)); + ret = env->ops->btf_struct_access (&env->log, reg, reg->btf, t, off, size, atype, &btf_id, &flag); }else { -if (atype !=BPF_READ ) { +if (atype !=BPF_READ && !(type_flag (reg->type) &MEM_TYPE_LOCAL )) {verbose (env,"only read is supported\n" );return -EACCES ; } - ret =btf_struct_access (&env->log, reg->btf, t, off, size, +if (reg->type &MEM_TYPE_LOCAL ) +WARN_ON_ONCE (!reg->ref_obj_id); + + ret =btf_struct_access (&env->log, reg, reg->btf, t, off, size, atype, &btf_id, &flag); }
@@ -4596,7 +4600,7 @@ static int check_ptr_to_map_access(struct bpf_verifier_env *env,return -EACCES ; } - ret =btf_struct_access (&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag); + ret =btf_struct_access (&env->log,NULL , btf_vmlinux, t, off, size, atype, &btf_id, &flag);if (ret <0 )return ret;
@@ -5816,6 +5820,7 @@ int check_func_arg_reg_off(struct bpf_verifier_env *env,* fixed offset. */ case PTR_TO_BTF_ID : +case PTR_TO_BTF_ID |MEM_TYPE_LOCAL :/* When referenced PTR_TO_BTF_ID is passed to release function, * it's fixed offset must be 0. In the other cases, fixed offset * can be non-zero.
net/bpf/bpf_dummy_struct_ops.c +2 -1
@@ -156,6 +156,7 @@ static bool bpf_dummy_ops_is_valid_access(int off, int size, } static int bpf_dummy_ops_btf_struct_access(struct bpf_verifier_log *log, + const struct bpf_reg_state *reg, const struct btf *btf, const struct btf_type *t, int off, int size, enum bpf_access_type atype,
@@ -177,7 +178,7 @@ static int bpf_dummy_ops_btf_struct_access(struct bpf_verifier_log *log,return -EACCES ; } - err =btf_struct_access (log, btf, t, off, size, atype, next_btf_id, + err =btf_struct_access (log, reg, btf, t, off, size, atype, next_btf_id, flag);if (err <0 )return err;
net/core/filter.c +8 -5
@@ -8647,13 +8647,15 @@ static bool tc_cls_act_is_valid_access(int off, int size,DEFINE_MUTEX (nf_conn_btf_access_lock);EXPORT_SYMBOL_GPL (nf_conn_btf_access_lock); -int (*nfct_btf_struct_access)(struct bpf_verifier_log *log,const struct btf *btf, +int (*nfct_btf_struct_access)(struct bpf_verifier_log *log, +const struct bpf_reg_state *reg,const struct btf *btf,const struct btf_type *t,int off,int size,enum bpf_access_type atype,u32 *next_btf_id,enum bpf_type_flag *flag);EXPORT_SYMBOL_GPL (nfct_btf_struct_access); static int tc_cls_act_btf_struct_access(struct bpf_verifier_log *log, + const struct bpf_reg_state *reg, const struct btf *btf, const struct btf_type *t, int off, int size, enum bpf_access_type atype,
@@ -8663,12 +8665,12 @@ static int tc_cls_act_btf_struct_access(struct bpf_verifier_log *log,int ret = -EACCES ;if (atype ==BPF_READ ) -return btf_struct_access (log, btf, t, off, size, atype, next_btf_id, +return btf_struct_access (log, reg, btf, t, off, size, atype, next_btf_id, flag);mutex_lock (&nf_conn_btf_access_lock);if (nfct_btf_struct_access) - ret =nfct_btf_struct_access (log, btf, t, off, size, atype, next_btf_id, flag); + ret =nfct_btf_struct_access (log, reg, btf, t, off, size, atype, next_btf_id, flag);mutex_unlock (&nf_conn_btf_access_lock);return ret;
@@ -8734,6 +8736,7 @@ void bpf_warn_invalid_xdp_action(struct net_device *dev, struct bpf_prog *prog,EXPORT_SYMBOL_GPL (bpf_warn_invalid_xdp_action); static int xdp_btf_struct_access(struct bpf_verifier_log *log, + const struct bpf_reg_state *reg, const struct btf *btf, const struct btf_type *t, int off, int size, enum bpf_access_type atype,
@@ -8743,12 +8746,12 @@ static int xdp_btf_struct_access(struct bpf_verifier_log *log,int ret = -EACCES ;if (atype ==BPF_READ ) -return btf_struct_access (log, btf, t, off, size, atype, next_btf_id, +return btf_struct_access (log, reg, btf, t, off, size, atype, next_btf_id, flag);mutex_lock (&nf_conn_btf_access_lock);if (nfct_btf_struct_access) - ret =nfct_btf_struct_access (log, btf, t, off, size, atype, next_btf_id, flag); + ret =nfct_btf_struct_access (log, reg, btf, t, off, size, atype, next_btf_id, flag);mutex_unlock (&nf_conn_btf_access_lock);return ret;
net/ipv4/bpf_tcp_ca.c +2 -1
@@ -69,6 +69,7 @@ static bool bpf_tcp_ca_is_valid_access(int off, int size, } static int bpf_tcp_ca_btf_struct_access(struct bpf_verifier_log *log, + const struct bpf_reg_state *reg, const struct btf *btf, const struct btf_type *t, int off, int size, enum bpf_access_type atype,
@@ -78,7 +79,7 @@ static int bpf_tcp_ca_btf_struct_access(struct bpf_verifier_log *log,size_t end;if (atype ==BPF_READ ) -return btf_struct_access (log, btf, t, off, size, atype, next_btf_id, +return btf_struct_access (log, reg, btf, t, off, size, atype, next_btf_id, flag);if (t != tcp_sock_type) {
net/netfilter/nf_conntrack_bpf.c +1 -0
@@ -191,6 +191,7 @@ BTF_ID(struct, nf_conn___init)/* Check writes into `struct nf_conn` */ static int _nf_conntrack_btf_struct_access(struct bpf_verifier_log *log, + const struct bpf_reg_state *reg, const struct btf *btf, const struct btf_type *t, int off, int size, enum bpf_access_type atype,
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 11/25 bpf: Recognize bpf_{spin_lock,list_head,list_node} in local kptrs
In reply to Kumar Kartikeya DwivediAllow specifying bpf_spin_lock, bpf_list_head, bpf_list_node fields in a local kptr.
A bpf_list_head allows implementing map-in-map style use cases, where local kptr with bpf_list_head is linked into a list in a map value. This would require embedding a bpf_list_node, support for which is also included.
Lastly, while we strictly don't require to hold a bpf_spin_lock while manipulating the bpf_list_head of a local kptr, as when have access to it, we have complete ownership of the object, the locking constraint is still kept and may be conditionally lifted in the future.
Note that the specification of such types can be done just like map values, e.g.:
struct bar {
struct bpf_list_node node;
};struct foo {
struct bpf_spin_lock lock;
struct bpf_list_head head __contains(bar, node);
struct bpf_list_node node;
};struct map_value {
struct bpf_spin_lock lock;
struct bpf_list_head head __contains(foo, node);
};To recognize such types in user BTF, we build a btf_struct_metas array of metadata items corresponding to each BTF ID. This is done once during the btf_parse stage to avoid having to do it each time during the verification process's requirement to inspect the metadata.
Moreover, the computed metadata needs to be passed to some helpers in future patches which requires allocating them and storing them in the BTF that is pinned by the program itself, so that valid access can be assumed to such data during program runtime.
--- include/linux/bpf.h | 7 ++ include/linux/btf.h | 35 ++++++++ kernel/bpf/btf.c | 196 +++++++++++++++++++++++++++++++++++++++---- kernel/bpf/syscall.c | 4 + 4 files changed, 224 insertions(+), 18 deletions(-)
include/linux/bpf.h +7 -0
@@ -178,6 +178,7 @@ enum btf_field_type {BPF_KPTR_REF = (1 <<3 ),BPF_KPTR =BPF_KPTR_UNREF |BPF_KPTR_REF ,BPF_LIST_HEAD = (1 <<4 ), + BPF_LIST_NODE = (1 << 5), }; struct btf_field_kptr {
@@ -278,6 +279,8 @@ static inline const char *btf_field_type_name(enum btf_field_type type)return "kptr" ;case BPF_LIST_HEAD :return "bpf_list_head" ; +case BPF_LIST_NODE : +return "bpf_list_node" ;default :WARN_ON_ONCE (1 );return "unknown" ;
@@ -296,6 +299,8 @@ static inline u32 btf_field_type_size(enum btf_field_type type)return sizeof (u64);case BPF_LIST_HEAD :return sizeof (struct bpf_list_head ); +case BPF_LIST_NODE : +return sizeof (struct bpf_list_node );default :WARN_ON_ONCE (1 );return 0 ;
@@ -314,6 +319,8 @@ static inline u32 btf_field_type_align(enum btf_field_type type)return __alignof__(u64 );case BPF_LIST_HEAD :return __alignof__(struct bpf_list_head ); +case BPF_LIST_NODE : +return __alignof__(struct bpf_list_node );default :WARN_ON_ONCE (1 );return 0 ;
include/linux/btf.h +35 -0
@@ -6,6 +6,8 @@#include <linux/types.h> #include <linux/bpfptr.h> +#include <linux/bsearch.h> +#include <linux/btf_ids.h> #include <uapi/linux/btf.h> #include <uapi/linux/bpf.h>
@@ -78,6 +80,17 @@ struct btf_id_dtor_kfunc {u32 kfunc_btf_id; }; +struct btf_struct_meta { +u32 btf_id; +struct btf_type_fields *fields_tab; +struct btf_type_fields_off *off_arr; +}; + +struct btf_struct_metas { +u32 cnt; +struct btf_struct_meta types[]; +}; +typedef void (*btf_dtor_kfunc_t )(void *);extern const struct file_operations btf_fops;
@@ -409,6 +422,23 @@ static inline struct btf_param *btf_params(const struct btf_type *t)return (struct btf_param *)(t +1 ); } +static inline int btf_id_cmp_func (const void *a,const void *b) +{ +const int *pa = a, *pb = b; + +return *pa - *pb; +} + +static inline bool btf_id_set_contains (const struct btf_id_set *set,u32 id) +{ +return bsearch (&id, set->ids, set->cnt,sizeof (u32), btf_id_cmp_func) !=NULL ; +} + +static inline void *btf_id_set8_contains (const struct btf_id_set8 *set,u32 id) +{ +return bsearch (&id, set->pairs, set->cnt,sizeof (set->pairs[0 ]), btf_id_cmp_func); +} +#ifdef CONFIG_BPF_SYSCALL struct bpf_prog ;
@@ -424,6 +454,7 @@ int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,s32 btf_find_dtor_kfunc (struct btf *btf,u32 btf_id);int register_btf_id_dtor_kfuncs (const struct btf_id_dtor_kfunc *dtors,u32 add_cnt,struct module *owner); +struct btf_struct_meta *btf_find_struct_meta (const struct btf *btf,u32 btf_id);#else static inline const struct btf_type *btf_type_by_id (const struct btf *btf,u32 type_id)
@@ -455,6 +486,10 @@ static inline int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dt {return 0 ; } +static inline struct btf_struct_meta *btf_find_struct_meta (const struct btf *btf,u32 btf_id) +{ +return NULL ; +}#endif static inline bool btf_type_is_struct_ptr (struct btf *btf,const struct btf_type *t)
kernel/bpf/btf.c +178 -18
272 lines not on this page · raw message
kernel/bpf/syscall.c +4 -0
@@ -537,6 +537,7 @@ void btf_type_fields_free(struct btf_type_fields *tab)btf_put (tab->fields[i].kptr.btf);break ;case BPF_LIST_HEAD : +case BPF_LIST_NODE :/* Nothing to release for bpf_list_head */ break ;default :
@@ -582,6 +583,7 @@ struct btf_type_fields *btf_type_fields_dup(const struct btf_type_fields *tab) }break ;case BPF_LIST_HEAD : +case BPF_LIST_NODE :/* Nothing to acquire for bpf_list_head */ break ;default :
@@ -648,6 +650,8 @@ void bpf_obj_free_fields(const struct btf_type_fields *tab, void *obj)continue ;bpf_list_head_free (field, field_ptr, obj + tab->spin_lock_off);break ; +case BPF_LIST_NODE : +break ;default :WARN_ON_ONCE (1 );continue ;
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 12/25 bpf: Verify ownership relationships for owning types
In reply to Kumar Kartikeya DwivediEnsure that there can be no ownership cycles among different types by way of having owning objects that can hold some other type as their element. For instance, a map value can only hold local kptrs, but these are allowed to have another bpf_list_head. To prevent unbounded recursion while freeing resources, elements of bpf_list_head in local kptrs can never have a bpf_list_head which are part of list in a map value.
Also, to make runtime destruction easier, once btf_struct_metas is fully populated, we can stash the metadata of the value type directly in the metadata of the list_head fields, as that allows easier access to the value type's layout to destruct it at runtime from the btf_field entry of the list head itself.
--- include/linux/bpf.h | 1 + include/linux/btf.h | 1 + kernel/bpf/btf.c | 71 ++++++++++++++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 4 +++ 4 files changed, 77 insertions(+)
include/linux/bpf.h +1 -0
@@ -192,6 +192,7 @@ struct btf_field_list_head {struct btf *btf;u32 value_btf_id;u32 node_offset; +struct btf_type_fields *value_tab; };struct btf_field {
include/linux/btf.h +1 -0
@@ -179,6 +179,7 @@ int btf_find_timer(const struct btf *btf, const struct btf_type *t);struct btf_type_fields *btf_parse_fields (const struct btf *btf,const struct btf_type *t,u32 field_mask,u32 value_size); +int btf_check_and_fixup_fields (const struct btf *btf,struct btf_type_fields *tab);struct btf_type_fields_off *btf_parse_fields_off (struct btf_type_fields *tab);bool btf_type_is_void (const struct btf_type *t);s32 btf_find_by_name_kind (const struct btf *btf,const char *name,u8 kind);
kernel/bpf/btf.c +71 -0
83 lines not on this page · raw message
kernel/bpf/syscall.c +4 -0
@@ -1043,6 +1043,10 @@ static int map_check_btf(struct bpf_map *map, const struct btf *btf, } } + ret =btf_check_and_fixup_fields (btf, map->fields_tab); +if (ret <0 ) + goto free_map_tab; +if (map->ops->map_check_btf) { ret = map->ops->map_check_btf (map, btf, key_type, value_type);if (ret <0 )
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 13/25 bpf: Support locking bpf_spin_lock in local kptr
In reply to Kumar Kartikeya DwivediAllow locking a bpf_spin_lock embedded in local kptr, in addition to already support map value pointers. The handling is similar to that of map values, by just preserving the reg->id of local kptrs as well, and adjusting process_spin_lock to work with non-PTR_TO_MAP_VALUE and remember the id in verifier state.
--- kernel/bpf/helpers.c | 2 ++ kernel/bpf/verifier.c | 74 ++++++++++++++++++++++++++++++++----------- 2 files changed, 57 insertions(+), 19 deletions(-)
kernel/bpf/helpers.c +2 -0
@@ -336,6 +336,7 @@ const struct bpf_func_proto bpf_spin_lock_proto = { .gpl_only = false, .ret_type = RET_VOID, .arg1_type = ARG_PTR_TO_SPIN_LOCK, + .arg1_btf_id = BPF_PTR_POISON, };static inline void __bpf_spin_unlock_irqrestore (struct bpf_spin_lock *lock)
@@ -358,6 +359,7 @@ const struct bpf_func_proto bpf_spin_unlock_proto = { .gpl_only = false, .ret_type = RET_VOID, .arg1_type = ARG_PTR_TO_SPIN_LOCK, + .arg1_btf_id = BPF_PTR_POISON, }; void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
kernel/bpf/verifier.c +55 -19
127 lines not on this page · raw message
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 14/25 bpf: Allow locking bpf_spin_lock global variables
In reply to Kumar Kartikeya DwivediGlobal variables reside in maps accessible using direct_value_addr callbacks, so giving each load instruction's rewrite a unique reg->id disallows us from holding locks which are global.
This is not great, so refactor the active_spin_lock into two separate fields, active_spin_lock_ptr and active_spin_lock_id, which is generic enough to allow it for global variables, map lookups, and local kptr registers at the same time.
Held vs non-held is indicated by active_spin_lock_ptr, which stores the reg->map_ptr or reg->btf pointer of the register used for locking spin lock. But the active_spin_lock_id also needs to be compared to ensure whether bpf_spin_unlock is for the same register.
Next, pseudo load instructions are not given a unique reg->id, as they are doing lookup for the same map value (max_entries is never greater than 1).
Essentially, we consider that the tuple of (active_spin_lock_ptr, active_spin_lock_id) will always be unique for any kind of argument to bpf_spin_{lock,unlock}.
Note that this can be extended in the future to also remember offset used for locking, so that we can introduce multiple bpf_spin_lock fields in the same allocation.
--- include/linux/bpf_verifier.h | 3 ++- kernel/bpf/verifier.c | 39 +++++++++++++++++++++++++----------- 2 files changed, 29 insertions(+), 13 deletions(-)
include/linux/bpf_verifier.h +2 -1
@@ -323,7 +323,8 @@ struct bpf_verifier_state {u32 branches;u32 insn_idx;u32 curframe; -u32 active_spin_lock; +void *active_spin_lock_ptr; +u32 active_spin_lock_id;bool speculative;/* first and last insn idx of this verifier state */
kernel/bpf/verifier.c +27 -12
@@ -1201,7 +1201,8 @@ static int copy_verifier_state(struct bpf_verifier_state *dst_state, } dst_state->speculative = src->speculative; dst_state->curframe = src->curframe; - dst_state->active_spin_lock = src->active_spin_lock; + dst_state->active_spin_lock_ptr = src->active_spin_lock_ptr; + dst_state->active_spin_lock_id = src->active_spin_lock_id; dst_state->branches = src->branches; dst_state->parent = src->parent; dst_state->first_insn_idx = src->first_insn_idx;
@@ -5460,22 +5461,35 @@ static int process_spin_lock(struct bpf_verifier_env *env, int regno,return -EINVAL ; }if (is_lock) { -if (cur->active_spin_lock) { +if (cur->active_spin_lock_ptr) {verbose (env,"Locking two bpf_spin_locks are not allowed\n" );return -EINVAL ; } - cur->active_spin_lock = reg->id; +if (map) + cur->active_spin_lock_ptr = map; +else + cur->active_spin_lock_ptr = btf; + cur->active_spin_lock_id = reg->id; }else { -if (!cur->active_spin_lock) { +void *ptr; + +if (map) + ptr = map; +else + ptr = btf; + +if (!cur->active_spin_lock_ptr) {verbose (env,"bpf_spin_unlock without taking a lock\n" );return -EINVAL ; } -if (cur->active_spin_lock != reg->id) { +if (cur->active_spin_lock_ptr != ptr || + cur->active_spin_lock_id != reg->id) {verbose (env,"bpf_spin_unlock of different lock\n" );return -EINVAL ; } - cur->active_spin_lock =0 ; + cur->active_spin_lock_ptr =NULL ; + cur->active_spin_lock_id =0 ; }return 0 ; }
@@ -10382,8 +10396,8 @@ static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { dst_reg->type =PTR_TO_MAP_VALUE ; dst_reg->off = aux->map_off; -if (btf_type_fields_has_field (map->fields_tab,BPF_SPIN_LOCK )) - dst_reg->id = ++env->id_gen; +WARN_ON_ONCE (map->max_entries !=1 ); +/* We want reg->id to be same (0) as map_value is not distinct */ } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || insn->src_reg == BPF_PSEUDO_MAP_IDX) { dst_reg->type =CONST_PTR_TO_MAP ;
@@ -10461,7 +10475,7 @@ static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)return err; } -if (env->cur_state->active_spin_lock) { +if (env->cur_state->active_spin_lock_ptr) {verbose (env,"BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n" );return -EINVAL ; }
@@ -11727,7 +11741,8 @@ static bool states_equal(struct bpf_verifier_env *env,if (old->speculative && !cur->speculative)return false; -if (old->active_spin_lock != cur->active_spin_lock) +if (old->active_spin_lock_ptr != cur->active_spin_lock_ptr || + old->active_spin_lock_id != cur->active_spin_lock_id)return false;/* for states to be equal callsites have to be the same
@@ -12366,7 +12381,7 @@ static int do_check(struct bpf_verifier_env *env)return -EINVAL ; } -if (env->cur_state->active_spin_lock && +if (env->cur_state->active_spin_lock_ptr && (insn->src_reg ==BPF_PSEUDO_CALL || insn->imm != BPF_FUNC_spin_unlock)) {verbose (env,"function calls are not allowed while holding a lock\n" );
@@ -12403,7 +12418,7 @@ static int do_check(struct bpf_verifier_env *env)return -EINVAL ; } -if (env->cur_state->active_spin_lock) { +if (env->cur_state->active_spin_lock_ptr) {verbose (env,"bpf_spin_unlock is missing\n" );return -EINVAL ; }
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 15/25 bpf: Rewrite kfunc argument handling
In reply to Kumar Kartikeya DwivediAs we continue to add more features, argument types, kfunc flags, and different extensions to kfuncs, the code to verify the correctness of the kfunc prototype wrt the passed in registers has become ad-hoc and ugly to read.
To make life easier, and make a very clear split between different stages of argument processing, move all the code into verifier.c and refactor into easier to read helpers and functions.
This also makes sharing code within the verifier easier with kfunc argument processing. This will be more and more useful in later patches as we are now moving to implement very core BPF helpers as kfuncs, to keep them experimental before baking into UAPI.
--- include/linux/btf.h | 29 + kernel/bpf/btf.c | 16 +- kernel/bpf/verifier.c | 546 +++++++++++++++++- .../bpf/prog_tests/kfunc_dynptr_param.c | 2 +- tools/testing/selftests/bpf/verifier/calls.c | 4 +- .../selftests/bpf/verifier/ref_tracking.c | 4 +- 6 files changed, 568 insertions(+), 33 deletions(-)
include/linux/btf.h +29 -0
@@ -339,6 +339,16 @@ static inline bool btf_type_is_struct(const struct btf_type *t)return kind ==BTF_KIND_STRUCT || kind ==BTF_KIND_UNION ; } +static inline bool __btf_type_is_struct (const struct btf_type *t) +{ +return BTF_INFO_KIND (t->info) ==BTF_KIND_STRUCT ; +} + +static inline bool btf_type_is_array (const struct btf_type *t) +{ +return BTF_INFO_KIND (t->info) ==BTF_KIND_ARRAY ; +} +static inline u16 btf_type_vlen (const struct btf_type *t) {return BTF_INFO_VLEN (t->info);
@@ -442,6 +452,7 @@ static inline void *btf_id_set8_contains(const struct btf_id_set8 *set, u32 id)#ifdef CONFIG_BPF_SYSCALL struct bpf_prog ; +struct bpf_verifier_log ;const struct btf_type *btf_type_by_id (const struct btf *btf,u32 type_id);const char *btf_name_by_offset (const struct btf *btf,u32 offset);
@@ -456,6 +467,12 @@ s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id);int register_btf_id_dtor_kfuncs (const struct btf_id_dtor_kfunc *dtors,u32 add_cnt,struct module *owner);struct btf_struct_meta *btf_find_struct_meta (const struct btf *btf,u32 btf_id); +const struct btf_member * +btf_get_prog_ctx_type (struct bpf_verifier_log *log,const struct btf *btf, +const struct btf_type *t,enum bpf_prog_type prog_type, +int arg); +bool btf_types_are_same (const struct btf *btf1,u32 id1, +const struct btf *btf2,u32 id2);#else static inline const struct btf_type *btf_type_by_id (const struct btf *btf,u32 type_id)
@@ -491,6 +508,18 @@ static inline struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf {return NULL ; } +static inline const struct btf_member * +btf_get_prog_ctx_type (struct bpf_verifier_log *log,const struct btf *btf, +const struct btf_type *t,enum bpf_prog_type prog_type, +int arg) +{ +return NULL ; +} +static inline bool btf_types_are_same (const struct btf *btf1,u32 id1, +const struct btf *btf2,u32 id2) +{ +return false; +}#endif static inline bool btf_type_is_struct_ptr (struct btf *btf,const struct btf_type *t)
kernel/bpf/btf.c +3 -13
@@ -478,16 +478,6 @@ static bool btf_type_nosize_or_null(const struct btf_type *t)return !t ||btf_type_nosize (t); } -static bool __btf_type_is_struct (const struct btf_type *t) -{ -return BTF_INFO_KIND (t->info) ==BTF_KIND_STRUCT ; -} - -static bool btf_type_is_array (const struct btf_type *t) -{ -return BTF_INFO_KIND (t->info) ==BTF_KIND_ARRAY ; -} -static bool btf_type_is_datasec (const struct btf_type *t) {return BTF_INFO_KIND (t->info) ==BTF_KIND_DATASEC ;
@@ -5537,7 +5527,7 @@ static u8 bpf_ctx_convert_map[] = {#undef BPF_MAP_TYPE#undef BPF_LINK_TYPE -static const struct btf_member * +const struct btf_member *btf_get_prog_ctx_type (struct bpf_verifier_log *log,const struct btf *btf,const struct btf_type *t,enum bpf_prog_type prog_type,int arg)
@@ -6322,8 +6312,8 @@ int btf_struct_access(struct bpf_verifier_log *log,* end up with two different module BTFs, but IDs point to the common type in * vmlinux BTF. */ -static bool btf_types_are_same (const struct btf *btf1,u32 id1, -const struct btf *btf2,u32 id2) +bool btf_types_are_same (const struct btf *btf1,u32 id1, +const struct btf *btf2,u32 id2) {if (id1 != id2)return false;
kernel/bpf/verifier.c +531 -15
601 lines not on this page · raw message
tools/testing/selftests/bpf/prog_tests/kfunc_dynptr_param.c +1 -1
@@ -22,7 +22,7 @@ static struct { "arg#0 pointer type STRUCT bpf_dynptr_kern points to unsupported dynamic pointer type", 0}, {"not_valid_dynptr" , "arg#0 pointer type STRUCT bpf_dynptr_kern must be valid and initialized", 0}, - {"not_ptr_to_stack", "arg#0 pointer type STRUCT bpf_dynptr_kern not to stack", 0}, + {"not_ptr_to_stack", "arg#0 expected pointer to stack", 0}, {"dynptr_data_null", NULL, -EBADMSG}, };
tools/testing/selftests/bpf/verifier/calls.c +2 -2
@@ -109,7 +109,7 @@ }, .prog_type = BPF_PROG_TYPE_SCHED_CLS, .result = REJECT, - .errstr = "arg#0 pointer type STRUCT prog_test_ref_kfunc must point", + .errstr = "arg#0 expected pointer to btf or socket", .fixup_kfunc_btf_id = { { "bpf_kfunc_call_test_acquire", 3 }, { "bpf_kfunc_call_test_release", 5 },
@@ -181,7 +181,7 @@ }, .result_unpriv = REJECT, .result = REJECT, - .errstr = "negative offset ptr_ ptr R1 off=-4 disallowed", + .errstr = "R1 must have zero offset when passed to release func", }, { "calls: invalid kfunc call: PTR_TO_BTF_ID with variable offset",
tools/testing/selftests/bpf/verifier/ref_tracking.c +2 -2
@@ -142,7 +142,7 @@ .kfunc = "bpf", .expected_attach_type = BPF_LSM_MAC, .flags = BPF_F_SLEEPABLE, - .errstr = "arg#0 pointer type STRUCT bpf_key must point to scalar, or struct with scalar", + .errstr = "arg#0 expected pointer to btf or socket", .fixup_kfunc_btf_id = { { "bpf_lookup_user_key", 2 }, { "bpf_key_put", 4 },
@@ -163,7 +163,7 @@ .kfunc = "bpf", .expected_attach_type = BPF_LSM_MAC, .flags = BPF_F_SLEEPABLE, - .errstr = "arg#0 pointer type STRUCT bpf_key must point to scalar, or struct with scalar", + .errstr = "arg#0 expected pointer to btf or socket", .fixup_kfunc_btf_id = { { "bpf_lookup_system_key", 1 }, { "bpf_key_put", 3 },
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 16/25 bpf: Drop kfunc bits from btf_check_func_arg_match
In reply to Kumar Kartikeya DwivediRemove all kfunc related bits now from btf_check_func_arg_match, as users have been converted away to refactored kfunc argument handling.
This is split into a separate commit to aid review, in order to compare what has been preserved from the removed bits easily instead of mixing removed hunks with previous patch.
--- include/linux/bpf.h | 11 -- include/linux/bpf_verifier.h | 2 - kernel/bpf/btf.c | 364 +---------------------------------- kernel/bpf/verifier.c | 4 +- 4 files changed, 10 insertions(+), 371 deletions(-)
include/linux/bpf.h +0 -11
@@ -2107,22 +2107,11 @@ int btf_distill_func_proto(struct bpf_verifier_log *log,const char *func_name, struct btf_func_model *m); -struct bpf_kfunc_arg_meta { -u64 r0_size; -bool r0_rdonly; -int ref_obj_id; -u32 flags; -}; -struct bpf_reg_state ;int btf_check_subprog_arg_match (struct bpf_verifier_env *env,int subprog,struct bpf_reg_state *regs);int btf_check_subprog_call (struct bpf_verifier_env *env,int subprog,struct bpf_reg_state *regs); -int btf_check_kfunc_arg_match (struct bpf_verifier_env *env, -const struct btf *btf,u32 func_id, -struct bpf_reg_state *regs, -struct bpf_kfunc_arg_meta *meta);int btf_prepare_func_args (struct bpf_verifier_env *env,int subprog,struct bpf_reg_state *reg); int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
include/linux/bpf_verifier.h +0 -2
@@ -590,8 +590,6 @@ int check_ptr_off_reg(struct bpf_verifier_env *env,int check_func_arg_reg_off (struct bpf_verifier_env *env,const struct bpf_reg_state *reg,int regno,enum bpf_arg_type arg_type); -int check_kfunc_mem_size_reg (struct bpf_verifier_env *env,struct bpf_reg_state *reg, -u32 regno);int check_mem_reg (struct bpf_verifier_env *env,struct bpf_reg_state *reg,u32 regno,u32 mem_size); bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
kernel/bpf/btf.c +8 -356
447 lines not on this page · raw message
kernel/bpf/verifier.c +2 -2
@@ -5368,8 +5368,8 @@ int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,return err; } -int check_kfunc_mem_size_reg (struct bpf_verifier_env *env,struct bpf_reg_state *reg, -u32 regno) +static int check_kfunc_mem_size_reg (struct bpf_verifier_env *env,struct bpf_reg_state *reg, +u32 regno) {struct bpf_reg_state *mem_reg = &cur_regs (env)[regno -1 ];bool may_be_null =type_may_be_null (mem_reg->type);
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 17/25 bpf: Support constant scalar arguments for kfuncs
In reply to Kumar Kartikeya DwivediAllow passing known constant scalars as arguments to kfuncs that do not represent a size parameter. This makes the search pruning optimization of verifier more conservative for such kfunc calls, and each non-distinct argument is considered unequivalent.
We will use this support to then expose a global bpf_kptr_alloc function where it takes the local type ID in program BTF, and returns a PTR_TO_BTF_ID to the local type. These will be called local kptrs, and allows programs to allocate their own objects.
However, this is still not completely safe, as mark_chain_precision logic is buggy without more work when the constant argument is not a size, but still needs precise marker propagation for pruning checks. Next patch will fix this problem.
--- Documentation/bpf/kfuncs.rst | 30 ++++++++++++++++++ kernel/bpf/verifier.c | 59 +++++++++++++++++++++++++++--------- 2 files changed, 75 insertions(+), 14 deletions(-)
Documentation/bpf/kfuncs.rst +30 -0
@@ -72,6 +72,36 @@ argument as its size. By default, without __sz annotation, the size of the type of the pointer is used. Without __sz annotation, a kfunc cannot accept a void pointer. +2.2.1 __k Annotation +-------------------- + +This annotation is only understood for scalar arguments, where it indicates that +the verifier must check the scalar argument to be a known constant, which does +not indicate a size parameter. This distinction is important, as when the scalar +argument does not represent a size parameter, verifier is more conservative in +state search pruning and does not consider two arguments equivalent for safety +purposes if the already verified value was within range of the new one. + +This assumption holds well for sizes (as memory accessed within smaller bounds +in old verified state will also work for bigger bounds in current to be explored +state), but not for other constant arguments where each carries a distinct +semantic effect. + +An example is given below:: + + void *bpf_mem_alloc(u32 local_type_id__k) + { + ... + } + +Here, bpf_mem_alloc uses local_type_id argument to find out the size of that +type ID in program's BTF and return a sized pointer to it. Each type ID will +have a distinct size, hence it is crucial to treat each such call as distinct +when values don't match. + +Hence, whenever a constant scalar argument is accepted by a kfunc which is not a +size parameter, __k suffix must be used. + .. _BPF_kfunc_nodef: 2.3 Using an existing kernel function
kernel/bpf/verifier.c +45 -14
88 lines not on this page · raw message
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 18/25 bpf: Teach verifier about non-size constant arguments
In reply to Kumar Kartikeya DwivediCurrently, the verifier has support for various arguments that either describe the size of the memory being passed in to a helper, or describe the size of the memory being returned. When a constant is passed in like this, it is assumed for the purposes of precision tracking that if the value in the already explored safe state is within the value in current state, it would fine to prune the search.
While this holds well for size arguments, arguments where each value may denote a distinct meaning and needs to be verified separately needs more work. Search can only be pruned if both are constant values and both are equal. In all other cases, it would be incorrect to treat those two precise registers as equivalent if the new value satisfies the old one (i.e. old <= cur).
Hence, make the register precision marker tri-state. There are now three values that reg->precise takes: NOT_PRECISE, PRECISE, EXACT.
Both PRECISE and EXACT are 'true' values. EXACT affects how regsafe decides whether both registers are equivalent for the purposes of verifier state equivalence. When it sees that one register has reg->precise == EXACT, unless both are absolute, it will return false. When both are, it returns true only when both are const and both have the same value. Otherwise, for PRECISE case it falls back to the default check that is present now (i.e. thinking that we're talking about sizes).
This is required as a future patch introduces a BPF memory allocator interface, where we take the program BTF's type ID as an argument. Each distinct type ID may result in the returned pointer obtaining a different size, hence precision tracking is needed, and pruning cannot just happen when the old value is within the current value. It must only happen when the type ID is equal. The type ID will always correspond to prog->aux->btf hence actual type match is not required.
Finally, change mark_chain_precision precision argument to EXACT for kfuncs constant non-size scalar arguments (tagged with __k suffix).
--- include/linux/bpf_verifier.h | 10 ++-- kernel/bpf/verifier.c | 101 ++++++++++++++++++++++------------- 2 files changed, 70 insertions(+), 41 deletions(-)
include/linux/bpf_verifier.h +7 -3
@@ -43,6 +43,12 @@ enum bpf_reg_liveness { REG_LIVE_DONE = 0x8, /* liveness won't be updating this register anymore */ }; +enum bpf_reg_precise { +NOT_PRECISE , +PRECISE , +EXACT , +}; +struct bpf_reg_state {/* Ordering of fields matters. See states_equal() */ enum bpf_reg_type type;
@@ -180,7 +186,7 @@ struct bpf_reg_state {s32 subreg_def;enum bpf_reg_liveness live;/* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */ -bool precise; +enum bpf_reg_precise precise; };enum bpf_stack_slot_type {
@@ -624,8 +630,6 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, struct bpf_attach_target_info *tgt_info);void bpf_free_kfunc_btf_tab (struct bpf_kfunc_btf_tab *tab); -int mark_chain_precision (struct bpf_verifier_env *env,int regno); -#define BPF_BASE_TYPE_MASK GENMASK(BPF_BASE_TYPE_BITS - 1, 0)/* extract base type from bpf_{arg, return, reg}_type. */
kernel/bpf/verifier.c +63 -38
287 lines not on this page · raw message
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 19/25 bpf: Introduce bpf_kptr_new
In reply to Kumar Kartikeya DwivediIntroduce type safe memory allocator bpf_kptr_new for BPF programs. The kernel side kfunc is named bpf_kptr_new_impl, as passing hidden arguments to kfuncs still requires having them in prototype, unlike BPF helpers which always take 5 arguments and have them checked using bpf_func_proto in verifier, ignoring unset argument types.
Introduce __ign suffix to ignore a specific kfunc argument during type checks, then use this to introduce support for passing type metadata to the bpf_kptr_new_impl kfunc.
The user passes BTF ID of the type it wants to allocates in program BTF, the verifier then rewrites the first argument as the size of this type, after performing some sanity checks (to ensure it exists and it is a struct type).
The second argument flags is reserved to be 0 for now.
The third argument is also fixed up and passed by the verifier. This is the btf_struct_meta for the type being allocated. It would be needed mostly for the offset array which is required for zero initializing special fields while leaving the rest of storage in unitialized state.
It would also be needed in the next patch to perform proper destruction of the object's special fields.
A convenience macro is included in the bpf_experimental.h header to hide over the ugly details of the implementation, leading to user code looking similar to a language level extension which allocates and constructs fields of a user type.
struct bar {
struct bpf_list_node node;
};struct foo {
struct bpf_spin_lock lock;
struct bpf_list_head head __contains(bar, node);
};void prog(void) {
struct foo *f;
f = bpf_kptr_new(typeof(*f));
if (!f)
return;
...
}A key piece of this story is still missing, i.e. the free function, which will come in the next patch.
--- include/linux/bpf.h | 21 ++-- include/linux/bpf_verifier.h | 2 + kernel/bpf/core.c | 14 +++ kernel/bpf/helpers.c | 41 +++++-- kernel/bpf/verifier.c | 107 ++++++++++++++++-- .../testing/selftests/bpf/bpf_experimental.h | 19 ++++ 6 files changed, 181 insertions(+), 23 deletions(-)
include/linux/bpf.h +13 -8
@@ -55,6 +55,8 @@ struct cgroup;extern struct idr btf_idr;extern spinlock_t btf_idr_lock;extern struct kobject *btf_kobj; +extern struct bpf_mem_alloc bpf_global_ma; +extern bool bpf_global_ma_set;typedef u64 (*bpf_callback_t )(u64 ,u64 ,u64 ,u64 ,u64 ); typedef int (*bpf_iter_init_seq_priv_t)(void *private_data,
@@ -335,16 +337,19 @@ static inline bool btf_type_fields_has_field(const struct btf_type_fields *tab,return tab->field_mask & type; } -static inline void check_and_init_map_value (struct bpf_map *map,void *dst) +static inline void bpf_obj_init (const struct btf_type_fields_off *off_arr,void *obj) { -if (!IS_ERR_OR_NULL (map->fields_tab)) { -struct btf_field *fields = map->fields_tab->fields; -u32 cnt = map->fields_tab->cnt; -int i; +int i; -for (i =0 ; i < cnt; i++) -memset (dst + fields[i].offset,0 ,btf_field_type_size (fields[i].type)); - } +if (!off_arr) +return ; +for (i =0 ; i < off_arr->cnt; i++) +memset (obj + off_arr->field_off[i],0 , off_arr->field_sz[i]); +} + +static inline void check_and_init_map_value (struct bpf_map *map,void *dst) +{ +bpf_obj_init (map->off_arr, dst); }/* memcpy that is used with 8-byte aligned pointers, power-of-8 size and
include/linux/bpf_verifier.h +2 -0
@@ -426,6 +426,8 @@ struct bpf_insn_aux_data {*/ struct bpf_loop_inline_state loop_inline_state; }; +u64 kptr_new_size;/* remember the size of type passed to bpf_kptr_new to rewrite R1 */ +struct btf_struct_meta *kptr_struct_meta;u64 map_key_state;/* constant (32 bit) key tracking for maps */ int ctx_field_size;/* the ctx field size for load insn, maybe 0 */ u32 seen;/* this insn was processed by the verifier at env->pass_cnt */
kernel/bpf/core.c +14 -0
@@ -34,6 +34,7 @@#include <linux/log2.h> #include <linux/bpf_verifier.h> #include <linux/nodemask.h> +#include <linux/bpf_mem_alloc.h> #include <asm/barrier.h> #include <asm/unaligned.h>
@@ -60,6 +61,9 @@#define CTX regs[BPF_REG_CTX]#define IMM insn->imm +struct bpf_mem_alloc bpf_global_ma; +bool bpf_global_ma_set; +/* No hurry in this branch * * Exported for the bpf jit load helper.
@@ -2740,6 +2744,16 @@ int __weak bpf_arch_text_invalidate(void *dst, size_t len)return -ENOTSUPP ; } +static int __init bpf_global_ma_init (void ) +{ +int ret; + + ret =bpf_mem_alloc_init (&bpf_global_ma,0 , false); + bpf_global_ma_set = !ret; +return ret; +} +late_initcall (bpf_global_ma_init); +DEFINE_STATIC_KEY_FALSE (bpf_stats_enabled_key);EXPORT_SYMBOL (bpf_stats_enabled_key);
kernel/bpf/helpers.c +34 -7
66 lines not on this page · raw message
kernel/bpf/verifier.c +99 -8
165 lines not on this page · raw message
tools/testing/selftests/bpf/bpf_experimental.h +19 -0
@@ -20,4 +20,23 @@ struct bpf_list_node {#endif #ifndef __KERNEL__ + +/* Description +* Allocates a local kptr of type represented by 'local_type_id' in program +* BTF. User may use the bpf_core_type_id_local macro to pass the type ID +* of a struct in program BTF. +* +* The 'local_type_id' parameter must be a known constant. The 'flags' +* parameter must be 0. +* +* The 'meta__ign' parameter is a hidden argument that is ignored. +* Returns +* A local kptr corresponding to passed in 'local_type_id', or NULL on +* failure. +*/ +extern void *bpf_kptr_new_impl (__u64 local_type_id,__u64 flags,void *meta__ign) __ksym; + +/* Convenience macro to wrap over bpf_kptr_new_impl */ +#define bpf_kptr_new (type) bpf_kptr_new_impl(bpf_core_type_id_local(type), 0, NULL) +#endif
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 20/25 bpf: Introduce bpf_kptr_drop
In reply to Kumar Kartikeya DwivediIntroduce bpf_kptr_drop, which is the kfunc used to free local kptrs allocated using bpf_kptr_new. Similar to bpf_kptr_new, it implicitly destructs the fields part of the local kptr automatically without user intervention.
Just like the previous patch, btf_struct_meta that is needed to free up the special fields is passed as a hidden argument to the kfunc.
For the user, a convenience macro hides over the kernel side kfunc which is named bpf_kptr_drop_impl.
Continuing the previous example:
void prog(void) {
struct foo *f;
f = bpf_kptr_new(typeof(*f));
if (!f)
return;
bpf_kptr_drop(f);
}--- kernel/bpf/helpers.c | 11 ++++ kernel/bpf/verifier.c | 66 +++++++++++++++---- .../testing/selftests/bpf/bpf_experimental.h | 13 ++++ 3 files changed, 79 insertions(+), 11 deletions(-)
kernel/bpf/helpers.c +11 -0
@@ -1755,6 +1755,16 @@ void *bpf_kptr_new_impl(u64 local_type_id__k, u64 flags, void *meta__ign)return p; } +void bpf_kptr_drop_impl (void *p__lkptr,void *meta__ign) +{ +struct btf_struct_meta *meta = meta__ign; +void *p = p__lkptr; + +if (meta) +bpf_obj_free_fields (meta->fields_tab, p); +bpf_mem_free (&bpf_global_ma, p); +} +__diag_pop ();BTF_SET8_START (generic_btf_ids)
@@ -1762,6 +1772,7 @@ BTF_SET8_START(generic_btf_ids) BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE)#endif BTF_ID_FLAGS(func, bpf_kptr_new_impl, KF_ACQUIRE | KF_RET_NULL) +BTF_ID_FLAGS(func, bpf_kptr_drop_impl, KF_RELEASE)BTF_SET8_END (generic_btf_ids) static const struct btf_kfunc_id_set generic_kfunc_set = {
kernel/bpf/verifier.c +55 -11
126 lines not on this page · raw message
tools/testing/selftests/bpf/bpf_experimental.h +13 -0
@@ -39,4 +39,17 @@ extern void *bpf_kptr_new_impl(__u64 local_type_id, __u64 flags, void *meta__ign/* Convenience macro to wrap over bpf_kptr_new_impl */ #define bpf_kptr_new (type) bpf_kptr_new_impl(bpf_core_type_id_local(type), 0, NULL) +/* Description +* Free a local kptr. All fields of local kptr that require destruction +* will be destructed before the storage is freed. +* +* The 'meta__ign' parameter is a hidden argument that is ignored. +* Returns +* Void. +*/ +extern void bpf_kptr_drop_impl(void *kptr, void *meta__ign) __ksym; + +/* Convenience macro to wrap over bpf_kptr_drop_impl */ +#define bpf_kptr_drop (kptr) bpf_kptr_drop_impl(kptr, NULL) +#endif
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 21/25 bpf: Permit NULL checking pointer with non-zero fixed offset
In reply to Kumar Kartikeya DwivediPointer increment on seeing PTR_MAYBE_NULL is already protected against, hence make an exception for local kptrs while still keeping the warning for other unintended cases that might creep in.
bpf_list_del{,tail} helpers return a local kptr with incremented offset pointing to bpf_list_node field. The user is supposed to then obtain the pointer to the entry using container_of after NULL checking it. The current restrictions trigger a warning when doing the NULL checking. Revisiting the reason, it is meant as an assertion which seems to actually work and catch the bad case.
Hence, under no other circumstances can reg->off be non-zero for a register that has the PTR_MAYBE_NULL type flag set.
--- kernel/bpf/verifier.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-)
kernel/bpf/verifier.c +9 -4
@@ -10612,15 +10612,20 @@ static void mark_ptr_or_null_reg(struct bpf_func_state *state, {if (type_may_be_null (reg->type) && reg->id == id && !WARN_ON_ONCE (!reg->id)) { -if (WARN_ON_ONCE (reg->smin_value || reg->smax_value || - !tnum_equals_const (reg->var_off,0 ) || - reg->off)) { +if (reg->smin_value || reg->smax_value || !tnum_equals_const (reg->var_off,0 ) || reg->off) {/* Old offset (both fixed and variable parts) should * have been known-zero, because we don't allow pointer * arithmetic on pointers that might be NULL. If we * see this happening, don't convert the register. +* +* But in some cases, some helpers that return local +* kptrs advance offset for the returned pointer. +* In those cases, it is fine to expect to see reg->off. */ -return ; +if (WARN_ON_ONCE (reg->type != (PTR_TO_BTF_ID |MEM_TYPE_LOCAL |PTR_MAYBE_NULL ))) +return ; +if (WARN_ON_ONCE (reg->smin_value || reg->smax_value || !tnum_equals_const (reg->var_off,0 ))) +return ; }if (is_null) { reg->type =SCALAR_VALUE ;
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 22/25 bpf: Introduce single ownership BPF linked list API
In reply to Kumar Kartikeya DwivediAdd a linked list API for use in BPF programs, where it expects protection from the bpf_spin_lock in the same allocation as the bpf_list_head. Future patches will extend the same infrastructure to have different flavors with varying protection domains and visibility (e.g. percpu variant with local_t protection, usable in NMI progs).
The following functions are added to kick things off:
bpf_list_addbpf_list_add_tailbpf_list_delbpf_list_del_tail
The lock protecting the bpf_list_head needs to be taken for all operations.
Once a node has been added to the list, it's pointer changes to PTR_UNTRUSTED. However, it is only released once the lock protecting the list is unlocked. For such local kptrs with PTR_UNTRUSTED set but an active ref_obj_id, it is still permitted to read and write to them as long as the lock is held.
bpf_list_del and bpf_list_del_tail delete the first or last item of the list respectively, and return pointer to the element at the list_node offset. The user can then use container_of style macro to get the actual entry type. The verifier however statically knows the actual type, so the safety properties are still preserved.
With these additions, programs can now manage their own linked lists and store their objects in them.
--- include/linux/bpf_verifier.h | 5 + kernel/bpf/helpers.c | 48 +++ kernel/bpf/verifier.c | 344 ++++++++++++++++-- .../testing/selftests/bpf/bpf_experimental.h | 28 ++ 4 files changed, 391 insertions(+), 34 deletions(-)
include/linux/bpf_verifier.h +5 -0
@@ -229,6 +229,11 @@ struct bpf_reference_state {* exiting a callback function. */ int callback_ref; +/* Mark the reference state to release the registers sharing the same id +* on bpf_spin_unlock (for nodes that we will lose ownership to but are +* safe to access inside the critical section). +*/ +bool release_on_unlock; };/* state of the program:
kernel/bpf/helpers.c +48 -0
60 lines not on this page · raw message
kernel/bpf/verifier.c +310 -34
458 lines not on this page · raw message
tools/testing/selftests/bpf/bpf_experimental.h +28 -0
@@ -52,4 +52,32 @@ extern void bpf_kptr_drop_impl(void *kptr, void *meta__ign) __ksym;/* Convenience macro to wrap over bpf_kptr_drop_impl */ #define bpf_kptr_drop (kptr) bpf_kptr_drop_impl(kptr, NULL) +/* Description +* Add a new entry to the head of the BPF linked list. +* Returns +* Void. +*/ +extern void bpf_list_add(struct bpf_list_node *node, struct bpf_list_head *head) __ksym; + +/* Description +* Add a new entry to the tail of the BPF linked list. +* Returns +* Void. +*/ +extern void bpf_list_add_tail(struct bpf_list_node *node, struct bpf_list_head *head) __ksym; + +/* Description +* Remove the entry at head of the BPF linked list. +* Returns +* Pointer to bpf_list_node of deleted entry, or NULL if list is empty. +*/ +extern struct bpf_list_node *bpf_list_del (struct bpf_list_head *head) __ksym; + +/* Description +* Remove the entry at tail of the BPF linked list. +* Returns +* Pointer to bpf_list_node of deleted entry, or NULL if list is empty. +*/ +extern struct bpf_list_node *bpf_list_del_tail (struct bpf_list_head *head) __ksym; +#endif
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 23/25 libbpf: Add support for private BSS map section
In reply to Kumar Kartikeya DwivediFrom: Dave Marchevsky <[email protected]>
Currently libbpf does not allow declaration of a struct bpf_spin_lock in global scope. Attempting to do so results in "failed to re-mmap" error, as .bss arraymap containing spinlock is not allowed to be mmap'd.
This patch adds support for a .bss.private section. The maps contained in this section will not be mmaped into userspace by libbpf, nor will they be exposed via bpftool-generated skeleton.
Intent here is to allow more natural programming pattern for global-scope spinlocks which will be used by rbtree locking mechanism in further patches in this series.
Notes:
* Initially I called the section .bss.no_mmap, but the broader 'private' term better indicates that skeleton shouldn't expose these maps at all, IMO.
* bpftool/gen.c's is_internal_mmapable_map function checks whether the map flags have BPF_F_MMAPABLE, so no bpftool changes were necessary to remove .bss.private maps from skeleton
--- tools/lib/bpf/libbpf.c | 65 ++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 21 deletions(-)
tools/lib/bpf/libbpf.c +44 -21
@@ -465,6 +465,7 @@ struct bpf_struct_ops {#define KCONFIG_SEC ".kconfig"#define KSYMS_SEC ".ksyms"#define STRUCT_OPS_SEC ".struct_ops" +#define BSS_SEC_PRIVATE ".bss.private"enum libbpf_map_type {LIBBPF_MAP_UNSPEC ,
@@ -578,6 +579,7 @@ enum sec_type {SEC_BSS ,SEC_DATA ,SEC_RODATA , + SEC_BSS_PRIVATE, }; struct elf_sec_desc {
@@ -1582,7 +1584,8 @@ bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);static int bpf_object__init_internal_map (struct bpf_object *obj,enum libbpf_map_type type, -const char *real_name,int sec_idx,void *data,size_t data_sz) +const char *real_name,int sec_idx,void *data, +size_t data_sz,bool do_mmap) {struct bpf_map_def *def;struct bpf_map *map;
@@ -1610,27 +1613,31 @@ bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type, def->max_entries =1 ; def->map_flags = type ==LIBBPF_MAP_RODATA || type ==LIBBPF_MAP_KCONFIG ?BPF_F_RDONLY_PROG :0 ; - def->map_flags |=BPF_F_MMAPABLE ; +if (do_mmap) + def->map_flags |=BPF_F_MMAPABLE ;pr_debug ("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n" , map->name, map->sec_idx, map->sec_offset, def->map_flags); - map->mmaped =mmap (NULL ,bpf_map_mmap_sz (map),PROT_READ |PROT_WRITE , -MAP_SHARED |MAP_ANONYMOUS ,-1 ,0 ); -if (map->mmaped ==MAP_FAILED ) { - err = -errno; - map->mmaped =NULL ; -pr_warn ("failed to alloc map '%s' content buffer: %d\n" , - map->name, err); -zfree (&map->real_name); -zfree (&map->name); -return err; + map->mmaped =NULL ; +if (do_mmap) { + map->mmaped =mmap (NULL ,bpf_map_mmap_sz (map),PROT_READ |PROT_WRITE , +MAP_SHARED |MAP_ANONYMOUS ,-1 ,0 ); +if (map->mmaped ==MAP_FAILED ) { + err = -errno; + map->mmaped =NULL ; +pr_warn ("failed to alloc map '%s' content buffer: %d\n" , + map->name, err); +zfree (&map->real_name); +zfree (&map->name); +return err; + } }/* failures are fine because of maps like .rodata.str1.1 */ (void )bpf_map_find_btf_info (obj, map); -if (data) +if (do_mmap && data)memcpy (map->mmaped, data, data_sz);pr_debug ("map %td is \"%s\"\n" , map - obj->maps, map->name);
@@ -1642,12 +1649,14 @@ static int bpf_object__init_global_data_maps(struct bpf_object *obj)struct elf_sec_desc *sec_desc;const char *sec_name;int err =0 , sec_idx; +bool do_mmap;/* * Populate obj->maps with libbpf internal maps. */ for (sec_idx =1 ; sec_idx < obj->efile.sec_cnt; sec_idx++) { sec_desc = &obj->efile.secs[sec_idx]; + do_mmap = true;/* Skip recognized sections with size 0. */ if (!sec_desc->data || sec_desc->data->d_size ==0 )
@@ -1659,7 +1668,8 @@ static int bpf_object__init_global_data_maps(struct bpf_object *obj) err =bpf_object__init_internal_map (obj,LIBBPF_MAP_DATA , sec_name, sec_idx, sec_desc->data->d_buf, - sec_desc->data->d_size); + sec_desc->data->d_size, + do_mmap);break ;case SEC_RODATA : obj->has_rodata = true;
@@ -1667,14 +1677,18 @@ static int bpf_object__init_global_data_maps(struct bpf_object *obj) err =bpf_object__init_internal_map (obj,LIBBPF_MAP_RODATA , sec_name, sec_idx, sec_desc->data->d_buf, - sec_desc->data->d_size); + sec_desc->data->d_size, + do_mmap);break ; +case SEC_BSS_PRIVATE : + do_mmap = false;case SEC_BSS : sec_name =elf_sec_name (obj,elf_sec_by_idx (obj, sec_idx)); err =bpf_object__init_internal_map (obj,LIBBPF_MAP_BSS , sec_name, sec_idx,NULL , - sec_desc->data->d_size); + sec_desc->data->d_size, + do_mmap);break ;default :/* skip */
@@ -1988,7 +2002,7 @@ static int bpf_object__init_kconfig_map(struct bpf_object *obj) map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz; err =bpf_object__init_internal_map (obj,LIBBPF_MAP_KCONFIG ,".kconfig" , obj->efile.symbols_shndx, -NULL , map_sz); +NULL , map_sz, true);if (err)return err;
@@ -3449,6 +3463,10 @@ static int bpf_object__elf_collect(struct bpf_object *obj) sec_desc->sec_type =SEC_BSS ; sec_desc->shdr = sh; sec_desc->data = data; + }else if (sh->sh_type ==SHT_NOBITS &&strcmp (name,BSS_SEC_PRIVATE ) ==0 ) { + sec_desc->sec_type =SEC_BSS_PRIVATE ; + sec_desc->shdr = sh; + sec_desc->data = data; }else {pr_info ("elf: skipping section(%d) %s (size %zu)\n" , idx, name, (size_t )sh->sh_size);
@@ -3911,6 +3929,7 @@ static bool bpf_object__shndx_is_data(const struct bpf_object *obj,case SEC_BSS :case SEC_DATA :case SEC_RODATA : +case SEC_BSS_PRIVATE :return true;default :return false;
@@ -3930,6 +3949,7 @@ bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)return LIBBPF_MAP_KCONFIG ;switch (obj->efile.secs[shndx].sec_type) { +case SEC_BSS_PRIVATE :case SEC_BSS :return LIBBPF_MAP_BSS ;case SEC_DATA :
@@ -4919,16 +4939,19 @@ bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map) {enum libbpf_map_type map_type = map->libbpf_type;char *cp, errmsg[STRERR_BUFSIZE ]; -int err, zero =0 ; +int err =0 , zero =0 ;if (obj->gen_loader) { -bpf_gen__map_update_elem (obj->gen_loader, map - obj->maps, - map->mmaped, map->def.value_size); +if (map->mmaped) +bpf_gen__map_update_elem (obj->gen_loader, map - obj->maps, + map->mmaped, map->def.value_size);if (map_type ==LIBBPF_MAP_RODATA || map_type ==LIBBPF_MAP_KCONFIG )bpf_gen__map_freeze (obj->gen_loader, map - obj->maps);return 0 ; } - err =bpf_map_update_elem (map->fd, &zero, map->mmaped,0 ); + +if (map->mmaped) + err =bpf_map_update_elem (map->fd, &zero, map->mmaped,0 );if (err) { err = -errno; cp =libbpf_strerror_r (err, errmsg,sizeof (errmsg));
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 24/25 selftests/bpf: Add __contains macro to bpf_experimental.h
In reply to Kumar Kartikeya DwivediAdd user facing __contains macro which provides a convenient wrapper over the verbose kernel specific BTF declaration tag required to annotate BPF list head structs in user types.
--- tools/testing/selftests/bpf/bpf_experimental.h | 2 ++ 1 file changed, 2 insertions(+)
tools/testing/selftests/bpf/bpf_experimental.h +2 -0
@@ -5,6 +5,8 @@#include <bpf/bpf_helpers.h> #include <bpf/bpf_core_read.h> +#define __contains (name, node) __attribute__((btf_decl_tag("contains:struct:" #name ":" #node))) +#else struct bpf_list_head {
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerPATCH 25/25 selftests/bpf: Add BPF linked list API tests
In reply to Kumar Kartikeya DwivediInclude various tests covering the success and failure cases. Also, run the success cases at runtime to verify correctness of linked list manipulation routines, in addition to ensuring successful verification.
--- kernel/bpf/helpers.c | 5 +- tools/testing/selftests/bpf/DENYLIST.s390x | 1 + .../selftests/bpf/prog_tests/linked_list.c | 88 +++++ .../testing/selftests/bpf/progs/linked_list.c | 325 ++++++++++++++++++ 4 files changed, 418 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/linked_list.c create mode 100644 tools/testing/selftests/bpf/progs/linked_list.c
kernel/bpf/helpers.c +4 -1
@@ -1830,7 +1830,10 @@ static const struct btf_kfunc_id_set generic_kfunc_set = {static int __init kfunc_init (void ) { -return register_btf_kfunc_id_set (BPF_PROG_TYPE_TRACING , &generic_kfunc_set); +int ret; + + ret =register_btf_kfunc_id_set (BPF_PROG_TYPE_TRACING , &generic_kfunc_set); +return ret ?:register_btf_kfunc_id_set (BPF_PROG_TYPE_SCHED_CLS , &generic_kfunc_set); }late_initcall (kfunc_init);
tools/testing/selftests/bpf/DENYLIST.s390x +1 -0
@@ -76,3 +76,4 @@ lookup_key # JIT does not support calling kernel f verify_pkcs7_sig # JIT does not support calling kernel function (kfunc) kfunc_dynptr_param # JIT does not support calling kernel function (kfunc) deny_namespace # failed to attach: ERROR: strerror_r(-524)=22 (trampoline) +linked_list # JIT does not support calling kernel function (kfunc)
tools/testing/selftests/bpf/prog_tests/linked_list.c new file +88 -0
88 lines not on this page · raw message
tools/testing/selftests/bpf/progs/linked_list.c new file +325 -0
325 lines not on this page · raw message
Signature · 1 line
2.34.1
Kumar Kartikeya Dwivedi
maintainerQuoted 8 lines · Kumar Kartikeya Dwivedi
Hi, this is the non-RFC v1. This is mostly a major rewrite of the previous set, hence complete review of some of these patches is needed again. I have cut down the series to only the specific pieces needed to enable other work (like Dave's RB-Tree). The rest will come as a follow up to this.
--
Ouch, this gets a merge conflict in CI because Roberto's series got applied just before I sent this out, and I didn't notice. I will wait for a day (?) for people to respond (unless someone asks me to hold it) and otherwise respin this again (it passes all tests locally fwiw).