Skip to contentSkip to conversation

net: fix unreadable net_iov skb handling across networking paths

PATCH In review Octavian Purdila 4 participants 42 messages Dec 3 – Dec 4

Subsystems (8)
lore
Share & tools
lore
#0 lore raw

cover net: fix unreadable net_iov skb handling across networking paths

Device-memory TCP and io_uring zcrx bind RX queues to page_pool memory providers whose net_iov fragments cannot be mapped or read by the CPU. While standard TCP devmem traffic uses flow steering onto isolated RX queues, several networking paths either propagate stale skb metadata, mix readable and unreadable fragments across frag_list, or attempt to map or copy payload fragments on the CPU when unexpected protocol traffic or socket options interact with unreadable skbs:

1. GRO fragment reuse and pull failure (patches 1-2): napi_frags_skb() calls napi_reuse_skb() while fragments remain attached on Ethernet header pull failure and napi_gro_frags() dereferences the resulting NULL skb; napi_reuse_skb() leaves stale skb->unreadable and skb->pp_recycle state on cached napi->skb heads.

2. IP fragment reassembly and generic skb helpers (patches 3-4): IP fragment reassembly permits mixing readable and unreadable fragments in the same queue and does not propagate head->unreadable to the frag_list wrapper skb, and skb_to_sgvec(), skb_send_sock_locked(), sockmap verdict processing, and strparser assume CPU-readable fragments.

3. kTLS RX and TCP-MD5 / TCP-AO (patches 5-6): kTLS tls_strp decryption and software TCP-MD5 / TCP-AO payload hashing attempt to access unreadable net_iov fragments on the CPU.

Patches 1-6 fix these paths by freeing failed napi_frags_skb() skbs, resetting cached GRO skb state, rejecting mixed-readability IP fragments, and rejecting unreadable fragments cleanly before CPU page mapping occurs.

Patches 7-8 add KUnit regression tests in net_test covering the napi_gro_frags, IP defrag, scatterlist, skmsg, and strparser paths and verifying page_pool and dmabuf binding reference counts remain balanced. Patches 9-10 extend devmem.py with end-to-end protocol regression tests for kTLS RX and TCP-MD5 / TCP-AO RX and TX rejection.

Verified with net_core KUnit tests in QEMU and end-to-end devmem.py runs over ConnectX-7 (mlx5_core) 400GbE hardware.

Octavian Purdila (10):
net: gro: free skb on napi_frags_skb() header pull failure
net: gro: reset unreadable and pp_recycle in napi_reuse_skb
inet: frag: reject fragments with mixed readability in reassembly
net: skbuff, skmsg, strparser: reject unreadable frags
tls: reject unreadable skbs in tls_strp
tcp: reject unreadable skbs on TCP-MD5 and TCP-AO
net: kunit: test unreadable net_iov napi_gro_frags
net: kunit: test unreadable net_iov defrag and skb helpers
selftests: drv-net: devmem: test unreadable kTLS RX
selftests: drv-net: devmem: test unreadable skbs on TCP-MD5 and TCP-AO

 include/net/inet_frag.h                       |   1 +
 include/net/tcp.h                             |  33 +-
 net/core/gro.c                                |   7 +-
 net/core/net_test.c                           | 628 +++++++++++++++++-
 net/core/skbuff.c                             |   8 +
 net/core/skmsg.c                              |  10 +
 net/ipv4/inet_fragment.c                      |  13 +-
 net/ipv4/tcp.c                                |  32 +-
 net/ipv4/tcp_ao.c                             |  29 +-
 net/ipv4/tcp_ipv4.c                           |  13 +-
 net/ipv4/tcp_output.c                         |   9 +-
 net/ipv6/tcp_ipv6.c                           |  10 +-
 net/strparser/strparser.c                     |   5 +
 net/tls/tls_strp.c                            |  24 +-
 tools/testing/selftests/drivers/net/hw/config |   2 +
 .../selftests/drivers/net/hw/devmem.py        |  17 +-
 .../selftests/drivers/net/hw/devmem_lib.py    | 445 ++++++++++++-
 .../drivers/net/hw/lib/py/__init__.py         |  11 +-
 18 files changed, 1247 insertions(+), 50 deletions(-)

base-commit: 90ae4042bd9f35a9098d14b1a12a43df9b326e2b

Signature · 1 line
2.56.1.915.g69d5ec7298-goog
#1 lore raw

PATCH 1/10 net: gro: free skb on napi_frags_skb() header pull failure

When skb_gro_header_slow() fails to pull the Ethernet header in napi_frags_skb() (for instance on an unreadable net_iov fragment without a linear header, or a short/malformed packet), the skb still has its attached fragments (nr_frags > 0, data_len > 0). Calling napi_reuse_skb() on this error path caches the dirty skb back onto napi->skb without releasing or clearing its fragments, leaking attached fragments and corrupting length metadata for the next napi_get_frags() call. In addition, napi_gro_frags() passes the resulting NULL skb straight into trace_napi_gro_frags_entry() and dev_gro_receive(), dereferencing a NULL pointer.

Free the skb with kfree_skb() in napi_frags_skb() on header-pull failure so attached fragments are released cleanly with their original recycling state intact, and return GRO_CONSUMED in napi_gro_frags() when napi_frags_skb() returns NULL.

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

Fixes f55720680080 ("gro: Fix page ref count for skbs freed normally")
Fixes 1d11fa696733 ("net-gro: remove GRO_DROP")
Assisted-by LLM
---
 net/core/gro.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
net/core/gro.c +4 -1
index 1241b23d66efa..fb730017fd3ba 100644
@@ -776,7 +776,7 @@ static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
 		if (unlikely(!eth)) {
 			net_warn_ratelimited("%s: dropping impossible skb from %s\n",
 					     __func__, napi->dev->name);
-			napi_reuse_skb(napi, skb);
+			kfree_skb(skb);
 			return NULL;
 		}
 	} else {
@@ -805,6 +805,9 @@ gro_result_t napi_gro_frags(struct napi_struct *napi)
 	gro_result_t ret;
 	struct sk_buff *skb = napi_frags_skb(napi);
 
+	if (unlikely(!skb))
+		return GRO_CONSUMED;
+
 	trace_napi_gro_frags_entry(skb);
 
 	ret = napi_frags_finish(napi, skb, dev_gro_receive(&napi->gro, skb));
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
Reviewed-by on v1 1/10
#2 lore raw

Re: [PATCH net 01/10] net: gro: free skb on napi_frags_skb() header pull failure

Quoted 17 lines · Octavian Purdila

When skb_gro_header_slow() fails to pull the Ethernet header in napi_frags_skb() (for instance on an unreadable net_iov fragment without a linear header, or a short/malformed packet), the skb still has its attached fragments (nr_frags > 0, data_len > 0). Calling napi_reuse_skb() on this error path caches the dirty skb back onto napi->skb without releasing or clearing its fragments, leaking attached fragments and corrupting length metadata for the next napi_get_frags() call. In addition, napi_gro_frags() passes the resulting NULL skb straight into trace_napi_gro_frags_entry() and dev_gro_receive(), dereferencing a NULL pointer.

Free the skb with kfree_skb() in napi_frags_skb() on header-pull failure so attached fragments are released cleanly with their original recycling state intact, and return GRO_CONSUMED in napi_gro_frags() when napi_frags_skb() returns NULL.

Quoted 8 lines

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

Fixes f55720680080 ("gro: Fix page ref count for skbs freed normally")
Fixes 1d11fa696733 ("net-gro: remove GRO_DROP")
Assisted-by LLM
Signature · 2 lines
Thanks,
Mina
#3 lore raw

PATCH 2/10 net: gro: reset unreadable and pp_recycle in napi_reuse_skb

In reply to Octavian Purdila

Drivers using napi_get_frags() and napi_gro_frags() cache and reuse the fragmentless head sk_buff on napi->skb whenever incoming fragments merge into an existing GRO flow. When an unreadable or page_pool-backed skb is cached and later reused for a normal readable packet (for instance across queue reconfiguration or shared NAPI instances), leaving skb->unreadable and skb->pp_recycle set on napi->skb leaks stale state onto subsequent packets, corrupting readability checks and causing skb_gro_receive() to refuse GRO merges due to mismatched pp_recycle state.

Reset skb->unreadable and skb->pp_recycle in napi_reuse_skb().

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

Fixes 6a5bcd84e886 ("page_pool: Allow drivers to hint on SKB recycling")
Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM
---
 net/core/gro.c | 2 ++
 1 file changed, 2 insertions(+)
net/core/gro.c +2 -0
index fb730017fd3ba..c1d07bca1b4eb 100644
@@ -697,6 +697,8 @@ static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
 
 	skb->encapsulation = 0;
 	skb->ip_summed = CHECKSUM_NONE;
+	skb->unreadable = 0;
+	skb->pp_recycle = 0;
 
 	shinfo = skb_shinfo(skb);
 	shinfo->gso_type = 0;
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
Reviewed-by on v1 2/10
#4 lore raw

Re: [PATCH net 02/10] net: gro: reset unreadable and pp_recycle in napi_reuse_skb

Quoted 29 lines · Octavian Purdila

Drivers using napi_get_frags() and napi_gro_frags() cache and reuse the fragmentless head sk_buff on napi->skb whenever incoming fragments merge into an existing GRO flow. When an unreadable or page_pool-backed skb is cached and later reused for a normal readable packet (for instance across queue reconfiguration or shared NAPI instances), leaving skb->unreadable and skb->pp_recycle set on napi->skb leaks stale state onto subsequent packets, corrupting readability checks and causing skb_gro_receive() to refuse GRO merges due to mismatched pp_recycle state.

Reset skb->unreadable and skb->pp_recycle in napi_reuse_skb().

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

Fixes 6a5bcd84e886 ("page_pool: Allow drivers to hint on SKB recycling")
Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM
---
 net/core/gro.c | 2 ++
 1 file changed, 2 insertions(+)
net/core/gro.c +0 -0
index fb730017fd3ba..c1d07bca1b4eb 100644

net/core/gro.c static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb) · line 702

Quoted 6 lines
net/core/gro.c +2 -0
@@ -697,6 +697,8 @@ static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
 
        skb->encapsulation = 0;
        skb->ip_summed = CHECKSUM_NONE;
+       skb->unreadable = 0;
+       skb->pp_recycle = 0;
 

LGTM for napi_reuse_skb() — definitely needed (e.g. gve_rx_dqo can reuse napi_get_frags() on copy-on-demand without marking pp_recycle).

Side note while we're in gro.c: AFAICT skb_gro_receive() (and gro_list_prepare()) only checks p->pp_recycle != skb->pp_recycle and doesn't check skb_frags_readable(p) != skb_frags_readable(skb). If a shared NAPI or driver ever puts readable pp_recycle=1 and unreadable pp_recycle=1 segments of the same flow through GRO, they could still get merged into a mixed-readability skb/frag_list (which also matters for patch 5). Probably worth a separate check in skb_gro_receive() too.

Signature · 2 lines
Thanks,
Mina
#5 lore raw

Re: [PATCH net 02/10] net: gro: reset unreadable and pp_recycle in napi_reuse_skb

Quoted 32 lines · Mina Almasry
Quoted 30 lines · Octavian Purdila

Drivers using napi_get_frags() and napi_gro_frags() cache and reuse the fragmentless head sk_buff on napi->skb whenever incoming fragments merge into an existing GRO flow. When an unreadable or page_pool-backed skb is cached and later reused for a normal readable packet (for instance across queue reconfiguration or shared NAPI instances), leaving skb->unreadable and skb->pp_recycle set on napi->skb leaks stale state onto subsequent packets, corrupting readability checks and causing skb_gro_receive() to refuse GRO merges due to mismatched pp_recycle state.

Reset skb->unreadable and skb->pp_recycle in napi_reuse_skb().

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

Fixes 6a5bcd84e886 ("page_pool: Allow drivers to hint on SKB recycling")
Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM
---
 net/core/gro.c | 2 ++
 1 file changed, 2 insertions(+)
net/core/gro.c +0 -0
index fb730017fd3ba..c1d07bca1b4eb 100644
@@ -697,6 +697,8 @@ static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
 
Quoted 9 lines

net/core/gro.c static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb) · line 702

Quoted 5 lines
net/core/gro.c +2 -0
        skb->encapsulation = 0;
        skb->ip_summed = CHECKSUM_NONE;
+       skb->unreadable = 0;
+       skb->pp_recycle = 0;
 

LGTM for napi_reuse_skb() — definitely needed (e.g. gve_rx_dqo can reuse napi_get_frags() on copy-on-demand without marking pp_recycle).

Thanks for the reviews Mina!

Quoted 8 lines

Side note while we're in gro.c: AFAICT skb_gro_receive() (and gro_list_prepare()) only checks p->pp_recycle != skb->pp_recycle and doesn't check skb_frags_readable(p) != skb_frags_readable(skb). If a shared NAPI or driver ever puts readable pp_recycle=1 and unreadable pp_recycle=1 segments of the same flow through GRO, they could still get merged into a mixed-readability skb/frag_list (which also matters for patch 5). Probably worth a separate check in skb_gro_receive() too.

Good catch, this seems indeed possible and a check seems reasonable to me. I'll follow up with a patch for v2.

Quoted 5 lines

--
Thanks,
Mina

#6 lore raw

Re: [PATCH net 02/10] net: gro: reset unreadable and pp_recycle in napi_reuse_skb

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] net: gro: napi_reuse_skb() clears pp_recycle on page_pool head_frag skb --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] net: gro: napi_reuse_skb() clears pp_recycle on page_pool head_frag skb
--

commit b36e9ed0c17bf92ac591da7f73dbb5d385defdc5
Author: Octavian Purdila <[email protected]>

net: gro: reset unreadable and pp_recycle in napi_reuse_skb

This commit clears skb->unreadable and skb->pp_recycle in napi_reuse_skb() so stale state is not carried over when napi->skb is reused.

net/core/gro.c static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb) · line 701

Quoted 10 lines
net/core/gro.c +2 -0
index fb730017fd3ba..c1d07bca1b4eb 100644
@@ -697,6 +697,8 @@ static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
 
 	skb->encapsulation = 0;
 	skb->ip_summed = CHECKSUM_NONE;
+	skb->unreadable = 0;
+	skb->pp_recycle = 0;

[Severity: Medium]
Can clearing skb->pp_recycle here break freeing skb->head when skb->head_frag is set?

On a TAP device with IFF_NAPI_FRAGS and a multi-buffer generic XDP program, tun_get_user() can store a system_page_pool-backed skb (head_frag = 1, pp_recycle = 1) from do_xdp_generic() -> skb_pp_cow_data() in tfile->napi.skb.

If the XDP program trims linear data to the headers while leaving payload in frag[0], skb_gro_receive() merges the frag with NAPI_GRO_FREE and routes that skb to napi_reuse_skb().

When the cached skb is later freed, skb_free_head() skips skb_pp_recycle() and frees the page_pool page via skb_free_frag() -> page_frag_free(). With CONFIG_DEBUG_VM or init_on_alloc this triggers bad_page ("page_pool leak") and leaks the page; otherwise pages_state_hold_cnt is permanently imbalanced.

Should napi_reuse_skb() reject skb->head_frag alongside skb->pfmemalloc and pass such skbs to consume_skb()?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#7 lore raw

Re: [PATCH net 02/10] net: gro: reset unreadable and pp_recycle in napi_reuse_skb

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 1

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] This patch can free a page_pool page through the page allocator.
- [Low] The commit message describes a live bug that no in-tree driver path has been shown to reach, and it carries two Fixes: tags that will…

--

net: gro: reset unreadable and pp_recycle in napi_reuse_skb

This patch clears skb->unreadable and skb->pp_recycle in napi_reuse_skb(). The goal is to stop that state carrying over from a cached napi->skb onto later packets. It carries Fixes: tags for the page_pool recycling hint and unreadable frags commits.

Quoted 6 lines

When an unreadable or page_pool-backed skb is
cached and later reused for a normal readable packet (for instance across queue reconfiguration or shared NAPI instances), leaving skb->unreadable and skb->pp_recycle set on napi->skb leaks stale state onto subsequent packets, corrupting readability checks and causing skb_gro_receive() to refuse GRO merges due to mismatched pp_recycle state.

[Severity: Low]

Is there an in-tree driver path that reaches this state?

For unreadable, gve is the only driver that uses napi_get_frags() together with unreadable netmem. gve_rx_dqo() reaches napi_get_frags() only when the first frag is the data buffer, which is a net_iov on a devmem queue.

For such an skb, skb_gro_reset_offset() leaves frag0_len at 0. The Ethernet pull in napi_frags_skb() then fails, because __pskb_pull_tail() returns NULL when !skb_frags_readable(). With the earlier patch in this series ("net: gro:
free skb on napi_frags_skb() header pull failure"), the skb is freed. It never reaches napi_reuse_skb() with unreadable set.

For queue reconfiguration, napi->skb is freed on this path, so nothing cached survives:

gve_rx_stop_ring_dqo()
gve_remove_napi()
netif_napi_del()
napi_free_frags()

For pp_recycle, gve_rx_dqo() marks every napi_get_frags() skb again:

	if (rx->dqo.page_pool)
		skb_mark_for_recycle(rx->ctx.skb_head);

The other producer that leaves pp_recycle set on napi->skb is tun's XDP COW path. There the flag is correct (see the comment on the diff below).

The KUnit test added later in the series ("net: kunit: test unreadable net_iov napi_gro_frags") builds this state by hand. It doesn't show a driver path that produces it.

Should this be described as hardening, with the Fixes: tags reconsidered since they would send it to stable? Or could the message name a concrete in-tree driver sequence that triggers it?

net/core/gro.c static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb) · line 701

Quoted 10 lines
net/core/gro.c +2 -0
index fb730017fd3ba..c1d07bca1b4eb 100644
@@ -697,6 +697,8 @@ static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
 
 	skb->encapsulation = 0;
 	skb->ip_summed = CHECKSUM_NONE;
+	skb->unreadable = 0;
+	skb->pp_recycle = 0;
         ^^^^

[Severity: Medium]

Can clearing pp_recycle here free a page_pool head through the page allocator?

napi_reuse_skb() keeps skb->head. This reset assumes the head of every skb cached on napi->skb is not page_pool memory. That holds for napi_get_frags(), but tun can store a different skb in napi.skb. This happens in tun_get_user() with IFF_NAPI_FRAGS and a generic XDP program attached:

drivers/net/tun.c:tun_get_user() {
    ...
			ret = do_xdp_generic(xdp_prog, &skb);
    ...
			if (frags && skb != tfile->napi.skb)
				tfile->napi.skb = skb;
    ...
}

The frags skb is always nonlinear, so do_xdp_generic() can replace it:

do_xdp_generic()
netif_receive_generic_xdp()

    netif_skb_check_for_xdp()
      skb_cow_data_for_xdp()
        skb_pp_cow_data()

skb_pp_cow_data() builds the new head with page_pool_dev_alloc_va() and napi_build_skb(), so head_frag is 1. It then calls skb_mark_for_recycle().

Suppose skb_gro_receive() merges that skb with headlen <= offset. It sets NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE, and napi_frags_finish() passes the skb to napi_reuse_skb(). pp_recycle is then cleared while skb->head is still a page_pool page.

The cached skb can be freed next in several ways:

- consume_skb() in skb_pp_cow_data() on the next XDP COW
- napi_free_frags() from netif_napi_del()
- a tun drop path

In each case skb_free_head() would take the non-recycle branch:

