pull request (net): ipsec 2026-12-01
Subsystems (6)
Steffen Klassert
maintainercover pull request (net): ipsec 2026-12-01
1) xfrm: ipcomp: account full fragment pages in truesize Charge the decompressed IPComp skb a page-rounded truesize, so the socket memory accounting matches the pages actually attached.
2) xfrm: esp: reset outer TCP GSO metadata on espintcp input Reset the GSO state inherited from the outer TCP stream on ESP-in-TCP input, so a decrypted packet isn't segmented with stale metadata and multi-segment records no longer crash.
3) xfrm: keep the mode module pinned until destroy_state returns Hold an extra module reference across the state destroy callback, so an rmmod racing the state GC can't free the module text while the callback is still running.
4) xfrm: serialize SA activation with state deletion Take the state lock for the final VOID-to-VALID transition, so a hard expiry can't delete the state in between and leave it in the per-CPU cache.
5) xfrm: keep old state references until migration deletion completes Delete the old states before dropping their lookup references, so a concurrent expiry can't free a state the migration still uses.
6) xfrm: hold migrated states through rollback
Keep a caller reference on the successor states and delete them before releasing it, so a failed migration can't touch a state that has already been reclaimed.
7) xfrm: check inner family via skb_dst for small_ipv6 DF clearing Take the inner address family from the dst instead of skb->protocol, so the outer DF bit is cleared for small IPv6 packets and the tunnel doesn't drop them.
8) xfrm: account XFRMA_MARK in xfrm_sa_len()
Count the mark attribute in the SA message length, so the netlink SA notifications are sized correctly.
9) xfrm: replay: Fix late packet handling with ESN crypto offload Drop packets far ahead of the replay window when the ICV check runs in hardware, so a late packet can't corrupt the offloaded ESN state.
10) xfrm: fix IPv6 first-fragment protocol decode
Let the flow dissector walk past an IPv6 fragment header, so the inbound policy lookup sees the real upper-layer protocol.
11) xfrm: fix selector matching for IPv6 atomic fragments Restore the port and protocol selector fields for atomic IPv6 fragments, so such packets can match a policy.
12) xfrm: espintcp: read the socket error queue for MSG_ERRQUEUE Read the error queue through the socket error path, so a queued timestamp is reported instead of being consumed as an IKE message.
13) xfrm: iptfs: force a dst reference before queueing an skb Take a dst reference while the packet is still under RCU, so the deferred IPTFS output doesn't use a dst that may already be gone.
14) xfrm: espintcp: select receive path by skb protocol Pick the receive path from the packet protocol instead of the socket family, so an IPv4 packet on a v4-mapped socket isn't parsed by the IPv6 path.
15) net: xfrm: interface: restore dst_orig on every xfrm interface Restore the original route in both arms of the interface xmit path, so a steered packet finds a policy and the metadata dst is left untouched.
16) xfrm: iptfs: make room before copying a continuation in reassembly Grow the skb head before copying a reassembly continuation, so a larger continuation doesn't overrun the buffer and panic.
17) xfrm/compat: pass on the translated length of a socket policy Pass the translated policy length to the 32-bit compat layer, so the last template isn't dropped and an ESP-required policy doesn't fall back to clear text.
18) xfrm: Give GC list nodes their own storage
Give the GC and hash list nodes separate storage, so adding a state to the GC list can't corrupt the hash linkage that RCU readers still follow.
19) xfrm: Serialize device state teardown
Let only one caller free the device state and hold a reference in the flush, so the state GC and a device flush can't free the same state.
20) xfrm: Wait for an RCU grace period before freeing device state Wait for an RCU grace period after collecting the device states, so the driver state isn't freed while readers are still using it.
21) Revert "xfrm: serialize state GC with device state flush" Revert the GC and flush mutex, since the reference handling and the single-free rule make it unnecessary and it can't cover the lookup path.
22) xfrm: Serialize offload stats updates with x->lock Serialize the offload stats refresh with the state lock, so the counters aren't updated twice and a dump doesn't copy them while they change.
Please pull or let me know if there are problems.
Thanks!
The following changes since commit 787268686c64be60023743b527645a907e38ccca:
ipmr, ip6mr: queue netlink route queries out of band (2026-11-03 22:30:55 +0100)
are available in the Git repository at:
git://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec.git tags/ipsec-2026-12-01
for you to fetch changes up to bb65a0da99bf4861dce01149ba64e875e47ae5a3:
xfrm: Serialize offload stats updates with x->lock (2026-11-30 11:36:34 +0100)
----------------------------------------------------------------
ipsec-2026-12-01
----------------------------------------------------------------
Andrii Tereshchenko (2):
xfrm: iptfs: make room before copying a continuation in reassembly xfrm/compat: pass on the translated length of a socket policy
Baek Kyu, Kim (1):
xfrm: espintcp: read the socket error queue for MSG_ERRQUEUE
Cen Zhang (3):
xfrm: keep the mode module pinned until destroy_state returns
xfrm: keep old state references until migration deletion completes
xfrm: hold migrated states through rollback
Cosmin Ratiu (1):
xfrm: replay: Fix late packet handling with ESN crypto offload
Guoshuai Yang (1):
xfrm: esp: reset outer TCP GSO metadata on espintcp input
Jamal Hadi Salim (1):
net: xfrm: interface: restore dst_orig on every xfrm interface
Jianbo Liu (5):
xfrm: Give GC list nodes their own storage
xfrm: Serialize device state teardown
xfrm: Wait for an RCU grace period before freeing device state Revert "xfrm: serialize state GC with device state flush"
xfrm: Serialize offload stats updates with x->lock
Jérémy Jean (2):
xfrm: fix IPv6 first-fragment protocol decode
xfrm: fix selector matching for IPv6 atomic fragments
Kyle Zeng (1):
xfrm: serialize SA activation with state deletion
Nguyen Ngoc Thang (1):
xfrm: iptfs: force a dst reference before queueing an skb
Sewook Seo (1):
xfrm: check inner family via skb_dst for small_ipv6 DF clearing
Yasuaki Torimaru (1):
xfrm: account XFRMA_MARK in xfrm_sa_len()
Zhiling Zou (1):
xfrm: ipcomp: account full fragment pages in truesize
Zihan Xi (1):
xfrm: espintcp: select receive path by skb protocol
include/net/esp.h | 51 +++++++++++++ include/net/ipv6.h | 1 + include/net/xfrm.h | 26 ++++--- net/core/filter.c | 8 -- net/ipv4/esp4.c | 9 +++ net/ipv6/esp6.c | 9 +++ net/ipv6/exthdrs_core.c | 25 ++++--- net/xfrm/espintcp.c | 5 +- net/xfrm/xfrm_compat.c | 18 ++++- net/xfrm/xfrm_device.c | 4 +- net/xfrm/xfrm_interface_bpf.c | 19 ++--- net/xfrm/xfrm_interface_core.c | 22 +++--- net/xfrm/xfrm_ipcomp.c | 2 +- net/xfrm/xfrm_iptfs.c | 17 ++++- net/xfrm/xfrm_output.c | 5 +- net/xfrm/xfrm_policy.c | 61 +++++++++++---- net/xfrm/xfrm_replay.c | 14 +++- net/xfrm/xfrm_state.c | 164 ++++++++++++++++++++++++++++++++--------- net/xfrm/xfrm_user.c | 50 +++++++++++-- 19 files changed, 395 insertions(+), 115 deletions(-)
Steffen Klassert
maintainerPATCH 1/22 xfrm: ipcomp: account full fragment pages in truesize
From: Zhiling Zou <[email protected]>
ipcomp_post_acomp() allocates order-0 pages for decompressed skb fragments, but on input charges truesize by the decompressed byte count. When the output ends partway through a page, the unused tail of its final page is not accounted to the receiving socket. Repeated IPComp packets can therefore retain more memory than the socket receive-memory limits charge.
Round the decompressed length up to page size when charging input skb truesize, matching the pages attached to the skb. Leave output accounting unchanged.
--- net/xfrm/xfrm_ipcomp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/xfrm/xfrm_ipcomp.c +1 -1
@@ -67,7 +67,7 @@ static int ipcomp_post_acomp(struct sk_buff *skb, int err, int hlen)/* Only update truesize on input. */ if (!hlen) - skb->truesize += dlen; + skb->truesize +=PAGE_ALIGN (dlen); skb->data_len = dlen; skb->len += dlen;
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 01/22] xfrm: ipcomp: account full fragment pages in truesize
TL;DR: In ipcomp_post_acomp(), the truesize increase may unbalance the sender's sk_wmem_alloc for skbs arriving via veth and ESP GRO, possibly underflowing it or freeing the socket early; the patch…
Quoted 1 line
xfrm: ipcomp: account full fragment pages in truesize
TL;DR: In ipcomp_post_acomp(), the truesize increase may unbalance the sender's sk_wmem_alloc for skbs arriving via veth and ESP GRO, possibly underflowing it or freeing the socket early; the patch enlarges an existing mismatch.
Quoted 3 lines
net/xfrm/xfrm_ipcomp.c +0
-0
[ ... ]
net/xfrm/xfrm_ipcomp.c static int ipcomp_post_acomp(struct sk_buff *skb, int err, int hlen) · line 72
Quoted 8 lines
net/xfrm/xfrm_ipcomp.c +1
-1@@ -67,7 +67,7 @@ static int ipcomp_post_acomp(struct sk_buff *skb, int err, int hlen)/* Only update truesize on input. */ if (!hlen) - skb->truesize += dlen; + skb->truesize +=PAGE_ALIGN (dlen); skb->data_len = dlen; skb->len += dlen;
Can this truesize write unbalance sk_wmem_alloc of the sending socket when the skb arrives through the ESP GRO path?
The input branch assumes the skb is not charged to any socket. On the ordinary xfrm4_rcv()/xfrm6_rcv() path the skb was already orphaned in ip_rcv_core()/ip6_rcv_core(), so that holds.
But a local UDP or raw sender's skb carries the sock_wfree destructor, and the following path keeps it:
veth_xmit()
veth_skb_is_eligible_for_gro() accepts skb->destructor == sock_wfree __dev_forward_skb() -> skb_scrub_packet() does not orphanveth_xdp_rcv_skb()
skb_prepare_for_gro() only orphans when destructor != sock_wfree napi_gro_receive()
inet_gro_receive() -> esp4_gro_receive() -> xfrm_input()
ipcomp_input() -> ipcomp_decompress() -> ipcomp_input_done2()
ipcomp_post_acomp(skb, err, 0)
skb->truesize += PAGE_ALIGN(dlen);The skb is still charged to the sender at that point. Later ip_rcv_core() calls skb_orphan(), and sock_wfree() subtracts the inflated skb->truesize from sk_wmem_alloc, which was only charged with the original value.
Each such packet over-subtracts PAGE_ALIGN(dlen) from the sender's sk_wmem_alloc, which can underflow the refcount or drop it to zero early and run __sk_free() while the socket is still in use.
The same hazard existed with the old "+= dlen", but this patch enlarges the mismatch by up to PAGE_SIZE - 1 per packet (about 64K on 64K-page kernels).
pskb_expand_head() guards this kind of change:
if (!skb->sk || skb->destructor == sock_edemux) skb->truesize += size - osize;
Would gating the input adjustment the same way keep the receive-side fix without touching a sender's wmem charge?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/46652847109
Re: [PATCH 01/22] xfrm: ipcomp: account full fragment pages in truesize
In reply to Steffen KlassertThis series was applied to netdev/net.git (main) by Steffen Klassert <[email protected]>:
Hello:
This series was applied to netdev/net.git (main) by Steffen Klassert <[email protected]>:
Quoted 10 lines · On Tue, 1 Dec 2026 13:41:27 +0100 you wrote:
From: Zhiling Zou <[email protected]>
ipcomp_post_acomp()allocates order-0 pages for decompressed skb fragments, but on input charges truesize by the decompressed byte count. When the output ends partway through a page, the unused tail of its final page is not accounted to the receiving socket. Repeated IPComp packets can therefore retain more memory than the socket receive-memory limits charge.[...]
Here is the summary with links:
- [01/22] xfrm: ipcomp: account full fragment pages in truesize
https://git.kernel.org/netdev/net/c/66a8ea84d849 - [02/22] xfrm: esp: reset outer TCP GSO metadata on espintcp input https://git.kernel.org/netdev/net/c/49d6c6c88b9d - [03/22] xfrm: keep the mode module pinned until destroy_state returns https://git.kernel.org/netdev/net/c/2f3afcc47c3c - [04/22] xfrm: serialize SA activation with state deletion https://git.kernel.org/netdev/net/c/d393ddcdd7e9 - [05/22] xfrm: keep old state references until migration deletion completes https://git.kernel.org/netdev/net/c/8c031a30a93c - [06/22] xfrm: hold migrated states through rollback https://git.kernel.org/netdev/net/c/f0e68014f4ac - [07/22] xfrm: check inner family via skb_dst for small_ipv6 DF clearing https://git.kernel.org/netdev/net/c/fdec80191ba2 - [08/22] xfrm: account XFRMA_MARK in xfrm_sa_len() https://git.kernel.org/netdev/net/c/c5236b0f7521 - [09/22] xfrm: replay: Fix late packet handling with ESN crypto offload https://git.kernel.org/netdev/net/c/923cfbb140b6 - [10/22] xfrm: fix IPv6 first-fragment protocol decode https://git.kernel.org/netdev/net/c/a1fcc50e87dc - [11/22] xfrm: fix selector matching for IPv6 atomic fragments https://git.kernel.org/netdev/net/c/f0c21f107b22 - [12/22] xfrm: espintcp: read the socket error queue for MSG_ERRQUEUE https://git.kernel.org/netdev/net/c/d60bd31718cd - [13/22] xfrm: iptfs: force a dst reference before queueing an skb https://git.kernel.org/netdev/net/c/b88c75488ecc - [14/22] xfrm: espintcp: select receive path by skb protocol https://git.kernel.org/netdev/net/c/2803867cf3de - [15/22] net: xfrm: interface: restore dst_orig on every xfrm interface https://git.kernel.org/netdev/net/c/552253ba07f6 - [16/22] xfrm: iptfs: make room before copying a continuation in reassembly https://git.kernel.org/netdev/net/c/a914eda8aad7 - [17/22] xfrm/compat: pass on the translated length of a socket policy https://git.kernel.org/netdev/net/c/1213df0bc599 - [18/22] xfrm: Give GC list nodes their own storage https://git.kernel.org/netdev/net/c/ae12bd0175b2 - [19/22] xfrm: Serialize device state teardown https://git.kernel.org/netdev/net/c/fee0b300b693 - [20/22] xfrm: Wait for an RCU grace period before freeing device state https://git.kernel.org/netdev/net/c/d4a171f1bcd6 - [21/22] Revert "xfrm: serialize state GC with device state flush" https://git.kernel.org/netdev/net/c/38c7f3b1f51b - [22/22] xfrm: Serialize offload stats updates with x->lock https://git.kernel.org/netdev/net/c/bb65a0da99bf
You are awesome, thank you!
Signature · 2 lines
Deet-doot-dot, I am a bot. https://korg.docs.kernel.org/patchwork/pwbot.html
Steffen Klassert
maintainerPATCH 2/22 xfrm: esp: reset outer TCP GSO metadata on espintcp input
In reply to Steffen KlassertFrom: Guoshuai Yang <[email protected]>
When ESP packets are received over TCP (RFC 8229 espintcp), strparser slices individual length-prefixed ESP records from the outer TCP stream by cloning the incoming TCP skb(s) in __strp_recv().
If the outer TCP skb was GRO-coalesced before reaching strparser, its skb_shinfo carries the outer TCP stream's GSO metadata (gso_size, gso_segs, and gso_type). When an ESP record spans two outer TCP segments, strparser chains the spillover clone onto skb_shinfo(head)->frag_list.
Subsequently in esp_input() and esp6_input(), skb_cow_data() unshares the head skb via pskb_expand_head() (preserving the outer TCP gso_size and gso_type in the new private skb_shinfo) and calls skb_copy() on each cloned frag_list member, which copies the outer TCP GSO fields via skb_copy_header() onto a linear frag_list child skb allocated from slab with head_frag == 0.
Furthermore, on kernels with TCP fraglist GRO support, if an outer TCP GRO aggregate carrying SKB_GSO_FRAGLIST reaches the espintcp socket unsegmented (for example, when rx-gro-list is enabled on a device in an outer netns where tcp4/6_check_fraglist_gro() finds no local socket and the aggregate is forwarded across a NETIF_F_GSO_FRAGLIST-capable veth device into the netns hosting the espintcp socket) and is chained onto skb_shinfo(head)->frag_list by __strp_recv(), skb_cow_data() invokes skb_copy() / skb_copy_expand() on that frag_list member and hits WARN_ON_ONCE(skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST), failing with -ENOMEM before decryption even begins. (On older stable trees without TCP fraglist GRO, the pre-pass is a no-op.)
After ESP decryption and header removal, the resulting single inner packet still has skb_is_gso(skb) == true with the stale outer TCP gso_size, while skb_headlen(head_skb) is now smaller than that gso_size due to stripping the outer framing and ESP header. When this packet passes through gro_cells_receive() (which flushes frag_list packets via GRO_NORMAL without resetting gso_size) and is forwarded, validate_xmit_skb() invokes tcp_gso_segment() -> skb_segment(). Because head_skb is shorter than the stale gso_size and SKB_GSO_DODGY is not set, skb_segment() attempts to map the slab-backed frag_list member as a scatter-gather page fragment where list_skb->head_frag == 0. On current mainline kernels, skb_segment() triggers DEBUG_NET_WARN_ON_ONCE(1) and fails with -EINVAL, causing validate_xmit_skb() to drop all multi-segment espintcp packets. On stable kernels prior to the removal of BUG_ON(!list_skb->head_frag) in skb_segment() (such as 6.12.94 where this trace was captured), it crashes the kernel:
Internal error: Oops - undefined instruction: 0 [#1] SMP ARM PC is at skb_segment+0x574/0xd20 LR is at skb_segment+0x884/0xd20 Call trace: skb_segment from tcp_gso_segment tcp_gso_segment from inet_gso_segment inet_gso_segment from skb_mac_gso_segment skb_mac_gso_segment from __skb_gso_segment __skb_gso_segment from validate_xmit_skb validate_xmit_skb from __dev_queue_xmit __dev_queue_xmit from ip_finish_output2 ip_finish_output2 from ip_output ip_output from ip_sublist_rcv_finish ip_sublist_rcv_finish from ip_sublist_rcv ip_list_rcv from __netif_receive_skb_list_core __netif_receive_skb_list_core from __netif_receive_skb_list __netif_receive_skb_list from gro_normal_list gro_normal_list from gro_cell_poll
Similarly, if a decrypted inner packet with a frag_list later takes the ip_do_fragment() frag_list fast path, each detached frag_list member is transmitted as a standalone IP fragment and would still carry the stale outer TCP GSO state when reaching validate_xmit_skb(). And even when an ESP record does not have a frag_list, leaving the stale outer TCP gso_size on the decrypted inner skb prevents dev_gro_receive() from initializing gso_size to the inner packet's skb_gro_len().
We cannot reset GSO state earlier in espintcp_rcv() / handle_esp() because the skb may still be a clone sharing skb_shinfo with the outer TCP skb held by strparser. Instead, in esp_input() and esp6_input():
1. Prior to skb_cow_data(), unshare/unclone and reset GSO metadata on any frag_list member carrying SKB_GSO_FRAGLIST (unsharing any shared predecessor frag_list members along the walk) so skb_copy() / skb_copy_expand() inside skb_cow_data() does not hit WARN_ON_ONCE() and drop the packet.
2. At skip_cow, where the head skb and all frag_list members are guaranteed to be uncloned with private skb_shinfo, call skb_gso_reset() on both the head skb and each skb_walk_frags() member.
--- include/net/esp.h | 51 +++++++++++++++++++++++++++++++++++++++++++++++ net/ipv4/esp4.c | 9 +++++++++ net/ipv6/esp6.c | 9 +++++++++ 3 files changed, 69 insertions(+)
include/net/esp.h +51 -0
@@ -28,6 +28,57 @@ static inline void esp_output_fill_trailer(u8 *tail, int tfclen, int plen, __u8 tail[plen -1 ] = proto; } +static inline int esp_reset_espintcp_fraglist_gso (struct sk_buff *skb) +{ +struct sk_buff **fragp; +struct sk_buff *frag; + + skb_walk_frags(skb, frag) { +if (skb_shinfo (frag)->gso_type &SKB_GSO_FRAGLIST ) +break ; + } +if (!frag) +return 0 ; + +if (skb_unclone (skb,GFP_ATOMIC )) +return -ENOMEM ; + +for (fragp = &skb_shinfo (skb)->frag_list; (frag = *fragp); + fragp = &frag->next) { +if (skb_shared (frag)) { +struct sk_buff *nfrag; + + nfrag =skb_clone (frag,GFP_ATOMIC ); +if (!nfrag) +return -ENOMEM ; + + nfrag->next = frag->next; +consume_skb (frag); + frag = nfrag; + *fragp = frag; + } + +if (!(skb_shinfo (frag)->gso_type &SKB_GSO_FRAGLIST )) +continue ; + +if (skb_unclone (frag,GFP_ATOMIC )) +return -ENOMEM ; + +skb_gso_reset (frag); + } + +return 0 ; +} + +static inline void esp_reset_espintcp_gso (struct sk_buff *skb) +{ +struct sk_buff *iter; + +skb_gso_reset (skb); + skb_walk_frags(skb, iter) +skb_gso_reset (iter); +} +struct esp_info {struct ip_esp_hdr *esph;__be64 seqno;
net/ipv4/esp4.c +9 -0
@@ -893,6 +893,12 @@ static int esp_input(struct xfrm_state *x, struct sk_buff *skb) } } +if (x->encap && x->encap->encap_type ==TCP_ENCAP_ESPINTCP ) { + err =esp_reset_espintcp_fraglist_gso (skb); +if (err) + goto out; + } + err =skb_cow_data (skb,0 , &trailer);if (err <0 ) goto out;
@@ -900,6 +906,9 @@ static int esp_input(struct xfrm_state *x, struct sk_buff *skb) nfrags = err; skip_cow: +if (x->encap && x->encap->encap_type ==TCP_ENCAP_ESPINTCP ) +esp_reset_espintcp_gso (skb); + err = -ENOMEM ; tmp =esp_alloc_tmp (aead, nfrags, seqhilen);if (!tmp)
net/ipv6/esp6.c +9 -0
@@ -936,6 +936,12 @@ static int esp6_input(struct xfrm_state *x, struct sk_buff *skb) } } +if (x->encap && x->encap->encap_type ==TCP_ENCAP_ESPINTCP ) { + ret =esp_reset_espintcp_fraglist_gso (skb); +if (ret) + goto out; + } + nfrags =skb_cow_data (skb,0 , &trailer);if (nfrags <0 ) { ret = -EINVAL ;
@@ -943,6 +949,9 @@ static int esp6_input(struct xfrm_state *x, struct sk_buff *skb) } skip_cow: +if (x->encap && x->encap->encap_type ==TCP_ENCAP_ESPINTCP ) +esp_reset_espintcp_gso (skb); + ret = -ENOMEM ; tmp =esp_alloc_tmp (aead, nfrags, seqhilen);if (!tmp)
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 3/22 xfrm: keep the mode module pinned until destroy_state returns
In reply to Steffen KlassertFrom: Cen Zhang <[email protected]>
An IPTFS state keeps its mode module referenced while mode_data exists. However, iptfs_destroy_state() drops that reference before returning to xfrm_state_gc_destroy(), which has no reference covering the callback's return path.
With CONFIG_XFRM_IPTFS=m and module unloading enabled, deleting the last IPTFS SA can overlap with ordinary module removal in this order:
XFRM GC worker rmmod xfrm_iptfs
iptfs_destroy_state()
free mode_data
module_put(owner)
<preempted>
delete_module()
xfrm_iptfs_fini()
unregister mode callbacks
free_module()
resume in freed module text
An unload started after the put can finish before the callback resumes. GC invokes the callback outside an RCU read-side critical section, after its grace period. The RCU waits in mode unregistration and module freeing therefore do not protect the callback. The GC mutex only serializes GC with device state flushes. Resuming the callback can cause an instruction-fetch fault in the freed module text.
The Oops below was observed on an earlier kernel with scheduling probes holding the worker in module_put() after the decrement until ordinary rmmod completed. The fixture created and deleted the SA over NETLINK_XFRM.
Take an additional reference to the already pinned owner before calling destroy_state(), and release it in XFRM core after the callback returns. Cache the owner before the call so releasing the extra reference does not need to access the callback table after the callback has finished.
Oops report as below:
BUG: unable to handle page fault for address: ffffffffc0407455
#PF: supervisor instruction fetch in kernel mode
#PF: error_code(0x0010) - not-present page
PGD 80a9067 P4D 80a9067 PUD 80ab067 PMD 0
Oops: Oops: 0010 [#1] SMP KASAN NOPTI
CPU: 3 UID: 0 PID: 53 Comm: kworker/3:1 Not tainted 7.2.0-rc5-pmb-xfrm-functional-v1+ #11 PREEMPT(lazy)
Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
Workqueue: events xfrm_state_gc_task
RIP: 0010:0xffffffffc0407455
Code: Unable to access opcode bytes at 0xffffffffc040742b.
RSP: 0018:ffff8881013e7aa0 EFLAGS: 00010282
RAX: 0000000000000000 RBX: ffffffffc02199c0 RCX: ffffffff816fc84e
RDX: ffff8881013c0000 RSI: 0000000000000000 RDI: ffffffff86338344
RBP: ffff8881013e7ba8 R08: 0000000000000001 R09: 0000000000000001
R10: ffffffff893e0257 R11: ffff8881013c0000 R12: ffff888107e9ec00
R13: ffff888102b07980 R14: ffff888107412ec0 R15: ffff8881013e7ae0
FS: 0000000000000000(0000) GS:ffff8881fd929000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: ffffffffc040742b CR3: 00000000080a6006 CR4: 0000000000770ef0
PKRU: 55555554
Call Trace:
<TASK>
? pmbd_gate_maybe+0x47/0x60
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? lock_is_held_type+0x8f/0x100
xfrm_state_gc_task+0x17e/0x790
? lock_acquire+0x17b/0x2f0
? __pfx_xfrm_state_gc_task+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x280
? srso_alias_return_thunk+0x5/0xfbef5
process_one_work+0x908/0x19c0
? __pfx_process_one_work+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? lock_is_held_type+0x8f/0x100
? srso_alias_return_thunk+0x5/0xfbef5
worker_thread+0x65c/0xe40
? srso_alias_return_thunk+0x5/0xfbef5
? __kthread_parkme+0x175/0x220
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_worker_thread+0x10/0x10
kthread+0x34f/0x460
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_kthread+0x10/0x10
ret_from_fork+0x659/0x940
? __pfx_ret_from_fork+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __switch_to+0x74f/0xf80
? __pfx_kthread+0x10/0x10
ret_from_fork_asm+0x1a/0x30
</TASK>
Modules linked in: [last unloaded: xfrm_iptfs]
CR2: ffffffffc0407455
---[ end trace 0000000000000000 ]---
RIP: 0010:0xffffffffc0407455
Code: Unable to access opcode bytes at 0xffffffffc040742b.
RSP: 0018:ffff8881013e7aa0 EFLAGS: 00010282
RAX: 0000000000000000 RBX: ffffffffc02199c0 RCX: ffffffff816fc84e
RDX: ffff8881013c0000 RSI: 0000000000000000 RDI: ffffffff86338344
RBP: ffff8881013e7ba8 R08: 0000000000000001 R09: 0000000000000001
R10: ffffffff893e0257 R11: ffff8881013c0000 R12: ffff888107e9ec00
R13: ffff888102b07980 R14: ffff888107412ec0 R15: ffff8881013e7ae0
FS: 0000000000000000(0000) GS:ffff8881fd929000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: ffffffffc040742b CR3: 00000000080a6006 CR4: 0000000000770ef0
PKRU: 55555554
Kernel panic - not syncing: Fatal exception
Kernel Offset: disabled--- net/xfrm/xfrm_state.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
net/xfrm/xfrm_state.c +7 -1
@@ -596,8 +596,14 @@ EXPORT_SYMBOL(xfrm_state_free);static void xfrm_state_delete_tunnel (struct xfrm_state *x);static void xfrm_state_gc_destroy (struct xfrm_state *x) { -if (x->mode_cbs && x->mode_cbs->destroy_state) +if (x->mode_cbs && x->mode_cbs->destroy_state) { +struct module *owner = x->mode_cbs->owner; + +/* The callback may drop the last module reference. */ +__module_get (owner); x->mode_cbs->destroy_state (x); +module_put (owner); + }hrtimer_cancel (&x->mtimer);timer_delete_sync (&x->rtimer);kfree_sensitive (x->aead);
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 4/22 xfrm: serialize SA activation with state deletion
In reply to Steffen KlassertFrom: Kyle Zeng <[email protected]>
xfrm_add_sa() publishes a newly constructed state and arms its lifetime timer before marking it VALID. The final VOID-to-VALID test and store are not serialized with state deletion. If hard expiry deletes the state between the test and the store, the store resurrects the unlinked state.
An input lookup which found the state before it was removed can then add it to the per-CPU cache after deletion has removed the cache entries. Once the remaining references are dropped, the cache points to freed memory.
Take x->lock around the conditional transition, with bottom halves disabled as in xfrm_state_delete(). This preserves DEAD if expiry won the race. The same protection covers UPDSA when it installs a replacement for an ACQ state.
--- net/xfrm/xfrm_user.c | 2 ++ 1 file changed, 2 insertions(+)
net/xfrm/xfrm_user.c +2 -0
@@ -1088,8 +1088,10 @@ static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh, goto out; } +spin_lock_bh (&x->lock);if (x->km.state ==XFRM_STATE_VOID ) x->km.state =XFRM_STATE_VALID ; +spin_unlock_bh (&x->lock); c.seq = nlh->nlmsg_seq; c.portid = nlh->nlmsg_pid;
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 5/22 xfrm: keep old state references until migration deletion completes
In reply to Steffen KlassertFrom: Cen Zhang <[email protected]>
xfrm_migrate() must retain the references returned by xfrm_migrate_state_find() until it finishes using the old states. The successful migration path instead calls xfrm_states_put() before xfrm_states_delete(), leaving the latter to use unreferenced pointers from x_cur[].
With CONFIG_XFRM_MIGRATE enabled, a privileged XFRM_MSG_MIGRATE or SADB_X_MIGRATE request can reach this path for an SA with a finite hard lifetime and no other users. If migration is preempted after the put, the old SA can expire and be reclaimed before deletion resumes:
Migration task Hard-expiry timer / GC worker
-------------- -----------------------------
xfrm_migrate_state_find()
hold old SA in x_cur[]
migrate state and policy
xfrm_states_put(x_cur, ...)
drop lookup reference
xfrm_timer_handler()
__xfrm_state_delete(old SA)
drop SAD reference
xfrm_state_gc_task()
synchronize_rcu()
free old SA
xfrm_states_delete(x_cur, ...)
xfrm_state_delete(old SA)
spin_lock_bh(&x->lock) /* use after free */The configuration mutex does not serialize migration with the timer or GC worker, and migration holds no RCU read lock across this interval. xfrm_state_delete() accesses the freed lock before it can check whether the state is already dead. Expiry before the migration put can open the same window, with that put dropping the last reference.
Delete the old states before putting their lookup references. Each state then remains allocated through the lock access and the dead-state check, including when expiry has already removed it from the SAD.
KASAN report as below:
==================================================================
BUG: KASAN: slab-use-after-free in _raw_spin_lock_bh+0x38/0x50
Read of size 1 at addr ffff88810967af48 by task python3/443
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
kasan_report+0xe0/0x110
__kasan_check_byte+0x36/0x50
lock_acquire+0x113/0x2f0
_raw_spin_lock_bh+0x38/0x50
xfrm_state_delete+0x26/0x60
xfrm_migrate+0xd26/0x1950
xfrm_do_migrate+0x797/0xad0
xfrm_user_rcv_msg+0x3b3/0xc20
netlink_rcv_skb+0x133/0x390
xfrm_netlink_rcv+0x76/0x90
netlink_unicast+0x504/0x840
netlink_sendmsg+0x7f7/0xcf0
__sys_sendto+0x425/0x470
__x64_sys_sendto+0xe5/0x1c0
do_syscall_64+0x115/0x6a0
entry_SYSCALL_64_after_hwframe+0x77/0x7f
</TASK>
Allocated by task 424:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_slab_alloc+0x89/0x90
kmem_cache_alloc_noprof+0x20b/0x5f0
xfrm_state_alloc+0x28/0x5d0
xfrm_add_sa+0xb81/0x5660
xfrm_user_rcv_msg+0x3b3/0xc20
netlink_rcv_skb+0x133/0x390
xfrm_netlink_rcv+0x76/0x90
netlink_unicast+0x504/0x840
netlink_sendmsg+0x7f7/0xcf0
____sys_sendmsg+0x88b/0x9d0
___sys_sendmsg+0x125/0x1d0
__sys_sendmsg+0x13e/0x1e0
do_syscall_64+0x115/0x6a0
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 66:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kmem_cache_free+0x242/0x580
xfrm_state_gc_task+0x534/0x780
process_one_work+0x908/0x19c0
worker_thread+0x65c/0xe40
kthread+0x34f/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
The buggy address belongs to the object at ffff88810967aec0
which belongs to the cache xfrm_state of size 936
The buggy address is located 136 bytes inside of
freed 936-byte region [ffff88810967aec0, ffff88810967b268)
==================================================================--- net/xfrm/xfrm_policy.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/xfrm/xfrm_policy.c +1 -1
@@ -4726,8 +4726,8 @@ int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,/* Stage 4 - delete old state(s) */ if (nx_cur) { -xfrm_states_put (x_cur, nx_cur);xfrm_states_delete (x_cur, nx_cur); +xfrm_states_put (x_cur, nx_cur); }/* Stage 5 - announce */
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 6/22 xfrm: hold migrated states through rollback
In reply to Steffen KlassertFrom: Cen Zhang <[email protected]>
xfrm_migrate() needs to keep each new state alive until it either commits or rolls back the migration. xfrm_state_migrate() publishes the successor using its initial reference as SAD ownership, then returns it without a caller reference. The pointer saved in x_new[] can therefore outlive the state.
A legacy migration can find an existing policy with no matching templates, install a successor and then fail xfrm_policy_migrate() with -ENODATA. If the successor inherits a finite hard lifetime and the migration task is delayed before rollback, expiry and GC can finish first:
Migration task Timer / GC
xfrm_state_migrate()
publish xc, arm mtimer
save xc in x_new[]
xfrm_policy_migrate()
return -ENODATA
<task delayed> xfrm_timer_handler(xc)
__xfrm_state_delete(xc) drop SAD reference
xfrm_state_gc_task()
synchronize_rcu() free xc
xfrm_states_delete(x_new)
xfrm_state_delete(xc)
spin_lock_bh(&xc->lock)The control mutex does not serialize the timer or GC, and migration holds no RCU read lock across this interval. Rollback consequently accesses the freed state's lock. This also affects the PF_KEY migration entry, which uses the same helpers.
Take a caller reference before installing the successor, and release it on installation failure or after the transaction succeeds. On rollback, delete the successors before dropping their caller references. This keeps each allocation alive even if its timer has already removed it from the SAD.
The reported execution used trace probes and paused the netlink migration before the rollback lock access while the normal timer and GC ran. The userspace setup installed an SA with a five-second hard lifetime and a policy without templates using ordinary XFRM requests.
KASAN report as below:
==================================================================
BUG: KASAN: slab-use-after-free in _raw_spin_lock_bh+0x38/0x50
Read of size 1 at addr ffff8881076d6248 by task python3/417
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
kasan_report+0xe0/0x110
__kasan_check_byte+0x36/0x50
lock_acquire+0x113/0x2f0
_raw_spin_lock_bh+0x38/0x50
xfrm_state_delete+0x26/0x60
xfrm_migrate+0x11af/0x18a0
xfrm_do_migrate+0x797/0xad0
xfrm_user_rcv_msg+0x3b3/0xc20
netlink_rcv_skb+0x133/0x390
xfrm_netlink_rcv+0x76/0x90
netlink_unicast+0x504/0x840
netlink_sendmsg+0x7f7/0xcf0
__sys_sendto+0x425/0x470
__x64_sys_sendto+0xe5/0x1c0
do_syscall_64+0x115/0x6a0
entry_SYSCALL_64_after_hwframe+0x77/0x7f
</TASK>
Allocated by task 417:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_slab_alloc+0x89/0x90
kmem_cache_alloc_noprof+0x20b/0x5f0
xfrm_state_alloc+0x28/0x5d0
xfrm_state_migrate_create+0x55/0x2470
xfrm_state_migrate+0x37/0x450
xfrm_migrate+0x80b/0x18a0
xfrm_do_migrate+0x797/0xad0
xfrm_user_rcv_msg+0x3b3/0xc20
netlink_rcv_skb+0x133/0x390
xfrm_netlink_rcv+0x76/0x90
netlink_unicast+0x504/0x840
netlink_sendmsg+0x7f7/0xcf0
__sys_sendto+0x425/0x470
__x64_sys_sendto+0xe5/0x1c0
do_syscall_64+0x115/0x6a0
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 11:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kmem_cache_free+0x242/0x580
xfrm_state_gc_task+0x533/0x730
process_one_work+0x908/0x19c0
worker_thread+0x65c/0xe40
kthread+0x34f/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
The buggy address belongs to the object at ffff8881076d61c0
which belongs to the cache xfrm_state of size 936
The buggy address is located 136 bytes inside of
freed 936-byte region [ffff8881076d61c0, ffff8881076d6568)
==================================================================--- net/xfrm/xfrm_policy.c | 5 ++++- net/xfrm/xfrm_state.c | 6 +++++- 2 files changed, 9 insertions(+), 2 deletions(-)
net/xfrm/xfrm_policy.c +4 -1
@@ -4733,6 +4733,7 @@ int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,/* Stage 5 - announce */ km_migrate (sel, dir, type, m, num_migrate, k, net, encap); +xfrm_states_put (x_new, nx_new);xfrm_pol_put (pol);return 0 ;
@@ -4744,8 +4745,10 @@ int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,xfrm_pol_put (pol);if (nx_cur)xfrm_states_put (x_cur, nx_cur); -if (nx_new) +if (nx_new) {xfrm_states_delete (x_new, nx_new); +xfrm_states_put (x_new, nx_new); + }return err; }
net/xfrm/xfrm_state.c +5 -1
@@ -2244,8 +2244,12 @@ struct xfrm_state *xfrm_state_migrate(struct xfrm_state *x,xfrm_migrate_sync (xc, x); -if (xfrm_state_migrate_install (x, xc, m, extack) <0 ) +/* Hold a reference for the caller before publishing the state. */ +xfrm_state_hold (xc); +if (xfrm_state_migrate_install (x, xc, m, extack) <0 ) { +xfrm_state_put (xc);return NULL ; + }return xc; }
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 7/22 xfrm: check inner family via skb_dst for small_ipv6 DF clearing
In reply to Steffen KlassertFrom: Sewook Seo <[email protected]>
Commit 6821ad877034 ("xfrm: do not set IPv4 DF flag when encapsulating IPv6 frames <= 1280 bytes.") intended to clear the outer IPv4 DF bit in xfrm4_tunnel_encap_add() when encapsulating inner IPv6 frames of at most IPV6_MIN_MTU (1280) bytes, by checking skb->protocol == htons(ETH_P_IPV6).
However, its caller xfrm4_prepare_output() overwrites skb->protocol with htons(ETH_P_IP) before invoking xfrm4_tunnel_encap_add(), since commit 0c620e97b349 ("xfrm: remove output indirection from xfrm_mode"). As a result, small_ipv6 always evaluates to false, leaving IP_DF set on outer IPv4 tunnel packets even when encapsulating <= 1280-byte IPv6 frames.
This issue was observed on devices in production use over IPv6-in-IPv4 ESP-in-UDP tunnels where an intermediate IPv4 link has an MTU smaller than the encapsulated packet size (e.g. < 1362 bytes) and ICMPv4 Fragmentation Needed errors are either filtered or not actionable below IPV6_MIN_MTU, causing encapsulated <= 1280-byte IPv6 packets to be dropped instead of fragmented by the outer IPv4 router.
At the time xfrm4_tunnel_encap_add() runs, skb_dst(skb) has not been popped yet and still represents the inner packet destination entry, as already used a few lines below to set top_iph->protocol via xfrm_af2proto(skb_dst(skb)->ops->family), while skb->len still holds the unencapsulated inner packet length. Check dst->ops->family == AF_INET6 instead of skb->protocol so small_ipv6 works as intended.
Tested on User-Mode Linux (ARCH=um) with a four-namespace IPv6-over-IPv4 XFRM ESP tunnel reproducer across a 1300-byte MTU router link with ICMPv4 Fragmentation Needed filtered (verifying 1280-byte inner IPv6 frames fail before the fix and pass via outer IPv4 fragmentation with the fix, while larger frames still preserve outer IP_DF), and verified all tests pass in tools/testing/selftests/net/xfrm_state.sh.
--- net/xfrm/xfrm_output.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
net/xfrm/xfrm_output.c +4 -1
@@ -275,11 +275,14 @@ static int xfrm4_beet_encap_add(struct xfrm_state *x, struct sk_buff *skb)*/ static int xfrm4_tunnel_encap_add (struct xfrm_state *x,struct sk_buff *skb) { -bool small_ipv6 = (skb->protocol ==htons (ETH_P_IPV6 )) && (skb->len <=IPV6_MIN_MTU );struct dst_entry *dst =skb_dst (skb);struct iphdr *top_iph; +bool small_ipv6;int flags; + small_ipv6 = (dst->ops->family ==AF_INET6 ) && + (skb->len <=IPV6_MIN_MTU ); +if (!skb->inner_protocol) {skb_set_inner_network_header (skb,skb_network_offset (skb));skb_set_inner_transport_header (skb,skb_transport_offset (skb));
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 07/22] xfrm: check inner family via skb_dst for small_ipv6 DF clearing
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Critical: 0 · High: 1 · Medium: 0 · Low: 0
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).
- [High] This patch fixes the family test, but small_ipv6 in xfrm4_tunnel_encap_add() (net/xfrm/xfrm_output.c:283-284) is still…
--
xfrm: check inner family via skb_dst for small_ipv6 DF clearing
This commit changes the small_ipv6 test in xfrm4_tunnel_encap_add(). It now checks dst->ops->family == AF_INET6 instead of skb->protocol, because xfrm4_prepare_output() has already set skb->protocol to ETH_P_IP. The aim is to clear the outer IPv4 DF bit when the inner IPv6 frame is 1280 bytes or less.
Quoted 7 lines
net/xfrm/xfrm_output.c +0
-0@@ -275,11 +275,14 @@ static int xfrm4_beet_encap_add(struct xfrm_state *x, struct sk_buff *skb)*/ static int xfrm4_tunnel_encap_add (struct xfrm_state *x,struct sk_buff *skb)
net/xfrm/xfrm_output.c static int xfrm4_beet_encap_add(struct xfrm_state *x, struct sk_buff *skb) · line 285
Quoted 10 lines
net/xfrm/xfrm_output.c +4
-1{ -bool small_ipv6 = (skb->protocol ==htons (ETH_P_IPV6 )) && (skb->len <=IPV6_MIN_MTU );struct dst_entry *dst =skb_dst (skb);struct iphdr *top_iph; +bool small_ipv6;int flags; + small_ipv6 = (dst->ops->family ==AF_INET6 ) && + (skb->len <=IPV6_MIN_MTU ); +
[Severity: High]
Does this test still give the wrong answer for GSO skbs that take the ESP offload path?
The commit message says that "skb->len still holds the unencapsulated inner packet length". On this path, though, skb->len appears to be the length of the whole unsegmented GSO skb.
In xfrm_output(), when xfrm_dev_offload_ok() returns true and the skb is GSO with no inner_protocol (for example, locally generated TCP over IPv6), the skb is not segmented first:
net/xfrm/xfrm_output.c:xfrm_output() {
...
if (skb_is_gso(skb)) {
if (skb->inner_protocol && x->props.mode == XFRM_MODE_TUNNEL)
return xfrm_output_gso(net, sk, skb);
skb_shinfo(skb)->gso_type |= SKB_GSO_ESP;
goto out;
}
...
}It then reaches xfrm4_tunnel_encap_add() through this chain:
xfrm_output2()->xfrm_output_resume()->xfrm_output_one()->
xfrm4_prepare_output()->xfrm4_tunnel_encap_add()
At that point skb->len can be close to 64KB.
Earlier on the same skb, xfrm6_tunnel_check_size() checks each segment rather than the total length:
net/xfrm/xfrm_output.c:xfrm6_tunnel_check_size() {
...
if ((!skb_is_gso(skb) && skb->len > mtu) ||
(skb_is_gso(skb) &&
!skb_gso_validate_network_len(skb, ip6_skb_dst_mtu(skb)))) {
...
}So every segment can be an IPv6 frame of 1280 bytes or less while small_ipv6 is still false. In that case frag_off is taken from XFRM_MODE_SKB_CB(skb)->frag_off & htons(IP_DF), and xfrm6_extract_header() always sets that field to htons(IP_DF). When esp4_gso_segment() or hardware crypto offload segments the skb later, each segment gets a copy of the outer IPv4 header with DF set.
This path does not seem to need offload hardware. xfrm_set_type_offload(x, false) sets x->type_offload whenever esp4_offload is registered. For a plain ESP software SA (x->xso.dev == NULL, x->encap == NULL), xfrm_dev_offload_ok() then reaches:
net/xfrm/xfrm_device.c:xfrm_dev_offload_ok() {
...
ok:
if (!dev)
return true;
...
}The ESP-in-UDP case reported in the commit message looks fully fixed. With x->encap set, xfrm_dev_offload_ok() returns false, and the GSO skb is segmented in xfrm_output_gso() before encapsulation.
Would it make sense to mirror xfrm6_tunnel_check_size() here, along these lines?
small_ipv6 = dst->ops->family == AF_INET6 && (skb_is_gso(skb) ? skb_gso_validate_network_len(skb, IPV6_MIN_MTU) : skb->len <= IPV6_MIN_MTU);
Quoted 3 lines
net/xfrm/xfrm_output.c +0
-0if (!skb->inner_protocol) {skb_set_inner_network_header (skb,skb_network_offset (skb));skb_set_inner_transport_header (skb,skb_transport_offset (skb));
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerRe: [PATCH 07/22] xfrm: check inner family via skb_dst for small_ipv6 DF clearing
Ccing the author of the patch.
Quoted 46 lines · On Wed, Dec 02, 2026 at 01:12:26PM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Critical: 0 · High: 1 · Medium: 0 · Low: 0
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).
- [High] This patch fixes the family test, but
small_ipv6inxfrm4_tunnel_encap_add()(net/xfrm/xfrm_output.c:283-284) is still…--
xfrm: check inner family via
skb_dstforsmall_ipv6DF clearingThis commit changes the
small_ipv6test inxfrm4_tunnel_encap_add(). It now checksdst->ops->family==AF_INET6instead ofskb->protocol, becausexfrm4_prepare_output()has already setskb->protocoltoETH_P_IP. The aim is to clear the outer IPv4 DF bit when the inner IPv6 frame is 1280 bytes or less.Quoted 7 lines
net/xfrm/xfrm_output.c +0
-0@@ -275,11 +275,14 @@ static int xfrm4_beet_encap_add(struct xfrm_state *x, struct sk_buff *skb)*/ static int xfrm4_tunnel_encap_add (struct xfrm_state *x,struct sk_buff *skb)net/xfrm/xfrm_output.c static int xfrm4_beet_encap_add(struct xfrm_state *x, struct sk_buff *skb) · line 285
Quoted 10 lines
net/xfrm/xfrm_output.c +4
-1{ -bool small_ipv6 = (skb->protocol ==htons (ETH_P_IPV6 )) && (skb->len <=IPV6_MIN_MTU );struct dst_entry *dst =skb_dst (skb);struct iphdr *top_iph; +bool small_ipv6;int flags; + small_ipv6 = (dst->ops->family ==AF_INET6 ) && + (skb->len <=IPV6_MIN_MTU ); +[Severity: High]
Does this test still give the wrong answer for GSO skbs that take the ESP offload path?
Quoted 3 lines
The commit message says that "
skb->lenstill holds the unencapsulated inner packet length". On this path, though,skb->lenappears to be the length of the whole unsegmented GSO skb.
Not a regression of this patch. The GSO path might have a similar issue. Can be fixed as a followup.
Steffen Klassert
maintainerPATCH 8/22 xfrm: account XFRMA_MARK in xfrm_sa_len()
In reply to Steffen KlassertFrom: Yasuaki Torimaru <[email protected]>
xfrm_notify_sa() sizes its netlink message with xfrm_sa_len(), while copy_to_user_state_extra() appends XFRMA_MARK whenever the state carries a mark. xfrm_sa_len() does not count that attribute. Only the XFRM_MSG_DELSA path adds it to the length separately, so for a marked state the XFRM_MSG_NEWSA and XFRM_MSG_UPDSA messages are sized short by nla_total_size(sizeof(struct xfrm_mark)), 12 bytes. The other length calculations in this file already account for the mark; xfrm_sa_len() is the only one that does not.
Instrumenting xfrm_notify_sa() on an x86-64 KASAN build under qemu to print the accounted length while adding a marked state confirms the gap:
accounting the mark raises the computed length by exactly 12 bytes (348 -> 360), matching nla_total_size(sizeof(struct xfrm_mark)).
Whether the shortfall is reached depends on the skb allocation, which is rounded up: xfrm_notify_sa() fails with -EMSGSIZE only when that slack is exhausted. km_state_notify() discards the return value, so such a failure would be silent. This was not reproduced.
Count the mark in xfrm_sa_len() for every event and drop the now redundant addition in the DELSA path. The message content is unchanged; only the computed length changes.
--- net/xfrm/xfrm_user.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/xfrm/xfrm_user.c +2 -1
@@ -4083,6 +4083,8 @@ static inline unsigned int xfrm_sa_len(struct xfrm_state *x) l +=nla_total_size (sizeof (*x->encap));if (x->tfcpad) l +=nla_total_size (sizeof (x->tfcpad)); +if (x->mark.v | x->mark.m) + l +=nla_total_size (sizeof (struct xfrm_mark ));if (x->replay_esn) l +=nla_total_size (xfrm_replay_state_esn_len (x->replay_esn));else
@@ -4138,7 +4140,6 @@ static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c)if (c->event ==XFRM_MSG_DELSA ) { len +=nla_total_size (headlen); headlen =sizeof (*id); - len +=nla_total_size (sizeof (struct xfrm_mark )); } len +=NLMSG_ALIGN (headlen);
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 9/22 xfrm: replay: Fix late packet handling with ESN crypto offload
In reply to Steffen KlassertFrom: Cosmin Ratiu <[email protected]>
xfrm_replay_seqhi() guesses seq_hi for a given ingress seq per RFC 4303 section A2.2. Packets with seq < bottom are interpreted as being ahead and the function returns the next seq_hi. xfrm_replay_check_esn() redoes the same computation and defers to the ICV check.
On SW crypto, such packets then fail the ICV check and are dropped, unless they're actual packets ~2^32 in the future (very unlikely).
But on crypto offload, the ICV check already happened in HW and isn't repeated. xfrm_replay_advance_esn() then increments replay_esn->seq_hi.
The problem becomes visible when the HW state is renewed (e.g. bond failover or mlx5 mid-sequence ESN state update). The newly offloaded SA carries the wrong seq_hi and completely breaks ingress since all future packets fail ICV.
This was verified on b2b ConnectX NICs, with an 'iperf3 -P 2' test over a pair of SAs over a bond device in active-backup mode. After ~10s of traffic at ~10 Gbps, replay_esn->seq_hi was ~2.5M due to the two streams sharing the ESN state.
Forcing a bond failover on both sides breaks traffic permanently.
Fix this by dropping packets up to 2^31 before the replay window for crypto offload, since the SW seq_hi guess cannot be validated. Packets up to 2^31 ahead are accepted as new, same as old code. A burst loss of more than 2^31 packets now stalls the SA (previously up to 2^32-wsize).
SW crypto is unaffected.
--- net/xfrm/xfrm_replay.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
net/xfrm/xfrm_replay.c +13 -1
@@ -451,6 +451,7 @@ static int xfrm_replay_overflow_esn(struct xfrm_state *x, struct sk_buff *skb)static int xfrm_replay_check_esn (struct xfrm_state *x,struct sk_buff *skb,__be32 net_seq) { +struct xfrm_offload *xo =xfrm_offload (skb);unsigned int bitnr, nr;u32 diff;struct xfrm_replay_state_esn *replay_esn = x->replay_esn;
@@ -469,7 +470,18 @@ static int xfrm_replay_check_esn(struct xfrm_state *x, diff = top - seq; -if (likely (top >= wsize -1 )) { +if (xo && (xo->flags &CRYPTO_DONE )) { +/* The ICV was already verified by HW with its own seq_hi, +* so the seq_hi guessed by xfrm_replay_seqhi() can't +* be validated in SW. +* +* Treat seq up to 2^31 ahead of top as new, everything else as +* behind: in-window ones go through the bitmap, the rest get +* dropped. +*/ +if (likely (diff >=BIT (31 ))) +return 0 ; + }else if (likely (top >= wsize -1 )) {/* A. same subspace */ if (likely (seq > top) || seq < bottom)return 0 ;
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 09/22] xfrm: replay: Fix late packet handling with ESN crypto offload
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: 1 · Medium: 0 · 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).
- [High] The fix is incomplete.
- [Low] The commit message understates the impact of the bug being fixed.
--
xfrm: replay: Fix late packet handling with ESN crypto offload
This changes xfrm_replay_check_esn() so that, for crypto offloaded packets (CRYPTO_DONE), only sequence numbers up to 2^31 ahead of the window top are treated as new. Everything else is treated as behind and either goes through the bitmap or is dropped. The aim is to stop the SW seq_hi from being bumped by late packets that the HW has already authenticated with a different seq_hi.
Quoted 7 lines
But on crypto offload, the ICV check already happened in HW and isn't repeated.
xfrm_replay_advance_esn()then incrementsreplay_esn->seq_hi.The problem becomes visible when the HW state is renewed (e.g. bond failover or mlx5 mid-sequence ESN state update). The newly offloaded SA carries the wrong
seq_hiand completely breaks ingress since all future packets fail ICV.
[Severity: Low]
Should the commit message also mention the anti-replay impact of the old code?
Before this patch, case A in xfrm_replay_check_esn() returned 0 for any seq < bottom:
if (likely(seq > top) || seq < bottom) return 0;
For a CRYPTO_DONE skb, xfrm_input() skips x->type->input(). It also skips the recheck:
if (!crypto_done && xfrm_replay_recheck(x, skb, seq)) {
...
xfrm_replay_advance(x, seq);That leaves xfrm_replay_check() as the only anti-replay barrier on the offload path. A genuine, HW-authenticated packet older than the replay window was therefore accepted and delivered a second time.
xfrm_replay_advance_esn() then saw wrap > 0. It cleared the bitmap, set replay_esn->seq to the old low value and did replay_esn->seq_hi++. That moves the window backwards. Packets already received between that value and the previous top could then be replayed as well.
The description only covers the seq_hi drift and the breakage after re-offload. Could it also say that out-of-window replays were being accepted on ESN crypto offload SAs, to help stable and CVE triage?
Quoted 4 lines
net/xfrm/xfrm_replay.c +0
-0
[ ... ]
Quoted 6 lines
net/xfrm/xfrm_replay.c +1
-1@@ -469,7 +470,18 @@ static int xfrm_replay_check_esn(struct xfrm_state *x, diff = top - seq; -if (likely (top >= wsize -1 )) { +if (xo && (xo->flags &CRYPTO_DONE )) {
net/xfrm/xfrm_replay.c static int xfrm_replay_check_esn(struct xfrm_state *x, · line 483
Quoted 10 lines
net/xfrm/xfrm_replay.c +10
-0+/* The ICV was already verified by HW with its own seq_hi, +* so the seq_hi guessed by xfrm_replay_seqhi() can't +* be validated in SW. +* +* Treat seq up to 2^31 ahead of top as new, everything else as +* behind: in-window ones go through the bitmap, the rest get +* dropped. +*/ +if (likely (diff >=BIT (31 ))) +return 0 ;
[Severity: High]
Can this still advance the SW ESN state on a seq_hi guess that differs from the seq_hi the HW used for the ICV?
When diff >= 2^31 and seq is numerically below top (a wrapped "ahead" packet), this branch returns 0 without checking the bitmap. For crypto_done packets, xfrm_input() then goes straight to the advance:
xfrm_input()
xfrm_replay_check()
xfrm_replay_check_esn() /* diff >= BIT(31) -> return 0 */
xfrm_replay_advance()
xfrm_replay_advance_esn()
xfrm_replay_seqhi() /* seq < bottom -> seq_hi + 1 */
replay_esn->seq = seq;
replay_esn->seq_hi++;The 2^31 boundary here is measured from top, but mlx5 picks its epoch from the window bottom. mlx5e_ipsec_update_esn_state() computes esn_msb from xfrm_replay_seqhi(x, htonl(seq_bottom)). It flips overlap based on seq_bottom versus 2^31:
if (unlikely(overlap && seq_bottom < MLX5E_IPSEC_ESN_SCOPE_MID)) {
sa_entry->esn_state.overlap = 0;
return true;
} else if (unlikely(!overlap &&
(seq_bottom >= MLX5E_IPSEC_ESN_SCOPE_MID))) {That update is also deferred to a work item bymlx5e_xfrm_advance_esn_state().
So there seem to be two windows where HW and SW disagree:
- Case 1: top is in [2^31 + 1, 2^31 + wsize - 2], or later while the overlap 0->1 work is still pending. The HW authenticates seq in [1, top - 2^31] with seq_hi H, but this branch accepts them as new under H + 1.
- Case 2: right after the low seq wraps to a small top, while the overlap 1->0 work is still pending. The HW still uses H for seq >= 2^31, but this branch accepts seq in [2^31, top + 2^31] as new under H + 1.
ESP sequence numbers are sent in cleartext, so an on-path attacker could time a replay of a captured epoch H packet into one of these windows. The packet passes the HW ICV check because it is genuine, and this branch then lets it be delivered again.
After that the SW state is (H + 1, s). In the first case, the sender's legitimate (H, 2^31 + k) packets then give diff < 2^31 and diff >= wsize. They are dropped as behind, which would stall the SA for roughly 2^31 packets.
The wrong seq_hi also reaches the driver through xfrm_dev_state_advance_esn(). A later re-offload would carry it, which is the failure the commit message describes.
Could the SW use the seq_hi the HW actually verified instead? Another option is to never let an offloaded packet bump seq_hi based only on the SW guess.
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerRe: [PATCH 09/22] xfrm: replay: Fix late packet handling with ESN crypto offload
Ccing the author of the patch.
Quoted 109 lines · On Wed, Dec 02, 2026 at 01:12:27PM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.
Critical: 0 · High: 1 · Medium: 0 · 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).
- [High] The fix is incomplete.
- [Low] The commit message understates the impact of the bug being fixed.--
xfrm: replay: Fix late packet handling with ESN crypto offload
This changes
xfrm_replay_check_esn()so that, for crypto offloaded packets (CRYPTO_DONE), only sequence numbers up to 2^31 ahead of the window top are treated as new. Everything else is treated as behind and either goes through the bitmap or is dropped. The aim is to stop the SWseq_hifrom being bumped by late packets that the HW has already authenticated with a differentseq_hi.Quoted 7 lines
But on crypto offload, the ICV check already happened in HW and isn't repeated.
xfrm_replay_advance_esn()then incrementsreplay_esn->seq_hi.The problem becomes visible when the HW state is renewed (e.g. bond failover or mlx5 mid-sequence ESN state update). The newly offloaded SA carries the wrong
seq_hiand completely breaks ingress since all future packets fail ICV.[Severity: Low]
Should the commit message also mention the anti-replay impact of the old code?Before this patch, case A in
xfrm_replay_check_esn()returned 0 for any seq < bottom:if (likely(seq > top) || seq < bottom) return 0;For a
CRYPTO_DONEskb,xfrm_input()skipsx->type->input(). It also skips the recheck:if (!crypto_done && xfrm_replay_recheck(x, skb, seq)) { ... xfrm_replay_advance(x, seq);That leaves
xfrm_replay_check()as the only anti-replay barrier on the offload path. A genuine, HW-authenticated packet older than the replay window was therefore accepted and delivered a second time.
xfrm_replay_advance_esn()then saw wrap > 0. It cleared the bitmap, setreplay_esn->seqto the old low value and did replay_esn->seq_hi++. That moves the window backwards. Packets already received between that value and the previous top could then be replayed as well.The description only covers the
seq_hidrift and the breakage after re-offload. Could it also say that out-of-window replays were being accepted on ESN crypto offload SAs, to help stable and CVE triage?Quoted 4 lines
net/xfrm/xfrm_replay.c +0
-0[ ... ]
Quoted 6 lines
net/xfrm/xfrm_replay.c +1
-1@@ -469,7 +470,18 @@ static int xfrm_replay_check_esn(struct xfrm_state *x, diff = top - seq; -if (likely (top >= wsize -1 )) { +if (xo && (xo->flags &CRYPTO_DONE )) {net/xfrm/xfrm_replay.c static int xfrm_replay_check_esn(struct xfrm_state *x, · line 483
Quoted 10 lines
net/xfrm/xfrm_replay.c +10
-0+/* The ICV was already verified by HW with its own seq_hi, +* so the seq_hi guessed by xfrm_replay_seqhi() can't +* be validated in SW. +* +* Treat seq up to 2^31 ahead of top as new, everything else as +* behind: in-window ones go through the bitmap, the rest get +* dropped. +*/ +if (likely (diff >=BIT (31 ))) +return 0 ;[Severity: High]
Can this still advance the SW ESN state on aseq_higuess that differs from theseq_hithe HW used for the ICV?When diff >= 2^31 and seq is numerically below top (a wrapped "ahead" packet), this branch returns 0 without checking the bitmap. For
crypto_donepackets,xfrm_input()then goes straight to the advance:
xfrm_input()
xfrm_replay_check()xfrm_replay_check_esn() /* diff >= BIT(31) -> return 0 */ xfrm_replay_advance() xfrm_replay_advance_esn() xfrm_replay_seqhi() /* seq < bottom -> seq_hi + 1 */ replay_esn->seq = seq; replay_esn->seq_hi++;The 2^31 boundary here is measured from top, but mlx5 picks its epoch from the window bottom.
mlx5e_ipsec_update_esn_state()computesesn_msbfromxfrm_replay_seqhi(x, htonl(seq_bottom)). It flips overlap based onseq_bottomversus 2^31:
Quoted 5 lines
if (unlikely(overlap && seq_bottom < MLX5E_IPSEC_ESN_SCOPE_MID)) {
sa_entry->esn_state.overlap = 0;
return true;
} else if (unlikely(!overlap &&
(seq_bottom >= MLX5E_IPSEC_ESN_SCOPE_MID))) {I don't know what the driver is doing here, but the patch fixes a real issue. So this should be handled as a followup.
Quoted 36 lines
That update is also deferred to a work item by
mlx5e_xfrm_advance_esn_state().So there seem to be two windows where HW and SW disagree:
- Case 1: top is in [2^31 + 1, 2^31 + wsize - 2], or later while the overlap 0->1 work is still pending. The HW authenticates seq in [1, top - 2^31] with
seq_hiH, but this branch accepts them as new under H + 1.- Case 2: right after the low seq wraps to a small top, while the overlap 1->0 work is still pending. The HW still uses H for seq >= 2^31, but this branch accepts seq in [2^31, top + 2^31] as new under H + 1.
ESP sequence numbers are sent in cleartext, so an on-path attacker could time a replay of a captured epoch H packet into one of these windows. The packet passes the HW ICV check because it is genuine, and this branch then lets it be delivered again.
After that the SW state is (H + 1, s). In the first case, the sender's legitimate (H, 2^31 + k) packets then give diff < 2^31 and diff >= wsize. They are dropped as behind, which would stall the SA for roughly 2^31 packets.
The wrong
seq_hialso reaches the driver throughxfrm_dev_state_advance_esn(). A later re-offload would carry it, which is the failure the commit message describes.Could the SW use the
seq_hithe HW actually verified instead? Another option is to never let an offloaded packet bumpseq_hibased only on the SW guess.Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerPATCH 10/22 xfrm: fix IPv6 first-fragment protocol decode
In reply to Steffen KlassertFrom: Jérémy Jean <[email protected]>
Commit 7a0207094f1b ("xfrm: policy: replace session decode with flow dissector") replaced XFRM session decoding with the flow dissector. While the old IPv6 decoder kept walking past an IPv6 Fragment extension header, the flow dissector stops unless the caller sets FLOW_DISSECTOR_F_PARSE_1ST_FRAG. For an atomic fragment followed by extension headers, inbound policy lookup can therefore see the header after Fragment instead of the actual upper-layer protocol and miss protocol selectors.
Make the dissector continue through first IPv6 fragments. Keep the port, ICMPv6 and GRE selector fields zero for all fragments, as the old decoder did. This also keeps the result the same when a BPF flow dissector fills ports for a first fragment.
--- net/xfrm/xfrm_policy.c | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-)
net/xfrm/xfrm_policy.c +22 -13
@@ -3484,23 +3484,29 @@ decode_session6(const struct xfrm_flow_keys *flkeys, struct flowi *fl, bool reveif (reverse) { fl6->saddr = flkeys->addrs.ipv6.dst; fl6->daddr = flkeys->addrs.ipv6.src; - fl6->fl6_sport = flkeys->ports.dst; - fl6->fl6_dport = flkeys->ports.src; }else { fl6->saddr = flkeys->addrs.ipv6.src; fl6->daddr = flkeys->addrs.ipv6.dst; - fl6->fl6_sport = flkeys->ports.src; - fl6->fl6_dport = flkeys->ports.dst; } -switch (flkeys->basic.ip_proto) { -case IPPROTO_GRE : - fl6->fl6_gre_key = flkeys->gre.keyid; -break ; -case IPPROTO_ICMPV6 : - fl6->fl6_icmp_type = flkeys->icmp.type; - fl6->fl6_icmp_code = flkeys->icmp.code; -break ; +if (!(flkeys->control.flags &FLOW_DIS_IS_FRAGMENT )) { +if (reverse) { + fl6->fl6_sport = flkeys->ports.dst; + fl6->fl6_dport = flkeys->ports.src; + }else { + fl6->fl6_sport = flkeys->ports.src; + fl6->fl6_dport = flkeys->ports.dst; + } + +switch (flkeys->basic.ip_proto) { +case IPPROTO_GRE : + fl6->fl6_gre_key = flkeys->gre.keyid; +break ; +case IPPROTO_ICMPV6 : + fl6->fl6_icmp_type = flkeys->icmp.type; + fl6->fl6_icmp_code = flkeys->icmp.code; +break ; + } } fl6->flowi6_proto = flkeys->basic.ip_proto;
@@ -3511,10 +3517,13 @@ int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fl unsigned int family, int reverse) {struct xfrm_flow_keys flkeys; +unsigned int flags =FLOW_DISSECTOR_F_STOP_AT_ENCAP ;memset (&flkeys,0 ,sizeof (flkeys)); +if (family ==AF_INET6 ) + flags |=FLOW_DISSECTOR_F_PARSE_1ST_FRAG ;__skb_flow_dissect (net, skb, &xfrm_session_dissector, &flkeys, -NULL ,0 ,0 ,0 ,FLOW_DISSECTOR_F_STOP_AT_ENCAP ); +NULL ,0 ,0 ,0 , flags);switch (family) {case AF_INET :
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 10/22] xfrm: fix IPv6 first-fragment protocol decode
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] The commit message describes the bug and the fix only for inbound policy lookup of IPv6 atomic fragments.
--
xfrm: fix IPv6 first-fragment protocol decode
This patch sets FLOW_DISSECTOR_F_PARSE_1ST_FRAG for IPv6 in __xfrm_decode_session(). With that flag, the flow dissector walks past the Fragment header of a first fragment to reach the real upper-layer protocol. It also stops decode_session6() from filling the port, ICMPv6 and GRE selector fields when the packet is a fragment.
Quoted 4 lines
net/xfrm/xfrm_policy.c +0
-0
[ ... ]
net/xfrm/xfrm_policy.c int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fl · line 3524
Quoted 9 lines
net/xfrm/xfrm_policy.c +3
-0@@ -3511,10 +3517,13 @@ int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fl unsigned int family, int reverse) {struct xfrm_flow_keys flkeys; +unsigned int flags =FLOW_DISSECTOR_F_STOP_AT_ENCAP ;memset (&flkeys,0 ,sizeof (flkeys)); +if (family ==AF_INET6 ) + flags |=FLOW_DISSECTOR_F_PARSE_1ST_FRAG ;
[Severity: Low]
This isn't a bug, but should the commit message describe the full impact of this change? The message says:
For an atomic fragment followed by extension headers, inbound policy lookup can therefore see the header after Fragment instead of the actual upper-layer protocol and miss protocol selectors.
Every AF_INET6 caller of __xfrm_decode_session() now gets the new flag, not only the inbound path. In __skb_flow_dissect(), the NEXTHDR_FRAGMENT case continues for any first fragment and does not check the M bit:
net/core/flow_dissector.c:__skb_flow_dissect() {
...
if (!(fh->frag_off & htons(IP6_OFFSET))) {
key_control->flags |= FLOW_DIS_FIRST_FRAG;
if (flags & FLOW_DISSECTOR_F_PARSE_1ST_FRAG) {
fdret = FLOW_DISSECT_RET_IPPROTO_AGAIN;
...
}Consider a router without conntrack defrag that forwards a non-atomic first fragment (offset 0, M=1) with a Destination Options header after the Fragment header. That packet now reaches both policy lookups through this decoder:
ip6_forward()
xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)
__xfrm_decode_session()
xfrm6_route_forward(skb)
__xfrm_decode_session()Before this patch, ip_proto came out as the Fragment header's nexthdr (60 for DSTOPTS), so FWD or OUT policies with a protocol selector did not match. After this patch they see the real upper-layer protocol.
Since this is Cc: stable, could the message also say that FWD and outbound IPsec policy selection for forwarded non-atomic first fragments changes too?
Quoted 6 lines
net/xfrm/xfrm_policy.c +1
-1__skb_flow_dissect (net, skb, &xfrm_session_dissector, &flkeys, -NULL ,0 ,0 ,0 ,FLOW_DISSECTOR_F_STOP_AT_ENCAP ); +NULL ,0 ,0 ,0 , flags);switch (family) {case AF_INET :
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerPATCH 11/22 xfrm: fix selector matching for IPv6 atomic fragments
In reply to Steffen KlassertFrom: Jérémy Jean <[email protected]>
IPv6 atomic fragments contain a complete packet, but XFRM leaves the port, ICMPv6 and GRE selector fields unset. Plaintext can then miss a matching policy.
Have ipv6_find_hdr() mark non-atomic Fragment headers. Restore the fields only when every Fragment header is atomic. Use its offset when the transport header is before skb->data. Read with skb_header_pointer() so decoding does not pull or reallocate the skb.
--- include/net/ipv6.h | 1 + net/ipv6/exthdrs_core.c | 25 +++++++++++++------------ net/xfrm/xfrm_policy.c | 19 ++++++++++++++++++- 3 files changed, 32 insertions(+), 13 deletions(-)
include/net/ipv6.h +1 -0
@@ -1110,6 +1110,7 @@ enum {IP6_FH_F_FRAG = (1 <<0 ),IP6_FH_F_AUTH = (1 <<1 ),IP6_FH_F_SKIP_RH = (1 <<2 ), + IP6_FH_F_NON_ATOMIC = (1 << 3), };/* find specified header and get offset to it */
net/ipv6/exthdrs_core.c +13 -12
@@ -183,7 +183,8 @@ EXPORT_SYMBOL_GPL(ipv6_find_tlv);* isn't NULL. * * if flags is not NULL and it's a fragment, then the frag flag -* IP6_FH_F_FRAG will be set. If it's an AH header, the +* IP6_FH_F_FRAG will be set. IP6_FH_F_NON_ATOMIC will be set for a +* non-atomic Fragment header. If it's an AH header, the * IP6_FH_F_AUTH flag is set and target < 0, then this function will * stop at the AH header. If IP6_FH_F_SKIP_RH flag was passed, then this * function will skip all those routing headers, where segements_left was 0.
@@ -191,23 +192,20 @@ EXPORT_SYMBOL_GPL(ipv6_find_tlv);int ipv6_find_hdr (const struct sk_buff *skb,unsigned int *offset,int target,unsigned short *fragoff,int *flags) { -unsigned int start =skb_network_offset (skb) +sizeof (struct ipv6hdr ); -u8 nexthdr =ipv6_hdr (skb)->nexthdr; +unsigned int start = *offset ?:skb_network_offset (skb); +struct ipv6hdr _ip6, *ip6;int exthdr_cnt =0 ; +u8 nexthdr;bool found;if (fragoff) *fragoff =0 ; -if (*offset) { -struct ipv6hdr _ip6, *ip6; - - ip6 =skb_header_pointer (skb, *offset,sizeof (_ip6), &_ip6); -if (!ip6 || (ip6->version !=6 )) -return -EBADMSG ; - start = *offset +sizeof (struct ipv6hdr ); - nexthdr = ip6->nexthdr; - } + ip6 =skb_header_pointer (skb, start,sizeof (_ip6), &_ip6); +if (!ip6 || (*offset && ip6->version !=6 )) +return -EBADMSG ; + nexthdr = ip6->nexthdr; + start +=sizeof (struct ipv6hdr ); do { struct ipv6_opt_hdr _hdr, *hp;
@@ -254,6 +252,9 @@ int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset,if (!fp)return -EBADMSG ; +if (flags && (*fp &htons (IP6_OFFSET |IP6_MF ))) + *flags |=IP6_FH_F_NON_ATOMIC ; + _frag_off =ntohs (*fp) & ~0x7 ;if (_frag_off) { if (target < 0 &&
net/xfrm/xfrm_policy.c +18 -1
@@ -3530,9 +3530,26 @@ int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fldecode_session4 (&flkeys, fl, reverse);break ;#if IS_ENABLED (CONFIG_IPV6 ) -case AF_INET6 : +case AF_INET6 : { +unsigned int offset =0 ; +int thoff = flkeys.control.thoff; +int fh_flags =0 ; + +if ((flkeys.control.flags &FLOW_DIS_IS_FRAGMENT ) && +ipv6_find_hdr (skb, &offset,-1 ,NULL , &fh_flags) >=0 && + (fh_flags &IP6_FH_F_FRAG ) && + !(fh_flags &IP6_FH_F_NON_ATOMIC )) { +if (offset >U16_MAX ) + thoff = (int )offset; + flkeys.control.flags &= ~FLOW_DIS_IS_FRAGMENT ; + flkeys.ports.ports =skb_flow_get_ports (skb, + thoff, + flkeys.basic.ip_proto, +NULL ,0 ); + }decode_session6 (&flkeys, fl, reverse);break ; + }#endif default :return -EAFNOSUPPORT ;
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 11/22] xfrm: fix selector matching for IPv6 atomic fragments
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: 1 · Medium: 0 · 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).
- [High] The fix leaves the same IPv6 policy miss open for some atomic fragments.
- [Low] The patch rewrites the default-offset (*offset == 0) path of the exported helper ipv6_find_hdr() in net/ipv6/exthdrs_core.c, and the…
--
xfrm: fix selector matching for IPv6 atomic fragments
This patch makes ipv6_find_hdr() set a new IP6_FH_F_NON_ATOMIC flag when it finds a Fragment header with a non-zero offset or MF set. In __xfrm_decode_session(), IPv6 packets that the flow dissector flagged as fragments are parsed again with ipv6_find_hdr(). If every Fragment header is atomic, FLOW_DIS_IS_FRAGMENT is cleared and the ports are restored, so decode_session6() fills in the selector fields.
Quoted 4 lines
net/ipv6/exthdrs_core.c +0
-0
[ ... ]
Quoted 19 lines
net/ipv6/exthdrs_core.c +3
-6@@ -192,23 +193,20 @@ EXPORT_SYMBOL_GPL(ipv6_find_tlv);int ipv6_find_hdr (const struct sk_buff *skb,unsigned int *offset,int target,unsigned short *fragoff,int *flags) { -unsigned int start =skb_network_offset (skb) +sizeof (struct ipv6hdr ); -u8 nexthdr =ipv6_hdr (skb)->nexthdr; +unsigned int start = *offset ?:skb_network_offset (skb); +struct ipv6hdr _ip6, *ip6;int exthdr_cnt =0 ; +u8 nexthdr;bool found;if (fragoff) *fragoff =0 ; -if (*offset) { -struct ipv6hdr _ip6, *ip6; - - ip6 =skb_header_pointer (skb, *offset,sizeof (_ip6), &_ip6);
net/ipv6/exthdrs_core.c EXPORT_SYMBOL_GPL(ipv6_find_tlv); · line 209
Quoted 10 lines
net/ipv6/exthdrs_core.c +5
-5-if (!ip6 || (ip6->version !=6 )) -return -EBADMSG ; - start = *offset +sizeof (struct ipv6hdr ); - nexthdr = ip6->nexthdr; - } + ip6 =skb_header_pointer (skb, start,sizeof (_ip6), &_ip6); +if (!ip6 || (*offset && ip6->version !=6 )) +return -EBADMSG ; + nexthdr = ip6->nexthdr; + start +=sizeof (struct ipv6hdr );
[Severity: Low]
This isn't a bug, but this hunk changes the default *offset == 0 path of the exported ipv6_find_hdr(). That affects all of its callers (netfilter ip6t/nft, IPVS, OVS, act_ct, act_pedit, seg6, BPF and several drivers), and the commit message doesn't mention it.
The old code read ipv6_hdr(skb)->nexthdr directly. The new code goes through skb_header_pointer() and can now return -EBADMSG on this path when the packet is shorter than skb_network_offset(skb) plus sizeof(struct ipv6hdr).
The commit message says:
Read with skb_header_pointer() so decoding does not pull or reallocate the skb.
The old ipv6_find_hdr() did not pull or reallocate the skb either, so this sentence doesn't seem to describe this change.
Since this is tagged for stable, could the commit message mention the change to the shared helper?
[ ... ]
Quoted 8 lines
net/xfrm/xfrm_policy.c +0
-0@@ -3530,9 +3530,26 @@ int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fldecode_session4 (&flkeys, fl, reverse);break ;#if IS_ENABLED (CONFIG_IPV6 )
net/xfrm/xfrm_policy.c int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fl · line 3541
Quoted 10 lines
net/xfrm/xfrm_policy.c +9
-1-case AF_INET6 : +case AF_INET6 : { +unsigned int offset =0 ; +int thoff = flkeys.control.thoff; +int fh_flags =0 ; + +if ((flkeys.control.flags &FLOW_DIS_IS_FRAGMENT ) && +ipv6_find_hdr (skb, &offset,-1 ,NULL , &fh_flags) >=0 && + (fh_flags &IP6_FH_F_FRAG ) && + !(fh_flags &IP6_FH_F_NON_ATOMIC )) {
[Severity: High]
Can atomic fragments with many extension headers still miss a policy here?
The flow dissector walks up to MAX_FLOW_DISSECT_HDRS (15) headers when it sets FLOW_DIS_IS_FRAGMENT, ip_proto and thoff. ipv6_find_hdr() gives up earlier, after IP6_MAX_EXT_HDRS_CNT (12):
net/ipv6/exthdrs_core.c:ipv6_find_hdr() {
...
if (unlikely(exthdr_cnt++ >= IP6_MAX_EXT_HDRS_CNT))
return -EBADMSG;
...
}Take a packet with 13 to 15 extension headers in which every Fragment header is atomic, followed by UDP, TCP, ICMPv6 or GRE. The dissector reaches L4, but ipv6_find_hdr() returns -EBADMSG. The >= 0 test fails, FLOW_DIS_IS_FRAGMENT stays set, and decode_session6() drops the ports, the ICMPv6 type/code and the GRE key.
Local delivery seems to be covered, because ip6_protocol_deliver_rcu() drops packets with more than IP6_MAX_EXT_HDRS_CNT extension headers before the transport-level policy check. The forwarding path has no such limit:
ip6_forward()
xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)
__xfrm_decode_session()
__skb_flow_dissect() <- reaches L4, sets FLOW_DIS_IS_FRAGMENT
ipv6_find_hdr() <- returns -EBADMSG
decode_session6() <- ports and type/code left zero
The xfrm6_route_forward() call in ip6_forward() takes the same route.
Could a remote sender then get plaintext past a port-specific or ICMPv6-type-specific FWD policy on a gateway? That is the "Plaintext can then miss a matching policy" case the commit message describes as fixed.
The same packet without the Fragment header is decoded correctly, so this only affects the atomic-fragment form the patch targets. None of ipv6_find_hdr(), the flow dissector or this hunk appears to change after this commit.
Would it be more robust to record the non-atomic fragment state during the walk the flow dissector already does, instead of parsing again with a helper that has a different header limit?
Quoted 14 lines
net/xfrm/xfrm_policy.c +9
-0+if (offset >U16_MAX ) + thoff = (int )offset; + flkeys.control.flags &= ~FLOW_DIS_IS_FRAGMENT ; + flkeys.ports.ports =skb_flow_get_ports (skb, + thoff, + flkeys.basic.ip_proto, + NULL, 0); + }decode_session6 (&flkeys, fl, reverse);break ; + }#endif default :return -EAFNOSUPPORT ;
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerRe: [PATCH 11/22] xfrm: fix selector matching for IPv6 atomic fragments
Ccing the author of the patch.
Quoted 122 lines · On Wed, Dec 02, 2026 at 01:12:29PM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.
Critical: 0 · High: 1 · Medium: 0 · 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).
- [High] The fix leaves the same IPv6 policy miss open for some atomic fragments.
- [Low] The patch rewrites the default-offset (*offset == 0) path of the exported helperipv6_find_hdr()innet/ipv6/exthdrs_core.c, and the…--
xfrm: fix selector matching for IPv6 atomic fragments
This patch makes
ipv6_find_hdr()set a newIP6_FH_F_NON_ATOMICflag when it finds a Fragment header with a non-zero offset or MF set. In__xfrm_decode_session(), IPv6 packets that the flow dissector flagged as fragments are parsed again withipv6_find_hdr(). If every Fragment header is atomic,FLOW_DIS_IS_FRAGMENTis cleared and the ports are restored, sodecode_session6()fills in the selector fields.Quoted 4 lines
net/ipv6/exthdrs_core.c +0
-0[ ... ]
Quoted 19 lines
net/ipv6/exthdrs_core.c +3
-6@@ -192,23 +193,20 @@ EXPORT_SYMBOL_GPL(ipv6_find_tlv);int ipv6_find_hdr (const struct sk_buff *skb,unsigned int *offset,int target,unsigned short *fragoff,int *flags) { -unsigned int start =skb_network_offset (skb) +sizeof (struct ipv6hdr ); -u8 nexthdr =ipv6_hdr (skb)->nexthdr; +unsigned int start = *offset ?:skb_network_offset (skb); +struct ipv6hdr _ip6, *ip6;int exthdr_cnt =0 ; +u8 nexthdr;bool found;if (fragoff) *fragoff =0 ; -if (*offset) { -struct ipv6hdr _ip6, *ip6; - - ip6 =skb_header_pointer (skb, *offset,sizeof (_ip6), &_ip6);net/ipv6/exthdrs_core.c EXPORT_SYMBOL_GPL(ipv6_find_tlv); · line 209
Quoted 10 lines
net/ipv6/exthdrs_core.c +5
-5-if (!ip6 || (ip6->version !=6 )) -return -EBADMSG ; - start = *offset +sizeof (struct ipv6hdr ); - nexthdr = ip6->nexthdr; - } + ip6 =skb_header_pointer (skb, start,sizeof (_ip6), &_ip6); +if (!ip6 || (*offset && ip6->version !=6 )) +return -EBADMSG ; + nexthdr = ip6->nexthdr; + start +=sizeof (struct ipv6hdr );[Severity: Low]
This isn't a bug, but this hunk changes the default *offset == 0 path of the exportedipv6_find_hdr(). That affects all of its callers (netfilter ip6t/nft, IPVS, OVS,act_ct,act_pedit, seg6, BPF and several drivers), and the commit message doesn't mention it.The old code read ipv6_hdr(skb)->nexthdr directly. The new code goes through
skb_header_pointer()and can now return-EBADMSGon this path when the packet is shorter thanskb_network_offset(skb)plus sizeof(struct ipv6hdr).The commit message says:
Read with
skb_header_pointer()so decoding does not pull or reallocate the skb.The old
ipv6_find_hdr()did not pull or reallocate the skb either, so this sentence doesn't seem to describe this change.Since this is tagged for stable, could the commit message mention the change to the shared helper?
[ ... ]
Quoted 8 lines
net/xfrm/xfrm_policy.c +0
-0@@ -3530,9 +3530,26 @@ int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fldecode_session4 (&flkeys, fl, reverse);break ;#if IS_ENABLED (CONFIG_IPV6 )net/xfrm/xfrm_policy.c int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fl · line 3541
Quoted 10 lines
net/xfrm/xfrm_policy.c +9
-1-case AF_INET6 : +case AF_INET6 : { +unsigned int offset =0 ; +int thoff = flkeys.control.thoff; +int fh_flags =0 ; + +if ((flkeys.control.flags &FLOW_DIS_IS_FRAGMENT ) && +ipv6_find_hdr (skb, &offset,-1 ,NULL , &fh_flags) >=0 && + (fh_flags &IP6_FH_F_FRAG ) && + !(fh_flags &IP6_FH_F_NON_ATOMIC )) {[Severity: High]
Can atomic fragments with many extension headers still miss a policy here?The flow dissector walks up to
MAX_FLOW_DISSECT_HDRS(15) headers when it setsFLOW_DIS_IS_FRAGMENT,ip_protoand thoff.ipv6_find_hdr()gives up earlier, afterIP6_MAX_EXT_HDRS_CNT(12):net/ipv6/exthdrs_core.c:ipv6_find_hdr() { ... if (unlikely(exthdr_cnt++ >= IP6_MAX_EXT_HDRS_CNT)) return -EBADMSG; ... }
Quoted 5 lines
Take a packet with 13 to 15 extension headers in which every Fragment header is atomic, followed by UDP, TCP, ICMPv6 or GRE. The dissector reaches L4, but
ipv6_find_hdr()returns-EBADMSG. The >= 0 test fails,FLOW_DIS_IS_FRAGMENTstays set, anddecode_session6()drops the ports, the ICMPv6 type/code and the GRE key.
Might happen because IPv6 does not limit the number of extension headers, but this is a bit artificial. A packet with 13 to 15 extension headers has other problems as well. Can be fixed as a followup.
Quoted 45 lines
Local delivery seems to be covered, because
ip6_protocol_deliver_rcu()drops packets with more thanIP6_MAX_EXT_HDRS_CNTextension headers before the transport-level policy check. The forwarding path has no such limit:
ip6_forward()
xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)
__xfrm_decode_session()
__skb_flow_dissect()<- reaches L4, setsFLOW_DIS_IS_FRAGMENT
ipv6_find_hdr()<- returns-EBADMSG
decode_session6()<- ports and type/code left zeroThe
xfrm6_route_forward()call inip6_forward()takes the same route.Could a remote sender then get plaintext past a port-specific or ICMPv6-type-specific FWD policy on a gateway? That is the "Plaintext can then miss a matching policy" case the commit message describes as fixed.
The same packet without the Fragment header is decoded correctly, so this only affects the atomic-fragment form the patch targets. None of
ipv6_find_hdr(), the flow dissector or this hunk appears to change after this commit.Would it be more robust to record the non-atomic fragment state during the walk the flow dissector already does, instead of parsing again with a helper that has a different header limit?
Quoted 14 lines
net/xfrm/xfrm_policy.c +9
-0+if (offset >U16_MAX ) + thoff = (int )offset; + flkeys.control.flags &= ~FLOW_DIS_IS_FRAGMENT ; + flkeys.ports.ports =skb_flow_get_ports (skb, + thoff, + flkeys.basic.ip_proto, + NULL, 0); + }decode_session6 (&flkeys, fl, reverse);break ; + }#endif default :return -EAFNOSUPPORT ;Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerPATCH 12/22 xfrm: espintcp: read the socket error queue for MSG_ERRQUEUE
In reply to Steffen KlassertFrom: "Baek Kyu, Kim" <[email protected]>
An ESP-in-TCP socket can have a TX timestamp queued and report POLLERR, but recvmsg(MSG_ERRQUEUE) returns EAGAIN because espintcp_recvmsg() reads the IKE queue instead. If an IKE message is pending, the same call consumes that message as though it were an error-queue result.
Handle MSG_ERRQUEUE through inet_recv_error() before reading the IKE queue. This exposes queued error metadata and leaves IKE messages for normal receive calls.
--- net/xfrm/espintcp.c | 3 +++ 1 file changed, 3 insertions(+)
net/xfrm/espintcp.c +3 -0
@@ -148,6 +148,9 @@ static int espintcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,int copied;int off =0 ; +if (unlikely (flags &MSG_ERRQUEUE )) +return inet_recv_error (sk, msg, len); + skb =__skb_recv_datagram (sk, &ctx->ike_queue, flags, &off, &err);if (!skb) {if (err == -EAGAIN && sk->sk_shutdown &RCV_SHUTDOWN )
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 13/22 xfrm: iptfs: force a dst reference before queueing an skb
In reply to Steffen KlassertFrom: Nguyen Ngoc Thang <[email protected]>
iptfs_output_collect() is the dst->output hook and runs under the caller's RCU read lock. It queues the skb and sends it later from the iptfs hrtimer. The skb may still carry a noref dst, e.g. one set by __ip_queue_xmit() via skb_dst_set_noref(). Once the RCU section ends, nothing keeps that dst alive.
When the timer fires, xfrm_output_one() calls skb_dst_force() outside any RCU section:
WARNING: include/net/dst.h:326 at xfrm_output_resume+0x41d9/0x64e0 Call Trace: xfrm_output_one net/xfrm/xfrm_output.c:549 [inline] xfrm_output_resume+0x41d9/0x64e0 net/xfrm/xfrm_output.c:597 iptfs_output_queued net/xfrm/xfrm_iptfs.c:2325 [inline] iptfs_delay_timer+0x3803/0x4310 net/xfrm/xfrm_iptfs.c:2362 __run_hrtimer kernel/time/hrtimer.c [inline] __hrtimer_run_queues+0x3bc/0xa10 kernel/time/hrtimer.c hrtimer_run_softirq+0x1e3/0x2e0 kernel/time/hrtimer.c:2153 handle_softirqs+0x265/0x8d0 kernel/softirq.c:669
The warning also means the queued skb may point to a dst that has already been freed.
Take a reference with skb_dst_force() while still under RCU, as other deferred xmit paths do, and drop the skb if its dst is already gone.
--- net/xfrm/xfrm_iptfs.c | 7 +++++++ 1 file changed, 7 insertions(+)
net/xfrm/xfrm_iptfs.c +7 -0
@@ -1914,6 +1914,13 @@ static int iptfs_output_collect(struct net *net, struct sock *sk, struct sk_buffcontinue ; } +/* The queued skb outlives our RCU section, so pin its dst. */ +if (!skb_dst_force (skb)) { +XFRM_INC_STATS (net,LINUX_MIB_XFRMOUTERROR ); +kfree_skb (skb); +continue ; + } +/* Enqueue to send in tunnel */ ok =iptfs_enqueue (xtfs, skb);if (!ok)
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 13/22] xfrm: iptfs: force a dst reference before queueing an skb
TL;DR: Commit message only: the claim that iptfs_output_collect() always runs under the caller's RCU read lock may be inaccurate, since the udp_sendmsg() path has no RCU lock. The code change itself…
Quoted 1 line
xfrm: iptfs: force a dst reference before queueing an skb
TL;DR: Commit message only: the claim that iptfs_output_collect() always runs under the caller's RCU read lock may be inaccurate, since the udp_sendmsg() path has no RCU lock. The code change itself looks fine.
Quoted 5 lines
iptfs_output_collect()is thedst->outputhook and runs under the caller's RCU read lock. It queues the skb and sends it later from the iptfs hrtimer. The skb may still carry a noref dst, e.g. one set by__ip_queue_xmit()viaskb_dst_set_noref(). Once the RCU section ends, nothing keeps that dst alive.
This isn't a bug, but is "runs under the caller's RCU read lock" accurate for every caller?
The udp_sendmsg() -> udp_send_skb() -> ip_send_skb() -> ip_local_out() -> dst_output() path reaches iptfs_output_collect() in process context without rcu_read_lock(), although the dst there is already refcounted so skb_dst_force() does nothing.
Would it be more precise to say that callers that attach a noref dst hold an RCU read lock?
Quoted 3 lines
net/xfrm/xfrm_iptfs.c +0
-0
[ ... ]
Quoted 4 lines
net/xfrm/xfrm_iptfs.c +0
-0@@ -1914,6 +1914,13 @@ static int iptfs_output_collect(struct net *net, struct sock *sk, struct sk_buffcontinue ; }
net/xfrm/xfrm_iptfs.c static int iptfs_output_collect(struct net *net, struct sock *sk, struct sk_buff · line 1926
Quoted 10 lines
net/xfrm/xfrm_iptfs.c +7
-0+/* The queued skb outlives our RCU section, so pin its dst. */ +if (!skb_dst_force (skb)) { +XFRM_INC_STATS (net,LINUX_MIB_XFRMOUTERROR ); +kfree_skb (skb); +continue ; + } +/* Enqueue to send in tunnel */ ok =iptfs_enqueue (xtfs, skb);if (!ok)
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/46652847109
Steffen Klassert
maintainerPATCH 14/22 xfrm: espintcp: select receive path by skb protocol
In reply to Steffen KlassertFrom: Zihan Xi <[email protected]>
An IPv6 socket can accept an IPv4 connection through a v4-mapped address. Such a socket still receives IPv4 skbs, but espintcp selected the XFRM receive path from the socket family.
Use the skb protocol when selecting the receive path so IPv4 packets are not passed to the IPv6 XFRM parser.
--- net/xfrm/espintcp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/xfrm/espintcp.c +1 -1
@@ -48,7 +48,7 @@ static void handle_esp(struct sk_buff *skb, struct sock *sk) }local_bh_disable ();#if IS_ENABLED (CONFIG_IPV6 ) -if (sk->sk_family ==AF_INET6 ) +if (skb->protocol ==htons (ETH_P_IPV6 ))xfrm6_rcv_encap (skb,IPPROTO_ESP ,0 ,TCP_ENCAP_ESPINTCP ); else#endif
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 15/22 net: xfrm: interface: restore dst_orig on every xfrm interface
In reply to Steffen KlassertFrom: Jamal Hadi Salim <[email protected]>
Found while auditing the xfrm metadata consumers of a steered packet. One of them is an xfrm interface, which restores the original route before the xfrm lookup; the swap warned on the metadata dst still installed in the skb, and only the collect_md arm restored the route at all.
The issue:
An xfrm interface takes the if_id and the underlying device either from its configuration or, in collect_md mode, from the xfrm metadata on the skb. When that metadata also carries the route the packet arrived through, xfrmi_xmit2() puts the route back on the skb, because the xfrm lookup takes the address family from it. skb_dst_set() expects the dst slot to be empty for a reference counted dst and warns when it is not, so the route landed over a metadata dst that was still there; a kernel built with CONFIG_DEBUG_NET=y panics on the first packet that takes this path when panic_on_warn is set.
Two more defects sit in the same place. An interface with a configured if_id never restores the route: it takes the metadata dst as it is, whose address family is AF_UNSPEC, so the lookup finds no policy and the packet is dropped as a link failure instead of being transformed. And the restore moved the route out of the metadata dst, which a clone of the skb shares, so the clone that reached the interface first left the original packet with nothing to restore.
The same slot overwrite is in the unstable helper a tc-bpf program uses to attach that metadata: bpf_skb_set_xfrm_info() records the route as dst_orig and installs a per-cpu metadata dst over it. The per-cpu dst is shared by every invocation of the program, so the restore cannot keep anything in it.
The Fix:
Restore dst_orig in both arms of xfrmi_xmit2(), taking a reference with dst_clone() so the metadata dst keeps its own, and empty the counted slot with skb_dst_drop() before the route is installed. The helper allocates a metadata dst per skb instead of a per-cpu one, so the route it records belongs to that skb and is released with it; the per-cpu allocation is no longer used and goes away.
Conditions to recreate the bug:
A tc-bpf program that records the route as dst_orig with bpf_skb_set_xfrm_info() is self-contained: the overwrite is in the helper, so the first packet that calls it panics inside bpf_skb_set_xfrm_info() on a CONFIG_DEBUG_NET=y build with panic_on_warn=1.
An interface with a configured if_id shows its own defect without any other patch: it drops the packet as a link failure without consulting the outbound policy. And a clone made after the metadata was attached consumes the route before the original packet arrives.
--- include/net/xfrm.h | 2 -- net/core/filter.c | 8 -------- net/xfrm/xfrm_interface_bpf.c | 19 ++++++++----------- net/xfrm/xfrm_interface_core.c | 22 ++++++++++++---------- 4 files changed, 20 insertions(+), 31 deletions(-)
include/net/xfrm.h +0 -2
@@ -2370,8 +2370,6 @@ static inline bool xfrm6_local_dontfrag(const struct sock *sk)#if (IS_BUILTIN (CONFIG_XFRM_INTERFACE ) &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF )) || \ (IS_MODULE (CONFIG_XFRM_INTERFACE ) &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF_MODULES )) -extern struct metadata_dst __percpu *xfrm_bpf_md_dst; -int register_xfrm_interface_bpf (void );#else
net/core/filter.c +0 -8
@@ -6271,14 +6271,6 @@ static const struct bpf_func_proto bpf_bind_proto = {#ifdef CONFIG_XFRM -#if (IS_BUILTIN (CONFIG_XFRM_INTERFACE ) &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF )) || \ - (IS_MODULE (CONFIG_XFRM_INTERFACE ) &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF_MODULES )) - -struct metadata_dst __percpu *xfrm_bpf_md_dst; -EXPORT_SYMBOL_GPL (xfrm_bpf_md_dst); - -#endif - BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index, struct bpf_xfrm_state *, to, u32, size, u64, flags) {
net/xfrm/xfrm_interface_bpf.c +8 -11
@@ -68,16 +68,9 @@ __bpf_kfunc int bpf_skb_set_xfrm_info(struct __sk_buff *skb_ctx, const struct bpif (unlikely (skb_metadata_dst (skb)))return -EINVAL ; -if (!xfrm_bpf_md_dst) { -struct metadata_dst __percpu *tmp; - - tmp =metadata_dst_alloc_percpu (0 ,METADATA_XFRM ,GFP_ATOMIC ); -if (!tmp) -return -ENOMEM ; -if (cmpxchg (&xfrm_bpf_md_dst,NULL , tmp)) -metadata_dst_free_percpu (tmp); - } - md_dst =this_cpu_ptr (xfrm_bpf_md_dst); + md_dst =metadata_dst_alloc (0 ,METADATA_XFRM ,GFP_ATOMIC ); +if (unlikely (!md_dst)) +return -ENOMEM ; info = &md_dst->u.xfrm_info;
@@ -86,7 +79,11 @@ __bpf_kfunc int bpf_skb_set_xfrm_info(struct __sk_buff *skb_ctx, const struct bpskb_dst_force (skb); info->dst_orig =skb_dst (skb); -dst_hold ((struct dst_entry *)md_dst); +/* The metadata dst releases dst_orig when it is freed, so the +* reference the skb held is stolen rather than dropped. The dst +* allocated above is handed to the skb with its single reference. +*/ +skb_dstref_steal (skb);skb_dst_set (skb, (struct dst_entry *)md_dst);return 0 ; }
net/xfrm/xfrm_interface_core.c +12 -10
@@ -423,6 +423,7 @@ static int xfrmi_rcv_cb(struct sk_buff *skb, int err)static int xfrmi_xmit2 (struct sk_buff *skb,struct net_device *dev,struct flowi *fl) { +struct xfrm_md_info *md_info =skb_xfrm_md_info (skb);struct xfrm_if *xi =netdev_priv (dev);struct dst_entry *dst =skb_dst (skb);unsigned int length = skb->len;
@@ -433,25 +434,26 @@ xfrmi_xmit2(struct sk_buff *skb, struct net_device *dev, struct flowi *fl)int mtu;if (xi->p.collect_md) { -struct xfrm_md_info *md_info =skb_xfrm_md_info (skb); -if (unlikely (!md_info))return -EINVAL ; if_id = md_info->if_id; fl->flowi_oif = md_info->link; -if (md_info->dst_orig) { -struct dst_entry *tmp_dst = dst; - - dst = md_info->dst_orig; -skb_dst_set (skb, dst); - md_info->dst_orig =NULL ; -dst_release (tmp_dst); - } }else { if_id = xi->p.if_id; } +/* The metadata dst carries the route the packet is still to be +* transformed for, and the lookup below takes the address family from +* the dst it is given. Put that route back, taking our own reference: +* the metadata dst keeps its own, as a clone of this skb shares it. +*/ +if (md_info && md_info->dst_orig) { + dst =dst_clone (md_info->dst_orig); +skb_dst_drop (skb); +skb_dst_set (skb, dst); + } +dst_hold (dst); dst =xfrm_lookup_with_ifid (xi->net, dst, fl,NULL ,0 , if_id);if (IS_ERR (dst)) {
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 15/22] net: xfrm: interface: restore dst_orig on every xfrm interface
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] The commit message leaves out the most serious production impact of the per-cpu design that this patch removes.
- [Low] The patch carries 'Cc: [email protected]' and 'Fixes:
94151f5aa966' (Dec 2022, v6.2 cycle), but it depends on helpers that…
--
net: xfrm: interface: restore dst_orig on every xfrm interface
This patch makes xfrmi_xmit2() restore md_info->dst_orig for both collect_md interfaces and interfaces with a configured if_id. It takes its own reference with dst_clone() and drops the metadata dst from the skb before installing the route. It also changes bpf_skb_set_xfrm_info() to allocate a metadata dst per skb instead of using the shared per-cpu xfrm_bpf_md_dst, which is removed.
Quoted 4 lines
The same slot overwrite is in the unstable helper a tc-bpf program uses to attach that metadata:
bpf_skb_set_xfrm_info()records the route asdst_origand installs a per-cpu metadata dst over it. The per-cpu dst is shared by every invocation of the program, so the restore cannot keep anything in it.
[Severity: Low]
This isn't a bug in the code. But does this paragraph understate what the per-cpu design did on production kernels built without CONFIG_DEBUG_NET?
In the old bpf_skb_set_xfrm_info(), the skb's counted reference on its route was moved into the shared per-cpu metadata dst and never dropped:
skb_dst_force(skb); info->dst_orig = skb_dst(skb); dst_hold((struct dst_entry *)md_dst); skb_dst_set(skb, (struct dst_entry *)md_dst);
Only one path gave that reference back: the collect_md arm of xfrmi_xmit2(), which cleared md_info->dst_orig and kept the route on the skb.
Any other packet left its route reference in this_cpu_ptr(xfrm_bpf_md_dst). That covers a packet dropped after the helper, a packet redirected to a non-xfrm device, and a packet sent through an xfrm interface with a configured if_id.
The next call to the helper on that CPU overwrote info->dst_orig. The per-cpu object is never freed, so metadata_dst_free() never got to run this:
if (md_dst->type == METADATA_XFRM) dst_release(md_dst->u.xfrm_info.dst_orig);
So it looks like one dst reference leaked for every such packet.
Also, if_id, link and dst_orig lived in a per-cpu object rather than in each packet. A packet held in a qdisc between the helper and xfrmi_xmit2() could then pick up another packet's if_id and route, or find dst_orig already cleared. Is that right?
The fix description only says the route "belongs to that skb and is released with it". Could the message also name the dst reference leak and the mixing of metadata between packets, next to the DEBUG_NET warning and the dropped packet?
Quoted 4 lines
net/xfrm/xfrm_interface_bpf.c +0
-0
[ ... ]
net/xfrm/xfrm_interface_bpf.c __bpf_kfunc int bpf_skb_set_xfrm_info(struct __sk_buff *skb_ctx, const struct bp · line 86
Quoted 10 lines
net/xfrm/xfrm_interface_bpf.c +5
-1@@ -86,7 +79,11 @@ __bpf_kfunc int bpf_skb_set_xfrm_info(struct __sk_buff *skb_ctx, const struct bpskb_dst_force (skb); info->dst_orig =skb_dst (skb); -dst_hold ((struct dst_entry *)md_dst); +/* The metadata dst releases dst_orig when it is freed, so the +* reference the skb held is stolen rather than dropped. The dst +* allocated above is handed to the skb with its single reference. +*/ +skb_dstref_steal (skb);
[Severity: Low]
The patch carries Cc: stable and Fixes: 94151f5aa966, which dates from the v6.2 cycle. skb_dstref_steal() was only added in August 2025, by commit c3f0c02997c7f8.
Will this build on stable branches that contain the Fixes target but not that commit, such as 6.6.y or 6.12.y?
The reproducer in the commit message also looks specific to newer kernels:
so the first packet that calls it panics inside bpf_skb_set_xfrm_info() on a CONFIG_DEBUG_NET=y build with panic_on_warn=1.
That warning is the DEBUG_NET_WARN_ON_ONCE() in skb_dst_check_unset(), which skb_dst_set() calls. It was added by commit a890348adcc993, also in August 2025. On older stable kernels skb_dst_set() overwrites the slot without warning, so the stated reproducer would not trigger there.
Should the commit message name these dependencies, or point to an adapted backport for older trees, for example one that clears skb->_skb_refdst directly?
Quoted 3 lines
net/xfrm/xfrm_interface_bpf.c +0
-0skb_dst_set (skb, (struct dst_entry *)md_dst);return 0 ; }
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerPATCH 16/22 xfrm: iptfs: make room before copying a continuation in reassembly
In reply to Steffen KlassertFrom: Andrii Tereshchenko <[email protected]>
When iptfs_reassem_cont() cannot share a continuation as page frags, it linearizes the in-progress skb and copies the data in with skb_put(), without checking the tailroom. An skb started by iptfs_pskb_add_frags() has little room after linearizing, so a larger continuation panics the kernel in softirq:
skbuff: skb_over_panic: ... len:2884 put:1442 ... end:0x6c0 dev:eth1 kernel BUG at net/core/skbuff.c:215!
Call Trace: <IRQ> skb_put.cold+0x1f/0x1f iptfs_reassem_cont+0x242/0x760 iptfs_input_ordered+0x382/0x3e0 iptfs_input+0x24d/0x630 xfrm_input+0x12a5/0x29f0
After linearizing, grow the head if the rest of the inner packet does not fit, and abandon the reassembly if that fails.
Made with an AI coding assistant, reviewed by the submitter.
--- net/xfrm/xfrm_iptfs.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
net/xfrm/xfrm_iptfs.c +9 -1
@@ -909,7 +909,15 @@ static u32 iptfs_reassem_cont(struct xfrm_iptfs_data *xtfs, u64 seq, iptfs_skb_can_add_frags(newskb, fragwalk, data, copylen)) { iptfs_skb_add_frags(newskb, fragwalk, data, copylen); } else { -if (skb_linearize (newskb)) { +/* A newskb started by iptfs_pskb_add_frags() has little +* tailroom after linearizing. Make room for the rest of +* the inner packet before copying. +*/ +if (skb_linearize (newskb) || + (skb_tailroom (newskb) < ipremain && +pskb_expand_head (newskb,0 , + ipremain -skb_tailroom (newskb), +GFP_ATOMIC | __GFP_NOWARN))) {XFRM_INC_STATS (xs_net (xtfs->x),LINUX_MIB_XFRMINBUFFERERROR ); goto abandon;
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 17/22 xfrm/compat: pass on the translated length of a socket policy
In reply to Steffen KlassertFrom: Andrii Tereshchenko <[email protected]>
xfrm_user_policy() compiles a 32-bit task's translated socket policy with the untranslated length, 4 bytes short, so the policy loses its last template: an ESP-required socket policy then sends in clear text. Have the translator return the translated length.
Made with an AI coding assistant, reviewed by the submitter.
--- include/net/xfrm.h | 2 +- net/xfrm/xfrm_compat.c | 18 ++++++++++++++---- net/xfrm/xfrm_state.c | 2 +- 3 files changed, 16 insertions(+), 6 deletions(-)
include/net/xfrm.h +1 -1
@@ -2331,7 +2331,7 @@ struct xfrm_translator { struct netlink_ext_ack *extack);/* Translate 32-bit user_policy from sockptr */ -int (*xlate_user_policy_sockptr)(u8 **pdata32,int optlen); +int (*xlate_user_policy_sockptr)(u8 **pdata32,int *optlen);struct module *owner; };
net/xfrm/xfrm_compat.c +14 -4
@@ -642,16 +642,25 @@ static struct nlmsghdr *xfrm_user_rcv_msg_compat(const struct nlmsghdr *h32,return h64; } -static int xfrm_user_policy_compat (u8 **pdata32,int optlen) +static int xfrm_user_policy_compat (u8 **pdata32,int *optlen) {struct compat_xfrm_userpolicy_info *p = (void *)*pdata32;u8 *src_templates, *dst_templates;u8 *data64; -if (optlen <sizeof (*p)) +/* The 64-bit layout only adds tail padding, and the templates +* after it are the same in both layouts. +*/ +BUILD_BUG_ON (sizeof (struct xfrm_userpolicy_info ) - +sizeof (struct compat_xfrm_userpolicy_info ) !=4 ); +BUILD_BUG_ON (offsetof(struct xfrm_userpolicy_info , share) != + offsetof(struct compat_xfrm_userpolicy_info , share)); +BUILD_BUG_ON (__alignof__(struct xfrm_user_tmpl ) >4 ); + +if (*optlen <sizeof (*p))return -EINVAL ; - data64 =kmalloc_track_caller (optlen +4 ,GFP_USER | __GFP_NOWARN); + data64 =kmalloc_track_caller (*optlen +4 ,GFP_USER | __GFP_NOWARN);if (!data64)return -ENOMEM ;
@@ -660,10 +669,11 @@ static int xfrm_user_policy_compat(u8 **pdata32, int optlen) src_templates = *pdata32 +sizeof (*p); dst_templates = data64 +sizeof (*p) +4 ; -memcpy (dst_templates, src_templates, optlen -sizeof (*p)); +memcpy (dst_templates, src_templates, *optlen -sizeof (*p));kfree (*pdata32); *pdata32 = data64; + *optlen +=4 ;return 0 ; }
net/xfrm/xfrm_state.c +1 -1
@@ -3115,7 +3115,7 @@ int xfrm_user_policy(struct sock *sk, int optname, sockptr_t optval, int optlen)return -EOPNOTSUPP ; } - err = xtr->xlate_user_policy_sockptr (&data, optlen); + err = xtr->xlate_user_policy_sockptr (&data, &optlen);xfrm_put_translator (xtr);if (err) {kfree (data);
Signature · 1 line
2.53.0
Steffen Klassert
maintainerPATCH 18/22 xfrm: Give GC list nodes their own storage
In reply to Steffen KlassertFrom: Jianbo Liu <[email protected]>
gclist currently shares storage with bydst, and dev_gclist shares storage with bysrc.
This is unsafe for bydst and bysrc, which can be traversed under RCU without holding xfrm_state_lock. __xfrm_state_delete() unlinks these nodes with hlist_del_init_rcu(), so a reader that started before the unlink may still be following their linkage after the state has been removed from the hash table.
Later, when the last reference is dropped, __xfrm_state_destroy() adds x->gclist to xfrm_state_gc_list. Since gclist and bydst currently share the same storage, adding the state to the GC list can overwrite the bydst linkage while an RCU reader is still using it. The same issue applies to dev_gclist and bysrc.
Give gclist, bydst, and bysrc separate storage so their hash-list linkage remains valid for outstanding RCU readers. Share dev_gclist with byseq instead. byseq has no RCU readers, only __xfrm_find_acq_byseq() under xfrm_state_lock, and the state is unlinked from byseq before dev_gclist is used. Sharing keeps the growth of struct xfrm_state at 16 bytes rather than 32.
--- include/net/xfrm.h | 10 ++++------ net/xfrm/xfrm_state.c | 1 + 2 files changed, 5 insertions(+), 6 deletions(-)
include/net/xfrm.h +4 -6
@@ -189,16 +189,14 @@ enum xfrm_replay_mode {/* Full description of state of transformer. */ struct xfrm_state {possible_net_t xs_net; -union { -struct hlist_node gclist; -struct hlist_node bydst; - }; +struct hlist_node bydst; +struct hlist_node bysrc; +struct hlist_node gclist;union {struct hlist_node dev_gclist; -struct hlist_node bysrc; +struct hlist_node byseq; };struct hlist_node byspi; -struct hlist_node byseq;struct hlist_node state_cache;struct hlist_node state_cache_input;
net/xfrm/xfrm_state.c +1 -0
@@ -751,6 +751,7 @@ struct xfrm_state *xfrm_state_alloc(struct net *net)INIT_HLIST_NODE (&x->state_cache);INIT_HLIST_NODE (&x->bydst);INIT_HLIST_NODE (&x->bysrc); +INIT_HLIST_NODE (&x->gclist);INIT_HLIST_NODE (&x->byspi);INIT_HLIST_NODE (&x->byseq); hrtimer_setup(&x->mtimer, xfrm_timer_handler, CLOCK_BOOTTIME,
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 18/22] xfrm: Give GC list nodes their own storage
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] The Fixes: tag is incomplete, and the description of the bysrc half is imprecise.
--
xfrm: Give GC list nodes their own storage
This patch takes gclist out of its union with bydst. It also moves dev_gclist out of its union with bysrc and into a union with byseq. This keeps the bydst and bysrc hash linkage intact for RCU readers that are still walking a state after it has been unlinked.
The code change appears to fix both overlays. The questions below are only about the commit message.
Quoted 1 line
The same issue applies to
dev_gclistand bysrc.
[Severity: Low]
Is the bysrc case really the same issue as the gclist case?
The gclist overwrite only happens when the last reference is dropped in __xfrm_state_destroy(). xfrm_state_gc_task() then runs synchronize_rcu() before freeing.
For offloaded states, dev_gclist is written right after bysrc is unlinked. It does not wait for the last reference:
__xfrm_state_delete()
hlist_del_init_rcu(&x->bysrc);
...
spin_unlock(&net->xfrm.xfrm_state_lock);
xfrm_dev_state_delete(x)
hlist_add_head(&x->dev_gclist, &xfrm_state_dev_gc_list);That overwrites bysrc.next while a reader in __xfrm_state_lookup_byaddr() may still be sitting on x:
hlist_for_each_entry_rcu(x, state_ptrs->bysrc + h, bysrc) {After that, xfrm_dev_state_flush() can call xfrm_dev_state_free(). That function does hlist_del(&x->dev_gclist), which sets next to LIST_POISON1 without a grace period. A concurrent bysrc reader could then dereference the poison pointer.
Could the commit message describe the bysrc case separately?
Quoted 1 line
Fixes d737a5805581 ("xfrm: state: don't use lock anymore unless acquire operation is needed")
Does this tag cover the bysrc half of the fix? d737a5805581 only made xfrm_state_find() walk bydst under rcu_read_lock(), so it matches the gclist/bydst overlay.
The dev_gclist/bysrc union came from 07b87f9eea0c ("xfrm: Fix unregister netdevice hang on hardware offload."). When that commit landed, every bysrc reader held xfrm_state_lock, so the overlay was safe.
The overlay became unsafe with 2e460eefbd4469 ("xfrm: state: make xfrm_state_lookup_byaddr lockless"). That commit replaced spin_lock_bh(&net->xfrm.xfrm_state_lock) with rcu_read_lock() in xfrm_state_lookup_byaddr(). This turned __xfrm_state_lookup_byaddr() into a lockless reader of bysrc while dev_gclist still shared its storage.
Should the patch also carry the following tag, possibly together with 07b87f9eea0c?
Backporting to trees without 07b87f9eea0c will hit a conflict in the xfrm.h hunk. The current message doesn't say that only the gclist/bydst split applies to those trees.
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerPATCH 19/22 xfrm: Serialize device state teardown
In reply to Steffen KlassertFrom: Jianbo Liu <[email protected]>
Commit 89fefad9f971 ("xfrm: serialize state GC with device state flush") stopped the state GC and xfrm_dev_state_flush() from freeing the same device state at once, but a third caller is not covered.
xfrm_state_find() frees a packet offload acquire state when km_query() fails. It runs under RCU and can't take the mutex. xfrm_dev_state_delete() first puts the state on xfrm_state_dev_gc_list with xso->dev still set, so a device flush can find it there and call xfrm_dev_state_free() too. Both callers see xso->dev set and both unlink the state, so the second hlist_del() hits a poisoned node.
Claim the device in xfrm_dev_state_free() by clearing xso->dev under x->lock and xfrm_state_dev_gc_lock, so only one caller unlinks the state, invokes xdo_dev_state_free() and drops the netdevice reference. x->lock also keeps xso->dev stable for the stats updates that hold it.
In the flush, take a state reference before removing a state from the device GC list, so it stays alive while the flush owns it. Skip a state with no reference left, the state GC frees it.
Keep xso->type unchanged after detaching the device, so lockless readers of xso->type do not see a packet offload state as a software state. Reject offloaded states with no device in xfrm_dev_offload_ok(): a packet offload state would otherwise pass the !dev check there, and xfrm_output() would send the packet with no ESP or use the NULL device in xfrm_dev_direct_output().
Found by the AI review of the commit above (see Link) and reproduced on ConnectX-7 with a packet offload policy that has no SA, an acquire listener that never reads, UDP senders hitting the policy and the device taken down in a loop:
[ 167.689163] Oops: general protection fault, probably for non-canonical address 0xdead000000000122: 0000 [#1] SMP [ 167.690938] CPU: 11 UID: 0 PID: 2093 Comm: python3 Not tainted 7.4.0-rc1+ #10 PREEMPTLAZY [ 167.694337] RIP: 0010:xfrm_dev_state_free+0x41/0xe0 [ 167.699068] RAX: dead000000000122 RBX: ff1100014f543800 RCX: ff11000103bbf800 [ 167.700247] RDX: dead000000000100 RSI: 0000000000000001 RDI: ffffffff82da8c68 [ 167.716897] Call Trace: [ 167.717405] <TASK> [ 167.717863] xfrm_state_find+0x19b0/0x1ab0 [ 167.718629] xfrm_resolve_and_create_bundle+0x17d/0x11e0 [ 167.722070] xfrm_lookup_with_ifid+0x1e7/0xb50 [ 167.722872] xfrm_lookup_route+0x1d/0xa0 [ 167.723593] udp_sendmsg+0x8da/0xc90 [ 167.724273] __sock_sendmsg+0x38/0x70 [ 167.724988] __sys_sendto+0x119/0x180 [ 167.727954] __x64_sys_sendto+0x20/0x30 [ 167.728666] do_syscall_64+0x72/0x3b0 [ 167.729357] entry_SYSCALL_64_after_hwframe+0x4b/0x53 [ 167.741064] </TASK> [ 167.752388] Kernel panic - not syncing: Fatal exception in interrupt
With this series the same test ran 400 cycles with no crash, and 150 cycles on a kernel with KASAN and lockdep.
--- net/xfrm/xfrm_device.c | 4 ++-- net/xfrm/xfrm_state.c | 51 ++++++++++++++++++++++++++++-------------- 2 files changed, 36 insertions(+), 19 deletions(-)
net/xfrm/xfrm_device.c +2 -2
@@ -422,11 +422,11 @@ bool xfrm_dev_offload_ok(struct sk_buff *skb, struct xfrm_state *x)int mtu;struct dst_entry *dst =skb_dst (skb);struct xfrm_dst *xdst = (struct xfrm_dst *)dst; -struct net_device *dev = x->xso.dev; +struct net_device *dev =READ_ONCE (x->xso.dev);bool check_tunnel_size;if (!x->type_offload || - (x->xso.type ==XFRM_DEV_OFFLOAD_UNSPECIFIED && x->encap)) + (x->xso.type ==XFRM_DEV_OFFLOAD_UNSPECIFIED ? !!x->encap : !dev))return false; if ((!dev || dev == xfrm_dst_path(dst)->dev) &&
net/xfrm/xfrm_state.c +34 -17
81 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 19/22] xfrm: Serialize device state teardown
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: 1 · Medium: 1 · Low: 0
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).
- [High] The fix for a NULL device in xfrm_dev_direct_output() only checks a local snapshot, so the NULL dereference is still reachable.
- [Medium] xfrm_dev_state_flush() can return while a state on xfrm_state_dev_gc_list still has xso->dev == dev, its driver SA and…
--
xfrm: Serialize device state teardown
This commit makes xfrm_dev_state_free() claim the device by clearing xso->dev under x->lock and xfrm_state_dev_gc_lock. With that, only one caller unlinks the state and drops the netdev reference. The device flush now takes a state reference before collecting states from the device GC list, and xfrm_dev_offload_ok() rejects offloaded states that have no device.
Quoted 8 lines
net/xfrm/xfrm_device.c +0
-0@@ -422,11 +422,11 @@ bool xfrm_dev_offload_ok(struct sk_buff *skb, struct xfrm_state *x)int mtu;struct dst_entry *dst =skb_dst (skb);struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
net/xfrm/xfrm_device.c bool xfrm_dev_offload_ok(struct sk_buff *skb, struct xfrm_state *x) · line 432
Quoted 10 lines
net/xfrm/xfrm_device.c +2
-2-struct net_device *dev = x->xso.dev; +struct net_device *dev =READ_ONCE (x->xso.dev);bool check_tunnel_size;if (!x->type_offload || - (x->xso.type ==XFRM_DEV_OFFLOAD_UNSPECIFIED && x->encap)) + (x->xso.type ==XFRM_DEV_OFFLOAD_UNSPECIFIED ? !!x->encap : !dev))return false; if ((!dev || dev == xfrm_dst_path(dst)->dev) &&
[Severity: High]
The commit message says this check stops xfrm_output() from using "the NULL device in xfrm_dev_direct_output()". Only the local snapshot of x->xso.dev is checked here, so is that window really closed?
Nothing that runs after this check receives the snapshot. Take a tunnel mode packet offload state with !skb->sk. xfrm_output() calls xfrm_dev_direct_output(), which runs the LOCAL_OUT hooks and then loads the pointer again:
net/xfrm/xfrm_output.c:xfrm_dev_direct_output() {
...
err = skb_dst(skb)->ops->local_out(net, sk, skb);
if (unlikely(err != 1))
return err;
...
skb->dev = x->xso.dev;
__skb_push(skb, skb->dev->hard_header_len);
return dev_queue_xmit(skb);
}The driver callback at the end of xfrm_dev_offload_ok() is also passed x rather than dev. For bonding, bond_ipsec_offload_ok()->bond_ipsec_dev() loads the pointer again and dereferences it without a NULL check. This happens for crypto offload as well:
drivers/net/bonding/bond_main.c:bond_ipsec_dev() {
struct net_device *bond_dev = xs->xso.dev;
...
bond = netdev_priv(bond_dev);
if (BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP)
return NULL;
...
}The bond_ipsec_dev() re-read predates this patch. It is the same NULL device use that the commit message says is handled.
Now that xso->type stays set after detach, can this sequence oops?
CPU1 (TX) CPU2 (NETDEV_DOWN/UNREGISTER)xfrm_dev_offload_ok()
dev = READ_ONCE(x->xso.dev)
/* non-NULL, check passes */
xfrm_dev_state_flush()
xfrm_dev_state_free()
WRITE_ONCE(xso->dev, NULL);
xfrm_output()
xfrm_dev_direct_output()
skb->dev = x->xso.dev; /* NULL */
skb->dev->hard_header_lenxfrm_dev_state_free() clears the pointer under x->lock and xfrm_state_dev_gc_lock. The TX path takes neither lock.
A later patch in this series, "xfrm: Wait for an RCU grace period before freeing device state", adds synchronize_rcu() before xfrm_dev_state_free() in the flush. That makes the window smaller but does not close it. xso->dev is cleared after the grace period rather than unpublished before it.
A TX user that holds a counted bundle dst taken before the delete can still enter xfrm_output() in a new RCU section after the grace period. Two examples:
- a forwarded packet that is NF_QUEUE'd and reinjected later
- a UDP sender that sleeps while copying user data after its route lookup
Could dev be read once and passed down to xfrm_dev_direct_output() and the driver callbacks? Alternatively, it could be checked again at each use, or TX users could be kept from reaching x before xso->dev is cleared.
Quoted 4 lines
net/xfrm/xfrm_state.c +0
-0
[ ... ]
Quoted 5 lines
net/xfrm/xfrm_state.c +0
-1@@ -1012,21 +1021,29 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valimutex_lock (&xfrm_state_gc_mutex);spin_lock_bh (&xfrm_state_dev_gc_lock); -restart_gc:
net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1029
Quoted 10 lines
net/xfrm/xfrm_state.c +2
-4hlist_for_each_entry_safe (x, tmp, &xfrm_state_dev_gc_list, dev_gclist) { xso = &x->xso;if (xso->dev == dev) { -spin_unlock_bh (&xfrm_state_dev_gc_lock); -xfrm_dev_state_free (x); -spin_lock_bh (&xfrm_state_dev_gc_lock); - goto restart_gc; +if (!refcount_inc_not_zero (&x->refcnt)) +continue ;
[Severity: Medium]
Can xfrm_dev_state_flush() return while a state on xfrm_state_dev_gc_list still has xso->dev == dev, along with its driver SA and its netdev reference?
This skip assumes the state GC already owns any state whose refcount is zero, and that xfrm_flush_gc() at the end will wait for it. However, xfrm_state_put() drops the refcount to zero before __xfrm_state_destroy() queues the state and schedules the work:
xfrm_state_put()
refcount_dec_and_test(&x->refcnt) /* refcnt is now 0 */
__xfrm_state_destroy()
spin_lock_bh(&xfrm_state_gc_lock);
hlist_add_head(&x->gclist, &xfrm_state_gc_list);
spin_unlock_bh(&xfrm_state_gc_lock);
schedule_work(&xfrm_state_gc_work);If the flush walks the dev GC list between those two points, it skips the state. xfrm_flush_gc() then calls flush_work() on a work item that is neither pending nor running, so it returns at once.
Before this patch, the flush freed the device state of every matching entry regardless of its refcount. Here the GC later calls xdo_dev_state_free() on a device the flush has already reported as clean. For unregister, netdev_wait_allrefs_any() has to wait for the reference.
The later patch "xfrm: Wait for an RCU grace period before freeing device state" only handles the case where the flush itself drops the last reference. This skip is still there at the end of the series.
[ ... ]
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerRe: [PATCH 19/22] xfrm: Serialize device state teardown
Ccing the author of the patch.
Quoted 83 lines · On Wed, Dec 02, 2026 at 01:12:32PM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.
Critical: 0 · High: 1 · Medium: 1 · Low: 0
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).
- [High] The fix for a NULL device in
xfrm_dev_direct_output()only checks a local snapshot, so the NULL dereference is still reachable.
- [Medium]xfrm_dev_state_flush()can return while a state onxfrm_state_dev_gc_liststill hasxso->dev== dev, its driver SA and…--
xfrm: Serialize device state teardown
This commit makes
xfrm_dev_state_free()claim the device by clearingxso->devunderx->lockandxfrm_state_dev_gc_lock. With that, only one caller unlinks the state and drops the netdev reference. The device flush now takes a state reference before collecting states from the device GC list, andxfrm_dev_offload_ok()rejects offloaded states that have no device.Quoted 8 lines
net/xfrm/xfrm_device.c +0
-0@@ -422,11 +422,11 @@ bool xfrm_dev_offload_ok(struct sk_buff *skb, struct xfrm_state *x)int mtu;struct dst_entry *dst =skb_dst (skb);struct xfrm_dst *xdst = (struct xfrm_dst *)dst;net/xfrm/xfrm_device.c bool xfrm_dev_offload_ok(struct sk_buff *skb, struct xfrm_state *x) · line 432
Quoted 10 lines
net/xfrm/xfrm_device.c +2
-2-struct net_device *dev = x->xso.dev; +struct net_device *dev =READ_ONCE (x->xso.dev);bool check_tunnel_size;if (!x->type_offload || - (x->xso.type ==XFRM_DEV_OFFLOAD_UNSPECIFIED && x->encap)) + (x->xso.type ==XFRM_DEV_OFFLOAD_UNSPECIFIED ? !!x->encap : !dev))return false; if ((!dev || dev == xfrm_dst_path(dst)->dev) &&[Severity: High]
The commit message says this check stopsxfrm_output()from using "the NULL device inxfrm_dev_direct_output()". Only the local snapshot ofx->xso.devis checked here, so is that window really closed?Nothing that runs after this check receives the snapshot. Take a tunnel mode packet offload state with !skb->sk.
xfrm_output()callsxfrm_dev_direct_output(), which runs theLOCAL_OUThooks and then loads the pointer again:net/xfrm/xfrm_output.c:xfrm_dev_direct_output() { ... err = skb_dst(skb)->ops->local_out(net, sk, skb); if (unlikely(err != 1)) return err; ... skb->dev = x->xso.dev; __skb_push(skb, skb->dev->hard_header_len); return dev_queue_xmit(skb); }The driver callback at the end of
xfrm_dev_offload_ok()is also passed x rather than dev. For bonding, bond_ipsec_offload_ok()->bond_ipsec_dev() loads the pointer again and dereferences it without a NULL check. This happens for crypto offload as well:drivers/net/bonding/bond_main.c:bond_ipsec_dev() { struct net_device *bond_dev = xs->xso.dev; ... bond = netdev_priv(bond_dev); if (BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP) return NULL; ... }
Quoted 2 lines
The
bond_ipsec_dev()re-read predates this patch. It is the same NULL device use that the commit message says is handled.
Jianbo Liu already commented on this when the patch was posted originally to the netdev list:
https://lore.kernel.org/ipsec/[email protected]/
Should be addressed with a separate fix.
Quoted 96 lines
Now that
xso->typestays set after detach, can this sequence oops?CPU1 (TX) CPU2 (NETDEV_DOWN/UNREGISTER)
xfrm_dev_offload_ok()
dev =READ_ONCE(x->xso.dev)
/* non-NULL, check passes */xfrm_dev_state_flush() xfrm_dev_state_free() WRITE_ONCE(xso->dev, NULL); xfrm_output() xfrm_dev_direct_output() skb->dev = x->xso.dev; /* NULL */ skb->dev->hard_header_len
xfrm_dev_state_free()clears the pointer underx->lockandxfrm_state_dev_gc_lock. The TX path takes neither lock.A later patch in this series, "xfrm: Wait for an RCU grace period before freeing device state", adds
synchronize_rcu()beforexfrm_dev_state_free()in the flush. That makes the window smaller but does not close it.xso->devis cleared after the grace period rather than unpublished before it.A TX user that holds a counted bundle dst taken before the delete can still enter
xfrm_output()in a new RCU section after the grace period. Two examples:- a forwarded packet that is NF_QUEUE'd and reinjected later
- a UDP sender that sleeps while copying user data after its route lookupCould dev be read once and passed down to
xfrm_dev_direct_output()and the driver callbacks? Alternatively, it could be checked again at each use, or TX users could be kept from reaching x beforexso->devis cleared.Quoted 4 lines
net/xfrm/xfrm_state.c +0
-0[ ... ]
Quoted 5 lines
net/xfrm/xfrm_state.c +0
-1@@ -1012,21 +1021,29 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valimutex_lock (&xfrm_state_gc_mutex);spin_lock_bh (&xfrm_state_dev_gc_lock); -restart_gc:net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1029
Quoted 10 lines
net/xfrm/xfrm_state.c +2
-4hlist_for_each_entry_safe (x, tmp, &xfrm_state_dev_gc_list, dev_gclist) { xso = &x->xso;if (xso->dev == dev) { -spin_unlock_bh (&xfrm_state_dev_gc_lock); -xfrm_dev_state_free (x); -spin_lock_bh (&xfrm_state_dev_gc_lock); - goto restart_gc; +if (!refcount_inc_not_zero (&x->refcnt)) +continue ;[Severity: Medium]
Canxfrm_dev_state_flush()return while a state onxfrm_state_dev_gc_liststill hasxso->dev== dev, along with its driver SA and its netdev reference?This skip assumes the state GC already owns any state whose refcount is zero, and that
xfrm_flush_gc()at the end will wait for it. However,xfrm_state_put()drops the refcount to zero before__xfrm_state_destroy()queues the state and schedules the work:
xfrm_state_put()
refcount_dec_and_test(&x->refcnt)/* refcnt is now 0 */
__xfrm_state_destroy()spin_lock_bh(&xfrm_state_gc_lock); hlist_add_head(&x->gclist, &xfrm_state_gc_list); spin_unlock_bh(&xfrm_state_gc_lock); schedule_work(&xfrm_state_gc_work);If the flush walks the dev GC list between those two points, it skips the state.
xfrm_flush_gc()then callsflush_work()on a work item that is neither pending nor running, so it returns at once.Before this patch, the flush freed the device state of every matching entry regardless of its refcount. Here the GC later calls
xdo_dev_state_free()on a device the flush has already reported as clean. For unregister,netdev_wait_allrefs_any()has to wait for the reference.The later patch "xfrm: Wait for an RCU grace period before freeing device state" only handles the case where the flush itself drops the last reference. This skip is still there at the end of the series.
[ ... ]
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerPATCH 20/22 xfrm: Wait for an RCU grace period before freeing device state
In reply to Steffen KlassertFrom: Jianbo Liu <[email protected]>
xfrm_dev_state_flush() can call xdo_dev_state_free() immediately after xdo_dev_state_delete(), without waiting for pre-existing RCU readers of the driver's SA state to complete.
The normal state GC path waits for an RCU grace period before destroying the state, but the device flush path does not.
Remove the immediate xfrm_dev_state_free() following xfrm_state_delete(). The delete path queues the state on xfrm_state_dev_gc_list. The subsequent collection pass picks it up if a reference is left. If the flush dropped the last one, the state GC frees it after its own grace period and xfrm_flush_gc() waits for it.
Wait for one RCU grace period after collecting the states and before freeing them. This establishes the required xdo_dev_state_delete() -> synchronize_rcu() -> xdo_dev_state_free() ordering while using a single grace period for the whole flush.
--- net/xfrm/xfrm_state.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
net/xfrm/xfrm_state.c +3 -1
@@ -1000,7 +1000,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valispin_unlock_bh (&net->xfrm.xfrm_state_lock); err =xfrm_state_delete (x); -xfrm_dev_state_free (x);xfrm_audit_state_delete (x, err ?0 :1 , task_valid);
@@ -1038,6 +1037,9 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valispin_unlock_bh (&xfrm_state_dev_gc_lock);mutex_unlock (&xfrm_state_gc_mutex); +if (!hlist_empty (&flush_list)) +synchronize_rcu (); +hlist_for_each_entry_safe (x, tmp, &flush_list, gclist) {hlist_del_init (&x->gclist);xfrm_dev_state_free (x);
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 20/22] xfrm: Wait for an RCU grace period before freeing device state
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 (1) · Medium: 1 · Low: 1 (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] xfrm: race in xfrm_dev_state_flush() misses in-flight state destruction
- [Low] The synchronize_rcu() this patch adds to xfrm_dev_state_flush() (net/xfrm/xfrm_state.c line 1041) always runs with RTNL held.
Pre-existing issues:
- [High] This problem wasn't introduced by this patch, but it is the same bug class on another caller.
- [Low] Documentation/networking/xfrm/xfrm_device.rst (lines 190-200) describes the xdo_dev_state_delete()/xdo_dev_state_free() sequence for…
--
xfrm: Wait for an RCU grace period before freeing device state
This commit removes the xfrm_dev_state_free() call that ran immediately after xfrm_state_delete() in xfrm_dev_state_flush(). It adds a single synchronize_rcu() before the collected device states are freed. The goal is to enforce xdo_dev_state_delete() -> synchronize_rcu() -> xdo_dev_state_free() ordering on the device flush path.
Quoted 4 lines
net/xfrm/xfrm_state.c +0
-0
[ ... ]
net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1042
Quoted 7 lines
net/xfrm/xfrm_state.c +3
-0@@ -1038,6 +1037,9 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valispin_unlock_bh (&xfrm_state_dev_gc_lock);mutex_unlock (&xfrm_state_gc_mutex); +if (!hlist_empty (&flush_list)) +synchronize_rcu (); +
[Severity: Low]
Would synchronize_net() be a better fit here than synchronize_rcu()?
As far as I can tell, every caller of xfrm_dev_state_flush() runs from a netdev notifier with RTNL held:
xfrm_dev_event()->xfrm_dev_down() (NETDEV_DOWN) xfrm_dev_event()->xfrm_dev_unregister() (NETDEV_UNREGISTER) bond_master_netdev_event() (NETDEV_UNREGISTER)
When flush_list is non-empty, RTNL stays held for a full normal grace period. That happens whenever offloaded states still have references, for example from policy bundles. It happens once per flushed device, including during batched unregister and netns teardown.
Before this patch, xfrm_flush_gc() could already wait on the GC worker's grace period, so this adds at most one more grace period per flush.
synchronize_net() gives the same ordering but uses the expedited variant when called in this context:
net/core/dev.c:synchronize_net() {
might_sleep();
if (from_cleanup_net() || rtnl_is_locked())
synchronize_rcu_expedited();
else
synchronize_rcu();
}The commit message discusses the cost ("using a single grace period for the whole flush") but not the RTNL context.
[Severity: High]
This isn't a bug introduced by this patch, but does bond_ipsec_del_sa_all() in drivers/net/bonding/bond_main.c need the same ordering?
The commit message says the xdo_dev_state_delete() -> synchronize_rcu() -> xdo_dev_state_free() ordering is required. On an active slave change, bond_change_active_slave()->bond_ipsec_del_sa_all() calls the two slave ops one right after the other:
drivers/net/bonding/bond_main.c:bond_ipsec_del_sa_all() {
...
spin_lock_bh(&ipsec->xs->lock);
ipsec->xs->xso.real_dev = NULL;
/* Don't double delete states killed by the user. */
if (ipsec->xs->km.state != XFRM_STATE_DEAD)
real_dev->xfrmdev_ops->xdo_dev_state_delete(real_dev,
ipsec->xs);
spin_unlock_bh(&ipsec->xs->lock);
if (real_dev->xfrmdev_ops->xdo_dev_state_free)
real_dev->xfrmdev_ops->xdo_dev_state_free(real_dev,
ipsec->xs);
...
}With mlx5 slaves, mlx5e_xfrm_del_state() only calls xa_erase_bh() on ipsec->sadb. mlx5e_xfrm_free_state() then calls kfree(sa_entry).
Meanwhile, the RX path reads sa_entry under RCU:
drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_rxtx.c:mlx5e_ipsec_offload_handle_rx_skb() {
...
rcu_read_lock();
sa_entry = xa_load(&ipsec->sadb, sa_handle);
...
xfrm_state_hold(sa_entry->x);
rcu_read_unlock();
...
}Suppose NAPI on the old slave loaded sa_entry before the xa_erase_bh(). Could it then dereference sa_entry->x after the kfree() and call xfrm_state_hold() on freed memory?
In-flight TX on the old slave seems to have the same exposure. mlx5e_ipsec_handle_tx_skb() uses x->xso.offload_handle and calls sa_entry->set_iv_op(). Bonding doesn't clear offload_handle before bond_ipsec_add_sa_all() reprograms it.
States with km.state == XFRM_STATE_DEAD skip the delete here but are still freed immediately. Their earlier slave delete went through xfrm_dev_state_delete()->bond_ipsec_del_sa() without a grace period before this free.
The window is narrow, because mlx5e_xfrm_free_state() runs firmware commands first. Still, nothing separates the two ops with a grace period.
net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1045
Quoted 3 lines
net/xfrm/xfrm_state.c +0
-0hlist_for_each_entry_safe (x, tmp, &flush_list, gclist) {hlist_del_init (&x->gclist);xfrm_dev_state_free (x);
[Severity: Low]
This is a pre-existing issue, but Documentation/networking/xfrm/ xfrm_device.rst doesn't say that the core provides an RCU grace period between xdo_dev_state_delete() and xdo_dev_state_free():
Later,
xdo_dev_state_free() and xdo_dev_policy_free() are called from a garbage collection routine after all reference counts to the state and policy have been removed
As a netdev is set to DOWN the XFRM stack's netdev listener will call xdo_dev_state_delete(), xdo_dev_policy_delete(), xdo_dev_state_free() and xdo_dev_policy_free() on any remaining offloaded states.
The "after all reference counts ... have been removed" wording also doesn't match this loop. Here xfrm_dev_state_free() runs while the flush still holds the reference it took with refcount_inc_not_zero(), and xfrm_state_put() is only called afterwards.
Both gaps predate this patch. xfrm_state_gc_task() already called synchronize_rcu() before xfrm_state_gc_destroy(), and the old flush path already freed device state while holding a reference.
Since this patch extends the grace-period guarantee to the flush path, could the documentation describe it for driver authors?
[ ... ]
net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1005
Quoted 8 lines
net/xfrm/xfrm_state.c +0
-1@@ -1000,7 +1000,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valispin_unlock_bh (&net->xfrm.xfrm_state_lock); err =xfrm_state_delete (x); -xfrm_dev_state_free (x);xfrm_audit_state_delete (x, err ?0 :1 , task_valid);
[Severity: Medium]
Can removing this call let xfrm_dev_state_flush() return before xdo_dev_state_free() has run for a state it just deleted?
After this change, the first loop drops its reference with xfrm_state_put(). It then relies on one of two things to free the device state before returning:
- the xfrm_state_dev_gc_list scan picking x up via refcount_inc_not_zero(), or
- xfrm_flush_gc() waiting for the GC worker.
Suppose another CPU holds the last reference to x while the flush runs, for example from an skb secpath, an xfrm_dst, or a concurrent lookup:
CPU0 (flush) CPU1
xfrm_state_delete(x)
xfrm_state_put(x) /* refcnt 1 */
xfrm_state_put(x)
refcount_dec_and_test() -> 0
scan xfrm_state_dev_gc_list
refcount_inc_not_zero() fails
x is skipped
xfrm_flush_gc()
flush_work() returns, nothing
queued yet
__xfrm_state_destroy(x)
hlist_add_head(&x->gclist)
schedule_work()__xfrm_state_destroy() queues x on xfrm_state_gc_list and calls schedule_work() without xfrm_state_dev_gc_lock. Since it can run from softirq, it can't take xfrm_state_gc_mutex either. Nothing orders it against the scan.
The same applies if xfrm_state_gc_task() is already running and has done hlist_move_list() before x is queued. In that case flush_work() only waits for that instance.
Before this patch, the synchronous xfrm_dev_state_free() after xfrm_state_delete() covered every state found in the bydst hash, no matter who held the last reference.
The effect of returning early depends on the device:
- Bond, NETDEV_UNREGISTER: unregister_netdevice_many_notify() calls bond_uninit(), which destroys bond->ipsec_lock. xfrm_state_gc_task() can later reach bond_ipsec_free_sa() and take that destroyed mutex.
- mlx5, NETDEV_DOWN: if mlx5e_xfrm_free_state() hasn't run yet, mlx5_eswitch_unblock_ipsec() is still pending, so eswitch mode changes can fail with -EBUSY.
- mlx5, later teardown: mlx5e_ipsec_cleanup() could free priv->ipsec
before mlx5e_xfrm_free_state() dereferences sa_entry->ipsec.
The later revert of "xfrm: serialize state GC with device state flush" in this series removes xfrm_state_gc_mutex. It doesn't seem to close this window either.
How is the flush meant to wait for offloaded states whose last reference is dropped concurrently with the dev_gclist scan?
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerRe: [PATCH 20/22] xfrm: Wait for an RCU grace period before freeing device state
Ccing the author of the patch.
Quoted 233 lines · On Wed, Dec 02, 2026 at 01:12:33PM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.
Critical: 0 · High: 0 (1) · Medium: 1 · Low: 1 (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] xfrm: race in
xfrm_dev_state_flush()misses in-flight state destruction
- [Low] Thesynchronize_rcu()this patch adds toxfrm_dev_state_flush()(net/xfrm/xfrm_state.cline 1041) always runs with RTNL held.Pre-existing issues:
- [High] This problem wasn't introduced by this patch, but it is the same bug class on another caller.
- [Low]Documentation/networking/xfrm/xfrm_device.rst(lines 190-200) describes the xdo_dev_state_delete()/xdo_dev_state_free() sequence for…--
xfrm: Wait for an RCU grace period before freeing device state
This commit removes the
xfrm_dev_state_free()call that ran immediately afterxfrm_state_delete()inxfrm_dev_state_flush(). It adds a singlesynchronize_rcu()before the collected device states are freed. The goal is to enforcexdo_dev_state_delete()->synchronize_rcu()->xdo_dev_state_free()ordering on the device flush path.Quoted 4 lines
net/xfrm/xfrm_state.c +0
-0[ ... ]
net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1042
Quoted 7 lines
net/xfrm/xfrm_state.c +3
-0@@ -1038,6 +1037,9 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valispin_unlock_bh (&xfrm_state_dev_gc_lock);mutex_unlock (&xfrm_state_gc_mutex); +if (!hlist_empty (&flush_list)) +synchronize_rcu (); +[Severity: Low]
Wouldsynchronize_net()be a better fit here thansynchronize_rcu()?As far as I can tell, every caller of
xfrm_dev_state_flush()runs from a netdev notifier with RTNL held:xfrm_dev_event()->xfrm_dev_down() (NETDEV_DOWN) xfrm_dev_event()->xfrm_dev_unregister() (NETDEV_UNREGISTER) bond_master_netdev_event() (NETDEV_UNREGISTER)When
flush_listis non-empty, RTNL stays held for a full normal grace period. That happens whenever offloaded states still have references, for example from policy bundles. It happens once per flushed device, including during batched unregister and netns teardown.Before this patch,
xfrm_flush_gc()could already wait on the GC worker's grace period, so this adds at most one more grace period per flush.
synchronize_net()gives the same ordering but uses the expedited variant when called in this context:net/core/dev.c:synchronize_net() { might_sleep(); if (from_cleanup_net() || rtnl_is_locked()) synchronize_rcu_expedited(); else synchronize_rcu(); }The commit message discusses the cost ("using a single grace period for the whole flush") but not the RTNL context.
[Severity: High]
This isn't a bug introduced by this patch, but doesbond_ipsec_del_sa_all()indrivers/net/bonding/bond_main.cneed the same ordering?The commit message says the
xdo_dev_state_delete()->synchronize_rcu()->xdo_dev_state_free()ordering is required. On an active slave change, bond_change_active_slave()->bond_ipsec_del_sa_all() calls the two slave ops one right after the other:drivers/net/bonding/bond_main.c:bond_ipsec_del_sa_all() { ... spin_lock_bh(&ipsec->xs->lock); ipsec->xs->xso.real_dev = NULL; /* Don't double delete states killed by the user. */ if (ipsec->xs->km.state != XFRM_STATE_DEAD) real_dev->xfrmdev_ops->xdo_dev_state_delete(real_dev, ipsec->xs); spin_unlock_bh(&ipsec->xs->lock); if (real_dev->xfrmdev_ops->xdo_dev_state_free) real_dev->xfrmdev_ops->xdo_dev_state_free(real_dev, ipsec->xs); ... }With mlx5 slaves,
mlx5e_xfrm_del_state()only callsxa_erase_bh()onipsec->sadb.mlx5e_xfrm_free_state()then callskfree(sa_entry).Meanwhile, the RX path reads
sa_entryunder RCU:drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_rxtx.c:mlx5e_ipsec_offload_handle_rx_skb() { ... rcu_read_lock(); sa_entry = xa_load(&ipsec->sadb, sa_handle); ... xfrm_state_hold(sa_entry->x); rcu_read_unlock(); ... }Suppose NAPI on the old slave loaded
sa_entrybefore thexa_erase_bh(). Could it then dereferencesa_entry->xafter thekfree()and callxfrm_state_hold()on freed memory?In-flight TX on the old slave seems to have the same exposure.
mlx5e_ipsec_handle_tx_skb()usesx->xso.offload_handleand callssa_entry->set_iv_op(). Bonding doesn't clearoffload_handlebeforebond_ipsec_add_sa_all()reprograms it.States with km.state ==
XFRM_STATE_DEADskip the delete here but are still freed immediately. Their earlier slave delete went through xfrm_dev_state_delete()->bond_ipsec_del_sa() without a grace period before this free.The window is narrow, because
mlx5e_xfrm_free_state()runs firmware commands first. Still, nothing separates the two ops with a grace period.net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1045
Quoted 3 lines
net/xfrm/xfrm_state.c +0
-0hlist_for_each_entry_safe (x, tmp, &flush_list, gclist) {hlist_del_init (&x->gclist);xfrm_dev_state_free (x);[Severity: Low]
This is a pre-existing issue, butDocumentation/networking/xfrm/xfrm_device.rstdoesn't say that the core provides an RCU grace period betweenxdo_dev_state_delete()andxdo_dev_state_free():Later,
xdo_dev_state_free()andxdo_dev_policy_free()are called from a garbage collection routine after all reference counts to the state and policy have been removedAs a netdev is set to DOWN the XFRM stack's netdev listener will call
xdo_dev_state_delete(),xdo_dev_policy_delete(),xdo_dev_state_free()andxdo_dev_policy_free()on any remaining offloaded states.The "after all reference counts ... have been removed" wording also doesn't match this loop. Here
xfrm_dev_state_free()runs while the flush still holds the reference it took withrefcount_inc_not_zero(), andxfrm_state_put()is only called afterwards.Both gaps predate this patch.
xfrm_state_gc_task()already calledsynchronize_rcu()beforexfrm_state_gc_destroy(), and the old flush path already freed device state while holding a reference.Since this patch extends the grace-period guarantee to the flush path, could the documentation describe it for driver authors?
[ ... ]
net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1005
Quoted 8 lines
net/xfrm/xfrm_state.c +0
-1@@ -1000,7 +1000,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valispin_unlock_bh (&net->xfrm.xfrm_state_lock); err =xfrm_state_delete (x); -xfrm_dev_state_free (x);xfrm_audit_state_delete (x, err ?0 :1 , task_valid);[Severity: Medium]
Can removing this call letxfrm_dev_state_flush()return beforexdo_dev_state_free()has run for a state it just deleted?After this change, the first loop drops its reference with
xfrm_state_put(). It then relies on one of two things to free the device state before returning:- the
xfrm_state_dev_gc_listscan picking x up viarefcount_inc_not_zero(), or
-xfrm_flush_gc()waiting for the GC worker.Suppose another CPU holds the last reference to x while the flush runs, for example from an skb secpath, an
xfrm_dst, or a concurrent lookup:CPU0 (flush) CPU1
xfrm_state_delete(x)
xfrm_state_put(x)/* refcnt 1 */xfrm_state_put(x) refcount_dec_and_test() -> 0 scan xfrm_state_dev_gc_list refcount_inc_not_zero() fails x is skipped xfrm_flush_gc() flush_work() returns, nothing queued yet __xfrm_state_destroy(x) hlist_add_head(&x->gclist) schedule_work()
__xfrm_state_destroy()queues x onxfrm_state_gc_listand callsschedule_work()withoutxfrm_state_dev_gc_lock. Since it can run from softirq, it can't takexfrm_state_gc_mutexeither. Nothing orders it against the scan.The same applies if
xfrm_state_gc_task()is already running and has donehlist_move_list()before x is queued. In that caseflush_work()only waits for that instance.Before this patch, the synchronous
xfrm_dev_state_free()afterxfrm_state_delete()covered every state found in the bydst hash, no matter who held the last reference.The effect of returning early depends on the device:
- Bond,
NETDEV_UNREGISTER:unregister_netdevice_many_notify()callsbond_uninit(), which destroysbond->ipsec_lock.xfrm_state_gc_task()can later reachbond_ipsec_free_sa()and take that destroyed mutex.- mlx5,
NETDEV_DOWN: ifmlx5e_xfrm_free_state()hasn't run yet,mlx5_eswitch_unblock_ipsec()is still pending, so eswitch mode changes can fail with-EBUSY.- mlx5, later teardown:
mlx5e_ipsec_cleanup()could freepriv->ipsec
Quoted 8 lines
before mlx5e_xfrm_free_state() dereferences sa_entry->ipsec.The later revert of "xfrm: serialize state GC with device state flush" in this series removes
xfrm_state_gc_mutex. It doesn't seem to close this window either.How is the flush meant to wait for offloaded states whose last reference is dropped concurrently with the
dev_gclistscan?
Jianbo Liu already commented on this when the patch was posted originally to the netdev list:
https://lore.kernel.org/ipsec/[email protected]/
Same as the previous patch, should be addressed with a separate fix.
Quoted 3 lines
Signature · 2 lines
-- Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerPATCH 21/22 Revert "xfrm: serialize state GC with device state flush"
In reply to Steffen KlassertFrom: Jianbo Liu <[email protected]>
This reverts commit 89fefad9f971bc637fb22373078144f2563c4be9.
The mutex kept the state GC from destroying a state while xfrm_dev_state_flush() was freeing its device state. It can't cover xfrm_state_find(), which frees device state under RCU.
The flush now holds a reference on each state it frees, and xfrm_dev_state_free() lets only one caller free the device state. Nothing is left for the mutex to protect, so remove it.
This needs "xfrm: Serialize device state teardown". Without that patch the flush frees the device state of a state it holds no reference on.
--- net/xfrm/xfrm_state.c | 5 ----- 1 file changed, 5 deletions(-)
net/xfrm/xfrm_state.c +0 -5
@@ -226,7 +226,6 @@ static struct xfrm_state_afinfo __rcu *xfrm_state_afinfo[NPROTO];static DEFINE_SPINLOCK (xfrm_state_gc_lock);static DEFINE_SPINLOCK (xfrm_state_dev_gc_lock); -static DEFINE_MUTEX (xfrm_state_gc_mutex);int __xfrm_state_delete (struct xfrm_state *x);
@@ -639,10 +638,8 @@ static void xfrm_state_gc_task(struct work_struct *work)synchronize_rcu (); -mutex_lock (&xfrm_state_gc_mutex);hlist_for_each_entry_safe (x, tmp, &gc_list, gclist)xfrm_state_gc_destroy (x); -mutex_unlock (&xfrm_state_gc_mutex); }static enum hrtimer_restart xfrm_timer_handler (struct hrtimer *me)
@@ -1018,7 +1015,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali out:spin_unlock_bh (&net->xfrm.xfrm_state_lock); -mutex_lock (&xfrm_state_gc_mutex);spin_lock_bh (&xfrm_state_dev_gc_lock);hlist_for_each_entry_safe (x, tmp, &xfrm_state_dev_gc_list, dev_gclist) { xso = &x->xso;
@@ -1035,7 +1031,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali } }spin_unlock_bh (&xfrm_state_dev_gc_lock); -mutex_unlock (&xfrm_state_gc_mutex);if (!hlist_empty (&flush_list))synchronize_rcu ();
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 21/22] Revert "xfrm: serialize state GC with device state flush"
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Critical: 0 · High: 0 · Medium: 1 · Low: 0
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] xfrm_dev_state_flush() in net/xfrm/xfrm_state.c no longer guarantees that all device offload state for dev has been freed when…
--
Revert "xfrm: serialize state GC with device state flush"
This reverts the xfrm_state_gc_mutex. That mutex serialized xfrm_state_gc_task() with the dev_gclist walk in xfrm_dev_state_flush(). The flush now takes a reference on each state it frees, and it relies on "xfrm: Serialize device state teardown" so that only one caller frees the device state.
Quoted 4 lines
net/xfrm/xfrm_state.c +0
-0
[ ... ]
Quoted 9 lines
net/xfrm/xfrm_state.c +0
-1@@ -1018,7 +1015,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali out:spin_unlock_bh (&net->xfrm.xfrm_state_lock); -mutex_lock (&xfrm_state_gc_mutex);spin_lock_bh (&xfrm_state_dev_gc_lock);hlist_for_each_entry_safe (x, tmp, &xfrm_state_dev_gc_list, dev_gclist) { xso = &x->xso;
net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1036
Quoted 7 lines
net/xfrm/xfrm_state.c +0
-1@@ -1035,7 +1031,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali } }spin_unlock_bh (&xfrm_state_dev_gc_lock); -mutex_unlock (&xfrm_state_gc_mutex);if (!hlist_empty (&flush_list))synchronize_rcu ();
[Severity: Medium]
The commit message says "Nothing is left for the mutex to protect". With "xfrm: Serialize device state teardown" applied, can xfrm_dev_state_flush() still return before all of the device state for dev has been freed?
The dev_gclist walk in xfrm_dev_state_flush() skips any matching state whose refcount is already zero:
if (xso->dev == dev) {
if (!refcount_inc_not_zero(&x->refcnt))
continue;This relies on the state GC freeing that state, and on the trailing xfrm_flush_gc() waiting for it. However, xfrm_state_put() drops the count to zero before the GC work is queued:
include/net/xfrm.h:xfrm_state_put() {
if (refcount_dec_and_test(&x->refcnt))
__xfrm_state_destroy(x);
}net/xfrm/xfrm_state.c:__xfrm_state_destroy() {
...
spin_lock_bh(&xfrm_state_gc_lock);
hlist_add_head(&x->gclist, &xfrm_state_gc_list);
spin_unlock_bh(&xfrm_state_gc_lock);
schedule_work(&xfrm_state_gc_work);
}Consider this interleaving:
CPU B (e.g. netlink delete, process context)xfrm_state_put(x)
refcount_dec_and_test() -> refcnt == 0
<preempted before __xfrm_state_destroy()>
CPU A (NETDEV_DOWN or NETDEV_UNREGISTER for the same dev) xfrm_dev_state_flush()
refcount_inc_not_zero() fails, x is skipped flush_list is empty, so synchronize_rcu() is skipped xfrm_flush_gc()
flush_work() returns at once, nothing is queued yet
Even when synchronize_rcu() does run because other states were collected, it doesn't wait for a preemptible process-context putter.
In that case the flush returns while x->xso.dev, the netdev tracker reference and the driver offload context are all still live. The driver's xdo_dev_state_free() and netdev_put() then run later from xfrm_state_gc_task(). That is after xfrm_dev_down(), xfrm_dev_unregister() or bond_master_netdev_event() has already finished.
At the series base, the flush called xfrm_dev_state_free() on every matching dev_gclist entry whatever its refcount was, and the mutex kept the GC from destroying it at the same time.
The mutex didn't cover this gap either. The window comes from the skip-on-refcnt==0 logic added in "xfrm: Serialize device state teardown", which this revert depends on. The code is unchanged at the end of the series.
If a driver tears down its offload resources once the notifier returns, could xdo_dev_state_free() then run against that torn-down state? On unregister, would netdev_wait_allrefs() also be delayed until the GC work runs?
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerRe: [PATCH 21/22] Revert "xfrm: serialize state GC with device state flush"
Ccing the author of the patch.
Quoted 104 lines · On Wed, Dec 02, 2026 at 01:12:34PM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Critical: 0 · High: 0 · Medium: 1 · Low: 0
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]
xfrm_dev_state_flush()innet/xfrm/xfrm_state.cno longer guarantees that all device offload state fordevhas been freed when…--
Revert "xfrm: serialize state GC with device state flush"
This reverts the
xfrm_state_gc_mutex. That mutex serializedxfrm_state_gc_task()with thedev_gclistwalk inxfrm_dev_state_flush(). The flush now takes a reference on each state it frees, and it relies on "xfrm: Serialize device state teardown" so that only one caller frees the device state.Quoted 4 lines
net/xfrm/xfrm_state.c +0
-0[ ... ]
Quoted 9 lines
net/xfrm/xfrm_state.c +0
-1@@ -1018,7 +1015,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali out:spin_unlock_bh (&net->xfrm.xfrm_state_lock); -mutex_lock (&xfrm_state_gc_mutex);spin_lock_bh (&xfrm_state_dev_gc_lock);hlist_for_each_entry_safe (x, tmp, &xfrm_state_dev_gc_list, dev_gclist) { xso = &x->xso;net/xfrm/xfrm_state.c int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali · line 1036
Quoted 7 lines
net/xfrm/xfrm_state.c +0
-1@@ -1035,7 +1031,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali } }spin_unlock_bh (&xfrm_state_dev_gc_lock); -mutex_unlock (&xfrm_state_gc_mutex);if (!hlist_empty (&flush_list))synchronize_rcu ();[Severity: Medium]
The commit message says "Nothing is left for the mutex to protect". With "xfrm: Serialize device state teardown" applied, can
xfrm_dev_state_flush()still return before all of the device state for dev has been freed?The
dev_gclistwalk inxfrm_dev_state_flush()skips any matching state whose refcount is already zero:if (xso->dev == dev) { if (!refcount_inc_not_zero(&x->refcnt)) continue;This relies on the state GC freeing that state, and on the trailing
xfrm_flush_gc()waiting for it. However,xfrm_state_put()drops the count to zero before the GC work is queued:include/net/xfrm.h:xfrm_state_put() { if (refcount_dec_and_test(&x->refcnt)) __xfrm_state_destroy(x); }net/xfrm/xfrm_state.c:__xfrm_state_destroy() { ... spin_lock_bh(&xfrm_state_gc_lock); hlist_add_head(&x->gclist, &xfrm_state_gc_list); spin_unlock_bh(&xfrm_state_gc_lock); schedule_work(&xfrm_state_gc_work); }Consider this interleaving:
CPU B (e.g. netlink delete, process context)
xfrm_state_put(x)
refcount_dec_and_test()-> refcnt == 0
<preempted before__xfrm_state_destroy()>CPU A (
NETDEV_DOWNorNETDEV_UNREGISTERfor the same dev)xfrm_dev_state_flush()
refcount_inc_not_zero()fails, x is skippedflush_listis empty, sosynchronize_rcu()is skippedxfrm_flush_gc()
flush_work()returns at once, nothing is queued yetEven when
synchronize_rcu()does run because other states were collected, it doesn't wait for a preemptible process-context putter.In that case the flush returns while
x->xso.dev, the netdev tracker reference and the driver offload context are all still live. The driver'sxdo_dev_state_free()andnetdev_put()then run later fromxfrm_state_gc_task(). That is afterxfrm_dev_down(),xfrm_dev_unregister()orbond_master_netdev_event()has already finished.
Quoted 8 lines
At the series base, the flush called
xfrm_dev_state_free()on every matchingdev_gclistentry whatever its refcount was, and the mutex kept the GC from destroying it at the same time.The mutex didn't cover this gap either. The window comes from the skip-on-refcnt==0 logic added in "xfrm: Serialize device state teardown", which this revert depends on. The code is unchanged at the end of the series.
We had this race already before this series. Should be fixed, but also with a followup.
Quoted 7 lines
If a driver tears down its offload resources once the notifier returns, could
xdo_dev_state_free()then run against that torn-down state? On unregister, wouldnetdev_wait_allrefs()also be delayed until the GC work runs?Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261201124252.1163254-2-steffen.klassert%40secunet.com
Steffen Klassert
maintainerPATCH 22/22 xfrm: Serialize offload stats updates with x->lock
In reply to Steffen KlassertFrom: Jianbo Liu <[email protected]>
xfrm_dev_state_update_stats() calls into the driver, which adds to x->curlft and x->stats what the device counted since the last call. Callers use different locks, so two of them can refresh the same state at once and count the same packets twice, and a dump can copy the counters while another caller updates them.
Serialize all device stats refreshes with x->lock and assert it in xfrm_dev_state_update_stats(). Build the SA message of a netlink dump, get or notification under the same lock.
The SA dump and xfrm_state_update_stats() walk the states under xfrm_state_lock, where x->lock cannot be taken: the lock order is x->lock, then xfrm_state_lock. Add xfrm_state_walk_batch(), which takes references on at most 32 states per xfrm_state_lock hold, and handle each state under x->lock after the list lock is dropped. States rejected by the dump filter count against the 32, so a filter that matches few states cannot keep the list lock held over the whole list. xfrm_state_walk() cannot give this bound: it calls back only for states that pass the filter. Walk markers and states being deleted do not count, so a call always covers 32 states or reaches the end of the list.
Keep the refresh right before each state is copied, so every part of a multi-part dump still has current counters. When a state does not fit into the skb, put the walk marker back in front of it and drop the references, so no state stays referenced between two dump calls. If the state was unlinked meanwhile, skip it and go on.
copy_to_user_state() cannot take x->lock itself: build_expire() calls it with the lock held. Move the refresh out of it and let each caller refresh under x->lock. PF_KEY never refreshed and does not change.
--- include/net/xfrm.h | 12 ++++++ net/xfrm/xfrm_state.c | 87 +++++++++++++++++++++++++++++++++++++++---- net/xfrm/xfrm_user.c | 45 ++++++++++++++++++++-- 3 files changed, 133 insertions(+), 11 deletions(-)
include/net/xfrm.h +12 -0
@@ -130,6 +130,13 @@ struct xfrm_state_walk {struct xfrm_address_filter *filter; }; +#define XFRM_STATE_WALK_BATCH_SIZE 32 + +struct xfrm_state_walk_batch { +struct xfrm_state *states[XFRM_STATE_WALK_BATCH_SIZE ]; +unsigned int count; +}; +enum {XFRM_DEV_OFFLOAD_IN =1 ,XFRM_DEV_OFFLOAD_OUT ,
@@ -1716,6 +1723,9 @@ void xfrm_state_walk_init(struct xfrm_state_walk *walk, u8 proto, struct xfrm_address_filter *filter);int xfrm_state_walk (struct net *net,struct xfrm_state_walk *walk,int (*func)(struct xfrm_state *,int ,void *),void *); +bool xfrm_state_walk_batch (struct net *net,struct xfrm_state_walk *walk, +struct xfrm_state_walk_batch *batch); +bool xfrm_state_walk_rewind (struct xfrm_state_walk *walk,struct xfrm_state *x);void xfrm_state_walk_done (struct xfrm_state_walk *walk,struct net *net);struct xfrm_state *xfrm_state_alloc (struct net *net);void xfrm_state_free (struct xfrm_state *x);
@@ -1740,6 +1750,8 @@ static inline void xfrm_dev_state_update_stats(struct xfrm_state *x)struct xfrm_dev_offload *xdo = &x->xso;struct net_device *dev =READ_ONCE (xdo->dev); +lockdep_assert_held (&x->lock); +if (dev && dev->xfrmdev_ops && dev->xfrmdev_ops->xdo_dev_state_update_stats) dev->xfrmdev_ops->xdo_dev_state_update_stats (x);
net/xfrm/xfrm_state.c +80 -7
101 lines not on this page · raw message
net/xfrm/xfrm_user.c +41 -4
94 lines not on this page · raw message
Signature · 1 line
2.53.0
Paolo Abeni
maintainerQuoted 96 lines · Steffen Klassert
1) xfrm: ipcomp: account full fragment pages in truesize Charge the decompressed IPComp skb a page-rounded truesize, so the socket memory accounting matches the pages actually attached.
2) xfrm: esp: reset outer TCP GSO metadata on espintcp input Reset the GSO state inherited from the outer TCP stream on ESP-in-TCP input, so a decrypted packet isn't segmented with stale metadata and multi-segment records no longer crash.
3) xfrm: keep the mode module pinned until
destroy_statereturns Hold an extra module reference across the state destroy callback, so an rmmod racing the state GC can't free the module text while the callback is still running.4) xfrm: serialize SA activation with state deletion
Take the state lock for the final VOID-to-VALID transition, so a hard expiry can't delete the state in between and leave it in the per-CPU cache.5) xfrm: keep old state references until migration deletion completes Delete the old states before dropping their lookup references, so a concurrent expiry can't free a state the migration still uses.
6) xfrm: hold migrated states through rollback
Keep a caller reference on the successor states and delete them before releasing it, so a failed migration can't touch a state that has already been reclaimed.7) xfrm: check inner family via
skb_dstforsmall_ipv6DF clearing Take the inner address family from the dst instead ofskb->protocol, so the outer DF bit is cleared for small IPv6 packets and the tunnel doesn't drop them.8) xfrm: account
XFRMA_MARKinxfrm_sa_len()
Count the mark attribute in the SA message length, so the netlink SA notifications are sized correctly.9) xfrm: replay: Fix late packet handling with ESN crypto offload Drop packets far ahead of the replay window when the ICV check runs in hardware, so a late packet can't corrupt the offloaded ESN state.
10) xfrm: fix IPv6 first-fragment protocol decode
Let the flow dissector walk past an IPv6 fragment header, so the inbound policy lookup sees the real upper-layer protocol.11) xfrm: fix selector matching for IPv6 atomic fragments Restore the port and protocol selector fields for atomic IPv6 fragments, so such packets can match a policy.
12) xfrm: espintcp: read the socket error queue for
MSG_ERRQUEUERead the error queue through the socket error path, so a queued timestamp is reported instead of being consumed as an IKE message.13) xfrm: iptfs: force a dst reference before queueing an skb Take a dst reference while the packet is still under RCU, so the deferred IPTFS output doesn't use a dst that may already be gone.
14) xfrm: espintcp: select receive path by skb protocol Pick the receive path from the packet protocol instead of the socket family, so an IPv4 packet on a v4-mapped socket isn't parsed by the IPv6 path.
15) net: xfrm: interface: restore
dst_origon every xfrm interface Restore the original route in both arms of the interface xmit path, so a steered packet finds a policy and the metadata dst is left untouched.16) xfrm: iptfs: make room before copying a continuation in reassembly Grow the skb head before copying a reassembly continuation, so a larger continuation doesn't overrun the buffer and panic.
17) xfrm/compat: pass on the translated length of a socket policy Pass the translated policy length to the 32-bit compat layer, so the last template isn't dropped and an ESP-required policy doesn't fall back to clear text.
18) xfrm: Give GC list nodes their own storage
Give the GC and hash list nodes separate storage, so adding a state to the GC list can't corrupt the hash linkage that RCU readers still follow.19) xfrm: Serialize device state teardown
Let only one caller free the device state and hold a reference in the flush, so the state GC and a device flush can't free the same state.20) xfrm: Wait for an RCU grace period before freeing device state Wait for an RCU grace period after collecting the device states, so the driver state isn't freed while readers are still using it.
21) Revert "xfrm: serialize state GC with device state flush" Revert the GC and flush mutex, since the reference handling and the single-free rule make it unnecessary and it can't cover the lookup path.
Quoted 4 lines
22) xfrm: Serialize offload stats updates with
x->lockSerialize the offload stats refresh with the state lock, so the counters aren't updated twice and a dump doesn't copy them while they change.
Sashiko had some feedback with high and mid priority, could you please double check if valid or if could be deferred to later work?
Thanks!
Paolo