Skip to contentSkip to conversation

6.18.63-rc1 review

PATCH In review Greg Kroah-Hartman 11 participants 880 messages Nov 7 – Nov 9 Page 6 of 7

Subsystems (5)
lore
Share & tools
lore
author maintainer
#683 lore raw

PATCH 681/869 drm/amdkfd: wait for a GPU reset before freeing a BO

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: William Palacek <[email protected]>

[ Upstream commit 47d799a718439764432d8ef3a0952af45f025f76 ]

When a GPU reset takes the reset domain, KFD eviction cannot unmap user queues: execute_queues_cpsch() fails its trylock with -EIO, so the queues keep running until the ASIC is reset. The TLB flush is also skipped while the reset is in progress. If the process unmaps and frees a BO in that window, its pages are released while a queue can still access them through stale translations.

On MI300X, munmap() then crashes in free_swap_cache() on a small bogus page pointer in its mmu_gather batch page:

  BUG: unable to handle page fault for address: 0000000000002900
  RIP: 0010:free_swap_cache+0x5/0xb0
  Call Trace:
   free_pages_and_swap_cache+0x3a/0x60
   tlb_batch_pages_flush+0x43/0x80
   tlb_flush_mmu+0x3d/0x110
   zap_pte_range+0x80d/0xcd0
   ...
   do_vmi_align_munmap+0x3e8/0x5b0
   do_vmi_munmap+0xdf/0x190
   __vm_munmap+0xad/0x180
   __x64_sys_munmap+0x1b/0x30

In a traced crash the bogus pointer was the read pointer value of an SDMA queue the process had just destroyed, at the read pointer's page offset:
the queue's writeback landed in its freed rptr page after the page was reused as the batch page.

commit f0b4440cdc18 ("drm/amdkfd: Fix mode1 reset crash issue") fixed this race on process exit by waiting for the reset to complete before freeing the process's BOs. Free through the ioctl has the same race. Wait for the reset there too, using the same helper.

Fixes 9c33e5fd4fb6 ("drm/amdgpu: fix locking scope when flushing tlb")
(cherry picked from commit 06ff8ce77726b15a98fcc285dd6005cb3f48558b)
---
 drivers/gpu/drm/amd/amdkfd/kfd_chardev.c | 3 +++
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h    | 1 +
 drivers/gpu/drm/amd/amdkfd/kfd_process.c | 2 +-
 3 files changed, 5 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +3 -0
index c224d78a770a1..1ec77554da503 100644
@@ -1222,6 +1222,9 @@ static int kfd_ioctl_free_memory_of_gpu(struct file *filep,
 		goto err_unlock;
 	}
 
+	/* Queues a reset could not stop may still access the buffer */
+	kfd_process_wait_gpu_reset_complete(p);
+
 	ret = amdgpu_amdkfd_gpuvm_free_memory_of_gpu(pdd->dev->adev,
 				(struct kgd_mem *)mem, pdd->drm_priv, &size);
 
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +1 -0
index ef1afeaa8d85d..1f5f528188980 100644
@@ -1084,6 +1084,7 @@ void kfd_unref_process(struct kfd_process *p);
 int kfd_process_evict_queues(struct kfd_process *p, uint32_t trigger);
 int kfd_process_restore_queues(struct kfd_process *p);
 void kfd_suspend_all_processes(void);