net/core/skbuff.c:skb_free_head() {
	...
	if (skb->head_frag) {
		if (skb_pp_recycle(skb, head))
			return;
		skb_free_frag(head);
	...
}

Wouldn't that return the page_pool page to the buddy allocator? It would then trip the page_pool_page_is_pp() bad page check and throw off page_pool's in-flight accounting.

Before this patch, pp_recycle stayed set across reuse and the head was recycled correctly. Mixing it with tun's non-page_pool frags was fine, because napi_pp_put_page() falls back for non-pp netmem.

Reaching this needs all of the following:

- CAP_NET_ADMIN
- an XDP program with frags support on the tun device
- deferred NAPI completion (napi_defer_hard_irqs or gro_flush_timeout)
- a merge where the linear length exactly matches the GRO header offset

Could pp_recycle be cleared only when the head is not page_pool memory? For example:

	!skb->head_frag ||
	!page_pool_page_is_pp(virt_to_head_page(skb->head))

Checking !head_frag alone wouldn't be enough, because napi_alloc_skb() can also return head_frag skbs.

Other options would be to drop the pp_recycle reset, or to make sure napi->skb only ever comes from napi_get_frags().

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796329894.git.tavip%40google.com
#8 lore raw

PATCH 3/10 inet: frag: reject fragments with mixed readability in reassembly

In reply to Octavian Purdila

A reassembled skb keeps the head fragment's unreadable bit while chaining subsequent fragments onto frag_list. Upper-layer socket receive paths dispatch based on skb_frags_readable() of the head skb (for example, tcp_recvmsg_locked() routes to skb_copy_datagram_msg() vs. tcp_recvmsg_dmabuf()), and require uniform readability across all frag_list entries. Mixing readable and unreadable fragments in the same reassembly queue (for example, when fragments split across a devmem queue and a normal queue, or when a size-threshold spill places only larger fragments in unreadable netmem) produces a mixed-readability reassembled skb that fails on delivery with -EFAULT or -ENODEV.

Reject a fragment in inet_frag_queue_insert() when its readability differs from the fragments already in the queue, mirroring IPFRAG_MIXED_SECPATH, while continuing to allow uniformly unreadable fragments to reassemble. Also propagate head->unreadable to the wrapper skb allocated by inet_frag_reasm_prepare() when the first fragment already carries a frag_list.

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM
---
 include/net/inet_frag.h  |  1 +
 net/ipv4/inet_fragment.c | 13 ++++++++++---
 2 files changed, 11 insertions(+), 3 deletions(-)
include/net/inet_frag.h +1 -0
index c1fb419a9cf03..668cb042b36b3 100644
@@ -175,6 +175,7 @@ extern const u8 ip_frag_ecn_table[16];
 #define IPFRAG_OVERLAP	2
 #define IPFRAG_MIXED_SECPATH	3
 #define IPFRAG_TOOBIG	4
+#define IPFRAG_MIXED_READABILITY	5
 
 /* Max sum of the truesize of fragments in a queue. This keeps the sums
  * done in inet_frag_reasm_prepare() and inet_frag_reasm_finish() well
net/ipv4/inet_fragment.c +10 -3
index f330d0a398233..caf07cf1a411c 100644
@@ -444,9 +444,15 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb,
 {
 	struct sk_buff *last = q->fragments_tail;
 
-	/* The reassembled skb keeps the first fragment's secpath. */
-	if (last && !secpath_equal(last, skb))
-		return IPFRAG_MIXED_SECPATH;
+	/* The reassembled skb keeps the first fragment's secpath and
+	 * readability state.
+	 */
+	if (last) {
+		if (!secpath_equal(last, skb))
+			return IPFRAG_MIXED_SECPATH;
+		if (skb_frags_readable(last) != skb_frags_readable(skb))
+			return IPFRAG_MIXED_READABILITY;
+	}
 
 	if (skb->truesize > INET_FRAG_MAX_TRUESIZE - q->truesize)
 		return IPFRAG_TOOBIG;
@@ -639,6 +645,7 @@ void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb,
 		head->truesize += clone->truesize;
 		clone->csum = 0;
 		clone->ip_summed = head->ip_summed;
+		clone->unreadable = head->unreadable;
 		add_frag_mem_limit(q->fqdir, clone->truesize);
 		skb_shinfo(head)->frag_list = clone;
 		nextp = &clone->next;
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
#9 lore raw

Re: [PATCH net 03/10] inet: frag: reject fragments with mixed readability in reassembly

Quoted 54 lines · Octavian Purdila

A reassembled skb keeps the head fragment's unreadable bit while chaining subsequent fragments onto frag_list. Upper-layer socket receive paths dispatch based on skb_frags_readable() of the head skb (for example, tcp_recvmsg_locked() routes to skb_copy_datagram_msg() vs. tcp_recvmsg_dmabuf()), and require uniform readability across all frag_list entries. Mixing readable and unreadable fragments in the same reassembly queue (for example, when fragments split across a devmem queue and a normal queue, or when a size-threshold spill places only larger fragments in unreadable netmem) produces a mixed-readability reassembled skb that fails on delivery with -EFAULT or -ENODEV.

Reject a fragment in inet_frag_queue_insert() when its readability differs from the fragments already in the queue, mirroring IPFRAG_MIXED_SECPATH, while continuing to allow uniformly unreadable fragments to reassemble. Also propagate head->unreadable to the wrapper skb allocated by inet_frag_reasm_prepare() when the first fragment already carries a frag_list.

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM
---
 include/net/inet_frag.h  |  1 +
 net/ipv4/inet_fragment.c | 13 ++++++++++---
 2 files changed, 11 insertions(+), 3 deletions(-)
include/net/inet_frag.h +1 -0
index c1fb419a9cf03..668cb042b36b3 100644
@@ -175,6 +175,7 @@ extern const u8 ip_frag_ecn_table[16];
 #define IPFRAG_OVERLAP 2
 #define IPFRAG_MIXED_SECPATH   3
 #define IPFRAG_TOOBIG  4
+#define IPFRAG_MIXED_READABILITY       5
 
 /* Max sum of the truesize of fragments in a queue. This keeps the sums
  * done in inet_frag_reasm_prepare() and inet_frag_reasm_finish() well
net/ipv4/inet_fragment.c +0 -3
index f330d0a398233..caf07cf1a411c 100644
@@ -444,9 +444,15 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb,
 {
        struct sk_buff *last = q->fragments_tail;
 
-       /* The reassembled skb keeps the first fragment's secpath. */
-       if (last && !secpath_equal(last, skb))
-               return IPFRAG_MIXED_SECPATH;

net/ipv4/inet_fragment.c int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb, · line 456

Quoted 10 lines
net/ipv4/inet_fragment.c +9 -0
+       /* The reassembled skb keeps the first fragment's secpath and
+        * readability state.
+        */
+       if (last) {
+               if (!secpath_equal(last, skb))
+                       return IPFRAG_MIXED_SECPATH;
+               if (skb_frags_readable(last) != skb_frags_readable(skb))
+                       return IPFRAG_MIXED_READABILITY;
+       }
 

I think this regresses io_uring zcrx for fragmented TCP datagrams? Unlike tcp_recvmsg_locked() / tcp_recvmsg_dmabuf(), io_zcrx_recv_skb() -> io_zcrx_recv_frag() actually handles readability per-frag (it falls back to io_zcrx_copy_frag() when !skb_frag_is_net_iov(frag)) and walks frag_list recursively. I don't think we want to regress that.

Signature · 2 lines
Thanks,
Mina
#10 lore raw

Re: [PATCH net 03/10] inet: frag: reject fragments with mixed readability in reassembly

Quoted 64 lines · Mina Almasry
Quoted 62 lines · Octavian Purdila

A reassembled skb keeps the head fragment's unreadable bit while chaining subsequent fragments onto frag_list. Upper-layer socket receive paths dispatch based on skb_frags_readable() of the head skb (for example, tcp_recvmsg_locked() routes to skb_copy_datagram_msg() vs. tcp_recvmsg_dmabuf()), and require uniform readability across all frag_list entries. Mixing readable and unreadable fragments in the same reassembly queue (for example, when fragments split across a devmem queue and a normal queue, or when a size-threshold spill places only larger fragments in unreadable netmem) produces a mixed-readability reassembled skb that fails on delivery with -EFAULT or -ENODEV.

Reject a fragment in inet_frag_queue_insert() when its readability differs from the fragments already in the queue, mirroring IPFRAG_MIXED_SECPATH, while continuing to allow uniformly unreadable fragments to reassemble. Also propagate head->unreadable to the wrapper skb allocated by inet_frag_reasm_prepare() when the first fragment already carries a frag_list.

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM
---
 include/net/inet_frag.h  |  1 +
 net/ipv4/inet_fragment.c | 13 ++++++++++---
 2 files changed, 11 insertions(+), 3 deletions(-)
include/net/inet_frag.h +1 -0
index c1fb419a9cf03..668cb042b36b3 100644
@@ -175,6 +175,7 @@ extern const u8 ip_frag_ecn_table[16];
 #define IPFRAG_OVERLAP 2
 #define IPFRAG_MIXED_SECPATH   3
 #define IPFRAG_TOOBIG  4
+#define IPFRAG_MIXED_READABILITY       5
 
 /* Max sum of the truesize of fragments in a queue. This keeps the sums
  * done in inet_frag_reasm_prepare() and inet_frag_reasm_finish() well
net/ipv4/inet_fragment.c +8 -3
index f330d0a398233..caf07cf1a411c 100644
@@ -444,9 +444,15 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb,
 {
        struct sk_buff *last = q->fragments_tail;
 
-       /* The reassembled skb keeps the first fragment's secpath. */
-       if (last && !secpath_equal(last, skb))
-               return IPFRAG_MIXED_SECPATH;
+       /* The reassembled skb keeps the first fragment's secpath and
+        * readability state.
+        */
+       if (last) {
+               if (!secpath_equal(last, skb))
+                       return IPFRAG_MIXED_SECPATH;
+               if (skb_frags_readable(last) != skb_frags_readable(skb))
+                       return IPFRAG_MIXED_READABILITY;
Quoted 9 lines

net/ipv4/inet_fragment.c int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb, · line 456

Quoted 2 lines
net/ipv4/inet_fragment.c +1 -0
+       }
 

I think this regresses io_uring zcrx for fragmented TCP datagrams? Unlike tcp_recvmsg_locked() / tcp_recvmsg_dmabuf(), io_zcrx_recv_skb() -> io_zcrx_recv_frag() actually handles readability per-frag (it falls back to io_zcrx_copy_frag() when !skb_frag_is_net_iov(frag)) and walks frag_list recursively. I don't think we want to regress that.

I hadn't considered io_zcrx_recv_frag() handling per-frag readability across frag_list, thanks for pointing this out.

The underlying issue on a readable head + unreadable frag_list entry is that head->unreadable stays 0, so __pskb_pull_tail() skips its !skb_frags_readable(skb) check and hits BUG_ON(skb_copy_bits()).

If we instead propagate head->unreadable |= skb->unreadable in inet_frag_reasm_finish() and clone->unreadable = head->unreadable in inet_frag_reasm_prepare() plus guarding skb_frag_is_net_iov(&shinfo->frags[0]) in validate_xmit_unreadable_skb(), io_zcrx_recv_skb() continues to handle mixed frag_list datagrams per-frag while preventing the BUG_ON().

What do you think?

Quoted 3 lines

--
Thanks,
Mina

#11 lore raw

Re: [PATCH net 03/10] inet: frag: reject fragments with mixed readability in reassembly

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 2

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] The patch propagates head->unreadable to the wrapper skb that inet_frag_reasm_prepare() (net/ipv4/inet_fragment.c) allocates when…
- [Low] The commit message says the patch will "reject a fragment" when its readability differs from the queue's.
- [Low] The commit message gives two triggers for mixed readability.

--

inet: frag: reject fragments with mixed readability in reassembly

This patch makes inet_frag_queue_insert() reject a fragment when its readability differs from the fragments already queued, in the same way as the existing secpath check. It also copies head->unreadable to the wrapper skb that inet_frag_reasm_prepare() allocates when the first fragment already carries a frag_list.

Quoted 5 lines

Mixing readable and unreadable fragments in the same reassembly queue (for example, when fragments split across a devmem queue and a normal queue, or when a size-threshold spill places only larger fragments in unreadable netmem) produces a mixed-readability reassembled skb that fails on delivery with -EFAULT or -ENODEV.

[Severity: Low]

Can the size-threshold example happen in this tree?

Both devmem and io_uring zcrx bind through netif_mp_open_rxq()->__netif_mp_open_rxq(), and that function refuses a non-zero header-data-split threshold:

net/core/netdev_rx_queue.c:__netif_mp_open_rxq() {
    ...
	if (dev->cfg->hds_thresh) {
		NL_SET_ERR_MSG(extack, "hds-thresh is not zero");
		return -EINVAL;
	}
    ...
}

With hds_thresh == 0, the payload of every packet on a memory provider queue goes to net_iov frags. Drivers also cannot copybreak net_iov memory. So a threshold-based mix within one queue does not look possible upstream, and only the cross-queue case seems to apply to current kernels.

That example may come from the per-socket devmem RX work mentioned later in the message. Could it be dropped or qualified, so stable backporters get an accurate picture of the exposure?

Quoted 9 lines
net/ipv4/inet_fragment.c +0 -1
index f330d0a398233..caf07cf1a411c 100644
@@ -444,9 +444,15 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb,
 {
 	struct sk_buff *last = q->fragments_tail;
 
-	/* The reassembled skb keeps the first fragment's secpath. */

net/ipv4/inet_fragment.c int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb, · line 454

Quoted 10 lines
net/ipv4/inet_fragment.c +8 -2
-	if (last && !secpath_equal(last, skb))
-		return IPFRAG_MIXED_SECPATH;
+	/* The reassembled skb keeps the first fragment's secpath and
+	 * readability state.
+	 */
+	if (last) {
+		if (!secpath_equal(last, skb))
+			return IPFRAG_MIXED_SECPATH;
+		if (skb_frags_readable(last) != skb_frags_readable(skb))
+			return IPFRAG_MIXED_READABILITY;

[Severity: Low]

The commit message says this will "reject a fragment". Don't the callers end up discarding the whole datagram instead?

In ip_frag_queue(), every error except IPFRAG_DUP falls through to discard_qp:

net/ipv4/ip_fragment.c:ip_frag_queue() {
    ...
insert_error:
	if (err == IPFRAG_DUP) {
		SKB_DR_SET(reason, DUP_FRAG);
		err = -EINVAL;
		goto err;
	}
	if (err == IPFRAG_OVERLAP)
		__IP_INC_STATS(net, IPSTATS_MIB_REASM_OVERLAPS);
	err = -EINVAL;
discard_qp:
	inet_frag_kill(&qp->q, refs);
	__IP_INC_STATS(net, IPSTATS_MIB_REASMFAILS);
    ...
}

ip6_frag_queue() and nf_ct_frag6_queue() also treat any non-DUP error as a failure.

So a single fragment that lands on a queue with different readability kills the queue and drops every fragment already queued. One example is a non-first fragment that RSS hashes away from the devmem queue.

Dropping the datagram matches IPFRAG_MIXED_SECPATH. However, the skb is freed with the default NOT_SPECIFIED drop reason, and there is no dedicated counter like IPSTATS_MIB_REASM_OVERLAPS. Only REASMFAILS goes up.

Would a specific drop reason or counter be worth adding? Could the commit message also say that the whole datagram is discarded?

net/ipv4/inet_fragment.c void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb, · line 651

Quoted 12 lines
net/ipv4/inet_fragment.c +2 -0
+	}
 
 	if (skb->truesize > INET_FRAG_MAX_TRUESIZE - q->truesize)
 		return IPFRAG_TOOBIG;
@@ -639,6 +645,7 @@ void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb,
 		head->truesize += clone->truesize;
 		clone->csum = 0;
 		clone->ip_summed = head->ip_summed;
+		clone->unreadable = head->unreadable;
 		add_frag_mem_limit(q->fqdir, clone->truesize);
 		skb_shinfo(head)->frag_list = clone;
 		nextp = &clone->next;

[Severity: Medium]

With this propagation, can the devmem receive path actually deliver the nested layout built here? After this branch the chain is:

head->frag_list = clone
clone->frag_list = original frag_list of the first fragment
clone->next = later fragments (nextp = &clone->next is used by
inet_frag_reasm_finish())

tcp_recvmsg_dmabuf() moves to the next skb with:

net/ipv4/tcp.c:tcp_recvmsg_dmabuf() {
    ...
		skb = skb_shinfo(skb)->frag_list ?: skb->next;
    ...
}
Quoted 1 line

From the clone, it goes down into clone->frag_list and follows that

chain to NULL. It never comes back to clone->next.

The bytes of the later fragments are never reached, and remaining_len stays non-zero. The result is -EFAULT, or a short read followed by -EFAULT on the next call.

Before this patch, the readable clone failed earlier with -ENODEV:

	if (skb_frags_readable(skb)) {
		err = -ENODEV;
		goto out;
	}

So this input is not a regression. But it also doesn't seem to deliver the "uniformly unreadable fragments to reassemble" case described in the commit message.

The readable path, __skb_datagram_iter() via skb_walk_frags(), handles nested frag_lists, so only the devmem consumer disagrees with this layout. The accompanying KUnit test only checks the readability flag on the wrapper, not delivery.

Hitting this needs an unreadable first fragment that already has a frag_list. One example is the inner first fragment of a tunnelled datagram that was reassembled itself, so it may be uncommon.

Should tcp_recvmsg_dmabuf() walk nested frag_lists? Or should reassembly avoid building this layout when the head is unreadable?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796329894.git.tavip%40google.com
#12 lore raw

PATCH 4/10 net: skbuff, skmsg, strparser: reject unreadable frags

In reply to Octavian Purdila

Scatterlist and sockmap/strparser consumers assume skb fragments are backed by CPU-accessible struct pages. If an skb carrying unreadable net_iov fragments reaches these paths (for instance via a devmem RX queue or after attaching a socket with queued devmem data), walking its fragments dereferences NULL page pointers or livelocks in delayed work retrying skb_linearize() on non-EMSGSIZE errors.

Fail fast with -EFAULT on unreadable skbs in scatterlist conversion, __skb_send_sock(), sockmap verdict processing, and strparser, and propagate non-EMSGSIZE enqueue errors while clearing SK_PSOCK_TX_ENABLED to stop further pass-verdict ingress queuing onto the faulted socket.

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM
---
 net/core/skbuff.c         |  8 ++++++++
 net/core/skmsg.c          | 10 ++++++++++
 net/strparser/strparser.c |  5 +++++
 3 files changed, 23 insertions(+)
net/core/skbuff.c +8 -0
index 8ac7ad1378a12..d20d08682a132 100644
@@ -3380,6 +3380,11 @@ static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
 	if (!len)
 		goto out;
 
+	if (unlikely(!skb_frags_readable(skb)) && skb_shinfo(skb)->nr_frags) {
+		ret = -EFAULT;
+		goto error;
+	}
+
 	/* Make offset relative to start of frags */
 	offset -= skb_headlen(skb);
 
@@ -5391,6 +5396,9 @@ __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
 		offset += copy;
 	}
 
+	if (unlikely(!skb_frags_readable(skb)) && skb_shinfo(skb)->nr_frags)
+		return -EFAULT;
+
 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
 		int end;
 
net/core/skmsg.c +10 -0
index 8a3b8536c0c21..f56393b43a462 100644
@@ -560,6 +560,9 @@ static int sk_psock_skb_ingress_enqueue(struct sk_buff *skb,
 	 */
 	num_sge = skb_to_sgvec(skb, msg->sg.data, off, len);
 	if (num_sge < 0) {
+		if (num_sge != -EMSGSIZE)
+			return num_sge;
+
 		/* skb linearize may fail with ENOMEM, but lets simply try again
 		 * later if this happens. Under memory pressure we don't want to
 		 * drop the skb. We need to linearize the skb so that the mapping
@@ -1015,6 +1018,13 @@ static int sk_psock_verdict_apply(struct sk_psock *psock, struct sk_buff *skb,
 	    skb_bpf_redirect_fetch(skb) == psock->sk)
 		verdict = __SK_PASS;
 
+	if (verdict != __SK_DROP && unlikely(!skb_frags_readable(skb))) {
+		sk_psock_report_error(psock, EFAULT);
+		sk_psock_clear_state(psock, SK_PSOCK_TX_ENABLED);
+		err = -EFAULT;
+		goto out_free;
+	}
+
 	switch (verdict) {
 	case __SK_PASS:
 		err = -EIO;
net/strparser/strparser.c +5 -0
index 9c1559d7923f2..e030eda7509cb 100644
@@ -99,6 +99,11 @@ static int strp_recv(read_descriptor_t *desc, struct sk_buff *orig_skb,
 	if (strp->paused)
 		return 0;
 
+	if (unlikely(!skb_frags_readable(orig_skb))) {
+		strp_parser_err(strp, -EFAULT, desc);
+		return 0;
+	}
+
 	head = strp->skb_head;
 	if (head) {
 		/* Message already in progress */
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
#13 lore raw

Re: [PATCH net 04/10] net: skbuff, skmsg, strparser: reject unreadable frags

Quoted 2 lines · Octavian Purdila

Scatterlist and sockmap/strparser consumers assume skb fragments are

Is there a realistic path to get unreadable skbs in these code paths?

Signature · 2 lines
Thanks,
Mina
#14 lore raw

Re: [PATCH net 04/10] net: skbuff, skmsg, strparser: reject unreadable frags

Quoted 8 lines · Mina Almasry
Quoted 2 lines · Octavian Purdila

Scatterlist and sockmap/strparser consumers assume skb fragments are

Is there a realistic path to get unreadable skbs in these code paths?

Not sure how realistic it is, but with standard queue-based devmem RX (NETDEV_CMD_BIND_RX + flow steering) and a BPF sockmap program attached to the receiving socket:
- BPF_SK_SKB_VERDICT redirect panics in skb_splice_from_iter() via
__skb_send_sock()
- BPF_SK_SKB_STREAM_PARSER (> MAX_MSG_FRAGS) livelocks
sk_psock_backlog() retrying skb_linearize().

Patch 8 covers the underlying helpers via KUnit, and I verified the sockmap crash/livelock on netdevsim.

Quoted 3 lines

--
Thanks,
Mina

#15 lore raw

Re: [PATCH net 04/10] net: skbuff, skmsg, strparser: reject unreadable frags

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] net: __skb_send_sock() transmits linear head and masks -EFAULT --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] net: __skb_send_sock() transmits linear head and masks -EFAULT
--

commit 176413a89d4b1baf360d64806067d08b833448bd
Author: Octavian Purdila <[email protected]>

net: skbuff, skmsg, strparser: reject unreadable frags

This commit adds readability checks for skb fragments in scatterlist conversion, __skb_send_sock(), sockmap verdict processing, and strparser to fail with -EFAULT on unreadable frags.

Quoted 5 lines
net/core/skbuff.c +0 -0
index 8ac7ad1378a12..d20d08682a132 100644

net/core/skbuff.c static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, · line 3389

Quoted 10 lines
net/core/skbuff.c +5 -0
@@ -3380,6 +3380,11 @@ static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
 	if (!len)
 		goto out;
 
+	if (unlikely(!skb_frags_readable(skb)) && skb_shinfo(skb)->nr_frags) {
+		ret = -EFAULT;
+		goto error;
+	}
+
 	/* Make offset relative to start of frags */
 	offset -= skb_headlen(skb);

[Severity: Medium]
Does this check run too late in __skb_send_sock(), after the linear head has already been sent and -EFAULT is masked?

When the requested range spans linear head data and unreadable fragments (or an unreadable frag_list member), the preceding loop sends the head and decrements len. At error:, orig_len != len, so __skb_send_sock() masks -EFAULT and returns the positive partial byte count instead.

Looping callers such as espintcp_sendskb_locked() then put a partial linear prefix on the wire before seeing -EFAULT on the next call. Checking whether the requested range reaches any unreadable fragments before sending linear bytes would avoid partial transmission.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#16 lore raw

Re: [PATCH net 04/10] net: skbuff, skmsg, strparser: reject unreadable frags

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] Concern: the commit message says the issue was "reproduced and verified with the accompanying net_test KUnit tests", but this commit…
- [Low] The commit uses the trailer "Assisted-by: LLM".
- [Low] The patch adds a new error class to skb_to_sgvec() but leaves its documentation and the related comments unchanged.

--

net: skbuff, skmsg, strparser: reject unreadable frags

This patch makes scatterlist conversion, __skb_send_sock(), sockmap verdict processing and strparser return -EFAULT when they see skbs with unreadable net_iov frags, rather than dereferencing NULL page pointers. sk_psock_skb_ingress_enqueue() now passes errors other than -EMSGSIZE back to the caller instead of retrying skb_linearize(). The verdict path also clears SK_PSOCK_TX_ENABLED on the faulted psock.

Quoted 3 lines

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying net_test KUnit tests.

[Severity: Low]
This is probably fine, but the KUnit tests mentioned here are not in this commit. They seem to come later in the series, in "net: kunit: test unreadable net_iov defrag and skb helpers". There, netmem_unreadable_test_sg_and_strp() checks that skb_to_sgvec() returns -EFAULT, and also exercises skb_send_sock_locked() and strp_data_ready().

Would it be worth naming that patch here?

Quoted 3 lines
Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM

[Severity: Low]
This isn't a bug, but Assisted-by is not one of the tags in $signature_tags in scripts/checkpatch.pl. Checkpatch will give a non-standard signature (BAD_SIGN_OFF) warning for this line.

"LLM" also doesn't name the tool. Documentation/process/generated-content.rst asks "What tools were used?".

Documentation/process/maintainer-netdev.rst asks that bug fixes describe how the issue was found and validated "in plain English, not with special tags or annotations".

Could the tool use go in the commit message body instead? The same trailer is on the other patches in the series.

Quoted 4 lines
net/core/skbuff.c +0 -0
index 8ac7ad1378a12..d20d08682a132 100644

[ ... ]

Quoted 15 lines
net/core/skbuff.c +3 -0
@@ -5391,6 +5396,9 @@ __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
 		offset += copy;
 	}
 
+	if (unlikely(!skb_frags_readable(skb)) && skb_shinfo(skb)->nr_frags)
+		return -EFAULT;
+
 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
 		int end;
 
net/core/skmsg.c +0 -0
index 8a3b8536c0c21..f56393b43a462 100644

