Skip to content

Bpf base test - #1

Open
mrpre wants to merge 9 commits into
bpf_basefrom
bpf_base_test
Open

mrpre wants to merge 9 commits into
bpf_basefrom
bpf_base_test

Conversation

@mrpre

@mrpre mrpre commented Nov 23, 2026

Copy link
Copy Markdown
Owner

No description provided.

Kernel Patches Daemon and others added 2 commits November 20, 2026 18:57
ai-code-review.yml only runs in kernel-patches/bpf: it needs the
organization's CodeBuild runners, AWS Bedrock role and review bot App.

Add a fork-local variant that starts when someone with write access
comments "@claude" on a PR. It reviews every commit of the PR on
GitHub-hosted runners, in the runner:ai-review container, and
authenticates with the repository's CLAUDE_CODE_OAUTH_TOKEN secret.
Reviews are posted with the workflow's own token.
@mrpre

mrpre commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

@claude

The review job runs in a container, where the github.workspace and
runner.temp contexts still expand to the host's paths. The semcode-index
step failed creating a symlink under /home/runner/work, which does not
exist in the container.

Use $GITHUB_WORKSPACE and workspace-relative paths instead.
Cc: Jiayuan Chen <[email protected]>
@mrpre

mrpre commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

@claude

@github-actions

Copy link
Copy Markdown
commit b0074ecfa44f0da0ae7e7dbcf929f34c2f500861
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix copied_seq updates with strparser

This commit changes tcp_bpf_strp_read_sock() and tcp_bpf_recvmsg_parser() to
add their own delta to the current tp->copied_seq instead of writing back a
saved value. It also counts ingress_bytes only in
sk_psock_skb_ingress_self() and orphans the skb when the enqueue there fails.

> bpf, sockmap: Fix copied_seq updates with strparser

TL;DR: Possible double count of dropped bytes in tp->copied_seq on SK_DROP
with strparser: copied_seq may pass rcv_nxt, stalling the parser and returning
-EAGAIN. Selftests appear to lack an SK_DROP case.

> diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c
> --- a/net/ipv4/tcp_bpf.c
> +++ b/net/ipv4/tcp_bpf.c

[ ... ]

> @@ -775,7 +774,8 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc,
>  	 * For SK_REDIRECT, we need to ack the frame immediately but for
>  	 * SK_PASS, we want to delay the ack until tcp_bpf_recvmsg_parser().
>  	 */
> -	tp->copied_seq = psock->copied_seq - psock->ingress_bytes;
> +	WRITE_ONCE(tp->copied_seq, tp->copied_seq + psock->copied_seq - seq -
> +				   psock->ingress_bytes);
>  	tcp_rcv_space_adjust(sk);
>  	__tcp_cleanup_rbuf(sk, copied - psock->ingress_bytes);

Can this double count dropped bytes in tp->copied_seq?

The new code assumes nothing else writes tp->copied_seq for strparser skbs
while tcp_read_sock_noack() runs.  But on an SK_DROP verdict,
sk_psock_verdict_apply() does:

    case __SK_DROP:
    default:
    out_free:
            skb_bpf_redirect_clear(skb);
            tcp_eat_skb(psock->sk, skb);
            sock_drop(psock->sk, skb);

and tcp_eat_skb() skips strparser skbs only if skb_bpf_strparser(skb) is
set:

    if (skb_bpf_strparser(skb))
            return;
    tcp = tcp_sk(sk);
    copied = tcp->copied_seq + skb->len;
    WRITE_ONCE(tcp->copied_seq, copied);

skb_bpf_redirect_clear() has already cleared BPF_F_STRPARSER at that point,
so tcp_eat_skb() adds skb->len to tp->copied_seq.  Then, when
tcp_read_sock_noack() returns, the line above adds the same bytes again via
psock->copied_seq - seq, since dropped bytes are not part of ingress_bytes.

For example, with a 100 byte message in one skb at P == tp->copied_seq ==
psock->copied_seq and a verdict of SK_DROP, tcp_eat_skb() sets tp->copied_seq
to P+100, and __tcp_read_sock() sets psock->copied_seq to P+100.  Then:

    tp->copied_seq = (P+100) + (P+100) - P - 0 = P+200

while rcv_nxt is P+100.

The old code also called tcp_eat_skb() here, but the absolute assignment
overwrote its write at the end of each read_sock call.  With the
read-modify-write, the extra skb->len stays in tp->copied_seq.

Once copied_seq passes rcv_nxt, tcp_epollin_ready() sees no available data,
tcp_data_ready() stops waking the parser, and tcp_bpf_recvmsg_parser()
returns -EAGAIN while skbs sit on sk_receive_queue.  That is the symptom this
commit is meant to fix.  Each further drop adds to the drift.

This looks reachable with any stream_verdict program that returns SK_DROP,
or bpf_sk_redirect_map() on an empty slot.  The SK_PASS paths that reach
out_free (SOCK_DEAD, !SK_PSOCK_TX_ENABLED) look like they hit it too.

Should tcp_eat_skb() be called before skb_bpf_redirect_clear() in out_free,
or should the strparser bit be tested before it is cleared?  The selftests
in prog_tests/sockmap_strp.c do not appear to have an SK_DROP case.



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix copied_seq updates with strparser
CI run summary: https://github.com/mrpre/bpf/actions/runs/45106916836

@mrpre

mrpre commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

@claude

@github-actions

Copy link
Copy Markdown
commit 8370f785a6cdf61f41fcf7d52d68bf202d15bfcc
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix concurrent senders on one psock

This adds a tx_mutex to the psock and holds it across the whole
tcp_bpf_sendmsg(), so that concurrent senders no longer share the verdict,
apply_bytes, sk_redir and cork state. A second sender waits for the mutex,
or gets -EAGAIN with MSG_DONTWAIT.

> bpf, sockmap: Fix concurrent senders on one psock

TL;DR: In tcp_bpf_sendmsg(), the new tx_mutex contention path returns -EAGAIN
without setting SOCK_NOSPACE, so a non-blocking sender may get no later
EPOLLOUT wakeup and edge-triggered waiters could stall.

> diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c
> --- a/net/ipv4/tcp_bpf.c
> +++ b/net/ipv4/tcp_bpf.c

[ ... ]

> @@ -602,6 +602,20 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
>  	if (unlikely(!psock))
>  		return tcp_sendmsg(sk, msg, size);
>  
> +	/*
> +	 * The verdict, apply_bytes, sk_redir and the cork live in the psock
> +	 * and span the places where the socket lock is dropped below. They
> +	 * can only serve one sender at a time.
> +	 */
> +	if (!(msg->msg_flags & MSG_DONTWAIT))
> +		err = mutex_lock_interruptible(&psock->tx_mutex);
> +	else if (!mutex_trylock(&psock->tx_mutex))
> +		err = -EAGAIN;
> +	if (err) {
> +		sk_psock_put(sk, psock);
> +		return err;
> +	}
> +

Can this -EAGAIN leave a non-blocking sender without a later EPOLLOUT
wakeup?

__tcp_check_space() returns early unless SOCK_NOSPACE is set:

    if (!sock || !test_bit(SOCK_NOSPACE, &sock->flags))
            return;
    tcp_new_space(sk);

and sk_stream_wait_memory() documents the contract at its do_eagain label:

    /* Make sure that whenever EAGAIN is returned, EPOLLOUT event can
     * be generated later. ... */
    sk_set_nospace(sk);
    err = -EAGAIN;

Before this patch tcp_bpf_sendmsg() only returned -EAGAIN from
sk_stream_wait_memory() or tcp_sendmsg_locked(), both of which set
SOCK_NOSPACE.  The new path returns -EAGAIN while the send buffer may have
plenty of room, and does not set SOCK_NOSPACE.  The holder's
mutex_unlock(), release_sock() and sk_psock_put() do not call
sk->sk_write_space() either, and tcp_poll() keeps reporting EPOLLOUT
because the send buffer is writable.

One way to hit it is sk_psock_backlog() sending through
sk_psock_handle_skb()->skb_send_sock()->__skb_send_sock()->sendmsg_unlocked()
->sock_sendmsg()->tcp_bpf_sendmsg() while the application does a
non-blocking send().  Two application threads, or a holder sleeping in
tcp_bpf_push_locked() on a full redirect target, would also do it.

An EPOLLOUT|EPOLLET waiter would then get no further edge, since nothing
set SOCK_NOSPACE, and may stall until an unrelated event wakes it.
Level-triggered poll/select users would see EPOLLOUT immediately and get
-EAGAIN from send() for as long as the other sender holds tx_mutex, which
can be unbounded when the holder sleeps on a redirect target.

tls_sw_sendmsg() does not behave this way, since it takes tx_lock with
mutex_lock_interruptible() and never returns -EAGAIN on contention.
sk_psock_backlog() does not need the wakeup because it reschedules itself
with schedule_delayed_work(&psock->work, 1).

Should this call sk_set_nospace(sk) before returning -EAGAIN, and have the
mutex holder call sk->sk_write_space(sk) after mutex_unlock() when
SOCK_NOSPACE is set?

[ ... ]



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix concurrent senders on one psock
CI run summary: https://github.com/mrpre/bpf/actions/runs/45132074264

@github-actions

Copy link
Copy Markdown
commit 847ec6647368782438686acc9e6a48942df453f9
Author: Jiayuan Chen <[email protected]>

> bpf, sockmap: Fix copied_seq updates with strparser

TL;DR: Commit message only: it may be inaccurate in saying tcp_data_ready()
releases the socket lock; only tcp_msg_wait_data() drops it. The review
suggests rewording; the code fix looks right.

