7.3.4-rc1 review
Subsystems (3)
Greg Kroah-Hartman
maintainerPATCH 967/1257 drm/amd/pm:restate all customized OD features on every table upload for smu 13.0.0/smu 14.0.2
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kenneth Feng <[email protected]>
[ Upstream commit 44d0d3031e47973ed65fd327669d5e2eaaf6c565 ]
PMFW interprets OverDriveTable.FeatureCtrlMask as the complete set of overdrive features that are currently overridden, not as a delta describing the operation at hand. On import it resets every feature whose bit is clear back to its default value - for the VF curve that means zeroing VoltageOffsetPerZoneBoundary[] outright.
The driver assumed the opposite. smu_v14_0_2_od_edit_dpm_table() clears the mask after a successful commit, so a subsequent above-default power1_cap write goes through smu_v14_0_2_set_ppt_limit() and uploads a table carrying only PP_OD_FEATURE_PPT_BIT. PMFW then drops the user's voltage offset and reverts to the stock V/F curve, while the driver's cached user table still reports the offset through pp_od_clk_voltage.
--- drivers/gpu/drm/amd/pm/swsmu/inc/amdgpu_smu.h | 2 + .../drm/amd/pm/swsmu/smu13/smu_v13_0_0_ppt.c | 35 +++++++---------- .../drm/amd/pm/swsmu/smu13/smu_v13_0_7_ppt.c | 32 +++++++--------- .../drm/amd/pm/swsmu/smu14/smu_v14_0_2_ppt.c | 38 +++++++++++-------- 4 files changed, 52 insertions(+), 55 deletions(-)
drivers/gpu/drm/amd/pm/swsmu/inc/amdgpu_smu.h +2 -0
@@ -433,6 +433,8 @@ struct smu_table_context {void *boot_overdrive_table;void *user_overdrive_table; +uint32_t user_od_feature_mask; +struct smu_driver_table driver_tables[SMU_DRIVER_TABLE_COUNT ]; };
drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_0_ppt.c +14 -21
@@ -1569,7 +1569,6 @@ static int smu_v13_0_0_od_edit_dpm_table(struct smu_context *smu,struct amdgpu_device *adev = smu->adev;uint32_t offset_of_voltageoffset;int32_t minimum, maximum; -uint32_t feature_ctrlmask;int i, ret =0 ;switch (type) {
@@ -1891,21 +1890,16 @@ static int smu_v13_0_0_od_edit_dpm_table(struct smu_context *smu,if (ret)return ret; }else { - feature_ctrlmask = od_table->OverDriveTable.FeatureCtrlMask;memcpy (od_table, table_context->boot_overdrive_table,sizeof (OverDriveTableExternal_t)); - od_table->OverDriveTable.FeatureCtrlMask = feature_ctrlmask; + od_table->OverDriveTable.FeatureCtrlMask =0 ; + table_context->user_od_feature_mask =0 ; } fallthrough;case PP_OD_COMMIT_DPM_TABLE : -/* -* The member below instructs PMFW the settings focused in -* this single operation. -* `uint32_t FeatureCtrlMask;` -* It does not contain actual informations about user's custom -* settings. Thus we do not cache it. -*/ + table_context->user_od_feature_mask = + od_table->OverDriveTable.FeatureCtrlMask; offset_of_voltageoffset = offsetof(OverDriveTable_t , VoltageOffsetPerZoneBoundary); if (memcmp((u8 *)od_table + offset_of_voltageoffset, table_context->user_overdrive_table + offset_of_voltageoffset,
@@ -1918,7 +1912,6 @@ static int smu_v13_0_0_od_edit_dpm_table(struct smu_context *smu,return ret; } - od_table->OverDriveTable.FeatureCtrlMask =0 ;memcpy (table_context->user_overdrive_table + offset_of_voltageoffset, (u8 *)od_table + offset_of_voltageoffset,sizeof (OverDriveTableExternal_t) - offset_of_voltageoffset);
@@ -2201,6 +2194,7 @@ static int smu_v13_0_0_set_default_od_settings(struct smu_context *smu) boot_od_table, sizeof(OverDriveTableExternal_t)); smu->user_dpm_profile.user_od = false; + smu->smu_table.user_od_feature_mask =0 ; }else if (smu->user_dpm_profile.user_od) { memcpy(&user_od_table_bak, user_od_table,
@@ -2250,12 +2244,8 @@ static int smu_v13_0_0_restore_user_od_settings(struct smu_context *smu)OverDriveTableExternal_t *od_table = table_context->overdrive_table;OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table;int res; - - user_od_table->OverDriveTable.FeatureCtrlMask =BIT (PP_OD_FEATURE_GFXCLK_BIT ) | -BIT (PP_OD_FEATURE_UCLK_BIT ) | -BIT (PP_OD_FEATURE_GFX_VF_CURVE_BIT ) | -BIT (PP_OD_FEATURE_FAN_CURVE_BIT ) | -BIT (PP_OD_FEATURE_ZERO_FAN_BIT ); + user_od_table->OverDriveTable.FeatureCtrlMask = + table_context->user_od_feature_mask; res =smu_v13_0_0_upload_overdrive_table (smu, user_od_table); user_od_table->OverDriveTable.FeatureCtrlMask =0 ;if (res ==0 )
@@ -3069,8 +3059,10 @@ static int smu_v13_0_0_set_ppt_limit(struct smu_context *smu,if (current_od_table.OverDriveTable.Ppt) { od_table->OverDriveTable.Ppt =0 ; - od_table->OverDriveTable.FeatureCtrlMask |=1U <<PP_OD_FEATURE_PPT_BIT ; - + table_context->user_od_feature_mask &= + ~(1U <<PP_OD_FEATURE_PPT_BIT ); + od_table->OverDriveTable.FeatureCtrlMask = + table_context->user_od_feature_mask; ret =smu_v13_0_0_upload_overdrive_table (smu, od_table);if (ret) {dev_err (smu->adev->dev,"Failed to upload overdrive table!\n" );
@@ -3084,8 +3076,9 @@ static int smu_v13_0_0_set_ppt_limit(struct smu_context *smu,return ret; od_table->OverDriveTable.Ppt = (limit *100 ) / msg_limit -100 ; - od_table->OverDriveTable.FeatureCtrlMask |=1U <<PP_OD_FEATURE_PPT_BIT ; - + table_context->user_od_feature_mask |=1U <<PP_OD_FEATURE_PPT_BIT ; + od_table->OverDriveTable.FeatureCtrlMask = + table_context->user_od_feature_mask; ret =smu_v13_0_0_upload_overdrive_table (smu, od_table);if (ret) {dev_err (smu->adev->dev,"Failed to upload overdrive table!\n" );
drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_7_ppt.c +14 -18
@@ -1578,7 +1578,6 @@ static int smu_v13_0_7_od_edit_dpm_table(struct smu_context *smu,struct amdgpu_device *adev = smu->adev;uint32_t offset_of_voltageoffset;int32_t minimum, maximum; -uint32_t feature_ctrlmask;int i, ret =0 ;switch (type) {
@@ -1900,22 +1899,17 @@ static int smu_v13_0_7_od_edit_dpm_table(struct smu_context *smu,if (ret)return ret; }else { - feature_ctrlmask = od_table->OverDriveTable.FeatureCtrlMask;memcpy (od_table, table_context->boot_overdrive_table,sizeof (OverDriveTableExternal_t)); - od_table->OverDriveTable.FeatureCtrlMask = feature_ctrlmask; + od_table->OverDriveTable.FeatureCtrlMask =0 ; + table_context->user_od_feature_mask =0 ; } fallthrough;case PP_OD_COMMIT_DPM_TABLE : -/* -* The member below instructs PMFW the settings focused in -* this single operation. -* `uint32_t FeatureCtrlMask;` -* It does not contain actual informations about user's custom -* settings. Thus we do not cache it. -*/ + table_context->user_od_feature_mask = + od_table->OverDriveTable.FeatureCtrlMask; offset_of_voltageoffset = offsetof(OverDriveTable_t , VoltageOffsetPerZoneBoundary); if (memcmp((u8 *)od_table + offset_of_voltageoffset, table_context->user_overdrive_table + offset_of_voltageoffset,
@@ -1928,7 +1922,6 @@ static int smu_v13_0_7_od_edit_dpm_table(struct smu_context *smu,return ret; } - od_table->OverDriveTable.FeatureCtrlMask =0 ;memcpy (table_context->user_overdrive_table + offset_of_voltageoffset, (u8 *)od_table + offset_of_voltageoffset,sizeof (OverDriveTableExternal_t) - offset_of_voltageoffset);
@@ -2203,6 +2196,7 @@ static int smu_v13_0_7_set_default_od_settings(struct smu_context *smu) boot_od_table, sizeof(OverDriveTableExternal_t)); smu->user_dpm_profile.user_od = false; + smu->smu_table.user_od_feature_mask =0 ; }else if (smu->user_dpm_profile.user_od) { memcpy(&user_od_table_bak, user_od_table,
@@ -2253,11 +2247,8 @@ static int smu_v13_0_7_restore_user_od_settings(struct smu_context *smu)OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table;int res; - user_od_table->OverDriveTable.FeatureCtrlMask =BIT (PP_OD_FEATURE_GFXCLK_BIT ) | -BIT (PP_OD_FEATURE_UCLK_BIT ) | -BIT (PP_OD_FEATURE_GFX_VF_CURVE_BIT ) | -BIT (PP_OD_FEATURE_FAN_CURVE_BIT ) | -BIT (PP_OD_FEATURE_ZERO_FAN_BIT ); + user_od_table->OverDriveTable.FeatureCtrlMask = + table_context->user_od_feature_mask; res =smu_v13_0_7_upload_overdrive_table (smu, user_od_table); user_od_table->OverDriveTable.FeatureCtrlMask =0 ;if (res ==0 )
@@ -2689,7 +2680,10 @@ static int smu_v13_0_7_set_ppt_limit(struct smu_context *smu,if (current_od_table.OverDriveTable.Ppt) { od_table->OverDriveTable.Ppt =0 ; - od_table->OverDriveTable.FeatureCtrlMask |=1U <<PP_OD_FEATURE_PPT_BIT ; + table_context->user_od_feature_mask &= + ~(1U <<PP_OD_FEATURE_PPT_BIT ); + od_table->OverDriveTable.FeatureCtrlMask = + table_context->user_od_feature_mask; ret =smu_v13_0_7_upload_overdrive_table (smu, od_table);if (ret) {
@@ -2704,7 +2698,9 @@ static int smu_v13_0_7_set_ppt_limit(struct smu_context *smu,return ret; od_table->OverDriveTable.Ppt = (limit *100 ) / msg_limit -100 ; - od_table->OverDriveTable.FeatureCtrlMask |=1U <<PP_OD_FEATURE_PPT_BIT ; + table_context->user_od_feature_mask |=1U <<PP_OD_FEATURE_PPT_BIT ; + od_table->OverDriveTable.FeatureCtrlMask = + table_context->user_od_feature_mask; ret =smu_v13_0_7_upload_overdrive_table (smu, od_table);if (ret) {
drivers/gpu/drm/amd/pm/swsmu/smu14/smu_v14_0_2_ppt.c +22 -16
@@ -2385,6 +2385,7 @@ static int smu_v14_0_2_set_default_od_settings(struct smu_context *smu) boot_od_table, sizeof(OverDriveTableExternal_t)); smu->user_dpm_profile.user_od = false; + smu->smu_table.user_od_feature_mask =0 ; }else if (smu->user_dpm_profile.user_od) { memcpy(&user_od_table_bak, user_od_table,
@@ -2433,11 +2434,8 @@ static int smu_v14_0_2_restore_user_od_settings(struct smu_context *smu)OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table;int res; - user_od_table->OverDriveTable.FeatureCtrlMask =BIT (PP_OD_FEATURE_GFXCLK_BIT ) | -BIT (PP_OD_FEATURE_UCLK_BIT ) | -BIT (PP_OD_FEATURE_GFX_VF_CURVE_BIT ) | -BIT (PP_OD_FEATURE_FAN_CURVE_BIT ) | -BIT (PP_OD_FEATURE_ZERO_FAN_BIT ); + user_od_table->OverDriveTable.FeatureCtrlMask = + table_context->user_od_feature_mask; res =smu_v14_0_2_upload_overdrive_table (smu, user_od_table); user_od_table->OverDriveTable.FeatureCtrlMask =0 ;if (res ==0 )
@@ -2522,7 +2520,6 @@ static int smu_v14_0_2_od_edit_dpm_table(struct smu_context *smu,struct amdgpu_device *adev = smu->adev;uint32_t offset_of_voltageoffset;int32_t minimum, maximum; -uint32_t feature_ctrlmask;int i, ret =0 ;switch (type) {
@@ -2811,21 +2808,26 @@ static int smu_v14_0_2_od_edit_dpm_table(struct smu_context *smu,if (ret)return ret; }else { - feature_ctrlmask = od_table->OverDriveTable.FeatureCtrlMask;memcpy (od_table, table_context->boot_overdrive_table,sizeof (OverDriveTableExternal_t)); - od_table->OverDriveTable.FeatureCtrlMask = feature_ctrlmask; + od_table->OverDriveTable.FeatureCtrlMask =0 ; + table_context->user_od_feature_mask =0 ; } fallthrough;case PP_OD_COMMIT_DPM_TABLE :/* -* The member below instructs PMFW the settings focused in -* this single operation. -* `uint32_t FeatureCtrlMask;` -* It does not contain actual informations about user's custom -* settings. Thus we do not cache it. +* PMFW interprets FeatureCtrlMask as the complete set of OD +* features that are currently overridden, not as a delta +* describing this single operation. Any feature whose bit is +* clear gets reset to its default on import. od_table's mask +* has accumulated every feature the user touched since the +* last full restore, so record it and keep restating it on +* subsequent uploads. */ + table_context->user_od_feature_mask = + od_table->OverDriveTable.FeatureCtrlMask; + offset_of_voltageoffset = offsetof(OverDriveTable_t , VoltageOffsetPerZoneBoundary); if (memcmp((u8 *)od_table + offset_of_voltageoffset, table_context->user_overdrive_table + offset_of_voltageoffset,
@@ -2838,7 +2840,6 @@ static int smu_v14_0_2_od_edit_dpm_table(struct smu_context *smu,return ret; } - od_table->OverDriveTable.FeatureCtrlMask =0 ;memcpy (table_context->user_overdrive_table + offset_of_voltageoffset, (u8 *)od_table + offset_of_voltageoffset,sizeof (OverDriveTableExternal_t) - offset_of_voltageoffset);
@@ -2882,7 +2883,10 @@ static int smu_v14_0_2_set_ppt_limit(struct smu_context *smu,if (current_od_table.OverDriveTable.Ppt) { od_table->OverDriveTable.Ppt =0 ; - od_table->OverDriveTable.FeatureCtrlMask |=1U <<PP_OD_FEATURE_PPT_BIT ; + table_context->user_od_feature_mask &= + ~(1U <<PP_OD_FEATURE_PPT_BIT ); + od_table->OverDriveTable.FeatureCtrlMask = + table_context->user_od_feature_mask; ret =smu_v14_0_2_upload_overdrive_table (smu, od_table);if (ret) {
@@ -2897,7 +2901,9 @@ static int smu_v14_0_2_set_ppt_limit(struct smu_context *smu,return ret; od_table->OverDriveTable.Ppt = (limit *100 ) / msg_limit -100 ; - od_table->OverDriveTable.FeatureCtrlMask |=1U <<PP_OD_FEATURE_PPT_BIT ; + table_context->user_od_feature_mask |=1U <<PP_OD_FEATURE_PPT_BIT ; + od_table->OverDriveTable.FeatureCtrlMask = + table_context->user_od_feature_mask; ret =smu_v14_0_2_upload_overdrive_table (smu, od_table);if (ret) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 968/1257 amdkfd: Fix memory availability double accounting of kfd pinned objects
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daniel Phillips <[email protected]>
[ Upstream commit 16df12d7158fb55f20d6e985abd1996cbabab9f8 ]
Pinned objects that are not kfd objects reduce the total vram available to kfd, so we subtract the total size of pinned objects from kdf vram availability. However this double counts objects pinned by kfd itself, because they are counted both as used and pinned. So track the total size of objects pinned by kfd and add it back to kfd availability to remove the double accounting.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h | 1 + drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c | 11 +++++++++++ 2 files changed, 12 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h +1 -0
@@ -106,6 +106,7 @@ struct amdgpu_kfd_dev {struct kfd_dev *dev;int64_t vram_used[MAX_XCP ];uint64_t vram_used_aligned[MAX_XCP ]; +atomic64_t vram_pinned;bool init_complete;struct work_struct reset_work;
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +11 -0
@@ -1536,6 +1536,11 @@ static int amdgpu_amdkfd_gpuvm_pin_bo(struct amdgpu_bo *bo, u32 domain)pr_err ("Error in Pinning BO to domain: %d\n" , domain);amdgpu_bo_sync_wait (bo,AMDGPU_FENCE_OWNER_KFD , false); + +if (!ret && bo->tbo.resource->mem_type ==TTM_PL_VRAM ) +atomic64_add (amdgpu_bo_size (bo), + &amdgpu_ttm_adev (bo->tbo.bdev)->kfd.vram_pinned); + out:amdgpu_bo_unreserve (bo);return ret;
@@ -1558,6 +1563,11 @@ static void amdgpu_amdkfd_gpuvm_unpin_bo(struct amdgpu_bo *bo)return ;amdgpu_bo_unpin (bo); + +if (bo->tbo.resource->mem_type ==TTM_PL_VRAM ) +atomic64_sub (amdgpu_bo_size (bo), + &amdgpu_ttm_adev (bo->tbo.bdev)->kfd.vram_pinned); +amdgpu_bo_unreserve (bo); }
@@ -1679,6 +1689,7 @@ size_t amdgpu_amdkfd_get_available_memory(struct amdgpu_device *adev, vram_available =KFD_XCP_MEMORY_SIZE (adev, xcp_id) - adev->kfd.vram_used_aligned[xcp_id] -atomic64_read (&adev->vram_pin_size) + +atomic64_read (&adev->kfd.vram_pinned) - reserved_for_pt - reserved_for_ras;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 969/1257 drm/amdkfd: correct vram_available calculation
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhen Han <[email protected]>
[ Upstream commit 9131cc85d0dedd8ba4cae60dbe5985d081551f30 ]
reserve_mem_limit() computes available VRAM as
vram_size - reserved - vram_pin_size - kfd.vram_used
However, kfd.vram_used already includes BOs that are later pinned. Pinning does not consume extra VRAM. Subtracting vram_pin_size counts those bytes twice and causes fake-OOM while VRAM is still free.
Reuse get_available_memory() in reserve_mem_limit(). Move ALIGN_DOWN to the ioctl so the userspace ABI is unchanged. The VRAM counter is a parameter: the ioctl passes vram_used_aligned[], the gate passes vram_used[] so a 4K BO is not charged 2MB.
kfd.vram_pinned is only updated in gpuvm_pin_bo(). dma-buf pin calls amdgpu_bo_pin() only, so the counter stays zero. Update it from amdgpu_bo_pin() through a KFD helper, on first pin and last unpin, matching vram_pin_size.
Track per-XCP pins in vram_pin_size_xcp[] and kfd.vram_pinned[]. Pins that are not owned by a single partition go to vram_pin_size_common, which every partition subtracts.
A KFD VRAM BO always carries a partition, so the KFD credit is only correct for xcp >= 0. Call the helper for both branches and let it warn once and skip if that ever stops holding: without the credit the BO would be subtracted through vram_pin_size_common and never added back, which is the double counting this patch removes, and kfd.vram_pinned[] would be indexed out of bounds.
--- drivers/gpu/drm/amd/amdgpu/amdgpu.h | 11 ++- drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h | 20 +++- .../gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c | 94 +++++++++++-------- drivers/gpu/drm/amd/amdgpu/amdgpu_object.c | 33 +++++++ drivers/gpu/drm/amd/amdkfd/kfd_chardev.c | 12 ++- 5 files changed, 127 insertions(+), 43 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu.h +10 -1
@@ -834,8 +834,17 @@ struct amdgpu_device {struct mutex mn_lock;DECLARE_HASHTABLE (mn_hash,7 ); -/* tracking pinned memory */ +/* tracking pinned memory +* +* vram_pin_size = sum(vram_pin_size_xcp[]) + vram_pin_size_common +* +* vram_pin_size total pin size in device +* vram_pin_size_xcp[i] pins owned by partition i (bo->xcp_id = i, i >= 0) +* vram_pin_size_common pins not owned by any partition, bo->xcp_id = -1 +*/ atomic64_t vram_pin_size; +atomic64_t vram_pin_size_xcp[MAX_XCP ]; +atomic64_t vram_pin_size_common;atomic64_t visible_pin_size;atomic64_t gart_pin_size;
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h +19 -1
@@ -42,6 +42,12 @@extern uint64_t amdgpu_amdkfd_total_mem_size; +/* +* Align VRAM availability to 2MB to avoid fragmentation caused by 4K +* allocations in the tail 2MB BO chunk. +*/ +#define VRAM_AVAILABLITY_ALIGN (1 << 21) +enum TLB_FLUSH_TYPE {TLB_FLUSH_LEGACY =0 ,TLB_FLUSH_LIGHTWEIGHT ,
@@ -106,7 +112,7 @@ struct amdgpu_kfd_dev {struct kfd_dev *dev;int64_t vram_used[MAX_XCP ];uint64_t vram_used_aligned[MAX_XCP ]; -atomic64_t vram_pinned; +atomic64_t vram_pinned[MAX_XCP ];bool init_complete;struct work_struct reset_work;
@@ -391,6 +397,8 @@ void amdgpu_amdkfd_gpuvm_destroy_cb(struct amdgpu_device *adev,* Allows KFD to release its resources associated with the GEM object. */ void amdgpu_amdkfd_release_notify (struct amdgpu_bo *bo); +void amdgpu_amdkfd_account_vram_pin (struct amdgpu_bo *bo,int xcp_id); +void amdgpu_amdkfd_account_vram_unpin (struct amdgpu_bo *bo,int xcp_id);void amdgpu_amdkfd_reserve_system_mem (uint64_t size);#else static inline
@@ -408,6 +416,16 @@ static inlinevoid amdgpu_amdkfd_release_notify (struct amdgpu_bo *bo) { } + +static inline +void amdgpu_amdkfd_account_vram_pin (struct amdgpu_bo *bo,int xcp_id) +{ +} + +static inline +void amdgpu_amdkfd_account_vram_unpin (struct amdgpu_bo *bo,int xcp_id) +{ +}#endif #if IS_ENABLED (CONFIG_HSA_AMD_SVM )
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +55 -39
175 lines not on this page · raw message
drivers/gpu/drm/amd/amdgpu/amdgpu_object.c +33 -0
@@ -915,6 +915,19 @@ void amdgpu_bo_unref(struct amdgpu_bo **bo) *bo =NULL ; } +/* Map a BO onto vram_pin_size_xcp[]. bo->xcp_id < 0 means "any partition": +* such pins are not owned by a single partition and go to +* vram_pin_size_common, which every partition subtracts. +*/ +static int amdgpu_bo_get_xcp (struct amdgpu_bo *bo) +{ +s8 xcp = bo->xcp_id; + +if (xcp >=0 && xcp <MAX_XCP ) +return xcp; +return -1 ; +} +/** * amdgpu_bo_pin - pin an &amdgpu_bo buffer object * @bo: &amdgpu_bo buffer object to be pinned
@@ -995,7 +1008,17 @@ int amdgpu_bo_pin(struct amdgpu_bo *bo, u32 domain)ttm_bo_pin (&bo->tbo);if (bo->tbo.resource->mem_type ==TTM_PL_VRAM ) { +int xcp =amdgpu_bo_get_xcp (bo); +atomic64_add (amdgpu_bo_size (bo), &adev->vram_pin_size); +if (xcp >=0 ) { +atomic64_add (amdgpu_bo_size (bo), + &adev->vram_pin_size_xcp[xcp]); + }else { +atomic64_add (amdgpu_bo_size (bo), + &adev->vram_pin_size_common); + } +amdgpu_amdkfd_account_vram_pin (bo, xcp);atomic64_add (amdgpu_vram_mgr_bo_visible_size (bo), &adev->visible_pin_size); }else if (bo->tbo.resource->mem_type ==TTM_PL_TT ) {
@@ -1028,7 +1051,17 @@ void amdgpu_bo_unpin(struct amdgpu_bo *bo)dma_buf_unpin (bo->tbo.base.import_attach);if (bo->tbo.resource->mem_type ==TTM_PL_VRAM ) { +int xcp =amdgpu_bo_get_xcp (bo); +atomic64_sub (amdgpu_bo_size (bo), &adev->vram_pin_size); +if (xcp >=0 ) { +atomic64_sub (amdgpu_bo_size (bo), + &adev->vram_pin_size_xcp[xcp]); + }else { +atomic64_sub (amdgpu_bo_size (bo), + &adev->vram_pin_size_common); + } +amdgpu_amdkfd_account_vram_unpin (bo, xcp);atomic64_sub (amdgpu_vram_mgr_bo_visible_size (bo), &adev->visible_pin_size); }else if (bo->tbo.resource->mem_type ==TTM_PL_TT ) {
drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +10 -2
@@ -1110,11 +1110,19 @@ static int kfd_ioctl_get_available_memory(struct file *filep, {struct kfd_ioctl_get_available_memory_args *args = data;struct kfd_process_device *pdd =kfd_lock_pdd_by_id (p, args->gpu_id); +struct amdgpu_device *adev; +size_t available;if (!pdd)return -EINVAL ; - args->available =amdgpu_amdkfd_get_available_memory (pdd->dev->adev, - pdd->dev->node_id); + + adev = pdd->dev->adev; + available =amdgpu_amdkfd_get_available_memory (adev, pdd->dev->node_id); +if (adev->apu_prefer_gtt) + args->available =ALIGN_DOWN (available,PAGE_SIZE ); +else + args->available =ALIGN_DOWN (available,VRAM_AVAILABLITY_ALIGN ); +kfd_unlock_pdd (pdd);return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 970/1257 netdev: Hide the netdev_priv() origin from GCC in netdev_from_priv()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kees Cook <[email protected]>
[ Upstream commit 56f8d919739b588e2ad8cb9fb9eff704f32afaab ]
GCC 15.1 and later can compute an object size of 0 for a pointer that container_of() derives from a pointer into a __counted_by flexible array member[1]; Clang gets it right. netdev_from_priv() does this with struct net_device's "priv" array, so when GCC can see that its argument came from netdev_priv(), FORTIFY_SOURCE sees a zero-sized net_device. Since commit 9027497a25e3c ("team: use netdev_from_priv()"), adding a port of another type to a team device can then fail the memcpy() to "dev->broadcast" in team_setup_by_port(), which GCC sees through after inlining team_port_add() into team_add_slave():
memcpy: detected buffer overflow: 4 byte write of buffer size 0
...
kernel BUG at lib/string_helpers.c:1044!
...
Call Trace: <TASK> team_add_slave.cold+0x88/0x201 do_set_master+0x11c/0x180 do_setlink.isra.0+0x3a4/0x1410
Whether GCC inlines that far depends on the architecture and the configuration. It does on ppc64le, where this was reported, and on x86_64 with defconfig plus hardening.config or with Debian's configuration, but not with allmodconfig.
Hide where "priv" came from with OPTIMIZER_HIDE_VAR(), so GCC sees a net_device of unknown size whose members have their declared sizes. (An "unknown" size is considered uncheckable by FORTIFY.) FORTIFY still bounds writes to members; only the whole-object size becomes unknown, as it already is for any net_device pointer GCC can't trace to its allocation. In an extracted PoC, the __builtin_dynamic_object_size() of "dev->broadcast" for the two types FORTIFY sees, before and after this patch:
GCC 16.2.0 Clang 22 and 24
before after
plain pointer, whole object unknown unknown 44
container_of(), whole object 0 unknown 44
container_of(), member 0 32 32In addition to getting the bogus "0" fixed in GCC, I'll be following up to solve the whole-object visiblity disparity as well.
Build tested with GCC 16.2.0: ARCH=x86_64 defconfig with hardening.config, CONFIG_NET_TEAM=y, and CONFIG_NET_IPGRE=y; ARCH=arm64 defconfig with hardening.config, CONFIG_NET_TEAM=y, CONFIG_PPP=y, and CONFIG_NET_AIROHA=m; and drivers/net/team/, drivers/net/ppp/, and drivers/net/ethernet/airoha/ in ARCH=x86_64 allmodconfig. Under QEMU, the x86_64 kernel hits the BUG above when adding the GRE fallback device "gre0" as a port of a new team device without this patch, and adds it with the patch.
--- include/linux/netdevice.h | 7 +++++++ 1 file changed, 7 insertions(+)
include/linux/netdevice.h +7 -0
@@ -2841,6 +2841,13 @@ static inline void *netdev_priv(const struct net_device *dev)*/ static inline struct net_device *netdev_from_priv (const void *priv) { +/* +* When GCC can see that @priv came from netdev_priv(), it can +* compute an object size of 0 for the net_device and its members, +* which makes FORTIFY_SOURCE fail valid accesses through the result: +* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=127875 +*/ +OPTIMIZER_HIDE_VAR (priv); return container_of(priv, struct net_device, priv); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 971/1257 ipv6: remove ifaddr from hash during ifdown list cleanup
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
[ Upstream commit 6ace56ed7b13a9c6d4cb7ef0d82d3a3d53324a63 ]
addrconf_ifdown() clears the address hash before snapshotting the per-device address list. A concurrent ipv6_add_addr() can publish an address after the hash scan and before the list snapshot.
The ifdown path then removes the address from the device list and drops the list-owned reference while it is still linked in the hash. Once the remaining references are released, inet6_ifa_finish_destroy() warns, but a DEAD address continues to kfree_rcu(). The hash therefore points to freed memory that later RCU walkers can dereference.
This follow-on was found by source review and was not separately triggered at runtime.
Remove each non-kept address from the hash immediately before removing it from the per-device list. Keeping it hashed through the delete notification blocks same-address publication until NETDEV_DOWN has been delivered. hlist_del_init_rcu() is safe when the earlier hash scan already removed the address.
This handles a late publisher captured by the list snapshot. The next change serializes publication with teardown so an add cannot miss both observations. Both changes are required when backporting the complete fix.
--- net/ipv6/addrconf.c | 4 ++++ 1 file changed, 4 insertions(+)
net/ipv6/addrconf.c +4 -0
@@ -4019,6 +4019,10 @@ static int addrconf_ifdown(struct net_device *dev, bool unregister) }if (!keep) { +spin_lock_bh (&net->ipv6.addrconf_hash_lock); +hlist_del_init_rcu (&ifa->addr_lst); +spin_unlock_bh (&net->ipv6.addrconf_hash_lock); +write_lock_bh (&idev->lock);list_del_rcu (&ifa->if_list);write_unlock_bh (&idev->lock);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 972/1257 ipv6: serialize address publication with device teardown
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
[ Upstream commit 06227034e2d93942119b922cf05f2de9da0ad848 ]
ipv6_add_addr() checks idev state before allocating an ifaddr, but publishes the object later. addrconf_ifdown() can mark and detach the idev between the check and publication.
This happens when a non-loopback device MTU falls below IPV6_MIN_MTU. A forced interleaving published an address on a dead idev, and ipv6_get_ifaddr() still returned it after teardown. Later device deletion remained blocked with:
unregister_netdevice: waiting for ac0 to become free. Usage count = 3
Protect the dead indication with idev->lock and keep that lock across both hash and device-list publication. Recheck dead before publishing; if teardown wins the lock, reject the unpublished object.
Non-unregister teardown does not set dead. The preceding change covers an add that misses the initial hash scan but reaches the per-device list snapshot. Both changes are required when backporting this fix.
--- net/ipv6/addrconf.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
net/ipv6/addrconf.c +9 -3
@@ -1168,14 +1168,18 @@ ipv6_add_addr(struct inet6_dev *idev, struct ifa6_config *cfg,rcu_read_lock (); - err =ipv6_add_addr_hash (idev->dev, ifa); +write_lock_bh (&idev->lock); + +if (idev->dead) + err = -ENODEV ; +else + err =ipv6_add_addr_hash (idev->dev, ifa);if (err <0 ) { +write_unlock_bh (&idev->lock);rcu_read_unlock (); goto out; } -write_lock_bh (&idev->lock); -/* Add to inet6_dev unicast addr list. */ ipv6_link_dev_addr (idev, ifa);
@@ -3897,7 +3901,9 @@ static int addrconf_ifdown(struct net_device *dev, bool unregister)* Do not dev_put! */ if (unregister) { +write_lock_bh (&idev->lock);WRITE_ONCE (idev->dead,1 ); +write_unlock_bh (&idev->lock);/* protected by rtnl_lock */ RCU_INIT_POINTER (dev->ip6_ptr,NULL );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 973/1257 ipv6: initialize temporary ifaddr before publication
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
[ Upstream commit ed7f278812e540db507f683e5bf9b6d0a1f5bc1e ]
ipv6_create_tempaddr() holds a reference to the public ifaddr, publishes the new temporary address through ipv6_add_addr(), and only then stores the reference and final timestamps.
addrconf_ifdown() can remove the temporary address before ifpub is stored, leaking the public ifaddr reference. Publishing ifpub alone is
insufficient: manage_tempaddrs() can then find the object before cstamp and tstamp are final, update its lifetimes, and have the constructor overwrite its timestamp with an older value.
This follow-on was found by source review and was not separately triggered at runtime.
Pass the public ifaddr and both timestamps in ifa6_config. Initialize all three fields before adding the temporary address to either the hash or per-device lists. On success the existing public-ifaddr reference transfers to the temporary object. On error it remains owned and released by ipv6_create_tempaddr().
--- include/net/addrconf.h | 3 +++ net/ipv6/addrconf.c | 20 +++++++++++++------- 2 files changed, 16 insertions(+), 7 deletions(-)
include/net/addrconf.h +3 -0
@@ -81,6 +81,9 @@ struct ifa6_config {u8 ifa_proto;const struct in6_addr *peer_pfx; +struct inet6_ifaddr *ifpub; +unsigned long cstamp; +unsigned long tstamp;u32 rt_priority;u32 ifa_flags;
net/ipv6/addrconf.c +13 -7
@@ -1155,10 +1155,19 @@ ipv6_add_addr(struct inet6_dev *idev, struct ifa6_config *cfg, ifa->flags |=IFA_F_TENTATIVE ; ifa->valid_lft = cfg->valid_lft; ifa->prefered_lft = cfg->preferred_lft; - ifa->cstamp = ifa->tstamp = jiffies; ifa->tokenized = false; ifa->rt = f6i; + ifa->ifpub = cfg->ifpub; +if (cfg->ifpub) { + ifa->cstamp = cfg->cstamp; + ifa->tstamp = cfg->tstamp; + }else { +unsigned long now = jiffies; + + ifa->cstamp = now; + ifa->tstamp = now; + } ifa->idev = idev;in6_dev_hold (idev);
@@ -1491,6 +1500,9 @@ static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, bool block) cfg.pfx = &addr; cfg.scope =ipv6_addr_scope (cfg.pfx); + cfg.ifpub = ifp; + cfg.cstamp = now; + cfg.tstamp = tmp_tstamp; ift =ipv6_add_addr (idev, &cfg, block,NULL );if (IS_ERR (ift)) {
@@ -1501,12 +1513,6 @@ static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, bool block) goto retry; } -spin_lock_bh (&ift->lock); - ift->ifpub = ifp; - ift->cstamp = now; - ift->tstamp = tmp_tstamp; -spin_unlock_bh (&ift->lock); -addrconf_dad_start (ift);in6_ifa_put (ift);in6_dev_put (idev);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 974/1257 ipv6: do not restart DAD for a dead ifaddr
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
[ Upstream commit ffb668669ce4144347973d8b2fad449e9be0563d ]
addrconf_dad_failure() can create a stable-privacy replacement without RTNL. After ipv6_add_addr() publishes it, addrconf_ifdown() can mark the new ifaddr DEAD, clear its route, and unlink it before the recovery path takes ifp2->lock.
The recovery path then unconditionally changes the state back to PREDAD and queues delayed DAD work. The MTU teardown path can leave IF_READY set. For an optimistic address, addrconf_dad_begin() can consequently pass the cleared NULL route to ip6_ins_rt().
This follow-on was found by source review and was not separately triggered at runtime.
The new ifaddr is already initialized in PREDAD. Under ifp2->lock, record the retry and queue DAD only if teardown has not changed the state to DEAD. If teardown wins after this check, the work observes DEAD and exits without reviving the address.
This complements the existing lock_errdad check that preserves the original ifaddr's DEAD state after the same function reacquires its lock.
--- net/ipv6/addrconf.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
net/ipv6/addrconf.c +7 -3
@@ -2198,6 +2198,7 @@ void addrconf_dad_failure(struct sk_buff *skb, struct inet6_ifaddr *ifp) ifp->idev->dev->name, &ifp->addr, eth_hdr(skb)->h_source);if (ifp->flags &IFA_F_STABLE_PRIVACY ) { +bool start_dad = false;struct in6_addr new_addr;struct inet6_ifaddr *ifp2;int retries = ifp->stable_privacy_retry +1 ;
@@ -2236,11 +2237,14 @@ void addrconf_dad_failure(struct sk_buff *skb, struct inet6_ifaddr *ifp) goto lock_errdad;spin_lock_bh (&ifp2->lock); - ifp2->stable_privacy_retry = retries; - ifp2->state =INET6_IFADDR_STATE_PREDAD ; +if (ifp2->state !=INET6_IFADDR_STATE_DEAD ) { + ifp2->stable_privacy_retry = retries; + start_dad = true; + }spin_unlock_bh (&ifp2->lock); -addrconf_mod_dad_work (ifp2, net->ipv6.sysctl.idgen_delay); +if (start_dad) +addrconf_mod_dad_work (ifp2, net->ipv6.sysctl.idgen_delay);in6_ifa_put (ifp2); lock_errdad:spin_lock_bh (&ifp->lock);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 975/1257 fbdev: bitblit: Fix glyph clipping when fbcon pans
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tingjie Zhong <[email protected]>
[ Upstream commit 06fccf840640d8f6b0e08a1756f8d2f0435b4cbe ]
Commit 3637d34b35b2 ("fbdev: Add bounds checking in bit_putcs to fix vmalloc-out-of-bounds") made bit_putcs() clip glyphs to var.yres. When fbcon scrolls by panning, it draws text rows up to var.yres_virtual, so after the first pan most new text is not drawn until the next full redraw. This affects fbdev drivers that set FBINFO_HWACCEL_YPAN or FBINFO_HWACCEL_YWRAP, such as vesafb with the ypan option, when CONFIG_FRAMEBUFFER_CONSOLE_LEGACY_ACCELERATION=y.
Clip to GETVYRES() instead, which fbcon_ud.c and fbcon_ccw.c already use as the drawing area height. When fbcon does not pan, GETVYRES() returns var.yres, keeping the existing bound. When fbcon pans, it returns var.yres_virtual, which the framebuffer memory must cover anyway for panning to work.
--- drivers/video/fbdev/core/bitblit.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/video/fbdev/core/bitblit.c +5 -2
@@ -18,6 +18,7 @@#include <linux/console.h> #include <asm/types.h> #include "fbcon.h" +#include "fbcon_rotate.h" /* * Accelerated handlers.
@@ -150,7 +151,9 @@ static void bit_putcs(struct vc_data *vc, struct fb_info *info, const unsigned short *s, int count, int yy, int xx, int fg, int bg) { + struct fbcon_par *par = info->fbcon_par;struct fb_image image; +u32 vyres =GETVYRES (par->p, info);u32 width =DIV_ROUND_UP (vc->vc_font.width,8 );u32 cellsize = width * vc->vc_font.height;u32 maxcnt = info->pixmap.size/cellsize;
@@ -167,10 +170,10 @@ static void bit_putcs(struct vc_data *vc, struct fb_info *info, image.height = vc->vc_font.height; image.depth =1 ; -if (image.dy >= info->var.yres) +if (image.dy >= vyres)return ; - image.height =min (image.height, info->var.yres - image.dy); + image.height =min (image.height, vyres - image.dy);if (attribute) { buf =kmalloc (cellsize,GFP_ATOMIC );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 976/1257 fbcon: Include font geometry in the rotated font cache
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yao Yiqi <[email protected]>
[ Upstream commit 10463bcd43495fb88ff667b2c5348200860f6bdc ]
fbcon_rotate_font() caches a rotated copy of the console font and skips the rebuild when the fontdata pointer and the rotation match. Raw font data carries no geometry, though: width, height and charcount live in vc->vc_font. fbcon_set_font() deduplicates uploads by byte equality, so the same bytes re-uploaded with different dimensions keep the fontdata pointer while the geometry changes, and the early-out skips the rebuild.
The rotated cell size depends on the geometry (rotation swaps width and height), so the stale buffer is indexed with the new cell size. Re-uploading a 4x16 font as 16x8 on a CW-rotated console, for example, doubles the rotated cell size and reads past the end of the old buffer.
Record the geometry the buffer was built from and compare it in the early-out. The pointer-only key used to be backed by an explicit width check in the deduplication, which commit 1e3c49aa03fb ("lib/fonts: Compare font data for equality with font_data_is_equal()") dropped.
--- drivers/video/fbdev/core/fbcon.h | 9 ++++++--- drivers/video/fbdev/core/fbcon_rotate.c | 9 ++++++++- 2 files changed, 14 insertions(+), 4 deletions(-)
drivers/video/fbdev/core/fbcon.h +6 -3
@@ -89,10 +89,13 @@ struct fbcon_par {char *cursor_data;#ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION struct { -font_data_t *fontdata;/* source font */ -u8 *buf;/* rotated glyphs */ +font_data_t *fontdata;/* source font */ +u8 *buf;/* rotated glyphs */ size_t bufsize; -int buf_rotate;/* rotation of buf */ +int buf_rotate;/* rotation of buf */ +unsigned int buf_width;/* geometry of source font */ +unsigned int buf_height; +unsigned int buf_charcount; } rotated;#endif u8 *cursor_src;
drivers/video/fbdev/core/fbcon_rotate.c +8 -1
@@ -21,11 +21,18 @@ int fbcon_rotate_font(struct fb_info *info, struct vc_data *vc)unsigned char *buf;int ret; -if (par->p->fontdata == par->rotated.fontdata && par->rotate == par->rotated.buf_rotate) +if (par->p->fontdata == par->rotated.fontdata && + par->rotate == par->rotated.buf_rotate && + vc->vc_font.width == par->rotated.buf_width && + vc->vc_font.height == par->rotated.buf_height && + vc->vc_font.charcount == par->rotated.buf_charcount)return 0 ; par->rotated.fontdata = par->p->fontdata; par->rotated.buf_rotate = par->rotate; + par->rotated.buf_width = vc->vc_font.width; + par->rotated.buf_height = vc->vc_font.height; + par->rotated.buf_charcount = vc->vc_font.charcount;if (info->fbops->fb_sync) info->fbops->fb_sync (info);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 977/1257 fbcon: Rebuild rotated font buffer on font change
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yao Yiqi <[email protected]>
[ Upstream commit e4b6b865d45d8dafb6c6f28c8a993a5b4431d25a ]
fbcon_rotate_font() caches a rotated copy of the console font in par->rotated.buf. The buffer is sized from the font's width, height and charcount, and is rebuilt in fbcon_init(), fbcon_switch() and fbcon_modechanged(), but not in fbcon_do_set_font().
When the font is changed through KDFONTOP, the new geometry is installed and vc_resize() redraws before the buffer is rebuilt. The rotated putcs/cursor ops then index the old buffer with the new cell size; KASAN reports a slab-out-of-bounds read in soft_cursor().
Rebuild the buffer for the visible console before the redraw, as the other callers do: select the console's blitting state with set_blitting_type() (which also uploads the new font's map on tile-blitting hardware), then rebuild. Background consoles keep their rebuild at fbcon_switch() time, as the buffer is shared per framebuffer and must not be updated for a console that is not being displayed.
To ensure a correct rollback when the rebuild or the following vc_resize() fails, save the rotated font state, clear it before rebuilding, and restore it in the error path of fbcon_do_set_font().
--- drivers/video/fbdev/core/fbcon.c | 46 ++++++++++++++++++++++++++++++++ drivers/video/fbdev/core/fbcon.h | 22 ++++++++------- 2 files changed, 59 insertions(+), 9 deletions(-)
drivers/video/fbdev/core/fbcon.c +46 -0
@@ -2414,6 +2414,10 @@ static int fbcon_do_set_font(struct vc_data *vc, int w, int h, int charcount,font_data_t *old_fontdata = p->fontdata;const u8 *old_data = vc->vc_font.data;unsigned short old_hi_font_mask = vc->vc_hi_font_mask; +#ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION +struct fbcon_rotated saved_rotated = { }; +bool rotated_saved = false; +#endif font_data_get (data);
@@ -2432,6 +2436,27 @@ static int fbcon_do_set_font(struct vc_data *vc, int w, int h, int charcount,else if (!vc->vc_hi_font_mask && charcount ==512 )set_vc_hi_font (vc, true); +/* +* Select the console's blitting state and update par->rotated to +* match the new font, so that the rendering below does not use a +* cache that was built for the old font. Clear the cached state so +* the rebuild allocates a fresh buffer; the old state is kept until +* the font change can no longer fail. +*/ +if (con_is_visible (vc)) { +set_blitting_type (vc, info); +if (par->bitops->rotate_font) { +#ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION + saved_rotated = par->rotated; +memset (&par->rotated,0 ,sizeof (par->rotated)); + rotated_saved = true; +#endif + ret = par->bitops->rotate_font (info, vc); +if (ret) + goto err_out; + } + } +if (resize) {int cols, rows;
@@ -2448,12 +2473,26 @@ static int fbcon_do_set_font(struct vc_data *vc, int w, int h, int charcount,update_screen (vc); } +#ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION +if (rotated_saved) +kfree (saved_rotated.buf); +#endif if (old_fontdata)font_data_put (old_fontdata);return 0 ; err_out: +#ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION +/* +* Drop the buffer built for the new font and restore the saved +* state. +*/ +if (rotated_saved) { +kfree (par->rotated.buf); + par->rotated = saved_rotated; + } +#endif p->fontdata = old_fontdata; vc->vc_font.data = old_data; vc->vc_font.width = old_width;
@@ -2466,6 +2505,13 @@ static int fbcon_do_set_font(struct vc_data *vc, int w, int h, int charcount,else if (!old_hi_font_mask && vc->vc_hi_font_mask)set_vc_hi_font (vc, false); +/* +* Re-select the blitting type, which re-uploads the font map on +* tile-blitting hardware. +*/ +if (con_is_visible (vc)) +set_blitting_type (vc, info); +font_data_put (data);return ret;
drivers/video/fbdev/core/fbcon.h +13 -9
@@ -72,6 +72,18 @@ struct fbcon_bitops {int (*rotate_font)(struct fb_info *info,struct vc_data *vc); }; +#ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION +struct fbcon_rotated { +font_data_t *fontdata;/* source font */ +u8 *buf;/* rotated glyphs */ +size_t bufsize; +int buf_rotate;/* rotation of buf */ +unsigned int buf_width;/* geometry of source font */ +unsigned int buf_height; +unsigned int buf_charcount; +}; +#endif +struct fbcon_par {struct fb_var_screeninfo var;/* copy of the current fb_var_screeninfo */ struct delayed_work cursor_work;/* Cursor timer */
@@ -88,15 +100,7 @@ struct fbcon_par {int rotate;char *cursor_data;#ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION -struct { -font_data_t *fontdata;/* source font */ -u8 *buf;/* rotated glyphs */ -size_t bufsize; -int buf_rotate;/* rotation of buf */ -unsigned int buf_width;/* geometry of source font */ -unsigned int buf_height; -unsigned int buf_charcount; - } rotated; +struct fbcon_rotated rotated;#endif u8 *cursor_src;u32 cursor_size;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 978/1257 fbcon: Retry rotated font allocation after failure
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yao Yiqi <[email protected]>
[ Upstream commit 7935db1a4a0f83a63590a222500e5016e2f6c85e ]
fbcon_rotate_font() records the font, its geometry and the rotation in par->rotated before calling font_data_rotate(). If the allocation fails, the error path clears par->rotated.buf, but the recorded key already looks up to date, so the next call takes the early-out and never retries. The rotated putcs/cursor ops keep returning early on the NULL buffer, and the console stays blank even after memory is available again.
Also test par->rotated.buf in the early-out, so a failed allocation is retried on the next call: at the next fbcon_switch(), fbcon_modechanged() or font change.
--- drivers/video/fbdev/core/fbcon_rotate.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/video/fbdev/core/fbcon_rotate.c +2 -1
@@ -25,7 +25,8 @@ int fbcon_rotate_font(struct fb_info *info, struct vc_data *vc) par->rotate == par->rotated.buf_rotate && vc->vc_font.width == par->rotated.buf_width && vc->vc_font.height == par->rotated.buf_height && - vc->vc_font.charcount == par->rotated.buf_charcount) + vc->vc_font.charcount == par->rotated.buf_charcount && + par->rotated.buf) return 0; par->rotated.fontdata = par->p->fontdata;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 979/1257 PCI: qcom-ep: Deinitialize endpoint on remove
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guangshuo Li <[email protected]>
[ Upstream commit ed1d71e41c7b2e755e0ef8e9af9cab9b6b185c4b ]
qcom_pcie_ep_probe() initializes the DesignWare PCIe endpoint with dw_pcie_ep_init(). The probe failure paths call dw_pcie_ep_deinit() to release the corresponding endpoint resources, but the remove path does not perform the matching teardown after a successful probe.
As a result, resources initialized by the DesignWare endpoint core can remain allocated when the endpoint controller is removed.
Notify endpoint functions about EPC deinitialization and call dw_pcie_ep_deinit() before disabling the controller resources. Keep the existing early return when the link is already disabled since Qualcomm endpoint controllers depend on the host refclk for hardware cleanup.
This issue was found by manual code inspection.
--- drivers/pci/controller/dwc/pcie-qcom-ep.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/pci/controller/dwc/pcie-qcom-ep.c +2 -0
@@ -944,6 +944,8 @@ static void qcom_pcie_ep_remove(struct platform_device *pdev)if (pcie_ep->link_status ==QCOM_PCIE_EP_LINK_DISABLED )return ; +pci_epc_deinit_notify (pcie_ep->pci.ep.epc); +dw_pcie_ep_deinit (&pcie_ep->pci.ep);qcom_pcie_disable_resources (pcie_ep); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 980/1257 net/rds: ib: dont enable IRQs in rds_ib_conn_free()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nguyen Ngoc Thang <[email protected]>
[ Upstream commit f6fa1d60ec3ceb7e6c26aa91eadfef34f94014e1 ]
__rds_conn_create() calls trans->conn_free() with rds_conn_lock held and IRQs disabled when it loses the race to insert a connection. rds_ib_conn_free() takes the device list lock with spin_lock_irq() and releases it with spin_unlock_irq(), so IRQs are turned on while rds_conn_lock is still held:
raw_local_irq_restore() called with IRQs enabled
WARNING: kernel/locking/irqflag-debug.c:10 at warn_bogus_irq_restore+0xc/0x20 _raw_spin_unlock_irqrestore+0x67/0x80 __rds_conn_create+0x1de5/0x2290 rds_conn_create_outgoing+0x43/0x60 rds_sendmsg+0xfca/0x20e0 __sys_sendto+0x408/0x5a0
It needs an RDS socket bound to an address on an RDMA device (e.g. rxe) and two concurrent sendto() calls to the same new destination.
The TCP and loopback ->conn_free() callbacks already use irqsave, so do the same here.
--- net/rds/ib_cm.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
net/rds/ib_cm.c +4 -2
@@ -1271,6 +1271,7 @@ void rds_ib_conn_free(void *arg) {struct rds_ib_connection *ic = arg;spinlock_t *lock_ptr; +unsigned long flags;rdsdebug ("ic %p\n" , ic);
@@ -1281,9 +1282,10 @@ void rds_ib_conn_free(void *arg)*/ lock_ptr = ic->rds_ibdev ? &ic->rds_ibdev->spinlock : &ib_nodev_conns_lock; -spin_lock_irq (lock_ptr); +/* May be called with IRQs already disabled (see __rds_conn_create()) */ +spin_lock_irqsave (lock_ptr, flags);list_del (&ic->ib_node); -spin_unlock_irq (lock_ptr); +spin_unlock_irqrestore (lock_ptr, flags);rds_ib_recv_free_caches (ic);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 981/1257 net: unix: reject negative max_dgram_qlen values
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 1a4e7bc6e3457ad95515a9d2c042452c3161bb2c ]
net.unix.max_dgram_qlen is parsed as a signed int and copied to the u32 sock::sk_max_ack_backlog when an AF_UNIX socket is created. Consequently, a negative value such as -1 is accepted and converted to UINT_MAX. Since the receive queue length is also u32, its fullness check cannot become true for that limit.
max_dgram_qlen has no documented negative sentinel. Its existing signed interface represents nonnegative values only through INT_MAX; negative bit patterns are not a supported encoding for the upper half of the u32 consumer range.
Switch to proc_dointvec_minmax and make the established 0..INT_MAX input range explicit. This rejects negative values without adding new accepted values or changing the default and zero-value behavior. Very large valid values can still make the queue limit impractical to reach; this change corrects the input domain rather than imposing a new resource ceiling.
--- Documentation/networking/ip-sysctl.rst | 3 ++- net/unix/sysctl_net_unix.c | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-)
Documentation/networking/ip-sysctl.rst +2 -1
@@ -3823,5 +3823,6 @@ l3mdev_accept - BOOLEAN max_dgram_qlen - INTEGER The maximum length of dgram socket receive queue - Default: 10 + Possible values: 0 - INT_MAX + Default: 10
net/unix/sysctl_net_unix.c +3 -1
@@ -19,7 +19,9 @@ static const struct ctl_table unix_table[] = { .data = &init_net.unx.sysctl_max_dgram_qlen, .maxlen = sizeof(int), .mode = 0644, - .proc_handler = proc_dointvec + .proc_handler = proc_dointvec_minmax, + .extra1 = SYSCTL_ZERO, + .extra2 = SYSCTL_INT_MAX, }, };
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 982/1257 mlxsw: Initialize register query payloads
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Til Kaiser <[email protected]>
[ Upstream commit 15b7a86a8888dc6a8fd19e181757e32389de9064 ]
MFGD register queries can exhaust EMAD retries and leave Mellanox Spectrum switches stuck during boot or shutdown when running OpenWrt built with GCC 15.
An example failure is shown below with the second line wrapped:
EMAD retries (5/5) (tid=9b544fc100001f35)
EMAD reg access failed (tid=9b544fc100001f35,reg_id=90f0(mfgd),
type=query,status=0(operation performed))
On an SN2100, the failure occurs during driver teardown on reboot. On an SN3420, it occurs while probing mlxsw_spectrum during boot.
The register query API transmits the supplied payload to the device before replacing it with the response. Both MFGD callers pass an uninitialized stack buffer, so the request contains arbitrary register field values and reserved bits. This makes the request depend on stack contents and compiler code generation.
Initialize both MFGD query buffers in the firmware fatal event configuration and reporter test paths. The initialization has been confirmed to eliminate the boot and shutdown hangs on both switches. The subsequent read-modify-write still preserves the other fields returned by the device.
Also initialize the FORE fan fault query and the MOGCR mirroring policer base query, which pass entirely uninitialized payloads. Restore the MTMP query initialization in the temperature history reset path, where only the slot and sensor index fields are set before querying the register.
This follows commit 5b0907407e7f ("mlxsw: core: Zero payload buffers for couple of registers"), which initialized other query payloads after a firmware field length bug caused firmware to consume uninitialized data.
Tested with firmware 2020.1148 and with 2016.3900 from linux-firmware.
--- drivers/net/ethernet/mellanox/mlxsw/core.c | 4 ++-- drivers/net/ethernet/mellanox/mlxsw/core_hwmon.c | 4 ++-- drivers/net/ethernet/mellanox/mlxsw/spectrum_span.c | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-)
drivers/net/ethernet/mellanox/mlxsw/core.c +2 -2
@@ -2001,7 +2001,7 @@ mlxsw_core_health_fw_fatal_test(struct devlink_health_reporter *reporter, struct netlink_ext_ack *extack) {struct mlxsw_core *mlxsw_core =devlink_health_reporter_priv (reporter); -char mfgd_pl[MLXSW_REG_MFGD_LEN ]; +char mfgd_pl[MLXSW_REG_MFGD_LEN ] = {0 };int err;/* Read the register first to make sure no other bits are changed. */
@@ -2022,7 +2022,7 @@ mlxsw_core_health_fw_fatal_ops = {static int mlxsw_core_health_fw_fatal_config (struct mlxsw_core *mlxsw_core,bool enable) { -char mfgd_pl[MLXSW_REG_MFGD_LEN ]; +char mfgd_pl[MLXSW_REG_MFGD_LEN ] = {0 };int err;/* Read the register first to make sure no other bits are changed. */
drivers/net/ethernet/mellanox/mlxsw/core_hwmon.c +2 -2
@@ -120,7 +120,7 @@ static ssize_t mlxsw_hwmon_temp_rst_store(struct device *dev, container_of(attr, struct mlxsw_hwmon_attr, dev_attr);struct mlxsw_hwmon_dev *mlxsw_hwmon_dev = mlxsw_hwmon_attr->mlxsw_hwmon_dev;struct mlxsw_hwmon *mlxsw_hwmon = mlxsw_hwmon_dev->hwmon; -char mtmp_pl[MLXSW_REG_MTMP_LEN ]; +char mtmp_pl[MLXSW_REG_MTMP_LEN ] = {0 };unsigned long val;int index;int err;
@@ -177,7 +177,7 @@ static ssize_t mlxsw_hwmon_fan_fault_show(struct device *dev, container_of(attr, struct mlxsw_hwmon_attr, dev_attr);struct mlxsw_hwmon_dev *mlxsw_hwmon_dev = mlxsw_hwmon_attr->mlxsw_hwmon_dev;struct mlxsw_hwmon *mlxsw_hwmon = mlxsw_hwmon_dev->hwmon; -char fore_pl[MLXSW_REG_FORE_LEN ]; +char fore_pl[MLXSW_REG_FORE_LEN ] = {0 };bool fault;int err;
drivers/net/ethernet/mellanox/mlxsw/spectrum_span.c +1 -1
@@ -1720,7 +1720,7 @@ static int mlxsw_sp2_span_init(struct mlxsw_sp *mlxsw_sp)static int mlxsw_sp2_span_policer_id_base_set (struct mlxsw_sp *mlxsw_sp,u16 policer_id_base) { -char mogcr_pl[MLXSW_REG_MOGCR_LEN ]; +char mogcr_pl[MLXSW_REG_MOGCR_LEN ] = {0 };int err; err =mlxsw_reg_query (mlxsw_sp->core,MLXSW_REG (mogcr), mogcr_pl);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 983/1257 exfat: advance valid_size to EOF for append writes
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chi Zhiling <[email protected]>
[ Upstream commit b70ab407503706289163dd59f1ac3e942bacc37d ]
For an append write, the write position is recalculated by generic_write_checks(). Therefore, the write position must be obtained after generic_write_checks() returns.
Using the original write position to advance valid_size may cause the valid_size update to be skipped, potentially exposing stale data.
Also move the truncate_pagecache() check below the recalculated position, so that pos is never read before it is assigned.
--- fs/exfat/file.c | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-)
fs/exfat/file.c +8 -10
@@ -854,8 +854,7 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter)struct file *file = iocb->ki_filp;struct inode *inode =file_inode (file);struct exfat_inode_info *ei =EXFAT_I (inode); -loff_t pos = iocb->ki_pos; -loff_t valid_size; +loff_t pos, valid_size;int err;if (unlikely (exfat_forced_shutdown (inode->i_sb)))
@@ -863,11 +862,6 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter)inode_lock (inode); -if (pos >i_size_read (inode)) -truncate_pagecache (inode,i_size_read (inode)); - - valid_size = ei->valid_size; - ret =generic_write_checks (iocb, iter);if (ret <=0 ) goto unlock;
@@ -878,6 +872,11 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter) goto unlock; } + pos = iocb->ki_pos; +if (pos >i_size_read (inode)) +truncate_pagecache (inode,i_size_read (inode)); + + valid_size = ei->valid_size;if (pos > valid_size) { ret =exfat_extend_valid_size (inode, pos);if (ret <0 && ret != -ENOSPC ) {
@@ -887,6 +886,8 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter) }if (ret <0 ) goto unlock; + + pos = valid_size; }if (iocb->ki_flags &IOCB_DIRECT )
@@ -899,9 +900,6 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter)inode_unlock (inode); -if (pos > valid_size) - pos = valid_size; -if (iocb->ki_pos > pos) {ssize_t err =generic_write_sync (iocb, iocb->ki_pos - pos);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 984/1257 exfat: hold the invalidate lock while truncating
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chi Zhiling <[email protected]>
[ Upstream commit 646df471c37483eb31548d76a1b062775db71d60 ]
truncate_setsize() ends in truncate_inode_pages(), which is documented as being "Called under (and serialised by) inode->i_rwsem and mapping->invalidate_lock".
Hold invalidate_lock while executing truncate_setsize() to ensure that truncate and mmap writes are mutually exclusive. This can simplify the handling in exfat_page_mkwrite().
--- fs/exfat/file.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/exfat/file.c +4 -0
@@ -413,6 +413,7 @@ int exfat_setattr(struct mnt_idmap *idmap, struct dentry *dentry,* about to be freed. */ inode_dio_wait (inode); +filemap_invalidate_lock (inode->i_mapping);truncate_setsize (inode, attr->ia_size);/*
@@ -420,6 +421,7 @@ int exfat_setattr(struct mnt_idmap *idmap, struct dentry *dentry,* is already written by it, so mark_inode_dirty() is unneeded. */ exfat_truncate (inode); +filemap_invalidate_unlock (inode->i_mapping); }else mark_inode_dirty (inode);
@@ -784,8 +786,10 @@ static int exfat_extend_valid_size(struct inode *inode, loff_t new_valid_size) ret =exfat_zero_new_range (inode, gap_start, new_valid_size);filemap_invalidate_unlock (inode->i_mapping);if (ret) { +filemap_invalidate_lock (inode->i_mapping);truncate_setsize (inode, old_valid_size);exfat_truncate (inode); +filemap_invalidate_unlock (inode->i_mapping);return ret; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 985/1257 exfat: dirty all new pages when extending valid_size
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chi Zhiling <[email protected]>
[ Upstream commit 03ac97285b699954fa7bc24f8b6cdc1830c94d28 ]
In the current code, exfat_zero_new_range() does not mark non-uptodate pages as dirty, which may cause some blocks within a page to not be written back.
This commit no longer checks each block in a non-uptodate page individually. Instead, it reads the entire page back into the cache and then writes it back as a whole. This allows concurrent writes and zeroing operations to be synchronized using the folio lock.
--- fs/exfat/file.c | 108 ++++++++++++------------------------------------ 1 file changed, 26 insertions(+), 82 deletions(-)
fs/exfat/file.c +26 -82
@@ -656,98 +656,42 @@ int exfat_file_fsync(struct file *filp, loff_t start, loff_t end, int datasync) }/* -* exfat_zero_new_range - zero [start, end) without overwriting uptodate blocks +* exfat_prepare_valid_range - populate and dirty folios covering [start, end) * -* Uptodate blocks may contain data written through a shared mapping beyond -* valid_size. +* Populate missing blocks via the read path, which zero-fills data +* beyond the current valid_size and skips uptodate blocks. +* Mark entire folios dirty so the newly valid range is written back. +* +* Call before advancing valid_size. */ -static int exfat_zero_new_range (struct inode *inode,loff_t start,loff_t end) +static int exfat_prepare_valid_range (struct inode *inode,loff_t start, +loff_t end) {struct address_space *mapping = inode->i_mapping; -unsigned int blocksize =i_blocksize (inode); -loff_t pos = start; -int err; - -while (pos < end) { -loff_t next =min_t (loff_t, -round_down (pos,PAGE_SIZE ) +PAGE_SIZE , end); -struct folio *folio; -loff_t bpos; - - folio =filemap_get_folio (mapping, pos >>PAGE_SHIFT ); -if (IS_ERR (folio)) { - err =iomap_zero_range (inode, pos, next - pos,NULL , - &exfat_iomap_ops,NULL ,NULL ); -if (err <0 ) -return err; - pos = next; -continue ; - } +loff_t next, pos = start; +struct folio *folio; +pgoff_t index; -if (folio_test_uptodate (folio)) { -folio_lock (folio); -if (folio->mapping == mapping) -folio_mark_dirty (folio); -folio_unlock (folio); -folio_put (folio); - pos = next; -continue ; - } +if (pos >= end) +return 0 ; -/* -* Zero not-uptodate block runs. iomap_zero_range() requires an -* unlocked folio, so recheck ->mapping after each call. -*/ -folio_lock (folio); - bpos = pos; -while (bpos < next) { -loff_t rstart, rend; - -if (folio->mapping != mapping) { -folio_unlock (folio); - err =iomap_zero_range (inode, bpos, next - bpos, -NULL , &exfat_iomap_ops,NULL ,NULL ); -if (err <0 ) { -folio_put (folio); -return err; - } -folio_lock (folio); -break ; - } - -if (iomap_is_partially_uptodate (folio, -offset_in_folio (folio, bpos), blocksize)) { - bpos += blocksize; -continue ; - } +while (pos < end) { + index = pos >>PAGE_SHIFT ; + next =min (((loff_t )index +1 ) <<PAGE_SHIFT , end); - rstart = bpos; - rend =min_t (loff_t, bpos + blocksize, next); -while (rend < next && - !iomap_is_partially_uptodate (folio, -offset_in_folio (folio, rend), blocksize)) - rend =min_t (loff_t, rend + blocksize, next); +balance_dirty_pages_ratelimited (mapping); -folio_unlock (folio); - err =iomap_zero_range (inode, rstart, rend - rstart, -NULL , &exfat_iomap_ops,NULL ,NULL ); -if (err <0 ) { -folio_put (folio); -return err; - } -folio_lock (folio); - bpos = rend; - } + folio =read_mapping_folio (mapping, index,NULL ); +if (IS_ERR (folio)) +return PTR_ERR (folio); -/* -* Dirty only a fully uptodate folio. Dirtying a partial folio could -* write uninitialised cache contents over valid on-disk blocks. -*/ -if (folio->mapping == mapping &&folio_test_uptodate (folio)) +folio_lock (folio); +if (folio->mapping == mapping) {folio_mark_dirty (folio); + pos = next; + }folio_unlock (folio);folio_put (folio); - pos = next; }return 0 ;
@@ -783,7 +727,7 @@ static int exfat_extend_valid_size(struct inode *inode, loff_t new_valid_size)if (gap_start < new_valid_size)unmap_mapping_range (inode->i_mapping, gap_start, new_valid_size - gap_start,0 ); - ret =exfat_zero_new_range (inode, gap_start, new_valid_size); + ret =exfat_prepare_valid_range (inode, gap_start, new_valid_size);filemap_invalidate_unlock (inode->i_mapping);if (ret) {filemap_invalidate_lock (inode->i_mapping);
@@ -965,7 +909,7 @@ static vm_fault_t exfat_page_mkwrite(struct vm_fault *vmf)* fault populated its folio and iomap_page_mkwrite() * will dirty it. */ - err =exfat_zero_new_range (inode, ei->zeroed_size, + err =exfat_prepare_valid_range (inode, ei->zeroed_size, fault_page_start);if (err <0 ) {inode_unlock (inode);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 986/1257 exfat: make valid_size and zeroed_size atomic
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chi Zhiling <[email protected]>
[ Upstream commit 6bb112f5d90a78461648e3bd89093ea299196be5 ]
ei->valid_size and ei->zeroed_size are 64-bit fields read from bio completion context (exfat_iomap_read_end_io()) and from ->iomap_begin without i_rwsem, while writers update them under i_rwsem. On 32-bit these loads can tear, and the "if (x < new) x = new" read-modify-write can lose an update or regress the value when two writers race.
Convert both to atomic64_t and funnel updates through a cmpxchg-based monotonic advance helper so the value only moves forward; plain reads use exfat_get_*(), and the few shrink/init paths (truncate, inode fill, create) use exfat_set_*(). This is a prerequisite for taking exfat_page_mkwrite() out from under i_rwsem.
--- fs/exfat/exfat_fs.h | 60 +++++++++++++++++++++++++++++++++++++++++++-- fs/exfat/file.c | 32 +++++++++++++----------- fs/exfat/inode.c | 16 ++++++------ fs/exfat/iomap.c | 20 +++++++-------- fs/exfat/namei.c | 4 +-- 5 files changed, 96 insertions(+), 36 deletions(-)
fs/exfat/exfat_fs.h +58 -2
@@ -7,6 +7,7 @@#define _EXFAT_FS_H#include <linux/fs.h> +#include <linux/atomic.h> #include <linux/ratelimit.h> #include <linux/nls.h> #include <linux/blkdev.h>
@@ -293,9 +294,16 @@ struct exfat_inode_info {/* on-disk position of directory entry or 0 */ loff_t i_pos; -loff_t valid_size; +/* +* valid_size and zeroed_size are updated from multiple contexts that +* are not serialised against each other (page_mkwrite runs without +* i_rwsem, while buffered/DIO writes advance them under i_rwsem). Keep +* them atomic and only ever advance them with a cmpxchg loop so a +* concurrent update can never regress the value or tear on 32-bit. +*/ +atomic64_t valid_size;/* block-aligned size zeroed in the page cache (>= valid_size) */ -loff_t zeroed_size; +atomic64_t zeroed_size;/* hash by i_location */ struct hlist_node i_hash_fat;struct inode vfs_inode;
@@ -313,6 +321,54 @@ static inline struct exfat_inode_info *EXFAT_I(struct inode *inode) return container_of(inode, struct exfat_inode_info, vfs_inode); } +static inline loff_t exfat_get_valid_size (struct exfat_inode_info *ei) +{ +return atomic64_read (&ei->valid_size); +} + +static inline loff_t exfat_get_zeroed_size (struct exfat_inode_info *ei) +{ +return atomic64_read (&ei->zeroed_size); +} + +static inline void exfat_set_valid_size (struct exfat_inode_info *ei,loff_t v) +{ +atomic64_set (&ei->valid_size, v); +} + +static inline void exfat_set_zeroed_size (struct exfat_inode_info *ei,loff_t v) +{ +atomic64_set (&ei->zeroed_size, v); +} + +/* +* Monotonically advance @v to at least @new. Returns true if the value was +* actually raised, so callers can decide whether to mark the inode dirty. +*/ +static inline bool exfat_size_advance (atomic64_t *v,loff_t new) +{ +loff_t old =atomic64_read (v); + +do { +if (old >= new) +return false; + }while (!atomic64_try_cmpxchg (v, &old, new)); + +return true; +} + +static inline bool exfat_advance_valid_size (struct exfat_inode_info *ei, +loff_t new) +{ +return exfat_size_advance (&ei->valid_size, new); +} + +static inline bool exfat_advance_zeroed_size (struct exfat_inode_info *ei, +loff_t new) +{ +return exfat_size_advance (&ei->zeroed_size, new); +} +static inline int exfat_forced_shutdown (struct super_block *sb) {return test_bit (EXFAT_FLAGS_SHUTDOWN , &EXFAT_SB (sb)->s_exfat_flags);
fs/exfat/file.c +18 -14
@@ -247,8 +247,10 @@ int __exfat_truncate(struct inode *inode) ei->start_clu =EXFAT_EOF_CLUSTER ; } -if (i_size_read (inode) < ei->valid_size) - ei->valid_size = ei->zeroed_size =i_size_read (inode); +if (i_size_read (inode) <exfat_get_valid_size (ei)) { +exfat_set_valid_size (ei,i_size_read (inode)); +exfat_set_zeroed_size (ei,i_size_read (inode)); + }if (ei->type ==TYPE_FILE ) ei->attr |=EXFAT_ATTR_ARCHIVE ;
@@ -700,12 +702,12 @@ static int exfat_prepare_valid_range(struct inode *inode, loff_t start,static int exfat_extend_valid_size (struct inode *inode,loff_t new_valid_size) {struct exfat_inode_info *ei =EXFAT_I (inode); -loff_t old_valid_size = ei->valid_size; +loff_t old_valid_size =exfat_get_valid_size (ei);int ret =0 ;if (old_valid_size < new_valid_size) {/* Do not re-zero blocks already covered by zeroed_size. */ -loff_t gap_start =max (old_valid_size, ei->zeroed_size); +loff_t gap_start =max (old_valid_size,exfat_get_zeroed_size (ei));if (i_size_read (inode) < new_valid_size) {/*
@@ -737,9 +739,9 @@ static int exfat_extend_valid_size(struct inode *inode, loff_t new_valid_size)return ret; } - ei->valid_size = new_valid_size; -if (ei->zeroed_size <round_up (new_valid_size,i_blocksize (inode))) - ei->zeroed_size =round_up (new_valid_size,i_blocksize (inode)); +exfat_set_valid_size (ei, new_valid_size); +exfat_advance_zeroed_size (ei, +round_up (new_valid_size,i_blocksize (inode)));mark_inode_dirty (inode); }
@@ -824,7 +826,7 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter)if (pos >i_size_read (inode))truncate_pagecache (inode,i_size_read (inode)); - valid_size = ei->valid_size; + valid_size =exfat_get_valid_size (ei);if (pos > valid_size) { ret =exfat_extend_valid_size (inode, pos);if (ret <0 && ret != -ENOSPC ) {
@@ -900,8 +902,10 @@ static vm_fault_t exfat_page_mkwrite(struct vm_fault *vmf) fault_page_start = ((loff_t )vmf->pgoff) <<PAGE_SHIFT ; new_valid_size =min (mmap_valid_size,i_size_read (inode)); -if (ei->valid_size < new_valid_size) { -if (ei->zeroed_size < fault_page_start) { +if (exfat_get_valid_size (ei) < new_valid_size) { +loff_t zeroed_size =exfat_get_zeroed_size (ei); + +if (zeroed_size < fault_page_start) {int err;/*
@@ -909,7 +913,7 @@ static vm_fault_t exfat_page_mkwrite(struct vm_fault *vmf)* fault populated its folio and iomap_page_mkwrite() * will dirty it. */ - err =exfat_prepare_valid_range (inode, ei->zeroed_size, + err =exfat_prepare_valid_range (inode, zeroed_size, fault_page_start);if (err <0 ) {inode_unlock (inode);
@@ -922,9 +926,9 @@ static vm_fault_t exfat_page_mkwrite(struct vm_fault *vmf)* at i_size recording blocks wholly beyond it could skip a * later required zeroing. */ -if (ei->zeroed_size <round_up (new_valid_size,i_blocksize (inode))) - ei->zeroed_size =round_up (new_valid_size,i_blocksize (inode)); - ei->valid_size = new_valid_size; +exfat_advance_zeroed_size (ei, +round_up (new_valid_size,i_blocksize (inode))); +exfat_set_valid_size (ei, new_valid_size);mark_inode_dirty (inode); }
fs/exfat/inode.c +9 -7
@@ -29,6 +29,7 @@ int __exfat_write_inode(struct inode *inode, int sync)struct exfat_sb_info *sbi =EXFAT_SB (sb);struct exfat_inode_info *ei =EXFAT_I (inode);bool is_dir = (ei->type ==TYPE_DIR ); +loff_t valid_size =exfat_get_valid_size (ei);struct timespec64 ts;if (inode->i_ino ==EXFAT_ROOT_INO )
@@ -81,7 +82,7 @@ int __exfat_write_inode(struct inode *inode, int sync)* preventing fsck from reporting "more clusters are allocated". */ on_disk_size = max_t(unsigned long long, i_size_read(inode), - ei->valid_size); + valid_size);if (ei->start_clu ==EXFAT_EOF_CLUSTER ) on_disk_size =0 ;
@@ -89,7 +90,7 @@ int __exfat_write_inode(struct inode *inode, int sync)* valid_size on disk must reflect only confirmed data (up to i_size) * and must not exceed on_disk_size. */ - on_disk_valid_size = min_t(unsigned long long, ei->valid_size, + on_disk_valid_size = min_t(unsigned long long, valid_size,i_size_read (inode));if (ei->start_clu ==EXFAT_EOF_CLUSTER ) on_disk_valid_size =0 ;
@@ -258,15 +259,16 @@ static void exfat_readahead(struct readahead_control *rac)struct inode *inode = mapping->host;struct exfat_inode_info *ei =EXFAT_I (inode);loff_t pos =readahead_pos (rac); +loff_t valid_size =exfat_get_valid_size (ei);struct iomap_read_folio_ctx ctx = { .ops = &exfat_iomap_bio_read_ops, .rac = rac, };/* Range cross valid_size, read it page by page. */ -if (ei->valid_size <i_size_read (inode) && - pos <= ei->valid_size && - ei->valid_size < pos +readahead_length (rac)) +if (valid_size <i_size_read (inode) && + pos <= valid_size && + valid_size < pos +readahead_length (rac))return ;iomap_readahead (&exfat_iomap_ops, &ctx,NULL );
@@ -371,8 +373,8 @@ static int exfat_fill_inode(struct inode *inode, struct exfat_dir_entry *info) ei->start_clu = info->start_clu; ei->flags = info->flags; ei->type = info->type; - ei->valid_size = info->valid_size; - ei->zeroed_size = info->valid_size; +exfat_set_valid_size (ei, info->valid_size); +exfat_set_zeroed_size (ei, info->valid_size); ei->version =0 ; ei->hint_stat.eidx =0 ;
fs/exfat/iomap.c +9 -11
@@ -46,6 +46,7 @@ static int __exfat_iomap_begin(struct inode *inode, loff_t offset, loff_t lengthstruct exfat_inode_info *ei =EXFAT_I (inode);unsigned int cluster, num_clusters;loff_t cluster_offset, cluster_length; +loff_t valid_size =exfat_get_valid_size (ei);int err;bool balloc = false;
@@ -88,7 +89,7 @@ static int __exfat_iomap_begin(struct inode *inode, loff_t offset, loff_t lengthif (may_alloc || flags &IOMAP_ZERO ) {if (balloc) iomap->flags |=IOMAP_F_NEW ; -else if (iomap->offset + iomap->length >= ei->valid_size) { +else if (iomap->offset + iomap->length >= valid_size) {/* * This is a write that starts at or extends beyond * the current valid_size. The region between the old
@@ -114,10 +115,10 @@ static int __exfat_iomap_begin(struct inode *inode, loff_t offset, loff_t length* return IOMAP_UNWRITTEN so the write path can * distinguish it from a real hole. */ -if (offset >= ei->valid_size) { +if (offset >= valid_size) { iomap->type = flags &IOMAP_REPORT ?IOMAP_HOLE :IOMAP_UNWRITTEN ; - }else if (offset + iomap->length > ei->valid_size) { + }else if (offset + iomap->length > valid_size) {if (flags &IOMAP_REPORT ) {/* * For SEEK_HOLE/SEEK_DATA, clip the length
@@ -125,9 +126,9 @@ static int __exfat_iomap_begin(struct inode *inode, loff_t offset, loff_t length* This ensures the caller gets the precise * hole position in byte units. */ - iomap->length = ei->valid_size - iomap->offset; + iomap->length = valid_size - iomap->offset; }else - iomap->length =round_up (ei->valid_size, + iomap->length =round_up (valid_size,i_blocksize (inode)) - iomap->offset; }
@@ -175,10 +176,8 @@ static int exfat_write_iomap_end(struct inode *inode, loff_t pos, loff_t length, end = pos + written; -if (ei->valid_size < end) { - ei->valid_size = end; +if (exfat_advance_valid_size (ei, end)) dirtied = true; - }/* * IOMAP_F_ZERO_TAIL zeroes the remainder of the last block. Track that
@@ -186,8 +185,7 @@ static int exfat_write_iomap_end(struct inode *inode, loff_t pos, loff_t length,*/ if (iomap->flags &IOMAP_F_ZERO_TAIL ) end =round_up (end,i_blocksize (inode)); -if (ei->zeroed_size < end) - ei->zeroed_size = end; +exfat_advance_zeroed_size (ei, end);if (dirtied || iomap->flags &IOMAP_F_SIZE_CHANGED )mark_inode_dirty (inode);
@@ -250,7 +248,7 @@ static void exfat_iomap_read_end_io(struct bio *bio)s64 valid_size;loff_t pos =folio_pos (folio); - valid_size = ei->valid_size; + valid_size =exfat_get_valid_size (ei);if (pos + iter.offset < valid_size && pos + iter.offset + iter.length > valid_size) folio_zero_segment(folio, offset_in_folio(folio, valid_size),
fs/exfat/namei.c +2 -2
@@ -380,7 +380,7 @@ int exfat_find_empty_entry(struct inode *inode,/* directory inode should be updated in here */ i_size_write (inode, size); - ei->valid_size += sbi->cluster_size; +atomic64_add (sbi->cluster_size, &ei->valid_size); ei->flags = p_dir->flags; inode->i_blocks += sbi->cluster_size >>9 ; }
@@ -1248,7 +1248,7 @@ static int __exfat_rename(struct inode *old_parent_inode, }i_size_write (new_inode,0 ); - new_ei->valid_size =0 ; +exfat_set_valid_size (new_ei,0 ); new_ei->start_clu =EXFAT_EOF_CLUSTER ; new_ei->flags =ALLOC_NO_FAT_CHAIN ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 987/1257 exfat: drain in-flight DIO before buffered writes
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 acea17f0f4c7742118375e96d3f876be34e449a5 ]
An asynchronous direct write can remain in flight after the inode lock is released. If a buffered operation dirties page cache while the direct write is still pending, the direct write's post-I/O invalidation can find the dirty pages, report a page cache invalidation failure, and record -EIO in the mapping error sequence. A later fsync() therefore returns -EIO.
Commit 15cdefd0c0522f9d5e12d947fa04f4c11649b699 ("ext4: drain in-flight DIO before buffered write fallback") fixed the same race in ext4. ExFAT does not drain in-flight DIO before a regular buffered write, the buffered fallback after iomap_dio_rw() returns -ENOTBLK or a short write, or the page-cache operations used to extend valid_size.
Wait for in-flight DIO before these paths can dirty page cache.
A reproducer using concurrent AIO direct writes and buffered fallback triggered the following warning and made a subsequent fsync() return -EIO:
Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!
--- fs/exfat/file.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-)
fs/exfat/file.c +12 -2
@@ -706,6 +706,8 @@ static int exfat_extend_valid_size(struct inode *inode, loff_t new_valid_size)int ret =0 ;if (old_valid_size < new_valid_size) { +inode_dio_wait (inode); +/* Do not re-zero blocks already covered by zeroed_size. */ loff_t gap_start =max (old_valid_size,exfat_get_zeroed_size (ei));
@@ -757,6 +759,8 @@ static ssize_t exfat_fallback_buffered_write(struct kiocb *iocb, iocb->ki_flags &= ~IOCB_DIRECT ; +inode_dio_wait (file_inode (iocb->ki_filp)); + written =iomap_file_buffered_write (iocb, from, &exfat_write_iomap_ops,NULL ,NULL );if (written <0 )
@@ -840,11 +844,17 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter) pos = valid_size; } -if (iocb->ki_flags &IOCB_DIRECT ) +if (iocb->ki_flags &IOCB_DIRECT ) { ret =exfat_dio_write_iter (iocb, iter); -else + }else { +/* +* Prevent concurrent direct I/O and buffered I/O to the same file +* range. Wait for in-flight DIO to finish before dirtying pages. +*/ +inode_dio_wait (inode); ret =iomap_file_buffered_write (iocb, iter, &exfat_write_iomap_ops,NULL ,NULL ); + }if (ret <0 ) goto unlock;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 988/1257 exfat: zero invalid tail on partial overwrites
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Namjae Jeon <[email protected]>
[ Upstream commit 748ad4ba13cd14163ed7262c6ac304c380804167 ]
Buffered overwrite that ends before valid_size in the same filesystem block reads the entire block without IOMAP_F_ZERO_TAIL. If an existing cluster contains stale bytes beyond valid_size, the synchronous read loads them into the page cache and marks the block uptodate. Subsequent buffered reads can return these bytes while i_size exceeds valid_size.
For example, with 512-byte blocks, valid_size of 1000 and i_size of 2048, a cold-cache overwrite of [900, 950) exposes stale data in [1000, 1024). Setting ZERO_TAIL for this write would also erase valid data in [950, 1000).
Use iomap_truncate_page() to zero only the invalid tail at valid_size before preparing such buffered overwrites. Call it after dropping s_lock and before iomap locks the write folio. The inode lock held by buffered writes serializes valid_size against truncation and page_mkwrite.
Skip direct I/O, fault mappings and new allocations. Writes that reach valid_size continue to use IOMAP_F_ZERO_TAIL.
--- fs/exfat/iomap.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-)
fs/exfat/iomap.c +21 -1
@@ -149,7 +149,27 @@ static int exfat_iomap_begin(struct inode *inode, loff_t offset, loff_t length,static int exfat_write_iomap_begin (struct inode *inode,loff_t offset,loff_t length,unsigned int flags,struct iomap *iomap,struct iomap *srcmap) { -return __exfat_iomap_begin (inode, offset, length, flags, iomap, true); +struct exfat_inode_info *ei =EXFAT_I (inode); +loff_t valid_size =exfat_get_valid_size (ei); +loff_t end; +int err; + + err =__exfat_iomap_begin (inode, offset, length, flags, iomap, true); +if (err || flags & (IOMAP_DIRECT |IOMAP_FAULT ) || + iomap->flags &IOMAP_F_NEW ) +return err; + + end = iomap->offset + iomap->length; +if (end >= valid_size || +round_up (end,i_blocksize (inode)) <= valid_size) +return 0 ; + +/* +* Zero the invalid bytes from valid_size to the end of the block +* to prevent stale data from being exposed through the page cache. +*/ +return iomap_truncate_page (inode, valid_size,NULL , &exfat_iomap_ops, +NULL ,NULL ); } static DEFINE_IOMAP_ITER_NEXT(exfat_iomap_next, exfat_iomap_begin);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 989/1257 exfat: fix a large buffered write failing when the volume is nearly full
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 73cababf93cb371e2e9d06da5261ca6ddd2404b6 ]
Commit 82a81a7352bc ("exfat: add iomap buffered I/O support") made a buffered write map the whole range of the write in one step, so the clusters for all of it are allocated at once.
However, exfat_alloc_cluster() returns -ENOSPC when fewer clusters are free than it is asked for. As of now, a write() that is larger than the free space writes nothing and fails with ENOSPC, while it used to write as much as fits and return a short count.
The issue can be reproduced with a 16M image made by mkfs.exfat that is filled except for 256K:
mount -o loop /img /mnt
dd if=/dev/zero of=/mnt/hole bs=256k count=1
dd if=/dev/zero of=/mnt/fill bs=4k
rm /mnt/hole
dd if=/dev/zero of=/mnt/f bs=1M count=1
wc -c < /mnt/fBefore commit 82a81a7352bc ("exfat: add iomap buffered I/O support"), the result is:
262144
After that commit, the result is:
0
This patch will map a single cluster when the clusters for the whole range cannot be allocated, so that the write goes on until the volume is full. Direct I/O is not changed, it still fails without writing as it did before that commit.
--- fs/exfat/iomap.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
fs/exfat/iomap.c +11 -0
@@ -75,6 +75,17 @@ static int __exfat_iomap_begin(struct inode *inode, loff_t offset, loff_t length err =exfat_map_cluster (inode,exfat_bytes_to_cluster (sbi, offset), &cluster, &num_clusters, may_alloc, &balloc); +if (err == -ENOSPC && !(flags &IOMAP_DIRECT )) { +/* +* There are not enough free clusters for the whole range. A +* buffered write can be short, so map what still fits. +*/ + num_clusters =1 ; + err =exfat_map_cluster (inode, +exfat_bytes_to_cluster (sbi, offset), + &cluster, &num_clusters, may_alloc, + &balloc); + }if (err) goto out;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 990/1257 exfat: mark straddling folio RO and zero the post-EOF range
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuezhang Mo <[email protected]>
[ Upstream commit 1043264c3cfa43b0668f7472a749868c1e21749b ]
When extending a file across a non-page-aligned EOF, the folio containing the old EOF must be marked RO so that subsequent mmap writes trigger ->page_mkwrite() and update valid_size.
The straddling folio remains mapped to the same filesystem block after the file is extended. As a result, the existing writable PTE may remain in place, allowing mmap writes to bypass ->page_mkwrite() and leave valid_size unchanged.
Furthermore, writes to the post-EOF range may occur between truncate_pagecache() and locking the folio. So the post-EOF range should be zeroed after marking the straddling folio RO, and using truncate_pagecache() to zero out the post-EOF range is redundant.
Introduce exfat_pagecache_isize_extended() to mark the straddling folio RO and zero the post-EOF range after clearing writable mapping. This ensures that data written beyond the old EOF before the extension is not exposed as valid file data, and that subsequent mmap writes trigger ->page_mkwrite() to update valid_size.
--- fs/exfat/file.c | 72 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 63 insertions(+), 9 deletions(-)
fs/exfat/file.c +63 -9
@@ -17,11 +17,70 @@#include <linux/fileattr.h> #include <linux/iomap.h> #include <linux/pagemap.h> +#include <linux/rmap.h> #include "exfat_raw.h" #include "exfat_fs.h" #include "iomap.h" +/* +* Unlike pagecache_isize_extended(), this function updates i_size while +* holding the straddling folio lock, and does not skip the straddling +* folio when the filesystem block size is >= PAGE_SIZE or when 'from' +* and 'to' fall within the same filesystem block. +* +* This ensures that the folio is marked RO and the post-EOF range is +* zeroed before readers or writeback can observe the updated i_size. +*/ +static void exfat_pagecache_isize_extended (struct inode *inode,loff_t from, +loff_t to) +{ +struct folio *folio; + +if (!(from & (PAGE_SIZE -1 ))) { +i_size_write (inode, to); +return ; + } + + folio =filemap_lock_folio (inode->i_mapping, from >>PAGE_SHIFT ); + +/* Folio not cached? Nothing to do */ +if (IS_ERR (folio)) { +i_size_write (inode, to); +return ; + } + +/* +* See folio_clear_dirty_for_io() for details why folio_mark_dirty() +* is needed. +*/ +if (folio_mkclean (folio)) +folio_mark_dirty (folio); + +/* +* Zero the post-EOF range before publishing the new size. Writeback +* normally does this, but the extension would expose the tail to +* readers before writeback gets a chance to zero it. +*/ +if (folio_test_dirty (folio)) { +loff_t offset, end; + + offset = from -folio_pos (folio); + end =min_t (loff_t, to -folio_pos (folio), +folio_size (folio)); +folio_zero_segment (folio, offset, end); + } + +/* +* Publish the new size after zeroing the tail. Uptodate folios can +* be read without taking the folio lock. +*/ +i_size_write (inode, to); + +folio_unlock (folio); +folio_put (folio); +} +static int exfat_cont_expand (struct inode *inode,loff_t size) {int ret;
@@ -32,8 +91,6 @@ static int exfat_cont_expand(struct inode *inode, loff_t size)struct exfat_chain clu;loff_t oldsize =i_size_read (inode); -truncate_pagecache (inode, oldsize); - ret =inode_newsize_ok (inode, size);if (ret)return ret;
@@ -81,15 +138,12 @@ static int exfat_cont_expand(struct inode *inode, loff_t size) out:inode_set_mtime_to_ts (inode,inode_set_ctime_current (inode)); -/* Expanded range not zeroed, do not update valid_size */ -i_size_write (inode, size);/* -* When extending file size, call truncate_pagecache() first, -* then update i_size, and call pagecache_isize_extended() -* to ensures the straddling folio is properly marked RO so -* page_mkwrite() is called and post-EOF area is zeroed. +* When extending file size, call exfat_pagecache_isize_extended() +* to update i_size and ensure the straddling folio is properly +* marked RO so page_mkwrite() is called and post-EOF area is zeroed. */ -pagecache_isize_extended (inode, oldsize, inode->i_size); +exfat_pagecache_isize_extended (inode, oldsize, size); inode->i_blocks =round_up (size, sbi->cluster_size) >>9 ;mark_inode_dirty (inode);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 991/1257 exfat: free clusters beyond EOF when a write fails or is short
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 b4c282c0d82e8715ea9ed0b35813a3f365e3f952 ]
Commit 82a81a7352bc ("exfat: add iomap buffered I/O support") and commit 867b9c96dc83 ("exfat: add iomap direct I/O support") made a write allocate the clusters for its whole range in one step. They also dropped exfat_write_failed(), which freed the clusters beyond the end of the file after a failed or short write.
However, a write can stop early, for example when the process is killed or when a part of the buffer cannot be read. As of now, the clusters for the part that was not written stay allocated beyond the end of the file. exfat_cont_expand() does not expect them, so a later write or truncate that extends the file fails with ENOSPC. The directory entry records only the size of the file, so the space can be lost for good once the volume is unmounted.
The issue can be reproduced on a 64M volume made by mkfs.exfat and mounted on /mnt, with a write of 1M from a buffer that has only its first 4K mapped:
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void)
{
char *p = mmap(NULL, 8192, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
int fd = open("/mnt/f", O_CREAT | O_WRONLY, 0644);
struct stat st;
munmap(p + 4096, 4096);
printf("write: %zd\n", write(fd, p, 1 << 20));
fstat(fd, &st);
printf("blocks: %ld\n", (long)st.st_blocks);
printf("ftruncate: %d\n", ftruncate(fd, 1 << 16));
return 0;
}Before commit 82a81a7352bc ("exfat: add iomap buffered I/O support"), the result is:
write: 4096
blocks: 8
ftruncate: 0After that commit, the result is:
write: 4096
blocks: 2048
ftruncate: -1This patch will bring back exfat_write_failed() and call it when a write ends before the end of its range, so that the clusters beyond the end of the file are freed again. It waits for direct I/O in flight first, as exfat_setattr() does before it frees clusters.
--- fs/exfat/file.c | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-)
fs/exfat/file.c +17 -1
@@ -804,6 +804,19 @@ static int exfat_extend_valid_size(struct inode *inode, loff_t new_valid_size)return ret; } +/* +* The clusters for a write are allocated before the data is copied. Free the +* ones that a failed or short write has left beyond the end of the file. +*/ +static void exfat_write_failed (struct inode *inode) +{ +inode_dio_wait (inode); +filemap_invalidate_lock (inode->i_mapping); +truncate_pagecache (inode,i_size_read (inode)); +exfat_truncate (inode); +filemap_invalidate_unlock (inode->i_mapping); +} +static ssize_t exfat_fallback_buffered_write (struct kiocb *iocb,struct iov_iter *from) {
@@ -862,7 +875,7 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter)struct file *file = iocb->ki_filp;struct inode *inode =file_inode (file);struct exfat_inode_info *ei =EXFAT_I (inode); -loff_t pos, valid_size; +loff_t pos, valid_size, end;int err;if (unlikely (exfat_forced_shutdown (inode->i_sb)))
@@ -881,6 +894,7 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter) } pos = iocb->ki_pos; + end = pos +iov_iter_count (iter);if (pos >i_size_read (inode))truncate_pagecache (inode,i_size_read (inode));
@@ -909,6 +923,8 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter) ret =iomap_file_buffered_write (iocb, iter, &exfat_write_iomap_ops,NULL ,NULL ); } +if (ret != -EIOCBQUEUED && end >i_size_read (inode)) +exfat_write_failed (inode);if (ret <0 ) goto unlock;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 992/1257 exfat: fix reading a directory whose FAT chain is longer than its size
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 8534eb11ac056dc2ca08007cf76d3ae7cbe42684 ]
Commit 08cf4a8181b4 ("exfat: use exfat_chain_advance helper") made the directory code walk the clusters of a directory with exfat_chain_advance().
However, exfat_chain_advance() returns -EIO once it has walked as many clusters as the size of the directory says. The FAT chain of a directory can be longer than that, because some cameras stop updating the size, see commit 1e5654de0f51 ("exfat: handle wrong stream entry size in exfat_readdir()"). As of now, opening such a directory fails with EIO as soon as the chain is two clusters longer than the size. Reading a directory that has a FAT chain after a seek past its end fails with EIO too.
The issue can be reproduced with an image in which the size of a directory with 200 files and 7 clusters is lowered to 2 clusters:
mount -o loop exfat.img /mnt
ls /mnt/d | wc -l
Before commit 08cf4a8181b4 ("exfat: use exfat_chain_advance helper"), the result is:
200
After that commit, ls fails with "Input/output error" and the result is:
0
This patch will make exfat_chain_advance() follow the FAT to its end when the directory has a FAT chain, as the code did before, and keep the size check for a directory without one.
--- fs/exfat/exfat_fs.h | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-)
fs/exfat/exfat_fs.h +19 -9
@@ -679,19 +679,29 @@ static inline int exfat_chain_advance(struct super_block *sb, struct exfat_chain *chain, unsigned int step) {unsigned int clu = chain->dir; +unsigned int i; -if (unlikely (chain->size < step)) -return -EIO ; +if (chain->flags ==ALLOC_NO_FAT_CHAIN ) { +if (unlikely (chain->size < step)) +return -EIO ; -if (exfat_cluster_walk (sb, &clu, step, chain->flags)) -return -EIO ; + chain->size -= step; + chain->dir = chain->size ? clu + step :EXFAT_EOF_CLUSTER ; +return 0 ; + } - chain->size -= step; +/* +* Only the FAT tells where a chain of this kind ends. The size can be +* smaller than the chain, see commit 1e5654de0f51 ("exfat: handle +* wrong stream entry size in exfat_readdir()"). +*/ +for (i =0 ; i < step && clu !=EXFAT_EOF_CLUSTER ; i++) { +if (exfat_get_next_cluster (sb, &clu)) +return -EIO ; + } -if (chain->size ==0 && chain->flags ==ALLOC_NO_FAT_CHAIN ) - chain->dir =EXFAT_EOF_CLUSTER ; -else - chain->dir = clu; + chain->size -=min (chain->size, step); + chain->dir = clu;return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 993/1257 net/smc: queue the copied chunk when smc_tx_sendmsg() faults
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bryam Vargas <[email protected]>
[ Upstream commit c0703534b223a5c6993e0f000fd1c3abe621fb65 ]
When a send wraps the end of the send buffer, smc_tx_sendmsg() copies the data in two chunks. If memcpy_from_msg() faults on the second one, smc_tx_sendmsg() returns send_done, which already counts the first chunk, but leaves tx_curs_prep and sndbuf_space as they were. send() reports bytes the peer never receives, and the next send() overwrites them. Any caller can hit this on its own stream with a buffer whose tail is unreadable.
On a fault in the second chunk, queue the first one. The next pass retries the rest and returns send_done if it faults again, so send() reports only what it queued, as TCP does.
--- net/smc/smc_tx.c | 7 +++++++ 1 file changed, 7 insertions(+)
net/smc/smc_tx.c +7 -0
@@ -249,6 +249,13 @@ int smc_tx_sendmsg(struct smc_sock *smc, struct msghdr *msg, size_t len) rc =memcpy_from_msg (sndbuf_base + chunk_off, msg, chunk_len);if (rc) { +if (chunk) { +/* send_done counts the first chunk: +* queue it and retry the rest +*/ + copylen -= chunk_len; +break ; + }smc_sndbuf_sync_sg_for_device (conn);if (send_done)return send_done;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 994/1257 alpha: determine tininess after rounding in the FP emulation
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Matt Turner <[email protected]>
[ Upstream commit b74843b38da8f1186fd7d447646c835b47096a15 ]
IEEE 754 lets an architecture determine tininess of a floating-point result either before or after rounding, but requires the same choice for every operation. Alpha determines it after rounding, and stdlib's tst-tininess confirms the hardware does so for the results it produces itself.
The soft-fp emulation has no notion of the distinction and always determines tininess before rounding, so a result that the hardware would not consider tiny is reported as underflowing whenever the instruction happens to trap for software completion. The two paths then disagree on the same machine. A multiply of the largest subnormal double by 1 + 2^-52 rounds up to the smallest normal and raises no underflow when the operands are normal, but raises it when an operand is subnormal and the instruction traps:
glibc math testsuite, test-float32x-float64-mul:
Failure: mul_double (0x3.ffffffffffffcp-1024, 0x1.0000000000001p+0):
Exception "Underflow" set
Add _FP_TININESS_AFTER_ROUNDING, as glibc's copy of soft-fp has, and set it for alpha. It determines tininess by rounding a copy of the result as if the exponent range were unbounded, which is what the definition asks for. A plain check of whether the rounded result came out normal is not
equivalent: it differs for values that are still tiny once rounded with an unbounded exponent range but reach the smallest normal on the coarser subnormal grid. That plain check is what the hardware itself does (it decides tininess from the delivered result), and it is why a divide such as -0x4p-128 / 0x1.000002p+0 in FE_DOWNWARD delivers -0x1p-126 and raises nothing although the result is tiny after rounding. Such cases do not trap, so the emulation never sees them; where it does get control, it follows the definition rather than reproducing that deviation, which is what glibc's soft-fp does as well.
The macro defaults to zero, so powerpc, sh and sparc keep determining tininess before rounding as they do now.
--- arch/alpha/include/asm/sfp-machine.h | 4 ++++ include/math-emu/op-common.h | 23 +++++++++++++++++++++-- include/math-emu/soft-fp.h | 8 ++++++++ 3 files changed, 33 insertions(+), 2 deletions(-)
arch/alpha/include/asm/sfp-machine.h +4 -0
@@ -59,6 +59,10 @@ R##_c = FP_CLS_NAN; \ }while (0 ) +/* Alpha determines tininess after rounding, so the emulation must do the + same as the hardware does for the results it produces itself. */ +#define _FP_TININESS_AFTER_ROUNDING 1 +/* Obtain the current rounding mode. */ #define FP_ROUNDMODE mode#define FP_RND_NEAREST (FPCR_DYN_NORMAL >> FPCR_DYN_SHIFT)
include/math-emu/op-common.h +21 -2
@@ -135,6 +135,24 @@ do { \ else \ { \/* we've got a denormalized number */ \ +int _FP_PACK_CANONICAL_is_tiny =1 ; \ + if (_FP_TININESS_AFTER_ROUNDING && X##_e == 0) \ + { \ +/* Architectures that detect tininess after rounding \ +only signal underflow if the result is still \ +subnormal once rounded as if the exponent range \ +were unbounded. Round a copy to find out. */ \ + FP_DECL_##fs(_FP_PACK_CANONICAL_T); \ + /* The class field is not used by the rounding below, \ +and is unused entirely where this block is dead. */ \ + (void)_FP_PACK_CANONICAL_T##_c; \ + _FP_FRAC_COPY_##wc(_FP_PACK_CANONICAL_T, X); \ + _FP_PACK_CANONICAL_T##_s = X##_s; \ + _FP_PACK_CANONICAL_T##_e = X##_e; \ + _FP_ROUND(wc, _FP_PACK_CANONICAL_T); \ + if (_FP_FRAC_OVERP_##wc(fs, _FP_PACK_CANONICAL_T)) \ + _FP_PACK_CANONICAL_is_tiny = 0; \ + } \ X##_e = -X##_e + 1; \ if (X##_e <= _FP_WFRACBITS_##fs) \ { \
@@ -161,8 +179,9 @@ do { \ _FP_FRAC_SRL_##wc(X, _FP_WORKBITS); \ } \ } \ - if ((FP_CUR_EXCEPTIONS & FP_EX_INEXACT) || \ - (FP_TRAPPING_EXCEPTIONS & FP_EX_UNDERFLOW)) \ + if (_FP_PACK_CANONICAL_is_tiny \ + && ((FP_CUR_EXCEPTIONS & FP_EX_INEXACT) || \ + (FP_TRAPPING_EXCEPTIONS & FP_EX_UNDERFLOW))) \ FP_SET_EXCEPTION(FP_EX_UNDERFLOW); \ } \ else \
include/math-emu/soft-fp.h +8 -0
@@ -31,6 +31,14 @@#include <endian.h> #endif +/* Whether the architecture determines tininess of a floating-point +result after rounding rather than before it. IEEE 754 permits either +but requires the same choice for every operation, so this has to agree +with what the hardware does for the results it produces itself. */ +#ifndef _FP_TININESS_AFTER_ROUNDING +#define _FP_TININESS_AFTER_ROUNDING 0 +#endif +#define _FP_WORKBITS 3#define _FP_WORK_LSB ((_FP_W_TYPE)1 << 3)#define _FP_WORK_ROUND ((_FP_W_TYPE)1 << 2)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 995/1257 ocfs2: reserve metadata for a new xattr block and its value tree
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
[ Upstream commit 8ad5fa0c11246d260d7b12c9672e604b1f431b2e ]
Patch series "ocfs2: fix metadata reservation for xattr value trees".
ocfs2_calc_xattr_set_need() reserves too little metadata for a new xattr value's extent tree on three paths. The reservation cannot be topped up once the transaction has started, so ocfs2_add_clusters_in_btree() gives up with RESTART_META when the value root fills and nothing is left. ocfs2_xattr_extend_allocation() turns that into -ENOSPC, after ocfs2_xa_cleanup_value_truncate() has dropped the entry and leaked the clusters already handed out; before commit 0cdc7dde00ec ("ocfs2: fix missing metadata reservation for large xattrs") it was a BUG_ON() instead. It takes a fragmented cluster allocator to get there, since the first extent always fits in the root.
Patch 1 fixes the create side of meta_guess: commit 3ed2be719eb9 ("ocfs2:
allow for more than one data extent when creating xattr") replaced the block reserved for the new xattr block with the two the value tree needs instead of adding them together.
Patch 2 fixes the arm that moves an xattr back into the inode, which charges credits for a value tree but no metadata for one.
Patch 3 drops a second copy of the same reservation on the path that falls through to meta_guess. That one is cleanup rather than a fix and is not for stable, and it must not be backported without patch 1: the duplicate it removes is what currently covers the shortfall patch 1 fixes.
This patch (of 3):
The create side of meta_guess in ocfs2_calc_xattr_set_need() reserves metadata for the new value's extent tree and nothing for the xattr block that will hold it:
} else {
credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS;
if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE) {
struct ocfs2_extent_list *el = &def_xv.xv.xr_list;
meta_add += ocfs2_extend_meta_needed(el);
...Commit 3ed2be719eb9 ("ocfs2: allow for more than one data extent when creating xattr") meant to add that tree on top of the meta_add += 1 the branch already had, but it moved the 1 into the else arm instead, so the external-value case lost it. The 1 is not optional: it is what ocfs2_create_xattr_block() takes from meta_ac through ocfs2_claim_metadata(), and it is spent before the value tree exists.
ocfs2_extend_meta_needed() on the empty def_xv list returns 2, so the branch reserves 2 where 3 are needed. The xattr block consumes one, and when the cluster allocator is fragmented enough that the value needs more than one extent, ocfs2_add_clusters_in_btree() comes back around with a full value root and ocfs2_alloc_context_bits_left() of 1 against a threshold of 2. It answers RESTART_META, which ocfs2_xattr_extend_allocation() turns into a BUG_ON(). Commit 0cdc7dde00ec ("ocfs2: fix missing metadata reservation for large xattrs") downgraded that to -ENOSPC, at the cost of leaking the clusters already handed out: ocfs2_xa_cleanup_value_truncate() takes its !orig_clusters arm, drops the entry and leaves the clusters for fsck.ocfs2 to reclaim.
Reserve for the block and the tree separately.
--- fs/ocfs2/xattr.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
fs/ocfs2/xattr.c +7 -1
@@ -3481,7 +3481,13 @@ static int ocfs2_calc_xattr_set_need(struct inode *inode, credits +=OCFS2_XATTR_BLOCK_CREATE_CREDITS ;if (xi->xi_value_len >OCFS2_XATTR_INLINE_SIZE ) {struct ocfs2_extent_list *el = &def_xv.xv.xr_list; - meta_add +=ocfs2_extend_meta_needed (el); +/* +* One block for the xattr block we may have to +* allocate, the rest for growing the value tree it +* would hold. If ocfs2_xattr_ibody_set() succeeds +* instead, that first block goes unused. +*/ + meta_add +=1 +ocfs2_extend_meta_needed (el); credits +=ocfs2_calc_extend_credits (inode->i_sb, el); }else {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 996/1257 ocfs2: reserve value tree metadata when moving an xattr into the inode
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
[ Upstream commit f5aee8ae5f85f8dfa78160e5c4963494319cdd64 ]
ocfs2_calc_xattr_set_need() charges no metadata for the case where an xattr living in an xattr block or bucket moves back into the inode:
if (old_in_xb) {
if (ocfs2_xattr_can_be_in_inode(inode, xi, xis)) {
clusters_add += new_clusters;
credits += ...;
if (!ocfs2_xattr_is_local(xe))
credits += ocfs2_calc_extend_credits(...);
goto out;
}
}The credits for extending a value tree are there but the matching blocks are not, so meta_add stays 0, ocfs2_init_xattr_set_ctxt() skips ocfs2_reserve_new_metadata_blocks() and ctxt->meta_ac is left NULL.
This is the shape commit 0cdc7dde00ec ("ocfs2: fix missing metadata reservation for large xattrs") fixed for the xattr block case, and it is reached the same way: namevalue_size() charges a value larger than OCFS2_XATTR_INLINE_SIZE as only OCFS2_XATTR_ROOT_SIZE, so ocfs2_xattr_can_be_in_inode() accepts a new value that will be stored outside. ocfs2_xa_prepare_entry() installs a value root from def_xv and grows it, and once the cluster allocator is fragmented enough to need a second extent ocfs2_add_clusters_in_btree() finds the root full with no meta_ac at all and answers RESTART_META. ocfs2_xattr_extend_allocation() turns that into -ENOSPC, or into a BUG_ON() without that commit, and ocfs2_xa_cleanup_value_truncate() takes its !orig_clusters arm, dropping the entry and leaking the clusters already handed out until fsck.ocfs2 reclaims them.
Reserve for the value tree here too. The entry moves back into the inode rather than into a new xattr block, so unlike the create side of meta_guess this needs no block of its own.
--- fs/ocfs2/xattr.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/ocfs2/xattr.c +8 -0
@@ -3381,6 +3381,14 @@ static int ocfs2_calc_xattr_set_need(struct inode *inode, credits +=ocfs2_calc_extend_credits ( inode->i_sb, &def_xv.xv.xr_list); +/* +* A value too big to stay inline is only charged as +* OCFS2_XATTR_ROOT_SIZE above, so it can still need a +* value tree of its own. No xattr block is allocated +* on this path, so the tree is all we reserve for. +*/ +if (xi->xi_value_len >OCFS2_XATTR_INLINE_SIZE ) + meta_add +=ocfs2_extend_meta_needed (&def_xv.xv.xr_list); goto out; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 997/1257 lib/cmdline: fix get_options() count and overflow with large ranges
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Armaan Sandhu <[email protected]>
[ Upstream commit 5d72266218b1c4dd2917f1df2b86f3b0e0a605c9 ]
get_range() stops writing once the array is full, but get_options() still advances its index by the whole range. So "1-100" parsed into four ints reports 99 numbers, and a range like "0-2147483647" wraps the index negative and writes outside the array.
Stop once a range fills the array, bail out in validation mode before the count overflows, and saturate the range length in get_range(). Add KUnit cases; without the fix "0-2147483647" panics the test kernel.
Only root can supply this input, so this is a robustness fix.
--- lib/cmdline.c | 13 ++++++++++++- lib/tests/cmdline_kunit.c | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-)
lib/cmdline.c +12 -1
@@ -11,6 +11,7 @@#include <linux/export.h> #include <linux/kernel.h> +#include <linux/overflow.h> #include <linux/string.h> #include <linux/ctype.h>
@@ -26,7 +27,9 @@ static int get_range(char **str, int *pint, int n) (*str)++; upper_range =simple_strtol ((*str),NULL ,0 ); - inc_counter = upper_range - *pint; +/* Keep the sign of the result when the difference doesn't fit */ +if (check_sub_overflow (upper_range, *pint, &inc_counter)) + inc_counter = upper_range < *pint ?-1 :INT_MAX ;for (x = *pint; n && x < upper_range; x++, n--) *pint++ = x;return inc_counter;
@@ -122,6 +125,14 @@ char *get_options(const char *str, int nints, int *ints) range_nums =get_range ((char **)&str, pint, n);if (range_nums <0 )break ; +/* The range didn't fit, so the array is full */ +if (!validate && range_nums > n) { + i = nints; +break ; + } +/* Leave room for the upper number of the range */ +if (range_nums >=INT_MAX - i) +break ;/* * Decrement the result by one to leave out the * last number in the range. The next iteration
lib/tests/cmdline_kunit.c +39 -0
@@ -140,6 +140,44 @@ static void cmdline_test_range(struct kunit *test) }while (++i <ARRAY_SIZE (cmdline_test_range_strings)); } +static const struct { +const char *in; +int parsed[4 ]; +int validated; +} cmdline_test_range_overflow_cases[] = { + {"1-100" , {3 ,1 ,2 ,3 , },100 , }, + {"1,5-100,7" , {3 ,1 ,5 ,6 , },98 , }, + {"1-2147483646" , {3 ,1 ,2 ,3 , },2147483646 , }, + {"0-2147483647" , {3 ,0 ,1 ,2 , },0 , }, + {"-5-2147483647" , {3 ,-5 ,-4 ,-3 , },0 , }, + {"2147483647--5" , {0 ,2147483647 , },0 , }, + {"1,0-2147483647" , {3 ,1 ,0 ,1 , },1 , }, +}; + +static void cmdline_test_range_overflow (struct kunit *test) +{ +unsigned int i, j; + +for (i =0 ; i <ARRAY_SIZE (cmdline_test_range_overflow_cases); i++) { +const char *in = cmdline_test_range_overflow_cases[i].in; +const int *e = cmdline_test_range_overflow_cases[i].parsed; +/* Two guard elements past the array handed to get_options() */ +int r[ARRAY_SIZE (cmdline_test_range_overflow_cases[0 ].parsed) +2 ]; +int n; + +memset (r,0 ,sizeof (r)); +get_options (in,ARRAY_SIZE (r) -2 , r); +for (j =0 ; j <ARRAY_SIZE (r) -2 ; j++) +KUNIT_EXPECT_EQ_MSG (test, r[j], e[j],"Pattern: %s at %u" , in, j); +for (; j <ARRAY_SIZE (r); j++) +KUNIT_EXPECT_EQ_MSG (test, r[j],0 ,"Pattern: %s out of bound at %u" , in, j); + +get_options (in,0 , &n); +KUNIT_EXPECT_EQ_MSG (test, n, cmdline_test_range_overflow_cases[i].validated, +"Pattern: %s (validated)" , in); + } +} +static void cmdline_test_next_arg_quoted_value (struct kunit *test) {char in[] ="foo=\"bar baz\" qux=1" ;
@@ -258,6 +296,7 @@ static struct kunit_case cmdline_test_cases[] = {KUNIT_CASE (cmdline_test_lead_int),KUNIT_CASE (cmdline_test_tail_int),KUNIT_CASE (cmdline_test_range), +KUNIT_CASE (cmdline_test_range_overflow),KUNIT_CASE (cmdline_test_next_arg_quoted_value),KUNIT_CASE (cmdline_test_next_arg_bare_quote_regression), KUNIT_CASE(cmdline_test_next_arg_mixed_tokens),
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 998/1257 ocfs2: deal with legacy signed dir index name hash values
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
[ Upstream commit d1b49d5ea1bf43cce2b0e249a7f7a30dde133907 ]
Patch series "ocfs2: deal with legacy signed name hash values", v2.
Commit 3bc753c06dd0 ("kbuild: treat char as always unsigned") turned on -funsigned-char globally, which changed the result of two naked 'char' loads in ocfs2 hashing code:
str2hashbuf() val = msg[i] + (val << 8); ocfs2_xattr_name_hash() hash = (hash << 5) ^ (hash >> 27) ^ *name++;
A name byte >= 0x80 used to sign-extend and now zero-extends. Both results are written to disk, the first into the dx leaf when a directory entry is indexed and the second into xe_name_hash when an xattr is stored, so anything written by a pre-6.2 kernel is looked up under a different hash and is no longer found. readdir and listxattr still list those names because neither of them hashes, which makes this look like the filesystem losing entries rather than like a lookup bug. Anderson Ferneda reported it that way for directories with non-ASCII names [1].
Patches 1 and 3 do what ext4 did in commit f3bbac32475b2 ("ext4: deal with legacy signed xattr name hash values"): look up with the current unsigned hash, retry with the legacy signed one on a miss, and always store new entries under the unsigned hash. The retry is skipped when the two hashes come out equal, so an ASCII name does not walk the index twice. Both hash functions now spell out the signedness instead of leaving it to -funsigned-char, as commit 854f0912f813 ("ext4: make xattr char unsignedness in hash explicit") did, so a backport to a kernel without the flag still computes both variants correctly.
Patch 2 is a separate fix, placed before patch 3 so that every commit in the series is correct on its own. ocfs2_check_xattr_bucket_collision() recomputes the hash of the name to decide whether splitting a full bucket can make room for the entry being set. That is right for a new entry and wrong for one that already exists, since an update leaves xe_name_hash alone. Against a bucket holding legacy hashes the comparison does not match, so the split goes ahead and cannot help: a bucket whose entries all share one hash has no divide position. How that ends depends on where the unsigned hash sorts. Below the legacy ones, the set fails with -ENOSPC after growing the tree for nothing. Above them, it lands in the empty bucket the split just appended and stores a second copy of the entry there while the original stays behind, so listxattr reports the name twice. Using the stored hash closes both.
Nothing retires a legacy hash at runtime. Deleting or updating an entry does not rewrite it, and the only code that rehashes existing dirents is ocfs2_expand_inline_dir() on the inline to extent conversion, so the retry stays for as long as the legacy entries do. Rebuilding the index offline is what removes it for good.
This patch (of 3):
Commit 3bc753c06dd0 ("kbuild: treat char as always unsigned") set -funsigned-char globally, which changed the result of the naked 'char' load in str2hashbuf():
val = msg[i] + (val << 8);
A name byte >= 0x80 used to sign-extend and now zero-extends, so ocfs2_dx_dir_name_hash() computes a different hash pair for every name containing one. The pair is written into the dx leaf when the entry is created, so an index built by an older kernel no longer matches and ocfs2_dx_dir_search() returns -ENOENT for a name that readdir still lists.
Search with the current unsigned hash and, on a miss, retry with the legacy signed one, as ext4 does in commit f3bbac32475b2 ("ext4: deal with legacy signed xattr name hash values"). New entries are always indexed under the unsigned hash. Skip the retry when the two hashes are equal, so that a miss on an ASCII name does not walk the index twice.
The retry costs a second walk of the dx tree, so a negative lookup of a name containing a byte >= 0x80 does twice the work. That is bounded and worth it, and directories whose dx root is still inline pay nothing extra, since there the retry only rescans the root block that is already loaded. Nothing retires it at runtime: a legacy entry keeps its legacy hash, because neither deleting nor updating an entry rewrites the dx hash, and the only code that rehashes existing dirents is ocfs2_expand_inline_dir() on the inline to extent conversion. Rebuilding the index offline is what removes the cost for good.
Also spell out the signedness in str2hashbuf() instead of leaving the current hash to -funsigned-char, as commit 854f0912f813 ("ext4: make xattr char unsignedness in hash explicit") did, so that both variants stay correct if this is backported to a kernel without the flag.
--- fs/ocfs2/dir.c | 76 ++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 65 insertions(+), 11 deletions(-)
fs/ocfs2/dir.c +65 -11
@@ -221,7 +221,8 @@ static void TEA_transform(__u32 buf[4], __u32 const in[]) buf[1 ] += b1; } -static void str2hashbuf (const char *msg,int len,__u32 *buf,int num) +static void str2hashbuf (const char *msg,int len,__u32 *buf,int num, +bool legacy_signed) {__u32 pad, val;int i;
@@ -235,7 +236,10 @@ static void str2hashbuf(const char *msg, int len, __u32 *buf, int num)for (i =0 ; i < len; i++) {if ((i %4 ) ==0 ) val = pad; - val = msg[i] + (val <<8 ); +if (legacy_signed) + val = (signed char )msg[i] + (val <<8 ); +else + val = (unsigned char )msg[i] + (val <<8 );if ((i %4 ) ==3 ) { *buf++ = val; val = pad;
@@ -248,8 +252,9 @@ static void str2hashbuf(const char *msg, int len, __u32 *buf, int num) *buf++ = pad; } -static void ocfs2_dx_dir_name_hash (struct inode *dir,const char *name,int len, -struct ocfs2_dx_hinfo *hinfo) +static void __ocfs2_dx_dir_name_hash (struct inode *dir,const char *name, +int len,struct ocfs2_dx_hinfo *hinfo, +bool legacy_signed) {struct ocfs2_super *osb =OCFS2_SB (dir->i_sb);const char *p;
@@ -279,7 +284,7 @@ static void ocfs2_dx_dir_name_hash(struct inode *dir, const char *name, int len, p = name;while (len >0 ) { -str2hashbuf (p, len, in,4 ); +str2hashbuf (p, len, in,4 , legacy_signed);TEA_transform (buf, in); len -=16 ; p +=16 ;
@@ -290,6 +295,19 @@ static void ocfs2_dx_dir_name_hash(struct inode *dir, const char *name, int len, hinfo->minor_hash = buf[1 ]; } +static void ocfs2_dx_dir_name_hash (struct inode *dir,const char *name,int len, +struct ocfs2_dx_hinfo *hinfo) +{ +__ocfs2_dx_dir_name_hash (dir, name, len, hinfo, false); +} + +static void ocfs2_dx_dir_name_hash_signed (struct inode *dir,const char *name, +int len, +struct ocfs2_dx_hinfo *hinfo) +{ +__ocfs2_dx_dir_name_hash (dir, name, len, hinfo, true); +} +/* * bh passed here can be an inode block or a dir data block, depending * on the inode inline data flag.
@@ -966,10 +984,10 @@ static int ocfs2_dx_dir_lookup(struct inode *inode,return ret; } -static int ocfs2_dx_dir_search (const char *name,int namelen, -struct inode *dir, -struct ocfs2_dx_root_block *dx_root, -struct ocfs2_dir_lookup_result *res) +static int __ocfs2_dx_dir_search (const char *name,int namelen, +struct inode *dir, +struct ocfs2_dx_root_block *dx_root, +struct ocfs2_dir_lookup_result *res) {int ret, i, found;u64 phys;
@@ -982,8 +1000,6 @@ static int ocfs2_dx_dir_search(const char *name, int namelen,struct ocfs2_extent_list *dr_el;struct ocfs2_dx_entry_list *entry_list; -ocfs2_dx_dir_name_hash (dir, name, namelen, &res->dl_hinfo); -if (ocfs2_dx_root_inline (dx_root)) { entry_list = &dx_root->dr_entries; goto search;
@@ -1080,6 +1096,44 @@ static int ocfs2_dx_dir_search(const char *name, int namelen,return ret; } +static int ocfs2_dx_dir_search (const char *name,int namelen, +struct inode *dir, +struct ocfs2_dx_root_block *dx_root, +struct ocfs2_dir_lookup_result *res) +{ +struct ocfs2_dx_hinfo legacy; +int ret; + +ocfs2_dx_dir_name_hash (dir, name, namelen, &res->dl_hinfo); + + ret =__ocfs2_dx_dir_search (name, namelen, dir, dx_root, res); +if (ret != -ENOENT ) +return ret; + +/* +* Nothing under the current hash. The entry may have been indexed by +* an older kernel, which sign-extended the name bytes when hashing. +* New entries are always indexed under the unsigned hash, so only fall +* back to the legacy signed one when it can actually differ: an ASCII +* name hashes the same either way, and a genuine miss on one should +* not have to walk the index twice. +*/ +ocfs2_dx_dir_name_hash_signed (dir, name, namelen, &legacy); +if (legacy.major_hash == res->dl_hinfo.major_hash && + legacy.minor_hash == res->dl_hinfo.minor_hash) +return ret; + + res->dl_hinfo = legacy; + + ret =__ocfs2_dx_dir_search (name, namelen, dir, dx_root, res); +if (ret) +return ret; + +pr_warn_once ("ocfs2: directory index with signed name hash\n" ); + +return 0 ; +} +static int ocfs2_find_entry_dx (const char *name,int namelen,struct inode *dir,struct ocfs2_dir_lookup_result *lookup)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 999/1257 ocfs2: use the stored hash when checking xattr bucket collision
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
[ Upstream commit e39baff18b85cf8956aee138d7944b6581e8ba36 ]
ocfs2_check_xattr_bucket_collision() decides whether splitting a full bucket can make room for the entry being set by recomputing the hash of the name:
u32 name_hash = ocfs2_xattr_name_hash(inode, name, strlen(name)); if (name_hash != le32_to_cpu(xh->xh_entries[0].xe_name_hash)) return 0;
For a new entry that is the hash it will be stored under, so comparing it is correct. An existing entry keeps the hash it already has: an update never rewrites xe_name_hash, since ocfs2_xa_add_entry() is the only writer of that field for a real entry and ocfs2_xa_prepare_entry() calls it only when loc->xl_entry is NULL.
An entry stored by a kernel that sign-extended the name bytes when hashing can still be updated, because ocfs2_xattr_find_entry() searches a non-indexed xattr block by memcmp on the name and never looks at xe_name_hash. Growing it past the space left in the block converts the block into a tree, ocfs2_cp_xattr_block_to_bucket() fills the bucket in stored hash order, and the update runs out of room in the bucket too. The collision check then compares the unsigned hash against the legacy hashes in the bucket and reports no collision.
ocfs2_xattr_set_entry_index_block() goes on to allocate a bucket that ocfs2_divide_xattr_bucket() cannot fill: a bucket whose entries all share one hash has no divide position, so all it does is append an empty bucket with a sentinel hash one above the last entry's.
The re-search that follows depends on where the unsigned hash sorts. Below the legacy ones, it comes back to the full bucket and the set fails with -ENOSPC, having grown the tree for nothing. Above them, it lands on the new empty bucket, which ocfs2_xattr_bucket_find() handles explicitly and ocfs2_find_xe_in_bucket() scans zero times, so the set stores a second copy of the entry under the unsigned hash and returns success. The original stays in the full bucket, listxattr reports the name twice and getxattr returns the new copy.
Pass the hash the entry is stored under instead: the stored one for an existing entry, the unsigned one for a new entry. A tree whose entries are all stored under the unsigned hash sees no change, since there the two are the same value.
--- fs/ocfs2/xattr.c | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-)
fs/ocfs2/xattr.c +17 -10
@@ -5769,16 +5769,14 @@ static int ocfs2_rm_xattr_cluster(struct inode *inode,/* * check whether the xattr bucket is filled up with the same hash value. -* If we want to insert the xattr with the same hash, return -ENOSPC. -* If we want to insert a xattr with different hash value, go ahead -* and ocfs2_divide_xattr_bucket will handle this. +* If the entry being set carries that same hash, return -ENOSPC, since +* ocfs2_divide_xattr_bucket() has no divide position to work with. +* Otherwise go ahead and ocfs2_divide_xattr_bucket() will handle this. */ -static int ocfs2_check_xattr_bucket_collision (struct inode *inode, -struct ocfs2_xattr_bucket *bucket, -const char *name) +static int ocfs2_check_xattr_bucket_collision (struct ocfs2_xattr_bucket *bucket, +u32 name_hash) {struct ocfs2_xattr_header *xh =bucket_xh (bucket); -u32 name_hash =ocfs2_xattr_name_hash (inode, name,strlen (name));if (name_hash !=le32_to_cpu (xh->xh_entries[0 ].xe_name_hash))return 0 ;
@@ -5847,6 +5845,7 @@ static int ocfs2_xattr_set_entry_index_block(struct inode *inode,struct ocfs2_xattr_search *xs, struct ocfs2_xattr_set_ctxt *ctxt) { + u32 name_hash;int ret;trace_ocfs2_xattr_set_entry_index_block (xi->xi_name);
@@ -5866,10 +5865,18 @@ static int ocfs2_xattr_set_entry_index_block(struct inode *inode,* the maximum number of collisions we will allow for then is * one bucket's worth, so check it here whether we need to * add a new bucket for the insert. +* +* An existing entry keeps the hash it was stored under, and that is +* the hash a split has to work with. A new entry is stored under the +* unsigned one, which is what ocfs2_xa_add_entry() will write. */ - ret =ocfs2_check_xattr_bucket_collision (inode, - xs->bucket, - xi->xi_name); +if (xs->not_found) + name_hash =ocfs2_xattr_name_hash (inode, xi->xi_name, + xi->xi_name_len); +else + name_hash =le32_to_cpu (xs->here->xe_name_hash); + + ret =ocfs2_check_xattr_bucket_collision (xs->bucket, name_hash);if (ret) {mlog_errno (ret); goto out;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1000/1257 ocfs2: deal with legacy signed xattr name hash values
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
[ Upstream commit 824d26d11448b4d4f19677bce27c7fe5e962f4c6 ]
Commit 3bc753c06dd0 ("kbuild: treat char as always unsigned") set -funsigned-char globally, which changed the result of the naked 'char' load in ocfs2_xattr_name_hash():
hash = (hash << OCFS2_HASH_SHIFT) ^ (hash >> (8*sizeof(hash) - OCFS2_HASH_SHIFT)) ^ *name++;
A name byte >= 0x80 used to sign-extend and now zero-extends, so the hash no longer matches the xe_name_hash an older kernel stored. An indexed xattr tree is searched by that hash alone, and both the bucket binary search and the entry scan within it stop as soon as the wanted hash falls below an entry's, so the entry is never reached: getxattr, setxattr and removexattr return -ENODATA for a name that listxattr still lists.
Search with the current unsigned hash and, on a miss, retry with the legacy signed one, as ext4 does in commit f3bbac32475b2 ("ext4: deal with legacy signed xattr name hash values"). New entries are always stored under the unsigned hash. Skip the retry when the two hashes are equal, so that a miss on an ASCII name does not walk the tree twice.
A miss is not empty handed: ocfs2_xattr_bucket_find() leaves xs->bucket holding the bucket a new entry would go into. So after a double miss drop it and search once more with the unsigned hash, otherwise a new entry would be placed by its legacy hash and stored under its unsigned one, breaking the ordering the search relies on.
Only indexed trees are affected; inline xattrs and non-indexed xattr blocks compare names with memcmp and never look at the hash.
Also spell out the signedness instead of leaving the current hash to -funsigned-char, as commit 854f0912f813 ("ext4: make xattr char unsignedness in hash explicit") did, so that both variants stay correct if this is backported to a kernel without the flag.
--- fs/ocfs2/xattr.c | 93 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 82 insertions(+), 11 deletions(-)
fs/ocfs2/xattr.c +82 -11
@@ -561,9 +561,10 @@ static inline const char *ocfs2_xattr_prefix(int name_index)return handler ?xattr_prefix (handler) :NULL ; } -static u32 ocfs2_xattr_name_hash (struct inode *inode, -const char *name, -int name_len) +static u32 __ocfs2_xattr_name_hash (struct inode *inode, +const char *name, +int name_len, +bool legacy_signed) {/* Get hash value of uuid from super block */ u32 hash =OCFS2_SB (inode->i_sb)->uuid_hash;
@@ -572,13 +573,30 @@ static u32 ocfs2_xattr_name_hash(struct inode *inode,/* hash extended attribute name */ for (i =0 ; i < name_len; i++) { hash = (hash <<OCFS2_HASH_SHIFT ) ^ - (hash >> (8 *sizeof (hash) -OCFS2_HASH_SHIFT )) ^ - *name++; + (hash >> (8 *sizeof (hash) -OCFS2_HASH_SHIFT )); +if (legacy_signed) + hash ^= (signed char )name[i]; +else + hash ^= (unsigned char )name[i]; }return hash; } +static u32 ocfs2_xattr_name_hash (struct inode *inode, +const char *name, +int name_len) +{ +return __ocfs2_xattr_name_hash (inode, name, name_len, false); +} + +static u32 ocfs2_xattr_name_hash_signed (struct inode *inode, +const char *name, +int name_len) +{ +return __ocfs2_xattr_name_hash (inode, name, name_len, true); +} +static int ocfs2_xattr_entry_real_size (int name_len,size_t value_len) { return namevalue_size(name_len, value_len) +
@@ -4187,11 +4205,12 @@ static int ocfs2_xattr_bucket_find(struct inode *inode,return ret; } -static int ocfs2_xattr_index_block_find (struct inode *inode, -struct buffer_head *root_bh, -int name_index, -const char *name, -struct ocfs2_xattr_search *xs) +static int __ocfs2_xattr_index_block_find (struct inode *inode, +struct buffer_head *root_bh, +int name_index, +const char *name, +u32 name_hash, +struct ocfs2_xattr_search *xs) {int ret; struct ocfs2_xattr_block *xb =
@@ -4200,7 +4219,6 @@ static int ocfs2_xattr_index_block_find(struct inode *inode,struct ocfs2_extent_list *el = &xb_root->xt_list;u64 p_blkno =0 ;u32 first_hash, num_clusters =0 ; -u32 name_hash =ocfs2_xattr_name_hash (inode, name,strlen (name));if (le16_to_cpu (el->l_next_free_rec) ==0 )return -ENODATA ;
@@ -4231,6 +4249,59 @@ static int ocfs2_xattr_index_block_find(struct inode *inode,return ret; } +static int ocfs2_xattr_index_block_find (struct inode *inode, +struct buffer_head *root_bh, +int name_index, +const char *name, +struct ocfs2_xattr_search *xs) +{ +u32 name_hash, legacy_hash; +int name_len =strlen (name); +int ret; + + name_hash =ocfs2_xattr_name_hash (inode, name, name_len); + + ret =__ocfs2_xattr_index_block_find (inode, root_bh, name_index, name, + name_hash, xs); +if (ret != -ENODATA ) +return ret; + +/* +* Nothing under the current hash. The entry may have been stored by +* an older kernel, which sign-extended the name bytes when hashing. +* Skip the retry when the two hashes are equal, so that a name made +* only of ASCII does not have to walk the tree twice. +*/ + legacy_hash =ocfs2_xattr_name_hash_signed (inode, name, name_len); +if (legacy_hash == name_hash) +return ret; + +/* +* A miss still leaves xs->bucket holding the bucket a new entry would +* be inserted into, so drop it before searching again. +*/ +ocfs2_xattr_bucket_relse (xs->bucket); + + ret =__ocfs2_xattr_index_block_find (inode, root_bh, name_index, name, + legacy_hash, xs); +if (!ret) { +pr_warn_once ("ocfs2: xattr tree with signed name hash\n" ); +return ret; + } +if (ret != -ENODATA ) +return ret; + +/* +* Not under either hash. Restore the unsigned placement, since that +* is where a new entry is stored: leaving the bucket where the legacy +* hash put it would break the ordering the search relies on. +*/ +ocfs2_xattr_bucket_relse (xs->bucket); + +return __ocfs2_xattr_index_block_find (inode, root_bh, name_index, name, + name_hash, xs); +} + static int ocfs2_iterate_xattr_buckets(struct inode *inode, u64 blkno, u32 clusters,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1001/1257 ocfs2/cluster: initialize heartbeat regions before publishing them
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit c5b7a30a5172317e1e3cba61d8c9f9c588c497bb ]
A region on o2hb_all_regions must have an initialized config item and name. o2hb_heartbeat_group_make_item() currently links the zeroed region under o2hb_live_lock, drops the lock, and only then initializes hr_item. The lock therefore protects the list without protecting initialization from readers of the published item.
With global heartbeat enabled, a DLM_QUERY_REGION from the current joining node can pass the existing-domain and protocol checks while a configfs mkdir creates another region. The DLM locks are not taken by the constructor, and the network worker does not take the configfs subsystem mutex. The following ordering is possible:
Configfs mkdir O2net receive worker
-------------- --------------------
Allocate reg
Lock o2hb_live_lock
Link into o2hb_all_regions
Unlock o2hb_live_lock
dlm_query_region_handler()
dlm_match_regions()
o2hb_get_all_regions()
Lock o2hb_live_lock Copy 32 bytes from NULL name Unlock o2hb_live_lock
config_item_init_type_name()
The query thus dereferences NULL. Initialize hr_item before linking the region so the existing list lock also orders name initialization before any reader. Reject a failed name allocation, since the initialization helper does not propagate that error.
Use config_item_put() on initialized constructor failures to release the name and respect references retained by o2hb_region_pin(). Initialize the list heads, mutex and delayed works needed by o2hb_region_release() before any such put, and leave the list node self-linked after rollback. Keep the existing handler drain before removing a failed published item.
KASAN report as below:
==================================================================
BUG: KASAN: null-ptr-deref in o2hb_get_all_regions+0xbb/0x1f0
Read of size 32 at addr 0000000000000000 by task kworker/u16:1/14
CPU: 2 UID: 0 PID: 14 Comm: kworker/u16:1 Not tainted 7.3.0-rc4-next-20260921-pmb-ocfs2-functional-v1+ #1 PREEMPT(lazy)
Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
Workqueue: o2net o2net_rx_until_empty
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
kasan_report+0xe0/0x110
? o2hb_get_all_regions+0xbb/0x1f0
kasan_check_range+0x105/0x1b0
__asan_memcpy+0x23/0x60
o2hb_get_all_regions+0xbb/0x1f0
dlm_query_region_handler+0x4c2/0xc20
? __pfx_dlm_query_region_handler+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
? srso_alias_return_thunk+0x5/0xfbef5
? kvm_clock_get_cycles+0x31/0x60
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_dlm_query_region_handler+0x10/0x10
o2net_rx_until_empty+0x1a50/0x3200
? reacquire_held_locks+0xdd/0x200
? __pfx_o2net_rx_until_empty+0x10/0x10
? lock_acquire+0x190/0x300
? process_one_work+0x935/0x1b40
? process_one_work+0x834/0x1b40
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
? srso_alias_return_thunk+0x5/0xfbef5
process_one_work+0x9a8/0x1b40
? __pfx_process_one_work+0x10/0x10
? lock_acquire+0x190/0x300
? lock_is_held_type+0x8f/0x100
? srso_alias_return_thunk+0x5/0xfbef5
worker_thread+0x65c/0xe40
? srso_alias_return_thunk+0x5/0xfbef5
? __kthread_parkme+0x177/0x220
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_worker_thread+0x10/0x10
kthread+0x351/0x460
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_kthread+0x10/0x10
ret_from_fork+0x659/0x940
? __pfx_ret_from_fork+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __switch_to+0x74f/0xf70
? __pfx_kthread+0x10/0x10
ret_from_fork_asm+0x1a/0x30
</TASK>
==================================================================--- fs/ocfs2/cluster/heartbeat.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-)
fs/ocfs2/cluster/heartbeat.c +17 -9
@@ -2137,6 +2137,18 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *g } reg->hr_node_num =O2NM_MAX_NODES ; +INIT_LIST_HEAD (®->hr_all_item); +mutex_init (®->hr_arming_mutex); + reg->hr_stopping = true; +INIT_DELAYED_WORK (®->hr_write_timeout_work, o2hb_write_timeout); +INIT_DELAYED_WORK (®->hr_nego_timeout_work, o2hb_nego_timeout); +INIT_LIST_HEAD (®->hr_handler_list); +config_item_init_type_name (®->hr_item, name, &o2hb_region_type); +if (!config_item_name (®->hr_item)) { + ret = -ENOMEM ; + goto put_item; + } +spin_lock (&o2hb_live_lock); reg->hr_region_num =0 ;if (o2hb_global_heartbeat_active ()) {
@@ -2145,26 +2157,19 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *gif (reg->hr_region_num >=O2NM_MAX_REGIONS ) {spin_unlock (&o2hb_live_lock); ret = -EFBIG ; - goto free; + goto put_item; }set_bit (reg->hr_region_num, o2hb_region_bitmap); }list_add_tail (®->hr_all_item, &o2hb_all_regions);spin_unlock (&o2hb_live_lock); -config_item_init_type_name (®->hr_item, name, &o2hb_region_type); -/* this is the same way to generate msg key as dlm, for local heartbeat, * name is also the same, so make initial crc value different to avoid * message key conflict. */ reg->hr_key =crc32_le (reg->hr_region_num +O2NM_MAX_REGIONS , name,strlen (name)); -mutex_init (®->hr_arming_mutex); - reg->hr_stopping = true; -INIT_DELAYED_WORK (®->hr_write_timeout_work, o2hb_write_timeout); -INIT_DELAYED_WORK (®->hr_nego_timeout_work, o2hb_nego_timeout); -INIT_LIST_HEAD (®->hr_handler_list); ret = o2net_register_handler(O2HB_NEGO_TIMEOUT_MSG, reg->hr_key, sizeof(struct o2hb_nego_msg), o2hb_nego_timeout_handler,
@@ -2187,10 +2192,13 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *go2net_unregister_and_flush_handler_list (®->hr_handler_list); remove_item:spin_lock (&o2hb_live_lock); -list_del (®->hr_all_item); +list_del_init (®->hr_all_item);if (o2hb_global_heartbeat_active ())clear_bit (reg->hr_region_num, o2hb_region_bitmap);spin_unlock (&o2hb_live_lock); +put_item: +config_item_put (®->hr_item); +return ERR_PTR (ret); free:kfree (reg);return ERR_PTR (ret);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1002/1257 Documentation: hyperv: Update documentation for sending VMBus packets
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michael Kelley <[email protected]>
[ Upstream commit 6a3d77a0a8cf69cf3d234305e6711729eb5d10c4 ]
The functions for sending VMBus packets have changed. vmbus_sendpacket_mpb_desc() can target multiple ranges, and vmbus_sendpacket_pagebuffer() has been removed. vmbus_sendpacket_getid() has been added. Update the documentation accordingly.
--- Documentation/virt/hyperv/vmbus.rst | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-)
Documentation/virt/hyperv/vmbus.rst +9 -8
@@ -141,14 +141,15 @@ Three functions exist to send VMBus channel messages: 1. vmbus_sendpacket(): Control-only messages and messages with embedded data -- no GPAs -2. vmbus_sendpacket_pagebuffer(): Message with list of GPAs - identifying data to transfer. An offset and length is - associated with each GPA so that multiple discontinuous areas - of guest memory can be targeted. -3. vmbus_sendpacket_mpb_desc(): Message with list of GPAs - identifying data to transfer. A single offset and length is - associated with a list of GPAs. The GPAs must describe a - single logical area of guest memory to be targeted. +2. vmbus_sendpacket_getid(): Similar to vmbus_sendpacket() but returns + a transaction ID that is matched against a reply from the Hyper-V + host. Useful when the struct completion (or other rendezvous data) + must reside on the caller's stack. By invalidating the transaction + ID before exiting the function due to a timeout or other error, a + late arriving interrupt is assured to not trash the stack. +3. vmbus_sendpacket_mpb_desc(): Message with one or more data ranges + to target. Each range consists of a single offset and length plus + a list of GPAs that describe a logical area of guest memory. Historically, Linux guests have trusted Hyper-V to send well-formed and valid messages, and Linux drivers for synthetic devices did not
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1003/1257 platform/x86: asus-wmi: fix TUF keyboard power state shutdown naming
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartu Alev <[email protected]>
[ Upstream commit 3d9a175707eeb15a2d577af1e669b98e0236719b ]
The fourth state flag of kbd_rgb_state_index is named "keyboard" and has long been treated as having no effect. In hardware the flag, BIT(7) of the payload sent to the TUF RGB state device, gates whether the keyboard backlight stays lit while the machine powers off: with the bit set the keyboard lights up white during the ACPI S5 sequence, with the bit clear the machine powers off dark. Verified by A/B testing both values on a TUF Gaming A15 (FA507NV).
Rename the fourth field and its index entry from "keyboard" to "shutdown". The write format is unchanged, the value is still positional, and the diff is two variable names and one string, so it backports cleanly.
--- drivers/platform/x86/asus-wmi.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/platform/x86/asus-wmi.c +4 -4
@@ -1132,10 +1132,10 @@ static ssize_t kbd_rgb_state_store(struct device *dev,struct device_attribute *attr, const char *buf, size_t count) { - u32 flags, cmd, boot, awake, sleep, keyboard; + u32 flags, cmd, boot, awake, sleep, shutdown;int err; -if (sscanf (buf,"%d %d %d %d %d" , &cmd, &boot, &awake, &sleep, &keyboard) !=5 ) +if (sscanf (buf,"%d %d %d %d %d" , &cmd, &boot, &awake, &sleep, &shutdown) !=5 )return -EINVAL ;if (cmd)
@@ -1148,7 +1148,7 @@ static ssize_t kbd_rgb_state_store(struct device *dev, flags |=BIT (3 );if (sleep) flags |=BIT (5 ); -if (keyboard) +if (shutdown) flags |=BIT (7 );/* 0xbd is the required default arg0 for the method. Nothing happens otherwise */
@@ -1162,7 +1162,7 @@ static ssize_t kbd_rgb_state_store(struct device *dev,static DEVICE_ATTR_WO (kbd_rgb_state); static DEVICE_STRING_ATTR_RO(kbd_rgb_state_index, 0444, - "cmd boot awake sleep keyboard"); + "cmd boot awake sleep shutdown");static struct attribute *kbd_rgb_state_attrs[] = { &dev_attr_kbd_rgb_state.attr,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1004/1257 writeback: reset dirtied_when when switching wbs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Julian Sun <[email protected]>
[ Upstream commit 13b9a606dd0a6cf9bac12894c97b9546d22a7425 ]
When switching a dirty inode to another wb, inode_do_switch_wbs() puts it at the newest end of the target b_dirty list instead of searching for its sorted position. This requires updating dirtied_when, which move_expired_inodes() uses to decide where to stop scanning.
However, the switch updates dirtied_time_when instead. This leaves b_dirty out of order and can make the scan stop before reaching older inodes. It also resets the lazytime expiration timestamp, potentially delaying timestamp writeback.
Update dirtied_when instead, preserving both the constant-time insertion and the lazytime expiration timestamp. Correct the field name in the comment and document the distinction between the two inode timestamps.
--- fs/fs-writeback.c | 6 +++--- include/linux/fs.h | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-)
fs/fs-writeback.c +3 -3
@@ -468,12 +468,12 @@ static bool inode_do_switch_wbs(struct inode *inode,if (inode_state_read (inode) &I_DIRTY_ALL ) {/* * We need to keep b_dirty list sorted by -* dirtied_time_when. However properly sorting the +* dirtied_when. However properly sorting the * inode in the list gets too expensive when switching * many inodes. So just attach inode at the end of the -* dirty list and clobber the dirtied_time_when. +* dirty list and clobber the dirtied_when. */ - inode->dirtied_time_when = jiffies; + inode->dirtied_when = jiffies;inode_io_list_move_locked (inode, new_wb, &new_wb->b_dirty); }else {
include/linux/fs.h +3 -1
@@ -815,7 +815,9 @@ struct inode {/* 32-bit hole */ struct rw_semaphore i_rwsem; -unsigned long dirtied_when;/* jiffies of first dirtying */ +/* Timestamp for writeback list ordering and age checks (jiffies). */ +unsigned long dirtied_when; +/* Start time for deciding when lazytime updates need writeback (jiffies). */ unsigned long dirtied_time_when;struct hlist_node i_hash;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1005/1257 writeback: clear old wb dirty state after inode switches
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Julian Sun <[email protected]>
[ Upstream commit a396fe9f74ea367ae3fab2dcb70b24e83db9f0cb ]
Switching an inode to another wb updates the target wb's dirty-I/O state, but no longer checks whether the source wb's dirty-I/O lists became empty. The check was lost when inode_io_list_del_locked(inode, old_wb) was removed to support tracking clean attached inodes.
If the last dirty inode is moved, WB_has_dirty_io remains set on the old wb and its bandwidth contribution remains in bdi->tot_write_bandwidth. This can keep an empty wb scheduled for periodic writeback and overstate the total bandwidth used to distribute writeback work.
Call wb_io_lists_depopulated() on the old wb after the batch of inode switches, while its list_lock is still held. This clears the flag and removes the bandwidth contribution if its dirty-I/O lists are empty.
--- fs/fs-writeback.c | 1 + 1 file changed, 1 insertion(+)
fs/fs-writeback.c +1 -0
@@ -566,6 +566,7 @@ static void process_inode_switch_wbs(struct bdi_writeback *new_wb, } } +wb_io_lists_depopulated (old_wb);spin_unlock (&new_wb->list_lock);spin_unlock (&old_wb->list_lock);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1006/1257 ALSA: aloop: Update the PCM Slave controls for a matching playback
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Henrik Enquist <[email protected]>
[ Upstream commit c3bde2beacbcb40790f0e3c3f909f9e16bbced9c ]
The "PCM Slave" format, rate, channels and access controls report the parameters of the playback side of a cable. loopback_check_format() updates them when a playback starts, but returns early when a capture is open and its parameters match. The controls then keep the module defaults, or the parameters of an earlier stream.
A playback that joins an open capture with the same parameters is the normal case without notify, where it is constrained to the capture's parameters, and also with notify whenever the player happens to use them. An application that reads the controls to find the playback's parameters, for example to reopen the capture side at the right rate after a restart, then gets the wrong values.
Only skip the capture stop when the parameters match, and update the controls in every case. A value event is still sent only for a control whose value changes.
Reproducer:
arecord -D hw:Loopback,1,0 -r 44100 -f S16_LE -c 2 /dev/null & aplay -D hw:Loopback,0,0 -t raw -r 44100 -f S16_LE -c 2 /dev/zero & amixer -c Loopback cget "iface=PCM,name='PCM Slave Rate',device=1"
Before: the control reports 48000, the module default.
After: it reports 44100.
--- sound/drivers/aloop.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
sound/drivers/aloop.c +7 -4
@@ -412,11 +412,14 @@ static int loopback_check_format(struct loopback_cable *cable, int stream) runtime->channels != cruntime->channels ||is_access_interleaved (runtime->access) !=is_access_interleaved (cruntime->access); -if (!check) -return 0 ; -if (stream ==SNDRV_PCM_STREAM_CAPTURE ) +/* +* Matching params also go on to the update below, so that +* the setup controls follow a playback that joins an open +* capture. +*/ +if (check && stream ==SNDRV_PCM_STREAM_CAPTURE )return -EIO ; -else if (cruntime->state ==SNDRV_PCM_STATE_RUNNING ) { +else if (check && cruntime->state ==SNDRV_PCM_STATE_RUNNING ) {/* close must not free the peer runtime below */ snd_refcount_get (&cable->stop_count); stop_capture = true;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1007/1257 sh: maple: Use the matching IRQ cookie when invoking free_irq()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Runyu Xiao <[email protected]>
[ Upstream commit e3ef44e77b40e3cecfb34757ff3c15ecceea0309 ]
The Maple DMA and VBLANK handlers are registered with &maple_unsupported_device as their dev_id. Passing NULL to free_irq() cannot find either action, so the handlers remain registered and the IRQ core warns.
Use the same cookie when freeing both handlers on the error paths.
--- drivers/sh/maple/maple.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/sh/maple/maple.c +2 -2
@@ -863,10 +863,10 @@ static int __init maple_bus_init(void)kmem_cache_destroy (maple_queue_cache); cleanup_bothirqs: -free_irq (HW_EVENT_VSYNC ,0 ); +free_irq (HW_EVENT_VSYNC , &maple_unsupported_device); cleanup_irq: -free_irq (HW_EVENT_MAPLE_DMA ,0 ); +free_irq (HW_EVENT_MAPLE_DMA , &maple_unsupported_device); cleanup_dma:free_pages ((unsigned long ) maple_sendbuf,MAPLE_DMA_PAGES );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1008/1257 PCI/pwrctrl: generic: Fix leaking array from of_regulator_bulk_get_all()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexey Charkov <[email protected]>
[ Upstream commit ee450e3a2d334c7e6383d8a55ad2d53b3822bacc ]
of_regulator_bulk_get_all() allocates the consumers array and returns it to the caller, who is expected to free it at an appropriate time. PCI pwrctrl never did, leading to a memory leak.
Add an explicit kfree() for the consumers array.
--- drivers/pci/pwrctrl/generic.c | 1 + 1 file changed, 1 insertion(+)
drivers/pci/pwrctrl/generic.c +1 -0
@@ -63,6 +63,7 @@ static void devm_slot_pwrctrl_release(void *data)struct slot_pwrctrl *slot = data;regulator_bulk_free (slot->num_supplies, slot->supplies); +kfree (slot->supplies); }static int slot_pwrctrl_probe (struct platform_device *pdev)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1009/1257 PCI/pwrctrl: Only destroy devices created by pwrctrl core
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Lin <[email protected]>
[ Upstream commit 7bf2ebcb7ca1e8814d3d0e35214a8e4b2193a619 ]
pci_pwrctrl_create_device() only creates platform devices for OF nodes that pci_pwrctrl_is_required() accepts, but pci_pwrctrl_destroy_device() unregisters the platform device of every available child node without that check.
Nodes under a PCI host controller that are not pwrctrl devices may have been populated by another mechanism. Destroying them here would tear down devices owned by other code.
Mirror the check done at creation time so that only devices created by the pwrctrl core are removed.
--- drivers/pci/pwrctrl/core.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/pci/pwrctrl/core.c +3 -0
@@ -388,6 +388,9 @@ static void pci_pwrctrl_destroy_device(struct device_node *np)for_each_available_child_of_node_scoped (np, child)pci_pwrctrl_destroy_device (child); +if (!pci_pwrctrl_is_required (np)) +return ; + pdev =of_find_device_by_node (np);if (!pdev)return ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1010/1257 nvmet: take subsys->lock while force-reconnecting in nvmet_subsys_attr_qid_max_store()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yu Zhang <[email protected]>
[ Upstream commit 9f426f14051181e251590783e68ce589a63e2b1c ]
nvmet_subsys_attr_qid_max_store() sets subsys->max_qid and then walks subsys->ctrls to force every controller to reconnect, but it holds only nvmet_config_sem (for write). subsys->ctrls is protected by subsys->lock:nvmet_alloc_ctrl() adds an entry under subsys->lock, and nvmet_ctrl_free() removes it under subsys->lock with list_del() + kfree() (not kfree_rcu). The free path takes no nvmet_config_sem, so the two locks are independent.
A controller teardown (host disconnect, keep-alive timeout or fatal error -> nvmet_sq_destroy() -> nvmet_ctrl_put() -> nvmet_ctrl_free()) can therefore list_del() an entry while qid_max_store() is iterating the list, corrupting the walk.
KASAN, concurrent "echo 128 > .../subsystems/<nqn>/attr_qid_max" racing nvme-loop controllers connecting and disconnecting, panics in seconds:
BUG: KASAN: null-ptr-deref in nvmet_subsys_attr_qid_max_store+0x10d/0x1b0 Read of size 8 at addr 0000000000000090 Call Trace: nvmet_subsys_attr_qid_max_store+0x10d/0x1b0 configfs_write_iter+0x1a7/0x250 vfs_write+0x5df/0x940 ksys_write+0xfd/0x1e0
(also seen as a general-protection fault dereferencing a LIST_POISON pointer at the same instruction.)
Take subsys->lock around the list_for_each_entry() loop, matching every other subsys->ctrls accessor. ->delete_ctrl() only queues asynchronous controller teardown, so it does not re-enter subsys->lock under the loop.
--- drivers/nvme/target/configfs.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/nvme/target/configfs.c +2 -0
@@ -1689,8 +1689,10 @@ static ssize_t nvmet_subsys_attr_qid_max_store(struct config_item *item, subsys->max_qid = qid_max;/* Force reconnect */ +mutex_lock (&subsys->lock);list_for_each_entry (ctrl, &subsys->ctrls, subsys_entry) ctrl->ops->delete_ctrl (ctrl); +mutex_unlock (&subsys->lock);up_write (&nvmet_config_sem);return cnt;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1011/1257 mshv_vtl: reject poll files with multiple waitqueues
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
[ Upstream commit 70cd4623f3e5068a72c72791b96f2dcb4c991131 ]
MSHV_SET_POLL_FILE invokes a file descriptor poll callback with a poll table backed by a single embedded wait entry. A poll callback may, however, register the table with more than one waitqueue. pipe_poll() does this naturally for an O_RDWR FIFO.
The second registration currently warns but then inserts the same list node into another list. The new insertion overwrites the entry links while the first waitqueue still points at it, corrupting the first waitqueue and causing an invalid callback traversal when that queue wakes.
Reject a second distinct waitqueue, remove the first registration through the common removal helper, and return -EINVAL from the ioctl. Repeated registration of the same waitqueue is treated as a no-op. A rejected replacement leaves the CPU slot unregistered, consistent with the existing remove-before-register ordering. Single-waitqueue users such as the OpenHCL io_uring poll file keep their existing behavior.
An LLM assisted the source audit, fix development, and validation of this issue.
--- drivers/hv/mshv_vtl_main.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-)
drivers/hv/mshv_vtl_main.c +21 -2
@@ -73,6 +73,7 @@ struct mshv_vtl_poll_file {wait_queue_entry_t wait;wait_queue_head_t *wqh;poll_table pt; +int error;int cpu; };
@@ -482,7 +483,18 @@ static void mshv_vtl_ptable_queue_proc(struct file *file, wait_queue_head_t *wqh { struct mshv_vtl_poll_file *poll_file = container_of(pt, struct mshv_vtl_poll_file, pt); -WARN_ON (poll_file->wqh); +if (poll_file->error) +return ; + +if (poll_file->wqh) { +if (poll_file->wqh == wqh) +return ; + +mshv_vtl_poll_file_remove_wait_queue (poll_file); + poll_file->error = -EINVAL ; +return ; + } + poll_file->wqh = wqh;add_wait_queue (wqh, &poll_file->wait); }
@@ -492,6 +504,7 @@ static int mshv_vtl_ioctl_set_poll_file(struct mshv_vtl_set_poll_file __user *usstruct file *file, *old_file;struct mshv_vtl_poll_file *poll_file;struct mshv_vtl_set_poll_file input; +int ret;if (copy_from_user (&input, user_input,sizeof (input)))return -EFAULT ;
@@ -518,6 +531,7 @@ static int mshv_vtl_ioctl_set_poll_file(struct mshv_vtl_set_poll_file __user *us old_file = poll_file->file; poll_file->file = file; + poll_file->error =0 ; poll_file->cpu = input.cpu;if (file) {
@@ -525,13 +539,18 @@ static int mshv_vtl_ioctl_set_poll_file(struct mshv_vtl_set_poll_file __user *usinit_poll_funcptr (&poll_file->pt, mshv_vtl_ptable_queue_proc);vfs_poll (file, &poll_file->pt); } + ret = poll_file->error; +if (ret) + poll_file->file =NULL ;mutex_unlock (&mshv_vtl_poll_file_lock);if (old_file)fput (old_file); +if (ret) +fput (file); -return 0 ; +return ret; }/* Static table mapping register names to their corresponding actions */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1012/1257 pppoe: delete session hash entries by pointer match
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Qingfang Deng <[email protected]>
[ Upstream commit b5b8c81836e2bec7b444dfa2b14fd14e912e9d63 ]
pppoe_connect() copies the requested PPPoE address to a socket before attempting to insert the socket into the session hash table. If the tuple already exists, __set_item() returns -EALREADY, but the copied address and ifindex remain set on the failed socket.
Closing that socket then deletes the existing socket's hash entry through pppoe_release(), preventing it from receiving further session traffic. An unprivileged process in the same network namespace can trigger this through a duplicate connection attempt.
To avoid the accidental delete, pass the pppox_sock to __delete_item(), and unlink only an entry whose pointer matches the requested socket.
--- drivers/net/ppp/pppoe.c | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-)
drivers/net/ppp/pppoe.c +8 -14
@@ -194,18 +194,16 @@ static int __set_item(struct pppoe_net *pn, struct pppox_sock *po)return 0 ; } -static void __delete_item (struct pppoe_net *pn,__be16 sid, -char *addr,int ifindex) +static void __delete_item (struct pppoe_net *pn,const struct pppox_sock *po) { -int hash =hash_item (sid, addr); +int hash =hash_item (po->pppoe_pa.sid, po->pppoe_pa.remote);struct pppox_sock *ret,__rcu **src; ret =rcu_dereference_protected (pn->hash_table[hash],lockdep_is_held (&pn->hash_lock)); src = &pn->hash_table[hash];while (ret) { -if (cmp_addr (&ret->pppoe_pa, sid, addr) && - ret->pppoe_ifindex == ifindex) { +if (ret == po) {struct pppox_sock *next; next = rcu_dereference_protected(ret->next,
@@ -236,11 +234,10 @@ static inline struct pppox_sock *get_item(struct pppoe_net *pn, __be16 sid,return po; } -static inline void delete_item (struct pppoe_net *pn,__be16 sid, -char *addr,int ifindex) +static void delete_item (struct pppoe_net *pn,const struct pppox_sock *po) {spin_lock (&pn->hash_lock); -__delete_item (pn, sid, addr, ifindex); +__delete_item (pn, po);spin_unlock (&pn->hash_lock); }
@@ -570,8 +567,7 @@ static int pppoe_release(struct socket *sock)* protect "po" from concurrent updates * on pppoe_flush_dev */ -delete_item (pn, po->pppoe_pa.sid, po->pppoe_pa.remote, - po->pppoe_ifindex); +delete_item (pn, po);sock_orphan (sk); sock->sk =NULL ;
@@ -621,8 +617,7 @@ static int pppoe_connect(struct socket *sock, struct sockaddr_unsized *uservaddrif (stage_session (po->pppoe_pa.sid)) {pppox_unbind_sock (sk); pn =pppoe_pernet (sock_net (sk)); -delete_item (pn, po->pppoe_pa.sid, - po->pppoe_pa.remote, po->pppoe_ifindex); +delete_item (pn, po);if (po->pppoe_dev) {dev_put (po->pppoe_dev); po->pppoe_dev =NULL ;
@@ -672,8 +667,7 @@ static int pppoe_connect(struct socket *sock, struct sockaddr_unsized *uservaddr error =ppp_register_net_channel (dev_net (dev), &po->chan);if (error) { -delete_item (pn, po->pppoe_pa.sid, - po->pppoe_pa.remote, po->pppoe_ifindex); +delete_item (pn, po); goto err_put; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1013/1257 net: wwan: iosm: validate msg_head before indexing msg_ring
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Liu Chao <[email protected]>
[ Upstream commit 46cbf85155e5451b6682ea0c17bc62ec564aec36 ]
ipc_protocol_free_msg_get() reads msg_head from shared memory and uses it directly as an index into msg_ring[]. If the head is out of range, the subsequent memset() writes beyond the message ring.
Validate head against IPC_MEM_MSG_ENTRIES before using it as an index. The ring is a circular buffer, so a value outside the valid range indicates a corrupted head pointer; report the error and fail the allocation instead of writing out of bounds.
--- drivers/net/wwan/iosm/iosm_ipc_protocol_ops.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/net/wwan/iosm/iosm_ipc_protocol_ops.c +5 -0
@@ -14,6 +14,11 @@ ipc_protocol_free_msg_get(struct iosm_protocol *ipc_protocol, int *index)u32 new_head = (head +1 ) %IPC_MEM_MSG_ENTRIES ;union ipc_mem_msg_entry *msg; +if (head >=IPC_MEM_MSG_ENTRIES ) { +dev_err (ipc_protocol->dev,"invalid message head %u" , head); +return NULL ; + } +if (new_head ==le32_to_cpu (ipc_protocol->p_ap_shm->msg_tail)) {dev_err (ipc_protocol->dev,"message ring is full" );return NULL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1014/1257 ata: libata-sff: fix race between IRQ deferral and ata_sff_flush_pio_task()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Niklas Cassel <[email protected]>
[ Upstream commit 69be770908ae57354a41d7e1cc99ab46278d2e86 ]
Commit 4a2e5409472e ("ata: libata-sff: don't busy-wait for PIO data-in command completion") allowed the interrupt handler to queue ap->sff_pio_task from ata_sff_hsm_move() when a PIO data-in command is still busy after its final data block.
ata_sff_flush_pio_task(), however, was written under the assumption that cancel_delayed_work_sync() is enough to prevent sff_pio_task from being queued again before the HSM state is reset to HSM_ST_IDLE and sff_pio_task_link is cleared.
The flush runs early during error handling, at a point where the timed out command is still active, the port is not frozen yet, and interrupts are still being serviced. If the final data-block interrupt of a PIO data-in command is serviced in the window between cancel_delayed_work_sync() and the reset of hsm_task_state, the interrupt handler queues sff_pio_task after the cancel has completed. When that work item then executes on ata_sff_wq after the flush cleared ap->sff_pio_task_link, ata_sff_pio_task() hits BUG_ON(ap->sff_pio_task_link == NULL) while holding the host lock with interrupts disabled; alternatively it proceeds on a stale link while error handling owns the port.
Fix this by resetting hsm_task_state to HSM_ST_IDLE before cancelling the work item. Once the state is IDLE, __ata_sff_port_intr() can no longer enter ata_sff_hsm_move(), so the interrupt handler can no longer queue the pio task, and cancel_delayed_work_sync() drains whatever was queued before the reset.
Also make ata_sff_pio_task() bail out quietly when the HSM state was marked idle by the flush, both at entry and after re-acquiring the port lock following ata_msleep(), since a work item can already be running when the flush resets the state.
--- drivers/ata/libata-sff.c | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-)
drivers/ata/libata-sff.c +29 -3
@@ -1196,8 +1196,6 @@ void ata_sff_flush_pio_task(struct ata_port *ap) {trace_ata_sff_flush_pio_task (ap); -cancel_delayed_work_sync (&ap->sff_pio_task); -/* * We wanna reset the HSM state to IDLE. If we do so without * grabbing the port lock, critical sections protected by it which
@@ -1205,11 +1203,26 @@ void ata_sff_flush_pio_task(struct ata_port *ap)* example, we may set IDLE in between the time * __ata_sff_port_intr() checks for HSM_ST_IDLE and before it calls * ata_sff_hsm_move() causing ata_sff_hsm_move() to BUG(). +* +* Reset the state before cancelling the work item: once the state +* is IDLE, __ata_sff_port_intr() can no longer enter +* ata_sff_hsm_move(), which prevents the interrupt handler from +* queueing sff_pio_task when deferring the completion of a PIO +* data-in command. The SCSI error handler cannot dispatch new +* commands while error handling is in progress, so issue-time +* queuing is not possible either. */ spin_lock_irq (ap->lock); ap->hsm_task_state =HSM_ST_IDLE ;spin_unlock_irq (ap->lock); +/* +* Now that the interrupt handler can no longer queue the pio task, +* cancel it. This also drains a work item that the interrupt +* handler managed to queue before the HSM state was reset. +*/ +cancel_delayed_work_sync (&ap->sff_pio_task); + ap->sff_pio_task_link =NULL ; }
@@ -1233,7 +1246,13 @@ static void ata_sff_pio_task(struct work_struct *work) } fsm_start: -WARN_ON_ONCE (ap->hsm_task_state ==HSM_ST_IDLE ); +/* +* ata_sff_flush_pio_task() may have marked the HSM idle after this +* work item was queued or while it was running. There is nothing +* left to do. +*/ +if (ap->hsm_task_state ==HSM_ST_IDLE ) + goto out_unlock; wait_mask =ATA_BUSY ;if (ap->hsm_task_state ==HSM_ST_LAST )
@@ -1252,6 +1271,13 @@ static void ata_sff_pio_task(struct work_struct *work)ata_msleep (ap,2 );spin_lock_irq (ap->lock); +/* +* ata_sff_flush_pio_task() may have marked the HSM idle +* while the port lock was dropped for ata_msleep(). +*/ +if (ap->hsm_task_state ==HSM_ST_IDLE ) + goto out_unlock; + status =ata_sff_busy_wait (ap, wait_mask,10 );if (status & wait_mask) {ata_sff_queue_pio_task (link,ATA_SHORT_PAUSE );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1015/1257 tipc: fix broadcast sender hang on last acker departure
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Henry Martin <[email protected]>
[ Upstream commit f4377bf85887f57b59abb5479f7660a81ffe4449 ]
TIPC group broadcast senders are blocked while a replicast still has outstanding member acks: tipc_group_bc_cong() returns true as long as grp->bc_ackers is non-zero, and clears *grp->open, which is what tipc_poll() uses to report EPOLLOUT (via tsk->group_is_open).
When the last outstanding acker departs before acking, tipc_group_delete_member() decrements grp->bc_ackers to zero but never restores *grp->open. As a result poll(EPOLLOUT) never fires again. A writer blocked in sendmsg() is only released if some other wakeup happens after the deletion: with TIPC_GROUP_MEMBER_EVTS the leave event delivery calls sk_data_ready() and wakes it, but without member events nothing does and it sleeps indefinitely, since the default send timeout is MAX_SCHEDULE_TIMEOUT.
Commit 99cc2a62e07a ("tipc: reject invalid and unexpected GRP_ACK_MSG to prevent bc_ackers underflow") already calls this out in its changelog as a pre-existing issue.
Restore the open state exactly on the 1->0 transition in the delete path, mirroring the GRP_ACK_MSG completion path, and invoke sk->sk_write_space() from tipc_sk_filter_rcv() when the group just became writable again.
Also make the ack accounting precise. The delete path used to test less(m->bc_acked, grp->bc_snd_nxt - 1), which also matches members that were never counted for the current replicast (JOINING/LEAVING members keep a stale bc_acked), and the GRP_ACK_MSG handler accepted an ack from any member whose bc_acked differed from the expected value. Either could zero bc_ackers on behalf of a member that owes nothing and silently void an ack still owed by a real acker. Track whether a member owes an ack for the current replicast in a new per-member bc_pending flag, set when the member is counted and cleared when its ack arrives, and use it both to accept an ack and to decide on deletion. bc_acked has no remaining user and is removed. Suggested by Tung Quang Nguyen.
This issue was discovered by Tencent CodeBuddy Security.
--- net/tipc/group.c | 19 ++++++++++--------- net/tipc/socket.c | 12 +++++++++++- 2 files changed, 21 insertions(+), 10 deletions(-)
net/tipc/group.c +10 -9
@@ -74,7 +74,7 @@ struct tipc_member {u16 window;u16 bc_rcv_nxt;u16 bc_syncpt; -u16 bc_acked; +bool bc_pending; };struct tipc_group {
@@ -316,7 +316,6 @@ static struct tipc_member *tipc_group_create_member(struct tipc_group *grp, m->node = node; m->port = port; m->instance = instance; - m->bc_acked = grp->bc_snd_nxt -1 ; ret =tipc_group_add_to_tree (grp, m);if (ret <0 ) {kfree (m);
@@ -340,9 +339,12 @@ static void tipc_group_delete_member(struct tipc_group *grp,rb_erase (&m->tree_node, &grp->members); grp->member_cnt--; -/* Check if we were waiting for replicast ack from this member */ -if (grp->bc_ackers &&less (m->bc_acked, grp->bc_snd_nxt -1 )) - grp->bc_ackers--; +/* If this member owed an ack for the current replicast and it +* was the last one, restore the open state so blocked broadcast +* senders can proceed. +*/ +if (grp->bc_ackers && m->bc_pending && !--grp->bc_ackers) + *grp->open = true;list_del_init (&m->list);list_del_init (&m->small_win);
@@ -394,7 +396,6 @@ void tipc_group_update_member(struct tipc_member *m, int len)void tipc_group_update_bc_members (struct tipc_group *grp,int len,bool ack) { -u16 prev = grp->bc_snd_nxt -1 ;struct tipc_member *m;struct rb_node *n;u16 ackers =0 ;
@@ -403,8 +404,8 @@ void tipc_group_update_bc_members(struct tipc_group *grp, int len, bool ack) m = container_of(n, struct tipc_member, tree_node);if (tipc_group_is_receiver (m)) {tipc_group_update_member (m, len); - m->bc_acked = prev; ackers++; + m->bc_pending = ack; } }
@@ -800,9 +801,9 @@ void tipc_group_proto_rcv(struct tipc_group *grp, bool *usr_wakeup,if (!m || !grp->bc_ackers)return ; acked =msg_grp_bc_acked (hdr); -if (acked != grp->bc_snd_nxt || m->bc_acked == acked) +if (acked != grp->bc_snd_nxt || !m->bc_pending)return ; - m->bc_acked = acked; + m->bc_pending = false;if (--grp->bc_ackers)return ;list_del_init (&m->small_win);
net/tipc/socket.c +11 -1
@@ -2356,8 +2356,18 @@ static void tipc_sk_filter_rcv(struct sock *sk, struct sk_buff *skb,if (unlikely (!msg_isdata (hdr)))tipc_sk_proto_rcv (sk, &inputq, xmitq); -if (unlikely (grp)) +if (unlikely (grp)) { +bool was_open = tsk->group_is_open; +tipc_group_filter_msg (grp, &inputq, xmitq); +/* A departing member may have held the last outstanding +* replicast ack, which can restore the open state inside +* tipc_group_filter_msg(); wake up senders blocked in +* poll()/write() if the group just became writable. +*/ +if (!was_open && tsk->group_is_open) + sk->sk_write_space (sk); + }if (unlikely (!grp) && mtyp ==TIPC_MCAST_MSG )tipc_mcast_filter_msg (net, &tsk->mc_method.deferredq, &inputq);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1016/1257 cgroup/cpuset: Fix task checking when enabling a partition
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guopeng Zhang <[email protected]>
[ Upstream commit f5b5cf2be574df6f25cbf1b000960340bff9a0bb ]
Creating a child partition can fail when tasks are present in its descendants, even though the parent has no tasks of its own.
On a cgroup v2 system with CPUs 0-7 online:
cd /sys/fs/cgroup
echo +cpuset > cgroup.subtree_control
mkdir A
echo 1-2 > A/cpuset.cpus
echo root > A/cpuset.cpus.partition
echo +cpuset > A/cgroup.subtree_control
mkdir A/B
echo 1-2 > A/B/cpuset.cpus
echo +cpuset > A/B/cgroup.subtree_control
mkdir A/B/C
echo 1-2 > A/B/C/cpuset.cpus
echo $$ > A/B/C/cgroup.procs
echo root > A/B/cpuset.cpus.partition
cat A/B/cpuset.cpus.partition
root invalid (Parent unable to distribute cpu downstream) cat A/cpuset.cpus.effective
1-2
B should be a valid root, leaving A with an empty effective CPU list. The task in C belongs to B's partition and does not need CPUs in A.
partition_is_populated() is called with B as excluded_child, but continue only skips B in the pre-order walk. The walk still visits C and finds the task there, so A is considered populated.
Fix this by skipping the whole excluded subtree with css_rightmost_descendant(), as is already done for valid child partitions. Also add a test case to test_cpuset_prs.sh with a task in a grandchild cpuset.
--- kernel/cgroup/cpuset.c | 4 ++-- tools/testing/selftests/cgroup/test_cpuset_prs.sh | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +2 -2
@@ -478,10 +478,10 @@ static inline bool partition_is_populated(struct cpuset *cs,rcu_read_lock ();cpuset_for_each_descendant_pre (cp, pos_css, cs) { -if (cp == cs || cp == excluded_child) +if (cp == cs)continue ; -if (is_partition_valid (cp)) { +if (cp == excluded_child ||is_partition_valid (cp)) { pos_css =css_rightmost_descendant (pos_css);continue ; }
tools/testing/selftests/cgroup/test_cpuset_prs.sh +3 -0
@@ -385,6 +385,9 @@ TEST_MATRIX=( # Enabling partition with child cpusets is allowed " C0-1 C1 . C2-3 P1 . . . 0 A1:0-1|A2:1 A1:P1" + # Tasks below a new partition belong to it, not to its parent. + " C1-2:P1 C1-2 C1-2:T . . P1 . . 0 A1:|A2:1-2|A3:1-2 A1:P1|A2:P1" + # A partition root with non-partition root parent is invalid| but it # can be made valid if its parent becomes a partition root too. " C0-1 C1 . C2-3 . P2 . . 0 A1:0-1|A2:1 A1:P0|A2:P-2"
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1017/1257 fs: rotate inodes whose page cache could not be dropped
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nikolaos Karaolidis <[email protected]>
[ Upstream commit 8ee09f597763acfd31c62a578ba88b792fc41b24 ]
When inode_lru_isolate() drops the page cache of an unused inode, it has to unlock the list, so it returns LRU_RETRY and the walk restarts at the head of the list, where the inode still is. If invalidate_mapping_pages() could not empty the mapping, the restarted walk strips the same inode again, and so on until nr_to_walk runs out. Every walk of that list then ends on this inode, and nothing behind it is reclaimed for as long as its cache stays.
Before commit 2a0629834cd8 ("vfs: Don't evict inode under the inode lru traversing context") the walker pinned the inode with a reference, and dropping it in iput_final() set I_REFERENCED, so the restarted walk rotated the inode to the tail. Set I_REFERENCED again when the mapping is still populated after the invalidation, in the same i_lock section that clears I_LRU_ISOLATING. inode_unpin_lru_isolating() now expects i_lock to be held, like inode_pin_lru_isolating().
On CONFIG_HIGHMEM kernels this can happen to any unused inode: a folio is left behind if it is locked, under writeback, spliced into a pipe, or still in another CPU's LRU-add batch after being read. Without HIGHMEM it happens to DAX inodes whose only entry is at index 0, which mapping_shrinkable() lets onto the LRU and invalidate_mapping_pages() never removes.
--- fs/inode.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
fs/inode.c +7 -2
@@ -593,12 +593,11 @@ static void inode_pin_lru_isolating(struct inode *inode)static void inode_unpin_lru_isolating (struct inode *inode) { -spin_lock (&inode->i_lock); +lockdep_assert_held (&inode->i_lock);WARN_ON (!(inode_state_read (inode) &I_LRU_ISOLATING ));inode_state_clear (inode,I_LRU_ISOLATING );/* Called with inode->i_lock which ensures memory ordering. */ inode_wake_up_bit (inode, __I_LRU_ISOLATING); -spin_unlock (&inode->i_lock); }static void inode_wait_for_lru_isolating (struct inode *inode)
@@ -981,7 +980,13 @@ static enum lru_status inode_lru_isolate(struct list_head *item,else __count_vm_events (PGINODESTEAL , reap);mm_account_reclaimed_pages (reap); + +spin_lock (&inode->i_lock); +/* The walk restarts here: don't retry leftovers right away */ +if (!mapping_empty (&inode->i_data)) +inode_state_set (inode,I_REFERENCED );inode_unpin_lru_isolating (inode); +spin_unlock (&inode->i_lock);return LRU_RETRY ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1018/1257 writeback: keep cleanup_offline_cgwb()s scan out of syncs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Liz Fong-Jones <[email protected]>
[ Upstream commit 90c96612460e6accddbda5a195e6ddaa391ecde0 ]
On a filesystem mounted with lazytime, sync() and syncfs() can return without persisting timestamp updates of inodes attached to a dying cgroup wb, so a crash after the sync loses them. File data and sizes are not affected.
Since commit f6988c90671e ("writeback: bound cleanup_offline_cgwb() rescans by rotating scanned inodes"), isw_prepare_wbs_switch() moves the inodes it walks to the newest end of the list. When a pass fills its isw before reaching an inode that got its lazytime update after a sync's cutoff, the walked inodes land past it on b_dirty_time, and the sync's queue_io(), which stops at the first inode dirtied after the cutoff, misses them. The late inode has to be one without a pending lazytime update; one already on b_dirty_time keeps its position.
The window is narrow. cleanup_offline_cgwbs_workfn() skips wbs with anything on b_dirty, b_io or b_more_io, so the scan has to land between wb_writeback() fixing dirtied_before and taking list_lock for its first queue_io(), unless a multi-pass drain started before the wb got dirty IO.
Take wb_switch_rwsem for read across the scan, asprocess_inode_switch_wbs() does for the switches.
--- fs/fs-writeback.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/fs-writeback.c +8 -0
@@ -790,6 +790,13 @@ bool cleanup_offline_cgwb(struct bdi_writeback *wb) new_wb = &wb->bdi->wb;/* wb_get() is noop for bdi's wb */ nr =0 ; +/* +* The scan moves walked inodes to the newest end of b_dirty_time, +* past ones it didn't reach. If one of those was dirtied after a +* sync's cutoff, the sync's queue_io() stops there and misses the +* moved ones. Exclude syncs as process_inode_switch_wbs() does. +*/ +down_read (&wb->bdi->wb_switch_rwsem);spin_lock (&wb->list_lock);/* * In addition to the inodes that have completed writeback, also switch
@@ -804,6 +811,7 @@ bool cleanup_offline_cgwb(struct bdi_writeback *wb) restart =isw_prepare_wbs_switch (new_wb, isw, &wb->b_dirty_time, &nr);spin_unlock (&wb->list_lock); +up_read (&wb->bdi->wb_switch_rwsem);/* no attached inodes? bail out */ if (nr ==0 ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1019/1257 exportfs: Release the get_name() directory file synchronously
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
[ Upstream commit 49184daab01674ca400cbef58ee101dba6dbbb9d ]
get_name() opens the parent directory with dentry_open() and releases it with fput(). From a kernel thread, fput() defers the final __fput() to the delayed_fput work item. NFSD threads are kernel threads, and NFSD reaches get_name() through exportfs_decode_fh() whenever a file handle's dentry is not connected to the root.
On a filesystem with more directories than the dcache retains, nearly every READDIRPLUS needs a reconnect. The deferred releases arrive faster than the work item retires them, and each pending file pins the directory's readdir state. On ext4 that state is the htree fname cache for the last leaf block read. A 64-thread NFSv3 server under a parallel tree walk showed unreclaimable slab growing by about 90 MB per second, and the same workload on a 5.15 kernel ended in a global OOM.
Commit 5ff318f645eb ("nfsd: use __fput_sync() to avoid delayed closing of files.") stopped NFSD's own closes from feeding the delayed_fput queue but did not cover the exportfs reconnect path.
Release the file with __fput_sync(). get_name() opened the file itself, read-only, on a directory, so __fput() involves nothing that could wait on the caller.
Note for LTS backports: Kernels before v6.6 need the __fput_sync() call guarded by current->flags & PF_KTHREAD, with a plain fput() otherwise.
--- fs/exportfs/expfs.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
fs/exportfs/expfs.c +5 -1
@@ -336,7 +336,11 @@ static int get_name(const struct path *path, char *name, struct dentry *child) } out_close: -fput (file); +/* +* @file is the read-only directory opened above, so __fput() +* cannot block on anything the caller holds. +*/ +__fput_sync (file); out:return error; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1020/1257 statmount: dont copy the reserved empty string past the buffer
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 11eef75006819f4e71d04ca2b9a1fb1580854a55 ]
statmount_string() reserves an empty string at the start of the seq buffer before it calls the handler for the requested string. That's what the offsets of unset strings point to since commit e52e97f09fb6 ("statmount: let unset strings be empty").
If the handler emits nothing the early return from commit 75ead69a7173 ("fs: don't let statmount return empty strings") skips the size check against the caller's buffer. Back then an empty emission meant an empty seq buffer and there was nothing to copy. Now the reserved NUL byte is there and copy_statmount_to_user() copies it to buf + sizeof(struct statmount) no matter how small bufsize is.
So request a string that may turn out empty with a buffer that's smaller than struct statmount and the kernel writes one zero byte past the caller's buffer and reports a size that's larger than the buffer. STATMOUNT_MNT_UIDMAP or STATMOUNT_MNT_GIDMAP on a mount that isn't idmapped will do, so will STATMOUNT_FS_SUBTYPE on anything but fuse or STATMOUNT_OPT_ARRAY on a filesystem without ->show_options(). None of this needs privileges. The byte only lands in the caller's own address space but that's still not ok.
prepare_kstatmount() already refuses a buffer of exactly sizeof(struct statmount) for string requests. A smaller buffer can't hold a string either and it can't even hold the reserved empty string. So refuse any buffer that isn't larger than the fixed part. That's also what the uapi header says: string requests need space after the fixed part of the structure.
Reproducer, unprivileged, on any mount that isn't idmapped:
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
#define STATMOUNT_FS_SUBTYPE 0x00000100U
#define STATMOUNT_MNT_UIDMAP 0x00002000U
#define STATX_MNT_ID_UNIQUE 0x00004000U
#define SM_SIZE 512 /* sizeof(struct statmount) */
struct mnt_id_req {
uint32_t size, mnt_ns_fd;
uint64_t mnt_id, param, mnt_ns_id;
};
static uint64_t root_mnt_id(void)
{
unsigned char stx[256]; /* struct statx, stx_mnt_id at offset 144 */
uint64_t id;
if (syscall(__NR_statx, AT_FDCWD, "/", 0, STATX_MNT_ID_UNIQUE, stx))
_exit(1);
memcpy(&id, stx + 144, sizeof(id));
return id;
}
static void probe(uint64_t mnt_id, uint64_t mask, int guard)
{
struct mnt_id_req req = {
.size = sizeof(req), .mnt_id = mnt_id, .param = mask,
};
long page = sysconf(_SC_PAGESIZE);
unsigned char *map, *buf;
uint32_t size;
long ret;
map = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
memset(map, 0xaa, 2 * page);
/* 100 byte buffer ending right at the page boundary */
buf = map + page - 100;
if (guard)
mprotect(map + page, page, PROT_NONE);
errno = 0;
ret = syscall(__NR_statmount, &req, buf, 100, 0);
printf("mask 0x%04llx%s: ret %ld errno %d", (unsigned long long)mask,
guard ? " guard page" : "", ret, errno);
if (!guard) {
memcpy(&size, buf, sizeof(size));
printf(", size 0x%x, byte[%d] 0x%02x", size, SM_SIZE,
buf[SM_SIZE]);
}
printf("\n");
munmap(map, 2 * page);
}
int main(void)
{
uint64_t id = root_mnt_id();
probe(id, STATMOUNT_MNT_UIDMAP, 0);
probe(id, STATMOUNT_FS_SUBTYPE, 0);
probe(id, STATMOUNT_MNT_UIDMAP, 1);
return 0;
}Before, on 7.3.0-rc7-00252-g4e3259b08c54 (vfs.fixes) in a VM, the same on a distro 7.1.13:
mask 0x2000: ret 0 errno 0, size 0x65, byte[512] 0x00
mask 0x0100: ret 0 errno 0, size 0x65, byte[512] 0x00
mask 0x2000 guard page: ret -1 errno 14After:
mask 0x2000: ret -1 errno 75, size 0xaaaaaaaa, byte[512] 0xaa
mask 0x0100: ret -1 errno 75, size 0xaaaaaaaa, byte[512] 0xaa
mask 0x2000 guard page: ret -1 errno 75--- fs/namespace.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
fs/namespace.c +2 -1
@@ -6058,7 +6058,8 @@ static int prepare_kstatmount(struct kstatmount *ks, struct mnt_id_req *kreq, ks->bufsize = bufsize;if (ks->mask &STATMOUNT_STRING_REQ ) { -if (bufsize ==sizeof (ks->sm)) +/* Even the reserved empty string needs room past the fixed part. */ +if (bufsize <=sizeof (ks->sm))return -EOVERFLOW ; ks->seq.buf =kvmalloc (seq_size,GFP_KERNEL_ACCOUNT );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1021/1257 listmount: dont wrap around with a U64_MAX cursor
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 95a5412022e437691f4eb1924ff249d9044f5ed1 ]
do_listmount() takes the last mount id the caller saw and looks up the first mount after it by searching for last_mnt_id + 1. With U64_MAX that wraps around to zero and the search finds the first mount in the namespace. So a cursor at the largest possible id restarts the listing from the beginning instead of ending it. A cursor of U64_MAX - 1 correctly returns nothing.
No mount will ever have that id. Mount ids come from a counter that starts at MNT_UNIQUE_ID_OFFSET + 1 and a caller that only feeds back ids it got from us can't hit this. It's still wrong. Nothing can come after the largest possible id so return no entries for it, just like for any other cursor past the last mount.
The reverse direction isn't affected. A cursor of zero is special-cased and anything else is larger than MNT_UNIQUE_ID_OFFSET so last_mnt_id - 1 can't underflow.
Reproducer, unprivileged:
#define _GNU_SOURCE
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
#define LSMT_ROOT 0xffffffffffffffffULL
struct mnt_id_req {
uint32_t size, mnt_ns_fd;
uint64_t mnt_id, param, mnt_ns_id;
};
static void list(uint64_t cursor)
{
struct mnt_id_req req = {
.size = sizeof(req), .mnt_id = LSMT_ROOT, .param = cursor,
};
uint64_t ids[8];
long ret;
errno = 0;
ret = syscall(__NR_listmount, &req, ids, 8, 0);
printf("cursor %llu: ret %ld errno %d", (unsigned long long)cursor,
ret, errno);
for (long i = 0; i < ret && i < 1; i++)
printf("%s%llu", i ? "," : " ids ", (unsigned long long)ids[i]);
printf("%s\n", ret > 1 ? ",..." : "");
}
int main(void)
{
list(0);
list(UINT64_MAX - 1);
list(UINT64_MAX);
return 0;
}Before, on 7.3.0-rc7-00252-g4e3259b08c54 (vfs.fixes) in a VM:
cursor 0: ret 5 errno 0 ids 2147483651,...
cursor 18446744073709551614: ret 0 errno 0
cursor 18446744073709551615: ret 5 errno 0 ids 2147483651,...After:
cursor 0: ret 5 errno 0 ids 2147483651,...
cursor 18446744073709551614: ret 0 errno 0
cursor 18446744073709551615: ret 0 errno 0--- fs/namespace.c | 2 ++ 1 file changed, 2 insertions(+)
fs/namespace.c +2 -0
@@ -6253,6 +6253,8 @@ static ssize_t do_listmount(struct klistmount *kls, bool reverse) }else {if (reverse) first =mnt_find_id_at_reverse (ns, last_mnt_id -1 ); +else if (last_mnt_id ==U64_MAX ) + first =NULL ;/* nothing comes after the largest id */ else first =mnt_find_id_at (ns, last_mnt_id +1 ); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1022/1257 fs: dont lose inodes that another LRU walker is isolating
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nikolaos Karaolidis <[email protected]>
[ Upstream commit 8dc4116041e2b377e5e1b62ba98b37636f9f3968 ]
When inode_lru_isolate() finds an unused inode that still has page cache, it sets I_LRU_ISOLATING, drops i_lock and the list_lru lock, invalidates the page cache, clears the flag again and returns LRU_RETRY so that the restarted walk can free the inode.
Another walker of the same list can reach the inode in that window. It sees a non-zero i_state and takes the inode off the LRU, as it would an inode that is in use. Page cache deletion requeues the inode once the mapping is shrinkable, so this is harmless if it happens before the last deletion. If it happens after, nothing puts the inode
back: it stays in memory, unused, clean and without page cache, out of reach of the shrinker and of drop_caches, until it is looked up again or the filesystem is unmounted.
Before commit 2a0629834cd8 ("vfs: Don't evict inode under the inode lru traversing context") the pin was an i_count reference, and the final iput() put the inode back on the LRU.
Skip inodes that are being isolated and leave them to the walker that pinned them, which restarts its walk once it has unpinned them.
The window is reached by any unused inode with page cache on CONFIG_HIGHMEM kernels, and otherwise by inodes whose page cache is a single shadow entry at index 0. On an i386 HIGHMEM guest, eight concurrent "echo 2 > /proc/sys/vm/drop_caches" over 2000 freshly read one-page ext4 files leave roughly 400 of the inodes off the LRU per round; on x86_64, with the files' pages first evicted through memory.reclaim, 3 to 4 per round. With this patch, none in either case.
--- fs/inode.c | 6 ++++++ 1 file changed, 6 insertions(+)
fs/inode.c +6 -0
@@ -941,6 +941,12 @@ static enum lru_status inode_lru_isolate(struct list_head *item,if (!spin_trylock (&inode->i_lock))return LRU_SKIP ; +/* Another walker is dropping its page cache, leave it to that one */ +if (inode_state_read (inode) &I_LRU_ISOLATING ) { +spin_unlock (&inode->i_lock); +return LRU_SKIP ; + } +/* * Inodes can get referenced, redirtied, or repopulated while * they're already on the LRU, and this can make them
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1023/1257 listns: dont wrap around with a U64_MAX cursor
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 2a1887000e2d4adc8cb3933b53431dea6d5e310b ]
do_listns() and do_listns_userns() take the last namespace id the caller saw and look up the first namespace after it by searching the rbtree for last_ns_id + 1. With U64_MAX that wraps around to zero and the search returns the namespace with the smallest id. So a cursor at the largest possible id restarts the listing from the beginning instead of failing with ENOENT like a cursor of U64_MAX - 1 does. That's the case for the unified tree, the type-specific trees and the owner tree alike.
No namespace will ever have that id. They come from a counter and a caller that only feeds back ids it got from us can't hit this. It's still wrong.
Instead of adding one to the cursor and searching for the smallest id that's greater or equal make the lookup helpers search for the smallest id that's strictly greater than the cursor. That's what both callers want anyway and there's nothing left to overflow.
Reproducer, unprivileged:
#define _GNU_SOURCE
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifndef __NR_listns
#define __NR_listns 470
#endif
#define CLONE_NEWUSER 0x10000000U
#define LISTNS_CURRENT_USER 0xffffffffffffffffULL
struct ns_id_req {
uint32_t size, spare;
uint64_t ns_id;
uint32_t ns_type, spare2;
uint64_t user_ns_id;
};
static void list(const char *tree, uint32_t type, uint64_t owner,
uint64_t cursor)
{
struct ns_id_req req = {
.size = sizeof(req), .ns_id = cursor, .ns_type = type,
.user_ns_id = owner,
};
uint64_t ids[8];
long ret;
errno = 0;
ret = syscall(__NR_listns, &req, ids, 8, 0);
printf("%s cursor %llu: ret %ld errno %d", tree,
(unsigned long long)cursor, ret, errno);
for (long i = 0; i < ret && i < 3; i++)
printf("%s%llu", i ? "," : " ids ", (unsigned long long)ids[i]);
printf("%s\n", ret > 3 ? ",..." : "");
}
int main(void)
{
static const uint64_t cursors[] = { 0, UINT64_MAX - 1, UINT64_MAX };
for (int i = 0; i < 3; i++)
list("unified", 0, 0, cursors[i]);
for (int i = 0; i < 3; i++)
list("userns", CLONE_NEWUSER, 0, cursors[i]);
for (int i = 0; i < 3; i++)
list("owner", 0, LISTNS_CURRENT_USER, cursors[i]);
return 0;
}Before, on 7.3.0-rc7-00252-g4e3259b08c54 (vfs.fixes) in a VM:
unified cursor 0: ret 8 errno 0 ids 1,2,3,...
unified cursor 18446744073709551614: ret -1 errno 2
unified cursor 18446744073709551615: ret 8 errno 0 ids 1,2,3,...
userns cursor 0: ret 1 errno 0 ids 3
userns cursor 18446744073709551614: ret -1 errno 2
userns cursor 18446744073709551615: ret 1 errno 0 ids 3
owner cursor 0: ret 8 errno 0 ids 1,2,4,...
owner cursor 18446744073709551614: ret -1 errno 2
owner cursor 18446744073709551615: ret 8 errno 0 ids 1,2,4,...After:
unified cursor 0: ret 8 errno 0 ids 1,2,3,...
unified cursor 18446744073709551614: ret -1 errno 2
unified cursor 18446744073709551615: ret -1 errno 2
userns cursor 0: ret 1 errno 0 ids 3
userns cursor 18446744073709551614: ret -1 errno 2
userns cursor 18446744073709551615: ret -1 errno 2
owner cursor 0: ret 8 errno 0 ids 1,2,4,...
owner cursor 18446744073709551614: ret -1 errno 2
owner cursor 18446744073709551615: ret -1 errno 2--- kernel/nstree.c | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-)
kernel/nstree.c +11 -18
@@ -459,10 +459,10 @@ static inline int prepare_klistns(struct klistns *kls, struct ns_id_req *kreq, }/* -* Lookup a namespace owned by owner with id >= ns_id. -* Returns the namespace with the smallest id that is >= ns_id. +* Lookup a namespace owned by owner with id > ns_id. +* Returns the namespace with the smallest id that is > ns_id. */ -static struct ns_common *lookup_ns_owner_at (u64 ns_id,struct ns_common *owner) +static struct ns_common *lookup_ns_owner_after (u64 ns_id,struct ns_common *owner) {struct ns_common *ret =NULL ;struct rb_node *node;
@@ -476,10 +476,8 @@ static struct ns_common *lookup_ns_owner_at(u64 ns_id, struct ns_common *owner)struct ns_common *ns; ns =node_to_ns_owner (node); -if (ns_id <= ns->ns_id) { +if (ns_id < ns->ns_id) { ret = ns; -if (ns_id == ns->ns_id) -break ; node = node->rb_left; }else { node = node->rb_right;
@@ -565,7 +563,7 @@ static ssize_t do_listns_userns(struct klistns *kls)* then use it's list entry to iterate from there. */ if (kls->last_ns_id) { - kls->first_ns =lookup_ns_owner_at (kls->last_ns_id +1 , ns); + kls->first_ns =lookup_ns_owner_after (kls->last_ns_id, ns);if (!kls->first_ns)return -ENOENT ; first_ns = kls->first_ns;
@@ -613,10 +611,10 @@ static ssize_t do_listns_userns(struct klistns *kls) }/* -* Lookup a namespace with id >= ns_id in either the unified tree or a type-specific tree. -* Returns the namespace with the smallest id that is >= ns_id. +* Lookup a namespace with id > ns_id in either the unified tree or a type-specific tree. +* Returns the namespace with the smallest id that is > ns_id. */ -static struct ns_common *lookup_ns_id_at (u64 ns_id,int ns_type) +static struct ns_common *lookup_ns_id_after (u64 ns_id,int ns_type) {struct ns_common *ret =NULL ;struct ns_tree_root *ns_tree =NULL ;
@@ -643,13 +641,8 @@ static struct ns_common *lookup_ns_id_at(u64 ns_id, int ns_type)else ns =node_to_ns_unified (node); -if (ns_id <= ns->ns_id) { -if (ns_type) - ret =node_to_ns (node); -else - ret =node_to_ns_unified (node); -if (ns_id == ns->ns_id) -break ; +if (ns_id < ns->ns_id) { + ret = ns; node = node->rb_left; }else { node = node->rb_right;
@@ -708,7 +701,7 @@ static ssize_t do_listns(struct klistns *kls) }if (kls->last_ns_id) { - kls->first_ns =lookup_ns_id_at (kls->last_ns_id +1 , ns_type); + kls->first_ns =lookup_ns_id_after (kls->last_ns_id, ns_type);if (!kls->first_ns)return -ENOENT ; first_ns = kls->first_ns;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1024/1257 ucount: take the rlimit reference before checking the limit
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nickolai Zeldovich <[email protected]>
[ Upstream commit b14fcabd34e02c40f72d3cd1e9bd4fd18df40ff1 ]
inc_rlimit_get_ucounts() takes the reference that pins a ucounts level while its rlimit count is non-zero only in the walk whose increment is the 0 -> 1 transition, and only after that walk passed the limit check. A walk that raises the count from zero and then fails the limit backs out without the reference, while a concurrent walk that raised it past one keeps its increment and never takes one either:
CPU0 (obeys the limit) CPU1 (overrides it)
new = add_return(1) -> 1
new = add_return(1) -> 2
new != 1, no get_ucounts() new > max -> dec_unwind
sub_return(1) -> 1 (no put)
The count is 1 with no reference held. When CPU1 drops its charge, dec_rlimit_put_ucounts() takes the count to 0 and puts a reference nobody took, which frees the live struct ucounts, and the user_namespace it pins, with kfree_rcu(). The mirror interleaving leaks the reference instead.
An unprivileged user reaches this on a kernel with CONFIG_USER_NS=y: in a user namespace with RLIMIT_SIGPENDING 0, one process taking synchronous SIGSEGVs (forced, so override_rlimit is set) races a second process in the same namespace and uid that queues real-time signals, which obey the limit. The two hold different sighand->siglock but charge the same per-namespace SIGPENDING ucounts. Unpatched, with rcuref debugging:
rcuref - imbalanced put()
WARNING: lib/rcuref.c:266 at rcuref_put_slowpath+0xf4/0x120 put_ucounts+0x5a/0x180 do_dec_rlimit_put_ucounts+0x70/0x90 __sigqueue_free+0x33/0xc0 get_signal+0x56f/0xd20 arch_do_signal_or_restart+0x87/0x380 irqentry_exit+0x243/0x650 asm_exc_page_fault+0x26/0x30
Take the reference on the 0 -> 1 transition before the limit is checked, so the walk that raises the count from zero owns that level's reference even when its request is rejected, and unwind a rejected level through do_dec_rlimit_put_ucounts(), which releases the reference when the count returns to 0. The get_ucounts() failure path is unchanged. With the patch the same interleaving, forced some 80000 times in a KASAN build, produces no warning and no KASAN report.
--- kernel/ucount.c | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-)
kernel/ucount.c +12 -9
@@ -308,23 +308,26 @@ long inc_rlimit_get_ucounts(struct ucounts *ucounts, enum rlimit_type type,for (iter = ucounts; iter; iter = iter->ns->ucounts) {long new =atomic_long_add_return (1 , &iter->rlimit[type]); -if (new <0 || new > max) +/* +* Take the extra reference on the 0 -> 1 transition before the +* limit check: a rejected walk must not leave a concurrent one +* holding the surviving increment with no reference. +*/ +if (new ==1 && !get_ucounts (iter)) goto dec_unwind; +if (new <0 || new > max) { +/* undo iter too, releasing the reference taken above */ +do_dec_rlimit_put_ucounts (ucounts, iter->ns->ucounts, type); +return 0 ; + }if (iter == ucounts) ret = new;if (!override_rlimit) max =get_userns_rlimit_max (iter->ns, type); -/* -* Grab an extra ucount reference for the caller when -* the rlimit count was previously 0. -*/ -if (new !=1 ) -continue ; -if (!get_ucounts (iter)) - goto dec_unwind; }return ret; dec_unwind: +/* get_ucounts() failed for iter: undo iter without a put */ dec =atomic_long_sub_return (1 , &iter->rlimit[type]);WARN_ON_ONCE (dec <0 );do_dec_rlimit_put_ucounts (ucounts, iter, type);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1025/1257 cpufreq: intel_pstate: cancel HWP notify work in driver cleanup
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tristan Madani <[email protected]>
[ Upstream commit 0ffc7534a210105ba973167a5b86d5ab39d4031f ]
intel_pstate_driver_cleanup() frees per-CPU data without cancelling the pending HWP notify delayed work. If hwp_notify_work is still scheduled or running when the struct is freed, the work function accesses freed memory via container_of().
Call intel_pstate_disable_hwp_interrupt() before kfree() to disable the interrupt source and cancel the pending work, matching the pattern used in intel_pstate_suspend() and intel_pstate_hwp_offline().
--- drivers/cpufreq/intel_pstate.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/cpufreq/intel_pstate.c +2 -0
@@ -3436,6 +3436,8 @@ static void intel_pstate_driver_cleanup(void)if (intel_pstate_driver == &intel_pstate)intel_pstate_clear_update_util_hook (cpu); +intel_pstate_disable_hwp_interrupt (all_cpu_data[cpu]); +kfree (all_cpu_data[cpu]);WRITE_ONCE (all_cpu_data[cpu],NULL ); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1026/1257 PM: EM: allocate the cpumask for every perf domain
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
[ Upstream commit 6c7a7007c5b7566fba4fbee1d40011fb8f833dc3 ]
em_create_pd() allocates space for the trailing cpus[] flexible array only for CPU devices. A performance domain registered for another device therefore has no storage for its cpumask.
All performance domains are added to em_pd_list. The netlink interface does not distinguish CPU and non-CPU domains when it calls cpumask_weight() or iterates over pd->cpus. A request for a non-CPU domain reads cpumask_size() bytes beyond the allocation and can report bits from the following memory as CPU attributes.
KASAN reports slab-out-of-bounds reads for both dump and by-ID requests against a synthetic non-CPU performance domain.
GET_PERF_DOMAINS does not require GENL_ADMIN_PERM, so an unprivileged request can reach this path when a GPU or another devfreq device has registered an energy model.
Allocate the cpumask for non-CPU domains too. The zeroed mask remains empty, as required for the documented unused field.
--- kernel/power/energy_model.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/power/energy_model.c +3 -1
@@ -439,7 +439,9 @@ static int em_create_pd(struct device *dev, int nr_states,cpumask_copy (em_span_cpus (pd), cpus); }else { - pd =kzalloc_obj (*pd); +/* Readers expect pd->cpus to exist and remain empty. */ + pd =kzalloc_flex (*pd, cpus, +BITS_TO_LONGS (large_cpumask_bits));if (!pd)return -ENOMEM ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1027/1257 i2c: acpi: Fix adapter reference leak in i2c_acpi_new_device_by_fwnode()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ma Ke <[email protected]>
[ Upstream commit a65917d0a22f9b10694853b725f9cd399fc3ef4d ]
i2c_acpi_new_device_by_fwnode() obtains an i2c_adapter through i2c_acpi_find_adapter_by_handle(). That helper uses bus_find_device() internally, so it returns the adapter with a reference held:
adapter = i2c_verify_adapter(dev);
if (!adapter)
put_device(dev);
return adapter;The reference is only put on the failure path inside that helper. The caller owns it otherwise. i2c_acpi_new_device_by_fwnode() never drops it, neither on the -EPROBE_DEFER path nor after i2c_new_client_device(), so every call leaks one reference on the adapter and the adapter can never be released.
i2c_new_client_device() does not consume that reference. It registers the new client with the adapter as its parent, and device_add() takes its own reference on the parent, which device_del() releases when the client goes away. The reference obtained by the lookup is a separate one and has to be dropped here.
i2c_acpi_notify() in the same file already does exactly this. It takes the adapter from the same helper, registers the client through i2c_acpi_register_device(), which calls i2c_new_client_device(), and then puts the reference.
i2c_new_client_device() gives the client its own reference on the adapter, so ours can be dropped unconditionally.
Found by code review.
--- drivers/i2c/i2c-core-acpi.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/i2c/i2c-core-acpi.c +5 -1
@@ -547,6 +547,7 @@ struct i2c_client *i2c_acpi_new_device_by_fwnode(struct fwnode_handle *fwnode, {struct i2c_acpi_lookup lookup;struct i2c_adapter *adapter; +struct i2c_client *client;struct acpi_device *adev;LIST_HEAD (resource_list);int ret;
@@ -574,7 +575,10 @@ struct i2c_client *i2c_acpi_new_device_by_fwnode(struct fwnode_handle *fwnode,if (!adapter)return ERR_PTR (-EPROBE_DEFER ); -return i2c_new_client_device (adapter, info); + client =i2c_new_client_device (adapter, info); +put_device (&adapter->dev); + +return client; }EXPORT_SYMBOL_GPL (i2c_acpi_new_device_by_fwnode);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1028/1257 i2c: designware: queue only one read command for block reads
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Navon John Lukose <[email protected]>
[ Upstream commit 73dae605cad7921800677d982bfaeb81cc930dec ]
i2c_dw_xfer_msg() pre-queues up to rx_fifo_depth read commands based on the initial msg.len. For I2C_M_RECV_LEN transfers the real length is unknown until the first byte arrives and i2c_dw_recv_len() runs. When a large initial length is passed, the surplus pre-queued reads leave rx_outstanding non-zero after i2c_dw_recv_len() adjusts msg.len, so the completion condition is never met and the transfer times out. In a loop, this repeatedly times out the controller and disrupts unrelated driver-bound devices on the same adapter.
Queue only one read command while I2C_M_RECV_LEN is pending. i2c_dw_recv_len() re-enables TX_EMPTY, and the rest are queued once the device-reported length is known.
--- drivers/i2c/busses/i2c-designware-master.c | 8 ++++++++ 1 file changed, 8 insertions(+)
drivers/i2c/busses/i2c-designware-master.c +8 -0
@@ -441,6 +441,14 @@ i2c_dw_xfer_msg(struct dw_i2c_dev *dev)if (dev->rx_outstanding >= dev->rx_fifo_depth)break ; +/* +* For block reads, queue only the length +* byte until i2c_dw_recv_len() runs. +*/ +if ((flags &I2C_M_RECV_LEN ) && + buf_len < msgs[dev->msg_write_idx].len) +break ; +regmap_write (dev->map,DW_IC_DATA_CMD , cmd |0x100 ); rx_limit--;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1029/1257 tpm: tpm2_probe: propagate transport errors
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexander Sverdlin <[email protected]>
[ Upstream commit 7d4f1cbfe063af5581dac66abe9e9c965e1031cc ]
tpm2_probe() reads the protocol version from the response tag and is documented to return -errno on failure, but it always returns 0. A transport error (tpm_transmit_cmd() < 0) is thus swallowed together with the intentionally ignored TPM response code, leaving TPM_CHIP_FLAG_TPM2 unset. A transient bus failure on the first command then misdetects a TPM 2.0 as a 1.2 and the probe fails on the TPM 1.2 path:
tpm_tis_i2c 0-002e: 1.2 TPM (device-id 0x1C, rev-id 22)
tpm tpm0: A TPM error (-62) occurred attempting to determine the timeouts
Return the transport error instead; rc >= 0 still means a valid header was received and the TPM's own response code is still ignored.
--- drivers/char/tpm/tpm2-cmd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm2-cmd.c +2 -1
@@ -483,8 +483,9 @@ int tpm2_probe(struct tpm_chip *chip) out = (struct tpm_header *)buf->data;if (be16_to_cpu (out->tag) ==TPM2_ST_NO_SESSIONS ) chip->flags |=TPM_CHIP_FLAG_TPM2 ; +return 0 ; } -return 0 ; +return rc; }EXPORT_SYMBOL_GPL (tpm2_probe);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1030/1257 tpm: tpm_nsc: fix NULL pointer dereference on init failure
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pei Xiao <[email protected]>
[ Upstream commit 1900449684cf71427a51e0bb1d7914c0c8b39152 ]
tpm_nsc_remove() is used as the release callback of the hand-created platform device and dereferences the chip drvdata unconditionally. If init fails before tpmm_chip_alloc() (e.g. request_region() cannot claim the ports), the error path drops the last device reference and the release callback runs with chip == NULL, crashing module init.
Return early when the chip has not been created yet.
--- drivers/char/tpm/tpm_nsc.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm_nsc.c +6 -1
@@ -259,7 +259,12 @@ static struct platform_device *pdev = NULL;static void tpm_nsc_remove (struct device *dev) {struct tpm_chip *chip =dev_get_drvdata (dev); -struct tpm_nsc_priv *priv =dev_get_drvdata (&chip->dev); +struct tpm_nsc_priv *priv; + +if (!chip) +return ; + + priv =dev_get_drvdata (&chip->dev);tpm_chip_unregister (chip);release_region (priv->base,2 );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1031/1257 tpm: tpm_nsc: stop using the cleanup callback as dev.release
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pei Xiao <[email protected]>
[ Upstream commit df0ef271087623439a1e900f323ed2a57204706d ]
tpm_nsc_remove() is called explicitly from cleanup_nsc() and also runs as the platform device release callback on the final platform_device_put(), so the cleanup executes twice on module exit; the second invocation operates on a chip that has already been freed by the devm cleanup, and the I/O region is released twice.
Overwriting the release callback installed by platform_device_alloc() also keeps platform_device_release() from running, leaking the platform object allocation.
Leave the default release callback in place; the explicit call in cleanup_nsc() remains the single cleanup point.
--- drivers/char/tpm/tpm_nsc.c | 1 - 1 file changed, 1 deletion(-)
drivers/char/tpm/tpm_nsc.c +0 -1
@@ -327,7 +327,6 @@ static int __init init_nsc(void) pdev->num_resources =0 ; pdev->dev.driver = &nsc_drv.driver; - pdev->dev.release = tpm_nsc_remove;if ((rc =platform_device_add (pdev)) <0 ) goto err_put_dev;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1032/1257 tpm: fix zero-length read discarding the pending response
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pei Xiao <[email protected]>
[ Upstream commit 6fc1b05077b8ac7c3193616f0bc419f6185988c6 ]
POSIX requires that a read() with a count of zero returns zero and has no other effects. tpm_common_read() treats such a call as a consumed response: it marks the pending response as read and drops it, so the response can never be retrieved; subsequent reads return zero and the next write() is allowed to overwrite the response buffer, silently breaking the command/response pairing of the TPM character devices.
Return early when the caller passes a zero count, leaving any pending response untouched for the next read. A zero-length read will not report a deferred asynchronous error; POSIX permits read() to skip error detection for a zero count.
--- drivers/char/tpm/tpm-dev-common.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/char/tpm/tpm-dev-common.c +3 -0
@@ -134,6 +134,9 @@ ssize_t tpm_common_read(struct file *file, char __user *buf,ssize_t ret_size =0 ;int rc; +if (!size) +return 0 ; +mutex_lock (&priv->buffer_mutex);if (priv->response_length) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1033/1257 gpiolib: dont report -ENOMEM for a requested line without a label
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Adrian Ambrozewicz <[email protected]>
[ Upstream commit dae739137441667d67fbfcc4d303a0ecc6618662 ]
gpiod_request_commit() sets GPIOD_FLAG_REQUESTED, calls ->request() and only then sets the label. A line in between has no label, so gpiochip_dup_line_label() passes NULL to kstrdup() and returns ERR_PTR(-ENOMEM), which for_each_hwgpio() then passes to kfree():
BUG: unable to handle page fault for address: ffcc73074355ffc8 Call Trace: gpio_sim_dbg_show gpiolib_seq_show seq_read_iter
Return NULL for such a line, as for an unrequested one.
Reproduced with gpio-sim: reading /sys/kernel/debug/gpio in a loop while lines are requested and released oopses within seconds; with this change, 100000 cycles pass.
--- drivers/gpio/gpiolib.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/gpio/gpiolib.c +6 -1
@@ -2719,6 +2719,7 @@ void gpiod_free(struct gpio_desc *desc)char *gpiochip_dup_line_label (struct gpio_chip *gc,unsigned int offset) {struct gpio_desc *desc; +const char *name;char *label; desc =gpiochip_get_desc (gc, offset);
@@ -2730,7 +2731,11 @@ char *gpiochip_dup_line_label(struct gpio_chip *gc, unsigned int offset)guard (srcu)(&desc->gdev->desc_srcu); - label =kstrdup (gpiod_get_label (desc),GFP_KERNEL ); + name =gpiod_get_label (desc); +if (!name) +return NULL ; + + label =kstrdup (name,GFP_KERNEL );if (!label)return ERR_PTR (-ENOMEM );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1034/1257 parisc: eisa_enumerator: Fix out-of-bounds reads of the EEPROM buffer
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jean Delu <[email protected]>
[ Upstream commit c0a3e153804f0c14f4159ddbd2b73483c9cb3577 ]
eisa_enumerator() trusts the contents of the EISA EEPROM. The number of slots is read from the EEPROM header and used to access the slot records at HPEE_SLOT_INFO(i) = 20 + 48*i within the fixed-size eeprom_buf (HPEE_MAX_LENGTH, 8192 bytes) without any bound check. As struct eeprom_eisa_slot_info is 48 bytes, only 170 records fit into the buffer, but num_slots is a u8 and may be up to 255, so a corrupted EEPROM makes the code read up to about 4 kB past the end of the buffer (e.g. record 254 is accessed at offset 20 + 48*254 = 12212).
parse_slot_config() has the same kind of problem: it clamps config_data_length against HPEE_MAX_LENGTH but does not take config_data_offset into account, so the parser can walk past the end of the buffer even when the offset itself is valid.
Clamp the number of slots so that all slot records fit into the buffer, and hand the number of bytes actually available to parse_slot_config() and bound the parse by it.
--- drivers/parisc/eisa_enumerator.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-)
drivers/parisc/eisa_enumerator.c +12 -3
@@ -311,6 +311,7 @@ static int configure_function(const unsigned char *buf, int *more)static int parse_slot_config (int slot,const unsigned char *buf, +unsigned int buflen,struct eeprom_eisa_slot_info *es,struct resource *io_parent,struct resource *mem_parent)
@@ -333,8 +334,8 @@ static int parse_slot_config(int slot,printk (KERN_INFO "EISA slot %d: %s %s " , slot, board, es->flags&HPEE_FLAG_BOARD_IS_ISA ?"ISA" :"EISA" ); - maxlen = es->config_data_length <HPEE_MAX_LENGTH ? - es->config_data_length :HPEE_MAX_LENGTH ; +/* never parse beyond the data that is actually in the buffer */ + maxlen = min_t(unsigned int, es->config_data_length, buflen);while ((pos < maxlen) && (num_func <= es->num_functions)) { pos+=configure_function (buf+pos, &function_len);
@@ -491,6 +492,13 @@ int eisa_enumerator(unsigned long eeprom_addr,printk (KERN_INFO "Enumerating EISA bus\n" ); eh = (struct eeprom_header *)(eeprom_buf); +/* +* The EEPROM contents are not to be trusted: clamp the number of +* slots so that all slot records fit into eeprom_buf. +*/ + eh->num_slots =min_t (u8, eh->num_slots, + (HPEE_MAX_LENGTH -sizeof (*eh)) / +sizeof (struct eeprom_eisa_slot_info ));for (i=0 ;i<eh->num_slots;i++) {struct eeprom_eisa_slot_info *es;
@@ -503,7 +511,8 @@ int eisa_enumerator(unsigned long eeprom_addr,if (es->config_data_offset <HPEE_MAX_LENGTH ) {if (parse_slot_config (i+1 , &eeprom_buf[es->config_data_offset], - es, io_parent, mem_parent)) { +HPEE_MAX_LENGTH - es->config_data_offset, + es, io_parent, mem_parent)) {return -1 ; } }else {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1035/1257 ASoC: tlv320aic32x4: Prevent division by zero in divider callbacks
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alex Kazinsky <[email protected]>
[ Upstream commit 8cf9607d2d855629260fc78e6b54ea7a98525708 ]
A zero rate requested through clk_set_rate() or clk_round_rate() reaches clk_aic32x4_div_determine_rate() when the minimum rate is zero. Clamping the requested rate to the allowed range leaves it unchanged, causing division by zero when calculating the divisor.
A zero parent rate can also cause division by zero in determine_rate(). For example, if reading a parent divider's register fails, clk_aic32x4_div_recalc_rate() returns zero, which the clock framework caches as the parent's rate. A subsequent rate request for a child divider receives this value in best_parent_rate. With a nonzero requested rate, the calculated divisor is zero. It passes the existing upper-bound check and causes division by zero in the resulting rate calculation.
The set_rate callback can receive a zero rate when an ancestor's rate changes. clk_calc_subtree() calculates descendant rates through recalc_rate() without calling their determine_rate callbacks. If reading a descendant divider's register fails, clk_aic32x4_div_recalc_rate() returns zero. This becomes the descendant's new_rate, which clk_change_rate() passes to clk_aic32x4_div_set_rate(), causing division by zero.
Reject zero rates in both callbacks and reject a zero divisor in clk_aic32x4_div_determine_rate().
Found by Linux Verification Center (linuxtesting.org) with SVACE.
--- sound/soc/codecs/tlv320aic32x4-clk.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
sound/soc/codecs/tlv320aic32x4-clk.c +7 -1
@@ -318,6 +318,9 @@ static int clk_aic32x4_div_set_rate(struct clk_hw *hw, unsigned long rate,struct clk_aic32x4 *div =to_clk_aic32x4 (hw);u8 divisor; +if (!rate) +return -EINVAL ; + divisor =DIV_ROUND_UP (parent_rate, rate);if (divisor >AIC32X4_DIV_MAX )return -EINVAL ;
@@ -331,8 +334,11 @@ static int clk_aic32x4_div_determine_rate(struct clk_hw *hw, {unsigned long divisor; +if (!req->rate) +return -EINVAL ; + divisor =DIV_ROUND_UP (req->best_parent_rate, req->rate); -if (divisor >AIC32X4_DIV_MAX ) +if (!divisor || divisor >AIC32X4_DIV_MAX )return -EINVAL ; req->rate =DIV_ROUND_UP (req->best_parent_rate, divisor);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1036/1257 i2c: mt7621: fix copying uninitialized kernel stack with reduced page_len
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Marangi <[email protected]>
[ Upstream commit b7fd977fec0d3f2bdd4f13bb59949c817a365652 ]
When a page_len is less than 5 bytes in mtk_i2c_xfer, uninitialized kernel stack data is copied and written to REG_SM0D1_REG. Equally on the read part, an unnecessary read is done.
Guard these extra copy/write and read for the page_len to fix leaking uninitialized stack memory.
--- drivers/i2c/busses/i2c-mt7621.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/i2c/busses/i2c-mt7621.c +6 -3
@@ -144,7 +144,6 @@ static int mtk_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,u16 addr;int i, j, ret, len, page_len;u32 cmd; -u32 data[2 ]; i2c =i2c_get_adapdata (adap);
@@ -186,6 +185,8 @@ static int mtk_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,/* transfer data */ for (len = pmsg->len, j =0 ; len >0 ; len -=8 , j +=8 ) { +u32 data[2 ] = { }; + page_len = (len >=8 ) ?8 : len;if (pmsg->flags &I2C_M_RD ) {
@@ -194,7 +195,8 @@ static int mtk_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs, }else {memcpy (data, &pmsg->buf[j], page_len);iowrite32 (data[0 ], i2c->base +REG_SM0D0_REG ); -iowrite32 (data[1 ], i2c->base +REG_SM0D1_REG ); +if (page_len >4 ) +iowrite32 (data[1 ], i2c->base +REG_SM0D1_REG ); cmd =SM0CTL1_WRITE ; }
@@ -204,7 +206,8 @@ static int mtk_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,if (pmsg->flags &I2C_M_RD ) { data[0 ] =ioread32 (i2c->base +REG_SM0D0_REG ); - data[1 ] =ioread32 (i2c->base +REG_SM0D1_REG ); +if (page_len >4 ) + data[1 ] =ioread32 (i2c->base +REG_SM0D1_REG );memcpy (&pmsg->buf[j], data, page_len); }else {if (!(pmsg->flags &I2C_M_IGNORE_NAK )) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1037/1257 sched/cache: Honor asym packing over cache aware scheduling on hybrid systems
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Chen <[email protected]>
[ Upstream commit ee92b7ef4c1e271b3c1ea2a8b13034bdc62422a7 ]
A regression was reported on an AMD Ryzen AI HX 370 running a cache intensive Clang full-LTO link. The little cores run at a much lower frequency (3.3 GHz vs 5.1 GHz) and have only half of the L3 cache (8 MB vs 16 MB), so pinning such a task to the little-core LLC hurts twice, and full-LTO builds slow down dramatically compared to pre-cache-aware-scheduling kernels.
Asym packing and cache aware scheduling express conflicting placement strategies. Asym packing wants a task to run on the highest priority CPU, whereas cache aware scheduling wants to co-locate the tasks of a process on one LLC regardless of the priority of CPUs in that LLC.
When asym packing tries to migrate task to an idle core that has higher priority than source cpu, let asym packing win. Moving tasks to a higher performing idle core will buy more performance than cache co-location.
Prioritize asym packing over LLC balancing for regular and active load balancing.
--- kernel/sched/fair.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-)
kernel/sched/fair.c +17 -3
@@ -10945,6 +10945,8 @@ static inline bool task_misfits_asym_cpu(struct lb_env *env, struct task_structreturn false; } +static inline bool sched_asym (struct sched_domain *sd,int dst_cpu,int src_cpu); +/* * Check if task p can migrate from source LLC to * destination LLC in terms of cache aware load balance.
@@ -10969,6 +10971,10 @@ static enum llc_mig can_migrate_llc_task(struct lb_env *env,if (cpu <0 ||cpus_share_cache (src_cpu, dst_cpu))return mig_unrestricted; +/* Prioritize asym packing to idle core over cache awareness */ +if (env->idle &&sched_asym (env->sd, dst_cpu, src_cpu)) +return mig_unrestricted; +/* skip cache aware load balance for too many threads */ if (invalid_llc_nr (grp, p, dst_cpu) ||exceed_llc_capacity (grp, dst_cpu)) {
@@ -12165,6 +12171,14 @@ static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs, sgs->group_misfit_task_load)return false; +/* +* On asym packing domains, if the destination CPU +* has higher priority than all CPUs in the source group, +* prioritize asym packing. +*/ +if (sgs->group_asym_packing) +return false; +/* * Skip cache aware tagging if nr_balanced_failed is sufficiently high. * Threshold of cache_nice_tries is set to 1 higher than nr_balance_failed
@@ -13580,12 +13594,12 @@ static int need_active_balance(struct lb_env *env) {struct sched_domain *sd = env->sd; -if (alb_break_llc (env)) -return 0 ; -if (asym_active_balance (env))return 1 ; +if (alb_break_llc (env)) +return 0 ; +if (imbalanced_active_balance (env))return 1 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1038/1257 sched: fix stale get_pref_llc() stub for !CONFIG_SCHED_CACHE
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 cac037a85c1971ec75c4d3edf5a28af9ec2a089c ]
Commit b636fef85bda ("sched/cache: Introduce task_struct->sched_cache_grp to fix UAF") switched get_pref_llc() from taking a struct mm_struct * to taking the task's struct sched_cache_group *, but only updated the CONFIG_SCHED_CACHE definition and its caller: the stub in the !CONFIG_SCHED_CACHE branch kept the old mm_struct parameter.
--- kernel/sched/fair.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/sched/fair.c +1 -1
@@ -2194,7 +2194,7 @@ void init_sched_mm(struct task_struct *p) { }static void task_tick_cache (struct rq *rq,struct task_struct *p) { }static inline int get_pref_llc (struct task_struct *p, -struct mm_struct *mm) +struct sched_cache_group *grp) {return -1 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1039/1257 spi: zynq-qspi: fix address buffer corruption and support 4-byte address
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pufan Jin <[email protected]>
[ Upstream commit dc5ca34f5e8dc10c566ef39aa3b1a201a17ca734 ]
In zynq_qspi_exec_mem_op(), when transmitting address bytes, the driver iterates over op->addr.nbytes and populates xqspi->txbuf[i]. However, xqspi->txbuf is never re-assigned before populating the address, meaning it still points to (u8 *)&op->cmd.opcode from the command phase.
This causes two severe issues:
1. Memory corruption: Writing into xqspi->txbuf writes past the opcode buffer on the stack (which was passed as const struct spi_mem_op *). If opcode is zero, xqspi->txbuf is uninitialized.
2. In zynq_qspi_supports_op(), operations with op->addr.nbytes > 3 are rejected. When paired with SPI NOR flashes larger than 16MB (such as Winbond W25Q256), spi_nor_spimem_check_read_pp_op() tests 4-byte address support, which fails and causes spi_nor_select_read() to drop all read capabilities, failing probe with -EINVAL (-22).
The Zynq-7000 QSPI controller hardware in manual I/O mode natively supports transmitting 1 to 4 address bytes via its TXD FIFO registers (ZYNQ_QSPI_TXD_00_00_OFFSET).
Fix this by introducing a local opaddr[4] buffer in zynq_qspi_exec_mem_op() and explicitly setting xqspi->txbuf = opaddr before populating address bytes. Also allow up to 4 address bytes in zynq_qspi_supports_op().
--- drivers/spi/spi-zynq-qspi.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-)
drivers/spi/spi-zynq-qspi.c +7 -6
@@ -229,11 +229,10 @@ static bool zynq_qspi_supports_op(struct spi_mem *mem,return false;/* -* The number of address bytes should be equal to or less than 3 bytes. +* The number of address bytes should be equal to or less than 4 bytes. */ -if (op->addr.nbytes >3 ) +if (op->addr.nbytes >4 )return false; -return true; }
@@ -526,6 +525,7 @@ static int zynq_qspi_exec_mem_op(struct spi_mem *mem, const struct spi_mem_op *op) {struct zynq_qspi *xqspi =spi_controller_get_devdata (mem->spi->controller); +u8 opaddr[4 ]__aligned(4) ;int err =0 , i;u8 *tmpbuf;
@@ -547,12 +547,13 @@ static int zynq_qspi_exec_mem_op(struct spi_mem *mem, }if (op->addr.nbytes) { -for (i =0 ; i < op->addr.nbytes; i++) { - xqspi->txbuf[i] = op->addr.val >> +for (i =0 ; i < op->addr.nbytes; i++) + opaddr[i] = op->addr.val >> (8 * (op->addr.nbytes - i -1 )); - }reinit_completion (&xqspi->data_completion); + xqspi->txbuf = opaddr; + xqspi->rxbuf =NULL ; xqspi->tx_bytes = op->addr.nbytes; xqspi->rx_bytes = op->addr.nbytes;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1040/1257 ipmr: only copy pktinfo to cache reports
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhiling Zou <[email protected]>
[ Upstream commit 94a6736bb5abe6b2ef38490d0cab19c1c6a7c71f ]
ipmr_cache_report() prepares IP_PKTINFO on the original skb. The ipv4_pktinfo_prepare() helper updates skb->cb and clears the pktinfo fields when packet info is disabled. Since the skb can continue through the data path, preserve and restore its original control block around the helper.
The original implementation copies the entire control block to the report skb. For synthetic RTM_GETROUTE packets, NETLINK_CB data is interpreted as IPCB by the raw IPv4 receive path. With IP_RECVOPTS or IP_RETOPTS enabled, corrupted option offsets cause out-of-bounds reads or a stack buffer overflow. WHOLEPKT and WRVIFWHOLE reports also inherit stale IP option offsets when their header is prepended.
Clear the report skb control block. Only prepare and copy pktinfo when the input skb has an IPv4 header. Synthetic route-query skbs use NETLINK_CB, not IPCB, so leave their report control block zeroed. Restore pkt->cb after preparing pktinfo for regular IPv4 packets.
--- net/ipv4/ipmr.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
net/ipv4/ipmr.c +10 -2
@@ -1057,6 +1057,7 @@ static void ipmr_cache_resolve(struct net *net, struct mr_table *mrt,static int ipmr_cache_report (const struct mr_table *mrt,struct sk_buff *pkt,vifi_t vifi,int assert) { +unsigned char pkt_cb[sizeof (pkt->cb)];const int ihl =ip_hdrlen (pkt);struct sock *mroute_sk;struct igmphdr *igmp;
@@ -1112,8 +1113,6 @@ static int ipmr_cache_report(const struct mr_table *mrt, msg = (struct igmpmsg *)skb_network_header (skb); msg->im_vif = vifi; msg->im_vif_hi = vifi >>8 ; -ipv4_pktinfo_prepare (mroute_sk, pkt, false); -memcpy (skb->cb, pkt->cb,sizeof (skb->cb));/* Add our header. * Note that code, csum and group fields are cleared. */
@@ -1124,6 +1123,15 @@ static int ipmr_cache_report(const struct mr_table *mrt, skb->transport_header = skb->network_header; } +memset (skb->cb,0 ,sizeof (skb->cb)); +/* Route queries from ipmr_get_route() carry NETLINK_CB, not IPCB. */ +if (ip_hdr (pkt)->version) { +memcpy (pkt_cb, pkt->cb,sizeof (pkt_cb)); +ipv4_pktinfo_prepare (mroute_sk, pkt, false); + *PKTINFO_SKB_CB (skb) = *PKTINFO_SKB_CB (pkt); +memcpy (pkt->cb, pkt_cb,sizeof (pkt_cb)); + } +igmpmsg_netlink_event (mrt, skb);/* Deliver to mrouted */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1041/1257 posix-cpu-timers: Fix pid refcount leak in do_cpu_nanosleep() signal path
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft) <[email protected]>
[ Upstream commit 8ccd731b63a0183ca2b0e18f3ca15864b3f37eda ]
do_cpu_nanosleep() sleeps on a temporary k_itimer whose reference on the target's struct pid is taken by posix_cpu_timer_create() and dropped by posix_cpu_timer_del(). When a signal ends the sleep, the timer is disarmed with posix_cpu_timer_set(), but posix_cpu_timer_del() is only called for a result of 0 or TIMER_RETRY. If the target thread or process has exited in the meantime, timer_lock_sighand() finds no task, posix_cpu_timer_set() returns -ESRCH and the pid reference is leaked.
An unprivileged user can trigger this: sleep on the CPU clock of a thread, let that thread exit, then signal the sleeper. Each round leaks one struct pid. Repeating it exhausts unreclaimable slab memory within minutes:
Out of memory: Killed process 150 (poc) total-vm:789292kB, anon-rss:484kB
Kernel panic - not syncing: System is deadlocked on memory
Fix this by also calling posix_cpu_timer_del() on -ESRCH. With the target gone, the deletion is safe. It finds no task either and only drops the pid reference.
--- kernel/time/posix-cpu-timers.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/time/posix-cpu-timers.c +2 -2
@@ -1600,8 +1600,8 @@ static int do_cpu_nanosleep(const clockid_t which_clock, int flags,*/ expires =cpu_timer_getexpires (&timer.it.cpu); error =posix_cpu_timer_set (&timer,0 , &zero_it, &it); -if (!error) { -/* Timer is now unarmed, deletion can not fail. */ +if (error !=TIMER_RETRY ) { +/* Unarmed or target gone (-ESRCH), deletion can not fail. */ posix_cpu_timer_del (&timer); }else {while (error ==TIMER_RETRY ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1042/1257 timekeeping: Require permission to set auxiliary clocks
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
[ Upstream commit 524d95c8a2000cba6cb80a173d76cb746c561244 ]
The generic clock_settime() entry point delegates permission checks to each clock-specific callback. aux_clock_set() does not perform one. Once an administrator enables an auxiliary clock, any local process can therefore change the global clock offset.
A test process running as UID and GID 65534 with no effective, permitted, inheritable, or ambient capabilities set CLOCK_AUX0 successfully, and a separate process observed the new value. The same process was denied by clock_adjtime(). An AppArmor profile denying sys_time also blocked CLOCK_REALTIME changes but did not see the auxiliary clock operation.
Call security_settime64() before mutating the auxiliary timekeeper. This matches CLOCK_REALTIME's permission model, enforces initial-user-namespace CAP_SYS_TIME, and gives LSMs the settime hook while preserving authorized clock changes.
--- kernel/time/timekeeping.c | 5 +++++ 1 file changed, 5 insertions(+)
kernel/time/timekeeping.c +5 -0
@@ -14,6 +14,7 @@#include <linux/random.h> #include <linux/sched/clock.h> #include <linux/sched/loadavg.h> +#include <linux/security.h> #include <linux/static_key.h> #include <linux/stop_machine.h> #include <linux/syscore_ops.h>
@@ -3215,11 +3216,15 @@ static int aux_clock_set(const clockid_t id, const struct timespec64 *tnew)struct tk_data *aux_tkd =aux_get_tk_data (id);struct timekeeper *aux_tks;ktime_t tnow, nsecs; +int ret;if (!timespec64_valid_settod (tnew))return -EINVAL ;if (!aux_tkd)return -ENODEV ; + ret =security_settime64 (tnew,NULL ); +if (ret) +return ret; aux_tks = &aux_tkd->shadow_timekeeper;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1043/1257 timekeeping: Update offsets on sequence counter retry in ktime_get_update_offsets_now()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Thomas Weißschuh (Schneider Electric) <[email protected]>
[ Upstream commit 6541fbc942f3b63bb8bd44e34eee6223e0abe719 ]
The sequence counter of the cwsseq target is modified during the sequence counter loop. If the loop retries, cwsseq will now match but the offsets contain the values from the previous loop iteration. These are not guaranteed to be consistent in themselves or with the current loops "now.
Save the target's original sequence counter value so that the update also happens on loop retries.
--- kernel/time/timekeeping.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/time/timekeeping.c +2 -1
@@ -2849,6 +2849,7 @@ ktime_t ktime_get_update_offsets_now(u32 *cwsseq, ktime_t *offs_real, ktime_t *offs_boot, ktime_t *offs_tai) {struct timekeeper *tk = &tk_core.timekeeper; +u32 cwsseq_orig = *cwsseq;unsigned int seq;ktime_t base;u64 nsecs;
@@ -2860,7 +2861,7 @@ ktime_t ktime_get_update_offsets_now(u32 *cwsseq, ktime_t *offs_real, nsecs =timekeeping_get_ns (&tk->tkr_mono); base =ktime_add_ns (base, nsecs); -if (*cwsseq != tk->clock_was_set_seq) { +if (cwsseq_orig != tk->clock_was_set_seq) { *cwsseq = tk->clock_was_set_seq; *offs_real = tk->offs_real; *offs_boot = tk->offs_boot;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1044/1257 cgroup: dont kill migrated processes through their exiting threads
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
[ Upstream commit 5f4a3f743acc96987ae5c2e966947942c34ba56c ]
Since commit da13e0e72a73 ("cgroup: fix cgroup.kill for exited thread group leader"), __cgroup_kill() visits every thread in the cgroup and sends SIGKILL with PIDTYPE_TGID, so each visited thread takes down its whole thread group.
A thread that has started exiting can stay in a cgroup after its process has been moved out of it. cgroup_migrate_add_task() skips PF_EXITING tasks, and the thread is only unlinked by cgroup_task_dead() after its final context switch. mm_release() clears the thread's clear_child_tid word and wakes the joiner well before that, so pthread_join() can return while the thread is still in the old cgroup.
If cgroup.kill is written in that window, __cgroup_kill() finds the exiting thread and complete_signal() passes the group-wide SIGKILL on to a live thread, killing a process that already left the cgroup. The cgroup selftest test_stress.sh runs into this: test_cgcore_proc_migration() joins its threads, moves itself back to the root cgroup, and cg_destroy() falls back to cgroup.kill on the old cgroup when rmdir() fails with EBUSY, so test_core kills itself. KernelCI has been reporting "with_stress.sh: line 94: ... Killed" on several arm64 boards since the commit reached linux-next.
Keep visiting every thread, but go back to sending SIGKILL to the thread that was found. A SIGKILL sent to a live thread still kills its whole thread group, so both cases fixed by that commit stay fixed, and task_can_queue_signal() drops one sent to a thread that is already exiting.
--- kernel/cgroup/cgroup.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/cgroup/cgroup.c +1 -1
@@ -4299,7 +4299,7 @@ static void __cgroup_kill(struct cgroup *cgrp)if (__fatal_signal_pending (task))continue ; -do_send_sig_info (SIGKILL ,SEND_SIG_NOINFO , task,PIDTYPE_TGID ); +send_sig (SIGKILL , task,0 ); }css_task_iter_end (&it); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1045/1257 gve: fix out-of-bounds read in gve_get_flow_rule_entry()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aamir Ahmed <[email protected]>
[ Upstream commit 45e0a63f9c86a558afc70d79b6df38f8ec7f502a ]
gve_get_flow_rule_entry() checks the requested location against the first and last cached rules, but rules_cache_num can be 0 while rules_cache_synced is true: GVE_FLOW_RULE_QUERY_RULES returns the rules from the requested location onwards, so a request past the last installed rule - or any request when no rules are installed - returns zero rules, which the driver accepts and marks as synced.
The next query evaluates rules_cache[*cache_num - 1] with *cache_num == 0. The zero-initialised cache does not trip the earlier comparison, *cache_num - 1 wraps to 0xFFFFFFFF in u32, and the read faults about 352 GiB past the cache. ETHTOOL_GRXCLSRULE needs no capability, so an unprivileged user can trigger it:
BUG: unable to handle page fault for address: ff240996c4c64fa8
#PF: supervisor read access in kernel mode
RIP: gve_get_flow_rule_entry+0xd4/0x110 [gve]Treat an empty cache as a cache miss and re-query.
--- drivers/net/ethernet/google/gve/gve_flow_rule.c | 1 + 1 file changed, 1 insertion(+)
drivers/net/ethernet/google/gve/gve_flow_rule.c +1 -0
@@ -206,6 +206,7 @@ int gve_get_flow_rule_entry(struct gve_priv *priv, struct ethtool_rxnfc *cmd)return -EOPNOTSUPP ;if (!priv->flow_rules_cache.rules_cache_synced || + !*cache_num || fsp->location <be32_to_cpu (rules_cache[0 ].location) || fsp->location >be32_to_cpu (rules_cache[*cache_num -1 ].location)) { err =gve_adminq_query_flow_rules (priv,GVE_FLOW_RULE_QUERY_RULES , fsp->location);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1046/1257 genirq/kexec: Do not take the bus lock of an interrupt chip on the crash path
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Velkov <[email protected]>
[ Upstream commit 717862eac6eff0eea8ac30a0c0de0bed84922aab ]
machine_kexec_mask_interrupts() calls irq_set_irqchip_state() for every started interrupt. That function takes the bus lock of the chip and desc->lock, and syncs the chip when it drops them. On the crash path interrupts are off and the other CPUs are stopped, so a chip whose bus transfer is completed by an interrupt never returns from the sync.
On RK3399 boards with an RK808 PMIC the RTC alarm interrupt belongs to the regmap-irq chip of the RK808, which sits on I2C. rk808_irq_chip sets init_ack_masked, so regmap_irq_sync_unlock() writes the ack register on every unlock, and the I2C controller needs its own interrupt to finish the transfer. A panic with a crash kernel loaded prints
SMP: stopping secondary CPUs
and then nothing until the watchdog resets the board.
machine_kexec_mask_interrupts() takes neither lock for the other operations on the descriptor. Move the search for the chip that implements irq_set_irqchip_state() into __irq_set_irqchip_state(), which takes no locks, and call it from machine_kexec_mask_interrupts().
--- kernel/irq/internals.h | 1 + kernel/irq/kexec.c | 2 +- kernel/irq/manage.c | 43 +++++++++++++++++++++++------------------- 3 files changed, 26 insertions(+), 20 deletions(-)
kernel/irq/internals.h +1 -0
@@ -83,6 +83,7 @@ enum {#include "settings.h" extern int __irq_set_trigger (struct irq_desc *desc,unsigned long flags); +extern int __irq_set_irqchip_state (struct irq_desc *desc,enum irqchip_irq_state which,bool val);extern void __disable_irq (struct irq_desc *desc);extern void __enable_irq (struct irq_desc *desc);
kernel/irq/kexec.c +1 -1
@@ -25,7 +25,7 @@ void machine_kexec_mask_interrupts(void)* First try to remove the active state from an interrupt which is forwarded * to a VM. If the interrupt is not forwarded, try to EOI the interrupt. */ - check_eoi =irq_set_irqchip_state (i,IRQCHIP_STATE_ACTIVE , false); + check_eoi =__irq_set_irqchip_state (desc,IRQCHIP_STATE_ACTIVE , false); }if (check_eoi && chip->irq_eoi &&irqd_irq_inprogress (&desc->irq_data))
kernel/irq/manage.c +24 -19
55 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1047/1257 veth: fix stale peer max_mtu on XDP program replacement
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: yanxia <[email protected]>
[ Upstream commit c955325db639e9503941227e14e1f1ccc99442a1 ]
veth_xdp_set() calculates the peer MTU limit from the incoming program's XDP fragment capability, but only stores it when no program was attached. Replacing a program with one having a different fragment capability therefore leaves the peer's max_mtu stale.
Replacing a regular program with an xdp.frags program keeps rejecting otherwise valid jumbo MTUs. The opposite replacement leaves a larger limit in place and permits MTUs which a fresh attachment of the regular program would reject.
Update peer->max_mtu after every successful attachment or replacement. Keep the GSO feature update conditional on the first attachment.
Found during review of the XDP replacement path and confirmed with native XDP on an isolated veth pair. Before the fix, direct replacement rejects MTU 9000 after switching to xdp.frags, and accepts it after switching back to a regular program. Detaching and attaching instead produces the expected results in both directions.
UML tests on net reproduce the problem before this change and match the detach/attach controls afterwards, with both devices up or down and with either endpoint receiving XDP. Failed replacements preserve the previous state; same-type replacements and detach also behave as expected. Small-frame traffic passes in the devices-up cases.
--- drivers/net/veth.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/net/veth.c +2 -3
@@ -1622,10 +1622,9 @@ static int veth_xdp_set(struct net_device *dev, struct bpf_prog *prog, } } -if (!old_prog) { +if (!old_prog) peer->hw_features &= ~NETIF_F_GSO_SOFTWARE ; - peer->max_mtu = max_mtu; - } + peer->max_mtu = max_mtu;xdp_features_set_redirect_target (peer, true); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1048/1257 scsi: ufs: bsg: Complete the job on error
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit cc0ce3fe8fac073ecded4f32c8ee5b89da1397e8 ]
When ufs_bsg_request() fails, it returns a non-zero status without calling bsg_job_done(). bsg_queue_rq() then ends the request with BLK_STS_IOERR without running bsg_complete(), leaking the job's device reference and mapped scatterlists.
Always complete the job via bsg_job_done() and return 0, matching other BSG transports. Requests failing with a negative errno now return it from SG_IO with the 4-byte result in the reply, while positive status codes still return 0 from SG_IO with the reply header.
--- drivers/ufs/core/ufs_bsg.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-)
drivers/ufs/core/ufs_bsg.c +3 -5
@@ -195,14 +195,12 @@ static int ufs_bsg_request(struct bsg_job *job)ufshcd_rpm_put_sync (hba);kfree (buff); bsg_reply->result = ret; -/* complete the job here only if no error */ -if (ret ==0 ) { +if (ret ==0 ) job->reply_len = rpmb ?sizeof (struct ufs_rpmb_reply ) :sizeof (struct ufs_bsg_reply ); -bsg_job_done (job, ret, bsg_reply->reply_payload_rcv_len); - } +bsg_job_done (job, ret, bsg_reply->reply_payload_rcv_len); -return ret; +return 0 ; }/**
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1049/1257 scsi: ufs: bsg: Clear the reply buffer before use
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit 2e63ac76cc08ea376ba61fef52f7b7849e35024d ]
The reply buffer is allocated once per tag and reused. Requests that complete with a positive status do not fill all of it, so user space receives bytes from an earlier request on the same tag.
Clear the whole reply buffer on entry to ufs_bsg_request().
--- drivers/ufs/core/ufs_bsg.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/ufs/core/ufs_bsg.c +1 -1
@@ -140,7 +140,7 @@ static int ufs_bsg_request(struct bsg_job *job)int ret;bool rpmb = false; - bsg_reply->reply_payload_rcv_len =0 ; +memset (job->reply,0 , job->reply_len);ufshcd_rpm_get_sync (hba);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1050/1257 scsi: ufs: bsg: Validate request_len before accessing request
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit 42aa443718104d10dbdb6f258810b425eb2451f8 ]
ufs_bsg_request() and ufs_bsg_exec_advanced_rpmb_req() read the request buffer without checking job->request_len, which userspace controls. A short request causes an out-of-bounds read. Found by syzkaller.
Reject requests shorter than the structure each path reads.
--- drivers/ufs/core/ufs_bsg.c | 9 +++++++++ 1 file changed, 9 insertions(+)
drivers/ufs/core/ufs_bsg.c +9 -0
@@ -73,6 +73,9 @@ static int ufs_bsg_exec_advanced_rpmb_req(struct ufs_hba *hba, struct bsg_job *jif (hba->ufs_version <ufshci_version (4 ,0 ) || !hba->dev_info.b_advanced_rpmb_en)return -EINVAL ; +if (job->request_len <sizeof (*rpmb_request)) +return -EINVAL ; +if (rpmb_request->ehs_req.length !=2 || rpmb_request->ehs_req.ehs_type !=1 )return -EINVAL ;
@@ -142,6 +145,11 @@ static int ufs_bsg_request(struct bsg_job *job)memset (job->reply,0 , job->reply_len); +if (job->request_len <sizeof (*bsg_request)) { + ret = -EINVAL ; + goto out_complete; + } +ufshcd_rpm_get_sync (hba); msgcode = bsg_request->msgcode;
@@ -194,6 +202,7 @@ static int ufs_bsg_request(struct bsg_job *job) out:ufshcd_rpm_put_sync (hba);kfree (buff); +out_complete: bsg_reply->result = ret;if (ret ==0 ) job->reply_len = rpmb ? sizeof(struct ufs_rpmb_reply) :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1051/1257 scsi: ufs: bsg: Reject UIC commands with a non-zero result byte
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit 1ae42513205a38b811afedb6797f9f9c4de37b90 ]
ufs_bsg_request() passes the user-supplied UIC argument2 unchanged, including the result byte (bits 7:0) that only the host controller writes. A non-zero value triggers the WARN_ON_ONCE() in ufshcd_dispatch_uic_cmd() and corrupts the reported result. Found by syzkaller.
Reject UIC commands that have the result byte set with -EINVAL.
--- drivers/ufs/core/ufs_bsg.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/ufs/core/ufs_bsg.c +4 -0
@@ -179,6 +179,10 @@ static int ufs_bsg_request(struct bsg_job *job)break ;case UPIU_TRANSACTION_UIC_CMD :memcpy (&uc, &bsg_request->upiu_req.uc,UIC_CMD_SIZE ); +if (uc.argument2 &MASK_UIC_COMMAND_RESULT ) { + ret = -EINVAL ; +break ; + } ret =ufshcd_send_bsg_uic_cmd (hba, &uc);if (ret)dev_err (hba->dev,"send uic cmd: error code %d\n" , ret);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1052/1257 scsi: ufs: core: Clear stale UIC result byte before peer DME retries
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit e4a9b7640914b248eb7537d4507aa42db080586a ]
Peer DME get and set retry a failed attempt with the same struct uic_command. UIC completion ORs the ConfigResultCode into argument2[7:0], and nothing clears it before the next attempt. Once an attempt fails, every retry keeps reporting that error code, even when the device returns success, so a transient failure becomes a hard failure after three retries. Each such retry also triggers the WARN_ON_ONCE() in ufshcd_dispatch_uic_cmd(). In ufshcd_dme_set_attr(), ufshcd_uic_cmd_compl() also overwrites argument3 with the register readback before the next attempt.
Clear the result byte and restore argument3 in ufshcd_dme_set_attr() when an attempt fails.
--- drivers/ufs/core/ufshcd.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/ufs/core/ufshcd.c +7 -2
@@ -4359,9 +4359,12 @@ int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,do {/* for peer attributes we retry upon failure */ ret =ufshcd_send_uic_cmd (hba, &uic_cmd); -if (ret) +if (ret) {dev_dbg (hba->dev,"%s: attr-id 0x%x val 0x%x error code %d\n" , set,UIC_GET_ATTR_ID (attr_sel), mib_val, ret); + uic_cmd.argument2 &= ~MASK_UIC_COMMAND_RESULT ; + uic_cmd.argument3 = mib_val; + } }while (ret && peer && --retries);if (ret)
@@ -4426,9 +4429,11 @@ int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,do {/* for peer attributes we retry upon failure */ ret =ufshcd_send_uic_cmd (hba, &uic_cmd); -if (ret) +if (ret) {dev_dbg (hba->dev,"%s: attr-id 0x%x error code %d\n" , get,UIC_GET_ATTR_ID (attr_sel), ret); + uic_cmd.argument2 &= ~MASK_UIC_COMMAND_RESULT ; + } }while (ret && peer && --retries);if (ret)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1053/1257 scsi: ufs: core: Fix a deadlock between clock scaling and device commands
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 2327df6d2a290af62a6da21b2ad301848bb86002 ]
Since commit 08b12cda6c44 ("scsi: ufs: core: Switch to scsi_get_internal_cmd()"), device management commands go through blk_execute_rq() on the pseudo SCSI device, which shares the tagset with the logical units, while ufshcd_dev_man_lock() holds clk_scaling_lock for reading.
ufshcd_clock_scaling_prepare() and ufshcd_pause_command_processing() quiesce the tagset before taking clk_scaling_lock for writing. A device management command holding the lock for reading at that point is never dispatched and never times out, so the writer waits forever with all logical units quiesced. On a Lenovo Legion Tab Y700 Gen 5 this ended in a hung task panic.
Take clk_scaling_lock before quiescing the tagset, and in ufshcd_clock_scaling_prepare() also wb_mutex, which is always taken before clk_scaling_lock. Release them in the reverse order. Commit b52d695d0620 ("scsi: ufs: core: Keep internal commands dispatchable during error handling") fixed the same problem in the error handler.
--- drivers/ufs/core/ufshcd.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/ufs/core/ufshcd.c +6 -6
@@ -1360,13 +1360,13 @@ int ufshcd_pause_command_processing(struct ufs_hba *hba, u64 timeout_us)int ret =0 ;mutex_lock (&hba->host->scan_mutex); -blk_mq_quiesce_tagset (&hba->host->tag_set);down_write (&hba->clk_scaling_lock); +blk_mq_quiesce_tagset (&hba->host->tag_set);if (ufshcd_wait_for_pending_cmds (hba, timeout_us)) { ret = -EBUSY ; -up_write (&hba->clk_scaling_lock);blk_mq_unquiesce_tagset (&hba->host->tag_set); +up_write (&hba->clk_scaling_lock);mutex_unlock (&hba->host->scan_mutex); }
@@ -1383,8 +1383,8 @@ void ufshcd_resume_command_processing(struct ufs_hba *hba) __releases(&hba->clk_scaling_lock) __releases(&hba->host->scan_mutex) { -up_write (&hba->clk_scaling_lock);blk_mq_unquiesce_tagset (&hba->host->tag_set); +up_write (&hba->clk_scaling_lock);mutex_unlock (&hba->host->scan_mutex); }
@@ -1461,16 +1461,16 @@ static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba, u64 timeout_us)* clock scaling is in progress */ mutex_lock (&hba->host->scan_mutex); -blk_mq_quiesce_tagset (&hba->host->tag_set);mutex_lock (&hba->wb_mutex);down_write (&hba->clk_scaling_lock); +blk_mq_quiesce_tagset (&hba->host->tag_set);if (!hba->clk_scaling.is_allowed ||ufshcd_wait_for_pending_cmds (hba, timeout_us)) { ret = -EBUSY ; +blk_mq_unquiesce_tagset (&hba->host->tag_set);up_write (&hba->clk_scaling_lock);mutex_unlock (&hba->wb_mutex); -blk_mq_unquiesce_tagset (&hba->host->tag_set);mutex_unlock (&hba->host->scan_mutex); goto out; }
@@ -1487,9 +1487,9 @@ static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err) __releases(&hba->wb_mutex) __releases(&hba->host->scan_mutex) { +blk_mq_unquiesce_tagset (&hba->host->tag_set);up_write (&hba->clk_scaling_lock);mutex_unlock (&hba->wb_mutex); -blk_mq_unquiesce_tagset (&hba->host->tag_set);mutex_unlock (&hba->host->scan_mutex);/* Enable Write Booster if current gear requires it else disable it */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1054/1257 scsi: libiscsi_tcp: Prevent R2T range check overflow
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ratnaker Gautam <[email protected]>
[ Upstream commit eb7aa7fd673fdc1582223cd133bcc5f54e7af19f ]
An iSCSI target controls the R2T data offset and length as 32-bit values. Adding them before comparing the result with the SCSI data buffer length can wrap. An R2T with offset 1 and length U32_MAX then passes the check for a 4096-byte write.
The transmit path treats the wrapped range as valid, exhausts the command scatterlist, and dereferences the NULL next entry in iscsi_tcp_segment_done().
Check the offset first, then compare the length with the remaining bytes in the data buffer.
--- drivers/scsi/libiscsi_tcp.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/scsi/libiscsi_tcp.c +2 -1
@@ -601,7 +601,8 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr) data_length, session->max_burst); data_offset =be32_to_cpu (rhdr->data_offset); -if (data_offset + data_length > task->sc->sdb.length) { +if (data_offset > task->sc->sdb.length || + data_length > task->sc->sdb.length - data_offset) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with data len %u at offset %u " "and total length %d\n", data_length,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1055/1257 scsi: sd: Mark the disk dead if runtime resume fails in sd_remove()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bart Van Assche <[email protected]>
[ Upstream commit 085bb18a0b91007f04ddca13af30277c78040157 ]
If a SCSI disk is unplugged while runtime suspended, its request queue is still in the pm-only state when sd_remove() is called. The runtime resume attempted by scsi_autopm_get_device() fails because the parent device, e.g. a USB device in the USB_STATE_NOTATTACHED state, cannot be resumed. Hence, sdev_runtime_resume() is not called and the pm-only state is not cleared. Next, del_gendisk() calls blk_report_disk_dead(disk, false), which calls sync_filesystem(). Any bio submitted by the filesystem waits forever in __bio_queue_enter() because the queue will never leave the pm-only state and because GD_DEAD has not yet been set:
__bio_queue_enter+0xb8/0x174 blk_mq_submit_bio+0x640/0x7e4 [ ... ] exfat_sync_fs+0xa4/0xe0 sync_filesystem+0xa8/0xdc fs_bdev_mark_dead+0x30/0x88 bdev_mark_dead+0x54/0xc4 blk_report_disk_dead+0x8c/0xd4 del_gendisk+0xa0/0x2f8 sd_remove+0x30/0x60 [ ... ] scsi_remove_host+0x88/0x18c usb_stor_disconnect+0x68/0xf4
Fix this hang by calling blk_mark_disk_dead() if runtime resume fails. This sets GD_DEAD, tells the filesystem that the disk has been removed without attempting to sync it, and wakes up any bios that are waiting in __bio_queue_enter(). Syncing the filesystem is not possible anyway if runtime resume failed, so no data is lost that could otherwise have been written. If runtime resume succeeds, behavior is not changed.
Please note that this patch converts temporary runtime resume failures into permanent failures. Before this patch, if runtime resume fails temporarily, a filesytem sync would be postponed until a later resume succeeds.
--- drivers/scsi/sd.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
drivers/scsi/sd.c +9 -1
@@ -4270,7 +4270,15 @@ static void sd_remove(struct scsi_device *sdp)struct device *dev = &sdp->sdev_gendev;struct scsi_disk *sdkp =dev_get_drvdata (dev); -scsi_autopm_get_device (sdkp->device); +/* +* If runtime resume fails, e.g. because the device was unplugged +* while runtime suspended, the request queue stays in the pm-only +* state and any I/O submitted by del_gendisk(), e.g. from +* sync_filesystem(), would wait forever in __bio_queue_enter(). +* Prevent this by marking the disk dead. +*/ +if (scsi_autopm_get_device (sdkp->device) <0 ) +blk_mark_disk_dead (sdkp->disk);device_del (&sdkp->disk_dev);del_gendisk (sdkp->disk);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1056/1257 scsi: handle out-of-range SG_SET_TIMEOUT values
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 9a6cb1da4f3bc4633bf6669faed25a361834b1b9 ]
SG_SET_TIMEOUT accepts a signed int in USER_HZ units. The sg character device rejects negative values and limits positive values so the converted timeout fits its destination field. The block SCSI and BSG paths instead pass the value to clock_t_to_jiffies(), which accepts an unsigned long, and store the result in an unsigned int.
Negative values are converted into large unsigned timeouts. On 64-bit systems, large positive values can also exceed UINT_MAX after conversion and are truncated on assignment. With HZ=1000 and USER_HZ=100, for example, 429496730 clock ticks become 4294967300 jiffies and are stored as 4 jiffies. On 32-bit systems, an overflowing conversion becomes ULONG_MAX, which is an unsafe relative interval for the block timer comparisons.
Reject negative values with -EIO, matching drivers/scsi/sg.c. Saturate the converted value at the smaller of the destination field limit and MAX_JIFFY_OFFSET. This preserves successful ioctl behavior while avoiding both narrowing wraparound and an unsafe 32-bit timer interval.
The block SCSI behavior predates Git history. BSG has exposed the same behavior since it was introduced.
--- block/bsg.c | 5 ++++- drivers/scsi/scsi_ioctl.c | 11 ++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-)
block/bsg.c +4 -1
@@ -132,7 +132,10 @@ static long bsg_ioctl(struct file *file, unsigned int cmd, unsigned long arg)case SG_SET_TIMEOUT :if (get_user (val, intp))return -EFAULT ; - bd->timeout =clock_t_to_jiffies (val); +if (val <0 ) +return -EIO ; + bd->timeout =min (clock_t_to_jiffies (val), +min (UINT_MAX ,MAX_JIFFY_OFFSET ));return 0 ;case SG_GET_TIMEOUT :return jiffies_to_clock_t (bd->timeout);
drivers/scsi/scsi_ioctl.c +8 -3
@@ -9,6 +9,7 @@#include <linux/blkdev.h> #include <linux/interrupt.h> #include <linux/errno.h> +#include <linux/jiffies.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/mm.h>
@@ -195,10 +196,14 @@ static int sg_set_timeout(struct scsi_device *sdev, int __user *p) {int timeout, err =get_user (timeout, p); -if (!err) - sdev->sg_timeout =clock_t_to_jiffies (timeout); +if (err) +return err; +if (timeout <0 ) +return -EIO ; -return err; + sdev->sg_timeout =min (clock_t_to_jiffies (timeout), +min (UINT_MAX ,MAX_JIFFY_OFFSET )); +return 0 ; }static int sg_get_reserved_size (struct scsi_device *sdev,int __user *p)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1057/1257 scsi: ufs: core: Remove an always-false WARN_ONCE()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit cd37a69c367b6a5f685db0ac7d01f08545081a30 ]
The WARN_ONCE() in ufshcd_poll() can never fire. completed_reqs is set to ~tr_doorbell & hba->outstanding_reqs on the line above, and hba->outstanding_reqs cannot change in between because ufshcd_poll() holds hba->outstanding_lock. So completed_reqs & ~hba->outstanding_reqs is always zero. Remove it. No functional change.
--- drivers/ufs/core/ufshcd.c | 3 --- 1 file changed, 3 deletions(-)
drivers/ufs/core/ufshcd.c +0 -3
@@ -6022,9 +6022,6 @@ static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)spin_lock_irqsave (&hba->outstanding_lock, flags); tr_doorbell =ufshcd_readl (hba,REG_UTP_TRANSFER_REQ_DOOR_BELL ); completed_reqs = ~tr_doorbell & hba->outstanding_reqs; -WARN_ONCE (completed_reqs & ~hba->outstanding_reqs, -"completed: %#lx; outstanding: %#lx\n" , completed_reqs, - hba->outstanding_reqs);if (queue_num ==UFSHCD_POLL_FROM_INTERRUPT_CONTEXT ) {/* Do not complete polled requests from interrupt context. */ ufshcd_clear_polled (hba, &completed_reqs);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1058/1257 scsi: ufs: core: Add a helper for clearing hba->outstanding_reqs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit 22d14117ec1845a81acb3a5c4be325f7e8332f70 ]
ufshcd_poll() and ufshcd_abort() each have their own copy of the code that clears bits in hba->outstanding_reqs under hba->outstanding_lock.
Move that code into ufshcd_clear_outstanding_reqs() and its locked variant __ufshcd_clear_outstanding_reqs(), and use them in both functions. No functional change.
--- drivers/ufs/core/ufshcd.c | 48 +++++++++++++++++++++++++++++---------- 1 file changed, 36 insertions(+), 12 deletions(-)
drivers/ufs/core/ufshcd.c +36 -12
@@ -6002,6 +6002,37 @@ static void ufshcd_clear_polled(struct ufs_hba *hba, } } +/* +* Return a bitmask of the transfer requests cleared from +* @hba->outstanding_reqs. +*/ +static unsigned long __ufshcd_clear_outstanding_reqs (struct ufs_hba *hba, +unsigned long mask, +bool from_irq) + __must_hold(&hba->outstanding_lock) +{ +unsigned long completed_reqs = mask & hba->outstanding_reqs; + +if (from_irq) { +/* Do not complete polled requests from interrupt context. */ +ufshcd_clear_polled (hba, &completed_reqs); + } + hba->outstanding_reqs &= ~completed_reqs; + +return completed_reqs; +} + +/* +* Return a bitmask of the transfer requests cleared from +* @hba->outstanding_reqs. +*/ +static unsigned long ufshcd_clear_outstanding_reqs (struct ufs_hba *hba, +unsigned long mask) +{ +guard (spinlock_irqsave)(&hba->outstanding_lock); +return __ufshcd_clear_outstanding_reqs (hba, mask, false); +} +/* * Return: > 0 if one or more commands have been completed or 0 if no * requests have been completed.
@@ -6012,6 +6043,7 @@ static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)unsigned long completed_reqs, flags;u32 tr_doorbell;struct ufs_hw_queue *hwq; +bool from_irq;if (hba->mcq_enabled) { hwq = &hba->uhq[queue_num];
@@ -6021,12 +6053,9 @@ static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)spin_lock_irqsave (&hba->outstanding_lock, flags); tr_doorbell =ufshcd_readl (hba,REG_UTP_TRANSFER_REQ_DOOR_BELL ); - completed_reqs = ~tr_doorbell & hba->outstanding_reqs; -if (queue_num ==UFSHCD_POLL_FROM_INTERRUPT_CONTEXT ) { -/* Do not complete polled requests from interrupt context. */ -ufshcd_clear_polled (hba, &completed_reqs); - } - hba->outstanding_reqs &= ~completed_reqs; + from_irq = queue_num ==UFSHCD_POLL_FROM_INTERRUPT_CONTEXT ; + completed_reqs =__ufshcd_clear_outstanding_reqs (hba, ~tr_doorbell, + from_irq);spin_unlock_irqrestore (&hba->outstanding_lock, flags);if (completed_reqs)
@@ -8060,7 +8089,6 @@ static int ufshcd_abort(struct scsi_cmnd *cmd)struct ufshcd_lrb *lrbp =scsi_cmd_priv (cmd);unsigned long flags;int err =FAILED ; -bool outstanding;u32 reg;ufshcd_hold (hba);
@@ -8155,11 +8183,7 @@ static int ufshcd_abort(struct scsi_cmnd *cmd)* Clear the corresponding bit from outstanding_reqs since the command * has been aborted successfully. */ -spin_lock_irqsave (&hba->outstanding_lock, flags); - outstanding =__test_and_clear_bit (tag, &hba->outstanding_reqs); -spin_unlock_irqrestore (&hba->outstanding_lock, flags); - -if (outstanding) +if (ufshcd_clear_outstanding_reqs (hba,BIT (tag)))ufshcd_release_scsi_cmd (hba, cmd); err =SUCCESS ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1059/1257 scsi: ufs: core: Fix double completion in ufshcd_clear_lu_cmds()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit 6b9c1f49971e4dfe8b8916f0527d30e97c15f234 ]
In SDB mode, ufshcd_clear_lu_cmds() clears the request slot in the controller and completes the request, but leaves its bit set in hba->outstanding_reqs. ufshcd_poll() treats a request whose bit is set in hba->outstanding_reqs and clear in the doorbell register as finished, so the next ufshcd_poll() completes the same request again and unmaps its DMA buffers twice.
Clear the bit with ufshcd_clear_outstanding_reqs() before completing the request, and complete it only if the bit was still set. If ufshcd_poll() has already completed the request, the bit is already clear and ufshcd_clear_lu_cmds() skips it.
--- drivers/ufs/core/ufshcd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/ufs/core/ufshcd.c +2 -1
@@ -7936,7 +7936,8 @@ static bool ufshcd_clear_lu_cmds(struct request *req, void *priv)return true; } -ufshcd_compl_one_cqe (hba, tag,NULL ); +if (ufshcd_clear_outstanding_reqs (hba,BIT (tag))) +ufshcd_compl_one_cqe (hba, tag,NULL );return true; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1060/1257 scsi: ufs: core: Fix double release in ufshcd_eh_timed_out()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit 3a7e551ae4bcc53f271fc15ab8e930598e28dad8 ]
In SDB mode, a command that times out during a power management operation can be released twice:
1. The command times out while its normal completion is running.
2. The completion path clears BIT(rq->tag) in hba->outstanding_reqs and releases the command. It has not called scsi_done() yet, so SCMD_STATE_COMPLETE is still clear.
3. ufshcd_eh_timed_out() recovers the link, sees SCMD_STATE_COMPLETE clear, clears BIT(rq->tag) in hba->outstanding_reqs without checking whether it was still set, and releases the same command a second time.
Return SCSI_EH_DONE when ufshcd_clear_outstanding_reqs() returns 0, as another path has already claimed the command.
--- drivers/ufs/core/ufshcd.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/ufs/core/ufshcd.c +2 -4
@@ -9606,12 +9606,10 @@ static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)*/ if (!test_bit (SCMD_STATE_COMPLETE , &scmd->state)) {if (!hba->mcq_enabled) { -unsigned long flags;struct request *rq =scsi_cmd_to_rq (scmd); -spin_lock_irqsave (&hba->outstanding_lock, flags); -__clear_bit (rq->tag, &hba->outstanding_reqs); -spin_unlock_irqrestore (&hba->outstanding_lock, flags); +if (!ufshcd_clear_outstanding_reqs (hba,BIT (rq->tag))) +return SCSI_EH_DONE ; }if (ufshcd_is_scsi_cmd (scmd)) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1061/1257 scsi: ufs: core: Remove completed-without-interrupt path in ufshcd_abort()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit 7cfdfdd6557906fd09cf0a9a564a07012e7fb0c1 ]
In SDB mode, a command that times out right as the controller finishes it can be completed twice:
1. The command times out and scsi_timeout() schedules ufshcd_abort().
2. The controller finishes the command and clears its doorbell bit in REG_UTP_TRANSFER_REQ_DOOR_BELL, while the completion handler has not yet cleared BIT(tag) in hba->outstanding_reqs.
3. ufshcd_abort() sees the doorbell bit clear and calls __ufshcd_transfer_req_compl() without clearing BIT(tag) in hba->outstanding_reqs.
4. The normal completion handler or the logical unit reset that follows sees BIT(tag) still set in hba->outstanding_reqs and completes the same command a second time.
This branch only exists for a rare corner case, a completion interrupt that is lost or arrives late. Remove it to simplify the abort path and leave such a command to the SCSI error handler, like any other command that cannot be aborted. The cost is a slower recovery in this corner case, which is acceptable since it only happens after a timeout.
--- drivers/ufs/core/ufshcd.c | 9 --------- 1 file changed, 9 deletions(-)
drivers/ufs/core/ufshcd.c +0 -9
@@ -8129,15 +8129,6 @@ static int ufshcd_abort(struct scsi_cmnd *cmd) } hba->req_abort_count++; -if (!hba->mcq_enabled && !(reg & (1 << tag))) { -/* only execute this code in single doorbell mode */ -dev_err (hba->dev, -"%s: cmd was completed, but without a notifying intr, tag = %d" , - __func__, tag); -__ufshcd_transfer_req_compl (hba,1UL << tag); - goto release; - } -/* * Task abort to the device W-LUN is illegal. When this command * will fail, due to spec violation, scsi err handling next step
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1062/1257 scsi: ufs: core: Do not release a reserved request in ufshcd_abort()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanley Jhu <[email protected]>
[ Upstream commit eb2c4847a1cb2f426cfc702364df7a38ebbf730b ]
In SDB mode, aborting a timed-out device management request drops a clock hold that the request never took:
1. ufshcd_dev_man_lock() takes one ufshcd_hold() for the whole device management command. ufshcd_queue_reserved_command() submits the request without taking a hold of its own.
2. The request times out and ufshcd_abort() clears its slot with
ufshcd_clear_cmd().
3. ufshcd_abort() claims BIT(tag) in hba->outstanding_reqs and calls ufshcd_release_scsi_cmd(), which calls ufshcd_release() for a hold the request never took.
4. When ufshcd_dev_man_unlock() drops the hold from step 1,
hba->clk_gating.active_reqs goes below zero.
Release the command only if it is a SCSI command.
--- drivers/ufs/core/ufshcd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/ufs/core/ufshcd.c +2 -1
@@ -8175,7 +8175,8 @@ static int ufshcd_abort(struct scsi_cmnd *cmd)* Clear the corresponding bit from outstanding_reqs since the command * has been aborted successfully. */ -if (ufshcd_clear_outstanding_reqs (hba,BIT (tag))) +if (ufshcd_clear_outstanding_reqs (hba,BIT (tag)) && +ufshcd_is_scsi_cmd (cmd))ufshcd_release_scsi_cmd (hba, cmd); err =SUCCESS ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1063/1257 compat: avoid double rounding in times()
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 6b30c39a5e333cfb1475acf0f73de6ef954eea8a ]
do_sys_times() already converts CPU time to USER_HZ ticks. The compat path converts each value back to jiffies before converting it to COMPAT_USER_HZ. This round trip can lose precision even when the two userspace rates match.
With HZ=250 and USER_HZ=COMPAT_USER_HZ=100, one user tick becomes two jiffies and then zero compat ticks. Every odd tick count loses one tick, so any of the four tms fields can underreport CPU time by an additional 10 ms.
Return the value directly when the native and compat units match. Keep the existing conversion for differing rates.
--- kernel/sys.c | 3 +++ 1 file changed, 3 insertions(+)
kernel/sys.c +3 -0
@@ -1077,6 +1077,9 @@ SYSCALL_DEFINE1(times, struct tms __user *, tbuf)#ifdef CONFIG_COMPAT static compat_clock_t clock_t_to_compat_clock_t (clock_t x) { +if (USER_HZ ==COMPAT_USER_HZ ) +return x; +return compat_jiffies_to_clock_t (clock_t_to_jiffies (x)); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1064/1257 stackdepot: stop preallocating after the final pool
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Caleb Kan <[email protected]>
[ Upstream commit 8f56ea8e0706d92774603260779c7032f03ef3ac ]
depot_init_pool() decides whether another pool is needed before it increments pools_num. When it registers the last allowed pool, pools_num is still one below stack_max_pools, so the existing comparison clears new_pool.
With new_pool cleared, stack_depot_save_flags() can allocate another order-2 pool after a lookup miss. depot_keep_new_pool() retains its pointer in the global new_pool, so the allocation is not lost. However, pools_num has already reached stack_max_pools, and depot_init_pool() rejects every attempt to register the pool. It remains allocated and unusable until reboot. The non-NULL pointer prevents later saves from allocating more spare pools.
Account for the pool being registered in the limit check so registering the final pool installs STACK_DEPOT_POISON and prevents the extra allocation.
--- lib/stackdepot.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
lib/stackdepot.c +1 -1
@@ -323,7 +323,7 @@ static bool depot_init_pool(void **prealloc)* NULL; do not reset to NULL if we have reached the maximum number of * pools. */ -if (pools_num < stack_max_pools) +if (pools_num +1 < stack_max_pools)WRITE_ONCE (new_pool,NULL );else WRITE_ONCE (new_pool,STACK_DEPOT_POISON );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1065/1257 ocfs2: snapshot the dentry name while tracing file release
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit 5898987d4a92b70ae73fd8355cc3a388b4dfa4e6 ]
ocfs2_file_release() passes the live dentry name and length to a trace event while holding oi->ip_lock. This lock protects the open count and delays RCU reclamation of external names, but it does not serialize name changes during rename. The dentry can switch between inline and external names, and a separately loaded length can describe a different name.
The ocfs2__file_ops event sizes and copies its __string separately. A concurrently rewritten inline name need not remain consistent between those operations. External names can also be selected at this call site; the existing spinlock critical section protects their allocation lifetime, while a snapshot additionally pairs a stable name with its length.
Take a name snapshot before acquiring oi->ip_lock and release it after dropping the lock. Keep the trace call and open-count argument inside the original critical section. Cache the event-enabled check so the snapshot stays paired even if tracing is toggled meanwhile.
--- fs/ocfs2/file.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-)
fs/ocfs2/file.c +13 -5
@@ -141,18 +141,26 @@ static int ocfs2_file_open(struct inode *inode, struct file *file)static int ocfs2_file_release (struct inode *inode,struct file *file) {struct ocfs2_inode_info *oi =OCFS2_I (inode); +struct dentry *dentry = file->f_path.dentry; +struct name_snapshot name; +bool trace_enabled =trace_ocfs2_file_release_enabled (); + +if (trace_enabled) +take_dentry_name_snapshot (&name, dentry);spin_lock (&oi->ip_lock);if (!--oi->ip_open_count) oi->ip_flags &= ~OCFS2_INODE_OPEN_DIRECT ; -trace_ocfs2_file_release (inode, file, file->f_path.dentry, - oi->ip_blkno, - file->f_path.dentry->d_name.len, - file->f_path.dentry->d_name.name, - oi->ip_open_count); +if (trace_enabled) +trace_ocfs2_file_release (inode, file, dentry, + oi->ip_blkno, name.name.len, + name.name.name, oi->ip_open_count);spin_unlock (&oi->ip_lock); +if (trace_enabled) +release_dentry_name_snapshot (&name); +ocfs2_free_file_private (inode, file);return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1066/1257 ocfs2/cluster: remove zero-address nodes from IP tree on teardown
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit 5dd57e77eff4ba3e85b3df126a55417c88245708 ]
o2nm_node_ipv4_address_store() accepts 0.0.0.0. It sets O2NM_NODE_ATTR_ADDRESS and links nd_ip_node into cl_node_ip_tree under cl_nodes_lock, but o2nm_node_group_drop_item() uses nd_ipv4_address as a membership test. A zero address therefore leaves the rbtree node linked when config_item_put() releases and frees struct o2nm_node. A later address store or IP lookup can then walk the stale node and dereference freed memory.
During teardown, drop_item takes cl_nodes_lock, skips rb_erase() for the zero key, and then calls config_item_put(). A later o2nm_node_ipv4_address_store() duplicate check or o2nm_get_node_by_ip() lookup takes the same lock and walks the stale cl_node_ip_tree entry. Use O2NM_NODE_ATTR_ADDRESS for teardown so every published nd_ip_node is erased before configfs can release the node, without rejecting 0.0.0.0 or changing lookup semantics.
--- fs/ocfs2/cluster/nodemanager.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
fs/ocfs2/cluster/nodemanager.c +5 -2
@@ -627,8 +627,11 @@ static void o2nm_node_group_drop_item(struct config_group *group,write_lock (&cluster->cl_nodes_lock); -/* XXX sloppy */ -if (node->nd_ipv4_address) +/* +* 0.0.0.0 is a valid configured address, so nd_ipv4_address does +* not tell us whether nd_ip_node was published in the IP tree. +*/ +if (test_bit (O2NM_NODE_ATTR_ADDRESS , &node->nd_set_attributes))rb_erase (&node->nd_ip_node, &cluster->cl_node_ip_tree);/* nd_num might be 0 if the node number hasn't been set.. */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1067/1257 mm/vma: dont leak the commit charge on mmap failure
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 aa09311c40f6d3aa6037065e17d257ffa48b9402 ]
Patch series "mm: various (urgent?) fixes", v1.
Here are various MM fixes. The majority was reported by Josef at Anthrophic, the remainder was found while reviewing/overhauling them.
Two issues/fixes reported are not included, as we are discussing (better) alternatives on the list already.
I left most of the original commit messages as schloppy as they are: I don't particularly care as long as the code is in good shape and as long as they are not actively wrong. But I (and Mike) could not be stopped from overhauling at least some of them.
While I don't think there is anything too critical in here, I think this is a good opportunity to see how fast we can get pre-screened/pre-reviewed fixes upstream that might be security-related.
The majority are hugetlb + uffd issues, that are not actually that relevant for most installations. But all things that should just get fixed. Some uffd fixes need proper follow ups to fix some more of the root causes of leftover UFFD PTE bits (or proof that there are none remaining).
This patch (of 10):
When an accountable mapping replaces existing mappings (MAP_FIXED), __mmap_setup() only charges the difference between the size of the new mapping and the VM_ACCOUNT pages it replaces. It then zeroes vms->nr_accounted so that unmapping the old VMAs does not return their charge, which now backs the new mapping.
If the operation fails after that point, the error path returns map->charged, i.e. only the difference. By then vms_clean_up_area() has zapped the page tables and closed the old VMAs, so vms_abort_munmap_vmas() cannot reattach them. It leaves a gap and finishes the unmap with vms_complete_munmap_vmas(), which uncharges vms->nr_accounted == 0 pages. The old VMAs are gone, the new one was never created, and the charge of the old ones is never returned, not even when the process exits.
No privilege is needed to hit this, only a file whose mmap hook fails, for example a socket (sock_no_mmap() returns -ENODEV):
p = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); mmap(p, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, socket_fd, 0);
Every iteration adds len to Committed_AS for good. With vm.overcommit_memory=2 this lets any user make all further accountable allocations in the system fail with -ENOMEM.
Once the new mapping has taken over the charge of the mappings it replaces, it owns the charge for all of its pages. Record that in map->charged, so that the error path returns all of it.
A failure in __mmap_setup() itself is not affected: it happens before the charge is taken over and the old VMAs are reattached with their charge intact.
Original fix generated by an LLM and sent in private by Josef.
--- mm/vma.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
mm/vma.c +7 -4
@@ -2577,14 +2577,17 @@ static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc,/* Private writable mapping: check memory availability. */ if (accountable_mapping (map)) { - map->charged = map->pglen; - map->charged -= vms->nr_accounted; -if (map->charged) { - error =security_vm_enough_memory_mm (map->mm, map->charged); +const unsigned long uncharged = map->pglen - vms->nr_accounted; + +/* Charge only what's not already charged by mappings we replace. */ +if (uncharged) { + error =security_vm_enough_memory_mm (map->mm, uncharged);if (error)return error; } +/* Our new mapping owns the entire charge now. */ + map->charged = map->pglen; vms->nr_accounted =0 ;vma_flags_set (&map->vma_flags,VMA_ACCOUNT_BIT ); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1068/1257 mm/hugetlb: unmap the page where the other VMA maps it
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 ae99c503eb362b42cd5d24d80bc6cba669acc4c2 ]
If the owner of a MAP_PRIVATE hugetlb mapping fails to allocate a page for CoW, unmap_ref_private() unmaps the old page from all other private VMAs that have no reservation of their own. It finds them by the offset in the file, but then zaps each of them at the address of the faulting VMA. Nothing says that another VMA maps the offset at that address: a child can have moved its copy of the VMA with mremap(), and a second mapping of the file is wherever mmap() has put it.
So __unmap_hugepage_range() walks the page tables of the other mm at an address outside of iter_vma, where i_mmap_rwsem of this file protects nothing and where anything can be mapped, and the page stays mapped where it really is.
All of the following was seen on v7.3-rc6+ (g6c377d19d4a5) in KVM guests, as a user without any privilege. It takes a pool of 2 MiB pages with no free page that is not reserved, so that the allocation fails: the user can take or reserve what is free itself.
- The child moves its VMA away. The page is never unmapped, the mapcount stays 2, and the owner goes round retry_avoidcopy in hugetlb_wp() until the child is gone or a page becomes free. SIGKILL to the owner does not end it. 5 of 5 runs.
- The owner's mm has a second private mapping of the offset, made with MAP_NORESERVE. The owner zaps its own entry and reads zeroes where its data was. 5 of 5 runs.
- The child moves its VMA away and maps a 1 GiB hugetlb page at the old address, so this one takes a pool with a 1 GiB page as well. huge_pte_offset() for the 2 MiB size steps through the PUD leaf, so the "PMD table" is the 1 GiB page itself and its "page table lock" is folio->private of that page, which holds 2. Kernels with lock debugging oops in __unmap_hugepage_range(), 7 of 7 runs. Others spin on that word for ever with preemption disabled, 5 of 5 runs:
watchdog: BUG: soft lockup - CPU#0 stuck for 26s! [u_det3:130]
RIP: 0010:queued_spin_lock_slowpath+0x8a/0x290
RAX: 0000000000000002 RBX: ffffea0001000028
Call Trace:
__unmap_hugepage_range+0x154/0x6d0
unmap_hugepage_range+0xc1/0x140
hugetlb_wp+0x55c/0x700
hugetlb_fault+0x5f3/0x8f0RCU stalls follow, and killing all tasks of the user changes nothing. Four such owners, whose children share a single 1 GiB page, took down the whole guest with its four CPUs, 2 of 2 runs: one reported soft lockups on all four, the other gave no sign of life any more.
i_mmap_rwsem stays write locked. With a MAP_PRIVATE mapping of a hugetlbfs file that belongs to another user, and that the attacker can only read, the next mmap() of that file by its owner sleeps uninterruptibly in __mmap_region(), 4 of 4 runs.
Compute the address from the offset for each VMA. The tree walk returns only VMAs that cover pgoff, and vm_start, vm_end and vm_pgoff of a hugetlb VMA are aligned to the huge page size, as pgoff is, so the whole range lies inside iter_vma. Its page tables can not go away there, since the VMA is unlinked from the file under i_mmap_rwsem first.
With the right address the page is unmapped from all VMAs but the owner's, so the retry in hugetlb_wp() finds a mapcount of 1 and reuses the page.
A child that has moved its copy of the VMA now loses the page, and gets SIGBUS when it faults on a missing page of that VMA. That is what the comment above the function has always promised to those who do not own the reservation, and what already happens to a child that has left the VMA in place.
The address has been wrong from the start, and the second case needs only mmap() and fork(). mremap() of hugetlb VMAs, which the other cases use, came with commit 550a7d60bd5e ("mm, hugepages: add mremap() support for hugepage backed vma") in v5.16.
Original fix generated by an LLM and sent in private by Josef.
--- mm/hugetlb.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-)
mm/hugetlb.c +13 -4
@@ -5446,6 +5446,8 @@ static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,struct address_space *mapping;pgoff_t pgoff; +VM_WARN_ON_ONCE (!folio_test_anon (folio)); +/* * vm_pgoff is in PAGE_SIZE units, hence the different calculation * from page cache lookup which is in HPAGE_SIZE units.
@@ -5480,10 +5482,17 @@ static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,* could insert a zeroed page instead of the data existing * from the time of fork. This would look like data corruption */ -if (!is_vma_resv_set (iter_vma,HPAGE_RESV_OWNER )) -unmap_hugepage_range (iter_vma, address, - address +huge_page_size (h), - folio,0 ); +if (is_vma_resv_set (iter_vma,HPAGE_RESV_OWNER )) +continue ; + +/* +* The address in other VMAs can differ. Even though our old +* folio is anon, we always operate on the underlying hugetlb +* file. +*/ + address =vma_filebacked_address (iter_vma, pgoff,1 ); +unmap_hugepage_range (iter_vma, address, + address +huge_page_size (h), folio,0 ); }i_mmap_unlock_write (mapping); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1069/1257 mm/hugetlb: dont clear the resv_map of a VMA whose lock is held
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 d42032c0fe3ca007986c1229128775af0340fbec ]
Since commit bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs") the lock of a private hugetlb VMA that owns a reservation is the rw_sema of its resv_map. The hugetlb_vma_*lock*() helpers find it through vma->vm_private_data, anew for every lock and every unlock.
At the end of mremap() the old VMA has to let go of the resv_map, which now belongs to the new VMA: clear_vma_resv_huge_pages() stores NULL into vm_private_data. mremap() holds mmap_lock for writing and has write locked the VMA, which keeps away everybody who comes through the mm. It does not keep away those who find the VMA through the file. For hole punch and truncation hugetlb_vmdelete_list() does
hugetlb_vma_trylock_write(vma); locks resv_map->rw_sema unmap_hugepage_range(vma, ...); vm_private_data = NULL hugetlb_vma_unlock_write(vma); no resv_map: does nothing
and the rw_sema stays write locked for ever:
WARNING: lock held when returning to user space! mremap_punch/116 is leaving the kernel with locks still held! locks held by mremap_punch/116: 1, last CPU#1:
#0: (&resv_map->rw_sema){+.+.}-{4:4}, at:
hugetlb_vmdelete_list+0x46/0x160
The next fault in the new VMA sleeps in hugetlb_vma_lock_read(), uninterruptibly, and it holds its entry of hugetlb_fault_mutex_table[]. That table is global, so a fault of any other process on a page that hashes to the same entry sleeps uninterruptibly as well.
All those who take the lock of a private VMA without taking the mmap/vma lock are affected: rmap walks. So hold i_mmap_rwsem around the clearing of the resv_map.
No change of behaviour, other than that mremap() of a hugetlb VMA takes i_mmap_rwsem once more.
Original fix generated by an LLM and sent in private by Josef.
--- mm/hugetlb.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-)
mm/hugetlb.c +11 -2
@@ -7473,6 +7473,15 @@ void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)*/ void fixup_hugetlb_reservations (struct vm_area_struct *vma) { -if (is_vm_hugetlb_page (vma)) -clear_vma_resv_huge_pages (vma); +if (!is_vm_hugetlb_page (vma)) +return ; + +/* +* Rmap walks might still find this VMA and take the lock +* inside the reservation map for __vma_private_lock(). Don't clear +* the reservation map while that is possible. +*/ +i_mmap_lock_write (vma->vm_file->f_mapping); +clear_vma_resv_huge_pages (vma); +i_mmap_unlock_write (vma->vm_file->f_mapping); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1070/1257 mm/hugetlb: fix endless write fault on a leftover uffd bit
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 f61e1cf15fb44f9cf89d43d8ef01f926322bb1c4 ]
hugetlb_fault() resolves the uffd bit on a write fault only if the VMA is registered for userfaultfd write protection, and hugetlb_wp() bails out for any entry with the uffd bit set assuming hugetlb_fault() has already resolved it.
When a read-only hugetlb entry with the uffd bit set is mapped in a VMA that is not registered for uffd-wp, a write fault to it never makes progress. If the access comes from the kernel, e.g. read(2) from /dev/zero into such page, the task spins in the page fault handler, ignores SIGKILL and keeps holding the locks taken by the system call.
Such entries should not exist, but an unprivileged user can create them, for example with MADV_DONTNEED of a page protected with UFFDIO_RWPROTECT or with UFFDIO_COPY in MODE_WP racing with UFFDIO_UNREGISTER.
Clear the uffd bit when the VMA is not registered for uffd-wp and let the fault proceed to hugetlb_wp(), like do_wp_page() does for regular pages.
Note that a FOLL_FORCE write to a page protected with UFFDIO_RWPROTECT in a private VMA that was made PROT_NONE now drops the RWP protection of that page.
Original fix generated by an LLM and sent in private by Josef.
--- mm/hugetlb.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
mm/hugetlb.c +6 -2
@@ -6190,15 +6190,19 @@ vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma, goto out_ptl;/* Handle userfault-wp first, before trying to lock more pages */ -if (userfaultfd_wp (vma) &&huge_pte_uffd (huge_ptep_get (mm, vmf.address, vmf.pte)) && +if (huge_pte_uffd (huge_ptep_get (mm, vmf.address, vmf.pte)) && (flags &FAULT_FLAG_WRITE ) && !huge_pte_write (vmf.orig_pte)) { -if (!userfaultfd_wp_async (vma)) { +if (userfaultfd_wp (vma) && !userfaultfd_wp_async (vma)) {spin_unlock (vmf.ptl);hugetlb_vma_unlock_read (vma);mutex_unlock (&hugetlb_fault_mutex_table[hash]);return handle_userfault (&vmf,VM_UFFD_WP ); } +/* +* TODO: fix all cases where uffd PTE bits remain in VMAs that +* are no longer registered with uffd. +*/ vmf.orig_pte =huge_pte_clear_uffd (vmf.orig_pte);set_huge_pte_at (mm, vmf.address, vmf.pte, vmf.orig_pte,huge_page_size (hstate_vma (vma)));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1071/1257 mm/hugetlb: tolerate uffd bits set without uffd for PROT_NONE 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 811777d82038d4fd3f5d3bf986f682df463b6f21 ]
The whole uffd handling when a VMA is unregistered from UFFD is shaky:
there are still some scenarios where we might have stale uffd PTE bits in VMAs no longer registered for UFFD, which confuses other code.
Let's just tolerate that for now and simply clear the PTE bit. Add a TODO to really clean up any uffd leftovers when unregistering a VMA from userfaultfd.
The handling is now more similar to what we have in handle_pte_fault().
--- mm/hugetlb.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
mm/hugetlb.c +6 -2
@@ -6133,16 +6133,20 @@ vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,* NUMA hinting), so let normal hugetlb fault handling proceed. */ if (pte_protnone (vmf.orig_pte) &&vma_is_accessible (vma) && -userfaultfd_rwp (vma) &&huge_pte_uffd (vmf.orig_pte)) { +huge_pte_uffd (vmf.orig_pte)) {spinlock_t *ptl;pte_t pte;/* Sync: drop hugetlb locks before blocking in handle_userfault() */ -if (!userfaultfd_rwp_async (vma)) +if (userfaultfd_rwp (vma) && !userfaultfd_rwp_async (vma))return hugetlb_handle_userfault (&vmf, mapping,VM_UFFD_RWP ); ptl =huge_pte_lock (h, mm, vmf.pte); pte =huge_ptep_get (mm, vmf.address, vmf.pte); +/* +* TODO: fix all cases where uffd PTE bits remain in VMAs that +* are no longer registered with uffd. +*/ if (pte_protnone (pte) &&huge_pte_uffd (pte)) {unsigned int shift =huge_page_shift (h);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1072/1257 mm/hugetlb: tolerate UFFD_WP markers outside uffd-wp VMAs
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 c37e9d9411a12240a60ca3796d3cbb496e6258a2 ]
UFFD PTE bit handling is a bit like swiss cheese, in particular with recently added RWP mode. Having uffd-wp markers outside uffd-wp VMAs already confused this code in the past and resulted in uffd-pte bits confusing other code later.
Let's play safe and just ignore these markers in hugetlb_no_page(), not silently propagating the uffd-wp PTE bit.
--- mm/hugetlb.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
mm/hugetlb.c +4 -1
@@ -5945,8 +5945,11 @@ static vm_fault_t hugetlb_no_page(struct address_space *mapping,/* * If this pte was previously wr-protected, keep it wr-protected even * if populated. +* +* TODO: fix all cases where uffd-wp markers remain in VMAs that are no +* longer registered with uffd. */ -if (unlikely (pte_is_uffd_wp_marker (vmf->orig_pte))) +if (unlikely (userfaultfd_wp (vma) &&pte_is_uffd_wp_marker (vmf->orig_pte))) new_pte =huge_pte_mkuffd (new_pte);set_huge_pte_at (mm, vmf->address, vmf->pte, new_pte,huge_page_size (h));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1073/1257 mm/hugetlb: dont leave a uffd-wp marker when zapping an RWP entry
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 f6605fc6b14bd5fc0fea90fc8226573adcec352b ]
An entry that is protected with UFFDIO_RWPROTECT is PAGE_NONE with the uffd bit set, the bit that userfaultfd write protection uses too. When __unmap_hugepage_range() zaps an entry with that bit it leaves a PTE_MARKER_UFFD_WP behind, whatever the VMA is registered for.
In a VMA registered with UFFDIO_REGISTER_MODE_RWP that marker means nothing. The next fault has hugetlb_no_page() turn it into a present, read-only entry with the uffd bit. That is not an RWP entry, since it is not PAGE_NONE, and the VMA has no VM_UFFD_WP (the two modes can not be registered together). An earlier fix solved some side effects, now just stop the zap from wrongly installing a marker.
Leave a marker only if the VMA is registered for write protection, both for present and for non-present entries. The zap of ordinary page tables has the same test, in cond_install_uffd_wp_ptes(), and hugetlb_change_protection() says that "uffd_rwp does not install markers".
After a zap the range of an RWP VMA is simply empty, as it is for anonymous memory and shmem. Nothing changes for VMAs with VM_UFFD_WP. In a VMA that is not registered at all a leftover uffd bit or marker is now dropped by the zap and no longer kept alive.
Original fix generated by an LLM and sent in private by Josef.
--- mm/hugetlb.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
mm/hugetlb.c +2 -2
@@ -5273,7 +5273,7 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,* drop the uffd-wp bit in this zap, then replace the * pte with a marker. */ -if (pte_swp_uffd_any (pte) && +if (userfaultfd_wp (vma) &&pte_swp_uffd_any (pte) && !(zap_flags &ZAP_FLAG_DROP_MARKER )) set_huge_pte_at(mm, address, ptep, make_pte_marker(PTE_MARKER_UFFD_WP),
@@ -5309,7 +5309,7 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,if (huge_pte_dirty (pte))folio_mark_dirty (folio);/* Leave a uffd-wp pte marker if needed */ -if (huge_pte_uffd (pte) && +if (userfaultfd_wp (vma) &&huge_pte_uffd (pte) && !(zap_flags &ZAP_FLAG_DROP_MARKER )) set_huge_pte_at(mm, address, ptep, make_pte_marker(PTE_MARKER_UFFD_WP),
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1074/1257 mm/mremap: fix calling fixup_hugetlb_reservations() on the wrong 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 cc078ca0b5b79b4a9e514b7f1b489f2afc83b195 ]
In case we fail to move the page tables, for example, because we fail to allocate a page table, we actually keep the old VMA.
Calling fixup_hugetlb_reservations() on the old VMA is wrong. Fix it by just calling it on the VMA that will be removed.
The user-visible impact is that the VMA loses its reservations, meaning that the existing reservations get stranded (leaked) and new hugetlb folios that are getting allocated in the VMA cannot make use of the reservations, failing these allocations.
--- mm/mremap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/mremap.c +1 -1
@@ -1345,7 +1345,7 @@ static int copy_vma_and_data(struct vma_remap_struct *vrm,mremap_userfaultfd_prep (new_vma, vrm->uf); } -fixup_hugetlb_reservations (vma); +fixup_hugetlb_reservations (vrm->vma); *new_vma_ptr = new_vma;return err;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1075/1257 mm/hugetlb: account migration target folio in per-node NR_HUGETLB vmstat
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hongfu Li <[email protected]>
[ Upstream commit 92635a3ffe8bb48304f50625dd591a27d7505698 ]
Patch series "mm: fix hugetlb NR_HUGETLB accounting on folio migration", v2.
The hugeTLB counters added by 05d4532b60e3 ("memcg/hugetlb: add hugeTLB counters to memcg") are maintained in two per-node places:
- the per-node vmstat counter NR_HUGETLB, exposed as nr_hugetlb in
/proc/vmstat;
- the per-node memcg lruvec stat, exposed via memory.numa_stat.
Both are accounted against the folio's node, and both drift when a hugetlb folio is migrated, though in different ways.
A migration target folio is allocated by alloc_hugetlb_folio_nodemask() and inherits the old folio's state without ever being accounted, while the old folio is freed right after and its free is accounted. That alone loses vmstat accounting: the target node has no matching increment for the decrement on the old node, so /proc/vmstat's nr_hugetlb shrinks by nr_pages per migration. Patch 1 accounts the folio where it is obtained, so the increment pairs with the free in free_huge_folio() on the successful as well as the failed migration path. The memfd page cache preallocation helper has the same asymmetry and is fixed in the same patch.
The per-node lruvec stat breaks differently. mem_cgroup_migrate() moves the charge to the new folio and drops the old folio's memcg data, so the old folio's free right after migration skips the memcg per-node decrement; the count stays attributed to the old node for the rest of the charge's life, and the target folio never gets an increment on its new node. Patch 2 moves that per-node accounting along with the charge, in move_hugetlb_state().
This patch (of 2):
The NR_HUGETLB vmstat counter is maintained per folio's node: incremented when a huge page is handed to a user via hugetlb_alloc_folio() and decremented when it is returned to the pool via free_huge_folio().
A folio obtained by alloc_hugetlb_folio_nodemask() never goes through hugetlb_alloc_folio(), so it is never accounted, while its free always is. For a migration target this means the target node gets no matching increment for the decrement on the old node, so the global nr_hugetlb in /proc/vmstat drops by nr_pages for each migration. The same asymmetry affects the failed migration path, which frees the target again right away, and the temporary folio hugetlb_mfill_atomic_pte() takes from the same helper.
alloc_hugetlb_folio_reserve(), used to preallocate the memfd page cache folios, has the same asymmetry: the folio is handed to a user without being accounted, while its free is accounted through free_huge_folio().
Account the folio where it is obtained, in alloc_hugetlb_folio_nodemask() and alloc_hugetlb_folio_reserve(), so that the increment pairs with the decrement in free_huge_folio(): a successful migration hands the folio to a user, a failed one frees it again.
--- mm/hugetlb.c | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-)
mm/hugetlb.c +23 -12
@@ -2191,6 +2191,11 @@ struct folio *alloc_hugetlb_folio_reserve(struct hstate *h, int preferred_nid, h->resv_huge_pages--;spin_unlock_irq (&hugetlb_lock); + +if (folio) +lruvec_stat_mod_folio (folio,NR_HUGETLB , +folio_nr_pages (folio)); +return folio; }
@@ -2198,24 +2203,30 @@ struct folio *alloc_hugetlb_folio_reserve(struct hstate *h, int preferred_nid,struct folio *alloc_hugetlb_folio_nodemask (struct hstate *h,int preferred_nid,nodemask_t *nmask,gfp_t gfp_mask,bool allow_alloc_fallback) { -spin_lock_irq (&hugetlb_lock); -if (available_huge_pages (h)) { -struct folio *folio; +struct folio *folio =NULL ; +spin_lock_irq (&hugetlb_lock); +if (available_huge_pages (h)) folio =dequeue_hugetlb_folio_nodemask (h, gfp_mask, preferred_nid, nmask); -if (folio) { -spin_unlock_irq (&hugetlb_lock); -return folio; - } - }spin_unlock_irq (&hugetlb_lock); -/* We cannot fallback to other nodes, as we could break the per-node pool. */ -if (!allow_alloc_fallback) - gfp_mask |= __GFP_THISNODE; +if (!folio) { +/* +* We cannot fallback to other nodes, as we could break the +* per-node pool. +*/ +if (!allow_alloc_fallback) + gfp_mask |= __GFP_THISNODE; -return alloc_migrate_hugetlb_folio (h, gfp_mask, preferred_nid, nmask); + folio =alloc_migrate_hugetlb_folio (h, gfp_mask, preferred_nid, + nmask); + } + +if (folio) +lruvec_stat_mod_folio (folio,NR_HUGETLB ,folio_nr_pages (folio)); + +return folio; }static nodemask_t *policy_mbind_nodemask (gfp_t gfp)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1076/1257 mm/memcg: migrate per-node hugetlb lruvec stat together with hugetlb folio
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hongfu Li <[email protected]>
[ Upstream commit 02e0c8cc2815f0082b5b5aabafe3b46688082adc ]
memory.numa_stat exposes per-node hugetlb counters from per-node lruvec stats. These stats are accounted against folio_nid(): incremented on the folio's node when handed to a user, decremented when the folio is returned to the pool.
During hugetlb folio migration, mem_cgroup_migrate() moves the charge to the new folio and drops the memcg data of the old one, so the free of the old folio right after the migration skips the memcg per-node lruvec decrement. The hugetlb count stays attributed to the old node for the rest of the life of the charge, while the target folio gets no increment on the new node; its later free decrements a counter that was never incremented.
Migrate the per-node lruvec accounting alongside migration. Global memcg totals remain balanced because they track resource consumption, not node placement.
--- include/linux/memcontrol.h | 8 ++++++++ mm/hugetlb.c | 25 +++++++++++++++++++++++++ mm/memcontrol.c | 5 ++--- 3 files changed, 35 insertions(+), 3 deletions(-)
include/linux/memcontrol.h +8 -0
@@ -958,6 +958,9 @@ unsigned long lruvec_page_state_monotonic(struct lruvec *lruvec,unsigned long lruvec_page_state_local (struct lruvec *lruvec,enum node_stat_item idx); +void mod_memcg_lruvec_state (struct lruvec *lruvec, +enum node_stat_item idx,int val); +void mem_cgroup_flush_stats (struct mem_cgroup *memcg);void mem_cgroup_flush_stats_ratelimited (struct mem_cgroup *memcg);
@@ -1420,6 +1423,11 @@ static inline unsigned long lruvec_page_state_local(struct lruvec *lruvec,return node_page_state (lruvec_pgdat (lruvec), idx); } +static inline void mod_memcg_lruvec_state (struct lruvec *lruvec, +enum node_stat_item idx,int val) +{ +} +static inline void mem_cgroup_flush_stats (struct mem_cgroup *memcg) { }
mm/hugetlb.c +25 -0
@@ -23,6 +23,7 @@#include <linux/mmdebug.h> #include <linux/sched/signal.h> #include <linux/rmap.h> +#include <linux/rcupdate.h> #include <linux/string_choices.h> #include <linux/string_helpers.h> #include <linux/swap.h>
@@ -7360,12 +7361,36 @@ void folio_putback_hugetlb(struct folio *folio)folio_put (folio); } +static void move_hugetlb_lruvec_stat (struct folio *old_folio, +struct folio *new_folio) +{ +struct mem_cgroup *memcg; +long nr_pages =folio_nr_pages (old_folio); +int old_nid =folio_nid (old_folio); +int new_nid =folio_nid (new_folio); + +if (old_nid == new_nid) +return ; + +guard (rcu)(); + + memcg =folio_memcg (new_folio); +if (!memcg) +return ; + +mod_memcg_lruvec_state (mem_cgroup_lruvec (memcg,NODE_DATA (old_nid)), +NR_HUGETLB , -nr_pages); +mod_memcg_lruvec_state (mem_cgroup_lruvec (memcg,NODE_DATA (new_nid)), +NR_HUGETLB , nr_pages); +} +void move_hugetlb_state (struct folio *old_folio,struct folio *new_folio,enum migrate_reason reason) {struct hstate *h =folio_hstate (old_folio);hugetlb_cgroup_migrate (old_folio, new_folio); +move_hugetlb_lruvec_stat (old_folio, new_folio);folio_set_owner_migrate_reason (new_folio, reason);/*
mm/memcontrol.c +2 -3
@@ -987,9 +987,8 @@ static void __mod_memcg_lruvec_state(struct mem_cgroup_per_node *pn,put_cpu (); } -static void mod_memcg_lruvec_state (struct lruvec *lruvec, -enum node_stat_item idx, -int val) +void mod_memcg_lruvec_state (struct lruvec *lruvec, +enum node_stat_item idx,int val) {struct pglist_data *pgdat =lruvec_pgdat (lruvec);struct mem_cgroup_per_node *pn;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1077/1257 mm/damon/core: preserve the quota passed to damon_new_scheme()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
[ Upstream commit f73ecbc0589c8df8f18e444f5f633de01ebb0d98 ]
Patch series "mm/damon/core: preserve quota state when constructing schemes", v3.
damon_commit_ctx() first commits the running context's parameters to a temporary context for validating proposed updates. Constructing the temporary schemes clears the running schemes' quota state because damon_new_scheme() initializes the quota passed as a parameter before copying it to the new scheme. Even an update later rejected with -EINVAL loses the running quota state.
Initialize the new scheme's copy instead, and add KUnit tests for the constructor and for accepted and rejected context updates.
Note: below are test results and changelogs that could be removed from the final commit log.
In the v1 live test with damo, a scheme with a plain 64 KiB size quota and a 60-second reset interval uses its quota, and a full "damo tune" with unchanged parameters then lets it try another 64 KiB within the same window. With the fix, sz_tried stays at 64 KiB.
KUnit was rerun after the rebase on x86-64 and i386. With only patch 2 applied, the two new tests fail. With the fix, all 46 DAMON KUnit tests pass on both architectures.
The v1 DAMON selftests showed no new failures (QEMU TCG guest; the wss_estimation test missed its accuracy bounds with and without the fix).
This patch (of 2):
damon_commit_ctx() first commits the running context's parameters to a temporary context for validating proposed updates. When damon_commit_schemes() creates the temporary schemes, it passes the running scheme's quota as the quota parameter of damon_new_scheme().
damon_new_scheme() calls damos_quota_init() on that quota before copying it to the new scheme. This clears the running scheme's effective quota, feedback input and charging state. Even an update rejected with -EINVAL loses the running quota state.
For a size quota, this discards the bytes already charged and allows the scheme to use a fresh quota before the reset interval has elapsed. For a goal-driven quota, the consist tuner loses its accumulated input and restarts from its minimum input. A time quota loses its throughput estimate and falls back to the initial estimate.
The end users will show DAMOS works more or less aggressively than expected for online-commit updates of quotas. DAMON provides best efforts by default. DAMON parameters online commit is supposed to be executed only occasionally. Hence, the issue wouldn't be critical on sane setups. For user_input type quota goals, online commit of the user input score is expected to be frequent. But, for the case commit_schemes_quota_goals command is recommended for optimal execution, and it doesn't have this bug.
Commit 60bd24f272d0 ("mm/damon/sysfs: test commit input against realistic destination") introduced this problem in v6.19 when sysfs validation began committing the running context's parameters to a temporary context. Commit b90408ef1163 ("mm/damon/core: safely validate src on damon_commit_ctx()") later moved that validation into the core API, exposing other callers including DAMON_RECLAIM and DAMON_LRU_SORT.
Sashiko reported the same side effect [1] on the RFC of the core API change.
Copy the quota to the new scheme first, then initialize that copy. Make damos_quota_init() return void, since its return value is no longer needed.
only occasionally. Hence, the issue wouldn't be critical on sane setups. For user_input type quota goals, online commit of the user input score is expected to be frequent. But, for the case commit_schemes_quota_goals command is recommended for optimal execution, and it doesn't have this bug.
Commit 60bd24f272d0 ("mm/damon/sysfs: test commit input against realistic destination") introduced this problem in v6.19 when sysfs validation began committing the running context's parameters to a temporary context.
--- mm/damon/core.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
mm/damon/core.c +3 -3
@@ -668,7 +668,7 @@ static bool damos_quota_goals_empty(struct damos_quota *q) }/* initialize fields of @quota that normally API users wouldn't set */ -static struct damos_quota *damos_quota_init (struct damos_quota *quota) +static void damos_quota_init (struct damos_quota *quota) { quota->esz =0 ; quota->total_charged_sz =0 ;
@@ -678,7 +678,6 @@ static struct damos_quota *damos_quota_init(struct damos_quota *quota) quota->charge_target_from =NULL ; quota->charge_addr_from =0 ; quota->esz_bp =0 ; -return quota; } struct damos *damon_new_scheme(struct damos_access_pattern *pattern,
@@ -710,7 +709,8 @@ struct damos *damon_new_scheme(struct damos_access_pattern *pattern, scheme->last_applied =NULL ;INIT_LIST_HEAD (&scheme->list); - scheme->quota = *(damos_quota_init (quota)); + scheme->quota = *quota; +damos_quota_init (&scheme->quota);/* quota.goals should be separately set by caller */ INIT_LIST_HEAD (&scheme->quota.goals);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1078/1257 mm/damon/core: prevent size quota overflow in the temporal goal tuner
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Donggeun Yoo <[email protected]>
[ Upstream commit 4293c54b72e75a9d8d2e79b1498cbc782267a4db ]
Patch series "mm/damon: fix the temporal goal tuner's size quota conversion", v5.
damos_goal_tune_esz_bp_temporal() hands the size quota to damos_set_effective_quota() through quota->esz_bp in basis points, and the multiply that gets it there is unchecked. On 32-bit it wraps above 429496 bytes, and a wrapped product below 10000 divides to a zero effective quota. damos_quota_is_full() is then true on the first test of every charge window, so the scheme makes no progress for as long as the goal is unachieved.
Patch 1 bounds the conversion. Patch 2 pins the boundary in the core kunit suite, where the new test would fail without patch 1 on any word size.
This patch (of 2):
damos_goal_tune_esz_bp_temporal() converts the scheme's size quota into basis points with "quota->esz_bp = quota->sz * 10000", both unsigned long, and damos_set_effective_quota() divides the result back by 10000. quotas/bytes is unbounded; bytes_store() hands it to kstrtoul() as is.
On 32-bit the product wraps for any size quota above ULONG_MAX / 10000, that is 429496 bytes. A wrapped product below 10000 divides to a zero effective quota: 429497 gives 0. damos_quota_is_full() is then true on the first test of every charge window. Other wrapped values are wrong without being zero: 500000 gives 70503.
Triggering this needs a scheme with a quota goal, the temporal goal tuner, and a size quota above ULONG_MAX / 10000 -- 429496 bytes on 32-bit, 1844674407370955 on 64-bit. The scheme then makes no progress for as long as the goal is unachieved, which is easy to notice, and writing a smaller size quota restores it. Nothing is corrupted and nothing leaks. This is unlikely to be hit on a tested setup.
addr_unit does not cover this. It only scales the numbers a paddr context writes to quotas/bytes, so a large enough scaled value wraps just the same, and vaddr and fvaddr contexts take raw byte values.
Bound the multiply.
--- mm/damon/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/damon/core.c +1 -1
@@ -3148,7 +3148,7 @@ static void damos_goal_tune_esz_bp_temporal(struct damon_ctx *c,if (score >=10000 ) quota->esz_bp =0 ; -else if (quota->sz) +else if (quota->sz && quota->sz <=ULONG_MAX /10000 ) quota->esz_bp = quota->sz *10000 ;else quota->esz_bp =ULONG_MAX ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1079/1257 mm: disallow ioremaping ordinary RAM in generic_access_phys()
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 4590752e20aa393cc0d4fe538c0747d14a98c97a ]
generic_access_phys() can end up getting called on CoW PFNMAP mappings, resulting in it trying to ioremap anonymous folios, which especially the x86 code doesn't enjoy, and which is in general just odd/wrong.
E.g., with a CoW mapping of a PCI BAR:
ioremap on RAM at 0x0000000045623000 - 0x0000000045623fff
WARNING: arch/x86/mm/ioremap.c:216 at __ioremap_caller.isra.0+0x4c2/0x5f0 Call Trace: generic_access_phys+0x130/0x4d0 mm/memory.c:7178 kernfs_vma_access+0x1ce/0x280 fs/kernfs/file.c:437 __access_remote_vm+0x58f/0x890 mm/memory.c:7256 mem_rw+0x2a1/0x670 fs/proc/base.c:912
But more generically, we should disallow access to anything that looks like ordinary RAM in the system: including allocating memory (e.g., alloc_pages) and mapping them in a VM_PFNMAP.
For pages with an online memmap, allow only pages marked as reserved (PageReserved). This also includes memblock allocations, however, distinguishing them from other MMIO is tricky, and nobody should really be mapping them in a PFNMAP (except someone abusing /dev/mem, which we do not care about).
So only allow access if there is no online memmap, or if the pages are marked reserved. Reject other pages with -EINVAL.
Note that, just like other pfn_to_online_page() users, we won't care about concurrent memory offlining; mapping memory that can concurrently get offlined is highly dubious.
--- mm/memory.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
mm/memory.c +14 -0
@@ -7159,6 +7159,7 @@ int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,resource_size_t phys_addr;pgprot_t prot =__pgprot (0 );void __iomem *maddr; +struct page *page;int offset =offset_in_page (addr);int ret = -EINVAL ;bool writable;
@@ -7173,6 +7174,19 @@ int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, retry:if (follow_pfnmap_start (&args))return -EINVAL ; + +/* +* Reject anything that looks like ordinary RAM, including anonymous +* folios in CoW mappings or allocated kernel memory. Note that we +* cannot distinguish memblock allocations from non-RAM reliably, so +* we cannot easily reject them here. +*/ + page =pfn_to_online_page (args.pfn); +if (page && !PageReserved (page)) { +follow_pfnmap_end (&args); +return -EINVAL ; + } + prot = args.pgprot; phys_addr = (resource_size_t )args.pfn <<PAGE_SHIFT ; writable = args.writable;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1080/1257 mm/memfd: fix hugetlb reservation accounting in error paths
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hongfu Li <[email protected]>
[ Upstream commit 50ee565c1e900e247e439e4139839b060c968343 ]
If hugetlb_add_to_page_cache() in memfd_alloc_folio() fails with -EEXIST, a concurrent fault has already instantiated the folio in the page cache, and the reservation now belongs to that folio. Calling hugetlb_unreserve_pages() in that case incorrectly removes the region backing the cached folio and releases one reservation more than it should, leaving that folio in the page cache with no region recording it.
That leaves resv_huge_pages one page short until that folio is removed from the page cache, so available_huge_pages() reports a page that is not actually free and the pool can grant one reservation more than it can back. Applications using hugetlb memfds can then fail to allocate or fault in a page they already reserved. They see -ENOMEM or -ENOSPC from the allocation or fault path even though the reservation and HugePages_Free still look healthy.
So hold the hugetlb fault mutex from hugetlb_reserve_pages() until the error-path unreserve completes to make the reserve, allocate and instantiate steps atomic against concurrent faults. With the mutex held from the start, a concurrent fault can no longer consume the reservation between reserve and allocate/instantiate. If a fault completed before the mutex was taken, it has already added the region for that index, so hugetlb_reserve_pages() returns 0 and the error path leaves the region in place.
--- mm/memfd.c | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-)
mm/memfd.c +16 -15
@@ -82,22 +82,31 @@ struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx)struct hstate *h =hstate_file (memfd);int err = -ENOMEM ;long nr_resv; +u32 hash; gfp_mask =htlb_alloc_mask (h); gfp_mask &= ~(__GFP_HIGHMEM | __GFP_MOVABLE); idx >>=huge_page_order (h); +/* +* Serialize hugepage allocation and instantiation to prevent +* races with concurrent allocations, as required by all other +* callers of hugetlb_add_to_page_cache(). +*/ + hash =hugetlb_fault_mutex_hash (memfd->f_mapping, idx); +mutex_lock (&hugetlb_fault_mutex_table[hash]); + nr_resv =hugetlb_reserve_pages (inode, idx, idx +1 ,NULL ,EMPTY_VMA_FLAGS ); -if (nr_resv <0 ) -return ERR_PTR (nr_resv); +if (nr_resv <0 ) { + err = nr_resv; + goto out_unlock; + } folio =alloc_hugetlb_folio_reserve (h,numa_node_id (),NULL , gfp_mask);if (folio) { -u32 hash; -/* * Zero the folio to prevent information leaks to userspace. * Use folio_zero_user() which is optimized for huge/gigantic
@@ -112,20 +121,9 @@ struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx)*/ __folio_mark_uptodate (folio); -/* -* Serialize hugepage allocation and instantiation to prevent -* races with concurrent allocations, as required by all other -* callers of hugetlb_add_to_page_cache(). -*/ - hash =hugetlb_fault_mutex_hash (memfd->f_mapping, idx); -mutex_lock (&hugetlb_fault_mutex_table[hash]); - err =hugetlb_add_to_page_cache (folio, memfd->f_mapping, idx); - -mutex_unlock (&hugetlb_fault_mutex_table[hash]); -if (err) {folio_put (folio); goto err_unresv;
@@ -133,11 +131,14 @@ struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx)hugetlb_set_folio_subpool (folio,subpool_inode (inode));folio_unlock (folio); +mutex_unlock (&hugetlb_fault_mutex_table[hash]); return folio; } err_unresv:if (nr_resv >0 )hugetlb_unreserve_pages (inode, idx, idx +1 ,0 ); +out_unlock: +mutex_unlock (&hugetlb_fault_mutex_table[hash]);return ERR_PTR (err); }#endif
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1081/1257 mm/madvise: add cond_resched() in THP branch of madvise_cold_or_pageout_pte_range()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wei Yang <[email protected]>
[ Upstream commit f5cfc8e3b20ad71949a1e5623ff45882c063a71b ]
During stress testing with stress-ng on a 256-CPU system, a softlockup was observed when madvise(MADV_COLD) was called on a 31GB memory region backed by transparent hugepages. The region contains 15935 THP PMD entries, and the softlockup was triggered after 14485 of them had been processed.
The THP branch of madvise_cold_or_pageout_pte_range() has no scheduling point. walk_pmd_range() invokes it once per 2MB PMD entry with no cond_resched() anywhere in the loop. Each iteration calls pmdp_invalidate() which issues a synchronous TLB shootdown (dsb ish) waiting for all CPUs to acknowledge. This operation can be time-consuming under heavy system load, causing the accumulated time across all PMD entries to exceed the softlockup threshold (20s) and panic when softlockup_panic=1. On a CONFIG_PREEMPT_NONE=y kernel, there is no other opportunity to reschedule during this entire traversal.
The regular PTE path already has an unconditional cond_resched() at the function tail (introduced by commit 9c276cc65a58 ("mm: introduce MADV_COLD") and commit 1a4e58cce84e ("mm: introduce MADV_PAGEOUT") when MADV_COLD and MADV_PAGEOUT were first introduced) and a conditional one inside the loop (commit b2f557a21bc8 ("mm/madvise: add cond_resched() in madvise_cold_or_pageout_pte_range()")). The THP branch never received equivalent treatment.
Fix by adding cond_resched() at the huge_unlock exit path after spin_unlock(ptl) and reclaim_pages(), which is the single exit point for all goto paths in the THP branch.
Crash log:
watchdog: BUG: soft lockup - CPU#63 stuck for 23s! [stress-ng-vm:1665914] ... Call trace: pmdp_invalidate+0x48/0x68 madvise_cold_or_pageout_pte_range+0x84c/0xb00 walk_pmd_range.isra.0+0x1ac/0x3b0 walk_pud_range+0x120/0x190 walk_pgd_range+0x170/0x1b8 __walk_page_range+0x184/0x198 walk_page_range_vma+0x94/0x128 madvise_cold+0xd8/0x198 madvise_vma_behavior+0x234/0x638 madvise_walk_vmas.constprop.0+0xdc/0x210 madvise_do_behavior+0xa8/0x328 do_madvise+0xd8/0x140 __arm64_sys_madvise+0x2c/0xe0
--- mm/madvise.c | 1 + 1 file changed, 1 insertion(+)
mm/madvise.c +1 -0
@@ -453,6 +453,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,spin_unlock (ptl);if (pageout)reclaim_pages (&folio_list); +cond_resched ();return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1082/1257 mm: page_alloc: make defrag_mode retries follow the promoted order
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 4cd78a2dcfbb13f049f841b98763896a3d1d7750 ]
Since commit 7e8756d7ad22 ("mm: page_alloc: fix non-movable reclaim storm in defrag_mode"), direct reclaim and compaction for non-movable requests under defrag_mode run at pageblock_order, to produce the whole blocks that ALLOC_NOFRAGMENT needs. The retry decisions that follow still use the request order. An order-0 request can therefore retry indefinitely without ever reaching the ALLOC_NOFRAGMENT fallback:
- Reclaim at pageblock_order gives up after one pass as soon as a zone looks compaction_ready(), and do_try_to_free_pages() then returns 1 even though nothing was reclaimed. It returns before the retry that would reclaim memory.low-protected cgroups, so when most memory is protected, the pass that did run finds next to nothing.
- Compaction at pageblock_order fails or is deferred.
- should_reclaim_retry() takes the reported progress as progress for the order-0 request and resets no_progress_loops. The request retries.
Order 1-3 requests loop the same way, and should_compact_retry() also checks their pageblock_order compaction result against the request order.
On a production host (64G, defrag_mode, memory.low covering most of the workload), 95% of direct reclaim runs were order-9 runs that returned 1 with nothing reclaimed, at up to 60k runs per second. Across ~200M should_reclaim_retry() calls in a day, no_progress_loops never left 0. The spinning allocations were SLUB slab refills for inode and dentry caches. The time spent registers as memory pressure, and pressure-based OOM killing takes down both workloads and system services.
For promoted requests:
- Reclaim progress does not reset no_progress_loops, as for costly orders.
- should_compact_retry() checks the compaction result at the promoted order and does not retry COMPACT_SKIPPED, since the request can fall back. The compaction priority floor and the COMPACT_SUCCESS retry limit stay those of the request order, so a non-costly request still gets its COMPACT_PRIO_SYNC_FULL pass before it falls back.
When a promoted request takes the fallback, reset the retry counters, so that the fallback attempt gets a full retry budget before the OOM killer is considered. A request whose reclaim was not promoted spent its budget on the request itself and keeps its counters, as Usama Arif pointed out.
__alloc_pages_slowpath() computes the promoted order once per iteration and keeps it in alloc_context for direct reclaim, direct compaction and the two retry helpers, so no callee has to recompute it. Harry Yoo asked for the promoted order to be explicit rather than derived in each callee, and Vlastimil Babka suggested alloc_context over new function parameters.
In a VM reproducer (32G, defrag_mode, inode churn under memory.low):
before after
should_reclaim_retry() calls 63M 293k
peak memory pressure (PSI some avg10) 99% 12%
File creation runs 5.7x faster.
--- mm/page_alloc.c | 65 +++++++++++++++++++++++++++++-------------------- mm/page_alloc.h | 2 ++ 2 files changed, 41 insertions(+), 26 deletions(-)
mm/page_alloc.c +39 -26
@@ -4135,6 +4135,12 @@ __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,return page; } +static inline bool order_defrag_promoted (unsigned int order, +const struct alloc_context *ac) +{ +return ac->reclaim_compact_order != order; +} +/* * Maximum number of compaction retries with a progress before OOM * killer is consider as the only way to move forward.
@@ -4157,22 +4163,7 @@ __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order, .order = order, .page = NULL, }; -int compact_order = order; - -/* -* If fallbacks are not permitted (defrag_mode), we either -* need to reclaim space in a block of matching type, or clear -* out an entire block to allow __rmqueue_claim() to convert. -* -* Reclaim by itself is primarily freeing space in movable -* blocks, since that's where the LRU pages live. So this -* works for movable requests, but not for others. -* -* For those, promote the order to help make blocks, instead -* of spinning in reclaim alone unproductively. -*/ -if ((alloc_flags &ALLOC_NOFRAGMENT ) && ac->migratetype !=MIGRATE_MOVABLE ) - compact_order =max (order, pageblock_order); +int compact_order = ac->reclaim_compact_order;if (!compact_order)return NULL ;
@@ -4265,7 +4256,7 @@ should_compact_retry(gfp_t gfp_mask, struct alloc_context *ac, int order,int retries = *compaction_retries;enum compact_priority priority = *compact_priority; -if (!order) +if (!ac->reclaim_compact_order)return false;if (fatal_signal_pending (current))
@@ -4274,10 +4265,12 @@ should_compact_retry(gfp_t gfp_mask, struct alloc_context *ac, int order,/* * Compaction was skipped due to a lack of free order-0 * migration targets. Continue if reclaim can help. +* Promoted requests fall back instead. */ if (compact_result ==COMPACT_SKIPPED ) { - ret =compaction_zonelist_suitable (ac, order, alloc_flags, - gfp_mask); +if (!order_defrag_promoted (order, ac)) + ret =compaction_zonelist_suitable (ac, order, + alloc_flags, gfp_mask); goto out; }
@@ -4476,11 +4469,7 @@ __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,struct page *page =NULL ;unsigned long pflags;bool drained = false; -int reclaim_order = order; - -/* Match the slowpath compaction promotion in __alloc_pages_direct_compact */ -if ((alloc_flags &ALLOC_NOFRAGMENT ) && ac->migratetype !=MIGRATE_MOVABLE ) - reclaim_order =max (order, pageblock_order); +int reclaim_order = ac->reclaim_compact_order;psi_memstall_enter (&pflags); *did_some_progress =__perform_reclaim (gfp_mask, reclaim_order, ac);
@@ -4656,9 +4645,12 @@ should_reclaim_retry(gfp_t gfp_mask, unsigned order,/* * Costly allocations might have made a progress but this doesn't mean * their order will become available due to high fragmentation so -* always increment the no progress counter for them +* always increment the no progress counter for them. The same goes for +* promoted requests: their reclaim reports progress when it backs off +* for compaction without freeing anything. */ -if (did_some_progress && order <=PAGE_ALLOC_COSTLY_ORDER ) +if (did_some_progress && order <=PAGE_ALLOC_COSTLY_ORDER && + !order_defrag_promoted (order, ac)) *no_progress_loops =0 ;else (*no_progress_loops)++;
@@ -4942,6 +4934,22 @@ __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,/* If allocation has taken excessively long, warn about it */ check_alloc_stall_warn (gfp_mask, ac->nodemask, order, alloc_start_time); +/* +* If fallbacks are not permitted (defrag_mode), we either +* need to reclaim space in a block of matching type, or clear +* out an entire block to allow __rmqueue_claim() to convert. +* +* Reclaim by itself is primarily freeing space in movable +* blocks, since that's where the LRU pages live. So this +* works for movable requests, but not for others. +* +* For those, promote the order to help make blocks, instead +* of spinning in reclaim alone unproductively. +*/ + ac->reclaim_compact_order = order; +if ((alloc_flags &ALLOC_NOFRAGMENT ) && ac->migratetype !=MIGRATE_MOVABLE ) + ac->reclaim_compact_order =max (order, pageblock_order); +/* Try direct reclaim and then allocating */ if (!compact_first) { page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags,
@@ -5023,6 +5031,11 @@ __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,/* Reclaim/compaction failed to prevent the fallback */ if (defrag_mode && (alloc_flags &ALLOC_NOFRAGMENT )) { alloc_flags &= ~ALLOC_NOFRAGMENT ; +/* Retries went into making blocks, start the fallback afresh */ +if (order_defrag_promoted (order, ac)) { + no_progress_loops =0 ; + compaction_retries =0 ; + } goto retry; }
mm/page_alloc.h +2 -0
@@ -93,6 +93,8 @@ struct alloc_context {bool spread_dirty_pages;/* Only flags that are global to the whole allocation go here. */ unsigned int alloc_flags; +/* Set by __alloc_pages_slowpath() before reclaim and compaction */ +unsigned int reclaim_compact_order; };/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1083/1257 mm/mlock: use a long for the page count in mlock_fixup()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nickolai Zeldovich <[email protected]>
[ Upstream commit 3ae91e3079b1504ef162b2884454d5f1421f4eb9 ]
mlock_fixup() adjusts mm->locked_vm, an unsigned long, by the number of pages whose VM_LOCKED state it changes, but computes that number in an int:
int nr_pages; ... nr_pages = (end - start) >> PAGE_SHIFT; ... mm->locked_vm += nr_pages;
When a single VMA range of 2^31 pages (8 TiB with 4 KiB pages) or more is locked or unlocked, the count is truncated to 32 bits and then sign-extended, so locked_vm is changed by the wrong amount, while munmap(), mremap() and the other paths that maintain locked_vm use the full unsigned long page count.
Such a range is reachable on 64-bit architectures with a 47-bit or larger user address space (x86_64, arm64 with 48-bit VA, riscv64 Sv48) by a task with CAP_IPC_LOCK or a raised RLIMIT_MEMLOCK, which do_mlock() checks against the full untruncated length. It costs nothing with MAP_NORESERVE and MLOCK_ONFAULT/MCL_ONFAULT, since then no page is populated. On x86_64, after
p = mmap(NULL, 8UL << 40, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); mlock2(p, 8UL << 40, MLOCK_ONFAULT);
VmLck in /proc/self/status reads 18446744065119617024 kB instead of 8589934592 kB; munmap() of the region then subtracts the true size and leaves VmLck at 18446744056529682432 kB instead of 0. With 16 TiB, locked_vm is not changed at all, VmLck stays 0 kB, and after the task drops CAP_IPC_LOCK or lowers RLIMIT_MEMLOCK, mlock(), mmap(MAP_LOCKED) and the other mlock_future_ok() and account_locked_vm() users enforce RLIMIT_MEMLOCK against that count, so they let the task lock memory beyond its limit (or, in the 8 TiB case, refuse every further lock). The error persists for the life of the mm; unlocking the range in pieces skews it further. The wrong count is per-mm accounting only: it does not change which pages are locked.
The int has been there since before git history (the variable was named "pages" until it was renamed in 2.6.28); every other updater of locked_vm uses an unsigned long or long count. Make nr_pages a long, which holds the page count of any user range and its negation, so the existing sign handling is unchanged.
Found by formal verification of mm/mlock.c against the kernel binary.
--- mm/mlock.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/mlock.c +1 -1
@@ -470,7 +470,7 @@ static int mlock_fixup(struct vma_iterator *vmi, struct vm_area_struct *vma, {const vma_flags_t old_vma_flags = vma->flags;struct mm_struct *mm = vma->vm_mm; -int nr_pages; +long nr_pages;int ret =0 ; if (vma_flags_same_pair(&old_vma_flags, new_vma_flags) ||
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1084/1257 userfaultfd: fix UFFDIO_MOVE livelock on large folio with extra references
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft) <[email protected]>
[ Upstream commit 454143aeb4c6c85ca7d50df36d1a66a64d88283e ]
To move one page out of a large folio, move_pages_ptes() first has to split the folio. __folio_split() refuses if the folio has any reference beyond its page table mappings and the caller's own, and it reports the refusal as -EAGAIN. move_pages() treats returned -EAGAIN as a transient race and keeps retrying the same address, holding the VMA read locks the whole time. This is incorrect since in some cases userspace can hold such a reference indefinitely, such as by registering the page as an io_uring buffer.
An unprivileged user can trigger this with three threads: first holds such a reference on a page of a THP, second calls UFFDIO_MOVE on another page of the same THP and spins in the kernel forever holding the VMA read locks, and third calls fork() or mprotect(), which takes mmap_lock for writing and then waits forever for those read locks. From then on every mmap_lock user of that mm hangs, including other processes inspecting it through /proc/<pid>/, until the process is SIGKILLed. The hung task detector reports the blocked tasks (third one), and with kernel.hung_task_panic=1 the machine panics:
INFO: task wedge:95 blocked for more than 122 seconds. task:wedge state:D stack:12528 pid:95 tgid:95 ppid:94 Call Trace: __schedule+0x596/0x1110 schedule+0x36/0xf0 __vma_start_exclude_readers+0x100/0x170 __vma_start_write+0x51/0xd0 __split_vma+0x208/0x3d0 vma_modify+0x6a8/0x840 vma_modify_flags+0xce/0x110 mprotect_fixup+0xbe/0x480 do_mprotect_pkey+0x2d9/0x580 __x64_sys_mprotect+0x1a/0x30
Fix by returning -EBUSY instead of -EAGAIN in move_pages_ptes(), the caller of split_folio(), when the split fails. Thus, move_pages() does not retry -EBUSY and the ioctl drops its locks and returns to userspace instead of spinning.
--- mm/userfaultfd.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
mm/userfaultfd.c +5 -1
@@ -1663,8 +1663,12 @@ static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmdpte_unmap (dst_pte); src_pte = dst_pte =NULL ; ret =split_folio (src_folio); -if (ret) +if (ret) { +/* do not retry, extra refs may be held forever */ +if (ret == -EAGAIN ) + ret = -EBUSY ; goto out; + }/* have to reacquire the folio after it got split */ folio_unlock (src_folio);folio_put (src_folio);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1085/1257 mm/percpu: account full object size for percpu memory allocations
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Harry Yoo (Meta) <[email protected]>
[ Upstream commit c7a467fbcbbc31e57a5077bfc9456d9f29cb1571 ]
When memory allocation profiling is enabled, the pages backing percpu memory chunks are attributed to func:pcpu_alloc_pages. However, the accounting of individual percpu memory allocations via alloc_percpu() and friends record only the size of a single object rather than its full size across all CPUs.
As a result, it is often not straightforward to identify which kernel code is actually responsible for percpu memory, because the size is under-accounted by a factor of num_possible_cpus().
Account full object size with pcpu_obj_full_size(size) instead, which multiplies the object size by num_possible_cpus() and adds the objcg pointer overhead. This is consistent with what memcg already does for charging percpu allocations.
Verified with 64-CPU VM by spawning 400 processes in a memory cgroup and measuring mm_init()'s rss_stat counters.
Delta of kernel/fork.c:1142 func:mm_init in /proc/allocinfo:
bytes calls per allocation
unpatched 6320 395 16
patched 418176 396 1056
'percpu' field in memory.stat: 422400 (1056 bytes per process)
Memory allocation profiling now accounts the same amount of memory as what memcg charges.
--- mm/percpu.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
mm/percpu.c +3 -2
@@ -1698,14 +1698,15 @@ static void pcpu_alloc_tag_alloc_hook(struct pcpu_chunk *chunk, int off, {if (mem_alloc_profiling_enabled () &&likely (chunk->obj_exts)) {alloc_tag_add (&chunk->obj_exts[off >>PCPU_MIN_ALLOC_SHIFT ].tag, - current->alloc_tag, size); + current->alloc_tag,pcpu_obj_full_size (size)); } }static void pcpu_alloc_tag_free_hook (struct pcpu_chunk *chunk,int off,size_t size) {if (mem_alloc_profiling_enabled () &&likely (chunk->obj_exts)) -alloc_tag_sub (&chunk->obj_exts[off >>PCPU_MIN_ALLOC_SHIFT ].tag, size); +alloc_tag_sub (&chunk->obj_exts[off >>PCPU_MIN_ALLOC_SHIFT ].tag, +pcpu_obj_full_size (size)); }#else static void pcpu_alloc_tag_alloc_hook(struct pcpu_chunk *chunk, int off,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1086/1257 mm/madvise: atomically clear the young bit on THP MADV_COLD
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pedro Falcato <[email protected]>
[ Upstream commit 246c8cc33438a71c28f9b86baa492d9a0a130316 ]
As-is, madvise_cold_or_pageout_pte_range() discards the hardware young bit by invalidating the PMD, doing pmd_mkold() and subsequently writing to the pmd again. However, it does so in a racy manner, looking at a possibly-stale snapshot. It's entirely possible that a write elsewhere set the hardware D bit, which this logic now loses.
Fix it by using pmdp_test_and_clear_young(). This is an atomic modification of the PMD entry, and thus safe against any possible racing writes. As a (nice) side-effect, this elides one non-required TLB flush in pmdp_invalidate().
This bug can interact with the swapping system in complicated ways, leading to data loss. For instance, if a folio is marked lazyfree, but was later read from, and then MADV_COLD'd while racing a write to that same THP, dropping the dirty bit may lead to data loss as reclaim/MADV_PAGEOUT drops the "clean" anon folio:
T0 T1
================================================================MADV_FREE(thp) |
folio marked lazyfree |
read(thp) |
PMD marked young by hardware |
| MADV_COLD(thp)
write(thp) | if (pmd_young(pmd)) {
PMD marked dirty by hardware | set(pmdp, pmd_mkold(pmd));
MADV_PAGEOUT/reclaim |
dirty bit may or may not be |
set |
reclaim/pageout may drop |
the folio |
--- mm/madvise.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-)
mm/madvise.c +1 -4
@@ -429,10 +429,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd, }if (!pageout &&pmd_young (orig_pmd)) { -pmdp_invalidate (vma, addr, pmd); - orig_pmd =pmd_mkold (orig_pmd); - -set_pmd_at (mm, addr, pmd, orig_pmd); +pmdp_test_and_clear_young (vma, addr, pmd);tlb_remove_pmd_tlb_entry (tlb, pmd, addr); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1087/1257 ipc/shm: fix RSS accounting for hugetlb shared memory
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weilin Tong <[email protected]>
[ Upstream commit e387ebe5cd31720b1e0281fd045be4eef36fadb3 ]
Commit a08c7193e4f1 ("mm/filemap: remove hugetlb special casing in filemap.c") changed mapping->nrpages to count base pages for hugetlb folios. However, shm_add_rss_swap() still multiplies it by pages_per_huge_page(), overcounting RSS in both SHM_INFO and /proc/sysvipc/shm.
Use mapping->nrpages for RSS accounting across all backing types, and account swap only for non-hugetlb shmem. Use READ_ONCE() for both counters instead of info->lock, which does not protect nrpages and cannot provide a consistent snapshot.
--- ipc/shm.c | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-)
ipc/shm.c +4 -19
@@ -936,26 +936,11 @@ static inline unsigned long copy_shminfo_to_user(void __user *buf, struct shminfstatic void shm_add_rss_swap (struct shmid_kernel *shp,unsigned long *rss_add,unsigned long *swp_add) { -struct inode *inode; +struct inode *inode =file_inode (shp->shm_file); - inode =file_inode (shp->shm_file); - -if (is_file_hugepages (shp->shm_file)) { -struct address_space *mapping = inode->i_mapping; -struct hstate *h =hstate_file (shp->shm_file); - *rss_add +=pages_per_huge_page (h) * mapping->nrpages; - }else { -#ifdef CONFIG_SHMEM -struct shmem_inode_info *info =SHMEM_I (inode); - -spin_lock_irq (&info->lock); - *rss_add += inode->i_mapping->nrpages; - *swp_add += info->swapped; -spin_unlock_irq (&info->lock); -#else - *rss_add += inode->i_mapping->nrpages; -#endif - } + *rss_add +=READ_ONCE (inode->i_mapping->nrpages); +if (IS_ENABLED (CONFIG_SHMEM ) && !is_file_hugepages (shp->shm_file)) + *swp_add +=READ_ONCE (SHMEM_I (inode)->swapped); }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1088/1257 mm: vmscan: dont count per-node proactive reclaim as memory pressure
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vernon Yang <[email protected]>
[ Upstream commit 2ca8b38962f239b17f7881a4710c11328ce38ac9 ]
When the cgroup has no memory pressure at all, writing to /sys/devices/system/nodeX/reclaim triggers proactive reclaim on NUMA node, causing increase in the writer cgroup's memory PSI.
Due to this reclaim is performed in the context of the write(), accounted as memory pressure on the writer, like
commit e22c6ed90aa9 ("mm: memcontrol: don't count limit-setting reclaim as memory pressure"). This is unexpected, the similar scenarios (e.g. senpai) will continue to occur, only this time it is for the /sys/devices/system/nodeX/reclaim knob.
The Documentation/ABI/stable/sysfs-devices-node documentation also notes that "This interface is equivalent to the memcg variant."
This patch unifies the semantics of the memcg and node interfaces:
per-node proactive reclaim is no longer counted as memory pressure, and the per-node proactive reclaim interface no longer produces phantom pressure.
I ran demo[1] that performs per-node proactive reclaim 10000 times in qemu, writer cgroup memory.pressure as follows:
without patch:
some avg10=31.53 avg60=13.42 avg300=3.31 total=10602985 full avg10=31.53 avg60=13.42 avg300=3.31 total=10602985
with patch:
some avg10=9.59 avg60=3.41 avg300=0.81 total=2686221 full avg10=9.59 avg60=3.41 avg300=0.81 total=2686221
--- mm/vmscan.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
mm/vmscan.c +4 -2
@@ -7847,7 +7847,8 @@ static unsigned long __node_reclaim(struct pglist_data *pgdat, sc->gfp_mask);cond_resched (); -psi_memstall_enter (&pflags); +if (!sc->proactive) +psi_memstall_enter (&pflags);delayacct_freepages_start ();fs_reclaim_acquire (sc->gfp_mask);/*
@@ -7871,7 +7872,8 @@ static unsigned long __node_reclaim(struct pglist_data *pgdat,memalloc_noreclaim_restore (noreclaim_flag);fs_reclaim_release (sc->gfp_mask);delayacct_freepages_end (); -psi_memstall_leave (&pflags); +if (!sc->proactive) +psi_memstall_leave (&pflags);trace_mm_vmscan_node_reclaim_end (sc->nr_reclaimed,NULL );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1089/1257 mm/swap: fix swap_cache_get_folio() returning a folio that left the swap cache
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiayuan Chen <[email protected]>
[ Upstream commit 60f34fedf3a4c91ed631ed2f80713ab993cde5ee ]
swap_cache_get_folio() reads the folio from the swap table and takes a reference with folio_try_get(), without any lock. If the folio is removed from the swap cache and freed in between, and its memory gets reused, folio_try_get() still succeeds and we return a page that has nothing to do with the swap entry:
CPU 0 CPU 1
do_swap_page()
swap_cache_get_folio()
swp_tb = swap_table_get()
folio = swp_tb_to_folio(swp_tb)
madvise(MADV_DONTNEED)
zap_nonpresent_ptes()
swap_put_entries_direct()
swap_put_entries_cluster()
__try_to_reclaim_swap()
swap_cache_del_folio()
folio_put() <- freed
page reused, e.g. as an anon folio of another task
folio_try_get(folio) <- succeeds
return folio
swap_update_readahead() <- may clear PG_readahead on it
folio_lock_or_retry() <- locks it
folio_matches_swap_entry() fails, unlock and put
filemap_get_entry() does the same lockless lookup for the page cache, and after folio_try_get() it rechecks the xarray, because the folio may have been freed and reused in between. swap_cache_get_folio() lost that recheck when the swap cache moved to the swap table.
So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.
When the race occurs, a swap fault can acquire a reference to a physical page that has been freed and reused for an unrelated purpose, potentially by another process. The fault handler may then clear that page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, and potentially attempt to remove it from an unrelated swap cache.
These operations can interfere with unrelated workloads and may cause unexpected stalls and impaired reclaim. The subsequent swap-entry validation normally prevents the wrong folio from being mapped into the faulting process.
It's documented that caller always double checks the folio so this part is harmless from the aspect of data corruption or crash.
Recheck the slot after folio_try_get() and retry if it no longer holds this folio.
--- mm/swap_state.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-)
mm/swap_state.c +13 -3
@@ -92,17 +92,27 @@ void show_swap_cache_info(void)*/ struct folio *swap_cache_get_folio (swp_entry_t entry) { +struct swap_cluster_info *ci =__swap_entry_to_cluster (entry); +unsigned int ci_off =swp_cluster_offset (entry);unsigned long swp_tb;struct folio *folio;for (;;) { - swp_tb =swap_table_get (__swap_entry_to_cluster (entry), -swp_cluster_offset (entry)); + swp_tb =swap_table_get (ci, ci_off);if (!swp_tb_is_folio (swp_tb))return NULL ; folio =swp_tb_to_folio (swp_tb); -if (likely (folio_try_get (folio))) +if (!folio_try_get (folio)) +continue ; +/* +* The folio may have been freed and its memory reused before +* we got the reference. Make sure it is still in the slot. +*/ + swp_tb =swap_table_get (ci, ci_off); +if (likely (swp_tb_is_folio (swp_tb) && +swp_tb_to_folio (swp_tb) == folio))return folio; +folio_put (folio); }return NULL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1090/1257 mm/page_alloc: count guard pages as free again when their buddy merges
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rik van Riel <[email protected]>
[ Upstream commit 1503710b3b0cec02b531978129c6c1eb70a7c490 ]
With debug_guardpage_minorder set, expand() turns the unused halves of a split into guard pages, which page_del_and_expand() leaves out of the free counts. Freeing the allocated half credits only that half, and __free_one_page() then merges the guard buddy with clear_page_guard(), which no longer touches the counters.
The merged block goes on a free list with the guard pages never counted, so NR_FREE_PAGES falls behind the free lists by every guard that merges. Before commit e0932b6c1f94 ("mm: page_alloc: consolidate free page accounting"), __set_page_guard() and __clear_page_guard() adjusted the counts themselves; that commit dropped both adjustments but kept the subtraction implicit in expand().
Count the guard pages under the merged block's migratetype when the buddy is cleared. account_freepages() skips an isolated block as it does for every other free page, and moving the block off the isolated list counts it then.
Booting a 16GB VM with debug_pagealloc=on debug_guardpage_minorder=1, check the difference in free pages reported between /proc/vmstat and /proc/buddyinfo.
At three points (idle, after a read and file-creation load, after a second load), check the difference between nr_free_pages and the buddyinfo numbers in the normal zone, as a number of pages:
idle after load after second load
unpatched -130 79205 99121
patched -16 45 0
The small remaining difference seems to be due to the numbers not being read at exactly the same time, and is also seen without guard pages.
--- mm/page_alloc.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
mm/page_alloc.c +4 -2
@@ -989,10 +989,12 @@ static inline void __free_one_page(struct page *page,* Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page, * merge with it and move up one order. */ -if (page_is_guard (buddy)) +if (page_is_guard (buddy)) {clear_page_guard (zone, buddy, order); -else +account_freepages (zone,1 << order, migratetype); + }else {__del_page_from_free_list (buddy, zone, order, buddy_mt); + }if (unlikely (buddy_mt != migratetype)) {/*
Signature · 1 line
2.53.0