Skip to contentSkip to conversation

6.18.64-rc1 review

PATCH In review Greg Kroah-Hartman 14 participants 700 messages Nov 13 – Nov 16 Page 3 of 6

Subsystems (3)
lore
Share & tools
lore
author maintainer
#219 lore raw

PATCH 219/686 drm/vc4: hdmi: enable scrambling before the TMDS clock starts

In reply to Greg Kroah-Hartman

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

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

From: Lucas Tanure <[email protected]>

[ Upstream commit 81383bd290a18f06ccf9b0bfb29e1a3ef73d9357 ]

HDMI 2.0 requires a source to suspend the TMDS clock, write the TMDS_Bit_Clock_Ratio bit in the sink's SCDC registers, wait at least 1 ms and only then resume the clock. vc4 does the opposite: the PHY starts at the new rate first, and the SCDC bits are written tens of milliseconds later, at the very end of the enable sequence, together with the source side scrambler. On disable the bits are cleared while the clock is still running.

Some sinks sample the bit only when the clock appears. One HDMI 2.0 sink we tested then sets up its receiver for a 1/10 clock and never
recovers: a Raspberry Pi 5 at 3840x2160@60 shows no picture, while 1080p60 and 4K30 work and other sources work at 4K60 on the same sink. Writing the bit by hand before enabling the output makes the same mode lock every time.

Enable scrambling, on the sink and in the controller, before the PHY is started, and disable it only after the PHY has been stopped. The SCDC helper already waits the required time after writing the ratio bit.

---
 drivers/gpu/drm/vc4/vc4_hdmi.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/gpu/drm/vc4/vc4_hdmi.c +4 -3
index 7a84d8414436f..8f5d43946583a 100644
@@ -839,8 +839,6 @@ static void vc4_hdmi_encoder_post_crtc_disable(struct drm_encoder *encoder,
 		spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
 	}
 
-	vc4_hdmi_disable_scrambling(encoder);
-
 	drm_dev_exit(idx);
 
 out:
@@ -869,6 +867,8 @@ static void vc4_hdmi_encoder_post_crtc_powerdown(struct drm_encoder *encoder,
 	if (vc4_hdmi->variant->phy_disable)
 		vc4_hdmi->variant->phy_disable(vc4_hdmi);
 
+	vc4_hdmi_disable_scrambling(encoder);
+
 	clk_disable_unprepare(vc4_hdmi->pixel_bvb_clock);
 	clk_disable_unprepare(vc4_hdmi->pixel_clock);
 
@@ -1478,6 +1478,8 @@ static void vc4_hdmi_encoder_pre_crtc_configure(struct drm_encoder *encoder,
 		goto err_disable_pixel_clock;
 	}
 
+	vc4_hdmi_enable_scrambling(encoder);
+
 	if (vc4_hdmi->variant->phy_init)
 		vc4_hdmi->variant->phy_init(vc4_hdmi, conn_state);
 
@@ -1612,7 +1614,6 @@ static void vc4_hdmi_encoder_post_crtc_enable(struct drm_encoder *encoder,
 	}
 
 	vc4_hdmi_recenter_fifo(vc4_hdmi);
-	vc4_hdmi_enable_scrambling(encoder);
 
 	drm_dev_exit(idx);
 
Signature · 1 line
2.53.0
author maintainer
#220 lore raw

PATCH 220/686 sctp: account for chunk padding in sctp_init_cause()

In reply to Greg Kroah-Hartman

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

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

From: Masafumi Suzuki <[email protected]>

[ Upstream commit ed6c53b27be492643da2017c6f8e2732be5edf1a ]

sctp_init_cause() accepts a chunk when skb_tailroom() can hold the cause header and the payload. sctp_addto_chunk() then writes 0-3 bytes of padding before that header so the chunk stays 4-byte aligned. The check does not include the padding, and the following skb_put() calls skb_over_panic() from softirq.

Count the padding sctp_addto_chunk() is about to write. The cause length on the wire stays the header plus the payload.

Found by LLM inspection, triggered and tested the fix.

Fixes 8914f4bace3f ("sctp: add sctp_make_op_error_limited and reuse inner functions")
---
 net/sctp/sm_make_chunk.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
net/sctp/sm_make_chunk.c +8 -1
index 04716666b29ba..8e4e88b1d0c06 100644
@@ -136,6 +136,7 @@ int sctp_init_cause(struct sctp_chunk *chunk, __be16 cause_code,
 		    size_t paylen)
 {
 	struct sctp_errhdr err;
+	int chunklen, padlen;
 	__u16 len;
 
 	/* Cause code constants are now defined in network order.  */
@@ -143,7 +144,13 @@ int sctp_init_cause(struct sctp_chunk *chunk, __be16 cause_code,
 	len = sizeof(err) + paylen;
 	err.length = htons(len);
 
-	if (skb_tailroom(chunk->skb) < len)
+	/* sctp_addto_chunk() pads the chunk up to a 4-byte boundary before
+	 * appending the cause, so account for that padding here as well.
+	 */
+	chunklen = ntohs(chunk->chunk_hdr->length);
+	padlen = SCTP_PAD4(chunklen) - chunklen;
+
+	if (skb_tailroom(chunk->skb) < padlen + len)
 		return -ENOSPC;
 
 	chunk->subh.err_hdr = sctp_addto_chunk(chunk, sizeof(err), &err);
Signature · 1 line
2.53.0
author maintainer
#221 lore raw

PATCH 221/686 btrfs: sysfs: restore NOFS context on early return in btrfs_sysfs_add_block_group_type()

In reply to Greg Kroah-Hartman

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

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

From: guolingxing <[email protected]>

[ Upstream commit 4172be965c2ce887ebfb1117c634a68555be8c11 ]

btrfs_sysfs_add_block_group_type() sets up a NOFS context with memalloc_nofs_save() because kobject_add() performs GFP_KERNEL allocations deep in its call chain, and the function may be called while holding a transaction handle or a lock required for a transaction commit, where reclaim could deadlock.

Every other return path of this function calls memalloc_nofs_restore() except the early return taken when another thread has already created the kobject for the same raid index (this can happen when restriping). Taking that path leaves PF_MEMALLOC_NOFS set on the calling task, so all subsequent memory allocations performed by that task remain restricted to the NOFS scope, which may lead to unexpected allocation failures or deadlocks later on.

Restore the NOFS context before returning from that path.

Fixes 49ea112da0e6 ("btrfs: do not create raid sysfs entries under any locks")
---
 fs/btrfs/sysfs.c | 1 +
 1 file changed, 1 insertion(+)
fs/btrfs/sysfs.c +1 -0
index d66681ce2b3da..204edb659304b 100644
@@ -1899,6 +1899,7 @@ void btrfs_sysfs_add_block_group_type(struct btrfs_block_group *cache)
 	if (space_info->block_group_kobjs[index]) {
 		spin_unlock(&space_info->lock);
 		kobject_put(&rkobj->kobj);
+		memalloc_nofs_restore(nofs_flag);
 		return;
 	} else {
 		space_info->block_group_kobjs[index] = &rkobj->kobj;
Signature · 1 line
2.53.0
author maintainer
#222 lore raw

PATCH 222/686 ptp: fix use-after-free in extts_fifo_show() reading tsevqs unlocked

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 603a0c40d414ea12509fc45f2b930449a8d4aad2 ]

extts_fifo_show() walks ptp->tsevqs with list_count_nodes() and then list_first_entry() without holding ptp->tsevqs_lock, the spinlock that "protects tsevqs from concurrent access". Every other accessor of the list honours it: ptp_open() (list_add_tail), ptp_release() (list_del followed by kfree of the per-fd queue), ptp_clock_release() and ptp_clock_event() all take tsevqs_lock. extts_fifo_show() is the only one that does not.

A per-fd timestamp queue is appended to tsevqs on open("/dev/ptpN") and removed and freed on close(), both under tsevqs_lock:

	scoped_guard(spinlock_irq, &ptp->tsevqs_lock)
		list_del(&queue->qlist);
	bitmap_free(queue->mask);
	kfree(queue);

So a read of /sys/class/ptp/ptpN/fifo running concurrently with a close() of a /dev/ptpN fd can have list_count_nodes() walk into the queue that close() is removing and freeing, dereferencing freed memory (use-after-free) or a poisoned list pointer.

Take tsevqs_lock around the list walk. The fifo only ever draws from the first queue, which is the registration-time queue created in ptp_clock_register() and freed only in ptp_clock_release(); that cannot run while the sysfs attribute is being read, so the dequeue from queue->buf under queue->lock may stay outside tsevqs_lock and the lock order is unchanged.

Fixes d26ab5a35ad9 ("ptp: Replace timestamp event queue with linked list")
---
 drivers/ptp/ptp_sysfs.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/ptp/ptp_sysfs.c +5 -1
index 200eaf5006968..0d4b081daf639 100644
@@ -80,13 +80,17 @@ static ssize_t extts_fifo_show(struct device *dev,
 	size_t qcnt;
 	int cnt = 0;
 
+	spin_lock_irqsave(&ptp->tsevqs_lock, flags);
 	cnt = list_count_nodes(&ptp->tsevqs);
-	if (cnt <= 0)
+	if (cnt <= 0) {
+		spin_unlock_irqrestore(&ptp->tsevqs_lock, flags);
 		goto out;
+	}
 
 	/* The sysfs fifo will always draw from the fist queue */
 	queue = list_first_entry(&ptp->tsevqs, struct timestamp_event_queue,
 				 qlist);
+	spin_unlock_irqrestore(&ptp->tsevqs_lock, flags);
 
 	memset(&event, 0, sizeof(event));
 	spin_lock_irqsave(&queue->lock, flags);
Signature · 1 line
2.53.0
author maintainer
#223 lore raw

PATCH 223/686 scsi: bsg: Report synchronous data copyback failures

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 a52f2ad45726d788755b525adcf51f65a6b836ff ]

scsi_bsg_sg_io_fn() ignores the result of blk_rq_unmap_user(). For a data-in command that uses a bounce buffer, unmapping copies the completed data to userspace. If that copy fails, SG_IO can report success despite the copyback failure.

Capture the unmap status. Preserve an earlier sense-buffer copy error and otherwise return the data copyback error. This matches the error precedence used by scsi_complete_sghdr_rq().

On x86_64, a virtio-scsi INQUIRY with an unaligned PROT_NONE destination made ioctl() return 0 in 20/20 runs before this change and return -1 with errno EFAULT in 20/20 runs afterward. Writable controls succeeded in 20/20 runs on both kernels.

---
 drivers/scsi/scsi_bsg.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
drivers/scsi/scsi_bsg.c +4 -2
index a9a9ec086a7e3..e2e4b8bb559f9 100644
@@ -15,7 +15,7 @@ static int scsi_bsg_sg_io_fn(struct request_queue *q, struct sg_io_v4 *hdr,
 	struct scsi_cmnd *scmd;
 	struct request *rq;
 	struct bio *bio;
-	int ret;
+	int ret, unmap_ret;
 
 	if (hdr->protocol != BSG_PROTOCOL_SCSI  ||
 	    hdr->subprotocol != BSG_SUB_PROTOCOL_SCSI_CMD)
@@ -89,7 +89,9 @@ static int scsi_bsg_sg_io_fn(struct request_queue *q, struct sg_io_v4 *hdr,
 	else
 		hdr->dout_resid = scmd->resid_len;
 
-	blk_rq_unmap_user(bio);
+	unmap_ret = blk_rq_unmap_user(bio);
+	if (!ret)
+		ret = unmap_ret;
 
 out_put_request:
 	blk_mq_free_request(rq);
Signature · 1 line
2.53.0
author maintainer
#224 lore raw

PATCH 224/686 scsi: target: Verify the iSCSI ISID is null-terminated

In reply to Greg Kroah-Hartman

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

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

From: Yuanhe Shu <[email protected]>

[ Upstream commit cdf4b87a18cb6a0ee26865cb1b7b5660a491d302 ]

iscsi_parse_pr_out_transport_id() returns the ISID of a FORMAT CODE 01b TransportID as a pointer into the PERSISTENT RESERVE OUT parameter list, lowercased in place and never null-terminated. spc4r37 Table 508 requires the field to be null-terminated, but a non-conforming initiator can omit the NULL; when the ISID ends at the end of the received buffer, the pointer is not a C string.

The registration code still consumes it as one: strcmp() in __core_scsi3_locate_pr_reg() and in the REGISTER AND MOVE path, and snprintf("%s") in __core_scsi3_do_alloc_registration(), which also reads its first 8 bytes unconditionally with get_unaligned_be64() - a NUL check does not bound that read.

When the parameter list spans more than one page, transport_kmap_data_sg() maps it with vmap(), and the over-read walks off the end of the mapping into the vmalloc() guard page and oopses. Reproduced with a PR OUT REGISTER + SPEC_I_PT parameter list of exactly 8192 bytes whose final TransportID carries a 12-byte ISID without a terminating NUL:

  BUG: unable to handle page fault for address: ffffc9000138c000
  RIP: 0010:strcmp+0xc/0x30
  Call Trace:
   __core_scsi3_locate_pr_reg+0xd3/0x120 [target_core_mod]
   core_scsi3_decode_spec_i_port+0x8fc/0x13a0 [target_core_mod]
   core_scsi3_emulate_pro_register+0x73c/0x900 [target_core_mod]
   ...
   iscsi_target_rx_thread+0xef/0x1d0 [iscsi_target_mod]

With a single-page parameter list the buffer is a kmap() direct mapping, so the over-read continues into the physically adjacent page instead of faulting. snprintf("%s") then copies whatever follows the ISID in memory into pr_reg_isid, and PR IN READ FULL STATUS reports the registration back to any initiator, turning the over-read into an info leak of kernel heap contents. Reproduced with a 4096-byte parameter list whose last TransportID ends at the end of the buffer with a 4-byte ISID and no NUL, interleaved with I/O to populate adjacent pages: the READ FULL STATUS response returned the ISID as "0xleak" followed by raw bytes that were not part of the parameter list. The snprintf() into pr_reg_isid[PR_REG_ISID_LEN] caps the echoed ISID at 15 characters, so at most 11 bytes past the buffer are leaked per command, but the PR OUT command is not rate limited.

Any initiator that can send PR OUT to an iSCSI-exported LUN can trigger either variant, including a guest via vhost-scsi.

Require 8 bytes to remain after the ",i,0x" separator, and a NUL inside the rest of the descriptor, before the ISID pointer is returned. REGISTER AND MOVE fails with TCM_INVALID_PARAMETER_LIST; on SPEC_I_PT no target port claims the malformed TransportID, and the command fails the same way.

Fixes d04a179085c2 ("scsi: target: Bound PR-OUT TransportID parsing to the received buffer")
Cc Bryam Vargas <[email protected]>
Cc John Garry <[email protected]>
Assisted-by LLM
Fixes c66ac9db8d4a ("[SCSI] target: Add LIO target core v4.0.0-rc6")
---
 drivers/target/target_core_fabric_lib.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/target/target_core_fabric_lib.c +10 -0
index 3af9a26cdefc4..a1ee106971cb0 100644
@@ -370,6 +370,16 @@ static bool iscsi_parse_pr_out_transport_id(
 			pr_err("Missing ISID in iSCSI Initiator port TransportID\n");
 			return false;
 		}
+		/*
+		 * The registration code reads the ISID as a C string,
+		 * and its first 8 bytes with get_unaligned_be64(), so
+		 * require 8 bytes after the separator and a NUL inside
+		 * the rest of the descriptor.
+		 */
+		if (buf + tid_len - p < 8 || !memchr(p, '\0', buf + tid_len - p)) {
+			pr_err("Incomplete or unterminated ISID in iSCSI Initiator port TransportID\n");
+			return false;
+		}
 		*port_nexus_ptr = p;
 		/*
 		 * Go ahead and do the lower case conversion of the received
Signature · 1 line
2.53.0
author maintainer
#225 lore raw

PATCH 225/686 scsi: target: tcmu: Fix divide-by-zero in data_pages_per_blk store

In reply to Greg Kroah-Hartman

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

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

From: Shao Mingyin <[email protected]>

[ Upstream commit b8d0bb6a8ba0d3878940a914a19336844101867b ]

tcmu_set_data_pages_per_blk() only validates the upper bound of the value parsed from data_pages_per_blk=. Zero passes that check and is then used as the divisor when computing udev->max_blocks:

divide error: 0000 [#1] SMP
...
tcmu_set_data_pages_per_blk
tcmu_configure_device

Reject non-positive values, as the neighbouring max_data_area_mb and cmd_ring_size setters already do.

Fixes 08976cb548d6 ("scsi: target: tcmu: Make data_pages_per_blk changeable via configfs")
---
 drivers/target/target_core_user.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/target/target_core_user.c +5 -0
index 3fd9636127758..72878700b1a6c 100644
@@ -2514,6 +2514,11 @@ static int tcmu_set_data_pages_per_blk(struct tcmu_dev *udev, substring_t *arg)
 		return ret;
 	}
 
+	if (val <= 0) {
+		pr_err("Invalid data_pages_per_blk %d.\n", val);
+		return -EINVAL;
+	}
+
 	if (val > TCMU_MBS_TO_PAGES(udev->data_area_mb)) {
 		pr_err("Invalid data_pages_per_blk %d: greater than max_data_area_mb %d -> %zd pages).\n",
 		       val, udev->data_area_mb,
Signature · 1 line
2.53.0
author maintainer
#226 lore raw

PATCH 226/686 drm/loongson: Fix framebuffer selection in async cursor updates

In reply to Greg Kroah-Hartman

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

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

From: Evanshenf <[email protected]>

[ Upstream commit fa66daafbb6d5c984de2502809ff533ab66f6573 ]

An asynchronous cursor update swaps the new framebuffer into the live plane state. However, the driver reads both old_fb and new_fb from the live state before this swap. When an enabled cursor changes buffers, the address-update condition is therefore false and the hardware continues scanning the previous buffer.

Read new_fb from the new plane state before swapping the framebuffer references. This updates the hardware address when the framebuffer changes while retaining the existing behavior for cursor movement.

Verified on a Loongson 3A5000 with LS7A2000 using 32x32 and 64x64 legacy cursor updates. Callback counters and read-only register observations confirmed the asynchronous path, the stale address before the change, and the new address afterward. Same-framebuffer movement and cursor disable/re-enable also passed, with the primary framebuffer and mode unchanged.

AI assistance was used to investigate the existing report, prepare the fix and test tools, run the build and hardware comparison, and draft this message.

---
 drivers/gpu/drm/loongson/lsdc_plane.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/loongson/lsdc_plane.c +1 -1
index aa9a97f9c4dc2..df941f13a9699 100644
@@ -228,7 +228,7 @@ static void lsdc_cursor_plane_atomic_async_update(struct drm_plane *plane,
 
 	new_state = drm_atomic_get_new_plane_state(state, plane);
 
-	new_fb = plane->state->fb;
+	new_fb = new_state->fb;
 
 	plane->state->crtc_x = new_state->crtc_x;
 	plane->state->crtc_y = new_state->crtc_y;
Signature · 1 line
2.53.0
author maintainer
#227 lore raw

PATCH 227/686 drm/loongson: Fix double free on BO initialization failure

In reply to Greg Kroah-Hartman

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

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

From: Evanshenf <[email protected]>

[ Upstream commit f086dbdeb6e56510e158a853d752c6d8ed9e0674 ]

If ttm_bo_init_validate() fails, it drops the buffer object's reference and cleans it up through the supplied destroy callback. lsdc_bo_destroy() releases the GEM object and frees the enclosing lsdc_bo, so freeing it again in lsdc_bo_create() causes a double free on a synchronous failure path.

Let TTM own the cleanup after initialization has started and return the error directly. Keep the explicit free on drm_gem_object_init() failure, which occurs before ownership is passed to TTM.

Tested on LS7A2000 by making drm_vma_offset_add() return -ENOSPC for one selected dumb-buffer creation. The error reached userspace, the destroy callback ran once, and no handle was published or tracked BO retained. Normal buffer creation, zeroing, mapping, readback and release passed.

AI assistance was used for the ownership analysis, fix, fault-injection tools, build and test execution.

Fixes f39db26c5428 ("drm: Add kms driver for loongson display controller")
Assisted-by LLM
---
 drivers/gpu/drm/loongson/lsdc_ttm.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/gpu/drm/loongson/lsdc_ttm.c +1 -3
index 2e42c6970c9fd..e8805a2a0db43 100644
@@ -474,10 +474,8 @@ struct lsdc_bo *lsdc_bo_create(struct drm_device *ddev,
 
 	ret = ttm_bo_init_validate(bdev, tbo, bo_type, &lbo->placement, 0,
 				   false, sg, resv, lsdc_bo_destroy);
-	if (ret) {
-		kfree(lbo);
+	if (ret)
 		return ERR_PTR(ret);
-	}
 
 	return lbo;
 }
Signature · 1 line
2.53.0
author maintainer
#228 lore raw

PATCH 228/686 drm/loongson: Handle buffer mapping failures when clearing a BO

In reply to Greg Kroah-Hartman

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

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

From: Evanshenf <[email protected]>

[ Upstream commit f00d7a241f846b053e89c0bb2285ef5988d4cafc ]

lsdc_bo_clear() ignores the return value from lsdc_bo_kmap() and writes to lbo->kptr unconditionally. When the first mapping of a newly allocated buffer fails, kptr is still NULL and the subsequent memset accesses it.

Return the mapping error without touching the buffer and propagate it from lsdc_gem_object_create(). Install the GEM object functions before clearing so that drm_gem_object_put() can release the buffer correctly on failure. Do not add the failed object to the tracking list or return an uncleared buffer to the caller.

Imported buffers still skip clearing, and successfully mapped buffers are cleared and unmapped as before.

Tested on LS7A2000 with a one-shot range error in ttm_bo_kmap(). Its -EINVAL return reached userspace, the object was destroyed once, and no GEM handle was published. Normal create/map/zero/write/read/close cycles passed, with the tracked BO count and VRAM usage unchanged.

AI assistance was used for the lifetime analysis, fix, fault-injection tools, build and test execution.

Fixes f39db26c5428 ("drm: Add kms driver for loongson display controller")
Assisted-by LLM
---
 drivers/gpu/drm/loongson/lsdc_gem.c | 12 ++++++++----
 drivers/gpu/drm/loongson/lsdc_ttm.c | 10 ++++++++--
 drivers/gpu/drm/loongson/lsdc_ttm.h |  2 +-
 3 files changed, 17 insertions(+), 7 deletions(-)
drivers/gpu/drm/loongson/lsdc_gem.c +8 -4
index a720d8f532093..5eb6b4f92302b 100644
@@ -155,14 +155,18 @@ struct drm_gem_object *lsdc_gem_object_create(struct drm_device *ddev,
 		return ERR_PTR(ret);
 	}
 
+	gobj = &lbo->tbo.base;
+	gobj->funcs = &lsdc_gem_object_funcs;
+
 	if (!sg) {
 		/* VRAM is filled with random data */
-		lsdc_bo_clear(lbo);
+		ret = lsdc_bo_clear(lbo);
+		if (ret) {
+			drm_gem_object_put(gobj);
+			return ERR_PTR(ret);
+		}
 	}
 
-	gobj = &lbo->tbo.base;
-	gobj->funcs = &lsdc_gem_object_funcs;
-
 	/* tracking the BOs we created */
 	mutex_lock(&ldev->gem.mutex);
 	list_add_tail(&lbo->list, &ldev->gem.objects);
drivers/gpu/drm/loongson/lsdc_ttm.c +8 -2
index e8805a2a0db43..17b1998254e23 100644
@@ -387,9 +387,13 @@ void lsdc_bo_kunmap(struct lsdc_bo *lbo)
 	ttm_bo_kunmap(&lbo->kmap);
 }
 
-void lsdc_bo_clear(struct lsdc_bo *lbo)
+int lsdc_bo_clear(struct lsdc_bo *lbo)
 {
-	lsdc_bo_kmap(lbo);
+	int ret;
+
+	ret = lsdc_bo_kmap(lbo);
+	if (ret)
+		return ret;
 
 	if (lbo->is_iomem)
 		memset_io((void __iomem *)lbo->kptr, 0, lbo->size);
@@ -397,6 +401,8 @@ void lsdc_bo_clear(struct lsdc_bo *lbo)
 		memset(lbo->kptr, 0, lbo->size);
 
 	lsdc_bo_kunmap(lbo);
+
+	return 0;
 }
 
 int lsdc_bo_evict_vram(struct drm_device *ddev)
drivers/gpu/drm/loongson/lsdc_ttm.h +1 -1
index 843e1475064e2..df47d9bb0d035 100644
@@ -89,7 +89,7 @@ size_t lsdc_bo_size(struct lsdc_bo *lbo);
 
 int lsdc_bo_kmap(struct lsdc_bo *lbo);
 void lsdc_bo_kunmap(struct lsdc_bo *lbo);
-void lsdc_bo_clear(struct lsdc_bo *lbo);
+int lsdc_bo_clear(struct lsdc_bo *lbo);
 
 int lsdc_bo_evict_vram(struct drm_device *ddev);
 
Signature · 1 line
2.53.0
author maintainer
#229 lore raw

PATCH 229/686 ALSA: us122l: Add missing NULL check in usb_stream_hwdep_mmap()

In reply to Greg Kroah-Hartman

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

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

From: YuanZhe Liu <[email protected]>

[ Upstream commit f5d3eb483fed59fc0f3b059b8b6a32cedc922360 ]

usb_stream_hwdep_mmap() reads us122l->sk.s and dereferences it without checking for NULL. The stream object is released by usb_stream_free(), which is reached through us122l_stop() both when the device is disconnected and when us122l_start() fails, and it leaves us122l->sk.s set to NULL. The hwdep file stays usable after that, so a later mmap()

	KASAN: null-ptr-deref in range [0x0000000000000010-0x0000000000000017]
	RIP: 0010:usb_stream_hwdep_mmap+0x107/0x890 sound/usb/usx2y/us122l.c:182

crashes while reading s->read_size, which sits at offset 0x10.

That NULL is an expected state for this field: usb_stream_hwdep_vm_fault(), usb_stream_hwdep_poll(), usb_stream_hwdep_ioctl(), usb_stream_stop() and usb_stream_free() all test it before use. Only the mmap callback misses the check, so let it return -ENODEV, matching what the other hwdep mapping in usx2yhwdeppcm.c does when its shared buffer has not been allocated.

Fixes 030a07e441296c372f946cd4065b5d831d8dc40c ("ALSA: Add USB US122L driver")
---
 sound/usb/usx2y/us122l.c | 2 ++
 1 file changed, 2 insertions(+)
sound/usb/usx2y/us122l.c +2 -0
index aaeae099b5f2e..50975b7ef1b8b 100644
@@ -179,6 +179,8 @@ static int usb_stream_hwdep_mmap(struct snd_hwdep *hw,
 	offset = area->vm_pgoff << PAGE_SHIFT;
 	guard(mutex)(&us122l->mutex);
 	s = us122l->sk.s;
+	if (!s)
+		return -ENODEV;
 	read = offset < s->read_size;
 	if (read) {
 		if (area->vm_flags & VM_WRITE)
Signature · 1 line
2.53.0
author maintainer
#230 lore raw

PATCH 230/686 ALSA: us122l: Fix NULL dereference at hwdep open and release

In reply to Greg Kroah-Hartman

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

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

From: YuanZhe Liu <[email protected]>

[ Upstream commit 820e0050866942b5498488496462d12c6ce1c7a9 ]

usb_stream_hwdep_open() and usb_stream_hwdep_release() pass the result of usb_ifnum_to_if() straight to usb_autopm_get_interface() and usb_autopm_put_interface(), without checking it for NULL.

usb_ifnum_to_if() returns NULL once the device is gone, since usb_disable_device() clears udev->actconfig on disconnect. The hwdep file can outlive the disconnect: the card is released with snd_card_free_when_closed(), so a process that keeps the character device open reaches the driver's release callback after the USB configuration has been dropped, and interface_to_usbdev() then dereferences the NULL interface at offsetof(struct device, parent). The open callback has the same problem when it races with the disconnect.

Check both lookups and fail the open with -ENODEV; in release, skip the runtime PM put when the interface is already gone and still run the rest of the per-file cleanup. Move the us122l->first bookkeeping after the checks so that a failed open no longer leaves a stale file pointer behind.

---
 sound/usb/usx2y/us122l.c | 25 +++++++++++++++++--------
 1 file changed, 17 insertions(+), 8 deletions(-)
sound/usb/usx2y/us122l.c +17 -8
index 50975b7ef1b8b..46dbf9ea1fb70 100644
@@ -129,19 +129,26 @@ static const struct vm_operations_struct usb_stream_hwdep_vm_ops = {
 static int usb_stream_hwdep_open(struct snd_hwdep *hw, struct file *file)
 {
 	struct us122l	*us122l = hw->private_data;
-	struct usb_interface *iface;
+	struct usb_interface *iface, *iface0 = NULL;
 
 	if (hw->used >= 2)
 		return -EBUSY;
 
-	if (!us122l->first)
-		us122l->first = file;
-
 	if (us122l->is_us144) {
-		iface = usb_ifnum_to_if(us122l->dev, 0);
-		usb_autopm_get_interface(iface);
+		iface0 = usb_ifnum_to_if(us122l->dev, 0);
+		if (!iface0)
+			return -ENODEV;
 	}
+
 	iface = usb_ifnum_to_if(us122l->dev, 1);
+	if (!iface)
+		return -ENODEV;
+
+	if (!us122l->first)
+		us122l->first = file;
+
+	if (iface0)
+		usb_autopm_get_interface(iface0);
 	usb_autopm_get_interface(iface);
 	return 0;
 }
@@ -153,10 +160,12 @@ static int usb_stream_hwdep_release(struct snd_hwdep *hw, struct file *file)
 
 	if (us122l->is_us144) {
 		iface = usb_ifnum_to_if(us122l->dev, 0);
-		usb_autopm_put_interface(iface);
+		if (iface)
+			usb_autopm_put_interface(iface);
 	}
 	iface = usb_ifnum_to_if(us122l->dev, 1);
-	usb_autopm_put_interface(iface);
+	if (iface)
+		usb_autopm_put_interface(iface);
 	if (us122l->first == file)
 		us122l->first = NULL;
 	guard(mutex)(&us122l->mutex);
Signature · 1 line
2.53.0
author maintainer
#231 lore raw

PATCH 231/686 ALSA: usx2y: Initialize idle URBs before submitting streams

In reply to Greg Kroah-Hartman

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

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

From: YuanZhe Liu <[email protected]>

[ Upstream commit ceb0d8c22473933099b46cec70639d0f1f7c68ad ]

usb_stream_start() submits the first two capture and playback URBs and only afterwards assigns sk->idle_inurb, sk->idle_outurb, sk->completed_inurb and sk->completed_outurb to the remaining two URBs of each direction.

A transfer can complete as soon as usb_submit_urb() has been called, so the completion handler i_capture_start() or i_playback_start() may run before those pointers are set. While the stream is still being synchronized (state below usb_stream_sync1), stream_start() then calls playback_prep_freqn(sk, sk->idle_outurb) with sk->idle_outurb still NULL, and the packet descriptors are written through that NULL pointer:

  Oops: general protection fault, probably for non-canonical address
  0xdffffc0000000018: 0000 [#1] SMP KASAN
  KASAN: null-ptr-deref in range [0x00000000000000c0-0x00000000000000c7]
  RIP: 0010:playback_prep_freqn+0x11c/0x4a0 sound/usb/usx2y/usb_stream.c:33
  Call Trace:
   <IRQ>
   stream_start+0x5dc/0x8d0 sound/usb/usx2y/usb_stream.c:596
   i_capture_start+0x3da/0x710 sound/usb/usx2y/usb_stream.c:654
   __usb_hcd_giveback_urb+0x238/0x550 drivers/usb/core/hcd.c:1657
   usb_giveback_urb_bh+0x20b/0x530 drivers/usb/core/hcd.c:1691
   tasklet_hi_action+0xa/0x20 kernel/softirq.c:994
   handle_softirqs+0x16f/0x440 kernel/softirq.c:645
   </IRQ>

The four URBs referenced by these pointers are allocated long before and do not depend on any transfer state, so assign them before the submit loop. Keeping the assignment inside the retry path also restores a well-defined URB rotation when the start frame mismatch handling kills and resubmits the streams.

Fixes 030a07e441296c372f946cd4065b5d831d8dc40c ("ALSA: Add USB US122L driver")
---
 sound/usb/usx2y/usb_stream.c | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
sound/usb/usx2y/usb_stream.c +4 -5
index 3122cf653273d..7d621280fba33 100644
@@ -682,6 +682,10 @@ int usb_stream_start(struct usb_stream_kernel *sk)
 	s->sync_packet = -1;
 	s->inpacket_head = -1;
 	sk->iso_frame_balance = 0;
+	sk->idle_inurb = sk->inurb[USB_STREAM_NURBS - 2];
+	sk->idle_outurb = sk->outurb[USB_STREAM_NURBS - 2];
+	sk->completed_inurb = sk->inurb[USB_STREAM_NURBS - 1];
+	sk->completed_outurb = sk->outurb[USB_STREAM_NURBS - 1];
 	++try;
 	for (u = 0; u < 2; u++) {
 		struct urb *inurb = sk->inurb[u];
@@ -739,11 +743,6 @@ int usb_stream_start(struct usb_stream_kernel *sk)
 		return -EFAULT;
 	}
 
-	sk->idle_inurb = sk->inurb[USB_STREAM_NURBS - 2];
-	sk->idle_outurb = sk->outurb[USB_STREAM_NURBS - 2];
-	sk->completed_inurb = sk->inurb[USB_STREAM_NURBS - 1];
-	sk->completed_outurb = sk->outurb[USB_STREAM_NURBS - 1];
-
 /* wait, check */
 	{
 		int wait_ms = 3000;
Signature · 1 line
2.53.0
author maintainer
#232 lore raw

PATCH 232/686 ALSA: hwdep: Serialize DSP load requests

In reply to Greg Kroah-Hartman

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

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

From: YuanZhe Liu <[email protected]>

[ Upstream commit aee83c204f80d56b4d55f53acdb8594308ddcd4a ]

The check of the loaded DSP indices and the call of the driver's dsp_load callback in snd_hwdep_dsp_load() are not serialized. A hwdep file descriptor can be shared among threads, or inherited across fork, so two SNDRV_HWDEP_IOCTL_DSP_LOAD requests for the same index can both observe the index as unloaded and enter the driver's callback concurrently, even though the device itself is opened exclusively.

This breaks the assumption behind hw->dsp_loaded that a firmware index is loaded only once. For example, snd-usb-usx2y hits WARN_ON(usx2y->as04.buffer) in usx2y_async_seq04_init() and may allocate the US-428 sequence URBs twice.

Serialize the check, the callback invocation and the bookkeeping with a per-hwdep mutex, so that the second request returns -EBUSY.

---
 include/sound/hwdep.h | 1 +
 sound/core/hwdep.c    | 2 ++
 2 files changed, 3 insertions(+)
include/sound/hwdep.h +1 -0
index b0da633184cde..7357727f06603 100644
@@ -57,6 +57,7 @@ struct snd_hwdep {
 
 	struct mutex open_mutex;
 	int used;			/* reference counter */
+	struct mutex dsp_mutex;		/* serializes DSP load requests */
 	unsigned int dsp_loaded;	/* bit fields of loaded dsp indices */
 	unsigned int exclusive:1;	/* exclusive access mode */
 };
sound/core/hwdep.c +2 -0
index 09200df2932c7..10a32004398ff 100644
@@ -212,6 +212,7 @@ static int snd_hwdep_dsp_load(struct snd_hwdep *hw,
 		return -ENXIO;
 	if (info->index >= 32)
 		return -EINVAL;
+	guard(mutex)(&hw->dsp_mutex);
 	/* check whether the dsp was already loaded */
 	if (hw->dsp_loaded & (1u << info->index))
 		return -EBUSY;
@@ -381,6 +382,7 @@ int snd_hwdep_new(struct snd_card *card, char *id, int device,
 
 	init_waitqueue_head(&hwdep->open_wait);
 	mutex_init(&hwdep->open_mutex);
+	mutex_init(&hwdep->dsp_mutex);
 	hwdep->card = card;
 	hwdep->device = device;
 	if (id)
Signature · 1 line
2.53.0
author maintainer
#233 lore raw

PATCH 233/686 bpf: Fix skb_pull() BUG in __bpf_redirect_neigh()

In reply to Greg Kroah-Hartman

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

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

From: Jamal Hadi Salim <[email protected]>

[ Upstream commit 23503acb214cbefaf3945d05ab9667ff11ae3de9 ]

The issue:
This is a follow-up to the short link-layer header fixes from Eric. After vlan pop_eth, a privileged SCHED_ACT BPF program can call bpf_skb_change_head(skb, 1, 0) and then bpf_redirect_neigh().

__bpf_redirect_neigh() calls skb_pull(skb, sizeof(*ethh)) after checking only that mac_header < network_header. Nothing verifies that the MAC header is long enough, that it is linear, or that the IP header the redirect goes on to read is linear either.

A SCHED_ACT BPF program can do:

    bpf_skb_change_head(skb, 1, 0);
    bpf_redirect_neigh(lo, NULL, 0, 0);

after vlan pop_eth. The skb then has mac_len == 1 and only one byte of linear data; skb_pull(ETH_HLEN) trips the skb->len < skb->data_len BUG in __skb_pull():

kernel BUG at ./include/linux/skbuff.h:2839!
RIP: skb_pull+0x40/0x50
Call Trace: skb_do_redirect -> packet_xmit -> packet_sendmsg Kernel panic - not syncing: Fatal exception in interrupt

The v4 and v6 paths read ip_hdr() and ipv6_hdr() as soon as the MAC header is gone. On the AF_PACKET frame below that leaves headlen == 0 after the pull, so the network header sits at skb->tail and the route lookup reads ip4h->protocol, ip4h->saddr and ip4h->daddr past the linear area.

The Fix:
Use skb_network_offset(), which is the MAC header span, instead of skb->mac_len. mac_len is zero for locally generated tc egress and netkit packets, while the span still rejects the one-byte header produced by pop_eth + bpf_skb_change_head(skb, 1, 0). The single check also covers the mac_header >= network_header test it replaces.

Use pskb_may_pull() to make the Ethernet header linear before it is read or pulled, and to make the IP header linear in both the v4 and the v6 path before ip_hdr()/ipv6_hdr() is read. The header pointers are taken after the pull, since pskb_may_pull() may reallocate skb->head.

Conditions to recreate the bug:
On x86-64 with 4 KiB pages, enable CONFIG_PACKET, CONFIG_BPF_SYSCALL, CONFIG_NET_SCH_INGRESS, CONFIG_NET_CLS_MATCHALL, CONFIG_NET_ACT_VLAN and CONFIG_NET_ACT_BPF. Run as root with BPF loading, network administration and raw-packet privileges. Bring lo up and attach a SCHED_ACT program that calls bpf_skb_change_head(skb, 1, 0), then returns bpf_redirect_neigh(skb->ifindex, NULL, 0, 0):

ip link set lo up
tc qdisc add dev lo clsact
tc filter add dev lo egress matchall action vlan pop_eth pipe \
action bpf object-file neigh_chghead.o section action

Send an untagged ETH_P_IP frame of ETH_HLEN + 8192 bytes through an AF_PACKET/SOCK_RAW socket bound to lo, without PACKET_VNET_HDR or PACKET_QDISC_BYPASS. Use a unicast destination MAC. The sender's skb has a 14-byte linear Ethernet prefix and a fragmented payload; pop_eth removes that prefix and change_head restores only one linear byte. The unfixed neighbor redirect then tries to pull 14 bytes and BUGs.

Sending the same frame without pop_eth and change_head leaves the IP header in the frags, which is the route lookup reading past skb->tail.

---
 net/core/filter.c | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)
net/core/filter.c +14 -7
index 6926903163592..6670b43cb640d 100644
@@ -2270,9 +2270,13 @@ static int bpf_out_neigh_v6(struct net *net, struct sk_buff *skb,
 static int __bpf_redirect_neigh_v6(struct sk_buff *skb, struct net_device *dev,
 				   struct bpf_nh_params *nh)
 {
-	const struct ipv6hdr *ip6h = ipv6_hdr(skb);
 	struct net *net = dev_net(dev);
 	int err, ret = NET_XMIT_DROP;
+	const struct ipv6hdr *ip6h;
+
+	if (unlikely(!pskb_may_pull(skb, sizeof(*ip6h))))
+		goto out_drop;
+	ip6h = ipv6_hdr(skb);
 
 	if (!nh) {
 		struct dst_entry *dst;
@@ -2375,9 +2379,13 @@ static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb,
 static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
 				   struct bpf_nh_params *nh)
 {
-	const struct iphdr *ip4h = ip_hdr(skb);
 	struct net *net = dev_net(dev);
 	int err, ret = NET_XMIT_DROP;
+	const struct iphdr *ip4h;
+
+	if (unlikely(!pskb_may_pull(skb, sizeof(*ip4h))))
+		goto out_drop;
+	ip4h = ip_hdr(skb);
 
 	if (!nh) {
 		struct flowi4 fl4 = {
@@ -2427,15 +2435,14 @@ static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
 static int __bpf_redirect_neigh(struct sk_buff *skb, struct net_device *dev,
 				struct bpf_nh_params *nh)
 {
-	struct ethhdr *ethh = eth_hdr(skb);
-
-	if (unlikely(skb->mac_header >= skb->network_header))
+	if (unlikely(skb_network_offset(skb) < ETH_HLEN ||
+		     !pskb_may_pull(skb, ETH_HLEN)))
 		goto out;
 	bpf_push_mac_rcsum(skb);
-	if (is_multicast_ether_addr(ethh->h_dest))
+	if (is_multicast_ether_addr(eth_hdr(skb)->h_dest))
 		goto out;
 
-	skb_pull(skb, sizeof(*ethh));
+	skb_pull(skb, ETH_HLEN);
 	skb_unset_mac_header(skb);
 	skb_reset_network_header(skb);
 
Signature · 1 line
2.53.0
author maintainer
#234 lore raw

PATCH 234/686 ksmbd: require DELETE access for delete-on-close opens

In reply to Greg Kroah-Hartman

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

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

From: Ian Bridges <[email protected]>

[ Upstream commit 1dd91081ba3c692565f9c1f884149178d5a06d1e ]

smb2_open() accepts FILE_DELETE_ON_CLOSE on an existing file without DELETE in DesiredAccess. When the request asks only for FILE_READ_ATTRIBUTES or READ_CONTROL, it also skips inode_permission() and the parent directory MAY_WRITE | MAY_EXEC check that delete-on-close is meant to get. The file is then marked for deletion by a caller who could not delete it.

The unlink happens later, in __ksmbd_inode_close(), when the last handle on the inode is closed, and it runs with the credentials of that handle. If the caller closes last, the unlink fails. If another user who can write the parent directory, such as the file's owner, still has the file open, the file is deleted when that user closes it. Until then new opens of the file fail with STATUS_DELETE_PENDING. So a user with only search permission on a directory can delete a file in it, or block opens of it, while the owner has it open.

A MAXIMUM_ALLOWED open that also requests DELETE has the same problem. The requested access is replaced with the maximal access, which does not include DELETE when the caller cannot write the parent directory, and the later permission checks are skipped as already done.

MS-FSA 2.1.5.1 requires an open with FILE_DELETE_ON_CLOSE and without DELETE in DesiredAccess to fail with STATUS_INVALID_PARAMETER, and Samba does the same. Add that check to the CreateOptions validation, using the generic-mapped DesiredAccess so that GENERIC_ALL still qualifies. This also refuses MAXIMUM_ALLOWED with FILE_DELETE_ON_CLOSE but no explicit DELETE, as MS-FSA and Samba do. When MAXIMUM_ALLOWED is requested with DELETE but the maximal access does not include DELETE, fail with STATUS_ACCESS_DENIED. With DELETE requested, delete-on-close opens go through the existing parent directory check.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb2pdu.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
fs/smb/server/smb2pdu.c +15 -0
index 40d86993dbe3d..ec4c54c9c6dc9 100644
@@ -3176,6 +3176,14 @@ int smb2_open(struct ksmbd_work *work)
 				req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
 			}
 		}
+
+		/* MS-FSA 2.1.5.1: delete-on-close requires DELETE access */
+		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE &&
+		    !(smb_map_generic_desired_access(req->DesiredAccess) &
+		      FILE_DELETE_LE)) {
+			rc = -EINVAL;
+			goto err_out2;
+		}
 	}
 
 	if (le32_to_cpu(req->CreateDisposition) >
@@ -3355,6 +3363,13 @@ int smb2_open(struct ksmbd_work *work)
 		maximal_access = daccess;
 	}
 
+	/* MAXIMUM_ALLOWED may not have granted the requested DELETE */
+	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE &&
+	    !(daccess & FILE_DELETE_LE)) {
+		rc = -EACCES;
+		goto err_out;
+	}
+
 	open_flags = smb2_create_open_flags(file_present, daccess,
 					    req->CreateDisposition,
 					    &may_flags,
Signature · 1 line
2.53.0
author maintainer
#235 lore raw

PATCH 235/686 rust: cpufreq: fix `undocumented_unsafe_blocks` in `PolicyCpu::from_cpu()`

In reply to Greg Kroah-Hartman

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

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

From: Miguel Ojeda <[email protected]>

[ Upstream commit 62a40c72905be262e9e10790008d505ed0be6c0f ]

For Rust <= 1.86, Clippy triggers after commit 02c5d7bfa872 ("rust:
cpufreq: reject NULL from cpufreq_cpu_get()"):

    warning: unsafe block missing a safety comment
       --> rust/kernel/cpufreq.rs:700:26
        |
    700 |             NonNull::new(unsafe { bindings::cpufreq_cpu_get(u32::from(cpu)) }).ok_or(ENODEV)?;
        |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        |
        = help: consider adding a safety comment on the preceding line
        = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#undocumented_unsafe_blocks
        = note: requested on the command line with `-W clippy::undocumented-unsafe-blocks`

Thus clean it up.

Fixes 02c5d7bfa872 ("rust: cpufreq: reject NULL from cpufreq_cpu_get()")
Assisted-by LLM
---
 rust/kernel/cpufreq.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
rust/kernel/cpufreq.rs +2 -2
index be312f523ebec..dbd1ea1e9be79 100644
@@ -695,8 +695,8 @@ fn clear_data<T: ForeignOwnable>(&mut self) -> Option<T> {
 impl<'a> PolicyCpu<'a> {
     fn from_cpu(cpu: CpuId) -> Result<Self> {
         // SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU.
-        let ptr =
-            NonNull::new(unsafe { bindings::cpufreq_cpu_get(u32::from(cpu)) }).ok_or(ENODEV)?;
+        let ptr = unsafe { bindings::cpufreq_cpu_get(u32::from(cpu)) };
+        let ptr = NonNull::new(ptr).ok_or(ENODEV)?;
 
         Ok(Self(
             // SAFETY: `ptr` is non-NULL and `cpufreq_cpu_get()` took a reference on it, so it is
Signature · 1 line
2.53.0
author maintainer
#236 lore raw

PATCH 236/686 x86/bugs: Select the BHI mitigation based on the attack vector properly

In reply to Greg Kroah-Hartman

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

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

From: Breno Leitao <[email protected]>

[ Upstream commit 3457b3bcd344005af894876cab4e634cabdcbb62 ]

The BHI mitigation selection is inconsistent with the documentation (attack_vector_controls.rst), which lists BHI under both the user->kernel and guest->host attack vectors. bhi_select_mitigation() only enables it when CPU_MITIGATE_GUEST_HOST is set; otherwise it selects BHI_MITIGATION_OFF, even if CPU_MITIGATE_USER_KERNEL is set.

As a result, a kernel compiled with KVM disabled gets BHI automatically disabled, since CPU_MITIGATE_GUEST_HOST defaults to off without KVM. This is a bug, given that CPU_MITIGATE_USER_KERNEL still needs it: on affected Intel CPUs these kernels lose BHI_DIS_S or the BHB clearing loop by default. Booting with mitigations=auto,no_guest_host has the same effect.

Select BHI_MITIGATION_ON whenever user->kernel is mitigated, and keep BHI_MITIGATION_VMEXIT_ONLY for the guest->host-only case.

[ bp: Clarify commit title. ]

---
 arch/x86/kernel/cpu/bugs.c | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)
arch/x86/kernel/cpu/bugs.c +5 -7
index 90d0488d54c5c..cbf5c0ddd3b38 100644
@@ -2233,14 +2233,12 @@ static void __init bhi_select_mitigation(void)
 	if (bhi_mitigation != BHI_MITIGATION_AUTO)
 		return;
 
-	if (cpu_attack_vector_mitigated(CPU_MITIGATE_GUEST_HOST)) {
-		if (cpu_attack_vector_mitigated(CPU_MITIGATE_USER_KERNEL))
-			bhi_mitigation = BHI_MITIGATION_ON;
-		else
-			bhi_mitigation = BHI_MITIGATION_VMEXIT_ONLY;
-	} else {
+	if (cpu_attack_vector_mitigated(CPU_MITIGATE_USER_KERNEL))
+		bhi_mitigation = BHI_MITIGATION_ON;
+	else if (cpu_attack_vector_mitigated(CPU_MITIGATE_GUEST_HOST))
+		bhi_mitigation = BHI_MITIGATION_VMEXIT_ONLY;
+	else
 		bhi_mitigation = BHI_MITIGATION_OFF;
-	}
 }
 
 static void __init bhi_update_mitigation(void)
Signature · 1 line
2.53.0
author maintainer
#237 lore raw

PATCH 237/686 drm/i915/psr: Clear selective fetch area when duplicating plane state

In reply to Greg Kroah-Hartman

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

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

From: Jouni Högander <[email protected]>

[ Upstream commit cbe565475988d3b22dc36f13c14d9f0eec1685cd ]

We are currently not clearing selective fetch area when duplicating plane state. This is causing problem when plane is re-used for another purpose. Fix this by clearing selective fetch area when duplicating plane state.

Now as the state is cleared we need to ensure we have consistent selective fetch area in plane state on full update. Earlier this was relying on selective fetch area being copied from old state on state duplicate. Now this isn't true anymore as we are clearing it. Tackle this by setting full plane area as selective fetch area for each plane on full update. Rename the label as skip_su_area_calc as the loop setting the plane selective fetch area is not skipped anymore.

Move also psr2_sel_fetch_pipe_state_supported check after psr2_su_area initialization. The loop is run on full update as well now and it needs initialized psr2_su_area. Clip_area_update is only touching rect height and x1/x2 are left untouched.

Don't set the area at all for planes not intersecting with the selective update area. It is already zero sized after plane state duplicate.

Fixes efab47658a6c ("drm/i915/display/psr: Calculate selective fetch plane registers")
Cc <[email protected]> # v5.12+
Assisted-by GitHub-Copilot:claude-opus-5
(cherry picked from commit bd58f0e221386808cd614bb205112e807dc6b159)
---
 drivers/gpu/drm/i915/display/intel_plane.c |  1 +
 drivers/gpu/drm/i915/display/intel_psr.c   | 24 ++++++++++------------
 2 files changed, 12 insertions(+), 13 deletions(-)
drivers/gpu/drm/i915/display/intel_plane.c +1 -0
index 91deeaec61100..6f9c22476b14d 100644
@@ -139,6 +139,7 @@ intel_plane_duplicate_state(struct drm_plane *plane)
 	intel_state->dpt_vma = NULL;
 	intel_state->flags = 0;
 	intel_state->damage = DRM_RECT_INIT(0, 0, 0, 0);
+	intel_state->psr2_sel_fetch_area = DRM_RECT_INIT(0, 0, 0, 0);
 
 	/* add reference to fb */
 	if (intel_state->hw.fb)
drivers/gpu/drm/i915/display/intel_psr.c +11 -13
index 5f6ccd953c1e3..d41ad77c086f4 100644
@@ -2797,16 +2797,16 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 	if (!crtc_state->enable_psr2_sel_fetch)
 		return 0;
 
-	if (!psr2_sel_fetch_pipe_state_supported(crtc_state)) {
-		full_update = true;
-		goto skip_sel_fetch_set_loop;
-	}
-
 	crtc_state->psr2_su_area.x1 = 0;
 	crtc_state->psr2_su_area.y1 = -1;
 	crtc_state->psr2_su_area.x2 = drm_rect_width(&display_area);
 	crtc_state->psr2_su_area.y2 = -1;
 
+	if (!psr2_sel_fetch_pipe_state_supported(crtc_state)) {
+		full_update = true;
+		goto skip_su_area_calc;
+	}
+
 	/*
 	 * Calculate minimal selective fetch area of each plane and calculate
 	 * the pipe damaged area.
@@ -2890,7 +2890,7 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 	}
 
 	if (full_update)
-		goto skip_sel_fetch_set_loop;
+		goto skip_su_area_calc;
 
 	intel_psr_apply_su_area_workarounds(crtc_state);
 
@@ -2926,6 +2926,11 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 			break;
 	} while (su_area_changed);
 
+skip_su_area_calc:
+	if (full_update)
+		clip_area_update(&crtc_state->psr2_su_area, &display_area,
+				 &display_area);
+
 	/*
 	 * Now that we have the pipe damaged area check if it intersect with
 	 * every plane, if it does set the plane selective fetch area.
@@ -2942,8 +2947,6 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 		inter = crtc_state->psr2_su_area;
 		sel_fetch_area = &new_plane_state->psr2_sel_fetch_area;
 		if (!drm_rect_intersect(&inter, &new_plane_state->uapi.dst)) {
-			sel_fetch_area->y1 = -1;
-			sel_fetch_area->y2 = -1;
 			/*
 			 * if plane sel fetch was previously enabled ->
 			 * disable it
@@ -2983,11 +2986,6 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 		}
 	}
 
-skip_sel_fetch_set_loop:
-	if (full_update)
-		clip_area_update(&crtc_state->psr2_su_area, &display_area,
-				 &display_area);
-
 	psr2_man_trk_ctl_calc(crtc_state, full_update);
 	crtc_state->pipe_srcsz_early_tpt =
 		psr2_pipe_srcsz_early_tpt_calc(crtc_state, full_update);
Signature · 1 line
2.53.0
author maintainer
#238 lore raw

PATCH 238/686 drm/i915/display: Add enabled pipe planes into state for selective fetch

In reply to Greg Kroah-Hartman

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

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

From: Jouni Högander <[email protected]>

[ Upstream commit 94cb1f08b197d9ae932ff98c741bd0dbc96e17e8 ]

Selective fetch support for biplanar formats relies on linking of UV and the Y planes. Planes that are not part of the atomic state are pulled in by the drm_atomic_add_affected_planes. If the UV plane is added into the state by drm_atomic_add_affected_planes in the selective fetch calculation, the linking isn't done anymore and the Y plane is left disabled.

Fix this by adding affected planes already in intel_add_affected_planes if selective fetch is enabled.

Remove redundant drm_atomic_add_affected_planes from intel_psr2_sel_fetch_update and redundant check for plane selective fetch support that is not needed as all planes are already in atomic state on first loop iterating them. Also switch to intel_atomic_get_new_plane_state for linked plane new plane state.

Fixes 3809991ff5f4 ("drm/i915/display: Add initial selective fetch support for biplanar formats")
Cc <[email protected]> # v5.17+
(cherry picked from commit 0d173898b11157d37de3e5f01ef28a48582167d8)
---
 drivers/gpu/drm/i915/display/intel_plane.c | 10 +++++++++
 drivers/gpu/drm/i915/display/intel_psr.c   | 25 +++++++---------------
 2 files changed, 18 insertions(+), 17 deletions(-)
drivers/gpu/drm/i915/display/intel_plane.c +10 -0
index 6f9c22476b14d..bbf85f47a73ff 100644
@@ -1699,6 +1699,16 @@ static int intel_add_affected_planes(struct intel_atomic_state *state)
 		ret = intel_joiner_add_affected_planes(state, intel_crtc_joined_pipe_mask(crtc_state));
 		if (ret)
 			return ret;
+
+		/*
+		 * Add affected plane here to ensure UV and Y plane linking is
+		 * in place if UV plane is added as a part of selective update.
+		 */
+		if (crtc_state->enable_psr2_sel_fetch) {
+			ret = intel_plane_add_affected(state, crtc);
+			if (ret)
+				return ret;
+		}
 	}
 
 	return 0;
drivers/gpu/drm/i915/display/intel_psr.c +8 -17
index d41ad77c086f4..253045374a061 100644
@@ -2779,7 +2779,7 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 		.y2 = crtc_state->hw.adjusted_mode.crtc_vdisplay,
 	};
 	bool full_update = false, su_area_changed;
-	int i, ret;
+	int i;
 
 	/*
 	 * Selective fetch is not always usable, for instance it is dropped
@@ -2894,19 +2894,15 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 
 	intel_psr_apply_su_area_workarounds(crtc_state);
 
-	ret = drm_atomic_add_affected_planes(&state->base, &crtc->base);
-	if (ret)
-		return ret;
-
 	do {
 		bool cursor_in_su_area = false;
 
 		/*
 		 * Adjust su area to cover cursor fully as necessary
-		 * (early transport). This needs to be done after
-		 * drm_atomic_add_affected_planes to ensure visible
-		 * cursor is added into affected planes even when
-		 * cursor is not updated by itself.
+		 * (early transport). A visible cursor is in the state
+		 * even when it is not updated by itself as all planes
+		 * of the pipe are added into the state before the plane
+		 * checks when selective fetch is enabled.
 		 */
 		intel_psr2_sel_fetch_et_alignment(state, crtc, &display_area,
 						  &cursor_in_su_area);
@@ -2957,11 +2953,6 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 			continue;
 		}
 
-		if (!psr2_sel_fetch_plane_state_supported(new_plane_state)) {
-			full_update = true;
-			break;
-		}
-
 		sel_fetch_area = &new_plane_state->psr2_sel_fetch_area;
 		sel_fetch_area->y1 = inter.y1 - new_plane_state->uapi.dst.y1;
 		sel_fetch_area->y2 = inter.y2 - new_plane_state->uapi.dst.y1;
@@ -2975,9 +2966,9 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 			struct intel_plane_state *linked_new_plane_state;
 			struct drm_rect *linked_sel_fetch_area;
 
-			linked_new_plane_state = intel_atomic_get_plane_state(state, linked);
-			if (IS_ERR(linked_new_plane_state))
-				return PTR_ERR(linked_new_plane_state);
+			linked_new_plane_state = intel_atomic_get_new_plane_state(state, linked);
+			if (!linked_new_plane_state)
+				return -EINVAL;
 
 			linked_sel_fetch_area = &linked_new_plane_state->psr2_sel_fetch_area;
 			linked_sel_fetch_area->y1 = sel_fetch_area->y1;
Signature · 1 line
2.53.0
author maintainer
#239 lore raw

PATCH 239/686 drm/i915/psr: Disable linked plane sel fetch as well

In reply to Greg Kroah-Hartman

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

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

From: Jouni Högander <[email protected]>

[ Upstream commit b56721c32eb3ad0f086fdc0f33479be395e43bb9 ]

Currently we are not setting linked plane selective area when selective fetch is about to be disabled for the UV plane. Fix this by simplifying the loop by just handling plane selective fetch disable and area setting same way.

Also set the update_planes bit based on comparing old and new plane selective fetch area. This way both the plane and its linked Y plane are updated only when their selective fetch area changed.

Fixes a4f477e6ac17 ("drm/i915/psr: Add proper handling for disabling sel fetch for planes")
Cc <[email protected]> # v6.8+
Assisted-by GitHub-Copilot:claude-opus-5
(cherry picked from commit b10c83af60cbc00ce4112742fd297581233e43cd)
---
 drivers/gpu/drm/i915/display/intel_psr.c | 27 ++++++++++++------------
 1 file changed, 13 insertions(+), 14 deletions(-)
drivers/gpu/drm/i915/display/intel_psr.c +13 -14
index 253045374a061..d1a9f9de75b9a 100644
@@ -2942,21 +2942,14 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 
 		inter = crtc_state->psr2_su_area;
 		sel_fetch_area = &new_plane_state->psr2_sel_fetch_area;
-		if (!drm_rect_intersect(&inter, &new_plane_state->uapi.dst)) {
-			/*
-			 * if plane sel fetch was previously enabled ->
-			 * disable it
-			 */
-			if (drm_rect_height(&old_plane_state->psr2_sel_fetch_area) > 0)
-				crtc_state->update_planes |= BIT(plane->id);
-
-			continue;
+		if (drm_rect_intersect(&inter, &new_plane_state->uapi.dst)) {
+			sel_fetch_area->y1 = inter.y1 - new_plane_state->uapi.dst.y1;
+			sel_fetch_area->y2 = inter.y2 - new_plane_state->uapi.dst.y1;
 		}
 
-		sel_fetch_area = &new_plane_state->psr2_sel_fetch_area;
-		sel_fetch_area->y1 = inter.y1 - new_plane_state->uapi.dst.y1;
-		sel_fetch_area->y2 = inter.y2 - new_plane_state->uapi.dst.y1;
-		crtc_state->update_planes |= BIT(plane->id);
+		if (!drm_rect_equals(&old_plane_state->psr2_sel_fetch_area,
+				     sel_fetch_area))
+			crtc_state->update_planes |= BIT(plane->id);
 
 		/*
 		 * Sel_fetch_area is calculated for UV plane. Use
@@ -2964,16 +2957,22 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,
 		 */
 		if (linked) {
 			struct intel_plane_state *linked_new_plane_state;
+			struct intel_plane_state *linked_old_plane_state;
 			struct drm_rect *linked_sel_fetch_area;
 
 			linked_new_plane_state = intel_atomic_get_new_plane_state(state, linked);
 			if (!linked_new_plane_state)
 				return -EINVAL;
 
+			linked_old_plane_state = intel_atomic_get_old_plane_state(state, linked);
+
 			linked_sel_fetch_area = &linked_new_plane_state->psr2_sel_fetch_area;
 			linked_sel_fetch_area->y1 = sel_fetch_area->y1;
 			linked_sel_fetch_area->y2 = sel_fetch_area->y2;
-			crtc_state->update_planes |= BIT(linked->id);
+
+			if (!drm_rect_equals(&linked_old_plane_state->psr2_sel_fetch_area,
+					     linked_sel_fetch_area))
+				crtc_state->update_planes |= BIT(linked->id);
 		}
 	}
 
Signature · 1 line
2.53.0
author maintainer
#240 lore raw

PATCH 240/686 drm/i915/psr: Fix SFF and CFF CTL register bit definitions

In reply to Greg Kroah-Hartman

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

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

From: Jouni Högander <[email protected]>

[ Upstream commit 15b3187740291c4705b995bbf984da462e9f1e35 ]

Single full frame bit in SFF_CTL and continuous full frame bit in CFF_CTL are bit 0. Fix the definitions accordingly.

Fixes 3b5bf853e309 ("drm/i915/psr: Add register definitions for SFF_CTL and CFF_CTL registers")
Cc <[email protected]> # v6.15+
(cherry picked from commit 95ca8fab5232dfb7459989d54f09501704a8d7ad)
---
 drivers/gpu/drm/i915/display/intel_psr_regs.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/gpu/drm/i915/display/intel_psr_regs.h +2 -2
index 8afbf5a383353..1e85860eefb83 100644
@@ -254,12 +254,12 @@
 #define _LNL_SFF_CTL_A				0x60918
 #define _LNL_SFF_CTL_B				0x61918
 #define LNL_SFF_CTL(tran)			_MMIO_TRANS(tran, _LNL_SFF_CTL_A, _LNL_SFF_CTL_B)
-#define  LNL_SFF_CTL_SF_SINGLE_FULL_FRAME	REG_BIT(1)
+#define  LNL_SFF_CTL_SF_SINGLE_FULL_FRAME	REG_BIT(0)
 
 #define _LNL_CFF_CTL_A				0x6091c
 #define _LNL_CFF_CTL_B				0x6191c
 #define LNL_CFF_CTL(tran)			_MMIO_TRANS(tran, _LNL_CFF_CTL_A, _LNL_CFF_CTL_B)
-#define  LNL_CFF_CTL_SF_CONTINUOUS_FULL_FRAME	REG_BIT(1)
+#define  LNL_CFF_CTL_SF_CONTINUOUS_FULL_FRAME	REG_BIT(0)
 
 /* PSR2 Early transport */
 #define _PIPE_SRCSZ_ERLY_TPT_A	0x70074
Signature · 1 line
2.53.0
author maintainer
#241 lore raw

PATCH 241/686 drm/i915/psr: Dont clip plane state destination rectangle

In reply to Greg Kroah-Hartman

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

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

From: Jouni Högander <[email protected]>

[ Upstream commit e30830d21860fbf030ad162c3db4d1219477dfb5 ]

clip_area_update() uses drm_rect_intersect which modifies passed r1 rectangle. Early transport alignment passes the cursor uapi.dst rectangle to clip_area_update, so the cursor uapi.dst is unintentionally modified by drm_rect_intersect.

Fix this by using local copy in clip_area_update(). Also make the damage and the display area const.

Fixes 1bff93b8bc27 ("drm/i915/psr: Extend SU area to cover cursor fully if needed")
Cc <[email protected]> # v6.9+
Assisted-by GitHub-Copilot:claude-opus-5
(cherry picked from commit 8621f3bcea6b0a790a954ddf2e6514c20a24ac1a)
---
 drivers/gpu/drm/i915/display/intel_psr.c | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)
drivers/gpu/drm/i915/display/intel_psr.c +11 -9
index d1a9f9de75b9a..ebade0f4e70ba 100644
@@ -2592,23 +2592,25 @@ static u32 psr2_pipe_srcsz_early_tpt_calc(struct intel_crtc_state *crtc_state,
 }
 
 static void clip_area_update(struct drm_rect *overlap_damage_area,
-			     struct drm_rect *damage_area,
-			     struct drm_rect *display_area)
+			     const struct drm_rect *damage_area,
+			     const struct drm_rect *display_area)
 {
-	if (!drm_rect_intersect(damage_area, display_area))
+	struct drm_rect inter = *damage_area;
+
+	if (!drm_rect_intersect(&inter, display_area))
 		return;
 
 	if (overlap_damage_area->y1 == -1) {
-		overlap_damage_area->y1 = damage_area->y1;
-		overlap_damage_area->y2 = damage_area->y2;
+		overlap_damage_area->y1 = inter.y1;
+		overlap_damage_area->y2 = inter.y2;
 		return;
 	}
 
-	if (damage_area->y1 < overlap_damage_area->y1)
-		overlap_damage_area->y1 = damage_area->y1;
+	if (inter.y1 < overlap_damage_area->y1)
+		overlap_damage_area->y1 = inter.y1;
 
-	if (damage_area->y2 > overlap_damage_area->y2)
-		overlap_damage_area->y2 = damage_area->y2;
+	if (inter.y2 > overlap_damage_area->y2)
+		overlap_damage_area->y2 = inter.y2;
 }
 
 static bool intel_psr2_sel_fetch_pipe_alignment(struct intel_crtc_state *crtc_state)
Signature · 1 line
2.53.0
author maintainer
#242 lore raw

PATCH 242/686 drm/i915/gem: Reset err for each fence entry

In reply to Greg Kroah-Hartman

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

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

From: Lu Yao <[email protected]>

[ Upstream commit 31643dc89818d9b65bf42ecb1c67c99b64146fba ]

If dma_fence_chain_find_seqno() failed once, 'err' will store val in the following loop. May causing returns '-EINVAL' even though that entry never called dma_fence_chain_find_seqno() at all.

Fixes 13149e8bafc4 ("drm/i915: add syncobj timeline support")
Cc <[email protected]> # v5.10+
(cherry picked from commit 4e9db08db75f55c920986ac929cfd82a4ee99f41)
---
 drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c +1 -1
index 61f1b8f172a76..e05b1e98c9b2b 100644
@@ -2789,7 +2789,6 @@ add_timeline_fence_array(struct i915_execbuffer *eb,
 	u64 __user *user_values;
 	struct eb_fence *f;
 	u64 nfences;
-	int err = 0;
 
 	nfences = timeline_fences->fence_count;
 	if (!nfences)
@@ -2827,6 +2826,7 @@ add_timeline_fence_array(struct i915_execbuffer *eb,
 		struct drm_syncobj *syncobj;
 		struct dma_fence *fence = NULL;
 		u64 point;
+		int err = 0;
 
 		if (__copy_from_user(&user_fence,
 				     user_fences++,
Signature · 1 line
2.53.0
author maintainer
#243 lore raw

PATCH 243/686 drm/i915/display: Single scaler per pipe on WCL

In reply to Greg Kroah-Hartman

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

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

From: Vidya Srinivas <[email protected]>

[ Upstream commit 25ea7671bdbc85820026776cbe22df41c560d518 ]

WCL has only one scaler per pipe. Set num_scalers to 1 for WCL.

v2: Rebase onto latest upstream
v3: Fix up the commit message
v4: Split the scaler and joiner changes into separate patches (Jani)

Bspec: 74286

Fixes f8e1c3e07db1 ("drm/i915/xe3lpd: Add support for display version 30.02")
(cherry picked from commit 8ff2ba499b20edf6c4aad89527a1e9a70c2b2074)
---
 drivers/gpu/drm/i915/display/intel_display_device.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/gpu/drm/i915/display/intel_display_device.c +4 -1
index f3f1f25b0f383..d94f07bda5ee6 100644
@@ -1767,7 +1767,10 @@ static void __intel_display_device_info_runtime_init(struct intel_display *displ
 	if (display->platform.alderlake_s && IS_DISPLAY_STEP(display, STEP_A0, STEP_A2))
 		for_each_pipe(display, pipe)
 			display_runtime->num_scalers[pipe] = 0;
-	else if (DISPLAY_VER(display) >= 11) {
+	else if (DISPLAY_VERx100(display) == 3002) {
+		for_each_pipe(display, pipe)
+			display_runtime->num_scalers[pipe] = 1;
+	} else if (DISPLAY_VER(display) >= 11) {
 		for_each_pipe(display, pipe)
 			display_runtime->num_scalers[pipe] = 2;
 	} else if (DISPLAY_VER(display) >= 9) {
Signature · 1 line
2.53.0
author maintainer
#244 lore raw

PATCH 244/686 net: atl1c: drop oversized RX frames instead of panicking

In reply to Greg Kroah-Hartman

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

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

From: Federico Musto <[email protected]>

[ Upstream commit c4ba1716853de5178a9df785844ebb5e397a80e6 ]

atl1c sizes its receive buffers from the netdev MTU plus a fixed set of L2 overheads, which comes to 1522 bytes at the default MTU. A link partner that sends a longer frame - in practice a MikroTik CCR2004-1G-2XS-PCIe, whose RouterOS side defaults to l2mtu 1600 while the host stays at MTU 1500
- makes the length reported by the RX return descriptor exceed what the hardware wrote, and skb_put() then either includes bytes that were never received or trips skb_over_panic and takes the host down.

Compare the descriptor length against buffer_info->length, the length the hardware was given, rather than against skb_tailroom(): the skb carries 64 bytes of slack for the DMA erratum, so tailroom is larger than the DMA buffer and a frame in between would pass the check and still be delivered with a tail the device never wrote. The same test rejects frames shorter than ETH_HLEN + ETH_FCS_LEN; before this change a reported length below ETH_FCS_LEN underflowed in skb_put().

The frame is dropped with kfree_skb_reason(SKB_DROP_REASON_PKT_TOO_BIG) so drop_monitor and the kfree_skb tracepoint see it, and counted through dev_core_stats_rx_dropped_inc(), which survives atl1c_get_stats() overwriting the hardware counters on every read. It also counts as work:
atl1c_clean_rfd() has already recycled the RFD, and the refill at the end of the poll only runs when work_done is non-zero, so sustained oversized traffic would otherwise drain the ring and stop RX.

Tested on a MikroTik CCR2004-1G-2XS-PCIe (4x AR8151) in a Proxmox VE host, with atl1c built from a DKMS tree carrying this change: the l2mtu-1600 traffic that panics the stock driver is dropped and counted with the patch applied, and received normally once the host MTU is raised to match.

This complements commit 36c2009d90f2 ("net: atl1c: fix soft lockup on out-of-range tpd_cons read"), which fixed the TX side of the same "host dies while the card resets" problem.

Fixes 43250ddd75a3 ("atl1c: Atheros L1C Gigabit Ethernet driver")
---
 .../net/ethernet/atheros/atl1c/atl1c_main.c   | 33 +++++++++++++++++++
 1 file changed, 33 insertions(+)
drivers/net/ethernet/atheros/atl1c/atl1c_main.c +33 -0
index e58f1d2c26bdf..eddd8406867f7 100644
@@ -1934,6 +1934,39 @@ static int atl1c_clean_rx(struct napi_struct *napi, int budget)
 			break;
 		}
 		atl1c_clean_rfd(rfd_ring, rrs, rfd_num);
+
+		/* A link partner whose l2mtu is larger than ours can hand us a
+		 * frame that does not fit the buffer the hardware was given:
+		 * the descriptor reports the untruncated length while at most
+		 * buffer_info->length bytes were written.  skb_put() of such a
+		 * length would pull in whatever the tail of the buffer holds
+		 * and, past the end of the skb, trips skb_over_panic and takes
+		 * the host down.  Bound it by what the device actually wrote
+		 * rather than by skb_tailroom(): the skb carries 64 bytes of
+		 * slack for the DMA erratum, so the two are not the same.
+		 *
+		 * Frames shorter than an Ethernet header plus its FCS are
+		 * rejected by the same test; before this, a length below
+		 * ETH_FCS_LEN underflowed in skb_put().
+		 */
+		if (unlikely(length < ETH_HLEN + ETH_FCS_LEN ||
+			     length > buffer_info->length)) {
+			dev_core_stats_rx_dropped_inc(netdev);
+			if (netif_msg_rx_err(adapter))
+				dev_warn_ratelimited(&pdev->dev,
+						     "dropped rx frame: %u bytes, buffer %u\n",
+						     length, buffer_info->length);
+			kfree_skb_reason(skb, SKB_DROP_REASON_PKT_TOO_BIG);
+			/* atl1c_clean_rfd() has already recycled the RFD, so
+			 * count the drop as work: the refill at the end of the
+			 * poll only runs when work_done is non-zero, and
+			 * sustained oversized traffic would otherwise drain the
+			 * ring and stop RX for good.
+			 */
+			work_done++;
+			continue;
+		}
+
 		skb_put(skb, length - ETH_FCS_LEN);
 		skb->protocol = eth_type_trans(skb, netdev);
 		atl1c_rx_checksum(adapter, skb, rrs);
Signature · 1 line
2.53.0
author maintainer
#245 lore raw

PATCH 245/686 ksmbd: grant a POSIX ACL group entry only to the groups members

In reply to Greg Kroah-Hartman

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

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

From: Ian Bridges <[email protected]>

[ Upstream commit c00ec7ad449b68c291a4986e481941302ed399c5 ]

When no ACE of the DACL matches the caller, Everyone or Authenticated Users, smb_check_perm_dacl() falls back to the file's POSIX ACL. It takes the first ACL_USER or ACL_GROUP entry whose id equals the caller's uid. For ACL_GROUP, this compares a gid with the caller's uid. A numerical match grants the group's permissions even when the caller is not a member.

Match a group entry only when the caller is also in the group.

---
 fs/smb/server/smbacl.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/smb/server/smbacl.c +4 -1
index 33a607e709f18..63f7bccb4d9af 100644
@@ -1606,7 +1606,10 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,
 				else
 					continue;
 
-				if (id == uid) {
+				/* A group entry grants only to the group's members */
+				if (id == uid &&
+				    (pa_entry->e_tag == ACL_USER ||
+				     in_group_p(make_kgid(&init_user_ns, id)))) {
 					mode_to_access_flags(pa_entry->e_perm,
 							     0777,
 							     &access_bits);
Signature · 1 line
2.53.0
author maintainer
#246 lore raw

PATCH 246/686 mm/mempolicy: charge shared policy nodes

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 68b2aa37afa390f08de13bc0bac61a9ded3318bc ]

Any local user can bypass memory.max with mbind() on a tmpfs file, and allocate unbounded kernel memory.

mbind() sets a NUMA memory policy for a range of a mapping. If the mapping is of a shmem and friends, the kernel also stores the policy on the inode, in a tree with one entry per range of the file.

Each mbind() on a single page of a mapping can add one shared policy node (struct sp_node) and one struct mempolicy to that tree. They outlive the mapping and stay around until the inode is destroyed. The tree is not bounded by the file size, so the file can be empty.

Memory that user space can allocate must be charged to a memory cgroup. A slab cache does that for all of its objects if it is created with SLAB_ACCOUNT. numa_policy_init() creates the slab caches for both structs without SLAB_ACCOUNT, so they are not charged to any cgroup.

Reproduced with mbind() on single pages of an empty tmpfs file, from a cgroup with memory.max=8M: the global OOM killer killed tasks owned by root, and the machine panicked.

Fix this by creating both caches with SLAB_ACCOUNT. This change implies that mbind() can now fail when running into memcg limits. Further, the policy_cache also serves task and VMA policies, so they are similarly accounted now.

Note that per-file limits are not really helpful, as the user could simply use many files; having limits per user is tricky as well.

Fix generated by an LLM and submitted by Chris Mason in private.

---
 mm/mempolicy.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/mempolicy.c +2 -2
index 919a505cabaee..3dfd20b55a9d7 100644
@@ -3269,11 +3269,11 @@ void __init numa_policy_init(void)
 
 	policy_cache = kmem_cache_create("numa_policy",
 					 sizeof(struct mempolicy),
-					 0, SLAB_PANIC, NULL);
+					 0, SLAB_PANIC | SLAB_ACCOUNT, NULL);
 
 	sn_cache = kmem_cache_create("shared_policy_node",
 				     sizeof(struct sp_node),
-				     0, SLAB_PANIC, NULL);
+				     0, SLAB_PANIC | SLAB_ACCOUNT, NULL);
 
 	for_each_node(nid) {
 		preferred_node_policy[nid] = (struct mempolicy) {
Signature · 1 line
2.53.0
author maintainer
#247 lore raw

PATCH 247/686 tmpfs: keep the quota soft limits of an unused id

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 968d73463059156e1b89bfa6b189acd7d27197b2 ]

When the last reference to a dquot goes away, shmem_release_dquot() stores its limits in the rb tree of the mount, unless shmem_is_empty_dquot() says that there is nothing worth storing. That function looks at the usage and at the two hard limits only.

So if the administrator sets nothing but soft limits for an id that owns no file yet, the entry is thrown away as soon as the dquot that Q_SETQUOTA used is released, and the id never gets to see a limit.

To fix it, compare the soft limits as well: an entry can be empty only if both soft limits are zero as well, which is exactly what shmem_acquire_dquot() sets for a new entry.

Fix generated by an LLM and sent by Josef Bacik in private.

Fixes de4c0e7ca8b5 ("shmem: Add default quota limit mount options")
[ david: slightly adjusted description ]
---
 mm/shmem_quota.c | 2 ++
 1 file changed, 2 insertions(+)
mm/shmem_quota.c +2 -0
index d1e32ac01407a..a359e8cceedb4 100644
@@ -251,6 +251,8 @@ static bool shmem_is_empty_dquot(struct dquot *dquot)
 	if (test_bit(DQ_FAKE_B, &dquot->dq_flags) ||
 		(dquot->dq_dqb.dqb_curspace == 0 &&
 		 dquot->dq_dqb.dqb_curinodes == 0 &&
+		 dquot->dq_dqb.dqb_bsoftlimit == 0 &&
+		 dquot->dq_dqb.dqb_isoftlimit == 0 &&
 		 dquot->dq_dqb.dqb_bhardlimit == bhardlimit &&
 		 dquot->dq_dqb.dqb_ihardlimit == ihardlimit))
 		return true;
Signature · 1 line
2.53.0
author maintainer
#248 lore raw

PATCH 248/686 tmpfs: preserve explicitly disabled quota limits

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 d5d861ee303da01e59fdf8e8b2f7096c76e7efd5 ]

An administrator’s decision to disable a user’s or group’s quota limits can be silently lost when tmpfs restores the mount defaults after releasing and reacquiring the quota record. This can cause later file creation or writes to fail with EDQUOT, even though the administrator has explicitly disabled quota limits for the user or group.

do_set_dqblk() sets DQ_FAKE_B when all block and inode limits are zero. This means quota enforcement is disabled for that user or group. shmem_is_empty_dquot() treats the flag as a reason to discard the entry from the mount's quota tree. The next shmem_acquire_dquot() finds no saved entry and recreates it with the mount's default hard limits.

If the cached dquot is reused, DQ_FAKE_B remains set: Q_GETQUOTA reports the restored defaults, but enforcement is still disabled. Once that dquot has been reclaimed, a new dquot enforces the restored defaults.

Remove the DQ_FAKE_B test. Only discard entries with zero usage, zero soft limits and hard limits equal to the mount defaults. Explicitly disabled limits are then preserved whenever the mount defaults are nonzero.

Explicitly disabled limits now retain a quota-tree entry, just like other limits that differ from the mount defaults.

Rename shmem_is_empty_dquot() to shmem_is_default_dquot() to describe the check for default values.

Fix generated by an LLM and sent by Josef Bacik in private.

Fixes de4c0e7ca8b5 ("shmem: Add default quota limit mount options")
[ david: code cleanups; rewrite description ]
---
 mm/shmem_quota.c | 30 +++++++++++++++---------------
 1 file changed, 15 insertions(+), 15 deletions(-)
mm/shmem_quota.c +15 -15
index a359e8cceedb4..868b3e05f1aa8 100644
@@ -234,7 +234,7 @@ static int shmem_acquire_dquot(struct dquot *dquot)
 	return ret;
 }
 
-static bool shmem_is_empty_dquot(struct dquot *dquot)
+static bool shmem_is_default_dquot(struct dquot *dquot)
 {
 	struct shmem_sb_info *sbinfo = dquot->dq_sb->s_fs_info;
 	qsize_t bhardlimit;
@@ -248,21 +248,21 @@ static bool shmem_is_empty_dquot(struct dquot *dquot)
 		ihardlimit = sbinfo->qlimits.grpquota_ihardlimit;
 	}
 
-	if (test_bit(DQ_FAKE_B, &dquot->dq_flags) ||
-		(dquot->dq_dqb.dqb_curspace == 0 &&
-		 dquot->dq_dqb.dqb_curinodes == 0 &&
-		 dquot->dq_dqb.dqb_bsoftlimit == 0 &&
-		 dquot->dq_dqb.dqb_isoftlimit == 0 &&
-		 dquot->dq_dqb.dqb_bhardlimit == bhardlimit &&
-		 dquot->dq_dqb.dqb_ihardlimit == ihardlimit))
-		return true;
-
-	return false;
+	/*
+	 * Defaults are zero usage and soft limits, and the mount's hard limits.
+	 * DQ_FAKE_B only means that *all* limits are zero, which need not match
+	 * the mount defaults.
+	 */
+	return dquot->dq_dqb.dqb_curspace == 0 &&
+	       dquot->dq_dqb.dqb_curinodes == 0 &&
+	       dquot->dq_dqb.dqb_bsoftlimit == 0 &&
+	       dquot->dq_dqb.dqb_isoftlimit == 0 &&
+	       dquot->dq_dqb.dqb_bhardlimit == bhardlimit &&
+	       dquot->dq_dqb.dqb_ihardlimit == ihardlimit;
 }
 /*
- * Store limits from dquot in the tree unless it's fake. If it is fake
- * remove the id from the tree since there is no useful information in
- * there.
+ * Remove the ID from the tree if it has no usage and its limits match
+ * the mount defaults. Otherwise, save its limits for the next acquire.
  */
 static int shmem_release_dquot(struct dquot *dquot)
 {
@@ -297,7 +297,7 @@ static int shmem_release_dquot(struct dquot *dquot)
 	return -ENOENT;
 
 found:
-	if (shmem_is_empty_dquot(dquot)) {
+	if (shmem_is_default_dquot(dquot)) {
 		/* Remove entry from the tree */
 		rb_erase(&entry->node, info->dqi_priv);
 		kfree(entry);
Signature · 1 line
2.53.0
author maintainer
#249 lore raw

PATCH 249/686 mm/shmem: stop retrying folios that cannot be split

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit a842a1f947da8a7020e72f885ffbf2ce6a93685f ]

A fault or collapse can insert a large folio crossing EOF after shmem_undo_range() has handled the boundary folios. If splitting that folio fails, truncate_inode_partial_folio() retains it when it is dirty. The final scan then repeatedly finds it because it restarts from an unchanged start.

Truncation keeps the inode lock and ignores fatal signals while looping. A concurrent unlink() can then block other directory operations while holding the directory lock and waiting for the file's lock.

Advance start past the retained folio, whose truncated part has already been zeroed. Do not move start backwards if the failed split has shrunk the folio.

Fix generated by an LLM and sent by Chris Mason in private.

Fixes 55ac8bbe358b ("mm/shmem: fix race in shmem_undo_range w/THP")
[ david: split fixes, simplify descriptions, adjust comments ]
---
 mm/shmem.c | 9 +++++++++
 1 file changed, 9 insertions(+)
mm/shmem.c +9 -0
index 68a3a0734e3df..2ee25d8ade752 100644
@@ -1243,6 +1243,15 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
 						index = start;
 						break;
 					}
+				} else if (folio->mapping) {
+					/*
+					 * Splitting failed, but the part in the
+					 * range is already zeroed. The folio
+					 * was not dropped, so skip it when
+					 * restarting the scan to avoid retrying
+					 * it forever.
+					 */
+					start = max(start, folio_next_index(folio));
 				}
 			}
 			folio_unlock(folio);
Signature · 1 line
2.53.0
author maintainer
#250 lore raw

PATCH 250/686 mm/shmem: preserve data in clean folios when splitting fails

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 0c800435394a172f33bf4df4a5a04e187546cc9b ]

A shared writable mapping can have dirty PTEs while its shmem folio is still clean. A read fault can install a writable PTE, and a later store sets the PTE's dirty bit without marking the folio dirty.

After shmem_undo_range() has handled the boundary folios, a concurrent read fault into a hole below the new EOF can allocate a large folio. For example, on a tmpfs mount with huge=always, the fault's offset must be within the file, but the allocated folio can extend beyond i_size. The final scan then finds this folio and calls truncate_inode_partial_folio() without marking it dirty.

Splitting normally collects the PTE dirty bits when unmapping the folio. An extra reference, for example from vmsplice(), can make it fail before that step. The fallback unmapping on split failure excludes shmem, so the helper still sees a clean folio and drops it, losing data outside the range.

CPU0: ftruncate(fd, 3M) CPU1: MAP_SHARED, tmpfs huge=always
───────────────────────────────────── ────────────────────────────────── i_size = 3M
shmem_undo_range(3M, -1)
first pass: hole, nothing to do
boundary folio at 3M: hole, none
read fault at 2M+x (below EOF)
PMD folio [2M,4M), crosses EOF writable PTE, folio clean
store to 2M+x
PTE dirty, folio still clean
vmsplice(2M+x)
extra folio reference
whole_folios: finds [2M,4M) folio truncate_inode_partial_folio()
zero [3M,4M)
folio_split()
unmap_folio(): extra ref
→ -EAGAIN, PTE dirty bit
never reaches the folio
folio clean
→ truncate_inode_folio(whole)
[2M,3M) dropped
read 2M+x → refault → zeroes

Mark large folios dirty before partial truncation in the final scan, as the boundary handling already does. Exclude failed-fallocate rollback, which must discard the folios it added.

Fix generated by an LLM and sent by Chris Mason in private.

Fixes b9a8a4195c7d ("truncate,shmem: Handle truncates that split large folios")
[ david: simplify descriptions, adjust comments ]
---
 mm/shmem.c | 9 +++++++++
 1 file changed, 9 insertions(+)
mm/shmem.c +9 -0
index 2ee25d8ade752..a764a26b0adf2 100644
@@ -1227,6 +1227,15 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
 				VM_BUG_ON_FOLIO(folio_test_writeback(folio),
 						folio);
 
+				/*
+				 * A shared mapping can have dirty PTEs while
+				 * the folio is still clean. Mark the folio
+				 * dirty so a failed split cannot discard data
+				 * outside the range.
+				 */
+				if (!unfalloc && folio_test_large(folio))
+					folio_mark_dirty(folio);
+
 				if (!folio_test_large(folio)) {
 					truncate_inode_folio(mapping, folio);
 				} else if (truncate_inode_partial_folio(folio, lstart, lend)) {
Signature · 1 line
2.53.0
author maintainer
#251 lore raw

PATCH 251/686 mm/shmem: discard whole new large folios on fallocate rollback

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 23f2a880c0b9518fcb7e7e2ad54a29c0a2c4fba0 ]

When undoing a failed fallocate(), shmem_undo_range() must discard each newly allocated folio. Its second scan instead passes large folios to truncate_inode_partial_folio(), which does not necessarily discard the entire large folio, but instead tries splitting it to discard only the requested range.

For example, with huge=always, a failed allocation starting at offset 4 KiB can leave page 0 allocated in an otherwise empty file.

Discard the whole folio when unfalloc is set. Note that we enter this path only for folios that are not uptodate, and can consequently be dropped without losing any data.

---
 mm/shmem.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/shmem.c +1 -1
index a764a26b0adf2..675d45aa85f64 100644
@@ -1236,7 +1236,7 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
 				if (!unfalloc && folio_test_large(folio))
 					folio_mark_dirty(folio);
 
-				if (!folio_test_large(folio)) {
+				if (unfalloc || !folio_test_large(folio)) {
 					truncate_inode_folio(mapping, folio);
 				} else if (truncate_inode_partial_folio(folio, lstart, lend)) {
 					/*
Signature · 1 line
2.53.0
author maintainer
#252 lore raw

PATCH 252/686 mm/shmem: rescan after nonuniform folio splitting

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 f0d67b3d0a464847337d5063766d55e16041323e ]

The final scan in shmem_undo_range() restarts after a successful split only if the original folio is no longer large. A nonuniform split can leave that folio large, so the scan skips the newly created folios. Hole punching then leaves pages within the hole allocated even though they could be discarded.

For example, a fault below the hole can allocate a 2 MiB folio after boundary handling. Punching a 1 MiB hole at offset 64 KiB splits the folio successfully but leaves the original folio at order 4. The scan continues past all 512 pages, leaving 2 MiB allocated instead of 1 MiB. The hole reads as zero, but the pages and their block charges remain.

---
 mm/shmem.c | 16 +++++-----------
 1 file changed, 5 insertions(+), 11 deletions(-)
mm/shmem.c +5 -11
index 675d45aa85f64..c598daacb5efa 100644
@@ -1240,18 +1240,12 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
 					truncate_inode_folio(mapping, folio);
 				} else if (truncate_inode_partial_folio(folio, lstart, lend)) {
 					/*
-					 * If we split a page, reset the loop so
-					 * that we pick up the new sub pages.
-					 * Otherwise the THP was entirely
-					 * dropped or the target range was
-					 * zeroed, so just continue the loop as
-					 * is.
+					 * The folio was split. Retry the scan
+					 * to find the split folios.
 					 */
-					if (!folio_test_large(folio)) {
-						folio_unlock(folio);
-						index = start;
-						break;
-					}
+					folio_unlock(folio);
+					index = start;
+					break;
 				} else if (folio->mapping) {
 					/*
 					 * Splitting failed, but the part in the
Signature · 1 line
2.53.0
author maintainer
#253 lore raw

PATCH 253/686 mm/shmem: fix truncate hang in large swap entry

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 fa213b08f37f9dff78ce240a87579dc264fc7a5d ]

Truncating a tmpfs file or memfd to a page-aligned size inside a large swap entry can loop indefinitely in shmem_undo_range(). The task holds the inode lock and cannot be killed.

A large swap entry represents a whole swapped-out folio. For example, truncate a file whose pages 0-7 share one swap entry to four pages:

[ 0 1 2 3 | 4 5 6 7 ]
keep | discard
^
new EOF, start = 4

i_size has already been updated when boundary handling asks shmem_get_partial_folio() for page 4. Since it is swapped out, the helper calls shmem_get_folio() with SGP_READ. That rejects page 4 with -EINVAL because its starting offset equals i_size. Nothing is read back.

The final scan cannot free the entry without losing pages 0-3. It skips it, restarts from start = 4, and finds it again indefinitely. An unaligned truncate avoids this particular failure because the requested page starts below i_size. Folios already in the page-cache cannot trigger it as the direct lookup will return them beyond EOF.

Fix it by letting shmem_get_partial_folio() call shmem_swapin_folio() directly for swap entries. This bypasses the read path's i_size check, allowing the existing boundary handling to zero and split the folio. If swap-in returns a smaller folio, it also splits the swap entry so the final scan can free the entries beyond EOF. Retry the lookup if the entry changes during swap-in.

Handling swap-in allocation failures remains broken and is unchanged by this commit. Even when shmem_swapin_folio() correctly returns -ENOMEM instead of -EEXIST, shmem_get_partial_folio() returns NULL and shmem_undo_range() skips boundary handling. If the large swap entry remains intact, truncation can still loop in the final scan, while hole punching can return without zeroing the boundary.

This may read an entire large folio back from swap while holding i_rwsem, only to discard part of it. Avoiding that I/O would require splitting both the swap entry and any large folio still in the swap cache. That, however, is much bigger work.

---
 mm/shmem.c | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
mm/shmem.c +7 -8
index c598daacb5efa..4c5e07c8f3173 100644
@@ -1057,12 +1057,10 @@ void shmem_unlock_mapping(struct address_space *mapping)
 
 static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index)
 {
+	const gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
 	struct folio *folio;
 
-	/*
-	 * At first avoid shmem_get_folio(,,,SGP_READ): that fails
-	 * beyond i_size, and reports fallocated folios as holes.
-	 */
+retry:
 	folio = filemap_get_entry(inode->i_mapping, index);
 	if (!folio)
 		return folio;
@@ -1073,13 +1071,14 @@ static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index)
 		/* The folio has been swapped out */
 		folio_unlock(folio);
 		folio_put(folio);
+		goto retry;
 	}
 	/*
-	 * But read a folio back from swap if any of it is within i_size
-	 * (although in some cases this is just a waste of time).
+	 * Truncation can look up a large swap entry at or beyond i_size.
+	 * Swap it in directly to bypass the size check in shmem_get_folio().
 	 */
-	folio = NULL;
-	shmem_get_folio(inode, index, 0, &folio, SGP_READ);
+	if (shmem_swapin_folio(inode, index, &folio, SGP_READ, gfp, NULL, NULL) == -EEXIST)
+		goto retry;
 	return folio;
 }
 
Signature · 1 line
2.53.0
author maintainer
#254 lore raw

PATCH 254/686 mm/shmem: fix truncate loop after boundary swapin failure

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 5f1ec2cf92a7d655a8eb39711987822f9b1f9d67 ]

If swapping in a large entry at the new EOF fails, shmem_undo_range() leaves the entry in place. Its final scan skips the entry, then restarts from the same start index and finds it again. Truncation can loop forever while holding i_rwsem.

Advance start past the skipped entry so that a restarted scan can finish, as we already do for folios that cannot be split.

Note that this does not fix the missing zeroing when boundary swapin fails, it merely prevents the endless loop.

---
 mm/shmem.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
mm/shmem.c +6 -4
index 4c5e07c8f3173..169ba30664782 100644
@@ -1197,14 +1197,16 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
 					order = shmem_confirm_swap(mapping, indices[i],
 								   radix_to_swp_entry(folio));
 					/*
-					 * If found a large swap entry cross the end or start
-					 * border, skip it as the truncate_inode_partial_folio
-					 * above should have at least zerod its content once.
+					 * Skip boundary entries when restarting
+					 * the scan to avoid endless loops after
+					 * swapin failure.
 					 */
 					if (order > 0) {
 						base = round_down(base, 1 << order);
-						if (base < start || base + (1 << order) > end)
+						if (base < start || base + (1 << order) > end) {
+							start = max(start, base + (1 << order));
 							continue;
+						}
 					}
 					/* Swap was replaced by page or extended, retry */
 					index = base;
Signature · 1 line
2.53.0
author maintainer
#255 lore raw

PATCH 255/686 mm/shmem: fix truncation of files containing only swapin-error markers

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 59511d630a6942356ac4b6984797998a8f3a9017 ]

It might not be very common, but we can end up with shmem files that are composed only of swapin-error/poison markers.

Such markers are not counted in info->alloced. Consequently, shmem_setattr() can skip shmem_truncate_range(), leaving the markers behind.

Truncating the file to zero and growing it again will result in reads failing with -EIO instead of returning zeroes.

Check whether the mapping contains entries, in addition to info->alloced, before skipping the truncation. Keep the info->alloced check so that shmem_recalc_inode(), called at the end of shmem_undo_range(), can fix up accounting after reclaim has emptied the mapping.

Fixes 6cec2b95dadf ("mm/shmem: fix infinite loop when swap in shmem error at swapoff time")
---
 mm/shmem.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/shmem.c +2 -1
index 169ba30664782..da043ca0c2e22 100644
@@ -1351,7 +1351,8 @@ static int shmem_setattr(struct mnt_idmap *idmap,
 			if (oldsize > holebegin)
 				unmap_mapping_range(inode->i_mapping,
 							holebegin, 0, 1);
-			if (info->alloced)
+			/* Swapin-error markers are not counted in alloced. */
+			if (info->alloced || !mapping_empty(inode->i_mapping))
 				shmem_truncate_range(inode,
 							newsize, (loff_t)-1);
 			/* unmap again to remove racily COWed private pages */
Signature · 1 line
2.53.0
author maintainer
#256 lore raw

PATCH 256/686 mm/mglru: dont use stack pointers when walking PUD and PMD tables

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 65a9bf08a3e4d6e58df211ed900c16bafb79b267 ]

MGLRU passes stack copies of page-table entries in walk_pud_range() and walk_pmd_range() when walking to the next level. These copies can become stale when khugepaged or MADV_DONTNEED (CONFIG_PT_RECLAIM) removes a PTE table concurrently.

This pattern dates back to commit bd74fdaea146 ("mm: multi-gen LRU:
support page table walks"). Likely, earlier locking masked the latent bug. Later changes exposed it: commit 1d65b771bc08 ("mm/khugepaged:
retract_page_tables() without mmap or vma lock") allowed concurrent retraction, and commit cf4a65539c13 ("memcg-v1: no need for memcg locking for MGLRU") dropped the walker's outer RCU protection.

The fix is simple, so just fix the original commit so we don't have to speculate. To fix it, pass the actual PMD/PUD pointers. This restores the RCU-protected lookup and validation against the live PMD. Note that the PUD handling is required as well to handle folded page tables correctly in all cases.

Fix generated by an LLM and sent by Josef Bacik in private.

[ david: handle walk_pud_range() as well, clarify+simplify description,
adjust Fixes: ]

---
 mm/vmscan.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/vmscan.c +2 -2
index e640d1ec59749..ed75f1bce9f0a 100644
@@ -3750,7 +3750,7 @@ static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
 
 		walk->mm_stats[MM_NONLEAF_FOUND]++;
 
-		if (!walk_pte_range(&val, addr, next, args))
+		if (!walk_pte_range(pmd + i, addr, next, args))
 			continue;
 
 		walk->mm_stats[MM_NONLEAF_ADDED]++;
@@ -3786,7 +3786,7 @@ static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
 		if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
 			continue;
 
-		walk_pmd_range(&val, addr, next, args);
+		walk_pmd_range(pud + i, addr, next, args);
 
 		if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
 			end = (addr | ~PUD_MASK) + 1;
Signature · 1 line
2.53.0
author maintainer
#257 lore raw

PATCH 257/686 mm/memfd: make f_pos accesses atomic

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 5426cd43a4d28f1041c9ca45955121b921f29548 ]

Commit 9c225f2655e3 ("vfs: atomic f_pos accesses as per POSIX") made read(), write() and lseek() on a shared open file description of a regular file serialize on ->f_pos_lock. The flag that asks for it, FMODE_ATOMIC_POS, is set in do_dentry_open(). A memfd is a regular file too, but its struct file comes from alloc_file_pseudo() and never passes through do_dentry_open(), so it does not get the flag:

CPU0 CPU1
write(memfd, "a", 1) write(memfd, "b", 1)

    pos = file->f_pos  (= 0)
                                        pos = file->f_pos  (= 0)
    vfs_write(..., &pos)
                                        vfs_write(..., &pos)
    file->f_pos = pos  (= 1)
                                        file->f_pos = pos  (= 1)

One of the two bytes is overwritten. Two threads writing 100000 bytes each, one at a time, to a memfd end up with a file that is far shorter than 200000 bytes, while the same program on a tmpfs file never loses a byte.

Set the flag when the memfd is created. As for any other regular file the lock is only taken if the file is reachable in more than one way, and nothing a memfd does in read or write waits for another operation on the same file. This cannot be done for all alloc_file_pseudo() files: anon inode files such as eventfd are S_IFREG as well, and a blocked read holding ->f_pos_lock would lock out the write that is supposed to wake it.

Fix generated by an LLM and sent by Josef Bacik in private.

---
 mm/memfd.c | 2 ++
 1 file changed, 2 insertions(+)
mm/memfd.c +2 -0
index f7ba1e9dea49a..aa3c948e55738 100644
@@ -472,6 +472,8 @@ static struct file *alloc_file(const char *name, unsigned int flags)
 	if (IS_ERR(file))
 		return file;
 	file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
+	/* a regular file like any other: POSIX.1-2008/SUSv4 Section XSI 2.9.7 */
+	file->f_mode |= FMODE_ATOMIC_POS;
 	file->f_flags |= O_LARGEFILE;
 
 	if (flags & MFD_NOEXEC_SEAL) {
Signature · 1 line
2.53.0
author maintainer
#258 lore raw

PATCH 258/686 mm/filemap: dont lose a folio lock wakeup to a signal

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 8ccb6ded6a47b59b4907ed4f8c293cf8122de889 ]

An exclusive waiter in folio_wait_bit_common() can leave the wait loop because of a fatal signal, then be woken by folio_unlock() before finish_wait(). If the waker did not hand over the lock, the waiter returns -EINTR without trying to acquire it.

folio_wake_bit() stops after waking the first exclusive waiter, so this loses the wakeup and can leave other waiters asleep indefinitely on an unlocked folio.

After finish_wait(), let a waiter woken without a lock handoff try once more to acquire the lock. If successful, return success so the caller's eventual unlock wakes the next waiter. Otherwise, the current lock owner will do so.

Fix generated by an LLM and sent by Josef Bacik in private.

Fixes 5ef64cc8987a ("mm: allow a controlled amount of unfairness in the page lock")
[ david: clarify and simplify comment + description ]
---
 mm/filemap.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
mm/filemap.c +15 -3
index 1a03588106090..7a8528d1daf79 100644
@@ -1383,10 +1383,22 @@ static inline int folio_wait_bit_common(struct folio *folio, int bit_nr,
 	 * return value based on that state without races.
 	 *
 	 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
-	 * waiter, but an exclusive one requires WQ_FLAG_DONE.
+	 * waiter, but an exclusive one must also acquire the bit.
 	 */
-	if (behavior == EXCLUSIVE)
-		return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
+	if (behavior == EXCLUSIVE) {
+		if (wait->flags & WQ_FLAG_DONE)
+			return 0;
+		/*
+		 * We might have just been woken up and the waker will not
+		 * wake up anybody else. If we ignore that now, the remaining
+		 * waiters may not get woken up: take the bit now if it is
+		 * still free.
+		 */
+		if ((wait->flags & WQ_FLAG_WOKEN) &&
+		    !test_and_set_bit(bit_nr, folio_flags(folio, 0)))
+			return 0;
+		return -EINTR;
+	}
 
 	return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
 }
Signature · 1 line
2.53.0
author maintainer
#259 lore raw

PATCH 259/686 mm/filemap: finish fault cleanup before dropping the fault lock

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 97156a6c355c21f7122421915f05461bd11699a4 ]

On a retried fault, a fatal signal interrupting the folio lock wait makes lock_folio_maybe_drop_mmap() drop the fault lock without pinning the file. However, filemap_fault() may still need to release mapping->invalidate_lock. A concurrent munmap() can release the last file reference and free the mapping before that unlock.

Defer dropping the fault lock to filemap_fault()'s retry cleanup, after releasing invalidate_lock. If the fault lock was already dropped for I/O, release the existing file reference instead. Keep the fault lock held for FAULT_FLAG_RETRY_NOWAIT as before.

---
 mm/filemap.c | 37 +++++++++++++------------------------
 1 file changed, 13 insertions(+), 24 deletions(-)
mm/filemap.c +13 -24
index 7a8528d1daf79..cd7af384cff26 100644
@@ -3222,11 +3222,11 @@ loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
  * @folio - the folio to lock.
  * @fpin - the pointer to the file we may pin (or is already pinned).
  *
- * This works similar to lock_folio_or_retry in that it can drop the
- * mmap_lock.  It differs in that it actually returns the folio locked
- * if it returns 1 and 0 if it couldn't lock the folio.  If we did have
- * to drop the mmap_lock then fpin will point to the pinned file and
- * needs to be fput()'ed at a later point.
+ * Returns 1 with the folio locked, or 0 if locking failed.
+ *
+ * On both entry and return, a non-NULL *fpin means the fault lock has
+ * already been dropped and the caller must eventually fput() the file.
+ * Otherwise the fault lock is still held, including on failure.
  */
 static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,
 				     struct file **fpin)
@@ -3243,21 +3243,9 @@ static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,
 		return 0;
 
 	*fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
-	if (vmf->flags & FAULT_FLAG_KILLABLE) {
-		if (__folio_lock_killable(folio)) {
-			/*
-			 * We didn't have the right flags to drop the
-			 * fault lock, but all fault_handlers only check
-			 * for fatal signals if we return VM_FAULT_RETRY,
-			 * so we need to drop the fault lock here and
-			 * return 0 if we don't have a fpin.
-			 */
-			if (*fpin == NULL)
-				release_fault_lock(vmf);
-			return 0;
-		}
-	} else
-		__folio_lock(folio);
+	if (vmf->flags & FAULT_FLAG_KILLABLE)
+		return !__folio_lock_killable(folio);
+	__folio_lock(folio);
 
 	return 1;
 }
@@ -3459,7 +3447,7 @@ static vm_fault_t filemap_fault_recheck_pte_none(struct vm_fault *vmf)
  * vma->vm_mm->mmap_lock must be held on entry.
  *
  * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
- * may be dropped before doing I/O or by lock_folio_maybe_drop_mmap().
+ * may be dropped before doing I/O or when aborting an interrupted wait.
  *
  * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
  * has not been released.
@@ -3615,9 +3603,8 @@ vm_fault_t filemap_fault(struct vm_fault *vmf)
 
 out_retry:
 	/*
-	 * We dropped the mmap_lock, we need to return to the fault handler to
-	 * re-find the vma and come back and find our hopefully still populated
-	 * page.
+	 * With fpin set, the fault lock was already dropped. Otherwise it is
+	 * still held. Release invalidate_lock before dropping either protection.
 	 */
 	if (!IS_ERR(folio))
 		folio_put(folio);
@@ -3625,6 +3612,8 @@ vm_fault_t filemap_fault(struct vm_fault *vmf)
 		filemap_invalidate_unlock_shared(mapping);
 	if (fpin)
 		fput(fpin);
+	else if (!(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
+		release_fault_lock(vmf);
 	return ret | VM_FAULT_RETRY;
 }
 EXPORT_SYMBOL(filemap_fault);
Signature · 1 line
2.53.0
author maintainer
#260 lore raw

PATCH 260/686 ext2: preserve completed DIO bytes when buffered fallback fails

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 cbf04dde8b3c5a7e043e91cefad68b8980ea0d18 ]

ext2_dio_write_iter() can complete part of a direct write before falling back to buffered I/O for a hole inside i_size. If generic_perform_write() then fails, its error overwrites the completed direct-I/O byte count.

For example, on a full filesystem, an 8 KiB write to a file with an allocated 4 KiB prefix and a 4 KiB hole overwrites the prefix but returns ENOSPC and leaves the file position unchanged. GNU dd with oflag=direct consequently reports zero bytes written.

Preserve a positive direct-I/O result and return the buffered error when no bytes were direct-written. This restores the fallback policy of generic_file_write_iter(), which ext2 used before its iomap conversion.

---
 fs/ext2/file.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/ext2/file.c +2 -1
index c59c19e5ff72b..81f9cf3b884ce 100644
@@ -256,7 +256,8 @@ static ssize_t ext2_dio_write_iter(struct kiocb *iocb, struct iov_iter *from)
 		pos = iocb->ki_pos;
 		status = generic_perform_write(iocb, from);
 		if (unlikely(status < 0)) {
-			ret = status;
+			if (!ret)
+				ret = status;
 			goto out_unlock;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#261 lore raw

PATCH 261/686 xfs: dont skip free extents in later batches of a whole-AG FITRIM

In reply to Greg Kroah-Hartman

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

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

From: Daejun Park <[email protected]>

[ Upstream commit 595e67d7261673d03c96950ffbb2e545c00376ed ]

A whole-device FITRIM walks every AG but the last by length, in batches. xfs_trim_gather_extents() saves the record to restart from in tcur->start. But tcur->start is also the start of the range to trim. Later batches therefore never discard the free extents below that block.

Save the restart record in a new restart_bno field.

Fixes b0ffe661fab4 ("xfs: fix performance problems when fstrimming a subset of a fragmented AG")
---
 fs/xfs/xfs_discard.c | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)
fs/xfs/xfs_discard.c +14 -4
index 6917de8321915..b866329c7a28d 100644
@@ -166,6 +166,8 @@ struct xfs_trim_cur {
 	xfs_agblock_t	end;
 	xfs_extlen_t	minlen;
 	bool		by_bno;
+	/* restart point (with count) for the by-length walk */
+	xfs_agblock_t	restart_bno;
 };
 
 static int
@@ -209,14 +211,15 @@ xfs_trim_gather_extents(
 		error = xfs_alloc_lookup_le(cur, tcur->start, 0, &i);
 		if (!error && !i)
 			error = xfs_alloc_lookup_ge(cur, tcur->start, 0, &i);
-	} else if (tcur->start == 0) {
+	} else if (tcur->restart_bno == NULLAGBLOCK) {
 		/* first time through a by-len starts with max length */
 		cur = xfs_cntbt_init_cursor(mp, tp, agbp, pag);
 		error = xfs_alloc_lookup_ge(cur, 0, tcur->count, &i);
 	} else {
 		/* nth time through a by-len starts where we left off */
 		cur = xfs_cntbt_init_cursor(mp, tp, agbp, pag);
-		error = xfs_alloc_lookup_le(cur, tcur->start, tcur->count, &i);
+		error = xfs_alloc_lookup_le(cur, tcur->restart_bno,
+					    tcur->count, &i);
 	}
 	if (error)
 		goto out_del_cursor;
@@ -246,9 +249,15 @@ xfs_trim_gather_extents(
 		if (--batch <= 0) {
 			/*
 			 * Update the cursor to point at this extent so we
-			 * restart the next batch from this extent.
+			 * restart the next batch from this extent. The
+			 * by-length walk does not visit extents in block
+			 * order, so it must keep the start of the range and
+			 * restart from restart_bno instead.
 			 */
-			tcur->start = fbno;
+			if (tcur->by_bno)
+				tcur->start = fbno;
+			else
+				tcur->restart_bno = fbno;
 			tcur->count = flen;
 			break;
 		}
@@ -351,6 +360,7 @@ xfs_trim_perag_extents(
 		.start		= start,
 		.end		= end,
 		.minlen		= minlen,
+		.restart_bno	= NULLAGBLOCK,
 	};
 	int			error = 0;
 
Signature · 1 line
2.53.0
author maintainer
#262 lore raw

PATCH 262/686 xfs: dont skip free extents of the longest length in a whole-AG FITRIM

In reply to Greg Kroah-Hartman

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

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

From: Daejun Park <[email protected]>

[ Upstream commit 5745f4f10a1a16aa5bb020acc38afa33f2d5ff99 ]

Since commit a66d636385d6 ("xfs: fix fstrim offset calculations"), the by-length walk of an AG in FITRIM starts with xfs_alloc_lookup_ge(cur, 0, pagf_longest) and walks down. The lookup lands on the longest free extent with the lowest block number. The other free extents of that length sort after it and are never discarded.

Start every by-length batch with xfs_alloc_lookup_le() at restart_bno.

---
 fs/xfs/xfs_discard.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
fs/xfs/xfs_discard.c +5 -5
index b866329c7a28d..98933c1725214 100644
@@ -211,12 +211,12 @@ xfs_trim_gather_extents(
 		error = xfs_alloc_lookup_le(cur, tcur->start, 0, &i);
 		if (!error && !i)
 			error = xfs_alloc_lookup_ge(cur, tcur->start, 0, &i);
-	} else if (tcur->restart_bno == NULLAGBLOCK) {
-		/* first time through a by-len starts with max length */
-		cur = xfs_cntbt_init_cursor(mp, tp, agbp, pag);
-		error = xfs_alloc_lookup_ge(cur, 0, tcur->count, &i);
 	} else {
-		/* nth time through a by-len starts where we left off */
+		/*
+		 * A by-len walk starts at the last record of the longest
+		 * length (restart_bno is NULLAGBLOCK until the first batch
+		 * ends) and then where the previous batch stopped.
+		 */
 		cur = xfs_cntbt_init_cursor(mp, tp, agbp, pag);
 		error = xfs_alloc_lookup_le(cur, tcur->restart_bno,
 					    tcur->count, &i);
Signature · 1 line
2.53.0
author maintainer
#263 lore raw

PATCH 263/686 drm/v3d: Initialize timedout_batches when running a CSD job

In reply to Greg Kroah-Hartman

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

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

From: Jose Maria Casanova Crespo <[email protected]>

[ Upstream commit 0afdbdd5b1af729108de8f893d179c3b99eac29d ]

v3d_csd_job_timedout() decides whether a compute job made progress by comparing CSD_CURRENT_CFG4, the number of batches the dispatcher still has to start, against the value saved at the previous timeout. That saved value is never initialized, so it is zero on the first timeout.

On V3D 7.1.6 and later, CFG4 counts down to zero once the dispatcher has started the last batch, but the dispatch keeps running until the batches in flight complete. If the first timeout fires in that window, the handler sees no change and resets the GPU while the job is about to complete. For example, this happens with long dispatches that only keep a single supergroup in flight.

Initialize timedout_batches to the value programmed in CFG4 when the job is started. The register does not return to it once a batch has started:
it counts down to zero on V3D 7.1.6 and later (CFG4 holds the number of batches), and to 0xffffffff on V3D 4.2 (CFG4 holds the number of batches minus one).

---
 drivers/gpu/drm/v3d/v3d_sched.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/gpu/drm/v3d/v3d_sched.c +2 -0
index 9b98386965796..5cdfc107a012d 100644
@@ -403,6 +403,8 @@ v3d_csd_job_run(struct drm_sched_job *sched_job)
 		dma_fence_put(job->base.irq_fence);
 	job->base.irq_fence = dma_fence_get(fence);
 
+	job->timedout_batches = job->args.cfg[4];
+
 	trace_v3d_submit_csd(dev, to_v3d_fence(fence)->seqno);
 
 	v3d_job_start_stats(&job->base, V3D_CSD);
Signature · 1 line
2.53.0
author maintainer
#264 lore raw

PATCH 264/686 drm/v3d: Widen cache_clean_lock over the whole L2TCACTL sequence

In reply to Greg Kroah-Hartman

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

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

From: Maíra Canal <[email protected]>

[ Upstream commit 994ba6e5c87d6a3d471ea987fe8622168f092334 ]

v3d_clean_caches() and v3d_flush_l2t() both write the single L2TCACTL register and poll its status bits. The mutex cache_clean_lock exists to serialize them, but v3d_clean_caches() only took the lock around its final FLM_CLEAN write.

These functions run concurrently: v3d_flush_l2t() is issued from the BIN/RENDER/CSD invalidate path while v3d_clean_caches() runs from the CACHE_CLEAN queue, and each queue's scheduler uses its own ordered workqueue, so their run_job callbacks execute in parallel.

Because clean locked only its final write, a concurrent flush can write L2TCACTL during clean's unlocked phase. Both use non read-modify-write writes to the one register, so whichever lands last wins: clean's TMUWCF write can land on the flush's in-flight L2TFLS invalidate, triggering the GFXH-1897 hazard of writing L2TCACTL while a flush is pending.

Hold cache_clean_lock across the entire L2TCACTL access sequence so it is fully mutually exclusive with v3d_flush_l2t(), which already takes the lock around its own write.

---
 drivers/gpu/drm/v3d/v3d_gem.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/gpu/drm/v3d/v3d_gem.c +2 -3
index b499f6635cd24..92df68f5523b1 100644
@@ -222,6 +222,8 @@ v3d_clean_caches(struct v3d_dev *v3d)
 	struct drm_device *dev = &v3d->drm;
 	int core = 0;
 
+	guard(mutex)(&v3d->cache_clean_lock);
+
 	trace_v3d_cache_clean_begin(dev);
 
 	/* GFXH-1897: Ensure pending flushes complete before writing L2TCACTL */
@@ -238,7 +240,6 @@ v3d_clean_caches(struct v3d_dev *v3d)
 		DRM_ERROR("Timeout waiting for TMU write combiner flush\n");
 	}
 
-	mutex_lock(&v3d->cache_clean_lock);
 	V3D_CORE_WRITE(core, V3D_CTL_L2TCACTL,
 		       V3D_L2TCACTL_L2TFLS |
 		       V3D_SET_FIELD(V3D_L2TCACTL_FLM_CLEAN, V3D_L2TCACTL_FLM));
@@ -248,8 +249,6 @@ v3d_clean_caches(struct v3d_dev *v3d)
 		DRM_ERROR("Timeout waiting for L2T clean\n");
 	}
 
-	mutex_unlock(&v3d->cache_clean_lock);
-
 	trace_v3d_cache_clean_end(dev);
 }
 
Signature · 1 line
2.53.0
author maintainer
#265 lore raw

PATCH 265/686 cipso: fix optlen corruption in cipso_v4_delopt()

In reply to Greg Kroah-Hartman

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

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

From: Qihang <[email protected]>

[ Upstream commit 1f1f8e8c5176234fa31858cd25f2e9b88aac0a45 ]

cipso_v4_delopt() recomputes the option length by walking the option buffer after the CIPSO option has been moved out. The walk then reads the stale bytes at the tail of the buffer as option data, and a crafted setsockopt(IP_OPTIONS) buffer can make it treat one of them as an option length, increasing opt->opt.optlen beyond the valid option data.

The corrupted length stays on the socket and is later used as the copy length by getsockopt(IP_OPTIONS) and by the udp/raw/ping sendmsg paths, where it exceeds the size of the buffers they copy into.

Compute the new length from the intact options before the move and subtract the CIPSO length, and fill the padding with IPOPT_END.

Assisted-by LLM
Fixes 014ab19a69c32 ("selinux: Set socket NetLabel based on connection endpoint")
---
 net/ipv4/cipso_ipv4.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
net/ipv4/cipso_ipv4.c +7 -2
index e741f0a47afbd..793c556c206d7 100644
@@ -2014,6 +2014,10 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr)
 		cipso_ptr = &opt->opt.__data[cipso_off];
 		cipso_len = cipso_ptr[1];
 
+		optlen_new = cipso_v4_get_actual_opt_len(opt->opt.__data,
+							 opt->opt.optlen);
+		optlen_new -= cipso_len;
+
 		if (opt->opt.srr > opt->opt.cipso)
 			opt->opt.srr -= cipso_len;
 		if (opt->opt.rr > opt->opt.cipso)
@@ -2027,11 +2031,12 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr)
 		memmove(cipso_ptr, cipso_ptr + cipso_len,
 			opt->opt.optlen - cipso_off - cipso_len);
 
-		optlen_new = cipso_v4_get_actual_opt_len(opt->opt.__data,
-							 opt->opt.optlen);
 		hdr_delta = opt->opt.optlen;
 		opt->opt.optlen = (optlen_new + 3) & ~3;
 		hdr_delta -= opt->opt.optlen;
+
+		memset(&opt->opt.__data[optlen_new], IPOPT_END,
+		       opt->opt.optlen - optlen_new);
 	} else {
 		/* only the cipso option was present on the socket so we can
 		 * remove the entire option struct */
Signature · 1 line
2.53.0
author maintainer
#266 lore raw

PATCH 266/686 vhost-vdpa: fix pinned page leak in vhost_vdpa_pa_map() error path

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit fd1462c96bafe2cb14e88c837b270f8990b717b5 ]

When pin_user_pages() or vhost_vdpa_map() fails, vhost_vdpa_pa_map() is supposed to unpin the pages pinned after the last successfully mapped chunk, i.e. the range [map_pfn, last_pfn]. The unpin is guarded by nchunks, but nchunks is reset to 0 every time a chunk is mapped from inside the current page list, so a failure after any such boundary leaves that pending range pinned forever. With physically scattered memory nearly every page list contains a boundary, so the leak happens on practically every failed IOTLB update.

The pending range is non-empty exactly when a page has been pinned, which last_pfn already tells us, so drop nchunks and test last_pfn.

Fixes ad89653f79f1 ("vhost-vdpa: fix page pinning leakage in error path (rework)")

Message-ID: <[email protected]>

---
 drivers/vhost/vdpa.c | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)
drivers/vhost/vdpa.c +2 -6
index 219af4f0d06a8..e4ddaf0e5abc6 100644
@@ -1149,7 +1149,7 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v,
 	unsigned long list_size = PAGE_SIZE / sizeof(struct page *);
 	unsigned int gup_flags = FOLL_LONGTERM;
 	unsigned long npages, cur_base, map_pfn, last_pfn = 0;
-	unsigned long lock_limit, sz2pin, nchunks, i;
+	unsigned long lock_limit, sz2pin, i;
 	unsigned long page_offset;
 	u64 start = iova;
 	long pinned;
@@ -1185,7 +1185,6 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v,
 
 	cur_base = uaddr & PAGE_MASK;
 	iova &= PAGE_MASK;
-	nchunks = 0;
 
 	while (npages) {
 		sz2pin = min_t(unsigned long, npages, list_size);
@@ -1200,7 +1199,6 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v,
 			}
 			goto out;
 		}
-		nchunks++;
 
 		if (!last_pfn)
 			map_pfn = page_to_pfn(page_list[0]);
@@ -1231,7 +1229,6 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v,
 
 				map_pfn = this_pfn;
 				iova += csize;
-				nchunks = 0;
 			}
 
 			last_pfn = this_pfn;
@@ -1246,7 +1243,7 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v,
 			     PFN_PHYS(map_pfn), perm, NULL);
 out:
 	if (ret) {
-		if (nchunks) {
+		if (last_pfn) {
 			unsigned long pfn;
 
 			/*
@@ -1258,7 +1255,6 @@ static int vhost_vdpa_pa_map(struct vhost_vdpa *v,
 			 * the corresponding unpinning will be handled by
 			 * vdpa_unmap().
 			 */
-			WARN_ON(!last_pfn);
 			for (pfn = map_pfn; pfn <= last_pfn; pfn++)
 				unpin_user_page(pfn_to_page(pfn));
 		}
Signature · 1 line
2.53.0
author maintainer
#267 lore raw

PATCH 267/686 vringh: bound top-level re-entry into indirect tables

In reply to Greg Kroah-Hartman

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

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

From: Fang Xieyan <[email protected]>

[ Upstream commit f898439ace7f89922e853b43bcbfcd26ea2e0a98 ]

In __vringh_iov(), the F_INDIRECT branch descends into the indirect table and continues before the descriptor accounting runs. A top-level indirect descriptor is therefore never charged to count. If such a descriptor sets NEXT to point back at itself, returning from the indirect table resumes at the same top-level descriptor, which is again not counted, so the walk never makes forward progress.

Because count stays flat and indirect_count is reset to 0 on every return to the top-level table, neither bound in the loop check trips. A guest can spin the vringh worker at 100% CPU inside __vringh_iov(), an uninterruptible host DoS.

Move the descriptor accounting above the indirect switch so that a top-level indirect descriptor is charged one top-level traversal step before the walk descends into its table, bringing this re-entry under the existing vrh->vring.num bound. Each top-level descriptor is still charged at most one step and indirect_count still bounds a single table, so legitimate chains (including the multiple-indirect case in tools/virtio/vringh_test.c) stay within vring.num, while a cyclic indirect descriptor is now rejected with -ELOOP.

Fixes dbd29e075228 ("vringh: Fix loop descriptors check in the indirect cases")
Cc Xie Yongji <[email protected]>
Assisted-by Hawkeye:GLM-5.3-flash
Assisted-by Qoder:Qwen3.8-Max

Message-ID: <[email protected]>

---
 drivers/vhost/vringh.c | 22 +++++++++++-----------
 1 file changed, 11 insertions(+), 11 deletions(-)
drivers/vhost/vringh.c +11 -11
index 925858cc60964..c753a0cee240d 100644
@@ -333,6 +333,17 @@ __vringh_iov(struct vringh *vrh, u16 i,
 		if (unlikely(err))
 			goto fail;
 
+		if (up_next == -1)
+			count++;
+		else
+			indirect_count++;
+
+		if (count > vrh->vring.num || indirect_count > desc_max) {
+			vringh_bad("Descriptor loop in %p", descs);
+			err = -ELOOP;
+			goto fail;
+		}
+
 		if (unlikely(desc.flags &
 			     cpu_to_vringh16(vrh, VRING_DESC_F_INDIRECT))) {
 			u64 a = vringh64_to_cpu(vrh, desc.addr);
@@ -358,17 +369,6 @@ __vringh_iov(struct vringh *vrh, u16 i,
 			continue;
 		}
 
-		if (up_next == -1)
-			count++;
-		else
-			indirect_count++;
-
-		if (count > vrh->vring.num || indirect_count > desc_max) {
-			vringh_bad("Descriptor loop in %p", descs);
-			err = -ELOOP;
-			goto fail;
-		}
-
 		if (desc.flags & cpu_to_vringh16(vrh, VRING_DESC_F_WRITE))
 			iov = wiov;
 		else {
Signature · 1 line
2.53.0
author maintainer
#268 lore raw

PATCH 268/686 vringh: reject empty / undersized indirect descriptor tables

In reply to Greg Kroah-Hartman

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

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

From: Fang Xieyan <[email protected]>

[ Upstream commit 60a792b97933a686316737838cd007d27963011e ]

move_to_indirect() validates an indirect descriptor table only with "len % sizeof(struct vring_desc)". A descriptor flagged VRING_DESC_F_INDIRECT with len == 0 passes that test, so *desc_max is set to 0 while *descs points at the empty table. __vringh_iov() then copies one struct vring_desc from descs[0] -- 16 bytes past the end of the table -- before the "indirect_count > desc_max" loop detection aborts the walk. The over-read value is discarded when the walk aborts and is never used to map anything, but the access itself is out of bounds.

Reject any len smaller than one descriptor, alongside the existing stride check, so an empty table is refused with -EINVAL and no descriptor is ever fetched from it.

Fixes f87d0fbb5798 ("vringh: host-side implementation of virtio rings.")
Assisted-by Hawkeye:GLM-5.3-flash
Assisted-by Qoder:Qwen3.8-Max

Message-ID: <[email protected]>

---
 drivers/vhost/vringh.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/vhost/vringh.c +3 -2
index c753a0cee240d..3391413379579 100644
@@ -197,8 +197,9 @@ static int move_to_indirect(const struct vringh *vrh,
 	}
 
 	len = vringh32_to_cpu(vrh, desc->len);
-	if (unlikely(len % sizeof(struct vring_desc))) {
-		vringh_bad("Strange indirect len %u", desc->len);
+	if (unlikely(len < sizeof(struct vring_desc) ||
+		     len % sizeof(struct vring_desc))) {
+		vringh_bad("Invalid indirect len %u", desc->len);
 		return -EINVAL;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#269 lore raw

PATCH 269/686 veth: keep carrier off when resizing channels with a down peer

In reply to Greg Kroah-Hartman

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

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

From: Xia Yan <[email protected]>

[ Upstream commit 2d02191779345b13de91048db441191b20264d16 ]

veth_set_channels() temporarily turns carrier off while reconfiguring a running interface. It then turns carrier on for both ends without checking whether the peer is administratively up. If only one end is up, changing its channel counts therefore reports LOWER_UP even though the peer remains down.

For example, after creating a pair with two RX and TX queues per end:

ip link set vca up
ethtool -L vca rx 1 tx 1

vca incorrectly reports LOWER_UP while vcb is still down.

Only restore carrier when the peer has IFF_UP, matching veth_open(). The local interface is already known to be running at this point.

Found during LLM-assisted source review and reproduced with a veth pair in network namespaces, without kernel instrumentation or error injection. The companion veth.sh test reproduces the two mixed up/down failures before the fix and passes after it.

---
 drivers/net/veth.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/veth.c +3 -2
index 25cdbba5dfa9b..c2b8b9d02e357 100644
@@ -1371,9 +1371,10 @@ static int veth_set_channels(struct net_device *dev,
 		 * to identify the range we have to disable
 		 */
 		veth_disable_range_safe(dev, new_rx_count, old_rx_count);
-		netif_carrier_on(dev);
-		if (peer)
+		if (peer && (peer->flags & IFF_UP)) {
+			netif_carrier_on(dev);
 			netif_carrier_on(peer);
+		}
 	}
 
 	/* update XDP supported features */
Signature · 1 line
2.53.0
author maintainer
#270 lore raw

PATCH 270/686 hwmon: (corsair-cpro) Cache fan target only after a successful command

In reply to Greg Kroah-Hartman

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

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

From: Baek Kyu, Kim <[email protected]>

[ Upstream commit e2c26431b4e47892378582a414b4bbaa9edf1798 ]

set_target() updates the cached fan target before sending the command. If the command fails, subsequent fanN_target reads report the failed request instead of the previous value. For example, after successfully setting 1200 RPM, a rejected request for 1800 RPM returns an error but leaves fanN_target reporting 1800. A failed request also replaces -ENODATA when no target has been successfully set.

Update the target cache under the existing mutex only after send_usb_cmd() succeeds, as set_pwm() already does when invalidating the target. Preserve the previous cached value and return the original error on failure.

---
 drivers/hwmon/corsair-cpro.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/hwmon/corsair-cpro.c +2 -1
index 17bb080eb9bb6..1c152a6db3806 100644
@@ -215,10 +215,11 @@ static int set_target(struct ccp_device *ccp, int channel, long val)
 	int ret;
 
 	val = clamp_val(val, 0, 0xFFFF);
-	ccp->target[channel] = val;
 
 	mutex_lock(&ccp->mutex);
 	ret = send_usb_cmd(ccp, CTL_SET_FAN_TARGET, channel, val >> 8, val);
+	if (!ret)
+		ccp->target[channel] = val;
 
 	mutex_unlock(&ccp->mutex);
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#271 lore raw

PATCH 271/686 hwmon: (aquacomputer_d5next) reject short status reports

In reply to Greg Kroah-Hartman

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

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

From: Jiale Yao <[email protected]>

[ Upstream commit cf8f81babd2e96087dedbb74985bc1781c98f73d ]

The HID raw_event callback runs before HID core validates the received report length. aqc_raw_event() reads device-specific status fields at fixed offsets, including multi-byte values, without first ensuring that the received buffer contains every field. A truncated report can therefore cause out-of-bounds reads and update hwmon state with unrelated data.

The required length differs between supported devices and cannot be derived from the HID report descriptor. Define the minimum length needed by each asynchronous status format, select it while configuring the device, and reject reports that do not contain the last field accessed by that format. Keep the published length zero until probe configuration is complete, which also excludes legacy devices whose status is retrieved through feature reports.

Fixes 0e35f63f7f4e ("hwmon: add driver for Aquacomputer D5 Next")
Fixes 19692f17cd13 ("hwmon: (aquacomputer_d5next) Add support for Aquacomputer Aquastream XT")
---
 drivers/hwmon/aquacomputer_d5next.c | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)
drivers/hwmon/aquacomputer_d5next.c +27 -0
index 0dcb8a3a691d6..1f0e71d3b52e4 100644
@@ -133,6 +133,7 @@ static u8 aquaero_secondary_ctrl_report[] = {
 #define AQUAERO_FAN_CURRENT_OFFSET		0x06
 #define AQUAERO_FAN_POWER_OFFSET		0x08
 #define AQUAERO_FAN_SPEED_OFFSET		0x00
+#define AQUAERO_MIN_STATUS_REPORT_SIZE		(0x18B + AQUAERO_FAN_POWER_OFFSET + sizeof(u16))
 static u16 aquaero_sensor_fan_offsets[] = { 0x167, 0x173, 0x17f, 0x18B };
 
 /* Control report offsets for the Aquaero fan controllers */
@@ -156,6 +157,8 @@ static u16 aquaero_ctrl_fan_offsets[] = { 0x20c, 0x220, 0x234, 0x248 };
 #define D5NEXT_5V_VOLTAGE		0x39
 #define D5NEXT_12V_VOLTAGE		0x37
 #define D5NEXT_VIRTUAL_SENSORS_START	0x3f
+#define D5NEXT_MIN_STATUS_REPORT_SIZE	(D5NEXT_PUMP_OFFSET + AQC_FAN_SPEED_OFFSET + \
+					 sizeof(u16))
 static u16 d5next_sensor_fan_offsets[] = { D5NEXT_PUMP_OFFSET, D5NEXT_FAN_OFFSET };
 
 /* Control report offsets for the D5 Next pump */
@@ -180,11 +183,14 @@ static u16 d5next_ctrl_fan_offsets[] = { 0x97, 0x42 };	/* Pump and fan speed (fr
 #define AQUASTREAMULT_FAN_CURRENT_OFFSET	0x00
 #define AQUASTREAMULT_FAN_POWER_OFFSET		0x04
 #define AQUASTREAMULT_FAN_SPEED_OFFSET		0x06
+#define AQUASTREAMULT_MIN_STATUS_REPORT_SIZE	(AQUASTREAMULT_PRESSURE_OFFSET + sizeof(u16))
 static u16 aquastreamult_sensor_fan_offsets[] = { AQUASTREAMULT_FAN_OFFSET };
 
 /* Spec and sensor report offset for the Farbwerk RGB controller */
 #define FARBWERK_NUM_SENSORS		4
 #define FARBWERK_SENSOR_START		0x2f
+#define FARBWERK_MIN_STATUS_REPORT_SIZE	(FARBWERK_SENSOR_START + \
+					 FARBWERK_NUM_SENSORS * AQC_SENSOR_SIZE)
 
 /* Specs of the Farbwerk 360 RGB controller */
 #define FARBWERK360_NUM_SENSORS			4
@@ -194,6 +200,8 @@ static u16 aquastreamult_sensor_fan_offsets[] = { AQUASTREAMULT_FAN_OFFSET };
 /* Sensor report offsets for the Farbwerk 360 */
 #define FARBWERK360_SENSOR_START		0x32
 #define FARBWERK360_VIRTUAL_SENSORS_START	0x3a
+#define FARBWERK360_MIN_STATUS_REPORT_SIZE	(FARBWERK360_VIRTUAL_SENSORS_START + \
+					 FARBWERK360_NUM_VIRTUAL_SENSORS * AQC_SENSOR_SIZE)
 
 /* Control report offsets for the Farbwerk 360 */
 #define FARBWERK360_TEMP_CTRL_OFFSET		0x8
@@ -210,6 +218,7 @@ static u16 aquastreamult_sensor_fan_offsets[] = { AQUASTREAMULT_FAN_OFFSET };
 #define OCTO_SENSOR_START		0x3D
 #define OCTO_VIRTUAL_SENSORS_START	0x45
 #define OCTO_FLOW_SENSOR_OFFSET		0x7B
+#define OCTO_MIN_STATUS_REPORT_SIZE	(0xD8 + AQC_FAN_SPEED_OFFSET + sizeof(u16))
 static u16 octo_sensor_fan_offsets[] = { 0x7D, 0x8A, 0x97, 0xA4, 0xB1, 0xBE, 0xCB, 0xD8 };
 
 /* Control report offsets for the Octo */
@@ -230,6 +239,7 @@ static u16 octo_ctrl_fan_offsets[] = { 0x5B, 0xB0, 0x105, 0x15A, 0x1AF, 0x204, 0
 #define QUADRO_SENSOR_START		0x34
 #define QUADRO_VIRTUAL_SENSORS_START	0x3c
 #define QUADRO_FLOW_SENSOR_OFFSET	0x6e
+#define QUADRO_MIN_STATUS_REPORT_SIZE	(0x97 + AQC_FAN_SPEED_OFFSET + sizeof(u16))
 static u16 quadro_sensor_fan_offsets[] = { 0x70, 0x7D, 0x8A, 0x97 };
 
 /* Control report offsets for the Quadro */
@@ -249,6 +259,7 @@ static u16 quadro_ctrl_fan_offsets[] = { 0x37, 0x8c, 0xe1, 0x136 }; /* Fan speed
 #define HIGHFLOWNEXT_CONDUCTIVITY	95
 #define HIGHFLOWNEXT_5V_VOLTAGE		97
 #define HIGHFLOWNEXT_5V_VOLTAGE_USB	99
+#define HIGHFLOWNEXT_MIN_STATUS_REPORT_SIZE	(HIGHFLOWNEXT_5V_VOLTAGE_USB + sizeof(u16))
 
 /* Specs of the Leakshield */
 #define LEAKSHIELD_NUM_SENSORS		2
@@ -264,6 +275,7 @@ static u16 quadro_ctrl_fan_offsets[] = { 0x37, 0x8c, 0xe1, 0x136 }; /* Fan speed
 #define LEAKSHIELD_FLOW_IN		111
 #define LEAKSHIELD_RESERVOIR_VOLUME	313
 #define LEAKSHIELD_RESERVOIR_FILLED	311
+#define LEAKSHIELD_MIN_STATUS_REPORT_SIZE	(LEAKSHIELD_RESERVOIR_VOLUME + sizeof(u16))
 
 /* Specs of the Aquastream XT pump */
 #define AQUASTREAMXT_SERIAL_START		0x3a
@@ -556,6 +568,7 @@ struct aqc_data {
 	const char *name;
 
 	int status_report_id;	/* Used for legacy devices, report is stored in buffer */
+	u16 min_report_size;
 	int ctrl_report_id;
 	int secondary_ctrl_report_id;
 	int secondary_ctrl_report_size;
@@ -1356,6 +1369,8 @@ static int aqc_raw_event(struct hid_device *hdev, struct hid_report *report, u8
 		return 0;
 
 	priv = hid_get_drvdata(hdev);
+	if (!priv->min_report_size || size < priv->min_report_size)
+		return 0;
 
 	/* Info provided with every report */
 	priv->serial_number[0] = get_unaligned_be16(data + priv->serial_number_start_offset);
@@ -1541,6 +1556,7 @@ static void aqc_debugfs_init(struct aqc_data *priv)
 static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 {
 	struct aqc_data *priv;
+	u16 min_report_size = 0;
 	int ret;
 
 	priv = devm_kzalloc(&hdev->dev, sizeof(*priv), GFP_KERNEL);
@@ -1608,6 +1624,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 		priv->power_label = label_fan_power;
 		priv->voltage_label = label_fan_voltage;
 		priv->current_label = label_fan_current;
+		min_report_size = AQUAERO_MIN_STATUS_REPORT_SIZE;
 		break;
 	case USB_PRODUCT_ID_D5NEXT:
 		priv->kind = d5next;
@@ -1633,6 +1650,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 		priv->power_label = label_d5next_power;
 		priv->voltage_label = label_d5next_voltages;
 		priv->current_label = label_d5next_current;
+		min_report_size = D5NEXT_MIN_STATUS_REPORT_SIZE;
 		break;
 	case USB_PRODUCT_ID_FARBWERK:
 		priv->kind = farbwerk;
@@ -1643,6 +1661,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 		priv->temp_sensor_start_offset = FARBWERK_SENSOR_START;
 
 		priv->temp_label = label_temp_sensors;
+		min_report_size = FARBWERK_MIN_STATUS_REPORT_SIZE;
 		break;
 	case USB_PRODUCT_ID_FARBWERK360:
 		priv->kind = farbwerk360;
@@ -1659,6 +1678,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 
 		priv->temp_label = label_temp_sensors;
 		priv->virtual_temp_label = label_virtual_temp_sensors;
+		min_report_size = FARBWERK360_MIN_STATUS_REPORT_SIZE;
 		break;
 	case USB_PRODUCT_ID_OCTO:
 		priv->kind = octo;
@@ -1688,6 +1708,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 		priv->power_label = label_fan_power;
 		priv->voltage_label = label_fan_voltage;
 		priv->current_label = label_fan_current;
+		min_report_size = OCTO_MIN_STATUS_REPORT_SIZE;
 		break;
 	case USB_PRODUCT_ID_QUADRO:
 		priv->kind = quadro;
@@ -1717,6 +1738,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 		priv->power_label = label_fan_power;
 		priv->voltage_label = label_fan_voltage;
 		priv->current_label = label_fan_current;
+		min_report_size = QUADRO_MIN_STATUS_REPORT_SIZE;
 		break;
 	case USB_PRODUCT_ID_HIGHFLOWNEXT:
 		priv->kind = highflownext;
@@ -1734,6 +1756,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 		priv->speed_label = label_highflownext_fan_speed;
 		priv->power_label = label_highflownext_power;
 		priv->voltage_label = label_highflownext_voltage;
+		min_report_size = HIGHFLOWNEXT_MIN_STATUS_REPORT_SIZE;
 		break;
 	case USB_PRODUCT_ID_LEAKSHIELD:
 		/*
@@ -1753,6 +1776,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 
 		priv->temp_label = label_leakshield_temp_sensors;
 		priv->speed_label = label_leakshield_fan_speed;
+		min_report_size = LEAKSHIELD_MIN_STATUS_REPORT_SIZE;
 		break;
 	case USB_PRODUCT_ID_AQUASTREAMXT:
 		priv->kind = aquastreamxt;
@@ -1783,6 +1807,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 		priv->power_label = label_aquastreamult_power;
 		priv->voltage_label = label_aquastreamult_voltages;
 		priv->current_label = label_aquastreamult_current;
+		min_report_size = AQUASTREAMULT_MIN_STATUS_REPORT_SIZE;
 		break;
 	case USB_PRODUCT_ID_POWERADJUST3:
 		priv->kind = poweradjust3;
@@ -1856,6 +1881,8 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 		break;
 	}
 
+	priv->min_report_size = min_report_size;
+
 	if (priv->buffer_size != 0) {
 		priv->checksum_start = 0x01;
 		priv->checksum_length = priv->buffer_size - 3;
Signature · 1 line
2.53.0
author maintainer
#272 lore raw

PATCH 272/686 hwmon: chipcap2: fix command error diagnostics

In reply to Greg Kroah-Hartman

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

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

From: Javier Carrasco <[email protected]>

[ Upstream commit d0a03e1a2d9bd53b94fe6dff7a1a8058d25be82d ]

The command response field only contains bits 1:0, while the error flags are stored in bits 2:5. The existing diagnostic checks test the extracted response field, so they can never report an error flag.

Test the full status byte for the error flags, and check the configuration-load flag instead of RAM parity for the last diagnostic.

Fixes 3af350929e75 ("hwmon: Add support for Amphenol ChipCap 2")
---
 drivers/hwmon/chipcap2.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/hwmon/chipcap2.c +4 -4
index 0e182454779e0..b3d944852e73a 100644
@@ -165,13 +165,13 @@ static int cc2_cmd_response_diagnostic(struct device *dev, u8 status)
 	case CC2_RESPONSE_BUSY:
 		return -EBUSY;
 	case CC2_RESPONSE_NACK:
-		if (resp & CC2_ERR_CORR_EEPROM)
+		if (status & CC2_ERR_CORR_EEPROM)
 			dev_dbg(dev, "Command failed: corrected EEPROM\n");
-		if (resp & CC2_ERR_UNCORR_EEPROM)
+		if (status & CC2_ERR_UNCORR_EEPROM)
 			dev_dbg(dev, "Command failed: uncorrected EEPROM\n");
-		if (resp & CC2_ERR_RAM_PARITY)
+		if (status & CC2_ERR_RAM_PARITY)
 			dev_dbg(dev, "Command failed: RAM parity\n");
-		if (resp & CC2_ERR_RAM_PARITY)
+		if (status & CC2_ERR_CONFIG_LOAD)
 			dev_dbg(dev, "Command failed: configuration error\n");
 		return -ENODATA;
 	default:
Signature · 1 line
2.53.0
author maintainer
#273 lore raw

PATCH 273/686 hwmon: chipcap2: fix off-by-one in command mode retry loop

In reply to Greg Kroah-Hartman

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

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

From: Javier Carrasco <[email protected]>

[ Upstream commit 4c0e65a4ed665c416ccb1524c58a646a580e491f ]

i == CC2_CM_RETRIES can never be true inside the loop, since it only runs while i < CC2_CM_RETRIES. Use CC2_CM_RETRIES - 1 so the last failed retry breaks out immediately instead of doing a useless disable + 80 ms power-cycle delay before the loop condition ends it anyway.

Fixes 3af350929e75 ("hwmon: Add support for Amphenol ChipCap 2")
---
 drivers/hwmon/chipcap2.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/chipcap2.c +1 -1
index b3d944852e73a..c5b6e147467cf 100644
@@ -224,7 +224,7 @@ static int cc2_command_mode_start(struct cc2_data *data)
 				     2 * CC2_RESP_START_CM_US);
 		}
 		ret = cc2_read_command_status(data->client);
-		if (ret != -ETIMEDOUT || i == CC2_CM_RETRIES)
+		if (ret != -ETIMEDOUT || i == CC2_CM_RETRIES - 1)
 			break;
 
 		/* command window missed, prepare for a retry */
Signature · 1 line
2.53.0
author maintainer
#274 lore raw

PATCH 274/686 hwmon: chipcap2: fix be16 handling

In reply to Greg Kroah-Hartman

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

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

From: Javier Carrasco <[email protected]>

[ Upstream commit 36b07ddfe20b0fe06a8bc32c5e09974876fb5e42 ]

The driver currently only works correctly on little-endian architectures when writing 16-bit register values.

Use i2c_smbus_write_word_swapped() for writes and get_unaligned_be16() for reads to correctly handle the ChipCap 2's big-endian data format on all architectures.

Fixes 3af350929e75 ("hwmon: Add support for Amphenol ChipCap 2")
---
 drivers/hwmon/chipcap2.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/hwmon/chipcap2.c +5 -5
index c5b6e147467cf..b7b59ca4a4f9d 100644
@@ -21,6 +21,7 @@
 #include <linux/interrupt.h>
 #include <linux/irq.h>
 #include <linux/module.h>
+#include <linux/unaligned.h>
 #include <linux/regulator/consumer.h>
 
 #define CC2_START_CM			0xA0
@@ -258,8 +259,7 @@ static int cc2_write_reg(struct cc2_data *data, u8 reg, u16 val)
 	if (ret < 0)
 		goto disable;
 
-	cpu_to_be16s(&val);
-	ret = i2c_smbus_write_word_data(data->client, reg, val);
+	ret = i2c_smbus_write_word_swapped(data->client, reg, val);
 	if (ret < 0)
 		goto disable;
 
@@ -309,7 +309,7 @@ static int cc2_read_reg(struct cc2_data *data, u8 reg, u16 *val)
 	if (ret != CC2_EEPROM_DATA_LEN)
 		return ret < 0 ? ret : -EIO;
 
-	*val = be16_to_cpup((__be16 *)&buf[1]);
+	*val = get_unaligned_be16(&buf[1]);
 
 	return cc2_read_command_status(data->client);
 }
@@ -349,10 +349,10 @@ static int cc2_data_fetch(struct i2c_client *client,
 
 	switch (type) {
 	case hwmon_humidity:
-		*val = cc2_rh_convert(be16_to_cpup((__be16 *)&data[0]));
+		*val = cc2_rh_convert(get_unaligned_be16(&data[0]));
 		break;
 	case hwmon_temp:
-		*val = cc2_temp_convert(be16_to_cpup((__be16 *)&data[2]));
+		*val = cc2_temp_convert(get_unaligned_be16(&data[2]));
 		break;
 	default:
 		return -EINVAL;
Signature · 1 line
2.53.0
author maintainer
#275 lore raw

PATCH 275/686 hwmon: chipcap2: defer probe when IRQs are unavailable

In reply to Greg Kroah-Hartman

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

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

From: Javier Carrasco <[email protected]>

[ Upstream commit b5a1412618f93b594f924cf4f3b4bb6b5dc49d41 ]

This device can work with or without interrupts, but if they are provided and still not available, but if -EPROBE_DEFER is read, its value must be propagated to enable probe retries.

Fixes 3af350929e75 ("hwmon: Add support for Amphenol ChipCap 2")
---
 drivers/hwmon/chipcap2.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/hwmon/chipcap2.c +6 -0
index b7b59ca4a4f9d..34c3e26211458 100644
@@ -624,6 +624,8 @@ static int cc2_request_ready_irq(struct cc2_data *data, struct device *dev)
 	int ret = 0;
 
 	data->irq_ready = fwnode_irq_get_byname(dev_fwnode(dev), "ready");
+	if (data->irq_ready == -EPROBE_DEFER)
+		return data->irq_ready;
 	if (data->irq_ready > 0) {
 		init_completion(&data->complete);
 		ret = devm_request_threaded_irq(dev, data->irq_ready, NULL,
@@ -641,6 +643,8 @@ static int cc2_request_alarm_irqs(struct cc2_data *data, struct device *dev)
 	int ret = 0;
 
 	data->irq_low = fwnode_irq_get_byname(dev_fwnode(dev), "low");
+	if (data->irq_low == -EPROBE_DEFER)
+		return data->irq_low;
 	if (data->irq_low > 0) {
 		ret = devm_request_threaded_irq(dev, data->irq_low, NULL,
 						cc2_low_interrupt,
@@ -654,6 +658,8 @@ static int cc2_request_alarm_irqs(struct cc2_data *data, struct device *dev)
 	}
 
 	data->irq_high = fwnode_irq_get_byname(dev_fwnode(dev), "high");
+	if (data->irq_high == -EPROBE_DEFER)
+		return data->irq_high;
 	if (data->irq_high > 0) {
 		ret = devm_request_threaded_irq(dev, data->irq_high, NULL,
 						cc2_high_interrupt,
Signature · 1 line
2.53.0
author maintainer
#276 lore raw

PATCH 276/686 hwmon: chipcap2: enable IRQ processing when regulator is already enabled

In reply to Greg Kroah-Hartman

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

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

From: Javier Carrasco <[email protected]>

[ Upstream commit d1ce827a9cc11ffdfec77b7fec9b73a8020a308d ]

cc2_enable() returns early when the regulator is already enabled. This can happen if a previous regulator_disable() failed or if the regulator was configured as always-on.

In this case, process_irqs remains false, causing the ready interrupt to be ignored. Subsequent operations waiting for the ready completion then time out.

Set process_irqs before returning when the regulator is already enabled, so that the driver continues to process ready interrupts.

Fixes 3af350929e75 ("hwmon: Add support for Amphenol ChipCap 2")
---
 drivers/hwmon/chipcap2.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/hwmon/chipcap2.c +3 -1
index 34c3e26211458..632efe64f190a 100644
@@ -118,8 +118,10 @@ static int cc2_enable(struct cc2_data *data)
 	int ret;
 
 	/* exclusive regulator, check in case a disable failed */
-	if (regulator_is_enabled(data->regulator))
+	if (regulator_is_enabled(data->regulator)) {
+		data->process_irqs = true;
 		return 0;
+	}
 
 	/* clear any pending completion */
 	try_wait_for_completion(&data->complete);
Signature · 1 line
2.53.0
author maintainer
#277 lore raw

PATCH 277/686 hwmon: chipcap2: balance regulator state

In reply to Greg Kroah-Hartman

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

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

From: Javier Carrasco <[email protected]>

[ Upstream commit 378add65fd7d352de9fe440d167fde5bf511b090 ]

The current implementation does not guarantee that the calls to regulator_enable() and regulator_disable() are balanced. regulator_is_enabled() might return a negative value, and an always-on attribute in the DT might break the symmetry anyway.

Add a regulator_enabled flag to keep balance within this regulator consumer.

Fixes 3af350929e75 ("hwmon: Add support for Amphenol ChipCap 2")
---
 drivers/hwmon/chipcap2.c | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)
drivers/hwmon/chipcap2.c +13 -5
index 632efe64f190a..3e8218a7ff2ad 100644
@@ -89,6 +89,7 @@ struct cc2_data {
 	int irq_low;
 	int irq_high;
 	bool process_irqs;
+	bool regulator_enabled;
 };
 
 /* %RH as a per cent mille from a register value */
@@ -118,7 +119,7 @@ static int cc2_enable(struct cc2_data *data)
 	int ret;
 
 	/* exclusive regulator, check in case a disable failed */
-	if (regulator_is_enabled(data->regulator)) {
+	if (data->regulator_enabled) {
 		data->process_irqs = true;
 		return 0;
 	}
@@ -130,6 +131,8 @@ static int cc2_enable(struct cc2_data *data)
 	if (ret < 0)
 		return ret;
 
+	data->regulator_enabled = true;
+
 	usleep_range(CC2_STARTUP_TIME_US, CC2_STARTUP_TIME_US + 125);
 
 	data->process_irqs = true;
@@ -145,11 +148,16 @@ static void cc2_disable(struct cc2_data *data)
 	data->process_irqs = false;
 
 	/* exclusive regulator, check in case an enable failed */
-	if (regulator_is_enabled(data->regulator)) {
-		err = regulator_disable(data->regulator);
-		if (err)
-			dev_dbg(&data->client->dev, "Failed to disable device");
+	if (!data->regulator_enabled)
+		return;
+
+	err = regulator_disable(data->regulator);
+	if (err) {
+		dev_dbg(&data->client->dev, "Failed to disable device");
+		return;
 	}
+
+	data->regulator_enabled = false;
 }
 
 static int cc2_cmd_response_diagnostic(struct device *dev, u8 status)
Signature · 1 line
2.53.0
author maintainer
#278 lore raw

PATCH 278/686 hwmon: chipcap2: do not discard pending alarms on disable

In reply to Greg Kroah-Hartman

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

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

From: Javier Carrasco <[email protected]>

[ Upstream commit 22aecf164e1c0c849808c342c65322d14f45176f ]

cc2_disable() stops processing interrupts before the device is powered down to ignore the alarms caused by voltage toggling. The handler of an alarm raised by the last measurement might not have run at that point, and the alarm is discarded when it finally does.

The sysfs read that triggered the measurement can then report no alarm although the device raised one.

Wait for the alarm handlers that have already been raised before the interrupt processing is stopped. This covers the case where the handler thread has not been scheduled yet; an alarm that has not reached the interrupt core at that point is discarded.

Fixes 3af350929e75 ("hwmon: Add support for Amphenol ChipCap 2")
---
 drivers/hwmon/chipcap2.c | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/hwmon/chipcap2.c +7 -0
index 3e8218a7ff2ad..5f4b0fd535af8 100644
@@ -144,6 +144,13 @@ static void cc2_disable(struct cc2_data *data)
 {
 	int err;
 
+	/* let the alarms already raised by the last measurement be processed */
+	if (data->irq_low > 0)
+		synchronize_irq(data->irq_low);
+
+	if (data->irq_high > 0)
+		synchronize_irq(data->irq_high);
+
 	/* ignore alarms triggered by voltage toggling when powering up */
 	data->process_irqs = false;
 
Signature · 1 line
2.53.0
author maintainer
#279 lore raw

PATCH 279/686 hwmon: (aquacomputer_d5next) Check maxcollection when probing AQUAERO devices

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit b7743c6dbe3ab94045164ef298f65cfb9b0b450a ]

When a USB HID device matching USB_PRODUCT_ID_AQUAERO presents a malformed report descriptor, an out-of-bounds array access occurs in aqc_probe() due to an unchecked index into the parsed collections array. During device initialization, the driver distinguishes between the multiple logical interfaces exposed by the Aquaero device by evaluating the type of the second element in the collection array. The driver unconditionally accesses hdev->collection[1] without verifying that hdev->maxcollection is greater than 1. Because the collection array is dynamically allocated by the HID core based on the number of collections found in the report descriptor, a crafted device exposing fewer than two collections causes an immediate heap out-of-bounds read or NULL pointer dereference. This leads to a kernel panic during the device probe phase.

Add the missing check to fix the problem.

Fixes 2c55211104b4 ("hwmon: (aquacomputer_d5next) Support sensors for Aquacomputer Aquaero")
Cc Aleksa Savic <[email protected]>
Cc Jack Doan <[email protected]>
---
 drivers/hwmon/aquacomputer_d5next.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/aquacomputer_d5next.c +1 -1
index 1f0e71d3b52e4..e0052ba4702c6 100644
@@ -1593,7 +1593,7 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id)
 		 * they present. The two other devices have the type of the second element in
 		 * their respective collections set to 1, while the real device has it set to 0.
 		 */
-		if (hdev->collection[1].type != 0) {
+		if (hdev->maxcollection < 2 || hdev->collection[1].type != 0) {
 			ret = -ENODEV;
 			goto fail_and_close;
 		}
Signature · 1 line
2.53.0
author maintainer
#280 lore raw

PATCH 280/686 hwmon: (asus_wmi_sensors) Avoid global struct mutation

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 59d586c9e47d1205563bc9b5a5d443adc3ba5bc5 ]

In the asus_wmi_sensors driver, device-managed memory allocated in asus_wmi_configure_sensor_setup() is assigned to a global static structure, leading to a potential use-after-free when the device is unbound. The driver defines a single global asus_wmi_chip_info structure to register with the hwmon core. During probe, it dynamically allocates the .info channel array using devm_kcalloc() and assigns it directly to this global structure. When a device is unbound, its device-managed memory is automatically freed, leaving asus_wmi_chip_info.info as a dangling pointer. Furthermore, if multiple WMI devices are probed sequentially, each probe overwrites the same global pointer, forcing all registered hwmon instances to reference the channel information of the most recently probed device.

While it is unlikely if not impossible that multiple WMI devices of the same kind exist, modifying a global static data structure is undesirable. Remove the static data structure and allocate it as part of struct asus_wmi_sensors to avoid the potential problem.

Fixes 548820e21ce1 ("hwmon: (asus_wmi_sensors) Support X370 Asus WMI.")
Cc Ed Brindley <[email protected]>
Cc Denis Pauk <[email protected]>
---
 drivers/hwmon/asus_wmi_sensors.c | 13 +++++--------
 1 file changed, 5 insertions(+), 8 deletions(-)
drivers/hwmon/asus_wmi_sensors.c +5 -8
index c2dd7ff882f24..502996e97cf14 100644
@@ -164,6 +164,7 @@ struct asus_wmi_wmi_info {
 
 struct asus_wmi_sensors {
 	struct asus_wmi_wmi_info wmi;
+	struct hwmon_chip_info chip_info;
 	/* lock access to internal cache */
 	struct mutex lock;
 };
@@ -496,11 +497,6 @@ static const struct hwmon_ops asus_wmi_hwmon_ops = {
 	.read_string = asus_wmi_hwmon_read_string,
 };
 
-static struct hwmon_chip_info asus_wmi_chip_info = {
-	.ops = &asus_wmi_hwmon_ops,
-	.info = NULL,
-};
-
 static int asus_wmi_configure_sensor_setup(struct device *dev,
 					   struct asus_wmi_sensors *sensor_data)
 {
@@ -508,7 +504,7 @@ static int asus_wmi_configure_sensor_setup(struct device *dev,
 	struct hwmon_channel_info *asus_wmi_hwmon_chan;
 	int nr_count[hwmon_max] = {}, nr_types = 0;
 	struct asus_wmi_sensor_info *temp_sensor;
-	const struct hwmon_chip_info *chip_info;
+	struct hwmon_chip_info *chip_info;
 	enum hwmon_sensor_types type;
 	struct device *hwdev;
 	int i, idx;
@@ -549,8 +545,9 @@ static int asus_wmi_configure_sensor_setup(struct device *dev,
 	if (!ptr_asus_wmi_ci)
 		return -ENOMEM;
 
-	asus_wmi_chip_info.info = ptr_asus_wmi_ci;
-	chip_info = &asus_wmi_chip_info;
+	chip_info = &sensor_data->chip_info;
+	chip_info->ops = &asus_wmi_hwmon_ops;
+	chip_info->info = ptr_asus_wmi_ci;
 
 	sensor_data->wmi.info_by_id = devm_kcalloc(dev, sensor_data->wmi.sensor_count,
 						   sizeof(*sensor_data->wmi.info_by_id),
Signature · 1 line
2.53.0
author maintainer
#281 lore raw

PATCH 281/686 hwmon: (hp-wmi-sensors) Avoid global struct mutation

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit dc992efeace99e479aec7a8f0c49a9493c729606 ]

In the HP WMI sensors driver, make_chip_info() assigns a device-managed memory allocation to a static global structure, resulting in a use-after-free when the device unbinds.
During hp_wmi_sensors_probe(), make_chip_info() dynamically allocates a hwmon_channel_info array using devm_kcalloc() and assigns it to the static global hp_wmi_chip_info.info pointer.

If multiple instances probe sequentially or concurrently, the shared global pointer is overwritten by each new device. When any device unbinds, its devm-managed memory is automatically freed, leaving the global hp_wmi_chip_info struct and any other active device instances with a dangling pointer. Subsequent accesses by the hwmon core (such as thermal zone reads) will dereference this freed memory, causing a use-after-free.

While this is not supposed to happen in the real world (there should only be one instance of the driver in any system), modifying global structures is undesirable and should be avoided whenever possible. Allocate struct hwmon_chip_info as part of struct hp_wmi_sensors instead and initialize it in make_chip_info() to avoid mutating the global structure.

Fixes 23902f98f8d4 ("hwmon: add HP WMI Sensors driver")
Cc James Seo <[email protected]>
---
 drivers/hwmon/hp-wmi-sensors.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
drivers/hwmon/hp-wmi-sensors.c +4 -7
index cfa0d6ad0fb3f..dd1fa48314a54 100644
@@ -390,6 +390,7 @@ struct hp_wmi_info {
  */
 struct hp_wmi_sensors {
 	struct wmi_device *wdev;
+	struct hwmon_chip_info chip_info;
 	struct hp_wmi_info **info_map[hwmon_max];
 	u8 channel_count[hwmon_max];
 	bool has_intrusion;
@@ -1531,11 +1532,6 @@ static const struct hwmon_ops hp_wmi_hwmon_ops = {
 	.write	     = hp_wmi_hwmon_write,
 };
 
-static struct hwmon_chip_info hp_wmi_chip_info = {
-	.ops         = &hp_wmi_hwmon_ops,
-	.info        = NULL,
-};
-
 static struct hp_wmi_info *match_fan_event(struct hp_wmi_sensors *state,
 					   const char *event_description)
 {
@@ -1962,7 +1958,8 @@ static int make_chip_info(struct hp_wmi_sensors *state, bool has_events)
 	if (!ptr_channel_info)
 		return -ENOMEM;
 
-	hp_wmi_chip_info.info = ptr_channel_info;
+	state->chip_info.ops = &hp_wmi_hwmon_ops;
+	state->chip_info.info = ptr_channel_info;
 
 	for (type = hwmon_chip; type < hwmon_max; type++) {
 		count = channel_count[type];
@@ -2053,7 +2050,7 @@ static int hp_wmi_sensors_init(struct hp_wmi_sensors *state)
 		return err;
 
 	hwdev = devm_hwmon_device_register_with_info(dev, "hp_wmi_sensors",
-						     state, &hp_wmi_chip_info,
+						     state, &state->chip_info,
 						     NULL);
 	return PTR_ERR_OR_ZERO(hwdev);
 }
Signature · 1 line
2.53.0
author maintainer
#282 lore raw

PATCH 282/686 hwmon: (hp-wmi-sensors) Fix unbounded loops in scale_numeric_sensor()

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 185039b1c0389b70ec52a6d3e3c1494e2d0e23da ]

In scale_numeric_sensor() in the hp-wmi-sensors hwmon driver, an unbounded loop occurs if the ACPI WMI implementation provides a highly anomalous or malformed UnitModifier value for a numeric sensor.
The UnitModifier property is extracted from a WMI ACPI object without bounds checking and cast to a signed 32-bit integer. This value directly controls the iteration count of two scaling loops. If the provided unit_modifier is extremely negative (e.g., INT_MIN), the first loop executes billions of times before reaching target_modifier. Conversely, if unit_modifier is extremely large (e.g., INT_MAX) and the current sensor reading (val) is exactly 0, the second loop's overflow safeguard (val > LONG_MAX / 10) never evaluates to true, resulting in billions of unnecessary iterations. This prolonged execution causes severe CPU stalls and thread soft lockups during driver initialization or whenever a user-space process reads the sensor attribute via sysfs, resulting in a denial of service on the affected CPU core.

Fix the problem in the first loop by exiting it as soon as val is zero. Fix the problem with the second loop by only entering it if val is not zero. Also add a check for val < LONG_MIN / 10 and exit the loop if that is the case.

Fixes 23902f98f8d4 ("hwmon: add HP WMI Sensors driver")
Cc James Seo <[email protected]>
---
 drivers/hwmon/hp-wmi-sensors.c | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)
drivers/hwmon/hp-wmi-sensors.c +12 -6
index dd1fa48314a54..12950666c9810 100644
@@ -739,15 +739,21 @@ static long scale_numeric_sensor(const struct hp_wmi_numeric_sensor *nsensor)
 
 	val = current_reading;
 
-	for (; unit_modifier < target_modifier; unit_modifier++)
+	for (; val && unit_modifier < target_modifier; unit_modifier++)
 		val = DIV_ROUND_CLOSEST(val, 10);
 
-	for (; unit_modifier > target_modifier; unit_modifier--) {
-		if (val > LONG_MAX / 10) {
-			val = LONG_MAX;
-			break;
+	if (val) {
+		for (; unit_modifier > target_modifier; unit_modifier--) {
+			if (val > LONG_MAX / 10) {
+				val = LONG_MAX;
+				break;
+			}
+			if (val < LONG_MIN / 10) {
+				val = LONG_MIN;
+				break;
+			}
+			val *= 10;
 		}
-		val *= 10;
 	}
 
 	if (sensor_type == HP_WMI_TYPE_TEMPERATURE) {
Signature · 1 line
2.53.0
author maintainer
#283 lore raw

PATCH 283/686 hwmon: (lm87) Fix drvdata type confusion in vrm_show() and vrm_store()

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 5b51ff0887b9f88d042b92dd07fcdda4132f0ebc ]

When an LM87 or ADM1024 device is probed with VID support enabled, reading from or writing to the vrm sysfs attribute triggers a driver data type confusion in vrm_show() and vrm_store() in drivers/hwmon/lm87.c.

In lm87_probe(), the driver stores the struct lm87_data pointer on the I2C client via i2c_set_clientdata() and passes the struct i2c_client pointer as the drvdata argument to devm_hwmon_device_register_with_groups(), which attaches the attribute groups to the registered hwmon device with client as its driver_data. Unlike the other sysfs callbacks that retrieve client via dev_get_drvdata() and then obtain data via i2c_get_clientdata(), vrm_show() and vrm_store() assign dev_get_drvdata(dev) directly to struct lm87_data *. Dereferencing data->vrm therefore accesses the struct i2c_client instance at offsetof(struct lm87_data, vrm), causing vrm_show() to leak an unrelated byte from struct i2c_client to userspace and vrm_store() to corrupt a byte within struct i2c_client while failing to update the actual VRM value.

Fix the problem by assigning the return value from dev_get_drvdata(dev) to struct i2c_client *client and using i2c_get_clientdata() to get the actual client data.

Fixes 00a0c905ab4b ("hwmon: (lm87) Use hwmon to create the sysfs groups")
---
 drivers/hwmon/lm87.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/hwmon/lm87.c +5 -2
index d2d970e73c616..bdd633feb2ba8 100644
@@ -600,13 +600,16 @@ static DEVICE_ATTR_RO(cpu0_vid);
 static ssize_t vrm_show(struct device *dev, struct device_attribute *attr,
 			char *buf)
 {
-	struct lm87_data *data = dev_get_drvdata(dev);
+	struct i2c_client *client = dev_get_drvdata(dev);
+	struct lm87_data *data = i2c_get_clientdata(client);
+
 	return sprintf(buf, "%d\n", data->vrm);
 }
 static ssize_t vrm_store(struct device *dev, struct device_attribute *attr,
 			 const char *buf, size_t count)
 {
-	struct lm87_data *data = dev_get_drvdata(dev);
+	struct i2c_client *client = dev_get_drvdata(dev);
+	struct lm87_data *data = i2c_get_clientdata(client);
 	unsigned long val;
 	int err;
 
Signature · 1 line
2.53.0
author maintainer
#284 lore raw

PATCH 284/686 hwmon: (nct6683) Fix incorrect struct cast in show_pwm() and store_pwm()

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit c4a01c2a80b203ab5f80885f6994346fe217f19c ]

On big-endian architectures, reading or writing the pwm[1-8] sysfs attributes in the nct6683 hardware monitoring driver always redirects to channel 0 due to an incorrect struct downcast in show_pwm() and store_pwm().
The driver defines the PWM sysfs attributes using SENSOR_TEMPLATE(), which initializes them as struct sensor_device_attribute (where the index is a 32-bit int). However, the sysfs callbacks show_pwm() and store_pwm() incorrectly downcast the attribute to a struct sensor_device_attribute_2 (where the index is an 8-bit u8). Because both structs start with struct device_attribute, container_of() resolves to the same base address. On big-endian architectures, reading the 8-bit index field from the memory layout of a 32-bit int fetches the most significant byte (which is 0), rather than the intended channel number.
This type mismatch causes all PWM reads to return data for channel 0, and any writes intended to configure other channels will silently overwrite the duty cycle of PWM channel 0 instead.

Fix the type casts in show_pwm() and store_pwm() to solve the problem.

Fixes 41082d66bfd6 ("hwmon: Driver for NCT6683D")
---
 drivers/hwmon/nct6683.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hwmon/nct6683.c +2 -2
index 4a83804140386..05fc440f417c8 100644
@@ -918,7 +918,7 @@ static ssize_t
 show_pwm(struct device *dev, struct device_attribute *attr, char *buf)
 {
 	struct nct6683_data *data = nct6683_update_device(dev);
-	struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr);
+	struct sensor_device_attribute *sattr = to_sensor_dev_attr(attr);
 	int index = sattr->index;
 
 	return sprintf(buf, "%d\n", data->pwm[index]);
@@ -928,7 +928,7 @@ static ssize_t
 store_pwm(struct device *dev, struct device_attribute *attr, const char *buf,
 	  size_t count)
 {
-	struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr);
+	struct sensor_device_attribute *sattr = to_sensor_dev_attr(attr);
 	struct nct6683_data *data = dev_get_drvdata(dev);
 	int index = sattr->index;
 	unsigned long val;
Signature · 1 line
2.53.0
author maintainer
#285 lore raw

PATCH 285/686 hwmon: (peci/dimmtemp) Fix devres leak and UAF on concurrent unbind

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 61bc4514b8e99e9733c04de028885f6fc906d628 ]

When a peci_dimmtemp device is unbound concurrently with its delayed initialization work (detect_work), newly allocated devm resources and the hwmon device are leaked, leading to a use-after-free when reading the lingering hwmon sysfs attributes.

In peci_dimmtemp_probe(), detect_work is registered for cancellation via devm_delayed_work_autocancel(). During driver detach, devres_release_all() first moves all existing entries from dev->devres_head onto a local todo list before invoking their release callbacks in reverse order. If create_dimm_temp_info_delayed() is already running when devm_delayed_work_drop() calls cancel_delayed_work_sync(), create_dimm_temp_info() can allocate dimmtemp_label strings via devm_kzalloc()/devm_kasprintf() and register the hwmon device via devm_hwmon_device_register_with_info(), appending new devres entries to the now-empty dev->devres_head. Once the work finishes, devres_release_all() frees priv and priv->name from the local todo list without re-evaluating dev->devres_head, leaving the late devres allocations and registered hwmon device behind with a dangling priv pointer.

Cancel detect_work synchronously in a driver .remove() callback instead of relying on devm_delayed_work_autocancel() so that the work is fully drained before devres_release_all() detaches dev->devres_head, allowing any devm resources registered by the delayed work to be released in proper reverse order. Also only schedule detect_work when check_populated_dimms() returns -EAGAIN so that probe failure paths do not leave delayed work pending.

Fixes 73bc1b885dae ("hwmon: peci: Add dimmtemp driver")
Cc Iwona Winiarska <[email protected]>
---
 drivers/hwmon/peci/dimmtemp.c | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)
drivers/hwmon/peci/dimmtemp.c +14 -7
index fbe82d9852e01..d327e38d59e18 100644
@@ -4,7 +4,6 @@
 #include <linux/auxiliary_bus.h>
 #include <linux/bitfield.h>
 #include <linux/bitops.h>
-#include <linux/devm-helpers.h>
 #include <linux/hwmon.h>
 #include <linux/jiffies.h>
 #include <linux/module.h>
@@ -331,11 +330,13 @@ static int create_dimm_temp_info(struct peci_dimmtemp *priv)
 	if (ret == -ENODEV) {
 		dev_dbg(priv->dev, "No DIMMs found\n");
 		return 0;
-	} else if (ret) {
+	}
+	if (ret == -EAGAIN) {
 		schedule_delayed_work(&priv->detect_work, DIMM_MASK_CHECK_DELAY_JIFFIES);
 		dev_dbg(priv->dev, "Deferred populating DIMM temp info\n");
-		return ret;
 	}
+	if (ret)
+		return ret;
 
 	channels = priv->gen_info->chan_rank_max * priv->gen_info->dimm_idx_max;
 
@@ -405,10 +406,8 @@ static int peci_dimmtemp_probe(struct auxiliary_device *adev, const struct auxil
 			 "Unexpected PECI revision %#x, some features may be unavailable\n",
 			 peci_dev->info.peci_revision);
 
-	ret = devm_delayed_work_autocancel(priv->dev, &priv->detect_work,
-					   create_dimm_temp_info_delayed);
-	if (ret)
-		return ret;
+	auxiliary_set_drvdata(adev, priv);
+	INIT_DELAYED_WORK(&priv->detect_work, create_dimm_temp_info_delayed);
 
 	ret = create_dimm_temp_info(priv);
 	if (ret && ret != -EAGAIN) {
@@ -419,6 +418,13 @@ static int peci_dimmtemp_probe(struct auxiliary_device *adev, const struct auxil
 	return 0;
 }
 
+static void peci_dimmtemp_remove(struct auxiliary_device *adev)
+{
+	struct peci_dimmtemp *priv = auxiliary_get_drvdata(adev);
+
+	cancel_delayed_work_sync(&priv->detect_work);
+}
+
 static int
 read_thresholds_hsx(struct peci_dimmtemp *priv, int dimm_order, int chan_rank, u32 *data)
 {
@@ -655,6 +661,7 @@ MODULE_DEVICE_TABLE(auxiliary, peci_dimmtemp_ids);
 
 static struct auxiliary_driver peci_dimmtemp_driver = {
 	.probe		= peci_dimmtemp_probe,
+	.remove		= peci_dimmtemp_remove,
 	.id_table	= peci_dimmtemp_ids,
 };
 
Signature · 1 line
2.53.0
author maintainer
#286 lore raw

PATCH 286/686 hwmon: (pmbus/q54sj108a2) Add missing NULL pointer check

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit a5802c587da97a4ff85c04aad6043fa26640fc9b ]

When CONFIG_DEBUG_FS is enabled and per-client PMBus debugfs directory creation fails during pmbus_do_probe(), q54sj108a2_probe() passes the NULL pointer returned by pmbus_get_debugfs_dir() to debugfs_create_dir() without validation, creating its debugfs directory at the debugfs root instead of under the client directory.

If pmbus_init_debugfs() fails to create the client directory, data->debugfs is left as NULL or an ERR_PTR, which pmbus_get_debugfs_dir() converts to NULL. Passing a NULL parent to debugfs_create_dir() places q54sj108a2_dir in the root of the debugfs filesystem and populates it with attribute files whose private data pointers reference psu->debugfs_entries. Because this root-level directory is outside the client debugfs hierarchy, PMBus core cleanup does not remove it on device unbind, leaking the debugfs entries and causing a use-after-free of the devm-allocated struct q54sj108a2_data if the orphaned files are accessed via q54sj108a2_debugfs_read() or q54sj108a2_debugfs_write() after device removal.

Fix the problem by adding the missing NULL pointer check.

Fixes d014538aa385 ("hwmon: (pmbus) Driver for Delta power supplies Q54SJ108A2")
---
 drivers/hwmon/pmbus/q54sj108a2.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/hwmon/pmbus/q54sj108a2.c +2 -0
index 7b0d292a425ae..1f2811354aac3 100644
@@ -343,6 +343,8 @@ static int q54sj108a2_probe(struct i2c_client *client)
 	psu->client = client;
 
 	debugfs = pmbus_get_debugfs_dir(client);
+	if (!debugfs)
+		return 0;
 
 	q54sj108a2_dir = debugfs_create_dir(client->name, debugfs);
 
Signature · 1 line
2.53.0
author maintainer
#287 lore raw

PATCH 287/686 hwmon: (pmbus) Check return value from pmbus_thermal_add_sensor()

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 11dfbd835b17b75f7cc7a4a969f33ff702b1b081 ]

During PMBus device probe, if registering a temperature sensor with the thermal subsystem fails, pmbus_add_sensor() silently ignores the error and returns success.
When a valid temperature sensor is detected (class PSC_TEMPERATURE and type "input"), pmbus_add_sensor() invokes pmbus_thermal_add_sensor() to hook it into the kernel's thermal framework. However, the return value of this call is completely discarded. If thermal registration fails, such as from an -ENOMEM allocation failure or an invalid device tree configuration like a malformed #thermal-sensor-cells property, no error is propagated.

Because the hardware monitor probe falsely succeeds despite the failure to register the thermal zone, the system is left without thermal mitigation for the affected PMBus device. This silently blinds the system to actual PMIC temperatures, preventing the execution of necessary cooling mechanisms or emergency shutdowns and risking localized overheating.

Pass the return value from pmbus_thermal_add_sensor() to the calling code to fix the problem. To enable passing the actual error, change the error return from pmbus_add_sensor() from NULL to ERR_PTR() and extract the error from in the calling code.

Fixes 3aa74796cfd0 ("hwmon: (pmbus) Register with thermal for PSC_TEMPERATURE")
---
 drivers/hwmon/pmbus/pmbus_core.c | 42 ++++++++++++++++++--------------
 1 file changed, 24 insertions(+), 18 deletions(-)
drivers/hwmon/pmbus/pmbus_core.c +24 -18
index aa578d2723f22..08702ee8105f4 100644
@@ -1420,10 +1420,11 @@ static struct pmbus_sensor *pmbus_add_sensor(struct pmbus_data *data,
 {
 	struct sensor_device_attribute *a;
 	struct pmbus_sensor *sensor;
+	int err;
 
 	sensor = devm_kzalloc(data->dev, sizeof(*sensor), GFP_KERNEL);
 	if (!sensor)
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 	a = &sensor->attribute;
 
 	if (type)
@@ -1448,14 +1449,17 @@ static struct pmbus_sensor *pmbus_add_sensor(struct pmbus_data *data,
 			pmbus_set_sensor, -1);
 
 	if (pmbus_add_attribute(data, &a->dev_attr.attr))
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 
 	sensor->next = data->sensors;
 	data->sensors = sensor;
 
 	/* temperature sensors with _input values are registered with thermal */
-	if (class == PSC_TEMPERATURE && strcmp(type, "input") == 0)
-		pmbus_thermal_add_sensor(data, sensor, seq);
+	if (class == PSC_TEMPERATURE && strcmp(type, "input") == 0) {
+		err = pmbus_thermal_add_sensor(data, sensor, seq);
+		if (err)
+			return ERR_PTR(err);
+	}
 
 	return sensor;
 }
@@ -1556,8 +1560,8 @@ static int pmbus_add_limit_attrs(struct i2c_client *client,
 						page, 0xff, l->reg, attr->class,
 						attr->update || l->update,
 						l->readonly, l->writeonly, true);
-			if (!curr)
-				return -ENOMEM;
+			if (IS_ERR(curr))
+				return PTR_ERR(curr);
 			if (l->sbit && (info->func[page] & attr->sfunc)) {
 				ret = pmbus_add_boolean(data, name,
 					l->alarm, index,
@@ -1596,8 +1600,8 @@ static int pmbus_add_sensor_attrs_one(struct i2c_client *client,
 	}
 	base = pmbus_add_sensor(data, name, "input", index, page, phase,
 				attr->reg, attr->class, true, true, false, true);
-	if (!base)
-		return -ENOMEM;
+	if (IS_ERR(base))
+		return PTR_ERR(base);
 	/* No limit and alarm attributes for phase specific sensors */
 	if (attr->sfunc && phase == 0xff) {
 		ret = pmbus_add_limit_attrs(client, data, info, name,
@@ -2270,8 +2274,8 @@ static int pmbus_add_fan_ctrl(struct i2c_client *client,
 				  0xff, PMBUS_VIRT_FAN_TARGET_1 + id, PSC_FAN,
 				  false, false, false, true);
 
-	if (!sensor)
-		return -ENOMEM;
+	if (IS_ERR(sensor))
+		return PTR_ERR(sensor);
 
 	if (!((data->info->func[page] & PMBUS_HAVE_PWM12) ||
 	      (data->info->func[page] & PMBUS_HAVE_PWM34)))
@@ -2281,15 +2285,15 @@ static int pmbus_add_fan_ctrl(struct i2c_client *client,
 				  0xff, PMBUS_VIRT_PWM_1 + id, PSC_PWM,
 				  false, false, false, true);
 
-	if (!sensor)
-		return -ENOMEM;
+	if (IS_ERR(sensor))
+		return PTR_ERR(sensor);
 
 	sensor = pmbus_add_sensor(data, "pwm", "enable", index, page,
 				  0xff, PMBUS_VIRT_PWM_ENABLE_1 + id, PSC_PWM,
 				  true, false, false, false);
 
-	if (!sensor)
-		return -ENOMEM;
+	if (IS_ERR(sensor))
+		return PTR_ERR(sensor);
 
 	return 0;
 }
@@ -2306,6 +2310,7 @@ static int pmbus_add_fan_attributes(struct i2c_client *client,
 		int f;
 
 		for (f = 0; f < ARRAY_SIZE(pmbus_fan_registers); f++) {
+			struct pmbus_sensor *sensor;
 			int regval;
 
 			if (!(info->func[page] & pmbus_fan_flags[f]))
@@ -2326,10 +2331,11 @@ static int pmbus_add_fan_attributes(struct i2c_client *client,
 			    (!(regval & (PB_FAN_1_INSTALLED >> ((f & 1) * 4)))))
 				continue;
 
-			if (pmbus_add_sensor(data, "fan", "input", index,
-					     page, 0xff, pmbus_fan_registers[f],
-					     PSC_FAN, true, true, false, true) == NULL)
-				return -ENOMEM;
+			sensor = pmbus_add_sensor(data, "fan", "input", index,
+						  page, 0xff, pmbus_fan_registers[f],
+						  PSC_FAN, true, true, false, true);
+			if (IS_ERR(sensor))
+				return PTR_ERR(sensor);
 
 			/* Fan control */
 			if (pmbus_check_word_register(client, page,
Signature · 1 line
2.53.0
author maintainer
#288 lore raw

PATCH 288/686 hwmon: (pmbus) Release devres allocated memory after devm_thermal_of_zone_register error

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 9aa6cc563e881c3cad96ea36926cadceee151f32 ]

In pmbus_thermal_add_sensor(), a devres memory leak occurs when a PMBus temperature sensor is initialized but no thermal zone is configured for it.
The function allocates a pmbus_thermal_data structure using devm_kzalloc(). It then attempts to register the sensor with the thermal subsystem via devm_thermal_of_zone_register(). If this registration returns -ENODEV (e.g., when no thermal zone is mapped in the Device Tree or CONFIG_THERMAL_OF is disabled), the function intentionally catches the error and returns 0 to allow device probing to continue.

Because devm_kfree() is not called on the -ENODEV path, the unused tdata structure remains allocated on the device's managed resource list. Since most PMBus temperature sensors are not attached to thermal zones, this results in an accumulation of unused objects that needlessly consume kernel memory for the lifetime of the PMBus device.

Add the missing call to devm_kfree() to fix the problem.

Fixes 3aa74796cfd0 ("hwmon: (pmbus) Register with thermal for PSC_TEMPERATURE")
---
 drivers/hwmon/pmbus/pmbus_core.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/hwmon/pmbus/pmbus_core.c +3 -1
index 08702ee8105f4..3f310c8e97012 100644
@@ -1404,8 +1404,10 @@ static int pmbus_thermal_add_sensor(struct pmbus_data *pmbus_data,
 	 * If CONFIG_THERMAL_OF is disabled, this returns -ENODEV,
 	 * so ignore that error but forward any other error.
 	 */
-	if (IS_ERR(tzd) && (PTR_ERR(tzd) != -ENODEV))
+	if (IS_ERR(tzd) && (PTR_ERR(tzd) != -ENODEV)) {
+		devm_kfree(dev, tdata);
 		return PTR_ERR(tzd);
+	}
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#289 lore raw

PATCH 289/686 hwmon: (pmbus) Fix return value check from thermal zone registration

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 4fc79634af8cdf734e0a633923ba4817e30d29ad ]

The PMBus core used to call devm_thermal_zone_of_sensor_register() to register thermal zones. Commit 613ed3f676092 ("hwmon: pm_bus: core:
Switch to new of thermal API") changed this to call devm_thermal_of_zone_register() instead. The code subsequently checks if the call failed because the thermal subsystem is not configured. devm_thermal_zone_of_sensor_register() used to return -ENODEV in this case. devm_thermal_of_zone_register() returns -ENOTSUPP. The code currently still checks for -ENOVEV. This results in driver instantiation failures if the thermal subsystem is disabled.

Check for -ENOTSUPP to fix the problem. Keep checking for -ENODEV because this indicates that no thermal zone is configured for the sensor, which is acceptable for the driver and must not cause a registration failure.

Fixes 613ed3f676092 ("hwmon: pm_bus: core: Switch to new of thermal API")
---
 drivers/hwmon/pmbus/pmbus_core.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/hwmon/pmbus/pmbus_core.c +4 -3
index 3f310c8e97012..acab5fdf108e7 100644
@@ -1401,10 +1401,11 @@ static int pmbus_thermal_add_sensor(struct pmbus_data *pmbus_data,
 	tzd = devm_thermal_of_zone_register(dev, index, tdata,
 					    &pmbus_thermal_ops);
 	/*
-	 * If CONFIG_THERMAL_OF is disabled, this returns -ENODEV,
-	 * so ignore that error but forward any other error.
+	 * If CONFIG_THERMAL_OF is disabled, devm_thermal_of_zone_register()
+	 * returns -ENOTSUPP. If no thermal zone is configured for the sensor,
+	 * it returns -ENODEV. Ignore those errors but forward any other error.
 	 */
-	if (IS_ERR(tzd) && (PTR_ERR(tzd) != -ENODEV)) {
+	if (IS_ERR(tzd) && PTR_ERR(tzd) !=  -ENODEV && PTR_ERR(tzd) != -ENOTSUPP) {
 		devm_kfree(dev, tdata);
 		return PTR_ERR(tzd);
 	}
Signature · 1 line
2.53.0
author maintainer
#290 lore raw

PATCH 290/686 hwmon: (gpio-fan) Update the speed cache before dropping the PM reference

In reply to Greg Kroah-Hartman

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

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

From: Baek Kyu, Kim <[email protected]>

[ Upstream commit f324179e6ccd05dfdc8e98fba2e9d50aea8e7ea2 ]

set_fan_speed() writes the GPIO control value before dropping the runtime PM reference when stopping the fan. pm_runtime_put_sync() decrements the usage count even when suspending the device fails, but the error return currently leaves speed_index at the previous running speed.

A request for that same running speed then returns success without changing the GPIOs or taking a runtime PM reference. Retrying the stop instead drops a reference the driver no longer owns and can trigger a runtime PM usage count underflow warning.

Update speed_index after writing the GPIOs and before dropping the PM reference. The initial same-speed check already excludes a stopped fan, so a zero target is sufficient to identify the transition that needs a PM put. Preserve the PM error return and the CONFIG_PM=n exception.

This keeps the cached control state and PM reference ownership consistent without restoring running GPIOs after a possibly partial supply failure. It does not clear persistent runtime PM errors or claim that a failing regulator has successfully powered off.

---
 drivers/hwmon/gpio-fan.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/hwmon/gpio-fan.c +4 -3
index 1dfc02df9bbb0..34986266180e2 100644
@@ -150,7 +150,10 @@ static int set_fan_speed(struct gpio_fan_data *fan_data, int speed_index)
 
 	__set_fan_ctrl(fan_data, fan_data->speed[speed_index].ctrl_val);
 
-	if (fan_data->speed_index > 0 && speed_index == 0) {
+	/* The GPIOs have changed, and a PM put drops the reference on error. */
+	fan_data->speed_index = speed_index;
+
+	if (speed_index == 0) {
 		int ret;
 
 		ret = pm_runtime_put_sync(fan_data->dev);
@@ -158,8 +161,6 @@ static int set_fan_speed(struct gpio_fan_data *fan_data, int speed_index)
 			return ret;
 	}
 
-	fan_data->speed_index = speed_index;
-
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#291 lore raw

PATCH 291/686 hwmon: (coretemp) Check for NULL platform device in hotplug callbacks

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 0f9c7ed3b5009a037e5533eac03a0d4d45ecf1f0 ]

coretemp_get_pdev() returns NULL when topology_logical_die_id(cpu) is negative (such as -ENODEV or -ERANGE from topology_get_logical_id() on a firmware/hardware APIC ID mismatch) or exceeds max_zones (for example, under asymmetric or anomalous ACPI die topologies where topology_max_packages() * topology_max_dies_per_package() is smaller than the logical die count).

Commit 6d03bbff456b ("hwmon: (coretemp) Simplify platform device handling") pre-allocated zone_devices[0 .. max_zones - 1] during module init and dropped the NULL checks on pdev in coretemp_cpu_online() and coretemp_cpu_offline(), passing pdev unconditionally to platform_get_drvdata(). When coretemp_get_pdev() returns NULL, platform_get_drvdata(pdev) dereferences &pdev->dev and triggers a kernel NULL pointer dereference.

Check for a NULL pdev and return 0 in both coretemp_cpu_online() and coretemp_cpu_offline() before calling platform_get_drvdata(). Returning 0 in coretemp_cpu_online() ignores the unmapped CPU without blocking CPU bringup or tearing down valid thermal zones on other dies.

Fixes 6d03bbff456b ("hwmon: (coretemp) Simplify platform device handling")
---
 drivers/hwmon/coretemp.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/hwmon/coretemp.c +6 -0
index c9b7e435eda81..ac56319ff90cf 100644
@@ -686,6 +686,9 @@ static int coretemp_cpu_online(unsigned int cpu)
 	if (!housekeeping_cpu(cpu, HK_TYPE_MISC))
 		return 0;
 
+	if (!pdev)
+		return 0;
+
 	pdata = platform_get_drvdata(pdev);
 	if (!pdata->hwmon_dev) {
 		struct device *hwmon;
@@ -737,6 +740,9 @@ static int coretemp_cpu_offline(unsigned int cpu)
 		return 0;
 
 	/* If the physical CPU device does not exist, just return */
+	if (!pdev)
+		return 0;
+
 	pd = platform_get_drvdata(pdev);
 	if (!pd->hwmon_dev)
 		return 0;
Signature · 1 line
2.53.0
author maintainer
#292 lore raw

PATCH 292/686 hwmon: (sht4x) Convert update_interval to jiffies in pending data check

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 1a30ea0be623b7443edb6adc79e07632418cefdc ]

In sht4x_read_values(), the check for whether a pending post-heater measurement is still fresh compares get_jiffies_64() against data->heating_complete + data->update_interval. However, data->heating_complete is stored in jiffies whereas data->update_interval is stored in milliseconds.

Whenever HZ != 1000, adding data->update_interval directly without msecs_to_jiffies() mixes incompatible time units. For example, with the default 2000 ms update_interval, the validity window is inflated to 8 seconds at HZ=250 and 20 seconds at HZ=100 instead of 2 seconds. A read within that extended window skips triggering a fresh measurement and instead returns and caches the stale post-heating measurement left in the sensor's output buffer.

Convert data->update_interval to jiffies using msecs_to_jiffies() when computing the pending measurement expiration deadline, matching the next_update calculation right below it.

Fixes 0eed6fc3d2b9 ("hwmon: (sht4x): add heater support")
---
 drivers/hwmon/sht4x.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/hwmon/sht4x.c +3 -1
index 83dc3ca67046b..53c8feb7e2910 100644
@@ -99,7 +99,9 @@ static int sht4x_read_values(struct sht4x_data *data)
 		msleep(jiffies_to_msecs(data->heating_complete - curr_jiffies));
 
 	if (data->data_pending &&
-	    time_before64(get_jiffies_64(), data->heating_complete + data->update_interval)) {
+	    time_before64(get_jiffies_64(),
+			  data->heating_complete +
+			  msecs_to_jiffies(data->update_interval))) {
 		data->data_pending = false;
 	} else {
 		next_update = data->last_updated +
Signature · 1 line
2.53.0
author maintainer
#293 lore raw

PATCH 293/686 hwmon: (aquacomputer_d5next) Avoid truncating scaled sensor readings

In reply to Greg Kroah-Hartman

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

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

From: Vas Zayarskiy <[email protected]>

[ Upstream commit c221091f7e30c64280e4cbfa27dc4c05edc96d0c ]

High Flow Next power is reported in watts. Multiplying the 16-bit value by one million can overflow both the signed intermediate and the u32 cache. Store power in long, perform the conversion in u64, and clamp to LONG_MAX. The other existing power conversions fit in a signed 32-bit value. Return -ENODATA for unavailable power instead of exposing the stored error as a reading.

The power cache is updated by HID reports without the hwmon read mutex. Read it once with READ_ONCE() and use that snapshot for both the availability check and the returned value. Mark the corresponding updates with WRITE_ONCE() so that the shared accesses are explicit.

Widen the shared current cache to u32. The Aquastream XT conversion to milliamperes can exceed 65535 mA; clamp its negative conversion results to zero before assigning to the unsigned cache. This also permits devices with scaled aggregate currents to store milliamperes directly.

Fixes aed80bb91de8 ("hwmon: (aquacomputer_d5next) Add support for Aquacomputer High Flow Next")
[groeck: Dropped obsolete 'Assisted-by: tag]
---
 drivers/hwmon/aquacomputer_d5next.c | 29 ++++++++++++++++++-----------
 1 file changed, 18 insertions(+), 11 deletions(-)
drivers/hwmon/aquacomputer_d5next.c +18 -11
index e0052ba4702c6..95ec74c6e67eb 100644
@@ -19,6 +19,7 @@
 #include <linux/hwmon.h>
 #include <linux/jiffies.h>
 #include <linux/ktime.h>
+#include <linux/limits.h>
 #include <linux/module.h>
 #include <linux/mutex.h>
 #include <linux/seq_file.h>
@@ -614,9 +615,9 @@ struct aqc_data {
 	u32 speed_input_min[1];
 	u32 speed_input_target[1];
 	u32 speed_input_max[1];
-	u32 power_input[8];
+	long power_input[8];
 	u16 voltage_input[8];
-	u16 current_input[8];
+	u32 current_input[8];
 
 	/* Label values */
 	const char *const *temp_label;
@@ -1009,7 +1010,7 @@ static int aqc_legacy_read(struct aqc_data *priv)
 
 		/* Calculation derived from linear regression */
 		sensor_value = get_unaligned_le16(priv->buffer + AQUASTREAMXT_PUMP_CURR_OFFSET);
-		priv->current_input[0] = DIV_ROUND_CLOSEST(sensor_value * 176, 100) - 52;
+		priv->current_input[0] = max(DIV_ROUND_CLOSEST(sensor_value * 176, 100) - 52, 0);
 
 		sensor_value = get_unaligned_le16(priv->buffer + AQUASTREAMXT_PUMP_VOLTAGE_OFFSET);
 		priv->voltage_input[0] = DIV_ROUND_CLOSEST(sensor_value * 1000, 61);
@@ -1042,6 +1043,7 @@ static int aqc_legacy_read(struct aqc_data *priv)
 static int aqc_read(struct device *dev, enum hwmon_sensor_types type, u32 attr,
 		    int channel, long *val)
 {
+	long power;
 	int ret;
 	struct aqc_data *priv = dev_get_drvdata(dev);
 
@@ -1106,7 +1108,10 @@ static int aqc_read(struct device *dev, enum hwmon_sensor_types type, u32 attr,
 		}
 		break;
 	case hwmon_power:
-		*val = priv->power_input[channel];
+		power = READ_ONCE(priv->power_input[channel]);
+		if (power == -ENODATA)
+			return -ENODATA;
+		*val = power;
 		break;
 	case hwmon_pwm:
 		switch (priv->kind) {
@@ -1406,9 +1411,9 @@ static int aqc_raw_event(struct hid_device *hdev, struct hid_report *report, u8
 		priv->speed_input[i] =
 		    get_unaligned_be16(data + priv->fan_sensor_offsets[i] +
 				       priv->fan_structure->speed);
-		priv->power_input[i] =
-		    get_unaligned_be16(data + priv->fan_sensor_offsets[i] +
-				       priv->fan_structure->power) * 10000;
+		WRITE_ONCE(priv->power_input[i],
+			   get_unaligned_be16(data + priv->fan_sensor_offsets[i] +
+					      priv->fan_structure->power) * 10000);
 		priv->voltage_input[i] =
 		    get_unaligned_be16(data + priv->fan_sensor_offsets[i] +
 				       priv->fan_structure->voltage) * 10;
@@ -1448,7 +1453,8 @@ static int aqc_raw_event(struct hid_device *hdev, struct hid_report *report, u8
 		priv->speed_input[2] = get_unaligned_be16(data + AQUASTREAMULT_PRESSURE_OFFSET);
 		priv->speed_input[3] = get_unaligned_be16(data + AQUASTREAMULT_FLOW_SENSOR_OFFSET);
 
-		priv->power_input[1] = get_unaligned_be16(data + AQUASTREAMULT_PUMP_POWER) * 10000;
+		WRITE_ONCE(priv->power_input[1],
+			   get_unaligned_be16(data + AQUASTREAMULT_PUMP_POWER) * 10000);
 
 		priv->voltage_input[1] = get_unaligned_be16(data + AQUASTREAMULT_PUMP_VOLTAGE) * 10;
 
@@ -1461,10 +1467,11 @@ static int aqc_raw_event(struct hid_device *hdev, struct hid_report *report, u8
 	case highflownext:
 		/* If external temp sensor is not connected, its power reading is also N/A */
 		if (priv->temp_input[1] == -ENODATA)
-			priv->power_input[0] = -ENODATA;
+			WRITE_ONCE(priv->power_input[0], -ENODATA);
 		else
-			priv->power_input[0] =
-			    get_unaligned_be16(data + HIGHFLOWNEXT_POWER) * 1000000;
+			WRITE_ONCE(priv->power_input[0],
+				   min_t(u64, get_unaligned_be16(data + HIGHFLOWNEXT_POWER) *
+					 1000000ULL, LONG_MAX));
 
 		priv->voltage_input[0] = get_unaligned_be16(data + HIGHFLOWNEXT_5V_VOLTAGE) * 10;
 		priv->voltage_input[1] =
Signature · 1 line
2.53.0
author maintainer
#294 lore raw

PATCH 294/686 nvme: unregister when pr_register() is given a zero new key

In reply to Greg Kroah-Hartman

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

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

From: Daejun Park <[email protected]>

[ Upstream commit a9d431124fb2e58215daf0299d6fcf47bbc2d6b1 ]

The block layer PR API defines a zero new_key in pr_register() as unregistering old_key. nvme_pr_register() sends Replace Reservation Key with a zero NRKEY instead. The host stays registered with key 0, and its next registration with another key fails with Reservation Conflict.

The pNFS SCSI layout client unregisters this way at umount. A later mount cannot register and sends all I/O through the metadata server.

Send Unregister Reservation Key when new_key is zero.

Fixes 1d277a637a71 ("NVMe: Add persistent reservation ops")
---
 drivers/nvme/host/pr.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/nvme/host/pr.c +6 -2
index fe7dbe2648158..d8b6ac4d83bb9 100644
@@ -128,8 +128,12 @@ static int nvme_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
 	data.crkey = cpu_to_le64(old_key);
 	data.nrkey = cpu_to_le64(new_key);
 
-	cdw10 = old_key ? NVME_PR_REGISTER_ACT_REPLACE :
-		NVME_PR_REGISTER_ACT_REG;
+	if (!new_key)
+		cdw10 = NVME_PR_REGISTER_ACT_UNREG;
+	else if (old_key)
+		cdw10 = NVME_PR_REGISTER_ACT_REPLACE;
+	else
+		cdw10 = NVME_PR_REGISTER_ACT_REG;
 	cdw10 |= (flags & PR_FL_IGNORE_KEY) ? NVME_PR_IGNORE_KEY : 0;
 	cdw10 |= NVME_PR_CPTPL_PERSIST;
 
Signature · 1 line
2.53.0
author maintainer
#295 lore raw

PATCH 295/686 KVM: x86/mmu: Conditionally resched when retrying gPTE walk on A/D update failure

In reply to Greg Kroah-Hartman

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

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

From: Sean Christopherson <[email protected]>

[ Upstream commit b2691b3a6cd230209736c89684dab90d939aa56b ]

Conditionally reschedule when retrying a guest PTE walk because the CMPXCHG to update A/D bits failed, e.g. because a different task/vCPU modified the relevant gPTEs. On kernels without involuntary preemption of some kind, a misbehaving guest can "capture" a pCPU effectively indefinitely and trigger soft lockups by continuously modifying its gPTEs such that the result of the walk is remains valid.

Fixes b3e4e63fd9ee ("KVM: MMU: Use cmpxchg for pte updates on walk_addr()")

Message-ID: <[email protected]>

---
 arch/x86/kvm/mmu/paging_tmpl.h | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/paging_tmpl.h +10 -1
index 4e84b5a1eeaaa..ec265eb196da4 100644
@@ -321,6 +321,13 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
 	gpa_t real_gpa;
 	gfn_t gfn;
 
+	/*
+	 * KVM might sleep/resched when retrying the walk if the updating A/D
+	 * fails because the gPTE changed between reading the gPTE and trying
+	 * the CMPXHG to set A/D bits.
+	 */
+	might_sleep();
+
 	trace_kvm_mmu_pagetable_walk(addr, access);
 retry_walk:
 	walker->level = mmu->cpu_role.base.level;
@@ -471,8 +478,10 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
 							addr, write_fault);
 		if (unlikely(ret < 0))
 			goto error;
-		else if (ret)
+		else if (ret) {
+			cond_resched();
 			goto retry_walk;
+		}
 	}
 
 	return 1;
Signature · 1 line
2.53.0
author maintainer
#296 lore raw

PATCH 296/686 KVM: x86: Conditionally resched when restarting REP string emulation

In reply to Greg Kroah-Hartman

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

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

From: Sean Christopherson <[email protected]>

[ Upstream commit ae85ac25eb671d174811cc3101549448671fd505 ]

When restarting emulation, e.g. of a REP-prefixed string instruction, conditionally reschedule as emulating guest writes can be deceptively slow and expensive, e.g. when shadow paging is in use and each write can trigger write tracking.

In a perfect world, restarting emulation (or not) would be less arbitrary, e.g. would honor not only host events (NEED_RESCHED, signals, etc.) but also guest events (e.g. by checking kvm_vcpu_has_events()). Unfortunately, as pointed out by Sashiko, pio_in_emulated()'s read-ahead logic is baked into the restart logic, as KVM relies on restarting emulation to drain the cache and avoid duplicate reads from the I/O port. I.e. re-entering the guest on kvm_vcpu_has_events() or __xfer_to_guest_mode_work_pending() would introduce architecturally-incorrect, guest-visible changes.

Fixes 5cd21917da24 ("KVM: x86 emulator: restart string instruction without going back to a guest.")
Cc David Woodhouse <[email protected]>

Message-ID: <[email protected]>

---
 arch/x86/kvm/x86.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
arch/x86/kvm/x86.c +4 -2
index 6576c692a94eb..0a6fb6e08d1bd 100644
@@ -9218,10 +9218,12 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
 	} else if (vcpu->arch.complete_userspace_io) {
 		writeback = false;
 		r = 0;
-	} else if (r == EMULATION_RESTART)
+	} else if (r == EMULATION_RESTART) {
+		cond_resched();
 		goto restart;
-	else
+	} else {
 		r = 1;
+	}
 
 writeback:
 	if (writeback) {
Signature · 1 line
2.53.0
author maintainer
#297 lore raw

PATCH 297/686 KVM: nVMX: Process each host MSR entry at most once when unwinding failed VM-Entry

In reply to Greg Kroah-Hartman

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

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

From: Sean Christopherson <[email protected]>

[ Upstream commit c33ef9d334059f7cb167569ed7b4779752fe4425 ]

Add a missing "break" in the inner for-loop of the open coded mess that unwinds MSRs back to the pre-VM-Enter state when VMLAUNCH/VMRESUME VM-Fails due to a consistency check that is caught by hardware but missed by KVM. I.e. move on to the next MSR in the VM-Entry load list after performing a write using a value found in the VM-Exit load list. Processing *every* matching entry in the VM-Exit load list makes the processing quadratic, which is problematic if the load lists are full of MSRs that are expensive to emulate. E.g. writing APIC_BASE triggers kvm_recalculate_apic_map() and a whole pile of unnecessary work.

Functionally, arbitrarily restoring the value of the first matching entry is "fine", because none of this is architecturally correct: the load lists are never supposed to have been used in the first place. In practice, it's likely a moot point as no well-behaved VMM will have multiple, diverging entries in the load lists.

Fixes bd18bffca353 ("KVM: nVMX: restore host state in nested_vmx_vmexit for VMFail")
Cc David Woodhouse <[email protected]>

Message-ID: <[email protected]>

---
 arch/x86/kvm/vmx/nested.c | 1 +
 1 file changed, 1 insertion(+)
arch/x86/kvm/vmx/nested.c +1 -0
index ab1558f1f9f8d..ffca5fef5b5ea 100644
@@ -5136,6 +5136,7 @@ static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
 					__func__, j, h.index, h.value);
 				goto vmabort;
 			}
+			break;
 		}
 	}
 
Signature · 1 line
2.53.0
author maintainer
#298 lore raw

PATCH 298/686 KVM: x86/mmu: Cap number of parent PTEs per SP at 1000 (the arbitrary rmap limit)

In reply to Greg Kroah-Hartman

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

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

From: Sean Christopherson <[email protected]>

[ Upstream commit e4558c3d7198ed9a0adc3304681f561f4e4d80e1 ]

When potentially reusing a shadow page, zap the shadow page if its number of parent PTEs exceeds KVM's (mostly) arbitrary rmap recycling threshold. Letting the guest create a (mostly) unbounded number of parent PTEs allows the guest to coerce KVM into creating lists containing millions of PTEs, effectively bounded only by the maximum number of shadow pages.

Because PTE lists are simple singly linked lists, removal is O(n). Even worse, if a list is constructed just so, teardown can be O(n^2), e.g. if SPTEs are built such that zapping child SPTEs always zaps the last entry in the list. To cap things off, all paths that walk PTE lists do so while holding mmu_lock, without conditionally rescheduling.

Using a doubly linked list would not address the issue, as removal would remain O(n) since KVM still wouldn't know where in the list to remove from. Removal could be made O(1) by storing a per-SPTE pointer, but that would largely defeat the purpose of reusing SPs, and would penalize well-behaved guests, especially for nested TDP where aliasing page tables is uncommon.

So, cap the maximum number of parent PTEs at the rmap limit. In practice, well-behaved guests will likely never run afoul of the limit. E.g. when running Linux as L1 with TDP, the number of parent PTEs for a single SP tops out at under 200 (though undoubtedly obscure workloads can push it higher). Deliberately use a "greater than or equal" as opposed to rmap's strictly "greater than", as the rmap code checks the threshold immediately *after* inserting into the list, i.e. the limit is 1000 for rmaps, KVM just very briefly blows past it.

Apply the check to both indirect and direct SPs, because while a fully direct MMU naturally limits the number of parent PTEs to '1', direct SPs in indirect MMUs have no such constraint. E.g. if the guest maps a huge PTE into many locations in its page tables, and KVM is backing the hugepage with a direct SP, i.e. with a series of smaller pages, then KVM could end up with a direct SP with many parents.

Note, shadow_mmu_try_split_huge_pages() always restarts the rmap walk or bails entirely if it gets to the point where it tries to grab a SP, i.e. there is *no* pre-existing bug that would be tripped by zapping a SP and thus rmaps when getting a SP.

Message-ID: <[email protected]>

---
 arch/x86/kvm/mmu/mmu.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
arch/x86/kvm/mmu/mmu.c +10 -0
index 24f22c10e6774..3b1fb5696ed65 100644
@@ -2279,6 +2279,16 @@ static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
 			continue;
 		}
 
+		/*
+		 * Note!  Unlike fully direct MMUs, direct SPs in indirect MMUs
+		 * can have an arbitrary number of parents, e.g if the guest is
+		 * mapping a huge PTE at many points in its page tables.
+		 */
+		if (pte_list_count(&sp->parent_ptes) >= RMAP_RECYCLE_THRESHOLD) {
+			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
+			break;
+		}
+
 		/* unsync and write-flooding only apply to indirect SPs. */
 		if (sp->role.direct)
 			goto out;
Signature · 1 line
2.53.0
author maintainer
#299 lore raw

PATCH 299/686 KVM: x86: Unconditionally reset MMU context when emulating INIT

In reply to Greg Kroah-Hartman

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

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

From: Sean Christopherson <[email protected]>

[ Upstream commit c7c288d178cb0b78d3464a616b16b1aa0b316049 ]

Force an MMU reset when emulating an INIT even if paging was already disabled, as the MMU page role includes guest_mode (L2), i.e. an INIT while L2 is running with CR0.PG=0 will result in KVM running L1 with a stale MMU context.

Alternatively, the reset could be scoped strictly to paging being enabled or L2 being active, but SMM is also encoded in the page role. Even though it _should_ be impossible for the vCPU to be INIT'd while SMM is active, there's zero value in not handling SMM. At that point, the only scenario where KVM _doesn't_ need to reset the MMU context is on an INIT with the vCPU running in Real Mode or Unpaged Protect Mode, and while INIT in those modes is somewhat common, it's far from a hot path and re-initializing the MMU is not expensive, especially when the role isn't changing (KVM elides most of the re-configuration in that case).

Note, like the Fixes commit, this bug only affects nested SVM as INIT is an unconditional intercept on VMX, i.e. it's impossible to emulate INIT while L2 is active.

Temporarily keep the guest TLB flush when CR0.PG is being cleared even though it is fully redundant with the flush that is emitted on all INIT events (KVM itself only does RESET when a vCPU is being created, i.e. when CR0.PG must be '0').

Fixes ed129ec9057f ("KVM: x86: forcibly leave nested mode on vCPU reset")
Cc Yosry Ahmed <[email protected]>

Message-ID: <[email protected]>

---
 arch/x86/kvm/x86.c | 25 +++++++++++++++----------
 1 file changed, 15 insertions(+), 10 deletions(-)
arch/x86/kvm/x86.c +15 -10
index 0a6fb6e08d1bd..3ca396316d3cf 100644
@@ -12278,18 +12278,23 @@ void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 	kvm_x86_call(set_efer)(vcpu, 0);
 	kvm_x86_call(update_exception_bitmap)(vcpu);
 
+	if (old_cr0 & X86_CR0_PG)
+		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
+
 	/*
-	 * On the standard CR0/CR4/EFER modification paths, there are several
-	 * complex conditions determining whether the MMU has to be reset and/or
-	 * which PCIDs have to be flushed.  However, CR0.WP and the paging-related
-	 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
-	 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
-	 * CR0 will be '0' prior to RESET).  So we only need to check CR0.PG here.
+	 * Unconditionally reset the MMU, even though super strictly speaking,
+	 * a MMU reset is only necessary if and only one of the page role bits
+	 * is changing.  All of the CR0/CR4/EFER bits effectively get covered
+	 * by checking CR0.PG=1, as CR0.WP and the paging-related bits in CR4
+	 * and EFER are irrelevant if CR0.PG was '0'.  Subtly, if the vCPU was
+	 * in guest mode (L2) or SMM (although emulating INIT in SMM _should_
+	 * be impossible), an MMU reset is also necessary as "guest mode" and
+	 * "smm" are both encoded in the shadow page role.  As a result, the
+	 * only scenarios where an MMU reset is *not* needed is if the vCPU is
+	 * in Real Mode or Unpaged Protected Mode, and micro-optimizing those
+	 * paths are not worth the risk of running with a stale MMU context.
 	 */
-	if (old_cr0 & X86_CR0_PG) {
-		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
-		kvm_mmu_reset_context(vcpu);
-	}
+	kvm_mmu_reset_context(vcpu);
 
 	/*
 	 * Intel's SDM states that all TLB entries are flushed on INIT.  AMD's
Signature · 1 line
2.53.0
author maintainer
#300 lore raw

PATCH 300/686 ipv6: reject wrapped temporary address preferred lifetimes

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 c3e67bd82b9b9b1a5118f09a429ccefe2aab0741 ]

ipv6_create_tempaddr() raises a temporary address's preferred lifetime to regen_advance + age + 1 when the configured lifetime is too short. The result is stored in a u32, while regen_advance and age are unsigned long. If the sum wraps or is truncated, the stored lifetime can still be less than or equal to regen_advance + age.

addrconf_verify_rtnl() then sees the new address as due for regeneration and creates another one. Temporary addresses are not limited by max_addresses since commit 4b08a8f1bd8c ("ipv6: remove max_addresses check from ipv6_create_tempaddr"), so this can cause unbounded address growth. With dad_transmits set to -1, a baseline kernel reached 2859 loopback addresses in two seconds.

After storing the adjusted lifetime, verify that it is still greater than regen_advance + age. Reject the new address if the check fails.

On an x86-64 KASAN kernel, the normal configuration created three IPv6 addresses. The negative dad_transmits, positive multiplication overflow, and large retransmission-time cases each left only the loopback and public addresses. An i386 defconfig and an x86-64 allmodconfig both built addrconf.o with W=1.

---
 net/ipv6/addrconf.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/ipv6/addrconf.c +2 -1
index 527ae9fc1c41c..8f651cafcb2a5 100644
@@ -1484,7 +1484,8 @@ static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, bool block)
 	age = (now - tmp_tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
 	if (cfg.preferred_lft <= regen_advance + age) {
 		cfg.preferred_lft = regen_advance + age + 1;
-		if (cfg.preferred_lft > cfg.valid_lft ||
+		if (cfg.preferred_lft <= regen_advance + age ||
+		    cfg.preferred_lft > cfg.valid_lft ||
 		    cfg.preferred_lft > if_public_preferred_lft) {
 			in6_ifa_put(ifp);
 			in6_dev_put(idev);
Signature · 1 line
2.53.0
author maintainer
#301 lore raw

PATCH 301/686 x86/vmware: Fix i386 high-bandwidth hypercall arguments

In reply to Greg Kroah-Hartman

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

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

From: Zack Rusin <[email protected]>

[ Upstream commit e0e022004bbedc7caf1c18770980eb5372019189 ]

The high-bandwidth hypercall helpers push %ebp before loading the in6 operand into it. On i386 without frame pointers, both GCC and Clang can address the memory-constrained operand relative to %esp. The push then moves the stack and the helpers load the wrong value.

Typical i386 configurations use the frame-pointer unwinder and happen to address the operand through %ebp. However, UNWINDER_GUESS is available with EXPERT and permits the affected frame-pointer-disabled configuration. vmwgfx is also available on i386 and calls both helpers.

Stage in6 through %eax before changing either stack register, then save %ebp and copy the staged value into it. Load the VMware magic immediately before the string I/O instruction. Mark %eax early-clobber so it cannot also provide in6 or an address register for it. Use the same sequence on x86-64, where the full-width register preserves in6.

---
 arch/x86/include/asm/vmware.h | 24 ++++++++++++++----------
 1 file changed, 14 insertions(+), 10 deletions(-)
arch/x86/include/asm/vmware.h +14 -10
index 4220dae14a2d9..fb011cef01e76 100644
@@ -276,20 +276,22 @@ unsigned long vmware_hypercall_hb_out(unsigned long cmd, unsigned long in2,
 
 	asm_inline volatile (
 		UNWIND_HINT_SAVE
+		"mov %[in6], %%" _ASM_AX "\n\t"
 		"push %%" _ASM_BP "\n\t"
 		UNWIND_HINT_UNDEFINED
-		"mov %[in6], %%" _ASM_BP "\n\t"
+		"mov %%" _ASM_AX ", %%" _ASM_BP "\n\t"
+		"mov %[magic], %%eax\n\t"
 		"rep outsb\n\t"
 		"pop %%" _ASM_BP "\n\t"
 		UNWIND_HINT_RESTORE
-		: "=a" (out0), "=b" (*out1)
-		: "a" (VMWARE_HYPERVISOR_MAGIC),
-		  "b" (cmd),
+		: "=&a" (out0), "=b" (*out1)
+		: "b" (cmd),
 		  "c" (in2),
 		  "d" (in3 | VMWARE_HYPERVISOR_PORT_HB),
 		  "S" (in4),
 		  "D" (in5),
-		  [in6] VMW_BP_CONSTRAINT (in6)
+		  [in6] VMW_BP_CONSTRAINT(in6),
+		  [magic] "i" (VMWARE_HYPERVISOR_MAGIC)
 		: "cc", "memory");
 	return out0;
 }
@@ -304,20 +306,22 @@ unsigned long vmware_hypercall_hb_in(unsigned long cmd, unsigned long in2,
 
 	asm_inline volatile (
 		UNWIND_HINT_SAVE
+		"mov %[in6], %%" _ASM_AX "\n\t"
 		"push %%" _ASM_BP "\n\t"
 		UNWIND_HINT_UNDEFINED
-		"mov %[in6], %%" _ASM_BP "\n\t"
+		"mov %%" _ASM_AX ", %%" _ASM_BP "\n\t"
+		"mov %[magic], %%eax\n\t"
 		"rep insb\n\t"
 		"pop %%" _ASM_BP "\n\t"
 		UNWIND_HINT_RESTORE
-		: "=a" (out0), "=b" (*out1)
-		: "a" (VMWARE_HYPERVISOR_MAGIC),
-		  "b" (cmd),
+		: "=&a" (out0), "=b" (*out1)
+		: "b" (cmd),
 		  "c" (in2),
 		  "d" (in3 | VMWARE_HYPERVISOR_PORT_HB),
 		  "S" (in4),
 		  "D" (in5),
-		  [in6] VMW_BP_CONSTRAINT (in6)
+		  [in6] VMW_BP_CONSTRAINT(in6),
+		  [magic] "i" (VMWARE_HYPERVISOR_MAGIC)
 		: "cc", "memory");
 	return out0;
 }
Signature · 1 line
2.53.0
author maintainer
#302 lore raw

PATCH 302/686 Bluetooth: hci_sync: re-enable legacy advertising on resume

In reply to Greg Kroah-Hartman

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

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

From: Valentin Kindschi <[email protected]>

[ Upstream commit 737139f4157d302292a6b937d96922879ecabfa3 ]

hci_resume_advertising_sync() never re-enables advertising on a controller without extended advertising.

It restores HCI_ADVERTISING from advertising_old_state, then calls hci_schedule_adv_instance_sync(), which starts with:

  if (hci_dev_test_flag(hdev, HCI_ADVERTISING) && !ext_adv_capable(hdev))
          return -EPERM;

The flag it tests was set a few lines earlier by the resume itself, so the call returns -EPERM without sending anything. The return value is discarded by every caller, so the failure is silent: advertising_paused is cleared, HCI_ADVERTISING is set, and the controller is not advertising.

Observed on a BCM43455 (no extended advertising) after an active scan:
btmon shows the pause disabling advertising and no re-enable in the ten seconds that follow, the device does not appear in another controller's scan, and btmgmt info still reports "advertising" in current settings.

Enable instance 0x00 directly in that case, the way reenable_adv_sync() already does for the same situation. Instances continue to go through hci_schedule_adv_instance_sync() so the software rotation loop is rearmed.

This affects every caller of hci_resume_advertising_sync(), not only the scan path: address resolution changes, accept list updates, discovery stop, suspend/resume and the end of an LE connection attempt all leave advertising disabled on such a controller today.

The resume does nothing when the controller is already advertising, as it is after directed advertising was started for a peripheral connection, so it does not replace that advertising.

err is initialised because the extended branch leaves it unset when adv_instances is empty and HCI_LE_ADV_0 is clear.

Fixes ad383c2c65a5 ("Bluetooth: hci_sync: Enable advertising when LL privacy is enabled")
Assisted-by Claude:claude-opus-5.5 btmon
---
 net/bluetooth/hci_sync.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
net/bluetooth/hci_sync.c +8 -2
index 8da58c61e9723..1bdaf7b2e01e1 100644
@@ -2708,7 +2708,7 @@ static int hci_pause_advertising_sync(struct hci_dev *hdev)
 static int hci_resume_advertising_sync(struct hci_dev *hdev)
 {
 	struct adv_info *adv, *tmp;
-	int err;
+	int err = 0;
 
 	/* If advertising has not been paused there is nothing  to do. */
 	if (!hdev->advertising_paused)
@@ -2741,13 +2741,19 @@ static int hci_resume_advertising_sync(struct hci_dev *hdev)
 		 */
 		if (hci_dev_test_and_clear_flag(hdev, HCI_LE_ADV_0))
 			err = hci_enable_ext_advertising_sync(hdev, 0x00);
-	} else {
+	} else if (hdev->cur_adv_instance) {
 		/* Schedule for most recent instance to be restarted and begin
 		 * the software rotation loop
 		 */
 		err = hci_schedule_adv_instance_sync(hdev,
 						     hdev->cur_adv_instance,
 						     true);
+	} else if (hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
+		   !hci_dev_test_flag(hdev, HCI_LE_ADV)) {
+		/* hci_schedule_adv_instance_sync() rejects instance 0x00 while
+		 * HCI_ADVERTISING is set, so enable it directly.
+		 */
+		err = hci_start_adv_sync(hdev, 0x00);
 	}
 
 	hdev->advertising_paused = false;
Signature · 1 line
2.53.0
author maintainer
#303 lore raw

PATCH 303/686 Bluetooth: hci_sync: pause advertising for the scan address update

In reply to Greg Kroah-Hartman

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

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

From: Valentin Kindschi <[email protected]>

[ Upstream commit 56ed6b127a27c418dc2daa3fd076539d8fe69c4c ]

hci_active_scan_sync() programs a non-resolvable private address with LE Set Random Address on every active scan start.

BLUETOOTH CORE SPECIFICATION Vol 4, Part E, 7.8.4 says the controller shall return Command Disallowed (0x0C) for that command while legacy advertising or scanning is enabled. hci_pause_addr_resolution(), called just above, only stops advertising when LL privacy is in use, so on a controller without it the command is issued while advertising is still on:

Bluetooth: hci0: Opcode 0x2005 failed: -16

It does not converge either. hdev->random_addr is only set on a successful command complete, so it stays BDADDR_ANY, and the deferral added by commit c2994b008492 ("Bluetooth: hci_sync: Fix not setting Random Address when required") requires it to be set. Unlike the resolvable address a few lines above, which is reused while rpa_valid(), the non-resolvable one is regenerated and rewritten on every call, so a controller that refuses the write is asked again at the scan restart period of about 10 s, for as long as discovery keeps restarting. Observed on a BCM43455, which has no LL privacy and no extended advertising, 190 rejections in one capture, every one retrying the same address:

  < LE Set Random Address  Address: 02:16:91:90:F1:D4 (Non-Resolvable)
  > Command Complete       LE Set Random Address, Command Disallowed
  < LE Set Random Address  Address: 26:90:57:96:9A:3E (Non-Resolvable)
  > Command Complete       LE Set Random Address, Command Disallowed

Pause advertising for the address update, and resume it once the update is done and before the scan is started. The pause does not outlive the
function: it is taken only when nothing else holds it, and every exit resumes advertising, which also releases the pause taken by hci_pause_addr_resolution(). A failed pause returns before marking anything paused, so the error path is a no-op.

The resume in the error path is no longer guarded by ll_privacy_capable(). That guard matched a pause taken only under LL privacy; the pause added here is unconditional, and hci_resume_advertising_sync() returns early when nothing was paused.

One caveat this widens, raised on the previous posting. When HCI_ADVERTISING is set, hci_pause_advertising_sync() also clears HCI_DISCOVERABLE and HCI_LIMITED_DISCOVERABLE and zeroes discov_timeout, and hci_resume_advertising_sync() restores only HCI_ADVERTISING, so the discoverable state is lost. It reproduces today on an LL privacy controller through hci_pause_addr_resolution(); the unconditional pause makes it reachable without LL privacy as well. hci_suspend_sync() also pauses unconditionally, so a device that suspends loses the same state on any controller today. That asymmetry is pre-existing and is left alone here rather than folded into a scan path fix.

Legacy controllers have one random address register, shared by the scanner and the advertiser. Restoring the advertiser here can reprogram it when the advertiser is non-connectable, so the scan then uses that address rather than the one generated for it. Both are non-resolvable and neither is linkable to the identity address. With privacy enabled both roles already share one resolvable address the same way.

With the patch, on the same hardware:

  < LE Set Advertising Enable    Enable: 0x00              Success
  < LE Set Random Address                                  Success
  < LE Set Advertising Parameters                          Success
  < LE Set Advertising Enable    Enable: 0x01              Success
  < LE Set Scan Parameters                                 Success
  < LE Set Scan Enable           Enable: 0x01              Success

The address write is accepted, and advertising is restored before the scan is started.

Over 119369 btmon records and about 12 minutes of the normal workload of that device, alternating active and passive scanning with ten outgoing connection attempts, every LE Set Random Address succeeded and there were no Command Disallowed responses of any opcode, against one per scan restart before.

Patch 1 is required: without it the resume added here returns -EPERM on the controllers this fixes and leaves advertising disabled.

Fixes 3c44a431d62b ("Bluetooth: hci_sync: Resume adv with no RPA when active scan")
Assisted-by Claude:claude-opus-5.5 btmon
---
 net/bluetooth/hci_sync.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
net/bluetooth/hci_sync.c +12 -3
index 1bdaf7b2e01e1..9cb1cdbff3fd2 100644
@@ -6146,6 +6146,7 @@ static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)
 	u8 filter_policy = 0x00;
 	/* Default is to enable duplicates filter */
 	u8 filter_dup = LE_SCAN_FILTER_DUP_ENABLE;
+	bool paused;
 	int err;
 
 	bt_dev_dbg(hdev, "");
@@ -6169,6 +6170,12 @@ static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)
 	if (err)
 		goto failed;
 
+	/* LE Set Random Address is disallowed while advertising is enabled. */
+	paused = !hdev->advertising_paused;
+	err = hci_pause_advertising_sync(hdev);
+	if (err)
+		goto failed;
+
 	/* All active scans will be done with either a resolvable private
 	 * address (when privacy feature has been enabled) or non-resolvable
 	 * private address.
@@ -6178,6 +6185,9 @@ static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)
 	if (err < 0)
 		own_addr_type = ADDR_LE_DEV_PUBLIC;
 
+	if (paused)
+		hci_resume_advertising_sync(hdev);
+
 	if (hci_is_adv_monitoring(hdev) ||
 	    (hci_test_quirk(hdev, HCI_QUIRK_STRICT_DUPLICATE_FILTER) &&
 	    hdev->discovery.result_filtering)) {
@@ -6201,9 +6211,8 @@ static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)
 		return err;
 
 failed:
-	/* Resume advertising if it was paused */
-	if (ll_privacy_capable(hdev))
-		hci_resume_advertising_sync(hdev);
+	/* No-op when advertising was not paused. */
+	hci_resume_advertising_sync(hdev);
 
 	/* Resume passive scanning */
 	hci_update_passive_scan_sync(hdev);
Signature · 1 line
2.53.0
author maintainer
#304 lore raw

PATCH 304/686 Bluetooth: qca: Fix the WCN3950 NVM baud rate offset

In reply to Greg Kroah-Hartman

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

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

From: Michael McAllister <[email protected]>

[ Upstream commit 5b7d0386a4e75c85479da0fbd9fd66a3e9201375 ]

WCN3950 uses the HCI transport tag layout that stores the UART baud rate at byte 1, like WCN3991. However, QCA_WCN3950 precedes QCA_WCN3991 in qca_btsoc_type, so qca_tlv_check_data() writes the baud rate to byte 2 instead.

On a Motorola Moto G10 with WCN3950 and cmnv12.bin, configuring a 3 Mbps UART therefore leaves the NVM baud rate at its default 3.2 Mbps and overwrites the following byte. Firmware download completes, but the subsequent HCI_RESET times out and Bluetooth initialization fails.

Include WCN3950 in the byte-1 case so the NVM baud rate matches the host UART without altering the following transport parameter.

Fixes d5712c511cb3 ("Bluetooth: qca: add WCN3950 support")
Assisted-by LLM
---
 drivers/bluetooth/btqca.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/bluetooth/btqca.c +2 -1
index bdbb5801b2400..4215522e62a2c 100644
@@ -443,7 +443,8 @@ static int qca_tlv_check_data(struct hci_dev *hdev,
 				tlv_nvm->data[0] |= 0x80;
 
 				/* UART Baud Rate */
-				if (soc_type >= QCA_WCN3991)
+				if (soc_type == QCA_WCN3950 ||
+				    soc_type >= QCA_WCN3991)
 					tlv_nvm->data[1] = nvm_baud_rate;
 				else
 					tlv_nvm->data[2] = nvm_baud_rate;
Signature · 1 line
2.53.0
author maintainer
#305 lore raw

PATCH 305/686 ASoC: qcom: q6apm: Guard callbacks until probe data is ready

In reply to Greg Kroah-Hartman

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

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

From: Mohit Sharma <[email protected]>

[ Upstream commit ef7062864c0511bba52775d0eb3aa72d886b5f3a ]

The GPR bus needs to make response callbacks available before invoking a client probe because clients can issue synchronous commands from probe. This creates a short interval where a callback can run before the client has published its private data.

Make q6apm publish its driver data only after all callback-visible state has been initialized. Have the q6apm and q6prm callbacks ignore packets received before driver data is available.

---
 sound/soc/qcom/qdsp6/q6apm.c | 6 ++++--
 sound/soc/qcom/qdsp6/q6prm.c | 3 +++
 2 files changed, 7 insertions(+), 2 deletions(-)
sound/soc/qcom/qdsp6/q6apm.c +4 -2
index 50d5d2143daaf..7894d4430ff17 100644
@@ -765,8 +765,6 @@ static int apm_probe(gpr_device_t *gdev)
 	if (!apm)
 		return -ENOMEM;
 
-	dev_set_drvdata(dev, apm);
-
 	mutex_init(&apm->lock);
 	apm->dev = dev;
 	apm->gdev = gdev;
@@ -780,6 +778,7 @@ static int apm_probe(gpr_device_t *gdev)
 
 	idr_init(&apm->modules_idr);
 
+	dev_set_drvdata(dev, apm);
 	g_apm = apm;
 
 	q6apm_get_apm_state(apm);
@@ -820,6 +819,9 @@ static int apm_callback(struct gpr_resp_pkt *data, void *priv, int op)
 	struct gpr_ibasic_rsp_result_t *result;
 	struct gpr_hdr *hdr = &data->hdr;
 
+	if (!apm)
+		return 0;
+
 	result = data->payload;
 
 	switch (hdr->opcode) {
sound/soc/qcom/qdsp6/q6prm.c +3 -0
index 81554d2026589..22e2a174a3871 100644
@@ -197,6 +197,9 @@ static int prm_callback(struct gpr_resp_pkt *data, void *priv, int op)
 	struct gpr_ibasic_rsp_result_t *result;
 	struct gpr_hdr *hdr = &data->hdr;
 
+	if (!prm)
+		return 0;
+
 	switch (hdr->opcode) {
 	case PRM_CMD_RSP_REQUEST_HW_RSC:
 	case PRM_CMD_RSP_RELEASE_HW_RSC:
Signature · 1 line
2.53.0
author maintainer
#306 lore raw

PATCH 306/686 x86/resctrl: Correct ABMC counter ID field width

In reply to Greg Kroah-Hartman

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

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

From: Babu Moger <[email protected]>

[ Upstream commit 84b4b620af7d24916add5d45104023bc5d804f53 ]

AMD's Assignable Bandwidth Monitoring Counters (ABMC) are configured via MSR_IA32_L3_QOS_ABMC_CFG. The cntr_id field selects the counter the configuration applies to. The number of counters a platform supports (the number of possible values written into that field) is enumerated separately via CPUID.

On platforms that enumerate more than 32 counters, the current 5-bit encoding truncates the counter ID and misprograms ABMC.

The section "Assignable Bandwidth Monitoring (ABMC)" in the APM has been updated to widen MSR_IA32_L3_QOS_ABMC_CFG.cntr_id from 5 bits to 12 bits.

The CPUID enumeration reports the maximum counter ID in a 16-bit field and may therefore report more counters than a 12-bit MSR_IA32_L3_QOS_ABMC_CFG.cntr_id can address.

Widen MSR_IA32_L3_QOS_ABMC_CFG.cntr_id to 12 bits to match the architecture. Cap the enumerated counter count at BIT(12) so every counter ID used by resctrl can be written to MSR_IA32_L3_QOS_ABMC_CFG.cntr_id without truncation.

[ bp: Massage and simplify commit message. ]

---
 arch/x86/kernel/cpu/resctrl/internal.h | 4 ++--
 arch/x86/kernel/cpu/resctrl/monitor.c  | 3 ++-
 2 files changed, 4 insertions(+), 3 deletions(-)
arch/x86/kernel/cpu/resctrl/internal.h +2 -2
index 6c9e75440c10e..6dd132414a95c 100644
@@ -201,8 +201,8 @@ union l3_qos_abmc_cfg {
 			      bw_src   :12,
 			      reserved1: 3,
 			      is_clos  : 1,
-			      cntr_id  : 5,
-			      reserved : 9,
+			      cntr_id  :12,
+			      reserved : 2,
 			      cntr_en  : 1,
 			      cfg_en   : 1;
 	} split;
arch/x86/kernel/cpu/resctrl/monitor.c +2 -1
index 9fc3adb4b232c..db0577d47b677 100644
@@ -476,7 +476,8 @@ int __init rdt_get_l3_mon_config(struct rdt_resource *r)
 	     rdt_cpu_has(X86_FEATURE_CQM_MBM_LOCAL))) {
 		r->mon.mbm_cntr_assignable = true;
 		cpuid_count(0x80000020, 5, &eax, &ebx, &ecx, &edx);
-		r->mon.num_mbm_cntrs = (ebx & GENMASK(15, 0)) + 1;
+		/* cntr_id is 12 bits and can only encode 4096 counters. */
+		r->mon.num_mbm_cntrs = min((ebx & GENMASK(15, 0)) + 1, BIT(12));
 		hw_res->mbm_cntr_assign_enabled = true;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#307 lore raw

PATCH 307/686 x86,fs/resctrl: Keep mbm_assign_mode in default mode at boot

In reply to Greg Kroah-Hartman

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

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

From: Babu Moger <[email protected]>

[ Upstream commit 7782a6a8dfc05f5622fdf616e5cf3df7d16eaef5 ]

The mbm_event mode assigns hardware MBM counters to RMID/event pairs. It is intended for deployments that need to manage counter assignment on platforms where the number of monitoring groups exceeds the available hardware counters. Hardware counters are scarce on these platforms, so mbm_event mode suits workflows that monitor a subset of groups at a time and rotate assignments as needed.

x86 resctrl enables the mbm_event mode by default on hardware that supports it. This breaks the pqos tool¹, which assumes the historical default mode. It creates 16 or more monitoring groups and uses two counters per group. On a platform with 32 counters per domain, that exhausts the mbm_event counters pool, causing additional groups to read "Unassigned". pqos interprets a non-numeric event read as zero bandwidth and reports 0 MB/s for those groups:

  $ sudo pqos -m all:0-4
  CORE         IPC      MISSES     LLC[KB]   MBL[MB/s]   MBR[MB/s]
     0        0.69         16k       192.0         0.0         0.0
     1        0.40          3k         0.0         0.0         0.0
     2        0.44          1k        64.0         0.0         0.0
     3        0.39          1k        64.0         0.0         0.0
     4        0.43          1k         0.0         0.0         0.0

Leave mbm_assign_mode in default mode during initialization as decided in the thread at the Link tag. Default mode uses one counter per monitoring group. On existing AMD platforms, the default active counters pool is 64 and may be larger on newer hardware. The active counters pool is the number of counters that the hardware can actively track in default mode.

Deployments within the active counters pool receive accurate bandwidth measurements in the default mode. Users can create more monitoring groups (for example, 4096 on current hardware) than there are active counters in the pool. Beyond that pool, readings may be misleading or report as "Unavailable", with no user-visible indication.

Default mode is still limited once the number of monitoring groups exceeds that active counters pool. After hardware re-allocates a counter, a read may return "Unavailable". pqos still treats "Unavailable" as zero. Successive reads can be a count, "Unavailable", then another count. pqos treats those jumps as wraparound and can report an inconsistent rate:

  $ sudo pqos -m all:0-4
  CORE     IPC      MISSES     LLC[KB]   MBL[MB/s]   MBR[MB/s]
  0        0.76         60k        32.0         0.0         0.0
  1        0.45          1k        32.0         0.0         0.0
  2        1.57        107k        64.0         0.0 17592186044184.9
  3        1.62        276k      4928.0         3.2         0.5

Users that need stable measurements beyond the active counters pool should use mbm_event mode and rotate assignments as needed. Enable it with:

  # echo mbm_event > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode

¹https://github.com/intel/intel-cmt-cat

[ bp: Massage commit message. ]

---
 Documentation/filesystems/resctrl.rst | 87 ++++++++++++++++-----------
 arch/x86/kernel/cpu/resctrl/monitor.c |  1 -
 2 files changed, 51 insertions(+), 37 deletions(-)
Documentation/filesystems/resctrl.rst +51 -36
index b7f35b07876a9..e48298f3babb8 100644
@@ -260,12 +260,12 @@ with the following files:
 "mbm_assign_mode":
 	The supported counter assignment modes. The enclosed brackets indicate which mode
 	is enabled. The MBM events associated with counters may reset when "mbm_assign_mode"
-	is changed.
+	is changed. See architecture specific notes below.
 	::
 
 	  # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
-	  [mbm_event]
-	  default
+	  [default]
+	  mbm_event
 
 	"mbm_event":
 
@@ -283,20 +283,17 @@ with the following files:
 	Moving to mbm_event counter assignment mode requires users to assign the counters
 	to the events. Otherwise, the MBM event counters will return 'Unassigned' when read.
 
-	The mode is beneficial for AMD platforms that support more CTRL_MON
-	and MON groups than available hardware counters. By default, this
-	feature is enabled on AMD platforms with the ABMC (Assignable Bandwidth
-	Monitoring Counters) capability, ensuring counters remain assigned even
-	when the corresponding RMID is not actively used by any processor.
+	It is intended for deployments that need to manage counter assignment on
+	platforms where the number of monitoring groups exceeds the available
+	hardware counters. Hardware counters are scarce on these platforms, so
+	mbm_event mode suits workflows that monitor a subset of groups at a time and
+	rotate assignments as needed. The mbm_event mode ensures counters remain
+	assigned even when the corresponding RMID is not actively used.
 
 	"default":
 
 	In default mode, resctrl assumes there is a hardware counter for each
-	event within every CTRL_MON and MON group. On AMD platforms, it is
-	recommended to use the mbm_event mode, if supported, to prevent reset of MBM
-	events between reads resulting from hardware re-allocating counters. This can
-	result in misleading values or display "Unavailable" if no counter is assigned
-	to the event.
+	event within every CTRL_MON and MON group.
 
 	* To enable "mbm_event" counter assignment mode:
 	  ::
@@ -308,6 +305,24 @@ with the following files:
 
 	    # echo "default" > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
 
+	In default mode on AMD platforms that support more CTRL_MON and MON groups
+	than hardware counters, hardware dynamically shares a smaller pool of
+	counters among RMIDs. One counter from this pool is used per monitoring
+	group and counts every MBM event of that group's RMID. The size of the pool
+	is not enumerated to software (unlike "num_mbm_cntrs"), and "num_rmids" may
+	be much larger. For example, 64 counters in this pool monitor 64 groups.
+	Newer hardware may provide a larger pool.
+
+	On such platforms, while the number of monitoring groups does not exceed
+	that pool, a counter stays attached to each RMID and readings remain
+	accurate. Creating more groups than the pool can cause hardware to
+	re-allocate those counters between successive reads of an event. Bandwidth
+	values may then be misleading, or a read may return "Unavailable" if no
+	counter is allocated to the RMID. There is no user-visible indication when
+	this begins. Users who need stable readings beyond that pool should switch
+	to mbm_event mode, if supported, and assign counters to the groups of
+	interest (rotating assignments as needed).
+
 "num_mbm_cntrs":
 	The maximum number of counters (total of available and assigned counters) in
 	each domain when the system supports mbm_event mode.
@@ -1639,17 +1654,19 @@ View the llc occupancy snapshot::
 Examples on working with mbm_assign_mode
 ========================================
 
-a. Check if MBM counter assignment mode is supported.
+a. Check if MBM counter assignment mode is supported. Enable "mbm_event"
+mode. Switching the mbm_assign_mode may reset all the MBM counters (and
+thus all MBM events) of all the resctrl groups.
 ::
 
-  # mount -t resctrl resctrl /sys/fs/resctrl/
-
+  # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
+  [default]
+  mbm_event
+  # echo "mbm_event" > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
   # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
   [mbm_event]
   default
 
-The "mbm_event" mode is detected and enabled.
-
 b. Check how many assignable counters are supported.
 ::
 
@@ -1660,36 +1677,39 @@ c. Check how many assignable counters are available for assignment in each domai
 ::
 
   # cat /sys/fs/resctrl/info/L3_MON/available_mbm_cntrs
-  0=30;1=30
+  0=32;1=32
 
-d. To list the default group's assign states.
+d. To list the default group's assign states. Counters are unassigned when the mode
+is switched to "mbm_event".
 ::
 
   # cat /sys/fs/resctrl/mbm_L3_assignments
-  mbm_total_bytes:0=e;1=e
-  mbm_local_bytes:0=e;1=e
+  mbm_total_bytes:0=_;1=_
+  mbm_local_bytes:0=_;1=_
 
-e.  To unassign the counter associated with the mbm_total_bytes event on domain 0.
+e. To assign the counter associated with the mbm_total_bytes event on domain 0
+in exclusive mode.
 ::
 
-  # echo "mbm_total_bytes:0=_" > /sys/fs/resctrl/mbm_L3_assignments
+  # echo "mbm_total_bytes:0=e" > /sys/fs/resctrl/mbm_L3_assignments
   # cat /sys/fs/resctrl/mbm_L3_assignments
-  mbm_total_bytes:0=_;1=e
-  mbm_local_bytes:0=e;1=e
+  mbm_total_bytes:0=e;1=_
+  mbm_local_bytes:0=_;1=_
 
 f. To unassign the counter associated with the mbm_total_bytes event on all domains.
 ::
 
   # echo "mbm_total_bytes:*=_" > /sys/fs/resctrl/mbm_L3_assignments
-  # cat /sys/fs/resctrl/mbm_L3_assignment
+  # cat /sys/fs/resctrl/mbm_L3_assignments
   mbm_total_bytes:0=_;1=_
-  mbm_local_bytes:0=e;1=e
+  mbm_local_bytes:0=_;1=_
 
-g. To assign a counter associated with the mbm_total_bytes event on all domains in
-exclusive mode.
+g. To assign a counter associated with the mbm_total_bytes and mbm_local_bytes
+events on all domains in exclusive mode.
 ::
 
   # echo "mbm_total_bytes:*=e" > /sys/fs/resctrl/mbm_L3_assignments
+  # echo "mbm_local_bytes:*=e" > /sys/fs/resctrl/mbm_L3_assignments
   # cat /sys/fs/resctrl/mbm_L3_assignments
   mbm_total_bytes:0=e;1=e
   mbm_local_bytes:0=e;1=e
@@ -1746,13 +1766,8 @@ the MBM counters (and thus all MBM events) of all the resctrl groups.
 
   # echo "default" > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
   # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
-  mbm_event
   [default]
-
-m. Unmount the resctrl filesystem.
-::
-
-  # umount /sys/fs/resctrl/
+  mbm_event
 
 Intel RDT Errata
 ================
arch/x86/kernel/cpu/resctrl/monitor.c +0 -1
index db0577d47b677..d16253607ac47 100644
@@ -478,7 +478,6 @@ int __init rdt_get_l3_mon_config(struct rdt_resource *r)
 		cpuid_count(0x80000020, 5, &eax, &ebx, &ecx, &edx);
 		/* cntr_id is 12 bits and can only encode 4096 counters. */
 		r->mon.num_mbm_cntrs = min((ebx & GENMASK(15, 0)) + 1, BIT(12));
-		hw_res->mbm_cntr_assign_enabled = true;
 	}
 
 	r->mon_capable = true;
Signature · 1 line
2.53.0
author maintainer
#308 lore raw

PATCH 308/686 mm/khugepaged: flush deferred unmaps before dropping a failed folio

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

[ Upstream commit 854e5ff8b3ce2a776586cabebaeae645c992345b ]

collapse_file() can fail its reference-count or dirty-folio check after unmapping with TTU_BATCH_FLUSH. Both paths put back the isolated folio, then unlock it and drop the lookup reference before reaching the common try_to_unmap_flush().

The page-cache reference does not keep the folio stable once the lock is released. Another collapse can replace and free it. With its PTEs already gone, that collapse cannot flush the first task's per-task TLB batch, and retract_page_tables() skips short or unaligned VMAs. A CPU can therefore retain a user translation to the freed folio. This has been reproduced with unprivileged MADV_COLLAPSE on a memfd.

Flush at out_unlock while the lookup reference and folio lock are still held. The common flush continues to cover the accumulated pagelist on both success and rollback, preserving batching on successful collapses.

Fixes 6d9df8a5889c ("mm/thp: collapse_file() do try_to_unmap(TTU_BATCH_FLUSH)")
Assisted-by LLM
Cc Barry Song <[email protected]>
Cc Dev Jain <[email protected]>
Cc Kiryl Shutsemau <[email protected]>
Cc Lance Yang <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc Nico Pache <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Usama Arif <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
---
 mm/khugepaged.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
mm/khugepaged.c +7 -3
index cc3a09a0c2596..8ed9b2a3e8f07 100644
@@ -2068,6 +2068,11 @@ static int collapse_file(struct mm_struct *mm, unsigned long addr,
 		index += folio_nr_pages(folio);
 		continue;
 out_unlock:
+		/*
+		 * The folio may have been unmapped with TTU_BATCH_FLUSH.
+		 * Flush before releasing the lock and our last reference.
+		 */
+		try_to_unmap_flush();
 		folio_unlock(folio);
 		folio_put(folio);
 		goto xa_unlocked;
@@ -2078,9 +2083,8 @@ static int collapse_file(struct mm_struct *mm, unsigned long addr,
 xa_unlocked:
 
 	/*
-	 * If collapse is successful, flush must be done now before copying.
-	 * If collapse is unsuccessful, does flush actually need to be done?
-	 * Do it anyway, to clear the state.
+	 * Flush before copying the folios, or releasing them in rollback.
+	 * This is a no-op if out_unlock already flushed the batch.
 	 */
 	try_to_unmap_flush();
 
Signature · 1 line
2.53.0
author maintainer
#309 lore raw

PATCH 309/686 mm/page-writeback: avoid 32-bit overflow in dirty threshold shares

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 9597c2056e05bd79df9d343a9b42e84a54de1c52 ]

The ratios used by __wb_calc_thresh() are scaled to parts per million, but the threshold and ratio operands are unsigned long. On 32-bit kernels, their multiplication can wrap before the result is assigned to u64.

For example, with a threshold of 25600 pages and the default maximum ratio of 1000000, wb_max_thresh becomes 4125 pages instead of 25600. The shared threshold and minimum share calculations can overflow in the same way, producing incorrect per-writeback dirty limits.

Use a u64 threshold for the three ratio multiplications and div_u64() to retain the existing division order and rounding.

Fixes ae82291e9ca4 ("mm: use part per 1000000 for bdi ratios")
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Stefan Roesch <[email protected]>
---
 mm/page-writeback.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
mm/page-writeback.c +5 -3
index 757bc4d3b5b55..17b12b4c4b667 100644
@@ -902,6 +902,7 @@ static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc,
 {
 	struct wb_domain *dom = dtc_dom(dtc);
 	struct bdi_writeback *wb = dtc->wb;
+	u64 threshold = thresh;
 	u64 wb_thresh;
 	u64 wb_max_thresh;
 	unsigned long numerator, denominator;
@@ -913,13 +914,14 @@ static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc,
 	fprop_fraction_percpu(&dom->completions, dtc->wb_completions,
 			      &numerator, &denominator);
 
-	wb_thresh = (thresh * (100 * BDI_RATIO_SCALE - bdi_min_ratio)) / (100 * BDI_RATIO_SCALE);
+	wb_thresh = div_u64(threshold * (100 * BDI_RATIO_SCALE - bdi_min_ratio),
+			    100 * BDI_RATIO_SCALE);
 	wb_thresh *= numerator;
 	wb_thresh = div64_ul(wb_thresh, denominator);
 
 	wb_min_max_ratio(wb, &wb_min_ratio, &wb_max_ratio);
 
-	wb_thresh += (thresh * wb_min_ratio) / (100 * BDI_RATIO_SCALE);
+	wb_thresh += div_u64(threshold * wb_min_ratio, 100 * BDI_RATIO_SCALE);
 
 	/*
 	 * It's very possible that wb_thresh is close to 0 not because the
@@ -935,7 +937,7 @@ static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc,
 			wb_thresh = max(wb_thresh, (thresh - dtc->dirty) / 8);
 	}
 
-	wb_max_thresh = thresh * wb_max_ratio / (100 * BDI_RATIO_SCALE);
+	wb_max_thresh = div_u64(threshold * wb_max_ratio, 100 * BDI_RATIO_SCALE);
 	if (wb_thresh > wb_max_thresh)
 		wb_thresh = wb_max_thresh;
 
Signature · 1 line
2.53.0
author maintainer
#310 lore raw

PATCH 310/686 mm/hugetlb: fix mremap move length truncation

In reply to Greg Kroah-Hartman

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

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

From: Li Zhe <[email protected]>

[ Upstream commit dfb190302d2b4af86c6ae48af0d3b09f28b35460 ]

Patch series "mm/hugetlb: fix mremap bugs", v3.

This series fixes a few hugetlb mremap bugs.

Patch 1 fixes the return type of move_hugetlb_page_tables(), so large hugetlb moves cannot be truncated when reported back to the generic mremap code.

Patch 2 disables hugetlb PMD sharing for UFFD missing mode, so UFFDIO_POISON markers cannot become visible through shared PMD page tables.

Patch 3 fixes the recursive i_mmap_rwsem deadlock in the hugetlb mremap path by avoiding the destination PMD sharing allocation path while the mapping lock is already held for write.

This patch (of 3):

move_hugetlb_page_tables() returns the number of bytes moved, but its return type is int while the generic move_page_tables() path uses unsigned long lengths.

A hugetlb mremap() move length above INT_MAX can therefore be misreported to copy_vma_and_data(). The out-of-range conversion to int is implementation-defined; on common 64-bit builds, for example, a 4 GiB move can be reported as zero, making the caller treat the move as a failure and use the wrong length for rollback.

Return unsigned long from move_hugetlb_page_tables(), matching move_page_tables() and preserving the full byte count.

Fixes 550a7d60bd5e ("mm, hugepages: add mremap() support for hugepage backed vma")
Cc Muchun Song <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Peter Xu <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Jose A. Perez de Azpillaga <[email protected]>
---
 include/linux/hugetlb.h | 15 ++++++---------
 mm/hugetlb.c            |  7 +++----
 2 files changed, 9 insertions(+), 13 deletions(-)
include/linux/hugetlb.h +6 -9
index ca6d6eb817118..d43965f4b6c82 100644
@@ -122,10 +122,9 @@ void hugepage_put_subpool(struct hugepage_subpool *spool);
 
 void hugetlb_dup_vma_private(struct vm_area_struct *vma);
 void clear_vma_resv_huge_pages(struct vm_area_struct *vma);
-int move_hugetlb_page_tables(struct vm_area_struct *vma,
-			     struct vm_area_struct *new_vma,
-			     unsigned long old_addr, unsigned long new_addr,
-			     unsigned long len);
+unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
+		struct vm_area_struct *new_vma, unsigned long old_addr,
+		unsigned long new_addr, unsigned long len);
 int copy_hugetlb_page_range(struct mm_struct *, struct mm_struct *,
 			    struct vm_area_struct *, struct vm_area_struct *);
 void unmap_hugepage_range(struct vm_area_struct *,
@@ -340,11 +339,9 @@ static inline int copy_hugetlb_page_range(struct mm_struct *dst,
 	return 0;
 }
 
-static inline int move_hugetlb_page_tables(struct vm_area_struct *vma,
-					   struct vm_area_struct *new_vma,
-					   unsigned long old_addr,
-					   unsigned long new_addr,
-					   unsigned long len)
+static inline unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
+		struct vm_area_struct *new_vma, unsigned long old_addr,
+		unsigned long new_addr, unsigned long len)
 {
 	BUG();
 	return 0;
mm/hugetlb.c +3 -4
index 42aace6e3ca17..1d71352bfec57 100644
@@ -5828,10 +5828,9 @@ static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr,
 	spin_unlock(dst_ptl);
 }
 
-int move_hugetlb_page_tables(struct vm_area_struct *vma,
-			     struct vm_area_struct *new_vma,
-			     unsigned long old_addr, unsigned long new_addr,
-			     unsigned long len)
+unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
+		struct vm_area_struct *new_vma, unsigned long old_addr,
+		unsigned long new_addr, unsigned long len)
 {
 	struct hstate *h = hstate_vma(vma);
 	struct address_space *mapping = vma->vm_file->f_mapping;
Signature · 1 line
2.53.0
author maintainer
#311 lore raw

PATCH 311/686 mm/hugetlb: fix mremap deadlock when PMD sharing is possible

In reply to Greg Kroah-Hartman

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

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

From: Li Zhe <[email protected]>

[ Upstream commit 92daa8652f88c8cfc05f4899a8408a04b02f211e ]

move_hugetlb_page_tables() holds the mapping's i_mmap_rwsem for write while moving hugetlb PTEs. This prevents races with truncation and protects huge_pmd_unshare(), but the move loop must not call helpers that can acquire the same rwsem for read.

huge_pte_alloc() can do that when the destination can use PMD
sharing: it may call huge_pmd_share(), which takes i_mmap_rwsem for read while searching for a shareable PMD table. Calling it while the move path already holds i_mmap_rwsem for write can deadlock.

Avoid that path for PMD-sized hugetlb mappings that can use PMD sharing. Instead of allocating or sharing the destination page table while moving, zap the source range and let the destination fault path populate or share the PMD lazily.

Reuse the hugetlb unmap logic for the source-side zap by splitting the core loop out of __unmap_hugepage_range(). The wrapper keeps the existing tlb_start_vma(), tlb_end_vma() and huge_pmd_unshare_flush() behavior, while move_hugetlb_page_tables() can reuse the unmap loop with its existing mmu_gather.

Fixes 550a7d60bd5e ("mm, hugepages: add mremap() support for hugepage backed vma")
Cc Muchun Song <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Peter Xu <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Jose A. Perez de Azpillaga <[email protected]>
---
 mm/hugetlb.c | 47 +++++++++++++++++++++++++++++++++++++----------
 1 file changed, 37 insertions(+), 10 deletions(-)
mm/hugetlb.c +37 -10
index 1d71352bfec57..bf1188e9b1c9b 100644
@@ -126,6 +126,10 @@ static int __huge_pmd_unshare(struct mmu_gather *tlb,
 		bool check_locks);
 static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
 		unsigned long start, unsigned long end, bool take_locks);
+static void hugetlb_unmap_range(struct mmu_gather *tlb,
+				struct vm_area_struct *vma, unsigned long start,
+				unsigned long end, struct folio *folio,
+				zap_flags_t zap_flags);
 static struct resv_map *vma_resv_map(struct vm_area_struct *vma);
 
 static void hugetlb_free_folio(struct folio *folio)
@@ -5860,6 +5864,8 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
 	for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
 		const unsigned long offset_to_last_entry =
 			(old_addr | last_addr_mask) - old_addr;
+		const unsigned long offset_to_last_dst_entry =
+			(new_addr | last_addr_mask) - new_addr;
 
 		src_pte = hugetlb_walk(vma, old_addr, sz);
 		if (!src_pte) {
@@ -5876,6 +5882,24 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
 			continue;
 		}
 
+		/*
+		 * Avoid entering the destination PMD sharing path while holding
+		 * i_mmap_rwsem for write. Leave destination page table
+		 * population to the fault path, which can share the PMD lazily.
+		 */
+		if (sz == PMD_SIZE && want_pmd_share(new_vma, new_addr)) {
+			const unsigned long unmap_size =
+				min(old_end - old_addr,
+				    offset_to_last_dst_entry + sz);
+
+			hugetlb_unmap_range(&tlb, vma, old_addr,
+					    old_addr + unmap_size, NULL,
+					    ZAP_FLAG_DROP_MARKER);
+			old_addr += unmap_size - sz;
+			new_addr += unmap_size - sz;
+			continue;
+		}
+
 		dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
 		if (!dst_pte)
 			break;
@@ -5895,9 +5919,10 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
 	return len + old_addr - old_end;
 }
 
-void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
-			    unsigned long start, unsigned long end,
-			    struct folio *folio, zap_flags_t zap_flags)
+static void hugetlb_unmap_range(struct mmu_gather *tlb,
+				struct vm_area_struct *vma, unsigned long start,
+				unsigned long end, struct folio *folio,
+				zap_flags_t zap_flags)
 {
 	struct mm_struct *mm = vma->vm_mm;
 	const bool folio_provided = !!folio;
@@ -5915,13 +5940,6 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
 	BUG_ON(start & ~huge_page_mask(h));
 	BUG_ON(end & ~huge_page_mask(h));
 
-	/*
-	 * This is a hugetlb vma, all the pte entries should point
-	 * to huge page.
-	 */
-	tlb_change_page_size(tlb, sz);
-	tlb_start_vma(tlb, vma);
-
 	last_addr_mask = hugetlb_mask_last_page(h);
 	address = start;
 	for (; address < end; address += sz) {
@@ -6050,6 +6068,15 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
 		if (folio_provided)
 			break;
 	}
+}
+
+void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
+			    unsigned long start, unsigned long end,
+			    struct folio *folio, zap_flags_t zap_flags)
+{
+	tlb_change_page_size(tlb, huge_page_size(hstate_vma(vma)));
+	tlb_start_vma(tlb, vma);
+	hugetlb_unmap_range(tlb, vma, start, end, folio, zap_flags);
 	tlb_end_vma(tlb, vma);
 
 	huge_pmd_unshare_flush(tlb, vma);
Signature · 1 line
2.53.0
author maintainer
#312 lore raw

PATCH 312/686 mm/page_alloc: mark pages freed by __free_pages_core() as not tagged

In reply to Greg Kroah-Hartman

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

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

From: Zenghui Yu (Huawei) <[email protected]>

[ Upstream commit b6732c6d43139ea56de8bc62e87ace8543ef784f ]

Onlining hotplugged memory (e.g., a dev_dax device bound to kmem) with CONFIG_MEM_ALLOC_PROFILING_DEBUG triggers:

alloc_tag was not set

  WARNING: ./include/linux/alloc_tag.h:166 at __pgalloc_tag_sub+0x1fc/0x254
  Call trace:
   __pgalloc_tag_sub+0x1fc/0x254 (P)
   __free_pages_ok+0x14c/0x6ac
   __free_pages_core+0xa8/0x188
   generic_online_page+0x14/0x20
   online_pages+0x220/0x3b0
   memory_subsys_online+0xfc/0x198
   device_online+0x58/0xe0
   state_store+0xf0/0xf8

Pages entering the buddy through __free_pages_core() have never been allocated, so their allocation tag references are NULL. The free path, __free_pages_prepare() -> pgalloc_tag_sub(), expects a valid tag or a CODETAG_EMPTY mark and warns otherwise. Paths feeding never-allocated pages into the buddy are therefore expected to mark them with clear_page_tag_ref() first, like init_cma_reserved_pageblock() and free_reserved_pages() do; of __free_pages_core()'s callers only memblock_free_pages() clears the tag ref itself, and the hotplug onlining path was missed.

Since all __free_pages_core() callers free never-allocated pages, mark the head page as not tagged in __free_pages_core() itself instead of relying on each caller, and drop the now-redundant clearing from memblock_free_pages().

Fixes dcfe378c81f7 ("lib: introduce support for page allocation tagging")
Cc Mike Rapoport <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Brendan Jackman <[email protected]>
Cc Zi Yan <[email protected]>
---
 mm/mm_init.c    | 2 --
 mm/page_alloc.c | 3 +++
 2 files changed, 3 insertions(+), 2 deletions(-)
mm/mm_init.c +0 -2
index a27ba1c1a7192..4e00624e3c7b5 100644
@@ -2524,8 +2524,6 @@ void __init memblock_free_pages(struct page *page, unsigned long pfn,
 		return;
 	}
 
-	/* pages were reserved and not allocated */
-	clear_page_tag_ref(page);
 	__free_pages_core(page, order, MEMINIT_EARLY);
 }
 
mm/page_alloc.c +3 -0
index 8d608699bf508..2685e570bf7de 100644
@@ -1662,6 +1662,9 @@ void __meminit __free_pages_core(struct page *page, unsigned int order,
 		atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
 	}
 
+	/* pages were never allocated */
+	clear_page_tag_ref(page);
+
 	if (page_contains_unaccepted(page, order)) {
 		if (order == MAX_PAGE_ORDER && __free_unaccepted(page))
 			return;
Signature · 1 line
2.53.0
author maintainer
#313 lore raw

PATCH 313/686 mm/ksm: keep soft-dirty when merging a page

In reply to Greg Kroah-Hartman

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

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

From: Samarth Narang <[email protected]>

[ Upstream commit 2efc6332f18bfd848f74f3d5ba45b31450601faa ]

replace_page() maps the KSM page with a PTE built from scratch, so the soft-dirty bit of the PTE it replaces is lost. A page written since "clear_refs 4" then no longer shows as soft-dirty once it is merged, and a soft-dirty based dumper treats it as unchanged.

Copy the soft-dirty bit from the original PTE to the new PTE.

Fixes 0f8975ec4db2 ("mm: soft-dirty bits for user memory changes tracking")
Assisted-by LLM
Cc Xu Xin <[email protected]>
Cc Chengming Zhou <[email protected]>
Cc Peter Xu <[email protected]>
Cc Kiryl Shutsemau <[email protected]>
Cc Mike Rapoport <[email protected]>
---
 mm/ksm.c | 4 ++++
 1 file changed, 4 insertions(+)
mm/ksm.c +4 -0
index 80274ace8155e..1eee363fd727e 100644
@@ -1414,6 +1414,10 @@ static int replace_page(struct vm_area_struct *vma, struct page *page,
 		dec_mm_counter(mm, MM_ANONPAGES);
 	}
 
+	/* Preserve soft-dirty when replacing the page. */
+	if (pte_soft_dirty(orig_pte))
+		newpte = pte_mksoft_dirty(newpte);
+
 	flush_cache_page(vma, addr, pte_pfn(ptep_get(ptep)));
 	/*
 	 * No need to notify as we are replacing a read only page with another
Signature · 1 line
2.53.0
author maintainer
#314 lore raw

PATCH 314/686 fs/proc/task_mmu: return -ENOTTY for unknown pagemap ioctls

In reply to Greg Kroah-Hartman

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

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

From: Hengyu Liang <[email protected]>

[ Upstream commit bfc1d9724c78aa7570dbeb17207a21089f2d1b1a ]

Commit 52526ca7fdb9 ("fs/proc/task_mmu: implement IOCTL to get and optionally clear info about PTEs") made do_pagemap_cmd() the ioctl handler of /proc/<pid>/pagemap.

However, do_pagemap_cmd() returns -EINVAL for every command other than PAGEMAP_SCAN. Before that commit, pagemap had no ioctl handler, and the VFS returned -ENOTTY for these commands. As of now, they fail with EINVAL, so tcgetattr() and isatty() on pagemap report EINVAL instead of ENOTTY.

The issue can be reproduced with a simple C program:

    #include <fcntl.h>
    #include <stdio.h>
    #include <termios.h>

    int main(void)
    {
            struct termios t;
            int fd = open("/proc/self/pagemap", O_RDONLY);

            if (tcgetattr(fd, &t) < 0)
                    perror("tcgetattr");
            return 0;
    }

Before that commit, the result is:

tcgetattr: Inappropriate ioctl for device

After that commit, the result is:

tcgetattr: Invalid argument

This patch will return -ENOIOCTLCMD for unknown commands, as procfs_procmap_ioctl() in the same file does, so that the VFS turns it into -ENOTTY.

Fixes 52526ca7fdb9 ("fs/proc/task_mmu: implement IOCTL to get and optionally clear info about PTEs")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Jann Horn <[email protected]>
Cc Muhammad Usama Anjum <[email protected]>
Cc Andrei Vagin <[email protected]>
Cc Michał Mirosław <[email protected]>
Cc Arnd Bergmann <[email protected]>
---
 fs/proc/task_mmu.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/proc/task_mmu.c +1 -1
index 0f08913cfa529..823e8ee1b0953 100644
@@ -3179,7 +3179,7 @@ static long do_pagemap_cmd(struct file *file, unsigned int cmd,
 		return do_pagemap_scan(mm, arg);
 
 	default:
-		return -EINVAL;
+		return -ENOIOCTLCMD;
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#315 lore raw

PATCH 315/686 mm/damon/sysfs-schemes: hold damon_sysfs_lock in target_metric_store()

In reply to Greg Kroah-Hartman

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

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

From: SJ Park <[email protected]>

[ Upstream commit a76adcace3550b16e5735ba4a5e95a9c2664e113 ]

Patch series "mm/damon: fix three race bugs in sysfs and core", v1.

There are three race condition bugs in DAMON sysfs interface and the core layer. User impacts are not critical but better to fix sooner than later.

Patch 1 fixes a toctou bug in DAMON sysfs interface that can mess up DAMOS auto-tuning. Patches 2 and 3 move static variables that can be wrongly shared with multiple kdamonds and therefore make DAMON monitoring results be a little more indeterministic.

This patch (of 3):

damon_sysfs_add_quota_score() reads damos_sysfs_quota_goal->metric twice, once to set damos_quota_goal->metric to the value, and once again to set the metric-dependent damos_quota_goal unions based on the value.

target_metrics_score() can update damos_sysfs_quota_goal->metric between the two reads. This time-of-check to time-of-use (toctou) race can make the union fields incorrectly set. The incorrect damos_quota_goal will be passed to the core layer and make DAMOS incorrectly behave.

Users could reproduce the race by writing a new value to the target_metric sysfs file while DAMON is starting, or online parameters update is ongoing. The issue will only rarely happen in the real use cases. It requires sysfs write permission. The race window is short. Sane users wouldn't do such writes while DAMON enablement and/or online parameters update is ongoing.

The user impact is not very critical. The race is not easy to unintentionally trigger. No leak or crash happens. Nonetheless, DAMOS could be unexpectedly more or less aggressive and does not achieve the auto-tune goal. Because of the nature of races, investigating will be difficult. Users can control the impact from unexpected aggressiveness using additional quotas and resolve the issue in runtime by re-installing the quota goal, though.

Avoid the race by protecting damos_sysfs_quota_goal->metric write in target_metric_store() with damon_sysfs_lock. Because damon_sysfs_add_quota_score() is called while holding the same lock, the race is removed.

The issue was discovered as a part of a bug report [1] from Sashiko, which is partially outdated. In more detail, the Sashiko report [1] was mainly for an outdated bug [2]. But it was also mentioning the issue of this patch as a similar class bug.

---
 mm/damon/sysfs-schemes.c | 3 +++
 1 file changed, 3 insertions(+)
mm/damon/sysfs-schemes.c +3 -0
index 952e12fd6dbf7..f90d079dc9628 100644
@@ -1072,7 +1072,10 @@ static ssize_t target_metric_store(struct kobject *kobj,
 
 		metric_name = &damos_sysfs_qgoal_metric_names[i];
 		if (sysfs_streq(buf, metric_name->name)) {
+			if (!mutex_trylock(&damon_sysfs_lock))
+				return -EBUSY;
 			goal->metric = metric_name->metric;
+			mutex_unlock(&damon_sysfs_lock);
 			return count;
 		}
 	}
Signature · 1 line
2.53.0
author maintainer
#316 lore raw

PATCH 316/686 mm: make swapoff interruptible when unusing mms/shmem

In reply to Greg Kroah-Hartman

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

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

From: Chris Down <[email protected]>

[ Upstream commit 740128dd1a3f2bd81a80314d079b6b03c39ba3af ]

try_to_unuse() only checks for a pending signal between mms, and shmem_unuse() doesn't check at all. That means that once swapoff gets to a process or a shmem file with a lot swapped out, nothing can interrupt it until every last page of it has been read back in.

Just as one example of where this can concretely show up, freezing tasks for suspend or hibernation has to wait for swapoff to notice the freezer's fake signal, and gives up after freeze_timeout_msecs (20 seconds by default).

Here's a facetious example where one swaps out 2GiB of one process to a swap file on ext4, starts swapoff, and half a second later tries to freeze with pm_test=freezer. Writing to /sys/power/state then fails with EBUSY and this in dmesg:

    Freezing user space processes failed after 20.003 seconds (1 tasks refusing to freeze, wq_busy=0):
    task:swapoff         state:D stack:0     pid:3175  tgid:3175  ppid:2955   task_flags:0x400100 flags:0x00000419
    Call trace:
     [...]
     io_schedule+0x44/0x70
     folio_wait_bit_common+0x1ec/0x3d0
     __folio_lock+0x24/0x40
     unuse_pte_range+0x2d0/0x348
     unuse_vma+0x158/0x248
     unuse_mm+0xfc/0x150
     try_to_unuse+0x104/0x3f8
     __do_sys_swapoff+0x220/0x5d8
     [...]

The same goes for anything else that wants swapoff to stop, like an admin hitting ^C in a panic, of course.

Prior to commit b56a2d8af914 ("mm: rid swapoff of quadratic complexity") try_to_unuse() was driven by find_next_to_unuse() which checks for a signal before every entry, so let's restore that behaviour.

Just as an example of the improvements, here's how long freezing takes in the same test while swapoff is happening on my computer:

                      before                  after
    400MiB anon       8.925s                  0.028s
    400MiB shmem      1.639s                  0.003s
    2GiB anon         failed after 20.003s    0.011s
Fixes b56a2d8af914 ("mm: rid swapoff of quadratic complexity")
Cc Hugh Dickins <[email protected]>
Cc Chris Li <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Baoquan He <[email protected]>
Cc Barry Song <[email protected]>
Cc Youngjun Park <[email protected]>
Cc Ying Huang <[email protected]>
Cc Kelley Nielsen <[email protected]>
Cc Rafael J. Wysocki <[email protected]>
---
 mm/shmem.c    | 4 ++++
 mm/swapfile.c | 4 +++-
 2 files changed, 7 insertions(+), 1 deletion(-)
mm/shmem.c +4 -0
index da043ca0c2e22..5efde9fcc3057 100644
@@ -1519,6 +1519,10 @@ static int shmem_unuse_inode(struct inode *inode, unsigned int type)
 		if (ret < 0)
 			break;
 
+		if (signal_pending(current)) {
+			ret = -ERESTARTSYS;
+			break;
+		}
 		start = indices[folio_batch_count(&fbatch) - 1];
 	} while (true);
 
mm/swapfile.c +3 -1
index 3ffa258de79ec..3a786446dacbe 100644
@@ -2349,6 +2349,8 @@ static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
 	pmd = pmd_offset(pud, addr);
 	do {
 		cond_resched();
+		if (signal_pending(current))
+			return -ERESTARTSYS;
 		next = pmd_addr_end(addr, end);
 		ret = unuse_pte_range(vma, pmd, addr, next, type);
 		if (ret)
@@ -2562,7 +2564,7 @@ static int try_to_unuse(unsigned int type)
 	if (swap_usage_in_pages(si)) {
 		if (!signal_pending(current))
 			goto retry;
-		return -EINTR;
+		return -ERESTARTSYS;
 	}
 
 success:
Signature · 1 line
2.53.0
author maintainer
#317 lore raw

PATCH 317/686 mm/migrate: untag addresses when querying page nodes

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 7d8746d7dc9cc4003661011424e5880ea7ae364b ]

When move_pages() is used with nodes == NULL, do_pages_stat_array() passes each page address directly to vma_lookup(). A valid tagged address therefore fails the VMA lookup and gets -EFAULT in its status entry, instead of the node reported for the corresponding untagged address.

The tagged address ABI permits these pointers, and the migration path already removes their tags. Apply the target mm's untagging rules to the query path as well, while holding its mmap read lock.

---
 mm/migrate.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/migrate.c +1 -1
index 08f1382318024..0d2b327368073 100644
@@ -2448,7 +2448,7 @@ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
 	mmap_read_lock(mm);
 
 	for (i = 0; i < nr_pages; i++) {
-		unsigned long addr = (unsigned long)(*pages);
+		unsigned long addr = (unsigned long)untagged_addr_remote(mm, *pages);
 		struct vm_area_struct *vma;
 		struct folio_walk fw;
 		struct folio *folio;
Signature · 1 line
2.53.0
author maintainer
#318 lore raw

PATCH 318/686 mm/migrate: snapshot the source nid before the misplaced migration

In reply to Greg Kroah-Hartman

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

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

From: Yafang Shao <[email protected]>

[ Upstream commit fe623a81ad9eddf10059b4e44bca0440d9120613 ]

A successful migration frees the source folio before the promotion counter update, so the folio_nid() read there operates on a freed folio — which may already have been reallocated. It happens to work today, as Zi explained:

: Strictly speaking, it can be seen as a benign UAF. It works, because : 1. folio->flags happens to be the same as page->flags,
: 2. folio/page nid is stored in the ->flags and never changed. :
: In memdesc world, after a folio is freed, I assume folio->flags would be : zeroed since struct folio is freed and calling folio_nid() on a freed : folio would give a bogus result (yeah, it can be mitigated by not : zeroing node field and each node has its own struct folio pool, but that : makes folio_nid() implementation dependent).

and Matthew explained further:

: once struct folio is separately allocated, it's a UAF. It could be : recycled to a different NID or maybe the slab containing the folio could : be freed (assuming we're not holding the RCU read lock at this point in : migration, and I don't see why we would be).

A separate concern is memory hot-removal. With memory-tiering mode enabled, successful migration can release the source before the promotion-accounting folio_nid() read. If the task is preempted there, an otherwise-free source block can be offlined and removed first. On the x86 path, removal can unmap the source's vmemmap, so the later read can fault. The snapshot avoids that read.

Fixes e39bb6be9f2b ("NUMA Balancing: add page promotion counter")
Cc Ying Huang <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Matthew Brost <[email protected]>
Cc Joshua Hahn <[email protected]>
Cc Byungchul Park <[email protected]>
Cc Gregory Price <[email protected]>
Cc Alistair Popple <[email protected]>
---
 mm/migrate.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/migrate.c +2 -1
index 0d2b327368073..2a5846a86baf8 100644
@@ -2737,6 +2737,7 @@ int migrate_misplaced_folio(struct folio *folio, int node)
 	pg_data_t *pgdat = NODE_DATA(node);
 	int nr_remaining;
 	unsigned int nr_succeeded;
+	int src_node = folio_nid(folio);
 	LIST_HEAD(migratepages);
 	struct mem_cgroup *memcg = get_mem_cgroup_from_folio(folio);
 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
@@ -2751,7 +2752,7 @@ int migrate_misplaced_folio(struct folio *folio, int node)
 		count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
 		count_memcg_events(memcg, NUMA_PAGE_MIGRATE, nr_succeeded);
 		if ((sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
-		    && !node_is_toptier(folio_nid(folio))
+		    && !node_is_toptier(src_node)
 		    && node_is_toptier(node))
 			mod_lruvec_state(lruvec, PGPROMOTE_SUCCESS, nr_succeeded);
 	}
Signature · 1 line
2.53.0
author maintainer
#319 lore raw

PATCH 319/686 mm/vma: update VMA iterator state on error in new VMA merge

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 168ed9c5d5ec2fd326715eba5750c2b69e559ff3 ]

Commit cacded5e42b9 ("mm: avoid using vma_merge() for new VMAs") shared code between vma_merge_new_range() and vma_expand().

However in doing so, it failed to correctly restore the VMA iterator when vma_expand() errors out.

This is a problem when the immediately preceding VMA is mergeable and vmg->just_expand isn't specified, at which point the VMA iterator is moved to the previous VMA.

(Note that vmg->just_expand is a special case for brk(), where the iterator will already be positioned at the VMA to be expanded.)

Resolve things by restoring the VMA iterator on error. Use vma_iter_next_range() to do this, so it will correctly stop on the gap after the previous VMA, rather than skip to the next VMA after it (this is a new VMA merge, so is being applied at a gap).

To isolate the error handling, return early when a merge isn't possible (what the vmg->target check was doing before), then handle the merge success/failure case explicitly.

While here, update vma_expand() to jump to the nomem case when dup_anon_vma() fails, so vmg->state is correctly updated.

This doesn't impact anything in practice, but is the correct course and since it's part of the error path that this patch addresses, it makes sense to update it also.

Users are very unlikely to have observed the issue this patch addresses in practice, as it is near-impossible to fail an allocation for an anon_vma, but a process under memory pressure that receives a fatal signal could trigger it.

This issue was originally reported by Li Jinyue for which I am grateful. He indicated this was uncovered by a private syzkaller instance.

---
 mm/vma.c | 28 ++++++++++++++++++----------
 1 file changed, 18 insertions(+), 10 deletions(-)
mm/vma.c +18 -10
index d1627a8ef32b1..dadf7d69182c2 100644
@@ -1046,6 +1046,7 @@ struct vm_area_struct *vma_merge_new_range(struct vma_merge_struct *vmg)
 	struct vm_area_struct *next = vmg->next;
 	unsigned long end = vmg->end;
 	bool can_merge_left, can_merge_right;
+	bool move_iter_back = false;
 
 	mmap_assert_write_locked(vmg->mm);
 	VM_WARN_ON_VMG(vmg->middle, vmg);
@@ -1083,23 +1084,30 @@ struct vm_area_struct *vma_merge_new_range(struct vma_merge_struct *vmg)
 			vmg->end = end;
 
 		/* In expand-only case we are already positioned at prev. */
-		if (!vmg->just_expand) {
-			/* Equivalent to going to the previous range. */
-			vma_prev(vmg->vmi);
-		}
+		if (!vmg->just_expand)
+			move_iter_back = true;
 	}
 
+	if (!can_merge_left && !can_merge_right)
+		return NULL;
+
+	if (move_iter_back)
+		vma_prev(vmg->vmi);
+
 	/*
 	 * Now try to expand adjacent VMA(s). This takes care of removing the
 	 * following VMA if we have VMAs on both sides.
 	 */
-	if (vmg->target && !vma_expand(vmg)) {
-		khugepaged_enter_vma(vmg->target, vmg->vm_flags);
-		vmg->state = VMA_MERGE_SUCCESS;
-		return vmg->target;
+	if (vma_expand(vmg)) {
+		/* Error occurred, restore iterator. */
+		if (move_iter_back)
+			vma_iter_next_range(vmg->vmi);
+		return NULL;
 	}
 
-	return NULL;
+	khugepaged_enter_vma(vmg->target, vmg->vm_flags);
+	vmg->state = VMA_MERGE_SUCCESS;
+	return vmg->target;
 }
 
 /*
@@ -1190,7 +1198,7 @@ int vma_expand(struct vma_merge_struct *vmg)
 	if (!ret && vmg->copied_from)
 		ret = dup_anon_vma(target, vmg->copied_from, &anon_dup);
 	if (ret)
-		return ret;
+		goto nomem;
 
 	if (remove_next) {
 		vma_start_write(next);
Signature · 1 line
2.53.0
author maintainer
#320 lore raw

PATCH 320/686 mm/cma: accept memory of multi-range CMA areas

In reply to Greg Kroah-Hartman

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

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

From: Mike Rapoport (Microsoft) <[email protected]>

[ Upstream commit 5d002001601a163b6c3500cdc098ff66c34f62d8 ]

Patch series "mm/cma: accept memory of CMA areas reserved with memblock_reserve()", v1.

Pages of allocated CMA areas are released to the buddy allocator with __free_pages(), which does not check for unaccepted memory.

This usually works because memblock accepts the memory it allocates.

However, multi-range CMA areas, used by hugetlb_cma, and fixed CMA areas requested with cma=<size>@<base> are reserved with memblock_reserve() and their memory is never accepted.

On TDX and SEV-SNP guests the first access to such a page is fatal.

To ease the backporting, each case is addressed by a separate patch:
- patch 1 accepts the memory of multi-range CMA areas
- patch 2 does the same for the fixed CMA areas

The second patch won't apply cleanly to 6.6 and 6.12, but I believe the stable team LLMs will take care of that :)

This patch (of 2):

On systems with unaccepted memory, memblock allocations accept the allocated range, but when cma_declare_contiguous_multi() uses open coded allocation of multiple ranges, it reserves them with memblock_reserve() and they are never accepted.

These pages are released to the buddy allocator by cma_activate_area() with __free_pages() that does not check for unaccepted memory, so the first access to such a page in a TDX or SEV-SNP guest is fatal.

Accept the memory of each range when it is reserved.

Fixes c009da4258f9 ("mm, cma: support multiple contiguous ranges, if requested")
Cc David Hildenbrand <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
---
 mm/cma.c | 2 ++
 1 file changed, 2 insertions(+)
mm/cma.c +2 -0
index 90d3ab262dae0..d829726319d81 100644
@@ -674,6 +674,8 @@ int __init cma_declare_contiguous_multi(phys_addr_t total_size,
 			break;
 		}
 
+		accept_memory(mlp->base, size);
+
 		pr_debug("created region %d: %016llx - %016llx\n",
 		    nr, (u64)mlp->base, (u64)mlp->base + size);
 		cmrp = &cma->ranges[nr++];
Signature · 1 line
2.53.0
author maintainer
#321 lore raw

PATCH 321/686 mm/cma: accept memory of CMA areas reserved at a fixed address

In reply to Greg Kroah-Hartman

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

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

From: Mike Rapoport (Microsoft) <[email protected]>

[ Upstream commit f8f9cbc34a309a388c052706f3329d1b52985aa3 ]

CMA areas allocated from memblock have their memory accepted by memblock_alloc_range_nid(), but areas reserved at a fixed address with memblock_reserve() are not.

If a fixed CMA area is requested by the cma=<size>@<base> command line parameter, it may be in regular RAM and on TDX and SEV-SNP guests it must be accepted.

Accept the memory of fixed CMA areas as well, so that all CMA areas are accepted regardless of how they were reserved.

Fixes 75d090fd167a ("x86/tdx: Add unaccepted memory support")
Cc David Hildenbrand <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
---
 mm/cma.c | 2 ++
 1 file changed, 2 insertions(+)
mm/cma.c +2 -0
index d829726319d81..f5c9da62aeb57 100644
@@ -377,6 +377,8 @@ static int __init cma_fixed_reserve(phys_addr_t base, phys_addr_t size)
 		return -EBUSY;
 	}
 
+	accept_memory(base, size);
+
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#322 lore raw

PATCH 322/686 mm: memcontrol: fix NULL pointer deref and UAF from high_work_func() on dying memcg

In reply to Greg Kroah-Hartman

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

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

From: T.J. Mercier <[email protected]>

[ Upstream commit dd94d8c7660a60dbfcd425e0d10120de6d02a7bd ]

When memory.high is exceeded in non-task context, try_charge_memcg() schedules memcg->high_work without taking a reference on the memcg, and high_work_func() invokes reclaim_high() without pinning the memcg.

With obj_cgroup reparenting, introduced in commit bf4f059954dc ("mm:
memcg/slab: obj_cgroup API"), objects charged to a child memcg are reparented to its parent in mem_cgroup_css_offline() instead of holding a reference on the child until uncharged. Subsequent uncharges of those objects go to the parent, which can leave the child's memory use permanently above its high limit, so any later charge on the offlined memcg in non-task context schedules high_work. This was later widened from kernel memory to LRU folios when commit f1cf8d2f36dc ("mm:
memcontrol: eliminate the problem of dying memory cgroup for LRU folios") converted LRU folios to use obj_cgroup reparenting.

cancel_work_sync(&memcg->high_work) only runs at the end of teardown in mem_cgroup_css_free(), so high_work_func() can start or still be running reclaim_high() after mem_cgroup_css_released() or shrink_many() has called lru_gen_release_memcg() and unhashed lruvec->lrugen.list. If reclaim tries to rotate the memcg, lru_gen_rotate_memcg() dereferences a NULL pprev pointer. This issue is specific to MGLRU and was introduced with the memcg LRU in commit e4dde56cd208 ("mm: multi-gen LRU: per-node lru_gen_folio lists").

With either traditional LRU or MGLRU, css_free_rwork_fn() calls css_rstat_exit() which frees per-CPU rstat data before calling mem_cgroup_css_free(). If reclaim_high() is still running, rstat updates via mod_lruvec_state() -> __css_rstat_updated() cause a use-after-free on the per-CPU rstat data. This was introduced when commit 5da3bfa029d6 ("cgroup: use separate rstat trees for each subsystem") moved css_rstat_exit() ahead of ss->css_free().

Fix both problems by acquiring a reference with css_tryget_online() in high_work_func() before calling reclaim_high(), and by resetting memory.high and swap.high to PAGE_COUNTER_MAX in mem_cgroup_css_offline() so that charges via references on an offlined memcg do not trigger high_work on the dead child and skip checking live ancestors in try_charge_memcg().

Acquiring the reference in high_work_func() rather than before scheduling high_work is safe because mem_cgroup_css_free() calls irq_work_sync() and cancel_work_sync() which cancels pending work and waits for an already running high_work_func() to complete before mem_cgroup_free() frees the memcg. css_tryget_online() uses percpu_ref_tryget_live() and is safe to call after percpu_ref_exit() before the cgroup is freed unlike css_tryget().

Oops: general protection fault, probably for non-canonical address 0xdffffc0000000000: 0000 [#1] SMP KASAN NOPTI
KASAN: null-ptr-deref in range [0x0000000000000000-0x0000000000000007]
CPU: 1 UID: 0 PID: 27 Comm: kworker/1:0 Tainted: G    B   W           7.3.0-rc5-g2bba28e98578 #284 PREEMPT(full)
Tainted: [B]=BAD_PAGE, [W]=WARN  <-- Taint from lru_gen_rotate_memcg() VM_WARN_ON_ONCE
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014
Workqueue: events high_work_func
RIP: 0010:lru_gen_rotate_memcg+0x1a3/0xe90
Call Trace:
 <TASK>
 ? read_ctrl_pos+0x22f/0x3f0
 shrink_lruvec+0x16cb/0x1b80
 ? ret_from_fork_asm+0x1a/0x30
 ? lapic_next_event+0x15/0x20
 ? clockevents_program_event+0x2bb/0x6f0
 ? lapic_next_event+0x15/0x20
 ? __pfx_shrink_lruvec+0x10/0x10
 ? __pfx_clockevents_program_event+0x10/0x10
 ? _raw_spin_lock+0x84/0xe0
 ? __pfx__raw_spin_lock+0x10/0x10
 ? kasan_save_stack+0x30/0x50
 ? psi_group_change+0x381/0x740
 ? __pfx_sched_clock_cpu+0x10/0x10
 ? save_fpregs_to_fpstate+0xc4/0x2c0
 ? finish_task_switch.isra.0+0x1de/0xac0
 ? __schedule+0xf62/0x42c0
 ? __pfx___schedule+0x10/0x10
 ? __pfx___irq_work_queue_local+0x10/0x10
 ? shrink_node+0x626/0x31e0
 shrink_node+0x626/0x31e0
 ? ring_buffer_unlock_commit+0x11d/0x5c0
 ? kswapd_clear_hopeless+0xa0/0x150
 ? __pfx_shrink_node+0x10/0x10
 ? 0xffffffffc0000095
 do_try_to_free_pages+0x255/0x13b0
 ? ring_buffer_unlock_commit+0x11d/0x5c0
 ? reclaim_high+0x10a/0x1b0
 try_to_free_mem_cgroup_pages+0x1f9/0x5a0
 ? __pfx_try_to_free_mem_cgroup_pages+0x10/0x10
 ? irqentry_exit+0xc6/0x670
 reclaim_high+0x10a/0x1b0
 ? __pfx_reclaim_high+0x10/0x10
 ? process_one_work+0x5ff/0x1030
 ? __pfx_high_work_func+0x10/0x10
 process_one_work+0x6e2/0x1030
 ? __pfx___schedule+0x10/0x10
 ? __pfx_process_one_work+0x10/0x10
 worker_thread+0x422/0xbb0
 ? __pfx_worker_thread+0x10/0x10
 kthread+0x2cd/0x3a0
 ? recalc_sigpending+0x15c/0x200
 ? __pfx_kthread+0x10/0x10
 ret_from_fork+0x368/0x590
 ? __pfx_ret_from_fork+0x10/0x10
 ? __switch_to+0x588/0xf50
 ? __pfx_kthread+0x10/0x10
 ret_from_fork_asm+0x1a/0x30
 </TASK>
Fixes e4dde56cd208 ("mm: multi-gen LRU: per-node lru_gen_folio lists")
Fixes 5da3bfa029d6 ("cgroup: use separate rstat trees for each subsystem")
Cc Michal Hocko <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Qi Zheng <[email protected]>
Cc JP Kobryn <[email protected]>
---
 mm/memcontrol.c | 5 +++++
 1 file changed, 5 insertions(+)
mm/memcontrol.c +5 -0
index eec89dcb7801b..97ed5ad4053f0 100644
@@ -2062,7 +2062,10 @@ static void high_work_func(struct work_struct *work)
 	struct mem_cgroup *memcg;
 
 	memcg = container_of(work, struct mem_cgroup, high_work);
+	if (!css_tryget_online(&memcg->css))
+		return;
 	reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
+	css_put(&memcg->css);
 }
 
 /*
@@ -3906,6 +3909,8 @@ static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
 
 	page_counter_set_min(&memcg->memory, 0);
 	page_counter_set_low(&memcg->memory, 0);
+	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
+	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
 
 	zswap_memcg_offline_cleanup(memcg);
 
Signature · 1 line
2.53.0
author maintainer
#323 lore raw

PATCH 323/686 openrisc: export __mulsi3 for modules

In reply to Greg Kroah-Hartman

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

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

From: Andrew Morton <[email protected]>

[ Upstream commit 8ff981aa283a0ce516c2dc65a48a185ed336c657 ]

OpenRISC configurations without hardware multiplication fail to build modules which contain compiler-generated calls to __mulsi3. The failure is widespread, affecting filesystems, drivers and KUnit tests at modpost.

When CONFIG_OPENRISC_HAVE_INST_MUL is disabled, the architecture Makefile passes -msoft-mul to GCC. The multiplication helper is supplied by the libgcc archive linked into vmlinux, but or32_ksyms.c does not export it. Built-in callers can therefore link while module callers cannot resolve the symbol.

Export __mulsi3 alongside the other compiler-generated helpers.

The omission predates 7c3f4d699f34 ("resource, kunit: stop selecting GET_FREE_REGION"), which the robot identified when reporting an additional failing module. It was already present in the initial OpenRISC export list.

Fixes 616257669e1a ("OpenRISC: Miscellaneous")
Cc Jonas Bonn <[email protected]>
Cc Stefan Kristiansson <[email protected]>
Cc Stafford Horne <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Karl Mehltretter <[email protected]>
---
 arch/openrisc/kernel/or32_ksyms.c | 1 +
 1 file changed, 1 insertion(+)
arch/openrisc/kernel/or32_ksyms.c +1 -0
index 212e5f85004cc..c63d7f25bc575 100644
@@ -35,6 +35,7 @@ DECLARE_EXPORT(__divsi3);
 DECLARE_EXPORT(__umodsi3);
 DECLARE_EXPORT(__modsi3);
 DECLARE_EXPORT(__muldi3);
+DECLARE_EXPORT(__mulsi3);
 DECLARE_EXPORT(__ashrdi3);
 DECLARE_EXPORT(__ashldi3);
 DECLARE_EXPORT(__lshrdi3);
Signature · 1 line
2.53.0
author maintainer
#324 lore raw

PATCH 324/686 ocfs2: find the xattr entry again after defragmenting a bucket

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 9a40c050f58344615a0604701b5d299519833163 ]

ocfs2_xattr_set_entry_bucket() hands loc.xl_entry to ocfs2_xa_set() twice:
once for the bucket as it stands, and, if that reports -ENOSPC, once more after ocfs2_defrag_xattr_bucket() has packed the name/value pairs down.

Defragmenting ends by sorting the entry array on xe_name_hash. Buckets are kept sorted, so the sort only permutes entries that share a hash, but lib/sort.c is an unstable heapsort and it does permute them. loc.xl_entry is an address inside xh_entries[], so afterwards it denotes whichever entry landed in that slot rather than the one the search found.

The second ocfs2_xa_set() then works on the wrong entry. Nothing on that path compares the entry's name with xi->xi_name, so what happens depends on how the two entries compare in size: ocfs2_xa_reuse_entry() trips its BUG_ON() when the padded name sizes differ, and otherwise the new value is written into the neighbouring attribute's value slot while the attribute being set is left untouched. setxattr() reports success either way.

Remember the entry's hash before defragmenting and look the entry up again afterwards, the way ocfs2_xattr_bucket_find() does. An entry that cannot be found again means the bucket no longer holds what the search found, so fail with -EFSCORRUPTED rather than writing through the stale pointer.

Fixes 012255961c9e ("ocfs2: Enable xattr set in index btree")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
fs/ocfs2/xattr.c +29 -1
index 734801de8e89e..e83db0ca737a6 100644
@@ -5635,13 +5635,18 @@ static int ocfs2_xattr_set_entry_bucket(struct inode *inode,
 					struct ocfs2_xattr_search *xs,
 					struct ocfs2_xattr_set_ctxt *ctxt)
 {
-	int ret;
+	int ret, found = 0;
+	u16 xe_index;
+	u32 name_hash;
 	struct ocfs2_xa_loc loc;
 
 	trace_ocfs2_xattr_set_entry_bucket(xi->xi_name);
 
 	ocfs2_init_xattr_bucket_xa_loc(&loc, xs->bucket,
 				       xs->not_found ? NULL : xs->here);
+	/* Defragmenting below may move this entry, so remember its hash. */
+	name_hash = loc.xl_entry ? le32_to_cpu(loc.xl_entry->xe_name_hash) : 0;
+
 	ret = ocfs2_xa_set(&loc, xi, ctxt);
 	if (!ret) {
 		xs->here = loc.xl_entry;
@@ -5660,6 +5665,29 @@ static int ocfs2_xattr_set_entry_bucket(struct inode *inode,
 		goto out;
 	}
 
+	/*
+	 * ocfs2_defrag_xattr_bucket() sorts the entries by name hash and
+	 * lib/sort.c is not stable, so entries sharing a hash may have traded
+	 * slots.  Look the entry up again before writing through it.
+	 */
+	if (loc.xl_entry) {
+		ret = ocfs2_find_xe_in_bucket(inode, xs->bucket,
+					      xi->xi_name_index, xi->xi_name,
+					      name_hash, &xe_index, &found);
+		if (ret) {
+			mlog_errno(ret);
+			goto out;
+		}
+		if (!found) {
+			mlog(ML_ERROR, "xattr entry not found in bucket %llu after defrag\n",
+			     (unsigned long long)bucket_blkno(xs->bucket));
+			ret = -EFSCORRUPTED;
+			goto out;
+		}
+		loc.xl_entry = &bucket_xh(xs->bucket)->xh_entries[xe_index];
+		xs->here = loc.xl_entry;
+	}
+
 	ret = ocfs2_xa_set(&loc, xi, ctxt);
 	if (!ret) {
 		xs->here = loc.xl_entry;
Signature · 1 line
2.53.0
author maintainer
#325 lore raw

PATCH 325/686 ocfs2: find the xattr entry again after converting a block to a bucket

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 9c191a7a44882487e291e09f095d2ae4d7cca146 ]

ocfs2_xattr_create_index_block() turns a non-indexed xattr block into a tree by copying it into a bucket, and the copy sorts the entries: a block holds them in insertion order, a bucket by name hash. ocfs2_xattr_update_xattr_search() nevertheless relocates the caller's search by the index the entry had in the block, so unless the two orders agreed it points at an unrelated entry, and nothing between there and the write compares that entry's name with the one being set.

Setting an xattr whose new value no longer fits the block arrives here with xs->not_found clear. The block gave up because ocfs2_xa_block_can_reuse() wants an exact namevalue size match, while ocfs2_xa_bucket_can_reuse() only wants an entry at least as large as the new one, so the bucket accepts a pair the block rejected and the update lands on whichever entry the sort left at that index. Equal padded name lengths get that other attribute's value replaced in place and its name left alone, so setxattr returns success while the attribute asked for keeps its old value. A longer one trips ocfs2_xa_reuse_entry()'s BUG_ON, and a shorter one is refused by the bucket as well, so ocfs2_xa_prepare_entry() wipes the entry and writes the new name over it, leaving xe_name_hash describing a name that is no longer there.

Find the entry again by the name being set, matching the type as well. The copy carries every entry and every name over unchanged, and (type, name) pairs are unique within a block, so the match is exact. The type matters because the handlers strip their prefix before calling ocfs2_xattr_set(), so user.foo and trusted.foo share a stored name, a stored length and a hash, and both can sit in the same block.

The name has to come from xi rather than from xs->here: a failed set can remove the entry xs->here names, and only the "growing" caller sets ctxt->set_abort, which is what stops the conversion. Scan every entry rather than narrowing on the hash the way ocfs2_find_xe_in_bucket() does, since an existing entry keeps the hash it was stored under, which a kernel that sign-extended the name bytes made different from the one computed now. An empty result means the entry did not survive the failed set and this has become an insert; leaving xs->here alone would keep it pointing into the block, which is rewritten as a tree root before the caller reads it again.

Fixes 012255961c9e ("ocfs2: Enable xattr set in index btree")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 54 +++++++++++++++++++++++++++++++++++++++---------
 1 file changed, 44 insertions(+), 10 deletions(-)
fs/ocfs2/xattr.c +44 -10
index e83db0ca737a6..406b40375f6c7 100644
@@ -256,6 +256,7 @@ static int ocfs2_xattr_tree_list_index_block(struct inode *inode,
 					size_t buffer_size);
 
 static int ocfs2_xattr_create_index_block(struct inode *inode,
+					  struct ocfs2_xattr_info *xi,
 					  struct ocfs2_xattr_search *xs,
 					  struct ocfs2_xattr_set_ctxt *ctxt);
 
@@ -3013,7 +3014,7 @@ static int ocfs2_xattr_block_set(struct inode *inode,
 		else if ((ret != -ENOSPC) || ctxt->set_abort)
 			goto end;
 		else {
-			ret = ocfs2_xattr_create_index_block(inode, xs, ctxt);
+			ret = ocfs2_xattr_create_index_block(inode, xi, xs, ctxt);
 			if (ret)
 				goto end;
 		}
@@ -4341,13 +4342,10 @@ static void ocfs2_cp_xattr_block_to_bucket(struct inode *inode,
  * real place of the xattr.
  */
 static void ocfs2_xattr_update_xattr_search(struct inode *inode,
-					    struct ocfs2_xattr_search *xs,
-					    struct buffer_head *old_bh)
+					    struct ocfs2_xattr_info *xi,
+					    struct ocfs2_xattr_search *xs)
 {
-	char *buf = old_bh->b_data;
-	struct ocfs2_xattr_block *old_xb = (struct ocfs2_xattr_block *)buf;
-	struct ocfs2_xattr_header *old_xh = &old_xb->xb_attrs.xb_header;
-	int i;
+	int i, count;
 
 	xs->header = bucket_xh(xs->bucket);
 	xs->base = bucket_block(xs->bucket, 0);
@@ -4356,11 +4354,47 @@ static void ocfs2_xattr_update_xattr_search(struct inode *inode,
 	if (xs->not_found)
 		return;
 
-	i = xs->here - old_xh->xh_entries;
-	xs->here = &xs->header->xh_entries[i];
+	/*
+	 * A block holds its entries in insertion order while a bucket holds
+	 * them by name hash, so ocfs2_cp_xattr_block_to_bucket() sorted the
+	 * copies and the index this entry had in the block no longer says
+	 * where it is.  It copied every entry and every name unchanged, and
+	 * (type, name) pairs are unique within a block, so find it again by
+	 * name.
+	 *
+	 * Search for the name being set, not for the name xs->here carries.
+	 * A failed set may have removed that entry, and ocfs2_xa_remove_entry()
+	 * then memmoves its successor into the slot.  Comparing every entry
+	 * rather than narrowing on the hash also finds an entry stored under
+	 * the legacy signed hash, which ocfs2_find_xe_in_bucket() would skip.
+	 */
+	count = le16_to_cpu(xs->header->xh_count);
+	for (i = 0; i < count; i++) {
+		struct ocfs2_xattr_entry *xe = &xs->header->xh_entries[i];
+
+		if (ocfs2_xattr_get_type(xe) != xi->xi_name_index)
+			continue;
+		if (xe->xe_name_len != xi->xi_name_len)
+			continue;
+		if (!memcmp(xs->base + le16_to_cpu(xe->xe_name_offset),
+			    xi->xi_name, xi->xi_name_len)) {
+			xs->here = xe;
+			return;
+		}
+	}
+
+	/*
+	 * The entry did not survive the failed set, so this has become an
+	 * insert.  Point xs->here back inside the bucket: it still refers to
+	 * the block being converted, which is about to be rewritten as a tree
+	 * root.
+	 */
+	xs->not_found = -ENODATA;
+	xs->here = xs->header->xh_entries;
 }
 
 static int ocfs2_xattr_create_index_block(struct inode *inode,
+					  struct ocfs2_xattr_info *xi,
 					  struct ocfs2_xattr_search *xs,
 					  struct ocfs2_xattr_set_ctxt *ctxt)
 {
@@ -4427,7 +4461,7 @@ static int ocfs2_xattr_create_index_block(struct inode *inode,
 	ocfs2_cp_xattr_block_to_bucket(inode, xb_bh, xs->bucket);
 	ocfs2_xattr_bucket_journal_dirty(handle, xs->bucket);
 
-	ocfs2_xattr_update_xattr_search(inode, xs, xb_bh);
+	ocfs2_xattr_update_xattr_search(inode, xi, xs);
 
 	/* Change from ocfs2_xattr_header to ocfs2_xattr_tree_root */
 	memset(&xb->xb_attrs, 0, inode->i_sb->s_blocksize -
Signature · 1 line
2.53.0
author maintainer
#326 lore raw

PATCH 326/686 ocfs2: do not read the entry array of an empty xattr bucket

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 e8de099f2958c84aa23186c5481e69f7ffd39355 ]

ocfs2_check_xattr_bucket_collision() decides whether splitting a bucket can make room by comparing the hash being inserted against the first and the last entry. xh_count comes off disk and is never checked, and a bucket is allowed to hold no entries: ocfs2_xa_remove_entry() keeps the last slot when it removes the only one, so that an empty bucket still carries the hash it is keyed by. xh_count then reads back as 0 while xh_entries[0] is still meaningful, and the second comparison indexes xh_entries[-1].

That is outside the __counted_by_le(xh_count) bounds of xh_entries[] and lands on the header. An entry is 16 bytes and xe_name_hash is its first field, so the value read is xh_count | xh_free_start << 16. It stays inside the block, but the answer is arbitrary, and for an empty bucket it says there is no collision, so a new bucket gets added on the strength of it.

An empty bucket holds no entries to collide with. Return before reading the array.

One way to reach the test with an empty bucket is a set that removes the bucket's only entry during cleanup and then fails for space again, since it is that second -ENOSPC which calls this. Growing a value past OCFS2_XATTR_INLINE_SIZE is the easy route: the cluster allocation fails, the "!orig_clusters" arm of ocfs2_xa_cleanup_value_truncate() removes the entry, and although the "growing" caller does set ctxt->set_abort, only ocfs2_xattr_block_set() and __ocfs2_xattr_set_handle() look at it, so ocfs2_xattr_set_entry_index_block() goes straight on to the collision check.

This sits on commit a9ea8b397864 ("ocfs2: use the stored hash when checking xattr bucket collision"), which gave the collision check its two argument form and is marked for 6.2 and later. The read fixed here is present in the three argument version too, but a tree without that commit needs the hunk adapted by hand.

Fixes 012255961c9e ("ocfs2: Enable xattr set in index btree")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
fs/ocfs2/xattr.c +10 -1
index 406b40375f6c7..a82fb4a5084c3 100644
@@ -5644,11 +5644,20 @@ static int ocfs2_check_xattr_bucket_collision(struct ocfs2_xattr_bucket *bucket,
 					      u32 name_hash)
 {
 	struct ocfs2_xattr_header *xh = bucket_xh(bucket);
+	u16 count = le16_to_cpu(xh->xh_count);
+
+	/*
+	 * An empty bucket keeps the hash of the entry that was removed in
+	 * xh_entries[0] so that it can still be found, but it holds no
+	 * entries to collide with.
+	 */
+	if (!count)
+		return 0;
 
 	if (name_hash != le32_to_cpu(xh->xh_entries[0].xe_name_hash))
 		return 0;
 
-	if (xh->xh_entries[le16_to_cpu(xh->xh_count) - 1].xe_name_hash ==
+	if (xh->xh_entries[count - 1].xe_name_hash ==
 	    xh->xh_entries[0].xe_name_hash) {
 		mlog(ML_ERROR, "Too much hash collision in xattr bucket %llu, "
 		     "hash = %u\n",
Signature · 1 line
2.53.0
author maintainer
#327 lore raw

PATCH 327/686 ocfs2: do not index before the entry array when dividing an empty bucket

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 7133a0d0954c109f1764ebf8ab32d7e757a6c587 ]

ocfs2_divide_xattr_bucket() appends an empty bucket carrying a sentinel hash when the source bucket has no divide position, taking that hash from xh_entries[start - 1]. ocfs2_xattr_find_divide_pos() returns count when every entry shares one hash, and its loop does not run at all for count < 2, so an empty bucket comes back with start == count == 0 and the read is xh_entries[-1].

That is outside the __counted_by_le(xh_count) bounds of xh_entries[] and lands on the header, so the value picked up is
xh_count | xh_free_start << 16. One above it is written into the new bucket's xh_entries[0] and committed, which leaves a bucket whose first hash does not follow the bucket before it. ocfs2_xattr_bucket_find() binary searches on xh_entries[0], so the broken key hides the range the sentinel was meant to cover: getxattr() answers -ENODATA for an attribute that is stored, and an insert can go to the wrong bucket and leave two copies of a name. The cross cluster divide hands the same value back as a tree record's e_cpos, which then claims a hash range it does not cover.

Read xh_entries[0] instead. The branch is only reached when every entry shares one hash, so for a non-empty bucket it holds the same value, and for an empty one it is the slot that carries the bucket key.

An empty bucket reaches the divide from ocfs2_check_xattr_bucket_collision(), which reports no collision for one, through ocfs2_add_new_xattr_bucket() and ocfs2_extend_xattr_bucket(). It does not take a failed set to get
there: a divide that finds no position is itself what leaves an empty sentinel bucket behind, and a later extend can pick it as the target.

Fixes 80bcaf3469b8 ("ocfs2/xattr: Proper hash collision handle in bucket division")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
fs/ocfs2/xattr.c +9 -1
index a82fb4a5084c3..5f263d24bbc3b 100644
@@ -4814,7 +4814,15 @@ static int ocfs2_divide_xattr_bucket(struct inode *inode,
 	start = ocfs2_xattr_find_divide_pos(xh);
 
 	if (start == count) {
-		xe = &xh->xh_entries[start-1];
+		/*
+		 * start == count means every entry shares one hash, so the
+		 * first of them carries it too.  An empty bucket has no
+		 * entries[start - 1], but its entries[0] still carries the
+		 * bucket key: either the hash ocfs2_xa_remove_entry()
+		 * deliberately leaves behind, or the sentinel a previous
+		 * divide wrote.
+		 */
+		xe = &xh->xh_entries[0];
 
 		/*
 		 * initialized a new empty bucket here.
Signature · 1 line
2.53.0
author maintainer
#328 lore raw

PATCH 328/686 ocfs2: do not read the entry array of an empty xattr block

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 cd7c3563a98fe8c984463d83772e518cb7e68356 ]

ocfs2_cp_xattr_block_to_bucket() sizes the name and value area it has to carry over from the block's last entry, so an empty block makes it read xh_entries[-1]. That lands on the header, where xe_name_offset overlaps xh_name_value_len, and block storage never maintains that field, so it reads as 0 and the copy runs from the header to the end of the block.

The bucket that comes out has xh_count 0 but a name_value_len of blocksize less the header, and a matching xh_free_start that claims those bytes are in use -- nearly the whole bucket with the common 4K block size -- while the last block of the bucket holds a copy of the old block's bytes. Nothing but a trace event reads xh_name_value_len, the copied bytes came from the same inode and were wiped before the entry was removed, and ocfs2_defrag_xattr_bucket() recomputes xh_free_start, so this corrupts the header rather than leaking anything.

Leave the bucket empty instead, carrying over the hash the block was keyed by, since ocfs2_add_new_xattr_bucket() and ocfs2_xattr_bucket_find() both read xh_entries[0] of an empty bucket. That read is the exception ocfs2_xa_remove_entry() documents rather than a new out of bounds access.

A block reaches the conversion empty when truncating an external value back fails partway through: the "reusing" and "overwriting" callers of ocfs2_xa_cleanup_value_truncate() remove the entry without setting ctxt->set_abort, so ocfs2_xattr_block_set() sees a plain -ENOSPC and converts. The "growing" caller does set it, and the block form makes a single attempt with no defragment and retry in between, so that is the only route here.

Fixes 012255961c9e ("ocfs2: Enable xattr set in index btree")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
fs/ocfs2/xattr.c +15 -0
index 5f263d24bbc3b..921d050c37581 100644
@@ -4296,6 +4296,21 @@ static void ocfs2_cp_xattr_block_to_bucket(struct inode *inode,
 	for (i = 0; i < blks; i++)
 		memset(bucket_block(bucket, i), 0, blocksize);
 
+	/*
+	 * An empty block has no names or values to carry over, and the
+	 * xh_entries[count - 1] below would be xh_entries[-1].  Leave the
+	 * bucket empty, but carry over the hash ocfs2_xa_remove_entry() left
+	 * in the block's xh_entries[0] so that the bucket still holds the key
+	 * it is looked up by.
+	 */
+	if (!count) {
+		xh->xh_num_buckets = cpu_to_le16(1);
+		xh->xh_free_start = cpu_to_le16(OCFS2_XATTR_BUCKET_SIZE);
+		xh->xh_entries[0].xe_name_hash =
+			xb_xh->xh_entries[0].xe_name_hash;
+		return;
+	}
+
 	/*
 	 * Since the xe_name_offset is based on ocfs2_xattr_header,
 	 * there is a offset change corresponding to the change of
Signature · 1 line
2.53.0
author maintainer
#329 lore raw

PATCH 329/686 fat: hold truncate_lock in fat_write_failed()

In reply to Greg Kroah-Hartman

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

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

From: Matheus Alves de Almeida <[email protected]>

[ Upstream commit 7b90009546f5d3f3ac9428040cd7ffbdfd60f2eb ]

The current fat_write_failed() implementation calls into fat_truncate_blocks() without holding truncate_lock.

A failed or short extending write racing with FIBMAP can spuriously make a FAT filesystem read-only. FIBMAP bounds its lookup by i_blocks, so it can walk allocated clusters beyond i_size while fat_write_failed() is removing them. If the chain is shortened during the walk, the mapper can report a bogus "request beyond EOF" error, triggering the default read-only error policy. Hold truncate_lock for write around the block cleanup to serialize it with _fat_bmap().

For comparison, fat_setattr() correctly holds truncate_lock during truncation:

	down_write(&MSDOS_I(inode)->truncate_lock);
	truncate_setsize(inode, attr->ia_size);
	fat_truncate_blocks(inode, attr->ia_size);
	up_write(&MSDOS_I(inode)->truncate_lock);

Make it so ->truncate_lock is held exclusive while truncating.

Fixes 16fab2015099 ("fat: permit to return phy block number by fibmap in fallocated region")
Fixes 459f6ed3b8c7 ("fat: convert to use the new truncate convention.")
Cc Pedro Falcato <[email protected]>
---
 fs/fat/inode.c | 2 ++
 1 file changed, 2 insertions(+)
fs/fat/inode.c +2 -0
index 9cfe20a3daaf6..1a951dfb33dc0 100644
@@ -215,7 +215,9 @@ static void fat_write_failed(struct address_space *mapping, loff_t to)
 
 	if (to > inode->i_size) {
 		truncate_pagecache(inode, inode->i_size);
+		down_write(&MSDOS_I(inode)->truncate_lock);
 		fat_truncate_blocks(inode, inode->i_size);
+		up_write(&MSDOS_I(inode)->truncate_lock);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#330 lore raw

PATCH 330/686 ocfs2: keep locking_state within the cluster connection lifetime

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 5bdef466851e39ba752634cbea68e5ea24ccfb24 ]

The locking_state reader calls ocfs2_dlm_lvb() through the selected cluster stack. Its debug-object reference keeps the tracking list alive, but does not keep that stack selected without a cluster connection.

DLM initialization publishes the file before establishing its connection, and DLM shutdown drops the connection while the file still exists. Both the mount error unwind in ocfs2_mount_volume() and ocfs2_dismount_volume() remove the debugfs subtree only after ocfs2_dlm_shutdown() has returned. Whenever the disconnect releases the last stack reference, which is the case for a failed mount and for any unmount without a pending hangup, a concurrent reader dereferences a NULL active_stack:

Mount error unwind Debugfs reader
------------------ --------------
ocfs2_mount_volume(): out_dlm

    ocfs2_dlm_shutdown()
      disconnect last cluster
        clear active_stack
                                      read locking_state
                                        ocfs2_dlm_seq_show()
                                          ocfs2_dlm_lvb()
                                            dereference active_stack

fill_super(): out_debugfs
remove debugfs subtree

Publish the debug files only after the connection and the mount lock resources are initialized, so a failed DLM initialization has no debug reference to drop. Remove them again in the common DLM shutdown helper before the connection is dropped: debugfs removal waits for readers that are inside the file operations, and the parent directory is still present at that point in every caller. This covers the mount error unwind, the ocfs2_fill_super() failures after a successful mount that dismount with mnt_err set, and unmounts whose disconnect releases the stack directly.

Only the relevant frames of the report are kept:

Oops: general protection fault, probably for non-canonical address 0xdffffc0000000001: 0000 [#1] SMP KASAN NOPTI
KASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f]
RIP: 0010:ocfs2_dlm_lvb+0x38/0xf0
Call Trace:
 <TASK>
 ocfs2_dlm_seq_show+0x36a/0xb70
 seq_read_iter+0x480/0x1110
 seq_read+0x362/0x5a0
 full_proxy_read+0x11f/0x180
 vfs_read+0x1a0/0xc20
 ksys_read+0x111/0x200
 </TASK>
---
 fs/ocfs2/dlmglue.c | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)
fs/ocfs2/dlmglue.c +13 -5
index 90d23dd7d4c8f..6f44f9f230596 100644
@@ -3335,6 +3335,14 @@ static void ocfs2_dlm_shutdown_debug(struct ocfs2_super *osb)
 {
 	struct ocfs2_dlm_debug *dlm_debug = osb->osb_dlm_debug;
 
+	/*
+	 * Drain the readers before the cluster stack goes away: the
+	 * locking_state reader resolves ocfs2_dlm_lvb() through the
+	 * stack. Every caller removes the parent directory later.
+	 */
+	debugfs_lookup_and_remove("locking_state", osb->osb_debug_root);
+	debugfs_lookup_and_remove("locking_filter", osb->osb_debug_root);
+
 	if (dlm_debug)
 		ocfs2_put_dlm_debug(dlm_debug);
 }
@@ -3349,8 +3357,6 @@ int ocfs2_dlm_init(struct ocfs2_super *osb)
 		goto local;
 	}
 
-	ocfs2_dlm_init_debug(osb);
-
 	/* launch downconvert thread */
 	osb->dc_task = kthread_run(ocfs2_downconvert_thread, osb, "ocfs2dc-%s",
 			osb->uuid_str);
@@ -3390,9 +3396,10 @@ int ocfs2_dlm_init(struct ocfs2_super *osb)
 	ocfs2_orphan_scan_lock_res_init(&osb->osb_orphan_scan.os_lockres, osb);
 
 	osb->cconn = conn;
+	if (conn)
+		ocfs2_dlm_init_debug(osb);
 bail:
 	if (status < 0) {
-		ocfs2_dlm_shutdown_debug(osb);
 		if (osb->dc_task)
 			kthread_stop(osb->dc_task);
 	}
@@ -3422,10 +3429,11 @@ void ocfs2_dlm_shutdown(struct ocfs2_super *osb,
 	ocfs2_lock_res_free(&osb->osb_orphan_scan.os_lockres);
 
 	if (osb->cconn) {
+		/* The disconnect below may release the selected stack. */
+		ocfs2_dlm_shutdown_debug(osb);
+
 		ocfs2_cluster_disconnect(osb->cconn, hangup_pending);
 		osb->cconn = NULL;
-
-		ocfs2_dlm_shutdown_debug(osb);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#331 lore raw

PATCH 331/686 ocfs2/dlm: serialize migration MLE cleanup on failure

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 61469249aab03799b0d3294b7a0cd25dd303017a ]

A migration MLE has a base reference for the mastering answer and an in-use reference held by dlm_migrate_lockres(). The finishing assertion consumes the base reference, but migration failure drops it again without checking whether the assertion already consumed it.

The target queues its migration worker before it acknowledges the ALL_DONE packet, so its finishing assertion can be handled while the sender still waits for the status. If the connection fails before the status arrives, dlm_send_one_lockres() returns an error for a migration that the target has already completed:

Old-master sender Finishing assertion
----------------- -------------------
publish MLE; take in-use reference
send ALL_DONE; wait for status
take lookup reference unlink MLE
put lookup and base references
send returns a connection error
put base reference again; free MLE
put in-use reference; access freed MLE

dlm_assert_master_handler() holds dlm->spinlock from the MLE lookup to the final puts, and it takes dlm->master_lock around the unlink and the puts. Decide under the same locks: if the MLE is already unhashed, the assertion consumed the base reference, so drop only the sender's in-use reference. Otherwise unlink it before consuming the base reference so a later assertion no longer finds it.

An assertion that got there first has also made the target the owner and cleared DLM_LOCK_RES_MIGRATING. Treating the attempt as failed at that point would leave the lockres owned by the target while this node still holds the other nodes' locks and refmap bits, so it could neither be purged nor migrated again. Finish our side as a completed migration does instead: drop those locks under res->spinlock if the target still owns the lockres, and recalculate its usage.

Use the same cleanup for the pre-send failure, the send failure and the target-death failure paths. The sender's in-use reference keeps the MLE alive until its final put outside the nested locks. Successful migration retains its existing in-use-only put.

A target that has died cannot assert after the sender has seen its death. The o2net node-down callback runs before the DLM one; it disconnects the node and flushes the workqueue that runs the message handlers, so an assertion already received has been handled by the time the DLM removes the node from the domain map. A node that leaves the domain cleanly sends its exit message only after its assertions have been answered.

Two windows of the hand-over itself are left as they are: the handler switches the owner and the sender drops the other nodes' locks moments later, and an assertion from a live target that arrives after the sender has given up still meets the owner check in the handler. Waiting for the target before giving up would only stretch the first window into the time in which recovery of the target can observe it.

KASAN report, only the relevant frames are kept:

BUG: KASAN: slab-use-after-free in dlm_put_mle_inuse+0xce/0xe0
Read of size 8 at addr ffff8881190e3c20 by task umount/593

Call Trace:
 <TASK>
 dlm_put_mle_inuse+0xce/0xe0
 dlm_migrate_lockres+0x16af/0x20d0
 dlm_empty_lockres+0x60a/0xbd0
 dlm_unregister_domain+0x53b/0x11d0
 o2cb_cluster_disconnect+0xa5/0x110
 ocfs2_cluster_disconnect+0x73/0xc0
 ocfs2_dlm_shutdown+0x311/0x440
 ocfs2_dismount_volume+0x696/0x940
 generic_shutdown_super+0x15f/0x490
 kill_block_super+0x40/0xa0
 deactivate_locked_super+0xae/0x120
 deactivate_super+0xa2/0xc0
 cleanup_mnt+0x217/0x450
 task_work_run+0x144/0x230
 </TASK>

Allocated by task 593:
 kmem_cache_alloc_noprof+0x20b/0x5c0
 dlm_migrate_lockres+0x20e/0x20d0
 dlm_empty_lockres+0x60a/0xbd0
 dlm_unregister_domain+0x53b/0x11d0
 o2cb_cluster_disconnect+0xa5/0x110
 ocfs2_cluster_disconnect+0x73/0xc0
 ocfs2_dlm_shutdown+0x311/0x440
 ocfs2_dismount_volume+0x696/0x940

Freed by task 593:
 kmem_cache_free+0x242/0x580
 __dlm_put_mle+0x4b2/0x660
 dlm_migrate_lockres+0x1690/0x20d0
 dlm_empty_lockres+0x60a/0xbd0
 dlm_unregister_domain+0x53b/0x11d0
 o2cb_cluster_disconnect+0xa5/0x110
 ocfs2_cluster_disconnect+0x73/0xc0
 ocfs2_dlm_shutdown+0x311/0x440

The buggy address belongs to the object at ffff8881190e3c00
 which belongs to the cache o2dlm_mle of size 480

The buggy address is located 32 bytes inside of
freed 480-byte region [ffff8881190e3c00, ffff8881190e3de0)

Fixes 6714d8e86bf4 ("[PATCH] OCFS2: The Second Oracle Cluster Filesystem")
Assisted-by LLM
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc Heming Zhao <[email protected]>
Cc Jia-Ju Bai <[email protected]>
---
 fs/ocfs2/dlm/dlmmaster.c | 70 ++++++++++++++++++++++++++++++++++------
 1 file changed, 61 insertions(+), 9 deletions(-)
fs/ocfs2/dlm/dlmmaster.c +61 -9
index 4ab8c48582b15..ee28a01e7be34 100644
@@ -2526,6 +2526,52 @@ static int dlm_is_lockres_migratable(struct dlm_ctxt *dlm,
  */
 
 
+/*
+ * Drop the sender's references on a migration MLE after the attempt has
+ * failed. The finishing assert from the target may already have unlinked
+ * the MLE and consumed its base reference; decide under the locks the
+ * assert handler holds, and only drop the base reference while the MLE is
+ * still hashed. Returns true when the assert got there first: the target
+ * has become the master, so the caller must complete the migration.
+ */
+static bool dlm_put_migration_mle(struct dlm_ctxt *dlm,
+				  struct dlm_master_list_entry *mle)
+{
+	bool asserted;
+
+	spin_lock(&dlm->spinlock);
+	spin_lock(&dlm->master_lock);
+	__dlm_mle_detach_hb_events(dlm, mle);
+	asserted = hlist_unhashed(&mle->master_hash_node);
+	if (!asserted) {
+		__dlm_unlink_mle(dlm, mle);
+		__dlm_put_mle(mle);
+	}
+	spin_unlock(&dlm->master_lock);
+	spin_unlock(&dlm->spinlock);
+
+	dlm_put_mle_inuse(mle);
+	return asserted;
+}
+
+/*
+ * The finishing assert got there first: it switched the owner to the
+ * target and cleared DLM_LOCK_RES_MIGRATING. Drop the other nodes' locks
+ * as a completed migration does, unless recovery has taken the lockres
+ * over since, and let the usage be recalculated.
+ */
+static void dlm_migrate_lockres_asserted(struct dlm_ctxt *dlm,
+					 struct dlm_lock_resource *res,
+					 u8 target)
+{
+	spin_lock(&res->spinlock);
+	if (res->owner == target)
+		dlm_remove_nonlocal_locks(dlm, res);
+	spin_unlock(&res->spinlock);
+
+	dlm_lockres_calc_usage(dlm, res);
+}
+
 static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
 			       struct dlm_lock_resource *res, u8 target)
 {
@@ -2610,9 +2656,10 @@ static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
 
 	if (ret < 0) {
 		if (mle_added) {
-			dlm_mle_detach_hb_events(dlm, mle);
-			dlm_put_mle(mle);
-			dlm_put_mle_inuse(mle);
+			if (dlm_put_migration_mle(dlm, mle)) {
+				dlm_migrate_lockres_asserted(dlm, res, target);
+				ret = 0;
+			}
 		} else if (mle) {
 			kmem_cache_free(dlm_mle_cache, mle);
 			mle = NULL;
@@ -2641,9 +2688,11 @@ static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
 		mlog(0, "migration to node %u failed with %d\n",
 		     target, ret);
 		/* migration failed, detach and clean up mle */
-		dlm_mle_detach_hb_events(dlm, mle);
-		dlm_put_mle(mle);
-		dlm_put_mle_inuse(mle);
+		if (dlm_put_migration_mle(dlm, mle)) {
+			dlm_migrate_lockres_asserted(dlm, res, target);
+			ret = 0;
+			goto leave;
+		}
 		spin_lock(&res->spinlock);
 		res->state &= ~DLM_LOCK_RES_MIGRATING;
 		wake = 1;
@@ -2687,9 +2736,12 @@ static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
 				     res->lockname.name, target);
 				ret = -EINVAL;
 				/* migration failed, detach and clean up mle */
-				dlm_mle_detach_hb_events(dlm, mle);
-				dlm_put_mle(mle);
-				dlm_put_mle_inuse(mle);
+				if (dlm_put_migration_mle(dlm, mle)) {
+					dlm_migrate_lockres_asserted(dlm, res,
+								     target);
+					ret = 0;
+					goto leave;
+				}
 				spin_lock(&res->spinlock);
 				res->state &= ~DLM_LOCK_RES_MIGRATING;
 				wake = 1;
Signature · 1 line
2.53.0
author maintainer
#332 lore raw

PATCH 332/686 ocfs2: stop recovery before shutting down local allocators

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 126429e2f503ade63502978beb0c519066442250 ]

Recovery completion needs the local allocators until it has finished reclaiming a failed node's allocation window and truncate log. During unmount, quota recovery is stopped first, but that leaves recovery_state at OCFS2_REC_QUOTA_DISABLED. New non-quota recovery can still start.

ocfs2_truncate_log_shutdown() drains existing completion work and releases osb_tl_bh before ocfs2_recovery_exit() closes that publication path:

Unmount Recovery
------- --------
stop quota recovery; disable quotas truncate_log_shutdown()
flush existing completion work
recover another failed node
queue completion
flush local log; release buffer
complete_truncate_log_recovery()
use released osb_tl_bh
recovery_exit(): disable and drain

An extra buffer reference alone would still let completion append new records after the final truncate-log flush.

Split stopping and draining recovery from freeing its state. Stop all recovery producers and drain completion work before shutting down either local allocator. Keep recovery-state release at its existing later point, so its lifetime relative to other teardown users stays unchanged. The second stop at recovery_exit() is harmless once recovery is disabled.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in ocfs2_truncate_log_needs_flush+0x23d/0x360
    Read of size 8 at addr ffff8881093711e8 by task kworker/u16:3/53

    CPU: 0 UID: 0 PID: 53 Comm: kworker/u16:3 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: ocfs2_wq ocfs2_complete_recovery
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? ocfs2_truncate_log_needs_flush+0x23d/0x360
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20e/0x420
     ? ocfs2_truncate_log_needs_flush+0x23d/0x360
     kasan_report+0xe0/0x110
     ? ocfs2_truncate_log_needs_flush+0x23d/0x360
     ocfs2_truncate_log_needs_flush+0x23d/0x360
     ? __pfx_ocfs2_truncate_log_needs_flush+0x10/0x10
     ? __pfx_down_write+0x10/0x10
     ocfs2_complete_truncate_log_recovery+0x315/0x780
     ? trace_hardirqs_on+0x18/0x160
     ? __pfx_ocfs2_complete_truncate_log_recovery+0x10/0x10
     ? ocfs2_complete_recovery+0x666/0x11b0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? kfree+0x308/0x580
     ocfs2_complete_recovery+0x676/0x11b0
     ? __pfx_ocfs2_complete_recovery+0x10/0x10
     ? reacquire_held_locks+0xdd/0x200
     ? process_one_work+0x7c8/0x1b40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_acquire+0x190/0x300
     ? __pfx_autoremove_wake_function+0x10/0x10
     ? 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>

    Allocated by task 538:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_slab_alloc+0x89/0x90
     kmem_cache_alloc_noprof+0x20b/0x5c0
     alloc_buffer_head+0x26/0x120
     folio_alloc_buffers+0x122/0x1d0
     bdev_getblk+0x299/0x4f0
     ocfs2_read_blocks_sync+0x513/0xbc0
     ocfs2_iget+0x9cd/0x1a00
     ocfs2_get_system_file_inode+0x25e/0x7a0
     ocfs2_fill_super+0x1b05/0x3930
     get_tree_bdev_flags+0x35d/0x5f0
     vfs_get_tree+0x93/0x320
     fc_mount+0x1d/0x200
     path_mount+0x592/0x1e00
     __x64_sys_mount+0x24b/0x2d0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 553:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kmem_cache_free+0x242/0x580
     free_buffer_head+0x4b/0xc0
     try_to_free_buffers+0x1dc/0x330
     ocfs2_truncate_log_shutdown+0x789/0x1290
     ocfs2_dismount_volume+0x1da/0x940
     generic_shutdown_super+0x15f/0x490
     kill_block_super+0x40/0xa0
     deactivate_locked_super+0xae/0x120
     deactivate_super+0xa2/0xc0
     cleanup_mnt+0x217/0x450
     task_work_run+0x144/0x230
     exit_to_user_mode_loop+0x17d/0x570
     do_syscall_64+0x4d1/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff8881093711c0
     which belongs to the cache buffer_head of size 160
    The buggy address is located 40 bytes inside of
     freed 160-byte region [ffff8881093711c0, ffff888109371260)

    The buggy address belongs to the physical page:
    page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x109371
    flags: 0x200000000000000(node=0|zone=2)
    page_type: f5(slab)
    raw: 0200000000000000 ffff8881008883c0 dead000000000100 dead000000000122
    raw: 0000000000000000 0000000000120012 00000000f5000000 0000000000000000
    page dumped because: kasan: bad access detected

    Memory state around the buggy address:
     ffff888109371080: 00 00 00 00 fc fc fc fc fc fc fc fc 00 00 00 00
     ffff888109371100: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    >ffff888109371180: fc fc fc fc fc fc fc fc fa fb fb fb fb fb fb fb
                                                              ^
     ffff888109371200: fb fb fb fb fb fb fb fb fb fb fb fb fc fc fc fc
     ffff888109371280: fc fc fc fc 00 00 00 00 00 00 00 00 00 00 00 00
    ==================================================================
---
 fs/ocfs2/journal.c | 15 ++++++++++++---
 fs/ocfs2/journal.h |  1 +
 fs/ocfs2/super.c   |  3 +++
 3 files changed, 16 insertions(+), 3 deletions(-)
fs/ocfs2/journal.c +12 -3
index 2b8b57e914f08..602b6c8dc39fc 100644
@@ -230,13 +230,22 @@ void ocfs2_recovery_disable_quota(struct ocfs2_super *osb)
 	ocfs2_recovery_disable(osb, OCFS2_REC_QUOTA_WANT_DISABLE);
 }
 
+/* Stop producers and drain completion work without freeing recovery state. */
+void ocfs2_recovery_stop(struct ocfs2_super *osb)
+{
+	ocfs2_recovery_disable(osb, OCFS2_REC_WANT_DISABLE);
+}
+
 void ocfs2_recovery_exit(struct ocfs2_super *osb)
 {
 	struct ocfs2_recovery_map *rm;
 
-	/* disable any new recovery threads and wait for any currently
-	 * running ones to exit. Do this before setting the vol_state. */
-	ocfs2_recovery_disable(osb, OCFS2_REC_WANT_DISABLE);
+	/*
+	 * Disable producers and drain work before freeing recovery state.
+	 * Do this before setting vol_state to VOLUME_DISMOUNTED: completion
+	 * work may still be waiting in __ocfs2_wait_on_mount().
+	 */
+	ocfs2_recovery_stop(osb);
 
 	/*
 	 * Now that recovery is shut down, and the osb is about to be
fs/ocfs2/journal.h +1 -0
index 19fc920d26b1c..4b52bf7b0938e 100644
@@ -147,6 +147,7 @@ void ocfs2_complete_recovery(struct work_struct *work);
 void ocfs2_wait_for_recovery(struct ocfs2_super *osb);
 
 int ocfs2_recovery_init(struct ocfs2_super *osb);
+void ocfs2_recovery_stop(struct ocfs2_super *osb);
 void ocfs2_recovery_exit(struct ocfs2_super *osb);
 void ocfs2_recovery_disable_quota(struct ocfs2_super *osb);
 
fs/ocfs2/super.c +3 -0
index fe4ab1659e0d9..ed5b303f56bf6 100644
@@ -1829,6 +1829,9 @@ static void ocfs2_dismount_volume(struct super_block *sb, int mnt_err)
 	/* Wait for worker to be done with the work structure in osb */
 	cancel_work_sync(&osb->dquot_drop_work);
 
+	/* Stop recovery producers before releasing their local allocators. */
+	ocfs2_recovery_stop(osb);
+
 	ocfs2_shutdown_local_alloc(osb);
 
 	ocfs2_truncate_log_shutdown(osb);
Signature · 1 line
2.53.0
author maintainer
#333 lore raw

PATCH 333/686 ocfs2/cluster: unlink socket containers before releasing resources

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 0988f0c0c7c908f0ff77fd8b90ce9918a1f41479 ]

A socket container's node and socket must remain alive while the container is on sock_containers. The debugfs formatter reads sc_node and sc_sock under o2net_debug_lock without taking their references, but sc_kref_release() releases both before taking that lock to unlink the container.

With CONFIG_DEBUG_FS enabled, a synchronous sender can retain its last socket-container reference after o2net_disconnect_node() has detached the connection and flushed o2net_wq. The caller runs outside that workqueue. After the sender removes its configfs dependency, node removal can proceed without waiting for the sender's final sc_put():

Sender (final sc_put) Configfs rmdir Debugfs reader
-------------------- -------------- --------------
o2nm_undepend_item()
Drop node item refs
o2nm_node_put()
[node can be freed]
sc_seq_show()
Lock debug lock Read sc_node->nd_name Unlock debug lock
sc_node = NULL
o2net_debug_del_sc()

The earlier socket release has a similar window. The container is still selectable while its socket has been released and sc_sock has not yet been cleared:

Sender (final sc_put) Debugfs reader
-------------------- --------------
sock_release(sc->sc_sock)
[socket can be freed]
sc_seq_show()
Lock debug lock Read sc_sock->sk fields Unlock debug lock
sc_sock = NULL
...
o2net_debug_del_sc()

Move o2net_debug_del_sc() before releasing either resource. Unlinking under the existing debug lock waits for an active formatter to finish and prevents later readers from selecting the container. This covers both socket fields and node fields, including nd_num in the stats formatter.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in string+0x42b/0x470
    Read of size 1 at addr ffff88810f56fc90 by task python3/506

    CPU: 0 UID: 0 PID: 506 Comm: python3 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
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     kasan_report+0xe0/0x110
     string+0x42b/0x470
     vsnprintf+0x330/0x1110
     seq_printf+0x1a8/0x260
     sc_seq_show+0x604/0x9f0
     seq_read_iter+0x480/0x1110
     seq_read+0x362/0x5a0
     full_proxy_read+0x11f/0x180
     vfs_read+0x1a0/0xc20
     ksys_read+0x111/0x200
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

(User register dump omitted.)

     </TASK>

    Allocated by task 497:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x28d/0x610
     o2nm_node_group_make_item+0xea/0x1a0
     configfs_mkdir+0x762/0xca0
     vfs_mkdir+0x399/0x7e0
     filename_mkdirat+0x129/0x450
     __x64_sys_mkdir+0x70/0xa0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 505:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x308/0x580
     config_item_cleanup+0x14b/0x230
     config_item_put+0x79/0x90
     sc_put+0x454/0x6e0
     o2net_send_message_vec+0x63d/0x1560
     o2net_send_message+0xa6/0xe0
     validation_send_write+0x17f/0x1d0
     full_proxy_write+0x11f/0x180
     vfs_write+0x25a/0x1010
     ksys_write+0x111/0x200
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff88810f56fc00
     which belongs to the cache kmalloc-512 of size 512
    The buggy address is located 144 bytes inside of
     freed 512-byte region [ffff88810f56fc00, ffff88810f56fe00)

(Page and shadow-memory dumps omitted.)

---
 fs/ocfs2/cluster/tcp.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/ocfs2/cluster/tcp.c +3 -2
index 32048c65b66ba..07b2252779410 100644
@@ -391,6 +391,9 @@ static void sc_kref_release(struct kref *kref)
 
 	sclog(sc, "releasing\n");
 
+	/* Unlink before freeing anything the debugfs readers dereference. */
+	o2net_debug_del_sc(sc);
+
 	if (sc->sc_sock) {
 		sock_release(sc->sc_sock);
 		sc->sc_sock = NULL;
@@ -400,8 +403,6 @@ static void sc_kref_release(struct kref *kref)
 	o2nm_node_put(sc->sc_node);
 	sc->sc_node = NULL;
 
-	o2net_debug_del_sc(sc);
-
 	if (sc->sc_page)
 		__free_page(sc->sc_page);
 	kfree(sc);
Signature · 1 line
2.53.0
author maintainer
#334 lore raw

PATCH 334/686 ocfs2: wait for filecheck kobject release after a failed add

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 a25c02af29c3e95128e4343fceb4bdace8e480a0 ]

The filecheck kobject and its release completion are embedded in ocfs2_super, so the osb must outlive the kobject. On a failed kobject_init_and_add(), creation clears fs_fcheck and calls kobject_put(), but returns without waiting for the release callback.

With CONFIG_DEBUG_KOBJECT_RELEASE, the last put queues delayed cleanup. Mount failure can then free the containing osb before the embedded release timer expires:

Mount failure Delayed cleanup
------------- ---------------
ocfs2_filecheck_create_sysfs()
kobject_init_and_add() fails
fs_fcheck = NULL
kobject_put()
queue delayed release
return to mount error cleanup
ocfs2_dismount_volume()
remove_sysfs() skips the wait
kfree(osb)
expire embedded release timer
access freed osb

The normal removal path waits for fs_kobj_unregister, but it returns early when fs_fcheck is NULL. The failed-add path therefore leaves the delayed work and its completion in freed storage.

Wait for the existing release completion after the failed-add kobject_put(), before returning to mount error cleanup. This keeps the enclosing osb alive until the kobject has finished releasing, matching the normal teardown path.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in __run_timers+0xa6d/0xa90
    Write of size 8 at addr ffff8881178a5658 by task swapper/0/0

    CPU: 0 UID: 0 PID: 0 Comm: swapper/0 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
    Call Trace:
     <IRQ>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? __run_timers+0xa6d/0xa90
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20e/0x420
     ? __run_timers+0xa6d/0xa90
     kasan_report+0xe0/0x110
     ? __run_timers+0xa6d/0xa90
     __run_timers+0xa6d/0xa90
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx___run_timers+0x10/0x10
     ? __lock_acquire+0x5a3/0x2140
     ? __pfx_do_raw_spin_lock+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     timer_expire_remote+0xfa/0x160
     ? __pfx_timer_expire_remote+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on+0x18/0x160
     tmigr_handle_remote_up+0x4ba/0x9d0
     ? __pfx_tmigr_handle_remote_up+0x10/0x10
     ? tmigr_handle_remote+0x21a/0x340
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x290
     ? __pfx_tmigr_handle_remote_up+0x10/0x10
     __walk_groups_from+0x5a/0x160
     tmigr_handle_remote+0x24f/0x340
     ? __pfx_tmigr_handle_remote+0x10/0x10
     ? lock_acquire+0x190/0x300
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x290
     run_timer_softirq+0x222/0x270
     ? __pfx_run_timer_softirq+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lockdep_hardirqs_on_prepare+0xb8/0x1a0
     ? srso_alias_return_thunk+0x5/0xfbef5
     handle_softirqs+0x1fa/0x8d0
     ? __pfx_handle_softirqs+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? _raw_spin_unlock+0x23/0x40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __hrtimer_rearm_deferred+0x1fb/0x5d0
     __irq_exit_rcu+0x113/0x1e0
     irq_exit_rcu+0xe/0x20
     sysvec_apic_timer_interrupt+0x6c/0x80
     </IRQ>
     <TASK>
     asm_sysvec_apic_timer_interrupt+0x1a/0x20
    RIP: 0010:pv_native_safe_halt+0xf/0x20
    Code: fa 18 01 e9 ee 37 ff fa 0f 1f 00 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 f3 0f 1e fa eb 07 0f 00 2d 23 c7 14 00 fb f4 <e9> c7 37 ff fa 66 2e 0f 1f 84 00 00 00 00 00 66 90 90 90 90 90 90
    RSP: 0018:ffffffff87c07cf8 EFLAGS: 00000206
    RAX: 0000000000045d0f RBX: ffffffff87c2d4c0 RCX: ffffffff86111e95
    RDX: 0000000000000000 RSI: 0000000000000000 RDI: ffffffff815b508e
    RBP: fffffbfff0f85a98 R08: 0000000000000001 R09: ffffed10310c68ba
    R10: ffff8881886345d3 R11: 0000000000000000 R12: 0000000000000001
    R13: 0000000000000000 R14: 1ffffffff0f80fa4 R15: dffffc0000000000
     ? ct_kernel_exit.constprop.0+0xc5/0xf0
     ? do_idle+0x3ae/0x650
     default_idle+0x9/0x10
     default_idle_call+0x6c/0xb0
     do_idle+0x3ae/0x650
     ? __pfx___schedule+0x10/0x10
     ? __pfx_do_idle+0x10/0x10
     ? rest_init+0x1cd/0x330
     ? srso_alias_return_thunk+0x5/0xfbef5
     cpu_startup_entry+0x54/0x60
     rest_init+0x1e1/0x330
     ? __pfx_acpi_read_bit_register+0x10/0x10
     ? __pfx_rest_init+0x10/0x10
     ? acpi_os_write_port+0x23/0xb0
     ? __pfx_kernel_init+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? acpi_ut_status_exit+0xd6/0x180
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? acpi_ut_status_exit+0xd6/0x180
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? acpi_enable_subsystem+0x2b0/0x4e0
     ? __pfx_x86_late_time_init+0x10/0x10
     start_kernel+0x417/0x4b0
     x86_64_start_reservations+0x18/0x30
     x86_64_start_kernel+0x111/0x120
     common_startup_64+0x13e/0x158
     </TASK>

    Allocated by task 494:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x28d/0x610
     ocfs2_initialize_super.isra.0+0xab/0x3070
     ocfs2_fill_super+0x801/0x3920
     get_tree_bdev_flags+0x35d/0x5f0
     vfs_get_tree+0x93/0x320
     fc_mount+0x1d/0x200
     path_mount+0x592/0x1e00
     __x64_sys_mount+0x24b/0x2d0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 494:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x308/0x580
     ocfs2_dismount_volume+0x43c/0x9b0
     ocfs2_fill_super+0x258f/0x3920
     get_tree_bdev_flags+0x35d/0x5f0
     vfs_get_tree+0x93/0x320
     fc_mount+0x1d/0x200
     path_mount+0x592/0x1e00
     __x64_sys_mount+0x24b/0x2d0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff8881178a4000
     which belongs to the cache kmalloc-8k of size 8192
    The buggy address is located 5720 bytes inside of
     freed 8192-byte region [ffff8881178a4000, ffff8881178a6000)

    The buggy address belongs to the physical page:
    page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x1178a0
    head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
    flags: 0x200000000000040(head|node=0|zone=2)
    page_type: f5(slab)
    raw: 0200000000000040 ffff888100043880 dead000000000122 0000000000000000
    raw: 0000000000000000 0000000000020002 00000000f5000000 0000000000000000
    head: 0200000000000040 ffff888100043880 dead000000000122 0000000000000000
    head: 0000000000000000 0000000000020002 00000000f5000000 0000000000000000
    head: 0200000000000003 fffffffffffffe01 00000000ffffffff 00000000ffffffff
    head: 0000000000000000 0000000000000000 00000000ffffffff 0000000000000000
    page dumped because: kasan: bad access detected

    Memory state around the buggy address:
     ffff8881178a5500: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff8881178a5580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
    >ffff8881178a5600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
                                                        ^
     ffff8881178a5680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff8881178a5700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
    ==================================================================
---
 fs/ocfs2/filecheck.c | 2 ++
 1 file changed, 2 insertions(+)
fs/ocfs2/filecheck.c +2 -0
index 47659ef73ca22..e676839078f44 100644
@@ -189,6 +189,8 @@ int ocfs2_filecheck_create_sysfs(struct ocfs2_super *osb)
 		/* Mount failure still calls ocfs2_filecheck_remove_sysfs(). */
 		entry->fs_fcheck = NULL;
 		kobject_put(&entry->fs_kobj);
+		/* Keep ocfs2_super alive until the kobject is released. */
+		wait_for_completion(&entry->fs_kobj_unregister);
 		kfree(fcheck);
 		return ret;
 	}
Signature · 1 line
2.53.0
author maintainer
#335 lore raw

PATCH 335/686 ocfs2: cache the mount context for dentry lock callbacks

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 5b4696e0bfc358619adaeab25ad35b4979af8331 ]

ocfs2_drop_dentry_lock() drops the inode reference before releasing the DENTRY lock. This lets inode eviction release the local inode and open locks before a remote unlink can proceed past the DENTRY lock.

A DLM callback can still arrive before the DENTRY lock has been dropped. ocfs2_get_dentry_osb() obtains the mount context through dl_inode->i_sb, which can access a freed inode when the downconvert thread drops the last inode reference in its post-unlock callback:

Downconvert thread DLM callback thread
------------------ -------------------
ocfs2_process_blocked_lock()

    ocfs2_dentry_post_unlock()
      ocfs2_dentry_lock_put()
        ocfs2_drop_dentry_lock()
          iput(dl->dl_inode)
          [inode reclaimed after RCU]
                                         ocfs2_blocking_ast()
                                           ocfs2_get_dentry_osb()
                                             dl->dl_inode->i_sb
          ocfs2_simple_drop_lockres()

Store the mount context in the DENTRY lock resource's l_priv field and use the default mount-context lookup. Recover the containing dentry lock with container_of(), as already done for refcount locks, and remove ocfs2_get_dentry_osb(). ocfs2_dismount_volume() shuts down the DLM before freeing the mount context, so callbacks can use it without accessing the inode. Preserve the existing iput-before-unlock order to avoid delaying local inode and open lock release until after the DENTRY lock is released.

Fixes 8ed6b23709b3 ("ocfs2: revert iput deferring code in ocfs2_drop_dentry_lock")
Assisted-by LLM
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc Heming Zhao <[email protected]>
Cc Jia-Ju Bai <[email protected]>
---
 fs/ocfs2/dcache.h  |  5 ++---
 fs/ocfs2/dlmglue.c | 16 ++++------------
 2 files changed, 6 insertions(+), 15 deletions(-)
fs/ocfs2/dcache.h +2 -3
index 7f246c5692d82..046ab9a807692 100644
@@ -17,9 +17,8 @@ struct ocfs2_dentry_lock {
 	u64			dl_parent_blkno;
 
 	/*
-	 * The ocfs2_dentry_lock keeps an inode reference until
-	 * dl_lockres has been destroyed. This is usually done in
-	 * ->d_iput() anyway, so there should be minimal impact.
+	 * The inode reference is dropped before dl_lockres is unlocked.
+	 * Callbacks must not use it to find the mount context during teardown.
 	 */
 	struct inode		*dl_inode;
 	struct ocfs2_lock_res	dl_lockres;
fs/ocfs2/dlmglue.c +4 -12
index 6f44f9f230596..fdd0ed900e7e7 100644
@@ -57,7 +57,6 @@ struct ocfs2_mask_waiter {
 #endif
 };
 
-static struct ocfs2_super *ocfs2_get_dentry_osb(struct ocfs2_lock_res *lockres);
 static struct ocfs2_super *ocfs2_get_inode_osb(struct ocfs2_lock_res *lockres);
 static struct ocfs2_super *ocfs2_get_file_osb(struct ocfs2_lock_res *lockres);
 static struct ocfs2_super *ocfs2_get_qinfo_osb(struct ocfs2_lock_res *lockres);
@@ -257,7 +256,6 @@ static const struct ocfs2_lock_res_ops ocfs2_orphan_scan_lops = {
 };
 
 static const struct ocfs2_lock_res_ops ocfs2_dentry_lops = {
-	.get_osb	= ocfs2_get_dentry_osb,
 	.post_unlock	= ocfs2_dentry_post_unlock,
 	.downconvert_worker = ocfs2_dentry_convert_worker,
 	.flags		= 0,
@@ -308,7 +306,7 @@ static inline struct ocfs2_dentry_lock *ocfs2_lock_res_dl(struct ocfs2_lock_res
 {
 	BUG_ON(lockres->l_type != OCFS2_LOCK_TYPE_DENTRY);
 
-	return (struct ocfs2_dentry_lock *)lockres->l_priv;
+	return container_of(lockres, struct ocfs2_dentry_lock, dl_lockres);
 }
 
 static inline struct ocfs2_mem_dqinfo *ocfs2_lock_res_qinfo(struct ocfs2_lock_res *lockres)
@@ -609,13 +607,6 @@ static __u64 ocfs2_get_dentry_lock_ino(struct ocfs2_lock_res *lockres)
 	return be64_to_cpu(inode_blkno_be);
 }
 
-static struct ocfs2_super *ocfs2_get_dentry_osb(struct ocfs2_lock_res *lockres)
-{
-	struct ocfs2_dentry_lock *dl = lockres->l_priv;
-
-	return OCFS2_SB(dl->dl_inode->i_sb);
-}
-
 void ocfs2_dentry_lock_res_init(struct ocfs2_dentry_lock *dl,
 				u64 parent, struct inode *inode)
 {
@@ -623,6 +614,7 @@ void ocfs2_dentry_lock_res_init(struct ocfs2_dentry_lock *dl,
 	u64 inode_blkno = OCFS2_I(inode)->ip_blkno;
 	__be64 inode_blkno_be = cpu_to_be64(inode_blkno);
 	struct ocfs2_lock_res *lockres = &dl->dl_lockres;
+	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
 
 	ocfs2_lock_res_init_once(lockres);
 
@@ -651,9 +643,9 @@ void ocfs2_dentry_lock_res_init(struct ocfs2_dentry_lock *dl,
 	memcpy(&lockres->l_name[OCFS2_DENTRY_LOCK_INO_START], &inode_blkno_be,
 	       sizeof(__be64));
 
-	ocfs2_lock_res_init_common(OCFS2_SB(inode->i_sb), lockres,
+	ocfs2_lock_res_init_common(osb, lockres,
 				   OCFS2_LOCK_TYPE_DENTRY, &ocfs2_dentry_lops,
-				   dl);
+				   osb);
 }
 
 static void ocfs2_super_lock_res_init(struct ocfs2_lock_res *res,
Signature · 1 line
2.53.0
author maintainer
#336 lore raw

PATCH 336/686 x86/init: Initialize wall clock in get_rtc_noop()

In reply to Greg Kroah-Hartman

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

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

From: Naman Jain <[email protected]>

[ Upstream commit 7d5af1f256fdecff6a7986bbc9146b69cb355bb5 ]

get_rtc_noop() is used when an RTC is unavailable, but leaves its output argument untouched. When CONFIG_INIT_STACK_ALL_ZERO is not enabled, timekeeping_init() may therefore receive a nonzero invalid persistent clock value and warn:

"Persistent clock returned invalid value"

Initialize the output to zero, the documented representation of an unsupported persistent clock.

---
 arch/x86/kernel/x86_init.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/kernel/x86_init.c +1 -1
index 0a2bbd674a6d9..c1e20abc7fe52 100644
@@ -36,7 +36,7 @@ static void iommu_shutdown_noop(void) { }
 bool __init bool_x86_init_noop(void) { return false; }
 void x86_op_int_noop(int cpu) { }
 int set_rtc_noop(const struct timespec64 *now) { return -EINVAL; }
-void get_rtc_noop(struct timespec64 *now) { }
+void get_rtc_noop(struct timespec64 *now) { *now = (struct timespec64){0}; }
 
 static __initconst const struct of_device_id of_cmos_match[] = {
 	{ .compatible = "motorola,mc146818" },
Signature · 1 line
2.53.0
author maintainer
#337 lore raw

PATCH 337/686 xfs: fix temporary cursor leak in btree shift corruption paths

In reply to Greg Kroah-Hartman

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

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

From: Jianyun Gao <[email protected]>

[ Upstream commit 2bbca049deeb1699cafd966cb2793fee576ee409 ]

In xfs_btree_lshift and xfs_btree_rshift, when XFS_IS_CORRUPT detects an invalid firstrec/lastrec result after xfs_btree_dup_cursor has successfully allocated a temporary cursor, the error path jumps to error0 which returns without freeing tcur. This leaks the cursor memory, the xfs_group reference, and the per-level buffer references held by the duplicated cursor. Jump to error1 instead, which calls xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR) to properly release all resources.

Fixes 9eaead51bed95 ("[XFS] implement generic xfs_btree_rshift")
---
 fs/xfs/libxfs/xfs_btree.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/xfs/libxfs/xfs_btree.c +2 -2
index dbe9df8c33004..b0824d381e7c6 100644
@@ -2567,7 +2567,7 @@ xfs_btree_lshift(
 		if (XFS_IS_CORRUPT(tcur->bc_mp, i != 1)) {
 			xfs_btree_mark_sick(cur);
 			error = -EFSCORRUPTED;
-			goto error0;
+			goto error1;
 		}
 
 		error = xfs_btree_decrement(tcur, level, &i);
@@ -2737,7 +2737,7 @@ xfs_btree_rshift(
 	if (XFS_IS_CORRUPT(tcur->bc_mp, i != 1)) {
 		xfs_btree_mark_sick(cur);
 		error = -EFSCORRUPTED;
-		goto error0;
+		goto error1;
 	}
 
 	error = xfs_btree_increment(tcur, level, &i);
Signature · 1 line
2.53.0
author maintainer
#338 lore raw

PATCH 338/686 net/sched: sch_qfq: prevent aggregate self-replacement

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

[ Upstream commit 2e54b3e187300893688c2c7517894f5d96732e05 ]

qfq_change_class() snapshots the current aggregate settings while holding the qdisc tree lock, but drops the lock before selecting the destination aggregate. During that gap, qfq_enqueue() can move the class to an aggregate matching the requested settings.

When qfq_change_class() resumes, qfq_find_agg() then returns cl->agg. If it is a singleton, qfq_deact_rm_from_agg() frees the aggregate before qfq_add_to_agg() immediately accesses the same pointer, causing a use-after-free.

While holding the tree lock, skip the replacement when the destination is already the current aggregate. Any estimator replacement has already completed, so the class change can finish normally.

---
 net/sched/sch_qfq.c | 3 +++
 1 file changed, 3 insertions(+)
net/sched/sch_qfq.c +3 -0
index 7d93690cb4360..d82b04827c2c4 100644
@@ -517,11 +517,14 @@ static int qfq_change_class(struct Qdisc *sch, u32 classid, u32 parentid,
 		sch_tree_lock(sch);
 		qfq_init_agg(q, new_agg, lmax, weight);
 	}
+	if (existing && new_agg == cl->agg)
+		goto unlock;
 	if (existing)
 		qfq_deact_rm_from_agg(q, cl);
 	else
 		qdisc_class_hash_insert(&q->clhash, &cl->common);
 	qfq_add_to_agg(q, new_agg, cl);
+unlock:
 	sch_tree_unlock(sch);
 	qdisc_class_hash_grow(sch, &q->clhash);
 
Signature · 1 line
2.53.0
author maintainer
#339 lore raw

PATCH 339/686 vhost-scsi: zero misaligned I/O bounce pages

In reply to Greg Kroah-Hartman

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

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

From: Shubham Antil <[email protected]>

[ Upstream commit 01c3a5fa6d641c93c7cef4fb25c5f12938316e18 ]

The misaligned I/O fallback copies the full bounce scatterlist to the request buffer during completion. If a data-in command transfers less than requested, part of a newly allocated bounce page can remain unwritten.

Allocate bounce pages with __GFP_ZERO so all bytes copied during completion have a defined value. This path is already the slow fallback for misaligned I/O, so the added initialization cost is acceptable.

Found during an LLM-assisted source audit and validated with a QEMU/KVM vhost-scsi target using misaligned data-in commands.

Fixes 5ced58bfa132 ("vhost-scsi: Fix alignment handling with windows")
Assisted-by LLM (OpenAI Codex, gpt-5.6-sol)

Message-ID: <[email protected]>

---
 drivers/vhost/scsi.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/vhost/scsi.c +6 -1
index deb4c8bfd3d57..fac400b25dad7 100644
@@ -906,7 +906,12 @@ vhost_scsi_copy_iov_to_sgl(struct vhost_scsi_cmd *cmd, struct iov_iter *iter,
 	}
 
 	for_each_sgtable_sg(sg_table, sg, i) {
-		page = alloc_page(GFP_KERNEL);
+		/*
+		 * Completion copies the full bounce buffer, including bytes the
+		 * target did not write. This is already the slow fallback for
+		 * misaligned I/O, so zeroing is acceptable here.
+		 */
+		page = alloc_page(GFP_KERNEL | __GFP_ZERO);
 		if (!page) {
 			ret = -ENOMEM;
 			goto err;
Signature · 1 line
2.53.0
author maintainer
#340 lore raw

PATCH 340/686 vhost: fix used ring index wrap in vhost_add_used_n_in_order

In reply to Greg Kroah-Hartman

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

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

From: Fang Xieyan <[email protected]>

[ Upstream commit e244725e86be02cd85cb878b3ed8570eba2e4be1 ]

vhost_add_used_n_in_order() advances start by nheads[i] but wraps it with a single subtraction. If start + nheads[i] >= 2 * vq->num, start can remain outside the ring.

With used-ring logging enabled, start > vq->num makes (vq->num - start) underflow. log_write() then sets bits beyond the dirty-log bitmap, potentially corrupting adjacent userspace memory. This is reachable on the vhost-net TX path with VIRTIO_F_IN_ORDER: done_idx can reach VHOST_NET_BATCH (64), triggering the issue with a 32-entry ring.

Wrap start with a mask to keep it within the ring. VHOST_SET_VRING_NUM enforces a nonzero power-of-two ring size, allowing start to be wrapped using & (vq->num - 1).

Fixes 67a873df0c41 ("vhost: basic in order support")

Message-ID: <[email protected]>

---
 drivers/vhost/vhost.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/vhost/vhost.c +1 -2
index ebdbf1cf9143a..78cee55cedf85 100644
@@ -3145,8 +3145,7 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
 		}
 		start += nheads[i];
 		new += nheads[i];
-		if (start >= vq->num)
-			start -= vq->num;
+		start &= vq->num - 1;
 	}
 
 	if (unlikely(vq->log_used)) {
Signature · 1 line
2.53.0
author maintainer
#341 lore raw

PATCH 341/686 iommu/virtio: Reset device before deleting virtqueues on probe failure

In reply to Greg Kroah-Hartman

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

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

From: Yuho Choi <[email protected]>

[ Upstream commit 1f8efac19a0870cdfdf8477e447e5a07ddce9623 ]

viommu_probe() marks the device DRIVER_OK before populating the event virtqueue and registering the IOMMU device in sysfs. viommu_fill_evtq() hands the device a set of device-writable buffers through virtqueue_add_inbuf(), so from that point on the device may write into them and into the rings.

If either step fails, the error path deletes the virtqueues without resetting the device first. The event buffers are allocated with devm_kmalloc_array() and are released as probe unwinds, so the device can go on writing to memory that has been freed.

Reset the device before deleting the virtqueues, the way viommu_remove() already does.

Fixes edcd69ab9a32 ("iommu: Add virtio-iommu driver")

Message-ID: <[email protected]>

---
 drivers/iommu/virtio-iommu.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
drivers/iommu/virtio-iommu.c +4 -2
index d314fa5cd8476..3aa54bd716728 100644
@@ -1227,12 +1227,12 @@ static int viommu_probe(struct virtio_device *vdev)
 	/* Populate the event queue with buffers */
 	ret = viommu_fill_evtq(viommu);
 	if (ret)
-		goto err_free_vqs;
+		goto err_reset_vdev;
 
 	ret = iommu_device_sysfs_add(&viommu->iommu, dev, NULL, "%s",
 				     virtio_bus_name(vdev));
 	if (ret)
-		goto err_free_vqs;
+		goto err_reset_vdev;
 
 	vdev->priv = viommu;
 
@@ -1244,6 +1244,8 @@ static int viommu_probe(struct virtio_device *vdev)
 
 	return 0;
 
+err_reset_vdev:
+	virtio_reset_device(vdev);
 err_free_vqs:
 	vdev->config->del_vqs(vdev);
 
Signature · 1 line
2.53.0
author maintainer
#342 lore raw

PATCH 342/686 vdpa/snet: Dont discard the DPU error in snet_send_ctrl_msg()

In reply to Greg Kroah-Hartman

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

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

From: Yuho Choi <[email protected]>

[ Upstream commit f41f153d49b4c18172ec61b69ba934c36e1be745 ]

snet_send_ctrl_msg() reads the error code the DPU reports when it ACKs a control message, but then overwrites it with the return value of snet_wait_for_dpu_completion(). As a result, a DESTROY, SUSPEND or RESUME that the DPU rejects is reported to the caller as a success as long as the DPU clears the opcode register in time.

For SUSPEND this means vhost-vdpa marks the device as suspended and lets userspace reprogram the vrings while the DPU is still running them; for DESTROY, snet_reset_dev() never even sees that the device failed to stop.

Return the error from the saved ACK value once the completion wait itself has succeeded.

Fixes 3f3a1675b731 ("vdpa/snet: support getting and setting VQ state")

Message-ID: <[email protected]>

---
 drivers/vdpa/solidrun/snet_ctrl.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/vdpa/solidrun/snet_ctrl.c +2 -1
index 3cef2571d15d3..1c3b5f2e44990 100644
@@ -291,7 +291,6 @@ static int snet_send_ctrl_msg(struct snet *snet, u16 opcode, u16 vq_idx)
 
 	/* Check for errors */
 	val = snet_read_ctrl(regs);
-	ret = SNET_VAL_TO_ERR(val);
 
 	/* Clear the chunk ready bit */
 	val &= ~SNET_CTRL_CHUNK_RDY_MASK;
@@ -301,6 +300,8 @@ static int snet_send_ctrl_msg(struct snet *snet, u16 opcode, u16 vq_idx)
 	if (ret)
 		SNET_WARN(pdev, "Timeout waiting for DPU to complete a control command, err %d\n",
 			  ret);
+	else
+		ret = SNET_VAL_TO_ERR(val);
 
 exit:
 	mutex_unlock(&snet->ctrl_lock);
Signature · 1 line
2.53.0
author maintainer
#343 lore raw

PATCH 343/686 drm/bridge: nwl-dsi: Cleanup endpoint mux control selection

In reply to Greg Kroah-Hartman

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

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

From: Esben Haabendal <[email protected]>

[ Upstream commit 8dad0ebd822f54102aadc6ca4f0f8777112d175d ]

Using the endpoint define values makes it more clear that the argument to mux_control_try_select() must be valid state integers, and not something that looks like a boolean.

The endpoint value is kept, as it will be used in a following patch that changes behavior slightly based on which endpoint is selected.

---
 drivers/gpu/drm/bridge/nwl-dsi.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
drivers/gpu/drm/bridge/nwl-dsi.c +6 -4
index 2f7429b24fc20..29f175c0d118c 100644
@@ -110,6 +110,8 @@ struct nwl_dsi {
 	int error;
 
 	struct nwl_dsi_transfer *xfer;
+
+	unsigned int endpoint;
 };
 
 static const struct regmap_config nwl_dsi_regmap_config = {
@@ -1088,13 +1090,12 @@ static int nwl_dsi_parse_dt(struct nwl_dsi *dsi)
 static int nwl_dsi_select_input(struct nwl_dsi *dsi)
 {
 	struct device_node *remote;
-	u32 use_dcss = 1;
 	int ret;
 
 	remote = of_graph_get_remote_node(dsi->dev->of_node, 0,
 					  NWL_DSI_ENDPOINT_LCDIF);
 	if (remote) {
-		use_dcss = 0;
+		dsi->endpoint = NWL_DSI_ENDPOINT_LCDIF;
 	} else {
 		remote = of_graph_get_remote_node(dsi->dev->of_node, 0,
 						  NWL_DSI_ENDPOINT_DCSS);
@@ -1103,11 +1104,12 @@ static int nwl_dsi_select_input(struct nwl_dsi *dsi)
 				      "No valid input endpoint found\n");
 			return -EINVAL;
 		}
+		dsi->endpoint = NWL_DSI_ENDPOINT_DCSS;
 	}
 
 	DRM_DEV_INFO(dsi->dev, "Using %s as input source\n",
-		     (use_dcss) ? "DCSS" : "LCDIF");
-	ret = mux_control_try_select(dsi->mux, use_dcss);
+		     (dsi->endpoint == NWL_DSI_ENDPOINT_DCSS) ? "DCSS" : "LCDIF");
+	ret = mux_control_try_select(dsi->mux, dsi->endpoint);
 	if (ret < 0)
 		DRM_DEV_ERROR(dsi->dev, "Failed to select input: %d\n", ret);
 
Signature · 1 line
2.53.0
author maintainer
#344 lore raw

PATCH 344/686 drm/bridge: nwl-dsi: Limit LCDIF specific sync override

In reply to Greg Kroah-Hartman

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

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

From: Esben Haabendal <[email protected]>

[ Upstream commit 54a88d9afcca66221d14f438d0960472984968ec ]

When using DCSS with NWL, overriding the mode flags to enforce active high sync is preventing the use of active low with downstream bridges, such as ti-sn65dsi83, which will not see such mode flags set by the panel.

Fixes 44cfc6233447 ("drm/bridge: Add NWL MIPI DSI host controller support")
---
 drivers/gpu/drm/bridge/nwl-dsi.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/gpu/drm/bridge/nwl-dsi.c +5 -2
index 29f175c0d118c..38bc83e7af475 100644
@@ -823,10 +823,13 @@ static int nwl_dsi_bridge_atomic_check(struct drm_bridge *bridge,
 				       struct drm_connector_state *conn_state)
 {
 	struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
+	struct nwl_dsi *dsi = bridge_to_dsi(bridge);
 
 	/* At least LCDIF + NWL needs active high sync */
-	adjusted_mode->flags |= (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC);
-	adjusted_mode->flags &= ~(DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC);
+	if (dsi->endpoint == NWL_DSI_ENDPOINT_LCDIF) {
+		adjusted_mode->flags |= (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC);
+		adjusted_mode->flags &= ~(DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC);
+	}
 
 	/*
 	 * Do a full modeset if crtc_state->active is changed to be true.
Signature · 1 line
2.53.0
author maintainer
#345 lore raw

PATCH 345/686 hwrng: virtio - prevent use-after-free after a failed restore

In reply to Greg Kroah-Hartman

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

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

From: Thorsten Blum <[email protected]>

[ Upstream commit 0f7bf47f5a0cc26320aa4b14f4504d03a07f4b74 ]

remove_common() frees the driver data during freeze, but does not clear vdev->priv, which points to freed memory. If probe_common() then fails during restore, a later remove or freeze can dereference the dangling pointer.

Clear vdev->priv on the probe_common() error cleanup path and before freeing the driver data in remove_common(). Also reset the device and return early from remove_common() if vdev->priv is already NULL for a safe teardown after a failed restore.

Fixes 08e53fbdb85c ("virtio-rng: support multiple virtio-rng devices")

Message-ID: <[email protected]>

---
 drivers/char/hw_random/virtio-rng.c | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/char/hw_random/virtio-rng.c +7 -0
index 2933f8cb769e4..fcb60d4deaacd 100644
@@ -187,6 +187,7 @@ static int probe_common(struct virtio_device *vdev)
 err_find:
 	ida_free(&rng_index_ida, index);
 err_ida:
+	vdev->priv = NULL;
 	kfree(vi);
 	return err;
 }
@@ -195,6 +196,11 @@ static void remove_common(struct virtio_device *vdev)
 {
 	struct virtrng_info *vi = vdev->priv;
 
+	if (!vi) {
+		virtio_reset_device(vdev);
+		return;
+	}
+
 	vi->hwrng_removed = true;
 	vi->data_avail = 0;
 	vi->data_idx = 0;
@@ -204,6 +210,7 @@ static void remove_common(struct virtio_device *vdev)
 	virtio_reset_device(vdev);
 	vdev->config->del_vqs(vdev);
 	ida_free(&rng_index_ida, vi->index);
+	vdev->priv = NULL;
 	kfree(vi);
 }
 
Signature · 1 line
2.53.0
author maintainer
#346 lore raw

PATCH 346/686 vduse: fix VA/PA confusion in the coherent page fault path

In reply to Greg Kroah-Hartman

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

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

From: chenglong.ma <[email protected]>

[ Upstream commit bb2e6f166547838fd7c320b01c90918b736f76e2 ]

vduse_domain_get_coherent_page() assumes that iotlb entries above bounce_size were installed by vduse_domain_alloc_coherent(), so it treats map->addr as a physical address. But vduse registers with use_va = true, and when the device is bound to vhost_vdpa, vhost_vdpa_va_map() stores a userspace virtual address in map->addr, which vduse_domain_set_map() then copies into the same iotlb. A process holding the domain file descriptor across a rebind can therefore fault in an arbitrary physical page with read/write access, ignoring the entry permissions.

Additionally, since the domain file mmap lacks VM_IO, the domain file itself can be mapped and passed to vhost_vdpa_va_map(), producing self-referential entries that bypass the coherent path check.

To fix, only translate entries whose backing file is the domain file itself in vduse_domain_get_coherent_page(), reject such entries in vduse_domain_set_map() since only external mappings should be imported, and set VM_IO on the domain file mmap so vhost_vdpa_va_map() refuses to map it in the first place.

Fixes 8c773d53fb7b ("vduse: Implement an MMU-based software IOTLB")
Cc Xie Yongji <[email protected]>
---
 drivers/vdpa/vdpa_user/iova_domain.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
drivers/vdpa/vdpa_user/iova_domain.c +10 -1
index e8b837df328f0..b8b2eb44410da 100644
@@ -76,6 +76,10 @@ int vduse_domain_set_map(struct vduse_iova_domain *domain,
 	for (map = vhost_iotlb_itree_first(iotlb, start, last); map;
 	     map = vhost_iotlb_itree_next(map, start, last)) {
 		map_file = (struct vdpa_map_file *)map->opaque;
+		if (!map_file || map_file->file == domain->file) {
+			ret = -EINVAL;
+			goto err;
+		}
 		ret = vduse_iotlb_add_range(domain, map->start, map->last,
 					    map->addr, map->perm,
 					    map_file->file,
@@ -226,6 +230,7 @@ vduse_domain_get_coherent_page(struct vduse_iova_domain *domain, u64 iova)
 {
 	u64 start = iova & PAGE_MASK;
 	u64 last = start + PAGE_SIZE - 1;
+	struct vdpa_map_file *map_file;
 	struct vhost_iotlb_map *map;
 	struct page *page = NULL;
 
@@ -234,6 +239,10 @@ vduse_domain_get_coherent_page(struct vduse_iova_domain *domain, u64 iova)
 	if (!map)
 		goto out;
 
+	map_file = (struct vdpa_map_file *)map->opaque;
+	if (!map_file || map_file->file != domain->file)
+		goto out;
+
 	page = pfn_to_page((map->addr + iova - map->start) >> PAGE_SHIFT);
 	get_page(page);
 out:
@@ -579,7 +588,7 @@ static int vduse_domain_mmap(struct file *file, struct vm_area_struct *vma)
 {
 	struct vduse_iova_domain *domain = file->private_data;
 
-	vm_flags_set(vma, VM_DONTDUMP | VM_DONTEXPAND);
+	vm_flags_set(vma, VM_IO | VM_DONTDUMP | VM_DONTEXPAND);
 	vma->vm_private_data = domain;
 	vma->vm_ops = &vduse_domain_mmap_ops;
 
Signature · 1 line
2.53.0
author maintainer
#347 lore raw

PATCH 347/686 inotify: do not coalesce rename events

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 581230d2ec3c0380917d1255792508851e7c4627 ]

inotify compares the mask, watch descriptor and name when coalescing adjacent unread events, but ignores their rename cookies. Distinct IN_MOVED_FROM events can therefore be coalesced, losing the cookie needed to match a later IN_MOVED_TO event.

For example, watch two directories with IN_MOVE. Move an entry from the first directory into an unwatched directory, recreate it under the same name, then move it from the first directory into the second watched directory before reading the events. The second IN_MOVED_FROM is merged with the first, while the IN_MOVED_TO retains the second rename's cookie. Userspace can no longer pair the second rename's events.

The original inotify implementation compared cookies before coalescing. The fsnotify conversion lost this comparison. Do not coalesce IN_MOVED_FROM or IN_MOVED_TO events, which carry the identity of their respective renames. Leave coalescing of other event types unchanged.

---
 fs/notify/inotify/inotify_fsnotify.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/notify/inotify/inotify_fsnotify.c +1 -1
index 7c326ec2e8a8c..6e3af6452dccb 100644
@@ -36,7 +36,7 @@ static bool event_compare(struct fsnotify_event *old_fsn,
 
 	old = INOTIFY_E(old_fsn);
 	new = INOTIFY_E(new_fsn);
-	if (old->mask & FS_IN_IGNORED)
+	if (old->mask & (FS_IN_IGNORED | FS_MOVE))
 		return false;
 	if ((old->mask == new->mask) &&
 	    (old->wd == new->wd) &&
Signature · 1 line
2.53.0
author maintainer
#348 lore raw

PATCH 348/686 blk-mq: end the request if getting a keyslot fails

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 e67cb6ed40e7f45912b63d7d575f18dfd2ebc98a ]

When blk_crypto_rq_get_keyslot() fails, blk_mq_submit_bio() ends the bio by hand and frees the request. By then blk_mq_bio_to_request() has done the IO accounting, which blk_mq_free_request() doesn't undo, so the in_flight counter never drops and iostat shows a device that is 100% busy. If the bio went through zone write plugging the zone stays plugged as well, and every later write to it waits forever.

Use blk_mq_end_request() like the dispatch path does for a request the driver rejected, after marking it for zone write plugging.

Move the call to blk_zone_write_plug_init_request() before blk_crypto_rq_get_keyslot() so that it doesn't need to be duplicated. It doesn't depend on the keyslot.

Fixes 99dc422335d8 ("block: support to account io_ticks precisely")
Fixes dd291d77cc90 ("block: Introduce zone write plugging")
---
 block/blk-mq.c | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
block/blk-mq.c +4 -5
index cced68a0e3c53..b7347c4462cb3 100644
@@ -3223,16 +3223,15 @@ void blk_mq_submit_bio(struct bio *bio)
 
 	blk_mq_bio_to_request(rq, bio, nr_segs);
 
+	if (bio_zone_write_plugging(bio))
+		blk_zone_write_plug_init_request(rq);
+
 	ret = blk_crypto_rq_get_keyslot(rq);
 	if (ret != BLK_STS_OK) {
-		bio_endio_status(bio, ret);
-		blk_mq_free_request(rq);
+		blk_mq_end_request(rq, ret);
 		return;
 	}
 
-	if (bio_zone_write_plugging(bio))
-		blk_zone_write_plug_init_request(rq);
-
 	if (op_is_flush(bio->bi_opf) && blk_insert_flush(rq))
 		return;
 
Signature · 1 line
2.53.0
author maintainer
#349 lore raw

PATCH 349/686 virtio_blk: use synchronous quiesce in virtblk_freeze_priv()

In reply to Greg Kroah-Hartman

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

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

From: Cong Zhang <[email protected]>

[ Upstream commit 6c6dec7883f8eb10b326bc9d109a4990c885d949 ]

blk_mq_run_work_fn() can call blk_mq_sched_dispatch_requests() through blk_mq_run_dispatch_ops(). The dispatcher checks QUEUE_FLAG_QUIESCED while the flag is clear. It can then be preempted before it gets a request. At that time, it has no queue usage reference, so blk_mq_freeze_queue() does not wait for it.

virtblk_freeze_priv() then calls blk_mq_quiesce_queue_nowait() and blk_mq_unfreeze_queue(). A new request can enter the queue. The old dispatcher can run again, use its old flag check, get the new request, and call virtio_queue_rq(). At the same time, virtblk_freeze_priv() can reset the device, delete the virtqueues, and free vblk->vqs. The old dispatcher can then use a deleted virtqueue or a NULL vblk->vqs, and the kernel can crash.

Fix this by using blk_mq_quiesce_queue(), which waits for dispatch code that was already running. Keep the existing freeze and unfreeze order. The queue remains quiesced until virtblk_restore_priv() calls blk_mq_unquiesce_queue().

---
 drivers/block/virtio_blk.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/block/virtio_blk.c +1 -1
index e577b02cf4003..84dc751266e9b 100644
@@ -1588,7 +1588,7 @@ static int virtblk_freeze_priv(struct virtio_device *vdev)
 
 	/* Ensure no requests in virtqueues before deleting vqs. */
 	memflags = blk_mq_freeze_queue(q);
-	blk_mq_quiesce_queue_nowait(q);
+	blk_mq_quiesce_queue(q);
 	blk_mq_unfreeze_queue(q, memflags);
 
 	/* Ensure we don't receive any more interrupts */
Signature · 1 line
2.53.0
author maintainer
#350 lore raw

PATCH 350/686 block: Return the soft block size for compat BLKBSZGET

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 57cd1a08717690e5ea01d7ac7a96bb33a2dca117 ]

BLKBSZGET returns the block device's soft block size, while BLKSSZGET returns its logical sector size. The compat BLKBSZGET_32 handler uses bdev_logical_block_size(), so it returns the wrong value when these sizes differ.

For example, on an x86_64 kernel a native query of a RAM or loop device with 512-byte logical sectors returns the initial soft block size of 4096 bytes, but an i386 process gets 512 bytes. This makes 32-bit blockdev --getbsz and the BSZ column of --report disagree with native queries, even without a preceding BLKBSZSET.

Use block_size() as the native handler and the pre-regression compat handler do, and correct the case comment to describe the soft size.

---
 block/ioctl.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
block/ioctl.c +2 -2
index 801f904b5af47..c038a4b27b573 100644
@@ -742,8 +742,8 @@ long compat_blkdev_ioctl(struct file *file, unsigned cmd, unsigned long arg)
 		return compat_put_ulong(argp, bdev_nr_sectors(bdev));
 
 	/* The data is compatible, but the command number is different */
-	case BLKBSZGET_32: /* get the logical block size (cf. BLKSSZGET) */
-		return put_int(argp, bdev_logical_block_size(bdev));
+	case BLKBSZGET_32: /* get the soft block size (cf. BLKSSZGET) */
+		return put_int(argp, block_size(bdev));
 	case BLKBSZSET_32:
 		return blkdev_bszset(file, mode, argp);
 	case BLKGETSIZE64_32:
Signature · 1 line
2.53.0