net/core/skmsg.c static int sk_psock_skb_ingress_enqueue(struct sk_buff *skb, · line 568

Quoted 9 lines
net/core/skmsg.c +3 -0
@@ -560,6 +560,9 @@ static int sk_psock_skb_ingress_enqueue(struct sk_buff *skb,
 	 */
 	num_sge = skb_to_sgvec(skb, msg->sg.data, off, len);
 	if (num_sge < 0) {
+		if (num_sge != -EMSGSIZE)
+			return num_sge;
+
 		/* skb linearize may fail with ENOMEM, but lets simply try again
 		 * later if this happens. Under memory pressure we don't want to
 		 * drop the skb. We need to linearize the skb so that the mapping

[Severity: Low]
Should the documentation and comments be updated now that skb_to_sgvec() can return -EFAULT?

The skb_to_sgvec() kernel-doc in net/core/skbuff.c still lists only one error:

* region of the buffer space attached to a socket buffer. Returns either
* the number of scatterlist items used, or -EMSGSIZE if the contents
* could not fit.

This caller now handles -EMSGSIZE differently from other errors. The comments around it still say skb_to_sgvec() fails only when MAX_MSG_FRAGS is exceeded, and that after linearizing "the mapping in skb_to_sgvec can not error".

The comment in sk_psock_verdict_apply() also looks out of date:

* queue work otherwise we may get OOO data. Otherwise,
* if sk_psock_skb_ingress errors will be handled by
* retrying later from workqueue.

When the error is not -EAGAIN, sk_psock_backlog() does not retry. It treats the error as a hard error:

				/* Hard errors break pipe and stop xmit. */
				sk_psock_report_error(psock, ret ? -ret : EPIPE);
				sk_psock_clear_state(psock, SK_PSOCK_TX_ENABLED);
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796329894.git.tavip%40google.com
#17 lore raw

PATCH 5/10 tls: reject unreadable skbs in tls_strp

In reply to Octavian Purdila

Software kTLS receive parses and decrypts TLS records on the CPU, assuming queued fragments are readable struct pages. If TLS_RX is configured on a socket with unreadable net_iov data in its receive queue (or receiving from a devmem RX queue), tls_strp either anchors unreadable skbs for CPU decryption or triggers warnings and advances skb lengths over uninitialized memory when skb_copy_bits() fails.

Reject unreadable skbs in tls_strp queue validation and abort stream parsing cleanly with -EFAULT if unreadable fragments are encountered.

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying devmem.py selftests.

Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM
---
 net/tls/tls_strp.c | 24 ++++++++++++++++++++++--
 1 file changed, 22 insertions(+), 2 deletions(-)
net/tls/tls_strp.c +22 -2
index 53d3256d0114a..a9e49384a1692 100644
@@ -45,6 +45,11 @@ tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb,
 	struct sk_buff *skb;
 	int i, err;
 
+	if (unlikely(!skb_frags_readable(in_skb))) {
+		tls_strp_abort_strp(strp, -EFAULT);
+		return NULL;
+	}
+
 	skb = alloc_skb_with_frags(0, len, TLS_PAGE_ORDER,
 				   &err, strp->sk->sk_allocation);
 	if (!skb)
@@ -53,9 +58,13 @@ tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb,
 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
 
-		WARN_ON_ONCE(skb_copy_bits(in_skb, offset,
+		if (unlikely(skb_copy_bits(in_skb, offset,
 					   skb_frag_address(frag),
-					   skb_frag_size(frag)));
+					   skb_frag_size(frag)))) {
+			kfree_skb(skb);
+			tls_strp_abort_strp(strp, -EFAULT);
+			return NULL;
+		}
 		offset += skb_frag_size(frag);
 	}
 
@@ -349,6 +358,12 @@ static int tls_strp_copyin(read_descriptor_t *desc, struct sk_buff *in_skb,
 	if (strp->msg_ready)
 		return 0;
 
+	if (unlikely(!skb_frags_readable(in_skb))) {
+		tls_strp_abort_strp(strp, -EFAULT);
+		desc->error = -EFAULT;
+		return 0;
+	}
+
 	skb = strp->anchor;
 	if (!skb->len)
 		skb_copy_decrypted(skb, in_skb);
@@ -438,6 +453,8 @@ static bool tls_strp_check_queue_ok(struct tls_strparser *strp,
 	u32 seq;
 
 	first = skb_shinfo(strp->anchor)->frag_list;
+	if (unlikely(!skb_frags_readable(first)))
+		return false;
 	skb = first;
 	seq = TCP_SKB_CB(first)->seq;
 
@@ -449,6 +466,9 @@ static bool tls_strp_check_queue_ok(struct tls_strparser *strp,
 		remaining -= skb->len;
 		skb = skb->next;
 
+		if (unlikely(!skb_frags_readable(skb)))
+			return false;
+
 		if (TCP_SKB_CB(skb)->seq != seq)
 			return false;
 		if (skb_cmp_decrypted(first, skb))
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
#18 lore raw

Re: [PATCH net 05/10] tls: reject unreadable skbs in tls_strp

Quoted 27 lines · Octavian Purdila

Software kTLS receive parses and decrypts TLS records on the CPU, assuming queued fragments are readable struct pages. If TLS_RX is configured on a socket with unreadable net_iov data in its receive queue (or receiving from a devmem RX queue), tls_strp either anchors unreadable skbs for CPU decryption or triggers warnings and advances skb lengths over uninitialized memory when skb_copy_bits() fails.

Reject unreadable skbs in tls_strp queue validation and abort stream parsing cleanly with -EFAULT if unreadable fragments are encountered.

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying devmem.py selftests.

Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Assisted-by LLM
---
 net/tls/tls_strp.c | 24 ++++++++++++++++++++++--
 1 file changed, 22 insertions(+), 2 deletions(-)
net/tls/tls_strp.c +0 -0
index 53d3256d0114a..a9e49384a1692 100644

net/tls/tls_strp.c tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb, · line 52

Quoted 8 lines
net/tls/tls_strp.c +5 -0
@@ -45,6 +45,11 @@ tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb,
        struct sk_buff *skb;
        int i, err;
 
+       if (unlikely(!skb_frags_readable(in_skb))) {
+               tls_strp_abort_strp(strp, -EFAULT);
+               return NULL;
+       }
+

Honestly I think these explicity checks in relatively high-level functions, I don't like.

I think in this case for example the real problem is that skb_copy_bits is failing. Lets make this call site handle a generic failure instead of explicitily checking readability.

Probably something similar should happen in all the other callers. I think the call site should detect some skb helper failing, not checking explicitly for readability.

Signature · 2 lines
Thanks,
Mina
#19 lore raw

Re: [PATCH net 05/10] tls: reject unreadable skbs in tls_strp

Quoted 11 lines · Mina Almasry

Honestly I think these explicity checks in relatively high-level functions, I don't like.

I think in this case for example the real problem is that skb_copy_bits is failing. Lets make this call site handle a generic failure instead of explicitily checking readability.

Probably something similar should happen in all the other callers. I think the call site should detect some skb helper failing, not checking explicitly for readability.

Agreed. The other TLS paths already check skb helper errors (tls_rx_msg_size() checks skb_copy_bits() and decrypt_skb_update() checks skb_to_sgvec()), and the real gap in tls_strp.c is the unchecked WARN_ON_ONCE(skb_copy_bits(...)) calls.

In v2 I'll drop the explicit !skb_frags_readable() checks and instead check skb_copy_bits() in tls_strp_skb_copy() and tls_strp_copyin_frag(), aborting the strparser and propagating the error (rather than turning it into -ENOMEM).

#20 lore raw

Re: [PATCH net 05/10] tls: reject unreadable skbs in tls_strp

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] tls: tls_strp_check_queue_ok() enters copy mode on unreadable skbs - [Medium] tls…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] tls: tls_strp_check_queue_ok() enters copy mode on unreadable skbs
- [Medium] tls: tls_strp_skb_copy() returns NULL on -EFAULT, misreported as -ENOMEM
- [Medium] tls: tls_strp_msg_load() skips queue validation on force_refresh
- [Medium] tls: tls_strp_copyin_frag() ignores skb_copy_bits() errors on frag_list
--

commit 2c01b4221727542d5938c961d8c4dd858cff2e10
Author: Octavian Purdila <[email protected]>

tls: reject unreadable skbs in tls_strp

This commit checks skb_frags_readable() in tls_strp_skb_copy(), tls_strp_copyin(), and tls_strp_check_queue_ok(), and aborts stream parsing with -EFAULT when unreadable fragments or skb_copy_bits() failures are encountered.

Quoted 21 lines
net/tls/tls_strp.c +5 -1
index 53d3256d0114a..a9e49384a1692 100644
@@ -45,6 +45,11 @@ tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb,
 	struct sk_buff *skb;
 	int i, err;
 
+	if (unlikely(!skb_frags_readable(in_skb))) {
+		tls_strp_abort_strp(strp, -EFAULT);
+		return NULL;
+	}
+
 	skb = alloc_skb_with_frags(0, len, TLS_PAGE_ORDER,
 				   &err, strp->sk->sk_allocation);
 	if (!skb)
@@ -53,9 +58,13 @@ tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb,
 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
 
-		WARN_ON_ONCE(skb_copy_bits(in_skb, offset,

net/tls/tls_strp.c tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb, · line 69

Quoted 10 lines
net/tls/tls_strp.c +6 -1
+		if (unlikely(skb_copy_bits(in_skb, offset,
 					   skb_frag_address(frag),
-					   skb_frag_size(frag)));
+					   skb_frag_size(frag)))) {
+			kfree_skb(skb);
+			tls_strp_abort_strp(strp, -EFAULT);
+			return NULL;
+		}
 		offset += skb_frag_size(frag);
 	}

[Severity: Medium]
Does returning NULL after tls_strp_abort_strp() cause callers to misreport -EFAULT as -ENOMEM?

All callers of tls_strp_skb_copy() (tls_strp_copyin_skb(), tls_strp_msg_cow(), and tls_decrypt_device() via tls_strp_msg_detach()) treat a NULL return as an allocation failure and return -ENOMEM. On the hardware offload path, tls_rx_one_record() then calls tls_err_abort(sk, -EBADMSG), overwriting the EFAULT just written to sk->sk_err, and returns -ENOMEM to userspace.

On the copyin path, tls_strp_check_rcv() sees -ENOMEM and queues strp->work on tls_strp_wq even though strp->stopped is already set. Returning ERR_PTR(-EFAULT) vs ERR_PTR(-ENOMEM) from tls_strp_skb_copy() and tls_strp_msg_make_copy() would preserve -EFAULT and avoid clobbering sk->sk_err or scheduling dead work.

net/tls/tls_strp.c static int tls_strp_copyin(read_descriptor_t *desc, struct sk_buff *in_skb, · line 369

Quoted 13 lines
net/tls/tls_strp.c +6 -0
@@ -349,6 +358,12 @@ static int tls_strp_copyin(read_descriptor_t *desc, struct sk_buff *in_skb,
 	if (strp->msg_ready)
 		return 0;
 
+	if (unlikely(!skb_frags_readable(in_skb))) {
+		tls_strp_abort_strp(strp, -EFAULT);
+		desc->error = -EFAULT;
+		return 0;
+	}
+
 	skb = strp->anchor;
 	if (!skb->len)
 		skb_copy_decrypted(skb, in_skb);

[Severity: Medium]
Can an skb with a readable head and an unreadable frag_list member still bypass this check and hit unchecked skb_copy_bits() calls in tls_strp_copyin_frag()?

skb_gro_receive() checks p->pp_recycle != skb->pp_recycle but not p->unreadable != skb->unreadable, so a readable pp_recycle head skb can chain an unreadable devmem skb onto frag_list (for example via gro_cells_receive() or a driver sharing one NAPI across RX queues).

When that happens, tls_strp_copyin() passes the head skb check and enters tls_strp_copyin_frag(), where both WARN_ON_ONCE(skb_copy_bits(...)) calls ignore -EFAULT, trigger a kernel warning, skip tls_strp_abort_strp(), and advance skb->len, skb->data_len, and frag size over uninitialized pages from alloc_page(). Checking the return value of both skb_copy_bits() calls in tls_strp_copyin_frag() and aborting with tls_strp_abort_strp(strp, -EFAULT) would match tls_strp_skb_copy().

Quoted 10 lines
net/tls/tls_strp.c +2 -0
@@ -438,6 +453,8 @@ static bool tls_strp_check_queue_ok(struct tls_strparser *strp,
 	u32 seq;
 
 	first = skb_shinfo(strp->anchor)->frag_list;
+	if (unlikely(!skb_frags_readable(first)))
+		return false;
 	skb = first;
 	seq = TCP_SKB_CB(first)->seq;
 

net/tls/tls_strp.c static bool tls_strp_check_queue_ok(struct tls_strparser *strp, · line 474

Quoted 9 lines
net/tls/tls_strp.c +3 -0
@@ -449,6 +466,9 @@ static bool tls_strp_check_queue_ok(struct tls_strparser *strp,
 		remaining -= skb->len;
 		skb = skb->next;
 
+		if (unlikely(!skb_frags_readable(skb)))
+			return false;
+
 		if (TCP_SKB_CB(skb)->seq != seq)
 			return false;
 		if (skb_cmp_decrypted(first, skb))

[Severity: Medium]
Should tls_strp_check_queue_ok() abort directly on unreadable skbs instead of returning false and entering copy mode?

Both callers in tls_strp_read_sock() treat a false return as a recoverable queue anomaly and call tls_strp_read_copy(strp, false). That allocates up to 20 KiB of pages (under GFP_ATOMIC in softirq) and discards the -EFAULT from tls_strp_read_copyin(), leaving those pages pinned on strp->anchor until socket close.

It also defers to tls_strp_wq on allocation failure instead of aborting, and consumes and ACKs any preceding readable skbs in the same record before hitting the unreadable skb. Aborting with -EFAULT directly and returning an error status to tls_strp_read_sock() would avoid the copy-mode fallback.

[Severity: Medium]
What about tls_strp_msg_load() when force_refresh is true?

tls_strp_msg_load() is the other caller of tls_strp_load_anchor_with_queue(), and it reloads strp->anchor without calling tls_strp_check_queue_ok(). If a validated readable record is drained from sk_receive_queue (for example via getsockopt(IPPROTO_TCP, TCP_ZEROCOPY_RECEIVE) forwarded by tls_getsockopt()) while an unreadable devmem skb of at least strp->stm.full_len bytes remains queued behind it, tls_strp_msg_load() anchors the unreadable skb and hands it to tls_rx_one_record().

tls_rx_one_record() then allocates decrypt buffers, fails, and calls tls_err_abort(sk, -EBADMSG) without stopping strp or clearing strp->msg_ready, so SO_ERROR reports EBADMSG, tls_sk_poll() keeps reporting EPOLLIN | EPOLLRDNORM, and later reads keep re-anchoring and failing on the same skb. Re-checking tls_strp_check_queue_ok(strp, strp->stm.full_len) in tls_strp_msg_load() and clearing strp->msg_ready on failure would route it back through tls_strp_read_sock() to abort cleanly with -EFAULT.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#21 lore raw

Re: [PATCH net 05/10] tls: reject unreadable skbs in tls_strp

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 2

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] The patch only closes part of the bug class it describes.
- [Low] After this patch, a NULL return from tls_strp_skb_copy() can mean two things.
- [Low] tls_strp_check_queue_ok() now also rejects unreadable skbs, but its comment still says only "Make sure there's no duplicate data in…

--

tls: reject unreadable skbs in tls_strp

This patch makes tls_strp reject skbs with unreadable (net_iov) frags. It adds readability checks to tls_strp_check_queue_ok(), tls_strp_copyin() and tls_strp_skb_copy(), and aborts the parser with -EFAULT when it finds unreadable data. It also changes the WARN_ON_ONCE() around skb_copy_bits() in tls_strp_skb_copy() into a checked failure path.

Quoted 19 lines
net/tls/tls_strp.c +5 -0
index 53d3256d0114a..a9e49384a1692 100644
@@ -45,6 +45,11 @@ tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb,
 	struct sk_buff *skb;
 	int i, err;
 
+	if (unlikely(!skb_frags_readable(in_skb))) {
+		tls_strp_abort_strp(strp, -EFAULT);
+		return NULL;
+	}
+
 	skb = alloc_skb_with_frags(0, len, TLS_PAGE_ORDER,
 				   &err, strp->sk->sk_allocation);
 	if (!skb)
@@ -53,9 +58,13 @@ tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb,
 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];

net/tls/tls_strp.c tls_strp_skb_copy(struct tls_strparser *strp, struct sk_buff *in_skb, · line 67

Quoted 10 lines
net/tls/tls_strp.c +6 -2
 
-		WARN_ON_ONCE(skb_copy_bits(in_skb, offset,
+		if (unlikely(skb_copy_bits(in_skb, offset,
 					   skb_frag_address(frag),
-					   skb_frag_size(frag)));
+					   skb_frag_size(frag)))) {
+			kfree_skb(skb);
+			tls_strp_abort_strp(strp, -EFAULT);
+			return NULL;
+		}

[Severity: Low]
With this change, a NULL return from tls_strp_skb_copy() can mean either of two things. It can be a transient alloc_skb_with_frags() failure. It can also be a permanent fault, where tls_strp_abort_strp(strp, -EFAULT) has already set strp->stopped and sk_err.

The callers still turn every NULL into -ENOMEM:

tls_strp_copyin_skb():

	nskb = tls_strp_skb_copy(strp, in_skb, offset, chunk);
	if (!nskb)
		return -ENOMEM;

tls_strp_msg_cow():

	skb = tls_strp_msg_make_copy(strp);
	if (!skb)
		return -ENOMEM;

tls_device_reencrypt() passes the tls_strp_msg_cow() error up. Also, tls_rx_one_record() in tls_sw.c returns -ENOMEM when tls_strp_msg_detach() returns NULL. Could recvmsg then report ENOMEM while sk_err on the lower socket holds EFAULT?

In copy mode, tls_strp_check_rcv() also treats this as memory pressure:

	if (tls_strp_read_sock(strp) == -ENOMEM)
		queue_work(tls_strp_wq, &strp->work);

The queued work only exits because strp->stopped happens to be set.

In practice, the new !skb_frags_readable(in_skb) check here doesn't seem reachable:

- From tls_strp_copyin_skb(), tls_strp_copyin() checks first.
- From tls_strp_msg_make_copy(), the anchor's unreadable bit is copied from first, which tls_strp_check_queue_ok() has already validated.

That leaves only the skb_copy_bits() failure branch, i.e. the nested frag_list case described below.

Would returning ERR_PTR(-EFAULT), or passing the error back through an int pointer, better match the commit message's "abort stream parsing cleanly with -EFAULT"?

Quoted 3 lines
net/tls/tls_strp.c +0 -0
 		offset += skb_frag_size(frag);
 	}
 

[ ... ]

net/tls/tls_strp.c static int tls_strp_copyin(read_descriptor_t *desc, struct sk_buff *in_skb, · line 366

Quoted 10 lines
net/tls/tls_strp.c +6 -0
@@ -349,6 +358,12 @@ static int tls_strp_copyin(read_descriptor_t *desc, struct sk_buff *in_skb,
 	if (strp->msg_ready)
 		return 0;
 
+	if (unlikely(!skb_frags_readable(in_skb))) {
+		tls_strp_abort_strp(strp, -EFAULT);
+		desc->error = -EFAULT;
+		return 0;
+	}
+

[Severity: Medium]
This only checks the unreadable bit on the head in_skb. Can a readable head skb still carry unreadable skbs on its own frag_list?

skb_copy_bits() recurses into frag_list members and returns -EFAULT for any member where !skb_frags_readable() is true. tls_strp_copyin_frag() still ignores that return value, both in the header copy and in the "Load up more data" loop:

tls_strp_copyin_frag() {
    ...
		WARN_ON_ONCE(skb_copy_bits(in_skb, offset,
					   skb_frag_address(frag) +
					   skb_frag_size(frag),
					   chunk));

		skb->len += chunk;
		skb->data_len += chunk;
		skb_frag_size_add(frag, chunk);
    ...
}

If that happens, isn't this still the case the commit message describes:
"triggers warnings and advances skb lengths over uninitialized memory when skb_copy_bits() fails"?

The pages come from alloc_page() in tls_strp_read_copy() and are not zeroed. tls_rx_msg_size() would parse those bytes, and they would then be passed to decryption. For a record with decrypted set and mixed_decrypted == 0, which goes through tls_strp_copyin_frag(), the bytes would be treated as plaintext.

The path would be:

tls_strp_read_copy()
tls_strp_read_copyin()
tcp_read_sock()
tls_strp_copyin() <- head check passes
tls_strp_copyin_frag()
skb_copy_bits() <- -EFAULT on a frag_list child, ignored

tls_strp_check_queue_ok() has the same gap. It checks each top-level queue skb, but not the skbs on their frag_list.

As far as I can tell, the merge path in skb_gro_receive() and tcp_gro_receive() doesn't compare unreadable between p and skb before chaining onto frag_list. It checks pp_recycle, zcopy and decrypted, but not readability. The series adds a mixed-readability rejection for IP defrag, but I couldn't find an equivalent for GRO.

I also couldn't find a concrete in-tree producer of a readable head with an unreadable child, since devmem RX needs tcp-data-split with hds-thresh=0. So this may be theoretical.

This patch already converts the same pattern in tls_strp_skb_copy(). Should the two skb_copy_bits() calls in tls_strp_copyin_frag() also abort with -EFAULT and return an error, without advancing skb->len, skb->data_len and the frag size?

[ ... ]

Quoted 10 lines
net/tls/tls_strp.c +2 -0
@@ -438,6 +453,8 @@ static bool tls_strp_check_queue_ok(struct tls_strparser *strp,
 	u32 seq;
 
 	first = skb_shinfo(strp->anchor)->frag_list;
+	if (unlikely(!skb_frags_readable(first)))
+		return false;
 	skb = first;
 	seq = TCP_SKB_CB(first)->seq;
 

net/tls/tls_strp.c static bool tls_strp_check_queue_ok(struct tls_strparser *strp, · line 471

Quoted 6 lines
net/tls/tls_strp.c +3 -0
@@ -449,6 +466,9 @@ static bool tls_strp_check_queue_ok(struct tls_strparser *strp,
 		remaining -= skb->len;
 		skb = skb->next;
 
+		if (unlikely(!skb_frags_readable(skb)))
+			return false;
+

[Severity: Low]
This isn't a bug, but the comment in tls_strp_check_queue_ok() still only mentions the old checks:

	/* Make sure there's no duplicate data in the queue,
	 * and the decrypted status matches.
	 */

Should it also mention the readability check?

A false return now has two meanings. It can mean the zero-copy anchor isn't usable but copy mode will work, as before. It can also mean the data is unreadable and copy mode can't help. Both callers in tls_strp_read_sock() still handle it the same way:

	if (!tls_strp_check_queue_ok(strp, strp->stm.full_len))
		return tls_strp_read_copy(strp, false);

With qshort == false, tls_strp_read_copy() allocates up to TLS_MAX_PAYLOAD_SIZE + PAGE_SIZE worth of pages and switches to copy mode. It then calls tls_strp_read_copyin() and ignores the return value.

Only after that does tls_strp_copyin() abort on the unreadable skb, and the -EFAULT is only visible through strp->stopped and sk_err. The pages are freed later on tls_strp_done(), so nothing leaks.

Would it be cleaner to abort directly from tls_strp_read_sock() in the unreadable case, rather than setting up copy mode first?

Quoted 3 lines
net/tls/tls_strp.c +0 -0
 		if (TCP_SKB_CB(skb)->seq != seq)
 			return false;
 		if (skb_cmp_decrypted(first, skb))
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796329894.git.tavip%40google.com
#22 lore raw

PATCH 6/10 tcp: reject unreadable skbs on TCP-MD5 and TCP-AO

In reply to Octavian Purdila

Software TCP-MD5 and TCP-AO compute packet digests on the CPU by mapping skb fragments via skb_frag_foreach_page() and kmap_local_page(), which dereferences NULL page pointers on unreadable net_iov fragments on both receive and transmit. In addition, tcp_ao_verify_hash() ignored tcp_ao_hash_skb() errors and compared the incoming option against a zeroed buffer.

Fail signature payload hashing with -EFAULT on unreadable skbs and check hash helper errors across TCP-MD5 and TCP-AO receive and reset paths. On transmit, disallow devmem sends in tcp_sendmsg_locked() when TCP-MD5 or TCP-AO is active on the socket, reject enabling TCP-MD5 or TCP-AO keys while unreadable skbs are queued on the write or retransmit queues, and keep a defensive guard in __tcp_transmit_skb().

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying devmem.py selftests.

Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Fixes bd61848900bf ("net: devmem: Implement TX path")
Assisted-by LLM
---
 include/net/tcp.h     | 33 ++++++++++++++++++++++++---------
 net/ipv4/tcp.c        | 32 +++++++++++++++++++++++++-------
 net/ipv4/tcp_ao.c     | 29 ++++++++++++++++++++---------
 net/ipv4/tcp_ipv4.c   | 13 +++++++++----
 net/ipv4/tcp_output.c |  9 ++++++++-
 net/ipv6/tcp_ipv6.c   | 10 ++++++----
 6 files changed, 92 insertions(+), 34 deletions(-)
include/net/tcp.h +24 -9
index 869e780fcb482..b189236e89dc9 100644
@@ -2104,8 +2104,8 @@ struct tcp6_pseudohdr {
 	__be32		protocol;	/* including padding */
 };
 
-void tcp_v4_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key,
-			 const struct sock *sk, const struct sk_buff *skb);
+int tcp_v4_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key,
+			const struct sock *sk, const struct sk_buff *skb);
 int tcp_md5_do_add(struct sock *sk, const union tcp_md5_addr *addr,
 		   int family, u8 prefixlen, int l3index, u8 flags,
 		   const u8 *newkey, u8 newkeylen);
@@ -2165,8 +2165,8 @@ static inline void tcp_md5_destruct_sock(struct sock *sk)
 #endif
 
 struct md5_ctx;
-void tcp_md5_hash_skb_data(struct md5_ctx *ctx, const struct sk_buff *skb,
-			   unsigned int header_len);
+int tcp_md5_hash_skb_data(struct md5_ctx *ctx, const struct sk_buff *skb,
+			  unsigned int header_len);
 void tcp_md5_hash_key(struct md5_ctx *ctx, const struct tcp_md5sig_key *key);
 
 /* From tcp_fastopen.c */
@@ -2358,6 +2358,21 @@ static inline bool tcp_rtx_and_write_queues_empty(const struct sock *sk)
 	return tcp_rtx_queue_empty(sk) && tcp_write_queue_empty(sk);
 }
 
+static inline bool tcp_tx_has_unreadable_skb(const struct sock *sk)
+{
+	struct sk_buff *skb;
+
+	skb_queue_walk(&sk->sk_write_queue, skb) {
+		if (!skb_frags_readable(skb))
+			return true;
+	}
+	skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
+		if (!skb_frags_readable(skb))
+			return true;
+	}
+	return false;
+}
+
 static inline void tcp_add_write_queue_tail(struct sock *sk, struct sk_buff *skb)
 {
 	__skb_queue_tail(&sk->sk_write_queue, skb);
@@ -2549,7 +2564,7 @@ struct tcp_sock_af_ops {
 #ifdef CONFIG_TCP_MD5SIG
 	struct tcp_md5sig_key	*(*md5_lookup) (const struct sock *sk,
 						const struct sock *addr_sk);
-	void		(*calc_md5_hash)(char *location,
+	int		(*calc_md5_hash)(char *location,
 					 const struct tcp_md5sig_key *md5,
 					 const struct sock *sk,
 					 const struct sk_buff *skb);
@@ -2577,10 +2592,10 @@ struct tcp_request_sock_ops {
 #ifdef CONFIG_TCP_MD5SIG
 	struct tcp_md5sig_key *(*req_md5_lookup)(const struct sock *sk,
 						 const struct sock *addr_sk);
-	void		(*calc_md5_hash) (char *location,
-					  const struct tcp_md5sig_key *md5,
-					  const struct sock *sk,
-					  const struct sk_buff *skb);
+	int		(*calc_md5_hash)(char *location,
+					 const struct tcp_md5sig_key *md5,
+					 const struct sock *sk,
+					 const struct sk_buff *skb);
 #endif
 #ifdef CONFIG_TCP_AO
 	struct tcp_ao_key *(*ao_lookup)(const struct sock *sk,
net/ipv4/tcp.c +25 -7
index 80de376a9d2ef..f0ab18b589872 100644
@@ -1226,6 +1226,16 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 		/* 'common' sending to sendq */
 	}
 
+	if (unlikely(binding)) {
+		struct tcp_key key;
+
+		tcp_get_current_key(sk, &key);
+		if (tcp_key_is_md5(&key) || tcp_key_is_ao(&key)) {
+			err = -EOPNOTSUPP;
+			goto out_err;
+		}
+	}
+
 	if (sockc_err) {
 		err = sockc_err;
 		goto out_err;
@@ -4891,8 +4901,8 @@ int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
 }
 
 #ifdef CONFIG_TCP_MD5SIG
-void tcp_md5_hash_skb_data(struct md5_ctx *ctx, const struct sk_buff *skb,
-			   unsigned int header_len)
+int tcp_md5_hash_skb_data(struct md5_ctx *ctx, const struct sk_buff *skb,
+			  unsigned int header_len)
 {
 	const unsigned int head_data_len = skb_headlen(skb) > header_len ?
 					   skb_headlen(skb) - header_len : 0;
@@ -4900,6 +4910,9 @@ void tcp_md5_hash_skb_data(struct md5_ctx *ctx, const struct sk_buff *skb,
 	struct sk_buff *frag_iter;
 	unsigned int i;
 
+	if (unlikely(!skb_frags_readable(skb)))
+		return -EFAULT;
+
 	md5_update(ctx, (const u8 *)tcp_hdr(skb) + header_len, head_data_len);
 
 	for (i = 0; i < shi->nr_frags; ++i) {
@@ -4916,8 +4929,12 @@ void tcp_md5_hash_skb_data(struct md5_ctx *ctx, const struct sk_buff *skb,
 		}
 	}
 
-	skb_walk_frags(skb, frag_iter)
-		tcp_md5_hash_skb_data(ctx, frag_iter, 0);
+	skb_walk_frags(skb, frag_iter) {
+		if (tcp_md5_hash_skb_data(ctx, frag_iter, 0))
+			return -EFAULT;
+	}
+
+	return 0;
 }
 
 void tcp_md5_hash_key(struct md5_ctx *ctx,
@@ -4945,6 +4962,7 @@ tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb,
 	const struct tcp_sock *tp = tcp_sk(sk);
 	struct tcp_md5sig_key *key;
 	u8 newhash[16];
+	int err;
 
 	key = tcp_md5_do_lookup(sk, l3index, saddr, family);
 	if (!key) {
@@ -4958,10 +4976,10 @@ tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb,
 	 * IPv4-mapped case.
 	 */
 	if (family == AF_INET)
-		tcp_v4_md5_hash_skb(newhash, key, NULL, skb);
+		err = tcp_v4_md5_hash_skb(newhash, key, NULL, skb);
 	else
-		tp->af_specific->calc_md5_hash(newhash, key, NULL, skb);
-	if (crypto_memneq(hash_location, newhash, 16)) {
+		err = tp->af_specific->calc_md5_hash(newhash, key, NULL, skb);
+	if (err || crypto_memneq(hash_location, newhash, 16)) {
 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5FAILURE);
 		trace_tcp_hash_md5_mismatch(sk, skb);
 		return SKB_DROP_REASON_TCP_MD5FAILURE;
net/ipv4/tcp_ao.c +20 -9
index 857b8684e01d9..34c69dfcedd04 100644
@@ -679,9 +679,9 @@ int tcp_ao_hash_hdr(unsigned short int family, char *ao_hash,
 	return 1;
 }
 
-static void tcp_ao_hash_skb_data(struct tcp_ao_mac_ctx *mac_ctx,
-				 const struct sk_buff *skb,
-				 unsigned int header_len)
+static int tcp_ao_hash_skb_data(struct tcp_ao_mac_ctx *mac_ctx,
+				const struct sk_buff *skb,
+				unsigned int header_len)
 {
 	const unsigned int head_data_len = skb_headlen(skb) > header_len ?
 					   skb_headlen(skb) - header_len : 0;
@@ -689,6 +689,9 @@ static void tcp_ao_hash_skb_data(struct tcp_ao_mac_ctx *mac_ctx,
 	struct sk_buff *frag_iter;
 	unsigned int i;
 
+	if (unlikely(!skb_frags_readable(skb)))
+		return -EFAULT;
+
 	tcp_ao_mac_update(mac_ctx, (const u8 *)tcp_hdr(skb) + header_len,
 			  head_data_len);
 
@@ -706,8 +709,12 @@ static void tcp_ao_hash_skb_data(struct tcp_ao_mac_ctx *mac_ctx,
 		}
 	}
 
-	skb_walk_frags(skb, frag_iter)
-		tcp_ao_hash_skb_data(mac_ctx, frag_iter, 0);
+	skb_walk_frags(skb, frag_iter) {
+		if (tcp_ao_hash_skb_data(mac_ctx, frag_iter, 0))
+			return -EFAULT;
+	}
+
+	return 0;
 }
 
 int tcp_ao_hash_skb(unsigned short int family,
@@ -726,7 +733,8 @@ int tcp_ao_hash_skb(unsigned short int family,
 	tcp_ao_hash_header(&mac_ctx, th,
 			   !!(key->keyflags & TCP_AO_KEYF_EXCLUDE_OPT),
 			   ao_hash, hash_offset, tcp_ao_maclen(key));
-	tcp_ao_hash_skb_data(&mac_ctx, skb, th->doff << 2);
+	if (tcp_ao_hash_skb_data(&mac_ctx, skb, th->doff << 2))
+		goto clear_hash;
 	tcp_ao_mac_final(&mac_ctx, hash_buf);
 
 	memcpy(ao_hash, hash_buf, tcp_ao_maclen(key));
@@ -970,9 +978,9 @@ tcp_ao_verify_hash(const struct sock *sk, const struct sk_buff *skb,
 	}
 
 	/* XXX: make it per-AF callback? */
-	tcp_ao_hash_skb(family, hash_buf, key, sk, skb, traffic_key,
-			(phash - (u8 *)th), sne);
-	if (crypto_memneq(phash, hash_buf, maclen)) {
+	if (tcp_ao_hash_skb(family, hash_buf, key, sk, skb, traffic_key,
+			    (phash - (u8 *)th), sne) ||
+	    crypto_memneq(phash, hash_buf, maclen)) {
 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAOBAD);
 		atomic64_inc(&info->counters.pkt_bad);
 		atomic64_inc(&key->pkt_bad);
@@ -1665,6 +1673,9 @@ static int tcp_ao_add_cmd(struct sock *sk, unsigned short int family,
 	if (IS_ERR(ao_info))
 		return PTR_ERR(ao_info);
 
+	if (tcp_tx_has_unreadable_skb(sk))
+		return -EOPNOTSUPP;
+
 	if (!ao_info) {
 		ao_info = tcp_ao_alloc_info(GFP_KERNEL);
 		if (!ao_info)
net/ipv4/tcp_ipv4.c +9 -4
index 8aa52376cf0aa..2f2b187a1ed85 100644
@@ -817,8 +817,8 @@ static void tcp_v4_send_reset(const struct sock *sk, struct sk_buff *skb,
 		if (!key)
 			goto out;
 
-		tcp_v4_md5_hash_skb(newhash, key, NULL, skb);
-		if (crypto_memneq(md5_hash_location, newhash, 16))
+		if (tcp_v4_md5_hash_skb(newhash, key, NULL, skb) ||
+		    crypto_memneq(md5_hash_location, newhash, 16))
 			goto out;
 	}
 
@@ -1399,6 +1399,9 @@ int tcp_md5_do_add(struct sock *sk, const union tcp_md5_addr *addr,
 {
 	struct tcp_sock *tp = tcp_sk(sk);
 
+	if (tcp_tx_has_unreadable_skb(sk))
+		return -EOPNOTSUPP;
+
 	if (!rcu_dereference_protected(tp->md5sig_info, lockdep_sock_is_held(sk))) {
 		if (fips_enabled) {
 			pr_warn_once("TCP-MD5 support is disabled due to FIPS\n");
@@ -1576,7 +1579,7 @@ tcp_v4_md5_hash_hdr(char *md5_hash, const struct tcp_md5sig_key *key,
 	md5_final(&ctx, md5_hash);
 }
 
-noinline_for_stack void
+noinline_for_stack int
 tcp_v4_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key,
 		    const struct sock *sk, const struct sk_buff *skb)
 {
@@ -1595,9 +1598,11 @@ tcp_v4_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key,
 
 	md5_init(&ctx);
 	tcp_v4_md5_hash_headers(&ctx, daddr, saddr, th, skb->len);
-	tcp_md5_hash_skb_data(&ctx, skb, th->doff << 2);
+	if (tcp_md5_hash_skb_data(&ctx, skb, th->doff << 2))
+		return -EFAULT;
 	tcp_md5_hash_key(&ctx, key);
 	md5_final(&ctx, md5_hash);
+	return 0;
 }
 
 #endif
net/ipv4/tcp_output.c +8 -1
index 043838d996404..6749ec5873dfd 100644
@@ -1606,6 +1606,14 @@ static int __tcp_transmit_skb(struct sock *sk, struct sk_buff *skb,
 
 	BUG_ON(!skb || !tcp_skb_pcount(skb));
 	tp = tcp_sk(sk);
+	tcp_get_current_key(sk, &key);
+	if (unlikely(!skb_frags_readable(skb) &&
+		     (tcp_key_is_md5(&key) || tcp_key_is_ao(&key)))) {
+		if (!clone_it)
+			kfree_skb(skb);
+		return -EOPNOTSUPP;
+	}
+
 	prior_wstamp = tp->tcp_wstamp_ns;
 	tp->tcp_wstamp_ns = max(tp->tcp_wstamp_ns, tp->tcp_clock_cache);
 	skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC);
@@ -1631,7 +1639,6 @@ static int __tcp_transmit_skb(struct sock *sk, struct sk_buff *skb,
 	tcb = TCP_SKB_CB(skb);
 	memset(&opts.cleared, 0, sizeof(opts.cleared));
 
-	tcp_get_current_key(sk, &key);
 	if (unlikely(tcb->tcp_flags & TCPHDR_SYN)) {
 		tcp_options_size = tcp_syn_options(sk, skb, &opts, &key);
 	} else {
net/ipv6/tcp_ipv6.c +6 -4
index 5c7ed38f1f56a..61bfdd5108740 100644
@@ -751,7 +751,7 @@ tcp_v6_md5_hash_hdr(char *md5_hash, const struct tcp_md5sig_key *key,
 	md5_final(&ctx, md5_hash);
 }
 
-static noinline_for_stack void
+static noinline_for_stack int
 tcp_v6_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key,
 		    const struct sock *sk, const struct sk_buff *skb)
 {
@@ -770,9 +770,11 @@ tcp_v6_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key,
 
 	md5_init(&ctx);
 	tcp_v6_md5_hash_headers(&ctx, daddr, saddr, th, skb->len);
-	tcp_md5_hash_skb_data(&ctx, skb, th->doff << 2);
+	if (tcp_md5_hash_skb_data(&ctx, skb, th->doff << 2))
+		return -EFAULT;
 	tcp_md5_hash_key(&ctx, key);
 	md5_final(&ctx, md5_hash);
+	return 0;
 }
 #endif
 
@@ -1083,8 +1085,8 @@ static void tcp_v6_send_reset(const struct sock *sk, struct sk_buff *skb,
 			goto out;
 		key.type = TCP_KEY_MD5;
 
-		tcp_v6_md5_hash_skb(newhash, key.md5_key, NULL, skb);
-		if (crypto_memneq(md5_hash_location, newhash, 16))
+		if (tcp_v6_md5_hash_skb(newhash, key.md5_key, NULL, skb) ||
+		    crypto_memneq(md5_hash_location, newhash, 16))
 			goto out;
 	}
 #endif
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
#23 lore raw

Re: [PATCH net 06/10] tcp: reject unreadable skbs on TCP-MD5 and TCP-AO

Quoted 15 lines · Octavian Purdila

Software TCP-MD5 and TCP-AO compute packet digests on the CPU by mapping skb fragments via skb_frag_foreach_page() and kmap_local_page(), which dereferences NULL page pointers on unreadable net_iov fragments on both receive and transmit. In addition, tcp_ao_verify_hash() ignored tcp_ao_hash_skb() errors and compared the incoming option against a zeroed buffer.

Fail signature payload hashing with -EFAULT on unreadable skbs and check hash helper errors across TCP-MD5 and TCP-AO receive and reset paths. On transmit, disallow devmem sends in tcp_sendmsg_locked() when TCP-MD5 or TCP-AO is active on the socket, reject enabling TCP-MD5 or TCP-AO keys while unreadable skbs are queued on the write or retransmit queues, and keep a defensive guard in __tcp_transmit_skb().

Quoted 8 lines

This issue was found by code inspection while developing per-socket devmem RX and reproduced and verified with the accompanying devmem.py selftests.

Fixes 65249feb6b3d ("net: add support for skbs with unreadable frags")
Fixes bd61848900bf ("net: devmem: Implement TX path")
Assisted-by LLM

This patch is too complicated for human review for me tbh. I would say drop it and post it by itself in its own patch (or even series, yikes this is complicated).

Or maybe a higher expert than me would be able to review this.

My LLM is pointing to many issues:

```
Wait, there is a TOCTOU race here that lets unreadable devmem skbs still
end up queued on an MD5/AO socket:

tcp_sendmsg_locked() only runs this check once before the send loop.
Inside the loop, wait_for_space calls sk_stream_wait_memory(), which
drops and re-acquires the socket lock. If no unreadable skb is queued
yet during that sleep (e.g. the send buffer held only earlier readable
data, or all prior devmem skbs were ACKed and freed while we slept), a
concurrent setsockopt(TCP_MD5SIG) (or TCP_REPAIR + TCP_AO_ADD_KEY) sees
tcp_tx_has_unreadable_skb(sk) == false and installs the key. When
sendmsg wakes up, it loops around and queues new unreadable devmem skbs
without rechecking tcp_get_current_key().

A second path doesn't even go through tcp_md5_do_add():
tcp_v4_md5_lookup() derives l3index from addr_sk->sk_bound_dev_if, so
SO_BINDTODEVICE on an established socket can activate a pre-existing
IFINDEX-scoped MD5 key after devmem skbs are already queued.

And once an unreadable skb is queued on an MD5/AO socket, two bad things
happen:

1. On the normal xmit path, __tcp_transmit_skb() returns -EOPNOTSUPP,
which tcp_write_xmit() treats like a transient error (just `break;`).
sendmsg() already reported success for those bytes, so the unreadable
skb sits stuck at the head of sk_write_queue and stalls the connection
until timeout (or forever if ACKs keep resetting probe0).

2. Worse, on current `net` (90ae4042bd9f), if MTU probing runs
(tcp_mtu_probing=2, or =1 after blackhole), tcp_clone_payload() copies
net_iov frags from the devmem skbs (which have skb_headlen == 0) into
the freshly allocated probe skb via skb_frag_page_copy() WITHOUT setting
to->unreadable = 1. (My tcp_clone_payload() unreadable fix hasn't hit
`net` yet.) That probe skb then has unreadable == 0 with net_iov frags,
so it bypasses BOTH the __tcp_transmit_skb() guard AND the
skb_frags_readable() check in tcp_md5_hash_skb_data() /
tcp_ao_hash_skb_data(), and crashes with a NULL page dereference in
skb_frag_foreach_page() / kmap_local_page().

Rechecking tcp_get_current_key() after sk_stream_wait_memory() (or on
new devmem segment allocation) closes the sendmsg race, and checking
skb_frag_is_net_iov(f) in the hashers (or fixing tcp_clone_payload()
here / as a prereq) closes the probe bypass.
```
Signature · 2 lines
Thanks,
Mina
#24 lore raw

Re: [PATCH net 06/10] tcp: reject unreadable skbs on TCP-MD5 and TCP-AO

Quoted 4 lines · Mina Almasry

This patch is too complicated for human review for me tbh. I would say drop it and post it by itself in its own patch (or even series, yikes this is complicated).

Fair point. I'll drop this patch (and its devmem.py selftest in 10/10) from v2 and revisit TCP-MD5/TCP-AO separately, addressing the sk_stream_wait_memory() TOCTOU, SO_BINDTODEVICE, and tcp_clone_payload() issues you flagged.

#25 lore raw

Re: [PATCH net 06/10] tcp: reject unreadable skbs on TCP-MD5 and TCP-AO

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] tcp: TOCTOU race in tcp_sendmsg_locked() queues devmem skb with MD5/AO - [Low] tcp: missing…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] tcp: TOCTOU race in tcp_sendmsg_locked() queues devmem skb with MD5/AO
- [Low] tcp: missing mac_ctx zeroization on error path in tcp_ao_hash_skb()
--

commit f478e860f2e25eba93883680fd5a2e35c2811f91
Author: Octavian Purdila <[email protected]>

tcp: reject unreadable skbs on TCP-MD5 and TCP-AO

This commit rejects unreadable devmem skbs in TCP-MD5 and TCP-AO digest calculation and checks the hash helper errors on receive and reset paths. On transmit, it blocks devmem sends when a TCP-MD5 or TCP-AO key is active, rejects adding keys while unreadable skbs are queued, and guards __tcp_transmit_skb().

Quoted 11 lines
net/ipv4/tcp.c +3 -0
index 80de376a9d2ef..f0ab18b589872 100644
@@ -1226,6 +1226,16 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 		/* 'common' sending to sendq */
 	}
 
+	if (unlikely(binding)) {
+		struct tcp_key key;
+

net/ipv4/tcp.c int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size) · line 1241

Quoted 10 lines
net/ipv4/tcp.c +7 -0
+		tcp_get_current_key(sk, &key);
+		if (tcp_key_is_md5(&key) || tcp_key_is_ao(&key)) {
+			err = -EOPNOTSUPP;
+			goto out_err;
+		}
+	}
+
 	if (sockc_err) {
 		err = sockc_err;
 		goto out_err;

[Severity: Medium]
Can a concurrent setsockopt(TCP_MD5SIG) race with sk_stream_wait_memory() and bypass this check?

tcp_sendmsg_locked() only checks tcp_get_current_key() once before the send loop, while sk_stream_wait_memory() drops and reacquires lock_sock(sk):

CPU0 CPU1
tcp_sendmsg_locked()
tcp_get_current_key() -> none
sk_stream_wait_memory()

    release_sock(sk)
                                setsockopt(TCP_MD5SIG)
                                  lock_sock(sk)
                                  tcp_md5_do_add()
                                    tcp_tx_has_unreadable_skb() -> false
                                    install MD5 key
                                  release_sock(sk)
    lock_sock(sk)

queue unreadable devmem skb <-- bypasses check

Once tcp_sendmsg_locked() queues the unreadable skb and returns success, __tcp_transmit_skb() rejects it with -EOPNOTSUPP without freeing it when clone_it is set. tcp_write_xmit() then breaks out leaving the skb stuck at tcp_send_head(sk), wedging TX until timeout, key removal, or socket close.

Re-checking tcp_get_current_key() for binding after sk_stream_wait_memory() returns would close this window.

[ ... ]

Quoted 4 lines
net/ipv4/tcp_ao.c +0 -0
index 857b8684e01d9..34c69dfcedd04 100644

[ ... ]

net/ipv4/tcp_ao.c int tcp_ao_hash_skb(unsigned short int family, · line 740

Quoted 10 lines
net/ipv4/tcp_ao.c +2 -1
@@ -726,7 +733,8 @@ int tcp_ao_hash_skb(unsigned short int family,
 	tcp_ao_hash_header(&mac_ctx, th,
 			   !!(key->keyflags & TCP_AO_KEYF_EXCLUDE_OPT),
 			   ao_hash, hash_offset, tcp_ao_maclen(key));
-	tcp_ao_hash_skb_data(&mac_ctx, skb, th->doff << 2);
+	if (tcp_ao_hash_skb_data(&mac_ctx, skb, th->doff << 2))
+		goto clear_hash;
 	tcp_ao_mac_final(&mac_ctx, hash_buf);
 
 	memcpy(ao_hash, hash_buf, tcp_ao_maclen(key));

[Severity: Low]
Does this error path leave mac_ctx unzeroized on the kernel stack?

Jumping to clear_hash skips tcp_ao_mac_final(), which normally clears the stack-local mac_ctx holding derived TCP-AO traffic-key state. Zeroizing mac_ctx with memzero_explicit() under clear_hash would match the crypto library cleanup contract.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#26 lore raw

Re: [PATCH net 06/10] tcp: reject unreadable skbs on TCP-MD5 and TCP-AO

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 2

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] The patch tries to stop unreadable (devmem) skbs on the TX queues from coexisting with an active TCP-MD5 key.
- [Low] The patch adds a new early exit in tcp_ao_hash_skb() (net/ipv4/tcp_ao.c): `if (tcp_ao_hash_skb_data(&mac_ctx, skb, th->doff…
- [Low] Documentation/networking/devmem.rst, 'Implementation & Caveats' -> 'Unreadable skbs', lists what breaks with devmem payloads:…

--

tcp: reject unreadable skbs on TCP-MD5 and TCP-AO

This patch makes the TCP-MD5 and TCP-AO payload hashing helpers fail with -EFAULT on unreadable (devmem) skbs, and checks those errors on the receive and reset paths. On transmit, it rejects devmem sends when an MD5 or AO key is active and rejects adding keys while unreadable skbs are queued. It also adds a guard in __tcp_transmit_skb().

Quoted 8 lines
net/ipv4/tcp.c +0 -0
index 80de376a9d2ef..f0ab18b589872 100644
@@ -1226,6 +1226,16 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 		/* 'common' sending to sendq */
 	}
 

net/ipv4/tcp.c int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size) · line 1238

Quoted 10 lines
net/ipv4/tcp.c +10 -0
+	if (unlikely(binding)) {
+		struct tcp_key key;
+
+		tcp_get_current_key(sk, &key);
+		if (tcp_key_is_md5(&key) || tcp_key_is_ao(&key)) {
+			err = -EOPNOTSUPP;
+			goto out_err;
+		}
+	}
+

[Severity: Medium]
This check runs only once, before the restart: label. Can a TCP-MD5 key become current after it has passed?

Inside the copy loop, new_segment can jump to wait_for_space. That happens, for example, when readable skbs from earlier sends fill sk_sndbuf:

wait_for_space:

		sk_set_nospace(sk);
		...
		err = sk_stream_wait_memory(sk, &timeo);

sk_stream_wait_memory() drops the socket lock in sk_wait_event(). While the lock is dropped, a concurrent setsockopt(TCP_MD5SIG) can run:

do_tcp_setsockopt()
tcp_v4_parse_md5_keys()
tcp_md5_do_add()
tcp_tx_has_unreadable_skb() <- only readable skbs queued so far

tcp_md5_do_add() has no socket state restriction, so the key gets installed. When the sender gets the lock back, it keeps queueing devmem skbs without checking the key again. The skb_frags_readable(skb) != !binding test forces new segments.

The TCP-AO version of this doesn't seem possible, because the first TCP_AO_ADD_KEY requires LISTEN or CLOSE state.

There also seems to be a way to get here with no key add at all. tcp_v4_md5_lookup() and tcp_v6_md5_lookup() take l3index from addr_sk->sk_bound_dev_if:

	l3index = l3mdev_master_ifindex_by_index(sock_net(sk),
						 addr_sk->sk_bound_dev_if);

Suppose a VRF-scoped (TCP_MD5SIG_FLAG_IFINDEX) key does not match the unbound socket. Devmem sends are then allowed and devmem skbs get queued.

A later first SO_BINDTODEVICE, or enslaving the device to the VRF, can make md5_lookup() return that key. tcp_md5_do_add() is never called in this case.

In both cases the guard added to __tcp_transmit_skb() fires on every transmit, retransmit and window probe. tcp_write_xmit() then leaves the skb at the head of the write queue:

		if (unlikely(tcp_transmit_skb(sk, skb, 1, gfp)))
			break;

sendmsg() has already reported this data as sent. Does the connection then stall until the probe or RTO limits abort it?

The guard does prevent the bad page mapping. However, the commit message calls it only "a defensive guard in __tcp_transmit_skb()", while this path is reachable and ends in a stall.

[ ... ]

Quoted 4 lines
net/ipv4/tcp_ao.c +0 -0
index 857b8684e01d9..34c69dfcedd04 100644

[ ... ]

net/ipv4/tcp_ao.c int tcp_ao_hash_skb(unsigned short int family, · line 740

Quoted 10 lines
net/ipv4/tcp_ao.c +2 -1
@@ -726,7 +733,8 @@ int tcp_ao_hash_skb(unsigned short int family,
 	tcp_ao_hash_header(&mac_ctx, th,
 			   !!(key->keyflags & TCP_AO_KEYF_EXCLUDE_OPT),
 			   ao_hash, hash_offset, tcp_ao_maclen(key));
-	tcp_ao_hash_skb_data(&mac_ctx, skb, th->doff << 2);
+	if (tcp_ao_hash_skb_data(&mac_ctx, skb, th->doff << 2))
+		goto clear_hash;
 	tcp_ao_mac_final(&mac_ctx, hash_buf);
 
 	memcpy(ao_hash, hash_buf, tcp_ao_maclen(key));

[Severity: Low]
This new exit is taken after tcp_ao_mac_init() has expanded the traffic key into the on-stack mac_ctx, and it skips tcp_ao_mac_final().

For HMAC-SHA1 and HMAC-SHA256, isn't the final step the only place the keyed context gets wiped? The library final routines end with memzero_explicit(ctx, sizeof(*ctx)). The clear_hash label only clears the output buffer:

clear_hash:

	memset(ao_hash, 0, tcp_ao_maclen(key));
	return 1;

On this path, the HMAC inner and outer state derived from the traffic key stays in the dead stack frame of tcp_ao_hash_skb(). A remote peer can reach this through tcp_ao_verify_hash()->tcp_ao_hash_skb() when AO-signed segments land on a devmem RX queue.

Could skb_frags_readable() be checked before tcp_ao_mac_init()? Alternatively, mac_ctx could be wiped with memzero_explicit() on the error path.

For AES-128-CMAC, aes_cmac_final() does not wipe mac_ctx->aes_cmac.key. The expanded AES key is therefore already left on the stack on the existing success path. Only the HMAC case is new here.

[ ... ]

net/ipv4/tcp_ao.c static int tcp_ao_add_cmd(struct sock *sk, unsigned short int family, · line 1678

Quoted 7 lines
net/ipv4/tcp_ao.c +3 -0
@@ -1665,6 +1673,9 @@ static int tcp_ao_add_cmd(struct sock *sk, unsigned short int family,
 	if (IS_ERR(ao_info))
 		return PTR_ERR(ao_info);
 
+	if (tcp_tx_has_unreadable_skb(sk))
+		return -EOPNOTSUPP;
+

[Severity: Low]
This isn't a bug, but Documentation/networking/devmem.rst has an "Unreadable skbs" caveat list. It covers loopback, software checksum, and tcpdump/bpf, but not the restrictions this patch adds:

- tcp_sendmsg_locked() returns -EOPNOTSUPP for devmem TX when TCP-MD5 or TCP-AO is active.

- setsockopt(TCP_MD5SIG/TCP_MD5SIG_EXT) via tcp_md5_do_add(), and setsockopt(TCP_AO_ADD_KEY) via tcp_ao_add_cmd(), return -EOPNOTSUPP while unreadable skbs are queued.

- Devmem RX segments on an MD5 or AO connection are dropped as authentication failures.

Could the caveat list be updated to say that devmem and TCP-MD5/TCP-AO cannot be combined?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796329894.git.tavip%40google.com
#27 lore raw

PATCH 7/10 net: kunit: test unreadable net_iov napi_gro_frags

In reply to Octavian Purdila

Add KUnit regression tests in net_test covering unreadable net_iov skb handling on napi_frags_skb() header-pull failure and NAPI GRO fragment reuse in napi_reuse_skb(), verifying that pull failures free the skb without crashing or leaking references, and that unreadable and pp_recycle flags are cleared on reuse with balanced page_pool and binding reference counts.

Assisted-by LLM
---
 net/core/net_test.c | 246 +++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 245 insertions(+), 1 deletion(-)
net/core/net_test.c +245 -1
index 47f5dc0fa5cf6..b939cc93e9050 100644
@@ -515,9 +515,13 @@ static void ip_tunnel_flags_test_run(struct kunit *test)
 
 /* Netmem & SKB fragment refcounting */
 
+#include <linux/etherdevice.h>
 #include <linux/skbuff_ref.h>
-#include <net/netmem.h>
+#include <net/gro.h>
+#include <net/ip.h>
+#include <net/netdev_lock.h>
 #include <net/netdev_rx_queue.h>
+#include <net/netmem.h>
 #include <net/page_pool/helpers.h>
 #include <net/page_pool/memory_provider.h>
 #include <net/tcp.h>
@@ -1720,6 +1724,244 @@ static void netmem_ref_test_tcp_devmem_recv(struct kunit *test)
 	page_pool_destroy(pool);
 	percpu_ref_exit(&binding.ref);
 }
+
+struct netmem_unreadable_env {
+	struct net_devmem_dmabuf_binding binding;
+	struct page_pool *pool;
+	struct net_iov niov;
+	netmem_ref niov_nm;
+	long base_ref;
+};
+
+static void netmem_unreadable_env_cleanup(struct netmem_unreadable_env *env)
+{
+	netmem_clear_pp_magic(env->niov_nm);
+	netmem_set_pp(env->niov_nm, NULL);
+	page_pool_destroy(env->pool);
+	percpu_ref_exit(&env->binding.ref);
+}
+
+KUNIT_DEFINE_ACTION_WRAPPER(netmem_unreadable_env_cleanup_action,
+			    netmem_unreadable_env_cleanup,
+			    struct netmem_unreadable_env *);
+
+static struct netmem_unreadable_env *
+netmem_unreadable_env_init(struct kunit *test)
+{
+	struct page_pool_params pp_params = {
+		.order = 0,
+		.pool_size = 8,
+		.nid = NUMA_NO_NODE,
+	};
+	struct netmem_unreadable_env *env;
+	int ret;
+
+	env = kunit_kzalloc(test, sizeof(*env), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, env);
+
+	ret = percpu_ref_init(&env->binding.ref, dummy_percpu_ref_release,
+			      PERCPU_REF_INIT_ATOMIC, GFP_KERNEL);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+
+	env->pool = page_pool_create(&pp_params);
+	if (IS_ERR(env->pool)) {
+		percpu_ref_exit(&env->binding.ref);
+		KUNIT_ASSERT_FALSE(test, IS_ERR(env->pool));
+	}
+
+	env->binding.area.niovs = &env->niov;
+	net_iov_init(&env->niov, &env->binding.area, NET_IOV_DMABUF);
+	env->niov_nm = net_iov_to_netmem(&env->niov);
+	netmem_set_pp(env->niov_nm, env->pool);
+	netmem_or_pp_magic(env->niov_nm, PP_SIGNATURE);
+	atomic_long_set(&env->niov.desc.pp_ref_count, 2);
+	env->base_ref = atomic_long_read(&env->binding.ref.data->count);
+
+	ret = kunit_add_action_or_reset(test,
+					netmem_unreadable_env_cleanup_action,
+					env);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+
+	return env;
+}
+
+static void netmem_unreadable_add_frag(struct sk_buff *skb,
+				       struct netmem_unreadable_env *env,
+				       u32 off, u32 len)
+{
+	skb->pp_recycle = 1;
+	skb_add_rx_frag_netmem(skb, 0, env->niov_nm, off, len, PAGE_SIZE);
+	napi_pp_get_page(env->niov_nm);
+}
+
+static void netmem_unreadable_env_check(struct kunit *test,
+					struct netmem_unreadable_env *env)
+{
+	KUNIT_EXPECT_EQ(test, atomic_long_read(&env->niov.desc.pp_ref_count),
+			2L);
+	KUNIT_EXPECT_EQ(test, atomic_long_read(&env->binding.ref.data->count),
+			env->base_ref);
+}
+
+struct gro_test_napi_ctx {
+	struct net_device *dev;
+	struct napi_struct napi;
+};
+
+static int dummy_napi_poll(struct napi_struct *napi, int budget)
+{
+	return 0;
+}
+
+static void gro_test_napi_cleanup(struct gro_test_napi_ctx *ctx)
+{
+	netdev_lock(ctx->dev);
+	__netif_napi_del_locked(&ctx->napi);
+	netdev_unlock(ctx->dev);
+	free_netdev(ctx->dev);
+}
+
+KUNIT_DEFINE_ACTION_WRAPPER(gro_test_napi_cleanup_action,
+			    gro_test_napi_cleanup,
+			    struct gro_test_napi_ctx *);
+
+static struct gro_test_napi_ctx *alloc_gro_test_napi(struct kunit *test)
+{
+	struct gro_test_napi_ctx *ctx;
+	int ret;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+
+	ctx->dev = alloc_etherdev(0);
+	KUNIT_ASSERT_NOT_NULL(test, ctx->dev);
+	ctx->dev->features |= NETIF_F_GRO;
+	netif_napi_add_weight(ctx->dev, &ctx->napi, dummy_napi_poll, 64);
+
+	ret = kunit_add_action_or_reset(test, gro_test_napi_cleanup_action,
+					ctx);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+
+	return ctx;
+}
+
+static void fill_tcp4_headers(struct sk_buff *skb, __be32 saddr, __be32 daddr,
+			      __be16 sport, __be16 dport, u32 seq, u32 ack_seq,
+			      unsigned int payload_len)
+{
+	struct ethhdr *eth;
+	struct tcphdr *th;
+	struct iphdr *iph;
+
+	skb_reset_mac_header(skb);
+	eth = skb_put_zero(skb, sizeof(*eth));
+	eth->h_proto = htons(ETH_P_IP);
+
+	skb_set_network_header(skb, skb->len);
+	iph = skb_put_zero(skb, sizeof(*iph));
+	iph->version = 4;
+	iph->ihl = 5;
+	iph->ttl = 64;
+	iph->protocol = IPPROTO_TCP;
+	iph->saddr = saddr;
+	iph->daddr = daddr;
+	iph->tot_len = htons(sizeof(*iph) + sizeof(*th) + payload_len);
+	ip_send_check(iph);
+
+	skb_set_transport_header(skb, skb->len);
+	th = skb_put_zero(skb, sizeof(*th));
+	th->source = sport;
+	th->dest = dport;
+	th->seq = htonl(seq);
+	th->ack_seq = htonl(ack_seq);
+	th->doff = sizeof(*th) / 4;
+	th->ack = 1;
+	th->window = htons(65535);
+
+	skb->protocol = htons(ETH_P_IP);
+	skb->ip_summed = CHECKSUM_UNNECESSARY;
+}
+
+static void netmem_unreadable_test_napi_pull_fail(struct kunit *test)
+{
+	struct netmem_unreadable_env *env = netmem_unreadable_env_init(test);
+	struct gro_test_napi_ctx *ctx = alloc_gro_test_napi(test);
+	struct napi_struct *napi = &ctx->napi;
+	gro_result_t ret = GRO_NORMAL;
+	bool has_cached = true;
+	struct sk_buff *skb;
+
+	/* Attach only an unreadable net_iov without linear ETH_HLEN so
+	 * napi_frags_skb() fails header pull: verify napi_gro_frags() returns
+	 * GRO_CONSUMED without crashing, caching a dirty skb, or leaking the
+	 * net_iov reference. napi_get_frags() and napi_gro_frags() require
+	 * BH-disabled NAPI context.
+	 */
+	local_bh_disable();
+	skb = napi_get_frags(napi);
+	if (skb) {
+		netmem_unreadable_add_frag(skb, env, 0, 64);
+		ret = napi_gro_frags(napi);
+		has_cached = !!napi->skb;
+	}
+	local_bh_enable();
+
+	KUNIT_ASSERT_NOT_NULL(test, skb);
+	KUNIT_EXPECT_EQ(test, ret, GRO_CONSUMED);
+	KUNIT_EXPECT_FALSE(test, has_cached);
+
+	kunit_release_action(test, gro_test_napi_cleanup_action, ctx);
+	netmem_unreadable_env_check(test, env);
+}
+
+static void netmem_unreadable_test_napi_reuse(struct kunit *test)
+{
+	struct netmem_unreadable_env *env = netmem_unreadable_env_init(test);
+	struct gro_test_napi_ctx *ctx = alloc_gro_test_napi(test);
+	struct napi_struct *napi = &ctx->napi;
+	gro_result_t ret1 = GRO_NORMAL, ret2 = GRO_NORMAL;
+	bool readable = false, pp_recycle = true;
+	struct sk_buff *skb;
+
+	/* Merge two unreadable pp_recycle segments via napi_gro_frags() so
+	 * napi_reuse_skb() caches the second skb on napi->skb, then verify
+	 * the cached skb has unreadable and pp_recycle cleared.
+	 * napi_get_frags() and napi_gro_frags() require BH-disabled context.
+	 */
+	local_bh_disable();
+	skb = napi_get_frags(napi);
+	if (!skb)
+		goto out_bh;
+	fill_tcp4_headers(skb, htonl(0xc0000201), htonl(0xc0000202),
+			  htons(10000), htons(20000), 1000, 1, 64);
+	netmem_unreadable_add_frag(skb, env, 0, 64);
+	ret1 = napi_gro_frags(napi);
+
+	skb = napi_get_frags(napi);
+	if (!skb)
+		goto out_bh;
+	fill_tcp4_headers(skb, htonl(0xc0000201), htonl(0xc0000202),
+			  htons(10000), htons(20000), 1064, 1, 64);
+	netmem_unreadable_add_frag(skb, env, 64, 64);
+	ret2 = napi_gro_frags(napi);
+
+	skb = napi_get_frags(napi);
+	if (skb) {
+		readable = skb_frags_readable(skb);
+		pp_recycle = skb->pp_recycle;
+	}
+out_bh:
+	local_bh_enable();
+
+	KUNIT_ASSERT_NOT_NULL(test, skb);
+	KUNIT_EXPECT_EQ(test, ret1, GRO_HELD);
+	KUNIT_EXPECT_EQ(test, ret2, GRO_MERGED_FREE);
+	KUNIT_EXPECT_TRUE(test, readable);
+	KUNIT_EXPECT_FALSE(test, pp_recycle);
+
+	kunit_release_action(test, gro_test_napi_cleanup_action, ctx);
+	netmem_unreadable_env_check(test, env);
+}
 #endif
 #endif
 
@@ -1789,6 +2031,8 @@ static struct kunit_case net_test_cases[] = {
 	KUNIT_CASE(netmem_ref_test_try_coalesce),
 #ifdef CONFIG_INET
 	KUNIT_CASE(netmem_ref_test_tcp_devmem_recv),
+	KUNIT_CASE(netmem_unreadable_test_napi_pull_fail),
+	KUNIT_CASE(netmem_unreadable_test_napi_reuse),
 #endif
 #endif
 	{ },
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
Reviewed-by on v1 7/10
#28 lore raw

Re: [PATCH net 07/10] net: kunit: test unreadable net_iov napi_gro_frags

Quoted 10 lines · Octavian Purdila

Add KUnit regression tests in net_test covering unreadable net_iov skb handling on napi_frags_skb() header-pull failure and NAPI GRO fragment reuse in napi_reuse_skb(), verifying that pull failures free the skb without crashing or leaking references, and that unreadable and pp_recycle flags are cleared on reuse with balanced page_pool and binding reference counts.

Assisted-by LLM

Do the maintainers like or hate the LLM-ism that it adds tons of tests for everything it does? Tests themselves are fine. Assuming we like adding so many tests:

Signature · 2 lines
Thanks,
Mina
#29 lore raw

Re: [PATCH net 07/10] net: kunit: test unreadable net_iov napi_gro_frags

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] net: kunit: netmem_unreadable_test_napi_reuse() does not verify skb reuse --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] net: kunit: netmem_unreadable_test_napi_reuse() does not verify skb reuse
--

commit 8e212ae67e43fed3dca591ffeed692d004c0027f
Author: Octavian Purdila <[email protected]>

net: kunit: test unreadable net_iov napi_gro_frags

This commit adds KUnit tests in net_test for unreadable net_iov skb handling in napi_gro_frags(), covering header-pull failure in napi_frags_skb() and skb flag clearing on reuse in napi_reuse_skb().

Quoted 4 lines
net/core/net_test.c +0 -0
index 47f5dc0fa5cf6..b939cc93e9050 100644

[ ... ]

Quoted 1 line
net/core/net_test.c +0 -0
@@ -1720,6 +1724,244 @@ static void netmem_ref_test_tcp_devmem_recv(struct kunit *test)

[ ... ]

Quoted 2 lines
net/core/net_test.c +2 -0
+static void netmem_unreadable_test_napi_reuse(struct kunit *test)
+{

[ ... ]

net/core/net_test.c static void netmem_ref_test_tcp_devmem_recv(struct kunit *test) · line 1952

Quoted 13 lines
net/core/net_test.c +13 -0
+	skb = napi_get_frags(napi);
+	if (!skb)
+		goto out_bh;
+	fill_tcp4_headers(skb, htonl(0xc0000201), htonl(0xc0000202),
+			  htons(10000), htons(20000), 1064, 1, 64);
+	netmem_unreadable_add_frag(skb, env, 64, 64);
+	ret2 = napi_gro_frags(napi);
+
+	skb = napi_get_frags(napi);
+	if (skb) {
+		readable = skb_frags_readable(skb);
+		pp_recycle = skb->pp_recycle;
+	}

[Severity: Low]
Does this verify that the third napi_get_frags() call actually returns the reused skb?

If napi_reuse_skb() drops the second skb (for instance when skb->pfmemalloc is set) and leaves napi->skb NULL, napi_get_frags() allocates a fresh skb with unreadable and pp_recycle already cleared, letting the test pass without exercising reuse.

Saving the second skb pointer and asserting that napi_get_frags() returns the same skb would catch a missed reuse.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#30 lore raw

Re: [PATCH net 07/10] net: kunit: test unreadable net_iov napi_gro_frags

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] In net/core/net_test.c, netmem_unreadable_test_napi_reuse() is meant to show that napi_reuse_skb() clears skb->unreadable and…

--

net: kunit: test unreadable net_iov napi_gro_frags

This commit adds two KUnit tests to net_test that cover unreadable net_iov skbs going through napi_gro_frags(). The first test checks that a header pull failure in napi_frags_skb() frees the skb without leaking references. The second test checks that napi_reuse_skb() clears unreadable and pp_recycle on the skb it caches on napi->skb.

Quoted 4 lines
net/core/net_test.c +0 -0
index 47f5dc0fa5cf6..b939cc93e9050 100644

[ ... ]

Quoted 1 line
net/core/net_test.c +0 -0
@@ -1720,6 +1724,244 @@ static void netmem_ref_test_tcp_devmem_recv(struct kunit *test)

[ ... ]

Quoted 26 lines
net/core/net_test.c +26 -0
+static void netmem_unreadable_test_napi_reuse(struct kunit *test)
+{
+	struct netmem_unreadable_env *env = netmem_unreadable_env_init(test);
+	struct gro_test_napi_ctx *ctx = alloc_gro_test_napi(test);
+	struct napi_struct *napi = &ctx->napi;
+	gro_result_t ret1 = GRO_NORMAL, ret2 = GRO_NORMAL;
+	bool readable = false, pp_recycle = true;
+	struct sk_buff *skb;
+
+	/* Merge two unreadable pp_recycle segments via napi_gro_frags() so
+	 * napi_reuse_skb() caches the second skb on napi->skb, then verify
+	 * the cached skb has unreadable and pp_recycle cleared.
+	 * napi_get_frags() and napi_gro_frags() require BH-disabled context.
+	 */
+	local_bh_disable();
+	skb = napi_get_frags(napi);
+	if (!skb)
+		goto out_bh;
+	fill_tcp4_headers(skb, htonl(0xc0000201), htonl(0xc0000202),
+			  htons(10000), htons(20000), 1000, 1, 64);
+	netmem_unreadable_add_frag(skb, env, 0, 64);
+	ret1 = napi_gro_frags(napi);
+
+	skb = napi_get_frags(napi);
+	if (!skb)
+		goto out_bh;

net/core/net_test.c static void netmem_ref_test_tcp_devmem_recv(struct kunit *test) · line 1952

Quoted 10 lines
net/core/net_test.c +10 -0
+	fill_tcp4_headers(skb, htonl(0xc0000201), htonl(0xc0000202),
+			  htons(10000), htons(20000), 1064, 1, 64);
+	netmem_unreadable_add_frag(skb, env, 64, 64);
+	ret2 = napi_gro_frags(napi);
+
+	skb = napi_get_frags(napi);
+	if (skb) {
+		readable = skb_frags_readable(skb);
+		pp_recycle = skb->pp_recycle;
+	}

[Severity: Low]
Can this check pass without napi_reuse_skb() ever caching the second skb?

Nothing confirms that the skb from the third napi_get_frags() is the same object as the second segment. napi_frags_finish() can also handle GRO_MERGED_FREE without caching anything:

net/core/gro.c:napi_frags_finish() {
    ...
	case GRO_MERGED_FREE:
		if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
			napi_skb_free_stolen_head(skb);
		else
			napi_reuse_skb(napi, skb);
		break;
    ...
}

napi_reuse_skb() can also exit early and free the skb:

net/core/gro.c:napi_reuse_skb() {
	...
	if (unlikely(skb->pfmemalloc)) {
		consume_skb(skb);
		return;
	}
	...
}

On either path napi->skb stays NULL. The third napi_get_frags() then returns a fresh skb from napi_alloc_skb(), and that skb already has unreadable and pp_recycle cleared. The checks on readable and pp_recycle would pass even though the reset was never tested.

The ret2 == GRO_MERGED_FREE check can't tell these cases apart, because all three paths return GRO_MERGED_FREE.

With the current skb_gro_receive() and the linear headers built by fill_tcp4_headers(), the packet should take the NAPI_GRO_FREE branch, so normal runs do exercise the reuse path. The gap appears only if the second skb is pfmemalloc, or if a later GRO change sends this case down the stolen-head path.

Would it help to save the second skb pointer and add KUNIT_EXPECT_PTR_EQ() against the third napi_get_frags() result? Checking that napi->skb is non-NULL before the third napi_get_frags() would also work.

Quoted 8 lines
net/core/net_test.c +8 -0
+out_bh:
+	local_bh_enable();
+
+	KUNIT_ASSERT_NOT_NULL(test, skb);
+	KUNIT_EXPECT_EQ(test, ret1, GRO_HELD);
+	KUNIT_EXPECT_EQ(test, ret2, GRO_MERGED_FREE);
+	KUNIT_EXPECT_TRUE(test, readable);
+	KUNIT_EXPECT_FALSE(test, pp_recycle);

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796329894.git.tavip%40google.com
#31 lore raw

PATCH 8/10 net: kunit: test unreadable net_iov defrag and skb helpers

In reply to Octavian Purdila

Add KUnit regression tests in net_test covering mixed-readability rejection and uniformly unreadable reassembly across IPv4 and Netfilter IPv6 fragment reassembly, scatterlist conversion via skb_to_sgvec(), skb_send_sock_locked(), and strparser stream aborting, verifying that page_pool and binding reference counts remain balanced.

Assisted-by LLM
---
 net/core/net_test.c | 382 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 382 insertions(+)
net/core/net_test.c +382 -0
index b939cc93e9050..8da6c5ab4430c 100644
@@ -516,14 +516,23 @@ static void ip_tunnel_flags_test_run(struct kunit *test)
 /* Netmem & SKB fragment refcounting */
 
 #include <linux/etherdevice.h>
+#include <linux/ipv6.h>
+#include <linux/scatterlist.h>
 #include <linux/skbuff_ref.h>
 #include <net/gro.h>
 #include <net/ip.h>
+#if IS_REACHABLE(CONFIG_NF_DEFRAG_IPV6)
+#include <net/ipv6_frag.h>
+#include <net/netfilter/ipv6/nf_defrag_ipv6.h>
+#endif
 #include <net/netdev_lock.h>
 #include <net/netdev_rx_queue.h>
 #include <net/netmem.h>
 #include <net/page_pool/helpers.h>
 #include <net/page_pool/memory_provider.h>
+#if IS_REACHABLE(CONFIG_STREAM_PARSER)
+#include <net/strparser.h>
+#endif
 #include <net/tcp.h>
 #include "devmem.h"
 #include "netmem_priv.h"
@@ -1962,6 +1971,377 @@ static void netmem_unreadable_test_napi_reuse(struct kunit *test)
 	kunit_release_action(test, gro_test_napi_cleanup_action, ctx);
 	netmem_unreadable_env_check(test, env);
 }
+
+static struct sk_buff *alloc_ipv4_frag_skb(u16 id, u16 frag_off)
+{
+	struct sk_buff *skb;
+	struct iphdr *iph;
+
+	skb = alloc_skb(64, GFP_KERNEL);
+	if (!skb)
+		return NULL;
+
+	skb->dev = init_net.loopback_dev;
+	skb_reset_network_header(skb);
+	iph = skb_put_zero(skb, sizeof(*iph));
+	iph->version = 4;
+	iph->ihl = 5;
+	iph->ttl = 64;
+	iph->id = htons(id);
+	iph->protocol = IPPROTO_UDP;
+	iph->saddr = htonl(0x7f000001);
+	iph->daddr = htonl(0x7f000001);
+	iph->frag_off = htons(frag_off);
+	iph->tot_len = htons(sizeof(*iph) + 16);
+	ip_send_check(iph);
+	return skb;
+}
+
+#if IS_REACHABLE(CONFIG_NF_DEFRAG_IPV6)
+static struct sk_buff *alloc_ipv6_frag_skb(u32 id, u16 frag_off)
+{
+	struct frag_hdr *fhdr;
+	struct ipv6hdr *ip6h;
+	struct sk_buff *skb;
+
+	skb = alloc_skb(128, GFP_KERNEL);
+	if (!skb)
+		return NULL;
+
+	skb->dev = init_net.loopback_dev;
+	skb->protocol = htons(ETH_P_IPV6);
+	skb_reset_network_header(skb);
+	ip6h = skb_put_zero(skb, sizeof(*ip6h));
+	ip6h->version = 6;
+	ip6h->nexthdr = NEXTHDR_FRAGMENT;
+	ip6h->hop_limit = 64;
+	ip6h->saddr.s6_addr[15] = 1;
+	ip6h->daddr.s6_addr[15] = 1;
+	ip6h->payload_len = htons(sizeof(*fhdr) + 16);
+	skb_set_transport_header(skb, skb->len);
+	fhdr = skb_put_zero(skb, sizeof(*fhdr));
+	fhdr->nexthdr = IPPROTO_UDP;
+	fhdr->frag_off = htons(frag_off);
+	fhdr->identification = htonl(id);
+	return skb;
+}
+#endif
+
+static void netmem_unreadable_test_ip_defrag(struct kunit *test)
+{
+	struct netmem_unreadable_env *env = netmem_unreadable_env_init(test);
+	struct sk_buff *frag1, *frag2, *child;
+	int err;
+
+	/* IPv4: readable first fragment + unreadable second fragment must fail
+	 * and tear down the fragment queue.
+	 */
+	frag1 = alloc_ipv4_frag_skb(0x4242, IP_MF);
+	frag2 = alloc_ipv4_frag_skb(0x4242, 16 >> 3);
+	if (!frag1 || !frag2) {
+		consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "failed to allocate IPv4 frags");
+	}
+	skb_put_zero(frag1, 16);
+	netmem_unreadable_add_frag(frag2, env, 0, 16);
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag1, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	if (err != -EINPROGRESS) {
+		if (!err)
+			consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "frag1 ip_defrag failed: %d", err);
+	}
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag2, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	KUNIT_EXPECT_EQ(test, err, -EINVAL);
+	if (!err)
+		consume_skb(frag2);
+
+	/* IPv4: unreadable first fragment + readable second fragment must fail
+	 * and release the queued unreadable fragment cleanly.
+	 */
+	frag1 = alloc_ipv4_frag_skb(0x4243, IP_MF);
+	frag2 = alloc_ipv4_frag_skb(0x4243, 16 >> 3);
+	if (!frag1 || !frag2) {
+		consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "failed to allocate IPv4 frags");
+	}
+	netmem_unreadable_add_frag(frag1, env, 0, 16);
+	skb_put_zero(frag2, 16);
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag1, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	if (err != -EINPROGRESS) {
+		if (!err)
+			consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "frag1 ip_defrag failed: %d", err);
+	}
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag2, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	KUNIT_EXPECT_EQ(test, err, -EINVAL);
+	if (!err)
+		consume_skb(frag2);
+
+	/* IPv4: uniformly unreadable fragments reassemble cleanly. */
+	frag1 = alloc_ipv4_frag_skb(0x4244, IP_MF);
+	frag2 = alloc_ipv4_frag_skb(0x4244, 16 >> 3);
+	if (!frag1 || !frag2) {
+		consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "failed to allocate IPv4 frags");
+	}
+	netmem_unreadable_add_frag(frag1, env, 0, 16);
+	netmem_unreadable_add_frag(frag2, env, 0, 16);
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag1, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	if (err != -EINPROGRESS) {
+		if (!err)
+			consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "frag1 ip_defrag failed: %d", err);
+	}
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag2, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	KUNIT_EXPECT_EQ(test, err, 0);
+	if (!err) {
+		KUNIT_EXPECT_FALSE(test, skb_frags_readable(frag2));
+		KUNIT_EXPECT_EQ(test, frag2->len, sizeof(struct iphdr) + 32);
+		consume_skb(frag2);
+	}
+
+	/* IPv4: uniformly unreadable first fragment that already carries a
+	 * frag_list propagates unreadable to the wrapper skb.
+	 */
+	frag1 = alloc_ipv4_frag_skb(0x4245, IP_MF);
+	frag2 = alloc_ipv4_frag_skb(0x4245, 16 >> 3);
+	child = alloc_skb(0, GFP_KERNEL);
+	if (!frag1 || !frag2 || !child) {
+		consume_skb(frag1);
+		consume_skb(frag2);
+		consume_skb(child);
+		KUNIT_FAIL_AND_ABORT(test, "failed to allocate IPv4 frags");
+	}
+	netmem_unreadable_add_frag(child, env, 0, 16);
+	skb_shinfo(frag1)->frag_list = child;
+	frag1->data_len = child->len;
+	frag1->len += child->len;
+	frag1->truesize += child->truesize;
+	frag1->unreadable = 1;
+	netmem_unreadable_add_frag(frag2, env, 0, 16);
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag1, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	if (err != -EINPROGRESS) {
+		if (!err)
+			consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "frag1 ip_defrag failed: %d", err);
+	}
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag2, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	KUNIT_EXPECT_EQ(test, err, 0);
+	if (!err) {
+		struct sk_buff *fl = skb_shinfo(frag2)->frag_list;
+
+		KUNIT_EXPECT_FALSE(test, skb_frags_readable(frag2));
+		KUNIT_EXPECT_NOT_NULL(test, fl);
+		if (fl)
+			KUNIT_EXPECT_FALSE(test, skb_frags_readable(fl));
+		consume_skb(frag2);
+	}
+
+#if IS_REACHABLE(CONFIG_NF_DEFRAG_IPV6)
+	/* Netfilter IPv6: mixed readability must fail and kill the queue. */
+	frag1 = alloc_ipv6_frag_skb(0x4242, IP6_MF);
+	frag2 = alloc_ipv6_frag_skb(0x4242, 16);
+	if (!frag1 || !frag2) {
+		consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "failed to allocate IPv6 frags");
+	}
+	netmem_unreadable_add_frag(frag1, env, 0, 16);
+	skb_put_zero(frag2, 16);
+
+	err = nf_ct_frag6_gather(&init_net, frag1, 0);
+	if (err != -EINPROGRESS) {
+		consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "frag1 nf_ct_frag6_gather failed: %d",
+				     err);
+	}
+
+	err = nf_ct_frag6_gather(&init_net, frag2, 0);
+	KUNIT_EXPECT_EQ(test, err, -EINVAL);
+	if (err != -EINPROGRESS)
+		consume_skb(frag2);
+
+	/* Netfilter IPv6: uniformly unreadable fragments reassemble cleanly. */
+	frag1 = alloc_ipv6_frag_skb(0x4243, IP6_MF);
+	frag2 = alloc_ipv6_frag_skb(0x4243, 16);
+	if (!frag1 || !frag2) {
+		consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "failed to allocate IPv6 frags");
+	}
+	netmem_unreadable_add_frag(frag1, env, 0, 16);
+	netmem_unreadable_add_frag(frag2, env, 0, 16);
+
+	err = nf_ct_frag6_gather(&init_net, frag1, 0);
+	if (err != -EINPROGRESS) {
+		consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "frag1 nf_ct_frag6_gather failed: %d",
+				     err);
+	}
+
+	err = nf_ct_frag6_gather(&init_net, frag2, 0);
+	KUNIT_EXPECT_EQ(test, err, 0);
+	if (!err)
+		KUNIT_EXPECT_FALSE(test, skb_frags_readable(frag2));
+	if (err != -EINPROGRESS)
+		consume_skb(frag2);
+#endif
+
+	netmem_unreadable_env_check(test, env);
+}
+
+KUNIT_DEFINE_ACTION_WRAPPER(sock_release_action, sock_release, struct socket *);
+KUNIT_DEFINE_ACTION_WRAPPER(consume_skb_action, consume_skb, struct sk_buff *);
+
+#if IS_REACHABLE(CONFIG_STREAM_PARSER)
+struct test_strp_ctx {
+	struct strparser strp;
+	struct socket *sock;
+};
+
+static void test_strp_ctx_cleanup(struct test_strp_ctx *ctx)
+{
+	strp_stop(&ctx->strp);
+	strp_done(&ctx->strp);
+	ctx->sock->sk->sk_state = TCP_CLOSE;
+	sock_release(ctx->sock);
+}
+
+KUNIT_DEFINE_ACTION_WRAPPER(test_strp_cleanup_act, test_strp_ctx_cleanup,
+			    struct test_strp_ctx *);
+
+static int dummy_strp_parse(struct strparser *strp, struct sk_buff *skb)
+{
+	return 64;
+}
+
+static void dummy_strp_rcv(struct strparser *strp, struct sk_buff *skb)
+{
+	kfree_skb(skb);
+}
+#endif
+
+static void netmem_unreadable_test_sg_and_strp(struct kunit *test)
+{
+	struct netmem_unreadable_env *env = netmem_unreadable_env_init(test);
+	struct scatterlist sg[4];
+	struct socket *tx_sock;
+	struct sk_buff *skb;
+	int ret;
+
+	skb = alloc_skb(32, GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, skb);
+	skb_put_zero(skb, 8);
+	netmem_unreadable_add_frag(skb, env, 0, 64);
+	KUNIT_ASSERT_EQ(test,
+			kunit_add_action_or_reset(test, consume_skb_action,
+						  skb),
+			0);
+
+	/* Linear prefix is readable; spanning into unreadable frag fails. */
+	sg_init_table(sg, ARRAY_SIZE(sg));
+	KUNIT_EXPECT_EQ(test, skb_to_sgvec(skb, sg, 0, 8), 1);
+	sg_init_table(sg, ARRAY_SIZE(sg));
+	KUNIT_EXPECT_EQ(test, skb_to_sgvec(skb, sg, 0, skb->len), -EFAULT);
+
+	KUNIT_ASSERT_EQ(test,
+			sock_create_kern(&init_net, AF_INET, SOCK_DGRAM,
+					 IPPROTO_UDP, &tx_sock),
+			0);
+	KUNIT_ASSERT_EQ(test,
+			kunit_add_action_or_reset(test, sock_release_action,
+						  tx_sock),
+			0);
+	lock_sock(tx_sock->sk);
+	ret = skb_send_sock_locked(tx_sock->sk, skb, 8, 64);
+	release_sock(tx_sock->sk);
+	KUNIT_EXPECT_EQ(test, ret, -EFAULT);
+	kunit_release_action(test, sock_release_action, tx_sock);
+	kunit_release_action(test, consume_skb_action, skb);
+
+#if IS_REACHABLE(CONFIG_STREAM_PARSER)
+	{
+		static const struct strp_callbacks cb = {
+			.parse_msg = dummy_strp_parse,
+			.rcv_msg = dummy_strp_rcv,
+		};
+		struct test_strp_ctx *ctx;
+
+		ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, ctx);
+		KUNIT_ASSERT_EQ(test,
+				sock_create_kern(&init_net, AF_INET,
+						 SOCK_STREAM, IPPROTO_TCP,
+						 &ctx->sock),
+				0);
+		ctx->sock->sk->sk_state = TCP_ESTABLISHED;
+		tcp_sk(ctx->sock->sk)->copied_seq = 0;
+		tcp_sk(ctx->sock->sk)->rcv_nxt = 64;
+		ret = strp_init(&ctx->strp, ctx->sock->sk, &cb);
+		if (ret) {
+			ctx->sock->sk->sk_state = TCP_CLOSE;
+			sock_release(ctx->sock);
+			KUNIT_ASSERT_EQ(test, ret, 0);
+		}
+		ret = kunit_add_action_or_reset(test, test_strp_cleanup_act,
+						ctx);
+		KUNIT_ASSERT_EQ(test, ret, 0);
+
+		skb = alloc_skb(0, GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, skb);
+		netmem_unreadable_add_frag(skb, env, 0, 64);
+		TCP_SKB_CB(skb)->seq = 0;
+		TCP_SKB_CB(skb)->end_seq = 64;
+		skb_queue_tail(&ctx->sock->sk->sk_receive_queue, skb);
+
+		local_bh_disable();
+		bh_lock_sock(ctx->sock->sk);
+		strp_data_ready(&ctx->strp);
+		bh_unlock_sock(ctx->sock->sk);
+		local_bh_enable();
+
+		KUNIT_EXPECT_TRUE(test, ctx->strp.stopped);
+		KUNIT_EXPECT_EQ(test, READ_ONCE(ctx->sock->sk->sk_err), EFAULT);
+
+		kunit_release_action(test, test_strp_cleanup_act, ctx);
+	}
+#endif
+
+	netmem_unreadable_env_check(test, env);
+}
 #endif
 #endif
 
@@ -2033,6 +2413,8 @@ static struct kunit_case net_test_cases[] = {
 	KUNIT_CASE(netmem_ref_test_tcp_devmem_recv),
 	KUNIT_CASE(netmem_unreadable_test_napi_pull_fail),
 	KUNIT_CASE(netmem_unreadable_test_napi_reuse),
+	KUNIT_CASE(netmem_unreadable_test_ip_defrag),
+	KUNIT_CASE(netmem_unreadable_test_sg_and_strp),
 #endif
 #endif
 	{ },
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
#32 lore raw

Re: [PATCH net 08/10] net: kunit: test unreadable net_iov defrag and skb helpers

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] net: kunit: queued init_net frags can outlive netmem_unreadable_env --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] net: kunit: queued init_net frags can outlive netmem_unreadable_env
--

commit 21831f6cfd8142662428e0c9b0635f40e76c1bbb
Author: Octavian Purdila <[email protected]>

net: kunit: test unreadable net_iov defrag and skb helpers

This commit adds KUnit tests for unreadable net_iov handling in IPv4 and Netfilter IPv6 fragment reassembly, skb_to_sgvec(), skb_send_sock_locked(), and strparser.

Quoted 4 lines
net/core/net_test.c +0 -0
index b939cc93e9050..8da6c5ab4430c 100644

[ ... ]

Quoted 5 lines
net/core/net_test.c +5 -0
+static void netmem_unreadable_test_ip_defrag(struct kunit *test)
+{
+	struct netmem_unreadable_env *env = netmem_unreadable_env_init(test);
+	struct sk_buff *frag1, *frag2, *child;
+	int err;

[ ... ]

Quoted 19 lines
net/core/net_test.c +19 -0
+	/* IPv4: unreadable first fragment + readable second fragment must fail
+	 * and release the queued unreadable fragment cleanly.
+	 */
+	frag1 = alloc_ipv4_frag_skb(0x4243, IP_MF);
+	frag2 = alloc_ipv4_frag_skb(0x4243, 16 >> 3);
+	if (!frag1 || !frag2) {
+		consume_skb(frag1);
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "failed to allocate IPv4 frags");
+	}
+	netmem_unreadable_add_frag(frag1, env, 0, 16);
+	skb_put_zero(frag2, 16);
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag1, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	if (err != -EINPROGRESS) {
+		if (!err)
+			consume_skb(frag1);

net/core/net_test.c static void netmem_unreadable_test_napi_reuse(struct kunit *test) · line 2094

Quoted 10 lines
net/core/net_test.c +10 -0
+		consume_skb(frag2);
+		KUNIT_FAIL_AND_ABORT(test, "frag1 ip_defrag failed: %d", err);
+	}
+
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag2, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	KUNIT_EXPECT_EQ(test, err, -EINVAL);
+	if (!err)
+		consume_skb(frag2);

[Severity: Medium]
Can a queued fragment referencing env->niov outlive env and trigger a use-after-free when the fragment timer expires?

When ip_defrag() queues frag1 into init_net, frag1 holds env->niov_nm pointing to &env->niov under an asynchronous ip_expire() timer. If init_net fragment memory exceeds high_thresh before frag2 arrives, inet_frag_find() returns NULL before looking up frag1's queue:

net/ipv4/inet_fragment.c:inet_frag_find() {
    ...
	if (!high_thresh || frag_mem_limit(fqdir) > high_thresh)
		return NULL;
    ...
}

frag2 then returns -ENOMEM without killing frag1's queue, and the test exits while frag1 is still queued in init_net. On exit, netmem_unreadable_env_cleanup() clears pp_magic, destroys env->pool, and exits env->binding.ref before KUnit frees env.

When ip_expire() later purges frag1, skb_release_data() -> skb_netmem_unref() reads freed env->niov and falls through to percpu_ref_put(&env->binding.ref) on freed memory in softirq context. The same lifetime issue affects the other IPv4 subtests and the nf_ct_frag6_gather(&init_net, ...) subtests.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#33 lore raw

Re: [PATCH net 08/10] net: kunit: test unreadable net_iov defrag and skb helpers

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 3

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] netmem_unreadable_test_ip_defrag() (net/core/net_test.c) puts fragment skbs into the global init_net reassembly queues: the IPv4…
- [Low] The commit "net: skbuff, skmsg, strparser: reject unreadable frags" says it was "reproduced and verified with the accompanying…
- [Low] The Netfilter IPv6 sub-cases of netmem_unreadable_test_ip_defrag() are wrapped in `#if…
- [Low] The IPv4 part of netmem_unreadable_test_ip_defrag() reassembles in the live init_net ipfrag fqdir with fixed keys.

--

net: kunit: test unreadable net_iov defrag and skb helpers

This commit adds KUnit tests to net_test for unreadable net_iov handling in IPv4 and Netfilter IPv6 fragment reassembly, skb_to_sgvec(), skb_send_sock_locked() and strparser. The tests also check that the page_pool and binding reference counts stay balanced.

Quoted 4 lines
net/core/net_test.c +0 -0
index b939cc93e9050..8da6c5ab4430c 100644

[ ... ]

Quoted 1 line
net/core/net_test.c +0 -0
@@ -1962,6 +1971,377 @@ static void netmem_unreadable_test_napi_reuse(struct kunit *test)

[ ... ]

Quoted 2 lines
net/core/net_test.c +2 -0
+static struct sk_buff *alloc_ipv4_frag_skb(u16 id, u16 frag_off)
+{

[ ... ]

net/core/net_test.c static void netmem_unreadable_test_napi_reuse(struct kunit *test) · line 1993

Quoted 4 lines
net/core/net_test.c +4 -0
+	iph->id = htons(id);
+	iph->protocol = IPPROTO_UDP;
+	iph->saddr = htonl(0x7f000001);
+	iph->daddr = htonl(0x7f000001);

[Severity: Low]
These fragments go into the live init_net ipfrag fqdir with a fixed key. The key is saddr = daddr = 127.0.0.1, protocol UDP, IDs 0x4242 to 0x4245, and user IP_DEFRAG_LOCAL_DELIVER. Also, netmem_unreadable_test_ip_defrag() re-enables BH between the two ip_defrag() calls.

Can real local-delivery fragments with the same key join or disturb the test's queue in that window? Loopback UDP with a reduced lo MTU or locally injected raw fragments could do this.

If a readable real fragment lands in one of the test's unreadable queues, the mixed-readability check drops the real packet and the test result is wrong. A queue left over from an earlier failed run with the same ID could also break the next run.

The IPv6 sub-cases don't seem to have this problem. The in-tree callers of nf_ct_frag6_gather() all use conntrack-range users rather than 0.

Would a dedicated netns, or less predictable addresses or IDs, isolate these tests?

Quoted 2 lines
net/core/net_test.c +2 -0
+#if IS_REACHABLE(CONFIG_NF_DEFRAG_IPV6)
+static struct sk_buff *alloc_ipv6_frag_skb(u32 id, u16 frag_off)

[ ... ]

Quoted 9 lines
net/core/net_test.c +9 -0
+static void netmem_unreadable_test_ip_defrag(struct kunit *test)
+{
+	struct netmem_unreadable_env *env = netmem_unreadable_env_init(test);
+	struct sk_buff *frag1, *frag2, *child;
+	int err;
+
+	/* IPv4: readable first fragment + unreadable second fragment must fail
+	 * and tear down the fragment queue.
+	 */

[ ... ]

net/core/net_test.c static void netmem_unreadable_test_napi_reuse(struct kunit *test) · line 2064

Quoted 6 lines
net/core/net_test.c +6 -0
+	local_bh_disable();
+	err = ip_defrag(&init_net, frag2, IP_DEFRAG_LOCAL_DELIVER);
+	local_bh_enable();
+	KUNIT_EXPECT_EQ(test, err, -EINVAL);
+	if (!err)
+		consume_skb(frag2);

[Severity: Medium]
What happens to the queued fragments if this second ip_defrag() call returns -EINPROGRESS?

KUNIT_EXPECT_EQ() doesn't abort the test. The live queue still owns fragments that hold page_pool references to env->niov, and nothing in the test kills that queue. At teardown, netmem_unreadable_env_cleanup() runs:

	netmem_clear_pp_magic(env->niov_nm);
	netmem_set_pp(env->niov_nm, NULL);
	page_pool_destroy(env->pool);
	percpu_ref_exit(&env->binding.ref);

KUnit then frees env, and with it the embedded struct net_iov.

When the frag queue timer fires later (ipfrag_time for IPv4, IPV6_FRAG_TIMEOUT for nf IPv6), the purge path would run:

inet_frag_rbtree_purge()

    kfree_skb()
      skb_release_data()
        napi_pp_put_page()

Wouldn't that read the freed niov and binding memory from softirq context, possibly after net_test.ko has been unloaded?

This doesn't need a kernel regression to happen. ip_frag_queue() checks ip_frag_too_far() before the readability check:

	if (!(IPCB(skb)->flags & IPSKB_FRAG_COMPLETE) &&
	    unlikely(ip_frag_too_far(qp)) &&
	    unlikely(err = ip_frag_reinit(qp))) {

Suppose more than ipfrag_max_dist fragments from 127.0.0.1 are processed between the two calls. ip_frag_reinit() then resets the queue, frag2 is queued alone, and ip_frag_queue() returns -EINPROGRESS. A regression in the reassembly code under test that leaves the queue incomplete would have the same result.

The other IPv4 sub-cases that expect 0 and the nf_ct_frag6_gather() sub-cases follow the same pattern. Could the test make sure any remaining queue is killed before the env is torn down?

[ ... ]

net/core/net_test.c static void netmem_unreadable_test_napi_reuse(struct kunit *test) · line 2172

Quoted 2 lines
net/core/net_test.c +2 -0
+#if IS_REACHABLE(CONFIG_NF_DEFRAG_IPV6)
+	/* Netfilter IPv6: mixed readability must fail and kill the queue. */

[Severity: Low]
NF_DEFRAG_IPV6 is a promptless tristate. With NET_TEST=y and NF_DEFRAG_IPV6=m, IS_REACHABLE() is false and this block is compiled out. NET_TEST in net/Kconfig only depends on KUNIT and selects neither option.

The CONFIG_STREAM_PARSER block in netmem_unreadable_test_sg_and_strp() has the same issue. STREAM_PARSER is def_bool n and is only enabled when BPF_STREAM_PARSER, AF_KCM or ESPINTCP selects it.

In those configs, netmem_unreadable_test_ip_defrag() and netmem_unreadable_test_sg_and_strp() still report PASS without running the IPv6 or strparser checks. Would an #else branch with kunit_mark_skipped(), or a Kconfig dependency for NET_TEST, make that visible?

[ ... ]

net/core/net_test.c

Quoted 2 lines
net/core/net_test.c +2 -0
+static void netmem_unreadable_test_sg_and_strp(struct kunit *test)
+{

[Severity: Low]
This isn't a bug in this patch. It concerns the earlier commit in the series, "net: skbuff, skmsg, strparser: reject unreadable frags", which says it was:

"reproduced and verified with the accompanying net_test KUnit tests"

This test covers skb_to_sgvec(), skb_send_sock_locked(), and strp_recv() through strp_data_ready(). It doesn't reach the skmsg changes in that commit:

- the new reject branch in sk_psock_verdict_apply(), which reports EFAULT and clears SK_PSOCK_TX_ENABLED
- the new -EMSGSIZE propagation in sk_psock_skb_ingress_enqueue()

No psock is created anywhere in net/core/net_test.c.

Should that commit message say what the tests actually cover, or should sockmap coverage be added here?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796329894.git.tavip%40google.com
#34 lore raw

PATCH 9/10 selftests: drv-net: devmem: test unreadable kTLS RX

In reply to Octavian Purdila

Add an end-to-end devmem.py protocol regression test covering unreadable net_iov skbs on kTLS TLS_RX decryption, verifying that configuring TLS_RX on a socket with queued unreadable devmem fragments rejects the record cleanly with EFAULT.

Bind the devmem RX queue directly from Python rather than via ncdevmem so the test owns the TCP socket and can install TLS_RX while unreadable devmem fragments are already queued.

Assisted-by LLM
---
 .../selftests/drivers/net/hw/devmem.py        |   9 +-
 .../selftests/drivers/net/hw/devmem_lib.py    | 210 +++++++++++++++++-
 .../drivers/net/hw/lib/py/__init__.py         |  11 +-
 3 files changed, 221 insertions(+), 9 deletions(-)
tools/testing/selftests/drivers/net/hw/devmem.py +7 -2
index 82c11ffc4add7..d15118060d261 100755
@@ -3,7 +3,7 @@
 
 from os import path
 from devmem_lib import (setup_test, run_rx, run_tx, run_tx_chunks, run_rx_hds,
-                        run_rx_large_niov)
+                        run_rx_large_niov, run_rx_tls)
 from lib.py import ksft_run, ksft_exit, ksft_disruptive
 from lib.py import NetDrvEpEnv
 
@@ -36,12 +36,17 @@ def check_rx_large_niov(cfg) -> None:
     run_rx_large_niov(cfg)
 
 
+def check_rx_tls(cfg) -> None:
+    """Run the unreadable kTLS RX test."""
+    run_rx_tls(cfg)
+
+
 def main() -> None:
     """Run the devmem test cases."""
     with NetDrvEpEnv(__file__) as cfg:
         setup_test(cfg, path.abspath(path.dirname(__file__) + "/ncdevmem"))
         ksft_run([check_rx, check_tx, check_tx_chunks, check_rx_hds,
-                  check_rx_large_niov],
+                  check_rx_large_niov, check_rx_tls],
                  args=(cfg,))
     ksft_exit()
 
tools/testing/selftests/drivers/net/hw/devmem_lib.py +208 -2

223 lines not on this page · raw message

tools/testing/selftests/drivers/net/hw/lib/py/__init__.py +6 -5
index 4077f5f1a1be3..1f7df889726aa 100644
@@ -29,8 +29,9 @@ try:
     from net.lib.py import KsftSkipEx, KsftFailEx, KsftXfailEx
     from net.lib.py import ksft_disruptive, ksft_exit, ksft_pr, ksft_run, \
         ksft_setup, ksft_variants, KsftNamedVariant
-    from net.lib.py import ksft_eq, ksft_ge, ksft_in, ksft_is, ksft_lt, \
-        ksft_ne, ksft_not_in, ksft_raises, ksft_true, ksft_gt, ksft_not_none
+    from net.lib.py import ksft_busy_wait, ksft_eq, ksft_ge, ksft_in, \
+        ksft_is, ksft_lt, ksft_ne, ksft_not_in, ksft_raises, ksft_true, \
+        ksft_gt, ksft_not_none
     from drivers.net.lib.py import set_ethtool_feat
     from drivers.net.lib.py import GenerateTraffic, Remote, Iperf3Runner
     from drivers.net.lib.py import NetDrvEnv, NetDrvEpEnv, NetDrvContEnv
@@ -46,9 +47,9 @@ try:
                "KsftSkipEx", "KsftFailEx", "KsftXfailEx",
                "ksft_disruptive", "ksft_exit", "ksft_pr", "ksft_run",
                "ksft_setup", "ksft_variants", "KsftNamedVariant",
-               "ksft_eq", "ksft_ge", "ksft_in", "ksft_is", "ksft_lt",
-               "ksft_ne", "ksft_not_in", "ksft_raises", "ksft_true", "ksft_gt",
-               "ksft_not_none", "ksft_not_none",
+               "ksft_busy_wait", "ksft_eq", "ksft_ge", "ksft_in", "ksft_is",
+               "ksft_lt", "ksft_ne", "ksft_not_in", "ksft_raises", "ksft_true",
+               "ksft_gt", "ksft_not_none", "ksft_not_none",
                "NetDrvEnv", "NetDrvEpEnv", "NetDrvContEnv", "GenerateTraffic",
                "Remote", "Iperf3Runner", "set_ethtool_feat"]
 except ModuleNotFoundError as e:
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
#35 lore raw

Re: [PATCH net 09/10] selftests: drv-net: devmem: test unreadable kTLS RX

Quoted 6 lines · Octavian Purdila

Add an end-to-end devmem.py protocol regression test covering unreadable net_iov skbs on kTLS TLS_RX decryption, verifying that configuring TLS_RX on a socket with queued unreadable devmem fragments rejects the record cleanly with EFAULT.

Quoted 6 lines

Bind the devmem RX queue directly from Python rather than via ncdevmem so the test owns the TCP socket and can install TLS_RX while unreadable devmem fragments are already queued.

Assisted-by LLM

I would drop this. ktLS + unreadable is not an interesting use case worthy of a test case in the tree. It's just an LLM-ism to add a test for everything it does I think.

Signature · 2 lines
Thanks,
Mina
#36 lore raw

Re: [PATCH net 09/10] selftests: drv-net: devmem: test unreadable kTLS RX

Quoted 12 lines · Mina Almasry
Quoted 10 lines · Octavian Purdila

Add an end-to-end devmem.py protocol regression test covering unreadable net_iov skbs on kTLS TLS_RX decryption, verifying that configuring TLS_RX on a socket with queued unreadable devmem fragments rejects the record cleanly with EFAULT.

Bind the devmem RX queue directly from Python rather than via ncdevmem so the test owns the TCP socket and can install TLS_RX while unreadable devmem fragments are already queued.

Quoted 7 lines
Quoted 2 lines
Assisted-by LLM

I would drop this. ktLS + unreadable is not an interesting use case worthy of a test case in the tree. It's just an LLM-ism to add a test for everything it does I think.

Fine with me, I'll drop it.

Quoted 3 lines

--
Thanks,
Mina

#37 lore raw

Re: [PATCH net 09/10] selftests: drv-net: devmem: test unreadable kTLS RX

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] selftests: drv-net: hardcoded UDMABUF_CREATE breaks non-generic arches - [Low] selftests: drv-net…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] selftests: drv-net: hardcoded UDMABUF_CREATE breaks non-generic arches
- [Low] selftests: drv-net: devmem: check_rx_tls() missing ksft_disruptive decorator
- [Low] selftests: drv-net: unchecked cm.exception.errno in run_rx_tls()
- [Low] selftests: drv-net: missing/late netlink close in _setup_devmem_rx_queue()
--

commit 410173c7bfe04f4674fa99cc975e15cce6f0d840
Author: Octavian Purdila <[email protected]>

selftests: drv-net: devmem: test unreadable kTLS RX

This commit adds an end-to-end devmem.py regression test that binds a devmem RX queue from Python and verifies that configuring kTLS TLS_RX on a socket with queued unreadable devmem fragments rejects the record with EFAULT.

Quoted 4 lines
tools/testing/selftests/drivers/net/hw/devmem.py +0 -0
index 82c11ffc4add7..d15118060d261 100755

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem.py def check_rx_large_niov(cfg) -> None: · line 41

Quoted 7 lines
tools/testing/selftests/drivers/net/hw/devmem.py +3 -0
@@ -36,12 +36,17 @@ def check_rx_large_niov(cfg) -> None:
     run_rx_large_niov(cfg)
 
 
+def check_rx_tls(cfg) -> None:
+    """Run the unreadable kTLS RX test."""
+    run_rx_tls(cfg)

[Severity: Low]
Should check_rx_tls() be annotated with @ksft_disruptive?

run_rx_tls() -> _setup_devmem_rx_queue() reconfigures ring HDS parameters via ethnl.rings_set(), which bounces the interface on drivers like bnxt (bnxt_set_ringparam() -> bnxt_close_nic()). Without @ksft_disruptive, running devmem.py with DISRUPTIVE=False on a single-interface host still executes this test and can disconnect NETIF.

[ ... ]

Quoted 4 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +0 -0
index 71b916c161969..75199a01ca3fc 100644

[ ... ]

Quoted 1 line
tools/testing/selftests/drivers/net/hw/devmem_lib.py +0 -0
@@ -314,3 +320,203 @@ def run_rx_hds(cfg):

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem_lib.py def run_rx_hds(cfg): · line 331

Quoted 2 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +2 -0
+UDMABUF_FLAGS_CLOEXEC = 0x01
+UDMABUF_CREATE = 0x40187542

[Severity: Medium]
Will hardcoding UDMABUF_CREATE = 0x40187542 break on architectures that do not use asm-generic/ioctl.h?

include/uapi/linux/udmabuf.h defines UDMABUF_CREATE with _IOW(), which evaluates to 0x80187542 on PowerPC, MIPS, SPARC, Alpha, and PA-RISC. On those architectures, udmabuf_ioctl() rejects 0x40187542 with ENOTTY in _Udmabuf.__init__().

[ ... ]

Quoted 8 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +8 -0
+def _setup_devmem_rx_queue(cfg):
+    """Isolate and bind one devmem RX queue; return its queue ID."""
+    require_devmem(cfg)
+    ethnl = EthtoolFamily()
+    channels = ethnl.channels_get({'header': {'dev-index': cfg.ifindex}})
+    qcnt = channels.get('rx-count', 0) + channels.get('combined-count', 0)
+    if qcnt < 2:
+        raise KsftSkipEx("Test requires at least 2 RX queues")

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem_lib.py def run_rx_hds(cfg): · line 416

Quoted 8 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +8 -0
+    netdevnl = NetdevFamily()
+    netdevnl.bind_rx({
+        "ifindex": cfg.ifindex,
+        "fd": ubuf.dmabuf_fd,
+        "queues": [{"type": "rx", "id": rxq}],
+    })
+    defer(netdevnl.close)
+    return rxq

[Severity: Low]
Can _setup_devmem_rx_queue() leak the netlink sockets or fail to restore HDS on error?

ethnl never registers defer(ethnl.close), and YnlFamily.__init__() creates a reference cycle via functools.partial(), so the socket stays open past scope exit until cyclic GC runs.

Similarly, defer(netdevnl.close) runs too late if netdevnl.bind_rx() fails after the kernel binds the queue: the socket stays open during teardown, causing _restore_hds() to fail with EINVAL in ethnl_set_rings().

Registering defer(ethnl.close) and defer(netdevnl.close) right after each constructor ensures deterministic close and unbinding before teardown.

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem_lib.py def run_rx_hds(cfg): · line 522

Quoted 5 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +5 -0
+        with ksft_raises(OSError) as cm:
+            conn.recv(64)
+        ksft_eq(cm.exception.errno, errno.EFAULT)
+        ksft_eq(conn.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0)
+        conn.close()

[Severity: Low]
Will cm.exception.errno raise AttributeError if conn.recv(64) does not fail?

When no exception is raised, ksft_raises.__exit__() records a failure and leaves cm.exception as None. Dereferencing cm.exception.errno then aborts the test with AttributeError, skipping the SO_ERROR check and conn.close() before exiting the _remote_py() context; guarding with
if cm.exception is not None avoids this.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#38 lore raw

Re: [PATCH net 09/10] selftests: drv-net: devmem: test unreadable kTLS RX

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 2

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] selftests: drv-net: hardcoded UDMABUF_CREATE breaks non- generic arches
- [Low] In run_rx_tls() (tools/testing/selftests/drivers/net/hw/devmem_lib.py), the assertion…
- [Low] selftests: drv-net: devmem: check_rx_tls() missing ksft_disruptive decorator

--

selftests: drv-net: devmem: test unreadable kTLS RX

This adds a devmem.py test that queues unreadable devmem fragments on a TCP socket, then installs TLS_RX on that socket. It checks that the first recv() fails with EFAULT. The devmem RX queue is bound directly from Python so that the test owns the TCP socket.

Quoted 4 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +0 -0
index 71b916c161969..75199a01ca3fc 100644

[ ... ]

Quoted 1 line
tools/testing/selftests/drivers/net/hw/devmem_lib.py +0 -0
@@ -314,3 +320,203 @@ def run_rx_hds(cfg):

[ ... ]

Quoted 2 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +2 -0
+def run_rx_tls(cfg):
+    """Verify kTLS RX rejects queued unreadable devmem skbs with EFAULT."""

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem_lib.py def run_rx_hds(cfg): · line 521

Quoted 11 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +11 -0
+        try:
+            conn.setsockopt(SOL_TLS, TLS_RX, crypto_info)
+        except OSError as e:
+            if e.errno in (errno.ENOENT, errno.EOPNOTSUPP):
+                raise KsftSkipEx("TLS_CIPHER_AES_GCM_128 unavailable") from e
+            raise
+
+        with ksft_raises(OSError) as cm:
+            conn.recv(64)
+        ksft_eq(cm.exception.errno, errno.EFAULT)
+        ksft_eq(conn.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0)

[Severity: Low]
Can this SO_ERROR check in run_rx_tls() ever fail?

When TLS_RX is armed while the unreadable devmem skb is queued, the parser is aborted in tls_strp_copyin():

net/tls/tls_strp.c:tls_strp_copyin() {
    ...
	if (unlikely(!skb_frags_readable(in_skb))) {
		tls_strp_abort_strp(strp, -EFAULT);
		desc->error = -EFAULT;
		return 0;
	}
    ...
}

tls_strp_abort_strp() sets strp->stopped and reports the error to user space only through sk->sk_err.

The recv(64) then goes through tls_sw_recvmsg()->tls_rx_rec_wait() with has_copied false, so it returns sock_error(sk):

net/tls/tls_sw.c:tls_rx_rec_wait() {
    ...
		if (sk->sk_err) {
			if (has_copied)
				return -READ_ONCE(sk->sk_err);
			return sock_error(sk);
		}
    ...
}

sock_error() does xchg(&sk->sk_err, 0). By the time getsockopt(SO_ERROR) runs, sk_err has already been cleared. SO_ERROR then falls back to sk_err_soft, which is also 0 for this flow. The check reads 0 no matter what the kernel did.

The assertion looks like it backs up the "rejects the record cleanly" wording in the commit message. It doesn't say anything about the state of the socket after the error, though. For example, the strparser stays stopped for good.

Would it make more sense to check that SO_ERROR == EFAULT before the recv(), to show that the error was latched during setsockopt(TLS_RX)? Another option is to check how a second recv() behaves. If neither is wanted, could this line be dropped? The main EFAULT check above is still meaningful.

Quoted 1 line

+ conn.close()

[ ... ]

Quoted 71 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +67 -0
@@ -314,3 +320,203 @@ def run_rx_hds(cfg):
             cmd(f"dd if=/dev/zero bs={size} count=1 2>/dev/null | "
                 f"{socat}", host=cfg.remote, shell=True)
         ksft_eq(ncdevmem.ret, 0, f"HDS failed for payload size {size}")
+
+
+SOL_TLS = 282
+TLS_RX = 2
+TLS_1_2_VERSION = 0x0303
+TLS_CIPHER_AES_GCM_128 = 51
+TCP_ULP = 31
+UDMABUF_FLAGS_CLOEXEC = 0x01
+UDMABUF_CREATE = 0x40187542
+NUM_DEVMEM_PAGES = 16000
+
+
+class _Udmabuf:
+    """Small udmabuf wrapper for Python socket protocol tests."""
+
+    def __init__(self, size=None):
+        if size is None:
+            size = os.sysconf("SC_PAGE_SIZE") * NUM_DEVMEM_PAGES
+        self.size = size
+        self.dmabuf_fd = -1
+        self.devfd = -1
+        self.memfd = -1
+        try:
+            self.memfd = os.memfd_create("devmem-test", os.MFD_ALLOW_SEALING)
+            os.ftruncate(self.memfd, size)
+            fcntl.fcntl(self.memfd, fcntl.F_ADD_SEALS, fcntl.F_SEAL_SHRINK)
+            try:
+                self.devfd = os.open("/dev/udmabuf", os.O_RDONLY)
+            except OSError as e:
+                if e.errno in (errno.ENOENT, errno.ENODEV, errno.EACCES):
+                    raise KsftSkipEx(f"/dev/udmabuf unavailable: {e}") from e
+                raise
+            req = bytearray(struct.pack("IIQQ", self.memfd,
+                                        UDMABUF_FLAGS_CLOEXEC, 0, size))
+            self.dmabuf_fd = fcntl.ioctl(self.devfd, UDMABUF_CREATE, req)
+        except BaseException:
+            self.close()
+            raise
+
+    def close(self):
+        """Close file descriptors."""
+        for attr in ("dmabuf_fd", "devfd", "memfd"):
+            fd = getattr(self, attr, -1)
+            if fd >= 0:
+                os.close(fd)
+                setattr(self, attr, -1)
+
+
+def _restore_hds(ethnl, ifindex, orig_split, has_thresh, orig_thresh):
+    req = {'header': {'dev-index': ifindex}, 'tcp-data-split': 'unknown'}
+    if has_thresh:
+        req['hds-thresh'] = orig_thresh
+    ethnl.rings_set(req)
+    cur = ethnl.rings_get({'header': {'dev-index': ifindex}})
+    if cur.get('tcp-data-split') != orig_split:
+        ethnl.rings_set({'header': {'dev-index': ifindex},
+                         'tcp-data-split': orig_split})
+
+
+def _setup_devmem_rx_queue(cfg):
+    """Isolate and bind one devmem RX queue; return its queue ID."""
+    require_devmem(cfg)
+    ethnl = EthtoolFamily()
+    channels = ethnl.channels_get({'header': {'dev-index': cfg.ifindex}})
+    qcnt = channels.get('rx-count', 0) + channels.get('combined-count', 0)
+    if qcnt < 2:
+        raise KsftSkipEx("Test requires at least 2 RX queues")

tools/testing/selftests/drivers/net/hw/devmem_lib.py def run_rx_hds(cfg): · line 399

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +10 -0
+
+    rxq = qcnt - 1
+    ubuf = _Udmabuf()
+    defer(ubuf.close)
+
+    rings = ethnl.rings_get({'header': {'dev-index': cfg.ifindex}})
+    orig_split = rings.get('tcp-data-split', 'unknown')
+    has_thresh = 'hds-thresh' in rings
+    orig_thresh = rings.get('hds-thresh', 0)
+    req = {'header': {'dev-index': cfg.ifindex}, 'tcp-data-split': 'enabled'}

[Severity: Low]
Should check_rx_tls() be marked @ksft_disruptive, like check_rx(), check_tx() and check_tx_chunks() in this file?

run_rx_tls() calls _setup_devmem_rx_queue(), which changes the NIC configuration in several ways:

- it flips tcp-data-split and hds-thresh through ethnl.rings_set(), and restores them again in _restore_hds()
- it rewrites the RSS indirection table with ethtool -X
- it binds a devmem RX queue

Some devmem capable drivers bounce the interface on a ring change. bnxt_set_ringparam() calls bnxt_close_nic() and bnxt_open_nic() when the device is running. gve does something similar through gve_adjust_config(). Either way NETIF can go down briefly.

drivers/net/README.rst says tests that may disconnect NETIF must be annotated with @ksft_disruptive, so that runs with DISRUPTIVE=False on single-interface hosts skip them. As written, this test still runs in that mode. It can drop the connection the harness relies on to reach the remote.

Quoted 113 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +113 -0
+    if has_thresh:
+        req['hds-thresh'] = 0
+    ethnl.rings_set(req)
+    defer(_restore_hds, ethnl, cfg.ifindex, orig_split, has_thresh,
+          orig_thresh)
+
+    ethtool(f"-X {cfg.ifname} equal {rxq}")
+    defer(ethtool, f"-X {cfg.ifname} default")
+
+    netdevnl = NetdevFamily()
+    netdevnl.bind_rx({
+        "ifindex": cfg.ifindex,
+        "fd": ubuf.dmabuf_fd,
+        "queues": [{"type": "rx", "id": rxq}],
+    })
+    defer(netdevnl.close)
+    return rxq
+
+
+def _steer_tcp_flow(cfg, port, rxq, src_port):
+    proto = f"tcp{cfg.addr_ipver}"
+    spec5 = (f"flow-type {proto} src-ip {cfg.remote_addr} dst-ip {cfg.addr} "
+             f"src-port {src_port} dst-port {port} queue {rxq}")
+    spec3 = (f"flow-type {proto} dst-ip {cfg.addr} dst-port {port} "
+             f"queue {rxq}")
+    try:
+        out = ethtool(f"-N {cfg.ifname} {spec5}").stdout
+    except CmdExitFailure:
+        out = ethtool(f"-N {cfg.ifname} {spec3}").stdout
+    rule_id = int(re.search(r"ID (\d+)", out).group(1))
+    defer(ethtool, f"-N {cfg.ifname} delete {rule_id}")
+    return rule_id
+
+
+def _remote_py(cfg, script, bg=False):
+    cfg.require_cmd("python3", local=False, remote=True)
+    b64 = base64.b64encode(script.encode("utf-8")).decode("ascii")
+    py_cmd = f"python3 -c 'import base64; exec(base64.b64decode(\"{b64}\"))'"
+    if bg:
+        return bkg(py_cmd, host=cfg.remote, exit_wait=True)
+    return cmd(py_cmd, host=cfg.remote)
+
+
+def _listen_tcp(cfg, port):
+    af = socket.AF_INET6 if cfg.addr_ipver == "6" else socket.AF_INET
+    srv = socket.socket(af, socket.SOCK_STREAM)
+    defer(srv.close)
+    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+    srv.settimeout(5.0)
+    srv.bind((cfg.addr, port))
+    srv.listen(1)
+    return srv, af
+
+
+def _tcp_inq(sock):
+    buf = fcntl.ioctl(sock.fileno(), termios.FIONREAD, b"\x00\x00\x00\x00")
+    return struct.unpack("i", buf)[0]
+
+
+def run_rx_tls(cfg):
+    """Verify kTLS RX rejects queued unreadable devmem skbs with EFAULT."""
+    rxq = _setup_devmem_rx_queue(cfg)
+    port = rand_port()
+    srv, af = _listen_tcp(cfg, port)
+
+    sender_script = f"""
+import socket
+s = socket.socket({int(af)}, socket.SOCK_STREAM)
+s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+s.bind(("{cfg.remote_addr}", 0))
+s.connect(("{cfg.addr}", {port}))
+s.sendall(b"\\x17\\x03\\x03\\x00\\x20" + (b"\\x05" * 8))
+s.recv(1)
+s.sendall(b"\\x11" * 24)
+try:
+    s.recv(1)
+except OSError:
+    pass
+s.close()
+"""
+    with _remote_py(cfg, sender_script, bg=True):
+        conn, peer = srv.accept()
+        defer(conn.close)
+        conn.settimeout(5.0)
+
+        ksft_busy_wait(lambda: _tcp_inq(conn) >= 13, deadline=5,
+                       comment="Timed out waiting for TLS header")
+        ksft_eq(len(conn.recv(13, socket.MSG_PEEK)), 13)
+
+        _steer_tcp_flow(cfg, port, rxq, peer[1])
+        conn.sendall(b"G")
+
+        ksft_busy_wait(lambda: _tcp_inq(conn) >= 37, deadline=5,
+                       comment="Timed out waiting for devmem TLS payload")
+        ksft_eq(_tcp_inq(conn), 37)
+
+        try:
+            conn.setsockopt(socket.IPPROTO_TCP, TCP_ULP, b"tls\x00")
+        except OSError as e:
+            if e.errno in (errno.ENOENT, errno.EOPNOTSUPP):
+                raise KsftSkipEx("TLS ULP is not available") from e
+            raise
+
+        crypto_info = struct.pack("=HH8s16s4s8s",
+                                  TLS_1_2_VERSION,
+                                  TLS_CIPHER_AES_GCM_128,
+                                  b"\x01" * 8,
+                                  b"\x02" * 16,
+                                  b"\x03" * 4,
+                                  b"\x04" * 8)
+        try:
+            conn.setsockopt(SOL_TLS, TLS_RX, crypto_info)

tools/testing/selftests/drivers/net/hw/devmem_lib.py def run_rx_hds(cfg): · line 522

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +10 -0
+        except OSError as e:
+            if e.errno in (errno.ENOENT, errno.EOPNOTSUPP):
+                raise KsftSkipEx("TLS_CIPHER_AES_GCM_128 unavailable") from e
+            raise
+
+        with ksft_raises(OSError) as cm:
+            conn.recv(64)
+        ksft_eq(cm.exception.errno, errno.EFAULT)
+        ksft_eq(conn.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0)
+        conn.close()

[Severity: Medium]
Will this ioctl number work on all architectures?

UDMABUF_CREATE is hardcoded here with the asm-generic _IOW() encoding. The uapi header defines it as _IOW('u', 0x42, struct udmabuf_create). The direction bits of that macro depend on the architecture.

On powerpc, mips, sparc and alpha, _IOC_WRITE is 4U and _IOC_DIRSHIFT is 29. On parisc, _IOC_WRITE is 2U. On all of these the kernel's value is 0x80187542, not 0x40187542.

udmabuf_ioctl() switches on the kernel-compiled UDMABUF_CREATE and returns -ENOTTY for anything else. So _Udmabuf.__init__() fails with OSError(ENOTTY) on every run on those architectures.

The skip handling does not cover this case. Only the os.open() of /dev/udmabuf is turned into KsftSkipEx. ncdevmem is built against the real linux/udmabuf.h, so require_devmem() succeeds before we get here. The result is a hard failure on otherwise working setups, for example ppc64le with a devmem capable NIC. The next patch in the series also uses _Udmabuf(), so it has the same problem.

Could the request number be derived from the per-arch _IOC layout, for example keyed on platform.machine(), instead of using a fixed constant? Or is there a better way to get the value from the real header?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796329894.git.tavip%40google.com
#39 lore raw

PATCH 10/10 selftests: drv-net: devmem: test unreadable skbs on TCP-MD5 and TCP-AO

In reply to Octavian Purdila

Add an end-to-end devmem.py regression test covering TCP-MD5 and TCP-AO sockets, verifying that devmem TX sends on authenticated sockets and adding TCP-MD5 or TCP-AO keys with unreadable TX skbs queued are both rejected with EOPNOTSUPP, and incoming authenticated payload segments landing in unreadable net_iov fragments are dropped while incrementing TCPMD5Failure and TCPAOBad.

Assisted-by LLM
---
 tools/testing/selftests/drivers/net/hw/config |   2 +
 .../selftests/drivers/net/hw/devmem.py        |  12 +-
 .../selftests/drivers/net/hw/devmem_lib.py    | 245 +++++++++++++++++-
 3 files changed, 252 insertions(+), 7 deletions(-)
tools/testing/selftests/drivers/net/hw/config +2 -0
index 081155bf7847f..e63d2bf5a2953 100644
@@ -22,6 +22,8 @@ CONFIG_NET_IPIP=y
 CONFIG_NETKIT=y
 CONFIG_NET_SCH_INGRESS=y
 CONFIG_SYNC_FILE=y
+CONFIG_TCP_AO=y
+CONFIG_TCP_MD5SIG=y
 CONFIG_TLS=y
 CONFIG_TLS_DEVICE=y
 CONFIG_UDMABUF=y
tools/testing/selftests/drivers/net/hw/devmem.py +9 -3
index d15118060d261..d7e3915e4ee36 100755
@@ -3,8 +3,8 @@
 
 from os import path
 from devmem_lib import (setup_test, run_rx, run_tx, run_tx_chunks, run_rx_hds,
-                        run_rx_large_niov, run_rx_tls)
-from lib.py import ksft_run, ksft_exit, ksft_disruptive
+                        run_rx_large_niov, run_rx_tls, run_tcp_auth)
+from lib.py import ksft_run, ksft_exit, ksft_disruptive, ksft_variants
 from lib.py import NetDrvEpEnv
 
 
@@ -41,12 +41,18 @@ def check_rx_tls(cfg) -> None:
     run_rx_tls(cfg)
 
 
+@ksft_variants(["md5", "ao"])
+def check_tcp_auth(cfg, mode) -> None:
+    """Run the TCP-MD5 or TCP-AO unreadable RX/TX test."""
+    run_tcp_auth(cfg, mode)
+
+
 def main() -> None:
     """Run the devmem test cases."""
     with NetDrvEpEnv(__file__) as cfg:
         setup_test(cfg, path.abspath(path.dirname(__file__) + "/ncdevmem"))
         ksft_run([check_rx, check_tx, check_tx_chunks, check_rx_hds,
-                  check_rx_large_niov, check_rx_tls],
+                  check_rx_large_niov, check_rx_tls, check_tcp_auth],
                  args=(cfg,))
     ksft_exit()
 
tools/testing/selftests/drivers/net/hw/devmem_lib.py +241 -4

282 lines not on this page · raw message

Signature · 1 line
2.56.1.915.g69d5ec7298-goog
#40 lore raw

Re: [PATCH net 10/10] selftests: drv-net: devmem: test unreadable skbs on TCP-MD5 and TCP-AO

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [Low] selftests/drv-net: missing ksft_disruptive on check_tcp_auth() - [Low] selftests: drv-net…

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [Low] selftests/drv-net: missing ksft_disruptive on check_tcp_auth()
- [Low] selftests: drv-net: run_tcp_auth() uses remote socat without require_cmd()
- [Low] selftests: drv-net: hardcoded asm-generic SO_ZEROCOPY and SCM_DEVMEM_DMABUF
- [Low] selftests: devmem: run_tcp_auth() aborts sender below TCP_RTO_MIN (150ms)
- [Low] selftests: devmem: run_tcp_auth() sends local-endian structs to remote
- [Low] selftests: drv-net: devmem: TCP_CORK 200ms probe timer races run_tcp_auth()
--

commit 7c6c1d51d9efdb69a8ea4cff34ab61665639eca4
Author: Octavian Purdila <[email protected]>

selftests: drv-net: devmem: test unreadable skbs on TCP-MD5 and TCP-AO

This commit adds a devmem.py test case for TCP-MD5 and TCP-AO sockets, verifying that devmem TX sends and key additions with queued unreadable skbs fail with EOPNOTSUPP while unreadable incoming authenticated segments are dropped.

Quoted 4 lines
tools/testing/selftests/drivers/net/hw/devmem.py +0 -0
index d15118060d261..d7e3915e4ee36 100755

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem.py def check_rx_tls(cfg) -> None: · line 47

Quoted 8 lines
tools/testing/selftests/drivers/net/hw/devmem.py +4 -0
@@ -41,12 +41,18 @@ def check_rx_tls(cfg) -> None:
     run_rx_tls(cfg)
 
 
+@ksft_variants(["md5", "ao"])
+def check_tcp_auth(cfg, mode) -> None:
+    """Run the TCP-MD5 or TCP-AO unreadable RX/TX test."""
+    run_tcp_auth(cfg, mode)

[Severity: Low]
Should check_tcp_auth() carry @ksft_disruptive below @ksft_variants()?

run_tcp_auth() calls _setup_devmem_rx_queue(), which reconfigures HDS rings via ethnl.rings_set(), changes the RSS indirection table, and binds a devmem RX queue. Without @ksft_disruptive, running devmem.py with DISRUPTIVE=False on a single-interface system will still execute this test and can disconnect NETIF.

Quoted 4 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +0 -0
index 75199a01ca3fc..13dd2c9482683 100644

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem_lib.py def run_rx_hds(cfg): · line 329

Quoted 7 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +3 -0
@@ -322,11 +324,19 @@ def run_rx_hds(cfg):
         ksft_eq(ncdevmem.ret, 0, f"HDS failed for payload size {size}")
 
 
+MSG_ZEROCOPY = 0x4000000
+SO_ZEROCOPY = 60
+SCM_DEVMEM_DMABUF = 79

[Severity: Low]
Will these hardcoded asm-generic values break on SPARC and PA-RISC?

On SPARC, SO_ZEROCOPY is 0x003e (62) and SCM_DEVMEM_DMABUF is 0x0058 (88), while 60 is SCM_TIMESTAMPING_PKTINFO; PA-RISC uses 0x4035 and 0x404f. Passing the wrong constants makes setsockopt() and _sendmsg_devmem_tx() target unrelated options or fail instead of exercising devmem TX.

[ ... ]

Quoted 14 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +14 -0
+    try:
+        if mode == "md5":
+            opt = _pack_md5sig(af, cfg.remote_addr, key)
+            remote_opt = _pack_md5sig(af, cfg.addr, key)
+            opt_num = TCP_MD5SIG_EXT
+        else:
+            opt = _pack_tcp_ao_add(af, cfg.remote_addr, key)
+            remote_opt = _pack_tcp_ao_add(af, cfg.addr, key)
+            opt_num = TCP_AO_ADD_KEY
+        srv.setsockopt(socket.IPPROTO_TCP, opt_num, opt)
+    except OSError as e:
+        if e.errno in (errno.ENOPROTOOPT, errno.EOPNOTSUPP, errno.ENOENT):
+            raise KsftSkipEx(f"{mode} unsupported on local kernel") from e
+        raise

tools/testing/selftests/drivers/net/hw/devmem_lib.py s.close() · line 672

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +10 -0
+
+    opt_hex = remote_opt.hex()
+    probe_script = (
+        f"import socket\n"
+        f"with socket.socket({int(af)}, socket.SOCK_STREAM) as s:\n"
+        f"    s.setsockopt(socket.IPPROTO_TCP, {opt_num}, "
+        f"bytes.fromhex('{opt_hex}'))\n"
+    )
+    if _remote_py(cfg, probe_script, fail=False).ret != 0:
+        raise KsftSkipEx(f"{mode} unsupported on remote kernel")

[Severity: Low]
Can remote_opt fail with EINVAL when the local and remote hosts have different endianness?

_pack_md5sig() and _pack_tcp_ao_add() serialize sa_family, tcpm_keylen, and the _TcpAoAdd bitfields in local host byte and bit order. On a mixed-endian SSH setup (for example, a big-endian DUT with a little-endian remote endpoint), the remote kernel rejects the swapped option with EINVAL and probe_script silently turns that into a skip. Packing the struct inside the remote Python script avoids the mismatch.

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem_lib.py s.close() · line 702

Quoted 5 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +5 -0
+s.recv(1)
+s.sendall(b"authenticated-payload")
+time.sleep(0.15)
+s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
+s.close()

[Severity: Low]
Could this 0.15s sleep cause ksft_busy_wait() to time out if the payload segment is dropped?

Linux TCP_RTO_MIN is 200ms, so neither the normal RTO nor a single-packet tail loss probe can fire before sender_script aborts the socket with SO_LINGER (1, 0) and purges the retransmit queue. Blocking on s.recv(1) with a safety timeout until the local side closes conn, as run_rx_tls() does, allows retransmissions and avoids the fixed 150ms idle delay.

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem_lib.py s.close() · line 732

Quoted 3 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +3 -0
+    cork_port = rand_port()
+    with bkg(socat_listen(cfg, cork_port), host=cfg.remote):
+        wait_port_listen(cork_port, host=cfg.remote)

[Severity: Low]
Is cfg.require_cmd("socat", local=False, remote=True) missing here?

Neither run_tcp_auth() nor socat_listen() checks for socat on the remote host, so if socat is not installed on cfg.remote the test fails with a 5-second wait_port_listen() timeout instead of skipping cleanly.

[ ... ]

tools/testing/selftests/drivers/net/hw/devmem_lib.py s.close() · line 749

Quoted 11 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +11 -0
+        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1)
+        ksft_eq(_sendmsg_devmem_tx(conn, tx_dmabuf_id, 64), 64)
+        if opt_num == TCP_AO_ADD_KEY:
+            with ksft_raises(OSError) as cm:
+                conn.setsockopt(socket.IPPROTO_TCP, opt_num, opt)
+            ksft_eq(cm.exception.errno, errno.EISCONN)
+            conn.setsockopt(socket.IPPROTO_TCP, TCP_REPAIR, TCP_REPAIR_ON)
+            try:
+                with ksft_raises(OSError) as cm:
+                    conn.setsockopt(socket.IPPROTO_TCP, opt_num, opt)
+                ksft_eq(cm.exception.errno, errno.EOPNOTSUPP)

[Severity: Low]
Can the TCP_CORK probe timer flush the 64-byte skb before the final setsockopt() runs?

Holding back the partial skb under TCP_CORK arms ICSK_TIME_PROBE0 for 200ms via __tcp_push_pending_frames() -> tcp_check_probe_timer(), and TCP_REPAIR_ON does not cancel that timer:

test thread <softirq>
_sendmsg_devmem_tx(..., 64)
tcp_check_probe_timer()
[>= 200ms delay]
tcp_probe_timer()
tcp_write_wakeup()
tcp_transmit_skb() <-- flushes skb
[peer ACKs, tcp_clean_rtx_queue() frees]
setsockopt(..., opt_num, opt)
tcp_tx_has_unreadable_skb() == false <-- succeeds instead of EOPNOTSUPP

Under a loaded CI VM or debug kernel, setsockopt() then succeeds, leaving cm.exception as None and failing on cm.exception.errno with AttributeError.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#41 lore raw

Re: [PATCH net 10/10] selftests: drv-net: devmem: test unreadable skbs on TCP-MD5 and TCP-AO

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 1

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] The corked TX part of run_tcp_auth() (tools/testing/selftests/drivers/net/hw/devmem_lib.py) can fail…
- [Low] selftests: drv-net: hardcoded asm-generic SO_ZEROCOPY and SCM_DEVMEM_DMABUF

--

selftests: drv-net: devmem: test unreadable skbs on TCP-MD5 and TCP-AO

This adds a devmem.py test for TCP-MD5 and TCP-AO sockets. It checks that devmem TX sends on authenticated sockets fail with EOPNOTSUPP. It also checks that adding an MD5 or AO key fails with EOPNOTSUPP while unreadable TX skbs are queued. Finally, it checks that authenticated segments landing in unreadable net_iov frags are dropped and counted in TCPMD5Failure or TCPAOBad.

Quoted 4 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +0 -0
index 75199a01ca3fc..13dd2c9482683 100644

[ ... ]

Quoted 1 line
tools/testing/selftests/drivers/net/hw/devmem_lib.py +0 -0
@@ -520,3 +530,230 @@ s.close()

[ ... ]

Quoted 2 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +2 -0
+def run_tcp_auth(cfg, mode):
+    """Verify TCP-MD5 or TCP-AO rejects unreadable devmem RX and TX skbs."""

[ ... ]

Quoted 17 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +17 -0
+    cork_port = rand_port()
+    with bkg(socat_listen(cfg, cork_port), host=cfg.remote):
+        wait_port_listen(cork_port, host=cfg.remote)
+        conn = socket.socket(af, socket.SOCK_STREAM)
+        defer(conn.close)
+        conn.settimeout(5.0)
+        conn.bind((cfg.addr, 0))
+        conn.connect((cfg.remote_addr, cork_port))
+        conn.setsockopt(socket.SOL_SOCKET, SO_ZEROCOPY, 1)
+        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1)
+        ksft_eq(_sendmsg_devmem_tx(conn, tx_dmabuf_id, 64), 64)
+        if opt_num == TCP_AO_ADD_KEY:
+            with ksft_raises(OSError) as cm:
+                conn.setsockopt(socket.IPPROTO_TCP, opt_num, opt)
+            ksft_eq(cm.exception.errno, errno.EISCONN)
+            conn.setsockopt(socket.IPPROTO_TCP, TCP_REPAIR, TCP_REPAIR_ON)
+            try:

tools/testing/selftests/drivers/net/hw/devmem_lib.py s.close() · line 756

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +10 -0
+                with ksft_raises(OSError) as cm:
+                    conn.setsockopt(socket.IPPROTO_TCP, opt_num, opt)
+                ksft_eq(cm.exception.errno, errno.EOPNOTSUPP)
+            finally:
+                conn.setsockopt(socket.IPPROTO_TCP, TCP_REPAIR,
+                                TCP_REPAIR_OFF_NO_WP)
+        else:
+            with ksft_raises(OSError) as cm:
+                conn.setsockopt(socket.IPPROTO_TCP, opt_num, opt)
+            ksft_eq(cm.exception.errno, errno.EOPNOTSUPP)

[Severity: Medium]
Can this corked TX check in run_tcp_auth() fail intermittently? TCP_CORK alone doesn't seem to keep the 64 byte devmem skb queued for good.

By the time _sendmsg_devmem_tx() returns, tcp_push() has already called __tcp_push_pending_frames(). Nothing is in flight and the write queue is not empty, so tcp_write_xmit() returns true and the probe timer is armed:

net/ipv4/tcp_output.c:__tcp_push_pending_frames() {
    ...
	if (tcp_write_xmit(sk, cur_mss, nonagle, 0,
			   sk_gfp_mask(sk, GFP_ATOMIC)))
		tcp_check_probe_timer(sk);
}

ICSK_TIME_PROBE0 is armed at tcp_probe0_base(), which is max(RTO, TCP_RTO_MIN), so about 200ms. When it fires, the call chain tcp_probe_timer()->tcp_send_probe0()->tcp_write_wakeup() sends the send head without checking TCP_CORK:

net/ipv4/tcp_output.c:tcp_write_wakeup() {
    ...
	skb = tcp_send_head(sk);
	if (skb && before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp))) {
	...
		err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC);
    ...
}

The remote socat then ACKs the segment, which frees it from tcp_rtx_queue. After that, tcp_tx_has_unreadable_skb() no longer finds an unreadable skb:

include/net/tcp.h:tcp_tx_has_unreadable_skb() {
    ...
	skb_queue_walk(&sk->sk_write_queue, skb) {
		if (!skb_frags_readable(skb))
			return true;
	}
	skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
    ...
}

At that point tcp_md5_do_add() or tcp_ao_add_cmd() would accept the key. The ksft_raises(OSError) check would then fail because no exception is raised.

Nothing in the test keeps the skb queued. The peer reads normally, there is no zero window, and TCP_REPAIR is not entered before the send. So the result depends on the following setsockopt() calls running within about one RTO, which may not happen on a loaded CI host.

The AO branch makes the window longer. It does the EISCONN setsockopt() and turns TCP_REPAIR on before the setsockopt() that is expected to fail with EOPNOTSUPP.

Could the test hold the unreadable skb in the queue in a deterministic way, so the result doesn't depend on timing?

Quoted 3 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +3 -0
+        conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
+                        struct.pack("ii", 1, 0))
+        conn.close()

[ ... ]

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +3 -0
@@ -322,11 +324,19 @@ def run_rx_hds(cfg):
         ksft_eq(ncdevmem.ret, 0, f"HDS failed for payload size {size}")
 
 
+MSG_ZEROCOPY = 0x4000000
+SO_ZEROCOPY = 60
+SCM_DEVMEM_DMABUF = 79
 SOL_TLS = 282
 TLS_RX = 2
 TLS_1_2_VERSION = 0x0303

tools/testing/selftests/drivers/net/hw/devmem_lib.py def run_rx_hds(cfg): · line 342

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/devmem_lib.py +5 -0
 TLS_CIPHER_AES_GCM_128 = 51
+TCP_REPAIR = 19
+TCP_REPAIR_ON = 1
+TCP_REPAIR_OFF_NO_WP = -1
 TCP_ULP = 31
+TCP_MD5SIG_EXT = 32
+TCP_AO_ADD_KEY = 38
 UDMABUF_FLAGS_CLOEXEC = 0x01
 UDMABUF_CREATE = 0x40187542
 NUM_DEVMEM_PAGES = 16000

[Severity: Low]
Are these values correct on every architecture? They come from include/uapi/asm-generic/socket.h, but the SOL_SOCKET option and cmsg numbers are arch specific.

On sparc, arch/sparc/include/uapi/asm/socket.h defines SO_ZEROCOPY as 0x003e and SCM_DEVMEM_DMABUF as 0x0058. There, 0x003c (60) is SCM_TIMESTAMPING_PKTINFO. On parisc, arch/parisc/include/uapi/asm/socket.h uses 0x4035 and 0x404f.

On those hosts, conn.setsockopt(socket.SOL_SOCKET, SO_ZEROCOPY, 1) in run_tcp_auth() would pass a different option number. The cmsg built by _sendmsg_devmem_tx() would also carry a type the kernel does not treat as a devmem dmabuf binding. So the TX checks would fail with an unrelated errno, or at least would not exercise devmem TX on an authenticated socket at all.

This is unlikely to matter much, since devmem capable NICs are rarely tested on sparc or parisc. Still, could these be taken from the socket module where it exports them, with the asm-generic numbers as a fallback? Alternatively, the test could skip on architectures where the asm-generic values don't apply, so it doesn't report a misleading failure there.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796329894.git.tavip%40google.com