7.3.7-rc1 review
Subsystems (3)
Greg Kroah-Hartman
maintainerPATCH 106/1005 bpf: Dont let bpf_skb_adjust_room() raise gso_size to GSO_BY_FRAGS
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit 6d8118937ba477e03fa2e94e9bd9abac7291a2a2 ]
When bpf_skb_adjust_room() shrinks a TCP GSO skb, it adds the number of removed bytes to gso_size. gso_size has 16 bits, and nothing checks the sum. Thus gso_size can wrap to 0 or to a small size, or it can be GSO_BY_FRAGS. GSO_BY_FRAGS is not a size. It tells skb_segment() to read the length of each segment from the frag_list. If the TCP GSO skb has no frag_list, skb_segment() dereferences a NULL pointer.
Return -ENOTSUPP and do not change the skb if the sum is GSO_BY_FRAGS or larger. With BPF_F_ADJ_ROOM_FIXED_GSO the helper does not change gso_size, so it shrinks the skb as before.
--- net/core/filter.c | 8 ++++++++ 1 file changed, 8 insertions(+)
net/core/filter.c +8 -0
@@ -3762,6 +3762,14 @@ static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff,return -ENOTSUPP ; } +/* +* The MSS is raised by len_diff. It has 16 bits, and GSO_BY_FRAGS is +* not a size. +*/ +if (skb_is_gso (skb) && !(flags &BPF_F_ADJ_ROOM_FIXED_GSO ) && +skb_shinfo (skb)->gso_size + len_diff >=GSO_BY_FRAGS ) +return -ENOTSUPP ; + ret =skb_unclone (skb,GFP_ATOMIC );if (unlikely (ret <0 ))return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 107/1005 bpf: Reject non-IPv6 packets in BPF_LWT_ENCAP_SEG6
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit 58e39f8d58b141b96c030008a20dde9d625ec997 ]
The mode BPF_LWT_ENCAP_SEG6 of bpf_lwt_push_encap() pushes an IPv6 header and an SRH, and it replaces the dst. The SRH says that IPv6 follows, and skb->protocol does not change. Thus the mode assumes an IPv6 packet, but an lwt_in prog also runs for IPv4 packets. After the prog, bpf_input() calls orig_input() of the old dst. This IPv4 handler reads the pushed headers as IPv4. It can write after the packet data, and the kernel crashes.
after the push orig_input() expects
--------------------- --------------------
skb->protocol ETH_P_IP ETH_P_IP
dst rt6_info rtable
packet | IPv6 | SRH | IPv4 | | IPv4 |The mode BPF_LWT_ENCAP_SEG6_INLINE returns -EBADMSG for non-IPv6 packets. Apply this check to both modes. End.BPF does not change, because seg6_local_input() drops non-IPv6 packets.
--- net/core/filter.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
net/core/filter.c +7 -3
@@ -6927,11 +6927,15 @@ static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 lenif (!seg6_validate_srh (srh, len, false))return -EINVAL ; +/* +* The encap mode names IPv6 as the inner protocol, and neither mode +* updates skb->protocol. +*/ +if (skb->protocol !=htons (ETH_P_IPV6 )) +return -EBADMSG ; +switch (type) {case BPF_LWT_ENCAP_SEG6_INLINE : -if (skb->protocol !=htons (ETH_P_IPV6 )) -return -EBADMSG ; - err =seg6_do_srh_inline (skb, srh);break ;case BPF_LWT_ENCAP_SEG6 :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 108/1005 bpf: Set a dst for test runs of lwt_in progs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit c1ca06e48e8848743fd876a1dc6b0f57bc76d23e ]
When an lwt prog runs on a route, the skb always has a dst. To push an SRH, bpf_lwt_push_encap() reads the device from this dst. But bpf_prog_test_run_skb() sets a dst for lwt_xmit progs only. Thus the helper dereferences a NULL dst in a test run of an lwt_in prog.
Set the same dst, ip6_null_entry, for lwt_in progs. When IPv6 is disabled or not built, their test run now fails with -EOPNOTSUPP too. An lwt_out prog cannot call this helper.
--- net/bpf/test_run.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/bpf/test_run.c +2 -1
@@ -1210,7 +1210,8 @@ int bpf_prog_test_run_skb(struct bpf_prog *prog, const union bpf_attr *kattr, skb->ip_summed =CHECKSUM_COMPLETE ; } -if (prog->type ==BPF_PROG_TYPE_LWT_XMIT ) { +if (prog->type ==BPF_PROG_TYPE_LWT_IN || + prog->type ==BPF_PROG_TYPE_LWT_XMIT ) {if (!ipv6_mod_enabled ()) {pr_warn_once ("Please test this program with IPv6 enabled kernel\n" ); ret = -EOPNOTSUPP ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 109/1005 bpf: Limit the SRH length in bpf_lwt_seg6_adjust_srh()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit ac159f39b252971141c49b68a27de0b637debfad ]
bpf_lwt_seg6_adjust_srh() lets an End.BPF prog change the size of the TLVs in the SRH. The helper keeps the SRH length in srh_state->hdrlen, in bytes and without the first 8 bytes. Later seg6_bpf_has_valid_srh() writes it to srh->hdrlen, an 8-bit field in units of 8 bytes. But srh_state->hdrlen has no upper limit, and the cast to u8 can truncate it. After that, seg6_validate_srh() gets the SRH length from srh->hdrlen, and thus it can accept the SRH. Then srh->hdrlen is too small, and a parser reads TLVs as the subsequent header.
Return -EFAULT when the new srh_state->hdrlen is larger than 2040, the largest length that srh->hdrlen can hold. To replace a TLV in the largest SRH, a prog can no longer add bytes first. It must remove bytes first.
--- net/core/filter.c | 3 +++ 1 file changed, 3 insertions(+)
net/core/filter.c +3 -0
@@ -7179,6 +7179,9 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,return -EFAULT ;if (unlikely (len <0 && (void *)((char *)ptr - len) > srh_end))return -EFAULT ; +/* The length field of the SRH has 8 bits, in units of 8 bytes. */ +if (unlikely (len > (U8_MAX <<3 ) - srh_state->hdrlen)) +return -EFAULT ;if (len >0 ) { ret =skb_cow_head (skb, len);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 110/1005 bpf: Dont look for the SRH again in the End.BPF helpers
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit 45bcc58d576705d2c001332766e10313f1c55bad ]
A packet can have two SRHs. Thus input_action_end_bpf() uses IP6_FH_F_SKIP_RH to skip routing headers with segments_left 0. The helpers bpf_lwt_seg6_store_bytes() and bpf_lwt_seg6_adjust_srh() can reallocate the head of the skb. Thus they look for the SRH again, but without this flag.
+------------------------+ <- the helpers: srh_state->srh | SRH 1, segments_left 0 | +------------------------+ <- input_action_end_bpf(): srh_state->srh | SRH 2 | and srh_state->hdrlen +------------------------+
Then the helpers check offset against the wrong limits. If a helper changes TLVs, seg6_bpf_has_valid_srh() writes the length of SRH 2 to SRH 1.
Neither helper changes the offset of the SRH from skb->data. Calculate the new address from this offset. To add IP6_FH_F_SKIP_RH is not sufficient, because advance_nextseg() can set segments_left of SRH 2 to 0. The helper bpf_lwt_seg6_action() can change the headers and still looks for the SRH.
--- net/core/filter.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
net/core/filter.c +6 -6
@@ -7024,12 +7024,13 @@ BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,this_cpu_ptr (&seg6_bpf_srh_states);struct ipv6_sr_hdr *srh = srh_state->srh;void *srh_tlvs, *srh_end, *ptr; -int srhoff =0 ; +int srhoff;lockdep_assert_held (&srh_state->bh_lock);if (srh ==NULL )return -EINVAL ; + srhoff = (unsigned char *)srh - skb->data; srh_tlvs = (void *)((char *)srh + ((srh->first_segment +1 ) <<4 )); srh_end = (void *)((char *)srh +sizeof (*srh) + srh_state->hdrlen);
@@ -7042,8 +7043,7 @@ BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,if (unlikely (bpf_try_make_writable (skb, offset + len)))return -EFAULT ; -if (ipv6_find_hdr (skb, &srhoff,IPPROTO_ROUTING ,NULL ,NULL ) <0 ) -return -EINVAL ; +/* The head may have moved. */ srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);memcpy (skb->data + offset, from, len);
@@ -7162,13 +7162,14 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,struct ipv6_sr_hdr *srh = srh_state->srh;void *srh_end, *srh_tlvs, *ptr;struct ipv6hdr *hdr; -int srhoff =0 ; +int srhoff;int ret;lockdep_assert_held (&srh_state->bh_lock);if (unlikely (srh ==NULL ))return -EINVAL ; + srhoff = (unsigned char *)srh - skb->data; srh_tlvs = (void *)((unsigned char *)srh +sizeof (*srh) + ((srh->first_segment +1 ) <<4 )); srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
@@ -7200,8 +7201,7 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset, hdr = (struct ipv6hdr *)skb->data; hdr->payload_len =htons (skb->len -sizeof (struct ipv6hdr )); -if (ipv6_find_hdr (skb, &srhoff,IPPROTO_ROUTING ,NULL ,NULL ) <0 ) -return -EINVAL ; +/* The bytes in front of offset have moved together with skb->data. */ srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); srh_state->hdrlen += len; srh_state->valid = false;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 111/1005 bpf: Move the MAC header in bpf_lwt_seg6_adjust_srh()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit 0fcb3f11a93d740e7f9ae1aeb48fe4d25838be18 ]
bpf_skb_net_hdr_push() and bpf_skb_net_hdr_pop() change skb->data and skb->mac_header by len. That is correct in a tc prog, where skb->data is the MAC header. But bpf_lwt_seg6_adjust_srh() calls them in an End.BPF prog, where skb->data is the network header. The MAC header does not move:
before push | free | MAC header | IPv6 | SRH | payload
^ head ^ mac_header ^ data
today | free | MAC h| IPv6 | SRH + len | payload
^ head ^ mac_header ^ data
this patch | free | MAC header | IPv6 | SRH + len | payload
^ head ^ mac_header ^ dataUsers of skb_mac_header() get incorrect bytes until __dev_queue_xmit() sets skb->mac_header again. skb_cow_head() reserves only len bytes. Thus the 16-bit offset skb->mac_header can wrap. A push also changes the "not set" value. In both cases skb_mac_header() points after the skb.
Move the MAC header too. Pass len + skb->mac_len to skb_cow_head(). Keep the "not set" value. The second Fixes tag is for this case. Since that commit an End.BPF prog can get an skb with skb->mac_header not set.
--- net/core/filter.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-)
net/core/filter.c +20 -1
@@ -7159,6 +7159,7 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset, {struct seg6_bpf_srh_state *srh_state =this_cpu_ptr (&seg6_bpf_srh_states); +bool mac_set =skb_mac_header_was_set (skb);struct ipv6_sr_hdr *srh = srh_state->srh;void *srh_end, *srh_tlvs, *ptr;struct ipv6hdr *hdr;
@@ -7184,20 +7185,38 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,if (unlikely (len > (U8_MAX <<3 ) - srh_state->hdrlen))return -EFAULT ; +/* +* skb->data is the network header here. The MAC header is in front of +* it, so bpf_skb_net_hdr_push() and bpf_skb_net_hdr_pop() do not move +* it with the other headers. +*/ if (len >0 ) { - ret =skb_cow_head (skb, len); + ret =skb_cow_head (skb, len + skb->mac_len);if (unlikely (ret <0 ))return ret; +/* The push can write over the MAC header, so move it first. */ +if (mac_set) +memmove (skb->data - len - skb->mac_len, +skb_mac_header (skb), skb->mac_len); ret =bpf_skb_net_hdr_push (skb, offset, len); }else { ret =bpf_skb_net_hdr_pop (skb, offset,-1 * len); +/* The pop has added -len to skb->mac_header. */ +if (likely (!ret) && mac_set) +memmove (skb->data - skb->mac_len, +skb_mac_header (skb) + len, skb->mac_len); }bpf_compute_data_pointers (skb);if (unlikely (ret <0 ))return ret; +if (mac_set) +skb_set_mac_header (skb, -skb->mac_len); +else +skb_unset_mac_header (skb); + hdr = (struct ipv6hdr *)skb->data; hdr->payload_len =htons (skb->len -sizeof (struct ipv6hdr ));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 112/1005 bpf: Dont leave a stale MAC header in bpf_lwt_push_ip_encap()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit 701ffd202b9e32942c8cfc065c9fe76ceaccc302 ]
With BPF_LWT_ENCAP_IP, bpf_lwt_push_encap() pushes a new IP header. The new header overwrites the MAC header of a received skb. But skb->mac_header continues to point to the same bytes. Code that reads the MAC header after the push, for example netfilter, gets bytes of the new header.
before the push | MAC header | old IP | payload
^ mac_header ^ network_header
today | new header | old IP | payload
network_header ^ ^ mac_header
this patch, lwt_in | MAC header | new header | old IP | payload
^ mac_header ^ network_header
this patch, lwt_xmit | new header | old IP | payload network_header ^ mac_header is not set
For lwt_in, move the MAC header in front of the new header before the memcpy(), as __seg6_do_srh_encap() does. skb_cow_head() already reserves len + skb->mac_len bytes.
For lwt_xmit, the output path makes a new MAC header. Thus mark skb->mac_header as not set. This is the state of a locally generated skb.
--- net/core/lwt_bpf.c | 8 ++++++++ 1 file changed, 8 insertions(+)
net/core/lwt_bpf.c +8 -0
@@ -649,6 +649,14 @@ int bpf_lwt_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len, bool ingress)if (ingress)skb_postpush_rcsum (skb, iph, len);skb_reset_network_header (skb); +/* +* The new header goes over the MAC header. On ingress move it first. +* On egress the packet gets a new one, so forget the old one. +*/ +if (ingress) +skb_mac_header_rebuild (skb); +else +skb_unset_mac_header (skb);if (is_udp_tunnel) {size_t iph_sz = ipv4 ? iph->ihl *4 :sizeof (struct ipv6hdr );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 113/1005 bpf: Reset skb->cb after an lwt prog pushes an IP header
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit b3ad42f6183286ab376389a5d26edf7ee3bdba27 ]
IPCB(skb)->opt holds the offsets from the network header to the IPv4 options. But bpf_lwt_push_ip_encap() moves the network header and does not change IPCB(skb). Then ip_forward_options() and __ip_options_echo() use the old offsets on the pushed header. Thus the kernel corrupts the skb and the stack. If the family changes, the kernel also reads IP6CB(skb) as IPCB(skb), or the reverse. With CONFIG_IPV6_MIP6, it reads IPSKB_FORWARDED as frag_max_size and adds a needless fragment header.
Reset skb->cb after the prog. bpf_lwt_push_ip_encap() cannot do it, because bpf_prog_run_save_cb() can restore skb->cb. For IPv4 in IPv4, clear IPCB(skb)->opt as ip_tunnel_xmit() does. If the family changes, clear the cb of the new family but keep iif, because ip6_forward() gets the input device from it. Behind a VRF, skb->skb_iif is the VRF device and cannot replace iif. Do nothing for IPv6 in IPv6, as in seg6_do_srh_encap().
Do the reset in bpf_input() only after a push. Without a push, ip_forward_options() needs the offsets. Do it in bpf_xmit() before each reroute, because an lwt_xmit prog can also change the options. Thus after a reroute without a push, ip_options_fragment() leaves the options in all fragments, and ICMP errors echo none. After BPF_OK or BPF_REDIRECT the skb goes to a device, thus bpf_xmit() does no reset. The inner IPv4 checksum can still be wrong after ip_rcv_options() changes an option.
--- net/core/lwt_bpf.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+)
net/core/lwt_bpf.c +33 -0
@@ -85,6 +85,32 @@ static int run_lwt_bpf(struct sk_buff *skb, struct bpf_lwt_prog *lwt,return ret; } +/* +* skb->cb still describes the IP header that was the first one before the +* prog ran. The option offsets in IPCB(skb)->opt are wrong for a pushed +* header, and a header of the other family needs the other layout. iif +* stays: behind a VRF skb->skb_iif is the L3 master and not the port. +* bpf_lwt_push_encap() cannot do this, because bpf_prog_run_save_cb() can +* restore skb->cb after the prog. +*/ +static void bpf_lwt_reset_cb (struct sk_buff *skb,__be16 proto) +{ +int iif; + +if (skb->protocol == proto) { +if (proto ==htons (ETH_P_IP )) +memset (&IPCB (skb)->opt,0 ,sizeof (IPCB (skb)->opt)); + }else if (skb->protocol ==htons (ETH_P_IP )) { + iif =IP6CB (skb)->iif; +memset (IPCB (skb),0 ,sizeof (*IPCB (skb))); +IPCB (skb)->iif = iif; + }else { + iif =IPCB (skb)->iif; +memset (IP6CB (skb),0 ,sizeof (*IP6CB (skb))); +IP6CB (skb)->iif = iif; + } +} +static int bpf_lwt_input_reroute (struct sk_buff *skb) {enum skb_drop_reason reason;
@@ -124,6 +150,8 @@ static int bpf_lwt_input_reroute(struct sk_buff *skb)static int bpf_input (struct sk_buff *skb) {struct dst_entry *dst =skb_dst (skb); +__be16 proto = skb->protocol; +unsigned int len = skb->len;struct bpf_lwt *bpf;int ret;
@@ -132,6 +160,9 @@ static int bpf_input(struct sk_buff *skb) ret =run_lwt_bpf (skb, &bpf->in, dst,NO_REDIRECT );if (ret <0 )return ret; +/* An lwt_in prog can change the length only with a push. */ +if (skb->len != len) +bpf_lwt_reset_cb (skb, proto);if (ret ==BPF_LWT_REROUTE )return bpf_lwt_input_reroute (skb); }
@@ -311,6 +342,8 @@ static int bpf_xmit(struct sk_buff *skb)case BPF_REDIRECT :return LWTUNNEL_XMIT_DONE ;case BPF_LWT_REROUTE : +/* An lwt_xmit prog can also write to the options. */ +bpf_lwt_reset_cb (skb, proto);return bpf_lwt_xmit_reroute (skb);default :return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 114/1005 bpf: Require BPF_LWT_REROUTE when an lwt_in prog changes the protocol
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit d9618a6196953718f7470de5d2e84121bed063f7 ]
When an lwt_in prog returns BPF_OK, bpf_input() calls orig_input(), the input handler of the route. This handler is for one IP version and needs a dst of the same family. But BPF_LWT_ENCAP_IP lets the prog push a header of the other IP version and thus change skb->protocol. Then the handler reads and changes a header of the other IP version. The push of an SRH also replaces the dst, because seg6_lookup_nexthop() puts an rt6_info into the skb. Then ip_forward() uses the rt6_info as a struct rtable.
Drop the skb with -EINVAL when skb->protocol changes, as bpf_xmit() does. Drop it also when the family of the dst changes, because skb->protocol does not always show this change. Today no such skb leaves as the prog made it. A prog works as before if it returns BPF_LWT_REROUTE, or if it pushes an SRH on an IPv6 route.
The commit in the first Fixes tag lets a prog change skb->protocol. The commit in the second tag adds the check to bpf_xmit() only.
--- net/core/lwt_bpf.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
net/core/lwt_bpf.c +10 -0
@@ -165,6 +165,16 @@ static int bpf_input(struct sk_buff *skb)bpf_lwt_reset_cb (skb, proto);if (ret ==BPF_LWT_REROUTE )return bpf_lwt_input_reroute (skb); +/* +* orig_input() is for the old protocol only, see bpf_xmit(). +* It also needs a dst of the old family. BPF_LWT_ENCAP_SEG6 +* puts an IPv6 dst into the skb. +*/ +if (skb->protocol != proto || +skb_dst (skb)->ops->family != dst->ops->family) { +kfree_skb (skb); +return -EINVAL ; + } }if (unlikely (!dst->lwtstate->orig_input)) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 115/1005 bpf: Dont let lwt_in progs call into IPv6 when it is disabled
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit 95f1d5e4abb79fe85a54f7a46b41f297ce533c31 ]
With ipv6.disable=1, inet6_init() returns before it registers any pernet subsystem. Thus net->ipv6.devconf_all and net->ipv6.seg6_data stay NULL. IS_ENABLED(CONFIG_IPV6) only says that the code is built in. bpf_lwt_input_reroute() and bpf_push_seg6_encap() call into IPv6, but do not test ipv6_mod_enabled(). An lwt_in prog also runs with ipv6.disable=1, and skb->protocol == htons(ETH_P_IPV6) does not prove that IPv6 is enabled. Thus the kernel dereferences NULL and crashes.
Return -EAFNOSUPPORT before these calls if ipv6_mod_enabled() is false. BPF_LWT_REROUTE then drops an IPv6 skb. With IPv6 enabled nothing changes.
The first Fixes tag is for bpf_push_seg6_encap(), which never had this test. The second tag is for bpf_lwt_input_reroute(). Until that commit it used ipv6_stub, which returned -EAFNOSUPPORT with ipv6.disable=1.
--- net/core/filter.c | 4 ++++ net/core/lwt_bpf.c | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-)
net/core/filter.c +4 -0
@@ -6924,6 +6924,10 @@ static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 lenint err;struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr; +/* With ipv6.disable=1 the netns has no seg6 data and no IPv6 tables. */ +if (!ipv6_mod_enabled ()) +return -EAFNOSUPPORT ; +if (!seg6_validate_srh (srh, len, false))return -EINVAL ;
net/core/lwt_bpf.c +1 -1
@@ -128,7 +128,7 @@ static int bpf_lwt_input_reroute(struct sk_buff *skb)dev_put (dev); }else if (skb->protocol ==htons (ETH_P_IPV6 )) {skb_dst_drop (skb); -if (IS_ENABLED (CONFIG_IPV6 )) { +if (ipv6_mod_enabled ()) {ip6_route_input (skb); err =skb_dst (skb)->error; }else {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 116/1005 bpf: Move the transport header with the moved headers
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit a9d08fe60fa728ce0e3a99085241e8e790fb14c6 ]
bpf_skb_net_hdr_pop() removes len bytes at offset off. bpf_skb_net_hdr_push() does the opposite.
skb->data off
before | A | removed | B |
after | A | B |
skb->data offmac_header and network_header move with A. transport_header moves only when it is equal to network_header. inner_transport_header never moves. This is correct only for a header in B. In bpf_lwt_seg6_adjust_srh() transport_header is in A. bpf_skb_adjust_room() can remove both transport headers. With an incorrect header offset, the stack can drop the skb or read outside of it.
Also move transport_header with A when it is in A. Set it to offset off when it is in the removed bytes. In BPF_ADJ_ROOM_MAC mode it is then equal to network_header. Do not unset it, because skb_gso_validate_mac_len() uses it without a check. After a removal, set inner_transport_header to off when it is not in B and skb->encapsulation is set. A has only outer headers.
--- net/core/filter.c | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-)
net/core/filter.c +31 -6
@@ -3402,9 +3402,25 @@ static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)return 0 ; } +/* +* bpf_skb_net_hdr_push() inserts bytes at @off, bpf_skb_net_hdr_pop() removes +* bytes at @off. Both move the bytes in front of @off together with skb->data, +* and leave the rest of the packet where it is. Return true if the transport +* header is in the part that moves. A transport header that is equal to the +* network header stays equal to it. +*/ +static bool bpf_skb_trans_hdr_moves (const struct sk_buff *skb,u32 off) +{ +if (skb->transport_header == skb->network_header) +return true; + +return skb_transport_header_was_set (skb) && + (u32 )skb_transport_offset (skb) < off; +} +static int bpf_skb_net_hdr_push (struct sk_buff *skb,u32 off,u32 len) { -bool trans_same = skb->transport_header == skb->network_header; +bool trans_moves =bpf_skb_trans_hdr_moves (skb, off);int ret;/* There's no need for __skb_push()/__skb_pull() pair to
@@ -3415,8 +3431,8 @@ static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)if (likely (!ret)) { skb->mac_header -= len; skb->network_header -= len; -if (trans_same) - skb->transport_header = skb->network_header; +if (trans_moves) + skb->transport_header -= len; }return ret;
@@ -3424,7 +3440,7 @@ static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)static int bpf_skb_net_hdr_pop (struct sk_buff *skb,u32 off,u32 len) { -bool trans_same = skb->transport_header == skb->network_header; +bool trans_moves =bpf_skb_trans_hdr_moves (skb, off);int ret;/* Same here, __skb_push()/__skb_pull() pair not needed. */
@@ -3432,8 +3448,17 @@ static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)if (likely (!ret)) { skb->mac_header += len; skb->network_header += len; -if (trans_same) - skb->transport_header = skb->network_header; +if (trans_moves) { + skb->transport_header += len; + }else if (skb_transport_header_was_set (skb) && +skb_transport_offset (skb) < (int )off) { +/* It was in the removed bytes or before skb->data. */ +skb_set_transport_header (skb, off); + } +/* Do not leave the inner transport header in front of @off. */ +if (skb->encapsulation && +skb_inner_transport_offset (skb) < (int )off) +skb_set_inner_transport_header (skb, off); }return ret;
Signature · 1 line
2.53.0
Quoted 4 lines · On Wed, 25 Nov 2026 15:22:18 +0100 Greg Kroah-Hartman…
This is the start of the stable review cycle for the 7.3.7 release. There are 1005 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
This rc kernel passes DAMON functionality test [1] on my test machine.
[1] https://github.com/damonitor/damon-tests/tree/next/corr
Thanks,
SJ
[...]
Greg Kroah-Hartman
maintainerPATCH 117/1005 bpf: Use the inner transport header after a decap
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit 33be492c2e239de8c525254e593357ae5e80852d ]
If skb->encapsulation is set, qdisc_pkt_len_segs_init() reads the TCP header of a GSO packet at skb->inner_transport_header. Otherwise it uses skb->transport_header. A decap with BPF_F_ADJ_ROOM_DECAP_L4_{GRE,UDP} removes the outer transport header. It clears skb->encapsulation if no tunnel flag remains in gso_type. The result in BPF_ADJ_ROOM_MAC mode is:
before | MAC | outer IP | GRE | inner IP | TCP | payload
transport_header ^ ^ inner_transport_header
after | MAC | inner IP | TCP | payload
transport_header ^ ^ inner_transport_headerThen qdisc_pkt_len_segs_init() reads the inner IP header as a TCP header. Thus the kernel can drop a valid packet with SKB_DROP_REASON_SKB_BAD_GSO.
Copy skb->inner_transport_header to skb->transport_header when a decap clears skb->encapsulation. Keep skb->transport_header if it is larger. This occurs if nothing sets the inner field. At tc ingress nothing changes for IPIP or GRO packets. Both fields are at the TCP header there.
--- net/core/filter.c | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-)
net/core/filter.c +23 -6
@@ -3769,6 +3769,25 @@ static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff,return 0 ; } +/* +* Code that went by the inner transport header while skb->encapsulation was set +* goes by the transport header from now on. So take the inner one over, unless +* it is the smaller one, as it is if nobody has set it. Do not leave the result +* in front of @off, where the bytes were removed. +*/ +static void bpf_skb_clear_encap (struct sk_buff *skb,u32 off) +{ +int thoff; + +if (!skb->encapsulation) +return ; + + thoff =max (skb->inner_transport_header, skb->transport_header) - +skb_headroom (skb); +skb_set_transport_header (skb,max_t (int, thoff, off)); + skb->encapsulation =0 ; +} +static int bpf_skb_net_shrink (struct sk_buff *skb,u32 off,u32 len_diff,u64 flags) {
@@ -3850,8 +3869,7 @@ static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff, SKB_GSO_IPXIP4 | SKB_GSO_IPXIP6 | SKB_GSO_ESP))) -if (skb->encapsulation) - skb->encapsulation =0 ; +bpf_skb_clear_encap (skb, off); }/* Header must be checked, and gso_segs recomputed. */
@@ -3859,10 +3877,9 @@ static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff, shinfo->gso_segs =0 ; }else {/* For non-GSO packets, clear encapsulation if decap flags are set */ -if ((flags & (BPF_F_ADJ_ROOM_DECAP_L4_MASK | -BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK )) && - skb->encapsulation) - skb->encapsulation =0 ; +if (flags & (BPF_F_ADJ_ROOM_DECAP_L4_MASK | +BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK )) +bpf_skb_clear_encap (skb, off); }return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 118/1005 bpf: Check the offset in bpf_skb_generic_{push,pop}()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit ee36c9aa44ef300cd651074bd97552b229337f85 ]
To make room for len bytes at offset off, bpf_skb_generic_push() moves the first off bytes and clears len bytes after them. It assumes that the first off bytes are in the linear part. But in bpf_skb_adjust_room() off can be the end of the IP header, and this header can be in a frag. Then the function reads and writes after skb->tail, and can damage skb_shared_info.
bpf_skb_generic_pop() checks off + len, but this u32 sum can wrap to a small value. bpf_skb_adjust_room() and bpf_skb_change_proto() calculate off from skb_mac_header_len(). This length is a very large u32 when network_header < mac_header. Then the check can pass, and memmove() reads and writes far outside the skb.
Return -ENOMEM from both functions, like the present check, when off > skb->len. Thus the sum cannot wrap. In bpf_skb_generic_push() also pull the first off bytes into the linear part. Now bpf_skb_adjust_room() fails when a prog grows an skb that ends before off. network_header stays wrong.
--- net/core/filter.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
net/core/filter.c +7 -2
@@ -3369,6 +3369,10 @@ static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {static int bpf_skb_generic_push (struct sk_buff *skb,u32 off,u32 len) { +/* The bytes in front of @off are moved with skb->data. */ +if (unlikely (off > skb->len || !pskb_may_pull (skb, off))) +return -ENOMEM ; +/* Caller already did skb_cow() with meta_len+len as headroom, * so no need to do it here. */
@@ -3389,9 +3393,10 @@ static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)void *old_data;/* skb_ensure_writable() is not needed here, as we're -* already working on an uncloned skb. +* already working on an uncloned skb. The first test +* keeps off + len from wrapping. */ -if (unlikely (!pskb_may_pull (skb, off + len))) +if (unlikely (off > skb->len || !pskb_may_pull (skb, off + len)))return -ENOMEM ; old_data = skb->data;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 119/1005 ASoC: tas2770: Configure transmit clock edge when setting DAI format
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: James Calligeros <[email protected]>
[ Upstream commit 72da22e9cc380ecda175983d2a17b4494a4b9d15 ]
On reset, TAS2770 is configured to transmit on the falling edge of the I2S clock. If BCLK is inverted, we are also receiving on the falling edge. This can cause data leaving the codec to be corrupted. Transmit should happen on the rising edge of the clock when receiving on the falling edge, and vice versa.
Fix up tas2770_set_fmt to take into account the BLCK polarity and always transmit on the correct edge of the clock. This fixes corrupted VISENSE data on Apple Silicon platforms at sample rates above 48 kHz.
--- sound/soc/codecs/tas2770.c | 9 +++++++++ sound/soc/codecs/tas2770.h | 4 +++- 2 files changed, 12 insertions(+), 1 deletion(-)
sound/soc/codecs/tas2770.c +9 -0
@@ -353,6 +353,7 @@ static int tas2770_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)struct tas2770_priv *tas2770 =snd_soc_component_get_drvdata (component);u8 tdm_rx_start_slot =0 , invert_fpol =0 , fpol_preinv =0 , asi_cfg_1 =0 ; +u8 tx_edge;int ret;switch (fmt &SND_SOC_DAIFMT_CLOCK_PROVIDER_MASK ) {
@@ -369,12 +370,14 @@ static int tas2770_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) fallthrough;case SND_SOC_DAIFMT_NB_NF : asi_cfg_1 |=TAS2770_TDM_CFG_REG1_RX_RSING ; + tx_edge =TAS2770_TDM_CFG_REG4_TX_FALING ;break ;case SND_SOC_DAIFMT_IB_IF : invert_fpol =1 ; fallthrough;case SND_SOC_DAIFMT_IB_NF : asi_cfg_1 |=TAS2770_TDM_CFG_REG1_RX_FALING ; + tx_edge =TAS2770_TDM_CFG_REG4_TX_RISING ;break ;default :dev_err (tas2770->dev,"ASI format Inverse is not found\n" );
@@ -387,6 +390,12 @@ static int tas2770_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)if (ret <0 )return ret; + ret =snd_soc_component_update_bits (component,TAS2770_TDM_CFG_REG4 , +TAS2770_TDM_CFG_REG4_TX_EDGE , + tx_edge); +if (ret <0 ) +return ret; +switch (fmt &SND_SOC_DAIFMT_FORMAT_MASK ) {case SND_SOC_DAIFMT_I2S : tdm_rx_start_slot =1 ;
sound/soc/codecs/tas2770.h +3 -1
@@ -74,7 +74,9 @@#define TAS2770_TDM_CFG_REG4_TX_KEEPER BIT(5)#define TAS2770_TDM_CFG_REG4_TX_FILL BIT(4)#define TAS2770_TDM_CFG_REG4_TX_OFFSET_MASK GENMASK(3, 1) -#define TAS2770_TDM_CFG_REG4_TX_EDGE_FALLING BIT(0) +#define TAS2770_TDM_CFG_REG4_TX_EDGE BIT(0) +#define TAS2770_TDM_CFG_REG4_TX_RISING 0x0 +#define TAS2770_TDM_CFG_REG4_TX_FALING 0x1/* TDM Configuration Reg5 */ #define TAS2770_TDM_CFG_REG5 TAS2770_REG(0X0, 0x0F)#define TAS2770_TDM_CFG_REG5_VSNS_MASK BIT(6)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 120/1005 spi: Fix ACPI SPI resources using relative path
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alban Bedel <[email protected]>
[ Upstream commit 4825287f6d2346e9273f35a928d1ef40e68bc58b ]
ACPI resources can use relative path when pointing to other resources. This didn't work with SPISerialBus resources because the device defining the resource was not passed to acpi_get_handle().
Pass the ACPI device handle through the lookup context to also allow for relative paths.
Stable-dep-of: 2d0953ab69d3 ("spi: acpi: only look up the IRQ of confirmed SPI devices")
--- drivers/spi/spi.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/spi/spi.c +3 -1
@@ -2983,6 +2983,7 @@ EXPORT_SYMBOL_GPL(devm_spi_new_ancillary_device); #ifdef CONFIG_ACPI struct acpi_spi_lookup { struct spi_controller *ctlr; + acpi_handle device_handle; u32 max_speed_hz; u32 mode; int irq;
@@ -3077,7 +3078,7 @@ static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)if (lookup->index !=-1 && lookup->n++ != lookup->index)return 1 ; - status =acpi_get_handle (NULL , + status =acpi_get_handle (lookup->device_handle, sb->resource_source.string_ptr, &parent_handle);
@@ -3169,6 +3170,7 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,return ERR_PTR (-EINVAL ); lookup.ctlr = ctlr; + lookup.device_handle =acpi_device_handle (adev); lookup.irq =-1 ; lookup.index = index; lookup.n =0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 121/1005 spi: acpi: only look up the IRQ of confirmed SPI devices
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
[ Upstream commit 2d0953ab69d316589624b0517fdce01f8e630bf0 ]
When an SPI controller is registered, acpi_register_spi_device() is called for every present ACPI device in the namespace and acpi_spi_device_alloc() walks each device's _CRS. While doing so, acpi_spi_add_resource() converts the first interrupt resource it finds, even for devices that have no SpiSerialBus resource at all and are discarded right afterwards. Converting an interrupt resource registers its GSI, so this maps IRQs for arbitrary unrelated ACPI devices.
On a Dell Precision M4800 (Lynx Point, 24-pin IOAPIC) the DSDT reports Haswell-ULT LPSS child devices (\_SB.PCI0.I2C0.ACD0 and \_SB.PCI0.SDHC.WI01) as present with interrupts on GSI 37 and 38. Registering the intel-spi controller then results in:
ERROR: Unable to locate IOAPIC for GSI 37
ERROR: Unable to locate IOAPIC for GSI 38
Do what the I2C core does and only parse the interrupt resource once the device has been identified as an SPI device on this controller.
--- drivers/spi/spi.c | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-)
drivers/spi/spi.c +28 -8
@@ -2986,7 +2986,6 @@ struct acpi_spi_lookup {acpi_handle device_handle;u32 max_speed_hz;u32 mode; -int irq;u8 bits_per_word;u8 chip_select;int n;
@@ -3129,17 +3128,25 @@ static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)if (sb->device_polarity ==ACPI_SPI_ACTIVE_HIGH ) lookup->mode |=SPI_CS_HIGH ; } - }else if (lookup->irq <0 ) { -struct resource r; - -if (acpi_dev_resource_interrupt (ares,0 , &r)) - lookup->irq = r.start; }/* Always tell the ACPI core to skip this resource */ return 1 ; } +static int acpi_spi_add_irq_resource (struct acpi_resource *ares,void *data) +{ +int *irq = data; +struct resource r; + +if (*irq <0 && ares->type !=ACPI_RESOURCE_TYPE_SERIAL_BUS && +acpi_dev_resource_interrupt (ares,0 , &r)) + *irq = r.start; + +/* Always tell the ACPI core to skip this resource */ +return 1 ; +} +/** * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information * @ctlr: controller to which the spi device belongs
@@ -3164,6 +3171,7 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,struct list_head resource_list;struct acpi_spi_lookup lookup = {};struct spi_device *spi; +int irq =-1 ;int ret;if (!ctlr && index ==-1 )
@@ -3171,7 +3179,6 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr, lookup.ctlr = ctlr; lookup.device_handle =acpi_device_handle (adev); - lookup.irq =-1 ; lookup.index = index; lookup.n =0 ;
@@ -3194,6 +3201,19 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,if (!lookup.max_speed_hz)return ERR_PTR (-ENODEV ); +/* +* Only look up the IRQ once we know this is an SPI device for us. +* Parsing an interrupt resource maps its GSI, which must not be done +* for every unrelated ACPI device walked during enumeration. +*/ +INIT_LIST_HEAD (&resource_list); + ret =acpi_dev_get_resources (adev, &resource_list, + acpi_spi_add_irq_resource, &irq); +if (ret <0 ) +return ERR_PTR (ret); + +acpi_dev_free_resource_list (&resource_list); + spi =spi_alloc_device (lookup.ctlr);if (!spi) { dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
@@ -3206,7 +3226,7 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,ACPI_COMPANION_SET (&spi->dev, adev); spi->max_speed_hz = lookup.max_speed_hz; spi->mode |= lookup.mode; - spi->irq = lookup.irq; + spi->irq = irq; spi->bits_per_word = lookup.bits_per_word;/* * By default spi->chip_select[0] will hold the physical CS number,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 122/1005 firmware: coreboot: Dont skip CBMEM entries outside of known memory
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michał Kopeć <[email protected]>
[ Upstream commit e094fd05defaf0b05774ea1c65fc2d0ab798c809 ]
coreboot leaves CBMEM out of the /memory node of the device tree that it passes to FIT payloads, e.g. LinuxBoot on arm64 Chromebooks, and only lists it in the memory reservation block. The kernel has no resource for that memory, so region_intersects() reports it as neither System RAM nor Reserved memory, and since commit e31ecda9e3af ("firmware: coreboot:
Skip no-map CBMEM entries") all CBMEM entries are skipped on such boards. That loses the coreboot log, the TPM event log and everything else that CBMEM devices expose.
Also accept entries that don't intersect any memory resource. No-map regions are still skipped, as they are IORESOURCE_MEM resources, as are device regions.
--- drivers/firmware/google/coreboot_table.c | 42 ++++++++++++++---------- 1 file changed, 25 insertions(+), 17 deletions(-)
drivers/firmware/google/coreboot_table.c +25 -17
@@ -114,6 +114,30 @@ void coreboot_driver_unregister(struct coreboot_driver *driver) }EXPORT_SYMBOL (coreboot_driver_unregister); +/* +* Whether the memory of a CBMEM entry may be mapped: it must be exclusively +* System RAM, or exclusively Reserved memory, as CBMEM often is on x86, or +* memory that the kernel doesn't know about at all. coreboot leaves CBMEM out +* of the /memory node of the device tree that it passes to FIT payloads, e.g. +* on arm64, and only lists it in the memory reservation block. +* +* Anything else, such as no-map regions on arm64, which are IORESOURCE_MEM +* (see request_standard_resources() in arch/arm64/kernel/setup.c), must not +* be mapped. +*/ +static bool cbmem_entry_is_mappable (const struct lb_cbmem_entry *entry) +{ +resource_size_t start = entry->address; +size_t size = entry->entry_size; + +return region_intersects (start, size,IORESOURCE_SYSTEM_RAM , +IORES_DESC_NONE ) ==REGION_INTERSECTS || +region_intersects (start, size,IORESOURCE_MEM , +IORES_DESC_RESERVED ) ==REGION_INTERSECTS || +region_intersects (start, size,IORESOURCE_MEM , +IORES_DESC_NONE ) ==REGION_DISJOINT ; +} +static int coreboot_table_populate (struct device *dev,void *ptr,resource_size_t len) {int i, ret;
@@ -149,23 +173,7 @@ static int coreboot_table_populate(struct device *dev, void *ptr, resource_size_switch (device->entry.tag) {case LB_TAG_CBMEM_ENTRY : -/* -* Skip entries that are not exclusively System RAM or -* Reserved memory. -* On ARM64, no-map regions are filtered out as they are -* IORESOURCE_MEM (see request_standard_resources() in -* arch/arm64/kernel/setup.c). -* On x86, CBMEM often resides in standard reserved regions -* (IORES_DESC_RESERVED). -*/ -if (region_intersects (device->cbmem_entry.address, - device->cbmem_entry.entry_size, -IORESOURCE_SYSTEM_RAM , -IORES_DESC_NONE ) !=REGION_INTERSECTS && -region_intersects (device->cbmem_entry.address, - device->cbmem_entry.entry_size, -IORESOURCE_MEM , -IORES_DESC_RESERVED ) !=REGION_INTERSECTS ) { +if (!cbmem_entry_is_mappable (&device->cbmem_entry)) {kfree (device);continue ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 123/1005 bpf: lwt: Free the skb when bpf_xmit() fails to expand the headroom
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuqiang Sun <[email protected]>
[ Upstream commit 5e96760b25fdedbbf9312827f1f237d6b18b03e8 ]
When an LWT xmit program returns BPF_OK, bpf_xmit() makes sure that the skb still has room for the link layer header. If pskb_expand_head() fails there, bpf_xmit() returns -ENOMEM without freeing the skb. Its callers, lwtunnel_xmit() and then ip_finish_output2() or ip6_finish_output2(), take any return value other than LWTUNNEL_XMIT_CONTINUE to mean that the skb has been consumed, so nothing frees it.
Each such failure leaks the skb, together with what it holds: its dst and its charge to the sending socket, so the socket is never freed either. The other error paths of bpf_xmit() (BPF_DROP, an illegal return code, a changed protocol, a failed reroute) all free the skb.
Free it here too.
The leak was found with kbound, a static analysis prototype for ownership mismatches at kernel interfaces, on v7.2.12; it is present in mainline.
Build-tested with x86_64 and arm64 allmodconfig (W=1, sparse): no new warnings. Run-tested on QEMU (x86_64, KVM) with KASAN: a route through a dummy device with an LWT xmit program that pushes one byte with bpf_skb_change_head(), so the headroom check has to expand the head, and failslab limited to allocations under bpf_xmit(). Each of 10 pings then fails with ENOMEM. Without this patch each leaves a raw socket behind (RAW slab objects 6 -> 16); with it none does (6 -> 6), and nothing else is reported. Without injection both kernels go from 6 to 6.
--- net/core/lwt_bpf.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
net/core/lwt_bpf.c +3 -1
@@ -345,8 +345,10 @@ static int bpf_xmit(struct sk_buff *skb)* made before LWT xmit. */ ret =xmit_check_headroom (skb, hroom); -if (unlikely (ret)) +if (unlikely (ret)) { +kfree_skb (skb);return ret; + }return LWTUNNEL_XMIT_CONTINUE ;case BPF_REDIRECT :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 124/1005 drm/i915/display: Limit NVL TRANS_VTOTAL.Vtotal skip to A-step
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Suraj Kandpal <[email protected]>
[ Upstream commit f704594d36809780cf41fb201729dc1ac352c5d4 ]
The hardware issue which required us to keep vtotal as 0 has since been fixed on B0 well, so applying the workaround there is no longer correct and causes issues on B-stepping.
Restrict the workaround to A-step only, in both transcoder timing paths and in the crtc_vtotal readout fixup in intel_vrr_get_config().
--- drivers/gpu/drm/i915/display/intel_display.c | 4 ++-- drivers/gpu/drm/i915/display/intel_vrr.c | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-)
drivers/gpu/drm/i915/display/intel_display.c +2 -2
@@ -2779,7 +2779,7 @@ void intel_set_transcoder_timings(const struct intel_crtc_state *crtc_state, HSYNC_END(adjusted_mode->crtc_hsync_end - 1));if (display->platform.novalake && -IS_DISPLAY_STEP (display,STEP_A0 ,STEP_C0 )) +IS_DISPLAY_STEP (display,STEP_A0 ,STEP_B0 )) crtc_vtotal =1 ; intel_de_write(display, TRANS_VTOTAL(display, transcoder),
@@ -2876,7 +2876,7 @@ void intel_set_transcoder_timings_lrr(const struct intel_crtc_state *crtc_state,* is the transcoder's undelayed vblank. */ if (display->platform.novalake && -IS_DISPLAY_STEP (display,STEP_A0 ,STEP_C0 )) +IS_DISPLAY_STEP (display,STEP_A0 ,STEP_B0 )) crtc_vtotal =1 ; intel_de_write(display, TRANS_VTOTAL(display, transcoder),
drivers/gpu/drm/i915/display/intel_vrr.c +1 -1
@@ -1110,7 +1110,7 @@ void intel_vrr_get_config(struct intel_crtc_state *crtc_state) }if (display->platform.novalake && -IS_DISPLAY_STEP (display,STEP_A0 ,STEP_C0 )) +IS_DISPLAY_STEP (display,STEP_A0 ,STEP_B0 )) crtc_state->hw.adjusted_mode.crtc_vtotal =intel_vrr_vmin_vtotal (crtc_state);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 125/1005 drm/i915/cmtg: Disable CMTG after encoder disable in hsw_crtc_disable()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Animesh Manna <[email protected]>
[ Upstream commit 0a5bad4cd8b87b8d575e3efccaa06c02158db32f ]
hsw_crtc_disable() disables CMTG at the very start of the CRTC disable sequence, before intel_encoders_disable(). With this ordering, the wait for CMTG_STATE to clear after CMTG_ENABLE is cleared intermittently times out:
xe 0000:00:02.0: [drm] CMTG: A disable timeout
WARNING: drivers/gpu/drm/i915/display/intel_cmtg.c:205 intel_cmtg_disable+0x331/0x3d0 [xe]
This is seen with igt@kms_hdr@bpc-switch-suspend, which repeatedly disables and re-enables the eDP across modesets and suspend/resume.
Move the CMTG disable after intel_encoders_disable(), so the eDP-side teardown (panel unprepare, ALPM disable, backlight off) has completed, but keep it before intel_encoders_post_disable() and intel_dpll_disable(). The transcoder timing generator, DDI buffer and port PLL are therefore still running while CMTG_STATE is polled, and the requirement to disable CMTG before the transcoder and the port PLL feeding it are turned off is preserved.
v2:
- Modify commit description regarding PSR exit. [Dibin]
- Add fixes tag. [Jani, Dibin]
v3:
- Add a cover letter with links to v1 and v2 for the review history. [Dibin]
--- drivers/gpu/drm/i915/display/intel_display.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-)
drivers/gpu/drm/i915/display/intel_display.c +11 -4
@@ -1791,15 +1791,22 @@ static void hsw_crtc_disable(struct intel_atomic_state *state,intel_atomic_get_old_crtc_state (state, crtc);struct intel_crtc *pipe_crtc; -if (crtc->cmtg.enabled &&intel_cmtg_is_allowed (old_crtc_state)) { -intel_cmtg_set_clk_select (old_crtc_state); -intel_cmtg_disable (old_crtc_state); - }/* * FIXME collapse everything to one hook. * Need care with mst->ddi interactions. */ intel_encoders_disable (state, crtc); + +/* +* Disable CMTG after the encoders are disabled, but before the +* transcoder and port PLL are torn down in +* intel_encoders_post_disable()/intel_dpll_disable(). +*/ +if (crtc->cmtg.enabled &&intel_cmtg_is_allowed (old_crtc_state)) { +intel_cmtg_set_clk_select (old_crtc_state); +intel_cmtg_disable (old_crtc_state); + } +intel_encoders_post_disable (state, crtc);intel_dpll_disable (old_crtc_state);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 126/1005 net/mlx5: macsec: free struct mlx5_fs_id after an RCU grace period
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joas Antonio dos Santos <[email protected]>
[ Upstream commit 902407bc588575af0ceae5de4f635fe1e024f258 ]
macsec_fs_id_del() removes a struct mlx5_fs_id from its rhashtable with rhashtable_remove_fast() and then frees it with kfree() right away.
The TX (SCI) table is read locklessly from the transmit path:mlx5e_macsec_handle_tx_skb() and mlx5e_macsec_tx_build_eseg() call mlx5_macsec_fs_get_fs_id_from_hashtable(), which does rhashtable_lookup() under rcu_read_lock() and then reads mlx5_fs_id->id. A transmit that looked the entry up just before it was removed reads freed memory.
Before commit d4ece08f4b1d ("net/mlx5: Maintain fs_id xarray per MACsec device inside macsec steering") the SCI table held struct mlx5e_macsec_sa directly, and mlx5e_macsec_del_txsa() freed it with kfree_rcu_mightsleep(). That commit moved the table into macsec_fs.c with the new struct mlx5_fs_id, but frees it with a plain kfree().
Add an rcu_head to struct mlx5_fs_id and free it with kfree_rcu().
The same issue was flagged by the Sashiko AI review as a pre-existing problem while reviewing the HW-GRO for PSP series.
--- drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c +2 -1
@@ -94,6 +94,7 @@ struct mlx5_fs_id {refcount_t refcnt;sci_t sci;struct rhash_head hash; +struct rcu_head rcu; };struct mlx5_macsec_device {
@@ -684,7 +685,7 @@ static void macsec_fs_id_del(struct list_head *macsec_devices_list, u32 fs_id,xa_erase (fs_id_xa, fs_id); -kfree (fs_id_found); +kfree_rcu (fs_id_found, rcu);if (macsec_fs_is_macsec_device_empty (macsec_device)) {list_del (&macsec_device->macsec_devices_list_entry);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 127/1005 bnxt_en: Dont keep MSI-X vectors added before FW reserves them
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vlad Poenaru <[email protected]>
[ Upstream commit af449230bd8de936d6e4f759240e787b9aad7cc0 ]
When dynamic MSI-X is supported, bnxt_check_rings() grows the MSI-X vectors with bnxt_change_msix() once FW says the new rings would fit, and keeps them. FW only reserves the extra IRQs later, when bnxt_reserve_rings() calls __bnxt_reserve_rings(). The MSI-X table entries beyond the function's reserved IRQs are not backed until then:
the MSI message written when the new vectors are activated is lost, and the entries read back as zero. After FW reserves them they are live but still zero, so the NQ rings bound to them signal address 0 and every completion on those rings is lost. The next ring change (for example ethtool -G) then times out freeing each of those rings and the TX watchdog fires:
bnxt_en 0002:01:00.0 eth0: Resp cmpl intr err msg: 0x51
bnxt_en 0002:01:00.0 eth0: hwrm_ring_free type 1 failed. rc:fffffff0 err:0
...
bnxt_en 0002:01:00.0 eth0: NETDEV WATCHDOG: CPU: 17: transmit queue 18 timed out 5716 ms
On x86 this is hidden: GENERIC_IRQ_RESERVATION_MODE makes the PCI MSI domains MSI_FLAG_MUST_REACTIVATE, so the message is composed and written again when the IRQ is requested, after FW has reserved the vector. Since commit 0d6a7c417983 ("irqchip/gic-v3-its: Enable dynamic MSI-X allocation"), arm64 GICv3 systems take the dynamic path as well, but write the message only once, at allocation. On an NVIDIA Grace system with a BCM57508, raising the channel count from 18 to 32 left MSI-X entries 18-31 all zero, and the 14 rings using them lost their interrupts.
Keep the allocation in bnxt_check_rings() as a check that enough vectors are available, but free the new vectors again right away when FW manages IRQ reservations (BNXT_NEW_RM). bnxt_reserve_rings() then allocates them after __bnxt_reserve_rings() has reserved them. Without BNXT_NEW_RM there is no IRQ reservation and bnxt_reserve_rings() does not grow the vectors, so keep the current behaviour there.
In bnxt_reserve_rings(), size that allocation from the rings FW actually reserved (bnxt_get_num_msix()) instead of the count computed before the reservation, so that a partial grant does not activate unreserved entries either, at least while no RoCE driver is registered.
The allocation can now fail after FW has committed the reservation. A later open would then find nothing to reserve and return before growing the vectors, and bnxt_request_irq() would use irq_tbl[] entries past bp->total_irqs, which still hold the freed virqs. Grow the vectors in that case as well, and clear irq_tbl[].vector when trimming.
--- drivers/net/ethernet/broadcom/bnxt/bnxt.c | 34 ++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-)
drivers/net/ethernet/broadcom/bnxt/bnxt.c +33 -1
@@ -11544,6 +11544,7 @@ static int bnxt_change_msix(struct bnxt *bp, int total) map.index = i -1 ; map.virq = bp->irq_tbl[i -1 ].vector;pci_msix_free_irq (bp->pdev, map); + bp->irq_tbl[i -1 ].vector =0 ; bp->total_irqs--; }return bp->total_irqs;
@@ -11721,8 +11722,23 @@ int bnxt_reserve_rings(struct bnxt *bp, bool irq_re_init)int irqs_required;int rc; -if (!bnxt_need_reserve_rings (bp)) +if (!bnxt_need_reserve_rings (bp)) { +/* FW may already hold the reservation from an earlier +* reservation that was not followed by growing the dynamic +* MSI-X vectors, e.g. because the allocation failed. +*/ +if (irq_re_init &&BNXT_NEW_RM (bp) && bp->irq_tbl && +pci_msix_can_alloc_dyn (bp->pdev)) { + irqs_required =bnxt_get_num_msix (bp); +if (irqs_required > bp->total_irqs && +bnxt_change_msix (bp, irqs_required) != irqs_required) { +netdev_err (bp->dev,"Unable to allocate %d MSIX vectors, maximum available %d\n" , + irqs_required, bp->total_irqs); +return -ENOSPC ; + } + }return 0 ; + }if (BNXT_NEW_RM (bp) && !bnxt_ulp_registered (edev)) {int ulp_msix =bnxt_get_avail_msix (bp, bp->ulp_num_msix_want);
@@ -11748,6 +11764,10 @@ int bnxt_reserve_rings(struct bnxt *bp, bool irq_re_init) rc =bnxt_init_int_mode (bp);bnxt_ulp_irq_restart (bp, rc); }else if (irq_change && !rc) { +/* Size the vectors from what FW actually reserved, which +* can be less than what was requested. +*/ + irqs_required =bnxt_get_num_msix (bp);if (bnxt_change_msix (bp, irqs_required) != irqs_required) rc = -ENOSPC ; }
@@ -15107,6 +15127,7 @@ int bnxt_check_rings(struct bnxt *bp, int tx, int rx, bool sh, int tcs, hwr.cp =min_t (int, hwr.cp,bnxt_get_max_func_irqs (bp)); }if (hwr.cp > bp->total_irqs) { +int old_total = bp->total_irqs;int total_msix =bnxt_change_msix (bp, hwr.cp);if (total_msix < hwr.cp) {
@@ -15114,6 +15135,17 @@ int bnxt_check_rings(struct bnxt *bp, int tx, int rx, bool sh, int tcs, hwr.cp, total_msix); rc = -ENOSPC ; } +/* FW has not reserved the new vectors yet, and writes to +* MSI-X table entries beyond the reserved IRQs don't +* stick (seen on BCM57508). Free them again; +* bnxt_reserve_rings() allocates them after +* __bnxt_reserve_rings(). Without the new resource +* manager there is no IRQ reservation and +* bnxt_reserve_rings() does not grow the vectors, so +* keep them. +*/ +if (BNXT_NEW_RM (bp)) +bnxt_change_msix (bp, old_total); } }return rc;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 128/1005 gpio: shared-proxy: Fix race between concurrent first users
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Guo <[email protected]>
[ Upstream commit eb70d2419e79b6720fd465b905a2dddd751f2a48 ]
The proxy lets a consumer set the line direction and reset the default value and vote tally only when usecnt == 1, i.e. when it is the sole requester. But request() and direction_output() take the descriptor mutex separately. When two consumers probe concurrently, both request the line before either configures it, both see usecnt == 2, both fall into the shared path, read back the still unconfigured direction (input) and fail with -EPERM.
On Nord RRD the two DAC supplies are reg-fixed-voltage regulators sharing tlmm GPIO 41. They probe asynchronously and intermittently both fail, leaving the codecs without supplies:
reg-fixed-voltage regulator-3p3-dac: setup of GPIO (default) failed: -1 reg-fixed-voltage regulator-5p0-dac: setup of GPIO (default) failed: -1
Requesting the line is not evidence that a consumer has claimed it. Instead, count proxies that have actually configured the line (set its direction or voted for a value) in a new cfgcnt, with a per-proxy configured flag, and allow (re)initialization only while no other proxy has done so. A consumer obtained with GPIOD_ASIS that votes via gpiod_set_value() without ever setting the direction counts as configured, so a later user can never reset def_val/votecnt behind its vote. The count is dropped when the proxy frees the line.
--- drivers/gpio/gpio-shared-proxy.c | 78 ++++++++++++++++++++++++++++---- drivers/gpio/gpiolib-shared.h | 1 + 2 files changed, 70 insertions(+), 9 deletions(-)
drivers/gpio/gpio-shared-proxy.c +69 -9
@@ -21,9 +21,37 @@ struct gpio_shared_proxy_data {struct gpio_chip gc;struct gpio_shared_desc *shared_desc;struct device *dev; +bool configured;bool voted_change; }; +/* +* A proxy may (re)initialize the line - set its direction and reset the +* default value and the vote tally - only while no other proxy has set the +* direction or voted for a value. Requesting the line is not enough: consumers +* may request concurrently, so counting requests lets every one of them +* conclude that it is not first. +*/ +static bool gpio_shared_proxy_may_init (struct gpio_shared_proxy_data *proxy) +{ +unsigned int cfgcnt = proxy->shared_desc->cfgcnt; + +lockdep_assert_held (&proxy->shared_desc->mutex); + +return !cfgcnt || (cfgcnt ==1 && proxy->configured); +} + +static void gpio_shared_proxy_mark_configured (struct gpio_shared_proxy_data *proxy) +{ +lockdep_assert_held (&proxy->shared_desc->mutex); + +if (proxy->configured) +return ; + + proxy->configured = true; + proxy->shared_desc->cfgcnt++; +} +static int gpio_shared_proxy_set_unlocked (struct gpio_shared_proxy_data *proxy,int value) {
@@ -117,6 +145,11 @@ static void gpio_shared_proxy_free(struct gpio_chip *gc, unsigned int offset) proxy->shared_desc->usecnt--; +if (proxy->configured) { + proxy->configured = false; + shared_desc->cfgcnt--; + } +dev_dbg (proxy->dev,"Shared GPIO freed, number of users: %u\n" , proxy->shared_desc->usecnt); }
@@ -131,7 +164,7 @@ static int gpio_shared_proxy_set_config(struct gpio_chip *gc,guard (mutex)(&shared_desc->mutex); -if (shared_desc->usecnt >1 ) { +if (!gpio_shared_proxy_may_init (proxy)) {if (shared_desc->cfg != cfg) {dev_dbg (proxy->dev,"Shared GPIO's configuration already set, accepting changes but users may conflict!!\n" );
@@ -155,15 +188,21 @@ static int gpio_shared_proxy_direction_input(struct gpio_chip *gc,struct gpio_shared_proxy_data *proxy =gpiochip_get_data (gc);struct gpio_shared_desc *shared_desc = proxy->shared_desc;struct gpio_desc *desc = shared_desc->desc; -int dir; +int ret, dir;guard (mutex)(&shared_desc->mutex); -if (shared_desc->usecnt ==1 ) { +if (gpio_shared_proxy_may_init (proxy)) {dev_dbg (proxy->dev, -"Only one user of this shared GPIO, allowing to set direction to input\n" ); +"No other user configured this shared GPIO, allowing to set direction to input\n" ); + + ret =gpiod_direction_input (desc); +if (ret) +return ret; -return gpiod_direction_input (desc); +gpio_shared_proxy_mark_configured (proxy); + +return 0 ; } dir =gpiod_get_direction (desc);
@@ -176,6 +215,8 @@ static int gpio_shared_proxy_direction_input(struct gpio_chip *gc,return -EPERM ; } +gpio_shared_proxy_mark_configured (proxy); +return 0 ; }
@@ -189,18 +230,20 @@ static int gpio_shared_proxy_direction_output(struct gpio_chip *gc,guard (mutex)(&shared_desc->mutex); -if (shared_desc->usecnt ==1 ) { +if (gpio_shared_proxy_may_init (proxy)) {dev_dbg (proxy->dev, -"Only one user of this shared GPIO, allowing to set direction to output with value '%s'\n" , +"No other user configured this shared GPIO, allowing to set direction to output with value '%s'\n" ,str_high_low (value)); ret =gpiod_direction_output (desc, value);if (ret)return ret; +/* Only this proxy can have voted, so the tally is ours to reset */ shared_desc->def_val = value; shared_desc->votecnt =0 ; proxy->voted_change = false; +gpio_shared_proxy_mark_configured (proxy);return 0 ; }
@@ -215,7 +258,13 @@ static int gpio_shared_proxy_direction_output(struct gpio_chip *gc,return -EPERM ; } -return gpio_shared_proxy_set_unlocked (proxy, value); + ret =gpio_shared_proxy_set_unlocked (proxy, value); +if (ret) +return ret; + +gpio_shared_proxy_mark_configured (proxy); + +return 0 ; } static int gpio_shared_proxy_get_cansleep(struct gpio_chip *gc,
@@ -230,10 +279,21 @@ static int gpio_shared_proxy_set_cansleep(struct gpio_chip *gc, unsigned int offset, int value) {struct gpio_shared_proxy_data *proxy =gpiochip_get_data (gc); +int ret;guard (mutex)(&proxy->shared_desc->mutex); -return gpio_shared_proxy_set_unlocked (proxy, value); +/* +* A GPIOD_ASIS consumer may vote without ever setting the direction; +* count it as configured so a later user can't reset its vote. +*/ + ret =gpio_shared_proxy_set_unlocked (proxy, value); +if (ret) +return ret; + +gpio_shared_proxy_mark_configured (proxy); + +return 0 ; } static int gpio_shared_proxy_get_direction(struct gpio_chip *gc,
drivers/gpio/gpiolib-shared.h +1 -0
@@ -41,6 +41,7 @@ struct gpio_shared_desc {struct gpio_desc *desc;unsigned long cfg;unsigned int usecnt; +unsigned int cfgcnt;unsigned int votecnt;int def_val;struct mutex mutex;/* serializes all proxy operations on this descriptor */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 129/1005 gpio: shared-proxy: Drop the vote of a released proxy on write failure
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Guo <[email protected]>
[ Upstream commit 53b7b1201964f6f147fa0fa2f61194403a65cdf0 ]
When a proxy that voted for a value change frees the line, it calls gpio_shared_proxy_set_unlocked() to withdraw its vote. If it is the last voter and restoring the default value fails, that function returns early, leaving votecnt incremented and voted_change set.
The consumer is gone, but its vote is not. The line is held at the non-default value for all remaining users, since votecnt can never drop to zero again. And the proxy data outlives the request, so voted_change is still set when the line is requested again. If another user has reinitialized the line in between, resetting votecnt to 0, the stale proxy's next vote for the default value decrements votecnt from 0 and underflows it.
Drop the vote unconditionally on release, after reporting the failure, since the consumer is going away regardless.
--- drivers/gpio/gpio-shared-proxy.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/gpio/gpio-shared-proxy.c +5 -1
@@ -138,9 +138,13 @@ static void gpio_shared_proxy_free(struct gpio_chip *gc, unsigned int offset)if (proxy->voted_change) { ret =gpio_shared_proxy_set_unlocked (proxy, shared_desc->def_val); -if (ret) +if (ret) {dev_err (proxy->dev,"Failed to unset the shared GPIO value on release: %d\n" , ret); +/* The consumer is going away regardless, drop its vote */ + shared_desc->votecnt--; + proxy->voted_change = false; + } } proxy->shared_desc->usecnt--;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 130/1005 gpio: shared-proxy: Drive the default value when no votes are cast
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Guo <[email protected]>
[ Upstream commit 0bc45604403176722e634e670f5e38de0aa42a9b ]
A consumer that requests a shared line with GPIOD_ASIS never calls direction_output(), so def_val keeps its initial value of 0. If the line was left high, for instance by the bootloader, a later gpiod_set_value(0) from that consumer matches def_val and the proxy treats it as withdrawing a vote it never cast. It returns success without writing the hardware, and the line stays high.
The consumer has no way to tell. Its request to drive the line low is silently ignored until it first votes for high and then withdraws that vote.
When the requested value is the default and no votes are outstanding, write it to the hardware instead of returning early. With votes outstanding the request remains a no-op, as the line must stay at the voted value.
Do this for all lines, not only GPIOD_ASIS ones. A line configured via direction_output() can be left at the non-default value as well: when a proxy releases the line and restoring the default fails, its vote is dropped regardless, leaving votecnt at 0 with the line at the voted value. The write lets any remaining user bring it back to the default. In the common case it is a redundant write of the value the line already has, and it only happens when a proxy that has not voted sets the default.
--- drivers/gpio/gpio-shared-proxy.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/gpio/gpio-shared-proxy.c +9 -2
@@ -85,9 +85,16 @@ gpio_shared_proxy_set_unlocked(struct gpio_shared_proxy_data *proxy, int value) }/* Desired value is the default. */ -if (!proxy->voted_change) -/* We didn't vote for change previously, nothing to do. */ +if (!proxy->voted_change) { +/* +* With no votes outstanding the line should be at the +* default, but a GPIOD_ASIS line may have been left at the +* opposite value. Drive it there. +*/ +if (!shared_desc->votecnt) + ret =gpiod_set_value_cansleep (desc, shared_desc->def_val); goto out; + }/* We previously voted for change. */ if (shared_desc->votecnt ==1 ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 131/1005 gpio: shared-proxy: Drop the vote when switching to input
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Guo <[email protected]>
[ Upstream commit 925409db963dbae4628d522bc6b14985e749c08b ]
A proxy that is the only one to have configured a shared line may reinitialize it. When it sets the direction to output, the proxy resets the vote tally, but when it sets the direction to input, it leaves any vote it cast in place, although an input line carries no value.
That vote outlives its meaning. When the consumer releases the line, gpio_shared_proxy_free() tries to withdraw it by writing the default value, which gpiolib refuses on an input line:
Failed to unset the shared GPIO value on release: -1
This happens, for instance, when a consumer votes for a change with gpiod_set_value() after setting the line to output and then switches it to input.
Clear the vote when the proxy reinitializes the line as input, as the output path already does. No other proxy can hold a vote at that
point: voting marks a proxy configured, and a proxy that frees the line drops its vote.
--- drivers/gpio/gpio-shared-proxy.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/gpio/gpio-shared-proxy.c +3 -0
@@ -211,6 +211,9 @@ static int gpio_shared_proxy_direction_input(struct gpio_chip *gc,if (ret)return ret; +/* An input carries no value, drop any vote this proxy cast */ + shared_desc->votecnt =0 ; + proxy->voted_change = false;gpio_shared_proxy_mark_configured (proxy);return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 132/1005 ipv6: fix fib6 walker UAF on NLM_F_REPLACE
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft) <[email protected]>
[ Upstream commit 23fec4bd76904e9df7a8cc0a81ceb14c36971da4 ]
fib6_walker uses w->leaf to remember the next fib6_info to dump, so an RTM_GETROUTE dump can continue there on the next recvmsg(). This assumes that whoever removes a route from the tree also updates the walkers pointing at it. fib6_del_route() does: it moves w->leaf to the next route. The NLM_F_REPLACE branch of fib6_add_rt2node() does
not: it removes the old route, fib6_add() frees it, and w->leaf keeps pointing at the freed object.
The fn_sernum version check in fib6_dump_table() normally protects against resuming on a stale w->leaf, but it can be bypassed:ip6_link_failure() resets fn_sernum to -1 when the default route fails, which an unprivileged user in a user+net namespace can cause:
1) link failure fn_sernum = -1
2) dump pauses on route R
3) replace R fn_sernum changed, R freed 4) link failure fn_sernum = -1 5) dump resumes -1 == -1, reads freed R <- UAF
BUG: KASAN: slab-use-after-free in rt6_fill_node+0x1c22/0x2cd0 Read of size 4 at addr ff11000011fa0064 by task poc/101 rt6_fill_node <- rt6_dump_route
Fix by adjusting walkers separately for replacement and deletion. For replacement, add fib6_walkers_replace_leaf() points w->leaf at the new route. For deletion and ECMP sibling removal, fib6_walkers_skip_rt() calls fib6_walkers_replace_leaf() with the next route. Reset w->skip_in_node when updating w->leaf, and set w->state to FWS_U when no next route remains.
--- net/ipv6/ip6_fib.c | 50 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 13 deletions(-)
net/ipv6/ip6_fib.c +37 -13
@@ -89,6 +89,40 @@ static void fib6_walker_unlink(struct net *net, struct fib6_walker *w)write_unlock_bh (&net->ipv6.fib6_walker_lock); } +/* @old is leaving the tree. Walkers resting on it continue from @new, or +* climb to the parent node when there is no @new. Called with tb6_lock +* held. +*/ +static void fib6_walkers_replace_leaf (struct net *net,struct fib6_info *old, +struct fib6_info *new) +{ +struct fib6_walker *w; + +read_lock (&net->ipv6.fib6_walker_lock); + FOR_WALKERS(net, w) { +if (w->state ==FWS_C && w->leaf == old) { +pr_debug ("walker %p adjusted by unlink of %p\n" , w, old); + w->leaf = new; + w->skip_in_node =0 ; +if (!new) + w->state =FWS_U ; + } + } +read_unlock (&net->ipv6.fib6_walker_lock); +} + +/* @rt is removed from its node: walkers resting on it continue from the +* next route of the node. +*/ +static void fib6_walkers_skip_rt (struct net *net,struct fib6_info *rt) +{ +struct fib6_info *next; + + next =rcu_dereference_protected (rt->fib6_next, +lockdep_is_held (&rt->fib6_table->tb6_lock)); +fib6_walkers_replace_leaf (net, rt, next); +} +static int fib6_new_sernum (struct net *net) {int new, old =atomic_read (&net->ipv6.fib6_sernum);
@@ -1312,6 +1346,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,rcu_assign_pointer (rt->fib6_node, fn); rt->fib6_next = iter->fib6_next;rcu_assign_pointer (*ins, rt); +fib6_walkers_replace_leaf (info->nl_net, iter, rt);if (!info->skip_notify)inet6_rt_notify (RTM_NEWROUTE , rt, info,NLM_F_REPLACE );if (!(fn->fn_flags &RTN_RTINFO )) {
@@ -1333,6 +1368,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,if (iter->fib6_metric > rt->fib6_metric)break ;if (rt6_qualify_for_ecmp (iter)) { +fib6_walkers_skip_rt (info->nl_net, iter); *ins = iter->fib6_next; iter->fib6_node =NULL ;list_add (&iter->purge_link, purge_list);
@@ -1967,7 +2003,6 @@ static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn, enum rt_del_reason del_reason) {struct fib6_info *leaf, *replace_rt =NULL ; -struct fib6_walker *w;struct fib6_info *rt =rcu_dereference_protected (*rtp,lockdep_is_held (&table->tb6_lock));struct net *net = info->nl_net;
@@ -2018,18 +2053,7 @@ static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn,rt6_multipath_rebalance (next_sibling); } -/* Adjust walkers */ -read_lock (&net->ipv6.fib6_walker_lock); - FOR_WALKERS(net, w) { -if (w->state ==FWS_C && w->leaf == rt) { -pr_debug ("walker %p adjusted by delroute\n" , w); - w->leaf =rcu_dereference_protected (rt->fib6_next, -lockdep_is_held (&table->tb6_lock)); -if (!w->leaf) - w->state =FWS_U ; - } - } -read_unlock (&net->ipv6.fib6_walker_lock); +fib6_walkers_skip_rt (net, rt);/* If it was last route, call fib6_repair_tree() to: * 1. For root node, put back null_entry as how the table was created.
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 133/1005 tcp: do not let tcp_collapse() drive sk_forward_alloc negative
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
[ Upstream commit 031c403d13e5046750e2abebd4e770631e7c4627 ]
tcp_collapse() charges each newly allocated skb with skb_set_owner_r() before the skbs it replaces are freed, without scheduling memory first.
Since sk_mem_uncharge() reclaims eagerly, sk->sk_forward_alloc has no cushion and can become negative. This can be durable when the collapsed skbs had a high payload/truesize ratio or were partially read, because the new skbs can have a bigger total truesize than the old ones.
A negative sk_forward_alloc then confuses tcp_wmem_schedule(), which can return a negative length to tcp_sendmsg_locked(), triggering a WARN_ON_ONCE(bytes > INT_MAX) in check_copy_size().
Call sk_forced_mem_schedule() before charging nskb.
--- net/ipv4/tcp_input.c | 4 ++++ 1 file changed, 4 insertions(+)
net/ipv4/tcp_input.c +4 -0
@@ -5846,6 +5846,10 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,__skb_queue_before (list, skb, nskb); else __skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */ +/* nskb is charged before the skbs it replaces are freed. +* Make sure sk->sk_forward_alloc can not become negative. +*/ +sk_forced_mem_schedule (sk, nskb->truesize);skb_set_owner_r (nskb, sk);mptcp_skb_ext_move (nskb, skb);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 134/1005 ata: libata-sata: allow re-enabling NCQ with the same queue_depth
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Pylypiv <[email protected]>
[ Upstream commit d7c5cc8cc21c1264cce07feb4a51be158688280e ]
When ata_eh_speed_down() disables NCQ due to excessive errors, it sets ATA_DFLAG_NCQ_OFF without changing sdev->queue_depth. Userspace can re-enable NCQ by writing a queue depth > 1 to the sysfs queue_depth attribute, which invokes ata_change_queue_depth() to clear ATA_DFLAG_NCQ_OFF.
However, ata_change_queue_depth() returns early if the requested queue_depth is equal to sdev->queue_depth before clearing ATA_DFLAG_NCQ_OFF. As a result, writing a different queue depth > 1 re-enables NCQ, whereas writing the current sdev->queue_depth value leaves ATA_DFLAG_NCQ_OFF set.
Since ata_change_queue_depth() already checks whether queue_depth equals sdev->queue_depth before calling scsi_change_queue_depth(), remove the early check so that writing the current queue_depth > 1 clears ATA_DFLAG_NCQ_OFF and re-enables NCQ.
--- drivers/ata/libata-sata.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/ata/libata-sata.c +1 -1
@@ -1287,7 +1287,7 @@ int ata_change_queue_depth(struct ata_port *ap, struct scsi_device *sdev,spin_lock_irqsave (ap->lock, flags); dev =ata_scsi_find_dev (ap, sdev); -if (!dev || queue_depth <1 || queue_depth == sdev->queue_depth) { +if (!dev || queue_depth <1 ) {spin_unlock_irqrestore (ap->lock, flags);return sdev->queue_depth; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 135/1005 ata: libata-eh: Retry non-NCQ commands when their sense data asks for it
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Niklas Cassel <[email protected]>
[ Upstream commit 597be4104c4045d73979c05307fa5fc778d1dbde ]
When a failed command has valid sense data, ata_eh_analyze_tf() asks scsi_check_sense() whether the command should be retried, and sets ATA_QCFLAG_RETRY if it should. ata_eh_link_autopsy() then clears AC_ERR_DEV and AC_ERR_OTHER from qc->err_mask, relying on that decision.
For an NCQ command, qc->err_mask still has AC_ERR_NCQ, so ata_eh_finish() honors ATA_QCFLAG_RETRY. For a non-NCQ command, whose sense data comes from REQUEST SENSE DATA EXT, qc->err_mask is now zero, and ata_eh_finish() completes the command with scmd->retries set to scmd->allowed, without looking at ATA_QCFLAG_RETRY. Such a command is thus never retried, even when its sense data asks for a retry, e.g. a transient error reported as ABORTED COMMAND.
Make ata_eh_finish() honor ATA_QCFLAG_RETRY for commands with valid sense data. ata_eh_qc_retry() cannot be used for this: as qc->err_mask is zero, it increments scmd->allowed, so every retry would allow one more, and a persistent error would be retried forever. Instead, complete the command without touching scmd->allowed or scmd->retries, so that the SCSI midlayer retries it at most scmd->allowed times, like any other failed command.
--- drivers/ata/libata-eh.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-)
drivers/ata/libata-eh.c +14 -2
@@ -4077,8 +4077,20 @@ void ata_eh_finish(struct ata_port *ap)ata_eh_qc_complete (qc); } }else { -if (qc->flags &ATA_QCFLAG_SENSE_VALID || - qc->flags &ATA_QCFLAG_EH_SUCCESS_CMD ) { +if (qc->flags &ATA_QCFLAG_SENSE_VALID && + qc->flags &ATA_QCFLAG_RETRY ) { +/* +* The sense data asks for a retry, see +* ata_eh_analyze_tf(). ata_eh_link_autopsy() +* cleared qc->err_mask, so ata_eh_qc_retry() +* would increment scmd->allowed. Leave +* scmd->allowed alone, so that upper layer +* only retries the command if it has not +* already been retried too many times. +*/ +__ata_eh_qc_complete (qc); + }else if (qc->flags &ATA_QCFLAG_SENSE_VALID || + qc->flags &ATA_QCFLAG_EH_SUCCESS_CMD ) {ata_eh_qc_complete (qc); }else {/* feed zero TF to sense generation */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 136/1005 net: stmmac: take ownership of saved RX state at poll entry
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: James Hilliard <[email protected]>
[ Upstream commit 26219e9402c22181f021034f127a8e278d40545f ]
When a saved partial packet completes with a poll budget of one, the old loop can leave state_saved and state.skb pointing at an skb that has already been delivered or freed. The next poll then reuses that pointer, causing a use-after-free or double free.
Take the saved state at poll entry and clear the stored ownership immediately. Save it again only if the packet remains incomplete, including when the next descriptor is still DMA-owned.
Track the frame-in-progress flag independently of the status read from the next descriptor. The old code keyed the save on the status of the last descriptor looked at, so a loop stopped at a DMA-owned descriptor (rx status not yet valid) could drop the saved error/length bookkeeping in stmmac_rx_zc().
Drop the saved state both when the queue parameters are reset and when the ring is destroyed. stmmac_reset_rx_queue() is reached from __stmmac_open(), stmmac_xdp_open(), stmmac_resume() and stmmac_enable_rx_queue(); without draining it there, a partial frame saved before suspend (or before a queue is disabled and re-enabled) survives while cur_rx and dirty_rx are rewound to zero. On the resume path the ring is only re-armed in place: stmmac_clear_descriptors() sets the ownership bits and stmmac_init_dma_engine() restores the tail pointer, but the RX buffer addresses are not reprogrammed. The first poll would then resume the stale skb against a ring position that no longer matches the descriptors it was built from. __free_dma_rx_desc_resources() releases it on teardown.
Apply the same state handling to stmmac_rx_zc(), which also leaves state_saved set when a saved frame finishes at the budget boundary. That path saves only error and length bookkeeping, not an skb pointer.
--- .../net/ethernet/stmicro/stmmac/stmmac_main.c | 72 +++++++++++-------- 1 file changed, 42 insertions(+), 30 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +42 -30
@@ -2151,6 +2151,9 @@ static void __free_dma_rx_desc_resources(struct stmmac_priv *priv,else dma_free_rx_skbufs (priv, dma_conf, queue); +dev_kfree_skb_any (rx_q->state.skb); + rx_q->state.skb =NULL ; + rx_q->state_saved = false; rx_q->buf_alloc_num =0 ; rx_q->xsk_pool =NULL ;
@@ -5536,12 +5539,12 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)unsigned int count =0 , error =0 , len =0 ;int dirty =stmmac_rx_dirty (priv, queue);unsigned int next_entry = rx_q->cur_rx; +bool in_progress = rx_q->state_saved;u32 rx_errors =0 , rx_dropped =0 ;unsigned int desc_size;struct bpf_prog *prog;bool failure = false;int xdp_status =0 ; -int status =0 ;if (netif_msg_rx_status (priv)) {void *rx_head =stmmac_get_rx_desc (priv, rx_q,0 );
@@ -5552,23 +5555,25 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)stmmac_display_ring (priv, rx_head, priv->dma_conf.dma_rx_size, true, rx_q->dma_rx_phy, desc_size); } + +if (rx_q->state_saved) { + error = rx_q->state.error; + len = rx_q->state.len; + rx_q->state_saved = false; + } +while (count < limit) {struct stmmac_rx_buffer *buf;struct stmmac_xdp_buff *ctx;unsigned int buf1_len =0 ;struct dma_desc *np, *p; -int entry; +int entry, status;int res; -if (!count && rx_q->state_saved) { - error = rx_q->state.error; - len = rx_q->state.len; - }else { - rx_q->state_saved = false; +if (!in_progress) { error =0 ; len =0 ; } - read_again:if (count >= limit)break ;
@@ -5607,6 +5612,8 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)if (!buf->xdp)break ; + in_progress = status & rx_not_ls; +if (priv->extend_desc) {/* Read the extended status after the own bit */ dma_rmb ();
@@ -5683,7 +5690,7 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) count++; } -if (status & rx_not_ls) { +if (in_progress) { rx_q->state_saved = true; rx_q->state.error = error; rx_q->state.len = len;
@@ -5725,9 +5732,10 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)struct stmmac_rx_queue *rx_q = &priv->dma_conf.rx_queue[queue];struct stmmac_channel *ch = &priv->channel[queue];unsigned int count =0 , error =0 , len =0 ; -int status =0 , coe = priv->hw->rx_csum;unsigned int next_entry = rx_q->cur_rx; +bool in_progress = rx_q->state_saved;enum dma_data_direction dma_dir; +int coe = priv->hw->rx_csum;unsigned int desc_size;struct sk_buff *skb =NULL ;struct stmmac_xdp_buff ctx;
@@ -5747,25 +5755,28 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)stmmac_display_ring (priv, rx_head, priv->dma_conf.dma_rx_size, true, rx_q->dma_rx_phy, desc_size); } + +if (rx_q->state_saved) { + skb = rx_q->state.skb; + error = rx_q->state.error; + len = rx_q->state.len; + rx_q->state.skb =NULL ; + rx_q->state_saved = false; + } +while (count < limit) {unsigned int buf1_len =0 , buf2_len =0 ;enum pkt_hash_types hash_type;struct stmmac_rx_buffer *buf;struct dma_desc *np, *p; -int entry; +int entry, status;u32 hash; -if (!count && rx_q->state_saved) { - skb = rx_q->state.skb; - error = rx_q->state.error; - len = rx_q->state.len; - }else { - rx_q->state_saved = false; +if (!in_progress) { skb =NULL ; error =0 ; len =0 ; } - read_again:if (count >= limit)break ;
@@ -5794,6 +5805,8 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)prefetch (np); + in_progress = status & rx_not_ls; +if (priv->extend_desc) {/* Read the extended status after the own bit */ dma_rmb ();
@@ -5811,11 +5824,10 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)if (unlikely (error && (status & rx_not_ls))) goto read_again; +if (unlikely (error)) {dev_kfree_skb (skb); - skb =NULL ; - count++; -continue ; + goto next; }/* Buffer is good. Go on. */
@@ -5889,9 +5901,7 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) STMMAC_XDP_REDIRECT)) { xdp_status |= xdp_res; buf->page =NULL ; - skb =NULL ; - count++; -continue ; + goto next; } } }
@@ -5948,10 +5958,8 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)/* Remove FCS if needed */ if (!fcs_stripped &&pskb_trim (skb, len)) {dev_kfree_skb_any (skb); - skb =NULL ; rx_dropped++; - count++; -continue ; + goto next; }stmmac_get_rx_hwtstamp (priv, p, np, skb);
@@ -5976,14 +5984,15 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)skb_record_rx_queue (skb, queue);napi_gro_receive (&ch->rx_napi, skb); - skb =NULL ; - rx_packets++; rx_bytes += len; +next: + in_progress = false; + skb =NULL ; count++; } -if (status & rx_not_ls || skb) { +if (in_progress || skb) { rx_q->state_saved = true; rx_q->state.skb = skb; rx_q->state.error = error;
@@ -8295,6 +8304,9 @@ static void stmmac_reset_rx_queue(struct stmmac_priv *priv, u32 queue) {struct stmmac_rx_queue *rx_q = &priv->dma_conf.rx_queue[queue]; +dev_kfree_skb_any (rx_q->state.skb); + rx_q->state.skb =NULL ; + rx_q->state_saved = false; rx_q->cur_rx =0 ; rx_q->dirty_rx =0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 137/1005 net: stmmac: drop split frames on AF_XDP zero-copy RX
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Bianconi <[email protected]>
[ Upstream commit 834ec95308320cbd8c162d86788ab95cc3fd6bf8 ]
stmmac_rx_zc() assumes a 1:1 mapping between a received frame and an XSK pool buffer and drops any frame that spans more than one RX descriptor:
/* XSK pool expects RX frame 1:1 mapped to XSK buffer */
if (likely(status & rx_not_ls)) {
xsk_buff_free(buf->xdp);
buf->xdp = NULL;
dirty++;
count++;
goto read_again;
}The non-last descriptors are freed and dropped, but the frame is not marked as errored. When the poll reaches the last descriptor of the same frame, error is still 0, so the fragment is handled as a complete
frame: it is passed to the XDP program, copied into an skb on XDP_PASS, or converted for XDP_TX. The tail starts in the middle of the original payload at a predictable offset and, parsed as a fresh frame (len == 0), stmmac_rx_buf1_len() reports the full dma_buf_sz length for it even though the DMA engine only wrote the tail remainder into that buffer, so the reads extend past the received bytes and can reach beyond the end of the XSK pool buffer. GMAC4 always enables jumbo frames (GMAC_CONFIG_JE in GMAC_CORE_INIT), so an on-link peer can trigger such a split even when the interface MTU is left at 1500.
Set error when the 1:1 mapping check drops a descriptor, so the remaining descriptors of the frame - including the last one - are drained and released with xsk_buff_free() instead of being processed as a new frame. Account every freed buffer with dirty and count the dropped frame once in the poll budget / rx_pkt_n. The direct 1:1 mapping drop also increments rx_dropped.
Use a bit test instead of an equality test for discard_frame. Commit 644b8437ccef9e ("net: stmmac: dwmac4: report Rx checksum errors in status") made dwmac4_wrback_get_rx_status() set discard_frame on RDES3_ERROR_SUMMARY and OR in csum_none on RDES1_IP_HDR_ERROR or RDES1_IP_PAYLOAD_ERROR, so it can return discard_frame | csum_none. The old "status == discard_frame" test missed that value and delivered frames with CRC, overflow, watchdog or giant errors to the stack in stmmac_rx() - or to XDP/XSK in stmmac_rx_zc() - when they also failed the IP checksum. The change therefore affects the regular RX path, not only zero-copy. The bit test is also required for the discard_frame | rx_not_ls value returned for non-last legacy descriptors below.
Normalize the legacy normal and enhanced descriptor callbacks to report rx_not_ls together with discard_frame for non-last descriptors. This allows both stmmac_rx_zc() and stmmac_rx() to drain split frames on dwmac100 and dwmac1000 instead of reparsing the final fragment as a new packet.
--- .../net/ethernet/stmicro/stmmac/enh_desc.c | 2 +- .../net/ethernet/stmicro/stmmac/norm_desc.c | 2 +- .../net/ethernet/stmicro/stmmac/stmmac_main.c | 21 ++++++++++++------- 3 files changed, 15 insertions(+), 10 deletions(-)
drivers/net/ethernet/stmicro/stmmac/enh_desc.c +1 -1
@@ -205,7 +205,7 @@ static int enh_desc_get_rx_status(struct stmmac_extra_stats *x,if (unlikely (!(rdes0 &RDES0_LAST_DESCRIPTOR ))) { x->rx_length++; -return discard_frame; +return discard_frame | rx_not_ls; }if (unlikely (rdes0 &RDES0_ERROR_SUMMARY )) {
drivers/net/ethernet/stmicro/stmmac/norm_desc.c +1 -1
@@ -70,7 +70,7 @@ static int ndesc_get_rx_status(struct stmmac_extra_stats *x,if (unlikely (!(rdes0 &RDES0_LAST_DESCRIPTOR ))) { x->rx_length++; -return discard_frame; +return discard_frame | rx_not_ls; }if (unlikely (rdes0 &RDES0_ERROR_SUMMARY )) {
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +13 -8
@@ -5621,18 +5621,21 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) &rx_q->dma_erx[entry], status); } -if (unlikely (status == discard_frame)) { -xsk_buff_free (buf->xdp); - buf->xdp =NULL ; - dirty++; + +if (unlikely (!error && (status & discard_frame))) { error =1 ;if (!priv->hwts_rx_en) rx_errors++; } -if (unlikely (error && (status & rx_not_ls))) - goto read_again;if (unlikely (error)) { +xsk_buff_free (buf->xdp); + buf->xdp =NULL ; + dirty++; + +if (status & rx_not_ls) + goto read_again; + count++;continue ; }
@@ -5641,8 +5644,9 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)if (likely (status & rx_not_ls)) {xsk_buff_free (buf->xdp); buf->xdp =NULL ; + rx_dropped++; + error =1 ; dirty++; - count++; goto read_again; }
@@ -5814,7 +5818,8 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) &rx_q->dma_erx[entry], status); } -if (unlikely (status == discard_frame)) { + +if (unlikely (status & discard_frame)) {page_pool_put_page (rx_q->page_pool, buf->page,0 , true); buf->page =NULL ; error =1 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 138/1005 net: stmmac: drop multi-buffer frames in XDP mode
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Bianconi <[email protected]>
[ Upstream commit 52ffd771e0029c5ad0504b1b4a8b7f932b65eea3 ]
stmmac_rx() runs the XDP program once per descriptor buffer and uses skb == NULL as the only marker for the start of a frame. A frame larger than one buffer is split by the hardware across several descriptors; GMAC4 enables jumbo frames unconditionally (GMAC_CONFIG_JE in GMAC_CORE_INIT), so an on-link peer can deliver such a frame even when the interface MTU is left at 1500.
When an XDP verdict ends a non-last descriptor, skb is cleared and the next descriptor of the same hardware frame is parsed as a new frame. For XDP_CONSUMED this happens via read_again with len preserved, so stmmac_rx_buf1_len() then returns min(dma_buf_sz, plen - len) for the last descriptor, which can be as small as 0-3 bytes. buf1_len -= ETH_FCS_LEN underflows and xdp_prepare_buff() puts data_end far past data; on XDP_PASS this produces an skb whose length is close to 4G that reaches the network stack (skb->tail and skb->len are 32-bit and wrap below skb->end, so skb_over_panic() does not fire). A 4+ byte tail is instead offered to the XDP program and delivered as a standalone mid-payload Ethernet frame on XDP_PASS. XDP_TX/XDP_REDIRECT instead falls through to the next iteration, resetting the running length, so the tail is re-parsed as a full-size new frame.
The same fault exists when a single descriptor uses its second buffer:
buffer2 is now handed to the hardware for non-SPH frames on GMAC4/XGMAC, so a frame up to 2 * dma_buf_sz can land on a single descriptor while the XDP program still only sees the first buffer. XDP_TX then transmits a truncated frame, and XDP_PASS appends the second buffer only after the program has already run over the first one.
XDP does not support scatter-gather frames until the multi-buffer rework, so drop the whole frame instead. When a non-last descriptor is seen while an XDP program is attached, mark the frame as errored and drain the remaining descriptors, including the last. A descriptor that uses its second buffer is dropped directly before the program runs as well; in XDP mode it is necessarily the last descriptor of the frame, so it does not need the error marker. Removing the re-parse lets both XDP verdict branches simply complete the packet via next.
The buffers consumed by the discard path are no longer returned to the page pool, and the new SG and second-buffer drops do not return them either. They stay in rx_q->buf_pool[] and stmmac_rx_refill() reuses them in place, allocating only when a slot is empty. This is safe because the drop checks run before the buffer is synced for CPU access or prefetched. The discard-path change and the in-place reuse apply with or without an XDP program attached.
The !error guard on the discard check also changes the accounting for errored multi-descriptor frames on dwmac100/dwmac1000: rx_errors is incremented once per frame instead of once per descriptor. This too is independent of XDP mode.
Note: the subsequent "net: stmmac: rework stmmac_rx to support XDP rx multi-buff" accumulates the whole frame into a single xdp_buff and supersedes this patch; the fix is kept so the net portion of the series stands on its own.
--- .../net/ethernet/stmicro/stmmac/stmmac_main.c | 35 ++++++++++--------- 1 file changed, 19 insertions(+), 16 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +19 -16
@@ -5819,18 +5819,23 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) status); } -if (unlikely (status & discard_frame)) { -page_pool_put_page (rx_q->page_pool, buf->page,0 , true); - buf->page =NULL ; +if (unlikely (!error && (status & discard_frame))) { error =1 ;if (!priv->hwts_rx_en) rx_errors++; } -if (unlikely (error && (status & rx_not_ls))) - goto read_again; +/* We do not support SG in XDP mode */ +if (unlikely (!error && (status & rx_not_ls) && +stmmac_xdp_is_enabled (priv))) { + rx_dropped++; + error =1 ; + }if (unlikely (error)) { +if (status & rx_not_ls) + goto read_again; +dev_kfree_skb (skb); goto next; }
@@ -5842,6 +5847,14 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) buf2_len =stmmac_rx_buf2_len (priv, p, status, len); len += buf2_len; +/* Drop the packet if it is split over buf1 and buf2 on a +* single descriptor if the interface is running in XDP mode. +*/ +if (unlikely (stmmac_xdp_is_enabled (priv) && buf2_len)) { + rx_dropped++; + goto next; + } +/* ACS is disabled; strip manually. */ if (likely (!(status & rx_not_ls))) len -=ETH_FCS_LEN ;
@@ -5891,17 +5904,7 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) sync_len, true); buf->page =NULL ; rx_dropped++; - -/* Clear skb as it was set as -* status by XDP program. -*/ - skb =NULL ; - -if (unlikely ((status & rx_not_ls))) - goto read_again; - - count++; -continue ; + goto next; }else if (xdp_res & (STMMAC_XDP_TX |STMMAC_XDP_REDIRECT )) { xdp_status |= xdp_res;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 139/1005 net: stmmac: copy XDP metadata in AF_XDP zero-copy RX
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Bianconi <[email protected]>
[ Upstream commit 41d78e9ac0984f0e9577e5312e62400b5a6760c8 ]
stmmac_construct_skb_zc() reserves headroom for the XDP metadata and records the length reported by the XDP program, but only copies the packet data starting at xdp->data. The bytes in [xdp->data_meta, xdp->data) are never copied into the new skb, so the skb advertises metadata that is not there: after eth_type_trans() anchors mac_header, data_meta points at uninitialized headroom instead of what the program wrote.
Copy the metadata together with the packet data starting at xdp->data_meta, leaving skb->data at the start of the frame and the metadata immediately before it, and record its length. This keeps data_meta valid for the stack and TC BPF after eth_type_trans() anchors mac_header.
--- drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +2 -1
@@ -5418,7 +5418,8 @@ static struct sk_buff *stmmac_construct_skb_zc(struct stmmac_channel *ch,return NULL ;skb_reserve (skb, xdp->data - xdp->data_hard_start); -memcpy (__skb_put (skb, datasize), xdp->data, datasize); +__skb_put (skb, datasize); +memcpy (skb->data - metasize, xdp->data_meta, datasize + metasize);if (metasize)skb_metadata_set (skb, metasize);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 140/1005 net: stmmac: fix VLAN tag stripping on short and non-linear RX frames
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Bianconi <[email protected]>
[ Upstream commit 68bdbffcae08699af5c16f7a2ec61a5489b78dbe ]
stmmac_rx_vlan() reads the VLAN header straight from skb->data and removes it with skb_pull(), assuming the header is fully present in the linear part of the skb. XDP can change the frame length and head layout before the tag is stripped.
An XDP program can use bpf_xdp_adjust_tail() to shrink a frame to as little as ETH_HLEN while bytes 12-13 still contain a VLAN ethertype. The driver then reads h_vlan_TCI past skb->len and pops the tag, leaving less than ETH_HLEN in the skb. eth_type_trans() cannot pull the MAC header, so a malformed skb is passed up. The TCI is also read from the wrong place when the tag is not fully in the linear head, e.g. when it spans into a frag.
Read h_vlan_proto after pulling ETH_HLEN into the linear part, and check it together with the device features. Only if the tag is actually going to be popped, pull VLAN_ETH_HLEN and re-derive the header pointer afterwards, as pskb_may_pull() may reallocate the skb head. Return an error so the callers can drop a frame that claims a VLAN tag but cannot provide the full header. This also drops and counts frames shorter than ETH_HLEN in rx_dropped, even when VLAN RX offload is disabled; bpf_xdp_adjust_head() and bpf_xdp_adjust_tail() cannot produce such a frame, so it only affects a runt that reaches the driver, and dropping it is safer than handing it to eth_type_trans().
Also move the XDP metadata written with bpf_xdp_adjust_meta() together with the MAC header when the tag is popped, so data_meta still points at the metadata after eth_type_trans() anchors mac_header, instead of at the first bytes of the destination MAC.
--- .../net/ethernet/stmicro/stmmac/stmmac_main.c | 48 +++++++++++++------ 1 file changed, 33 insertions(+), 15 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +33 -15
@@ -5063,22 +5063,35 @@ static netdev_features_t stmmac_features_check(struct sk_buff *skb,return vlan_features_check (skb, features); } -static void stmmac_rx_vlan (struct net_device *dev,struct sk_buff *skb) +static int stmmac_rx_vlan (struct net_device *dev,struct sk_buff *skb) { -struct vlan_ethhdr *veth =skb_vlan_eth_hdr (skb); -__be16 vlan_proto = veth->h_vlan_proto; -u16 vlanid; +struct vlan_ethhdr *veth; -if ((vlan_proto ==htons (ETH_P_8021Q ) && +if (!pskb_may_pull (skb,ETH_HLEN )) +return -EINVAL ; + + veth =skb_vlan_eth_hdr (skb); +if ((veth->h_vlan_proto ==htons (ETH_P_8021Q ) && dev->features &NETIF_F_HW_VLAN_CTAG_RX ) || - (vlan_proto ==htons (ETH_P_8021AD ) && + (veth->h_vlan_proto ==htons (ETH_P_8021AD ) && dev->features &NETIF_F_HW_VLAN_STAG_RX )) { +__be16 vlan_proto = veth->h_vlan_proto; +u8 meta_len =skb_metadata_len (skb); +u16 vlanid; +/* pop the vlan tag */ +if (!pskb_may_pull (skb,VLAN_ETH_HLEN )) +return -EINVAL ; + + veth =skb_vlan_eth_hdr (skb); vlanid =ntohs (veth->h_vlan_TCI); -memmove (skb->data +VLAN_HLEN , veth,ETH_ALEN *2 ); +memmove (skb->data - meta_len +VLAN_HLEN , + skb->data - meta_len, meta_len +ETH_ALEN *2 );skb_pull (skb,VLAN_HLEN );__vlan_hwaccel_put_tag (skb, vlan_proto, vlanid); } + +return 0 ; }/**
@@ -5445,12 +5458,15 @@ static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue, }stmmac_get_rx_hwtstamp (priv, p, np, skb); -if (priv->hw->hw_vlan_en) +if (priv->hw->hw_vlan_en) {/* MAC level stripping. */ stmmac_rx_hw_vlan (priv, priv->hw, p, skb); -else -/* Driver level stripping. */ -stmmac_rx_vlan (priv->dev, skb); + }else if (stmmac_rx_vlan (priv->dev, skb)) { +dev_kfree_skb_any (skb); + priv->xstats.rx_dropped++; +return ; + } + skb->protocol =eth_type_trans (skb, priv->dev);if (unlikely (!coe) || !stmmac_has_ip_ethertype (skb))
@@ -5973,12 +5989,14 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)stmmac_get_rx_hwtstamp (priv, p, np, skb); -if (priv->hw->hw_vlan_en) +if (priv->hw->hw_vlan_en) {/* MAC level stripping. */ stmmac_rx_hw_vlan (priv, priv->hw, p, skb); -else -/* Driver level stripping. */ -stmmac_rx_vlan (priv->dev, skb); + }else if (stmmac_rx_vlan (priv->dev, skb)) { +dev_kfree_skb_any (skb); + rx_dropped++; + goto next; + } skb->protocol =eth_type_trans (skb, priv->dev);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 141/1005 net: stmmac: fix XDP RX buffer DMA sync length
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Bianconi <[email protected]>
[ Upstream commit 363ff816277d4c7064514b160e655bed1dfb3ed8 ]
stmmac_rx() bounded the DMA sync length by the largest data_end seen before and after the XDP program and passed it to page_pool_put_page() on the XDP_CONSUMED path. bpf_xdp_adjust_tail() zeroes the grown area, which dirties the CPU cache, but a later negative adjust only moves data_end back. If the program grows and then shrinks the tail, both endpoints miss the zeroed range, so those dirty cache lines are not written back before the page is reused.
The length was also wrong since commit 88095728511e ("net: stmmac: fix rx Scatter-Gather support") moved the page_pool DMA window to offset 0 and set max_len to dma_buf_sz + page_offset: the driver still subtracted buf->page_offset, so it synced [base, data_end - page_offset) instead of [base, data_end).
On a non-coherent platform those dirty lines can be evicted after the device has DMA'd the next frame into the recycled page and corrupt it.
Sync the whole page_pool DMA window on the XDP_CONSUMED path with page_pool_recycle_direct(), as the PASS path and page_pool allocation already do. The device only writes [page_offset, page_offset + dma_buf_sz), so syncing [base, base + max_len) covers every cache line it can touch, regardless of how the program adjusted the packet.
--- .../net/ethernet/stmicro/stmmac/stmmac_main.c | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +2 -15
@@ -5877,8 +5877,6 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) len -=ETH_FCS_LEN ;if (!skb) { -unsigned int pre_len, sync_len; -/* Each frame starts here: reset the FCS handling */ fcs_stripped = false;
@@ -5896,29 +5894,18 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)xdp_prepare_buff (&ctx.xdp,page_address (buf->page), buf->page_offset, buf1_len, true); - pre_len = ctx.xdp.data_end - ctx.xdp.data_hard_start - - buf->page_offset; - ctx.priv = priv; ctx.desc = p; ctx.ndesc = np; skb =stmmac_xdp_run_prog (priv, &ctx.xdp); -/* Due xdp_adjust_tail: DMA sync for_device -* cover max len CPU touch -*/ - sync_len = ctx.xdp.data_end - ctx.xdp.data_hard_start - - buf->page_offset; - sync_len =max (sync_len, pre_len); -/* For Not XDP_PASS verdict */ if (IS_ERR (skb)) {unsigned int xdp_res = -PTR_ERR (skb);if (xdp_res &STMMAC_XDP_CONSUMED ) { -page_pool_put_page (rx_q->page_pool, -virt_to_head_page (ctx.xdp.data), - sync_len, true); +page_pool_recycle_direct (rx_q->page_pool, +virt_to_head_page (ctx.xdp.data)); buf->page =NULL ; rx_dropped++; goto next;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 142/1005 ata: libata-core: Check device support before querying power state
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giuseppe Piscitelli <[email protected]>
[ Upstream commit ec585ac78742527f80495dd8f451dcda7e9e7f59 ]
The standby path queries the power state before checking whether the device accepts ATA power-management commands. This sends CHECK POWER MODE to ATAPI devices, including the QEMU DVD-ROM, which rejects it.
Run the existing taskfile initialization and device-class check first, as the active-power path already does.
--- drivers/ata/libata-core.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/ata/libata-core.c +4 -4
@@ -2059,6 +2059,10 @@ void ata_dev_power_set_standby(struct ata_device *dev)struct ata_taskfile tf;unsigned int err_mask; +/* Issue STANDBY IMMEDIATE command only if supported by the device */ +if (!ata_dev_power_init_tf (dev, &tf, false)) +return ; +/* If the device is already sleeping or in standby, do nothing. */ if ((dev->flags &ATA_DFLAG_SLEEPING ) || !ata_dev_power_is_active (dev))
@@ -2077,10 +2081,6 @@ void ata_dev_power_set_standby(struct ata_device *dev) system_entering_hibernation())return ; -/* Issue STANDBY IMMEDIATE command only if supported by the device */ -if (!ata_dev_power_init_tf (dev, &tf, false)) -return ; -ata_dev_notice (dev,"Entering standby power mode\n" ); err_mask =ata_exec_internal (dev, &tf,NULL ,DMA_NONE ,NULL ,0 ,0 );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 143/1005 net: lan966x: dont free XDP buffers in fdma tx clear with budget 0
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daniel Machon <[email protected]>
[ Upstream commit 263a5514cb9535380734b5e300b298f82570eb57 ]
lan966x_fdma_tx_clear_buf() runs from the NAPI poll and frees the buffers of completed tx DCBs with napi_consume_skb(), page_pool_recycle_direct() and xdp_return_frame_bulk().
netpoll calls the NAPI poll with a budget of 0 and hardirqs disabled. With a budget of 0, a driver cannot call any XDP or page pool API.
Before this patch, the XDP_TX pages and ndo_xdp_xmit frames are freed regardless of the budget. With netconsole on the port that owns the FDMA NAPI, such a buffer is freed with hardirqs disabled, and __page_pool_put_page() warns via lockdep_assert_no_hardirq().
Leave the XDP buffers of completed DCBs in place when the budget is 0, and free them in the next NAPI poll. napi_consume_skb() already handles a budget of 0, so skbs are still freed.
Found by an AI code review agent. Reproduced on a lan9668 board with a modified kernel that runs the NAPI poll with a budget of 0 and hardirqs disabled. With the fix the warning is gone.
--- drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c +6 -0
@@ -354,6 +354,12 @@ static void lan966x_fdma_tx_clear_buf(struct lan966x *lan966x, int weight)if (!fdma_db_is_done (db))continue ; +/* XDP and page pool APIs can't be used with a budget of 0. +* Leave these buffers for the next NAPI poll. +*/ +if (!weight && !dcb_buf->use_skb) +continue ; + dcb_buf->dev->stats.tx_packets++; dcb_buf->dev->stats.tx_bytes += dcb_buf->len;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 144/1005 erofs: apply the stacked fs check to extra file-backed devices
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daejun Park <[email protected]>
[ Upstream commit e9aeaa63fd94b0d2bb9b303be5774b33ca9c01cf ]
erofs_fc_fill_super() rejects a file-backed mount whose image is on a file-backed EROFS or on a filesystem with s_stack_depth set. This bounds the nesting of reads. Extra devices given by device= are not checked. File-backed mounts can still nest through them without limit.
Apply the same check to extra devices.
--- fs/erofs/super.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-)
fs/erofs/super.c +14 -3
@@ -122,6 +122,14 @@ void *erofs_read_metadata(struct super_block *sb, struct erofs_buf *buf,return buffer; } +/* see the comment in erofs_fc_fill_super() */ +static bool erofs_is_stacked_file (struct file *file) +{ +struct super_block *sb =file_inode (file)->i_sb; + +return (sb->s_op == &erofs_sops && !sb->s_bdev) || sb->s_stack_depth; +} +static int erofs_init_device (struct erofs_buf *buf,struct super_block *sb,struct erofs_device_info *dif,erofs_off_t *pos) {
@@ -161,6 +169,11 @@ static int erofs_init_device(struct erofs_buf *buf, struct super_block *sb, }else if (!S_ISREG (file_inode (file)->i_mode)) {fput (file);return -EINVAL ; + }else if (erofs_is_stacked_file (file)) { +erofs_err (sb,"%s: file-backed devices cannot be on stacked fses" , + dif->path); +fput (file); +return -EINVAL ; }if (!dif->dax_dev &&test_opt (&sbi->opt,DAX_ALWAYS )) { erofs_info(sb, "DAX unsupported by %s. Turning off DAX.",
@@ -701,9 +714,7 @@ static int erofs_fc_fill_super(struct super_block *sb, struct fs_context *fc)* It MUST change if another fs plans to support them, which * may also require adjusting FILESYSTEM_MAX_STACK_DEPTH. */ - inode =file_inode (sbi->dif0.file); -if ((inode->i_sb->s_op == &erofs_sops && - !inode->i_sb->s_bdev) || inode->i_sb->s_stack_depth) { +if (erofs_is_stacked_file (sbi->dif0.file)) {erofs_err (sb,"file-backed mounts cannot be applied to stacked fses" );return -ENOTBLK ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 145/1005 drm/panel: visionox-r66451: Send the brightness value MSB first
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vladimir Zapolskiy <[email protected]>
[ Upstream commit 00fe6be187ffde738fdb71ea7deb671fc939e583 ]
The panel expects to get two bytes of the DCS Set Display Brightness command with the most significant byte first, and it uses the lower 12 bits of the value, use mipi_dsi_dcs_set_display_brightness_large() to correct the programmed brightness values.
Tested on the SM8350-HDK display card, the display brightness increases gradually with:
for v in $(seq 16 16 4095); do sleep 0.1; \
echo $v > /sys/class/backlight/ae94000.dsi.0/brightness; \
donewhile without the change the display is dark during all writes.
--- drivers/gpu/drm/panel/panel-visionox-r66451.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/panel/panel-visionox-r66451.c +1 -1
@@ -227,7 +227,7 @@ static int visionox_r66451_bl_update_status(struct backlight_device *bl)struct mipi_dsi_device *dsi =bl_get_data (bl);u16 brightness =backlight_get_brightness (bl); -return mipi_dsi_dcs_set_display_brightness (dsi, brightness); +return mipi_dsi_dcs_set_display_brightness_large (dsi, brightness); }static const struct backlight_ops visionox_r66451_bl_ops = {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 146/1005 drm/panel: visionox-r66451: Wait longer after the panel reset
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vladimir Zapolskiy <[email protected]>
[ Upstream commit b4b2778d5e175b166e4a27e5df5d61da468ad004 ]
The initialization sequence is sent 10ms after the panel reset is deasserted, however on the SM8350-HDK display card the panel does not answer a DCS read at that time, as a result the panel initialization commands are lost, and the panel does not exit sleep mode and the display stays black. With the first command sent about 15ms after the reset the panel comes up reliably, so wait 20ms after deasserting the reset.
--- drivers/gpu/drm/panel/panel-visionox-r66451.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/panel/panel-visionox-r66451.c +1 -1
@@ -36,7 +36,7 @@ static void visionox_r66451_reset(struct visionox_r66451 *ctx)gpiod_set_value_cansleep (ctx->reset_gpio,1 );usleep_range (10000 ,10100 );gpiod_set_value_cansleep (ctx->reset_gpio,0 ); -usleep_range (10000 ,10100 ); +usleep_range (20000 ,21000 ); }static int visionox_r66451_on (struct visionox_r66451 *ctx)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 147/1005 ntfs: dont allow resident values to overlap the attribute header
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Namjae Jeon <[email protected]>
[ Upstream commit 99afbf38a5c571157526b7b1c6d8dd7ad1a234d5 ]
The resident value bounds check allows value_offset to point inside the attribute header. The reported image has an unnamed $DATA attribute with a value_offset of zero and a value_length of two, which passes lookup.
Appending to this file makes ntfs_resident_attr_value_resize() shrink the attribute record to eight bytes. Moving the following attributes then overwrites the resident header fields, so the subsequent memset() uses a corrupted value_offset and writes outside the MFT record buffer.
Require the resident value to start after the complete resident header. Both lookup paths then return -EIO for the corrupt record, before callers can resize or access its value.
--- fs/ntfs/attrib.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
fs/ntfs/attrib.c +6 -3
@@ -704,17 +704,20 @@ static bool ntfs_resident_attr_value_get(const struct attr_record *a, struct ntfs_resident_attr_value *value) {u32 attr_len; +u32 min_len;u16 value_offset; attr_len =le32_to_cpu (a->length); - if (attr_len < offsetof(struct attr_record, data.resident.reserved) + - sizeof(a->data.resident.reserved)) + min_len = offsetof(struct attr_record, data.resident.reserved) + +sizeof (a->data.resident.reserved); +if (attr_len < min_len)return false; value->len =le32_to_cpu (a->data.resident.value_length); value_offset =le16_to_cpu (a->data.resident.value_offset); -if (value->len > attr_len || value_offset > attr_len - value->len) +if (value_offset < min_len || value->len > attr_len || + value_offset > attr_len - value->len)return false; value->data = (const u8 *)a + value_offset;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 148/1005 sfc: ptp: drop the stale frequency reset in efx_ptp_start()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alex Austin <[email protected]>
[ Upstream commit 21d4917cfc8b6837c44d8aa186941a6a16ec17a0 ]
FW does not touch the clock frequency state on MC_CMD_PTP_OP_DISABLE or MC_CMD_PTP_OP_ENABLE, so the driver doesn't need to either. Doing so just desyncs the driver's cached current_adjfreq from what FW still has programmed.
Resetting current_adjfreq to 0 here means the first efx_phc_adjtime() call after efx_ptp_start() reprograms the NIC's clock frequency to 0, since efx_phc_adjtime() always sends current_adjfreq to FW alongside the time step. efx_ptp_start() runs on every SIOCSHWTSTAMP mode change, on ifup, and on the reset_required path in efx_ptp_worker(), so each of those silently drops any frequency correction the PTP servo had already applied.
efx_ptp_start() is also reached from reset recovery, but that is fine:
on an FLR or PCIe reset FW does not touch the NIC clock, and on a full MC reboot the clock is reset to 1970, so a stale current_adjfreq from before the reset is hardly consequential - especially as it is bound to MAX_PPB, 1000000 ppb.
--- drivers/net/ethernet/sfc/ptp.c | 1 - 1 file changed, 1 deletion(-)
drivers/net/ethernet/sfc/ptp.c +0 -1
@@ -1446,7 +1446,6 @@ static int efx_ptp_start(struct efx_nic *efx) goto fail; ptp->evt_frag_idx =0 ; - ptp->current_adjfreq =0 ;return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 149/1005 sfc: ptp: serialize host and MC synchronization transactions
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alex Austin <[email protected]>
[ Upstream commit f707347b33feebdd67633bccea52f96807c18d6e ]
efx_ptp_synchronize() clears the MC-ready DMA flag before efx_mcdi_rpc_start() acquires the MCDI interface, and processes results into ptp->timeset[] after efx_mcdi_rpc_finish() has released it. The PPS worker and the hwtstamp enable path can therefore clobber each other's handshake flag and timesets.
Hold a PHC mutex across the whole transaction and over the clock operations, so efx_phc_settime() reads and adjusts atomically and current_adjfreq is consistently read and written under one lock. Also bail out when efx_mcdi_rpc_start() fails rather than finishing an RPC that was never acquired.
--- drivers/net/ethernet/sfc/ptp.c | 81 +++++++++++++++++++++++----------- 1 file changed, 55 insertions(+), 26 deletions(-)
drivers/net/ethernet/sfc/ptp.c +55 -26
@@ -36,6 +36,7 @@#include <linux/errno.h> #include <linux/ktime.h> #include <linux/module.h> +#include <linux/mutex.h> #include <linux/pps_kernel.h> #include <linux/ptp_clock_kernel.h> #include "net_driver.h"
@@ -272,6 +273,8 @@ struct efx_ptp_rxfilter {* frequency adjustment into a fixed point fractional nanosecond format. * @current_adjfreq: Current ppb adjustment. * @phc_clock: Pointer to registered phc device (if primary function) +* @phc_lock: Serializes PHC commands and synchronization, and protects +* @current_adjfreq * @phc_clock_info: Registration structure for phc device * @pps_work: pps work task for handling pps events * @pps_workwq: pps work queue
@@ -331,6 +334,7 @@ struct efx_ptp_data {unsigned int adjfreq_ppb_shift;s64 current_adjfreq;struct ptp_clock *phc_clock; +struct mutex phc_lock;struct ptp_clock_info phc_clock_info;struct work_struct pps_work;struct workqueue_struct *pps_workwq;
@@ -1008,7 +1012,14 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),return 0 ; } -/* Synchronize times between the host and the MC */ +/* Synchronize times between the host and the MC. +* +* The MC serializes PTP requests, so MC_CMD_PTP_OP_ADJUST cannot be applied +* while MC_CMD_PTP_OP_SYNCHRONIZE is collecting timesets. This holds across +* functions of a controller, which share the clock but adjust it only through +* the function that registered it, so a secondary function can capture here +* without serializing against the primary. +*/ static int efx_ptp_synchronize (struct efx_nic *efx,unsigned int num_readings) {struct efx_ptp_data *ptp = efx->ptp_data;
@@ -1027,11 +1038,14 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)MCDI_SET_QWORD (synch_buf,PTP_IN_SYNCHRONIZE_START_ADDR , ptp->start.dma_addr); +mutex_lock (&ptp->phc_lock); +/* Clear flag that signals MC ready */ WRITE_ONCE (*start,0 ); rc =efx_mcdi_rpc_start (efx,MC_CMD_PTP , synch_buf,MC_CMD_PTP_IN_SYNCHRONIZE_LEN ); -EFX_WARN_ON_ONCE_PARANOID (rc); +if (rc) + goto out;/* Wait for start from MCDI (or timeout) */ timeout = jiffies +msecs_to_jiffies (MAX_SYNCHRONISE_WAIT_MS );
@@ -1062,11 +1076,13 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings) ++ptp->no_time_syncs; } +out:/* Increment the bad syncs counter if the synchronize fails, whatever * the reason. */ if (rc !=0 ) ++ptp->bad_syncs; +mutex_unlock (&ptp->phc_lock);return rc; }
@@ -1569,6 +1585,7 @@ int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel)if (!efx->ptp_data)return -ENOMEM ; +mutex_init (&ptp->phc_lock); ptp->efx = efx; ptp->channel = channel;
@@ -1640,6 +1657,7 @@ int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel)efx_nic_free_buffer (efx, &ptp->start); fail1: +mutex_destroy (&ptp->phc_lock);kfree (efx->ptp_data); efx->ptp_data =NULL ;
@@ -1694,6 +1712,7 @@ void efx_ptp_remove(struct efx_nic *efx)destroy_workqueue (efx->ptp_data->workwq);efx_nic_free_buffer (efx, &efx->ptp_data->start); +mutex_destroy (&efx->ptp_data->phc_lock);kfree (efx->ptp_data); efx->ptp_data =NULL ; }
@@ -2105,23 +2124,23 @@ static int efx_phc_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)MCDI_SET_QWORD (inadj,PTP_IN_ADJUST_FREQ , adjustment_ns);MCDI_SET_DWORD (inadj,PTP_IN_ADJUST_SECONDS ,0 );MCDI_SET_DWORD (inadj,PTP_IN_ADJUST_NANOSECONDS ,0 ); +mutex_lock (&ptp_data->phc_lock); rc =efx_mcdi_rpc (efx,MC_CMD_PTP , inadj,sizeof (inadj),NULL ,0 ,NULL ); -if (rc !=0 ) -return rc; - - ptp_data->current_adjfreq = adjustment_ns; -return 0 ; +if (!rc) + ptp_data->current_adjfreq = adjustment_ns; +mutex_unlock (&ptp_data->phc_lock); +return rc; } -static int efx_phc_adjtime (struct ptp_clock_info *ptp,s64 delta) +static int _efx_phc_adjtime (struct efx_ptp_data *ptp_data,s64 delta) + __must_hold(&ptp_data->phc_lock) { -u32 nic_major, nic_minor; -struct efx_ptp_data *ptp_data =container_of (ptp, - struct efx_ptp_data, - phc_clock_info); -struct efx_nic *efx = ptp_data->efx;MCDI_DECLARE_BUF (inbuf,MC_CMD_PTP_IN_ADJUST_LEN ); +struct efx_nic *efx = ptp_data->efx; +u32 nic_major, nic_minor; + +lockdep_assert_held (&ptp_data->phc_lock); efx->ptp_data->ns_to_nic_time (delta, &nic_major, &nic_minor);
@@ -2134,6 +2153,18 @@ static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta) NULL, 0, NULL); } +static int efx_phc_adjtime (struct ptp_clock_info *ptp,s64 delta) +{ + struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data, + phc_clock_info); +int rc; + +mutex_lock (&ptp_data->phc_lock); + rc =_efx_phc_adjtime (ptp_data, delta); +mutex_unlock (&ptp_data->phc_lock); +return rc; +} +static int efx_phc_gettime (struct ptp_clock_info *ptp,struct timespec64 *ts) { struct efx_ptp_data *ptp_data = container_of(ptp,
@@ -2165,23 +2196,21 @@ static int efx_phc_settime(struct ptp_clock_info *ptp, {/* Get the current NIC time, efx_phc_gettime. * Subtract from the desired time to get the offset -* call efx_phc_adjtime with the offset +* call _efx_phc_adjtime with the offset */ + struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data, + phc_clock_info); +struct timespec64 time_now, delta;int rc; -struct timespec64 time_now; -struct timespec64 delta; +mutex_lock (&ptp_data->phc_lock); rc =efx_phc_gettime (ptp, &time_now); -if (rc !=0 ) -return rc; - - delta =timespec64_sub (*e_ts, time_now); - - rc =efx_phc_adjtime (ptp,timespec64_to_ns (&delta)); -if (rc !=0 ) -return rc; - -return 0 ; +if (!rc) { + delta =timespec64_sub (*e_ts, time_now); + rc =_efx_phc_adjtime (ptp_data,timespec64_to_ns (&delta)); + } +mutex_unlock (&ptp_data->phc_lock); +return rc; } static int efx_phc_enable(struct ptp_clock_info *ptp,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 150/1005 sfc: ptp: avoid racing PPS timestamp updates
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alex Austin <[email protected]>
[ Upstream commit 23d23e6c6517d0fea4f64340a23e33c89f82c03c ]
efx_ptp_pps_worker() can race with SIOCHWTSTAMP via efx_ptp_change_mode(). After the worker completes synchronization, the ioctl can start another synchronization and update host_time_pps while the worker copies it into the PPS event. This can report a partially updated timestamp. Serializing synchronization transactions alone does not protect this copy, which happens after phc_lock is released.
Return the timestamp through the caller's own pps_event_time rather than the shared field in efx_ptp_data, so the worker reads storage no one else can write.
--- drivers/net/ethernet/sfc/ptp.c | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-)
drivers/net/ethernet/sfc/ptp.c +16 -10
@@ -268,7 +268,6 @@ struct efx_ptp_rxfilter {* @evt_frag_idx: Current fragment number * @evt_code: Last event code * @start: Address at which MC indicates ready for synchronisation -* @host_time_pps: Host time at last PPS * @adjfreq_ppb_shift: Shift required to convert scaled parts-per-billion * frequency adjustment into a fixed point fractional nanosecond format. * @current_adjfreq: Current ppb adjustment.
@@ -330,7 +329,6 @@ struct efx_ptp_data {int evt_frag_idx;int evt_code;struct efx_buffer start; -struct pps_event_time host_time_pps;unsigned int adjfreq_ppb_shift;s64 current_adjfreq;struct ptp_clock *phc_clock;
@@ -912,7 +910,8 @@ static void efx_ptp_read_timeset(MCDI_DECLARE_STRUCT_PTR(data),static int efx_ptp_process_times (struct efx_nic *efx,MCDI_DECLARE_STRUCT_PTR (synch_buf ),size_t response_length, -const struct pps_event_time *last_time) +const struct pps_event_time *last_time, +struct pps_event_time *host_time_pps) {unsigned number_readings = MCDI_VAR_ARRAY_LEN(response_length,
@@ -990,6 +989,10 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf), "PTP bad synchronisation seconds\n");return -EAGAIN ; } + +if (!host_time_pps) +return 0 ; + delta.tv_sec = (last_sec - start_sec) &1 ; delta.tv_nsec = last_time->ts_real.tv_nsec -
@@ -1006,8 +1009,8 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf), delta.tv_nsec +=ktime_to_timespec64 (mc_time).tv_nsec;/* Set PPS timestamp to match NIC top of second */ - ptp->host_time_pps = *last_time; -pps_sub_ts (&ptp->host_time_pps, delta); + *host_time_pps = *last_time; +pps_sub_ts (host_time_pps, delta);return 0 ; }
@@ -1020,7 +1023,8 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),* the function that registered it, so a secondary function can capture here * without serializing against the primary. */ -static int efx_ptp_synchronize (struct efx_nic *efx,unsigned int num_readings) +static int efx_ptp_synchronize (struct efx_nic *efx,unsigned int num_readings, +struct pps_event_time *host_time_pps) {struct efx_ptp_data *ptp = efx->ptp_data;MCDI_DECLARE_BUF (synch_buf,MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX );
@@ -1069,7 +1073,7 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings) &response_length);if (rc ==0 ) { rc =efx_ptp_process_times (efx, synch_buf, response_length, - &last_time); + &last_time, host_time_pps);if (rc ==0 ) ++ptp->good_syncs;else
@@ -1501,14 +1505,15 @@ static void efx_ptp_pps_worker(struct work_struct *work) {struct efx_ptp_data *ptp = container_of(work, struct efx_ptp_data, pps_work); +struct pps_event_time host_time_pps = {};struct efx_nic *efx = ptp->efx;struct ptp_clock_event ptp_evt; -if (efx_ptp_synchronize (efx,PTP_SYNC_ATTEMPTS )) +if (efx_ptp_synchronize (efx,PTP_SYNC_ATTEMPTS , &host_time_pps))return ; ptp_evt.type =PTP_CLOCK_PPSUSR ; - ptp_evt.pps_times = ptp->host_time_pps; + ptp_evt.pps_times = host_time_pps;ptp_clock_event (ptp->phc_clock, &ptp_evt); }
@@ -1844,7 +1849,8 @@ int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted, rc =efx_ptp_start (efx);if (rc ==0 ) { rc =efx_ptp_synchronize (efx, -PTP_SYNC_ATTEMPTS *2 ); +PTP_SYNC_ATTEMPTS *2 , +NULL );if (rc !=0 )efx_ptp_stop (efx); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 151/1005 virtio-spi: Fix virtio_spi_config kernel-doc
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
[ Upstream commit 62b0a9b11e94a4bc7f67c89348d0619cba82b54b ]
struct virtio_spi_config contains max_cs_inactive_ns, but its kernel-doc describes max_cs_incative_ns. This leaves the real member undescribed and adds a nonexistent member to the generated documentation.
Correct the spelling.
Message-ID: <[email protected]>
--- include/uapi/linux/virtio_spi.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
include/uapi/linux/virtio_spi.h +1 -1
@@ -73,7 +73,7 @@* @max_cs_hold_ns: the maximum delay supported before chipselect is deasserted, * in ns unit, 0 means delay is not supported to introduce before chipselect * is deasserted. -* @max_cs_incative_ns: maximum delay supported after chipselect is deasserted, +* @max_cs_inactive_ns: maximum delay supported after chipselect is deasserted, * in ns unit, 0 means delay is not supported to introduce after chipselect is * deasserted. */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 152/1005 virtio_ring: reset IN_ORDER state in virtqueue_init()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li RongQing <[email protected]>
[ Upstream commit d7825623a9d4452f97da7ea0d84b2967d507ccf9 ]
The IN_ORDER feature uses additional software state to track the next available descriptor and in-flight descriptor batches.
virtqueue_init() resets the common virtqueue state, but free_head and batch_last.id are initialized only when the virtqueue is created. When an IN_ORDER virtqueue is reset, these fields can retain state from the previous queue instance.
Reset free_head and invalidate batch_last when initializing an IN_ORDER virtqueue. Keep this in virtqueue_init() so the state is initialized consistently for both newly created and reset virtqueues.
Message-ID: <[email protected]>
--- drivers/virtio/virtio_ring.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/virtio/virtio_ring.c +5 -0
@@ -559,6 +559,11 @@ static void virtqueue_init(struct vring_virtqueue *vq, u32 num) vq->in_use = false; vq->last_add_time_valid = false;#endif + +if (virtqueue_is_in_order (vq)) { + vq->free_head =0 ; + vq->batch_last.id =UINT_MAX ; + } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 153/1005 vdpa_sim: serialize IOTLB updates with dataplane access
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Linfeng Sun <[email protected]>
[ Upstream commit 8517ed4429a2eefd002dce00ea46e23e6714350b ]
The simulator translates IOTLB entries into iovecs or bvecs under iommu_lock, then drops the lock before copying data. A concurrent DMA unmap can delete the mapping and release its pinned backing pages while the copy is still in progress, leading to a UAF in _copy_from_iter().
Use the existing simulator mutex to serialize DMA map changes with the full backend work function. Also make vhost-vdpa stop device access before unpinning the backing pages. Otherwise, waiting in the simulator DMA unmap callback happens after the pages have already been released and cannot protect their lifetime.
Keep iommu_lock for the IOTLB table itself and avoid adding a second long-lived lock to the simulator.
I found this bug myself, though the patch was written with AI assistance.
Message-ID: <[email protected]>
--- drivers/vdpa/vdpa_sim/vdpa_sim.c | 4 ++++ drivers/vhost/vdpa.c | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-)
drivers/vdpa/vdpa_sim/vdpa_sim.c +4 -0
@@ -713,6 +713,7 @@ static int vdpasim_dma_map(struct vdpa_device *vdpa, unsigned int asid,if (asid >= vdpasim->dev_attr.nas)return -EINVAL ; +mutex_lock (&vdpasim->mutex);spin_lock (&vdpasim->iommu_lock);if (vdpasim->iommu_pt[asid]) {vhost_iotlb_reset (&vdpasim->iommu[asid]);
@@ -721,6 +722,7 @@ static int vdpasim_dma_map(struct vdpa_device *vdpa, unsigned int asid, ret =vhost_iotlb_add_range_ctx (&vdpasim->iommu[asid], iova, iova + size -1 , pa, perm, opaque);spin_unlock (&vdpasim->iommu_lock); +mutex_unlock (&vdpasim->mutex);return ret; }
@@ -733,6 +735,7 @@ static int vdpasim_dma_unmap(struct vdpa_device *vdpa, unsigned int asid,if (asid >= vdpasim->dev_attr.nas)return -EINVAL ; +mutex_lock (&vdpasim->mutex);spin_lock (&vdpasim->iommu_lock);if (vdpasim->iommu_pt[asid]) {vhost_iotlb_reset (&vdpasim->iommu[asid]);
@@ -740,6 +743,7 @@ static int vdpasim_dma_unmap(struct vdpa_device *vdpa, unsigned int asid, }vhost_iotlb_del_range (&vdpasim->iommu[asid], iova, iova + size -1 );spin_unlock (&vdpasim->iommu_lock); +mutex_unlock (&vdpasim->mutex);return 0 ; }
drivers/vhost/vdpa.c +2 -1
@@ -976,6 +976,8 @@ static void vhost_vdpa_pa_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,unsigned long pfn, pinned;while ((map =vhost_iotlb_itree_first (iotlb, start, last)) !=NULL ) { +/* Stop device access before releasing the pinned pages. */ +vhost_vdpa_general_unmap (v, map, asid); pinned =PFN_DOWN (map->size);for (pfn =PFN_DOWN (map->addr); pinned >0 ; pfn++, pinned--) {
@@ -985,7 +987,6 @@ static void vhost_vdpa_pa_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,unpin_user_page (page); }atomic64_sub (PFN_DOWN (map->size), &dev->mm->pinned_vm); -vhost_vdpa_general_unmap (v, map, asid);vhost_iotlb_map_free (iotlb, map); } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 154/1005 vdpa: invalidate DMA mappings before releasing memory
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Linfeng Sun <[email protected]>
[ Upstream commit acbf36deb53d9e14e4768bf58883795a8232aa5b ]
vdpa can release pinned pages and file references before the device stops using the corresponding mappings, allowing stale DMA to corrupt memory.
Invalidate mappings before dropping their backing references. For set_map backends, publish an IOTLB without the invalidated range and keep the old references if that fails. Do this immediately even within a batch.
Serialize vdpa_sim set_map updates with its worker so publishing a new map cannot race an active transfer. Abort mlx5 map replacement when resumable virtqueues cannot be suspended, since changing the memory region while those queues remain active would preserve the same stale DMA window. Reject zero-sized and wrapping invalidations before calculating their inclusive range end.
I found this bug myself, though the patch was written with AI assistance.
Message-ID: <[email protected]>
--- drivers/vdpa/mlx5/net/mlx5_vnet.c | 10 +++++++- drivers/vdpa/vdpa_sim/vdpa_sim.c | 3 +++ drivers/vhost/vdpa.c | 40 ++++++++++++++++++++++++------- 3 files changed, 43 insertions(+), 10 deletions(-)
drivers/vdpa/mlx5/net/mlx5_vnet.c +9 -1
@@ -3059,7 +3059,15 @@ static int mlx5_vdpa_change_map(struct mlx5_vdpa_dev *mvdev,bool teardown = !is_resumable (ndev);int err; -suspend_vqs (ndev,0 , ndev->cur_num_vqs); +if ((mvdev->status &VIRTIO_CONFIG_S_DRIVER_OK ) && !mvdev->suspended) { + err =suspend_vqs (ndev,0 , ndev->cur_num_vqs); +if (err && !teardown) { +for (int i =0 ; i < ndev->cur_num_vqs; i++) +resume_vqs (ndev, i,1 ); +mlx5_vdpa_put_mr (mvdev, new_mr); +return err; + } + }if (teardown) { err =save_channels_info (ndev);if (err) {
drivers/vdpa/vdpa_sim/vdpa_sim.c +3 -0
@@ -638,6 +638,7 @@ static int vdpasim_set_map(struct vdpa_device *vdpa, unsigned int asid,if (asid >= vdpasim->dev_attr.nas)return -EINVAL ; +mutex_lock (&vdpasim->mutex);spin_lock (&vdpasim->iommu_lock); iommu = &vdpasim->iommu[asid];
@@ -652,11 +653,13 @@ static int vdpasim_set_map(struct vdpa_device *vdpa, unsigned int asid, goto err; }spin_unlock (&vdpasim->iommu_lock); +mutex_unlock (&vdpasim->mutex);return 0 ; err:vhost_iotlb_reset (iommu);spin_unlock (&vdpasim->iommu_lock); +mutex_unlock (&vdpasim->mutex);return ret; }
drivers/vhost/vdpa.c +31 -9
@@ -998,10 +998,10 @@ static void vhost_vdpa_va_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,struct vdpa_map_file *map_file;while ((map =vhost_iotlb_itree_first (iotlb, start, last)) !=NULL ) { +vhost_vdpa_general_unmap (v, map, asid); map_file = (struct vdpa_map_file *)map->opaque;fput (map_file->file);kfree (map_file); -vhost_vdpa_general_unmap (v, map, asid);vhost_iotlb_map_free (iotlb, map); } }
@@ -1075,21 +1075,39 @@ static int vhost_vdpa_map(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,return 0 ; } -static void vhost_vdpa_unmap (struct vhost_vdpa *v, -struct vhost_iotlb *iotlb, -u64 iova,u64 size) +static int vhost_vdpa_unmap (struct vhost_vdpa *v, +struct vhost_iotlb *iotlb, +u64 iova,u64 size) {struct vdpa_device *vdpa = v->vdpa;const struct vdpa_config_ops *ops = vdpa->config; +struct vhost_iotlb_map *map; +struct vhost_iotlb new_iotlb;u32 asid =iotlb_to_asid (iotlb); +u64 last = iova + size -1 ; +int ret; -vhost_vdpa_iotlb_unmap (v, iotlb, iova, iova + size -1 , asid); +if (ops->set_map && !ops->dma_map) { +vhost_iotlb_init (&new_iotlb, iotlb->limit, iotlb->flags); +list_for_each_entry (map, &iotlb->list, link) { +if (map->start <= last && map->last >= iova) +continue ; + ret =vhost_iotlb_add_range_ctx (&new_iotlb, map->start, + map->last, map->addr, + map->perm, map->opaque); +if (ret) + goto reset; + } -if (ops->set_map) { -if (!v->in_batch) - ops->set_map (vdpa, asid, iotlb); + ret = ops->set_map (vdpa, asid, &new_iotlb); +reset: +vhost_iotlb_reset (&new_iotlb); +if (ret) +return ret; } +vhost_vdpa_iotlb_unmap (v, iotlb, iova, last, asid); +return 0 ; } static int vhost_vdpa_va_map(struct vhost_vdpa *v,
@@ -1339,7 +1357,11 @@ static int vhost_vdpa_process_iotlb_msg(struct vhost_dev *dev, u32 asid, r =vhost_vdpa_process_iotlb_update (v, iotlb, msg);break ;case VHOST_IOTLB_INVALIDATE : -vhost_vdpa_unmap (v, iotlb, msg->iova, msg->size); +if (!msg->size || msg->iova >U64_MAX - msg->size +1 ) { + r = -EINVAL ; +break ; + } + r =vhost_vdpa_unmap (v, iotlb, msg->iova, msg->size);break ;case VHOST_IOTLB_BATCH_BEGIN : v->batch_asid = asid;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 155/1005 vhost-scsi: preserve event ordering
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jia Jia <[email protected]>
[ Upstream commit a9a428115b7d8aa45e12e41899f90f60551bfa82 ]
vhost_scsi_send_evt() uses llist_add(), so pending events are LIFO. vhost_scsi_complete_events() walks the detached list directly. This can deliver a later hotplug or hotunplug event before an earlier one.
Reverse the detached list before processing it.
This keeps delivery in enqueue order.
Message-ID: <[email protected]>
--- drivers/vhost/scsi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/vhost/scsi.c +1 -1
@@ -667,7 +667,7 @@ static void vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop)struct llist_node *llnode;mutex_lock (&vq->mutex); - llnode =llist_del_all (&vs->vs_event_list); + llnode =llist_reverse_order (llist_del_all (&vs->vs_event_list));llist_for_each_entry_safe (evt, t, llnode, list) {if (!drop)vhost_scsi_do_evt_work (vs, evt);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 156/1005 vhost-scsi: do not relock event vq mutex on send_evt fallback
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jia Jia <[email protected]>
[ Upstream commit a016d03a9cfe29aeeba438f32f8e8f63291e3275 ]
vhost_scsi_send_evt() is called with the event virtqueue mutex held. If the worker is gone, the fallback currently calls vhost_scsi_complete_events(), which tries to acquire the same mutex again and deadlocks the caller.
Split event completion into a helper for callers that already hold the mutex and a locking wrapper for the event worker. Use the helper on the fallback path.
Message-ID: <[email protected]>
--- drivers/vhost/scsi.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-)
drivers/vhost/scsi.c +11 -4
@@ -660,19 +660,26 @@ vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt)vhost_scsi_log_write (vq, vq_log, log_num); } -static void vhost_scsi_complete_events (struct vhost_scsi *vs,bool drop) +/* Caller must hold the event virtqueue mutex. */ +static void __vhost_scsi_complete_events (struct vhost_scsi *vs,bool drop) { -struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT ].vq;struct vhost_scsi_evt *evt, *t;struct llist_node *llnode; -mutex_lock (&vq->mutex); llnode =llist_reverse_order (llist_del_all (&vs->vs_event_list));llist_for_each_entry_safe (evt, t, llnode, list) {if (!drop)vhost_scsi_do_evt_work (vs, evt);vhost_scsi_free_evt (vs, evt); } +} + +static void vhost_scsi_complete_events (struct vhost_scsi *vs,bool drop) +{ +struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT ].vq; + +mutex_lock (&vq->mutex); +__vhost_scsi_complete_events (vs, drop);mutex_unlock (&vq->mutex); }
@@ -1864,7 +1871,7 @@ vhost_scsi_send_evt(struct vhost_scsi *vs, struct vhost_virtqueue *vq,llist_add (&evt->list, &vs->vs_event_list);if (!vhost_vq_work_queue (vq, &vs->vs_event_work)) -vhost_scsi_complete_events (vs, true); +__vhost_scsi_complete_events (vs, true); }static void vhost_scsi_evt_handle_kick (struct vhost_work *work)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 157/1005 vhost: fix dirty logging for in-order used ring entries
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Linfeng Sun <[email protected]>
[ Upstream commit bfcde6b64769bc168037b8bd882de4def4b2b3f4 ]
With VIRTIO_F_IN_ORDER, one used ring element can represent multiple buffers, so vhost_add_used_n_in_order() can write consecutive elements to nonadjacent slots. Dirty logging combines the initial slot with a length based on the final position, which can miss written elements or log past the end of the ring.
Replay nheads[] after the write barrier and log the written slots, coalescing adjacent elements and splitting at gaps and wraps.
Message-ID: <[email protected]>
--- drivers/vhost/vhost.c | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-)
drivers/vhost/vhost.c +23 -7
@@ -3163,7 +3163,6 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,return -EINVAL ; start = vq->last_used_idx & (vq->num -1 ); - used = vq->used->ring + start;for (i =0 ; i < count; i++) {if (vhost_put_used (vq, &heads[i], start,1 )) {
@@ -3176,14 +3175,31 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq, }if (unlikely (vq->log_used)) { +unsigned int log_count =0 ; +int log_start =0 , next; +/* Make sure data is seen before log. */ smp_wmb (); -/* Log used ring entry write. */ -log_used (vq, ((void __user *)used - (void __user *)vq->used), - (vq->num - start) *sizeof *used); -if (start + count > vq->num) -log_used (vq,0 , - (start + count - vq->num) *sizeof *used); +/* Log contiguous runs of used ring entries that were written. */ + start = vq->last_used_idx & (vq->num -1 ); +for (i =0 ; i < count; i++) { +if (!log_count) + log_start = start; + log_count++; + + next = start + nheads[i]; +if (next >= vq->num) + next -= vq->num; +if (i +1 == count || next != start +1 ) { + used = vq->used->ring + log_start; +log_used (vq, + ((void __user *)used - + (void __user *)vq->used), + log_count *sizeof (*used)); + log_count =0 ; + } + start = next; + } } old = vq->last_used_idx;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 158/1005 virtio_pci: add missing newline to the pmcsr error message
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Maoxia <[email protected]>
[ Upstream commit 104d58a6d2592898fbb6989732600b07d543a8e5 ]
The error message emitted when the PCI power management control register cannot be read is not newline-terminated, so the next kernel message is appended to it on the same line.
Add the missing '\n'.
Message-ID: <[email protected]>
--- drivers/virtio/virtio_pci_common.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/virtio/virtio_pci_common.c +1 -1
@@ -633,7 +633,7 @@ static bool vp_supports_pm_no_reset(struct device *dev)pci_read_config_word (pci_dev, pci_dev->pm_cap +PCI_PM_CTRL , &pmcsr);if (PCI_POSSIBLE_ERROR (pmcsr)) { -dev_err (dev,"Unable to query pmcsr" ); +dev_err (dev,"Unable to query pmcsr\n" );return false; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 159/1005 vdpa: fix double free of the reply skb in vdpa_nl_cmd_dev_config_get_doit()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiang Mei <[email protected]>
[ Upstream commit 1f8824fe7f6eaaf2355404db08d3cd05a28aa576 ]
genlmsg_reply() consumes the reply skb on every outcome: netlink_unicast() frees it whether it queues it, drops it, or bails out early. vdpa_nl_cmd_dev_config_get_doit() lets its return value fall through to the shared error label, which calls nlmsg_free(msg) again and double-frees the sk_buff on any reply failure. The failure is reachable unprivileged:VDPA_CMD_DEV_CONFIG_GET carries no GENL_ADMIN_PERM, so batching several requests into one sendto() on a socket with a shrunken SO_RCVBUF fills the receive queue, and netlink_attachskb() then takes its MSG_DONTWAIT path, freeing the skb and returning -EAGAIN.
Set msg to NULL once genlmsg_reply() has consumed it so the shared exit path frees the skb only on the early error gotos that still own it; nlmsg_free(NULL) is a no-op.
BUG: KASAN: slab-use-after-free in sk_skb_reason_drop (net/core/skbuff.c:1220) Read of size 4 at addr ffff88800d99d49c by task exploit/147 Call Trace: sk_skb_reason_drop (net/core/skbuff.c:1220) vdpa_nl_cmd_dev_config_get_doit (drivers/vdpa/vdpa.c:1324) genl_family_rcv_msg_doit (net/netlink/genetlink.c:1114) genl_rcv_msg (net/netlink/genetlink.c:1194) netlink_rcv_skb (net/netlink/af_netlink.c:2556) genl_rcv (net/netlink/genetlink.c:1218) netlink_unicast (net/netlink/af_netlink.c:1345) netlink_sendmsg (net/netlink/af_netlink.c:1900) __sys_sendto (net/socket.c:2281) __x64_sys_sendto (net/socket.c:2284) entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:121) The buggy address belongs to the object at ffff88800d99d3c0 which belongs to the cache skbuff_head_cache of size 232 The buggy address is located 220 bytes inside of freed 232-byte region [ffff88800d99d3c0, ffff88800d99d4a8)
Message-ID: <[email protected]>
--- drivers/vdpa/vdpa.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/vdpa/vdpa.c +4 -3
@@ -1313,15 +1313,16 @@ static int vdpa_nl_cmd_dev_config_get_doit(struct sk_buff *skb, struct genl_info } err =vdpa_dev_config_fill (vdev, msg, info->snd_portid, info->snd_seq,0 , info->extack); -if (!err) +if (!err) { err =genlmsg_reply (msg, info); + msg =NULL ; + } mdev_err:put_device (dev); dev_err:up_read (&vdpa_dev_lock); -if (err) -nlmsg_free (msg); +nlmsg_free (msg);return err; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 160/1005 vhost: reject invalid IOTLB update permissions
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Linfeng Sun <[email protected]>
[ Upstream commit b179f21d2d8a60ede29a00472bffdefb0284ef39 ]
vhost_chr_write_iter() validates the type and size of an IOTLB update, but does not validate its permission field. An invalid permission can therefore reach perm_to_iommu_flags() and trigger its warning in vhost_vdpa_map().
Reject IOTLB UPDATE messages whose permission field is empty or contains bits outside VHOST_ACCESS_RW before dispatching them to a backend.
Message-ID: <[email protected]>
--- drivers/vhost/vhost.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/vhost/vhost.c +2 -1
@@ -1750,7 +1750,8 @@ ssize_t vhost_chr_write_iter(struct vhost_dev *dev, goto done; } -if (msg.type ==VHOST_IOTLB_UPDATE && msg.size ==0 ) { +if (msg.type ==VHOST_IOTLB_UPDATE && + (!msg.size || !msg.perm || (msg.perm & ~VHOST_ACCESS_RW ))) { ret = -EINVAL ; goto done; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 161/1005 vhost-vdpa: drop the parents vq callback before the call fd is released
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yu Zhang <[email protected]>
[ Upstream commit c9c1c1b7b31fc8b9a5d6c04f5f0ae647d081a39d ]
VHOST_SET_VRING_CALL releases the previous call eventfd inside vhost_vring_ioctl() -- it swaps the new context into vq->call_ctx.ctx and then eventfd_ctx_put()s the old one, which is a synchronous kfree(). The parent vdpa device is only told about the change afterwards, when vhost_vdpa_vring_ioctl() reaches ops->set_vq_cb().
Parent drivers cache the pointer handed to them in vdpa_callback::trigger and do not take a reference on it, so throughout that window the parent holds a dangling eventfd_ctx and may signal it. The documentation added with the field describes what signalling it means but says nothing about how long it stays valid.
This is the same hazard that "vhost_vdpa: assign irq bypass producer token correctly" addressed for the irq bypass producer token, by moving vhost_vdpa_unsetup_vq_irq() ahead of the vhost_vring_ioctl() call. The producer token was only one of the two consumers of that pointer; the one the parent keeps via ->set_vq_cb() was left behind the free.
With VDUSE the window is directly reachable from userspace, because the device emulation daemon can inject an interrupt at any time from a different fd, and neither side shares a lock with the other: VDUSE takes vq->irq_lock, vhost takes vhost_dev.mutex + vq->mutex.
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irqsave+0x76/0xe0 Write of size 4 at addr ffff8881084e8788 by task vduse_uaf/2987 _raw_spin_lock_irqsave+0x76/0xe0 eventfd_signal_mask+0x69/0x120 vduse_dev_ioctl+0x337/0x1a60 <- vduse_vq_signal_irqfd(), inlined __x64_sys_ioctl+0x120/0x170 <- VDUSE_VQ_INJECT_IRQ Allocated by task 2986: do_eventfd+0x50/0x200 __x64_sys_eventfd2+0x2e/0x40
kmalloc-64, freed 64-byte region [ffff8881084e8780, ffff8881084e87c0)
One thread loops VHOST_SET_VRING_CALL on /dev/vhost-vdpa-N with a fresh eventfd and then unbinds it, while another loops VDUSE_VQ_INJECT_IRQ on /dev/vduse/<name>. This reproduces in 5 out of 5 ten-second runs on v7.1.6 and 3 out of 3 on v7.2-rc6. With the patch there are no reports in 3 out of 3 runs on either, while the same workload still gets ~30000 interrupts per run delivered into live eventfds, so the path is still being exercised.
Tell the parent to drop the callback before vhost_vring_ioctl() can free the eventfd, mirroring what is already done for the bypass producer, and restore it if the ioctl fails -- on failure the swap never happened, the old context is still installed, and leaving the parent without a callback would silently drop that vq's interrupts.
Clearing the callback only stops a parent from starting to use the context; a handler that already loaded it can still be running. For parents with a real interrupt, wait for it with synchronize_irq() on the vq's irq. VDUSE does not implement get_vq_irq, so that case stays covered by the teardown above.
Message-ID: <[email protected]>
--- drivers/vhost/vdpa.c | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-)
drivers/vhost/vdpa.c +34 -1
@@ -767,13 +767,46 @@ static long vhost_vdpa_vring_ioctl(struct vhost_vdpa *v, unsigned int cmd,if (ops->get_status (vdpa) &VIRTIO_CONFIG_S_DRIVER_OK )vhost_vdpa_unsetup_vq_irq (v, idx); +/* +* The parent caches call_ctx.ctx in cb.trigger without +* holding a reference, so it has to stop using it +* before vhost_vring_ioctl() drops the last one. +*/ + cb.callback =NULL ; + cb.private =NULL ; + cb.trigger =NULL ; + ops->set_vq_cb (vdpa, idx, &cb); + +/* +* A parent interrupt handler that loaded the callback +* before that store can still be running, so wait for +* it to finish with the context too. +*/ +if (ops->get_vq_irq) { +int irq = ops->get_vq_irq (vdpa, idx); + +if (irq >=0 ) +synchronize_irq (irq); + } }break ; } r =vhost_vring_ioctl (&v->vdev, cmd, argp); -if (r) +if (r) { +/* +* A failure here means the swap never happened and the old +* context is still installed, so give the parent back the +* callback that was torn down above. +*/ +if (cmd ==VHOST_SET_VRING_CALL && vq->call_ctx.ctx) { + cb.callback = vhost_vdpa_virtqueue_cb; + cb.private = vq; + cb.trigger = vq->call_ctx.ctx; + ops->set_vq_cb (vdpa, idx, &cb); + }return r; + }switch (cmd) {case VHOST_SET_VRING_ADDR :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 162/1005 virtio-blk: clamp max_segments to virtqueue ring size
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sergii Ushakov <[email protected]>
[ Upstream commit 434d2bc41bd0c0ac576d4d259bd9f2ab49071174 ]
In virtblk_add_req(), each request consumes 2 extra descriptors (out_hdr and in_hdr) in addition to the data scatter-gather segments.
When a hypervisor (e.g. QNX Hypervisor) advertises VIRTIO_BLK_F_SEG_MAX with seg_max = 1024 alongside a 1024-entry split ring (vring.num = 1024) and VIRTIO_RING_F_INDIRECT_DESC disabled, lim->max_segments is set to 1024. When the block layer submits requests with 1023 or 1024 data segments, total_sg reaches 1025 or 1026. This exceeds vring.num (1024), causing virtqueue_add_split() to return -ENOSPC and permanently wedge the blk-mq queue.
Furthermore, the Virtio specification (2.7.5.3.1) requires that a descriptor chain never exceed the Queue Size, and virtqueue_add_split() falls back to direct descriptors if indirect table allocation fails.
Fix this by:
1. Rejecting queues with ring_size < 3 at probe, or ring_size < (queue_max_segments + 2) during resume/reset recovery in init_vq().
2. Unconditionally clamping sg_elems to (ring_size - 2) across all virtqueues in virtblk_read_limits().
Message-ID: <[email protected]>
--- drivers/block/virtio_blk.c | 44 +++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-)
drivers/block/virtio_blk.c +43 -1
@@ -1022,6 +1022,30 @@ static int init_vq(struct virtio_blk *vblk) goto out;for (i =0 ; i < num_vqs; i++) { +unsigned int ring_size =virtqueue_get_vring_size (vqs[i]); +/* +* Each request consumes 2 extra descriptors (out_hdr and +* in_hdr) in addition to the data segments. +* +* At initial probe (!vblk->disk), each virtqueue must fit at +* least 1 data segment + 2 header descriptors (3). +* On resume/recovery (vblk->disk), each virtqueue must fit the +* existing queue_max_segments() + 2 header descriptors. +*/ +unsigned int min_ring_size =3 ; + +if (vblk->disk) + min_ring_size =queue_max_segments (vblk->disk->queue) +2 ; + +if (ring_size < min_ring_size) { +dev_err (&vdev->dev, +"virtqueue %u ring size %u is smaller than minimum %u\n" , + i, ring_size, min_ring_size); + vdev->config->del_vqs (vdev); + err = -EINVAL ; + goto out; + } +spin_lock_init (&vblk->vqs[i].lock); vblk->vqs[i].vq = vqs[i]; }
@@ -1254,7 +1278,7 @@ static int virtblk_read_limits(struct virtio_blk *vblk,u16 min_io_size;u8 physical_block_exp, alignment_offset;size_t max_dma_size; -int err; +int err, i;/* We need to know how many segments before we allocate. */ err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
@@ -1268,6 +1292,23 @@ static int virtblk_read_limits(struct virtio_blk *vblk,/* Prevent integer overflows and honor max vq size */ sg_elems =min_t (u32, sg_elems,VIRTIO_BLK_MAX_SG_ELEMS -2 ); +/* +* virtblk_add_req() uses separate outgoing and incoming header +* descriptors (out_hdr and in_hdr), consuming 2 extra descriptors +* per request in addition to the data segments. +* +* Per virtio specification (2.7.5.3.1), a driver MUST NOT create a +* descriptor chain longer than the Queue Size of the device. +* +* Clamp max_segments to (ring_size - 2) across all virtqueues so +* that a request never exceeds the ring size of any queue. +*/ +for (i =0 ; i < vblk->num_vqs; i++) { +u32 ring_size =virtqueue_get_vring_size (vblk->vqs[i].vq); + + sg_elems =min_t (u32, sg_elems, ring_size -2 ); + } +/* We can handle whatever the host told us to handle. */ lim->max_segments = sg_elems;
@@ -1467,6 +1508,7 @@ static int virtblk_probe(struct virtio_device *vdev)mutex_init (&vblk->vdev_mutex); vblk->vdev = vdev; + vblk->disk =NULL ;INIT_WORK (&vblk->config_work, virtblk_config_changed_work);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 163/1005 vduse: avoid infinite loop when no affinity CPU is online
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jia Jia <[email protected]>
[ Upstream commit cf0a5805d43236e308f14188f9737ddcf83fb53a ]
If all CPUs in vq->irq_affinity are offline, cpumask_next() walks to the end of the mask, and the loop then resets the cursor to IRQ_UNBOUND and restarts the scan. When VDUSE_VQ_INJECT_IRQ is issued, the intersection of vq->irq_affinity and cpu_online_mask is empty, so the caller busy-loops in kernel context on its current CPU (e.g. CPU2).
Replace the while loop in vduse_vq_update_effective_cpu() with cpumask_next_and_wrap() to find the intersection of vq->irq_affinity and cpu_online_mask in a single wrapped scan. If the intersection is empty, set curr_cpu to IRQ_UNBOUND and let the existing unbound workqueue handle injection, avoiding repeated rescans when all CPUs in the affinity are offline. Use cpus_read_lock()/cpus_read_unlock() to keep the selected CPU online.
Message-ID: <[email protected]>
--- drivers/vdpa/vdpa_user/vduse_dev.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-)
drivers/vdpa/vdpa_user/vduse_dev.c +7 -8
@@ -15,6 +15,7 @@#include <linux/module.h> #include <linux/cdev.h> #include <linux/device.h> +#include <linux/cpu.h> #include <linux/eventfd.h> #include <linux/slab.h> #include <linux/wait.h>
@@ -1430,14 +1431,10 @@ static void vduse_vq_update_effective_cpu(struct vduse_virtqueue *vq) {int curr_cpu = vq->irq_effective_cpu; -while (true) { - curr_cpu =cpumask_next (curr_cpu, &vq->irq_affinity); -if (cpu_online (curr_cpu)) -break ; - -if (curr_cpu >= nr_cpu_ids) - curr_cpu =IRQ_UNBOUND ; - } + curr_cpu =cpumask_next_and_wrap (curr_cpu, &vq->irq_affinity, + cpu_online_mask); +if (curr_cpu >= nr_cpu_ids) + curr_cpu =IRQ_UNBOUND ; vq->irq_effective_cpu = curr_cpu; }
@@ -1672,10 +1669,12 @@ static long vduse_dev_ioctl(struct file *file, unsigned int cmd, ret =0 ; index =array_index_nospec (index, dev->vq_num);if (!vduse_vq_signal_irqfd (dev->vqs[index])) { +cpus_read_lock ();vduse_vq_update_effective_cpu (dev->vqs[index]); ret =vduse_dev_queue_irq_work (dev, &dev->vqs[index]->inject, dev->vqs[index]->irq_effective_cpu); +cpus_read_unlock (); }break ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 164/1005 virtio_blk: Reset device on probe error paths after DRIVER_OK
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuho Choi <[email protected]>
[ Upstream commit f4f6e9a9cb349003d333f0776de94f12ac95b8d2 ]
virtblk_probe() marks the device ready before revalidating zones and adding the disk, and either of those can fail. The out_cleanup_disk path they take goes on to delete the virtqueues, but nothing tells the device to stop first, so it is still live when the rings are freed.
Reset the device at out_cleanup_disk, which is only reachable after virtio_device_ready(). virtblk_remove() and virtblk_freeze_priv() both reset before deleting the virtqueues for the same reason.
Message-ID: <[email protected]>
--- drivers/block/virtio_blk.c | 1 + 1 file changed, 1 insertion(+)
drivers/block/virtio_blk.c +1 -0
@@ -1590,6 +1590,7 @@ static int virtblk_probe(struct virtio_device *vdev)return 0 ; out_cleanup_disk: +virtio_reset_device (vdev);put_disk (vblk->disk); out_free_tags:blk_mq_free_tag_set (&vblk->tag_set);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 165/1005 regulator: qcom_spmi: dont take a sleeping lock in the SAW IPI
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dmitry Baryshkov <[email protected]>
[ Upstream commit 053c50a7052549aab0d310ad505947db3e211592 ]
The SAW voltage change runs on CPU 0 from an IPI, but it reaches the SAW registers through the syscon regmap, which is protected by a spinlock_t. That is a sleeping lock on PREEMPT_RT, and lockdep complains as soon as VDD_APCC actually changes voltage:
BUG: Invalid wait context ... regmap_lock_spinlock+0x18/0x30 regmap_read+0x3c/0x78 spmi_saw_set_vdd+0x50/0x1ac __flush_smp_call_function_queue+0x1ac/0x334
Map the SAW with a regmap of our own that uses a raw spinlock, and fail the probe when that cannot be done instead of carrying an error pointer around as the SAW regmap.
--- drivers/regulator/Kconfig | 1 + drivers/regulator/qcom_spmi-regulator.c | 35 +++++++++++++++++++------ 2 files changed, 28 insertions(+), 8 deletions(-)
drivers/regulator/Kconfig +1 -0
@@ -1191,6 +1191,7 @@ config REGULATOR_QCOM_SMD_RPM config REGULATOR_QCOM_SPMI tristate "Qualcomm SPMI regulator driver" depends on SPMI || COMPILE_TEST + select REGMAP_MMIO help If you say yes to this option, support will be included for the regulators found in Qualcomm SPMI PMICs.
drivers/regulator/qcom_spmi-regulator.c +27 -8
@@ -12,13 +12,13 @@#include <linux/bitops.h> #include <linux/slab.h> #include <linux/of.h> +#include <linux/of_address.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/ktime.h> #include <linux/regulator/driver.h> #include <linux/regmap.h> #include <linux/list.h> -#include <linux/mfd/syscon.h> #include <linux/io.h> /* Pin control enable input pins. */
@@ -1335,6 +1335,14 @@ static irqreturn_t spmi_regulator_vs_ocp_isr(int irq, void *data)static struct regmap *saw_regmap; +static const struct regmap_config saw_regmap_config = { + .name ="saw" , + .reg_bits =32 , + .val_bits =32 , + .reg_stride =4 , + .use_raw_spinlock = true, +}; +static void spmi_saw_set_vdd (void *data) {u32 vctl, data3, avs_ctl, pmic_sts;
@@ -2504,7 +2512,8 @@ static int qcom_spmi_regulator_probe(struct platform_device *pdev)const char *name;struct device *dev = &pdev->dev;struct device_node *node = pdev->dev.of_node; -struct device_node *syscon, *reg_node; +struct device_node *saw, *reg_node; +void __iomem *saw_base;struct property *reg_prop;int ret, lenp;struct list_head *vreg_list;
@@ -2523,12 +2532,22 @@ static int qcom_spmi_regulator_probe(struct platform_device *pdev)if (!reg)return -ENODEV ; - syscon =of_parse_phandle (node,"qcom,saw-reg" ,0 ); -if (syscon) { - saw_regmap =syscon_node_to_regmap (syscon); -of_node_put (syscon); -if (IS_ERR (saw_regmap)) -dev_err (dev,"ERROR reading SAW regmap\n" ); + saw =of_parse_phandle (node,"qcom,saw-reg" ,0 ); +if (saw) { + saw_base =devm_of_iomap (dev, saw,0 ,NULL ); +of_node_put (saw); +if (IS_ERR (saw_base)) +return dev_err_probe (dev,PTR_ERR (saw_base), +"failed to map the SAW\n" ); + + saw_regmap =devm_regmap_init_mmio (dev, saw_base, + &saw_regmap_config); +if (IS_ERR (saw_regmap)) { + ret =PTR_ERR (saw_regmap); + saw_regmap =NULL ; +return dev_err_probe (dev, ret, +"failed to set the SAW regmap up\n" ); + } }for (; reg->name; reg++) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 166/1005 net: sparx5/lan969x: release the in-flight slot of a stale TX skb
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daniel Machon <[email protected]>
[ Upstream commit 873363ac591a1774aa3ced84f7ea3d93a3eb9b07 ]
sparx5_ptp_txtstamp_request() counts every two step TX skb waiting for its timestamp in sparx5->ptp_skbs, and refuses new ones once SPARX5_MAX_PTP_ID are in flight. sparx5_ptp_txtstamp_old_release() frees the skbs that have waited longer than SPARX5_PTP_TIMEOUT.
Before this patch, old_release() does not decrement ptp_skbs, so every skb whose timestamp never arrives, for example because the switch discarded the frame, keeps its slot forever. Once SPARX5_MAX_PTP_ID slots are lost, two step frames fail to transmit on every port of the switch.
Return the number of released skbs from old_release() and subtract it from ptp_skbs in txtstamp_request(), under the ptp_ts_id_lock it already takes.
This fixes the accounting only. A port's stale skbs are still aged out only when that port sends a two step frame, so a port that stops sending them keeps its stale skbs, and their slots, until it sends one again. That behaviour is unchanged by this patch.
Found by an AI code review agent. Reproduced on a lan9696 board with a modified kernel that drops the TX timestamps of two step frames, after which two step timestamping stopped working on the port. With the fix, timestamping keeps working on that board and on a sparx5 PCB135 board.
--- drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c +8 -2
@@ -204,9 +204,10 @@ static void sparx5_ptp_classify(struct sparx5_port *port, struct sk_buff *skb, *rew_op =IFH_REW_OP_TWO_STEP_PTP ; } -static void sparx5_ptp_txtstamp_old_release (struct sparx5_port *port) +static unsigned int sparx5_ptp_txtstamp_old_release (struct sparx5_port *port) {struct sk_buff *skb, *skb_tmp; +unsigned int purged =0 ;unsigned long flags;spin_lock_irqsave (&port->tx_skbs.lock, flags);
@@ -217,8 +218,11 @@ static void sparx5_ptp_txtstamp_old_release(struct sparx5_port *port)__skb_unlink (skb, &port->tx_skbs);dev_kfree_skb_any (skb); + purged++; }spin_unlock_irqrestore (&port->tx_skbs.lock, flags); + +return purged; } int sparx5_ptp_txtstamp_request(struct sparx5_port *port,
@@ -226,6 +230,7 @@ int sparx5_ptp_txtstamp_request(struct sparx5_port *port, {struct sparx5 *sparx5 = port->sparx5;u8 rew_op, pdu_type, pdu_w16_offset; +unsigned int purged;unsigned long flags;sparx5_ptp_classify (port, skb, &rew_op, &pdu_type, &pdu_w16_offset);
@@ -236,9 +241,10 @@ int sparx5_ptp_txtstamp_request(struct sparx5_port *port,if (rew_op !=IFH_REW_OP_TWO_STEP_PTP )return 0 ; -sparx5_ptp_txtstamp_old_release (port); + purged =sparx5_ptp_txtstamp_old_release (port);spin_lock_irqsave (&sparx5->ptp_ts_id_lock, flags); + sparx5->ptp_skbs -= purged;if (sparx5->ptp_skbs ==SPARX5_MAX_PTP_ID ) {spin_unlock_irqrestore (&sparx5->ptp_ts_id_lock, flags);return -EBUSY ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 167/1005 gpio: mpc8xxx: Fix potential use-after-free of IRQ domain
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guangshuo Li <[email protected]>
[ Upstream commit 9e4b35c95fede87bad36f68b7ff1eae94ea6b910 ]
GPIO chip cleanup can call the to_irq callback while releasing requested GPIOs. Removing the IRQ domain first leaves that callback using a freed domain, both on removal and after an IRQ request failure.
Register domain cleanup before GPIO chip registration so devres removes the chip before freeing the domain.
This issue was found by our static analysis tool under development.
--- drivers/gpio/gpio-mpc8xxx.c | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-)
drivers/gpio/gpio-mpc8xxx.c +15 -7
@@ -319,6 +319,14 @@ static const struct of_device_id mpc8xxx_gpio_ids[] = { {} }; +static void mpc8xxx_irq_domain_remove (void *data) +{ +struct mpc8xxx_gpio_chip *mpc8xxx_gc = data; + +if (mpc8xxx_gc->irq) +irq_domain_remove (mpc8xxx_gc->irq); +} +static int mpc8xxx_probe (struct platform_device *pdev) {const struct mpc8xxx_gpio_devtype *devtype =NULL ;
@@ -405,6 +413,11 @@ static int mpc8xxx_probe(struct platform_device *pdev) mpc8xxx_gc->regs + GPIO_DIR); } +/* GPIO chip cleanup still needs the IRQ domain. */ + ret =devm_add_action_or_reset (dev, mpc8xxx_irq_domain_remove, mpc8xxx_gc); +if (ret) +return ret; + ret =devm_gpiochip_add_data (dev, gc, mpc8xxx_gc);if (ret) { dev_err(dev,
@@ -437,7 +450,7 @@ static int mpc8xxx_probe(struct platform_device *pdev)if (ret) {dev_err (dev,"failed to devm_request_irq(%d), ret = %d\n" , mpc8xxx_gc->irqn, ret); - goto err; +return ret; } ret =devm_device_init_wakeup (dev);
@@ -445,19 +458,14 @@ static int mpc8xxx_probe(struct platform_device *pdev)return dev_err_probe (dev, ret,"Failed to init wakeup\n" );return 0 ; -err: -irq_domain_remove (mpc8xxx_gc->irq); -return ret; }static void mpc8xxx_remove (struct platform_device *pdev) {struct mpc8xxx_gpio_chip *mpc8xxx_gc =platform_get_drvdata (pdev); -if (mpc8xxx_gc->irq) { +if (mpc8xxx_gc->irq)irq_set_chained_handler_and_data (mpc8xxx_gc->irqn,NULL ,NULL ); -irq_domain_remove (mpc8xxx_gc->irq); - } }static int mpc8xxx_suspend (struct device *dev)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 168/1005 net/iucv: take a private, writable frame before rewriting it in place
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bryam Vargas <[email protected]>
[ Upstream commit f38bce9af9e2a3cced7d303a1476f21c1f42bcb7 ]
afiucv_hs_rcv() rewrites the frame in place -- EBCASC() on four name fields, then afiucv_swap_src_dest() swaps them and pushes an Ethernet header -- and can hand the same skb to dev_queue_xmit(), without making it private first, so a packet socket that also gets the frame reads the rewritten names. An ETH_P_ALL tap runs first and leaves af_iucv a cloned skb; a socket opened for ETH_P_AF_IUCV sits on a ptype_specific list, walked after ptype_base[], so deliver_skb() takes a reference and af_iucv runs on an skb that is shared but not cloned.
Unshare, then cow, in that order: skb_cow() can reach pskb_expand_head(), which has BUG_ON(skb_shared()). skb_cow() tests skb_cloned(), which is what a rewrite of the data needs; skb_cow_head() tests only the header. Asking for ETH_HLEN also covers the unchecked push in afiucv_swap_src_dest(); on the ordinary path eth_type_trans() has already pulled that much, so it only compares.
--- net/iucv/af_iucv.c | 9 +++++++++ 1 file changed, 9 insertions(+)
net/iucv/af_iucv.c +9 -0
@@ -2072,11 +2072,20 @@ static int afiucv_hs_rcv(struct sk_buff *skb, struct net_device *dev,int err =NET_RX_SUCCESS ;char nullstring[8 ]; + skb =skb_share_check (skb,GFP_ATOMIC ); +if (!skb) +return NET_RX_SUCCESS ; +if (!pskb_may_pull (skb,sizeof (*trans_hdr))) {kfree_skb (skb);return NET_RX_SUCCESS ; } +if (skb_cow (skb,ETH_HLEN )) { +kfree_skb (skb); +return NET_RX_SUCCESS ; + } + trans_hdr =iucv_trans_hdr (skb);EBCASC (trans_hdr->destAppName,sizeof (trans_hdr->destAppName));EBCASC (trans_hdr->destUserID,sizeof (trans_hdr->destUserID));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 169/1005 net: phy: add phy_detach_internal() helper
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Markus Stockhausen <[email protected]>
[ Upstream commit 2df76677c1c08f622cc577a49f0645a5976d7c91 ]
For the upcoming MDIO bus notification enhancements the PHY detach path needs to inform the bus about these actions. Until now phy_detach() is used for the regular detach path as well as from the phy_attach_direct() error paths So in the future there must be a clear indication if a notification is needed (normal path) or not (cleanup path).
Carve out the phy_detach() code into a new helper phy_detach_internal() and make phy_detach() a short stub that calls the new helper.
Stable-dep-of: d1cf56164dc2 ("net: phy: don't require RTNL to detach a PHY from an unregistered netdev")
--- drivers/net/phy/phy_device.c | 172 +++++++++++++++++++---------------- 1 file changed, 92 insertions(+), 80 deletions(-)
drivers/net/phy/phy_device.c +92 -80
@@ -1734,6 +1734,98 @@ static bool phy_drv_supports_irq(const struct phy_driver *phydrv)return phydrv->config_intr && phydrv->handle_interrupt; } +/** +* phy_detach_internal - detach a PHY device from its network device +* @phydev: target phy_device struct +* +* This detaches the phy device from its network device and the phy +* driver, and drops the reference count taken in phy_attach_direct(). +*/ +static void phy_detach_internal (struct phy_device *phydev) +{ +struct net_device *dev = phydev->attached_dev; +struct module *ndev_owner =NULL ; +struct mii_bus *bus; + +if (phydev->devlink) { +device_link_del (phydev->devlink); + phydev->devlink =NULL ; + } + +if (phydev->sysfs_links) { +if (dev) +sysfs_remove_link (&dev->dev.kobj,"phydev" ); +sysfs_remove_link (&phydev->mdio.dev.kobj,"attached_dev" ); + } + +if (!phydev->attached_dev) +sysfs_remove_file (&phydev->mdio.dev.kobj, + &dev_attr_phy_standalone.attr); + +phy_suspend (phydev); +if (dev) { +struct hwtstamp_provider *hwprov; + +/* hwprov may technically be protected by ops lock but +* not for devices with a phydev, see phy_link_topo_add_phy() +*/ + hwprov =rtnl_dereference (dev->hwprov); +/* Disable timestamp if it is the one selected */ +if (hwprov && hwprov->phydev == phydev) { +rcu_assign_pointer (dev->hwprov,NULL ); +kfree_rcu (hwprov, rcu_head); + } + + phydev->attached_dev->phydev =NULL ; + phydev->attached_dev =NULL ; +phy_link_topo_del_phy (dev, phydev); + } + + phydev->phy_link_change =NULL ; + phydev->phylink =NULL ; + +if (phydev->mdio.dev.driver) +module_put (phydev->mdio.dev.driver->owner); + +/* If the device had no specific driver before (i.e. - it +* was using the generic driver), we unbind the device +* from the generic driver so that there's a chance a +* real driver could be loaded +*/ +if (phydev->is_genphy_driven) { +device_release_driver (&phydev->mdio.dev); + phydev->is_genphy_driven =0 ; + } + +/* Assert the reset signal */ +phy_device_reset (phydev,1 ); + +/* +* The phydev might go away on the put_device() below, so avoid +* a use-after-free bug by reading the underlying bus first. +*/ + bus = phydev->mdio.bus; + +put_device (&phydev->mdio.dev); +if (dev) + ndev_owner = dev->dev.parent->driver->owner; +if (ndev_owner != bus->owner) +module_put (bus->owner); +} + +/** +* phy_detach - detach a PHY device from its network device +* @phydev: target phy_device struct +* +* This detaches the phy device from its network device and the phy +* driver, and drops the reference count taken in phy_attach_direct(). +*/ +void phy_detach (struct phy_device *phydev) +{ +phy_detach_internal (phydev); +} +EXPORT_SYMBOL (phy_detach); +/** * phy_attach_direct - attach a network device to a given PHY device pointer * @dev: network device to attach
@@ -1906,86 +1998,6 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev, }EXPORT_SYMBOL (phy_attach_direct); -/** -* phy_detach - detach a PHY device from its network device -* @phydev: target phy_device struct -* -* This detaches the phy device from its network device and the phy -* driver, and drops the reference count taken in phy_attach_direct(). -*/ -void phy_detach (struct phy_device *phydev) -{ -struct net_device *dev = phydev->attached_dev; -struct module *ndev_owner =NULL ; -struct mii_bus *bus; - -if (phydev->devlink) { -device_link_del (phydev->devlink); - phydev->devlink =NULL ; - } - -if (phydev->sysfs_links) { -if (dev) -sysfs_remove_link (&dev->dev.kobj,"phydev" ); -sysfs_remove_link (&phydev->mdio.dev.kobj,"attached_dev" ); - } - -if (!phydev->attached_dev) -sysfs_remove_file (&phydev->mdio.dev.kobj, - &dev_attr_phy_standalone.attr); - -phy_suspend (phydev); -if (dev) { -struct hwtstamp_provider *hwprov; - -/* hwprov may technically be protected by ops lock but -* not for devices with a phydev, see phy_link_topo_add_phy() -*/ - hwprov =rtnl_dereference (dev->hwprov); -/* Disable timestamp if it is the one selected */ -if (hwprov && hwprov->phydev == phydev) { -rcu_assign_pointer (dev->hwprov,NULL ); -kfree_rcu (hwprov, rcu_head); - } - - phydev->attached_dev->phydev =NULL ; - phydev->attached_dev =NULL ; -phy_link_topo_del_phy (dev, phydev); - } - - phydev->phy_link_change =NULL ; - phydev->phylink =NULL ; - -if (phydev->mdio.dev.driver) -module_put (phydev->mdio.dev.driver->owner); - -/* If the device had no specific driver before (i.e. - it -* was using the generic driver), we unbind the device -* from the generic driver so that there's a chance a -* real driver could be loaded -*/ -if (phydev->is_genphy_driven) { -device_release_driver (&phydev->mdio.dev); - phydev->is_genphy_driven =0 ; - } - -/* Assert the reset signal */ -phy_device_reset (phydev,1 ); - -/* -* The phydev might go away on the put_device() below, so avoid -* a use-after-free bug by reading the underlying bus first. -*/ - bus = phydev->mdio.bus; - -put_device (&phydev->mdio.dev); -if (dev) - ndev_owner = dev->dev.parent->driver->owner; -if (ndev_owner != bus->owner) -module_put (bus->owner); -} -EXPORT_SYMBOL (phy_detach); -int phy_suspend (struct phy_device *phydev) {struct net_device *netdev = phydev->attached_dev;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 170/1005 net: phy: dont require RTNL to detach a PHY from an unregistered netdev
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nguyen Ngoc Thang <[email protected]>
[ Upstream commit d1cf56164dc25c2c54853b23eab42369f53c8329 ]
phy_detach_internal() reads dev->hwprov with rtnl_dereference(), but MAC drivers commonly attach and detach PHYs while their net_device is not registered, without holding RTNL. Before register_netdev(), a failed phylink_connect_phy() or phy_attach_direct() unwinds through phy_detach_internal(). After unregister_netdev(), a driver's remove path may call phy_disconnect(). Both trip lockdep:
WARNING: suspicious RCU usage
drivers/net/phy/phy_device.c:1831 suspicious rcu_dereference_protected() usage!
phy_detach_internal+0x6a5/0x830 drivers/net/phy/phy_device.c:1831 phylink_connect_phy+0x22e/0x2b0 drivers/net/phy/phylink.c:2452 ax88772_bind+0xbb1/0x1520 drivers/net/usb/asix_devices.c:925 usbnet_probe+0xbb3/0x27e0 drivers/net/usb/usbnet.c:1812
syzbot hits this with an emulated asix device. phy_eee_rx_clock_stop() fails on a USB MDIO error, so phylink_bringup_phy() fails and the PHY is detached from inside usbnet_probe(), before the netdev is registered.
hwprov is only set through ethtool, under RTNL, on a registered device. reg_state also changes only under RTNL. So if the device is not registered, no one else can reach hwprov, and RTNL is not needed. Tell lockdep that. A detach from a registered device without RTNL still warns.
--- drivers/net/phy/phy_device.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/net/phy/phy_device.c +6 -2
@@ -1767,9 +1767,13 @@ static void phy_detach_internal(struct phy_device *phydev)struct hwtstamp_provider *hwprov;/* hwprov may technically be protected by ops lock but -* not for devices with a phydev, see phy_link_topo_add_phy() +* not for devices with a phydev, see phy_link_topo_add_phy(). +* Drivers may detach without RTNL while dev is unregistered, +* but then nothing else can reach hwprov. */ - hwprov =rtnl_dereference (dev->hwprov); + hwprov =rcu_dereference_protected (dev->hwprov, +lockdep_rtnl_is_held () || + dev->reg_state !=NETREG_REGISTERED );/* Disable timestamp if it is the one selected */ if (hwprov && hwprov->phydev == phydev) {rcu_assign_pointer (dev->hwprov,NULL );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 171/1005 wifi: ath12k: dont advertise EHT-MCS15 to firmware unless we support it
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baochen Qiang <[email protected]>
[ Upstream commit 83d689bbe8f90ce39961bcc3a64f2ca2ec184019 ]
ath12k_peer_assoc_h_eht() copies the peer's EHT PHY capabilities into the WMI peer assoc command as is, including the EHT-MCS15 support bits. Firmware rate control enables EHT-MCS15 for TX whenever those bits are set, without checking whether the local PHY supports MCS15.
Currently WCN7850 firmware does not support EHT-MCS15 for TX and does not advertise it in its own EHT PHY capabilities. When connected to an AP that advertises MCS15 support, rate control may still select EHT-MCS15, and every PPDU at that rate is aborted by the PHY before it goes on the air. TX then stops for minutes while the association stays up, and frames sit in the queue until the firmware releases them as aged.
Keep only the peer's MCS15 support bits that we also support ourselves to fix it. Chips that support MCS15 are not affected.
Tested-on: WCN7850 hw2.0 PCI WLAN.HMT.1.1.c7-00108-QCAHMTSWPL_V1.0_V2.0_SILICONZ_UPSTREAM-3
--- drivers/net/wireless/ath/ath12k/mac.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
drivers/net/wireless/ath/ath12k/mac.c +11 -0
@@ -3366,6 +3366,7 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,u32 *rx_mcs, *tx_mcs;u16 *eht_mcs_mask;u8 max_nss =0 ; +u8 mcs15;lockdep_assert_wiphy (ath12k_ar_to_hw (ar)->wiphy);
@@ -3416,6 +3417,16 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,memcpy (arg->peer_eht_cap_phy, eht_cap->eht_cap_elem.phy_cap_info,sizeof (eht_cap->eht_cap_elem.phy_cap_info)); +/* +* Firmware rate control enables EHT-MCS15 based only on the peer's +* MCS15 support bits, so keep only the ones we support ourselves. +*/ + mcs15 =u8_get_bits (eht_cap->eht_cap_elem.phy_cap_info[6 ] & + own_eht_cap->eht_cap_elem.phy_cap_info[6 ], +IEEE80211_EHT_PHY_CAP6_MCS15_SUPP_MASK ); +u8p_replace_bits (&((u8 *)arg->peer_eht_cap_phy)[6 ], mcs15, +IEEE80211_EHT_PHY_CAP6_MCS15_SUPP_MASK ); + rx_mcs = arg->peer_eht_rx_mcs_set; tx_mcs = arg->peer_eht_tx_mcs_set;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 172/1005 net: stmmac: propagate PTP init failures in __stmmac_open() and stmmac_resume()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Bianconi <[email protected]>
[ Upstream commit 8181678a92f0143ad3dafcc2e811afa44ecb4fd6 ]
stmmac_setup_ptp() returns void and swallows both PTP setup errors:
the PTP reference clock enable and stmmac_init_timestamping() failures are logged but never propagated. When they fail, the MAC system time counter is left in its post-reset, non-running state, while the driver keeps operating as if timestamping were up. This matters for TAPRIO/EST qdisc offloading, which derives the EST base time from the hardware timestamp counter: arming the gate list against a non-advancing time base would leave the schedule permanently stuck.
Make stmmac_setup_ptp() return an error code and propagate the failure in __stmmac_open(), stopping the DMA engines when PTP setup fails. In stmmac_resume(), re-initialise timestamping only when the PTP clock was registered before suspend, re-apply the platform clock rate configuration, and stop the DMA engines if re-initialisation fails.
While at it, factor the hardware timestamping capability check into a stmmac_check_timestamp_cap() helper and apply it to the hwtstamp get path and the ethtool ts_info path. stmmac_setup_ptp() now enables the PTP reference clock and runs the platform ptp_clk_freq_config() callback before validating the resulting clock rate; if no valid rate is available, it disables the clock and returns success without registering the PTP clock. This keeps the interface operational on platforms with PTP-capable silicon but an unconfigured PTP clock, where timestamping cannot be enabled: instead of failing, the driver proceeds without setting up timestamping. Extend the timestamping gate on the set path (which keeps testing the core's basic/advanced timestamping capability) and the devlink registration with the PTP reference clock rate requirement.
Gate the PTP reference clock enable/disable in the platform noirq suspend/resume callbacks on priv->ptp_enabled, keeping the clock reference balanced against the new early return in stmmac_release_ptp().
Stable-dep-of: 23d96de472f7 ("net: stmmac: re-apply taprio offload in __stmmac_open() and stmmac_resume()")
--- drivers/net/ethernet/stmicro/stmmac/stmmac.h | 7 ++ .../ethernet/stmicro/stmmac/stmmac_ethtool.c | 3 +- .../net/ethernet/stmicro/stmmac/stmmac_main.c | 114 +++++++++++++----- .../ethernet/stmicro/stmmac/stmmac_platform.c | 6 +- 4 files changed, 95 insertions(+), 35 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac.h +7 -0
@@ -336,6 +336,8 @@ struct stmmac_priv {struct kernel_hwtstamp_config tstamp_config;struct ptp_clock *ptp_clock;struct ptp_clock_info ptp_clock_ops; +bool ptp_enabled; +unsigned int default_addend;u32 sub_second_inc;u32 systime_flags;
@@ -426,6 +428,11 @@ int stmmac_set_clk_tx_rate(void *bsp_priv, struct clk *clk_tx_i,struct plat_stmmacenet_data *stmmac_plat_dat_alloc (struct device *dev); +static inline bool stmmac_check_timestamp_cap (struct stmmac_priv *priv) +{ +return priv->dma_cap.time_stamp || priv->dma_cap.atime_stamp; +} +static inline bool stmmac_xdp_is_enabled (struct stmmac_priv *priv) {return !!priv->xdp_prog;
drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c +1 -2
@@ -1008,8 +1008,7 @@ static int stmmac_get_ts_info(struct net_device *dev, {struct stmmac_priv *priv =netdev_priv (dev); -if ((priv->dma_cap.time_stamp || priv->dma_cap.atime_stamp)) { - +if (stmmac_check_timestamp_cap (priv)) { info->so_timestamping =SOF_TIMESTAMPING_TX_SOFTWARE |SOF_TIMESTAMPING_TX_HARDWARE | SOF_TIMESTAMPING_RX_HARDWARE |
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +82 -32
202 lines not on this page · raw message
drivers/net/ethernet/stmicro/stmmac/stmmac_platform.c +5 -1
@@ -959,7 +959,8 @@ static int __maybe_unused stmmac_pltfr_noirq_suspend(struct device *dev)if (!priv->wolopts) {/* Disable clock in case of PWM is off */ -clk_disable_unprepare (priv->plat->clk_ptp_ref); +if (priv->ptp_enabled) +clk_disable_unprepare (priv->plat->clk_ptp_ref); ret =pm_runtime_force_suspend (dev);if (ret)
@@ -984,6 +985,9 @@ static int __maybe_unused stmmac_pltfr_noirq_resume(struct device *dev)if (ret)return ret; +if (!priv->ptp_enabled) +return 0 ; + ret =clk_prepare_enable (priv->plat->clk_ptp_ref);if (ret <0 ) { netdev_warn(priv->dev,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 173/1005 net: stmmac: ptp: switch to gettimex64() interface
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: James Clark <[email protected]>
[ Upstream commit d7804253678eb18d2be950e0542364b50be096a9 ]
The stmmac PTP support currently implements the gettime64 callback to retrieve the hardware clock time. Update the implementation to provide the gettimex64 callback instead, adding support for the PTP_SYS_OFFSET_EXTENDED ioctl.
The system clock readings are taken around the read of the nanoseconds register in get_systime(), so get_systime() gains a ptp_system_timestamp argument.
Stable-dep-of: 23d96de472f7 ("net: stmmac: re-apply taprio offload in __stmmac_open() and stmmac_resume()")
--- drivers/net/ethernet/stmicro/stmmac/hwif.h | 5 ++++- .../ethernet/stmicro/stmmac/stmmac_hwtstamp.c | 7 +++++-- .../net/ethernet/stmicro/stmmac/stmmac_ptp.c | 21 ++++++++++--------- .../stmicro/stmmac/stmmac_selftests.c | 4 ++-- .../net/ethernet/stmicro/stmmac/stmmac_tc.c | 3 ++- 5 files changed, 24 insertions(+), 16 deletions(-)
drivers/net/ethernet/stmicro/stmmac/hwif.h +4 -1
@@ -496,6 +496,8 @@ struct stmmac_ops { #define stmmac_fpe_map_preemption_class(__priv, __args...) \ stmmac_do_callback(__priv, mac, fpe_map_preemption_class, __args) +struct ptp_system_timestamp ; +/* PTP and HW Timer helpers */ struct stmmac_hwtimestamp {void (*config_hw_tstamping) (void __iomem *ioaddr,u32 data);
@@ -505,7 +507,8 @@ struct stmmac_hwtimestamp {int (*config_addend) (void __iomem *ioaddr,u32 addend);int (*adjust_systime) (void __iomem *ioaddr,u32 sec,u32 nsec,int add_sub,int gmac4); -void (*get_systime) (void __iomem *ioaddr,u64 *systime); +void (*get_systime)(void __iomem *ioaddr,u64 *systime, +struct ptp_system_timestamp *sts);void (*get_ptptime)(void __iomem *ioaddr,u64 *ptp_time);void (*timestamp_interrupt)(struct stmmac_priv *priv);void (*hwtstamp_correct_latency)(struct stmmac_priv *priv);
drivers/net/ethernet/stmicro/stmmac/stmmac_hwtstamp.c +5 -2
@@ -183,7 +183,8 @@ static int adjust_systime(void __iomem *ioaddr, u32 sec, u32 nsec, 10, 100000); } -static void get_systime (void __iomem *ioaddr,u64 *systime) +static void get_systime (void __iomem *ioaddr,u64 *systime, +struct ptp_system_timestamp *sts) {u64 ns, sec0, sec1;
@@ -191,8 +192,10 @@ static void get_systime(void __iomem *ioaddr, u64 *systime) sec1 =readl_relaxed (ioaddr +PTP_STSR );do { sec0 = sec1; +ptp_read_system_prets (sts);/* Get the TSSS value */ - ns =readl_relaxed (ioaddr +PTP_STNSR ); + ns =readl (ioaddr +PTP_STNSR ); +ptp_read_system_postts (sts);/* Get the TSS value */ sec1 =readl_relaxed (ioaddr +PTP_STSR ); }while (sec0 != sec1);
drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +11 -10
@@ -89,7 +89,8 @@ static int stmmac_adjust_time(struct ptp_clock_info *ptp, s64 delta)u64 cycle_time;mutex_lock (&priv->est_lock); - priv->ptp_clock_ops.gettime64 (&priv->ptp_clock_ops, ¤t_time); + priv->ptp_clock_ops.gettimex64 (&priv->ptp_clock_ops, + ¤t_time,NULL ); current_time_ns =timespec64_to_ktime (current_time); time.tv_nsec = priv->est->btr_reserve[0 ]; time.tv_sec = priv->est->btr_reserve[1 ];
@@ -114,15 +115,15 @@ static int stmmac_adjust_time(struct ptp_clock_info *ptp, s64 delta) }/** -* stmmac_get_time -* +* stmmac_get_timex - read the PTP clock, with system timestamps if requested * @ptp: pointer to ptp_clock_info structure * @ts: pointer to hold time/result +* @sts: pointer to hold system timestamps around the read, or NULL * -* Description: this function will read the current time from the -* hardware clock and store it in @ts. +* Return: 0 */ -static int stmmac_get_time (struct ptp_clock_info *ptp,struct timespec64 *ts) +static int stmmac_get_timex (struct ptp_clock_info *ptp,struct timespec64 *ts, +struct ptp_system_timestamp *sts) {struct stmmac_priv *priv = container_of(ptp, struct stmmac_priv, ptp_clock_ops);
@@ -130,7 +131,7 @@ static int stmmac_get_time(struct ptp_clock_info *ptp, struct timespec64 *ts)u64 ns =0 ;read_lock_irqsave (&priv->ptp_lock, flags); -stmmac_get_systime (priv, priv->ptpaddr, &ns); +stmmac_get_systime (priv, priv->ptpaddr, &ns, sts);read_unlock_irqrestore (&priv->ptp_lock, flags); *ts =ns_to_timespec64 (ns);
@@ -200,7 +201,7 @@ static int stmmac_enable(struct ptp_clock_info *ptp, target_ns = cfg->start.tv_nsec + ((u64 )cfg->start.tv_sec *NSEC_PER_SEC ); -stmmac_get_systime (priv, priv->ptpaddr, &ns); +stmmac_get_systime (priv, priv->ptpaddr, &ns,NULL );if (ns >TIME64_MAX -PTP_SAFE_TIME_OFFSET_NS )return -EINVAL ;
@@ -304,7 +305,7 @@ const struct ptp_clock_info stmmac_ptp_clock_ops = { .pps = 0, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, - .gettime64 = stmmac_get_time, + .gettimex64 = stmmac_get_timex, .settime64 = stmmac_set_time, .enable = stmmac_enable, };
@@ -321,7 +322,7 @@ const struct ptp_clock_info dwmac1000_ptp_clock_ops = { .pps = 0, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, - .gettime64 = stmmac_get_time, + .gettimex64 = stmmac_get_timex, .settime64 = stmmac_set_time, .enable = dwmac1000_ptp_enable, };
drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c +2 -2
@@ -1887,7 +1887,7 @@ static int stmmac_test_tbs(struct stmmac_priv *priv)return ret;read_lock_irqsave (&priv->ptp_lock, flags); -stmmac_get_systime (priv, priv->ptpaddr, &curr_time); +stmmac_get_systime (priv, priv->ptpaddr, &curr_time,NULL );read_unlock_irqrestore (&priv->ptp_lock, flags);if (!curr_time) {
@@ -1909,7 +1909,7 @@ static int stmmac_test_tbs(struct stmmac_priv *priv)/* Check if expected time has elapsed */ read_lock_irqsave (&priv->ptp_lock, flags); -stmmac_get_systime (priv, priv->ptpaddr, &curr_time); +stmmac_get_systime (priv, priv->ptpaddr, &curr_time,NULL );read_unlock_irqrestore (&priv->ptp_lock, flags);if ((curr_time - start_time) <STMMAC_TBS_LT_OFFSET )
drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +2 -1
@@ -1070,7 +1070,8 @@ static int tc_taprio_configure(struct stmmac_priv *priv,mutex_lock (&priv->est_lock);/* Adjust for real system time */ - priv->ptp_clock_ops.gettime64 (&priv->ptp_clock_ops, ¤t_time); + priv->ptp_clock_ops.gettimex64 (&priv->ptp_clock_ops, ¤t_time, +NULL ); current_time_ns =timespec64_to_ktime (current_time); time =stmmac_calc_tas_basetime (qopt->base_time, current_time_ns, qopt->cycle_time);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 174/1005 net: stmmac: initialize est_lock at probe time
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Bianconi <[email protected]>
[ Upstream commit 98caed39c1db002b2c34b8040ab765c5fa9c6675 ]
priv->est is allocated with devm_kzalloc() on the first TAPRIO REPLACE and priv->est_lock is initialized in the same place, which ties the validity of the lock to whether TAPRIO has ever been configured. The lock is also never destroyed.
Initialize priv->est_lock in __stmmac_dvr_probe() next to priv->lock and destroy it in stmmac_dvr_remove(). This keeps the lock valid for the entire lifetime of the device, independent of the TAPRIO state, and removes the lazy initialization from the TAPRIO configuration path.
No functional change intended.
Stable-dep-of: 23d96de472f7 ("net: stmmac: re-apply taprio offload in __stmmac_open() and stmmac_resume()")
--- drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 2 ++ drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +2 -0
@@ -8145,6 +8145,7 @@ static int __stmmac_dvr_probe(struct device *device,stmmac_napi_add (ndev);mutex_init (&priv->lock); +mutex_init (&priv->est_lock);rwlock_init (&priv->ptp_lock);stmmac_fpe_init (priv);
@@ -8278,6 +8279,7 @@ void stmmac_dvr_remove(struct device *dev)destroy_workqueue (priv->wq);mutex_destroy (&priv->lock); +mutex_destroy (&priv->est_lock);bitmap_free (priv->af_xdp_zc_qps);pm_runtime_disable (dev);
drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +0 -2
@@ -1028,8 +1028,6 @@ static int tc_taprio_configure(struct stmmac_priv *priv, GFP_KERNEL);if (!priv->est)return -ENOMEM ; - -mutex_init (&priv->est_lock); }else {mutex_lock (&priv->est_lock);memset (priv->est,0 ,sizeof (*priv->est));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 175/1005 net: stmmac: pass the desired EST enable state to est_configure()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Bianconi <[email protected]>
[ Upstream commit e4f5b46dfb8ac27a822fa0b411bd4526abf5ba97 ]
Pass the desired EST enable state explicitly to est_configure() instead of having it derive from cfg->enable. This decouples the hardware programming state from the priv->est->enable flag, which records whether the taprio offload is attached.
No functional change intended: the callers keep toggling priv->est->enable around the EST programming, as before.
Stable-dep-of: 23d96de472f7 ("net: stmmac: re-apply taprio offload in __stmmac_open() and stmmac_resume()")
--- drivers/net/ethernet/stmicro/stmmac/hwif.h | 2 +- drivers/net/ethernet/stmicro/stmmac/stmmac_est.c | 6 +++--- drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c | 4 ++-- drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-)
drivers/net/ethernet/stmicro/stmmac/hwif.h +1 -1
@@ -623,7 +623,7 @@ struct stmmac_mmc_ops {struct stmmac_est_ops {int (*configure)(struct stmmac_priv *priv,struct stmmac_est *cfg, -unsigned int ptp_rate); +unsigned int ptp_rate,bool enable);void (*irq_status)(struct stmmac_priv *priv,struct net_device *dev,struct stmmac_extra_stats *x,u32 txqcnt); };
drivers/net/ethernet/stmicro/stmmac/stmmac_est.c +3 -3
@@ -26,7 +26,7 @@ static int est_write(void __iomem *est_addr, u32 reg, u32 val, bool gcl) }static int est_configure (struct stmmac_priv *priv,struct stmmac_est *cfg, -unsigned int ptp_rate) +unsigned int ptp_rate,bool enable) {void __iomem *est_addr = priv->estaddr;int i, ret =0 ;
@@ -62,7 +62,7 @@ static int est_configure(struct stmmac_priv *priv, struct stmmac_est *cfg, ctrl |= ((NSEC_PER_SEC / ptp_rate) *EST_GMAC5_PTOV_MUL ) <<EST_GMAC5_PTOV_SHIFT ; } -if (cfg->enable) +if (enable) ctrl |=EST_EEST |EST_SSWL |EST_DFBS ;else ctrl &= ~EST_EEST ;
@@ -70,7 +70,7 @@ static int est_configure(struct stmmac_priv *priv, struct stmmac_est *cfg,writel (ctrl, est_addr +EST_CONTROL );/* Configure EST interrupt */ -if (cfg->enable) +if (enable) ctrl =EST_IECGCE |EST_IEHS |EST_IEHF |EST_IEBE |EST_IECC ;else ctrl =0 ;
drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +2 -2
@@ -74,7 +74,7 @@ static int stmmac_adjust_time(struct ptp_clock_info *ptp, s64 delta)mutex_lock (&priv->est_lock); priv->est->enable = false;stmmac_est_configure (priv, priv, priv->est, - priv->plat->clk_ptp_rate); + priv->plat->clk_ptp_rate, false);mutex_unlock (&priv->est_lock); }
@@ -105,7 +105,7 @@ static int stmmac_adjust_time(struct ptp_clock_info *ptp, s64 delta) priv->est->btr[1 ] = (u32 )time.tv_sec; priv->est->enable = true; ret =stmmac_est_configure (priv, priv, priv->est, - priv->plat->clk_ptp_rate); + priv->plat->clk_ptp_rate, true);mutex_unlock (&priv->est_lock);if (ret)netdev_err (priv->dev,"failed to configure EST\n" );
drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +2 -2
@@ -1090,7 +1090,7 @@ static int tc_taprio_configure(struct stmmac_priv *priv,tc_taprio_map_maxsdu_txq (priv, qopt); ret =stmmac_est_configure (priv, priv, priv->est, - priv->plat->clk_ptp_rate); + priv->plat->clk_ptp_rate, true);mutex_unlock (&priv->est_lock);if (ret) {netdev_err (priv->dev,"failed to configure EST\n" );
@@ -1109,7 +1109,7 @@ static int tc_taprio_configure(struct stmmac_priv *priv,mutex_lock (&priv->est_lock); priv->est->enable = false;stmmac_est_configure (priv, priv, priv->est, - priv->plat->clk_ptp_rate); + priv->plat->clk_ptp_rate, false);/* Reset taprio status */ for (i =0 ; i < priv->plat->tx_queues_to_use; i++) { priv->xstats.max_sdu_txq_drop[i] =0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 176/1005 net: stmmac: re-apply taprio offload in __stmmac_open() and stmmac_resume()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Bianconi <[email protected]>
[ Upstream commit 23d96de472f735858a7dd227c77aebff21ea09f5 ]
The core soft reset issued by stmmac_init_dma_engine(), called from stmmac_hw_setup(), clears the MTL_EST registers. Nothing re-applies the taprio offload afterwards, so priv->est->enable stays true while the hardware EST block is left disabled: taprio keeps being reported as offloaded, the TX/XDP paths keep dropping frames larger than priv->est->max_sdu[], and the programmed base time is stale.
Re-apply the offload from __stmmac_open() and stmmac_resume() after PTP has been brought up. The base time is recomputed from the reserved base time and the current PTP time, because the timestamp counter has been re-initialised and the previously programmed base time cannot be reused.
Factor the recompute-and-program sequence into __stmmac_setup_est(), which must be called with est_lock held, and into stmmac_setup_est(), which takes the lock and re-applies the offload only when it is currently enabled and PTP has been brought up. Use the same helper in stmmac_adjust_time() so the PTP adjust path shares the base time computation.
Only tc_taprio_configure() updates priv->est->enable: it is set when a REPLACE succeeds and cleared on DESTROY or a programming failure. The re-apply helpers leave it untouched, so the flag records that an offload is installed rather than the current hardware programming state. __stmmac_setup_est() only reprograms the EST block, and stmmac_setup_est() replays the FPE mapping afterwards. On a failed re-apply the open and resume callers abort, while stmmac_adjust_time() keeps the offload configured.
The same reset also discards the FPE preemption programming, and on XGMAC stmmac_dma_tx_mode() overwrites the queue-to-traffic-class map. Save the preemptible traffic class mask in priv->est->pclass when a REPLACE succeeds and replay the FPE mapping from stmmac_setup_est() as well.
Re-applying the offload is best-effort with respect to PTP:stmmac_setup_est() does nothing when PTP was not enabled (for example when clk_ptp_rate is 0), so a missing PTP reference clock does not by itself fail ndo_open(). If re-applying the EST or FPE programming fails while restoring the interface, the failure is fatal to the caller:__stmmac_open() aborts the open, and stmmac_resume() takes the same error path already used for a failed timestamp counter restore.
Since __stmmac_open() and stmmac_resume() now trust priv->est->enable, also make tc_taprio_configure() consistent: hold est_lock across the whole validate-and-program sequence, build the gate list in a temporary buffer, and only commit it and enable EST after validation and hardware programming succeed. A REPLACE rejected during validation then leaves the currently installed schedule intact in both software and hardware, while a hardware or FPE mapping failure disables EST instead of leaving a stale enable flag behind. Reject cycle times whose seconds field would not fit in priv->est->ctr[1].
--- drivers/net/ethernet/stmicro/stmmac/stmmac.h | 1 + .../net/ethernet/stmicro/stmmac/stmmac_est.c | 55 ++++++++++++ .../net/ethernet/stmicro/stmmac/stmmac_est.h | 8 ++ .../net/ethernet/stmicro/stmmac/stmmac_main.c | 11 ++- .../net/ethernet/stmicro/stmmac/stmmac_ptp.c | 44 ++-------- .../net/ethernet/stmicro/stmmac/stmmac_tc.c | 88 ++++++++++++------- 6 files changed, 139 insertions(+), 68 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac.h +1 -0
@@ -239,6 +239,7 @@ struct stmmac_est {u32 gcl[EST_GCL ];u32 gcl_size;u32 max_sdu[MTL_MAX_TX_QUEUES ]; +u32 pclass; };struct stmmac_msi {
drivers/net/ethernet/stmicro/stmmac/stmmac_est.c +55 -0
61 lines not on this page · raw message
drivers/net/ethernet/stmicro/stmmac/stmmac_est.h +8 -0
@@ -4,6 +4,9 @@* stmmac EST(802.3 Qbv) handling */ +#ifndef __STMMAC_EST_H__ +#define __STMMAC_EST_H__ +#define EST_GMAC4_OFFSET 0x00000c50#define EST_XGMAC_OFFSET 0x00001050
@@ -65,3 +68,8 @@#define EST_GCL_DATA 0x00000034extern const struct stmmac_est_ops dwmac510_est_ops; + +int __stmmac_setup_est (struct stmmac_priv *priv); +int stmmac_setup_est (struct stmmac_priv *priv); + +#endif /* __STMMAC_EST_H__ */
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +10 -1
@@ -48,6 +48,7 @@#include "stmmac_ptp.h" #include "stmmac_fpe.h" #include "stmmac.h" +#include "stmmac_est.h" #include "stmmac_pcs.h" #include "stmmac_xdp.h" #include <linux/reset.h>
@@ -4213,6 +4214,10 @@ static int __stmmac_open(struct net_device *dev,if (ret) goto ptp_error; + ret =stmmac_setup_est (priv); +if (ret) + goto est_error; +stmmac_init_coalesce (priv);phylink_start (priv->phylink);
@@ -4234,7 +4239,7 @@ static int __stmmac_open(struct net_device *dev,for (chan =0 ; chan < priv->plat->tx_queues_to_use; chan++)hrtimer_cancel (&priv->dma_conf.tx_queue[chan].txtimer); - +est_error:stmmac_release_ptp (priv); ptp_error:stmmac_stop_all_dma (priv);
@@ -8462,6 +8467,10 @@ int stmmac_resume(struct device *dev) ret =stmmac_init_timestamping (priv);if (ret) goto error_stop_dma; + + ret =stmmac_setup_est (priv); +if (ret) + goto error_stop_dma; } init_coalesce:
drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +9 -35
70 lines not on this page · raw message
drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +56 -32
150 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 177/1005 bpf: Dont move a MAP_FIXED address in arena_get_unmapped_area()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit 92b5ce3ca5b7c641e2678f92419aa7833951bc9d ]
The user range of an arena must not cross a 4 GiB boundary. Thus arena_get_unmapped_area() asks the mm for 2 * len bytes and rounds the result up if necessary. This is correct only if the mm finds a free range. With MAP_FIXED the mm does no search and returns addr. For MAP_FIXED_NOREPLACE, do_mmap() also sets MAP_FIXED.
With MAP_FIXED the arena is not at addr after round_up(). Thus mmap() removes mappings outside the range from addr to addr + len. It keeps a part of those in this range. Also, round_up() can wrap to address 0, and the test for address 0 is before it.
The arch code gets twice the length of the mapping. Thus it can refuse a valid MAP_FIXED range. On s390 the arch code also grows the page table for the range. With the double length it can omit this step for a valid range.
The test for a crossing is not exact. Because ret is a long, ret >> 32 extends the sign, but the other side is unsigned. The sides are never equal for an address with bit 63 set, and round_up() always runs. Such user addresses exist on s390. arena_map_alloc() does the same test with a u64.
With MAP_FIXED, pass len to the mm. Return -EINVAL if the range crosses a boundary, as for address 0. Make ret unsigned, so that only these ranges get the error. On x86-64, if round_up() gives address 0 today, mmap() now fails with -EINVAL or with -ENOMEM from the mm. Today mmap() can also fail for the address after round_up(), for example with -ENOMEM, -EEXIST, -EPERM or -EBUSY.
Without MAP_FIXED the mm must still find a free range of 2 * len bytes inside the address space of the task. The range after round_up() is inside it, and round_up() cannot wrap. An address with bit 63 set now moves only if its range crosses a boundary.
For an arena, libbpf uses MAP_FIXED only with map_extra, and arena_map_alloc() refuses a map_extra range that crosses a boundary. A subsequent mmap() must use the range of the first mmap(). For mmap() of the map fd, this range comes from arena_get_unmapped_area(), thus it crosses no boundary. arena_map_alloc() still accepts a map_extra above TASK_SIZE, and mmap() of such an arena fails.
--- kernel/bpf/arena.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-)
kernel/bpf/arena.c +11 -2
@@ -7,6 +7,7 @@#include <linux/irq_work.h> #include "linux/filter.h" #include <linux/llist.h> +#include <linux/mman.h> #include <linux/btf_ids.h> #include <linux/vmalloc.h> #include <linux/pagemap.h>
@@ -630,7 +631,7 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad {struct bpf_map *map = filp->private_data; struct bpf_arena *arena = container_of(map, struct bpf_arena, map); -long ret; +unsigned long ret;if (pgoff)return -EINVAL ;
@@ -647,7 +648,13 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long adreturn -EINVAL ; } - ret =mm_get_unmapped_area (filp, addr, len *2 ,0 , flags); +/* +* Without MAP_FIXED the mm finds a free range. Ask for twice the +* length, so that there is room for round_up(). With MAP_FIXED the mm +* does no search, and the caller wants this address. Thus the range +* cannot move. +*/ + ret =mm_get_unmapped_area (filp, addr, flags &MAP_FIXED ? len : len *2 ,0 , flags);if (IS_ERR_VALUE (ret))return ret;if (!ret)
@@ -655,6 +662,8 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long adreturn -EINVAL ;if ((ret >>32 ) == ((ret + len -1 ) >>32 ))return ret; +if (flags &MAP_FIXED ) +return -EINVAL ;return round_up (ret,SZ_4G ); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 178/1005 sched_ext: Reject scx_bpf_destroy_dsq() in tracing programs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shubhang Kaushik (Ampere) <[email protected]>
[ Upstream commit 4c2e0751d5e6d181a5b9b2a8ada869b5bee66a83 ]
scx_bpf_destroy_dsq() takes the target user DSQ's raw spinlock. However, it is in scx_kfunc_ids_any, which is also registered for BPF_PROG_TYPE_TRACING.
For an active root scheduler without ops.sub_attach, the compatibility path in scx_prog_sched() lets an unassociated tracing program resolve to that scheduler. The tracing program can then call scx_bpf_destroy_dsq() while the target DSQ lock is already held.
For example, a scheduler which mixes FIFO and priority-queue insertions into a user DSQ triggers scx_error() from scx_dispatch_enqueue() while holding that DSQ's lock. scx_claim_exit() emits sched_ext_exit before the lock is released:
scx_dispatch_enqueue()
raw_spin_lock(&dsq->lock)
scx_error()
scx_claim_exit()
trace_sched_ext_exit()
tracing BPF program
scx_bpf_destroy_dsq(dsq_id)
destroy_dsq()
raw_spin_lock_irqsave(&dsq->lock)The tracing program recursively acquires the same raw spinlock and locks up the CPU. Because the tracepoint runs before scx_finish_exit(), disable_irq_work is not queued and the scheduler cannot enter its normal disable path.
Reject scx_bpf_destroy_dsq() from tracing programs at verification time. The kfunc remains available to SCX struct_ops and syscall programs.
--- kernel/sched/ext/ext.c | 4 ++++ 1 file changed, 4 insertions(+)
kernel/sched/ext/ext.c +4 -0
@@ -11226,6 +11226,9 @@ static const struct btf_kfunc_id_set scx_kfunc_set_any = {* when scx_locked_rq() returns NULL. Taking it while the context already holds * an rq lock, the same one or another cpu's, can deadlock. * +* scx_bpf_destroy_dsq() takes a user DSQ lock. A tracing program can run while +* that lock is already held and recursively acquire it. +* * Before returning, scx_bpf_sub_grant() and scx_bpf_sub_revoke() invoke * ops.sub_caps_updated() of the sub-schedulers whose caps changed, so those ops * run in the tracing program's context. No SCX op expects to run from an
@@ -11240,6 +11243,7 @@ BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS) +BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS)BTF_KFUNCS_END (scx_kfunc_ids_no_tracing)/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 179/1005 ASoC: meson: axg-fifo: request the irq with the clock enabled
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jerome Brunet <[email protected]>
[ Upstream commit 82fa7bfab6b961a03d6575348334e0ec15fdc712 ]
The fifo irq handler accesses registers which need pclk, but the irq is requested before pclk is enabled on open and freed after it is disabled on close.
Request the irq after enabling pclk and masking the fifo irqs. Free it before disabling pclk.
--- sound/soc/meson/axg-fifo.c | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-)
sound/soc/meson/axg-fifo.c +14 -14
@@ -244,17 +244,10 @@ int axg_fifo_pcm_open(struct snd_soc_component *component,if (ret)return ret; -/* Use the threaded irq handler only with non-atomic links */ - ret =request_threaded_irq (fifo->irq,NULL , - axg_fifo_pcm_irq_block, -IRQF_ONESHOT ,dev_name (dev), ss); -if (ret) -return ret; -/* Enable pclk to access registers and clock the fifo ip */ ret =clk_prepare_enable (fifo->pclk);if (ret) - goto free_irq; +return ret;/* Setup status2 so it reports the memory pointer */ regmap_update_bits(fifo->map, FIFO_CTRL1,
@@ -271,17 +264,24 @@ int axg_fifo_pcm_open(struct snd_soc_component *component,/* Clear any pending interrupt */ axg_fifo_ack_irq (fifo,FIFO_INT_MASK ); +/* Use the threaded irq handler only with non-atomic links */ + ret =request_threaded_irq (fifo->irq,NULL , + axg_fifo_pcm_irq_block, +IRQF_ONESHOT ,dev_name (dev), ss); +if (ret) + goto free_clk; +/* Take memory arbitror out of reset */ ret =reset_control_deassert (fifo->arb);if (ret) - goto free_clk; + goto free_irq;return 0 ; -free_clk: -clk_disable_unprepare (fifo->pclk); free_irq:free_irq (fifo->irq, ss); +free_clk: +clk_disable_unprepare (fifo->pclk);return ret; }EXPORT_SYMBOL_GPL (axg_fifo_pcm_open);
@@ -295,12 +295,12 @@ int axg_fifo_pcm_close(struct snd_soc_component *component,/* Put the memory arbitror back in reset */ ret =reset_control_assert (fifo->arb); -/* Disable fifo ip and register access */ -clk_disable_unprepare (fifo->pclk); -/* remove IRQ */ free_irq (fifo->irq, ss); +/* Disable fifo ip and register access */ +clk_disable_unprepare (fifo->pclk); +return ret; }EXPORT_SYMBOL_GPL (axg_fifo_pcm_close);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 180/1005 bpf: Fix the join of fp+0 with a value that is not a pointer to stack
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit 6185d4fc6e64439cad415d9bf527f8ffb3fa3db4 ]
arg_track follows pointers to the stack through registers and spills. Scalar evolution and the removal of dead slots rely on it to know which slots an insn reads and writes.
Where two paths meet, a register can be fp-N on one path and not a pointer to the stack on the other path. There is no value for that. The join adds a fake second offset, fp+0: with two offsets no store through the register is a certain write. But for fp+0 the fake offset is the offset itself:
join(fp-8, none) = {fp-8, fp+0} two offsets
join(fp+0, none) = {fp+0} one offset: "exactly fp+0"
Then a store counts as a certain write to the stack, but at run time it can go to other memory:
r7 = r10, or r7 = map_value + 8 ; arg_track: exactly fp+0 *(u64 *)(r10 - 8) = fp-24
*(u64 *)(r7 - 8) = map_value ; arg_track: fp-8 is overwritten
r8 = *(u64 *)(r10 - 8) ; fp-24 or map_value. arg_track: none
loop:
r1 = *(u64 *)(r10 - 24) ; the counter of the loop
...
*(u64 *)(r8 + 0) = 4096 ; arg_track: not a write to fp-24Scalar evolution does not see the last store. It gives the counter the range of a loop that only increments it. The prog loads, and it accesses a map value out of bounds.
Valid progs are rejected as well. The store through r7 makes fp-8 dead, and a later read of fp-8 fails with "slot poisoned by dead code elimination".
When the single offset is 0, drop the offsets. The result is a pointer to an unknown slot of the frame, and all updates through it are weak.
Veristat sees no difference in selftests, Cilium and sched_ext.
--- kernel/bpf/liveness.c | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-)
kernel/bpf/liveness.c +17 -14
@@ -872,6 +872,19 @@ static struct arg_track arg_join_imprecise(struct arg_track a, struct arg_trackreturn (struct arg_track ){ .mask = m, .frame =ARG_IMPRECISE }; } +/* +* 'a' or a value that is not a pointer to stack. A single fp-N gets a fake fp+0, +* to keep stack_use and prevent stack_def. fp+0 itself would stay a single offset. +*/ +static struct arg_track arg_or_none (struct arg_track a) +{ +if (a.off_cnt !=1 ) +return a; +if (!a.off[0 ]) +return (struct arg_track ){ .frame = a.frame }; +return arg_merge_offsets (a,arg_single (a.frame,0 )); +} +/* Join two arg_track values at merge points */ static struct arg_track __arg_track_join (struct arg_track a,struct arg_track b) {
@@ -896,20 +909,10 @@ static struct arg_track __arg_track_join(struct arg_track a, struct arg_track b)*/ if (a.frame ==ARG_NONE && b.frame ==ARG_NONE )return a; -if (a.frame >=0 && b.frame ==ARG_NONE ) { -/* -* When joining single fp-N add fake fp+0 to -* keep stack_use and prevent stack_def -*/ -if (a.off_cnt ==1 ) -return arg_merge_offsets (a,arg_single (a.frame,0 )); -return a; - } -if (b.frame >=0 && a.frame ==ARG_NONE ) { -if (b.off_cnt ==1 ) -return arg_merge_offsets (b,arg_single (b.frame,0 )); -return b; - } +if (a.frame >=0 && b.frame ==ARG_NONE ) +return arg_or_none (a); +if (b.frame >=0 && a.frame ==ARG_NONE ) +return arg_or_none (b);return arg_join_imprecise (a, b); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 181/1005 bpf: Rename bpf_call_summary::num_params to arg_slot_cnt
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yonghong Song <[email protected]>
[ Upstream commit c6ff4e06033fede2fd1d41232ae942add649b759 ]
The field 'num_params' counts the argument registers and outgoing stack slots a helper or kfunc call takes. The next patch gives a 16-byte parameter two slots, so the name stops describing what the field holds.
Rename 'num_params' to 'arg_slot_cnt'. No functional change.
Stable-dep-of: cdefba74b53f ("bpf: Don't trust pointers spilled in slots that a callee can write")
--- include/linux/bpf_verifier.h | 2 +- kernel/bpf/liveness.c | 10 +++++----- kernel/bpf/verifier.c | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-)
include/linux/bpf_verifier.h +1 -1
@@ -1053,7 +1053,7 @@ static inline struct bpf_subprog_info *subprog_info(struct bpf_verifier_env *env }struct bpf_call_summary { -u8 num_params; +u8 arg_slot_cnt;bool is_void;bool fastcall; };
kernel/bpf/liveness.c +5 -5
@@ -1596,21 +1596,21 @@ static int record_call_access(struct bpf_verifier_env *env, {struct bpf_insn *insn = &env->prog->insnsi[insn_idx];struct bpf_call_summary cs; -int r, err, num_params =5 ; +int r, err, arg_slot_cnt =5 ;if (bpf_pseudo_call (insn))return 0 ;if (bpf_get_call_summary (env, insn, &cs)) - num_params = cs.num_params; + arg_slot_cnt = cs.arg_slot_cnt; -for (r =BPF_REG_1 ; r <BPF_REG_1 +min (num_params,MAX_BPF_FUNC_REG_ARGS ); r++) { +for (r =BPF_REG_1 ; r <BPF_REG_1 +min (arg_slot_cnt,MAX_BPF_FUNC_REG_ARGS ); r++) { err =record_arg_access (env, instance, insn, &at[r], r -1 , insn_idx);if (err)return err; } -for (r =0 ; r <MAX_STACK_ARG_SLOTS && r < num_params -MAX_BPF_FUNC_REG_ARGS ; r++) { +for (r =0 ; r <MAX_STACK_ARG_SLOTS && r < arg_slot_cnt -MAX_BPF_FUNC_REG_ARGS ; r++) { err =record_arg_access (env, instance, insn, &at[MAX_BPF_REG + r], r +MAX_BPF_FUNC_REG_ARGS , insn_idx);if (err)
@@ -2386,7 +2386,7 @@ static void compute_insn_live_regs(struct bpf_verifier_env *env, def =ALL_CALLER_SAVED_REGS ; use = def & ~BIT (BPF_REG_0 );if (bpf_get_call_summary (env, insn, &cs)) - use =GENMASK (min_t (u8, cs.num_params,MAX_BPF_FUNC_REG_ARGS ),1 ); + use =GENMASK (min_t (u8, cs.arg_slot_cnt,MAX_BPF_FUNC_REG_ARGS ),1 ); def =mask_widen (def); use =mask_widen (use);break ;
kernel/bpf/verifier.c +4 -4
@@ -17985,11 +17985,11 @@ bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, (bpf_verifier_inlines_helper_call (env, call->imm) ||bpf_jit_inlines_helper_call (call->imm)); cs->is_void = fn->ret_type ==RET_VOID ; - cs->num_params =0 ; + cs->arg_slot_cnt =0 ;for (i =0 ; i <ARRAY_SIZE (fn->arg_type); ++i) {if (fn->arg_type[i] ==ARG_DONTCARE )break ; - cs->num_params++; + cs->arg_slot_cnt++; }return true; }
@@ -18001,7 +18001,7 @@ bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,if (err <0 )/* error would be reported later */ return false; - cs->num_params =btf_type_vlen (meta.func_proto); + cs->arg_slot_cnt =btf_type_vlen (meta.func_proto); cs->fastcall = meta.kfunc_flags &KF_FASTCALL ; cs->is_void =btf_type_is_void (btf_type_by_id (meta.btf, meta.func_proto->type));return true;
@@ -18110,7 +18110,7 @@ static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,* - includes R1-R5 if corresponding parameter has is described * in the function prototype. */ - clobbered_regs_mask =GENMASK (cs.num_params, cs.is_void ?1 :0 ); + clobbered_regs_mask =GENMASK (cs.arg_slot_cnt, cs.is_void ?1 :0 );/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ expected_regs_mask = ~clobbered_regs_mask &ALL_CALLER_SAVED_REGS ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 182/1005 bpf: Prepare static analysis passes for callx instruction
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit 373e3fd0bff0e276fd76c86c830cdb16a3457776 ]
BPF_JMP | BPF_CALL | BPF_X (callx) will be an indirect call of static subprog with address in dst_reg. The passes that run before the main verifier pass don't know which subprog callx calls.
Teach them to treat callx as a call with unknown callee:
- const_fold: callx clobbers R0-R5 like any other call. Otherwise bpf_prune_dead_branches() could rewrite a live conditional jump.
- live regs: callx uses R1-R5 and dst_reg, defines R0-R5.
- stack liveness: func instances are keyed by (callsite, depth) and cannot describe a callsite with multiple callees. Don't create instances for callees of callx. If any callx argument is derived from fp mark stack of all frames as read at callx insn and keep slots of outer frames alive 'before' the callsite while the callee is verified. Same as for callbacks that are not known statically. The callee is analyzed as standalone instance.
- backtracking: treat callx as a call of static subprog, same as BPF_PSEUDO_CALL.
callx is still rejected as unknown opcode. No functional change.
Stable-dep-of: cdefba74b53f ("bpf: Don't trust pointers spilled in slots that a callee can write")
--- include/linux/bpf_verifier.h | 6 ++++++ kernel/bpf/backtrack.c | 20 +++++++++++-------- kernel/bpf/const_fold.c | 3 ++- kernel/bpf/liveness.c | 38 +++++++++++++++++++++++++++++++----- 4 files changed, 53 insertions(+), 14 deletions(-)
include/linux/bpf_verifier.h +6 -0
@@ -1076,6 +1076,12 @@ static inline bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) insn->src_reg ==BPF_PSEUDO_KFUNC_CALL ; } +/* callx: indirect call of a bpf subprog whose address is in insn->dst_reg */ +static inline bool bpf_is_callx (const struct bpf_insn *insn) +{ +return insn->code == (BPF_JMP |BPF_CALL |BPF_X ); +} + __printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log,const char *fmt,va_list args); __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
kernel/bpf/backtrack.c +12 -8
@@ -406,15 +406,18 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,if (class ==BPF_STX )bt_set_reg (bt, sreg); }else if (class ==BPF_JMP || class ==BPF_JMP32 ) { -if (bpf_pseudo_call (insn)) { -int subprog_insn_idx, subprog; +if (bpf_pseudo_call (insn) ||bpf_is_callx (insn)) { +int subprog_insn_idx, subprog =-1 ; - subprog_insn_idx = idx + insn->imm +1 ; - subprog =bpf_find_subprog (env, subprog_insn_idx); -if (subprog <0 ) -return -EFAULT ; +if (bpf_pseudo_call (insn)) { + subprog_insn_idx = idx + insn->imm +1 ; + subprog =bpf_find_subprog (env, subprog_insn_idx); +if (subprog <0 ) +return -EFAULT ; + } -if (bpf_subprog_is_global (env, subprog)) { +/* callx calls static subprogs only */ +if (subprog >=0 &&bpf_subprog_is_global (env, subprog)) {/* check that jump history doesn't have any * extra instructions from subprog; the next * instruction after call to global subprog
@@ -531,7 +534,8 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,* necessary. In the former we never do that. */ from_subprog_call = subseq_idx -1 >=0 && -bpf_pseudo_call (&env->prog->insnsi[subseq_idx -1 ]); + (bpf_pseudo_call (&env->prog->insnsi[subseq_idx -1 ]) || +bpf_is_callx (&env->prog->insnsi[subseq_idx -1 ])); r0_precise = from_subprog_call &&bt_is_reg_set (bt,BPF_REG_0 );
kernel/bpf/const_fold.c +2 -1
@@ -191,7 +191,8 @@ static void const_reg_xfer(struct bpf_verifier_env *env, struct const_arg_info * dst->val = val;break ;case BPF_JMP : -if (opcode !=BPF_CALL ) +/* both 'call imm' and 'callx reg' clobber caller saved registers */ +if (BPF_OP (insn->code) !=BPF_CALL )break ; process_call:for (r =BPF_REG_0 ; r <=BPF_REG_5 ; r++)
kernel/bpf/liveness.c +33 -5
@@ -464,12 +464,29 @@ int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_return 0 ; } +/* +* Stack slots of outer frames that the callee may read are accounted as read +* by the @callsite insn itself, i.e. they are live before @callsite and may be +* dead after it, when: +* - @callsite calls a callback, which may be called several times; +* - @callsite is callx. Its callee is not known when stack liveness is +* computed, so there is no func instance for it at @callsite. While +* the verifier is in the callee lookup_instance() finds its standalone +* instance that knows nothing about outer frames. What the callee may read +* there is recorded by record_call_access(). +*/ +static bool callee_stack_access_at_callsite (struct bpf_verifier_env *env,u32 callsite) +{ +return bpf_calls_callback (env, callsite) || +bpf_is_callx (&env->prog->insnsi[callsite]); +} +bool bpf_stack_slot_alive (struct bpf_verifier_env *env,u32 frameno,u32 half_spi) {/* * Slot is alive if it is read before q->insn_idx in current func instance, * or if for some outer func instance: -* - alive before callsite if callsite calls callback, otherwise +* - alive before callsite if callsite calls callback or is callx, otherwise * - alive after callsite */ struct live_stack_query *q = &env->liveness->live_stack_query;
@@ -502,7 +519,7 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp/* Get callsite from verifier state, not from instance callchain */ callsite = q->callsites[i]; - alive =bpf_calls_callback (env, callsite) + alive =callee_stack_access_at_callsite (env, callsite) ?is_live_before (instance, callsite, rel, half_spi) :is_live_before (instance, callsite +1 , rel, half_spi);if (alive)
@@ -1601,7 +1618,15 @@ static int record_call_access(struct bpf_verifier_env *env,if (bpf_pseudo_call (insn))return 0 ; -if (bpf_get_call_summary (env, insn, &cs)) +if (bpf_is_callx (insn)) +/* +* The callee is not known statically. Assume that all arg +* slots are passed and let record_arg_access() conservatively +* mark the stack of all frames as read if any of them is +* derived from a frame pointer. +*/ + arg_slot_cnt =MAX_BPF_FUNC_REG_ARGS +MAX_STACK_ARG_SLOTS ; +else if (bpf_get_call_summary (env, insn, &cs)) arg_slot_cnt = cs.arg_slot_cnt;for (r =BPF_REG_1 ; r <BPF_REG_1 +min (arg_slot_cnt,MAX_BPF_FUNC_REG_ARGS ); r++) {
@@ -1695,7 +1720,7 @@ static void print_subprog_arg_access(struct bpf_verifier_env *env,bool has_extra = false;u8 cls =BPF_CLASS (insns[idx].code);bool is_ldx_stx_call = cls ==BPF_LDX || cls ==BPF_STX || - insns[idx].code == (BPF_JMP |BPF_CALL ); + (cls ==BPF_JMP &&BPF_OP (insns[idx].code) ==BPF_CALL );verbose (env,"%3d: " , idx);bpf_verbose_insn (env, &insns[idx]);
@@ -1887,7 +1912,7 @@ static int compute_subprog_args(struct bpf_verifier_env *env,if (err) goto err_free; -if (insn->code == (BPF_JMP |BPF_CALL )) { +if (BPF_CLASS (insn->code) ==BPF_JMP &&BPF_OP (insn->code) ==BPF_CALL ) { err =record_call_access (env, instance, at_in[i], idx);if (err) goto err_free;
@@ -2389,6 +2414,9 @@ static void compute_insn_live_regs(struct bpf_verifier_env *env, use =GENMASK (min_t (u8, cs.arg_slot_cnt,MAX_BPF_FUNC_REG_ARGS ),1 ); def =mask_widen (def); use =mask_widen (use); +/* callx reads the address of the callee from dst_reg */ +if (bpf_is_callx (insn)) + use |= dst;break ;default : def =0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 183/1005 bpf: Dont trust pointers spilled in slots that a callee can write
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Starovoitov <[email protected]>
[ Upstream commit cdefba74b53fb9b482355ebde1654800aea45dae ]
arg_track follows pointers to the stack through registers and spills. Scalar evolution and the removal of dead slots rely on it to know which slots an insn reads and writes.
arg_track assumes that a call does not change the pointers that are spilled in the frame of the caller. But a static subprog or a callback can store a pointer to other memory there, and the caller can use it:
*(u64 *)(r10 - 16) = fp-8
r1 = fp-16, r2 = map_value
call sub ; *(u64 *)(r1 + 0) = r2
r7 = *(u64 *)(r10 - 16) ; verifier: map_value. arg_track: fp-8
*(u64 *)(r10 - 8) = fp-24
*(u64 *)(r7 + 0) = 0 ; arg_track: fp-8 is overwritten
r8 = *(u64 *)(r10 - 8) ; verifier: fp-24. arg_track: none
loop:
r1 = *(u64 *)(r10 - 24) ; the counter of the loop
...
*(u64 *)(r8 + 0) = 4096 ; arg_track: not a write to fp-24Scalar evolution does not see the last store. It gives the counter the range of a loop that only increments it. The prog loads, and it accesses a map value out of bounds.
Valid progs are rejected as well. The store through r7 makes fp-8 dead, and a later read of fp-8 fails with "slot poisoned by dead code elimination".
When a static subprog or a callback can get a pointer to the frame of its caller, join every slot of that frame with "not a pointer to the stack". Reads and possible writes through a filled pointer are still seen, but no store through it is a certain write. It has to be every slot: the callee reaches the whole frame from one pointer, and callees are analyzed after the caller. The price is precision: an 8-byte load through a filled pointer gives a value that can point to any frame.
For a spilled copy of r10 this needs "bpf: Fix the join of fp+0 with a value that is not a pointer to stack".
In selftests, Cilium and sched_ext the stack marks change in 4 of 12522 progs. Verdicts, insns and states do not change in any prog.
one_fp_clear_stack_threshold and two_fp_clear_stack_threshold expect the fake offset fp+0 in the log now.
--- kernel/bpf/liveness.c | 52 ++++++++++++++----- .../selftests/bpf/progs/verifier_live_stack.c | 12 +++-- 2 files changed, 47 insertions(+), 17 deletions(-)
kernel/bpf/liveness.c +39 -13
@@ -1282,6 +1282,31 @@ static struct arg_track arg_track_deref(struct bpf_verifier_env *env, struct bpfreturn (struct arg_track ){ .frame =ARG_NONE }; } +/* +* True if the call at @insn_idx can pass a pointer to the frame at @depth to a static subprog +* or to a callback. They use it as a pointer to stack, a global subprog gets plain memory. +* It errs on the safe side: it looks at all argument registers and stack args, also at those +* that this callee doesn't take. +*/ +static bool subprog_gets_local_fp (struct bpf_verifier_env *env,struct bpf_insn *insn,int insn_idx, +struct arg_track *at,int depth) +{ +int r; + +if (bpf_pseudo_call (insn)) { + r =bpf_find_subprog (env, insn_idx + insn->imm +1 ); +if (r >=0 &&bpf_subprog_is_global (env, r)) +return false; + }else if (!bpf_is_callx (insn) && !bpf_calls_callback (env, insn_idx)) { +return false; + } +/* R1-R5 and stack args */ +for (r =BPF_REG_1 ; r <MAX_AT_TRACK_REGS ; r++) +if ((r <=BPF_REG_5 || r >=MAX_BPF_REG ) &&can_be_local_fp (depth, r, &at[r])) +return true; +return false; +} +/* * Pure dataflow transfer function for arg_track state. * Updates at_out[] based on how the instruction modifies registers.
@@ -1345,21 +1370,22 @@ static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn, *dst = none; }else if (class ==BPF_JMP && code ==BPF_CALL ) {/* -* at_stack_out[slot] is not cleared by the helper and subprog calls. -* The fill_from_stack() may return the stale spill — which is an FP-derived arg_track -* (the value that was originally spilled there). The loaded register then carries -* a phantom FP-derived identity that doesn't correspond to what's actually in the slot. -* This phantom FP pointer propagates forward, and wherever it's subsequently used -* (as a helper argument, another store, etc.), it sets stack liveness bits. -* Those bits correspond to stack accesses that don't actually happen. -* So the effect is over-reporting stack liveness — marking slots as live that aren't -* actually accessed. The verifier preserves more state than necessary across calls, -* which is conservative. +* Helpers, kfuncs and global subprogs can scratch stack slots. The verifier reads +* a scalar from a scratched slot, but at_stack_out[slot] is not cleared, and +* fill_from_stack() returns the stale spill: an FP-derived arg_track for a scalar. +* A scalar can't be dereferenced, so the stale value can only set liveness bits +* for stack accesses that don't happen. That is conservative. * -* helpers can scratch stack slots, but they won't make a valid pointer out of it. -* subprogs are allowed to write into parent slots, but they cannot write -* _any_ FP-derived pointer into it (either their own or parent's FP). +* Static subprogs and callbacks can't store an FP-derived pointer into the frame of +* the caller, but they can store any other pointer there. The caller can fill it +* and store through it. With the stale spill that store would be a definite write +* to a stack slot, and it doesn't touch the stack. Callees are analyzed after the +* caller, and they reach the whole frame from one pointer to it. So after the call +* every slot holds what it held before or a value that is not FP-derived. */ +if (subprog_gets_local_fp (env, insn, insn_idx, at_out, depth)) +for (slot =0 ; slot < nslots; slot++) + at_stack_out[slot] =__arg_track_join (at_stack_out[slot], none);for (r =BPF_REG_0 ; r <=BPF_REG_5 ; r++) at_out[r] = none; }else if (class ==BPF_LDX ) {
tools/testing/selftests/bpf/progs/verifier_live_stack.c +8 -4
@@ -1763,11 +1763,15 @@ static __used __naked void grandchild_deref(void) ::: __clobber_all); } +/* +* The callee gets a pointer to the frame that holds the spills. It can store a pointer +* that is not FP-derived over them: after the call each of them is "fp-N or not FP-derived". +*/ SEC("socket") __log_level(2) __success -__msg("14: (79) r1 = *(u64 *)(r10 -8) // r6=fp0-8 r7=fp1-16 fp-8=fp1-16 fp-16=fp0-8") -__msg("15: (79) r0 = *(u64 *)(r1 +0) // r1=fp1-16 r6=fp0-8 r7=fp1-16 fp-8=fp1-16 fp-16=fp0-8") +__msg("14: (79) r1 = *(u64 *)(r10 -8) // r6=fp0-8 r7=fp1-16 fp-8=fp1-16|fp1+0 fp-16=fp0-8|fp0+0") +__msg("15: (79) r0 = *(u64 *)(r1 +0) // r1=fp1-16|fp1+0 r6=fp0-8 r7=fp1-16 fp-8=fp1-16|fp1+0") __msg("stack use/def subprog#1 mid_two_fp_threshold (d1,cs2):") __msg("14: (79) r1 = *(u64 *)(r10 -8) ; use: fp1-8")__msg ("15: (79) r0 = *(u64 *)(r1 +0) ; use: fp1-16" )
@@ -1812,8 +1816,8 @@ static __used __naked void inner_nop_fptest(void) SEC("socket") __log_level(2) __success -__msg("13: (79) r1 = *(u64 *)(r10 -8) // r6=fp0-8 r7=fp1-16 fp-8=fp1-16 fp-16=fp0-8") -__msg("14: (79) r0 = *(u64 *)(r1 +0) // r1=fp1-16 r6=fp0-8 r7=fp1-16 fp-8=fp1-16 fp-16=fp0-8") +__msg("13: (79) r1 = *(u64 *)(r10 -8) // r6=fp0-8 r7=fp1-16 fp-8=fp1-16|fp1+0 fp-16=fp0-8|fp0+0") +__msg("14: (79) r0 = *(u64 *)(r1 +0) // r1=fp1-16|fp1+0 r6=fp0-8 r7=fp1-16 fp-8=fp1-16|fp1+0") __msg("stack use/def subprog#1 mid_one_fp_threshold (d1,cs2):") __msg("13: (79) r1 = *(u64 *)(r10 -8) ; use: fp1-8")__msg ("14: (79) r0 = *(u64 *)(r1 +0) ; use: fp1-16" )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 184/1005 regulator: mt6363: Fix the registers of the VSRAM CPU and APU LDOs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: GIBEOM LEE (이기범) <[email protected]>
[ Upstream commit 8aed8b66751e006589b6a9474af757d1ba04a857 ]
VSRAM_CPUB, VSRAM_CPUM, VSRAM_CPUL and VSRAM_APU have a register of their own for the enable (bit 0) and low power (bit 1) bits, which the header defines as MT6363_RG_LDO_VSRAM_*_ADDR. The driver does not use it:MT6363_LDO_L() takes the registers of the BUCK1 group, which is right only for the VSRAM_{DIGRF,MDFE,MODEM} LDOs of MT6363_LDO_L_SC().
Bit 0 of the BUCK1 enable register is VS1 and bit 1 of the BUCK1 low power register is VS3. So disabling one of these LDOs disables VS1, their state is the state of VS1, and asking for their low power mode puts VS3 in it. The LDOs themselves are never switched.
Use the register of the LDO, as MediaTek's driver does.
--- drivers/regulator/mt6363-regulator.c | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-)
drivers/regulator/mt6363-regulator.c +14 -11
@@ -147,7 +147,7 @@ struct mt6363_regulator_info { }#define MT6363_LDO_LINEAR_OPS (match, vreg, in_sup, vops, min, max, \ - step, buck_reg, ocp_intn) \ + step, en_reg, lp_reg, ocp_intn) \ [MT6363_ID_##vreg] = { \ .desc = { \ .name = match, \
@@ -160,13 +160,13 @@ struct mt6363_regulator_info { .n_voltages = (max - min) / step + 1, \ .min_uV = min, \ .uV_step = step, \ - .enable_reg = MT6363_RG_##buck_reg##_EN_ADDR, \ + .enable_reg = en_reg, \ .enable_mask = BIT(MT6363_RG_LDO_##vreg##_EN_BIT), \ .vsel_reg = MT6363_RG_LDO_##vreg##_VOSEL_ADDR, \ .vsel_mask = MT6363_RG_LDO_##vreg##_VOSEL_MASK, \ .of_map_mode = mt6363_map_mode, \ }, \ - .lp_mode_reg = MT6363_RG_##buck_reg##_LP_ADDR, \ + .lp_mode_reg = lp_reg, \ .lp_mode_mask = BIT(MT6363_RG_LDO_##vreg##_LP_BIT), \ .hw_lp_mode_reg = MT6363_LDO_##vreg##_HW_LP_MODE, \ .hw_lp_mode_mask = 0x4, \
@@ -176,12 +176,15 @@ struct mt6363_regulator_info {#define MT6363_LDO_L_SC (match, vreg, inp, min, max, step, buck_reg, \ ocp_intn) \ MT6363_LDO_LINEAR_OPS(match, vreg, inp, mt6363_vreg_setclr_ops, \ - min, max, step, buck_reg, ocp_intn) + min, max, step, \ + MT6363_RG_##buck_reg##_EN_ADDR, \ + MT6363_RG_##buck_reg##_LP_ADDR, ocp_intn) -#define MT6363_LDO_L (match, vreg, inp, min, max, step, buck_reg, \ - ocp_intn) \ +#define MT6363_LDO_L (match, vreg, inp, min, max, step, ocp_intn) \ MT6363_LDO_LINEAR_OPS(match, vreg, inp, mt6363_ldo_linear_ops, \ - min, max, step, buck_reg, ocp_intn) + min, max, step, \ + MT6363_RG_LDO_##vreg##_ADDR, \ + MT6363_RG_LDO_##vreg##_ADDR, ocp_intn)#define MT6363_LDO_LINEAR_CAL_OPS (match, vreg, in_sup, vops, vrnum, \ ocp_intn) \
@@ -754,10 +757,10 @@ static struct mt6363_regulator_info mt6363_regulators[] = {MT6363_LDO_VT ("vio0p75" ,VIO075 ,"vs1-ldo1" ,5 ,36 ),MT6363_LDO_VT ("vio18" ,VIO18 ,"vs1-ldo2" ,3 ,35 ),MT6363_LDO_VT ("vm18" ,VM18 ,"vs1-ldo1" ,4 ,40 ), -MT6363_LDO_L ("vsram-apu" ,VSRAM_APU ,"vs3-ldo1" ,400000 ,1193750 ,6250 ,BUCK1 ,30 ), -MT6363_LDO_L ("vsram-cpub" ,VSRAM_CPUB ,"vs2-ldo1" ,400000 ,1193750 ,6250 ,BUCK1 ,27 ), -MT6363_LDO_L ("vsram-cpum" ,VSRAM_CPUM ,"vs2-ldo1" ,400000 ,1193750 ,6250 ,BUCK1 ,28 ), -MT6363_LDO_L ("vsram-cpul" ,VSRAM_CPUL ,"vs2-ldo2" ,400000 ,1193750 ,6250 ,BUCK1 ,29 ), +MT6363_LDO_L ("vsram-apu" ,VSRAM_APU ,"vs3-ldo1" ,400000 ,1193750 ,6250 ,30 ), +MT6363_LDO_L ("vsram-cpub" ,VSRAM_CPUB ,"vs2-ldo1" ,400000 ,1193750 ,6250 ,27 ), +MT6363_LDO_L ("vsram-cpum" ,VSRAM_CPUM ,"vs2-ldo1" ,400000 ,1193750 ,6250 ,28 ), +MT6363_LDO_L ("vsram-cpul" ,VSRAM_CPUL ,"vs2-ldo2" ,400000 ,1193750 ,6250 ,29 ),MT6363_LDO_L_SC ("vsram-digrf" ,VSRAM_DIGRF ,"vs3-ldo1" ,400000 ,1193750 ,6250 ,BUCK1 ,23 ),MT6363_LDO_L_SC ("vsram-mdfe" ,VSRAM_MDFE ,"vs3-ldo1" ,400000 ,1193750 ,6250 ,BUCK1 ,24 ), MT6363_LDO_L_SC("vsram-modem", VSRAM_MODEM, "vs3-ldo2", 400000, 1193750, 6250, BUCK1, 25),
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 185/1005 regulator: mt6363: Use 8-bit register values
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexandre Mergnat <[email protected]>
[ Upstream commit 7318d3833067e4edb7c2a9bc244e8818b1597ff2 ]
The registers are 8 bits wide, but the regulator regmap uses 16-bit values, so every access also covers the next register. On little-endian CPUs, each regmap_write() also writes zero to the next register:
disabling VS2 or a VBUCK rail through its clear register 0x212 also clears the enable bits of VS1, VS3 and three VSRAM rails in 0x213.
Change the regmap values to 8 bits. Store the BUCK and TMA keys as __le16 so that the low byte goes to the first key register on any CPU, as it did on little-endian CPUs.
--- drivers/regulator/mt6363-regulator.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
drivers/regulator/mt6363-regulator.c +6 -5
@@ -384,7 +384,7 @@ static unsigned int mt6363_regulator_get_mode(struct regulator_dev *rdev)static int mt6363_buck_unlock (struct regmap *map,bool unlock) { -u16 buf = unlock ?MT6363_BUCK_TOP_UNLOCK_VALUE :0 ; +__le16 buf =cpu_to_le16 (unlock ?MT6363_BUCK_TOP_UNLOCK_VALUE :0 );return regmap_bulk_write (map,MT6363_BUCK_TOP_KEY_PROT_LO , &buf,sizeof (buf)); }
@@ -485,7 +485,8 @@ static int mt6363_regulator_set_load(struct regulator_dev *rdev, int load_uA)static int mt6363_vemc_set_voltage_sel (struct regulator_dev *rdev,unsigned int sel) { -const u16 tma_unlock_key =MT6363_TMA_UNLOCK_VALUE ; +const __le16 tma_unlock_key =cpu_to_le16 (MT6363_TMA_UNLOCK_VALUE ); +const __le16 tma_lock_key =cpu_to_le16 (0 );const struct regulator_desc *rdesc = rdev->desc;struct regmap *regmap = rdev->regmap;unsigned int range, val;
@@ -542,8 +543,8 @@ static int mt6363_vemc_set_voltage_sel(struct regulator_dev *rdev, unsigned int lock_tma:/* Unconditionally re-lock TMA */ - val =0 ; -regmap_bulk_write (rdev->regmap,MT6363_TOP_TMA_KEY_L , &val,2 ); +regmap_bulk_write (rdev->regmap,MT6363_TOP_TMA_KEY_L , + &tma_lock_key,sizeof (tma_lock_key));return ret; }
@@ -814,7 +815,7 @@ static struct regmap *mt6363_spmi_register_regmap(struct device *dev) {struct regmap_config mt6363_regmap_config = { .reg_bits =16 , - .val_bits =16 , + .val_bits =8 , .max_register =0x1f90 , .fast_io = true, };
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 186/1005 regulator: mt6363: Fix VEMC voltage selection
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexandre Mergnat <[email protected]>
[ Upstream commit a8d72f246edb9323f6e0ae8283676a323b7847eb ]
VEMC encodes its voltage as a range and a trim value. The custom getter looks up the range with
if (rdesc->linear_range_selectors_bitfield[range] != calsel)
so it stops at the first non-matching range and the reported voltage is wrong for every range setting. With hardware trap 1, the custom getter and setter apply MT6363_RG_VEMC_VOSEL_1_MASK, the trap 1 range field, to the trap 0 trim register and keep the trap 0 range field. Voltage changes are then not applied and the reported voltage does not reflect the trap 1 settings.
Apart from the trap handling, both callbacks reimplement the regulator core pickable regmap helpers, which work for VEMC once the descriptor holds the range field and trim register of the hardware trap. Select that field and register at probe and use the helpers instead of fixing the copies. Keep the setter as a wrapper for the TMA unlock and relock around the write, which the helper does not do. A trap value other than 0 or 1, or a failed trap read, now fails the probe instead of the VEMC voltage get and set.
--- drivers/regulator/mt6363-regulator.c | 120 ++++++--------------- include/linux/regulator/mt6363-regulator.h | 1 + 2 files changed, 33 insertions(+), 88 deletions(-)
drivers/regulator/mt6363-regulator.c +32 -88
@@ -4,7 +4,6 @@// Copyright (c) 2025 Collabora Ltd // AngeloGioacchino Del Regno <[email protected]> -#include <linux/bitfield.h> #include <linux/delay.h> #include <linux/devm-helpers.h> #include <linux/err.h>
@@ -487,30 +486,7 @@ static int mt6363_vemc_set_voltage_sel(struct regulator_dev *rdev, unsigned int {const __le16 tma_unlock_key =cpu_to_le16 (MT6363_TMA_UNLOCK_VALUE );const __le16 tma_lock_key =cpu_to_le16 (0 ); -const struct regulator_desc *rdesc = rdev->desc; -struct regmap *regmap = rdev->regmap; -unsigned int range, val; -int i, ret; -u16 mask; - -for (i =0 ; i < rdesc->n_linear_ranges; i++) { -const struct linear_range *r = &rdesc->linear_ranges[i]; -unsigned int voltages_in_range =linear_range_values_in_range (r); - -if (sel < voltages_in_range) -break ; - sel -= voltages_in_range; - } - -if (i == rdesc->n_linear_ranges) -return -EINVAL ; - - ret =regmap_read (rdev->regmap,MT6363_TOP_TRAP , &val); -if (ret) -return ret; - -if (val >1 ) -return -EINVAL ; +int ret;/* Unlock TMA for writing */ ret = regmap_bulk_write(rdev->regmap, MT6363_TOP_TMA_KEY_L,
@@ -518,30 +494,8 @@ static int mt6363_vemc_set_voltage_sel(struct regulator_dev *rdev, unsigned intif (ret)return ret; -/* If HW trapping value is 1, use VEMC_VOSEL_1 instead of VEMC_VOSEL_0 */ -if (val ==1 ) { - mask =MT6363_RG_VEMC_VOSEL_1_MASK ; - sel =FIELD_PREP (MT6363_RG_VEMC_VOSEL_1_MASK , sel); - }else { - mask = rdesc->vsel_mask; - } - - sel <<=ffs (rdesc->vsel_mask) -1 ; - sel += rdesc->linear_ranges[i].min_sel; - - range = rdesc->linear_range_selectors_bitfield[i]; - range <<=ffs (rdesc->vsel_range_mask) -1 ; - -/* Write to the vreg calibration register for voltage finetuning */ - ret =regmap_update_bits (regmap, rdesc->vsel_range_reg, - rdesc->vsel_range_mask, range); -if (ret) - goto lock_tma; - -/* Function must return the result of this write operation */ - ret =regmap_update_bits (regmap, rdesc->vsel_reg, mask, sel); + ret =regulator_set_voltage_sel_pickable_regmap (rdev, sel); -lock_tma:/* Unconditionally re-lock TMA */ regmap_bulk_write (rdev->regmap,MT6363_TOP_TMA_KEY_L , &tma_lock_key,sizeof (tma_lock_key));
@@ -549,45 +503,6 @@ static int mt6363_vemc_set_voltage_sel(struct regulator_dev *rdev, unsigned intreturn ret; } -static int mt6363_vemc_get_voltage_sel (struct regulator_dev *rdev) -{ -const struct regulator_desc *rdesc = rdev->desc; -unsigned int vosel, trap, calsel; -int vcal, vsel, range, ret; - - ret =regmap_read (rdev->regmap, rdesc->vsel_reg, &vosel); -if (ret) -return ret; - - ret =regmap_read (rdev->regmap, rdesc->vsel_range_reg, &calsel); -if (ret) -return ret; - - calsel &= rdesc->vsel_range_mask; -for (range =0 ; range < rdesc->n_linear_ranges; range++) -if (rdesc->linear_range_selectors_bitfield[range] != calsel) -break ; - -if (range == rdesc->n_linear_ranges) -return -EINVAL ; - - ret =regmap_read (rdev->regmap,MT6363_TOP_TRAP , &trap); -if (ret) -return ret; - -/* If HW trapping value is 1, use VEMC_VOSEL_1 instead of VEMC_VOSEL_0 */ -if (trap >1 ) -return -EINVAL ; -else if (trap ==1 ) - vsel =FIELD_GET (MT6363_RG_VEMC_VOSEL_1_MASK , vosel); -else - vsel = vosel & rdesc->vsel_mask; - - vcal =linear_range_values_in_range_array (rdesc->linear_ranges, range); - -return vsel + vcal; -} -static int mt6363_va15_set_voltage_sel (struct regulator_dev *rdev,unsigned int sel) {struct regmap *regmap = rdev->regmap;
@@ -700,7 +615,7 @@ static const struct regulator_ops mt6363_ldo_vemc_ops = { .list_voltage = regulator_list_voltage_pickable_linear_range, .map_voltage = regulator_map_voltage_pickable_linear_range, .set_voltage_sel = mt6363_vemc_set_voltage_sel, - .get_voltage_sel = mt6363_vemc_get_voltage_sel, + .get_voltage_sel = regulator_get_voltage_sel_pickable_regmap, .set_voltage_time_sel = regulator_set_voltage_time_sel, .enable = regulator_enable_regmap, .disable = regulator_disable_regmap,
@@ -797,6 +712,30 @@ static int mt6363_backup_op_setting(struct regmap *map, struct mt6363_regulator_return 0 ; } +static int mt6363_vemc_select_bank (struct regmap *map,struct regulator_desc *desc) +{ +unsigned int trap; +int ret; + + ret =regmap_read (map,MT6363_TOP_TRAP , &trap); +if (ret) +return ret; + +/* The hardware trap value selects which VEMC voltage controls are used */ +switch (trap) { +case 0 : + desc->vsel_reg =MT6363_RG_VEMC_VOCAL_ADDR ; + desc->vsel_range_mask =MT6363_RG_VEMC_VOSEL_MASK ; +return 0 ; +case 1 : + desc->vsel_reg =MT6363_RG_VEMC_VOCAL_1_ADDR ; + desc->vsel_range_mask =MT6363_RG_VEMC_VOSEL_1_MASK ; +return 0 ; +default : +return -EINVAL ; + } +} +static void mt6363_irq_remove (void *data) {int *virq = data;
@@ -881,6 +820,11 @@ static int mt6363_regulator_probe(struct platform_device *pdev)*/ regmap_read (config.regmap,MT6363_TOP_TRAP , &val); + ret =mt6363_vemc_select_bank (config.regmap, + &mt6363_regulators[MT6363_ID_VEMC ].desc); +if (ret) +return dev_err_probe (dev, ret,"Failed to select VEMC bank\n" ); + interrupt_parent =of_irq_find_parent (dev->of_node);if (!interrupt_parent)return dev_err_probe (dev, -EINVAL ,"Cannot find IRQ parent\n" );
include/linux/regulator/mt6363-regulator.h +1 -0
@@ -138,6 +138,7 @@#define MT6363_RG_LDO_VSRAM_APU_VOSEL_ADDR 0x1b17#define MT6363_RG_LDO_VSRAM_APU_VOSEL_MASK GENMASK(6, 0)#define MT6363_RG_VEMC_VOCAL_ADDR 0x1b1b +#define MT6363_RG_VEMC_VOCAL_1_ADDR 0x1b1c#define MT6363_RG_VEMC_VOCAL_MASK GENMASK(3, 0)#define MT6363_RG_LDO_VCN15_ADDR 0x1b57#define MT6363_RG_LDO_VCN15_EN_BIT 0
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 187/1005 Bluetooth: hci_sync: Fix invalid Supervision_Timeout in LE Set Default Rate
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Luiz Augusto von Dentz <[email protected]>
[ Upstream commit fb1baa000d7a0b597ab9eb29b179b03e70e5f6ee ]
The LE Set Default Rate Parameters command is rejected with Invalid HCI Command Parameters (0x12) because the Supervision_Timeout of 120 ms is exactly the minimum recommended by HOGP v1.2:
Greater than or equal to (1 + Peripheral Latency) x Subrate max x Connection Interval max x 2
But the Core spec treats the equality as invalid:
BLUETOOTH CORE SPECIFICATION Version 6.3 | Vol 4, Part E 7.8.158. LE Set Default Rate Parameters command
If Connection_Interval_Max x Subrate_Max x (Max_Latency + 1) is greater than or equal to Supervision_Timeout x 40, the Controller shall return the error code Invalid HCI Command Parameters (0x12).
With the current values 0x78 x 4 x 1 = 480 >= 0x0c x 40 = 480.
Fix this by using 2 s as the default Supervision_Timeout, which is 10x lower than the 20 s used for non-SCI connections while still well above the minimum required, and make sure it remains above the minimum in case interval_max is raised to match the controller's minimum supported connection interval.
--- net/bluetooth/hci_sync.c | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-)
net/bluetooth/hci_sync.c +27 -3
@@ -4834,6 +4834,9 @@ static int hci_le_set_def_rate_sync(struct hci_dev *hdev)struct hci_cp_le_set_def_rate cp;u16 interval_min =0x000a ;/* 1.25 ms */ u16 interval_max =0x0078 ;/* 15 ms */ +u16 subrate_max =0x0004 ; +u16 max_latency =0x0000 ; +u32 supv_timeout;if (!le_sci_capable (hdev))return 0 ;
@@ -4858,10 +4861,31 @@ static int hci_le_set_def_rate_sync(struct hci_dev *hdev) cp.interval_min =cpu_to_le16 (interval_min); cp.interval_max =cpu_to_le16 (interval_max); cp.subrate_min =cpu_to_le16 (0x0001 ); - cp.subrate_max =cpu_to_le16 (0x0004 ); - cp.max_latency =cpu_to_le16 (0x0000 ); + cp.subrate_max =cpu_to_le16 (subrate_max); + cp.max_latency =cpu_to_le16 (max_latency); cp.cont_num =cpu_to_le16 (0x0001 ); - cp.supv_timeout =cpu_to_le16 (0x000c );/* 120 ms */ + +/* HOGP v1.2 recommends a Supervision_Timeout greater than or equal to +* (1 + Max_Latency) x Subrate_Max x Connection_Interval_Max x 2, but +* the Core spec treats the equality as invalid: +* +* BLUETOOTH CORE SPECIFICATION Version 6.3 | Vol 4, Part E +* 7.8.158. LE Set Default Rate Parameters command +* +* If Connection_Interval_Max x Subrate_Max x (Max_Latency + 1) is +* greater than or equal to Supervision_Timeout x 40, the Controller +* shall return the error code Invalid HCI Command Parameters (0x12). +* +* So default to 2 s, 10x lower than the 20 s used for non-SCI +* connections while still well above the minimum required, but make +* sure it stays strictly above the minimum in case interval_max has +* been raised. +*/ + supv_timeout = (u32 )interval_max * subrate_max * (max_latency +1 ); + supv_timeout = supv_timeout /40 +1 ; + supv_timeout =clamp_t (u32,max_t (u32, supv_timeout,0x00c8 ), +0x000a ,0x0c80 ); + cp.supv_timeout =cpu_to_le16 (supv_timeout);/* The connection event length recommended in requests by a Peripheral * uses units of 125 us with a valid range of 0x0001 to 0x7CFF
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 188/1005 Bluetooth: hci_core: Initialize IRK before publication
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Binbin Deng <[email protected]>
[ Upstream commit f0cf5a24cefeb629876bd15d668ff062c8655e28 ]
hci_add_irk() initializes the identity address and address type of a newly allocated IRK, publishes it on hdev->identity_resolving_keys, and only then initializes its value and RPA. RCU readers such as hci_find_irk_by_rpa() and the debugfs identity_resolving_keys_show() can traverse the new entry during that window and see a zero or partially initialized IRK.
The race is reachable by racing an IRK addition with another CPU resolving or dumping IRKs. In particular, userspace can issue MGMT_OP_LOAD_IRKS while another process reads the corresponding debugfs file or triggers RPA resolution.
Initialize the IRK value and RPA before publishing a newly allocated IRK. Existing IRKs remain published and continue to be updated in place.
Found during a static-analysis-assisted audit: candidate sites were surfaced by a Coccinelle rule, and the reader/writer paths were confirmed by LLM-assisted (GLM-5.3) code inspection. The issue was not observed at runtime; it is identified by code inspection only.
--- net/bluetooth/hci_core.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
net/bluetooth/hci_core.c +6 -3
@@ -1315,9 +1315,10 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr,struct smp_irk *hci_add_irk (struct hci_dev *hdev,bdaddr_t *bdaddr,u8 addr_type,u8 val[16 ],bdaddr_t *rpa) { -struct smp_irk *irk; +struct smp_irk *irk, *old_irk; - irk =hci_find_irk_by_addr (hdev, bdaddr, addr_type); + old_irk =hci_find_irk_by_addr (hdev, bdaddr, addr_type); + irk = old_irk;if (!irk) { irk =kzalloc_obj (*irk);if (!irk)
@@ -1326,12 +1327,14 @@ struct smp_irk *hci_add_irk(struct hci_dev *hdev, bdaddr_t *bdaddr,bacpy (&irk->bdaddr, bdaddr); irk->addr_type = addr_type; -list_add_rcu (&irk->list, &hdev->identity_resolving_keys); }memcpy (irk->val, val,16 );bacpy (&irk->rpa, rpa); +if (!old_irk) +list_add_rcu (&irk->list, &hdev->identity_resolving_keys); +return irk; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 189/1005 Bluetooth: hci_core: Initialize link key before publication
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Binbin Deng <[email protected]>
[ Upstream commit ae9c8df1ffb84560ac01cbdc26cfb19027f4d25f ]
hci_add_link_key() allocates a new link key with kzalloc(), inserts it into hdev->link_keys with list_add_rcu(), and only then initializes its address, value, type, and PIN length. RCU readers such as hci_find_link_key() and the debugfs link_keys_show() do not take hci_dev_lock, so they can traverse the new entry during that initialization window and observe a zero or partially initialized key.
This can be triggered by racing a link-key update with another CPU looking up or dumping keys. In particular, userspace can issue MGMT_OP_LOAD_LINK_KEYS while another process reads the corresponding debugfs file.
Complete all fields of a newly allocated key before publishing it with list_add_rcu(). Existing keys remain visible and keep their current in-place update behavior.
Found during a static-analysis-assisted audit: candidate sites were surfaced by a Coccinelle rule, and the reader/writer paths were confirmed by LLM-assisted (GLM-5.3) code inspection. The issue was not observed at runtime; it is identified by code inspection only.
--- net/bluetooth/hci_core.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
net/bluetooth/hci_core.c +3 -1
@@ -1252,7 +1252,6 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, key =kzalloc_obj (*key);if (!key)return NULL ; -list_add_rcu (&key->list, &hdev->link_keys); }BT_DBG ("%s key for %pMR type %u" , hdev->name, bdaddr, type);
@@ -1276,6 +1275,9 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn,else key->type = type; +if (!old_key) +list_add_rcu (&key->list, &hdev->link_keys); +if (persistent) *persistent =hci_persistent_key (hdev, conn, type, old_key_type);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 190/1005 Bluetooth: hci_core: Initialize LTK before publication
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Binbin Deng <[email protected]>
[ Upstream commit 4335849380aa1081ee9a1c2b934cbdda0961fa57 ]
hci_add_ltk() publishes a newly allocated LTK on hdev->long_term_keys before initializing its address, type, value, authentication state, encryption size, EDIV, and random value. hci_find_ltk() and the debugfs long_term_keys_show() traverse this list under RCU and can therefore see a zero or partially initialized key before those stores complete.
The race is reachable by racing an LTK addition with another CPU looking up or dumping long-term keys. For example, userspace can issue MGMT_OP_LOAD_LONG_TERM_KEYS while another process reads the corresponding debugfs file.
Initialize all fields of a new LTK before list_add_rcu() makes it visible to RCU readers. Existing LTKs remain published and continue to be updated in place.
Found during a static-analysis-assisted audit: candidate sites were surfaced by a Coccinelle rule, and the reader/writer paths were confirmed by LLM-assisted (GLM-5.3) code inspection. The issue was not observed at runtime; it is identified by code inspection only.
--- net/bluetooth/hci_core.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
net/bluetooth/hci_core.c +3 -1
@@ -1299,7 +1299,6 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, key =kzalloc_obj (*key);if (!key)return NULL ; -list_add_rcu (&key->list, &hdev->long_term_keys); }bacpy (&key->bdaddr, bdaddr);
@@ -1311,6 +1310,9 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, key->enc_size = enc_size; key->type = type; +if (!old_key) +list_add_rcu (&key->list, &hdev->long_term_keys); +return key; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 191/1005 Bluetooth: hci_core: Fix queuing rx_work while workqueue is drained
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Akhil Arul <[email protected]>
[ Upstream commit 19b4e5701712f74d005cc66a36374559e8dfd281 ]
hci_recv_frame() drops a frame unless HCI_UP or HCI_INIT is set, but the check is not synchronized with hci_dev_close_sync(). A driver can pass the check, then close clears HCI_UP, flushes rx_work and starts drain_workqueue(), and the late queue_work() of rx_work hits the draining workqueue:
workqueue: cannot queue hci_rx_work on wq hci0
WARNING: kernel/workqueue.c:2352 at __queue_work+0x2c0/0x780 Call Trace: queue_work_on+0xb2/0xc0 hci_recv_frame+0x18f/0x330 vhci_write+0x174/0x240 vfs_write+0x271/0x680 ksys_write+0x7c/0x110
Skipping the queue_work() while HCI_CMD_DRAIN_WORKQUEUE is set, as done for tx_work, does not work for rx_work: the flag covers the whole close, and events still have to be received in that window, for the commands sent by hdev->shutdown() and for the reset done with HCI_QUIRK_RESET_ON_CLOSE.
Run hci_recv_frame() under rcu_read_lock() and wait with synchronize_rcu() once HCI_UP has been cleared, so that every caller which still saw HCI_UP has queued its work before the workqueue is drained, and later callers drop the frame.
HCI_INIT does not reopen that window. Apart from the HCI_QUIRK_RESET_ON_CLOSE reset, which runs after drain_workqueue() has returned, it is only set by hci_dev_init_sync() during open, and open and close are serialized by hci_req_sync_lock. So once the grace period has ended, nothing can pass the check and queue rx_work until the drain is over.
Tested in qemu with the syzbot C reproducer, one run per boot: the warning showed up on 12 of 30 boots before and on none of 42 boots after. Bringing a vhci controller up and down 50 times behaves the same with and without this change.
--- net/bluetooth/hci_core.c | 9 +++++++++ net/bluetooth/hci_sync.c | 5 +++++ 2 files changed, 14 insertions(+)
net/bluetooth/hci_core.c +9 -0
@@ -2904,8 +2904,14 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb) {u8 dev_pkt_type; +/* Pairs with synchronize_rcu() in hci_dev_close_sync(), so rx_work is +* not queued once the workqueue is being drained. +*/ +rcu_read_lock (); +if (!hdev || (!test_bit (HCI_UP , &hdev->flags) && !test_bit (HCI_INIT , &hdev->flags))) { +rcu_read_unlock ();kfree_skb (skb);return -ENXIO ; }
@@ -2939,6 +2945,7 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb)case HCI_DRV_PKT :break ;default : +rcu_read_unlock ();kfree_skb (skb);return -EINVAL ; }
@@ -2952,6 +2959,8 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb)skb_queue_tail (&hdev->rx_q, skb);queue_work (hdev->workqueue, &hdev->rx_work); +rcu_read_unlock (); +return 0 ; }EXPORT_SYMBOL (hci_recv_frame);
net/bluetooth/hci_sync.c +5 -0
@@ -5659,6 +5659,11 @@ int hci_dev_close_sync(struct hci_dev *hdev)return err; } +/* Wait for hci_recv_frame() callers that still saw HCI_UP, so that +* none of them queues rx_work while the workqueue is drained below. +*/ +synchronize_rcu (); +hci_leds_update_powered (hdev, false);/* Flush RX and TX works */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 192/1005 Bluetooth: btintel: fix buffer over-read in fw payload
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Catherine L <[email protected]>
[ Upstream commit f92b7bca985205082c86140d0bd7c86c5be00efc ]
The firmware decoder cast fw_ptr + frag_len to struct hci_command_hdr and read cmd->plen before confirming the header and payload still fit in the remaining firmware buffer.
Add explicit bounds checks before each dereference:
1. Reject if the command header is not fully contained in remain.
2. Reject if the full command including payload exceeds remain.
3. Log the offending fragment length and remaining size before returning -EINVAL.
--- drivers/bluetooth/btintel.c | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-)
drivers/bluetooth/btintel.c +23 -1
@@ -1150,7 +1150,29 @@ static int btintel_download_firmware_payload(struct hci_dev *hdev, err = -EINVAL ;while (fw_ptr - fw->data < fw->size) { -struct hci_command_hdr *cmd = (void *)(fw_ptr + frag_len); +struct hci_command_hdr *cmd; +size_t remain = fw->size - (fw_ptr - fw->data); + +/* Ensure the header fits before dereferencing */ +if (frag_len +sizeof (*cmd) > remain) { +bt_dev_err (hdev, +"Firmware buffer overrun at header (frag_len %u, need %zu, remain %zu)" , + frag_len, frag_len +sizeof (*cmd), remain); + err = -EINVAL ; + goto done; + } + + cmd = (void *)(fw_ptr + frag_len); + +/* Ensure the full command (header + payload) fits before use */ +if (frag_len +sizeof (*cmd) + cmd->plen > remain) { +bt_dev_err (hdev, +"Firmware buffer overrun at payload (frag_len %u, plen %u, need %zu, remain %zu)" , + frag_len, cmd->plen, + frag_len +sizeof (*cmd) + cmd->plen, remain); + err = -EINVAL ; + goto done; + } frag_len +=sizeof (*cmd) + cmd->plen;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 193/1005 Bluetooth: hci_event: Clear explicit connect state on LE connection
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kevin Dewald <[email protected]>
[ Upstream commit f5cd268af1c6f87fb3847e98274e22b8c6324aa4 ]
Since commit 6cd29ec6ae5e ("Bluetooth: hci_sync: Wait for proper events when connecting LE"), create_le_conn_complete() only runs once the LE Connection Complete event has been handled, and le_conn_complete_evt() has already removed the connection parameters from pend_le_conns by then. hci_connect_le_scan_cleanup() looks the parameters up in pend_le_conns, so after a successful connection it no longer clears explicit_connect, nor deletes the parameters that were only created for the explicit connect.
The parameters of every device connected through an explicit connect, such as an L2CAP or ATT connect or MGMT Pair Device, are thus left with explicit_connect set. MGMT Remove Device for all devices then keeps them as HCI_AUTO_CONN_EXPLICIT instead of freeing them, and if the device was set to auto-connect and is disconnected, they also stay onpend_le_conns: the kernel keeps scanning for the device and connects to it as soon as it advertises, although no one asked for it any more.
Do the cleanup in le_conn_complete_evt() instead, where the explicit connect request is fulfilled: clear explicit_connect, delete the parameters if they only existed for it, and put report parameters back on pend_le_reports. Auto-connect parameters are added back to pend_le_conns on disconnection, as before. Update the comment in hci_explicit_conn_params_set() that names hci_connect_le_scan_cleanup() as the only place deleting them.
--- net/bluetooth/hci_conn.c | 5 +++-- net/bluetooth/hci_event.c | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-)
net/bluetooth/hci_conn.c +3 -2
@@ -1586,8 +1586,9 @@ static int hci_explicit_conn_params_set(struct hci_dev *hdev,if (!params)return -ENOMEM ; -/* If we created new params, mark them to be deleted in -* hci_connect_le_scan_cleanup. It's different case than +/* If we created new params, mark them to be deleted once the +* explicit connect is done, see le_conn_complete_evt() and +* hci_connect_le_scan_cleanup(). It's different case than * existing disabled params, those will stay after cleanup. */ params->auto_connect =HCI_AUTO_CONN_EXPLICIT ;
net/bluetooth/hci_event.c +22 -0
@@ -5956,6 +5956,28 @@ static void le_conn_complete_evt(struct hci_dev *hdev, u8 status,hci_conn_put (params->conn); params->conn =NULL ; } + +/* An explicit connect request is complete once connected, so +* clean it up here: hci_connect_le_scan_cleanup() no longer +* finds the params since they have just been removed from +* pend_le_conns. +*/ +if (params->explicit_connect) { + params->explicit_connect = false; + +switch (params->auto_connect) { +case HCI_AUTO_CONN_EXPLICIT : +hci_conn_params_del (hdev, &conn->dst, + conn->dst_type); +break ; +case HCI_AUTO_CONN_REPORT : +hci_pend_le_list_add (params, + &hdev->pend_le_reports); +break ; +default : +break ; + } + } }/* If we are central and have subrate parameters stored, queue a
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 194/1005 Bluetooth: use assign_bit() where applicable
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Peng Fan <[email protected]>
[ Upstream commit c4154fc34772134b0dbd14ab0134ba10b90c52cc ]
Convert open-coded if/else with set_bit/clear_bit the assign_bit API.
Done with Coccinelle semantic patch:
// set_bit -> clear_bit => assign_bit
@@
expression cond, bit, addr;
@@
-if (cond)
- set_bit(bit, addr);
-else
- clear_bit(bit, addr);
+assign_bit(bit, addr, cond);
@@
expression cond, bit, addr;
@@
-if (cond)
- clear_bit(bit, addr);
-else
- set_bit(bit, addr);
+assign_bit(bit, addr, !cond);Stable-dep-of: 5d005ded2cb1 ("Bluetooth: L2CAP: Hold incoming data until encryption key size is known")
--- net/bluetooth/hci_event.c | 31 +++++++------------------------ net/bluetooth/iso.c | 15 +++------------ net/bluetooth/l2cap_sock.c | 22 ++++++---------------- net/bluetooth/rfcomm/core.c | 6 ++---- net/bluetooth/rfcomm/sock.c | 5 +---- net/bluetooth/sco.c | 10 ++-------- 6 files changed, 21 insertions(+), 68 deletions(-)
net/bluetooth/hci_event.c +7 -24
@@ -404,10 +404,7 @@ static u8 hci_cc_write_auth_enable(struct hci_dev *hdev, void *data,if (!rp->status) {__u8 param = *((__u8 *) sent); -if (param ==AUTH_ENABLED ) -set_bit (HCI_AUTH , &hdev->flags); -else -clear_bit (HCI_AUTH , &hdev->flags); +assign_bit (HCI_AUTH , &hdev->flags, param ==AUTH_ENABLED ); }if (hci_dev_test_flag (hdev,HCI_MGMT ))
@@ -436,10 +433,7 @@ static u8 hci_cc_write_encrypt_mode(struct hci_dev *hdev, void *data, param = *((__u8 *) sent); -if (param) -set_bit (HCI_ENCRYPT , &hdev->flags); -else -clear_bit (HCI_ENCRYPT , &hdev->flags); +assign_bit (HCI_ENCRYPT , &hdev->flags, param);return rp->status; }
@@ -466,15 +460,9 @@ static u8 hci_cc_write_scan_enable(struct hci_dev *hdev, void *data, goto done; } -if (param &SCAN_INQUIRY ) -set_bit (HCI_ISCAN , &hdev->flags); -else -clear_bit (HCI_ISCAN , &hdev->flags); +assign_bit (HCI_ISCAN , &hdev->flags, param &SCAN_INQUIRY ); -if (param &SCAN_PAGE ) -set_bit (HCI_PSCAN , &hdev->flags); -else -clear_bit (HCI_PSCAN , &hdev->flags); +assign_bit (HCI_PSCAN , &hdev->flags, param &SCAN_PAGE ); done:hci_dev_unlock (hdev);
@@ -4661,10 +4649,8 @@ static void hci_mode_change_evt(struct hci_dev *hdev, void *data,if (!test_and_clear_bit (HCI_CONN_MODE_CHANGE_PEND , &conn->flags)) { -if (conn->mode ==HCI_CM_ACTIVE ) -set_bit (HCI_CONN_POWER_SAVE , &conn->flags); -else -clear_bit (HCI_CONN_POWER_SAVE , &conn->flags); +assign_bit (HCI_CONN_POWER_SAVE , &conn->flags, + conn->mode ==HCI_CM_ACTIVE ); }if (test_and_clear_bit (HCI_CONN_SCO_SETUP_PEND , &conn->flags))
@@ -4864,10 +4850,7 @@ static void hci_link_key_notify_evt(struct hci_dev *hdev, void *data, goto unlock; } -if (persistent) -clear_bit (HCI_CONN_FLUSH_KEY , &conn->flags); -else -set_bit (HCI_CONN_FLUSH_KEY , &conn->flags); +assign_bit (HCI_CONN_FLUSH_KEY , &conn->flags, !persistent); unlock:hci_dev_unlock (hdev);
net/bluetooth/iso.c +3 -12
@@ -1977,10 +1977,7 @@ static int iso_sock_setsockopt(struct socket *sock, int level, int optname,if (err)break ; -if (opt) -set_bit (BT_SK_DEFER_SETUP , &bt_sk (sk)->flags); -else -clear_bit (BT_SK_DEFER_SETUP , &bt_sk (sk)->flags); +assign_bit (BT_SK_DEFER_SETUP , &bt_sk (sk)->flags, opt);break ;case BT_PKT_STATUS :
@@ -1988,10 +1985,7 @@ static int iso_sock_setsockopt(struct socket *sock, int level, int optname,if (err)break ; -if (opt) -set_bit (BT_SK_PKT_STATUS , &bt_sk (sk)->flags); -else -clear_bit (BT_SK_PKT_STATUS , &bt_sk (sk)->flags); +assign_bit (BT_SK_PKT_STATUS , &bt_sk (sk)->flags, opt);break ;case BT_PKT_SEQNUM :
@@ -1999,10 +1993,7 @@ static int iso_sock_setsockopt(struct socket *sock, int level, int optname,if (err)break ; -if (opt) -set_bit (BT_SK_PKT_SEQNUM , &bt_sk (sk)->flags); -else -clear_bit (BT_SK_PKT_SEQNUM , &bt_sk (sk)->flags); +assign_bit (BT_SK_PKT_SEQNUM , &bt_sk (sk)->flags, opt);break ;case BT_ISO_QOS :
net/bluetooth/l2cap_sock.c +6 -16
@@ -871,15 +871,11 @@ static int l2cap_sock_setsockopt_old(struct socket *sock, int optname,if (opt &L2CAP_LM_SECURE ) chan->sec_level =BT_SECURITY_HIGH ; -if (opt &L2CAP_LM_MASTER ) -set_bit (FLAG_ROLE_SWITCH , &chan->flags); -else -clear_bit (FLAG_ROLE_SWITCH , &chan->flags); +assign_bit (FLAG_ROLE_SWITCH , &chan->flags, + opt &L2CAP_LM_MASTER ); -if (opt &L2CAP_LM_RELIABLE ) -set_bit (FLAG_FORCE_RELIABLE , &chan->flags); -else -clear_bit (FLAG_FORCE_RELIABLE , &chan->flags); +assign_bit (FLAG_FORCE_RELIABLE , &chan->flags, + opt &L2CAP_LM_RELIABLE );break ;default :
@@ -1046,10 +1042,7 @@ static int l2cap_sock_setsockopt(struct socket *sock, int level, int optname, } } -if (opt) -set_bit (FLAG_FLUSHABLE , &chan->flags); -else -clear_bit (FLAG_FLUSHABLE , &chan->flags); +assign_bit (FLAG_FLUSHABLE , &chan->flags, opt);break ;case BT_POWER :
@@ -1065,10 +1058,7 @@ static int l2cap_sock_setsockopt(struct socket *sock, int level, int optname,if (err)break ; -if (pwr.force_active) -set_bit (FLAG_FORCE_ACTIVE , &chan->flags); -else -clear_bit (FLAG_FORCE_ACTIVE , &chan->flags); +assign_bit (FLAG_FORCE_ACTIVE , &chan->flags, pwr.force_active);break ;case BT_CHANNEL_POLICY :
net/bluetooth/rfcomm/core.c +2 -4
@@ -1740,10 +1740,8 @@ static int rfcomm_recv_msc(struct rfcomm_session *s, int cr, struct sk_buff *skbreturn 0 ;if (cr) { -if (msc->v24_sig &RFCOMM_V24_FC && !d->cfc) -set_bit (RFCOMM_TX_THROTTLED , &d->flags); -else -clear_bit (RFCOMM_TX_THROTTLED , &d->flags); +assign_bit (RFCOMM_TX_THROTTLED , &d->flags, + msc->v24_sig &RFCOMM_V24_FC && !d->cfc);rfcomm_dlc_lock (d);
net/bluetooth/rfcomm/sock.c +1 -4
@@ -724,10 +724,7 @@ static int rfcomm_sock_setsockopt(struct socket *sock, int level, int optname,if (err)break ; -if (opt) -set_bit (BT_SK_DEFER_SETUP , &bt_sk (sk)->flags); -else -clear_bit (BT_SK_DEFER_SETUP , &bt_sk (sk)->flags); +assign_bit (BT_SK_DEFER_SETUP , &bt_sk (sk)->flags, opt);break ;
net/bluetooth/sco.c +2 -8
@@ -1037,10 +1037,7 @@ static int sco_sock_setsockopt(struct socket *sock, int level, int optname,if (err)break ; -if (opt) -set_bit (BT_SK_DEFER_SETUP , &bt_sk (sk)->flags); -else -clear_bit (BT_SK_DEFER_SETUP , &bt_sk (sk)->flags); +assign_bit (BT_SK_DEFER_SETUP , &bt_sk (sk)->flags, opt);break ;case BT_VOICE :
@@ -1080,10 +1077,7 @@ static int sco_sock_setsockopt(struct socket *sock, int level, int optname,if (err)break ; -if (opt) -set_bit (BT_SK_PKT_STATUS , &bt_sk (sk)->flags); -else -clear_bit (BT_SK_PKT_STATUS , &bt_sk (sk)->flags); +assign_bit (BT_SK_PKT_STATUS , &bt_sk (sk)->flags, opt);break ;case BT_CODEC :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 195/1005 Bluetooth: MGMT: Add management security level changed event
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Frédéric Danis <[email protected]>
[ Upstream commit 1b723bd2945df4c75d7a4a4525660704ef8f4df8 ]
Add an event on device security level or encryption type change to let user space know which level is currently in use. Reset security level to 0 on disconnection so further connections will correctly report security level changes.
This will be used for BlueZ qualification automation.
Stable-dep-of: 5d005ded2cb1 ("Bluetooth: L2CAP: Hold incoming data until encryption key size is known")
--- include/net/bluetooth/hci_core.h | 18 +++-- include/net/bluetooth/mgmt.h | 14 ++++ net/bluetooth/hci_conn.c | 28 ++++++++ net/bluetooth/hci_event.c | 118 +++++++++++++++++++++++++++++-- net/bluetooth/mgmt.c | 66 ++++++++++++++++- 5 files changed, 232 insertions(+), 12 deletions(-)
include/net/bluetooth/hci_core.h +14 -4
@@ -2208,6 +2208,8 @@ static inline void hci_auth_cfm(struct hci_conn *conn, __u8 status) conn->security_cfm_cb (conn, status); } +void mgmt_security_level_changed (struct hci_conn *conn); +static inline void hci_encrypt_cfm (struct hci_conn *conn,__u8 status) {struct hci_cb *cb;
@@ -2230,11 +2232,19 @@ static inline void hci_encrypt_cfm(struct hci_conn *conn, __u8 status) encrypt =0x01 ;if (!status) { -if (conn->sec_level ==BT_SECURITY_SDP ) +/* Callers either set conn->sec_level = conn->pending_sec_level +* unconditionally before calling this function, or never +* reach here with status == 0 (e.g. conn->state == BT_CONFIG +* returns early above, or status is actually an error). So +* conn->pending_sec_level is never greater than +* conn->sec_level at this point; only the initial +* BT_SECURITY_SDP -> BT_SECURITY_LOW bump can still happen +* here. +*/ +if (conn->sec_level ==BT_SECURITY_SDP ) { conn->sec_level =BT_SECURITY_LOW ; - -if (conn->pending_sec_level > conn->sec_level) - conn->sec_level = conn->pending_sec_level; +mgmt_security_level_changed (conn); + } }mutex_lock (&hci_cb_list_lock);
include/net/bluetooth/mgmt.h +14 -0
@@ -1221,3 +1221,17 @@ struct mgmt_ev_conn_subrate {__le16 cont_num;__le16 supv_timeout; } __packed; + +#define MGMT_CONN_SEC_ENCRYPT_NONE 0x00 +#define MGMT_CONN_SEC_ENCRYPT_E0 0x01 +#define MGMT_CONN_SEC_ENCRYPT_AES_CCM 0x02 + +#define MGMT_SEC_LEVEL_CHANGED_PARAM_LEVEL 0x0000 +#define MGMT_SEC_LEVEL_CHANGED_PARAM_ENC_TYPE 0x0001 + +#define MGMT_EV_SECURITY_LEVEL_CHANGED 0x0034 +struct mgmt_ev_security_level_changed { +struct mgmt_addr_info addr; +__u8 tlv_length; + __u8 tlv_data[] __counted_by(tlv_length); +} __packed;
net/bluetooth/hci_conn.c +28 -0
@@ -1233,6 +1233,29 @@ static void hci_conn_unlink(struct hci_conn *conn)if (!conn->parent) {struct hci_link *link, *t; + conn->sec_level =BT_SECURITY_SDP ; +clear_bit (HCI_CONN_ENCRYPT , &conn->flags); +clear_bit (HCI_CONN_AES_CCM , &conn->flags); +/* mgmt_security_level_changed() reports the reset only if +* this connection was actually reported to userspace as +* connected (it checks HCI_CONN_MGMT_CONNECTED itself), so it +* must be called before the flag is cleared below. +* Callers that already know whether the connection was +* mgmt-connected (e.g. disconnect event handlers) only peek +* at the flag, so it is still set here; this is the place +* actually clearing it. +* +* Skip the report if hdev is down: this means +* hci_dev_close_sync()/hci_conn_hash_flush() is in progress +* and no MGMT_EV_DEVICE_DISCONNECTED was ever sent for this +* connection, so sending a security level reset here would +* be a spurious, order-less event; the adapter-wide powered +* off notification is enough for userspace to reset state. +*/ +if (test_bit (HCI_UP , &hdev->flags)) +mgmt_security_level_changed (conn); +clear_bit (HCI_CONN_MGMT_CONNECTED , &conn->flags); +list_for_each_entry_safe (link, t, &conn->link_list, list) {struct hci_conn *child = link->conn;
@@ -1543,6 +1566,11 @@ struct hci_conn *hci_connect_le(struct hci_dev *hdev, bdaddr_t *dst, conn->pending_sec_level = sec_level; } +/* Do not report the security level here: conn->dst may still hold +* the peer's RPA instead of its identity address, and the connection +* is not established yet. le_conn_complete_evt() reports it once the +* connection completes and the identity address has been resolved. +*/ conn->sec_level =BT_SECURITY_LOW ; conn->conn_timeout = conn_timeout; conn->le_adv_phy = phy;
net/bluetooth/hci_event.c +111 -7
197 lines not on this page · raw message
net/bluetooth/mgmt.c +65 -1
90 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 196/1005 Bluetooth: hci_core: Convert hci_conn flags to a bitmap
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Luiz Augusto von Dentz <[email protected]>
[ Upstream commit 1eebde8ecede18e351ccf438f17b53d3b62a75a9 ]
struct hci_conn stores its flags in a single unsigned long, but the HCI_CONN_* enum already has 33 entries (up to HCI_CONN_PA_SYNC_FAILED = 32), so on 32-bit architectures set_bit()/test_bit() on the highest flags access memory past the flags field, aliasing the adjacent conn_reason field.
Fix this by declaring flags with DECLARE_BITMAP() sized by a new __HCI_CONN_NUM_FLAGS terminator so it can accommodate any number of flags.
Stable-dep-of: 5d005ded2cb1 ("Bluetooth: L2CAP: Hold incoming data until encryption key size is known")
--- include/net/bluetooth/hci_core.h | 101 ++++++++++---------- net/bluetooth/hci_conn.c | 87 +++++++++--------- net/bluetooth/hci_event.c | 152 +++++++++++++++---------------- net/bluetooth/hci_sync.c | 36 ++++---- net/bluetooth/iso.c | 20 ++-- net/bluetooth/l2cap_core.c | 2 +- net/bluetooth/mgmt.c | 20 ++-- net/bluetooth/smp.c | 24 ++--- 8 files changed, 221 insertions(+), 221 deletions(-)
include/net/bluetooth/hci_core.h +51 -50
@@ -677,6 +677,44 @@ enum conn_reasons { CONN_REASON_ISO_CONNECT, }; +enum { +HCI_CONN_AUTH_PEND , +HCI_CONN_ENCRYPT_PEND , +HCI_CONN_RSWITCH_PEND , +HCI_CONN_MODE_CHANGE_PEND , +HCI_CONN_SCO_SETUP_PEND , +HCI_CONN_MGMT_CONNECTED , +HCI_CONN_SSP_ENABLED , +HCI_CONN_SC_ENABLED , +HCI_CONN_AES_CCM , +HCI_CONN_POWER_SAVE , +HCI_CONN_FLUSH_KEY , +HCI_CONN_ENCRYPT , +HCI_CONN_AUTH , +HCI_CONN_SECURE , +HCI_CONN_FIPS , +HCI_CONN_STK_ENCRYPT , +HCI_CONN_AUTH_INITIATOR , +HCI_CONN_DROP , +HCI_CONN_CANCEL , +HCI_CONN_PARAM_REMOVAL_PEND , +HCI_CONN_NEW_LINK_KEY , +HCI_CONN_SCANNING , +HCI_CONN_AUTH_FAILURE , +HCI_CONN_PER_ADV , +HCI_CONN_BIG_CREATED , +HCI_CONN_CREATE , +HCI_CONN_CREATE_CIS , +HCI_CONN_CREATE_BIG_SYNC , +HCI_CONN_BIG_SYNC , +HCI_CONN_BIG_SYNC_FAILED , +HCI_CONN_CREATE_PA_SYNC , +HCI_CONN_PA_SYNC , +HCI_CONN_PA_SYNC_FAILED , + + __HCI_CONN_NUM_FLAGS, +}; +struct hci_conn {struct list_head list;
@@ -747,7 +785,7 @@ struct hci_conn {__u8 num_bis;__u8 bis[HCI_MAX_ISO_BIS ]; -unsigned long flags; +DECLARE_BITMAP (flags, __HCI_CONN_NUM_FLAGS);enum conn_reasons conn_reason;__u8 abort_reason;
@@ -977,55 +1015,18 @@ u32 hci_inquiry_cache_update(struct hci_dev *hdev, struct inquiry_data *data, bool name_known);void hci_inquiry_cache_flush (struct hci_dev *hdev); -/* ----- HCI Connections ----- */ -enum { -HCI_CONN_AUTH_PEND , -HCI_CONN_ENCRYPT_PEND , -HCI_CONN_RSWITCH_PEND , -HCI_CONN_MODE_CHANGE_PEND , -HCI_CONN_SCO_SETUP_PEND , -HCI_CONN_MGMT_CONNECTED , -HCI_CONN_SSP_ENABLED , -HCI_CONN_SC_ENABLED , -HCI_CONN_AES_CCM , -HCI_CONN_POWER_SAVE , -HCI_CONN_FLUSH_KEY , -HCI_CONN_ENCRYPT , -HCI_CONN_AUTH , -HCI_CONN_SECURE , -HCI_CONN_FIPS , -HCI_CONN_STK_ENCRYPT , -HCI_CONN_AUTH_INITIATOR , -HCI_CONN_DROP , -HCI_CONN_CANCEL , -HCI_CONN_PARAM_REMOVAL_PEND , -HCI_CONN_NEW_LINK_KEY , -HCI_CONN_SCANNING , -HCI_CONN_AUTH_FAILURE , -HCI_CONN_PER_ADV , -HCI_CONN_BIG_CREATED , -HCI_CONN_CREATE , -HCI_CONN_CREATE_CIS , -HCI_CONN_CREATE_BIG_SYNC , -HCI_CONN_BIG_SYNC , -HCI_CONN_BIG_SYNC_FAILED , -HCI_CONN_CREATE_PA_SYNC , -HCI_CONN_PA_SYNC , -HCI_CONN_PA_SYNC_FAILED , -}; -static inline bool hci_conn_ssp_enabled (struct hci_conn *conn) {struct hci_dev *hdev = conn->hdev;return hci_dev_test_flag (hdev,HCI_SSP_ENABLED ) && -test_bit (HCI_CONN_SSP_ENABLED , &conn->flags); +test_bit (HCI_CONN_SSP_ENABLED , conn->flags); }static inline bool hci_conn_sc_enabled (struct hci_conn *conn) {struct hci_dev *hdev = conn->hdev;return hci_dev_test_flag (hdev,HCI_SC_ENABLED ) && -test_bit (HCI_CONN_SC_ENABLED , &conn->flags); +test_bit (HCI_CONN_SC_ENABLED , conn->flags); }static inline void hci_conn_hash_add (struct hci_dev *hdev,struct hci_conn *c)
@@ -1198,7 +1199,7 @@ hci_conn_hash_lookup_create_pa_sync(struct hci_dev *hdev)if (c->type !=PA_LINK )continue ; -if (!test_bit (HCI_CONN_CREATE_PA_SYNC , &c->flags)) +if (!test_bit (HCI_CONN_CREATE_PA_SYNC , c->flags))continue ;rcu_read_unlock ();
@@ -1222,7 +1223,7 @@ hci_conn_hash_lookup_per_adv_bis(struct hci_dev *hdev,list_for_each_entry_rcu (c, &h->list, list) {if (bacmp (&c->dst, ba) || c->type !=BIS_LINK || - !test_bit (HCI_CONN_PER_ADV , &c->flags)) + !test_bit (HCI_CONN_PER_ADV , c->flags))continue ; if (c->iso_qos.bcast.big == big &&
@@ -1459,7 +1460,7 @@ hci_conn_hash_lookup_pa_sync_big_handle(struct hci_dev *hdev, __u8 big)list_for_each_entry_rcu (c, &h->list, list) {if (c->type !=BIS_LINK || - !test_bit (HCI_CONN_PA_SYNC , &c->flags)) + !test_bit (HCI_CONN_PA_SYNC , c->flags))continue ;if (c->iso_qos.bcast.big == big) {
@@ -1535,7 +1536,7 @@ static inline void hci_conn_hash_list_flag(struct hci_dev *hdev,rcu_read_lock ();list_for_each_entry_rcu (c, &h->list, list) { -if (c->type == type &&test_bit (flag, &c->flags)) +if (c->type == type &&test_bit (flag, c->flags))func (c, data); }
@@ -1551,7 +1552,7 @@ static inline struct hci_conn *hci_lookup_le_connect(struct hci_dev *hdev)list_for_each_entry_rcu (c, &h->list, list) {if (c->type ==LE_LINK && c->state ==BT_CONNECT && - !test_bit (HCI_CONN_SCANNING , &c->flags)) { + !test_bit (HCI_CONN_SCANNING , c->flags)) {rcu_read_unlock ();return c; }
@@ -1572,7 +1573,7 @@ static inline bool hci_is_le_conn_scanning(struct hci_dev *hdev)list_for_each_entry_rcu (c, &h->list, list) {if (c->type ==LE_LINK && c->state ==BT_CONNECT && -test_bit (HCI_CONN_SCANNING , &c->flags)) { +test_bit (HCI_CONN_SCANNING , c->flags)) {rcu_read_unlock ();return true; }
@@ -2192,10 +2193,10 @@ static inline void hci_auth_cfm(struct hci_conn *conn, __u8 status)struct hci_cb *cb;__u8 encrypt; -if (test_bit (HCI_CONN_ENCRYPT_PEND , &conn->flags)) +if (test_bit (HCI_CONN_ENCRYPT_PEND , conn->flags))return ; - encrypt =test_bit (HCI_CONN_ENCRYPT , &conn->flags) ?0x01 :0x00 ; + encrypt =test_bit (HCI_CONN_ENCRYPT , conn->flags) ?0x01 :0x00 ;mutex_lock (&hci_cb_list_lock);list_for_each_entry (cb, &hci_cb_list, list) {
@@ -2224,9 +2225,9 @@ static inline void hci_encrypt_cfm(struct hci_conn *conn, __u8 status)return ; } -if (!test_bit (HCI_CONN_ENCRYPT , &conn->flags)) +if (!test_bit (HCI_CONN_ENCRYPT , conn->flags)) encrypt =0x00 ; -else if (test_bit (HCI_CONN_AES_CCM , &conn->flags)) +else if (test_bit (HCI_CONN_AES_CCM , conn->flags)) encrypt =0x02 ;else encrypt =0x01 ;
net/bluetooth/hci_conn.c +43 -44
289 lines not on this page · raw message
net/bluetooth/hci_event.c +76 -76
501 lines not on this page · raw message
net/bluetooth/hci_sync.c +18 -18
@@ -5958,11 +5958,11 @@ static int hci_le_connect_cancel_sync(struct hci_dev *hdev,/* Return reason if scanning since the connection shall probably be * cleanup directly. */ -if (test_bit (HCI_CONN_SCANNING , &conn->flags)) +if (test_bit (HCI_CONN_SCANNING , conn->flags))return reason;if (conn->role ==HCI_ROLE_SLAVE || -test_and_set_bit (HCI_CONN_CANCEL , &conn->flags)) +test_and_set_bit (HCI_CONN_CANCEL , conn->flags))return 0 ; return __hci_cmd_sync_status(hdev, HCI_OP_LE_CREATE_CONN_CANCEL,
@@ -5984,7 +5984,7 @@ static int hci_connect_cancel_sync(struct hci_dev *hdev, struct hci_conn *conn,* then an HCI_LE_CIS_Established event shall also be sent for * this CIS with the Status Operation Cancelled by Host (0x44). */ -if (test_bit (HCI_CONN_CREATE_CIS , &conn->flags)) +if (test_bit (HCI_CONN_CREATE_CIS , conn->flags))return hci_disconnect_sync (hdev, conn, reason);/* CIS with no Create CIS sent have nothing to cancel */
@@ -6982,7 +6982,7 @@ static int hci_le_create_conn_sync(struct hci_dev *hdev, void *data)bt_dev_dbg (hdev,"conn %p" , conn); -clear_bit (HCI_CONN_SCANNING , &conn->flags); +clear_bit (HCI_CONN_SCANNING , conn->flags); conn->state =BT_CONNECT ;/* If requested to connect as peripheral use directed advertising */
@@ -7049,7 +7049,7 @@ static int hci_le_create_conn_sync(struct hci_dev *hdev, void *data)/* Mark create connection in flight so hci_cancel_connect_sync() can * cancel it while blocking on the connection complete event. */ -set_bit (HCI_CONN_CREATE , &conn->flags); +set_bit (HCI_CONN_CREATE , conn->flags);/* Send command LE Extended Create Connection if supported */ if (use_ext_conn (hdev)) {
@@ -7086,7 +7086,7 @@ static int hci_le_create_conn_sync(struct hci_dev *hdev, void *data) conn->conn_timeout, NULL); done: -clear_bit (HCI_CONN_CREATE , &conn->flags); +clear_bit (HCI_CONN_CREATE , conn->flags);if (err == -ETIMEDOUT )hci_le_connect_cancel_sync (hdev, conn,0x00 );
@@ -7133,7 +7133,7 @@ int hci_le_create_cis_sync(struct hci_dev *hdev)/* Wait until previous Create CIS has completed */ list_for_each_entry_rcu (conn, &hdev->conn_hash.list, list) { -if (test_bit (HCI_CONN_CREATE_CIS , &conn->flags)) +if (test_bit (HCI_CONN_CREATE_CIS , conn->flags)) goto done; }
@@ -7169,7 +7169,7 @@ int hci_le_create_cis_sync(struct hci_dev *hdev) conn->iso_qos.ucast.cig != cig)continue ; -set_bit (HCI_CONN_CREATE_CIS , &conn->flags); +set_bit (HCI_CONN_CREATE_CIS , conn->flags); cis->acl_handle =cpu_to_le16 (conn->parent->handle); cis->cis_handle =cpu_to_le16 (conn->handle); timeout = conn->conn_timeout;
@@ -7372,14 +7372,14 @@ static int hci_acl_create_conn_sync(struct hci_dev *hdev, void *data)/* Mark create connection in flight so hci_cancel_connect_sync() can * cancel it while blocking on the connection complete event. */ -set_bit (HCI_CONN_CREATE , &conn->flags); +set_bit (HCI_CONN_CREATE , conn->flags); err =__hci_cmd_sync_status_sk (hdev,HCI_OP_CREATE_CONN ,sizeof (cp), &cp,HCI_EV_CONN_COMPLETE , conn->conn_timeout,NULL ); -clear_bit (HCI_CONN_CREATE , &conn->flags); +clear_bit (HCI_CONN_CREATE , conn->flags);return err; }
@@ -7468,7 +7468,7 @@ static int hci_acl_cancel_create_conn_sync(struct hci_dev *hdev,mutex_lock (&hdev->cmd_sync_work_lock);/* In flight: this connection owns the pending request, cancel it. */ -if (test_bit (HCI_CONN_CREATE , &conn->flags)) { +if (test_bit (HCI_CONN_CREATE , conn->flags)) {hci_cmd_sync_cancel (hdev,ECANCELED ); goto unlock; }
@@ -7499,7 +7499,7 @@ static int hci_le_cancel_create_conn_sync(struct hci_dev *hdev,*/ mutex_lock (&hdev->cmd_sync_work_lock); -if (test_bit (HCI_CONN_CREATE , &conn->flags)) { +if (test_bit (HCI_CONN_CREATE , conn->flags)) {hci_cmd_sync_cancel (hdev,ECANCELED ); goto unlock; }
@@ -7526,7 +7526,7 @@ static int hci_cis_cancel_create_conn_sync(struct hci_dev *hdev,*/ mutex_lock (&hdev->cmd_sync_work_lock); -if (test_bit (HCI_CONN_CREATE_CIS , &conn->flags)) +if (test_bit (HCI_CONN_CREATE_CIS , conn->flags))hci_cmd_sync_cancel (hdev,ECANCELED );mutex_unlock (&hdev->cmd_sync_work_lock);
@@ -7663,7 +7663,7 @@ static void create_pa_complete(struct hci_dev *hdev, void *data, int err)hci_dev_lock (hdev);if (hci_conn_valid (hdev, conn)) -clear_bit (HCI_CONN_CREATE_PA_SYNC , &conn->flags); +clear_bit (HCI_CONN_CREATE_PA_SYNC , conn->flags);if (!err) goto unlock;
@@ -7675,7 +7675,7 @@ static void create_pa_complete(struct hci_dev *hdev, void *data, int err)if (IS_ERR (pa_sync)) goto unlock; -set_bit (HCI_CONN_PA_SYNC_FAILED , &pa_sync->flags); +set_bit (HCI_CONN_PA_SYNC_FAILED , pa_sync->flags);/* Notify iso layer */ hci_connect_cfm (pa_sync,bt_status (err));
@@ -7748,7 +7748,7 @@ static int hci_le_pa_create_sync(struct hci_dev *hdev, void *data)* program the address in the allow list so PA advertisements can be * received. */ -set_bit (HCI_CONN_CREATE_PA_SYNC , &conn->flags); +set_bit (HCI_CONN_CREATE_PA_SYNC , conn->flags);hci_update_passive_scan_sync (hdev);
@@ -7851,7 +7851,7 @@ static void create_big_complete(struct hci_dev *hdev, void *data, int err)if (err == -ECANCELED ) goto done; -clear_bit (HCI_CONN_CREATE_BIG_SYNC , &conn->flags); +clear_bit (HCI_CONN_CREATE_BIG_SYNC , conn->flags); done:hci_conn_put (conn);
@@ -7868,7 +7868,7 @@ static int hci_le_big_create_sync(struct hci_dev *hdev, void *data)if (!hci_conn_valid (hdev, conn))return -ECANCELED ; -set_bit (HCI_CONN_CREATE_BIG_SYNC , &conn->flags); +set_bit (HCI_CONN_CREATE_BIG_SYNC , conn->flags);memset (cp,0 ,sizeof (*cp)); cp->handle = qos->bcast.big;
net/bluetooth/iso.c +10 -10
@@ -912,7 +912,7 @@ static void iso_sock_disconn(struct sock *sk)struct sock *bis_sk;struct hci_conn *hcon =iso_pi (sk)->conn->hcon; -if (test_bit (HCI_CONN_BIG_CREATED , &hcon->flags)) { +if (test_bit (HCI_CONN_BIG_CREATED , hcon->flags)) { bis_sk =iso_get_sock_big (sk, &iso_pi (sk)->src, &iso_pi (sk)->dst,iso_pi (sk)->qos.bcast.big);
@@ -957,8 +957,8 @@ static void __iso_sock_close(struct sock *sk)case BT_CONNECT2 :if (iso_pi (sk)->conn->hcon && - (test_bit (HCI_CONN_PA_SYNC , &iso_pi (sk)->conn->hcon->flags) || -test_bit (HCI_CONN_PA_SYNC_FAILED , &iso_pi (sk)->conn->hcon->flags))) + (test_bit (HCI_CONN_PA_SYNC ,iso_pi (sk)->conn->hcon->flags) || +test_bit (HCI_CONN_PA_SYNC_FAILED ,iso_pi (sk)->conn->hcon->flags)))iso_sock_disconn (sk);else iso_chan_del (sk,ECONNRESET );
@@ -2289,7 +2289,7 @@ static void iso_conn_ready(struct iso_conn *conn) hdev = hcon->hdev; -if (test_bit (HCI_CONN_BIG_SYNC , &hcon->flags)) { +if (test_bit (HCI_CONN_BIG_SYNC , hcon->flags)) {/* A BIS slave hcon is notified to the ISO layer * after the Command Complete for the LE Setup * ISO Data Path command is received. Get the
@@ -2298,7 +2298,7 @@ static void iso_conn_ready(struct iso_conn *conn) parent =iso_get_sock (hdev, &hcon->src, &hcon->dst,BT_LISTEN , iso_match_big_hcon, hcon); - }else if (test_bit (HCI_CONN_BIG_SYNC_FAILED , &hcon->flags)) { + }else if (test_bit (HCI_CONN_BIG_SYNC_FAILED , hcon->flags)) { ev =hci_recv_event_data (hcon->hdev,HCI_EVT_LE_BIG_SYNC_ESTABLISHED );
@@ -2312,7 +2312,7 @@ static void iso_conn_ready(struct iso_conn *conn) &hcon->dst,BT_LISTEN , iso_match_big, ev); - }else if (test_bit (HCI_CONN_PA_SYNC_FAILED , &hcon->flags)) { + }else if (test_bit (HCI_CONN_PA_SYNC_FAILED , hcon->flags)) { ev2 =hci_recv_event_data (hcon->hdev,HCI_EV_LE_PA_SYNC_ESTABLISHED );if (ev2)
@@ -2320,7 +2320,7 @@ static void iso_conn_ready(struct iso_conn *conn) &hcon->dst,BT_LISTEN , iso_match_sid, ev2); - }else if (test_bit (HCI_CONN_PA_SYNC , &hcon->flags)) { + }else if (test_bit (HCI_CONN_PA_SYNC , hcon->flags)) { ev3 =hci_recv_event_data (hcon->hdev,HCI_EV_LE_PER_ADV_REPORT );if (ev3)
@@ -2376,7 +2376,7 @@ static void iso_conn_ready(struct iso_conn *conn) hcon->dst_type =le_addr_type (iso_pi (parent)->dst_type); } -if (test_bit (HCI_CONN_PA_SYNC , &hcon->flags)) { +if (test_bit (HCI_CONN_PA_SYNC , hcon->flags)) {iso_pi (sk)->qos =iso_pi (parent)->qos; hcon->iso_qos =iso_pi (sk)->qos;iso_pi (sk)->bc_sid =iso_pi (parent)->bc_sid;
@@ -2676,8 +2676,8 @@ static void iso_connect_cfm(struct hci_conn *hcon, __u8 status)* into the accept queue of the listening socket and wake up * userspace, to inform the user about the event. */ -if (!status ||test_bit (HCI_CONN_BIG_SYNC_FAILED , &hcon->flags) || -test_bit (HCI_CONN_PA_SYNC_FAILED , &hcon->flags)) { +if (!status ||test_bit (HCI_CONN_BIG_SYNC_FAILED , hcon->flags) || +test_bit (HCI_CONN_PA_SYNC_FAILED , hcon->flags)) {struct iso_conn *conn; conn =iso_conn_add (hcon);
net/bluetooth/l2cap_core.c +1 -1
@@ -1556,7 +1556,7 @@ static bool l2cap_check_enc_key_size(struct hci_conn *hcon,if (chan->sec_level ==BT_SECURITY_FIPS ) min_key_size =16 ; -return (!test_bit (HCI_CONN_ENCRYPT , &hcon->flags) || +return (!test_bit (HCI_CONN_ENCRYPT , hcon->flags) || hcon->enc_key_size >= min_key_size); }
net/bluetooth/mgmt.c +10 -10
@@ -3239,7 +3239,7 @@ static int unpair_device(struct sock *sk, struct hci_dev *hdev, void *data,/* Defer clearing up the connection parameters until closing to * give a chance of keeping them if a repairing happens. */ -set_bit (HCI_CONN_PARAM_REMOVAL_PEND , &conn->flags); +set_bit (HCI_CONN_PARAM_REMOVAL_PEND , conn->flags);/* Disable auto-connection parameters if present */ params =hci_conn_params_lookup (hdev, &cp->addr.bdaddr, addr_type);
@@ -3414,7 +3414,7 @@ static int get_connections(struct sock *sk, struct hci_dev *hdev, void *data, i =0 ;list_for_each_entry (c, &hdev->conn_hash.list, list) { -if (test_bit (HCI_CONN_MGMT_CONNECTED , &c->flags)) +if (test_bit (HCI_CONN_MGMT_CONNECTED , c->flags)) i++; }
@@ -3426,7 +3426,7 @@ static int get_connections(struct sock *sk, struct hci_dev *hdev, void *data, i =0 ;list_for_each_entry (c, &hdev->conn_hash.list, list) { -if (!test_bit (HCI_CONN_MGMT_CONNECTED , &c->flags)) +if (!test_bit (HCI_CONN_MGMT_CONNECTED , c->flags))continue ;bacpy (&rp->addr[i].bdaddr, &c->dst); rp->addr[i].type =link_to_bdaddr (c->type, c->dst_type);
@@ -3626,7 +3626,7 @@ static int pairing_complete(struct mgmt_pending_cmd *cmd, u8 status)/* The device is paired so there is no need to remove * its connection parameters anymore. */ -clear_bit (HCI_CONN_PARAM_REMOVAL_PEND , &conn->flags); +clear_bit (HCI_CONN_PARAM_REMOVAL_PEND , conn->flags);hci_conn_put (conn);
@@ -10116,7 +10116,7 @@ void mgmt_device_connected(struct hci_dev *hdev, struct hci_conn *conn,u16 eir_len =0 ;u32 flags =0 ; -if (test_and_set_bit (HCI_CONN_MGMT_CONNECTED , &conn->flags)) +if (test_and_set_bit (HCI_CONN_MGMT_CONNECTED , conn->flags))return ;/* allocate buff for LE or BR/EDR adv */
@@ -10165,7 +10165,7 @@ void mgmt_device_connected(struct hci_dev *hdev, struct hci_conn *conn,* since userspace did not know about them yet, so report it now. * Unencrypted connections have no change to report. */ -if (test_bit (HCI_CONN_ENCRYPT , &conn->flags)) +if (test_bit (HCI_CONN_ENCRYPT , conn->flags))mgmt_security_level_changed (conn); }
@@ -10277,7 +10277,7 @@ void mgmt_connect_failed(struct hci_dev *hdev, struct hci_conn *conn, u8 status)* still needs it set to know whether to report the security level * reset, so it is consumed there instead of here. */ -if (test_bit (HCI_CONN_MGMT_CONNECTED , &conn->flags)) { +if (test_bit (HCI_CONN_MGMT_CONNECTED , conn->flags)) {mgmt_device_disconnected (hdev, &conn->dst, conn->type, conn->dst_type,hci_to_mgmt_reason (status), true);
@@ -10918,7 +10918,7 @@ void mgmt_security_level_changed(struct hci_conn *conn)u8 *tlv_data;u8 tlv_len; -if (!test_bit (HCI_CONN_MGMT_CONNECTED , &conn->flags)) +if (!test_bit (HCI_CONN_MGMT_CONNECTED , conn->flags))return ;/* Only ACL, LE and BIS links are tracked as mgmt connections, so
@@ -10949,9 +10949,9 @@ void mgmt_security_level_changed(struct hci_conn *conn) tlv = (void *)tlv_data; tlv->type =cpu_to_le16 (MGMT_SEC_LEVEL_CHANGED_PARAM_ENC_TYPE ); tlv->length =sizeof (__u8); -if (!test_bit (HCI_CONN_ENCRYPT , &conn->flags)) +if (!test_bit (HCI_CONN_ENCRYPT , conn->flags)) tlv->value[0 ] =MGMT_CONN_SEC_ENCRYPT_NONE ; -else if (test_bit (HCI_CONN_AES_CCM , &conn->flags)) +else if (test_bit (HCI_CONN_AES_CCM , conn->flags)) tlv->value[0 ] =MGMT_CONN_SEC_ENCRYPT_AES_CCM ;else tlv->value[0 ] =MGMT_CONN_SEC_ENCRYPT_E0 ;
net/bluetooth/smp.c +12 -12
@@ -982,12 +982,12 @@ static u8 smp_random(struct smp_chan *smp)smp_s1 (smp->tk, smp->rrnd, smp->prnd, stk); -if (test_and_set_bit (HCI_CONN_ENCRYPT_PEND , &hcon->flags)) +if (test_and_set_bit (HCI_CONN_ENCRYPT_PEND , hcon->flags))return SMP_UNSPECIFIED ;hci_le_start_enc (hcon, ediv, rand, stk, smp->enc_key_size); hcon->enc_key_size = smp->enc_key_size; -set_bit (HCI_CONN_STK_ENCRYPT , &hcon->flags); +set_bit (HCI_CONN_STK_ENCRYPT , hcon->flags); }else {u8 stk[16 ], auth;__le64 rand =0 ;
@@ -1026,7 +1026,7 @@ static void smp_notify_keys(struct l2cap_conn *conn) persistent = false; else persistent = !test_bit (HCI_CONN_FLUSH_KEY , - &hcon->flags); + hcon->flags); }else {/* The LTKs, IRKs and CSRKs should be persistent only if * both sides had the bonding bit set in their
@@ -1751,7 +1751,7 @@ static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb)/* SMP over BR/EDR requires special treatment */ if (conn->hcon->type ==ACL_LINK ) {/* We must have a BR/EDR SC link */ -if (!test_bit (HCI_CONN_AES_CCM , &conn->hcon->flags) && +if (!test_bit (HCI_CONN_AES_CCM , conn->hcon->flags) && !hci_dev_test_flag (hdev,HCI_FORCE_BREDR_SMP ))return SMP_CROSS_TRANSP_NOT_ALLOWED ;
@@ -2208,14 +2208,14 @@ static bool smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level)if (smp_ltk_sec_level (key) < sec_level)return false; -if (test_and_set_bit (HCI_CONN_ENCRYPT_PEND , &hcon->flags)) +if (test_and_set_bit (HCI_CONN_ENCRYPT_PEND , hcon->flags))return true;hci_le_start_enc (hcon, key->ediv, key->rand, key->val, key->enc_size); hcon->enc_key_size = key->enc_size;/* We never store STKs for initiator role, so clear this flag */ -clear_bit (HCI_CONN_STK_ENCRYPT , &hcon->flags); +clear_bit (HCI_CONN_STK_ENCRYPT , hcon->flags);return true; }
@@ -2233,7 +2233,7 @@ bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level,* don't have an LTK (e.g. because of key distribution bits). */ if (key_pref ==SMP_USE_LTK && -test_bit (HCI_CONN_STK_ENCRYPT , &hcon->flags) && +test_bit (HCI_CONN_STK_ENCRYPT , hcon->flags) &&hci_find_ltk (hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role))return false;
@@ -3082,11 +3082,11 @@ static void bredr_pairing(struct l2cap_chan *chan)bt_dev_dbg (hdev,"chan %p" , chan);/* Only new pairings are interesting */ -if (!test_bit (HCI_CONN_NEW_LINK_KEY , &hcon->flags)) +if (!test_bit (HCI_CONN_NEW_LINK_KEY , hcon->flags))return ;/* Don't bother if we're not encrypted */ -if (!test_bit (HCI_CONN_ENCRYPT , &hcon->flags)) +if (!test_bit (HCI_CONN_ENCRYPT , hcon->flags))return ;/* Only initiator may initiate SMP over BR/EDR */
@@ -3098,7 +3098,7 @@ static void bredr_pairing(struct l2cap_chan *chan)return ;/* BR/EDR must use Secure Connections for SMP */ -if (!test_bit (HCI_CONN_AES_CCM , &hcon->flags) && +if (!test_bit (HCI_CONN_AES_CCM , hcon->flags) && !hci_dev_test_flag (hdev,HCI_FORCE_BREDR_SMP ))return ;
@@ -3147,7 +3147,7 @@ static void smp_resume_cb(struct l2cap_chan *chan)if (!smp)return ; -if (!test_bit (HCI_CONN_ENCRYPT , &hcon->flags)) +if (!test_bit (HCI_CONN_ENCRYPT , hcon->flags))return ;cancel_delayed_work (&smp->security_timer);
@@ -3170,7 +3170,7 @@ static void smp_ready_cb(struct l2cap_chan *chan)*/ conn->smp = chan; -if (hcon->type ==ACL_LINK &&test_bit (HCI_CONN_ENCRYPT , &hcon->flags)) +if (hcon->type ==ACL_LINK &&test_bit (HCI_CONN_ENCRYPT , hcon->flags))bredr_pairing (chan); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 197/1005 Bluetooth: L2CAP: Hold incoming data until encryption key size is known
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Luiz Augusto von Dentz <[email protected]>
[ Upstream commit 5d005ded2cb14531c4d4ab5d02383407c75dbee6 ]
Once encryption is enabled on an ACL link, the encryption key size is read from the controller, using hdev->min_enc_key_size in the meantime. Data received before the reply is processed with that key size, so a peer starting SMP over BR/EDR right after encryption, which it may do, gets its Pairing Request rejected with "Encryption Key Size" whenever the pending security level is FIPS, as that requires a 16 octet key:
Quoted 2 lines
HCI Event: Encryption Change (
0x08) plen 4
ACL Data RX: Handle 1 flags0x02dlen 11
BR/EDR SMP: Pairing Request (0x01) len 6
@ MGMT Event: Authentication Failed (0x0011) plen 8
Status: Authentication Failed (0x05)< HCI Command: Read Encryption Key Size (0x05|0x0008) plen 2
Quoted 1 line
HCI Event: Command Complete (
0x0e) plen 7
Key size: 16
< ACL Data TX: Handle 1 flags 0x00 dlen 6
BR/EDR SMP: Pairing Failed (0x05) len 1
Reason: Encryption key size (0x06)Mark the connection with HCI_CONN_ENC_KEY_SIZE_PEND while the key size is read and hold incoming L2CAP data back in pending_rx meanwhile, processing it once the reply is handled.
Found with mgmt-tester "Pairing Acceptor - SMP over BR/EDR 2" under User Mode Linux time travel, where the emulated peer always replies before the key size is read.
--- include/net/bluetooth/hci_core.h | 1 + net/bluetooth/hci_event.c | 12 +++++++++++- net/bluetooth/l2cap_core.c | 16 ++++++++++++++-- 3 files changed, 26 insertions(+), 3 deletions(-)
include/net/bluetooth/hci_core.h +1 -0
@@ -711,6 +711,7 @@ enum {HCI_CONN_CREATE_PA_SYNC ,HCI_CONN_PA_SYNC ,HCI_CONN_PA_SYNC_FAILED , +HCI_CONN_ENC_KEY_SIZE_PEND , __HCI_CONN_NUM_FLAGS, };
net/bluetooth/hci_event.c +11 -1
@@ -724,6 +724,8 @@ static u8 hci_cc_read_enc_key_size(struct hci_dev *hdev, void *data, goto done; } +clear_bit (HCI_CONN_ENC_KEY_SIZE_PEND , conn->flags); +/* While unexpected, the read_enc_key_size command may fail. The most * secure approach is to then assume the key size is 0 to force a * disconnection.
@@ -3190,6 +3192,7 @@ static int hci_read_enc_key_size(struct hci_dev *hdev, struct hci_conn *conn) {struct hci_cp_read_enc_key_size cp;u8 *key_enc_size =hci_conn_key_enc_size (conn); +int err;if (!read_key_size_capable (hdev)) { conn->enc_key_size =HCI_LINK_KEY_SIZE ;
@@ -3211,7 +3214,14 @@ static int hci_read_enc_key_size(struct hci_dev *hdev, struct hci_conn *conn)else conn->enc_key_size = hdev->min_enc_key_size; -return hci_send_cmd (hdev,HCI_OP_READ_ENC_KEY_SIZE ,sizeof (cp), &cp); +/* L2CAP holds incoming data back until the key size is known */ +set_bit (HCI_CONN_ENC_KEY_SIZE_PEND , conn->flags); + + err =hci_send_cmd (hdev,HCI_OP_READ_ENC_KEY_SIZE ,sizeof (cp), &cp); +if (err) +clear_bit (HCI_CONN_ENC_KEY_SIZE_PEND , conn->flags); + +return err; } static void hci_conn_complete_evt(struct hci_dev *hdev, void *data,
net/bluetooth/l2cap_core.c +14 -2
@@ -7253,7 +7253,11 @@ static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb)u16 cid, len;__le16 psm; -if (hcon->state !=BT_CONNECTED ) { +/* Also hold data back while the encryption key size is read, as +* the security of the link, e.g. for SMP over BR/EDR, depends on it. +*/ +if (hcon->state !=BT_CONNECTED || +test_bit (HCI_CONN_ENC_KEY_SIZE_PEND , hcon->flags)) {BT_DBG ("queueing pending rx skb" );skb_queue_tail (&conn->pending_rx, skb);return ;
@@ -7316,7 +7320,11 @@ static void process_pending_rx(struct work_struct *work)mutex_lock (&conn->lock); -while ((skb =skb_dequeue (&conn->pending_rx))) +/* l2cap_recv_frame() would queue it all again while the encryption +* key size is read, l2cap_security_cfm() schedules this once known. +*/ +while (!test_bit (HCI_CONN_ENC_KEY_SIZE_PEND , conn->hcon->flags) && + (skb =skb_dequeue (&conn->pending_rx)))l2cap_recv_frame (conn, skb);mutex_unlock (&conn->lock);
@@ -7899,6 +7907,10 @@ static void l2cap_security_cfm(struct hci_conn *hcon, u8 status, u8 encrypt) }mutex_unlock (&conn->lock); + +/* Process data held back while the encryption key size was read */ +if (!skb_queue_empty (&conn->pending_rx)) +queue_work (hcon->hdev->workqueue, &conn->pending_rx_work); }/* Append fragment into frame respecting the maximum len of rx_skb */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 198/1005 Bluetooth: hci_sync: Update the CIS host feature when enabling LE
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Luiz Augusto von Dentz <[email protected]>
[ Upstream commit e24bfbc5e20711dafa0cdc2b3325c69de1cff068 ]
The Connected Isochronous Stream (Host Support) feature bit is only set during init, based on LE being enabled at that time. If LE is enabled afterwards without the init being repeated, as happens when the controller is still auto powered on after registration, the bit stays cleared and controllers enforcing it reject LE Create CIS with Command Disallowed.
Update the bit whenever LE Host Supported is written, so it follows the LE state.
--- net/bluetooth/hci_sync.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-)
net/bluetooth/hci_sync.c +14 -2
@@ -3511,9 +3511,13 @@ int hci_write_ssp_mode_sync(struct hci_dev *hdev, u8 mode)return hci_write_sc_support_sync (hdev,0x01 ); } +static int hci_le_set_host_feature_sync (struct hci_dev *hdev,u16 bit, +u8 value); +int hci_write_le_host_supported_sync (struct hci_dev *hdev,u8 le,u8 simul) {struct hci_cp_write_le_host_supported cp; +int err;if (!hci_dev_test_flag (hdev,HCI_LE_ENABLED ) || !lmp_bredr_capable (hdev))
@@ -3531,8 +3535,16 @@ int hci_write_le_host_supported_sync(struct hci_dev *hdev, u8 le, u8 simul) cp.le = le; cp.simul = simul; -return __hci_cmd_sync_status (hdev,HCI_OP_WRITE_LE_HOST_SUPPORTED , -sizeof (cp), &cp,HCI_CMD_TIMEOUT ); + err =__hci_cmd_sync_status (hdev,HCI_OP_WRITE_LE_HOST_SUPPORTED , +sizeof (cp), &cp,HCI_CMD_TIMEOUT ); +if (err || !cis_capable (hdev)) +return err; + +/* The CIS host feature is set during init based on LE being enabled, +* which is not repeated when LE is enabled afterwards, e.g. while the +* controller is still auto powered on, so update it here. +*/ +return hci_le_set_host_feature_sync (hdev,32 ,iso_enabled (hdev)); }static int hci_powered_update_adv_sync (struct hci_dev *hdev)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 199/1005 Bluetooth: btmtk: drop zero-length ISO packets from endpoint padding
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Lu <[email protected]>
[ Upstream commit 8524c3588fbb9d5c1b876e6f908c42926845650d ]
The ISO interrupt IN endpoint delivers a fixed-size transfer that holds one HCI ISO packet and zero-fills the remainder. That padding belongs to the transfer rather than to the stream, so it has to be dropped instead of reported to the host.
btmtk_recv_isopkt() keeps parsing it: the zero bytes read as an ISO header with handle 0 and a Data_Total_Length of zero, and each one is passed to hci_recv_frame() as a complete frame. A single transfer yields a long run of them, which is what fills the HCI log with malformed ISO packets, and iso_recv() drops the SDU it is reassembling whenever handle 0 belongs to a live CIS/BIS.
A zero Data_Total_Length carries no ISO Data Load, so such a packet is never part of the stream. Check for the zero-filled remainder before starting to parse the next frame, rather than after assembling a 4-byte
header: a remainder shorter than HCI_ISO_HDR_SIZE would otherwise be held across calls as a partial header, corrupting the next transfer's framing. This also means a fully zero-filled remainder no longer costs an skb allocation that gets immediately freed. Reaching a zero Data_Total_Length any other way is then a genuine error, not padding.
This was observed on MT7925, but btmtk_recv_isopkt() is shared by every MediaTek USB controller that supports ISO data.
--- drivers/bluetooth/btmtk.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+)
drivers/bluetooth/btmtk.c +20 -0
@@ -7,6 +7,7 @@#include <linux/usb.h> #include <linux/iopoll.h> #include <linux/overflow.h> +#include <linux/string.h> #include <linux/unaligned.h> #include <net/bluetooth/bluetooth.h>
@@ -1170,6 +1171,14 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)int len;if (!skb) { +/* Drop the endpoint's zero-filled padding before +* allocating an skb for it; a zero Data_Total_Length +* check below would miss a padding remainder +* shorter than an ISO header. +*/ +if (mem_is_zero (buffer, count)) +break ; + skb =bt_skb_alloc (HCI_MAX_ISO_SIZE ,GFP_ATOMIC );if (!skb) { err = -ENOMEM ;
@@ -1193,6 +1202,17 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)/* Complete ISO header */ hci_skb_expect (skb) =__le16_to_cpu (dlen); +if (!hci_skb_expect (skb)) { +/* Zero padding was ruled out above, so a +* zero Data_Total_Length here is invalid. +*/ +kfree_skb (skb); + skb =NULL ; + + err = -EILSEQ ; +break ; + } +if (skb_tailroom (skb) <hci_skb_expect (skb)) {kfree_skb (skb); skb =NULL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 200/1005 Bluetooth: btmtk: bound the ISO payload length by the controllers MTU
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Lu <[email protected]>
[ Upstream commit d015faf684129a276f2137ad2e11c6c985294648 ]
btmtk_recv_isopkt() bounds the Data_Total_Length reported by the controller with skb_tailroom(skb) < hci_skb_expect(skb). That keeps the reassembly inside the skb, but it enforces no protocol limit: the head allocation is rounded up to the next kmalloc bucket and skb_tailroom() reports what the bucket can hold rather than what was requested, which is several hundred bytes more. An oversized length therefore passes, and the parser keeps pulling bytes out of the following transfers to fill it, swallowing the real ISO packets they carry until the frame is handed to hci_recv_frame().
The controller reports the largest ISO_Data_Packet_Length it will send in LE Read Buffer Size [v2], which hci_cc_le_read_buffer_size_v2() keeps in hdev->iso_mtu. Once that is available, bound the length by it and size the receive skb to hold that much plus the 4-byte header. HCI_MAX_ISO_SIZE is kept only as a fallback for the window before the command completes.
Keep the skb_tailroom() test as well, because a fragment started before hdev->iso_mtu was populated sits in an skb sized for the fallback.
--- drivers/bluetooth/btmtk.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-)
drivers/bluetooth/btmtk.c +16 -2
@@ -1162,8 +1162,15 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)struct btmtk_data *btmtk_data =hci_get_priv (hdev);struct sk_buff *skb;unsigned long flags; +unsigned int iso_mtu;int err =0 ; +/* The controller reports the largest Data_Total_Length it will send in +* LE Read Buffer Size [v2]. Fall back to HCI_MAX_ISO_SIZE while that +* command has not completed yet. +*/ + iso_mtu = hdev->iso_mtu ? hdev->iso_mtu :HCI_MAX_ISO_SIZE ; +spin_lock_irqsave (&btmtk_data->isorxlock, flags); skb = btmtk_data->isopkt_skb;
@@ -1179,7 +1186,8 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)if (mem_is_zero (buffer, count))break ; - skb =bt_skb_alloc (HCI_MAX_ISO_SIZE ,GFP_ATOMIC ); + skb =bt_skb_alloc (HCI_ISO_HDR_SIZE + iso_mtu, +GFP_ATOMIC );if (!skb) { err = -ENOMEM ;break ;
@@ -1213,7 +1221,13 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)break ; } -if (skb_tailroom (skb) <hci_skb_expect (skb)) { +/* Reject a length the controller said it would never +* send. The skb_tailroom() test is kept because a +* fragment started before hdev->iso_mtu was populated +* sits in a smaller skb than iso_mtu now allows. +*/ +if (hci_skb_expect (skb) > iso_mtu || +skb_tailroom (skb) <hci_skb_expect (skb)) {kfree_skb (skb); skb =NULL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 201/1005 Bluetooth: btmtk: derive the firmware ISO setting from MTK_ISO_THRESHOLD
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Lu <[email protected]>
[ Upstream commit 855c9a54608f1e94f4c52afe3790def30534155a ]
The ISO data transfer size is spelled out twice: as a raw byte pair in the vendor command sent by btmtk_usb_isointf_init(), and as MTK_ISO_THRESHOLD for the padding in btmtk_isopkt_pad(). Build the command payload from the macro so the size is stated once, and update the setting for current MediaTek controllers.
--- drivers/bluetooth/btmtk.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/bluetooth/btmtk.c +3 -3
@@ -25,7 +25,7 @@#define MTK_SEC_MAP_NEED_SEND_SIZE 52/* It is for mt79xx iso data transmission setting */ -#define MTK_ISO_THRESHOLD 264 +#define MTK_ISO_THRESHOLD 342struct btmtk_patch_header {u8 datetime[16 ];
@@ -1346,7 +1346,7 @@ static int btmtk_submit_intr_urb(struct hci_dev *hdev, gfp_t mem_flags)static int btmtk_usb_isointf_init (struct hci_dev *hdev) {struct btmtk_data *btmtk_data =hci_get_priv (hdev); -u8 iso_param[2 ] = {0x08 ,0x01 }; +__le16 iso_param =cpu_to_le16 (MTK_ISO_THRESHOLD );struct sk_buff *skb;int err;
@@ -1361,7 +1361,7 @@ static int btmtk_usb_isointf_init(struct hci_dev *hdev)return err; } - skb =__hci_cmd_sync (hdev,0xfd98 ,sizeof (iso_param), iso_param, + skb =__hci_cmd_sync (hdev,0xfd98 ,sizeof (iso_param), &iso_param,HCI_INIT_TIMEOUT );if (IS_ERR (skb)) {bt_dev_err (hdev,"Failed to apply iso setting (%ld)" ,PTR_ERR (skb));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 202/1005 Bluetooth: hci_sync: Copy the LE accept list under hdev->lock
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit 674006912777747170ad70d7727804ad4f2d047f ]
The LE accept-list mirror consists of bdaddr_list entries that are added, removed and freed under hdev->lock. The ordinary branch of hci_update_accept_list_sync() traverses this list without that lock. The request worker's req_lock does not serialize raw HCI completions, and the RCU sections protect connection and pending-action lookups, not the accept-list nodes.
Changing connectability can reach this iterator through set_connectable_sync(), hci_update_connectable_sync(), hci_update_passive_scan_sync() and hci_passive_scan_sync(). With a populated mirror, a privileged raw HCI sender can issue HCI_OP_LE_CLEAR_ACCEPT_LIST while request work is reconciling it:
Request work HCI event work
select b and successor t
hci_cc_le_clear_accept_list()
hci_dev_lock(hdev) hci_bdaddr_list_clear()
unlink nodes and kfree(b)
hci_dev_unlock(hdev)
read b->bdaddr_type
The clear completion can therefore free the selected node before its field read, or the saved successor before the iterator advances. KASAN reported a one-byte read of bdaddr_type from the freed node.
Copy each entry's address and type under hdev->lock and reconcile the private array instead. Release the mutex before issuing synchronous commands, since their completion handlers also acquire it. Free the copy after iteration and use the existing error path to disable accept-list filtering if allocation fails.
This change has not been runtime-tested.
KASAN report as below:
==================================================================
BUG: KASAN: slab-use-after-free in hci_passive_scan_sync+0x1cc4/0x1f80
Read of size 1 at addr ffff888105ee6c56 by task kworker/u17:1/499
Workqueue: hci0 hci_cmd_sync_work
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? hci_passive_scan_sync+0x1cc4/0x1f80
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20d/0x410
? hci_passive_scan_sync+0x1cc4/0x1f80
kasan_report+0xe0/0x110
? hci_passive_scan_sync+0x1cc4/0x1f80
hci_passive_scan_sync+0x1cc4/0x1f80
? pmbd_gate_site_armed+0x31/0x1c0
? __pfx_hci_passive_scan_sync+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? pmbd_probe_hit_cookie+0x10/0x1c0
? __pfx_pmbd_probe_hit_cookie+0x10/0x10
? hci_update_passive_scan_sync+0x43f/0x9e0
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x280
hci_update_passive_scan_sync+0x473/0x9e0
hci_update_connectable_sync+0x13c/0x250
set_connectable_sync+0x39/0xb0
hci_cmd_sync_work+0x1b3/0x450
? 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
? __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>
Allocated by task 511:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x251/0x610
hci_bdaddr_list_add+0x179/0x390
hci_cc_le_add_to_accept_list+0x189/0x2d0
hci_cmd_complete_evt+0x373/0xab0
hci_event_packet+0x4e8/0xc70
hci_rx_work+0x367/0xf00
process_one_work+0x908/0x19c0
worker_thread+0x65c/0xe40
kthread+0x34f/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
Freed by task 511:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kfree+0x307/0x580
hci_bdaddr_list_clear+0x134/0x230
hci_cc_le_clear_accept_list+0x80/0x1f0
hci_cmd_complete_evt+0x373/0xab0
hci_event_packet+0x4e8/0xc70
hci_rx_work+0x367/0xf00
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 ffff888105ee6c40
which
belongs to the cache kmalloc-32 of size 32
The buggy address is located 22 bytes inside of
freed
32-byte region [ffff888105ee6c40,
ffff888105ee6c60)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000
index:0xffff888105ee69c0 pfn:0x105ee6
flags: 0x200000000000200(workingset|node=0|zone=2)
page_type: f5(slab)
raw: 0200000000000200 ffff888100042780 ffffea0004187150
ffffea00042534d0
raw: ffff888105ee69c0 000000000040003f 00000000f5000000
0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff888105ee6b00: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
ffff888105ee6b80: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
>ffff888105ee6c00: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
^
ffff888105ee6c80: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
ffff888105ee6d00: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
==================================================================--- net/bluetooth/hci_sync.c | 53 ++++++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 10 deletions(-)
net/bluetooth/hci_sync.c +43 -10
@@ -2885,6 +2885,31 @@ static struct conn_params *conn_params_copy(struct list_head *list, size_t *n)return p; } +static struct conn_params *le_accept_list_copy (struct hci_dev *hdev, +size_t *n) +{ +struct bdaddr_list *entry; +struct conn_params *params; +size_t i =0 ; + +hci_dev_lock (hdev); + + *n =list_count_nodes (&hdev->le_accept_list); + params = kvzalloc_objs(struct conn_params, *n); +if (!params) + goto unlock; + +list_for_each_entry (entry, &hdev->le_accept_list, list) { +bacpy (¶ms[i].addr, &entry->bdaddr); + params[i].addr_type = entry->bdaddr_type; + i++; + } + +unlock: +hci_dev_unlock (hdev); +return params; +} +/* Clear LE Accept List */ static int hci_le_clear_accept_list_sync (struct hci_dev *hdev) {
@@ -2915,7 +2940,6 @@ static int hci_le_clear_accept_list_sync(struct hci_dev *hdev)static u8 hci_update_accept_list_sync (struct hci_dev *hdev) {struct conn_params *params; -struct bdaddr_list *b, *t;u8 num_entries =0 ;bool pend_conn, pend_report;u8 filter_policy;
@@ -2980,20 +3004,27 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev)* report. If not present in either list, then remove it from * the controller. */ -list_for_each_entry_safe (b, t, &hdev->le_accept_list, list) { + params =le_accept_list_copy (hdev, &n); +if (!params) { + err = -ENOMEM ; + goto done; + } + +for (i =0 ; i < n; i++) {rcu_read_lock (); -if (hci_conn_hash_lookup_le (hdev, &b->bdaddr, b->bdaddr_type)) { +if (hci_conn_hash_lookup_le (hdev, ¶ms[i].addr, + params[i].addr_type)) {rcu_read_unlock ();continue ; } pend_conn =hci_pend_le_action_lookup (&hdev->pend_le_conns, - &b->bdaddr, - b->bdaddr_type); - pend_report =hci_pend_le_action_lookup (&hdev->pend_le_reports, - &b->bdaddr, - b->bdaddr_type); + ¶ms[i].addr, + params[i].addr_type); + pend_report =hci_pend_le_action_lookup ( + &hdev->pend_le_reports, ¶ms[i].addr, + params[i].addr_type);rcu_read_unlock ();
@@ -3001,14 +3032,16 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev)* remove it from the acceptlist. */ if (!pend_conn && !pend_report) { -hci_le_del_accept_list_sync (hdev, &b->bdaddr, - b->bdaddr_type); +hci_le_del_accept_list_sync (hdev, ¶ms[i].addr, + params[i].addr_type);continue ; } num_entries++; } +kvfree (params); +/* Since all no longer valid accept list entries have been * removed, walk through the list of pending connections * and ensure that any new device gets programmed into
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 203/1005 Bluetooth: hci_sync: Protect resolving-list lookups
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit f05bd61a3213613de7848c8df2865492d5225023 ]
The host resolving list is updated under hdev->lock, and each bdaddr_list_with_irk entry must remain alive throughout a lookup. hci_le_del_resolve_list_sync() and hci_le_add_resolve_list_sync() traverse that list without taking the lock.
On an LE privacy-capable controller with a programmed entry, passive scan reconciliation can reach hci_le_del_resolve_list_sync() while a privileged HCI_RAW client sends LE Clear Resolving List. The raw command does not take req_lock, and its successful completion runs on the controller workqueue independently of request work:
Request work Raw HCI / event work
hci_le_del_resolve_list_sync()
lookup loads a list node
hci_sock_sendmsg()
queue LE Clear Resolving List
hci_cc_le_clear_resolv_list()
take hdev->lock unlink and free the node release hdev->lock
read the node's address/type
The clear can free the node after the lookup loads it and before its address/type read, causing a use-after-free. The report below shows this access with the delete helper on the faulting stack. The add helper uses the same unprotected lookup.
Take hdev->lock around each resolving-list membership lookup and retain only a boolean result. This serializes traversal with clear completion and keeps entry pointers inside the protected section. Release the lock before issuing a synchronous HCI command, whose completion also needs the lock.
KASAN report as below:
==================================================================
BUG: KASAN: slab-use-after-free in
hci_bdaddr_list_lookup_with_irk+0x106/0x120
Read of size 1 at addr ffff88810b036e16 by task kworker/u17:0/495
CPU: 2 UID: 0 PID: 495 Comm: kworker/u17:0 Not tainted
7.2.0-rc6-pmb-bt-functional-v1+ #3 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: hci0 hci_cmd_sync_work
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? hci_bdaddr_list_lookup_with_irk+0x106/0x120
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20d/0x410
? hci_bdaddr_list_lookup_with_irk+0x106/0x120
kasan_report+0xe0/0x110
? hci_bdaddr_list_lookup_with_irk+0x106/0x120
hci_bdaddr_list_lookup_with_irk+0x106/0x120
hci_le_del_resolve_list_sync.isra.0+0xd6/0x3f0
? __pfx_hci_le_del_resolve_list_sync.isra.0+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
hci_le_del_accept_list_sync.isra.0+0x11c/0x290
? __pfx_hci_le_del_accept_list_sync.isra.0+0x10/0x10
? hci_passive_scan_sync+0x551/0x1e80
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x280
hci_passive_scan_sync+0x71c/0x1e80
? __pfx_hci_passive_scan_sync+0x10/0x10
? find_held_lock+0x2b/0x80
? hci_lookup_le_connect+0xe1/0x3c0
? srso_alias_return_thunk+0x5/0xfbef5
? find_held_lock+0x2b/0x80
? hci_update_passive_scan_sync+0x437/0x950
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x280
hci_update_passive_scan_sync+0x461/0x950
hci_cmd_sync_work+0x1b3/0x450
? 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
? __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>
Allocated by task 495:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x251/0x610
hci_bdaddr_list_add_with_irk+0x183/0x3e0
hci_cc_le_add_to_resolv_list+0x18c/0x240
hci_cmd_complete_evt+0x373/0xab0
hci_event_packet+0x4e8/0xc70
hci_rx_work+0x367/0xf00
process_one_work+0x908/0x19c0
worker_thread+0x65c/0xe40
kthread+0x34f/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
Freed by task 497:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kfree+0x307/0x580
hci_bdaddr_list_clear+0x134/0x230
hci_cc_le_clear_resolv_list+0x13d/0x240
hci_cmd_complete_evt+0x373/0xab0
hci_event_packet+0x4e8/0xc70
hci_rx_work+0x367/0xf00
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 ffff88810b036e00
which belongs to the cache kmalloc-64 of size 64
The buggy address is located 22 bytes inside of
freed 64-byte region [ffff88810b036e00, ffff88810b036e40)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0
pfn:0x10b036
flags: 0x200000000000000(node=0|zone=2)
page_type: f5(slab)
raw: 0200000000000000 ffff8881000428c0 dead000000000100
dead000000000122
raw: 0000000000000000 0000000000200020 00000000f5000000
0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff88810b036d00: 00 00 00 00 00 00 00 00 fc fc fc fc fc fc fc fc
ffff88810b036d80: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
>ffff88810b036e00: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
^
ffff88810b036e80: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
ffff88810b036f00: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
==================================================================
Disabling lock debugging due to kernel taint--- net/bluetooth/hci_sync.c | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-)
net/bluetooth/hci_sync.c +12 -9
@@ -2448,15 +2448,17 @@ static int hci_le_del_resolve_list_sync(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 bdaddr_type) {struct hci_cp_le_del_from_resolv_list cp; -struct bdaddr_list_with_irk *entry; +bool exists;if (!ll_privacy_capable (hdev))return 0 ;/* Check if the IRK has been programmed */ - entry =hci_bdaddr_list_lookup_with_irk (&hdev->le_resolv_list, bdaddr, - bdaddr_type); -if (!entry) +hci_dev_lock (hdev); + exists =hci_bdaddr_list_lookup_with_irk (&hdev->le_resolv_list, + bdaddr, bdaddr_type); +hci_dev_unlock (hdev); +if (!exists)return 0 ; cp.bdaddr_type = bdaddr_type;
@@ -2512,8 +2514,8 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev, {struct hci_cp_le_add_to_resolv_list cp;struct smp_irk *irk; -struct bdaddr_list_with_irk *entry;struct hci_conn_params *p; +bool exists;if (!ll_privacy_capable (hdev))return 0 ;
@@ -2536,10 +2538,11 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev,return 0 ;/* Check if the IK has _not_ been programmed yet. */ - entry =hci_bdaddr_list_lookup_with_irk (&hdev->le_resolv_list, - ¶ms->addr, - params->addr_type); -if (entry) +hci_dev_lock (hdev); + exists =hci_bdaddr_list_lookup_with_irk ( + &hdev->le_resolv_list, ¶ms->addr, params->addr_type); +hci_dev_unlock (hdev); +if (exists)return 0 ; cp.bdaddr_type = params->addr_type;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 204/1005 Bluetooth: mgmt: reply to cancelled mgmt commands instead of silently dropping
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shuai Zhang <[email protected]>
[ Upstream commit c0bb764fc082672678d371c375597a6a9f614cf9 ]
The kernel sets HCI_AUTO_OFF when a controller is first registered and starts a 2-second timer. On slower boots bluetoothd and the HCI_AUTO_OFF timer can race: hci_power_off() is already queued while bluetoothd is still in the middle of its adapter setup sequence. hci_cmd_sync_clear() then cancels any pending mgmt commands with -ECANCELED, including the MGMT_OP_REMOVE_ADV_MONITOR sent by reset_adv_monitors() early in the setup sequence.
When auto_off=1, hci_dev_close_sync() skips __mgmt_power_off() entirely, so there is no fallback path to reply to the cancelled commands. mgmt_remove_adv_monitor_complete() silently returns on -ECANCELED, leaving the command with no reply. Since bluez's mgmt queue is strictly serialised, this stalls all subsequent commands indefinitely, leaving bluetoothd unable to register the adapter.
Fix by mapping -ECANCELED to MGMT_STATUS_CANCELLED in mgmt_errno_status() and replying to the cancelled command in mgmt_remove_adv_monitor_complete() instead of returning early.
Stable-dep-of: 7eac80614300 ("Bluetooth: MGMT: Return RFKILLED for Set Powered on a blocked controller")
--- net/bluetooth/mgmt.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
net/bluetooth/mgmt.c +13 -1
@@ -302,6 +302,8 @@ static u8 mgmt_errno_status(int err)return MGMT_STATUS_ALREADY_CONNECTED ;case -ENOTCONN :return MGMT_STATUS_DISCONNECTED ; +case -ECANCELED : +return MGMT_STATUS_CANCELLED ; }return MGMT_STATUS_FAILED ;
@@ -5690,8 +5692,18 @@ static void mgmt_remove_adv_monitor_complete(struct hci_dev *hdev,struct mgmt_pending_cmd *cmd = data;struct mgmt_cp_remove_adv_monitor *cp; -if (status == -ECANCELED ) +/* Reply to a cancelled command so bluetoothd's serialised mgmt queue +* is not blocked. +*/ +if (status == -ECANCELED ) { + cp = cmd->param; + rp.monitor_handle = cp->monitor_handle; + +mgmt_cmd_complete (cmd->sk, cmd->hdev->id, cmd->opcode, +mgmt_status (status), &rp,sizeof (rp)); +mgmt_pending_free (cmd);return ; + }hci_dev_lock (hdev);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 205/1005 Bluetooth: MGMT: Return RFKILLED for Set Powered on a blocked controller
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tobias Wilken <[email protected]>
[ Upstream commit 7eac80614300563470cffabf4df2b63616787ee7 ]
Since MGMT_OP_SET_POWERED runs through hci_cmd_sync, powering on a controller that is blocked by rfkill fails with -ERFKILL from hci_dev_open_sync(), and mgmt_set_powered_complete() reports it with mgmt_status(err). mgmt_errno_status() has no case for -ERFKILL, so userspace gets MGMT_STATUS_FAILED instead of MGMT_STATUS_RFKILLED.
Before that conversion, power on went through hci_power_on(), whose error path mgmt_set_powered_failed() still maps -ERFKILL to MGMT_STATUS_RFKILLED. bluetoothd relies on that status: for RFKILLED it sets the adapter PowerState to "off-blocked" and returns org.bluez.Error.Blocked for the Powered property, for any other status it returns org.bluez.Error.Failed.
With the controller soft blocked, "bluetoothctl power on" printed "Failed to set power on: org.bluez.Error.Failed" and btmon showed "Set Powered (0x0005) Status: Failed (0x03)". With this change it prints org.bluez.Error.Blocked and btmon shows "Status: RFKilled (0x12)".
Map -ERFKILL to MGMT_STATUS_RFKILLED in mgmt_errno_status().
--- net/bluetooth/mgmt.c | 2 ++ 1 file changed, 2 insertions(+)
net/bluetooth/mgmt.c +2 -0
@@ -304,6 +304,8 @@ static u8 mgmt_errno_status(int err)return MGMT_STATUS_DISCONNECTED ;case -ECANCELED :return MGMT_STATUS_CANCELLED ; +case -ERFKILL : +return MGMT_STATUS_RFKILLED ; }return MGMT_STATUS_FAILED ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 206/1005 Bluetooth: btmtk: fix error handling in btmtk_usb_isointf_init()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ismail Tarim <[email protected]>
[ Upstream commit 3b70dd827b27bfadd89e7b1a2d422b04da38797c ]
btmtk_usb_isointf_init() submits the ISO interrupt IN URB and then sends the vendor command 0xfd98. If that command fails, the function returns an error without killing the URB it has just submitted. The caller then leaves BTMTK_ISOPKT_RUNNING clear, so the driver treats the ISO path as inactive while its RX URB is still in flight, and btmtk_usb_suspend() skips killing it. Kill the anchored URBs on this path, as the URB submission failure path already does.
The return value of __set_mtk_intr_interface() is also ignored: a failure to select the ISO alternate setting or to find its endpoints is logged, but the function goes on to submit the URB. Return the error instead.
--- drivers/bluetooth/btmtk.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/bluetooth/btmtk.c +4 -1
@@ -1352,7 +1352,9 @@ static int btmtk_usb_isointf_init(struct hci_dev *hdev)spin_lock_init (&btmtk_data->isorxlock); -__set_mtk_intr_interface (hdev); + err =__set_mtk_intr_interface (hdev); +if (err <0 ) +return err; err =btmtk_submit_intr_urb (hdev,GFP_KERNEL );if (err <0 ) {
@@ -1364,6 +1366,7 @@ static int btmtk_usb_isointf_init(struct hci_dev *hdev) skb =__hci_cmd_sync (hdev,0xfd98 ,sizeof (iso_param), &iso_param,HCI_INIT_TIMEOUT );if (IS_ERR (skb)) { +usb_kill_anchored_urbs (&btmtk_data->isopkt_anchor);bt_dev_err (hdev,"Failed to apply iso setting (%ld)" ,PTR_ERR (skb));return PTR_ERR (skb); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 207/1005 Bluetooth: hci_core: Keep link-key filtering inside RCU
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit 281ddc4e01ab54cab07995f2a1b72cf81bf90eb5 ]
hci_find_link_key() must keep the matching link key allocated while it checks the key against the blocked-key list. It currently leaves the key-list RCU read-side section before passing k->val to hci_is_blocked_key(). That helper's own RCU section protects the blocked-key list, but it cannot keep an unlinked link key from being reclaimed.
The SMP receive path calls the finder without hdev->lock: Secure Connections key distribution over BR/EDR reaches it through smp_distribute_keys() and sc_generate_ltk(). With a stored peer link key and a link-key entry in the blocked-key list, MGMT_OP_LOAD_LINK_KEYS can free the selected key before the comparison:
HCI RX worker (SMP) Management / RCU reclamation
hci_find_link_key()
rcu_read_lock()
select k
rcu_read_unlock()
load_link_keys()
hci_dev_lock(hdev)
hci_link_keys_clear(hdev)
list_del_rcu(), kfree_rcu()
hci_dev_unlock(hdev)
grace period ends, k is freed
hci_is_blocked_key(hdev, ..., k->val)
memcmp() reads the freed keyKeep the RCU read-side section active through the blocked-key comparison and the warning that prints k->bdaddr, and release it before returning on both matched-key paths. hci_find_ltk() already handles its blocked-key check this way.
KASAN reported this on a test kernel whose scheduling hook paused the receive worker after the lookup until the key had been freed.
KASAN report as below:
==================================================================
BUG: KASAN: slab-use-after-free in hci_is_blocked_key+0x2db/0x300
Read of size 1 at addr ffff88810b5f89a7 by task kworker/u17:0/502
CPU: 1 UID: 0 PID: 502 Comm: kworker/u17:0 Not tainted 7.2.0-rc6-pmb-bt-functional-v1+ #5 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: hci1 hci_rx_work
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? hci_is_blocked_key+0x2db/0x300
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20d/0x410
? hci_is_blocked_key+0x2db/0x300
kasan_report+0xe0/0x110
? hci_is_blocked_key+0x2db/0x300
hci_is_blocked_key+0x2db/0x300
hci_find_link_key+0x12e/0x400
smp_distribute_keys+0x1830/0x2950
? trace_hardirqs_on+0x18/0x160
? srso_alias_return_thunk+0x5/0xfbef5
? queue_delayed_work_on+0xb3/0xf0
? __pfx_smp_distribute_keys+0x10/0x10
? __pfx_smp_send_cmd.isra.0+0x10/0x10
? __cancel_work+0x1b0/0x290
? __entry_text_end+0x1020f7/0x1020f9
? lockdep_hardirqs_on_prepare+0xea/0x1a0
? srso_alias_return_thunk+0x5/0xfbef5
? __asan_memset+0x23/0x50
? smp_recv_cb+0x12c7/0x8d80
? srso_alias_return_thunk+0x5/0xfbef5
smp_recv_cb+0x12c7/0x8d80
? __pfx_smp_recv_cb+0x10/0x10
? __pfx___might_resched+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? stack_depot_save_flags+0x29/0x9a0
? srso_alias_return_thunk+0x5/0xfbef5
? __mutex_lock+0x182c/0x2590
? kasan_save_stack+0x42/0x60
? l2cap_recv_frame+0x9ef/0x8830
? __kasan_slab_free+0x5f/0x80
? kmem_cache_free+0x242/0x580
? kfree_skbmem+0x15e/0x1d0
? sk_skb_reason_drop+0x12f/0x490
? hci_event_packet+0x556/0xc70
? hci_rx_work+0x367/0xf00
? process_one_work+0x908/0x19c0
? worker_thread+0x65c/0xe40
? __pfx___mutex_lock+0x10/0x10
? __lock_acquire+0x466/0x2260
? __pfx_l2cap_chan_hold_unless_zero+0x10/0x10
? l2cap_recv_frame+0x13cc/0x8830
? __pfx_smp_recv_cb+0x10/0x10
l2cap_recv_frame+0x13cc/0x8830
? srso_alias_return_thunk+0x5/0xfbef5
? __mutex_lock+0x182c/0x2590
? __pfx_l2cap_recv_frame+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? find_held_lock+0x2b/0x80
? l2cap_recv_acldata+0x1eb/0x10e0
? __pfx___mutex_lock+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __mutex_unlock_slowpath+0x147/0x920
? __pfx_l2cap_conn_hold_unless_zero+0x10/0x10
? __pfx_hci_conn_enter_active_mode+0x10/0x10
? l2cap_recv_acldata+0x13d/0x10e0
? srso_alias_return_thunk+0x5/0xfbef5
l2cap_recv_acldata+0xe9f/0x10e0
? srso_alias_return_thunk+0x5/0xfbef5
hci_rx_work+0x5a6/0xf00
? 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
? __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>
Allocated by task 504:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x251/0x610
hci_add_link_key+0x474/0x840
hci_link_key_notify_evt+0x492/0xce0
hci_event_packet+0x894/0xc70
hci_rx_work+0x367/0xf00
process_one_work+0x908/0x19c0
worker_thread+0x65c/0xe40
kthread+0x34f/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
Freed by task 29:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
__rcu_free_sheaf_prepare+0x65/0x2a0
rcu_free_sheaf_nobarn+0x1d/0x50
rcu_core+0x661/0x1d10
handle_softirqs+0x201/0x930
run_ksoftirqd+0x33/0x60
smpboot_thread_fn+0x3bd/0x9a0
kthread+0x34f/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
The buggy address belongs to the object at ffff88810b5f8980
which belongs to the cache kmalloc-64 of size 64
The buggy address is located 39 bytes inside of
freed 64-byte region [ffff88810b5f8980, ffff88810b5f89c0)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x10b5f8
flags: 0x200000000000000(node=0|zone=2)
page_type: f5(slab)
raw: 0200000000000000 ffff8881000428c0 dead000000000100 dead000000000122
raw: 0000000000000000 0000000000200020 00000000f5000000 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff88810b5f8880: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
ffff88810b5f8900: 00 00 00 00 00 00 00 fc fc fc fc fc fc fc fc fc
>ffff88810b5f8980: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
^
ffff88810b5f8a00: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
ffff88810b5f8a80: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
==================================================================--- net/bluetooth/hci_core.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
net/bluetooth/hci_core.c +2 -3
@@ -1075,17 +1075,16 @@ struct link_key *hci_find_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr)rcu_read_lock ();list_for_each_entry_rcu (k, &hdev->link_keys, list) {if (bacmp (bdaddr, &k->bdaddr) ==0 ) { -rcu_read_unlock (); -if (hci_is_blocked_key (hdev,HCI_BLOCKED_KEY_TYPE_LINKKEY , k->val)) {bt_dev_warn_ratelimited (hdev,"Link key blocked for %pMR" , &k->bdaddr); -return NULL ; + k =NULL ; } +rcu_read_unlock ();return k; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 208/1005 Bluetooth: SMP: Protect link keys during LTK derivation
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit ebc4f217c1fbe8364b5ef2ad8e3a8e9a1b2701a7 ]
sc_generate_ltk() reads the type and value of the peer link key after hci_find_link_key() has returned. The finder ends its RCU read-side section before returning the borrowed entry, and the SMP receive path does not hold hdev->lock: l2cap_recv_acldata() releases it before the PDU is dispatched. The L2CAP connection and channel locks held by SMP do not serialize with management link-key removal.
When BR/EDR Secure Connections pairing derives an LTK from the stored link key, MGMT_OP_LOAD_LINK_KEYS can free that key mid-derivation:
HCI RX worker (SMP) Management / RCU reclamation
sc_generate_ltk()
key = hci_find_link_key()
load_link_keys()
hci_dev_lock(hdev)
hci_link_keys_clear(hdev)
list_del_rcu(), kfree_rcu()
hci_dev_unlock(hdev)
grace period ends, key is freed
read key->type
smp_h6() or smp_h7() reads key->valHold an RCU read-side section from the lookup until the type and value have been consumed. smp_h6() and smp_h7() only run the synchronous AES-CMAC library code, which neither sleeps nor allocates. Release the section before sc_add_ltk(), which allocates with GFP_KERNEL.
KASAN reported this on a test kernel whose scheduling hook paused the receive worker after the lookup; the hook frames appear in the trace.
KASAN report as below:
==================================================================
BUG: KASAN: slab-use-after-free in smp_distribute_keys+0x2983/0x2b70
Read of size 1 at addr ffff88810618e9a6 by task kworker/u17:0/500
CPU: 0 UID: 0 PID: 500 Comm: kworker/u17:0 Not tainted 7.2.0-rc6-pmb-bt-functional-v1+ #1 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: hci1 hci_rx_work
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? smp_distribute_keys+0x2983/0x2b70
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20d/0x410
? smp_distribute_keys+0x2983/0x2b70
kasan_report+0xe0/0x110
? smp_distribute_keys+0x2983/0x2b70
smp_distribute_keys+0x2983/0x2b70
? __pfx_smp_distribute_keys+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? pmbd_gate_maybe+0x47/0x60
? srso_alias_return_thunk+0x5/0xfbef5
? pmbd_probe_hit_cookie+0xe7/0x1c0
? srso_alias_return_thunk+0x5/0xfbef5
? pmbd_probe_hit_cookie+0xee/0x1c0
? __pfx_pmbd_probe_hit_cookie+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __asan_memset+0x23/0x50
? smp_recv_cb+0x12e2/0x8f30
? srso_alias_return_thunk+0x5/0xfbef5
smp_recv_cb+0x12e2/0x8f30
? __pfx_smp_recv_cb+0x10/0x10
? __pfx___might_resched+0x10/0x10
? __pfx_sched_balance_find_src_group+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __mutex_lock+0x182c/0x2590
? l2cap_recv_frame+0x9ef/0x8830
? __pfx___mutex_lock+0x10/0x10
? __lock_acquire+0x466/0x2260
? __pfx_l2cap_chan_hold_unless_zero+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? l2cap_recv_frame+0x13cc/0x8830
? __pfx_smp_recv_cb+0x10/0x10
l2cap_recv_frame+0x13cc/0x8830
? srso_alias_return_thunk+0x5/0xfbef5
? __mutex_lock+0x182c/0x2590
? __pfx_l2cap_recv_frame+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? find_held_lock+0x2b/0x80
? l2cap_recv_acldata+0x1eb/0x10e0
? __pfx___mutex_lock+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __mutex_unlock_slowpath+0x147/0x920
? __pfx_l2cap_conn_hold_unless_zero+0x10/0x10
? __pfx_hci_conn_enter_active_mode+0x10/0x10
? l2cap_recv_acldata+0x13d/0x10e0
? srso_alias_return_thunk+0x5/0xfbef5
l2cap_recv_acldata+0xe9f/0x10e0
? srso_alias_return_thunk+0x5/0xfbef5
hci_rx_work+0x5a6/0xf00
? 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
? __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>
Allocated by task 500:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x251/0x610
hci_add_link_key+0x474/0x840
hci_link_key_notify_evt+0x492/0xce0
hci_event_packet+0x894/0xc70
hci_rx_work+0x367/0xf00
process_one_work+0x908/0x19c0
worker_thread+0x65c/0xe40
kthread+0x34f/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
Freed by task 0:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
__rcu_free_sheaf_prepare+0x65/0x2a0
rcu_free_sheaf+0x1f/0xe0
rcu_core+0x661/0x1d10
handle_softirqs+0x201/0x930
__irq_exit_rcu+0x110/0x1e0
irq_exit_rcu+0xe/0x20
sysvec_apic_timer_interrupt+0x6c/0x80
asm_sysvec_apic_timer_interrupt+0x1a/0x20
The buggy address belongs to the object at ffff88810618e980
which belongs to the cache kmalloc-64 of size 64
The buggy address is located 38 bytes inside of
freed 64-byte region [ffff88810618e980, ffff88810618e9c0)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x10618e
flags: 0x200000000000000(node=0|zone=2)
page_type: f5(slab)
raw: 0200000000000000 ffff8881000428c0 dead000000000122 0000000000000000
raw: 0000000000000000 0000000000200020 00000000f5000000 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff88810618e880: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
ffff88810618e900: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
>ffff88810618e980: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
^
ffff88810618ea00: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
ffff88810618ea80: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
==================================================================--- net/bluetooth/smp.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-)
net/bluetooth/smp.c +11 -4
@@ -1184,9 +1184,13 @@ static void sc_generate_ltk(struct smp_chan *smp)struct hci_conn *hcon = smp->conn->hcon;struct hci_dev *hdev = hcon->hdev;struct link_key *key; +int err; + +rcu_read_lock (); key =hci_find_link_key (hdev, &hcon->dst);if (!key) { +rcu_read_unlock ();bt_dev_err (hdev,"no Link Key found to generate LTK" );return ; }
@@ -1198,16 +1202,19 @@ static void sc_generate_ltk(struct smp_chan *smp)/* SALT = 0x000000000000000000000000746D7032 */ const u8 salt[16 ] = {0x32 ,0x70 ,0x6d ,0x74 }; -if (smp_h7 (key->val, salt, smp->tk)) -return ; + err =smp_h7 (key->val, salt, smp->tk); }else {/* From core spec. Spells out in ASCII as 'tmp2'. */ const u8 tmp2[4 ] = {0x32 ,0x70 ,0x6d ,0x74 }; -if (smp_h6 (key->val, tmp2, smp->tk)) -return ; + err =smp_h6 (key->val, tmp2, smp->tk); } +rcu_read_unlock (); + +if (err) +return ; +if (smp_h6 (smp->tk, brle, smp->tk))return ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 209/1005 Bluetooth: SMP: Protect LTK encryption with RCU
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit add463a65802bb117e4a17b8c00d747fa70399fc ]
smp_ltk_encrypt() checks the security level of the LTK returned by hci_find_ltk() and then starts encryption with its EDIV, Rand, value and key size. The finder ends its RCU read-side section before returning the borrowed entry, and neither caller holds hdev->lock: the SMP Security Request handler runs from the receive path, and setsockopt(BT_SECURITY) reaches smp_conn_security() with only the socket and channel locks held.
MGMT_OP_LOAD_LONG_TERM_KEYS can therefore free the LTK in between:
Socket security request Management / RCU reclamation
smp_ltk_encrypt()
key = hci_find_ltk()
load_long_term_keys()
hci_dev_lock(hdev) hci_smp_ltks_clear(hdev)
list_del_rcu(), kfree_rcu()
hci_dev_unlock(hdev)
grace period ends, key is freed
smp_ltk_sec_level(key)
hci_le_start_enc(hcon, key->ediv, key->rand, key->val, ...)
Keep an RCU read-side section across the lookup and every use of the key. hci_le_start_enc() copies the key into the command and queues it with a GFP_ATOMIC allocation, so the whole sequence can stay inside the section.
KFENCE reported this on a test kernel where the socket thread was paused after the lookup until the RCU callback had freed the key.
KFENCE report as below:
==================================================================
BUG: KFENCE: use-after-free read in smp_ltk_encrypt.isra.0+0xf3/0x370
Use-after-free read at 0x00000000c45332eb (in kfence-#128):
smp_ltk_encrypt.isra.0+0xf3/0x370
smp_conn_security+0x489/0x9d0
l2cap_sock_setsockopt+0x1bbe/0x2300
do_sock_setsockopt+0x1fb/0x430
__sys_setsockopt+0x106/0x180
__x64_sys_setsockopt+0xc2/0x160
do_syscall_64+0x115/0x6a0
entry_SYSCALL_64_after_hwframe+0x77/0x7f
kfence-#128: 0x00000000d45af9b0-0x0000000053c1365e, size=72, cache=kmalloc-96
allocated by task 533 on cpu 0 at 50.484258s (0.449177s ago):
hci_add_ltk+0x1f5/0x3a0
load_long_term_keys+0x6ea/0x930
hci_sock_sendmsg+0x128b/0x22e0
sock_write_iter+0x4c0/0x550
vfs_write+0x637/0x1010
ksys_write+0x1b7/0x200
do_syscall_64+0x115/0x6a0
entry_SYSCALL_64_after_hwframe+0x77/0x7f
freed by task 0 on cpu 0 at 50.846944s (0.093664s ago):
__rcu_free_sheaf_prepare+0x261/0x2a0
rcu_free_sheaf_nobarn+0x1d/0x50
rcu_core+0x661/0x1d10
handle_softirqs+0x201/0x930
__irq_exit_rcu+0x110/0x1e0
irq_exit_rcu+0xe/0x20
sysvec_apic_timer_interrupt+0x6c/0x80
asm_sysvec_apic_timer_interrupt+0x1a/0x20
pv_native_safe_halt+0xf/0x20
default_idle+0x9/0x10
default_idle_call+0x6c/0xb0
do_idle+0x3a7/0x650
cpu_startup_entry+0x54/0x60
rest_init+0x15e/0x2b0
start_kernel+0x412/0x4b0
x86_64_start_reservations+0x18/0x30
x86_64_start_kernel+0x111/0x120
common_startup_64+0x13e/0x158
CPU: 2 UID: 0 PID: 534 Comm: l2cap-ltk-actor Not tainted 7.2.0-rc6-pmb-bt-functional-v1+ #5 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
==================================================================--- net/bluetooth/smp.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
net/bluetooth/smp.c +10 -4
@@ -2207,16 +2207,20 @@ static bool smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level) {struct smp_ltk *key;struct hci_conn *hcon = conn->hcon; +bool ret = false; + +rcu_read_lock (); key =hci_find_ltk (hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role);if (!key) -return false; + goto unlock;if (smp_ltk_sec_level (key) < sec_level) -return false; + goto unlock; + ret = true;if (test_and_set_bit (HCI_CONN_ENCRYPT_PEND , hcon->flags)) -return true; + goto unlock;hci_le_start_enc (hcon, key->ediv, key->rand, key->val, key->enc_size); hcon->enc_key_size = key->enc_size;
@@ -2224,7 +2228,9 @@ static bool smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level)/* We never store STKs for initiator role, so clear this flag */ clear_bit (HCI_CONN_STK_ENCRYPT , hcon->flags); -return true; +unlock: +rcu_read_unlock (); +return ret; } bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 210/1005 Bluetooth: hci_sync: Copy the resolving-list IRK under RCU
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit 9ff737119177a6c1ce6083ef8c0fc06355f11869 ]
hci_le_add_resolve_list_sync() copies the peer IRK into the LE Add Device To Resolving List command after hci_find_irk_by_addr() has returned. The finder ends its RCU read-side section before returning the borrowed entry, and neither the request worker nor interleave_scan_work() holds hdev->lock here. The resolving-list membership check between the lookup and the copy takes hdev->lock and may sleep on it, which widens the window.
When LL privacy programs a peer with address resolution enabled, MGMT_OP_LOAD_IRKS can free its IRK before the copy:
Request worker Management / RCU reclamation
hci_le_add_resolve_list_sync()
irk = hci_find_irk_by_addr()
load_irks()
hci_dev_lock(hdev) hci_smp_irks_clear(hdev)
list_del_rcu(), kfree_rcu()
hci_dev_unlock(hdev)
grace period ends, irk is freed
resolving-list membership check
memcpy(cp.peer_irk, irk->val, 16)
Copy the IRK value in an RCU read-side section right after the lookup, as hci_le_set_privacy_mode_sync() does for the identity address. The section ends before hdev->lock is taken and before the synchronous HCI command is sent.
KASAN reported this on a test kernel with scheduling hooks, whose frames appear in the trace. The report predates the hdev->lock taken by the membership check.
KASAN report as below:
==================================================================
BUG: KASAN: slab-use-after-free in hci_le_add_resolve_list_sync+0x8d9/0x910
Read of size 16 at addr ffff88810d21452d by task kworker/u17:0/504
CPU: 2 UID: 0 PID: 504 Comm: kworker/u17:0 Not tainted 7.2.0-rc6-pmb-bt-functional-v1+ #2 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: hci0 interleave_scan_work
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? hci_le_add_resolve_list_sync+0x8d9/0x910
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20d/0x410
? hci_le_add_resolve_list_sync+0x8d9/0x910
kasan_report+0xe0/0x110
? hci_le_add_resolve_list_sync+0x8d9/0x910
hci_le_add_resolve_list_sync+0x8d9/0x910
? __pfx_hci_le_add_resolve_list_sync+0x10/0x10
? pmbd_probe_hit_cookie+0xe7/0x1c0
? srso_alias_return_thunk+0x5/0xfbef5
? pmbd_probe_hit_cookie+0xee/0x1c0
? __pfx_pmbd_probe_hit_cookie+0x10/0x10
hci_le_add_accept_list_sync+0x18e/0x820
? conn_params_copy+0x36e/0x650
? __pfx_hci_le_add_accept_list_sync+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? conn_params_copy+0x3a0/0x650
hci_passive_scan_sync+0x95f/0x1f10
? __pfx_hci_passive_scan_sync+0x10/0x10
? debug_object_deactivate+0x2f8/0x3c0
? pwq_dec_nr_in_flight+0x880/0xdf0
? srso_alias_return_thunk+0x5/0xfbef5
? lock_acquire+0x17b/0x2f0
? process_one_work+0x895/0x19c0
interleave_scan_work+0x11b/0x470
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
? __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>
Allocated by task 535:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x251/0x610
hci_add_irk+0xb6/0x220
load_irks+0x5f9/0x840
hci_sock_sendmsg+0x128b/0x22e0
__sys_sendto+0x425/0x470
__x64_sys_sendto+0xe5/0x1c0
do_syscall_64+0x115/0x6a0
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 0:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
__rcu_free_sheaf_prepare+0x65/0x2a0
rcu_free_sheaf+0x1f/0xe0
rcu_core+0x661/0x1d10
handle_softirqs+0x201/0x930
__irq_exit_rcu+0x110/0x1e0
irq_exit_rcu+0xe/0x20
sysvec_apic_timer_interrupt+0x6c/0x80
asm_sysvec_apic_timer_interrupt+0x1a/0x20
The buggy address belongs to the object at ffff88810d214500
which belongs to the cache kmalloc-64 of size 64
The buggy address is located 45 bytes inside of
freed 64-byte region [ffff88810d214500, ffff88810d214540)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x10d214
flags: 0x200000000000000(node=0|zone=2)
page_type: f5(slab)
raw: 0200000000000000 ffff8881000428c0 dead000000000100 dead000000000122
raw: 0000000000000000 0000000000200020 00000000f5000000 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff88810d214400: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
ffff88810d214480: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
>ffff88810d214500: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
^
ffff88810d214580: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
ffff88810d214600: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
==================================================================--- net/bluetooth/hci_sync.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
net/bluetooth/hci_sync.c +9 -2
@@ -2533,9 +2533,17 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev, }else if (!(params->flags &HCI_CONN_FLAG_ADDRESS_RESOLUTION ))return 0 ; +rcu_read_lock (); + irk =hci_find_irk_by_addr (hdev, ¶ms->addr, params->addr_type); -if (!irk) +if (!irk) { +rcu_read_unlock ();return 0 ; + } + +memcpy (cp.peer_irk, irk->val,16 ); + +rcu_read_unlock ();/* Check if the IK has _not_ been programmed yet. */ hci_dev_lock (hdev);
@@ -2547,7 +2555,6 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev, cp.bdaddr_type = params->addr_type;bacpy (&cp.bdaddr, ¶ms->addr); -memcpy (cp.peer_irk, irk->val,16 );/* Default privacy mode is always Network */ params->privacy_mode =HCI_NETWORK_PRIVACY ;
Signature · 1 line
2.53.0