6.12.117-rc1 review
Subsystems (5)
Greg Kroah-Hartman
maintainerPATCH 526/1536 drm/amdkfd: Avoid integer underflow with ffs in EOP ring size calc
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Francis <[email protected]>
[ Upstream commit c883d0a132d430ef7ebb23fd94323be94d0fbdb8 ]
The low 6 bits of cp_hqd_eop_control store the base-2 logarithm of the EOP ring size. This was calculated as
ffs(q->eop_ring_buffer_size / sizeof(unsigned int)) - 1 - 1
But ffs can in theory return 1 or 0, so this could underflow (although in practice the ring buffer size cannot be less than 4096).
Change this to
ffs(q->eop_ring_buffer_size / sizeof(unsigned int) / 4)
using properties of logarithms.
--- drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v10.c | 2 +- drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v11.c | 2 +- drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v12.c | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v10.c +1 -1
@@ -199,7 +199,7 @@ static void update_mqd(struct mqd_manager *mm, void *mqd,* is safe, giving a maximum field value of 0xA. */ m->cp_hqd_eop_control = q->eop_ring_buffer_size ?min (0xA , -ffs (q->eop_ring_buffer_size /sizeof (unsigned int )) -1 -1 ) :0 ; +ffs (q->eop_ring_buffer_size /sizeof (unsigned int ) /4 )) :0 ; m->cp_hqd_eop_base_addr_lo =lower_32_bits (q->eop_ring_buffer_address >>8 ); m->cp_hqd_eop_base_addr_hi =
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v11.c +1 -1
@@ -252,7 +252,7 @@ static void update_mqd(struct mqd_manager *mm, void *mqd,* is safe, giving a maximum field value of 0xA. */ m->cp_hqd_eop_control = q->eop_ring_buffer_size ?min (0xA , -ffs (q->eop_ring_buffer_size /sizeof (unsigned int )) -1 -1 ) :0 ; +ffs (q->eop_ring_buffer_size /sizeof (unsigned int ) /4 )) :0 ; m->cp_hqd_eop_base_addr_lo =lower_32_bits (q->eop_ring_buffer_address >>8 ); m->cp_hqd_eop_base_addr_hi =
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v12.c +1 -1
@@ -215,7 +215,7 @@ static void update_mqd(struct mqd_manager *mm, void *mqd,* is safe, giving a maximum field value of 0xA. */ m->cp_hqd_eop_control = q->eop_ring_buffer_size ?min (0xA , -ffs (q->eop_ring_buffer_size /sizeof (unsigned int )) -1 -1 ) :0 ; +ffs (q->eop_ring_buffer_size /sizeof (unsigned int ) /4 )) :0 ; m->cp_hqd_eop_base_addr_lo =lower_32_bits (q->eop_ring_buffer_address >>8 ); m->cp_hqd_eop_base_addr_hi =
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 527/1536 drm/amdkfd: Avoid integer underflow in EOP ring size calculation.
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Francis <[email protected]>
[ Upstream commit 8ee521b8b189799e361d4233c5180ba56656d4d4 ]
The low 6 bits of cp_hqd_eop_control store the base-2 logarithm of the EOP ring size. This was calculated as
order_base_2(q->eop_ring_buffer_size / 4) - 1
But order_base_2 can in theory return 0, so this could underflow (although in practice the ring buffer size cannot be less than 4096).
Change this to
order_base_2(q->eop_ring_buffer_size / 8)
using properties of logarithms.
Also add to the above comment to make the mathematics more clear.
--- drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v9.c | 6 +++++- drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_vi.c | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v9.c +5 -1
@@ -271,6 +271,10 @@ static void update_mqd(struct mqd_manager *mm, void *mqd,1 <<CP_HQD_IB_CONTROL__IB_EXE_DISABLE__SHIFT ;/* +* The lowest 6 bits of eop_control store the EOP ring size. If +* their value is X, the ring size is 2^(X + 1) dwords, or +* 2^(X + 3) bytes. +* * HW does not clamp this field correctly. Maximum EOP queue size * is constrained by per-SE EOP done signal count, which is 8-bit. * Limit is 0xFF EOP entries (= 0x7F8 dwords). CP will not submit
@@ -282,7 +286,7 @@ static void update_mqd(struct mqd_manager *mm, void *mqd,* */ m->cp_hqd_eop_control = q->eop_ring_buffer_size ? -min (0xA ,order_base_2 (q->eop_ring_buffer_size /4 ) -1 ) :0 ; +min (0xA ,order_base_2 (q->eop_ring_buffer_size /8 )) :0 ; m->cp_hqd_eop_base_addr_lo =lower_32_bits (q->eop_ring_buffer_address >>8 );
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_vi.c +4 -1
@@ -203,6 +203,9 @@ static void __update_mqd(struct mqd_manager *mm, void *mqd, mtype <<CP_HQD_IB_CONTROL__MTYPE__SHIFT ;/* +* The lowest 6 bits of eop_control store the EOP ring size. If +* their value is X, the ring size is 2^(X + 1) dwords, or +* 2^(X + 3) bytes. * HW does not clamp this field correctly. Maximum EOP queue size * is constrained by per-SE EOP done signal count, which is 8-bit. * Limit is 0xFF EOP entries (= 0x7F8 dwords). CP will not submit
@@ -210,7 +213,7 @@ static void __update_mqd(struct mqd_manager *mm, void *mqd,* is safe, giving a maximum field value of 0xA. */ m->cp_hqd_eop_control |= q->eop_ring_buffer_size ?min (0xA , -order_base_2 (q->eop_ring_buffer_size /4 ) -1 ) :0 ; +order_base_2 (q->eop_ring_buffer_size /8 )) :0 ; m->cp_hqd_eop_base_addr_lo =lower_32_bits (q->eop_ring_buffer_address >>8 ); m->cp_hqd_eop_base_addr_hi =
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 528/1536 smb: client: delete compound mids on send failure before unlock
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Adarsh Das <[email protected]>
[ Upstream commit 8f6f8a48399f82f4a83f7b9f25b9707e0062a4f9 ]
When sending a compound request fails, smb_send_rqst() kicks off a reconnect. compound_send_recv() still has those mids on pending_mid_q, but it unlocks the server without removing them first.
During reconnect, cifs_abort_connection() walks pending_mid_q and runs each mid callback. With no response yet, those callbacks return credits and drop in_flight. Then compound_send_recv()'s send-error path returns the same credits again. in_flight ends up decremented twice and smb2_add_credits() WARNs.
syzbot hits this during SMB2_negotiate when the socket send fails.
cifs_call_async() already calls delete_mid() before unlock on send failure. Do the same for compound chains and set cancelled_mid[] so the
out: path does not delete them again.
--- fs/smb/client/transport.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/smb/client/transport.c +4 -0
@@ -1170,6 +1170,10 @@ compound_send_recv(const unsigned int xid, struct cifs_ses *ses,if (rc <0 ) {revert_current_mid (server, num_rqst); server->sequence_number -=2 ; +for (i =0 ; i < num_rqst; i++) { +delete_mid (midQ[i]); + cancelled_mid[i] = true; + } }cifs_server_unlock (server);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 529/1536 drm/i915/dp_mst: Fix configuring TUs for a disconnected stream
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Imre Deak <[email protected]>
[ Upstream commit a443e0b8d647c1401b110d9f919d8c6cb8607260 ]
During an atomic commit after all the MST stream CRTC state is computed the driver ensures that the sum of TUs of all the streams on a given MST topology link is within limits (63 for 8b10 and 64 for 128b132b). For a disconnected stream the DRM MST core's BW verification doesn't ensure this, because the topology state it uses for this is destroyed as soon as the stream (i.e. MST connector/port) is disconnected. The driver should keep the link state valid even for such disconnected streams, as userspace may disable them one-by-one only in a deferred way. Ensure the link's sum of TUs stays within limits in this case by simply reusing the maximum link BPP limit from the stream's (i.e. CRTC's) old state.
The disconnection can happen either via the whole topology getting disconnected or via only the given stream's port getting disconnected. Check for both of these conditions separately, as a connector gets unregistered after a link disconnect event only in a deferred way.
--- drivers/gpu/drm/i915/display/intel_dp_mst.c | 21 ++++++++++++++++++++ drivers/gpu/drm/i915/display/intel_dp_mst.h | 2 ++ drivers/gpu/drm/i915/display/intel_link_bw.c | 4 +++- 3 files changed, 26 insertions(+), 1 deletion(-)
drivers/gpu/drm/i915/display/intel_dp_mst.c +21 -0
@@ -2054,6 +2054,27 @@ bool intel_dp_mst_crtc_needs_modeset(struct intel_atomic_state *state,return false; } +bool intel_dp_mst_stream_disconnected (struct intel_atomic_state *state, +const struct intel_crtc *crtc) +{ +struct intel_connector *connector; + + connector =get_connector_in_state_for_crtc (state, crtc); +if (!connector) +return false; + +if (!connector->mst.dp) +return false; + +if (!connector->mst.dp->mst.mgr.mst_state) +return true; + +if (drm_connector_is_unregistered (&connector->base)) +return true; + +return false; +} +/** * intel_dp_mst_prepare_probe - Prepare an MST link for topology probing * @intel_dp: DP port object
drivers/gpu/drm/i915/display/intel_dp_mst.h +2 -0
@@ -27,6 +27,8 @@ int intel_dp_mst_atomic_check_link(struct intel_atomic_state *state, struct intel_link_bw_limits *limits);bool intel_dp_mst_crtc_needs_modeset (struct intel_atomic_state *state,struct intel_crtc *crtc); +bool intel_dp_mst_stream_disconnected (struct intel_atomic_state *state, +const struct intel_crtc *crtc);void intel_dp_mst_prepare_probe (struct intel_dp *intel_dp);bool intel_dp_mst_verify_dpcd_state (struct intel_dp *intel_dp);
drivers/gpu/drm/i915/display/intel_link_bw.c +3 -1
@@ -35,7 +35,9 @@ void intel_link_bw_init_limits(struct intel_atomic_state *state,intel_atomic_get_new_crtc_state (state,intel_crtc_for_pipe (display, pipe)); -if (state->base.duplicated && crtc_state) { +if ((state->base.duplicated && crtc_state) || +intel_dp_mst_stream_disconnected (state, +intel_crtc_for_pipe (display, pipe))) { limits->max_bpp_x16[pipe] = crtc_state->max_link_bpp_x16;if (crtc_state->fec_enable) limits->force_fec_pipes |=BIT (pipe);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 530/1536 KVM: x86: Re-pend GET_NESTED_STATE_PAGES if getting said pages fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit 10180a277549339020b08000206092c07e0bff5a ]
Re-pend GET_NESTED_STATE_PAGES before exiting to userspace if getting the nested pages fails in the KVM_RUN path. If userspace re-runs the vCPU, and vmcs02 holds valid PFNs from the *previous* run of L2, then KVM could re-enter L2 with stale, unpinned PFNs mapped into e.g. the vAPIC page.
Note, both SVM and VMX (as of commit 11722439fb20 ("KVM: nVMX: Ensure KVM_REQ_GET_NESTED_STATE_PAGES is cleared on VM-Exit") ensure the request is cleared on VM-Exit (including the "forced" case), i.e. there is no risk of double-mapping due to emulated VMLAUNCH/VMRESUME/VMRUN *and* the request trying to map the nested pages.
--- arch/x86/kvm/x86.c | 1 + 1 file changed, 1 insertion(+)
arch/x86/kvm/x86.c +1 -0
@@ -10300,6 +10300,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)if (kvm_check_request (KVM_REQ_GET_NESTED_STATE_PAGES , vcpu)) {if (unlikely (!kvm_x86_ops.nested_ops->get_nested_state_pages (vcpu))) { +kvm_make_request (KVM_REQ_GET_NESTED_STATE_PAGES , vcpu); r =0 ; goto out; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 531/1536 KVM: x86: Fill kvm_run exit fields in common get_nested_state_pages() error paths
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit c1214f293d77c6e425a379f90d09bdb4815993a8 ]
Fill kvm_run with "internal error, emulation" in the common error handling paths for getting nested state pages, as requiring each check to manually fill kvm_run is error prone and requires a non-trivial amount of copy+paste.
Specifically, both SVM and VMX fail to fill kvm_run if load_pdptrs() fails, and SVM fails to fill kvm_run if kvm_hv_verify_vp_assist() fails. If those flows fail, the *best* case scenario is that KVM will exit to userspace with KVM_EXIT_UNKNOWN. The worst case scenario is that KVM exits with a stale exit_reason and confuses userspace.
Note, SVM never exits to userspace if something goes sideways when dealing with vmcb12 assets while emulating VMRUN, i.e. lack of SVM-specific code is not a bug.
--- arch/x86/kvm/svm/nested.c | 7 +------ arch/x86/kvm/vmx/nested.c | 15 +++++---------- arch/x86/kvm/x86.c | 3 +++ 3 files changed, 9 insertions(+), 16 deletions(-)
arch/x86/kvm/svm/nested.c +1 -6
@@ -1834,13 +1834,8 @@ static bool svm_get_nested_state_pages(struct kvm_vcpu *vcpu)if (CC (!load_pdptrs (vcpu, vcpu->arch.cr3)))return false; -if (!nested_svm_vmrun_msrpm (svm)) { - vcpu->run->exit_reason =KVM_EXIT_INTERNAL_ERROR ; - vcpu->run->internal.suberror = -KVM_INTERNAL_ERROR_EMULATION ; - vcpu->run->internal.ndata =0 ; +if (!nested_svm_vmrun_msrpm (svm))return false; - }if (kvm_hv_verify_vp_assist (vcpu))return false;
arch/x86/kvm/vmx/nested.c +5 -10
@@ -3361,10 +3361,6 @@ static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu) }else {pr_debug_ratelimited ("%s: no backing for APIC-access address in vmcs12\n" , __func__); - vcpu->run->exit_reason =KVM_EXIT_INTERNAL_ERROR ; - vcpu->run->internal.suberror = -KVM_INTERNAL_ERROR_EMULATION ; - vcpu->run->internal.ndata =0 ;return false; } }
@@ -3435,11 +3431,6 @@ static bool vmx_get_nested_state_pages(struct kvm_vcpu *vcpu)if (!nested_get_evmcs_page (vcpu)) {pr_debug_ratelimited ("%s: enlightened vmptrld failed\n" , __func__); - vcpu->run->exit_reason =KVM_EXIT_INTERNAL_ERROR ; - vcpu->run->internal.suberror = -KVM_INTERNAL_ERROR_EMULATION ; - vcpu->run->internal.ndata =0 ; -return false; }#endif
@@ -3844,8 +3835,12 @@ static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch) vmentry_failed: vmx->nested.nested_run_pending =0 ; -if (status ==NVMX_VMENTRY_KVM_INTERNAL_ERROR ) +if (status ==NVMX_VMENTRY_KVM_INTERNAL_ERROR ) { + vcpu->run->exit_reason =KVM_EXIT_INTERNAL_ERROR ; + vcpu->run->internal.suberror =KVM_INTERNAL_ERROR_EMULATION ; + vcpu->run->internal.ndata =0 ;return 0 ; + }if (status ==NVMX_VMENTRY_VMEXIT )return 1 ;WARN_ON_ONCE (status !=NVMX_VMENTRY_VMFAIL );
arch/x86/kvm/x86.c +3 -0
@@ -10300,6 +10300,9 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)if (kvm_check_request (KVM_REQ_GET_NESTED_STATE_PAGES , vcpu)) {if (unlikely (!kvm_x86_ops.nested_ops->get_nested_state_pages (vcpu))) { + vcpu->run->exit_reason =KVM_EXIT_INTERNAL_ERROR ; + vcpu->run->internal.suberror =KVM_INTERNAL_ERROR_EMULATION ; + vcpu->run->internal.ndata =0 ;kvm_make_request (KVM_REQ_GET_NESTED_STATE_PAGES , vcpu); r =0 ; goto out;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 532/1536 serial: 8250_omap: fix wake irq cleared during suspend
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kendall Willis <[email protected]>
[ Upstream commit 73f3e6ca7a6a7c952977c7c94f1c6dddebcafa34 ]
The wake irq was cleared in shutdown(), which runs during the suspend sequence, making it impossible to wake the system via UART. Move wake irq setup to probe() and teardown to remove() so the irq remains armed during suspend when the UART is a wakeup source.
--- drivers/tty/serial/8250/8250_omap.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-)
drivers/tty/serial/8250/8250_omap.c +8 -7
@@ -716,12 +716,6 @@ static int omap_8250_startup(struct uart_port *port)struct uart_8250_dma *dma = &priv->omap8250_dma;int ret; -if (priv->wakeirq) { - ret =dev_pm_set_dedicated_wake_irq (port->dev, priv->wakeirq); -if (ret) -return ret; - } -pm_runtime_get_sync (port->dev);serial_out (up,UART_FCR ,UART_FCR_CLEAR_RCVR |UART_FCR_CLEAR_XMIT );
@@ -794,7 +788,6 @@ static void omap_8250_shutdown(struct uart_port *port)serial_out (up,UART_IER ,0 );uart_port_unlock_irq (port);disable_irq_nosync (up->port.irq); -dev_pm_clear_wake_irq (port->dev);serial8250_release_dma (up); up->dma =NULL ;
@@ -1602,6 +1595,12 @@ static int omap8250_probe(struct platform_device *pdev) priv->wakeirq =irq_of_parse_and_map (np,1 ); +if (priv->wakeirq) { + ret =dev_pm_set_dedicated_wake_irq (&pdev->dev, priv->wakeirq); +if (ret) + goto err; + } + ret =serial8250_register_8250_port (&up);if (ret <0 ) {dev_err (&pdev->dev,"unable to register 8250 port\n" );
@@ -1612,6 +1611,7 @@ static int omap8250_probe(struct platform_device *pdev)pm_runtime_put_autosuspend (&pdev->dev);return 0 ; err: +dev_pm_clear_wake_irq (&pdev->dev);pm_runtime_dont_use_autosuspend (&pdev->dev);pm_runtime_put_sync (&pdev->dev);flush_work (&priv->qos_work);
@@ -1634,6 +1634,7 @@ static void omap8250_remove(struct platform_device *pdev)omap_8250_shutdown (&up->port);serial8250_unregister_port (priv->line); priv->line = -ENODEV ; +dev_pm_clear_wake_irq (&pdev->dev);pm_runtime_dont_use_autosuspend (&pdev->dev);pm_runtime_put_sync (&pdev->dev);flush_work (&priv->qos_work);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 533/1536 net/sched: act_ct: remove add_helper dead code
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ilya Maximets <[email protected]>
[ Upstream commit 00df72e39f306e2f7adb68528a5c92109da6a0a9 ]
This variable can only become 'true' when the connection is not confirmed, but it is only checked when it is confirmed. So, it can be treated as being always false and just removed.
--- net/sched/act_ct.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
net/sched/act_ct.c +2 -3
@@ -984,7 +984,6 @@ TC_INDIRECT_SCOPE int tcf_ct_act(struct sk_buff *skb, const struct tc_action *a,struct nf_hook_state state;int nh_ofs, err, retval;struct tcf_ct_params *p; -bool add_helper = false;bool skb_is_ours = false;bool skip_add = false;bool defrag = false;
@@ -1094,7 +1093,7 @@ TC_INDIRECT_SCOPE int tcf_ct_act(struct sk_buff *skb, const struct tc_action *a, err =__nf_ct_try_assign_helper (ct, p->tmpl,GFP_ATOMIC );if (err) goto drop; - add_helper = true; +if (nat && !nfct_seqadj (ct)) {if (!nfct_seqadj_ext_add (ct)) goto drop;
@@ -1113,7 +1112,7 @@ TC_INDIRECT_SCOPE int tcf_ct_act(struct sk_buff *skb, const struct tc_action *a,* or if we're about to commit. This has to be done after all the * extensions are already added. */ -if (nf_ct_is_confirmed (ct) ? ((!cached && !skip_add) || add_helper) : commit) { +if (nf_ct_is_confirmed (ct) ? (!cached && !skip_add) : commit) { err =nf_ct_helper (skb, ct, ctinfo, family);if (err !=NF_ACCEPT ) goto nf_error;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 534/1536 fs: dont silently unmount busy mounts
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 6857e209015f95be7a8f19a9cd5dac345b9b9859 ]
The propagate_mount_busy() helper exists to decide whether a synchronous can suceed. It does that by looking at the copies of the victims in the mounts its parent propagates to. One of those functions from propagation hell.
It skips a copy that has child mounts except for the case of a single child mount covering the copy's root. That algorithm used to be exact. It isn't anymore.
Originally only childless copies were unmounted during propagation. And 1064f874abc0 ("mnt: Tuck mounts under others instead of creating shadow/side mounts.") ended up adding covered mounts to both sides in one go.
Along came 99b19d16471e ("mnt: In propgate_umount handle visiting mounts in any order") and that started to unmount more than before:
[1]: A copy of a mount is unmounted when each of its children is either
its overmount or a copy of the victim itself. In the former case the overmount gets reparented. In the latter case the copy of the victim will end up being unmounted.
So propagate_umount() ended up being rewritten without adjusting propagate_mount_busy(). And currently propagate_mount_busy() doesn't look at copies of the victim that have two or more children nor a single child that is not the overmount.
So any such copy in [1] is not checked for
references. The result is that a synchronous unmount succeeds, pulling out a mount that is still in use.
A container can run into this with its own mounts. The host shares a tree with the container and the host has a mount in that tree:
mount -t tmpfs none /mnt mount --make-shared /mnt mount -t tmpfs none /mnt/a
The container's /mnt is a slave copy of the host mount. The container now takes a detached copy of the tree and mounts that copy beneath its propagated copy of /mnt/a and keeps the file descriptor to the tree open:
unshare -m --propagation unchanged mount --make-rslave / fd = open_tree(AT_FDCWD, "/mnt", OPEN_TREE_CLONE | AT_RECURSIVE) move_mount(fd, "", AT_FDCWD, "/mnt/a", MOVE_MOUNT_BENEATH)
grep /mnt /proc/self/mountinfo
775 355 ... /mnt ... master:646 777 775 ... /mnt/a ... master:646 776 777 ... /mnt/a ... master:647
778 777 ... /mnt/a/a ... master:647
The now attached tree (777) is now mounted beneath the container's copy of /mnt/a. That's also where the host mount sits (as seen from the host mount namespace). So the propagated copy (776) of the host's mount is on top of its root and the copy of that (778) is inside it. Now the host runs:
umount /mnt/a
and it succeeds. The moved tree tree and the copy inside of it are gone from the container. Now only the propagated copy is left and it got reparented to where it was before:
grep /mnt /proc/self/mountinfo
775 355 ... /mnt ... master:646
776 775 ... /mnt/a ...
But the file descriptor still refers to the moved tree. So a synchronous umount detached a mount that is still in use.
Teach propagate_mount_busy() the same checks that propagate_umount() does. It now checks for a single victim mount without children for which it can assume that MNT_LOCKED is cleared on every copy like propagate_umount() does. The copies form chains. IOW, when a copy itself receives propagation from the victim's parent then the mount at the same mountpoint inside that copy is a copy as well. Whether a mount receives propagation from the victim's can simply be checked by walking its masters. Walk each chain once from its top so we are sure that nested copies stay linear. Check every reference once of every copy that gets unmounted.
--- fs/pnode.c | 125 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 93 insertions(+), 32 deletions(-)
fs/pnode.c +93 -32
@@ -331,21 +331,6 @@ int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp,return ret; } -static struct mount *find_topper (struct mount *mnt) -{ -/* If there is exactly one mount covering mnt completely return it. */ -struct mount *child; - -if (!list_is_singular (&mnt->mnt_mounts)) -return NULL ; - - child = list_first_entry(&mnt->mnt_mounts, struct mount, mnt_child); -if (child->mnt_mountpoint != mnt->mnt.mnt_root) -return NULL ; - -return child; -} -/* * return true if the refcount is greater than count */
@@ -394,20 +379,103 @@ bool propagation_would_overmount(const struct mount *from,return false; } +/* Does @m receive propagation from @parent? */ +static bool receives_from (struct mount *m,struct mount *parent) +{ +if (m == parent) +return false; +for (; m; m = m->mnt_master) +if (m == parent ||peers (m, parent)) +return true; +return false; +} + +/* +* Does @m receive propagation from the victim's parent as well? If so, then +* the mount at the victim's mountpoint inside of @m is a umount candidate as +* well. So it's the next candidate in the chain. Otherwise the chain ends at +* @m. +*/ +static struct mount *next_candidate (struct mount *m,struct mount *victim) +{ +if (!receives_from (m, victim->mnt_parent)) +return NULL ; +return __lookup_mnt (&m->mnt, victim->mnt_mountpoint); +} + +/* +* Would propagate_umount() pull out a mount of the chain of candidates that +* starts at @c, and does that mount have references beyond its own? +* +* This mirrors how trim_one(), trim_ancestors() and handle_locked() handle a +* synchronous umount: +* +* - single victim +* - without children +* - with MNT_LOCKED already cleared on every candidate by propagate_mount_unlock() +* +* A copy of the victim gets unmounted when each of its children is +* the next candidate in the chain or its overmount, unless the next +* unmount candidate is not its overmount and some unmount candidate further +* down has a child outside the chain. Keep this in sync with +* Documentation/filesystems/propagate_umount.txt. +*/ +static bool chain_busy (struct mount *c,struct mount *victim) +{ +struct mount *m, *n, *next, *deepest =NULL ; +bool above; + +/* the deepest candidate with a child outside the chain */ +for (m = c; m; m = next) { + next =next_candidate (m, victim); +list_for_each_entry (n, &m->mnt_mounts, mnt_child) { +if (n != next && n != victim) { + deepest = m; +break ; + } + } + } + + above = deepest !=NULL ;/* @deepest is at or below @m */ +for (m = c; m; m = next) { +bool goes = true; +int count =1 ; + + next =next_candidate (m, victim); +list_for_each_entry (n, &m->mnt_mounts, mnt_child) { +if (n != next && n->mnt_mountpoint != m->mnt.mnt_root && + n != victim) { + goes = false; +break ; + } + count++; + } +if (goes && next && next->mnt_mountpoint != m->mnt.mnt_root && + above && m != deepest) + goes = false; +if (m == deepest) + above = false; +if (goes &&do_refcount_check (m, count)) +return true; + } +return false; +} +/* * check if the mount 'mnt' can be unmounted successfully. * @mnt: the mount to be checked for unmount * NOTE: unmounting 'mnt' would naturally propagate to all * other mounts its parent propagates to. -* Check if any of these mounts that **do not have submounts** -* have more references than 'refcnt'. If so return busy. +* Check if any of the mounts that propagate_umount() would pull out +* along with it have more references than their own. If so return busy. * * vfsmount lock must be held for write */ int propagate_mount_busy (struct mount *mnt,int refcnt) { -struct mount *m, *child, *topper;struct mount *parent = mnt->mnt_parent; +struct dentry *mp = mnt->mnt_mountpoint; +struct mount *m;if (mnt == parent)return do_refcount_check (mnt, refcnt);
@@ -420,23 +488,16 @@ int propagate_mount_busy(struct mount *mnt, int refcnt)if (!list_empty (&mnt->mnt_mounts) ||do_refcount_check (mnt, refcnt))return 1 ; +/* the candidates are the mounts at @mp below the receivers */ for (m =propagation_next (parent, parent); m; - m =propagation_next (m, parent)) { -int count =1 ; - child =__lookup_mnt (&m->mnt, mnt->mnt_mountpoint); -if (!child) -continue ; + m =propagation_next (m, parent)) { +struct mount *c =__lookup_mnt (&m->mnt, mp); -/* Is there exactly one mount on the child that covers -* it completely whose reference should be ignored? -*/ - topper =find_topper (child); -if (topper) - count +=1 ; -else if (!list_empty (&child->mnt_mounts)) +/* each chain once, from its top: skip receivers that are candidates */ +if (!c || (mnt_has_parent (m) && m->mnt_mountpoint == mp && +receives_from (m->mnt_parent, parent)))continue ; - -if (do_refcount_check (child, count)) +if (chain_busy (c, mnt))return 1 ; }return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 535/1536 netfs: Fix missing alloc tagging of direct mempool allocations
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hao Ge <[email protected]>
[ Upstream commit b78b728e21c32ec4c330b299f657fb1eb02dffc2 ]
Commit 1d78d56c43ef ("netfs: Fix folio_queue ENOMEM in writeback by adding a mempool") added a mempool for the folio_queues and made the request, subrequest and folio_queue allocations distinguish between writeback and everything else. Writeback is part of memory reclaim and must not fail due to ENOMEM, so it allocates under GFP_NOFS through mempool_alloc(), which may dip into the pool's reserve and, if that runs empty, wait for elements to be returned. The GFP_KERNEL paths, which can return -ENOMEM to their callers, invoke the pool's ->alloc() callback directly instead.
The direct call, however, skips the alloc_hooks() wrapper that the mempool_alloc() macro provides. The pool callbacks, mempool_alloc_slab() and mempool_kmalloc(), call kmem_cache_alloc_noprof() and kmalloc_noprof() and rely on current->alloc_tag having been set by the caller. With CONFIG_MEM_ALLOC_PROFILING_DEBUG=y this leads to
current->alloc_tag not set
WARNING: ./include/linux/alloc_tag.h:161 at __alloc_tagging_slab_alloc_hook alloc_tag was not set
WARNING: ./include/linux/alloc_tag.h:166 at __alloc_tagging_slab_free_hook
at allocation and free time respectively, as reported when reading files on a CIFS mount. The allocations are also missing from /proc/allocinfo.
Wrap the direct ->alloc() invocations in alloc_hooks() with a new mempool_alloc_noreserve() helper in include/linux/mempool.h, next to the other alloc_hooks()-wrapped macros such as mempool_alloc(). The GFP_KERNEL paths keep their failable allocation semantics, they just get tagged now.
--- fs/netfs/objects.c | 4 ++-- fs/netfs/rolling_buffer.c | 2 +- include/linux/mempool.h | 7 +++++++ 3 files changed, 10 insertions(+), 3 deletions(-)
fs/netfs/objects.c +2 -2
@@ -32,7 +32,7 @@ struct netfs_io_request *netfs_alloc_request(struct address_space *mapping, rreq =mempool_alloc (mempool, gfp); }else { - rreq = mempool->alloc (gfp, mempool->pool_data); + rreq =mempool_alloc_noreserve (mempool, gfp);if (!rreq)return ERR_PTR (-ENOMEM ); }
@@ -189,7 +189,7 @@ struct netfs_io_subrequest *netfs_alloc_subrequest(struct netfs_io_request *rreq/* The write-side callers don't handle failure, so only reads may fail. */ if (rreq->gfp ==GFP_KERNEL && rreq->origin <=NETFS_DIO_READ ) - subreq = mempool->alloc (rreq->gfp, mempool->pool_data); + subreq =mempool_alloc_noreserve (mempool, rreq->gfp);else subreq =mempool_alloc (mempool, rreq->gfp);if (!subreq)
fs/netfs/rolling_buffer.c +1 -1
@@ -29,7 +29,7 @@ struct folio_queue *netfs_folioq_alloc(unsigned int rreq_id, gfp_t gfp,struct folio_queue *fq;if (gfp ==GFP_KERNEL ) - fq = netfs_folioq_pool.alloc (gfp, netfs_folioq_pool.pool_data); + fq =mempool_alloc_noreserve (&netfs_folioq_pool, gfp);else fq =mempool_alloc (&netfs_folioq_pool, gfp);if (fq) {
include/linux/mempool.h +7 -0
@@ -67,6 +67,13 @@ extern void *mempool_alloc_noprof(mempool_t *pool, gfp_t gfp_mask) __malloc;#define mempool_alloc (...) \ alloc_hooks(mempool_alloc_noprof(__VA_ARGS__)) +/* +* Allocate a new element without dipping into the pool's reserves or +* waiting. Returns NULL on failure. +*/ +#define mempool_alloc_noreserve (_pool, _gfp) \ + alloc_hooks((_pool)->alloc(_gfp, (_pool)->pool_data)) +extern void *mempool_alloc_preallocated (mempool_t *pool) __malloc;extern void mempool_free (void *element,mempool_t *pool);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 536/1536 KVM: SVM: Preserve TLB control (i.e. pending TLB flush) on failed VMRUN
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit 60d93c27859fb3ec5b5a689e24de303f166477d0 ]
Don't reset the VMCB's TLB control back to "do nothing" on a failed VMRUN, as empirical testing shows that the CPU performs the requested TLB flush if and only if VMRUN is successful, i.e. clearing TLB control on a failed VMRUN effectively drops a TLB flush.
Explicitly track the need to flush all ASIDs on a per-CPU basis, as the ASID reuse condition is tied to the pCPU, not to the vCPU. As a bonus, this also obviates the need to avoid clobbering FLUSH_ALL_ASID with TLB_CONTROL_FLUSH_ASID, e.g. in svm_flush_tlb_asid().
Deliberately don't bother saving/restoring the "old" tlb_ctl on failure, in quotes because it's not exactly the old tlb_ctl, it's the tlb_ctl from after pre_svm_run(), but before updating tlb_ctl for flush_all_asids. If VMRUN fails and TLB_CONTROL_FLUSH_ALL_ASID is forced, then the next successful run of the VMCB *may* unnecessarily flush all ASIDs, which strictly speaking could result in noisy neighbor issues. However, the fact that new_asid() is already guest-triggerable, because of KVM's flawed behavior of clearing the ASID on emulated INIT, means that a guest can already trigger a flush of all ASIDs at roughly the same rate. And once KVM stops clobbering the ASID on emulated INIT, *or* assigns a static ASID to each vCPU, this flaw goes away.
Message-ID: <[email protected]>
--- arch/x86/kvm/svm/svm.c | 14 +++++++++++--- arch/x86/kvm/svm/svm.h | 1 + 2 files changed, 12 insertions(+), 3 deletions(-)
arch/x86/kvm/svm/svm.c +11 -3
@@ -2032,8 +2032,7 @@ static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)if (sd->next_asid > sd->max_asid) { ++sd->asid_generation; sd->next_asid = sd->min_asid; - svm->vmcb->control.tlb_ctl =TLB_CONTROL_FLUSH_ALL_ASID ; -vmcb_mark_dirty (svm->vmcb,VMCB_ASID ); + sd->flush_all_asids = true; } svm->current_vmcb->asid_generation = sd->asid_generation;
@@ -4380,6 +4379,11 @@ static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu, u64 run_flags) svm->vmcb->control.asid = svm->asid;vmcb_mark_dirty (svm->vmcb,VMCB_ASID ); } +if (this_cpu_ptr (&svm_data)->flush_all_asids) { + svm->vmcb->control.tlb_ctl =TLB_CONTROL_FLUSH_ALL_ASID ; +vmcb_mark_dirty (svm->vmcb,VMCB_ASID ); + } + svm->vmcb->save.cr2 = vcpu->arch.cr2;svm_hv_update_vp_id (svm->vmcb, vcpu);
@@ -4460,7 +4464,11 @@ static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu, u64 run_flags) svm->nested.nested_run_pending =0 ; } - svm->vmcb->control.tlb_ctl =TLB_CONTROL_DO_NOTHING ; +if (svm->vmcb->control.exit_code !=SVM_EXIT_ERR ) { +this_cpu_ptr (&svm_data)->flush_all_asids = false; + svm->vmcb->control.tlb_ctl =TLB_CONTROL_DO_NOTHING ; + } +vmcb_mark_all_clean (svm->vmcb);/* if exit due to PF check for async PF */
arch/x86/kvm/svm/svm.h +1 -0
@@ -341,6 +341,7 @@ struct svm_cpu_data {u32 next_asid;u32 min_asid; +bool flush_all_asids;bool bp_spec_reduce_set;struct vmcb *save_area;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 537/1536 KVM: SVM: Update control fields on #VMEXIT if and only if VMRUN succeeded
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit e27fc915c8f575ab5630e27d97465c2077d4b9d1 ]
Leave control.erap_ctl and control.clean as-is in the VMCS if VMRUN fails, because as per AMD:
there's no explicit architectural guarantee about the behavior in the presence of VMRUN failures. So the best thing to do would be to assume that if VMRUN fails, the actions requested in the control fields may not have been performed.
Message-ID: <[email protected]>
--- arch/x86/kvm/svm/svm.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/x86/kvm/svm/svm.c +2 -2
@@ -4467,9 +4467,9 @@ static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu, u64 run_flags)if (svm->vmcb->control.exit_code !=SVM_EXIT_ERR ) {this_cpu_ptr (&svm_data)->flush_all_asids = false; svm->vmcb->control.tlb_ctl =TLB_CONTROL_DO_NOTHING ; - } -vmcb_mark_all_clean (svm->vmcb); +vmcb_mark_all_clean (svm->vmcb); + }/* if exit due to PF check for async PF */ if (svm->vmcb->control.exit_code ==SVM_EXIT_EXCP_BASE +PF_VECTOR )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 538/1536 ALSA: hda/realtek: Fix silent speaker on Higole F9B
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yu-Hsiang Tseng <[email protected]>
[ Upstream commit 2a8ee6897302ca12ff39e8eb180503956797c60c ]
The Higole F9B is an Alder Lake-N mini PC with a 7" touchscreen and an ALC269VC codec (subsystem ID 0x10ec111e). Its DMI strings are all "Default string", so the SSID is the only way to identify it.
The internal speaker is silent out of the box. The generic parser assigns DAC 0x03 to the speaker pin 0x14 and DAC 0x02 to the headphone pin 0x15, but the speaker only reproduces what DAC 0x02 plays, whatever its connection selection says. Checked one path at a time, only the gain of DAC 0x02 and the mute of pin 0x14 change what comes out of the speaker. User space only knows the path it was told the speaker uses, so selecting the speaker turns the path that actually reaches it all the way down.
Route both 0x14 and 0x15 through mixer 0x0c (DAC 0x02), which is what ALC290_FIXUP_MONO_SPEAKERS already does. Tested on the device: the speaker plays.
--- sound/pci/hda/patch_realtek.c | 1 + 1 file changed, 1 insertion(+)
sound/pci/hda/patch_realtek.c +1 -0
@@ -11408,6 +11408,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {SND_PCI_QUIRK (0x10cf ,0x1757 ,"Lifebook E752" ,ALC269_FIXUP_LIFEBOOK_HP_PIN ),SND_PCI_QUIRK (0x10cf ,0x1845 ,"Lifebook U904" ,ALC269_FIXUP_LIFEBOOK_EXTMIC ),SND_PCI_QUIRK (0x10ec ,0x10f2 ,"Intel Reference board" ,ALC700_FIXUP_INTEL_REFERENCE ), +SND_PCI_QUIRK (0x10ec ,0x111e ,"Higole F9B" ,ALC290_FIXUP_MONO_SPEAKERS ),SND_PCI_QUIRK (0x10ec ,0x118c ,"Medion EE4254 MD62100" ,ALC256_FIXUP_MEDION_HEADSET_NO_PRESENCE ),SND_PCI_QUIRK (0x10ec ,0x119e ,"Positivo SU C1400" ,ALC269_FIXUP_ASPIRE_HEADSET_MIC ), SND_PCI_QUIRK(0x10ec, 0x11bc, "VAIO VJFE-IL", ALC269_FIXUP_LIMIT_INT_MIC_BOOST),
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 539/1536 smb: client: clear post-EOF pagecache when extending a file via truncate
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
[ Upstream commit 35024595f641e790e24609f3f046e1667e3b280a ]
cifs_setsize() relied on pagecache_isize_extended() to zero the tail of the folio straddling the old EOF, but that helper is a no-op on CIFS (i_blkbits is 14), so data dirtied past EOF through an mmap survived and became visible once the file was extended.
Use netfs_clear_stale_post_isize() instead, called after i_size is updated since cifs_setsize() callers hold i_rwsem exclusively for the whole resize. truncate_pagecache() is then called as in truncate_setsize(): a no-op on extend, and it drops the pagecache beyond the new EOF on shrink.
Also thread old_size as an explicit parameter through cifs_setsize() and cifs_resize_file_locked(), captured by each caller before its own resize RPC. This closes a race where a concurrent stat() could adopt the RPC's already-updated server size via is_size_safe_to_change() before cifs_setsize() reads old_size itself.
--- fs/smb/client/cifsfs.h | 5 +++-- fs/smb/client/inode.c | 21 ++++++++++++++------- fs/smb/client/smb2ops.c | 8 +++++--- 3 files changed, 22 insertions(+), 12 deletions(-)
fs/smb/client/cifsfs.h +3 -2
@@ -134,8 +134,9 @@ extern ssize_t cifs_file_copychunk_range(unsigned int xid, size_t len, unsigned int flags);extern long cifs_ioctl (struct file *filep,unsigned int cmd,unsigned long arg); -extern void cifs_setsize (struct inode *inode,loff_t offset); -extern void cifs_resize_file_locked (struct inode *inode,loff_t offset); +extern void cifs_setsize (struct inode *inode,loff_t old_size,loff_t offset); +extern void cifs_resize_file_locked (struct inode *inode,loff_t old_size, +loff_t offset);extern int cifs_truncate_page (struct address_space *mapping,loff_t from);struct smb3_fs_context ;
fs/smb/client/inode.c +14 -7
@@ -2961,32 +2961,38 @@ int cifs_truncate_page(struct address_space *mapping, loff_t from)return rc; } -void cifs_setsize (struct inode *inode,loff_t offset) +void cifs_setsize (struct inode *inode,loff_t old_size,loff_t offset) {struct cifsInodeInfo *cifs_i =CIFS_I (inode); -loff_t old_size;spin_lock (&inode->i_lock); - old_size =i_size_read (inode);i_size_write (inode, offset);spin_unlock (&inode->i_lock);/* Cached inode must be refreshed on truncate */ cifs_i->time =0 ; + +/* +* Zero the tail of the folio straddling the old EOF so data dirtied +* past EOF through an mmap isn't exposed. truncate_pagecache() then +* drops any pagecache beyond the new EOF, as in truncate_setsize(). +*/ if (offset > old_size) -pagecache_isize_extended (inode, old_size, offset); +netfs_clear_stale_post_isize (inode, old_size, offset); +truncate_pagecache (inode, offset);netfs_wait_for_outstanding_io (inode); } -void cifs_resize_file_locked (struct inode *inode,loff_t offset) +void cifs_resize_file_locked (struct inode *inode,loff_t old_size, +loff_t offset) {struct fscache_cookie *cookie =cifs_inode_cookie (inode);lockdep_assert_held_write (&inode->i_rwsem);netfs_resize_file (netfs_inode (inode), offset, true); -cifs_setsize (inode, offset); +cifs_setsize (inode, old_size, offset);if (!cookie)return ;
@@ -3004,6 +3010,7 @@ cifs_set_file_size(struct inode *inode, struct iattr *attrs,struct cifsFileInfo *open_file;struct cifsInodeInfo *cifsInode =CIFS_I (inode);struct cifs_sb_info *cifs_sb =CIFS_SB (inode->i_sb); +loff_t old_size =i_size_read (inode);struct tcon_link *tlink =NULL ;struct cifs_tcon *tcon =NULL ;struct TCP_Server_Info *server;
@@ -3059,7 +3066,7 @@ cifs_set_file_size(struct inode *inode, struct iattr *attrs, set_size_out:if (rc ==0 ) { -cifs_resize_file_locked (inode, attrs->ia_size); +cifs_resize_file_locked (inode, old_size, attrs->ia_size);/* * i_blocks is not related to (i_size / i_blksize), but instead * 512 byte (2**9) size is required for calculating num blocks.
fs/smb/client/smb2ops.c +5 -3
@@ -2275,6 +2275,7 @@ smb2_duplicate_extents(const unsigned int xid,struct inode *inode;struct duplicate_extents_to_file dup_ext_buf;struct cifs_tcon *tcon =tlink_tcon (trgtfile->tlink); +loff_t old_size;/* server fileays advertise duplicate extent support with this flag */ if ((le32_to_cpu(tcon->fsAttrInfo.Attributes) &
@@ -2292,7 +2293,8 @@ smb2_duplicate_extents(const unsigned int xid, trgtfile->fid.volatile_fid, tcon->tid, tcon->ses->Suid, src_off, dest_off, len); inode =d_inode (trgtfile->dentry); -if (i_size_read (inode) < dest_off + len) { + old_size =i_size_read (inode); +if (old_size < dest_off + len) { rc =smb2_set_file_size (xid, tcon, trgtfile, dest_off + len, false);if (rc) goto duplicate_extents_out;
@@ -2304,7 +2306,7 @@ smb2_duplicate_extents(const unsigned int xid,* size will be queried on next revalidate, but it is important * to make sure that file's cached size is updated immediately */ -cifs_resize_file_locked (inode, dest_off + len); +cifs_resize_file_locked (inode, old_size, dest_off + len); } rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid, trgtfile->fid.volatile_fid,
@@ -3831,7 +3833,7 @@ static long smb3_simple_falloc(struct file *file, struct cifs_tcon *tcon, rc =SMB2_set_eof (xid, tcon, cfile->fid.persistent_fid, cfile->fid.volatile_fid, cfile->pid, new_eof);if (rc ==0 ) { -cifs_resize_file_locked (inode, new_eof); +cifs_resize_file_locked (inode, old_eof, new_eof);cifs_truncate_page (inode->i_mapping, inode->i_size);truncate_setsize (inode, new_eof); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 540/1536 smb: client: discard post-EOF pagecache when extending a file via clone range
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
[ Upstream commit 4721587f96cb8de8164f3fd203093a0875560999 ]
cifs_remap_file_range() discarded the pagecache only for the folios overlapping the destination region, so when a clone extends the file the folio straddling the old EOF - which may hold data dirtied past EOF through an mmap - was never dropped and became visible as file content once the file was extended.
Start the discard at the smaller of fstart and the old EOF. i_size is still old here, so nothing past the old EOF is flushed to the server.
--- fs/smb/client/cifsfs.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
fs/smb/client/cifsfs.c +8 -2
@@ -1378,9 +1378,15 @@ static loff_t cifs_remap_file_range(struct file *src_file, loff_t off, target_cifsi->netfs.zero_point = fend +1 ; old_size = target_cifsi->netfs.remote_i_size; -/* Discard all the folios that overlap the destination region. */ +/* +* Discard all the folios that overlap the destination region. Start at +* the old EOF when extending so the folio straddling it, which may hold +* data written past EOF through an mmap, is dropped too. +*/ cifs_dbg (FYI ,"about to discard pages %llx-%llx\n" , fstart, fend); -truncate_inode_pages_range (&target_inode->i_data, fstart, fend); +truncate_inode_pages_range (&target_inode->i_data, +min_t (loff_t, fstart,i_size_read (target_inode)), + fend);fscache_invalidate (cifs_inode_cookie (target_inode),NULL ,i_size_read (target_inode),0 );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 541/1536 smb: client: flush and commit data before querying allocated ranges
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
[ Upstream commit aa994489bd835547c191827acc460192e147032d ]
The mode 0 / FALLOC_FL_KEEP_SIZE fallocate emulation for small interior ranges in smb3_simple_fallocate_range() issues FSCTL_QUERY_ALLOCATED_RANGES and zero-fills any sub-range the server reports as an unallocated hole, to force block allocation without changing file contents.
This is unsafe against Windows servers. Per the Win32 documentation, FSCTL_QUERY_ALLOCATED_RANGES only reports ranges that *may* contain nonzero data and is explicitly not coherent with recently written data:
"a call to FSCTL_QUERY_ALLOCATED_RANGES [after writing to a network
file] would not necessarily return a correct list of allocated regions. To ensure coherency [...] flush the data to the file"
fsx (generic/363) reproduces the resulting corruption against Windows Server 2022: a range is written, an uncached read returns the data, yet the next FSCTL_QUERY_ALLOCATED_RANGES on that range reports it as a whole hole, so the emulation overwrites live data with zeroes. A network trace confirmed the WRITE, the READ returning data and the query returning an empty range list within microseconds. Samba does not exhibit this; its query is coherent with the written data.
Write back the dirty pages, drain any outstanding I/O and issue an SMB2 FLUSH to force the server to commit the data before querying the allocated ranges, so the query reflects the data actually present.
With this, generic/363 passes against both Windows Server 2022 and Samba over 100000 fsx operations.
--- fs/smb/client/smb2ops.c | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-)
fs/smb/client/smb2ops.c +28 -8
@@ -3683,6 +3683,7 @@ static int smb3_simple_fallocate_range(unsigned int xid,struct cifsFileInfo *cfile, loff_t off, loff_t len) { + struct inode *inode = d_inode(cfile->dentry);struct file_allocated_range_buffer in_data, *out_data =NULL , *tmp_data;u32 out_data_len;char *buf =NULL ;
@@ -3690,6 +3691,24 @@ static int smb3_simple_fallocate_range(unsigned int xid,loff_t l;int rc; +filemap_invalidate_lock (inode->i_mapping); + +/* +* Flush and commit the data to the server, otherwise +* FSCTL_QUERY_ALLOCATED_RANGES might report recently written data as +* unallocated holes on Windows Servers, and the loop below would +* then zero-fill them and corrupt the file. +*/ + rc =filemap_write_and_wait_range (inode->i_mapping, off, + off + len -1 ); +if (rc) + goto out_unlock; +netfs_wait_for_outstanding_io (inode); + rc =SMB2_flush (xid, tcon, cfile->fid.persistent_fid, + cfile->fid.volatile_fid); +if (rc) + goto out_unlock; + in_data.file_offset =cpu_to_le64 (off); in_data.length =cpu_to_le64 (len); rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
@@ -3699,12 +3718,12 @@ static int smb3_simple_fallocate_range(unsigned int xid,1024 *sizeof (struct file_allocated_range_buffer ), (char **)&out_data, &out_data_len);if (rc) - goto out; + goto out_unlock; buf =kvzalloc (min_t (loff_t, len,SMB2_MAX_BUFFER_SIZE ),GFP_KERNEL );if (buf ==NULL ) { rc = -ENOMEM ; - goto out; + goto out_unlock; } tmp_data = out_data;
@@ -3715,12 +3734,12 @@ static int smb3_simple_fallocate_range(unsigned int xid,if (out_data_len ==0 ) { rc =smb3_simple_fallocate_write_range (xid, tcon, cfile, off, len, buf); - goto out; + goto out_unlock; }if (out_data_len <sizeof (struct file_allocated_range_buffer )) { rc = -EINVAL ; - goto out; + goto out_unlock; } range_start =le64_to_cpu (tmp_data->file_offset);
@@ -3728,7 +3747,7 @@ static int smb3_simple_fallocate_range(unsigned int xid,if (check_add_overflow (range_start, range_len, &range_end) || range_end >S64_MAX ) { rc = -EINVAL ; - goto out; + goto out_unlock; }if (off < range_start) {
@@ -3743,11 +3762,11 @@ static int smb3_simple_fallocate_range(unsigned int xid, rc =smb3_simple_fallocate_write_range (xid, tcon, cfile, off, l, buf);if (rc) - goto out; + goto out_unlock; off = off + l; len = len - l;if (len ==0 ) - goto out; + goto out_unlock; }/* * We are at a section of allocated data, just skip forward
@@ -3766,7 +3785,8 @@ static int smb3_simple_fallocate_range(unsigned int xid, out_data_len -=sizeof (struct file_allocated_range_buffer ); } - out: + out_unlock: +filemap_invalidate_unlock (inode->i_mapping);kfree (out_data);kvfree (buf);return rc;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 542/1536 smb: client: flush dirty data before zeroing a range
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
[ Upstream commit 8f8d32c1044f70e46e87550e039a15ff20a4b21c ]
smb3_zero_range() emulates FALLOC_FL_ZERO_RANGE by invalidating the page cache over the target range with truncate_pagecache_range() and then issuing FSCTL_SET_ZERO_DATA to the server.
Dirty data was only flushed conditionally, when the range reached or extended EOF. For a purely interior zero range that does not reach EOF, no flush happened, so a dirty folio overlapping the range could be written back to the server after the FSCTL and refill the range that was just zeroed with stale data.
Fix this by unconditionally flushing and waiting for dirty data in the range before invalidating the page cache and issuing FSCTL_SET_ZERO_DATA, exactly as was done for smb3_punch_hole() in commit d7d2adcd022b ("smb/client: flush dirty data before punching a hole"); the two paths are structurally identical here.
This is observed as generic/363 randomly reading stale data where a zeroed range is expected against Windows Server.
--- fs/smb/client/smb2ops.c | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-)
fs/smb/client/smb2ops.c +5 -9
@@ -3486,8 +3486,7 @@ static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,struct inode *inode =file_inode (file);struct cifsInodeInfo *cifsi =CIFS_I (inode);struct cifsFileInfo *cfile = file->private_data; -struct netfs_inode *ictx =netfs_inode (inode); -unsigned long long i_size, new_size, remote_size; +unsigned long long i_size, new_size;long rc;unsigned int xid;
@@ -3506,14 +3505,11 @@ static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,filemap_invalidate_lock (inode->i_mapping); i_size =i_size_read (inode); - remote_size = ictx->remote_i_size; -if (offset + len >= remote_size && offset < i_size) { -unsigned long long top =umin (offset + len, i_size); - rc =filemap_write_and_wait_range (inode->i_mapping, offset, top -1 ); -if (rc <0 ) - goto zero_range_exit; - } + rc =filemap_write_and_wait_range (inode->i_mapping, offset, + offset + len -1 ); +if (rc <0 ) + goto zero_range_exit;/* * We zero the range through ioctl, so we need remove the page caches
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 543/1536 smb: client: drain and invalidate before server-side copy/clone
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
[ Upstream commit c9b1194e8ec99d95db25db45edd2fbf690f043ab ]
cifs_file_copychunk_range() and the clone (FICLONE) path of cifs_remap_file_range() do not serialise the destination page cache against the server-side copy the way the other server-side range operations (smb3_zero_range(), smb3_punch_hole(), smb3_collapse_range() and smb3_insert_range()) do.
cifs_file_copychunk_range() invalidates the destination range with filemap_invalidate_inode(), which takes and drops the mapping's invalidate_lock internally, so the lock is no longer held when the copychunk ioctl is issued. It also never drains in-flight netfs I/O on the target. The clone path never takes the invalidate_lock at all (only i_rwsem), uses a bare truncate_inode_pages_range() and likewise does not drain outstanding I/O.
As a result an asynchronous destination writeback can complete after the server-side copy/clone has run and reinstate stale data over the region just written by the server, corrupting the file. This is the same class of corruption as commit d7d2adcd022b ("smb/client: flush dirty data before punching a hole") and has been seen randomly in generic/363 against Windows Server.
Fix both paths to follow the established ordering: hold the target mapping's invalidate_lock across the flush and invalidation of the destination and the server ioctl, and call netfs_wait_for_outstanding_io() on the target to drain in-flight writes before the ioctl is issued. Only the target inode's invalidate_lock is required, as the source is merely flushed and not invalidated; i_rwsem (already held via lock_two_nondirectories()) is acquired before the invalidate_lock, matching the VFS lock ordering. Since filemap_invalidate_inode() takes that same lock internally, replace it with its own unmap/flush/invalidate steps instead of calling it, and return early on a zero-length copy to avoid a range underflow.
--- fs/smb/client/cifsfs.c | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-)
fs/smb/client/cifsfs.c +26 -5
@@ -1326,6 +1326,7 @@ static loff_t cifs_remap_file_range(struct file *src_file, loff_t off,* server could even support copy of range where source = target */ lock_two_nondirectories (target_inode, src_inode); +filemap_invalidate_lock (target_inode->i_mapping);if (len ==0 ) {loff_t src_size =i_size_read (src_inode);
@@ -1387,6 +1388,7 @@ static loff_t cifs_remap_file_range(struct file *src_file, loff_t off,truncate_inode_pages_range (&target_inode->i_data,min_t (loff_t, fstart,i_size_read (target_inode)), fend); +netfs_wait_for_outstanding_io (target_inode);fscache_invalidate (cifs_inode_cookie (target_inode),NULL ,i_size_read (target_inode),0 );
@@ -1422,6 +1424,7 @@ static loff_t cifs_remap_file_range(struct file *src_file, loff_t off,that target is updated on the server */ CIFS_I (target_inode)->time =0 ; unlock: +filemap_invalidate_unlock (target_inode->i_mapping);/* although unlocking in the reverse order from locking is not strictly necessary here it is a little cleaner to be consistent */ unlock_two_nondirectories (src_inode, target_inode);
@@ -1445,6 +1448,9 @@ ssize_t cifs_file_copychunk_range(unsigned int xid,struct cifs_tcon *target_tcon;ssize_t rc; +if (len ==0 ) +return 0 ; +cifs_dbg (FYI ,"copychunk range\n" );if (!src_file->private_data || !dst_file->private_data) {
@@ -1474,6 +1480,7 @@ ssize_t cifs_file_copychunk_range(unsigned int xid,* server could even support copy of range where source = target */ lock_two_nondirectories (target_inode, src_inode); +filemap_invalidate_lock (target_inode->i_mapping);cifs_dbg (FYI ,"about to flush pages\n" );
@@ -1499,11 +1506,24 @@ ssize_t cifs_file_copychunk_range(unsigned int xid,* Start at the old EOF when extending so the folio straddling it, which * may hold data written past EOF through an mmap, is dropped too. */ - rc =filemap_invalidate_inode (target_inode, true, -min (destoff,i_size_read (target_inode)), - destoff + len -1 ); -if (rc) - goto unlock; +if (target_inode->i_mapping->nrpages) { +loff_t fstart =min (destoff,i_size_read (target_inode)); +loff_t fend = destoff + len -1 ; + +unmap_mapping_pages (target_inode->i_mapping, + fstart >>PAGE_SHIFT , + (fend >>PAGE_SHIFT ) - + (fstart >>PAGE_SHIFT ) +1 , + false); + rc =filemap_write_and_wait_range (target_inode->i_mapping, + fstart, fend); +if (rc) + goto unlock; +invalidate_inode_pages2_range (target_inode->i_mapping, + fstart >>PAGE_SHIFT , + fend >>PAGE_SHIFT ); + } +netfs_wait_for_outstanding_io (target_inode);fscache_invalidate (cifs_inode_cookie (target_inode),NULL ,i_size_read (target_inode),0 );
@@ -1531,6 +1551,7 @@ ssize_t cifs_file_copychunk_range(unsigned int xid,CIFS_I (target_inode)->time =0 ; unlock: +filemap_invalidate_unlock (target_inode->i_mapping);/* although unlocking in the reverse order from locking is not * strictly necessary here it is a little cleaner to be consistent */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 544/1536 smb: client: only require read lease for size-extending zero range
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
[ Upstream commit fafc68cccf8a00ed0a1f47c1413a3f16ce4dcdfa ]
smb3_zero_range() refuses any FALLOC_FL_ZERO_RANGE that clears FALLOC_FL_KEEP_SIZE with -EOPNOTSUPP whenever the inode is not read caching:
/* if file not oplocked can't be sure whether asking to extend size */ rc = -EOPNOTSUPP; if (keep_size == false && !CIFS_CACHE_READ(cifsi)) goto zero_range_exit;
The read lease is only needed to trust the cached i_size when deciding whether the range extends the file. When it is not held, the size can instead be fetched from the server, which is authoritative, rather than refusing the request outright: query the server's end of file and take the larger of it and the cached size for the interior-vs-extend decision. The larger of the two is used because the server's end of file reflects another client's growth while the cached size reflects this client's own writes that may not have reached the server yet; using the server size alone would wrongly shrink the file when the range flush above left an extending write unwritten.
The query isn't lease-protected either, so its result is only trusted to confirm the range is interior, never to justify extending: if it still shows the range going past EOF, refuse with -EOPNOTSUPP instead of calling SMB2_set_eof(), which could otherwise shrink the file if another client extended it further between the query and the call. For the same reason, take the larger of the already-computed i_size and a fresh i_size_read(inode) right before that call, instead of relying on either
alone: the local variable carries the query's result, which is never written back to the inode, while a concurrent write on this client can still extend the cached i_size during the flush, the query, or the zero-data round trip that happen in between.
Rejecting interior ranges is observed as generic/363 randomly failing against Windows Server with
do_zero_range: fallocate: Operation not supported
fsx issues an interior, non-KEEP_SIZE zero range while the inode is transiently not read caching: the server had just downgraded the file's lease from RWH to RH after breaking the write caching, and the ensuing handle reopen/revalidation left CIFS_CACHE_READ momentarily clear. The range sat well within the server's end of file, so no extend was needed, yet the range was refused and fsx aborted. This keeps the emulation correct even when a genuine lease break from another client leaves the inode without read caching -- the case the -EOPNOTSUPP guard turned into a hard failure. The extra round trip only happens on the no-lease path; the common cached case is unchanged.
--- fs/smb/client/smb2ops.c | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-)
fs/smb/client/smb2ops.c +27 -6
@@ -3478,6 +3478,21 @@ static long smb3_zero_data(struct file *file, struct cifs_tcon *tcon, 0, NULL, NULL); } +static long query_server_eof (const unsigned int xid, +struct cifs_tcon *tcon, +struct cifsFileInfo *cfile, +unsigned long long *eof) +{ +struct smb2_file_all_info file_inf = {}; +long rc; + + rc =SMB2_query_info (xid, tcon, cfile->fid.persistent_fid, + cfile->fid.volatile_fid, &file_inf); +if (!rc) + *eof =le64_to_cpu (file_inf.EndOfFile); +return rc; +} +static long smb3_zero_range (struct file *file,struct cifs_tcon *tcon,unsigned long long offset,unsigned long long len,bool keep_size)
@@ -3486,7 +3501,7 @@ static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,struct inode *inode =file_inode (file);struct cifsInodeInfo *cifsi =CIFS_I (inode);struct cifsFileInfo *cfile = file->private_data; -unsigned long long i_size, new_size; +unsigned long long i_size, new_size, remote_i_size;long rc;unsigned int xid;
@@ -3521,10 +3536,16 @@ static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,truncate_pagecache_range (inode,min (offset, i_size), offset + len -1 );netfs_wait_for_outstanding_io (inode); -/* if file not oplocked can't be sure whether asking to extend size */ - rc = -EOPNOTSUPP ; -if (keep_size == false && !CIFS_CACHE_READ (cifsi)) - goto zero_range_exit; +if (!keep_size && !CIFS_CACHE_READ (cifsi)) { + rc =query_server_eof (xid, tcon, cfile, &remote_i_size); +if (rc) + goto zero_range_exit; + i_size =max (i_size, remote_i_size); +if (i_size < new_size) { + rc = -EOPNOTSUPP ; + goto zero_range_exit; + } + }fscache_invalidate (cifs_inode_cookie (inode),NULL ,i_size_read (inode),0 );
@@ -3536,7 +3557,7 @@ static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,/* * do we also need to change the size of the file? */ -if (keep_size == false && (unsigned long long )i_size_read (inode) < new_size) { +if (!keep_size &&umax (i_size,i_size_read (inode)) < new_size) { rc =SMB2_set_eof (xid, tcon, cfile->fid.persistent_fid, cfile->fid.volatile_fid, cfile->pid, new_size);if (rc >=0 ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 545/1536 smb: client: require stable pages for signed connections
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
[ Upstream commit 53c5c2c1095eb21e214811fec16cd75f89d72ee2 ]
When signing, cifs computes the SMB signature over the pagecache folios in place and then hands those same folios to the socket. If a buffered write mutates a folio while a write subrequest is still in flight, the signature no longer matches the data that follows it, the server rejects the write with STATUS_ACCESS_DENIED (-EACCES), and the error is latched in the mapping, so the next fsync()/fallocate() returns -EIO.
Mark the mapping for stable writes so netfs_perform_write() waits for writeback to complete before modifying an in-flight folio. This is only needed when the connection is signed.
--- fs/smb/client/inode.c | 2 ++ 1 file changed, 2 insertions(+)
fs/smb/client/inode.c +2 -0
@@ -87,6 +87,8 @@ static void cifs_set_ops(struct inode *inode)else inode->i_data.a_ops = &cifs_addr_ops;mapping_set_large_folios (inode->i_mapping); +if (cifs_sb_master_tcon (cifs_sb)->ses->server->sign) +mapping_set_stable_writes (inode->i_mapping);break ;case S_IFDIR :if (IS_AUTOMOUNT (inode)) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 546/1536 dm-integrity: validate the superblock on resume
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
[ Upstream commit fc79aeb86a2c244c1f1894e2d8f2966fe2b60fa2 ]
dm_integrity_resume() re-reads the superblock from the device so that it picks up the flags and the recalculate position. It performs no validation on the result, while the constructor validates the superblock it reads and sizes all the in-memory structures according to it. The user may modify the superblock on the underlying device while the dm-integrity device is suspended, so that the two no longer agree.
In particular, access_journal_data() shifts the journal entry index by ic->sb->log2_sectors_per_block, while ic->journal_section_sectors and the journal page list were computed with the value that was present at constructor time. Increasing log2_sectors_per_block makes the index run past the end of the journal, and dm-integrity then writes 512 bytes through lowmem_page_address(NULL).
Snapshot the validated superblock in the constructor and refuse to resume if any of the fields that describe the on-disk geometry changed.
--- drivers/md/dm-integrity.c | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+)
drivers/md/dm-integrity.c +50 -0
@@ -179,6 +179,7 @@ struct dm_integrity_c {struct dm_bufio_client *bufio;struct workqueue_struct *metadata_wq;struct superblock *sb; +struct superblock *sb_copy;unsigned int journal_pages;unsigned int n_bitmap_blocks;
@@ -3706,6 +3707,35 @@ static void dm_integrity_postsuspend(struct dm_target *ti) ic->journal_uptodate = true; } +/* +* The superblock is re-read from the device on every resume, so that we pick +* up the flags and the recalculate position. The geometry described by the +* superblock must not change though - the in-memory structures (and the +* journal in particular) were sized according to the superblock that was +* validated in the constructor. Reject a superblock that was modified behind +* our back. +* +* Only the fields that the driver never rewrites may be tested here. In +* particular, "version" is recalculated by sb_set_version on every superblock +* write and it depends on SB_FLAG_RECALCULATING and SB_FLAG_DIRTY_BITMAP, and +* SB_FLAG_DISCARD_KEYED may be set by dm_integrity_resume itself. +*/ +static bool superblock_changed (struct dm_integrity_c *ic) +{ +const __le32 immutable_flags =cpu_to_le32 (SB_FLAG_HAVE_JOURNAL_MAC | +SB_FLAG_FIXED_PADDING | +SB_FLAG_FIXED_HMAC | +SB_FLAG_INLINE ); + +return memcmp (ic->sb->magic, ic->sb_copy->magic,sizeof (ic->sb->magic)) !=0 || + ic->sb->log2_interleave_sectors != ic->sb_copy->log2_interleave_sectors || + ic->sb->integrity_tag_size != ic->sb_copy->integrity_tag_size || + ic->sb->journal_sections != ic->sb_copy->journal_sections || + ic->sb->log2_sectors_per_block != ic->sb_copy->log2_sectors_per_block || + ((ic->sb->flags ^ ic->sb_copy->flags) & immutable_flags) !=0 || +memcmp (ic->sb->salt, ic->sb_copy->salt,SALT_SIZE ) !=0 ; +} +static void dm_integrity_resume (struct dm_target *ti) {struct dm_integrity_c *ic = ti->private;
@@ -3724,6 +3754,18 @@ static void dm_integrity_resume(struct dm_target *ti)if (r)dm_integrity_io_error (ic,"reading superblock" , r); +if (unlikely (superblock_changed (ic))) { +/* +* Restore the superblock that we validated in the constructor, +* so that the rest of the driver doesn't operate on values +* that don't match the in-memory structures. +*/ +memcpy (ic->sb, ic->sb_copy,sizeof (struct superblock )); +DMERR ("The superblock was changed while the device was suspended" ); +dm_integrity_io_error (ic,"superblock check" , -EINVAL ); + goto skip_writes; + } +if (ic->mode =='R' ) goto skip_writes;
@@ -5236,6 +5278,13 @@ static int dm_integrity_ctr(struct dm_target *ti, unsigned int argc, char **argv ic->just_formatted = true; } + ic->sb_copy =kmemdup (ic->sb,sizeof (struct superblock ),GFP_KERNEL ); +if (!ic->sb_copy) { + ti->error ="Cannot allocate superblock copy" ; + r = -ENOMEM ; + goto bad; + } +if (!ic->meta_dev && ic->mode !='I' ) { r =dm_set_target_max_io_len (ti,1U << ic->sb->log2_interleave_sectors);if (r)
@@ -5332,6 +5381,7 @@ static void dm_integrity_dtr(struct dm_target *ti)kvfree (ic->journal_tree);if (ic->sb)free_pages_exact (ic->sb,SB_SECTORS <<SECTOR_SHIFT ); +kfree (ic->sb_copy);if (ic->internal_shash)crypto_free_shash (ic->internal_shash);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 547/1536 namespace: check a recursive bind mount for mount namespace loops
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit c640a01a78e42302879006ed7b7d5a9a943ba815 ]
do_loopback() refuses to bind mount the file of a mount namespace that is as old as the caller's or older because a mount namespace that holds a mount of its own file, or of an ancestor's, would cause a cycle. But it only checks the dentry the bind mount starts from. With MS_REC everything below it is copied and do_loopback() passes CL_COPY_MNT_NS_FILE so mount namespace files below the source are copied.
That's fine for a source in the caller's own mount namespace. Every mount namespace file in there passed the same check when it was bind-mounted. It isn't fine for a source in another mount namespace. may_copy_tree() accepts a bind mount of any nsfs or pidfs file no matter what mount namespace it lives in so that /proc/<pid>/ns/<ns> and pidfds can be bind mounted. If we create a bind-mount stack of mount namespaces file descriptors the kernel will copy them irrespective of their ancestoral relationship to the mount namespace in question:
151 146 0:7 net:[4026531833] /tmp/nrc/y rw - nsfs nsfs rw 152 151 0:7 mnt:[4026532293] /tmp/nrc/y rw - nsfs nsfs rw
Mount 152 is a mount of the mount namespace file of mount namespace 4026532293 inside mount namespace 4026532293. That namespace and every mount in it are leaked... All it takes is a process in an older mount namespace that stacks the file and repeating it leaks without limit:
after control: Shmem: 380 kB
child: mount(/proc/self/fd/6, MS_BIND|MS_REC): ok
after cycle: Shmem: 65916 kB
do_move_mount() runs check_for_nsfs_mounts() over a detached tree for exactly that reason. Do the same for the copy before it is grafted.
--- fs/namespace.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
fs/namespace.c +7 -1
@@ -2805,6 +2805,8 @@ static int do_change_type(struct path *path, int ms_flags)return err; } +static bool check_for_nsfs_mounts (struct mount *subtree); +static struct mount *__do_loopback (struct path *old_path,int recurse) {struct mount *mnt =ERR_PTR (-EINVAL ), *old =real_mount (old_path->mnt);
@@ -2872,7 +2874,11 @@ static int do_loopback(struct path *path, const char *old_name, goto out2; } - err =graft_tree (mnt, parent, mp); +/* the copy may carry mount namespace files from below the source */ +if (recurse && !check_for_nsfs_mounts (mnt)) + err = -EINVAL ; +else + err =graft_tree (mnt, parent, mp);if (err) {lock_mount_hash ();umount_tree (mnt,UMOUNT_SYNC );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 548/1536 drm/amd/display: Fix fast updates on DCE 6.x
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Timur Kristóf <[email protected]>
[ Upstream commit 88427119e1f039c8cdffd63726c136a986ef519f ]
DCE6 should use legacy fast updates, just like all DCE8 - DCN2. Set that flag for DCE 6.0, 6.1 and 6.4 (all DCE6 versions).
Technically DCE6 should have been included when the fast update code was refactored, but it just happened to work until now.
A recent commit "Attach only plane updates that actually changed" has exposed this issue because with that commit, DC accidentally took the new fast update code path for DCE6 as well, which caused it to boot into a black screen with a flip done timeout.
This fix should be backported to all kernel versions that have "Refactor fast update to use new HWSS build sequence", but this patch won't apply cleanly to older kernels due to another refactor in "Remove dc param from check_update".
--- drivers/gpu/drm/amd/display/dc/dce60/dce60_resource.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/gpu/drm/amd/display/dc/dce60/dce60_resource.c +7 -0
@@ -438,6 +438,10 @@ static const struct dce_abm_mask abm_mask = { ABM_MASK_SH_LIST_DCE110(_MASK) }; +static const struct dc_debug_options debug_defaults = { + .enable_legacy_fast_update = true, +}; +#define CTX ctx#define REG (reg) mm ## reg
@@ -973,6 +977,7 @@ static bool dce60_construct( dc->caps.max_cursor_size =64 ; dc->caps.dual_link_dvi = true; dc->caps.extended_aux_timeout_support = false; + dc->debug = debug_defaults;/************************************************* * Create resources *
@@ -1170,6 +1175,7 @@ static bool dce61_construct( dc->caps.i2c_speed_in_khz =40 ; dc->caps.max_cursor_size =64 ; dc->caps.is_apu = true; + dc->debug = debug_defaults;/************************************************* * Create resources *
@@ -1367,6 +1373,7 @@ static bool dce64_construct( dc->caps.max_downscale_ratio =200 ; dc->caps.i2c_speed_in_khz =40 ; dc->caps.max_cursor_size =64 ; + dc->debug = debug_defaults;/************************************************* * Create resources *
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 549/1536 drm/amdgpu: remove gart_window_lock usage from gmc v12
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pierre-Eric Pelloux-Prayer <[email protected]>
[ Upstream commit c79cf5a7d903a16459846b4296fc3cd988837c54 ]
This lock was part of the SDMA workaround originally implemented in gmc_v10_0_flush_gpu_tlb (a70cb2176f7ef6f moved it to amdgpu_gmc_flush_gpu_tlb).
This means this lock is useless and be safely dropped.
Stable-dep-of: 0bfb1bfc82e8 ("drm/amdgpu/gmc12: properly pass flush_type to gmc_v12_0_flush_vm_hub()")
--- drivers/gpu/drm/amd/amdgpu/gmc_v12_0.c | 2 -- 1 file changed, 2 deletions(-)
drivers/gpu/drm/amd/amdgpu/gmc_v12_0.c +0 -2
@@ -339,9 +339,7 @@ static void gmc_v12_0_flush_gpu_tlb(struct amdgpu_device *adev, uint32_t vmid,return ; } -mutex_lock (&adev->mman.gtt_window_lock);gmc_v12_0_flush_vm_hub (adev, vmid, vmhub,0 ); -mutex_unlock (&adev->mman.gtt_window_lock);return ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 550/1536 drm/amdgpu/gmc12: properly pass flush_type to gmc_v12_0_flush_vm_hub()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alex Deucher <[email protected]>
[ Upstream commit 0bfb1bfc82e8fa386d4fad1caa5812b6afafa626 ]
In gmc_v12_0_flush_gpu_tlb(), flush_type was not properly passed to gmc_v12_0_flush_vm_hub(). This only affected the MMIO path. In most cases the flush would go through MES.
--- drivers/gpu/drm/amd/amdgpu/gmc_v12_0.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/amd/amdgpu/gmc_v12_0.c +1 -1
@@ -339,7 +339,7 @@ static void gmc_v12_0_flush_gpu_tlb(struct amdgpu_device *adev, uint32_t vmid,return ; } -gmc_v12_0_flush_vm_hub (adev, vmid, vmhub,0 ); +gmc_v12_0_flush_vm_hub (adev, vmid, vmhub, flush_type);return ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 551/1536 drm/amdgpu: skip the noirq suspend reset for a switcheroo-parked GPU
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Theo Andersen Carton <[email protected]>
[ Upstream commit eadb85cca111152bd334b861fb53747ab851d13a ]
amdgpu_pmops_suspend_noirq() resets the ASIC unconditionally. When the GPU has been parked by vga_switcheroo it has neither power nor a PCIe link, so the reset cannot reach it: pci_set_power_state() reports the device as inaccessible and amdgpu_asic_reset() returns -EINVAL. A failure there aborts the entire noirq suspend phase, and with it the system suspend, so the machine cannot sleep at all while the GPU is switched off.
amdgpu_device_prepare(), amdgpu_device_suspend() and amdgpu_device_resume() all bail out early on DRM_SWITCH_POWER_OFF. This callback was added later, for an unrelated reason, and did not inherit the check. nouveau guards every one of its PM callbacks the same way.
Bail out the same way here. On a single-GPU system switch_power_state is never DRM_SWITCH_POWER_OFF, so this is a no-op there.
Found on a MacBookPro11,5, where the Radeon is powered down through apple-gmux so that the internal panel can be driven by the iGPU instead. Every suspend failed in amdgpu_pmops_suspend_noirq() while the card was off; with this check a full S3 cycle completes.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c | 9 +++++++++ 1 file changed, 9 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c +9 -0
@@ -2623,6 +2623,15 @@ static int amdgpu_pmops_suspend_noirq(struct device *dev)struct amdgpu_device *adev =drm_to_adev (drm_dev); adev->suspend_complete = true; + +/* +* A GPU parked by vga_switcheroo has no power and no PCIe link, so the +* ASIC reset below would fail and abort the whole noirq suspend phase. +* Bail out like amdgpu_device_prepare/suspend/resume() already do. +*/ +if (drm_dev->switch_power_state ==DRM_SWITCH_POWER_OFF ) +return 0 ; +if (amdgpu_acpi_should_gpu_reset (adev))return amdgpu_asic_reset (adev);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 552/1536 namespace: never expire a locked mount
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit f78ddcc872248c7aa1d7e904928441a0be4c6d5d ]
Locked mounts are special. They protect the underlying files and directories from being revealed. do_umount() refuses to unmount locked mounts but shrink_submounts() doesn't.
A shrinkable mount can become locked once the owner of a user namespace puts it beneath a locked mount with MOVE_MOUNT_BENEATH. The locked property now moves to the mount at the bottom making it possible to unmount the top mount.
So umount() of an unlocked ancestor now expires the bottom mount first and the covered directory is revealed:
move_mount(c -> x/hidden, MOVE_MOUNT_BENEATH) = 0
the cover after the lock moved: umount2(x/hidden) = 0 the holder of the lock: umount2(x/hidden) = EINVAL the root of the copy, busy: umount2(x) = EBUSY
reads x/hidden/secret: "covered-by-root"
So leave a locked mount alone as it dies together with its parent. A plain umount() of an unlocked mount with a locked one below it is EBUSY from now on. It's the same for any other locked child. A lazy umount still takes the whole tree.
mark_mounts_for_expiry() never sees a locked mount. lock_mnt_tree() leaves a mount on an expiry list alone and nothing else puts a locked one on such a list. Add an assert for this.
--- fs/namespace.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/namespace.c +4 -1
@@ -3710,6 +3710,8 @@ void mark_mounts_for_expiry(struct list_head *mounts)* cleared by mntput()) */ list_for_each_entry_safe (mnt, next, mounts, mnt_expire) { +/* lock_mnt_tree() leaves expirable mounts alone */ +WARN_ON_ONCE (IS_MNT_LOCKED (mnt));if (!xchg (&mnt->mnt_expiry_mark,1 ) ||propagate_mount_busy (mnt,1 ))continue ;
@@ -3738,7 +3740,8 @@ EXPORT_SYMBOL_GPL(mark_mounts_for_expiry);*/ static bool shrink_submount (struct mount *mnt) { -if (propagate_mount_busy (mnt,1 )) +/* not the kernel's to remove either */ +if (IS_MNT_LOCKED (mnt) ||propagate_mount_busy (mnt,1 ))return false;touch_mnt_namespace (mnt->mnt_ns);umount_tree (mnt,UMOUNT_PROPAGATE |UMOUNT_SYNC );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 553/1536 regulator: of: fill in supply names in of_regulator_bulk_get_all()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexey Charkov <[email protected]>
[ Upstream commit e2151c29cec73f6cc70abf1c7cbc7b9b202489f5 ]
of_regulator_bulk_get_all() returns an array it allocated itself, and fills in only the consumer of each entry. Every other way of getting a bulk array has the supply name set, because the caller provides it, and the core expects it to be there: regulator_bulk_enable() prints it when a supply fails to enable, so a caller that hands such an array to it dereferences uninitialised memory on that path.
Copy each name into the array's own allocation, right behind the entries, so that it shares the array's lifetime and callers still have nothing extra to free. That also retires the fixed 64 byte stack buffer the names were assembled in, which is_supply_name() never bounded the copy against.
--- drivers/regulator/of_regulator.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-)
drivers/regulator/of_regulator.c +17 -9
@@ -872,15 +872,15 @@ static int is_supply_name(const char *name)int of_regulator_bulk_get_all (struct device *dev,struct device_node *np,struct regulator_bulk_data **consumers) { -int num_consumers =0 ; +int num_consumers =0 , names_len =0 ;struct regulator *tmp;struct regulator_bulk_data *_consumers =NULL ;struct property *prop; +char *names;int i, n =0 , ret; -char name[64 ];/* -* first pass: get numbers of xxx-supply +* first pass: get numbers of xxx-supply and the room their names take * second pass: fill consumers */ restart:
@@ -890,16 +890,19 @@ int of_regulator_bulk_get_all(struct device *dev, struct device_node *np,continue ;if (!_consumers) { num_consumers++; + names_len += i +1 ;continue ; }else { -memcpy (name, prop->name, i); - name[i] ='\0' ; - tmp =regulator_get (dev, name); +memcpy (names, prop->name, i); + names[i] ='\0' ; + tmp =regulator_get (dev, names);if (IS_ERR (tmp)) { ret =PTR_ERR (tmp); goto error; } + _consumers[n].supply = names; _consumers[n].consumer = tmp; + names += i +1 ; n++;continue ; }
@@ -910,11 +913,16 @@ int of_regulator_bulk_get_all(struct device *dev, struct device_node *np, }if (num_consumers ==0 )return 0 ; - _consumers =kmalloc_array (num_consumers, -sizeof (struct regulator_bulk_data ), -GFP_KERNEL ); +/* +* The supply names are kept in the same allocation as the array, so +* that they share its lifetime and the caller has nothing extra to +* free. +*/ + _consumers =kzalloc (size_add (size_mul (num_consumers,sizeof (*_consumers)), + names_len),GFP_KERNEL );if (!_consumers)return -ENOMEM ; + names = (char *)(_consumers + num_consumers); goto restart; error:
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 554/1536 net: team: free skb when broadcast has no txable port
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
[ Upstream commit 489114c9ecae44e523361a4b3e610ee5ebd9189c ]
bc_transmit() sends the original skb through the last txable port. When no port is txable, it returns false without consuming the skb, but team_xmit() still returns NETDEV_TX_OK. AF_PACKET sends then retain the skb and its socket write-memory charge.
A TX-enabled, link-down port keeps the broadcast transmit op installed. Carrier can stay up through a second link-up, TX-disabled port or be forced on by userspace. Free the original skb on the no-port path while leaving the existing drop accounting intact.
Discovered by Sashiko during review of previous commit.
--- drivers/net/team/team_mode_broadcast.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/net/team/team_mode_broadcast.c +2 -0
@@ -37,6 +37,8 @@ static bool bc_transmit(struct team *team, struct sk_buff *skb) ret = !team_dev_queue_xmit (team, last, skb);if (!sum_ret) sum_ret = ret; + }else { +dev_kfree_skb_any (skb); }return sum_ret; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 555/1536 Input: xpad - add support for 8BitDo Pro 2 Wired Controller for Xbox
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bihaan Sen <[email protected]>
[ Upstream commit 41363c27b8509bd4efcba244803edac9ba25d1b5 ]
The 8BitDo Pro 2 Wired Controller for Xbox is already matched by the vendor-wide XPAD_XBOXONE_VENDOR(0x2dc8) entry, but a later hardware revision reports product ID 0x201e, which has no entry in the xpad_device table. The device therefore binds and functions but is exposed to userspace as "Generic X-Box pad".
Add the VID/PID pair so the controller is named correctly, and set MAP_SHARE_BUTTON to expose the share button as KEY_RECORD.
--- drivers/input/joystick/xpad.c | 1 + 1 file changed, 1 insertion(+)
drivers/input/joystick/xpad.c +1 -0
@@ -406,6 +406,7 @@ static const struct xpad_device { { 0x294b, 0x3404, "Snakebyte GAMEPAD RGB X", 0, XTYPE_XBOXONE }, { 0x2993, 0x2001, "TECNO Pocket Go", 0, XTYPE_XBOX360 }, { 0x2dc8, 0x2000, "8BitDo Pro 2 Wired Controller fox Xbox", 0, XTYPE_XBOXONE }, + { 0x2dc8, 0x201e, "8BitDo Pro 2 Wired Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2dc8, 0x3106, "8BitDo Ultimate Wireless / Pro 2 Wired Controller", 0, XTYPE_XBOX360 }, { 0x2dc8, 0x3109, "8BitDo Ultimate Wireless Bluetooth", 0, XTYPE_XBOX360 }, { 0x2dc8, 0x310a, "8BitDo Ultimate 2C Wireless Controller", 0, XTYPE_XBOX360 },
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 556/1536 drm/i915/dmc: Add sanity check for DMC load address
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dibin Moolakadan Subrahmanian <[email protected]>
[ Upstream commit 7dedc5bb11f95e96fe80757c924d8d9aa7327759 ]
For DMC firmware header version 3, the firmware load address is stored in dmc_info->start_mmioaddr and later used by dmc_load_program().
Unlike the MMIO address table, the firmware load address is not validated. Add a sanity check to ensure it is within the valid range.
BSpec: 69671, 68378
--- drivers/gpu/drm/i915/display/intel_dmc.c | 55 +++++++++++++++++++ drivers/gpu/drm/i915/display/intel_dmc_regs.h | 12 ++++ 2 files changed, 67 insertions(+)
drivers/gpu/drm/i915/display/intel_dmc.c +55 -0
@@ -699,6 +699,55 @@ static void dmc_set_fw_offset(struct intel_dmc *dmc, } } +/* +* Check if the load address is within the valid range for the given DMC ID. +*/ +static bool dmc_load_addr_sanity_check (struct intel_dmc *dmc, +u32 start_addr,u32 payload_size, +int header_ver,enum intel_dmc_id dmc_id) +{ +u32 start_range, end_range, end_addr; + +if (header_ver !=3 ) +return true; + +switch (dmc_id) { +case DMC_FW_MAIN : + start_range =DMC_MAIN_PROGRAM_BASE_START ; + end_range =DMC_MAIN_PROGRAM_BASE_END ; +break ; +case DMC_FW_PIPEA : + start_range =DMC_PIPEA_PROGRAM_BASE_START ; + end_range =DMC_PIPEA_PROGRAM_BASE_END ; +break ; +case DMC_FW_PIPEB : + start_range =DMC_PIPEB_PROGRAM_BASE_START ; + end_range =DMC_PIPEB_PROGRAM_BASE_END ; +break ; +case DMC_FW_PIPEC : + start_range =DMC_PIPEC_PROGRAM_BASE_START ; + end_range =DMC_PIPEC_PROGRAM_BASE_END ; +break ; +case DMC_FW_PIPED : + start_range =DMC_PIPED_PROGRAM_BASE_START ; + end_range =DMC_PIPED_PROGRAM_BASE_END ; +break ; +default : +MISSING_CASE (dmc_id); +return false; + } + +if (payload_size ==0 ) + end_addr = start_addr; +else if (check_add_overflow (start_addr, payload_size -1 , &end_addr)) +return false; + +if (start_addr < start_range || end_addr > end_range) +return false; + +return true; +} +static bool dmc_mmio_addr_sanity_check (struct intel_dmc *dmc,const u32 *mmioaddr,u32 mmio_count,int header_ver,enum intel_dmc_id dmc_id)
@@ -842,6 +891,12 @@ static u32 parse_dmc_fw_header(struct intel_dmc *dmc,return 0 ; } +if (!dmc_load_addr_sanity_check (dmc, start_mmioaddr, payload_size, + dmc_header->header_ver, dmc_id)) { +drm_err (&i915->drm,"DMC %d: firmware has wrong load address\n" , dmc_id); +return 0 ; + } + dmc_info->payload =kmalloc (payload_size,GFP_KERNEL );if (!dmc_info->payload)return 0 ;
drivers/gpu/drm/i915/display/intel_dmc_regs.h +12 -0
@@ -87,6 +87,18 @@#define TGL_PIPE_MMIO_END (dmc_id) _PICK_EVEN(((dmc_id) - 1), _TGL_PIPEA_MMIO_END,\ _TGL_PIPEB_MMIO_END) +/* For DMC header version v3*/ +#define DMC_MAIN_PROGRAM_BASE_START 0x80000 +#define DMC_MAIN_PROGRAM_BASE_END 0x86fff +#define DMC_PIPEA_PROGRAM_BASE_START 0x90000 +#define DMC_PIPEA_PROGRAM_BASE_END 0x96fff +#define DMC_PIPEB_PROGRAM_BASE_START 0x98000 +#define DMC_PIPEB_PROGRAM_BASE_END 0x9efff +#define DMC_PIPEC_PROGRAM_BASE_START 0x52000 +#define DMC_PIPEC_PROGRAM_BASE_END 0x53fff +#define DMC_PIPED_PROGRAM_BASE_START 0x59000 +#define DMC_PIPED_PROGRAM_BASE_END 0x5afff +#define SKL_DMC_DC3_DC5_COUNT _MMIO(0x80030)#define SKL_DMC_DC5_DC6_COUNT _MMIO(0x8002C)#define BXT_DMC_DC3_DC5_COUNT _MMIO(0x80038)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 557/1536 ipc: create_ipc_ns: drop mqueue mount on sysctl setup failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vlad Kulikov <[email protected]>
[ Upstream commit 7229d74e5e8c1f140529d405c88d4493e37ce4e3 ]
If setup_mq_sysctls(ns) fails after mq_init_ns(ns) succeeds, the error path skipped releasing the internal kernel mqueue mount kept in ns->mq_mnt. That leaves the vfsmount/superblock referenced until final namespace teardown, i.e. a resource leak on this rare failure edge.
Unwind it by calling mntput(ns->mq_mnt) before dropping user_ns and freeing the IPC namespace. This mirrors the normal ordering used in free_ipc_ns().
Stable-dep-of: f0e48172a59e ("ipc: drop the mqueue mount with kern_unmount() on setup failure")
--- ipc/namespace.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
ipc/namespace.c +5 -4
@@ -76,10 +76,10 @@ static struct ipc_namespace *create_ipc_ns(struct user_namespace *user_ns, err = -ENOMEM ;if (!setup_mq_sysctls (ns)) - goto fail_put; + goto fail_mq_mount;if (!setup_ipc_sysctls (ns)) - goto fail_mq; + goto fail_mq_sysctls; err =msg_init_ns (ns);if (err)
@@ -92,9 +92,10 @@ static struct ipc_namespace *create_ipc_ns(struct user_namespace *user_ns, fail_ipc:retire_ipc_sysctls (ns); -fail_mq: +fail_mq_sysctls:retire_mq_sysctls (ns); - +fail_mq_mount: +mntput (ns->mq_mnt); fail_put:put_user_ns (ns->user_ns);ns_free_inum (&ns->ns);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 558/1536 ipc: drop the mqueue mount with kern_unmount() on setup failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit f0e48172a59e517e613b73f73cc35f24fd123aeb ]
mq_init_ns() creates the mqueue mount with fc_mount_longterm(), so its ->mnt_ns is MNT_NS_INTERNAL. When setting up the mqueue or ipc sysctls or msg_init_ns() fails afterwards, create_ipc_ns() drops it with a plain mntput(). With ->mnt_ns set that takes the fast path of mntput_no_expire(). The count drops to zero and nothing ever kills the mount, so the mount and the mqueue superblock are leaked.
Commit dc55e35f9e81 ("ipc: Store mqueue sysctls in the ipc namespace") added the first failure path after mq_init_ns() and never dropped the mount. Commit 7229d74e5e8c ("ipc: create_ipc_ns: drop mqueue mount on sysctl setup failure") tried to fix that with a mntput() but that doesn't help for a long-term mount.
Use kern_unmount(). free_ipc() open-codes the same thing for a namespace that made it.
--- ipc/namespace.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
ipc/namespace.c +1 -1
@@ -95,7 +95,7 @@ static struct ipc_namespace *create_ipc_ns(struct user_namespace *user_ns, fail_mq_sysctls:retire_mq_sysctls (ns); fail_mq_mount: -mntput (ns->mq_mnt); +kern_unmount (ns->mq_mnt); fail_put:put_user_ns (ns->user_ns);ns_free_inum (&ns->ns);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 559/1536 ntfs3: free replaced mount options after a grace period
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 56c3824de56b5275c02ff6b6aa27ddbacfbb9b25 ]
ntfs_fs_reconfigure() replaces the old mount options with new mount options in sbi->options. The old mount options land in fs_context and are freed as soon as remount returns. With a pathwalk held up in ntfs_nls_to_utf16() between loading sbi->options and dereferencing it while a remount replaces them:
BUG: KASAN: slab-use-after-free in ntfs_nls_to_utf16+0x7ae/0x7c0 Read of size 8 at addr ff110001044fd448 by task walker/98 Call Trace: <TASK> ntfs_nls_to_utf16+0x7ae/0x7c0 ntfs_d_hash+0x22b/0x500 link_path_walk+0x11ad/0x1d30 path_lookupat+0x63/0xb00 filename_lookup+0x1f1/0x5b0 vfs_statx+0xd7/0x3b0 [...] Allocated by task 95: __kmalloc_node_track_caller_noprof+0x2a2/0x730 kmemdup_noprof+0x25/0x50 ntfs_fill_super+0x1e5/0x4550 [...] Freed by task 97: kfree+0x1db/0x5b0 put_fs_context+0x13c/0x7d0 path_mount+0x54a/0x2130 __x64_sys_mount+0x20c/0x270
That info is needed in rcu lookup in the dentry hash and dentry compary methods for ntfs3 and causes a UAF today. Delay freeing with an rcu grace period.
ntfs_nls_to_utf16() reads ->nls and ->ads once under rcu_read_lock() so the hooks pair with the release in ntfs_fs_reconfigure(). That also covers callers outside of rcu pathwalk such as ntfs_lookup(). They don't hold rcu_read_lock() themselves and wouldn't be protected by the grace period otherwise. Remount refuses to change the iocharset so ->nls stays valid after rcu_read_unlock().
--- fs/ntfs3/dir.c | 9 ++++++++- fs/ntfs3/ntfs_fs.h | 2 ++ fs/ntfs3/super.c | 16 +++++++++++++++- 3 files changed, 25 insertions(+), 2 deletions(-)
fs/ntfs3/dir.c +8 -1
@@ -185,11 +185,18 @@ int ntfs_nls_to_utf16(struct ntfs_sb_info *sbi, const u8 *name, u32 name_len, {int ret, slen;const u8 *end; -struct nls_table *nls = sbi->options->nls; +struct ntfs_mount_options *opts; +struct nls_table *nls;u16 *uname = uni->name;static_assert (sizeof (wchar_t) ==sizeof (u16)); +/* ntfs_fs_reconfigure() may replace the options, but not ->nls */ +rcu_read_lock (); + opts =READ_ONCE (sbi->options); + nls = opts->nls; +rcu_read_unlock (); +if (!nls) {/* utf8 -> utf16 */ ret =_utf8s_to_utf16s (name, name_len, endian, uname, max_ulen);
fs/ntfs3/ntfs_fs.h +2 -0
@@ -90,6 +90,8 @@ enum utf16_endian;struct ntfs_mount_options {char *nls_name;struct nls_table *nls; +/* ->d_hash() and ->d_compare() read the options in rcu pathwalk */ +struct rcu_head rcu;kuid_t fs_uid;kgid_t fs_gid;
fs/ntfs3/super.c +15 -1
@@ -242,6 +242,11 @@ static inline void put_mount_options(struct ntfs_mount_options *options)kfree (options); } +static void put_mount_options_rcu (struct rcu_head *head) +{ +put_mount_options (container_of(head ,struct ntfs_mount_options ,rcu )); +} +enum Opt { Opt_uid, Opt_gid,
@@ -408,6 +413,7 @@ static int ntfs_fs_reconfigure(struct fs_context *fc)struct super_block *sb = fc->root->d_sb;struct ntfs_sb_info *sbi = sb->s_fs_info;struct ntfs_mount_options *new_opts = fc->fs_private; +struct ntfs_mount_options *old_opts;int ro_rw;/* If ntfs3 is used as legacy ntfs enforce read-only mode. */
@@ -444,7 +450,15 @@ static int ntfs_fs_reconfigure(struct fs_context *fc) out:sync_filesystem (sb); -swap (sbi->options, fc->fs_private); + old_opts = sbi->options; +/* pairs with the READ_ONCE() in ntfs_nls_to_utf16() */ +smp_store_release (&sbi->options, new_opts); + fc->fs_private =NULL ; +/* +* ntfs_d_hash() and ntfs_d_compare() of a pathwalk in rcu mode may +* still read the old options through the sbi. +*/ +call_rcu (&old_opts->rcu, put_mount_options_rcu);return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 560/1536 tracing: Fix fully-qualified variable reference printing in histograms
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tom Zanussi <[email protected]>
[ Upstream commit 9236eebd138aa2753f7b30fc6cee7b7202841247 ]
The syntax for fully-qualified variable references in histograms is subsys.event.$var, which is parsed correctly, but not displayed correctly when printing a histogram spec. The current code puts the $ reference at the beginning of the fully-qualified variable name i.e. $subsys.event.var, which is incorrect.
Before:
trigger info: hist:keys=next_comm:vals=hitcount:wakeup_lat=common_timestamp.usecs-$sched.sched_wakeup.ts0: ...
After:
trigger info: hist:keys=next_comm:vals=hitcount:wakeup_lat=common_timestamp.usecs-sched.sched_wakeup.$ts0: ...
Stable-dep-of: a0777b9e5315 ("tracing: Fix NULL dereference when copying keys for a field variable")
--- kernel/trace/trace_events_hist.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
kernel/trace/trace_events_hist.c +10 -5
@@ -1342,9 +1342,12 @@ static const char *hist_field_name(struct hist_field *field, field->flags & HIST_FIELD_FL_VAR_REF) {if (field->system) {static char full_name[MAX_FILTER_STR_VAL ]; +static char *fmt;int len; - len =snprintf (full_name,sizeof (full_name),"%s.%s.%s" , + fmt = field->flags &HIST_FIELD_FL_VAR_REF ?"%s.%s.$%s" :"%s.%s.%s" ; + + len =snprintf (full_name,sizeof (full_name), fmt, field->system, field->event_name, field->name);if (len <sizeof (full_name))
@@ -1724,9 +1727,10 @@ static const char *get_hist_field_flags(struct hist_field *hist_field)static void expr_field_str (struct hist_field *field,char *expr) { -if (field->flags &HIST_FIELD_FL_VAR_REF ) -strcat (expr,"$" ); -else if (field->flags &HIST_FIELD_FL_CONST ) { +if (field->flags &HIST_FIELD_FL_VAR_REF ) { +if (!field->system) +strcat (expr,"$" ); + }else if (field->flags &HIST_FIELD_FL_CONST ) {char str[HIST_CONST_DIGITS_MAX ];snprintf (str,HIST_CONST_DIGITS_MAX ,"%llu" , field->constant);
@@ -6137,7 +6141,8 @@ static void hist_field_print(struct seq_file *m, struct hist_field *hist_field)else if (field_name) {if (hist_field->flags &HIST_FIELD_FL_VAR_REF || hist_field->flags &HIST_FIELD_FL_ALIAS ) -seq_putc (m,'$' ); +if (!hist_field->system) +seq_putc (m,'$' );seq_printf (m,"%s" , field_name); }else if (hist_field->flags &HIST_FIELD_FL_TIMESTAMP )seq_puts (m,"common_timestamp" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 561/1536 tracing: Use __free() for expr_str() buffer
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pengpeng Hou <[email protected]>
[ Upstream commit 988995c0552b6213b6bf16cea57258d4842c1488 ]
expr_str() allocates a temporary expression buffer and manually frees it on some error paths.
Convert the buffer to __free(kfree) and return it with return_ptr() on success. This keeps ownership handling separate from the later ERR_PTR() conversion and string-bound change.
Stable-dep-of: a0777b9e5315 ("tracing: Fix NULL dereference when copying keys for a field variable")
--- kernel/trace/trace_events_hist.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-)
kernel/trace/trace_events_hist.c +6 -8
@@ -1751,7 +1751,7 @@ static void expr_field_str(struct hist_field *field, char *expr)static char *expr_str (struct hist_field *field,unsigned int level) { -char *expr; + char *expr __free(kfree) = NULL;if (level >1 )return NULL ;
@@ -1762,7 +1762,7 @@ static char *expr_str(struct hist_field *field, unsigned int level)if (!field->operands[0 ]) {expr_field_str (field, expr); -return expr; +return_ptr (expr); }if (field->operator ==FIELD_OP_UNARY_MINUS ) {
@@ -1770,16 +1770,15 @@ static char *expr_str(struct hist_field *field, unsigned int level)strcat (expr,"-(" ); subexpr =expr_str (field->operands[0 ], ++level); -if (!subexpr) { -kfree (expr); +if (!subexpr)return NULL ; - } +strcat (expr, subexpr);strcat (expr,")" );kfree (subexpr); -return expr; +return_ptr (expr); }expr_field_str (field->operands[0 ], expr);
@@ -1798,13 +1797,12 @@ static char *expr_str(struct hist_field *field, unsigned int level)strcat (expr,"*" );break ;default : -kfree (expr);return NULL ; }expr_field_str (field->operands[1 ], expr); -return expr; +return_ptr (expr); }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 562/1536 tracing: Return ERR_PTR() from expr_str()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pengpeng Hou <[email protected]>
[ Upstream commit a5ca27e8ff1c10e949af7cfe474d6d1a08fb5601 ]
expr_str() currently reports all failure cases as NULL, so callers cannot distinguish invalid recursion depth from allocation failure or later string construction errors.
Return ERR_PTR()-encoded errors from expr_str() and make parse_unary() and parse_expr() propagate them. Clear expr->name before destroying the hist field so the error pointer is not freed as a string.
Stable-dep-of: 935601a4276f ("tracing: Bound histogram expression strings with seq_buf")
--- kernel/trace/trace_events_hist.c | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-)
kernel/trace/trace_events_hist.c +20 -5
@@ -1754,11 +1754,11 @@ static char *expr_str(struct hist_field *field, unsigned int level) char *expr __free(kfree) = NULL;if (level >1 ) -return NULL ; +return ERR_PTR (-EINVAL ); expr =kzalloc (MAX_FILTER_STR_VAL ,GFP_KERNEL );if (!expr) -return NULL ; +return ERR_PTR (-ENOMEM );if (!field->operands[0 ]) {expr_field_str (field, expr);
@@ -1770,8 +1770,8 @@ static char *expr_str(struct hist_field *field, unsigned int level)strcat (expr,"-(" ); subexpr =expr_str (field->operands[0 ], ++level); -if (!subexpr) -return NULL ; +if (IS_ERR (subexpr)) +return subexpr;strcat (expr, subexpr);strcat (expr,")" );
@@ -1797,7 +1797,7 @@ static char *expr_str(struct hist_field *field, unsigned int level)strcat (expr,"*" );break ;default : -return NULL ; +return ERR_PTR (-EINVAL ); }expr_field_str (field->operands[1 ], expr);
@@ -2603,6 +2603,11 @@ static struct hist_field *parse_unary(struct hist_trigger_data *hist_data, expr->is_signed = operand1->is_signed; expr->operator =FIELD_OP_UNARY_MINUS ; expr->name =expr_str (expr,0 ); +if (IS_ERR (expr->name)) { + ret =PTR_ERR (expr->name); + expr->name =NULL ; + goto free; + } expr->type =kstrdup_const (operand1->type,GFP_KERNEL );if (!expr->type) { ret = -ENOMEM ;
@@ -2815,6 +2820,11 @@ static struct hist_field *parse_expr(struct hist_trigger_data *hist_data,destroy_hist_field (operand1,0 ); expr->name =expr_str (expr,0 ); +if (IS_ERR (expr->name)) { + ret =PTR_ERR (expr->name); + expr->name =NULL ; + goto free_expr; + } }else {/* The operand sizes should be the same, so just pick one */ expr->size = operand1->size;
@@ -2828,6 +2838,11 @@ static struct hist_field *parse_expr(struct hist_trigger_data *hist_data, } expr->name =expr_str (expr,0 ); +if (IS_ERR (expr->name)) { + ret =PTR_ERR (expr->name); + expr->name =NULL ; + goto free_expr; + } }return expr;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 563/1536 tracing: Bound histogram expression strings with seq_buf
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pengpeng Hou <[email protected]>
[ Upstream commit 935601a4276f28105498609f7f98aa66e86e9c96 ]
expr_str() allocates a fixed MAX_FILTER_STR_VAL buffer and then builds expression names with a series of raw strcat() appends. Nested operands, constants, field flags, and generated field names can push the rendered string past that fixed limit before the name is attached to the hist field.
Build expression strings with seq_buf and return -E2BIG when the rendered name would exceed MAX_FILTER_STR_VAL. This keeps the existing tracing-side limit while replacing the raw append logic with bounded construction.
Stable-dep-of: a0777b9e5315 ("tracing: Fix NULL dereference when copying keys for a field variable")
--- kernel/trace/trace_events_hist.c | 57 ++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 24 deletions(-)
kernel/trace/trace_events_hist.c +33 -24
@@ -94,7 +94,6 @@ typedef u64 (*hist_field_fn_t) (struct hist_field *field,#define HIST_FIELD_OPERANDS_MAX 2#define HIST_FIELDS_MAX (TRACING_MAP_FIELDS_MAX + TRACING_MAP_VARS_MAX)#define HIST_ACTIONS_MAX 8 -#define HIST_CONST_DIGITS_MAX 21#define HIST_DIV_SHIFT 20/* For optimizing division by constants */ enum field_op_id {
@@ -1725,33 +1724,36 @@ static const char *get_hist_field_flags(struct hist_field *hist_field)return flags_str; } -static void expr_field_str (struct hist_field *field,char *expr) +static bool expr_field_str (struct hist_field *field,struct seq_buf *s) { +const char *field_name; +if (field->flags &HIST_FIELD_FL_VAR_REF ) {if (!field->system) -strcat (expr,"$" ); - }else if (field->flags &HIST_FIELD_FL_CONST ) { -char str[HIST_CONST_DIGITS_MAX ]; +seq_buf_putc (s,'$' ); + }else if (field->flags &HIST_FIELD_FL_CONST ) +seq_buf_printf (s,"%llu" , field->constant); -snprintf (str,HIST_CONST_DIGITS_MAX ,"%llu" , field->constant); -strcat (expr, str); - } + field_name =hist_field_name (field,0 ); +if (!field_name) +return false; -strcat (expr,hist_field_name (field,0 )); +seq_buf_puts (s, field_name);if (field->flags && !(field->flags &HIST_FIELD_FL_VAR_REF )) {const char *flags_str =get_hist_field_flags (field); -if (flags_str) { -strcat (expr,"." ); -strcat (expr, flags_str); - } +if (flags_str) +seq_buf_printf (s,".%s" , flags_str); } + +return !seq_buf_has_overflowed (s); }static char *expr_str (struct hist_field *field,unsigned int level) { char *expr __free(kfree) = NULL; +struct seq_buf s;if (level >1 )return ERR_PTR (-EINVAL );
@@ -1760,47 +1762,54 @@ static char *expr_str(struct hist_field *field, unsigned int level)if (!expr)return ERR_PTR (-ENOMEM ); +seq_buf_init (&s, expr,MAX_FILTER_STR_VAL ); +if (!field->operands[0 ]) { -expr_field_str (field, expr); +if (!expr_field_str (field, &s)) +return ERR_PTR (-E2BIG ); +return_ptr (expr); }if (field->operator ==FIELD_OP_UNARY_MINUS ) {char *subexpr; -strcat (expr,"-(" ); subexpr =expr_str (field->operands[0 ], ++level);if (IS_ERR (subexpr))return subexpr; -strcat (expr, subexpr); -strcat (expr,")" ); - +seq_buf_printf (&s,"-(%s)" , subexpr);kfree (subexpr); +if (seq_buf_has_overflowed (&s)) +return ERR_PTR (-E2BIG ); +return_ptr (expr); } -expr_field_str (field->operands[0 ], expr); +if (!expr_field_str (field->operands[0 ], &s)) +return ERR_PTR (-E2BIG );switch (field->operator) {case FIELD_OP_MINUS : -strcat (expr,"-" ); +seq_buf_putc (&s,'-' );break ;case FIELD_OP_PLUS : -strcat (expr,"+" ); +seq_buf_putc (&s,'+' );break ;case FIELD_OP_DIV : -strcat (expr,"/" ); +seq_buf_putc (&s,'/' );break ;case FIELD_OP_MULT : -strcat (expr,"*" ); +seq_buf_putc (&s,'*' );break ;default :return ERR_PTR (-EINVAL ); } -expr_field_str (field->operands[1 ], expr); +if (seq_buf_has_overflowed (&s) || + !expr_field_str (field->operands[1 ], &s)) +return ERR_PTR (-E2BIG );return_ptr (expr); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 564/1536 tracing: Fix NULL dereference when copying keys for a field variable
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Donggeun Yoo <[email protected]>
[ Upstream commit a0777b9e53157f1f6848a0fd0650f5465391ea81 ]
In event_hist_trigger_parse() where it needs to create actions like "onmatch", it calls:
event_hist_trigger_parse() {
create_actions() {
action_create() {
trace_action_create() {
trace_action_create_field_var() {
create_field_var_hist()Where create_field_var_hist() does a loop on the hist_data representing the keys. The issue is, if the keys uses one of the pseudo field types (like common_cpu), the hist_data field element will have NULL for its field member causing a NULL pointer dereference when accessing the key_field->field->name.
# echo 'hist:keys=common_cpu:ts0=common_timestamp.usecs' > \
events/sched/sched_waking/trigger
# echo 'my_synth u64 lat; int prio' > synthetic_events
# echo 'hist:keys=common_cpu:wakeup_lat=common_timestamp.usecs-$ts0:\
onmatch(sched.sched_waking).my_synth($wakeup_lat,prio)' > \
events/sched/sched_switch/triggerKASAN: null-ptr-deref in range [0x0000000000000010-0x0000000000000017] RIP: 0010:create_field_var_hist+0x771/0x1380 Call Trace: trace_action_create_field_var+0x360/0x600 trace_action_create+0x393/0xe80 event_hist_trigger_parse+0x3e47/0x69e0 trigger_process_regex+0x1a6/0x250 event_trigger_write+0xce/0x160
Instead of accessing it directly, use the proper handler expr_field_str() to get the name.
The three previous patches are prerequisites: without them a .buckets key and a common_stacktrace key each render into a command that cannot be parsed back.
--- kernel/trace/trace_events_hist.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/trace/trace_events_hist.c +1 -1
@@ -3075,7 +3075,7 @@ create_field_var_hist(struct hist_trigger_data *target_hist_data, key_field = hist_data->fields[i];if (!first)seq_buf_putc (&s,',' ); -seq_buf_puts (&s, key_field->field->name); +expr_field_str (key_field, &s); first = false; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 565/1536 drm/amdgpu/uvd3.1: Fix checking whether UVD firmware keyselect was already set
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Timur Kristóf <[email protected]>
[ Upstream commit 800ea86e83e137395eba54103e5c459c2bc9965f ]
The PASS_MASK is for a different register not for UVD_FW_START. It was a mistake to check this flag. It should be enough to check that the register is non-zero.
--- drivers/gpu/drm/amd/amdgpu/uvd_v3_1.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/amd/amdgpu/uvd_v3_1.c +1 -1
@@ -288,7 +288,7 @@ static int uvd_v3_1_fw_validate(struct amdgpu_device *adev)int i;uint32_t keysel = adev->uvd.keyselect; -if (RREG32 (mmUVD_FW_START) &UVD_FW_STATUS__PASS_MASK ) { +if (RREG32 (mmUVD_FW_START)) {dev_dbg (adev->dev,"UVD keyselect already set: 0x%x (on CPU: 0x%x)\n" ,RREG32 (mmUVD_FW_START), adev->uvd.keyselect);return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 566/1536 RISC-V: KVM: Fix double-free of sdata in kvm_pmu_clear_snapshot_area()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiakai Xu <[email protected]>
[ Upstream commit 310e2096b082ae0010e7afef666073b966ac2fa7 ]
In kvm_riscv_vcpu_pmu_snapshot_set_shmem(), when kvm_vcpu_write_guest() fails, kvpmu->sdata is freed but not set to NULL. This leaves a dangling pointer that will be freed again when kvm_pmu_clear_snapshot_area() is called during vcpu teardown, triggering a KASAN double-free report.
First free occurs in kvm_riscv_vcpu_pmu_snapshot_set_shmem():
kvm_riscv_vcpu_pmu_snapshot_set_shmem arch/riscv/kvm/vcpu_pmu.c:443 kvm_sbi_ext_pmu_handler arch/riscv/kvm/vcpu_sbi_pmu.c:74 kvm_riscv_vcpu_sbi_ecall arch/riscv/kvm/vcpu_sbi.c:608 kvm_riscv_vcpu_exit arch/riscv/kvm/vcpu_exit.c:240 kvm_arch_vcpu_ioctl_run arch/riscv/kvm/vcpu.c:1008 kvm_vcpu_ioctl virt/kvm/kvm_main.c:4476
Second free (double-free) occurs in kvm_pmu_clear_snapshot_area():
kvm_pmu_clear_snapshot_area arch/riscv/kvm/vcpu_pmu.c:403 [inline] kvm_riscv_vcpu_pmu_deinit.part arch/riscv/kvm/vcpu_pmu.c:905 kvm_riscv_vcpu_pmu_deinit arch/riscv/kvm/vcpu_pmu.c:893 kvm_arch_vcpu_destroy arch/riscv/kvm/vcpu.c:199 kvm_vcpu_destroy virt/kvm/kvm_main.c:469 [inline] kvm_destroy_vcpus virt/kvm/kvm_main.c:489 kvm_arch_destroy_vm arch/riscv/kvm/vm.c:54 kvm_destroy_vm virt/kvm/kvm_main.c:1301 [inline] kvm_put_kvm virt/kvm/kvm_main.c:1338 kvm_vm_release virt/kvm/kvm_main.c:1361
Fix it by setting kvpmu->sdata to NULL after kfree() in kvm_riscv_vcpu_pmu_snapshot_set_shmem(), so that the subsequent kfree(NULL) in kvm_pmu_clear_snapshot_area() becomes a safe no-op.
This bug was found by fuzzing the KVM RISC-V PMU interface.
--- arch/riscv/kvm/vcpu_pmu.c | 1 + 1 file changed, 1 insertion(+)
arch/riscv/kvm/vcpu_pmu.c +1 -0
@@ -451,6 +451,7 @@ int kvm_riscv_vcpu_pmu_snapshot_set_shmem(struct kvm_vcpu *vcpu, unsigned long sif (kvm_vcpu_write_guest (vcpu, saddr, kvpmu->sdata, snapshot_area_size)) {kfree (kvpmu->sdata); + kvpmu->sdata =NULL ; sbiret =SBI_ERR_FAILURE ; goto out; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 567/1536 drm/amd/display: guard dc_sink dereferences in MST mode validation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hari Mishal <[email protected]>
[ Upstream commit 217f64f348c90cba62164e7ff38e0ccf78a5ca09 ]
dm_dp_mst_is_port_support_mode() reads aconnector->dc_sink->dsc_caps... for the DSC branch-throughput check, and get_conv_frl_bw()'s HDMI-PCON FRL-bandwidth path reads aconnector->dc_sink->edid_caps.max_frl_rate, both without a NULL check. dc_sink is cleared asynchronously on MST unplug, and both functions run from paths that the driver's own comments document as racing that teardown: the connector probe worker's ->mode_valid callback and a compositor's atomic check, neither of which holds the MST manager lock that the teardown path uses. The former does have an existing dsc_aux NULL check, but dsc_aux isn't reliably cleared in every path that clears dc_sink, so it doesn't cover this.
Fail the port-support check and skip the FRL conversion path when the sink is already gone.
--- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_mst_types.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_mst_types.c +3 -0
@@ -1819,6 +1819,9 @@ enum dc_status dm_dp_mst_is_port_support_mode(struct dc_dsc_config_options dsc_options = {0 };uint32_t stream_kbps; +if (!aconnector->dc_sink) +return DC_FAIL_BANDWIDTH_VALIDATE ; +/* DSC unnecessary case * Check if timing could be supported within end-to-end BW */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 568/1536 net/sched: cls_bpf: accept dev-bound programs on shared blocks
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 d305547d1632a242818c5ebb430c85121a2ed434 upstream.
The issue:
Follow-up to commit 120977e2c096 ("net/sched: cls_bpf: reject dev-bound programs bound to a different device"), which derived the target device from block->q:
dev = block->q ? qdisc_dev(block->q) : NULL;
tcf_block_create() leaves block->q NULL for shared blocks, so a device-bound program attached through a shared block is rejected with -EINVAL even when it is bound to a netdev that owns the block. The offload path (cls_bpf_offload_cmd()) never consults block->q and drives the per-device callbacks for shared blocks as before.
The Fix:
Accept the attach on a shared block when bpf_offload_dev_match() matches every netdev bound to the block, and reject an empty block. Every member must match because the offload path broadcasts the program to every callback registered on the block, so an any-member check would re-admit the wrong-device attach on a mixed block. Every dev-bound SCHED_CLS attach is skip_sw, which becomes err_stop and aborts the offload on the first failing callback, so the all-members rule is the offload path's own semantics.
Iterate the public block->ports xarray (913b47d3424e, v6.8-rc1) rather than block->owner_list, which is private to cls_api.c. The shared-block rejection reports "Program is not bound to every device in the block", distinct from the non-shared message, because a member can exist without a registered callback (netdevsim registers its block callback ingress-only).
Context note:
This patch is not an independent fix: it re-exposes the shared-block replay path that commit 120977e2c096 ("net/sched: cls_bpf: reject dev-bound programs bound to a different device") had closed, so patch 1 must be applied first, including in stable. A stable tree taking this patch alone would re-enable shared-block attaches on a kernel whose netdevsim callback is still unchecked.
Conditions to recreate the bug:
- CONFIG_NETDEVSIM=y, CONFIG_NET_CLS_BPF=y
- load a dev-bound SCHED_CLS program for netdevsim device B (prog_ifindex=B), pin it in bpffs
- tc qdisc add dev B ingress_block 22 clsact
- tc filter add block 22 ingress bpf da object-pinned <pin> skip_sw Unfixed, the filter add fails with -EINVAL ("Program is bound to a different device"); fixed, it succeeds. Adding a second, independently backed netdevsim device to the same block makes the attach fail again.
--- net/sched/cls_bpf.c | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-)
net/sched/cls_bpf.c +24 -4
@@ -392,11 +392,31 @@ static int cls_bpf_prog_from_efd(structif (bpf_prog_is_dev_bound (fp->aux)) {struct tcf_block *block = tp->chain->block;struct net_device *dev; +unsigned long ifindex; +bool match = false; - dev = block->q ?qdisc_dev (block->q) :NULL ; -if (!dev || !bpf_offload_dev_match (fp, dev)) { -NL_SET_ERR_MSG (extack, -"Program is bound to a different device" ); +/* A shared block has no qdisc of its own, but it may bind +* several netdevs and the program is offloaded to all of them; +* require a match with every member. +*/ +if (!tcf_block_shared (block)) { + dev =qdisc_dev (tcf_block_q (block)); + match =bpf_offload_dev_match (fp, dev); +if (!match) +NL_SET_ERR_MSG (extack, +"Program is bound to a different device" ); + }else { +xa_for_each (&block->ports, ifindex, dev) { + match =bpf_offload_dev_match (fp, dev); +if (!match) +break ; + } +if (!match) +NL_SET_ERR_MSG (extack, +"Program is not bound to every device in the block" ); + } + +if (!match) {bpf_prog_put (fp);return -EINVAL ; }
Greg Kroah-Hartman
maintainerPATCH 569/1536 net/sched: cls_flower: avoid stale mask references after delete
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuhang Zheng <[email protected]>
commit 58f7989da6e715ce834ac861b7ba6ae9f9bdb098 upstream.
Flower releases a mask reference when a filter is removed from the classifier. The filter object can remain alive while dump, walk, or hardware reoffload paths hold a reference to it. Those paths can then dereference f->mask after the mask has already been released.
Keep the mask reference until the filter reference count reaches zero. Release the mask synchronously from the final __fl_put() while the caller still holds the tcf_proto reference, and leave the existing RCU work to free the mask. This keeps the mask available to every reader that still holds the filter.
The filter is still removed from the classifier indexes immediately. Therefore, a deleted filter can temporarily retain an otherwise empty mask; fl_delete() uses the handle IDR, rather than the mask list, to determine whether the classifier has become empty.
Failed mask assignment can leave fnew->mask as an error or borrowed pointer without an owned mask reference. Clear it before the common failure path so the final put cannot release an unowned reference.
This fix does not add fields, snapshots, or per-filter memory.
--- net/sched/cls_flower.c | 50 +++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 22 deletions(-)
net/sched/cls_flower.c +28 -22
@@ -522,15 +522,22 @@ static void fl_hw_update_stats(struct tctcf_exts_hw_stats_update (&f->exts, &cls_flower.stats, cls_flower.use_act_stats); } -static void __fl_put (struct cls_fl_filter *f) +static bool __fl_put (struct tcf_proto *tp,struct cls_fl_filter *f) { +bool last = false; +if (!refcount_dec_and_test (&f->refcnt)) -return ; +return false; + +if (f->mask) + last =fl_mask_put (fl_head_dereference (tp), f->mask);if (tcf_exts_get_net (&f->exts))tcf_queue_work (&f->rwork, fl_destroy_filter_work);else __fl_destroy_filter (f); + +return last; }static struct cls_fl_filter *__fl_get (struct cls_fl_head *head,u32 handle)
@@ -576,11 +583,10 @@ static int __fl_delete(struct tcf_protolist_del_rcu (&f->list);spin_unlock (&tp->lock); - *last =fl_mask_put (head, f->mask);if (!tc_skip_hw (f->flags))fl_hw_destroy_filter (tp, f, rtnl_held, extack);tcf_unbind_filter (tp, &f->res); -__fl_put (f); + *last =__fl_put (tp, f);return 0 ; }
@@ -621,7 +627,7 @@ static void fl_put(struct tcf_proto *tp, {struct cls_fl_filter *f = arg; -__fl_put (f); +__fl_put (tp, f); }static void *fl_get (struct tcf_proto *tp,u32 handle)
@@ -2492,12 +2498,14 @@ static int fl_change(struct net *net, st } err =fl_check_assign_mask (head, fnew, fold, mask); -if (err) +if (err) { + fnew->mask =NULL ; goto unbind_filter; + } err =fl_ht_insert_unique (fnew, fold, &in_ht);if (err) - goto errout_mask; + goto unbind_filter;if (!tc_skip_hw (fnew->flags)) { err =fl_hw_replace_filter (tp, fnew, rtnl_held, extack);
@@ -2551,7 +2559,6 @@ static int fl_change(struct net *net, stspin_unlock (&tp->lock); -fl_mask_put (head, fold->mask);if (!tc_skip_hw (fold->flags))fl_hw_destroy_filter (tp, fold, rtnl_held,NULL );tcf_unbind_filter (tp, &fold->res);
@@ -2559,7 +2566,7 @@ static int fl_change(struct net *net, st* after this. */ refcount_dec (&fold->refcnt); -__fl_put (fold); +__fl_put (tp, fold); }else {idr_replace (&head->handle_idr, fnew, fnew->handle);
@@ -2584,9 +2591,6 @@ errout_hw:if (in_ht)rhashtable_remove_fast (&fnew->mask->ht, &fnew->ht_node, fnew->mask->filter_ht_params); -errout_mask: -fl_mask_put (head, fnew->mask); - unbind_filter:if (bound_to_filter) {if (flags &TCA_ACT_FLAGS_NO_RTNL )
@@ -2602,14 +2606,14 @@ errout_idr:idr_remove (&head->handle_idr, fnew->handle);spin_unlock (&tp->lock); } -__fl_put (fnew); +__fl_put (tp, fnew); errout_tb:kfree (tb); errout_mask_alloc:tcf_queue_work (&mask->rwork, fl_uninit_mask_free_work); errout_fold:if (fold) -__fl_put (fold); +__fl_put (tp, fold);return err; }
@@ -2622,8 +2626,10 @@ static int fl_delete(struct tcf_proto *tint err =0 ; err =__fl_delete (tp, f, &last_on_mask, rtnl_held, extack); - *last =list_empty (&head->masks); -__fl_put (f); +spin_lock (&tp->lock); + *last =idr_is_empty (&head->handle_idr); +spin_unlock (&tp->lock); +__fl_put (tp, f);return err; }
@@ -2645,12 +2651,12 @@ static void fl_walk(struct tcf_proto *tprcu_read_unlock ();if (arg->fn (tp, f, arg) <0 ) { -__fl_put (f); +__fl_put (tp, f); arg->stop =1 ;rcu_read_lock ();break ; } -__fl_put (f); +__fl_put (tp, f); arg->count++;rcu_read_lock (); }
@@ -2701,7 +2707,7 @@ static int fl_reoffload(struct tcf_proto cls_flower.rule =flow_rule_alloc (tcf_exts_num_actions (&f->exts));if (!cls_flower.rule) { -__fl_put (f); +__fl_put (tp, f);return -ENOMEM ; }
@@ -2719,7 +2725,7 @@ static int fl_reoffload(struct tcf_protoif (err) {kfree (cls_flower.rule);if (tc_skip_sw (f->flags)) { -__fl_put (f); +__fl_put (tp, f);return err; } goto next_flow;
@@ -2735,11 +2741,11 @@ static int fl_reoffload(struct tcf_protokfree (cls_flower.rule);if (err) { -__fl_put (f); +__fl_put (tp, f);return err; } next_flow: -__fl_put (f); +__fl_put (tp, f); }return 0 ;
Greg Kroah-Hartman
maintainerPATCH 570/1536 net/sched: sch_teql: fix slaves_lock IRQ deadlock
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 8b2043279dae25483fe1f2d926e76d41ab95c398 upstream.
This is a followup of commit e5b811fe7931 ("net/sched: sch_teql:
Introduce slaves_lock to avoid race condition and UAF") as reported by Sashiko.
The issue: master->slaves_lock serializes the master's ring of slave qdiscs. The control paths -- teql_dequeue(), teql_destroy() and teql_qdisc_init() -- take it with spin_lock_bh(), while teql_master_xmit() (the master's ndo_start_xmit) takes it with plain spin_lock().
netpoll_send_skb() wraps the transmit in local_irq_save(), and __netpoll_send_skb() asserts lockdep_assert_irqs_disabled(), so teql_master_xmit() reached from netconsole always acquires slaves_lock with hard IRQs disabled. On PREEMPT_RT spinlock_t is an rtmutex, and Documentation/locking/locktypes.rst names
local_irq_disable(); spin_lock(&lock);
as a sequence that breaks there because the rtmutex requires a fully preemptible context. This is reachable without any panic: the nbcon printer thread calls netconsole's write_thread() callback on every message. The usual remedy -- folding the IRQ disable into the lock with spin_lock_irqsave() -- is unavailable because the local_irq_save() is netpoll's, not ours.
On non-RT the same asymmetry leaves slaves_lock acquirable with hard IRQs disabled on one path and held with hard IRQs enabled on another. That is only exploitable during the panic console flush (netconsole is CON_NBCON_ATOMIC_UNSAFE, so console_is_usable() admits its write_atomic() only from nbcon_atomic_flush_unsafe(), which panic() alone calls), and even then an IRQ-saving lock does not help if the holder oopsed inside the section or was stopped by panic_other_cpus_shutdown(). So the non-RT half is hardening; the PREEMPT_RT half is the bug.
The Fix: take slaves_lock as a raw spinlock with IRQs saved at every site. Since skb_queue_purge() takes the queue's spinlock_t and may not nest inside a raw lock on PREEMPT_RT, move its call in teql_destroy() outside the raw section; dat->q is the dying qdisc's own queue and was never serialized by slaves_lock, so the move is behaviour-neutral.
The new critical sections contain only RCU pointer assignments and netdev_get_tx_queue(); skb_queue_purge(), netif_wake_queue() and dev_reset_queue() are all outside them. teql_destroy()'s ring walk is O(slaves), two pointer loads and a compare per iteration, so even a large ring is microseconds with IRQs off. Keeping the purge conditional rather than dropping it outright is the conservative call for a backport.
Some context: commit 6301f6a34ed8 ("net/sched: sch_teql: move rcu_read_lock()/spin_lock() from _bh variants") hardened the parent fix; together they addressed the master->slaves resurrection use-after-free and the xmit-side BH warning but left the reverse direction -- a hard IRQ re-entering xmit while a control path holds the lock -- unaddressed.
Conditions to recreate the bug:
- CONFIG_PREEMPT_RT, CONFIG_NET_SCH_TEQL, CONFIG_DUMMY and CONFIG_NETCONSOLE.
- Run ip link add dev teqlslave0 type dummy, bring teqlslave0 up, attach it with tc qdisc add dev teqlslave0 root teql0, and bring teql0 up.
- Configure a netconsole target on teql0 with explicit local and remote IP addresses and a remote MAC address, then emit a console message. The nbcon printer thread reaches teql_master_xmit() with hard IRQs disabled by netpoll; taking slaves_lock as a spinlock_t is invalid on PREEMPT_RT. No panic or concurrent qdisc change is required.
- Reachable by an admin with CAP_NET_ADMIN; teql devices exist only in the initial netns (no per-netns ops), so a user namespace does not suffice.
--- net/sched/sch_teql.c | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-)
net/sched/sch_teql.c +28 -17
@@ -53,7 +53,7 @@ struct teql_master {struct Qdisc_ops qops;struct net_device *dev;struct Qdisc __rcu *slaves; -spinlock_t slaves_lock;/* serializes writes to ->slaves */ +raw_spinlock_t slaves_lock;/* serializes writes to ->slaves */ struct list_head master_list;unsigned long tx_bytes;unsigned long tx_packets;
@@ -92,6 +92,7 @@ teql_dequeue(struct Qdisc *sch) {struct teql_sched_data *dat =qdisc_priv (sch);struct netdev_queue *dat_queue; +unsigned long flags;struct sk_buff *skb;struct Qdisc *q;
@@ -102,9 +103,9 @@ teql_dequeue(struct Qdisc *sch)if (skb ==NULL ) {struct net_device *m =qdisc_dev (q);if (m) { -spin_lock_bh (&dat->m->slaves_lock); +raw_spin_lock_irqsave (&dat->m->slaves_lock, flags);rcu_assign_pointer (dat->m->slaves, sch); -spin_unlock_bh (&dat->m->slaves_lock); +raw_spin_unlock_irqrestore (&dat->m->slaves_lock, flags);netif_wake_queue (m); } }else {
@@ -137,11 +138,13 @@ teql_destroy(struct Qdisc *sch)struct teql_master *master = dat->m;struct netdev_queue *txq =NULL ;bool reset_master_queue = false; +unsigned long flags; +bool purge = false;if (!master)return ; -spin_lock_bh (&master->slaves_lock); +raw_spin_lock_irqsave (&master->slaves_lock, flags); prev =rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock));if (prev) {
@@ -169,12 +172,18 @@ teql_destroy(struct Qdisc *sch) reset_master_queue = true; } } -skb_queue_purge (&dat->q); + purge = true;break ; }while (prev !=rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock))); } -spin_unlock_bh (&master->slaves_lock); +raw_spin_unlock_irqrestore (&master->slaves_lock, flags); + +/* skb_queue_purge() takes the queue's spinlock_t, which cannot nest +* inside a raw lock on PREEMPT_RT; purge after the raw section. +*/ +if (purge) +skb_queue_purge (&dat->q);if (reset_master_queue)dev_reset_queue (master->dev, txq,NULL );
@@ -187,6 +196,7 @@ static int teql_qdisc_init(struct Qdiscstruct teql_master *m = (struct teql_master *)sch->ops;struct teql_sched_data *q =qdisc_priv (sch);struct Qdisc *first; +unsigned long flags;if (dev->hard_header_len > m->dev->hard_header_len)return -EINVAL ;
@@ -203,7 +213,7 @@ static int teql_qdisc_init(struct Qdiscskb_queue_head_init (&q->q); -spin_lock_bh (&m->slaves_lock); +raw_spin_lock_irqsave (&m->slaves_lock, flags); first =rcu_dereference_protected (m->slaves,lockdep_is_held (&m->slaves_lock));if (first) {if (m->dev->flags &IFF_UP ) {
@@ -214,7 +224,7 @@ static int teql_qdisc_init(struct Qdisc (m->dev->flags & IFF_MULTICAST && !(dev->flags & IFF_MULTICAST)) || dev->mtu < m->dev->mtu) { -spin_unlock_bh (&m->slaves_lock); +raw_spin_unlock_irqrestore (&m->slaves_lock, flags);return -EINVAL ; } }else {
@@ -237,7 +247,7 @@ static int teql_qdisc_init(struct Qdisc m->dev->mtu = dev->mtu; m->dev->flags = (m->dev->flags&~FMASK )|(dev->flags&FMASK ); } -spin_unlock_bh (&m->slaves_lock); +raw_spin_unlock_irqrestore (&m->slaves_lock, flags);return 0 ; }
@@ -302,11 +312,12 @@ static inline int teql_resolve(struct skstatic netdev_tx_t teql_master_xmit (struct sk_buff *skb,struct net_device *dev) {struct teql_master *master =netdev_priv (dev); -struct Qdisc *start, *q; -int busy; -int nores;int subq =skb_get_queue_mapping (skb);struct sk_buff *skb_res =NULL ; +struct Qdisc *start, *q; +unsigned long flags; +int nores; +int busy; restart: nores =0 ;
@@ -342,13 +353,13 @@ restart: netdev_start_xmit(skb, slave, slave_txq, false) == NETDEV_TX_OK) {__netif_tx_unlock (slave_txq); -spin_lock (&master->slaves_lock); +raw_spin_lock_irqsave (&master->slaves_lock, flags);if (rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock)) == q)rcu_assign_pointer (master->slaves,rcu_dereference_protected (NEXT_SLAVE (q),lockdep_is_held (&master->slaves_lock))); -spin_unlock (&master->slaves_lock); +raw_spin_unlock_irqrestore (&master->slaves_lock, flags);netif_wake_queue (dev); master->tx_packets++; master->tx_bytes += length;
@@ -361,13 +372,13 @@ restart: busy =1 ;break ;case 1 : -spin_lock (&master->slaves_lock); +raw_spin_lock_irqsave (&master->slaves_lock, flags);if (rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock)) == q)rcu_assign_pointer (master->slaves,rcu_dereference_protected (NEXT_SLAVE (q),lockdep_is_held (&master->slaves_lock))); -spin_unlock (&master->slaves_lock); +raw_spin_unlock_irqrestore (&master->slaves_lock, flags);rcu_read_unlock ();return NETDEV_TX_OK ;default :
@@ -489,7 +500,7 @@ static __init void teql_master_setup(strstruct teql_master *master =netdev_priv (dev);struct Qdisc_ops *ops = &master->qops; -spin_lock_init (&master->slaves_lock); +raw_spin_lock_init (&master->slaves_lock); master->dev = dev; ops->priv_size =sizeof (struct teql_sched_data );
Greg Kroah-Hartman
maintainerPATCH 571/1536 net/sched: sch_teql: fix use-after-free on lower qdisc drop
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: owen kwan <[email protected]>
commit 782d6bb8f9b8e9d8591181662222bf74cd3ecf79 upstream.
The issue: teql_master_xmit() tests the slave's ndo_start_xmit() return value against NETDEV_TX_OK alone. A slave that consumes the skb but returns an error code (rc < NET_XMIT_MASK, e.g. NET_XMIT_DROP) is treated as if the skb were still owned, so the loop restores skb->dev and calls __skb_pull() on it. A VLAN slave returns the result of dev_queue_xmit() from its ndo_start_xmit() (propagated since cbbef5e18307), and when the lower qdisc drops the packet that value is NET_XMIT_DROP after the skb has been freed, giving a use-after-free in teql_master_xmit().
The Fix: test for consumption with dev_xmit_complete(), which accepts NETDEV_TX_OK and every rc < NET_XMIT_MASK, matching other callers that need to distinguish consumed results from busy. Only NETDEV_TX_OK keeps the packet counted in tx_packets/tx_bytes and advances the slave; a consumed result that is neither a success nor NET_XMIT_CN ends the attempt and is charged to tx_dropped, so lower-qdisc drops are no longer reported as good transmits. NET_XMIT_CN is counted like success because it can accompany acceptance of the current packet: pfifo_head_drop drops the old head, enqueues the current skb and returns NET_XMIT_CN.
Conditions to recreate the bug:
With CONFIG_NET_SCH_TEQL,CONFIG_VLAN_8021Q and CONFIG_DUMMY enabled, add lkrdummy0 (dummy) and lkrvlan0 (VLAN id 37 on lkrdummy0); set a pfifo limit 0 root on lkrdummy0 and a teql0 root on lkrvlan0; bring teql0 up with an address and send one UDP packet to it. The VLAN xmit returns NET_XMIT_DROP from the lower qdisc while holding a freed skb.
--- net/sched/sch_teql.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
net/sched/sch_teql.c +10 -5
@@ -347,12 +347,18 @@ restart:case 0 :if (__netif_tx_trylock (slave_txq)) {unsigned int length =qdisc_pkt_len (skb); +int rc =NETDEV_TX_BUSY ; skb->dev = slave; -if (!netif_xmit_frozen_or_stopped (slave_txq) && -netdev_start_xmit (skb, slave, slave_txq, false) == -NETDEV_TX_OK ) { -__netif_tx_unlock (slave_txq); +if (!netif_xmit_frozen_or_stopped (slave_txq)) + rc =netdev_start_xmit (skb, slave, slave_txq, false); +__netif_tx_unlock (slave_txq); +if (dev_xmit_complete (rc)) { +if (rc !=NETDEV_TX_OK && rc !=NET_XMIT_CN ) { + master->tx_dropped++; +rcu_read_unlock (); +return NETDEV_TX_OK ; + }raw_spin_lock_irqsave (&master->slaves_lock, flags);if (rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock)) == q)
@@ -366,7 +372,6 @@ restart:rcu_read_unlock ();return NETDEV_TX_OK ; } -__netif_tx_unlock (slave_txq); }if (netif_xmit_stopped (netdev_get_tx_queue (dev,0 ))) busy =1 ;
Greg Kroah-Hartman
maintainerPATCH 572/1536 net/sched: fix packet reordering on requeue
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Antonio Quartulli <[email protected]>
commit 14368b9aa1017fee35d2589be7b17e0485c0f93e upstream.
dev_requeue_skb() appends requeued skbs to the tail of q->gso_skb, while dequeue_skb() takes them back one at a time from the head. If the driver returns NETDEV_TX_BUSY again for the first of them, it moves behind the skbs still parked there and is sent after them.
This showed up as heavy TCP reordering while benchmarking over veth,
which returns NETDEV_TX_BUSY whenever its ring is full since
commit dc82a33297fc ("veth: apply qdisc backpressure on full ptr_ring to reduce TX drops").
Requeue the skbs at the head of gso_skb, keeping their order. With 4 TCP streams over a veth pair with a pfifo qdisc, this removes about 1.3M out-of-order segments and 15-37k retransmits per 15 seconds, and raises throughput from about 40 to 76 Gbit/s.
--- net/sched/sch_generic.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
net/sched/sch_generic.c +9 -1
@@ -142,8 +142,11 @@ static inline void qdisc_enqueue_skb_badstatic inline void dev_requeue_skb (struct sk_buff *skb,struct Qdisc *q) { +struct sk_buff_head requeue;spinlock_t *lock =NULL ; +__skb_queue_head_init (&requeue); +if (q->flags &TCQ_F_NOLOCK ) { lock =qdisc_lock (q);spin_lock (lock);
@@ -152,7 +155,7 @@ static inline void dev_requeue_skb(strucwhile (skb) {struct sk_buff *next = skb->next; -__skb_queue_tail (&q->gso_skb, skb); +__skb_queue_tail (&requeue, skb);/* it's still part of the queue */ if (qdisc_is_percpu_stats (q)) {
@@ -168,6 +171,11 @@ static inline void dev_requeue_skb(struc skb = next; } +/* the skbs may come from the head of gso_skb, so put them back there: +* appending them would let the ones still parked overtake them +*/ +skb_queue_splice (&requeue, &q->gso_skb); +if (lock) {spin_unlock (lock);set_bit (__QDISC_STATE_MISSED, &q->state);
Greg Kroah-Hartman
maintainerPATCH 573/1536 net/sched: act_ife: do not consume the inner 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 498c631f9c6d74aad4bf43039fa3ce70ae9a8bb7 upstream.
The issue:tcf_ife_decode() unconditionally calls eth_type_trans(), which pulls ETH_HLEN. On egress this consumes the inner Ethernet header, and the device receives an skb whose data points to the L3 header:
- loopback_xmit() parses L3 data as Ethernet: the "ethertype" comes from the inner IPv4 source address, and the decapsulated packet is dropped or misparsed.
- a real NIC transmits the frame without its Ethernet header.
(The __skb_pull() BUG this used to trigger in loopback_xmit() when the remaining linear area was short is handled by "loopback: use eth_type_trans_careful()".)
The Fix:
Parse the inner Ethernet header with eth_type_trans() in both directions, then restore the egress data position and MAC length. On ingress the existing behavior is unchanged. On egress, push the inner Ethernet header back after parsing so the xmit path sees the original frame and later actions see a consistent network header.
Conditions to recreate the bug:
- egress tc filter on lo: action ife decode pipe;
- AF_PACKET SOCK_RAW frame: outer Ethernet with ETH_P_IFE, IFE metadata, inner Ethernet + a valid IPv4 ICMP echo request to a local address;
- before this patch, no echo is received; after it, the echo is delivered and answered.
--- net/sched/act_ife.c | 4 ++++ 1 file changed, 4 insertions(+)
net/sched/act_ife.c +4 -0
@@ -762,6 +762,10 @@ static int tcf_ife_decode(struct sk_buff skb->protocol =eth_type_trans (skb, skb->dev);skb_reset_network_header (skb); +if (!skb_at_tc_ingress (skb)) { +skb_push (skb,ETH_HLEN ); +skb_reset_mac_len (skb); + }return action; }
Greg Kroah-Hartman
maintainerPATCH 574/1536 driver core: take parent lock on deferred probe
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johan Hovold <[email protected]>
commit 4059f8986c8f50102a04335cc1da4921dfd262d8 upstream.
USB interfaces should be probed with the parent USB device lock held, but this is not honoured when probe is deferred.
Add a new bus_probe_device_deferred() helper to handle deferred probe where the parent device lock is not held.
--- drivers/base/base.h | 1 + drivers/base/bus.c | 28 +++++++++++++++++++++------- drivers/base/dd.c | 7 ++++--- 3 files changed, 26 insertions(+), 10 deletions(-)
drivers/base/base.h +1 -0
@@ -150,6 +150,7 @@ struct kobject *virtual_device_parent(voint bus_add_device (struct device *dev);void bus_probe_device (struct device *dev); +void bus_probe_device_deferred (struct device *dev);void bus_remove_device (struct device *dev);void bus_notify (struct device *dev,enum bus_notifier_event value);bool bus_is_registered (const struct bus_type *bus);
drivers/base/bus.c +21 -7
@@ -562,13 +562,7 @@ out_put:return error; } -/** -* bus_probe_device - probe drivers for a new device -* @dev: device to probe -* -* - Automatically probe for a driver if the bus allows it. -*/ -void bus_probe_device (struct device *dev) +static void __bus_probe_device (struct device *dev) {struct subsys_private *sp =bus_to_subsys (dev->bus);struct subsys_interface *sif;
@@ -588,6 +582,26 @@ void bus_probe_device(struct device *dev }/** +* bus_probe_device - probe drivers for a new device +* @dev: device to probe +* +* - Automatically probe for a driver if the bus allows it. +*/ +void bus_probe_device (struct device *dev) +{ +__bus_probe_device (dev); +} + +void bus_probe_device_deferred (struct device *dev) +{ +if (dev->type && dev->type->need_parent_lock) +device_lock (dev->parent); +__bus_probe_device (dev); +if (dev->type && dev->type->need_parent_lock) +device_unlock (dev->parent); +} + +/** * bus_remove_device - remove device from bus * @dev: device to be removed *
drivers/base/dd.c +4 -3
@@ -85,8 +85,9 @@ static void deferred_probe_work_func(str/* * This block processes every device in the deferred 'active' list. * Each device is removed from the active list and passed to -* bus_probe_device() to re-attempt the probe. The loop continues -* until every device in the active list is removed and retried. +* bus_probe_device_deferred() to re-attempt the probe. The loop +* continues until every device in the active list is removed and +* retried. * * Note: Once the device is removed from the list and the mutex is * released, it is possible for the device get freed by another thread
@@ -120,7 +121,7 @@ static void deferred_probe_work_func(strdevice_pm_move_to_tail (dev);dev_dbg (dev,"Retrying from deferred list\n" ); -bus_probe_device (dev); +bus_probe_device_deferred (dev);mutex_lock (&deferred_probe_mutex);put_device (dev);
Greg Kroah-Hartman
maintainerPATCH 575/1536 driver core: Limit the messages on a refused uevent
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 a01c8e5b1dff1ce489e6b339139e744db36b8bb3 upstream.
A write to a "uevent" file which is no valid action makes kobject_synth_uevent() print a warning and uevent_store() an error every time. This is generally considered a bad thing so rate limit these messages.
--- drivers/base/core.c | 4 +++- lib/kobject_uevent.c | 6 +++--- 2 files changed, 6 insertions(+), 4 deletions(-)
drivers/base/core.c +3 -1
@@ -2840,7 +2840,9 @@ static ssize_t uevent_store(struct devic rc =kobject_synth_uevent (&dev->kobj, buf, count);if (rc) { -dev_err (dev,"uevent: failed to send synthetic uevent: %d\n" , rc); +dev_err_ratelimited (dev, +"uevent: failed to send synthetic uevent: %d\n" , + rc);return rc; }
lib/kobject_uevent.c +3 -3
@@ -223,9 +223,9 @@ int kobject_synth_uevent(struct kobject out:if (r) { devpath =kobject_get_path (kobj,GFP_KERNEL ); -pr_warn ("synth uevent: %s: %s\n" , - devpath ?:"unknown device" , - msg ?:"failed to send uevent" ); +pr_warn_ratelimited ("synth uevent: %s: %s\n" , + devpath ?:"unknown device" , + msg ?:"failed to send uevent" );kfree (devpath); }return r;
Greg Kroah-Hartman
maintainerPATCH 576/1536 driver core: fix parent lock use-after-free on USB disconnect
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johan Hovold <[email protected]>
commit 0f554506a3fc6a21e714adf38cc3eb0ffe1bb452 upstream.
USB interfaces should be probed with their parent USB device lock held and the USB bus therefore sets the need_parent_lock bus flag so that driver core takes the parent lock when needed.
Driver core is only guaranteed to hold a reference to the parent device during initial probe however and nothing prevents the device and its parent from being deregistered and the parent potentially freed, for example, while iterating over devices in driver_attach() or bus_rescan_devices_helper().
Since commit 524134d42231 ("USB: don't cancel queued resets when unbinding drivers") USB interfaces hold a reference to their parent USB device, but a parent hub may still go away while probing a USB device (e.g. via the drivers_probe sysfs interface). This can lead to a use-after-free when taking the parent device lock before checking the device->p->dead flag of the device being probed.
As only USB interfaces actually need the parent lock, make the need_parent_lock feature even more fine grained by making it a device type rather than bus feature. By requiring that any users also make sure that their devices hold a reference to their parents (like USB does), driver core can lock a device and its parent without first checking if the device has been deregistered.
Note that this will also increase parallelism when using asynchronous probe as USB devices connected to the same hub can now be probed in parallel.
[ Fix mention of bus vs. device type in __device_driver_{un}lock().
- Danilo ]
--- drivers/base/bus.c | 4 ++-- drivers/base/dd.c | 8 ++++---- drivers/usb/core/driver.c | 1 - drivers/usb/core/message.c | 1 + include/linux/device.h | 5 +++++ include/linux/device/bus.h | 3 --- 6 files changed, 12 insertions(+), 10 deletions(-)
drivers/base/bus.c +2 -2
@@ -823,10 +823,10 @@ static int __must_check bus_rescan_devicint ret =0 ;if (!dev->driver) { -if (dev->parent && dev->bus->need_parent_lock) +if (dev->type && dev->type->need_parent_lock)device_lock (dev->parent); ret =device_attach (dev); -if (dev->parent && dev->bus->need_parent_lock) +if (dev->type && dev->type->need_parent_lock)device_unlock (dev->parent); }return ret <0 ? ret :0 ;
drivers/base/dd.c +4 -4
@@ -1161,7 +1161,7 @@ void device_initial_probe(struct device/* * __device_driver_lock - acquire locks needed to manipulate dev->drv * @dev: Device we will update driver info for -* @parent: Parent device. Needed if the bus requires parent lock +* @parent: Parent device. Needed if the device type requires parent lock * * This function will take the required locks for manipulating dev->drv. * Normally this will just be the @dev lock, but when called for a USB
@@ -1169,7 +1169,7 @@ void device_initial_probe(struct device*/ static void __device_driver_lock (struct device *dev,struct device *parent) { -if (parent && dev->bus->need_parent_lock) +if (dev->type && dev->type->need_parent_lock && parent)device_lock (parent);device_lock (dev); }
@@ -1177,7 +1177,7 @@ static void __device_driver_lock(struct/* * __device_driver_unlock - release locks needed to manipulate dev->drv * @dev: Device we will update driver info for -* @parent: Parent device. Needed if the bus requires parent lock +* @parent: Parent device. Needed if the device type requires parent lock * * This function will release the required locks for manipulating dev->drv. * Normally this will just be the @dev lock, but when called for a
@@ -1186,7 +1186,7 @@ static void __device_driver_lock(structstatic void __device_driver_unlock (struct device *dev,struct device *parent) {device_unlock (dev); -if (parent && dev->bus->need_parent_lock) +if (dev->type && dev->type->need_parent_lock && parent)device_unlock (parent); }
drivers/usb/core/driver.c +0 -1
@@ -2044,5 +2044,4 @@ const struct bus_type usb_bus_type = { .name = "usb", .match = usb_device_match, .uevent = usb_uevent, - .need_parent_lock = true, };
drivers/usb/core/message.c +1 -0
@@ -1920,6 +1920,7 @@ const struct device_type usb_if_device_t .name = "usb_interface", .release = usb_release_interface, .uevent = usb_if_uevent, + .need_parent_lock = true, }; static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
include/linux/device.h +5 -0
@@ -84,6 +84,10 @@ int subsys_virtual_register(const struct* information, equivalent to the kobj_type of a kobject. * If "name" is specified, the uevent will contain it in * the DEVTYPE variable. +* +* @need_parent_lock: When probing or removing a device of this type, +* driver core should lock the device's parent. Note that +* the device must hold a reference to its parent. */ struct device_type {const char *name;
@@ -94,6 +98,7 @@ struct device_type {void (*release)(struct device *dev);const struct dev_pm_ops *pm; +bool need_parent_lock; };/**
include/linux/device/bus.h +0 -3
@@ -66,8 +66,6 @@ struct fwnode_handle;* @driver_override: Set to true if this bus supports the driver_override * mechanism, which allows userspace to force a specific * driver to bind to a device via a sysfs attribute. -* @need_parent_lock: When probing or removing a device on this bus, the -* device core should lock the device's parent. * * A bus is a channel between the processor and one or more devices. For the * purposes of the device model, all devices are connected via a bus, even if
@@ -108,7 +106,6 @@ struct bus_type {const struct dev_pm_ops *pm;bool driver_override; -bool need_parent_lock; };int __must_check bus_register (const struct bus_type *bus);
Greg Kroah-Hartman
maintainerPATCH 577/1536 Drivers: hv: vmbus: Bounds check the shared ring buffer indices
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kameron Carr <[email protected]>
commit 1d287c17cc5bfd6386fe0770999be410b248d021 upstream.
In a CoCo VM the host is untrusted. Since the VMBus ring buffer read and write indices live in shared memory, the guest has to treat both as potentially malicious.
hv_ringbuffer_write() copies into the ring at write_index with no bounds checking, so the host can make the guest write packet data at any offset up to 4 GiB past the start of the ring buffer. read_index matters too:
the available space derived from both indices is the only bound on how much is copied, and an out-of-range index can make it far larger than the ring.
The fix is to validate both indices before use and to use the validated snapshot instead of re-accessing. For invalid indices, hv_ringbuffer_write() logs and returns -EIO.
One re-read of write_index is left unchecked in this patch:hv_get_ring_bufferindices() fetches it again for the prev_indices trailer. The value is only returned to the host and is not used as an offset or length for indexing. Since this is not a security issue, it is addressed later in the series.
Open-coding the bytes available arithmetic keeps the fix free of prerequisites; a later patch refactors it into a helper function.
--- drivers/hv/ring_buffer.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-)
drivers/hv/ring_buffer.c +16 -13
@@ -69,15 +69,6 @@ static void hv_signal_on_write(u32 old_w } } -/* Get the next write location for the specified ring buffer. */ -static inline u32 -hv_get_next_write_location (struct hv_ring_buffer_info *ring_info) -{ -u32 next = ring_info->ring_buffer->write_index; - -return next; -} -/* Set the next write location for the specified ring buffer. */ static inline void hv_set_next_write_location(struct hv_ring_buffer_info *ring_info,
@@ -281,6 +272,7 @@ int hv_ringbuffer_write(struct vmbus_chau32 totalbytes_towrite =sizeof (u64);u32 next_write_location;u32 old_write; +u32 read_index;u64 prev_indices;unsigned long flags;struct hv_ring_buffer_info *outring_info = &channel->outbound;
@@ -295,7 +287,20 @@ int hv_ringbuffer_write(struct vmbus_chaspin_lock_irqsave (&outring_info->ring_lock, flags); - bytes_avail_towrite =hv_get_bytes_to_write (outring_info); + read_index =READ_ONCE (outring_info->ring_buffer->read_index); + old_write =READ_ONCE (outring_info->ring_buffer->write_index); +if (unlikely (read_index >= outring_info->ring_datasize || + old_write >= outring_info->ring_datasize)) { +spin_unlock_irqrestore (&outring_info->ring_lock, flags); +pr_err_ratelimited ("outbound ring indices out of range: relid %u read %u write %u size %u\n" , + channel->offermsg.child_relid, read_index, + old_write, outring_info->ring_datasize); +return -EIO ; + } + + bytes_avail_towrite = old_write >= read_index ? + outring_info->ring_datasize - (old_write - read_index) : + read_index - old_write;/* * If there is only room for the packet, assume it is full.
@@ -317,9 +322,7 @@ int hv_ringbuffer_write(struct vmbus_cha channel->out_full_flag = false;/* Write to the ring buffer */ - next_write_location =hv_get_next_write_location (outring_info); - - old_write = next_write_location; + next_write_location = old_write;for (i =0 ; i < kv_count; i++) { next_write_location = hv_copyto_ringbuffer(outring_info,
Greg Kroah-Hartman
maintainerPATCH 578/1536 backlight: lm3630a: Cancel delayed work before destroying workqueue
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
commit 2cf184caab8b406fdd9db126ee40d62418237456 upstream.
The interrupt handler queues delayed work to read the interrupt status. After free_irq() stops the producer, this work can still be waiting on its timer. destroy_workqueue() cannot drain delayed work that has not yet been queued by its timer, so the timer can outlive both the workqueue and the devm-allocated chip containing the work.
Cancel the delayed work synchronously after freeing the IRQ and before destroying the workqueue. This also waits for any running status read to finish before the chip's resources are released.
This issue was identified during our ongoing static-analysis research while reviewing kernel code.
--- drivers/video/backlight/lm3630a_bl.c | 1 + 1 file changed, 1 insertion(+)
drivers/video/backlight/lm3630a_bl.c +1 -0
@@ -591,6 +591,7 @@ static void lm3630a_remove(struct i2c_clif (pchip->irq) {free_irq (pchip->irq, pchip); +cancel_delayed_work_sync (&pchip->work);destroy_workqueue (pchip->irqthread); } }
Greg Kroah-Hartman
maintainerPATCH 579/1536 backlight: qcom-wled: Fix NULL pointer dereference in wled_remove()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Heidelberg <[email protected]>
commit 1dbd46d4b2fb416a8202b1a8e4ef9d0cadbe075f upstream.
wled_probe() doesn't set the driver data for the platform device. As a result, platform_get_drvdata() in wled_remove() will return NULL, and the first dereference of it crashes on unbind.
Set the platform device driver data in wled_probe().
--- drivers/video/backlight/qcom-wled.c | 1 + 1 file changed, 1 insertion(+)
drivers/video/backlight/qcom-wled.c +1 -0
@@ -1682,6 +1682,7 @@ static int wled_probe(struct platform_de wled->regmap = regmap; wled->dev = &pdev->dev; +platform_set_drvdata (pdev, wled); wled->version = (uintptr_t )of_device_get_match_data (&pdev->dev);if (!wled->version) {
Greg Kroah-Hartman
maintainerPATCH 580/1536 backlight: qcom-wled: Fix unbalanced OVP IRQ enable at probe
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Heidelberg <[email protected]>
commit 5eda6b51461932f9fd835ef9e4574650c69c4fe8 upstream.
wled_configure_ovp_irq() derives the initial state of the OVP interrupt from the hardware:
/* Keep OVP irq disabled until module is enabled */
if (!(val & WLED3_CTRL_REG_MOD_EN_MASK))
disable_irq(wled->ovp_irq);but wled->brightness, which is what the rest of the driver uses to tell whether the module is on, is left at zero.
On boards where the bootloader hands the kernel a lit backlight the two disagree. MOD_EN is already set, so the interrupt is left enabled, while wled_update_status() still believes the backlight is off and takes
if (!!brightness != !!wled->brightness)
rc = wled_module_enable(wled, !!brightness);on the first backlight update. wled_module_enable() then schedules wled_ovp_work(), which calls enable_irq() on the already enabled interrupt:
Unbalanced enable for IRQ 176
WARNING: CPU: 0 PID: 160 at kernel/irq/manage.c:774 __enable_irq+0x50/0x80 Hardware name: Xiaomi Pocophone F1 (DT) Workqueue: events wled_ovp_work Call trace: __enable_irq+0x50/0x80 enable_irq+0x48/0xa0 wled_ovp_work+0x18/0x24 process_one_work+0x1d0/0x350 worker_thread+0x13c/0x460 kthread+0x110/0x114 ret_from_fork+0x10/0x20
The bootloader is not the only way to get there. The readback runs after wledN_setup(), and wled4_setup() sets MOD_EN itself on the path where the sink configuration does not already match, as does the tail of wled_auto_string_detection(), which all three setup paths can reach through wled_auto_detection_at_init(). A cold-booted board with a dark panel can therefore reach the same disagreement.
Move the MOD_EN readback into wled_probe() and use it to seed wled->brightness, so the driver starts out agreeing with the hardware, and key the OVP interrupt off wled->brightness instead. The first backlight update then only reprograms the brightness registers and leaves both the module and the interrupt alone. The OVP interrupt also stays armed from probe whenever the module is already enabled, rather than being disabled at probe and only enabled once something writes brightness.
Note that a backlight update requesting brightness 0 before any non-zero one now really does turn the module off wherever MOD_EN was already set, where before it was silently ignored.
wled->brightness is seeded with default-brightness rather than the level the bootloader actually programmed, so the first update can still step the brightness. Reading that level back is version specific and is done in a follow-up, to keep this fix small enough to backport.
--- drivers/video/backlight/qcom-wled.c | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-)
drivers/video/backlight/qcom-wled.c +21 -11
@@ -1627,7 +1627,6 @@ static int wled_configure_ovp_irq(struct struct platform_device *pdev) {int rc; -u32 val; wled->ovp_irq =platform_get_irq_byname (pdev,"ovp" );if (wled->ovp_irq <0 ) {
@@ -1645,13 +1644,8 @@ static int wled_configure_ovp_irq(structreturn 0 ; } - rc =regmap_read (wled->regmap, wled->ctrl_addr + -WLED3_CTRL_REG_MOD_EN , &val); -if (rc <0 ) -return rc; - -/* Keep OVP irq disabled until module is enabled */ -if (!(val &WLED3_CTRL_REG_MOD_EN_MASK )) +/* Keep the OVP irq disabled until the module is enabled */ +if (!wled->brightness)disable_irq (wled->ovp_irq);return 0 ;
@@ -1667,6 +1661,7 @@ static int wled_probe(struct platform_destruct backlight_device *bl;struct wled *wled;struct regmap *regmap; +u32 mod_en;u32 val;int rc;
@@ -1737,6 +1732,24 @@ static int wled_probe(struct platform_deINIT_DELAYED_WORK (&wled->ovp_work, wled_ovp_work); + val =WLED_DEFAULT_BRIGHTNESS ; +of_property_read_u32 (pdev->dev.of_node,"default-brightness" , &val); + +/* +* The module may already be enabled, either by a bootloader that left +* the backlight lit or by the setup above. Record that, so that the +* first brightness update does not enable an already enabled module, +* and so that the OVP irq is armed from probe rather than from that +* first update. +*/ + rc =regmap_read (wled->regmap, wled->ctrl_addr +WLED3_CTRL_REG_MOD_EN , + &mod_en); +if (rc <0 ) +return rc; + +if (mod_en &WLED3_CTRL_REG_MOD_EN_MASK ) + wled->brightness = val; + rc =wled_configure_short_irq (wled, pdev);if (rc <0 )return rc;
@@ -1745,9 +1758,6 @@ static int wled_probe(struct platform_deif (rc <0 )return rc; - val =WLED_DEFAULT_BRIGHTNESS ; -of_property_read_u32 (pdev->dev.of_node,"default-brightness" , &val); -memset (&props,0 ,sizeof (struct backlight_properties )); props.type =BACKLIGHT_RAW ; props.brightness = val;
Greg Kroah-Hartman
maintainerPATCH 581/1536 backlight: qcom-wled: Fix WLED3 brightness register stride
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Heidelberg <[email protected]>
commit e60dc9c05e0f415ef8bc63b3179abdd49830a619 upstream.
WLED3 has a 16-bit brightness register pair per string, at 0x40 + 2*n, which is what the pm8941-wled driver wrote to:
rc = regmap_bulk_write(wled->regmap, wled->addr + WLED3_CTRL_REG_VAL_BASE + 2 * i, v, 2);
The restructuring for WLED3 turned that into WLED3_SINK_REG_BRIGHT(n), defined as 0x40 + n, so the two byte writes for consecutive strings
overlap: string 1 overwrites the MSB of string 0 with its own LSB, and with the default three strings only string 1 ends up with the requested value.
Use the 2 byte stride.
--- drivers/video/backlight/qcom-wled.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/video/backlight/qcom-wled.c +1 -1
@@ -59,7 +59,7 @@#define WLED3_SINK_REG_CURR_SINK_SHFT 5/* WLED3 specific per-'string' registers below */ -#define WLED3_SINK_REG_BRIGHT (n) (0x40 + n) +#define WLED3_SINK_REG_BRIGHT (n) (0x40 + (n * 0x2))#define WLED3_SINK_REG_STR_MOD_EN (n) (0x60 + (n * 0x10))#define WLED3_SINK_REG_STR_MOD_MASK BIT(7)
Greg Kroah-Hartman
maintainerPATCH 582/1536 ksmbd: accept share config responses from ksmbd-tools before 3.5.3
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 4f1ce9ffb996a524acf864316479a7806ae500c6 upstream.
ksmbd-tools releases before 3.5.2 do not have the payload_sz field in struct ksmbd_share_config_response; the field occupies the last word of their reserved[] area, so the kernel always sees payload_sz == 0 from them. ipc_validate_msg() and share_config_request() used to treat payload_sz == 0 as "legacy userspace" and skip the payload size checks.
That case was removed by
commit f25e93768fcc ("ksmbd: prevent out-of-bounds reads in share config responses").
With payload_sz == 0:
- the IPC$ (pipe) response fails the final message size comparison:
these tools always send a one-byte payload, so msg_sz is sizeof(*resp) + 1, but the expected size is now computed as sizeof(*resp) + 0;
- every other share fails "payload_sz <= veto_list_sz".
In addition, ksmbd-tools before 3.5.3 copy a global "veto files" setting into the IPC$ response, so with such a configuration IPC$ also fails the now unconditional "veto_list_sz > payload_sz" check, even though pipe shares never use a veto list.
ksmbd_ipc_share_config_request() then returns NULL and every tree connect fails with STATUS_BAD_NETWORK_NAME, so ksmbd cannot serve any share when used with these ksmbd-tools releases, for example the 3.5.1 package shipped by Ubuntu 24.04. Login still works, which makes the failure look like a configuration problem:
CIFS: VFS: BAD_NETWORK_NAME: \\127.0.0.1\IPC$
CIFS: VFS: \\127.0.0.1 failed to connect to IPC (rc=-2)
When payload_sz is zero, derive it from the size of the message actually received and store it back in the response, so that the checks in ipc_validate_msg() and the path and veto list parsing in share_config_request() all use the same bound. The response is the kernel's own copy made by handle_response(), and msg_sz has already been checked to be at least sizeof(*resp), so this cannot underflow. All checks added by that commit then apply unchanged, bounded by the bytes that really arrived, and newer ksmbd-tools that fill in payload_sz are unaffected. Also skip the veto list size check for pipe shares:share_config_request() reads neither the path nor the veto list for them.
Tested in QEMU with ksmbd-tools 3.5.1 and 3.5.7 and the in-kernel SMB client over loopback, with and without a global "veto files" setting.
--- fs/smb/server/transport_ipc.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-)
fs/smb/server/transport_ipc.c +15 -1
@@ -524,11 +524,25 @@ static int ipc_validate_msg(struct ipc_mif (entry->msg_sz <sizeof (struct ksmbd_share_config_response ))return -EINVAL ; +/* +* ksmbd-tools releases before 3.5.2 leave payload_sz zero. +* Derive it from the size of the message actually received so +* the checks below bound the payload for those releases too. +*/ +if (!resp->payload_sz) + resp->payload_sz = entry->msg_sz - +sizeof (struct ksmbd_share_config_response ); +if (strnlen (resp->share_name,sizeof (resp->share_name)) ==sizeof (resp->share_name))return -EINVAL ; -if (resp->veto_list_sz > resp->payload_sz) +/* +* Pipe shares carry no veto list, but ksmbd-tools before 3.5.3 +* copy a global "veto files" setting into the IPC$ response. +*/ +if (!(resp->flags &KSMBD_SHARE_FLAG_PIPE ) && + resp->veto_list_sz > resp->payload_sz)return -EINVAL ; if (resp->flags != KSMBD_SHARE_FLAG_INVALID &&
Greg Kroah-Hartman
maintainerPATCH 583/1536 ksmbd: avoid restoring only in-memory EOF after allocation change
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: DaeMyung Kang <[email protected]>
commit 9455e920aebe41217cabff3f81e90da4c407fdb6 upstream.
When SetAllocation requests a size below the allocated block count but above EOF, ksmbd truncates the file to that size and restores only the in-memory i_size. The larger EOF remains on disk and reappears after a reboot. A 3-byte file preallocated to 64 KiB can acquire a 4 KiB EOF after reducing its allocation to 4 KiB. Extending EOF this way is not a reliable way to reclaim the preallocation beyond the old EOF either.
Only use this truncate path when the requested allocation is at or below the observed EOF. A truncate to the existing EOF still lets filesystems release preallocated blocks beyond EOF. Remove the in-memory-only i_size restoration. The size check still precedes vfs_truncate() taking the inode lock, so a concurrent shrink can make the truncate extend EOF; that race also existed in the original path.
--- fs/smb/server/smb2pdu.c | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-)
fs/smb/server/smb2pdu.c +4 -11
@@ -6495,24 +6495,17 @@ static int set_file_allocation_info(strupr_err ("vfs_fallocate is failed : %d\n" , rc);return rc; } - }else if (alloc_blks < stat.blocks) { -loff_t size; - + }else if (alloc_blks < stat.blocks && + alloc_blks *512 <=i_size_read (inode)) {/* -* Allocation size could be smaller than original one -* which means allocated blocks in file should be -* deallocated. use truncate to cut out it, but inode -* size is also updated with truncate offset. -* inode size is retained by backup inode size. +* Truncate at or below EOF to discard excess allocation. +* Truncating above EOF would extend the file on disk. */ - size =i_size_read (inode); rc =ksmbd_vfs_truncate (work, fp, alloc_blks *512 );if (rc) {pr_err ("truncate failed!, err %d\n" , rc);return rc; } -if (size < alloc_blks *512 ) -i_size_write (inode, size); }return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 584/1536 ksmbd: fix extended session security negotiation for raw NTLMSSP
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Namjae Jeon <[email protected]>
commit 6868f857514bbfd2ed10b9b566664dc4a8ca039d upstream.
ksmbd_build_ntlmssp_challenge_blob() only advertises extended session security when conn->use_spnego is true. As a result, raw NTLMSSP negotiation drops NTLMSSP_NEGOTIATE_EXTENDED_SEC from the challenge even when the client requested it.
A Windows capture shows an initial SPNEGO authentication succeeding, followed by a raw NTLMSSP negotiation on the same TCP connection. The raw challenge omits extended session security, and the client does not send an AUTHENTICATE message. The unfinished session then occupies the pending session slot, causing subsequent SESSION_SETUP requests to fail with STATUS_INSUFFICIENT_RESOURCES.
Set NTLMSSP_NEGOTIATE_EXTENDED_SEC whenever the client requests it, independently of the SPNEGO wrapper, as required by [MS-NLMP].
--- fs/smb/server/auth.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
fs/smb/server/auth.c +1 -2
@@ -446,8 +446,7 @@ ksmbd_build_ntlmssp_challenge_blob(strucif (cflags &NTLMSSP_REQUEST_TARGET ) flags |=NTLMSSP_REQUEST_TARGET ; -if (conn->use_spnego && - (cflags &NTLMSSP_NEGOTIATE_EXTENDED_SEC )) +if (cflags &NTLMSSP_NEGOTIATE_EXTENDED_SEC ) flags |=NTLMSSP_NEGOTIATE_EXTENDED_SEC ;if (cflags &NTLMSSP_NEGOTIATE_KEY_XCH )
Greg Kroah-Hartman
maintainerPATCH 585/1536 ksmbd: fix OOB read and cross-share confusion in ksmbd_validate_name_reconnect()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dairui Zhang <[email protected]>
commit 783a7fc454991544bf92268d8f2413af1a7c7eb8 upstream.
ksmbd_validate_name_reconnect() indexes ab_pathname[share->path_sz + 1] without checking that the path is longer than share->path_sz + 1 (d_path() fills the buffer from the end). A durable fp is not bound to its original share, so a client can preserve a file from a short-path share and reconnect it on a long-path share, making strcmp() read past the PATH_MAX buffer - with a long enough share path this oopses the kernel, and on a mapped page it also gives a byte-equality oracle on adjacent heap (the reconnect succeeds exactly when the out-of-bounds string equals the requested name). A same-share variant with the durable fp at the share root reads 1 byte past the buffer (strlen(ab_pathname) == share->path_sz).
Check before comparing: the path must be longer than share->path_sz, it must start with share->path, and the next character must be '/'. The share root itself is accepted only for an empty name.
--- fs/smb/server/vfs_cache.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-)
fs/smb/server/vfs_cache.c +15 -3
@@ -1339,9 +1339,21 @@ int ksmbd_validate_name_reconnect(structreturn -EACCES ; } -if (name &&strcmp (&ab_pathname[share->path_sz +1 ], name)) { -ksmbd_debug (SMB ,"invalid name reconnect %s\n" , name); - ret = -EINVAL ; +if (name) { +size_t len =strlen (ab_pathname); + +if (len == share->path_sz && !strncmp (ab_pathname, share->path, len)) { +/* the durable fp is the share root itself */ +if (name[0 ]) + ret = -EINVAL ; + }else if (len <= share->path_sz || +strncmp (ab_pathname, share->path, share->path_sz) || + ab_pathname[share->path_sz] !='/' || +strcmp (&ab_pathname[share->path_sz +1 ], name)) { + ret = -EINVAL ; + } +if (ret) +ksmbd_debug (SMB ,"invalid name reconnect %s\n" , name); }kfree (pathname);
Greg Kroah-Hartman
maintainerPATCH 586/1536 ksmbd: fix overflow in dacloffset bounds check in build_sec_desc()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giorgi Kobakhia <[email protected]>
commit eb96e2a0e817807c48dc8387ca6a5249fdeae3a0 upstream.
When the large dacl_offset is provided, dacl_offset + sizeof(struct smb_acl) overflows on 32-bit builds and the check is passed, Which makes le16_to_cpu(ppdacl_ptr->size) read out-of-bounds. This only happens for dacl_offset in range [0xFFFFFFF8, 0xFFFFFFFF]. So the oob read is max 8 bytes preceding the allocated ppntsd.
unsigned int dacl_offset = le32_to_cpu(ppntsd->dacloffset);
int ppdacl_size, ntacl_size = ppntsd_size - dacl_offset;
if (!dacl_offset ||
(dacl_offset + sizeof(struct smb_acl) > ppntsd_size))
goto out;Commit beff0bc9d69b ("ksmbd: fix overflow in dacloffset bounds check") fixes similar checks in other functions. But leaves this one out, because it is only valid for 32-bit builds.
Reproduced on 32-bit ARM with KASAN, by a client sending SMB2 SET_INFO(SEC) with dacloffset=0xfffffff8, then QUERY_INFO(SEC) on the same file:
BUG: KASAN: slab-out-of-bounds in build_sec_desc (fs/smb/server/smbacl.c:1105) Read of size 2 at addr c2a273fa by task kworker/1:1/35 CPU: 1 UID: 0 PID: 35 Comm: kworker/1:1 Not tainted 7.3.0-rc2+ #5 Workqueue: ksmbd-io handle_ksmbd_work Call trace: kasan_check_range from build_sec_desc (fs/smb/server/smbacl.c:1105) build_sec_desc from smb2_query_info (fs/smb/server/smb2pdu.c:7676) smb2_query_info from handle_ksmbd_work (fs/smb/server/server.c:160) handle_ksmbd_work from process_one_work (kernel/workqueue.c:3401) process_one_work from worker_thread (kernel/workqueue.c:3473) worker_thread from kthread (kernel/kthread.c:436)
Add overflow check.
--- fs/smb/server/smbacl.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/smb/server/smbacl.c +4 -1
@@ -1093,9 +1093,12 @@ int build_sec_desc(struct mnt_idmap *idmstruct smb_acl *ppdacl_ptr;unsigned int dacl_offset =le32_to_cpu (ppntsd->dacloffset);int ppdacl_size, ntacl_size = ppntsd_size - dacl_offset; +size_t dacl_struct_end;if (!dacl_offset || - (dacl_offset +sizeof (struct smb_acl ) > ppntsd_size)) +check_add_overflow (dacl_offset,sizeof (struct smb_acl ), + &dacl_struct_end) || + dacl_struct_end > (size_t )ppntsd_size) goto out; ppdacl_ptr = (struct smb_acl *)((char *)ppntsd + dacl_offset);
Greg Kroah-Hartman
maintainerPATCH 587/1536 ksmbd: fix parent dentry lifetime in directory enumeration
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 171df27077fb49b4af2c53ad2cedcd0e39664fe8 upstream.
ksmbd_populate_dot_dotdot_entries() builds the ".." entry from the open directory's d_parent and passes that pointer to ksmbd_vfs_fill_dentry_attrs() without taking a reference. That pointer is only valid while the directory stays under this parent. If a concurrent rename moves the directory elsewhere, the old parent loses its last reference; a following rmdir then turns it into a negative dentry with d_inode cleared, and after the RCU grace period the dentry itself is freed. The worker still holds the raw pointer and dereferences d_inode through vfs_getattr() and vfs_getxattr().
A remote SMB client, authenticated or guest, triggers this by listing a directory while that directory is moved under a new parent and the old parent is deleted. It can be done by the client itself with write access or by other concurrent writers, triggering null-ptr-deref and slab-use-after-free on a KASAN build.
KASAN: null-ptr-deref in range
[0x0000000000000000-0x0000000000000007]
Workqueue: ksmbd-io handle_ksmbd_work
RIP: 0010:xattr_permission+0x9d/0x160
Call Trace:
vfs_getxattr+0x9c/0x1b0
ksmbd_vfs_getxattr+0x82/0x100
ksmbd_vfs_get_dos_attrib_xattr+0x7f/0x130
ksmbd_vfs_fill_dentry_attrs+0x435/0x650
ksmbd_populate_dot_dotdot_entries+0x25e/0x630
smb2_query_dir+0xcf9/0x1a20
handle_ksmbd_work+0x5f1/0x1c80
process_one_work+0x90b/0x19d0Fix by using the dentry reference counting APIs: take the parent with dget_parent(), take a matching dget() on ".", and dput() the dentry once ksmbd_vfs_fill_dentry_attrs() has returned or the pattern does not match.
--- fs/smb/server/smb_common.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/server/smb_common.c +4 -2
@@ -447,16 +447,17 @@ int ksmbd_populate_dot_dotdot_entries(stif (i ==0 ) { d_info->name ="." ; d_info->name_len =1 ; - dentry = dir->filp->f_path.dentry; + dentry =dget (dir->filp->f_path.dentry); }else { d_info->name =".." ; d_info->name_len =2 ; - dentry = dir->filp->f_path.dentry->d_parent; + dentry =dget_parent (dir->filp->f_path.dentry); }if (!match_pattern (d_info->name, d_info->name_len, search_pattern)) { dir->dot_dotdot[i] =1 ; +dput (dentry);continue ; }
@@ -465,6 +466,7 @@ int ksmbd_populate_dot_dotdot_entries(st idmap, dentry, &ksmbd_kstat); +dput (dentry);if (rc)break ;
Greg Kroah-Hartman
maintainerPATCH 588/1536 ksmbd: ignore network devices of other namespaces
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jan Koester <[email protected]>
commit 1f5ce2b8b9164b3fcb93a18fe1e7b451c2fc6eea upstream.
With no interface list configured, ksmbd binds every interface that comes up. ksmbd_netdev_event() does not look at the device's namespace, and create_socket() opens the listener in the namespace of the task raising NETDEV_UP. A container with its own address on a bridge brings up its interface and finds port 445 in its namespace already taken by ksmbd, so an SMB server running inside the container fails with "Address already in use".
Interfaces are also matched by name only, so a container's eth0 going down would stop the listener on the host's eth0.
Only handle netdev events for devices in init_net.
--- fs/smb/server/transport_tcp.c | 9 +++++++++ 1 file changed, 9 insertions(+)
fs/smb/server/transport_tcp.c +9 -0
@@ -602,6 +602,15 @@ static int ksmbd_netdev_event(struct notstruct interface *iface;int ret; +/* +* ksmbd serves the initial namespace only. create_socket() listens in +* the namespace of the task raising the event, so a container bringing +* up its own interface would get a listener on its port 445, and the +* name-only interface lookup would let its interfaces stop ours. +*/ +if (!net_eq (dev_net (netdev), &init_net)) +return NOTIFY_DONE ; +switch (event) {case NETDEV_UP :if (netif_is_bridge_port (netdev))
Greg Kroah-Hartman
maintainerPATCH 589/1536 ksmbd: preserve unreadable named streams on open
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: DaeMyung Kang <[email protected]>
commit 80c816c047f7cae3c99cc75740c1f5d2c4d97b45 upstream.
A write-only client can open an existing named stream with FILE_OPEN_IF without permission to read the underlying file. The case-insensitive lookup finds the xattr name, but querying its value length then fails with -EACCES. smb2_set_stream_name_xattr() treats every negative result as a missing stream and replaces the existing xattr with an empty value.
A failed xattr list is not proof that the stream is absent either:
for example, -ENOMEM can lead to the same empty replacement. Preserve listing errors and create a stream only for -ENOENT or -ENODATA. The latter can occur if the xattr is removed between listing its name and querying its value. Return other lookup errors without changing the stream.
A write-only FILE_OPEN now reports access denied instead of name not found. FILE_OVERWRITE_IF and FILE_SUPERSEDE on an unreadable stream also fail instead of appearing to replace it. Stream writes and EOF changes already need to read the old value, so such handles cannot update the stream after opening either.
--- fs/smb/server/smb2pdu.c | 2 ++ fs/smb/server/vfs.c | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +2 -0
@@ -2548,6 +2548,8 @@ static noinline int smb2_set_stream_name xattr_stream_size);if (rc >=0 )return 0 ; +if (rc != -ENOENT && rc != -ENODATA ) +return rc;if (fp->cdoption ==FILE_OPEN_LE ) {ksmbd_debug (SMB ,"XATTR stream name lookup failed: %d\n" , rc);
fs/smb/server/vfs.c +5 -1
@@ -1818,7 +1818,11 @@ ssize_t ksmbd_vfs_casexattr_len(struct mssize_t value_len = -ENOENT , xattr_list_len; xattr_list_len =ksmbd_vfs_listxattr (dentry, &xattr_list); -if (xattr_list_len <=0 ) +if (xattr_list_len <0 ) { + value_len = xattr_list_len; + goto out; + } +if (!xattr_list_len) goto out; for (name = xattr_list; name - xattr_list < xattr_list_len;
Greg Kroah-Hartman
maintainerPATCH 590/1536 ksmbd: reserve space for the UTF-16 terminator in stream info
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Abdifatah Suruur <[email protected]>
commit a025c4991a7d83edc4dd339e3ea86d8ff6226eca upstream.
smb_strtoUTF16() always writes a terminating zero UTF-16 unit after the converted characters, but get_file_stream_info() budgets only sizeof(struct smb2_file_stream_info) + streamlen * 2 for a stream entry and sizeof(struct smb2_file_stream_info) + 7 * 2 for the trailing "::$DATA" entry. When an entry exactly fills the 448-byte small response buffer, the terminator is written two bytes past the allocation.
Reserve one extra UTF-16 unit in both budget checks. The terminator is not part of the wire format, so the reported lengths are unchanged.
--- fs/smb/server/smb2pdu.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
fs/smb/server/smb2pdu.c +3 -2
@@ -5220,7 +5220,8 @@ static int get_file_stream_info(struct k ":%s", &stream_name[XATTR_NAME_STREAM_LEN]); next =sizeof (struct smb2_file_stream_info ) + streamlen *2 ; -if (next > buf_free_len) { +/* smbConvertToUTF16() also writes a terminating UTF-16 unit. */ +if (next +sizeof (__le16) > buf_free_len) {kfree (stream_buf);break ; }
@@ -5254,7 +5255,7 @@ static int get_file_stream_info(struct k out:if (!S_ISDIR (stat.mode) && - buf_free_len >=sizeof (struct smb2_file_stream_info ) +7 *2 ) { + buf_free_len >=sizeof (struct smb2_file_stream_info ) + (7 +1 ) *2 ) { file_info = (struct smb2_file_stream_info *) &rsp->Buffer[nbytes]; streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
Greg Kroah-Hartman
maintainerPATCH 591/1536 ksmbd: return end of file for reads past a named streams data
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: DaeMyung Kang <[email protected]>
commit 626611dc22a3b63b3264a7a797d9dbc530234fcd upstream.
A READ on a non-empty named stream at or beyond its end fails with STATUS_INVALID_PARAMETER. ksmbd_vfs_stream_read() returns -EINVAL when the offset is not below the stream length, and smb2_read() maps -EINVAL to that status.
smb2_read() already turns a zero-byte read into STATUS_END_OF_FILE, the status a regular file returns at its end, and an empty stream already takes that path. Return 0 instead of -EINVAL so that non-empty streams do the same. Clients that read a stream until end of file otherwise get an error once they have read all of its data.
The buffered copychunk path converts a zero-byte source read to -EIO, as it does for a regular file that shrinks during copying.
--- fs/smb/server/vfs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/server/vfs.c +1 -1
@@ -299,7 +299,7 @@ static int ksmbd_vfs_stream_read(structreturn (int )v_len;if (v_len <= *pos) { - count = -EINVAL ; + count =0 ; goto free_buf; }
Greg Kroah-Hartman
maintainerPATCH 592/1536 ksmbd: use u8 for SMB2 oplock level values
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
commit f622fedabbb58c8006ee21373968ae07bf8a9467 upstream.
The SMB2 oplock level is an unsigned 8-bit wire value, but smb20_oplock_break_ack() stores it in a plain char. On architectures where plain char is signed, the value 0xff becomes -1 and cannot compare equal to SMB2_OPLOCK_LEVEL_LEASE (0xff). The acknowledgment is consequently rejected with STATUS_INVALID_OPLOCK_PROTOCOL instead of the intended STATUS_INVALID_PARAMETER.
Use u8 for the request and response oplock-level variables. This preserves all wire values in their original representation.
--- fs/smb/server/smb2pdu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +1 -1
@@ -8822,7 +8822,7 @@ static void smb20_oplock_break_ack(struc__le32 status =STATUS_SUCCESS ;int ret;u64 volatile_id, persistent_id; -char req_oplevel =0 , rsp_oplevel =0 ; +u8 req_oplevel =0 , rsp_oplevel =0 ;WORK_BUFFERS (work, req, rsp);
Greg Kroah-Hartman
maintainerPATCH 593/1536 ksmbd: validate security descriptor offsets before pointer arithmetic
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Namjae Jeon <[email protected]>
commit 3474e1a304fbf9f7c996b24adcd519e031227a90 upstream.
parse_sec_desc() constructs SID and DACL pointers by adding untrusted 32-bit offsets to the security descriptor before checking their bounds. The existing checks reject offsets into the descriptor header, but do not reject offsets beyond the descriptor's length.
On a 32-bit kernel, a large offset can wrap the pointer before the descriptor. The end-only checks in parse_sid() and parse_dacl() can then accept it, allowing an authenticated SMB2 SET_INFO request to access memory outside the security descriptor and fault the kernel.
Check each nonzero offset against acl_len before constructing its pointer. Initialize the optional owner and group SID pointers to NULL so an omitted SID remains absent when parsing the DACL.
--- fs/smb/server/smbacl.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-)
fs/smb/server/smbacl.c +11 -9
@@ -896,7 +896,7 @@ int parse_sec_desc(struct mnt_idmap *idm int acl_len, struct smb_fattr *fattr) { int rc = 0; -struct smb_sid *owner_sid_ptr, *group_sid_ptr; +struct smb_sid *owner_sid_ptr =NULL , *group_sid_ptr =NULL ;struct smb_acl *dacl_ptr;/* no need for SACL ptr */ char *end_of_acl = ((char *)pntsd) + acl_len;__u32 dacloffset;
@@ -908,12 +908,7 @@ int parse_sec_desc(struct mnt_idmap *idmif (acl_len <sizeof (struct smb_ntsd ))return -EINVAL ; - owner_sid_ptr = (struct smb_sid *)((char *)pntsd + -le32_to_cpu (pntsd->osidoffset)); - group_sid_ptr = (struct smb_sid *)((char *)pntsd + -le32_to_cpu (pntsd->gsidoffset)); dacloffset =le32_to_cpu (pntsd->dacloffset); - dacl_ptr = (struct smb_acl *)((char *)pntsd + dacloffset); ksmbd_debug(SMB, "revision %d type 0x%x ooffset 0x%x goffset 0x%x sacloffset 0x%x dacloffset 0x%x\n", pntsd->revision, pntsd->type, le32_to_cpu(pntsd->osidoffset),
@@ -929,9 +924,12 @@ int parse_sec_desc(struct mnt_idmap *idm pntsd->type =cpu_to_le16 (DACL_PRESENT );if (pntsd->osidoffset) { -if (le32_to_cpu (pntsd->osidoffset) <sizeof (struct smb_ntsd )) +if (le32_to_cpu (pntsd->osidoffset) <sizeof (struct smb_ntsd ) || +le32_to_cpu (pntsd->osidoffset) >= acl_len)return -EINVAL ; + owner_sid_ptr = (struct smb_sid *)((char *)pntsd + +le32_to_cpu (pntsd->osidoffset)); rc =parse_sid (owner_sid_ptr, end_of_acl);if (rc) {pr_err ("%s: Error %d parsing Owner SID\n" , __func__, rc);
@@ -947,9 +945,12 @@ int parse_sec_desc(struct mnt_idmap *idm }if (pntsd->gsidoffset) { -if (le32_to_cpu (pntsd->gsidoffset) <sizeof (struct smb_ntsd )) +if (le32_to_cpu (pntsd->gsidoffset) <sizeof (struct smb_ntsd ) || +le32_to_cpu (pntsd->gsidoffset) >= acl_len)return -EINVAL ; + group_sid_ptr = (struct smb_sid *)((char *)pntsd + +le32_to_cpu (pntsd->gsidoffset)); rc =parse_sid (group_sid_ptr, end_of_acl);if (rc) { pr_err("%s: Error %d mapping Owner SID to gid\n",
@@ -971,9 +972,10 @@ int parse_sec_desc(struct mnt_idmap *idm pntsd->type |=cpu_to_le16 (DACL_PROTECTED );if (dacloffset) { -if (dacloffset <sizeof (struct smb_ntsd )) +if (dacloffset <sizeof (struct smb_ntsd ) || dacloffset >= acl_len)return -EINVAL ; + dacl_ptr = (struct smb_acl *)((char *)pntsd + dacloffset); rc =parse_dacl (idmap, dacl_ptr, end_of_acl, owner_sid_ptr, group_sid_ptr, fattr);if (rc)
Greg Kroah-Hartman
maintainerPATCH 594/1536 tcp: Fix potential UAF in reqsk_timer_handler().
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kuniyuki Iwashima <[email protected]>
commit 97c8a3c1f73d828de43a5a88e8a9a143efb2b661 upstream.
When TCP socket migration fails at inet_ehash_insert() in reqsk_timer_handler(), we jump to the no_ownership: label and free the new reqsk immediately with __reqsk_free().
Thus, we must stop the new reqsk's timer before jumping to the label, but the timer might be missed since the cited commit, resulting in UAF.
As we are in the original reqsk's timer context, we can safely call timer_delete_sync() for the new reqsk.
Let's pass false to __inet_csk_reqsk_queue_drop() to stop the new reqsk's timer.
--- net/ipv4/inet_connection_sock.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/ipv4/inet_connection_sock.c +1 -1
@@ -1158,7 +1158,7 @@ static void reqsk_timer_handler(struct tif (!inet_ehash_insert (req_to_sk (nreq),req_to_sk (oreq),NULL )) {/* delete timer */ -__inet_csk_reqsk_queue_drop (sk_listener, nreq, true); +__inet_csk_reqsk_queue_drop (sk_listener, nreq, false); goto no_ownership; }
Greg Kroah-Hartman
maintainerPATCH 595/1536 vlan: restore HW VLAN tag insertion with reorder_hdr off
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
[ Upstream commit c2124f80be4ceb6ec566ca3b5fc87f84ea9c36e0 ]
Commit 447cbe95ebb9 ("vlan: fix skb_under_panic and races when toggling HW VLAN offload") replaced vlan_passthru_header_ops with vlan_header_ops unconditionally to avoid lockless data races when modifying hard_header_len dynamically under RTNL.
Prior to that commit, vlan devices on top of a real device capable of HW VLAN TX offload used vlan_passthru_header_ops, which never inserted the 802.1Q header in the frame.
Now, with reorder_hdr=off (as done by Home Assistant OS / NetworkManager when flags are omitted over D-Bus), vlan_dev_hard_header() always pushes an in-band 802.1Q header, and vlan_dev_hard_start_xmit() hands the frame to the real device as is, even if the real device supports HW VLAN TX offload.
This is a regression for r8169 users (Realtek RTL8168h), who report transmit queue timeouts (NETDEV WATCHDOG): this NIC stalls when asked to offload checksum and/or TSO for frames carrying an in-band tag. Users of r8152 based USB adapters were affected as well.
Reverting the blamed commit, disabling TX checksum offload (which also disables TSO), or setting reorder_hdr=on were all reported to work around the issue.
Keep vlan_dev_hard_header() as is: the in-band header keeps the frame layout seen at the vlan device egress (taps, tc, netfilter) unchanged, and is relied upon by stacked vlans (Q-in-Q) and by AF_PACKET SOCK_DGRAM users sending ETH_P_8021Q frames.
Instead, when vlan_dev_hard_start_xmit() gets a frame carrying an in-band tag with our protocol and the real device can insert tags, move that tag to skb->vlan_tci with __skb_vlan_pop(), so that the real device inserts it. Frames sent on the wire are unchanged, except that frames shorter than 64 bytes with their tag now get up to 4 bytes of extra padding, as with reorder_hdr=on and before 447cbe95ebb9.
skb_reset_mac_header() is needed first, because not all ndo_start_xmit() callers set the mac header (e.g. AF_XDP copy mode, which uses __dev_direct_xmit()).
vlan_set_encap_proto() may read the two bytes after the vlan header, so frames whose linear part is shorter than VLAN_ETH_HLEN + 2 are sent unchanged, as before. This also makes sure h_vlan_proto, read earlier in the function, was in the linear part. Shared skbs (e.g. from pktgen) are also sent unchanged, since popping the tag modifies the skb, as are skbs already carrying a hwaccel tag (e.g. from generic XDP redirect), whose tag must not be overwritten, skbs carrying XDP metadata, which the pop would have to move, and CHECKSUM_PARTIAL skbs whose csum_start lies within the first VLAN_ETH_HLEN bytes (only possible with bogus offsets, e.g. from AF_XDP tx metadata), which the pop would leave before skb->data.
If popping the header fails (memory allocation failure), the frame is dropped and counted in tx_dropped, rather than handing the real device a frame with an in-band tag.
tx_bytes is now sampled before the pop, so the vlan device statistics do not change.
This also applies to frames provided by the sender with our tag (AF_PACKET SOCK_RAW, or frames redirected from another reorder_hdr=off vlan): the real device now inserts their tag too.
--- net/8021q/vlan_dev.c | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-)
net/8021q/vlan_dev.c +32 -1
@@ -109,6 +109,8 @@ static netdev_tx_t vlan_dev_hard_start_xmit(struct sk_buff *skb,unsigned int len;int ret; + len = skb->len; +/* Handle non-VLAN frames if they are sent to us, for example by DHCP. * * NOTE: THIS ASSUMES DIX ETHERNET, SPECIFICALLY NOT SUPPORTING
@@ -120,10 +122,39 @@ static netdev_tx_t vlan_dev_hard_start_xmit(struct sk_buff *skb, vlan_tci = vlan->vlan_id; vlan_tci |=vlan_dev_get_egress_qos_mask (dev, skb->priority);__vlan_hwaccel_put_tag (skb, vlan->vlan_proto, vlan_tci); + }else if (skb_headlen (skb) >=VLAN_ETH_HLEN +sizeof (__be16) && + !skb_shared (skb) && !skb_vlan_tag_present (skb) && + !skb_metadata_len (skb) && + (skb->ip_summed !=CHECKSUM_PARTIAL || +skb_checksum_start_offset (skb) >=VLAN_ETH_HLEN ) && +vlan_hw_offload_capable (READ_ONCE (vlan->real_dev->features), + vlan->vlan_proto)) { +u16 vlan_tci; + +/* The frame carries its outer tag in-band, either inserted +* by vlan_dev_hard_header() or provided by the sender. +* Let the real device insert it: some NICs can not offload +* checksum or TSO for frames carrying an in-band tag. +* Not all ndo_start_xmit() callers set the mac header. +* vlan_set_encap_proto() may read two bytes after the vlan +* header, so frames with a shorter linear part are sent +* unchanged, as are shared skbs (e.g. from pktgen), skbs +* already carrying a hwaccel tag (e.g. from generic XDP +* redirect), skbs carrying XDP metadata, and CHECKSUM_PARTIAL +* skbs whose checksum starts within the header to be popped. +* On allocation failure, drop the frame rather than handing +* it to the real device with an in-band tag. +*/ +skb_reset_mac_header (skb); +if (unlikely (__skb_vlan_pop (skb, &vlan_tci))) { +dev_kfree_skb_any (skb); +this_cpu_inc (vlan->vlan_pcpu_stats->tx_dropped); +return NETDEV_TX_OK ; + } +__vlan_hwaccel_put_tag (skb, vlan->vlan_proto, vlan_tci); } skb->dev = vlan->real_dev; - len = skb->len;if (unlikely (netpoll_tx_running (dev)))return vlan_netpoll_send_skb (vlan, skb);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 596/1536 Revert "Bluetooth: btusb: Add ASUS USB-BT600 for Realtek 8761CU"
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christoph Zwerschke <[email protected]>
This reverts commit 32412aff8d11d00672053cb10750869f2de94a1f which is commit 6f0624b4427e38c3bb63a951c536cf8adaee1238 upstream.
With the device ID in the table, the adapter is handed over to btrtl, which in this tree, together with the backport of commit 4a23ce935f74 ("Bluetooth: btrtl: Add the support for RTL8761CUV"), now requires rtl_bt/rtl8761cu_fw.bin. That file is only shipped by linux-firmware since 20251111. On systems with older firmware packages, such as Debian trixie, the adapter no longer initializes. Without the ID entry it binds via the generic Bluetooth class and works on its ROM firmware, as it did before the backport.
Mainline keeps the ID entry, so this revert is for 6.12.y only, as agreed in the regression thread.
--- drivers/bluetooth/btusb.c | 2 -- 1 file changed, 2 deletions(-)
drivers/bluetooth/btusb.c +0 -2
@@ -820,8 +820,6 @@ static const struct usb_device_id quirks_table[] = {/* Additional Realtek 8761CU Bluetooth devices */ { USB_DEVICE(0x0b05, 0x1bef), .driver_info = BTUSB_REALTEK | BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0b05, 0x1d70), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, /* Additional Realtek 8821AE Bluetooth devices */ { USB_DEVICE(0x0b05, 0x17dc), .driver_info = BTUSB_REALTEK },
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 597/1536 Revert "Bluetooth: btusb: Add ASUS USB-BT540 for Realtek 8761CU"
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christoph Zwerschke <[email protected]>
This reverts commit f05baf6e0680d8c10d2fbbc5953848fc3e3db957 which is commit 980084de4d9b25193398d89a1c0430ba3501b683 upstream.
With the device ID in the table, the adapter is handed over to btrtl, which in this tree, together with the backport of commit 4a23ce935f74 ("Bluetooth: btrtl: Add the support for RTL8761CUV"), now requires rtl_bt/rtl8761cu_fw.bin. That file is only shipped by linux-firmware since 20251111. On systems with older firmware packages, such as Debian trixie, the adapter no longer initializes. Without the ID entry it binds via the generic Bluetooth class and works on its ROM firmware, as it did before the backport.
Mainline keeps the ID entry, so this revert is for 6.12.y only, as agreed in the regression thread.
--- drivers/bluetooth/btusb.c | 4 ---- 1 file changed, 4 deletions(-)
drivers/bluetooth/btusb.c +0 -4
@@ -817,10 +817,6 @@ static const struct usb_device_id quirks_table[] = { { USB_DEVICE(0x37ad, 0x0600), .driver_info = BTUSB_REALTEK | BTUSB_WIDEBAND_SPEECH }, - /* Additional Realtek 8761CU Bluetooth devices */ - { USB_DEVICE(0x0b05, 0x1bef), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - /* Additional Realtek 8821AE Bluetooth devices */ { USB_DEVICE(0x0b05, 0x17dc), .driver_info = BTUSB_REALTEK }, { USB_DEVICE(0x13d3, 0x3414), .driver_info = BTUSB_REALTEK },
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 598/1536 KVM: x86/mmu: pass PFERR_GUEST_PAGE/FINAL_MASK to kvm_translate_gpa
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paolo Bonzini <[email protected]>
[ Upstream commit bd1c40114b02cf63ba33da8e7df71ed0fc2a3019 ]
The XS/XU bit for EPT are only applied to final accesses, and use the U bit from the page walk itself. While strictly speaking not necessary (any value of PFERR_USER_MASK would be the same for page table accesses, because they're reads and writes only), it is clearer and less hackish to only apply MBEC to PFERR_GUEST_FINAL_MASK. Allow kvm-intel.ko to distinguish the two cases.
[doebel: load_pdptrs() lives in arch/x86/kvm/regs.c in this tree; keep
this tree's mmu_is_nested() in the Hyper-V hunk]
Stable-dep-of: 96b067b59ad9 ("KVM: VMX: Synthesize nested EPT violation GVA_IS_VALID/GVA_TRANSLATED bits")
--- arch/x86/kvm/hyperv.c | 3 ++- arch/x86/kvm/mmu/mmu.c | 3 ++- arch/x86/kvm/mmu/paging_tmpl.h | 7 +++++-- arch/x86/kvm/regs.c | 3 ++- 4 files changed, 11 insertions(+), 5 deletions(-)
arch/x86/kvm/hyperv.c +2 -1
@@ -2055,7 +2055,8 @@ static u64 kvm_hv_flush_tlb(struct kvm_vcpu *vcpu, struct kvm_hv_hcall *hc)* read with kvm_read_guest(). */ if (!hc->fast &&mmu_is_nested (vcpu)) { - hc->ingpa =translate_nested_gpa (vcpu, hc->ingpa,0 ,NULL ); + hc->ingpa =translate_nested_gpa (vcpu, hc->ingpa, +PFERR_GUEST_FINAL_MASK ,NULL );if (unlikely (hc->ingpa ==INVALID_GPA ))return HV_STATUS_INVALID_HYPERCALL_INPUT ; }
arch/x86/kvm/mmu/mmu.c +2 -1
@@ -4138,7 +4138,8 @@ static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, {if (exception) exception->error_code =0 ; -return kvm_translate_gpa (vcpu, mmu, vaddr, access, exception); +return kvm_translate_gpa (vcpu, mmu, vaddr, access |PFERR_GUEST_FINAL_MASK , + exception); }static bool mmio_info_in_cache (struct kvm_vcpu *vcpu,u64 addr,bool direct)
arch/x86/kvm/mmu/paging_tmpl.h +5 -2
@@ -377,7 +377,8 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker, walker->pte_gpa[walker->level -1 ] = pte_gpa; real_gpa =kvm_translate_gpa (vcpu, mmu,gfn_to_gpa (table_gfn), - nested_access, &walker->fault); + nested_access |PFERR_GUEST_PAGE_MASK , + &walker->fault);/* * FIXME: This can happen if emulation (for of an INS/OUTS
@@ -445,7 +446,9 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker, gfn +=pse36_gfn_delta (pte);#endif - real_gpa =kvm_translate_gpa (vcpu, mmu,gfn_to_gpa (gfn), access, &walker->fault); + real_gpa =kvm_translate_gpa (vcpu, mmu,gfn_to_gpa (gfn), + access |PFERR_GUEST_FINAL_MASK , + &walker->fault);if (real_gpa ==INVALID_GPA )return 0 ;
arch/x86/kvm/regs.c +2 -1
@@ -166,7 +166,8 @@ int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)* to an L1 GPA. */ real_gpa =kvm_translate_gpa (vcpu, mmu,gfn_to_gpa (pdpt_gfn), -PFERR_USER_MASK |PFERR_WRITE_MASK ,NULL ); +PFERR_USER_MASK |PFERR_WRITE_MASK | +PFERR_GUEST_PAGE_MASK ,NULL );if (real_gpa ==INVALID_GPA )return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 599/1536 KVM: x86: Tell ->inject_page_fault() whether or a fault came from hardware
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit fe0b872d750023eda270cbc01c53ead52b1049d8 ]
When injecting a page fault (including nested TDP faults into L1), tell the injection routine whether or not the fault originated in hardware, i.e. if KVM is effectively forwarding a fault it intercept. For nested TDP fault injection, KVM needs to grab PAGE_WALK vs. GUEST_FINAL information from the VMCB/VMCS, _if_ the fault originated in hardware.
Note, simply checking whether or not the original exit was due a #NPF or EPT Violation isn't sufficient/correct, as the fault being synthesized for L1 may or may not be the "same" fault that triggered a VM-Exit from L2. E.g. if access to emulated MMIO in L2 hits a !PRESENT fault (EPT Violation or #NPF), e.g. because MMIO caching is disabled or it's the first time the GPA has been accessed by L2, then KVM will enter the emulator. If emulating the MMIO instruction then hits a nested TDP fault, e.g. because L2 was accessing MMIO with a MOVSQ (memory-to-memory move), or because L1 has since unmapped the code stream, then the TDP fault synthesized to L1 will not be the same emulated fault the triggered the VM-Exit.
No functional change intended (nothing uses the new param, yet...).
[doebel: keep this tree's split kvm_requeue_exception()/_e()
declarations and EXPORT_SYMBOL_GPL()]
Stable-dep-of: 96b067b59ad9 ("KVM: VMX: Synthesize nested EPT violation GVA_IS_VALID/GVA_TRANSLATED bits")
--- arch/x86/include/asm/kvm_host.h | 18 ++++++++++++++---- arch/x86/kvm/mmu/paging_tmpl.h | 2 +- arch/x86/kvm/svm/nested.c | 3 ++- arch/x86/kvm/vmx/nested.c | 3 ++- arch/x86/kvm/x86.c | 16 +++++++++------- 5 files changed, 28 insertions(+), 14 deletions(-)
arch/x86/include/asm/kvm_host.h +14 -4
@@ -451,7 +451,8 @@ struct kvm_mmu {u64 (*get_pdptr)(struct kvm_vcpu *vcpu,int index);int (*page_fault)(struct kvm_vcpu *vcpu,struct kvm_page_fault *fault);void (*inject_page_fault)(struct kvm_vcpu *vcpu, -struct x86_exception *fault); +struct x86_exception *fault, +bool from_hardware);gpa_t (*gva_to_gpa)(struct kvm_vcpu *vcpu,struct kvm_mmu *mmu,gpa_t gva_or_gpa,u64 access,struct x86_exception *exception);
@@ -2140,9 +2141,18 @@ void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code);void kvm_queue_exception_p (struct kvm_vcpu *vcpu,unsigned nr,unsigned long payload);void kvm_requeue_exception (struct kvm_vcpu *vcpu,unsigned nr);void kvm_requeue_exception_e (struct kvm_vcpu *vcpu,unsigned nr,u32 error_code); -void kvm_inject_page_fault (struct kvm_vcpu *vcpu,struct x86_exception *fault); -void kvm_inject_emulated_page_fault (struct kvm_vcpu *vcpu, -struct x86_exception *fault); +void kvm_inject_page_fault (struct kvm_vcpu *vcpu,struct x86_exception *fault, +bool from_hardware); +void __kvm_inject_emulated_page_fault (struct kvm_vcpu *vcpu, +struct x86_exception *fault, +bool from_hardware); + +static inline void kvm_inject_emulated_page_fault (struct kvm_vcpu *vcpu, +struct x86_exception *fault) +{ +__kvm_inject_emulated_page_fault (vcpu, fault, false); +} +bool kvm_require_cpl (struct kvm_vcpu *vcpu,int required_cpl);bool kvm_require_dr (struct kvm_vcpu *vcpu,int dr);
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
@@ -799,7 +799,7 @@ static int FNAME(page_fault)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault*/ if (!r) {if (!fault->prefetch) -kvm_inject_emulated_page_fault (vcpu, &walker.fault); +__kvm_inject_emulated_page_fault (vcpu, &walker.fault, true);return RET_PF_RETRY ; }
arch/x86/kvm/svm/nested.c +2 -1
@@ -34,7 +34,8 @@#define CC KVM_NESTED_VMENTER_CONSISTENCY_CHECKstatic void nested_svm_inject_npf_exit (struct kvm_vcpu *vcpu, -struct x86_exception *fault) +struct x86_exception *fault, +bool from_hardware) {struct vcpu_svm *svm =to_svm (vcpu);struct vmcb *vmcb = svm->vmcb;
arch/x86/kvm/vmx/nested.c +2 -1
@@ -414,7 +414,8 @@ static void nested_ept_invalidate_addr(struct kvm_vcpu *vcpu, gpa_t eptp, }static void nested_ept_inject_page_fault (struct kvm_vcpu *vcpu, -struct x86_exception *fault) +struct x86_exception *fault, +bool from_hardware) {struct vmcs12 *vmcs12 =get_vmcs12 (vcpu);struct vcpu_vmx *vmx =to_vmx (vcpu);
arch/x86/kvm/x86.c +9 -7
@@ -921,7 +921,8 @@ static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err) EMULTYPE_COMPLETE_USER_EXIT); } -void kvm_inject_page_fault (struct kvm_vcpu *vcpu,struct x86_exception *fault) +void kvm_inject_page_fault (struct kvm_vcpu *vcpu,struct x86_exception *fault, +bool from_hardware) { ++vcpu->stat.pf_guest;
@@ -938,8 +939,9 @@ void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault) fault->address); } -void kvm_inject_emulated_page_fault (struct kvm_vcpu *vcpu, -struct x86_exception *fault) +void __kvm_inject_emulated_page_fault (struct kvm_vcpu *vcpu, +struct x86_exception *fault, +bool from_hardware) {struct kvm_mmu *fault_mmu;WARN_ON_ONCE (fault->vector !=PF_VECTOR );
@@ -956,9 +958,9 @@ void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,kvm_mmu_invalidate_addr (vcpu, fault_mmu, fault->address,KVM_MMU_ROOT_CURRENT ); - fault_mmu->inject_page_fault (vcpu, fault); + fault_mmu->inject_page_fault (vcpu, fault, from_hardware); } -EXPORT_SYMBOL_GPL (kvm_inject_emulated_page_fault); +EXPORT_SYMBOL_GPL (__kvm_inject_emulated_page_fault);void kvm_inject_nmi (struct kvm_vcpu *vcpu) {
@@ -12661,7 +12663,7 @@ bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu, fault.nested_page_fault = false; fault.address = work->arch.token; fault.async_page_fault = true; -kvm_inject_page_fault (vcpu, &fault); +kvm_inject_page_fault (vcpu, &fault, false);return true; }else {/*
@@ -12917,7 +12919,7 @@ void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_c fault.address = gva; fault.async_page_fault = false; } - vcpu->arch.walk_mmu->inject_page_fault (vcpu, &fault); + vcpu->arch.walk_mmu->inject_page_fault (vcpu, &fault, true); }EXPORT_SYMBOL_GPL (kvm_fixup_and_inject_pf_error);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 600/1536 KVM: VMX: Synthesize nested EPT violation GVA_IS_VALID/GVA_TRANSLATED bits
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kevin Cheng <[email protected]>
[ Upstream commit 96b067b59ad9ccede585fcadab27543188353bff ]
When injecting an EPT Violation into L2 in response to a fault detected while emulating an L2 GVA access, synthesize the GVA_IS_VALID and GVA_TRANSLATED bits using information provided by the walker, instead of pulling the bits from vmcs02.EXIT_QUALIFICATION. The information in vmcs02.EXIT_QUALIFICATION is valid/correct if and only if the fault being injected into L1 is the direct result of an EPT Violation VM-Exit from L2.
E.g. if KVM is emulating an I/O instruction and the memory operand's translation through L1's EPT fails, using vmcs02.EXIT_QUALIFICATION is wrong as the semantics for EXIT_QUALIFICATION would be for an I/O exit, not an EPT Violation exit.
Opportunistically clean up the formatting for creating the mask of bits to pull from vmcs02.EXIT_QUALIFICATION.
[doebel: no advanced EPT vmexit info here, so the mask keeps only the two GVA bits; set GVA_TRANSLATED via !(access & PFERR_GUEST_PAGE_MASK)]
--- arch/x86/kvm/mmu/paging_tmpl.h | 17 ++++++++++++++++- arch/x86/kvm/vmx/nested.c | 23 +++++++++++++++++++---- 2 files changed, 35 insertions(+), 5 deletions(-)
arch/x86/kvm/mmu/paging_tmpl.h +16 -1
@@ -495,7 +495,7 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,* [2:0] - Derive from the access bits. The exit_qualification might be * out of date if it is serving an EPT misconfiguration. * [5:3] - Calculated by the page walk of the guest EPT page tables -* [7:8] - Derived from [7:8] of real exit_qualification +* [7:8] - Derived from "fault stage" access bits * * The other bits are set to 0. */
@@ -509,6 +509,21 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,if (fetch_fault) walker->fault.exit_qualification |=EPT_VIOLATION_ACC_INSTR ; +/* +* KVM doesn't emulate features that access GPAs directly, e.g. +* Intel Processor Trace. Assume the GVA is always valid; when +* propagating faults from hardware, KVM will discard this info +* and use the EXIT_QUALIFICATION bits from the VMCS. +*/ + walker->fault.exit_qualification |=EPT_VIOLATION_GVA_IS_VALID ; + +/* +* Accesses to guest paging structures are not the translation of +* a guest linear address, i.e. GVA_TRANSLATED must be left clear. +*/ +if (!(access &PFERR_GUEST_PAGE_MASK )) + walker->fault.exit_qualification |=EPT_VIOLATION_GVA_TRANSLATED ; +/* * Note, pte_access holds the raw RWX bits from the EPTE, not * ACC_*_MASK flags!
arch/x86/kvm/vmx/nested.c +19 -4
@@ -447,10 +447,25 @@ static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu, vm_exit_reason =EXIT_REASON_EPT_MISCONFIG ; exit_qualification =0 ; }else { - exit_qualification = fault->exit_qualification; - exit_qualification |=vmx_get_exit_qual (vcpu) & - (EPT_VIOLATION_GVA_IS_VALID | -EPT_VIOLATION_GVA_TRANSLATED ); +const u64 mask =EPT_VIOLATION_GVA_IS_VALID | +EPT_VIOLATION_GVA_TRANSLATED ; + + exit_qualification = fault->exit_qualification & ~mask; + +/* +* Use the EXIT_QUALIFICATION from the VMCS if and only +* if the hardware VM-Exit from L2 was an EPT Violation. +* If the fault is synthesized, then EXIT_QUALIFICATION +* is stale and/or holds entirely different data. And +* conversely, KVM _must_ rely on EXIT_QUALIFICATION if +* the fault came from hardware, because KVM only sees +* and walks the faulting GPA. +*/ +if (from_hardware) + exit_qualification |=vmx_get_exit_qual (vcpu) & mask; +else + exit_qualification |= fault->exit_qualification & mask; + vm_exit_reason =EXIT_REASON_EPT_VIOLATION ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 601/1536 x86/ioperm: Prevent NULL dereference on theoretical missing IO bitmap
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li RongQing <[email protected]>
[ Upstream commit 2d36d3b451a94899db9c965adde15492ffe6027a ]
Outside the IOPL emulation path, the IO bitmap is always expected to be allocated when TIF_IO_BITMAP is set. The paranoid WARN_ON_ONCE() handles the case where the flag and the pointer got out of sync. In this theoretical scenario, which presumes some other bug in the code that triggers the WARN_ON_ONCe(), return early, instead of continuing and dereferencing a NULL pointer.
[ mingo: Clarified the changelog. ]
--- arch/x86/kernel/process.c | 1 + 1 file changed, 1 insertion(+)
arch/x86/kernel/process.c +1 -0
@@ -472,6 +472,7 @@ void native_tss_update_io_bitmap(void)if (WARN_ON_ONCE (!iobm)) {clear_thread_flag (TIF_IO_BITMAP );native_tss_invalidate_io_bitmap (); +return ; }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 602/1536 wifi: b43: fix use-after-free in b43_bcma_remove()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andreas Wendleder <[email protected]>
commit c6c8bc355657115664131b38c53c5ddf7d93b072 upstream.
b43_one_core_detach() frees the struct b43_wldev it is given the bus device of. b43_bcma_remove() then reads wldev->dev again to free the bus device, which is a read of freed memory.
b43_ssb_remove() does not have the problem: it takes a copy of wldev->dev at the start. Do the same here.
--- drivers/net/wireless/broadcom/b43/main.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/wireless/broadcom/b43/main.c +3 -2
@@ -5663,6 +5663,7 @@ static void b43_bcma_remove(struct bcma_ {struct b43_wldev *wldev =bcma_get_drvdata (core);struct b43_wl *wl = wldev->wl; +struct b43_bus_dev *dev = wldev->dev;/* We must cancel any work here before unregistering from ieee80211, * as the ieee80211 unreg will destroy the workqueue. */
@@ -5677,14 +5678,14 @@ static void b43_bcma_remove(struct bcma_ieee80211_unregister_hw (wl->hw); } -b43_one_core_detach (wldev->dev); +b43_one_core_detach (dev);/* Unregister HW RNG driver */ b43_rng_exit (wl);b43_leds_unregister (wl);ieee80211_free_hw (wl->hw); -kfree (wldev->dev); +kfree (dev); }static struct bcma_driver b43_bcma_driver = {
Greg Kroah-Hartman
maintainerPATCH 603/1536 SUNRPC: fix netns use-after-free in write_gssp()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zijing Yin <[email protected]>
commit e7a8721b7edb54a157623f9e31d71345333b5fb9 upstream.
While fuzzing with a customized syzkaller, I hit a refcount warning in xprt_alloc(), reached from a write to /proc/net/rpc/use-gss-proxy:
refcount_t: addition on 0; use-after-free.
WARNING: lib/refcount.c:25 at refcount_warn_saturate+0xf8/0x120 CPU: 0 PID: 10404 Comm: syz.0.17 Not tainted 7.3.0-rc1-00096-gcfebfd3db73d Call Trace: <TASK> xprt_alloc+0x83f/0x9d0 xs_setup_xprt+0xaf/0x3c0 xs_setup_local+0x47/0x7f0 xprt_create_transport+0x16c/0x730 rpc_create+0x38e/0x7f0 gssp_rpc_create+0xe2/0x180 set_gssp_clnt+0xba/0x1b0 write_gssp+0x200/0x310 proc_reg_write+0x240/0x330 vfs_write+0x2aa/0x1050 ksys_write+0x12a/0x250 do_syscall_64+0x117/0x750 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK>
create_use_gss_proxy_proc_entry() stores the struct net pointer as the proc entry's private data without taking a reference on it, and an open file descriptor does not pin the namespace either, as procfs only pins the proc_dir_entry. write_gssp() reads that pointer back with pde_data() and hands it to set_gssp_clnt(), which reaches xprt_init():
xprt->xprt_net = get_net_track(net, &xprt->ns_tracker, GFP_KERNEL);
get_net_track() -> get_net() -> refcount_inc() is unconditional, so rpc_create() assumes its caller holds a reference on args.net. write_gssp() does not.
Dropping the last ns.count reference does not make the file go away. __put_net() only queues cleanup_net() on a workqueue, and the remove_proc_entry() that fences off further writes runs from the rpcsec_gss pernet .exit method, that is, from inside cleanup_net(). A write landing between those two points increments a refcount that is already zero. cleanup_net() does not re-read ns.count, so the namespace is freed anyway and the rpc_xprt -- along with the AF_LOCAL socket opened for it -- is left pointing at freed memory. The resurrected count is visible to the rest of that teardown too: with CONFIG_IPV6_MROUTE the same cleanup_net() worker then trips !mr_can_free_table() in ip6mr_free_table(), which tests check_net() on the namespace it is freeing.
It reduces to opening /proc/net/rpc/use-gss-proxy inside a new network namespace, calling setns() back to the original one to drop the last reference, and then writing "1" to the still-open descriptor.
Take the reference in write_gssp() itself and refuse the write when the namespace is already gone. This is what procfs does for every other /proc/net file: get_proc_net() is maybe_get_net(PDE_NET(PDE(inode))) and seq_open_net() returns -ENXIO when it fails. PDE_NET() cannot be reused here because the parent directory /proc/net/rpc carries no namespace pointer. Adding a .pre_exit to rpcsec_gss_net_ops so the entry is removed earlier would only narrow the window, since pre_exit also runs from cleanup_net().
Live namespaces are unaffected: a write still returns the error from set_gssp_clnt(), a write of "2" still returns -EINVAL, and reads are untouched.
--- net/sunrpc/auth_gss/svcauth_gss.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-)
net/sunrpc/auth_gss/svcauth_gss.c +11 -3
@@ -1420,10 +1420,18 @@ static ssize_t write_gssp(struct file *freturn res;if (i !=1 )return -EINVAL ; + +/* +* Neither the proc entry nor an open descriptor pins @net, so it +* might already be dying when rpc_create() takes its reference. +*/ +if (!maybe_get_net (net)) +return -ENXIO ; + res =set_gssp_clnt (net); -if (res) -return res; - res =set_gss_proxy (net,1 ); +if (!res) + res =set_gss_proxy (net,1 ); +put_net (net);if (res)return res;return count;
Greg Kroah-Hartman
maintainerPATCH 604/1536 smb: client: fix use-after-free infoleak via the readdir resume name
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Diego Oliva <[email protected]>
commit 59131dd72f62b198fc9ea1489ad9d3573154f684 upstream.
CIFSFindNext() copies the resume name that cifs_save_resume_key() recorded from the last entry of the previous response into its request; psrch_inf->presume_name points into the response buffer that entry came from, and nothing ever clears it. find_cifs_entry() records a new name only from a response with a usable last entry, and cifs_readdir() only from an entry it walks to, so a response that carries no entries and leaves last_entry NULL, because CIFSFindFirst() or CIFSFindNext() rejected LastNameOffset, refreshes neither and presume_name keeps pointing into the previous response. That buffer has already been
released: by CIFSFindNext() before it installs the new response, or by find_cifs_entry() when it rewinds the search, which does not drop the name either and can then fail in initiate_cifs_search() before a new response replaces it. The next CIFSFindNext() then copies up to PATH_MAX - 1 bytes of the resume name out of the released buffer into its request and sends them to the server: a use-after-free read that leaks kernel memory to a malicious or compromised server, which can provoke it with a single FindNext response that carries no entries and a LastNameOffset above CIFSMaxBufSize, which is all the existing check rejects.
With KASAN enabled, a server that answers a listing that way gives:
CIFS: VFS: ignoring corrupt resume name
==================================================================
BUG: KASAN: slab-use-after-free in CIFSFindNext+0x8ca/0x14c0 Read of size 4080 at addr ffff88807c823f98 by task ls/83 CPU: 0 UID: 0 PID: 83 Comm: ls Tainted: G B 7.3.0-rc4-00457-gf14572c203d5 #69 PREEMPT(lazy) Tainted: [B]=BAD_PAGE Call Trace: <TASK> kasan_report+0xdf/0x1a0 kasan_check_range+0x10f/0x1e0 __asan_memcpy+0x23/0x60 CIFSFindNext+0x8ca/0x14c0 cifs_readdir+0xf51/0x29c0 iterate_dir+0x1c0/0x570 __x64_sys_getdents64+0x133/0x270 do_syscall_64+0x109/0x5d0 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK> Allocated by task 83 on cpu 1 at 13.497119s: cifs_buf_get+0x36/0x90 smb_init+0x4f/0x110 CIFSFindNext+0xf7/0x14c0 cifs_readdir+0xf51/0x29c0 Freed by task 83 on cpu 0 at 13.584018s: cifs_buf_release+0x41/0x80 CIFSFindNext+0xfce/0x14c0 cifs_readdir+0xf51/0x29c0
The buggy address is located 16280 bytes inside of
freed 16588-byte region [ffff88807c820000, ffff88807c8240cc)
==================================================================
The same memcpy() first reads past the end of that object while it is still live, a slab-out-of-bounds read that the following patches bound; that is the taint the report above carries.
SMB1 is not negotiated by default; reaching this code requires an explicit vers=1.0 mount.
Clear presume_name and resume_name_len whenever a new response is installed and when the rewind path releases the search buffer, so that the name never outlives the buffer it points into, and reset resume_key with them, since it was taken from the same entry and would otherwise be sent with an empty name. A response without a usable last entry then continues the search with an empty resume name rather than a stale one; CIFSFindNext() skips the copy of a zero-length name so that it never runs on the NULL pointer.
The next patch in the series leaves last_entry NULL for a response that carries no entries, and bounds LastNameOffset against the received response rather than against CIFSMaxBufSize. Responses that are given a last entry today then take the path fixed here, so that patch must not be applied without this one.
--- fs/smb/client/cifssmb.c | 11 ++++++++++- fs/smb/client/readdir.c | 3 +++ 2 files changed, 13 insertions(+), 1 deletion(-)
fs/smb/client/cifssmb.c +10 -1
@@ -4131,6 +4131,9 @@ findFirstRetry: psrch_inf->entries_in_buffer =le16_to_cpu (parms->SearchCount); psrch_inf->index_of_last_entry =2 /* skip . and .. */ + psrch_inf->entries_in_buffer; + psrch_inf->presume_name =NULL ; + psrch_inf->resume_name_len =0 ; + psrch_inf->resume_key =0 ; lnoff =le16_to_cpu (parms->LastNameOffset);if (CIFSMaxBufSize < lnoff) {cifs_dbg (VFS ,"ignoring corrupt resume name\n" );
@@ -4194,7 +4197,10 @@ int CIFSFindNext(const unsigned int xid, name_len = psrch_inf->resume_name_len; params += name_len;if (name_len <PATH_MAX ) { -memcpy (pSMB->ResumeFileName, psrch_inf->presume_name, name_len); +if (name_len) { +memcpy (pSMB->ResumeFileName, + psrch_inf->presume_name, name_len); + } byte_count += name_len;/* 14 byte parm len above enough for 2 byte null terminator */ pSMB->ResumeFileName[name_len] =0 ;
@@ -4249,6 +4255,9 @@ int CIFSFindNext(const unsigned int xid, psrch_inf->endOfSearch = !!parms->EndofSearch; psrch_inf->entries_in_buffer =le16_to_cpu (parms->SearchCount); psrch_inf->index_of_last_entry += psrch_inf->entries_in_buffer; + psrch_inf->presume_name =NULL ; + psrch_inf->resume_name_len =0 ; + psrch_inf->resume_key =0 ; lnoff =le16_to_cpu (parms->LastNameOffset);if (CIFSMaxBufSize < lnoff) {cifs_dbg (VFS ,"ignoring corrupt resume name\n" );
fs/smb/client/readdir.c +3 -0
@@ -748,6 +748,9 @@ find_cifs_entry(const unsigned int xid, cfile->srch_inf.ntwrk_buf_start =NULL ; cfile->srch_inf.srch_entries_start =NULL ; cfile->srch_inf.last_entry =NULL ; + cfile->srch_inf.presume_name =NULL ; + cfile->srch_inf.resume_name_len =0 ; + cfile->srch_inf.resume_key =0 ; } rc =initiate_cifs_search (xid, file, full_path);if (rc) {
Greg Kroah-Hartman
maintainerPATCH 605/1536 smb: client: fix use-after-free in cifs_ses_add_channel()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Henry Martin <[email protected]>
commit 031278577380e7875d95aed81a2b2bcac39be923 upstream.
The error path of cifs_ses_add_channel() calls cifs_put_tcp_session() before cifs_chan_clear_need_reconnect(). The latter reaches cifs_ses_get_chan_index(), which dereferences server->terminate; if the put was the final reference, TCP_Server_Info is already freed and this is a use-after-free. Same put-then-use pattern as the recently fixed sibling in commit 717e0a25036b ("cifs: Fix server use-after-free in cifs_chan_skip_or_disable()").
Move the put last, but do not read chan->server after droppingchan_lock: chan points into ses->chans[], and once chan_count is decremented a concurrent add_channel can reuse the slot and overwrite the pointer, so the put would act on the new channel's server. Cache the pointer under chan_lock, clear the reconnect bit and decrement chan_count while still holding the reference, and release it after the unlock.
This issue was discovered by Tencent CodeBuddy Security.
--- fs/smb/client/sess.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/client/sess.c +4 -2
@@ -648,12 +648,13 @@ cifs_ses_add_channel(struct cifs_ses *se out:if (rc && chan->server) { -cifs_put_tcp_session (chan->server,0 ); +struct TCP_Server_Info *pserver;spin_lock (&ses->chan_lock); + pserver = chan->server;/* we rely on all bits beyond chan_count to be clear */ -cifs_chan_clear_need_reconnect (ses, chan->server); +cifs_chan_clear_need_reconnect (ses, pserver); ses->chan_count--;/* * chan_count should never reach 0 as at least the primary
@@ -661,6 +662,7 @@ out:*/ WARN_ON (ses->chan_count <1 );spin_unlock (&ses->chan_lock); +cifs_put_tcp_session (pserver,0 ); }kfree (ctx->UNC);
Greg Kroah-Hartman
maintainerPATCH 606/1536 rapidio: mport_cdev: fix use-after-free in mport_mm_close()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: James Kim <[email protected]>
commit 0f2cd84858e67cf8e02438bf28243bcdc67aa49a upstream.
A use-after-free vulnerability was identified in mport_mm_close() in drivers/rapidio/devices/rio_mport_cdev.c, identical to the pattern previously addressed in dma_req_free().
This is observable from userspace when an application creates an mmap mapping via the RapidIO character device and subsequently unmaps it (or terminates, triggering exit_mmap()). During munmap, mport_mm_close() is invoked and drops the mapping reference via kref_put().
If kref_put() drops the last reference, mport_release_mapping() is called, which frees the underlying rio_mport_mapping structure. The subsequent mutex_unlock() then dereferences map->md to unlock buf_mutex, leading to a use-after-free:
mport_mm_close()
-> mutex_lock(&map->md->buf_mutex);
...
-> kref_put(&map->ref, mport_release_mapping); /* map is freed */
-> mutex_unlock(&map->md->buf_mutex); /* UAF: map used */Fix this by caching map->md before kref_put() and using the cached pointer for mutex unlocking, ensuring that freed memory is not accessed.
--- drivers/rapidio/devices/rio_mport_cdev.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/rapidio/devices/rio_mport_cdev.c +3 -2
@@ -2188,11 +2188,12 @@ static void mport_mm_open(struct vm_areastatic void mport_mm_close (struct vm_area_struct *vma) {struct rio_mport_mapping *map = vma->vm_private_data; +struct mport_dev *md = map->md;rmcd_debug (MMAP ,"%pad" , &map->phys_addr); -mutex_lock (&map->md->buf_mutex); +mutex_lock (&md->buf_mutex);kref_put (&map->ref, mport_release_mapping); -mutex_unlock (&map->md->buf_mutex); +mutex_unlock (&md->buf_mutex); }static const struct vm_operations_struct vm_ops = {
Greg Kroah-Hartman
maintainerPATCH 607/1536 nvmet-fc: fix use-after-free in nvmet_fc_ls_create_connection()
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 2c29f8c9b9e598c09fa50aa02200136a107f6b3f upstream.
nvmet_fc_ls_create_connection() looks up the association with nvmet_fc_find_target_assoc(), which returns it with a reference held, and drops that reference as soon as the target queue has been allocated. iod->assoc is then dereferenced again by nvmet_fc_makeconnid() while building the connection id.
The queue only borrows the pointer and takes no reference of its own. Once the lookup reference is dropped the association is kept alive solely by the reference taken when it was created, so a disconnect LS or a remote port unregister running concurrently can free it before nvmet_fc_makeconnid() reads it:
BUG: KASAN: slab-use-after-free in nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:193 drivers/nvme/target/fc.c:1841 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021) Read of size 8 at addr ffff888179f1b000 by task kworker/u9:2/1167 Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 Workqueue: nvmet-wq nvmet_fc_handle_ls_rqst_work Call Trace: <TASK> dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120) print_report (mm/kasan/report.c:378 mm/kasan/report.c:482) kasan_report (mm/kasan/report.c:595) nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:193 drivers/nvme/target/fc.c:1841 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021) process_scheduled_works (kernel/workqueue.c:3322 kernel/workqueue.c:3405) worker_thread (kernel/workqueue.c:3486) kthread (kernel/kthread.c:436) ret_from_fork (archkernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) </TASK> Freed by task 1167 on cpu 0 at 405.998150s: kasan_save_track (mm/kasan/common.c:57 mm/kasan/common.c:78) kasan_save_free_info (mm/kasan/generic.c:584) __kasan_slab_free (mm/kasan/common.c:253 mm/kasan/common.c:285) kfree (include/linux/kasan.h:235 mm/slub.c:2705 mm/slub.c:6405 mm/slub.c:6720) nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:1808 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021) process_scheduled_works (kernel/workqueue.c:3322 kernel/workqueue.c:3405) worker_thread (kernel/workqueue.c:3486) kthread (kernel/kthread.c:436) ret_from_fork (archkernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) The buggy address belongs to the object at ffff888179f1b000 which belongs to the cache kmalloc-2k of size 2048
The buggy address is located 0 bytes inside of
freed 2048-byte region [ffff888179f1b000, ffff888179f1b800)
Hold the lookup reference until the response has been built, and drop it on the error path as well.
--- drivers/nvme/target/fc.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/nvme/target/fc.c +5 -3
@@ -1777,9 +1777,6 @@ nvmet_fc_ls_create_connection(struct nvm be16_to_cpu(rqst->connect_cmd.sqsize));if (!queue) ret =VERR_QUEUE_ALLOC_FAIL ; - -/* release get taken in nvmet_fc_find_target_assoc */ -nvmet_fc_tgt_a_put (iod->assoc); } }
@@ -1793,6 +1790,8 @@ nvmet_fc_ls_create_connection(struct nvm FCNVME_RJT_RC_INV_ASSOC :FCNVME_RJT_RC_LOGIC , FCNVME_RJT_EXP_NONE, 0); +if (iod->assoc) +nvmet_fc_tgt_a_put (iod->assoc);return ; }
@@ -1814,6 +1813,9 @@ nvmet_fc_ls_create_connection(struct nvm acc->connectid.connection_id =cpu_to_be64 (nvmet_fc_makeconnid (iod->assoc,be16_to_cpu (rqst->connect_cmd.qid))); + +/* release get taken in nvmet_fc_find_target_assoc */ +nvmet_fc_tgt_a_put (iod->assoc); }/*
Greg Kroah-Hartman
maintainerPATCH 608/1536 landlock: Fix superblock use-after-free in release_inode()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Günther Noack <[email protected]>
commit 3e271a27c46fd591d1011c7de5a644a41e2010f1 upstream.
Without this fix, release_inode() (task 1) can race with a umount operation in hook_sb_delete() (task 2). The order of operations in which the race occurs is:
* task 2: hook_sb_delete() arrives at the end of the function, waiting for landlock_superblock(sb)->inode_refs to become zero.
* task 1: release_inode(): does atomic_long_dec_and_test(), decrementing inode_refs to zero.
* task 2: gets woken up through some other means, sees that inode_refs is zero and returns. The caller is the unmount operation and proceeds to release the superblock.
* task 1: Runs wake_up_var(&landlock_superblock(sb)->inode_refs), *dereferencing the sb_security on the freed-up superblock*.
Notably, wake_up_var() does not dereference the pointer passed to it, and only uses it to determine an overapproximated set of tasks to wake up. So while it's potentially possible for an attacker to provide a different value for that pointer, this only results in the wrong set of tasks getting woken up, and in this scenario, no further tasks are actually waiting.
Nevertheless, KASAN detects it as a slab-use-after-free read on sb->s_security:
BUG: KASAN: slab-use-after-free in release_inode+0x196/0x290 Read of size 8 at addr ffff888103b6c0a8 by task repro/217 release_inode+0x196/0x290 landlock_put_object+0x71/0x90 landlock_free_rules+0x38/0xc0 landlock_put_ruleset+0x47/0x130 fop_ruleset_release+0x33/0x40 __fput+0x305/0x780 Freed by task 54: kfree+0x11c/0x390 process_scheduled_works+0x766/0xe50 worker_thread+0x7bc/0xb20
The fix is to determine &landlock_superblock(inode->i_sb)->inode_refs only once earlier in release_inode(), and later use that precalculated address for the wake_up_var() call, without having to dereference through the superblock.
--- security/landlock/fs.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)
security/landlock/fs.c +5 -5
@@ -53,7 +53,7 @@ static void release_inode(struct landloc __releases(object->lock) {struct inode *const inode = object->underobj; -struct super_block *sb; +atomic_long_t *inode_refs;if (!inode) {spin_unlock (&object->lock);
@@ -69,8 +69,8 @@ static void release_inode(struct landloc* Makes sure that if the filesystem is concurrently unmounted, * hook_sb_delete() will wait for us to finish iput(). */ - sb = inode->i_sb; -atomic_long_inc (&landlock_superblock (sb)->inode_refs); + inode_refs = &landlock_superblock (inode->i_sb)->inode_refs; +atomic_long_inc (inode_refs);spin_unlock (&object->lock);/* * Because object->underobj was not NULL, hook_sb_delete() and
@@ -84,8 +84,8 @@ static void release_inode(struct landloc*/ iput (inode); -if (atomic_long_dec_and_test (&landlock_superblock (sb)->inode_refs)) -wake_up_var (&landlock_superblock (sb)->inode_refs); +if (atomic_long_dec_and_test (inode_refs)) +wake_up_var (inode_refs); }static const struct landlock_object_underops landlock_fs_underops = {
Greg Kroah-Hartman
maintainerPATCH 609/1536 lockd: Fix use-after-free in nlmsvc_retry_blocked
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit f5b7634f0f213299a07b461fb10385c8639a4ab8 upstream.
nlmsvc_retry_blocked() examines the block at the head of nlm_blocked under nlm_blocked_lock, then releases the lock before calling nlmsvc_grant_blocked() or retry_deferred_block(). The nlm_blocked list reference is all that keeps the block alive across that window. nlmsvc_grant_blocked() does take one of its own, but not until after the lock has been dropped. Unmounting the nfsd filesystem while a lock request is still blocked reaches nlmsvc_traverse_blocks(), which drops the list reference and frees the block along with the nlm_rqst hanging off it.
BUG: KASAN: slab-use-after-free in nlm_async_call+0xd6/0x230
Read of size 8 at addr ffff88811b04c808 by task lockd/8377
nlm_async_call+0xd6/0x230
nlmsvc_retry_blocked+0x61c/0x800
lockd+0x144/0x1c0
Freed by task 8392:
nlmsvc_release_block+0x231/0x290
nlmsvc_traverse_blocks+0x139/0x1b0
nlm_traverse_files+0x1aa/0xa00
nlmsvc_free_host_resources+0x12/0x60
nlm_shutdown_hosts_net+0x127/0x280
lockd_down+0xd5/0x1c0Take a reference before releasing nlm_blocked_lock and drop it once the retry has run.
--- fs/lockd/svclock.c | 2 ++ 1 file changed, 2 insertions(+)
fs/lockd/svclock.c +2 -0
@@ -1051,6 +1051,7 @@ nlmsvc_retry_blocked(struct svc_rqst *rq timeout = block->b_when - jiffies;break ; } +kref_get (&block->b_count);spin_unlock (&nlm_blocked_lock); dprintk("nlmsvc_retry_blocked(%p, when=%ld)\n",
@@ -1061,6 +1062,7 @@ nlmsvc_retry_blocked(struct svc_rqst *rqretry_deferred_block (block); }else nlmsvc_grant_blocked (block); +nlmsvc_release_block (block);spin_lock (&nlm_blocked_lock); }spin_unlock (&nlm_blocked_lock);
Greg Kroah-Hartman
maintainerPATCH 610/1536 media: au0828: fix use-after-free in bulk_timeout timer on disconnect
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 521030837bee352515d5ea57cc6a29581db3506e upstream.
start_urb_transfer() arms dev->bulk_timeout, whose callback au0828_bulk_timeout() queues dev->restart_streaming; that work in turn calls start_urb_transfer() and re-arms the timer.
au0828_dvb_unregister() cancels restart_streaming on disconnect but does not sync bulk_timeout. au0828_usb_release() then frees dev with kfree(), so a timer still armed or pending at that point can fire after the free and dereference dev through timer_container_of().
Sync the timer with timer_shutdown_sync() before cancel_work_sync(). The timer callback queues the work, so the timer must be stopped first; the shutdown variant is needed because the work re-arms the timer through start_urb_transfer(). The dvb->frontend == NULL early return guards the register-failure path where the timer was never set up.
This bug was found by static analysis.
--- drivers/media/usb/au0828/au0828-dvb.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/usb/au0828/au0828-dvb.c +1 -0
@@ -537,6 +537,7 @@ void au0828_dvb_unregister(struct au0828if (dvb->frontend ==NULL )return ; +timer_shutdown_sync (&dev->bulk_timeout);cancel_work_sync (&dev->restart_streaming);dvb_net_release (&dvb->net);
Greg Kroah-Hartman
maintainerPATCH 611/1536 media: cx23885: Fix use-after-free in cx23885_finidev due to race condition
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pei Xiao <[email protected]>
commit 75016a992d9b03f5cc6df1414d1da35840d4feeb upstream.
In cx23885_v4l2_dev_notify_init, &dev->cx25840_work is bound with cx23885_av_work_handler, and &dev->ir_rx_work and &dev->ir_tx_work are bound with cx23885_ir_rx_work_handler and cx23885_ir_tx_work_handler. cx23885_irq can schedule these works on system_wq when an AV_CORE interrupt is received, and the IR subdevice can also schedule the IR works from its interrupt service routine via the v4l2_device notify callback.
If we remove the device, cx23885_finidev makes cleanup and the memory allocated for dev is released by kfree(dev), while the works mentioned above may still be pending or running. The sequence of operations that may lead to a UAF bug is as follows:
CPU0 CPU1
| cx23885_irq
| schedule_work(&dev->cx25840_work)
cx23885_finidev |
cx23885_input_fini(dev) |
cx23885_ir_fini(dev) |
cx23885_shutdown(dev) |
free_irq(pci_dev->irq, dev) |
pci_disable_device(pci_dev) |
cx23885_dev_unregister(dev) |
v4l2_device_unregister(v4l2_dev) |
kfree(dev) |
// dev is freed |
| cx23885_av_work_handler
| // use dev (use-after-free)Fix it by canceling the works after the IRQ handler that can schedule them has been stopped, and before proceeding with the remaining cleanup in cx23885_finidev.
Note that the flush_work() calls in cx23885_input_ir_stop() do not close this race: they only wait for works that are already queued or running at that moment, they do not prevent the IRQ handler, which is still registered at that point, from scheduling the works again afterwards, and they are skipped entirely when dev->sd_ir is NULL. The cancel_work_sync() calls are therefore placed after free_irq(), the only point at which no new work can be scheduled.
--- drivers/media/pci/cx23885/cx23885-core.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/pci/cx23885/cx23885-core.c +4 -0
@@ -2233,6 +2233,10 @@ static void cx23885_finidev(struct pci_d/* unregister stuff */ free_irq (pci_dev->irq, dev); +cancel_work_sync (&dev->cx25840_work); +cancel_work_sync (&dev->ir_rx_work); +cancel_work_sync (&dev->ir_tx_work); +pci_disable_device (pci_dev);cx23885_dev_unregister (dev);
Greg Kroah-Hartman
maintainerPATCH 612/1536 media: hackrf: fix use-after-free in hackrf_alloc_urbs() error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Anuj Bolewar <[email protected]>
commit 6802ad4b6b267dda02209b5811edac7825c8a5f6 upstream.
hackrf_alloc_urbs() frees the URBs it allocated so far when one allocation fails, but leaves the entries in dev->urb_list[] and dev->urbs_initialized untouched. The caller, hackrf_start_streaming(), then calls hackrf_free_urbs() on the error path, which walks dev->urbs_initialized entries and calls usb_free_urb() a second time on the already-freed URBs, causing a use-after-free (slab-use-after-free Write in usb_free_urb()).
Drop the redundant cleanup loop inside hackrf_alloc_urbs() and let hackrf_free_urbs(), which the caller already invokes on error, own the cleanup of the successfully allocated URBs.
--- drivers/media/usb/hackrf/hackrf.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-)
drivers/media/usb/hackrf/hackrf.c +2 -5
@@ -665,7 +665,7 @@ static int hackrf_free_urbs(struct hackrstatic int hackrf_alloc_urbs (struct hackrf_dev *dev,bool rcv) { -int i, j; +int i;unsigned int pipe;usb_complete_t complete;
@@ -681,11 +681,8 @@ static int hackrf_alloc_urbs(struct hackfor (i =0 ; i <MAX_BULK_BUFS ; i++) {dev_dbg (dev->dev,"alloc urb=%d\n" , i); dev->urb_list[i] =usb_alloc_urb (0 ,GFP_KERNEL ); -if (!dev->urb_list[i]) { -for (j =0 ; j < i; j++) -usb_free_urb (dev->urb_list[j]); +if (!dev->urb_list[i])return -ENOMEM ; - } usb_fill_bulk_urb(dev->urb_list[i], dev->udev, pipe,
Greg Kroah-Hartman
maintainerPATCH 613/1536 media: imon: fix use-after-free in display_close via dev_dbg
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Deepanshu Kartikey <[email protected]>
commit 118a3590a4080c71c565265b05b3f92e814d7647 upstream.
ictx->dev is a raw pointer to the usb_interface's embedded device. On disconnect, usb_disconnect() can drop the last reference on the interface and free it while a userspace fd for /dev/lcd0 is still open. When that fd is later closed, display_close() dereferences the now-freed ictx->dev via dev_dbg(), causing a use-after-free.
Remove the dev_dbg() calls that dereference ictx->dev in display_close() and free_imon_context(), rather than taking a reference on the device.
--- drivers/media/rc/imon.c | 5 ----- 1 file changed, 5 deletions(-)
drivers/media/rc/imon.c +0 -5
@@ -497,16 +497,12 @@ MODULE_PARM_DESC(pad_thresh, "Thresholdstatic void free_imon_context (struct imon_context *ictx) { -struct device *dev = ictx->dev; -usb_free_urb (ictx->tx_urb);WARN_ON (ictx->dev_present_intf0);usb_free_urb (ictx->rx_urb_intf0);WARN_ON (ictx->dev_present_intf1);usb_free_urb (ictx->rx_urb_intf1);kfree_rcu (ictx, rcu); - -dev_dbg (dev,"%s: iMON context freed\n" , __func__); }/*
@@ -582,7 +578,6 @@ static int display_close(struct inode *i retval = -EIO ; }else { ictx->display_isopen = false; -dev_dbg (ictx->dev,"display port closed\n" ); }mutex_unlock (&ictx->lock);
Greg Kroah-Hartman
maintainerPATCH 614/1536 mm/hugetlb: fix use-after-free in hugetlb_mfill_atomic_pte()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
commit d8a9cd7fd2fb01211430c933932da58839b8ca65 upstream.
Let's fix another instance where we use a folio after dropping the PTL, where someone else could e.g., MADV_DONTNEED it once we drop the PTL, making us trigger a use-after-free on the folio.
--- mm/hugetlb.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
mm/hugetlb.c +6 -1
@@ -6772,11 +6772,16 @@ int hugetlb_mfill_atomic_pte(pte_t *dst_/* No need to invalidate - it was non-present before */ update_mmu_cache (dst_vma, dst_addr, dst_pte); -spin_unlock (ptl);if (!is_continue)folio_set_hugetlb_migratable (folio);if (vm_shared || is_continue)folio_unlock (folio); + +/* +* Hold the PTL until we're done with the folio: the page table owns the +* folio reference now. +*/ +spin_unlock (ptl); ret =0 ; out:return ret;
Greg Kroah-Hartman
maintainerPATCH 615/1536 apparmor: fix a use-after-free in aa_lookupn_ns()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Binbin Deng <[email protected]>
commit f292873ceb4bd3a1a0f75f884361cd556e457692 upstream.
aa_lookupn_ns() takes a reference on the namespace it finds with aa_get_ns(), which is kref_get() on the reference count that the namespace is released through, without checking whether the namespace is still in use. A concurrent removal of a ":"-prefixed namespace looks the same namespace up and only then takes the parent lock to remove it, so the last reference can be dropped between the lookup and the aa_get_ns() call: the reference count then reports the increment on a zero count and the kernel classifies the following use of the object as a use-after-free. A user with CAP_MAC_ADMIN can trigger this by writing a ":<name>" removal and a ":<name>/<profile>" removal to /sys/kernel/security/apparmor/.remove concurrently.
refcount_t: addition on 0; use-after-free.
WARNING: lib/refcount.c:25 at refcount_warn_saturate+0xc0/0xe0, CPU#6 Call Trace: <TASK> aa_lookupn_ns+0xa9/0xc0 aa_remove_profiles+0x4fb/0x730 ? __kvmalloc_node_noprof+0x219/0x5c0 ? __pfx_aa_remove_profiles+0x10/0x10 ? aa_loaddata_alloc+0x65/0x1f0 ? _copy_from_user+0x2d/0x80 ? aa_loaddata_alloc+0x111/0x1f0 profile_remove+0x2ee/0x4a0 vfs_write+0x21e/0xcf0 ? rcu_core+0x29c/0x1740 ? timerqueue_linked_add+0x1f4/0x3d0 ? __pfx_vfs_write+0x10/0x10 ? mutex_lock+0x81/0xe0 ? __pfx_mutex_lock+0x10/0x10 ? __pfx_rcu_core+0x10/0x10 ? __pfx_hrtimer_update_next_event+0x10/0x10 ? mutex_unlock+0x7b/0xd0 ? fdget_pos+0x24d/0x4b0 ksys_write+0xf7/0x1c0 ? __pfx_ksys_write+0x10/0x10 ? restore_fpregs_from_fpstate+0x37/0xc0 do_syscall_64+0xf9/0x540 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK>
Fix by rejecting a namespace whose reference count is zero.
--- security/apparmor/include/policy_ns.h | 16 ++++++++++++++++ security/apparmor/policy_ns.c | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-)
security/apparmor/include/policy_ns.h +16 -0
@@ -118,6 +118,22 @@ static inline struct aa_ns *aa_get_ns(st }/** +* aa_get_ns_not0 - increment references count on @ns found via lookup +* @ns: namespace to increment reference count of (MAYBE NULL) +* +* Returns: pointer to @ns, if @ns is NULL returns NULL, +* NULL if @ns is being freed +* Requires: @ns must be held with valid refcount when called +*/ +static inline struct aa_ns *aa_get_ns_not0 (struct aa_ns *ns) +{ +if (ns &&aa_get_profile_not0 (ns->unconfined)) +return ns; + +return NULL ; +} + +/** * aa_put_ns - decrement refcount on @ns * @ns: namespace to put reference of *
security/apparmor/policy_ns.c +1 -1
@@ -207,7 +207,7 @@ struct aa_ns *aa_lookupn_ns(struct aa_nsstruct aa_ns *ns =NULL ;rcu_read_lock (); - ns =aa_get_ns (__aa_lookupn_ns (view, name, n)); + ns =aa_get_ns_not0 (__aa_lookupn_ns (view, name, n));rcu_read_unlock ();return ns;
Greg Kroah-Hartman
maintainerPATCH 616/1536 ata: sata_fsl: Fix use-after-free of host_priv on probe() failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Niklas Cassel <[email protected]>
commit 70b1196740d61aabda13b2ad0e9c1dfa2ef9cfa3 upstream.
sata_fsl_host_stop() releases hcr_base and host_priv:
static void sata_fsl_host_stop(struct ata_host *host)
{
struct sata_fsl_host_priv *host_priv = host->private_data;
iounmap(host_priv->hcr_base);
kfree(host_priv);
}->host_stop() is called by the driver core through the ata_host_stop() devres action which ata_host_start() registers, so it is called both when the device is unbound and when probe() fails after the host has been started.
The error_exit_with_cleanup label of sata_fsl_probe() releases hcr_base and host_priv as well, and it is reachable from the two device_create_file() calls which are done after the host has been activated. In that case sata_fsl_host_stop() runs on an already freed host_priv, resulting in a use-after-free and a double iounmap()/kfree().
Add a separate error label for the failures happening after the host has been activated, which only detaches the host and leaves hcr_base and host_priv to sata_fsl_host_stop().
Note that ata_host_detach() is dropped from error_exit_with_cleanup, as that label is now only reachable while host is still NULL.
--- drivers/ata/sata_fsl.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-)
drivers/ata/sata_fsl.c +13 -5
@@ -1499,7 +1499,7 @@ static int sata_fsl_probe(struct platfor host_priv->intr_coalescing.attr.mode =S_IRUGO |S_IWUSR ; retval =device_create_file (host->dev, &host_priv->intr_coalescing);if (retval) - goto error_exit_with_cleanup; + goto error_exit_detach; host_priv->rx_watermark.show = fsl_sata_rx_watermark_show; host_priv->rx_watermark.store = fsl_sata_rx_watermark_store;
@@ -1509,16 +1509,24 @@ static int sata_fsl_probe(struct platfor retval =device_create_file (host->dev, &host_priv->rx_watermark);if (retval) {device_remove_file (&ofdev->dev, &host_priv->intr_coalescing); - goto error_exit_with_cleanup; + goto error_exit_detach; }return 0 ; -error_exit_with_cleanup: +error_exit_detach: +/* +* Once the host has been activated, hcr_base and host_priv are +* released by sata_fsl_host_stop(), which is called by the driver core +* through the ata_host_stop() devres action registered by +* ata_host_start(). Releasing them here as well would result in a +* double iounmap() and a use-after-free. +*/ +ata_host_detach (host); -if (host) -ata_host_detach (host); +return retval; +error_exit_with_cleanup:if (hcr_base)iounmap (hcr_base);kfree (host_priv);
Greg Kroah-Hartman
maintainerPATCH 617/1536 s390/cpum_cf: Check session mask before cpu offline
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sumanth Korikkar <[email protected]>
commit 99a95985dfc85eecad97f0991a2401d2fcef294c upstream.
cfset_offline_cpu() stops counter sets for every active session without checking whether the outgoing cpu belongs to the session mask.
For example, run an hwctr session on cpu0 and a cpu bound perf event on cpu1:
lshwc -l 9999 -i 5 0:b
perf stat -C 1 -e cpum_cf/CPU_CYCLES/ sleep 120
chcpu -d 1
chcpu -e 1
Although the hwctr session does not include cpu1, cfset_offline_cpu() decrements its counter set reference count. The subsequent perf teardown decrements it again, causing it to underflow.
The perf event keeps the percpu state alive across hotplug. When cpu1 comes online, the hwctr session is started there and the reference count moves from -1 to 0. Stopping the hwctr session then decrements it to -1 again, so the zero triggered counter set disable path is skipped.
Check the session mask before stopping counter sets on the outgoing cpu. This prevents the unmatched decrement and the resulting reference count underflow.
--- arch/s390/kernel/perf_cpum_cf.c | 3 +++ 1 file changed, 3 insertions(+)
arch/s390/kernel/perf_cpum_cf.c +3 -0
@@ -1803,6 +1803,9 @@ static int cfset_offline_cpu(unsigned inif (!list_empty (&cfset_session.head)) {list_for_each_entry (rp, &cfset_session.head, node) { +if (!cpumask_test_cpu (cpu, &rp->mask)) +continue ; + p.sets = rp->ctrset;cfset_ioctl_off (&p);cpumask_clear_cpu (cpu, &rp->mask);
Greg Kroah-Hartman
maintainerPATCH 618/1536 s390/probes: Fix wrong opcode for cgrb fixup
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Heiko Carstens <[email protected]>
commit d7ccab11a13475e656b9d2277900422c1bfc12c5 upstream.
The last byte of the cgrb instruction is 0xe4, however the probes code compares against 0xe6. Fix it.
--- arch/s390/lib/probes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/s390/lib/probes.c +1 -1
@@ -99,8 +99,8 @@ int probe_get_fixup_type(u16 *insn)break ;case 0xec :switch (insn[2 ] &0xff ) { +case 0xe4 :/* cgrb */ case 0xe5 :/* clgrb */ -case 0xe6 :/* cgrb */ case 0xf6 :/* crb */ case 0xf7 :/* clrb */ case 0xfc :/* cgib */
Greg Kroah-Hartman
maintainerPATCH 619/1536 s390/signal: Fix incorrect return address in signal frame
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Heiko Carstens <[email protected]>
commit adc9e872f7350e3ac29c1818d8c68b0760b4ba23 upstream.
exit_to_user_mode_loop() can call arch_do_signal_or_restart() multiple times when signals are pending.
If the first call set up a vDSO system call restart by saving the real user return address and adjusting psw.addr so it points to the vDSO stub, a second call builds the signal frame with the wrong return address.
Restore psw.addr from arch_data, and set the return code to -EINTR before building the signal frame.
This requires restart_block.arch_data to be properly initialized for all tasks. Move the initialization in copy_thread() in front of the kernel thread check, so that it also covers kernel threads and their children (PID 1, usermode helpers). Only PID 0 is left uninitialized, since it never returns to user space.
--- arch/s390/kernel/process.c | 12 ++++++------ arch/s390/kernel/signal.c | 6 +++++- 2 files changed, 11 insertions(+), 7 deletions(-)
arch/s390/kernel/process.c +6 -6
@@ -133,6 +133,12 @@ int copy_thread(struct task_struct *p, c p->thread.hardirq_timer =0 ; p->thread.softirq_timer =0 ; p->thread.last_break =1 ; +/* +* s390 stores the svc return address in arch_data when calling +* sigreturn()/restart_syscall() via vdso. 1 means no valid address +* stored. +*/ + p->restart_block.arch_data =1 ; frame->sf.back_chain =0 ; frame->sf.gprs[11 -6 ] = (unsigned long )&frame->childregs;
@@ -174,12 +180,6 @@ int copy_thread(struct task_struct *p, c p->thread.acrs[1 ] = (unsigned int )tls; } } -/* -* s390 stores the svc return address in arch_data when calling -* sigreturn()/restart_syscall() via vdso. 1 means no valid address -* stored. -*/ - p->restart_block.arch_data =1 ;return 0 ; }
arch/s390/kernel/signal.c +5 -1
@@ -488,7 +488,11 @@ void arch_do_signal_or_restart(struct pt }/* No longer in a system call */ clear_pt_regs_flag (regs,PIF_SYSCALL ); - +if (!(current->restart_block.arch_data &1 )) { + regs->psw.addr = current->restart_block.arch_data; + current->restart_block.arch_data =1 ; + regs->gprs[2 ] = -EINTR ; + }rseq_signal_deliver (&ksig, regs);if (is_compat_task ())handle_signal32 (&ksig, oldset, regs);
Greg Kroah-Hartman
maintainerPATCH 620/1536 s390/zcrypt: Fix out-of-bounds ptr advance in cca_query_crypto_facility()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Harald Freudenberger <[email protected]>
commit 9fd7fca66735307fd7afa3450882a55ef80f2add upstream.
The FQ reply parser code blindly advanced the walk pointer by a length value read directly from the hardware reply payload without checking that the advance stayed within the allocated reply buffer. A corrupt or malicious device response could push ptr beyond the cprbmem region, causing an out-of-bounds dereference or kernel memory exposure via the subsequent memcpy().
Fix this by tracking the remaining reply buffer space in a variable and validating each device-supplied length field against it before advancing or dereferencing the pointer.
--- drivers/s390/crypto/zcrypt_ccamisc.c | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-)
drivers/s390/crypto/zcrypt_ccamisc.c +20 -2
@@ -1559,6 +1559,7 @@ int cca_query_crypto_facility(u16 cardnru8 subfunc_code[2 ];u8 lvdata[]; }__packed * prepparm; +size_t datalen;/* get already prepared memory for 2 cprbs with param block each */ rc =alloc_and_prep_cprbmem (parmbsize, &mem, &preqcblk, &prepcblk);
@@ -1604,27 +1605,44 @@ int cca_query_crypto_facility(u16 cardnr prepcblk->rpl_parmb = (u8 __user *)ptr; prepparm = (struct fqrepparm *)ptr; ptr = prepparm->lvdata; + datalen = parmbsize -2 *sizeof (u8);/* check and possibly copy reply rule array */ len = *((u16 *)ptr); +if (len > datalen) { +ZCRYPT_DBF_ERR ("%s reply rule array len %u exceeds datalen %zu\n" , + __func__, len, datalen); + rc = -EIO ; + goto out; + } + datalen -=sizeof (u16); + ptr +=sizeof (u16);if (len >sizeof (u16)) { - ptr +=sizeof (u16); len -=sizeof (u16);if (rarray && rarraylen && *rarraylen >0 ) { *rarraylen = (len > *rarraylen ? *rarraylen : len);memcpy (rarray, ptr, *rarraylen); } + datalen -= len; ptr += len; }/* check and possible copy reply var array */ len = *((u16 *)ptr); +if (len > datalen) { +ZCRYPT_DBF_ERR ("%s reply var array len %u exceeds datalen %zu\n" , + __func__, len, datalen); + rc = -EIO ; + goto out; + } + datalen -=sizeof (u16); + ptr +=sizeof (u16);if (len >sizeof (u16)) { - ptr +=sizeof (u16); len -=sizeof (u16);if (varray && varraylen && *varraylen >0 ) { *varraylen = (len > *varraylen ? *varraylen : len);memcpy (varray, ptr, *varraylen); } + datalen -= len; ptr += len; }
Greg Kroah-Hartman
maintainerPATCH 621/1536 HID: wacom: Use hdev->product in wacom_setup_touch_input_capabilities
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit 86472508a7ef74b525e79a79d2d02d911a641d6b upstream.
Replace the lookup-dependent 'wacom_wac->shared->touch->product' references with 'hdev->product' inside wacom_setup_touch_input_capabilities() since 'hdev' is already available (via container_of) and represents the touch device itself.
--- drivers/hid/wacom_wac.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-)
drivers/hid/wacom_wac.c +9 -9
@@ -3961,8 +3961,8 @@ int wacom_setup_pen_input_capabilities(sint wacom_setup_touch_input_capabilities (struct input_dev *input_dev,struct wacom_wac *wacom_wac) { + struct hid_device *hdev = container_of(wacom_wac, struct wacom, wacom_wac)->hdev;struct wacom_features *features = &wacom_wac->features; -if (!(features->device_type &WACOM_DEVICETYPE_TOUCH ))return -ENODEV ;
@@ -3971,9 +3971,11 @@ int wacom_setup_touch_input_capabilitieselse __set_bit (INPUT_PROP_POINTER , input_dev->propbit); -if (features->type ==HID_GENERIC ) +if (features->type ==HID_GENERIC ) { +hid_dbg (hdev,"generic touch setup\n" );/* setup has already been done */ return 0 ; + } input_dev->evbit[0 ] |=BIT_MASK (EV_KEY ) |BIT_MASK (EV_ABS );__set_bit (BTN_TOUCH , input_dev->keybit);
@@ -4005,19 +4007,17 @@ int wacom_setup_touch_input_capabilities input_dev->evbit[0 ] |=BIT_MASK (EV_SW );__set_bit (SW_MUTE_DEVICE , input_dev->swbit); -if (wacom_wac->shared->touch->product ==0x361 ) { +if (hdev->product ==0x361 ) {input_set_abs_params (input_dev,ABS_MT_POSITION_X ,0 ,12440 ,4 ,0 );input_set_abs_params (input_dev,ABS_MT_POSITION_Y ,0 ,8640 ,4 ,0 ); - } -else if (wacom_wac->shared->touch->product ==0x360 ) { + }else if (hdev->product ==0x360 ) {input_set_abs_params (input_dev,ABS_MT_POSITION_X ,0 ,8960 ,4 ,0 );input_set_abs_params (input_dev,ABS_MT_POSITION_Y ,0 ,5920 ,4 ,0 ); - } -else if (wacom_wac->shared->touch->product ==0x393 ) { + }else if (hdev->product ==0x393 ) {input_set_abs_params (input_dev,ABS_MT_POSITION_X ,0 ,6400 ,4 ,0 ); input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
@@ -4047,8 +4047,8 @@ int wacom_setup_touch_input_capabilities fallthrough;case WACOM_27QHDT : -if (wacom_wac->shared->touch->product ==0x32C || - wacom_wac->shared->touch->product ==0xF6 ) { +if (hdev->product ==0x32C || + hdev->product ==0xF6 ) { input_dev->evbit[0 ] |=BIT_MASK (EV_SW );__set_bit (SW_MUTE_DEVICE , input_dev->swbit); wacom_wac->has_mute_touch_switch = true;
Greg Kroah-Hartman
maintainerPATCH 622/1536 HID: wacom: Advertise SW_MUTE_DEVICE capability prior to registration
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit ba16e5ffbaa10fde960918d69af5e49f2b3fdd5e upstream.
Input subsystem guidelines require that device capabilities are advertised before the input device is registered. The Wacom driver was violating this by advertising the SW_MUTE_DEVICE capability post-registration in wacom_set_shared_values() (and duplicating it in device-specific setup cases).
Resolve this by moving the SW_MUTE_DEVICE capability setup to wacom_setup_touch_input_capabilities() for all touch devices that support it.
For generic touch devices whose capabilities depend on mute switch usages parsed from a sibling Pen/Pad interface, defer registration with -EPROBE_DEFER until the sibling has parsed its descriptors and initialized shared capabilities.
--- drivers/hid/wacom_sys.c | 93 ++++++++++++++++++++++++++++++++++++++---------- drivers/hid/wacom_wac.c | 5 ++ 2 files changed, 79 insertions(+), 19 deletions(-)
drivers/hid/wacom_sys.c +74 -19
@@ -895,19 +895,14 @@ static int wacom_add_shared_data(structlist_add_tail (&data->list, &wacom_udev_list); } -mutex_unlock (&wacom_udev_list_lock); - wacom_wac->shared = &data->shared; - retval =devm_add_action_or_reset (&hdev->dev, wacom_remove_shared_data, wacom); -if (retval) -return retval; +if (wacom_wac->has_mute_touch_switch) +WRITE_ONCE (wacom_wac->shared->has_mute_touch_switch, true); -if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) - wacom_wac->shared->touch = hdev; -else if (wacom_wac->features.device_type &WACOM_DEVICETYPE_PEN ) - wacom_wac->shared->pen = hdev; +mutex_unlock (&wacom_udev_list_lock); + retval =devm_add_action_or_reset (&hdev->dev, wacom_remove_shared_data, wacom);return retval; }
@@ -2319,13 +2314,12 @@ static void wacom_release_resources(strustatic void wacom_set_shared_values (struct wacom_wac *wacom_wac) { -if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) { - wacom_wac->shared->type = wacom_wac->features.type; - wacom_wac->shared->touch_input = wacom_wac->touch_input; - } + struct wacom *wacom = container_of(wacom_wac, struct wacom, wacom_wac); + +guard (mutex)(&wacom_udev_list_lock);if (wacom_wac->has_mute_touch_switch) { - wacom_wac->shared->has_mute_touch_switch = true; +WRITE_ONCE (wacom_wac->shared->has_mute_touch_switch, true);/* Hardware touch switch may be off. Wait until * we know the switch state to decide is_touch_on. * Softkey state should be initialized to "on" to
@@ -2335,12 +2329,67 @@ static void wacom_set_shared_values(stru wacom_wac->shared->is_touch_on = true; } -if (wacom_wac->shared->has_mute_touch_switch && - wacom_wac->shared->touch_input) { -set_bit (EV_SW , wacom_wac->shared->touch_input->evbit); -input_set_capability (wacom_wac->shared->touch_input,EV_SW , -SW_MUTE_DEVICE ); +if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) { + wacom_wac->shared->type = wacom_wac->features.type; + wacom_wac->shared->touch_input = wacom_wac->touch_input; + wacom_wac->shared->touch = wacom->hdev; + }else if (wacom_wac->features.device_type &WACOM_DEVICETYPE_PEN ) { +/* Pairs with smp_load_acquire() in wacom_sibling_pending() */ +smp_store_release (&wacom_wac->shared->pen, wacom->hdev); + } +} + +static bool wacom_sibling_pending (struct wacom *wacom) +{ +const struct wacom_features *features = &wacom->wacom_wac.features; +struct hid_device *hdev = wacom->hdev; +struct usb_interface *sibling_intf; +int ifnum; + +if (features->type !=HID_GENERIC || + !(features->device_type &WACOM_DEVICETYPE_TOUCH )) +return false; + +if (wacom->wacom_wac.shared) { +/* Pairs with smp_store_release() in wacom_set_shared_values() */ +if (smp_load_acquire (&wacom->wacom_wac.shared->pen)) +return false; } + +if (!hid_is_usb (hdev) || !wacom->usbdev || !wacom->intf || + !wacom->intf->cur_altsetting) +return false; + + ifnum = wacom->intf->cur_altsetting->desc.bInterfaceNumber; + +/* +* On composite Wacom devices, the Pen interface is always interface 0. +* If the Touch interface is interface 0, there is no sibling Pen +* interface on this device (standalone touch device). +*/ +if (ifnum ==0 ) +return false; + +/* Look for the sibling Pen interface at interface 0 */ + sibling_intf =usb_ifnum_to_if (wacom->usbdev,0 ); +if (!sibling_intf || !sibling_intf->cur_altsetting) +return false; + +if (sibling_intf->cur_altsetting->desc.bInterfaceClass != +USB_INTERFACE_CLASS_HID ) +return false; + +if (sibling_intf->cur_altsetting->desc.bInterfaceSubClass ==1 && + (sibling_intf->cur_altsetting->desc.bInterfaceProtocol ==1 || + sibling_intf->cur_altsetting->desc.bInterfaceProtocol ==2 )) +return false; + +/* +* Interface 0 is a candidate HID interface on this composite device +* whose probe has not completed yet (shared->pen is NULL). Defer until +* interface 0 finishes probing and registers shared values. +*/ +return true; }static int wacom_parse_and_register (struct wacom *wacom,bool wireless)
@@ -2416,6 +2465,11 @@ static int wacom_parse_and_register(struif (error) goto fail; +if (wacom_sibling_pending (wacom)) { + error = -EPROBE_DEFER ; + goto fail; + } + error =wacom_setup_inputs (wacom);if (error) goto fail;
@@ -2473,6 +2527,7 @@ static int wacom_parse_and_register(stru fail_hw_stop:hid_hw_stop (hdev); +cancel_delayed_work_sync (&wacom->init_work); fail:wacom_release_resources (wacom);return error;
drivers/hid/wacom_wac.c +5 -0
@@ -3973,6 +3973,11 @@ int wacom_setup_touch_input_capabilitiesif (features->type ==HID_GENERIC ) {hid_dbg (hdev,"generic touch setup\n" ); +if (wacom_wac->has_mute_touch_switch || + (wacom_wac->shared &&READ_ONCE (wacom_wac->shared->has_mute_touch_switch))) { +input_set_capability (input_dev,EV_SW ,SW_MUTE_DEVICE ); + wacom_wac->has_mute_touch_switch = true; + }/* setup has already been done */ return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 623/1536 HID: wacom: Fix Use-After-Free in wacom_intuos_pad
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit ef32877368a7013c060ef6bd03a30b6da2fe0c41 upstream.
wacom_intuos_pad() accesses wacom->shared->touch_input locklessly inside the interrupt handler context. If the Touch sibling device is disconnected, wacom_remove_shared_data() clears 'touch_input' outside any lock, creating a Time-of-Check to Time-of-Use (TOCTOU) race condition where a preempted reader in interrupt context dereferences the freed pointer, leading to a Use-After-Free.
Resolve this by introducing RCU protection for the touch_input pointer:
- Annotate 'touch_input' in wacom_shared struct with __rcu
- Wrap all lockless readers in wacom_wac.c with guard(rcu)() and rcu_dereference() using a unified wacom_report_touch_mute() helper
- Update writers in wacom_sys.c using rcu_assign_pointer()
- Call synchronize_rcu() in wacom_remove_shared_data() to ensure all active RCU readers have finished before the input device is freed
Also wrap wacom_set_shared_values() and touch/pen assignments in wacom_add_shared_data() inside the wacom_udev_list_lock to serialize concurrent probe assignments, and verify that 'shared->touch == hdev' before setting touch_input to prevent concurrent sibling probe state desynchronization.
--- drivers/hid/wacom_sys.c | 23 ++++++++++++++++------- drivers/hid/wacom_wac.c | 36 ++++++++++++++++++------------------ drivers/hid/wacom_wac.h | 2 +- 3 files changed, 35 insertions(+), 26 deletions(-)
drivers/hid/wacom_sys.c +16 -7
@@ -863,10 +863,16 @@ static void wacom_remove_shared_data(voi data = container_of(wacom_wac->shared, struct wacom_hdev_data, shared); -if (wacom_wac->shared->touch == wacom->hdev) - wacom_wac->shared->touch =NULL ; -else if (wacom_wac->shared->pen == wacom->hdev) - wacom_wac->shared->pen =NULL ; + scoped_guard(mutex, &wacom_udev_list_lock) { +if (wacom_wac->shared->touch == wacom->hdev) { + wacom_wac->shared->touch =NULL ; +rcu_assign_pointer (wacom_wac->shared->touch_input,NULL ); + }else if (wacom_wac->shared->pen == wacom->hdev) { + wacom_wac->shared->pen =NULL ; + } + } + +synchronize_rcu ();kref_put (&data->kref, wacom_release_shared_data); wacom_wac->shared =NULL ;
@@ -903,6 +909,7 @@ static int wacom_add_shared_data(structmutex_unlock (&wacom_udev_list_lock); retval =devm_add_action_or_reset (&hdev->dev, wacom_remove_shared_data, wacom); +return retval; }
@@ -2330,9 +2337,11 @@ static void wacom_set_shared_values(stru }if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) { - wacom_wac->shared->type = wacom_wac->features.type; - wacom_wac->shared->touch_input = wacom_wac->touch_input; - wacom_wac->shared->touch = wacom->hdev; +if (wacom_wac->shared->touch == wacom->hdev || !wacom_wac->shared->touch) { + wacom_wac->shared->type = wacom_wac->features.type; + wacom_wac->shared->touch = wacom->hdev; +rcu_assign_pointer (wacom_wac->shared->touch_input, wacom_wac->touch_input); + } }else if (wacom_wac->features.device_type &WACOM_DEVICETYPE_PEN ) {/* Pairs with smp_load_acquire() in wacom_sibling_pending() */ smp_store_release (&wacom_wac->shared->pen, wacom->hdev);
drivers/hid/wacom_wac.c +18 -18
@@ -510,6 +510,18 @@ static void wacom_intuos_schedule_prox_e } } +static void wacom_report_touch_mute (struct wacom_wac *wacom_wac,bool mute) +{ +struct input_dev *touch_input; + +guard (rcu)(); + touch_input =rcu_dereference (wacom_wac->shared->touch_input); +if (touch_input) { +input_report_switch (touch_input,SW_MUTE_DEVICE , mute); +input_sync (touch_input); + } +} +static int wacom_intuos_pad (struct wacom_wac *wacom) {struct wacom_features *features = &wacom->features;
@@ -650,12 +662,8 @@ static int wacom_intuos_pad(struct wacominput_report_key (input,KEY_CONTROLPANEL , menu);input_report_key (input,KEY_INFO , info); -if (wacom->shared && wacom->shared->touch_input) { -input_report_switch (wacom->shared->touch_input, -SW_MUTE_DEVICE , - !wacom->shared->is_touch_on); -input_sync (wacom->shared->touch_input); - } +if (wacom->shared) +wacom_report_touch_mute (wacom, !wacom->shared->is_touch_on);input_report_abs (input,ABS_RX , strip1);input_report_abs (input,ABS_RY , strip2);
@@ -2166,7 +2174,7 @@ static void wacom_wac_pad_event(struct h*/ if ((equivalent_usage ==WACOM_HID_WD_MUTE_DEVICE ) || (equivalent_usage ==WACOM_HID_WD_TOUCHONOFF )) { -if (wacom_wac->shared->touch_input) { +if (wacom_wac->shared) {bool *is_touch_on = &wacom_wac->shared->is_touch_on;if (equivalent_usage ==WACOM_HID_WD_MUTE_DEVICE && value)
@@ -2174,9 +2182,7 @@ static void wacom_wac_pad_event(struct helse if (equivalent_usage ==WACOM_HID_WD_TOUCHONOFF ) *is_touch_on = value; -input_report_switch (wacom_wac->shared->touch_input, -SW_MUTE_DEVICE , !(*is_touch_on)); -input_sync (wacom_wac->shared->touch_input); +wacom_report_touch_mute (wacom_wac, !(*is_touch_on)); }return ; }
@@ -3391,11 +3397,8 @@ static int wacom_wireless_irq(struct wacif ((wacom->shared->type ==INTUOSHT || wacom->shared->type ==INTUOSHT2 ) && - wacom->shared->touch_input && wacom->shared->touch_max) { -input_report_switch (wacom->shared->touch_input, -SW_MUTE_DEVICE , data[5 ] &0x40 ); -input_sync (wacom->shared->touch_input); +wacom_report_touch_mute (wacom, data[5 ] &0x40 ); } pid =get_unaligned_be16 (&data[6 ]);
@@ -3430,11 +3433,8 @@ static int wacom_status_irq(struct wacomif ((features->type ==INTUOSHT || features->type ==INTUOSHT2 ) && - wacom_wac->shared->touch_input && features->touch_max) { -input_report_switch (wacom_wac->shared->touch_input, -SW_MUTE_DEVICE , data[8 ] &0x40 ); -input_sync (wacom_wac->shared->touch_input); +wacom_report_touch_mute (wacom_wac, data[8 ] &0x40 ); }if (data[9 ] &0x02 ) {/* wireless module is attached */
drivers/hid/wacom_wac.h +1 -1
@@ -288,7 +288,7 @@ struct wacom_shared {/* for wireless device to access USB interfaces */ unsigned touch_max;int type; -struct input_dev *touch_input; +struct input_dev __rcu *touch_input;struct hid_device *pen;struct hid_device *touch;bool has_mute_touch_switch;
Greg Kroah-Hartman
maintainerPATCH 624/1536 HID: wacom: Fix Use-After-Free in wacom_bamboo_pad
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit 3a523ecf9ac3fdd33f5eb31c43937ee44135395b upstream.
wacom_bamboo_pad_pen_event() accesses wacom->shared->pen locklessly relative to wacom_remove_shared_data() which nullifies it. This can lead to a Use-After-Free if the sibling device is removed while events are being processed.
Resolve this by introducing RCU protection for pen and touch pointers:
- Annotate 'pen' and 'touch' in wacom_shared struct with __rcu.
- Wrap lockless readers in wacom_bamboo_pad_pen_event() with rcu_read_lock() and rcu_dereference().
- Update writers in wacom_sys.c using rcu_assign_pointer().
- Use rcu_dereference_protected for comparisons under wacom_udev_list_lock.
- Also use rcu_access_pointer in wacom_sibling_pending() and wacom_mode_change_work() to avoid warnings (while lockless access in the latter remains a pre-existing issue).
--- drivers/hid/wacom_sys.c | 40 ++++++++++++++++++++++++++-------------- drivers/hid/wacom_wac.c | 13 ++++++------- drivers/hid/wacom_wac.h | 4 ++-- 3 files changed, 34 insertions(+), 23 deletions(-)
drivers/hid/wacom_sys.c +26 -14
@@ -864,11 +864,18 @@ static void wacom_remove_shared_data(voi shared); scoped_guard(mutex, &wacom_udev_list_lock) { -if (wacom_wac->shared->touch == wacom->hdev) { - wacom_wac->shared->touch =NULL ; +struct hid_device *touch = +rcu_dereference_protected (wacom_wac->shared->touch, +lockdep_is_held (&wacom_udev_list_lock)); +struct hid_device *pen = +rcu_dereference_protected (wacom_wac->shared->pen, +lockdep_is_held (&wacom_udev_list_lock)); + +if (touch == wacom->hdev) { +rcu_assign_pointer (wacom_wac->shared->touch,NULL );rcu_assign_pointer (wacom_wac->shared->touch_input,NULL ); - }else if (wacom_wac->shared->pen == wacom->hdev) { - wacom_wac->shared->pen =NULL ; + }else if (pen == wacom->hdev) { +rcu_assign_pointer (wacom_wac->shared->pen,NULL ); } }
@@ -2337,14 +2344,17 @@ static void wacom_set_shared_values(stru }if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) { -if (wacom_wac->shared->touch == wacom->hdev || !wacom_wac->shared->touch) { +struct hid_device *touch = +rcu_dereference_protected (wacom_wac->shared->touch, +lockdep_is_held (&wacom_udev_list_lock)); + +if (touch == wacom->hdev || !touch) { wacom_wac->shared->type = wacom_wac->features.type; - wacom_wac->shared->touch = wacom->hdev; +rcu_assign_pointer (wacom_wac->shared->touch, wacom->hdev);rcu_assign_pointer (wacom_wac->shared->touch_input, wacom_wac->touch_input); } }else if (wacom_wac->features.device_type &WACOM_DEVICETYPE_PEN ) { -/* Pairs with smp_load_acquire() in wacom_sibling_pending() */ -smp_store_release (&wacom_wac->shared->pen, wacom->hdev); +rcu_assign_pointer (wacom_wac->shared->pen, wacom->hdev); } }
@@ -2360,8 +2370,7 @@ static bool wacom_sibling_pending(structreturn false;if (wacom->wacom_wac.shared) { -/* Pairs with smp_store_release() in wacom_set_shared_values() */ -if (smp_load_acquire (&wacom->wacom_wac.shared->pen)) +if (rcu_access_pointer (wacom->wacom_wac.shared->pen))return false; }
@@ -2824,16 +2833,19 @@ static void wacom_mode_change_work(strucbool is_direct = wacom->wacom_wac.is_direct_mode;int error =0 ; -if (shared->pen) { - wacom1 =hid_get_drvdata (shared->pen); +struct hid_device *pen =rcu_access_pointer (shared->pen); +struct hid_device *touch =rcu_access_pointer (shared->touch); + +if (pen) { + wacom1 =hid_get_drvdata (pen);wacom_release_resources (wacom1);hid_hw_stop (wacom1->hdev); wacom1->wacom_wac.has_mode_change = true; wacom1->wacom_wac.is_direct_mode = is_direct; } -if (shared->touch) { - wacom2 =hid_get_drvdata (shared->touch); +if (touch) { + wacom2 =hid_get_drvdata (touch);wacom_release_resources (wacom2);hid_hw_stop (wacom2->hdev); wacom2->wacom_wac.has_mode_change = true;
drivers/hid/wacom_wac.c +6 -7
@@ -3302,6 +3302,7 @@ static int wacom_bpt_irq(struct wacom_wastatic void wacom_bamboo_pad_pen_event (struct wacom_wac *wacom,unsigned char *data) { +struct hid_device *pen;unsigned char prefix;/*
@@ -3314,13 +3315,11 @@ static void wacom_bamboo_pad_pen_event(s prefix = data[0 ]; data[0 ] =WACOM_REPORT_BPAD_PEN ; -/* -* actually reroute the event. -* No need to check if wacom->shared->pen is valid, hid_input_report() -* will check for us. -*/ -hid_input_report (wacom->shared->pen,HID_INPUT_REPORT , data, -WACOM_PKGLEN_PENABLED ,1 ); +guard (rcu)(); + pen =rcu_dereference (wacom->shared->pen); +if (pen) +hid_input_report (pen,HID_INPUT_REPORT , data, +WACOM_PKGLEN_PENABLED ,1 ); data[0 ] = prefix; }
drivers/hid/wacom_wac.h +2 -2
@@ -289,8 +289,8 @@ struct wacom_shared {unsigned touch_max;int type;struct input_dev __rcu *touch_input; -struct hid_device *pen; -struct hid_device *touch; +struct hid_device __rcu *pen; +struct hid_device __rcu *touch;bool has_mute_touch_switch;bool is_touch_on; };
Greg Kroah-Hartman
maintainerPATCH 625/1536 HID: wacom: Redesign shared sibling data lifecycle
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit 480c9cb14ae81f8e112ff83f8778b3d7b9324dc8 upstream.
The Wacom driver coordinates state between sibling interfaces of the same physical device using a shared structure 'wacom_shared' inside 'wacom_hdev_data'. The driver kept a volatile representative pointer 'data->dev' pointing to a sibling 'hid_device' for physical path comparisons during sibling matching.
This pointer management is fragile. When the representative device is disconnected, wacom_remove_shared_data() failed to clear/update 'data->dev', leading to a Use-After-Free vulnerability when subsequent sibling probes dereference the dangling 'data->dev' pointer.
Resolve this issue by redesigning the sibling data lifecycle:
- Eliminate the volatile 'data->dev' representative pointer completely
- Redesign 'wacom_hdev_data' to store stable static copies of the required attributes upon first allocation: 'phys' path string, 'vendor', 'product' IDs and the sibling's 'device_type'
- Use these static attributes for stable sibling matching in wacom_are_sibling() and wacom_get_hdev_data()
This ensures sibling matching remains safe and stable even if individual siblings are dynamically added or removed.
To secure the lifecycle against concurrent probe/disconnect races:
- Switch kref_put() to kref_put_mutex() in wacom_remove_shared_data() to serialize refcount drops with list traversal and lookup
- Modify wacom_release_shared_data() to assume the list lock is already held
Also, do not accumulate the 'device_type' capability flag during subsequent sibling probes. Keeping only the first probed sibling's device_type exactly preserves the original sibling matching behavior without introducing side effects.
--- drivers/hid/wacom_sys.c | 70 +++++++++++++++++++++++++++++++----------------- 1 file changed, 46 insertions(+), 24 deletions(-)
drivers/hid/wacom_sys.c +46 -24
@@ -745,27 +745,47 @@ static void wacom_retrieve_hid_descriptostruct wacom_hdev_data {struct list_head list;struct kref kref; -struct hid_device *dev; +char phys[64 ]; +__u32 vendor; +__u32 product; +__u32 device_type;struct wacom_shared shared; }; +static bool wacom_compare_device_paths (struct hid_device *hdev_a, +const char *phys_b,char separator) +{ +const char *p1 =strrchr (hdev_a->phys, separator); +const char *p2 =strrchr (phys_b, separator); +int n1, n2; + +if (!p1 || !p2) +return false; + + n1 = p1 - hdev_a->phys; + n2 = p2 - phys_b; + +if (n1 != n2 || n1 <=0 || n2 <=0 ) +return false; + +return !strncmp (hdev_a->phys, phys_b, n1); +} +static LIST_HEAD (wacom_udev_list);static DEFINE_MUTEX (wacom_udev_list_lock);static bool wacom_are_sibling (struct hid_device *hdev, -struct hid_device *sibling) +struct wacom_hdev_data *data) {struct wacom *wacom =hid_get_drvdata (hdev);struct wacom_features *features = &wacom->wacom_wac.features; -struct wacom *sibling_wacom =hid_get_drvdata (sibling); -struct wacom_features *sibling_features = &sibling_wacom->wacom_wac.features;__u32 oVid = features->oVid ? features->oVid : hdev->vendor;__u32 oPid = features->oPid ? features->oPid : hdev->product;/* The defined oVid/oPid must match that of the sibling */ -if (features->oVid !=HID_ANY_ID && sibling->vendor != oVid) +if (features->oVid !=HID_ANY_ID && data->vendor != oVid)return false; -if (features->oPid !=HID_ANY_ID && sibling->product != oPid) +if (features->oPid !=HID_ANY_ID && data->product != oPid)return false;/*
@@ -773,11 +793,11 @@ static bool wacom_are_sibling(struct hid* device path, while those with different VID/PID must share * the same physical parent device path. */ -if (hdev->vendor == sibling->vendor && hdev->product == sibling->product) { -if (!hid_compare_device_paths (hdev, sibling,'/' )) +if (hdev->vendor == data->vendor && hdev->product == data->product) { +if (!wacom_compare_device_paths (hdev, data->phys,'/' ))return false; }else { -if (!hid_compare_device_paths (hdev, sibling,'.' )) +if (!wacom_compare_device_paths (hdev, data->phys,'.' ))return false; }
@@ -790,7 +810,7 @@ static bool wacom_are_sibling(struct hid* devices. */ if ((features->device_type &WACOM_DEVICETYPE_DIRECT ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_DIRECT )) + !(data->device_type &WACOM_DEVICETYPE_DIRECT ))return false;/*
@@ -798,17 +818,17 @@ static bool wacom_are_sibling(struct hid* devices. */ if (!(features->device_type &WACOM_DEVICETYPE_DIRECT ) && - (sibling_features->device_type &WACOM_DEVICETYPE_DIRECT )) + (data->device_type &WACOM_DEVICETYPE_DIRECT ))return false;/* Pen devices may only be siblings of touch devices */ if ((features->device_type &WACOM_DEVICETYPE_PEN ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_TOUCH )) + !(data->device_type &WACOM_DEVICETYPE_TOUCH ))return false;/* Touch devices may only be siblings of pen devices */ if ((features->device_type &WACOM_DEVICETYPE_TOUCH ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_PEN )) + !(data->device_type &WACOM_DEVICETYPE_PEN ))return false;/*
@@ -824,7 +844,7 @@ static struct wacom_hdev_data *wacom_get/* Try to find an already-probed interface from the same device */ list_for_each_entry (data, &wacom_udev_list, list) { -if (hid_compare_device_paths (hdev, data->dev,'/' )) { +if (wacom_compare_device_paths (hdev, data->phys,'/' )) {kref_get (&data->kref);return data; }
@@ -832,7 +852,7 @@ static struct wacom_hdev_data *wacom_get/* Fallback to finding devices that appear to be "siblings" */ list_for_each_entry (data, &wacom_udev_list, list) { -if (wacom_are_sibling (hdev, data->dev)) { +if (wacom_are_sibling (hdev, data)) {kref_get (&data->kref);return data; }
@@ -846,18 +866,15 @@ static void wacom_release_shared_data(ststruct wacom_hdev_data *data = container_of(kref, struct wacom_hdev_data, kref); -mutex_lock (&wacom_udev_list_lock);list_del (&data->list); -mutex_unlock (&wacom_udev_list_lock); -kfree (data); }static void wacom_remove_shared_data (void *res) { -struct wacom *wacom = res; +struct wacom *res_wacom = res;struct wacom_hdev_data *data; -struct wacom_wac *wacom_wac = &wacom->wacom_wac; +struct wacom_wac *wacom_wac = &res_wacom->wacom_wac;if (wacom_wac->shared) { data = container_of(wacom_wac->shared, struct wacom_hdev_data,
@@ -871,17 +888,19 @@ static void wacom_remove_shared_data(voircu_dereference_protected (wacom_wac->shared->pen,lockdep_is_held (&wacom_udev_list_lock)); -if (touch == wacom->hdev) { +if (touch == res_wacom->hdev) {rcu_assign_pointer (wacom_wac->shared->touch,NULL );rcu_assign_pointer (wacom_wac->shared->touch_input,NULL ); - }else if (pen == wacom->hdev) { + }else if (pen == res_wacom->hdev) {rcu_assign_pointer (wacom_wac->shared->pen,NULL ); } }synchronize_rcu (); -kref_put (&data->kref, wacom_release_shared_data); +if (kref_put_mutex (&data->kref, wacom_release_shared_data, &wacom_udev_list_lock)) +mutex_unlock (&wacom_udev_list_lock); + wacom_wac->shared =NULL ; } }
@@ -904,7 +923,10 @@ static int wacom_add_shared_data(struct }kref_init (&data->kref); - data->dev = hdev; +strscpy (data->phys, hdev->phys,sizeof (data->phys)); + data->vendor = hdev->vendor; + data->product = hdev->product; + data->device_type = wacom_wac->features.device_type;list_add_tail (&data->list, &wacom_udev_list); }
Greg Kroah-Hartman
maintainerPATCH 626/1536 HID: wacom: Setup SW_MUTE_DEVICE according to the order of input registration
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ping Cheng <[email protected]>
commit 97ce491bcef2d231b8d51cee8e579183319a5ba4 upstream.
The refactored SW_MUTE_DEVICE code assumed that stylus will be the first regiestered input. In reality, touch can be registered before stylus, such as the Wacom Cintiq Pro 13 and 16.
This patch covers both touch-first and stylus-first cases.
--- drivers/hid/wacom_wac.c | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-)
drivers/hid/wacom_wac.c +30 -3
@@ -3972,10 +3972,18 @@ int wacom_setup_touch_input_capabilitiesif (features->type ==HID_GENERIC ) {hid_dbg (hdev,"generic touch setup\n" ); -if (wacom_wac->has_mute_touch_switch || - (wacom_wac->shared &&READ_ONCE (wacom_wac->shared->has_mute_touch_switch))) { + +/* +* This is to setup the touch switch for those devices that report +* pen interface first. The setup can only be done here since this +* routine is only called once. When we are here, the shared +* has_mute_touch_switch has been set by the pad. + +* There are two ways of reporting inputs from firmware: stylus first +* or touch first. This path covers the stylus input first case. +*/ +if (wacom_wac->shared &&READ_ONCE (wacom_wac->shared->has_mute_touch_switch)) {input_set_capability (input_dev,EV_SW ,SW_MUTE_DEVICE ); - wacom_wac->has_mute_touch_switch = true; }/* setup has already been done */ return 0 ;
@@ -4398,7 +4406,26 @@ int wacom_setup_pad_input_capabilities(sbreak ;case INTUOSHT3_BT : +break ; +case HID_GENERIC : +if (wacom_wac->shared) { +/* +* The setup of touch switch capability can only be done +* here for those devices, such as Cintiq Pro 13 and 16, +* that have touch input registered before stylus and pad +* inputs. +* +* There are two ways of reporting inputs from firmware: +* stylus first or touch first. This path covers the touch +* input first case. +*/ +if (wacom_wac->has_mute_touch_switch && + wacom_wac->shared->touch_input) { +input_set_capability (wacom_wac->shared->touch_input, +EV_SW ,SW_MUTE_DEVICE ); + } + }break ;default :
Greg Kroah-Hartman
maintainerPATCH 627/1536 HID: wacom: Write shared touch initial status only once
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ping Cheng <[email protected]>
commit cae3031c691dff0be61a26bc64e31a6939010d5c upstream.
For consistency with how the shared has_mute_touch_switch is handled during registration, let's apply WRITE_ONCE to is_touch_on too.
--- drivers/hid/wacom_sys.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hid/wacom_sys.c +1 -1
@@ -2362,7 +2362,7 @@ static void wacom_set_shared_values(stru* match historic default. */ if (wacom_wac->is_soft_touch_switch) - wacom_wac->shared->is_touch_on = true; +WRITE_ONCE (wacom_wac->shared->is_touch_on, true); }if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) {
Greg Kroah-Hartman
maintainerPATCH 628/1536 klist: avoid accesses after waking klist_remove()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
commit 732e3e10234cbe302d0dcbaa98c91c66628209cb upstream.
klist_remove() waits until a node is unreferenced so that its caller can free the containing object. klist_release() currently publishes waiter->woken and wakes the waiter before its final accesses to the waiter and node. klist_remove() can then return, allowing its stack waiter and the containing object to be freed or reused while klist_release() is still running. In particular, bus_remove_driver() can free drv->p while __device_attach() walks the same bus klist with bus_for_each_drv().
On an arm64 Cortex-A72 system, an unpatched 7.2.0-rc3 kernel with CONFIG_PREEMPT_RT=y and CONFIG_KASAN=y reproduced the bug through the in-tree I2C/at24 path. KASAN reported a use-after-free in klist_dec_and_del() reached from klist_next()/bus_for_each_drv() while at24 was being unregistered.
Clear n_klist and take a task reference before publishing woken. Use release/acquire accesses for that publication and wake the referenced task. The task reference keeps the waiter task alive if it returns and exits before wake_up_process().
--- lib/klist.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
lib/klist.c +12 -4
@@ -36,6 +36,7 @@#include <linux/klist.h> #include <linux/export.h> #include <linux/sched.h> +#include <linux/sched/task.h> /* * Use the lowest bit of n_klist to mark deleted nodes and exclude
@@ -187,18 +188,24 @@ static void klist_release(struct kref *kWARN_ON (!knode_dead (n));list_del (&n->n_node); +knode_set_klist (n,NULL );spin_lock (&klist_remove_lock);list_for_each_entry_safe (waiter, tmp, &klist_remove_waiters, list) { +struct task_struct *p; +if (waiter->node != n)continue ; + p = waiter->process; +get_task_struct (p);list_del (&waiter->list); - waiter->woken =1 ; +/* Publish only after the final waiter and n accesses */ +smp_store_release (&waiter->woken,1 );mb (); -wake_up_process (waiter->process); +wake_up_process (p); +put_task_struct (p); }spin_unlock (&klist_remove_lock); -knode_set_klist (n,NULL ); }static int klist_dec_and_del (struct klist_node *n)
@@ -250,7 +257,8 @@ void klist_remove(struct klist_node *n)for (;;) {set_current_state (TASK_UNINTERRUPTIBLE ); -if (waiter.woken) +/* Pairs with the release store in klist_release() */ +if (smp_load_acquire (&waiter.woken))break ;schedule (); }
Greg Kroah-Hartman
maintainerPATCH 629/1536 objtool/rust: add one more `noreturn` Rust function for Rust 1.101.0
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Miguel Ojeda <[email protected]>
commit 6b704ec9007a3f23ec5ded8f320825ac444f307d upstream.
Starting with Rust 1.101.0 (expected 2026-12-24), objtool may report:
rust/kernel.o: warning: objtool: _R..._4core6result13unwrap_failed...() falls through to next function _R..._4core6result13unwrap_failed...()
(and others) due to calls to the noreturn symbol:
core::result::unwrap_failed::unwrap_failed_inner
Rust introduced this helper when making unwrap_failed generic [1]. The existing entry for unwrap_failed does not match the new helper.
Thus add the mangled one to the list so that objtool knows it is actually noreturn.
See commit 56d680dd23c3 ("objtool/rust: list noreturn Rust functions") for more details.
--- tools/objtool/check.c | 1 + 1 file changed, 1 insertion(+)
tools/objtool/check.c +1 -0
@@ -213,6 +213,7 @@ static bool is_rust_noreturn(const strucstr_ends_with (func->name,"_4core6option13expect_failed" ) ||str_ends_with (func->name,"_4core6option13unwrap_failed" ) ||str_ends_with (func->name,"_4core6result13unwrap_failed" ) || +str_ends_with (func->name,"_4core6result13unwrap_failed19unwrap_failed_inner" ) ||str_ends_with (func->name,"_4core9panicking5panic" ) ||str_ends_with (func->name,"_4core9panicking9panic_fmt" ) || str_ends_with(func->name, "_4core9panicking14panic_explicit") ||
Greg Kroah-Hartman
maintainerPATCH 630/1536 rust: block: fix `Send` bound for `GenDisk`
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andreas Hindborg <[email protected]>
commit e502b667ee70a7fa2a578e7722672ecd4fe0eb81 upstream.
The Send implementation for GenDisk<T> was conditioned on T: Send. This constrains the wrong type. T is the Operations implementation, which is typically a zero-sized marker type that carries no data, so `T:
Send says nothing about whether the data a GenDisk` actually owns can be moved to another thread.
A GenDisk<T> owns the queue data T::QueueData (stored as the gendisk's queuedata and dropped when the GenDisk is dropped) and an Arc<TagSet<T>>. These are the values transferred when a GenDisk is sent across a thread boundary, so the Send bound must constrain exactly them. Bound T::QueueData: Send and Arc<TagSet<T>>: Send instead.
--- rust/kernel/block/mq/gen_disk.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
rust/kernel/block/mq/gen_disk.rs +8 -2
@@ -191,8 +191,14 @@ pub struct GenDisk<T: Operations> { }// SAFETY: `GenDisk` is an owned pointer to a `struct gendisk` and an `Arc` to a -// `TagSet` It is safe to send this to other threads as long as T is Send. -unsafe impl <T :Operations +Send >Send for GenDisk <T > {} +// `TagSet`. It is safe to send this to other threads as long as these two are `Send`. +unsafe impl <T >Send for GenDisk <T > +where +T :Operations , +T ::QueueData :Send , +Arc <TagSet <T >>:Send , +{ +}impl <T :Operations >Drop for GenDisk <T > {fn drop (&mut self) {
Miguel Ojeda
maintainerRe: [PATCH 6.12 0630/1536] rust: block: fix `Send` bound for `GenDisk`
Quoted 21 lines · On Sat, 07 Nov 2026 08:44:06 -0500 Greg Kroah-Hartman…
6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andreas Hindborg <[email protected]>
commit
e502b667ee70a7fa2a578e7722672ecd4fe0eb81upstream.The
Sendimplementation forGenDisk<T>was conditioned onT: Send. This constrains the wrong type.Tis theOperationsimplementation, which is typically a zero-sized marker type that carries no data, so `T:
Sendsays nothing about whether the data aGenDisk` actually owns can be moved to another thread.A
GenDisk<T>owns the queue dataT::QueueData(stored as thegendisk'squeuedataand dropped when theGenDiskis dropped) and anArc<TagSet<T>>. These are the values transferred when aGenDiskis sent across a thread boundary, so theSendbound must constrain exactly them. BoundT::QueueData: SendandArc<TagSet<T>>: Sendinstead.
Quoted 11 lines
Fixes 3253aba3408a ("rust: block: introduce `kernel::block::mq` module")Reported-by Priya Bala Govindasamy <[email protected]>, Dylan Zueck <[email protected]>, Yuan Tan <[email protected]>Signed-off-by Yuan Tan <[email protected]>[ Andreas: Fix tags to make checkpatch happy. Change summary line. ]Signed-off-by Andreas Hindborg <[email protected]>Signed-off-by Jens Axboe <[email protected]>Signed-off-by Greg Kroah-Hartman <[email protected]>
This one breaks most Rust builds:
error[E0220]: associated type `QueueData` not found for `T`
--> rust/kernel/block/mq/gen_disk.rs:198:8
|
198 | T::QueueData: Send,
| ^^^^^^^^^ associated type `QueueData` not foundbecause there is no QueueData in 6.12.y. We would also need commit 06dad60393f2 ("rust: block: implement Send and Sync for TagSet") for the other bound anyway.
I would suggest dropping the patch for the moment.
Andreas: could you please take a look and see how you would like to resolve it, if at all?
Thanks!
Cheers,
Miguel
Sasha Levin
maintainerRe: [PATCH 6.12 0630/1536] rust: block: fix `Send` bound for `GenDisk`
Quoted 8 lines · Miguel Ojeda
This one breaks most Rust builds:
error[E0220]: associated type `QueueData` not found for `T` --> rust/kernel/block/mq/gen_disk.rs:198:8 | 198 | T::QueueData: Send, | ^^^^^^^^^ associated type `QueueData` not found
Quoted 5 lines
because there is no
QueueDatain 6.12.y. We would also need commit06dad60393f2("rust: block: implementSendandSyncforTagSet") for the other bound anyway.I would suggest dropping the patch for the moment.
Dropped from the 6.12 queue, thanks for the report.
Signature · 2 lines
Thanks, Sasha
Greg Kroah-Hartman
maintainerPATCH 631/1536 ALSA: control: Fix UAF in snd_ctl_elem_add() on card disconnect
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 d4febca239be3c91498762dd0535a87d4af1eabc upstream.
A use-after-free can be triggered via SNDRV_CTL_IOCTL_ELEM_ADD when a USB audio card is disconnected while an ELEM_ADD ioctl is in flight.
The reproducer parks the ioctl thread inside copy_from_user() using userfaultfd, then tears down the USB device. Unlike every other ALSA control _user handler (ELEM_INFO, ELEM_READ, ELEM_WRITE, TLV_*), snd_ctl_elem_add_user() never calls snd_power_ref_and_wait(), so the parked thread holds no power reference. snd_card_disconnect() therefore cannot observe it via snd_power_sync_ref() and proceeds unimpeded:
1. card->shutdown is set to 1
2. device_del(&card->card_dev) drops the kobject reference on the
parent USB interface device (card->dev = &intf->dev)
3. The USB core drops its own reference and calls device_release(), freeing the struct usb_interface, including the embedded struct device that card->dev points to
When the userfaultfd is resolved and the thread resumes, snd_ctl_elem_add() acquires controls_rwsem without checking card->shutdown and calls __snd_ctl_add_replace(). Because the reproducer pre-registered the same control, the CTL_ADD_EXCLUSIVE path calls dev_err(card->dev, ...) on the freed USB interface:
KASAN: slab-use-after-free Read in __dev_printk
Add a card->shutdown guard immediately after acquiring controls_rwsem in snd_ctl_elem_add(). At that point card->shutdown is guaranteed to be stable: snd_card_disconnect() sets it before freeing the parent device, and it never transitions back to 0. A thread that acquired the lock before disconnect sees shutdown=0 and holds the write lock through the rest of the operation, preventing concurrent disconnect from proceeding past its own controls_rwsem-less shutdown=1 store (which happened earlier, outside the lock) from racing with dev_err().
--- sound/core/control.c | 2 ++ 1 file changed, 2 insertions(+)
sound/core/control.c +2 -0
@@ -1676,6 +1676,8 @@ static int snd_ctl_elem_add(struct snd_c alloc_size =compute_user_elem_size (private_size, count);guard (rwsem_write)(&card->controls_rwsem); +if (card->shutdown) +return -ENODEV ;if (check_user_elem_overflow (card, alloc_size))return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 632/1536 ALSA: pcmtest: handle multiple wraps in random capture fill
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sung Byeongchan <[email protected]>
commit 6541871e8e63e721733cd120af4d9cd22c5ef62f upstream.
The random capture helpers assume that the data generated for one timer tick wraps the DMA ring at most once. However, b_rw describes 200 ms of audio because the timer runs at 5 Hz, so it can be several times larger than a small ring.
For 48 kHz, S16_LE, four-channel capture with a 512-frame buffer, the DMA ring is 4096 bytes while one tick generates 76800 bytes. After filling the 4096-byte tail, the existing code issues a second 72704-byte write from the ring base, writing 68608 bytes beyond the ring. Both interleaved and non-interleaved capture are affected.
KASAN reports the first write into the adjacent free page as a use-after-free in the random-byte generator. The underlying defect is an out-of-bounds write from the live DMA ring, not a stale DMA allocation.
Split each random write repeatedly at the interleaved ring or per-channel block boundary. Keep the hardware-pointer update exactly once after the complete logical write.
The issue reproduced on three of three clean boots. With this change, the same vulnerable geometry completed six times without a sanitizer finding. Boundary, pattern-fill, no-timer, open/close, and module-reload controls also completed normally.
snd-pcmtest is a test driver, and selecting random fill requires an administrator-controlled module parameter. The written values come from the kernel random generator; no privilege escalation or attacker-controlled write primitive was demonstrated.
--- sound/drivers/pcmtest.c | 42 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 23 deletions(-)
sound/drivers/pcmtest.c +19 -23
@@ -279,39 +279,35 @@ static void fill_block_pattern(struct pcfill_block_pattern_n (v_iter, runtime); } +static void fill_random_block (char *buf,size_t buf_size,size_t pos, +size_t count) +{ +while (count) { +size_t chunk =min (count, buf_size - pos); + +get_random_bytes (buf + pos, chunk); + count -= chunk; + pos =0 ; + } +} +static void fill_block_rand_n (struct pcmtst_buf_iter *v_iter,struct snd_pcm_runtime *runtime) {unsigned int channels = runtime->channels; -// Remaining space in all channel buffers -size_t bytes_remain = runtime->dma_bytes - v_iter->buf_pos; +size_t pos = v_iter->buf_pos / channels;unsigned int i; -for (i =0 ; i < channels; i++) { -if (v_iter->b_rw <= bytes_remain) { -//b_rw - count of bytes must be written for all channels at each timer tick -get_random_bytes (runtime->dma_area +buf_pos_n (v_iter, channels, i), - v_iter->b_rw / channels); - }else { -// Write to the end of buffer and start from the beginning of it -get_random_bytes (runtime->dma_area +buf_pos_n (v_iter, channels, i), - bytes_remain / channels); -get_random_bytes (runtime->dma_area + v_iter->chan_block * i, - (v_iter->b_rw - bytes_remain) / channels); - } - } +for (i =0 ; i < channels; i++) +fill_random_block (runtime->dma_area + v_iter->chan_block * i, + v_iter->chan_block, pos, + v_iter->b_rw / channels);inc_buf_pos (v_iter, v_iter->b_rw, runtime->dma_bytes); }static void fill_block_rand_i (struct pcmtst_buf_iter *v_iter,struct snd_pcm_runtime *runtime) { -size_t in_cur_block = runtime->dma_bytes - v_iter->buf_pos; - -if (v_iter->b_rw <= in_cur_block) { -get_random_bytes (&runtime->dma_area[v_iter->buf_pos], v_iter->b_rw); - }else { -get_random_bytes (&runtime->dma_area[v_iter->buf_pos], in_cur_block); -get_random_bytes (runtime->dma_area, v_iter->b_rw - in_cur_block); - } +fill_random_block (runtime->dma_area, runtime->dma_bytes, + v_iter->buf_pos, v_iter->b_rw);inc_buf_pos (v_iter, v_iter->b_rw, runtime->dma_bytes); }
Greg Kroah-Hartman
maintainerPATCH 633/1536 Bluetooth: hci_vhci: Pin module for debugfs file operations
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bui Viet Dung <[email protected]>
commit 645ee6b176c958579cff1c783413d5cff65c8197 upstream.
An open debugfs file retains its file_operations pointer in the debugfs proxy state. However, force_suspend_fops, force_wakeup_fops, aosp_capable_fops, and force_devcoredump_fops have no .owner set to THIS_MODULE. As a result, full_proxy_open_regular() calls fops_get() which succeeds without taking a reference to the hci_vhci module.
When userspace opens any of these debugfs files and later closes the /dev/vhci file descriptor (triggering vhci_release() and debugfs file removal), the open debugfs file descriptor remains valid in userspace. Because the module refcount was not incremented, the hci_vhci module can be unloaded via delete_module (rmmod hci_vhci).
When the userspace process subsequently closes the debugfs file descriptor, full_proxy_release() accesses the already unmapped file_operations structure, resulting in a kernel page fault / oops:
BUG: unable to handle page fault for address: fffffbfff846f18b #PF: supervisor read access in kernel mode #PF: error_code(0x0000) - not-present page Oops: Oops: 0000 [#1] SMP KASAN NOPTI RIP: 0010:full_proxy_release+0x8e/0x140 Call Trace: <TASK> __fput+0x39f/0xa60 fput_close_sync+0xff/0x200 __x64_sys_close+0x8c/0xf0 do_syscall_64+0xc3/0x590 entry_SYSCALL_64_after_hwframe+0x76/0x7e </TASK> Modules linked in: ... [last unloaded: hci_vhci(E)]
The issue was discovered via manual code audit of drivers/bluetooth/hci_vhci.c and verified on a Linux 7.3-rc6 test VM with CONFIG_BT_VHCI=m by keeping a debugfs file open across controller teardown and module unload.
Set .owner = THIS_MODULE on all four file_operations structures so that debugfs pins the module until all file descriptors are closed.
--- drivers/bluetooth/hci_vhci.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/bluetooth/hci_vhci.c +4 -0
@@ -155,6 +155,7 @@ static ssize_t force_suspend_write(struc }static const struct file_operations force_suspend_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = force_suspend_read, .write = force_suspend_write,
@@ -194,6 +195,7 @@ static ssize_t force_wakeup_write(struct }static const struct file_operations force_wakeup_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = force_wakeup_read, .write = force_wakeup_write,
@@ -263,6 +265,7 @@ static ssize_t aosp_capable_write(struct }static const struct file_operations aosp_capable_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = aosp_capable_read, .write = aosp_capable_write,
@@ -386,6 +389,7 @@ static ssize_t force_devcd_write(struct }static const struct file_operations force_devcoredump_fops = { + .owner =THIS_MODULE , .open = simple_open, .write = force_devcd_write, };
Greg Kroah-Hartman
maintainerPATCH 634/1536 drm/panthor: Fix TOCTOU race between GROUP_REGISTERED check and erase
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Osama Abdelkader <[email protected]>
commit 7764289d76a38c3a2f9b093bf17e193ab54acd70 upstream.
panthor_group_destroy() checks the GROUP_REGISTERED mark and then calls xa_erase() without holding the xarray lock across both. If the handle is destroyed by another thread in between, and a concurrent GROUP_CREATE reuses the freed ID, the first destroy erases and releases the new, still-initializing group, leading to a use-after-free in panthor_group_create().
Do the mark check and erase atomically under xa_lock().
--- drivers/gpu/drm/panthor/panthor_sched.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/gpu/drm/panthor/panthor_sched.c +10 -4
@@ -3533,12 +3533,18 @@ int panthor_group_destroy(struct panthorstruct panthor_group_pool *gpool = pfile->groups;struct panthor_device *ptdev = pfile->ptdev;struct panthor_scheduler *sched = ptdev->scheduler; -struct panthor_group *group; +struct panthor_group *group =NULL ; -if (!xa_get_mark (&gpool->xa, group_handle,GROUP_REGISTERED )) -return -EINVAL ; +/* +* Check the mark and erase the entry atomically, so a concurrent +* destroy + create can't make us erase a group that's still being +* initialized and happens to reuse the same handle. +*/ +xa_lock (&gpool->xa); +if (xa_get_mark (&gpool->xa, group_handle,GROUP_REGISTERED )) + group =__xa_erase (&gpool->xa, group_handle); +xa_unlock (&gpool->xa); - group =xa_erase (&gpool->xa, group_handle);if (!group)return -EINVAL ;
Greg Kroah-Hartman
maintainerPATCH 635/1536 fbdev: atmel_lcdfb: Prevent FIFO work after removal
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yibo Tan <[email protected]>
commit 20b3b97cf89cb381bf07516090d99399cc9b91fd upstream.
The LCD controller IRQ schedules sinfo->task to recover from a FIFO underflow. Probe currently requests the IRQ before initializing the work, so an early interrupt can schedule an uninitialized work item.
The probe error path and remove path cancel the work before freeing the IRQ. A FIFO-underflow interrupt can schedule the work again after that cancellation. framebuffer_release() may then free sinfo while the work is still pending.
KASAN reported a use-after-free in atmel_lcdfb_task() when an underflow interrupt occurred during removal. With the IRQ freed before the work was cancelled, the same test completed without a kernel diagnostic.
Initialize the work before requesting the IRQ. In both cleanup paths, free the IRQ before cancelling the work so that it cannot be scheduled again after cancellation.
--- drivers/video/fbdev/atmel_lcdfb.c | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
drivers/video/fbdev/atmel_lcdfb.c +5 -6
@@ -1148,6 +1148,9 @@ static int atmel_lcdfb_probe(struct plat/* Initialize PWM for contrast or backlight ("off") */ init_contrast (sinfo); +/* Some LCDC recovery operations require process context. */ +INIT_WORK (&sinfo->task, atmel_lcdfb_task); +/* interrupt */ ret =request_irq (sinfo->irq_base, atmel_lcdfb_interrupt,0 , pdev->name, info);if (ret) {
@@ -1155,10 +1158,6 @@ static int atmel_lcdfb_probe(struct plat goto unmap_mmio; } -/* Some operations on the LCDC might sleep and -* require a preemptible task context */ -INIT_WORK (&sinfo->task, atmel_lcdfb_task); - ret =atmel_lcdfb_init_fbinfo (sinfo);if (ret <0 ) {dev_err (dev,"init fbinfo failed: %d\n" , ret);
@@ -1194,8 +1193,8 @@ reset_drvdata:dev_set_drvdata (dev,NULL );fb_dealloc_cmap (&info->cmap); unregister_irqs: -cancel_work_sync (&sinfo->task);free_irq (sinfo->irq_base, info); +cancel_work_sync (&sinfo->task); unmap_mmio:exit_backlight (sinfo);iounmap (sinfo->mmio);
@@ -1232,6 +1231,7 @@ static void atmel_lcdfb_remove(struct plreturn ; sinfo = info->par; +free_irq (sinfo->irq_base, info);cancel_work_sync (&sinfo->task);exit_backlight (sinfo);atmel_lcdfb_power_control (sinfo,0 );
@@ -1240,7 +1240,6 @@ static void atmel_lcdfb_remove(struct plclk_put (sinfo->lcdc_clk);clk_put (sinfo->bus_clk);fb_dealloc_cmap (&info->cmap); -free_irq (sinfo->irq_base, info);iounmap (sinfo->mmio);release_mem_region (info->fix.mmio_start, info->fix.mmio_len);if (platform_get_resource (pdev,IORESOURCE_MEM ,1 )) {
Greg Kroah-Hartman
maintainerPATCH 636/1536 fbdev: udlfb: dont rebuild the mode list while the framebuffer is in use
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiang Mei <[email protected]>
commit ac9cfa552102b8e80e88c2872e80dc9cb5f07dda upstream.
dlfb_setup_modes() frees info->modelist with fb_destroy_modelist() and rebuilds it, but fbcon holds raw pointers into that list in fb_display[i].mode and nothing un-publishes them the way do_unregister_framebuffer() and store_modes() do with fbcon_delete_modelist(). The function does refuse to install a new mode while the framebuffer has users (dlfb->fb_count != 0), but only after the list is already destroyed. Reached from the 0666 "edid" sysfs attribute, an unprivileged write to /sys/class/graphics/fb0/edid therefore fails with -EINVAL and still leaves every fb_display[i].mode dangling; the next console switch reads the freed fb_videomode in fb_videomode_to_var().
Test fb_count before touching the list. fbcon takes a reference through fbcon_open(), so that condition covers exactly the states in which fb_display[] points into the list, and the errno returned to userspace is unchanged.
BUG: KASAN: slab-use-after-free in fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) Read of size 4 at addr ffff8880107b449c by task kworker/1:1/47 Workqueue: events console_callback Call Trace: fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) display_to_var (drivers/video/fbdev/core/fbcon.c:998) fbcon_switch (drivers/video/fbdev/core/fbcon.c:2182) redraw_screen (drivers/tty/vt/vt.c:994) complete_change_console (drivers/tty/vt/vt_ioctl.c:1141) console_callback (drivers/tty/vt/vt.c:3358) process_one_work (kernel/workqueue.c:3396) worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560) kthread (kernel/kthread.c:436) ret_from_fork (arch/x86/kernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) ... The buggy address is located 28 bytes inside of freed 96-byte region [ffff8880107b4480, ffff8880107b44e0)
--- drivers/video/fbdev/udlfb.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/video/fbdev/udlfb.c +5 -0
@@ -1293,6 +1293,11 @@ static int dlfb_setup_modes(struct dlfb_ goto error; } +if (dlfb->fb_count) { + result = -EINVAL ; + goto error; + } +fb_destroy_modelist (&info->modelist);memset (&info->monspecs,0 ,sizeof (info->monspecs));
Greg Kroah-Hartman
maintainerPATCH 637/1536 fs/proc/task_mmu: pin mm_users in do_pagemap_scan()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ngoc Quy <[email protected]>
commit 4fb975471717c953f912776bb60301add1ffae11 upstream.
The PAGEMAP_SCAN ioctl takes mmap_read_lock() on an mm obtained from /proc/<pid>/pagemap without holding a reference to mm_users.
proc_mem_open() deliberately grabs only mm_count, so a consumer that touches the address space has to call mmget_not_zero() first. Every other consumer in this file does -- m_start(), do_procmap_query(), show_smaps_rollup() and pagemap_read() -- but do_pagemap_scan() does not.
Without that reference the target can reach exit_mmap() concurrently, and exit_mmap() calls unmap_vmas() while holding mmap_lock only for reading, which does not exclude the scanner. For ordinary VMAs this is harmless, as free_pgtables() and remove_vma() run afterwards under mmap_write_lock. A shared hugetlb VMA is different: __hugetlb_zap_end() frees the VMA's hugetlb_vma_lock inside the read-locked phase.
walk_hugetlb_range() can therefore load vma->vm_private_data, have the lock freed underneath it, and then down_read() a freed rw_semaphore. The load happens before the freeing side clears the pointer, so this is a use-after-free and not a NULL dereference. Any unprivileged user can reach it with no huge pages configured, as hugetlb_reserve_pages() allocates the lock before the VM_NORESERVE early return.
Pin mm_users across the scan, the way the other consumers do. mmput() from the exiting task can then no longer reach exit_mmap() while a walk is in progress.
--- fs/proc/task_mmu.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
fs/proc/task_mmu.c +7 -2
@@ -2862,15 +2862,18 @@ static long do_pagemap_scan(struct mm_stsize_t n_ranges_out =0 ;int ret; +if (!mmget_not_zero (mm)) +return -ESRCH ; + ret =pagemap_scan_get_args (&p.arg, uarg);if (ret) -return ret; + goto out_mmput; p.masks_of_interest = p.arg.category_mask | p.arg.category_anyof_mask | p.arg.return_mask; ret =pagemap_scan_init_bounce_buffer (&p);if (ret) -return ret; + goto out_mmput;for (walk_start = p.arg.start; walk_start < p.arg.end; walk_start = p.arg.walk_end) {
@@ -2925,6 +2928,8 @@ static long do_pagemap_scan(struct mm_st ret = -EFAULT ;kfree (p.vec_buf); +out_mmput: +mmput (mm);return ret; }
Greg Kroah-Hartman
maintainerPATCH 638/1536 genirq: Defer kfree(irqaction) until irq_thread_dtor() finishes
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Richard Patel <[email protected]>
commit d04adff6860587e843948b0c31174f8ae11b8dfe upstream.
When an interrupt thread exits abnormally via do_exit() (e.g. the interrupt handler oopses) without returning from irq_thread(), a concurrent call to free_irq() could free the irqaction before the irq_thread_dtor() exit task work runs.
irq thread (oopsed) free_irq()
------------------- ----------
do_exit()
exit_mm()
complete_vfork_done() -------> kthread_stop() returns
exit_files() ... kfree(action)
exit_task_work()
irq_thread_dtor()
action->... <- use-after-freeTrack the pending exit work with the IRQTF_EXIT_WORK thread flag, and have __free_irq() wait for the bit to clear before kfree().
irq_thread_dtor() only runs on irq_thread abnormal exit. If that dtor also faults, free_irq() will hang indefinitely, but double IRQ thread faults require a reboot anyways.
[ tglx: Add missing include ]
--- kernel/irq/internals.h | 2 ++ kernel/irq/manage.c | 26 ++++++++++++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-)
kernel/irq/internals.h +2 -0
@@ -30,6 +30,7 @@ extern struct irqaction chained_action;* IRQTF_AFFINITY - irq thread is requested to adjust affinity * IRQTF_FORCED_THREAD - irq action is force threaded * IRQTF_READY - signals that irq thread is ready +* IRQTF_EXIT_WORK - irq thread exit task_work is pending */ enum {IRQTF_RUNTHREAD ,
@@ -37,6 +38,7 @@ enum {IRQTF_AFFINITY ,IRQTF_FORCED_THREAD ,IRQTF_READY , + IRQTF_EXIT_WORK, };/*
kernel/irq/manage.c +20 -6
@@ -21,6 +21,7 @@#include <linux/sched/isolation.h> #include <uapi/linux/sched/types.h> #include <linux/task_work.h> +#include <linux/wait_bit.h> #include "internals.h"
@@ -1230,17 +1231,14 @@ void wake_threads_waitq(struct irq_descwake_up (&desc->wait_for_threads); } -static void irq_thread_dtor (struct callback_head *unused) +static void __irq_thread_dtor (struct irqaction *action) {struct task_struct *tsk = current;struct irq_desc *desc; -struct irqaction *action;if (WARN_ON_ONCE (!(current->flags &PF_EXITING )))return ; - action =kthread_data (tsk); -pr_err ("exiting task \"%s\" (%d) is an active IRQ thread (irq %d)\n" , tsk->comm, tsk->pid, action->irq);
@@ -1257,6 +1255,14 @@ static void irq_thread_dtor(struct callbirq_finalize_oneshot (desc, action); } +static void irq_thread_dtor (struct callback_head *unused) +{ +struct irqaction *action =kthread_data (current); + +__irq_thread_dtor (action); +clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags); +} +static void irq_wake_secondary (struct irq_desc *desc,struct irqaction *action) {struct irqaction *secondary = action->secondary;
@@ -1315,6 +1321,7 @@ static int irq_thread(void *data)else handler_fn = irq_thread_fn; +set_bit (IRQTF_EXIT_WORK , &action->thread_flags);init_task_work (&on_exit_work, irq_thread_dtor);task_work_add (current, &on_exit_work,TWA_NONE );
@@ -1335,6 +1342,7 @@ static int irq_thread(void *data)* oneshot mask bit can be set. */ task_work_cancel_func (current, irq_thread_dtor); +clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags);return 0 ; }
@@ -1872,6 +1880,12 @@ out_mput:return ret; } +static void irq_stop_thread (struct irqaction *action) +{ +kthread_stop_put (action->thread); +wait_on_bit (&action->thread_flags,IRQTF_EXIT_WORK ,TASK_UNINTERRUPTIBLE ); +} +/* * Internal function to unregister an irqaction - used to free * regular and special interrupts that are part of the architecture.
@@ -1976,9 +1990,9 @@ static struct irqaction *__free_irq(stru* the same bit to a newly requested action. */ if (action->thread) { -kthread_stop_put (action->thread); +irq_stop_thread (action);if (action->secondary && action->secondary->thread) -kthread_stop_put (action->secondary->thread); +irq_stop_thread (action->secondary); }/* Last action releases resources */
Greg Kroah-Hartman
maintainerPATCH 639/1536 genirq: Move interrupt thread exit_work object to irqaction
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Richard Patel <[email protected]>
commit 89a9e003a2ef73f67dff03dfd59e0a5474b56b0b upstream.
irq_thread() registers irq_thread_dtor() as exit task_work using a stack-allocated callback_head. On normal interrupt thread exit, this work gets cancelled and never runs.
On x86, an abnormal interrupt thread exit (e.g. handler oops) discards the stack, including the callback_head, while that callback_head is still pending. By the time exit_task_work() runs, the stack memory formerly backing callback_head is already clobbered.
irq_thread() <-- on_exit_work allocated
** IRQ handler faults **
oops_end()
rewind_stack_and_make_dead() <-- on_exit_work freed
make_task_dead()
do_exit(SIGSEGV)
...
exit_shm() <-- on_exit_work clobbered
...
exit_task_work() <-- stack use-after-free
exit_shm()+0x30 <-- wild jump to return addrThus, a benign threaded IRQ oops (e.g. a NULL pointer deref) is turned into a wild jump. This is caught by kernel IBT:
** first fault **
Oops: general protection fault, kernel NULL pointer dereference 0x3c0: 0000 [#1] SMP NOPTI ... ** second fault ** Missing ENDBR: exit_shm+0x30/0x1c0 kernel BUG at arch/x86/kernel/cet.c:133! ... ? task_work_run+0x5c/0x90 ? do_exit+0x209/0x460 ? rewind_stack_and_make_dead+0x16/0x20 ... note: irq/165-AudioDS[1427] exited with irqs disabled Fixing recursive fault but reboot is needed!
Fix this by storing the callback_head in struct irqaction. The irqaction is only freed once irq_thread_dtor() finishes.
--- include/linux/interrupt.h | 2 ++ kernel/irq/manage.c | 9 ++++----- 2 files changed, 6 insertions(+), 5 deletions(-)
include/linux/interrupt.h +2 -0
@@ -118,6 +118,7 @@ typedef irqreturn_t (*irq_handler_t)(int* @thread_flags: flags related to @thread * @thread_mask: bitmask for keeping track of @thread activity * @dir: pointer to the proc/irq/NN/name entry +* @thread_dtor: task_work for @thread irregular exit cleanup */ struct irqaction {irq_handler_t handler;
@@ -133,6 +134,7 @@ struct irqaction {unsigned long thread_mask;const char *name;struct proc_dir_entry *dir; +struct callback_head thread_dtor; }____cacheline_internodealigned_in_smp ;extern irqreturn_t no_action (int cpl,void *dev_id);
kernel/irq/manage.c +4 -5
@@ -1255,9 +1255,9 @@ static void __irq_thread_dtor(struct irqirq_finalize_oneshot (desc, action); } -static void irq_thread_dtor (struct callback_head *unused) +static void irq_thread_dtor (struct callback_head *work) { -struct irqaction *action =kthread_data (current); + struct irqaction *action = container_of(work, struct irqaction, thread_dtor);__irq_thread_dtor (action);clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags);
@@ -1305,7 +1305,6 @@ static void wake_up_and_wait_for_irq_thr*/ static int irq_thread (void *data) { -struct callback_head on_exit_work;struct irqaction *action = data;struct irq_desc *desc =irq_to_desc (action->irq); irqreturn_t (*handler_fn)(struct irq_desc *desc,
@@ -1322,8 +1321,8 @@ static int irq_thread(void *data) handler_fn = irq_thread_fn;set_bit (IRQTF_EXIT_WORK , &action->thread_flags); -init_task_work (&on_exit_work, irq_thread_dtor); -task_work_add (current, &on_exit_work,TWA_NONE ); +init_task_work (&action->thread_dtor, irq_thread_dtor); +task_work_add (current, &action->thread_dtor,TWA_NONE );while (!irq_wait_for_interrupt (desc, action)) {irqreturn_t action_ret;
Greg Kroah-Hartman
maintainerPATCH 640/1536 HID: hiddev: keep state alive through disconnect unlock
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yousef Alhouseen <[email protected]>
commit 03f449b5de36a25fc5eba7dabf2b4494389bdb91 upstream.
mutex_unlock() clears the mutex owner before taking its wait lock. A thread spinning in the final hiddev file release can acquire existancelock after hiddev_disconnect() clears the owner, then free hiddev before the disconnecting thread reaches the mutex wait lock. This causes a use-after-free in the mutex slow unlock path.
Give the connection and each open file an explicit reference. Drop each reference only after its existancelock critical section has completed, so neither unlock path can free the mutex while the other is still using it.
--- drivers/hid/usbhid/hiddev.c | 37 +++++++++++++++++++------------------ include/linux/hiddev.h | 2 ++ 2 files changed, 21 insertions(+), 18 deletions(-)
drivers/hid/usbhid/hiddev.c +19 -18
@@ -46,6 +46,12 @@ struct hiddev_list {struct mutex thread_lock; }; +static void hiddev_put (struct hiddev *hiddev) +{ +if (refcount_dec_and_test (&hiddev->refcount)) +kfree (hiddev); +} +/* * Find a report, given the report's type and ID. The ID can be specified * indirectly by REPORT_ID_FIRST (which returns the first report of the given
@@ -216,26 +222,21 @@ static int hiddev_fasync(int fd, structstatic int hiddev_release (struct inode * inode,struct file * file) {struct hiddev_list *list = file->private_data; +struct hiddev *hiddev = list->hiddev;unsigned long flags; -spin_lock_irqsave (&list->hiddev->list_lock, flags); +spin_lock_irqsave (&hiddev->list_lock, flags);list_del (&list->node); -spin_unlock_irqrestore (&list->hiddev->list_lock, flags); +spin_unlock_irqrestore (&hiddev->list_lock, flags); -mutex_lock (&list->hiddev->existancelock); -if (!--list->hiddev->open) { -if (list->hiddev->exist) { -hid_hw_close (list->hiddev->hid); -hid_hw_power (list->hiddev->hid,PM_HINT_NORMAL ); - }else { -mutex_unlock (&list->hiddev->existancelock); -kfree (list->hiddev); -vfree (list); -return 0 ; - } +mutex_lock (&hiddev->existancelock); +if (!--hiddev->open && hiddev->exist) { +hid_hw_close (hiddev->hid); +hid_hw_power (hiddev->hid,PM_HINT_NORMAL ); } -mutex_unlock (&list->hiddev->existancelock); +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev);vfree (list);return 0 ;
@@ -270,6 +271,7 @@ static int __hiddev_open(struct hiddev *spin_unlock_irq (&hiddev->list_lock); file->private_data = list; +refcount_inc (&hiddev->refcount);return 0 ;
@@ -897,6 +899,7 @@ int hiddev_connect(struct hid_device *hiINIT_LIST_HEAD (&hiddev->list);spin_lock_init (&hiddev->list_lock);mutex_init (&hiddev->existancelock); +refcount_set (&hiddev->refcount,1 ); hid->hiddev = hiddev; hiddev->hid = hid; hiddev->exist =1 ;
@@ -937,9 +940,7 @@ void hiddev_disconnect(struct hid_deviceif (hiddev->open) {hid_hw_close (hiddev->hid);wake_up_interruptible (&hiddev->wait); -mutex_unlock (&hiddev->existancelock); - }else { -mutex_unlock (&hiddev->existancelock); -kfree (hiddev); } +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev); }
include/linux/hiddev.h +2 -0
@@ -13,6 +13,7 @@#ifndef _HIDDEV_H#define _HIDDEV_H +#include <linux/refcount.h> #include <uapi/linux/hiddev.h>
@@ -24,6 +25,7 @@ struct hiddev {int minor;int exist;int open; +refcount_t refcount;struct mutex existancelock;wait_queue_head_t wait;struct hid_device *hid;
Greg Kroah-Hartman
maintainerPATCH 641/1536 io_uring/io-wq: save worker type before dropping its reference
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 37e425460b7c41687e51e3254b1eb1d799da9614 upstream.
io_wq_cancel_tw_create() inspects cb->func after calling io_worker_cancel_cb(). For an existing worker, that call can drop the last worker reference and wake io_worker_exit(). If the canceling task is preempted, the worker can be unlinked and freed by kfree_rcu() before the callback function is inspected. KASAN reports a slab-use-after-free read in this path.
Save whether the callback belongs to an unpublished continuation worker while its reference is still held, then use the saved result for the conditional free. This preserves the existing accounting and frees only the worker allocated for the canceled continuation.
--- io_uring/io-wq.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
io_uring/io-wq.c +5 -3
@@ -1328,14 +1328,16 @@ static void io_wq_cancel_tw_create(strucwhile ((cb =task_work_cancel_match (wq->task, io_task_work_match, wq)) !=NULL ) {struct io_worker *worker; +bool free_worker; worker = container_of(cb, struct io_worker, create_work); -io_worker_cancel_cb (worker);/* * Only the worker continuation helper has worker allocated and -* hence needs freeing. +* hence needs freeing. Save this before dropping its reference. */ -if (cb->func == create_worker_cont) + free_worker = cb->func == create_worker_cont; +io_worker_cancel_cb (worker); +if (free_worker)kfree (worker); } }
Greg Kroah-Hartman
maintainerPATCH 642/1536 KVM: PPC: Book3S HV: Add SRCU protection for virtual-mode HPT hcalls
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit 61a39797bb136243c48b46e2586d8a9e2cea6a89 upstream.
The virtual-mode HPT hcall handlers (H_ENTER, H_REMOVE, H_BULK_REMOVE, H_CLEAR_REF, H_CLEAR_MOD) call into book3s_hv_rm_mmu.c, which accesses memslots via kvm_memslots_raw(). kvm_memslots_raw() uses rcu_dereference_raw_check() to bypass SRCU lockdep annotation checking. This is safe in real mode because the entire guest entry/exit is wrapped in srcu_read_lock/unlock inside kvmppc_run_core() and kvmhv_run_single_vcpu().
However, since commit 6165d5dd99db ("KVM: PPC: Book3S HV: add virtual mode handlers for HPT hcalls and page faults"), these same handlers are also executed in virtual mode via kvmppc_pseries_do_hcall(), which runs after SRCU has already been released on guest exit.
A concurrent KVM_SET_USER_MEMORY_REGION deletion or move can therefore call synchronize_srcu_expedited() — which does not wait for this thread — and then kfree(slot) and vfree(slot->arch.rmap) while the hcall handler still holds a raw pointer to the memslot. lock_rmap() then writes to freed vmalloc memory, leading to use-after-free and memory corruption. Because kvm_memslots_raw() suppresses lockdep checks, this race is entirely silent.
Fix this by factoring out the 7 HPT hcall handlers (H_REMOVE, H_ENTER, H_READ, H_CLEAR_MOD, H_CLEAR_REF, H_PROTECT, H_BULK_REMOVE) into a helper function, kvmppc_pseries_do_hpt_hcall(), and wrapping its call site in srcu_read_lock(&kvm->srcu) / srcu_read_unlock(&kvm->srcu, idx). Targeting only the HPT hcalls avoids wrapping non-HPT hcalls that sleep (such as H_CONFER, H_REGISTER_VPA, H_PAGE_INIT) or handlers that already acquire SRCU internally (such as H_RTAS).
--- arch/powerpc/kvm/book3s_hv.c | 70 +++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 35 deletions(-)
arch/powerpc/kvm/book3s_hv.c +35 -35
@@ -1139,6 +1139,38 @@ static long kvmppc_h_rpt_invalidate(strureturn H_SUCCESS ; } +static long kvmppc_pseries_do_hpt_hcall (struct kvm_vcpu *vcpu,unsigned long req) +{ +switch (req) { +case H_REMOVE : +return kvmppc_h_remove (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 )); +case H_ENTER : +return kvmppc_h_enter (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 ), +kvmppc_get_gpr (vcpu,7 )); +case H_READ : +return kvmppc_h_read (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_CLEAR_MOD : +return kvmppc_h_clear_mod (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_CLEAR_REF : +return kvmppc_h_clear_ref (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_PROTECT : +return kvmppc_h_protect (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 )); +case H_BULK_REMOVE : +return kvmppc_h_bulk_remove (vcpu); + } + +return H_FUNCTION ; +} +int kvmppc_pseries_do_hcall (struct kvm_vcpu *vcpu) {struct kvm *kvm = vcpu->kvm;
@@ -1154,47 +1186,15 @@ int kvmppc_pseries_do_hcall(struct kvm_vswitch (req) {case H_REMOVE : - ret =kvmppc_h_remove (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_ENTER : - ret =kvmppc_h_enter (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 ), -kvmppc_get_gpr (vcpu,7 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_READ : - ret =kvmppc_h_read (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_CLEAR_MOD : - ret =kvmppc_h_clear_mod (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_CLEAR_REF : - ret =kvmppc_h_clear_ref (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_PROTECT : - ret =kvmppc_h_protect (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_BULK_REMOVE : - ret =kvmppc_h_bulk_remove (vcpu); + idx =srcu_read_lock (&kvm->srcu); + ret =kvmppc_pseries_do_hpt_hcall (vcpu, req); +srcu_read_unlock (&kvm->srcu, idx);if (ret ==H_TOO_HARD )return RESUME_HOST ;break ;
Greg Kroah-Hartman
maintainerPATCH 643/1536 media: cx23885: unregister DVB bus when SP2 CI setup fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
commit 22f552ff726a82a086be4ef02ce5099a0e8624b6 upstream.
The DVBSKY S950C, DVBSKY T980C and TechnoTrend CT2-4500 CI paths register the DVB bus before attaching their SP2 CI client. If that client cannot be created, bound, or pinned, the current error path removes the I2C frontend components and only deallocates the frontend list, leaving the registered DVB adapter behind. Removing an I2C demod before unregistering the DVB bus can also expose the use-after-free ordering fixed for the normal remove path.
Unregister the DVB bus immediately when SP2 CI setup fails, before the existing I2C client cleanup. The bus helper empties the frontend list, so the later frontend deallocation has nothing left to release. Keep failures from vb2_dvb_register_bus() on the existing cleanup path. Also release an unbound SP2 client and propagate the actual I2C creation or CI registration error.
This issue was identified during our ongoing static-analysis research while reviewing kernel code.
--- drivers/media/pci/cx23885/cx23885-dvb.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/media/pci/cx23885/cx23885-dvb.c +10 -4
@@ -1160,8 +1160,12 @@ static int dvb_register_ci_mac(struct cx info.platform_data = &sp2_config;request_module (info.type); client_ci =i2c_new_client_device (&i2c_bus->i2c_adap, &info); -if (!i2c_client_has_driver (client_ci)) +if (IS_ERR (client_ci)) +return PTR_ERR (client_ci); +if (!client_ci->dev.driver) { +i2c_unregister_device (client_ci);return -ENODEV ; + }if (!try_module_get (client_ci->dev.driver->owner)) {i2c_unregister_device (client_ci);return -ENODEV ;
@@ -1204,7 +1208,7 @@ static int dvb_register(struct cx23885_tint (*p_set_voltage)(struct dvb_frontend *fe,enum fe_sec_voltage voltage) =NULL ;int mfe_shared =0 ;/* bus not shared by default */ -int ret; +int ret = -EINVAL ;/* Get the first frontend */ fe0 =vb2_dvb_get_frontend (&port->frontends,1 );
@@ -2586,8 +2590,10 @@ static int dvb_register(struct cx23885_t goto frontend_detach; ret =dvb_register_ci_mac (port); -if (ret) +if (ret) { +vb2_dvb_unregister_bus (&port->frontends); goto frontend_detach; + }return 0 ;
@@ -2618,7 +2624,7 @@ frontend_detach: port->gate_ctrl =NULL ;vb2_dvb_dealloc_frontends (&port->frontends); -return -EINVAL ; +return ret; }int cx23885_dvb_register (struct cx23885_tsport *port)
Greg Kroah-Hartman
maintainerPATCH 644/1536 media: gspca: use vb2_video_unregister_device() on disconnect
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shuangpeng Bai <[email protected]>
commit 3dbbbc3cafa2de377d9b97af4e35b8b6b5282047 upstream.
gspca uses vb2_fop_release(), but gspca_disconnect() only unregisters the video device. If the queue owner closes the device after USB disconnect, vb2_fop_release() releases the queue and invokes gspca_stop_streaming() at that point.
gspca_stream_off() calls subdriver stop callbacks and usb_set_interface() through gspca_dev->dev. By the time the late close runs, the USB core can have freed the usb_device, resulting in a use-after-free. This was observed as a KASAN use-after-free in sd_stopN().
Use vb2_video_unregister_device() so the queue is released and streaming is stopped synchronously during disconnect, while the usb_device is still valid. Since the helper takes the queue lock, which is usb_lock, call it after dropping that lock.
--- drivers/media/usb/gspca/gspca.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/media/usb/gspca/gspca.c +1 -2
@@ -1643,9 +1643,8 @@ void gspca_disconnect(struct usb_interfa#endif v4l2_device_disconnect (&gspca_dev->v4l2_dev); -video_unregister_device (&gspca_dev->vdev); -mutex_unlock (&gspca_dev->usb_lock); +vb2_video_unregister_device (&gspca_dev->vdev);/* (this will call gspca_release() immediately or on last close) */ v4l2_device_put (&gspca_dev->v4l2_dev);
Greg Kroah-Hartman
maintainerPATCH 645/1536 media: imx-jpeg: cancel timeout worker when streaming stops
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 78fdfbf117c409273eecbfa7a528ef42358a0e38 upstream.
Each per-fd context ctx owns a delayed_work (ctx->task_timer, callback mxc_jpeg_device_run_timeout) armed via schedule_delayed_work() at the end of mxc_jpeg_device_run() to recover a stalled encode/decode job. The only existing cancellation is cancel_delayed_work() in the frame-done IRQ handler, which de-queues a pending work item but does not wait for a callback that has already started, and it only runs when a frame completes.
When the fd is closed while a job is in flight (the frame-done IRQ has not fired yet), nothing syncs the worker before mxc_jpeg_release() frees ctx with kfree() after v4l2_m2m_ctx_release(). A queued or executing mxc_jpeg_device_run_timeout() can then recover ctx through container_of(&ctx->task_timer) and dereference it (ctx->mxc_jpeg, slot_data, dev_warn) after ctx has been freed.
Cancel the worker from mxc_jpeg_stop_streaming(). The cancel cannot live in mxc_jpeg_release(): mxc_jpeg_device_run() arms the timer while holding only hw_lock, not the mxc_jpeg->lock mutex that release holds, so a cancel in release could still race a concurrent mxc_jpeg_device_run() that re-arms the timer afterwards. mxc_jpeg_stop_streaming() instead runs inside v4l2_m2m_ctx_release() -> vb2_queue_release(), i.e. after v4l2_m2m_cancel_job() has set TRANS_ABORT and waited for any in-flight job to finish (so __v4l2_m2m_try_queue() will not queue and v4l2_m2m_try_run() will not run any further job for this context, which prevents mxc_jpeg_device_run() from re-arming the timer) and before the m2m context is freed. cancel_delayed_work_sync() removes a pending work item and waits for a running callback, so the worker can no longer race with the subsequent kfree(). The cancel is placed before the buffer-release loop so a concurrently running timeout callback cannot race with it over the same buffers. If the frame-done IRQ canceled a still-pending timer, this cancel is a no-op; if the timeout callback has already started, it waits for the callback to finish. The same mxc_jpeg_stop_streaming() call is also reached from VIDIOC_STREAMOFF, which drains the worker early, although STREAMOFF itself does not free ctx -- the use-after-free arises only when the fd is later closed.
This bug was found by static analysis.
--- drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c +2 -0
@@ -1660,6 +1660,8 @@ static void mxc_jpeg_stop_streaming(strudev_dbg (ctx->mxc_jpeg->dev,"Stop streaming ctx=%p" , ctx); +cancel_delayed_work_sync (&ctx->task_timer); +/* Release all active buffers */ for (;;) {if (V4L2_TYPE_IS_OUTPUT (q->type))
Greg Kroah-Hartman
maintainerPATCH 646/1536 media: marvell: mcam: stop DMA and cancel s_bh_work before freeing DMA buffers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 0f29f84317c1e35f6a9265277be33e60d3fc8c1c upstream.
In vmalloc mode the frame-completion IRQ queues mcam_frame_work() on cam->s_bh_work, which memcpy()s from the dma_bufs[] that mcam_free_dma_bufs() frees with dma_free_coherent(). mccic_shutdown() frees those buffers without stopping the controller, so while streaming a late frame IRQ can re-arm the work after the buffers are gone, causing a use-after-free.
Stop the controller in mccic_shutdown() when streaming is still active (gated on an open fd, which holds a runtime-PM reference, so the device is powered), cancel s_bh_work in mcam_free_dma_bufs(), and move INIT_WORK() into mccic_register() before the device can be published.
--- drivers/media/platform/marvell/mcam-core.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/media/platform/marvell/mcam-core.c +13 -1
@@ -406,6 +406,8 @@ static void mcam_free_dma_bufs(struct mc {int i; +cancel_work_sync (&cam->s_bh_work); +for (i =0 ; i < cam->nbufs; i++) {dma_free_coherent (cam->dev, cam->dma_buf_size, cam->dma_bufs[i], cam->dma_handles[i]);
@@ -1310,7 +1312,6 @@ static int mcam_setup_vb2(struct mcam_cabreak ;case B_vmalloc:#ifdef MCAM_MODE_VMALLOC -INIT_WORK (&cam->s_bh_work, mcam_frame_work); vq->ops = &mcam_vb2_ops; vq->mem_ops = &vb2_vmalloc_memops; cam->dma_setup = mcam_ctlr_dma_vmalloc;
@@ -1868,6 +1869,12 @@ int mccic_register(struct mcam_camera *c goto out; } +#ifdef MCAM_MODE_VMALLOC +/* Init before sensor bind: armed by IRQ, cancelled on probe-error paths. */ +if (cam->buffer_mode == B_vmalloc) +INIT_WORK (&cam->s_bh_work, mcam_frame_work); +#endif +mutex_init (&cam->s_mutex); cam->state =S_NOTREADY ;mcam_set_config_needed (cam,1 );
@@ -1926,10 +1933,15 @@ void mccic_shutdown(struct mcam_camera ** take it down again will wedge the machine, which is frowned * upon. */ +mutex_lock (&cam->s_mutex);if (!list_empty (&cam->vdev.fh_list)) {cam_warn (cam,"Removing a device with users!\n" ); +/* Stop so the IRQ can't re-arm s_bh_work after the buffers are freed. */ +if (cam->state ==S_STREAMING ) +mcam_ctlr_stop_dma (cam);sensor_call (cam, core, s_power,0 ); } +mutex_unlock (&cam->s_mutex);if (cam->buffer_mode == B_vmalloc)mcam_free_dma_bufs (cam);v4l2_ctrl_handler_free (&cam->ctrl_handler);
Greg Kroah-Hartman
maintainerPATCH 647/1536 media: microchip-csi2dc: fix async notifier leak on probe error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cong Nguyen <[email protected]>
commit c7528789244ce7329ca883170fb9315d739ae985 upstream.
csi2dc_of_parse() ends up calling csi2dc_prepare_notifier(), which registers the V4L2 async notifier with v4l2_async_nf_register(). The probe error label csi2dc_probe_cleanup_notifier is reached after csi2dc_of_parse() has already succeeded (e.g. when media entity init, csi2dc_power() or v4l2_async_register_subdev() fail), but it calls only v4l2_async_nf_cleanup() and never v4l2_async_nf_unregister().
The notifier therefore stays chained in the global notifier_list while the enclosing struct csi2dc_device is freed, leading to list corruption and a use-after-free when the list is next walked.
Unregister the notifier before cleaning it up on the error path, matching the teardown already done in csi2dc_remove().
--- drivers/media/platform/microchip/microchip-csi2dc.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/platform/microchip/microchip-csi2dc.c +1 -0
@@ -736,6 +736,7 @@ static int csi2dc_probe(struct platform_return 0 ; csi2dc_probe_cleanup_notifier: +v4l2_async_nf_unregister (&csi2dc->notifier);v4l2_async_nf_cleanup (&csi2dc->notifier); csi2dc_probe_cleanup_entity:media_entity_cleanup (&csi2dc->csi2dc_sd.entity);
Greg Kroah-Hartman
maintainerPATCH 648/1536 media: microchip-isc: take a reference on the parsed endpoints
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Balakrishnan Sambath <[email protected]>
commit f2eb2fd388bf3f1959556a326e797cacca341c86 upstream.
for_each_endpoint_of_node() drops the reference on the current node as it advances. xisc_parse_dt() and isc_parse_dt() store the node in subdev_entity->epn and release it later with of_node_put(), but never took their own reference, so the stored pointer refers to an already-released node. This underflows the refcount and can use-after-free, reachable through the camera device tree overlay.
Take a reference with of_node_get() when storing the node, and drop it in microchip_isc_subdev_cleanup() so the entities the bind loop never reaches on an early exit do not leak it.
--- drivers/media/platform/microchip/microchip-isc-base.c | 6 +++++ drivers/media/platform/microchip/microchip-sama5d2-isc.c | 17 ++++++++++----- drivers/media/platform/microchip/microchip-sama7g5-isc.c | 17 ++++++++++----- 3 files changed, 30 insertions(+), 10 deletions(-)
drivers/media/platform/microchip/microchip-isc-base.c +6 -0
@@ -1862,6 +1862,12 @@ void microchip_isc_subdev_cleanup(structlist_for_each_entry (subdev_entity, &isc->subdev_entities, list) {v4l2_async_nf_unregister (&subdev_entity->notifier);v4l2_async_nf_cleanup (&subdev_entity->notifier); +/* +* Release the endpoint reference taken while parsing. It is +* NULL for entities the bind loop already consumed, so this +* only drops the ones left over on an early exit. +*/ +of_node_put (subdev_entity->epn); }INIT_LIST_HEAD (&isc->subdev_entities);
drivers/media/platform/microchip/microchip-sama5d2-isc.c +12 -5
@@ -356,28 +356,30 @@ static int isc_parse_dt(struct device *dstruct device_node *epn;struct isc_subdev_entity *subdev_entity;unsigned int flags; +int ret;INIT_LIST_HEAD (&isc->subdev_entities);for_each_endpoint_of_node (np, epn) {struct v4l2_fwnode_endpoint v4l2_epn = { .bus_type =0 }; -int ret; ret =v4l2_fwnode_endpoint_parse (of_fwnode_handle (epn), &v4l2_epn);if (ret) { -of_node_put (epn);dev_err (dev,"Could not parse the endpoint\n" ); -return -EINVAL ; +of_node_put (epn); + ret = -EINVAL ; + goto err_cleanup; } subdev_entity =devm_kzalloc (dev,sizeof (*subdev_entity),GFP_KERNEL );if (!subdev_entity) {of_node_put (epn); -return -ENOMEM ; + ret = -ENOMEM ; + goto err_cleanup; } - subdev_entity->epn = epn; + subdev_entity->epn =of_node_get (epn); flags = v4l2_epn.bus.parallel.flags;
@@ -398,6 +400,11 @@ static int isc_parse_dt(struct device *d }return 0 ; + +err_cleanup: +list_for_each_entry (subdev_entity, &isc->subdev_entities, list) +of_node_put (subdev_entity->epn); +return ret; }static int microchip_isc_probe (struct platform_device *pdev)
drivers/media/platform/microchip/microchip-sama7g5-isc.c +12 -5
@@ -340,6 +340,7 @@ static int xisc_parse_dt(struct device *struct isc_subdev_entity *subdev_entity;unsigned int flags;bool mipi_mode; +int ret;INIT_LIST_HEAD (&isc->subdev_entities);
@@ -347,23 +348,24 @@ static int xisc_parse_dt(struct device *for_each_endpoint_of_node (np, epn) {struct v4l2_fwnode_endpoint v4l2_epn = { .bus_type =0 }; -int ret; ret =v4l2_fwnode_endpoint_parse (of_fwnode_handle (epn), &v4l2_epn);if (ret) { -of_node_put (epn);dev_err (dev,"Could not parse the endpoint\n" ); -return -EINVAL ; +of_node_put (epn); + ret = -EINVAL ; + goto err_cleanup; } subdev_entity =devm_kzalloc (dev,sizeof (*subdev_entity),GFP_KERNEL );if (!subdev_entity) {of_node_put (epn); -return -ENOMEM ; + ret = -ENOMEM ; + goto err_cleanup; } - subdev_entity->epn = epn; + subdev_entity->epn =of_node_get (epn); flags = v4l2_epn.bus.parallel.flags;
@@ -387,6 +389,11 @@ static int xisc_parse_dt(struct device * }return 0 ; + +err_cleanup: +list_for_each_entry (subdev_entity, &isc->subdev_entities, list) +of_node_put (subdev_entity->epn); +return ret; }static int microchip_xisc_probe (struct platform_device *pdev)
Greg Kroah-Hartman
maintainerPATCH 649/1536 media: redrat3: fix UAF in probe error path leaving rc device registered
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rik van Riel <[email protected]>
commit af452b9e01331b5338a1e5141624f17607239207 upstream.
redrat3 stores its device name and phys path inside the main rr3 structure, and the rc device's device_name and input_phys point into rr3. When the RC device is registered, it keeps those pointers.
KASAN: slab-use-after-free in string_nocheck lib/vsprintf.c:648 Read of size 1 at addr ffff888051fda758 by task udevd/7464 Call Trace: string_nocheck lib/vsprintf.c:648 [inline] string+0x216/0x2d0 lib/vsprintf.c:730 vsnprintf+0x74a/0xef0 lib/vsprintf.c:2945 vscnprintf+0x41/0x90 lib/vsprintf.c:3014 sysfs_emit+0x10e/0x180 fs/sysfs/file.c:761 input_dev_show_name+0x58/0x70 drivers/input/input.c:1282 Allocated by task 10: redrat3_dev_probe+0x477/0x2570 drivers/media/rc/redrat3.c:1023 Freed by task 10: redrat3_delete drivers/media/rc/redrat3.c:466 [inline] redrat3_dev_probe+0x1bf4/0x2570 drivers/media/rc/redrat3.c:1124
Syzkaller triggers this via usb probing. It probes the RedRat3 USB interface, which calls redrat3_dev_probe() in redrat3.c. That function allocates rr3, then builds an rc device whose name points into rr3 via redrat3_init_rc_dev() in redrat3.c, and registers it with rc_register_device().
When the detector enable fails after the RC device is registered, the probe jumps to the led_free path. That path unregisters the LED but does not unregister the RC device before freeing rr3 via redrat3_delete() in redrat3.c. The RC device still holds device_name = rr3->name which is now freed.
Later udevd reads /sys/.../input device name via sysfs_emit() in file.c, which calls input_dev_show_name() in input.c, which emits dev->name which is the freed rr3->name.
When the detector enable fails after the RC device is registered, the error path must not leave the RC device registered. Make the probe error path clean up the same way redrat3_dev_disconnect() does.
This change should be safe because the RC device is fully registered at this point and its teardown via rc_unregister_device() is protected by the input device mutex, and rr3 is still alive during unregister so device_name remains valid until after unregister. The URBs are killed before rc_free, so no completion can run after rc is freed. No new lock ordering is introduced.
--- drivers/media/rc/redrat3.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/rc/redrat3.c +4 -0
@@ -977,6 +977,7 @@ static int redrat3_dev_probe(struct usb_struct device *dev = &intf->dev;struct usb_host_interface *uhi;struct redrat3_dev *rr3; +struct rc_dev *rc;struct usb_endpoint_descriptor *ep;struct usb_endpoint_descriptor *ep_narrow =NULL ;struct usb_endpoint_descriptor *ep_wide =NULL ;
@@ -1121,9 +1122,12 @@ static int redrat3_dev_probe(struct usb_return 0 ; led_free: +rc_unregister_device (rr3->rc);led_classdev_unregister (&rr3->led); redrat_free: + rc = rr3->rc;redrat3_delete (rr3, rr3->udev); +rc_free_device (rc); no_endpoints:return retval;
Greg Kroah-Hartman
maintainerPATCH 650/1536 mm/slab: sample slab_state once in kmem_cache_destroy()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Imre Kaloz <[email protected]>
commit 088bfdc0d7947d623f4899b9011c866e4445074d upstream.
kmem_cache_release() tests slab_state >= FULL after kmem_cache_destroy() has dropped slab_mutex and unlinked the cache, and for a SLAB_TYPESAFE_BY_RCU cache after rcu_barrier(). If slab_late_init() runs before that test it sets slab_state to FULL but skips the unlinked cache, which never got a sysfs entry, so sysfs_slab_release() calls kobject_put() on a kobject that was never initialized:
WARNING: lib/kobject.c:734 at kobject_put+0x64/0x2c0, CPU#1: kworker/u8:3/55 kobject: '(null)' ((____ptrval____)): is not initialized, yet kobject_put() is being called. refcount_t: underflow; use-after-free. kobject_put+0x64/0x2c0 sysfs_slab_release+0xc/0x20 kmem_cache_destroy+0x104/0x1e0 bioset_exit+0x13c/0x1e0 disk_release+0x54/0x140 put_disk+0x18/0x40 floppy_async_init+0xbec/0xd10
slab_state >= FULL asks whether the cache has a kobject, which cache creation skips while slab_state <= UP. UP is the state just below FULL, so a false sample cannot skip a kobject_put() that was owed.
Seen on sparc64 at boot, where the asynchronous floppy init tears down its bio slab while the late initcalls are running.
Sample slab_state once, under slab_mutex which slab_late_init() holds when it sets FULL, and use the result for both the unlink and the release.
The history of this problem dates back to v3.2:
Commit 69cb8e6b7c29 ("slub: free slabs without holding locks") in v3.2 moved sysfs_slab_remove() outside slub_lock and introduced a race condition between kmem_cache_destroy() and slab_sysfs_init().
Commit 945cf2b6199be ("mm/sl[aou]b: Extract a common function for kmem_cache_destroy") in v3.7 accidentally closed the race while extracting a common implementation for kmem_cache_destroy().
Commit 5413dfba88d6 ("slub: drop mutex before deleting sysfs entry") in v3.8 re-opened the race by dropping slab_mutex around sysfs_slab_remove() in __kmem_cache_shutdown(), to avoid a lockdep splat between slab_mutex and the sysfs lock.
Commit 657dc2f97220 ("slab: remove synchronous rcu_barrier() call in memcg cache release path") in v4.11 shifted from synchronous rcu_barrier() to asynchronous RCU work for SLAB_TYPESAFE_BY_RCU caches. That commit, again, accidentally closed the race by moving sysfs_slab_release() to shutdown_cache(), but only for !SLAB_TYPESAFE_BY_RCU caches because destruction of SLAB_TYPESAFE_BY_RCU caches is done in an RCU work.
Commit 0495e337b703 ("mm/slab_common: Deleting kobject in kmem_cache_destroy() without holding slab_mutex/cpu_hotplug_lock") in v6.0 re-introduced the race for !SLAB_TYPESAFE_BY_RCU caches.
--- mm/slab_common.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-)
mm/slab_common.c +13 -4
@@ -487,10 +487,10 @@ EXPORT_SYMBOL(kmem_buckets_create);* and release of the kobject does not need slab_mutex or cpu_hotplug_lock * protection. So they are now done without holding those locks. */ -static void kmem_cache_release (struct kmem_cache *s) +static void kmem_cache_release (struct kmem_cache *s,bool sysfs_ready) {kfence_shutdown_cache (s); -if (__is_defined (SLAB_SUPPORTS_SYSFS ) && slab_state >=FULL ) +if (__is_defined (SLAB_SUPPORTS_SYSFS ) && sysfs_ready)sysfs_slab_release (s);else slab_kmem_cache_release (s);
@@ -505,6 +505,7 @@ void slab_kmem_cache_release(struct kmemvoid kmem_cache_destroy (struct kmem_cache *s) { +bool sysfs_ready;int err;if (unlikely (!s) || !kasan_check_byte (s))
@@ -549,10 +550,18 @@ void kmem_cache_destroy(struct kmem_cachlist_del (&s->list); +/* +* slab_late_init() sets slab_state to FULL under slab_mutex and adds +* sysfs entries only for caches still on the list. Sample the state +* here, so that a cache unlinked before that point is not handed to +* sysfs_slab_release() with an uninitialized kobject. +*/ + sysfs_ready = slab_state >=FULL ; +mutex_unlock (&slab_mutex);cpus_read_unlock (); -if (slab_state >=FULL ) +if (sysfs_ready)sysfs_slab_unlink (s);debugfs_slab_release (s);
@@ -562,7 +571,7 @@ void kmem_cache_destroy(struct kmem_cachif (s->flags &SLAB_TYPESAFE_BY_RCU )rcu_barrier (); -kmem_cache_release (s); +kmem_cache_release (s, sysfs_ready); }EXPORT_SYMBOL (kmem_cache_destroy);
Greg Kroah-Hartman
maintainerPATCH 651/1536 mm: khugepaged: fix folio is used after folio_put/unlock()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vernon Yang <[email protected]>
commit 9010383e71e6ce75fcd3c8f87133c8ce6c0e6ab4 upstream.
On the rollback path, folio_put() has already dropped the last reference of new_folio. On the success path, new_folio is already unlocked and can be freed concurrently. The trace_mm_khugepaged_collapse_file() is left with a dangling folio pointer.
So using the folio_pfn() before dropping the reference, closing use-after-free window.
--- include/trace/events/huge_memory.h | 6 +++--- mm/khugepaged.c | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-)
include/trace/events/huge_memory.h +3 -3
@@ -207,10 +207,10 @@ TRACE_EVENT(mm_khugepaged_scan_file, ); TRACE_EVENT(mm_khugepaged_collapse_file, - TP_PROTO(struct mm_struct *mm, struct folio *new_folio, pgoff_t index, + TP_PROTO(struct mm_struct *mm, unsigned long new_pfn, pgoff_t index, unsigned long addr, bool is_shmem, struct file *file, int nr, int result), - TP_ARGS(mm, new_folio, index, addr, is_shmem, file, nr, result), + TP_ARGS(mm, new_pfn, index, addr, is_shmem, file, nr, result), TP_STRUCT__entry( __field(struct mm_struct *, mm) __field(unsigned long, hpfn)
@@ -224,7 +224,7 @@ TRACE_EVENT(mm_khugepaged_collapse_file,TP_fast_assign ( __entry->mm = mm; - __entry->hpfn = new_folio ?folio_pfn (new_folio) :-1 ; + __entry->hpfn = new_pfn; __entry->index = index; __entry->addr = addr; __entry->is_shmem = is_shmem;
mm/khugepaged.c +3 -1
@@ -1811,6 +1811,7 @@ static int collapse_file(struct mm_strucstruct address_space *mapping = file->f_mapping;struct page *dst;struct folio *folio, *tmp, *new_folio; +unsigned long new_pfn =-1 ;pgoff_t index =0 , end = start +HPAGE_PMD_NR ;LIST_HEAD (pagelist);XA_STATE_ORDER (xas, &mapping->i_pages, start,HPAGE_PMD_ORDER );
@@ -1823,6 +1824,7 @@ static int collapse_file(struct mm_struc result =alloc_charge_folio (&new_folio, mm, cc);if (result !=SCAN_SUCCEED ) goto out; + new_pfn =folio_pfn (new_folio);mapping_set_update (&xas, mapping);
@@ -2242,7 +2244,7 @@ rollback:folio_put (new_folio); out:VM_BUG_ON (!list_empty (&pagelist)); -trace_mm_khugepaged_collapse_file (mm, new_folio, index, addr, is_shmem, file,HPAGE_PMD_NR , result); +trace_mm_khugepaged_collapse_file (mm, new_pfn, index, addr, is_shmem, file,HPAGE_PMD_NR , result);return result; }
Greg Kroah-Hartman
maintainerPATCH 652/1536 serial: core: shut down initialized port on removal
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Putko <[email protected]>
commit 810d467c11f0c85107874d08dfdd11acba6aa0c0 upstream.
When a serial port configured as a console is opened and subsequently closed, tty_port_shutdown() skips invoking port->ops->shutdown() because port->console is true. As a result, tty_port_initialized() remains true and the port's interrupt handler stays registered in the irq subsystem.
If the underlying device is later unbound or removed (e.g. via sysfs driver unbind or device hot-unplug), serial_core_remove_one_port() unregisters the console, frees uport->name via kfree(), and tears down the port without shutting it down or freeing its IRQ. Consequently, the irqaction descriptor remains registered in genirq with action->name pointing to freed memory.
This triggers a use-after-free read whenever genirq accesses action->name, such as when reading /proc/interrupts:
BUG: KASAN: slab-use-after-free in string+0x476/0x570 Call Trace: string+0x476/0x570 vsnprintf+0x422/0x1300 seq_printf+0x... show_interrupts+...
Fix this by acquiring port->mutex in serial_core_remove_one_port() after console unregistration, clearing port->console under the mutex to prevent data races with concurrent tty_port_shutdown(), and invoking uart_shutdown(NULL, state) if the port remains initialized. This ensures that port->ops->shutdown() is called and the IRQ is freed before kfree(uport->name).
--- drivers/tty/serial/serial_core.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/tty/serial/serial_core.c +7 -0
@@ -3271,6 +3271,13 @@ static void serial_core_remove_one_port(if (uart_console (uport))unregister_console (uport->cons); + scoped_guard(mutex, &port->mutex) { + port->console = false; + +if (tty_port_initialized (port)) +uart_shutdown (NULL , state); + } +/* * Free the port IO and memory resources, if any. */
Greg Kroah-Hartman
maintainerPATCH 653/1536 xen-blkfront: unbind irq before tearing down ring and shadow requests
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuchao Zhang <[email protected]>
commit f3e27b7955727a4d7c0e9264a2a209fbba788bdc upstream.
In blkif_free_ring(), the driver tears down the ring's persistent grants, shadow request arrays, and shared ring structure (xenbus_teardown_ring), and only calls unbind_from_irqhandler() at the very end.
While blkif_free_ring() is freeing persistent grants and clearing the shadow array, the event channel interrupt (blkif_interrupt) is still registered and active. If an interrupt arrives from the backend during this teardown window, blkif_interrupt() reads rinfo->ring.sring and, via blkif_completion(), accesses rinfo->shadow[id].grants_used and rinfo->shadow[id].sg. blkif_free_ring() tears these structures down without holding rinfo->ring_lock, and the handler only checks info->connected at entry, so this is a real race resulting in a use-after-free or NULL pointer dereference.
Fix this by moving unbind_from_irqhandler() to the beginning of blkif_free_ring(). Calling unbind_from_irqhandler() first frees the IRQ and synchronizes with any in-flight interrupt handlers on other CPUs before ring memory and shadow request structures are deallocated, matching the teardown order in drivers/net/xen-netfront.c.
Message-ID: <[email protected]>
--- drivers/block/xen-blkfront.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/block/xen-blkfront.c +8 -4
@@ -1212,6 +1212,14 @@ static void blkif_free_ring(struct blkfrint i, j, segs;/* +* Interrupt teardown must be done ahead of freeing queue-related +* data, otherwise the interrupt handler can race with the cleanup. +*/ +if (rinfo->irq) +unbind_from_irqhandler (rinfo->irq, rinfo); + rinfo->evtchn = rinfo->irq =0 ; + +/* * Remove indirect pages, this only happens when using indirect * descriptors but not persistent grants */
@@ -1293,10 +1301,6 @@ free_shadow:/* Free resources associated with old device channel. */ xenbus_teardown_ring ((void **)&rinfo->ring.sring, info->nr_ring_pages, rinfo->ring_ref); - -if (rinfo->irq) -unbind_from_irqhandler (rinfo->irq, rinfo); - rinfo->evtchn = rinfo->irq =0 ; }static void blkif_free (struct blkfront_info *info,int suspend)
Greg Kroah-Hartman
maintainerPATCH 654/1536 wifi: ath9k: delete channel-context timers on deinit
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
commit 81394dfb9a7905472957628b560ae894eae3a30f upstream.
ath9k_deinit_channel_context() cancels chanctx_work but does not delete the offchannel and sched timers set up by ath9k_init_channel_context(). If either timer fires after deinit (e.g. during driver unload or suspend), it accesses sc->sc_ah which may already be freed by ath9k_hw_deinit(), causing a use-after-free.
Delete both timers with timer_shutdown_sync() before cancelling the work item.
--- drivers/net/wireless/ath/ath9k/channel.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/net/wireless/ath/ath9k/channel.c +2 -0
@@ -1368,6 +1368,8 @@ void ath9k_init_channel_context(struct avoid ath9k_deinit_channel_context (struct ath_softc *sc) { +timer_shutdown_sync (&sc->sched.timer); +timer_shutdown_sync (&sc->offchannel.timer);cancel_work_sync (&sc->chanctx_work); }