+void kfd_process_wait_gpu_reset_complete(struct kfd_process *p);
 int kfd_resume_all_processes(void);
 
 struct kfd_process_device *kfd_process_device_data_by_id(struct kfd_process *process,
drivers/gpu/drm/amd/amdkfd/kfd_process.c +1 -1
index 0b760aab11c6f..1c591953cc80d 100644
@@ -1144,7 +1144,7 @@ static void kfd_process_remove_sysfs(struct kfd_process *p)
 /*
  * If any GPU is ongoing reset, wait for reset complete.
  */
-static void kfd_process_wait_gpu_reset_complete(struct kfd_process *p)
+void kfd_process_wait_gpu_reset_complete(struct kfd_process *p)
 {
 	int i;
 
Signature · 1 line
2.53.0
author maintainer
#684 lore raw

PATCH 682/869 drm/amdgpu: wait for pending page table updates before switching a VM to CPU updates

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: John Fisher <[email protected]>

[ Upstream commit 53d9ef2f518add783bb48a69d77bbc8aea99e911 ]

amdgpu_vm_make_compute() switches a VM from SDMA to CPU page table updates when a KFD process acquires it. It syncs "with the last SDMA update/clear" through amdgpu_bo_sync_wait() on the root PD, but that walks the reservation with DMA_RESV_USAGE_READ, and the clears of the VM's page tables (the root PD from amdgpu_vm_init(), and the PDs/PTs the seq64 mapping allocates at the render node's open) are added there by amdgpu_vm_sdma_commit() with DMA_RESV_USAGE_BOOKKEEP only:
amdgpu_vm_pt_clear() commits them with a NULL fence, so they do not reach vm->last_update. The CPU path's own waits (amdgpu_vm_cpu_update(), amdgpu_bo_kmap()) use DMA_RESV_USAGE_KERNEL. None of them waits for a clear that is still queued.

When one is, the CPU writes the first entries of the new compute VM (the KFD trap handler's TBA/TMA page at AMDGPU_VA_RESERVED_TRAP_START, mapped during ACQUIRE_VM) into a page directory the SDMA then clears. The entries are gone, the handler's page is unmapped, and the first wave save of any queue of the process faults in the SQC instruction fetch at the handler's address (GCVM_L2_PROTECTION_FAULT_STATUS 0x008012B1, PERMISSION_FAULTS 0xb). The MES then fails REMOVE_QUEUE and SUSPEND, and the device takes a MODE1 reset with VRAM lost on 7.2.9; on 7.3-rc6 the queue is reset instead.

The window is the time between the render node's open and ACQUIRE_VM. ROCr spends milliseconds there and is practically never hit; a minimal KFD client that opens the render node and acquires the VM at once is hit most of the time. On a Radeon AI PRO R9700 (gfx1201, Resizable BAR, so vm_update_mode defaults to CPU updates for compute VMs), a wave reading the trap handler's page right after queue creation found it unmapped in 8 of 12 runs; a 5 ms sleep between the open and ACQUIRE_VM made that 0 of 9, and the same sleep after queue creation instead 3 of 3.

The wait covered these jobs until commit 926c79ad6ecd ("drm/amdgpu:
promote the implicit sync to the dependent read fences") narrowed amdgpu_sync_resv() from DMA_RESV_USAGE_BOOKKEEP to DMA_RESV_USAGE_READ; the VM's page table jobs have been added with BOOKKEEP since commit 4247084057cf ("drm/amdgpu: use DMA_RESV_USAGE_BOOKKEEP v2"), so from v6.16 on the sync in amdgpu_vm_make_compute() waits for nothing of them.

Record the clears in vm->last_update, as amdgpu_vm_update_pdes() does with its updates, and wait for it, uninterruptibly, before switching the update functions. The clears all go through vm->delayed, so the last one covers the earlier ones; immediate clears are not recorded, as before.

With this, on 7.3-rc6 and on 7.2.9, the same client reads the handler 10 of 10 times, 8 busy queues on the 4 compute slots complete in 5 of 5 runs on 7.3-rc6 and 3 of 3 on 7.2.9 (1 of 6 before), 16 and 32 queues complete on 7.3-rc6, and two processes with 8 queues each complete together on both, with no fault.

Fixes 926c79ad6ecd ("drm/amdgpu: promote the implicit sync to the dependent read fences")
Cc Prike Liang <[email protected]>
(cherry picked from commit 9ec91b35baba45209c3fcd00f086224a158dd512)
Cc [email protected] # v6.16+
---
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c    | 5 +----
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c | 2 +-
 2 files changed, 2 insertions(+), 5 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +1 -4
index f78ac6777ee5c..c9614a99b40d1 100644
@@ -2720,10 +2720,7 @@ int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
 
 	if (vm->use_cpu_for_update) {
 		/* Sync with last SDMA update/clear before switching to CPU */
-		r = amdgpu_bo_sync_wait(vm->root.bo,
-					AMDGPU_FENCE_OWNER_UNDEFINED, true);
-		if (r)
-			goto unreserve_bo;
+		dma_fence_wait(vm->last_update, false);
 
 		vm->update_funcs = &amdgpu_vm_cpu_funcs;
 		r = amdgpu_vm_pt_map_tables(adev, vm);
drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c +1 -1
index f794fb1cc06e6..a05f34259d578 100644
@@ -421,7 +421,7 @@ int amdgpu_vm_pt_clear(struct amdgpu_device *adev, struct amdgpu_vm *vm,
 	if (r)
 		goto exit;
 
-	r = vm->update_funcs->commit(&params, NULL);
+	r = vm->update_funcs->commit(&params, &vm->last_update);
 exit:
 	drm_dev_exit(idx);
 	return r;
Signature · 1 line
2.53.0
author maintainer
#685 lore raw

PATCH 683/869 amdkfd: Fix memory availability double accounting of kfd pinned objects

In reply to Greg Kroah-Hartman

6.18-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.

(cherry picked from commit b8257bdb26ca5d9a75f4b81f629422f17afa221b)
---
 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
index c59b5d9cd36b6..b15798489af0c 100644
@@ -104,6 +104,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
index d56728b257f49..bf4cea36d3ad4 100644
@@ -1518,6 +1518,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;
@@ -1540,6 +1545,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);
 }
 
@@ -1661,6 +1671,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
author maintainer
#686 lore raw

PATCH 684/869 drm/amdkfd: correct vram_available calculation

In reply to Greg Kroah-Hartman

6.18-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.

(cherry picked from commit 894cbb31c50e3cf49657130396bbf6c0475304e4)
---
 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
index 803b6fc360a07..034f2d03e367e 100644
@@ -1195,8 +1195,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
index b15798489af0c..21dbc8675f4e7 100644
@@ -40,6 +40,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,
@@ -104,7 +110,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;
 
@@ -375,6 +381,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
@@ -392,6 +400,16 @@ static inline
 void 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
index cdab2c098cfab..c2f13584a5a32 100644
@@ -917,6 +917,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
@@ -997,7 +1010,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) {
@@ -1030,7 +1053,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
index 1ec77554da503..b90bfbd121f88 100644
@@ -1035,11 +1035,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
author maintainer
#687 lore raw

PATCH 685/869 ipv6: remove ifaddr from hash during ifdown list cleanup

In reply to Greg Kroah-Hartman

6.18-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
index 81f5bda2a89fc..067d325291b9f 100644
@@ -4006,6 +4006,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
author maintainer
#688 lore raw

PATCH 686/869 ipv6: serialize address publication with device teardown

In reply to Greg Kroah-Hartman

6.18-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
index 067d325291b9f..caf8f3bd2372f 100644
@@ -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);
 
@@ -3884,7 +3888,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
author maintainer
#689 lore raw

PATCH 687/869 ipv6: initialize temporary ifaddr before publication

In reply to Greg Kroah-Hartman

6.18-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
index b353dea9aedc8..03d6543a51890 100644
@@ -80,6 +80,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
index caf8f3bd2372f..e277b78313686 100644
@@ -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
author maintainer
#690 lore raw

PATCH 688/869 ipv6: do not restart DAD for a dead ifaddr

In reply to Greg Kroah-Hartman

6.18-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
index e277b78313686..527ae9fc1c41c 100644
@@ -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
author maintainer
#691 lore raw

PATCH 689/869 fbdev: bitblit: Fix glyph clipping when fbcon pans

In reply to Greg Kroah-Hartman

6.18-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
index 8f6a2d1736d39..86ae7a7252d21 100644
@@ -18,6 +18,7 @@
 #include <linux/console.h>
 #include <asm/types.h>
 #include "fbcon.h"
+#include "fbcon_rotate.h"
 
 /*
  * Accelerated handlers.
@@ -151,7 +152,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;
@@ -168,10 +171,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
author maintainer
#692 lore raw

PATCH 690/869 PCI: qcom-ep: Deinitialize endpoint on remove

In reply to Greg Kroah-Hartman

6.18-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.

Fixes f55fee56a631 ("PCI: qcom-ep: Add Qualcomm PCIe Endpoint controller driver")
---
 drivers/pci/controller/dwc/pcie-qcom-ep.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/pci/controller/dwc/pcie-qcom-ep.c +2 -0
index f1bc0ac81a928..72bb2a2dd238e 100644
@@ -920,6 +920,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
author maintainer
#693 lore raw

PATCH 691/869 net/rds: ib: dont enable IRQs in rds_ib_conn_free()

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 745cbccac3fe ("RDS: Rewrite connection cleanup, fixing oops on rmmod")
Reported-by [email protected]
---
 net/rds/ib_cm.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
net/rds/ib_cm.c +4 -2
index 1c6e3b3f39d00..c8771aa7df53a 100644
@@ -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
author maintainer
#694 lore raw

PATCH 692/869 net: unix: reject negative max_dgram_qlen values

In reply to Greg Kroah-Hartman

6.18-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
index 27a861053b2f5..c2ca933f7bdbc 100644
@@ -3729,5 +3729,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
index e02ed6e3955c0..bb93cf3aa6fee 100644
@@ -19,7 +19,9 @@ static 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
author maintainer
#695 lore raw

PATCH 693/869 net/smc: queue the copied chunk when smc_tx_sendmsg() faults

In reply to Greg Kroah-Hartman

6.18-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
index 3144b4b1fe290..495fb1354728c 100644
@@ -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
author maintainer
#696 lore raw

PATCH 694/869 alpha: determine tininess after rounding in the FP emulation

In reply to Greg Kroah-Hartman

6.18-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
index 5fe63afbd474f..bff1ad963c689 100644
@@ -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
index 8ce066c035cfa..1d1ce5c08efcf 100644
@@ -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
index 5650c16283830..02ada0a9fca16 100644
@@ -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
author maintainer
#697 lore raw

PATCH 695/869 ocfs2: reserve metadata for a new xattr block and its value tree

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 3ed2be719eb9 ("ocfs2: allow for more than one data extent when creating xattr")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
fs/ocfs2/xattr.c +7 -1
index b5029c4e3784e..a47a038b3311b 100644
@@ -3243,7 +3243,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
author maintainer
#698 lore raw

PATCH 696/869 ocfs2: reserve value tree metadata when moving an xattr into the inode

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 78f30c314a74 ("ocfs2/xattr: Reserve meta/data at the beginning of ocfs2_xattr_set.")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 8 ++++++++
 1 file changed, 8 insertions(+)
fs/ocfs2/xattr.c +8 -0
index a47a038b3311b..ab117ed2623e7 100644
@@ -3143,6 +3143,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
author maintainer
#699 lore raw

PATCH 697/869 ocfs2: deal with legacy signed dir index name hash values

In reply to Greg Kroah-Hartman

6.18-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
index fbfce8cd131aa..1dee6b8eaf2d0 100644
@@ -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.
@@ -961,10 +979,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;
@@ -977,8 +995,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;
@@ -1075,6 +1091,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
author maintainer
#700 lore raw

PATCH 698/869 ocfs2: use the stored hash when checking xattr bucket collision

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 3bc753c06dd0 ("kbuild: treat char as always unsigned")
Cc Anderson Ferneda <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc <[email protected]> # 6.2+
---
 fs/ocfs2/xattr.c | 27 +++++++++++++++++----------
 1 file changed, 17 insertions(+), 10 deletions(-)
fs/ocfs2/xattr.c +17 -10
index ab117ed2623e7..523d5ac597f41 100644
@@ -5531,16 +5531,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;
@@ -5609,6 +5607,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);
@@ -5628,10 +5627,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
author maintainer
#701 lore raw

PATCH 699/869 ocfs2: deal with legacy signed xattr name hash values

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 3bc753c06dd0 ("kbuild: treat char as always unsigned")
Cc Anderson Ferneda <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc <[email protected]> # 6.2+
---
 fs/ocfs2/xattr.c | 93 ++++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 82 insertions(+), 11 deletions(-)
fs/ocfs2/xattr.c +82 -11
index 523d5ac597f41..8013451927a83 100644
@@ -533,9 +533,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;
@@ -544,13 +545,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) +
@@ -3949,11 +3967,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 =
@@ -3962,7 +3981,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;
@@ -3993,6 +4011,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
author maintainer
#702 lore raw

PATCH 700/869 ocfs2/cluster: initialize heartbeat regions before publishing them

In reply to Greg Kroah-Hartman

6.18-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>
    ==================================================================
Fixes 536f0741f324 ("ocfs2/cluster: Track number of global heartbeat regions")
Assisted-by LLM
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc Heming Zhao <[email protected]>
Cc Yufan Chen <[email protected]>
Cc Christophe JAILLET <[email protected]>
Cc Kees Cook <[email protected]>
Cc Karl Mehltretter <[email protected]>
Cc Sunil Mushran <[email protected]>
Cc Jia-Ju Bai <[email protected]>
---
 fs/ocfs2/cluster/heartbeat.c | 26 +++++++++++++++++---------
 1 file changed, 17 insertions(+), 9 deletions(-)
fs/ocfs2/cluster/heartbeat.c +17 -9
index 61e5eb0090d39..0888c44f677c1 100644
@@ -2124,6 +2124,18 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *g
 	}
 	reg->hr_node_num = O2NM_MAX_NODES;
 
+	INIT_LIST_HEAD(&reg->hr_all_item);
+	mutex_init(&reg->hr_arming_mutex);
+	reg->hr_stopping = true;
+	INIT_DELAYED_WORK(&reg->hr_write_timeout_work, o2hb_write_timeout);
+	INIT_DELAYED_WORK(&reg->hr_nego_timeout_work, o2hb_nego_timeout);
+	INIT_LIST_HEAD(&reg->hr_handler_list);
+	config_item_init_type_name(&reg->hr_item, name, &o2hb_region_type);
+	if (!config_item_name(&reg->hr_item)) {
+		ret = -ENOMEM;
+		goto put_item;
+	}
+
 	spin_lock(&o2hb_live_lock);
 	reg->hr_region_num = 0;
 	if (o2hb_global_heartbeat_active()) {
@@ -2132,26 +2144,19 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *g
 		if (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(&reg->hr_all_item, &o2hb_all_regions);
 	spin_unlock(&o2hb_live_lock);
 
-	config_item_init_type_name(&reg->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(&reg->hr_arming_mutex);
-	reg->hr_stopping = true;
-	INIT_DELAYED_WORK(&reg->hr_write_timeout_work, o2hb_write_timeout);
-	INIT_DELAYED_WORK(&reg->hr_nego_timeout_work, o2hb_nego_timeout);
-	INIT_LIST_HEAD(&reg->hr_handler_list);
 	ret = o2net_register_handler(O2HB_NEGO_TIMEOUT_MSG, reg->hr_key,
 			sizeof(struct o2hb_nego_msg),
 			o2hb_nego_timeout_handler,
@@ -2174,10 +2179,13 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *g
 	o2net_unregister_and_flush_handler_list(&reg->hr_handler_list);
 remove_item:
 	spin_lock(&o2hb_live_lock);
-	list_del(&reg->hr_all_item);
+	list_del_init(&reg->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(&reg->hr_item);
+	return ERR_PTR(ret);
 free:
 	kfree(reg);
 	return ERR_PTR(ret);
Signature · 1 line
2.53.0
author maintainer
#703 lore raw

PATCH 701/869 Documentation: hyperv: Update documentation for sending VMBus packets

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 45a442fe369e ("Drivers: hv: vmbus: Remove vmbus_sendpacket_pagebuffer()")
---
 Documentation/virt/hyperv/vmbus.rst | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)
Documentation/virt/hyperv/vmbus.rst +9 -8
index 654bb48499724..c546e821ce6b2 100644
@@ -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
author maintainer
#704 lore raw

PATCH 702/869 platform/x86: asus-wmi: fix TUF keyboard power state shutdown naming

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 61f64515299e ("platform/x86: asus-wmi: Implement TUF laptop keyboard power states")
---
 drivers/platform/x86/asus-wmi.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/platform/x86/asus-wmi.c +4 -4
index 486c12b232d14..c8cc47df9294e 100644
@@ -998,10 +998,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)
@@ -1014,7 +1014,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 */
@@ -1028,7 +1028,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
author maintainer
#705 lore raw

PATCH 703/869 writeback: reset dirtied_when when switching wbs

In reply to Greg Kroah-Hartman

6.18-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
index 094d2872881d3..b74a7387bea74 100644
@@ -454,12 +454,12 @@ static bool inode_do_switch_wbs(struct inode *inode,
 		if (inode->i_state & 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
index 55ecd9d26b4fb..349b7fc57db36 100644
@@ -847,7 +847,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
author maintainer
#706 lore raw

PATCH 704/869 writeback: clear old wb dirty state after inode switches

In reply to Greg Kroah-Hartman

6.18-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.

Fixes f3b6a6df38aa ("writeback, cgroup: keep list of inodes attached to bdi_writeback")
---
 fs/fs-writeback.c | 1 +
 1 file changed, 1 insertion(+)
fs/fs-writeback.c +1 -0
index b74a7387bea74..3025fc7ddfe84 100644
@@ -534,6 +534,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
author maintainer
#707 lore raw

PATCH 705/869 ALSA: aloop: Update the PCM Slave controls for a matching playback

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 597603d615d2 ("ALSA: introduce the snd-aloop module for the PCM loopback")
---
 sound/drivers/aloop.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
sound/drivers/aloop.c +7 -4
index eefc41f628462..fd8d6b474e465 100644
@@ -365,11 +365,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 */
 				atomic_inc(&cable->stop_count);
 				stop_capture = true;
Signature · 1 line
2.53.0
author maintainer
#708 lore raw

PATCH 706/869 sh: maple: Use the matching IRQ cookie when invoking free_irq()

In reply to Greg Kroah-Hartman

6.18-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
index 6dc0549f79005..3d3302c900caf 100644
@@ -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
author maintainer
#709 lore raw

PATCH 707/869 nvmet: take subsys->lock while force-reconnecting in nvmet_subsys_attr_qid_max_store()

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 3e980f5995e0 ("nvmet: expose max queues to configfs")
---
 drivers/nvme/target/configfs.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/nvme/target/configfs.c +2 -0
index f6ac42eaac0e0..e2032b58191c5 100644
@@ -1662,8 +1662,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
author maintainer
#710 lore raw

PATCH 708/869 net: wwan: iosm: validate msg_head before indexing msg_ring

In reply to Greg Kroah-Hartman

6.18-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
index 4627847c6daab..455b3b6f09917 100644
@@ -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
author maintainer
#711 lore raw

PATCH 709/869 tipc: fix broadcast sender hang on last acker departure

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 2f487712b893 ("tipc: guarantee that group broadcast doesn't bypass group unicast")
---
 net/tipc/group.c  | 19 ++++++++++---------
 net/tipc/socket.c | 12 +++++++++++-
 2 files changed, 21 insertions(+), 10 deletions(-)
net/tipc/group.c +10 -9
index 0da7b27133949..a9ce1c7018b6c 100644
@@ -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
index af14b50933f5c..4780264a8a491 100644
@@ -2355,8 +2355,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
author maintainer
#712 lore raw

PATCH 710/869 exportfs: Release the get_name() directory file synchronously

In reply to Greg Kroah-Hartman

6.18-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
index d3e55de4a2a2a..ab470783e798d 100644
@@ -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
author maintainer
#713 lore raw

PATCH 711/869 statmount: dont copy the reserved empty string past the buffer

In reply to Greg Kroah-Hartman

6.18-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 14

After:

    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
index ab050a939cb53..fd7949d88a6c5 100644
@@ -5817,7 +5817,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
author maintainer
#714 lore raw

PATCH 712/869 listmount: dont wrap around with a U64_MAX cursor

In reply to Greg Kroah-Hartman

6.18-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
index fd7949d88a6c5..bb73b317f9e72 100644
@@ -5998,6 +5998,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
author maintainer
#715 lore raw

PATCH 713/869 ucount: take the rlimit reference before checking the limit

In reply to Greg Kroah-Hartman

6.18-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
index fc4a8f2d30965..5cbf1553658ea 100644
@@ -302,23 +302,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
author maintainer
#716 lore raw

PATCH 714/869 cpufreq: intel_pstate: cancel HWP notify work in driver cleanup

In reply to Greg Kroah-Hartman

6.18-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().

Fixes d845cd901b28 ("cpufreq: intel_pstate: Support highest performance change interrupt")
Cc All applicable <[email protected]>
[ rjw: Fixed the Fixes: tag ]
---
 drivers/cpufreq/intel_pstate.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/cpufreq/intel_pstate.c +2 -0
index 1de12358c0b98..a498d66883b52 100644
@@ -3458,6 +3458,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
author maintainer
#717 lore raw

PATCH 715/869 i2c: acpi: Fix adapter reference leak in i2c_acpi_new_device_by_fwnode()

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 605f8fc22442 ("i2c: core: Add new i2c_acpi_new_device helper function")
Cc <[email protected]> # v4.12+
---
 drivers/i2c/i2c-core-acpi.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/i2c/i2c-core-acpi.c +5 -1
index 98ebbc973f212..8805fc454a4ef 100644
@@ -545,6 +545,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;
@@ -572,7 +573,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
author maintainer
#718 lore raw

PATCH 716/869 i2c: designware: queue only one read command for block reads

In reply to Greg Kroah-Hartman

6.18-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.

Fixes c3ae106050b9 ("i2c: designware: Implement support for SMBus block read and write")
Cc <[email protected]> # v4.10+
---
 drivers/i2c/busses/i2c-designware-master.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/i2c/busses/i2c-designware-master.c +8 -0
index c4bab532eed1e..593ddec3c40ee 100644
@@ -515,6 +515,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
author maintainer
#719 lore raw

PATCH 717/869 tpm: tpm_nsc: fix NULL pointer dereference on init failure

In reply to Greg Kroah-Hartman

6.18-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
index 879ac88f5783c..46a52dc99b148 100644
@@ -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
author maintainer
#720 lore raw

PATCH 718/869 tpm: tpm_nsc: stop using the cleanup callback as dev.release

In reply to Greg Kroah-Hartman

6.18-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
index 46a52dc99b148..bcfa2a1a208a9 100644
@@ -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
author maintainer
#721 lore raw

PATCH 719/869 tpm: fix zero-length read discarding the pending response

In reply to Greg Kroah-Hartman

6.18-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
index f2a5e09257ddd..a856b4ddbdc2c 100644
@@ -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
author maintainer
#722 lore raw

PATCH 720/869 gpiolib: dont report -ENOMEM for a requested line without a label

In reply to Greg Kroah-Hartman

6.18-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
index 635b77c0eab53..c23ba5e94cd6f 100644
@@ -2556,6 +2556,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);
@@ -2567,7 +2568,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
author maintainer
#723 lore raw

PATCH 721/869 parisc: eisa_enumerator: Fix out-of-bounds reads of the EEPROM buffer

In reply to Greg Kroah-Hartman

6.18-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
index f0cb31198a8f0..aa41d3abc6c22 100644
@@ -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
author maintainer
#724 lore raw

PATCH 722/869 ASoC: tlv320aic32x4: Prevent division by zero in divider callbacks

In reply to Greg Kroah-Hartman

6.18-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.

Fixes a51b50062091 ("ASoC: tlv320aic32x4: Model DAC/ADC dividers in CCF")
---
 sound/soc/codecs/tlv320aic32x4-clk.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
sound/soc/codecs/tlv320aic32x4-clk.c +7 -1
index 5c0a76a4a106b..1a815de909097 100644
@@ -320,6 +320,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;
@@ -333,8 +336,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
author maintainer
#725 lore raw

PATCH 723/869 i2c: mt7621: fix copying uninitialized kernel stack with reduced page_len

In reply to Greg Kroah-Hartman

6.18-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.

Fixes d04913ec5f89 ("i2c: mt7621: Add MediaTek MT7621/7628/7688 I2C driver")
Cc <[email protected]> # v5.3+
---
 drivers/i2c/busses/i2c-mt7621.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/i2c/busses/i2c-mt7621.c +6 -3
index 0a288c998419b..9ea5e3f9a7632 100644
@@ -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
author maintainer
#726 lore raw

PATCH 724/869 spi: zynq-qspi: fix address buffer corruption and support 4-byte address

In reply to Greg Kroah-Hartman

6.18-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().

Fixes 67dca5e580f1 ("spi: spi-mem: Add support for Zynq QSPI controller")
---
 drivers/spi/spi-zynq-qspi.c | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)
drivers/spi/spi-zynq-qspi.c +7 -6
index 406fd9d5337ee..c9588fd1d1237 100644
@@ -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
author maintainer
#727 lore raw

PATCH 725/869 posix-cpu-timers: Fix pid refcount leak in do_cpu_nanosleep() signal path

In reply to Greg Kroah-Hartman

6.18-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
index b3d4bae9ee3e0..fcb98cbb1219b 100644
@@ -1597,8 +1597,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
author maintainer
#728 lore raw

PATCH 726/869 timekeeping: Update offsets on sequence counter retry in ktime_get_update_offsets_now()

In reply to Greg Kroah-Hartman

6.18-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
index 377e29ca5a521..32f59de2ba4ce 100644
@@ -2569,6 +2569,7 @@ ktime_t ktime_get_update_offsets_now(unsigned int *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;
@@ -2580,7 +2581,7 @@ ktime_t ktime_get_update_offsets_now(unsigned int *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
author maintainer
#729 lore raw

PATCH 727/869 cgroup: dont kill migrated processes through their exiting threads

In reply to Greg Kroah-Hartman

6.18-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.

Fixes da13e0e72a73 ("cgroup: fix cgroup.kill for exited thread group leader")
Cc [email protected] # v5.14+
---
 kernel/cgroup/cgroup.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/cgroup/cgroup.c +1 -1
index 28db81da10b81..aa629b7d76e53 100644
@@ -4229,7 +4229,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
author maintainer
#730 lore raw

PATCH 728/869 gve: fix out-of-bounds read in gve_get_flow_rule_entry()

In reply to Greg Kroah-Hartman

6.18-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
index 0bb8cd1876a3f..426a264af8b26 100644
@@ -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
author maintainer
#731 lore raw

PATCH 729/869 genirq/kexec: Do not take the bus lock of an interrupt chip on the crash path

In reply to Greg Kroah-Hartman

6.18-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
index d197854a93c8f..97e50ade3bb98 100644
@@ -78,6 +78,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
index 1a3deffe6b5b6..f245b98764225 100644
@@ -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
author maintainer
#732 lore raw

PATCH 730/869 veth: fix stale peer max_mtu on XDP program replacement

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 7cda76d858a4 ("veth: Allow jumbo frames in xdp mode")
---
 drivers/net/veth.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/net/veth.c +2 -3
index 148114ab85ac3..25cdbba5dfa9b 100644
@@ -1621,10 +1621,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
author maintainer
#733 lore raw

PATCH 731/869 scsi: ufs: bsg: Complete the job on error

In reply to Greg Kroah-Hartman

6.18-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
index bb6ff8ca5c7a8..237ade1f0cd83 100644
@@ -194,14 +194,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
author maintainer
#734 lore raw

PATCH 732/869 scsi: ufs: bsg: Clear the reply buffer before use

In reply to Greg Kroah-Hartman

6.18-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
index 237ade1f0cd83..0e0b08a3821c4 100644
@@ -142,7 +142,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
author maintainer
#735 lore raw

PATCH 733/869 scsi: ufs: core: Clear stale UIC result byte before peer DME retries

In reply to Greg Kroah-Hartman

6.18-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
index 52df1df6333aa..d225ad90cc392 100644
@@ -4219,9 +4219,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)
@@ -4285,9 +4288,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
author maintainer
#736 lore raw

PATCH 734/869 scsi: libiscsi_tcp: Prevent R2T range check overflow

In reply to Greg Kroah-Hartman

6.18-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
index d35f93451ee9b..3c9e736d45e7e 100644
@@ -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
author maintainer
#737 lore raw

PATCH 735/869 scsi: ufs: core: Remove an always-false WARN_ONCE()

In reply to Greg Kroah-Hartman

6.18-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
index d225ad90cc392..b3dbfd3552dc4 100644
@@ -5714,9 +5714,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
author maintainer
#738 lore raw

PATCH 736/869 scsi: ufs: core: Remove completed-without-interrupt path in ufshcd_abort()

In reply to Greg Kroah-Hartman

6.18-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
index b3dbfd3552dc4..97f86b6905b56 100644
@@ -7777,15 +7777,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
author maintainer
#739 lore raw

PATCH 737/869 compat: avoid double rounding in times()

In reply to Greg Kroah-Hartman

6.18-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.

Fixes f06febc96ba8 ("timers: fix itimer/many thread hang")
Cc Arnd Bergmann <[email protected]>
Cc Thomas Gleixner <[email protected]>
---
 kernel/sys.c | 3 +++
 1 file changed, 3 insertions(+)
kernel/sys.c +3 -0
index c8376d7a0741b..bc89bd1331119 100644
@@ -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
author maintainer
#740 lore raw

PATCH 738/869 stackdepot: stop preallocating after the final pool

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 31639fd6cebd ("stackdepot: use variable size records for non-evictable entries")
Cc Andrey Konovalov <[email protected]>
Cc Mikhail Gavrilov <[email protected]>
Cc Caleb Kan <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Vlastimil Babka <[email protected]>
---
 lib/stackdepot.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/stackdepot.c +1 -1
index de0b0025af2b9..b20f4db5c83f6 100644
@@ -322,7 +322,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
author maintainer
#741 lore raw

PATCH 739/869 ocfs2: snapshot the dentry name while tracing file release

In reply to Greg Kroah-Hartman

6.18-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
index a0df92a23498a..f4c36ce1678d0 100644
@@ -140,18 +140,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
author maintainer
#742 lore raw

PATCH 740/869 ocfs2/cluster: remove zero-address nodes from IP tree on teardown

In reply to Greg Kroah-Hartman

6.18-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
index 87aeb1a7a90ae..bfc7c0fb2be05 100644
@@ -626,8 +626,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
author maintainer
#743 lore raw

PATCH 741/869 mm/hugetlb: dont clear the resv_map of a VMA whose lock is held

In reply to Greg Kroah-Hartman

6.18-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.

[david: avoid local variable, move and refine comment, description cleanups+simplifications]
Fixes bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Jann Horn <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Naoya Horiguchi <[email protected]>
Cc Adam Litke <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Peter Xu <[email protected]>
Cc Kiryl Shutsemau <[email protected]>
Cc Mike Rapoport <[email protected]>
---
 mm/hugetlb.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
mm/hugetlb.c +11 -2
index 8832923dfbcd8..ed4fb48cb35b8 100644
@@ -8054,6 +8054,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
author maintainer
#744 lore raw

PATCH 742/869 mm/mremap: fix calling fixup_hugetlb_reservations() on the wrong VMA

In reply to Greg Kroah-Hartman

6.18-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.

Fixes b714ccb02a76 ("mm/mremap: complete refactor of move_vma()")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Jann Horn <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Naoya Horiguchi <[email protected]>
Cc Adam Litke <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Peter Xu <[email protected]>
Cc Kiryl Shutsemau <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Josef Bacik <[email protected]>
---
 mm/mremap.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/mremap.c +1 -1
index f0e63d3b3c148..f023b05dfb3d9 100644
@@ -1245,7 +1245,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
author maintainer
#745 lore raw

PATCH 743/869 mm/hugetlb: account migration target folio in per-node NR_HUGETLB vmstat

In reply to Greg Kroah-Hartman

6.18-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
index ed4fb48cb35b8..42aace6e3ca17 100644
@@ -2353,6 +2353,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;
 }
 
@@ -2360,24 +2365,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
author maintainer
#746 lore raw

PATCH 744/869 mm: disallow ioremaping ordinary RAM in generic_access_phys()

In reply to Greg Kroah-Hartman

6.18-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
index d755b5c1f1287..01d14ca0e74d2 100644
@@ -6808,6 +6808,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;
@@ -6822,6 +6823,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
author maintainer
#747 lore raw

PATCH 745/869 mm/madvise: add cond_resched() in THP branch of madvise_cold_or_pageout_pte_range()

In reply to Greg Kroah-Hartman

6.18-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
index 505a580cd9c4c..bb02220e1959b 100644
@@ -452,6 +452,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
author maintainer
#748 lore raw

PATCH 746/869 mm/mlock: use a long for the page count in mlock_fixup()

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Assisted-by LLM
Cc Liam R. Howlett <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Jann Horn <[email protected]>
---
 mm/mlock.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/mlock.c +1 -1
index 31045f17766a7..20061dd281502 100644
@@ -468,7 +468,7 @@ static int mlock_fixup(struct vma_iterator *vmi, struct vm_area_struct *vma,
 	       unsigned long end, vm_flags_t newflags)
 {
 	struct mm_struct *mm = vma->vm_mm;
-	int nr_pages;
+	long nr_pages;
 	int ret = 0;
 	vm_flags_t oldflags = vma->vm_flags;
 
Signature · 1 line
2.53.0
author maintainer
#749 lore raw

PATCH 747/869 userfaultfd: fix UFFDIO_MOVE livelock on large folio with extra references

In reply to Greg Kroah-Hartman

6.18-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.

Fixes adef440691ba ("userfaultfd: UFFDIO_MOVE uABI")
Assisted-by LLM
Cc Mike Rapoport <[email protected]>
Cc Peter Xu <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Andrea Arcangeli <[email protected]>
---
 mm/userfaultfd.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
mm/userfaultfd.c +5 -1
index 34798ce783e6c..579445bddf561 100644
@@ -1414,8 +1414,12 @@ static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd
 			pte_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
author maintainer
#750 lore raw

PATCH 748/869 mm/percpu: account full object size for percpu memory allocations

In reply to Greg Kroah-Hartman

6.18-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.

Fixes 60fa4a9e2323 ("mm: percpu: add codetag reference into pcpuobj_ext")
Assisted-by LLM # Verification
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Hao Ge <[email protected]>
---
 mm/percpu.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/percpu.c +3 -2
index 81462ce5866e1..32519523845b3 100644
@@ -1692,14 +1692,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
author maintainer
#751 lore raw

PATCH 749/869 mm/madvise: atomically clear the young bit on THP MADV_COLD

In reply to Greg Kroah-Hartman

6.18-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
index bb02220e1959b..729d8f2f07fd8 100644
@@ -428,10 +428,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
author maintainer
#752 lore raw

PATCH 750/869 ipc/shm: fix RSS accounting for hugetlb shared memory

In reply to Greg Kroah-Hartman

6.18-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.

Fixes a08c7193e4f1 ("mm/filemap: remove hugetlb special casing in filemap.c")
Cc Oscar Salvador <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Sidhartha Kumar <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Dan Carpenter <[email protected]>
Cc Baolin Wang <[email protected]>
---
 ipc/shm.c | 23 ++++-------------------
 1 file changed, 4 insertions(+), 19 deletions(-)
ipc/shm.c +4 -19
index c77a6c8683ce9..2f5cee0c78c7d 100644
@@ -936,26 +936,11 @@ static inline unsigned long copy_shminfo_to_user(void __user *buf, struct shminf
 static 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
author maintainer
#753 lore raw

PATCH 751/869 mm: vmscan: dont count per-node proactive reclaim as memory pressure

In reply to Greg Kroah-Hartman

6.18-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

Fixes b980077899ea ("mm: introduce per-node proactive reclaim interface")
Cc David Hildenbrand <[email protected]>
Cc Kairui Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Baoquan He <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Roman Gushchin <[email protected]>
---
 mm/vmscan.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
mm/vmscan.c +4 -2
index c983815bde5bf..6d53f83e9dbcf 100644
@@ -7642,7 +7642,8 @@ static unsigned long __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask,
 					   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);
 	/*
@@ -7666,7 +7667,8 @@ static unsigned long __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask,
 	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);
 
Signature · 1 line
2.53.0
author maintainer
#754 lore raw

PATCH 752/869 mm/swap: fix swap_cache_get_folio() returning a folio that left the swap cache

In reply to Greg Kroah-Hartman

6.18-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.

[[email protected]: add LLM-generated description of userspace impact]
Fixes 8578e0c00dcf ("mm, swap: use the swap table for the swap cache and switch API")
Cc Chris Li <[email protected]>
Cc Kemeng Shi <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Baoquan He <[email protected]>
Cc Barry Song <[email protected]>
Cc Youngjun Park <[email protected]>
---
 mm/swap_state.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
mm/swap_state.c +13 -3
index b8d7744b4436a..57cae6f6eac1e 100644
@@ -86,17 +86,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
author maintainer
#755 lore raw

PATCH 753/869 mm/page_alloc: count guard pages as free again when their buddy merges

In reply to Greg Kroah-Hartman

6.18-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.

Fixes e0932b6c1f94 ("mm: page_alloc: consolidate free page accounting")
Assisted-by LLM
Cc Suren Baghdasaryan <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Brendan Jackman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Baoquan He <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Frank van der Linden <[email protected]>
---
 mm/page_alloc.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
mm/page_alloc.c +4 -2
index b866357339c56..8bdc35efad26b 100644
@@ -1027,10 +1027,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
author maintainer
#756 lore raw

PATCH 754/869 mm/truncate: fix the zeroing end of pagecache_isize_extended()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Nickolai Zeldovich <[email protected]>

[ Upstream commit 8f9039840588dd618c72a726c192126bb7b98228 ]

A process that extends a file by 4 GiB or more past a dirty folio, on a file system whose block size is smaller than the page size (ext4 with 1k blocks), reads back the bytes it wrote through a shared mapping beyond the old end of file instead of zeroes, and a later write into that block carries them to the disk. With the example of commit 52aecaee1c26 ("mm:
zero range of eof folio exposed by inode size extension") and the truncate taken 4 GiB further (pwrite 2k at 0, mmap the first page and write 'X' over [2k, 4k), truncate(2) to 4 GiB + 2k), the read of [2k, 4k) returns the 2048 'X' bytes, and a pwrite of 16 bytes at 3k followed by fsync() and a remount leaves 1008 'X' bytes on the disk in [3k+16, 4k). No privilege is needed, and every size extension of 4 GiB or more reaches it:
truncate(2)/ftruncate(2) through truncate_setsize(), writes beyond the end of file through generic_write_end(), ext4, iomap, btrfs, exfat, ntfs, afs and orangefs. Affected since v6.13.

pagecache_isize_extended() zeroes the part of the dirty folio straddling the old end of file that the size extension exposes, from the old size to the new size or the end of the folio, whichever comes first:

	end = min_t(unsigned int, to - folio_pos(folio), folio_size(folio));

min_t() converts both operands to unsigned int before comparing, so the loff_t difference to - folio_pos(folio) is reduced modulo 2^32 first. When the file grows by 4 GiB or more past the folio, end is that residue instead of folio_size(folio): below offset nothing is zeroed, above it only [offset, end) is. The bytes beyond the old end of file stay in the dirty folio and, now inside i_size, are file data.

Compare in loff_t; the result is at most folio_size(folio) and fits end.

Found while formally verifying pagecache_isize_extended() against the kernel binary.

Fixes 52aecaee1c26 ("mm: zero range of eof folio exposed by inode size extension")
Assisted-by LLM
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Brian Foster <[email protected]>
Cc Theodore Ts'o <[email protected]>
---
 mm/truncate.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
mm/truncate.c +1 -2
index 9b1baa688a104..3534bc320a9c5 100644
@@ -880,8 +880,7 @@ void pagecache_isize_extended(struct inode *inode, loff_t from, loff_t to)
 		unsigned int offset, end;
 
 		offset = from - folio_pos(folio);
-		end = min_t(unsigned int, to - folio_pos(folio),
-			    folio_size(folio));
+		end = min_t(loff_t, to - folio_pos(folio), folio_size(folio));
 		folio_zero_segment(folio, offset, end);
 	}
 
Signature · 1 line
2.53.0
author maintainer
#757 lore raw

PATCH 755/869 mm/mremap: populate calculated fields in vrm state correctly

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Lorenzo Stoakes (ARM) <[email protected]>

[ Upstream commit 34e753f8d927069785f6b675f5769da5da4ef78e ]

Commit d5c8aec0542e ("mm/mremap: initial refactor of move_vma()") introduced the vma_remap_struct helper to pass state sanely through mremap() logic.

Part of this state is vrm->delta - equal to the absolute difference between vrm->old_len and vrm->new_len (the old and new lengths of the VMA, respectively).

This value is used to correctly charge accounted VMAs.

When shrinking a VMA, mremap_to() sets vrm->old_len equal to vrm->new_len having performed the shrink of the VMA first, prior to any potential move (e.g. MREMAP_FIXED | MREMAP_MAYMOVE specified).

However it does not recalculate vrm->delta, which results in incorrectly overcharging the VMA when both moving and shrinking a VMA.

The charge leaks to Committed_AS globally, meaning a mischievous user can cause allocations to fail across the system in strict overcommit mode.

Resolve the issue by abstracting the update of vrm->delta to vrm_populate_calculated() and invoking this from mremap_to() when vrm->old_len is changed.

Additionally, update vrm->remap_type whose value depends on vrm->delta. The field is not read again after the shrink, but it is the logically correct thing to do and protects against future changes which break this.

---
 mm/mremap.c | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)
mm/mremap.c +9 -8
index f023b05dfb3d9..593e6f94eba3d 100644
@@ -874,12 +874,6 @@ unsigned long move_page_tables(struct pagetable_move_control *pmc)
 	return pmc_progress(pmc);
 }
 
-/* Set vrm->delta to the difference in VMA size specified by user. */
-static void vrm_set_delta(struct vma_remap_struct *vrm)
-{
-	vrm->delta = abs_diff(vrm->old_len, vrm->new_len);
-}
-
 /* Determine what kind of remap this is - shrink, expand or no resize at all. */
 static enum mremap_type vrm_remap_type(struct vma_remap_struct *vrm)
 {
@@ -892,6 +886,13 @@ static enum mremap_type vrm_remap_type(struct vma_remap_struct *vrm)
 	return MREMAP_EXPAND;
 }
 
+/* Populate calculated fields. */
+static void vrm_populate_calculated(struct vma_remap_struct *vrm)
+{
+	vrm->delta = abs_diff(vrm->old_len, vrm->new_len);
+	vrm->remap_type = vrm_remap_type(vrm);
+}
+
 /*
  * When moving a VMA to vrm->new_adr, does this result in the new and old VMAs
  * overlapping?
@@ -1422,6 +1423,7 @@ static unsigned long mremap_to(struct vma_remap_struct *vrm)
 
 		/* Set up for the move now shrink has been executed. */
 		vrm->old_len = vrm->new_len;
+		vrm_populate_calculated(vrm);
 	}
 
 	/* MREMAP_DONTUNMAP expands by old_len since old_len == new_len */
@@ -1694,8 +1696,7 @@ static int check_prep_vma(struct vma_remap_struct *vrm)
 	if (is_vm_hugetlb_page(vma) && !align_hugetlb(vrm))
 		return -EINVAL;
 
-	vrm_set_delta(vrm);
-	vrm->remap_type = vrm_remap_type(vrm);
+	vrm_populate_calculated(vrm);
 	/* For convenience, we set new_addr even if VMA won't move. */
 	if (!vrm_implies_new_addr(vrm))
 		vrm->new_addr = addr;
Signature · 1 line
2.53.0
author maintainer
#758 lore raw

PATCH 756/869 mm/mremap: correctly uncharge accountable VMAs in error path

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Lorenzo Stoakes (ARM) <[email protected]>

[ Upstream commit 65e722a74df992719676ead85a9e93fb2b5a0983 ]

The mremap error path is a fragile and unwieldy beast - it reverses the page table move then updates vma_remap_struct state to swap VMA, length and address between old and new VMAs in copy_vma_and_data().

If the mremap() operation didn't specify MREMAP_DONTUNMAP then its caller, move_vma(), invokes unmap_source_vma(), which unmaps the new VMA rather than the old one.

For accountable VMAs when MREMAP_DONTUNMAP is not specified, unmap_source_vma() unsets VMA_ACCOUNT_BIT during this unmap in order that only the delta of a VMA expansion is charged (performed by vrm_calc_charge() earlier).

Therefore nothing uncharges the expanded VMA size, and there is a permanent leak in global Committed_AS.

Resolve the issue by uncharging when MREMAP_DONTUNMAP is not specified.

Fixes fdbef6149135 ("mm/mremap: don't account pages in vma_to_resize()")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Jann Horn <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Brian Geffon <[email protected]>
Cc Dmitry Safonov <[email protected]>
---
 mm/mremap.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
mm/mremap.c +14 -0
index 593e6f94eba3d..8ed7c50e499b8 100644
@@ -1239,6 +1239,20 @@ static int copy_vma_and_data(struct vma_remap_struct *vrm,
 		pmc_revert.need_rmap_locks = true;
 		move_page_tables(&pmc_revert);
 
+		/*
+		 * When copy_vma_and_data() returns, the new VMA will be
+		 * unmapped rather than the old one.
+		 *
+		 * When an accountable move is being performed, this unmapping
+		 * will not uncharge any expansion, so do that now.
+		 *
+		 * A move is accountable if the VMA is accountable and
+		 * MREMAP_DONTUNMAP is not specified, so only do so if the
+		 * latter is true.
+		 */
+		if (!(vrm->flags & MREMAP_DONTUNMAP))
+			vrm_uncharge(vrm);
+
 		vrm->vma = new_vma;
 		vrm->old_len = vrm->new_len;
 		vrm->addr = vrm->new_addr;
Signature · 1 line
2.53.0
author maintainer
#759 lore raw

PATCH 757/869 mm/vmscan: reclaim every zone in per-node proactive reclaim

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Gregory Price (Meta) <[email protected]>

[ Upstream commit d0a12d80d2f7e9f4ed2030b6f04c8a897956bf84 ]

user_proactive_reclaim() limits per-node reclaim to gfp_zone(GFP_KERNEL), which is ZONE_NORMAL. Proactive reclaim serves no allocation, but that limit makes shrink_node() skip every ZONE_MOVABLE folio, so writing to /sys/devices/system/node/nodeN/reclaim never reclaims a node's movable memory. A movable-only node, such as dax/kmem or hotplugged memory onlined movable, reclaims nothing and fails with -EAGAIN.

To reproduce, fill a movable-only node with clean page cache and write 200M to its nodeN/reclaim: the write fails with -EAGAIN and the page cache stays. The same write to a ZONE_NORMAL node frees 200MB.

Scan every zone, as memory.reclaim does.

---
 mm/vmscan.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/vmscan.c +1 -1
index 6d53f83e9dbcf..8fb0d79a00b9e 100644
@@ -7825,7 +7825,7 @@ int user_proactive_reclaim(char *buf,
 		} else {
 			struct scan_control sc = {
 				.gfp_mask = current_gfp_context(gfp_mask),
-				.reclaim_idx = gfp_zone(gfp_mask),
+				.reclaim_idx = MAX_NR_ZONES - 1,
 				.proactive_swappiness = swappiness == -1 ? NULL : &swappiness,
 				.priority = DEF_PRIORITY,
 				.may_writepage = !laptop_mode,
Signature · 1 line
2.53.0
author maintainer
#760 lore raw

PATCH 758/869 mm/mempolicy: apply bind policies against the scoped allocation zone

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Gregory Price (Meta) <[email protected]>

[ Upstream commit d4ea410ce4b8aa46a316476ea2624a357bf31fa9 ]

QEMU fails to start a guest with a VFIO device when guest RAM comes from a memory backend bound to a movable-only node:

vfio_container_dma_map(0x55b1b1317800, 0x0, 0x10000000,
0x7f39a2200000)
= -12 (Cannot allocate memory)

VFIO pins guest RAM when the device is realized, and the pin faults the pages in. io_uring fixed buffers fail the same way. Faulting the range in before pinning lets the same pin succeed, since resident pages are migrated off the node instead.

A long-term pin faults under memalloc_pin_save(). PF_MEMALLOC_PIN makes current_gfp_context() clear __GFP_MOVABLE, but policy_nodemask() tests apply_policy_zone() against the caller's gfp.

The bind keeps its movable-only nodemask, and the allocation finds no usable zone:

page allocation failure:

      order:0,
      mode:0x140dc2(GFP_HIGHUSER|__GFP_ZERO|__GFP_COMP),
      nodemask=1,cpuset=/,mems_allowed=0-1
  Call Trace:
   warn_alloc+0x136/0x150
   __alloc_frozen_pages_noprof+0xed8/0x1720
   alloc_pages_mpol+0xaa/0x170
   vma_alloc_folio_noprof+0x65/0xd0
   __handle_mm_fault+0x137b/0x1ac0
   handle_mm_fault+0xa0/0x270
   __get_user_pages+0x250/0xfd0
   __gup_longterm_locked+0x116/0x870
   gup_fast_fallback+0xcfc/0xdf0
   pin_user_pages_fast+0x47/0x60
   io_pin_pages+0x9a/0x110

Base page faults fail with -ENOMEM.
hugetlb faults fail with -EFAULT.

Check the policy zone against current_gfp_context(gfp), so a pin-scoped fault falls back off the movable-only nodemask, like any other non-movable allocation under the same bind.

Tested in qemu with a dax/kmem movable-only node 1. io_uring and VFIO pins of unfaulted base pages and 2MB hugetlb pages now succeed and land on node 0 (correct). QEMU now starts with the same backend binding.

Fixes 8e3560d963d2 ("mm: honor PF_MEMALLOC_PIN for all movable pages")
Cc David Hildenbrand <[email protected]>
Cc Zi Yan <[email protected]>
Cc Rakie Kim <[email protected]>
Cc Ying Huang <[email protected]>
Cc Pasha Tatashin <[email protected]>
Cc Michal Hocko <[email protected]>
---
 mm/mempolicy.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/mempolicy.c +1 -1
index 197a5ea0d76d9..919a505cabaee 100644
@@ -2206,7 +2206,7 @@ static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *pol,
 		break;
 	case MPOL_BIND:
 		/* Restrict to nodemask (but not on lower zones) */
-		if (apply_policy_zone(pol, gfp_zone(gfp)) &&
+		if (apply_policy_zone(pol, gfp_zone(current_gfp_context(gfp))) &&
 		    cpuset_nodemask_valid_mems_allowed(&pol->nodes))
 			nodemask = &pol->nodes;
 		if (pol->home_node != NUMA_NO_NODE)
Signature · 1 line
2.53.0
author maintainer
#761 lore raw

PATCH 759/869 riscv: mm: exclude invalid THP PMDs from page table check

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yunhui Cui <[email protected]>

[ Upstream commit bdda2887cbf3937c2d0f56589c2124c4167324e1 ]

RISC-V THP splitting uses a temporary invalid PMD state where pmd_mkinvalid() clears _PAGE_PRESENT and _PAGE_PROT_NONE but leaves _PAGE_LEAF set so the MM code can still recognize the PMD as a THP split in-progress entry.

That temporary state no longer describes a user-accessible mapping, but page_table_check currently treats it as one because the RISC-V PMD user-accessibility test only checks whether the PMD is a leaf and has user permissions.

As a result, when a PMD-sized anonymous THP is split during a COW fault, page_table_check can account the invalid intermediate PMD as a live PMD mapping, and then account the replacement PTE mappings again when the split installs the PTE table. This leaves stale PMD accounting behind and later triggers page_table_check failures such as a non-zero anon_map_count when the folio is freed.

Fix this by tightening pmd_user_accessible_page() so PMD page-table-check accounting only considers leaf PMDs that still carry either _PAGE_PRESENT or _PAGE_PROT_NONE. This preserves the THP split semantics required by the MM code while preventing page_table_check from treating invalid split PMDs as live user mappings.

With CONFIG_PAGE_TABLE_CHECK=y and CONFIG_PAGE_TABLE_CHECK_ENFORCED=y, tools/testing/selftests/mm/cow completes successfully on RISC-V after this change.

Fixes 3fee229a8eb9 ("riscv/mm: enable ARCH_SUPPORTS_PAGE_TABLE_CHECK")
Cc Albert Ou <[email protected]>
Cc Palmer Dabbelt <[email protected]>
Cc Pasha Tatashin <[email protected]>
Cc Paul Walmsley <[email protected]>
Cc tongtiangen <[email protected]>
Cc Alexandre Ghiti <[email protected]>
Cc David Hildenbrand (Arm) <[email protected]>
Cc Vivian Wang <[email protected]>
Cc Yaxing Guo <[email protected]>
---
 arch/riscv/include/asm/pgtable.h | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
arch/riscv/include/asm/pgtable.h +8 -1
index 9b2e967c9fe08..420d402336d0b 100644
@@ -833,7 +833,14 @@ static inline bool pte_user_accessible_page(pte_t pte)
 
 static inline bool pmd_user_accessible_page(pmd_t pmd)
 {
-	return pmd_leaf(pmd) && pmd_user(pmd);
+	/*
+	 * page_table_check() must ignore THP split invalidation entries created by
+	 * pmd_mkinvalid(). These retain _PAGE_LEAF so pmd_present()/pmd_leaf() stay
+	 * true during the split, but they no longer describe a user-accessible
+	 * mapping once both _PAGE_PRESENT and _PAGE_PROT_NONE are cleared.
+	 */
+	return (pmd_val(pmd) & (_PAGE_PRESENT | _PAGE_PROT_NONE)) &&
+		(pmd_val(pmd) & _PAGE_LEAF) && pmd_user(pmd);
 }
 
 static inline bool pud_user_accessible_page(pud_t pud)
Signature · 1 line
2.53.0
author maintainer
#762 lore raw

PATCH 760/869 mm: multi-gen LRU: fix NULL lruvec->pgdat deref with memcg disabled on cmdline

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Siddharth Chintamaneni <[email protected]>

[ Upstream commit 183895979c441e52dbd651b388553b09eaa35cfa ]

When CONFIG_MEMCG=y, lruvec_pgdat() returns lruvec->pgdat, which for the per-node pgdat->__lruvec is left NULL by lruvec_init() and only filled in lazily by mem_cgroup_lruvec(). Normally that happens early, e.g. on the first folio_add_lru().

With cgroup_disable=memory, lru_gen_shrink_node() passes &pgdat->__lruvec directly to shrink_one(). If direct reclaim runs before anything has called mem_cgroup_lruvec() for the node, which can happen during early boot under memory pressure (e.g. a kdump kernel), get_swappiness() ends up dereferencing a NULL pgdat:

  Unable to handle kernel NULL pointer dereference at virtual address 0000000000005040
  pc : get_swappiness+0x68/0xb0
  lr : try_to_shrink_lruvec+0x54/0x2c0
  Call trace:
   get_swappiness+0x68/0xb0 (P)
   try_to_shrink_lruvec+0x54/0x2c0
   shrink_one+0x8c/0x240
   shrink_node+0xc6c/0xe08
   do_try_to_free_pages+0xdc/0x570
   try_to_free_pages+0x124/0x278
   __alloc_frozen_pages_noprof+0x6e8/0xf78
   alloc_pages_mpol+0xc4/0x1c0
   alloc_frozen_pages_noprof+0x54/0xe8
   alloc_pages_noprof+0x1c/0x40
   atomic_pool_expand+0x98/0x300
   __dma_atomic_pool_init+0x58/0xd8
   dma_atomic_pool_init+0x154/0x170
   do_one_initcall+0x64/0x350
   kernel_init_freeable+0x214/0x430
   kernel_init+0x2c/0x208
   ret_from_fork+0x10/0x20

The classic LRU path and MGLRU before per-node lru_gen_folio lists obtained the lruvec through mem_cgroup_lruvec(), which sets lruvec->pgdat.

The above was hit on an arm64 kdump kernel (6.18-based) booted with cgroup_disable=memory nr_cpus=4. It also reproduces on mainline on an arm64 VM with CONFIG_ARM64_64K_PAGES=y, CONFIG_MEMCG=y, CONFIG_LRU_GEN_ENABLED=y and:

mem=160M nr_cpus=4 coherent_pool=512M cgroup_disable=memory

These options only serve to force direct reclaim early in boot; with 160M the boot eventually ends in OOM regardless. On mainline the first LRU reclaim happens while unpacking the initramfs, and faults the same way:

  Unable to handle kernel NULL pointer dereference at virtual address 0000000000005040
  pc : get_swappiness+0xd4/0x150
  Call trace:
   get_swappiness+0xd4/0x150 (P)
   try_to_shrink_lruvec+0x44/0x2b8
   shrink_one+0x80/0x1a0
   shrink_node+0xd98/0xea8
   do_try_to_free_pages+0xf4/0x4b0
   try_to_free_pages+0x110/0x360
   __alloc_frozen_pages_noprof+0x8b0/0x1718
   ...
   __filemap_get_folio_mpol+0x2ac/0x548
   simple_write_begin+0x44/0xf8
   page_symlink+0x178/0x198
   ...
   do_populate_rootfs+0x13c/0x200
Fixes e4dde56cd208 ("mm: multi-gen LRU: per-node lru_gen_folio lists")
Assisted-by LLM
Cc Johannes Weiner <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Kairui Song <[email protected]>
Cc Axel Rasmussen <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Wei Xu <[email protected]>
Cc Baoquan He <[email protected]>
Cc Yu Zhao <[email protected]>
Cc <[email protected]> # 6.3+
---
 mm/vmscan.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/vmscan.c +1 -1
index 8fb0d79a00b9e..e72d50bab730a 100644
@@ -5082,7 +5082,7 @@ static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *
 		sc->nr_reclaimed = 0;
 
 	if (mem_cgroup_disabled())
-		shrink_one(&pgdat->__lruvec, sc);
+		shrink_one(mem_cgroup_lruvec(NULL, pgdat), sc);
 	else
 		shrink_many(pgdat, sc);
 
Signature · 1 line
2.53.0
author maintainer
#763 lore raw

PATCH 761/869 fscrypt: Fix missing barrier in fscrypt_find_mode_key()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Baokun Li <[email protected]>

[ Upstream commit cf66375465b9ca531f5c294f468db1df293c178c ]

fscrypt_find_mode_key() walks an RCU list and hands out a per-mode key without an acquire:

setup task
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
setup_per_mode_enc_key()

   ├─ fscrypt_prepare_key()
   │  └─ fscrypt_prepare_inline_crypt_key()
   │     └─ blk_crypto_start_using_key()
   │        └─ blk_crypto_fallback_start_using_mode()
   │           ├─ init profile, keyslots, tfms[]
   │           └─ smp_store_release(tfms_inited[mode])  # init order
   └─ list_add_tail_rcu(&new_node->link, ...)  # release -> finder

finding task (later submits the I/O itself)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
fscrypt_find_mode_key()

   ├─ list_for_each_entry_rcu(node, ...)
   └─ return &node->key                 # no acquire, chain breaks
  ...
  blk_crypto_fallback_bio_prep()        # WRITE path
   ├─ tfms_inited[mode]                 # addr-dep, reads true
   ├─ blk_crypto_fallback_profile       # no dependency
   ├─ blk_crypto_keyslots               # no dependency
   └─ slotp->tfms[mode]                 # no dependency

RCU publishes the node and the key reachable from it, so tfms_inited[mode] reads true through the address dependency. The independent fallback globals are not covered by it and can be read as uninitialized.

On a weakly ordered machine, a WRITE bio can crash in blk_crypto_get_keyslot() or crypto_sync_skcipher_setkey().

Other tasks reach the key through fscrypt_inode_info's cmpxchg_release()/smp_load_acquire(), which is already ordered after the list walk; only the finding task's own later I/O was not.

Fix this by upgrading the control dependency to an acquire with smp_acquire__after_ctrl_dep() once a matching entry has been found.

---
 fs/crypto/keysetup.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
fs/crypto/keysetup.c +7 -1
index f27997ef9a08c..707552228ed62 100644
@@ -207,8 +207,14 @@ fscrypt_find_mode_key(struct fscrypt_master_key *mk, u8 hkdf_context,
 		if (node->hkdf_context == hkdf_context &&
 		    node->mode_num == mode_num &&
 		    node->data_unit_bits == ci->ci_data_unit_bits &&
-		    fscrypt_is_key_prepared(&node->key, ci))
+		    fscrypt_is_key_prepared(&node->key, ci)) {
+			/*
+			 * Upgrade the RCU dereference to a full ACQUIRE, so
+			 * that blk-crypto global state is seen as initialized.
+			 */
+			smp_acquire__after_ctrl_dep();
 			return &node->key;
+		}
 	}
 	return NULL;
 }
Signature · 1 line
2.53.0
author maintainer
#764 lore raw

PATCH 762/869 fbdev: atmel_lcdfb: fix list_first_entry() on possibly empty modelist in probe

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Wang Haoran <[email protected]>

[ Upstream commit 01d1204582f16e8b7bfce29648e5cf77a585d962 ]

list_first_entry() does not return NULL on an empty list; it returns a bogus pointer computed by container_of() from the list head. atmel_lcdfb_probe() initializes info->modelist with INIT_LIST_HEAD() and later takes its first entry with list_first_entry(), assuming atmel_lcdfb_of_init() populated it. However, atmel_lcdfb_of_init() drops the return value of fb_add_videomode() — unlike every other fallible call in the same function — so if fb_add_videomode() fails (its internal kmalloc can return -ENOMEM under memory pressure or fault injection), the list stays empty while of_init() reports success. The probe path then dereferences the bogus pointer in fb_videomode_to_var(&info->var, &modelist->mode). Because the bogus pointer lands inside the contiguous fb_info allocation, this may not fault immediately; instead it silently reads adjacent memory as a struct fb_videomode and programs garbage timing parameters into the LCD controller. This was found by code audit; we do not have Atmel hardware to reproduce it.

Fix this on two levels: check the return value of fb_add_videomode() in atmel_lcdfb_of_init() so the failure is propagated (root cause), and use list_first_entry_or_null() in atmel_lcdfb_probe() with a NULL check that fails probe gracefully with -EINVAL (defense in depth), consistent with the surrounding error handling which bails out to stop_clk.

---
 drivers/video/fbdev/atmel_lcdfb.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/video/fbdev/atmel_lcdfb.c +10 -3
index 35862e83f7afa..2b602ad004dd9 100644
@@ -1009,7 +1009,9 @@ static int atmel_lcdfb_of_init(struct atmel_lcdfb_info *sinfo)
 	if (ret < 0)
 		goto put_display_node;
 
-	fb_add_videomode(&fb_vm, &info->modelist);
+	ret = fb_add_videomode(&fb_vm, &info->modelist);
+	if (ret < 0)
+		goto put_display_node;
 
 put_display_node:
 	of_node_put(display_np);
@@ -1077,8 +1079,13 @@ static int atmel_lcdfb_probe(struct platform_device *pdev)
 	}
 	atmel_lcdfb_start_clock(sinfo);
 
-	modelist = list_first_entry(&info->modelist,
-			struct fb_modelist, list);
+	modelist = list_first_entry_or_null(&info->modelist,
+					    struct fb_modelist, list);
+	if (!modelist) {
+		dev_err(dev, "no video mode available\n");
+		ret = -EINVAL;
+		goto stop_clk;
+	}
 	fb_videomode_to_var(&info->var, &modelist->mode);
 
 	atmel_lcdfb_check_var(&info->var, info);
Signature · 1 line
2.53.0
author maintainer
#765 lore raw

PATCH 763/869 timers/itimer: Keep a nonzero value at CPU timer expiry

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hungyu Lin <[email protected]>

[ Upstream commit ef60f61208a30eb5b941b707debdf04517271b4f ]

get_cpu_itimer() returns a zero remaining time when the sampled CPU time is exactly equal to the nonzero expiry. This makes an armed ITIMER_VIRTUAL or ITIMER_PROF timer appear disarmed.

The cputime cleanup replaced cputime_le(), which implements <=, with <. Restore the inclusive comparison so the equality case returns TICK_NSEC, like the overdue case and set_process_cpu_timer().

Fixes 648616343cdb ("[S390] cputime: add sparse checking and cleanup")
---
 kernel/time/itimer.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/time/itimer.c +1 -1
index 03a32dffc56cc..f7de39769095f 100644
@@ -60,7 +60,7 @@ static void get_cpu_itimer(struct task_struct *tsk, unsigned int clock_id,
 		thread_group_sample_cputime(tsk, samples);
 		t = samples[clock_id];
 
-		if (val < t)
+		if (val <= t)
 			/* about to fire */
 			val = TICK_NSEC;
 		else
Signature · 1 line
2.53.0
author maintainer
#766 lore raw

PATCH 764/869 time/namespace: Fix overflow when converting absolute deadlines

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hungyu Lin <[email protected]>

[ Upstream commit d69cfd33b5a8d176124c564513b9ceb933595d93 ]

do_timens_ktime_to_host() subtracts the namespace offset from an absolute deadline and clamps the result to [0, KTIME_MAX]. A negative offset can make a large deadline overflow to a negative value. Since ktime_t is signed and KTIME_MAX is its maximum value, the subsequent comparison against KTIME_MAX can never detect this overflow.

For example, with a -1 second boottime offset, an absolute CLOCK_BOOTTIME timerfd deadline of KTIME_MAX can expire immediately. An absolute clock_nanosleep() using the same clock and deadline can also return immediately instead of waiting.

The earlier tim < offset check already handles the lower bound. A negative subtraction result in the remaining branch therefore indicates overflow. Detect that result and clamp it to KTIME_MAX.

Fixes 89dd8eecfe961 ("time: Add do_timens_ktime_to_host() helper")
---
 kernel/time/namespace.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/time/namespace.c +1 -1
index 99dcdb3315db7..632f331572847 100644
@@ -51,7 +51,7 @@ ktime_t do_timens_ktime_to_host(clockid_t clockid, ktime_t tim,
 		tim = 0;
 	} else {
 		tim = ktime_sub(tim, offset);
-		if (unlikely(tim > KTIME_MAX))
+		if (unlikely(tim < 0))
 			tim = KTIME_MAX;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#767 lore raw

PATCH 765/869 KVM: arm64: Set HCR_EL2.BSU to Inner Shareable for guests

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Fuad Tabba <[email protected]>

[ Upstream commit 00e73757518020273ccf6308a51f214e58c21ad5 ]

KVM sets HCR_EL2.BSU to Inner Shareable for guests, so that a guest's barriers cover the TLB and I-cache invalidations that HCR_EL2.FB broadcasts. However, since HCR_BSU_IS became an alias of the generated HCR_EL2_BSU_IS, it is the unshifted field value 0b01, which sets bit 0 (VM, already set) and leaves BSU at 0b00. A guest's DSB NSH is then not required to wait for a broadcast TLBI to complete on other CPUs.

Build the field with SYS_FIELD_PREP_ENUM().

Fixes d0f39259eff4 ("arm64: sysreg: Add layout for HCR_EL2")
---
 arch/arm64/include/asm/kvm_arm.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm64/include/asm/kvm_arm.h +1 -1
index 1da290aeedce7..641276868a653 100644
@@ -98,7 +98,7 @@
  * TID1:	Trap REVIDR_EL1, AIDR_EL1, and SMIDR_EL1
  */
 #define HCR_GUEST_FLAGS (HCR_TSC | HCR_TSW | HCR_TWE | HCR_TWI | HCR_VM | \
-			 HCR_BSU_IS | HCR_FB | HCR_TACR | \
+			 SYS_FIELD_PREP_ENUM(HCR_EL2, BSU, IS) | HCR_EL2_FB | HCR_EL2_TACR | \
 			 HCR_AMO | HCR_SWIO | HCR_TIDCP | HCR_RW | HCR_TLOR | \
 			 HCR_FMO | HCR_IMO | HCR_PTW | HCR_TID3 | HCR_TID1)
 #define HCR_HOST_NVHE_FLAGS (HCR_RW | HCR_API | HCR_APK | HCR_ATA)
Signature · 1 line
2.53.0
author maintainer
#768 lore raw

PATCH 766/869 ceph: avoid pending truncate during nonblocking cap acquire

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Max Kellermann <[email protected]>

[ Upstream commit 979b7ed4457a04c5a41c36f86052ecc6b76c67d9 ]

Readahead acquires caps while the folios are locked. This can deadlock when processing a pending truncate; truncate_pagecache() can then attempt to a folio that is already locked.

Return -EAGAIN instead when NON_BLOCKING is set, causing the readahead to be abandoned.

Fixes 49870056005c ("ceph: convert ceph_readpages to ceph_readahead")
---
 fs/ceph/caps.c | 4 ++++
 1 file changed, 4 insertions(+)
fs/ceph/caps.c +4 -0
index 91cb305815cbd..7ce1af5b61c88 100644
@@ -2878,6 +2878,10 @@ static int try_get_cap_refs(struct inode *inode, int need, int want,
 	}
 
 	/* finish pending truncate */
+	if (ci->i_truncate_pending && (flags & NON_BLOCKING)) {
+		ret = -EAGAIN;
+		goto out_unlock;
+	}
 	while (ci->i_truncate_pending) {
 		spin_unlock(&ci->i_ceph_lock);
 		if (snap_rwsem_locked) {
Signature · 1 line
2.53.0
author maintainer
#769 lore raw

PATCH 767/869 ceph: fix out-of-bounds read in ceph_netfs_issue_op_inline()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Guanglei Zhu <[email protected]>

[ Upstream commit cdbb60f00f87297a9db2652847dfc0eaaf3c45aa ]

The read offset is validated against i_size but never against inline_len, and the two fields come from the MDS independently. When a read starts past the end of the inline data, the subtraction

	len = min_t(size_t, iinfo->inline_len - subreq->start, subreq->len);

underflows and min_t() ends up with subreq->len, so copy_to_iter() reads past the end of the inline buffer straight into the user buffer. A malicious or buggy MDS reporting a short inline payload together with an inflated i_size can thus leak kernel heap memory to userspace.

Bail out with -ENODATA when the offset is not within the inline data.

Fixes 5b19f1eba459 ("ceph: make ceph_netfs_issue_op() handle inlined data")
---
 fs/ceph/addr.c | 6 ++++++
 1 file changed, 6 insertions(+)
fs/ceph/addr.c +6 -0
index cfbd88412f047..f58eba5456e36 100644
@@ -314,6 +314,12 @@ static bool ceph_netfs_issue_op_inline(struct netfs_io_subrequest *subreq)
 		return false;
 	}
 
+	if (subreq->start >= iinfo->inline_len) {
+		ceph_mdsc_put_request(req);
+		err = -ENODATA;
+		goto out;
+	}
+
 	len = min_t(size_t, iinfo->inline_len - subreq->start, subreq->len);
 	err = copy_to_iter(iinfo->inline_data + subreq->start, len, &subreq->io_iter);
 	if (err == 0) {
Signature · 1 line
2.53.0
author maintainer
#770 lore raw

PATCH 768/869 ceph: reject mdsmaps that claim more than CEPH_MAX_MDS ranks

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Xiang Mei <[email protected]>

[ Upstream commit c1742590d2b2fc5fb217e1a9b520108f1fe282e5 ]

check_new_map() sizes its export-target bitmap from CEPH_MAX_MDS but walks it with newmap->possible_max_rank, which comes straight off the wire:
ceph_mdsmap_decode() sets it to max(m_num_active_mds, m_max_mds), then overwrites it with the size of the "in" set. Neither is bounded by CEPH_MAX_MDS, only by m_info allocating, so a monitor announcing more ranks than the bitmap holds makes test_bit() read past the end of targets[]. The clear_bit() loop above indexes the same bitmap, though it is additionally bounded by mdsc->max_sessions. The map arrives on the monitor connection, which is unauthenticated in legacy msgr mode.

CEPH_MAX_MDS is a protocol constant from src/mds/mdstypes.h, and the reserved inode ranges in super.h are laid out one rank apart over that span, so a map claiming more ranks is corrupt. Reject it where the rank space is established rather than letting the count reach check_new_map().

  BUG: KASAN: stack-out-of-bounds in check_new_map (fs/ceph/mds_client.c:5968)
  Read of size 8 at addr ffffc90000ac7798 by task kworker/1:2/127
  Workqueue: ceph-msgr ceph_con_workfn
  Call Trace:
   <TASK>
   dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120)
   print_report (mm/kasan/report.c:378 mm/kasan/report.c:482)
   kasan_report (mm/kasan/report.c:595)
   kasan_check_range (mm/kasan/generic.c:186 mm/kasan/generic.c:200)
   check_new_map (fs/ceph/mds_client.c:5968)
   ceph_mdsc_handle_mdsmap (fs/ceph/mds_client.c:7060)
   extra_mon_dispatch (fs/ceph/super.c:802)
   mon_dispatch (net/ceph/mon_client.c:1483)
   ceph_con_process_message (net/ceph/messenger.c:1424)
   ceph_con_v1_try_read (net/ceph/messenger_v1.c:1430)
   ceph_con_workfn (net/ceph/messenger.c:1576)
   process_one_work (kernel/workqueue.c:3396)
   worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560)
   kthread (kernel/kthread.c:436)
   ret_from_fork (arch/x86/kernel/process.c:158)
   ret_from_fork_asm (arch/x86/entry/entry_64.S:245)
   </TASK>
  The buggy address belongs to stack of task kworker/1:2/127
   and is located at offset 288 in frame:
   check_new_map (fs/ceph/mds_client.c:5846)
  This frame has 1 object:
   [32, 288) 'targets'
Fixes d517b3983dd3 ("ceph: reconnect to the export targets on new mdsmaps")
Reported-by [email protected]
Assisted-by LLM
---
 fs/ceph/mdsmap.c | 8 ++++++++
 1 file changed, 8 insertions(+)
fs/ceph/mdsmap.c +8 -0
index c91c0e2e118ba..0fd578f0b2cd2 100644
@@ -170,6 +170,10 @@ struct ceph_mdsmap *ceph_mdsmap_decode(struct ceph_mds_client *mdsc, void **p,
 	 * and the mds rank >= m_num_active_mds.
 	 */
 	m->possible_max_rank = max(m->m_num_active_mds, m->m_max_mds);
+	if (m->possible_max_rank > CEPH_MAX_MDS) {
+		err = -EIO;
+		goto corrupt;
+	}
 
 	m->m_info = kcalloc(m->possible_max_rank, sizeof(*m->m_info), GFP_NOFS);
 	if (!m->m_info)
@@ -316,6 +320,10 @@ struct ceph_mdsmap *ceph_mdsmap_decode(struct ceph_mds_client *mdsc, void **p,
 	{
 		int num_laggy = 0;
 		ceph_decode_32_safe(p, end, n, bad_ext);
+		if (n > CEPH_MAX_MDS) {
+			err = -EIO;
+			goto corrupt;
+		}
 		ceph_decode_need(p, end, sizeof(u32) * n, bad_ext);
 
 		for (i = 0; i < n; i++) {
Signature · 1 line
2.53.0
author maintainer
#771 lore raw

PATCH 769/869 ceph: require the dentry lease record to cover struct ceph_mds_reply_lease

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Xiang Mei <[email protected]>

[ Upstream commit 7286b2ffe04d4b39b4e9884f714792589d94f316 ]

parse_reply_info_lease() reads a 32-bit struct_len off the wire and only checks that many bytes are present, without requiring struct_len to cover sizeof(struct ceph_mds_reply_lease) (10 bytes). A malicious MDS can declare a shorter record and still get the pointer published: the following *p += sizeof(**lease) overshoot is undone by *p = lend, so nothing downstream rejects the reply. ceph_fill_trace() -> update_dentry_lease() then reads 10 bytes through that pointer on any lookup on a mounted CephFS, running past the end of the message front.

Require the record to cover the structure, matching the sibling parse_reply_info_dir(). A conforming MDS always encodes the full 10 bytes.

  BUG: KASAN: slab-out-of-bounds in __update_dentry_lease.constprop.0 (fs/ceph/inode.c:1459)
  Read of size 4 at addr ffff888026c63d65 by task kworker/0:3/2366
  Workqueue: ceph-msgr ceph_con_workfn
  Call Trace:
   __update_dentry_lease.constprop.0 (fs/ceph/inode.c:1459)
   ceph_fill_trace (fs/ceph/inode.c:1474 fs/ceph/inode.c:1823)
   mds_dispatch (fs/ceph/mds_client.c:4229 fs/ceph/mds_client.c:7225)
   ceph_con_process_message (net/ceph/messenger.c:1424)
   ceph_con_v1_try_read (net/ceph/messenger_v1.c:1430)
   ceph_con_workfn (net/ceph/messenger.c:1576)
   process_one_work (kernel/workqueue.c:3396)
   worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560)
   kthread (kernel/kthread.c:436)
   ret_from_fork (arch/x86/kernel/process.c:158)
   ret_from_fork_asm (arch/x86/entry/entry_64.S:245)

The buggy address is located 357 bytes inside of
allocated 360-byte region [ffff888026c63c00, ffff888026c63d68)

Fixes 4ac4c23eaa38 ("ceph: decode alternate_name in lease info")
Reported-by [email protected]
Assisted-by LLM
---
 fs/ceph/mds_client.c | 2 ++
 1 file changed, 2 insertions(+)
fs/ceph/mds_client.c +2 -0
index 342d8778b69cf..a5bc9f75e0f9c 100644
@@ -338,6 +338,8 @@ static int parse_reply_info_lease(void **p, void *end,
 
 	lend = *p + struct_len;
 	ceph_decode_need(p, end, struct_len, bad);
+	if (struct_len < sizeof(**lease))
+		goto bad;
 	*lease = *p;
 	*p += sizeof(**lease);
 
Signature · 1 line
2.53.0
author maintainer
#772 lore raw

PATCH 770/869 libceph: only set read_from_replica on read requests

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Xiubo Li <[email protected]>

[ Upstream commit d6c7a5fcd08873c45a2dcd645a0690fd1443af50 ]

ceph_osdc_alloc_request() ORs the mount option's read_from_replica flag into r_flags for every request, writes included. The flag is meant for reads: calc_target() skips the replica choice for any request that has CEPH_OSD_FLAG_WRITE, and the OSDs only know BALANCE_READS on read ops. Sending it on writes is at best ignored; with read_from_replica=balance a buffered write that fell back to ceph_sync_write() after losing BUFFER to a revoke failed with -EIO, while the same run without the option works fine.

Gate the flag on CEPH_OSD_FLAG_READ.

Fixes 22d2cfdffa5b ("libceph: move away from global osd_req_flags")
Assisted-by Cursor
---
 net/ceph/osd_client.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
net/ceph/osd_client.c +3 -1
index 46b2c2ae77784..92d76df2701ef 100644
@@ -1108,7 +1108,9 @@ struct ceph_osd_request *ceph_osdc_new_request(struct ceph_osd_client *osdc,
 	req->r_base_oloc.pool = layout->pool_id;
 	req->r_base_oloc.pool_ns = ceph_try_get_string(layout->pool_ns);
 	ceph_oid_printf(&req->r_base_oid, "%llx.%08llx", vino.ino, objnum);
-	req->r_flags = flags | osdc->client->options->read_from_replica;
+	req->r_flags = flags;
+	if (flags & CEPH_OSD_FLAG_READ)
+		req->r_flags |= osdc->client->options->read_from_replica;
 
 	req->r_snapid = vino.snap;
 	if (flags & CEPH_OSD_FLAG_WRITE)
Signature · 1 line
2.53.0
author maintainer
#773 lore raw

PATCH 771/869 libceph: Fix unsafe decode in ceph_redirect_decode()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Raphael Zimmer <[email protected]>

[ Upstream commit 0405670e50f213594366ab7eddc07002bd7f84c0 ]

ceph_redirect_decode handles unchecked data received over the network from an OSD. Currently, there is only a bounds check covering the first three decode operations. After decoding the first len field from the message, the only remaining check ensures there is enough buffer space to hold len bytes. However, there is no guarantee that this value is large enough to hold the subsequently decoded fields. The decoding of the second len field is missing an explicit bounds check. Consequently, a corrupted message can trigger an out-of-bounds read.

This patch fixes the issue by switching the decoding from ceph_decode_32() to the bounds-checked version ceph_decode_32_safe().

Fixes 205ee1187a67 ("libceph: follow redirect replies from osds")
Assisted-by Cursor
---
 net/ceph/osd_client.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/ceph/osd_client.c +1 -1
index 92d76df2701ef..47879d73029aa 100644
@@ -3642,7 +3642,7 @@ static int ceph_redirect_decode(void **p, void *end,
 	if (ret)
 		goto out;
 
-	len = ceph_decode_32(p);
+	ceph_decode_32_safe(p, end, len, e_inval);
 	if (len > 0) {
 		pr_warn("ceph_request_redirect::object_name is set\n");
 		goto e_inval;
Signature · 1 line
2.53.0
author maintainer
#774 lore raw

PATCH 772/869 libceph: Fix multiple unsafe decodes in ceph_oloc_decode()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Raphael Zimmer <[email protected]>

[ Upstream commit 10655007b9b679e46a9e383202c7bb791e5d1d13 ]

ceph_oloc_decode handles unchecked data received over the network from an OSD. Currently, there are multiple decode operations that aren't covered by any bounds check. Decoding these fields can therefore result in out-of-bounds reads if a corrupted message is received.

This patch fixes the issue by adding bounds checks covering all previously uncovered decode operations.

[ idryomov: use ceph_decode_64_safe() for hash ]

Fixes 205ee1187a67 ("libceph: follow redirect replies from osds")
Assisted-by Cursor
---
 net/ceph/osd_client.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
net/ceph/osd_client.c +5 -2
index 47879d73029aa..0b37fb3c62644 100644
@@ -3570,6 +3570,7 @@ static int ceph_oloc_decode(void **p, void *end,
 	ceph_decode_need(p, end, len, e_inval);
 	struct_end = *p + len;
 
+	ceph_decode_need(p, end, 8 + 4 + 4, e_inval);
 	oloc->pool = ceph_decode_64(p);
 	*p += 4; /* skip preferred */
 
@@ -3582,7 +3583,7 @@ static int ceph_oloc_decode(void **p, void *end,
 	if (struct_v >= 5) {
 		bool changed = false;
 
-		len = ceph_decode_32(p);
+		ceph_decode_32_safe(p, end, len, e_inval);
 		if (len > 0) {
 			ceph_decode_need(p, end, len, e_inval);
 			if (!oloc->pool_ns ||
@@ -3601,7 +3602,9 @@ static int ceph_oloc_decode(void **p, void *end,
 	}
 
 	if (struct_v >= 6) {
-		s64 hash = ceph_decode_64(p);
+		s64 hash;
+
+		ceph_decode_64_safe(p, end, hash, e_inval);
 		if (hash != -1) {
 			pr_warn("ceph_object_locator::hash is set\n");
 			goto e_inval;
Signature · 1 line
2.53.0
author maintainer
#775 lore raw

PATCH 773/869 libceph: reject mismatched CRUSH weight-set sizes

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Felix Hoffmann <[email protected]>

[ Upstream commit d8fc89b5bfe4cb3aebe4c8a818247d11291b841c ]

A CEPH_MSG_OSD_MAP message can contain CRUSH choose args with replacement weight vectors for straw2 buckets. decode_choose_args() validates the optional IDs vector against the referenced bucket, but does not validate the size of any replacement-weight vector.

The CRUSH mapper assumes that each replacement vector has exactly as many entries as the bucket. A zero-length vector for a nonempty bucket makes bucket_straw2_choose() dereference NULL, while a shorter nonzero vector causes an out-of-bounds read. An authenticated monitor or OSD can deliver such a map and crash a kernel client when it performs placement for an ordinary request.

Reject a nonempty collection of weight sets for an absent bucket and require every replacement-weight vector to match its bucket size.

Fixes 5cf9c4a9959b ("libceph, crush: per-pool crush_choose_arg_map for crush_do_rule()")
Assisted-by Codex:gpt-5
---
 net/ceph/osdmap.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
net/ceph/osdmap.c +12 -2
index 68bd45852fc37..e812b30778d57 100644
@@ -378,7 +378,9 @@ static int decode_choose_args(void **p, void *end, struct crush_map *c)
 		ceph_decode_32_safe(p, end, num_buckets, e_inval);
 		while (num_buckets--) {
 			struct crush_choose_arg *arg;
+			struct crush_bucket *bucket;
 			u32 bucket_index;
+			u32 i;
 
 			ceph_decode_32_safe(p, end, bucket_index, e_inval);
 			if (bucket_index >= arg_map->size)
@@ -389,10 +391,18 @@ static int decode_choose_args(void **p, void *end, struct crush_map *c)
 			if (ret)
 				goto fail;
 
+			bucket = c->buckets[bucket_index];
 			if (arg->ids_size &&
-			    (!c->buckets[bucket_index] ||
-			     arg->ids_size != c->buckets[bucket_index]->size))
+			    (!bucket || arg->ids_size != bucket->size))
 				goto e_inval;
+
+			if (arg->weight_set_size && !bucket)
+				goto e_inval;
+
+			for (i = 0; i < arg->weight_set_size; i++) {
+				if (arg->weight_set[i].size != bucket->size)
+					goto e_inval;
+			}
 		}
 
 		if (!__insert_choose_arg_map(&c->choose_args, arg_map)) {
Signature · 1 line
2.53.0
author maintainer
#776 lore raw

PATCH 774/869 libceph: reject an initial monmap with no monitors

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yogesh Gaur <[email protected]>

[ Upstream commit 94dbce2ae4fdb57bdb53ffa3456da777a5cfb981 ]

build_initial_monmap() takes the monitor count straight from ceph_options::num_mon and builds a monmap with that many entries without checking that there is at least one. ceph_parse_ips() writes *count only after it has parsed an address successfully, so a ceph_options that went through a failed parse still has num_mon == 0 and the resulting monmap has no monitors in it at all.

The first thing the client does with that monmap is open a session, and pick_new_mon() asserts the invariant that it is non-empty:

kernel BUG at net/ceph/mon_client.c:211!

  RIP: 0010:pick_new_mon net/ceph/mon_client.c:211 [inline]
  RIP: 0010:__open_session+0x60f/0x740 net/ceph/mon_client.c:245
  Call Trace:
   ceph_monc_open_session+0x46/0x60 net/ceph/mon_client.c:534
   __ceph_open_session+0x135/0x590 net/ceph/ceph_common.c:798
   ceph_real_mount fs/ceph/super.c:1173 [inline]
   ceph_get_tree+0xd98/0x1fd0 fs/ceph/super.c:1362
   vfs_get_tree+0x92/0x320 fs/super.c:1947
   vfs_cmd_create+0xd7/0x2a0 fs/fsopen.c:231
   __do_sys_fsconfig+0x55a/0xcb0 fs/fsopen.c:463

The reproducer gets there through the new device syntax: an fsconfig() mon_addr= that does not resolve ("libceph: resolve '127.0.0.' (ret=-3):
failed") leaves fsopt->mon_addr set but num_mon at 0, so the "No monitor address" check in ceph_get_tree() passes and the mount proceeds with an empty monmap. The next patch stops that string from being kept, but the assertion should not be reachable from a mount option in the first place.

Commit 40480eee361e ("libceph: Reject monmaps advertising zero monitors") made the same BUG_ON() unreachable from the wire by rejecting num_mon == 0 in ceph_monmap_decode(). Apply the same rule to the initial monmap, which is the only other way one gets built, and fail the mount with -EINVAL rather than assert afterwards.

---
 net/ceph/mon_client.c | 3 +++
 1 file changed, 3 insertions(+)
net/ceph/mon_client.c +3 -0
index 614d2bba9fd60..a406fff75ba0d 100644
@@ -1141,6 +1141,9 @@ static int build_initial_monmap(struct ceph_mon_client *monc)
 	int num_mon = opt->num_mon;
 	int i;
 
+	if (num_mon < 1 || num_mon > CEPH_MAX_MON)
+		return -EINVAL;
+
 	/* build initial monmap */
 	monc->monmap = kzalloc(struct_size(monc->monmap, mon_inst, num_mon),
 			       GFP_KERNEL);
Signature · 1 line
2.53.0
author maintainer
#777 lore raw

PATCH 775/869 ceph: fix integer overflow in the snap trace bounds check

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Xiang Mei <[email protected]>

[ Upstream commit b3bf89767e3ca9506f1c7167cac97c41ec254d42 ]

ceph_update_snap_trace() bounds the two encoded snapid arrays that follow a struct ceph_mds_snap_realm with sizeof(u64) * (num_snaps + num_prior_parent_snaps). Both counts come straight off the wire as __le32, so the addition is evaluated in unsigned int and wraps before sizeof(u64) promotes it to size_t: an MDS sending num_snaps = 1 and num_prior_parent_snaps = 0xffffffff makes the sum zero and the check degenerates to ceph_decode_need(&p, e, 0, bad), which always passes. dup_array() then reads num_snaps * 8 bytes past the end of the message front, which ceph_msg_new2() allocates at exactly front_len bytes. An unsolicited CEPH_MSG_CLIENT_SNAP reaches this from a malicious or compromised MDS with no client-side action, as do the snaptraces carried in an MDS reply and in a cap import.

Compute the length with size_add()/size_mul() so it saturates at SIZE_MAX instead of wrapping, in the style fs/ceph/mdsmap.c already uses for num_export_targets.

  BUG: KASAN: slab-out-of-bounds in dup_array (include/linux/unaligned.h:28 fs/ceph/snap.c:500)
  Read of size 8 at addr ffff8880102a16c8 by task kworker/1:2/129
  Workqueue: ceph-msgr ceph_con_workfn
  Call Trace:
   dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120)
   print_report (mm/kasan/report.c:378 mm/kasan/report.c:482)
   kasan_report (mm/kasan/report.c:595)
   dup_array (include/linux/unaligned.h:28 fs/ceph/snap.c:500)
   ceph_update_snap_trace (fs/ceph/snap.c:836)
   ceph_handle_snap (fs/ceph/snap.c:1155)
   mds_dispatch (fs/ceph/mds_client.c:7234)
   ceph_con_process_message (net/ceph/messenger.c:1424)
   ceph_con_v1_try_read (net/ceph/messenger_v1.c:1430)
   ceph_con_workfn (net/ceph/messenger.c:1576)
   process_one_work (kernel/workqueue.c:3396)
   worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560)
   kthread (kernel/kthread.c:436)
   ret_from_fork (arch/x86/kernel/process.c:158)
   ret_from_fork_asm (arch/x86/entry/entry_64.S:245)
  ...
  The buggy address is located 0 bytes to the right of
   allocated 72-byte region [ffff8880102a1680, ffff8880102a16c8)
Fixes 963b61eb041e ("ceph: snapshot management")
Reported-by [email protected]
Assisted-by LLM
---
 fs/ceph/snap.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
fs/ceph/snap.c +5 -2
index c65f2b202b2b3..00cfcef5fbb25 100644
@@ -788,6 +788,7 @@ int ceph_update_snap_trace(struct ceph_mds_client *mdsc,
 	struct ceph_snap_realm *first_realm = NULL;
 	struct ceph_snap_realm *realm_to_rebuild = NULL;
 	struct ceph_client *client = mdsc->fsc->client;
+	size_t snaps_len;
 	int rebuild_snapcs;
 	int err = -ENOMEM;
 	int ret;
@@ -802,8 +803,10 @@ int ceph_update_snap_trace(struct ceph_mds_client *mdsc,
 	ceph_decode_need(&p, e, sizeof(*ri), bad);
 	ri = p;
 	p += sizeof(*ri);
-	ceph_decode_need(&p, e, sizeof(u64)*(le32_to_cpu(ri->num_snaps) +
-			    le32_to_cpu(ri->num_prior_parent_snaps)), bad);
+	snaps_len = size_mul(size_add(le32_to_cpu(ri->num_snaps),
+				      le32_to_cpu(ri->num_prior_parent_snaps)),
+			     sizeof(u64));
+	ceph_decode_need(&p, e, snaps_len, bad);
 	snaps = p;
 	p += sizeof(u64) * le32_to_cpu(ri->num_snaps);
 	prior_parent_snaps = p;
Signature · 1 line
2.53.0
author maintainer
#778 lore raw

PATCH 776/869 ceph: Fix xattr buffer leak in __send_cap()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Wentao Liang <[email protected]>

[ Upstream commit e51cf76e7275d1bb5ad2d529bb00feade632dadc ]

__prep_cap() takes a reference on the xattr blob via ceph_buffer_get() and also grabs a reference to the old xattr blob returned by __ceph_build_xattrs_blob(). These references are normally dropped in __send_cap() after the cap message has been sent, but when ceph_msg_new() fails, __send_cap() requeues the cap and returns early without dropping them, leaking both buffers on every allocation failure.

Release arg->old_xattr_buf and arg->xattr_buf on the ceph_msg_new() failure path before returning.

Fixes 16d68903f56a ("ceph: break up send_cap_msg")
---
 fs/ceph/caps.c | 2 ++
 1 file changed, 2 insertions(+)
fs/ceph/caps.c +2 -0
index 7ce1af5b61c88..3dfd230412cc2 100644
@@ -1561,6 +1561,8 @@ static void __send_cap(struct cap_msg_args *arg, struct ceph_inode_info *ci)
 		spin_lock(&ci->i_ceph_lock);
 		__cap_delay_requeue(arg->session->s_mdsc, ci);
 		spin_unlock(&ci->i_ceph_lock);
+		ceph_buffer_put(arg->old_xattr_buf);
+		ceph_buffer_put(arg->xattr_buf);
 		return;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#779 lore raw

PATCH 777/869 ceph: Fix mds session leak in __open_export_target_session()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Wentao Liang <[email protected]>

[ Upstream commit 6c80207392fdb86107d7acbdbf4c86cac38da1af ]

__open_export_target_session() holds a reference on the target session, either from __ceph_lookup_mds_session() or from register_session(), which the caller is expected to drop. When __open_session() fails, the helper returns ERR_PTR(ret) without dropping that reference, leaking one session reference on every open failure.

Drop the session reference before returning the error.

Fixes b682c6d41bc2 ("ceph: switch to WARN_ON_ONCE in encode_supported_features()")
---
 fs/ceph/mds_client.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/ceph/mds_client.c +3 -1
index a5bc9f75e0f9c..56d8df7f7ebdd 100644
@@ -1758,8 +1758,10 @@ __open_export_target_session(struct ceph_mds_client *mdsc, int target)
 	if (session->s_state == CEPH_MDS_SESSION_NEW ||
 	    session->s_state == CEPH_MDS_SESSION_CLOSING) {
 		ret = __open_session(mdsc, session);
-		if (ret)
+		if (ret) {
+			ceph_put_mds_session(session);
 			return ERR_PTR(ret);
+		}
 	}
 
 	return session;
Signature · 1 line
2.53.0
author maintainer
#780 lore raw

PATCH 778/869 ceph: fix 32-bit overflow in readdir reply count check

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jérémy Jean <[email protected]>

[ Upstream commit 52913831ba56efceaafd80b501d68fa00f79bde6 ]

parse_reply_info_readdir() checks how many entries are in a readdir reply by computing the end pointer of the decoded array. That pointer addition can wrap on 32-bit kernels and let an oversized count pass the check. For example, a count of 0x40000000 with 156-byte entries wraps to a zero offset, so the decoder can write past the preallocated buffer.

Check the count against the number of entries that fit in the allocation before publishing dir_nr. Reject oversized replies through the existing error path.

Fixes 54008399dc0c ("ceph: preallocate buffer for readdir reply")
Assisted-by LLM
---
 fs/ceph/mds_client.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
fs/ceph/mds_client.c +1 -3
index 56d8df7f7ebdd..9e1b4bc3eab7c 100644
@@ -436,10 +436,8 @@ static int parse_reply_info_readdir(void **p, void *end,
 		goto done;
 
 	BUG_ON(!info->dir_entries);
-	if ((unsigned long)(info->dir_entries + num) >
-	    (unsigned long)info->dir_entries + info->dir_buf_size) {
+	if (num > info->dir_buf_size / sizeof(*info->dir_entries)) {
 		pr_err_client(cl, "dir contents are larger than expected\n");
-		WARN_ON(1);
 		goto bad;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#781 lore raw

PATCH 779/869 libceph: fix out-of-bounds reads from repeated CRUSH bucket entries

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jérémy Jean <[email protected]>

[ Upstream commit 569a9bb1e5615c2b88b8d76f03a4ab82e65a673e ]

decode_choose_arg() assumes that its destination is zero-initialized. Although decode_choose_args() zeroes the argument array, it does not reject a repeated bucket_index and can decode into an already populated entry.

Repeating a bucket with weight_set_size=0 preserves its existing weight_set pointer but clears the count. Placement then reads weight_set[-1].weights and dereferences the resulting pointer.

A malformed monitor OSDMap triggers this during RBD placement:

  BUG: KASAN: slab-out-of-bounds in crush_bucket_choose+0xdd1/0xf90
  Read of size 8 at addr ffff88800290df70 by task init/75

Reject populated arguments before decoding another entry, so the error path can free their original allocations.

Fixes c7ed1a4bf4b4 ("crush: assume weight_set != null imples weight_set_size > 0")
Assisted-by Codex:gpt-5
---
 net/ceph/osdmap.c | 2 ++
 1 file changed, 2 insertions(+)
net/ceph/osdmap.c +2 -0
index e812b30778d57..803514a1bc7ce 100644
@@ -387,6 +387,8 @@ static int decode_choose_args(void **p, void *end, struct crush_map *c)
 				goto e_inval;
 
 			arg = &arg_map->args[bucket_index];
+			if (arg->ids || arg->weight_set)
+				goto e_inval;
 			ret = decode_choose_arg(p, end, arg);
 			if (ret)
 				goto fail;
Signature · 1 line
2.53.0
author maintainer
#782 lore raw

PATCH 780/869 ceph: clamp MDS reply result code to the errno range

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yuanfu Xie <[email protected]>

[ Upstream commit ec8d583469ed64b4973192a21b5a41c33219721f ]

ceph_mdsc_wait_request() returns the reply head result code of the MDS request to its callers as a plain int errno. The value is a server-controlled u32 and nothing checks that it actually is an errno; several callers pass it straight to ERR_PTR(), e.g. ceph_finish_lookup() on the atomic open path:

	err = ceph_mdsc_wait_request(...)	/* e.g. +0x50fc00 */
	...
	if (err)
		dentry = ERR_PTR(err);

IS_ERR() only recognizes the [-MAX_ERRNO, -1] window, so an out-of-range value is not caught anywhere and survives as a "struct dentry *". On the open path the positive error travels ceph_finish_lookup() -> ceph_atomic_open() -> ERR_PTR() in fs/namei.c's atomic_open() wrapper -> step_into(), which dereferences it as a dentry and oopses (mainline 7.3-rc3-135-g4982d3552a3b, the value in R12 is the server-supplied result):

BUG: KASAN: probably user-memory-access in range
[0x000000000050fc00-0x000000000050fc07]
RIP: 0010:step_into_slowpath+0x3e3/0xe60
R12: 000000000050fc00
Call Trace:
 <TASK>
 ? __pfx_ceph_atomic_open+0x10/0x10
 path_openat+0xf41/0x2440
 do_file_open+0x228/0x480
 do_sys_openat2+0x103/0x1d0
 __x64_sys_openat+0x141/0x200
 do_syscall_64+0xe8/0x4f0
 entry_SYSCALL_64_after_hwframe+0x77/0x79
 </TASK>

(0xdffffc00000a1f80 in the full report is the KASAN shadow of 0x50fc00; without KASAN the raw value is read.) Values with the top bit set fare no better: 0xd8000000 sign-extends through the int conversion into the kernel address range and takes a page fault instead.

Clamp the result at the single read and return -EIO for anything outside the errno range, which is what a malformed reply means there. net/9p does the same to server errno values with safe_errno(). This is the path the reported crash takes; the other readers of head->result, including the ceph_async_create_cb() and ceph_async_unlink_cb() callbacks, are not covered by this patch.

Each of the six crashing opens was run on a build of 7.3-rc3-135-g4982d3552a3bf with only this change applied: it crashes the unpatched kernel on the first openat() (verified on the same tree without the patch), and with the patch the open fails cleanly without an oops. A few hundred normal file operations on the patched kernel also completed without a crash; valid errno values pass through unchanged.

Fixes 2f2dc053404febedc9c273452d9d518fb31fde72 ("ceph: MDS client")
---
 fs/ceph/mds_client.c | 8 ++++++++
 1 file changed, 8 insertions(+)
fs/ceph/mds_client.c +8 -0
index 9e1b4bc3eab7c..e1a0f77acc1ad 100644
@@ -3814,6 +3814,14 @@ int ceph_mdsc_wait_request(struct ceph_mds_client *mdsc,
 	/* only abort if we didn't race with a real reply */
 	if (test_bit(CEPH_MDS_R_GOT_RESULT, &req->r_req_flags)) {
 		err = le32_to_cpu(req->r_reply_info.head->result);
+		if (err > 0 || err < -MAX_ERRNO) {
+			/*
+			 * The result is server-controlled.  Values outside
+			 * the errno range are turned into bogus pointers by
+			 * the ERR_PTR() users among the callers.
+			 */
+			err = -EIO;
+		}
 	} else if (err < 0) {
 		doutc(cl, "aborted request %lld with %d\n", req->r_tid, err);
 
Signature · 1 line
2.53.0
author maintainer
#783 lore raw

PATCH 781/869 ceph: dont fail write_begin with -EAGAIN after flushing old snapc

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Venky Shankar <[email protected]>

[ Upstream commit 6ff7920ca78f6edcabc26c63d20f681d938027c7 ]

When ceph_netfs_check_write_begin() finds the folio dirty in an older snap context, it drops the folio, waits for that snap context to be flushed and then returns -EAGAIN so that the write is retried.

However, since commit fac47b43c760 ("netfs: do not unlock and put the folio twice"), netfs_write_begin() retries only when ->check_write_begin() returns 0 with *foliop cleared -- every error, -EAGAIN included, is returned as is. The -EAGAIN thus propagates up to write(2), which fails with "Resource temporarily unavailable" once the dirty data has been flushed, rather than being retried.

This is easily hit by buffered writers rewriting dirty pages while snapshots are being taken, e.g. a kernel build linking vmlinux into a directory under a snapshot schedule:

ld: final link failed: Resource temporarily unavailable

Return the wait_event_killable() result as is so that netfs re-gets the folio and retries on success.

Fixes fac47b43c760 ("netfs: do not unlock and put the folio twice")
---
 fs/ceph/addr.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
fs/ceph/addr.c +6 -1
index f58eba5456e36..fe8b7b4f6e8bf 100644
@@ -1889,7 +1889,12 @@ static int ceph_netfs_check_write_begin(struct file *file, loff_t pos, unsigned
 		r = wait_event_killable(ci->i_cap_wq,
 					context_is_writeable_or_written(inode, snapc));
 		ceph_put_snap_context(snapc);
-		return r == 0 ? -EAGAIN : r;
+		/*
+		 * *foliop is cleared, so a return of 0 makes
+		 * netfs_write_begin() grab the folio again and call us again
+		 * to recheck it. Any error (fatal signal) fails the write.
+		 */
+		return r;
 	}
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#784 lore raw

PATCH 782/869 ceph: validate fscrypt auth blob length

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: sung byeongchan <[email protected]>

[ Upstream commit bc418e234e5be14b97dec90e84a680e615b4134e ]

ceph_crypt_get_context() trusts cfa_blob_len after checking only that the inode-owned fscrypt_auth allocation contains the fixed header and one byte. An MDS can therefore place a larger inner length in a shorter outer object, causing memcpy() to read beyond the allocation when a caller requests the encryption nonce.

Require the complete blob to fit in the inode-owned allocation before using the inner length.

On the tested baseline, the malformed reply produced the same KASAN slab-out-of-bounds read twice. An ordinary UID obtained sixteen wire-absent SLUB redzone bytes in two non-KASAN production-path runs. The input was rejected twice after this change, while a complete context still worked.

Fixes 2d332d5bc424 ("ceph: fscrypt_auth handling for ceph")
Assisted-by LLM
---
 fs/ceph/crypto.c | 3 +++
 1 file changed, 3 insertions(+)
fs/ceph/crypto.c +3 -0
index a236035f3a7a4..f23ba5c148780 100644
@@ -83,6 +83,9 @@ static int ceph_crypt_get_context(struct inode *inode, void *ctx, size_t len)
 		return -ENOBUFS;
 
 	ctxlen = le32_to_cpu(cfa->cfa_blob_len);
+	if (ctxlen > ci->fscrypt_auth_len -
+		     offsetof(struct ceph_fscrypt_auth, cfa_blob))
+		return -ENOBUFS;
 	if (len < ctxlen)
 		return -ERANGE;
 
Signature · 1 line
2.53.0
author maintainer
#785 lore raw

PATCH 783/869 ceph: bound name skips in ceph_mdsmap_decode() by the message end

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: sung byeongchan <[email protected]>

[ Upstream commit 7f702e1703c9648fcb02a217d66c880d00417150 ]

ceph_mdsmap_decode() reads two remote u32 name lengths and advances its parser cursor without checking that either string remains in the message. On a 32-bit client, a sufficiently large length can wrap the cursor below end. The following numerical bounds check then succeeds and dereferences the wrapped address.

Use ceph_decode_skip_n() for both names so the remaining bytes are checked before the cursor advances.

The issue produced a page fault in ceph_mdsmap_decode twice on the tested i386 baseline. The same frame was rejected without a fault twice after this change, while a normal MDSMap continued to be accepted.

Fixes 2f2dc053404f ("ceph: MDS client")
Assisted-by LLM
---
 fs/ceph/mdsmap.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/ceph/mdsmap.c +2 -2
index 0fd578f0b2cd2..d377d13f854d5 100644
@@ -209,7 +209,7 @@ struct ceph_mdsmap *ceph_mdsmap_decode(struct ceph_mds_client *mdsc, void **p,
 		ceph_decode_need(p, end, sizeof(u64) + sizeof(u32), bad);
 		*p += sizeof(u64);
 		namelen = ceph_decode_32(p);  /* skip mds name */
-		*p += namelen;
+		ceph_decode_skip_n(p, end, namelen, bad);
 
 		ceph_decode_32_safe(p, end, mds, bad);
 		ceph_decode_32_safe(p, end, inc, bad);
@@ -227,7 +227,7 @@ struct ceph_mdsmap *ceph_mdsmap_decode(struct ceph_mds_client *mdsc, void **p,
 		laggy = laggy_since.tv_sec != 0 || laggy_since.tv_nsec != 0;
 		*p += sizeof(u32);
 		ceph_decode_32_safe(p, end, namelen, bad);
-		*p += namelen;
+		ceph_decode_skip_n(p, end, namelen, bad);
 		if (info_v >= 2) {
 			ceph_decode_32_safe(p, end, num_export_targets, bad);
 			export_targets_len = size_mul(num_export_targets,
Signature · 1 line
2.53.0
author maintainer
#786 lore raw

PATCH 784/869 ceph: validate MDS reply fragtree split array length

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: sung byeongchan <[email protected]>

[ Upstream commit 8cab7e7461f81ea1e0fd45082b50bb3c04c0bb10 ]

parse_reply_info_in() advances over the fragtree split array using an unchecked count multiplication. On a 32-bit client, nsplits=0x20000000 wraps the byte length to zero, so the reply is accepted and ceph_fill_fragtree() sorts far beyond the message front.

Compute the split length with size_mul() and require the complete array to remain in the inode record before advancing the cursor.

The malformed reply faulted in frag_tree_split_cmp() twice on the tested i386 baseline. It was rejected without a fault twice after this change, while a normal reply and a one-split control remained functional.

Fixes 2f2dc053404f ("ceph: MDS client")
Assisted-by LLM
---
 fs/ceph/mds_client.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
fs/ceph/mds_client.c +7 -3
index e1a0f77acc1ad..0220daac0fba7 100644
@@ -14,6 +14,7 @@
 #include <linux/ktime.h>
 #include <linux/bitmap.h>
 #include <linux/mnt_idmapping.h>
+#include <linux/overflow.h>
 
 #include "super.h"
 #include "mds_client.h"
@@ -104,6 +105,7 @@ static int parse_reply_info_in(void **p, void *end,
 			       u64 features)
 {
 	int err = 0;
+	size_t splits_len;
 	u8 struct_v = 0;
 
 	if (features == (u64)-1) {
@@ -122,9 +124,11 @@ static int parse_reply_info_in(void **p, void *end,
 
 	ceph_decode_need(p, end, sizeof(struct ceph_mds_reply_inode), bad);
 	info->in = *p;
-	*p += sizeof(struct ceph_mds_reply_inode) +
-		sizeof(*info->in->fragtree.splits) *
-		le32_to_cpu(info->in->fragtree.nsplits);
+	splits_len = size_mul(sizeof(*info->in->fragtree.splits),
+			      le32_to_cpu(info->in->fragtree.nsplits));
+	*p += sizeof(struct ceph_mds_reply_inode);
+	ceph_decode_need(p, end, splits_len, bad);
+	*p += splits_len;
 
 	ceph_decode_32_safe(p, end, info->symlink_len, bad);
 	ceph_decode_need(p, end, info->symlink_len, bad);
Signature · 1 line
2.53.0
author maintainer
#787 lore raw

PATCH 785/869 ceph: validate encoded xattr name lengths

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: sung byeongchan <[email protected]>

[ Upstream commit 166375898d29fea050a9abec855da6075050d5c9 ]

__build_xattrs() advances over an MDS-provided name length before checking that the name remains in the encoded xattr blob. On 32-bit clients, UINT_MAX wraps the cursor and is stored as a negative internal name length. A later ordinary listxattr() converts it back to a UINT_MAX memcpy size and corrupts kernel memory.

Check the name range before advancing and reject name, value, or aggregate sizes that overflow the signed internal accounting.

The malformed blob corrupted kernel state in two baseline boots. It was rejected cleanly twice with this change, while normal and length-only controls remained safe.

Fixes 355da1eb7a1f ("ceph: inode operations")
Assisted-by LLM
---
 fs/ceph/xattr.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
fs/ceph/xattr.c +10 -0
index cc73b0874ce40..90a9e7de8fea0 100644
@@ -11,6 +11,7 @@
 #include <linux/security.h>
 #include <linux/posix_acl_xattr.h>
 #include <linux/slab.h>
+#include <linux/overflow.h>
 
 #define XATTR_CEPH_PREFIX "ceph."
 #define XATTR_CEPH_PREFIX_LEN (sizeof (XATTR_CEPH_PREFIX) - 1)
@@ -845,14 +846,23 @@ static int __build_xattrs(struct inode *inode)
 		}
 		err = -EIO;
 		while (numattr--) {
+			int names_size, vals_size;
+
 			ceph_decode_32_safe(&p, end, len, bad);
 			namelen = len;
 			name = p;
+			ceph_decode_need(&p, end, namelen, bad);
 			p += len;
 			ceph_decode_32_safe(&p, end, len, bad);
 			ceph_decode_need(&p, end, len, bad);
 			val = p;
 			p += len;
+			if (namelen > INT_MAX || len > INT_MAX ||
+			    check_add_overflow(ci->i_xattrs.names_size,
+					       (int)namelen, &names_size) ||
+			    check_add_overflow(ci->i_xattrs.vals_size,
+					       (int)len, &vals_size))
+				goto bad;
 
 			err = __set_xattr(ci, name, namelen, val, len,
 					  0, 0, &xattrs[numattr]);
Signature · 1 line
2.53.0
author maintainer
#788 lore raw

PATCH 786/869 ceph: fix uninitialized err in ceph_netfs_issue_read()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Alex Markuze <[email protected]>

[ Upstream commit 823d21c78453fcdf58dbd8ecefbb41f4f3eb6540 ]

ceph_netfs_issue_read() declares err without an initializer. On the unencrypted, non-sparse success path nothing assigns it, then the
out: label does if (err) netfs_read_subreq_terminated(subreq).

With CONFIG_INIT_STACK_ALL_PATTERN, err is 0xaaaaaaaa (nonzero), so the subrequest is terminated while the OSD READ is still in flight. netfs then frees the rolling buffer that the OSD iterator still points at, causing a KASAN UAF / oops, and finish_netfs_read() terminates the same subrequest a second time. CONFIG_INIT_STACK_ALL_ZERO hides it because err happens to be 0.

Restore the err = 0 initializer so a successful submit leaves completion to finish_netfs_read() only.

Fixes ee4cdf7ba857 ("netfs: Speed up buffered reading")
---
 fs/ceph/addr.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ceph/addr.c +1 -1
index fe8b7b4f6e8bf..51aeae341f56d 100644
@@ -362,7 +362,7 @@ static void ceph_netfs_issue_read(struct netfs_io_subrequest *subreq)
 	struct ceph_client *cl = fsc->client;
 	struct ceph_osd_request *req = NULL;
 	struct ceph_vino vino = ceph_vino(inode);
-	int err;
+	int err = 0;
 	u64 len;
 	bool sparse = IS_ENCRYPTED(inode) || ceph_test_mount_opt(fsc, SPARSEREAD);
 	u64 off = subreq->start;
Signature · 1 line
2.53.0
author maintainer
#789 lore raw

PATCH 787/869 f2fs: fix to update superblock crc in sanity_check_area_boundary()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Chao Yu <[email protected]>

[ Upstream commit f8f956c7ec8c0285d7a80bed497d2f7adcbded15 ]

This patch fixes the bug reported by Sashiko:

We should update superblock crc along w/ raw_super->segment_count in sanity_check_area_boundary() if sb_checksum feature is enabled.

Fixes d440c52d3151 ("f2fs: support superblock checksum")
---
 fs/f2fs/super.c | 6 ++++++
 1 file changed, 6 insertions(+)
fs/f2fs/super.c +6 -0
index 11d218b415b0d..69d36e1a301bf 100644
@@ -3920,6 +3920,12 @@ static inline bool sanity_check_area_boundary(struct f2fs_sb_info *sbi,
 		/* fix in-memory information all the time */
 		raw_super->segment_count = cpu_to_le32((main_end_blkaddr -
 				segment0_blkaddr) >> log_blocks_per_seg);
+		if (__F2FS_HAS_FEATURE(raw_super, F2FS_FEATURE_SB_CHKSUM)) {
+			__u32 crc = f2fs_crc32(raw_super,
+					offsetof(struct f2fs_super_block, crc));
+
+			raw_super->crc = cpu_to_le32(crc);
+		}
 
 		if (f2fs_readonly(sb) || f2fs_hw_is_readonly(sbi)) {
 			set_sbi_flag(sbi, SBI_NEED_SB_WRITE);
Signature · 1 line
2.53.0
author maintainer
#790 lore raw

PATCH 788/869 ASoC: qcom: qdsp6: q6afe: fix clk vote response type mismatch

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Val Packett <[email protected]>

[ Upstream commit f3c7bee984aa0ba2b48a44e16a6f3ec2c27f851e ]

The response sent by the firmware when requesting a clock vote (opcode AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST) does not actually have the same opcode + status payload as APR_BASIC_RSP_RESULT. Rather, it returns one single u32 which is the client_handle that must be used in future unvote requests for the same clock.

As a result of this type confusion, the status returned by the callback to q6afe_vote_lpass_core_hw was actually an out-of-bounds read. It was only interpreted as success (0) most of the time due to luck, but there are some reports of random errors such as:

[   20.961100] qcom-q6afe aprsvc:service:4:4: AFE failed to vote (3)
[   20.961131] Failed to prepare clk 'core': -110

Fix by correctly interpreting the response as a single u32, and actually store it as the client_handle to ensure unvote would work correctly.

---
 sound/soc/qcom/qdsp6/q6afe.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
sound/soc/qcom/qdsp6/q6afe.c +8 -2
index 7b59d514b432a..d2cb0ccd34562 100644
@@ -377,6 +377,7 @@ struct q6afe {
 	struct q6core_svc_api_info ainfo;
 	struct mutex lock;
 	struct aprv2_ibasic_rsp_result_t result;
+	uint32_t vote_result;
 	wait_queue_head_t wait;
 	struct list_head port_list;
 	spinlock_t port_list_lock;
@@ -966,13 +967,14 @@ static int q6afe_callback(struct apr_device *adev, struct apr_resp_pkt *data)
 	struct aprv2_ibasic_rsp_result_t *res;
 	struct apr_hdr *hdr = &data->hdr;
 	struct q6afe_port *port;
+	uint32_t *vote_res;
 
 	if (!data->payload_size)
 		return 0;
 
-	res = data->payload;
 	switch (hdr->opcode) {
 	case APR_BASIC_RSP_RESULT: {
+		res = data->payload;
 		if (res->status) {
 			dev_err(afe->dev, "cmd = 0x%x returned error = 0x%x\n",
 				res->opcode, res->status);
@@ -999,8 +1001,10 @@ static int q6afe_callback(struct apr_device *adev, struct apr_resp_pkt *data)
 	}
 		break;
 	case AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST:
+		vote_res = data->payload;
 		afe->result.opcode = hdr->opcode;
-		afe->result.status = res->status;
+		afe->result.status = 0;
+		afe->vote_result = *vote_res;
 		wake_up(&afe->wait);
 		break;
 	default:
@@ -1910,6 +1914,8 @@ int q6afe_vote_lpass_core_hw(struct device *dev, uint32_t hw_block_id,
 			       AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST);
 	if (ret)
 		dev_err(afe->dev, "AFE failed to vote (%d)\n", hw_block_id);
+	else
+		*client_handle = afe->vote_result;
 
 
 	kfree(pkt);
Signature · 1 line
2.53.0
author maintainer
#791 lore raw

PATCH 789/869 ASoC: codecs: wsa884x: Accept temperatures across the full trim range

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Srinivas Kandagatla <[email protected]>

[ Upstream commit 00535515e3c14fbee20de4a1aa61cfb3390f0f50 ]

wsa884x_get_temp() rejects any reading outside 5..45 degC with -EAGAIN. A speaker that has been playing, or sits in a warm laptop, easily runs above 45 degC, so its temperature becomes unreadable when it matters.

The check only needs to drop bogus conversions, such as the all-zero reading before the PA is first enabled. Bound it by the -10..150 degC two-point trim range instead.

Fixes 6b99dc62d940 ("ASoC: codecs: wsa884x: Implement temperature reading and hwmon")
---
 sound/soc/codecs/wsa884x.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
sound/soc/codecs/wsa884x.c +6 -5
index 5ecd7962d77ae..d941e9826ba00 100644
@@ -720,10 +720,11 @@
 
 /*
  * Device will report senseless data in many cases, so discard any measurements
- * outside of valid range.
+ * outside of the two-point trim range. Do not narrow this to ambient: a
+ * speaker that has been playing easily runs well above 45 degC.
  */
-#define WSA884X_LOW_TEMP_THRESHOLD	5
-#define WSA884X_HIGH_TEMP_THRESHOLD	45
+#define WSA884X_LOW_TEMP_THRESHOLD	WSA884X_T1_TEMP
+#define WSA884X_HIGH_TEMP_THRESHOLD	WSA884X_T2_TEMP
 
 struct wsa884x_priv {
 	struct regmap *regmap;
@@ -1931,8 +1932,8 @@ static int wsa884x_get_temp(struct wsa884x_priv *wsa884x, long *temp)
 	dev_dbg(wsa884x->dev, "Measured temp %ld (dmeas=%d, d1=%d, d2=%d)\n",
 		val, dmeas, d1, d2);
 
-	if ((val > WSA884X_LOW_TEMP_THRESHOLD) &&
-	    (val < WSA884X_HIGH_TEMP_THRESHOLD)) {
+	if (val >= WSA884X_LOW_TEMP_THRESHOLD &&
+	    val <= WSA884X_HIGH_TEMP_THRESHOLD) {
 		wsa884x->temperature = val;
 		*temp = val * 1000;
 		ret = 0;
Signature · 1 line
2.53.0
author maintainer
#792 lore raw

PATCH 790/869 ASoC: codecs: wsa883x: Accept temperatures across the full trim range

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Srinivas Kandagatla <[email protected]>

[ Upstream commit 6a55cf0d9dd2e2493a5030a4f7b0413d31165e45 ]

wsa883x_get_temp() rejects any reading outside 5..45 degC with -EAGAIN, so a speaker that has been playing, or sits in a warm chassis, becomes unreadable above 45 degC.

Bound the check by the -10..150 degC two-point trim range instead, and use inclusive comparisons, as in_range() excludes the upper bound.

Fixes a02c42d41af7 ("ASoC: codecs: wsa883x: Implement temperature reading and hwmon")
---
 sound/soc/codecs/wsa883x.c | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)
sound/soc/codecs/wsa883x.c +7 -6
index 5f2ced650dcc8..6fb50b6e5e188 100644
@@ -455,10 +455,11 @@
 
 /*
  * Device will report senseless data in many cases, so discard any measurements
- * outside of valid range.
+ * outside of the two-point trim range. Do not narrow this to ambient: a
+ * speaker that has been playing easily runs well above 45 degC.
  */
-#define WSA883X_LOW_TEMP_THRESHOLD	5
-#define WSA883X_HIGH_TEMP_THRESHOLD	45
+#define WSA883X_LOW_TEMP_THRESHOLD	WSA883X_T1_TEMP
+#define WSA883X_HIGH_TEMP_THRESHOLD	WSA883X_T2_TEMP
 
 struct wsa883x_priv {
 	struct regmap *regmap;
@@ -1430,7 +1431,7 @@ static int wsa883x_get_temp(struct wsa883x_priv *wsa883x, long *temp)
 	unsigned int dmeas_msb = 0, dmeas_lsb = 0;
 	int d1, d2, dmeas;
 	unsigned int mask;
-	int ret, range;
+	int ret;
 	long val;
 
 	guard(mutex)(&wsa883x->sp_lock);
@@ -1493,8 +1494,8 @@ static int wsa883x_get_temp(struct wsa883x_priv *wsa883x, long *temp)
 	}
 
 	val = WSA883X_T1_TEMP + (((dmeas - d1) * (WSA883X_T2_TEMP - WSA883X_T1_TEMP)) / (d2 - d1));
-	range = WSA883X_HIGH_TEMP_THRESHOLD - WSA883X_LOW_TEMP_THRESHOLD;
-	if (in_range(val, WSA883X_LOW_TEMP_THRESHOLD, range)) {
+	if (val >= WSA883X_LOW_TEMP_THRESHOLD &&
+	    val <= WSA883X_HIGH_TEMP_THRESHOLD) {
 		wsa883x->temperature = val;
 		*temp = val * 1000;
 		ret = 0;
Signature · 1 line
2.53.0
author maintainer
#793 lore raw

PATCH 791/869 net: usb: pegasus: check rx pkt_len against the received length

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Wei Jie Law <[email protected]>

[ Upstream commit efee699f6de06611234ef9b0abd52db1340e5452 ]

read_bulk_callback() takes the frame length from the device, from the receive header on the 0x8513 and from the trailing status bytes on the other chips, and only checks it against PEGASUS_MTU before passing that many bytes up the stack. In two cases the stack then uses bytes that the device did not send:

- A device that sends a short transfer but claims a long frame gets the stale or uninitialized remainder of the receive skb delivered as packet data.

- A device that claims a frame shorter than an Ethernet header gets past the check as well. eth_type_trans() takes pkt_type from h_dest and the protocol from h_proto without checking skb->len. If the transfer is also short, those come from bytes left in the skb by an earlier transfer, or from uninitialized memory.

Drop frames shorter than ETH_HLEN, and frames whose claimed length, plus the 0x8513 header, does not fit in the bytes actually received, and count them as length errors. urb->actual_length never exceeds the PEGASUS_MTU sized transfer buffer, so this also covers the existing PEGASUS_MTU check. Valid Ethernet frames are at least 60 bytes long without the FCS, so they are not affected.

Found by code review with LLM assistance. With an emulated USB device, a 101-byte transfer claiming a 1500-byte frame was passed up as a 1500-byte packet before this change and is dropped after it, and frames claiming 0, 4 and 13 bytes were passed up and are now dropped and counted in rx_length_errors. The extra bytes happened to be zero in the first test, so disclosure of actual kernel data was not demonstrated.

---
 drivers/net/usb/pegasus.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/net/usb/pegasus.c +9 -3
index f5a26a0bc679a..69445a94ee6ff 100644
@@ -523,11 +523,17 @@ static void read_bulk_callback(struct urb *urb)
 	}
 
 	/*
-	 * If the packet is unreasonably long, quietly drop it rather than
-	 * kernel panicing by calling skb_put.
+	 * Drop frames shorter than an Ethernet header, because
+	 * eth_type_trans() reads the header whatever the length, and frames
+	 * longer than what was actually received. Passing either up would
+	 * expose stale buffer contents, and skb_put() could panic on the
+	 * latter. count is at most PEGASUS_MTU.
 	 */
-	if (pkt_len > PEGASUS_MTU - rx_offset)
+	if (pkt_len < ETH_HLEN || pkt_len + rx_offset > count) {
+		net->stats.rx_errors++;
+		net->stats.rx_length_errors++;
 		goto goon;
+	}
 
 	/*
 	 * at this point we are sure pegasus->rx_skb != NULL
Signature · 1 line
2.53.0
author maintainer
#794 lore raw

PATCH 792/869 bonding: fix out-of-bounds read of arp_ip_target

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jiayuan Chen <[email protected]>

[ Upstream commit a81513bf5bdf29cf00c0a11f56be515c1ec260f4 ]

arp_ip_target is a module parameter array with BOND_MAX_ARP_TARGETS entries. In the loop parsing it in bond_check_params(), arp_ip_count is the number of accepted targets, while i is the index into arp_ip_target. Invalid and duplicate entries are skipped without bumping arp_ip_count, so bounding the loop with arp_ip_count lets i run past the end of arp_ip_target, e.g. 16 targets with one duplicate:

  BUG: KASAN: global-out-of-bounds in bond_check_params.constprop.0+0x1148/0x1440
  Read of size 8 at addr ffffffff96e9ee00 by task swapper/0/1
  Call Trace:
   <TASK>
   dump_stack_lvl+0x91/0xf0
   print_report+0xd1/0x630
   kasan_report+0xf3/0x130
   __asan_report_load8_noabort+0x14/0x30
   bond_check_params.constprop.0+0x1148/0x1440
   bonding_init+0x13/0xe0
   do_one_initcall+0xe7/0x5b0
   kernel_init_freeable+0xa91/0x1120
   kernel_init+0x24/0x220
   ret_from_fork+0x5b3/0x820
   ret_from_fork_asm+0x1a/0x30
   </TASK>

  The buggy address belongs to the variable:
   arp_ip_target+0x80/0xa0

Bound the loop with i instead. arp_ip_count never exceeds i, so it stays within BOND_MAX_ARP_TARGETS too.

---
 drivers/net/bonding/bond_main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/bonding/bond_main.c +1 -1
index baafc13603d3d..2e9e1b4d74da9 100644
@@ -6270,7 +6270,7 @@ static int __init bond_check_params(struct bond_params *params)
 	}
 
 	for (arp_ip_count = 0, i = 0;
-	     (arp_ip_count < BOND_MAX_ARP_TARGETS) && arp_ip_target[i]; i++) {
+	     (i < BOND_MAX_ARP_TARGETS) && arp_ip_target[i]; i++) {
 		__be32 ip;
 
 		/* not a complete check, but good enough to catch mistakes */
Signature · 1 line
2.53.0
author maintainer
#795 lore raw

PATCH 793/869 ipmr: fully initialize the synthetic IP header in ipmr_get_route()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Ido Schimmel <[email protected]>

[ Upstream commit 134351edc28e083c61012b6c69e8e54dd7fa5bcc ]

For an unresolved multicast route query, ipmr_get_route() builds a synthetic IP header in the headroom obtained from skb_realloc_headroom(), which does not zero the memory it allocates. Only a few fields are initialized, leaving others as stale heap contents.

ipmr_cache_report() copies this header into the IGMPMSG_NOCACHE report that is queued to the mroute socket, so a recvmsg() on that socket leaks the uninitialized bytes to user space: the 'tos' field [1] and the 'id' and 'frag_off' fields [2].

Fix by zeroing the IP header before filling in the few fields that are used, so that the entire header is initialized, as in ip6mr_get_route().

[1]

BUG: KMSAN: kernel-infoleak in _copy_to_iter
 raw_recvmsg

Uninit was stored to memory at:
ipmr_cache_report
ipmr_cache_unresolved
ipmr_get_route

Uninit was created at:
pskb_expand_head
skb_realloc_headroom
ipmr_get_route

Byte 1 of 28 is uninitialized

[2]

BUG: KMSAN: kernel-infoleak in _copy_to_iter
 raw_recvmsg

Uninit was stored to memory at:
ipmr_cache_report
ipmr_cache_unresolved
ipmr_get_route

Uninit was created at:
pskb_expand_head
skb_realloc_headroom
ipmr_get_route

Bytes 4-7 of 28 are uninitialized

---
 net/ipv4/ipmr.c | 1 +
 1 file changed, 1 insertion(+)
net/ipv4/ipmr.c +1 -0
index b1282c01a77e0..66a7f25f236b8 100644
@@ -2474,6 +2474,7 @@ int ipmr_get_route(struct net *net, struct sk_buff *skb,
 		skb_push(skb2, sizeof(struct iphdr));
 		skb_reset_network_header(skb2);
 		iph = ip_hdr(skb2);
+		memset(iph, 0, sizeof(*iph));
 		iph->ihl = sizeof(struct iphdr) >> 2;
 		iph->saddr = saddr;
 		iph->daddr = daddr;
Signature · 1 line
2.53.0
author maintainer
#796 lore raw

PATCH 794/869 dt-bindings: clock: ma35d1: Document the missing crystal inputs

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Miquel Raynal <[email protected]>

[ Upstream commit ea1f41802312e77b58113146a060fb0546b2234d ]

The MA35D1 clock controller takes two crystal oscillator inputs from the board:
- HXT, a high-speed 24 MHz crystal for most of the system
- LXT, a low-speed 32.768 kHz crytal for the RTC and low power modes

So far the binding was expecting a single crystal. The example named it HXT, but no real definition for it was given. LXT was not even described. In order to remain backward compatible, we will continue to allow either one (HXT) or two (HXT then LXT) input clocks. I propose to give those phandles a name to clarify what these entries expect, but I'm not listing the clock-names property in the required block, for backward compatibility. The rates are fixed by the TRM, so even if the second oscillator is not described, the OS can make an educated guess.

Fixes 2f8b5eb589cb ("dt-bindings: clock: nuvoton: add binding for ma35d1 clock controller")
---
 .../bindings/clock/nuvoton,ma35d1-clk.yaml       | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)
Documentation/devicetree/bindings/clock/nuvoton,ma35d1-clk.yaml +14 -2
index 8f0c43683729b..9649feda8d7a5 100644
@@ -29,7 +29,18 @@ properties:
     const: 1
 
   clocks:
-    maxItems: 1
+    minItems: 1
+    maxItems: 2
+    description:
+      The controller takes 2 crystal oscillator inputs from the board.
+      HXT is a 24 MHz crystal feeding the internal PLLs. LXT is a 32.768
+      kHz crystal, for RTC and low power operations.
+
+  clock-names:
+    minItems: 1
+    items:
+      - const: hxt
+      - const: lxt
 
   nuvoton,pll-mode:
     description:
@@ -58,6 +69,7 @@ examples:
         compatible = "nuvoton,ma35d1-clk";
         reg = <0x40460200 0x100>;
         #clock-cells = <1>;
-        clocks = <&clk_hxt>;
+        clocks = <&clk_hxt>, <&clk_lxt>;
+        clock-names = "hxt", "lxt";
     };
 ...
Signature · 1 line
2.53.0
author maintainer
#797 lore raw

PATCH 795/869 tcp: limit tcp_tso_rtt_log to a valid shift count

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yingjie Wang <[email protected]>

[ Upstream commit 850a7225bc61cdfaf0c4b02ff341ae7cb54902f5 ]

tcp_tso_autosize() right-shifts the u32 returned by tcp_min_rtt() by sysctl_tcp_tso_rtt_log. The sysctl uses proc_dou8vec_minmax() without an upper bound, so it accepts values through 255. Values above 31 make the shift undefined.

A process with CAP_NET_ADMIN in the target network namespace can set the per-netns sysctl. With CONFIG_UBSAN_SHIFT=y, setting it to 32 and sending TCP data over loopback triggers:

  UBSAN: shift-out-of-bounds in net/ipv4/tcp_output.c:2264:30
  shift exponent 32 is too large for 32-bit type 'unsigned int'
  Call Trace:
   __ubsan_handle_shift_out_of_bounds
   tcp_tso_segs
   tcp_write_xmit
   __tcp_push_pending_frames
   tcp_push
   tcp_sendmsg_locked

Limit the sysctl to 31, the largest valid shift count for a u32, and document the accepted range. Writes of larger values now fail with -EINVAL.

On a UBSAN/KASAN build of the net tree, values 0 and 31 remained accepted, values 32 and 255 returned -EINVAL, and TCP traffic with the valid boundary values produced no sanitizer diagnostics.

---
 Documentation/networking/ip-sysctl.rst | 2 ++
 net/ipv4/sysctl_net_ipv4.c             | 2 ++
 2 files changed, 4 insertions(+)
Documentation/networking/ip-sysctl.rst +2 -0
index c2ca933f7bdbc..9b8a1980bb546 100644
@@ -1088,6 +1088,8 @@ tcp_tso_rtt_log - INTEGER
 
 	If you want to use the old autosizing, set this sysctl to 0.
 
+	Possible values are [0, 31], inclusive.
+
 	Default: 9  (2^9 = 512 usec)
 
 tcp_pacing_ss_ratio - INTEGER
net/ipv4/sysctl_net_ipv4.c +2 -0
index 34a8a932402d8..bc3e5d6b8662c 100644
@@ -26,6 +26,7 @@ static int ip_local_port_range_max[] = { 65535, 65535 };
 static int tcp_adv_win_scale_min = -31;
 static int tcp_adv_win_scale_max = 31;
 static int tcp_app_win_max = 31;
+static int tcp_tso_rtt_log_max = 31;
 static int tcp_min_snd_mss_min = TCP_MIN_SND_MSS;
 static int tcp_min_snd_mss_max = 65535;
 static int tcp_rto_max_max = TCP_RTO_MAX_SEC * MSEC_PER_SEC;
@@ -1379,6 +1380,7 @@ static struct ctl_table ipv4_net_table[] = {
 		.maxlen		= sizeof(u8),
 		.mode		= 0644,
 		.proc_handler	= proc_dou8vec_minmax,
+		.extra2		= &tcp_tso_rtt_log_max,
 	},
 	{
 		.procname	= "tcp_min_rtt_wlen",
Signature · 1 line
2.53.0
author maintainer
#798 lore raw

PATCH 796/869 xsk: restore UMEM flags after failed pool assignment

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Paul Moses <[email protected]>

[ Upstream commit b88b826ec54a06f48a42580c609ba81293ebec8e ]

xp_assign_dev() sets XDP_UMEM_SG_FLAG before checking whether the device supports multibuffer zero-copy. If assignment fails, xsk_bind() destroys the pool but retains the registered UMEM. A subsequent bind without XDP_USE_SG inherits the stale flag.

The flag also changes RX buffer sizing after DMA mapping. On igc, a failed SG bind followed by a non-SG retry with 4096-byte chunks and 1792 bytes of headroom passes admission with 2048 bytes, but programs a 1024-byte RX buffer. On I225-V hardware, an ordinary 1514-byte frame is truncated to 1024 bytes or 1008 with RX timestamps enabled. Restoring the original flags eliminates the truncation in both cases.

Save the UMEM flags before assignment and restore them on failure.

Discovered during development of AF_XDP changes for igc.

---
 net/xdp/xsk_buff_pool.c | 2 ++
 1 file changed, 2 insertions(+)
net/xdp/xsk_buff_pool.c +2 -0
index 5ee0edaf075c0..9dc1ff31867a1 100644
@@ -175,6 +175,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 {
 	u32 needed = netdev->mtu + ETH_PAD_LEN;
 	u32 segs = netdev->xdp_zc_max_segs;
+	u8 umem_flags = pool->umem->flags;
 	bool mbuf = flags & XDP_USE_SG;
 	bool force_zc, force_copy;
 	struct netdev_bpf bpf;
@@ -270,6 +271,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 	if (!force_zc)
 		err = 0; /* fallback to copy mode */
 	if (err) {
+		pool->umem->flags = umem_flags;
 		xsk_clear_pool_at_qid(netdev, queue_id);
 		dev_put(netdev);
 	}
Signature · 1 line
2.53.0
author maintainer
#799 lore raw

PATCH 797/869 loop: check for read-write open mode on LOOP_SET_STATUS in lo_compat_ioctl()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Dominik Maier <[email protected]>

[ Upstream commit 87409eedc543d288cdd49c2174f7d61eca7b8db5 ]

lo_ioctl() checks for (mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN) before allowing LOOP_SET_STATUS or LOOP_SET_STATUS64, but not lo_compat_ioctl(), the handler used by 32-bit user space on 64-bit kernels.

As a result, on 64-bit kernels with CONFIG_COMPAT=y, a 32-bit unprivileged user-space process holding a read-only (O_RDONLY) file descriptor to an active /dev/loopN device can issue a compat LOOP_SET_STATUS ioctl to modify lo_offset, clear lo_sizelimit to 0 (exposing backing-file data past the configured limit), or alter lo_flags.

Enforce the same (mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN) check on LOOP_SET_STATUS in lo_compat_ioctl().

---
 drivers/block/loop.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
drivers/block/loop.c +4 -2
index 13ce229d450cd..57d3babbd63bf 100644
@@ -1686,8 +1686,10 @@ static int lo_compat_ioctl(struct block_device *bdev, blk_mode_t mode,
 
 	switch(cmd) {
 	case LOOP_SET_STATUS:
-		err = loop_set_status_compat(lo,
-			     (const struct compat_loop_info __user *)arg);
+		err = -EPERM;
+		if ((mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN))
+			err = loop_set_status_compat(lo,
+				(const struct compat_loop_info __user *)arg);
 		break;
 	case LOOP_GET_STATUS:
 		err = loop_get_status_compat(lo,
Signature · 1 line
2.53.0
author maintainer
#800 lore raw

PATCH 798/869 ALSA: usb-audio: Bound packet copies by the PCM buffer size

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Sinan Turunc <[email protected]>

[ Upstream commit 06be918062adc1a5a76dc346803b136b20bdb5ae ]

retire_capture_urb() and prepare_playback_urb() assume that one USB packet never carries more data than the whole ALSA ring buffer. Nothing enforces that: the packet size comes from the device (wMaxPacketSize, and curpacksize == maxpacksize when the class-specific endpoint descriptor sets MaxPacketsOnly), while the PCM hardware constraints only require 64-byte periods, two periods and a period time of one data interval. An 8 kHz mono U8 stream on a 128-byte buffer is legal, and a full-speed device can send 1023-byte packets into it.

On the first oversized packet hwptr_done is wrapped once and stays beyond buffer_bytes (895 for 1023 bytes into 128). On the next packet the wrap arithmetic in the copy path computes

    bytes1 = subs->buffer_bytes - oldptr

with oldptr > buffer_bytes, so bytes1 wraps to about 4 GB and memcpy() runs off the end of the URB buffer and of the vmalloc'd DMA buffer:

  BUG: KASAN: slab-out-of-bounds in retire_capture_urb+0x251/0x870
  Read of size 4294966529 at addr ffff88800c1e2800 by task vhci_rx/82

and for playback, where copy_to_urb() has the same shape:

  BUG: KASAN: vmalloc-out-of-bounds in copy_to_urb.isra.0+0x188/0x430
  Read of size 4294966529 at addr ffffc9000004537f by task vhci_rx/79
   prepare_playback_urb+0x98a/0x1fc0

Truncate an oversized capture packet to the buffer size, and stop filling a playback URB once it holds a whole buffer. With bytes <= buffer_bytes the single wrap of hwptr_done and the two-part memcpy() in both copy paths stay inside the buffer. A device whose packets do not fit the buffer at all was never going to play correctly anyway.

Reproduced on 7.3-rc7 with a USB/IP device (dummy_hcd cannot carry isochronous data) advertising a UAC1 endpoint with MaxPacketsOnly and wMaxPacketSize 1023, and a PCM client using period_size 64, periods 2.

---
 sound/usb/pcm.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
sound/usb/pcm.c +19 -1
index 682b6c1fe76ba..c2f7b08607ac8 100644
@@ -1343,6 +1343,18 @@ static void retire_capture_urb(struct snd_usb_substream *subs,
 			bytes -= adj;
 			subs->stream_offset_adj -= adj;
 		}
+		/*
+		 * A packet can be as large as the endpoint's maxpacksize, which
+		 * the device chooses, while the ring buffer can be as small as
+		 * two 64-byte periods. The hwptr_done wrap below handles one
+		 * wrap only, so never take more than one buffer from a packet.
+		 */
+		if (unlikely(bytes > subs->buffer_bytes)) {
+			dev_warn_ratelimited(&subs->dev->dev,
+					     "%u-byte packet exceeds %u-byte buffer, truncating\n",
+					     bytes, subs->buffer_bytes);
+			bytes = subs->buffer_bytes;
+		}
 		frames = bytes / stride;
 		if (!subs->txfr_quirk)
 			bytes = frames * stride;
@@ -1553,8 +1565,14 @@ static int prepare_playback_urb(struct snd_usb_substream *subs,
 
 		for (i = 0; i < ctx->packets; i++) {
 			counts = snd_usb_endpoint_next_packet_size(ep, ctx, i, avail);
+			/*
+			 * Bound by the ring buffer as well as by the URB:
+			 * copy_to_urb() wraps hwptr_done once, so one URB must
+			 * never carry more than the whole buffer.
+			 */
 			if (counts < 0 ||
-			    (frames + counts) * stride > ctx->buffer_size)
+			    (frames + counts) * stride > ctx->buffer_size ||
+			    (frames + counts) * stride > subs->buffer_bytes)
 				break;
 			/* set up descriptor */
 			urb->iso_frame_desc[i].offset = frames * stride;
Signature · 1 line
2.53.0
author maintainer
#801 lore raw

PATCH 799/869 ALSA: hda: Reject codec reset on ASoC (ext_ops) buses

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Peter Ujfalusi <[email protected]>

[ Upstream commit a4311e9447bbb219044db38897f95be112f46a8a ]

Writing to the reconfig or clear sysfs nodes of a codec handled by ASoC (SOF via hdac_hda, AVS via codecs/hda) hangs the writer.

snd_hda_codec_reset() sets card->shutdown and calls device_release_driver(). With ext_ops the driver unbind unregisters the ASoC component, which unbinds and frees the whole ASoC card:
- snd_card_disconnect() returns early as card->shutdown is already set, so the card's child devices are not removed and snd_card_free() waits for the card release forever.
- Even without that, freeing the card removes the codec's hwdep device, which owns the sysfs node the reset was issued from, deadlocking in kernfs while waiting for the active write to finish.

The legacy HDA driver keeps the card across a driver rebind, ASoC does not, so the reset cannot be supported there. Return -EOPNOTSUPP and skip the misleading "codec is being used" messages in the callers.

---
 sound/hda/common/codec.c | 6 ++++++
 sound/hda/common/sysfs.c | 4 ++++
 2 files changed, 10 insertions(+)
sound/hda/common/codec.c +6 -0
index 7869f673894fe..e6548e03a32ce 100644
@@ -1806,6 +1806,12 @@ int snd_hda_codec_reset(struct hda_codec *codec)
 {
 	struct hda_bus *bus = codec->bus;
 
+	/* ASoC: driver unbind frees the card, incl. the hwdep issuing the reset */
+	if (bus->core.ext_ops) {
+		codec_err(codec, "Codec reset is not supported with ASoC\n");
+		return -EOPNOTSUPP;
+	}
+
 	if (snd_hda_lock_devices(bus) < 0)
 		return -EBUSY;
 
sound/hda/common/sysfs.c +4 -0
index f8c8483fd5e5f..121a54ea3150a 100644
@@ -117,6 +117,8 @@ static int clear_codec(struct hda_codec *codec)
 	int err;
 
 	err = snd_hda_codec_reset(codec);
+	if (err == -EOPNOTSUPP)
+		return err;
 	if (err < 0) {
 		codec_err(codec, "The codec is being used, can't free.\n");
 		return err;
@@ -132,6 +134,8 @@ static int reconfig_codec(struct hda_codec *codec)
 	CLASS(snd_hda_power, pm)(codec);
 	codec_info(codec, "hda-codec: reconfiguring\n");
 	err = snd_hda_codec_reset(codec);
+	if (err == -EOPNOTSUPP)
+		return err;
 	if (err < 0) {
 		codec_err(codec,
 			   "The codec is being used, can't reconfigure.\n");
Signature · 1 line
2.53.0
author maintainer
#802 lore raw

PATCH 800/869 ixgbe: reserve TX timestamp after skb preparation

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Eric Dumazet <[email protected]>

[ Upstream commit f75062536e2d45ee182828f0e47e0124be2fdc8d ]

ixgbe_xmit_frame_ring() takes an extra skb reference with skb_get() for the pending TX timestamp before preparing the skb for transmit. Several of the following steps may need to reallocate the skb head:

- ixgbe_tso() calls skb_cow_head(), which reaches pskb_expand_head() when the header is cloned (e.g. a packet tap holds a clone).
- ixgbe_tx_csum() falls back to skb_checksum_help() for unsupported checksum offsets, which can call pskb_expand_head() through skb_ensure_writable().
- With DCB and a software VLAN tag, skb_cow_head() is called to rewrite the VLAN priority.

pskb_expand_head() used to BUG() on shared skbs. Since commit c7d8bc3dd511 ("net: skbuff: don't BUG() on bad arguments to pskb_expand_head()") it returns -EINVAL instead, so these packets are dropped (TSO, DCB) or sent with an unfinished checksum (skb_checksum_help() errors are ignored by ixgbe_tx_csum()).

Reserve the TX timestamp right before ixgbe_tx_map(), after all skb preparation, as i40e and ice already do. The timestamp request remains covered on the FCoE path, and the cleanup on ixgbe_tx_map() failure is unchanged.

Fixes 891dc0821d20 ("ixgbe: Add ptp work item to poll for the Tx timestamp")
---
 drivers/net/ethernet/intel/ixgbe/ixgbe_main.c | 40 +++++++++++--------
 1 file changed, 23 insertions(+), 17 deletions(-)
drivers/net/ethernet/intel/ixgbe/ixgbe_main.c +23 -17
index f950570909ab2..75ba78a84c865 100644
@@ -9426,23 +9426,6 @@ netdev_tx_t ixgbe_xmit_frame_ring(struct sk_buff *skb,
 	}
 	protocol = vlan_get_protocol(skb);
 
-	if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP) &&
-	    adapter->ptp_clock) {
-		if (adapter->tstamp_config.tx_type == HWTSTAMP_TX_ON &&
-		    !test_and_set_bit_lock(__IXGBE_PTP_TX_IN_PROGRESS,
-					   &adapter->state)) {
-			skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
-			tx_flags |= IXGBE_TX_FLAGS_TSTAMP;
-
-			/* schedule check for Tx timestamp */
-			adapter->ptp_tx_skb = skb_get(skb);
-			adapter->ptp_tx_start = jiffies;
-			schedule_work(&adapter->ptp_tx_work);
-		} else {
-			adapter->tx_hwtstamp_skipped++;
-		}
-	}
-
 #ifdef CONFIG_PCI_IOV
 	/*
 	 * Use the l2switch_enable flag - would be false if the DMA
@@ -9507,6 +9490,29 @@ netdev_tx_t ixgbe_xmit_frame_ring(struct sk_buff *skb,
 #ifdef IXGBE_FCOE
 xmit_fcoe:
 #endif /* IXGBE_FCOE */
+	/* Reserve the Tx timestamp only after all skb preparation:
+	 * skb_get() makes the skb shared, and pskb_expand_head()
+	 * (reached from skb_cow_head() or skb_checksum_help())
+	 * refuses shared skbs.
+	 */
+	if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP) &&
+	    adapter->ptp_clock) {
+		if (adapter->tstamp_config.tx_type == HWTSTAMP_TX_ON &&
+		    !test_and_set_bit_lock(__IXGBE_PTP_TX_IN_PROGRESS,
+					   &adapter->state)) {
+			skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
+			tx_flags |= IXGBE_TX_FLAGS_TSTAMP;
+			first->tx_flags |= IXGBE_TX_FLAGS_TSTAMP;
+
+			/* schedule check for Tx timestamp */
+			adapter->ptp_tx_skb = skb_get(skb);
+			adapter->ptp_tx_start = jiffies;
+			schedule_work(&adapter->ptp_tx_work);
+		} else {
+			adapter->tx_hwtstamp_skipped++;
+		}
+	}
+
 	if (ixgbe_tx_map(tx_ring, first, hdr_len))
 		goto cleanup_tx_timestamp;
 
Signature · 1 line
2.53.0
author maintainer
#803 lore raw

PATCH 801/869 ASoC: hdac_hda: Balance the runtime PM disable in codec remove

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Peter Ujfalusi <[email protected]>

[ Upstream commit f26c0d5f91d918bb66cbbc8916f41836adb38346 ]

hdac_hda_codec_remove() disables runtime PM of the codec device before releasing the HDA link and calling the codec driver's remove callback, so that no runtime resume can race with the teardown and access the link or the already freed codec driver data. snd_hda_codec_cleanup_for_unbind() then disables runtime PM again.

On the next probe snd_hda_codec_register() enables runtime PM only once, leaving it disabled after the ASoC card or the codec driver has been unbound and bound again: the codec stays powered and runtime_status reads 'unsupported'.

Re-enable runtime PM at the end of hdac_hda_codec_remove() to balance its own disable. The codec remains disabled until it is registered again.

Fixes c3ec8ac82105 ("ASoC: hdac_hda: fix memleak on module unload")
---
 sound/soc/codecs/hdac_hda.c | 4 ++++
 1 file changed, 4 insertions(+)
sound/soc/codecs/hdac_hda.c +4 -0
index b4d93b9404bb7..1a89f570fd1f4 100644
@@ -557,6 +557,7 @@ static void hdac_hda_codec_remove(struct snd_soc_component *component)
 		return;
 	}
 
+	/* prevent runtime PM callbacks while the link and the codec are torn down */
 	pm_runtime_disable(&hdev->dev);
 	snd_hdac_ext_bus_link_put(hdev->bus, hlink);
 
@@ -564,6 +565,9 @@ static void hdac_hda_codec_remove(struct snd_soc_component *component)
 		driver->ops->remove(codec);
 
 	snd_hda_codec_cleanup_for_unbind(codec);
+
+	/* Balances the disable above, cleanup_for_unbind keeps runtime PM disabled */
+	pm_runtime_enable(&hdev->dev);
 }
 
 static const struct snd_soc_dapm_route hdac_hda_dapm_routes[] = {
Signature · 1 line
2.53.0
author maintainer
#804 lore raw

PATCH 802/869 LoongArch: Call cpu_final_simd() with pure_initcall()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Huacai Chen <[email protected]>

[ Upstream commit 9b56c3659a7e5d930ab3c07ea74cc46af65b6d20 ]

After commit 35ebc4de105989034f12 ("xor: remove macro abuse for XOR implementation registrations"), using "simd=128" to limit SIMD on a platform with 256bit SIMD instructions causes a boot failure.

Because cpu_final_simd() is called with arch_initcall() now, which is after xor_init(), LASX flavors are selected but not workable.

Call cpu_final_simd() with pure_initcall() which is before xor_init().

---
 arch/loongarch/kernel/cpu-probe.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/kernel/cpu-probe.c +1 -1
index 4ac9c95991670..9f0f9fdac011b 100644
@@ -93,7 +93,7 @@ static int __init cpu_final_simd(void)
 	return 0;
 }
 
-arch_initcall(cpu_final_simd);
+pure_initcall(cpu_final_simd);
 
 static inline void set_elf_platform(int cpu, const char *plat)
 {
Signature · 1 line
2.53.0
author maintainer
#805 lore raw

PATCH 803/869 LoongArch: Use pa_to_nid()/nid_to_addrbase() rather than hard-code

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Huacai Chen <[email protected]>

[ Upstream commit 244eb26bbd152896f976db6415550993cd60b46d ]

NODE_ADDRSPACE_SHIFT is 44 now but may be changed in future, so use pa_to_nid()/nid_to_addrbase() rather than hard-code.

---
 arch/loongarch/include/asm/numa.h | 2 +-
 arch/loongarch/kernel/irq.c       | 3 ++-
 arch/loongarch/pci/pci.c          | 3 ++-
 3 files changed, 5 insertions(+), 3 deletions(-)
arch/loongarch/include/asm/numa.h +1 -1
index bbf9f70bd25f4..c9654ff900a3a 100644
@@ -14,7 +14,7 @@
 #define NODE_ADDRSPACE_SHIFT 44
 
 #define pa_to_nid(addr)		(((addr) & 0xf00000000000) >> NODE_ADDRSPACE_SHIFT)
-#define nid_to_addrbase(nid)	(_ULCAST_(nid) << NODE_ADDRSPACE_SHIFT)
+#define nid_to_addrbase(nid)	(_U64CAST_(nid) << NODE_ADDRSPACE_SHIFT)
 
 #ifdef CONFIG_NUMA
 
arch/loongarch/kernel/irq.c +2 -1
index 80946cafaec1b..130954ab9ee20 100644
@@ -19,6 +19,7 @@
 
 #include <asm/irq.h>
 #include <asm/loongson.h>
+#include <asm/numa.h>
 #include <asm/setup.h>
 
 DEFINE_PER_CPU(unsigned long, irq_stack);
@@ -68,7 +69,7 @@ static int __init early_pci_mcfg_parse(struct acpi_table_header *header)
 
 	for (i = 0; i < n; i++, mptr++) {
 		msi_group[i].pci_segment = mptr->pci_segment;
-		pch_group[i].node = msi_group[i].node = (mptr->address >> 44) & 0xf;
+		pch_group[i].node = msi_group[i].node = pa_to_nid(mptr->address);
 	}
 
 	return 0;
arch/loongarch/pci/pci.c +2 -1
index f33c7ea1443d9..0b99b32110a5d 100644
@@ -12,6 +12,7 @@
 #include <linux/io-64-nonatomic-lo-hi.h>
 #include <asm/cacheflush.h>
 #include <asm/loongson.h>
+#include <asm/numa.h>
 
 #define PCI_DEVICE_ID_LOONGSON_HOST     0x7a00
 #define PCI_DEVICE_ID_LOONGSON_DC1      0x7a06
@@ -43,7 +44,7 @@ int raw_pci_write(unsigned int domain, unsigned int bus, unsigned int devfn,
 
 phys_addr_t mcfg_addr_init(int node)
 {
-	return (((u64)node << 44) | MCFG_EXT_PCICFG_BASE);
+	return (nid_to_addrbase(node) | MCFG_EXT_PCICFG_BASE);
 }
 
 static int __init pcibios_init(void)
Signature · 1 line
2.53.0
author maintainer
#806 lore raw

PATCH 804/869 LoongArch: Remove arch-specific __smp_mb__{before,after}_atomic()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tiezhu Yang <[email protected]>

[ Upstream commit 85cebdfee765e92e748e71b9b91889eef5988282 ]

When running BPF selftest "test_progs -t timer_lockup" on a LoongArch machine, the kernel intermittently experiences soft lockups and panics in hrtimer_cancel().

The root cause is that the bpf_timer_cancel() implementation relies on smp_mb__after_atomic() to provide a full data barrier after a relaxed atomic_inc() to ensure the proper store-load ordering before performing lockless dependency checks on weakly-ordered architectures, such as on LoongArch, but the current definition of smp_mb__after_atomic() is just a plain compiler barrier.

This allows a subsequent read to bypass the prior write due to store- load reordering, enabling concurrent CPUs to simultaneously bypass the software deadlock detection, enter hrtimer_cancel(), and then trigger a severe ABBA deadlock in the hrtimer core.

Moreover, there are hundreds of smp_mb__after_atomic() call sites across the core kernel (kernel/, drivers/, mm/, net/, fs/) that currently lack necessary full data barriers on LoongArch, which have potential risks.

To comply with the LKMM specification, fix this by removing the arch- specific definition of __smp_mb__after_atomic(), so that this macro can automatically fall back to the generic definition in asm-generic that maps to __smp_mb() and emits the required hardware DBAR instruction.

While at it, do the same thing for __smp_mb__before_atomic().

With this patch the BPF timer_lockup selftest was stressed for millions consecutive loops on a physical LoongArch machine, without encountering any further lockups.

---
 arch/loongarch/include/asm/barrier.h | 3 ---
 1 file changed, 3 deletions(-)
arch/loongarch/include/asm/barrier.h +0 -3
index 4b663f1977061..84c6d739119d1 100644
@@ -57,9 +57,6 @@
 #define __WEAK_LLSC_MB		"			\n"
 #endif
 
-#define __smp_mb__before_atomic()	barrier()
-#define __smp_mb__after_atomic()	barrier()
-
 /**
  * array_index_mask_nospec() - generate a ~0 mask when index < size, 0 otherwise
  * @index: array element index
Signature · 1 line
2.53.0
author maintainer
#807 lore raw

PATCH 805/869 LoongArch: Remove redundant call in update_bp_registers()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tiezhu Yang <[email protected]>

[ Upstream commit 23534c6efeb718e8a4d9107fa7d6707b5b1f5859 ]

In update_bp_registers(), there is a duplicate call to write_wb_reg() when enabling an execute breakpoint:

    write_wb_reg(CSR_CFG_CTRL, i, 0, CTRL_PLV_ENABLE);
    write_wb_reg(CSR_CFG_CTRL, i, 0, CTRL_PLV_ENABLE);

The two lines are completely identical. Remove the redundant call to clean up the code and eliminate unnecessary register writes.

Fixes edffa33c7bb5 ("LoongArch: Add hardware breakpoints/watchpoints support")
---
 arch/loongarch/kernel/hw_breakpoint.c | 1 -
 1 file changed, 1 deletion(-)
arch/loongarch/kernel/hw_breakpoint.c +0 -1
index c35f9bf380334..deeb2f9795705 100644
@@ -453,7 +453,6 @@ static void update_bp_registers(struct pt_regs *regs, int enable, int type)
 		if (enable) {
 			if ((info->ctrl.type == LOONGARCH_BREAKPOINT_EXECUTE) && (type == 0)) {
 				write_wb_reg(CSR_CFG_CTRL, i, 0, CTRL_PLV_ENABLE);
-				write_wb_reg(CSR_CFG_CTRL, i, 0, CTRL_PLV_ENABLE);
 			} else {
 				ctrl = read_wb_reg(CSR_CFG_CTRL, i, 1);
 				if (info->ctrl.type == LOONGARCH_BREAKPOINT_LOAD)
Signature · 1 line
2.53.0
author maintainer
#808 lore raw

PATCH 806/869 LoongArch: Fix bitmask corruption in update_bp_registers()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tiezhu Yang <[email protected]>

[ Upstream commit 30c52672bf456decf675c11f3c65acd73a6bcca8 ]

In update_bp_registers(), when disabling a LOAD or STORE watchpoint, the code attempts to clear the bit of LoadEn or StoreEn by using the standard bit-clearing pattern.

However, due to the omission of parentheses, the bitwise NOT operator '~' takes higher precedence than the left shift operator '<<'. Then:
(1) ~0x1 << MWPnCFG3_LoadEn evaluates to "(~0x1) << 8 = 0xFFFFFE00",
(2) ~0x1 << MWPnCFG3_StoreEn evaluates to "(~0x1) << 9 = 0xFFFFFC00", that incorrectly clears all configuration fields in the lower 8 bits.

These fields in the lower 8 bits contain critical configurations such as DSOnly (bit 0), PLV0-PLV3 privilege levels (bits 1-4), and LCL (bit 7). Writing back these corrupted values severely breaks configuration isolation and ruins the hardware watchpoint states.

Add parentheses to ensure the correct evaluation order, so that only the targeted LoadEn/StoreEn bit is cleared while preserving the other crucial configuration bits in the lower 8 bits.

Fixes edffa33c7bb5 ("LoongArch: Add hardware breakpoints/watchpoints support")
---
 arch/loongarch/kernel/hw_breakpoint.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/loongarch/kernel/hw_breakpoint.c +2 -2
index deeb2f9795705..bd891b3808a6b 100644
@@ -468,9 +468,9 @@ static void update_bp_registers(struct pt_regs *regs, int enable, int type)
 			} else {
 				ctrl = read_wb_reg(CSR_CFG_CTRL, i, 1);
 				if (info->ctrl.type == LOONGARCH_BREAKPOINT_LOAD)
-					ctrl &= ~0x1 << MWPnCFG3_LoadEn;
+					ctrl &= ~(0x1 << MWPnCFG3_LoadEn);
 				if (info->ctrl.type == LOONGARCH_BREAKPOINT_STORE)
-					ctrl &= ~0x1 << MWPnCFG3_StoreEn;
+					ctrl &= ~(0x1 << MWPnCFG3_StoreEn);
 				write_wb_reg(CSR_CFG_CTRL, i, 1, ctrl);
 			}
 			regs->csr_prmd &= ~CSR_PRMD_PWE;
Signature · 1 line
2.53.0
author maintainer
#809 lore raw

PATCH 807/869 LoongArch: Fix architectural naming typo for CSR_FWPS_SKIP

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tiezhu Yang <[email protected]>

[ Upstream commit f322ebfdfda2bce91fb1d3fb0072c735051fed85 ]

According to the LoongArch Reference Manual, the single-step 'Skip' bit resides in the instruction breakpoint status register (CSR.FWPS), rather than the configuration register (CSR.FWPC).

Furthermore, the kernel code comments also explicitly document it as "CSR.FWPS.Skip", yet the macro was erroneously defined as CSR_FWPC_SKIP and used as such in traps.c and hw_breakpoint.c. This mismatch creates architectural naming confusion.

Fix this by renaming the macro from CSR_FWPC_SKIP to CSR_FWPS_SKIP to precisely match the manual and comments. Also, update all call sites to align with the rectified definition.

Fixes 424421a7f34c ("LoongArch: ptrace: Add hardware single step support")
---
 arch/loongarch/include/asm/loongarch.h | 4 ++--
 arch/loongarch/kernel/hw_breakpoint.c  | 2 +-
 arch/loongarch/kernel/traps.c          | 4 ++--
 3 files changed, 5 insertions(+), 5 deletions(-)
arch/loongarch/include/asm/loongarch.h +2 -2
index 58a4a3b6b035d..642dc9adddceb 100644
@@ -1090,8 +1090,8 @@
 #define LOONGARCH_CSR_DERA		0x501	/* debug era */
 #define LOONGARCH_CSR_DESAVE		0x502	/* debug save */
 
-#define CSR_FWPC_SKIP_SHIFT		16
-#define CSR_FWPC_SKIP			(_ULCAST_(1) << CSR_FWPC_SKIP_SHIFT)
+#define CSR_FWPS_SKIP_SHIFT		16
+#define CSR_FWPS_SKIP			(_ULCAST_(1) << CSR_FWPS_SKIP_SHIFT)
 
 /*
  * CSR_ECFG IM
arch/loongarch/kernel/hw_breakpoint.c +1 -1
index bd891b3808a6b..7f69cf361a5e2 100644
@@ -550,7 +550,7 @@ void hw_breakpoint_thread_switch(struct task_struct *next)
 		addr = read_wb_reg(CSR_CFG_ADDR, 0, 0);
 		mask = read_wb_reg(CSR_CFG_MASK, 0, 0);
 		if (!((regs->csr_era ^ addr) & ~mask))
-			csr_write32(CSR_FWPC_SKIP, LOONGARCH_CSR_FWPS);
+			csr_write32(CSR_FWPS_SKIP, LOONGARCH_CSR_FWPS);
 		regs->csr_prmd |= CSR_PRMD_PWE;
 	} else {
 		/* Update breakpoints */
arch/loongarch/kernel/traps.c +2 -2
index 8e51ce004572c..4c2e5a13f07e4 100644
@@ -821,7 +821,7 @@ asmlinkage void noinstr do_watch(struct pt_regs *regs)
 			 * instruction. So don't clear llbit and reset CSR.FWPS.Skip until
 			 * the llsc execution is completed.
 			 */
-			csr_write32(CSR_FWPC_SKIP, LOONGARCH_CSR_FWPS);
+			csr_write32(CSR_FWPS_SKIP, LOONGARCH_CSR_FWPS);
 			csr_write32(CSR_LLBCTL_KLO, LOONGARCH_CSR_LLBCTL);
 			goto out;
 		}
@@ -838,7 +838,7 @@ asmlinkage void noinstr do_watch(struct pt_regs *regs)
 				 * current pc, If yes, then we should not set the CSR.FWPS.SKIP
 				 * bit to break the original instruction stream.
 				 */
-				csr_write32(CSR_FWPC_SKIP, LOONGARCH_CSR_FWPS);
+				csr_write32(CSR_FWPS_SKIP, LOONGARCH_CSR_FWPS);
 				goto out;
 			}
 		}
Signature · 1 line
2.53.0
author maintainer
#810 lore raw

PATCH 808/869 LoongArch: Only send SIGTRAP signal if necessary in do_watch()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tiezhu Yang <[email protected]>

[ Upstream commit f087903018e35d38b8932e18b010ee2e8699d1a1 ]

In do_watch(), the kernel unconditionally forces a SIGTRAP signal at the end of the handler via force_sig(SIGTRAP). This is essential for ptrace operations, but it severely disrupts standard perf_event usage.

Under normal perf usage, it is not necessary to force a SIGTRAP signal on every hit. Forcing it unnecessarily aborts the target process if no user-space signal handler is registered, which violates performance monitoring behaviors and injects context switch overheads.

However, a conditional check using only 'current->ptrace' would block legitimate user-requested signals when a perf_event is configured with 'attr.sigtrap = 1' for asynchronous user-space tracking.

Fix this by refactoring breakpoint_handler() and watchpoint_handler() to return a boolean status indicating whether any triggered breakpoint explicitly requires a signal notification. Update do_watch() to enforce the SIGTRAP signal only when the process is actively being debugged via ptrace, or when the underlying perf_event infrastructure specifically demands it via 'attr.sigtrap'.

Fixes 424421a7f34c ("LoongArch: ptrace: Add hardware single step support")
---
 arch/loongarch/include/asm/hw_breakpoint.h |  4 ++--
 arch/loongarch/kernel/hw_breakpoint.c      | 18 ++++++++++++++++--
 arch/loongarch/kernel/traps.c              |  9 ++++++---
 3 files changed, 24 insertions(+), 7 deletions(-)
arch/loongarch/include/asm/hw_breakpoint.h +2 -2
index 5faa97a87a9e2..d202052df8a16 100644
@@ -116,8 +116,8 @@ extern void arch_uninstall_hw_breakpoint(struct perf_event *bp);
 extern int hw_breakpoint_slots(int type);
 extern void hw_breakpoint_pmu_read(struct perf_event *bp);
 
-void breakpoint_handler(struct pt_regs *regs);
-void watchpoint_handler(struct pt_regs *regs);
+bool breakpoint_handler(struct pt_regs *regs);
+bool watchpoint_handler(struct pt_regs *regs);
 
 #ifdef CONFIG_HAVE_HW_BREAKPOINT
 extern void ptrace_hw_copy_thread(struct task_struct *task);
arch/loongarch/kernel/hw_breakpoint.c +16 -2
index 7f69cf361a5e2..d009ed780cf02 100644
@@ -482,9 +482,10 @@ NOKPROBE_SYMBOL(update_bp_registers);
 /*
  * Debug exception handlers.
  */
-void breakpoint_handler(struct pt_regs *regs)
+bool breakpoint_handler(struct pt_regs *regs)
 {
 	int i;
+	bool need_sigtrap = false;
 	struct perf_event *bp, **slots;
 
 	slots = this_cpu_ptr(bp_on_reg);
@@ -494,17 +495,24 @@ void breakpoint_handler(struct pt_regs *regs)
 			bp = slots[i];
 			if (bp == NULL)
 				continue;
+
 			perf_bp_event(bp, regs);
+			if (bp->attr.sigtrap)
+				need_sigtrap = true;
+
 			csr_write32(0x1 << i, LOONGARCH_CSR_FWPS);
 			update_bp_registers(regs, 0, 0);
 		}
 	}
+
+	return need_sigtrap;
 }
 NOKPROBE_SYMBOL(breakpoint_handler);
 
-void watchpoint_handler(struct pt_regs *regs)
+bool watchpoint_handler(struct pt_regs *regs)
 {
 	int i;
+	bool need_sigtrap = false;
 	struct perf_event *wp, **slots;
 
 	slots = this_cpu_ptr(wp_on_reg);
@@ -514,11 +522,17 @@ void watchpoint_handler(struct pt_regs *regs)
 			wp = slots[i];
 			if (wp == NULL)
 				continue;
+
 			perf_bp_event(wp, regs);
+			if (wp->attr.sigtrap)
+				need_sigtrap = true;
+
 			csr_write32(0x1 << i, LOONGARCH_CSR_MWPS);
 			update_bp_registers(regs, 0, 1);
 		}
 	}
+
+	return need_sigtrap;
 }
 NOKPROBE_SYMBOL(watchpoint_handler);
 
arch/loongarch/kernel/traps.c +6 -3
index 4c2e5a13f07e4..9ce12327d64ea 100644
@@ -807,6 +807,8 @@ asmlinkage void noinstr do_watch(struct pt_regs *regs)
 #ifndef CONFIG_HAVE_HW_BREAKPOINT
 	pr_warn("Hardware watch point handler not implemented!\n");
 #else
+	bool need_sigtrap = !!current->ptrace;
+
 	if (kgdb_breakpoint_handler(regs))
 		goto out;
 
@@ -843,11 +845,12 @@ asmlinkage void noinstr do_watch(struct pt_regs *regs)
 			}
 		}
 	} else {
-		breakpoint_handler(regs);
-		watchpoint_handler(regs);
+		need_sigtrap |= breakpoint_handler(regs);
+		need_sigtrap |= watchpoint_handler(regs);
 	}
 
-	force_sig(SIGTRAP);
+	if (need_sigtrap)
+		force_sig(SIGTRAP);
 out:
 #endif
 	irqentry_exit(regs, state);
Signature · 1 line
2.53.0
author maintainer
#811 lore raw

PATCH 809/869 LoongArch: Fix perf hardware breakpoint failure via installation

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tiezhu Yang <[email protected]>

[ Upstream commit f5c0f8427469e703465c719c4304ce91282a32eb ]

In hw_breakpoint_control(), the logic to enable CSR_PRMD_PWE (global watchpoint enable) incorrectly relies on TIF_LOAD_WATCH. This thread flag is only set during ptrace operations, meaning that the standard hardware breakpoints created via perf_event_open() will never have this flag set.

As a result, the CSR_PRMD_PWE switch is skipped, leaving the hardware breakpoint completely inactive in perf usage.

Fix this by decoupling the CSR_PRMD_PWE from the ptrace specific flag TIF_LOAD_WATCH, which ensures that CSR_PRMD_PWE is enabled whenever a hardware breakpoint is installed.

Here is a user-space reproducer to demonstrate the issue:

(1) Test program (test_perf_install.c):

  #include <stdio.h>
  #include <unistd.h>
  #include <sys/syscall.h>
  #include <sys/ioctl.h>
  #include <linux/perf_event.h>
  #include <linux/hw_breakpoint.h>

  static int var = 0;

  int main(void)
  {
  	size_t count = 0;
  	struct perf_event_attr attr = {
  		.type = PERF_TYPE_BREAKPOINT,
  		.size = sizeof(attr),
  		.bp_type = HW_BREAKPOINT_W,
  		.bp_addr = (unsigned long)&var,
  		.bp_len = HW_BREAKPOINT_LEN_1,
  		.exclude_kernel = 1,
  	};

  	int fd = syscall(__NR_perf_event_open, &attr, 0, -1, -1, 0);
  	ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);

  	asm volatile("st.b %1, %0" : "=m"(var) : "r"(11) : "memory");

  	ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
  	read(fd, &count, sizeof(size_t));

  	printf("Watchpoint counts: expected = 1, actual = %zu\n", count);

  	close(fd);
  	return 0;
  }

(2) Test steps:

  $ gcc test_perf_install.c -o test_perf_install
  $ ./test_perf_install

(3) Test results:

Without this patch:

Watchpoint counts: expected = 1, actual = 0

With this patch:

Watchpoint counts: expected = 1, actual = 1

Fixes 3892b11eac5a ("LoongArch: Check TIF_LOAD_WATCH to enable user space watchpoint")
---
 arch/loongarch/kernel/hw_breakpoint.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/kernel/hw_breakpoint.c +1 -1
index d009ed780cf02..1a05350159f7b 100644
@@ -233,7 +233,7 @@ static int hw_breakpoint_control(struct perf_event *bp,
 		}
 		enable = csr_read64(LOONGARCH_CSR_CRMD);
 		csr_write64(CSR_CRMD_WE | enable, LOONGARCH_CSR_CRMD);
-		if (bp->hw.target && test_tsk_thread_flag(bp->hw.target, TIF_LOAD_WATCH))
+		if (bp->hw.target)
 			regs->csr_prmd |= CSR_PRMD_PWE;
 		break;
 	case HW_BREAKPOINT_UNINSTALL:
Signature · 1 line
2.53.0
author maintainer
#812 lore raw

PATCH 810/869 cpufreq: stats: Fix potential out-of-bounds access in deferred reset

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhongqiu Han <[email protected]>

[ Upstream commit 8a702989677216489e471a6f27599da53f753567 ]

cpufreq_stats_create_table() sets stats->last_index to -1 if policy->cur is not in the frequency table. It then stays at -1, because cpufreq_stats_record_transition() returns early on old_index == -1 before it gets to update last_index.

Commit 46a310b80bc2 ("[CPUFREQ] Don't set stat->last_index to -1 if the pol->cur has incorrect value.") added that check. However, since commit 40c3bd4cfa6f ("cpufreq: stats: Defer stats update to cpufreq_stats_record_transition()"), the stats reset is deferred to the beginning of cpufreq_stats_record_transition(), before that check, and cpufreq_stats_reset_table() ends with an unconditional cpufreq_stats_update(). So if the "reset" attribute is written while last_index is -1, the next frequency transition accesses time_in_state[-1].

Fix it by also returning early on last_index == -1 in cpufreq_stats_reset_table().

Fixes 40c3bd4cfa6f ("cpufreq: stats: Defer stats update to cpufreq_stats_record_transition()")
Cc 5.10+ <[email protected]> # 5.10+
---
 drivers/cpufreq/cpufreq_stats.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/cpufreq/cpufreq_stats.c +4 -0
index 40a9ff18da068..d457848b3eabd 100644
@@ -52,6 +52,10 @@ static void cpufreq_stats_reset_table(struct cpufreq_stats *stats)
 	 * reset_pending accesses in cpufreq_stats_record_transition().
 	 */
 	smp_rmb();
+
+	if (stats->last_index == -1)
+		return;
+
 	cpufreq_stats_update(stats, READ_ONCE(stats->reset_time));
 }
 
Signature · 1 line
2.53.0
author maintainer
#813 lore raw

PATCH 811/869 arm64/mm: restrict transparent contpte mappings to valid PTEs

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Gongyi <[email protected]>

[ Upstream commit 486d396b19e93f6e56e0a0ba96c14a9ccc1a5977 ]

The transparent contpte layer treats PTE_CONT as software grouping state. When a valid PTE has PTE_CONT set, the contpte helpers may align an operation to a CONT_PTE_SIZE block and operate on the whole block. The current single-PTE helpers use pte_valid_cont() to identify such groups; this is a helper contract, not an architectural restriction on using PTE_CONT with present-invalid descriptors. Explicit users such as hugetlb manage their contiguous encodings separately.

contpte_set_ptes() currently sets PTE_CONT from alignment alone. Batched set_ptes() users can therefore install present-invalid PTEs with PTE_CONT set, for example mprotect(PROT_NONE), NUMA hinting through modify_prot_commit_ptes(), fork() copying a PROT_NONE large folio, or a PMD split installing PAGE_NONE PTEs.

This is not a hardware programming problem: invalid descriptors are not translated, so the hardware ignores descriptor bits such as PTE_CONT. It is a software-state problem. Some arm64 fast paths, such as test_and_clear_young_ptes(), test pte_cont() directly instead of pte_valid_cont().

In the observed failure, mprotect(PROT_NONE) installed a full CONT_PTE_SIZE range of present-invalid PTEs with PTE_CONT set. MADV_GUARD_INSTALL then zapped one PTE. The nr == 1 clear_full_ptes() path only unfolds pte_valid_cont() entries, so the neighbouring present-invalid entries kept PTE_CONT while the target entry became a guard marker.

clear_refs_pte_range() then reached the marker through:

ptep_test_and_clear_young()
test_and_clear_young_ptes()
contpte_test_and_clear_young_ptes()
contpte_align_addr_ptep()
__ptep_test_and_clear_young()

The marker changed from old_pte=0x00000000000047c0 to new_pte=0x00000000000043c0 by clearing PTE_AF. For swap PTEs, bit 10 is part of the swap type field, bits 6-10: 0x47c0 is SWP_PTE_MARKER with offset 4, while 0x43c0 has type 15 and is decoded as an ordinary swap entry. Zap later warned in swap_put_entries_direct() with a bad swap entry.

Present-invalid PTEs could retain PTE_CONT as software grouping state, but their single-PTE modification paths would then need to recognize and unfold those groups consistently. Since current helpers mostly use pte_valid_cont() for membership, avoid creating present-invalid transparent contpte groups in contpte_set_ptes(). They bring no hardware benefit while invalid, and eligible valid ranges can be grouped again when they are installed.

The public set_ptes() wrapper already clears PTE_CONT before calling contpte_set_ptes(). Return invalid PTEs through __set_ptes() directly, and warn if a future direct caller unexpectedly passes an invalid PTE with PTE_CONT set.

This is triggerable by a user process against its own address space. On systems running with panic_on_warn, the warning becomes a denial of service.

Fixes 4602e5757bcc ("arm64/mm: wire up PTE_CONT for user mappings")
---
 arch/arm64/include/asm/pgtable.h | 3 +++
 arch/arm64/mm/contpte.c          | 4 +++-
 2 files changed, 6 insertions(+), 1 deletion(-)
arch/arm64/include/asm/pgtable.h +3 -0
index 1765e484fb9f0..2ce69d64e60ca 100644
@@ -1675,6 +1675,9 @@ extern void modify_prot_commit_ptes(struct vm_area_struct *vma, unsigned long ad
  * The contpte APIs are used to transparently manage the contiguous bit in ptes
  * where it is possible and makes sense to do so. The PTE_CONT bit is considered
  * a private implementation detail of the public ptep API (see below).
+ * Single-PTE transparent contpte helpers use pte_valid_cont() to identify
+ * grouped PTEs; explicit contiguous-encoding users such as hugetlb manage
+ * their entries separately.
  */
 extern void __contpte_try_fold(struct mm_struct *mm, unsigned long addr,
 				pte_t *ptep, pte_t pte);
arch/arm64/mm/contpte.c +3 -1
index 29024e20e876d..c39a290c6b5a2 100644
@@ -444,8 +444,10 @@ void contpte_set_ptes(struct mm_struct *mm, unsigned long addr,
 	 */
 	VM_WARN_ON(nr == 1);
 
-	if (!mm_is_user(mm))
+	if (!mm_is_user(mm) || !pte_valid(pte)) {
+		VM_WARN_ON_ONCE(!pte_valid(pte) && pte_cont(pte));
 		return __set_ptes(mm, addr, ptep, pte, nr);
+	}
 
 	end = addr + (nr << PAGE_SHIFT);
 	pfn = pte_pfn(pte);
Signature · 1 line
2.53.0
author maintainer
#814 lore raw

PATCH 812/869 perf machine: Fix NULL deref in thread__resolve_callchain_sample()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: lvyating <[email protected]>

[ Upstream commit 4626d370ae89b8af4d46a45372b269f926ec662d ]

When recording with -j stack, resolve_lbr_callchain_sample() can dereference a NULL 'chain' pointer while resolving the branch stack.

$ perf record -j stack -e branches:u uname
perf: Segmentation fault

Fix it by checking 'chain' for NULL before dereferencing it.

Fixes 29be60c93d2d9300 ("perf build-id: Mark DSO in sample callchains")
Cc Adrian Hunter <[email protected]>
Cc Alexander Shishkin <[email protected]>
Cc Dai Hualiang <[email protected]>
Cc Ian Rogers <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc James Clark <[email protected]>
Cc Jiri Olsa <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Namhyung Kim <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Qingtao Liu <[email protected]>
Cc Shen Lin <[email protected]>
---
 tools/perf/util/machine.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/perf/util/machine.c +1 -1
index cb138d1bdd7b9..8452d776d994a 100644
@@ -2743,7 +2743,7 @@ static int thread__resolve_callchain_sample(struct thread *thread,
 	if (chain)
 		chain_nr = chain->nr;
 
-	if (evsel__has_branch_callstack(evsel)) {
+	if (chain && evsel__has_branch_callstack(evsel)) {
 		struct perf_env *env = evsel__env(evsel);
 
 		err = resolve_lbr_callchain_sample(thread, cursor, sample, parent,
Signature · 1 line
2.53.0
author maintainer
#815 lore raw

PATCH 813/869 drm/amdkfd: stop restore retries on device unplug

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Olivier Kaloudoff <[email protected]>

[ Upstream commit 3254ed0b15f2fe656c9cb36ccb59b92422440bf8 ]

amdgpu_amdkfd_restore_userptr_worker() and svm_range_restore_work() reschedule themselves when validation fails with evicted objects pending. After a surprise removal the restore paths fail with -ENODEV permanently, so rescheduling just spins the worker uselessly until cancel_delayed_work_sync() in fini finally stops it - which can take a while, since process teardown itself is delayed by the dead device.

Treat -ENODEV as terminal in both workers.

Cc Xiaogang Chen <[email protected]>
(cherry picked from commit 266fab83139600e58db7e900e930c722e619b78c)
---
 .../gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c   | 18 +++++++++++++-----
 drivers/gpu/drm/amd/amdkfd/kfd_svm.c           |  8 +++++---
 2 files changed, 18 insertions(+), 8 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +13 -5
index 35dffb14a20aa..6de7dfa30ce50 100644
@@ -2824,6 +2824,7 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
 	struct task_struct *usertask;
 	struct mm_struct *mm;
 	uint32_t evicted_bos;
+	int ret;
 
 	mutex_lock(&process_info->notifier_lock);
 	evicted_bos = process_info->evicted_bos;
@@ -2843,14 +2844,16 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
 
 	mutex_lock(&process_info->lock);
 
-	if (update_invalid_user_pages(process_info, mm))
+	ret = update_invalid_user_pages(process_info, mm);
+	if (ret)
 		goto unlock_out;
 	/* userptr_inval_list can be empty if all evicted userptr BOs
 	 * have been freed. In that case there is nothing to validate
 	 * and we can just restart the queues.
 	 */
 	if (!list_empty(&process_info->userptr_inval_list)) {
-		if (validate_invalid_user_pages(process_info))
+		ret = validate_invalid_user_pages(process_info);
+		if (ret)
 			goto unlock_out;
 	}
 	/* Final check for concurrent evicton and atomic update. If
@@ -2859,11 +2862,14 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
 	 * reference counting inside KFD will handle this case.
 	 */
 	mutex_lock(&process_info->notifier_lock);
-	if (process_info->evicted_bos != evicted_bos)
+	if (process_info->evicted_bos != evicted_bos) {
+		ret = -EAGAIN;
 		goto unlock_notifier_out;
+	}
 
 	if (confirm_valid_user_pages_locked(process_info)) {
 		WARN(1, "User pages unexpectedly invalid");
+		ret = -EINVAL;
 		goto unlock_notifier_out;
 	}
 
@@ -2881,8 +2887,10 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
 unlock_out:
 	mutex_unlock(&process_info->lock);
 
-	/* If validation failed, reschedule another attempt */
-	if (evicted_bos) {
+	/* If validation failed, reschedule another attempt, unless the
+	 * device is gone for good
+	 */
+	if (evicted_bos && ret != -ENODEV) {
 		queue_delayed_work(system_freezable_wq,
 			&process_info->restore_userptr_work,
 			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
drivers/gpu/drm/amd/amdkfd/kfd_svm.c +5 -3
index 1b29dee7948d8..366b31191ac1e 100644
@@ -1853,7 +1853,7 @@ static void svm_range_restore_work(struct work_struct *work)
 	struct mm_struct *mm;
 	int evicted_ranges;
 	int invalid;
-	int r;
+	int r = 0;
 
 	svms = container_of(dwork, struct svm_range_list, restore_work);
 	evicted_ranges = atomic_read(&svms->evicted_ranges);
@@ -1927,8 +1927,10 @@ static void svm_range_restore_work(struct work_struct *work)
 	mmap_write_unlock(mm);
 	mutex_unlock(&process_info->lock);
 
-	/* If validation failed, reschedule another attempt */
-	if (evicted_ranges) {
+	/* If validation failed, reschedule another attempt, unless the
+	 * device is gone for good
+	 */
+	if (evicted_ranges && r != -ENODEV) {
 		pr_debug("reschedule to restore svm range\n");
 		queue_delayed_work(system_freezable_wq, &svms->restore_work,
 			msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS));
Signature · 1 line
2.53.0