fix misc sockmap issues
Subsystems (9)
Jiayuan Chen
maintainercover fix misc sockmap issues
This series fixes misc issues in sockmap. Most of them are old.
Patches 1-2 fix copied_seq when a strparser is attached and SK_PASS data is left unread, with a selftest. It was reported by Vega and comes from my earlier fix, commit 36b62df5683c ("bpf: Fix wrong copied_seq calculation").
Patches 3, 4 and 7 are old issues I ran into while reading the code:
03 strparser is initialized again while the old one is still alive,
after the parser link is removed and added back
04 an ingress redirect queues an empty sk_msg
07 sk_psock_backlog() takes the refcnt of the wrong psock
The rest (patches 5, 6 and 8-11) are the old issues that came up in the review of Alexei's sockmap series [1]. They are not from that series, so they were left for a follow-up.
Patch 05 returns -EBUSY to a second concurrent sender, and patch 06 rejects disconnect with -EOPNOTSUPP like TLS does. Both change what user space sees, see the commit messages for why.
[1] https://lore.kernel.org/bpf/[email protected]/
Jiayuan Chen (11):
bpf, sockmap: Fix copied_seq updates with strparser selftests/bpf: Add test for unread SK_PASS data with strparser bpf, sockmap: Fix strparser reinit after the parser link is removed bpf, sockmap: Fix empty sk_msg queued by ingress redirect bpf, sockmap: Fix concurrent senders on one psock
bpf, sockmap: Fix reconnect with a psock by rejecting disconnect bpf, sockmap: Fix psock refcnt taken in sk_psock_backlog() bpf, sockmap: Fix socket lock taken on a child before accept() bpf, sockmap: Fix apply_bytes when a redirect sends only a part selftests/bpf: Fix errno expected by the wait send mem test of
test_sockmap
selftests/bpf: Add test for apply_bytes when a redirect sends a part
include/linux/skmsg.h | 8 ++ net/core/skmsg.c | 44 +++++- net/core/sock_map.c | 67 +++++++++- net/ipv4/tcp_bpf.c | 79 +++++++++-- .../selftests/bpf/prog_tests/sockmap_basic.c | 126 ++++++++++++++++++ .../selftests/bpf/prog_tests/sockmap_strp.c | 86 ++++++++++++ .../bpf/progs/test_sockmap_msg_apply.c | 46 +++++++ tools/testing/selftests/bpf/test_sockmap.c | 3 +- 8 files changed, 436 insertions(+), 23 deletions(-) create mode 100644 tools/testing/selftests/bpf/progs/test_sockmap_msg_apply.c
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 1/11 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->skand 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. 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 BUG_ON(offset < 0) in tcp_collapse() when copied_seq trails the head of sk_receive_queue is not addressed here.
--- net/core/skmsg.c | 18 ++++++++++++++---- net/ipv4/tcp_bpf.c | 12 ++++++------ 2 files changed, 20 insertions(+), 10 deletions(-)
net/core/skmsg.c +14 -4
@@ -574,9 +574,6 @@ static int sk_psock_skb_ingress_enqueue(struct sk_buff *skb,return num_sge; } -#if IS_ENABLED (CONFIG_BPF_STREAM_PARSER ) - psock->ingress_bytes += len; -#endif copied = len; msg->sg.start =0 ; msg->sg.size = copied;
@@ -642,8 +639,21 @@ static int sk_psock_skb_ingress_self(struct sk_psock *psock, struct sk_buff *skb*/ msg->sk = sk; err =sk_psock_skb_ingress_enqueue (skb, off, len, psock, sk, msg, take_ref); -if (err <0 ) +if (err <0 ) {kfree (msg); +/* +* A strparser skb comes in without an owner and read_sock counts +* it as consumed once it is left to the backlog. Drop the owner +* again, or sk_psock_skb_ingress() takes the skb->sk == sk path +* and recvmsg() counts it a second time. +*/ +if (skb_bpf_strparser (skb)) +skb_orphan (skb); + } +#if IS_ENABLED (CONFIG_BPF_STREAM_PARSER ) + else + psock->ingress_bytes += len; +#endif return err; }
net/ipv4/tcp_bpf.c +6 -6
@@ -249,7 +249,6 @@ static int tcp_bpf_recvmsg_parser(struct sock *sk,struct tcp_sock *tcp;int copied_from_self =0 ;int copied =0 ; -u32 seq;if (unlikely (flags &MSG_ERRQUEUE ))return inet_recv_error (sk, msg, len);
@@ -263,7 +262,6 @@ static int tcp_bpf_recvmsg_parser(struct sock *sk,lock_sock (sk); tcp =tcp_sk (sk); - seq = tcp->copied_seq;/* We may have received data on the sk_receive_queue pre-accept and * then we can not use read_skb in this context because we haven't * assigned a sk_socket yet so have no link to the ops. The work-around
@@ -295,11 +293,10 @@ static int tcp_bpf_recvmsg_parser(struct sock *sk,if (is_fin) { copied =0 ; - seq++; + copied_from_self++; goto out; } } - seq += copied_from_self;if (!copied) {long timeo;int data;
@@ -341,7 +338,7 @@ static int tcp_bpf_recvmsg_parser(struct sock *sk, } out:if (!peek) -WRITE_ONCE (tcp->copied_seq, seq); +WRITE_ONCE (tcp->copied_seq, tcp->copied_seq + copied_from_self);tcp_rcv_space_adjust (sk);/* Data on the psock outlives the connection that it came in on */ if (copied >0 &&tcp_can_send_ack (sk))
@@ -756,6 +753,7 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc,struct sk_psock *psock;struct tcp_sock *tp;int copied =0 ; +u32 seq; tp =tcp_sk (sk);rcu_read_lock ();
@@ -765,6 +763,7 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc, goto out; } + seq = psock->copied_seq; psock->ingress_bytes =0 ; copied =tcp_read_sock_noack (sk, desc, recv_actor, true, &psock->copied_seq);
@@ -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); out:
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 2/11 selftests/bpf: Add test for unread SK_PASS data with strparser
In reply to Jiayuan ChenSend two packets and wait for each to reach ingress_msg before sending the next, so that the parser runs once per packet with the first one still unread. Read both, then send a third packet and expect it to be delivered.
Without the fix the third packet is never read: copied_seq has passed rcv_nxt after the first recv(), so the parser is not woken anymore.
--- .../selftests/bpf/prog_tests/sockmap_strp.c | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+)
tools/testing/selftests/bpf/prog_tests/sockmap_strp.c +86 -0
@@ -364,6 +364,88 @@ static void test_sockmap_strp_pass(int family, int sotype, bool fionread)test_sockmap_strp__destroy (strp); } +static int sockmap_strp_wait_fionread (int fd,int expected) +{ +int err, avail =0 ; + +while (1 ) { + err =ioctl (fd,FIONREAD , &avail); +if (!ASSERT_OK (err,"ioctl(FIONREAD) error" )) +return -1 ; +if (avail >= expected) +break ; +usleep (10000 ); + } +return ASSERT_EQ (avail, expected,"ioctl(FIONREAD)" ) ?0 :-1 ; +} + +/* +* Let the parser run twice before the reader reads anything. Each round +* must keep the SK_PASS bytes of the earlier rounds out of copied_seq, +* otherwise copied_seq runs past rcv_nxt and the stream stalls. +*/ +static void test_sockmap_strp_pass_unread (int family,int sotype) +{ +int zero =0 , one =1 , pkt_size =STRP_PKT_FULL_LEN , sent, recvd; +int err, map, i; +int c =-1 , p =-1 ; +struct test_sockmap_strp *strp =NULL ; +char rcv[STRP_PKT_FULL_LEN *2 +1 ] ="0" ; + + strp =sockmap_strp_init (&map, true, true); +if (!ASSERT_TRUE (strp,"sockmap_strp_init" )) +return ; + + err =create_pair (family, sotype, &c, &p); +if (err) + goto out; + + err =bpf_map_update_elem (map, &zero, &p,BPF_NOEXIST ); +if (!ASSERT_OK (err,"bpf_map_update_elem(p)" )) + goto out_close; + + err =setsockopt (c,IPPROTO_TCP ,TCP_NODELAY , &one,sizeof (one)); +if (!ASSERT_OK (err,"setsockopt(TCP_NODELAY)" )) + goto out_close; + +/* +* wait for each packet to reach ingress_msg before sending the +* next one, so that the parser runs once per packet +*/ +for (i =1 ; i <=2 ; i++) { + sent =xsend (c, packet, pkt_size,0 ); +if (!ASSERT_EQ (sent, pkt_size,"xsend(c)" )) + goto out_close; +if (sockmap_strp_wait_fionread (p, pkt_size * i)) + goto out_close; + } + + recvd =recv_timeout (p, rcv,sizeof (rcv),MSG_DONTWAIT ,IO_TIMEOUT_SEC ); +if (!ASSERT_EQ (recvd, pkt_size *2 ,"recv_timeout(p)" ) || + !ASSERT_OK (memcmp (packet, rcv, pkt_size),"memcmp, data mismatch" ) || + !ASSERT_OK (memcmp (packet, rcv + pkt_size, pkt_size), +"memcmp, second data mismatch" )) + goto out_close; + +/* the next packet must still wake the parser */ + sent =xsend (c, packet, pkt_size,0 ); +if (!ASSERT_EQ (sent, pkt_size,"xsend(c) after read" )) + goto out_close; + + recvd =recv_timeout (p, rcv,sizeof (rcv),MSG_DONTWAIT ,IO_TIMEOUT_SEC ); +if (!ASSERT_EQ (recvd, pkt_size,"recv_timeout(p) after read" ) || + !ASSERT_OK (memcmp (packet, rcv, pkt_size), +"memcmp, data mismatch after read" )) + goto out_close; + +out_close: +close (c); +close (p); + +out: +test_sockmap_strp__destroy (strp); +} +/* Test strparser with verdict mode */ static void test_sockmap_strp_verdict (int family,int sotype) {
@@ -470,6 +552,10 @@ void test_sockmap_strp(void)test_sockmap_strp_pass (AF_INET ,SOCK_STREAM , true);if (test__start_subtest ("sockmap strp tcp v6 pass fionread" ))test_sockmap_strp_pass (AF_INET6 ,SOCK_STREAM , true); +if (test__start_subtest ("sockmap strp tcp pass unread" )) +test_sockmap_strp_pass_unread (AF_INET ,SOCK_STREAM ); +if (test__start_subtest ("sockmap strp tcp v6 pass unread" )) +test_sockmap_strp_pass_unread (AF_INET6 ,SOCK_STREAM );if (test__start_subtest ("sockmap strp tcp verdict" ))test_sockmap_strp_verdict (AF_INET ,SOCK_STREAM );if (test__start_subtest ("sockmap strp tcp v6 verdict" ))
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 3/11 bpf, sockmap: Fix strparser reinit after the parser link is removed
In reply to Jiayuan ChenA socket can sit in several sockmaps at once, so a psock can outlive the link that brought the stream parser. When that link goes away, sock_map_del_link() can only call sk_psock_stop_strp(), which marks the strparser stopped. strp_done(), which cancels the message timer and the work and frees the partial skb, needs lock_sock() and sync cancels and is only run from sk_psock_destroy(). With another link holding the psock, destroy never comes and the strparser stays in that half state.
Adding the socket to another map with a parser then goes through sk_psock_init_strp() again, because progs.stream_parser and saved_data_ready were both cleared. strp_init() memsets the strparser and reinits its work and timer while the old timer may still be on the timer wheel and the old work may still be queued. The partial skb is leaked. Once the timer fires, __run_timers() unlinks a timer_list that no longer matches the wheel and delayed_work_timer_fn() dereferences the zeroed wq:
BUG: KASAN: slab-use-after-free in __run_timers+0xa7d/0xab0 Write of size 8 at addr ffff888001ed40e0 by task systemd-journal/148 Call Trace: <IRQ> __run_timers+0xa7d/0xab0 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> Allocated by task 756: sk_psock_init+0x187/0x850 sock_map_link+0x7d8/0xcf0 sock_map_update_common+0xbd/0x6c0 sock_map_update_elem_sys+0x324/0x460 Freed by task 684: sk_psock_destroy+0x847/0xb30 process_one_work+0x93a/0x1b60 Oops: general protection fault, probably for non-canonical address 0xdffffc0000000038 KASAN: null-ptr-deref in range [0x00000000000001c0-0x00000000000001c7] RIP: 0010:__queue_work+0x94/0x1850 Call Trace: <IRQ> delayed_work_timer_fn+0x5d/0xa0 call_timer_fn+0x17d/0x510 __run_timers+0x4e5/0xab0 run_timer_base+0x107/0x190 run_timer_softirq+0x1a/0x40 </IRQ>
Finish the strparser when the parser link is removed instead of waiting for the psock to die. sock_map_del_link() cannot sleep, so take a psock reference and queue sk_psock_destroy() on psock->rwork with SK_PSOCK_STRP_DONE_PENDING set. The work then only runs strp_done(), clears SK_PSOCK_RX_STRP_ENABLED and drops the reference. The work holds the psock, so the normal destroy cannot be queued before it finishes, and the final put may requeue rwork for the real destroy from inside the handler.
sock_map_link() refuses to attach a parser while SK_PSOCK_RX_STRP_ENABLED is still set, under sk_callback_lock together with the bit updates. sock_map_update_elem_sys() flushes the pending work before taking the socket lock, so userspace can remove a parser and attach a new one back to back without seeing -EBUSY.
BPF programs updating a sockmap (sockops helpers, iterator, sk_lookup and sk_reuseport programs) cannot wait and may get a transient -EBUSY if they add a socket to a parser map right after its parser link was removed. Before this change the same sequence reinitialized a live strparser, so this is the better outcome.
The psock now also lives a little longer after the last link to a parser map is removed, until the work has run. A TLS upgrade attempted in that window is rejected like for any socket with a psock.
--- include/linux/skmsg.h | 6 ++++++ net/core/skmsg.c | 24 ++++++++++++++++++++++++ net/core/sock_map.c | 39 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 68 insertions(+), 1 deletion(-)
include/linux/skmsg.h +6 -0
@@ -68,6 +68,7 @@ struct sk_psock_progs {enum sk_psock_state_bits {SK_PSOCK_TX_ENABLED ,SK_PSOCK_RX_STRP_ENABLED , +SK_PSOCK_STRP_DONE_PENDING , };struct sk_psock_link {
@@ -459,6 +460,7 @@ void sk_psock_stop(struct sk_psock *psock);int sk_psock_init_strp (struct sock *sk,struct sk_psock *psock);void sk_psock_start_strp (struct sock *sk,struct sk_psock *psock);void sk_psock_stop_strp (struct sock *sk,struct sk_psock *psock); +void sk_psock_queue_strp_done (struct sk_psock *psock);#else static inline int sk_psock_init_strp (struct sock *sk,struct sk_psock *psock) {
@@ -472,6 +474,10 @@ static inline void sk_psock_start_strp(struct sock *sk, struct sk_psock *psock)static inline void sk_psock_stop_strp (struct sock *sk,struct sk_psock *psock) { } + +static inline void sk_psock_queue_strp_done (struct sk_psock *psock) +{ +}#endif void sk_psock_start_verdict (struct sock *sk,struct sk_psock *psock);
net/core/skmsg.c +24 -0
@@ -879,6 +879,18 @@ static void sk_psock_destroy(struct work_struct *work) {struct sk_psock *psock =container_of (to_rcu_work (work), struct sk_psock, rwork); + +if (sk_psock_test_state (psock,SK_PSOCK_STRP_DONE_PENDING )) { +/* Parser link gone, other links keep the psock alive */ +sk_psock_done_strp (psock); +write_lock_bh (&psock->sk->sk_callback_lock); +sk_psock_clear_state (psock,SK_PSOCK_RX_STRP_ENABLED ); +sk_psock_clear_state (psock,SK_PSOCK_STRP_DONE_PENDING ); +write_unlock_bh (&psock->sk->sk_callback_lock); +sk_psock_put (psock->sk, psock); +return ; + } +/* No sk_callback_lock since already detached. */ sk_psock_done_strp (psock);
@@ -1208,6 +1220,18 @@ void sk_psock_stop_strp(struct sock *sk, struct sk_psock *psock)strp_stop (&psock->strp); } +/* Called with sk_callback_lock held while a link still holds the psock */ +void sk_psock_queue_strp_done (struct sk_psock *psock) +{ +if (!sk_psock_test_state (psock,SK_PSOCK_RX_STRP_ENABLED ) || +test_and_set_bit (SK_PSOCK_STRP_DONE_PENDING , &psock->state)) +return ; + +refcount_inc (&psock->refcnt); +INIT_WORK (&psock->rwork.work, sk_psock_destroy); +schedule_work (&psock->rwork.work); +} +static void sk_psock_done_strp (struct sk_psock *psock) {/* Parser has been stopped */
net/core/sock_map.c +38 -1
@@ -115,6 +115,33 @@ int sock_map_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)return ret; } +/* +* Wait for the strparser of a removed parser link to be torn down, so that +* a new parser can be attached right after the old one was removed. +*/ +static void sock_map_strp_done_wait (struct bpf_map *map,struct sock *sk) +{ +struct sk_psock *psock; + +if (!READ_ONCE (sock_map_progs (map)->stream_parser)) +return ; + +rcu_read_lock (); +read_lock_bh (&sk->sk_callback_lock); + psock =sk_psock (sk); +if (!psock || + !sk_psock_test_state (psock,SK_PSOCK_STRP_DONE_PENDING ) || + !refcount_inc_not_zero (&psock->refcnt)) + psock =NULL ; +read_unlock_bh (&sk->sk_callback_lock); +rcu_read_unlock (); +if (!psock) +return ; + +flush_work (&psock->rwork.work); +sk_psock_put (sk, psock); +} +static void sock_map_sk_acquire (struct sock *sk) __acquires(&sk->sk_lock.slock) {
@@ -169,8 +196,10 @@ static void sock_map_del_link(struct sock *sk,write_lock_bh (&sk->sk_callback_lock);if (psock->saved_data_ready) { -if (strp_stop) +if (strp_stop) {sk_psock_stop_strp (sk, psock); +sk_psock_queue_strp_done (psock); + }if (verdict_stop)sk_psock_stop_verdict (sk, psock);
@@ -297,6 +326,13 @@ static int sock_map_link(struct bpf_map *map, struct sock *sk) }write_lock_bh (&sk->sk_callback_lock); +if (stream_parser && +sk_psock_test_state (psock,SK_PSOCK_RX_STRP_ENABLED )) { +write_unlock_bh (&sk->sk_callback_lock); +sk_psock_put (sk, psock); + ret = -EBUSY ; + goto out_progs; + }if (msg_parser)psock_set_prog (&psock->progs.msg_parser, msg_parser);if (stream_parser)
@@ -597,6 +633,7 @@ int sock_map_update_elem_sys(struct bpf_map *map, void *key, void *value, goto out; } +sock_map_strp_done_wait (map, sk);sock_map_sk_acquire (sk);if (!sock_map_sk_state_allowed (sk)) ret = -EOPNOTSUPP ;
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 4/11 bpf, sockmap: Fix empty sk_msg queued by ingress redirect
In reply to Jiayuan ChenAn 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.
--- net/ipv4/tcp_bpf.c | 3 +++ 1 file changed, 3 insertions(+)
net/ipv4/tcp_bpf.c +3 -0
@@ -39,6 +39,9 @@ static int bpf_tcp_ingress(struct sock *sk, struct sk_psock *psock,struct sk_msg *tmp;int i, ret =0 ; +if (!msg->sg.size) +return 0 ; + tmp =kzalloc_obj (*tmp, __GFP_NOWARN |GFP_KERNEL );if (unlikely (!tmp))return -ENOMEM ;
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 5/11 bpf, sockmap: Fix concurrent senders on one psock
In reply to Jiayuan Chentcp_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. There is no use for it with sockmap either, so refuse it. Mark the psock busy for the whole tcp_bpf_sendmsg() and return -EBUSY to a second sender.
The second sender could wait instead, but that takes a wait queue with signal and timeout handling. Concurrent sends on one socket are rare, so keep the fix simple.
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.
--- include/linux/skmsg.h | 1 + net/ipv4/tcp_bpf.c | 11 +++++++++++ 2 files changed, 12 insertions(+)
include/linux/skmsg.h +1 -0
@@ -69,6 +69,7 @@ enum sk_psock_state_bits {SK_PSOCK_TX_ENABLED ,SK_PSOCK_RX_STRP_ENABLED ,SK_PSOCK_STRP_DONE_PENDING , + SK_PSOCK_TX_BUSY, }; struct sk_psock_link {
net/ipv4/tcp_bpf.c +11 -0
@@ -602,6 +602,16 @@ 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 (test_and_set_bit (SK_PSOCK_TX_BUSY , &psock->state)) { +sk_psock_put (sk, psock); +return -EBUSY ; + } +lock_sock (sk); timeo =sock_sndtimeo (sk, msg->msg_flags &MSG_DONTWAIT );while (msg_data_left (msg)) {
@@ -677,6 +687,7 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)if (err <0 ) err =sk_stream_error (sk, msg->msg_flags, err);release_sock (sk); +clear_bit (SK_PSOCK_TX_BUSY , &psock->state);sk_psock_put (sk, psock);return copied >0 ? copied : err; }
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 6/11 bpf, sockmap: Fix reconnect with a psock by rejecting disconnect
In reply to Jiayuan ChenCommit 8cc3aef0cb19 ("tcp: Do not allow buggy transitions between ehash and lhash2.") rejects connect() -> disconnect -> listen(), but connect() -> disconnect -> connect() is still allowed.
A socket in a sockmap keeps its psock across tcp_disconnect(), and the new connection runs into what the old one left there:
- recvmsg() returns the old data still queued on psock->ingress_msg.
- psock->copied_seq and psock->ingress_bytes still account for it, so copied_seq runs ahead of rcv_nxt for the rest of the connection.
- sk_psock_backlog() does not take the socket lock for ingress, so it can queue old skbs from psock->ingress_skb after the reconnect.
Cleaning all of this up on disconnect is hard. Do what TLS did in commit 5071a1e606b3 ("net: tls: explicitly disallow disconnect") and reject the disconnect with -EOPNOTSUPP.
Unlike TLS, some callers have to be let through. None of them leads to a reconnect with old data:
- A child can be added to a sockmap before accept(), e.g. by a sockops prog. When the listener is closed, inet_child_forget() disconnects the child and frees it right after, without looking at the return value. Such a child has no sk_socket.
- close() with a zero linger time disconnects through sk_prot, which is still tcp_bpf as long as somebody else holds the psock. sock_map_close() sets SK_PSOCK_CLOSING for it.
- A listener is disconnected by shutdown(SHUT_RD) and connect(AF_UNSPEC), and has no data.
--- include/linux/skmsg.h | 1 + net/core/sock_map.c | 1 + net/ipv4/tcp_bpf.c | 21 +++++++++++++++++++++ 3 files changed, 23 insertions(+)
include/linux/skmsg.h +1 -0
@@ -70,6 +70,7 @@ enum sk_psock_state_bits {SK_PSOCK_RX_STRP_ENABLED ,SK_PSOCK_STRP_DONE_PENDING ,SK_PSOCK_TX_BUSY , + SK_PSOCK_CLOSING, }; struct sk_psock_link {
net/core/sock_map.c +1 -0
@@ -1763,6 +1763,7 @@ void sock_map_close(struct sock *sk, long timeout)sock_map_remove_links (sk, psock);rcu_read_unlock ();sk_psock_stop (psock); +sk_psock_set_state (psock,SK_PSOCK_CLOSING );release_sock (sk);cancel_delayed_work_sync (&psock->work);sk_psock_put (sk, psock);
net/ipv4/tcp_bpf.c +21 -0
@@ -710,12 +710,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 ); +rcu_read_unlock (); +if (reject) +return -EOPNOTSUPP ; + +return tcp_disconnect (sk, flags); +} +static void tcp_bpf_rebuild_protos (struct proto prot[TCP_BPF_NUM_CFGS ],struct proto *base) { prot[TCP_BPF_BASE ] = *base; prot[TCP_BPF_BASE ].destroy = sock_map_destroy; prot[TCP_BPF_BASE ].close = sock_map_close; + prot[TCP_BPF_BASE ].disconnect = tcp_bpf_disconnect; prot[TCP_BPF_BASE ].recvmsg = tcp_bpf_recvmsg; prot[TCP_BPF_BASE ].sock_is_readable = sk_msg_is_readable; prot[TCP_BPF_BASE ].ioctl = tcp_bpf_ioctl;
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 7/11 bpf, sockmap: Fix psock refcnt taken in sk_psock_backlog()
In reply to Jiayuan Chensk_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.
--- net/core/skmsg.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/core/skmsg.c +1 -1
@@ -704,7 +704,7 @@ static void sk_psock_backlog(struct work_struct *work)* before sk_socket freed. If refcnt increment fails, it indicates * sock_map_close() completed with sk_socket potentially already freed. */ -if (!sk_psock_get (psock->sk)) +if (!refcount_inc_not_zero (&psock->refcnt))return ;mutex_lock (&psock->work_mutex);while ((skb =skb_peek (&psock->ingress_skb))) {
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 8/11 bpf, sockmap: Fix socket lock taken on a child before accept()
In reply to Jiayuan ChenA 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 4aeaad1c536e ("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(). Refuse the ingress redirect too, and do it before taking the lock: a child has no sk_socket until accept() has taken it off the queue.
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.
--- net/core/sock_map.c | 27 +++++++++++++++++++++++---- net/ipv4/tcp_bpf.c | 10 +++++++++- 2 files changed, 32 insertions(+), 5 deletions(-)
net/core/sock_map.c +23 -4
@@ -386,6 +386,19 @@ static int sock_map_link(struct bpf_map *map, struct sock *sk)return ret; } +/* +* The listener frees a child that nobody has accepted yet without waiting +* for the owner of its socket lock. Unlink such a child without the lock, +* as a delete does. +*/ +static bool sock_map_free_lock_sk (struct sock *sk) +{ +if (!READ_ONCE (sk->sk_socket)) +return false; +lock_sock (sk); +return true; +} +static void sock_map_free (struct bpf_map *map) { struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
@@ -402,12 +415,15 @@ static void sock_map_free(struct bpf_map *map) sk =xchg (psk,NULL );if (sk) { +bool locked; +sock_hold (sk); -lock_sock (sk); + locked =sock_map_free_lock_sk (sk);rcu_read_lock ();sock_map_unref (sk, psk);rcu_read_unlock (); -release_sock (sk); +if (locked) +release_sock (sk);sock_put (sk); } }
@@ -1228,12 +1244,15 @@ static void sock_hash_free(struct bpf_map *map)* link to sockhash. */ hlist_for_each_entry_safe (elem, node, &unlink_list, node) { +bool locked; +hlist_del (&elem->node); -lock_sock (elem->sk); + locked =sock_map_free_lock_sk (elem->sk);rcu_read_lock ();sock_map_unref (elem->sk, elem);rcu_read_unlock (); -release_sock (elem->sk); +if (locked) +release_sock (elem->sk);sock_put (elem->sk);sock_hash_free_elem (htab, elem); }
net/ipv4/tcp_bpf.c +9 -1
@@ -188,9 +188,17 @@ static int tcp_bpf_push_locked(struct sock *sk, struct sk_msg *msg,int tcp_bpf_sendmsg_redir (struct sock *sk,bool ingress,struct sk_msg *msg,u32 bytes,int flags) { -struct sk_psock *psock =sk_psock_get (sk); +struct sk_psock *psock;int ret; +/* +* The listener frees a child that nobody has accepted yet without +* waiting for the owner of its socket lock. +*/ +if (!READ_ONCE (sk->sk_socket)) +return sock_flag (sk,SOCK_DEAD ) ? -EPIPE : -EINVAL ; + + psock =sk_psock_get (sk);if (unlikely (!psock))return -EPIPE ;
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 9/11 bpf, sockmap: Fix apply_bytes when a redirect sends only a part
In reply to Jiayuan ChenAn 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.
--- net/ipv4/tcp_bpf.c | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-)
net/ipv4/tcp_bpf.c +17 -5
@@ -449,7 +449,7 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, {bool cork = false, enospc =sk_msg_full (msg), redir_ingress;struct sock *sk_redir; -u32 tosend, origsize, sent, delta =0 ; +u32 tosend, origsize, sent, apply, delta =0 ;u32 eval;int ret;
@@ -518,6 +518,7 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, redir_ingress = psock->redir_ingress; sk_redir = psock->sk_redir;sock_hold (sk_redir); + apply = psock->apply_bytes;sk_msg_apply_bytes (psock, tosend);if (!psock->apply_bytes) {/* Clean up before releasing the sock lock. */
@@ -540,10 +541,6 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, msg, tosend, flags); sent = origsize - msg->sg.size; -if (eval == __SK_REDIRECT) -sock_put (sk_redir); -sock_put (sk_redir); -lock_sock (sk);sk_mem_uncharge (sk, sent);if (unlikely (ret <0 )) {
@@ -566,6 +563,21 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, msg =NULL ; ret =0 ; } +/* +* Bytes that were not sent and come back, in msg or in the +* next sendmsg(), are still covered by the verdict. +*/ +if (apply && sent < tosend && !cork) { + psock->apply_bytes += tosend - sent; +if (eval == __SK_REDIRECT) { + psock->eval = eval; + psock->sk_redir = sk_redir; + eval = __SK_NONE; + } + } +if (eval == __SK_REDIRECT) +sock_put (sk_redir); +sock_put (sk_redir);break ;case __SK_DROP:default :
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 10/11 selftests/bpf: Fix errno expected by the wait send mem test of test_sockmap
In reply to Jiayuan ChenThe test closes the redirect target while the sender waits for its send memory. A part of the data has gone out, so sendmsg() returns that part and the test calls sendmsg() again.
With apply_bytes, the previous patch keeps the verdict for the bytes that were not sent. The next sendmsg() sends to the same target and returns -EPIPE, instead of running the prog again, which no longer finds the target in the map and returns SK_DROP, -EACCES.
Accept -EPIPE as well.
--- tools/testing/selftests/bpf/test_sockmap.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
tools/testing/selftests/bpf/test_sockmap.c +2 -1
@@ -566,7 +566,8 @@ static int msg_loop(int fd, int iov_count, int iov_length, int cnt, sent =sendmsg (fd, &msg, flags);if (!drop && sent <0 ) { -if (opt->tx_wait_mem && errno ==EACCES ) { +if (opt->tx_wait_mem && + (errno ==EACCES || errno ==EPIPE )) { errno =0 ; goto out_errno; }
Signature · 1 line
2.43.0
Jiayuan Chen
maintainerPATCH 11/11 selftests/bpf: Add test for apply_bytes when a redirect sends a part
In reply to Jiayuan ChenAn sk_msg prog parses the header of a message and applies its verdict to the whole message with bpf_msg_apply_bytes(), so it runs once per message, at the header:
+-----+-----------+-----+-------+------ | hdr | body | hdr | body | ... +-----+-----------+-----+-------+------ ^ ^
prog: apply(len1) prog: apply(len2)
The test sends one such message and redirects it to the egress of a socket that has the smallest send buffer, whose peer has the smallest receive buffer. The redirect sends only a part, so send() returns early, and the test sends the rest:
+-----+-----------+
| hdr | body |
+-----+-----------+
|<-- send -->|
|<-->| send againCheck that the prog ran once, at the header, and that the peer gets the whole message.
--- .../selftests/bpf/prog_tests/sockmap_basic.c | 126 ++++++++++++++++++ .../bpf/progs/test_sockmap_msg_apply.c | 46 +++++++ 2 files changed, 172 insertions(+) create mode 100644 tools/testing/selftests/bpf/progs/test_sockmap_msg_apply.c
tools/testing/selftests/bpf/prog_tests/sockmap_basic.c +126 -0
@@ -14,6 +14,7 @@#include "test_sockmap_drop_prog.skel.h" #include "test_sockmap_change_tail.skel.h" #include "test_sockmap_msg_pop_data.skel.h" +#include "test_sockmap_msg_apply.skel.h" #include "bpf_iter_sockmap.skel.h" #include "sockmap_helpers.h"
@@ -1362,6 +1363,129 @@ static void test_sockmap_no_verdict_fionread(void)test_sockmap_pass_prog__destroy (skel); } +#define APPLY_MSG_MAGIC 0xbeefcafe + +/* +* One message: a header with its length, then the body. The sk_msg prog +* applies the verdict to the whole message and redirects it to the egress +* of b. b has the smallest send buffer and its peer the smallest receive +* buffer, so the first send() stops in the middle of the message. The rest +* must still go to b without another run of the prog. +*/ +static void test_sockmap_msg_verdict_apply_partial (void ) +{ +int a =-1 , a_peer =-1 , b =-1 , b_peer =-1 , s =-1 ; +struct test_sockmap_msg_apply *skel; +int err, map, one =1 , zero =0 ; +struct sockaddr_storage addr; +size_t len, off =0 , got =0 ; +char *buf =NULL , *rbuf =NULL ; +int sndbuf, rcvbuf; +socklen_t optlen; +struct { +__u32 magic; +__u32 len; + } hdr; +ssize_t n; + + skel =test_sockmap_msg_apply__open_and_load (); +if (!ASSERT_OK_PTR (skel,"open_and_load" )) +return ; + map =bpf_map__fd (skel->maps.sock_map); + + err =bpf_prog_attach (bpf_program__fd (skel->progs.prog_msg_apply_redir), + map,BPF_SK_MSG_VERDICT ,0 ); +if (!ASSERT_OK (err,"bpf_prog_attach" )) + goto out; + + err =create_pair (AF_INET ,SOCK_STREAM , &a_peer, &a); +if (!ASSERT_OK (err,"create_pair" )) + goto out; + +/* The peer of b gets its receive buffer before the handshake */ + s =socket_loopback (AF_INET ,SOCK_STREAM ); +if (!ASSERT_GE (s,0 ,"socket_loopback" )) + goto out_close; +if (xsetsockopt (s,SOL_SOCKET ,SO_RCVBUF , &one,sizeof (one))) + goto out_close; + b =xsocket (AF_INET ,SOCK_STREAM ,0 ); +if (b <0 ) + goto out_close; +if (xsetsockopt (b,SOL_SOCKET ,SO_SNDBUF , &one,sizeof (one))) + goto out_close; + optlen =sizeof (addr); +if (xgetsockname (s,sockaddr (&addr), &optlen)) + goto out_close; +if (xconnect (b,sockaddr (&addr), optlen)) + goto out_close; + b_peer =xaccept_nonblock (s,NULL ,NULL ); +if (b_peer <0 ) + goto out_close; + + optlen =sizeof (sndbuf); +if (xgetsockopt (b,SOL_SOCKET ,SO_SNDBUF , &sndbuf, &optlen)) + goto out_close; + optlen =sizeof (rcvbuf); +if (xgetsockopt (b_peer,SOL_SOCKET ,SO_RCVBUF , &rcvbuf, &optlen)) + goto out_close; +/* Larger than what b and its peer can hold */ + len =4 * (sndbuf + rcvbuf); + + err =bpf_map_update_elem (map, &zero, &b,BPF_NOEXIST ); +if (!ASSERT_OK (err,"bpf_map_update_elem(b)" )) + goto out_close; + err =bpf_map_update_elem (map, &one, &a,BPF_NOEXIST ); +if (!ASSERT_OK (err,"bpf_map_update_elem(a)" )) + goto out_close; + + buf =malloc (len); + rbuf =calloc (len,1 ); +if (!ASSERT_OK_PTR (buf,"malloc" ) || !ASSERT_OK_PTR (rbuf,"calloc" )) + goto out_close; +memset (buf,0xaa , len); + hdr.magic =APPLY_MSG_MAGIC ; + hdr.len = len; +memcpy (buf, &hdr,sizeof (hdr)); + +while (got < len) { +if (off < len) { + n =send (a, buf + off, len - off,MSG_DONTWAIT ); +if (!ASSERT_TRUE (n >=0 || errno ==EAGAIN ,"send" )) +break ; +if (n >0 ) { +if (!off && !ASSERT_LT (n, len,"first send partial" )) +break ; + off += n; + }else { +usleep (1000 ); + } + } +while (got < off) { + n =recv_timeout (b_peer, rbuf + got, off - got,0 , +IO_TIMEOUT_SEC ); +if (!ASSERT_GT (n,0 ,"recv_timeout" )) + goto out_close; + got += n; + } + } + +ASSERT_EQ (got, len,"received" ); +ASSERT_OK (memcmp (buf, rbuf, len),"data" ); +ASSERT_EQ (skel->bss->good_hdrs,1 ,"prog runs on the header" ); +ASSERT_EQ (skel->bss->bad_hdrs,0 ,"prog runs in the body" ); + +out_close: +free (buf); +free (rbuf); +close (s); +close (a); +close (a_peer); +close (b); +close (b_peer); +out: +test_sockmap_msg_apply__destroy (skel); +} +void test_sockmap_basic (void ) {if (test__start_subtest ("sockmap create_update_free" ))
@@ -1438,4 +1562,6 @@ void test_sockmap_basic(void)test_sockmap_multi_channels (SOCK_STREAM );if (test__start_subtest ("sockmap udp multi channels" ))test_sockmap_multi_channels (SOCK_DGRAM ); +if (test__start_subtest ("sockmap msg_verdict apply_bytes partial redirect" )) +test_sockmap_msg_verdict_apply_partial (); }
tools/testing/selftests/bpf/progs/test_sockmap_msg_apply.c new file +46 -0
46 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH bpf 05/11] bpf, sockmap: Fix concurrent senders on one psock
In reply to Jiayuan ChenThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] bpf, sockmap: -EBUSY from tcp_bpf_sendmsg() aborts sk_psock_backlog() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] bpf, sockmap: -EBUSY from tcp_bpf_sendmsg() aborts sk_psock_backlog()
--
commit d941631cdccff7e72d215bc4dd09b124e439b443
Author: Jiayuan Chen <[email protected]>
bpf, sockmap: Fix concurrent senders on one psock
This commit adds an SK_PSOCK_TX_BUSY state bit to reject concurrent callers of tcp_bpf_sendmsg() on the same psock with -EBUSY.
Quoted 7 lines
net/ipv4/tcp_bpf.c +0
-0@@ -602,6 +602,16 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)if (unlikely (!psock))return tcp_sendmsg (sk, msg, size);
net/ipv4/tcp_bpf.c static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) · line 613
Quoted 10 lines
net/ipv4/tcp_bpf.c +9
-0+/* +* 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 (test_and_set_bit (SK_PSOCK_TX_BUSY , &psock->state)) { +sk_psock_put (sk, psock); +return -EBUSY ; + }
[Severity: High]
Can returning -EBUSY here abort sk_psock_backlog() when an sk_buff is redirected to the egress of a socket that also has a msg_parser program attached?
For egress sk_buff redirects, sk_psock_handle_skb() sends the packet via skb_send_sock() -> sendmsg_unlocked() -> sock_sendmsg() -> tcp_bpf_sendmsg(). Previously, skb_send_sock() and a userspace sendmsg() on that socket serialized on lock_sock(sk). With this change, when a userspace sender sleeps in sk_stream_wait_memory() with SK_PSOCK_TX_BUSY set and freeing send buffer space wakes sk_psock_write_space(), the backlog work runs and hits -EBUSY:
CPU0 (userspace sendmsg) CPU1 (psock->work)tcp_bpf_sendmsg()
test_and_set_bit(SK_PSOCK_TX_BUSY, ...)
lock_sock(sk)
...
sk_stream_wait_memory()
release_sock(sk)
sk_psock_backlog()
sk_psock_handle_skb()
skb_send_sock()
...
tcp_bpf_sendmsg()
test_and_set_bit(SK_PSOCK_TX_BUSY)
return -EBUSYsk_psock_backlog() only retries on -EAGAIN and treats any other error as fatal:
net/core/skmsg.c:sk_psock_backlog() {
...
if (ret <= 0) {
if (ret == -EAGAIN) {
...
goto end;
}
/* Hard errors break pipe and stop xmit. */
sk_psock_report_error(psock, ret ? -ret : EPIPE);
sk_psock_clear_state(psock, SK_PSOCK_TX_ENABLED);
goto end;
}
...
}This sets sk->sk_err = EBUSY (which also aborts the sleeping userspace sendmsg()) and permanently clears SK_PSOCK_TX_ENABLED, stranding queued packets in psock->ingress_skb. Conversely, if sk_psock_backlog() sets SK_PSOCK_TX_BUSY first, a single userspace sender on the socket fails with -EBUSY instead of waiting on lock_sock(sk).
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
[email protected]
AI reviewRe: [PATCH bpf 08/11] bpf, sockmap: Fix socket lock taken on a child before accept()
In reply to Jiayuan ChenThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf, sockmap: lock_sock() still taken on unaccepted child in strp_done() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf, sockmap: lock_sock() still taken on unaccepted child in strp_done()
--
commit e631a931dbfb1352e17feb424d762db532b4db74
Author: Jiayuan Chen <[email protected]>
bpf, sockmap: Fix socket lock taken on a child before accept()
This commit avoids taking lock_sock() on unaccepted child sockets (where sk->sk_socket is NULL) by rejecting sk_msg redirects in tcp_bpf_sendmsg_redir() before locking and by unlinking such sockets without locking in sock_map_free() and sock_hash_free().
Quoted 32 lines
net/core/sock_map.c +15
-1@@ -386,6 +386,19 @@ static int sock_map_link(struct bpf_map *map, struct sock *sk)return ret; } +/* +* The listener frees a child that nobody has accepted yet without waiting +* for the owner of its socket lock. Unlink such a child without the lock, +* as a delete does. +*/ +static bool sock_map_free_lock_sk (struct sock *sk) +{ +if (!READ_ONCE (sk->sk_socket)) +return false; +lock_sock (sk); +return true; +} +static void sock_map_free (struct bpf_map *map) { struct bpf_stab *stab = container_of(map, struct bpf_stab, map);@@ -402,12 +415,15 @@ static void sock_map_free(struct bpf_map *map) sk =xchg (psk,NULL );if (sk) { +bool locked; +sock_hold (sk); -lock_sock (sk);
net/core/sock_map.c static void sock_map_free(struct bpf_map *map) · line 429
Quoted 10 lines
net/core/sock_map.c +3
-1+ locked =sock_map_free_lock_sk (sk);rcu_read_lock ();sock_map_unref (sk, psk);rcu_read_unlock (); -release_sock (sk); +if (locked) +release_sock (sk);sock_put (sk); } }
[Severity: Medium]
Can asynchronous psock teardown still take lock_sock(sk) on an unaccepted child when the map has a stream parser attached?
When a passive TCP child is added at BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB to a map with stream_parser and stream_verdict programs, sock_map_link() starts the stream parser on the child and sets SK_PSOCK_RX_STRP_ENABLED. Even though sock_map_free() and sock_hash_free() skip lock_sock(sk) here, sock_map_unref() queues sk_psock_destroy() via sock_map_del_link() and sk_psock_put(), which runs sk_psock_done_strp() -> strp_done():
net/strparser/strparser.c:strp_done() {
WARN_ON(!strp->stopped);
lock_sock(strp->sk);
/* sync with pending strp_recv */
release_sock(strp->sk);
...
}If the listener closes while sk_psock_destroy() runs on the workqueue before accept(), strp_done() locks the unaccepted child and inet_csk_listen_stop() can still hit WARN_ON(sock_owned_by_user(child)).
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
[email protected]
AI reviewRe: [PATCH bpf 01/11] bpf, sockmap: Fix copied_seq updates with strparser
In reply to Jiayuan ChenThank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] bpf, sockmap: missing skb_orphan() on error in sk_psock_skb_ingress() - [High] bpf, sockmap…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] bpf, sockmap: missing skb_orphan() on error in sk_psock_skb_ingress()
- [High] bpf, sockmap: multi-segment strparser message rewinds tp->copied_seq
--
commit 4f9dfdace1214b93f005e54687ec6d1b8e1449f2
Author: Jiayuan Chen <[email protected]>
bpf, sockmap: Fix copied_seq updates with strparser
This commit updates tcp->copied_seq incrementally in tcp_bpf_strp_read_sock() and tcp_bpf_recvmsg_parser(), moves psock->ingress_bytes accounting to sk_psock_skb_ingress_self(), and orphans strparser skbs when sk_psock_skb_ingress_enqueue() fails.
Quoted 26 lines
net/core/skmsg.c +6
-4@@ -574,9 +574,6 @@ static int sk_psock_skb_ingress_enqueue(struct sk_buff *skb,return num_sge; } -#if IS_ENABLED (CONFIG_BPF_STREAM_PARSER ) - psock->ingress_bytes += len; -#endif copied = len; msg->sg.start =0 ; msg->sg.size = copied;@@ -642,8 +639,21 @@ static int sk_psock_skb_ingress_self(struct sk_psock *psock, struct sk_buff *skb*/ msg->sk = sk; err =sk_psock_skb_ingress_enqueue (skb, off, len, psock, sk, msg, take_ref); -if (err <0 ) +if (err <0 ) {kfree (msg); +/* +* A strparser skb comes in without an owner and read_sock counts +* it as consumed once it is left to the backlog. Drop the owner +* again, or sk_psock_skb_ingress() takes the skb->sk == sk path +* and recvmsg() counts it a second time.
net/core/skmsg.c static int sk_psock_skb_ingress_self(struct sk_psock *psock, struct sk_buff *skb · line 658
Quoted 10 lines
net/core/skmsg.c +8
-0+*/ +if (skb_bpf_strparser (skb)) +skb_orphan (skb); + } +#if IS_ENABLED (CONFIG_BPF_STREAM_PARSER ) + else + psock->ingress_bytes += len; +#endif return err; }
[Severity: High]
Does sk_psock_skb_ingress() also need to orphan the skb when sk_psock_skb_ingress_enqueue() fails?
net/core/skmsg.c:sk_psock_skb_ingress() {
if (unlikely(skb->sk == sk))
return sk_psock_skb_ingress_self(psock, skb, off, len, true);
msg = sk_psock_create_ingress_msg(sk, skb);
if (!msg)
return -EAGAIN;
skb_set_owner_r(skb, sk);
err = sk_psock_skb_ingress_enqueue(skb, off, len, psock, sk, msg, true);
if (err < 0)
kfree(msg);
return err;
}When sk_psock_backlog() processes a strparser skb (or an skb redirected to ingress from another socket), skb->sk != sk, so sk_psock_skb_ingress() calls skb_set_owner_r(skb, sk) and then sk_psock_skb_ingress_enqueue(). If sk_psock_skb_ingress_enqueue() fails with -EAGAIN (for instance, when an skb with more than MAX_MSG_FRAGS fragments fails skb_linearize() under memory pressure), the skb stays on psock->ingress_skb with skb->sk == sk while sk_psock_backlog() has already stripped BPF_F_STRPARSER via skb_bpf_redirect_clear().
On the next backlog run, sk_psock_skb_ingress() sees skb->sk == sk and takes the sk_psock_skb_ingress_self() branch without holding the socket lock. That modifies psock->ingress_bytes concurrently with tcp_bpf_strp_read_sock() and sets msg->sk = sk, so tcp_bpf_recvmsg_parser() adds the bytes to tcp->copied_seq a second time (or counts foreign redirected bytes against this socket's tcp->copied_seq), pushing tcp->copied_seq past rcv_nxt and stalling the socket.
Quoted 4 lines
net/ipv4/tcp_bpf.c +0
-0
[ ... ]
Quoted 17 lines
net/ipv4/tcp_bpf.c +2
-0@@ -756,6 +753,7 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc,struct sk_psock *psock;struct tcp_sock *tp;int copied =0 ; +u32 seq; tp =tcp_sk (sk);rcu_read_lock ();@@ -765,6 +763,7 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc, goto out; } + seq = psock->copied_seq; psock->ingress_bytes =0 ; copied =tcp_read_sock_noack (sk, desc, recv_actor, true, &psock->copied_seq);
net/ipv4/tcp_bpf.c int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc, · line 781
Quoted 9 lines
net/ipv4/tcp_bpf.c +2
-1@@ -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); out:
[Severity: High]
What happens here when a strparser message spans multiple TCP segments across separate tcp_bpf_strp_read_sock() calls?
When the first segment of length L1 arrives and is buffered in strp->skb_head awaiting the rest of the message, strp->cb.rcv_msg does not run yet, so psock->copied_seq - seq is L1 and psock->ingress_bytes is 0. tcp_bpf_strp_read_sock() advances tp->copied_seq by L1 and calls __tcp_cleanup_rbuf(sk, L1) before any verdict runs (and if the partial message later times out or hits a parser error, tp->copied_seq remains permanently over-advanced by L1).
When the second segment of length L2 arrives and completes the message with SK_PASS, sk_psock_verdict_apply() passes stm->full_len (L1 + L2) to sk_psock_skb_ingress_self(), setting psock->ingress_bytes to L1 + L2 while psock->copied_seq - seq is only L2. Subtracting psock->ingress_bytes then adds L2 - (L1 + L2) = -L1, rewinding tp->copied_seq backwards, and makes copied - psock->ingress_bytes negative, which suppresses immediate ACKs in __tcp_cleanup_rbuf() for any SK_REDIRECT frame processed in the same call.
Holding back tp->copied_seq for unread SK_PASS messages in ingress_msg also inflates strp_peek_len() (which queries tcp_inq(), i.e. tp->rcv_nxt - tp->copied_seq), so strp_recv() can see stm->strp.full_len - stm->accum_len <= strp_peek_len(strp) on an intermediate segment and skip updating strp->need_bytes, causing strp_data_ready() not to wake the parser once the earlier message is read.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [PATCH bpf 02/11] selftests/bpf: Add test for unread SK_PASS data with strparser
In reply to Jiayuan ChenThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] selftests/bpf: unbounded FIONREAD polling loop in sockmap_strp_wait_fionread() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] selftests/bpf: unbounded FIONREAD polling loop in sockmap_strp_wait_fionread()
--
commit 7dc8918154820719ad134eef16ba69d4d7e96153
Author: Jiayuan Chen <[email protected]>
selftests/bpf: Add test for unread SK_PASS data with strparser
This commit adds IPv4 and IPv6 sockmap strparser subtests verifying that unread SK_PASS data across multiple parser invocations does not stall subsequent packet delivery.
Quoted 12 lines
tools/testing/selftests/bpf/prog_tests/sockmap_strp.c +4
-0@@ -364,6 +364,88 @@ static void test_sockmap_strp_pass(int family, int sotype, bool fionread)test_sockmap_strp__destroy (strp); } +static int sockmap_strp_wait_fionread (int fd,int expected) +{ +int err, avail =0 ; +
tools/testing/selftests/bpf/prog_tests/sockmap_strp.c static void test_sockmap_strp_pass(int family, int sotype, bool fionread) · line 380
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/sockmap_strp.c +10
-0+while (1 ) { + err =ioctl (fd,FIONREAD , &avail); +if (!ASSERT_OK (err,"ioctl(FIONREAD) error" )) +return -1 ; +if (avail >= expected) +break ; +usleep (10000 ); + } +return ASSERT_EQ (avail, expected,"ioctl(FIONREAD)" ) ?0 :-1 ; +}
[Severity: Low]
Can sockmap_strp_wait_fionread() hang test_progs forever if a regression prevents the expected bytes from arriving? Without a timeout or retry bound on the loop, avail < expected spins indefinitely instead of exiting and failing the ASSERT_EQ() check.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [PATCH bpf 03/11] bpf, sockmap: Fix strparser reinit after the parser link is removed
In reply to Jiayuan ChenThank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] bpf, sockmap: active work_struct reinit on psock->rwork in skmsg - [High] bpf, sockmap…
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] bpf, sockmap: active work_struct reinit on psock->rwork in skmsg
- [High] bpf, sockmap: sk_psock_init_strp() rewinds psock->copied_seq
- [High] bpf, sockmap: softirq livelock in sock_map_destroy() on rwork put
- [Medium] bpf, sockmap: race and missing wait in sock_map_strp_done_wait()
--
commit d7a98bf12f6088d3395a10dfb32d450db8554b49
Author: Jiayuan Chen <[email protected]>
bpf, sockmap: Fix strparser reinit after the parser link is removed
This commit tears down the strparser asynchronously via psock->rwork when a parser link is removed while other sockmap links keep the psock alive, and blocks attaching a new parser until teardown finishes.
Quoted 13 lines
net/core/skmsg.c +5
-0@@ -879,6 +879,18 @@ static void sk_psock_destroy(struct work_struct *work) {struct sk_psock *psock =container_of (to_rcu_work (work), struct sk_psock, rwork); + +if (sk_psock_test_state (psock,SK_PSOCK_STRP_DONE_PENDING )) { +/* Parser link gone, other links keep the psock alive */ +sk_psock_done_strp (psock); +write_lock_bh (&psock->sk->sk_callback_lock);
net/core/skmsg.c static void sk_psock_destroy(struct work_struct *work) · line 896
Quoted 10 lines
net/core/skmsg.c +7
-0+sk_psock_clear_state (psock,SK_PSOCK_RX_STRP_ENABLED ); +sk_psock_clear_state (psock,SK_PSOCK_STRP_DONE_PENDING ); +write_unlock_bh (&psock->sk->sk_callback_lock); +sk_psock_put (psock->sk, psock); +return ; + } +/* No sk_callback_lock since already detached. */ sk_psock_done_strp (psock);
[Severity: High]
Does calling sk_psock_put() with bottom halves enabled here risk a softirq livelock in sock_map_destroy()?
When the removed parser link was the last link on the socket, sk_psock_queue_strp_done() holds a psock reference until rwork runs. If the socket is closed in the meantime, sock_map_close() does not wait for rwork and calls saved_close() while sk->sk_prot->destroy is still sock_map_destroy. When rwork drops the last psock reference with BH enabled, a softirq destroying the socket on the same CPU can interrupt between refcount_dec_and_test() and sk_psock_restore_proto():
sk_psock_destroy()
write_unlock_bh(&sk->sk_callback_lock)
sk_psock_put(sk, psock)
refcount_dec_and_test(&psock->refcnt) -> true
<softirq>
tcp_v4_rcv()
...
sock_map_destroy()
sk_psock_get(sk) -> NULL
READ_ONCE(sk->sk_prot)->destroy == sock_map_destroy
goto retry; <-- spins forever
sk_psock_drop()
sk_psock_restore_proto()The interrupted kworker cannot resume to restore sk->sk_prot, so the CPU hard-locks in the retry loop.
Quoted 9 lines
net/core/skmsg.c +5
-0@@ -1208,6 +1220,18 @@ void sk_psock_stop_strp(struct sock *sk, struct sk_psock *psock)strp_stop (&psock->strp); } +/* Called with sk_callback_lock held while a link still holds the psock */ +void sk_psock_queue_strp_done (struct sk_psock *psock) +{ +if (!sk_psock_test_state (psock,SK_PSOCK_RX_STRP_ENABLED ) || +test_and_set_bit (SK_PSOCK_STRP_DONE_PENDING , &psock->state))
net/core/skmsg.c void sk_psock_stop_strp(struct sock *sk, struct sk_psock *psock) · line 1237
Quoted 10 lines
net/core/skmsg.c +7
-0+return ; + +refcount_inc (&psock->refcnt); +INIT_WORK (&psock->rwork.work, sk_psock_destroy); +schedule_work (&psock->rwork.work); +} +static void sk_psock_done_strp (struct sk_psock *psock) {/* Parser has been stopped */
[Severity: High]
Can re-initializing psock->rwork here and in sk_psock_drop() corrupt the work item while it is still executing or being flushed?
When sk_psock_destroy() finishes the SK_PSOCK_STRP_DONE_PENDING path and calls sk_psock_put(), dropping the last reference calls sk_psock_drop() -> INIT_RCU_WORK(&psock->rwork, sk_psock_destroy) from inside the running psock->rwork.work callback. If another link kept the psock alive, a concurrent parser attach and detach on another CPU can likewise call sk_psock_queue_strp_done() -> INIT_WORK(&psock->rwork.work, ...) as soon as sk_callback_lock is released, while the first worker is still in process_one_work() or while another task is in flush_work():
CPU0 (kworker) CPU1process_one_work(rwork.work)
sk_psock_destroy()
clear SK_PSOCK_STRP_DONE_PENDING
write_unlock_bh()
sock_map_del_link()
sk_psock_queue_strp_done()
INIT_WORK(&psock->rwork.work, ...)
schedule_work(&psock->rwork.work)
sk_psock_put()
sk_psock_drop()
INIT_RCU_WORK(&psock->rwork, ...)
queue_rcu_work(..., &psock->rwork)
process_one_work(rwork.work)
sk_psock_destroy()
kfree(psock) <-- use-after-freeINIT_WORK() and INIT_RCU_WORK() overwrite work->data (wiping the worker pool ID needed by find_worker_executing_work() and start_flush_work()) and re-initialize work->lockdep_map. That lets __queue_work() run sk_psock_destroy() on a second CPU concurrently while the first worker is still finishing, and causes flush_work() in sock_map_strp_done_wait() to see a NULL pool and return early without waiting. Could psock->rwork be initialized once in sk_psock_init() instead?
[Severity: High]
When a surviving psock is later added to another parser map and goes through sk_psock_init_strp() again, does resetting psock->copied_seq drop subsequent incoming TCP data?
net/core/skmsg.c:sk_psock_init_strp() {
...
if (sk_is_tcp(sk)) {
psock->strp.cb.read_sock = tcp_bpf_strp_read_sock;
psock->copied_seq = tcp_sk(sk)->copied_seq;
}
...
}In tcp_bpf_strp_read_sock(), tp->copied_seq is held behind psock->copied_seq by the unread SK_PASS bytes sitting in psock->ingress_msg. If unread SK_PASS messages from the first parser are still queued in psock->ingress_msg when the second parser is initialized, overwriting psock->copied_seq with tcp_sk(sk)->copied_seq rewinds psock->copied_seq behind the next skb on sk->sk_receive_queue. On later packets, tcp_recv_skb() computes offset = seq - TCP_SKB_CB(skb)->seq, which underflows u32 to a value larger than skb->len and causes __tcp_read_sock() to discard incoming skbs via tcp_eat_recv_skb().
Quoted 24 lines
net/core/sock_map.c +16
-0@@ -115,6 +115,33 @@ int sock_map_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)return ret; } +/* +* Wait for the strparser of a removed parser link to be torn down, so that +* a new parser can be attached right after the old one was removed. +*/ +static void sock_map_strp_done_wait (struct bpf_map *map,struct sock *sk) +{ +struct sk_psock *psock; + +if (!READ_ONCE (sock_map_progs (map)->stream_parser)) +return ; + +rcu_read_lock (); +read_lock_bh (&sk->sk_callback_lock); + psock =sk_psock (sk); + if (!psock || + !sk_psock_test_state(psock, SK_PSOCK_STRP_DONE_PENDING) ||
net/core/sock_map.c int sock_map_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype) · line 143
Quoted 10 lines
net/core/sock_map.c +10
-0+ !refcount_inc_not_zero(&psock->refcnt)) + psock =NULL ; +read_unlock_bh (&sk->sk_callback_lock); +rcu_read_unlock (); +if (!psock) +return ; + +flush_work (&psock->rwork.work); +sk_psock_put (sk, psock); +}
[Severity: Medium]
Can a back-to-back map update still race with a dying zero-link psock or attach to it before teardown finishes?
kworker CPU1sk_psock_destroy()
write_lock_bh(&sk_callback_lock)
clear SK_PSOCK_STRP_DONE_PENDING
write_unlock_bh(&sk_callback_lock)
sock_map_update_elem_sys()
sock_map_strp_done_wait()
/* DONE_PENDING clear: no wait */
sock_map_link()
sock_map_psock_get_checked()
sk_psock_put()
refcount_dec_and_test() -> 0
refcount_inc_not_zero() -> 0
return ERR_PTR(-EBUSY)
sk_psock_drop()
rcu_assign_sk_user_data(sk, NULL)Because sk_psock_queue_strp_done() takes a reference on psock when the last link is removed, the zero-link psock stays in sk->sk_user_data until rwork drops that reference. Clearing SK_PSOCK_STRP_DONE_PENDING before sk_psock_put() opens a window where sock_map_strp_done_wait() does not flush, and sock_map_psock_get_checked() either returns -EBUSY (if refcnt just hit 0) or resurrects the dying psock with its old psock->progs.msg_parser still installed.
Also, because sock_map_strp_done_wait() and the SK_PSOCK_RX_STRP_ENABLED check in sock_map_link() both only trigger when the new map has a stream_parser, adding the socket to a map without a stream_parser right after removing its last link from a parser map skips the wait completely:
it can hit the same resurrection or -EBUSY, or call sk_psock_start_verdict() while strp_done() is still pending.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
[email protected]
AI reviewRe: [PATCH bpf 09/11] bpf, sockmap: Fix apply_bytes when a redirect sends only a part
In reply to Jiayuan ChenTL;DR: The apply_bytes give-back in tcp_bpf_send_verdict() may leave a source socket permanently failing sendmsg() with -EPIPE after its redirect target closes, since the restored redirect verdict…
Quoted 1 line
bpf, sockmap: Fix
apply_byteswhen a redirect sends only a part
TL;DR: The apply_bytes give-back in tcp_bpf_send_verdict() may leave a source socket permanently failing sendmsg() with -EPIPE after its redirect target closes, since the restored redirect verdict is never cleared.
Quoted 3 lines
net/ipv4/tcp_bpf.c +0
-0
[ ... ]
Quoted 10 lines
net/ipv4/tcp_bpf.c +6
-0@@ -566,6 +563,21 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, msg =NULL ; ret =0 ; } +/* +* Bytes that were not sent and come back, in msg or in the +* next sendmsg(), are still covered by the verdict. +*/ +if (apply && sent < tosend && !cork) { + psock->apply_bytes += tosend - sent;
net/ipv4/tcp_bpf.c static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, · line 581
Quoted 10 lines
net/ipv4/tcp_bpf.c +9
-0+if (eval == __SK_REDIRECT) { + psock->eval = eval; + psock->sk_redir = sk_redir; + eval = __SK_NONE; + } + } +if (eval == __SK_REDIRECT) +sock_put (sk_redir); +sock_put (sk_redir);break ;
Can this give-back leave the source socket unable to send after the redirect target goes away?
The give-back runs for every short redirect, whatever the error. Some errors from tcp_bpf_sendmsg_redir() are permanent and send nothing (sent == 0):
if (!READ_ONCE(sk->sk_socket))
return sock_flag(sk, SOCK_DEAD) ? -EPIPE : -EINVAL;
psock = sk_psock_get(sk);
if (unlikely(!psock))
return -EPIPE;They happen when the target was closed (__tcp_close() -> sock_orphan()) or removed from the sockmap. The same goes for an egress target whose connection was reset, where tcp_sendmsg_locked() returns -EPIPE.
In those cases sk_msg_apply_bytes(psock, tosend) takes off tosend bytes and the new code adds tosend - 0 back, so psock->apply_bytes ends up at its old value. When apply_bytes had reached 0, the code also puts back psock->eval = __SK_REDIRECT and psock->sk_redir = <dead target>.
Nothing else clears that state. The only writers of psock->eval, apply_bytes and sk_redir are this function, sk_psock_msg_verdict() (which runs only when psock->eval == __SK_NONE), the cork_bytes reset in tcp_bpf_sendmsg(), and sk_psock_destroy(). So every later sendmsg() on the source socket follows the same path:
tcp_bpf_sendmsg() -> tcp_bpf_send_verdict()
psock->eval == __SK_REDIRECT, prog not run
tcp_bpf_sendmsg_redir(dead target) -> -EPIPE, sent = 0
apply_bytes restored, verdict restored
-> sk_stream_error() -> -EPIPE (plus SIGPIPE unless MSG_NOSIGNAL)The source socket's own connection is healthy, but it can no longer send while it is in the sockmap. The sk_msg program never runs again, so it cannot pick a new target or drop. The dead target's struct sock also stays pinned by psock->sk_redir until the psock is destroyed.
Before this patch the verdict always used up tosend bytes, even on failure. A redirect to a dead target failed at most about apply_bytes / tosend times. Then psock->eval went back to __SK_NONE, the prog ran again, and with the closed target gone from the map the lookup failed and the prog returned SK_DROP (or chose another target).
The give-back is right for short sends the user is expected to retry (-EAGAIN, -ENOMEM from bpf_tcp_ingress(), a partial ret == 0). Should it be skipped, or should the verdict be cleared, when the target cannot take data any more (for example -EPIPE)?
No later commit in the series changes net/ipv4/tcp_bpf.c; the rest of the series only adds selftests.
---
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
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44896626218
[email protected]
AI reviewRe: [PATCH bpf 09/11] bpf, sockmap: Fix apply_bytes when a redirect sends only a part
In reply to Jiayuan ChenThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf, sockmap: partial ingress redirect re-corks and drops verdict --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf, sockmap: partial ingress redirect re-corks and drops verdict
--
commit 0323f7103abecfb3f1dce63a498066c469f02365
Author: Jiayuan Chen <[email protected]>
bpf, sockmap: Fix apply_bytes when a redirect sends only a part
When a redirect in tcp_bpf_send_verdict() sends fewer than tosend bytes, this commit restores the unsent portion to psock->apply_bytes and preserves the __SK_REDIRECT verdict and target socket on psock.
Quoted 4 lines
net/ipv4/tcp_bpf.c +0
-0
[ ... ]
Quoted 9 lines
net/ipv4/tcp_bpf.c +5
-0@@ -566,6 +563,21 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, msg =NULL ; ret =0 ; } +/* +* Bytes that were not sent and come back, in msg or in the +* next sendmsg(), are still covered by the verdict. +*/ +if (apply && sent < tosend && !cork) {
net/ipv4/tcp_bpf.c static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, · line 580
Quoted 10 lines
net/ipv4/tcp_bpf.c +10
-0+ psock->apply_bytes += tosend - sent; +if (eval == __SK_REDIRECT) { + psock->eval = eval; + psock->sk_redir = sk_redir; + eval = __SK_NONE; + } + } +if (eval == __SK_REDIRECT) +sock_put (sk_redir); +sock_put (sk_redir);
[Severity: Medium]
Can a partial ingress redirect of a message with msg->cork_bytes set end up re-corking the unsent remainder and dropping the preserved __SK_REDIRECT verdict?
If an sk_msg verdict program uses both bpf_msg_cork_bytes() and bpf_msg_apply_bytes() (or flushes an existing psock->cork), and bpf_tcp_ingress() transfers at least one scatterlist element before running out of receive buffer space on a later element, bpf_tcp_ingress() returns 0 with 0 < sent < tosend and msg->sg.size > 0. When msg was psock->cork, the preceding check:
net/ipv4/tcp_bpf.c:tcp_bpf_send_verdict() {
...
if (cork && msg->sg.size && !psock->cork) {
psock->cork = msg;
cork = false;
}
...
}puts msg back into psock->cork and clears cork, so the new block restores psock->apply_bytes and psock->eval = __SK_REDIRECT, and execution jumps to more_data.
At more_data, sk_psock_msg_verdict() is skipped because psock->eval is no longer __SK_NONE, but msg->cork_bytes still holds the original cork threshold while msg->sg.size has shrunk by sent:
net/ipv4/tcp_bpf.c:tcp_bpf_send_verdict() {more_data:
if (psock->eval == __SK_NONE) {
...
}
if (msg->cork_bytes &&
msg->cork_bytes > msg->sg.size && !enospc) {
psock->cork_bytes = msg->cork_bytes - msg->sg.size;
...
sk_msg_reset_curr(msg);
memcpy(psock->cork, msg, sizeof(*msg));
return 0;
}
}Because msg->cork_bytes > msg->sg.size is now true, this re-corks the unsent tail (and calls memcpy(psock->cork, msg, sizeof(*msg)) with psock->cork == msg when msg was already psock->cork). On the next sendmsg(), once the new psock->cork_bytes count is satisfied, tcp_bpf_sendmsg() resets psock->eval = __SK_NONE, losing the preserved __SK_REDIRECT verdict and re-running the BPF program in the middle of the message.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
[email protected]
AI reviewRe: [PATCH bpf 08/11] bpf, sockmap: Fix socket lock taken on a child before accept()
In reply to Jiayuan ChenTL;DR: Behaviour change question: sk_msg ingress redirects to not-yet-accepted children now fail with -EINVAL instead of queueing, and with bpf_msg_cork_bytes() send() may report success while…
Quoted 1 line
bpf, sockmap: Fix socket lock taken on a child before
accept()
TL;DR: Behaviour change question: sk_msg ingress redirects to not-yet-accepted children now fail with -EINVAL instead of queueing, and with bpf_msg_cork_bytes() send() may report success while dropping data. Intended?
Quoted 3 lines
net/ipv4/tcp_bpf.c +0
-0
[ ... ]
Quoted 4 lines
net/ipv4/tcp_bpf.c +0
-0@@ -188,9 +188,17 @@ static int tcp_bpf_push_locked(struct sock *sk, struct sk_msg *msg,int tcp_bpf_sendmsg_redir (struct sock *sk,bool ingress,struct sk_msg *msg,u32 bytes,int flags) {
net/ipv4/tcp_bpf.c static int tcp_bpf_push_locked(struct sock *sk, struct sk_msg *msg, · line 199
Quoted 10 lines
net/ipv4/tcp_bpf.c +7
-1-struct sk_psock *psock =sk_psock_get (sk); +struct sk_psock *psock;int ret; +/* +* The listener frees a child that nobody has accepted yet without +* waiting for the owner of its socket lock. +*/ +if (!READ_ONCE (sk->sk_socket)) +return sock_flag (sk,SOCK_DEAD ) ? -EPIPE : -EINVAL ;
Before this patch, an ingress redirect (BPF_F_INGRESS) to a peer that the server has not accepted yet queued the data on the psock, and the server read it after accept(). Is this change in behavior intended?
A common setup adds the client at BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB and the server child at BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB, and the client's sk_msg program redirects to the peer with BPF_F_INGRESS. If the client sends before the server calls accept(), the child still has sk->sk_socket == NULL, so this now returns -EINVAL.
The old path was:
tcp_bpf_sendmsg_redir(child, ingress=true)
bpf_tcp_ingress()
lock_sock(child)
sk_psock_queue_msg()
sk_psock_data_ready()
and tcp_bpf_recvmsg() read psock->ingress_msg after accept(). The comment in tcp_bpf_recvmsg_parser() ("We may have received data on the sk_receive_queue pre-accept ...") suggests pre-accept data on a sockmap child is a supported state.
For a plain send(), this means the call fails depending on whether it runs before the server's accept().
With bpf_msg_cork_bytes(), the failure looks worse. In tcp_bpf_send_verdict():
if (unlikely(ret < 0)) {
int free = sk_msg_free(sk, msg);
if (!cork)
*copied -= free;
}
...
if (cork) {
sk_msg_free(sk, msg);
kfree(msg);
msg = NULL;
ret = 0;
}For a corked message the data is freed, ret is set to 0 and *copied is left unchanged, so can send() report success while the bytes are dropped from the TCP stream?
Also, sk_psock_skb_ingress() still queues to unaccepted children, so sk_skb and sk_msg redirects now behave differently.
The commit message says "Refuse the ingress redirect too". It does not mention that a redirect which used to deliver now fails, or that corked data can be dropped. Could the ingress case avoid the WARN_ON without refusing delivery, or should this behavior change be stated and justified?
net/ipv4/tcp_bpf.c static int tcp_bpf_push_locked(struct sock *sk, struct sk_msg *msg, · line 203
Quoted 4 lines
net/ipv4/tcp_bpf.c +1
-0+ psock =sk_psock_get (sk);if (unlikely (!psock))return -EPIPE ;
---
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
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44896626218
[email protected]
AI reviewRe: [PATCH bpf 03/11] bpf, sockmap: Fix strparser reinit after the parser link is removed
In reply to Jiayuan ChenTL;DR: - Behaviour regression possible: re-adding a socket to a parser map after removing its only parser link may now fail with -EBUSY (also kcm/TLS setup) - Misleading comment in…
Quoted 1 line
bpf, sockmap: Fix strparser reinit after the parser link is removed
TL;DR:
- Behaviour regression possible: re-adding a socket to a parser map after removing its only parser link may now fail with -EBUSY (also kcm/TLS setup)
- Misleading comment in sk_psock_destroy() and commit message for single-link case
Quoted 3 lines
net/core/skmsg.c +0
-0
[ ... ]
net/core/skmsg.c static void sk_psock_destroy(struct work_struct *work) · line 884
Quoted 7 lines
net/core/skmsg.c +3
-0@@ -879,6 +879,18 @@ static void sk_psock_destroy(struct work_struct *work) {struct sk_psock *psock =container_of (to_rcu_work (work), struct sk_psock, rwork); + +if (sk_psock_test_state (psock,SK_PSOCK_STRP_DONE_PENDING )) { +/* Parser link gone, other links keep the psock alive */
This comment doesn't hold when the removed link was the psock's only link. In that case only the reference taken in sk_psock_queue_strp_done() keeps the psock alive.
Quoted 1 line
net/core/skmsg.c +1
-0+sk_psock_done_strp (psock);
[ ... ]
Quoted 3 lines
net/core/sock_map.c +0
-0
[ ... ]
Quoted 11 lines
net/core/sock_map.c +3
-1@@ -169,8 +196,10 @@ static void sock_map_del_link(struct sock *sk,write_lock_bh (&sk->sk_callback_lock);if (psock->saved_data_ready) { -if (strp_stop) +if (strp_stop) {sk_psock_stop_strp (sk, psock); +sk_psock_queue_strp_done (psock); + }if (verdict_stop)sk_psock_stop_verdict (sk, psock);
[ ... ]
net/core/sock_map.c static int sock_map_link(struct bpf_map *map, struct sock *sk) · line 335
Quoted 11 lines
net/core/sock_map.c +7
-0@@ -297,6 +326,13 @@ static int sock_map_link(struct bpf_map *map, struct sock *sk) }write_lock_bh (&sk->sk_callback_lock); +if (stream_parser && +sk_psock_test_state (psock,SK_PSOCK_RX_STRP_ENABLED )) { +write_unlock_bh (&sk->sk_callback_lock); +sk_psock_put (sk, psock); + ret = -EBUSY ; + goto out_progs; + }
Can this make a previously working sequence fail when the removed parser link was the only link on the psock?
Before this patch, removing the last link ended in sock_map_unref() -> sk_psock_put() -> refcnt 0 -> sk_psock_drop(), which cleared sk_user_data and restored sk_prot synchronously. A following add of the same socket to a parser map found no psock in sock_map_psock_get_checked() and sk_psock_init() created a fresh psock.
With this patch, sock_map_del_link() calls sk_psock_queue_strp_done(), which does:
refcount_inc(&psock->refcnt); INIT_WORK(&psock->rwork.work, sk_psock_destroy); schedule_work(&psock->rwork.work);
so the old psock stays attached until the work runs. sock_map_psock_get_checked() then returns that psock, and the new check above sees SK_PSOCK_RX_STRP_ENABLED and returns -EBUSY.
sock_map_update_elem_sys() waits via sock_map_strp_done_wait(), but sock_map_update_elem() as the map op and bpf_sock_map_update() / bpf_sock_hash_update() cannot wait. A sockops or iterator program that deletes a socket from its only parser map and adds it to a parser map now fails with -EBUSY whenever the update comes before the work completes. If the program runs with the socket lock owned, the work cannot finish in between at all, since strp_done() takes lock_sock().
The lingering psock also seems to make kcm_attach() fail:
if (csk->sk_user_data) ... err = -EALREADY
and TLS setup fail in that window, where both would have succeeded on the psock-less socket before.
The commit message says "Before this change the same sequence reinitialized a live strparser, so this is the better outcome." Does that premise only hold when another link keeps the psock alive? In the single-link case the old code returned success.
Could the deferred strp_done be limited to psocks that survive the unlink? Or could the commit message at least describe the single-link behavior 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
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44896626218
Quoted 1 line · Jiayuan Chen
This series fixes misc issues in sockmap. Most of them are old.
Jiayuan,
thanks for the follow up,
but the fixes are way too heavy. bots are correct.
The patches introduce more bugs than the fix.
Pls ask your bot to think of absolultely minimal fixes that do not introduce new states.
pw-bot: cr