Skip to contentSkip to conversation

bpf: Add SOCK_OPS hooks for TCP AutoLOWAT.

PATCH In review Kuniyuki Iwashima 6 participants 39 messages May 23 – May 28

Subsystems (8)
lore
Share & tools
lore

Kuniyuki Iwashima

author reviewer
#0 lore raw

v3 cover bpf: Add SOCK_OPS hooks for TCP AutoLOWAT.

This series introduces BPF_SOCK_OPS_RCVQ_CB, a new type of opt-in hooks for BPF SOCK_OPS prog.

The hooks can be enabled on per-socket basis by bpf_setsockopt():

  int flag = BPF_SOCK_OPS_RCVQ_CB_FLAG;

  bpf_setsockopt(sk, SOL_TCP, TCP_BPF_SOCK_OPS_CB_FLAGS,
                 &flags, sizeof(flags));

or via the SOCK_OPS specific helper:

  bpf_sock_ops_cb_flags_set(skops, BPF_SOCK_OPS_RCVQ_CB_FLAG);

Once activated, the BPF prog will be invoked with bpf_sock_ops.op set to BPF_SOCK_OPS_RCVQ_CB upon the following events:

1. TCP stack enqueues skb to sk->sk_receive_queue
2. TCP recvmsg() completes

This allows the BPF prog to dynamically adjust sk->sk_rcvlowat, suppressing unnecessary EPOLLIN wakeups until sufficient data is available in the receive queue.

This functionality, which we call "TCP AutoLOWAT", was originally developed in 2020 by Tenzin Ukyab with the help of Soheil Hassas Yeganeh, Arjun Roy, and Eric Dumazet. It has served Google RPC workloads for more than 5 years.

Combined with TCP RX zerocopy, this typically allows us to read an entire RPC frame with just a single wakeup and a single system call.

While the original implementation was specialised for our internal RPC format, this series introduces a more flexible version by leveraging BPF.

The BPF SOCK_OPS prog in the last selftest patch closely mirrors the core logic of the original implementation to provide a real-world example.

Overview:

  Patch  1      : misc cleanup for testing
  Patch  2      : Add BPF_SOCK_OPS_RCVQ_CB with no actual hooks
  Patch  3 -  5 : Add bpf helpers
  Patch  6 -  8 : Add safe guard for BPF_SOCK_OPS_RCVQ_CB
  Patch  9 - 10 : Add BPF_SOCK_OPS_RCVQ_CB hooks

Patch 11 : selftest

Changes:
v3:

    Patch  6: Check sk->sk_prot and update tp->bpf_sock_ops_cb_flags
               under sk->sk_callback_lock, and only when not flagged yet.

v2: https://lore.kernel.org/bpf/[email protected]/
Add Patch 6 - 8
Patch 2: s/BPF_SOCK_OPS_RCVLOWAT_CB/BPF_SOCK_OPS_RCVQ_CB/g Patch 3: Explain why using ____ version instead of __ version Patch 10: Add explanation of tcp_bpf_rcvlowat() placement. Patch 11: Make copy_len u64 and swap validation order for it
to pass no_alu32 test case

v1: https://lore.kernel.org/bpf/[email protected]/

Kuniyuki Iwashima (11):
selftest: bpf: Use BPF_SOCK_OPS_ALL_CB_FLAGS + 1 for bad_cb_test_rv.
bpf: tcp: Introduce BPF_SOCK_OPS_RCVQ_CB.
bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.
tcp: Split out __tcp_set_rcvlowat().
bpf: tcp: Add kfunc to adjust sk->sk_rcvlowat.
bpf: tcp: Make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive.
bpf: mptcp: Don't support BPF_SOCK_OPS_RCVQ_CB.
bpf: tcp: Reject BPF_SOCK_OPS_RCVQ_CB if receive queue is not empty.
bpf: tcp: Factorise bpf_skops_established().
bpf: tcp: Add SOCK_OPS rcvlowat hook.
selftest: bpf: Add test for BPF_SOCK_OPS_RCVQ_CB.

 include/net/tcp.h                             |  14 +
 include/uapi/linux/bpf.h                      |  18 +-
 net/core/filter.c                             |  95 ++++-
 net/ipv4/tcp.c                                |  14 +-
 net/ipv4/tcp_bpf.c                            |  12 +
 net/ipv4/tcp_fastopen.c                       |   2 +
 net/ipv4/tcp_input.c                          |  25 +-
 tools/include/uapi/linux/bpf.h                |  18 +-
 tools/testing/selftests/bpf/bpf_kfuncs.h      |   4 +
 .../selftests/bpf/prog_tests/tcp_autolowat.c  | 350 ++++++++++++++++++
 .../selftests/bpf/prog_tests/tcpbpf_user.c    |   3 +-
 .../selftests/bpf/progs/bpf_tracing_net.h     |   2 +
 .../selftests/bpf/progs/tcp_autolowat.c       | 326 ++++++++++++++++
 .../selftests/bpf/progs/test_tcpbpf_kern.c    |   3 +-
 14 files changed, 870 insertions(+), 16 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c
 create mode 100644 tools/testing/selftests/bpf/progs/tcp_autolowat.c
Signature · 1 line
2.54.0.746.g67dd491aae-goog
author reviewer
#1 lore raw

PATCH v3 1/11 selftest: bpf: Use BPF_SOCK_OPS_ALL_CB_FLAGS + 1 for bad_cb_test_rv.

Once bpf_sock_ops_cb_flags_set() supports a new flag, tcpbpf_user.c fails due to the hard-coded max value, 0x80.

Let's replace 0x80 with BPF_SOCK_OPS_ALL_CB_FLAGS + 1.

---
 tools/testing/selftests/bpf/prog_tests/tcpbpf_user.c | 3 ++-
 tools/testing/selftests/bpf/progs/test_tcpbpf_kern.c | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)
tools/testing/selftests/bpf/prog_tests/tcpbpf_user.c +2 -1
index 7e8fe1bad03f..e4849d2a2956 100644
@@ -26,7 +26,8 @@ static void verify_result(struct tcpbpf_globals *result)
 	ASSERT_EQ(result->bytes_acked, 1002, "bytes_acked");
 	ASSERT_EQ(result->data_segs_in, 1, "data_segs_in");
 	ASSERT_EQ(result->data_segs_out, 1, "data_segs_out");
-	ASSERT_EQ(result->bad_cb_test_rv, 0x80, "bad_cb_test_rv");
+	ASSERT_EQ(result->bad_cb_test_rv, BPF_SOCK_OPS_ALL_CB_FLAGS + 1,
+		  "bad_cb_test_rv");
 	ASSERT_EQ(result->good_cb_test_rv, 0, "good_cb_test_rv");
 	ASSERT_EQ(result->num_listen, 1, "num_listen");
 
tools/testing/selftests/bpf/progs/test_tcpbpf_kern.c +2 -1
index 6935f32eeb8f..e30cb1fab079 100644
@@ -92,7 +92,8 @@ int bpf_testcb(struct bpf_sock_ops *skops)
 		break;
 	case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
 		/* Test failure to set largest cb flag (assumes not defined) */
-		global.bad_cb_test_rv = bpf_sock_ops_cb_flags_set(skops, 0x80);
+		global.bad_cb_test_rv = bpf_sock_ops_cb_flags_set(skops,
+								  BPF_SOCK_OPS_ALL_CB_FLAGS + 1);
 		/* Set callback */
 		global.good_cb_test_rv = bpf_sock_ops_cb_flags_set(skops,
 						 BPF_SOCK_OPS_STATE_CB_FLAG);
Signature · 1 line
2.54.0.746.g67dd491aae-goog
#2 lore raw

Re: [PATCH v3 bpf-next 01/11] selftest: bpf: Use BPF_SOCK_OPS_ALL_CB_FLAGS + 1 for bad_cb_test_rv.

Multiple reviewers raised concerns about forward compatibility with this approach. When the test is compiled, BPF_SOCK_OPS_ALL_CB_FLAGS + 1 becomes a hardcoded value. If this compiled test runs on a…
Quoted 14 lines
tools/testing/selftests/bpf/prog_tests/tcpbpf_user.c +2 -1
index 7e8fe1bad03f..e4849d2a2956 100644
@@ -26,7 +26,8 @@ static void verify_result(struct tcpbpf_globals *result)
 	ASSERT_EQ(result->bytes_acked, 1002, "bytes_acked");
 	ASSERT_EQ(result->data_segs_in, 1, "data_segs_in");
 	ASSERT_EQ(result->data_segs_out, 1, "data_segs_out");
-	ASSERT_EQ(result->bad_cb_test_rv, 0x80, "bad_cb_test_rv");
+	ASSERT_EQ(result->bad_cb_test_rv, BPF_SOCK_OPS_ALL_CB_FLAGS + 1,
+		  "bad_cb_test_rv");
 	ASSERT_EQ(result->good_cb_test_rv, 0, "good_cb_test_rv");
 	ASSERT_EQ(result->num_listen, 1, "num_listen");
 

[ ... ]

tools/testing/selftests/bpf/progs/test_tcpbpf_kern.c int bpf_testcb(struct bpf_sock_ops *skops) · line 96

Quoted 11 lines
tools/testing/selftests/bpf/progs/test_tcpbpf_kern.c +2 -1
index 6935f32eeb8f..e4cb1fab079 100644
@@ -92,7 +92,8 @@ int bpf_testcb(struct bpf_sock_ops *skops)
 		break;
 	case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
 		/* Test failure to set largest cb flag (assumes not defined) */
-		global.bad_cb_test_rv = bpf_sock_ops_cb_flags_set(skops, 0x80);
+		global.bad_cb_test_rv = bpf_sock_ops_cb_flags_set(skops,
+								  BPF_SOCK_OPS_ALL_CB_FLAGS + 1);

Multiple reviewers raised concerns about forward compatibility with this approach. When the test is compiled, BPF_SOCK_OPS_ALL_CB_FLAGS + 1 becomes a hardcoded value. If this compiled test runs on a future kernel where that value becomes a valid flag, the helper will successfully set the flag and return 0, causing the test to fail unexpectedly.

Additionally, this assumes contiguous bitmasks. If a flag is ever deprecated or skipped, adding 1 could overlap with valid bits.

Would it be better to use a safely distant bit, such as 1 << 30, to guarantee the flag remains unsupported and the test doesn't break in the future?

Reference: https://lore.kernel.org/bpf/[email protected]/

This concern was raised by [email protected] in v1 and v2, and also flagged by [email protected] in v2. The author's v1 response indicated the test is not supposed to run on older kernels, but the reviewers are concerned about FUTURE kernels, not older ones.

---
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/26328541814

author reviewer
#3 lore raw

PATCH v3 2/11 bpf: tcp: Introduce BPF_SOCK_OPS_RCVQ_CB.

In reply to Kuniyuki Iwashima

We will introduce a new type of opt-in hooks for BPF SOCK_OPS prog.

The hooks can be enabled on per-socket basis by bpf_setsockopt():

  int flag = BPF_SOCK_OPS_RCVQ_CB_FLAG;

  bpf_setsockopt(sk, SOL_TCP, TCP_BPF_SOCK_OPS_CB_FLAGS,
                 &flags, sizeof(flags));

or via the SOCK_OPS specific helper:

  bpf_sock_ops_cb_flags_set(skops, BPF_SOCK_OPS_RCVQ_CB_FLAG);

Once activated, the BPF prog will be invoked with bpf_sock_ops.op set to BPF_SOCK_OPS_RCVQ_CB upon the following events:

1. TCP stack enqueues skb to sk->sk_receive_queue
2. TCP recvmsg() completes

This will allow the BPF prog to dynamically adjust sk->sk_rcvlowat, suppressing unnecessary EPOLLIN wakeups until sufficient data (e.g., a full RPC frame) is available in the receive queue.

Note that is_locked_tcp_sock_ops() is left unchanged not to enable bpf_setsockopt() unnecessarily, but bpf_sock_ops_cb_flags_set() is supported at BPF_SOCK_OPS_RCVQ_CB to disable by itself.

---
v2: s/BPF_SOCK_OPS_RCVLOWAT_CB/BPF_SOCK_OPS_RCVQ_CB/g

---
 include/uapi/linux/bpf.h       | 18 +++++++++++++++++-
 net/core/filter.c              |  3 ++-
 tools/include/uapi/linux/bpf.h | 18 +++++++++++++++++-
 3 files changed, 36 insertions(+), 3 deletions(-)
include/uapi/linux/bpf.h +17 -1
index aec171ccb6ef..31130e1b63ea 100644
@@ -6960,6 +6960,9 @@ struct bpf_sock_ops {
 	 *					the 3WHS.
 	 * BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB: The ACK that concludes
 	 *					the 3WHS.
+	 * BPF_SOCK_OPS_RCVQ_CB : No header included.  The payload is only
+	 *			  accessible by passing bpf_sock_ops to
+	 *			  bpf_skb_load_bytes().
 	 *
 	 * bpf_load_hdr_opt() can also be used to read a particular option.
 	 */
@@ -7031,8 +7034,16 @@ enum {
 	 * options first before the BPF program does.
 	 */
 	BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG = (1<<6),
+	/* Call bpf when TCP payload is queued to sk->sk_receive_queue
+	 * and after recvmsg().  The bpf prog will be called under
+	 * sock_ops->op == BPF_SOCK_OPS_RCVQ_CB.
+	 *
+	 * It can be used to adjust sk->sk_rcvlowat and suppress
+	 * unnecessary wakeups before sufficient data is available.
+	 */
+	BPF_SOCK_OPS_RCVQ_CB_FLAG = (1<<7),
 /* Mask of all currently supported cb flags */
-	BPF_SOCK_OPS_ALL_CB_FLAGS       = 0x7F,
+	BPF_SOCK_OPS_ALL_CB_FLAGS       = 0xFF,
 };
 
 enum {
@@ -7176,6 +7187,11 @@ enum {
 					 * sendmsg timestamp with corresponding
 					 * tskey.
 					 */
+	BPF_SOCK_OPS_RCVQ_CB,		/* Called when TCP payload is queued to
+					 * sk->sk_receive_queue and after recvmsg()
+					 * to allow adjusting sk->sk_rcvlowat and
+					 * to suppress early wakeups.
+					 */
 };
 
 /* List of TCP states. There is a build check in net/ipv4/tcp.c to detect
net/core/filter.c +2 -1
index 9590877b0714..4a50fe2cd863 100644
@@ -6002,7 +6002,8 @@ BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
 	struct sock *sk = bpf_sock->sk;
 	int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
 
-	if (!is_locked_tcp_sock_ops(bpf_sock))
+	if (!is_locked_tcp_sock_ops(bpf_sock) &&
+	    bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB)
 		return -EOPNOTSUPP;
 
 	if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
tools/include/uapi/linux/bpf.h +17 -1
index 37142e6d911a..3b8f392d8c69 100644
@@ -6960,6 +6960,9 @@ struct bpf_sock_ops {
 	 *					the 3WHS.
 	 * BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB: The ACK that concludes
 	 *					the 3WHS.
+	 * BPF_SOCK_OPS_RCVQ_CB : No header included.  The payload is only
+	 *			  accessible by passing bpf_sock_ops to
+	 *			  bpf_skb_load_bytes().
 	 *
 	 * bpf_load_hdr_opt() can also be used to read a particular option.
 	 */
@@ -7031,8 +7034,16 @@ enum {
 	 * options first before the BPF program does.
 	 */
 	BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG = (1<<6),
+	/* Call bpf when TCP payload is queued to sk->sk_receive_queue
+	 * and after recvmsg().  The bpf prog will be called under
+	 * sock_ops->op == BPF_SOCK_OPS_RCVQ_CB.
+	 *
+	 * It can be used to adjust sk->sk_rcvlowat and suppress
+	 * unnecessary wakeups before sufficient data is available.
+	 */
+	BPF_SOCK_OPS_RCVQ_CB_FLAG = (1<<7),
 /* Mask of all currently supported cb flags */
-	BPF_SOCK_OPS_ALL_CB_FLAGS       = 0x7F,
+	BPF_SOCK_OPS_ALL_CB_FLAGS       = 0xFF,
 };
 
 enum {
@@ -7176,6 +7187,11 @@ enum {
 					 * sendmsg timestamp with corresponding
 					 * tskey.
 					 */
+	BPF_SOCK_OPS_RCVQ_CB,		/* Called when TCP payload is queued to
+					 * sk->sk_receive_queue and after recvmsg()
+					 * to allow adjusting sk->sk_rcvlowat and
+					 * to suppress early wakeups.
+					 */
 };
 
 /* List of TCP states. There is a build check in net/ipv4/tcp.c to detect
Signature · 1 line
2.54.0.746.g67dd491aae-goog
author reviewer
#4 lore raw

PATCH v3 3/11 bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

In reply to Kuniyuki Iwashima

When a TCP skb is queued to sk->sk_receive_queue, BPF SOCK_OPS prog can be called with BPF_SOCK_OPS_RCVQ_CB.

In this hook, we want to parse the RPC descriptor in the skb and adjust sk->sk_rcvlowat based on the RPC frame size.

However, we cannot access payload via bpf_sock_ops.data on modern NICs with TCP header/data split on as the payload is not placed in the linear area.

Let's support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Three notes:

1) bpf_sock_ops_kern.skb will be NULL when the BPF prog is invoked from recvmsg().

2) Access to bpf_sock_ops.data will be disabled by passing 0 end_offset to bpf_skops_init_skb().

3) ____bpf_skb_load_bytes() is called directly instead of __bpf_skb_load_bytes() to allow compilers to inline it instead of generating a tail-call.

---
v2: Explain why using ____ version instead of __

---
 net/core/filter.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
net/core/filter.c +34 -0
index 4a50fe2cd863..fa8a7c7d86eb 100644
@@ -7760,6 +7760,38 @@ static const struct bpf_func_proto bpf_sk_assign_proto = {
 	.arg3_type	= ARG_ANYTHING,
 };
 
+BPF_CALL_4(bpf_sock_ops_skb_load_bytes, struct bpf_sock_ops_kern *, bpf_sock,
+	   u32, offset, void *, to, u32, len)
+{
+	int err;
+
+	if (bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB) {
+		err = -EOPNOTSUPP;
+		goto err_clear;
+	}
+
+	if (!bpf_sock->skb) {
+		err = -EPERM;
+		goto err_clear;
+	}
+
+	return ____bpf_skb_load_bytes(bpf_sock->skb, offset, to, len);
+
+err_clear:
+	memset(to, 0, len);
+	return err;
+}
+
+static const struct bpf_func_proto bpf_sock_ops_skb_load_bytes_proto = {
+	.func		= bpf_sock_ops_skb_load_bytes,
+	.gpl_only	= false,
+	.ret_type	= RET_INTEGER,
+	.arg1_type	= ARG_PTR_TO_CTX,
+	.arg2_type	= ARG_ANYTHING,
+	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
+	.arg4_type	= ARG_CONST_SIZE,
+};
+
 static const u8 *bpf_search_tcp_opt(const u8 *op, const u8 *opend,
 				    u8 search_kind, const u8 *magic,
 				    u8 magic_len, bool *eol)
@@ -8616,6 +8648,8 @@ sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
 	case BPF_FUNC_get_netns_cookie:
 		return &bpf_get_netns_cookie_sock_ops_proto;
 #ifdef CONFIG_INET
+	case BPF_FUNC_skb_load_bytes:
+		return &bpf_sock_ops_skb_load_bytes_proto;
 	case BPF_FUNC_load_hdr_opt:
 		return &bpf_sock_ops_load_hdr_opt_proto;
 	case BPF_FUNC_store_hdr_opt:
Signature · 1 line
2.54.0.746.g67dd491aae-goog
#5 lore raw

Re: [PATCH v3 bpf-next 03/11] bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Quoted 17 lines · Kuniyuki Iwashima

When a TCP skb is queued to sk->sk_receive_queue, BPF SOCK_OPS prog can be called with BPF_SOCK_OPS_RCVQ_CB.

In this hook, we want to parse the RPC descriptor in the skb and adjust sk->sk_rcvlowat based on the RPC frame size.

However, we cannot access payload via bpf_sock_ops.data on modern NICs with TCP header/data split on as the payload is not placed in the linear area.

Let's support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Three notes:

1) bpf_sock_ops_kern.skb will be NULL when the BPF prog is invoked from recvmsg().

Quoted 6 lines

2) Access to bpf_sock_ops.data will be disabled by passing 0 end_offset to bpf_skops_init_skb().

3) ____bpf_skb_load_bytes() is called directly instead of __bpf_skb_load_bytes() to allow compilers to inline it instead of generating a tail-call.

Some observations below.

Quoted 13 lines

---
v2: Explain why using ____ version instead of __

---
 net/core/filter.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
net/core/filter.c +0 -0
index 4a50fe2cd863..fa8a7c7d86eb 100644

net/core/filter.c static const struct bpf_func_proto bpf_sk_assign_proto = { · line 7768

Quoted 9 lines
net/core/filter.c +6 -0
@@ -7760,6 +7760,38 @@ static const struct bpf_func_proto bpf_sk_assign_proto = {
 	.arg3_type	= ARG_ANYTHING,
 };
 
+BPF_CALL_4(bpf_sock_ops_skb_load_bytes, struct bpf_sock_ops_kern *, bpf_sock,
+	   u32, offset, void *, to, u32, len)
+{
+	int err;
+
+	if (bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB) {

bpf_dynptr_from_skb() and bpf_dynptr_slice() kfunc could also be considered. One less bpf_sock->op check in filter.c to maintain and could also avoid a data copy. There is a bpf_cast_to_kern_ctx() to get to a trusted skops_kern pointer but this will need changes in verifier.c to get to skops_kern->skb (e.g. in type_is_trusted_or_null) and this is the tradeoff.

If this new rcvq callback is added to the 'bpf_tcp_ops' proposal [1], all this will go away. 'struct sk_buff *skb' can be directly passed to an ops of the 'bpf_tcp_ops'. Supporting '*skb' in a struct_ops has already been done in the bpf_qdisc.

[1]: https://lore.kernel.org/bpf/[email protected]/

author reviewer
#6 lore raw

Re: [PATCH v3 bpf-next 03/11] bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Quoted 44 lines · Martin KaFai Lau
Quoted 17 lines · Kuniyuki Iwashima

When a TCP skb is queued to sk->sk_receive_queue, BPF SOCK_OPS prog can be called with BPF_SOCK_OPS_RCVQ_CB.

In this hook, we want to parse the RPC descriptor in the skb and adjust sk->sk_rcvlowat based on the RPC frame size.

However, we cannot access payload via bpf_sock_ops.data on modern NICs with TCP header/data split on as the payload is not placed in the linear area.

Let's support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Three notes:

1) bpf_sock_ops_kern.skb will be NULL when the BPF prog is invoked from recvmsg().

Quoted 6 lines

2) Access to bpf_sock_ops.data will be disabled by passing 0 end_offset to bpf_skops_init_skb().

3) ____bpf_skb_load_bytes() is called directly instead of __bpf_skb_load_bytes() to allow compilers to inline it instead of generating a tail-call.

Some observations below.

Quoted 16 lines

---
v2: Explain why using ____ version instead of __

---
 net/core/filter.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
net/core/filter.c +0 -0
index 4a50fe2cd863..fa8a7c7d86eb 100644
@@ -7760,6 +7760,38 @@ static const struct bpf_func_proto bpf_sk_assign_proto = {
      .arg3_type      = ARG_ANYTHING,
 };
 
Quoted 12 lines

net/core/filter.c static const struct bpf_func_proto bpf_sk_assign_proto = { · line 7768

Quoted 6 lines
net/core/filter.c +6 -0
+BPF_CALL_4(bpf_sock_ops_skb_load_bytes, struct bpf_sock_ops_kern *, bpf_sock,
+        u32, offset, void *, to, u32, len)
+{
+     int err;
+
+     if (bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB) {

bpf_dynptr_from_skb() and bpf_dynptr_slice() kfunc could also be considered. One less bpf_sock->op check in filter.c to maintain and could also avoid a data copy. There is a bpf_cast_to_kern_ctx() to get to a trusted skops_kern pointer but this will need changes in verifier.c to get to skops_kern->skb (e.g. in type_is_trusted_or_null) and this is the tradeoff.

Maybe a dumb question, but does it add extra cost (extra dynptr function call?) if data overlaps two frags, or can dynptr handle it seamlessly with a single bpf_dynptr_slice() ?

In our case, the data copy is ~16 bytes, so the cost will not be a big problem I think.

Quoted 7 lines

If this new rcvq callback is added to the 'bpf_tcp_ops' proposal [1], all this will go away. 'struct sk_buff *skb' can be directly passed to an ops of the 'bpf_tcp_ops'. Supporting '*skb' in a struct_ops has already been done in the bpf_qdisc.

[1]: https://lore.kernel.org/bpf/[email protected]/

Oh I missed the series, the struct_ops conversion looks nice ! Since this work isn't urgent, I can wait for your series if mine churns it.

Jason's series is adding a new op, and I guess this can be integrated too ?
https://lore.kernel.org/bpf/[email protected]/

#7 lore raw

Re: [PATCH v3 bpf-next 03/11] bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Quoted 58 lines · Kuniyuki Iwashima
Quoted 44 lines · Martin KaFai Lau
Quoted 17 lines · Kuniyuki Iwashima

When a TCP skb is queued to sk->sk_receive_queue, BPF SOCK_OPS prog can be called with BPF_SOCK_OPS_RCVQ_CB.

In this hook, we want to parse the RPC descriptor in the skb and adjust sk->sk_rcvlowat based on the RPC frame size.

However, we cannot access payload via bpf_sock_ops.data on modern NICs with TCP header/data split on as the payload is not placed in the linear area.

Let's support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Three notes:

1) bpf_sock_ops_kern.skb will be NULL when the BPF prog is invoked from recvmsg().

Quoted 6 lines

2) Access to bpf_sock_ops.data will be disabled by passing 0 end_offset to bpf_skops_init_skb().

3) ____bpf_skb_load_bytes() is called directly instead of __bpf_skb_load_bytes() to allow compilers to inline it instead of generating a tail-call.

Some observations below.

Quoted 16 lines

---
v2: Explain why using ____ version instead of __

---
 net/core/filter.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
net/core/filter.c +0 -0
index 4a50fe2cd863..fa8a7c7d86eb 100644
@@ -7760,6 +7760,38 @@ static const struct bpf_func_proto bpf_sk_assign_proto = {
      .arg3_type      = ARG_ANYTHING,
 };
 
Quoted 12 lines

net/core/filter.c static const struct bpf_func_proto bpf_sk_assign_proto = { · line 7768

Quoted 6 lines
net/core/filter.c +6 -0
+BPF_CALL_4(bpf_sock_ops_skb_load_bytes, struct bpf_sock_ops_kern *, bpf_sock,
+        u32, offset, void *, to, u32, len)
+{
+     int err;
+
+     if (bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB) {

bpf_dynptr_from_skb() and bpf_dynptr_slice() kfunc could also be considered. One less bpf_sock->op check in filter.c to maintain and could also avoid a data copy. There is a bpf_cast_to_kern_ctx() to get to a trusted skops_kern pointer but this will need changes in verifier.c to get to skops_kern->skb (e.g. in type_is_trusted_or_null) and this is the tradeoff.

Quoted 3 lines

Maybe a dumb question, but does it add extra cost (extra dynptr function call?) if data overlaps two frags, or can dynptr handle it seamlessly with a single bpf_dynptr_slice() ?

Right, there is an extra bpf_dynptr_from_skb(). I don't think we have benchmarked it.

If I read it correctly, unlike bpf_xdp_pointer, the skb_header_pointer will still copy even if the data is in one frag. It works well if the data is in the headlen and the worst case is to copy, which is the same as load_bytes.

It is a readonly use case. Maybe the bpf prog can directly read the frag. Regardless, it is useful to have a kfunc/helper to read it.

Quoted 13 lines

In our case, the data copy is ~16 bytes, so the cost will not be a big problem I think.

Quoted 7 lines

If this new rcvq callback is added to the 'bpf_tcp_ops' proposal [1], all this will go away. 'struct sk_buff *skb' can be directly passed to an ops of the 'bpf_tcp_ops'. Supporting '*skb' in a struct_ops has already been done in the bpf_qdisc.

[1]: https://lore.kernel.org/bpf/[email protected]/

Quoted 7 lines

Oh I missed the series, the struct_ops conversion looks nice ! Since this work isn't urgent, I can wait for your series if mine churns it.

Jason's series is adding a new op, and I guess this can be integrated too ?
https://lore.kernel.org/bpf/[email protected]/

imo, a new sock_ops cb should be added as an ops in struct_ops. For example, in patch 4 of that series, bpf_skops_rx_timestamping assigns u64 to 'u32 args[4]', which is adding tech debt to the current sock_ops interface. For the timestamping case, it could be a separate ops for the 'struct sock' instead of 'struct tcp_sock' because it should
at least work for both TCP and UDP.

#8 lore raw

Re: [PATCH v3 bpf-next 03/11] bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Quoted 96 lines · Martin KaFai Lau
Quoted 58 lines · Kuniyuki Iwashima
Quoted 44 lines · Martin KaFai Lau
Quoted 17 lines · Kuniyuki Iwashima

When a TCP skb is queued to sk->sk_receive_queue, BPF SOCK_OPS prog can be called with BPF_SOCK_OPS_RCVQ_CB.

In this hook, we want to parse the RPC descriptor in the skb and adjust sk->sk_rcvlowat based on the RPC frame size.

However, we cannot access payload via bpf_sock_ops.data on modern NICs with TCP header/data split on as the payload is not placed in the linear area.

Let's support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Three notes:

1) bpf_sock_ops_kern.skb will be NULL when the BPF prog is invoked from recvmsg().

Quoted 6 lines

2) Access to bpf_sock_ops.data will be disabled by passing 0 end_offset to bpf_skops_init_skb().

3) ____bpf_skb_load_bytes() is called directly instead of __bpf_skb_load_bytes() to allow compilers to inline it instead of generating a tail-call.

Some observations below.

Quoted 16 lines

---
v2: Explain why using ____ version instead of __

---
 net/core/filter.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
net/core/filter.c +0 -0
index 4a50fe2cd863..fa8a7c7d86eb 100644
@@ -7760,6 +7760,38 @@ static const struct bpf_func_proto bpf_sk_assign_proto = {
      .arg3_type      = ARG_ANYTHING,
 };
 
Quoted 12 lines

net/core/filter.c static const struct bpf_func_proto bpf_sk_assign_proto = { · line 7768

Quoted 6 lines
net/core/filter.c +6 -0
+BPF_CALL_4(bpf_sock_ops_skb_load_bytes, struct bpf_sock_ops_kern *, bpf_sock,
+        u32, offset, void *, to, u32, len)
+{
+     int err;
+
+     if (bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB) {

bpf_dynptr_from_skb() and bpf_dynptr_slice() kfunc could also be considered. One less bpf_sock->op check in filter.c to maintain and could also avoid a data copy. There is a bpf_cast_to_kern_ctx() to get to a trusted skops_kern pointer but this will need changes in verifier.c to get to skops_kern->skb (e.g. in type_is_trusted_or_null) and this is the tradeoff.

Quoted 3 lines

Maybe a dumb question, but does it add extra cost (extra dynptr function call?) if data overlaps two frags, or can dynptr handle it seamlessly with a single bpf_dynptr_slice() ?

Right, there is an extra bpf_dynptr_from_skb(). I don't think we have benchmarked it.

If I read it correctly, unlike bpf_xdp_pointer, the skb_header_pointer will still copy even if the data is in one frag. It works well if the data is in the headlen and the worst case is to copy, which is the same as load_bytes.

It is a readonly use case. Maybe the bpf prog can directly read the frag. Regardless, it is useful to have a kfunc/helper to read it.

Quoted 13 lines

In our case, the data copy is ~16 bytes, so the cost will not be a big problem I think.

Quoted 7 lines

If this new rcvq callback is added to the 'bpf_tcp_ops' proposal [1], all this will go away. 'struct sk_buff *skb' can be directly passed to an ops of the 'bpf_tcp_ops'. Supporting '*skb' in a struct_ops has already been done in the bpf_qdisc.

[1]: https://lore.kernel.org/bpf/[email protected]/

Quoted 7 lines

Oh I missed the series, the struct_ops conversion looks nice ! Since this work isn't urgent, I can wait for your series if mine churns it.

Jason's series is adding a new op, and I guess this can be integrated too ?
https://lore.kernel.org/bpf/[email protected]/

Quoted 6 lines

imo, a new sock_ops cb should be added as an ops in struct_ops. For example, in patch 4 of that series, bpf_skops_rx_timestamping assigns u64 to 'u32 args[4]', which is adding tech debt to the current sock_ops interface. For the timestamping case, it could be a separate ops for the 'struct sock' instead of 'struct tcp_sock' because it should
at least work for both TCP and UDP.

Sorry, I don't get it. What is the tech debt in this? And bpf_skops_rx_timestamping() only outputs the timestamps, which has nothing to do with either 'sock' or 'tcp_sock'.

Could you show me what to do next? Thanks in advance. It sounds like the tx side of bpf timestamping should be adjusted accordingly?

Thanks,
Jason

#9 lore raw

Re: [PATCH v3 bpf-next 03/11] bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Quoted 104 lines · Jason Xing
Quoted 96 lines · Martin KaFai Lau
Quoted 58 lines · Kuniyuki Iwashima
Quoted 44 lines · Martin KaFai Lau
Quoted 17 lines · Kuniyuki Iwashima

When a TCP skb is queued to sk->sk_receive_queue, BPF SOCK_OPS prog can be called with BPF_SOCK_OPS_RCVQ_CB.

In this hook, we want to parse the RPC descriptor in the skb and adjust sk->sk_rcvlowat based on the RPC frame size.

However, we cannot access payload via bpf_sock_ops.data on modern NICs with TCP header/data split on as the payload is not placed in the linear area.

Let's support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Three notes:

1) bpf_sock_ops_kern.skb will be NULL when the BPF prog is invoked from recvmsg().

Quoted 6 lines

2) Access to bpf_sock_ops.data will be disabled by passing 0 end_offset to bpf_skops_init_skb().

3) ____bpf_skb_load_bytes() is called directly instead of __bpf_skb_load_bytes() to allow compilers to inline it instead of generating a tail-call.

Some observations below.

Quoted 16 lines

---
v2: Explain why using ____ version instead of __

---
 net/core/filter.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
net/core/filter.c +0 -0
index 4a50fe2cd863..fa8a7c7d86eb 100644
@@ -7760,6 +7760,38 @@ static const struct bpf_func_proto bpf_sk_assign_proto = {
      .arg3_type      = ARG_ANYTHING,
 };
 
Quoted 12 lines

net/core/filter.c static const struct bpf_func_proto bpf_sk_assign_proto = { · line 7768

Quoted 6 lines
net/core/filter.c +6 -0
+BPF_CALL_4(bpf_sock_ops_skb_load_bytes, struct bpf_sock_ops_kern *, bpf_sock,
+        u32, offset, void *, to, u32, len)
+{
+     int err;
+
+     if (bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB) {

bpf_dynptr_from_skb() and bpf_dynptr_slice() kfunc could also be considered. One less bpf_sock->op check in filter.c to maintain and could also avoid a data copy. There is a bpf_cast_to_kern_ctx() to get to a trusted skops_kern pointer but this will need changes in verifier.c to get to skops_kern->skb (e.g. in type_is_trusted_or_null) and this is the tradeoff.

Quoted 3 lines

Maybe a dumb question, but does it add extra cost (extra dynptr function call?) if data overlaps two frags, or can dynptr handle it seamlessly with a single bpf_dynptr_slice() ?

Right, there is an extra bpf_dynptr_from_skb(). I don't think we have benchmarked it.

If I read it correctly, unlike bpf_xdp_pointer, the skb_header_pointer will still copy even if the data is in one frag. It works well if the data is in the headlen and the worst case is to copy, which is the same as load_bytes.

It is a readonly use case. Maybe the bpf prog can directly read the frag. Regardless, it is useful to have a kfunc/helper to read it.

Quoted 13 lines

In our case, the data copy is ~16 bytes, so the cost will not be a big problem I think.

Quoted 7 lines

If this new rcvq callback is added to the 'bpf_tcp_ops' proposal [1], all this will go away. 'struct sk_buff *skb' can be directly passed to an ops of the 'bpf_tcp_ops'. Supporting '*skb' in a struct_ops has already been done in the bpf_qdisc.

[1]: https://lore.kernel.org/bpf/[email protected]/

Quoted 7 lines

Oh I missed the series, the struct_ops conversion looks nice ! Since this work isn't urgent, I can wait for your series if mine churns it.

Jason's series is adding a new op, and I guess this can be integrated too ?
https://lore.kernel.org/bpf/[email protected]/

Quoted 6 lines

imo, a new sock_ops cb should be added as an ops in struct_ops. For example, in patch 4 of that series, bpf_skops_rx_timestamping assigns u64 to 'u32 args[4]', which is adding tech debt to the current sock_ops interface. For the timestamping case, it could be a separate ops for the 'struct sock' instead of 'struct tcp_sock' because it should
at least work for both TCP and UDP.

Quoted 3 lines

Sorry, I don't get it. What is the tech debt in this? And bpf_skops_rx_timestamping() only outputs the timestamps, which has nothing to do with either 'sock' or 'tcp_sock'.

Did I say the tech debt is in bpf_skops_rx_timestamping? I said the tech debt of the bpf_sock_ops[_kern] interface. Besides always memzero the whole &sockops, the way that the bpf prog needs to get a u64 timestamp from u32 is not thrilling in 2026. args[4] is also not reliable when the earlier cgroup bpf prog writes to replylong. We had already hit some of these in our rx net timestamping discussion a few years ago. I suggest you go back and revisit.

Quoted 3 lines

Could you show me what to do next? Thanks in advance. It sounds like the tx side of bpf timestamping should be adjusted accordingly?

imo, the bpf_tcp_ops can land first. and then add net timestamping ops (existing tx and the new rx) in bpf_sock_ops.

#10 lore raw

Re: [PATCH v3 bpf-next 03/11] bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Quoted 36 lines · Martin KaFai Lau
Quoted 22 lines
Quoted 15 lines
Quoted 7 lines
Quoted 6 lines

If this new rcvq callback is added to the 'bpf_tcp_ops' proposal [1], all this will go away. 'struct sk_buff *skb' can be directly passed to an ops of the 'bpf_tcp_ops'. Supporting '*skb' in a struct_ops has already been done in the bpf_qdisc.

[1]: https://lore.kernel.org/bpf/[email protected]/

Quoted 7 lines

Oh I missed the series, the struct_ops conversion looks nice ! Since this work isn't urgent, I can wait for your series if mine churns it.

Jason's series is adding a new op, and I guess this can be integrated too ?
https://lore.kernel.org/bpf/[email protected]/

Quoted 6 lines

imo, a new sock_ops cb should be added as an ops in struct_ops. For example, in patch 4 of that series, bpf_skops_rx_timestamping assigns u64 to 'u32 args[4]', which is adding tech debt to the current sock_ops interface. For the timestamping case, it could be a separate ops for the 'struct sock' instead of 'struct tcp_sock' because it should
at least work for both TCP and UDP.

Quoted 3 lines

Sorry, I don't get it. What is the tech debt in this? And bpf_skops_rx_timestamping() only outputs the timestamps, which has nothing to do with either 'sock' or 'tcp_sock'.

Did I say the tech debt is in bpf_skops_rx_timestamping? I said the tech debt of the bpf_sock_ops[_kern] interface. Besides always memzero the whole &sockops, the way that the bpf prog needs to get a u64 timestamp from u32 is not thrilling in 2026. args[4] is also not reliable when the earlier cgroup bpf prog writes to replylong. We had already hit some of these in our rx net timestamping discussion a few years ago. I suggest you go back and revisit.

Quoted 1 line
Quoted 5 lines
Quoted 2 lines

Could you show me what to do next? Thanks in advance. It sounds like the tx side of bpf timestamping should be adjusted accordingly?

imo, the bpf_tcp_ops can land first. and then add net timestamping ops (existing tx and the new rx) in bpf_sock_ops.

To be clear, for bpf_sock_ops, I meant a struct_ops named bpf_sock_ops (or another better name).

author reviewer
#11 lore raw

Re: [PATCH v3 bpf-next 03/11] bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

In reply to Martin KaFai Lau
Quoted 110 lines · Martin KaFai Lau
Quoted 104 lines · Jason Xing
Quoted 96 lines · Martin KaFai Lau
Quoted 58 lines · Kuniyuki Iwashima
Quoted 44 lines · Martin KaFai Lau
Quoted 17 lines · Kuniyuki Iwashima

When a TCP skb is queued to sk->sk_receive_queue, BPF SOCK_OPS prog can be called with BPF_SOCK_OPS_RCVQ_CB.

In this hook, we want to parse the RPC descriptor in the skb and adjust sk->sk_rcvlowat based on the RPC frame size.

However, we cannot access payload via bpf_sock_ops.data on modern NICs with TCP header/data split on as the payload is not placed in the linear area.

Let's support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Three notes:

1) bpf_sock_ops_kern.skb will be NULL when the BPF prog is invoked from recvmsg().

Quoted 6 lines

2) Access to bpf_sock_ops.data will be disabled by passing 0 end_offset to bpf_skops_init_skb().

3) ____bpf_skb_load_bytes() is called directly instead of __bpf_skb_load_bytes() to allow compilers to inline it instead of generating a tail-call.

Some observations below.

Quoted 16 lines

---
v2: Explain why using ____ version instead of __

---
 net/core/filter.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
net/core/filter.c +0 -0
index 4a50fe2cd863..fa8a7c7d86eb 100644
@@ -7760,6 +7760,38 @@ static const struct bpf_func_proto bpf_sk_assign_proto = {
      .arg3_type      = ARG_ANYTHING,
 };
 
Quoted 12 lines

net/core/filter.c static const struct bpf_func_proto bpf_sk_assign_proto = { · line 7768

Quoted 6 lines
net/core/filter.c +6 -0
+BPF_CALL_4(bpf_sock_ops_skb_load_bytes, struct bpf_sock_ops_kern *, bpf_sock,
+        u32, offset, void *, to, u32, len)
+{
+     int err;
+
+     if (bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB) {

bpf_dynptr_from_skb() and bpf_dynptr_slice() kfunc could also be considered. One less bpf_sock->op check in filter.c to maintain and could also avoid a data copy. There is a bpf_cast_to_kern_ctx() to get to a trusted skops_kern pointer but this will need changes in verifier.c to get to skops_kern->skb (e.g. in type_is_trusted_or_null) and this is the tradeoff.

Quoted 3 lines

Maybe a dumb question, but does it add extra cost (extra dynptr function call?) if data overlaps two frags, or can dynptr handle it seamlessly with a single bpf_dynptr_slice() ?

Right, there is an extra bpf_dynptr_from_skb(). I don't think we have benchmarked it.

If I read it correctly, unlike bpf_xdp_pointer, the skb_header_pointer will still copy even if the data is in one frag. It works well if the data is in the headlen and the worst case is to copy, which is the same as load_bytes.

It is a readonly use case. Maybe the bpf prog can directly read the frag. Regardless, it is useful to have a kfunc/helper to read it.

Quoted 13 lines

In our case, the data copy is ~16 bytes, so the cost will not be a big problem I think.

Quoted 7 lines

If this new rcvq callback is added to the 'bpf_tcp_ops' proposal [1], all this will go away. 'struct sk_buff *skb' can be directly passed to an ops of the 'bpf_tcp_ops'. Supporting '*skb' in a struct_ops has already been done in the bpf_qdisc.

[1]: https://lore.kernel.org/bpf/[email protected]/

Quoted 7 lines

Oh I missed the series, the struct_ops conversion looks nice ! Since this work isn't urgent, I can wait for your series if mine churns it.

Jason's series is adding a new op, and I guess this can be integrated too ?
https://lore.kernel.org/bpf/[email protected]/

Quoted 6 lines

imo, a new sock_ops cb should be added as an ops in struct_ops. For example, in patch 4 of that series, bpf_skops_rx_timestamping assigns u64 to 'u32 args[4]', which is adding tech debt to the current sock_ops interface. For the timestamping case, it could be a separate ops for the 'struct sock' instead of 'struct tcp_sock' because it should
at least work for both TCP and UDP.

Quoted 3 lines

Sorry, I don't get it. What is the tech debt in this? And bpf_skops_rx_timestamping() only outputs the timestamps, which has nothing to do with either 'sock' or 'tcp_sock'.

Quoted 8 lines

Did I say the tech debt is in bpf_skops_rx_timestamping? I said the tech debt of the bpf_sock_ops[_kern] interface. Besides always memzero the whole &sockops, the way that the bpf prog needs to get a u64 timestamp from u32 is not thrilling in 2026. args[4] is also not reliable when the earlier cgroup bpf prog writes to replylong. We had already hit some of these in our rx net timestamping discussion a few years ago. I suggest you go back and revisit.

I remember the tech debt was mentioned when I implemented BPF SYN proxy in SOCK_OPS too.

Quoted 7 lines
Quoted 4 lines

Could you show me what to do next? Thanks in advance. It sounds like the tx side of bpf timestamping should be adjusted accordingly?

imo, the bpf_tcp_ops can land first. and then add net timestamping ops (existing tx and the new rx) in bpf_sock_ops.

Sounds good to me. I'll rebase TCP AutoLOWAT feature on top of the struct_ops series.

#12 lore raw

Re: [PATCH v3 bpf-next 03/11] bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Quoted 8 lines · Kuniyuki Iwashima
Quoted 5 lines
Quoted 2 lines

Could you show me what to do next? Thanks in advance. It sounds like the tx side of bpf timestamping should be adjusted accordingly?

imo, the bpf_tcp_ops can land first. and then add net timestamping ops (existing tx and the new rx) in bpf_sock_ops.

Sounds good to me. I'll rebase TCP AutoLOWAT feature on top of the struct_ops series.

Thanks.

The ops in bpf_tcp_ops do not have a skb arg yet.
A few lines similar to bpf_qdisc_is_valid_access() in bpf_qdisc.c are needed. I recall it works around btf_ctx_access(). We can probably clean it up in the future, which should be generic enough for all struct_ops taking a skb.

I believe the "if (prog->aux->st_ops != &bpf_Qdisc_ops)" check in bpf_qdisc_kfunc_filter() may get in the way. bpf_dynptr_from_skb kfunc should not be limited to the bpf_qdisc struct_ops. I think the net subsystem should allow bpf_dynptr_from_skb as the basic kfunc for all struct_ops programs as long as skb is a trusted pointer. You should be able to work around it for now by tweaking bpf_qdisc_kfunc_filter. The struct_ops program will only have read-only access to the skb through bpf_dynptr_*() kfuncs.

The struct_ops series will need to address some issues (excluding the pre-existing ones in cgroup.c) pointed out by Sashiko. Amery is kind enough to help me figure out how to resolve it and then respin.

#13 lore raw

Re: [PATCH v3 bpf-next 03/11] bpf: tcp: Support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

In reply to Martin KaFai Lau
Quoted 110 lines · Martin KaFai Lau
Quoted 104 lines · Jason Xing
Quoted 96 lines · Martin KaFai Lau
Quoted 58 lines · Kuniyuki Iwashima
Quoted 44 lines · Martin KaFai Lau
Quoted 17 lines · Kuniyuki Iwashima

When a TCP skb is queued to sk->sk_receive_queue, BPF SOCK_OPS prog can be called with BPF_SOCK_OPS_RCVQ_CB.

In this hook, we want to parse the RPC descriptor in the skb and adjust sk->sk_rcvlowat based on the RPC frame size.

However, we cannot access payload via bpf_sock_ops.data on modern NICs with TCP header/data split on as the payload is not placed in the linear area.

Let's support bpf_skb_load_bytes() for BPF_SOCK_OPS_RCVQ_CB.

Three notes:

1) bpf_sock_ops_kern.skb will be NULL when the BPF prog is invoked from recvmsg().

Quoted 6 lines

2) Access to bpf_sock_ops.data will be disabled by passing 0 end_offset to bpf_skops_init_skb().

3) ____bpf_skb_load_bytes() is called directly instead of __bpf_skb_load_bytes() to allow compilers to inline it instead of generating a tail-call.

Some observations below.

Quoted 16 lines

---
v2: Explain why using ____ version instead of __

---
 net/core/filter.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
net/core/filter.c +0 -0
index 4a50fe2cd863..fa8a7c7d86eb 100644
@@ -7760,6 +7760,38 @@ static const struct bpf_func_proto bpf_sk_assign_proto = {
      .arg3_type      = ARG_ANYTHING,
 };
 
Quoted 12 lines

net/core/filter.c static const struct bpf_func_proto bpf_sk_assign_proto = { · line 7768

Quoted 6 lines
net/core/filter.c +6 -0
+BPF_CALL_4(bpf_sock_ops_skb_load_bytes, struct bpf_sock_ops_kern *, bpf_sock,
+        u32, offset, void *, to, u32, len)
+{
+     int err;
+
+     if (bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB) {

bpf_dynptr_from_skb() and bpf_dynptr_slice() kfunc could also be considered. One less bpf_sock->op check in filter.c to maintain and could also avoid a data copy. There is a bpf_cast_to_kern_ctx() to get to a trusted skops_kern pointer but this will need changes in verifier.c to get to skops_kern->skb (e.g. in type_is_trusted_or_null) and this is the tradeoff.

Quoted 3 lines

Maybe a dumb question, but does it add extra cost (extra dynptr function call?) if data overlaps two frags, or can dynptr handle it seamlessly with a single bpf_dynptr_slice() ?

Right, there is an extra bpf_dynptr_from_skb(). I don't think we have benchmarked it.

If I read it correctly, unlike bpf_xdp_pointer, the skb_header_pointer will still copy even if the data is in one frag. It works well if the data is in the headlen and the worst case is to copy, which is the same as load_bytes.

It is a readonly use case. Maybe the bpf prog can directly read the frag. Regardless, it is useful to have a kfunc/helper to read it.

Quoted 13 lines

In our case, the data copy is ~16 bytes, so the cost will not be a big problem I think.

Quoted 7 lines

If this new rcvq callback is added to the 'bpf_tcp_ops' proposal [1], all this will go away. 'struct sk_buff *skb' can be directly passed to an ops of the 'bpf_tcp_ops'. Supporting '*skb' in a struct_ops has already been done in the bpf_qdisc.

[1]: https://lore.kernel.org/bpf/[email protected]/

Quoted 7 lines

Oh I missed the series, the struct_ops conversion looks nice ! Since this work isn't urgent, I can wait for your series if mine churns it.

Jason's series is adding a new op, and I guess this can be integrated too ?
https://lore.kernel.org/bpf/[email protected]/

Quoted 6 lines

imo, a new sock_ops cb should be added as an ops in struct_ops. For example, in patch 4 of that series, bpf_skops_rx_timestamping assigns u64 to 'u32 args[4]', which is adding tech debt to the current sock_ops interface. For the timestamping case, it could be a separate ops for the 'struct sock' instead of 'struct tcp_sock' because it should
at least work for both TCP and UDP.

Quoted 3 lines

Sorry, I don't get it. What is the tech debt in this? And bpf_skops_rx_timestamping() only outputs the timestamps, which has nothing to do with either 'sock' or 'tcp_sock'.

Quoted 8 lines

Did I say the tech debt is in bpf_skops_rx_timestamping? I said the tech debt of the bpf_sock_ops[_kern] interface. Besides always memzero the whole &sockops, the way that the bpf prog needs to get a u64 timestamp from u32 is not thrilling in 2026. args[4] is also not reliable when the earlier cgroup bpf prog writes to replylong. We had already hit some of these in our rx net timestamping discussion a few years ago. I suggest you go back and revisit.

Actually I revisited some historical threads and didn't notice something like this probably because of too much information there. Anyway, thanks for your information.

Quoted 7 lines
Quoted 4 lines

Could you show me what to do next? Thanks in advance. It sounds like the tx side of bpf timestamping should be adjusted accordingly?

imo, the bpf_tcp_ops can land first. and then add net timestamping ops (existing tx and the new rx) in bpf_sock_ops.

I'll rework after your series gets landed.

Thanks,
Jason

author reviewer
#14 lore raw

PATCH v3 4/11 tcp: Split out __tcp_set_rcvlowat().

In reply to Kuniyuki Iwashima

We will add a kfunc for BPF_SOCK_OPS_RCVQ_CB hooks to adjust sk->sk_rcvlowat.

These hooks will be triggered when:

1. TCP stack enqueues skb to sk->sk_receive_queue
2. TCP recvmsg() completes

In the enqueue path, tcp_data_ready() is always called after the hooks in tcp_queue_rcv() and tcp_ofo_queue().

If tcp_set_rcvlowat() were used as is, tcp_data_ready() could be called twice for the same skb, which is redundant and also confusing.

Let's split out __tcp_set_rcvlowat() and add a flag to control wakeup behaviour.

---
 include/net/tcp.h |  1 +
 net/ipv4/tcp.c    | 12 +++++++++---
 2 files changed, 10 insertions(+), 3 deletions(-)
include/net/tcp.h +1 -0
index ecbadcb3a744..c6a6853909c4 100644
@@ -515,6 +515,7 @@ void tcp_set_keepalive(struct sock *sk, int val);
 void tcp_syn_ack_timeout(const struct request_sock *req);
 int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
 		int flags);
+int __tcp_set_rcvlowat(struct sock *sk, int val, bool wakeup);
 int tcp_set_rcvlowat(struct sock *sk, int val);
 void tcp_set_rcvbuf(struct sock *sk, int val);
 int tcp_set_window_clamp(struct sock *sk, int val);
net/ipv4/tcp.c +9 -3
index 432fa28e47d4..3afeb69a547a 100644
@@ -1829,8 +1829,7 @@ int tcp_peek_len(struct socket *sock)
 	return tcp_inq(sock->sk);
 }
 
-/* Make sure sk_rcvbuf is big enough to satisfy SO_RCVLOWAT hint */
-int tcp_set_rcvlowat(struct sock *sk, int val)
+int __tcp_set_rcvlowat(struct sock *sk, int val, bool wakeup)
 {
 	struct tcp_sock *tp = tcp_sk(sk);
 	int space, cap;
@@ -1843,7 +1842,8 @@ int tcp_set_rcvlowat(struct sock *sk, int val)
 	WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
 
 	/* Check if we need to signal EPOLLIN right now */
-	tcp_data_ready(sk);
+	if (wakeup)
+		tcp_data_ready(sk);
 
 	if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
 		return 0;
@@ -1858,6 +1858,12 @@ int tcp_set_rcvlowat(struct sock *sk, int val)
 	return 0;
 }
 
+/* Make sure sk_rcvbuf is big enough to satisfy SO_RCVLOWAT hint */
+int tcp_set_rcvlowat(struct sock *sk, int val)
+{
+	return __tcp_set_rcvlowat(sk, val, true);
+}
+
 void tcp_set_rcvbuf(struct sock *sk, int val)
 {
 	tcp_set_window_clamp(sk, tcp_win_from_space(sk, val));
Signature · 1 line
2.54.0.746.g67dd491aae-goog
author reviewer
#15 lore raw

PATCH v3 5/11 bpf: tcp: Add kfunc to adjust sk->sk_rcvlowat.

In reply to Kuniyuki Iwashima

We will invoke BPF SOCK_OPS prog with BPF_SOCK_OPS_RCVQ_CB to adjust sk->sk_rcvlowat when

1. TCP stack enqueues skb to sk->sk_receive_queue
2. TCP recvmsg() completes

Let's provide a kfunc to set sk->sk_rcvlowat.

Negative values are clamped to INT_MAX, consistent with SO_RCVLOWAT.

The wakeup flag is determined based on bpf_sock_ops_kern.skb:

* For the enqueue hook, skb is always non-NULL, and wakeup is set to false because

* tcp_data_ready() is always called after the hooks in tcp_queue_rcv() and tcp_ofo_queue().

* when tcp_fastopen_add_skb() is called for TFO SYN, the socket is not yet accept()ed, and when called for TFO SYN+ACK, the socket is woken up by sk->sk_state_change() anyway.

* For the recvmsg() hook, skb is always NULL, and wakeup is set to true because tcp_data_ready() is not called in the path.

An alternative would be to support bpf_setsockopt() by adding BPF_SOCK_OPS_RCVQ_CB to is_locked_tcp_sock_ops().

However, that approach involves excessive conditionals and an unnecessary memcpy(), costs we do not want to pay for every skb in the TCP fast path.

---
 net/core/filter.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
net/core/filter.c +17 -0
index fa8a7c7d86eb..3608036632a8 100644
@@ -12388,6 +12388,22 @@ __bpf_kfunc int bpf_sk_assign_tcp_reqsk(struct __sk_buff *s, struct sock *sk,
 #endif
 }
 
+__bpf_kfunc int bpf_sock_ops_tcp_set_rcvlowat(struct bpf_sock_ops_kern *skops,
+					      int rcvlowat)
+{
+#ifdef CONFIG_INET
+	if (skops->op != BPF_SOCK_OPS_RCVQ_CB)
+		return -EOPNOTSUPP;
+
+	if (rcvlowat < 0)
+		rcvlowat = INT_MAX;
+
+	return __tcp_set_rcvlowat(skops->sk, rcvlowat, !skops->skb);
+#else
+	return -EOPNOTSUPP;
+#endif
+}
+
 __bpf_kfunc int bpf_sock_ops_enable_tx_tstamp(struct bpf_sock_ops_kern *skops,
 					      u64 flags)
 {
@@ -12539,6 +12555,7 @@ BTF_KFUNCS_END(bpf_kfunc_check_set_tcp_reqsk)
 
 BTF_KFUNCS_START(bpf_kfunc_check_set_sock_ops)
 BTF_ID_FLAGS(func, bpf_sock_ops_enable_tx_tstamp)
+BTF_ID_FLAGS(func, bpf_sock_ops_tcp_set_rcvlowat)
 BTF_KFUNCS_END(bpf_kfunc_check_set_sock_ops)
 
 static const struct btf_kfunc_id_set bpf_kfunc_set_skb = {
Signature · 1 line
2.54.0.746.g67dd491aae-goog
#16 lore raw

Re: [PATCH v3 bpf-next 05/11] bpf: tcp: Add kfunc to adjust sk->sk_rcvlowat.

Should this kfunc prevent operation on MPTCP subflows? Bjorn Topel raised this concern in v1, noting the issue that commit fcf4692fa39e ("mptcp: prevent BPF accessing lowat from a subflow socket.")…
Quoted 9 lines
net/core/filter.c +1 -0
index fa8a7c7d86eb..3608036632a8 100644
@@ -12388,6 +12388,22 @@ __bpf_kfunc int bpf_sk_assign_tcp_reqsk(struct __sk_buff *s, struct sock *sk,
 #endif
 }
 
+__bpf_kfunc int bpf_sock_ops_tcp_set_rcvlowat(struct bpf_sock_ops_kern *skops,

net/core/filter.c __bpf_kfunc int bpf_sk_assign_tcp_reqsk(struct __sk_buff *s, struct sock *sk, · line 12401

Quoted 10 lines
net/core/filter.c +10 -0
+					      int rcvlowat)
+{
+#ifdef CONFIG_INET
+	if (skops->op != BPF_SOCK_OPS_RCVQ_CB)
+		return -EOPNOTSUPP;
+
+	if (rcvlowat < 0)
+		rcvlowat = INT_MAX;
+
+	return __tcp_set_rcvlowat(skops->sk, rcvlowat, !skops->skb);

Should this kfunc prevent operation on MPTCP subflows? Bjorn Topel raised this concern in v1, noting the issue that commit fcf4692fa39e ("mptcp: prevent BPF accessing lowat from a subflow socket.") was designed to prevent.

You acknowledged this and stated you would drop MPTCP support for now, mentioning that a subsequent patch (patch 7 in the v3 series: "bpf:
mptcp: Don't support BPF_SOCK_OPS_RCVQ_CB.") would disable the callback for MPTCP.

However, the current code lacks any MPTCP check. Without either disabling BPF_SOCK_OPS_RCVQ_CB for MPTCP subflows in the callback registration or adding a check like:

	if (sk_is_mptcp(skops->sk))
		return -EOPNOTSUPP;

couldn't a BPF program invoke this kfunc on MPTCP subflows and trigger the same problem that fcf4692fa39e was designed to prevent?

Reference: https://lore.kernel.org/bpf/[email protected]/

Quoted 9 lines
net/core/filter.c +5 -0
+#else
+	return -EOPNOTSUPP;
+#endif
+}
+
 __bpf_kfunc int bpf_sock_ops_enable_tx_tstamp(struct bpf_sock_ops_kern *skops,
 					      u64 flags)
 {

net/core/filter.c BTF_KFUNCS_END(bpf_kfunc_check_set_tcp_reqsk) · line 12561

Quoted 7 lines
net/core/filter.c +1 -0
@@ -12539,6 +12555,7 @@ BTF_KFUNCS_END(bpf_kfunc_check_set_tcp_reqsk)
 
 BTF_KFUNCS_START(bpf_kfunc_check_set_sock_ops)
 BTF_ID_FLAGS(func, bpf_sock_ops_enable_tx_tstamp)
+BTF_ID_FLAGS(func, bpf_sock_ops_tcp_set_rcvlowat)
 BTF_KFUNCS_END(bpf_kfunc_check_set_sock_ops)
 
 static const struct btf_kfunc_id_set bpf_kfunc_set_skb = {

---
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/26328541814

author reviewer
#17 lore raw

PATCH v3 6/11 bpf: tcp: Make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive.

In reply to Kuniyuki Iwashima

Both BPF_SOCK_OPS_RCVQ_CB and SOCKMAP can intercept and handle socket receive queues, leading to overlapping use cases.

While BPF_SOCK_OPS_RCVQ_CB focuses on optimizing single-socket performance by reducing EPOLLIN wakeups and fully preserves TCP zerocopy support, SOCKMAP is designed to facilitate multi-socket routing at the cost of higher overhead and no zerocopy support.

Enabling both features on the same socket makes no sense and results in unexpected interference between them.

For instance, SOCKMAP calls __tcp_cleanup_rbuf(), where we will add a BPF_SOCK_OPS_RCVQ_CB hook, and bpf_sock_ops_tcp_set_rcvlowat() calls sk->sk_data_ready(), which would trigger SOCKMAP.

Let's make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive.

Note that it requires write_lock_bh(&sk->sk_callback_lock) to synchronise with tcp_bpf_update_proto() and check if sk->sk_prot is one of tcp_bpf_prots[][] because sock_map_update_elem() only holds bh_lock_sock() without checking sock_owned_by_user().

---
v3: Check sk->sk_prot and update tp->bpf_sock_ops_cb_flags

    under sk->sk_callback_lock, and only when not flagged yet.
---
 include/net/tcp.h  |  1 +
 net/core/filter.c  | 35 +++++++++++++++++++++++++++++++----
 net/ipv4/tcp_bpf.c | 12 ++++++++++++
 3 files changed, 44 insertions(+), 4 deletions(-)
include/net/tcp.h +1 -0
index c6a6853909c4..bc95d8e7b62e 100644
@@ -2853,6 +2853,7 @@ struct sk_msg;
 struct sk_psock;
 
 #ifdef CONFIG_BPF_SYSCALL
+bool tcp_in_sockmap(const struct sock *sk);
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore);
 void tcp_bpf_clone(const struct sock *sk, struct sock *newsk);
 #ifdef CONFIG_BPF_STREAM_PARSER
net/core/filter.c +31 -4
index 3608036632a8..1fb63b264b18 100644
@@ -5382,12 +5382,34 @@ static int bpf_sol_tcp_getsockopt(struct sock *sk, int optname,
 	return 0;
 }
 
+static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)
+{
+	if (!(val & BPF_SOCK_OPS_RCVQ_CB_FLAG) ||
+	    tcp_sk(sk)->bpf_sock_ops_cb_flags & BPF_SOCK_OPS_RCVQ_CB_FLAG) {
+		tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+		return 0;
+	}
+
+	write_lock_bh(&sk->sk_callback_lock);
+
+	if (unlikely(tcp_in_sockmap(sk))) {
+		write_unlock_bh(&sk->sk_callback_lock);
+		return -EBUSY;
+	}
+
+	tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+
+	write_unlock_bh(&sk->sk_callback_lock);
+
+	return 0;
+}
+
 static int bpf_sol_tcp_setsockopt(struct sock *sk, int optname,
 				  char *optval, int optlen)
 {
 	struct tcp_sock *tp = tcp_sk(sk);
 	unsigned long timeout;
-	int val;
+	int val, err;
 
 	if (optlen != sizeof(int))
 		return -EINVAL;
@@ -5424,7 +5446,9 @@ static int bpf_sol_tcp_setsockopt(struct sock *sk, int optname,
 	case TCP_BPF_SOCK_OPS_CB_FLAGS:
 		if (val & ~(BPF_SOCK_OPS_ALL_CB_FLAGS))
 			return -EINVAL;
-		tp->bpf_sock_ops_cb_flags = val;
+		err = __bpf_sock_ops_cb_flags_set(sk, val);
+		if (err)
+			return err;
 		break;
 	default:
 		return -EINVAL;
@@ -5999,8 +6023,9 @@ static const struct bpf_func_proto bpf_sock_ops_getsockopt_proto = {
 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
 	   int, argval)
 {
-	struct sock *sk = bpf_sock->sk;
 	int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
+	struct sock *sk = bpf_sock->sk;
+	int err;
 
 	if (!is_locked_tcp_sock_ops(bpf_sock) &&
 	    bpf_sock->op != BPF_SOCK_OPS_RCVQ_CB)
@@ -6009,7 +6034,9 @@ BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
 	if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
 		return -EINVAL;
 
-	tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+	err = __bpf_sock_ops_cb_flags_set(sk, val);
+	if (err)
+		return err;
 
 	return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
 }
net/ipv4/tcp_bpf.c +12 -0
index cc0bd73f36b6..7e7966b095f9 100644
@@ -705,6 +705,16 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc,
 }
 #endif /* CONFIG_BPF_STREAM_PARSER */
 
+bool tcp_in_sockmap(const struct sock *sk)
+{
+	const struct proto *prot = sk->sk_prot;
+
+	lockdep_assert_held(&sk->sk_callback_lock);
+
+	return &tcp_bpf_prots[0][0] <= prot &&
+		prot <= &tcp_bpf_prots[TCP_BPF_NUM_PROTS - 1][TCP_BPF_NUM_CFGS - 1];
+}
+
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 {
 	int family = sk->sk_family == AF_INET6 ? TCP_BPF_IPV6 : TCP_BPF_IPV4;
@@ -729,6 +739,8 @@ int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 			sock_replace_proto(sk, psock->sk_proto);
 		}
 		return 0;
+	} else if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG)) {
+		return -EBUSY;
 	}
 
 	if (sk->sk_family == AF_INET6) {
Signature · 1 line
2.54.0.746.g67dd491aae-goog
#18 lore raw

Re: [PATCH v3 bpf-next 06/11] bpf: tcp: Make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive.

A subsystem pattern flags this as potentially concerning: the commit message explains that write_lock_bh(&sk->sk_callback_lock) is taken to synchronise with tcp_bpf_update_proto(), but does…
Quoted 16 lines
include/net/tcp.h +1 -0
index c6a6853909c4..bc95d8e7b62e 100644
@@ -2853,6 +2853,7 @@ struct sk_msg;
 struct sk_psock;
 
 #ifdef CONFIG_BPF_SYSCALL
+bool tcp_in_sockmap(const struct sock *sk);
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore);
 void tcp_bpf_clone(const struct sock *sk, struct sock *newsk);
 #ifdef CONFIG_BPF_STREAM_PARSER
net/core/filter.c +0 -0
index 3608036632a8..1fb63b264b18 100644

[ ... ]

Quoted 26 lines
net/core/filter.c +22 -0
@@ -5382,12 +5382,34 @@ static int bpf_sol_tcp_getsockopt(struct sock *sk, int optname,
 	return 0;
 }
 
+static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)
+{
+	if (!(val & BPF_SOCK_OPS_RCVQ_CB_FLAG) ||
+	    tcp_sk(sk)->bpf_sock_ops_cb_flags & BPF_SOCK_OPS_RCVQ_CB_FLAG) {
+		tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+		return 0;
+	}
+
+	write_lock_bh(&sk->sk_callback_lock);
+
+	if (unlikely(tcp_in_sockmap(sk))) {
+		write_unlock_bh(&sk->sk_callback_lock);
+		return -EBUSY;
+	}
+
+	tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+
+	write_unlock_bh(&sk->sk_callback_lock);
+
+	return 0;
+}
+

[ ... ]

Quoted 22 lines
net/ipv4/tcp_bpf.c +10 -0
index cc0bd73f36b6..7e7966b095f9 100644
@@ -705,6 +705,16 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc,
 }
 #endif /* CONFIG_BPF_STREAM_PARSER */
 
+bool tcp_in_sockmap(const struct sock *sk)
+{
+	const struct proto *prot = sk->sk_prot;
+
+	lockdep_assert_held(&sk->sk_callback_lock);
+
+	return &tcp_bpf_prots[0][0] <= prot &&
+		prot <= &tcp_bpf_prots[TCP_BPF_NUM_PROTS - 1][TCP_BPF_NUM_CFGS - 1];
+}
+
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 {
 	int family = sk->sk_family == AF_INET6 ? TCP_BPF_IPV6 : TCP_BPF_IPV4;

net/ipv4/tcp_bpf.c int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore) · line 743

Quoted 5 lines
net/ipv4/tcp_bpf.c +2 -0
@@ -729,6 +739,8 @@ int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 			sock_replace_proto(sk, psock->sk_proto);
 		}
 		return 0;
+	} else if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG)) {
+		return -EBUSY;
                   ^^^^

A subsystem pattern flags this as potentially concerning: the commit message explains that write_lock_bh(&sk->sk_callback_lock) is taken to synchronise with tcp_bpf_update_proto(), but does tcp_bpf_update_proto() actually take sk->sk_callback_lock?

Looking at the call chain, tcp_bpf_update_proto() is invoked from the SOCKMAP path through:

sock_map_link() in net/core/sock_map.c
-> sock_map_init_proto()

     -> tcp_bpf_update_proto()

In sock_map_link(), sk_callback_lock is acquired after sock_map_init_proto() completes, not before. The lock is taken when setting sk_user_data to the psock, but sock_map_init_proto() runs outside the lock and calls sock_replace_proto() to write sk->sk_prot without holding sk_callback_lock.

Is there a race here? Consider this interleaving (the commit message acknowledges sock_map_update_elem only holds bh_lock_sock(), so it can run concurrently with setsockopt that holds the socket lock):

CPU 0 (sockmap path) CPU 1 (BPF setsockopt RCVQ_CB)
sock_map_link(): __bpf_sock_ops_cb_flags_set():
sk_psock_init(): (val has RCVQ_CB, current=0)
lock sk_callback_lock
set sk_user_data = psock
unlock sk_callback_lock
sock_map_init_proto():
tcp_bpf_update_proto():
BPF_SOCK_OPS_TEST_FLAG: 0
(no flag yet, check passes)
write_lock_bh(sk_callback_lock) tcp_in_sockmap(sk): sk_prot still old, returns false tp->bpf_sock_ops_cb_flags = val (RCVQ_CB set) write_unlock_bh
sock_replace_proto(sk,
&tcp_bpf_prots[][])
(sk_prot now in tcp_bpf_prots)

Final state: sk_prot is in tcp_bpf_prots[][] AND bpf_sock_ops_cb_flags has BPF_SOCK_OPS_RCVQ_CB_FLAG. Both features are now enabled, which violates the mutual exclusion goal.

The validation checks in tcp_bpf_update_proto() and __bpf_sock_ops_cb_flags_set() each check shared state before the exclusion point, not under common exclusion. Running a lockset analysis on the two shared variables:

bpf_sock_ops_cb_flags: written by __bpf_sock_ops_cb_flags_set under sk_callback_lock; read by tcp_bpf_update_proto with no lock. Lockset intersection = {sk_callback_lock} intersect {} = {}.

sk->sk_prot: read by tcp_in_sockmap under sk_callback_lock; written by sock_replace_proto (called from tcp_bpf_update_proto) with no lock. Lockset intersection = {} intersect {sk_callback_lock} = {}.

Could the synchronization be strengthened so both paths access both variables under the same lock?

net/ipv4/tcp_bpf.c int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore) · line 746

Quoted 3 lines
net/ipv4/tcp_bpf.c +0 -0
 	}
 
 	if (sk->sk_family == AF_INET6) {

---
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/26328541814

author reviewer
#19 lore raw

Re: [PATCH v3 bpf-next 06/11] bpf: tcp: Make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive.

Quoted 86 lines · On Sat, May 23, 2026 at 2:20 AM <[email protected]> wrote:
Quoted 17 lines
include/net/tcp.h +1 -0
index c6a6853909c4..bc95d8e7b62e 100644
@@ -2853,6 +2853,7 @@ struct sk_msg;
 struct sk_psock;
 
 #ifdef CONFIG_BPF_SYSCALL
+bool tcp_in_sockmap(const struct sock *sk);
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore);
 void tcp_bpf_clone(const struct sock *sk, struct sock *newsk);
 #ifdef CONFIG_BPF_STREAM_PARSER
net/core/filter.c +0 -0
index 3608036632a8..1fb63b264b18 100644

[ ... ]

Quoted 26 lines
net/core/filter.c +22 -0
@@ -5382,12 +5382,34 @@ static int bpf_sol_tcp_getsockopt(struct sock *sk, int optname,
      return 0;
 }
 
+static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)
+{
+     if (!(val & BPF_SOCK_OPS_RCVQ_CB_FLAG) ||
+         tcp_sk(sk)->bpf_sock_ops_cb_flags & BPF_SOCK_OPS_RCVQ_CB_FLAG) {
+             tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+             return 0;
+     }
+
+     write_lock_bh(&sk->sk_callback_lock);
+
+     if (unlikely(tcp_in_sockmap(sk))) {
+             write_unlock_bh(&sk->sk_callback_lock);
+             return -EBUSY;
+     }
+
+     tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+
+     write_unlock_bh(&sk->sk_callback_lock);
+
+     return 0;
+}
+

[ ... ]

Quoted 22 lines
net/ipv4/tcp_bpf.c +10 -0
index cc0bd73f36b6..7e7966b095f9 100644
@@ -705,6 +705,16 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc,
 }
 #endif /* CONFIG_BPF_STREAM_PARSER */
 
+bool tcp_in_sockmap(const struct sock *sk)
+{
+     const struct proto *prot = sk->sk_prot;
+
+     lockdep_assert_held(&sk->sk_callback_lock);
+
+     return &tcp_bpf_prots[0][0] <= prot &&
+             prot <= &tcp_bpf_prots[TCP_BPF_NUM_PROTS - 1][TCP_BPF_NUM_CFGS - 1];
+}
+
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 {
      int family = sk->sk_family == AF_INET6 ? TCP_BPF_IPV6 : TCP_BPF_IPV4;

net/ipv4/tcp_bpf.c int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore) · line 743

Quoted 5 lines
net/ipv4/tcp_bpf.c +2 -0
@@ -729,6 +739,8 @@ int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
                      sock_replace_proto(sk, psock->sk_proto);
              }
              return 0;
+     } else if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG)) {
+             return -EBUSY;
                   ^^^^

A subsystem pattern flags this as potentially concerning: the commit message explains that write_lock_bh(&sk->sk_callback_lock) is taken to synchronise with tcp_bpf_update_proto(), but does tcp_bpf_update_proto() actually take sk->sk_callback_lock?

Looking at the call chain, tcp_bpf_update_proto() is invoked from the SOCKMAP path through:

Quoted 6 lines

sock_map_link() in net/core/sock_map.c
-> sock_map_init_proto()

     -> tcp_bpf_update_proto()

In sock_map_link(), sk_callback_lock is acquired after sock_map_init_proto() completes, not before.

Oh I assumed it's under lock since sock_map_del_link() and sk_psock_drop() call it under the lock.

I'll move sock_map_init_proto() under the lock as well.

Quoted 57 lines

The lock is taken when setting sk_user_data to the
psock, but sock_map_init_proto() runs outside the lock and calls sock_replace_proto() to write sk->sk_prot without holding sk_callback_lock.

Is there a race here? Consider this interleaving (the commit message acknowledges sock_map_update_elem only holds bh_lock_sock(), so it can run concurrently with setsockopt that holds the socket lock):

CPU 0 (sockmap path) CPU 1 (BPF setsockopt RCVQ_CB)
sock_map_link(): __bpf_sock_ops_cb_flags_set():
sk_psock_init(): (val has RCVQ_CB, current=0)
lock sk_callback_lock
set sk_user_data = psock
unlock sk_callback_lock
sock_map_init_proto():
tcp_bpf_update_proto():
BPF_SOCK_OPS_TEST_FLAG: 0
(no flag yet, check passes)
write_lock_bh(sk_callback_lock) tcp_in_sockmap(sk): sk_prot still old, returns false tp->bpf_sock_ops_cb_flags = val (RCVQ_CB set) write_unlock_bh
sock_replace_proto(sk,
&tcp_bpf_prots[][])
(sk_prot now in tcp_bpf_prots)

Final state: sk_prot is in tcp_bpf_prots[][] AND bpf_sock_ops_cb_flags has BPF_SOCK_OPS_RCVQ_CB_FLAG. Both features are now enabled, which violates the mutual exclusion goal.

The validation checks in tcp_bpf_update_proto() and __bpf_sock_ops_cb_flags_set() each check shared state before the exclusion point, not under common exclusion. Running a lockset analysis on the two shared variables:

bpf_sock_ops_cb_flags: written by __bpf_sock_ops_cb_flags_set under sk_callback_lock; read by tcp_bpf_update_proto with no lock. Lockset intersection = {sk_callback_lock} intersect {} = {}.

sk->sk_prot: read by tcp_in_sockmap under sk_callback_lock; written by sock_replace_proto (called from tcp_bpf_update_proto) with no lock. Lockset intersection = {} intersect {sk_callback_lock} = {}.

Could the synchronization be strengthened so both paths access both variables under the same lock?

net/ipv4/tcp_bpf.c int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore) · line 746

Quoted 3 lines
net/ipv4/tcp_bpf.c +0 -0
      }
 
      if (sk->sk_family == AF_INET6) {

---
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/26328541814

#20 lore raw

Re: [PATCH v3 bpf-next 06/11] bpf: tcp: Make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive.

In reply to Kuniyuki Iwashima
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] The mutual exclusion between BPF_SOCK_OPS_RCVQ_CB and SOCKMAP is completely bypassed due to a…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] The mutual exclusion between BPF_SOCK_OPS_RCVQ_CB and SOCKMAP is completely bypassed due to a Time-of-Check to Time-of-Use (TOCTOU) race condition.
- [High] tcp_in_sockmap() fails to detect a sockmap if an Upper Layer Protocol (ULP) like TLS is attached, allowing the mutual exclusion to be bypassed.
- [Low] Calling tcp_in_sockmap() in net/core/filter.c breaks the build when CONFIG_BPF_SYSCALL is disabled.
- [Low] Using relational operators on pointers from different array objects is undefined behavior in C.
--

commit ebabac3763475d472254639d69b23d839f36111b
Author: Kuniyuki Iwashima <[email protected]>

bpf: tcp: Make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive.

This patch aims to make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive, as both can intercept and handle socket receive queues. It introduces checks in tcp_bpf_update_proto() and __bpf_sock_ops_cb_flags_set() to prevent both from being enabled on the same socket simultaneously.

Quoted 16 lines
include/net/tcp.h +1 -0
index c6a6853909c4b..bc95d8e7b62e8 100644
@@ -2853,6 +2853,7 @@ struct sk_msg;
 struct sk_psock;
 
 #ifdef CONFIG_BPF_SYSCALL
+bool tcp_in_sockmap(const struct sock *sk);
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore);
 void tcp_bpf_clone(const struct sock *sk, struct sock *newsk);
 #ifdef CONFIG_BPF_STREAM_PARSER
net/core/filter.c +0 -0
index 3608036632a81..1fb63b264b181 100644

[ ... ]

Quoted 5 lines
net/core/filter.c +1 -0
@@ -5382,12 +5382,34 @@ static int bpf_sol_tcp_getsockopt(struct sock *sk, int optname,
 	return 0;
 }
 
+static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)

net/core/filter.c static int bpf_sol_tcp_getsockopt(struct sock *sk, int optname, · line 5395

Quoted 10 lines
net/core/filter.c +10 -0
+{
+	if (!(val & BPF_SOCK_OPS_RCVQ_CB_FLAG) ||
+	    tcp_sk(sk)->bpf_sock_ops_cb_flags & BPF_SOCK_OPS_RCVQ_CB_FLAG) {
+		tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+		return 0;
+	}
+
+	write_lock_bh(&sk->sk_callback_lock);
+
+	if (unlikely(tcp_in_sockmap(sk))) {

[Severity: Low]
Does calling tcp_in_sockmap() unconditionally here break the build when CONFIG_BPF_SYSCALL is disabled? The declaration in include/net/tcp.h is guarded by #ifdef CONFIG_BPF_SYSCALL, but there does not appear to be a dummy fallback for when it is disabled.

Quoted 10 lines
net/core/filter.c +10 -0
+		write_unlock_bh(&sk->sk_callback_lock);
+		return -EBUSY;
+	}
+
+	tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+
+	write_unlock_bh(&sk->sk_callback_lock);
+
+	return 0;
+}

[ ... ]

Quoted 6 lines
net/ipv4/tcp_bpf.c +0 -0
index cc0bd73f36b6d..7e7966b095f9a 100644
@@ -705,6 +705,16 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc,
 }

net/ipv4/tcp_bpf.c int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc, · line 715

Quoted 10 lines
net/ipv4/tcp_bpf.c +8 -0
 #endif /* CONFIG_BPF_STREAM_PARSER */
 
+bool tcp_in_sockmap(const struct sock *sk)
+{
+	const struct proto *prot = sk->sk_prot;
+
+	lockdep_assert_held(&sk->sk_callback_lock);
+
+	return &tcp_bpf_prots[0][0] <= prot &&
+		prot <= &tcp_bpf_prots[TCP_BPF_NUM_PROTS - 1][TCP_BPF_NUM_CFGS - 1];

[Severity: Low]
Is this pointer comparison safe? In C, relational comparisons (<=, >=) between pointers that do not point to the same array object result in undefined behavior.

[Severity: High]
Does this logic fail to detect a sockmap if an Upper Layer Protocol (ULP) like TLS is attached?

If a socket is already in a sockmap and a ULP is attached, the ULP initialization replaces sk->sk_prot with its own protocol structure (e.g., tls_prots).

This would cause tcp_in_sockmap() to return false, allowing __bpf_sock_ops_cb_flags_set() to enable BPF_SOCK_OPS_RCVQ_CB_FLAG and bypass the mutual exclusion.

net/ipv4/tcp_bpf.c int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore) · line 743

Quoted 11 lines
net/ipv4/tcp_bpf.c +4 -0
+}
+
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 {
 	int family = sk->sk_family == AF_INET6 ? TCP_BPF_IPV6 : TCP_BPF_IPV4;
@@ -729,6 +739,8 @@ int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 			sock_replace_proto(sk, psock->sk_proto);
 		}
 		return 0;
+	} else if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG)) {
+		return -EBUSY;

[Severity: High]
Can sock_map_update_elem() and bpf_sol_tcp_setsockopt() race here, allowing both features to be enabled?

sock_map_update_elem() does not call sock_owned_by_user() and only takes bh_lock_sock(sk). This means it can execute concurrently with bpf_sol_tcp_setsockopt() from another thread which holds lock_sock(sk) (because lock_sock() releases the slock spinlock).

If Thread A in sock_map_update_elem() calls tcp_bpf_update_proto(), it checks BPF_SOCK_OPS_TEST_FLAG() before sk->sk_callback_lock is ever acquired.

Concurrently, Thread B in bpf_sol_tcp_setsockopt() takes sk->sk_callback_lock, finds tcp_in_sockmap() is false because Thread A hasn't replaced sk->sk_prot yet, sets the BPF_SOCK_OPS_RCVQ_CB_FLAG, and unlocks.

Thread A then continues and replaces sk->sk_prot to the sockmap protocol, resulting in both features being active on the same socket.

Quoted 3 lines
net/ipv4/tcp_bpf.c +0 -0
 	}
 
 	if (sk->sk_family == AF_INET6) {
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author reviewer
#21 lore raw

Re: [PATCH v3 bpf-next 06/11] bpf: tcp: Make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive.

Quoted 48 lines · On Sat, May 23, 2026 at 2:29 AM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] The mutual exclusion between BPF_SOCK_OPS_RCVQ_CB and SOCKMAP is completely bypassed due to a Time-of-Check to Time-of-Use (TOCTOU) race condition.
- [High] tcp_in_sockmap() fails to detect a sockmap if an Upper Layer Protocol (ULP) like TLS is attached, allowing the mutual exclusion to be bypassed.
- [Low] Calling tcp_in_sockmap() in net/core/filter.c breaks the build when CONFIG_BPF_SYSCALL is disabled.
- [Low] Using relational operators on pointers from different array objects is undefined behavior in C.
--

commit ebabac3763475d472254639d69b23d839f36111b
Author: Kuniyuki Iwashima <[email protected]>

bpf: tcp: Make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive.

This patch aims to make BPF_SOCK_OPS_RCVQ_CB and SOCKMAP mutually exclusive, as both can intercept and handle socket receive queues. It introduces checks in tcp_bpf_update_proto() and __bpf_sock_ops_cb_flags_set() to prevent both from being enabled on the same socket simultaneously.

Quoted 16 lines
include/net/tcp.h +1 -0
index c6a6853909c4b..bc95d8e7b62e8 100644
@@ -2853,6 +2853,7 @@ struct sk_msg;
 struct sk_psock;
 
 #ifdef CONFIG_BPF_SYSCALL
+bool tcp_in_sockmap(const struct sock *sk);
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore);
 void tcp_bpf_clone(const struct sock *sk, struct sock *newsk);
 #ifdef CONFIG_BPF_STREAM_PARSER
net/core/filter.c +0 -0
index 3608036632a81..1fb63b264b181 100644

[ ... ]

Quoted 13 lines
net/core/filter.c +9 -0
@@ -5382,12 +5382,34 @@ static int bpf_sol_tcp_getsockopt(struct sock *sk, int optname,
      return 0;
 }
 
+static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)
+{
+     if (!(val & BPF_SOCK_OPS_RCVQ_CB_FLAG) ||
+         tcp_sk(sk)->bpf_sock_ops_cb_flags & BPF_SOCK_OPS_RCVQ_CB_FLAG) {
+             tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+             return 0;
+     }
+
+     write_lock_bh(&sk->sk_callback_lock);
Quoted 8 lines

net/core/filter.c static int bpf_sol_tcp_getsockopt(struct sock *sk, int optname, · line 5395

Quoted 2 lines
net/core/filter.c +2 -0
+
+     if (unlikely(tcp_in_sockmap(sk))) {

[Severity: Low]
Does calling tcp_in_sockmap() unconditionally here break the build when CONFIG_BPF_SYSCALL is disabled? The declaration in include/net/tcp.h is guarded by #ifdef CONFIG_BPF_SYSCALL, but there does not appear to be a dummy fallback for when it is disabled.

Will fix.

Quoted 38 lines
Quoted 11 lines
net/core/filter.c +10 -0
+             write_unlock_bh(&sk->sk_callback_lock);
+             return -EBUSY;
+     }
+
+     tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
+
+     write_unlock_bh(&sk->sk_callback_lock);
+
+     return 0;
+}

[ ... ]

Quoted 6 lines
net/ipv4/tcp_bpf.c +0 -0
index cc0bd73f36b6d..7e7966b095f9a 100644
@@ -705,6 +705,16 @@ int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc,
 }

net/ipv4/tcp_bpf.c int tcp_bpf_strp_read_sock(struct strparser *strp, read_descriptor_t *desc, · line 715

Quoted 10 lines
net/ipv4/tcp_bpf.c +8 -0
 #endif /* CONFIG_BPF_STREAM_PARSER */
 
+bool tcp_in_sockmap(const struct sock *sk)
+{
+     const struct proto *prot = sk->sk_prot;
+
+     lockdep_assert_held(&sk->sk_callback_lock);
+
+     return &tcp_bpf_prots[0][0] <= prot &&
+             prot <= &tcp_bpf_prots[TCP_BPF_NUM_PROTS - 1][TCP_BPF_NUM_CFGS - 1];

[Severity: Low]
Is this pointer comparison safe? In C, relational comparisons (<=, >=) between pointers that do not point to the same array object result in undefined behavior.

[Severity: High]
Does this logic fail to detect a sockmap if an Upper Layer Protocol (ULP) like TLS is attached?

Quoted 7 lines

If a socket is already in a sockmap and a ULP is attached, the ULP initialization replaces sk->sk_prot with its own protocol structure (e.g., tls_prots).

This would cause tcp_in_sockmap() to return false, allowing __bpf_sock_ops_cb_flags_set() to enable BPF_SOCK_OPS_RCVQ_CB_FLAG and bypass the mutual exclusion.

I'll check sk->sk_prot->destroy() instead since it's not overwritten by kTLS.

Quoted 40 lines

net/ipv4/tcp_bpf.c int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore) · line 743

Quoted 12 lines
net/ipv4/tcp_bpf.c +4 -0
+}
+
 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 {
      int family = sk->sk_family == AF_INET6 ? TCP_BPF_IPV6 : TCP_BPF_IPV4;
@@ -729,6 +739,8 @@ int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
                      sock_replace_proto(sk, psock->sk_proto);
              }
              return 0;
+     } else if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG)) {
+             return -EBUSY;

[Severity: High]
Can sock_map_update_elem() and bpf_sol_tcp_setsockopt() race here, allowing both features to be enabled?

sock_map_update_elem() does not call sock_owned_by_user() and only takes bh_lock_sock(sk). This means it can execute concurrently with bpf_sol_tcp_setsockopt() from another thread which holds lock_sock(sk) (because lock_sock() releases the slock spinlock).

If Thread A in sock_map_update_elem() calls tcp_bpf_update_proto(), it checks BPF_SOCK_OPS_TEST_FLAG() before sk->sk_callback_lock is ever acquired.

Concurrently, Thread B in bpf_sol_tcp_setsockopt() takes sk->sk_callback_lock, finds tcp_in_sockmap() is false because Thread A hasn't replaced sk->sk_prot yet, sets the BPF_SOCK_OPS_RCVQ_CB_FLAG, and unlocks.

Thread A then continues and replaces sk->sk_prot to the sockmap protocol, resulting in both features being active on the same socket.

net/ipv4/tcp_bpf.c int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore) · line 746

Quoted 3 lines
net/ipv4/tcp_bpf.c +0 -0
      }
 
      if (sk->sk_family == AF_INET6) {

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6

author reviewer
#22 lore raw

PATCH v3 7/11 bpf: mptcp: Don't support BPF_SOCK_OPS_RCVQ_CB.

In reply to Kuniyuki Iwashima

MPTCP has its own sock->ops->set_rcvlowat() / mptcp_set_rcvlowat().

We should not allow calling __tcp_set_rcvlowat() for MPTCP subflows.

Let's disable BPF_SOCK_OPS_RCVQ_CB for MPTCP for now.

If needed in the future, bpf_sock_ops_tcp_set_rcvlowat() could be extended to properly support MPTCP.

---
 net/core/filter.c | 3 +++
 1 file changed, 3 insertions(+)
net/core/filter.c +3 -0
index 1fb63b264b18..82ec2291d6f0 100644
@@ -5390,6 +5390,9 @@ static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)
 		return 0;
 	}
 
+	if (unlikely(sk_is_mptcp(sk)))
+		return -EOPNOTSUPP;
+
 	write_lock_bh(&sk->sk_callback_lock);
 
 	if (unlikely(tcp_in_sockmap(sk))) {
Signature · 1 line
2.54.0.746.g67dd491aae-goog
author reviewer
#23 lore raw

PATCH v3 8/11 bpf: tcp: Reject BPF_SOCK_OPS_RCVQ_CB if receive queue is not empty.

In reply to Kuniyuki Iwashima

Unlike SOCKMAP, BPF_SOCK_OPS_RCVQ_CB does not iterate existing skbs in the receive queue when it is enabled for the first time.

In practical production use cases, this behavior is usually not a problem.

We can safely assume that the upper-layer protocol is designed with specific synchronisation points where the connection is temporarily quiet.

At these points, the application can completely drain the receive queue and safely enable BPF_SOCK_OPS_RCVQ_CB while no skbs are pending.

A prime example is an application transitioning from HTTP to an RPC protocol:

     Client                                Server
       |                                     |
       | --- HTTP Upgrade request ---------> |
       |                                     | [Drain all skbs]
       |                                     | [Enable BPF_SOCK_OPS_RCVQ_CB]
       | <-- HTTP 200/Switching protocol --- |
       |                                     |
       | --- RPC Frame 1 ------------------> |

However, to strictly prevent any potential race conditions arising from unconventional upper-layer protocol designs, let's explicitly signal a failure if BPF_SOCK_OPS_RCVQ_CB is enabled while the receive queue is not empty.

-EUCLEAN is chosen to indicate that the caller needs to clean up the receive queue before enabling the feature.

---
 net/core/filter.c | 3 +++
 1 file changed, 3 insertions(+)
net/core/filter.c +3 -0
index 82ec2291d6f0..4041b9fc1c74 100644
@@ -5390,6 +5390,9 @@ static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)
 		return 0;
 	}
 
+	if (!skb_queue_empty(&sk->sk_receive_queue))
+		return -EUCLEAN;
+
 	if (unlikely(sk_is_mptcp(sk)))
 		return -EOPNOTSUPP;
 
Signature · 1 line
2.54.0.746.g67dd491aae-goog
#24 lore raw

Re: [PATCH v3 bpf-next 08/11] bpf: tcp: Reject BPF_SOCK_OPS_RCVQ_CB if receive queue is not empty.

Is there a TOCTOU issue here? The check occurs before acquiring sk->sk_callback_lock, which means:

net/core/filter.c static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val) · line 5395

Quoted 11 lines
net/core/filter.c +3 -0
index 82ec2291d6f0..4041b9fc1c74 100644
@@ -5390,6 +5390,9 @@ static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)
 		return 0;
 	}
 
+	if (!skb_queue_empty(&sk->sk_receive_queue))
+		return -EUCLEAN;
+

Is there a TOCTOU issue here? The check occurs before acquiring sk->sk_callback_lock, which means:

Thread A (process context)
__bpf_sock_ops_cb_flags_set()

    if (!skb_queue_empty(&sk->sk_receive_queue))  // queue is empty
        // check passes

Thread B (softirq context)
tcp_rcv_established()

    // adds packet to sk->sk_receive_queue

Thread A (continuing)
__bpf_sock_ops_cb_flags_set()

    write_lock_bh(&sk->sk_callback_lock);
    // sets bpf_sock_ops_cb_flags despite queue being non-empty

Looking at the tcp_in_sockmap() check below, it contains lockdep_assert_held(&sk->sk_callback_lock), showing that related validation checks are expected to be performed under this lock:

net/core/filter.c

Quoted 9 lines
net/core/filter.c +0 -0
 	if (unlikely(sk_is_mptcp(sk)))
 		return -EOPNOTSUPP;
 
net/core/filter.c +0 -0
 	write_lock_bh(&sk->sk_callback_lock);
 
 	if (unlikely(tcp_in_sockmap(sk))) {
 		write_unlock_bh(&sk->sk_callback_lock);
 		return -EBUSY;
 	}

The commit message says the goal is to "strictly prevent any potential race conditions" by ensuring the receive queue is empty when BPF_SOCK_OPS_RCVQ_CB is enabled. Can this check be moved after the write_lock_bh() call to eliminate the race window?

---
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/26328541814

#25 lore raw

Re: [PATCH v3 bpf-next 08/11] bpf: tcp: Reject BPF_SOCK_OPS_RCVQ_CB if receive queue is not empty.

In reply to Kuniyuki Iwashima
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Lockless call to `skb_queue_empty()` on `sk_receive_queue` causes a data race. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Lockless call to skb_queue_empty() on sk_receive_queue causes a data race. --

commit 928b34616ed5f1b766d25ef2fd83e4165fe1e903
Author: Kuniyuki Iwashima <[email protected]>

bpf: tcp: Reject BPF_SOCK_OPS_RCVQ_CB if receive queue is not empty.

This commit modifies the behavior of BPF_SOCK_OPS_RCVQ_CB to explicitly fail if it is enabled while the receive queue is not empty. It returns -EUCLEAN to signal that the caller must drain the queue first.

net/core/filter.c static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val) · line 5394

Quoted 10 lines
net/core/filter.c +2 -0
index 82ec2291d6f00..4041b9fc1c741 100644
@@ -5390,6 +5390,9 @@ static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)
 		return 0;
 	}
 
+	if (!skb_queue_empty(&sk->sk_receive_queue))
+		return -EUCLEAN;

[Severity: Low]
Does this lockless call to skb_queue_empty() cause a data race?

The __bpf_sock_ops_cb_flags_set() function can be executed without the socket lock via the bpf_unlocked_sk_setsockopt() helper. At the same time, TCP softirq processing like tcp_queue_rcv() may enqueue packets and modify the receive queue.

Since skb_queue_empty() performs a plain read of list->next without READ_ONCE(), this concurrent access can trigger KCSAN splats. Would it be better to use skb_queue_empty_lockless() here to safely check the queue state from potentially unlocked contexts?

Quoted 4 lines
net/core/filter.c +1 -0
+
 	if (unlikely(sk_is_mptcp(sk)))
 		return -EOPNOTSUPP;
 
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
author reviewer
#26 lore raw

Re: [PATCH v3 bpf-next 08/11] bpf: tcp: Reject BPF_SOCK_OPS_RCVQ_CB if receive queue is not empty.

Quoted 22 lines · On Sat, May 23, 2026 at 2:42 AM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Lockless call to skb_queue_empty() on sk_receive_queue causes a data race. --

commit 928b34616ed5f1b766d25ef2fd83e4165fe1e903
Author: Kuniyuki Iwashima <[email protected]>

bpf: tcp: Reject BPF_SOCK_OPS_RCVQ_CB if receive queue is not empty.

This commit modifies the behavior of BPF_SOCK_OPS_RCVQ_CB to explicitly fail if it is enabled while the receive queue is not empty. It returns -EUCLEAN to signal that the caller must drain the queue first.

Quoted 8 lines
net/core/filter.c +0 -0
index 82ec2291d6f00..4041b9fc1c741 100644
@@ -5390,6 +5390,9 @@ static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val)
              return 0;
      }
 
Quoted 5 lines

net/core/filter.c static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val) · line 5394

Quoted 2 lines
net/core/filter.c +2 -0
+     if (!skb_queue_empty(&sk->sk_receive_queue))
+             return -EUCLEAN;

[Severity: Low]
Does this lockless call to skb_queue_empty() cause a data race?

No, the socket is under lock_sock() here.

Quoted 18 lines

The __bpf_sock_ops_cb_flags_set() function can be executed without the socket lock via the bpf_unlocked_sk_setsockopt() helper. At the same time, TCP softirq processing like tcp_queue_rcv() may enqueue packets and modify the receive queue.

Since skb_queue_empty() performs a plain read of list->next without READ_ONCE(), this concurrent access can trigger KCSAN splats. Would it be better to use skb_queue_empty_lockless() here to safely check the queue state from potentially unlocked contexts?

net/core/filter.c static int __bpf_sock_ops_cb_flags_set(struct sock *sk, int val) · line 5398

Quoted 4 lines
net/core/filter.c +1 -0
+
      if (unlikely(sk_is_mptcp(sk)))
              return -EOPNOTSUPP;
 

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8

author reviewer
#27 lore raw

PATCH v3 9/11 bpf: tcp: Factorise bpf_skops_established().

In reply to Kuniyuki Iwashima

We will call BPF SOCK_OPS prog with BPF_SOCK_OPS_RCVQ_CB.

It requires a similar setup to bpf_skops_established(), and the only difference is the skb data length.

Let's factor out the common logic into bpf_skops_common_locked().

---
 net/ipv4/tcp_input.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
net/ipv4/tcp_input.c +11 -4
index d5c9e65d9760..c4ba4f1e9d9e 100644
@@ -179,8 +179,9 @@ static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
 	BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
 }
 
-static void bpf_skops_established(struct sock *sk, int bpf_op,
-				  struct sk_buff *skb)
+static void bpf_skops_common_locked(struct sock *sk, int bpf_op,
+				    struct sk_buff *skb,
+				    unsigned int end_offset)
 {
 	struct bpf_sock_ops_kern sock_ops;
 
@@ -191,12 +192,18 @@ static void bpf_skops_established(struct sock *sk, int bpf_op,
 	sock_ops.is_fullsock = 1;
 	sock_ops.is_locked_tcp_sock = 1;
 	sock_ops.sk = sk;
-	/* sk with TCP_REPAIR_ON does not have skb in tcp_finish_connect */
 	if (skb)
-		bpf_skops_init_skb(&sock_ops, skb, tcp_hdrlen(skb));
+		bpf_skops_init_skb(&sock_ops, skb, end_offset);
 
 	BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
 }
+
+static void bpf_skops_established(struct sock *sk, int bpf_op,
+				  struct sk_buff *skb)
+{
+	/* sk with TCP_REPAIR_ON does not have skb in tcp_finish_connect */
+	bpf_skops_common_locked(sk, bpf_op, skb, skb ? tcp_hdrlen(skb) : 0);
+}
 #else
 static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
 {
Signature · 1 line
2.54.0.746.g67dd491aae-goog
author reviewer
#28 lore raw

PATCH v3 10/11 bpf: tcp: Add SOCK_OPS rcvlowat hook.

In reply to Kuniyuki Iwashima

Now, it is time to add the new hooks for BPF_SOCK_OPS_RCVQ_CB.

Let's invoke the BPF SOCK_OPS prog when

1. TCP stack enqueues skb to sk->sk_receive_queue

     -> tcp_queue_rcv(), tcp_ofo_queue(), and tcp_fastopen_add_skb()

2. TCP recvmsg() completes

     -> __tcp_cleanup_rbuf()

This will allow the BPF prog to parse each skb and dynamically adjust sk->sk_rcvlowat to suppress unnecessary EPOLLIN wakeups until sufficient data (e.g., a full RPC frame) is available in the receive queue.

Note that the direct access to bpf_sock_ops.data is intentionally disabled by passing 0 as end_offset.

Instead, the BPF prog is supposed to use bpf_skb_load_bytes() with bpf_sock_ops because payload is not in the linear area with TCP header/data split on and skb may contain a RPC descriptor in skb frag. This also simplifies the BPF prog.

The placement of tcp_bpf_rcvlowat() in tcp_ofo_queue() and tcp_fastopen_add_skb() is chosen to provide the same snapshot with tcp_queue_rcv().

For example, if tcp_bpf_rcvlowat() were called before updating TCP_SKB_CB(skb)->seq in tcp_fastopen_add_skb(), BPF prog would need to implement an unlikely if branch to strip SYN.

In addition, TCP stack can queue overlapping skb into recvq. Once rcv_nxt is updated with a new skb, BPF prog cannot infer the previous one from skb->len.

---
v2: Add explanation of tcp_bpf_rcvlowat() placement.

---
 include/net/tcp.h       | 12 ++++++++++++
 net/ipv4/tcp.c          |  2 ++
 net/ipv4/tcp_fastopen.c |  2 ++
 net/ipv4/tcp_input.c    | 10 ++++++++++
 4 files changed, 26 insertions(+)
include/net/tcp.h +12 -0
index bc95d8e7b62e..a409f2ea710f 100644
@@ -2889,12 +2889,24 @@ static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
 	skops->skb = skb;
 	skops->skb_data_end = skb->data + end_offset;
 }
+
+void bpf_skops_rcvlowat(struct sock *sk, struct sk_buff *skb);
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+	if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG))
+		bpf_skops_rcvlowat(sk, skb);
+}
 #else
 static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
 				      struct sk_buff *skb,
 				      unsigned int end_offset)
 {
 }
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+}
 #endif
 
 /* Call BPF_SOCK_OPS program that returns an int. If the return value
net/ipv4/tcp.c +2 -0
index 3afeb69a547a..f7e32891bb4e 100644
@@ -1602,6 +1602,8 @@ void __tcp_cleanup_rbuf(struct sock *sk, int copied)
 		tcp_mstamp_refresh(tp);
 		tcp_send_ack(sk);
 	}
+
+	tcp_bpf_rcvlowat(sk, NULL);
 }
 
 void tcp_cleanup_rbuf(struct sock *sk, int copied)
net/ipv4/tcp_fastopen.c +2 -0
index 471c78be5513..91bf421fc5b6 100644
@@ -281,6 +281,8 @@ void tcp_fastopen_add_skb(struct sock *sk, struct sk_buff *skb)
 	TCP_SKB_CB(skb)->seq++;
 	TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_SYN;
 
+	tcp_bpf_rcvlowat(sk, skb);
+
 	tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
 	tcp_add_receive_queue(sk, skb);
 	tp->syn_data_acked = 1;
net/ipv4/tcp_input.c +10 -0
index c4ba4f1e9d9e..477bcf2ba89d 100644
@@ -204,6 +204,12 @@ static void bpf_skops_established(struct sock *sk, int bpf_op,
 	/* sk with TCP_REPAIR_ON does not have skb in tcp_finish_connect */
 	bpf_skops_common_locked(sk, bpf_op, skb, skb ? tcp_hdrlen(skb) : 0);
 }
+
+void bpf_skops_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+	/* skb is NULL when called from __tcp_cleanup_rbuf(). */
+	bpf_skops_common_locked(sk, BPF_SOCK_OPS_RCVQ_CB, skb, 0);
+}
 #else
 static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
 {
@@ -5306,6 +5312,8 @@ static void tcp_ofo_queue(struct sock *sk)
 			continue;
 		}
 
+		tcp_bpf_rcvlowat(sk, skb);
+
 		tail = skb_peek_tail(&sk->sk_receive_queue);
 		eaten = tail && tcp_try_coalesce(sk, tail, skb, &fragstolen);
 		tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
@@ -5509,6 +5517,8 @@ static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb,
 	int eaten;
 	struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
 
+	tcp_bpf_rcvlowat(sk, skb);
+
 	eaten = (tail &&
 		 tcp_try_coalesce(sk, tail,
 				  skb, fragstolen)) ? 1 : 0;
Signature · 1 line
2.54.0.746.g67dd491aae-goog
#29 lore raw

Re: [PATCH v3 bpf-next 10/11] bpf: tcp: Add SOCK_OPS rcvlowat hook.

Quoted 79 lines · Kuniyuki Iwashima

Now, it is time to add the new hooks for BPF_SOCK_OPS_RCVQ_CB.

Let's invoke the BPF SOCK_OPS prog when

1. TCP stack enqueues skb to sk->sk_receive_queue

     -> tcp_queue_rcv(), tcp_ofo_queue(), and tcp_fastopen_add_skb()

2. TCP recvmsg() completes

     -> __tcp_cleanup_rbuf()

This will allow the BPF prog to parse each skb and dynamically adjust sk->sk_rcvlowat to suppress unnecessary EPOLLIN wakeups until sufficient data (e.g., a full RPC frame) is available in the receive queue.

Note that the direct access to bpf_sock_ops.data is intentionally disabled by passing 0 as end_offset.

Instead, the BPF prog is supposed to use bpf_skb_load_bytes() with bpf_sock_ops because payload is not in the linear area with TCP header/data split on and skb may contain a RPC descriptor in skb frag. This also simplifies the BPF prog.

The placement of tcp_bpf_rcvlowat() in tcp_ofo_queue() and tcp_fastopen_add_skb() is chosen to provide the same snapshot with tcp_queue_rcv().

For example, if tcp_bpf_rcvlowat() were called before updating TCP_SKB_CB(skb)->seq in tcp_fastopen_add_skb(), BPF prog would need to implement an unlikely if branch to strip SYN.

In addition, TCP stack can queue overlapping skb into recvq. Once rcv_nxt is updated with a new skb, BPF prog cannot infer the previous one from skb->len.

---
v2: Add explanation of tcp_bpf_rcvlowat() placement.

---
 include/net/tcp.h       | 12 ++++++++++++
 net/ipv4/tcp.c          |  2 ++
 net/ipv4/tcp_fastopen.c |  2 ++
 net/ipv4/tcp_input.c    | 10 ++++++++++
 4 files changed, 26 insertions(+)
include/net/tcp.h +12 -0
index bc95d8e7b62e..a409f2ea710f 100644
@@ -2889,12 +2889,24 @@ static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
 	skops->skb = skb;
 	skops->skb_data_end = skb->data + end_offset;
 }
+
+void bpf_skops_rcvlowat(struct sock *sk, struct sk_buff *skb);
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+	if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG))
+		bpf_skops_rcvlowat(sk, skb);
+}
 #else
 static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
 				      struct sk_buff *skb,
 				      unsigned int end_offset)
 {
 }
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+}
 #endif
 
 /* Call BPF_SOCK_OPS program that returns an int. If the return value
net/ipv4/tcp.c +0 -0
index 3afeb69a547a..f7e32891bb4e 100644

net/ipv4/tcp.c void __tcp_cleanup_rbuf(struct sock *sk, int copied) · line 1606

Quoted 5 lines
net/ipv4/tcp.c +2 -0
@@ -1602,6 +1602,8 @@ void __tcp_cleanup_rbuf(struct sock *sk, int copied)
 		tcp_mstamp_refresh(tp);
 		tcp_send_ack(sk);
 	}
+
+	tcp_bpf_rcvlowat(sk, NULL);

hmm... so NULL is a way for the bpf prog to tell where it is called?

With skb NULL, what does the bpf prog usually do?

author reviewer
#30 lore raw

Re: [PATCH v3 bpf-next 10/11] bpf: tcp: Add SOCK_OPS rcvlowat hook.

Quoted 75 lines · Martin KaFai Lau
Quoted 73 lines · Kuniyuki Iwashima

Now, it is time to add the new hooks for BPF_SOCK_OPS_RCVQ_CB.

Let's invoke the BPF SOCK_OPS prog when

1. TCP stack enqueues skb to sk->sk_receive_queue

     -> tcp_queue_rcv(), tcp_ofo_queue(), and tcp_fastopen_add_skb()

2. TCP recvmsg() completes

     -> __tcp_cleanup_rbuf()

This will allow the BPF prog to parse each skb and dynamically adjust sk->sk_rcvlowat to suppress unnecessary EPOLLIN wakeups until sufficient data (e.g., a full RPC frame) is available in the receive queue.

Note that the direct access to bpf_sock_ops.data is intentionally disabled by passing 0 as end_offset.

Instead, the BPF prog is supposed to use bpf_skb_load_bytes() with bpf_sock_ops because payload is not in the linear area with TCP header/data split on and skb may contain a RPC descriptor in skb frag. This also simplifies the BPF prog.

The placement of tcp_bpf_rcvlowat() in tcp_ofo_queue() and tcp_fastopen_add_skb() is chosen to provide the same snapshot with tcp_queue_rcv().

For example, if tcp_bpf_rcvlowat() were called before updating TCP_SKB_CB(skb)->seq in tcp_fastopen_add_skb(), BPF prog would need to implement an unlikely if branch to strip SYN.

In addition, TCP stack can queue overlapping skb into recvq. Once rcv_nxt is updated with a new skb, BPF prog cannot infer the previous one from skb->len.

---
v2: Add explanation of tcp_bpf_rcvlowat() placement.

---
 include/net/tcp.h       | 12 ++++++++++++
 net/ipv4/tcp.c          |  2 ++
 net/ipv4/tcp_fastopen.c |  2 ++
 net/ipv4/tcp_input.c    | 10 ++++++++++
 4 files changed, 26 insertions(+)
include/net/tcp.h +12 -0
index bc95d8e7b62e..a409f2ea710f 100644
@@ -2889,12 +2889,24 @@ static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
      skops->skb = skb;
      skops->skb_data_end = skb->data + end_offset;
 }
+
+void bpf_skops_rcvlowat(struct sock *sk, struct sk_buff *skb);
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+     if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG))
+             bpf_skops_rcvlowat(sk, skb);
+}
 #else
 static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
                                    struct sk_buff *skb,
                                    unsigned int end_offset)
 {
 }
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+}
 #endif
 
Quoted 13 lines

net/ipv4/tcp.c void __tcp_cleanup_rbuf(struct sock *sk, int copied) · line 1606

Quoted 11 lines
include/net/tcp.h +0 -0
 /* Call BPF_SOCK_OPS program that returns an int. If the return value
net/ipv4/tcp.c +2 -0
index 3afeb69a547a..f7e32891bb4e 100644
@@ -1602,6 +1602,8 @@ void __tcp_cleanup_rbuf(struct sock *sk, int copied)
              tcp_mstamp_refresh(tp);
              tcp_send_ack(sk);
      }
+
+     tcp_bpf_rcvlowat(sk, NULL);

hmm... so NULL is a way for the bpf prog to tell where it is called?

Yes. The selftest fetches bpf_cast_to_kern_ctx(ops)->skb first to check it since we need to access skb->cb anyway to read TCP_SKB_CB()->{seq,end_seq} for non-NULL case.

Quoted 2 lines

With skb NULL, what does the bpf prog usually do?

In that case, the prog reads tp->copied_seq and some sequence numbers from sk local storage and calls kfunc to adjust sk->sk_rcvlowat.

#31 lore raw

Re: [PATCH v3 bpf-next 10/11] bpf: tcp: Add SOCK_OPS rcvlowat hook.

a

Quoted 6 lines · Kuniyuki Iwashima
Quoted 4 lines · Martin KaFai Lau
Quoted 2 lines · Kuniyuki Iwashima

Now, it is time to add the new hooks for BPF_SOCK_OPS_RCVQ_CB.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

Let's invoke the BPF SOCK_OPS prog when

1. TCP stack enqueues skb to sk->sk_receive_queue

     -> tcp_queue_rcv(), tcp_ofo_queue(), and tcp_fastopen_add_skb()

2. TCP recvmsg() completes

     -> __tcp_cleanup_rbuf()

Not sure if this is just me, but having to differentiating call sites by checking if skb == NULL seems a bit less ideal (feels a bit arbitrary and may be restrictive to extend in the future)

If new sockops is going to be built on top of bpf_tcp_ops, it would be more obvious as different call sites will be different struct_ops op. Although arguably tcp_queue_rcv(), tcp_ofo_queue(), and tcp_fastopen_add_skb() may share the same struct_ops op.

Quoted 89 lines
Quoted 64 lines
Quoted 64 lines

This will allow the BPF prog to parse each skb and dynamically adjust sk->sk_rcvlowat to suppress unnecessary EPOLLIN wakeups until sufficient data (e.g., a full RPC frame) is available in the receive queue.

Note that the direct access to bpf_sock_ops.data is intentionally disabled by passing 0 as end_offset.

Instead, the BPF prog is supposed to use bpf_skb_load_bytes() with bpf_sock_ops because payload is not in the linear area with TCP header/data split on and skb may contain a RPC descriptor in skb frag. This also simplifies the BPF prog.

The placement of tcp_bpf_rcvlowat() in tcp_ofo_queue() and tcp_fastopen_add_skb() is chosen to provide the same snapshot with tcp_queue_rcv().

For example, if tcp_bpf_rcvlowat() were called before updating TCP_SKB_CB(skb)->seq in tcp_fastopen_add_skb(), BPF prog would need to implement an unlikely if branch to strip SYN.

In addition, TCP stack can queue overlapping skb into recvq. Once rcv_nxt is updated with a new skb, BPF prog cannot infer the previous one from skb->len.

---
v2: Add explanation of tcp_bpf_rcvlowat() placement.

---
 include/net/tcp.h       | 12 ++++++++++++
 net/ipv4/tcp.c          |  2 ++
 net/ipv4/tcp_fastopen.c |  2 ++
 net/ipv4/tcp_input.c    | 10 ++++++++++
 4 files changed, 26 insertions(+)
include/net/tcp.h +12 -0
index bc95d8e7b62e..a409f2ea710f 100644
@@ -2889,12 +2889,24 @@ static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
      skops->skb = skb;
      skops->skb_data_end = skb->data + end_offset;
 }
+
+void bpf_skops_rcvlowat(struct sock *sk, struct sk_buff *skb);
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+     if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG))
+             bpf_skops_rcvlowat(sk, skb);
+}
 #else
 static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
                                    struct sk_buff *skb,
                                    unsigned int end_offset)
 {
 }
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+}
 #endif
 
Quoted 13 lines

net/ipv4/tcp.c void __tcp_cleanup_rbuf(struct sock *sk, int copied) · line 1606

Quoted 11 lines
include/net/tcp.h +0 -0
 /* Call BPF_SOCK_OPS program that returns an int. If the return value
net/ipv4/tcp.c +2 -0
index 3afeb69a547a..f7e32891bb4e 100644
@@ -1602,6 +1602,8 @@ void __tcp_cleanup_rbuf(struct sock *sk, int copied)
              tcp_mstamp_refresh(tp);
              tcp_send_ack(sk);
      }
+
+     tcp_bpf_rcvlowat(sk, NULL);

hmm... so NULL is a way for the bpf prog to tell where it is called?

Yes. The selftest fetches bpf_cast_to_kern_ctx(ops)->skb first to check it since we need to access skb->cb anyway to read TCP_SKB_CB()->{seq,end_seq} for non-NULL case.

Quoted 2 lines

With skb NULL, what does the bpf prog usually do?

In that case, the prog reads tp->copied_seq and some sequence numbers from sk local storage and calls kfunc to adjust sk->sk_rcvlowat.

author reviewer
#32 lore raw

Re: [PATCH v3 bpf-next 10/11] bpf: tcp: Add SOCK_OPS rcvlowat hook.

Quoted 15 lines · Amery Hung

a

Quoted 11 lines · Kuniyuki Iwashima
Quoted 9 lines · Martin KaFai Lau
Quoted 7 lines · Kuniyuki Iwashima

Now, it is time to add the new hooks for BPF_SOCK_OPS_RCVQ_CB.

Let's invoke the BPF SOCK_OPS prog when

1. TCP stack enqueues skb to sk->sk_receive_queue

     -> tcp_queue_rcv(), tcp_ofo_queue(), and tcp_fastopen_add_skb()
Quoted 6 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

2. TCP recvmsg() completes

     -> __tcp_cleanup_rbuf()

Not sure if this is just me, but having to differentiating call sites by checking if skb == NULL seems a bit less ideal (feels a bit arbitrary and may be restrictive to extend in the future)

I think Martin shares the feeling :)

I chose the way for two reasons: 1) bpf_skops_established() already accepts null skb (for unlikely TCP_REPAIR_ON), and
2) adding another op just for the case seems redundant (it adds more conditionals in the fast path, kfunc) while bpf prog is capable of distinguishing a null skb.

Quoted 5 lines

If new sockops is going to be built on top of bpf_tcp_ops, it would be more obvious as different call sites will be different struct_ops op. Although arguably tcp_queue_rcv(), tcp_ofo_queue(), and tcp_fastopen_add_skb() may share the same struct_ops op.

Yes, this sounds fascinating.

Quoted 90 lines
Quoted 90 lines
Quoted 65 lines
Quoted 65 lines

This will allow the BPF prog to parse each skb and dynamically adjust sk->sk_rcvlowat to suppress unnecessary EPOLLIN wakeups until sufficient data (e.g., a full RPC frame) is available in the receive queue.

Note that the direct access to bpf_sock_ops.data is intentionally disabled by passing 0 as end_offset.

Instead, the BPF prog is supposed to use bpf_skb_load_bytes() with bpf_sock_ops because payload is not in the linear area with TCP header/data split on and skb may contain a RPC descriptor in skb frag. This also simplifies the BPF prog.

The placement of tcp_bpf_rcvlowat() in tcp_ofo_queue() and tcp_fastopen_add_skb() is chosen to provide the same snapshot with tcp_queue_rcv().

For example, if tcp_bpf_rcvlowat() were called before updating TCP_SKB_CB(skb)->seq in tcp_fastopen_add_skb(), BPF prog would need to implement an unlikely if branch to strip SYN.

In addition, TCP stack can queue overlapping skb into recvq. Once rcv_nxt is updated with a new skb, BPF prog cannot infer the previous one from skb->len.

---
v2: Add explanation of tcp_bpf_rcvlowat() placement.

---
 include/net/tcp.h       | 12 ++++++++++++
 net/ipv4/tcp.c          |  2 ++
 net/ipv4/tcp_fastopen.c |  2 ++
 net/ipv4/tcp_input.c    | 10 ++++++++++
 4 files changed, 26 insertions(+)
include/net/tcp.h +12 -0
index bc95d8e7b62e..a409f2ea710f 100644
@@ -2889,12 +2889,24 @@ static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
      skops->skb = skb;
      skops->skb_data_end = skb->data + end_offset;
 }
+
+void bpf_skops_rcvlowat(struct sock *sk, struct sk_buff *skb);
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+     if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_RCVQ_CB_FLAG))
+             bpf_skops_rcvlowat(sk, skb);
+}
 #else
 static inline void bpf_skops_init_skb(struct bpf_sock_ops_kern *skops,
                                    struct sk_buff *skb,
                                    unsigned int end_offset)
 {
 }
+
+static inline void tcp_bpf_rcvlowat(struct sock *sk, struct sk_buff *skb)
+{
+}
 #endif
 
Quoted 13 lines

net/ipv4/tcp.c void __tcp_cleanup_rbuf(struct sock *sk, int copied) · line 1606

Quoted 11 lines
include/net/tcp.h +0 -0
 /* Call BPF_SOCK_OPS program that returns an int. If the return value
net/ipv4/tcp.c +2 -0
index 3afeb69a547a..f7e32891bb4e 100644
@@ -1602,6 +1602,8 @@ void __tcp_cleanup_rbuf(struct sock *sk, int copied)
              tcp_mstamp_refresh(tp);
              tcp_send_ack(sk);
      }
+
+     tcp_bpf_rcvlowat(sk, NULL);

hmm... so NULL is a way for the bpf prog to tell where it is called?

Yes. The selftest fetches bpf_cast_to_kern_ctx(ops)->skb first to check it since we need to access skb->cb anyway to read TCP_SKB_CB()->{seq,end_seq} for non-NULL case.

Quoted 2 lines

With skb NULL, what does the bpf prog usually do?

In that case, the prog reads tp->copied_seq and some sequence numbers from sk local storage and calls kfunc to adjust sk->sk_rcvlowat.

author reviewer
#33 lore raw

PATCH v3 11/11 selftest: bpf: Add test for BPF_SOCK_OPS_RCVQ_CB.

In reply to Kuniyuki Iwashima

The test is roughly divided into two stages, and the sequence is as follows:

I) Setup

1. Attach two BPF programs to a cgroup
2. Establish a TCP connection (@client <-> @child) within the cgroup
3. Enable BPF_SOCK_OPS_RCVQ_CB on @child

II) RPC frame exchange in various patterns

4. Send a partial RPC descriptor from @client to @child
5. Verify that epoll does NOT wake up @child
6. Send the remaining data of the RPC frame
7. Verify that epoll finally wakes up @child

During setup, two BPF programs are attached to simulate a real-world scenario; one is SOCK_OPS and the other is CGROUP_SOCKOPT.

While the SOCK_OPS prog handles the dynamic adjustment of sk->sk_rcvlowat, the CGROUP_SOCKOPT prog is used to enable BPF_SOCK_OPS_RCVQ_CB via userspace setsockopt() using pseudo options:

  #define SOL_BPF               0xdeadbeef
  #define BPF_TCP_AUTOLOWAT     0x8badf00d

  setsockopt(fd, SOL_BPF, BPF_TCP_AUTOLOWAT, &(int){1}, sizeof(int));

This reflects a common production use case where an application decides to start parsing RPC frames only at a certain point in the stream (e.g., after HTTP Upgrade), rather than immediately after TCP 3WHS (BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB, etc).

When BPF_TCP_AUTOLOWAT is enabled, the BPF prog initialises sk_local_storage for two sequence numbers to manage its state.

Then, for the RPC frame exchange, this test uses a simple format defined as follows

0 8 16 24 32

  +--------+--------+-------+--------+ `.
  |            header size           |  |
  +--------+--------+-------+--------+   > RPC descriptor (8 bytes)
  |            payload size          |  |
  +--------+--------+-------+--------+ .'
  ~               header             ~
  +--------+--------+-------+--------+
  ~               payload            ~
  +--------+--------+-------+--------+

Every time a new skb is enqueued to sk->sk_receive_queue, the SOCK_OPS prog parses it and updates these sequence numbers:

rpc_desc_seq : the SEQ # of the start of the RPC descriptor rpc_end_seq : the SEQ # of the end of the RPC frame
=> rpc_desc_seq + 8 + header size + payload size

Assume we receive two RPC descriptors in the following pattern:

1. When we receive skb-1, only a part of RPC descriptor is parsed. rpc_desc_seq is set to the first byte while rpc_end_seq is unknown. Thus, sk->sk_rcvlowat is set to the size of the RPC descriptor (8 bytes).

<- skb-1 -> <---- skb-2 ----> <------ skb-3 ----->

  +-----------+.................+....................+......
  |  RPC desc 1  |  header + payload  |  RPC desc 2  | ...
  +-----------+.................+....................+......
  ^              ^-.
  `- rpc_desc_seq   `- sk->sk_rcvlowat

2. Next, we receive skb-2, which completes the first RPC descriptor.

     Now rpc_end_seq is known, so sk->sk_rcvlowat is advanced to it.

<- skb-1 -> <---- skb-2 ----> <------ skb-3 ----->

  +-----------+-----------------+....................+......
  |  RPC desc 1  |  header + payload  |  RPC desc 2  | ...
  +-----------+-----------------+....................+......
  ^                                   ^
  '- rpc_desc_seq                     '- rpc_end_seq
                                           & sk->sk_rcvlowat

3. Once we receive skb-3, which contains the next full RPC descriptor, rpc_desc_seq is advanced and rpc_end_seq is updated according to the size of RPC frame 2.

Note that sk->sk_rcvlowat is NOT updated to the new rpc_end_seq yet. This ensures that the application is woken up to read the already complete RPC frame 1.

<- skb-1 -> <---- skb-2 ----> <------ skb-3 ----->

  +-----------+-----------------+--------------------+......
  |  RPC desc 1  |  header + payload  |  RPC desc 2  | ...   |
  +-----------+-----------------+--------------------+......
                                      ^                      ^
              rpc_desc_seq -----------'  rpc_end_seq ----...-'
                & sk->sk_rcvlowat

This sequence corresponds to the 4th test case in rpc_test_cases[], and we can see helpful output if we "#define DEBUG":

  # cat /sys/kernel/tracing/trace_pipe | \
    awk '{ if ($0 ~ /AF_/) sub(/^.*AF_/, "AF_"); print $0 }' & \
    BGPID=$!; ./test_progs -t tcp_autolowat; kill -9 -$BGPID
  ...
  AF_INET6 rpc_test_cases[3]: Start parsing skb: seq: 0, end_seq: 1, len: 1, rpc_desc_seq: 0, rpc_end_seq: 0, rpc_buff_len: 0
  AF_INET6 rpc_test_cases[3]: Copied 1 bytes: rpc_desc_buff_len: 1
  AF_INET6 rpc_test_cases[3]: Setting rcvlowat: tp->copied_seq: 0, rpc_desc_seq: 0, rpc_end_seq: 0, rpc_desc_buff_len: 1
  AF_INET6 rpc_test_cases[3]: Set rcvlowat: expected: 8, actual: 8

AF_INET6 rpc_test_cases[3]: Start parsing skb: seq: 1, end_seq: 8, len: 7, rpc_desc_seq: 0, rpc_end_seq: 0, rpc_buff_len: 1 AF_INET6 rpc_test_cases[3]: Copied full descriptor: rpc_desc_seq: 0, rpc_end_seq: 258, header_len: 100, payload_len: 150 AF_INET6 rpc_test_cases[3]: No more descriptor: rpc_end_seq: 258, end_seq: 8
AF_INET6 rpc_test_cases[3]: Setting rcvlowat: tp->copied_seq: 0, rpc_desc_seq: 0, rpc_end_seq: 258, rpc_desc_buff_len: 8 AF_INET6 rpc_test_cases[3]: Set rcvlowat: expected: 258, actual: 258
...

---
v2:
* Make copy_len u64 and swap validation order for it

    for no_alu32.
---
 tools/testing/selftests/bpf/bpf_kfuncs.h      |   4 +
 .../selftests/bpf/prog_tests/tcp_autolowat.c  | 350 ++++++++++++++++++
 .../selftests/bpf/progs/bpf_tracing_net.h     |   2 +
 .../selftests/bpf/progs/tcp_autolowat.c       | 326 ++++++++++++++++
 4 files changed, 682 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c
 create mode 100644 tools/testing/selftests/bpf/progs/tcp_autolowat.c
tools/testing/selftests/bpf/bpf_kfuncs.h +4 -0
index ae71e9b69051..fc4d6f68f247 100644
@@ -64,6 +64,10 @@ struct bpf_tcp_req_attrs;
 extern int bpf_sk_assign_tcp_reqsk(struct __sk_buff *skb, struct sock *sk,
 				   struct bpf_tcp_req_attrs *attrs, int attrs__sz) __ksym;
 
+struct bpf_sock_ops_kern;
+extern int bpf_sock_ops_tcp_set_rcvlowat(struct bpf_sock_ops_kern *skops_kern,
+					 int rcvlowat) __ksym;
+
 void *bpf_cast_to_kern_ctx(void *) __ksym;
 
 extern void *bpf_rdonly_cast(const void *obj, __u32 btf_id) __ksym __weak;
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +350 -0

350 lines not on this page · raw message

tools/testing/selftests/bpf/progs/bpf_tracing_net.h +2 -0
index d8dacef37c16..bdf28d320383 100644
@@ -74,6 +74,8 @@
 
 #define NEXTHDR_TCP		6
 
+#define TCPHDR_FIN		0x01
+
 #define TCPOPT_NOP		1
 #define TCPOPT_EOL		0
 #define TCPOPT_MSS		2
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +326 -0

326 lines not on this page · raw message

Signature · 1 line
2.54.0.746.g67dd491aae-goog
#34 lore raw

Re: [PATCH v3 bpf-next 11/11] selftest: bpf: Add test for BPF_SOCK_OPS_RCVQ_CB.

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Medium] The test case incorrectly asserts that `SO_RCVLOWAT` is automatically updated to `RPC_DESC_SIZE`…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Medium] The test case incorrectly asserts that SO_RCVLOWAT is automatically updated to RPC_DESC_SIZE (8) immediately after recv() reads the first RPC frame.
- [Low] Multi-line comments do not follow the mandatory BPF subsystem style.
- [Low] Incorrect ASSERT macros used for file descriptor validation.
--

commit ab873db7faa26eaced426077409e35dd60974a4f
Author: Kuniyuki Iwashima <[email protected]>
Subject: selftest: bpf: Add test for BPF_SOCK_OPS_RCVQ_CB.

This commit introduces a new selftest for the BPF_SOCK_OPS_RCVQ_CB hook. It simulates an RPC frame exchange over TCP to verify that a BPF program can dynamically adjust sk_rcvlowat and properly control epoll wakeups.

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +0 -0
new file mode 100644
index 0000000000000..5e971c42a32a4

[ ... ]

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +7 -0
+	{
+		.desc = {
+			{.header_len = 100, .payload_len = 150},
+			{.header_len = 200, .payload_len = 500},
+		},
+		.event = {
+			{ .type = RPC_EVENT_AUTOLOWAT,	.val = 1},

[ ... ]

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 119

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +8 -0
+			/* skb has the first payload and 1 byte of the next descriptor. */
+			{.type = RPC_EVENT_SEND,	.len = 150 + 1},
+			{.type = RPC_EVENT_EPOLL,	.nfds = 1},
+			{.type = RPC_EVENT_RCVLOWAT,	.rcvlowat = RPC_DESC_SIZE + 150 + 100},
+			/* After reading the first RPC message, SO_RCVLOWAT should be RPC_DESC_SIZE. */
+			{.type = RPC_EVENT_RECV,	.len = RPC_DESC_SIZE + 150 + 100},
+			{.type = RPC_EVENT_EPOLL,	.nfds = 0},
+			{.type = RPC_EVENT_RCVLOWAT,	.rcvlowat = RPC_DESC_SIZE},