> bpf, sockmap: Fix copied_seq updates with strparser
>
> With strparser, read_sock advances tp->copied_seq when it pulls skbs
> off sk_receive_queue, and recvmsg() advances it again when the user
> reads from ingress_msg. For a skb that the verdict passes back to the
> same socket, this counted the bytes twice, so commit 36b62df5683c
> ("bpf: Fix wrong copied_seq calculation") added psock->ingress_bytes to
> record how many bytes went to self and take them out of the read_sock
> side.
>
> That works for RPC style traffic, where each reply is read before the
> next one arrives. But psock->copied_seq is advanced on every read_sock
> call while ingress_bytes is reset on every call, so tp->copied_seq
> moves forward whenever a new skb arrives, even if the user never calls
> recvmsg(). Once the parser runs twice before a read, the SK_PASS bytes
> of the first run are no longer subtracted and tp->copied_seq already
> covers them. recvmsg() then adds them again and copied_seq passes
> rcv_nxt. The socket now looks empty to TCP, the parser is not woken for
> new data anymore and recvmsg() keeps returning -EAGAIN while the skbs
> sit on sk_receive_queue.
>
> tcp_bpf_recvmsg_parser() has the same problem from the other side. It
> snapshots tp->copied_seq at entry and writes the snapshot plus
> copied_from_self back at exit. tcp_data_ready() and tcp_msg_wait_data()
> release the socket lock in between, and the parser can consume data and
> advance copied_seq meanwhile. Writing the snapshot back rewinds that
> progress and leaves copied_seq behind the queued data.
>
> tp->copied_seq should only cover bytes that have left the socket: what
> the verdict redirected or dropped, plus what the user has read. SK_PASS
> bytes still queued in ingress_msg must not count until recvmsg() hands
> them out. So let both sides add only their own delta to the current
> tp->copied_seq instead of recomputing it from a saved value. The
> read_sock side advances by what this call consumed minus what it passed
> to self, taking the delta from psock->copied_seq rather than the return
> value so that the FIN byte is still counted. The recvmsg() side adds
> copied_from_self, and counts the FIN there as well. Either change alone
> moves the mismatch to the other side, so they go together.
>
> ingress_bytes is also bumped from sk_psock_skb_ingress_enqueue(), which
> the backlog work reaches without the socket lock for skbs redirected
> from other sockets. Those bytes are not part of this socket's stream
> and recvmsg() never adds them back, so subtracting them leaves
> copied_seq behind. Count only in sk_psock_skb_ingress_self(), where
> msg->sk is set, which is what recvmsg() checks.
>
> A strparser skb has no owner when the verdict runs.
> sk_psock_skb_ingress_self() sets one with skb_set_owner_r(), and when
> the enqueue fails after that, the skb is left to the backlog with
> skb->sk still set. It is not in ingress_bytes, so read_sock has already
> counted it as consumed. But the backlog picks the path by skb->sk:
>
>   sk_psock_backlog
>     sk_psock_handle_skb
>       sk_psock_skb_ingress
>         if (skb->sk == sk)
>           sk_psock_skb_ingress_self   <- sets msg->sk
>
> and recvmsg() counts the bytes again. So once a strparser skb is left
> to the backlog, it must not take the skb->sk == sk path. Drop the owner
> with skb_orphan() when the enqueue fails, in sk_psock_skb_ingress() as
> well, where the backlog sets the owner before the enqueue. This also
> gives the rmem charge back, and the backlog charges the skb again like
> any other strparser skb queued there. Picking the path by skb->sk is
> nasty and will be reworked later.
>
> The drop path clears the strparser bit before tcp_eat_skb(), so
> tcp_eat_skb() no longer skips the skb and adds skb->len to
> tp->copied_seq. The old code overwrote that at the end of read_sock.
> With the delta it would stay, so call tcp_eat_skb() first.
>
> Fixes: 36b62df5683c ("bpf: Fix wrong copied_seq calculation")
> Fixes: e5c6de5fa025 ("bpf, sockmap: Incorrectly handling copied_seq")
> Cc: [email protected]
> Reported-by: Vega <[email protected]>
> Suggested-by: Alexei Starovoitov <[email protected]>
> Co-developed-by: Zhiling Zou <[email protected]>
> Signed-off-by: Zhiling Zou <[email protected]>
> Signed-off-by: Jiayuan Chen <[email protected]>

This patch changes how tp->copied_seq is updated in the sockmap strparser
read_sock path and in tcp_bpf_recvmsg_parser(), by adding deltas instead of
writing back saved values.

> tcp_bpf_recvmsg_parser() has the same problem from the other side. It
> snapshots tp->copied_seq at entry and writes the snapshot plus
> copied_from_self back at exit. tcp_data_ready() and tcp_msg_wait_data()
> release the socket lock in between, and the parser can consume data and
> advance copied_seq meanwhile.

Is it accurate to say that tcp_data_ready() releases the socket lock?

In tcp_bpf_recvmsg_parser() it runs under lock_sock().  With strparser,
sk_psock_strp_data_ready() -> strp_data_ready() sees
sock_owned_by_user_nocheck() and only calls queue_work(), so nothing is
consumed there.

With read_skb and no parser, sk_psock_verdict_data_ready() runs the verdict
synchronously under the held lock, and tcp_eat_skb() advances copied_seq
after the old snapshot.  Only tcp_msg_wait_data() (via sk_wait_event())
drops the lock.

The conclusion that the snapshot can be stale looks right, but could the
sentence say that tcp_data_ready() runs the read_skb verdict synchronously
and that tcp_msg_wait_data() is what drops the lock?



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix copied_seq updates with strparser
CI run summary: https://github.com/mrpre/bpf/actions/runs/45132074264

@mrpre

mrpre commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

@claude

@github-actions

Copy link
Copy Markdown
commit a363dd426e6dcbd167ec25ffa1d41ef03f65e059
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix concurrent senders on one psock

This commit adds a tx_mutex to struct sk_psock and holds it for the whole
of tcp_bpf_sendmsg(), so that only one sender at a time uses the verdict,
apply_bytes, sk_redir and cork state kept in the psock.

> bpf, sockmap: Fix concurrent senders on one psock

TL;DR: Nit only: with tx_mutex now serializing senders, comments in
tcp_bpf_send_verdict() still describe concurrent senders, and the !psock->cork
test may be redundant.

> diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c
> --- a/net/ipv4/tcp_bpf.c
> +++ b/net/ipv4/tcp_bpf.c

[ ... ]

> @@ -599,6 +599,17 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
>  	if (unlikely(!psock))
>  		return tcp_sendmsg(sk, msg, size);
>  
> +	/*
> +	 * The verdict, apply_bytes, sk_redir and the cork live in the psock
> +	 * and span the places where the socket lock is dropped below. They
> +	 * can only serve one sender at a time.
> +	 */
> +	err = mutex_lock_interruptible(&psock->tx_mutex);
> +	if (err) {
> +		sk_psock_put(sk, psock);
> +		return err;
> +	}
> +

this isn't a bug, but now that tx_mutex serializes the senders, should the
comments in tcp_bpf_send_verdict() that still describe a concurrent sender
be updated, here or in a follow-up?

They contradict the comment added above:

	/* Another sender can use up the rest during the push */

	 * Another thread can make a cork while this one sends msg
	 * without the socket lock. Leave that cork alone.

	 * another thread made a new cork while the lock was released.

Is the !psock->cork test next to the last of those comments still needed,
given that nothing else can set psock->cork while the socket lock is
dropped?



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix concurrent senders on one psock
CI run summary: https://github.com/mrpre/bpf/actions/runs/45141848465

mrpre added a commit that referenced this pull request Nov 24, 2026
security_inet_csk_clone() is called at the end of inet_csk_clone_lock().
The child is locked, which is why the hook is in
bpf_lsm_locked_sockopt_hooks, but it is not set up yet:
icsk->icsk_ca_ops and the ipv6_pinfo still point to the ones of the
listener, and the timers are not initialized.

So bpf_setsockopt() from a lsm_cgroup prog is wrong there for:

 - TCP_CONGESTION: puts icsk->icsk_ca_ops, which the child holds no
   reference on.
 - IPV6_TCLASS, IPV6_AUTOFLOWLABEL: write to the ipv6_pinfo of the
   listener.
 - SO_KEEPALIVE, TCP_KEEPIDLE: arm the keepalive timer before
   tcp_init_xmit_timers() sets it up.

Options considered:
 1. Remove the hook from bpf_lsm_locked_sockopt_hooks, as commit
    5416c9a ("bpf: Fix the kernel crash caused by bpf_setsockopt().")
    did for socket_sock_rcv_skb. Not done, setting options like
    SO_PRIORITY on the child is what the hook is used for and it works.
 2. Make these options work. This needs the child set up before the
    hook, too much for a fix.

So give the hook its own bpf_setsockopt() and return -EOPNOTSUPP for
these options there. bpf_getsockopt() is left as is.

