Skip to content

Commit 62a898b

Browse files
Hou TaoAlexei Starovoitov
authored andcommitted
bpf: Add bpf_mem_alloc_check_size() helper
Introduce bpf_mem_alloc_check_size() to check whether the allocation size exceeds the limitation for the kmalloc-equivalent allocator. The upper limit for percpu allocation is LLIST_NODE_SZ bytes larger than non-percpu allocation, so a percpu argument is added to the helper. The helper will be used in the following patch to check whether the size parameter passed to bpf_mem_alloc() is too big. Signed-off-by: Hou Tao <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Alexei Starovoitov <[email protected]>
1 parent 101ccfb commit 62a898b

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

include/linux/bpf_mem_alloc.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ int bpf_mem_alloc_percpu_init(struct bpf_mem_alloc *ma, struct obj_cgroup *objcg
3333
int bpf_mem_alloc_percpu_unit_init(struct bpf_mem_alloc *ma, int size);
3434
void bpf_mem_alloc_destroy(struct bpf_mem_alloc *ma);
3535

36+
/* Check the allocation size for kmalloc equivalent allocator */
37+
int bpf_mem_alloc_check_size(bool percpu, size_t size);
38+
3639
/* kmalloc/kfree equivalent: */
3740
void *bpf_mem_alloc(struct bpf_mem_alloc *ma, size_t size);
3841
void bpf_mem_free(struct bpf_mem_alloc *ma, void *ptr);

kernel/bpf/memalloc.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@
3535
*/
3636
#define LLIST_NODE_SZ sizeof(struct llist_node)
3737

38+
#define BPF_MEM_ALLOC_SIZE_MAX 4096
39+
3840
/* similar to kmalloc, but sizeof == 8 bucket is gone */
3941
static u8 size_index[24] __ro_after_init = {
4042
3, /* 8 */
@@ -65,7 +67,7 @@ static u8 size_index[24] __ro_after_init = {
6567

6668
static int bpf_mem_cache_idx(size_t size)
6769
{
68-
if (!size || size > 4096)
70+
if (!size || size > BPF_MEM_ALLOC_SIZE_MAX)
6971
return -1;
7072

7173
if (size <= 192)
@@ -1005,3 +1007,13 @@ void notrace *bpf_mem_cache_alloc_flags(struct bpf_mem_alloc *ma, gfp_t flags)
10051007

10061008
return !ret ? NULL : ret + LLIST_NODE_SZ;
10071009
}
1010+
1011+
int bpf_mem_alloc_check_size(bool percpu, size_t size)
1012+
{
1013+
/* The size of percpu allocation doesn't have LLIST_NODE_SZ overhead */
1014+
if ((percpu && size > BPF_MEM_ALLOC_SIZE_MAX) ||
1015+
(!percpu && size > BPF_MEM_ALLOC_SIZE_MAX - LLIST_NODE_SZ))
1016+
return -E2BIG;
1017+
1018+
return 0;
1019+
}

0 commit comments

Comments
 (0)