7.3.5-rc1 review
Subsystems (2)
Greg Kroah-Hartman
maintainerPATCH 116/507 ASoC: SOF: Intel: hda-sdw-bpt: Stop active DMA before closing BPT streams
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
[ Upstream commit 348bc756d912dd8f47fd36c167075717951a515e ]
When sdw_enable_stream() fails in intel_ace2x_bpt_send_async() after hda_sdw_bpt_send_async() has already started the TX and RX DMA streams, intel_ace2x_bpt_close_stream() invokes hda_sdw_bpt_close() directly without calling hda_sdw_bpt_wait(). As a result, hda_sdw_bpt_dma_deprepare() tears down the DMA buffers and BDL while the DMA hardware is still running.
Disable any running TX or RX BPT DMA stream at the start of hda_sdw_bpt_close() before unmapping channels and depreparing DMA resources.
--- sound/soc/sof/intel/hda-sdw-bpt.c | 6 ++++++ 1 file changed, 6 insertions(+)
sound/soc/sof/intel/hda-sdw-bpt.c +6 -0
@@ -456,6 +456,12 @@ int hda_sdw_bpt_close(struct device *dev, int link_id, struct hdac_ext_stream *bint ret;int ret1; +if (bpt_rx_stream &&hdac_stream (bpt_rx_stream)->running) +hda_sdw_bpt_dma_disable (dev, bpt_rx_stream); + +if (bpt_tx_stream &&hdac_stream (bpt_tx_stream)->running) +hda_sdw_bpt_dma_disable (dev, bpt_tx_stream); +/* * In the case of SoundWire we need to reset the PCMSyCM registers. * Need to continue depreparing the DMA buffers even if this fails.
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 117/507 x86/bugs: Select the BHI mitigation based on the attack vector properly
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Breno Leitao <[email protected]>
[ Upstream commit 3457b3bcd344005af894876cab4e634cabdcbb62 ]
The BHI mitigation selection is inconsistent with the documentation (attack_vector_controls.rst), which lists BHI under both the user->kernel and guest->host attack vectors. bhi_select_mitigation() only enables it when CPU_MITIGATE_GUEST_HOST is set; otherwise it selects BHI_MITIGATION_OFF, even if CPU_MITIGATE_USER_KERNEL is set.
As a result, a kernel compiled with KVM disabled gets BHI automatically disabled, since CPU_MITIGATE_GUEST_HOST defaults to off without KVM. This is a bug, given that CPU_MITIGATE_USER_KERNEL still needs it: on affected Intel CPUs these kernels lose BHI_DIS_S or the BHB clearing loop by default. Booting with mitigations=auto,no_guest_host has the same effect.
Select BHI_MITIGATION_ON whenever user->kernel is mitigated, and keep BHI_MITIGATION_VMEXIT_ONLY for the guest->host-only case.
[ bp: Clarify commit title. ]
--- arch/x86/kernel/cpu/bugs.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-)
arch/x86/kernel/cpu/bugs.c +5 -7
@@ -2088,14 +2088,12 @@ static void __init bhi_select_mitigation(void)if (bhi_mitigation !=BHI_MITIGATION_AUTO )return ; -if (cpu_attack_vector_mitigated (CPU_MITIGATE_GUEST_HOST )) { -if (cpu_attack_vector_mitigated (CPU_MITIGATE_USER_KERNEL )) - bhi_mitigation =BHI_MITIGATION_ON ; -else - bhi_mitigation =BHI_MITIGATION_VMEXIT_ONLY ; - }else { +if (cpu_attack_vector_mitigated (CPU_MITIGATE_USER_KERNEL )) + bhi_mitigation =BHI_MITIGATION_ON ; +else if (cpu_attack_vector_mitigated (CPU_MITIGATE_GUEST_HOST )) + bhi_mitigation =BHI_MITIGATION_VMEXIT_ONLY ; +else bhi_mitigation =BHI_MITIGATION_OFF ; - } }static void __init bhi_update_mitigation (void )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 118/507 x86/csum: Relax the len and proto constraints in 32-bit csum_ipv6_magic()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
[ Upstream commit f01a394fe2a00d3cb4cf2cda279c58604a2540ad ]
Building an i386 allmodconfig kernel with clang fails since allmodconfig started building netfilter with GCOV profiling:
In file included from net/netfilter/nf_synproxy_core.c:7:
In file included from ./include/linux/skbuff.h:26:
In file included from ./include/net/checksum.h:21:
In file included from ./arch/x86/include/asm/checksum.h:9:
./arch/x86/include/asm/checksum_32.h:149:6: error: inline assembly requires more registers than available
The csum_ipv6_magic() asm needs five registers at once: the early-clobber sum plus register-only inputs for saddr, daddr, htonl(len) and htonl(proto). With frame pointers enabled, six general purpose registers are left to choose from.
In synproxy_send_tcp_ipv6(), the GCOV instrumentation lets clang's machine scheduler move the copies of two incoming register arguments, EDX and ECX, below the asm.
Both registers then stay live across the asm, which leaves four registers for its five operands. This is LLVM issue #206307. The error goes away without either GCOV or frame pointers, and it reproduces with clang 19-22.
Neither len nor proto has to be in a register: ADCL also takes a 32-bit memory or immediate source operand. Use "g" for both, so the asm needs at most three registers whatever the caller looks like.
ASM_INPUT_G, which normally replaces "g" to avoid clang's poor handling of it, is not enough here. It expands to "ir" for clang, so callers that pass a variable protocol, like nf_ip6_checksum(), would still need five registers. With "g", clang passes a non-constant len or proto through the stack and still turns constants into immediates.
[ bp: Make Rosen Penev the author because of a previous identical submission
https://lore.kernel.org/all/[email protected]/ and Sasha graciously agreeing and giving his much more detailed commit message explaining the background of why this exists. ]
--- arch/x86/include/asm/checksum_32.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/include/asm/checksum_32.h +1 -1
@@ -159,7 +159,7 @@ static inline __sum16 csum_ipv6_magic(const struct in6_addr *saddr, "adcl $0, %0 ;\n" : "=&r" (sum) : "r" (saddr), "r" (daddr), - "r" (htonl(len)), "r" (htonl(proto)), "0" (sum) + "g" (htonl(len)), "g" (htonl(proto)), "0" (sum) : "memory");return csum_fold (sum);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 119/507 drm/i915/psr: Clear selective fetch area when duplicating plane state
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jouni Högander <[email protected]>
[ Upstream commit cbe565475988d3b22dc36f13c14d9f0eec1685cd ]
We are currently not clearing selective fetch area when duplicating plane state. This is causing problem when plane is re-used for another purpose. Fix this by clearing selective fetch area when duplicating plane state.
Now as the state is cleared we need to ensure we have consistent selective fetch area in plane state on full update. Earlier this was relying on selective fetch area being copied from old state on state duplicate. Now this isn't true anymore as we are clearing it. Tackle this by setting full plane area as selective fetch area for each plane on full update. Rename the label as skip_su_area_calc as the loop setting the plane selective fetch area is not skipped anymore.
Move also psr2_sel_fetch_pipe_state_supported check after psr2_su_area initialization. The loop is run on full update as well now and it needs initialized psr2_su_area. Clip_area_update is only touching rect height and x1/x2 are left untouched.
Don't set the area at all for planes not intersecting with the selective update area. It is already zero sized after plane state duplicate.
--- drivers/gpu/drm/i915/display/intel_plane.c | 1 + drivers/gpu/drm/i915/display/intel_psr.c | 24 ++++++++++------------ 2 files changed, 12 insertions(+), 13 deletions(-)
drivers/gpu/drm/i915/display/intel_plane.c +1 -0
@@ -140,6 +140,7 @@ intel_plane_duplicate_state(struct drm_plane *plane) intel_state->dpt_vma =NULL ; intel_state->fence_id =-1 ; intel_state->damage =DRM_RECT_INIT (0 ,0 ,0 ,0 ); + intel_state->psr2_sel_fetch_area =DRM_RECT_INIT (0 ,0 ,0 ,0 );/* add reference to fb */ if (intel_state->hw.fb)
drivers/gpu/drm/i915/display/intel_psr.c +11 -13
@@ -2913,16 +2913,16 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,if (!crtc_state->enable_psr2_sel_fetch)return 0 ; -if (!psr2_sel_fetch_pipe_state_supported (crtc_state)) { - full_update = true; - goto skip_sel_fetch_set_loop; - } - crtc_state->psr2_su_area.x1 =0 ; crtc_state->psr2_su_area.y1 =-1 ; crtc_state->psr2_su_area.x2 =drm_rect_width (&display_area); crtc_state->psr2_su_area.y2 =-1 ; +if (!psr2_sel_fetch_pipe_state_supported (crtc_state)) { + full_update = true; + goto skip_su_area_calc; + } +/* * Calculate minimal selective fetch area of each plane and calculate * the pipe damaged area.
@@ -3006,7 +3006,7 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, }if (full_update) - goto skip_sel_fetch_set_loop; + goto skip_su_area_calc;intel_psr_apply_su_area_workarounds (crtc_state);
@@ -3042,6 +3042,11 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,break ; }while (su_area_changed); +skip_su_area_calc: +if (full_update) +clip_area_update (&crtc_state->psr2_su_area, &display_area, + &display_area); +/* * Now that we have the pipe damaged area check if it intersect with * every plane, if it does set the plane selective fetch area.
@@ -3058,8 +3063,6 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, inter = crtc_state->psr2_su_area; sel_fetch_area = &new_plane_state->psr2_sel_fetch_area;if (!drm_rect_intersect (&inter, &new_plane_state->uapi.dst)) { - sel_fetch_area->y1 =-1 ; - sel_fetch_area->y2 =-1 ;/* * if plane sel fetch was previously enabled -> * disable it
@@ -3099,11 +3102,6 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, } } -skip_sel_fetch_set_loop: -if (full_update) -clip_area_update (&crtc_state->psr2_su_area, &display_area, - &display_area); -psr2_man_trk_ctl_calc (crtc_state, full_update); crtc_state->pipe_srcsz_early_tpt =psr2_pipe_srcsz_early_tpt_calc (crtc_state, full_update);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 120/507 drm/i915/display: Add enabled pipe planes into state for selective fetch
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jouni Högander <[email protected]>
[ Upstream commit 94cb1f08b197d9ae932ff98c741bd0dbc96e17e8 ]
Selective fetch support for biplanar formats relies on linking of UV and the Y planes. Planes that are not part of the atomic state are pulled in by the drm_atomic_add_affected_planes. If the UV plane is added into the state by drm_atomic_add_affected_planes in the selective fetch calculation, the linking isn't done anymore and the Y plane is left disabled.
Fix this by adding affected planes already in intel_add_affected_planes if selective fetch is enabled.
Remove redundant drm_atomic_add_affected_planes from intel_psr2_sel_fetch_update and redundant check for plane selective fetch support that is not needed as all planes are already in atomic state on first loop iterating them. Also switch to intel_atomic_get_new_plane_state for linked plane new plane state.
--- drivers/gpu/drm/i915/display/intel_plane.c | 10 +++++++++ drivers/gpu/drm/i915/display/intel_psr.c | 25 +++++++--------------- 2 files changed, 18 insertions(+), 17 deletions(-)
drivers/gpu/drm/i915/display/intel_plane.c +10 -0
@@ -1931,6 +1931,16 @@ static int intel_add_affected_planes(struct intel_atomic_state *state) ret =intel_joiner_add_affected_planes (state,intel_crtc_joined_pipe_mask (crtc_state));if (ret)return ret; + +/* +* Add affected plane here to ensure UV and Y plane linking is +* in place if UV plane is added as a part of selective update. +*/ +if (crtc_state->enable_psr2_sel_fetch) { + ret =intel_plane_add_affected (state, crtc); +if (ret) +return ret; + } }return 0 ;
drivers/gpu/drm/i915/display/intel_psr.c +8 -17
@@ -2895,7 +2895,7 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, .y2 = crtc_state->hw.adjusted_mode.crtc_vdisplay, };bool full_update = false, su_area_changed; -int i, ret; +int i;/* * Selective fetch is not always usable, for instance it is dropped
@@ -3010,19 +3010,15 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,intel_psr_apply_su_area_workarounds (crtc_state); - ret =drm_atomic_add_affected_planes (&state->base, &crtc->base); -if (ret) -return ret; - do { bool cursor_in_su_area = false; /* * Adjust su area to cover cursor fully as necessary - * (early transport). This needs to be done after - * drm_atomic_add_affected_planes to ensure visible - * cursor is added into affected planes even when - * cursor is not updated by itself. + * (early transport). A visible cursor is in the state + * even when it is not updated by itself as all planes + * of the pipe are added into the state before the plane + * checks when selective fetch is enabled. */ intel_psr2_sel_fetch_et_alignment(state, crtc, &display_area, &cursor_in_su_area);
@@ -3073,11 +3069,6 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,continue ; } -if (!psr2_sel_fetch_plane_state_supported (new_plane_state)) { - full_update = true; -break ; - } - sel_fetch_area = &new_plane_state->psr2_sel_fetch_area; sel_fetch_area->y1 = inter.y1 - new_plane_state->uapi.dst.y1; sel_fetch_area->y2 = inter.y2 - new_plane_state->uapi.dst.y1;
@@ -3091,9 +3082,9 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,struct intel_plane_state *linked_new_plane_state;struct drm_rect *linked_sel_fetch_area; - linked_new_plane_state =intel_atomic_get_plane_state (state, linked); -if (IS_ERR (linked_new_plane_state)) -return PTR_ERR (linked_new_plane_state); + linked_new_plane_state =intel_atomic_get_new_plane_state (state, linked); +if (!linked_new_plane_state) +return -EINVAL ; linked_sel_fetch_area = &linked_new_plane_state->psr2_sel_fetch_area; linked_sel_fetch_area->y1 = sel_fetch_area->y1;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 121/507 drm/i915/psr: Disable linked plane sel fetch as well
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jouni Högander <[email protected]>
[ Upstream commit b56721c32eb3ad0f086fdc0f33479be395e43bb9 ]
Currently we are not setting linked plane selective area when selective fetch is about to be disabled for the UV plane. Fix this by simplifying the loop by just handling plane selective fetch disable and area setting same way.
Also set the update_planes bit based on comparing old and new plane selective fetch area. This way both the plane and its linked Y plane are updated only when their selective fetch area changed.
--- drivers/gpu/drm/i915/display/intel_psr.c | 27 ++++++++++++------------ 1 file changed, 13 insertions(+), 14 deletions(-)
drivers/gpu/drm/i915/display/intel_psr.c +13 -14
@@ -3058,21 +3058,14 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, inter = crtc_state->psr2_su_area; sel_fetch_area = &new_plane_state->psr2_sel_fetch_area; -if (!drm_rect_intersect (&inter, &new_plane_state->uapi.dst)) { -/* -* if plane sel fetch was previously enabled -> -* disable it -*/ -if (drm_rect_height (&old_plane_state->psr2_sel_fetch_area) >0 ) - crtc_state->update_planes |=BIT (plane->id); - -continue ; +if (drm_rect_intersect (&inter, &new_plane_state->uapi.dst)) { + sel_fetch_area->y1 = inter.y1 - new_plane_state->uapi.dst.y1; + sel_fetch_area->y2 = inter.y2 - new_plane_state->uapi.dst.y1; } - sel_fetch_area = &new_plane_state->psr2_sel_fetch_area; - sel_fetch_area->y1 = inter.y1 - new_plane_state->uapi.dst.y1; - sel_fetch_area->y2 = inter.y2 - new_plane_state->uapi.dst.y1; - crtc_state->update_planes |=BIT (plane->id); +if (!drm_rect_equals (&old_plane_state->psr2_sel_fetch_area, + sel_fetch_area)) + crtc_state->update_planes |=BIT (plane->id);/* * Sel_fetch_area is calculated for UV plane. Use
@@ -3080,16 +3073,22 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,*/ if (linked) {struct intel_plane_state *linked_new_plane_state; +struct intel_plane_state *linked_old_plane_state;struct drm_rect *linked_sel_fetch_area; linked_new_plane_state =intel_atomic_get_new_plane_state (state, linked);if (!linked_new_plane_state)return -EINVAL ; + linked_old_plane_state =intel_atomic_get_old_plane_state (state, linked); + linked_sel_fetch_area = &linked_new_plane_state->psr2_sel_fetch_area; linked_sel_fetch_area->y1 = sel_fetch_area->y1; linked_sel_fetch_area->y2 = sel_fetch_area->y2; - crtc_state->update_planes |=BIT (linked->id); + +if (!drm_rect_equals (&linked_old_plane_state->psr2_sel_fetch_area, + linked_sel_fetch_area)) + crtc_state->update_planes |=BIT (linked->id); } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 122/507 drm/i915/psr: Fix SFF and CFF CTL register bit definitions
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jouni Högander <[email protected]>
[ Upstream commit 15b3187740291c4705b995bbf984da462e9f1e35 ]
Single full frame bit in SFF_CTL and continuous full frame bit in CFF_CTL are bit 0. Fix the definitions accordingly.
--- drivers/gpu/drm/i915/display/intel_psr_regs.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/gpu/drm/i915/display/intel_psr_regs.h +2 -2
@@ -254,12 +254,12 @@#define _LNL_SFF_CTL_A 0x60918#define _LNL_SFF_CTL_B 0x61918#define LNL_SFF_CTL (tran) _MMIO_TRANS(tran, _LNL_SFF_CTL_A, _LNL_SFF_CTL_B) -#define LNL_SFF_CTL_SF_SINGLE_FULL_FRAME REG_BIT(1) +#define LNL_SFF_CTL_SF_SINGLE_FULL_FRAME REG_BIT(0)#define _LNL_CFF_CTL_A 0x6091c#define _LNL_CFF_CTL_B 0x6191c#define LNL_CFF_CTL (tran) _MMIO_TRANS(tran, _LNL_CFF_CTL_A, _LNL_CFF_CTL_B) -#define LNL_CFF_CTL_SF_CONTINUOUS_FULL_FRAME REG_BIT(1) +#define LNL_CFF_CTL_SF_CONTINUOUS_FULL_FRAME REG_BIT(0)/* PSR2 Early transport */ #define _PIPE_SRCSZ_ERLY_TPT_A 0x70074
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 123/507 drm/i915/psr: Dont clip plane state destination rectangle
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jouni Högander <[email protected]>
[ Upstream commit e30830d21860fbf030ad162c3db4d1219477dfb5 ]
clip_area_update() uses drm_rect_intersect which modifies passed r1 rectangle. Early transport alignment passes the cursor uapi.dst rectangle to clip_area_update, so the cursor uapi.dst is unintentionally modified by drm_rect_intersect.
Fix this by using local copy in clip_area_update(). Also make the damage and the display area const.
--- drivers/gpu/drm/i915/display/intel_psr.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-)
drivers/gpu/drm/i915/display/intel_psr.c +11 -9
@@ -2702,23 +2702,25 @@ static u32 psr2_pipe_srcsz_early_tpt_calc(struct intel_crtc_state *crtc_state, }static void clip_area_update (struct drm_rect *overlap_damage_area, -struct drm_rect *damage_area, -struct drm_rect *display_area) +const struct drm_rect *damage_area, +const struct drm_rect *display_area) { -if (!drm_rect_intersect (damage_area, display_area)) +struct drm_rect inter = *damage_area; + +if (!drm_rect_intersect (&inter, display_area))return ;if (overlap_damage_area->y1 ==-1 ) { - overlap_damage_area->y1 = damage_area->y1; - overlap_damage_area->y2 = damage_area->y2; + overlap_damage_area->y1 = inter.y1; + overlap_damage_area->y2 = inter.y2;return ; } -if (damage_area->y1 < overlap_damage_area->y1) - overlap_damage_area->y1 = damage_area->y1; +if (inter.y1 < overlap_damage_area->y1) + overlap_damage_area->y1 = inter.y1; -if (damage_area->y2 > overlap_damage_area->y2) - overlap_damage_area->y2 = damage_area->y2; +if (inter.y2 > overlap_damage_area->y2) + overlap_damage_area->y2 = inter.y2; }static bool intel_psr2_sel_fetch_pipe_alignment (struct intel_crtc_state *crtc_state)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 124/507 drm/i915/display: Add quirk to force backlight type on some TUXEDO devices
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Werner Sembach <[email protected]>
[ Upstream commit 88d804cd1be9a8ffcaf67f1a414ee92b5166a0a8 ]
The display backlight on TUXEDO DX1708 and InsanityBook 15 v1 have a broken VBT in the AUO 12701 and AUO 12701 panels, but not others. They are advertising INTEL_BACKLIGHT_DISPLAY_DDI, but are actually failing to use the Intel interface. Adding a fallback to the VESA interface gives these devices a working backlight for both the broken and non broken panel VBTs.
Forcing the fallback can already be achieved via a module parameter, but this patch adds a quirk to apply this by default on the mentioned devices.
This commit does not actually test for the exact panels as the ID that is used in the intel_dpcd_quirks list is sadly zeroed on the devices, but afaik all these devices use try_intel_interface first anyway so all the quirk does is to add the fallback to try_vesa_interface, so the behaviour on the devices not needing the quirk and fallback should functionally stay the same.
--- .../drm/i915/display/intel_dp_aux_backlight.c | 22 ++++++++++++++++- drivers/gpu/drm/i915/display/intel_quirks.c | 24 +++++++++++++++++++ drivers/gpu/drm/i915/display/intel_quirks.h | 1 + 3 files changed, 46 insertions(+), 1 deletion(-)
drivers/gpu/drm/i915/display/intel_dp_aux_backlight.c +21 -1
@@ -41,6 +41,7 @@#include "intel_display_types.h" #include "intel_dp.h" #include "intel_dp_aux_backlight.h" +#include "intel_quirks.h" /* * DP AUX registers for Intel's proprietary HDR backlight interface. We define
@@ -687,11 +688,30 @@ int intel_dp_aux_init_backlight_funcs(struct intel_connector *connector)struct drm_device *dev = connector->base.dev;struct intel_panel *panel = &connector->panel;bool try_intel_interface = false, try_vesa_interface = false; +int enable_dpcd_backlight; + +/* +* Some devices have a broken VBT in some Panels, but not others, +* advertising INTEL_BACKLIGHT_DISPLAY_DDI, but actually failing to use +* the Intel interface. Adding a fallback to the Vesa interface gives +* these devices a working backlight for both the broken and non broken +* panel VBTs. +* +* This fallback can not be made the general default as this has broken +* other devices in the past whose VBT correctly reports +* INTEL_BACKLIGHT_DISPLAY_DDI and whose PWM path is the actual +* backlight control, but whose DPCD optimistically advertises +* DP_EDP_BACKLIGHT_AUX_ENABLE_CAP / _BRIGHTNESS_AUX_SET_CAP. +*/ + enable_dpcd_backlight = display->params.enable_dpcd_backlight; +if (enable_dpcd_backlight ==INTEL_DP_AUX_BACKLIGHT_AUTO && +intel_has_dpcd_quirk (intel_dp,QUIRK_ENABLE_DPCD_BACKLIGHT )) + enable_dpcd_backlight =INTEL_DP_AUX_BACKLIGHT_ON ;/* Check the VBT and user's module parameters to figure out which * interfaces to probe */ -switch (display->params.enable_dpcd_backlight) { +switch (enable_dpcd_backlight) {case INTEL_DP_AUX_BACKLIGHT_OFF :return -ENODEV ;case INTEL_DP_AUX_BACKLIGHT_AUTO :
drivers/gpu/drm/i915/display/intel_quirks.c +24 -0
@@ -100,6 +100,14 @@ static void quirk_disable_psr2(struct intel_display *display)drm_info (display->drm,"PSR2 support not currently available for this setup, applying disable PSR2 quirk\n" ); } +static void quirk_enable_dpcd_backlight (struct intel_dp *intel_dp) +{ +struct intel_display *display =to_intel_display (intel_dp); + +intel_set_dpcd_quirk (intel_dp,QUIRK_ENABLE_DPCD_BACKLIGHT ); +drm_info (display->drm,"Applying Enable DPCD Backlight quirk\n" ); +} +struct intel_quirk {int device;int subsystem_vendor;
@@ -289,6 +297,22 @@ static const struct intel_dpcd_quirk intel_dpcd_quirks[] = { .sink_oui = SINK_OUI(0x00, 0x22, 0xb9), .hook = quirk_disable_edp_panel_replay, }, +/* TUXEDO InsanityBook 15 v1 */ + { + .device = 0x591b, + .subsystem_vendor = 0x1558, + .subsystem_device = 0x9501, + .sink_oui = SINK_OUI(0x38, 0xec, 0x11), + .hook = quirk_enable_dpcd_backlight, + }, +/* TUXEDO DX1708 */ + { + .device = 0x3e9b, + .subsystem_vendor = 0x1558, + .subsystem_device = 0x8500, + .sink_oui = SINK_OUI(0x38, 0xec, 0x11), + .hook = quirk_enable_dpcd_backlight, + }, };void intel_init_quirks (struct intel_display *display)
drivers/gpu/drm/i915/display/intel_quirks.h +1 -0
@@ -23,6 +23,7 @@ enum intel_quirk_id {QUIRK_EDP_LIMIT_RATE_HBR2 ,QUIRK_DISABLE_EDP_PANEL_REPLAY ,QUIRK_DISABLE_PSR2 , + QUIRK_ENABLE_DPCD_BACKLIGHT, };void intel_init_quirks (struct intel_display *display);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 125/507 drm/i915/gem: Reset err for each fence entry
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lu Yao <[email protected]>
[ Upstream commit 31643dc89818d9b65bf42ecb1c67c99b64146fba ]
If dma_fence_chain_find_seqno() failed once, 'err' will store val in the following loop. May causing returns '-EINVAL' even though that entry never called dma_fence_chain_find_seqno() at all.
--- drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c +1 -1
@@ -2790,7 +2790,6 @@ add_timeline_fence_array(struct i915_execbuffer *eb,u64 __user *user_values;struct eb_fence *f;u64 nfences; -int err =0 ; nfences = timeline_fences->fence_count;if (!nfences)
@@ -2828,6 +2827,7 @@ add_timeline_fence_array(struct i915_execbuffer *eb,struct drm_syncobj *syncobj;struct dma_fence *fence =NULL ;u64 point; +int err =0 ; if (__copy_from_user(&user_fence, user_fences++,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 126/507 drm/i915/display: Single scaler per pipe on WCL
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vidya Srinivas <[email protected]>
[ Upstream commit 25ea7671bdbc85820026776cbe22df41c560d518 ]
WCL has only one scaler per pipe. Set num_scalers to 1 for WCL.
v2: Rebase onto latest upstream
v3: Fix up the commit message
v4: Split the scaler and joiner changes into separate patches (Jani)
Bspec: 74286
--- drivers/gpu/drm/i915/display/intel_display_device.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/gpu/drm/i915/display/intel_display_device.c +4 -1
@@ -1813,7 +1813,10 @@ static void __intel_display_device_info_runtime_init(struct intel_display *displif (intel_display_wa (display,INTEL_DISPLAY_WA_14011765242 ))for_each_pipe (display, pipe) display_runtime->num_scalers[pipe] =0 ; -else if (DISPLAY_VER (display) >=11 ) { +else if (DISPLAY_VERx100 (display) ==3002 ) { +for_each_pipe (display, pipe) + display_runtime->num_scalers[pipe] =1 ; + }else if (DISPLAY_VER (display) >=11 ) {for_each_pipe (display, pipe) display_runtime->num_scalers[pipe] =2 ; }else if (DISPLAY_VER (display) >=9 ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 127/507 drm/i915/display: Disable pipe joiner on WCL
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vidya Srinivas <[email protected]>
[ Upstream commit b42b656db1384255044754cd2163d370d766b776 ]
Pipe joining is not supported in the WCL display configuration. Report no joiner support on WCL so that modes which would require joining are rejected, matching the 4k 60Hz maximum resolution documented for the platform.
v2: Rebase onto latest upstream
v3: Fix up the commit message
v4: Split the scaler and joiner changes into separate patches (Jani)
Bspec: 74286
--- drivers/gpu/drm/i915/display/intel_dp.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/gpu/drm/i915/display/intel_dp.c +2 -2
@@ -475,9 +475,9 @@ bool intel_dp_has_joiner(struct intel_dp *intel_dp) !connector->panel.vbt.edp.pipe_joiner_enable)return false; -return DISPLAY_VER (display) >=12 || +return ((DISPLAY_VER (display) >=12 &&DISPLAY_VERx100 (display) !=3002 ) || (DISPLAY_VER (display) ==11 && - encoder->port !=PORT_A ); + encoder->port !=PORT_A )); }static int dg2_max_source_rate (struct intel_dp *intel_dp)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 128/507 drm/i915/display: Allow port sync on PTL
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mitul Golani <[email protected]>
[ Upstream commit 285300ef89aacbe902ba29c91625975f51345217 ]
Some dual-SST tiled displays exhibit visual corruption on PTL, with one tile's image vertically shifted or wrapped by a random amount that changes on every hotplug.
PTL supports port sync, so allow it to be used to avoid these display issues.
--- drivers/gpu/drm/i915/display/intel_ddi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/i915/display/intel_ddi.c +1 -1
@@ -4594,7 +4594,7 @@ intel_ddi_port_sync_transcoders(const struct intel_crtc_state *ref_crtc_state,* From, xe3lpd onwards we have defeatured this with reference to * Wa_16024710867 */ -if (!IS_DISPLAY_VER (display,9 ,20 )) +if (!IS_DISPLAY_VER (display,9 ,30 ))return 0 ;if (!intel_crtc_has_type (ref_crtc_state,INTEL_OUTPUT_DP ))
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 129/507 net: atl1c: drop oversized RX frames instead of panicking
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Federico Musto <[email protected]>
[ Upstream commit c4ba1716853de5178a9df785844ebb5e397a80e6 ]
atl1c sizes its receive buffers from the netdev MTU plus a fixed set of L2 overheads, which comes to 1522 bytes at the default MTU. A link partner that sends a longer frame - in practice a MikroTik CCR2004-1G-2XS-PCIe, whose RouterOS side defaults to l2mtu 1600 while the host stays at MTU 1500
- makes the length reported by the RX return descriptor exceed what the hardware wrote, and skb_put() then either includes bytes that were never received or trips skb_over_panic and takes the host down.
Compare the descriptor length against buffer_info->length, the length the hardware was given, rather than against skb_tailroom(): the skb carries 64 bytes of slack for the DMA erratum, so tailroom is larger than the DMA buffer and a frame in between would pass the check and still be delivered with a tail the device never wrote. The same test rejects frames shorter than ETH_HLEN + ETH_FCS_LEN; before this change a reported length below ETH_FCS_LEN underflowed in skb_put().
The frame is dropped with kfree_skb_reason(SKB_DROP_REASON_PKT_TOO_BIG) so drop_monitor and the kfree_skb tracepoint see it, and counted through dev_core_stats_rx_dropped_inc(), which survives atl1c_get_stats() overwriting the hardware counters on every read. It also counts as work:atl1c_clean_rfd() has already recycled the RFD, and the refill at the end of the poll only runs when work_done is non-zero, so sustained oversized traffic would otherwise drain the ring and stop RX.
Tested on a MikroTik CCR2004-1G-2XS-PCIe (4x AR8151) in a Proxmox VE host, with atl1c built from a DKMS tree carrying this change: the l2mtu-1600 traffic that panics the stock driver is dropped and counted with the patch applied, and received normally once the host MTU is raised to match.
This complements commit 36c2009d90f2 ("net: atl1c: fix soft lockup on out-of-range tpd_cons read"), which fixed the TX side of the same "host dies while the card resets" problem.
--- .../net/ethernet/atheros/atl1c/atl1c_main.c | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+)
drivers/net/ethernet/atheros/atl1c/atl1c_main.c +33 -0
@@ -1934,6 +1934,39 @@ static int atl1c_clean_rx(struct napi_struct *napi, int budget)break ; }atl1c_clean_rfd (rfd_ring, rrs, rfd_num); + +/* A link partner whose l2mtu is larger than ours can hand us a +* frame that does not fit the buffer the hardware was given: +* the descriptor reports the untruncated length while at most +* buffer_info->length bytes were written. skb_put() of such a +* length would pull in whatever the tail of the buffer holds +* and, past the end of the skb, trips skb_over_panic and takes +* the host down. Bound it by what the device actually wrote +* rather than by skb_tailroom(): the skb carries 64 bytes of +* slack for the DMA erratum, so the two are not the same. +* +* Frames shorter than an Ethernet header plus its FCS are +* rejected by the same test; before this, a length below +* ETH_FCS_LEN underflowed in skb_put(). +*/ +if (unlikely (length <ETH_HLEN +ETH_FCS_LEN || + length > buffer_info->length)) { +dev_core_stats_rx_dropped_inc (netdev); +if (netif_msg_rx_err (adapter)) +dev_warn_ratelimited (&pdev->dev, +"dropped rx frame: %u bytes, buffer %u\n" , + length, buffer_info->length); +kfree_skb_reason (skb,SKB_DROP_REASON_PKT_TOO_BIG ); +/* atl1c_clean_rfd() has already recycled the RFD, so +* count the drop as work: the refill at the end of the +* poll only runs when work_done is non-zero, and +* sustained oversized traffic would otherwise drain the +* ring and stop RX for good. +*/ + work_done++; +continue ; + } +skb_put (skb, length -ETH_FCS_LEN ); skb->protocol =eth_type_trans (skb, netdev);atl1c_rx_checksum (adapter, skb, rrs);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 130/507 ksmbd: do not read past the DACL in the access denied debug message
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ian Bridges <[email protected]>
[ Upstream commit 8296a64df5448548f410fb246c1d88a93609602b ]
When smb_check_perm_dacl() falls back to the POSIX ACL and then denies the request, its debug message prints the access mask of the ACE that the second DACL walk stopped at. On that path the walk ran to the end of the DACL, so the pointer is one past the last ACE. If the DACL is the last part of the stored security descriptor, the message reads 4 bytes past the buffer, and KASAN reports a slab-out-of-bounds read in smb_check_perm_dacl().
Print the requested and allowed masks instead. They are what the check compares.
--- fs/smb/server/smbacl.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/smb/server/smbacl.c +2 -2
@@ -1665,8 +1665,8 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, }if (granted & ~access_bits) { -ksmbd_debug (SMB ,"Access denied with winACL, granted : %x, access_req : %x\n" , - granted,le32_to_cpu (ace->access_req)); +ksmbd_debug (SMB ,"Access denied with winACL, requested : %x, allowed : %x\n" , + granted, access_bits); rc = -EACCES ; goto err_out; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 131/507 ksmbd: grant a POSIX ACL group entry only to the groups members
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ian Bridges <[email protected]>
[ Upstream commit c00ec7ad449b68c291a4986e481941302ed399c5 ]
When no ACE of the DACL matches the caller, Everyone or Authenticated Users, smb_check_perm_dacl() falls back to the file's POSIX ACL. It takes the first ACL_USER or ACL_GROUP entry whose id equals the caller's uid. For ACL_GROUP, this compares a gid with the caller's uid. A numerical match grants the group's permissions even when the caller is not a member.
Match a group entry only when the caller is also in the group.
--- fs/smb/server/smbacl.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/smb/server/smbacl.c +4 -1
@@ -1618,7 +1618,10 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,else continue ; -if (id == uid) { +/* A group entry grants only to the group's members */ +if (id == uid && + (pa_entry->e_tag ==ACL_USER || +in_group_p (make_kgid (&init_user_ns, id)))) {mode_to_access_flags (pa_entry->e_perm,0777 , &access_bits);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 132/507 ksmbd: let the owner read and change the DACL when no ACE names it
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ian Bridges <[email protected]>
[ Upstream commit ffc855fe16afe02b22305111aa68cd8d07360941 ]
smb_check_perm_dacl() refuses the owner when neither its DACL lookup nor the POSIX ACL fallback matches. The owner then cannot read or replace the DACL over SMB. MS-DTYP 2.5.3.2 grants the owner READ_CONTROL and WRITE_DAC unless an OWNER RIGHTS ACE applies.
An empty DACL allows the owner's explicit requests for these rights but refuses MAXIMUM_ALLOWED. smb2_open() uses that check for the maximal access reply (MS-SMB2 3.3.5.9.5), so even a READ_CONTROL open fails when it asks for that reply.
Grant the owner's implicit rights on both paths, for explicit requests and MAXIMUM_ALLOWED, unless an OWNER RIGHTS ACE applies.
--- fs/smb/server/smbacl.c | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-)
fs/smb/server/smbacl.c +30 -4
@@ -1470,6 +1470,7 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,int i, found =0 ;unsigned int access_bits =0 , denied =0 ;struct smb_ace *others_ace =NULL ; +bool or_ace = false;struct posix_acl_entry *pa_entry;unsigned int sid_type =SIDOWNER ;unsigned short ace_size;
@@ -1502,6 +1503,8 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, is_owner = uid ==from_kuid (&init_user_ns,vfsuid_into_kuid (vfsuid));if (!pdacl->num_aces) { +unsigned int allowed =0 ; +/* * An empty (present, zero-ACE) DACL grants no access to * anyone except the object owner's implicit READ_CONTROL
@@ -1510,9 +1513,14 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,* not let trailing bytes after a zero-ACE DACL become an * implicit grant. */ -if (!is_owner || - (*pdaccess & ~(FILE_READ_CONTROL_LE |FILE_WRITE_DAC_LE ))) +if (is_owner) + allowed =READ_CONTROL |WRITE_DAC ; +if (*pdaccess &FILE_MAXIMAL_ACCESS_LE ) + requested |= allowed; +if (!allowed || requested & ~allowed) rc = -EACCES ; +else + *pdaccess =cpu_to_le32 (requested); goto err_out; }
@@ -1597,6 +1605,9 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, found =1 ;break ; } +if (!compare_sids (&sid_owner_rights, &ace->sid) && + !(ace->flags &INHERIT_ONLY_ACE )) + or_ace = true;if (!compare_sids (&sid_everyone, &ace->sid) || !compare_sids (&sid_authusers, &ace->sid)) others_ace = ace;
@@ -1641,8 +1652,23 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,if (others_ace) { ace = others_ace; }else { -ksmbd_debug (SMB ,"Can't find corresponding sid\n" ); - rc = -EACCES ; +unsigned int allowed =0 ; + +/* +* No ACE names the owner, who may still read and +* change the DACL unless OWNER RIGHTS applies +* (MS-DTYP 2.5.3.2). +*/ +if (is_owner && !or_ace) + allowed =READ_CONTROL |WRITE_DAC ; +if (*pdaccess &FILE_MAXIMAL_ACCESS_LE ) + requested |= allowed; +if (!allowed || requested & ~allowed) { +ksmbd_debug (SMB ,"Can't find corresponding sid\n" ); + rc = -EACCES ; + goto err_out; + } + *pdaccess =cpu_to_le32 (requested); goto err_out; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 133/507 mm/mempolicy: charge shared policy nodes
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit 68b2aa37afa390f08de13bc0bac61a9ded3318bc ]
Any local user can bypass memory.max with mbind() on a tmpfs file, and allocate unbounded kernel memory.
mbind() sets a NUMA memory policy for a range of a mapping. If the mapping is of a shmem and friends, the kernel also stores the policy on the inode, in a tree with one entry per range of the file.
Each mbind() on a single page of a mapping can add one shared policy node (struct sp_node) and one struct mempolicy to that tree. They outlive the mapping and stay around until the inode is destroyed. The tree is not bounded by the file size, so the file can be empty.
Memory that user space can allocate must be charged to a memory cgroup. A slab cache does that for all of its objects if it is created with SLAB_ACCOUNT. numa_policy_init() creates the slab caches for both structs without SLAB_ACCOUNT, so they are not charged to any cgroup.
Reproduced with mbind() on single pages of an empty tmpfs file, from a cgroup with memory.max=8M: the global OOM killer killed tasks owned by root, and the machine panicked.
Fix this by creating both caches with SLAB_ACCOUNT. This change implies that mbind() can now fail when running into memcg limits. Further, the policy_cache also serves task and VMA policies, so they are similarly accounted now.
Note that per-file limits are not really helpful, as the user could simply use many files; having limits per user is tricky as well.
Fix generated by an LLM and submitted by Chris Mason in private.
--- mm/mempolicy.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
mm/mempolicy.c +2 -2
@@ -3346,11 +3346,11 @@ void __init numa_policy_init(void) policy_cache =kmem_cache_create ("numa_policy" ,sizeof (struct mempolicy ), -0 ,SLAB_PANIC ,NULL ); +0 ,SLAB_PANIC |SLAB_ACCOUNT ,NULL ); sn_cache =kmem_cache_create ("shared_policy_node" ,sizeof (struct sp_node ), -0 ,SLAB_PANIC ,NULL ); +0 ,SLAB_PANIC |SLAB_ACCOUNT ,NULL );for_each_node (nid) { preferred_node_policy[nid] = (struct mempolicy ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 134/507 tmpfs: keep the quota soft limits of an unused id
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
[ Upstream commit 968d73463059156e1b89bfa6b189acd7d27197b2 ]
When the last reference to a dquot goes away, shmem_release_dquot() stores its limits in the rb tree of the mount, unless shmem_is_empty_dquot() says that there is nothing worth storing. That function looks at the usage and at the two hard limits only.
So if the administrator sets nothing but soft limits for an id that owns no file yet, the entry is thrown away as soon as the dquot that Q_SETQUOTA used is released, and the id never gets to see a limit.
To fix it, compare the soft limits as well: an entry can be empty only if both soft limits are zero as well, which is exactly what shmem_acquire_dquot() sets for a new entry.
Fix generated by an LLM and sent by Josef Bacik in private.
--- mm/shmem_quota.c | 2 ++ 1 file changed, 2 insertions(+)
mm/shmem_quota.c +2 -0
@@ -251,6 +251,8 @@ static bool shmem_is_empty_dquot(struct dquot *dquot)if (test_bit (DQ_FAKE_B , &dquot->dq_flags) || (dquot->dq_dqb.dqb_curspace ==0 && dquot->dq_dqb.dqb_curinodes ==0 && + dquot->dq_dqb.dqb_bsoftlimit ==0 && + dquot->dq_dqb.dqb_isoftlimit ==0 && dquot->dq_dqb.dqb_bhardlimit == bhardlimit && dquot->dq_dqb.dqb_ihardlimit == ihardlimit))return true;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 135/507 tmpfs: preserve explicitly disabled quota limits
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
[ Upstream commit d5d861ee303da01e59fdf8e8b2f7096c76e7efd5 ]
An administrator’s decision to disable a user’s or group’s quota limits can be silently lost when tmpfs restores the mount defaults after releasing and reacquiring the quota record. This can cause later file creation or writes to fail with EDQUOT, even though the administrator has explicitly disabled quota limits for the user or group.
do_set_dqblk() sets DQ_FAKE_B when all block and inode limits are zero. This means quota enforcement is disabled for that user or group. shmem_is_empty_dquot() treats the flag as a reason to discard the entry from the mount's quota tree. The next shmem_acquire_dquot() finds no saved entry and recreates it with the mount's default hard limits.
If the cached dquot is reused, DQ_FAKE_B remains set: Q_GETQUOTA reports the restored defaults, but enforcement is still disabled. Once that dquot has been reclaimed, a new dquot enforces the restored defaults.
Remove the DQ_FAKE_B test. Only discard entries with zero usage, zero soft limits and hard limits equal to the mount defaults. Explicitly disabled limits are then preserved whenever the mount defaults are nonzero.
Explicitly disabled limits now retain a quota-tree entry, just like other limits that differ from the mount defaults.
Rename shmem_is_empty_dquot() to shmem_is_default_dquot() to describe the check for default values.
Fix generated by an LLM and sent by Josef Bacik in private.
--- mm/shmem_quota.c | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-)
mm/shmem_quota.c +15 -15
@@ -234,7 +234,7 @@ static int shmem_acquire_dquot(struct dquot *dquot)return ret; } -static bool shmem_is_empty_dquot (struct dquot *dquot) +static bool shmem_is_default_dquot (struct dquot *dquot) {struct shmem_sb_info *sbinfo = dquot->dq_sb->s_fs_info;qsize_t bhardlimit;
@@ -248,21 +248,21 @@ static bool shmem_is_empty_dquot(struct dquot *dquot) ihardlimit = sbinfo->qlimits.grpquota_ihardlimit; } -if (test_bit (DQ_FAKE_B , &dquot->dq_flags) || - (dquot->dq_dqb.dqb_curspace ==0 && - dquot->dq_dqb.dqb_curinodes ==0 && - dquot->dq_dqb.dqb_bsoftlimit ==0 && - dquot->dq_dqb.dqb_isoftlimit ==0 && - dquot->dq_dqb.dqb_bhardlimit == bhardlimit && - dquot->dq_dqb.dqb_ihardlimit == ihardlimit)) -return true; - -return false; +/* +* Defaults are zero usage and soft limits, and the mount's hard limits. +* DQ_FAKE_B only means that *all* limits are zero, which need not match +* the mount defaults. +*/ +return dquot->dq_dqb.dqb_curspace ==0 && + dquot->dq_dqb.dqb_curinodes ==0 && + dquot->dq_dqb.dqb_bsoftlimit ==0 && + dquot->dq_dqb.dqb_isoftlimit ==0 && + dquot->dq_dqb.dqb_bhardlimit == bhardlimit && + dquot->dq_dqb.dqb_ihardlimit == ihardlimit; }/* -* Store limits from dquot in the tree unless it's fake. If it is fake -* remove the id from the tree since there is no useful information in -* there. +* Remove the ID from the tree if it has no usage and its limits match +* the mount defaults. Otherwise, save its limits for the next acquire. */ static int shmem_release_dquot (struct dquot *dquot) {
@@ -297,7 +297,7 @@ static int shmem_release_dquot(struct dquot *dquot)return -ENOENT ; found: -if (shmem_is_empty_dquot (dquot)) { +if (shmem_is_default_dquot (dquot)) {/* Remove entry from the tree */ rb_erase (&entry->node, info->dqi_priv);kfree (entry);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 136/507 mm/shmem: stop retrying folios that cannot be split
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit a842a1f947da8a7020e72f885ffbf2ce6a93685f ]
A fault or collapse can insert a large folio crossing EOF after shmem_undo_range() has handled the boundary folios. If splitting that folio fails, truncate_inode_partial_folio() retains it when it is dirty. The final scan then repeatedly finds it because it restarts from an unchanged start.
Truncation keeps the inode lock and ignores fatal signals while looping. A concurrent unlink() can then block other directory operations while holding the directory lock and waiting for the file's lock.
Advance start past the retained folio, whose truncated part has already been zeroed. Do not move start backwards if the failed split has shrunk the folio.
Fix generated by an LLM and sent by Chris Mason in private.
--- mm/shmem.c | 9 +++++++++ 1 file changed, 9 insertions(+)
mm/shmem.c +9 -0
@@ -1275,6 +1275,15 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend, index = start;break ; } + }else if (folio->mapping) { +/* +* Splitting failed, but the part in the +* range is already zeroed. The folio +* was not dropped, so skip it when +* restarting the scan to avoid retrying +* it forever. +*/ + start =max (start,folio_next_index (folio)); } }folio_unlock (folio);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 137/507 mm/shmem: preserve data in clean folios when splitting fails
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit 0c800435394a172f33bf4df4a5a04e187546cc9b ]
A shared writable mapping can have dirty PTEs while its shmem folio is still clean. A read fault can install a writable PTE, and a later store sets the PTE's dirty bit without marking the folio dirty.
After shmem_undo_range() has handled the boundary folios, a concurrent read fault into a hole below the new EOF can allocate a large folio. For example, on a tmpfs mount with huge=always, the fault's offset must be within the file, but the allocated folio can extend beyond i_size. The final scan then finds this folio and calls truncate_inode_partial_folio() without marking it dirty.
Splitting normally collects the PTE dirty bits when unmapping the folio. An extra reference, for example from vmsplice(), can make it fail before that step. The fallback unmapping on split failure excludes shmem, so the helper still sees a clean folio and drops it, losing data outside the range.
CPU0: ftruncate(fd, 3M) CPU1: MAP_SHARED, tmpfs huge=always
───────────────────────────────────── ────────────────────────────────── i_size = 3Mshmem_undo_range(3M, -1)
first pass: hole, nothing to do
boundary folio at 3M: hole, none
read fault at 2M+x (below EOF)
PMD folio [2M,4M), crosses EOF writable PTE, folio clean
store to 2M+x
PTE dirty, folio still clean
vmsplice(2M+x)
extra folio reference
whole_folios: finds [2M,4M) folio truncate_inode_partial_folio()
zero [3M,4M)
folio_split()
unmap_folio(): extra ref
→ -EAGAIN, PTE dirty bit
never reaches the folio
folio clean
→ truncate_inode_folio(whole)
[2M,3M) dropped
read 2M+x → refault → zeroes
Mark large folios dirty before partial truncation in the final scan, as the boundary handling already does. Exclude failed-fallocate rollback, which must discard the folios it added.
Fix generated by an LLM and sent by Chris Mason in private.
--- mm/shmem.c | 9 +++++++++ 1 file changed, 9 insertions(+)
mm/shmem.c +9 -0
@@ -1259,6 +1259,15 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,VM_BUG_ON_FOLIO (folio_test_writeback (folio), folio); +/* +* A shared mapping can have dirty PTEs while +* the folio is still clean. Mark the folio +* dirty so a failed split cannot discard data +* outside the range. +*/ +if (!unfalloc &&folio_test_large (folio)) +folio_mark_dirty (folio); +if (!folio_test_large (folio)) {truncate_inode_folio (mapping, folio); }else if (truncate_inode_partial_folio (folio, lstart, lend)) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 138/507 mm/shmem: discard whole new large folios on fallocate rollback
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit 23f2a880c0b9518fcb7e7e2ad54a29c0a2c4fba0 ]
When undoing a failed fallocate(), shmem_undo_range() must discard each newly allocated folio. Its second scan instead passes large folios to truncate_inode_partial_folio(), which does not necessarily discard the entire large folio, but instead tries splitting it to discard only the requested range.
For example, with huge=always, a failed allocation starting at offset 4 KiB can leave page 0 allocated in an otherwise empty file.
Discard the whole folio when unfalloc is set. Note that we enter this path only for folios that are not uptodate, and can consequently be dropped without losing any data.
--- mm/shmem.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/shmem.c +1 -1
@@ -1268,7 +1268,7 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,if (!unfalloc &&folio_test_large (folio))folio_mark_dirty (folio); -if (!folio_test_large (folio)) { +if (unfalloc || !folio_test_large (folio)) {truncate_inode_folio (mapping, folio); }else if (truncate_inode_partial_folio (folio, lstart, lend)) {/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 139/507 mm/shmem: rescan after nonuniform folio splitting
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit f0d67b3d0a464847337d5063766d55e16041323e ]
The final scan in shmem_undo_range() restarts after a successful split only if the original folio is no longer large. A nonuniform split can leave that folio large, so the scan skips the newly created folios. Hole punching then leaves pages within the hole allocated even though they could be discarded.
For example, a fault below the hole can allocate a 2 MiB folio after boundary handling. Punching a 1 MiB hole at offset 64 KiB splits the folio successfully but leaves the original folio at order 4. The scan continues past all 512 pages, leaving 2 MiB allocated instead of 1 MiB. The hole reads as zero, but the pages and their block charges remain.
--- mm/shmem.c | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-)
mm/shmem.c +5 -11
@@ -1272,18 +1272,12 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,truncate_inode_folio (mapping, folio); }else if (truncate_inode_partial_folio (folio, lstart, lend)) {/* -* If we split a page, reset the loop so -* that we pick up the new sub pages. -* Otherwise the THP was entirely -* dropped or the target range was -* zeroed, so just continue the loop as -* is. +* The folio was split. Retry the scan +* to find the split folios. */ -if (!folio_test_large (folio)) { -folio_unlock (folio); - index = start; -break ; - } +folio_unlock (folio); + index = start; +break ; }else if (folio->mapping) {/* * Splitting failed, but the part in the
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 140/507 mm/shmem: fix truncate hang in large swap entry
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit fa213b08f37f9dff78ce240a87579dc264fc7a5d ]
Truncating a tmpfs file or memfd to a page-aligned size inside a large swap entry can loop indefinitely in shmem_undo_range(). The task holds the inode lock and cannot be killed.
A large swap entry represents a whole swapped-out folio. For example, truncate a file whose pages 0-7 share one swap entry to four pages:
[ 0 1 2 3 | 4 5 6 7 ]
keep | discard
^
new EOF, start = 4
i_size has already been updated when boundary handling asks shmem_get_partial_folio() for page 4. Since it is swapped out, the helper calls shmem_get_folio() with SGP_READ. That rejects page 4 with -EINVAL because its starting offset equals i_size. Nothing is read back.
The final scan cannot free the entry without losing pages 0-3. It skips it, restarts from start = 4, and finds it again indefinitely. An unaligned truncate avoids this particular failure because the requested page starts below i_size. Folios already in the page-cache cannot trigger it as the direct lookup will return them beyond EOF.
Fix it by letting shmem_get_partial_folio() call shmem_swapin_folio() directly for swap entries. This bypasses the read path's i_size check, allowing the existing boundary handling to zero and split the folio. If swap-in returns a smaller folio, it also splits the swap entry so the final scan can free the entries beyond EOF. Retry the lookup if the entry changes during swap-in.
Handling swap-in allocation failures remains broken and is unchanged by this commit. Even when shmem_swapin_folio() correctly returns -ENOMEM instead of -EEXIST, shmem_get_partial_folio() returns NULL and shmem_undo_range() skips boundary handling. If the large swap entry remains intact, truncation can still loop in the final scan, while hole punching can return without zeroing the boundary.
This may read an entire large folio back from swap while holding i_rwsem, only to discard part of it. Avoiding that I/O would require splitting both the swap entry and any large folio still in the swap cache. That, however, is much bigger work.
--- mm/shmem.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-)
mm/shmem.c +7 -8
@@ -1089,12 +1089,10 @@ void shmem_unlock_mapping(struct address_space *mapping)static struct folio *shmem_get_partial_folio (struct inode *inode,pgoff_t index) { +const gfp_t gfp =mapping_gfp_mask (inode->i_mapping);struct folio *folio; -/* -* At first avoid shmem_get_folio(,,,SGP_READ): that fails -* beyond i_size, and reports fallocated folios as holes. -*/ +retry: folio =filemap_get_entry (inode->i_mapping, index);if (!folio)return folio;
@@ -1105,13 +1103,14 @@ static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index)/* The folio has been swapped out */ folio_unlock (folio);folio_put (folio); + goto retry; }/* -* But read a folio back from swap if any of it is within i_size -* (although in some cases this is just a waste of time). +* Truncation can look up a large swap entry at or beyond i_size. +* Swap it in directly to bypass the size check in shmem_get_folio(). */ - folio =NULL ; -shmem_get_folio (inode, index,0 , &folio,SGP_READ ); +if (shmem_swapin_folio (inode, index, &folio,SGP_READ , gfp,NULL ,NULL ) == -EEXIST ) + goto retry;return folio; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 141/507 mm/shmem: preserve allocation errors when swapping in large entries
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit f4ce23b1feef16d435aa1188b6c2a637a5373ed5 ]
shmem_swapin_folio() adjusts swap to the requested slot within a large swap entry before allocating a folio. If allocation or charging fails, the error path compares this adjusted value with the original entry still stored in the XArray in shmem_confirm_swap().
Unless the index is at the start of the entry, this turns -ENOMEM into -EEXIST even though nothing changed.
The caller retries -EEXIST, so persistent allocation failures can leave the task spinning instead of returning the error.
Restore swap to index_entry on allocation failure so the existing error path checks the original entry. This preserves the allocation error if the entry is unchanged and still retries if it changed concurrently.
--- mm/shmem.c | 2 ++ 1 file changed, 2 insertions(+)
mm/shmem.c +2 -0
@@ -2327,6 +2327,8 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,else error = -ENOMEM ; folio =NULL ; +/* Make sure to validate the original value. */ + swap = index_entry; goto failed; }if (fault_type) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 142/507 mm/shmem: fix truncate loop after boundary swapin failure
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit 5f1ec2cf92a7d655a8eb39711987822f9b1f9d67 ]
If swapping in a large entry at the new EOF fails, shmem_undo_range() leaves the entry in place. Its final scan skips the entry, then restarts from the same start index and finds it again. Truncation can loop forever while holding i_rwsem.
Advance start past the skipped entry so that a restarted scan can finish, as we already do for folios that cannot be split.
Note that this does not fix the missing zeroing when boundary swapin fails, it merely prevents the endless loop.
--- mm/shmem.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-)
mm/shmem.c +6 -4
@@ -1229,14 +1229,16 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend, order =shmem_confirm_swap (mapping, indices[i],radix_to_swp_entry (folio));/* -* If found a large swap entry cross the end or start -* border, skip it as the truncate_inode_partial_folio -* above should have at least zerod its content once. +* Skip boundary entries when restarting +* the scan to avoid endless loops after +* swapin failure. */ if (order >0 ) { base =round_down (base,1 << order); -if (base < start || base + (1 << order) > end) +if (base < start || base + (1 << order) > end) { + start =max (start, base + (1 << order));continue ; + } }/* Swap was replaced by page or extended, retry */ index = base;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 143/507 mm/shmem: fix accounting of swapin-error markers
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit 66ce68a249f4ac56cd6968aa6d8ded20fb4b7d09 ]
A failed swap read replaces the swap entry with a swapin-error marker in the page-cache and subtracts its pages from "alloced" and "swapped"; however, it leaves their block charge in place.
Removing the marker during truncate then subtracts from "swapped" again. This can underflow the counters or make swapped reach zero while other pages remain swapped out, causing swapoff to loop without finding them.
When installing the marker, subtract only from "swapped" and let shmem_recalc_inode() reduce "alloced" and release the block charge.
Make shmem_free_swap() report successful removal separately from the number of swap pages freed, so removing a swapin-error marker does not subtract from "swapped" again.
It's a bit confusing, but replacing a swapped out page by a swapin-error marker in shmem_set_folio_swapin_error() behaves as follows:
Initially:
alloced=1, swapped=1, nrpages=0 Calling shmem_recalc_inode(inode, 0, -1) -> swapped = 0 -> freed = 1 - 0 - 0 = 1 -> alloced -= freed -> alloced=0, swapped=0, block charge released
--- mm/shmem.c | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-)
mm/shmem.c +14 -17
@@ -968,12 +968,11 @@ static void shmem_delete_from_page_cache(struct folio *folio, void *radswap) }/* -* Remove swap entry from page cache, free the swap and its page cache. Returns -* the number of pages being freed. 0 means entry not found in XArray (0 pages -* being freed). +* Remove a swap entry or swapin-error marker wholly within [index, end]. +* Return whether it was removed, counting freed swap pages in nr_swaps_freed. */ -static long shmem_free_swap (struct address_space *mapping, -pgoff_t index,pgoff_t end,void *radswap) +static bool shmem_free_swap (struct address_space *mapping, +pgoff_t index,pgoff_t end,void *radswap,long *nr_swaps_freed) {XA_STATE (xas, &mapping->i_pages, index);const softleaf_t swp =radix_to_swp_entry (radswap);
@@ -994,8 +993,10 @@ static long shmem_free_swap(struct address_space *mapping,xas_unlock_irq (&xas);/* A swapin-error marker holds no swap slot, so just drop it. */ -if (nr_pages &&softleaf_is_swap (swp)) +if (nr_pages &&softleaf_is_swap (swp)) {swap_put_entries_direct (swp, nr_pages); + *nr_swaps_freed += nr_pages; + }return nr_pages; }
@@ -1149,8 +1150,8 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,if (xa_is_value (folio)) {if (unfalloc)continue ; - nr_swaps_freed +=shmem_free_swap (mapping, indices[i], - end -1 , folio); +shmem_free_swap (mapping, indices[i], end -1 , + folio, &nr_swaps_freed);continue ; }
@@ -1217,13 +1218,11 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,if (xa_is_value (folio)) {int order; -long swaps_freed;if (unfalloc)continue ; - swaps_freed =shmem_free_swap (mapping, indices[i], - end -1 , folio); -if (!swaps_freed) { +if (!shmem_free_swap (mapping, indices[i], end -1 , + folio, &nr_swaps_freed)) {pgoff_t base = indices[i]; order = shmem_confirm_swap(mapping, indices[i],
@@ -1244,7 +1243,6 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend, index = base;break ; } - nr_swaps_freed += swaps_freed;continue ; }
@@ -2184,11 +2182,10 @@ static void shmem_set_folio_swapin_error(struct inode *inode, pgoff_t index,folio_put_swap (folio,NULL );swap_cache_del_folio (folio);/* -* Don't treat swapin error folio as alloced. Otherwise inode->i_blocks -* won't be 0 when inode is released and thus trigger WARN_ON(i_blocks) -* in shmem_evict_inode(). +* Let shmem_recalc_inode() reduce alloced and release the block charge +* for the freed swap pages. */ -shmem_recalc_inode (inode, -nr_pages, -nr_pages); +shmem_recalc_inode (inode,0 , -nr_pages); } static int shmem_split_large_entry(struct inode *inode, pgoff_t index,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 144/507 mm/shmem: fix truncation of files containing only swapin-error markers
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit 59511d630a6942356ac4b6984797998a8f3a9017 ]
It might not be very common, but we can end up with shmem files that are composed only of swapin-error/poison markers.
Such markers are not counted in info->alloced. Consequently, shmem_setattr() can skip shmem_truncate_range(), leaving the markers behind.
Truncating the file to zero and growing it again will result in reads failing with -EIO instead of returning zeroes.
Check whether the mapping contains entries, in addition to info->alloced, before skipping the truncation. Keep the info->alloced check so that shmem_recalc_inode(), called at the end of shmem_undo_range(), can fix up accounting after reclaim has emptied the mapping.
--- mm/shmem.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
mm/shmem.c +2 -1
@@ -1384,7 +1384,8 @@ static int shmem_setattr(struct mnt_idmap *idmap,if (oldsize > holebegin)unmap_mapping_range (inode->i_mapping, holebegin,0 ,1 ); -if (info->alloced) +/* Swapin-error markers are not counted in alloced. */ +if (info->alloced || !mapping_empty (inode->i_mapping))shmem_truncate_range (inode, newsize, (loff_t)-1 );/* unmap again to remove racily COWed private pages */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 145/507 mm/mglru: dont use stack pointers when walking PUD and PMD tables
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
[ Upstream commit 65a9bf08a3e4d6e58df211ed900c16bafb79b267 ]
MGLRU passes stack copies of page-table entries in walk_pud_range() and walk_pmd_range() when walking to the next level. These copies can become stale when khugepaged or MADV_DONTNEED (CONFIG_PT_RECLAIM) removes a PTE table concurrently.
This pattern dates back to commit bd74fdaea146 ("mm: multi-gen LRU:
support page table walks"). Likely, earlier locking masked the latent bug. Later changes exposed it: commit 1d65b771bc08 ("mm/khugepaged:retract_page_tables() without mmap or vma lock") allowed concurrent retraction, and commit cf4a65539c13 ("memcg-v1: no need for memcg locking for MGLRU") dropped the walker's outer RCU protection.
The fix is simple, so just fix the original commit so we don't have to speculate. To fix it, pass the actual PMD/PUD pointers. This restores the RCU-protected lookup and validation against the live PMD. Note that the PUD handling is required as well to handle folded page tables correctly in all cases.
Fix generated by an LLM and sent by Josef Bacik in private.
[ david: handle walk_pud_range() as well, clarify+simplify description,
adjust Fixes: ]
--- mm/vmscan.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
mm/vmscan.c +2 -2
@@ -3771,7 +3771,7 @@ static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end, walk->mm_stats[MM_NONLEAF_FOUND ]++; -if (!walk_pte_range (&val, addr, next, args)) +if (!walk_pte_range (pmd + i, addr, next, args))continue ; walk->mm_stats[MM_NONLEAF_ADDED ]++;
@@ -3807,7 +3807,7 @@ static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,if (!pud_present (val) ||WARN_ON_ONCE (pud_leaf (val)))continue ; -walk_pmd_range (&val, addr, next, args); +walk_pmd_range (pud + i, addr, next, args);if (need_resched () || walk->batched >=MAX_LRU_BATCH ) { end = (addr | ~PUD_MASK ) +1 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 146/507 fork: take mmap_lock before copying mm_struct
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit ef694e2d210111cc08c52fd25da9ab130170bfa3 ]
dup_mm() copies the parent's mm_struct before dup_mmap() takes the mmap_lock. A concurrent brk() can leave the child with a stale mm->brk and newer heap mappings, causing later brk() requests to fail.
Other operations (e.g., PR_SET_MM) on the parent's mm_struct can similarly cause inconsistencies.
As a simple and robust fix, grab the parent's mmap_lock earlier. This way we don't need to update individual mm fields in dup_mmap() and keep missing ones. Stop updating the 4 existing members (total_vm, data_vm, exec_vm, stack_vm), as that is now no longer required.
Keep releasing the parent's mmap_lock in dup_mmap(), before userfaultfd completion, to avoid moving the userfaultfd handling into the caller. This should get cleaned up later.
Move uprobe_start_dup_mmap() to preserve the lock ordering.
--- kernel/fork.c | 20 ++++++++++++++------ mm/mmap.c | 8 +------- mm/nommu.c | 2 +- 3 files changed, 16 insertions(+), 14 deletions(-)
kernel/fork.c +14 -6
@@ -1535,12 +1535,19 @@ static struct mm_struct *dup_mm(struct task_struct *tsk,if (!mm) goto fail_nomem; +uprobe_start_dup_mmap (); +if (mmap_write_lock_killable (oldmm)) { +free_mm (mm); + goto fail_uprobe; + } +memcpy (mm, oldmm,sizeof (*mm)); -if (!mm_init (mm, tsk)) - goto fail_nomem; +if (!mm_init (mm, tsk)) { +mmap_write_unlock (oldmm); + goto fail_uprobe; + } -uprobe_start_dup_mmap (); err =dup_mmap (mm, oldmm);if (err) goto free_pt;
@@ -1559,9 +1566,10 @@ static struct mm_struct *dup_mm(struct task_struct *tsk, mm->binfmt =NULL ;mm_init_owner (mm,NULL );mmput (mm); -if (err) -uprobe_end_dup_mmap (); - +if (!err) +return NULL ; +fail_uprobe: +uprobe_end_dup_mmap (); fail_nomem:return NULL ; }
mm/mmap.c +1 -7
@@ -1713,8 +1713,7 @@ __latent_entropy int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)LIST_HEAD (uf);VMA_ITERATOR (vmi, mm,0 ); -if (mmap_write_lock_killable (oldmm)) -return -EINTR ; +mmap_assert_write_locked (oldmm);flush_cache_dup_mm (oldmm);uprobe_dup_mmap (oldmm, mm);/*
@@ -1725,11 +1724,6 @@ __latent_entropy int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)/* No ordering required: file already has been exposed. */ dup_mm_exe_file (mm, oldmm); - mm->total_vm = oldmm->total_vm; - mm->data_vm = oldmm->data_vm; - mm->exec_vm = oldmm->exec_vm; - mm->stack_vm = oldmm->stack_vm; -/* Use __mt_dup() to efficiently build an identical maple tree. */ retval =__mt_dup (&oldmm->mm_mt, &mm->mm_mt,GFP_KERNEL );if (unlikely (retval))
mm/nommu.c +1 -1
@@ -1926,7 +1926,7 @@ subsys_initcall(init_admin_reserve);int dup_mmap (struct mm_struct *mm,struct mm_struct *oldmm) { -mmap_write_lock (oldmm); +mmap_assert_write_locked (oldmm);dup_mm_exe_file (mm, oldmm);mmap_write_unlock (oldmm);return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 147/507 mm/shmem: make shmem_file() check the files inode
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit d3710111839d11339e414b1bb3fea3d05ab83f6e ]
shmem_file() only checks if file->f_mapping is a shmem mapping. This mapping can belong to another file, however, as with a Coda file backed by a tmpfs container after mmap().
So it does not guarantee that the file inode is an actual shmem inode.
Seal handling and memfd preservation use this check before accessing shmem inode state, so they can access an inode of the wrong type.
Let's make shmem_file() check the inode's file operations instead, to identify shmem inodes reliably. This will identify regular shmem inodes, including memfds and ordinary tmpfs files, independently of wrapper file operations.
Use shmem_mapping() in collapse_file() instead to not change the behavior of collapse_file(): it operates on the page cache and uses mapping->host for shmem inode operations. Focusing on the file does not seem relevant.
--- include/linux/shmem_fs.h | 15 ++++++--------- mm/khugepaged.c | 2 +- mm/shmem.c | 5 +++++ 3 files changed, 12 insertions(+), 10 deletions(-)
include/linux/shmem_fs.h +6 -9
@@ -111,8 +111,14 @@ extern unsigned long shmem_get_unmapped_area(struct file *, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags);extern int shmem_lock (struct file *file,int lock,struct ucounts *ucounts);#ifdef CONFIG_SHMEM +bool shmem_file (struct file *file);bool shmem_mapping (const struct address_space *mapping);#else +static inline bool shmem_file (struct file *file) +{ +return false; +} +static inline bool shmem_mapping (const struct address_space *mapping) {return false;
@@ -187,15 +193,6 @@ static inline struct page *shmem_read_mapping_page( mapping_gfp_mask(mapping)); } -static inline bool shmem_file (struct file *file) -{ -if (!IS_ENABLED (CONFIG_SHMEM )) -return false; -if (!file || !file->f_mapping) -return false; -return shmem_mapping (file->f_mapping); -} -/* Must be called with inode lock taken exclusive. */ static inline void shmem_freeze (struct inode *inode,bool freeze) {
mm/khugepaged.c +1 -1
@@ -2251,6 +2251,7 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr, struct file *file, pgoff_t start, struct collapse_control *cc) { struct address_space *mapping = file->f_mapping; +const bool is_shmem =shmem_mapping (mapping);struct page *dst;struct folio *folio, *tmp, *new_folio;unsigned long new_pfn =-1 ;
@@ -2259,7 +2260,6 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,XA_STATE_ORDER (xas, &mapping->i_pages, start,HPAGE_PMD_ORDER );enum scan_result result =SCAN_SUCCEED ;int nr_none =0 ; -bool is_shmem =shmem_file (file);/* * MADV_COLLAPSE ignores shmem huge config, so do not check shmem
mm/shmem.c +5 -0
@@ -275,6 +275,11 @@ static const struct vm_operations_struct shmem_vm_ops;static const struct vm_operations_struct shmem_anon_vm_ops;static struct file_system_type shmem_fs_type; +bool shmem_file (struct file *file) +{ +return file &&file_inode (file)->i_fop == &shmem_file_operations; +} +bool shmem_mapping (const struct address_space *mapping) {return mapping->a_ops == &shmem_aops;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 148/507 mm/memfd: make f_pos accesses atomic
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
[ Upstream commit 5426cd43a4d28f1041c9ca45955121b921f29548 ]
Commit 9c225f2655e3 ("vfs: atomic f_pos accesses as per POSIX") made read(), write() and lseek() on a shared open file description of a regular file serialize on ->f_pos_lock. The flag that asks for it, FMODE_ATOMIC_POS, is set in do_dentry_open(). A memfd is a regular file too, but its struct file comes from alloc_file_pseudo() and never passes through do_dentry_open(), so it does not get the flag:
CPU0 CPU1
write(memfd, "a", 1) write(memfd, "b", 1)
pos = file->f_pos (= 0)
pos = file->f_pos (= 0)
vfs_write(..., &pos)
vfs_write(..., &pos)
file->f_pos = pos (= 1)
file->f_pos = pos (= 1)One of the two bytes is overwritten. Two threads writing 100000 bytes each, one at a time, to a memfd end up with a file that is far shorter than 200000 bytes, while the same program on a tmpfs file never loses a byte.
Set the flag when the memfd is created. As for any other regular file the lock is only taken if the file is reachable in more than one way, and nothing a memfd does in read or write waits for another operation on the same file. This cannot be done for all alloc_file_pseudo() files: anon inode files such as eventfd are S_IFREG as well, and a blocked read holding ->f_pos_lock would lock out the write that is supposed to wake it.
Fix generated by an LLM and sent by Josef Bacik in private.
--- mm/memfd.c | 2 ++ 1 file changed, 2 insertions(+)
mm/memfd.c +2 -0
@@ -482,6 +482,8 @@ struct file *memfd_alloc_file(const char *name, unsigned int flags) } file->f_mode |=FMODE_LSEEK |FMODE_PREAD |FMODE_PWRITE ; +/* a regular file like any other: POSIX.1-2008/SUSv4 Section XSI 2.9.7 */ + file->f_mode |=FMODE_ATOMIC_POS ; file->f_flags |=O_LARGEFILE ;if (flags &MFD_NOEXEC_SEAL ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 149/507 mm/truncate: look again if a folio left the mapping
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit 9cf632e139737314afa889ca18122bc3fddb9120 ]
invalidate_inode_pages2_range() skips a folio which no longer belongs to the mapping by the time it has got the folio lock, on the assumption that somebody else has removed it from the page cache. But the folio may have been replaced, and then there is a new folio with the same data at that index.
For most cases, like folio migration, that is impossible. However, collapse_file() only checks the refcount of the old folios, under the i_pages lock, and relies on their folio locks from there on. That works for users which repeat the lookup when they find folio->mapping changed. The following scenario is, however, possible:
CPU0 pwrite(O_DIRECT) CPU1 collapse_file()
kiocb_invalidate_pages()
read the folio (old data), lock it refcount check
the write completes copy to new_folio
kiocb_invalidate_post_direct_write()
find_get_entries() -> old folio
xas_store(new_folio)
folio->mapping = NULL
folio_unlock(folio)
folio_lock()
folio->mapping != mapping
-> continueIn that scenario, the collapsed folio with the data from before the write stays in the page cache after the write has returned.
This used to be impossible, as khugepaged only collapsed files that nobody had open for writing.
Restart the lookup at that index, like shmem_undo_range() does. The same problem seems to exist in truncate_inode_pages_range() as well when truncate_inode_folio() fails, so handle it there as well, but slightly
differently: simply check once more through find_get_entries().
--- mm/truncate.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-)
mm/truncate.c +11 -2
@@ -436,8 +436,11 @@ void truncate_inode_pages_range(struct address_space *mapping, } } +if (start >= end) +return ; + index = start; -while (index < end) { +while (true) {cond_resched ();if (!find_get_entries (mapping, &index, end -1 , &fbatch, indices)) {
@@ -460,6 +463,7 @@ void truncate_inode_pages_range(struct address_space *mapping,folio_lock (folio);VM_BUG_ON_FOLIO (!folio_contains (folio, indices[i]), folio);folio_wait_writeback (folio); +/* Do not handle errors, we'll do another lookup */ truncate_inode_folio (mapping, folio);folio_unlock (folio); }
@@ -721,7 +725,12 @@ int invalidate_inode_pages2_range(struct address_space *mapping,folio_lock (folio);if (unlikely (folio->mapping != mapping)) {folio_unlock (folio); -continue ; +/* +* Folio might have been replaced: look up +* again. +*/ + index = indices[i]; +break ; }VM_BUG_ON_FOLIO (!folio_contains (folio, indices[i]), folio);folio_wait_writeback (folio);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 150/507 mm/filemap: read mapping->a_ops->free_folio under i_lock
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
[ Upstream commit dc24e273244e9d712257d5a6c20a32c7f5ca84e6 ]
memory_failure() -> ... -> filemap_remove_folio() can read mapping->a_ops after the inode has been freed. Once the folio is deleted from the pagecache it no longer pins the mapping, so after i_lock is dropped e.g., a concurrent final iput() can evict and free the inode before filemap_free_folio() looks up mapping->a_ops->free_folio.
Most callers hold a reference on the inode, but not all.
Documentation/filesystems/vfs.rst explicitly states that ->free_folio() must not assume the original address_space mapping still exists.
Fix it by loading ->free_folio while i_lock is still held, similar to what folio_unmap_invalidate() does.
Inline filemap_free_folio() into its remaining caller such that delete_from_page_cache_batch() also just loads the callback before dropping the i_lock.
The bug was found by code inspection and has not been reproduced.
Fix generated by an LLM and sent by Josef Bacik in private.
--- mm/filemap.c | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-)
mm/filemap.c +14 -15
@@ -227,18 +227,6 @@ void __filemap_remove_folio(struct folio *folio, void *shadow)page_cache_delete (mapping, folio, shadow); } -static void filemap_free_folio (const struct address_space *mapping, -struct folio *folio) -{ -void (*free_folio)(struct folio *); - - free_folio = mapping->a_ops->free_folio; -if (free_folio) -free_folio (folio); - -folio_put_refs (folio,folio_nr_pages (folio)); -} -/** * filemap_remove_folio - Remove folio from page cache. * @folio: The folio.
@@ -250,6 +238,7 @@ static void filemap_free_folio(const struct address_space *mapping,void filemap_remove_folio (struct folio *folio) {struct address_space *mapping = folio->mapping; +void (*free_folio)(struct folio *folio);BUG_ON (!folio_test_locked (folio));spin_lock (&mapping->host->i_lock);
@@ -258,9 +247,12 @@ void filemap_remove_folio(struct folio *folio)xa_unlock_irq (&mapping->i_pages);if (mapping_shrinkable (mapping))inode_lru_list_add (mapping->host); + free_folio = mapping->a_ops->free_folio;spin_unlock (&mapping->host->i_lock); -filemap_free_folio (mapping, folio); +if (free_folio) +free_folio (folio); +folio_put_refs (folio,folio_nr_pages (folio)); }/*
@@ -320,6 +312,7 @@ static void page_cache_delete_batch(struct address_space *mapping,void delete_from_page_cache_batch (struct address_space *mapping,struct folio_batch *fbatch) { +void (*free_folio)(struct folio *folio);int i;if (!folio_batch_count (fbatch))
@@ -337,10 +330,16 @@ void delete_from_page_cache_batch(struct address_space *mapping,xa_unlock_irq (&mapping->i_pages);if (mapping_shrinkable (mapping))inode_lru_list_add (mapping->host); + free_folio = mapping->a_ops->free_folio;spin_unlock (&mapping->host->i_lock); -for (i =0 ; i <folio_batch_count (fbatch); i++) -filemap_free_folio (mapping, fbatch->folios[i]); +for (i =0 ; i <folio_batch_count (fbatch); i++) { +struct folio *folio = fbatch->folios[i]; + +if (free_folio) +free_folio (folio); +folio_put_refs (folio,folio_nr_pages (folio)); + } }int filemap_check_errors (struct address_space *mapping)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 151/507 mm/filemap: dont lose a folio lock wakeup to a signal
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
[ Upstream commit 8ccb6ded6a47b59b4907ed4f8c293cf8122de889 ]
An exclusive waiter in folio_wait_bit_common() can leave the wait loop because of a fatal signal, then be woken by folio_unlock() before finish_wait(). If the waker did not hand over the lock, the waiter returns -EINTR without trying to acquire it.
folio_wake_bit() stops after waking the first exclusive waiter, so this loses the wakeup and can leave other waiters asleep indefinitely on an unlocked folio.
After finish_wait(), let a waiter woken without a lock handoff try once more to acquire the lock. If successful, return success so the caller's eventual unlock wakes the next waiter. Otherwise, the current lock owner will do so.
Fix generated by an LLM and sent by Josef Bacik in private.
--- mm/filemap.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-)
mm/filemap.c +15 -3
@@ -1374,10 +1374,22 @@ static inline int folio_wait_bit_common(struct folio *folio, int bit_nr,* return value based on that state without races. * * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive -* waiter, but an exclusive one requires WQ_FLAG_DONE. +* waiter, but an exclusive one must also acquire the bit. */ -if (behavior ==EXCLUSIVE ) -return wait->flags &WQ_FLAG_DONE ?0 : -EINTR ; +if (behavior ==EXCLUSIVE ) { +if (wait->flags &WQ_FLAG_DONE ) +return 0 ; +/* +* We might have just been woken up and the waker will not +* wake up anybody else. If we ignore that now, the remaining +* waiters may not get woken up: take the bit now if it is +* still free. +*/ +if ((wait->flags &WQ_FLAG_WOKEN ) && + !test_and_set_bit (bit_nr,folio_flags (folio,0 ))) +return 0 ; +return -EINTR ; + }return wait->flags &WQ_FLAG_WOKEN ?0 : -EINTR ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 152/507 mm/filemap: finish fault cleanup before dropping the fault lock
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit 97156a6c355c21f7122421915f05461bd11699a4 ]
On a retried fault, a fatal signal interrupting the folio lock wait makes lock_folio_maybe_drop_mmap() drop the fault lock without pinning the file. However, filemap_fault() may still need to release mapping->invalidate_lock. A concurrent munmap() can release the last file reference and free the mapping before that unlock.
Defer dropping the fault lock to filemap_fault()'s retry cleanup, after releasing invalidate_lock. If the fault lock was already dropped for I/O, release the existing file reference instead. Keep the fault lock held for FAULT_FLAG_RETRY_NOWAIT as before.
--- mm/filemap.c | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-)
mm/filemap.c +13 -24
@@ -3290,11 +3290,11 @@ loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,* @folio - the folio to lock. * @fpin - the pointer to the file we may pin (or is already pinned). * -* This works similar to lock_folio_or_retry in that it can drop the -* mmap_lock. It differs in that it actually returns the folio locked -* if it returns 1 and 0 if it couldn't lock the folio. If we did have -* to drop the mmap_lock then fpin will point to the pinned file and -* needs to be fput()'ed at a later point. +* Returns 1 with the folio locked, or 0 if locking failed. +* +* On both entry and return, a non-NULL *fpin means the fault lock has +* already been dropped and the caller must eventually fput() the file. +* Otherwise the fault lock is still held, including on failure. */ static int lock_folio_maybe_drop_mmap (struct vm_fault *vmf,struct folio *folio,struct file **fpin)
@@ -3311,21 +3311,9 @@ static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,return 0 ; *fpin =maybe_unlock_mmap_for_io (vmf, *fpin); -if (vmf->flags &FAULT_FLAG_KILLABLE ) { -if (__folio_lock_killable (folio)) { -/* -* We didn't have the right flags to drop the -* fault lock, but all fault_handlers only check -* for fatal signals if we return VM_FAULT_RETRY, -* so we need to drop the fault lock here and -* return 0 if we don't have a fpin. -*/ -if (*fpin ==NULL ) -release_fault_lock (vmf); -return 0 ; - } - }else -__folio_lock (folio); +if (vmf->flags &FAULT_FLAG_KILLABLE ) +return !__folio_lock_killable (folio); +__folio_lock (folio);return 1 ; }
@@ -3554,7 +3542,7 @@ static vm_fault_t filemap_fault_recheck_pte_none(struct vm_fault *vmf)* vma->vm_mm->mmap_lock must be held on entry. * * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock -* may be dropped before doing I/O or by lock_folio_maybe_drop_mmap(). +* may be dropped before doing I/O or when aborting an interrupted wait. * * If our return value does not have VM_FAULT_RETRY set, the mmap_lock * has not been released.
@@ -3710,9 +3698,8 @@ vm_fault_t filemap_fault(struct vm_fault *vmf) out_retry:/* -* We dropped the mmap_lock, we need to return to the fault handler to -* re-find the vma and come back and find our hopefully still populated -* page. +* With fpin set, the fault lock was already dropped. Otherwise it is +* still held. Release invalidate_lock before dropping either protection. */ if (!IS_ERR (folio))folio_put (folio);
@@ -3720,6 +3707,8 @@ vm_fault_t filemap_fault(struct vm_fault *vmf)filemap_invalidate_unlock_shared (mapping);if (fpin)fput (fpin); +else if (!(vmf->flags &FAULT_FLAG_RETRY_NOWAIT )) +release_fault_lock (vmf);return ret |VM_FAULT_RETRY ; }EXPORT_SYMBOL (filemap_fault);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 153/507 mm/rmap: handle device-exclusive entries in folio_referenced_one()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit f3c493d2f42b5f44a5c134d8d7ea7f960caf5e2c ]
page_vma_mapped_walk() can return non-present device-exclusive entries, but folio_referenced_one() passes them to PTE young-bit accessors that require present PTEs.
We must neither call clear_flush_young_ptes_notify() nor folio_pte_batch() with non-present entries. For example, clearing the young bit on non-present PTEs can corrupt the entry: on arm64 PTE_AF overlaps the swap type, so clearing it turns a device-exclusive entry into an ordinary swap entry.
folio_pte_batch() will VM_WARN_ON_FOLIO.
Apply the same approach as the previous fixes to e.g., damon_ptep_mkold():
treat these entries as old from the CPU's perspective and obtain their young state through the MMU notifier.
Skip PTE batching and MGLRU look-around for non-present entries, and don't modify non-present PTEs.
--- mm/rmap.c | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-)
mm/rmap.c +19 -4
@@ -926,6 +926,7 @@ static bool folio_referenced_one(struct folio *folio,DEFINE_FOLIO_VMA_WALK (pvmw, folio, vma, address,0 );int ptes =0 , referenced =0 ;unsigned int nr; +pte_t pteval;while (page_vma_mapped_walk (&pvmw)) { address = pvmw.address;
@@ -970,10 +971,12 @@ static bool folio_referenced_one(struct folio *folio,return false; } -if (pvmw.pte &&folio_test_large (folio)) { +if (pvmw.pte) + pteval =ptep_get (pvmw.pte); + +if (pvmw.pte &&pte_present (pteval) &&folio_test_large (folio)) {const unsigned long end_addr =pmd_addr_end (address, vma->vm_end);const unsigned int max_nr = (end_addr - address) >>PAGE_SHIFT ; -pte_t pteval =ptep_get (pvmw.pte); nr =folio_pte_batch (folio, pvmw.pte, pteval, max_nr); }
@@ -983,11 +986,23 @@ static bool folio_referenced_one(struct folio *folio,* are. —they could be on active/inactive lists or on MGLRU. So the * simplest approach is to disable this look-around optimization. */ -if (lru_gen_enabled () && !lru_gen_switching () && pvmw.pte) { +if (lru_gen_enabled () && !lru_gen_switching () && pvmw.pte && +pte_present (pteval)) {if (lru_gen_look_around (&pvmw, nr)) referenced++; }else if (pvmw.pte) { -if (clear_flush_young_ptes_notify (vma, address, pvmw.pte, nr)) +bool young = false; + +/* +* PFN swap PTEs, such as device-exclusive ones, that +* actually map pages are "old" from a CPU perspective. +* The MMU notifier takes care of any device aspects. +*/ +if (pte_present (pteval)) + young =clear_flush_young_ptes (vma, address, pvmw.pte, nr); + young |=mmu_notifier_clear_flush_young (vma->vm_mm, address, + address + nr *PAGE_SIZE ); +if (young) referenced++; }else if (IS_ENABLED (CONFIG_TRANSPARENT_HUGEPAGE )) { if (pmdp_clear_flush_young_notify(vma, address,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 154/507 mm/huge_memory: fix list corruption when deferred_split_scan() races with deferred_split_folio()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit f09171b67ea06a7fe425db33e8b74a92de1426b9 ]
Since the deferred split queue became a list_lru, the isolate callback moves the folios it took a reference on to an on-stack list, linked through folio->_deferred_list, and deferred_split_scan() takes them off that list with list_del_init() without holding the list_lru lock.
deferred_split_folio() does not know about the on-stack list. It only holds the list_lru lock when it looks at the same list_head, and it can run for such a folio: a THP is queued when it is mapped, as a candidate for the underused check, and is queued "again" when a part of it gets unmapped:
CPU0 deferred_split_scan() CPU1 deferred_split_folio()
list_del_init(&folio->_deferred_list)
next->prev = prev
prev->next = next
entry->next = entry
list_lru_lock_irqsave()
folio_set_partially_mapped()
__list_lru_add()
list_empty(item) -> true
list_add_tail(item, &l->list)
item->next = &l->list
item->prev = tail
entry->prev = entryThe folio now sits on the list_lru with ->prev pointing to itself. The next removal leaves the neighbours pointing to it, and they still do so after the folio has been freed. With CONFIG_DEBUG_LIST:
list_del corruption. prev->next should be ffd4000000270090, but was ffd4000000278090. (prev=ffd4000000270090)
Fix it by grabbing the lock around list_del_init() so deferred_split_folio() cannot race with it.
--- mm/huge_memory.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-)
mm/huge_memory.c +13 -2
@@ -4511,8 +4511,7 @@ int split_folio_to_list(struct folio *folio, struct list_head *list)* * It is unsafe to call folio_unqueue_deferred_split() until folio refcount is * zero: because even when the list_lru lock is held, a non-empty -* _deferred_list might be in use on deferred_split_scan()'s unlocked -* on-stack list. +* _deferred_list might be in use on deferred_split_scan()'s on-stack list. * * The list_lru sublist is determined by folio's memcg: it is therefore * important to unqueue deferred split before changing folio memcg.
@@ -4658,10 +4657,22 @@ static unsigned long deferred_split_scan(struct shrinker *shrink, deferred_split_isolate, &dispose);list_for_each_entry_safe (folio, next, &dispose, _deferred_list) { +struct mem_cgroup *memcg; +struct list_lru_one *lru;bool did_split = false;bool underused = false; +/* +* Sync with deferred_split_folio(), which can requeue the +* folio once list_empty() is true, and sets PG_partially_mapped. +*/ +rcu_read_lock (); + memcg =folio_memcg (folio); + lru =list_lru_lock_irq (&deferred_split_lru,folio_nid (folio), + &memcg);list_del_init (&folio->_deferred_list); +list_lru_unlock_irq (lru); +rcu_read_unlock ();if (!folio_test_partially_mapped (folio)) {/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 155/507 mm/huge_memory: properly handle refcounted PUD mappings on fork
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit d90bdc02e36ec08d8248ebc6cdc52e12043eb28c ]
copy_huge_pud() copies device-DAX entries without taking a folio reference or updating mapcounts and the child's RSS.
For example, MADV_GUARD_INSTALL sets VM_MAYBE_GUARD on a device-DAX VMA, forcing copy_page_range() to traverse the whole VMA on fork. Any remaining huge PUDs are then copied without accounting for the new mappings. Unmapping them in the child decrements accounting that was never added.
Use vm_normal_page_pud() to identify refcounted mappings. Take a folio reference and add the child's PUD rmap and RSS accounting before installing the copied entry. Pass src and dst VMAs consistently instead of src and dst MM. Move the TODO.
--- include/linux/huge_mm.h | 5 ++--- mm/huge_memory.c | 27 +++++++++++++++++++-------- mm/memory.c | 4 +--- 3 files changed, 22 insertions(+), 14 deletions(-)
include/linux/huge_mm.h +2 -3
@@ -12,9 +12,8 @@ int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm, pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr, struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma);bool huge_pmd_set_accessed (struct vm_fault *vmf); -int copy_huge_pud (struct mm_struct *dst_mm,struct mm_struct *src_mm, -pud_t *dst_pud,pud_t *src_pud,unsigned long addr, -struct vm_area_struct *vma); +int copy_huge_pud (struct vm_area_struct *dst_vma,struct vm_area_struct *src_vma, +pud_t *dst_pud,pud_t *src_pud,unsigned long addr);#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD void huge_pud_set_accessed (struct vm_fault *vmf,pud_t orig_pud);
mm/huge_memory.c +19 -8
@@ -2073,11 +2073,13 @@ void touch_pud(struct vm_area_struct *vma, unsigned long addr,update_mmu_cache_pud (vma, addr, pud); } -int copy_huge_pud (struct mm_struct *dst_mm,struct mm_struct *src_mm, -pud_t *dst_pud,pud_t *src_pud,unsigned long addr, -struct vm_area_struct *vma) +int copy_huge_pud (struct vm_area_struct *dst_vma,struct vm_area_struct *src_vma, +pud_t *dst_pud,pud_t *src_pud,unsigned long addr) { +struct mm_struct *dst_mm = dst_vma->vm_mm; +struct mm_struct *src_mm = src_vma->vm_mm;spinlock_t *dst_ptl, *src_ptl; +struct page *page;pud_t pud;int ret;
@@ -2090,11 +2092,20 @@ int copy_huge_pud(struct mm_struct *dst_mm, struct mm_struct *src_mm,if (unlikely (!pud_trans_huge (pud))) goto out_unlock; -/* -* TODO: once we support anonymous pages, use -* folio_try_dup_anon_rmap_*() and split if duplicating fails. -*/ -if (vma_is_cow_mapping (vma) &&pud_write (pud)) { + page =vm_normal_page_pud (src_vma, addr, pud); +if (page) { +struct folio *folio =page_folio (page); + +folio_get (folio); +/* +* TODO: once we support anonymous pages, use +* folio_try_dup_anon_rmap_*() and split if duplicating fails. +*/ +folio_add_file_rmap_pud (folio, page, dst_vma); +add_mm_counter (dst_mm,mm_counter_file (folio),HPAGE_PUD_NR ); + } + +if (vma_is_cow_mapping (src_vma) &&pud_write (pud)) {pudp_set_wrprotect (src_mm, addr, src_pud); pud =pud_wrprotect (pud); }
mm/memory.c +1 -3
@@ -1500,7 +1500,6 @@ copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, unsigned long end) {struct mm_struct *dst_mm = dst_vma->vm_mm; -struct mm_struct *src_mm = src_vma->vm_mm;pud_t *src_pud, *dst_pud;unsigned long next;
@@ -1514,8 +1513,7 @@ copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,int err;VM_BUG_ON_VMA (next-addr !=HPAGE_PUD_SIZE , src_vma); - err =copy_huge_pud (dst_mm, src_mm, - dst_pud, src_pud, addr, src_vma); + err =copy_huge_pud (dst_vma, src_vma, dst_pud, src_pud, addr);if (err == -ENOMEM )return -ENOMEM ;if (!err)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 156/507 ext2: preserve completed DIO bytes when buffered fallback fails
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
[ Upstream commit cbf04dde8b3c5a7e043e91cefad68b8980ea0d18 ]
ext2_dio_write_iter() can complete part of a direct write before falling back to buffered I/O for a hole inside i_size. If generic_perform_write() then fails, its error overwrites the completed direct-I/O byte count.
For example, on a full filesystem, an 8 KiB write to a file with an allocated 4 KiB prefix and a 4 KiB hole overwrites the prefix but returns ENOSPC and leaves the file position unchanged. GNU dd with oflag=direct consequently reports zero bytes written.
Preserve a positive direct-I/O result and return the buffered error when no bytes were direct-written. This restores the fallback policy of generic_file_write_iter(), which ext2 used before its iomap conversion.
--- fs/ext2/file.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
fs/ext2/file.c +2 -1
@@ -138,7 +138,8 @@ static ssize_t ext2_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) pos = iocb->ki_pos; status =generic_perform_write (iocb, from);if (unlikely (status <0 )) { - ret = status; +if (!ret) + ret = status; goto out_unlock; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 157/507 xfs: set healthmon mount cookie before publishing it
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Binbin Deng <[email protected]>
[ Upstream commit 0344a9492efac4c79202a07cf284a382f7054170 ]
xfs_ioc_health_monitor() allocates the healthmon object with kzalloc(), so mount_cookie starts as zero. zero is also DETACHED_MOUNT_COOKIE, but xfs_healthmon_attach() publishes hm through mp->m_healthmon before storing the mount cookie. A concurrent reporter can therefore acquire hm from xfs_healthmon_get(), see the detached cookie in xfs_healthmon_push(), and drop the event even though the monitor is being attached.
This is reachable by racing XFS_IOC_HEALTH_MONITOR with an operation that reports a health event, such as a filesystem shutdown. Initialize the mount cookie before making hm visible through the RCU pointer so reporters always observe an attached monitor.
Found during a static-analysis-assisted audit: candidate sites were surfaced by a Coccinelle rule, and the reader/writer paths were confirmed by LLM-assisted (GLM-5.3) code inspection. The issue was not observed at runtime; it is identified by code inspection only.
--- fs/xfs/xfs_healthmon.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/xfs_healthmon.c +1 -1
@@ -114,8 +114,8 @@ xfs_healthmon_attach( }refcount_inc (&hm->ref); -rcu_assign_pointer (mp->m_healthmon, hm); hm->mount_cookie = (uintptr_t )mp->m_super; +rcu_assign_pointer (mp->m_healthmon, hm);spin_unlock (&xfs_healthmon_lock);return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 158/507 xfs: dont skip free extents in later batches of a whole-AG FITRIM
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daejun Park <[email protected]>
[ Upstream commit 595e67d7261673d03c96950ffbb2e545c00376ed ]
A whole-device FITRIM walks every AG but the last by length, in batches. xfs_trim_gather_extents() saves the record to restart from in tcur->start. But tcur->start is also the start of the range to trim. Later batches therefore never discard the free extents below that block.
Save the restart record in a new restart_bno field.
--- fs/xfs/xfs_discard.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-)
fs/xfs/xfs_discard.c +14 -4
@@ -155,6 +155,8 @@ struct xfs_trim_cur {xfs_agblock_t end;xfs_extlen_t minlen;bool by_bno; +/* restart point (with count) for the by-length walk */ +xfs_agblock_t restart_bno; }; static int
@@ -198,14 +200,15 @@ xfs_trim_gather_extents( error =xfs_alloc_lookup_le (cur, tcur->start,0 , &i);if (!error && !i) error =xfs_alloc_lookup_ge (cur, tcur->start,0 , &i); - }else if (tcur->start ==0 ) { + }else if (tcur->restart_bno ==NULLAGBLOCK ) {/* first time through a by-len starts with max length */ cur =xfs_cntbt_init_cursor (mp, tp, agbp, pag); error =xfs_alloc_lookup_ge (cur,0 , tcur->count, &i); }else {/* nth time through a by-len starts where we left off */ cur =xfs_cntbt_init_cursor (mp, tp, agbp, pag); - error =xfs_alloc_lookup_le (cur, tcur->start, tcur->count, &i); + error =xfs_alloc_lookup_le (cur, tcur->restart_bno, + tcur->count, &i); }if (error) goto out_del_cursor;
@@ -235,9 +238,15 @@ xfs_trim_gather_extents(if (--batch <=0 ) {/* * Update the cursor to point at this extent so we -* restart the next batch from this extent. +* restart the next batch from this extent. The +* by-length walk does not visit extents in block +* order, so it must keep the start of the range and +* restart from restart_bno instead. */ - tcur->start = fbno; +if (tcur->by_bno) + tcur->start = fbno; +else + tcur->restart_bno = fbno; tcur->count = flen;break ; }
@@ -340,6 +349,7 @@ xfs_trim_perag_extents( .start = start, .end = end, .minlen = minlen, + .restart_bno = NULLAGBLOCK, };int error =0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 159/507 xfs: dont skip free extents of the longest length in a whole-AG FITRIM
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daejun Park <[email protected]>
[ Upstream commit 5745f4f10a1a16aa5bb020acc38afa33f2d5ff99 ]
Since commit a66d636385d6 ("xfs: fix fstrim offset calculations"), the by-length walk of an AG in FITRIM starts with xfs_alloc_lookup_ge(cur, 0, pagf_longest) and walks down. The lookup lands on the longest free extent with the lowest block number. The other free extents of that length sort after it and are never discarded.
Start every by-length batch with xfs_alloc_lookup_le() at restart_bno.
--- fs/xfs/xfs_discard.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)
fs/xfs/xfs_discard.c +5 -5
@@ -200,12 +200,12 @@ xfs_trim_gather_extents( error =xfs_alloc_lookup_le (cur, tcur->start,0 , &i);if (!error && !i) error =xfs_alloc_lookup_ge (cur, tcur->start,0 , &i); - }else if (tcur->restart_bno ==NULLAGBLOCK ) { -/* first time through a by-len starts with max length */ - cur =xfs_cntbt_init_cursor (mp, tp, agbp, pag); - error =xfs_alloc_lookup_ge (cur,0 , tcur->count, &i); }else { -/* nth time through a by-len starts where we left off */ +/* +* A by-len walk starts at the last record of the longest +* length (restart_bno is NULLAGBLOCK until the first batch +* ends) and then where the previous batch stopped. +*/ cur =xfs_cntbt_init_cursor (mp, tp, agbp, pag); error =xfs_alloc_lookup_le (cur, tcur->restart_bno, tcur->count, &i);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 160/507 drm/v3d: Initialize timedout_batches when running a CSD job
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jose Maria Casanova Crespo <[email protected]>
[ Upstream commit 0afdbdd5b1af729108de8f893d179c3b99eac29d ]
v3d_csd_job_timedout() decides whether a compute job made progress by comparing CSD_CURRENT_CFG4, the number of batches the dispatcher still has to start, against the value saved at the previous timeout. That saved value is never initialized, so it is zero on the first timeout.
On V3D 7.1.6 and later, CFG4 counts down to zero once the dispatcher has started the last batch, but the dispatch keeps running until the batches in flight complete. If the first timeout fires in that window, the handler sees no change and resets the GPU while the job is about to complete. For example, this happens with long dispatches that only keep a single supergroup in flight.
Initialize timedout_batches to the value programmed in CFG4 when the job is started. The register does not return to it once a batch has started:
it counts down to zero on V3D 7.1.6 and later (CFG4 holds the number of batches), and to 0xffffffff on V3D 4.2 (CFG4 holds the number of batches minus one).
--- drivers/gpu/drm/v3d/v3d_sched.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/gpu/drm/v3d/v3d_sched.c +2 -0
@@ -360,6 +360,8 @@ v3d_csd_job_run(struct drm_sched_job *sched_job)dma_fence_put (job->base.irq_fence); job->base.irq_fence =dma_fence_get (fence); + job->timedout_batches = job->args.cfg[4 ]; +trace_v3d_submit_csd (dev,to_v3d_fence (fence)->seqno);v3d_job_start_stats (&job->base);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 161/507 drm/v3d: Widen cache_clean_lock over the whole L2TCACTL sequence
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Maíra Canal <[email protected]>
[ Upstream commit 994ba6e5c87d6a3d471ea987fe8622168f092334 ]
v3d_clean_caches() and v3d_flush_l2t() both write the single L2TCACTL register and poll its status bits. The mutex cache_clean_lock exists to serialize them, but v3d_clean_caches() only took the lock around its final FLM_CLEAN write.
These functions run concurrently: v3d_flush_l2t() is issued from the BIN/RENDER/CSD invalidate path while v3d_clean_caches() runs from the CACHE_CLEAN queue, and each queue's scheduler uses its own ordered workqueue, so their run_job callbacks execute in parallel.
Because clean locked only its final write, a concurrent flush can write L2TCACTL during clean's unlocked phase. Both use non read-modify-write writes to the one register, so whichever lands last wins: clean's TMUWCF write can land on the flush's in-flight L2TFLS invalidate, triggering the GFXH-1897 hazard of writing L2TCACTL while a flush is pending.
Hold cache_clean_lock across the entire L2TCACTL access sequence so it is fully mutually exclusive with v3d_flush_l2t(), which already takes the lock around its own write.
--- drivers/gpu/drm/v3d/v3d_gem.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/gpu/drm/v3d/v3d_gem.c +2 -3
@@ -217,6 +217,8 @@ v3d_clean_caches(struct v3d_dev *v3d)struct drm_device *dev = &v3d->drm;int core =0 ; +guard (mutex)(&v3d->cache_clean_lock); +trace_v3d_cache_clean_begin (dev);/* GFXH-1897: Ensure pending flushes complete before writing L2TCACTL */
@@ -233,7 +235,6 @@ v3d_clean_caches(struct v3d_dev *v3d)drm_err (dev,"Timeout waiting for TMU write combiner flush\n" ); } -mutex_lock (&v3d->cache_clean_lock);V3D_CORE_WRITE (core,V3D_CTL_L2TCACTL ,V3D_L2TCACTL_L2TFLS |V3D_SET_FIELD (V3D_L2TCACTL_FLM_CLEAN ,V3D_L2TCACTL_FLM ));
@@ -243,8 +244,6 @@ v3d_clean_caches(struct v3d_dev *v3d)drm_err (dev,"Timeout waiting for L2T clean\n" ); } -mutex_unlock (&v3d->cache_clean_lock); -trace_v3d_cache_clean_end (dev); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 162/507 cipso: fix optlen corruption in cipso_v4_delopt()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Qihang <[email protected]>
[ Upstream commit 1f1f8e8c5176234fa31858cd25f2e9b88aac0a45 ]
cipso_v4_delopt() recomputes the option length by walking the option buffer after the CIPSO option has been moved out. The walk then reads the stale bytes at the tail of the buffer as option data, and a crafted setsockopt(IP_OPTIONS) buffer can make it treat one of them as an option length, increasing opt->opt.optlen beyond the valid option data.
The corrupted length stays on the socket and is later used as the copy length by getsockopt(IP_OPTIONS) and by the udp/raw/ping sendmsg paths, where it exceeds the size of the buffers they copy into.
Compute the new length from the intact options before the move and subtract the CIPSO length, and fill the padding with IPOPT_END.
--- net/ipv4/cipso_ipv4.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
net/ipv4/cipso_ipv4.c +7 -2
@@ -2013,6 +2013,10 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr) cipso_ptr = &opt->opt.__data[cipso_off]; cipso_len = cipso_ptr[1 ]; + optlen_new =cipso_v4_get_actual_opt_len (opt->opt.__data, + opt->opt.optlen); + optlen_new -= cipso_len; +if (opt->opt.srr > opt->opt.cipso) opt->opt.srr -= cipso_len;if (opt->opt.rr > opt->opt.cipso)
@@ -2026,11 +2030,12 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr)memmove (cipso_ptr, cipso_ptr + cipso_len, opt->opt.optlen - cipso_off - cipso_len); - optlen_new =cipso_v4_get_actual_opt_len (opt->opt.__data, - opt->opt.optlen); hdr_delta = opt->opt.optlen; opt->opt.optlen = (optlen_new +3 ) & ~3 ; hdr_delta -= opt->opt.optlen; + +memset (&opt->opt.__data[optlen_new],IPOPT_END , + opt->opt.optlen - optlen_new); }else {/* only the cipso option was present on the socket so we can * remove the entire option struct */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 163/507 ntfs: dont allow compression on volumes with clusters larger than 4K
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhan Xusheng <[email protected]>
[ Upstream commit c77ab4eeeb3ed471bcc99a94673f0e0142c4b84a ]
On a volume made with "mkntfs -c 8192", a user can set FILE_ATTR_COMPRESSED on an empty file through system.ntfs_attrib. Writing to the file and reading it back after dropping the page cache then crashes:
BUG: KASAN: slab-out-of-bounds in ntfs_read_compressed_block+0xa2c/0x2040 Read of size 8192 at addr ffff88804355a000 by task dd/106
The read path only handles clusters up to 4K. It copies each cluster out of a single page, and a compression block of 16 8K clusters does not fit in the 64K ntfs_compression_buffer. Loading an inode already rejects compressed data on such volumes.
Reject the flag change the same way.
--- fs/ntfs/ea.c | 5 +++++ 1 file changed, 5 insertions(+)
fs/ntfs/ea.c +5 -0
@@ -699,6 +699,11 @@ static int ntfs_new_attr_flags(struct ntfs_inode *ni, __le32 fattr) goto err_out; } +if ((new_aflags &ATTR_IS_COMPRESSED ) && ni->vol->cluster_size >4096 ) { + err = -EOPNOTSUPP ; + goto err_out; + } +if (!a->non_resident) {if (!(new_aflags & (ATTR_IS_SPARSE |ATTR_IS_COMPRESSED ))) { err =0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 164/507 vhost-vdpa: fix pinned page leak in vhost_vdpa_pa_map() error path
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tal Zussman <[email protected]>
[ Upstream commit fd1462c96bafe2cb14e88c837b270f8990b717b5 ]
When pin_user_pages() or vhost_vdpa_map() fails, vhost_vdpa_pa_map() is supposed to unpin the pages pinned after the last successfully mapped chunk, i.e. the range [map_pfn, last_pfn]. The unpin is guarded by nchunks, but nchunks is reset to 0 every time a chunk is mapped from inside the current page list, so a failure after any such boundary leaves that pending range pinned forever. With physically scattered memory nearly every page list contains a boundary, so the leak happens on practically every failed IOTLB update.
The pending range is non-empty exactly when a page has been pinned, which last_pfn already tells us, so drop nchunks and test last_pfn.
Message-ID: <[email protected]>
--- drivers/vhost/vdpa.c | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-)
drivers/vhost/vdpa.c +2 -6
@@ -1151,7 +1151,7 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v,unsigned long list_size =PAGE_SIZE /sizeof (struct page *);unsigned int gup_flags =FOLL_LONGTERM ;unsigned long npages, cur_base, map_pfn, last_pfn =0 ; -unsigned long lock_limit, sz2pin, nchunks, i; +unsigned long lock_limit, sz2pin, i;unsigned long page_offset;u64 start = iova;long pinned;
@@ -1187,7 +1187,6 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v, cur_base = uaddr &PAGE_MASK ; iova &=PAGE_MASK ; - nchunks =0 ;while (npages) { sz2pin = min_t(unsigned long, npages, list_size);
@@ -1202,7 +1201,6 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v, } goto out; } - nchunks++;if (!last_pfn) map_pfn =page_to_pfn (page_list[0 ]);
@@ -1233,7 +1231,6 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v, map_pfn = this_pfn; iova += csize; - nchunks =0 ; } last_pfn = this_pfn;
@@ -1248,7 +1245,7 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v, PFN_PHYS(map_pfn), perm, NULL); out:if (ret) { -if (nchunks) { +if (last_pfn) {unsigned long pfn;/*
@@ -1260,7 +1257,6 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v,* the corresponding unpinning will be handled by * vdpa_unmap(). */ -WARN_ON (!last_pfn);for (pfn = map_pfn; pfn <= last_pfn; pfn++)unpin_user_page (pfn_to_page (pfn)); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 165/507 vringh: bound top-level re-entry into indirect tables
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fang Xieyan <[email protected]>
[ Upstream commit f898439ace7f89922e853b43bcbfcd26ea2e0a98 ]
In __vringh_iov(), the F_INDIRECT branch descends into the indirect table and continues before the descriptor accounting runs. A top-level indirect descriptor is therefore never charged to count. If such a descriptor sets NEXT to point back at itself, returning from the indirect table resumes at the same top-level descriptor, which is again not counted, so the walk never makes forward progress.
Because count stays flat and indirect_count is reset to 0 on every return to the top-level table, neither bound in the loop check trips. A guest can spin the vringh worker at 100% CPU inside __vringh_iov(), an uninterruptible host DoS.
Move the descriptor accounting above the indirect switch so that a top-level indirect descriptor is charged one top-level traversal step before the walk descends into its table, bringing this re-entry under the existing vrh->vring.num bound. Each top-level descriptor is still charged at most one step and indirect_count still bounds a single table, so legitimate chains (including the multiple-indirect case in tools/virtio/vringh_test.c) stay within vring.num, while a cyclic indirect descriptor is now rejected with -ELOOP.
Message-ID: <[email protected]>
--- drivers/vhost/vringh.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-)
drivers/vhost/vringh.c +11 -11
@@ -333,6 +333,17 @@ __vringh_iov(struct vringh *vrh, u16 i,if (unlikely (err)) goto fail; +if (up_next ==-1 ) + count++; +else + indirect_count++; + +if (count > vrh->vring.num || indirect_count > desc_max) { +vringh_bad ("Descriptor loop in %p" , descs); + err = -ELOOP ; + goto fail; + } +if (unlikely (desc.flags &cpu_to_vringh16 (vrh,VRING_DESC_F_INDIRECT ))) {u64 a =vringh64_to_cpu (vrh, desc.addr);
@@ -358,17 +369,6 @@ __vringh_iov(struct vringh *vrh, u16 i,continue ; } -if (up_next ==-1 ) - count++; -else - indirect_count++; - -if (count > vrh->vring.num || indirect_count > desc_max) { -vringh_bad ("Descriptor loop in %p" , descs); - err = -ELOOP ; - goto fail; - } -if (desc.flags &cpu_to_vringh16 (vrh,VRING_DESC_F_WRITE )) iov = wiov;else {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 166/507 vringh: reject empty / undersized indirect descriptor tables
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fang Xieyan <[email protected]>
[ Upstream commit 60a792b97933a686316737838cd007d27963011e ]
move_to_indirect() validates an indirect descriptor table only with "len % sizeof(struct vring_desc)". A descriptor flagged VRING_DESC_F_INDIRECT with len == 0 passes that test, so *desc_max is set to 0 while *descs points at the empty table. __vringh_iov() then copies one struct vring_desc from descs[0] -- 16 bytes past the end of the table -- before the "indirect_count > desc_max" loop detection aborts the walk. The over-read value is discarded when the walk aborts and is never used to map anything, but the access itself is out of bounds.
Reject any len smaller than one descriptor, alongside the existing stride check, so an empty table is refused with -EINVAL and no descriptor is ever fetched from it.
Message-ID: <[email protected]>
--- drivers/vhost/vringh.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/vhost/vringh.c +3 -2
@@ -197,8 +197,9 @@ static int move_to_indirect(const struct vringh *vrh, } len =vringh32_to_cpu (vrh, desc->len); -if (unlikely (len %sizeof (struct vring_desc ))) { -vringh_bad ("Strange indirect len %u" , desc->len); +if (unlikely (len <sizeof (struct vring_desc ) || + len %sizeof (struct vring_desc ))) { +vringh_bad ("Invalid indirect len %u" , desc->len);return -EINVAL ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 167/507 veth: keep carrier off when resizing channels with a down peer
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xia Yan <[email protected]>
[ Upstream commit 2d02191779345b13de91048db441191b20264d16 ]
veth_set_channels() temporarily turns carrier off while reconfiguring a running interface. It then turns carrier on for both ends without checking whether the peer is administratively up. If only one end is up, changing its channel counts therefore reports LOWER_UP even though the peer remains down.
For example, after creating a pair with two RX and TX queues per end:
ip link set vca up
ethtool -L vca rx 1 tx 1
vca incorrectly reports LOWER_UP while vcb is still down.
Only restore carrier when the peer has IFF_UP, matching veth_open(). The local interface is already known to be running at this point.
Found during LLM-assisted source review and reproduced with a veth pair in network namespaces, without kernel instrumentation or error injection. The companion veth.sh test reproduces the two mixed up/down failures before the fix and passes after it.
--- drivers/net/veth.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/veth.c +3 -2
@@ -1372,9 +1372,10 @@ static int veth_set_channels(struct net_device *dev,* to identify the range we have to disable */ veth_disable_range_safe (dev, new_rx_count, old_rx_count); -netif_carrier_on (dev); -if (peer) +if (peer && (peer->flags &IFF_UP )) { +netif_carrier_on (dev);netif_carrier_on (peer); + } }/* update XDP supported features */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 168/507 hwmon: (sht15) Stop deferred work before releasing its resources
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
[ Upstream commit 5eab1e7f7ed12893f3864fe46ffcd5a41a752d6a ]
The IRQ handler and regulator notifier can leave work pending after a measurement or notification completes. Neither work item is drained before its resources are released on removal or probe failure.
Disable read_work before freeing the IRQ, since the worker can re-enable it. Use request_irq()/free_irq() for explicit teardown. Unregister the regulator notifier before cancelling update_supply_work and disabling the regulator. Apply the same ordering to probe failures.
--- drivers/hwmon/sht15.c | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-)
drivers/hwmon/sht15.c +14 -8
@@ -31,6 +31,7 @@#include <linux/bitrev.h> #include <linux/gpio/consumer.h> #include <linux/of.h> +#include <linux/workqueue.h> /* Commands */ #define SHT15_MEASURE_TEMP 0x03
@@ -976,25 +977,22 @@ static int sht15_probe(struct platform_device *pdev) goto err_release_reg; } - ret =devm_request_irq (&pdev->dev,gpiod_to_irq (data->data), - sht15_interrupt_fired, -IRQF_TRIGGER_FALLING , -"sht15 data" , - data); + ret =request_irq (gpiod_to_irq (data->data), sht15_interrupt_fired, +IRQF_TRIGGER_FALLING ,"sht15 data" , data);if (ret) goto err_release_reg;disable_irq_nosync (gpiod_to_irq (data->data)); ret =sht15_connection_reset (data);if (ret) - goto err_release_reg; + goto err_free_irq; ret =sht15_soft_reset (data);if (ret) - goto err_release_reg; + goto err_free_irq; ret =sysfs_create_group (&pdev->dev.kobj, &sht15_attr_group);if (ret) {dev_err (&pdev->dev,"sysfs create failed\n" ); - goto err_release_reg; + goto err_free_irq; } data->hwmon_dev =hwmon_device_register (data->dev);
@@ -1007,9 +1005,13 @@ static int sht15_probe(struct platform_device *pdev) err_release_sysfs_group:sysfs_remove_group (&pdev->dev.kobj, &sht15_attr_group); +err_free_irq: +disable_work_sync (&data->read_work); +free_irq (gpiod_to_irq (data->data), data); err_release_reg:if (!IS_ERR (data->reg)) {regulator_unregister_notifier (data->reg, &data->nb); +cancel_work_sync (&data->update_supply_work);regulator_disable (data->reg); }return ret;
@@ -1023,12 +1025,16 @@ static void sht15_remove(struct platform_device *pdev)hwmon_device_unregister (data->hwmon_dev);sysfs_remove_group (&pdev->dev.kobj, &sht15_attr_group); +disable_work_sync (&data->read_work); +free_irq (gpiod_to_irq (data->data), data); + ret =sht15_soft_reset (data);if (ret)dev_err (&pdev->dev,"Failed to reset device (%pe)\n" ,ERR_PTR (ret));if (!IS_ERR (data->reg)) {regulator_unregister_notifier (data->reg, &data->nb); +cancel_work_sync (&data->update_supply_work);regulator_disable (data->reg); } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 169/507 hwmon: (corsair-cpro) Cache fan target only after a successful command
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baek Kyu, Kim <[email protected]>
[ Upstream commit e2c26431b4e47892378582a414b4bbaa9edf1798 ]
set_target() updates the cached fan target before sending the command. If the command fails, subsequent fanN_target reads report the failed request instead of the previous value. For example, after successfully setting 1200 RPM, a rejected request for 1800 RPM returns an error but leaves fanN_target reporting 1800. A failed request also replaces -ENODATA when no target has been successfully set.
Update the target cache under the existing mutex only after send_usb_cmd() succeeds, as set_pwm() already does when invalidating the target. Preserve the previous cached value and return the original error on failure.
--- drivers/hwmon/corsair-cpro.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/hwmon/corsair-cpro.c +2 -1
@@ -215,10 +215,11 @@ static int set_target(struct ccp_device *ccp, int channel, long val)int ret; val =clamp_val (val,0 ,0xFFFF ); - ccp->target[channel] = val;mutex_lock (&ccp->mutex); ret =send_usb_cmd (ccp,CTL_SET_FAN_TARGET , channel, val >>8 , val); +if (!ret) + ccp->target[channel] = val;mutex_unlock (&ccp->mutex);return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 170/507 hwmon: (aquacomputer_d5next) reject short status reports
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
[ Upstream commit cf8f81babd2e96087dedbb74985bc1781c98f73d ]
The HID raw_event callback runs before HID core validates the received report length. aqc_raw_event() reads device-specific status fields at fixed offsets, including multi-byte values, without first ensuring that the received buffer contains every field. A truncated report can therefore cause out-of-bounds reads and update hwmon state with unrelated data.
The required length differs between supported devices and cannot be derived from the HID report descriptor. Define the minimum length needed by each asynchronous status format, select it while configuring the device, and reject reports that do not contain the last field accessed by that format. Keep the published length zero until probe configuration is complete, which also excludes legacy devices whose status is retrieved through feature reports.
--- drivers/hwmon/aquacomputer_d5next.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+)
drivers/hwmon/aquacomputer_d5next.c +27 -0
@@ -132,6 +132,7 @@ static u8 aquaero_secondary_ctrl_report[] = {#define AQUAERO_FAN_CURRENT_OFFSET 0x06#define AQUAERO_FAN_POWER_OFFSET 0x08#define AQUAERO_FAN_SPEED_OFFSET 0x00 +#define AQUAERO_MIN_STATUS_REPORT_SIZE (0x18B + AQUAERO_FAN_POWER_OFFSET + sizeof(u16))static u16 aquaero_sensor_fan_offsets[] = {0x167 ,0x173 ,0x17f ,0x18B };/* Control report offsets for the Aquaero fan controllers */
@@ -155,6 +156,8 @@ static u16 aquaero_ctrl_fan_offsets[] = { 0x20c, 0x220, 0x234, 0x248 };#define D5NEXT_5V_VOLTAGE 0x39#define D5NEXT_12V_VOLTAGE 0x37#define D5NEXT_VIRTUAL_SENSORS_START 0x3f +#define D5NEXT_MIN_STATUS_REPORT_SIZE (D5NEXT_PUMP_OFFSET + AQC_FAN_SPEED_OFFSET + \ + sizeof(u16))static u16 d5next_sensor_fan_offsets[] = {D5NEXT_PUMP_OFFSET ,D5NEXT_FAN_OFFSET };/* Control report offsets for the D5 Next pump */
@@ -179,11 +182,14 @@ static u16 d5next_ctrl_fan_offsets[] = { 0x97, 0x42 }; /* Pump and fan speed (fr#define AQUASTREAMULT_FAN_CURRENT_OFFSET 0x00#define AQUASTREAMULT_FAN_POWER_OFFSET 0x04#define AQUASTREAMULT_FAN_SPEED_OFFSET 0x06 +#define AQUASTREAMULT_MIN_STATUS_REPORT_SIZE (AQUASTREAMULT_PRESSURE_OFFSET + sizeof(u16))static u16 aquastreamult_sensor_fan_offsets[] = {AQUASTREAMULT_FAN_OFFSET };/* Spec and sensor report offset for the Farbwerk RGB controller */ #define FARBWERK_NUM_SENSORS 4#define FARBWERK_SENSOR_START 0x2f +#define FARBWERK_MIN_STATUS_REPORT_SIZE (FARBWERK_SENSOR_START + \ + FARBWERK_NUM_SENSORS * AQC_SENSOR_SIZE)/* Specs of the Farbwerk 360 RGB controller */ #define FARBWERK360_NUM_SENSORS 4
@@ -193,6 +199,8 @@ static u16 aquastreamult_sensor_fan_offsets[] = { AQUASTREAMULT_FAN_OFFSET };/* Sensor report offsets for the Farbwerk 360 */ #define FARBWERK360_SENSOR_START 0x32#define FARBWERK360_VIRTUAL_SENSORS_START 0x3a +#define FARBWERK360_MIN_STATUS_REPORT_SIZE (FARBWERK360_VIRTUAL_SENSORS_START + \ + FARBWERK360_NUM_VIRTUAL_SENSORS * AQC_SENSOR_SIZE)/* Control report offsets for the Farbwerk 360 */ #define FARBWERK360_TEMP_CTRL_OFFSET 0x8
@@ -209,6 +217,7 @@ static u16 aquastreamult_sensor_fan_offsets[] = { AQUASTREAMULT_FAN_OFFSET };#define OCTO_SENSOR_START 0x3D#define OCTO_VIRTUAL_SENSORS_START 0x45#define OCTO_FLOW_SENSOR_OFFSET 0x7B +#define OCTO_MIN_STATUS_REPORT_SIZE (0xD8 + AQC_FAN_SPEED_OFFSET + sizeof(u16))static u16 octo_sensor_fan_offsets[] = {0x7D ,0x8A ,0x97 ,0xA4 ,0xB1 ,0xBE ,0xCB ,0xD8 };/* Control report offsets for the Octo */
@@ -229,6 +238,7 @@ static u16 octo_ctrl_fan_offsets[] = { 0x5B, 0xB0, 0x105, 0x15A, 0x1AF, 0x204, 0#define QUADRO_SENSOR_START 0x34#define QUADRO_VIRTUAL_SENSORS_START 0x3c#define QUADRO_FLOW_SENSOR_OFFSET 0x6e +#define QUADRO_MIN_STATUS_REPORT_SIZE (0x97 + AQC_FAN_SPEED_OFFSET + sizeof(u16))static u16 quadro_sensor_fan_offsets[] = {0x70 ,0x7D ,0x8A ,0x97 };/* Control report offsets for the Quadro */
@@ -248,6 +258,7 @@ static u16 quadro_ctrl_fan_offsets[] = { 0x37, 0x8c, 0xe1, 0x136 }; /* Fan speed#define HIGHFLOWNEXT_CONDUCTIVITY 95#define HIGHFLOWNEXT_5V_VOLTAGE 97#define HIGHFLOWNEXT_5V_VOLTAGE_USB 99 +#define HIGHFLOWNEXT_MIN_STATUS_REPORT_SIZE (HIGHFLOWNEXT_5V_VOLTAGE_USB + sizeof(u16))/* Specs of the Leakshield */ #define LEAKSHIELD_NUM_SENSORS 2
@@ -263,6 +274,7 @@ static u16 quadro_ctrl_fan_offsets[] = { 0x37, 0x8c, 0xe1, 0x136 }; /* Fan speed#define LEAKSHIELD_FLOW_IN 111#define LEAKSHIELD_RESERVOIR_VOLUME 313#define LEAKSHIELD_RESERVOIR_FILLED 311 +#define LEAKSHIELD_MIN_STATUS_REPORT_SIZE (LEAKSHIELD_RESERVOIR_VOLUME + sizeof(u16))/* Specs of the Aquastream XT pump */ #define AQUASTREAMXT_SERIAL_START 0x3a
@@ -554,6 +566,7 @@ struct aqc_data {const char *name;int status_report_id;/* Used for legacy devices, report is stored in buffer */ +u16 min_report_size;int ctrl_report_id;int secondary_ctrl_report_id;int secondary_ctrl_report_size;
@@ -1333,6 +1346,8 @@ static int aqc_raw_event(struct hid_device *hdev, struct hid_report *report, u8return 0 ; priv =hid_get_drvdata (hdev); +if (!priv->min_report_size || size < priv->min_report_size) +return 0 ;/* Info provided with every report */ priv->serial_number[0 ] =get_unaligned_be16 (data + priv->serial_number_start_offset);
@@ -1518,6 +1533,7 @@ static void aqc_debugfs_init(struct aqc_data *priv)static int aqc_probe (struct hid_device *hdev,const struct hid_device_id *id) {struct aqc_data *priv; +u16 min_report_size =0 ;int ret; priv =devm_kzalloc (&hdev->dev,sizeof (*priv),GFP_KERNEL );
@@ -1585,6 +1601,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) priv->power_label = label_fan_power; priv->voltage_label = label_fan_voltage; priv->current_label = label_fan_current; + min_report_size =AQUAERO_MIN_STATUS_REPORT_SIZE ;break ;case USB_PRODUCT_ID_D5NEXT : priv->kind = d5next;
@@ -1610,6 +1627,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) priv->power_label = label_d5next_power; priv->voltage_label = label_d5next_voltages; priv->current_label = label_d5next_current; + min_report_size =D5NEXT_MIN_STATUS_REPORT_SIZE ;break ;case USB_PRODUCT_ID_FARBWERK : priv->kind = farbwerk;
@@ -1620,6 +1638,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) priv->temp_sensor_start_offset =FARBWERK_SENSOR_START ; priv->temp_label = label_temp_sensors; + min_report_size =FARBWERK_MIN_STATUS_REPORT_SIZE ;break ;case USB_PRODUCT_ID_FARBWERK360 : priv->kind = farbwerk360;
@@ -1636,6 +1655,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) priv->temp_label = label_temp_sensors; priv->virtual_temp_label = label_virtual_temp_sensors; + min_report_size =FARBWERK360_MIN_STATUS_REPORT_SIZE ;break ;case USB_PRODUCT_ID_OCTO : priv->kind = octo;
@@ -1665,6 +1685,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) priv->power_label = label_fan_power; priv->voltage_label = label_fan_voltage; priv->current_label = label_fan_current; + min_report_size =OCTO_MIN_STATUS_REPORT_SIZE ;break ;case USB_PRODUCT_ID_QUADRO : priv->kind = quadro;
@@ -1694,6 +1715,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) priv->power_label = label_fan_power; priv->voltage_label = label_fan_voltage; priv->current_label = label_fan_current; + min_report_size =QUADRO_MIN_STATUS_REPORT_SIZE ;break ;case USB_PRODUCT_ID_HIGHFLOWNEXT : priv->kind = highflownext;
@@ -1711,6 +1733,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) priv->speed_label = label_highflownext_fan_speed; priv->power_label = label_highflownext_power; priv->voltage_label = label_highflownext_voltage; + min_report_size =HIGHFLOWNEXT_MIN_STATUS_REPORT_SIZE ;break ;case USB_PRODUCT_ID_LEAKSHIELD :/*
@@ -1730,6 +1753,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) priv->temp_label = label_leakshield_temp_sensors; priv->speed_label = label_leakshield_fan_speed; + min_report_size =LEAKSHIELD_MIN_STATUS_REPORT_SIZE ;break ;case USB_PRODUCT_ID_AQUASTREAMXT : priv->kind = aquastreamxt;
@@ -1760,6 +1784,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) priv->power_label = label_aquastreamult_power; priv->voltage_label = label_aquastreamult_voltages; priv->current_label = label_aquastreamult_current; + min_report_size =AQUASTREAMULT_MIN_STATUS_REPORT_SIZE ;break ;case USB_PRODUCT_ID_POWERADJUST3 : priv->kind = poweradjust3;
@@ -1833,6 +1858,8 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)break ; } + priv->min_report_size = min_report_size; +if (priv->buffer_size !=0 ) { priv->checksum_start =0x01 ; priv->checksum_length = priv->buffer_size -3 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 171/507 hwmon: (asus_rog_ryujin) Fix pump control source on the Ryujin III
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zac Lanzon <[email protected]>
[ Upstream commit 743b4481b6112d8ac11c165628daa8e0f0ecf78c ]
The RYUJIN III pump has a 4-pin cable for a motherboard fan header in addition to USB. Byte 2 of the set cooler duty command selects the pump control source: 0 hands the pump to its internal controller, which follows the PWM of the header its 4-pin cable is plugged into, and 1 makes it follow the pump duty in byte 3. Byte 3 of the cooler duty report returns the current source.
The driver fills byte 2 with duty_channel, which is 1 for the RYUJIN III, and a pwm2 write re-sends the reported pump duty with the new fan duty. So writing only the internal fan duty takes the pump away from its internal controller.
Measured on a RYUJIN III 360 (firmware AURJ2-S750-0108) with the pump cable on AIO_PUMP and the header PWM set through nct6775, after loading the driver with the pump on its internal controller (pump rpm):
header 50% header 80% source
no write yet 2160 3090 0 pwm2 = 40%, before this patch 1740 1740 1 pwm2 = 40%, with this patch 2130 3090 0
Send the reported source with pwm2 writes. The fan duty applies with either source (40%: 1545 to 1590 rpm, 30%: 870 rpm). A pwm2 write sent right after a pwm1 write that took the pump over, before the report could show the change, left the pump on USB and applied its fan duty (2 of 2 trials, and 7 of 7 with raw commands up to 0.9 s after).
pwm1 writes keep selecting source 1. The cooler reports the pump duty of the last write, whichever source it selected, and 40% after power-on. Byte 9 of the status report follows the duty the pump runs at. Measured from power-on (PSU switched off) once per driver, with the header at 100%:
before this patch with this patch
source duty rpm source duty rpm
no write yet 0 100 3570 0 100 3570 pwm2 = 40% 1 100 3570 0 100 3570 pwm1 = 40%, the reported duty 1 100 3570 1 40 1710 pwm1 = 60% 1 60 2430 pwm1 = 40% 1 40 1725
So a pwm1 write of the reported duty did not reach the pump, while other duties applied in one write, also when taking the pump from its internal controller (60%: 2460 rpm). When a pwm1 write requests the reported duty, write a duty 1% away first (below at 100%), then the requested one. Sent back to back, the two writes left the pump at the requested duty in all 19 trials, 9 with raw commands and 10 through this driver.
Tested on the RYUJIN III 360 only. The EXTREME, EVA and WHITE EDITION use the same rog_ryujin_iii_info and send the same command, and Edward Blair's analysis of the WHITE EDITION firmware shows the same pump control source. The RYUJIN II, whose duty_channel is 0, is unchanged.
--- Documentation/hwmon/asus_rog_ryujin.rst | 6 +++ drivers/hwmon/asus_rog_ryujin.c | 54 ++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 1 deletion(-)
Documentation/hwmon/asus_rog_ryujin.rst +6 -0
@@ -33,6 +33,12 @@ Usage notes As these are USB HIDs, the driver can be loaded automatically by the kernel and supports hot swapping. +The pump of the RYUJIN III also has a 4-pin cable for a motherboard fan header. +The cooler either hands the pump to its internal controller, which follows the +PWM of the header its 4-pin cable is plugged into, or runs it at the pump duty +set over USB. Writing pwm1 selects the duty set over USB. Writing pwm2 sets +only the internal fan duty and leaves the pump control as it is. + Sysfs entries -------------
drivers/hwmon/asus_rog_ryujin.c +53 -1
100 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 172/507 hwmon: (gpd-fan) Reset both fans to automatic on duo boards
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexei Solcanu <[email protected]>
[ Upstream commit d1f60971fbf85c243ab6c78f6535fbc88fa640ce ]
On boards using gpd_duo_drvdata (GPD Duo, GPD Win 5), writing pwm1_enable=2 only returns the first fan to EC control. The second fan keeps its last manual duty cycle, e.g. full speed after pwm1=255, so a fan control tool that exits leaves it running at that speed.
gpd_duo_write_pwm() writes both fan registers (pwm_write and pwm_write + 1), but switching to automatic only clears pwm_write. Also clear pwm_write + 1, so both fans return to EC control.
Tested on a GPD Win 5 (G1618-05). Not tested on the GPD Duo.
--- drivers/hwmon/gpd-fan.c | 1 + 1 file changed, 1 insertion(+)
drivers/hwmon/gpd-fan.c +1 -0
@@ -444,6 +444,7 @@ static void gpd_duo_set_pwm_enable(struct gpd_fan_data *data, enum FAN_PWM_ENABLbreak ;case AUTOMATIC :gpd_ecram_write (data->drvdata, data->drvdata->pwm_write,0 ); +gpd_ecram_write (data->drvdata, data->drvdata->pwm_write +1 ,0 );break ; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 173/507 hwmon: chipcap2: fix command error diagnostics
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit d0a03e1a2d9bd53b94fe6dff7a1a8058d25be82d ]
The command response field only contains bits 1:0, while the error flags are stored in bits 2:5. The existing diagnostic checks test the extracted response field, so they can never report an error flag.
Test the full status byte for the error flags, and check the configuration-load flag instead of RAM parity for the last diagnostic.
--- drivers/hwmon/chipcap2.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/hwmon/chipcap2.c +4 -4
@@ -167,13 +167,13 @@ static int cc2_cmd_response_diagnostic(struct device *dev, u8 status)case CC2_RESPONSE_BUSY :return -EBUSY ;case CC2_RESPONSE_NACK : -if (resp &CC2_ERR_CORR_EEPROM ) +if (status &CC2_ERR_CORR_EEPROM )dev_dbg (dev,"Command failed: corrected EEPROM\n" ); -if (resp &CC2_ERR_UNCORR_EEPROM ) +if (status &CC2_ERR_UNCORR_EEPROM )dev_dbg (dev,"Command failed: uncorrected EEPROM\n" ); -if (resp &CC2_ERR_RAM_PARITY ) +if (status &CC2_ERR_RAM_PARITY )dev_dbg (dev,"Command failed: RAM parity\n" ); -if (resp &CC2_ERR_RAM_PARITY ) +if (status &CC2_ERR_CONFIG_LOAD )dev_dbg (dev,"Command failed: configuration error\n" );return -ENODATA ;default :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 174/507 hwmon: chipcap2: fix off-by-one in command mode retry loop
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit 4c0e65a4ed665c416ccb1524c58a646a580e491f ]
i == CC2_CM_RETRIES can never be true inside the loop, since it only runs while i < CC2_CM_RETRIES. Use CC2_CM_RETRIES - 1 so the last failed retry breaks out immediately instead of doing a useless disable + 80 ms power-cycle delay before the loop condition ends it anyway.
--- drivers/hwmon/chipcap2.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/chipcap2.c +1 -1
@@ -226,7 +226,7 @@ static int cc2_command_mode_start(struct cc2_data *data) 2 * CC2_RESP_START_CM_US); } ret =cc2_read_command_status (data->client); -if (ret != -ETIMEDOUT || i ==CC2_CM_RETRIES ) +if (ret != -ETIMEDOUT || i ==CC2_CM_RETRIES -1 )break ;/* command window missed, prepare for a retry */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 175/507 hwmon: chipcap2: fix be16 handling
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit 36b07ddfe20b0fe06a8bc32c5e09974876fb5e42 ]
The driver currently only works correctly on little-endian architectures when writing 16-bit register values.
Use i2c_smbus_write_word_swapped() for writes and get_unaligned_be16() for reads to correctly handle the ChipCap 2's big-endian data format on all architectures.
--- drivers/hwmon/chipcap2.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/hwmon/chipcap2.c +5 -5
@@ -21,6 +21,7 @@#include <linux/interrupt.h> #include <linux/irq.h> #include <linux/module.h> +#include <linux/unaligned.h> #include <linux/regulator/consumer.h> #include <linux/mod_devicetable.h> #include <linux/property.h>
@@ -260,8 +261,7 @@ static int cc2_write_reg(struct cc2_data *data, u8 reg, u16 val)if (ret <0 ) goto disable; -cpu_to_be16s (&val); - ret =i2c_smbus_write_word_data (data->client, reg, val); + ret =i2c_smbus_write_word_swapped (data->client, reg, val);if (ret <0 ) goto disable;
@@ -311,7 +311,7 @@ static int cc2_read_reg(struct cc2_data *data, u8 reg, u16 *val)if (ret !=CC2_EEPROM_DATA_LEN )return ret <0 ? ret : -EIO ; - *val =be16_to_cpup ((__be16 *)&buf[1 ]); + *val =get_unaligned_be16 (&buf[1 ]);return cc2_read_command_status (data->client); }
@@ -351,10 +351,10 @@ static int cc2_data_fetch(struct i2c_client *client,switch (type) {case hwmon_humidity: - *val =cc2_rh_convert (be16_to_cpup ((__be16 *)&data[0 ])); + *val =cc2_rh_convert (get_unaligned_be16 (&data[0 ]));break ;case hwmon_temp: - *val =cc2_temp_convert (be16_to_cpup ((__be16 *)&data[2 ])); + *val =cc2_temp_convert (get_unaligned_be16 (&data[2 ]));break ;default :return -EINVAL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 176/507 hwmon: chipcap2: defer probe when IRQs are unavailable
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit b5a1412618f93b594f924cf4f3b4bb6b5dc49d41 ]
This device can work with or without interrupts, but if they are provided and still not available, but if -EPROBE_DEFER is read, its value must be propagated to enable probe retries.
--- drivers/hwmon/chipcap2.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/hwmon/chipcap2.c +6 -0
@@ -636,6 +636,8 @@ static int cc2_request_ready_irq(struct cc2_data *data, struct device *dev)int ret =0 ; data->irq_ready =fwnode_irq_get_byname (dev_fwnode (dev),"ready" ); +if (data->irq_ready == -EPROBE_DEFER ) +return data->irq_ready;if (data->irq_ready >0 ) {init_completion (&data->complete); ret = devm_request_threaded_irq(dev, data->irq_ready, NULL,
@@ -653,6 +655,8 @@ static int cc2_request_alarm_irqs(struct cc2_data *data, struct device *dev)int ret =0 ; data->irq_low =fwnode_irq_get_byname (dev_fwnode (dev),"low" ); +if (data->irq_low == -EPROBE_DEFER ) +return data->irq_low;if (data->irq_low >0 ) { ret = devm_request_threaded_irq(dev, data->irq_low, NULL, cc2_low_interrupt,
@@ -666,6 +670,8 @@ static int cc2_request_alarm_irqs(struct cc2_data *data, struct device *dev) } data->irq_high =fwnode_irq_get_byname (dev_fwnode (dev),"high" ); +if (data->irq_high == -EPROBE_DEFER ) +return data->irq_high;if (data->irq_high >0 ) { ret = devm_request_threaded_irq(dev, data->irq_high, NULL, cc2_high_interrupt,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 177/507 hwmon: chipcap2: fix IRQ teardown ordering
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit d2a66c515d7730fd453485ffb306c412f1f46d72 ]
The threaded IRQs are currently requested before the hwmon device is registered. Since devres releases resources in reverse order, the hwmon device is unregistered before the IRQs are freed during driver teardown. An IRQ may therefore still run after the hwmon device has been released and access the stale data->hwmon pointer.
Separate IRQ discovery from IRQ registration so that the IRQ numbers and alarm visibility flags are initialized before registering the hwmon device while the IRQs are released before the hwmon device during devres cleanup.
--- drivers/hwmon/chipcap2.c | 52 ++++++++++++++++++++++++---------------- 1 file changed, 32 insertions(+), 20 deletions(-)
drivers/hwmon/chipcap2.c +32 -20
@@ -631,32 +631,47 @@ static int cc2_write(struct device *dev, enum hwmon_sensor_types type, u32 attr, } } -static int cc2_request_ready_irq (struct cc2_data *data,struct device *dev) +static int cc2_get_irqs (struct cc2_data *data,struct device *dev) { -int ret =0 ; - data->irq_ready =fwnode_irq_get_byname (dev_fwnode (dev),"ready" );if (data->irq_ready == -EPROBE_DEFER )return data->irq_ready; -if (data->irq_ready >0 ) { +if (data->irq_ready >0 )init_completion (&data->complete); + + data->irq_low =fwnode_irq_get_byname (dev_fwnode (dev),"low" ); +if (data->irq_low == -EPROBE_DEFER ) +return data->irq_low; +if (data->irq_low >0 ) + data->rh_alarm.low_alarm_visible = true; + + data->irq_high =fwnode_irq_get_byname (dev_fwnode (dev),"high" ); +if (data->irq_high == -EPROBE_DEFER ) +return data->irq_high; +if (data->irq_high >0 ) + data->rh_alarm.high_alarm_visible = true; + +return 0 ; +} + +static int cc2_request_data_ready (struct cc2_data *data,struct device *dev) +{ +int ret =0 ; + +if (data->irq_ready >0 ) ret =devm_request_threaded_irq (dev, data->irq_ready,NULL , cc2_ready_interrupt,IRQF_ONESHOT |IRQF_TRIGGER_RISING ,dev_name (dev), data); - }return ret; } -static int cc2_request_alarm_irqs (struct cc2_data *data,struct device *dev) +static int cc2_request_alarms (struct cc2_data *data,struct device *dev) {int ret =0 ; - data->irq_low =fwnode_irq_get_byname (dev_fwnode (dev),"low" ); -if (data->irq_low == -EPROBE_DEFER ) -return data->irq_low;if (data->irq_low >0 ) { ret = devm_request_threaded_irq(dev, data->irq_low, NULL, cc2_low_interrupt,
@@ -665,13 +680,8 @@ static int cc2_request_alarm_irqs(struct cc2_data *data, struct device *dev) dev_name(dev), data);if (ret)return ret; - - data->rh_alarm.low_alarm_visible = true; } - data->irq_high =fwnode_irq_get_byname (dev_fwnode (dev),"high" ); -if (data->irq_high == -EPROBE_DEFER ) -return data->irq_high;if (data->irq_high >0 ) { ret = devm_request_threaded_irq(dev, data->irq_high, NULL, cc2_high_interrupt,
@@ -680,8 +690,6 @@ static int cc2_request_alarm_irqs(struct cc2_data *data, struct device *dev) dev_name(dev), data);if (ret)return ret; - - data->rh_alarm.high_alarm_visible = true; }return ret;
@@ -732,13 +740,13 @@ static int cc2_probe(struct i2c_client *client)device_property_read_string (dev,"label" , &data->label); - ret =cc2_request_ready_irq (data, dev); + ret =cc2_get_irqs (data, dev);if (ret) -return dev_err_probe (dev, ret,"Failed to request ready irq\n" ); +return dev_err_probe (dev, ret,"Failed to get IRQs\n" ); - ret =cc2_request_alarm_irqs (data, dev); + ret =cc2_request_data_ready (data, dev);if (ret) -return dev_err_probe (dev, ret,"Failed to request alarm irqs\n" ); +return dev_err_probe (dev, ret,"Failed to request ready irq\n" ); data->hwmon = devm_hwmon_device_register_with_info(dev, client->name, data, &cc2_chip_info,
@@ -747,6 +755,10 @@ static int cc2_probe(struct i2c_client *client)return dev_err_probe (dev,PTR_ERR (data->hwmon),"Failed to register hwmon device\n" ); + ret =cc2_request_alarms (data, dev); +if (ret) +return dev_err_probe (dev, ret,"Failed to request alarm irqs\n" ); +return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 178/507 hwmon: chipcap2: disable device after hwmon teardown
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit 4724ac5556ce63f01a3f5d61fc7fcc20f4ddef3f ]
cc2_remove() disables the device while the device-managed hwmon device is still registered. A concurrent sysfs callback can then enable the device after it has been disabled during removal.
Register a device-managed disable action before registering the hwmon device, so devres unregisters the hwmon device before disabling the physical device.
--- drivers/hwmon/chipcap2.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-)
drivers/hwmon/chipcap2.c +9 -8
@@ -152,6 +152,11 @@ static void cc2_disable(struct cc2_data *data) } } +static void cc2_disable_action (void *data) +{ +cc2_disable (data); +} +static int cc2_cmd_response_diagnostic (struct device *dev,u8 status) {int resp;
@@ -744,6 +749,10 @@ static int cc2_probe(struct i2c_client *client)if (ret)return dev_err_probe (dev, ret,"Failed to get IRQs\n" ); + ret =devm_add_action_or_reset (dev, cc2_disable_action, data); +if (ret) +return ret; + ret =cc2_request_data_ready (data, dev);if (ret)return dev_err_probe (dev, ret,"Failed to request ready irq\n" );
@@ -762,13 +771,6 @@ static int cc2_probe(struct i2c_client *client)return 0 ; } -static void cc2_remove (struct i2c_client *client) -{ -struct cc2_data *data =i2c_get_clientdata (client); - -cc2_disable (data); -} -static const struct i2c_device_id cc2_id[] = { { .name ="cc2d23" }, { .name ="cc2d23s" },
@@ -801,7 +803,6 @@ static struct i2c_driver cc2_driver = { .of_match_table = cc2_of_match, }, .probe = cc2_probe, - .remove = cc2_remove, .id_table = cc2_id, };module_i2c_driver (cc2_driver);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 179/507 hwmon: chipcap2: enable IRQ processing when regulator is already enabled
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit d1ce827a9cc11ffdfec77b7fec9b73a8020a308d ]
cc2_enable() returns early when the regulator is already enabled. This can happen if a previous regulator_disable() failed or if the regulator was configured as always-on.
In this case, process_irqs remains false, causing the ready interrupt to be ignored. Subsequent operations waiting for the ready completion then time out.
Set process_irqs before returning when the regulator is already enabled, so that the driver continues to process ready interrupts.
--- drivers/hwmon/chipcap2.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/hwmon/chipcap2.c +3 -1
@@ -120,8 +120,10 @@ static int cc2_enable(struct cc2_data *data)int ret;/* exclusive regulator, check in case a disable failed */ -if (regulator_is_enabled (data->regulator)) +if (regulator_is_enabled (data->regulator)) { + data->process_irqs = true;return 0 ; + }/* clear any pending completion */ try_wait_for_completion (&data->complete);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 180/507 hwmon: chipcap2: balance regulator state
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit 378add65fd7d352de9fe440d167fde5bf511b090 ]
The current implementation does not guarantee that the calls to regulator_enable() and regulator_disable() are balanced. regulator_is_enabled() might return a negative value, and an always-on attribute in the DT might break the symmetry anyway.
Add a regulator_enabled flag to keep balance within this regulator consumer.
--- drivers/hwmon/chipcap2.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-)
drivers/hwmon/chipcap2.c +13 -5
@@ -91,6 +91,7 @@ struct cc2_data {int irq_low;int irq_high;bool process_irqs; +bool regulator_enabled; };/* %RH as a per cent mille from a register value */
@@ -120,7 +121,7 @@ static int cc2_enable(struct cc2_data *data)int ret;/* exclusive regulator, check in case a disable failed */ -if (regulator_is_enabled (data->regulator)) { +if (data->regulator_enabled) { data->process_irqs = true;return 0 ; }
@@ -132,6 +133,8 @@ static int cc2_enable(struct cc2_data *data)if (ret <0 )return ret; + data->regulator_enabled = true; +usleep_range (CC2_STARTUP_TIME_US ,CC2_STARTUP_TIME_US +125 ); data->process_irqs = true;
@@ -147,11 +150,16 @@ static void cc2_disable(struct cc2_data *data) data->process_irqs = false;/* exclusive regulator, check in case an enable failed */ -if (regulator_is_enabled (data->regulator)) { - err =regulator_disable (data->regulator); -if (err) -dev_dbg (&data->client->dev,"Failed to disable device" ); +if (!data->regulator_enabled) +return ; + + err =regulator_disable (data->regulator); +if (err) { +dev_dbg (&data->client->dev,"Failed to disable device" ); +return ; } + + data->regulator_enabled = false; }static void cc2_disable_action (void *data)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 181/507 hwmon: chipcap2: do not discard pending alarms on disable
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit 22aecf164e1c0c849808c342c65322d14f45176f ]
cc2_disable() stops processing interrupts before the device is powered down to ignore the alarms caused by voltage toggling. The handler of an alarm raised by the last measurement might not have run at that point, and the alarm is discarded when it finally does.
The sysfs read that triggered the measurement can then report no alarm although the device raised one.
Wait for the alarm handlers that have already been raised before the interrupt processing is stopped. This covers the case where the handler thread has not been scheduled yet; an alarm that has not reached the interrupt core at that point is discarded.
--- drivers/hwmon/chipcap2.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/hwmon/chipcap2.c +7 -0
@@ -146,6 +146,13 @@ static void cc2_disable(struct cc2_data *data) {int err; +/* let the alarms already raised by the last measurement be processed */ +if (data->irq_low >0 ) +synchronize_irq (data->irq_low); + +if (data->irq_high >0 ) +synchronize_irq (data->irq_high); +/* ignore alarms triggered by voltage toggling when powering up */ data->process_irqs = false;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 182/507 hwmon: chipcap2: serialize access to the alarm indicators
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit bed5f0c075eb99442fca6a61c009a32752eceda2 ]
low_alarm and high_alarm are accessed from the threaded interrupt handlers and from sysfs without any locking, which can lead to lost alarms.
Add a mutex to serialize the access to the alarm indicators and to process_irqs, which the handlers use to decide whether an interrupt belongs to an ongoing operation.
--- drivers/hwmon/chipcap2.c | 58 +++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 21 deletions(-)
drivers/hwmon/chipcap2.c +37 -21
@@ -20,6 +20,7 @@#include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/irq.h> +#include <linux/mutex.h> #include <linux/module.h> #include <linux/unaligned.h> #include <linux/regulator/consumer.h>
@@ -91,6 +92,8 @@ struct cc2_data {int irq_low;int irq_high;bool process_irqs; +/* protects process_irqs and the alarm indicators */ +struct mutex irq_lock;bool regulator_enabled; };
@@ -122,7 +125,8 @@ static int cc2_enable(struct cc2_data *data)/* exclusive regulator, check in case a disable failed */ if (data->regulator_enabled) { - data->process_irqs = true; +scoped_guard (mutex, &data->irq_lock) + data->process_irqs = true;return 0 ; }
@@ -137,7 +141,8 @@ static int cc2_enable(struct cc2_data *data)usleep_range (CC2_STARTUP_TIME_US ,CC2_STARTUP_TIME_US +125 ); - data->process_irqs = true; +scoped_guard (mutex, &data->irq_lock) + data->process_irqs = true;return 0 ; }
@@ -154,7 +159,8 @@ static void cc2_disable(struct cc2_data *data)synchronize_irq (data->irq_high);/* ignore alarms triggered by voltage toggling when powering up */ - data->process_irqs = false; +scoped_guard (mutex, &data->irq_lock) + data->process_irqs = false;/* exclusive regulator, check in case an enable failed */ if (!data->regulator_enabled)
@@ -514,10 +520,12 @@ static irqreturn_t cc2_low_interrupt(int irq, void *data) {struct cc2_data *cc2 = data; -if (cc2->process_irqs) { -hwmon_notify_event (cc2->hwmon, hwmon_humidity, - hwmon_humidity_min_alarm,0 ); - cc2->rh_alarm.low_alarm = true; + scoped_guard(mutex, &cc2->irq_lock) { +if (cc2->process_irqs) { +hwmon_notify_event (cc2->hwmon, hwmon_humidity, + hwmon_humidity_min_alarm,0 ); + cc2->rh_alarm.low_alarm = true; + } }return IRQ_HANDLED ;
@@ -527,10 +535,12 @@ static irqreturn_t cc2_high_interrupt(int irq, void *data) {struct cc2_data *cc2 = data; -if (cc2->process_irqs) { -hwmon_notify_event (cc2->hwmon, hwmon_humidity, - hwmon_humidity_max_alarm,0 ); - cc2->rh_alarm.high_alarm = true; + scoped_guard(mutex, &cc2->irq_lock) { +if (cc2->process_irqs) { +hwmon_notify_event (cc2->hwmon, hwmon_humidity, + hwmon_humidity_max_alarm,0 ); + cc2->rh_alarm.high_alarm = true; + } }return IRQ_HANDLED ;
@@ -546,11 +556,13 @@ static int cc2_humidity_min_alarm_status(struct cc2_data *data, long *val)if (ret <0 )return ret; -if (data->rh_alarm.low_alarm) { - *val = (measurement < min_hyst) ?1 :0 ; - data->rh_alarm.low_alarm = *val; - }else { - *val =0 ; + scoped_guard(mutex, &data->irq_lock) { +if (data->rh_alarm.low_alarm) { + *val = (measurement < min_hyst) ?1 :0 ; + data->rh_alarm.low_alarm = *val; + }else { + *val =0 ; + } }return 0 ;
@@ -566,11 +578,13 @@ static int cc2_humidity_max_alarm_status(struct cc2_data *data, long *val)if (ret <0 )return ret; -if (data->rh_alarm.high_alarm) { - *val = (measurement > max_hyst) ?1 :0 ; - data->rh_alarm.high_alarm = *val; - }else { - *val =0 ; + scoped_guard(mutex, &data->irq_lock) { +if (data->rh_alarm.high_alarm) { + *val = (measurement > max_hyst) ?1 :0 ; + data->rh_alarm.high_alarm = *val; + }else { + *val =0 ; + } }return 0 ;
@@ -753,6 +767,8 @@ static int cc2_probe(struct i2c_client *client)i2c_set_clientdata (client, data); +mutex_init (&data->irq_lock); + data->client = client; data->regulator =devm_regulator_get_exclusive (dev,"vdd" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 183/507 hwmon: chipcap2: synchronize ready IRQ state
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit 8c02722be2caa6604a837b81faeaba78250eda4a ]
The ready IRQ handler can race with reinit_completion() in the enable path. In particular, a handler from an earlier operation can complete the completion after it is reset for a new operation.
Use irq_lock to serialize access to the completion and process_irqs. Disable IRQ processing and synchronize any running handler before resetting the completion for a new operation.
--- drivers/hwmon/chipcap2.c | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-)
drivers/hwmon/chipcap2.c +17 -5
@@ -123,6 +123,16 @@ static int cc2_enable(struct cc2_data *data) {int ret; +if (data->irq_ready >0 ) { +scoped_guard (mutex, &data->irq_lock) + data->process_irqs = false; + +synchronize_irq (data->irq_ready); + + scoped_guard(mutex, &data->irq_lock) +reinit_completion (&data->complete); + } +/* exclusive regulator, check in case a disable failed */ if (data->regulator_enabled) {scoped_guard (mutex, &data->irq_lock)
@@ -130,9 +140,6 @@ static int cc2_enable(struct cc2_data *data)return 0 ; } -/* clear any pending completion */ -try_wait_for_completion (&data->complete); - ret =regulator_enable (data->regulator);if (ret <0 )return ret;
@@ -162,6 +169,9 @@ static void cc2_disable(struct cc2_data *data)scoped_guard (mutex, &data->irq_lock) data->process_irqs = false; +if (data->irq_ready >0 ) +synchronize_irq (data->irq_ready); +/* exclusive regulator, check in case an enable failed */ if (!data->regulator_enabled)return ;
@@ -510,8 +520,10 @@ static irqreturn_t cc2_ready_interrupt(int irq, void *data) {struct cc2_data *cc2 = data; -if (cc2->process_irqs) -complete (&cc2->complete); + scoped_guard(mutex, &cc2->irq_lock) { +if (cc2->process_irqs) +complete (&cc2->complete); + }return IRQ_HANDLED ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 184/507 hwmon: (aquacomputer_d5next) Check maxcollection when probing AQUAERO devices
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit b7743c6dbe3ab94045164ef298f65cfb9b0b450a ]
When a USB HID device matching USB_PRODUCT_ID_AQUAERO presents a malformed report descriptor, an out-of-bounds array access occurs in aqc_probe() due to an unchecked index into the parsed collections array. During device initialization, the driver distinguishes between the multiple logical interfaces exposed by the Aquaero device by evaluating the type of the second element in the collection array. The driver unconditionally accesses hdev->collection[1] without verifying that hdev->maxcollection is greater than 1. Because the collection array is dynamically allocated by the HID core based on the number of collections found in the report descriptor, a crafted device exposing fewer than two collections causes an immediate heap out-of-bounds read or NULL pointer dereference. This leads to a kernel panic during the device probe phase.
Add the missing check to fix the problem.
--- drivers/hwmon/aquacomputer_d5next.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/aquacomputer_d5next.c +1 -1
@@ -1570,7 +1570,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)* they present. The two other devices have the type of the second element in * their respective collections set to 1, while the real device has it set to 0. */ -if (hdev->collection[1 ].type !=0 ) { +if (hdev->maxcollection <2 || hdev->collection[1 ].type !=0 ) { ret = -ENODEV ; goto fail_and_close; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 185/507 hwmon: (asus_wmi_sensors) Avoid global struct mutation
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 59d586c9e47d1205563bc9b5a5d443adc3ba5bc5 ]
In the asus_wmi_sensors driver, device-managed memory allocated in asus_wmi_configure_sensor_setup() is assigned to a global static structure, leading to a potential use-after-free when the device is unbound. The driver defines a single global asus_wmi_chip_info structure to register with the hwmon core. During probe, it dynamically allocates the .info channel array using devm_kcalloc() and assigns it directly to this global structure. When a device is unbound, its device-managed memory is automatically freed, leaving asus_wmi_chip_info.info as a dangling pointer. Furthermore, if multiple WMI devices are probed sequentially, each probe overwrites the same global pointer, forcing all registered hwmon instances to reference the channel information of the most recently probed device.
While it is unlikely if not impossible that multiple WMI devices of the same kind exist, modifying a global static data structure is undesirable. Remove the static data structure and allocate it as part of struct asus_wmi_sensors to avoid the potential problem.
--- drivers/hwmon/asus_wmi_sensors.c | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-)
drivers/hwmon/asus_wmi_sensors.c +5 -8
@@ -164,6 +164,7 @@ struct asus_wmi_wmi_info {struct asus_wmi_sensors {struct asus_wmi_wmi_info wmi; +struct hwmon_chip_info chip_info;/* lock access to internal cache */ struct mutex lock; };
@@ -496,11 +497,6 @@ static const struct hwmon_ops asus_wmi_hwmon_ops = { .read_string = asus_wmi_hwmon_read_string, }; -static struct hwmon_chip_info asus_wmi_chip_info = { - .ops = &asus_wmi_hwmon_ops, - .info =NULL , -}; -static int asus_wmi_configure_sensor_setup (struct device *dev,struct asus_wmi_sensors *sensor_data) {
@@ -508,7 +504,7 @@ static int asus_wmi_configure_sensor_setup(struct device *dev,struct hwmon_channel_info *asus_wmi_hwmon_chan;int nr_count[hwmon_max] = {}, nr_types =0 ;struct asus_wmi_sensor_info *temp_sensor; -const struct hwmon_chip_info *chip_info; +struct hwmon_chip_info *chip_info;enum hwmon_sensor_types type;struct device *hwdev;int i, idx;
@@ -549,8 +545,9 @@ static int asus_wmi_configure_sensor_setup(struct device *dev,if (!ptr_asus_wmi_ci)return -ENOMEM ; - asus_wmi_chip_info.info = ptr_asus_wmi_ci; - chip_info = &asus_wmi_chip_info; + chip_info = &sensor_data->chip_info; + chip_info->ops = &asus_wmi_hwmon_ops; + chip_info->info = ptr_asus_wmi_ci; sensor_data->wmi.info_by_id = devm_kcalloc(dev, sensor_data->wmi.sensor_count, sizeof(*sensor_data->wmi.info_by_id),
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 186/507 hwmon: (hp-wmi-sensors) Avoid global struct mutation
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit dc992efeace99e479aec7a8f0c49a9493c729606 ]
In the HP WMI sensors driver, make_chip_info() assigns a device-managed memory allocation to a static global structure, resulting in a use-after-free when the device unbinds.
During hp_wmi_sensors_probe(), make_chip_info() dynamically allocates a hwmon_channel_info array using devm_kcalloc() and assigns it to the static global hp_wmi_chip_info.info pointer.
If multiple instances probe sequentially or concurrently, the shared global pointer is overwritten by each new device. When any device unbinds, its devm-managed memory is automatically freed, leaving the global hp_wmi_chip_info struct and any other active device instances with a dangling pointer. Subsequent accesses by the hwmon core (such as thermal zone reads) will dereference this freed memory, causing a use-after-free.
While this is not supposed to happen in the real world (there should only be one instance of the driver in any system), modifying global structures is undesirable and should be avoided whenever possible. Allocate struct hwmon_chip_info as part of struct hp_wmi_sensors instead and initialize it in make_chip_info() to avoid mutating the global structure.
--- drivers/hwmon/hp-wmi-sensors.c | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-)
drivers/hwmon/hp-wmi-sensors.c +4 -7
@@ -390,6 +390,7 @@ struct hp_wmi_info {*/ struct hp_wmi_sensors {struct wmi_device *wdev; +struct hwmon_chip_info chip_info;struct hp_wmi_info **info_map[hwmon_max];u8 channel_count[hwmon_max];bool has_intrusion;
@@ -1531,11 +1532,6 @@ static const struct hwmon_ops hp_wmi_hwmon_ops = { .write = hp_wmi_hwmon_write, }; -static struct hwmon_chip_info hp_wmi_chip_info = { - .ops = &hp_wmi_hwmon_ops, - .info =NULL , -}; -static struct hp_wmi_info *match_fan_event (struct hp_wmi_sensors *state,const char *event_description) {
@@ -1962,7 +1958,8 @@ static int make_chip_info(struct hp_wmi_sensors *state, bool has_events)if (!ptr_channel_info)return -ENOMEM ; - hp_wmi_chip_info.info = ptr_channel_info; + state->chip_info.ops = &hp_wmi_hwmon_ops; + state->chip_info.info = ptr_channel_info;for (type = hwmon_chip; type < hwmon_max; type++) { count = channel_count[type];
@@ -2053,7 +2050,7 @@ static int hp_wmi_sensors_init(struct hp_wmi_sensors *state)return err; hwdev =devm_hwmon_device_register_with_info (dev,"hp_wmi_sensors" , - state, &hp_wmi_chip_info, + state, &state->chip_info,NULL );return PTR_ERR_OR_ZERO (hwdev); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 187/507 hwmon: (hp-wmi-sensors) Fix unbounded loops in scale_numeric_sensor()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 185039b1c0389b70ec52a6d3e3c1494e2d0e23da ]
In scale_numeric_sensor() in the hp-wmi-sensors hwmon driver, an unbounded loop occurs if the ACPI WMI implementation provides a highly anomalous or malformed UnitModifier value for a numeric sensor.
The UnitModifier property is extracted from a WMI ACPI object without bounds checking and cast to a signed 32-bit integer. This value directly controls the iteration count of two scaling loops. If the provided unit_modifier is extremely negative (e.g., INT_MIN), the first loop executes billions of times before reaching target_modifier. Conversely, if unit_modifier is extremely large (e.g., INT_MAX) and the current sensor reading (val) is exactly 0, the second loop's overflow safeguard (val > LONG_MAX / 10) never evaluates to true, resulting in billions of unnecessary iterations. This prolonged execution causes severe CPU stalls and thread soft lockups during driver initialization or whenever a user-space process reads the sensor attribute via sysfs, resulting in a denial of service on the affected CPU core.
Fix the problem in the first loop by exiting it as soon as val is zero. Fix the problem with the second loop by only entering it if val is not zero. Also add a check for val < LONG_MIN / 10 and exit the loop if that is the case.
--- drivers/hwmon/hp-wmi-sensors.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-)
drivers/hwmon/hp-wmi-sensors.c +12 -6
@@ -739,15 +739,21 @@ static long scale_numeric_sensor(const struct hp_wmi_numeric_sensor *nsensor) val = current_reading; -for (; unit_modifier < target_modifier; unit_modifier++) +for (; val && unit_modifier < target_modifier; unit_modifier++) val =DIV_ROUND_CLOSEST (val,10 ); -for (; unit_modifier > target_modifier; unit_modifier--) { -if (val >LONG_MAX /10 ) { - val =LONG_MAX ; -break ; +if (val) { +for (; unit_modifier > target_modifier; unit_modifier--) { +if (val >LONG_MAX /10 ) { + val =LONG_MAX ; +break ; + } +if (val <LONG_MIN /10 ) { + val =LONG_MIN ; +break ; + } + val *=10 ; } - val *=10 ; }if (sensor_type ==HP_WMI_TYPE_TEMPERATURE ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 188/507 hwmon: (lm87) Fix drvdata type confusion in vrm_show() and vrm_store()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 5b51ff0887b9f88d042b92dd07fcdda4132f0ebc ]
When an LM87 or ADM1024 device is probed with VID support enabled, reading from or writing to the vrm sysfs attribute triggers a driver data type confusion in vrm_show() and vrm_store() in drivers/hwmon/lm87.c.
In lm87_probe(), the driver stores the struct lm87_data pointer on the I2C client via i2c_set_clientdata() and passes the struct i2c_client pointer as the drvdata argument to devm_hwmon_device_register_with_groups(), which attaches the attribute groups to the registered hwmon device with client as its driver_data. Unlike the other sysfs callbacks that retrieve client via dev_get_drvdata() and then obtain data via i2c_get_clientdata(), vrm_show() and vrm_store() assign dev_get_drvdata(dev) directly to struct lm87_data *. Dereferencing data->vrm therefore accesses the struct i2c_client instance at offsetof(struct lm87_data, vrm), causing vrm_show() to leak an unrelated byte from struct i2c_client to userspace and vrm_store() to corrupt a byte within struct i2c_client while failing to update the actual VRM value.
Fix the problem by assigning the return value from dev_get_drvdata(dev) to struct i2c_client *client and using i2c_get_clientdata() to get the actual client data.
--- drivers/hwmon/lm87.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/hwmon/lm87.c +5 -2
@@ -606,13 +606,16 @@ static DEVICE_ATTR_RO(cpu0_vid);static ssize_t vrm_show (struct device *dev,struct device_attribute *attr,char *buf) { -struct lm87_data *data =dev_get_drvdata (dev); +struct i2c_client *client =dev_get_drvdata (dev); +struct lm87_data *data =i2c_get_clientdata (client); +return sprintf (buf,"%d\n" , data->vrm); }static ssize_t vrm_store (struct device *dev,struct device_attribute *attr,const char *buf,size_t count) { -struct lm87_data *data =dev_get_drvdata (dev); +struct i2c_client *client =dev_get_drvdata (dev); +struct lm87_data *data =i2c_get_clientdata (client);unsigned long val;int err;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 189/507 hwmon: (nct6683) Fix incorrect struct cast in show_pwm() and store_pwm()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit c4a01c2a80b203ab5f80885f6994346fe217f19c ]
On big-endian architectures, reading or writing the pwm[1-8] sysfs attributes in the nct6683 hardware monitoring driver always redirects to channel 0 due to an incorrect struct downcast in show_pwm() and store_pwm().
The driver defines the PWM sysfs attributes using SENSOR_TEMPLATE(), which initializes them as struct sensor_device_attribute (where the index is a 32-bit int). However, the sysfs callbacks show_pwm() and store_pwm() incorrectly downcast the attribute to a struct sensor_device_attribute_2 (where the index is an 8-bit u8). Because both structs start with struct device_attribute, container_of() resolves to the same base address. On big-endian architectures, reading the 8-bit index field from the memory layout of a 32-bit int fetches the most significant byte (which is 0), rather than the intended channel number.
This type mismatch causes all PWM reads to return data for channel 0, and any writes intended to configure other channels will silently overwrite the duty cycle of PWM channel 0 instead.
Fix the type casts in show_pwm() and store_pwm() to solve the problem.
--- drivers/hwmon/nct6683.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hwmon/nct6683.c +2 -2
@@ -920,7 +920,7 @@ static ssize_t show_pwm(struct device *dev, struct device_attribute *attr, char *buf) { struct nct6683_data *data = nct6683_update_device(dev); -struct sensor_device_attribute_2 *sattr =to_sensor_dev_attr_2 (attr); +struct sensor_device_attribute *sattr =to_sensor_dev_attr (attr);int index = sattr->index;return sprintf (buf,"%d\n" , data->pwm[index]);
@@ -930,7 +930,7 @@ static ssize_t store_pwm(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr); + struct sensor_device_attribute *sattr = to_sensor_dev_attr(attr);struct nct6683_data *data =dev_get_drvdata (dev);int index = sattr->index;unsigned long val;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 190/507 hwmon: (peci/dimmtemp) Fix devres leak and UAF on concurrent unbind
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 61bc4514b8e99e9733c04de028885f6fc906d628 ]
When a peci_dimmtemp device is unbound concurrently with its delayed initialization work (detect_work), newly allocated devm resources and the hwmon device are leaked, leading to a use-after-free when reading the lingering hwmon sysfs attributes.
In peci_dimmtemp_probe(), detect_work is registered for cancellation via devm_delayed_work_autocancel(). During driver detach, devres_release_all() first moves all existing entries from dev->devres_head onto a local todo list before invoking their release callbacks in reverse order. If create_dimm_temp_info_delayed() is already running when devm_delayed_work_drop() calls cancel_delayed_work_sync(), create_dimm_temp_info() can allocate dimmtemp_label strings via devm_kzalloc()/devm_kasprintf() and register the hwmon device via devm_hwmon_device_register_with_info(), appending new devres entries to the now-empty dev->devres_head. Once the work finishes, devres_release_all() frees priv and priv->name from the local todo list without re-evaluating dev->devres_head, leaving the late devres allocations and registered hwmon device behind with a dangling priv pointer.
Cancel detect_work synchronously in a driver .remove() callback instead of relying on devm_delayed_work_autocancel() so that the work is fully drained before devres_release_all() detaches dev->devres_head, allowing any devm resources registered by the delayed work to be released in proper reverse order. Also only schedule detect_work when check_populated_dimms() returns -EAGAIN so that probe failure paths do not leave delayed work pending.
--- drivers/hwmon/peci/dimmtemp.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-)
drivers/hwmon/peci/dimmtemp.c +14 -7
@@ -4,7 +4,6 @@#include <linux/auxiliary_bus.h> #include <linux/bitfield.h> #include <linux/bitops.h> -#include <linux/devm-helpers.h> #include <linux/hwmon.h> #include <linux/jiffies.h> #include <linux/module.h>
@@ -326,11 +325,13 @@ static int create_dimm_temp_info(struct peci_dimmtemp *priv)if (ret == -ENODEV ) {dev_dbg (priv->dev,"No DIMMs found\n" );return 0 ; - }else if (ret) { + } +if (ret == -EAGAIN ) {schedule_delayed_work (&priv->detect_work,DIMM_MASK_CHECK_DELAY_JIFFIES );dev_dbg (priv->dev,"Deferred populating DIMM temp info\n" ); -return ret; } +if (ret) +return ret; channels = priv->gen_info->chan_rank_max * priv->gen_info->dimm_idx_max;
@@ -398,10 +399,8 @@ static int peci_dimmtemp_probe(struct auxiliary_device *adev, const struct auxil"Unexpected PECI revision %#x, some features may be unavailable\n" , peci_dev->info.peci_revision); - ret =devm_delayed_work_autocancel (priv->dev, &priv->detect_work, - create_dimm_temp_info_delayed); -if (ret) -return ret; +auxiliary_set_drvdata (adev, priv); +INIT_DELAYED_WORK (&priv->detect_work, create_dimm_temp_info_delayed); ret =create_dimm_temp_info (priv);if (ret && ret != -EAGAIN ) {
@@ -412,6 +411,13 @@ static int peci_dimmtemp_probe(struct auxiliary_device *adev, const struct auxilreturn 0 ; } +static void peci_dimmtemp_remove (struct auxiliary_device *adev) +{ +struct peci_dimmtemp *priv =auxiliary_get_drvdata (adev); + +cancel_delayed_work_sync (&priv->detect_work); +} +static int read_thresholds_hsx (struct peci_dimmtemp *priv,int dimm_order,int chan_rank,u32 *data) {
@@ -665,6 +671,7 @@ MODULE_DEVICE_TABLE(auxiliary, peci_dimmtemp_ids);static struct auxiliary_driver peci_dimmtemp_driver = { .probe = peci_dimmtemp_probe, + .remove = peci_dimmtemp_remove, .id_table = peci_dimmtemp_ids, };
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 191/507 hwmon: (pmbus/q54sj108a2) Add missing NULL pointer check
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit a5802c587da97a4ff85c04aad6043fa26640fc9b ]
When CONFIG_DEBUG_FS is enabled and per-client PMBus debugfs directory creation fails during pmbus_do_probe(), q54sj108a2_probe() passes the NULL pointer returned by pmbus_get_debugfs_dir() to debugfs_create_dir() without validation, creating its debugfs directory at the debugfs root instead of under the client directory.
If pmbus_init_debugfs() fails to create the client directory, data->debugfs is left as NULL or an ERR_PTR, which pmbus_get_debugfs_dir() converts to NULL. Passing a NULL parent to debugfs_create_dir() places q54sj108a2_dir in the root of the debugfs filesystem and populates it with attribute files whose private data pointers reference psu->debugfs_entries. Because this root-level directory is outside the client debugfs hierarchy, PMBus core cleanup does not remove it on device unbind, leaking the debugfs entries and causing a use-after-free of the devm-allocated struct q54sj108a2_data if the orphaned files are accessed via q54sj108a2_debugfs_read() or q54sj108a2_debugfs_write() after device removal.
Fix the problem by adding the missing NULL pointer check.
--- drivers/hwmon/pmbus/q54sj108a2.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/hwmon/pmbus/q54sj108a2.c +2 -0
@@ -351,6 +351,8 @@ static int q54sj108a2_probe(struct i2c_client *client) psu->client = client; debugfs =pmbus_get_debugfs_dir (client); +if (!debugfs) +return 0 ; q54sj108a2_dir =debugfs_create_dir (client->name, debugfs);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 192/507 hwmon: (pmbus) Check return value from pmbus_thermal_add_sensor()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 11dfbd835b17b75f7cc7a4a969f33ff702b1b081 ]
During PMBus device probe, if registering a temperature sensor with the thermal subsystem fails, pmbus_add_sensor() silently ignores the error and returns success.
When a valid temperature sensor is detected (class PSC_TEMPERATURE and type "input"), pmbus_add_sensor() invokes pmbus_thermal_add_sensor() to hook it into the kernel's thermal framework. However, the return value of this call is completely discarded. If thermal registration fails, such as from an -ENOMEM allocation failure or an invalid device tree configuration like a malformed #thermal-sensor-cells property, no error is propagated.
Because the hardware monitor probe falsely succeeds despite the failure to register the thermal zone, the system is left without thermal mitigation for the affected PMBus device. This silently blinds the system to actual PMIC temperatures, preventing the execution of necessary cooling mechanisms or emergency shutdowns and risking localized overheating.
Pass the return value from pmbus_thermal_add_sensor() to the calling code to fix the problem. To enable passing the actual error, change the error return from pmbus_add_sensor() from NULL to ERR_PTR() and extract the error from in the calling code.
--- drivers/hwmon/pmbus/pmbus_core.c | 42 ++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 18 deletions(-)
drivers/hwmon/pmbus/pmbus_core.c +24 -18
@@ -1526,10 +1526,11 @@ static struct pmbus_sensor *pmbus_add_sensor(struct pmbus_data *data, {struct sensor_device_attribute *a;struct pmbus_sensor *sensor; +int err; sensor =devm_kzalloc (data->dev,sizeof (*sensor),GFP_KERNEL );if (!sensor) -return NULL ; +return ERR_PTR (-ENOMEM ); a = &sensor->attribute;if (type)
@@ -1554,14 +1555,17 @@ static struct pmbus_sensor *pmbus_add_sensor(struct pmbus_data *data, pmbus_set_sensor, -1);if (pmbus_add_attribute (data, &a->dev_attr.attr)) -return NULL ; +return ERR_PTR (-ENOMEM ); sensor->next = data->sensors; data->sensors = sensor;/* temperature sensors with _input values are registered with thermal */ -if (class ==PSC_TEMPERATURE &&strcmp (type,"input" ) ==0 ) -pmbus_thermal_add_sensor (data, sensor, seq); +if (class ==PSC_TEMPERATURE &&strcmp (type,"input" ) ==0 ) { + err =pmbus_thermal_add_sensor (data, sensor, seq); +if (err) +return ERR_PTR (err); + }return sensor; }
@@ -1662,8 +1666,8 @@ static int pmbus_add_limit_attrs(struct i2c_client *client, page,0xff , l->reg, attr->class, attr->update || l->update, l->readonly, l->writeonly, true); -if (!curr) -return -ENOMEM ; +if (IS_ERR (curr)) +return PTR_ERR (curr);if (l->sbit && (info->func[page] & attr->sfunc)) { ret = pmbus_add_boolean(data, name, l->alarm, index,
@@ -1702,8 +1706,8 @@ static int pmbus_add_sensor_attrs_one(struct i2c_client *client, } base =pmbus_add_sensor (data, name,"input" , index, page, phase, attr->reg, attr->class, true, true, false, true); -if (!base) -return -ENOMEM ; +if (IS_ERR (base)) +return PTR_ERR (base);/* No limit and alarm attributes for phase specific sensors */ if (attr->sfunc && phase ==0xff ) { ret = pmbus_add_limit_attrs(client, data, info, name,
@@ -2376,8 +2380,8 @@ static int pmbus_add_fan_ctrl(struct i2c_client *client,0xff ,PMBUS_VIRT_FAN_TARGET_1 + id,PSC_FAN , false, false, false, true); -if (!sensor) -return -ENOMEM ; +if (IS_ERR (sensor)) +return PTR_ERR (sensor);if (!((data->info->func[page] &PMBUS_HAVE_PWM12 ) || (data->info->func[page] &PMBUS_HAVE_PWM34 )))
@@ -2387,15 +2391,15 @@ static int pmbus_add_fan_ctrl(struct i2c_client *client,0xff ,PMBUS_VIRT_PWM_1 + id,PSC_PWM , false, false, false, true); -if (!sensor) -return -ENOMEM ; +if (IS_ERR (sensor)) +return PTR_ERR (sensor); sensor =pmbus_add_sensor (data,"pwm" ,"enable" , index, page,0xff ,PMBUS_VIRT_PWM_ENABLE_1 + id,PSC_PWM , true, false, false, false); -if (!sensor) -return -ENOMEM ; +if (IS_ERR (sensor)) +return PTR_ERR (sensor);return 0 ; }
@@ -2412,6 +2416,7 @@ static int pmbus_add_fan_attributes(struct i2c_client *client,int f;for (f =0 ; f <ARRAY_SIZE (pmbus_fan_registers); f++) { +struct pmbus_sensor *sensor;int regval;if (!(info->func[page] & pmbus_fan_flags[f]))
@@ -2432,10 +2437,11 @@ static int pmbus_add_fan_attributes(struct i2c_client *client, (!(regval & (PB_FAN_1_INSTALLED >> ((f & 1) * 4))))) continue; -if (pmbus_add_sensor (data,"fan" ,"input" , index, - page,0xff , pmbus_fan_registers[f], -PSC_FAN , true, true, false, true) ==NULL ) -return -ENOMEM ; + sensor =pmbus_add_sensor (data,"fan" ,"input" , index, + page,0xff , pmbus_fan_registers[f], +PSC_FAN , true, true, false, true); +if (IS_ERR (sensor)) +return PTR_ERR (sensor);/* Fan control */ if (pmbus_check_word_register(client, page,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 193/507 hwmon: (pmbus) Release devres allocated memory after devm_thermal_of_zone_register error
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 9aa6cc563e881c3cad96ea36926cadceee151f32 ]
In pmbus_thermal_add_sensor(), a devres memory leak occurs when a PMBus temperature sensor is initialized but no thermal zone is configured for it.
The function allocates a pmbus_thermal_data structure using devm_kzalloc(). It then attempts to register the sensor with the thermal subsystem via devm_thermal_of_zone_register(). If this registration returns -ENODEV (e.g., when no thermal zone is mapped in the Device Tree or CONFIG_THERMAL_OF is disabled), the function intentionally catches the error and returns 0 to allow device probing to continue.
Because devm_kfree() is not called on the -ENODEV path, the unused tdata structure remains allocated on the device's managed resource list. Since most PMBus temperature sensors are not attached to thermal zones, this results in an accumulation of unused objects that needlessly consume kernel memory for the lifetime of the PMBus device.
Add the missing call to devm_kfree() to fix the problem.
--- drivers/hwmon/pmbus/pmbus_core.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/hwmon/pmbus/pmbus_core.c +3 -1
@@ -1510,8 +1510,10 @@ static int pmbus_thermal_add_sensor(struct pmbus_data *pmbus_data,* If CONFIG_THERMAL_OF is disabled, this returns -ENODEV, * so ignore that error but forward any other error. */ -if (IS_ERR (tzd) && (PTR_ERR (tzd) != -ENODEV )) +if (IS_ERR (tzd) && (PTR_ERR (tzd) != -ENODEV )) { +devm_kfree (dev, tdata);return PTR_ERR (tzd); + }return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 194/507 hwmon: (pmbus) Fix return value check from thermal zone registration
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 4fc79634af8cdf734e0a633923ba4817e30d29ad ]
The PMBus core used to call devm_thermal_zone_of_sensor_register() to register thermal zones. Commit 613ed3f676092 ("hwmon: pm_bus: core:
Switch to new of thermal API") changed this to call devm_thermal_of_zone_register() instead. The code subsequently checks if the call failed because the thermal subsystem is not configured. devm_thermal_zone_of_sensor_register() used to return -ENODEV in this case. devm_thermal_of_zone_register() returns -ENOTSUPP. The code currently still checks for -ENOVEV. This results in driver instantiation failures if the thermal subsystem is disabled.
Check for -ENOTSUPP to fix the problem. Keep checking for -ENODEV because this indicates that no thermal zone is configured for the sensor, which is acceptable for the driver and must not cause a registration failure.
--- drivers/hwmon/pmbus/pmbus_core.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/hwmon/pmbus/pmbus_core.c +4 -3
@@ -1507,10 +1507,11 @@ static int pmbus_thermal_add_sensor(struct pmbus_data *pmbus_data, tzd =devm_thermal_of_zone_register (dev, index, tdata, &pmbus_thermal_ops);/* -* If CONFIG_THERMAL_OF is disabled, this returns -ENODEV, -* so ignore that error but forward any other error. +* If CONFIG_THERMAL_OF is disabled, devm_thermal_of_zone_register() +* returns -ENOTSUPP. If no thermal zone is configured for the sensor, +* it returns -ENODEV. Ignore those errors but forward any other error. */ -if (IS_ERR (tzd) && (PTR_ERR (tzd) != -ENODEV )) { +if (IS_ERR (tzd) &&PTR_ERR (tzd) != -ENODEV &&PTR_ERR (tzd) != -ENOTSUPP ) {devm_kfree (dev, tdata);return PTR_ERR (tzd); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 195/507 hwmon: (lm75) Fix setting polarity mask for chips with 16-bit config register
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 3897309ede38d7f3ff34c4c4583b1dd345666988 ]
When probing a 16-bit compatible temperature sensor configured with the "ti,alert-polarity-active-high" device property, lm75_generic_probe() writes to a reserved bit instead of the alert polarity bit due to an incorrect bit shift in the 16-bit polarity mask.
On 16-bit sensors, the polarity bit is physically located at bit 2 of the MSByte. When accessed via i2c_smbus_read_word_data() or i2c_smbus_write_word_data(), the SMBus protocol maps the first received byte (the physical MSByte) to the lower 8 bits of the integer representation. Consequently, the polarity bit is consistently mapped to bit 2, identically to 8-bit sensors. However, the LM75_ALERT_POLARITY_HIGH_16_BIT macro applies an 8-bit left shift, erroneously targeting bit 10. This causes the driver to silently corrupt a reserved bit in the configuration register while leaving the active-high alert polarity unconfigured, breaking the polarity feature.
Use BIT(2) as polarity mask in the configuration register for all chips to fix the problem.
--- drivers/hwmon/lm75.c | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-)
drivers/hwmon/lm75.c +2 -7
@@ -123,8 +123,7 @@ struct lm75_data {static const u8 lm75_sample_set_masks[] = {0 <<5 ,1 <<5 ,2 <<5 ,3 <<5 }; -#define LM75_ALERT_POLARITY_HIGH_8_BIT (BIT(2)) -#define LM75_ALERT_POLARITY_HIGH_16_BIT (BIT(2) << 8) +#define LM75_ALERT_POLARITY_HIGH_BIT BIT(2)#define LM75_SAMPLE_CLEAR_MASK (3 << 5)/* The structure below stores the configuration values of the supported devices.
@@ -770,11 +769,7 @@ static int lm75_generic_probe(struct device *dev, const char *name, data->orig_conf = status;/* Enforce polarity active-low (default) or active-high (devicetree) */ -if (!data->params->config_reg_16bits) - pol_mask =LM75_ALERT_POLARITY_HIGH_8_BIT ; -else - pol_mask =LM75_ALERT_POLARITY_HIGH_16_BIT ; - + pol_mask =LM75_ALERT_POLARITY_HIGH_BIT ; clr_mask = data->params->clr_mask | pol_mask; set_mask = data->params->set_mask & ~pol_mask;if (device_property_read_bool (dev,"ti,alert-polarity-active-high" ))
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 196/507 hwmon: (tmp108) Fix initial conversion delay and wait until ready
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 7cd60538073e465310c94b2a2f0ea8d2f03768ef ]
In tmp108_common_probe(), the driver only adds the 30 ms conversion delay (TMP108_CONVERSION_TIME_MS) to ready_time if the sensor was previously in TMP108_MODE_SHUTDOWN. However, the TMP108 hardware defaults to continuous conversion mode (TMP108_MODE_CONTINUOUS) upon power-on reset, including immediately after enabling the vcc supply regulator during probe, while the temperature register retains its power-on reset value of 0x0000 (0°C) until the first conversion completes. Because the initial mode is not shutdown, the delay is bypassed and early reads via thermal zone registration or sysfs before the first conversion finishes return an uninitialized 0°C reading.
In addition, returning -EAGAIN from tmp108_read() while waiting for a conversion to complete after probe or resume can trigger an unnecessary tight retry loop in callers or fail initial reads.
Unconditionally set ready_time to TMP108_CONVERSION_TIME_MS ahead in tmp108_common_probe(), track ready_time as ktime_t, and wait for the remaining conversion time in tmp108_read() using usleep_range() instead of returning -EAGAIN.
--- drivers/hwmon/tmp108.c | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-)
drivers/hwmon/tmp108.c +11 -15
@@ -13,7 +13,7 @@#include <linux/i2c.h> #include <linux/i3c/device.h> #include <linux/init.h> -#include <linux/jiffies.h> +#include <linux/ktime.h> #include <linux/regmap.h> #include <linux/regulator/consumer.h> #include <linux/slab.h>
@@ -78,7 +78,7 @@struct tmp108 {struct regmap *regmap;u16 orig_config; -u64 ready_time; +ktime_t ready_time;const struct tmp108_params *params; };
@@ -121,6 +121,7 @@ static int tmp108_read(struct device *dev, enum hwmon_sensor_types type,struct tmp108 *tmp108 =dev_get_drvdata (dev);unsigned int regval;int err, hyst; +s64 delay;if (type == hwmon_chip) {if (attr == hwmon_chip_update_interval) {
@@ -137,12 +138,10 @@ static int tmp108_read(struct device *dev, enum hwmon_sensor_types type,switch (attr) {case hwmon_temp_input: -/* Is it too early to return a conversion ? */ -if (time_before64 (get_jiffies_64 (), tmp108->ready_time)) { -dev_dbg (dev,"%s: Conversion not ready yet..\n" , - __func__); -return -EAGAIN ; - } +/* Wait if it is too early to return a conversion */ + delay =ktime_us_delta (tmp108->ready_time,ktime_get ()); +if (delay >0 ) +usleep_range (delay, delay +1000 ); err =regmap_read (tmp108->regmap,TMP108_REG_TEMP , ®val);if (err <0 )return err;
@@ -477,11 +476,8 @@ static int tmp108_common_probe(struct device *dev, struct regmap *regmap, char *return err; } - tmp108->ready_time =get_jiffies_64 (); -if ((tmp108->orig_config &TMP108_CONF_MODE_MASK ) == -TMP108_MODE_SHUTDOWN ) - tmp108->ready_time += -msecs_to_jiffies (TMP108_CONVERSION_TIME_MS ); + tmp108->ready_time =ktime_add_ms (ktime_get (), +TMP108_CONVERSION_TIME_MS ); err =devm_add_action_or_reset (dev, tmp108_restore_config, tmp108);if (err) {
@@ -528,8 +524,8 @@ static int tmp108_resume(struct device *dev) err =regmap_update_bits (tmp108->regmap,TMP108_REG_CONF ,TMP108_CONF_MODE_MASK ,TMP108_MODE_CONTINUOUS ); - tmp108->ready_time =get_jiffies_64 () + -msecs_to_jiffies (TMP108_CONVERSION_TIME_MS ); + tmp108->ready_time =ktime_add_ms (ktime_get (), +TMP108_CONVERSION_TIME_MS );return err; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 197/507 hwmon: (gpio-fan) Update the speed cache before dropping the PM reference
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baek Kyu, Kim <[email protected]>
[ Upstream commit f324179e6ccd05dfdc8e98fba2e9d50aea8e7ea2 ]
set_fan_speed() writes the GPIO control value before dropping the runtime PM reference when stopping the fan. pm_runtime_put_sync() decrements the usage count even when suspending the device fails, but the error return currently leaves speed_index at the previous running speed.
A request for that same running speed then returns success without changing the GPIOs or taking a runtime PM reference. Retrying the stop instead drops a reference the driver no longer owns and can trigger a runtime PM usage count underflow warning.
Update speed_index after writing the GPIOs and before dropping the PM reference. The initial same-speed check already excludes a stopped fan, so a zero target is sufficient to identify the transition that needs a PM put. Preserve the PM error return and the CONFIG_PM=n exception.
This keeps the cached control state and PM reference ownership consistent without restoring running GPIOs after a possibly partial supply failure. It does not clear persistent runtime PM errors or claim that a failing regulator has successfully powered off.
--- drivers/hwmon/gpio-fan.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/hwmon/gpio-fan.c +4 -3
@@ -150,7 +150,10 @@ static int set_fan_speed(struct gpio_fan_data *fan_data, int speed_index)__set_fan_ctrl (fan_data, fan_data->speed[speed_index].ctrl_val); -if (fan_data->speed_index >0 && speed_index ==0 ) { +/* The GPIOs have changed, and a PM put drops the reference on error. */ + fan_data->speed_index = speed_index; + +if (speed_index ==0 ) {int ret; ret =pm_runtime_put_sync (fan_data->dev);
@@ -158,8 +161,6 @@ static int set_fan_speed(struct gpio_fan_data *fan_data, int speed_index)return ret; } - fan_data->speed_index = speed_index; -return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 198/507 hwmon: (coretemp) Check for NULL platform device in hotplug callbacks
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 0f9c7ed3b5009a037e5533eac03a0d4d45ecf1f0 ]
coretemp_get_pdev() returns NULL when topology_logical_die_id(cpu) is negative (such as -ENODEV or -ERANGE from topology_get_logical_id() on a firmware/hardware APIC ID mismatch) or exceeds max_zones (for example, under asymmetric or anomalous ACPI die topologies where topology_max_packages() * topology_max_dies_per_package() is smaller than the logical die count).
Commit 6d03bbff456b ("hwmon: (coretemp) Simplify platform device handling") pre-allocated zone_devices[0 .. max_zones - 1] during module init and dropped the NULL checks on pdev in coretemp_cpu_online() and coretemp_cpu_offline(), passing pdev unconditionally to platform_get_drvdata(). When coretemp_get_pdev() returns NULL, platform_get_drvdata(pdev) dereferences &pdev->dev and triggers a kernel NULL pointer dereference.
Check for a NULL pdev and return 0 in both coretemp_cpu_online() and coretemp_cpu_offline() before calling platform_get_drvdata(). Returning 0 in coretemp_cpu_online() ignores the unmapped CPU without blocking CPU bringup or tearing down valid thermal zones on other dies.
--- drivers/hwmon/coretemp.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/hwmon/coretemp.c +6 -0
@@ -695,6 +695,9 @@ static int coretemp_cpu_online(unsigned int cpu)if (!housekeeping_cpu (cpu,HK_TYPE_MISC ))return 0 ; +if (!pdev) +return 0 ; + pdata =platform_get_drvdata (pdev);if (!pdata->hwmon_dev) {struct device *hwmon;
@@ -746,6 +749,9 @@ static int coretemp_cpu_offline(unsigned int cpu)return 0 ;/* If the physical CPU device does not exist, just return */ +if (!pdev) +return 0 ; + pd =platform_get_drvdata (pdev);if (!pd->hwmon_dev)return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 199/507 hwmon: (coretemp) Set nr_cores only after core_data allocation succeeds
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 95638f1f05ced75a82e83f610cd01b636d2a21b1 ]
In init_temp_data(), pdata->nr_cores is populated from topology_num_cores_per_package() before allocating pdata->core_data. If that allocation fails, init_temp_data() returns NULL with pdata->core_data still NULL and pdata->nr_cores set to a positive value.
coretemp_add_core() logs the error without failing coretemp_cpu_online(), so the CPU still comes online with pdata->hwmon_dev registered. When the CPU is later taken offline (or the module is unloaded), coretemp_cpu_offline() calls get_temp_data(pd, cpu), which loops up to pdata->nr_cores and dereferences the NULL pdata->core_data pointer.
Store the core count in a local variable and assign pdata->nr_cores only after pdata->core_data is allocated, preserving the invariant that pdata->nr_cores is zero whenever pdata->core_data is NULL.
--- drivers/hwmon/coretemp.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/hwmon/coretemp.c +4 -3
@@ -491,11 +491,12 @@ init_temp_data(struct platform_data *pdata, unsigned int cpu, int pkg_flag)struct temp_data *tdata;if (!pdata->core_data) { - pdata->nr_cores =topology_num_cores_per_package (); - pdata->core_data = kzalloc_objs(struct temp_data *, - pdata->nr_cores); +int nr_cores =topology_num_cores_per_package (); + + pdata->core_data = kzalloc_objs(struct temp_data *, nr_cores);if (!pdata->core_data)return NULL ; + pdata->nr_cores = nr_cores; } tdata = kzalloc_obj(struct temp_data);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 200/507 hwmon: (sht4x) Convert update_interval to jiffies in pending data check
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 1a30ea0be623b7443edb6adc79e07632418cefdc ]
In sht4x_read_values(), the check for whether a pending post-heater measurement is still fresh compares get_jiffies_64() against data->heating_complete + data->update_interval. However, data->heating_complete is stored in jiffies whereas data->update_interval is stored in milliseconds.
Whenever HZ != 1000, adding data->update_interval directly without msecs_to_jiffies() mixes incompatible time units. For example, with the default 2000 ms update_interval, the validity window is inflated to 8 seconds at HZ=250 and 20 seconds at HZ=100 instead of 2 seconds. A read within that extended window skips triggering a fresh measurement and instead returns and caches the stale post-heating measurement left in the sensor's output buffer.
Convert data->update_interval to jiffies using msecs_to_jiffies() when computing the pending measurement expiration deadline, matching the next_update calculation right below it.
--- drivers/hwmon/sht4x.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/hwmon/sht4x.c +3 -1
@@ -99,7 +99,9 @@ static int sht4x_read_values(struct sht4x_data *data)msleep (jiffies_to_msecs (data->heating_complete - curr_jiffies));if (data->data_pending && -time_before64 (get_jiffies_64 (), data->heating_complete + data->update_interval)) { +time_before64 (get_jiffies_64 (), + data->heating_complete + +msecs_to_jiffies (data->update_interval))) { data->data_pending = false; }else { next_update = data->last_updated +
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 201/507 hwmon: (aquacomputer_d5next) Avoid truncating scaled sensor readings
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vas Zayarskiy <[email protected]>
[ Upstream commit c221091f7e30c64280e4cbfa27dc4c05edc96d0c ]
High Flow Next power is reported in watts. Multiplying the 16-bit value by one million can overflow both the signed intermediate and the u32 cache. Store power in long, perform the conversion in u64, and clamp to LONG_MAX. The other existing power conversions fit in a signed 32-bit value. Return -ENODATA for unavailable power instead of exposing the stored error as a reading.
The power cache is updated by HID reports without the hwmon read mutex. Read it once with READ_ONCE() and use that snapshot for both the availability check and the returned value. Mark the corresponding updates with WRITE_ONCE() so that the shared accesses are explicit.
Widen the shared current cache to u32. The Aquastream XT conversion to milliamperes can exceed 65535 mA; clamp its negative conversion results to zero before assigning to the unsigned cache. This also permits devices with scaled aggregate currents to store milliamperes directly.
--- drivers/hwmon/aquacomputer_d5next.c | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-)
drivers/hwmon/aquacomputer_d5next.c +18 -11
@@ -19,6 +19,7 @@#include <linux/hwmon.h> #include <linux/jiffies.h> #include <linux/ktime.h> +#include <linux/limits.h> #include <linux/module.h> #include <linux/seq_file.h> #include <linux/unaligned.h>
@@ -612,9 +613,9 @@ struct aqc_data {u32 speed_input_min[1 ];u32 speed_input_target[1 ];u32 speed_input_max[1 ]; -u32 power_input[8 ]; +long power_input[8 ];u16 voltage_input[8 ]; -u16 current_input[8 ]; +u32 current_input[8 ];/* Label values */ const char *const *temp_label;
@@ -989,7 +990,7 @@ static int aqc_legacy_read(struct aqc_data *priv)/* Calculation derived from linear regression */ sensor_value =get_unaligned_le16 (priv->buffer +AQUASTREAMXT_PUMP_CURR_OFFSET ); - priv->current_input[0 ] =DIV_ROUND_CLOSEST (sensor_value *176 ,100 ) -52 ; + priv->current_input[0 ] =max (DIV_ROUND_CLOSEST (sensor_value *176 ,100 ) -52 ,0 ); sensor_value =get_unaligned_le16 (priv->buffer +AQUASTREAMXT_PUMP_VOLTAGE_OFFSET ); priv->voltage_input[0 ] =DIV_ROUND_CLOSEST (sensor_value *1000 ,61 );
@@ -1019,6 +1020,7 @@ static int aqc_legacy_read(struct aqc_data *priv)static int aqc_read (struct device *dev,enum hwmon_sensor_types type,u32 attr,int channel,long *val) { +long power;int ret;struct aqc_data *priv =dev_get_drvdata (dev);
@@ -1083,7 +1085,10 @@ static int aqc_read(struct device *dev, enum hwmon_sensor_types type, u32 attr, }break ;case hwmon_power: - *val = priv->power_input[channel]; + power =READ_ONCE (priv->power_input[channel]); +if (power == -ENODATA ) +return -ENODATA ; + *val = power;break ;case hwmon_pwm:switch (priv->kind) {
@@ -1383,9 +1388,9 @@ static int aqc_raw_event(struct hid_device *hdev, struct hid_report *report, u8 priv->speed_input[i] =get_unaligned_be16 (data + priv->fan_sensor_offsets[i] + priv->fan_structure->speed); - priv->power_input[i] = -get_unaligned_be16 (data + priv->fan_sensor_offsets[i] + - priv->fan_structure->power) *10000 ; +WRITE_ONCE (priv->power_input[i], +get_unaligned_be16 (data + priv->fan_sensor_offsets[i] + + priv->fan_structure->power) *10000 ); priv->voltage_input[i] =get_unaligned_be16 (data + priv->fan_sensor_offsets[i] + priv->fan_structure->voltage) *10 ;
@@ -1425,7 +1430,8 @@ static int aqc_raw_event(struct hid_device *hdev, struct hid_report *report, u8 priv->speed_input[2 ] =get_unaligned_be16 (data +AQUASTREAMULT_PRESSURE_OFFSET ); priv->speed_input[3 ] =get_unaligned_be16 (data +AQUASTREAMULT_FLOW_SENSOR_OFFSET ); - priv->power_input[1 ] =get_unaligned_be16 (data +AQUASTREAMULT_PUMP_POWER ) *10000 ; +WRITE_ONCE (priv->power_input[1 ], +get_unaligned_be16 (data +AQUASTREAMULT_PUMP_POWER ) *10000 ); priv->voltage_input[1 ] =get_unaligned_be16 (data +AQUASTREAMULT_PUMP_VOLTAGE ) *10 ;
@@ -1438,10 +1444,11 @@ static int aqc_raw_event(struct hid_device *hdev, struct hid_report *report, u8case highflownext:/* If external temp sensor is not connected, its power reading is also N/A */ if (priv->temp_input[1 ] == -ENODATA ) - priv->power_input[0 ] = -ENODATA ; +WRITE_ONCE (priv->power_input[0 ], -ENODATA );else - priv->power_input[0 ] = -get_unaligned_be16 (data +HIGHFLOWNEXT_POWER ) *1000000 ; +WRITE_ONCE (priv->power_input[0 ], +min_t (u64,get_unaligned_be16 (data +HIGHFLOWNEXT_POWER ) * +1000000ULL ,LONG_MAX )); priv->voltage_input[0 ] =get_unaligned_be16 (data +HIGHFLOWNEXT_5V_VOLTAGE ) *10 ; priv->voltage_input[1] =
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 202/507 net: qrtr: announce local services again once our HELLO is sent
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joonhoe Kim <[email protected]>
[ Upstream commit 743b5c86276b1c3241e6f0f395b55f98f0756ef0 ]
Since commit 544d85de4dc2 ("net: qrtr: Send HELLO message on endpoint register"), qrtr_node_enqueue() drops every packet but HELLO with -EAGAIN until our HELLO has gone out to the node. When the remote's HELLO arrives first, the NEW_SERVER replies from the name service are dropped, and so are the broadcasts for services registered before our HELLO goes out. Nothing announces these services again, so the remote never learns about them.
On Kaanapali the modem sends its HELLO before it accepts ours. With rmtfs started first, the modem never learns about rmtfs and its watchdog resets the SoC about 40 s later.
Remember that the remote has sent a HELLO. Once our HELLO has been sent to such a node, pass a HELLO from it to the local name service again, so that it announces the services it has at that point. Retry the replay if it cannot be queued, and queue it under ep_lock only while the endpoint is registered, so that it cannot follow the BYE from qrtr_endpoint_unregister().
The flag is not cleared when qrtr_endpoint_hello() restarts the handshake on resume, so a HELLO that the remote sent before then is not lost. The cost is that the remote gets the same NEW_SERVER announcements twice when its HELLO arrives before ours goes out but the name service handles it after, and on every resume.
--- net/qrtr/af_qrtr.c | 53 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 8 deletions(-)
net/qrtr/af_qrtr.c +45 -8
@@ -122,6 +122,7 @@ static DEFINE_XARRAY_ALLOC(qrtr_ports);* @qrtr_tx_flow: xarray of qrtr_tx_flow, keyed by node << 32 | port * @qrtr_tx_lock: lock for qrtr_tx_flow inserts * @hello_sent: hello packet send successful +* @hello_rcvd: remote has sent a hello packet * @rx_queue: receive queue * @item: list item for broadcast list * @say_hello: delayed work for sending hello packet
@@ -136,6 +137,7 @@ struct qrtr_node {struct mutex qrtr_tx_lock;/* for qrtr_tx_flow */ bool hello_sent; +bool hello_rcvd;struct sk_buff_head rx_queue;struct list_head item;
@@ -541,6 +543,11 @@ int qrtr_endpoint_post(struct qrtr_endpoint *ep, const void *data, size_t len)qrtr_node_assign (node,le32_to_cpu (pkt->server.node)); } +if (cb->type ==QRTR_TYPE_HELLO ) { +/* Pairs with smp_load_acquire() in qrtr_hello_work() */ +smp_store_release (&node->hello_rcvd, true); + } +if (cb->type ==QRTR_TYPE_RESUME_TX ) {qrtr_tx_resume (node, skb); }else {
@@ -599,6 +606,8 @@ static void qrtr_hello_work(struct work_struct *work)struct qrtr_node *node;struct qrtr_sock *ctrl;struct sk_buff *skb; +bool hello_sent; +int rc =0 ; node = container_of(to_delayed_work(work), struct qrtr_node, say_hello);
@@ -609,17 +618,45 @@ static void qrtr_hello_work(struct work_struct *work)return ; } - skb =qrtr_alloc_ctrl_packet (&pkt,GFP_KERNEL ); -if (!skb) { -qrtr_port_put (ctrl); -schedule_delayed_work (&node->say_hello,msecs_to_jiffies (100 )); -return ; +mutex_lock (&node->ep_lock); + hello_sent = node->hello_sent; +mutex_unlock (&node->ep_lock); + + from.sq_node = qrtr_local_nid; +if (!hello_sent) { + skb =qrtr_alloc_ctrl_packet (&pkt,GFP_KERNEL ); +if (!skb) + goto retry; + + pkt->cmd =cpu_to_le32 (QRTR_TYPE_HELLO ); + to.sq_node = node->nid; +if (qrtr_node_enqueue (node, skb,QRTR_TYPE_HELLO , &from, &to)) + goto out; } +/* Pairs with smp_store_release() in qrtr_endpoint_post() */ +if (!smp_load_acquire (&node->hello_rcvd)) + goto out; + + skb =qrtr_alloc_ctrl_packet (&pkt,GFP_KERNEL ); +if (!skb) + goto retry; + pkt->cmd =cpu_to_le32 (QRTR_TYPE_HELLO ); - from.sq_node = qrtr_local_nid; - to.sq_node = node->nid; -qrtr_node_enqueue (node, skb,QRTR_TYPE_HELLO , &from, &to); + to.sq_node =READ_ONCE (node->nid); + +mutex_lock (&node->ep_lock); +if (node->ep) + rc =qrtr_local_enqueue (NULL , skb,QRTR_TYPE_HELLO , &to, &from); +else +kfree_skb (skb); +mutex_unlock (&node->ep_lock); +if (!rc) + goto out; + +retry: +schedule_delayed_work (&node->say_hello,msecs_to_jiffies (100 )); +out:qrtr_port_put (ctrl); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 203/507 nvme-rdma: fix NULL queue->ctrl dereference on reconnect
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Aurich Zanettini Martins <[email protected]>
[ Upstream commit 3ee50a2d76f278ea0ced45716a62730059283787 ]
Since commit 2a8513091d2f ("nvme-rdma: parallelize I/O queue allocation and startup"), a reconnect that gets more I/O queues than before grows the tag set before the new queues are set up. queue->ctrl is only set by nvme_rdma_setup_io_queues(), so I/O submitted in between reaches nvme_rdma_queue_rq() on a queue that was never allocated and dereferences a NULL queue->ctrl:
BUG: kernel NULL pointer dereference, address: 000000000000034c RIP: 0010:nvme_rdma_queue_rq+0x52/0xb90
Set queue->ctrl for every queue when allocating the controller. Such requests are then requeued like on any other queue that is not live.
--- drivers/nvme/host/rdma.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/nvme/host/rdma.c +4 -3
@@ -735,7 +735,6 @@ static int nvme_rdma_setup_io_queues(struct nvme_rdma_ctrl *ctrl,for (i =0 ; i < nr_queues; i++) {struct nvme_rdma_queue *queue = &ctrl->queues[first + i]; - queue->ctrl = ctrl; queue->queue_size = queue_size; ctxs[i].queue = queue;
@@ -798,7 +797,6 @@ static int nvme_rdma_configure_admin_queue(struct nvme_rdma_ctrl *ctrl,bool pi_capable = false;int error; - ctrl->queues[0 ].ctrl = ctrl; ctrl->queues[0 ].queue_size =NVME_AQ_DEPTH ; error =nvme_rdma_alloc_queue (&ctrl->queues[0 ]);if (error)
@@ -2284,7 +2282,7 @@ static struct nvme_rdma_ctrl *nvme_rdma_alloc_ctrl(struct device *dev, struct nvmf_ctrl_options *opts) {struct nvme_rdma_ctrl *ctrl; -int ret; +int ret, i; ctrl =kzalloc_obj (*ctrl);if (!ctrl)
@@ -2343,6 +2341,9 @@ static struct nvme_rdma_ctrl *nvme_rdma_alloc_ctrl(struct device *dev,if (!ctrl->queues) goto out_free_ctrl; +for (i =0 ; i < ctrl->ctrl.queue_count; i++) + ctrl->queues[i].ctrl = ctrl; + ret =nvme_init_ctrl (&ctrl->ctrl, dev, &nvme_rdma_ctrl_ops,0 /* no quirks, we're perfect! */ );if (ret)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 204/507 nvme: unregister when pr_register() is given a zero new key
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daejun Park <[email protected]>
[ Upstream commit a9d431124fb2e58215daf0299d6fcf47bbc2d6b1 ]
The block layer PR API defines a zero new_key in pr_register() as unregistering old_key. nvme_pr_register() sends Replace Reservation Key with a zero NRKEY instead. The host stays registered with key 0, and its next registration with another key fails with Reservation Conflict.
The pNFS SCSI layout client unregisters this way at umount. A later mount cannot register and sends all I/O through the metadata server.
Send Unregister Reservation Key when new_key is zero.
--- drivers/nvme/host/pr.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/nvme/host/pr.c +6 -2
@@ -128,8 +128,12 @@ static int nvme_pr_register(struct block_device *bdev, u64 old_key, u64 new_key, data.crkey =cpu_to_le64 (old_key); data.nrkey =cpu_to_le64 (new_key); - cdw10 = old_key ?NVME_PR_REGISTER_ACT_REPLACE : -NVME_PR_REGISTER_ACT_REG ; +if (!new_key) + cdw10 =NVME_PR_REGISTER_ACT_UNREG ; +else if (old_key) + cdw10 =NVME_PR_REGISTER_ACT_REPLACE ; +else + cdw10 =NVME_PR_REGISTER_ACT_REG ; cdw10 |= (flags &PR_FL_IGNORE_KEY ) ?NVME_PR_IGNORE_KEY :0 ; cdw10 |=NVME_PR_CPTPL_PERSIST ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 205/507 nvme: Do not drop the cdev reference twice when cdev_device_add() fails
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuqiang Sun <[email protected]>
[ Upstream commit 7dfe79db5615df8d37ae7de6d3ec099b71bf3e03 ]
Since commit 9952f3882ecb ("nvme: fix cdev lifetime"), nvme_add_ns_cdev() and nvme_add_ns_head_cdev() take a reference to the namespace (or namespace head) before calling nvme_cdev_add(), to be dropped by the char device's release, nvme_cdev_rel(), and drop it themselves when nvme_cdev_add() fails. But when cdev_device_add() fails, nvme_cdev_add() has already put the device, and nvme_cdev_rel() has already dropped that reference: the caller drops it a second time.
With one allocation failure injected into cdev_device_add() for a namespace on an NVMe over loop controller, deleting the controller gives, with native multipath:
BUG: KASAN: slab-use-after-free in nvme_put_ns_head+0x21/0x140 Write of size 4 at addr ff1100000a4ea078 by task init/1 nvme_put_ns_head nvme_put_ns nvme_remove_namespaces nvme_do_delete_ctrl nvme_delete_ctrl_sync nvme_sysfs_delete Freed by task 1: kfree nvme_ns_remove nvme_remove_namespaces refcount_t: underflow; use-after-free.
Take the reference in nvme_cdev_add() instead, right before cdev_device_add(), and let the callers neither take nor drop it. Add nvme_is_ns_cdev() for the check that nvme_cdev_rel() and nvme_cdev_add() now share.
--- drivers/nvme/host/core.c | 18 +++++++++++++++--- drivers/nvme/host/multipath.c | 2 -- 2 files changed, 15 insertions(+), 5 deletions(-)
drivers/nvme/host/core.c +15 -3
@@ -3941,10 +3941,16 @@ static int nvme_subsys_check_duplicate_ids(struct nvme_subsystem *subsys,return 0 ; } +/* The char device of a namespace rather than of a namespace head */ +static bool nvme_is_ns_cdev (struct device *dev) +{ +return dev->parent->class == &nvme_class; +} +static void nvme_cdev_rel (struct device *dev) {ida_free (&nvme_ns_chr_minor_ida,MINOR (dev->devt)); -if (dev->parent->class == &nvme_class) +if (nvme_is_ns_cdev (dev)) nvme_put_ns(container_of(dev, struct nvme_ns, cdev_device));else nvme_put_ns_head(container_of(dev, struct nvme_ns_head,
@@ -3978,6 +3984,14 @@ int nvme_cdev_add(struct cdev *cdev, struct device *cdev_device,device_initialize (cdev_device);cdev_init (cdev, fops); cdev->owner = owner; +/* Undone in nvme_cdev_rel() */ +if (nvme_is_ns_cdev (cdev_device)) + nvme_get_ns(container_of(cdev_device, struct nvme_ns, + cdev_device)); +else +nvme_get_ns_head (container_of (cdev_device, + struct nvme_ns_head, + cdev_device)); ret =cdev_device_add (cdev, cdev_device);if (ret)put_device (cdev_device);
@@ -4010,13 +4024,11 @@ static void nvme_add_ns_cdev(struct nvme_ns *ns) { ns->cdev_device.parent = ns->ctrl->device; -nvme_get_ns (ns);/* Undone in nvme_cdev_rel() */ if (nvme_cdev_add (&ns->cdev, &ns->cdev_device, &nvme_ns_chr_fops, ns->ctrl->ops->module, ns->ctrl->instance, ns->head->instance)) {dev_err (ns->ctrl->device,"Unable to create the ng%dn%d device\n" , ns->ctrl->instance, ns->head->instance); -nvme_put_ns (ns);return ; }set_bit (NVME_NS_CDEV_LIVE , &ns->flags);
drivers/nvme/host/multipath.c +0 -2
@@ -648,14 +648,12 @@ static void nvme_add_ns_head_cdev(struct nvme_ns_head *head) { head->cdev_device.parent = &head->subsys->dev; -nvme_get_ns_head (head);/* Undone in nvme_cdev_rel() */ if (nvme_cdev_add (&head->cdev, &head->cdev_device, &nvme_ns_head_chr_fops,THIS_MODULE , head->subsys->instance, head->instance)) {dev_err (disk_to_dev (head->disk),"Unable to create the ng%dn%d device\n" , head->subsys->instance, head->instance); -nvme_put_ns_head (head);return ; }set_bit (NVME_NSHEAD_CDEV_LIVE , &head->flags);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 206/507 KVM: x86/mmu: Conditionally resched when retrying gPTE walk on A/D update failure
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit b2691b3a6cd230209736c89684dab90d939aa56b ]
Conditionally reschedule when retrying a guest PTE walk because the CMPXCHG to update A/D bits failed, e.g. because a different task/vCPU modified the relevant gPTEs. On kernels without involuntary preemption of some kind, a misbehaving guest can "capture" a pCPU effectively indefinitely and trigger soft lockups by continuously modifying its gPTEs such that the result of the walk is remains valid.
Message-ID: <[email protected]>
--- arch/x86/kvm/mmu/paging_tmpl.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/paging_tmpl.h +10 -1
@@ -339,6 +339,13 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,gpa_t real_gpa;gfn_t gfn; +/* +* KVM might sleep/resched when retrying the walk if the updating A/D +* fails because the gPTE changed between reading the gPTE and trying +* the CMPXHG to set A/D bits. +*/ +might_sleep (); +trace_kvm_mmu_pagetable_walk (addr, access); retry_walk: walker->level = w->cpu_role.base.level;
@@ -479,8 +486,10 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker, addr, write_fault);if (unlikely (ret <0 )) goto error; -else if (ret) +else if (ret) { +cond_resched (); goto retry_walk; + } }return 1 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 207/507 KVM: x86: Conditionally resched when restarting REP string emulation
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit ae85ac25eb671d174811cc3101549448671fd505 ]
When restarting emulation, e.g. of a REP-prefixed string instruction, conditionally reschedule as emulating guest writes can be deceptively slow and expensive, e.g. when shadow paging is in use and each write can trigger write tracking.
In a perfect world, restarting emulation (or not) would be less arbitrary, e.g. would honor not only host events (NEED_RESCHED, signals, etc.) but also guest events (e.g. by checking kvm_vcpu_has_events()). Unfortunately, as pointed out by Sashiko, pio_in_emulated()'s read-ahead logic is baked into the restart logic, as KVM relies on restarting emulation to drain the cache and avoid duplicate reads from the I/O port. I.e. re-entering the guest on kvm_vcpu_has_events() or __xfer_to_guest_mode_work_pending() would introduce architecturally-incorrect, guest-visible changes.
Message-ID: <[email protected]>
--- arch/x86/kvm/x86.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
arch/x86/kvm/x86.c +4 -2
@@ -6515,10 +6515,12 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, }else if (vcpu->arch.complete_userspace_io) { writeback = false; r =0 ; - }else if (r ==EMULATION_RESTART ) + }else if (r ==EMULATION_RESTART ) { +cond_resched (); goto restart; -else + }else { r =1 ; + } writeback:if (writeback) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 208/507 KVM: nVMX: Process each host MSR entry at most once when unwinding failed VM-Entry
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit c33ef9d334059f7cb167569ed7b4779752fe4425 ]
Add a missing "break" in the inner for-loop of the open coded mess that unwinds MSRs back to the pre-VM-Enter state when VMLAUNCH/VMRESUME VM-Fails due to a consistency check that is caught by hardware but missed by KVM. I.e. move on to the next MSR in the VM-Entry load list after performing a write using a value found in the VM-Exit load list. Processing *every* matching entry in the VM-Exit load list makes the processing quadratic, which is problematic if the load lists are full of MSRs that are expensive to emulate. E.g. writing APIC_BASE triggers kvm_recalculate_apic_map() and a whole pile of unnecessary work.
Functionally, arbitrarily restoring the value of the first matching entry is "fine", because none of this is architecturally correct: the load lists are never supposed to have been used in the first place. In practice, it's likely a moot point as no well-behaved VMM will have multiple, diverging entries in the load lists.
Message-ID: <[email protected]>
--- arch/x86/kvm/vmx/nested.c | 1 + 1 file changed, 1 insertion(+)
arch/x86/kvm/vmx/nested.c +1 -0
@@ -5059,6 +5059,7 @@ static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu) __func__, j, h.index, h.value); goto vmabort; } +break ; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 209/507 KVM: x86/mmu: Cap number of parent PTEs per SP at 1000 (the arbitrary rmap limit)
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit e4558c3d7198ed9a0adc3304681f561f4e4d80e1 ]
When potentially reusing a shadow page, zap the shadow page if its number of parent PTEs exceeds KVM's (mostly) arbitrary rmap recycling threshold. Letting the guest create a (mostly) unbounded number of parent PTEs allows the guest to coerce KVM into creating lists containing millions of PTEs, effectively bounded only by the maximum number of shadow pages.
Because PTE lists are simple singly linked lists, removal is O(n). Even worse, if a list is constructed just so, teardown can be O(n^2), e.g. if SPTEs are built such that zapping child SPTEs always zaps the last entry in the list. To cap things off, all paths that walk PTE lists do so while holding mmu_lock, without conditionally rescheduling.
Using a doubly linked list would not address the issue, as removal would remain O(n) since KVM still wouldn't know where in the list to remove from. Removal could be made O(1) by storing a per-SPTE pointer, but that would largely defeat the purpose of reusing SPs, and would penalize well-behaved guests, especially for nested TDP where aliasing page tables is uncommon.
So, cap the maximum number of parent PTEs at the rmap limit. In practice, well-behaved guests will likely never run afoul of the limit. E.g. when running Linux as L1 with TDP, the number of parent PTEs for a single SP tops out at under 200 (though undoubtedly obscure workloads can push it higher). Deliberately use a "greater than or equal" as opposed to rmap's strictly "greater than", as the rmap code checks the threshold immediately *after* inserting into the list, i.e. the limit is 1000 for rmaps, KVM just very briefly blows past it.
Apply the check to both indirect and direct SPs, because while a fully direct MMU naturally limits the number of parent PTEs to '1', direct SPs in indirect MMUs have no such constraint. E.g. if the guest maps a huge PTE into many locations in its page tables, and KVM is backing the hugepage with a direct SP, i.e. with a series of smaller pages, then KVM could end up with a direct SP with many parents.
Note, shadow_mmu_try_split_huge_pages() always restarts the rmap walk or bails entirely if it gets to the point where it tries to grab a SP, i.e. there is *no* pre-existing bug that would be tripped by zapping a SP and thus rmaps when getting a SP.
Message-ID: <[email protected]>
--- arch/x86/kvm/mmu/mmu.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
arch/x86/kvm/mmu/mmu.c +10 -0
@@ -2310,6 +2310,16 @@ static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,continue ; } +/* +* Note! Unlike fully direct MMUs, direct SPs in indirect MMUs +* can have an arbitrary number of parents, e.g if the guest is +* mapping a huge PTE at many points in its page tables. +*/ +if (pte_list_count (&sp->parent_ptes) >=RMAP_RECYCLE_THRESHOLD ) { +kvm_mmu_prepare_zap_page (kvm, sp, &invalid_list); +break ; + } +/* unsync and write-flooding only apply to indirect SPs. */ if (sp->role.direct) goto out;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 210/507 KVM: x86: Unconditionally reset MMU context when emulating INIT
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit c7c288d178cb0b78d3464a616b16b1aa0b316049 ]
Force an MMU reset when emulating an INIT even if paging was already disabled, as the MMU page role includes guest_mode (L2), i.e. an INIT while L2 is running with CR0.PG=0 will result in KVM running L1 with a stale MMU context.
Alternatively, the reset could be scoped strictly to paging being enabled or L2 being active, but SMM is also encoded in the page role. Even though it _should_ be impossible for the vCPU to be INIT'd while SMM is active, there's zero value in not handling SMM. At that point, the only scenario where KVM _doesn't_ need to reset the MMU context is on an INIT with the vCPU running in Real Mode or Unpaged Protect Mode, and while INIT in those modes is somewhat common, it's far from a hot path and re-initializing the MMU is not expensive, especially when the role isn't changing (KVM elides most of the re-configuration in that case).
Note, like the Fixes commit, this bug only affects nested SVM as INIT is an unconditional intercept on VMX, i.e. it's impossible to emulate INIT while L2 is active.
Temporarily keep the guest TLB flush when CR0.PG is being cleared even though it is fully redundant with the flush that is emitted on all INIT events (KVM itself only does RESET when a vCPU is being created, i.e. when CR0.PG must be '0').
Message-ID: <[email protected]>
--- arch/x86/kvm/x86.c | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-)
arch/x86/kvm/x86.c +15 -10
@@ -9663,18 +9663,23 @@ void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)kvm_x86_call (set_efer)(vcpu,0 );kvm_x86_call (update_exception_bitmap)(vcpu); +if (old_cr0 &X86_CR0_PG ) +kvm_make_request (KVM_REQ_TLB_FLUSH_GUEST , vcpu); +/* -* On the standard CR0/CR4/EFER modification paths, there are several -* complex conditions determining whether the MMU has to be reset and/or -* which PCIDs have to be flushed. However, CR0.WP and the paging-related -* bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush -* is needed anyway if CR0.PG was '1' (which can only happen for INIT, as -* CR0 will be '0' prior to RESET). So we only need to check CR0.PG here. +* Unconditionally reset the MMU, even though super strictly speaking, +* a MMU reset is only necessary if and only one of the page role bits +* is changing. All of the CR0/CR4/EFER bits effectively get covered +* by checking CR0.PG=1, as CR0.WP and the paging-related bits in CR4 +* and EFER are irrelevant if CR0.PG was '0'. Subtly, if the vCPU was +* in guest mode (L2) or SMM (although emulating INIT in SMM _should_ +* be impossible), an MMU reset is also necessary as "guest mode" and +* "smm" are both encoded in the shadow page role. As a result, the +* only scenarios where an MMU reset is *not* needed is if the vCPU is +* in Real Mode or Unpaged Protected Mode, and micro-optimizing those +* paths are not worth the risk of running with a stale MMU context. */ -if (old_cr0 &X86_CR0_PG ) { -kvm_make_request (KVM_REQ_TLB_FLUSH_GUEST , vcpu); -kvm_mmu_reset_context (vcpu); - } +kvm_mmu_reset_context (vcpu);/* * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 211/507 ASoC: tas2770: Fix error detection in tas2770_set_dai_tdm_idle
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: James Calligeros <[email protected]>
[ Upstream commit f65f866dacbb10a37e4fae4076627c767afd3cbb ]
snd_soc_component_update_bits returns 1 on a successful update, and we were returning from tas2770_set_dai_tdm_idle early on any nonzero return code. Change this so that only negative return codes are treated as errors.
--- sound/soc/codecs/tas2770.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-)
sound/soc/codecs/tas2770.c +7 -7
@@ -513,7 +513,7 @@ static int tas2770_set_dai_tdm_idle(struct snd_soc_dai *dai, ret =snd_soc_component_update_bits (component,TAS2770_DIN_PD ,TAS2770_DIN_PD_SDOUT ,TAS2770_DIN_PD_SDOUT ); -if (ret) +if (ret <0 )return ret;break ;
@@ -521,12 +521,12 @@ static int tas2770_set_dai_tdm_idle(struct snd_soc_dai *dai, ret =snd_soc_component_update_bits (component,TAS2770_TDM_CFG_REG4 ,TAS2770_TDM_CFG_REG4_TX_KEEPER ,TAS2770_TDM_CFG_REG4_TX_KEEPER ); -if (ret) +if (ret <0 )return ret; ret =snd_soc_component_update_bits (component,TAS2770_TDM_CFG_REG4 ,TAS2770_TDM_CFG_REG4_TX_FILL ,0 ); -if (ret) +if (ret <0 )return ret;break ;
@@ -534,25 +534,25 @@ static int tas2770_set_dai_tdm_idle(struct snd_soc_dai *dai, ret =snd_soc_component_update_bits (component,TAS2770_TDM_CFG_REG4 ,TAS2770_TDM_CFG_REG4_TX_KEEPER ,TAS2770_TDM_CFG_REG4_TX_KEEPER ); -if (ret) +if (ret <0 )return ret; ret =snd_soc_component_update_bits (component,TAS2770_TDM_CFG_REG4 ,TAS2770_TDM_CFG_REG4_TX_FILL ,TAS2770_TDM_CFG_REG4_TX_FILL ); -if (ret) +if (ret <0 )return ret;break ;case SND_SOC_DAI_TDM_IDLE_OFF : ret =snd_soc_component_update_bits (component,TAS2770_DIN_PD ,TAS2770_DIN_PD_SDOUT ,0 ); -if (ret) +if (ret <0 )return ret; ret =snd_soc_component_update_bits (component,TAS2770_TDM_CFG_REG4 ,TAS2770_TDM_CFG_REG4_TX_KEEPER ,0 ); -if (ret) +if (ret <0 )return ret;break ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 212/507 inet: frags: limit the truesize of a reassembly queue
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
[ Upstream commit 3ae20e4697eb969104fe4b1e98a675f0100382b6 ]
The truesize of fragments in a reassembly queue is only bounded by the per netns ipfrag_high_thresh sysctl, which has no upper limit.
inet_frag_reasm_finish() sums the truesize of all fragments in an int. If this sum reaches 2^32, it wraps, and the final sk_wmem_alloc adjustment of the socket owning the reassembled skb can cancel its own reference, leading to a use-after-free of this socket.
This can be triggered from an unprivileged user/network namespace, raising ipfrag_high_thresh and using padded TUN packets, which keep a large truesize after being trimmed by ip_rcv_core().
Track the sum of the truesize of fragments in each queue, and refuse a fragment that would make it bigger than INT_MAX / 2. Callers kill the queue on this error. This bound is far above the needs of legitimate traffic.
--- include/net/inet_frag.h | 9 +++++++++ net/ipv4/inet_fragment.c | 5 +++++ 2 files changed, 14 insertions(+)
include/net/inet_frag.h +9 -0
@@ -79,6 +79,7 @@ struct frag_v6_compare_key {* @tstamp_type: stamp has a mono delivery time (EDT) * @flags: fragment queue flags * @max_size: maximum received fragment size +* @truesize: sum of the truesize of queued fragments * @fqdir: pointer to struct fqdir * @rcu: rcu head for freeing deferall */
@@ -100,6 +101,7 @@ struct inet_frag_queue {u8 tstamp_type;__u8 flags;u16 max_size; +unsigned int truesize;struct fqdir *fqdir;struct rcu_head rcu; };
@@ -172,6 +174,13 @@ extern const u8 ip_frag_ecn_table[16];#define IPFRAG_DUP 1#define IPFRAG_OVERLAP 2#define IPFRAG_MIXED_SECPATH 3 +#define IPFRAG_TOOBIG 4 + +/* Max sum of the truesize of fragments in a queue. This keeps the sums +* done in inet_frag_reasm_prepare() and inet_frag_reasm_finish() well +* below INT_MAX. Legitimate traffic stays far below this limit. +*/ +#define INET_FRAG_MAX_TRUESIZE (INT_MAX / 2)int inet_frag_queue_insert (struct inet_frag_queue *q,struct sk_buff *skb,int offset,int end); void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb,
net/ipv4/inet_fragment.c +5 -0
@@ -336,6 +336,7 @@ void inet_frag_queue_flush(struct inet_frag_queue *q, q->rb_fragments =RB_ROOT ; q->fragments_tail =NULL ; q->last_run_head =NULL ; + q->truesize =0 ; }EXPORT_SYMBOL (inet_frag_queue_flush);
@@ -446,6 +447,9 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb,if (last && !secpath_equal (last, skb))return IPFRAG_MIXED_SECPATH ; +if (skb->truesize >INET_FRAG_MAX_TRUESIZE - q->truesize) +return IPFRAG_TOOBIG ; +/* An IP fragment is never a GSO packet, but an untrusted source * (virtio_net_hdr) may have attached GSO metadata to it. Do not let * that reach the reassembled skb, whose head keeps the first
@@ -510,6 +514,7 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb,if (offset)nf_reset_ct (skb); + q->truesize += skb->truesize;return IPFRAG_OK ; }EXPORT_SYMBOL (inet_frag_queue_insert);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 213/507 ipv6: reject wrapped temporary address preferred lifetimes
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
[ Upstream commit c3e67bd82b9b9b1a5118f09a429ccefe2aab0741 ]
ipv6_create_tempaddr() raises a temporary address's preferred lifetime to regen_advance + age + 1 when the configured lifetime is too short. The result is stored in a u32, while regen_advance and age are unsigned long. If the sum wraps or is truncated, the stored lifetime can still be less than or equal to regen_advance + age.
addrconf_verify_rtnl() then sees the new address as due for regeneration and creates another one. Temporary addresses are not limited by max_addresses since commit 4b08a8f1bd8c ("ipv6: remove max_addresses check from ipv6_create_tempaddr"), so this can cause unbounded address growth. With dad_transmits set to -1, a baseline kernel reached 2859 loopback addresses in two seconds.
After storing the adjusted lifetime, verify that it is still greater than regen_advance + age. Reject the new address if the check fails.
On an x86-64 KASAN kernel, the normal configuration created three IPv6 addresses. The negative dad_transmits, positive multiplication overflow, and large retransmission-time cases each left only the loopback and public addresses. An i386 defconfig and an x86-64 allmodconfig both built addrconf.o with W=1.
--- net/ipv6/addrconf.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/ipv6/addrconf.c +2 -1
@@ -1484,7 +1484,8 @@ static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, bool block) age = (now - tmp_tstamp +ADDRCONF_TIMER_FUZZ_MINUS ) /HZ ;if (cfg.preferred_lft <= regen_advance + age) { cfg.preferred_lft = regen_advance + age +1 ; -if (cfg.preferred_lft > cfg.valid_lft || +if (cfg.preferred_lft <= regen_advance + age || + cfg.preferred_lft > cfg.valid_lft || cfg.preferred_lft > if_public_preferred_lft) {in6_ifa_put (ifp);in6_dev_put (idev);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 214/507 x86/vmware: Fix i386 high-bandwidth hypercall arguments
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zack Rusin <[email protected]>
[ Upstream commit e0e022004bbedc7caf1c18770980eb5372019189 ]
The high-bandwidth hypercall helpers push %ebp before loading the in6 operand into it. On i386 without frame pointers, both GCC and Clang can address the memory-constrained operand relative to %esp. The push then moves the stack and the helpers load the wrong value.
Typical i386 configurations use the frame-pointer unwinder and happen to address the operand through %ebp. However, UNWINDER_GUESS is available with EXPERT and permits the affected frame-pointer-disabled configuration. vmwgfx is also available on i386 and calls both helpers.
Stage in6 through %eax before changing either stack register, then save %ebp and copy the staged value into it. Load the VMware magic immediately before the string I/O instruction. Mark %eax early-clobber so it cannot also provide in6 or an address register for it. Use the same sequence on x86-64, where the full-width register preserves in6.
--- arch/x86/include/asm/vmware.h | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-)
arch/x86/include/asm/vmware.h +14 -10
@@ -276,20 +276,22 @@ unsigned long vmware_hypercall_hb_out(unsigned long cmd, unsigned long in2, asm_inline volatile ( UNWIND_HINT_SAVE + "mov %[in6], %%" _ASM_AX "\n\t" "push %%" _ASM_BP "\n\t" UNWIND_HINT_UNDEFINED - "mov %[in6], %%" _ASM_BP "\n\t" + "mov %%" _ASM_AX ", %%" _ASM_BP "\n\t" + "mov %[magic], %%eax\n\t" "rep outsb\n\t" "pop %%" _ASM_BP "\n\t" UNWIND_HINT_RESTORE - : "=a" (out0), "=b" (*out1) - : "a" (VMWARE_HYPERVISOR_MAGIC), -"b" (cmd), + : "=&a" (out0), "=b" (*out1) + : "b" (cmd),"c" (in2),"d" (in3 |VMWARE_HYPERVISOR_PORT_HB ),"S" (in4), "D" (in5), - [in6] VMW_BP_CONSTRAINT (in6) + [in6] VMW_BP_CONSTRAINT(in6), + [magic] "i" (VMWARE_HYPERVISOR_MAGIC) : "cc", "memory"); return out0; }
@@ -304,20 +306,22 @@ unsigned long vmware_hypercall_hb_in(unsigned long cmd, unsigned long in2, asm_inline volatile ( UNWIND_HINT_SAVE + "mov %[in6], %%" _ASM_AX "\n\t" "push %%" _ASM_BP "\n\t" UNWIND_HINT_UNDEFINED - "mov %[in6], %%" _ASM_BP "\n\t" + "mov %%" _ASM_AX ", %%" _ASM_BP "\n\t" + "mov %[magic], %%eax\n\t" "rep insb\n\t" "pop %%" _ASM_BP "\n\t" UNWIND_HINT_RESTORE - : "=a" (out0), "=b" (*out1) - : "a" (VMWARE_HYPERVISOR_MAGIC), -"b" (cmd), + : "=&a" (out0), "=b" (*out1) + : "b" (cmd),"c" (in2),"d" (in3 |VMWARE_HYPERVISOR_PORT_HB ),"S" (in4), "D" (in5), - [in6] VMW_BP_CONSTRAINT (in6) + [in6] VMW_BP_CONSTRAINT(in6), + [magic] "i" (VMWARE_HYPERVISOR_MAGIC) : "cc", "memory"); return out0; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 215/507 Bluetooth: hci_sync: re-enable legacy advertising on resume
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Valentin Kindschi <[email protected]>
[ Upstream commit 737139f4157d302292a6b937d96922879ecabfa3 ]
hci_resume_advertising_sync() never re-enables advertising on a controller without extended advertising.
It restores HCI_ADVERTISING from advertising_old_state, then calls hci_schedule_adv_instance_sync(), which starts with:
if (hci_dev_test_flag(hdev, HCI_ADVERTISING) && !ext_adv_capable(hdev))
return -EPERM;The flag it tests was set a few lines earlier by the resume itself, so the call returns -EPERM without sending anything. The return value is discarded by every caller, so the failure is silent: advertising_paused is cleared, HCI_ADVERTISING is set, and the controller is not advertising.
Observed on a BCM43455 (no extended advertising) after an active scan:
btmon shows the pause disabling advertising and no re-enable in the ten seconds that follow, the device does not appear in another controller's scan, and btmgmt info still reports "advertising" in current settings.
Enable instance 0x00 directly in that case, the way reenable_adv_sync() already does for the same situation. Instances continue to go through hci_schedule_adv_instance_sync() so the software rotation loop is rearmed.
This affects every caller of hci_resume_advertising_sync(), not only the scan path: address resolution changes, accept list updates, discovery stop, suspend/resume and the end of an LE connection attempt all leave advertising disabled on such a controller today.
The resume does nothing when the controller is already advertising, as it is after directed advertising was started for a peripheral connection, so it does not replace that advertising.
err is initialised because the extended branch leaves it unset when adv_instances is empty and HCI_LE_ADV_0 is clear.
--- net/bluetooth/hci_sync.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
net/bluetooth/hci_sync.c +8 -2
@@ -2687,7 +2687,7 @@ static int hci_pause_advertising_sync(struct hci_dev *hdev)static int hci_resume_advertising_sync (struct hci_dev *hdev) {struct adv_info *adv, *tmp; -int err; +int err =0 ;/* If advertising has not been paused there is nothing to do. */ if (!hdev->advertising_paused)
@@ -2720,13 +2720,19 @@ static int hci_resume_advertising_sync(struct hci_dev *hdev)*/ if (hci_dev_test_and_clear_flag (hdev,HCI_LE_ADV_0 )) err =hci_enable_ext_advertising_sync (hdev,0x00 ); - }else { + }else if (hdev->cur_adv_instance) {/* Schedule for most recent instance to be restarted and begin * the software rotation loop */ err =hci_schedule_adv_instance_sync (hdev, hdev->cur_adv_instance, true); + }else if (hci_dev_test_flag (hdev,HCI_ADVERTISING ) && + !hci_dev_test_flag (hdev,HCI_LE_ADV )) { +/* hci_schedule_adv_instance_sync() rejects instance 0x00 while +* HCI_ADVERTISING is set, so enable it directly. +*/ + err =hci_start_adv_sync (hdev,0x00 ); } hdev->advertising_paused = false;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 216/507 Bluetooth: hci_sync: pause advertising for the scan address update
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Valentin Kindschi <[email protected]>
[ Upstream commit 56ed6b127a27c418dc2daa3fd076539d8fe69c4c ]
hci_active_scan_sync() programs a non-resolvable private address with LE Set Random Address on every active scan start.
BLUETOOTH CORE SPECIFICATION Vol 4, Part E, 7.8.4 says the controller shall return Command Disallowed (0x0C) for that command while legacy advertising or scanning is enabled. hci_pause_addr_resolution(), called just above, only stops advertising when LL privacy is in use, so on a controller without it the command is issued while advertising is still on:
Bluetooth: hci0: Opcode 0x2005 failed: -16
It does not converge either. hdev->random_addr is only set on a successful command complete, so it stays BDADDR_ANY, and the deferral added by commit c2994b008492 ("Bluetooth: hci_sync: Fix not setting Random Address when required") requires it to be set. Unlike the resolvable address a few lines above, which is reused while rpa_valid(), the non-resolvable one is regenerated and rewritten on every call, so a controller that refuses the write is asked again at the scan restart period of about 10 s, for as long as discovery keeps restarting. Observed on a BCM43455, which has no LL privacy and no extended advertising, 190 rejections in one capture, every one retrying the same address:
< LE Set Random Address Address: 02:16:91:90:F1:D4 (Non-Resolvable) > Command Complete LE Set Random Address, Command Disallowed < LE Set Random Address Address: 26:90:57:96:9A:3E (Non-Resolvable) > Command Complete LE Set Random Address, Command Disallowed
Pause advertising for the address update, and resume it once the update is done and before the scan is started. The pause does not outlive the
function: it is taken only when nothing else holds it, and every exit resumes advertising, which also releases the pause taken by hci_pause_addr_resolution(). A failed pause returns before marking anything paused, so the error path is a no-op.
The resume in the error path is no longer guarded by ll_privacy_capable(). That guard matched a pause taken only under LL privacy; the pause added here is unconditional, and hci_resume_advertising_sync() returns early when nothing was paused.
One caveat this widens, raised on the previous posting. When HCI_ADVERTISING is set, hci_pause_advertising_sync() also clears HCI_DISCOVERABLE and HCI_LIMITED_DISCOVERABLE and zeroes discov_timeout, and hci_resume_advertising_sync() restores only HCI_ADVERTISING, so the discoverable state is lost. It reproduces today on an LL privacy controller through hci_pause_addr_resolution(); the unconditional pause makes it reachable without LL privacy as well. hci_suspend_sync() also pauses unconditionally, so a device that suspends loses the same state on any controller today. That asymmetry is pre-existing and is left alone here rather than folded into a scan path fix.
Legacy controllers have one random address register, shared by the scanner and the advertiser. Restoring the advertiser here can reprogram it when the advertiser is non-connectable, so the scan then uses that address rather than the one generated for it. Both are non-resolvable and neither is linkable to the identity address. With privacy enabled both roles already share one resolvable address the same way.
With the patch, on the same hardware:
< LE Set Advertising Enable Enable: 0x00 Success < LE Set Random Address Success < LE Set Advertising Parameters Success < LE Set Advertising Enable Enable: 0x01 Success < LE Set Scan Parameters Success < LE Set Scan Enable Enable: 0x01 Success
The address write is accepted, and advertising is restored before the scan is started.
Over 119369 btmon records and about 12 minutes of the normal workload of that device, alternating active and passive scanning with ten outgoing connection attempts, every LE Set Random Address succeeded and there were no Command Disallowed responses of any opcode, against one per scan restart before.
Patch 1 is required: without it the resume added here returns -EPERM on the controllers this fixes and leaves advertising disabled.
--- net/bluetooth/hci_sync.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-)
net/bluetooth/hci_sync.c +12 -3
@@ -6278,6 +6278,7 @@ static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)u8 filter_policy =0x00 ;/* Default is to enable duplicates filter */ u8 filter_dup =LE_SCAN_FILTER_DUP_ENABLE ; +bool paused;int err;bt_dev_dbg (hdev,"" );
@@ -6301,6 +6302,12 @@ static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)if (err) goto failed; +/* LE Set Random Address is disallowed while advertising is enabled. */ + paused = !hdev->advertising_paused; + err =hci_pause_advertising_sync (hdev); +if (err) + goto failed; +/* All active scans will be done with either a resolvable private * address (when privacy feature has been enabled) or non-resolvable * private address.
@@ -6310,6 +6317,9 @@ static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)if (err <0 ) own_addr_type =ADDR_LE_DEV_PUBLIC ; +if (paused) +hci_resume_advertising_sync (hdev); +if (hci_is_adv_monitoring (hdev) || (hci_test_quirk (hdev,HCI_QUIRK_STRICT_DUPLICATE_FILTER ) && hdev->discovery.result_filtering)) {
@@ -6333,9 +6343,8 @@ static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)return err; failed: -/* Resume advertising if it was paused */ -if (ll_privacy_capable (hdev)) -hci_resume_advertising_sync (hdev); +/* No-op when advertising was not paused. */ +hci_resume_advertising_sync (hdev);/* Resume passive scanning */ hci_update_passive_scan_sync (hdev);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 217/507 Bluetooth: qca: Fix the WCN3950 NVM baud rate offset
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michael McAllister <[email protected]>
[ Upstream commit 5b7d0386a4e75c85479da0fbd9fd66a3e9201375 ]
WCN3950 uses the HCI transport tag layout that stores the UART baud rate at byte 1, like WCN3991. However, QCA_WCN3950 precedes QCA_WCN3991 in qca_btsoc_type, so qca_tlv_check_data() writes the baud rate to byte 2 instead.
On a Motorola Moto G10 with WCN3950 and cmnv12.bin, configuring a 3 Mbps UART therefore leaves the NVM baud rate at its default 3.2 Mbps and overwrites the following byte. Firmware download completes, but the subsequent HCI_RESET times out and Bluetooth initialization fails.
Include WCN3950 in the byte-1 case so the NVM baud rate matches the host UART without altering the following transport parameter.
--- drivers/bluetooth/btqca.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/bluetooth/btqca.c +2 -1
@@ -426,7 +426,8 @@ static int qca_tlv_check_data(struct hci_dev *hdev, tlv_nvm->data[0 ] |=0x80 ;/* UART Baud Rate */ -if (soc_type >=QCA_WCN3991 ) +if (soc_type ==QCA_WCN3950 || + soc_type >=QCA_WCN3991 ) tlv_nvm->data[1 ] = nvm_baud_rate;else tlv_nvm->data[2 ] = nvm_baud_rate;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 218/507 ASoC: qcom: q6apm: Guard callbacks until probe data is ready
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mohit Sharma <[email protected]>
[ Upstream commit ef7062864c0511bba52775d0eb3aa72d886b5f3a ]
The GPR bus needs to make response callbacks available before invoking a client probe because clients can issue synchronous commands from probe. This creates a short interval where a callback can run before the client has published its private data.
Make q6apm publish its driver data only after all callback-visible state has been initialized. Have the q6apm and q6prm callbacks ignore packets received before driver data is available.
--- sound/soc/qcom/qdsp6/q6apm.c | 6 ++++-- sound/soc/qcom/qdsp6/q6prm.c | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-)
sound/soc/qcom/qdsp6/q6apm.c +4 -2
@@ -884,8 +884,6 @@ static int apm_probe(gpr_device_t *gdev)if (!apm)return -ENOMEM ; -dev_set_drvdata (dev, apm); -mutex_init (&apm->lock); apm->dev = dev; apm->gdev = gdev;
@@ -899,6 +897,7 @@ static int apm_probe(gpr_device_t *gdev)idr_init (&apm->modules_idr); +dev_set_drvdata (dev, apm); g_apm = apm;q6apm_get_apm_state (apm);
@@ -942,6 +941,9 @@ static int apm_callback(const struct gpr_resp_pkt *data, void *priv, int op)const struct gpr_hdr *hdr = &data->hdr;int graph_id, is_pos_buf; +if (!apm) +return 0 ; + result = data->payload;switch (hdr->opcode) {
sound/soc/qcom/qdsp6/q6prm.c +3 -0
@@ -192,6 +192,9 @@ static int prm_callback(const struct gpr_resp_pkt *data, void *priv, int op)const struct gpr_ibasic_rsp_result_t *result;const struct gpr_hdr *hdr = &data->hdr; +if (!prm) +return 0 ; +switch (hdr->opcode) {case PRM_CMD_RSP_REQUEST_HW_RSC :case PRM_CMD_RSP_RELEASE_HW_RSC :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 219/507 x86/resctrl: Correct ABMC counter ID field width
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Babu Moger <[email protected]>
[ Upstream commit 84b4b620af7d24916add5d45104023bc5d804f53 ]
AMD's Assignable Bandwidth Monitoring Counters (ABMC) are configured via MSR_IA32_L3_QOS_ABMC_CFG. The cntr_id field selects the counter the configuration applies to. The number of counters a platform supports (the number of possible values written into that field) is enumerated separately via CPUID.
On platforms that enumerate more than 32 counters, the current 5-bit encoding truncates the counter ID and misprograms ABMC.
The section "Assignable Bandwidth Monitoring (ABMC)" in the APM has been updated to widen MSR_IA32_L3_QOS_ABMC_CFG.cntr_id from 5 bits to 12 bits.
The CPUID enumeration reports the maximum counter ID in a 16-bit field and may therefore report more counters than a 12-bit MSR_IA32_L3_QOS_ABMC_CFG.cntr_id can address.
Widen MSR_IA32_L3_QOS_ABMC_CFG.cntr_id to 12 bits to match the architecture. Cap the enumerated counter count at BIT(12) so every counter ID used by resctrl can be written to MSR_IA32_L3_QOS_ABMC_CFG.cntr_id without truncation.
[ bp: Massage and simplify commit message. ]
--- arch/x86/kernel/cpu/resctrl/internal.h | 4 ++-- arch/x86/kernel/cpu/resctrl/monitor.c | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-)
arch/x86/kernel/cpu/resctrl/internal.h +2 -2
@@ -214,8 +214,8 @@ union l3_qos_abmc_cfg { bw_src :12, reserved1: 3, is_clos : 1, - cntr_id : 5, - reserved : 9, + cntr_id :12, + reserved : 2, cntr_en : 1, cfg_en : 1; } split;
arch/x86/kernel/cpu/resctrl/monitor.c +2 -1
@@ -470,7 +470,8 @@ int __init rdt_get_l3_mon_config(struct rdt_resource *r) r->mon.mbm_cntr_assignable = true; r->mon.mbm_cntr_configurable = true;cpuid_count (0x80000020 ,5 , &eax, &ebx, &ecx, &edx); - r->mon.num_mbm_cntrs = (ebx &GENMASK (15 ,0 )) +1 ; +/* cntr_id is 12 bits and can only encode 4096 counters. */ + r->mon.num_mbm_cntrs =min ((ebx &GENMASK (15 ,0 )) +1 ,BIT (12 )); hw_res->mbm_cntr_assign_enabled = true; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 220/507 x86,fs/resctrl: Keep mbm_assign_mode in default mode at boot
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Babu Moger <[email protected]>
[ Upstream commit 7782a6a8dfc05f5622fdf616e5cf3df7d16eaef5 ]
The mbm_event mode assigns hardware MBM counters to RMID/event pairs. It is intended for deployments that need to manage counter assignment on platforms where the number of monitoring groups exceeds the available hardware counters. Hardware counters are scarce on these platforms, so mbm_event mode suits workflows that monitor a subset of groups at a time and rotate assignments as needed.
x86 resctrl enables the mbm_event mode by default on hardware that supports it. This breaks the pqos tool¹, which assumes the historical default mode. It creates 16 or more monitoring groups and uses two counters per group. On a platform with 32 counters per domain, that exhausts the mbm_event counters pool, causing additional groups to read "Unassigned". pqos interprets a non-numeric event read as zero bandwidth and reports 0 MB/s for those groups:
$ sudo pqos -m all:0-4
CORE IPC MISSES LLC[KB] MBL[MB/s] MBR[MB/s]
0 0.69 16k 192.0 0.0 0.0
1 0.40 3k 0.0 0.0 0.0
2 0.44 1k 64.0 0.0 0.0
3 0.39 1k 64.0 0.0 0.0
4 0.43 1k 0.0 0.0 0.0Leave mbm_assign_mode in default mode during initialization as decided in the thread at the Link tag. Default mode uses one counter per monitoring group. On existing AMD platforms, the default active counters pool is 64 and may be larger on newer hardware. The active counters pool is the number of counters that the hardware can actively track in default mode.
Deployments within the active counters pool receive accurate bandwidth measurements in the default mode. Users can create more monitoring groups (for example, 4096 on current hardware) than there are active counters in the pool. Beyond that pool, readings may be misleading or report as "Unavailable", with no user-visible indication.
Default mode is still limited once the number of monitoring groups exceeds that active counters pool. After hardware re-allocates a counter, a read may return "Unavailable". pqos still treats "Unavailable" as zero. Successive reads can be a count, "Unavailable", then another count. pqos treats those jumps as wraparound and can report an inconsistent rate:
$ sudo pqos -m all:0-4 CORE IPC MISSES LLC[KB] MBL[MB/s] MBR[MB/s] 0 0.76 60k 32.0 0.0 0.0 1 0.45 1k 32.0 0.0 0.0 2 1.57 107k 64.0 0.0 17592186044184.9 3 1.62 276k 4928.0 3.2 0.5
Users that need stable measurements beyond the active counters pool should use mbm_event mode and rotate assignments as needed. Enable it with:
# echo mbm_event > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
¹https://github.com/intel/intel-cmt-cat
[ bp: Massage commit message. ]
--- Documentation/filesystems/resctrl.rst | 87 ++++++++++++++++----------- arch/x86/kernel/cpu/resctrl/monitor.c | 1 - 2 files changed, 51 insertions(+), 37 deletions(-)
Documentation/filesystems/resctrl.rst +51 -36
@@ -351,12 +351,12 @@ with the following files: "mbm_assign_mode": The supported counter assignment modes. The enclosed brackets indicate which mode is enabled. The MBM events associated with counters may reset when "mbm_assign_mode" - is changed. + is changed. See architecture specific notes below. :: # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode - [mbm_event] - default + [default] + mbm_event "mbm_event":
@@ -374,20 +374,17 @@ with the following files: Moving to mbm_event counter assignment mode requires users to assign the counters to the events. Otherwise, the MBM event counters will return 'Unassigned' when read. - The mode is beneficial for AMD platforms that support more CTRL_MON - and MON groups than available hardware counters. By default, this - feature is enabled on AMD platforms with the ABMC (Assignable Bandwidth - Monitoring Counters) capability, ensuring counters remain assigned even - when the corresponding RMID is not actively used by any processor. + It is intended for deployments that need to manage counter assignment on + platforms where the number of monitoring groups exceeds the available + hardware counters. Hardware counters are scarce on these platforms, so + mbm_event mode suits workflows that monitor a subset of groups at a time and + rotate assignments as needed. The mbm_event mode ensures counters remain + assigned even when the corresponding RMID is not actively used. "default": In default mode, resctrl assumes there is a hardware counter for each - event within every CTRL_MON and MON group. On AMD platforms, it is - recommended to use the mbm_event mode, if supported, to prevent reset of MBM - events between reads resulting from hardware re-allocating counters. This can - result in misleading values or display "Unavailable" if no counter is assigned - to the event. + event within every CTRL_MON and MON group. * To enable "mbm_event" counter assignment mode: ::
@@ -399,6 +396,24 @@ with the following files: # echo "default" > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode + In default mode on AMD platforms that support more CTRL_MON and MON groups + than hardware counters, hardware dynamically shares a smaller pool of + counters among RMIDs. One counter from this pool is used per monitoring + group and counts every MBM event of that group's RMID. The size of the pool + is not enumerated to software (unlike "num_mbm_cntrs"), and "num_rmids" may + be much larger. For example, 64 counters in this pool monitor 64 groups. + Newer hardware may provide a larger pool. + + On such platforms, while the number of monitoring groups does not exceed + that pool, a counter stays attached to each RMID and readings remain + accurate. Creating more groups than the pool can cause hardware to + re-allocate those counters between successive reads of an event. Bandwidth + values may then be misleading, or a read may return "Unavailable" if no + counter is allocated to the RMID. There is no user-visible indication when + this begins. Users who need stable readings beyond that pool should switch + to mbm_event mode, if supported, and assign counters to the groups of + interest (rotating assignments as needed). + "num_mbm_cntrs": The maximum number of counters (total of available and assigned counters) in each domain when the system supports mbm_event mode.
@@ -1783,17 +1798,19 @@ View the llc occupancy snapshot:: Examples on working with mbm_assign_mode ======================================== -a. Check if MBM counter assignment mode is supported. +a. Check if MBM counter assignment mode is supported. Enable "mbm_event" +mode. Switching the mbm_assign_mode may reset all the MBM counters (and +thus all MBM events) of all the resctrl groups. :: - # mount -t resctrl resctrl /sys/fs/resctrl/ - + # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode + [default] + mbm_event + # echo "mbm_event" > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode [mbm_event] default -The "mbm_event" mode is detected and enabled. - b. Check how many assignable counters are supported. ::
@@ -1804,36 +1821,39 @@ c. Check how many assignable counters are available for assignment in each domai :: # cat /sys/fs/resctrl/info/L3_MON/available_mbm_cntrs - 0=30;1=30 + 0=32;1=32 -d. To list the default group's assign states. +d. To list the default group's assign states. Counters are unassigned when the mode +is switched to "mbm_event". :: # cat /sys/fs/resctrl/mbm_L3_assignments - mbm_total_bytes:0=e;1=e - mbm_local_bytes:0=e;1=e + mbm_total_bytes:0=_;1=_ + mbm_local_bytes:0=_;1=_ -e. To unassign the counter associated with the mbm_total_bytes event on domain 0. +e. To assign the counter associated with the mbm_total_bytes event on domain 0 +in exclusive mode. :: - # echo "mbm_total_bytes:0=_" > /sys/fs/resctrl/mbm_L3_assignments + # echo "mbm_total_bytes:0=e" > /sys/fs/resctrl/mbm_L3_assignments # cat /sys/fs/resctrl/mbm_L3_assignments - mbm_total_bytes:0=_;1=e - mbm_local_bytes:0=e;1=e + mbm_total_bytes:0=e;1=_ + mbm_local_bytes:0=_;1=_ f. To unassign the counter associated with the mbm_total_bytes event on all domains. :: # echo "mbm_total_bytes:*=_" > /sys/fs/resctrl/mbm_L3_assignments - # cat /sys/fs/resctrl/mbm_L3_assignment + # cat /sys/fs/resctrl/mbm_L3_assignments mbm_total_bytes:0=_;1=_ - mbm_local_bytes:0=e;1=e + mbm_local_bytes:0=_;1=_ -g. To assign a counter associated with the mbm_total_bytes event on all domains in -exclusive mode. +g. To assign a counter associated with the mbm_total_bytes and mbm_local_bytes +events on all domains in exclusive mode. :: # echo "mbm_total_bytes:*=e" > /sys/fs/resctrl/mbm_L3_assignments + # echo "mbm_local_bytes:*=e" > /sys/fs/resctrl/mbm_L3_assignments # cat /sys/fs/resctrl/mbm_L3_assignments mbm_total_bytes:0=e;1=e mbm_local_bytes:0=e;1=e
@@ -1890,13 +1910,8 @@ the MBM counters (and thus all MBM events) of all the resctrl groups. # echo "default" > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode - mbm_event [default] - -m. Unmount the resctrl filesystem. -:: - - # umount /sys/fs/resctrl/ + mbm_event Intel RDT Errata ================
arch/x86/kernel/cpu/resctrl/monitor.c +0 -1
@@ -472,7 +472,6 @@ int __init rdt_get_l3_mon_config(struct rdt_resource *r)cpuid_count (0x80000020 ,5 , &eax, &ebx, &ecx, &edx);/* cntr_id is 12 bits and can only encode 4096 counters. */ r->mon.num_mbm_cntrs =min ((ebx &GENMASK (15 ,0 )) +1 ,BIT (12 )); - hw_res->mbm_cntr_assign_enabled = true; } r->mon_capable = true;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 221/507 mm/khugepaged: flush deferred unmaps before dropping a failed folio
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
[ Upstream commit 854e5ff8b3ce2a776586cabebaeae645c992345b ]
collapse_file() can fail its reference-count or dirty-folio check after unmapping with TTU_BATCH_FLUSH. Both paths put back the isolated folio, then unlock it and drop the lookup reference before reaching the common try_to_unmap_flush().
The page-cache reference does not keep the folio stable once the lock is released. Another collapse can replace and free it. With its PTEs already gone, that collapse cannot flush the first task's per-task TLB batch, and retract_page_tables() skips short or unaligned VMAs. A CPU can therefore retain a user translation to the freed folio. This has been reproduced with unprivileged MADV_COLLAPSE on a memfd.
Flush at out_unlock while the lookup reference and folio lock are still held. The common flush continues to cover the accumulated pagelist on both success and rollback, preserving batching on successful collapses.
--- mm/khugepaged.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
mm/khugepaged.c +7 -3
@@ -2488,6 +2488,11 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr, index +=folio_nr_pages (folio);continue ; out_unlock: +/* +* The folio may have been unmapped with TTU_BATCH_FLUSH. +* Flush before releasing the lock and our last reference. +*/ +try_to_unmap_flush ();folio_unlock (folio);folio_put (folio); goto xa_unlocked;
@@ -2498,9 +2503,8 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr, xa_unlocked:/* -* If collapse is successful, flush must be done now before copying. -* If collapse is unsuccessful, does flush actually need to be done? -* Do it anyway, to clear the state. +* Flush before copying the folios, or releasing them in rollback. +* This is a no-op if out_unlock already flushed the batch. */ try_to_unmap_flush ();
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 222/507 mm: fix address wraparound when scanning large folio PTEs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit f681d4580d5c3c749f623cda722a21aefd3147b3 ]
numa_rebuild_large_mapping() and do_swap_page() can be tricked into generating an address wraparound, crashing the kernel. All that's required is to map a tail page of a large folio close enough to the start/end of the address space to e.g., make
unsigned long addr_start = addr - (nr << PAGE_SHIFT);
to wrap around.
Let's fix it by providing a better helper, folio_scan_range(), that takes care of staying within VMA and page table boundaries while handling possible wraparounds.
There are some nasty details, like not being able to use pmd_addr_end() in this context. Add some helpful comments for these cases.
--- mm/memory.c | 50 ++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 14 deletions(-)
mm/memory.c +36 -14
@@ -4868,6 +4868,34 @@ static void check_swap_exclusive(struct folio *folio, swp_entry_t entry, }while (--nr_pages); } +/* +* Get the address range in which a folio might be mapped, assuming its pages +* are mapped consecutively and the folio page at the given idx is mapped at +* the given address. +*/ +static void folio_pte_range (const struct folio *folio, +const struct vm_area_struct *vma,unsigned long addr, +unsigned long idx,unsigned long *start,unsigned long *end) +{ +/* Stay within the page table and VMA boundaries. */ +const unsigned long pmd_start = addr &PMD_MASK ; +const unsigned long pmd_end = pmd_start +PMD_SIZE ; +const unsigned long lower =max (pmd_start, vma->vm_start); +/* +* We cannot use pmd_addr_end(), as it does not clamp reliably. To +* avoid wraparounds, compute using the inclusive end. +*/ +const unsigned long upper =min (pmd_end -1 , vma->vm_end -1 ) +1 ; +const unsigned long offset = idx <<PAGE_SHIFT ; + +/* +* Avoid start/end addresses wrapping by not adding/subtracting more +* than the lower/upper limits would allow. +*/ + *start = addr -min (addr - lower, offset); + *end = addr +min (upper - addr,folio_size (folio) - offset); +} +/* * We enter with either the VMA lock or the mmap_lock held (see * FAULT_FLAG_VMA_LOCK), and pte mapped but not yet locked.
@@ -5050,16 +5078,15 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) address = vmf->address; ptep = vmf->pte;if (folio_test_large (folio) &&folio_test_swapcache (folio)) { -int nr =folio_nr_pages (folio); -unsigned long idx =folio_page_idx (folio, page); -unsigned long folio_start = address - idx *PAGE_SIZE ; -unsigned long folio_end = folio_start + nr *PAGE_SIZE ; +const int nr =folio_nr_pages (folio); +const unsigned long idx =folio_page_idx (folio, page); +unsigned long folio_start, folio_end;pte_t *folio_ptep;pte_t folio_pte; -if (unlikely (folio_start <max (address &PMD_MASK , vma->vm_start))) - goto check_folio; -if (unlikely (folio_end >pmd_addr_end (address, vma->vm_end))) +folio_pte_range (folio, vma, address, idx, &folio_start, + &folio_end); +if (unlikely ((folio_end - folio_start) >>PAGE_SHIFT != nr)) goto check_folio; folio_ptep = vmf->pte - idx;
@@ -6209,16 +6236,11 @@ static void numa_rebuild_large_mapping(struct vm_fault *vmf, struct vm_area_stru struct folio *folio, pte_t fault_pte, bool ignore_writable, bool pte_write_upgrade) { - int nr = pte_pfn(fault_pte) - folio_pfn(folio); + const unsigned long idx = pte_pfn(fault_pte) - folio_pfn(folio);unsigned long start, end, addr = vmf->address; -unsigned long addr_start = addr - (nr <<PAGE_SHIFT ); -unsigned long pt_start =ALIGN_DOWN (addr,PMD_SIZE );pte_t *start_ptep; -/* Stay within the VMA and within the page table. */ - start =max3 (addr_start, pt_start, vma->vm_start); - end =min3 (addr_start +folio_size (folio), pt_start +PMD_SIZE , - vma->vm_end); +folio_pte_range (folio, vma, addr, idx, &start, &end); start_ptep = vmf->pte - ((addr - start) >>PAGE_SHIFT );/* Restore all PTEs' mapping of the large folio */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 223/507 mm: memory: fix truncation removing mapped folios
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baolin Wang <[email protected]>
[ Upstream commit 243cf1f67b365668389832463fc31cbb9fec47af ]
Ayush reported an issue that shmem/tmpfs folios are still mapped when truncating them on production:
"
BUG: Bad page cache in process ... pfn:... page dumped because: still mapped when deleted
"
I reproduced the issue with Ayush's reproducer [1] with the latest mm-unstable branch, and I got the following crash info. From the dump message, we can see that truncate_inode_folio() is really trying to remove mapped folios, which is incorrect.
"
[ 189.171977] page: refcount:3 mapcount:1 mapping:00000000fe168ee1 index:0x3880 pfn:0x191647 [ 189.171995] memcg:ffff0000cc073d40 [ 189.171997] aops:shmem_aops ino:3c01 dentry name(?):"memfd:runsc-memory" [ 189.172006] flags: 0x17fffef0002022d(locked|referenced|uptodate|lru| workingset|swapbacked|node=0|zone=2|lastcpupid=0x3ffff) ....... [ 189.172017] page dumped because: VM_BUG_ON_FOLIO(folio_mapped(folio)) [ 189.172026] ------------[ cut here ]------------ [ 189.172027] kernel BUG at mm/filemap.c:155! [ 189.172057] Internal error: Oops - BUG: 00000000f2000800 [#1] SMP ....... [ 189.177721] CPU: 3 UID: 0 PID: 5521 Comm: repro Kdump: loaded Tainted: 7.3.0-rc4+ #277 PREEMPT(lazy) ....... [ 189.183986] Call trace: [ 189.184124] filemap_unaccount_folio+0xf0/0x1e8 (P) [ 189.184391] __filemap_remove_folio+0x34/0x160 [ 189.184633] filemap_remove_folio+0x4c/0xb0 [ 189.184859] truncate_inode_folio+0x34/0x58 [ 189.185087] shmem_undo_range+0x220/0x658 [ 189.185308] shmem_fallocate+0x2f0/0x470 [ 189.185527] vfs_fallocate+0x128/0x328 ...... [ 189.187078] el0t_64_sync+0x184/0x188
"
After analysis, I believe the race exists between truncation and MADV_DONTNEED, and shmem's ->map_pages() merely makes the issue easier to reproduce. Since MADV_DONTNEED synchronously releases the pagetable page before calling tlb_flush_rmaps(), this could cause another thread's truncation to skip zap_pte_range() (due to pmd is none) but still observe the folio's mapcount as non-zero. A possible race scenario is as follows:
CPU 0 CPU 1shmem_fallocate madvise_dontneed_single_vma
unmap_mapping_range .......
......
(filemap_map_pages() remap folios)
zap_pte_range
truncate_inode_folio zap_empty_pte_table(pmd clear)
unmap_mapping_folio
......
zap_pmd_range (saw pmd none, skip)
filemap_remove_folio
BUG_ON(folio_mapped)
tlb_flush_rmaps(remove rmaps)
To fix this issue, we should move the pmd clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps() and use sync_with_folio_pmd_zap() to sync with concurrent zapping, so that when we find a pmd_none() while unmapping a folio without holding the PTL, the folio's mappings are guaranteed to have been removed via tlb_flush_rmaps().
Meanwhile move the second pmd_none() check to where it belongs: if splitting zapped the PMD.
--- mm/internal.h | 10 ++++++---- mm/memory.c | 35 ++++++++++++++++++++--------------- 2 files changed, 26 insertions(+), 19 deletions(-)
mm/internal.h +6 -4
@@ -584,14 +584,16 @@ void free_pgtables(struct mmu_gather *tlb, struct unmap_desc *desc);void pmd_install (struct mm_struct *mm,pmd_t *pmd,pgtable_t *pte);/** -* sync_with_folio_pmd_zap - sync with concurrent zapping of a folio PMD +* sync_with_folio_pmd_zap - sync with concurrent zapping of folios * @mm: The mm_struct. * @pmdp: Pointer to the pmd that was found to be pmd_none(). * * When we find a pmd_none() while unmapping a folio without holding the PTL, -* zap_huge_pmd() may have cleared the PMD but not yet modified the folio to -* indicate that it's unmapped. Skipping the PMD without synchronization could -* make folio unmapping code assume that unmapping failed. +* zap_huge_pmd() may have cleared the PMD but not yet updated the folio +* mapcount, and zap_empty_pte_table() clears the PMD only after the rmaps +* for the table have been removed, but nothing orders the pmd_none() read +* against later mapcount reads. Skipping the PMD without synchronization +* could make folio unmapping code assume that unmapping failed. * * Wait for concurrent zapping to complete by grabbing the PTL. */
mm/memory.c +20 -15
@@ -2071,6 +2071,15 @@ static unsigned long zap_pte_range(struct mmu_gather *tlb, } }while (pte += nr, addr +=PAGE_SIZE * nr, addr != end); +add_mm_rss_vec (mm, rss); +lazy_mmu_mode_disable (); + +/* Do the actual TLB flush before dropping ptl */ +if (force_flush) { +tlb_flush_mmu_tlbonly (tlb); +tlb_flush_rmaps (tlb, vma); + } +/* * Fast path: try to hold the pmd lock and unmap the PTE page. *
@@ -2078,18 +2087,12 @@ static unsigned long zap_pte_range(struct mmu_gather *tlb,* to hold the pmd lock failed, then we need to recheck all pte entries * to ensure they are still none, thereby preventing the pte entries * from being repopulated by another thread. +* +* Clear the PMD after the rmaps for the table have been removed, in case +* an incorrect mapcount is observed after unmapping the folio. */ if (can_reclaim_pt && direct_reclaim && addr == end) direct_reclaim =zap_empty_pte_table (mm, pmd, ptl, &pmdval); - -add_mm_rss_vec (mm, rss); -lazy_mmu_mode_disable (); - -/* Do the actual TLB flush before dropping ptl */ -if (force_flush) { -tlb_flush_mmu_tlbonly (tlb); -tlb_flush_rmaps (tlb, vma); - }pte_unmap_unlock (start_pte, ptl);/*
@@ -2136,13 +2139,15 @@ static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, addr = next;continue ; } +/* We already synchronized with concurrent zapping. */ +if (pmd_none (*pmd)) { + addr = next; +continue ; + }/* fall through */ - }else if (details && details->single_folio && -folio_test_pmd_mappable (details->single_folio) && - next - addr ==HPAGE_PMD_SIZE &&pmd_none (*pmd)) { -sync_with_folio_pmd_zap (tlb->mm, pmd); - } -if (pmd_none (*pmd)) { + }else if (pmd_none (*pmd)) { +if (details && details->single_folio) +sync_with_folio_pmd_zap (tlb->mm, pmd); addr = next;continue ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 224/507 mm/page-writeback: avoid 32-bit overflow in dirty threshold shares
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
[ Upstream commit 9597c2056e05bd79df9d343a9b42e84a54de1c52 ]
The ratios used by __wb_calc_thresh() are scaled to parts per million, but the threshold and ratio operands are unsigned long. On 32-bit kernels, their multiplication can wrap before the result is assigned to u64.
For example, with a threshold of 25600 pages and the default maximum ratio of 1000000, wb_max_thresh becomes 4125 pages instead of 25600. The shared threshold and minimum share calculations can overflow in the same way, producing incorrect per-writeback dirty limits.
Use a u64 threshold for the three ratio multiplications and div_u64() to retain the existing division order and rounding.
--- mm/page-writeback.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
mm/page-writeback.c +5 -3
@@ -883,6 +883,7 @@ static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc, {struct wb_domain *dom =dtc_dom (dtc);struct bdi_writeback *wb = dtc->wb; +u64 threshold = thresh;u64 wb_thresh;u64 wb_max_thresh;unsigned long numerator, denominator;
@@ -894,13 +895,14 @@ static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc,fprop_fraction_percpu (&dom->completions, dtc->wb_completions, &numerator, &denominator); - wb_thresh = (thresh * (100 *BDI_RATIO_SCALE - bdi_min_ratio)) / (100 *BDI_RATIO_SCALE ); + wb_thresh =div_u64 (threshold * (100 *BDI_RATIO_SCALE - bdi_min_ratio), +100 *BDI_RATIO_SCALE ); wb_thresh *= numerator; wb_thresh =div64_ul (wb_thresh, denominator);wb_min_max_ratio (wb, &wb_min_ratio, &wb_max_ratio); - wb_thresh += (thresh * wb_min_ratio) / (100 *BDI_RATIO_SCALE ); + wb_thresh +=div_u64 (threshold * wb_min_ratio,100 *BDI_RATIO_SCALE );/* * It's very possible that wb_thresh is close to 0 not because the
@@ -916,7 +918,7 @@ static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc, wb_thresh =max (wb_thresh, (thresh - dtc->dirty) /8 ); } - wb_max_thresh = thresh * wb_max_ratio / (100 *BDI_RATIO_SCALE ); + wb_max_thresh =div_u64 (threshold * wb_max_ratio,100 *BDI_RATIO_SCALE );if (wb_thresh > wb_max_thresh) wb_thresh = wb_max_thresh;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 225/507 mm/page_alloc: let the highest memory node recover from hopeless state
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
[ Upstream commit 83367658a01087375ede31ae343c99da03f72ac8 ]
free_frozen_page_commit() clears a hopeless node's kswapd failures once its zone recovers above the high watermark, but only if another memory node exists for allocations to fall back to.
The test next_memory_node(nid) < MAX_NUMNODES finds only memory nodes with a higher id. The highest-numbered memory node therefore never recovers on this path, and its kswapd stays disabled until reclaim on that node makes progress and balances it, or demotion is re-enabled.
In many cases, direct reclaim many never fully run against a lower node (CXL/kmem), and that means its kswapd can end up full disabled in rare situations.
To reproduce, fill the highest memory node with bound, non-THP anonymous memory and no swap until kswapd gives up, then free it: /proc/zoneinfo keeps showing node_unreclaimable 1 for that node. A lower node recovers.
Count the memory nodes instead. Adding first_memory_node != nid to the existing test would also work, but a count says directly what the check
means: some other memory node exists.
--- mm/page_alloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/page_alloc.c +1 -1
@@ -2947,7 +2947,7 @@ static bool free_frozen_page_commit(struct zone *zone,* kswapd work again by resetting kswapd_failures. */ if (kswapd_test_hopeless (pgdat) && -next_memory_node (pgdat->node_id) <MAX_NUMNODES ) +num_node_state (N_MEMORY ) >1 )kswapd_clear_hopeless (pgdat,KSWAPD_CLEAR_HOPELESS_PCP ); }return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 226/507 mm/hugetlb: fix mremap move length truncation
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Zhe <[email protected]>
[ Upstream commit dfb190302d2b4af86c6ae48af0d3b09f28b35460 ]
Patch series "mm/hugetlb: fix mremap bugs", v3.
This series fixes a few hugetlb mremap bugs.
Patch 1 fixes the return type of move_hugetlb_page_tables(), so large hugetlb moves cannot be truncated when reported back to the generic mremap code.
Patch 2 disables hugetlb PMD sharing for UFFD missing mode, so UFFDIO_POISON markers cannot become visible through shared PMD page tables.
Patch 3 fixes the recursive i_mmap_rwsem deadlock in the hugetlb mremap path by avoiding the destination PMD sharing allocation path while the mapping lock is already held for write.
This patch (of 3):
move_hugetlb_page_tables() returns the number of bytes moved, but its return type is int while the generic move_page_tables() path uses unsigned long lengths.
A hugetlb mremap() move length above INT_MAX can therefore be misreported to copy_vma_and_data(). The out-of-range conversion to int is implementation-defined; on common 64-bit builds, for example, a 4 GiB move can be reported as zero, making the caller treat the move as a failure and use the wrong length for rollback.
Return unsigned long from move_hugetlb_page_tables(), matching move_page_tables() and preserving the full byte count.
--- include/linux/hugetlb.h | 15 ++++++--------- mm/hugetlb.c | 7 +++---- 2 files changed, 9 insertions(+), 13 deletions(-)
include/linux/hugetlb.h +6 -9
@@ -121,10 +121,9 @@ void hugepage_put_subpool(struct hugepage_subpool *spool);void hugetlb_dup_vma_private (struct vm_area_struct *vma);void clear_vma_resv_huge_pages (struct vm_area_struct *vma); -int move_hugetlb_page_tables (struct vm_area_struct *vma, -struct vm_area_struct *new_vma, -unsigned long old_addr,unsigned long new_addr, -unsigned long len); +unsigned long move_hugetlb_page_tables (struct vm_area_struct *vma, +struct vm_area_struct *new_vma,unsigned long old_addr, +unsigned long new_addr,unsigned long len);int copy_hugetlb_page_range (struct mm_struct *,struct mm_struct *,struct vm_area_struct *,struct vm_area_struct *); void unmap_hugepage_range(struct vm_area_struct *,
@@ -339,11 +338,9 @@ static inline int copy_hugetlb_page_range(struct mm_struct *dst,return 0 ; } -static inline int move_hugetlb_page_tables (struct vm_area_struct *vma, -struct vm_area_struct *new_vma, -unsigned long old_addr, -unsigned long new_addr, -unsigned long len) +static inline unsigned long move_hugetlb_page_tables (struct vm_area_struct *vma, +struct vm_area_struct *new_vma,unsigned long old_addr, +unsigned long new_addr,unsigned long len) {BUG ();return 0 ;
mm/hugetlb.c +3 -4
@@ -5157,10 +5157,9 @@ static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr,spin_unlock (dst_ptl); } -int move_hugetlb_page_tables (struct vm_area_struct *vma, -struct vm_area_struct *new_vma, -unsigned long old_addr,unsigned long new_addr, -unsigned long len) +unsigned long move_hugetlb_page_tables (struct vm_area_struct *vma, +struct vm_area_struct *new_vma,unsigned long old_addr, +unsigned long new_addr,unsigned long len) {struct hstate *h =hstate_vma (vma);struct address_space *mapping = vma->vm_file->f_mapping;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 227/507 mm/hugetlb: fix mremap deadlock when PMD sharing is possible
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Zhe <[email protected]>
[ Upstream commit 92daa8652f88c8cfc05f4899a8408a04b02f211e ]
move_hugetlb_page_tables() holds the mapping's i_mmap_rwsem for write while moving hugetlb PTEs. This prevents races with truncation and protects huge_pmd_unshare(), but the move loop must not call helpers that can acquire the same rwsem for read.
huge_pte_alloc() can do that when the destination can use PMD
sharing: it may call huge_pmd_share(), which takes i_mmap_rwsem for read while searching for a shareable PMD table. Calling it while the move path already holds i_mmap_rwsem for write can deadlock.
Avoid that path for PMD-sized hugetlb mappings that can use PMD sharing. Instead of allocating or sharing the destination page table while moving, zap the source range and let the destination fault path populate or share the PMD lazily.
Reuse the hugetlb unmap logic for the source-side zap by splitting the core loop out of __unmap_hugepage_range(). The wrapper keeps the existing tlb_start_vma(), tlb_end_vma() and huge_pmd_unshare_flush() behavior, while move_hugetlb_page_tables() can reuse the unmap loop with its existing mmu_gather.
--- mm/hugetlb.c | 47 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 10 deletions(-)
mm/hugetlb.c +37 -10
@@ -125,6 +125,10 @@ static int __huge_pmd_unshare(struct mmu_gather *tlb, bool check_locks);static void hugetlb_unshare_pmds (struct vm_area_struct *vma,unsigned long start,unsigned long end,bool take_locks); +static void hugetlb_unmap_range (struct mmu_gather *tlb, +struct vm_area_struct *vma,unsigned long start, +unsigned long end,struct folio *folio, +zap_flags_t zap_flags);static struct resv_map *vma_resv_map (struct vm_area_struct *vma);static inline bool subpool_is_free (struct hugepage_subpool *spool)
@@ -5189,6 +5193,8 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,for (; old_addr < old_end; old_addr += sz, new_addr += sz) {const unsigned long offset_to_last_entry = (old_addr | last_addr_mask) - old_addr; +const unsigned long offset_to_last_dst_entry = + (new_addr | last_addr_mask) - new_addr; src_pte =hugetlb_walk (vma, old_addr, sz);if (!src_pte) {
@@ -5205,6 +5211,24 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,continue ; } +/* +* Avoid entering the destination PMD sharing path while holding +* i_mmap_rwsem for write. Leave destination page table +* population to the fault path, which can share the PMD lazily. +*/ +if (sz ==PMD_SIZE &&want_pmd_share (new_vma, new_addr)) { +const unsigned long unmap_size = +min (old_end - old_addr, + offset_to_last_dst_entry + sz); + +hugetlb_unmap_range (&tlb, vma, old_addr, + old_addr + unmap_size,NULL , +ZAP_FLAG_DROP_MARKER ); + old_addr += unmap_size - sz; + new_addr += unmap_size - sz; +continue ; + } + dst_pte =huge_pte_alloc (mm, new_vma, new_addr, sz);if (!dst_pte)break ;
@@ -5224,9 +5248,10 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,return len + old_addr - old_end; } -void __unmap_hugepage_range (struct mmu_gather *tlb,struct vm_area_struct *vma, -unsigned long start,unsigned long end, -struct folio *folio,zap_flags_t zap_flags) +static void hugetlb_unmap_range (struct mmu_gather *tlb, +struct vm_area_struct *vma,unsigned long start, +unsigned long end,struct folio *folio, +zap_flags_t zap_flags) {struct mm_struct *mm = vma->vm_mm;const bool folio_provided = !!folio;
@@ -5244,13 +5269,6 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,BUG_ON (start & ~huge_page_mask (h));BUG_ON (end & ~huge_page_mask (h)); -/* -* This is a hugetlb vma, all the pte entries should point -* to huge page. -*/ -tlb_change_page_size (tlb, sz); -tlb_start_vma (tlb, vma); - last_addr_mask =hugetlb_mask_last_page (h); address = start;for (; address < end; address += sz) {
@@ -5379,6 +5397,15 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,if (folio_provided)break ; } +} + +void __unmap_hugepage_range (struct mmu_gather *tlb,struct vm_area_struct *vma, +unsigned long start,unsigned long end, +struct folio *folio,zap_flags_t zap_flags) +{ +tlb_change_page_size (tlb,huge_page_size (hstate_vma (vma))); +tlb_start_vma (tlb, vma); +hugetlb_unmap_range (tlb, vma, start, end, folio, zap_flags);tlb_end_vma (tlb, vma);huge_pmd_unshare_flush (tlb, vma);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 228/507 mm/page_alloc: mark pages freed by __free_pages_core() as not tagged
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zenghui Yu (Huawei) <[email protected]>
[ Upstream commit b6732c6d43139ea56de8bc62e87ace8543ef784f ]
Onlining hotplugged memory (e.g., a dev_dax device bound to kmem) with CONFIG_MEM_ALLOC_PROFILING_DEBUG triggers:
alloc_tag was not set
WARNING: ./include/linux/alloc_tag.h:166 at __pgalloc_tag_sub+0x1fc/0x254 Call trace: __pgalloc_tag_sub+0x1fc/0x254 (P) __free_pages_ok+0x14c/0x6ac __free_pages_core+0xa8/0x188 generic_online_page+0x14/0x20 online_pages+0x220/0x3b0 memory_subsys_online+0xfc/0x198 device_online+0x58/0xe0 state_store+0xf0/0xf8
Pages entering the buddy through __free_pages_core() have never been allocated, so their allocation tag references are NULL. The free path, __free_pages_prepare() -> pgalloc_tag_sub(), expects a valid tag or a CODETAG_EMPTY mark and warns otherwise. Paths feeding never-allocated pages into the buddy are therefore expected to mark them with clear_page_tag_ref() first, like init_cma_reserved_pageblock() and free_reserved_pages() do; of __free_pages_core()'s callers only memblock_free_pages() clears the tag ref itself, and the hotplug onlining path was missed.
Since all __free_pages_core() callers free never-allocated pages, mark the head page as not tagged in __free_pages_core() itself instead of relying on each caller, and drop the now-redundant clearing from memblock_free_pages().
--- mm/mm_init.c | 2 -- mm/page_alloc.c | 3 +++ 2 files changed, 3 insertions(+), 2 deletions(-)
mm/mm_init.c +0 -2
@@ -2422,8 +2422,6 @@ void __init memblock_free_pages(unsigned long pfn, unsigned int order)return ; } -/* pages were reserved and not allocated */ -clear_page_tag_ref (page);__free_pages_core (page, order,MEMINIT_EARLY ); }
mm/page_alloc.c +3 -0
@@ -1634,6 +1634,9 @@ void __meminit __free_pages_core(struct page *page, unsigned int order,atomic_long_add (nr_pages, &page_zone (page)->managed_pages); } +/* pages were never allocated */ +clear_page_tag_ref (page); +if (page_contains_unaccepted (page, order)) {if (order ==MAX_PAGE_ORDER &&__free_unaccepted (page))return ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 229/507 mm/vma: write lock source VMA before duplicating it in __split_vma()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit 769417e410dd19b2a438c6addb61b194b7a4c387 ]
__split_vma() duplicates the source VMA before taking its VMA write lock, and until the VMA is write-locked, a concurrent thread might set VMA_MAYBE_GUARD_BIT, resulting in the duplication missing the flag.
If this happens, then fork may fail to duplicate guard markers and, if a file-backed mapping, THP collapse may also discard the markers.
Resolve this by taking the VMA write lock before vm_area_dup() and, since all callers of vm_area_dup() now hold the VMA write lock, assert that this is the case there, and add a comment to explain why it's needed.
--- mm/vma.c | 2 +- mm/vma_init.c | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-)
mm/vma.c +1 -1
@@ -557,6 +557,7 @@ __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,return err; } +vma_start_write (vma); new =vm_area_dup (vma);if (!new)return -ENOMEM ;
@@ -587,7 +588,6 @@ __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,if (new->vm_ops && new->vm_ops->open) new->vm_ops->open (new); -vma_start_write (vma);vma_start_write (new);init_vma_prep (&vp, vma);
mm/vma_init.c +3 -0
@@ -127,6 +127,9 @@ struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig) {struct vm_area_struct *new =kmem_cache_alloc (vm_area_cachep,GFP_KERNEL ); +/* Must hold a write lock to stabilise atomic VMA flags. */ +vma_assert_write_locked (orig); +if (!new)return NULL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 230/507 mm/ksm: keep soft-dirty when merging a page
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Samarth Narang <[email protected]>
[ Upstream commit 2efc6332f18bfd848f74f3d5ba45b31450601faa ]
replace_page() maps the KSM page with a PTE built from scratch, so the soft-dirty bit of the PTE it replaces is lost. A page written since "clear_refs 4" then no longer shows as soft-dirty once it is merged, and a soft-dirty based dumper treats it as unchanged.
Copy the soft-dirty bit from the original PTE to the new PTE.
--- mm/ksm.c | 4 ++++ 1 file changed, 4 insertions(+)
mm/ksm.c +4 -0
@@ -1462,6 +1462,10 @@ static int replace_page(struct vm_area_struct *vma, struct page *page,dec_mm_counter (mm,MM_ANONPAGES ); } +/* Preserve soft-dirty when replacing the page. */ +if (pte_soft_dirty (orig_pte)) + newpte =pte_mksoft_dirty (newpte); +flush_cache_page (vma, addr,pte_pfn (ptep_get (ptep)));/* * No need to notify as we are replacing a read only page with another
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 231/507 fs/proc/task_mmu: return -ENOTTY for unknown pagemap ioctls
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hengyu Liang <[email protected]>
[ Upstream commit bfc1d9724c78aa7570dbeb17207a21089f2d1b1a ]
Commit 52526ca7fdb9 ("fs/proc/task_mmu: implement IOCTL to get and optionally clear info about PTEs") made do_pagemap_cmd() the ioctl handler of /proc/<pid>/pagemap.
However, do_pagemap_cmd() returns -EINVAL for every command other than PAGEMAP_SCAN. Before that commit, pagemap had no ioctl handler, and the VFS returned -ENOTTY for these commands. As of now, they fail with EINVAL, so tcgetattr() and isatty() on pagemap report EINVAL instead of ENOTTY.
The issue can be reproduced with a simple C program:
#include <fcntl.h>
#include <stdio.h>
#include <termios.h>
int main(void)
{
struct termios t;
int fd = open("/proc/self/pagemap", O_RDONLY);
if (tcgetattr(fd, &t) < 0)
perror("tcgetattr");
return 0;
}Before that commit, the result is:
tcgetattr: Inappropriate ioctl for device
After that commit, the result is:
tcgetattr: Invalid argument
This patch will return -ENOIOCTLCMD for unknown commands, as procfs_procmap_ioctl() in the same file does, so that the VFS turns it into -ENOTTY.
--- fs/proc/task_mmu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/proc/task_mmu.c +1 -1
@@ -3314,7 +3314,7 @@ static long do_pagemap_cmd(struct file *file, unsigned int cmd,return do_pagemap_scan (mm, arg);default : -return -EINVAL ; +return -ENOIOCTLCMD ; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 232/507 mm/damon/sysfs-schemes: hold damon_sysfs_lock in target_metric_store()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: SJ Park <[email protected]>
[ Upstream commit a76adcace3550b16e5735ba4a5e95a9c2664e113 ]
Patch series "mm/damon: fix three race bugs in sysfs and core", v1.
There are three race condition bugs in DAMON sysfs interface and the core layer. User impacts are not critical but better to fix sooner than later.
Patch 1 fixes a toctou bug in DAMON sysfs interface that can mess up DAMOS auto-tuning. Patches 2 and 3 move static variables that can be wrongly shared with multiple kdamonds and therefore make DAMON monitoring results be a little more indeterministic.
This patch (of 3):
damon_sysfs_add_quota_score() reads damos_sysfs_quota_goal->metric twice, once to set damos_quota_goal->metric to the value, and once again to set the metric-dependent damos_quota_goal unions based on the value.
target_metrics_score() can update damos_sysfs_quota_goal->metric between the two reads. This time-of-check to time-of-use (toctou) race can make the union fields incorrectly set. The incorrect damos_quota_goal will be passed to the core layer and make DAMOS incorrectly behave.
Users could reproduce the race by writing a new value to the target_metric sysfs file while DAMON is starting, or online parameters update is ongoing. The issue will only rarely happen in the real use cases. It requires sysfs write permission. The race window is short. Sane users wouldn't do such writes while DAMON enablement and/or online parameters update is ongoing.
The user impact is not very critical. The race is not easy to unintentionally trigger. No leak or crash happens. Nonetheless, DAMOS could be unexpectedly more or less aggressive and does not achieve the auto-tune goal. Because of the nature of races, investigating will be difficult. Users can control the impact from unexpected aggressiveness using additional quotas and resolve the issue in runtime by re-installing the quota goal, though.
Avoid the race by protecting damos_sysfs_quota_goal->metric write in target_metric_store() with damon_sysfs_lock. Because damon_sysfs_add_quota_score() is called while holding the same lock, the race is removed.
The issue was discovered as a part of a bug report [1] from Sashiko, which is partially outdated. In more detail, the Sashiko report [1] was mainly for an outdated bug [2]. But it was also mentioning the issue of this patch as a similar class bug.
--- mm/damon/sysfs-schemes.c | 3 +++ 1 file changed, 3 insertions(+)
mm/damon/sysfs-schemes.c +3 -0
@@ -1300,7 +1300,10 @@ static ssize_t target_metric_store(struct kobject *kobj, metric_name = &damos_sysfs_qgoal_metric_names[i];if (sysfs_streq (buf, metric_name->name)) { +if (!mutex_trylock (&damon_sysfs_lock)) +return -EBUSY ; goal->metric = metric_name->metric; +mutex_unlock (&damon_sysfs_lock);return count; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 233/507 mm/damon/core: move static variable last_nr_regions to damon_ctx
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: SJ Park <[email protected]>
[ Upstream commit 26ae50a0901a44f7d50053f87dc38abd9f9a269c ]
kdamond_split_regions() uses a static variable last_nr_regions, to infer if the region boundaries are too stable. If it looks too stable, it does a more aggressive region split because it might be a fake stability coming from non-aggressive split. Because the variable is static, the inference can be racy and wrong when multiple kdamonds are running in parallel.
The user impact is not critical. No crash, no leak. DAMON's best-effort monitoring accuracy can be degraded when multiple kdamonds are used in parallel and the workload has certain access patterns. Still it is a bug that is better to fix.
Move the variable into the damon_ctx struct to fix the problem.
--- include/linux/damon.h | 5 +++++ mm/damon/core.c | 5 ++--- 2 files changed, 7 insertions(+), 3 deletions(-)
include/linux/damon.h +5 -0
@@ -914,6 +914,11 @@ struct damon_ctx {/* @rnd_state: Per-ctx PRNG state for damon_rand(). */ struct rnd_state rnd_state; +/* +* number of regions after last merge. Read kdamond_split_regions() +* for more details. +*/ +unsigned long last_nr_regions; };/* Get a random number in [@l, @r) using @ctx's lockless PRNG. */
mm/damon/core.c +2 -3
@@ -3610,7 +3610,6 @@ static void kdamond_split_regions(struct damon_ctx *ctx)struct damon_target *t;unsigned long nr_regions =0 ;unsigned long max_nr_regions = ctx->attrs.max_nr_regions; -static unsigned long last_nr_regions;int nr_subregions =2 ;damon_for_each_target (t, ctx)
@@ -3626,7 +3625,7 @@ static void kdamond_split_regions(struct damon_ctx *ctx) }/* Maybe the middle of the region has different access frequency */ -if (last_nr_regions == nr_regions && +if (ctx->last_nr_regions == nr_regions && nr_regions < max_nr_regions /3 ) nr_subregions =3 ;
@@ -3635,7 +3634,7 @@ static void kdamond_split_regions(struct damon_ctx *ctx) ctx->min_region_sz); done: - last_nr_regions = nr_regions; + ctx->last_nr_regions = nr_regions; }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 234/507 mm/damon/core: move static variable rotation to damon_ctx
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: SJ Park <[email protected]>
[ Upstream commit c4ff3ea30640b394df4156d7ddf60ad8ffe765f1 ]
damon_split_some_reigons() uses a static variable, rotation, to remember how many times it was called. It is again used to determine fair selection of regions to split. Since it is a static variable, it can be indeterministic and therefore less fair.
The user impact is not critical. No crash, no leak. DAMON's best-effort and indeterministic monitoring accuracy could be slightly more indeterministic when multiple kdamonds are used in parallel.
Fix the problem by moving the static variable into the damon_ctx struct.
--- include/linux/damon.h | 5 +++++ mm/damon/core.c | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-)
include/linux/damon.h +5 -0
@@ -919,6 +919,11 @@ struct damon_ctx {* for more details. */ unsigned long last_nr_regions; +/* +* number of damon_split_some_regions() invocations for this context. +* Read damon_split_some_regions() for more details. +*/ +unsigned long region_split_rotation; };/* Get a random number in [@l, @r) using @ctx's lockless PRNG. */
mm/damon/core.c +3 -2
@@ -3568,12 +3568,13 @@ static void damon_split_regions_of(struct damon_ctx *ctx,static void damon_split_some_regions (struct damon_ctx *ctx,unsigned long split_step) { -static unsigned long rotation;struct damon_target *t;struct damon_region *r, *next; -unsigned long offset = rotation++ % split_step; +unsigned long offset;unsigned long idx =0 ; + offset = ctx->region_split_rotation++ % split_step; +damon_for_each_target (t, ctx) {damon_for_each_region_safe (r, next, t) {unsigned long sz_region, sz_sub;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 235/507 mm: make swapoff interruptible when unusing mms/shmem
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Down <[email protected]>
[ Upstream commit 740128dd1a3f2bd81a80314d079b6b03c39ba3af ]
try_to_unuse() only checks for a pending signal between mms, and shmem_unuse() doesn't check at all. That means that once swapoff gets to a process or a shmem file with a lot swapped out, nothing can interrupt it until every last page of it has been read back in.
Just as one example of where this can concretely show up, freezing tasks for suspend or hibernation has to wait for swapoff to notice the freezer's fake signal, and gives up after freeze_timeout_msecs (20 seconds by default).
Here's a facetious example where one swaps out 2GiB of one process to a swap file on ext4, starts swapoff, and half a second later tries to freeze with pm_test=freezer. Writing to /sys/power/state then fails with EBUSY and this in dmesg:
Freezing user space processes failed after 20.003 seconds (1 tasks refusing to freeze, wq_busy=0):
task:swapoff state:D stack:0 pid:3175 tgid:3175 ppid:2955 task_flags:0x400100 flags:0x00000419
Call trace:
[...]
io_schedule+0x44/0x70
folio_wait_bit_common+0x1ec/0x3d0
__folio_lock+0x24/0x40
unuse_pte_range+0x2d0/0x348
unuse_vma+0x158/0x248
unuse_mm+0xfc/0x150
try_to_unuse+0x104/0x3f8
__do_sys_swapoff+0x220/0x5d8
[...]The same goes for anything else that wants swapoff to stop, like an admin hitting ^C in a panic, of course.
Prior to commit b56a2d8af914 ("mm: rid swapoff of quadratic complexity") try_to_unuse() was driven by find_next_to_unuse() which checks for a signal before every entry, so let's restore that behaviour.
Just as an example of the improvements, here's how long freezing takes in the same test while swapoff is happening on my computer:
before after
400MiB anon 8.925s 0.028s
400MiB shmem 1.639s 0.003s
2GiB anon failed after 20.003s 0.011s--- mm/shmem.c | 4 ++++ mm/swapfile.c | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-)
mm/shmem.c +4 -0
@@ -1561,6 +1561,10 @@ static int shmem_unuse_inode(struct inode *inode, unsigned int type)if (ret <0 )break ; +if (signal_pending (current)) { + ret = -ERESTARTSYS ; +break ; + } start = indices[folio_batch_count (&fbatch) -1 ]; }while (true);
mm/swapfile.c +3 -1
@@ -2609,6 +2609,8 @@ static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud, pmd =pmd_offset (pud, addr); do { cond_resched(); + if (signal_pending(current)) + return -ERESTARTSYS; next = pmd_addr_end(addr, end); ret = unuse_pte_range(vma, pmd, addr, next, type); if (ret)
@@ -2823,7 +2825,7 @@ static int try_to_unuse(unsigned int type)if (swap_usage_in_pages (si)) {if (!signal_pending (current)) goto retry; -return -EINTR ; +return -ERESTARTSYS ; } success:
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 236/507 mm/migrate: untag addresses when querying page nodes
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
[ Upstream commit 7d8746d7dc9cc4003661011424e5880ea7ae364b ]
When move_pages() is used with nodes == NULL, do_pages_stat_array() passes each page address directly to vma_lookup(). A valid tagged address therefore fails the VMA lookup and gets -EFAULT in its status entry, instead of the node reported for the corresponding untagged address.
The tagged address ABI permits these pointers, and the migration path already removes their tags. Apply the target mm's untagging rules to the query path as well, while holding its mmap read lock.
--- mm/migrate.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/migrate.c +1 -1
@@ -2462,7 +2462,7 @@ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,mmap_read_lock (mm);for (i =0 ; i < nr_pages; i++) { -unsigned long addr = (unsigned long )(*pages); +unsigned long addr = (unsigned long )untagged_addr_remote (mm, *pages);struct vm_area_struct *vma;struct folio_walk fw;struct folio *folio;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 237/507 mm/ksm: fix userfaultfd protection during merge and unmerge
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lance Yang <[email protected]>
[ Upstream commit 990d6c2194a938a19a8cf94c6cfd75171345089b ]
KSM loses userfaultfd protection when replace_page() builds a new PTE from vma->vm_page_prot. Dropping its uffd bit lets a subsequent write go through ordinary COW instead of userfaultfd write protection handling. For RWP, a merged page also becomes readable without faulting.
Keeping the uffd bit and restoring PAGE_NONE fixes merging, but we also have to handle unmerging. An existing KSM page can be protected with RWP before MADV_UNMERGEABLE, so unmerging already needs fixing independently of preserving RWP during merging.
Unsharing replaces a shared page with a private one and should leave userfaultfd protection in place, as do_wp_page() already does for write protection. Currently, an unshare fault reaches do_uffd_rwp() before it can proceed to do_wp_page().
- With synchronous RWP, handle_userfault() returns VM_FAULT_SIGBUS. break_ksm() then reports success with a KSM page still merged.
- With asynchronous RWP, protection is cleared before unsharing.
Preserve the uffd bit when merging, and restore PAGE_NONE for RWP. Let FAULT_FLAG_UNSHARE skip RWP fault handling and keep PAGE_NONE on each private copy as well. Unsharing can then complete with RWP still armed for a subsequent access.
--- mm/ksm.c | 8 +++++++- mm/memory.c | 14 ++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-)
mm/ksm.c +7 -1
@@ -34,6 +34,7 @@#include <linux/memory.h> #include <linux/mmu_notifier.h> #include <linux/swap.h> +#include <linux/userfaultfd_k.h> #include <linux/ksm.h> #include <linux/hashtable.h> #include <linux/freezer.h>
@@ -1462,9 +1463,14 @@ static int replace_page(struct vm_area_struct *vma, struct page *page,dec_mm_counter (mm,MM_ANONPAGES ); } -/* Preserve soft-dirty when replacing the page. */ +/* Preserve soft-dirty and uffd protection when replacing the page. */ if (pte_soft_dirty (orig_pte)) newpte =pte_mksoft_dirty (newpte); +if (pte_uffd (orig_pte)) { + newpte =pte_mkuffd (newpte); +if (userfaultfd_rwp (vma)) + newpte =pte_modify (newpte,PAGE_NONE ); + }flush_cache_page (vma, addr,pte_pfn (ptep_get (ptep)));/*
mm/memory.c +10 -4
@@ -4060,8 +4060,11 @@ static vm_fault_t wp_page_copy(struct vm_fault *vmf)if (unlikely (unshare)) {if (pte_soft_dirty (vmf->orig_pte)) entry =pte_mksoft_dirty (entry); -if (pte_uffd (vmf->orig_pte)) +if (pte_uffd (vmf->orig_pte)) { entry =pte_mkuffd (entry); +if (userfaultfd_rwp (vma)) + entry =pte_modify (entry,PAGE_NONE ); + } }else { entry =maybe_mkwrite (pte_mkdirty (entry), vma); }
@@ -6591,9 +6594,12 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf)* VM_UFFD_RWP VMA, a protnone PTE without the uffd bit is * NUMA hinting and must still fall through to do_numa_page(). */ -if (userfaultfd_pte_rwp (vmf->vma, vmf->orig_pte)) -return do_uffd_rwp (vmf); -return do_numa_page (vmf); +if (userfaultfd_pte_rwp (vmf->vma, vmf->orig_pte)) { +if (!(vmf->flags &FAULT_FLAG_UNSHARE )) +return do_uffd_rwp (vmf); + }else { +return do_numa_page (vmf); + } }spin_lock (vmf->ptl);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 238/507 mm/migrate: snapshot the source nid before the misplaced migration
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yafang Shao <[email protected]>
[ Upstream commit fe623a81ad9eddf10059b4e44bca0440d9120613 ]
A successful migration frees the source folio before the promotion counter update, so the folio_nid() read there operates on a freed folio — which may already have been reallocated. It happens to work today, as Zi explained:
: Strictly speaking, it can be seen as a benign UAF. It works, because : 1. folio->flags happens to be the same as page->flags,
: 2. folio/page nid is stored in the ->flags and never changed. :
: In memdesc world, after a folio is freed, I assume folio->flags would be : zeroed since struct folio is freed and calling folio_nid() on a freed : folio would give a bogus result (yeah, it can be mitigated by not : zeroing node field and each node has its own struct folio pool, but that : makes folio_nid() implementation dependent).
and Matthew explained further:
: once struct folio is separately allocated, it's a UAF. It could be : recycled to a different NID or maybe the slab containing the folio could : be freed (assuming we're not holding the RCU read lock at this point in : migration, and I don't see why we would be).
A separate concern is memory hot-removal. With memory-tiering mode enabled, successful migration can release the source before the promotion-accounting folio_nid() read. If the task is preempted there, an otherwise-free source block can be offlined and removed first. On the x86 path, removal can unmap the source's vmemmap, so the later read can fault. The snapshot avoids that read.
--- mm/migrate.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
mm/migrate.c +2 -1
@@ -2757,6 +2757,7 @@ int migrate_misplaced_folio(struct folio *folio, int node)pg_data_t *pgdat =NODE_DATA (node);int nr_remaining;unsigned int nr_succeeded; +int src_node =folio_nid (folio);LIST_HEAD (migratepages);struct mem_cgroup *memcg =get_mem_cgroup_from_folio (folio);struct lruvec *lruvec =mem_cgroup_lruvec (memcg, pgdat);
@@ -2771,7 +2772,7 @@ int migrate_misplaced_folio(struct folio *folio, int node)count_vm_numa_events (NUMA_PAGE_MIGRATE , nr_succeeded);count_memcg_events (memcg,NUMA_PAGE_MIGRATE , nr_succeeded);if ((sysctl_numa_balancing_mode &NUMA_BALANCING_MEMORY_TIERING ) - && !node_is_toptier (folio_nid (folio)) + && !node_is_toptier (src_node) &&node_is_toptier (node))mod_lruvec_state (lruvec,PGPROMOTE_SUCCESS , nr_succeeded); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 239/507 mm/vma: update VMA iterator state on error in new VMA merge
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
[ Upstream commit 168ed9c5d5ec2fd326715eba5750c2b69e559ff3 ]
Commit cacded5e42b9 ("mm: avoid using vma_merge() for new VMAs") shared code between vma_merge_new_range() and vma_expand().
However in doing so, it failed to correctly restore the VMA iterator when vma_expand() errors out.
This is a problem when the immediately preceding VMA is mergeable and vmg->just_expand isn't specified, at which point the VMA iterator is moved to the previous VMA.
(Note that vmg->just_expand is a special case for brk(), where the iterator will already be positioned at the VMA to be expanded.)
Resolve things by restoring the VMA iterator on error. Use vma_iter_next_range() to do this, so it will correctly stop on the gap after the previous VMA, rather than skip to the next VMA after it (this is a new VMA merge, so is being applied at a gap).
To isolate the error handling, return early when a merge isn't possible (what the vmg->target check was doing before), then handle the merge success/failure case explicitly.
While here, update vma_expand() to jump to the nomem case when dup_anon_vma() fails, so vmg->state is correctly updated.
This doesn't impact anything in practice, but is the correct course and since it's part of the error path that this patch addresses, it makes sense to update it also.
Users are very unlikely to have observed the issue this patch addresses in practice, as it is near-impossible to fail an allocation for an anon_vma, but a process under memory pressure that receives a fatal signal could trigger it.
This issue was originally reported by Li Jinyue for which I am grateful. He indicated this was uncovered by a private syzkaller instance.
--- mm/vma.c | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-)
mm/vma.c +18 -10
@@ -1143,6 +1143,7 @@ struct vm_area_struct *vma_merge_new_range(struct vma_merge_struct *vmg)struct vm_area_struct *next = vmg->next;unsigned long end = vmg->end;bool can_merge_left, can_merge_right; +bool move_iter_back = false;mmap_assert_write_locked (vmg->mm);VM_WARN_ON_VMG (vmg->middle, vmg);
@@ -1182,23 +1183,30 @@ struct vm_area_struct *vma_merge_new_range(struct vma_merge_struct *vmg) vmg->end = end;/* In expand-only case we are already positioned at prev. */ -if (!vmg->just_expand) { -/* Equivalent to going to the previous range. */ -vma_prev (vmg->vmi); - } +if (!vmg->just_expand) + move_iter_back = true; } +if (!can_merge_left && !can_merge_right) +return NULL ; + +if (move_iter_back) +vma_prev (vmg->vmi); +/* * Now try to expand adjacent VMA(s). This takes care of removing the * following VMA if we have VMAs on both sides. */ -if (vmg->target && !vma_expand (vmg)) { -khugepaged_enter_vma (vmg->target, vmg->vm_flags); - vmg->state =VMA_MERGE_SUCCESS ; -return vmg->target; +if (vma_expand (vmg)) { +/* Error occurred, restore iterator. */ +if (move_iter_back) +vma_iter_next_range (vmg->vmi); +return NULL ; } -return NULL ; +khugepaged_enter_vma (vmg->target, vmg->vm_flags); + vmg->state =VMA_MERGE_SUCCESS ; +return vmg->target; }/*
@@ -1293,7 +1301,7 @@ int vma_expand(struct vma_merge_struct *vmg)if (!ret && vmg->copied_from) ret =dup_anon_vma (target, vmg->copied_from, &anon_dup);if (ret) -return ret; + goto nomem;if (remove_next) {vma_flags_t next_sticky;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 240/507 mm/hugetlb_vmemmap: map the shared tail page writable
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kiryl Shutsemau (Meta) <[email protected]>
[ Upstream commit 0120a603afadba8ab4954bb1ce60f8195f80efc8 ]
page_ref_add_unless_zero() reads the refcount and then updates it with a cmpxchg. A lockless get, such as a page cache lookup or a PFN scanner, can read a non-zero refcount from a page that is then freed and reused as a hugetlb tail page. If HVO remaps its struct page to the shared tail page in between, the cmpxchg writes to read-only vmemmap:
CPU0 (lockless get) CPU1
c = atomic_read(&page->_refcount)
page freed
page allocated as a hugetlb tail HVO remaps the struct page RO
try_cmpxchg(&page->_refcount, &c, c + 1)
-> write fault on read-only vmemmap
The refcount is zero by then and the compare fails, but a compare-and-swap instruction needs write access whether or not it succeeds. The kernel oopses when hugetlb pages are allocated at runtime with HVO enabled while a lockless get races with it.
Commit bd225530a4c7 ("mm/hugetlb_vmemmap: fix race with speculative PFN walkers") closed the window with RCU on both sides. The RCU was removed together with fake heads, on the wrong belief that it was only needed for them.
Map the shared tail page writable instead of restoring the RCU. Every struct page on it is a tail with a zero refcount, so a late cmpxchg fails and leaves the page unchanged. RCU would put rcu_read_lock() back around every get and synchronize_rcu() back into hugetlb allocation and freeing.
The cost is the protection against stray writes to tail struct pages. The shared page is shared by all hugetlb folios of the same order in the zone, so such a write now corrupts all of them instead of oopsing.
Bootmem folios optimized when the memmap is set up keep their tails read-only. Nothing does a lockless get on them before hugetlb takes them over.
--- Documentation/mm/vmemmap_dedup.rst | 15 +++++++++++++-- mm/hugetlb_vmemmap.c | 8 +++++--- 2 files changed, 18 insertions(+), 5 deletions(-)
Documentation/mm/vmemmap_dedup.rst +13 -2
@@ -131,8 +131,19 @@ pages of ``struct page`` (page 1 to page 7) are tail pages. The optimization is only applied when the size of the struct page is a power of 2. In this case, all tail pages of the same order are identical. See compound_head(). This allows us to remap the tail pages of the vmemmap to a -shared, read-only page. The head page is also remapped to a new page. This -allows the original vmemmap pages to be freed. +shared page. The head page is also remapped to a new page. This allows the +original vmemmap pages to be freed. + +The shared page is mapped writable. A lockless get of a page reference can +read a non-zero refcount before the remap and attempt its atomic update +after it. The refcount of a tail page is zero, so the update fails without +changing the page. Nothing else may write to the shared page: it is shared +by all HugeTLB pages of the same size in the zone, and a stray write would +corrupt all of them. + +HugeTLB pages whose vmemmap is optimized when the memmap is first set up at +boot keep a read-only mapping of the shared page. Nothing can do a lockless +get on them before they are handed to HugeTLB. Here is how things look after remapping::
mm/hugetlb_vmemmap.c +5 -3
@@ -222,10 +222,12 @@ static void vmemmap_remap_pte(pte_t *pte, unsigned long addr,VM_WARN_ON_ONCE (!PageTail ((const struct page *)addr));/* -* Remap the tail pages as read-only to catch illegal write -* operation to the tail pages. +* Map the shared tail page writable. A lockless get that read +* a non-zero refcount before the remap can still do its +* cmpxchg after it. The refcount is zero, so the cmpxchg +* fails and leaves the page unchanged. */ - entry =mk_pte (walk->vmemmap_tail,PAGE_KERNEL_RO ); + entry =mk_pte (walk->vmemmap_tail,PAGE_KERNEL ); }list_add (&page->lru, walk->vmemmap_pages);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 241/507 mm: page_alloc: do not give all non-blocking requests reserve access
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johannes Weiner <[email protected]>
[ Upstream commit 6ee3d87b940848aaed5d4e8d005c5f674bf2637a ]
Patch series "mm: page_alloc: fix reserve access for non-blocking requests", v2.
Two fixes for how non-blocking allocations interact with the highatomic reserve. There are prerequisites for Salvatore's "mm/page_alloc: avoid direct reclaim and compaction for costly __GFP_NORETRY allocations" [0].
Patch 1 narrows which requests may physically take highatomic pages, patch 2 narrows which requests may count them in their watermark check.
Both are prerequisites for Salvatore's patch: it clears __GFP_DIRECT_RECLAIM for costly __GFP_NORETRY requests, which turns every large page cache folio allocation that reaches the slowpath into a non-blocking one. Without patch 1, those requests may fall back to the highatomic freelists reserved for atomic requests. Without patch 2, they count the free highatomic pages in their watermark check while being served from regular memory, so they can consume regular high-order blocks below the min watermark by the size of the reserve. GFP_NOWAIT requests hit both paths today, so these are existing problems worthy of their own stable backports; but Salvatore's patch would widen them significantly.
Patch 2 reproduction: a GFP_NOWAIT burst under memory pressure can drain regular free memory to zero while the highatomic reserve sits idle. Measured on a 32G box with an anonymous working set, swap, and a full 290M reserve, three synthetic bursts drove the 28G Normal zone's regular free memory to 28M, 0.8M and 0.6M against a 60M min watermark. Swapout failed its swap table allocation inside reclaim, reclaim scanned 13M pages to free 200k, and page faults stalled for tens to hundreds of milliseconds. With the fix the burst stops at the min watermark and nothing else happens. This was found in review and reproduced synthetically; it has not been observed in production.
GFP_ATOMIC order-0 requests have a milder version of the same problem:
They are entitled to the reserve but are served regular memory first, so the fix there has to change the watermark check and the freelist order together. Salvatore's change doesn't interact with this, though; fixing that is left for a separate patch.
This patch (of 2):
281dd25c1a01 ("mm/page_alloc: let GFP_ATOMIC order-0 allocs access highatomic reserves") accidentally gave all non-blocking allocation requests access to highatomic reserves, which includes GFP_NOWAIT and other sites clearing __GFP_DIRECT_RECLAIM.
While this improved atomic request success rate, it's unintentionally broad and can actually worsen highatomic requests by squandering the reserves on requests that don't need it.
There are concurrent efforts to clear __GFP_DIRECT_RECLAIM altogether for costly order __GFP_NORETRY requests, which would then also fall into this exemption and deplete reserves even faster.
What GFP_ATOMIC has over the others is __GFP_HIGH, which alloc_flags_slowpath() translates to ALLOC_MIN_RESERVE.
Narrow the exemption to contexts that have both ALLOC_NON_BLOCK | ALLOC_MIN_RESERVE.
regular free memory to zero while the highatomic reserve sits idle. Measured on a 32G box with an anonymous working set, swap, and a full 290M reserve, three synthetic bursts drove the 28G Normal zone's regular free memory to 28M, 0.8M and 0.6M against a 60M min watermark. Swapout failed its swap table allocation inside reclaim, reclaim scanned 13M pages to free 200k, and page faults stalled for tens to hundreds of milliseconds.
--- mm/page_alloc.c | 4 +++- mm/page_alloc.h | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-)
mm/page_alloc.c +3 -1
@@ -3259,7 +3259,9 @@ struct page *rmqueue_buddy(struct zone *preferred_zone, struct zone *zone,* reserves as failing now is worse than failing a * high-order atomic allocation in the future. */ -if (!page && (alloc_flags & (ALLOC_OOM |ALLOC_NON_BLOCK ))) +if (!page && + ((alloc_flags &ALLOC_OOM ) || + (alloc_flags &ALLOC_MASK_ATOMIC ) ==ALLOC_MASK_ATOMIC )) page =__rmqueue_smallest (zone, order,MIGRATE_HIGHATOMIC );if (!page) {
mm/page_alloc.h +3 -0
@@ -60,6 +60,9 @@/* Flags that allow allocations below the min watermark. */ #define ALLOC_RESERVES (ALLOC_NON_BLOCK|ALLOC_MIN_RESERVE|ALLOC_HIGHATOMIC|ALLOC_OOM) +/* Flags that mean GFP_ATOMIC */ +#define ALLOC_MASK_ATOMIC (ALLOC_NON_BLOCK|ALLOC_MIN_RESERVE) +/* * Structure for holding the mostly immutable allocation parameters passed * between functions involved in allocations, including the alloc_pages*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 242/507 mm: page_alloc: remove ALLOC_NON_BLOCK from ALLOC_RESERVES
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johannes Weiner <[email protected]>
[ Upstream commit fe21f930d1e64d121191673076fc4ebe79fc82d5 ]
1ebbb21811b7 ("mm/page_alloc: explicitly define how __GFP_HIGH non-blocking allocations accesses reserves") stopped handing out reserve access for ALLOC_NON_BLOCK on its own: the extra 25% below the min watermark is now only granted on top of ALLOC_MIN_RESERVE. But the flag was left in ALLOC_RESERVES, which produces something odd:
With the ALLOC_RESERVES match, __zone_watermark_unusable_free() doesn't subtract the free highatomic pages for them. So in the slowpath, they get to consume regular blocks below the min watermark by the number of free highatomic pages. The highatomic reserve is capped at 1% of the zone, which on any decently sized machine is a multiple of the min watermark:GFP_NOWAIT can drain regular memory to zero.
The user-visible result is brutal hiccups during bursts of GFP_NOWAIT allocations under memory pressure. This was found in review and reproduced with a synthetic burst, not observed in production, but the sequence of events is a realistic one: On a 32G box with an anonymous working set, swap, and a filled 290M highatomic reserve, a GFP_NOWAIT burst drove regular free memory in the 28G Normal zone (min=60M) to 28M, 0.8M and 0.6M in three runs. Swapout failed to allocate its swap table, reclaim scanned 13M pages to reclaim 200k, page faults stalled for tens to hundreds of milliseconds. The machine survives it, but not by design:
direct reclaimers eventually fail and start unreserving highatomic blocks, until the allocation succeeds or the reserve is gone and the OOM killer runs. That reserve exists for high-order atomic allocations; here it is destroyed to bail out a GFP_NOWAIT consumer that was never entitled to the memory.
Remove ALLOC_NON_BLOCK from ALLOC_RESERVES. With that, the GFP_NOWAIT burst is stopped short at the min watermark. No direct reclaim, no stalls, no failed allocations, and the highatomic reserve stays intact for the requests it exists for.
__zone_watermark_ok() is unaffected, since everything it keys on ALLOC_NON_BLOCK is already nested under ALLOC_MIN_RESERVE. Update the flag comments accordingly: ALLOC_NON_BLOCK just means the caller can't block; the reserve math belongs with ALLOC_MIN_RESERVE.
GFP_ATOMIC order-0 requests have a milder version of the same problem. Through ALLOC_MIN_RESERVE they also count the free highatomic pages in their watermark check, but rmqueue_buddy() serves them regular pages first and only falls back to the reserve once those are gone. They can still push regular free memory to 37.5% of min minus the free highatomic pages before the reserve is touched. Unlike GFP_NOWAIT they are entitled to the reserve, so this needs the watermark check and the freelist order reworked together, and is left to a separate patch.
--- mm/page_alloc.h | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
mm/page_alloc.h +5 -6
@@ -32,12 +32,11 @@#define ALLOC_OOM ALLOC_NO_WATERMARKS#endif -#define ALLOC_NON_BLOCK 0x10/* Caller cannot block. Allow access -* to 25% of the min watermark or -* 62.5% if __GFP_HIGH is set. -*/ +#define ALLOC_NON_BLOCK 0x10/* Caller cannot block. */ #define ALLOC_MIN_RESERVE 0x20/* __GFP_HIGH set. Allow access to 50% -* of the min watermark. +* of the min watermark, or 62.5% if +* the caller cannot block either +* (ALLOC_NON_BLOCK). */ #define ALLOC_CPUSET 0x40/* check for correct cpuset */ #define ALLOC_CMA 0x80/* allow allocations from CMA areas */
@@ -58,7 +57,7 @@#define ALLOC_NO_CODETAG 0x1000/* Flags that allow allocations below the min watermark. */ -#define ALLOC_RESERVES (ALLOC_NON_BLOCK|ALLOC_MIN_RESERVE|ALLOC_HIGHATOMIC|ALLOC_OOM) +#define ALLOC_RESERVES (ALLOC_MIN_RESERVE|ALLOC_HIGHATOMIC|ALLOC_OOM)/* Flags that mean GFP_ATOMIC */ #define ALLOC_MASK_ATOMIC (ALLOC_NON_BLOCK|ALLOC_MIN_RESERVE)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 243/507 mm/cma: accept memory of multi-range CMA areas
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mike Rapoport (Microsoft) <[email protected]>
[ Upstream commit 5d002001601a163b6c3500cdc098ff66c34f62d8 ]
Patch series "mm/cma: accept memory of CMA areas reserved with memblock_reserve()", v1.
Pages of allocated CMA areas are released to the buddy allocator with __free_pages(), which does not check for unaccepted memory.
This usually works because memblock accepts the memory it allocates.
However, multi-range CMA areas, used by hugetlb_cma, and fixed CMA areas requested with cma=<size>@<base> are reserved with memblock_reserve() and their memory is never accepted.
On TDX and SEV-SNP guests the first access to such a page is fatal.
To ease the backporting, each case is addressed by a separate patch:
- patch 1 accepts the memory of multi-range CMA areas
- patch 2 does the same for the fixed CMA areas
The second patch won't apply cleanly to 6.6 and 6.12, but I believe the stable team LLMs will take care of that :)
This patch (of 2):
On systems with unaccepted memory, memblock allocations accept the allocated range, but when cma_declare_contiguous_multi() uses open coded allocation of multiple ranges, it reserves them with memblock_reserve() and they are never accepted.
These pages are released to the buddy allocator by cma_activate_area() with __free_pages() that does not check for unaccepted memory, so the first access to such a page in a TDX or SEV-SNP guest is fatal.
Accept the memory of each range when it is reserved.
--- mm/cma.c | 2 ++ 1 file changed, 2 insertions(+)
mm/cma.c +2 -0
@@ -678,6 +678,8 @@ int __init cma_declare_contiguous_multi(phys_addr_t total_size,break ; } +accept_memory (mlp->base, size); +pr_debug ("created region %d: %016llx - %016llx\n" , nr, (u64 )mlp->base, (u64 )mlp->base + size); cmrp = &cma->ranges[nr++];
Signature · 1 line
2.53.0