For example, SO_KEEPALIVE ends up with:

  Oops: general protection fault, probably for non-canonical address 0xfbd59c0000000025: 0000 [#1] SMP KASAN PTI
  KASAN: maybe wild-memory-access in range [0xdead000000000128-0xdead00000000012f]
  RIP: 0010:__run_timers+0x5d2/0xab0
  Call Trace:
   <IRQ>
   run_timer_base+0x107/0x190
   run_timer_softirq+0x1a/0x40
   handle_softirqs+0x251/0xa70
   __irq_exit_rcu+0x1a8/0x260
   irq_exit_rcu+0xe/0x30
   sysvec_apic_timer_interrupt+0xc2/0x110
   </IRQ>

Fixes: 9113d7e ("bpf: expose bpf_{g,s}etsockopt to lsm cgroup")
Signed-off-by: Jiayuan Chen <[email protected]>
@mrpre

mrpre commented Nov 24, 2026

Copy link
Copy Markdown
Owner Author

@claude

@mrpre

mrpre commented Nov 26, 2026

Copy link
Copy Markdown
Owner Author

@claude

@github-actions

Copy link
Copy Markdown
commit 436ebfa113713dac1537837b482c5a0ffe5f8163
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix empty sk_msg queued by ingress redirect

This commit makes bpf_tcp_ingress() return early when the sk_msg is empty,
so a message fully popped by bpf_msg_pop_data() is no longer queued as a
zero sized sk_msg on the peer's ingress_msg.

> bpf, sockmap: Fix empty sk_msg queued by ingress redirect

TL;DR: Commit message only: the Fixes: tag may be wrong, since 7246d8ed4dcc
rejected popping the whole message; 5d609ba26247 first allowed it and may be
the right target.

>     bpf, sockmap: Fix empty sk_msg queued by ingress redirect
>
>     An SK_MSG program can pop the whole message with bpf_msg_pop_data() and
>     then redirect it with BPF_F_INGRESS. tcp_bpf_send_verdict() does not
>     check for that and calls bpf_tcp_ingress() with nothing to send. Its
>     do-while loop still walks the empty ring, charges zero bytes and queues
>     a zero sized sk_msg on the peer's ingress_msg.
>     __sk_msg_recvmsg() hits the zero length element first, returns -EFAULT
>     and never dequeues it, so every later message on that socket sits
>     behind it and recvmsg() keeps failing. Only tearing down the psock gets
>     rid of it.
>     Return early from bpf_tcp_ingress() when the message is empty. SK_PASS
>     and egress redirect already send nothing in that case.
>     Fixes: 7246d8ed4dcc ("bpf: helper to pop data from messages")
>     Signed-off-by: Jiayuan Chen <[email protected]>

In 7246d8ed4dcc ("bpf: helper to pop data from messages"), bpf_msg_pop_data()
rejected popping the entire message, because the bounds check
'last >= msg->sg.size' returned -EINVAL.  An empty sk_msg could therefore not
be produced and redirected at that point.

Popping the whole message was first allowed by 5d609ba26247 ("bpf, sockmap:
Several fixes to bpf_msg_pop_data"), which changed the check to
'last > msg->sg.size'.

Should the Fixes: tag point at that commit instead:

  Fixes: 5d609ba26247 ("bpf, sockmap: Several fixes to bpf_msg_pop_data")



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix empty sk_msg queued by ingress redirect
CI run summary: https://github.com/mrpre/bpf/actions/runs/45737398136

@github-actions

Copy link
Copy Markdown
commit b78b779e0c1e5825c87deab4dfa4d42e97af571c
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix concurrent senders on one psock

This adds a tx_mutex to struct sk_psock and holds it for the whole of
tcp_bpf_sendmsg(), so a second sender on the same psock waits instead of
running with the verdict, apply_bytes, sk_redir and cork of the first.

> bpf, sockmap: Fix concurrent senders on one psock

TL;DR: Comments only: tcp_bpf_send_verdict() still describes other senders
racing on the psock, which may contradict the new tx_mutex serialization. Asks
whether they should be updated or dropped.

> diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c
> --- a/net/ipv4/tcp_bpf.c
> +++ b/net/ipv4/tcp_bpf.c

[ ... ]

> @@ -597,16 +597,27 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
>  	psock = sk_psock_get(sk);
>  	if (unlikely(!psock))
>  		return tcp_sendmsg(sk, msg, size);
>  
> +	/*
> +	 * The verdict, apply_bytes, sk_redir and the cork live in the psock
> +	 * and span the places where the socket lock is dropped below. They
> +	 * can only serve one sender at a time.
> +	 */
> +	err = mutex_lock_interruptible(&psock->tx_mutex);
> +	if (err) {
> +		sk_psock_put(sk, psock);
> +		return err;
> +	}
> +
>  	lock_sock(sk);

this isn't a bug, but tcp_bpf_send_verdict() still has comments describing
other senders racing on the same psock, for example:

	/*
	 * Another thread can make a cork while this one sends msg
	 * without the socket lock. Leave that cork alone.
	 */
	if (psock->cork == msg) {

and:

	/*
	 * The verdict was for tosend bytes. The rest goes back, unless
	 * another thread made a new cork while the lock was released.
	 */

and, in the SK_PASS error path:

	/* Another sender can use up the rest during the push */

As far as I can see, psock->cork, apply_bytes, eval and sk_redir are only
written from tcp_bpf_send_verdict() and sk_psock_msg_verdict(), both of
which now run only from tcp_bpf_sendmsg() under tx_mutex.

Can another sender still create a cork or use up apply_bytes while the
socket lock is dropped?  If not, should these comments be updated or
dropped together with this change, since they now read as if they
contradict the new "They can only serve one sender at a time" comment?



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix concurrent senders on one psock
CI run summary: https://github.com/mrpre/bpf/actions/runs/45737398136

@github-actions

Copy link
Copy Markdown
commit 86f705671e0bce35eb3f1cceb88a964f106951e9
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix reconnect with a psock by rejecting disconnect

This commit makes tcp_bpf_disconnect() reject disconnect with -EOPNOTSUPP
for sockets that have a psock, so that connect() -> disconnect -> connect()
cannot reuse stale psock state.  Children not yet accepted, listeners and
sockets in close() (marked by a new SK_PSOCK_CLOSING bit) are let through.

> bpf, sockmap: Fix reconnect with a psock by rejecting disconnect

TL;DR: A psock attached after sock_map_close() may lack SK_PSOCK_CLOSING, so
tcp_bpf_disconnect() could reject the zero-linger abort in tcp_close(),
possibly leaking the orphaned socket and its psock.

> diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c
> index 5c01a4d78c16..705f57458141 100644
> --- a/net/ipv4/tcp_bpf.c
> +++ b/net/ipv4/tcp_bpf.c

[ ... ]

> @@ -711,12 +711,33 @@ static struct proto *tcpv6_prot_saved __read_mostly;
>  static DEFINE_SPINLOCK(tcpv6_prot_lock);
>  static struct proto tcp_bpf_prots[TCP_BPF_NUM_PROTS][TCP_BPF_NUM_CFGS];
>  
> +static int tcp_bpf_disconnect(struct sock *sk, int flags)
> +{
> +	struct sk_psock *psock;
> +	bool reject;
> +
> +	/*
> +	 * A new connection must not reuse the psock. Let through a child
> +	 * that nobody has accepted yet, a socket in close() and a listener.
> +	 */
> +	rcu_read_lock();
> +	psock = sk_psock(sk);
> +	reject = psock && sk->sk_socket && sk->sk_state != TCP_LISTEN &&
> +		 !sk_psock_test_state(psock, SK_PSOCK_CLOSING);

The close() exemption depends on SK_PSOCK_CLOSING, which sock_map_close()
sets on the psock attached at that moment.  Can a psock attached after
sock_map_close() be the one tcp_bpf_disconnect() sees from __tcp_close()?

sock_map_close() drops its reference with sk_psock_put() and then calls
saved_close, which is tcp_close().  If that put is the last one,
sk_psock_drop() restores sk_prot and clears sk_user_data.  A BPF program
that may update a sockmap (a bpf_iter__sockmap copy program, or
SK_LOOKUP/SK_REUSEPORT) can then insert the same socket into a map through
sock_map_update_elem().  That function takes only bh_lock_sock() and checks
only that the state is TCP_ESTABLISHED, so it can run even while tcp_close()
owns the socket:

    local_bh_disable();
    bh_lock_sock(sk);
    if (!sock_map_sk_state_allowed(sk))
    ...
        ret = sock_map_update_common(map, *(u32 *)key, sk, flags);

sock_map_link() then finds no psock and calls sk_psock_init().  The new
psock has only SK_PSOCK_TX_ENABLED set, and sk_prot is switched back to
tcp_bpf_prots, so .disconnect is tcp_bpf_disconnect() again.  The sockmap
iterator reads the socket under RCU and takes no reference, so it can read
the element before sock_map_remove_links() and call the update after
sk_psock_drop().

In __tcp_close(), the zero-linger branch (and the tp->repair branch) ignores
the return value:

    } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
        /* Check zero linger _after_ checking for unread data. */
        sk->sk_prot->disconnect(sk, 0);
        NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);

At that point sk->sk_socket is still set, because sock_orphan() runs later
at adjudge_to_death.  The state is TCP_ESTABLISHED and the new psock does
not have SK_PSOCK_CLOSING set, so the disconnect is rejected with
-EOPNOTSUPP.  No RST is sent and the state stays TCP_ESTABLISHED.

adjudge_to_death then orphans the socket and skips inet_csk_destroy_sock(),
because sk_state != TCP_CLOSE.  Can the orphan stay in the ehash and in the
map, holding the psock, with no FIN and no timer unless keepalive is set?
If the peer is idle, or later sends a FIN (CLOSE_WAIT), the socket would
never be freed.

Before this patch the same interleaving ran tcp_disconnect().  That moved
the socket to TCP_CLOSE and sent the RST, and inet_csk_destroy_sock() ->
sock_map_destroy() then removed the new psock.

Could the close() case be recognised without relying on a bit in one
particular psock, so that a psock attached after sock_map_close() cannot
make __tcp_close() silently skip the abort?

> +	rcu_read_unlock();
> +	if (reject)
> +		return -EOPNOTSUPP;
> +
> +	return tcp_disconnect(sk, flags);
> +}

[ ... ]



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix reconnect with a psock by rejecting disconnect
CI run summary: https://github.com/mrpre/bpf/actions/runs/45737398136

@mrpre

mrpre commented Nov 26, 2026

Copy link
Copy Markdown
Owner Author

@claude

@github-actions

Copy link
Copy Markdown
commit b78b779e0c1e5825c87deab4dfa4d42e97af571c
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix concurrent senders on one psock

This adds a tx_mutex to struct sk_psock and holds it for the whole of
tcp_bpf_sendmsg(), so a second sender on the same psock waits for the
first one instead of using its verdict, apply_bytes, sk_redir and cork.

> bpf, sockmap: Fix concurrent senders on one psock

TL;DR: New tx_mutex wait in tcp_bpf_sendmsg() uses mutex_lock_interruptible(),
so a blocked second sender may get -EINTR instead of a transparent restart,
and ignores SO_SNDTIMEO; the commit message omits this.

> diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c
> --- a/net/ipv4/tcp_bpf.c
> +++ b/net/ipv4/tcp_bpf.c

[ ... ]

> @@ -602,6 +602,17 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
>  	if (unlikely(!psock))
>  		return tcp_sendmsg(sk, msg, size);
>  
> +	/*
> +	 * The verdict, apply_bytes, sk_redir and the cork live in the psock
> +	 * and span the places where the socket lock is dropped below. They
> +	 * can only serve one sender at a time.
> +	 */
> +	err = mutex_lock_interruptible(&psock->tx_mutex);
> +	if (err) {
> +		sk_psock_put(sk, psock);
> +		return err;
> +	}
> +
>  	lock_sock(sk);
>  	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
>  	while (msg_data_left(msg)) {

Can this return -EINTR to user space where send() used to be restarted?

Before this patch a second blocking sender waited in lock_sock(), which
ignores signals, and then in sk_stream_wait_memory(), which returns
sock_intr_errno(*timeo_p), i.e. -ERESTARTSYS when no SO_SNDTIMEO is set.
A SA_RESTART handler or a stop signal therefore restarted send()
transparently.

Now the second sender sleeps in mutex_lock_interruptible() for as long as
the first sender is blocked in sk_stream_wait_memory() or tcp_bpf_push(),
which can be unbounded without SO_SNDTIMEO.  Any signal in that window
makes send() fail with -EINTR, even with SA_RESTART:

sendmsg()
  sock_sendmsg()
    inet_sendmsg()
      tcp_bpf_sendmsg()
        mutex_lock_interruptible(&psock->tx_mutex)  /* returns -EINTR */
        return err;

The commit message models this on tls_sw_sendmsg(), which has the same
behaviour.  Would it be better to compute timeo with sock_sndtimeo()
before taking the mutex and return sock_intr_errno(timeo) on failure, as
rxrpc_do_sendmsg() does with 'ret = sock_intr_errno(timeo);'?

Related to that, the second sender's SO_SNDTIMEO is not honoured while it
waits for tx_mutex either.  The commit message covers MSG_DONTWAIT but
mentions neither timeouts nor restarts.



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix concurrent senders on one psock
CI run summary: https://github.com/mrpre/bpf/actions/runs/45815466644

@github-actions

Copy link
Copy Markdown
commit 86f705671e0bce35eb3f1cceb88a964f106951e9
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix reconnect with a psock by rejecting disconnect

This commit makes tcp_bpf_disconnect() reject disconnect with -EOPNOTSUPP
for sockmap sockets that have a psock, so a reconnect cannot reuse stale
psock state.  Child sockets without sk_socket, listeners and sockets whose
psock has SK_PSOCK_CLOSING set are let through.

> bpf, sockmap: Fix reconnect with a psock by rejecting disconnect

TL;DR: A narrow race, if a sockmap iterator re-inserts a socket already in
close(), may make tcp_bpf_disconnect() return -EOPNOTSUPP, leaving an orphaned
socket established and linked in the map.

> diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c
> --- a/net/ipv4/tcp_bpf.c
> +++ b/net/ipv4/tcp_bpf.c

[ ... ]

> +static int tcp_bpf_disconnect(struct sock *sk, int flags)
> +{
> +	struct sk_psock *psock;
> +	bool reject;
> +
> +	/*
> +	 * A new connection must not reuse the psock. Let through a child
> +	 * that nobody has accepted yet, a socket in close() and a listener.
> +	 */
> +	rcu_read_lock();
> +	psock = sk_psock(sk);
> +	reject = psock && sk->sk_socket && sk->sk_state != TCP_LISTEN &&
> +		 !sk_psock_test_state(psock, SK_PSOCK_CLOSING);

SK_PSOCK_CLOSING is a property of one psock, while being in close() is a
property of the socket.  Can a socket in close() end up with a psock that
does not have the bit set?

With a sockmap iterator that copies sockets into another map (the copy()
use case in progs/bpf_iter_sockmap.c), this interleaving looks possible:

CPU0 (iter, rcu_read_lock only)          CPU1 close(), SO_LINGER {1, 0}

sock_map_seq_lookup_elem(): info->sk = sk
                                         sock_map_close()
                                           sock_map_remove_links(sk, A)
                                           sk_psock_set_state(A, SK_PSOCK_CLOSING)
                                           release_sock(sk)
                                           sk_psock_put(sk, A)
                                             -> sk_psock_drop()
                                             restores tcp_prot
bpf_map_update_elem(&dst, &key, sk, 0)
  sock_map_update_elem(): bh_lock_sock() only
  sock_map_link() -> sk_psock_init() -> psock B
  tcp_bpf_update_proto() -> sk_prot = tcp_bpf
                                         tcp_close() -> __tcp_close()
                                           sk->sk_prot->disconnect(sk, 0)
                                           = tcp_bpf_disconnect()

Here tcp_bpf_disconnect() sees psock B, sk->sk_socket is still set, the
state is not TCP_LISTEN and B has no SK_PSOCK_CLOSING, so it returns
-EOPNOTSUPP, and __tcp_close() ignores the return value.

__tcp_close() then continues to sk_stream_wait_close() and reaches
adjudge_to_death with sk_state still TCP_ESTABLISHED.  No RST or FIN is
sent and the queues are not purged, so the orphaned socket stays
established and linked in the dst map until the peer resets or closes it.

Before this patch the disconnect always went to tcp_disconnect(), and the
following inet_csk_destroy_sock() -> sock_map_destroy() removed the new
links.

The window is narrow and needs a BPF program that re-inserts sockets, so
this is a race and not a deterministic failure.

Could the close() exemption be tied to the socket instead of the psock, or
could sock_map_link() refuse sockets that are already in close()?

> +	rcu_read_unlock();
> +	if (reject)
> +		return -EOPNOTSUPP;
> +
> +	return tcp_disconnect(sk, flags);
> +}

[ ... ]



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix reconnect with a psock by rejecting disconnect
CI run summary: https://github.com/mrpre/bpf/actions/runs/45815466644

@mrpre
mrpre force-pushed the bpf_base_test branch 3 times, most recently from b43aed1 to c952c98 Compare November 26, 2026 12:33
@mrpre

mrpre commented Nov 26, 2026

Copy link
Copy Markdown
Owner Author

@claude

@github-actions

Copy link
Copy Markdown
commit dd5a5b8dc290dfc1282ad2846eba3f001eaa6e76
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix socket lock taken on a child before accept()

This commit avoids taking lock_sock() on a child socket that has not been
accepted yet. Egress redirects to such a child are refused before the lock,
ingress redirects use lock_sock_fast(), and sock_map_free()/sock_hash_free()
unlink such a child without the lock.

> bpf, sockmap: Fix socket lock taken on a child before accept()

TL;DR: Switching bpf_tcp_ingress() to lock_sock_fast() may make the memcg
charge atomic and forced, so ingress redirects could exceed memory.max with no
sk_rcvbuf check; the review asks whether that is intended.

> diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c
> --- a/net/ipv4/tcp_bpf.c
> +++ b/net/ipv4/tcp_bpf.c

[ ... ]

> @@ -46,7 +47,11 @@ static int bpf_tcp_ingress(struct sock *sk, struct sk_psock *psock,
>  	if (unlikely(!tmp))
>  		return -ENOMEM;
>
> -	lock_sock(sk);
> +	/*
> +	 * sk may be a child that nobody has accepted yet. The listener frees
> +	 * it under bh_lock_sock() and doesn't expect an owner.
> +	 */
> +	slow = lock_sock_fast(sk);
>  	tmp->sg.start = msg->sg.start;
>  	i = msg->sg.start;
>  	do {

[ ... ]

When the target has no owner, lock_sock_fast() returns with sk_lock.slock
held and BH disabled, and __sk_rmem_schedule() then runs in that section:

  __sk_rmem_schedule()
    __sk_mem_schedule()
      __sk_mem_raise_allocated()
        charged = mem_cgroup_sk_charge(sk, amt, gfp_memcg_charge());

  static inline gfp_t gfp_memcg_charge(void)
  {
  	return in_softirq() ? GFP_ATOMIC : GFP_KERNEL;
  }

Before this patch the code ran under lock_sock(), so the charge used
GFP_KERNEL and try_charge_memcg() could reclaim in the target's memcg and
fail with -ENOMEM, making __sk_rmem_schedule() fail.

With BH disabled the charge is GFP_ATOMIC, which has __GFP_HIGH, so
try_charge_memcg() takes the force path:

  nomem:
  	if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH))) {
  		ret = -ENOMEM;
  		goto out;
  	}
  force:
  	page_counter_charge(&memcg->memory, nr_pages);

Can this let an ingress redirect charge past memory.max?

Normal TCP receive also force-charges from softirq, but
tcp_try_rmem_schedule() bounds it by sk_rcvbuf first, and the skb ingress
path checks sk_rmem_alloc > sk_rcvbuf.  bpf_tcp_ingress() has no such
check, so the memcg limit no longer bounds the data left on a target that
does not read, and with sk_bypass_prot_mem set nothing bounds it at all.

The commit message says the ingress path "only queues the data and never
sleeps".  The old GFP_KERNEL charge could sleep in memcg reclaim, so the
path doesn't sleep now only because the charge became a forced atomic
charge.

Is this intended?  Should bpf_tcp_ingress() check sk_rcvbuf, or charge
before taking the spinlock?



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix socket lock taken on a child before accept()
CI run summary: https://github.com/mrpre/bpf/actions/runs/45820900072

With strparser, read_sock advances tp->copied_seq when it pulls skbs
off sk_receive_queue, and recvmsg() advances it again when the user
reads from ingress_msg. For a skb that the verdict passes back to the
same socket, this counted the bytes twice, so commit 36b62df
("bpf: Fix wrong copied_seq calculation") added psock->ingress_bytes to
record how many bytes went to self and take them out of the read_sock
side.

That works for RPC style traffic, where each reply is read before the
next one arrives. But psock->copied_seq is advanced on every read_sock
call while ingress_bytes is reset on every call, so tp->copied_seq
moves forward whenever a new skb arrives, even if the user never calls
recvmsg(). Once the parser runs twice before a read, the SK_PASS bytes
of the first run are no longer subtracted and tp->copied_seq already
covers them. recvmsg() then adds them again and copied_seq passes
rcv_nxt. The socket now looks empty to TCP, the parser is not woken for
new data anymore and recvmsg() keeps returning -EAGAIN while the skbs
sit on sk_receive_queue.

tcp_bpf_recvmsg_parser() has the same problem from the other side. It
snapshots tp->copied_seq at entry and writes the snapshot plus
copied_from_self back at exit. In between, tcp_msg_wait_data() releases
the socket lock and tcp_data_ready() runs the verdict of read_skb under
it. Both can advance copied_seq after the snapshot. Writing the snapshot
back rewinds that progress and leaves copied_seq behind the queued data.

tp->copied_seq should only cover bytes that have left the socket: what
the verdict redirected or dropped, plus what the user has read. SK_PASS
bytes still queued in ingress_msg must not count until recvmsg() hands
them out. So let both sides add only their own delta to the current
tp->copied_seq instead of recomputing it from a saved value. The
read_sock side advances by what this call consumed minus what it passed
to self, taking the delta from psock->copied_seq rather than the return
value so that the FIN byte is still counted. The recvmsg() side adds
copied_from_self, and counts the FIN there as well. Either change alone
moves the mismatch to the other side, so they go together.

ingress_bytes is also bumped from sk_psock_skb_ingress_enqueue(), which
the backlog work reaches without the socket lock for skbs redirected
from other sockets. Those bytes are not part of this socket's stream
and recvmsg() never adds them back, so subtracting them leaves
copied_seq behind. Count only in sk_psock_skb_ingress_self(), where
msg->sk is set, which is what recvmsg() checks.

A strparser skb has no owner when the verdict runs.
sk_psock_skb_ingress_self() sets one with skb_set_owner_r(), and when
the enqueue fails after that, the skb is left to the backlog with
skb->sk still set. It is not in ingress_bytes, so read_sock has already
counted it as consumed. But the backlog picks the path by skb->sk:

  sk_psock_backlog
    sk_psock_handle_skb
      sk_psock_skb_ingress
        if (skb->sk == sk)
          sk_psock_skb_ingress_self   <- sets msg->sk

and recvmsg() counts the bytes again. So once a strparser skb is left
to the backlog, it must not take the skb->sk == sk path. Drop the owner
with skb_orphan() when the enqueue fails, in sk_psock_skb_ingress() as
well, where the backlog sets the owner before the enqueue. This also
gives the rmem charge back, and the backlog charges the skb again like
any other strparser skb queued there. Picking the path by skb->sk is
nasty and will be reworked later.

The drop path clears the strparser bit before tcp_eat_skb(), so
tcp_eat_skb() no longer skips the skb and adds skb->len to
tp->copied_seq. The old code overwrote that at the end of read_sock.
With the delta it would stay, so call tcp_eat_skb() first.

Fixes: 36b62df ("bpf: Fix wrong copied_seq calculation")
Fixes: e5c6de5 ("bpf, sockmap: Incorrectly handling copied_seq")
Cc: [email protected]
Reported-by: Vega <[email protected]>
Suggested-by: Alexei Starovoitov <[email protected]>
Co-developed-by: Zhiling Zou <[email protected]>
Signed-off-by: Zhiling Zou <[email protected]>
Signed-off-by: Jiayuan Chen <[email protected]>
An SK_MSG program can pop the whole message with bpf_msg_pop_data() and
then redirect it with BPF_F_INGRESS. tcp_bpf_send_verdict() does not
check for that and calls bpf_tcp_ingress() with nothing to send. Its
do-while loop still walks the empty ring, charges zero bytes and queues
a zero sized sk_msg on the peer's ingress_msg.

__sk_msg_recvmsg() hits the zero length element first, returns -EFAULT
and never dequeues it, so every later message on that socket sits
behind it and recvmsg() keeps failing. Only tearing down the psock gets
rid of it.

Return early from bpf_tcp_ingress() when the message is empty. SK_PASS
and egress redirect already send nothing in that case.

Fixes: 5d609ba ("bpf, sockmap: Several fixes to bpf_msg_pop_data")
Signed-off-by: Jiayuan Chen <[email protected]>
tcp_bpf_sendmsg() keeps the state of the current send in the psock:
the verdict in eval, the byte budget in apply_bytes, the redirect
target in sk_redir and the message being built in cork. The socket lock
does not protect that state all the way through. tcp_bpf_push() drops
it in sk_stream_wait_memory(), and the SK_REDIRECT branch of
tcp_bpf_send_verdict() drops it around tcp_bpf_sendmsg_redir(). A
second sendmsg() on the same socket then runs with the state of the
first one.

The cork is the worst case. The SK_PASS branch pushes psock->cork while
it is still attached. When the push sleeps, the second sender picks the
same cork up through psock->cork, appends to it, runs the prog on it,
and on SK_REDIRECT frees it. The first sender wakes up in
tcp_bpf_push() and writes to a freed sk_msg. The other fields are not
freed, but the second sender sends without a verdict, or with the
verdict and the budget of the first one.

Plain TCP has no state of this kind, and two senders on one stream
socket only get their bytes interleaved. Add a mutex to the psock and
hold it for the whole tcp_bpf_sendmsg(). A second sender waits for it.

tls_sw_sendmsg() does the same with tx_lock, and the wait is the same
as there. The mutex is taken with MSG_DONTWAIT as well, and SO_SNDTIMEO
does not apply to it. A trylock that returns -EAGAIN has nothing to wake
the sender up later, since the send buffer is not full.

sk_psock_backlog() is a sender too when an skb is redirected to the
egress of a socket with an sk_msg prog. So a bit in psock->state that
fails the second sender with -EBUSY is smaller, but it breaks the
backlog and a single user sender that runs into it.

Redirects to another socket go through tcp_bpf_push_locked() and
bpf_tcp_ingress() and do not touch the target's send state, so they are
not affected.

tcp_bpf_send_verdict() already has a few checks for a second sender,
added by earlier fixes. They do no harm with the mutex and are left
as they are, comments included, to keep this patch small.

Fixes: 4f738ad ("bpf: create tcp_bpf_ulp allowing BPF to monitor socket TX/RX data")
Signed-off-by: Jiayuan Chen <[email protected]>
sk_psock_backlog() runs for a given psock, but takes the reference with
sk_psock_get(psock->sk), which returns the psock that sk_user_data points
to now. That is the same psock only while psock->sk->psock == psock.

If sk is removed from the map and added back while the backlog runs, the
old psock is dropped and sk_user_data points to the new one. The backlog
of the old psock then takes a reference on the new psock and puts the old
one, whose refcnt is already 0. The old one hits a refcount underflow and
the new one leaks a reference. The SK_PSOCK_TX_ENABLED check before it
does not close this window.

Take the reference on the psock itself.

Fixes: 8259eb0 ("bpf, sockmap: Avoid using sk_socket after free when sending")
Signed-off-by: Jiayuan Chen <[email protected]>
@mrpre

mrpre commented Nov 27, 2026

Copy link
Copy Markdown
Owner Author

@claude

@github-actions

Copy link
Copy Markdown
commit 374f14e3dcd1018cf927c46eaa4c7c69c5cad0fa
Author: Jiayuan Chen <[email protected]>

bpf, sockmap: Fix socket lock taken on a child before accept()

This commit refuses an egress redirect to a not-yet-accepted child before
taking the socket lock, and switches bpf_tcp_ingress() to lock_sock_fast()
so an ingress redirect to such a child no longer sleeps.  It also unlinks
such children from sockmaps without the lock in sock_map_free() and
sock_hash_free().

> bpf, sockmap: Fix socket lock taken on a child before accept()

TL;DR: lock_sock_fast() in bpf_tcp_ingress() may make memcg charges GFP_ATOMIC
and force-succeed, so ingress redirects to a non-reading accepted socket could
grow the queue past memory.max with no sk_rcvbuf bound.

> diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c
> --- a/net/ipv4/tcp_bpf.c
> +++ b/net/ipv4/tcp_bpf.c

[ ... ]

> @@ -46,7 +47,11 @@ static int bpf_tcp_ingress(struct sock *sk, struct sk_psock *psock,
>  	if (unlikely(!tmp))
>  		return -ENOMEM;
>  
> -	lock_sock(sk);
> +	/*
> +	 * sk may be a child that nobody has accepted yet. The listener frees
> +	 * it under bh_lock_sock() and doesn't expect an owner.
> +	 */
> +	slow = lock_sock_fast(sk);

Can this remove the memcg limit on the ingress queue of an accepted
socket?  The commit message says the memcg "is still over its limit after
that, so the next allocation in it reclaims or hits OOM as before", but
that does not seem to hold when the next allocation is the next redirect.

In the fast path __lock_sock_fast() does spin_lock_bh(&sk->sk_lock.slock),
so in_softirq() is true.  The charge chain is:

bpf_tcp_ingress()
  __sk_rmem_schedule()
    __sk_mem_schedule()
      __sk_mem_raise_allocated()
        mem_cgroup_sk_charge(sk, amt, gfp_memcg_charge())

gfp_memcg_charge() returns "in_softirq() ? GFP_ATOMIC : GFP_KERNEL", so it
is now GFP_ATOMIC.  In try_charge_memcg(), a charge over memory.max then
does:

    if (!gfpflags_allow_blocking(gfp_mask))
            goto nomem;

and since GFP_ATOMIC has __GFP_HIGH, it falls through to the force label:

    page_counter_charge(&memcg->memory, nr_pages);

and returns 0, so the charge always succeeds on cgroup v2.  Before the
patch lock_sock() left BH enabled, the charge used GFP_KERNEL, reclaimed,
ran mem_cgroup_oom(), and finally failed with -ENOMEM, which made
bpf_tcp_ingress() stop queueing at the memcg limit.

After the patch, with net.core.bypass_prot_mem=1 __sk_mem_raise_allocated()
returns 1 right after the forced charge:

    if (sk->sk_bypass_prot_mem)
            return 1;

so nothing bounds the queue.  Otherwise only the global tcp_mem[2] limit
does.

The TCP softirq receive path that the commit message compares against is
bounded per socket, since tcp_try_rmem_schedule() checks tcp_can_ingest()
(sk_rmem_alloc against sk_rcvbuf) before sk_rmem_schedule().  The
skb-verdict ingress path, sk_psock_create_ingress_msg(), also checks:

    atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf

bpf_tcp_ingress() checks neither.

Consider an sk_msg prog redirecting with BPF_F_INGRESS into an accepted
socket in memcg B whose reader does not read.  The receiver is not in a
syscall, so every redirect takes the fast path.  tcp_bpf_send_verdict()
calls sk_mem_uncharge() on the sender after each transfer, so the sender
can keep calling sendmsg().  Each call force-charges B and grows
psock->ingress_msg past memory.max.  If B's tasks do not allocate, nothing
in B reclaims or OOM-kills.

The commit message defers the sk_rcvbuf check to a separate patch, and the
next commit in the range, f1a90c6a0357 ("bpf, sockmap: Fix apply_bytes when
a redirect sends only a part"), does not add it.  Should the sk_rcvbuf
bound come before, or together with, this change?



AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

In-Reply-To-Subject: bpf, sockmap: Fix socket lock taken on a child before accept()
CI run summary: https://github.com/mrpre/bpf/actions/runs/45931522562

A sockops prog can add a child that is not accepted yet to a sockmap at
BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB. An sk_msg redirect to this child,
ingress or egress, takes lock_sock() on it. If the listener is closed at
that time, inet_csk_listen_stop() hits:

	WARN_ON(sock_owned_by_user(child));

WARNING: net/ipv4/inet_connection_sock.c:1492 at inet_csk_listen_stop+0x7ba/0xc40
Call Trace:
 <TASK>
 __tcp_close+0xb64/0xee0
 tcp_close+0x24/0xf0
 inet_release+0x10a/0x240
 __sock_release+0xaf/0x270
 sock_close+0x18/0x30
 __fput+0x360/0xa90
 fput_close_sync+0xe6/0x1d0
 __x64_sys_close+0x80/0xe0
 x64_sys_call+0x2680/0x27e0
 do_syscall_64+0xe5/0x610
 entry_SYSCALL_64_after_hwframe+0x76/0x7e
 </TASK>

Commit 4aeaad1 ("bpf, sockmap: Check the target of an egress
redirect before each send") already refuses an egress redirect to such a
child, but only after lock_sock(). Do it before taking the lock: a child
has no sk_socket until accept() has taken it off the queue.

An ingress redirect to such a child works today and the data is read
after accept(), so it can't be refused. It only queues the data and
never sleeps, so take the lock of a child with lock_sock_fast() instead.
The child is not owned then and inet_csk_listen_stop() waits on
bh_lock_sock(). An accepted socket keeps lock_sock(). Under
lock_sock_fast() its memcg charge would be atomic and forced at the
limit. A child has no memcg until accept().

sock_map_free() and sock_hash_free() also lock the sockets in the map.
They can't refuse, so unlink such a child without the lock, as a delete
from the map already does.

A child with a strparser is still locked by strp_done() and the
strparser work. That is in the strparser code and is left for later.

Fixes: 604326b ("bpf, sockmap: convert to generic sk_msg interface")
Fixes: 7e81a35 ("bpf: Sockmap, ensure sock lock held during tear down")
Signed-off-by: Jiayuan Chen <[email protected]>
An sk_msg prog can parse the header of an application message and call
bpf_msg_apply_bytes() with the message length. The verdict then covers
the whole message, and the prog runs again at the next header:

  +-----+-----------+-----+-------+-----+------
  | hdr |   body    | hdr | body  | hdr | ...
  +-----+-----------+-----+-------+-----+------
  ^                 ^             ^
  prog: apply(len1) prog: apply(len2)
                                  prog: apply(len3)

For SK_REDIRECT, tcp_bpf_send_verdict() takes tosend bytes off
apply_bytes before the redirect. But the redirect can send only a part:
the ingress target can't get more memory, or the egress target has no
send buffer left. The rest stays in msg, or goes back to the user who
sends it again. The verdict has already used up these bytes, so the prog
runs on the rest, in the middle of a message:

  +-----+-----------+-----+-------+------
  | hdr |   body    | hdr | body  | ...
  +-----+-----------+-----+-------+------
  |<- apply(len1) ->|
  |<-- sent -->|
               ^
               prog runs here and takes body as a header

From then on the message boundaries are wrong.

Give back the bytes that were not sent, and keep the verdict while
apply_bytes is not 0. The bytes of a cork that fails are freed and
reported as sent, so they stay used.

A cork that is sent only in part is not fixed here. The rest is corked
again and the prog runs on it later, in the middle of the message as
before. That needs more work on the cork and is left for later.

This is for a target that is busy. If the target is dead, the verdict
is kept too and sendmsg() keeps failing. A part of the message is
already at the target and the rest can't go anywhere else, so the
message is lost anyway. Return the error and let the user decide.

Fixes: 604326b ("bpf, sockmap: convert to generic sk_msg interface")
Signed-off-by: Jiayuan Chen <[email protected]>
@mrpre

mrpre commented Nov 27, 2026

Copy link
Copy Markdown
Owner Author

@claude

mrpre pushed a commit that referenced this pull request Nov 29, 2026
Since the driver can use a regmap on a bus that can sleep, as for
VSC7512 attached over SPI, it still registers the gpiochip as not
sleeping and adds the chained irqchip when the node has an interrupt.
The chained handler and the irq_chip callbacks run in atomic context and
access the registers through that regmap, and consumers may use the
lines of a gpiochip that is not marked as sleeping from atomic context.

Mark the gpiochip as sleeping when the regmap can sleep, and do not
register the chained irqchip in that case.

The issue was found by code inspection and reproduced on a lan9668
board (pcb8385) with a lan9645x attached over SPI, whose pinctrl node
has an interrupt, by requesting an edge interrupt on one of its GPIOs
through the GPIO character device:

  BUG: sleeping function called from invalid context at kernel/locking/mutex.c:623
  in_atomic(): 1, irqs_disabled(): 128, non_block: 0, pid: 420, name: gpiomon
  preempt_count: 1, expected: 0
  locks held by gpiomon/420: 3, last CPU#0:
   #0: 84463cd0 (&gdev->srcu){.+.+}-{0:0}, at: lineinfo_get+0x13f/0x140
   #1: 838bbd30 (request_class){+.+.}-{4:4}, at: __setup_irq+0xe8/0x5c0
   #2: 838bbc70 (lock_class){-...}-{2:2}, at: __setup_irq+0x104/0x5c0
  ...
  Call trace:
  ...
   mutex_lock_nested from regmap_update_bits_base+0x1c/0x80
   regmap_update_bits_base from ocelot_irq_unmask+0x42/0x80
   ocelot_irq_unmask from irq_enable+0x1e/0x80
   irq_enable from irq_startup+0x64/0xc0
   irq_startup from __setup_irq+0x38c/0x5c0
   __setup_irq from request_threaded_irq+0x86/0x140
   request_threaded_irq from edge_detector_setup+0x1d8/0x240
   edge_detector_setup from linereq_create+0x3e2/0x540
   linereq_create from gpio_ioctl+0xa4/0x240

With the fix the lan9645x gpiochip is registered as sleeping and
without the chained irqchip, the request fails with -ENXIO instead and
without lockdep reports.

Fixes: 181f604 ("pinctrl: ocelot: add ability to be used in a non-mmio configuration")
Signed-off-by: Jens Emil Schulz Østergaard <[email protected]>
Reviewed-by: Colin Foster <[email protected]>
Signed-off-by: Linus Walleij <[email protected]>
mrpre pushed a commit that referenced this pull request Nov 29, 2026
ufx_usb_probe() stores the usb_device pointer in dev->udev without
taking a reference, and ufx_usb_disconnect() does not wait for in-flight
control transfers.  A mode set or blank request that runs while the
device is being unplugged - through ufx_ops_set_par() or ufx_ops_blank()
on an open /dev/fbN file - keeps issuing synchronous control messages for
the whole ufx_set_vid_mode() sequence, including two msleep(1) delays in
ufx_config_pix_clk().  Once the disconnect callback returns, the USB core
may release the usb_device, and the next ufx_reg_write()/ufx_reg_read()
dereferences dev->udev through __create_pipe():

  general protection fault, probably for non-canonical address
  0xdffffc0000000006: 0000 [#1] SMP
  KASAN: null-ptr-deref in range [0x0000000000000030-0x0000000000000037]
  RIP: __create_pipe include/linux/usb.h:2031
  Call Trace:
   ufx_set_vid_mode
   ufx_ops_set_par
   fb_set_var
   fb_set_var_from_user
   store_rotate

Take a reference to the usb_device in ufx_usb_probe() and drop it in
ufx_free(), so dev->udev and dev->gdev stay valid until the last
ufx_data user is gone.  The control transfers then fail with -ENODEV
instead of dereferencing freed memory.

Also return early from ufx_set_vid_mode() while the device is inactive,
matching the other transmit paths.  That check alone is not enough,
because it is not serialized against ufx_usb_disconnect() and the
transfer sequence continues after it; it only avoids a long series of
failing transfers.

Fixes: 3c8a63e ("Add support for SMSC UFX6000/7000 USB display adapters")
Signed-off-by: YuanZhe Liu <[email protected]>
Cc: [email protected]
Signed-off-by: Helge Deller <[email protected]>
mrpre pushed a commit that referenced this pull request Nov 29, 2026
Christian reported that booting preemptible kernel on FSL Cyrus+ board
causes boot hang.

The logs pointed that system was busy in printing below warning.

WARNING: at .enable_kernel_fp+0x30/0x78, CPU#3: qemu-system-ppc/4884
Modules linked in:
CPU: 3 UID: 1000 PID: 4884 Comm: qemu-system-ppc Not tainted 7.3.0-rc1-powerpc64-smp-preempt #1 PREEMPT
NIP [c000000000003338] .enable_kernel_fp+0x30/0x78
LR [c00000000005de84] .kvmppc_load_guest_fp+0x30/0x80
Call Trace:
[c000000085ca7700] [c00000000005de84] .kvmppc_load_guest_fp+0x30/0x80
[c000000085ca7780] [c00000000005f2a0] .kvmppc_handle_exit+0x5bc/0x5cc
[c000000085ca7830] [c00000000006204c] .kvmppc_resume_host+0xb8/0x10c

Which is...

void enable_kernel_fp(void)
{
        unsigned long cpumsr;
        WARN_ON(preemptible());

And...

Though irq's are hard disabled after kvmppc_prepare_to_enter, but
kvmppc_fix_ee_before_entry enables the softmask's IRQ state.
That causes the irqs_disabled to return false.
Hence leading to the warnings.

Fix it by re-ordering the code to load the FP and Altivec
before enabling the softmask IRQ state.

Suggested-by: Narayana Murty N <[email protected]>
Fixes: 3efc7da ("KVM: PPC: Book3E: Increase FPU laziness")
Reported-by: Christian Zigotzky <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Tested-by: Christian Zigotzky <[email protected]>
Reviewed-by: Narayana Murty N <[email protected]>
Reviewed-by: Ritesh Harjani (IBM) <[email protected]>
Reviewed-by: Mukesh Kumar Chaurasiya (IBM) <[email protected]>
Signed-off-by: Shrikanth Hegde <[email protected]>
Signed-off-by: Madhavan Srinivasan <[email protected]>
Link: https://patch.msgid.link/[email protected]
mrpre pushed a commit that referenced this pull request Nov 29, 2026
After applying preempt disable patch, i.e PATCH 2/3, Christian reported
a subsequent warning stopping his board to boot properly.

WARNING: at .kvmppc_fix_ee_before_entry+0x10/0x28, CPU#0: qemu-system-ppc/4667
CPU: 0 UID: 1000 PID: 4667 Comm: qemu-system-ppc Tainted: G        W           7.3.0-rc4-2-powerpc64-smp #1 PREEMPT
Tainted: [W]=WARN
Hardware name: varisys,CYRUS5040 e5500 0x80240012 CoreNet Generic
NIP [c00000000005dc3c] .kvmppc_fix_ee_before_entry+0x10/0x28
LR [c00000000005f298] .kvmppc_handle_exit+0x5b4/0x5e8
Call Trace:
[c000000086587780] [c00000000005ee10] .kvmppc_handle_exit+0x12c/0x5e8 (unreliable)
[c000000086587830] [c000000000062068] .kvmppc_resume_host+0xb8/0x10c

It triggers below warning...

static inline void kvmppc_fix_ee_before_entry(void)
{
        trace_hardirqs_on();

        /*
         * To avoid races, the caller must have gone directly from having
         * interrupts fully-enabled to hard-disabled.
         */
        WARN_ON(local_paca->irq_happened != PACA_IRQ_HARD_DIS);

This happens since kvmppc_prepare_to_enter does first local_irq_disable
followed by hard_irq_disable. This leaves a small window where interrupt
may occur and it could set the irq pending bit in PACA.

That local_irq_disable was necessary for PPC32 to track the lockdep
state etc. On PPC64 hard_irq_disable is good enough. There is no need to
do both. With now hard_irq_disable, doing local_irq_disable for PPC32,
just calling that is enough.

Suggested-by: Ritesh Harjani (IBM) <[email protected]>
Fixes: 12013e3 ("KVM: powerpc: Use generic xfer to guest work function")
Reported-by: Christian Zigotzky <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Tested-by: Christian Zigotzky <[email protected]>
Reviewed-by: Mukesh Kumar Chaurasiya (IBM) <[email protected]>
Reviewed-by: Narayana Murty N <[email protected]>
Reviewed-by: Ritesh Harjani (IBM) <[email protected]>
Signed-off-by: Shrikanth Hegde <[email protected]>
Signed-off-by: Madhavan Srinivasan <[email protected]>
Link: https://patch.msgid.link/[email protected]
mrpre pushed a commit that referenced this pull request Nov 29, 2026
The C compiler is asked to add a `cs` prefix to the `call` and `jmp`
instructions that go through the indirect thunks for the `r8`-`r15`
registers, which makes them 6 bytes long instead of 5. That gives
`patch_retpoline()` enough room to inline them, e.g. as `lfence; call
*%r11` for `spectre_v2=retpoline,lfence`.

However, Rust code does not get the prefix, e.g. for a
`CONFIG_MITIGATION_RETPOLINE=y` build:

    $ objdump -dr rust/kernel.o
    ...
      e2b: e8 00 00 00 00        call   e30 <...>
                e2c: R_X86_64_PLT32  __x86_indirect_thunk_r11-0x4

Moreover, since commit 4a1e02b ("x86,retpoline: Optimize
patch_retpoline()"), `emit_indirect()` assumes there is enough room
for the inlined sequence -- e.g. with `spectre_v2=retpoline,lfence`,
the kernel warns and dies while patching a site inside `core`:

    WARNING: arch/x86/kernel/alternative.c:736 at apply_retpolines+0x2ee/0x400, CPU#0: swapper/0/0
    ...
    Call Trace:
     <TASK>
     ? _RNvMs6_NtNtCshS2CUL9MEDn_4core3fmt8buildersNtB5_9DebugList21finish_non_exhaustive+0x5b/0xd0
     ...
     alternative_instructions+0x1d/0x60
     arch_cpu_finalize_init+0x5a/0xb0
     start_kernel+0x1f4/0x280

Similarly, paranoid FineIBT rewrites each kCFI call site into a fixed
20-byte sequence, i.e. the 14 bytes of the kCFI check plus a 6-byte
call. For a 5-byte call, that overwrites the first byte of the next
instruction, corrupting Rust code:

    SMP alternatives: Using paranoid FineIBT CFI
    ...
    Oops: double fault: 0000 [#1]
    ...
    RIP: 0010:_RNvNtCsdVypMZsLRAh_4core3fmt5write+0x1e9/0x210
    Code: ... b8 68 81 16 9f 41 3b 43 f5 2e 4d 8d 5b f0 75 fd 41 ff e3 <cc> c0 eb 02 b0 01 ...
    ...
    Kernel panic - not syncing: Fatal exception in interrupt

Non-paranoid FineIBT is not affected, since it only rewrites the kCFI
check and leaves the call itself to `apply_retpolines()`.

We added support for `-Zindirect-branch-cs-prefix` [1][2] in Rust 1.91.0
[3]. Thus pass it for `RETPOLINE` builds when possible, which makes all
sites indeed get the prefix:

      e3c: 2e e8 00 00 00 00     cs call e42 <...>
                e3e: R_X86_64_PLT32  __x86_indirect_thunk_r11-0x4

The kernel above boots fine with `spectre_v2=retpoline,lfence`, inlining
the Rust sites as well.

For older Rust compilers, set the LLVM module flag instead, which
has the same code-generation effect. This means that every Rust version
that the kernel supports gets the prefix, that the kernel boots fine with
`spectre_v2=retpoline,lfence`, and that paranoid FineIBT no longer
corrupts.

In addition, add it to our target modifier workaround for `rustdoc`.

Cc: [email protected] # 6.18.y+
Link: rust-lang/rust#116852 [1]
Link: rust-lang/compiler-team#899 [2]
Link: rust-lang/rust#140740 [3]
Reported-by: Kent Overstreet <[email protected]>
Acked-by: Borislav Petkov <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Miguel Ojeda <[email protected]>
mrpre pushed a commit that referenced this pull request Nov 29, 2026
Per-thread mmap buffers use CPU -1 to mean any CPU. Combining --per-thread
with --affinity=cpu passes this value to __set_bit() when constructing the
reader affinity mask, causing an out-of-bounds bitmap access and SIGSEGV.

Program received signal SIGSEGV, Segmentation fault.
0x0000555555f3488e in mmap.mmap ()
#0  0x0000555555f3488e in mmap.mmap ()
#1  0x0000555555e2f7bf in mmap_per_evsel (evlist=evlist@entry=0x7fffedcc1150, ops=ops@entry=0x7fffffffaf50, idx=idx@entry=0, mp=mp@entry=0x7fffffffaf70, cpu_idx=cpu_idx@entry=0, thread=thread@entry=0, _output=0x7fffffffaf08, _output_overwrite=0x7fffffffaf04, nr_mmaps=0x7fffffffaf0c) at evlist.c:598
#2  0x0000555555e2ef96 in mmap_per_thread (evlist=0x7fffedcc1150, ops=0x7fffffffaf50, mp=0x7fffffffaf70) at evlist.c:650
#3  perf_evlist__mmap_ops (evlist=0x7fffedcc1150, ops=0x7fffffffaf50, mp=0x7fffffffaf70) at evlist.c:748
kernel-patches#4  0x0000555555f2150d in evlist.mmap_ex ()
kernel-patches#5  0x0000555555db0b0a in record.open ()
kernel-patches#6  0x0000555555dadea7 in __cmd_record ()
kernel-patches#7  0x0000555555daca89 in cmd_record ()
kernel-patches#8  0x0000555555e27d53 in run_builtin ()
kernel-patches#9  0x0000555555e277cf in main ()
rip            0x555555f3488e      0x555555f3488e <mmap.mmap+382>
rax            0x7fffef9e9bd0      140737213537232
rbx            0x7fffedd249a0      140737183369632
rcx            0x3ffffffffffffff   288230376151711743
rdx            0x8000000000000000  -9223372036854775808
rsi            0x0                 0
rdi            0x7fffef9e9bd0      140737213537232
   0x555555f34876 <mmap__mmap+358>:	movswq 0x10(%rbx),%rcx
   0x555555f3487b <mmap__mmap+363>:	mov    0xb8(%rbx),%rax
   0x555555f34882 <mmap__mmap+370>:	mov    $0x1,%edx
   0x555555f34887 <mmap__mmap+375>:	shl    %cl,%rdx
   0x555555f3488a <mmap__mmap+378>:	shr    $0x6,%rcx
=> 0x555555f3488e <mmap__mmap+382>:	or     %rdx,(%rax,%rcx,8)
   0x555555f34892 <mmap__mmap+386>:	lea    0x17711b(%rip),%r14        # 0x5555560ab9b4 <verbose>
   0x555555f34899 <mmap__mmap+393>:	cmpl   $0x2,(%r14)
   0x555555f3489d <mmap__mmap+397>:	jne    0x555555f348f7 <mmap__mmap+487>
   0x555555f3489f <mmap__mmap+399>:	mov    0xb8(%rbx),%rdi
   0x555555f348a6 <mmap__mmap+406>:	mov    0xc0(%rbx),%esi
   0x555555f348ac <mmap__mmap+412>:	lea    -0x430(%rbp),%r12

Only construct and apply reader affinity masks for buffers with a
nonnegative CPU. Skip the reader-side bitmap operations as well, since
per-thread buffers no longer allocate an affinity mask.

Fixes: 8384a26 ("perf record: Adapt affinity to machines with #CPUs > 1K")
Signed-off-by: Paul Moses <[email protected]>
Acked-by: Namhyung Kim <[email protected]>
Cc: Adrian Hunter <[email protected]>
Cc: Alexander Shishkin <[email protected]>
Cc: Alexey Budankov <[email protected]>
Cc: Ian Rogers <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: James Clark <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Mark Rutland <[email protected]>
Cc: Namhyung Kim <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
mrpre pushed a commit that referenced this pull request Nov 29, 2026
The SiFive P550 (ESWIN EIC7700X) implements the hypervisor extension
on a privileged spec 1.11 base, so it has neither henvcfg nor senvcfg.
KVM swaps senvcfg on every guest entry and writes henvcfg on vCPU load
regardless, and the host dies on the first guest entry:

  Oops - illegal instruction [#1]
  Modules linked in: kvm
  CPU: 2 UID: 0 PID: 127 Comm: qemu-system-ris Not tainted 7.2.0+ kernel-patches#4 PREEMPTLAZY
  Hardware name: Unknown Unknown Product/Unknown Product, BIOS 2024.01 01/01/2024
  epc : kvm_riscv_vcpu_enter_exit+0x26/0xcf8 [kvm]
   ra : kvm_arch_vcpu_ioctl_run+0x4ce/0x5a6 [kvm]
  status: 0000000200000100 badaddr: 0000000010a797f3 cause: 0000000000000002
  [<ffffffff01df432e>] kvm_riscv_vcpu_enter_exit+0x26/0xcf8 [kvm]
  [<ffffffff01deb3b0>] kvm_arch_vcpu_ioctl_run+0x4ce/0x5a6 [kvm]
  [<ffffffff01dd7914>] kvm_vcpu_ioctl+0x180/0x5e4 [kvm]
  [<ffffffff8025702e>] __riscv_sys_ioctl+0x84/0x9a
  [<ffffffff80dfdc72>] do_trap_ecall_u+0x1d8/0x38a
  [<ffffffff80e08644>] handle_exception+0x168/0x174
  Code: 84aa 892e b703 8887 1773 1067 3023 16e5 b783 8907 (97f3) 10a7

Introduce a hardware quirk for this core, similar to the Andes AX66 TLB one,
and skip both CSRs when it is set. The FWFT features that KVM implements
with henvcfg bits then disabled.

Fixes: db3c01c ("RISCV: KVM: Add senvcfg context save/restore")
Suggested-by: Anup Patel <[email protected]>
Signed-off-by: Davidlohr Bueso <[email protected]>
Reviewed-by: Anup Patel <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Anup Patel <[email protected]>
mrpre pushed a commit that referenced this pull request Nov 29, 2026
… into HEAD

KVM/riscv fixes for 7.4, take #1

- Validate AIA MMIO address ranges before AIA is initialized
- Disallow GPA-width changes after AIA is initialized
- Fix double free of the split page cache
- Do not touch the envcfg CSRs on the SiFive P550
- Set Accessed bit in dirty-log write fault fast-path
- Validate PMU counter info using available counters
- Fix G-stage page table memory leak on VM destroy
mrpre pushed a commit that referenced this pull request Nov 29, 2026
DSA registers the user ports in dsa_tree_setup_ports() before it sets
conduit->dsa_ptr in dsa_tree_setup_conduit(). On teardown, it clears
conduit->dsa_ptr in dsa_tree_teardown_conduit() before
dsa_tree_teardown_ports() removes the user ports. RTNL is not held
across either pair of steps, so user space can open a user port while
conduit->dsa_ptr is NULL.

In NPI mode, felix_port_enable() calls felix_cpu_port_for_conduit().
For a physical conduit, that function reads the CPU port index through
conduit->dsa_ptr without checking for NULL. This caused an oops on an
LS1028A RDB when systemd-networkd tried to open a user port while the
switch was being probed again at runtime:

  [  166.722423] Unable to handle kernel access to user memory outside uaccess routines at virtual address 0000000000000028
  [  166.816908] Internal error: Oops: 0000000096000004 [#1]  SMP
  [  166.961766] pc : felix_cpu_port_for_conduit.isra.0+0x90/0xb8 [mscc_felix_dsa_lib]
  [  166.969289] lr : felix_port_enable+0x120/0x1a0 [mscc_felix_dsa_lib]

The oops left RTNL locked. Later operations that waited for RTNL hung,
and the board had to be power cycled.

NPI mode uses one CPU port for the whole switch. Changing the conduit
of a user port can move the NPI port to another CPU port, and the check
in felix_port_enable() keeps user ports that still use the old CPU port
down.

For a physical conduit, compare dp->cpu_dp->index with the NPI port
instead. DSA sets dp->cpu_dp before it registers the user port and
clears it only after it removes the user port, so the check keeps
working while conduit->dsa_ptr is NULL. As long as the physical
conduit is set up, conduit->dsa_ptr and dp->cpu_dp point to the same
CPU port, so the check gives the same result as before. LAG conduits
keep using felix_cpu_port_for_conduit(), which does not read dsa_ptr
for them.

Fixes: eca7010 ("net: dsa: felix: add support for changing DSA master")
Signed-off-by: Aristo Chen <[email protected]>
Reviewed-by: Vladimir Oltean <[email protected]>
Tested-by: Vladimir Oltean <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Paolo Abeni <[email protected]>
mrpre pushed a commit that referenced this pull request Nov 29, 2026
keyctl_chown_key() looks up the target key by calling lookup_user_key()
with the KEY_LOOKUP_PARTIAL flag. That flag lets a caller with
CAP_SYS_ADMIN change the UID of an uninstantiated key during construction.
When the UID changes, keyctl_chown_key() replaces key->user under key->sem
and drops the old reference with key_user_put().

__key_instantiate_and_link() and key_reject_and_link() hold
key_construction_mutex during instantiation, but neither function takes
key->sem. Both functions increment key->user->nikeys, and
__key_instantiate_and_link() also calls key->type->instantiate() without
holding key->sem. When a key is in quota and its size changes,
key_payload_reserve() reads key->user seven times without key->sem. Those
reads include spin_lock_irqsave(&key->user->lock, flags) at the start and
spin_unlock_irqrestore(&key->user->lock, flags) at the end.

If keyctl_chown_key() swaps key->user between those two calls,
key_payload_reserve() unlocks the new owner's spinlock and leaves the old
spinlock held. By source inspection, key_user_put() can also kfree() the
old struct key_user while instantiation still dereferences it. That struct
key_user use-after-free was found by reading the code and did not trigger
during our KASAN runs.

  =====================================
  WARNING: bad unlock balance detected!
  7.4.0-rc2-g23c62304dde2 #3 Not tainted
  -------------------------------------
  request-key/163 is trying to release lock (&candidate->lock) at:
  [<ffffffff82698fff>] key_payload_reserve+0x29f/0x370
  but there are no more locks to release!

  other info that might help us debug this:
  locks held by request-key/163: 2, on CPU#3:
   #0: ffffffff871c10a0 (key_construction_mutex){+.+.}-{4:4}, at: __key_instantiate_and_link+0x38/0x370
   #1: ffff88800de4a8b8 (&candidate->lock){..-.}-{3:3}, at: key_payload_reserve+0x160/0x370

  Call Trace:
   lock_release+0x286/0x2e0
   _raw_spin_unlock_irqrestore+0x1a/0x50
   key_payload_reserve+0x29f/0x370
   generic_key_instantiate+0x42/0x230
   __key_instantiate_and_link+0xd7/0x370
   key_instantiate_and_link+0x40d/0x4b0
   keyctl_instantiate_key_common+0x2d2/0x450
   keyctl_instantiate_key+0x167/0x180
   __do_sys_keyctl+0x391/0x550

Take key->sem for write with down_write_nested(&key->sem, 2) inside
key_construction_mutex in __key_instantiate_and_link() and
key_reject_and_link().

Fixes: 5801649 ("[PATCH] keys: let keyctl_chown() change a key's owner")
Cc: [email protected]
Signed-off-by: Sinan Turunc <[email protected]>
Reviewed-by: Jarkko Sakkinen <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Jarkko Sakkinen <[email protected]>
mrpre pushed a commit that referenced this pull request Nov 29, 2026
big_key_update() reserves quota with the raw payload length and then
destroys the old payload before instantiating the new one.  For a payload
of N < 16 bytes that reserve releases 16-N bytes, so the reserve of 16
done by generic_key_instantiate() charges them again and can fail with
-EDQUOT once the payload is already destroyed.  big_key_destroy() keeps
payload->length but clears path and data, so the key stays positive with
a stale length that KEYCTL_READ and KEYCTL_REVOKE then follow:

kernel BUG at fs/open.c:1145!
Oops: invalid opcode: 0000 [#1] SMP KASAN NOPTI
RIP: 0010:dentry_open+0x7b/0x90
 big_key_read+0x141/0x280

Instantiate the new payload first and destroy the old one only on success;
a positive key's reservation is already 16 bytes, so it cannot fail.

This issue was discovered by Tencent CodeBuddy Security.

Cc: [email protected]
Fixes: b6f61c3 ("keys: Implement update for the big_key type")
Signed-off-by: Henry Martin <[email protected]>
Reviewed-by: Jarkko Sakkinen <[email protected]>
Reviewed-by: Guicai Ma <[email protected]>
Tested-by: Guicai Ma <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Jarkko Sakkinen <[email protected]>
mrpre pushed a commit that referenced this pull request Nov 29, 2026
bpf_throw() does not return, its return address stays on the shadow
call stack. The caller of the program takes it for its own.
test_progs -t exceptions crashes the kernel with
CONFIG_SHADOW_CALL_STACK:

  Internal error: Oops - FPAC: 0000000072000000 [#1]  SMP
  pc : bpf_test_run+0x410/0x968

JITed code puts nothing on the shadow call stack, and bpf_throw() skips
only frames of JITed code. So that address is the only entry that is
left behind. Pop it in the prologue of the exception callback.

Fixes: 22fc0e8 ("bpf, arm64: support exceptions")
Signed-off-by: Alexei Starovoitov <[email protected]>
Link: https://patch.msgid.link/[email protected]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant