Re: [PATCH bpf-next v5 2/2] selftests/bpf: Add test to verify freeing the special fields when update [lru_,]percpu_hash maps

From: Alexei Starovoitov

Date: Tue Nov 04 2025 - 12:39:50 EST


On Tue, Nov 4, 2025 at 6:52 AM <bot+bpf-ci@xxxxxxxxxx> wrote:
>
> > diff --git a/tools/testing/selftests/bpf/progs/refcounted_kptr.c b/tools/testing/selftests/bpf/progs/refcounted_kptr.c
> > index 893a4fdb4..87b0cc018 100644
> > --- a/tools/testing/selftests/bpf/progs/refcounted_kptr.c
> > +++ b/tools/testing/selftests/bpf/progs/refcounted_kptr.c
>
> [ ... ]
>
> > @@ -568,4 +568,64 @@ int BPF_PROG(rbtree_sleepable_rcu_no_explicit_rcu_lock,
> > return 0;
> > }
> >
> > +private(kptr_ref) u64 ref;
> > +
> > +static int probe_read_refcount(void)
> > +{
> > + u32 refcount;
> > +
> > + bpf_probe_read_kernel(&refcount, sizeof(refcount), (void *) ref);
> > + return refcount;
> > +}
> > +
> > +static int __insert_in_list(struct bpf_list_head *head, struct bpf_spin_lock *lock,
> > + struct node_data __kptr **node)
> > +{
> > + struct node_data *n, *m;
> > +
> > + n = bpf_obj_new(typeof(*n));
> > + if (!n)
> > + return -1;
> > +
> > + m = bpf_refcount_acquire(n);
> > + n = bpf_kptr_xchg(node, n);
> > + if (n) {
> > + bpf_obj_drop(n);
> > + bpf_obj_drop(m);
> > + return -2;
> > + }
>
> In __insert_in_list(), after bpf_kptr_xchg() stores the new object in
> the map and returns the old value in n, can the error path drop both
> n and m? At this point, the new object (pointed to by m) is already
> referenced by the map. Dropping m here would free an object that the
> map still points to, leaving a dangling pointer.

AI is wrong, but I bet it got confused by reuse of variable 'n'.
It's hard for humans too.
Leon,
please use a different var.
n = bpf_kptr_xchg(node, n); is a head scratcher.

Also see Yonghong's comment on v4 which I suspect applies to v5.

pw-bot: cr