6.12.120-rc1 review
Subsystems (3)
Greg Kroah-Hartman
maintainerPATCH 584/816 vsock/virtio: clear vqs[] to avoid a UAF on a failed PM restore
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jerome Mohm <[email protected]>
commit 2a24ba1694f14299fbde3fa107e5d56629f2f8b6 upstream.
virtio_vsock_vqs_del() frees the virtqueues but leaves vsock->vqs[] pointing at them. If virtio_vsock_restore() then fails, the driver stays bound with a dangling vqs[], and the next freeze or unbind passes a freed virtqueue to virtqueue_detach_unused_buf():
BUG: KASAN: slab-use-after-free in virtqueue_detach_unused_buf virtio_vsock_vqs_del (net/vmw_vsock/virtio_transport.c:785) virtio_vsock_remove Freed by task ...: vp_del_vqs virtio_vsock_freeze
Clear vqs[] after del_vqs() and when virtio_find_vqs() fails. Return early from virtio_vsock_vqs_del() when vqs[] is empty: the detach loops would pass NULL to virtqueue_detach_unused_buf(), and a second del_vqs() would free virtio-mmio's IRQ again, which only WARNs in free_irq() ("Trying to free already-free IRQ").
Found with the help of Anthropic's Claude and reproduced on virtio-pci and virtio-mmio by failing the restore with failslab, without other kernel changes; the virtio-mmio WARN was found by the netdev Sashiko review and reproduced with v1 of this patch. With this patch neither report appears on virtio-pci or virtio-mmio guests, and the vsock vmtest.sh single-VM tests pass. A find_vqs() failure after some virtqueues were set up was not exercised.
--- net/vmw_vsock/virtio_transport.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-)
net/vmw_vsock/virtio_transport.c +13 -3
@@ -690,8 +690,10 @@ static int virtio_vsock_vqs_init(structatomic_set (&vsock->queued_replies,0 ); ret =virtio_find_vqs (vdev,VSOCK_VQ_MAX , vsock->vqs, vqs_info,NULL ); -if (ret <0 ) +if (ret <0 ) { +memset (vsock->vqs,0 ,sizeof (vsock->vqs));return ret; + }virtio_vsock_update_guest_cid (vsock);
@@ -752,11 +754,19 @@ static void virtio_vsock_vqs_del(struct vsock->event_run = false;mutex_unlock (&vsock->event_lock); +virtio_vsock_skb_queue_purge (&vsock->send_pkt_queue); +/* Flush all device writes and interrupts, device will not use any * more buffers. */ virtio_reset_device (vdev); +/* After a failed restore no virtqueues are live, and a second +* del_vqs() would free virtio-mmio's IRQ again (a WARN in free_irq()). +*/ +if (!vsock->vqs[VSOCK_VQ_RX ]) +return ; +mutex_lock (&vsock->rx_lock);while ((skb =virtqueue_detach_unused_buf (vsock->vqs[VSOCK_VQ_RX ])))kfree_skb (skb);
@@ -767,10 +777,10 @@ static void virtio_vsock_vqs_del(structkfree_skb (skb);mutex_unlock (&vsock->tx_lock); -virtio_vsock_skb_queue_purge (&vsock->send_pkt_queue); -/* Delete virtqueues and flush outstanding callbacks if any */ vdev->config->del_vqs (vdev); + +memset (vsock->vqs,0 ,sizeof (vsock->vqs)); }static int virtio_vsock_probe (struct virtio_device *vdev)
Greg Kroah-Hartman
maintainerPATCH 585/816 tsacct: Keep task begin times stable across suspend
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
commit c49b3c20a2d0b22700e2100a527e68e829ece7f0 upstream.
bacct_add_tsk() derives ac_btime and ac_btime64 by subtracting a CLOCK_MONOTONIC elapsed duration from CLOCK_REALTIME. MONOTONIC stops during suspend while REALTIME continues, so querying an existing task after resume moves its reported begin time forward by the time spent suspended.
Calculate the begin time from the wall-clock boot timestamp and the task's CLOCK_BOOTTIME start timestamp instead. This accounts for suspend and adds the nanoseconds before truncating to seconds. Keep ac_etime and ac_tgetime on CLOCK_MONOTONIC and retain the existing rebasing when the wall clock is adjusted.
The new begin time can be negative: setting CLOCK_REALTIME is bounded by CLOCK_MONOTONIC, which excludes suspend, rather than CLOCK_BOOTTIME. A permitted backward clock adjustment after suspend can therefore put the task's begin time before the epoch. Clamp ac_btime64 at zero too, instead of wrapping in the unsigned field, and retain its positive range.
--- kernel/tsacct.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-)
kernel/tsacct.c +6 -4
@@ -24,7 +24,7 @@ void bacct_add_tsk(struct user_namespaceconst struct cred *tcred;u64 utime, stime, utimescaled, stimescaled;u64 now_ns, delta; -time64_t btime; +struct timespec64 btime;BUILD_BUG_ON (TS_COMM_LEN <TASK_COMM_LEN );
@@ -39,9 +39,11 @@ void bacct_add_tsk(struct user_namespacedo_div (delta,NSEC_PER_USEC ); stats->ac_etime = delta;/* Convert to seconds for btime (note y2106 limit) */ - btime =ktime_get_real_seconds () -div_u64 (delta,USEC_PER_SEC ); - stats->ac_btime =clamp_t (time64_t, btime,0 ,U32_MAX ); - stats->ac_btime64 = btime; +getboottime64 (&btime); + btime =timespec64_add (btime,ns_to_timespec64 (tsk->start_boottime)); + stats->ac_btime =clamp_t (time64_t, btime.tv_sec,0 ,U32_MAX ); +/* Setting the clock back after suspend can make btime negative. */ + stats->ac_btime64 =max_t (time64_t, btime.tv_sec,0 );if (tsk->flags &PF_EXITING ) stats->ac_exitcode = tsk->exit_code;
Greg Kroah-Hartman
maintainerPATCH 586/816 tls: only install push_pending_record for a TX context
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rishikesh Jethwani <[email protected]>
commit c47e766c5307c06a78304582b2b5b5ab01ee1358 upstream.
tls_set_sw_offload() assigns ctx->push_pending_record for both directions, but the hook is a TX-side dispatcher. On a socket whose TX side is HW offloaded, tls_set_device_offload() installs tls_device_push_pending_record(); any later TLS_RX setsockopt overwrites it with tls_sw_push_pending_record(), because tls_set_device_offload_rx() itself calls tls_set_sw_offload(sk, 0, NULL) for the software half of a successful HW RX offload, and so does the fallback when the RX offload is declined (NIC with TX-only offload, tls_dev_add() failure).
Quoted 1 line
From then on
tls_handle_open_record()(aTLS_SET_RECORD_TYPEcmsg after
a MSG_MORE send, or the close path with a pending writer) runs tls_sw_push_pending_record() against priv_ctx_tx, which is a struct tls_offload_context_tx, not a struct tls_sw_context_tx, and reads open_rec from inside the offload context. On x86_64 without lock debugging that field overlays sg_tx_data[2].dma_address, which is never set, so the push is silently skipped and the data buffered by the MSG_MORE send is later sent under the cmsg's record type, e.g. application data in a handshake or alert record. Enabling CONFIG_DEBUG_SPINLOCK, CONFIG_DEBUG_LOCK_ALLOC and CONFIG_LOCKDEP, but not CONFIG_LOCK_STAT, in the tested x86_64 configuration moves open_rec over sg_tx_data[5].page_link. Once populated, its page pointer and scatterlist flags are interpreted as a tls_rec pointer and dereferenced while reading msg_plaintext.sg.size.
Only set the hook when initialising the TX side.
Found by code review while developing TLS 1.3 HW offload rekey support.
Tested with HW TLS TX and RX offload on Mellanox ConnectX-6 Dx (Crypto Enabled): after setting TLS_RX, send() "AAAA" with MSG_MORE, then sendmsg() "BBBB" with a TLS_SET_RECORD_TYPE cmsg for a handshake record. Without this patch the peer receives a single handshake record "AAAABBBB"; with it, an application data record "AAAA" followed by a handshake record "BBBB".
--- net/tls/tls_sw.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/tls/tls_sw.c +2 -1
@@ -2887,7 +2887,8 @@ int tls_set_sw_offload(struct sock *sk, } } - ctx->push_pending_record = tls_sw_push_pending_record; +if (tx) + ctx->push_pending_record = tls_sw_push_pending_record; rc =crypto_aead_setkey (*aead, key, cipher_desc->key);if (rc)
Greg Kroah-Hartman
maintainerPATCH 587/816 tcp: fix authentication bypass via unsupported TCP auth options
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 7cc235fb1251fec1183e3158c60d2e504c2a8e8b upstream.
tcp_inbound_hash() parses both TCP-MD5 and TCP-AO options when at least one of the two features is enabled. With TCP_MD5SIG=y and TCP_AO=n, a packet carrying an AO option reaches the disabled tcp_inbound_ao_hash() stub. That stub returns success, so sockets configured to require MD5 authentication end up accepting unauthenticated data. A forged AO option skips the unsigned fast path, which is the only place where tcp_inbound_hash() can return SKB_DROP_REASON_TCP_MD5NOTFOUND.
The inverse configuration with TCP_MD5SIG=n and TCP_AO=y has the same problem for an MD5 option on AO sockets.
Note that TCP-AO depends on 64BIT: therefore, every 32-bit kernel with TCP_MD5SIG=y is in the vulnerable configuration.
Make the disabled stubs reject options for the unsupported authentication scheme. This matches the real helpers' behavior for sockets without keys. It also means that kernels with TCP_MD5SIG=n and TCP_AO=y now drop segments carrying an MD5 option on unkeyed sockets, as kernels configured with TCP_MD5SIG=y already do.
--- include/net/tcp_ao.h | 3 ++- net/ipv4/tcp.c | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-)
include/net/tcp_ao.h +2 -1
@@ -287,7 +287,8 @@ static inline enum skb_drop_reason tcp_i const struct request_sock *req, int l3index, const struct tcp_ao_hdr *aoh) { - return SKB_NOT_DROPPED_YET; +NET_INC_STATS (sock_net (sk ),LINUX_MIB_TCPAOKEYNOTFOUND ); +return SKB_DROP_REASON_TCP_AOUNEXPECTED ; } static inline struct tcp_ao_key *tcp_ao_do_lookup(const struct sock *sk,
net/ipv4/tcp.c +2 -1
@@ -4809,7 +4809,8 @@ tcp_inbound_md5_hash(const struct sock * const void *saddr, const void *daddr, int family, int l3index, const __u8 *hash_location) { - return SKB_NOT_DROPPED_YET; +NET_INC_STATS (sock_net (sk ),LINUX_MIB_TCPMD5UNEXPECTED ); +return SKB_DROP_REASON_TCP_MD5UNEXPECTED ; }#endif
Greg Kroah-Hartman
maintainerPATCH 588/816 seg6: validate state in netfilter continuations
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zixuan Chai <[email protected]>
commit 549484dd3e80a721d51bd695f22a800d2e05bea1 upstream.
When nf_hooks_lwtunnel is enabled, End.DX4 sends decapsulated packets through NF_INET_PRE_ROUTING. If DNAT changes the inner destination, nf_nat_ipv4_pre_routing() drops skb_dst(), and the continuation then dereferences the missing dst's lwtstate. This causes a KASAN NULL pointer dereference and fatal exception panic.
End.DX6 has the same issue with IPv6 DNAT. In seg6_iptunnel, POST_ROUTING SNAT with an outbound XFRM policy can replace the dst before the continuation resumes.
Validate the current dst and expected lwtstate type in each NF_HOOK() continuation before calling the existing handler. Drop packets with missing or incompatible state while preserving direct no-hook paths. The helpers return bool because callers only need a validity check.
Testing shows that the End.DX4 DNAT reproducer triggers a KASAN NULL pointer dereference without this change and no longer does so with the fix. The SNAT+ESP/XFRM reproducer also completes without the reported fault. The in-tree End.DX4 netfilter forwarding selftest passes all four bidirectional checks with nf_hooks_lwtunnel disabled and enabled.
--- net/ipv6/seg6_iptunnel.c | 46 +++++++++++++++++++++++++++++++++++---- net/ipv6/seg6_local.c | 55 ++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 94 insertions(+), 7 deletions(-)
net/ipv6/seg6_iptunnel.c +42 -4
@@ -18,6 +18,7 @@#include <net/ip6_fib.h> #include <net/route.h> #include <net/seg6.h> +#include <net/dst_metadata.h> #include <linux/seg6.h> #include <linux/seg6_iptunnel.h> #include <net/addrconf.h>
@@ -58,6 +59,21 @@ static inline struct seg6_lwt *seg6_lwt_return (struct seg6_lwt *)lwt->data; } +static bool seg6_skb_has_lwtstate (struct sk_buff *skb) +{ +struct dst_entry *dst; + +if (unlikely (!skb_valid_dst (skb))) +return false; + + dst =skb_dst (skb); +if (unlikely (!dst->lwtstate || + dst->lwtstate->type !=LWTUNNEL_ENCAP_SEG6 )) +return false; + +return true; +} +static inline struct seg6_iptunnel_encap *seg6_encap_lwtunnel (struct lwtunnel_state *lwt) {
@@ -538,6 +554,17 @@ drop:return err; } +static int seg6_input_core_nf (struct net *net,struct sock *sk, +struct sk_buff *skb) +{ +if (unlikely (!seg6_skb_has_lwtstate (skb))) { +kfree_skb (skb); +return -EINVAL ; + } + +return seg6_input_core (net, sk, skb); +} +static int seg6_input_nf (struct sk_buff *skb) {struct net_device *dev =skb_dst_dev (skb);
@@ -546,10 +573,10 @@ static int seg6_input_nf(struct sk_buffswitch (skb->protocol) {case htons (ETH_P_IP ):return NF_HOOK (NFPROTO_IPV4 ,NF_INET_POST_ROUTING , net,NULL , - skb,NULL , dev, seg6_input_core); + skb,NULL , dev, seg6_input_core_nf);case htons (ETH_P_IPV6 ):return NF_HOOK (NFPROTO_IPV6 ,NF_INET_POST_ROUTING , net,NULL , - skb,NULL , dev, seg6_input_core); + skb,NULL , dev, seg6_input_core_nf); }return -EINVAL ;
@@ -624,6 +651,17 @@ drop:return err; } +static int seg6_output_core_nf (struct net *net,struct sock *sk, +struct sk_buff *skb) +{ +if (unlikely (!seg6_skb_has_lwtstate (skb))) { +kfree_skb (skb); +return -EINVAL ; + } + +return seg6_output_core (net, sk, skb); +} +static int seg6_output_nf (struct net *net,struct sock *sk,struct sk_buff *skb) {struct net_device *dev =skb_dst_dev (skb);
@@ -631,10 +669,10 @@ static int seg6_output_nf(struct net *neswitch (skb->protocol) {case htons (ETH_P_IP ):return NF_HOOK (NFPROTO_IPV4 ,NF_INET_POST_ROUTING , net, sk, skb, -NULL , dev, seg6_output_core); +NULL , dev, seg6_output_core_nf);case htons (ETH_P_IPV6 ):return NF_HOOK (NFPROTO_IPV6 ,NF_INET_POST_ROUTING , net, sk, skb, -NULL , dev, seg6_output_core); +NULL , dev, seg6_output_core_nf); }return -EINVAL ;
net/ipv6/seg6_local.c +52 -3
103 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 589/816 mptcp: reject DATA_ACKs against a reversed send interval
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit d75e5cd72995ec2fa77ec77a593cea28e2490ff1 upstream.
ack_update_msk() samples snd_nxt before taking the data lock, but reads snd_una after taking it. Concurrent transmission and ACK processing can therefore leave the sampled upper bound behind snd_una. Active-open completion also exposes a reversed interval when it initializes snd_una to IDSN + 1 while the socket-owned state synchronization is deferred.
A peer-supplied 64-bit Data ACK half a sequence space away can pass both wraparound comparisons against such an interval. The resulting snd_una can make __mptcp_retrans() inflate a fragment's already_sent field. Later ACKs can then underflow data_len and cause out-of-bounds page fragments to be passed to TCP.
Read snd_nxt after acquiring the data lock and reject reversed intervals before checking the received Data ACK. This keeps the interval shorter than half the sequence space, so the existing upper-bound check cannot accept an advance beyond snd_nxt. Preserve the existing handling of old ACKs and keep the transmit fields under their existing socket locking.
--- net/mptcp/options.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
net/mptcp/options.c +8 -4
@@ -1139,9 +1139,9 @@ static void ack_update_msk(struct mptcp_struct sock *ssk, struct mptcp_options_received *mp_opt) { - u64 new_wnd_end, new_snd_una, snd_nxt = READ_ONCE(msk->snd_nxt); + u64 new_wnd_end, new_snd_una, old_snd_una;struct sock *sk = (struct sock *)msk; -u64 old_snd_una; +u64 snd_nxt;mptcp_data_lock (sk);
@@ -1150,10 +1150,14 @@ static void ack_update_msk(struct mptcp_* more dangerous than missing an ack */ old_snd_una = msk->snd_una; + snd_nxt =READ_ONCE (msk->snd_nxt); new_snd_una =mptcp_expand_seq (old_snd_una, mp_opt->data_ack, mp_opt->ack64); -/* ACK for data not even sent yet? Ignore.*/ -if (unlikely (after64 (new_snd_una, snd_nxt))) +/* The active-open state sync can defer the snd_nxt update. Do not +* accept an ACK against a reversed interval, or beyond snd_nxt. +*/ +if (unlikely (before64 (snd_nxt, old_snd_una) || +after64 (new_snd_una, snd_nxt))) new_snd_una = old_snd_una; new_wnd_end = new_snd_una +tcp_sk (ssk)->snd_wnd;
Greg Kroah-Hartman
maintainerPATCH 590/816 ipv4: keep XFRM headers out of corked skb lengths
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 0f47fce51a98d3d9f439c16861d519a7b833a176 upstream.
__ip_append_data() allocates space for dst.header_len in the first skb, but includes that space in skb->len until __ip_make_skb() pulls it. Fragment accounting uses an MTU that already excludes the XFRM headers. As a result, the next skb can have a fraggap larger than its capped datalen, and skb_copy_and_csum_bits() can overwrite its shared info.
For example, five AH tunnel states can reserve 500 bytes while leaving an effective MTU of 348. With 40 bytes of IPv4 options, the second skb has room for 288 bytes of fragment data but receives a 500-byte gap copy. The overwritten shared info is subsequently consumed by the skb release paths.
Reserve the XFRM headers together with the link-layer headroom instead. This keeps skb->len, the gap-copy offsets and the trim lengths relative to the IPv4 packet throughout corking. The network and transport header addresses and the headroom available to XFRM at output are unchanged. Both paged and linear allocations, including subsequent corked appends, use the corrected accounting.
--- net/ipv4/ip_output.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
net/ipv4/ip_output.c +4 -4
@@ -1152,16 +1152,16 @@ alloc_new_skb:*/ skb->ip_summed = csummode; skb->csum =0 ; -skb_reserve (skb, hh_len); +skb_reserve (skb, hh_len + exthdrlen);/* * Find where to start putting bytes. */ - data =skb_put (skb, fraglen + exthdrlen - pagedlen); -skb_set_network_header (skb, exthdrlen); + data =skb_put (skb, fraglen - pagedlen); +skb_reset_network_header (skb); skb->transport_header = (skb->network_header + fragheaderlen); - data += fragheaderlen + exthdrlen; + data += fragheaderlen;if (fraggap) { skb->csum = skb_copy_and_csum_bits(
Greg Kroah-Hartman
maintainerPATCH 591/816 ipv4: fib_trie: prevent speculative out-of-bounds child access
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daniël Trujillo <[email protected]>
commit fd3d73286662950656f54616d0b3fea29e2dc99a upstream.
fib_table_lookup() checks the child index against the bounds before passing it to get_child_rcu().
The index is derived from the lookup key, which in turn is derived from flp->daddr. A userspace process can therefore influence the index by triggering lookups for chosen destination IPv4 addresses.
If this bounds check is mispredicted as in-bounds, an out-of-bounds index can be transiently passed to get_child_rcu(). The value loaded beyond the child array is then treated as a node pointer. A later transient dereference of that pointer can cause a data-dependent cache footprint.
This was found during Spectre-v1 research. Leakage was demonstrated with instrumentation that delays branch resolution with a CLFLUSH before the mispredicted branch and makes the leaked location deterministic for reproducible measurement. In that setup, a userspace-controlled IPv4 lookup key was able to trigger a transient out-of-bounds child access. The transient use of the loaded value as a pointer caused a data-dependent cache footprint that was recoverable from userspace using Prime+Probe. A real-world attacker would likely need to delay branch resolution, which was not demonstrated end-to-end without the added CLFLUSH.
Sanitize the index with array_index_nospec() before accessing the child array. This removed the observed leakage in the described setup.
Apply the hardening before setting cindex in fib_table_lookup(), because cindex can later be used by the backtrace path to load another child pointer. fib_find_node() has the same pattern, with the checked index derived from a user-provided key in fib_table_insert() and fib_table_delete(). leaf_walk_rcu() has a similar checked cindex before get_child_rcu(), and the traversed state can be influenced by userspace actions. fib_find_node() runs under RTNL and leaf_walk_rcu() is not on the packet lookup hot path, so harden those analogous accesses in the same way. Also harden fib_trie_get_next(), where a mispredicted loop condition could transiently read one child past the array.
I see a slowdown of roughly 10% in a microbenchmark where we call fib_table_lookup() with 64 routes directly from inside the kernel. I observed no slowdown in a loopback UDP sendto() microbenchmark.
--- net/ipv4/fib_trie.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
net/ipv4/fib_trie.c +13 -1
@@ -61,6 +61,7 @@#include <linux/export.h> #include <linux/vmalloc.h> #include <linux/notifier.h> +#include <linux/nospec.h> #include <net/net_namespace.h> #include <net/inet_dscp.h> #include <net/ip.h>
@@ -967,6 +968,8 @@ static struct key_vector *fib_find_node(break ; } + index =array_index_nospec (index,1ul << n->bits); +/* keep searching until we find a perfect match leaf or NULL */ }while (IS_TNODE (n));
@@ -1472,6 +1475,8 @@ int fib_table_lookup(struct fib_table *tif (IS_LEAF (n)) goto found; + index =array_index_nospec (index,1ul << n->bits); +/* only record pn and cindex if we are going to be chopping * bits later. Otherwise we are just wasting cycles. */
@@ -1772,6 +1777,8 @@ static struct key_vector *leaf_walk_rcu(if (cindex >> pn->bits)break ; + cindex =array_index_nospec (cindex,1ul << pn->bits); +/* descend into the next child */ n =get_child_rcu (pn, cindex++);if (!n)
@@ -1793,6 +1800,8 @@ static struct key_vector *leaf_walk_rcu(continue ; } + cindex =array_index_nospec (cindex,1ul << pn->bits); +/* grab the next available node */ n =get_child_rcu (pn, cindex++);if (!n)
@@ -2444,7 +2453,10 @@ static struct key_vector *fib_trie_get_nwhile (!IS_TRIE (pn)) {while (cindex <child_length (pn)) { -struct key_vector *n =get_child_rcu (pn, cindex++); +struct key_vector *n; + + cindex =array_index_nospec (cindex,child_length (pn)); + n =get_child_rcu (pn, cindex++);if (!n)continue ;
Greg Kroah-Hartman
maintainerPATCH 592/816 ipv6: fix cached route reuse for control messages
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xia Yan <[email protected]>
commit f778e80b3daf5033fb996f45c2b5d0ce1e82c0a7 upstream.
A connected IPv6 UDP or ping socket can reuse its cached route when an SO_MARK cmsg requests another mark. A packet can then bypass a prohibit rule instead of failing with EACCES.
ip6_sk_dst_lookup_flow() reads the cache even when connected is false. UDP clears connected after parsing IP or socket control messages. Ping always passes false.
Only read the cache when connected is true. Ordinary connected UDP sends keep using the cache. Ping sends do a fresh lookup.
Found during code review of IPv6 UDP route caching. On UML, the same connected-socket selftest fails four IPv6 cases before the fix and passes all 54 with it.
--- net/ipv6/ip6_output.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-)
net/ipv6/ip6_output.c +8 -5
@@ -1285,7 +1285,7 @@ EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow);* @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup -* @connected: whether @sk is connected or not +* @connected: whether the flow can use and update the socket dst cache * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid.
@@ -1302,11 +1302,14 @@ struct dst_entry *ip6_sk_dst_lookup_flow const struct in6_addr *final_dst, bool connected) { -struct dst_entry *dst =sk_dst_check (sk,inet6_sk (sk)->dst_cookie); +struct dst_entry *dst; - dst =ip6_sk_dst_check (sk, dst, fl6); -if (dst) -return dst; +if (connected) { + dst =sk_dst_check (sk,inet6_sk (sk)->dst_cookie); + dst =ip6_sk_dst_check (sk, dst, fl6); +if (dst) +return dst; + } dst =ip6_dst_lookup_flow (sock_net (sk), sk, fl6, final_dst);if (connected && !IS_ERR (dst))
Greg Kroah-Hartman
maintainerPATCH 593/816 ipv6: reject routes without an inet6_dev
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
commit 08a1eb7a634f665718ebe74e0960e242f597135e upstream.
ip6_route_output() and ip6_route_lookup() can return an error-free route whose rt6i_idev is NULL. Lowering an external nexthop device's MTU below IPV6_MIN_MTU tears down its inet6_dev, while fib6_ifdown() leaves routes using nexthop objects in the FIB.
An unprivileged user with CAP_NET_ADMIN in a private user and network namespace can construct this state. Consumers which treat a route without an error as usable can then dereference the NULL rt6i_idev. This was reproduced as a KASAN NULL pointer dereference in ip6_tnl_xmit().
An audit of IPv6 route and tunnel users found this unchecked ip6_dst_idev() dereference.
A similar missing inet6_dev check was fixed in commit 1b9b5323725e ("netfilter: ip6t_rpfilter: reject routes without inet6_dev"). However, the route construction path still marks routes without an inet6_dev as successful, leaving every consumer responsible for the same check.
Acquire the inet6_dev reference before initializing the destination. If a non-reject route has no inet6_dev, initialize it as RTN_UNREACHABLE instead of a successful route. Explicit reject routes keep their original type and error. This establishes that ordinary error-free IPv6 routes have an inet6_dev while retaining the existing defensive checks at callers.
The modified route object builds cleanly with W=1. A full x86_64 KASAN bzImage build completes; it reports two pre-existing kernel-doc warnings outside this change.
Tests:
- make W=1 net/ipv6/route.o
- full x86_64 KASAN bzImage build with W=1
- KASAN QEMU with an unprivileged user and network namespace: after lowering the MTU, the stale route returned No route to host, a normal route still resolved, and the collect_md trigger completed without KASAN, oops, or panic
- tools/testing/selftests/net/ip6_tunnel.sh in the same KASAN QEMU
--- net/ipv6/route.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
net/ipv6/route.c +7 -1
@@ -1144,6 +1144,12 @@ static void ip6_rt_init_dst(struct rt6_ireturn ; } +/* addrconf_ifdown() removed inet6_dev. The device can't do IPv6. */ +if (!rt->rt6i_idev) { +ip6_rt_init_dst_reject (rt,RTN_UNREACHABLE ); +return ; + } + rt->dst.error =0 ; rt->dst.output = ip6_output;
@@ -1178,10 +1184,10 @@ static void ip6_rt_copy_init(struct rt6_const struct net_device *dev = nh->fib_nh_dev;struct fib6_info *f6i = res->f6i; + rt->rt6i_idev = dev ?in6_dev_get (dev) :NULL ;ip6_rt_init_dst (rt, res); rt->rt6i_dst = f6i->fib6_dst; - rt->rt6i_idev = dev ?in6_dev_get (dev) :NULL ; rt->rt6i_flags = res->fib6_flags;if (nh->fib_nh_gw_family) { rt->rt6i_gateway = nh->fib_nh_gw6;
Greg Kroah-Hartman
maintainerPATCH 594/816 ipvs: Defer application parent freeing until after RCU readers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chengfeng Ye <[email protected]>
commit 1e0808008e44d736e57a897a51d14fa995099010 upstream.
unregister_ip_vs_app() removes each incarnation from its protocol list and uses call_rcu() to defer freeing it, but frees the parent application immediately. An RCU reader that already found an incarnation can still access the parent through inc->app in ip_vs_app_inc_get().
During FTP helper module unload, the following interleaving is possible:
CPU 0 (RCU reader) CPU 1 (module unload)
tcp_app_conn_bind()
find inc in protocol list
unregister_ip_vs_app()
ip_vs_app_inc_release(inc)
list_del_rcu(&inc->p_list)
call_rcu(&inc->rcu_head, ...)
kfree(a)
ip_vs_app_inc_get(inc)
try_module_get(inc->app->module)The helper module is already going away, so try_module_get() would fail, but evaluating its argument first reads the freed parent. The subsequent rcu_barrier() in pernet unregistration cannot protect this earlier free. KASAN reported:
BUG: KASAN: slab-use-after-free in ip_vs_app_inc_get+0x7c/0x90 Call Trace: ip_vs_app_inc_get+0x7c/0x90 tcp_app_conn_bind+0x1bc/0x290 ip_vs_conn_new+0x1915/0x20d0 ip_vs_schedule+0x697/0xea0 tcp_conn_schedule+0x489/0x820 ip_vs_in_hook+0x7bf/0x1f40 Allocated by task 88: kmemdup_noprof+0x20/0x50 register_ip_vs_app+0x12d/0x2c0 __ip_vs_ftp_init+0x56/0x160 [ip_vs_ftp] Freed by task 104: kfree+0x131/0x3c0 unregister_ip_vs_app+0x2f4/0x5b0 unregister_pernet_operations+0x232/0x490 unregister_pernet_subsys+0x1c/0x30 __do_sys_delete_module+0x346/0x510
Use kfree_rcu() with the existing rcu_head to keep the parent alive until these readers finish. Successful helper references already prevent normal module unload, and incarnation RCU callbacks do not access the parent.
--- net/netfilter/ipvs/ip_vs_app.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/netfilter/ipvs/ip_vs_app.c +1 -1
@@ -243,7 +243,7 @@ void unregister_ip_vs_app(struct netns_i }list_del (&a->a_list); -kfree (a); +kfree_rcu (a, rcu_head);/* decrease the module use count */ ip_vs_use_count_dec ();
Greg Kroah-Hartman
maintainerPATCH 595/816 ipvs: fix protocol data lifetime during namespace teardown
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chengfeng Ye <[email protected]>
commit 832aa3e89e806bb2667fe4e656b705f4088b3c9d upstream.
IPVS frees its per-net protocol data before control cleanup cancels defense work and unregisters the sysctl table. A defense worker can load a protocol data pointer, then namespace cleanup can unlink and free that object before the worker dereferences pd->pp or pd->next. The worker's securetcp_lock does not serialize with protocol cleanup. A concurrent defense-mode sysctl write can reach the same timeout update path.
KASAN reported:
BUG: KASAN: slab-use-after-free in ip_vs_protocol_timeout_change Workqueue: events_long defense_work_handler Call Trace: ip_vs_protocol_timeout_change+0x1b4/0x1e0 update_defense_level+0x63e/0xd80 defense_work_handler+0x1e/0xc0 Allocated by task 125: ip_vs_protocol_net_init+0xda/0x2f0 __ip_vs_init+0x16b/0x240 setup_net+0xfc/0x310 Freed by task 12: ip_vs_protocol_net_cleanup+0x1d6/0x2e0 __ip_vs_cleanup_batch+0x7d/0x100 cleanup_net+0x38c/0x770
Run control cleanup before protocol cleanup so that defense work and active sysctl handlers have finished before their protocol data is freed. Initialize protocols before exposing the control interface, and unwind in reverse order, to enforce the same lifetime on initialization failure. Protocol initialization and exit do not depend on control state.
--- net/netfilter/ipvs/ip_vs_core.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
net/netfilter/ipvs/ip_vs_core.c +6 -6
@@ -2319,12 +2319,12 @@ static int __net_init __ip_vs_init(strucif (ip_vs_estimator_net_init (ipvs) <0 ) goto estimator_fail; -if (ip_vs_control_net_init (ipvs) <0 ) - goto control_fail; -if (ip_vs_protocol_net_init (ipvs) <0 ) goto protocol_fail; +if (ip_vs_control_net_init (ipvs) <0 ) + goto control_fail; +if (ip_vs_app_net_init (ipvs) <0 ) goto app_fail;
@@ -2344,10 +2344,10 @@ sync_fail: conn_fail:ip_vs_app_net_cleanup (ipvs); app_fail: -ip_vs_protocol_net_cleanup (ipvs); -protocol_fail:ip_vs_control_net_cleanup (ipvs); control_fail: +ip_vs_protocol_net_cleanup (ipvs); +protocol_fail:ip_vs_estimator_net_cleanup (ipvs); estimator_fail: net->ipvs =NULL ;
@@ -2364,8 +2364,8 @@ static void __net_exit __ip_vs_cleanup_b ipvs =net_ipvs (net);ip_vs_conn_net_cleanup (ipvs);ip_vs_app_net_cleanup (ipvs); -ip_vs_protocol_net_cleanup (ipvs);ip_vs_control_net_cleanup (ipvs); +ip_vs_protocol_net_cleanup (ipvs);ip_vs_estimator_net_cleanup (ipvs);IP_VS_DBG (2 ,"ipvs netns %d released\n" , ipvs->gen); net->ipvs =NULL ;
Greg Kroah-Hartman
maintainerPATCH 596/816 gtp: free the skb after handling an echo response
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joas Antonio dos Santos <[email protected]>
commit f17b293d155f377e4cff582b8113991d2ad346d6 upstream.
gtp0_handle_echo_resp() and gtp1u_handle_echo_resp() return the result of genlmsg_multicast_netns() to gtp_encap_recv(). When the netlink notification is delivered that result is 0, and gtp_encap_recv() treats 0 as "the skb has been consumed":
switch (ret) {
case 1:
netdev_dbg(gtp->dev, "pass up to the process\n");
break;
case 0:
break;
case -1:
netdev_dbg(gtp->dev, "GTP packet has been dropped\n");
kfree_skb(skb);
ret = 0;
break;
}The echo response handlers only read from the skb and never free it or pass it on, so every echo response that is reported to a listener on the gtp multicast group leaks the skb. Echo responses are handled for any peer when the UDP sockets were created by the kernel, so a remote host can leak memory on the receiver by sending GTP echo responses while a process with CAP_NET_ADMIN is subscribed to the gtp multicast group, for example a daemon that monitors echo responses.
The error paths do not leak but have a related problem. -ENOMEM and the error from genlmsg_multicast_netns() (-ESRCH when nobody listens) are not -1, so they are returned unchanged to the UDP stack, which takes a negative value from encap_rcv() as a request to resubmit the packet to the protocol with that number.
Return -1 when the notification cannot be built, so that gtp_encap_recv() drops the skb, and consume the skb once the notification has been handed to netlink, whether or not anybody is listening.
Found by LLM-assisted source review, untested.
--- drivers/net/gtp.c | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-)
drivers/net/gtp.c +14 -8
@@ -556,16 +556,19 @@ static int gtp0_handle_echo_resp(struct msg =nlmsg_new (NLMSG_DEFAULT_SIZE ,GFP_ATOMIC );if (!msg) -return -ENOMEM ; +return -1 ; ret =gtp_genl_fill_echo (msg,0 ,0 ,0 ,GTP_CMD_ECHOREQ , echo);if (ret <0 ) {nlmsg_free (msg); -return ret; +return -1 ; } -return genlmsg_multicast_netns (>p_genl_family,dev_net (gtp->dev), - msg,0 ,GTP_GENL_MCGRP ,GFP_ATOMIC ); +genlmsg_multicast_netns (>p_genl_family,dev_net (gtp->dev), + msg,0 ,GTP_GENL_MCGRP ,GFP_ATOMIC ); +consume_skb (skb); + +return 0 ; }static int gtp_proto_to_family (__u16 proto)
@@ -742,16 +745,19 @@ static int gtp1u_handle_echo_resp(struct msg =nlmsg_new (NLMSG_DEFAULT_SIZE ,GFP_ATOMIC );if (!msg) -return -ENOMEM ; +return -1 ; ret =gtp_genl_fill_echo (msg,0 ,0 ,0 ,GTP_CMD_ECHOREQ , echo);if (ret <0 ) {nlmsg_free (msg); -return ret; +return -1 ; } -return genlmsg_multicast_netns (>p_genl_family,dev_net (gtp->dev), - msg,0 ,GTP_GENL_MCGRP ,GFP_ATOMIC ); +genlmsg_multicast_netns (>p_genl_family,dev_net (gtp->dev), + msg,0 ,GTP_GENL_MCGRP ,GFP_ATOMIC ); +consume_skb (skb); + +return 0 ; }static int gtp_parse_exthdrs (struct sk_buff *skb,unsigned int *hdrlen)
Greg Kroah-Hartman
maintainerPATCH 597/816 hv_netvsc: Stop PPI parsing on invalid metadata
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Erni Sri Satya Vennela <[email protected]>
commit 19a227903e65c7a9c179156485660a4e017575fe upstream.
rndis_get_ppi() uses continue when a per-packet information entry has an invalid size or offset, or cannot hold the requested metadata. However, the remaining length and entry pointer are only updated at the bottom of the loop. Each error path therefore retries the same invalid entry indefinitely, repeatedly logging the error and preventing receive processing from completing.
Return NULL on these validation failures instead of continuing. This terminates the lookup when malformed metadata is encountered while preserving the existing behavior for valid entries.
The issue was reported through an internal bug-tracking system and confirmed by manual code inspection. The pre-fix hang has not been reproduced locally.
--- drivers/net/hyperv/rndis_filter.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/net/hyperv/rndis_filter.c +3 -3
@@ -401,12 +401,12 @@ static inline void *rndis_get_ppi(struct/* Validate ppi_offset and ppi_size */ if (ppi->size > len) {netdev_err (ndev,"Invalid ppi size: %u\n" , ppi->size); -continue ; +return NULL ; }if (ppi->ppi_offset >= ppi->size) {netdev_err (ndev,"Invalid ppi_offset: %u\n" , ppi->ppi_offset); -continue ; +return NULL ; }if (ppi->type == type && ppi->internal == internal) {
@@ -414,7 +414,7 @@ static inline void *rndis_get_ppi(structif (ppi->size - ppi->ppi_offset < ppi_size) {netdev_err (ndev,"Invalid ppi: size %u ppi_offset %u\n" , ppi->size, ppi->ppi_offset); -continue ; +return NULL ; }return (void *)((ulong )ppi + ppi->ppi_offset); }
Greg Kroah-Hartman
maintainerPATCH 598/816 net: gro: avoid parsing headers from shared fragments
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 44818c9a826d766dc0e21179dc76f229334f1dda upstream.
When an skb has an empty linear head, skb_gro_reset_offset() can expose the first page fragment directly to GRO header parsers. For an SKBFL_SHARED_FRAG skb, those bytes may still be writable through a file mapping. Headers validated during receive can therefore differ from the headers later copied into the linear head and used during completion.
For example, changing an IPv6 destination-options length between the short and full header fetches in ipv6_gro_pull_exthdrs() can make ipv6_gro_complete() pass an out-of-bounds offset to udp6_gro_complete(). A userspace reproducer triggered a KASAN slab-out-of-bounds read there on an unmodified kernel as UID 1000. The same completion path can write the UDP checksum and length through the invalid offset. The packet has trusted TCP GSO metadata and spliced file data, so it reaches completion without an skb zerocopy destructor or a second GRO packet.
Disable the direct-fragment fast path for skbs with externally writable fragments. With an empty linear head, frag0_len remains zero, so skb_gro_header_slow() pulls each required header into the linear head before it is inspected. Subsequent pulls preserve the validated prefix. This covers both gro_receive_skb() and napi_gro_frags(), including other protocols using the same helpers. Linear headers and private fragments retain their existing fast paths.
Codex assisted with review of the supplied report, reproducer and draft fix, related-path analysis, and this changelog. The patched net/core/gro.o builds with W=1 using the supplied x86-64 configuration, allyesconfig and allmodconfig. The fix was checked by code-path analysis; the reproducer and kernel selftests have not been run on a booted patched kernel.
The issue was found by an LLM.
--- net/core/gro.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/core/gro.c +2 -1
@@ -418,7 +418,8 @@ static inline void skb_gro_reset_offset( headlen =skb_headlen (skb);NAPI_GRO_CB (skb)->frag0 = skb->data;NAPI_GRO_CB (skb)->frag0_len = headlen; -if (headlen) +/* Shared fragments must be pulled into the linear head before parsing. */ +if (headlen ||skb_has_shared_frag (skb))return ; pinfo =skb_shinfo (skb);
Greg Kroah-Hartman
maintainerPATCH 599/816 net: gro: do not undo remote checksum offload on merged packets
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
commit c817ec1b06875b98460fbd19591be541bc3fa924 upstream.
skb_gro_flush_final_remcsum() calls skb_gro_remcsum_cleanup() to undo the checksum adjustment done by skb_gro_remcsum_process() when the packet was not consumed by GRO.
When the inner handler merged the packet (NAPI_GRO_CB(skb)->same_flow is set), grc->offset can no longer be trusted:
- skb_gro_receive() either gives the frags or the head of the skb to the held packet, or uses __skb_pull(skb, offset) before adding the skb to the frag_list of the held packet.
- skb_gro_receive_list() uses skb_pull(skb, skb_gro_offset(skb)).
grc->offset is relative to the original skb->data, so the 2-byte read-modify-write done by skb_gro_remcsum_cleanup() can land in the payload of a packet which now belongs to the GRO packet. pskb_may_pull() can also be called on this frag_list member.
With fraglist GRO, this can also be a use-after-free:pskb_may_pull(skb, skb_gro_offset(skb)) in skb_gro_receive_list() or udp_gro_receive_segment() releases the first page fragment if it only contains headers. NAPI_GRO_CB(skb)->frag0 and frag0_len are not updated, so skb_gro_remcsum_cleanup() takes the fast path and writes through frag0 into a page the skb no longer holds a reference on. The non merged case, where frag0 is used after this pull, is handled in the following patch.
For skbs merged by skb_gro_receive(), the cleanup can be skipped:
the skb is freed, or its headers are rebuilt from the head skb in skb_segment().
Fraglist members keep their own inner headers, as skb_segment_list() only copies the link-layer and tunnel headers from the head skb. Their checksum can not be right in all cases: a packet forwarded with its tunnel header needs the original value, while a VXLAN packet decapsulated locally needs the adjusted one, as vxlan_remcsum() only adjusts the head skb. Make skb_gro_receive_list() refuse packets with skb->remcsum_offload set, so that fraglist members never carry an adjusted checksum.
This affects VXLAN (VXLAN_F_REMCSUM_NOPARTIAL) and GUE (FOU_F_REMCSUM_NOPARTIAL).
This was found while fixing a report from Taesoo Kim and Cen Zhang, who used LLM assisted code analysis and provided reproducers.
--- include/net/gro.h | 8 +++++++- net/core/gro.c | 7 +++++++ 2 files changed, 14 insertions(+), 1 deletion(-)
include/net/gro.h +7 -1
@@ -354,7 +354,13 @@ static inline void skb_gro_remcsum_cleanvoid *ptr;size_t plen = grc->offset +sizeof (u16); -if (!grc->delta) +/* Once merged, grc->offset can not be trusted: the frags or head +* of this skb now belong to the GRO packet, or skb->data was pulled +* past the headers before adding it to a frag_list. +* skb_gro_receive_list() does not merge packets with an adjusted +* checksum, other merged packets do not use their headers anymore. +*/ +if (!grc->delta ||NAPI_GRO_CB (skb)->same_flow)return ; ptr =skb_gro_header (skb, plen, grc->offset);
net/core/gro.c +7 -0
@@ -242,6 +242,13 @@ int skb_gro_receive_list(struct sk_buff NAPI_GRO_CB(skb)->flush))return -E2BIG ; +/* Fraglist members keep their own headers. Their checksum can not +* be right both for a forwarded packet and for a decapsulated one, +* if remote checksum offload adjusted it. +*/ +if (unlikely (skb->remcsum_offload)) +return -EINVAL ; +if (!pskb_may_pull (skb,skb_gro_offset (skb))) {NAPI_GRO_CB (skb)->flush =1 ;return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 600/816 netfilter: xt_recent: do not call remove_proc_entry() under recent_lock
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft) <[email protected]>
commit 17c2e41736b62cfe444c64d67860b1fbc1e886ac upstream.
recent_proc_net_exit() removes the /proc/net/xt_recent/<name> entries of a dying network namespace while holding spin_lock_bh(&recent_lock). remove_proc_entry() may sleep: proc_entry_rundown() waits until every task that is still inside the entry's file operations has left. A reader of such an entry is counted in by proc_reg_read() before recent_seq_start() takes recent_lock. So if a read is in flight when the namespace is torn down, cleanup_net() sleeps in atomic context holding the spinlock that the reader is spinning on, and neither side can ever make progress.
An unprivileged user can trigger this from a user namespace by adding a rule with the "recent" match and reading its proc file while the namespace is being destroyed. As recent_lock is global, every later attempt to take it spins forever too: the spinning can spread to all CPUs, and network namespace teardown stops system-wide.
BUG: sleeping function called from invalid context at
kernel/sched/completion.c:116
#3: (recent_lock){+...}-{3:3}, at: recent_net_exit+0x2b/0x140
Workqueue: netns cleanup_net
Call Trace:
proc_entry_rundown+0x185/0x1b0
remove_proc_entry+0x21a/0x520
recent_net_exit+0x7f/0x140
cleanup_net+0x414/0x8f0
...
rcu: INFO: rcu_preempt self-detected stall on CPU
Call Trace:
queued_spin_lock_slowpath+0x313/0xc20
recent_seq_start+0x87/0x1b0
seq_read_iter+0x265/0x11e0
proc_reg_read+0x1ab/0x270Fix by taking recent_mutex instead of recent_lock. According to commit a0e889bb1bdc ("[NETFILTER]: recent match: fix "sleeping function called from invalid context""), recent_mutex is the lock to use here: it protects recent_net->tables and was introduced so that proc entries are created and removed without recent_lock held, because those calls may sleep. hashlimit_proc_net_exit() does the same for xt_hashlimit.
--- net/netfilter/xt_recent.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
net/netfilter/xt_recent.c +4 -3
@@ -649,14 +649,15 @@ static void __net_exit recent_proc_net_e/* recent_net_exit() is called before recent_mt_destroy(). Make sure * that the parent xt_recent proc entry is empty before trying to -* remove it. +* remove it. Use recent_mutex instead of recent_lock since +* remove_proc_entry() may sleep. */ -spin_lock_bh (&recent_lock); +mutex_lock (&recent_mutex);list_for_each_entry (t, &recent_net->tables, list)remove_proc_entry (t->name, recent_net->xt_recent); recent_net->xt_recent =NULL ; -spin_unlock_bh (&recent_lock); +mutex_unlock (&recent_mutex);remove_proc_entry ("xt_recent" , net->proc_net); }
Greg Kroah-Hartman
maintainerPATCH 601/816 netfilter: flowtable: extend ct timeout of offloaded GRE flows
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michail Andreas Michalopoulos <[email protected]>
commit 46ecda278f6eedffb2898d41e3e56757c996a41f upstream.
Since commit 03428ca5cee9 ("netfilter: conntrack: rework offload nf_conn timeout extension logic"), the flowtable gc worker extends the timeout of an offloaded conntrack entry from nf_flow_table_extend_ct_timeout() once it falls below 5 minutes. That function only knows about TCP and UDP and hits WARN_ON_ONCE() for any other layer 4 protocol. However, GRE flows can be offloaded too, both via nft_flow_offload and act_ct, since commit 4e8d9584d154 ("netfilter: flowtable: Support GRE").
The timeout of an offloaded GRE entry drops below that threshold as soon as a packet of the flow still goes through conntrack. With ip6gre tunnels using the default encapsulation limit this is ordinary traffic:
the flowtable does not parse the Destination Options header in front of GRE, so every packet of the flow takes the classic forwarding path. It also happens for a packet with ttl <= 1, which the flowtable fast path passes up to the classic forwarding path. nf_conntrack_gre_packet() then refreshes ct->timeout to the GRE stream timeout (180 seconds by default), and the next gc run triggers, as reported by syzbot:
WARNING: net/netfilter/nf_flow_table_core.c:553 at nf_flow_table_extend_ct_timeout+0x1ee/0x2f0 Workqueue: events_power_efficient nf_flow_offload_work_gc Call Trace: nf_flow_offload_gc_step+0x545/0x7b0 nf_flow_table_iterate+0x13c/0x1f0 nf_flow_offload_work_gc+0x22/0x70 process_scheduled_works+0xc3d/0x1630 worker_thread+0xa47/0xfb0 kthread+0x38b/0x480
Besides the splat, which panics the machine with panic_on_warn, the default branch sets the new timeout to 1 jiffy, so the conntrack entry expires right away and the offloaded flow is torn down.
Handle GRE like UDP and extend the timeout to NF_CT_DAY. GRE conntrack has no protocol state to take into account, and NF_CT_DAY is also what flow_offload_add() already sets for every offloaded entry, GRE included. This also restores the behaviour from before commit 03428ca5cee9, when the conntrack gc worker extended offloaded entries of any protocol to NF_CT_DAY.
--- net/netfilter/nf_flow_table_core.c | 1 + 1 file changed, 1 insertion(+)
net/netfilter/nf_flow_table_core.c +1 -0
@@ -496,6 +496,7 @@ static void nf_flow_table_extend_ct_timeswitch (l4proto) {case IPPROTO_UDP : +case IPPROTO_GRE : new_timeout =NF_CT_DAY ;break ;case IPPROTO_TCP :
Greg Kroah-Hartman
maintainerPATCH 602/816 net/sched: sch_teql: reject qdiscs from another network namespace
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jamal Hadi Salim <[email protected]>
commit 1ae84bdd736f8fab30180159996e1d193f8029ff upstream.
Reported by shaos <[email protected]> with a reproducer, which was reproduced and verified in our test environment.
The issue:
The teql master devices are created once in the initial network namespace and their Qdisc_ops are global. teql_qdisc_init() takes the teql_master embedded in the registered sch->ops and uses it without checking whether the new qdisc's device lives in the same network namespace as the master. A qdisc created in another netns can therefore attach to the init-net master and change its MTU and flags.
The Fix:
Reject a teql qdisc whose device is not in the master's network namespace with -EOPNOTSUPP and an extack message; same-netns teql still works.
Initialize the private skb queue before any validation so every constructor failure path, including qdisc_create_dflt(), which resets the qdisc before destroying it, sees an initialized empty queue.
Conditions to recreate the bug:CONFIG_NET_SCH_TEQL=y, CONFIG_DUMMY=y, CONFIG_USER_NS=y, CONFIG_NET_NS=y. As an unprivileged UID, unshare a user and network namespace, create a dummy device, set its MTU to 60000, and add a root teql0 qdisc:
unshare -Urn
ip link add dummy0 type dummy
ip link set dummy0 mtu 60000
tc qdisc add dev dummy0 root teql0
The init-net teql0 device changes from MTU 1500 to 60000. A pfifo control on the same device leaves the MTU unchanged, and a direct MTU change on init-net teql0 is denied. The namespace needs CAP_NET_ADMIN; no init-net privilege is required. With the fix the attach fails with "Operation not supported" and the init-net MTU stays 1500.
--- net/sched/sch_teql.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
net/sched/sch_teql.c +7 -2
@@ -198,6 +198,8 @@ static int teql_qdisc_init(struct Qdiscstruct Qdisc *first;unsigned long flags; +skb_queue_head_init (&q->q); +if (dev->hard_header_len > m->dev->hard_header_len)return -EINVAL ;
@@ -209,9 +211,12 @@ static int teql_qdisc_init(struct Qdiscreturn -EOPNOTSUPP ; } - q->m = m; +if (dev_net (dev) !=dev_net (m->dev)) { +NL_SET_ERR_MSG_MOD (extack,"teql master is in a different network namespace" ); +return -EOPNOTSUPP ; + } -skb_queue_head_init (&q->q); + q->m = m;raw_spin_lock_irqsave (&m->slaves_lock, flags); first =rcu_dereference_protected (m->slaves,lockdep_is_held (&m->slaves_lock));
Greg Kroah-Hartman
maintainerPATCH 603/816 net/sched: act_ife: encode configured zero metadata values
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jamal Hadi Salim <[email protected]>
commit 7d02c07c738bf5c4b9a7d7ef498fbf465c446853 upstream.
Reported by shaos <[email protected]> with a reproducer for the 32-bit case, which was reproduced and verified in our test environment.
The issue:ife_check_meta_u32() and ife_check_meta_u16() both reserve eight bytes of metadata for a configured value even when that value is zero, but the matching encoder returns without calling ife_tlv_meta_encode(). The encoder therefore writes neither the TLV header nor its value, while the enclosing IFE length still includes the reserved bytes, exposing stale skb headroom contents to the peer.
The 32-bit helper has been present since the IFE action was introduced (v4.6); the 16-bit helper was added with the 16-bit metadata helpers used by the skbtcindex callback (v4.9). Both defects predate the oldest supported stable kernel (5.10), so they are fixed together in this patch. Each hunk keeps its own Fixes: tag for provenance.
The fix:
Encode any configured value, including zero; skip the TLV only when there is neither a configured nor a runtime value. The runtime fallback is unchanged.
A raw TCA_IFE_METALST netlink request is needed to express the configured zero: the IFE_META_SKBMARK attribute carries four zero payload bytes for the u32 helper, and IFE_META_TCINDEX two zero payload bytes for the 16-bit helper (not an absent or zero-length attribute). Stock tc cannot build these requests; "use mark 0x0" emits no mark attribute and "allow mark" emits a zero-length one.
Conditions to recreate the bug:CONFIG_NET_ACT_IFE=y, CONFIG_NET_IFE_SKBMARK=y, CONFIG_NET_IFE_SKBTCINDEX=y, CONFIG_NET_CLS_MATCHALL=y, CONFIG_NET_SCH_INGRESS=y, CONFIG_USER_NS=y, CONFIG_NET_NS=y, CONFIG_VETH=y. In a fresh user and network namespace create a veth pair and attach clsact to the egress side. Install a matchall filter whose ife encode action carries a zero skb mark (or a zero tcindex) in TCA_IFE_METALST. Send a frame through the veth and inspect the IFE metadata in the received frame. The metadata region is eight bytes but holds neither a valid TLV header nor a value; it exposes prior headroom contents. Setting the value to a nonzero one does not trigger the leak. The namespace needs CAP_NET_ADMIN; no additional privilege is required. With the fix the zero TLVs are 0001000800000000 (u32) and 0005000600000000 (u16).
--- net/sched/act_ife.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
net/sched/act_ife.c +2 -4
@@ -50,8 +50,7 @@ int ife_encode_meta_u16(u16 metaval, voi edata = *(u16 *)mi->metaval; else if (metaval) edata = metaval; - -if (!edata)/* will not encode */ + else return 0; edata =htons (edata);
@@ -94,8 +93,7 @@ int ife_encode_meta_u32(u32 metaval, voi edata = *(u32 *)mi->metaval; else if (metaval) edata = metaval; - -if (!edata)/* will not encode */ + else return 0; edata =htonl (edata);
Greg Kroah-Hartman
maintainerPATCH 604/816 net/sched: act_ife: require a full Ethernet header on egress
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jamal Hadi Salim <[email protected]>
commit 11dbce09083473249c3843ff31bf8d8fa01bdeef upstream.
This is a followup of commit 5b483f7791b0 ("net/sched: act_ife: Only operate on Ethernet frames") as reported by Sashiko.
The finding was raised by both Sashiko providers (nipa and gemini) while reviewing the parent patchset. shaos <[email protected]> independently reported the same undersized-egress path with a reproducer, which was reproduced and verified in our test environment.
The issue:
On egress tcf_ife_is_eth_skb() only checks the device type; it does not check that the skb carries a full Ethernet header. For an Ethernet or loopback device it returns true even when the skb has no Ethernet header. tcf_ife_encode() then calls ife_encode(), which copies ETH_HLEN bytes from skb->data. A short skb therefore reads past its linear data and the copied bytes, including stale kernel memory, are emitted in the outer Ethernet header.
The parent commit fixed the reported ingress mac_len case but left the egress path without a length check.
A total-length test is not sufficient: a non-GSO TUN skb can have a large total length while only a single byte sits in the linear area, so ife_encode() still reads past the linear header. Require instead that the Ethernet header the encoder copies is present in the linear part of the skb.
The Fix:
On egress require pskb_may_pull(skb, ETH_HLEN) before encoding, which ensures the Ethernet header is present in the linear data ife_encode() copies from; the ingress mac_len check is unchanged. A short egress skb is now dropped instead of being encoded.
Conditions to recreate the bug:CONFIG_NET_ACT_IFE=y, CONFIG_NET_CLS_MATCHALL=y, CONFIG_NET_SCH_INGRESS=y, CONFIG_TUN=y, CONFIG_NET_ACT_MIRRED=y. In two user and network namespaces (a victim and an attacker), open a TUN device in IFF_TUN mode and attach clsact to it and to lo. Redirect ingress traffic from the TUN device to lo egress with mirred, and install an ife encode action on lo egress:
tc qdisc add dev <tun> clsact
tc qdisc add dev lo clsact
tc filter add dev <tun> ingress matchall action mirred egress \
redirect dev lo
tc filter add dev lo egress matchall action ife encode use mark 1 \
action ok
Send a TUN packet shorter than ETH_HLEN (a one-byte payload is enough) and receive the emitted frame on the other side. Without the fix the outer Ethernet header contains bytes copied past the short packet; with the fix the short skb is dropped. The attacker needs CAP_NET_ADMIN in its user namespace; no init-net privilege is required.
The same path is reachable when the total length is large but the Ethernet header is not linear: write a non-GSO virtio header with hdr_len=1 followed by an 8192-byte packet so that only one byte stays linear. Without the fix the copied header reads past the linear data; with the fix the header is pulled into the linear area before the copy.
--- net/sched/act_ife.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
net/sched/act_ife.c +5 -2
@@ -871,13 +871,16 @@ drop:* is an Ethernet header because the skb could've been redirected with mirred * from a non-Ethernet device. */ -static bool tcf_ife_is_eth_skb (const struct sk_buff *skb) +static bool tcf_ife_is_eth_skb (struct sk_buff *skb) {if (skb->dev->type !=ARPHRD_ETHER && skb->dev->type !=ARPHRD_LOOPBACK )return false; -return !skb_at_tc_ingress (skb) || skb->mac_len ==ETH_HLEN ; +if (skb_at_tc_ingress (skb)) +return skb->mac_len ==ETH_HLEN ; + +return pskb_may_pull (skb,ETH_HLEN ); } TC_INDIRECT_SCOPE int tcf_ife_act(struct sk_buff *skb,
Greg Kroah-Hartman
maintainerPATCH 605/816 NFSv4: Prevent indefinite waits for out-of-order OPEN stateids
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Menninger <[email protected]>
commit 151d95a1e696979a7d54b23c96338754be2fcc1f upstream.
When processing an out-of-order OPEN stateid on an NFSv4.1 or later mount, nfs_set_open_stateid_locked() waits for stateid updates to be processed in order. A five-second timeout is intended to prevent indefinite waits when preceding updates never arrive.
However, each iteration calls schedule_timeout() with a fresh five-second timeout. An update to the shared open state can wake the caller without satisfying its ordering check. The remaining timeout is then discarded, and the next iteration starts another full wait.
Under sustained concurrent OPEN/CLOSE activity on the same open state, repeated wakeups can prevent the timeout from ever expiring. Some tasks can remain stuck in update_open_stateid() while others continue making progress.
Compute a single deadline on entry and pass only the remaining time to schedule_timeout(). Once the deadline expires, take the existing timeout path rather than starting another wait. This prevents wakeups from extending the wait indefinitely.
Observed on Linux 6.8.0 and reproduced on 7.3.0 with 96 concurrent O_RDWR|O_TRUNC open/close loops on one NFSv4.1/TCP file (nconnect=16). Ten workers made no progress for over 300 seconds while others ran. With the fix, all workers resumed after transient stalls.
--- fs/nfs/nfs4proc.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/nfs/nfs4proc.c +4 -1
@@ -1748,6 +1748,8 @@ static void nfs_set_open_stateid_locked( {DEFINE_WAIT (wait);int status =0 ; +unsigned long deadline = jiffies +5 *HZ ; +signed long remaining;for (;;) {if (nfs_stateid_is_sequential (state, stateid))
@@ -1782,7 +1784,8 @@ static void nfs_set_open_stateid_locked(if (!fatal_signal_pending (current) && !nfs_current_task_exiting ()) { -if (schedule_timeout (5 *HZ ) ==0 ) + remaining = (long )(deadline - jiffies); +if (remaining <=0 ||schedule_timeout (remaining) ==0 ) status = -EAGAIN ;else status =0 ;
Greg Kroah-Hartman
maintainerPATCH 606/816 openvswitch: advance by the real header length in get_ipv6_ext_hdrs()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joas Antonio dos Santos <[email protected]>
commit dbce972650ed6348e3d3856e49308aa5603e02a7 upstream.
get_ipv6_ext_hdrs() walks the IPv6 extension header chain to fill key->ipv6.exthdrs, but advances to the next header with ipv6_optlen() whatever the current header is. That is only right for Hop-by-Hop, Destination Options and Routing headers:
- an Authentication Header is ((hdrlen + 2) << 2) bytes long (ipv6_authlen()), so with hdrlen = 4 the walk skips 40 bytes instead of 24 and reads the next "header" from the ICV and payload;
- a Fragment header is always 8 bytes, and the byte read as hdrlen is its Reserved field, which the sender controls and receivers ignore, so a non-zero value makes the walk skip up to 2048 bytes and miss the headers that follow;
- in a non-first fragment nothing after the Fragment header is a header at all, it is the middle of the fragmentable part, yet the walk keeps parsing it as an extension header chain.
In all cases the OFPIEH12_* bits stored in key->ipv6.exthdrs depend on bytes chosen by the sender rather than on the headers that are actually
present: payload bytes that look like another AH or a Hop-by-Hop header add OFPIEH12_UNREP/OFPIEH12_UNSEQ, and real headers after a Fragment header can go unreported. Flows that match on OVS_KEY_ATTR_IPV6_EXTHDRS then classify such packets wrongly. There is no memory safety issue, skb_header_pointer() bounds every read.
Advance by sizeof(struct frag_hdr) for Fragment headers and by ipv6_authlen() for AH, and stop at the Fragment header if its offset is non-zero, as ipv6_find_hdr() does.
--- net/openvswitch/flow.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-)
net/openvswitch/flow.c +18 -1
@@ -374,11 +374,28 @@ static void get_ipv6_ext_hdrs(struct sk_return ; } +if (next_type ==IPPROTO_FRAGMENT ) { +struct frag_hdr _fh, *fh; + + fh =skb_header_pointer (skb, start,sizeof (_fh), &_fh); +if (!fh) +break ; +/* Only the first fragment has the headers that follow. */ +if (fh->frag_off &htons (IP6_OFFSET )) +break ; + start +=sizeof (_fh); + next_type = fh->nexthdr; +continue ; + } + hp =skb_header_pointer (skb, start,sizeof (_hdr), &_hdr);if (!hp)break ; +if (next_type ==IPPROTO_AH ) + start +=ipv6_authlen (hp); +else + start +=ipv6_optlen (hp); next_type = hp->nexthdr; - start +=ipv6_optlen (hp); } }
Greg Kroah-Hartman
maintainerPATCH 607/816 perf/core: Do not resurrect cpuctx->cgrp after last cgroup event exit
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Phat Dinh <[email protected]>
commit 59f1398140869432c7171b9a2a279ca315467c4e upstream.
perf_cgroup_switch() relies on:
/*
* cpuctx->cgrp is set when the first cgroup event enabled,
* and is cleared when the last cgroup event disabled. */
It computes the next task's cgroup, schedules out the CPU context and then assigns cpuctx->cgrp unconditionally:
ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
/*
* must not be done before ctxswout due
* to update_cgrp_time_from_cpuctx() in
* ctx_sched_out()
*/
cpuctx->cgrp = cgrp;However, ctx_sched_out() can disable events itself. If a cgroup event has a pending disable from perf_event_disable_inatomic() (e.g. its PERF_EVENT_IOC_REFRESH limit ran out) that the irq_work has not handled yet, event_sched_out() consumes it inline:
if (event->pending_disable) {
event->pending_disable = 0;
perf_cgroup_event_disable(event, ctx);
state = PERF_EVENT_STATE_OFF;
}If that was the last cgroup event, perf_cgroup_event_disable() clears cpuctx->cgrp:
if (--ctx->nr_cgroups)
return;
cpuctx->cgrp = NULL;and perf_cgroup_switch() then sets it again. cpuctx->cgrp is left non-NULL with ctx.nr_cgroups == 0, so the NULL check in perf_cgroup_switch() no longer catches it and the next switch trips:
WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
cpuctx->cgrp does not hold a reference on the cgroup. Once that cgroup is removed, the next ctx_sched_in() dereferences the stale pointer:
BUG: KASAN: slab-use-after-free in ctx_sched_in+0xb1f/0xfa0 Read of size 8 at addr ffff8881008972d0 by task swapper/3/0 Tainted: [W]=WARN Call Trace: <IRQ> ctx_sched_in+0xb1f/0xfa0 perf_event_sched_in+0x1a/0x70 ctx_resched+0x32b/0xac0 __perf_install_in_context+0x475/0xab0 remote_function+0x105/0x200 __flush_smp_call_function_queue+0x179/0x8d0 __sysvec_call_function_single+0x1b/0x1c0 sysvec_call_function_single+0x66/0x80 </IRQ> <TASK> asm_sysvec_call_function_single+0x1a/0x20
Only assign cpuctx->cgrp when cgroup events remain after the context has been scheduled out, so that it stays NULL as the invariant requires.
--- kernel/events/core.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
kernel/events/core.c +6 -1
@@ -925,8 +925,13 @@ static void perf_cgroup_switch(struct ta* must not be done before ctxswout due * to update_cgrp_time_from_cpuctx() in * ctx_sched_out() +* +* ctx_sched_out() can consume a pending disable and drop the last cgroup +* event, which clear the cpuctx->cgrp. Cgroup tracking follow active cgroup +* event, so do not resurrect it */ - cpuctx->cgrp = cgrp; +if (cpuctx->ctx.nr_cgroups) + cpuctx->cgrp = cgrp;/* * set cgrp before ctxsw in to allow * perf_cgroup_set_timestamp() in ctx_sched_in()
Greg Kroah-Hartman
maintainerPATCH 608/816 PM: runtime: Update last_busy in rpm_resume() for active devices
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rafael J. Wysocki <[email protected]>
commit 55b2b8af704f845e01fa2f31ee259b07641ce3a9 upstream.
Setting an autosuspend delay for a device can be expected to cause a runtime suspend of the device after calling, say, pm_runtime_put() to be deferred, so the time between the last successful attempt to resume the device and its subsequent suspend is at least equal to the autosuspend delay.
However, that expectation is only met after the device has been actually resumed in rpm_resume() by invoking its runtime resume callback. If the runtime PM status of the device is already "active" when rpm_resume() runs for it, the device's last_busy timestamp is not updated which may allow a subsequent pm_runtime_put() invocation (or similar) to suspend it right away.
This is arguably inconsistent and confusing, so make rpm_resume() also update the device's last_busy timestamp when it finds that the device is already "active" and it is about to return 1 early.
--- drivers/base/power/runtime.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/base/power/runtime.c +6 -0
@@ -797,6 +797,12 @@ static int rpm_resume(struct device *devpm_runtime_deactivate_timer (dev);if (dev->power.runtime_status ==RPM_ACTIVE ) { +/* +* The attempt to resume the device means that it is needed for +* something, so update its last_busy timestamp as in the case +* in which it actually resumes below. +*/ +pm_runtime_mark_last_busy (dev); retval =1 ; goto out; }
Greg Kroah-Hartman
maintainerPATCH 609/816 ASoC: SOF: ipc4-topology: Fix pin format leak in process widget setup
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baoli Zhang <[email protected]>
commit e5c09fe3f9c8d9da33b177ee432db15b6ab46884 upstream.
sof_ipc4_widget_setup_comp_process() allocates the input and output pin format arrays via sof_ipc4_get_audio_fmt(). When the following sof_ipc4_widget_setup_msg() fails, e.g. because the firmware does not provide a module matching the widget UUID, the error path jumps to the 'err' label, which frees the process struct and clears swidget->private but skips sof_ipc4_free_audio_fmt(). The arrays are then unreachable and are reported by kmemleak:
sof_ipc4_get_audio_fmt+0xc9/0x420 [snd_sof]
sof_ipc4_widget_setup_comp_process+0x8e/0x200 [snd_sof]
snd_sof_load_topology+0x71a/0x840 [snd_sof]
sof_pcm_probe+0x77/0x120 [snd_sof]
snd_soc_component_probe+0x21/0x60 [snd_soc_core]
...Jump to 'free_available_fmt' instead, as the other process widget error paths after sof_ipc4_get_audio_fmt() already do.
The other IPC4 widget setup functions (pga, mixer, src, asrc) free the audio formats in their common error label and are not affected.
--- sound/soc/sof/ipc4-topology.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/sof/ipc4-topology.c +1 -1
@@ -1003,7 +1003,7 @@ static int sof_ipc4_widget_setup_comp_pr ret =sof_ipc4_widget_setup_msg (swidget, &process->msg);if (ret) - goto err; + goto free_available_fmt;/* parse process init module payload config type from module info */ fw_module = swidget->module_info;
Greg Kroah-Hartman
maintainerPATCH 610/816 Bluetooth: hci_qca: fix use-after-free in ibs debugfs files
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: YuanZhe Liu <[email protected]>
commit eeca795cec6d9c6c193c2c1bd0cb26cde44f9fc3 upstream.
qca_debugfs_init() creates an "ibs" directory under hdev->debugfs and stores pointers to fields of struct qca_data in the debugfs files. qca_close() frees qca_data without removing that directory, while hdev->debugfs is only removed when the HCI device is released. The HCI device can outlive the driver data, for example when an HCI socket still references it, so reading or writing one of the ibs files then dereferences freed memory.
Store the directory dentry in struct qca_data and remove the directory with debugfs_remove_recursive() before qca_data is freed. debugfs_remove() waits for callers that are already inside the file operations, and any later access fails with -EIO instead of reaching the debugfs helpers. This covers the two writable files as well.
--- drivers/bluetooth/hci_qca.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/bluetooth/hci_qca.c +5 -0
@@ -160,6 +160,7 @@ struct qca_data {struct delayed_work ctrl_memdump_timeout;struct qca_memdump_info *qca_memdump;unsigned long flags; +struct dentry *debugfs_ibs_dir;struct completion drop_ev_comp;wait_queue_head_t suspend_wait_q;enum qca_memdump_states memdump_state;
@@ -652,6 +653,7 @@ static void qca_debugfs_init(struct hci_return ; ibs_dir =debugfs_create_dir ("ibs" , hdev->debugfs); + qca->debugfs_ibs_dir = ibs_dir;/* read only */ mode =0444 ;
@@ -727,6 +729,9 @@ static int qca_close(struct hci_uart *hu hu->priv =NULL ; +debugfs_remove_recursive (qca->debugfs_ibs_dir); + qca->debugfs_ibs_dir =NULL ; +kfree (qca);return 0 ;
Greg Kroah-Hartman
maintainerPATCH 611/816 Bluetooth: L2CAP: Keep recvmsg from resuming a closed channel
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 1f2ac56137c51be0601e18a163d817e02a15913f upstream.
Reading buffered ERTM data after ACL link loss can clear local busy and send a supervisory frame after l2cap_conn_del() has destroyed the HCI channel, which oopses on a NULL pointer in hci_send_acl(). The socket still owns its L2CAP channel, so its lifetime does not protect the underlying HCI channel.
Require BT_CONNECTED before clearing local busy in recvmsg. The socket lock already held here serializes this check and send with teardown, which closes the socket before the HCI channel is destroyed. Continue to allow buffered data to be read after disconnection.
AI assistance was used.
--- net/bluetooth/l2cap_sock.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/bluetooth/l2cap_sock.c +2 -1
@@ -1289,7 +1289,8 @@ static int l2cap_sock_recvmsg(struct soc* available. This avoids resending large numbers of * frames. */ -if (test_bit (CONN_LOCAL_BUSY , &pi->chan->conn_state) && +if (sk->sk_state ==BT_CONNECTED && +test_bit (CONN_LOCAL_BUSY , &pi->chan->conn_state) &&atomic_read (&sk->sk_rmem_alloc) <= sk->sk_rcvbuf >>1 )l2cap_chan_busy (pi->chan,0 );
Greg Kroah-Hartman
maintainerPATCH 612/816 cgroup/cpuset: Dont revive invalid partition without active CPU on hotplug
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ridong Chen <[email protected]>
commit acec9637e03ca54bd3c3a0c1a6ad5c6dfa07c0df upstream.
When a CPU hotplug leaves no CPU outside of the partitions for the top cpuset, cpuset_handle_hotplug() clears subpartitions_cpus and gives all the active CPUs back to the top cpuset. cpuset_hotplug_update_tasks() then walks the hierarchy and invalidates the partitions, as subpartitions_cpus is empty.
However, an invalid partition visited in the same walk may be revived if its effective_xcpus is not empty. tasks_nocpu_error() doesn't catch it when its CPUs are all offline but it has no task. Its CPUs are put back into subpartitions_cpus, and the valid partitions visited after it are no longer invalidated, as subpartitions_cpus is not empty any more. The top cpuset is left with CPUs overlapping with these partitions.
It can be reproduced on a system with 8 CPUs:
# cd /sys/fs/cgroup # echo +cpuset > cgroup.subtree_control # mkdir A1 B1 # echo 1 > A1/cpuset.cpus # echo 1 > A1/cpuset.cpus.exclusive # echo 0,2-7 > B1/cpuset.cpus # echo root > B1/cpuset.cpus.partition # echo root > A1/cpuset.cpus.partition # cat A1/cpuset.cpus.partition root invalid (Parent unable to distribute cpu downstream) # echo 0 > /sys/devices/system/cpu/cpu1/online # cat A1/cpuset.cpus.partition B1/cpuset.cpus.partition root root # cat cpuset.cpus.effective 0,2-7
A1 can't take CPU 1, the last CPU of the root cgroup which has tasks. When CPU 1 is offlined, A1 is revived without any active CPU, and B1 stays valid while its CPUs are also in the effective CPUs of the root cgroup, which triggers
WARNING: kernel/cgroup/cpuset.c:919 at rebuild_sched_domains_locked
Only revive an invalid partition in hotplug if its effective_xcpus has an active CPU, the same as what is required to create a partition with tasks. With that, A1 and B1 are both invalidated in the above case.
--- kernel/cgroup/cpuset.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +2 -2
@@ -3884,10 +3884,10 @@ retry: partcmd = partcmd_invalidate;/* * On the other hand, an invalid partition root may be transitioned -* back to a regular one with a non-empty effective xcpus. +* back to a regular one if its effective xcpus has an active CPU. */ else if (is_partition_valid(parent) && is_partition_invalid(cs) && - !cpumask_empty(cs->effective_xcpus)) + cpumask_intersects(cs->effective_xcpus, cpu_active_mask)) partcmd = partcmd_update;if (partcmd >=0 ) {
Greg Kroah-Hartman
maintainerPATCH 613/816 crypto: caam - reject overlong RSA CRT parameters
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 828c3b265b6df877dced3dde56ea41daa2e6181e upstream.
caam_read_rsa_crt() right-aligns dP, dQ, and qInv in buffers sized from the corresponding prime. rsa_parse_priv_key() only bounds these integers against n, so a malformed key can provide, for example, a two-byte dP with a one-byte p. dstlen - nbytes then underflows and memcpy() writes outside the allocation during set_priv_key(). KASAN reports a slab-out-of-bounds write in caam_read_rsa_crt().
Reject empty or overlong CRT parameters after stripping leading zeros. qInv is consumed by CAAM as a p-sized value, so size it from p rather than q to match the DMA mapping in set_rsa_priv_f3_pdb(). Let the top-level key cleanup handle partial form-3 allocations and return the specific error to the caller.
Also test nbytes before dereferencing it while stripping zeros, so an all-zero integer does not read one byte beyond its input.
--- drivers/crypto/caam/caampkc.c | 79 +++++++++++++++++------------------------- 1 file changed, 32 insertions(+), 47 deletions(-)
drivers/crypto/caam/caampkc.c +32 -47
@@ -880,7 +880,7 @@ static void caam_rsa_free_key(struct caastatic void caam_rsa_drop_leading_zeros (const u8 **ptr,size_t *nbytes) { -while (!**ptr && *nbytes) { +while (*nbytes && !**ptr) { (*ptr)++; (*nbytes)--; }
@@ -896,22 +896,22 @@ static void caam_rsa_drop_leading_zeros(* @ptr : pointer to {dP, dQ, qInv} CRT member * @nbytes: length in bytes of {dP, dQ, qInv} CRT member * @dstlen: length in bytes of corresponding p or q prime factor +* @dst : pointer to the zero-padded output buffer */ -static u8 *caam_read_rsa_crt (const u8 *ptr,size_t nbytes,size_t dstlen) +static int caam_read_rsa_crt (const u8 *ptr,size_t nbytes,size_t dstlen, +u8 **dst) { -u8 *dst; -caam_rsa_drop_leading_zeros (&ptr, &nbytes); -if (!nbytes) -return NULL ; +if (!nbytes || nbytes > dstlen) +return -EINVAL ; - dst =kzalloc (dstlen,GFP_KERNEL ); -if (!dst) -return NULL ; + *dst =kzalloc (dstlen,GFP_KERNEL ); +if (!*dst) +return -ENOMEM ; -memcpy (dst + (dstlen - nbytes), ptr, nbytes); +memcpy (*dst + (dstlen - nbytes), ptr, nbytes); -return dst; +return 0 ; }/**
@@ -991,6 +991,7 @@ static int caam_rsa_set_priv_key_form(stsize_t p_sz = raw_key->p_sz;size_t q_sz = raw_key->q_sz;unsigned aligned_size; +int ret; rsa_key->p =caam_read_raw_data (raw_key->p, &p_sz);if (!rsa_key->p)
@@ -999,57 +1000,39 @@ static int caam_rsa_set_priv_key_form(st rsa_key->q =caam_read_raw_data (raw_key->q, &q_sz);if (!rsa_key->q) - goto free_p; +return -ENOMEM ; rsa_key->q_sz = q_sz; aligned_size =ALIGN (raw_key->p_sz,dma_get_cache_alignment ()); rsa_key->tmp1 =kzalloc (aligned_size,GFP_KERNEL );if (!rsa_key->tmp1) - goto free_q; +return -ENOMEM ; aligned_size =ALIGN (raw_key->q_sz,dma_get_cache_alignment ()); rsa_key->tmp2 =kzalloc (aligned_size,GFP_KERNEL );if (!rsa_key->tmp2) - goto free_tmp1; +return -ENOMEM ; rsa_key->priv_form =FORM2 ; - rsa_key->dp =caam_read_rsa_crt (raw_key->dp, raw_key->dp_sz, p_sz); -if (!rsa_key->dp) - goto free_tmp2; - - rsa_key->dq =caam_read_rsa_crt (raw_key->dq, raw_key->dq_sz, q_sz); -if (!rsa_key->dq) - goto free_dp; - - rsa_key->qinv =caam_read_rsa_crt (raw_key->qinv, raw_key->qinv_sz, - q_sz); -if (!rsa_key->qinv) - goto free_dq; + ret =caam_read_rsa_crt (raw_key->dp, raw_key->dp_sz, p_sz, + &rsa_key->dp); +if (ret) +return ret; + + ret =caam_read_rsa_crt (raw_key->dq, raw_key->dq_sz, q_sz, + &rsa_key->dq); +if (ret) +return ret; + + ret =caam_read_rsa_crt (raw_key->qinv, raw_key->qinv_sz, p_sz, + &rsa_key->qinv); +if (ret) +return ret; rsa_key->priv_form =FORM3 ;return 0 ; - -free_dq: -kfree_sensitive (rsa_key->dq); - rsa_key->dq =NULL ; -free_dp: -kfree_sensitive (rsa_key->dp); - rsa_key->dp =NULL ; -free_tmp2: -kfree_sensitive (rsa_key->tmp2); - rsa_key->tmp2 =NULL ; -free_tmp1: -kfree_sensitive (rsa_key->tmp1); - rsa_key->tmp1 =NULL ; -free_q: -kfree_sensitive (rsa_key->q); - rsa_key->q =NULL ; -free_p: -kfree_sensitive (rsa_key->p); - rsa_key->p =NULL ; -return -ENOMEM ; } static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key,
@@ -1067,6 +1050,8 @@ static int caam_rsa_set_priv_key(structif (ret)return ret; + ret = -ENOMEM ; +/* Copy key in DMA zone */ rsa_key->d =kmemdup (raw_key.d, raw_key.d_sz,GFP_KERNEL );if (!rsa_key->d)
@@ -1103,7 +1088,7 @@ static int caam_rsa_set_priv_key(struct err:caam_rsa_free_key (rsa_key); -return -ENOMEM ; +return ret; }static unsigned int caam_rsa_max_size (struct crypto_akcipher *tfm)
Greg Kroah-Hartman
maintainerPATCH 614/816 crypto: essiv - fix use-after-free in AEAD path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit e9ce64dce975a14700e835003847415e29918474 upstream.
The request that ESSIV submits to its wrapped AEAD transform may finish before crypto_aead_encrypt() or crypto_aead_decrypt() returns. In case this happens, essiv_aead_done() calls aead_request_complete() on the original ESSIV request, which can end up freeing the request before essiv_aead_crypt() resumes, creating a UAF:
BUG: KASAN: slab-use-after-free in essiv_aead_crypt+0x8e6/0x950 Read of size 8 at addr ffff888102af1360 by task init/66
Check the return status before dereferencing rctx after submitting that request. If the operation did not return -EINPROGRESS or -EBUSY, then the request cannot have been freed yet.
--- crypto/essiv.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
crypto/essiv.c +1 -1
@@ -250,7 +250,7 @@ static int essiv_aead_crypt(struct aead_ err = enc ?crypto_aead_encrypt (subreq) :crypto_aead_decrypt (subreq); -if (rctx->assoc && err != -EINPROGRESS && err != -EBUSY ) +if (err != -EINPROGRESS && err != -EBUSY )kfree (rctx->assoc);return err; }
Greg Kroah-Hartman
maintainerPATCH 615/816 fs/adfs: bound directory entry name length in adfs_fplus_getnext()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
commit ebf5025b0d989f95542fc9da899b7de2fec499f2 upstream.
adfs_fplus_getnext() reads the per-entry name length bigdirobnamelen straight from the on-disk big directory and passes it to adfs_dir_copyfrom() as the copy length into obj->name[], a fixed ADFS_MAX_NAME_LEN (260) byte buffer. adfs_dir_copyfrom() only bounds the copy against the number of directory buffers, not the size of the destination, so a crafted image with bigdirobnamelen larger than the buffer overflows the stack-allocated object_info::name that adfs_fplus_iterate() passes in.
adfs_object_fixup() may additionally append a four byte ",xyz" filetype suffix, so the accepted length must also leave room for that.
The old-style directory parser (dir_f.c) already clamps names to ADFS_F_NAME_LEN, and adfs_fplus_validate_header() validates the header name fields, but the per-entry name length in the big directory format was never checked. Reject over-long entries, using -EIO as elsewhere in this file for a corrupt big directory.
--- fs/adfs/dir_fplus.c | 2 ++ 1 file changed, 2 insertions(+)
fs/adfs/dir_fplus.c +2 -0
@@ -192,6 +192,8 @@ adfs_fplus_getnext(struct adfs_dir *dir, obj->indaddr =le32_to_cpu (bde.bigdirindaddr); obj->attr =le32_to_cpu (bde.bigdirattr); obj->name_len =le32_to_cpu (bde.bigdirobnamelen); +if (obj->name_len >ADFS_MAX_NAME_LEN -4 )/* leave room for ,xyz suffix */ +return -EIO ; offset =adfs_fplus_offset (h,le32_to_cpu (h->bigdirentries)); offset +=le32_to_cpu (bde.bigdirobnameptr);
Greg Kroah-Hartman
maintainerPATCH 616/816 fs/proc: fix the write length returned by proc_sys_call_handler()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cheng Yongkang <[email protected]>
commit fbdc020ee1b82079102e493aaa7200de5f497a38 upstream.
proc_sys_call_handler() reads the write length from iov_iter_count() and copies that many bytes from the iterator into kbuf. A cgroup/sysctl BPF program can replace the new value through bpf_sysctl_set_new_value() and update count to the length of the replacement value. The handler then returns that adjusted count as the number of bytes written, even though the iterator originally held a different number of bytes.
If the replacement value is longer than the original input, ->write_iter() reports more bytes than the iterator held. splice(2) passes that value to iter_file_splice_write(), which subtracts it from the pipe length and walks past the pipe head:
Splice Exceeded! ret=7 tot=1 left=0
Oops: general protection fault RIP: 0010:iter_file_splice_write+0xb6f/0x1170
The write path consumes at most the original iterator length in copy_from_iter_full() before the BPF hook runs. Return the smaller of the adjusted and original counts on the write path, so an expanded BPF value cannot exceed the iterator while a handler that reports a shorter parsed length still produces a short write. The read path keeps using the adjusted count for copy_to_iter().
--- fs/proc/proc_sysctl.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/proc/proc_sysctl.c +4 -1
@@ -552,6 +552,8 @@ static ssize_t proc_sys_call_handler(strstruct ctl_table_header *head =grab_header (inode);struct ctl_table *table =PROC_I (inode)->sysctl_entry;size_t count =iov_iter_count (iter); +/* ->write_iter() must never report more than the iterator held */ +size_t orig_count = count;char *kbuf;ssize_t error;
@@ -602,7 +604,8 @@ static ssize_t proc_sys_call_handler(str goto out_free_buf; } - error = count; +/* the write path consumed at most the original iterator length */ + error = write ?min (count, orig_count) : count; out_free_buf:kvfree (kbuf); out:
Greg Kroah-Hartman
maintainerPATCH 617/816 fs/splice: clamp an over-reported write_iter result
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cheng Yongkang <[email protected]>
commit 2d956723e82cddae8ff8e9da99a666217b02065f upstream.
iter_file_splice_write() builds a bvec iterator of at most sd.total_len - left bytes and passes it to ->write_iter(). It then subtracts the returned length from sd.total_len and walks the pipe buffers by that length. A ->write_iter() implementation that reports more bytes than the iterator held makes sd.total_len underflow and the dismissal loop advance pipe->tail past pipe->head, releasing a zeroed pipe buffer:
Splice Exceeded! ret=7 tot=1 left=0
Oops: general protection fault RIP: 0010:iter_file_splice_write+0xb6f/0x1170
Commit a3de58b12ce0 ("netfs: Fix unbuffered write error handling") added the warning for this condition but only reports it. Clamp the return value to the size of the iterator that was actually handed to ->write_iter(), so the pipe accounting stays consistent even when a producer violates the iterator contract.
--- fs/splice.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
fs/splice.c +6 -3
@@ -744,9 +744,12 @@ iter_file_splice_write(struct pipe_inode sd.pos = kiocb.ki_pos;if (ret <=0 )break ; -WARN_ONCE (ret > sd.total_len - left, -"Splice Exceeded! ret=%zd tot=%zu left=%zu\n" , - ret, sd.total_len, left); +if (unlikely (ret > sd.total_len - left)) { +WARN_ONCE (1 , +"Splice Exceeded! ret=%zd tot=%zu left=%zu\n" , + ret, sd.total_len, left); + ret = sd.total_len - left; + } sd.num_spliced += ret; sd.total_len -= ret;
Greg Kroah-Hartman
maintainerPATCH 618/816 arm64: errata: Add Cortex-A715/A720 AMU core counter workaround
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Beata Michalska <[email protected]>
commit be777145858218f591b4d9d19f3d40d3ecea9de3 upstream.
On Cortex-A715 (erratum 2738462) and Cortex-A720 (erratum 2738461), the AMEVCNTR00 counter may continue incrementing while the core remains in WFE with the clocks being enabled. The resulting core cycle count may become unreliable.
Add a workaround that effectively treats the AMU counter as unavailable.
--- Documentation/arch/arm64/silicon-errata.rst | 4 +++ arch/arm64/Kconfig | 32 ++++++++++++++++++++++++++++ arch/arm64/kernel/cpu_errata.c | 20 +++++++++++++++++ arch/arm64/kernel/cpufeature.c | 3 +- arch/arm64/kernel/topology.c | 3 +- arch/arm64/tools/cpucaps | 1 6 files changed, 61 insertions(+), 2 deletions(-)
Documentation/arch/arm64/silicon-errata.rst +4 -0
@@ -160,8 +160,12 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A715 | #2645198 | ARM64_ERRATUM_2645198 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A715 | #2738462 | ARM64_ERRATUM_2738461 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A715 | #3456084 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A720 | #2738461 | ARM64_ERRATUM_2738461 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A720 | #3456091 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A725 | #3456106 | ARM64_ERRATUM_3194386 |
arch/arm64/Kconfig +32 -0
@@ -1030,6 +1030,38 @@ config ARM64_WORKAROUND_BROKEN_AMU_CONST # making it unreliable. As a result, AMU users should treat it as # unavailable rather than relying on misleading counter values. +config ARM64_WORKAROUND_BROKEN_AMU_CORECNT + bool + # Targeting errata affecting AMEVCNTR00, the AMU core cycle counter. + # On affected CPUs the counter may continue incrementing while core + # remains in WFE with the clocks enabled. + # This may lead to readings of said counter being unreliable. + # How much though depends on the sampling intervals. + +config ARM64_ERRATUM_2738461 + bool "Cortex-A715/Cortex-A720: workaround for AMEVCNTR00 incrementing incorrectly" + depends on ARM64_AMU_EXTN + select ARM64_WORKAROUND_BROKEN_AMU_CORECNT + default y + help + This option adds the workaround for the following errata: + + * ARM Cortex-A715 erratum 2738462 + * ARM Cortex-A720 erratum 2738461 + + On affected cores the AMEVCNTR00 counter (AMU core frequency cycles + counter) may continue incrementing while the core remains in WFE + with the clocks being enabled. + This may result in inaccurate counter readings, with the magnitude + of the discrepancy depending on the sampling interval. + + With this workaround, reads of the affected counter return 0 in + the relevant paths. This causes users of the counter to treat it + as unavailable and is functionally equivalent to firmware disabling + the affected counter. + + If unsure, say Y. + config ARM64_ERRATUM_2457168 bool "Cortex-A510: 2457168: workaround for AMEVCNTR01 incrementing incorrectly" depends on ARM64_AMU_EXTN
arch/arm64/kernel/cpu_errata.c +20 -0
@@ -273,6 +273,18 @@ static const struct midr_range workaroun };#endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT */ +#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT +static const struct midr_range workaround_amu_corecnt_list[] = { +#ifdef CONFIG_ARM64_ERRATUM_2738461 +/* Cortex-A715 r0p0 - r1p3 */ +MIDR_RANGE (MIDR_CORTEX_A715 ,0 ,0 ,1 ,3 ), +/* Cortex-A720 r0p0 - r0p1 */ +MIDR_RANGE (MIDR_CORTEX_A720 ,0 ,0 ,0 ,1 ), +#endif + {} +}; +#endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT */ +#ifdef CONFIG_CAVIUM_ERRATUM_23154 static const struct midr_range cavium_erratum_23154_cpus[] = { MIDR_ALL_VERSIONS(MIDR_THUNDERX),
@@ -772,6 +784,14 @@ const struct arm64_cpu_capabilities arm6 CAP_MIDR_RANGE_LIST(workaround_amu_constcnt_list) },#endif +#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT + { + .desc = "Broken AMU AMEVCNTR00 (core cycle counter)", + .capability = ARM64_WORKAROUND_BROKEN_AMU_CORECNT, + .type = ARM64_CPUCAP_WEAK_LOCAL_CPU_FEATURE, + CAP_MIDR_RANGE_LIST(workaround_amu_corecnt_list) + }, +#endif #ifdef CONFIG_ARM64_ERRATUM_2038923 { .desc = "ARM erratum 2038923",
arch/arm64/kernel/cpufeature.c +2 -1
@@ -2070,7 +2070,8 @@ static void cpu_amu_enable(struct arm64_cpumask_set_cpu (smp_processor_id (), &amu_cpus);/* 0 reference values signal broken/disabled counters */ -if (!this_cpu_has_cap (ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT )) +if (!this_cpu_has_cap (ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT ) && + !this_cpu_has_cap (ARM64_WORKAROUND_BROKEN_AMU_CORECNT ))update_freq_counters_refs (); } }
arch/arm64/kernel/topology.c +2 -1
@@ -260,7 +260,8 @@ static void cpu_read_corecnt(void *val)* counter read is properly handled as an error case by the users of the * counter. */ - *(u64 *)val =read_corecnt (); + *(u64 *)val =this_cpu_has_cap (ARM64_WORKAROUND_BROKEN_AMU_CORECNT ) ? +0UL :read_corecnt (); }static void cpu_read_constcnt (void *val)
arch/arm64/tools/cpucaps +1 -0
@@ -105,3 +105,4 @@ WORKAROUND_SPECULATIVE_AT WORKAROUND_SPECULATIVE_SSBS WORKAROUND_SPECULATIVE_UNPRIV_LOAD WORKAROUND_BROKEN_AMU_CONSTCNT +WORKAROUND_BROKEN_AMU_CORECNT
Greg Kroah-Hartman
maintainerPATCH 619/816 arm64: ptrace: dont warn on missing siginfo in a group-stop
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Gongyi <[email protected]>
commit 5306f124f3171289b2ef5bac1e08aad175f66d1e upstream.
PTRACE_ATTACH to a group-stopped child can enter do_jobctl_trap(), which calls ptrace_stop() without siginfo. If the tracer writes NT_ARM_SYSTEM_CALL, system_call_set() can change syscallno from NO_SYSCALL before update_syscall_orig_x0_after_ptrace() checks last_siginfo. WARN_ON_ONCE(!info) then fires for a valid ptrace stop.
Keep the early return when siginfo is absent, but remove the warning. This leaves orig_x0 untouched at a non-seized group-stop and preserves the existing syscall-exit-stop handling.
--- arch/arm64/kernel/ptrace.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
arch/arm64/kernel/ptrace.c +6 -2
@@ -572,8 +572,12 @@ static void update_syscall_orig_x0_afterif (regs->syscallno ==NO_SYSCALL )return ; -/* We should only be called when target is in a ptrace stop */ -if (WARN_ON_ONCE (!info)) +/* +* For exit-stops, info is always non-NULL, but that's not true for other +* stops such as non-seized group-stops. In those cases, just return early +* as there's no need to update orig_x0 anyway. +*/ +if (!info)return ;/*
Greg Kroah-Hartman
maintainerPATCH 620/816 arm64: suspend: Save POR_EL0 over suspend
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mark Brown <[email protected]>
commit 2386c3dcf13e39d7576eae821af66537332c02de upstream.
POR_EL0 is a live EL0 register on systems with S1POE but it is not saved and restored by cpu_do_suspend()/cpu_do_resume(). This means that the task that initiated suspend can return to userspace with an UNKNOWN value. Fix this by saving and restoring the value over suspend.
This increases the size of struct cpu_suspend_ctx.
--- arch/arm64/include/asm/suspend.h | 2 +- arch/arm64/mm/proc.S | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-)
arch/arm64/include/asm/suspend.h +1 -1
@@ -2,7 +2,7 @@#ifndef __ASM_SUSPEND_H#define __ASM_SUSPEND_H -#define NR_CTX_REGS 15 +#define NR_CTX_REGS 16#define NR_CALLEE_SAVED_REGS 12/*
arch/arm64/mm/proc.S +8 -0
@@ -108,6 +108,10 @@ alternative_if ARM64_SME mrs_s x2, SYS_TPIDR2_EL0 str x2, [x0, #112] alternative_else_nop_endif +alternative_if ARM64_HAS_S1POE + mrs x2, REG_POR_EL0 + str x2, [x0, #120] +alternative_else_nop_endif ret SYM_FUNC_END(cpu_do_suspend)
@@ -150,6 +154,10 @@ alternative_if ARM64_SME ldr x2, [x0, #112] msr_s SYS_TPIDR2_EL0, x2 alternative_else_nop_endif +alternative_if ARM64_HAS_S1POE + ldr x2, [x0, #120] + msr REG_POR_EL0, x2 +alternative_else_nop_endif msr sctlr_el1, x12 set_this_cpu_offset x13
Greg Kroah-Hartman
maintainerPATCH 621/816 cpufreq: acpi-cpufreq: fix P-state index mismatch in extract_io()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li RongQing <[email protected]>
commit 6bc092a0fc4d331a4adbbb664078af149c580834 upstream.
When policy->freq_table is built in acpi_cpufreq_cpu_init(), entries that are not lower in frequency than the previous one are skipped. For each remaining entry, freq_table[].driver_data stores the original ACPI P-state index, so the index space of freq_table no longer matches perf->states[].
extract_io() currently walks perf->states[] with index i and uses the same i to index policy->freq_table[i]. When duplicate frequencies exist, this can associate a P-state status with the frequency of a different P-state. It can also access an invalid or sentinel entry in freq_table when the number of entries in perf->states[] is greater than the number of entries remaining in the frequency table.
extract_io() is used on ACPI_ADR_SPACE_SYSTEM_IO platforms by the frequency verification path, which is enabled by the acpi_pstate_strict module parameter. With the mismatched lookup, check_freqs() can fail to match the frequency of the P-state that drv_write() has already programmed. It then sleeps through all 100 iterations - at least ~1 ms of usleep_range() plus 100 cross-CPU calls and I/O port reads, all with policy->rwsem held, and .target_index() returns -EAGAIN, leaving perf->state at its previous value while the hardware is running at the newly requested P-state.
The cpufreq core consequently keeps policy->cur at the old frequency. Since __cpufreq_driver_target() returns early when the requested frequency equals policy->cur, the driver is not called again for that frequency and the control register is not rewritten. The hardware can therefore remain at a frequency that differs from the frequency known to the cpufreq core.
Fix this by iterating over policy->freq_table and using pos->driver_data as the original ACPI P-state index when accessing perf->states[], as extract_msr() already does.
--- drivers/cpufreq/acpi-cpufreq.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-)
drivers/cpufreq/acpi-cpufreq.c +4 -5
@@ -200,14 +200,13 @@ static unsigned extract_io(struct cpufre {struct acpi_cpufreq_data *data = policy->driver_data;struct acpi_processor_performance *perf; -int i; +struct cpufreq_frequency_table *pos; perf =to_perf_data (data); -for (i =0 ; i < perf->state_count; i++) { -if (value == perf->states[i].status) -return policy->freq_table[i].frequency; - } +cpufreq_for_each_entry (pos, policy->freq_table) +if (value == perf->states[pos->driver_data].status) +return pos->frequency;return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 622/816 cpufreq: intel_pstate: Clear last written P-state value on suspend
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rafael J. Wysocki <[email protected]>
commit 02e77af824d5be3a94fdd885835a352f90d24c5c upstream.
Preserving cpu->pstate.current_pstate across system suspend-resume cycles, when running in the passive mode with HWP disabled, is a mistake because its value from before system suspend may become stale after the subsequent system resume and in some cases it prevents MSR_IA32_PERF_CTL from being updated properly after system resume [1].
Address this by clearing cpu->pstate.current_pstate after the governor has been stopped during system suspend.
--- drivers/cpufreq/intel_pstate.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/cpufreq/intel_pstate.c +13 -1
@@ -3322,10 +3322,11 @@ static void intel_cpufreq_cpu_exit(strucstatic int intel_cpufreq_suspend (struct cpufreq_policy *policy) { +struct cpudata *cpu = all_cpu_data[policy->cpu]; +intel_pstate_suspend (policy);if (hwp_active) { -struct cpudata *cpu = all_cpu_data[policy->cpu];u64 value =READ_ONCE (cpu->hwp_req_cached);/*
@@ -3336,6 +3337,17 @@ static int intel_cpufreq_suspend(struct value &= ~HWP_DESIRED_PERF (~0L );wrmsrl_on_cpu (cpu->cpu,MSR_HWP_REQUEST , value);WRITE_ONCE (cpu->hwp_req_cached, value); + }else { +/* +* Invalidate the cached P-state value that may be stale when +* the governor is started again during resume and may prevent +* MSR_IA32_PERF_CTL from being updated. +* +* This does not require synchronization because the core +* prevents frequency updates for suspended policies from +* occurring. +*/ + cpu->pstate.current_pstate =0 ; }return 0 ;
Greg Kroah-Hartman
maintainerPATCH 623/816 cpufreq: Cache post-resolution target frequency in __resolve_freq()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rafael J. Wysocki <[email protected]>
commit 166207cac45191637c47a457a5c16ca6b6773a16 upstream.
get_next_freq() in the schedutil governor returns the resolved frequency from cpufreq_driver_resolve_freq(), and that resolved value is then passed to cpufreq_driver_fast_switch(). The only reader of cached_target_freq, acpi_cpufreq_fast_switch(), compares it with the post-resolution target frequency, but it holds the pre-resolution clamped frequency, so any request that falls between table entries misses the cache and falls back to a table scan.
Address this by making __resolve_freq() store the post-resolution frequency in cached_target_freq.
--- drivers/cpufreq/cpufreq.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/cpufreq/cpufreq.c +2 -2
@@ -548,8 +548,8 @@ static unsigned int __resolve_freq(struc idx =cpufreq_frequency_table_target (policy, target_freq, min, max, relation); policy->cached_resolved_idx = idx; - policy->cached_target_freq = target_freq; -return policy->freq_table[idx].frequency; + policy->cached_target_freq = policy->freq_table[idx].frequency; +return policy->cached_target_freq; }/**
Greg Kroah-Hartman
maintainerPATCH 624/816 software node: only let the owner release a managed node
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit f8623ce596492d2e96ca57eeec992938d3d79f00 upstream.
device_create_managed_software_node() creates a node whose lifetime is tied to the device it was created for. software_node_notify_remove() is called for every device that has the node as its fwnode (primary OR secondary) and, if the node is managed, unconditionally detaches it from that device and drops the creation reference.
This breaks when the node is shared with another device. Example: the i2c-designware copies the parent's fwnode to the adapter's struct device. When the adapter is deleted, it releases the reference that belongs to the owner and the latter ends up with a dangling pointer.
Record the device's "manager" and only perform the actual release when notify is called for that "owner" device.
Note that it was never the intention that managed software nodes would be shared, but descendants reusing ancestor firmware nodes is not uncommon and such use is hard to predict when allocating software nodes.
[ johan: drop temporary variable; skip clearing owner field;
mention reuse not intended in commit message ]
--- drivers/base/swnode.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/base/swnode.c +4 -3
@@ -29,6 +29,8 @@ struct swnode {struct fwnode_handle fwnode;const struct software_node *node;int id; +/* Device the managed node's lifetime is tied to. */ +struct device *owner;/* hierarchy */ struct ida child_ids;
@@ -37,7 +39,6 @@ struct swnode {struct swnode *parent; unsigned int allocated:1; - unsigned int managed:1; };static DEFINE_IDA (swnode_root_ids);
@@ -1060,7 +1061,7 @@ int device_create_managed_software_node(if (IS_ERR (fwnode))return PTR_ERR (fwnode); -to_swnode (fwnode)->managed = true; +to_swnode (fwnode)->owner = dev;set_secondary_fwnode (dev, fwnode);if (device_is_registered (dev))
@@ -1104,7 +1105,7 @@ void software_node_notify_remove(structsysfs_remove_link (&dev->kobj,"software_node" );kobject_put (&swnode->kobj); -if (swnode->managed) { +if (swnode->owner == dev) {set_secondary_fwnode (dev,NULL );kobject_put (&swnode->kobj); }
Greg Kroah-Hartman
maintainerPATCH 625/816 SUNRPC: Fix TCP-with-TLS transport class identification
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
commit 0502c7e7f171a8c9c892bdef89e6aa6f44d7b2a3 upstream.
xs_setup_tcp_tls() assigns the ordinary TCP transport class to a TCP-with-TLS transport. When rpc_clnt_add_xprt() is called with an unspecified transport type, it inherits the class identifier and can create an unencrypted TCP transport.
Looks like a copy-paste error from the commit 3 years ago.
NFSv4 trunk discovery uses an unspecified transport type when adding server-advertised addresses. If the additional transport passes server-identity validation, it can be admitted to the client's transport switch.
An isolated loopback test reproduced plaintext application RPC transmission for TLS- and mTLS-configured clients, including an unpinned TLS-client RPC that selected the added transport.
Assign the TCP-with-TLS class instead. With the fix, the plaintext-only test peer receives TLS negotiation probes but no application payloads.
--- net/sunrpc/xprtsock.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sunrpc/xprtsock.c +1 -1
@@ -3534,7 +3534,7 @@ static struct rpc_xprt *xs_setup_tcp_tls transport = container_of(xprt, struct sock_xprt, xprt); xprt->prot =IPPROTO_TCP ; - xprt->xprt_class = &xs_tcp_transport; + xprt->xprt_class = &xs_tcp_tls_transport; xprt->max_payload =RPC_MAX_FRAGMENT_SIZE ; xprt->bind_timeout =XS_BIND_TO ;
Greg Kroah-Hartman
maintainerPATCH 626/816 timekeeping: Read getboottime64() offsets under the sequence counter
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
commit 385b5ec1f31dd39297578eed42be74b07ae74017 upstream.
getboottime64() computes the wall-clock boot timestamp from offs_real minus offs_boot without checking tk_core.seq. A concurrent timekeeping update can leave the reader with an inconsistent pair of offsets or, on 32-bit systems, a torn 64-bit offset, producing an incorrect boot timestamp.
Read both offsets under tk_core.seq and retry if an update overlaps the sample. Convert the resulting local value to a timespec64 afterward.
--- kernel/time/timekeeping.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
kernel/time/timekeeping.c +7 -1
@@ -2296,7 +2296,13 @@ void update_wall_time(void)void getboottime64 (struct timespec64 *ts) {struct timekeeper *tk = &tk_core.timekeeper; -ktime_t t =ktime_sub (tk->offs_real, tk->offs_boot); +unsigned int seq; +ktime_t t; + +do { + seq =read_seqcount_begin (&tk_core.seq); + t =ktime_sub (tk->offs_real, tk->offs_boot); + }while (read_seqcount_retry (&tk_core.seq, seq)); *ts =ktime_to_timespec64 (t); }
Greg Kroah-Hartman
maintainerPATCH 627/816 tpm: acpi: Fix memory leak at tpm_read_log_acpi() error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Takashi Iwai <[email protected]>
commit 03fcb358249dc715124b3616f814ea0ecc6ec36c upstream.
When devm_add_action() returns an error, tpm_read_log_acpi() clears log->bios_event_log unnecessarily to NULL before calling tpm_bios_log_free(), and it would lead to a memory leak of the allocated log buffer.
Fix it by simply jumping to the err.
--- drivers/char/tpm/eventlog/acpi.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/char/tpm/eventlog/acpi.c +1 -3
@@ -167,10 +167,8 @@ int tpm_read_log_acpi(struct tpm_chip *c } ret =devm_add_action (&chip->dev, tpm_bios_log_free, log->bios_event_log); -if (ret) { - log->bios_event_log =NULL ; +if (ret) goto err; - }return format;
Greg Kroah-Hartman
maintainerPATCH 628/816 tpm: Check return value of crypto_kpp_set_secret()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Biggers <[email protected]>
commit 8cff8f1c89d33e55c9af82177b14f6f9f6a899fe upstream.
crypto_kpp_set_secret() can fail, for example if the kernel is booted with fips=1 and the broken-by-design FIPS RNG used for ECC private key generation doesn't feel like generating random bytes at the moment. Check for error, cancelling the TPM session creation rather than proceeding with a zero or uninitialized private key.
--- drivers/char/tpm/tpm2-sessions.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm2-sessions.c +3 -1
@@ -579,7 +579,9 @@ static int tpm_buf_append_salt(struct tp }crypto_ecdh_encode_key (encoded_key, buf_len, &p);/* this generates a random private key */ -crypto_kpp_set_secret (kpp, encoded_key, buf_len); + rc =crypto_kpp_set_secret (kpp, encoded_key, buf_len); +if (rc) + goto err_free_kpp;/* salt is now the public point of this private key */ req =kpp_request_alloc (kpp,GFP_KERNEL );
Greg Kroah-Hartman
maintainerPATCH 629/816 tpm: eventlog: check the payload size before reading tag events
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guanglei Zhu <[email protected]>
commit 0a385f668ba77d29ae167c1668fd452418ebc9d6 upstream.
The EVENT_TAG branch of get_event_name() casts the event payload to struct tcpa_pc_event and reads from it:
pc_event = (struct tcpa_pc_event *)event_entry;
switch (do_endian_conversion(pc_event->event_id)) {
...
for (i = 0; i < 20; i++)
d_len += sprintf(&data[2*i], "%02x",
pc_event->event_data[i]);The log iterators only verify that the event header plus the declared event_size stays within the log buffer; they do not require the payload of an EVENT_TAG entry to be large enough for the fields the branch reads. A truncated entry makes the branch read up to 20 bytes of event_data[] past the end of the entry, and, for the last entry in the log, past the end of the buffer itself.
The legacy PC Client spec defines the EV_EVENT_TAG payload as a TCPA_PC_EVENT - event_id, event_size and event-type-specific data - so a conformant entry carries the 8-byte header and the hash-type ids carry a full digest. The log itself, however, is an ACPI table the firmware leaves in memory: the TPM never measures the log, so the kernel cannot tell a conformant log from a corrupted one. The iterators already work on that assumption - they stop once the declared event_size runs past the buffer end - and the readers should apply the same rule to what they take off the payload.
Skip entries whose payload cannot even hold the event id, and skip the 20-byte digest dump when the payload cannot hold the full tcpa_pc_event header plus the digest, so the branch never reads beyond the entry it is formatting.
--- drivers/char/tpm/eventlog/tpm1.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/char/tpm/eventlog/tpm1.c +7 -0
@@ -178,6 +178,10 @@ static int get_event_name(char *dest, st }break ;case EVENT_TAG : +if (do_endian_conversion (event->event_size) < +sizeof (pc_event->event_id)) +break ; + pc_event = (struct tcpa_pc_event *)event_entry;/* ToDo Row data -> Base64 */
@@ -203,6 +207,9 @@ static int get_event_name(char *dest, st name = tcpa_pc_event_id_strings[do_endian_conversion (pc_event->event_id)]; n_len =strlen (name); +if (do_endian_conversion (event->event_size) < +sizeof (struct tcpa_pc_event ) +20 ) +break ;for (i =0 ; i <20 ; i++) d_len +=sprintf (&data[2 *i],"%02x" , pc_event->event_data[i]);
Greg Kroah-Hartman
maintainerPATCH 630/816 x86/mm: Ensure write visibility during LDT installation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Hansen <[email protected]>
commit 0dc2a4dac3d04e9e4479aeb0b46172feab1cca0a upstream.
During LDT installation, the intent is to overwrite the old per-mm LDT value, then send an IPI to the mm user CPUs to have each load the new value.
But there is an ordering problem: a new mm user CPU sets itself in mm_cpumask() and then reads mm->context.ldt. The LDT-installing CPU writes mm->context.ldt and then reads mm_cpumask(). But, there is nothing which orders the LDT installation side actions. The CPU can read mm_cpumask() before its write becomes visible.
Ensure that new mm user CPUs see the new mm->context.ldt. Make mm->context.ldt visible before reading mm_cpumask().
Also convert the smp_store_release() over to a WRITE_ONCE(). smp_store_release() has an internal barrier which is weaker than the new smp_mb(). Avoid an extra barrier by converting it to WRITE_ONCE().
Also refresh/correct misleading comments. READ/WRITE_ONCE() do not "synchronize" anything themselves.
--- arch/x86/kernel/ldt.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
arch/x86/kernel/ldt.c +9 -3
@@ -43,7 +43,7 @@ void load_mm_ldt(struct mm_struct *mm) {struct ldt_struct *ldt; -/* READ_ONCE synchronizes with smp_store_release */ +/* Pairs with WRITE_ONCE() in install_ldt() */ ldt =READ_ONCE (mm->context.ldt);/*
@@ -422,8 +422,14 @@ static void install_ldt(struct mm_struct {mutex_lock (&mm->context.lock); -/* Synchronizes with READ_ONCE in load_mm_ldt. */ -smp_store_release (&mm->context.ldt, ldt); +/* +* Ensure that new mm user CPUs either see the new LDT value +* or get an IPI. Make the store visible before reading +* mm_cpumask(). New mm users make their mm_cpumask() writes +* visible before reading mm->context.ldt. +*/ +WRITE_ONCE (mm->context.ldt, ldt); +smp_mb ();/* Activate the LDT for all CPUs using currents mm. */ on_each_cpu_mask (mm_cpumask (mm), flush_ldt, mm, true);
Greg Kroah-Hartman
maintainerPATCH 631/816 xen/gntdev: fix deadlock between map ioctl and mmap
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
commit 7620a997e4854c94eacebf0c2d453fbd78ccdb46 upstream.
Commit 45ca1afe2fd1 ("xen/gntdev: fix error handling in ioctl") moved copy_to_user() in gntdev_ioctl_map_grant_ref() under priv->lock. A fault in copy_to_user() takes mmap_lock, while gntdev_mmap() is called with mmap_lock held and takes priv->lock:
ioctl thread mmap thread
mutex_lock(&priv->lock)
mmap_write_lock(mm)
gntdev_mmap()
mutex_lock(&priv->lock) copy_to_user() faults
mmap_read_lock(mm)
Reproduced on Debian 6.12.111 in a Xen guest, with the ioctl argument on a MAP_PRIVATE file page that has not been written yet. sysrq-w:
task:repro state:D stack:0 pid:4479 tgid:4477 ppid:1 flags:0x00000000
rwsem_down_read_slowpath+0x25c/0x480 down_read_killable+0x48/0xc0 lock_mm_and_find_vma+0x96/0x250 do_user_addr_fault+0x12d/0x620 exc_page_fault+0x7e/0x180 asm_exc_page_fault+0x26/0x30 _copy_to_user+0x36/0x50 gntdev_ioctl+0x3b9/0xa00 [xen_gntdev] __x64_sys_ioctl+0x97/0xc0 task:repro state:D stack:0 pid:4480 tgid:4477 ppid:1 flags:0x00000000 __mutex_lock.constprop.0+0x41b/0x720 gntdev_mmap+0x4d/0x330 [xen_gntdev] __mmap_region+0x697/0xb10 mmap_region+0x78/0xa0 do_mmap+0x45d/0x630 vm_mmap_pgoff+0xf8/0x1c0
Drop priv->lock before copy_to_user() again. On failure, re-take it and remove the map by index, as IOCTL_GNTDEV_UNMAP_GRANT_REF does, since another thread may have unmapped it meanwhile.
Message-ID: <[email protected]>
--- drivers/xen/gntdev.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/xen/gntdev.c +6 -2
@@ -678,15 +678,19 @@ static long gntdev_ioctl_map_grant_ref(smutex_lock (&priv->lock);gntdev_add_map (priv, map); op.index = map->index <<PAGE_SHIFT ; +mutex_unlock (&priv->lock);if (copy_to_user (u, &op,sizeof (op)) !=0 ) { -list_del (&map->next); +mutex_lock (&priv->lock); + map =gntdev_find_map_index (priv, op.index >>PAGE_SHIFT , + op.count); +if (map) +list_del (&map->next);mutex_unlock (&priv->lock);gntdev_put_map (priv, map);return -EFAULT ; } -mutex_unlock (&priv->lock);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 632/816 xen/privcmd: fix double free when an irqfd is shut down twice
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Qihang <[email protected]>
commit 72a900c666adb97df77b05cf8540c4117f9c83ba upstream.
irqfd_deactivate() takes the irqfd off irqfds_list and queues irqfd_shutdown(). queue_work() is not a once-only gate: it refuses to enqueue a work item only while WORK_STRUCT_PENDING is set, and process_one_work() clears that bit before it calls the work function. So nothing records that the shutdown work has already been queued, and nothing protects the window between the start of irqfd_shutdown() and the kfree() at its end.
Two paths call irqfd_deactivate() for the same irqfd:
- privcmd_irqfd_deassign(), from the PRIVCMD_IRQFD_FLAG_DEASSIGN ioctl;
- irqfd_wakeup(), with EPOLLHUP set, when the last reference to the
eventfd file goes away, which runs wake_up_poll(&ctx->wqh, EPOLLHUP)
from eventfd_release().irqfds_lock serialises the two calls, but it does not make the second one a no-op, and eventfd_ctx_fdget() takes a reference to the eventfd_ctx, not to the struct file, so the last fd can still be closed while the ioctl is running:
CPU0 CPU1
eventfd_ctx_fdget()
spin_lock(irqfds_lock)
list_del_init(&kirqfd->list)
queue_work(&kirqfd->shutdown) close(fd)
eventfd_release()
wake_up_poll(EPOLLHUP)
irqfd_wakeup() spin_lock(irqfds_lock) irqfd_deactivate() again
If the work item has already started by then, its pending bit has been cleared and the second queue_work() succeeds. irqfd_shutdown() then runs twice, so eventfd_ctx_remove_wait_queue(), eventfd_ctx_put() and kfree() each hit the same object a second time; and when the second queue_work() lands after the irqfd has been freed, the workqueue list operations write to freed memory.
virt/kvm/eventfd.c has the same two callers and has had this guard since the original irqfd support (721eecbf4fe99): irqfd_wakeup() calls irqfd_deactivate() only if irqfd_is_active(). The comment there explains why that is enough: the other side deactivates the irqfd before it takes it off the waitqueue, and irqfd_shutdown() needs the waitqueue lock, which this callback holds, so the irqfd cannot be freed under it.
Do the same here. list_del_init() leaves the list head empty and the irqfd stays off the list until kfree(), so it serves as a one-way "active" flag. The test is in irqfd_deactivate() rather than in irqfd_wakeup() because privcmd_irqfd_deassign() walks irqfds_list and can therefore never reach an inactive irqfd; only the wakeup path can, and a single test covers both callers.
Message-ID: <[email protected]>
--- drivers/xen/privcmd.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
drivers/xen/privcmd.c +15 -0
@@ -903,10 +903,25 @@ struct privcmd_kernel_irqfd {poll_table pt; }; +static bool irqfd_is_active (struct privcmd_kernel_irqfd *kirqfd) +{ +lockdep_assert_held (&irqfds_lock); + +return !list_empty (&kirqfd->list); +} +static void irqfd_deactivate (struct privcmd_kernel_irqfd *kirqfd) {lockdep_assert_held (&irqfds_lock); +/* +* Both the deassign ioctl and the eventfd wakeup path can reach +* this function. list_del_init() marks the irqfd inactive, so +* only the first caller may queue the shutdown work. +*/ +if (!irqfd_is_active (kirqfd)) +return ; +list_del_init (&kirqfd->list);queue_work (irqfd_cleanup_wq, &kirqfd->shutdown); }
Greg Kroah-Hartman
maintainerPATCH 633/816 xen/pvcalls: unwind pvcalls_new_active_socket() step by step
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 702ba3c80a8736898813a2c7484d695278aa114d upstream.
Every error path in pvcalls_new_active_socket() jumps to one shared label that does list_del(&map->list) and then hands map to pvcalls_back_release_active(). But map comes from kzalloc() and its list_head is only published at the very end of the function, after the last of those jumps:
down(&fedata->socket_lock); list_add_tail(&map->list, &fedata->socket_mappings); up(&fedata->socket_lock);
so on the error path map->list is still {NULL, NULL} and __list_del() writes through a NULL pointer.
A frontend gets there with one value it owns: the ring_order field of the page it granted. Anything above MAX_RING_ORDER takes the second goto, and nothing else in the function has run by then.
The result is an oops in whichever context handled the request - the pvcalls-back threaded IRQ handler for PVCALLS_CONNECT, mappass->wq for PVCALLS_ACCEPT - and because it happens after down(&fedata->socket_lock) that semaphore is never released, so every later operation on the frontend blocks on it and the backend never completes backend_disconnect(). (With CONFIG_DEBUG_LIST the list_del() only reports and returns, and pvcalls_back_release_active() then runs on a map whose irq is still 0 and whose bytes, ioworker.wq and saved_data_ready are all NULL.)
A frontend asking for ring_order 5, on a dom0 built with KASAN (the request was issued by a test-only change to the frontend):
[ 133.728877] pvcalls_new_active_socket frontend requested ring_order 5, which is > MAX (4) [ 133.732868] Oops: general protection fault, probably for non-canonical address 0xdffffc0000000001: 0000 [#1] SMP KASAN NOPTI [ 133.737910] KASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f] [ 133.741666] CPU: 0 UID: 0 PID: 133 Comm: irq/39-pvcalls- Not tainted 7.3.0-kCTLblk2-15482-g21a7f44fd076-dirty #1 PREEMPT(full) [ 133.746986] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 [ 133.751512] RIP: 0010:pvcalls_new_active_socket+0x821/0xb90 [ 133.754237] Code: 48 89 fa 48 c1 ea 03 80 3c 02 00 0f 85 f6 01 00 00 48 8d 79 08 4c 8b 6b 08 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03 <80> 3c 02 00 0f 85 14 02 00 00 4c 89 ea 4c 89 69 08 48 b8 00 00 00 [ 133.763126] RSP: 0018:ffffc900004afb38 EFLAGS: 00010202 [ 133.765861] RAX: dffffc0000000000 RBX: ffff88810886c900 RCX: 0000000000000000 [ 133.769348] RDX: 0000000000000001 RSI: 0000000000000246 RDI: 0000000000000008 [ 133.772787] RBP: 1ffff92000095f6b R08: 0000000000000001 R09: fffff52000095f58 [ 133.776260] R10: 0000000000000003 R11: ffff888100077320 R12: ffff88810858b410 [ 133.779823] R13: 0000000000000000 R14: ffff88810858b460 R15: ffff88810858b400 [ 133.783382] FS: 0000000000000000(0000) GS:ffff8881b034c000(0000) knlGS:0000000000000000 [ 133.787351] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 133.790308] CR2: 00000000006042c0 CR3: 0000000108400001 CR4: 0000000000770ef0 [ 133.793822] PKRU: 55555554 [ 133.795347] Call Trace: [ 133.796778] <TASK> [ 133.798082] ? __pfx_pvcalls_new_active_socket+0x10/0x10 [ 133.800801] ? security_socket_post_create+0x4d/0x60 [ 133.803275] ? release_sock+0x1a/0x1d0 [ 133.805182] pvcalls_back_event+0x1b09/0x23e0 [ 133.807431] ? __pfx_pvcalls_back_event+0x10/0x10 [ 133.809814] ? __pfx__raw_spin_lock_irqsave+0x10/0x10 [ 133.812251] ? __pfx_pvcalls_back_event+0x10/0x10 [ 133.814554] irq_thread_fn+0x86/0x150 [ 133.816468] irq_thread+0x2da/0x580 [ 133.818363] ? __pfx_irq_thread_fn+0x10/0x10 [ 133.820586] ? __pfx_irq_thread+0x10/0x10 [ 133.822670] ? __kthread_parkme+0x88/0x170 [ 133.824803] ? __pfx_irq_thread+0x10/0x10 [ 133.827153] ? __pfx_irq_thread+0x10/0x10 [ 133.829304] kthread+0x2c8/0x3b0 [ 133.831176] ? recalc_sigpending+0x15c/0x1e0 [ 133.833570] ? __pfx_kthread+0x10/0x10 [ 133.835572] ret_from_fork+0x373/0x5b0 [ 133.837581] ? __pfx_ret_from_fork+0x10/0x10 [ 133.839978] ? __switch_to+0x3c4/0xb40 [ 133.841984] ? __pfx_kthread+0x10/0x10 [ 133.843970] ret_from_fork_asm+0x1a/0x30 [ 133.846031] </TASK> [ 133.847420] Modules linked in: [ 133.849240] ---[ end trace 0000000000000000 ]---
Give each failure its own label, so that only resources that were actually acquired are released and the list the map was never added to is left
alone. The map is not published anywhere at that point, so the error path needs no socket_lock at all. sock_release() stays in the callee on every error path, the way
commit 8fafac202d18 ("xen/pvcalls-back: fix double frees with pvcalls_new_active_socket()") arranged it.
Message-ID: <[email protected]>
--- drivers/xen/pvcalls-back.c | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-)
drivers/xen/pvcalls-back.c +15 -10
@@ -337,7 +337,7 @@ static struct sock_mapping *pvcalls_new_ ret =xenbus_map_ring_valloc (fedata->dev, &ref,1 , &page);if (ret <0 ) - goto out; + goto out_map; map->ring = page; map->ring_order = map->ring->ring_order;/* first read the order, then map the data ring */
@@ -345,19 +345,19 @@ static struct sock_mapping *pvcalls_new_if (map->ring_order >MAX_RING_ORDER ) {pr_warn ("%s frontend requested ring_order %u, which is > MAX (%u)\n" , __func__, map->ring_order,MAX_RING_ORDER ); - goto out; + goto out_unmap_ring; } ret =xenbus_map_ring_valloc (fedata->dev, map->ring->ref, (1 << map->ring_order), &page);if (ret <0 ) - goto out; + goto out_unmap_ring; map->bytes = page; ret =bind_interdomain_evtchn_to_irqhandler_lateeoi ( fedata->dev, evtchn, pvcalls_back_conn_event,0 ,"pvcalls-backend" , map);if (ret <0 ) - goto out; + goto out_unmap_bytes; map->irq = ret; map->data.in = map->bytes;
@@ -365,7 +365,7 @@ static struct sock_mapping *pvcalls_new_ map->ioworker.wq =alloc_ordered_workqueue ("pvcalls_io" ,0 );if (!map->ioworker.wq) - goto out; + goto out_unbind;atomic_set (&map->io,1 );INIT_WORK (&map->ioworker.register_work, pvcalls_back_ioworker);
@@ -381,11 +381,16 @@ static struct sock_mapping *pvcalls_new_write_unlock_bh (&map->sock->sk->sk_callback_lock);return map; -out: -down (&fedata->socket_lock); -list_del (&map->list); -pvcalls_back_release_active (fedata->dev, fedata, map); -up (&fedata->socket_lock); + +out_unbind: +unbind_from_irqhandler (map->irq, map); +out_unmap_bytes: +xenbus_unmap_ring_vfree (fedata->dev, map->bytes); +out_unmap_ring: +xenbus_unmap_ring_vfree (fedata->dev, (void *)map->ring); +out_map: +sock_release (sock); +kfree (map);return NULL ; }
Greg Kroah-Hartman
maintainerPATCH 634/816 xen/pvcalls: destroy the per-socket workqueue on release
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 6b3feb6bfa9ac384f7a3ec25c40b9b4d3da96d25 upstream.
pvcalls_new_active_socket() gives every active socket its own ordered workqueue:
map->ioworker.wq = alloc_ordered_workqueue("pvcalls_io", 0);and nothing ever destroys it. pvcalls_back_release_active() flushes map->ioworker.register_work and frees map, but the workqueue and its pool_workqueues stay allocated, so a frontend leaks a workqueue per socket it connects and releases - a loop a guest can run as long as it likes.
Destroy it right after flush_work(): the IRQ is disabled and sk_data_ready restored by then, so nothing can queue new work, and the rings are still mapped while it drains - pvcalls_conn_back_read() reads map->ring and map->data, which xenbus_unmap_ring_vfree() takes away a few lines later. pvcalls_back_ioworker() does not take fedata->socket_lock, which the backend_disconnect() caller holds here - only the socket's own sk_receive_queue lock - so draining it from this point is safe; the flush_work() just above already has the same requirement.
Message-ID: <[email protected]>
--- drivers/xen/pvcalls-back.c | 1 + 1 file changed, 1 insertion(+)
drivers/xen/pvcalls-back.c +1 -0
@@ -452,6 +452,7 @@ static int pvcalls_back_release_active(satomic_set (&map->release,1 );flush_work (&map->ioworker.register_work); +destroy_workqueue (map->ioworker.wq);xenbus_unmap_ring_vfree (dev, map->bytes);xenbus_unmap_ring_vfree (dev, (void *)map->ring);
Greg Kroah-Hartman
maintainerPATCH 635/816 hwmon: (aht10) Fix update_interval overflow on 64-bit
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rupesh Majhi <[email protected]>
commit b5c5b67e02406fb48acf57cf2c30a570230fd6aa upstream.
On 64-bit, update_interval writes are clamped to LONG_MAX ms, but ms_to_ktime() overflows above 9223372036854 ms and the interval wraps. LONG_MAX becomes -1 ms, so every read starts a new measurement and update_interval reads back -1.
Clamp to INT_MAX like sht4x, so the limit is the same on all platforms.
--- drivers/hwmon/aht10.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/aht10.c +1 -1
@@ -229,7 +229,7 @@ static int aht10_read_values(struct aht1static ssize_t aht10_interval_write (struct aht10_data *data,long val) { - data->min_poll_interval =ms_to_ktime (clamp_val (val,2000 ,LONG_MAX )); + data->min_poll_interval =ms_to_ktime (clamp_val (val,2000 ,INT_MAX ));return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 636/816 hwmon: (pmbus/mp2975) Get vout fault limits dynamically
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Felix Radensky <[email protected]>
commit 00944852275efd39706fe7b9ce75c28edde983eb upstream.
The over- and under-voltage fault limits of the tracking mode are relative to the voltage reference, which follows the VID/AVS requests issued to the device and therefore changes at runtime.
The driver reads the voltage reference once during probe and derives the limits from that snapshot, which the PMBus core caches in addition. As a result in2_crit and in2_lcrit reflect the operating point at probe, rather than the thresholds the device enforces. On systems where the device supplies the CPU core voltage, in2_crit was reported anywhere between 1.15V and 1.70V across identical systems, causing false over-voltage reports once the CPU voltage exceeded the value latched at probe.
Read the voltage reference and the over-voltage offset selector whenever a limit is requested, and mark both limits with pmbus_set_update(), so that the core does not cache them. The voltage reference is available on page 3 only. Let the core change the page, so that the page it caches matches the device, except for a single rail configuration, for which the core does not issue PAGE commands, and the page is changed directly.
With the selector read at runtime, a device configured with an unsupported selector no longer fails to probe. The OVP1 threshold, which does not depend on the selector, is reported for it instead, with a warning.
Clamp the under-voltage limit to zero, since the offset can exceed a low voltage reference, while a negative value would be reported as a read error.
--- drivers/hwmon/pmbus/mp2975.c | 207 +++++++++++++++++++++++-------------------- 1 file changed, 115 insertions(+), 92 deletions(-)
drivers/hwmon/pmbus/mp2975.c +115 -92
@@ -110,10 +110,7 @@ struct mp2975_data {int vout_scale;int max_phases[MP2975_PAGE_NUM ];int vid_step[MP2975_PAGE_NUM ]; -int vref[MP2975_PAGE_NUM ]; -int vref_off[MP2975_PAGE_NUM ];int vout_max[MP2975_PAGE_NUM ]; -int vout_ov_fixed[MP2975_PAGE_NUM ];int curr_sense_gain[MP2975_PAGE_NUM ]; };
@@ -466,12 +463,77 @@ static int mp2973_write_word_data(structreturn pmbus_write_word_data (client,0 ,PMBUS_SMBALERT_MASK , ret); } +/* +* Let the PMBus core change the page, so that the page it caches matches the +* device. The core does not issue PAGE commands for a single rail +* configuration, thus change the page directly then. +*/ +static int +mp2975_page_set (struct i2c_client *client,struct mp2975_data *data,int page) +{ +if (data->info.pages >1 ) +return pmbus_set_page (client, page,0xff ); + +return i2c_smbus_write_byte_data (client,PMBUS_PAGE , page); +} + +/* +* Voltage reference is available on page 3 only. The callers read a register +* of the rail through the core first, thus the core caches the rail page. +*/ +static int +mp2975_vref_get (struct i2c_client *client,struct mp2975_data *data,int page) +{ +int ret, vref; + + ret =mp2975_page_set (client, data,3 ); +if (ret <0 ) +return ret; + + vref =i2c_smbus_read_word_data (client, page ?MP2975_MFR_READ_VREF_R2 : +MP2975_MFR_READ_VREF_R1 ); + + ret =mp2975_page_set (client, data, page); +if (ret <0 ) +return ret; + +return (vref <0 ) ? vref : vref * data->vid_step[page]; +} + +static int +mp2975_ovp2_offset_get (int ovp_th_set) +{ +switch ((ovp_th_set &GENMASK (5 ,3 )) >>3 ) { +case 1 : +return 140 ; +case 2 : +return 220 ; +case 4 : +return 400 ; +default : +return -EINVAL ; + } +} + +static int +mp2975_vout_ovp2_get (struct i2c_client *client,struct mp2975_data *data, +int page,int vref_off) +{ +int vref; + + vref =mp2975_vref_get (client, data, page); +if (vref <0 ) +return vref; + +return vref +DIV_ROUND_CLOSEST (vref_off * data->vout_scale,10 ); +} +static int mp2975_read_word_data (struct i2c_client *client,int page,int phase,int reg) {const struct pmbus_driver_info *info =pmbus_get_driver_info (client);struct mp2975_data *data =to_mp2975_data (info); -int ret; +int ret, ovp1, vref_off, uv_off;switch (reg) {case PMBUS_OT_FAULT_LIMIT :
@@ -488,19 +550,35 @@ static int mp2975_read_word_data(structbreak ;case PMBUS_VOUT_OV_FAULT_LIMIT :/* -* Register provides two values for over-voltage protection -* threshold for fixed (ovp2) and tracking (ovp1) modes. The -* minimum of these two values is provided as over-voltage -* fault alarm. +* Device provides dual over-voltage protection. OVP1 is +* referred to the maximum reference voltage, while OVP2 is +* referred to the current voltage reference, which is changed +* at runtime. Protection is tripped by any of them, thus the +* minimum of the two is exposed as over-voltage fault alarm, +* and OVP2 is obtained on each read. */ ret =mp2975_read_word_helper (client, page, phase,MP2975_MFR_OVP_TH_SET , -GENMASK (2 ,0 )); +GENMASK (5 ,0 ));if (ret <0 )return ret; - ret =min_t (int, data->vout_max[page] +50 * (ret +1 ), - data->vout_ov_fixed[page]); + ovp1 = data->vout_max[page] +50 * ((ret &GENMASK (2 ,0 )) +1 ); + +/* OVP1 still applies if the OVP2 threshold is unknown. */ + vref_off =mp2975_ovp2_offset_get (ret); +if (vref_off <0 ) { +dev_warn_once (&client->dev, +"unsupported OVP2 selector, reporting OVP1 threshold\n" ); + ret = ovp1; +break ; + } + + ret =mp2975_vout_ovp2_get (client, data, page, vref_off); +if (ret <0 ) +return ret; + + ret =min_t (int, ovp1, ret);break ;case PMBUS_VOUT_UV_FAULT_LIMIT : ret = mp2975_read_word_helper(client, page, phase,
@@ -509,8 +587,17 @@ static int mp2975_read_word_data(structif (ret <0 )return ret; - ret =DIV_ROUND_CLOSEST (data->vref[page] *10 -50 * - (ret +1 ) * data->vout_scale,10 ); + uv_off =50 * (ret +1 ) * data->vout_scale; + + ret =mp2975_vref_get (client, data, page); +if (ret <0 ) +return ret; + +/* +* Offset can exceed the voltage reference, while a negative +* value would be reported as a read error. +*/ + ret =max_t (int,DIV_ROUND_CLOSEST (ret *10 - uv_off,10 ),0 );break ;case PMBUS_VIRT_READ_POUT_MAX : ret = mp2975_read_word_helper(client, page, phase,
@@ -760,60 +847,6 @@ mp2975_current_sense_gain_get(struct i2c }static int -mp2975_vref_get (struct i2c_client *client,struct mp2975_data *data, -struct pmbus_driver_info *info) -{ -int ret; - - ret =i2c_smbus_write_byte_data (client,PMBUS_PAGE ,3 ); -if (ret <0 ) -return ret; - -/* Get voltage reference value for rail 1. */ - ret =i2c_smbus_read_word_data (client,MP2975_MFR_READ_VREF_R1 ); -if (ret <0 ) -return ret; - - data->vref[0 ] = ret * data->vid_step[0 ]; - -/* Get voltage reference value for rail 2, if connected. */ -if (data->info.pages ==MP2975_PAGE_NUM ) { - ret =i2c_smbus_read_word_data (client,MP2975_MFR_READ_VREF_R2 ); -if (ret <0 ) -return ret; - - data->vref[1 ] = ret * data->vid_step[1 ]; - } -return 0 ; -} - -static int -mp2975_vref_offset_get (struct i2c_client *client,struct mp2975_data *data, -int page) -{ -int ret; - - ret =i2c_smbus_read_word_data (client,MP2975_MFR_OVP_TH_SET ); -if (ret <0 ) -return ret; - -switch ((ret &GENMASK (5 ,3 )) >>3 ) { -case 1 : - data->vref_off[page] =140 ; -break ; -case 2 : - data->vref_off[page] =220 ; -break ; -case 4 : - data->vref_off[page] =400 ; -break ; -default : -return -EINVAL ; - } -return 0 ; -} - -static int mp2975_vout_max_get (struct i2c_client *client,struct mp2975_data *data,struct pmbus_driver_info *info,int page) {
@@ -917,25 +950,6 @@ mp2975_vout_per_rail_config_get(struct i ret =mp2975_vout_max_get (client, data, info, i);if (ret <0 )return ret; - -/* Skip if reading Vref is unsupported */ -if (data->chip_id != mp2975) -continue ; - -/* Obtain voltage reference offsets. */ - ret =mp2975_vref_offset_get (client, data, i); -if (ret <0 ) -return ret; - -/* -* Set over-voltage fixed value. Thresholds are provided as -* fixed value, and tracking value. The minimum of them are -* exposed as over-voltage critical threshold. -*/ - data->vout_ov_fixed[i] = data->vref[i] + -DIV_ROUND_CLOSEST (data->vref_off[i] * - data->vout_scale, -10 ); }return 0 ;
@@ -1049,11 +1063,6 @@ static int mp2975_probe(struct i2c_clienif (ret)return ret; -/* Obtain voltage reference values. */ - ret =mp2975_vref_get (client, data, info); -if (ret) -return ret; -/* Obtain vout over-voltage scales. */ ret =mp2975_vout_ov_scale_get (client, data, info);if (ret <0 )
@@ -1070,7 +1079,21 @@ static int mp2975_probe(struct i2c_clienif (ret)return ret; -return pmbus_do_probe (client, info); + ret =pmbus_do_probe (client, info); +if (ret) +return ret; + +/* +* Vout over- and under-voltage fault limits are relative to the +* voltage reference, which is changed at runtime. Do not allow the +* PMBus core to cache them. +*/ +if (data->chip_id == mp2975) { +pmbus_set_update (client,PMBUS_VOUT_OV_FAULT_LIMIT , true); +pmbus_set_update (client,PMBUS_VOUT_UV_FAULT_LIMIT , true); + } + +return 0 ; }static const struct of_device_id mp2975_of_match[] = {
Greg Kroah-Hartman
maintainerPATCH 637/816 hwmon: (sy7636a) fix negative temperatures
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pablo Mazzini <[email protected]>
commit fc8519fab34e162b0c29dacccf73031820878917 upstream.
The thermistor readout is a signed 8-bit value in degrees Celsius.
--- drivers/hwmon/sy7636a-hwmon.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/sy7636a-hwmon.c +1 -1
@@ -29,7 +29,7 @@ static int sy7636a_read(struct device *dif (ret)return ret; - *temp = reg_val *1000 ; + *temp = (s8 )reg_val *1000 ;return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 638/816 hwmon: (scmi) Check channel config allocation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sudeep Holla <[email protected]>
commit a2996d892d0150d059d39c683d95d6fd7a37630a upstream.
scmi_hwmon_add_chan_info() can fail to allocate a channel's config array. Ignoring that error leaves a channel with a NULL config pointer in the hwmon chip info, which hwmon dereferences while registering the device.
Check the helper's return value and abort probe on failure.
--- drivers/hwmon/scmi-hwmon.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/hwmon/scmi-hwmon.c +7 -5
@@ -228,8 +228,8 @@ static int scmi_thermal_sensor_register(static int scmi_hwmon_probe (struct scmi_device *sdev) { -int i, idx;u16 nr_sensors; +int i, idx, ret;enum hwmon_sensor_types type;struct scmi_sensors *scmi_sensors;const struct scmi_sensor_info *sensor;
@@ -297,8 +297,12 @@ static int scmi_hwmon_probe(struct scmi_if (!nr_count[type])continue ; -scmi_hwmon_add_chan_info (scmi_hwmon_chan, dev, nr_count[type], - type, hwmon_attributes[type]); + ret =scmi_hwmon_add_chan_info (scmi_hwmon_chan, dev, + nr_count[type], type, + hwmon_attributes[type]); +if (ret) +return ret; + *ptr_scmi_ci++ = scmi_hwmon_chan++; scmi_sensors->info[type] =
@@ -333,8 +337,6 @@ static int scmi_hwmon_probe(struct scmi_return PTR_ERR (hwdev);for (i =0 ; i < nr_count_temp; i++) { -int ret; - sensor = *(scmi_sensors->info[hwmon_temp] + i);if (!sensor)continue ;
Greg Kroah-Hartman
maintainerPATCH 639/816 hwmon: (max31760) Fix the local temperature limit registers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Aleksandrov <[email protected]>
commit 028ed93145d9be88eee670088ef13482b5d36c1a upstream.
temp2_max and temp2_crit use each other's registers, so reading them shows the local limits swapped and writing temp2_max changes the overtemperature (SHDN) threshold.
Use the high limit (0x0C) for temp2_max and the overtemperature limit (0x08) for temp2_crit.
--- drivers/hwmon/max31760.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hwmon/max31760.c +2 -2
@@ -27,8 +27,8 @@#define REG_TACH (ch) (0x52 + (ch) * 2)#define REG_TEMP_INPUT (ch) (0x56 + (ch) * 2) -#define REG_TEMP_MAX (ch) (0x06 + (ch) * 2) -#define REG_TEMP_CRIT (ch) (0x0A + (ch) * 2) +#define REG_TEMP_MAX (ch) ((ch) ? 0x0C : 0x06) +#define REG_TEMP_CRIT (ch) ((ch) ? 0x08 : 0x0A)#define TEMP11_FROM_REG (reg) ((reg) / 32 * 125)#define TEMP11_TO_REG (val) (DIV_ROUND_CLOSEST(clamp_val((val), -128000, \
Greg Kroah-Hartman
maintainerPATCH 640/816 hwmon: (max31760) Leave standby mode at probe
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Aleksandrov <[email protected]>
commit 95bddc5252a4c0a2ed9d62e7e53a3461265d9603 upstream.
The driver never clears the standby bit (CR2_STBY) during probe. While max31760_resume() clears this bit on resume, probe only configured CR2_ALERTS.
If the chip was left in standby (for example, by boot firmware or a previously running OS before a warm reboot), it remains in standby:
temperature sensing, fan speed counting, and PWM output are halted. This occurs on the Samsung Galaxy XR, where the bootloader places the chip in standby during boot.
Clear CR2_STBY alongside setting CR2_ALERTS in probe.
--- drivers/hwmon/max31760.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/hwmon/max31760.c +3 -2
@@ -533,8 +533,9 @@ static int max31760_probe(struct i2c_clidev_set_drvdata (dev, state); -/* Set alert output to comparator mode */ - ret =regmap_set_bits (state->regmap,REG_CR2 ,CR2_ALERTS ); +/* Leave standby mode, set alert output to comparator mode */ + ret =regmap_update_bits (state->regmap,REG_CR2 ,CR2_STBY |CR2_ALERTS , +CR2_ALERTS );if (ret)return dev_err_probe (dev, ret,"cannot write register\n" );
Greg Kroah-Hartman
maintainerPATCH 641/816 hwmon: (max31760) Report 0 RPM before the first fan speed measurement
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Aleksandrov <[email protected]>
commit 33d58cbf2ab26bda81bc3052158d8b9867d5b9a6 upstream.
The tachometer count registers initialize to 0 until the first measurement cycle completes after power-on. To prevent division by zero, tach_to_rpm() clamped tach == 0 to 1, causing it to compute and report 3,000,000 RPM (60 * 100000 / 1 / 2).
Return 0 RPM when tach == 0 instead.
--- drivers/hwmon/max31760.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/hwmon/max31760.c +2 -1
@@ -68,8 +68,9 @@ static const int max31760_pwm_freq[] = {static int tach_to_rpm (u16 tach) { +/* The count is 0 until the first measurement */ if (tach ==0 ) - tach =1 ; +return 0 ;return 60 *100000 / tach /2 ; }
Greg Kroah-Hartman
maintainerPATCH 642/816 s390/dasd: Fix wrong free and refcount leak in build_check_tcw error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stefan Haberland <[email protected]>
commit df56f7a6c20a5eb2794c0a7391bde50ba7c8c54b upstream.
dasd_eckd_build_check_tcw() allocates its request with dasd_fmalloc_request(), but its out_err path frees it with dasd_sfree_request(). The latter uses a different pool and therefor, leading to invalid pointer arithmetic and a crash.
Use the matching dasd_ffree_request() instead.
The same error path also leaves start_priv->count incremented without ever decrementing it again.
This leaks a permanent reference on every build failure. Decrement it before freeing the request.
--- drivers/s390/block/dasd_eckd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/s390/block/dasd_eckd.c +2 -1
@@ -2593,7 +2593,8 @@ dasd_eckd_build_check_tcw(struct dasd_dereturn cqr; out_err: -dasd_sfree_request (cqr, startdev); + start_priv->count--; +dasd_ffree_request (cqr, startdev);return ERR_PTR (rc); }
Greg Kroah-Hartman
maintainerPATCH 643/816 s390/dasd: Dont trust userspace-supplied result field in format check
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stefan Haberland <[email protected]>
commit 7cc2dda4f7aaf596c1796184649007151ff98f8d upstream.
BIODASDCHECKFMT used to copy the entire format_check_t struct from userspace, including the result/unit/rec/num_records/blksize/ key_length fields that are output fields only. dasd_eckd_format_evaluate_tracks() relies on cdata->result being zero to decide whether to apply an index correction (i--/pos--) after a successful check. A caller that pre-sets result to a non-zero value can suppress that correction, leaving pos advanced past the last valid entry; the (partially out-of-bounds) fmt_buffer[pos] fields are then copied back to userspace, leaking heap contents.
Only expect is an Input field; copy just that member in and zero the rest of cdata.
--- drivers/s390/block/dasd_ioctl.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/s390/block/dasd_ioctl.c +3 -1
@@ -303,7 +303,9 @@ static int dasd_ioctl_check_format(struc goto out_err; } -if (copy_from_user (&cdata, argp,sizeof (cdata))) { +/* copy only input fields, clear the rest */ +memset (&cdata,0 ,sizeof (cdata)); +if (copy_from_user (&cdata.expect, argp,sizeof (cdata.expect))) { rc = -EFAULT ; goto out_err; }
Greg Kroah-Hartman
maintainerPATCH 644/816 sched/deadline: Fix spurious -EPERM for migration-disabled tasks
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit 6616bffa9b52da1338cf8bff9882404e02b9e361 upstream.
sched_setattr() can refuse to make a task SCHED_DEADLINE with -EPERM, even though the task's affinity covers the whole root domain. A retry can succeed, but the error blames an affinity the task does not have.
__sched_setscheduler() tests p->cpus_ptr, which is not always the task's affinity. When a task is scheduled out inside a migrate_disable() section, migrate_disable_switch() points p->cpus_ptr at the current CPU until migrate_enable(). On PREEMPT_RT every spinlock_t holder is in such a section, so ordinary kernel work opens the window. Elsewhere, seccomp filters run in one.
Test p->cpus_mask instead, which keeps the task's affinity and is what sched_getaffinity() reports. This should be safe because an admitted task's cpus_mask covers the root domain, so set_cpus_allowed_dl() moves no bandwidth when migrate_enable() restores p->cpus_ptr.
The following program, run as root, had 553679, 453720 and 424623 of its 1000000 requests refused on three boots of a 4-CPU PREEMPT_RT guest, and 236182, 217174 and 237183 without PREEMPT_RT. With this applied the count is 0, also with lockdep, and a task pinned to one CPU is still refused:
#define _GNU_SOURCE
#include <errno.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
#define REQUESTS 1000000
#define INSNS 300
struct attr {
uint32_t size, policy;
uint64_t flags;
int32_t nice;
uint32_t prio;
uint64_t runtime, deadline, period;
}; static volatile int stop;
static volatile pid_t target;
static long set(struct attr a)
{
a.size = sizeof(a);
return syscall(SYS_sched_setattr, target, &a, 0);
}
static void *worker(void *arg)
{
struct sock_filter f[INSNS + 1];
struct sock_fprog prog = { .len = INSNS + 1, .filter = f };
int i; /* Reading the arguments keeps seccomp from caching the result */
for (i = 0; i < INSNS; i++)
f[i] = (struct sock_filter)
BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
offsetof(struct seccomp_data, args));
f[INSNS] = (struct sock_filter)
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW);
syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog);
target = syscall(SYS_gettid);
while (!stop)
syscall(SYS_getppid);
return arg;}
static void *hog(void *arg)
{
while (!stop)
;
return arg;
}
int main(void)
{
pthread_t t[9];
long refused = 0;
int i; pthread_create(&t[0], NULL, worker, NULL);
while (!target)
usleep(100);
for (i = 1; i < 9; i++)
pthread_create(&t[i], NULL, hog, NULL);
for (i = 0; i < REQUESTS; i++) {
/* SCHED_DEADLINE, 2us every 1s */
if (set((struct attr){ .policy = 6, .runtime = 2000,
.deadline = 1000000000,
.period = 1000000000 }) && errno == EPERM)
refused++;
set((struct attr){ .policy = 0 }); /* SCHED_OTHER */
}
stop = 1;
for (i = 0; i < 9; i++)
pthread_join(t[i], NULL);
printf("%ld of %d requests refused\n", refused, REQUESTS);
return 0;}
An LLM helped find this bug and write this patch and its test.
--- kernel/sched/syscalls.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/sched/syscalls.c +1 -1
@@ -631,7 +631,7 @@ change:* the entire root_domain to become SCHED_DEADLINE. We * will also fail if there's no bandwidth available. */ -if (!cpumask_subset (span, p->cpus_ptr) || +if (!cpumask_subset (span, &p->cpus_mask) || rq->rd->dl_bw.bw ==0 ) { retval = -EPERM ; goto unlock;
Greg Kroah-Hartman
maintainerPATCH 645/816 sched/uclamp: Reject clamp values above SCHED_CAPACITY_SCALE
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit 8127ec8458df29bd702db602473042ccb9e619b9 upstream.
sched_setattr() accepts sched_util_min and sched_util_max values that do not fit in uclamp_se::value. A single thread can do:
sched_setattr(max = 800) returns 0
sched_setattr(min = 0xfffffffe) returns 0
sched_getattr() min=2046 max=800
which leaves the minimum above both SCHED_CAPACITY_SCALE and the task's own maximum.
The range check in uclamp_validate() relies on the + 1 wrapping -1, the reset value, to 0:
if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)
That only works for an unsigned type. util_min and util_max are int and SCHED_CAPACITY_SCALE is a long, so every negative value passes the check, and so does INT_MAX, whose + 1 wraps.
uclamp_se_set() then truncates what got through to the 11 bits of uclamp_se::value, but computes the bucket from the full value. A minimum of 0xfffff800 is stored as 0 in the top bucket, where uclamp_rq_max_value() takes it for the highest active clamp once a higher value leaves the rq. The rq clamp falls below what the remaining tasks requested, and emptying their bucket trips the WARN_ON_ONCE() in uclamp_rq_dec_id(), without any privilege:
WARNING: kernel/sched/core.c:1862 at dequeue_task+0x2a3/0x2b0, CPU#0: repro/126 Call Trace: __schedule+0x933/0x1320 schedule+0x36/0x100 do_nanosleep+0x61/0x190 hrtimer_nanosleep+0xb5/0x1d0
Make util_min and util_max unsigned int, so that -1 is the only value that wraps. The pair check below is unaffected, since it skips -1 explicitly and anything else is at most SCHED_CAPACITY_SCALE by then.
Requests that were only accepted because of this now fail with -EINVAL.
The following program triggers the warning when run by any user outside a child cpu cgroup. With this applied, its 0xfffff800 request fails with -EINVAL and the warning no longer appears:
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
struct attr {
uint32_t size, policy;
uint64_t flags;
int32_t nice;
uint32_t prio;
uint64_t runtime, deadline, period;
uint32_t util_min, util_max;
};static volatile int stop;
static void set_min(uint32_t v)
{
/* KEEP_POLICY | KEEP_PARAMS | UTIL_CLAMP_MIN */
struct attr a = { .size = sizeof(a), .flags = 0x38, .util_min = v };syscall(SYS_sched_setattr, 0, &a, 0);
}
static void burn(long us)
{
struct timespec s, n; clock_gettime(CLOCK_MONOTONIC, &s);
do
clock_gettime(CLOCK_MONOTONIC, &n);
while ((n.tv_sec - s.tv_sec) * 1000000 +
(n.tv_nsec - s.tv_nsec) / 1000 < us);}
static void *bogus(void *arg)
{
set_min(0xfffff800);
while (!stop)
burn(1000);
return arg;
}
static void *worker(void *arg)
{
long v = (long)arg; set_min(v);
while (!stop) {
burn(v == 800 ? 300 : 1500);
usleep(100);
}
return arg;}
int main(void)
{
pthread_t t[3];
cpu_set_t c;
int i; CPU_ZERO(&c);
CPU_SET(0, &c);
sched_setaffinity(0, sizeof(c), &c);
pthread_create(&t[0], NULL, bogus, NULL);
usleep(50000);
pthread_create(&t[1], NULL, worker, (void *)500L);
pthread_create(&t[2], NULL, worker, (void *)800L);
sleep(15);
stop = 1;
for (i = 0; i < 3; i++)
pthread_join(t[i], NULL);
return 0;}
An LLM helped find the warning and write this patch and its tests.
--- kernel/sched/syscalls.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/sched/syscalls.c +2 -2
@@ -321,8 +321,8 @@ static bool check_same_owner(struct taskstatic int uclamp_validate (struct task_struct *p,const struct sched_attr *attr) { -int util_min = p->uclamp_req[UCLAMP_MIN ].value; -int util_max = p->uclamp_req[UCLAMP_MAX ].value; +unsigned int util_min = p->uclamp_req[UCLAMP_MIN ].value; +unsigned int util_max = p->uclamp_req[UCLAMP_MAX ].value;if (attr->sched_flags &SCHED_FLAG_UTIL_CLAMP_MIN ) { util_min = attr->sched_util_min;
Greg Kroah-Hartman
maintainerPATCH 646/816 sched/core: Fix cpuset_mutex double unlock in __sched_setscheduler()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit f7141257dd67d4936f906a6cfd1d0007721f6898 upstream.
A sched_setattr() with SCHED_FLAG_KEEP_POLICY on a SCHED_DEADLINE task unlocks cpuset_mutex twice if the task's policy changes concurrently:
WARNING: bad unlock balance detected! 7.4.0-rc1 #1 Not tainted
-------------------------------------
repro/126 is trying to release lock (cpuset_mutex) at:
[<ffffffff9a17cacc>] __sched_setscheduler+0x9cc/0xc40 but there are no more locks to release! ... Call Trace: print_unlock_imbalance_bug.part.0+0xfb/0x110 lock_release+0x286/0x2e0 __mutex_unlock_slowpath+0x1a/0x400 __sched_setscheduler+0x9cc/0xc40 __x64_sys_sched_setattr+0xa3/0x1b0 do_syscall_64+0x106/0x5f0 entry_SYSCALL_64_after_hwframe+0x77/0x7f
__sched_setscheduler() samples p->policy before taking any lock, and restarts from the recheck label if p->policy differs under the rq lock. The restart drops cpuset_mutex but leaves cpuset_locked set, so a pass that no longer needs the mutex still unlocks it on its way out:
CPU 1 CPU 2
__sched_setscheduler(KEEP_POLICY)
policy = p->policy /* DEADLINE */
__sched_setscheduler(SCHED_OTHER)
p->policy = SCHED_OTHER
cpuset_locked = true
cpuset_lock()
rq = task_rq_lock(p)
oldpolicy != p->policy
cpuset_unlock()
goto recheck
/* no cpuset_lock() this time */
...
if (cpuset_locked)
cpuset_unlock()Without CONFIG_DEBUG_MUTEXES, or CONFIG_DEBUG_RT_MUTEXES on PREEMPT_RT, nothing warns. The second unlock still clears the owner field regardless of who holds the mutex, so another task can lose cpuset_mutex inside its critical section. Entering SCHED_DEADLINE needs CAP_SYS_NICE, but a racing caller that owns the task does not need it if it samples a policy other than SCHED_DEADLINE.
Clear cpuset_locked when dropping the mutex for the restart. This should be safe because the flag is only tested on the paths leaving the next pass, after that pass has set it again if it took the mutex.
The following program, run as root, reproduces the splat, which no longer appears with this applied. On PREEMPT_RT it crashes the kernel within seconds, which this also fixes:
#define _GNU_SOURCE
#include <pthread.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <unistd.h>
struct attr {
uint32_t size, policy;
uint64_t flags;
int32_t nice;
uint32_t prio;
uint64_t runtime, deadline, period;
}; static volatile int stop;
static volatile pid_t target;
static void set(struct attr a)
{
a.size = sizeof(a);
syscall(SYS_sched_setattr, target, &a, 0);
}
static void *sleeper(void *arg)
{
target = syscall(SYS_gettid);
while (!stop)
usleep(1000);
return arg;
}
static void *switcher(void *arg)
{
while (!stop) {
/* SCHED_DEADLINE, 2us every 1s */
set((struct attr){ .policy = 6, .runtime = 2000,
.deadline = 1000000000,
.period = 1000000000 });
set((struct attr){ .policy = 0 }); /* SCHED_OTHER */
}
return arg;
}
static void *racer(void *arg)
{
/* KEEP_POLICY | KEEP_PARAMS */
while (!stop)
set((struct attr){ .flags = 0x18 });
return arg;
}
int main(void)
{
pthread_t t[5];
int i; pthread_create(&t[0], NULL, sleeper, NULL);
while (!target)
usleep(100);
pthread_create(&t[1], NULL, switcher, NULL);
for (i = 2; i < 5; i++)
pthread_create(&t[i], NULL, racer, NULL);
sleep(30);
stop = 1;
for (i = 0; i < 5; i++)
pthread_join(t[i], NULL);
return 0;}
An LLM helped find the PREEMPT_RT crash and write this patch and its test.
--- kernel/sched/syscalls.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/sched/syscalls.c +3 -1
@@ -644,8 +644,10 @@ change:if (unlikely (oldpolicy !=-1 && oldpolicy != p->policy)) { policy = oldpolicy =-1 ;task_rq_unlock (rq, p, &rf); -if (cpuset_locked) +if (cpuset_locked) {cpuset_unlock (); + cpuset_locked = false; + } goto recheck; }
Greg Kroah-Hartman
maintainerPATCH 647/816 sctp: abort unordered partial delivery when its message is skipped
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Budding <[email protected]>
commit 05852c8b70f2291a50bb3f740a66ce9caf9cb98d upstream.
When an I-FORWARD-TSN skips unordered messages on a stream, sctp_intl_skip() only aborts the stream's unordered partial delivery if the MID being delivered is lower than the skipped MID. If the skipped message is the one being partially delivered, partial delivery stays in
progress: no PARTIAL_DELIVERY_ABORTED is sent, and the next unordered message on the stream is delivered as the rest of the abandoned one.
Abort the partial delivery when the MID being delivered is at or below the skipped MID, as the ordered case already does.
Reproduced on an unmodified kernel with the uo_pd test of the sctp_ifwdtsn.sh selftest added later in this series; its partial delivery checks pass with this fix. Reproduction and fix done with AI assistance.
--- net/sctp/stream_interleave.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sctp/stream_interleave.c +1 -1
@@ -1255,7 +1255,7 @@ static void sctp_intl_skip(struct sctp_ustruct sctp_stream *stream = &ulpq->asoc->stream;if (flags &SCTP_FTSN_U_BIT ) { -if (sin->pd_mode_uo &&MID_lt (sin->mid_uo, mid)) { +if (sin->pd_mode_uo && !MID_lt (mid, sin->mid_uo)) { sin->pd_mode_uo =0 ;sctp_intl_stream_abort_pd (ulpq, sid, mid,0x1 ,GFP_ATOMIC );
Greg Kroah-Hartman
maintainerPATCH 648/816 sctp: avoid requeueing pending control chunks
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 665b4149e91b781a71bce8637c3a4d7d64dba05f upstream.
The T4 and RE-CONFIG timeout handlers take a reference to their cached control chunk and submit it through SCTP_CMD_REPLY. A previous transmission can still be on the control outqueue when output is corked or suppressed, or when sctp_packet_transmit_chunk() could not append the chunk.
sctp_outq_tail() then adds the same list node a second time. Re-adding a non-tail entry can corrupt the list without being caught by the insertion-time list checks. A subsequent flush or association teardown can access an already freed chunk. The ASCONF path is reproducible by an unprivileged SCTP socket owner in a user/network namespace, with KASAN reporting a use-after-free in __sctp_outq_teardown().
Check sctp_chunk_pending() in both timeout handlers before taking the extra reference and issuing SCTP_CMD_REPLY. If the chunk is already linked, leave the existing entry for normal output processing. Keep the remaining timer and error-handling commands unchanged. This also covers RE-CONFIG retransmission after sctp_assoc_rm_peer() moves the request to another transport and starts its timer.
The issue was found by an LLM.
--- net/sctp/sm_statefuns.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-)
net/sctp/sm_statefuns.c +10 -6
@@ -1122,9 +1122,11 @@ enum sctp_disposition sctp_sf_send_reconreturn SCTP_DISPOSITION_DELETE_TCB ; } -sctp_chunk_hold (asoc->strreset_chunk); -sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , -SCTP_CHUNK (asoc->strreset_chunk)); +if (!sctp_chunk_pending (asoc->strreset_chunk)) { +sctp_chunk_hold (asoc->strreset_chunk); +sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , +SCTP_CHUNK (asoc->strreset_chunk)); + }sctp_add_cmd_sf (commands,SCTP_CMD_STRIKE ,SCTP_TRANSPORT (transport));return SCTP_DISPOSITION_CONSUME ;
@@ -6194,9 +6196,11 @@ enum sctp_disposition sctp_sf_t4_timer_e* chunk, it MUST be the same (including its serial number) as the last * ASCONF sent. */ -sctp_chunk_hold (asoc->addip_last_asconf); -sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , -SCTP_CHUNK (asoc->addip_last_asconf)); +if (!sctp_chunk_pending (asoc->addip_last_asconf)) { +sctp_chunk_hold (asoc->addip_last_asconf); +sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , +SCTP_CHUNK (asoc->addip_last_asconf)); + }/* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different * destination is selected, then the RTO used will be that of the new
Greg Kroah-Hartman
maintainerPATCH 649/816 sctp: fix ASCONF address change on single-homed hosts
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
commit 5175b2fb34c77cf2cd56a290affa45412cb3a228 upstream.
Commit 9b2854f86f0b ("sctp: don't free the ASCONF's own transport in DEL-IP processing") refuses a DEL-IP of the transport the ASCONF was located by, so that a later wildcard DEL-IP cannot use it after free.
This also breaks the single-homed address change (RFC 5061 5.3.2). The host sends [Address Parameter L] [ADD-IP S] [DEL-IP L], the association is located by L, and DEL-IP L is now refused. The sender never gets an all-success ASCONF-ACK, keeps src_out_of_asoc_ok set and stops sending data, so the association stalls.
Fix the wildcard DEL-IP instead: look up the transport of the packet source rather than reusing asconf->transport. Both DEL-IP paths can now free asconf->transport, and chunks bundled after the ASCONF still use it, so point it at a surviving transport: the packet source for the wildcard delete, the primary path for a plain one.
Found by manual code inspection while reviewing a backport of commit 9b2854f86f0b; reproduced on a two-namespace single-homed renumber.
--- net/sctp/sm_make_chunk.c | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-)
net/sctp/sm_make_chunk.c +8 -9
@@ -3191,9 +3191,12 @@ static __be16 sctp_process_asconf_param(* packet MUST be deleted. */ if (af->is_any (&addr)) { -sctp_assoc_set_primary (asoc, asconf->transport); -sctp_assoc_del_nonprimary_peers (asoc, - asconf->transport); + peer =sctp_assoc_lookup_paddr (asoc, &asconf->source); +if (!peer) +return SCTP_ERROR_REQ_REFUSED ; +sctp_assoc_set_primary (asoc, peer); +sctp_assoc_del_nonprimary_peers (asoc, peer); + asconf->transport = peer;return SCTP_ERROR_NO_ERROR ; }
@@ -3206,13 +3209,9 @@ static __be16 sctp_process_asconf_param(if (!peer)return SCTP_ERROR_DNS_FAILED ; -/* Don't free asconf->transport; a later wildcard DEL-IP -* parameter reuses it. -*/ -if (peer == asconf->transport) -return SCTP_ERROR_REQ_REFUSED ; -sctp_assoc_rm_peer (asoc, peer); +if (asconf->transport == peer) + asconf->transport = asoc->peer.primary_path;break ;case SCTP_PARAM_SET_PRIMARY :/* ADDIP Section 4.2.4
Greg Kroah-Hartman
maintainerPATCH 650/816 sctp: fix I-FORWARD-TSN handling of fragments on other streams
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Budding <[email protected]>
commit 5b9cfc6491a6e32e7315dc222992c7dbd5baa3e9 upstream.
sctp_report_iftsn() incorrectly frees queued I-DATA fragments in two cases. First, it drops any queued fragments with TSN less than or equal to the New Cumulative TSN. This prevents reconstruction of messages still being received on other streams and can fully block an ordered stream. Second, it calls sctp_intl_abort_pd() if the New Cumulative TSN equals the highest TSN seen. This check exists for association resets but can be inadvertently triggered by any I-FORWARD-TSN that arrives before data with a higher TSN, causing data loss and, if a partial delivery is in progress on an ordered stream, an aborted association.
Fix the first by freeing fragments from sctp_intl_skip() based on stream, U bit, and MID instead of TSN. Fix the second by moving the call to sctp_intl_abort_pd() from sctp_report_iftsn() to the corresponding reset handlers.
Observed in real use as unexpected message loss. Reproduced on an unmodified kernel with the sctp_ifwdtsn.sh selftest added later in this series, which passes with this fix. Reproduction and fix done with AI assistance.
--- net/sctp/stream.c | 2 ++ net/sctp/stream_interleave.c | 32 +++++++++++--------------------- 2 files changed, 13 insertions(+), 21 deletions(-)
net/sctp/stream.c +2 -0
@@ -749,6 +749,7 @@ struct sctp_chunk *sctp_process_strreset*/ max_tsn_seen =sctp_tsnmap_get_max_tsn_seen (&asoc->peer.tsn_map); asoc->stream.si->report_ftsn (&asoc->ulpq, max_tsn_seen); + asoc->stream.si->abort_pd (&asoc->ulpq,GFP_ATOMIC );/* G1: Compute an appropriate value for the Receiver's Next TSN -- the * TSN that the peer should use to send the next DATA chunk. The
@@ -1028,6 +1029,7 @@ struct sctp_chunk *sctp_process_strresetLIST_HEAD (temp); asoc->stream.si->report_ftsn (&asoc->ulpq, mtsn); + asoc->stream.si->abort_pd (&asoc->ulpq,GFP_ATOMIC ); sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
net/sctp/stream_interleave.c +11 -21
@@ -1203,28 +1203,21 @@ static void sctp_report_fwdtsn(struct scsctp_ulpq_abort_pd (ulpq,GFP_ATOMIC ); } -static void sctp_intl_reasm_flushtsn (struct sctp_ulpq *ulpq,__u32 ftsn) +static void sctp_intl_reasm_flush_mid (struct sk_buff_head *reasm,__u16 sid, +__u32 mid) {struct sk_buff *pos, *tmp; - skb_queue_walk_safe(&ulpq->reasm, pos, tmp) { + skb_queue_walk_safe(reasm, pos, tmp) {struct sctp_ulpevent *event =sctp_skb2event (pos); -__u32 tsn = event->tsn; -if (TSN_lte (tsn, ftsn)) { -__skb_unlink (pos, &ulpq->reasm); -sctp_ulpevent_free (event); - } - } +if (event->stream < sid) +continue ; +if (event->stream > sid ||MID_lt (mid, event->mid)) +break ; - skb_queue_walk_safe(&ulpq->reasm_uo, pos, tmp) { -struct sctp_ulpevent *event =sctp_skb2event (pos); -__u32 tsn = event->tsn; - -if (TSN_lte (tsn, ftsn)) { -__skb_unlink (pos, &ulpq->reasm_uo); -sctp_ulpevent_free (event); - } +__skb_unlink (pos, reasm); +sctp_ulpevent_free (event); } }
@@ -1232,11 +1225,6 @@ static void sctp_report_iftsn(struct sct {/* Move the Cumulattive TSN Ack ahead. */ sctp_tsnmap_skip (&ulpq->asoc->peer.tsn_map, ftsn); -/* purge the fragmentation queue */ -sctp_intl_reasm_flushtsn (ulpq, ftsn); -/* abort only when it's for all data */ -if (ftsn ==sctp_tsnmap_get_max_tsn_seen (&ulpq->asoc->peer.tsn_map)) -sctp_intl_abort_pd (ulpq,GFP_ATOMIC ); }static void sctp_handle_fwdtsn (struct sctp_ulpq *ulpq,struct sctp_chunk *chunk)
@@ -1260,6 +1248,7 @@ static void sctp_intl_skip(struct sctp_usctp_intl_stream_abort_pd (ulpq, sid, mid,0x1 ,GFP_ATOMIC ); } +sctp_intl_reasm_flush_mid (&ulpq->reasm_uo, sid, mid);return ; }
@@ -1271,6 +1260,7 @@ static void sctp_intl_skip(struct sctp_usctp_intl_stream_abort_pd (ulpq, sid, mid,0x0 ,GFP_ATOMIC ); } +sctp_intl_reasm_flush_mid (&ulpq->reasm, sid, mid);sctp_mid_skip (stream, in, sid, mid);sctp_intl_reap_ordered (ulpq, sid);
Greg Kroah-Hartman
maintainerPATCH 651/816 sctp: report the partially delivered MID in PARTIAL_DELIVERY_ABORTED
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Budding <[email protected]>
commit 3097fba868019924e92b8786ebd473992565f015 upstream.
When an I-FORWARD-TSN skips the message being partially delivered on a stream, sctp_intl_skip() passes the MID from the I-FORWARD-TSN to the PARTIAL_DELIVERY_ABORTED notification as pdapi_seq. That MID is the highest one skipped on the stream, so when more than one message is skipped, the notification names a later message instead of the one whose partial delivery was aborted.
Report the MID being partially delivered, sin->mid_uo or sin->mid, instead.
Reproduced on an unmodified kernel with the pdapi and pdapi_uo tests of the sctp_ifwdtsn.sh selftest added later in this series, which pass with this fix. Reproduction and fix done with AI assistance.
--- net/sctp/stream_interleave.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
net/sctp/stream_interleave.c +2 -2
@@ -1245,7 +1245,7 @@ static void sctp_intl_skip(struct sctp_uif (flags &SCTP_FTSN_U_BIT ) {if (sin->pd_mode_uo && !MID_lt (mid, sin->mid_uo)) { sin->pd_mode_uo =0 ; -sctp_intl_stream_abort_pd (ulpq, sid, mid,0x1 , +sctp_intl_stream_abort_pd (ulpq, sid, sin->mid_uo,0x1 ,GFP_ATOMIC ); }sctp_intl_reasm_flush_mid (&ulpq->reasm_uo, sid, mid);
@@ -1257,7 +1257,7 @@ static void sctp_intl_skip(struct sctp_uif (sin->pd_mode) { sin->pd_mode =0 ; -sctp_intl_stream_abort_pd (ulpq, sid, mid,0x0 ,GFP_ATOMIC ); +sctp_intl_stream_abort_pd (ulpq, sid, sin->mid,0x0 ,GFP_ATOMIC ); }sctp_intl_reasm_flush_mid (&ulpq->reasm, sid, mid);
Greg Kroah-Hartman
maintainerPATCH 652/816 sctp: reset stored flag for each association
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
commit 173712d868eb20628ad82deb07f6829a68a9e064 upstream.
sctp_send_asconf_del_ip() walks every association on an endpoint. The stored flag records that the current association took the single-homed deferral path and therefore did not allocate an ASCONF chunk. It is currently scoped to the whole function. Once one association sets it, later eligible multihomed associations allocate chunks but skip sctp_send_asconf(), leaking each chunk and its skb.
Reset stored for every association so only an association taking the deferral path skips transmission. In an A/B kmemleak test, the vulnerable kernel reported 210 leaked objects from this call path and the fixed kernel reported none.
--- net/sctp/socket.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sctp/socket.c +1 -1
@@ -809,7 +809,6 @@ static int sctp_send_asconf_del_ip(strucstruct sctp_sockaddr_entry *saddr;int i;int retval =0 ; -int stored =0 ; chunk =NULL ; sp =sctp_sk (sk);
@@ -822,6 +821,7 @@ static int sctp_send_asconf_del_ip(struc __func__, sk, addrs, addrcnt);list_for_each_entry (asoc, &ep->asocs, asocs) { +int stored =0 ;if (!asoc->peer.asconf_capable)continue ;
Greg Kroah-Hartman
maintainerPATCH 653/816 LoongArch: Restore KFENCE pages through DMW on resume
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mike Rapoport (Microsoft) <[email protected]>
commit 40d7a3e63c3d88b43e9115d23d9937dd506bbd02 upstream.
With KFENCE enabled, resume from hibernation triggers KFENCE reports while swsusp_asm_resume() copies the image pages, for example:
BUG: KFENCE: use-after-free write in swsusp_asm_resume+0x20/0x94
Use-after-free write at 0x00000000a57ee925 (in kfence-#254):
swsusp_asm_resume+0x20/0x94 hibernation_restore+0x128/0x1a0 load_image_and_restore+0x6c/0xc8 software_resume+0x240/0x260 do_one_initcall+0x68/0x200 kernel_init_freeable+0x26c/0x304 kernel_init+0x20/0x134 ret_from_kernel_thread+0x24/0x1d0 ret_from_kernel_thread_asm+0xc/0x98
During resume from hibernation, the image pages that occupy physical pages used by the restore kernel are first loaded into free pages and then, as the very last step, swsusp_asm_resume() copies them to their final location pointed to by pbe->orig_address, which the hibernation core sets to page_address() of the page in the restore kernel.
The early KFENCE pool is allocated from memblock and normally occupies the same physical pages in the restore kernel and in the image kernel, so these pages are usually copied by swsusp_asm_resume().
The KFENCE pool is remapped into the KFENCE area above vm_map_base and set_page_address() adjusts page->virtual so that page_address() returns the page-table mapped alias rather than the DMW virtual address of the pool pages.
Hence, pbe->orig_address of KFENCE pages points to that alias and swsusp_asm_resume() writes them through the page tables. But:
* the copy loop overwrites the kernel page tables, so a TLB refill for the KFENCE alias may use a partially restored page table
* the KFENCE pool pages that are protected in the restore kernel fault in the middle of the copy
Convert pbe->orig_address to DMW addresses before starting the copy.
--- arch/loongarch/power/hibernate.c | 6 ++++++ 1 file changed, 6 insertions(+)
arch/loongarch/power/hibernate.c +6 -0
@@ -59,6 +59,12 @@ extern int swsusp_asm_resume(void);int swsusp_arch_resume (void ) { +#ifdef CONFIG_KFENCE +struct pbe *pbe; + +for (pbe = restore_pblist; pbe; pbe = pbe->next) + pbe->orig_address =__va (virt_to_phys (pbe->orig_address)); +#endif /* Avoid TLB mismatch during and after kernel resume */ local_flush_tlb_all ();return swsusp_asm_resume ();
Greg Kroah-Hartman
maintainerPATCH 654/816 tracing/eprobe: Fix 1-byte signed field fetch in get_event_field()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit a0f836eea463d4c468edb58eedb03911c9c0791d upstream.
Because the kernel is built with -funsigned-char, plain 'char' is unsigned on all architectures. Reading 1-byte signed trace event fields via *(char *)addr in get_event_field() therefore zero-extends instead of sign-extending negative s8 values.
Use explicit fixed-width integer types (s8/u8, s16/u16, s32/u32) when reading event fields.
--- kernel/trace/trace_eprobe.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
kernel/trace/trace_eprobe.c +6 -6
@@ -327,21 +327,21 @@ get_event_field(struct fetch_insn *code,switch (field->size) {case 1 :if (field->is_signed) - val = *(char *)addr; + val = *(s8 *)addr;else - val = *(unsigned char *)addr; + val = *(u8 *)addr;break ;case 2 :if (field->is_signed) - val = *(short *)addr; + val = *(s16 *)addr;else - val = *(unsigned short *)addr; + val = *(u16 *)addr;break ;case 4 :if (field->is_signed) - val = *(int *)addr; + val = *(s32 *)addr;else - val = *(unsigned int *)addr; + val = *(u32 *)addr;break ;default :if (field->is_signed)
Greg Kroah-Hartman
maintainerPATCH 655/816 tracing/eprobe: Disallow attaching eprobes to fprobe events
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 92d9fa0ed69e1f724feed908bd0a462a42df4b88 upstream.
Event probes (eprobes) are not allowed to attach to other dynamic probe events (kprobes, uprobes, and eprobes) to avoid recursive probe chains and lifecycle dependencies. However, when fprobe events were introduced, TRACE_EVENT_FL_FPROBE was omitted from the exclusion mask in find_and_get_event(), allowing eprobes to attach to fprobe and tprobe events.
Exclude TRACE_EVENT_FL_FPROBE events in find_and_get_event().
--- kernel/trace/trace_eprobe.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/trace/trace_eprobe.c +2 -1
@@ -750,7 +750,8 @@ find_and_get_event(const char *system, c (TRACE_EVENT_FL_IGNORE_ENABLE |TRACE_EVENT_FL_KPROBE |TRACE_EVENT_FL_UPROBE | - TRACE_EVENT_FL_EPROBE)) +TRACE_EVENT_FL_EPROBE | + TRACE_EVENT_FL_FPROBE)) continue;if (!tp_event->class->system ||strcmp (system, tp_event->class->system))
Greg Kroah-Hartman
maintainerPATCH 656/816 tracing/probes: Check enabled and busy state before unlinking sibling probes
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit f1d9b7a3fe99b4228acdbab3c744c29f7ffe86ef upstream.
When a multiprobe event is enabled or referenced (for example, by an eprobe, trigger, or open tracefs file) and a user attempts to delete the event or one of its probes via dynamic_events, checking trace_probe_has_sibling() before the enabled and busy checks allows the first probe to be unlinked and freed while the event is still active, only returning -EBUSY on the last sibling probe. For uprobe events, unlinking and freeing an enabled sibling probe without unregistering its uprobe_consumer also causes a use-after-free.
Ensure all four probe types (kprobe, fprobe, uprobe, and eprobe) verify that the event is neither enabled nor busy before unlinking any sibling probe.
--- kernel/trace/trace_eprobe.c | 12 ++++++++---- kernel/trace/trace_fprobe.c | 8 ++++---- kernel/trace/trace_kprobe.c | 8 ++++---- kernel/trace/trace_uprobe.c | 8 ++++++-- 4 files changed, 22 insertions(+), 14 deletions(-)
kernel/trace/trace_eprobe.c +8 -4
@@ -88,14 +88,18 @@ static int eprobe_dyn_event_show(structstatic int unregister_trace_eprobe (struct trace_eprobe *ep) { -/* If other probes are on the event, just unregister eprobe */ -if (trace_probe_has_sibling (&ep->tp)) - goto unreg; -/* Enabled event can not be unregistered */ if (trace_probe_is_enabled (&ep->tp))return -EBUSY ; +/* If there's a reference to the dynamic event */ +if (trace_event_dyn_busy (trace_probe_event_call (&ep->tp))) +return -EBUSY ; + +/* If other probes are on the event, just unregister eprobe */ +if (trace_probe_has_sibling (&ep->tp)) + goto unreg; +/* Will fail if probe is being used by ftrace or perf */ if (trace_probe_unregister_event_call (&ep->tp))return -EBUSY ;
kernel/trace/trace_fprobe.c +4 -4
@@ -753,10 +753,6 @@ static void __unregister_trace_fprobe(st/* Unregister a trace_probe and probe_event */ static int unregister_trace_fprobe (struct trace_fprobe *tf) { -/* If other probes are on the event, just unregister fprobe */ -if (trace_probe_has_sibling (&tf->tp)) - goto unreg; -/* Enabled event can not be unregistered */ if (trace_probe_is_enabled (&tf->tp))return -EBUSY ;
@@ -765,6 +761,10 @@ static int unregister_trace_fprobe(strucif (trace_event_dyn_busy (trace_probe_event_call (&tf->tp)))return -EBUSY ; +/* If other probes are on the event, just unregister fprobe */ +if (trace_probe_has_sibling (&tf->tp)) + goto unreg; +/* Will fail if probe is being used by ftrace or perf */ if (unregister_fprobe_event (tf))return -EBUSY ;
kernel/trace/trace_kprobe.c +4 -4
@@ -538,10 +538,6 @@ static void __unregister_trace_kprobe(st/* Unregister a trace_probe and probe_event */ static int unregister_trace_kprobe (struct trace_kprobe *tk) { -/* If other probes are on the event, just unregister kprobe */ -if (trace_probe_has_sibling (&tk->tp)) - goto unreg; -/* Enabled event can not be unregistered */ if (trace_probe_is_enabled (&tk->tp))return -EBUSY ;
@@ -550,6 +546,10 @@ static int unregister_trace_kprobe(strucif (trace_event_dyn_busy (trace_probe_event_call (&tk->tp)))return -EBUSY ; +/* If other probes are on the event, just unregister kprobe */ +if (trace_probe_has_sibling (&tk->tp)) + goto unreg; +/* Will fail if probe is being used by ftrace or perf */ if (unregister_kprobe_event (tk))return -EBUSY ;
kernel/trace/trace_uprobe.c +6 -2
@@ -392,13 +392,17 @@ static int unregister_trace_uprobe(struc {int ret; -if (trace_probe_has_sibling (&tu->tp)) - goto unreg; +/* Enabled event can not be unregistered */ +if (trace_probe_is_enabled (&tu->tp)) +return -EBUSY ;/* If there's a reference to the dynamic event */ if (trace_event_dyn_busy (trace_probe_event_call (&tu->tp)))return -EBUSY ; +if (trace_probe_has_sibling (&tu->tp)) + goto unreg; + ret =unregister_uprobe_event (tu);if (ret)return ret;
Greg Kroah-Hartman
maintainerPATCH 657/816 tracing/probes: Fix user-space dereference string array store type
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 2721573e6c6faaba2e31f352f2c02ec5f3ecf5e9 upstream.
When finalizing a string array argument (e.g. +0u(%reg):string[N]), finalize_fetch_insn() advances the instruction pointer to a new slot for the store operation before checking whether the preceding operation was FETCH_OP_UDEREF. As a result, user-space dereference string arrays with type "string" emit FETCH_OP_ST_STRING (kernel memory read) instead of FETCH_OP_ST_USTRING.
Check for FETCH_OP_UDEREF before advancing the instruction pointer.
--- kernel/trace/trace_probe.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
kernel/trace/trace_probe.c +4 -2
@@ -1333,6 +1333,8 @@ static int finalize_fetch_insn(struct fe/* Store operation */ if (parg->type->is_string) { +bool is_uderef; +/* Check bad combination of the type and the last fetch_insn. */ if (!strcmp (parg->type->name,"symstr" )) { if (code->op != FETCH_OP_REG && code->op != FETCH_OP_STACK &&
@@ -1352,6 +1354,7 @@ static int finalize_fetch_insn(struct fe } } + is_uderef = (code->op ==FETCH_OP_UDEREF ); if (!strcmp(parg->type->name, "symstr") || (code->op == FETCH_OP_IMM || code->op == FETCH_OP_COMM || code->op == FETCH_OP_DATA) || code->op == FETCH_OP_TP_ARG ||
@@ -1372,8 +1375,7 @@ static int finalize_fetch_insn(struct fe }/* If op == DEREF, replace it with STRING */ -if (!strcmp (parg->type->name,"ustring" ) || - code->op ==FETCH_OP_UDEREF ) +if (!strcmp (parg->type->name,"ustring" ) || is_uderef) code->op =FETCH_OP_ST_USTRING ;else if (!strcmp (parg->type->name,"symstr" )) code->op =FETCH_OP_ST_SYMSTR ;
Greg Kroah-Hartman
maintainerPATCH 658/816 tracing/probes: Reject array count on non-dereference string sources
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 0941144ebeaf3ce46c80711f00e935921eb28b21 upstream.
The runtime array loop (FETCH_OP_LP_ARRAY) for string types requires a preceding memory dereference instruction so it can advance the pointer address on each iteration. Non-dereference string sources such as $comm, immediate strings, and eprobe event fields cannot be indexed as pointer arrays, but finalize_fetch_insn() still accepts an array count on them and emits an invalid FETCH_OP_LP_ARRAY sequence.
Reject string array counts when the preceding operation is not a memory dereference.
--- kernel/trace/trace_probe.c | 6 ++++++ 1 file changed, 6 insertions(+)
kernel/trace/trace_probe.c +6 -0
@@ -1367,6 +1367,12 @@ static int finalize_fetch_insn(struct fe* For the symstr, it doesn't need to dereference, thus * it just get the value. */ +if (parg->count && (code->op !=FETCH_OP_DEREF && + code->op !=FETCH_OP_UDEREF )) { +trace_probe_log_err (ctx->offset + type_offset, +BAD_STRING ); +return -EINVAL ; + } code++;if (code->op !=FETCH_OP_NOP ) {trace_probe_log_err (ctx->offset,TOO_MANY_OPS );
Greg Kroah-Hartman
maintainerPATCH 659/816 wifi: ath9k_htc: do not start ANI before the first channel is set
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mehmet Fide <[email protected]>
commit dda63dd136ba2bc3b297079b190ac81a0aea40ae upstream.
ath9k_htc_add_interface() starts ANI for the first AP interface, before any channel is configured. The per-channel calibration data only gets attached by the first ath9k_htc_set_channel() that is not a fast channel change, and that same call cancels the ANI work a few milliseconds after add_interface, so normally the work never runs.
When the bring-up stalls for more than the 100 ms ANI poll interval in between, it does run, and ar9002_hw_per_calibration() records the IQ calibration result in the calibration data that does not exist yet:
Unable to handle kernel NULL pointer dereference at virtual address 00000008 PC is at ar9002_hw_calibrate+0x1f8/0x570 [ath9k_hw] Workqueue: phy0 ath9k_htc_ani_work [ath9k_htc]
Seen about once per thousand AP starts with an AR9271 on a Cortex-A5 board that starts hostapd while still booting; a 500 ms delay after add_interface reproduces it on every start. The crashed work never completes, so the next cancel_delayed_work_sync() blocks for good.
Drop the start; it has nothing to calibrate against and is cancelled anyway. The TSF adjust bit that shared its condition is now set for every AP interface, which is harmless: the next reset applies it. The next patch starts ANI once the interface beacons.
--- drivers/net/wireless/ath/ath9k/htc_drv_main.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-)
drivers/net/wireless/ath/ath9k/htc_drv_main.c +1 -4
@@ -1098,11 +1098,8 @@ static int ath9k_htc_add_interface(strucath9k_htc_set_opmode (priv); -if ((priv->ah->opmode ==NL80211_IFTYPE_AP ) && - !test_bit (ATH_OP_ANI_RUN , &common->op_flags)) { +if (priv->ah->opmode ==NL80211_IFTYPE_AP )ath9k_hw_set_tsfadjust (priv->ah, true); -ath9k_htc_start_ani (priv); - }ath_dbg (common,CONFIG ,"Attach a VIF of type: %d at idx: %d\n" , vif->type, avp->index);
Greg Kroah-Hartman
maintainerPATCH 660/816 wifi: cfg80211: release rejected nontransmitted BSS reference
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit f3c45d5b741a7d7586e639c2f55d2557029f2e1a upstream.
Repeated MBSSID reports without an SSID can leak BSS entries outside the scan cache, where the BSS entry limit cannot account for them.
__cfg80211_bss_update() returns a referenced BSS. If adding it to the transmitting BSS list fails, unlinking drops the cache reference, but the caller reference is lost when res is cleared.
Release the caller reference before discarding the unlinked BSS.
LLM assistance was used to find the bug and review.
--- net/wireless/scan.c | 1 + 1 file changed, 1 insertion(+)
net/wireless/scan.c +1 -0
@@ -2354,6 +2354,7 @@ cfg80211_inform_single_bss_data(struct wif (cfg80211_add_nontrans_list (data->source_bss, &res->pub)) {if (__cfg80211_unlink_bss (rdev, res)) { rdev->bss_generation++; +bss_ref_put (rdev, res); res =NULL ; } }
Greg Kroah-Hartman
maintainerPATCH 661/816 wifi: cfg80211: preserve mesh A-MSDU lengths when adding mesh headers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 9083da9dd3223068237395432323b407012aec1f upstream.
A malformed mesh A-MSDU subframe with a declared payload length near 65535 bytes can pass validation against a much shorter aggregate.
ieee80211_amsdu_subframe_length() adds the mesh control length to the declared length in a u16, and ieee80211_is_valid_amsdu() stores the result in a u16 local. The sum therefore wraps before either walker compares it with the remaining aggregate length. The decomposer then splits and delivers the malformed aggregate instead of rejecting it.
Keep the computed length in unsigned int in both the helper and the validator so oversized subframes cannot wrap.
LLM assistance was used to find the bug and review.
--- net/wireless/util.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
net/wireless/util.c +3 -3
@@ -772,12 +772,12 @@ __ieee80211_amsdu_copy(struct sk_buff *sreturn frame; } -static u16 +static unsigned int ieee80211_amsdu_subframe_length (void *field,u8 mesh_flags,u8 hdr_type) {__le16 *field_le = field;__be16 *field_be = field; -u16 len; +unsigned int len;if (hdr_type >=2 ) len =le16_to_cpu (*field_le);
@@ -799,7 +799,7 @@ bool ieee80211_is_valid_amsdu(struct sk___be16 len;u8 mesh_flags; } hdr; -u16 len; +unsigned int len;if (sizeof (hdr) > remaining)return false;
Greg Kroah-Hartman
maintainerPATCH 662/816 wifi: cfg80211: dont truncate the merged MBSSID profile length
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wahid Khan <[email protected]>
commit 3ea152f3f77eeffc37b2f4423688b4df9136f90c upstream.
cfg80211_parse_mbssid_data() keeps the length of a non-transmitted BSSID profile in a u8. cfg80211_merge_profile() returns a size_t, and it concatenates a profile that is split over several Multiple BSSID elements, so the merged length can be well above 255 even though every single sub-element is at most 255 bytes long.
The value is then cut to its low 8 bits. A 300 byte profile is handled as a 44 byte one: the elements after the cut are lost from the generated non-transmitted BSS, and if the Multiple BSSID-Index element lies past the cut the BSS is dropped altogether. Any AP in range can send such a profile.
The multi-link code further down in the same file already uses a signed size type for the profile length. Do the same here, cfg80211_find_ie() and cfg80211_gen_new_ie() take a size_t anyway.
--- net/wireless/scan.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/wireless/scan.c +1 -1
@@ -2497,7 +2497,7 @@ cfg80211_parse_mbssid_data(struct wiphyif (elem->data[0 ] <1 || (int )elem->data[0 ] >8 )continue ;for_each_element (sub, elem->data +1 , elem->datalen -1 ) { -u8 profile_len; +size_t profile_len;if (sub->id !=0 || sub->datalen <4 ) {/* not a valid BSS profile */
Greg Kroah-Hartman
maintainerPATCH 663/816 wifi: mac80211: fix use-after-free when MLO link setup is rolled back
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit a155ef2ef79531c139244289c5b8f15c05d16a0e upstream.
Rolling back an MLO link addition can free link containers while RCU readers still hold pointers to them. ieee80211_vif_update_links() publishes new links before checking for duplicate addresses and calling drv_change_vif_links(). If either fails, it restores the old pointers and frees the new containers without waiting for readers.
During a non-MLO to MLO transition, the published link 0 replaces the deflink, so existing link 0 users can acquire the new container. Readers such as ieee80211_csa_finish() and ieee80211_obss_color_collision_notify() can also queue work embedded in the link. If they queue after ieee80211_link_stop() cancels that work, it remains queued when the container is freed.
Wait for RCU readers after restoring the old pointers and before stopping the new links, so their work is queued before it is cancelled.
--- net/mac80211/link.c | 2 ++ 1 file changed, 2 insertions(+)
net/mac80211/link.c +2 -0
@@ -380,6 +380,8 @@ static int ieee80211_vif_update_links(stmemcpy (sdata->link, old_data,sizeof (old_data));memcpy (sdata->vif.link_conf, old,sizeof (old));ieee80211_set_vif_links_bitmaps (sdata, old_links, dormant_links); +/* drain RCU readers before cancelling work they may queue */ +synchronize_rcu ();for_each_set_bit (link_id, &add,IEEE80211_MLD_MAX_NUM_LINKS ) {ieee80211_link_debugfs_remove (&links[link_id]->data);ieee80211_link_stop (&links[link_id]->data);
Greg Kroah-Hartman
maintainerPATCH 664/816 wifi: mac80211: drain link readers before stopping removed links
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 745f5d04395dfc4c311f443c7c04ccb00c436984 upstream.
Removing an MLO link can leave work queued on its link container after the container is freed.
ieee80211_tear_down_links() stops each link before the RCU grace period. A reader that fetched the link earlier can therefore queue work after ieee80211_link_stop() has canceled it. ieee80211_request_smps() and ieee80211_csa_finish() can both reach this window.
Record each removed link while removing its keys and debugfs state. Wait for RCU readers, then stop the recorded links so cancellation includes work queued by those readers. Free the detached keys after the grace period as before.
LLM assistance was used to find the bug and review.
--- net/mac80211/link.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
net/mac80211/link.c +7 -1
@@ -176,6 +176,7 @@ struct link_container {static void ieee80211_tear_down_links (struct ieee80211_sub_if_data *sdata,struct link_container **links,u16 mask) { +struct ieee80211_link_data *stop[IEEE80211_MLD_MAX_NUM_LINKS ] = {};struct ieee80211_link_data *link;LIST_HEAD (keys);unsigned int link_id;
@@ -190,11 +191,16 @@ static void ieee80211_tear_down_links(stcontinue ;ieee80211_remove_link_keys (link, &keys);ieee80211_link_debugfs_remove (link); -ieee80211_link_stop (link); + stop[link_id] = link; } +/* drain RCU readers before cancelling work they may queue */ synchronize_rcu (); +for (link_id =0 ; link_id <IEEE80211_MLD_MAX_NUM_LINKS ; link_id++) +if (stop[link_id]) +ieee80211_link_stop (stop[link_id]); +ieee80211_free_key_list (sdata->local, &keys); }
Greg Kroah-Hartman
maintainerPATCH 665/816 wifi: mac80211: recheck injected headers after removing FCS
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 339564c7ac50464695dfed847f89d118f4cc1dc5 upstream.
Injecting a short frame with IEEE80211_RADIOTAP_F_FCS on a monitor interface can pass a truncated 802.11 header to transmit handlers.
ieee80211_monitor_start_xmit() validates the linear 802.11 header before parsing radiotap. Radiotap parsing then removes the four-byte FCS without rechecking the remaining header length. Software encryption can subtract the larger header length and pass the resulting negative length as an unsigned size.
Recheck the required linear header length after pulling the radiotap header and before handing the frame to the transmit path. Require at least addr1, which the transmit path reads even for extension frames whose header is shorter.
LLM assistance was used to find the bug and review.
--- net/mac80211/tx.c | 6 ++++++ 1 file changed, 6 insertions(+)
net/mac80211/tx.c +6 -0
@@ -2553,6 +2553,12 @@ netdev_tx_t ieee80211_monitor_start_xmit/* remove the injection radiotap header */ skb_pull (skb, len_rthdr); +/* FCS removal may have shortened the 802.11 header. */ + hdrlen =max_t (int, hdrlen, + offsetofend(struct ieee80211_hdr, addr1)); +if (skb_headlen (skb) < hdrlen) + goto fail_rcu; +ieee80211_xmit (sdata,NULL , skb);rcu_read_unlock ();
Greg Kroah-Hartman
maintainerPATCH 666/816 wifi: mac80211: recheck the IBSS station limit before insertion
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit f7670bcdf650b37551a9c5d084521f877d939f11 upstream.
Frames from successive unknown IBSS peers can make the deferred worker install more than 128 stations.
The receive path checks local->num_sta before allocating each station, but pending stations are not included in that count. Several allocations can therefore pass before the worker inserts any of them, and the worker then drains the list without rechecking the limit.
Recheck the installed-station limit in the worker under the wiphy mutex and free entries that no longer fit.
LLM assistance was used to find the bug and review.
--- net/mac80211/ibss.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
net/mac80211/ibss.c +6 -2
@@ -1662,8 +1662,12 @@ void ieee80211_ibss_work(struct ieee8021list_del (&sta->list);spin_unlock_bh (&ifibss->incomplete_lock); -ieee80211_ibss_finish_sta (sta); -rcu_read_unlock (); +if (sdata->local->num_sta >=IEEE80211_IBSS_MAX_STA_ENTRIES ) { +sta_info_free (sdata->local, sta); + }else { +ieee80211_ibss_finish_sta (sta); +rcu_read_unlock (); + }spin_lock_bh (&ifibss->incomplete_lock); }spin_unlock_bh (&ifibss->incomplete_lock);
Greg Kroah-Hartman
maintainerPATCH 667/816 wifi: mac80211: recheck the OCB station limit before insertion
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 27e29a077b4887d0e0a813337f8b7e06bd020c81 upstream.
Frames from successive unknown OCB peers can make the deferred worker install more than 128 stations.
The receive path checks local->num_sta before allocating each station, but pending stations are not included in that count. Several allocations can therefore pass before the worker inserts any of them, and the worker then drains the list without rechecking the limit.
Recheck the installed-station limit in the worker under the wiphy mutex and free entries that no longer fit.
LLM assistance was used to find the bug and review.
--- net/mac80211/ocb.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
net/mac80211/ocb.c +6 -2
@@ -136,8 +136,12 @@ void ieee80211_ocb_work(struct ieee80211list_del (&sta->list);spin_unlock_bh (&ifocb->incomplete_lock); -ieee80211_ocb_finish_sta (sta); -rcu_read_unlock (); +if (sdata->local->num_sta >=IEEE80211_OCB_MAX_STA_ENTRIES ) { +sta_info_free (sdata->local, sta); + }else { +ieee80211_ocb_finish_sta (sta); +rcu_read_unlock (); + }spin_lock_bh (&ifocb->incomplete_lock); }spin_unlock_bh (&ifocb->incomplete_lock);
Greg Kroah-Hartman
maintainerPATCH 668/816 wifi: mac80211: reject invalid EHT guard intervals in airtime estimates
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 582edbdbc5d288bd128b54935738fe38f15c8c29 upstream.
An invalid EHT guard interval can select the wrong airtime group and, at 320 MHz, read beyond airtime_mcs_groups.
Guard interval 3 advances EHT_GROUP_IDX() into the next bandwidth group at narrower widths. With one spatial stream and 320 MHz, it evaluates to 264, one past the 264-entry table. RX rate parsing rejects the value, but the common TX-status validator has no EHT check and last_rate_info can carry it to the airtime helper.
Reject values above NL80211_RATE_INFO_EHT_GI_3_2 in the helper. This also protects exported ieee80211_calc_rx_airtime() callers that do not pass through the TX-status validator.
LLM assistance was used to find the bug and review.
--- net/mac80211/airtime.c | 2 ++ 1 file changed, 2 insertions(+)
net/mac80211/airtime.c +2 -0
@@ -550,6 +550,8 @@ static u32 ieee80211_get_rate_duration(s group =HE_GROUP_IDX (streams, status->he_gi, bw);break ;case RX_ENC_EHT : +if (status->eht.gi >NL80211_RATE_INFO_EHT_GI_3_2 ) +return 0 ; streams = status->nss; idx = status->rate_idx; group =EHT_GROUP_IDX (streams, status->eht.gi, bw);
Greg Kroah-Hartman
maintainerPATCH 669/816 wifi: mac80211: restore dormant links when link updates fail
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit bb22f3b2d8f8a2f883944f24678cf84e18b162e8 upstream.
A failed MLO link update can leave the interface with the requested dormant-links bitmap instead of its previous one. This can disable active links or trigger a bitmap warning during rollback.
The error path restores the old valid-links bitmap but passes the new dormant_links argument to ieee80211_set_vif_links_bitmaps().
Save the old dormant bitmap before changing link state and use it when restoring the old configuration.
LLM assistance was used to find the bug and review.
--- net/mac80211/link.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/mac80211/link.c +2 -1
@@ -281,6 +281,7 @@ static int ieee80211_vif_update_links(st {u16 old_links = sdata->vif.valid_links;u16 old_active = sdata->vif.active_links; +u16 old_dormant = sdata->vif.dormant_links;unsigned long add = new_links & ~old_links;unsigned long rem = old_links & ~new_links;unsigned int link_id;
@@ -385,7 +386,7 @@ static int ieee80211_vif_update_links(st/* restore config */ memcpy (sdata->link, old_data,sizeof (old_data));memcpy (sdata->vif.link_conf, old,sizeof (old)); -ieee80211_set_vif_links_bitmaps (sdata, old_links, dormant_links); +ieee80211_set_vif_links_bitmaps (sdata, old_links, old_dormant);/* drain RCU readers before cancelling work they may queue */ synchronize_rcu ();for_each_set_bit (link_id, &add,IEEE80211_MLD_MAX_NUM_LINKS ) {
Greg Kroah-Hartman
maintainerPATCH 670/816 wifi: mac80211: bound pending IBSS station allocations
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 3029ca2112d7bee4d3e3eadd02decdb3eddb9485 upstream.
Delaying the IBSS station worker while frames arrive from new peers can retain an unbounded number of station allocations.
The receive-side limit counts installed stations, while new allocations wait on incomplete_stations until process context inserts them. The list lock does not cover the interval between allocation and list insertion.
Reserve one of 128 pending slots per interface before allocation. Release the reservation on allocation failure, after the worker inserts or frees the station, and when disconnect frees the pending list.
LLM assistance was used to find the bug and review.
--- net/mac80211/ibss.c | 13 ++++++++++++- net/mac80211/ieee80211_i.h | 1 + 2 files changed, 13 insertions(+), 1 deletion(-)
net/mac80211/ibss.c +12 -1
@@ -698,6 +698,7 @@ static void ieee80211_ibss_disconnect(stspin_unlock_bh (&ifibss->incomplete_lock);sta_info_free (local, sta); +atomic_dec (&ifibss->incomplete_sta_count);spin_lock_bh (&ifibss->incomplete_lock); }spin_unlock_bh (&ifibss->incomplete_lock);
@@ -1213,9 +1214,18 @@ void ieee80211_ibss_rx_no_sta(struct iee band = chanctx_conf->def.chan->band;rcu_read_unlock (); +if (!atomic_add_unless (&ifibss->incomplete_sta_count,1 , +IEEE80211_IBSS_MAX_STA_ENTRIES )) { +net_info_ratelimited ("%s: No room for a new IBSS STA entry %pM\n" , + sdata->name, addr); +return ; + } + sta =sta_info_alloc (sdata, addr,GFP_ATOMIC ); -if (!sta) +if (!sta) { +atomic_dec (&ifibss->incomplete_sta_count);return ; + }/* make sure mandatory rates are always added */ sband = local->hw.wiphy->bands[band];
@@ -1668,6 +1678,7 @@ void ieee80211_ibss_work(struct ieee8021ieee80211_ibss_finish_sta (sta);rcu_read_unlock (); } +atomic_dec (&ifibss->incomplete_sta_count);spin_lock_bh (&ifibss->incomplete_lock); }spin_unlock_bh (&ifibss->incomplete_lock);
net/mac80211/ieee80211_i.h +1 -0
@@ -634,6 +634,7 @@ struct ieee80211_if_ibss {spinlock_t incomplete_lock;struct list_head incomplete_stations; +atomic_t incomplete_sta_count;enum {IEEE80211_IBSS_MLME_SEARCH ,
Greg Kroah-Hartman
maintainerPATCH 671/816 wifi: mac80211: bound pending OCB station allocations
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit ee1a5e92dba0a98cabe476c780e3af4f0ab88b27 upstream.
Delaying the OCB station worker while frames arrive from new peers can retain an unbounded number of station allocations.
The receive-side limit counts installed stations, while new allocations wait on incomplete_stations until process context inserts them. The list lock does not cover the interval between allocation and list insertion.
Reserve one of 128 pending slots per interface before allocation. Release the reservation on allocation failure, after the worker inserts or frees the station, and when leave frees the pending list.
LLM assistance was used to find the bug and review.
--- net/mac80211/ieee80211_i.h | 2 ++ net/mac80211/ocb.c | 13 ++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-)
net/mac80211/ieee80211_i.h +2 -0
@@ -649,6 +649,7 @@ struct ieee80211_if_ibss {* @wrkq_flags: OCB deferred task action * @incomplete_lock: delayed STA insertion lock * @incomplete_stations: list of STAs waiting for delayed insertion +* @incomplete_sta_count: pending entries and reserved allocations * @joined: indication if the interface is connected to an OCB network */ struct ieee80211_if_ocb {
@@ -657,6 +658,7 @@ struct ieee80211_if_ocb {spinlock_t incomplete_lock;struct list_head incomplete_stations; +atomic_t incomplete_sta_count;bool joined; };
net/mac80211/ocb.c +12 -1
@@ -70,9 +70,18 @@ void ieee80211_ocb_rx_no_sta(struct ieee band = chanctx_conf->def.chan->band;rcu_read_unlock (); +if (!atomic_add_unless (&ifocb->incomplete_sta_count,1 , +IEEE80211_OCB_MAX_STA_ENTRIES )) { +net_info_ratelimited ("%s: No room for a new OCB STA entry %pM\n" , + sdata->name, addr); +return ; + } + sta =sta_info_alloc (sdata, addr,GFP_ATOMIC ); -if (!sta) +if (!sta) { +atomic_dec (&ifocb->incomplete_sta_count);return ; + }/* Add only mandatory rates for now */ sband = local->hw.wiphy->bands[band];
@@ -142,6 +151,7 @@ void ieee80211_ocb_work(struct ieee80211ieee80211_ocb_finish_sta (sta);rcu_read_unlock (); } +atomic_dec (&ifocb->incomplete_sta_count);spin_lock_bh (&ifocb->incomplete_lock); }spin_unlock_bh (&ifocb->incomplete_lock);
@@ -225,6 +235,7 @@ int ieee80211_ocb_leave(struct ieee80211spin_unlock_bh (&ifocb->incomplete_lock);sta_info_free (local, sta); +atomic_dec (&ifocb->incomplete_sta_count);spin_lock_bh (&ifocb->incomplete_lock); }spin_unlock_bh (&ifocb->incomplete_lock);
Greg Kroah-Hartman
maintainerPATCH 672/816 gpio: brcmstb: fix UAF after IRQ domain setup failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guangshuo Li <[email protected]>
commit baa14758afb3e2828de1f76511edc1de50216f39 upstream.
When devm_request_irq() fails in brcmstb_gpio_irq_setup(), the error path removes the IRQ domain but leaves priv->irq_domain non-NULL.
The probe error path subsequently calls brcmstb_gpio_remove(), which checks priv->irq_domain and attempts to access the already-freed domain through irq_find_mapping(). It also attempts to remove the domain again, resulting in a use-after-free and potentially further memory corruption.
Set priv->irq_domain to NULL after removing it so that the common cleanup path skips the already-freed IRQ domain.
This issue was found by our static analysis tool under development.
--- drivers/gpio/gpio-brcmstb.c | 1 + 1 file changed, 1 insertion(+)
drivers/gpio/gpio-brcmstb.c +1 -0
@@ -487,6 +487,7 @@ static int brcmstb_gpio_irq_setup(struct out_free_domain:irq_domain_remove (priv->irq_domain); + priv->irq_domain =NULL ;return err; }
Greg Kroah-Hartman
maintainerPATCH 673/816 gpio: rockchip: Fix debounce arithmetic for GPIO v2
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cunhao Lu <[email protected]>
commit 13467fd6998f5da4f5b4f172f1af3d9c48d5de8f upstream.
The debounce interval calculations use unsigned long operands. On 32-bit systems, the numerator used to calculate the maximum interval overflows before division, while multiplying the requested interval by the clock rate overflows before it is assigned to a u64. A zero debounce clock rate also causes division by zero.
Use 64-bit arithmetic for both calculations and reject a zero clock rate before division.
At 32768 Hz, a 1 us request rounds to zero divider periods. Subtracting one then wraps the divider value to ULONG_MAX. Decrement only a nonzero rounded period count so that such requests use the smallest divider value.
--- drivers/gpio/gpio-rockchip.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/gpio/gpio-rockchip.c +10 -5
@@ -192,20 +192,25 @@ static int rockchip_gpio_set_debounce(st {struct rockchip_pin_bank *bank =gpiochip_get_data (gc);const struct rockchip_gpio_regs *reg = bank->gpio_regs; -unsigned long flags, div_reg, freq, max_debounce; +unsigned long flags, div_reg, freq;bool div_debounce_support;unsigned int cur_div_reg; -u64 div; +u64 div, max_debounce;if (bank->gpio_type ==GPIO_TYPE_V2 && !IS_ERR (bank->db_clk)) { div_debounce_support = true; freq =clk_get_rate (bank->db_clk); - max_debounce = (GENMASK (23 ,0 ) +1 ) *2 *1000000 / freq; +if (!freq) +return -EINVAL ; + + div = (u64)(GENMASK (23 ,0 ) +1 ) *2 *USEC_PER_SEC ; + max_debounce =div64_u64 (div, freq);if (debounce > max_debounce)return -EINVAL ; - div = debounce * freq; - div_reg =DIV_ROUND_CLOSEST_ULL (div,2 *USEC_PER_SEC ) -1 ; + div = (u64 )debounce * freq; + div_reg =DIV_ROUND_CLOSEST_ULL (div,2 *USEC_PER_SEC ); + div_reg = div_reg ? div_reg -1 :0 ; }else { div_debounce_support = false; }
Greg Kroah-Hartman
maintainerPATCH 674/816 gpio: sodaville: fix use-after-free bug when registering the irqchip
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit ab9102375b7c77e0c4d33c7594e514454dc9f2b3 upstream.
In sdv_register_irqsupport(), if irq_domain_create_legacy() fails during device probing, a generic IRQ chip is left registered in the global gc_list while its underlying memory is freed, leading to a use-after-free. Use the managed variant of irq_setup_generic_chip() to ensure that the chip gets unregistered before the memory it uses is freed.
--- drivers/gpio/gpio-sodaville.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/gpio/gpio-sodaville.c +6 -3
@@ -165,9 +165,12 @@ static int sdv_register_irqsupport(struc ct->chip.irq_eoi = irq_gc_eoi; ct->chip.irq_set_type = sdv_gpio_pub_set_type; -irq_setup_generic_chip (sd->gc,IRQ_MSK (SDV_NUM_PUB_GPIOS ), -IRQ_GC_INIT_MASK_CACHE ,IRQ_NOREQUEST , -IRQ_LEVEL |IRQ_NOPROBE ); + ret =devm_irq_setup_generic_chip (&pdev->dev, sd->gc, +IRQ_MSK (SDV_NUM_PUB_GPIOS ), +IRQ_GC_INIT_MASK_CACHE ,IRQ_NOREQUEST , +IRQ_LEVEL |IRQ_NOPROBE ); +if (ret) +return ret; sd->id =irq_domain_add_legacy (pdev->dev.of_node,SDV_NUM_PUB_GPIOS , sd->irq_base,0 , &irq_domain_sdv_ops, sd);
Greg Kroah-Hartman
maintainerPATCH 675/816 gpio: virtuser: fix interrupt leak and UAF
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit 24cafd9580627f9f066296f4a6ce1b282a3f425d upstream.
When configuring interrupt handlers for GPIOs requested by virtual users, we never verify if an interrupt has been previously requested and just leak it if it was.
We also never free the interrupts at device unbind. This is both a leak and a potential UAF bug.
We use atomic_t for the irq field for now reason, it can't be modifying or read from atomic context. Let's repurpose the existing consumer_lock mutex and serialize access to the irq field. Let's add sanitization of input and schedule a tear-down action.
--- drivers/gpio/gpio-virtuser.c | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-)
drivers/gpio/gpio-virtuser.c +29 -10
@@ -57,9 +57,9 @@ struct gpio_virtuser_line_array_data {struct gpio_virtuser_line_data {struct gpio_virtuser_attr_data ad;char consumer[GPIO_VIRTUSER_NAME_BUF_LEN ]; -struct mutex consumer_lock; +struct mutex lock;unsigned int debounce; -atomic_t irq; +int irq;atomic_t irq_count; };
@@ -613,7 +613,7 @@ static ssize_t gpio_virtuser_consumer_rememset (buf,0x0 ,sizeof (buf)); -scoped_guard (mutex, &data->consumer_lock) +scoped_guard (mutex, &data->lock) ret = snprintf(buf, sizeof(buf), "%s\n", data->consumer);return simple_read_from_buffer (user_buf, size, ppos, buf, ret);
@@ -641,7 +641,7 @@ static ssize_t gpio_virtuser_consumer_wrif (ret)return ret; - scoped_guard(mutex, &data->consumer_lock) + scoped_guard(mutex, &data->lock)strscpy (data->consumer, buf,sizeof (data->consumer));return count;
@@ -681,7 +681,12 @@ static int gpio_virtuser_interrupts_set(if (val >1 )return -EINVAL ; +guard (mutex)(&ld->lock); +if (val) { +if (ld->irq >=0 ) +return -EBUSY ; + irq =gpiod_to_irq (ld->ad.desc);if (irq <0 )return irq;
@@ -695,11 +700,13 @@ static int gpio_virtuser_interrupts_set(if (ret)return ret; -atomic_set (&ld->irq, irq); + ld->irq = irq; }else { - irq =atomic_xchg (&ld->irq,0 ); -if (irq) -free_irq (irq, ld); +if (ld->irq <0 ) +return -EBUSY ; + +free_irq (ld->irq, ld); + ld->irq =-1 ; }return 0 ;
@@ -799,6 +806,14 @@ static int gpio_virtuser_dbgfs_init_line data->ad.dbgfs_dir, data); } +static void gpio_virtuser_free_irq (void *data) +{ +struct gpio_virtuser_line_data *ld = data; + +if (ld->irq >=0 ) +free_irq (ld->irq, ld); +} + static int gpio_virtuser_dbgfs_init_line_attrs(struct device *dev, struct gpio_desc *desc, const char *id,
@@ -815,14 +830,18 @@ static int gpio_virtuser_dbgfs_init_line data->ad.desc = desc;strscpy (data->consumer, id); -atomic_set (&data->irq,0 ); + data->irq =-1 ;atomic_set (&data->irq_count,0 ); + ret =devm_add_action_or_reset (dev, gpio_virtuser_free_irq, data); +if (ret) +return ret; + name =devm_kasprintf (dev,GFP_KERNEL ,"gpiod:%s:%u" , id, index);if (!name)return -ENOMEM ; - ret =devm_mutex_init (dev, &data->consumer_lock); + ret =devm_mutex_init (dev, &data->lock);if (ret)return ret;
Greg Kroah-Hartman
maintainerPATCH 676/816 gpio: virtuser: remove the debugfs files before freeing the line data
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yu Zhang <[email protected]>
commit c2d0710318b8cd57d0ef6088d0ee4bbc1e827fd3 upstream.
gpio_virtuser_probe() registers the devm action that removes the debugfs directory before it allocates the per-line and per-array data that the debugfs files point to. devres releases resources in reverse order, so on unbind the line data is freed, the consumer_lock mutex is destroyed and the GPIO descriptors are put first, and the debugfs files are only removed afterwards.
A read or write of any of the per-line debugfs files (value, direction, consumer, interrupts, ...) that runs in that window dereferences the freed data. debugfs_remove_recursive() waits for in-flight file operations, but by then the data has already been freed.
Running eight threads that read the per-line debugfs files while another task writes 1 and 0 to the configfs "live" attribute triggers this within a second on a KASAN kernel, with gpio-sim as the provider:
BUG: KASAN: slab-use-after-free in gpio_virtuser_value_get+0x19/0x60 Read of size 8 at addr ffff888005109e38 by task vu_race/3479 Call Trace: gpio_virtuser_value_get+0x19/0x60 simple_attr_read+0x109/0x290 debugfs_attr_read+0x5e/0x80 full_proxy_read+0xae/0xe0 vfs_read+0x1bc/0x7a0 Allocated by task 1: devm_kmalloc+0x89/0x1d0 gpio_virtuser_probe+0x56f/0x910 Freed by task 1: kfree+0x196/0x430 release_nodes+0x77/0xa0 devres_release_all+0xf3/0x150 device_unbind_cleanup+0x18/0x130 ... platform_device_unregister+0x3c/0x50 gpio_virtuser_device_deactivate+0x3c/0xc0
The same run also reports use-after-free on the freed consumer_lock from the consumer attribute.
Register the debugfs removal action after the line data has been set up, so that it runs first on unbind, and remove the directory by hand on the probe error paths before that point.
--- drivers/gpio/gpio-virtuser.c | 46 +++++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 17 deletions(-)
drivers/gpio/gpio-virtuser.c +29 -17
@@ -952,38 +952,50 @@ static int gpio_virtuser_probe(struct pl "Failed to get the IDs of GPIOs to request\n"); dbgfs_entry =debugfs_create_dir (dev_name (dev), gpio_virtuser_dbg_root); - ret =devm_add_action_or_reset (dev, gpio_virtuser_debugfs_remove, - dbgfs_entry); -if (ret) -return ret;for (i =0 ; i < num_ids; i++) { descs =devm_gpiod_get_array (dev, ids[i],GPIOD_ASIS ); -if (IS_ERR (descs)) -return dev_err_probe (dev,PTR_ERR (descs), -"Failed to request the '%s' GPIOs\n" , - ids[i]); +if (IS_ERR (descs)) { + ret =dev_err_probe (dev,PTR_ERR (descs), +"Failed to request the '%s' GPIOs\n" , + ids[i]); + goto err_remove_debugfs; + } ret =gpio_virtuser_dbgfs_init_line_array_attrs (dev, descs, ids[i], dbgfs_entry); -if (ret) -return dev_err_probe (dev, ret, -"Failed to setup the debugfs array interface for the '%s' GPIOs\n" , - ids[i]); +if (ret) { +dev_err_probe (dev, ret, +"Failed to setup the debugfs array interface for the '%s' GPIOs\n" , + ids[i]); + goto err_remove_debugfs; + }for (j =0 ; j < descs->ndescs; j++) { ret =gpio_virtuser_dbgfs_init_line_attrs (dev, descs->desc[j], ids[i], j, dbgfs_entry); -if (ret) -return dev_err_probe (dev, ret, -"Failed to setup the debugfs line interface for the '%s' GPIOs\n" , - ids[i]); +if (ret) { +dev_err_probe (dev, ret, +"Failed to setup the debugfs line interface for the '%s' GPIOs\n" , + ids[i]); + goto err_remove_debugfs; + } } } -return 0 ; +/* +* The debugfs files point to the devres-managed line data allocated +* above. Register the removal last so that it runs first on unbind, +* before any of that data is released. +*/ +return devm_add_action_or_reset (dev, gpio_virtuser_debugfs_remove, + dbgfs_entry); + +err_remove_debugfs: +debugfs_remove_recursive (dbgfs_entry); +return ret; }static const struct of_device_id gpio_virtuser_of_match[] = {
Greg Kroah-Hartman
maintainerPATCH 677/816 ovl: do not always clear absolute_redirect
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giuseppe Scrivano <[email protected]>
commit 477449a7a5fd1b2fe973fe2978b0c921115a65f3 upstream.
ovl_check_redirect() clears d->absolute_redirect before it checks that the path element has a redirect xattr. An element without one, such as an intermediate directory in a lower layer, then clears the flag set by the absolute redirect of a metacopy file found in a higher layer. The lookup of the data in the data-only layers is not deferred any more and the lookup fails with -EIO:
# l2/f: metacopy, redirect "/dir/file"; l1/dir/ exists, no "file"
mount -t overlay none -o metacopy=on,redirect_dir=on,\
lowerdir+=l2,lowerdir+=l1,datadir+=data m
cat m/f # Input/output errorSet d->absolute_redirect only when a redirect xattr was read.
--- fs/overlayfs/namei.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
fs/overlayfs/namei.c +2 -3
@@ -38,13 +38,12 @@ static int ovl_check_redirect(const struchar *buf;struct ovl_fs *ofs =OVL_FS (d->sb); - d->absolute_redirect = false; buf =ovl_get_redirect_xattr (ofs, path, prelen +strlen (post));if (IS_ERR_OR_NULL (buf))return PTR_ERR (buf); -if (buf[0 ] =='/' ) { - d->absolute_redirect = true; + d->absolute_redirect = buf[0 ] =='/' ; +if (d->absolute_redirect) {/* * One of the ancestor path elements in an absolute path * lookup in ovl_lookup_layer() could have been opaque and
Greg Kroah-Hartman
maintainerPATCH 678/816 ovl: reject different lower idmaps on the same fs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 720f40c05b2785406121da0151543751204f2953 upstream.
Overayfs mounted with index=on or nfs_export=on require file handle support from backing filesystems.
Overlay file handles identify a backing filesystem, but not the lower mount used to decode it. If lower layers share a superblock and use different idmaps, a handle can decode through the wrong layer.
Record the first idmap on a private lower clone for each backing filesystem. Fail if another clone has a different idmap. Comparing the private clones prevents mount_setattr() from changing the checked state. Distinct idmap objects are treated as ambiguous.
--- fs/overlayfs/ovl_entry.h | 2 ++ fs/overlayfs/super.c | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+)
fs/overlayfs/ovl_entry.h +2 -0
@@ -24,6 +24,8 @@ struct ovl_config {struct ovl_sb {struct super_block *sb;dev_t pseudo_dev; +/* Idmap of the first lower layer on this fs */ +const struct mnt_idmap *lower_idmap;/* Unusable (conflicting) uuid */ bool bad_uuid;/* Used as a lower layer (but maybe also as upper) */
fs/overlayfs/super.c +23 -0
@@ -1056,6 +1056,29 @@ static int ovl_get_layers(struct super_b }/* +* Lower file handles identify the lower fs, but not the layer, +* so with different idmaps on the same lower fs, index and +* nfs_export may decode a file handle through a layer with the +* wrong idmap. Following copy up origin without index is only +* used for st_ino, which does not depend on the idmap. +*/ +if (i < nr_merged_lower && + (ofs->config.index || ofs->config.nfs_export)) { +const struct mnt_idmap *idmap =mnt_idmap (mnt); +struct ovl_sb *fs = &ofs->fs[fsid]; + +if (!fs->lower_idmap) { + fs->lower_idmap = idmap; + }else if (fs->lower_idmap != idmap) { +pr_err ("lower layer '%pd2' conflicts with idmap of another lower layer on the same fs, mount with '-o index=off,nfs_export=off' to override.\n" , + l->path.dentry); +iput (trap); +kern_unmount (mnt); +return -EINVAL ; + } + } + +/* * Make lower layers R/O. That way fchmod/fchown on lower file * will fail instead of modifying lower fs. */
Greg Kroah-Hartman
maintainerPATCH 679/816 ovl: report the requested redirect_dir mode in conflicting options
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
commit 248503755b3cab89742edcc3cfd53adbcf7bfec2 upstream.
Since the redirect_dir mode is stored as an enum, "off" is translated to "follow" or "nofollow" when parsing the option and redirect_dir=follow is translated to "on" for a non-upper mount, so the errors about options that conflict with an explicit redirect_dir= report a mode that the user did not request.
Translate "off" when verifying the mount options instead of when parsing them and report the requested mode in those errors.
--- fs/overlayfs/overlayfs.h | 10 +++++++--- fs/overlayfs/params.c | 43 ++++++++++++++++++++++++++++++------------- 2 files changed, 37 insertions(+), 16 deletions(-)
fs/overlayfs/overlayfs.h +7 -3
@@ -74,9 +74,13 @@ enum ovl_entry_flag { };enum { -OVL_REDIRECT_OFF ,/* "off" mode is never used. In effect */ -OVL_REDIRECT_FOLLOW ,/* ...it translates to either "follow" */ -OVL_REDIRECT_NOFOLLOW ,/* ...or "nofollow". */ +/* +* "off" mode is never used after mount options are verified. In effect +* it translates to either "follow" or "nofollow". +*/ +OVL_REDIRECT_OFF , +OVL_REDIRECT_FOLLOW , +OVL_REDIRECT_NOFOLLOW ,OVL_REDIRECT_ON , };
fs/overlayfs/params.c +30 -13
99 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 680/816 ovl: return EIO if the lowerdata is missing
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giuseppe Scrivano <[email protected]>
commit 0d5e729c515f4ae4eacc179dbcf350d9b499a161 upstream.
The data of a metacopy file that redirects to a data-only layer is looked up when the file is opened, and the error of the lookup is returned as is. If the data file is missing, open() fails with ENOENT even though the file is there and stat() works.
This can be an integrity problem when using composefs: a data file that is changed or has the wrong fs-verity digest is reported with EIO, but a missing one is not reported, the file just looks like it does not exist, e.g. a configuration file that overrides the defaults.
Return EIO as it is already done in ovl_lookup() when no lower data is found for a metacopy file. ENOMEM is not changed.
--- fs/overlayfs/namei.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/overlayfs/namei.c +8 -0
@@ -1020,6 +1020,14 @@ out: out_err:pr_warn_ratelimited ("lazy lowerdata lookup failed (%pd2, err=%i)\n" , dentry, err); +/* +* The data of a metacopy file is missing or is not a regular file in +* the data-only layers: the layers are corrupted. Do not return the +* error of the lookup (e.g. ENOENT) to the caller, it would make the +* file look like it does not exist. +*/ +if (err != -ENOMEM ) + err = -EIO ; goto out; }
Greg Kroah-Hartman
maintainerPATCH 681/816 smb: client: bound invalid NTLMSSP signature diagnostic
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yifan Zhang <[email protected]>
commit 0584b02669c3e76188097174b4f25ed13723e94c upstream.
The NTLMSSP Signature field is an eight-byte binary value and need not be NUL-terminated. decode_ntlmssp_challenge() prints it with %s on the signature-mismatch path, so the diagnostic can continue beyond the received blob until it encounters a zero byte.
KASAN reports:
BUG: KASAN: slab-out-of-bounds in string Read of size 1 string vsnprintf _printk decode_ntlmssp_challenge
Print the fixed-width field with the bounded hexadecimal format.
The patched kernel reaches the invalid-signature path and returns -EINVAL without a KASAN report.
--- fs/smb/client/sess.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/smb/client/sess.c +2 -2
@@ -961,8 +961,8 @@ int decode_ntlmssp_challenge(char *bcc_p }if (memcmp (pblob->Signature,"NTLMSSP" ,8 )) { -cifs_dbg (VFS ,"blob signature incorrect %s\n" , - pblob->Signature); +cifs_dbg (VFS ,"%s: blob signature incorrect: %8phN\n" , + __func__, pblob->Signature);return -EINVAL ; }if (pblob->MessageType != NtLmChallenge) {
Greg Kroah-Hartman
maintainerPATCH 682/816 smb: client: compare owner and group SIDs using their encoded lengths
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: liuyong <[email protected]>
commit a2dabe73ea05ad3b3f8e1cc08fb2e7c2ddc5564b upstream.
populate_new_aces() compares owner and group SIDs over sizeof(struct smb_sid), including storage for all 15 possible subauthorities. Received SIDs contain only their encoded subauthorities. The comparison can read past the security descriptor, as shown by the supplied KASAN report for a 44-byte descriptor during chmod.
The input SIDs have already been checked by sid_from_sd(). Require equal subauthority counts, then compare only the fixed SID header and the encoded subauthorities with memcmp(). The count check ensures that both validated SIDs contain the number of bytes being compared.
These issues were discovered and fixed by Qihoo 360's Tulongfeng multi-agent system.
--- fs/smb/client/cifsacl.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/smb/client/cifsacl.c +4 -1
@@ -1062,7 +1062,10 @@ static void populate_new_aces(char *nacl* updated in the inode. */ -if (!memcmp (pownersid, pgrpsid,sizeof (struct smb_sid ))) { +if (pownersid->num_subauth == pgrpsid->num_subauth && + !memcmp (pownersid, pgrpsid, +CIFS_SID_BASE_SIZE + + pownersid->num_subauth *sizeof (__le32))) {/* * Case when owner and group SIDs are the same. * Set the more restrictive of the two modes.
Greg Kroah-Hartman
maintainerPATCH 683/816 smb: client: dont block dying tasks waiting for writeback on close
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 15ea186abbcd04157c62e0901701870b812bb2bd upstream.
cifs_flush() waits uninterruptibly for the writeback it starts. A task that gets killed while closing a file on a hard mount with an unresponsive server is stuck in D state until the server comes back. It also consumes any writeback error for a caller that is about to exit, hiding it from everyone else.
Wait killably instead. If the closer gets killed, stop waiting and leave the error bits in the mapping for others to see; writeback already in flight completes on its own. Don't wait at all, nor check for errors, if it is already dying.
This is also needed before letting dying tasks issue their writes from a worker, which would otherwise make them wait for every one of them.
--- fs/smb/client/file.c | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-)
fs/smb/client/file.c +30 -3
@@ -2760,17 +2760,44 @@ fsync_exit:return rc; } +static int cifs_wait_writeback_killable (struct address_space *mapping) +{ +struct folio_batch fbatch; +pgoff_t index =0 ; +int rc =0 ; + +folio_batch_init (&fbatch); +while (!rc && +filemap_get_folios_tag (mapping, &index, (pgoff_t)-1 , +PAGECACHE_TAG_WRITEBACK , &fbatch)) { +for (unsigned int i =0 ; + !rc && i <folio_batch_count (&fbatch); i++) + rc =folio_wait_writeback_killable (fbatch.folios[i]); +folio_batch_release (&fbatch); +cond_resched (); + } +return rc; +} +/* * As file closes, flush all cached write data for this inode checking * for write behind errors. */ int cifs_flush (struct file *file,fl_owner_t id) { +struct address_space *mapping = file->f_mapping;struct inode *inode =file_inode (file); -int rc =0 ; +int rc =0 , rc2; -if (file->f_mode &FMODE_WRITE ) - rc =filemap_write_and_wait (inode->i_mapping); +if (file->f_mode &FMODE_WRITE ) { + rc =filemap_fdatawrite (mapping); +if (fatal_signal_pending (current) || +cifs_wait_writeback_killable (mapping)) +return 0 ; + rc2 =filemap_check_errors (mapping); +if (!rc) + rc = rc2; + }cifs_dbg (FYI ,"Flush inode %p file %p rc %d\n" , inode, file, rc);if (rc) {
Greg Kroah-Hartman
maintainerPATCH 684/816 smb: client: dont block dying tasks waiting for writeback on fsync
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 0df0f24803061b6c2bef0d24de7c63c9cce46a49 upstream.
cifs_fsync() and cifs_strict_fsync() wait uninterruptibly for writeback through file_write_and_wait_range(). As with close, a task killed in fsync(2) on a hard mount with an unresponsive server is stuck in D state until the server comes back.
Wait killably instead, using the same helper as cifs_flush(). The writeback keeps going and its errors stay in the mapping; only the dying caller stops waiting for it.
--- fs/smb/client/file.c | 64 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 42 insertions(+), 22 deletions(-)
fs/smb/client/file.c +42 -22
@@ -2655,6 +2655,45 @@ cifs_get_readable_path(struct cifs_tconreturn -ENOENT ; } +static int cifs_wait_writeback_killable (struct address_space *mapping, +loff_t start,loff_t end) +{ +pgoff_t end_index = end >>PAGE_SHIFT ; +pgoff_t index = start >>PAGE_SHIFT ; +struct folio_batch fbatch; +int rc =0 ; + +folio_batch_init (&fbatch); +while (!rc && +filemap_get_folios_tag (mapping, &index, end_index, +PAGECACHE_TAG_WRITEBACK , &fbatch)) { +for (unsigned int i =0 ; + !rc && i <folio_batch_count (&fbatch); i++) + rc =folio_wait_writeback_killable (fbatch.folios[i]); +folio_batch_release (&fbatch); +cond_resched (); + } +return rc; +} + +static int cifs_file_write_and_wait_killable (struct file *file, +loff_t start,loff_t end) +{ +struct address_space *mapping = file->f_mapping; +int rc, rc2; + +if (end < start) +return 0 ; + + rc =filemap_fdatawrite_range (mapping, start, end); +if (cifs_wait_writeback_killable (mapping, start, end)) +return -EINTR ; + rc2 =file_check_and_advance_wb_err (file); +if (!rc) + rc = rc2; +return rc; +} +/* * Flush data on a strict file. */
@@ -2669,7 +2708,7 @@ int cifs_strict_fsync(struct file *file,struct inode *inode =file_inode (file);struct cifs_sb_info *cifs_sb =CIFS_SB (inode->i_sb); - rc =file_write_and_wait_range (file, start, end); + rc =cifs_file_write_and_wait_killable (file, start, end);if (rc) {trace_cifs_fsync_err (inode->i_ino, rc);return rc;
@@ -2725,7 +2764,7 @@ int cifs_fsync(struct file *file, loff_tstruct inode *inode =file_inode (file);struct cifs_sb_info *cifs_sb =CIFS_FILE_SB (file); - rc =file_write_and_wait_range (file, start, end); + rc =cifs_file_write_and_wait_killable (file, start, end);if (rc) {trace_cifs_fsync_err (file_inode (file)->i_ino, rc);return rc;
@@ -2760,25 +2799,6 @@ fsync_exit:return rc; } -static int cifs_wait_writeback_killable (struct address_space *mapping) -{ -struct folio_batch fbatch; -pgoff_t index =0 ; -int rc =0 ; - -folio_batch_init (&fbatch); -while (!rc && -filemap_get_folios_tag (mapping, &index, (pgoff_t)-1 , -PAGECACHE_TAG_WRITEBACK , &fbatch)) { -for (unsigned int i =0 ; - !rc && i <folio_batch_count (&fbatch); i++) - rc =folio_wait_writeback_killable (fbatch.folios[i]); -folio_batch_release (&fbatch); -cond_resched (); - } -return rc; -} -/* * As file closes, flush all cached write data for this inode checking * for write behind errors.
@@ -2792,7 +2812,7 @@ int cifs_flush(struct file *file, fl_ownif (file->f_mode &FMODE_WRITE ) { rc =filemap_fdatawrite (mapping);if (fatal_signal_pending (current) || -cifs_wait_writeback_killable (mapping)) +cifs_wait_writeback_killable (mapping,0 ,LLONG_MAX ))return 0 ; rc2 =filemap_check_errors (mapping);if (!rc)
Greg Kroah-Hartman
maintainerPATCH 685/816 smb: client: fix OOB write when compounding SMB2_IOCTL with encryption
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
commit 73a0060cb22a1d2bd8bff364c18a4259ec0cb528 upstream.
On an encrypted ("seal") mount, SMB2_ioctl_init() keeps the IOCTL input in a separate iov (iov[1]); iov[0] is a 448-byte buffer from cifs_small_buf_get(). When such an IOCTL is not the last request of a compound, smb2_set_next_command() pads it for alignment by copying the whole request into iov[0]. A large enough input overflows that 448-byte buffer and corrupts the slab; the copy also sets rq_nvec to 1, so the input buffer is leaked too.
An unprivileged user can trigger it by creating a symlink with a long target on such a mount: the native symlink is sent as FSCTL_SET_REPARSE_POINT + QUERY_INFO + CLOSE in one compound, so the IOCTL is not the last request.
With slub_debug red zones on the cifs_small_rq cache, the overflow is caught on the next allocation from that cache in the same compound (the 0x61 bytes are the 'a' characters of the symlink target):
BUG cifs_small_rq (Not tainted): Object corrupt
[Left Redzone overwritten] 0xffff8a59c7790500-0xffff8a59c779053f First byte 0x61 instead of 0xbb
Call Trace: check_object+0x1a8/0x350 alloc_debug_processing+0xab/0x110 ___slab_alloc+0x7e/0x2f0 kmem_cache_alloc_noprof+0x28d/0x4b0 mempool_alloc_slab+0x16/0x30 cifs_small_buf_get+0x1a/0x30 [cifs] SMB2_close_init+0x8a/0x100 [cifs] smb2_compound_op+0x2571/0x2b50 [cifs] smb2_create_reparse_inode+0x27e/0x490 [cifs] mknod_nfs+0x1ce/0x2e0 [cifs] create_reparse_symlink+0x119/0x180 [cifs] cifs_symlink+0x19f/0x8e0 [cifs] vfs_symlink+0xa3/0x1b0 __x64_sys_symlink+0x41/0x70
Pad the input to a multiple of 8 bytes when encryption is required. The request is then already aligned and smb2_set_next_command() no longer copies it; InputCount still carries the real length.
--- fs/smb/client/smb2pdu.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
fs/smb/client/smb2pdu.c +8 -4
@@ -3357,11 +3357,12 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, char *in_data, u32 indatalen, __u32 max_response_size) { - struct smb2_ioctl_req *req; struct kvec *iov = rqst->rq_iov; +struct smb2_ioctl_req *req; +u32 in_buf_len = indatalen;unsigned int total_len; -int rc;char *in_data_buf; +int rc; rc =smb2_ioctl_req_init (opcode, tcon, server, (void **) &req, &total_len);
@@ -3369,15 +3370,18 @@ SMB2_ioctl_init(struct cifs_tcon *tcon,return rc;if (indatalen) { +if (smb3_encryption_required (tcon)) + in_buf_len =ALIGN (indatalen,8 );/* * indatalen is usually small at a couple of bytes max, so * just allocate through generic pool */ - in_data_buf =kmemdup (in_data, indatalen,GFP_NOFS ); + in_data_buf =kzalloc (in_buf_len,GFP_NOFS );if (!in_data_buf) {cifs_small_buf_release (req);return -ENOMEM ; } +memcpy (in_data_buf, in_data, indatalen); } req->CtlCode =cpu_to_le32 (opcode);
@@ -3401,7 +3405,7 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, rqst->rq_nvec =2 ; iov[0 ].iov_len = total_len -1 ; iov[1 ].iov_base = in_data_buf; - iov[1 ].iov_len = indatalen; + iov[1 ].iov_len = in_buf_len; }else { rqst->rq_nvec =1 ; iov[0 ].iov_len = total_len;
Greg Kroah-Hartman
maintainerPATCH 686/816 smb: client: fix out-of-bounds read in dfs_parse_target_referral()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fredric Cover <[email protected]>
commit 86aacc2f3f6ba18e1d87feee24f37c94b3ce863a upstream.
dfs_parse_target_referral() decides whether a prefix path remains after the consumed part of full_path with:
if (strlen(full_path) - ref->path_consumed)
strlen() returns size_t, so if path_consumed is larger than the length of full_path, the subtraction wraps around to a huge non-zero value. The branch is then taken, prepath is set to a pointer past the terminating NUL of full_path, and *prepath reads out of bounds.
path_consumed can exceed strlen(full_path) when the mount charset is not utf8. The referral code derives path_consumed from the canonical path, which is in the DFS cache charset (utf8), but it is applied here to full_path, which is in the mount charset. Each non-ASCII character in the consumed part of the path that is longer in utf8 than in the mount charset makes the count too large by the difference.
This was reproduced with iocharset=iso8859-1 against a Samba DFS root containing a link named "café", mounting with the single Latin-1 byte 0xe9 in the path. On an unmodified tree such a mount fails earlier with -ENOENT because the path is converted to utf8 twice in setup_dfs_ref(); with that fixed ("smb: client: fix double conversion of DFS path in setup_dfs_ref()"), the mount reaches this code. full_path was 29 bytes while path_consumed was 30:
BUG: KASAN: slab-out-of-bounds in dfs_parse_target_referral+0x26a/0x270 Read of size 1 at addr ffff88810db89d5f by task mount/1743 ... The buggy address is located 0 bytes to the right of allocated 31-byte region [ffff88810db89d40, ffff88810db89d5f)
Compare path_consumed against the string length instead of subtracting, so that no prefix path is used when the consumed count covers the whole string. With the bounds check in place the same mount succeeds and no KASAN report is produced.
This only prevents the out-of-bounds access. path_consumed is still in the wrong units, so a non-ASCII link followed by a path component can still produce a wrong prefix path. That needs a separate fix.
--- fs/smb/client/dfs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/client/dfs.c +1 -1
@@ -31,7 +31,7 @@ int dfs_parse_target_referral(const charif (WARN_ON_ONCE (!ref->node_name || ref->path_consumed <0 ))return -EINVAL ; -if (strlen (full_path) - ref->path_consumed) { +if ((size_t )ref->path_consumed <strlen (full_path)) { prepath = full_path + ref->path_consumed;/* skip initial delimiter */ if (*prepath =='/' || *prepath =='\\' )
Greg Kroah-Hartman
maintainerPATCH 687/816 smb: client: flush deferred handles of other names before a hard link open
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 25912ed3b75dcf5ff623dcb549b925dd0d0948f7 upstream.
Opening a hard link of a file whose other name still holds a deferred, leased handle fails with EINVAL over SMB3. The client caches lease keys per inode, but the server ties a lease to the file name it was granted under, so reusing the inode's lease key to open a different name of the same inode is rejected with STATUS_INVALID_PARAMETER (MS-SMB2 3.3.5.9.11).
Commit 262b73ef442e ("smb3 client: fix open hardlink on deferred close file error") already closes the inode's deferred handles before such an open so the new name can take a fresh lease, but cifs_get_hardlink_path() only triggered that flush when a cached handle had the same open flags as the new open, so a differently accessed name - written then read, say - slipped through and still failed.
Match on the name instead: flush when a cached handle for another name of the inode is open, regardless of access mode.
--- fs/smb/client/file.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/client/file.c +1 -1
@@ -2095,7 +2095,7 @@ cifs_get_hardlink_path(struct cifs_tconspin_lock (&cinode->open_file_lock);list_for_each_entry (open_file, &cinode->openFileList, flist) { -if (file->f_flags == open_file->f_flags) { +if (open_file->dentry !=file_dentry (file)) { rc = -EINVAL ;break ; }
Greg Kroah-Hartman
maintainerPATCH 688/816 smb: client: hold the inode across cifs_oplock_break()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit fce78321f1b59531cf6fc94860550db1db8dec55 upstream.
cifs_oplock_break() drops the handle reference in the middle of the handler and keeps using cinode afterwards, to send the break acknowledgment and again in cifs_done_oplock_break(). The reference cifs_queue_oplock_break() takes is the only pin: the handle holds the dentry and the dentry is what keeps the inode alive.
When that put is the last reference, the dput() in cifsFileInfo_put_final() kills an unhashed dentry, drops the last i_count and evicts the inode, so the rest of the handler runs on an object whose free is only RCU-deferred. An unhashed dentry that a handle still references is an ordinary state: unlinking an open file leaves the dentry that way, and so does the dcache teardown at unmount.
Take a reference on the inode for the lifetime of the handler and drop it once the break has been reported. This also covers the cifs_get_tlink() failure path, where the put is followed directly by the out label.
--- fs/smb/client/file.c | 9 +++++++++ 1 file changed, 9 insertions(+)
fs/smb/client/file.c +9 -0
@@ -3188,6 +3188,14 @@ void cifs_oplock_break(struct work_struc__u64 persistent_fid, volatile_fid;__u16 net_fid; +/* +* Dropping the handle reference below also drops the dentry +* reference that pins this inode, and cinode is still needed to +* acknowledge the break and to report it as complete. Hold the inode +* until that is done. +*/ +ihold (inode); +wait_on_bit (&cinode->flags,CIFS_INODE_PENDING_WRITERS ,TASK_UNINTERRUPTIBLE );
@@ -3263,6 +3271,7 @@ oplock_break_ack:cifs_put_tlink (tlink); out:cifs_done_oplock_break (cinode); +iput (inode); } static int cifs_swap_activate(struct swap_info_struct *sis,
Greg Kroah-Hartman
maintainerPATCH 689/816 smb: client: issue writes from a worker if the task is dying
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 1a747bacf250959703c68fed1bb643f888dd3ad2 upstream.
A task with a fatal signal pending can't send on the socket:__smb_send_rqst() refuses it upfront with -ERESTARTSYS, as SIGKILL can't be blocked and a send interrupted halfway forces a reconnect. Writeback, however, runs in the context of whoever starts it, so when a dying task flushes dirty pages - close() racing with SIGKILL, or fd teardown during exit_group() - every write subrequest gets refused:
smb3_write_err: ... offset=0x1400000 len=0x400000 rc=-512
cifs_flush_err: ino=... rc=-512
Since the switch to netfslib, a failed upload ends writeback with the folios clean, so the data is silently lost: the server ends up with 20MiB of a 64MiB file while stat(2) reports the full size.
Issue writeback subrequests of dying tasks from a new cifswritebackd workqueue instead, like afs does for all of its writes, so they get sent from a context with no signals. Leave direct and unbuffered writes alone, as their callers get the error. Use a dedicated WQ_UNBOUND workqueue as the writes may block for long on credits, sends or reopens, e.g. on hard mounts with an unresponsive server, and must not hold up other cifs work such as reconnects, nor starve the WQ_MEM_RECLAIM rescuer of cifsiod_wq.
--- fs/smb/client/cifsfs.c | 13 ++++++++++++- fs/smb/client/cifsglob.h | 1 + fs/smb/client/file.c | 26 +++++++++++++++++++++++++- 3 files changed, 38 insertions(+), 2 deletions(-)
fs/smb/client/cifsfs.c +12 -1
@@ -158,6 +158,7 @@ struct workqueue_struct *cifsoplockd_wq;struct workqueue_struct *deferredclose_wq;struct workqueue_struct *serverclose_wq;struct workqueue_struct *cfid_put_wq; +struct workqueue_struct *cifs_writeback_wq;__u32 cifs_lock_secret;/*
@@ -2016,9 +2017,16 @@ init_cifs(void) goto out_destroy_serverclose_wq; } + cifs_writeback_wq =alloc_workqueue ("cifswritebackd" , +WQ_UNBOUND |WQ_MEM_RECLAIM ,0 ); +if (!cifs_writeback_wq) { + rc = -ENOMEM ; + goto out_destroy_cfid_put_wq; + } + rc =cifs_init_inodecache ();if (rc) - goto out_destroy_cfid_put_wq; + goto out_destroy_writeback_wq; rc =cifs_init_netfs ();if (rc)
@@ -2089,6 +2097,8 @@ out_destroy_netfs:cifs_destroy_netfs (); out_destroy_inodecache:cifs_destroy_inodecache (); +out_destroy_writeback_wq: +destroy_workqueue (cifs_writeback_wq); out_destroy_cfid_put_wq:destroy_workqueue (cfid_put_wq); out_destroy_serverclose_wq:
@@ -2134,6 +2144,7 @@ exit_cifs(void)destroy_workqueue (fileinfo_put_wq);destroy_workqueue (serverclose_wq);destroy_workqueue (cfid_put_wq); +destroy_workqueue (cifs_writeback_wq);destroy_workqueue (cifsiod_wq); }
fs/smb/client/cifsglob.h +1 -0
@@ -2051,6 +2051,7 @@ extern struct workqueue_struct *cifsoploextern struct workqueue_struct *deferredclose_wq;extern struct workqueue_struct *serverclose_wq;extern struct workqueue_struct *cfid_put_wq; +extern struct workqueue_struct *cifs_writeback_wq;extern __u32 cifs_lock_secret;extern mempool_t *cifs_sm_req_poolp;
fs/smb/client/file.c +25 -1
@@ -97,10 +97,16 @@ retry:#endif } +static bool cifs_writeback_dying (struct netfs_io_subrequest *subreq) +{ +return subreq->rreq->origin ==NETFS_WRITEBACK && +fatal_signal_pending (current); +} +/* * Issue a subrequest to upload to the server. */ -static void cifs_issue_write (struct netfs_io_subrequest *subreq) +static void __cifs_issue_write (struct netfs_io_subrequest *subreq) {struct cifs_io_subrequest *wdata = container_of(subreq, struct cifs_io_subrequest, subreq);
@@ -134,6 +140,24 @@ fail: goto out; } +static void cifs_issue_write_worker (struct work_struct *work) +{ +struct netfs_io_subrequest *subreq; + + subreq = container_of(work, struct netfs_io_subrequest, work); +__cifs_issue_write (subreq); +} + +static void cifs_issue_write (struct netfs_io_subrequest *subreq) +{ +if (unlikely (cifs_writeback_dying (subreq))) { + subreq->work.func = cifs_issue_write_worker; +WARN_ON_ONCE (!queue_work (cifs_writeback_wq, &subreq->work)); +return ; + } +__cifs_issue_write (subreq); +} +static void cifs_netfs_invalidate_cache (struct netfs_io_request *wreq) {cifs_invalidate_cache (wreq->inode,0 );
Greg Kroah-Hartman
maintainerPATCH 690/816 smb: client: skip NULL channel in __cifs_put_smb_ses()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit 8deaf64a59a263161dfc5128f8398fb3dcba4fac upstream.
cifs_chan_skip_or_disable() clears a secondary channel's slot in the session (ses->chans[chan_index].server = NULL) without lowering chan_count when the server stops supporting multichannel. When the session is later released, __cifs_put_smb_ses() walks every slot up to chan_count and calls cifs_put_tcp_session() on it, which dereferences the server pointer immediately, so a slot left NULL by the skip path makes the release crash with a NULL pointer dereference.
Clearing a slot without lowering chan_count is older than cifs_chan_skip_or_disable(): cifs_chan_update_iface() could already do the same since commit b54034a73baf9 ("cifs: during reconnect, update interface if necessary"), and the release loop has been unguarded since then. Commit 12d1e301bdfd1 ("cifs: do not let cifs_chan_update_iface deallocate channels") later removed that trigger, but the crash is reachable through it on older kernels.
cifs_decrease_secondary_channels() already guards the same put with if (server). Add the same guard to the release loop so a skipped channel slot is left alone.
--- fs/smb/client/connect.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
fs/smb/client/connect.c +2 -1
@@ -2140,7 +2140,8 @@ void __cifs_put_smb_ses(struct cifs_seskref_put (&ses->chans[i].iface->refcount, release_iface); ses->chans[i].iface =NULL ; } -cifs_put_tcp_session (ses->chans[i].server,0 ); +if (ses->chans[i].server) +cifs_put_tcp_session (ses->chans[i].server,0 ); ses->chans[i].server =NULL ; }
Greg Kroah-Hartman
maintainerPATCH 691/816 dm log userspace: drop the device reference on error
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: [email protected] <[email protected]>
commit 0550d3b14e008b033b02cfce668008ec6addffe4 upstream.
userspace_ctr() takes a reference on the log device with dm_get_device(). When the integrated-flush workqueue allocation fails it jumps to the shared error path, which frees the log context without dropping that reference, so the device stays busy and cannot be removed.
userspace_dtr() drops the reference correctly; do the same here.
--- drivers/md/dm-log-userspace-base.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm-log-userspace-base.c +5 -1
@@ -294,9 +294,11 @@ static int userspace_ctr(struct dm_dirty } r =dm_get_device (ti, devices_rdata,dm_table_get_mode (ti->table), &lc->log_dev); -if (r) +if (r) {DMERR ("Failed to register %s with device-mapper" , devices_rdata); + goto out; + } }if (lc->integrated_flush) {
@@ -314,6 +316,8 @@ static int userspace_ctr(struct dm_dirty out:kfree (devices_rdata);if (r) { +if (lc->log_dev) +dm_put_device (lc->ti, lc->log_dev);mempool_exit (&lc->flush_entry_pool);kfree (lc);kfree (ctr_str);
Greg Kroah-Hartman
maintainerPATCH 692/816 dm: avoid double-dropping the zone reset submission reference
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yaohan Li <[email protected]>
commit c4965effbe15f837a8089e79c0fc17ab19363cce upstream.
On an error in __send_zone_reset_all(), the submission reference held by the dm_io can be decremented there and again by the caller's error path. If another clone is still outstanding, the second drop can release the dm_io before that clone completes.
Only drop the submission reference in __send_zone_reset_all() on success. On failure, leave the reference for the caller's existing error handling to release once.
The error path was reproduced under KASAN with an injected GFP_NOIO allocation failure while another zone-reset clone remained in flight. With the change, the same failure was reported normally, without the observed use-after-free, and ordinary zone resets continued to work.
--- drivers/md/dm.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/md/dm.c +7 -2
@@ -1945,8 +1945,13 @@ static blk_status_t __send_zone_reset_albreak ; } -/* Release the reference that alloc_io() took for submission. */ -atomic_sub (1 , &ci->io->io_count); +/* +* Release the reference that alloc_io() took for submission. On error, +* that reference was not consumed: dm_split_and_process_bio() releases +* it on the error path, so do not release it here a second time. +*/ +if (sts ==BLK_STS_OK ) +atomic_dec (&ci->io->io_count);return sts; }
Greg Kroah-Hartman
maintainerPATCH 693/816 dm: Reject table setup after queue or disk teardown
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kirtikumar Anandrao Ramchandani <[email protected]>
commit ae310e4ad872a42f4707a596e66417f2aaa52826 upstream.
A failed table load can leave a mapped device in a state where its queue has already been initialized or its disk has been removed, while md->type is still DM_TYPE_NONE. A later table load then calls blk_mq_init_allocated_queue() on the same queue. If del_gendisk() exited the old hardware contexts, blk_mq_exit_hctx() dereferences their cleared flush queue pointer.
Reject setup attempts after queue initialization or disk removal. A failed request queue initialization still leaves md->tag_set NULL and can be retried. Set the request-based disk operations only after that initialization succeeds, so an unsuccessful attempt cannot leave a bio-based retry with request-based operations.
--- drivers/md/dm.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm.c +5 -1
@@ -2595,13 +2595,17 @@ int dm_setup_md_queue(struct mapped_deviWARN_ON_ONCE (type ==DM_TYPE_NONE ); +/* A failed setup may have left the queue initialized or the disk dead. */ +if (md->tag_set ||test_bit (GD_DEAD , &md->disk->state)) +return -ENODEV ; +if (type ==DM_TYPE_REQUEST_BASED ) { - md->disk->fops = &dm_rq_blk_dops; r =dm_mq_init_request_queue (md, t);if (r) {DMERR ("Cannot initialize queue for request-based dm mapped device" );return r; } + md->disk->fops = &dm_rq_blk_dops; } r =dm_calculate_queue_limits (t, &limits);
Greg Kroah-Hartman
maintainerPATCH 694/816 dm cache: reject kcopyd client destory if it setup failed
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Edward Adam Davis <[email protected]>
commit 8b97b168eb4d3affcf23d2980a0c3f35ed9262e2 upstream.
The value of cache->copier is -EINTR when failed to create a rescuer kthread for wq kcopyd, in cache_create(), the code jumps directly to __destroy(cache), it merely performs a simple check to see whether copier is NULL, potentially hitting:
BUG: KASAN: null-ptr-deref in dm_kcopyd_client_destroy+0xae/0x480 drivers/md/dm-kcopyd.c:980 Read of size 4 at addr 0000000000000174 by task syz.2.19/6560 Call Trace: dm_kcopyd_client_destroy+0xae/0x480 drivers/md/dm-kcopyd.c:980 __destroy+0x172/0x2f0 drivers/md/dm-cache-target.c:1973 cache_create drivers/md/dm-cache-target.c:2604 [inline] cache_ctr+0x1674/0x2bf0 drivers/md/dm-cache-target.c:2649 dm_table_add_target+0x58d/0xc70 drivers/md/dm-table.c:749 populate_table drivers/md/dm-ioctl.c:1602 [inline] table_load+0x325/0x8a0 drivers/md/dm-ioctl.c:1645 ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]
Set copier to NULL to avoid destroying a invalid kcopy client.
--- drivers/md/dm-cache-target.c | 1 + 1 file changed, 1 insertion(+)
drivers/md/dm-cache-target.c +1 -0
@@ -2550,6 +2550,7 @@ static int cache_create(struct cache_argif (IS_ERR (cache->copier)) { *error ="could not create kcopyd client" ; r =PTR_ERR (cache->copier); + cache->copier =NULL ; goto bad; }
Greg Kroah-Hartman
maintainerPATCH 695/816 dm crypt: fix use of uninitialized percpu_counter in ctr error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Feng <[email protected]>
commit 8ba1ade3e6b595b9091040feaa3341d7e45ba95d upstream.
If percpu_counter_init() fails in crypt_ctr() (e.g. when the underlying percpu allocation fails under memory pressure or fault injection), the error path jumps to "bad", which calls crypt_dtr(). crypt_dtr() then evaluates WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0) and calls percpu_counter_destroy() on a counter that was never initialized, because __percpu_counter_init_many() returns -ENOMEM before calling raw_spin_lock_init() on fbc->lock.
With lockdep enabled this triggers "INFO: trying to register non-static key" in __percpu_counter_sum(), as reported by syzbot. The console additionally shows "crypt: Unknown error (-ENOMEM)" because this failure path sets no ti->error.
Move percpu_counter_init() to right after the allocation of cc, before ti->private is set and before any "goto bad" can happen. On failure, set ti->error and free cc directly, so that crypt_dtr() is only ever called with an initialized counter.
--- drivers/md/dm-crypt.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/md/dm-crypt.c +8 -4
@@ -3308,6 +3308,14 @@ static int crypt_ctr(struct dm_target *t ti->error ="Cannot allocate encryption context" ;return -ENOMEM ; } + + ret =percpu_counter_init (&cc->n_allocated_pages,0 ,GFP_KERNEL ); +if (ret <0 ) { + ti->error ="Cannot initialize page counter" ; +kfree_sensitive (cc); +return ret; + } + cc->key_size = key_size; cc->sector_size = (1 <<SECTOR_SHIFT ); cc->sector_shift =0 ;
@@ -3319,10 +3327,6 @@ static int crypt_ctr(struct dm_target *tcrypt_calculate_pages_per_client ();spin_unlock (&dm_crypt_clients_lock); - ret =percpu_counter_init (&cc->n_allocated_pages,0 ,GFP_KERNEL ); -if (ret <0 ) - goto bad; -/* Optional parameters need to be read before cipher constructor */ if (argc >5 ) { ret =crypt_ctr_optional (ti, argc -5 , &argv[5 ]);
Greg Kroah-Hartman
maintainerPATCH 696/816 dm mpath: fix buffer overflow in parse_hw_handler()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: [email protected] <[email protected]>
commit 8f611fe94a781c6fb658488cc7eab4e4923e6df6 upstream.
parse_hw_handler() builds the hw_handler parameter string in a buffer sized with
len = 4;
plus one byte per argument. Those four bytes were meant for the decimal form of the parameter count, three digits plus the terminating NUL. dm_read_arg_group() accepts up to 1024 arguments and the count written is 'hw_argc - 1', so a count of 1000 or more needs four digits plus the NUL and sprintf() writes one byte past the allocation.
Size the buffer from the actual string length instead.
--- drivers/md/dm-mpath.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-mpath.c +2 -1
@@ -1082,8 +1082,9 @@ static int parse_hw_handler(struct dm_arif (hw_argc >1 ) {char *p; -int i, j, len =4 ; +int i, j, len; + len =snprintf (NULL ,0 ,"%d" , hw_argc -1 ) +1 ;for (i =0 ; i <= hw_argc -2 ; i++) len +=strlen (as->argv[i]) +1 ; p = m->hw_handler_params =kzalloc (len,GFP_KERNEL );
Greg Kroah-Hartman
maintainerPATCH 697/816 dm mpath: cap queue_if_no_path_timeout_secs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
commit ae5b40accbc06f93e6a513e0e9a07fd32b197e49 upstream.
enable_nopath_timeout() arms the no-path timer with
jiffies + queue_if_no_path_timeout_secs * HZ. The module parameter is an unbounded unsigned long, so the delay can exceed what mod_timer()
handles: a delay above LONG_MAX is treated as already expired, and values above ULONG_MAX / HZ also wrap in the multiplication. The timer then clears queue_if_no_path right away, and I/O queued after the last path fails gets -EIO instead of waiting for the configured time.
On x86-64 with HZ=1000, 9223372036854776 seconds failed a write after 124 ms while one second less remained queued throughout a 4.2-second observation window. A value of 18446744073709552 seconds wrapped to 384 jiffies and failed the write after 455 ms. On 32-bit kernels with HZ=1000 the delay passes LONG_MAX above 2147483 seconds, a little under 25 days.
Cap the seconds value at the largest whole-second delay not exceeding MAX_JIFFY_OFFSET before multiplying by HZ. This prevents signed-delta overflow and multiplication wrap. The timer wheel's existing handling of very long delays is unchanged.
--- drivers/md/dm-mpath.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-mpath.c +2 -1
@@ -801,7 +801,8 @@ static void queue_if_no_path_timeout_worstatic void enable_nopath_timeout (struct multipath *m) {unsigned long queue_if_no_path_timeout = -READ_ONCE (queue_if_no_path_timeout_secs) *HZ ; + min_t(unsigned long, READ_ONCE(queue_if_no_path_timeout_secs), +MAX_JIFFY_OFFSET /HZ ) *HZ ;lockdep_assert_held (&m->lock);
Greg Kroah-Hartman
maintainerPATCH 698/816 dm thin: avoid wrapping no_space_timeout
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
commit bcb78d49620f666b4a9d62997691e8d031fd4ebc upstream.
set_pool_mode() converts the no_space_timeout module parameter with READ_ONCE(no_space_timeout_secs) * HZ. The usual arithmetic conversions evaluate the product as unsigned int, so it can wrap before being stored in the unsigned long delay. With HZ=1000, 4294968 seconds becomes 704
jiffies: a pool that runs out of data space switches to error_if_no_space and fails queued writes with -ENOSPC after about 0.7 seconds.
Widen the value before the multiplication and cap it at MAX_JIFFY_OFFSET / HZ, so large timeouts no longer wrap into short delays. On 32-bit kernels, values beyond the supported jiffies range saturate at the largest whole-second delay not exceeding MAX_JIFFY_OFFSET. The timer wheel's existing handling of very long delays is unchanged.
--- drivers/md/dm-thin.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-thin.c +3 -1
@@ -2544,7 +2544,9 @@ static void set_pool_mode(struct pool *pstruct pool_c *pt = pool->ti->private;bool needs_check =dm_pool_metadata_needs_check (pool->pmd);enum pool_mode old_mode =get_pool_mode (pool); -unsigned long no_space_timeout =READ_ONCE (no_space_timeout_secs) *HZ ; +unsigned long no_space_timeout = + min_t(unsigned long, READ_ONCE(no_space_timeout_secs), +MAX_JIFFY_OFFSET /HZ ) *HZ ;/* * Never allow the pool to transition to PM_WRITE mode if user
Greg Kroah-Hartman
maintainerPATCH 699/816 dm-sysfs: fix misbehavior if kobject_init_and_add fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 406d576cc457203cf86eac7f17839b2efec81db4 upstream.
If kobject_init_and_add fails, we must call kobject_put (see the comment at kobject_init_and_add).
Before calling kobject_init_and_add, we must zero the kobject (see
https://lwn.net/Articles/52085/). If the first call to dm_sysfs_init failed, it may be called again, and that second call would see an uninitialized kobject.
--- drivers/md/dm-sysfs.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-)
drivers/md/dm-sysfs.c +14 -3
@@ -132,9 +132,20 @@ static const struct kobj_type dm_ktype =*/ int dm_sysfs_init (struct mapped_device *md) { -return kobject_init_and_add (dm_kobject (md), &dm_ktype, - &disk_to_dev (dm_disk (md))->kobj, -"%s" ,"dm" ); +struct kobject *kobj =dm_kobject (md); +int r; + +/* The kobject must be zeroed before calling kobject_init */ +memset (kobj,0 ,sizeof (struct kobject )); + r =kobject_init_and_add (kobj, &dm_ktype, + &disk_to_dev (dm_disk (md))->kobj, +"%s" ,"dm" ); +if (unlikely (r)) { +/* Weird semantics - we must call kobject_put on failure */ +dm_sysfs_exit (md); +return r; + } +return 0 ; }/*
Greg Kroah-Hartman
maintainerPATCH 700/816 dm-verity: dont restart or panic on errors during system shutdown
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weijiang Zhou <[email protected]>
commit 47930d1236d2988cdc580c10d3af21b6b02d7ece upstream.
Commit 252bd1256396 ("dm verity: skip verity work if I/O error when system is shutting down") stopped I/O errors during shutdown from triggering a restart, since devices may legitimately be gone by then. Errors that reach verity_handle_err(), e.g. through a failed hash block read followed by a failed FEC attempt, are not covered and still call kernel_restart() or panic().
During a reboot that is both wrong (nothing is corrupt) and harmful: it races with the reboot already in progress and replaces its reason with "dm-verity device corrupted", which bootloaders such as Android's treat as a verity failure and switch the device to EIO mode.
Apply the same shutdown check in verity_handle_err(). Corruption is still logged, recorded in hash_failed and reported via uevent, and the I/O still fails.
--- drivers/md/dm-verity-target.c | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-)
drivers/md/dm-verity-target.c +18 -9
@@ -229,6 +229,15 @@ static void verity_hash_at_level(struct }/* +* Skip verity work in response to I/O error when system is shutting down. +*/ +static inline bool verity_is_system_shutting_down (void ) +{ +return system_state ==SYSTEM_HALT || system_state ==SYSTEM_POWER_OFF + || system_state ==SYSTEM_RESTART ; +} + +/* * Handle verification errors. */ static int verity_handle_err(struct dm_verity *v, enum verity_block_type type,
@@ -277,6 +286,15 @@ out:if (v->mode ==DM_VERITY_MODE_LOGGING )return 0 ; +/* +* Devices may already be quiesced (e.g. UFS set offline by its +* shutdown hook), so a failure here does not imply corruption. Fail +* the I/O but do not restart or panic, which would also override the +* reboot reason of the shutdown already in progress. +*/ +if (verity_is_system_shutting_down ()) +return 1 ; +if (v->mode ==DM_VERITY_MODE_RESTART )kernel_restart ("dm-verity device corrupted" );
@@ -579,15 +597,6 @@ static int verity_verify_io(struct dm_vereturn 0 ; } -/* -* Skip verity work in response to I/O error when system is shutting down. -*/ -static inline bool verity_is_system_shutting_down (void ) -{ -return system_state ==SYSTEM_HALT || system_state ==SYSTEM_POWER_OFF - || system_state ==SYSTEM_RESTART ; -} -static void restart_io_error (struct work_struct *w) {kernel_restart ("dm-verity device has I/O error" );
Greg Kroah-Hartman
maintainerPATCH 701/816 dm persistent data: test return value of node_copy
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 624d146d97c5fbe7200ef4b2dd5350ecf57d6b79 upstream.
There were 3 places where the return value of node_copy was not tested.
--- drivers/md/persistent-data/dm-btree-remove.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/md/persistent-data/dm-btree-remove.c +10 -3
@@ -253,7 +253,9 @@ static int __rebalance2(struct dm_btree_/* * Merge */ -node_copy (left, right, -nr_right); + ret =node_copy (left, right, -nr_right); +if (unlikely (ret)) +return ret; left->header.nr_entries =cpu_to_le32 (nr_left + nr_right);delete_at (parent, r->index);
@@ -315,13 +317,16 @@ static int delete_center_node(struct dm_ {uint32_t max_entries =le32_to_cpu (left->header.max_entries);unsigned int shift =min (max_entries - nr_left, nr_center); +int ret;if (nr_left + shift > max_entries) {DMERR ("node shift out of bounds" );return -EINVAL ; } -node_copy (left, center, -shift); + ret =node_copy (left, center, -shift); +if (unlikely (ret)) +return ret; left->header.nr_entries =cpu_to_le32 (nr_left + shift);if (shift != nr_center) {
@@ -333,7 +338,9 @@ static int delete_center_node(struct dm_ }node_shift (right, shift); -node_copy (center, right, shift); + ret =node_copy (center, right, shift); +if (unlikely (ret)) +return ret; right->header.nr_entries =cpu_to_le32 (nr_right + shift); } *key_ptr (parent, r->index) = right->keys[0 ];
Greg Kroah-Hartman
maintainerPATCH 702/816 dm persistent data: dont ignore writeback errors
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit fa887f2ebee7aff97eb87b3365939616ade09774 upstream.
An error returned by ie_cache_writeback could be silently overwritten by another successful ie_cache_writeback. This commit fixes disk_ll_commit, so that it doesn't ignore the error and returns it immediatelly.
--- drivers/md/persistent-data/dm-space-map-common.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/md/persistent-data/dm-space-map-common.c +6 -3
@@ -1190,17 +1190,20 @@ static dm_block_t disk_ll_max_entries(ststatic int disk_ll_commit (struct ll_disk *ll) { -int r =0 ; +int r;unsigned int i;for (i =0 ; i <IE_CACHE_SIZE ; i++) {struct ie_cache *iec = ll->ie_cache + i; -if (iec->valid && iec->dirty) +if (iec->valid && iec->dirty) { r =ie_cache_writeback (ll, iec); +if (unlikely (r)) +return r; + } } -return r; +return 0 ; }int sm_ll_new_disk (struct ll_disk *ll,struct dm_transaction_manager *tm)
Greg Kroah-Hartman
maintainerPATCH 703/816 dm persistent data: dont leak bufio buffer if find_leaf fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit b27523a0781aae0b51ac13f29dc65373d14b8434 upstream.
If find_leaf fails, the function dm_btree_cursor_begin would return an error, but it would keep the dm-bufio buffers held. This would result in a memory leak and a warning when releasing the dm-bufio cache.
This commit fixes it, so that dm_btree_cursor_begin releases the buffers on error.
--- drivers/md/persistent-data/dm-btree.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/md/persistent-data/dm-btree.c +7 -1
@@ -1582,7 +1582,13 @@ int dm_btree_cursor_begin(struct dm_btreif (r)return r; -return find_leaf (c); + r =find_leaf (c); +if (unlikely (r)) { +dm_btree_cursor_end (c); +return r; + } + +return 0 ; }EXPORT_SYMBOL_GPL (dm_btree_cursor_begin);
Greg Kroah-Hartman
maintainerPATCH 704/816 dm snapshot: fix discard_granularity unit in snapshot_io_hints
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: wuyuehong <[email protected]>
commit d7216d7be2bbfdf3312695b6e41a4fc7c5e22902 upstream.
snapshot_io_hints() copies the snapshot store's chunk_size, which is in 512-byte sectors, into queue_limits.discard_granularity, which, like all other members of struct queue_limits, is in bytes.
For snapshots with a chunk size smaller than 512 sectors, e.g. the 16 KiB (32-sector) chunks created by the syzkaller reproducer, the resulting granularity is smaller than a single sector. When dm_calculate_queue_limits() then stacks the target limits into the table limits:
blk_stack_limits(limits, &ti_limits, 0)
queue_limit_discard_alignment() truncates that granularity to zero sectors and sector_div() divides by zero:
Oops: divide error: 0000 [#1] SMP KASAN NOPTI RIP: 0010:queue_limit_discard_alignment block/blk-settings.c:645 [inline] RIP: 0010:blk_stack_limits+0x1105/0x2d00 block/blk-settings.c:916 Call Trace: dm_calculate_queue_limits+0x70c/0x1510 drivers/md/dm-table.c:1823 dm_setup_md_queue+0x199/0x4f0 drivers/md/dm.c:2618 table_load+0x4fd/0x8a0 drivers/md/dm-ioctl.c:1661
The divide fault itself only became reachable when commit e924da7d6622 ("block: Drop granularity check in queue_limit_discard_alignment()") removed the check for a sub-sector granularity in v6.13. Kernels before that returned a zero discard alignment instead of faulting, but they still advertised a granularity 512 times too small.
Use the same chunk_size << SECTOR_SHIFT conversion that io_overlaps_chunk() already applies to turn chunk_size into bytes.
--- drivers/md/dm-snap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-snap.c +1 -1
@@ -2420,7 +2420,7 @@ static void snapshot_io_hints(struct dm_ snap = snap_src;/* All discards are split on chunk_size boundary */ - limits->discard_granularity = snap->store->chunk_size; + limits->discard_granularity = snap->store->chunk_size <<SECTOR_SHIFT ; limits->max_hw_discard_sectors = snap->store->chunk_size;up_read (&_origins_lock);
Greg Kroah-Hartman
maintainerPATCH 705/816 dm snapshot: split discards on chunk boundaries
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chen Cheng <[email protected]>
commit 4fe2c2baad01da64d47f1a0c8fc093df994bcef5 upstream.
dm-snapshot did not set ti->max_discard_granularity when it allows discards, so a discard could reach the target unaligned, or spanning several chunks. Set the flag, so dm splits discards on chunk boundaries.
--- drivers/md/dm-snap.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-snap.c +3 -1
@@ -1364,8 +1364,10 @@ static int snapshot_ctr(struct dm_target ti->private = s; ti->num_flush_bios = num_flush_bios; -if (s->discard_zeroes_cow) +if (s->discard_zeroes_cow) { ti->num_discard_bios = (s->discard_passdown_origin ?2 :1 ); + ti->max_discard_granularity = true; + } ti->per_io_data_size =sizeof (struct dm_snap_tracked_chunk );/* Add snapshot to the list of snapshots for this origin */
Greg Kroah-Hartman
maintainerPATCH 706/816 dm snapshot: fix discard writing into the next COW chunk
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chen Cheng <[email protected]>
commit 73174b4bb6fcd0e6cf973c9402a0fae2e567ad9f upstream.
zero_exception() zeroes one chunk of the COW device and takes the start sector from bio->bi_iter.bi_sector. remap_exception() has already set that to the COW chunk start plus the offset inside the chunk. That offset is needed for reads and writes, but for a discard it is wrong:
the zeroing window is shifted, so the head of the target chunk keeps its old data and the tail lands in the next COW chunk, which holds a different exception.
io_overlaps_chunk() should have caught this, but it only compares the length. "maps to entire chunks" in snapshot.rst also means the discard has to start on a chunk boundary.
A discard that is not a full chunk has a second problem: after remap_exception() it is sent to the COW device, where it hits a chunk that still backs a live exception. After a discard the contents are undefined, but the exception stays in the table and keeps pointing at that chunk, so a later read returns whatever the discard left instead of the snapshot's data.
Reproducer:
truncate -s 4M o.img c.img o=$(losetup -f --show o.img) c=$(losetup -f --show c.img) dmsetup create snap --table \ "0 8192 snapshot $o $c P 512 1 discard_zeroes_cow" # write two chunks, this creates two exceptions head -c 256K /dev/zero | tr '\000' '\252' > pat dd if=pat of=/dev/mapper/snap bs=256K seek=1 count=1 conv=notrunc dd if=pat of=/dev/mapper/snap bs=256K seek=2 count=1 conv=notrunc # shift the snapshot by 8 sectors, so a discard that is aligned on # top is unaligned inside the snapshot dmsetup create top --table "0 8184 linear /dev/mapper/snap 8" blkdiscard -o 262144 -l 262144 /dev/mapper/top sync echo 3 > /proc/sys/vm/drop_caches # chunk 1 dd if=/dev/mapper/snap bs=512 skip=512 count=8 | od -An -tx1 -N1 # chunk 2 dd if=/dev/mapper/snap bs=512 skip=1024 count=8 | od -An -tx1 -N1
Before: aa 00 <- chunk 2 was zeroed although it was not discarded After: aa aa <- nothing written, a discard is only a hint
Fix it by requiring the discard to start on a chunk boundary in io_overlaps_chunk(), and by finishing a discard that is not a full chunk with bio_endio() instead of passing it down to the COW device.
--- drivers/md/dm-snap.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/md/dm-snap.c +7 -5
@@ -1954,8 +1954,8 @@ static void zero_exception(struct dm_snastatic bool io_overlaps_chunk (struct dm_snapshot *s,struct bio *bio) { -return bio->bi_iter.bi_size == - (s->store->chunk_size <<SECTOR_SHIFT ); +return bio->bi_iter.bi_size == (s->store->chunk_size <<SECTOR_SHIFT ) && + !(bio->bi_iter.bi_sector & s->store->chunk_mask); }static int snapshot_map (struct dm_target *ti,struct bio *bio)
@@ -2015,11 +2015,13 @@ static int snapshot_map(struct dm_target e =dm_lookup_exception (&s->complete, chunk);if (e) {remap_exception (s, e, bio, chunk); -if (unlikely (bio_op (bio) ==REQ_OP_DISCARD ) && -io_overlaps_chunk (s, bio)) { +if (unlikely (bio_op (bio) ==REQ_OP_DISCARD )) {dm_exception_table_unlock (&lock);up_read (&s->lock); -zero_exception (s, e, bio, chunk); +if (io_overlaps_chunk (s, bio)) +zero_exception (s, e, bio, chunk); +else +bio_endio (bio); r =DM_MAPIO_SUBMITTED ;/* discard is not issued */ goto out; }
Greg Kroah-Hartman
maintainerPATCH 707/816 dm zoned: back off when reclaim cannot make progress
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyrylo Biryuk <[email protected]>
commit 9bb1d14877f4929be17f7fdbeb4cfdf5025d464b upstream.
When a reclaim pass cannot make progress, dmz_reclaim_work() still ends with dmz_schedule_reclaim(). If the target is idle, dmz_should_reclaim() keeps returning true, the work is queued again with no delay and the worker spins on the same failing pass. This patch handles two such cases:
- dmz_do_reclaim() fails with -ENOSPC because no free zone is available to copy the data into, for example on a target without cache zones that has no free sequential zone left. The next patch also makes this the expected result when an idle target with cache zones has random zones but no free sequential zone.
- dmz_do_reclaim() finds no zone it can lock for reclaim and returns -EBUSY. Since commit 90a9b8693f1b ("dm zoned: reclaim random zones when idle"), dmz_should_reclaim() returns true on an idle target whenever the total number of random (and cache) zones is non-zero, whether or not any of them holds data. Each pass then also runs dmz_check_dev(), which checks every device for media events (a TEST UNIT READY on SCSI disks).
The -EBUSY loop lasts as long as the target stays idle; it ends when a pass finishes while the target is busy and has enough free zones. On three 27 TB host-managed SATA drives used as md RAID5 members (7.2.10 with the module built out of tree, all random zones free, target idle for 300 seconds, kprobes attached, two other drives on the controller being zero-filled), each member's SCSI device counted about 108,000 requests per second with the stock module and the system used about 915 s of CPU time, against about 46 s with this series. libata completes TEST UNIT READY in software, so these counters do not measure commands sent to the drives; the cost is CPU time.
When a pass fails with -ENOSPC or -EBUSY, retrying at once is unlikely to make progress: re-arm the idle poll instead, so that reclaim is retried after DMZ_IDLE_PERIOD unless a zone allocation or a "reclaim" message queues it earlier. On a busy target, zone allocations can restart reclaim immediately when free space is low enough to require reclaim. Re-arming also keeps the poll running after a complete idle drain. The poll can still stop after a pass that ends while reclaim is not needed; that is unchanged.
Skip the device check for these two results: they normally mean that there is no zone to copy into or no zone to reclaim, not that a device failed, and the I/O paths check the devices themselves. Use queue_delayed_work() so that work an allocation has already queued is not postponed.
A pass that fails with an I/O error, for example on an unreadable block of a device that stays online, is still retried at once while the target is idle; this patch does not change that.
Tested on 7.4-rc1 with this patch and the next one, on three emulated host-managed drives (scsi_debug, 1 GiB, 32 MiB zones) each under dm-zoned as md RAID5 members, all random zones free and the target idle for 300 seconds. With the stock module each member's SCSI device counted about 70.2 million requests and the reclaim workers used 726 s of CPU. With this series: 75 requests per member, 30 passes per worker (one per DMZ_IDLE_PERIOD) and 0.08 s of CPU. Data written during the tests read back with matching checksums, and no kernel warnings were logged.
--- drivers/md/dm-zoned-reclaim.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
drivers/md/dm-zoned-reclaim.c +10 -0
@@ -539,6 +539,16 @@ static void dmz_reclaim_work(struct work dmz_nr_rnd_zones(zmd, zrc->dev_idx)); ret =dmz_do_reclaim (zrc); +if (ret == -ENOSPC || ret == -EBUSY ) { +/* +* No zone to copy into (-ENOSPC) or no zone to reclaim +* (-EBUSY): retrying at once cannot make progress and would +* spin. Poll again after the idle period instead, without +* postponing work that an allocation has already queued. +*/ +queue_delayed_work (zrc->wq, &zrc->work,DMZ_IDLE_PERIOD ); +return ; + }if (ret && ret != -EINTR ) {if (!dmz_check_dev (zmd))return ;
Greg Kroah-Hartman
maintainerPATCH 708/816 dm zoned: do not reclaim a random zone into another random zone
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyrylo Biryuk <[email protected]>
commit dab527d83462a618d99bfc96370ce45ae3428706 upstream.
dmz_reclaim_rnd_data() falls back to a random destination zone when no free sequential zone is available and the target has cache zones. When the target is idle and the cache zone list is empty, dmz_get_rnd_zone_for_reclaim() selects random zones of the zoned device as well, so a random zone is then copied into another random zone. That frees nothing: the next pass picks the next random zone and copies it again, for as long as the target stays idle.
Seen on a two-device target (256 GiB regular cache device plus a 27 TB host-managed drive) used as an md RAID5 member: after a full rebuild every chunk was mapped and no sequential zone was free, and the idle drive kept reading and writing while the free zone counters in "dmsetup status" did not change.
Only switch to a random destination zone when the zone being reclaimed is a cache zone: moving it to the zoned device still frees cache space.
This depends on "dm zoned: back off when reclaim cannot make progress":
without it, dmz_reclaim_work() would retry the resulting -ENOSPC at once, and run dmz_check_dev(), for as long as the target stays idle.
Tested on 7.4-rc1 together with the previous patch, on a two-device target (a 512 MiB RAM-backed regular cache device plus a 1 GiB scsi_debug host-managed drive) filled until no sequential zone was free, then idle for 60 seconds: the stock module made 877 random-to-random copies; with this series it made none, and each pass failed with -ENOSPC once per DMZ_IDLE_PERIOD without a device check.
--- drivers/md/dm-zoned-reclaim.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/md/dm-zoned-reclaim.c +7 -1
@@ -290,7 +290,13 @@ static int dmz_reclaim_rnd_data(struct d again: szone =dmz_alloc_zone (zmd, zrc->dev_idx, alloc_flags |DMZ_ALLOC_RECLAIM ); -if (!szone && alloc_flags ==DMZ_ALLOC_SEQ &&dmz_nr_cache_zones (zmd)) { +/* +* If no free sequential zone is available, a cache zone can still be +* moved into a free random zone of the zoned device, which frees cache +* space. Do not do this for a random zone: moving it into another +* random zone frees nothing and, on an idle target, repeats forever. +*/ +if (!szone && alloc_flags ==DMZ_ALLOC_SEQ &&dmz_is_cache (dzone)) { alloc_flags =DMZ_ALLOC_RND ; goto again; }
Greg Kroah-Hartman
maintainerPATCH 709/816 dm-cache: fix NULL pointer dereference on open failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit d12afc2f9ed6e14019fed9c02a74ad699915dc85 upstream.
When __begin_transaction_flags in metadata_open fails, dm_cache_metadata_close is called. dm_cache_metadata_close attempts to execute list_del(&cmd->list);, but the "cmd" object is not on any list yet, thus it crashes with NULL pointer dereference.
Fix this by initializing cmd->list after cmd is allocated.
--- drivers/md/dm-cache-metadata.c | 1 + 1 file changed, 1 insertion(+)
drivers/md/dm-cache-metadata.c +1 -0
@@ -766,6 +766,7 @@ static struct dm_cache_metadata *metadatreturn ERR_PTR (-ENOMEM ); } +INIT_LIST_HEAD (&cmd->list); cmd->version = metadata_version;refcount_set (&cmd->ref_count,1 );init_rwsem (&cmd->root_lock);
Greg Kroah-Hartman
maintainerPATCH 710/816 dm-cache: fix ending a cursor that never began
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 421420758be348cb90715bfaa26e1211a12ff1d0 upstream.
If dm_bitset_cursor_begin fails, dm_array_cursor_end(&cmd->hint_cursor) is called. However, cmd->hint_cursor was only initialized if the variable hints_valid is true. Thus, we must also destroy hint_cursor only if hints_valid is true.
--- drivers/md/dm-cache-metadata.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-cache-metadata.c +2 -1
@@ -1442,7 +1442,8 @@ static int __load_mappings(struct dm_cacfrom_cblock (cmd->cache_blocks), &cmd->dirty_cursor);if (r) { -dm_array_cursor_end (&cmd->hint_cursor); +if (hints_valid) +dm_array_cursor_end (&cmd->hint_cursor);dm_array_cursor_end (&cmd->mapping_cursor);return r; }
Greg Kroah-Hartman
maintainerPATCH 711/816 dm-crypt: reject integrity_key_size with non-authenc AEAD ciphers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: xietangxin <[email protected]>
commit bd93c4e59c5132282c01f142806e307c7380e7ea upstream.
When integrity_key_size parameter is paired with a pure AEAD cipher that is not an authenc composite, crypt_ctr_auth_cipher() returns 0 early without allocating cc->authenc_key, but cc->key_mac_size remains non-zero because CRYPT_KEY_MAC_SIZE_SET was set during option parsing. As a result crypt_copy_authenckey() dereferences NULL crashes the kernel.
Reject the contradictory configuration explicitly instead of silently returning 0, so userspace gets a clear -EINVAL.
--- drivers/md/dm-crypt.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/md/dm-crypt.c +4 -1
@@ -2926,8 +2926,11 @@ static int crypt_ctr_auth_cipher(structchar *start, *end, *mac_alg =NULL ;struct crypto_ahash *mac; -if (!strstarts (cipher_api,"authenc(" )) +if (!strstarts (cipher_api,"authenc(" )) { +if (test_bit (CRYPT_KEY_MAC_SIZE_SET , &cc->cipher_flags)) +return -EINVAL ;return 0 ; + } start =strchr (cipher_api,'(' ); end =strchr (cipher_api,',' );
Greg Kroah-Hartman
maintainerPATCH 712/816 dm-crypt: defer async write submission to write thread
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Schlehofer <[email protected]>
commit 6fed9e26810f0b466dbcebe35a73d1fd48793ff5 upstream.
With no_write_workqueue, kcryptd_crypt_write_io_submit() submits the bio directly, even when called from kcryptd_async_done(). An async cipher may run this callback in softirq or with BH disabled, where submit_bio_noacct() must not be called because it can sleep.
Submit inline only when async is false. Async completions are sent to the write thread, as is already done for submit_from_crypt_cpus. Use the async flag rather than in_interrupt(), since callback context depends on the cipher driver. Sync ciphers still submit inline.
Tested with cryptd in QEMU (x86_64 and arm64) with CONFIG_DEBUG_ATOMIC_SLEEP, and on a P2020 running 6.18.55 without it.
In QEMU:
- 4k writes logging "sleeping function called from invalid context":
100/100 unpatched, 0/155 patched.
- nr_requests=4 on a loop device: 0/6 unpatched runs completed, 4/4 patched runs completed.
On the P2020, a warning in blk_mq_run_hw_queue() appeared in the 6th unpatched run and did not appear in 30 patched runs.
--- drivers/md/dm-crypt.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/md/dm-crypt.c +3 -2
@@ -2059,8 +2059,9 @@ static void kcryptd_crypt_write_io_submi clone->bi_iter.bi_sector = cc->start + io->sector; -if ((likely (!async) &&test_bit (DM_CRYPT_NO_OFFLOAD , &cc->flags)) || -test_bit (DM_CRYPT_NO_WRITE_WORKQUEUE , &cc->flags)) { +if (likely (!async) && + (test_bit (DM_CRYPT_NO_OFFLOAD , &cc->flags) || +test_bit (DM_CRYPT_NO_WRITE_WORKQUEUE , &cc->flags))) {dm_submit_bio_remap (io->base_bio, clone);return ; }
Greg Kroah-Hartman
maintainerPATCH 713/816 dm-integrity: dont recalculate with HMAC because of a dirty bitmap
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sinan Polat <[email protected]>
commit 875a7161fe1574205293c36f7bbd0815023e48a1 upstream.
Commit 5c02406428d5 ("dm integrity: conditionally disable "recalculate" feature") refuses a superblock with SB_FLAG_RECALCULATING if a keyed hash is used without "legacy_recalculate". Otherwise someone who can write to the device, but does not know the key, could modify data and have the kernel compute valid tags for it.
dm_integrity_resume() can still start the same recalculation in J or D
mode: if SB_FLAG_DIRTY_BITMAP is set and the bitmap is not clear, or log2_blocks_per_bitmap_bit does not match, it sets SB_FLAG_RECALCULATING and recalc_sector = 0. The superblock is not authenticated unless fix_hmac and journal_mac are both used, so the flag can be set offline. Resume also runs on the first activation.
Apply the constructor's policy there. If recalculation is not allowed, log an error and keep the existing tags, so modified blocks fail verification. This also avoids queueing recalc_work on a NULL recalc_wq when internal_hash is not used.
--- drivers/md/dm-integrity.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-)
drivers/md/dm-integrity.c +22 -2
@@ -3736,6 +3736,24 @@ static bool superblock_changed(struct dmmemcmp (ic->sb->salt, ic->sb_copy->salt,SALT_SIZE ) !=0 ; } +/* +* The superblock is authenticated only if fix_hmac and journal_mac are used, +* so SB_FLAG_DIRTY_BITMAP may have been set by someone who doesn't know the +* key. Apply the policy that the constructor applies to SB_FLAG_RECALCULATING. +*/ +static bool dm_integrity_may_recalc_dirty_bitmap (struct dm_integrity_c *ic) +{ +if (!ic->internal_hash) { +DMERR ("Dirty bitmap found, but internal_hash is not used" ); +return false; + } +if (dm_integrity_disable_recalculate (ic)) { +DMERR ("Dirty bitmap found, but HMAC recalculation requires \"legacy_recalculate\"" ); +return false; + } +return true; +} +static void dm_integrity_resume (struct dm_target *ti) {struct dm_integrity_c *ic = ti->private;
@@ -3825,8 +3843,10 @@ static void dm_integrity_resume(struct dif (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&block_bitmap_op (ic, ic->journal,0 , ic->provided_data_sectors,BITMAP_OP_TEST_ALL_CLEAR )) || ic->reset_recalculate_flag) { - ic->sb->flags |=cpu_to_le32 (SB_FLAG_RECALCULATING ); - ic->sb->recalc_sector =cpu_to_le64 (0 ); +if (dm_integrity_may_recalc_dirty_bitmap (ic)) { + ic->sb->flags |=cpu_to_le32 (SB_FLAG_RECALCULATING ); + ic->sb->recalc_sector =cpu_to_le64 (0 ); + } }init_journal (ic,0 , ic->journal_sections,0 );replay_journal (ic);
Greg Kroah-Hartman
maintainerPATCH 714/816 dm-integrity: dont attempt to commit journal on disabled device
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit e5e03918fbec31f0c896f4f43c2bd2aadf35d43d upstream.
If the device is disabled due to an error, we shouldn't attempt to flush the journal. We jump straight to the label release_flush_bios, that will call do_endio on all queued bios. do_endio will terminate the bios with the error.
This fixes WARN_ON in the function pad_uncommitted reported by syzkaller.
--- drivers/md/dm-integrity.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm-integrity.c +5 -1
@@ -2773,6 +2773,11 @@ static void integrity_commit(struct workspin_lock_irq (&ic->endio_wait.lock); flushes =bio_list_get (&ic->flush_bio_list); +if (unlikely (dm_integrity_failed (ic))) { +wake_up_locked (&ic->endio_wait); +spin_unlock_irq (&ic->endio_wait.lock); + goto release_flush_bios; + }if (unlikely (ic->mode !='J' )) {spin_unlock_irq (&ic->endio_wait.lock);dm_integrity_flush_buffers (ic, true);
@@ -5239,7 +5244,6 @@ try_smaller_buffer: r =create_journal (ic, &ti->error);if (r) goto bad; - }if (ic->mode =='B' ) {
Greg Kroah-Hartman
maintainerPATCH 715/816 dm-raid: bound array_position before indexing failed_devices
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jay Vadayath <[email protected]>
commit 11b5cd14c0eecae458cecbe53d21a3dbc10190f5 upstream.
super_init_validation() reads role = le32_to_cpu(sb2->array_position) out of an on-disk dm_raid_superblock and then uses it as a bit index into the failed_devices bitmap via test_bit(role, (void *)failed_devices). failed_devices is a uint64_t[DISKS_ARRAY_ELEMS] (DISKS_ARRAY_ELEMS == 4, i.e. 256 bits) living on the stack. The only guard is role < 0, so any on-disk array_position >= 256 makes test_bit() read past the end of the stack array (array_position == 256 reads failed_devices[4], 8 bytes past the object). For a raid1 set the role != raid_disk reorder branch falls through to the same test_bit().
A crafted dm-raid superblock therefore causes a stack out-of-bounds read during table load. Reachable by anyone able to issue a dmsetup create with attacker-controlled metadata (CAP_SYS_ADMIN in the target namespace); the crash fires in the constructor / analyse_superblocks path, before any md_run or array sizing.
BUG: KASAN: stack-out-of-bounds in super_validate+0x1cd0/0x3390 Read of size 8 at addr ffff888007b17828 by task poc/152 Call Trace: dump_stack_lvl+0x64/0x80 print_report+0xd0/0x630 kasan_report+0xe5/0x120 kasan_check_range+0x105/0x1b0 super_validate+0x1cd0/0x3390 (super_init_validation, inlined) raid_ctr+0x2c4b/0xa0f0 dm_table_add_target+0x66f/0xf80 table_load+0x2ee/0x780 ctl_ioctl+0x362/0x9f0 dm_ctl_ioctl+0x9/0x10 __x64_sys_ioctl+0x134/0x1c0 do_syscall_64+0xe2/0x4b0 entry_SYSCALL_64_after_hwframe+0x77/0x7f
role is a device position that must refer to an actual member of the array, so reject anything outside [0, rs->raid_disks) instead of only the negative case. rs->raid_disks is always <= the 256-bit capacity of failed_devices, so this both closes the out-of-bounds access and matches the intended semantics.
This bug was discovered by Artiphishell's vTriage pipeline, which generated a crafted raid1 superblock (magic "DmRd", compat_features=1, num_devices=2, array_position=256, level=1) and a dmsetup-create reproducer that reliably triggers the KASAN report on an unpatched kernel (the precursor DMINFO "raid device #256 now at position #0" is visible in the serial log just before the splat). The fix below was drafted with the Claude coding assistant; a userspace reproducer is available on request.
--- drivers/md/dm-raid.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-raid.c +2 -1
@@ -2424,7 +2424,8 @@ static int super_init_validation(struct*/ if (!test_bit (FirstUse, &r->flags) && (r->raid_disk >=0 )) { role =le32_to_cpu (sb2->array_position); -if (role <0 ) +/* Bound @role before it indexes the failed_devices stack bitmap. */ +if (role <0 || role >= rs->raid_disks)continue ;if (role != r->raid_disk) {
Greg Kroah-Hartman
maintainerPATCH 716/816 dm-raid: fix use-after-free in raid_dtr()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Youhong <[email protected]>
commit 46af2c975958119290ddcd984a98491966123a7b upstream.
raid_dtr() currently flushes event_work only if work_pending() is true. This is insufficient because once a worker has dequeued the work, the PENDING bit is cleared while do_table_event() is still running. In that window raid_set_free() can free the raid_set, leading to a use-after-free when do_table_event() accesses rs->ti->table.
Flush event_work whenever it has been initialized, so raid_set is not freed while the event handler is still running. The .func guard skips the flush for mddev instances where INIT_WORK has not run yet.
--- drivers/md/dm-raid.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-raid.c +1 -1
@@ -3332,7 +3332,7 @@ static void raid_dtr(struct dm_target *tmd_stop (&rs->md);mddev_unlock (&rs->md); -if (work_pending (&rs->md.event_work)) +if (rs->md.event_work.func)flush_work (&rs->md.event_work);raid_set_free (rs); }
Greg Kroah-Hartman
maintainerPATCH 717/816 dm-thin: fix data corruption if discard races with regular I/O
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 62ee9c09366cad69410330087d990e469dd92314 upstream.
In the function break_up_discard_bio, if a discard hits the same block as regular I/O, it was intended to skip the discard for the affected range. However, the skip code only advances "data_begin", it doesn't advance "virt_begin". So, the data_begin and virt_begin variables become unsynchronized.
process_prepared_discard_passdown_pt1 calculates "data_end = m->data_block + (m->virt_end - m->virt_begin);" - if m->data_block is incremented and m->virt_begin isn't, it will overshoot the intended discard range.
--- drivers/md/dm-thin.c | 1 + 1 file changed, 1 insertion(+)
drivers/md/dm-thin.c +1 -0
@@ -1705,6 +1705,7 @@ static void break_up_discard_bio(struct (void )build_key (tc->td,PHYSICAL , data_begin, data_begin + len, &data_key);if (bio_detain (tc->pool, &data_key,NULL , &data_cell)) {/* contention, we'll give up with this range */ + virt_begin += len; data_begin += len;continue ; }
Greg Kroah-Hartman
maintainerPATCH 718/816 dm-thin: fix leak if __set_snapshot_details fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit dfb95816cf6f2f2660af2ec64c65dc204c60b5e7 upstream.
If __set_snapshot_details fails, the variable td is leaked - this prevents any other snapshot with the same id from being created.
Fix this by removing it from the list and freeing it.
--- drivers/md/dm-thin-metadata.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/md/dm-thin-metadata.c +4 -1
@@ -1225,10 +1225,13 @@ static int __create_snap(struct dm_pool___close_device (td);if (r) - goto bad; + goto bad2;return 0 ; +bad2: +list_del (&td->list); +kfree (td); bad:dm_btree_remove (&pmd->tl_info, pmd->root, &key, &pmd->root); dm_btree_remove(&pmd->details_info, pmd->details_root,
Greg Kroah-Hartman
maintainerPATCH 719/816 dm-thin: fix parsing of feature arguments
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit c557fa19a83efad1e20eb733df821b745a4589ff upstream.
"struct dm_arg _args" limits the number of arguments to 4, but there are 5 possible arguments that can be specified.
--- drivers/md/dm-thin.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-thin.c +1 -1
@@ -3151,7 +3151,7 @@ static int parse_pool_features(struct dmconst char *arg_name;static const struct dm_arg _args[] = { - {0 ,4 ,"Invalid number of pool feature arguments" }, + {0 ,5 ,"Invalid number of pool feature arguments" }, };/*
Greg Kroah-Hartman
maintainerPATCH 720/816 vt: serialise the producers of the flip buffer
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 5d1d814408c1c8e797031eac8ddd40de1a9e8e93 upstream.
Typing on a virtual console while the console replies to an escape sequence can make the kernel write past the end of a buffer. A user who can write to the foreground console can cause this on purpose if they can also inject key events, through /dev/uinput or by writing to the /dev/input/event* node of a keyboard.
Input for a tty goes through the flip buffer of its port. A driver inserts the data with tty_insert_flip_*() and then calls tty_flip_buffer_push() to pass it on to the line discipline. The insert functions take no lock: they check that the current struct tty_buffer has room, copy the data to offset ->used, and then advance ->used. So a flip buffer supports only one producer at a time, and a driver that has several must serialise them.
Four functions feed the flip buffer of a virtual console:
- put_queue(), puts_queue() and fn_send_intr() insert typed characters and breaks for the keyboard handler. They run under kbd_event_lock.
- respond_string() inserts the reply when a program writes an escape sequence that requests one, such as a cursor position report. It runs under the console lock.
The keyboard handler gets its events from the input layer and feeds the foreground console. Key events that a program writes to /dev/uinput or to an event node reach it in the same way as typed keys.
The keyboard handler and respond_string() share no lock, so they can interleave:
keyboard handler respond_string()
================ ================
room check passes
room check passes
memcpy() to offset used
used += len
memcpy() to offset used used += len
/* used > size of the buffer */
The room check subtracts ->used from the size, and both are unsigned. Once ->used exceeds the size, the result wraps, so the check always passes, and each later insert lands further past the buffer.
Reproduced as root, with keys from a uinput keyboard and cursor position reports on the same console: KFENCE reported an out-of-bounds write 1,024 bytes past the buffer in under 10 s.
Fix this by taking port->lock, with interrupts disabled, around the insert and the push in these four functions. kbd_keycode() already takes port->lock under kbd_event_lock, so this lock ordering is not new.
--- drivers/tty/vt/keyboard.c | 6 ++++++ drivers/tty/vt/vt.c | 2 ++ 2 files changed, 8 insertions(+)
drivers/tty/vt/keyboard.c +6 -0
@@ -321,15 +321,20 @@ int kbd_rate(struct kbd_repeat *rpt)/* * Helper Functions. +* +* A flip buffer allows one producer at a time, and respond_string() in vt.c +* feeds the same one under the console lock. So take the lock of the port. */ static void put_queue (struct vc_data *vc,int ch) { +guard (spinlock_irqsave)(&vc->port.lock);tty_insert_flip_char (&vc->port, ch,0 );tty_flip_buffer_push (&vc->port); }static void puts_queue (struct vc_data *vc,const char *cp) { +guard (spinlock_irqsave)(&vc->port.lock);tty_insert_flip_string (&vc->port, cp,strlen (cp));tty_flip_buffer_push (&vc->port); }
@@ -590,6 +595,7 @@ static void fn_inc_console(struct vc_datstatic void fn_send_intr (struct vc_data *vc) { +guard (spinlock_irqsave)(&vc->port.lock);tty_insert_flip_char (&vc->port,0 ,TTY_BREAK );tty_flip_buffer_push (&vc->port); }
drivers/tty/vt/vt.c +2 -0
@@ -1818,6 +1818,8 @@ static void csi_m(struct vc_data *vc)static void respond_string (const char *p,size_t len,struct tty_port *port) { +/* The keyboard handler feeds the same flip buffer. */ +guard (spinlock_irqsave)(&port->lock);tty_insert_flip_string (port, p, len);tty_flip_buffer_push (port); }
Greg Kroah-Hartman
maintainerPATCH 721/816 comedi: addi_apci_1500: fix clearing of the gate enable
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit ade85ceef46892425a08f3ee52ca06729ee4922e upstream.
INSN_CONFIG_SET_GATE_SRC reads the mode register of the counter/timer, is meant to clear the External Gate Enable bit, sets it again if the external gate was asked for, and writes the register back. The mask lacks its '~': all the bits but EGE are cleared instead. So
- the external gate can be enabled but never be disabled again, and
- the instruction wipes the mode (continuous or single cycle, external output, count and trigger enables, retrigger, duty cycle) which INSN_CONFIG_SET_COUNTER_MODE has programmed: the timer silently falls back to a single cycle pulse.
With the right mask, the instruction only changes the gate bit. An application which sets the gate source after the counter mode now keeps the mode it has asked for.
--- drivers/comedi/drivers/addi_apci_1500.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/comedi/drivers/addi_apci_1500.c +1 -1
@@ -696,7 +696,7 @@ static int apci1500_timer_insn_config(streturn -EINVAL ; val =z8536_read (dev,Z8536_CT_MODE_REG (chan)); - val &=Z8536_CT_MODE_EGE ; + val &= ~Z8536_CT_MODE_EGE ;if (data[1 ] ==1 ) val |=Z8536_CT_MODE_EGE ;else if (data[1 ] >1 )
Greg Kroah-Hartman
maintainerPATCH 722/816 comedi: ni_660x: dont poll without a DMA channel
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 5a0c88567a5ebbe24ecb7828e200f63ed972718f upstream.
A counter command owns a MITE DMA channel from ni_660x_cmd() to ni_660x_cancel(). A command does not only end by COMEDI_CANCEL: when the reader is too slow mite_sync_input_dma() sets COMEDI_CB_OVERFLOW, and counter errors set COMEDI_CB_ERROR, and comedi_handle_events() then calls ->cancel() from the interrupt handler. That releases the channel and clears counter->mite_chan, but s->busy stays set until the owner has read the rest of the data and seen the end of the acquisition.
do_poll_ioctl() only looks at s->busy, so a COMEDI_POLL in that state ends in mite_sync_dma(NULL, s), which dereferences the channel.
Test the channel like ni_pcidio_poll() and ni_sync_ai_dma() do. The pointer only changes under dev->mutex, which the ioctl holds, or in the interrupt handler under interrupt_lock, which is taken here.
--- drivers/comedi/drivers/ni_660x.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/comedi/drivers/ni_660x.c +2 -1
@@ -459,7 +459,8 @@ static int ni_660x_input_poll(struct com/* lock to avoid race with comedi_poll */ spin_lock_irqsave (&devpriv->interrupt_lock, flags); -mite_sync_dma (counter->mite_chan, s); +if (counter->mite_chan) +mite_sync_dma (counter->mite_chan, s);spin_unlock_irqrestore (&devpriv->interrupt_lock, flags);return comedi_buf_read_n_available (s); }
Greg Kroah-Hartman
maintainerPATCH 723/816 comedi: ni_tio: Fix overflow of the clock period
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit ec214735bb113be747454812035b83010892e0d2 upstream.
ni_tio_set_clock_src() stores the period of the clock source, which the user passes in nanoseconds, in picoseconds:
counter->clock_period_ps = period_ns * 1000;
period_ns is an unsigned int, so that the product is computed in 32 bits, although clock_period_ps is a u64. It wraps for periods above 4294967 ns, that is for external clocks slower than 233 Hz. INSN_CONFIG_GET_CLOCK_SRC then reports a wrong period, and ni_tio_set_sync_mode() decides on a wrong one: 4294968 ns become 704 ps, which is below the limit of 25 ns under which the alternate synchronization mode for fast clocks is switched on.
The multiplication was done in 64 bits until the constant pico_per_nano, a uint64_t, was replaced by a literal. Widen again.
--- drivers/comedi/drivers/ni_tio.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/comedi/drivers/ni_tio.c +1 -1
@@ -800,7 +800,7 @@ static int ni_tio_set_clock_src(struct nGI_PRESCALE_X2 (counter_dev->variant) | GI_PRESCALE_X8(counter_dev->variant), bits); } - counter->clock_period_ps = period_ns *1000 ; + counter->clock_period_ps = (u64 )period_ns *1000 ;ni_tio_set_sync_mode (counter);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 724/816 comedi: vmk80xx: report failed transfers of the K8061
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 92fa93505576188acc22c5de1999db9a1c70c09b upstream.
For the K8061 board vmk80xx_read_packet() and vmk80xx_write_packet() call vmk80xx_do_bulk_msg(), which ignores the result of its two bulk transfers, and return 0. After a timeout, a stall or an unplug the instruction handlers therefore go on and hand the old content of usb_rx_buf to user space as a fresh sample (analog and digital inputs, counters, PWM and output read-back), and writes to the outputs are reported as done.
All callers check the result already, because the K8055 branch of the two functions returns that of usb_interrupt_msg(). Return the error of the bulk transfers as well, and don't wait for an answer to a command that could not be sent.
--- drivers/comedi/drivers/vmk80xx.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-)
drivers/comedi/drivers/vmk80xx.c +12 -13
@@ -151,7 +151,7 @@ struct vmk80xx_private {enum vmk80xx_model model; }; -static void vmk80xx_do_bulk_msg (struct comedi_device *dev) +static int vmk80xx_do_bulk_msg (struct comedi_device *dev) {struct vmk80xx_private *devpriv = dev->private;struct usb_device *usb =comedi_to_usb_dev (dev);
@@ -161,6 +161,7 @@ static void vmk80xx_do_bulk_msg(struct cunsigned int rx_pipe;size_t tx_size;size_t rx_size; +int ret; tx_addr = devpriv->ep_tx->bEndpointAddress; rx_addr = devpriv->ep_rx->bEndpointAddress;
@@ -169,11 +170,13 @@ static void vmk80xx_do_bulk_msg(struct c tx_size =usb_endpoint_maxp (devpriv->ep_tx); rx_size =usb_endpoint_maxp (devpriv->ep_rx); -usb_bulk_msg (usb, tx_pipe, devpriv->usb_tx_buf, tx_size,NULL , -PACKET_TIMEOUT ); + ret =usb_bulk_msg (usb, tx_pipe, devpriv->usb_tx_buf, tx_size,NULL , +PACKET_TIMEOUT ); +if (ret) +return ret; -usb_bulk_msg (usb, rx_pipe, devpriv->usb_rx_buf, rx_size,NULL , -PACKET_TIMEOUT ); +return usb_bulk_msg (usb, rx_pipe, devpriv->usb_rx_buf, rx_size,NULL , +PACKET_TIMEOUT ); }static int vmk80xx_read_packet (struct comedi_device *dev)
@@ -183,10 +186,8 @@ static int vmk80xx_read_packet(struct costruct usb_endpoint_descriptor *ep;unsigned int pipe; -if (devpriv->model ==VMK8061_MODEL ) { -vmk80xx_do_bulk_msg (dev); -return 0 ; - } +if (devpriv->model ==VMK8061_MODEL ) +return vmk80xx_do_bulk_msg (dev); ep = devpriv->ep_rx; pipe =usb_rcvintpipe (usb, ep->bEndpointAddress);
@@ -204,10 +205,8 @@ static int vmk80xx_write_packet(struct c devpriv->usb_tx_buf[0 ] = cmd; -if (devpriv->model ==VMK8061_MODEL ) { -vmk80xx_do_bulk_msg (dev); -return 0 ; - } +if (devpriv->model ==VMK8061_MODEL ) +return vmk80xx_do_bulk_msg (dev); ep = devpriv->ep_tx; pipe =usb_sndintpipe (usb, ep->bEndpointAddress);
Greg Kroah-Hartman
maintainerPATCH 725/816 iio: accel: adxl380: dont stay in standby on -EINVAL
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 4c56180167ea4d419a0578545bf62110494b563d upstream.
adxl380_set_act_inact_threshold() puts the sensor into standby, writes the threshold and switches the measurement on again. A threshold above 8191 is refused in between, and the sensor stays in standby: no samples and no events until the next write that succeeds.
adxl380_set_range() has the same problem and a worse one. It rescales both thresholds for the new range. If one no longer fits it returns -EINVAL with the sensor in standby, the new range in the chip, the old one in st->range and rescaled thresholds in the driver's state: from the next successful write on the samples are reported with the wrong scale.
Switch the measurement on again if the threshold is refused. In adxl380_set_range() see whether the thresholds fit before anything is changed.
--- drivers/iio/accel/adxl380.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
drivers/iio/accel/adxl380.c +10 -1
@@ -341,8 +341,11 @@ static int adxl380_set_act_inact_threshoreturn ret; ret =adxl380_write_act_inact_threshold (st, act, th); -if (ret) +if (ret) { +/* Leave standby also if the value was refused */ +adxl380_set_measure_en (st, true);return ret; + }return adxl380_set_measure_en (st, true); }
@@ -709,6 +712,12 @@ static int adxl380_set_range(struct adxlguard (mutex)(&st->lock); +/* The thresholds are rescaled: see that they fit before any change */ +if (mult_frac (max (st->act_threshold, st->inact_threshold), + adxl380_range_scale_factor_tbl[st->range], + adxl380_range_scale_factor_tbl[range]) >ADXL380_THRESH_MAX ) +return -EINVAL ; + ret =adxl380_set_measure_en (st, false);if (ret)return ret;
Greg Kroah-Hartman
maintainerPATCH 726/816 iio: addac: ad74413r: fix the values of set_multiple
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit e6dfbd84b833ed595a5236b027357e917de28260 upstream.
ad74413r_gpio_set_multiple() walks over the lines in the mask and looks up the new value of each with
if (*bits & offset)
offset is the number of the line, not a bit mask. Line 0 is always driven low, line 1 gets the value meant for line 0, line 2 the one meant for line 1, and line 3 is driven high if either of these two is.
Test the bit which belongs to the line.
--- drivers/iio/addac/ad74413r.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/addac/ad74413r.c +1 -1
@@ -312,7 +312,7 @@ static void ad74413r_gpio_set_multiple(sreturn ; real_mask |=BIT (real_offset); -if (*bits & offset) +if (test_bit (offset, bits)) real_bits |=BIT (real_offset); }
Greg Kroah-Hartman
maintainerPATCH 727/816 iio: hid-sensors: fix a division by zero
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit fd4c92bbd3a64556e81042ff8d30545b15a3b93a upstream.
convert_to_vtf_format() divides the micro part of a value by 10^(6 + exp). The unit exponent of a HID field is a nibble and goes down to -8. For -7 and -8 the argument of int_pow() is negative, which the unsigned parameter turns into a huge power of ten: 0 modulo 2^64. The division by it is a divide error. The exponent comes from the report descriptor of the sensor hub, the value from a write to the hysteresis attribute of the IIO device.
Multiply by 10^(-exp - 6) in these two cases.
--- drivers/iio/common/hid-sensors/hid-sensor-attributes.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/iio/common/hid-sensors/hid-sensor-attributes.c +4 -1
@@ -137,7 +137,10 @@ static u32 convert_to_vtf_format(int sizif (val1 <0 || val2 <0 ) sign =-1 ; exp =hid_sensor_convert_exponent (exp); -if (exp <0 ) { +if (exp <-6 ) { + value =abs (val1) *int_pow (10 , -exp); + value +=abs (val2) *int_pow (10 , -exp -6 ); + }else if (exp <0 ) { divisor =int_pow (10 ,6 + exp); value =abs (val1) *int_pow (10 , -exp); value +=abs (val2) / divisor;
Greg Kroah-Hartman
maintainerPATCH 728/816 iio: sx9310: use the data of the I2C table
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit f3fc8718af9189aad13a2ad7f5b256475bb14b21 upstream.
sx9310_check_whoami() takes the chip information from device_get_match_data(), which only looks at the OF and ACPI tables, and dereferences it. For a client which was bound through the i2c_device_id table, for instance one created with
echo sx9310 0x28 > /sys/bus/i2c/devices/i2c-1/new_device
it returns NULL, and the kernel oopses as soon as something at that address answers the read of the WHOAMI register.
The I2C table has the same pointers. Use i2c_get_match_data(), which falls back to it.
--- drivers/iio/proximity/sx9310.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/proximity/sx9310.c +1 -1
@@ -885,7 +885,7 @@ static int sx9310_check_whoami(struct deif (ret)return ret; - ddata =device_get_match_data (dev); + ddata =i2c_get_match_data (data->client);if (ddata->whoami != whoami)return -ENODEV ;
Greg Kroah-Hartman
maintainerPATCH 729/816 misc: bcm-vk: fix DMA allocation memory leak
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guangshuo Li <[email protected]>
commit a36b3db60466d44eefcc5c252ce927c043429922 upstream.
bcm_vk_dma_alloc() leaks dma->pages and pinned user-page references when page pinning or coherent SG allocation fails. DMA mapping failures can also leave the SG list and earlier mappings unreleased, as bcm_vk_sg_alloc() skips the partially initialized slot.
This issue was found by our static analysis tool under development.
--- drivers/misc/bcm-vk/bcm_vk_sg.c | 43 +++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-)
drivers/misc/bcm-vk/bcm_vk_sg.c +36 -7
@@ -80,7 +80,8 @@ static int bcm_vk_dma_alloc(struct devic dma->nr_pages = (err >=0 ) ? err :0 ;dev_err (dev,"get_user_pages_fast, err=%d [%d]\n" , err, dma->nr_pages); -return err <0 ? err : -EINVAL ; + err = err <0 ? err : -EINVAL ; + goto err_pages; }/* Max size of sg list is 1 per mapped page + fields at start */
@@ -92,8 +93,10 @@ static int bcm_vk_dma_alloc(struct devic dma->sglen, &dma->handle, GFP_KERNEL); -if (!dma->sglist) -return -ENOMEM ; +if (!dma->sglist) { + err = -ENOMEM ; + goto err_pages; + } dma->sglist[SGLIST_NUM_SG ] =0 ; dma->sglist[SGLIST_TOTALSIZE ] = vkdata->size;
@@ -110,8 +113,8 @@ static int bcm_vk_dma_alloc(struct devic dma->direction); transfer_size = size;if (unlikely (dma_mapping_error (dev, sg_addr))) { -__free_page (dma->pages[0 ]); -return -EIO ; + err = -EIO ; + goto err_sglist; }for (i =1 ; i < dma->nr_pages; i++) {
@@ -123,8 +126,8 @@ static int bcm_vk_dma_alloc(struct devic size, dma->direction);if (unlikely (dma_mapping_error (dev, addr))) { -__free_page (dma->pages[i]); -return -EIO ; + err = -EIO ; + goto err_unmap; }/*
@@ -169,6 +172,32 @@ static int bcm_vk_dma_alloc(struct devic#endif return 0 ; + +err_unmap: +/* +* Unmap completed SG entries and the in-progress DMA range, +* which has not been written to the SG list yet. +*/ + sgdata = (struct _vk_data *)&dma->sglist[SGLIST_VKDATA_START ]; +for (i =0 ; i < dma->sglist[SGLIST_NUM_SG ]; i++) { + size = sgdata[i].size; + addr =get_unaligned (&sgdata[i].address); +dma_unmap_page (dev, addr, size, dma->direction); + } +dma_unmap_page (dev, sg_addr, transfer_size, dma->direction); + +err_sglist: +dma_free_coherent (dev, dma->sglen, dma->sglist, dma->handle); + +err_pages: +for (i =0 ; i < dma->nr_pages; i++) +put_page (dma->pages[i]); +kfree (dma->pages); + dma->pages =NULL ; + dma->sglist =NULL ; + dma->sglen =0 ; + dma->nr_pages =0 ; +return err; } int bcm_vk_sg_alloc(struct device *dev,
Greg Kroah-Hartman
maintainerPATCH 730/816 misc: ibmvmc: initialize HMC state before device registration
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 2022f170e5655c40b93ed98629f7d0adb98cea49 upstream.
misc_register() exposes the IBM VMC device before the HMC state and spinlocks are initialized. A userspace operation racing module initialization can therefore access an HMC through an uninitialized spinlock.
Initialize all HMC state before registering the misc device.
--- drivers/misc/ibmvmc.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)
drivers/misc/ibmvmc.c +8 -8
@@ -2365,14 +2365,6 @@ static int __init ibmvmc_module_init(voi ibmvmc.state = ibmvmc_state_initial;pr_info ("ibmvmc: version %s\n" ,IBMVMC_DRIVER_VERSION ); - rc =misc_register (&ibmvmc_miscdev); -if (rc) { -pr_err ("ibmvmc: misc registration failed\n" ); - goto misc_register_failed; - } -pr_info ("ibmvmc: node %d:%d\n" ,MISC_MAJOR , - ibmvmc_miscdev.minor); -/* Initialize data structures */ memset (hmcs,0 ,sizeof (struct ibmvmc_hmc ) *MAX_HMCS );for (i =0 ; i <MAX_HMCS ; i++) {
@@ -2382,6 +2374,14 @@ static int __init ibmvmc_module_init(voi hmcs[i].queue_outbound_msgs[j] =VMC_INVALID_BUFFER_ID ; } + rc =misc_register (&ibmvmc_miscdev); +if (rc) { +pr_err ("ibmvmc: misc registration failed\n" ); + goto misc_register_failed; + } +pr_info ("ibmvmc: node %d:%d\n" ,MISC_MAJOR , + ibmvmc_miscdev.minor); +/* Sanity check module parms */ ibmvmc_scrub_module_parms ();