[Severity: Medium]
Does this assertion accurately reflect the kernel's behavior?

The test calls recv() here, which executes in process context. However, tcp_recvmsg() does not trigger the BPF_SOCK_OPS_RCVQ_CB hook, as that hook only runs when new SKBs are enqueued from the network stack.

Since no new network packet has arrived yet, the BPF program hasn't run to update sk->sk_rcvlowat. Could this cause sk->sk_rcvlowat to remain at 258 instead of dropping to 8 (RPC_DESC_SIZE), resulting in a test failure here?

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +7 -0
+			/* The second descriptor is available. */
+			{.type = RPC_EVENT_SEND,	.len = RPC_DESC_SIZE - 1},
+			{.type = RPC_EVENT_EPOLL,	.nfds = 0},
+			{.type = RPC_EVENT_RCVLOWAT,	.rcvlowat = RPC_DESC_SIZE + 200 + 500},
+		},
+	},
+};

[ ... ]

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 166

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +11 -0
+static int tcp_autolowat_setup_cb(struct tcp_autolowat_test_cb *cb, int family)
+{
+	struct epoll_event ev = {};
+	int err;
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(cb->fd); i++)
+		cb->fd[i] = -1;
+
+	cb->saved_netns = open("/proc/self/ns/net", O_RDONLY);
+	if (!ASSERT_NEQ(cb->saved_netns, -1, "save netns"))

[Severity: Low]
Is it preferred to use the ASSERT_OK_FD() macro here instead of ASSERT_NEQ() for file descriptor validation, to better align with modern BPF selftest patterns?

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 178

Quoted 12 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +12 -0
+		goto err;
+
+	err = unshare(CLONE_NEWNET);
+	if (!ASSERT_OK(err, "unshare"))
+		goto err;
+
+	err = system("ip link set dev lo up");
+	if (!ASSERT_OK(err, "set up lo"))
+		goto err;
+
+	cb->server = start_server(family, SOCK_STREAM, NULL, 0, 0);
+	if (!ASSERT_NEQ(cb->server, -1, "start_server"))

[Severity: Low]
Similarly, could this use ASSERT_OK_FD() as well? This pattern is repeated for connect_to_fd(), accept(), and epoll_create1() below.

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +2 -0
+		goto err;
+

[ ... ]

Quoted 5 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +0 -0
new file mode 100644
index 0000000000000..41eacfdb34aa1

[ ... ]

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 79

Quoted 4 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +4 -0
+	/* Since LLVM commit 324e27e8bad83ca23a3cd276d7e2e729b1b0b8c7,
+	 * clang omits the "copy_len == 0" check below, which is necessary
+	 * to satisfy the BPF verifier's range check for bpf_skb_load_bytes().
+	 */

[Severity: Low]
This isn't a bug, but could we update these multi-line comments to follow the preferred BPF subsystem style, where the opening /* is placed on its own line?

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 84

Quoted 5 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +5 -0
+	barrier_var(copy_len);
+
+	/* Do not swap the order of the two copy_len checks below.
+	 * The BPF verifier somehow does not properly track the minimum
+	 * value for 'copy_len == 0'.

[Severity: Low]
This isn't a bug, but this comment also starts the text on the same line as the opening /*.

Quoted 6 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +6 -0
+	 *
+	 * 91: (15) if r7 == 0x0 goto pc+40      ; R7=scalar(smin=smin32=-247,smax=smax32=8)
+	 * 92: (25) if r7 > 0x8 goto pc+39       ; R7=scalar(smin=smin32=0,smax=umax=smax32=umax32=8,var_off=(0x0; 0xf))
+	 *
+	 * This does not occur if copy_len is u32.
+	 */
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
author reviewer
#35 lore raw

Re: [PATCH v3 bpf-next 11/11] selftest: bpf: Add test for BPF_SOCK_OPS_RCVQ_CB.

Quoted 42 lines · On Sat, May 23, 2026 at 2:12 AM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Medium] The test case incorrectly asserts that SO_RCVLOWAT is automatically updated to RPC_DESC_SIZE (8) immediately after recv() reads the first RPC frame.
- [Low] Multi-line comments do not follow the mandatory BPF subsystem style.
- [Low] Incorrect ASSERT macros used for file descriptor validation.
--

commit ab873db7faa26eaced426077409e35dd60974a4f
Author: Kuniyuki Iwashima <[email protected]>
Subject: selftest: bpf: Add test for BPF_SOCK_OPS_RCVQ_CB.

This commit introduces a new selftest for the BPF_SOCK_OPS_RCVQ_CB hook. It simulates an RPC frame exchange over TCP to verify that a BPF program can dynamically adjust sk_rcvlowat and properly control epoll wakeups.

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +0 -0
new file mode 100644
index 0000000000000..5e971c42a32a4

[ ... ]

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +7 -0
+     {
+             .desc = {
+                     {.header_len = 100, .payload_len = 150},
+                     {.header_len = 200, .payload_len = 500},
+             },
+             .event = {
+                     { .type = RPC_EVENT_AUTOLOWAT,  .val = 1},

[ ... ]

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 119

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +8 -0
+                     /* skb has the first payload and 1 byte of the next descriptor. */
+                     {.type = RPC_EVENT_SEND,        .len = 150 + 1},
+                     {.type = RPC_EVENT_EPOLL,       .nfds = 1},
+                     {.type = RPC_EVENT_RCVLOWAT,    .rcvlowat = RPC_DESC_SIZE + 150 + 100},
+                     /* After reading the first RPC message, SO_RCVLOWAT should be RPC_DESC_SIZE. */
+                     {.type = RPC_EVENT_RECV,        .len = RPC_DESC_SIZE + 150 + 100},
+                     {.type = RPC_EVENT_EPOLL,       .nfds = 0},
+                     {.type = RPC_EVENT_RCVLOWAT,    .rcvlowat = RPC_DESC_SIZE},
Quoted 6 lines

[Severity: Medium]
Does this assertion accurately reflect the kernel's behavior?

The test calls recv() here, which executes in process context. However, tcp_recvmsg() does not trigger the BPF_SOCK_OPS_RCVQ_CB hook, as that hook only runs when new SKBs are enqueued from the network stack.

This is similarly wrong. I don't know why AI thought the hook is not called from recvmsg() since it's overly explained in multiple commits.

Quoted 15 lines

Since no new network packet has arrived yet, the BPF program hasn't run to update sk->sk_rcvlowat. Could this cause sk->sk_rcvlowat to remain at 258 instead of dropping to 8 (RPC_DESC_SIZE), resulting in a test failure here?

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +7 -0
+                     /* The second descriptor is available. */
+                     {.type = RPC_EVENT_SEND,        .len = RPC_DESC_SIZE - 1},
+                     {.type = RPC_EVENT_EPOLL,       .nfds = 0},
+                     {.type = RPC_EVENT_RCVLOWAT,    .rcvlowat = RPC_DESC_SIZE + 200 + 500},
+             },
+     },
+};

[ ... ]

