Re: [PATCH bpf-next v4 3/5] selftests/bpf: Add ksock kfunc test
Mahe Tardy <[email protected]>
| Newsgroups | org.kernel.vger.bpf,org.kernel.vger.netdev |
|---|---|
| Message-ID | <[email protected]> |
On Fri, Aug 07, 2026 at 05:12:21PM +0800, Jiayuan Chen wrote:
>
> On 8/7/26 2:22 AM, Mahe Tardy wrote:
> > Add
> [...]
> > +
> > +SEC("lsm.s/socket_bind")
> > +int BPF_PROG(ksock_socket_bind, struct socket *sock, struct sockaddr *address,
> > + int addrlen, int ret)
> > +{
> > + struct __ksock_ctx_value *v;
> > + struct bpf_ksock *ks, *tmp;
> > + u32 pid = bpf_get_current_pid_tgid() >> 32;
> > +
> > + if (ret || pid != target_pid)
> > + return ret;
> > +
> > + v = ksock_ctx_value_lookup();
> > + if (!v) {
> > + send_ret = -ENOENT;
> > + return ret;
> > + }
> > +
> > + ks = NULL;
> > + bpf_rcu_read_lock();
> > + tmp = v->ctx;
> > + if (tmp)
> > + ks = bpf_ksock_acquire(tmp);
> > + bpf_rcu_read_unlock();
> > +
> > + if (!ks) {
> > + send_ret = -ENOENT;
> > + return ret;
> > + }
> > +
>
>
> Since bpf_ksock_send() is sleepable, every consumer of the kptr is
> necessarily a sleepable program and thus has to open-code the same
> bpf_rcu_read_lock()/acquire/unlock sequence before each send.
>
> Given ksock_common.h already wraps the insert side, how about also
> providing the get side, e.g.:
>
> static inline struct bpf_ksock *ksock_ctx_get(void)
> {
> Â Â struct __ksock_ctx_value *v = ksock_ctx_value_lookup();
> Â Â struct bpf_ksock *ks = NULL, *tmp;
>
> Â Â if (!v)
> Â Â Â Â Â Â return NULL;
> Â Â bpf_rcu_read_lock();
> Â Â tmp = v->ctx;
> Â Â if (tmp)
> Â Â Â Â Â Â ks = bpf_ksock_acquire(tmp);
> Â Â bpf_rcu_read_unlock();
> Â Â return ks;
> }
>
> These selftests will be the reference everyone copies from, so
> encapsulating the RCU dance here also documents the correct usage.
>
Yeah good idea, I'll just keep a slightly difference dance using
bpf_kptr_xchg() in the ksock_lsm_verifier.c program because I want the
verifier to bump against bpf_ksock_send() restriction explicitely and
not bpf_ksock_acquire().