Skip to content

Commit e706907

Browse files
committed
bpf: add bpf_dynptr_memset() kfunc
Currently there is no straightforward way to fill dynptr memory with a value (most commonly zero). One can do it with bpf_dynptr_write(), but a temporary buffer is necessary for that. Implement bpf_dynptr_memset() - an analogue of memset() from libc. Signed-off-by: Ihor Solodrai <[email protected]>
1 parent 3ce7cdd commit e706907

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

kernel/bpf/helpers.c

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,53 @@ __bpf_kfunc int bpf_dynptr_copy(struct bpf_dynptr *dst_ptr, u32 dst_off,
29062906
return 0;
29072907
}
29082908

2909+
/**
2910+
* bpf_dynptr_memset() - Fill dynptr memory with a constant byte.
2911+
* @ptr: Destination dynptr - where data will be filled
2912+
* @ptr_off: Offset into the dynptr to start filling from
2913+
* @size: Number of bytes to fill
2914+
* @val: Constant byte to fill the memory with
2915+
*
2916+
* Fills the size bytes of the memory area pointed to by ptr
2917+
* at offset ptr_off with the constant byte val.
2918+
* Returns 0 on success; negative error, otherwise.
2919+
*/
2920+
__bpf_kfunc int bpf_dynptr_memset(struct bpf_dynptr *ptr, u32 ptr_off, u32 size, u8 val)
2921+
{
2922+
struct bpf_dynptr_kern *p = (struct bpf_dynptr_kern *)ptr;
2923+
char buf[256];
2924+
u32 chunk_sz;
2925+
void* slice;
2926+
u32 offset;
2927+
int err;
2928+
2929+
if (__bpf_dynptr_is_rdonly(p))
2930+
return -EINVAL;
2931+
2932+
err = bpf_dynptr_check_off_len(p, ptr_off, size);
2933+
if (err)
2934+
return err;
2935+
2936+
slice = bpf_dynptr_slice_rdwr(ptr, ptr_off, NULL, size);
2937+
if (likely(slice)) {
2938+
memset(slice, val, size);
2939+
return 0;
2940+
}
2941+
2942+
/* Non-linear data under the dynptr, write from a local buffer */
2943+
chunk_sz = min_t(u32, sizeof(buf), size);
2944+
memset(buf, val, chunk_sz);
2945+
2946+
for (offset = ptr_off; offset < ptr_off + size; offset += chunk_sz) {
2947+
chunk_sz = min_t(u32, sizeof(buf), size - offset);
2948+
err = __bpf_dynptr_write(p, offset, buf, chunk_sz, 0);
2949+
if (err)
2950+
return err;
2951+
}
2952+
2953+
return 0;
2954+
}
2955+
29092956
__bpf_kfunc void *bpf_cast_to_kern_ctx(void *obj)
29102957
{
29112958
return obj;
@@ -3364,6 +3411,7 @@ BTF_ID_FLAGS(func, bpf_dynptr_is_rdonly)
33643411
BTF_ID_FLAGS(func, bpf_dynptr_size)
33653412
BTF_ID_FLAGS(func, bpf_dynptr_clone)
33663413
BTF_ID_FLAGS(func, bpf_dynptr_copy)
3414+
BTF_ID_FLAGS(func, bpf_dynptr_memset)
33673415
#ifdef CONFIG_NET
33683416
BTF_ID_FLAGS(func, bpf_modify_return_test_tp)
33693417
#endif

0 commit comments

Comments
 (0)