Quoted 16 lines

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 166

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +11 -0
+static int tcp_autolowat_setup_cb(struct tcp_autolowat_test_cb *cb, int family)
+{
+     struct epoll_event ev = {};
+     int err;
+     int i;
+
+     for (i = 0; i < ARRAY_SIZE(cb->fd); i++)
+             cb->fd[i] = -1;
+
+     cb->saved_netns = open("/proc/self/ns/net", O_RDONLY);
+     if (!ASSERT_NEQ(cb->saved_netns, -1, "save netns"))

[Severity: Low]
Is it preferred to use the ASSERT_OK_FD() macro here instead of ASSERT_NEQ() for file descriptor validation, to better align with modern BPF selftest patterns?

Will use ASSERT_OK_FD().

Quoted 60 lines

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 178

Quoted 13 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +12 -0
+             goto err;
+
+     err = unshare(CLONE_NEWNET);
+     if (!ASSERT_OK(err, "unshare"))
+             goto err;
+
+     err = system("ip link set dev lo up");
+     if (!ASSERT_OK(err, "set up lo"))
+             goto err;
+
+     cb->server = start_server(family, SOCK_STREAM, NULL, 0, 0);
+     if (!ASSERT_NEQ(cb->server, -1, "start_server"))

[Severity: Low]
Similarly, could this use ASSERT_OK_FD() as well? This pattern is repeated for connect_to_fd(), accept(), and epoll_create1() below.

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +2 -0
+             goto err;
+

[ ... ]

Quoted 5 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +0 -0
new file mode 100644
index 0000000000000..41eacfdb34aa1

[ ... ]

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 79

Quoted 4 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +4 -0
+     /* Since LLVM commit 324e27e8bad83ca23a3cd276d7e2e729b1b0b8c7,
+      * clang omits the "copy_len == 0" check below, which is necessary
+      * to satisfy the BPF verifier's range check for bpf_skb_load_bytes().
+      */

[Severity: Low]
This isn't a bug, but could we update these multi-line comments to follow the preferred BPF subsystem style, where the opening /* is placed on its own line?

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 84

Quoted 5 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +5 -0
+     barrier_var(copy_len);
+
+     /* Do not swap the order of the two copy_len checks below.
+      * The BPF verifier somehow does not properly track the minimum
+      * value for 'copy_len == 0'.

[Severity: Low]
This isn't a bug, but this comment also starts the text on the same line as the opening /*.

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 90

Quoted 6 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +6 -0
+      *
+      * 91: (15) if r7 == 0x0 goto pc+40      ; R7=scalar(smin=smin32=-247,smax=smax32=8)
+      * 92: (25) if r7 > 0x8 goto pc+39       ; R7=scalar(smin=smin32=0,smax=umax=smax32=umax32=8,var_off=(0x0; 0xf))
+      *
+      * This does not occur if copy_len is u32.
+      */

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11

#36 lore raw

Re: [PATCH v3 bpf-next 11/11] selftest: bpf: Add test for BPF_SOCK_OPS_RCVQ_CB.

In reply to Kuniyuki Iwashima
Does calling recv() actually trigger the BPF program to update SO_RCVLOWAT?
Quoted 14 lines
tools/testing/selftests/bpf/bpf_kfuncs.h +4 -0
@@ -64,6 +64,10 @@
 extern int bpf_sk_assign_tcp_reqsk(struct __sk_buff *skb, struct sock *sk,
 				   struct bpf_tcp_req_attrs *attrs, int attrs__sz) __ksym;
 
+struct bpf_sock_ops_kern;
+extern int bpf_sock_ops_tcp_set_rcvlowat(struct bpf_sock_ops_kern *skops_kern,
+					 int rcvlowat) __ksym;
+
 void *bpf_cast_to_kern_ctx(void *) __ksym;
 
 extern void *bpf_rdonly_cast(const void *obj, __u32 btf_id) __ksym __weak;

[ ... ]

Quoted 12 lines
tools/testing/selftests/bpf/progs/bpf_tracing_net.h +2 -0
@@ -74,6 +74,8 @@ #define ETH_P_IPV6		0x86DD
 
 #define NEXTHDR_TCP		6
 
+#define TCPHDR_FIN		0x01
+
 #define TCPOPT_NOP		1
 #define TCPOPT_EOL		0
 #define TCPOPT_MSS		2

[ ... ]

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +0 -0
@@ -0,0 +1,350 @@

[ ... ]

Quoted 12 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +12 -0
+		.event = {
+			{ .type = RPC_EVENT_AUTOLOWAT,	.val = 1},
+			/* The first descriptor is partial. */
+			{.type = RPC_EVENT_SEND,	.len = 1},
+			{.type = RPC_EVENT_EPOLL,	.nfds = 0},
+			{.type = RPC_EVENT_RCVLOWAT,	.rcvlowat = RPC_DESC_SIZE},
+			/* The first descriptor is available. */
+			{.type = RPC_EVENT_SEND,	.len = RPC_DESC_SIZE - 1},
+			{.type = RPC_EVENT_EPOLL,	.nfds = 0},
+			{.type = RPC_EVENT_RCVLOWAT,	.rcvlowat = RPC_DESC_SIZE + 150 + 100},
+			/* The first header is ready. */
+			{.type = RPC_EVENT_SEND,	.len = 100},

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 119

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +10 -0
+			{.type = RPC_EVENT_EPOLL,	.nfds = 0},
+			{.type = RPC_EVENT_RCVLOWAT,	.rcvlowat = RPC_DESC_SIZE + 150 + 100},
+			/* skb has the first payload and 1 byte of the next descriptor. */
+			{.type = RPC_EVENT_SEND,	.len = 150 + 1},
+			{.type = RPC_EVENT_EPOLL,	.nfds = 1},
+			{.type = RPC_EVENT_RCVLOWAT,	.rcvlowat = RPC_DESC_SIZE + 150 + 100},
+			/* After reading the first RPC message, SO_RCVLOWAT should be RPC_DESC_SIZE. */
+			{.type = RPC_EVENT_RECV,	.len = RPC_DESC_SIZE + 150 + 100},
+			{.type = RPC_EVENT_EPOLL,	.nfds = 0},
+			{.type = RPC_EVENT_RCVLOWAT,	.rcvlowat = RPC_DESC_SIZE},

Does calling recv() actually trigger the BPF program to update SO_RCVLOWAT?

Since the kernel only invokes BPF_SOCK_OPS_RCVQ_CB when a new skb is added to the receive queue, and not when data is dequeued via recv(), the BPF program doesn't seem to run here.

Could this cause the test to fail unconditionally because sk_rcvlowat retains its previous value?

Reference: https://lore.kernel.org/bpf/[email protected]/
Reviewer: [email protected] (Fri, 22 May 2026 08:35:27 +0000)

[ ... ]

Quoted 20 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +20 -0
+static void tcp_autolowat_run_rpc_test(struct tcp_autolowat_test_cb *cb,
+				       struct rpc_test_case *test_case)
+{
+	struct rpc_event *event = test_case->event;
+	char *ptr = test_case->data;
+	struct epoll_event ev;
+	socklen_t optlen;
+	int err, optval;
+	char buf[4096];
+
+	if (tcp_autolowat_build_data(test_case))
+		return;
+
+	while (1) {
+		switch (event->type) {
+		case RPC_EVENT_END:
+			return;
+		case RPC_EVENT_AUTOLOWAT:
+			err = setsockopt(cb->child, SOL_BPF, BPF_TCP_AUTOLOWAT,
+					 &event->val, sizeof(event->val));

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 262

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +10 -0
+			if (!ASSERT_OK(err, "setsockopt"))
+				return;
+			break;
+		case RPC_EVENT_SEND:
+			err = send(cb->client, ptr, event->len, 0);
+			if (!ASSERT_EQ(err, event->len, "send"))
+				return;
+
+			ptr += event->len;
+			break;

Could this lead to race conditions causing flaky tests?

The test calls send() to transmit data and immediately executes the next event. Because network transmission over the loopback interface involves asynchronous softirq processing, send() might return before the packet is fully processed by the receiving socket.

If the next event is RPC_EVENT_EPOLL with a timeout of 0, could epoll_wait() prematurely return 0? Similarly, for RPC_EVENT_RCVLOWAT, could getsockopt() read a stale sk_rcvlowat value before the TCP stack and BPF program have finished processing the packet?

Reference: https://lore.kernel.org/bpf/[email protected]/
Reviewer: [email protected] (Fri, 22 May 2026 08:35:27 +0000)

[ ... ]

Quoted 4 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +0 -0
@@ -0,0 +1,326 @@

[ ... ]

Quoted 11 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +11 -0
+static int tcp_parse_descriptor(struct bpf_sock_ops *skops,
+				struct tcp_autolowat_cb *cb,
+				u32 seq, u32 end_seq)
+{
+	struct rpc_descriptor *rpc_desc;
+	u32 rpc_copied_seq;
+	u64 copy_len; /* u32 should work, but not for no_alu32 :/ */
+	u64 rpc_len;
+	int err;
+
+	rpc_copied_seq = cb->rpc_desc_seq + cb->rpc_desc_buff_len;

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 79

Quoted 10 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +10 -0
+
+	if (before(cb->rpc_desc_seq + RPC_DESC_SIZE, end_seq))
+		copy_len = RPC_DESC_SIZE - cb->rpc_desc_buff_len;
+	else
+		copy_len = end_seq - rpc_copied_seq;
+
+	/* Since LLVM commit 324e27e8bad83ca23a3cd276d7e2e729b1b0b8c7,
+	 * clang omits the "copy_len == 0" check below, which is necessary
+	 * to satisfy the BPF verifier's range check for bpf_skb_load_bytes().
+	 */

This isn't a bug, but multi-line comments in the BPF subsystem are expected to have the opening '/*' on its own line:

	/*
	 * Since LLVM commit ...
	 * ...
	 */

Reference: https://lore.kernel.org/bpf/[email protected]/
Reviewer: [email protected] (Fri, 22 May 2026 08:35:27 +0000)

[ ... ]

Quoted 6 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +6 -0
+static void tcp_set_autolowat(struct bpf_sock_ops_kern *skops_kern,
+			      struct tcp_autolowat_cb *cb,
+			      struct tcp_sock *tp)
+{
+	/* To handle wraparound. */
+	u32 val = 0;

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 146

Quoted 10 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +10 -0
+
+	LOG("Setting rcvlowat: tp->copied_seq: %u, rpc_desc_seq: %u, rpc_end_seq: %u, rpc_desc_buff_len: %u",
+	    TP_SEQ(copied_seq), CB_SEQ(rpc_desc_seq), CB_SEQ(rpc_end_seq), cb->rpc_desc_buff_len);
+
+	if (before(tp->copied_seq, cb->rpc_desc_seq))
+		val = cb->rpc_desc_seq - tp->copied_seq;
+	else if (cb->rpc_desc_buff_len != RPC_DESC_SIZE)
+		val = RPC_DESC_SIZE;
+	else
+		val = cb->rpc_end_seq - tp->copied_seq;

Does this code incorrectly set SO_RCVLOWAT to the total combined size of all unread frames when multiple RPC frames are received in a single skb?

If multiple complete frames arrive in the same skb, the parsing loop in tcp_do_autolowat() parses all of them and advances cb->rpc_desc_seq to the end of the last parsed frame. This sets:

val = cb->rpc_desc_seq - tp->copied_seq

which evaluates to the length of all unread frames combined.

If an application sequentially reads one frame at a time, tp->copied_seq advances and the queue size decreases, but sk_rcvlowat is not updated because BPF_SOCK_OPS_RCVQ_CB only fires on packet enqueue.

The remaining queue size will then be strictly less than sk_rcvlowat, causing epoll_wait to block and trapping the remaining fully-received frames in the receive queue.

Could this hang applications that rely on epoll to read one message at a time?

Reference: https://lore.kernel.org/bpf/[email protected]/
Reviewer: [email protected] (Fri, 22 May 2026 08:35:27 +0000)

---
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/26328541814

author reviewer
#37 lore raw

Re: [PATCH v3 bpf-next 11/11] selftest: bpf: Add test for BPF_SOCK_OPS_RCVQ_CB.

Quoted 63 lines · On Sat, May 23, 2026 at 2:20 AM <[email protected]> wrote:
Quoted 15 lines
tools/testing/selftests/bpf/bpf_kfuncs.h +4 -0
@@ -64,6 +64,10 @@
 extern int bpf_sk_assign_tcp_reqsk(struct __sk_buff *skb, struct sock *sk,
                                 struct bpf_tcp_req_attrs *attrs, int attrs__sz) __ksym;
 
+struct bpf_sock_ops_kern;
+extern int bpf_sock_ops_tcp_set_rcvlowat(struct bpf_sock_ops_kern *skops_kern,
+                                      int rcvlowat) __ksym;
+
 void *bpf_cast_to_kern_ctx(void *) __ksym;
 
 extern void *bpf_rdonly_cast(const void *obj, __u32 btf_id) __ksym __weak;

[ ... ]

Quoted 12 lines
tools/testing/selftests/bpf/progs/bpf_tracing_net.h +2 -0
@@ -74,6 +74,8 @@ #define ETH_P_IPV6          0x86DD
 
 #define NEXTHDR_TCP          6
 
+#define TCPHDR_FIN           0x01
+
 #define TCPOPT_NOP           1
 #define TCPOPT_EOL           0
 #define TCPOPT_MSS           2

[ ... ]

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +0 -0
@@ -0,0 +1,350 @@

[ ... ]

Quoted 12 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +12 -0
+             .event = {
+                     { .type = RPC_EVENT_AUTOLOWAT,  .val = 1},
+                     /* The first descriptor is partial. */
+                     {.type = RPC_EVENT_SEND,        .len = 1},
+                     {.type = RPC_EVENT_EPOLL,       .nfds = 0},
+                     {.type = RPC_EVENT_RCVLOWAT,    .rcvlowat = RPC_DESC_SIZE},
+                     /* The first descriptor is available. */
+                     {.type = RPC_EVENT_SEND,        .len = RPC_DESC_SIZE - 1},
+                     {.type = RPC_EVENT_EPOLL,       .nfds = 0},
+                     {.type = RPC_EVENT_RCVLOWAT,    .rcvlowat = RPC_DESC_SIZE + 150 + 100},
+                     /* The first header is ready. */
+                     {.type = RPC_EVENT_SEND,        .len = 100},

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 119

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +10 -0
+                     {.type = RPC_EVENT_EPOLL,       .nfds = 0},
+                     {.type = RPC_EVENT_RCVLOWAT,    .rcvlowat = RPC_DESC_SIZE + 150 + 100},
+                     /* skb has the first payload and 1 byte of the next descriptor. */
+                     {.type = RPC_EVENT_SEND,        .len = 150 + 1},
+                     {.type = RPC_EVENT_EPOLL,       .nfds = 1},
+                     {.type = RPC_EVENT_RCVLOWAT,    .rcvlowat = RPC_DESC_SIZE + 150 + 100},
+                     /* After reading the first RPC message, SO_RCVLOWAT should be RPC_DESC_SIZE. */
+                     {.type = RPC_EVENT_RECV,        .len = RPC_DESC_SIZE + 150 + 100},
+                     {.type = RPC_EVENT_EPOLL,       .nfds = 0},
+                     {.type = RPC_EVENT_RCVLOWAT,    .rcvlowat = RPC_DESC_SIZE},
Quoted 4 lines

Does calling recv() actually trigger the BPF program to update SO_RCVLOWAT?

Since the kernel only invokes BPF_SOCK_OPS_RCVQ_CB when a new skb is added to the receive queue, and not when data is dequeued via recv(),

Again, this is wrong.

Quoted 35 lines

the BPF
program doesn't seem to run here.

Could this cause the test to fail unconditionally because sk_rcvlowat retains its previous value?

Reference: https://lore.kernel.org/bpf/[email protected]/
Reviewer: [email protected] (Fri, 22 May 2026 08:35:27 +0000)

[ ... ]

Quoted 24 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +24 -0
+static void tcp_autolowat_run_rpc_test(struct tcp_autolowat_test_cb *cb,
+                                    struct rpc_test_case *test_case)
+{
+     struct rpc_event *event = test_case->event;
+     char *ptr = test_case->data;
+     struct epoll_event ev;
+     socklen_t optlen;
+     int err, optval;
+     char buf[4096];
+
+     if (tcp_autolowat_build_data(test_case))
+             return;
+
+     while (1) {
+             switch (event->type) {
+             case RPC_EVENT_END:
+                     return;
+             case RPC_EVENT_AUTOLOWAT:
+                     err = setsockopt(cb->child, SOL_BPF, BPF_TCP_AUTOLOWAT,
+                                      &event->val, sizeof(event->val));
+                     if (!ASSERT_OK(err, "setsockopt"))
+                             return;
+                     break;
+             case RPC_EVENT_SEND:
Quoted 8 lines

tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c line 262

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/tcp_autolowat.c new file +6 -0
+                     err = send(cb->client, ptr, event->len, 0);
+                     if (!ASSERT_EQ(err, event->len, "send"))
+                             return;
+
+                     ptr += event->len;
+                     break;

Could this lead to race conditions causing flaky tests?

No, it's over loopback.

Quoted 82 lines

The test calls send() to transmit data and immediately executes the next event. Because network transmission over the loopback interface involves asynchronous softirq processing, send() might return before the packet is fully processed by the receiving socket.

If the next event is RPC_EVENT_EPOLL with a timeout of 0, could epoll_wait() prematurely return 0? Similarly, for RPC_EVENT_RCVLOWAT, could getsockopt() read a stale sk_rcvlowat value before the TCP stack and BPF program have finished processing the packet?

Reference: https://lore.kernel.org/bpf/[email protected]/
Reviewer: [email protected] (Fri, 22 May 2026 08:35:27 +0000)

[ ... ]

Quoted 4 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +0 -0
@@ -0,0 +1,326 @@

[ ... ]

Quoted 11 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +11 -0
+static int tcp_parse_descriptor(struct bpf_sock_ops *skops,
+                             struct tcp_autolowat_cb *cb,
+                             u32 seq, u32 end_seq)
+{
+     struct rpc_descriptor *rpc_desc;
+     u32 rpc_copied_seq;
+     u64 copy_len; /* u32 should work, but not for no_alu32 :/ */
+     u64 rpc_len;
+     int err;
+
+     rpc_copied_seq = cb->rpc_desc_seq + cb->rpc_desc_buff_len;

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 79

Quoted 10 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +10 -0
+
+     if (before(cb->rpc_desc_seq + RPC_DESC_SIZE, end_seq))
+             copy_len = RPC_DESC_SIZE - cb->rpc_desc_buff_len;
+     else
+             copy_len = end_seq - rpc_copied_seq;
+
+     /* Since LLVM commit 324e27e8bad83ca23a3cd276d7e2e729b1b0b8c7,
+      * clang omits the "copy_len == 0" check below, which is necessary
+      * to satisfy the BPF verifier's range check for bpf_skb_load_bytes().
+      */

This isn't a bug, but multi-line comments in the BPF subsystem are expected to have the opening '/*' on its own line:

/*
* Since LLVM commit ...
* ...
*/

Reference: https://lore.kernel.org/bpf/[email protected]/
Reviewer: [email protected] (Fri, 22 May 2026 08:35:27 +0000)

[ ... ]

Quoted 6 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +6 -0
+static void tcp_set_autolowat(struct bpf_sock_ops_kern *skops_kern,
+                           struct tcp_autolowat_cb *cb,
+                           struct tcp_sock *tp)
+{
+     /* To handle wraparound. */
+     u32 val = 0;

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 146

Quoted 10 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +10 -0
+
+     LOG("Setting rcvlowat: tp->copied_seq: %u, rpc_desc_seq: %u, rpc_end_seq: %u, rpc_desc_buff_len: %u",
+         TP_SEQ(copied_seq), CB_SEQ(rpc_desc_seq), CB_SEQ(rpc_end_seq), cb->rpc_desc_buff_len);
+
+     if (before(tp->copied_seq, cb->rpc_desc_seq))
+             val = cb->rpc_desc_seq - tp->copied_seq;
+     else if (cb->rpc_desc_buff_len != RPC_DESC_SIZE)
+             val = RPC_DESC_SIZE;
+     else
+             val = cb->rpc_end_seq - tp->copied_seq;

Does this code incorrectly set SO_RCVLOWAT to the total combined size of all unread frames when multiple RPC frames are received in a single skb?

If multiple complete frames arrive in the same skb, the parsing loop in tcp_do_autolowat() parses all of them and advances cb->rpc_desc_seq to the end of the last parsed frame. This sets:

Quoted 7 lines

val = cb->rpc_desc_seq - tp->copied_seq

which evaluates to the length of all unread frames combined.

If an application sequentially reads one frame at a time, tp->copied_seq advances and the queue size decreases, but sk_rcvlowat is not updated because BPF_SOCK_OPS_RCVQ_CB only fires on packet enqueue.

This comment is based on the wrong assumption too :/

Quoted 17 lines

The remaining queue size will then be strictly less than sk_rcvlowat, causing epoll_wait to block and trapping the remaining fully-received frames in the receive queue.

Could this hang applications that rely on epoll to read one message at a time?

Reference: https://lore.kernel.org/bpf/[email protected]/
Reviewer: [email protected] (Fri, 22 May 2026 08:35:27 +0000)

---
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/26328541814

#38 lore raw

Re: [PATCH v3 bpf-next 11/11] selftest: bpf: Add test for BPF_SOCK_OPS_RCVQ_CB.

In reply to Kuniyuki Iwashima
Quoted 24 lines · Kuniyuki Iwashima
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +24 -0
+static void tcp_do_autolowat(struct bpf_sock_ops *skops,
+			     struct tcp_autolowat_cb *cb,
+			     struct tcp_sock *tp)
+{
+	struct bpf_sock_ops_kern *skops_kern;
+	struct tcp_skb_cb *tcb;
+	struct sk_buff *skb;
+	u32 seq, end_seq;
+	int ret = 0, i;
+
+	skops_kern = bpf_cast_to_kern_ctx(skops);
+	skb = skops_kern->skb;
+
+	if (!skb)
+		goto update;
+
+	tcb = bpf_core_cast(skb->cb, struct tcp_skb_cb);
+	seq = tcb->seq;
+	end_seq = tcb->end_seq - !!(tcb->tcp_flags & TCPHDR_FIN);
+
+	LOG("Start parsing skb: seq: %u, end_seq: %u, len: %u, "
+	    "rpc_desc_seq: %u, rpc_end_seq: %u, rpc_buff_len: %u",
+	    SEQ(seq), SEQ(end_seq), end_seq - seq,
+	    CB_SEQ(rpc_desc_seq), CB_SEQ(rpc_end_seq), cb->rpc_desc_buff_len);

tools/testing/selftests/bpf/progs/tcp_autolowat.c line 204

Quoted 10 lines
tools/testing/selftests/bpf/progs/tcp_autolowat.c new file +10 -0
+
+	if (cb->rpc_desc_buff_len != RPC_DESC_SIZE) {
+		ret = tcp_parse_descriptor(skops, cb, seq, end_seq);
+		if (ret)
+			goto update;
+	}
+
+	i = 0;
+
+	while (1) {

A nit. It may be useful to take a look at progs/arena_htab.c or rbtree_search.c on the 'for (i = zero; i < xyz && can_loop; i++)' usage.

#> ./veristat tcp_autolowat.bpf.o
Processing 'tcp_autolowat.bpf.o'...

File                 Program                   Verdict  Duration (us)  Insns  States  Program size  Jited size
-------------------  ------------------------  -------  -------------  -----  ------  ------------  ----------
tcp_autolowat.bpf.o  tcp_autolowat             success         245961  12624     338           141         939

The "Insns" could likely be reduced to ~1000s level.