Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit aad9db66 authored by Alexei Starovoitov's avatar Alexei Starovoitov Committed by Greg Kroah-Hartman
Browse files

bpf: fix struct htab_elem layout



commit 9f691549f76d488a0c74397b3e51e943865ea01f upstream.

when htab_elem is removed from the bucket list the htab_elem.hash_node.next
field should not be overridden too early otherwise we have a tiny race window
between lookup and delete.
The bug was discovered by manual code analysis and reproducible
only with explicit udelay() in lookup_elem_raw().

Fixes: 6c905981 ("bpf: pre-allocate hash map elements")
Reported-by: default avatarJonathan Perry <jonperry@fb.com>
Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
Acked-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
Signed-off-by: default avatarDavid S. Miller <davem@davemloft.net>
Signed-off-by: default avatarChenbo Feng <fengc@google.com>
Signed-off-by: default avatarSasha Levin <sashal@kernel.org>
parent 9b04b510
Loading
Loading
Loading
Loading
+22 −6
Original line number Diff line number Diff line
@@ -41,9 +41,14 @@ enum extra_elem_state {
struct htab_elem {
	union {
		struct hlist_node hash_node;
		struct {
			void *padding;
			union {
				struct bpf_htab *htab;
				struct pcpu_freelist_node fnode;
			};
		};
	};
	union {
		struct rcu_head rcu;
		enum extra_elem_state state;
@@ -114,8 +119,10 @@ static int prealloc_elems_and_freelist(struct bpf_htab *htab)
	if (err)
		goto free_elems;

	pcpu_freelist_populate(&htab->freelist, htab->elems, htab->elem_size,
			       htab->map.max_entries);
	pcpu_freelist_populate(&htab->freelist,
			       htab->elems + offsetof(struct htab_elem, fnode),
			       htab->elem_size, htab->map.max_entries);

	return 0;

free_elems:
@@ -148,6 +155,11 @@ static struct bpf_map *htab_map_alloc(union bpf_attr *attr)
	int err, i;
	u64 cost;

	BUILD_BUG_ON(offsetof(struct htab_elem, htab) !=
		     offsetof(struct htab_elem, hash_node.pprev));
	BUILD_BUG_ON(offsetof(struct htab_elem, fnode.next) !=
		     offsetof(struct htab_elem, hash_node.pprev));

	if (attr->map_flags & ~BPF_F_NO_PREALLOC)
		/* reserved bits should not be used */
		return ERR_PTR(-EINVAL);
@@ -429,9 +441,13 @@ static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key,
	int err = 0;

	if (prealloc) {
		l_new = (struct htab_elem *)pcpu_freelist_pop(&htab->freelist);
		if (!l_new)
		struct pcpu_freelist_node *l;

		l = pcpu_freelist_pop(&htab->freelist);
		if (!l)
			err = -E2BIG;
		else
			l_new = container_of(l, struct htab_elem, fnode);
	} else {
		if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
			atomic_dec(&htab->count);