Skip to contentSkip to conversation

6.18.65-rc1 review

PATCH In review Greg Kroah-Hartman 12 participants 2,163 messages Nov 18 – Nov 20 Stable branch Page 11 of 17

lore
Share & tools
lore
author maintainer
#1329 lore raw

PATCH 1327/2151 mailbox: arm_mhuv2: time out if the receiver never comes up

In reply to Greg Kroah-Hartman

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

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

From: Linkai Gong <[email protected]>

[ Upstream commit 86976f7cc324aac254136a352f74ac17f21e574c ]

mhuv2_tx_init() waits forever for access_ready. Fail probe after 1s instead of hanging boot.

Fixes 5a6338cce9f4 ("mailbox: arm_mhuv2: Add driver")
---
 drivers/mailbox/arm_mhuv2.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/mailbox/arm_mhuv2.c +7 -2
index 213fd4a399937..a5d5a2e09bca4 100644
@@ -27,6 +27,7 @@
 
 #include <linux/amba/bus.h>
 #include <linux/interrupt.h>
+#include <linux/iopoll.h>
 #include <linux/mailbox_controller.h>
 #include <linux/mailbox/arm_mhuv2_message.h>
 #include <linux/module.h>
@@ -968,6 +969,7 @@ static int mhuv2_tx_init(struct amba_device *adev, struct mhuv2 *mhu,
 {
 	struct device *dev = mhu->mbox.dev;
 	int ret, i;
+	u32 val;
 
 	mhu->frame = SENDER_FRAME;
 	mhu->mbox.ops = &mhuv2_sender_ops;
@@ -1008,8 +1010,11 @@ static int mhuv2_tx_init(struct amba_device *adev, struct mhuv2 *mhu,
 out:
 	/* Wait for receiver to be ready */
 	writel_relaxed(0x1, &mhu->send->access_request);
-	while (!readl_relaxed(&mhu->send->access_ready))
-		continue;
+	if (readl_relaxed_poll_timeout(&mhu->send->access_ready, val, val,
+				       100, 1000000)) {
+		dev_err(dev, "receiver not ready\n");
+		return -ETIMEDOUT;
+	}
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#1330 lore raw

PATCH 1328/2151 mailbox: qcom-ipcc: remove stray disable_irq_wake() call

In reply to Greg Kroah-Hartman

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

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

From: Anup Vishwakarma <[email protected]>

[ Upstream commit 134ef0278d4e48bcc325a7699250dfe861c11953 ]

Commit afaf2ba5b430 ("mailbox: qcom-ipcc: Support interrupt wake up from suspend") replaced enable_irq_wake() with IRQF_NO_SUSPEND on the IRQ request, but left the paired disable_irq_wake() in remove() behind.

disable_irq_wake() decrements the IRQ's wake_depth. With no matching enable_irq_wake() left to increment it, wake_depth stays at 0 and irq_set_irq_wake() reports:

WARN(1, "Unbalanced IRQ %d wake disable\n", irq)

on every unbind. Since there is no enable_irq_wake() to pair it with, remove the stray disable_irq_wake() call; IRQF_NO_SUSPEND already provides the intended wake behaviour.

Fixes afaf2ba5b430 ("mailbox: qcom-ipcc: Support interrupt wake up from suspend")
---
 drivers/mailbox/qcom-ipcc.c | 1 -
 1 file changed, 1 deletion(-)
drivers/mailbox/qcom-ipcc.c +0 -1
index 43985fe6816c2..c1dec33290a79 100644
@@ -351,7 +351,6 @@ static void qcom_ipcc_remove(struct platform_device *pdev)
 {
 	struct qcom_ipcc *ipcc = platform_get_drvdata(pdev);
 
-	disable_irq_wake(ipcc->irq);
 	irq_domain_remove(ipcc->irq_domain);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1331 lore raw

PATCH 1329/2151 seq_buf: Export seq_buf_putmem_hex() and add KUnit tests

In reply to Greg Kroah-Hartman

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

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

From: Shuvam Pandey <[email protected]>

[ Upstream commit ae3197ee07cc8ec66261d891b2b5bf3879e7b852 ]

The seq_buf KUnit suite does not exercise seq_buf_putmem_hex().

Add one test for the len > 8 chunking path and one overflow test where a later chunk no longer fits in the buffer.

Export seq_buf_putmem_hex() as well so SEQ_BUF_KUNIT_TEST=m links cleanly. Without the export, modpost reports seq_buf_putmem_hex as undefined when seq_buf_kunit is built as a module.

Stable-dep-of: a09fb764832d ("seq_buf: Do not print an empty line from an overflowed seq_buf_do_printk()")

---
 lib/seq_buf.c             |  1 +
 lib/tests/seq_buf_kunit.c | 34 ++++++++++++++++++++++++++++++++++
 2 files changed, 35 insertions(+)
lib/seq_buf.c +1 -0
index f3f3436d60a94..b59488fa8135c 100644
@@ -298,6 +298,7 @@ int seq_buf_putmem_hex(struct seq_buf *s, const void *mem,
 	}
 	return 0;
 }
+EXPORT_SYMBOL_GPL(seq_buf_putmem_hex);
 
 /**
  * seq_buf_path - copy a path into the sequence buffer
lib/tests/seq_buf_kunit.c +34 -0
index 8a01579a978e6..eb466386bbefb 100644
@@ -184,6 +184,38 @@ static void seq_buf_get_buf_commit_test(struct kunit *test)
 	KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s));
 }
 
+static void seq_buf_putmem_hex_test(struct kunit *test)
+{
+	DECLARE_SEQ_BUF(s, 24);
+	const u8 data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+#ifdef __BIG_ENDIAN
+	const char *expected = "0001020304050607 0809 ";
+#else
+	const char *expected = "0706050403020100 0908 ";
+#endif
+
+	KUNIT_EXPECT_EQ(test, seq_buf_putmem_hex(&s, data, sizeof(data)), 0);
+	KUNIT_EXPECT_FALSE(test, seq_buf_has_overflowed(&s));
+	KUNIT_EXPECT_EQ(test, seq_buf_used(&s), strlen(expected));
+	KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), expected);
+}
+
+static void seq_buf_putmem_hex_overflow_test(struct kunit *test)
+{
+	DECLARE_SEQ_BUF(s, 20);
+	const u8 data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+#ifdef __BIG_ENDIAN
+	const char *expected = "0001020304050607 ";
+#else
+	const char *expected = "0706050403020100 ";
+#endif
+
+	KUNIT_EXPECT_EQ(test, seq_buf_putmem_hex(&s, data, sizeof(data)), -1);
+	KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s));
+	KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 20);
+	KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), expected);
+}
+
 static struct kunit_case seq_buf_test_cases[] = {
 	KUNIT_CASE(seq_buf_init_test),
 	KUNIT_CASE(seq_buf_declare_test),
@@ -194,6 +226,8 @@ static struct kunit_case seq_buf_test_cases[] = {
 	KUNIT_CASE(seq_buf_printf_test),
 	KUNIT_CASE(seq_buf_printf_overflow_test),
 	KUNIT_CASE(seq_buf_get_buf_commit_test),
+	KUNIT_CASE(seq_buf_putmem_hex_test),
+	KUNIT_CASE(seq_buf_putmem_hex_overflow_test),
 	{}
 };
 
Signature · 1 line
2.53.0
author maintainer
#1332 lore raw

PATCH 1330/2151 seq_buf: Do not print an empty line from an overflowed seq_buf_do_printk()

In reply to Greg Kroah-Hartman

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

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

From: Kees Cook <[email protected]>

[ Upstream commit a09fb764832dd7dbb9ccc38a9830f7294889c8ae ]

seq_buf_do_printk() prints a buffer line by line, then prints whatever follows the last newline. When a string has overflowed at exactly a newline, an empty line is printed since the pointer hasn't reached the overflow mark of the seq_buf. Switch to just check if the string is already empty and only print if not.

The only caller is the memory cgroup OOM report, so this could only ever add a blank line to a report whose statistics already did not fit.

Add a test that registers a console to count the records that seq_buf_do_printk() emits. It counts the records carrying the test's marker, and the records holding nothing but a line feed that arrive after one, so that unrelated kernel messages do not disturb it. Both states that reach the flaw are covered: exactly full, and overflowed.

Tests passed under qemu on ARCH=x86_64 with GCC 16.2.0 and CONFIG_KASAN=y, and on big-endian ARCH=s390 with GCC s390x-linux-gnu 16.2.0.

Fixes 96928d9032a7c ("seq_buf: Add seq_buf_do_printk() helper")
Assisted-by LLM
---
 lib/seq_buf.c             |   2 +-
 lib/tests/seq_buf_kunit.c | 132 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 133 insertions(+), 1 deletion(-)
lib/seq_buf.c +1 -1
index b59488fa8135c..5161987fc8916 100644
@@ -128,7 +128,7 @@ void seq_buf_do_printk(struct seq_buf *s, const char *lvl)
 	}
 
 	/* No trailing LF */
-	if (start < s->buffer + s->len)
+	if (*start)
 		printk("%s%s\n", lvl, start);
 }
 EXPORT_SYMBOL_GPL(seq_buf_do_printk);
lib/tests/seq_buf_kunit.c +132 -0

151 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#1333 lore raw

PATCH 1331/2151 ALSA: timer: Pin the module for userspace timer controllers

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

The static snd_utimer_ids IDA must remain live until a userspace timer controller has returned its ID. However, snd_utimer_fops has no owner, so anon_inode_getfd() does not take a reference to snd-timer for the controller file.

With CONFIG_SND_TIMER=m and CONFIG_SND_UTIMER=y, userspace can create a controller with SNDRV_TIMER_IOCTL_CREATE and close the native timer file. If no timer instances or dependent modules retain snd-timer, ordinary module unload can then overlap the controller's final release:

Controller final release Module unload
snd_utimer_release()
snd_utimer_free()
snd_timer_free(): unlink provider
snd_utimer_put_id()
enter ida_free()
delete_module()
alsa_timer_exit() free_module(): free MOD_DATA
access snd_utimer_ids.xa

The provider is already absent from snd_timer_free_all() when unload runs. Neither register_mutex nor the IDA's lock keeps module storage resident through the remaining IDA access. That access can therefore use freed module data and fault while acquiring the XArray lock, as shown in the Oops below.

Set snd_utimer_fops.owner to THIS_MODULE so anonymous-file creation takes the existing module reference. The VFS drops it only after snd_utimer_release() returns, keeping the IDA resident through ida_free() and preventing ordinary unload during that interval.

Oops report as below:

    BUG: unable to handle page fault for address: fffffbfff80480af
    #PF: supervisor read access in kernel mode
    #PF: error_code(0x0000) - not-present page
    PGD 1a7ff6067 P4D 1a7ff6067 PUD 1a7ff2067 PMD 100ad6067 PTE 0
    Oops: Oops: 0000 [#1] SMP KASAN NOPTI
    CPU: 0 UID: 0 PID: 485 Comm: alsa-utimer-fix Tainted: G           O        7.2.0-rc6-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
    Tainted: [O]=OOT_MODULE
    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
    RIP: 0010:kasan_byte_accessible+0x15/0x30
    Code: 00 00 0f 1f 00 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 0f 1f 40 d6 48 b8 00 00 00 00 00 fc ff df 48 c1 ef 03 48 01 c7 <0f> b6 07 3c 07 0f 96 c0 e9 69 f1 2b ff 66 66 2e 0f 1f 84 00 00 00
    RSP: 0018:ffff88811a457c48 EFLAGS: 00010086
    RAX: dffffc0000000000 RBX: ffffffffc0240578 RCX: 0000000000000000
    RDX: 0000000000000000 RSI: ffffffff861f111c RDI: fffffbfff80480af
    RBP: ffffffffc0240578 R08: 0000000000000001 R09: 0000000000000000
    R10: ffffffff891cc057 R11: ffff88811531ba00 R12: ffffffff861f111c
    R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000000
    FS:  00007ff190ff7780(0000) GS:ffff8881fda2a000(0000) knlGS:0000000000000000
    CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    CR2: fffffbfff80480af CR3: 0000000116890003 CR4: 0000000000770ef0
    PKRU: 55555554
    Call Trace:
     <TASK>
     __kasan_check_byte+0x13/0x50
     lock_acquire+0x113/0x2f0
     ? __pfx_pmbd_probe_hit_cookie+0x10/0x10
     ? lock_release+0xc8/0x280
     ? srso_alias_return_thunk+0x5/0xfbef5
     _raw_spin_lock_irqsave+0x3c/0x60
     ? ida_free+0xd4/0x2b0
     ida_free+0xd4/0x2b0
     ? __pfx_ida_free+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_locks_remove_file+0x10/0x10
     ? __fput+0x39f/0xa60
     ? fput_close_sync+0xff/0x200
     ? __pfx_fput_close_sync+0x10/0x10
     ? dnotify_flush+0x22/0x4b0
     ? __x64_sys_close+0x8c/0xf0
     ? do_syscall_64+0x115/0x6a0
     ? entry_SYSCALL_64_after_hwframe+0x77/0x7f
     </TASK>
    Modules linked in: snd(O) [last unloaded: snd_timer(O)]
    CR2: fffffbfff80480af
    ---[ end trace 0000000000000000 ]---
Fixes 37745918e0e7 ("ALSA: timer: Introduce virtual userspace-driven timers")
Assisted-by LLM
---
 sound/core/timer.c | 1 +
 1 file changed, 1 insertion(+)
sound/core/timer.c +1 -0
index 64bffc21295d4..37c298aa287c0 100644
@@ -2101,6 +2101,7 @@ static long snd_utimer_ioctl(struct file *file, unsigned int ioctl, unsigned lon
 }
 
 static const struct file_operations snd_utimer_fops = {
+	.owner		=	THIS_MODULE,
 	.llseek		=	noop_llseek,
 	.release	=	snd_utimer_release,
 	.unlocked_ioctl	=	snd_utimer_ioctl,
Signature · 1 line
2.53.0
author maintainer
#1334 lore raw

PATCH 1332/2151 ALSA: virtio: reset I/O message fill level on prepare

In reply to Greg Kroah-Hartman

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

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

From: Ting-Han Hou <[email protected]>

[ Upstream commit f0e9db0f84249b65a72b5fba43e91212281ad378 ]

Since commit fe981e67568c ("ALSA: virtio: use ack callback"), an I/O message is only queued to the device once the application has filled the whole period: virtsnd_pcm_msg_send() accumulates the transferred bytes in msg->length and queues the message when it reaches period_bytes. msg->length is reset to 0 only when the device completes the message.

If the substream is stopped (e.g. snd_pcm_drop()) while a period is only partially filled, the corresponding message is never queued and keeps its partial length. virtsnd_pcm_prepare() resets msg_count, hw_ptr and the indirect PCM state, but not msg->length. After the next start, the stale length is added to the new data, the sum never equals period_bytes, and the message is never sent again. Playback then stalls once hw_ptr reaches that period: writes fail with -EIO ("DMA or IRQ trouble") and drain fails with -EIO. Capture is affected the same way after a partial read.

Clear the fill level of all messages in prepare. Outside of the resume path, virtsnd_pcm_prepare() already refuses to run while I/O messages are pending, so no message is owned by the device at this point and the reset does not race with message completion.

Reproduced in QEMU (virtio-sound-pci, wav audiodev): prepare, write 1.5 periods, drop, prepare, write 16 full periods, drain. Without this patch WRITEI returns -EIO after 14 periods and DRAIN fails; with it all 16 periods are played and DRAIN succeeds. Period-aligned prefill works in both cases. The same sequence on capture (read 1.5 periods, drop, prepare, read 16 periods) fails with -EIO after 10 periods without this patch and reads all 16 with it.

Found by code inspection, confirmed with the reproducer above.

Fixes fe981e67568c ("ALSA: virtio: use ack callback")
Assisted-by LLM
---
 sound/virtio/virtio_pcm.h     |  2 ++
 sound/virtio/virtio_pcm_msg.c | 19 +++++++++++++++++++
 sound/virtio/virtio_pcm_ops.c |  1 +
 3 files changed, 22 insertions(+)
sound/virtio/virtio_pcm.h +2 -0
index 5dd1b43b94932..0f3a433175e49 100644
@@ -119,6 +119,8 @@ int virtsnd_pcm_msg_alloc(struct virtio_pcm_substream *vss,
 
 void virtsnd_pcm_msg_free(struct virtio_pcm_substream *vss);
 
+void virtsnd_pcm_msg_reset(struct virtio_pcm_substream *vss);
+
 int virtsnd_pcm_msg_send(struct virtio_pcm_substream *vss, unsigned long offset,
 			 unsigned long bytes);
 
sound/virtio/virtio_pcm_msg.c +19 -0
index 9778020a7ba89..d04763aba507e 100644
@@ -182,6 +182,25 @@ void virtsnd_pcm_msg_free(struct virtio_pcm_substream *vss)
 	vss->nmsgs = 0;
 }
 
+/**
+ * virtsnd_pcm_msg_reset() - Reset the fill level of all I/O messages.
+ * @vss: VirtIO PCM substream.
+ *
+ * Messages that were only partially filled by the application when the
+ * substream was stopped are never sent to the device, so their length must be
+ * cleared before the substream is started again.
+ *
+ * Context: Any context. Takes and releases the VirtIO substream spinlock.
+ */
+void virtsnd_pcm_msg_reset(struct virtio_pcm_substream *vss)
+{
+	unsigned int i;
+
+	guard(spinlock_irqsave)(&vss->lock);
+	for (i = 0; vss->msgs && i < vss->nmsgs; ++i)
+		vss->msgs[i]->length = 0;
+}
+
 /**
  * virtsnd_pcm_msg_send() - Send asynchronous I/O messages.
  * @vss: VirtIO PCM substream.
sound/virtio/virtio_pcm_ops.c +1 -0
index 1105e7ff3523a..1091100a4c982 100644
@@ -299,6 +299,7 @@ static int virtsnd_pcm_prepare(struct snd_pcm_substream *substream)
 	vss->xfer_xrun = false;
 	vss->suspended = false;
 	vss->msg_count = 0;
+	virtsnd_pcm_msg_reset(vss);
 
 	memset(&vss->pcm_indirect, 0, sizeof(vss->pcm_indirect));
 	vss->pcm_indirect.sw_buffer_size =
Signature · 1 line
2.53.0
author maintainer
#1335 lore raw

PATCH 1333/2151 RDMA/mlx5: Cancel deferred page-fault EQ work before teardown

In reply to Greg Kroah-Hartman

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

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

From: Prathamesh Deshpande <[email protected]>

[ Upstream commit aea64024ac37d29e99b82b315a56a9145dc0bc23 ]

Page-fault EQ work can remain queued after the notifier is disabled. Destroying the EQ before cancelling that work can let the worker access freed EQ memory.

Cancel the deferred work before destroying the EQ.

Fixes d5d284b829a6 ("{net,IB}/mlx5: Move Page fault EQ and ODP logic to RDMA")
---
 drivers/infiniband/hw/mlx5/odp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/infiniband/hw/mlx5/odp.c +1 -1
index 5cd1968a33d0d..796378cbf2a25 100644
@@ -1879,8 +1879,8 @@ mlx5_ib_odp_destroy_eq(struct mlx5_ib_dev *dev, struct mlx5_ib_pf_eq *eq)
 	if (!eq->core)
 		return 0;
 	mlx5_eq_disable(dev->mdev, eq->core, &eq->irq_nb);
-	err = mlx5_eq_destroy_generic(dev->mdev, eq->core);
 	cancel_work_sync(&eq->work);
+	err = mlx5_eq_destroy_generic(dev->mdev, eq->core);
 	destroy_workqueue(eq->wq);
 	mempool_destroy(eq->pool);
 
Signature · 1 line
2.53.0
author maintainer
#1336 lore raw

PATCH 1334/2151 RDMA/mlx5: Cancel software CQ notifications before teardown

In reply to Greg Kroah-Hartman

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

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

From: Prathamesh Deshpande <[email protected]>

[ Upstream commit a0ab2bb269e7fd8523f87950b91a42a36c7f8f2a ]

GSI completions queue notify_work to invoke the CQ completion handler. CQ destruction drains hardware events and core polling, but does not cancel this software notifier.

Fixes 25361e02c448 ("IB/mlx5: Generate completions in software")
---
 drivers/infiniband/hw/mlx5/cq.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/infiniband/hw/mlx5/cq.c +3 -0
index c6590dde68332..4f25aa8c72fd6 100644
@@ -1064,6 +1064,9 @@ int mlx5_ib_pre_destroy_cq(struct ib_cq *cq)
 	struct mlx5_ib_dev *dev = to_mdev(cq->device);
 	struct mlx5_ib_cq *mcq = to_mcq(cq);
 
+	if (!cq->uobject)
+		cancel_work_sync(&mcq->notify_work);
+
 	return mlx5_core_destroy_cq(dev->mdev, &mcq->mcq);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1337 lore raw

PATCH 1335/2151 bpftool: Fix out-of-bounds read in kprobe_multi link info dump

In reply to Greg Kroah-Hartman

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

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

From: Yuan Chen <[email protected]>

[ Upstream commit 0d5e3fc78a6f2522e6339743b8e5ecc02351a9dd ]

show_kprobe_multi_{plain,json}() walk the sorted kallsyms array against the sorted addr/cookie array with j as a cursor into the latter. The loop terminating condition is checked after the cursor has already been used to access the array:

    if (j++ == info->kprobe_multi.count)
            break;

After all count entries have been printed, j has been bumped to count, but the loop keeps running and dereferences data[count] -- one element past the end of the calloc(count, sizeof(*data)) allocation -- while comparing every remaining kallsyms symbol. If the out-of-bounds value happens to match a symbol address, a bogus entry with a garbage addr/cookie pair is printed to boot.

Fix the off-by-one by advancing the cursor before the comparison, so the loop terminates as soon as the last entry has been printed.

Verified with an ASAN build of bpftool against a live kprobe_multi link of 3 symbols:

before: ERROR: AddressSanitizer: heap-buffer-overflow READ of size 8
at link.c:860 (show_kprobe_multi_plain) and link.c:352 (show_kprobe_multi_json), 0 bytes after the 48-byte get_addr_cookie_array() allocation
after: clean output, no ASAN report

---
 tools/bpf/bpftool/link.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tools/bpf/bpftool/link.c +2 -2
index bdcd717b0348f..ddcdd8754add7 100644
@@ -364,7 +364,7 @@ show_kprobe_multi_json(struct bpf_link_info *info, json_writer_t *wtr)
 		}
 		jsonw_uint_field(json_wtr, "cookie", data[j].cookie);
 		jsonw_end_object(json_wtr);
-		if (j++ == info->kprobe_multi.count)
+		if (++j == info->kprobe_multi.count)
 			break;
 	}
 	jsonw_end_array(json_wtr);
@@ -799,7 +799,7 @@ static void show_kprobe_multi_plain(struct bpf_link_info *info)
 		else
 			printf("  ");
 
-		if (j++ == info->kprobe_multi.count)
+		if (++j == info->kprobe_multi.count)
 			break;
 	}
 error:
Signature · 1 line
2.53.0
author maintainer
#1338 lore raw

PATCH 1336/2151 dm-snapshot: make the chunk list sorted by the chunk number

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

[ Upstream commit bbd6f974d0386036e560af332b6b8cdd17010a72 ]

Commit 8581b19eb2c5 ("dm-snapshot: fix 'scheduling while atomic' on real-time kernels") replaced hlist_bl_for_each_entry with hlist_for_each_entry, but the two iteration macros differ after the loop
ends: hlist_bl_for_each_entry leaves "e" pointing at the last element, while hlist_for_each_entry() sets it to NULL.

The result is that the list is no longer sorted by chunk number as it was intended to be. This bug doesn't cause data corruption because dm_lookup_exception walks the full list.

Restore the invariant by tracking the list tail in the "prev" variable and appending after it with hlist_add_behind.

Fixes 8581b19eb2c5 ("dm-snapshot: fix 'scheduling while atomic' on real-time kernels")
Assisted-by Claude:claude-opus-5
---
 drivers/md/dm-snap.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)
drivers/md/dm-snap.c +10 -8
index 4a3a6cf772f77..c04e570756ef2 100644
@@ -770,7 +770,7 @@ static void dm_insert_exception(struct dm_exception_table *eh,
 				struct dm_exception *new_e)
 {
 	struct hlist_head *l;
-	struct dm_exception *e = NULL;
+	struct dm_exception *e = NULL, *prev = NULL;
 
 	l = &eh->table[exception_hash(eh, new_e->old_chunk)].head;
 
@@ -802,21 +802,23 @@ static void dm_insert_exception(struct dm_exception_table *eh,
 
 		if (new_e->old_chunk < e->old_chunk)
 			break;
+
+		prev = e;
 	}
 
 out:
-	if (!e) {
+	if (e && new_e->old_chunk < e->old_chunk) {
+		/* Add before an existing exception */
+		hlist_add_before(&new_e->hash_list, &e->hash_list);
+	} else if (prev) {
+		/* Add to l's tail: prev is the last exception in this slot */
+		hlist_add_behind(&new_e->hash_list, &prev->hash_list);
+	} else {
 		/*
 		 * Either the table doesn't support consecutive chunks or slot
 		 * l is empty.
 		 */
 		hlist_add_head(&new_e->hash_list, l);
-	} else if (new_e->old_chunk < e->old_chunk) {
-		/* Add before an existing exception */
-		hlist_add_before(&new_e->hash_list, &e->hash_list);
-	} else {
-		/* Add to l's tail: e is the last exception in this slot */
-		hlist_add_behind(&new_e->hash_list, &e->hash_list);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#1339 lore raw

PATCH 1337/2151 ALSA: control: Relax __free() variable declarations

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 7b4721ca3159bce6338dbdf9188b785083571ed4 ]

We used to have a variable declaration with __free() initialized with NULL. This was to keep the old coding style rule, but recently it's relaxed and rather recommends to follow the new rule to declare in place of use for __free() -- which avoids potential deadlocks or UAFs with nested cleanups.

Although the current code has no bug, per se, let's follow the new standard and move the declaration to the place of assignment (or directly assign the allocated result) instead of NULL initializations.

Fixes 7dba48a474e6 ("ALSA: control_led: Use guard() for locking")
Fixes 1052d9882269 ("ALSA: control: Use automatic cleanup of kfree()")

Stable-dep-of: 682d6bb5f783 ("ALSA: control_led: Fix deadlock between sysfs writes and card disconnect")

---
 sound/core/control.c        | 12 ++++++------
 sound/core/control_compat.c | 21 +++++++++++----------
 sound/core/control_led.c    | 12 ++++++------
 3 files changed, 23 insertions(+), 22 deletions(-)
sound/core/control.c +6 -6
index 750bb3f52d26d..cf601ad1a70be 100644
@@ -867,9 +867,9 @@ EXPORT_SYMBOL(snd_ctl_find_id);
 static int snd_ctl_card_info(struct snd_card *card, struct snd_ctl_file * ctl,
 			     unsigned int cmd, void __user *arg)
 {
-	struct snd_ctl_card_info *info __free(kfree) = NULL;
+	struct snd_ctl_card_info *info __free(kfree) =
+		kzalloc(sizeof(*info), GFP_KERNEL);
 
-	info = kzalloc(sizeof(*info), GFP_KERNEL);
 	if (! info)
 		return -ENOMEM;
 	scoped_guard(rwsem_read, &snd_ioctl_rwsem) {
@@ -1244,10 +1244,10 @@ static int snd_ctl_elem_read(struct snd_card *card,
 static int snd_ctl_elem_read_user(struct snd_card *card,
 				  struct snd_ctl_elem_value __user *_control)
 {
-	struct snd_ctl_elem_value *control __free(kfree) = NULL;
 	int result;
+	struct snd_ctl_elem_value *control __free(kfree) =
+		memdup_user(_control, sizeof(*control));
 
-	control = memdup_user(_control, sizeof(*control));
 	if (IS_ERR(control))
 		return PTR_ERR(control);
 
@@ -1320,11 +1320,11 @@ static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,
 static int snd_ctl_elem_write_user(struct snd_ctl_file *file,
 				   struct snd_ctl_elem_value __user *_control)
 {
-	struct snd_ctl_elem_value *control __free(kfree) = NULL;
 	struct snd_card *card;
 	int result;
+	struct snd_ctl_elem_value *control __free(kfree) =
+		memdup_user(_control, sizeof(*control));
 
-	control = memdup_user(_control, sizeof(*control));
 	if (IS_ERR(control))
 		return PTR_ERR(control);
 
sound/core/control_compat.c +11 -10
index 6459809ed3648..b8988a4bcd9b5 100644
@@ -80,10 +80,10 @@ static int snd_ctl_elem_info_compat(struct snd_ctl_file *ctl,
 				    struct snd_ctl_elem_info32 __user *data32)
 {
 	struct snd_card *card = ctl->card;
-	struct snd_ctl_elem_info *data __free(kfree) = NULL;
 	int err;
+	struct snd_ctl_elem_info *data __free(kfree) =
+		kzalloc(sizeof(*data), GFP_KERNEL);
 
-	data = kzalloc(sizeof(*data), GFP_KERNEL);
 	if (! data)
 		return -ENOMEM;
 
@@ -169,14 +169,15 @@ static int get_ctl_type(struct snd_card *card, struct snd_ctl_elem_id *id,
 			int *countp)
 {
 	struct snd_kcontrol *kctl;
-	struct snd_ctl_elem_info *info __free(kfree) = NULL;
 	int err;
 
 	guard(rwsem_read)(&card->controls_rwsem);
 	kctl = snd_ctl_find_id(card, id);
 	if (!kctl)
 		return -ENOENT;
-	info = kzalloc(sizeof(*info), GFP_KERNEL);
+
+	struct snd_ctl_elem_info *info __free(kfree) =
+		kzalloc(sizeof(*info), GFP_KERNEL);
 	if (info == NULL)
 		return -ENOMEM;
 	info->id = *id;
@@ -280,10 +281,10 @@ static int copy_ctl_value_to_user(void __user *userdata,
 static int __ctl_elem_read_user(struct snd_card *card,
 				void __user *userdata, void __user *valuep)
 {
-	struct snd_ctl_elem_value *data __free(kfree) = NULL;
 	int err, type, count;
+	struct snd_ctl_elem_value *data __free(kfree) =
+		kzalloc(sizeof(*data), GFP_KERNEL);
 
-	data = kzalloc(sizeof(*data), GFP_KERNEL);
 	if (data == NULL)
 		return -ENOMEM;
 
@@ -314,11 +315,11 @@ static int ctl_elem_read_user(struct snd_card *card,
 static int __ctl_elem_write_user(struct snd_ctl_file *file,
 				 void __user *userdata, void __user *valuep)
 {
-	struct snd_ctl_elem_value *data __free(kfree) = NULL;
 	struct snd_card *card = file->card;
 	int err, type, count;
+	struct snd_ctl_elem_value *data __free(kfree) =
+		kzalloc(sizeof(*data), GFP_KERNEL);
 
-	data = kzalloc(sizeof(*data), GFP_KERNEL);
 	if (data == NULL)
 		return -ENOMEM;
 
@@ -378,9 +379,9 @@ static int snd_ctl_elem_add_compat(struct snd_ctl_file *file,
 				   struct snd_ctl_elem_info32 __user *data32,
 				   int replace)
 {
-	struct snd_ctl_elem_info *data __free(kfree) = NULL;
+	struct snd_ctl_elem_info *data __free(kfree) =
+		kzalloc(sizeof(*data), GFP_KERNEL);
 
-	data = kzalloc(sizeof(*data), GFP_KERNEL);
 	if (! data)
 		return -ENOMEM;
 
sound/core/control_led.c +6 -6
index ae903af93dd32..f76a2f7ac7366 100644
@@ -243,12 +243,12 @@ static void snd_ctl_led_notify(struct snd_card *card, unsigned int mask,
 static int snd_ctl_led_set_id(int card_number, struct snd_ctl_elem_id *id,
 			      unsigned int group, bool set)
 {
-	struct snd_card *card __free(snd_card_unref) = NULL;
 	struct snd_kcontrol *kctl;
 	struct snd_kcontrol_volatile *vd;
 	unsigned int ioff, access, new_access;
+	struct snd_card *card __free(snd_card_unref) =
+		snd_card_ref(card_number);
 
-	card = snd_card_ref(card_number);
 	if (!card)
 		return -ENXIO;
 	guard(rwsem_write)(&card->controls_rwsem);
@@ -302,13 +302,13 @@ static void snd_ctl_led_clean(struct snd_card *card)
 
 static int snd_ctl_led_reset(int card_number, unsigned int group)
 {
-	struct snd_card *card __free(snd_card_unref) = NULL;
 	struct snd_ctl_led_ctl *lctl, *_lctl;
 	struct snd_ctl_led *led;
 	struct snd_kcontrol_volatile *vd;
 	bool change = false;
+	struct snd_card *card __free(snd_card_unref) =
+		snd_card_ref(card_number);
 
-	card = snd_card_ref(card_number);
 	if (!card)
 		return -ENXIO;
 
@@ -598,11 +598,11 @@ static ssize_t list_show(struct device *dev,
 			 struct device_attribute *attr, char *buf)
 {
 	struct snd_ctl_led_card *led_card = container_of(dev, struct snd_ctl_led_card, dev);
-	struct snd_card *card __free(snd_card_unref) = NULL;
 	struct snd_ctl_led_ctl *lctl;
 	size_t l = 0;
+	struct snd_card *card __free(snd_card_unref) =
+		snd_card_ref(led_card->number);
 
-	card = snd_card_ref(led_card->number);
 	if (!card)
 		return -ENXIO;
 	guard(rwsem_read)(&card->controls_rwsem);
Signature · 1 line
2.53.0
author maintainer
#1340 lore raw

PATCH 1338/2151 ALSA: control_led: Fix deadlock between sysfs writes and card disconnect

In reply to Greg Kroah-Hartman

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

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

From: Ali Ahmet Memiş <[email protected]>

[ Upstream commit 682d6bb5f783adea7fa2a5b05166bff01b338081 ]

snd_ctl_led_disconnect() removes the ctl-led sysfs files while holding card->controls_rwsem. device_unregister() waits for running sysfs callbacks which can deadlock when a concurrent write causes the attach or detach callback to wait for controls_rwsem.

Break kernfs active protection in the attach, detach and list callbacks and hold a module reference instead.

Fixes a135dfb5de15 ("ALSA: led control - add sysfs kcontrol LED marking layer")
---
 sound/core/control_led.c | 62 ++++++++++++++++++++++++++++++++++++----
 1 file changed, 57 insertions(+), 5 deletions(-)
sound/core/control_led.c +57 -5
index f76a2f7ac7366..415b186561152 100644
@@ -563,12 +563,43 @@ static ssize_t set_led_id(struct snd_ctl_led_card *led_card, const char *buf, si
 	return count;
 }
 
+/*
+ * snd_ctl_led_disconnect() removes these files with card->controls_rwsem
+ * held. so don't let the removal wait for a callback that takes it.
+ */
+static struct kernfs_node *snd_ctl_led_sysfs_enter(struct device *dev,
+						   struct device_attribute *attr)
+{
+	struct kernfs_node *kn;
+
+	if (!try_module_get(THIS_MODULE))
+		return NULL;
+	kn = sysfs_break_active_protection(&dev->kobj, &attr->attr);
+	if (!kn)
+		module_put(THIS_MODULE);
+	return kn;
+}
+
+static void snd_ctl_led_sysfs_exit(struct kernfs_node *kn)
+{
+	sysfs_unbreak_active_protection(kn);
+	module_put(THIS_MODULE);
+}
+
 static ssize_t attach_store(struct device *dev,
 			    struct device_attribute *attr,
 			    const char *buf, size_t count)
 {
 	struct snd_ctl_led_card *led_card = container_of(dev, struct snd_ctl_led_card, dev);
-	return set_led_id(led_card, buf, count, true);
+	struct kernfs_node *kn;
+	ssize_t ret;
+
+	kn = snd_ctl_led_sysfs_enter(dev, attr);
+	if (!kn)
+		return -ENODEV;
+	ret = set_led_id(led_card, buf, count, true);
+	snd_ctl_led_sysfs_exit(kn);
+	return ret;
 }
 
 static ssize_t detach_store(struct device *dev,
@@ -576,7 +607,15 @@ static ssize_t detach_store(struct device *dev,
 			    const char *buf, size_t count)
 {
 	struct snd_ctl_led_card *led_card = container_of(dev, struct snd_ctl_led_card, dev);
-	return set_led_id(led_card, buf, count, false);
+	struct kernfs_node *kn;
+	ssize_t ret;
+
+	kn = snd_ctl_led_sysfs_enter(dev, attr);
+	if (!kn)
+		return -ENODEV;
+	ret = set_led_id(led_card, buf, count, false);
+	snd_ctl_led_sysfs_exit(kn);
+	return ret;
 }
 
 static ssize_t reset_store(struct device *dev,
@@ -594,10 +633,8 @@ static ssize_t reset_store(struct device *dev,
 	return count;
 }
 
-static ssize_t list_show(struct device *dev,
-			 struct device_attribute *attr, char *buf)
+static ssize_t snd_ctl_led_list(struct snd_ctl_led_card *led_card, char *buf)
 {
-	struct snd_ctl_led_card *led_card = container_of(dev, struct snd_ctl_led_card, dev);
 	struct snd_ctl_led_ctl *lctl;
 	size_t l = 0;
 	struct snd_card *card __free(snd_card_unref) =
@@ -620,6 +657,21 @@ static ssize_t list_show(struct device *dev,
 	return l;
 }
 
+static ssize_t list_show(struct device *dev,
+			 struct device_attribute *attr, char *buf)
+{
+	struct snd_ctl_led_card *led_card = container_of(dev, struct snd_ctl_led_card, dev);
+	struct kernfs_node *kn;
+	ssize_t ret;
+
+	kn = snd_ctl_led_sysfs_enter(dev, attr);
+	if (!kn)
+		return -ENODEV;
+	ret = snd_ctl_led_list(led_card, buf);
+	snd_ctl_led_sysfs_exit(kn);
+	return ret;
+}
+
 static DEVICE_ATTR_WO(attach);
 static DEVICE_ATTR_WO(detach);
 static DEVICE_ATTR_WO(reset);
Signature · 1 line
2.53.0
author maintainer
#1341 lore raw

PATCH 1339/2151 drm/panfrost: Explicitly enable MMU interrupts at device init

In reply to Greg Kroah-Hartman

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

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

From: Adrián Larumbe <[email protected]>

[ Upstream commit 8a597d099b8b2f25df655cbe8e30765013784fed ]

Because the device must be in a position to accept jobs between the time drm_dev_register() is called and autosuspend first kicks in, there's a very narrow window inbetween during which jobs targeting the tiler buffer object would time out, since the device's PM status is 'Active', but no MMU interrupts were enabled at device initialisation time.

---
 drivers/gpu/drm/panfrost/panfrost_mmu.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/gpu/drm/panfrost/panfrost_mmu.c +9 -2
index f6b91c052cfbc..fcb3bac8fd458 100644
@@ -330,6 +330,12 @@ void panfrost_mmu_as_put(struct panfrost_device *pfdev, struct panfrost_mmu *mmu
 	WARN_ON(atomic_read(&mmu->as_count) < 0);
 }
 
+static void panfrost_mmu_enable_interrupts(struct panfrost_device *pfdev)
+{
+	mmu_write(pfdev, MMU_INT_CLEAR, ~0);
+	mmu_write(pfdev, MMU_INT_MASK, ~0);
+}
+
 void panfrost_mmu_reset(struct panfrost_device *pfdev)
 {
 	struct panfrost_mmu *mmu, *mmu_tmp;
@@ -349,8 +355,7 @@ void panfrost_mmu_reset(struct panfrost_device *pfdev)
 
 	spin_unlock(&pfdev->as_lock);
 
-	mmu_write(pfdev, MMU_INT_CLEAR, ~0);
-	mmu_write(pfdev, MMU_INT_MASK, ~0);
+	panfrost_mmu_enable_interrupts(pfdev);
 }
 
 static size_t get_pgsize(u64 addr, size_t size, size_t *count)
@@ -911,6 +916,8 @@ int panfrost_mmu_init(struct panfrost_device *pfdev)
 		return err;
 	}
 
+	panfrost_mmu_enable_interrupts(pfdev);
+
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1342 lore raw

PATCH 1340/2151 ACPI: PCI: pci_link: clear driver_data before free

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 691c33289b4d7a50b6fe1e03918bfbc21d4641c5 ]

acpi_pci_link_remove() frees the link object without clearing the ACPI device's driver_data pointer. The ACPI device survives hot-removal and can later be retrieved by acpi_fetch_acpi_dev(), leaving callers with a dangling pointer.

Clear driver_data before freeing the link.

Fixes db89b4f0dbab ("ACPI: catch calls of acpi_driver_data on pointer of wrong type")
[ rjw: Subject tweak ]
---
 drivers/acpi/pci_link.c | 1 +
 1 file changed, 1 insertion(+)
drivers/acpi/pci_link.c +1 -0
index bed7dc85612e3..303a1ba83bf2e 100644
@@ -780,6 +780,7 @@ static void acpi_pci_link_remove(struct acpi_device *device)
 	list_del(&link->list);
 	mutex_unlock(&acpi_link_lock);
 
+	device->driver_data = NULL;
 	kfree(link);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1343 lore raw

PATCH 1341/2151 drm/rockchip: dw_hdmi_qp: remove now-redundant call to drm_connector_attach_encoder()

In reply to Greg Kroah-Hartman

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

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

From: Luca Ceresoli <[email protected]>

[ Upstream commit 14a25df41b19aba228e66c0d9578e6e6b3cc58f9 ]

drm_connector_attach_encoder() is now called by
drm_bridge_connector_init().

Stable-dep-of: b6e19848c9db ("drm/rockchip: dw_hdmi_qp: Fix invalid drvdata access in PM ops")

---
 drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c +1 -1
index 409f1a1e82a06..9c30a9bfb6b9d 100644
@@ -563,7 +563,7 @@ static int dw_hdmi_qp_rockchip_bind(struct device *dev, struct device *master,
 		return ret;
 	}
 
-	return drm_connector_attach_encoder(connector, encoder);
+	return 0;
 }
 
 static void dw_hdmi_qp_rockchip_unbind(struct device *dev,
Signature · 1 line
2.53.0
author maintainer
#1344 lore raw

PATCH 1342/2151 drm/rockchip: dw_hdmi_qp: Fix invalid drvdata access in PM ops

In reply to Greg Kroah-Hartman

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

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

From: Cristian Ciocaltea <[email protected]>

[ Upstream commit b6e19848c9db535d81d6db85c7cc1324e6611791 ]

The system-sleep PM callbacks fetch the driver state via dev_get_drvdata() and dereference it unconditionally. However, the platform device is bound by ->probe(), which merely registers a component, hence the callbacks may well run when no valid state is available:

- Before the aggregate driver calls ->bind(), e.g. when the system suspends while probing is still deferred waiting for the VOP, dev_get_drvdata() returns NULL.

- After ->unbind(), or when ->bind() fails past platform_set_drvdata(), drvdata is left pointing to memory obtained via drmm_kzalloc(), which is released together with the DRM device, while this platform device remains bound and PM-capable.

Publish the driver data only after ->bind() completes successfully, and clear it in ->unbind(). This ensures that a non-NULL drvdata always represents live state, allowing each PM callback to rely on a single NULL check.

---
 drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c +9 -3
index 9c30a9bfb6b9d..d834d637655ea 100644
@@ -547,8 +547,6 @@ static int dw_hdmi_qp_rockchip_bind(struct device *dev, struct device *master,
 	drm_encoder_helper_add(encoder, &dw_hdmi_qp_rockchip_encoder_helper_funcs);
 	drm_simple_encoder_init(drm, encoder, DRM_MODE_ENCODER_TMDS);
 
-	platform_set_drvdata(pdev, hdmi);
-
 	hdmi->hdmi = dw_hdmi_qp_bind(pdev, encoder, &plat_data);
 	if (IS_ERR(hdmi->hdmi)) {
 		ret = PTR_ERR(hdmi->hdmi);
@@ -563,6 +561,8 @@ static int dw_hdmi_qp_rockchip_bind(struct device *dev, struct device *master,
 		return ret;
 	}
 
+	platform_set_drvdata(pdev, hdmi);
+
 	return 0;
 }
 
@@ -572,6 +572,8 @@ static void dw_hdmi_qp_rockchip_unbind(struct device *dev,
 {
 	struct rockchip_hdmi_qp *hdmi = dev_get_drvdata(dev);
 
+	dev_set_drvdata(dev, NULL);
+
 	cancel_delayed_work_sync(&hdmi->hpd_work);
 
 	drm_encoder_cleanup(&hdmi->encoder.encoder);
@@ -596,7 +598,8 @@ static int __maybe_unused dw_hdmi_qp_rockchip_suspend(struct device *dev)
 {
 	struct rockchip_hdmi_qp *hdmi = dev_get_drvdata(dev);
 
-	dw_hdmi_qp_suspend(dev, hdmi->hdmi);
+	if (hdmi)
+		dw_hdmi_qp_suspend(dev, hdmi->hdmi);
 
 	return 0;
 }
@@ -605,6 +608,9 @@ static int __maybe_unused dw_hdmi_qp_rockchip_resume(struct device *dev)
 {
 	struct rockchip_hdmi_qp *hdmi = dev_get_drvdata(dev);
 
+	if (!hdmi)
+		return 0;
+
 	hdmi->ctrl_ops->io_init(hdmi);
 
 	dw_hdmi_qp_resume(dev, hdmi->hdmi);
Signature · 1 line
2.53.0
author maintainer
#1345 lore raw

PATCH 1343/2151 drm/rockchip: dw_hdmi_qp: Cancel pending HPD work on suspend

In reply to Greg Kroah-Hartman

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

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

From: Cristian Ciocaltea <[email protected]>

[ Upstream commit 5d0aa771a5308f6a6c83eeaa89351a472ae580c3 ]

The HPD threaded handler debounces hotplug events by delaying hdmi->hpd_work for 150 ms. Nothing discards that work when the system goes to sleep: drm_kms_helper_poll_disable() only disables the HPD IRQ line via the bridge .hpd_disable() op, and disable_irq() merely waits for the threaded handler, which has already returned after arming the timer.

If the debounce expires during suspend, its non-freezable work may probe the connector and read the EDID over DDC. Since genpd powers off the HDMI controller's power domain in ->suspend_noirq(), this access may hit unpowered hardware and hang the system.

Cancel the work in the suspend callback. The DRM device is registered as a consumer of the HDMI device, so it always suspends first and the HPD IRQ is already disabled by that point, meaning nothing can re-arm the work behind our back. No counterpart is needed on resume, as the work gets scheduled again on the next hotplug interrupt.

---
 drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c +6 -2
index d834d637655ea..0953ff8073103 100644
@@ -598,8 +598,12 @@ static int __maybe_unused dw_hdmi_qp_rockchip_suspend(struct device *dev)
 {
 	struct rockchip_hdmi_qp *hdmi = dev_get_drvdata(dev);
 
-	if (hdmi)
-		dw_hdmi_qp_suspend(dev, hdmi->hdmi);
+	if (!hdmi)
+		return 0;
+
+	cancel_delayed_work_sync(&hdmi->hpd_work);
+
+	dw_hdmi_qp_suspend(dev, hdmi->hdmi);
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#1346 lore raw

PATCH 1344/2151 block: use iomap_dirty_folio for block devices

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

With CONFIG_BUFFER_HEAD=n, block devices are written back through iomap, but def_blk_aops uses filemap_dirty_folio, which only sets PG_dirty. It does not set the per-block dirty bits in the folio's iomap_folio_state, so iomap_writeback_folio() finds no dirty range, submits no I/O and clears PG_dirty, resulting in data loss.

Other iomap users set .dirty_folio to iomap_dirty_folio, which marks the folio's blocks dirty before calling filemap_dirty_folio().

This is only observable with block size < folio size. With a single block there is no iomap_folio_state to get out of sync and iomap_writeback_folio() marks the whole folio dirty itself. For a page-aligned device, this may require using the BLKBSZSET ioctl to set the block size, which requires CAP_SYS_ADMIN. A device whose size is not page aligned already gets a sub-page block size from set_init_blocksize(), so no ioctl and no privilege is needed.

To reproduce, on a device with a sub-page block size, write a known pattern with O_DIRECT, mmap the same range, store to it, msync() and fsync(), then read it back with O_DIRECT. A reproducer is available at [1].

[1] https://gist.github.com/tzussman/18ab05cba4b3fdc79cce0a69d1fd05b4

---
 block/fops.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
block/fops.c +1 -1
index cc9cb54fcd416..b805f360e4606 100644
@@ -593,7 +593,7 @@ static int blkdev_writepages(struct address_space *mapping,
 }
 
 const struct address_space_operations def_blk_aops = {
-	.dirty_folio	= filemap_dirty_folio,
+	.dirty_folio		= iomap_dirty_folio,
 	.release_folio		= iomap_release_folio,
 	.invalidate_folio	= iomap_invalidate_folio,
 	.read_folio		= blkdev_read_folio,
Signature · 1 line
2.53.0
author maintainer
#1347 lore raw

PATCH 1345/2151 block: skip redundant flush for O_DSYNC direct writes

In reply to Greg Kroah-Hartman

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

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

From: Zhenxian Ma <[email protected]>

[ Upstream commit bec7d36a6514153ded6ffe1323ab14912ced42df ]

For an O_DIRECT | O_DSYNC write, dio_bio_write_op() adds REQ_FUA to the bio, so the data is durable once the direct I/O returns. The unconditional generic_write_sync() in blkdev_write_iter() then issues a REQ_PREFLUSH that is redundant.

Skip it when the direct path already provided durability via FUA. A need_sync flag, clear by default, is set only for buffered writes and for the buffered fallback after a partial direct write.

Measured on a Seagate ST20000NM007D (20 TB, 7200 rpm, fua=1, write_cache=write back), Linux v7.2.0-rc7, single-threaded pwrite() loop opening the raw block device with O_WRONLY | O_DIRECT | O_DSYNC, 4 KiB writes for 60 s:

Sequential 4 KiB writes:

                            baseline    patched
    IOPS                       119.7     7497.0
    avg latency (us)            8357        133
    p50 latency (us)            8346        127
    p99 latency (us)            8368        395
    p99.9 latency (us)          8728        569

Random 4 KiB writes (100 GiB span):

                            baseline    patched
    IOPS                       156.1      666.4
    avg latency (us)            6405       1500
    p50 latency (us)            6186       1450
    p99 latency (us)           16133       2285
    p99.9 latency (us)         17250       9916

Stable-dep-of: 2fec4fd97cc3 ("block: take i_rwsem for the direct I/O write fallback")

---
 block/fops.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
block/fops.c +6 -2
index b805f360e4606..45398fcdaacbc 100644
@@ -761,6 +761,7 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
 	bool atomic = iocb->ki_flags & IOCB_ATOMIC;
 	loff_t size = bdev_nr_bytes(bdev);
 	size_t shorted = 0;
+	bool need_sync = false;
 	ssize_t ret;
 
 	if (bdev_read_only(bdev))
@@ -798,9 +799,11 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
 
 	if (iocb->ki_flags & IOCB_DIRECT) {
 		ret = blkdev_direct_write(iocb, from);
-		if (ret >= 0 && iov_iter_count(from))
+		if (ret >= 0 && iov_iter_count(from)) {
 			ret = direct_write_fallback(iocb, from, ret,
 					blkdev_buffered_write(iocb, from));
+			need_sync = true;
+		}
 	} else {
 		/*
 		 * Take i_rwsem and invalidate_lock to avoid racing with
@@ -810,9 +813,10 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
 		inode_lock_shared(bd_inode);
 		ret = blkdev_buffered_write(iocb, from);
 		inode_unlock_shared(bd_inode);
+		need_sync = true;
 	}
 
-	if (ret > 0)
+	if (ret > 0 && need_sync)
 		ret = generic_write_sync(iocb, ret);
 	iov_iter_reexpand(from, iov_iter_count(from) + shorted);
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#1348 lore raw

PATCH 1346/2151 block: only use REQ_FUA for direct writes if the device supports it

In reply to Greg Kroah-Hartman

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

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

From: Zhenxian Ma <[email protected]>

[ Upstream commit 0d492f40c4ad7af7b1625fd81dd58a7978ab97f6 ]

When a block device does not support FUA natively, the block layer emulates it by adding a cache flush to every write bio. An O_DSYNC direct write that spans N bios then costs N flushes, rather than the single generic_write_sync() issued after the write completes.

Introduce blkdev_dio_fua() to decide when REQ_FUA is set. A synchronous write can rely on generic_write_sync() when the device lacks FUA, so it sets REQ_FUA only when bdev_fua() is true. An asynchronous write completes in blkdev_bio_end_io() and cannot call the blocking generic_write_sync(), so it keeps REQ_FUA (emulated when needed) to stay durable.

Stable-dep-of: 2fec4fd97cc3 ("block: take i_rwsem for the direct I/O write fallback")

---
 block/fops.c | 32 +++++++++++++++++++++++++++-----
 1 file changed, 27 insertions(+), 5 deletions(-)
block/fops.c +27 -5
index 45398fcdaacbc..e94ad38f0a426 100644
@@ -26,12 +26,26 @@ static inline struct inode *bdev_file_inode(struct file *file)
 	return file->f_mapping->host;
 }
 
-static blk_opf_t dio_bio_write_op(struct kiocb *iocb)
+static bool blkdev_dio_fua(struct kiocb *iocb, struct block_device *bdev)
+{
+	if (!iocb_is_dsync(iocb))
+		return false;
+	/*
+	 * Async writes cannot fall back to generic_write_sync(), so they must
+	 * use FUA (emulated if needed); sync writes only need it when the
+	 * device supports FUA natively.
+	 */
+	if (!is_sync_kiocb(iocb))
+		return true;
+	return bdev_fua(bdev);
+}
+
+static blk_opf_t dio_bio_write_op(struct kiocb *iocb, struct block_device *bdev)
 {
 	blk_opf_t opf = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
 
 	/* avoid the need for a I/O completion work item */
-	if (iocb_is_dsync(iocb))
+	if (blkdev_dio_fua(iocb, bdev))
 		opf |= REQ_FUA;
 	return opf;
 }
@@ -76,7 +90,8 @@ static ssize_t __blkdev_direct_IO_simple(struct kiocb *iocb,
 		if (user_backed_iter(iter))
 			should_dirty = true;
 	} else {
-		bio_init(&bio, bdev, vecs, nr_pages, dio_bio_write_op(iocb));
+		bio_init(&bio, bdev, vecs, nr_pages,
+			 dio_bio_write_op(iocb, bdev));
 	}
 	bio.bi_iter.bi_sector = pos >> SECTOR_SHIFT;
 	bio.bi_write_hint = file_inode(iocb->ki_filp)->i_write_hint;
@@ -180,7 +195,7 @@ static ssize_t __blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
 	struct blkdev_dio *dio;
 	struct bio *bio;
 	bool is_read = (iov_iter_rw(iter) == READ), is_sync;
-	blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb);
+	blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb, bdev);
 	loff_t pos = iocb->ki_pos;
 	int ret = 0;
 
@@ -328,7 +343,7 @@ static ssize_t __blkdev_direct_IO_async(struct kiocb *iocb,
 					unsigned int nr_pages)
 {
 	bool is_read = iov_iter_rw(iter) == READ;
-	blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb);
+	blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb, bdev);
 	struct blkdev_dio *dio;
 	struct bio *bio;
 	loff_t pos = iocb->ki_pos;
@@ -803,6 +818,13 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
 			ret = direct_write_fallback(iocb, from, ret,
 					blkdev_buffered_write(iocb, from));
 			need_sync = true;
+		} else if (ret > 0 && !blkdev_dio_fua(iocb, bdev)) {
+			/*
+			 * The device does not support FUA, so REQ_FUA was not
+			 * set and the O_DSYNC direct write still needs a flush
+			 * to be made durable.
+			 */
+			need_sync = true;
 		}
 	} else {
 		/*
Signature · 1 line
2.53.0
author maintainer
#1349 lore raw

PATCH 1347/2151 block: take i_rwsem for the direct I/O write fallback

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 2fec4fd97cc3ce32283aac03b6882d3d36cbd4bb ]

Commit c0e473a0d226 ("block: fix race between set_blocksize and read paths") closed a race between set_blocksize() and block device I/O: with large sector size support, set_blocksize() can change i_blkbits and the mapping's minimum folio order while a concurrent reader still holds a folio of the old, smaller order, leading to crashes. In particular, it made blkdev_write_iter() wrap buffered writes in inode_lock_shared().

However, the direct I/O fallback path was missed in that conversion. blkdev_write_iter() passes blkdev_buffered_write() as an argument to direct_write_fallback() with no lock held. A direct write that completes only partially then finishes as a buffered write with no protection.

This can cause a BUG by racing partial direct writes against ioctl(BLKBSZSET). Writer threads issue O_DIRECT pwritev() with a two-segment iovec whose second segment is an unreadable PROT_NONE mapping. The direct path then writes the first segment, fails to pin the second, and returns short, entering the fallback. A second thread keeps toggling the second segment's protection so that some fallbacks get past fault_in_iov_iter_readable() and reach the page cache, a third thread populates the page cache with folios of the current block size via pread() and readahead(), and a fourth thread toggles the block size between 512 bytes and 64K with BLKBSZSET. The minimum folio order only moves with block sizes above PAGE_SIZE, i.e. with CONFIG_TRANSPARENT_HUGEPAGE raising BLK_MAX_BLOCK_SIZE to 64K.

On a CONFIG_DEBUG_VM kernel this yields the following BUG:

  page dumped because: VM_BUG_ON_FOLIO(folio_order(folio) < mapping_min_folio_order(mapping))
  kernel BUG at mm/filemap.c:858!
  Oops: invalid opcode: 0000 [#1] SMP KASAN NOPTI
  RIP: 0010:__filemap_add_folio+0x860/0x8d0
  Call Trace:
   filemap_add_folio+0xc9/0x1f0
   __filemap_get_folio_mpol+0x240/0x660
   iomap_write_begin+0xa87/0xd70
   iomap_file_buffered_write+0x304/0x6a0
   blkdev_write_iter+0x255/0x510
   do_iter_readv_writev+0x23d/0x3c0
   vfs_writev+0x211/0x7d0
   do_pwritev+0x121/0x190
   do_syscall_64+0x121/0x630
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

The same workload also trips WARN_ON_ONCE(pos >= folio_pos(folio) + fsize) in iomap_trim_folio_range().

Fix this by calling blkdev_buffered_write() in the fallback path under inode_lock_shared(), matching the plain buffered-write branch. With the fix the same workload runs clean.

A short IOCB_NOWAIT direct write reaches the same fallback. Taking i_rwsem there can now block behind set_blocksize(), and the fallback already blocks on writeback of the data it copied in direct_write_fallback(). blkdev_write_iter() already rejects a purely buffered IOCB_NOWAIT write with -EOPNOTSUPP, so do not enter the fallback for IOCB_NOWAIT at all: return the bytes the direct path already wrote, or -EAGAIN if none, and let the caller retry.

The reproducer used was written by an LLM, and is available at [1].

[1] https://gist.github.com/tzussman/69d06bc57d42a42989eb038b1b5aeb74

---
 block/fops.c | 25 ++++++++++++++++++++++---
 1 file changed, 22 insertions(+), 3 deletions(-)
block/fops.c +22 -3
index e94ad38f0a426..4b058996fe086 100644
@@ -815,9 +815,28 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
 	if (iocb->ki_flags & IOCB_DIRECT) {
 		ret = blkdev_direct_write(iocb, from);
 		if (ret >= 0 && iov_iter_count(from)) {
-			ret = direct_write_fallback(iocb, from, ret,
-					blkdev_buffered_write(iocb, from));
-			need_sync = true;
+			if (iocb->ki_flags & IOCB_NOWAIT) {
+				/*
+				 * The buffered fallback blocks on i_rwsem and
+				 * on writeback of the data it copied: return
+				 * the short direct write instead and let the
+				 * caller retry. The bytes already written
+				 * still need a flush if REQ_FUA was not set.
+				 */
+				if (!ret)
+					ret = -EAGAIN;
+				else if (!blkdev_dio_fua(iocb, bdev))
+					need_sync = true;
+			} else {
+				ssize_t ret2;
+
+				inode_lock_shared(bd_inode);
+				ret2 = blkdev_buffered_write(iocb, from);
+				inode_unlock_shared(bd_inode);
+				ret = direct_write_fallback(iocb, from, ret,
+							    ret2);
+				need_sync = true;
+			}
 		} else if (ret > 0 && !blkdev_dio_fua(iocb, bdev)) {
 			/*
 			 * The device does not support FUA, so REQ_FUA was not
Signature · 1 line
2.53.0
author maintainer
#1350 lore raw

PATCH 1348/2151 block: take i_rwsem for the splice read 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 5574b81c642e83d962732e86399020517f5f15af ]

def_blk_fops wires ->splice_read directly to filemap_splice_read(), which allocates folios based on mapping_min_folio_order() without any lock against set_blocksize(). A splice from a block device can race set_blocksize() raising the minimum folio order and insert a folio that is too small for the mapping. blkdev_read_iter() wraps filemap_read() in inode_lock_shared() for this reason, but the splice path was missed.

Splicing from a block device while toggling the block size between 512 bytes and 64K with BLKBSZSET hits this within seconds on a CONFIG_DEBUG_VM kernel:

  page dumped because: VM_BUG_ON_FOLIO(folio_order(folio) < mapping_min_folio_order(mapping))
  kernel BUG at mm/filemap.c:858!
  Oops: invalid opcode: 0000 [#1] SMP NOPTI
  RIP: 0010:__filemap_add_folio+0x51c/0x570
  Call Trace:
   filemap_add_folio+0x64/0x140
   page_cache_ra_order+0x1dd/0x3d0
   filemap_get_pages+0x153/0x760
   filemap_splice_read+0x13f/0x300
   splice_file_to_pipe+0xc0/0xd0
   do_splice+0x6a8/0x890
   __do_splice+0xb0/0x210
   __x64_sys_splice+0x80/0x100
   do_syscall_64+0x10e/0x520
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

Take inode_lock_shared() around filemap_splice_read(), like the read path does.

Fixes 3c20917120ce ("block/bdev: enable large folio support for large logical block sizes")
Assisted-by Claude:claude-fable-5
---
 block/fops.c | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)
block/fops.c +17 -1
index 4b058996fe086..de28ac38bcfef 100644
@@ -916,6 +916,22 @@ static ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
 	return ret;
 }
 
+/*
+ * Take i_rwsem to avoid racing with set_blocksize changing i_blkbits/folio
+ * order and punching out the pagecache.
+ */
+static ssize_t blkdev_splice_read(struct file *in, loff_t *ppos,
+		struct pipe_inode_info *pipe, size_t len, unsigned int flags)
+{
+	struct inode *bd_inode = bdev_file_inode(in);
+	ssize_t ret;
+
+	inode_lock_shared(bd_inode);
+	ret = filemap_splice_read(in, ppos, pipe, len, flags);
+	inode_unlock_shared(bd_inode);
+	return ret;
+}
+
 #define	BLKDEV_FALLOC_FL_SUPPORTED					\
 		(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |		\
 		 FALLOC_FL_ZERO_RANGE | FALLOC_FL_WRITE_ZEROES)
@@ -1017,7 +1033,7 @@ const struct file_operations def_blk_fops = {
 #ifdef CONFIG_COMPAT
 	.compat_ioctl	= compat_blkdev_ioctl,
 #endif
-	.splice_read	= filemap_splice_read,
+	.splice_read	= blkdev_splice_read,
 	.splice_write	= iter_file_splice_write,
 	.fallocate	= blkdev_fallocate,
 	.uring_cmd	= blkdev_uring_cmd,
Signature · 1 line
2.53.0
author maintainer
#1351 lore raw

PATCH 1349/2151 block: honor IOCB_NOWAIT in the block device buffered read 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 d16519a561f4ccc2cebbf52831435833cac1fec6 ]

blkdev_read_iter() takes inode_lock_shared() unconditionally around filemap_read(). Unlike blkdev_write_iter(), it does not reject IOCB_NOWAIT for buffered I/O, so a non-blocking read, or the buffered tail of a short IOCB_NOWAIT direct read, blocks behind set_blocksize() holding i_rwsem across sync_blockdev().

A preadv2(RWF_NOWAIT) issued while another thread changes the block size with a dirty page cache blocks for as long as sync_blockdev() takes, 4 to 6 seconds on a scsi_debug device with delay=5.

Use inode_trylock_shared() for IOCB_NOWAIT and return the bytes the direct path already read, or -EAGAIN if none, when the lock is contended, preserving NOWAIT semantics.

---
 block/fops.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
block/fops.c +9 -1
index de28ac38bcfef..1b3d86b85da9a 100644
@@ -906,7 +906,15 @@ static ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
 	 * Take i_rwsem and invalidate_lock to avoid racing with set_blocksize
 	 * changing i_blkbits/folio order and punching out the pagecache.
 	 */
-	inode_lock_shared(bd_inode);
+	if (iocb->ki_flags & IOCB_NOWAIT) {
+		if (!inode_trylock_shared(bd_inode)) {
+			if (!ret)
+				ret = -EAGAIN;
+			goto reexpand;
+		}
+	} else {
+		inode_lock_shared(bd_inode);
+	}
 	ret = filemap_read(iocb, to, ret);
 	inode_unlock_shared(bd_inode);
 
Signature · 1 line
2.53.0
author maintainer
#1352 lore raw

PATCH 1350/2151 block: dont fall back to buffered I/O for atomic writes

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 9fd1afea19fa7c4ba438a1d162739e0832073a4c ]

blkdev_direct_write() turns an -EBUSY from page cache invalidation into a 0 return, so an IOCB_ATOMIC write is retried in full through blkdev_buffered_write(), with no atomicity guarantee.

Skip the buffered fallback in blkdev_write_iter() for IOCB_ATOMIC, as it already does for IOCB_NOWAIT, so the -EBUSY case returns -EAGAIN and the caller retries, matching __iomap_dio_rw().

ext4 has the same fallback and only warns in it. For block devices the fallback can be skipped before any I/O is submitted, so fail early instead.

---
 block/fops.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
block/fops.c +3 -2
index 1b3d86b85da9a..17cdecf39398c 100644
@@ -815,10 +815,11 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
 	if (iocb->ki_flags & IOCB_DIRECT) {
 		ret = blkdev_direct_write(iocb, from);
 		if (ret >= 0 && iov_iter_count(from)) {
-			if (iocb->ki_flags & IOCB_NOWAIT) {
+			if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_ATOMIC)) {
 				/*
 				 * The buffered fallback blocks on i_rwsem and
-				 * on writeback of the data it copied: return
+				 * on writeback of the data it copied, and
+				 * can't provide torn-write protection: return
 				 * the short direct write instead and let the
 				 * caller retry. The bytes already written
 				 * still need a flush if REQ_FUA was not set.
Signature · 1 line
2.53.0
author maintainer
#1353 lore raw

PATCH 1351/2151 btrfs: add extra device item checks at mount

In reply to Greg Kroah-Hartman

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

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

From: Qu Wenruo <[email protected]>

[ Upstream commit 34308187395ff01f2d54007eb8b222f843bdf445 ]

[BUG]
There is a bug report where after a dev-replace, the replace source device with devid 4 is properly erased (dump tree shows it's the old devid 4), but the target device is still using devid 0.

When the user tries to mount the fs degraded, the mount failed with the following errors:

BTRFS: device fsid 84a1ed4a-365c-45c3-a9ee-a7df525dc3c9 devid 5 transid 1394395 /dev/sda (8:0) scanned by btrfs (261)
BTRFS: device fsid 84a1ed4a-365c-45c3-a9ee-a7df525dc3c9 devid 6 transid 1394395 /dev/sde (8:64) scanned by btrfs (261)
BTRFS: device fsid 84a1ed4a-365c-45c3-a9ee-a7df525dc3c9 devid 0 transid 1394395 /dev/sdd (8:48) scanned by btrfs (261)
BTRFS: device fsid 84a1ed4a-365c-45c3-a9ee-a7df525dc3c9 devid 3 transid 1394395 /dev/sdf (8:80) scanned by btrfs (261) BTRFS info (device sdd): first mount of filesystem 84a1ed4a-365c-45c3-a9ee-a7df525dc3c9
BTRFS info (device sdd): using crc32c (crc32c-intel) checksum algorithm
BTRFS warning (device sdd): devid 4 uuid 01e2081c-9c2a-4071-b9f4-e1b27e571ff5 is missing
BTRFS info (device sdd): bdev <missing disk> errs: wr 84994544, rd 15567, flush 65872, corrupt 0, gen 0 BTRFS info (device sdd): bdev /dev/sdd errs: wr 71489901, rd 0, flush 30001, corrupt 0, gen 0 BTRFS error (device sdd): replace without active item, run 'device scan --forget' on the target device BTRFS error (device sdd): failed to init dev_replace: -117
BTRFS error (device sdd): open_ctree failed: -117

[CAUSE]
The devid 0 didn't get its devid updated is its own problem, here I'm only focusing on the mount failure itself.

The mount is not caused by the missing device, as the fs has RAID1C3 for metadata and RAID10 for data, thus is completely able to tolerate one missing device.

The device tree shows the dev-replace has properly finished:

item 7 key (0 DEV_REPLACE 0) itemoff 15931 itemsize 72
src devid -1 cursor left 11091821199360 cursor right 11091821199360 mode ALWAYS state FINISHED write errors 0 uncorrectable read errors 0
^^^^^^^^

And the chunk tree shows there is no devid 0:

leaf 37980736602112 items 23 free space 12548 generation 1394388 owner CHUNK_TREE leaf 37980736602112 flags 0x1(WRITTEN) backref revision 1
fs uuid 84a1ed4a-365c-45c3-a9ee-a7df525dc3c9
chunk uuid d074c661-6311-4570-b59f-a5c83fd37f8e

         item 0 key (DEV_ITEMS DEV_ITEM 3) itemoff 16185 itemsize 98
                 devid 3 total_bytes 20000588955648 bytes_used 8282877984768
                 io_align 4096 io_width 4096 sector_size 4096 type 0
                 generation 0 start_offset 0 dev_group 0
                 seek_speed 0 bandwidth 0
                 uuid 0d596b69-fb0d-4031-b4af-a301d0868b8b
                 fsid 84a1ed4a-365c-45c3-a9ee-a7df525dc3c9
         ...

Which shows the first device is devid 3.

But there is indeed /dev/sdd with devid 0:

superblock: bytenr=65536, device=/dev/sdd
---------------------------------------------------------

  csum_type               0 (crc32c)
  csum_size               4
  csum                    0xd4bed87e [match]
  bytenr                  65536
  flags                   0x1
                          ( WRITTEN )
  magic                   _BHRfS_M [match]
  fsid                    84a1ed4a-365c-45c3-a9ee-a7df525dc3c9
  ...
  uuid_tree_generation    1394388
  dev_item.uuid           ee6532ad-5442-45f7-87fb-7703e29ed934
  dev_item.fsid           84a1ed4a-365c-45c3-a9ee-a7df525dc3c9 [match]
  dev_item.type           0
  dev_item.total_bytes    20000588955648
  dev_item.bytes_used     8292541661184
  dev_item.io_align       0
  dev_item.io_width       0
  dev_item.sector_size    0
  dev_item.devid          0 <<<

So this means device scan will register sdd as devid 0 into the fs, then during btrfs_init_dev_replace(), we located the replace progress item, found the previous replace is finished, but we still need to check if the dev-replace target device (devid 0) exists.

If that device exists, we error out showing that error message.

But to be honest the end user may not really remember which device is the replace target device, thus not sure what to do in the next step.

[ENHANCEMENT]
To make the error more obvious, and tell the end user which devices should be unregistered:

- Introduce BTRFS_DEV_STATE_ITEM_FOUND flag
During device item read from the chunk tree, set the flag for each found device item.

- Verify there is no device without the above flag during mount Even missing device should have that flag set.
If we found a device without that flag set, it means it's an unexpected one and should be rejected.

- More detailed error message on what to do next
This will show all unexpected devices and tell the end user to use 'btrfs dev scan --forget' to forget them or remove them before mount.

There is an example dmesg where a device of a valid filesystem is modified to have devid 0, then try degraded mount:

BTRFS info (device dm-6): first mount of filesystem 7c873869-844c-4b39-bd75-a96148bf4656
BTRFS info (device dm-6): using crc32c checksum algorithm
BTRFS warning (device dm-6): devid 3 uuid b4a9f35b-db42-4ac4-b55a-cbf81d3b9683 is missing
BTRFS error (device dm-6): devid 0 path /dev/mapper/test-scratch3 is registered but not found in chunk tree BTRFS error (device dm-6): please remove above devices or use 'btrfs device scan --forget <dev>' to unregister them before mount BTRFS error (device dm-6): open_ctree failed: -117

Stable-dep-of: f5166f53b60b ("btrfs: roll back sprout setup after device add failure")

---
 fs/btrfs/disk-io.c |  4 ++++
 fs/btrfs/volumes.c | 40 ++++++++++++++++++++++++++++++++++++++++
 fs/btrfs/volumes.h |  4 ++++
 3 files changed, 48 insertions(+)
fs/btrfs/disk-io.c +4 -0
index 083be891fc99f..2af30d1009783 100644
@@ -3566,6 +3566,10 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
 
+	if (unlikely(btrfs_verify_dev_items(fs_info))) {
+		ret = -EUCLEAN;
+		goto fail_block_groups;
+	}
 	ret = btrfs_verify_dev_extents(fs_info);
 	if (ret) {
 		btrfs_err(fs_info,
fs/btrfs/volumes.c +40 -0
index a07b5a4d6e4df..0f5c3d1606a48 100644
@@ -7401,6 +7401,7 @@ static int read_one_dev(struct extent_buffer *leaf,
 			return -EINVAL;
 		}
 	}
+	set_bit(BTRFS_DEV_STATE_ITEM_FOUND, &device->dev_state);
 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
 	   !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
@@ -8227,6 +8228,45 @@ int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
 	return verify_chunk_dev_extent_mapping(fs_info);
 }
 
+/*
+ * Ensure that all devices registered in the fs have their device items in the
+ * chunk tree.
+ *
+ * Return true if unexpected device is found.
+ * Return false otherwise.
+ */
+bool btrfs_verify_dev_items(const struct btrfs_fs_info *fs_info)
+{
+	struct btrfs_fs_devices *seed_devs;
+	struct btrfs_device *dev;
+	bool ret = false;
+
+	mutex_lock(&uuid_mutex);
+	list_for_each_entry(dev, &fs_info->fs_devices->devices, dev_list) {
+		if (!test_bit(BTRFS_DEV_STATE_ITEM_FOUND, &dev->dev_state)) {
+			btrfs_err(fs_info,
+			"devid %llu path %s is registered but not found in chunk tree",
+				  dev->devid, btrfs_dev_name(dev));
+			ret = true;
+		}
+	}
+	list_for_each_entry(seed_devs, &fs_info->fs_devices->seed_list, seed_list) {
+		list_for_each_entry(dev, &seed_devs->devices, dev_list) {
+			if (!test_bit(BTRFS_DEV_STATE_ITEM_FOUND, &dev->dev_state)) {
+				btrfs_err(fs_info,
+			"devid %llu path %s is registered but not found in chunk tree",
+					  dev->devid, btrfs_dev_name(dev));
+				ret = true;
+			}
+		}
+	}
+	mutex_unlock(&uuid_mutex);
+	if (ret)
+		btrfs_err(fs_info,
+"remove the above devices or use 'btrfs device scan --forget <dev>' to unregister them before mount");
+	return ret;
+}
+
 /*
  * Check whether the given block group or device is pinned by any inode being
  * used as a swapfile.
fs/btrfs/volumes.h +4 -0
index 2cbf8080eade0..ed900ce46e1fd 100644
@@ -101,6 +101,9 @@ enum btrfs_raid_types {
 #define BTRFS_DEV_STATE_FLUSH_SENT	(4)
 #define BTRFS_DEV_STATE_NO_READA	(5)
 
+/* Set when the device item is found in chunk tree, used to catch unexpected registered device. */
+#define BTRFS_DEV_STATE_ITEM_FOUND	(7)
+
 /* Special value encoding failure to write primary super block. */
 #define BTRFS_SUPER_PRIMARY_WRITE_ERROR		(INT_MAX / 2)
 
@@ -889,6 +892,7 @@ enum btrfs_raid_types __attribute_const__ btrfs_bg_flags_to_raid_index(u64 flags
 int btrfs_bg_type_to_factor(u64 flags);
 const char *btrfs_bg_type_to_raid_name(u64 flags);
 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info);
+bool btrfs_verify_dev_items(const struct btrfs_fs_info *fs_info);
 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical);
 
 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr);
Signature · 1 line
2.53.0
author maintainer
#1354 lore raw

PATCH 1352/2151 btrfs: introduce the device layout aware per-profile available space

In reply to Greg Kroah-Hartman

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

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

From: Qu Wenruo <[email protected]>

[ Upstream commit 52fead5eb8a743384bab24ca8c3695257c755f0f ]

[BUG]
There is a long known bug that if metadata is using RAID1 on two disks with unbalanced sizes, there is a very high chance to hit ENOSPC related transaction abort.

[CAUSE]
The root cause is in the available space estimation code:

- Factor based calculation
Just use all unallocated space, divide by the profile factor One obvious user is can_overcommit().

This can not handle the following example:

devid 1 unallocated: 1GiB
devid 2 unallocated: 50GiB
metadata type: RAID1

If using factor based estimation, we can use (1GiB + 50GiB) / 2 = 25.5GiB free space for metadata.
Thus we can continue allocating metadata (over-commit) way beyond the 1GiB limit.

But this estimation is completely wrong, in reality we can only allocate one single 1GiB RAID1 block group, thus if we continue over-commit, at one time we will hit ENOSPC at some critical path and flips the fs read-only.

[SOLUTION]
This patch will introduce per-profile available space estimation, which can provide chunk-allocator like behavior to give a (mostly) accurate result, with under-estimate corner cases.

There are some differences between the estimation and real chunk allocator:

- No consideration on hole size
It's fine for most cases, as all data/metadata strips are in 1GiB size thus there should not be any hole wasting much space.

And chunk allocator is able to use smaller stripes when there is really no other choice.

Although in theory this means it can lead to some over-estimation, it should not cause too much hassle in the real world.

The other benefit of such behavior is, we avoid dev-extent tree search completely, thus the overhead is very small.

- No true balance for certain cases
If we have 3 disks RAID1, and each device has 2GiB unallocated space, we can load balance the chunk allocation so that we can allocate 3GiB RAID1 chunks, and that's what chunk allocator will do.

But this current estimation code is using the largest available space to do a single allocation. Meaning the estimation will be 2GiB, thus under estimate.

Such under estimation is fine and after the first chunk allocation, the estimation will be updated and still give a correct 2GiB estimation.
So this only means the estimation will be a little conservative, which is safer for call sites like metadata over-commit check.

With that facility, for above 1GiB + 50GiB case, it will give a RAID1 estimation of 1GiB, instead of the incorrect 25.5GiB.

Or for a more complex example:
devid 1 unallocated: 1T
devid 2 unallocated: 1T
devid 3 unallocated: 10T

We will get an array of:
RAID10: 2T
RAID1: 2T
RAID1C3: 1T
RAID1C4: 0 (not enough devices)
DUP: 6T
RAID0: 3T
SINGLE: 12T
RAID5: 2T
RAID6: 1T

[IMPLEMENTATION]
And for the each profile , we go chunk allocator level calculation:
The pseudo code looks like:

  clear_virtual_used_space_of_all_rw_devices();
  do {
  	/*
  	 * The same as chunk allocator, despite used space,
  	 * we also take virtual used space into consideration.
  	 */
  	sort_device_with_virtual_free_space();

/*
* Unlike chunk allocator, we don't need to bother hole/stripe
* size, so we use the smallest device to make sure we can
* allocated as many stripes as regular chunk allocator */

  	stripe_size = device_with_smallest_free->avail_space;
	stripe_size = min(stripe_size, to_alloc / ndevs);

/*
* Allocate a virtual chunk, allocated virtual chunk will
* increase virtual used space, allow next iteration to
* properly emulate chunk allocator behavior. */
ret = alloc_virtual_chunk(stripe_size, &allocated_size); if (ret == 0)
avail += allocated_size;
} while (ret == 0)

This minimal available space based calculation is not perfect, but the important part is, the estimation is never exceeding the real available space.

This patch just introduces the infrastructure, no hooks are executed yet.

Stable-dep-of: f5166f53b60b ("btrfs: roll back sprout setup after device add failure")

---
 fs/btrfs/volumes.c | 164 +++++++++++++++++++++++++++++++++++++++++++++
 fs/btrfs/volumes.h |  34 ++++++++++
 2 files changed, 198 insertions(+)
fs/btrfs/volumes.c +164 -0
index 0f5c3d1606a48..ebf9132a295b6 100644
@@ -388,6 +388,7 @@ static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
 	INIT_LIST_HEAD(&fs_devs->alloc_list);
 	INIT_LIST_HEAD(&fs_devs->fs_list);
 	INIT_LIST_HEAD(&fs_devs->seed_list);
+	spin_lock_init(&fs_devs->per_profile_lock);
 
 	if (fsid) {
 		memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
@@ -5209,6 +5210,169 @@ static int btrfs_cmp_device_info(const void *a, const void *b)
 	return 0;
 }
 
+/*
+ * Return 0 if we allocated any virtual(*) chunk, and restore the size to
+ * @allocated.
+ * Return -ENOSPC if we have no more space to allocate virtual chunk
+ *
+ * *: A virtual chunk is a chunk that only exists during per-profile available
+ *    estimation.
+ *    Those numbers won't really take on-disk space, but only to emulate
+ *    chunk allocator behavior to get accurate estimation on available space.
+ *
+ *    Another difference is, a virtual chunk has no size limit and doesn't care
+ *    about holes in the device tree, allowing us to exhaust device space
+ *    much faster.
+ */
+static int alloc_virtual_chunk(struct btrfs_fs_info *fs_info,
+			       struct btrfs_device_info *devices_info,
+			       enum btrfs_raid_types type,
+			       u64 *allocated)
+{
+	const struct btrfs_raid_attr *raid_attr = &btrfs_raid_array[type];
+	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
+	struct btrfs_device *device;
+	u64 stripe_size;
+	int ndevs = 0;
+
+	lockdep_assert_held(&fs_info->chunk_mutex);
+
+	/* Go through devices to collect their unallocated space. */
+	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
+		u64 avail;
+
+		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
+					&device->dev_state) ||
+		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
+			continue;
+
+		if (device->total_bytes > device->bytes_used +
+				device->per_profile_allocated)
+			avail = device->total_bytes - device->bytes_used -
+				device->per_profile_allocated;
+		else
+			avail = 0;
+
+		avail = round_down(avail, fs_info->sectorsize);
+
+		/* And exclude the [0, 1M) reserved space. */
+		if (avail > BTRFS_DEVICE_RANGE_RESERVED)
+			avail -= BTRFS_DEVICE_RANGE_RESERVED;
+		else
+			avail = 0;
+
+		/*
+		 * Not enough to support a single stripe, this device
+		 * can not be utilized for chunk allocation.
+		 */
+		if (avail < BTRFS_STRIPE_LEN)
+			continue;
+
+		/*
+		 * Unlike chunk allocator, we don't care about stripe or hole
+		 * size, so here we use @avail directly.
+		 */
+		devices_info[ndevs].dev_offset = 0;
+		devices_info[ndevs].total_avail = avail;
+		devices_info[ndevs].max_avail = avail;
+		devices_info[ndevs].dev = device;
+		++ndevs;
+	}
+	sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
+	     btrfs_cmp_device_info, NULL);
+	ndevs = rounddown(ndevs, raid_attr->devs_increment);
+	if (ndevs < raid_attr->devs_min)
+		return -ENOSPC;
+	if (raid_attr->devs_max)
+		ndevs = min(ndevs, (int)raid_attr->devs_max);
+	else
+		ndevs = min(ndevs, (int)BTRFS_MAX_DEVS(fs_info));
+
+	/*
+	 * Stripe size will be determined by the device with the least
+	 * unallocated space.
+	 */
+	stripe_size = devices_info[ndevs - 1].total_avail;
+
+	for (int i = 0; i < ndevs; i++)
+		devices_info[i].dev->per_profile_allocated += stripe_size;
+	*allocated = div_u64(stripe_size * (ndevs - raid_attr->nparity),
+			     raid_attr->ncopies);
+	return 0;
+}
+
+static int calc_one_profile_avail(struct btrfs_fs_info *fs_info,
+				  enum btrfs_raid_types type,
+				  u64 *result_ret)
+{
+	struct btrfs_device_info *devices_info = NULL;
+	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
+	struct btrfs_device *device;
+	u64 allocated;
+	u64 result = 0;
+	int ret = 0;
+
+	lockdep_assert_held(&fs_info->chunk_mutex);
+	ASSERT(type >= 0 && type < BTRFS_NR_RAID_TYPES);
+
+	/* Not enough devices, quick exit, just update the result. */
+	if (fs_devices->rw_devices < btrfs_raid_array[type].devs_min) {
+		ret = -ENOSPC;
+		goto out;
+	}
+
+	devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
+			       GFP_NOFS);
+	if (!devices_info) {
+		ret = -ENOMEM;
+		goto out;
+	}
+	/* Clear virtual chunk used space for each device. */
+	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list)
+		device->per_profile_allocated = 0;
+
+	while (!alloc_virtual_chunk(fs_info, devices_info, type, &allocated))
+		result += allocated;
+
+out:
+	kfree(devices_info);
+	if (ret < 0 && ret != -ENOSPC)
+		return ret;
+	*result_ret = result;
+	return 0;
+}
+
+/* Update the per-profile available space array. */
+void btrfs_update_per_profile_avail(struct btrfs_fs_info *fs_info)
+{
+	u64 results[BTRFS_NR_RAID_TYPES];
+	int ret;
+
+	/*
+	 * Zoned is more complex as we can not simply get the amount of
+	 * available space for each device.
+	 */
+	if (btrfs_is_zoned(fs_info))
+		goto error;
+
+	for (int i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
+		ret = calc_one_profile_avail(fs_info, i, &results[i]);
+		if (ret < 0)
+			goto error;
+	}
+
+	spin_lock(&fs_info->fs_devices->per_profile_lock);
+	for (int i = 0; i < BTRFS_NR_RAID_TYPES; i++)
+		fs_info->fs_devices->per_profile_avail[i] = results[i];
+	spin_unlock(&fs_info->fs_devices->per_profile_lock);
+	return;
+error:
+	spin_lock(&fs_info->fs_devices->per_profile_lock);
+	for (int i = 0; i < BTRFS_NR_RAID_TYPES; i++)
+		fs_info->fs_devices->per_profile_avail[i] = U64_MAX;
+	spin_unlock(&fs_info->fs_devices->per_profile_lock);
+}
+
 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
 {
 	if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
fs/btrfs/volumes.h +34 -0
index ed900ce46e1fd..b3b9329f4cf9a 100644
@@ -22,6 +22,7 @@
 #include <uapi/linux/btrfs_tree.h>
 #include "messages.h"
 #include "extent-io-tree.h"
+#include "fs.h"
 
 struct block_device;
 struct bdev_handle;
@@ -204,6 +205,12 @@ struct btrfs_device {
 
 	/* Bandwidth limit for scrub, in bytes */
 	u64 scrub_speed_max;
+
+	/*
+	 * A temporary number of allocated space during per-profile
+	 * available space calculation.
+	 */
+	u64 per_profile_allocated;
 };
 
 /*
@@ -471,6 +478,15 @@ struct btrfs_fs_devices {
 	/* Checksum mode - offload it or do it synchronously. */
 	enum btrfs_offload_csum_mode offload_csum_mode;
 #endif
+
+	/*
+	 * Each value indicates the available space for that profile.
+	 * U64_MAX means the estimation is unavailable.
+	 *
+	 * Protected by per_profile_lock;
+	 */
+	u64 per_profile_avail[BTRFS_NR_RAID_TYPES];
+	spinlock_t per_profile_lock;
 };
 
 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info)	\
@@ -893,6 +909,24 @@ int btrfs_bg_type_to_factor(u64 flags);
 const char *btrfs_bg_type_to_raid_name(u64 flags);
 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info);
 bool btrfs_verify_dev_items(const struct btrfs_fs_info *fs_info);
+void btrfs_update_per_profile_avail(struct btrfs_fs_info *fs_info);
+
+static inline bool btrfs_get_per_profile_avail(struct btrfs_fs_info *fs_info,
+					       u64 profile, u64 *avail_ret)
+{
+	enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(profile);
+	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
+	bool uptodate = false;
+
+	spin_lock(&fs_devices->per_profile_lock);
+	if (fs_devices->per_profile_avail[index] != U64_MAX) {
+		uptodate = true;
+		*avail_ret = fs_devices->per_profile_avail[index];
+	}
+	spin_unlock(&fs_info->fs_devices->per_profile_lock);
+	return uptodate;
+}
+
 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical);
 
 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr);
Signature · 1 line
2.53.0
author maintainer
#1355 lore raw

PATCH 1353/2151 btrfs: update per-profile available estimation

In reply to Greg Kroah-Hartman

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

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

From: Qu Wenruo <[email protected]>

[ Upstream commit c84053d9f7f758c79320716caa098cafc70a74da ]

This involves the following timing:

- Chunk allocation
- Chunk removal
- After Mount
- New device
- Device removal
- Device shrink
- Device enlarge

And since the function btrfs_update_per_profile_avail() will not return an error, this won't cause new error handling path.

Although when btrfs_update_per_profile_avail() failed (only ENOSPC possible) it will mark the per-profile available estimation as unreliable, so later btrfs_get_per_profile_avail() will return false and require the caller to have a fallback solution.

The function btrfs_update_per_profile_avail() will be executed with chunk_mutex hold, thus it will slightly slow down those involved functions, but not a lot.

As all the core workload is just various u64 calculations inside a loop, without any tree search, the overhead should be acceptable even for all supported 9 profiles.

For 4 disks (which exercises all 9 profiles), the execution time of that function will still be less than 10 us.

Stable-dep-of: f5166f53b60b ("btrfs: roll back sprout setup after device add failure")

---
 fs/btrfs/volumes.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
fs/btrfs/volumes.c +19 -1
index ebf9132a295b6..a0984d6332dca 100644
@@ -2339,6 +2339,7 @@ int btrfs_rm_device(struct btrfs_fs_info *fs_info,
 		mutex_lock(&fs_info->chunk_mutex);
 		list_del_init(&device->dev_alloc_list);
 		device->fs_devices->rw_devices--;
+		btrfs_update_per_profile_avail(fs_info);
 		mutex_unlock(&fs_info->chunk_mutex);
 	}
 
@@ -2450,6 +2451,7 @@ int btrfs_rm_device(struct btrfs_fs_info *fs_info,
 		list_add(&device->dev_alloc_list,
 			 &fs_devices->alloc_list);
 		device->fs_devices->rw_devices++;
+		btrfs_update_per_profile_avail(fs_info);
 		mutex_unlock(&fs_info->chunk_mutex);
 	}
 	return ret;
@@ -2937,6 +2939,7 @@ int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path
 	 */
 	btrfs_clear_space_info_full(fs_info);
 
+	btrfs_update_per_profile_avail(fs_info);
 	mutex_unlock(&fs_info->chunk_mutex);
 
 	/* Add sysfs device entry */
@@ -2947,6 +2950,7 @@ int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path
 	if (seeding_dev) {
 		mutex_lock(&fs_info->chunk_mutex);
 		ret = init_first_rw_device(trans);
+		btrfs_update_per_profile_avail(fs_info);
 		mutex_unlock(&fs_info->chunk_mutex);
 		if (unlikely(ret)) {
 			btrfs_abort_transaction(trans, ret);
@@ -3033,6 +3037,7 @@ int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path
 				    orig_super_total_bytes);
 	btrfs_set_super_num_devices(fs_info->super_copy,
 				    orig_super_num_devices);
+	btrfs_update_per_profile_avail(fs_info);
 	mutex_unlock(&fs_info->chunk_mutex);
 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
 error_trans:
@@ -3126,6 +3131,7 @@ int btrfs_grow_device(struct btrfs_trans_handle *trans,
 	if (list_empty(&device->post_commit_list))
 		list_add_tail(&device->post_commit_list,
 			      &trans->transaction->dev_update_list);
+	btrfs_update_per_profile_avail(fs_info);
 	mutex_unlock(&fs_info->chunk_mutex);
 
 	btrfs_reserve_chunk_metadata(trans, false);
@@ -3495,6 +3501,7 @@ int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
 		}
 	}
 
+	btrfs_update_per_profile_avail(fs_info);
 	mutex_unlock(&fs_info->chunk_mutex);
 	trans->removing_chunk = false;
 
@@ -5023,6 +5030,7 @@ int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
 		atomic64_sub(free_diff, &fs_info->free_chunk_space);
 	}
 
+	btrfs_update_per_profile_avail(fs_info);
 	/*
 	 * Once the device's size has been set to the new size, ensure all
 	 * in-memory chunks are synced to disk so that the loop below sees them
@@ -5138,6 +5146,7 @@ int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
 	WARN_ON(diff > old_total);
 	btrfs_set_super_total_bytes(super_copy,
 			round_down(old_total - diff, fs_info->sectorsize));
+	btrfs_update_per_profile_avail(fs_info);
 	mutex_unlock(&fs_info->chunk_mutex);
 
 	btrfs_reserve_chunk_metadata(trans, false);
@@ -5850,6 +5859,8 @@ static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
 	check_raid56_incompat_flag(info, type);
 	check_raid1c34_incompat_flag(info, type);
 
+	btrfs_update_per_profile_avail(info);
+
 	return block_group;
 }
 
@@ -8389,7 +8400,14 @@ int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
 	}
 
 	/* Ensure all chunks have corresponding dev extents */
-	return verify_chunk_dev_extent_mapping(fs_info);
+	ret = verify_chunk_dev_extent_mapping(fs_info);
+	if (ret < 0)
+		return ret;
+
+	mutex_lock(&fs_info->chunk_mutex);
+	btrfs_update_per_profile_avail(fs_info);
+	mutex_unlock(&fs_info->chunk_mutex);
+	return 0;
 }
 
 /*
Signature · 1 line
2.53.0
author maintainer
#1356 lore raw

PATCH 1354/2151 btrfs: roll back sprout setup after device add failure

In reply to Greg Kroah-Hartman

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

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

From: Guanghui Yang <[email protected]>

[ Upstream commit f5166f53b60b4d1ee9957c0baccd3b09735001d4 ]

btrfs_init_new_device() calls btrfs_setup_sprout() before creating the first writable chunks for a seed filesystem. That moves the seed devices out of fs_info->fs_devices, clears the seeding state and installs a new fsid for the sprout filesystem.

If a later step fails, the error path removes the new device but leaves fs_info->fs_devices in the partially initialized sprout state. The mounted filesystem can then be left with no open devices after the failed device add.

Add the inverse of btrfs_setup_sprout() and use it from the error path so the mounted seed filesystem is restored before the temporary seed_devices copy is released.

Fixes 2b82032c34ec ("Btrfs: Seed device support")
Assisted-by Codex:gpt-5

[ Fix a conflict with per-profile available space, revert sprout before
updating per-profile available space estimation. ]

---
 fs/btrfs/volumes.c | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
fs/btrfs/volumes.c +37 -0
index a0984d6332dca..5d55e55bb8244 100644
@@ -2728,6 +2728,41 @@ static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info,
 	btrfs_set_super_flags(disk_super, super_flags);
 }
 
+static void btrfs_rollback_sprout(struct btrfs_fs_info *fs_info,
+				  struct btrfs_fs_devices *seed_devices)
+{
+	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
+	struct btrfs_super_block *disk_super = fs_info->super_copy;
+	struct btrfs_device *device;
+	u64 super_flags;
+
+	lockdep_assert_held(&uuid_mutex);
+	lockdep_assert_held(&fs_devices->device_list_mutex);
+
+	list_del_init(&seed_devices->seed_list);
+	list_splice_init_rcu(&seed_devices->devices, &fs_devices->devices, synchronize_rcu);
+	list_for_each_entry(device, &fs_devices->devices, dev_list) {
+		device->fs_devices = fs_devices;
+	}
+
+	fs_devices->seeding = true;
+	fs_devices->num_devices = seed_devices->num_devices;
+	fs_devices->open_devices = seed_devices->open_devices;
+	fs_devices->missing_devices = seed_devices->missing_devices;
+	fs_devices->rotating = seed_devices->rotating;
+	fs_devices->latest_dev = seed_devices->latest_dev;
+
+	memcpy(fs_devices->fsid, seed_devices->fsid, BTRFS_FSID_SIZE);
+	memcpy(fs_devices->metadata_uuid, seed_devices->metadata_uuid, BTRFS_FSID_SIZE);
+	memcpy(disk_super->fsid, seed_devices->fsid, BTRFS_FSID_SIZE);
+
+	super_flags = (btrfs_super_flags(disk_super) | BTRFS_SUPER_FLAG_SEEDING);
+	btrfs_set_super_flags(disk_super, super_flags);
+
+	seed_devices->opened = 0;
+	free_fs_devices(seed_devices);
+}
+
 /*
  * Store the expected generation for seed devices in device items.
  */
@@ -3037,6 +3072,8 @@ int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path
 				    orig_super_total_bytes);
 	btrfs_set_super_num_devices(fs_info->super_copy,
 				    orig_super_num_devices);
+	if (seeding_dev)
+		btrfs_rollback_sprout(fs_info, seed_devices);
 	btrfs_update_per_profile_avail(fs_info);
 	mutex_unlock(&fs_info->chunk_mutex);
 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
Signature · 1 line
2.53.0
author maintainer
#1357 lore raw

PATCH 1355/2151 btrfs: refactor read_key_bytes() to remove the dest_folio parameter

In reply to Greg Kroah-Hartman

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

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

From: Qu Wenruo <[email protected]>

[ Upstream commit fdf56b9d03d475881d73b75afbdbe4058db04ffc ]

The function read_key_bytes() have 3 call sites:

- For BTRFS_VERITY_DESC_ITEM_KEY offset 0 inside btrfs_get_verity_descriptor()
- For BTRFS_VERITY_DESC_ITEM_KEY offset 1 inside btrfs_get_verity_descriptor() Those are to read the description items, which are pretty small with fixed item size.

Those call sites do not utilize the @dest_folio parameter.

- For btrfs_read_merkle_tree_page()
This is to read the BTRFS_VERITY_MERKLE_ITEM_KEY, which can be pretty large and split into multiple items.

This is the only call site utilizing the @dest_folio parameter.

Just for the only btrfs_read_merkle_tree_page() call site, we have a complex scheme for @dest and @dest_folio parameters.
Since @dest can be NULL, it means if we pass @dest as NULL, then no matter if @dest_folio is provided, the merkle data will not be loaded into that @dest_folio.

This can lead to a bug where a highmem folio is not mapped, then we pass folio_address(folio), which is NULL, into read_key_bytes(), causing no data to be written into @dest_folio.

To address the complex scheme between @dest and @dest_folio, remove the @dest_folio parameter completely, and let the only caller to map the folio and pass the mapped kernel address into read_key_bytes() instead.

This not only reduces the parameter list, but also make it much clear on the @dest parameter handling.
The only downside is a longer duration of locally mapped page, but this should still be fine, as kmap_local_folio() can survive context switch.

---
 fs/btrfs/verity.c | 31 ++++++++++++++-----------------
 1 file changed, 14 insertions(+), 17 deletions(-)
fs/btrfs/verity.c +14 -17
index 43433577076b7..bb2d2fc47ee91 100644
@@ -286,21 +286,17 @@ static int write_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
  * @dest:       Buffer to read into. This parameter has slightly tricky
  *              semantics.  If it is NULL, the function will not do any copying
  *              and will just return the size of all the items up to len bytes.
- *              If dest_page is passed, then the function will kmap_local the
- *              page and ignore dest, but it must still be non-NULL to avoid the
- *              counting-only behavior.
  * @len:        length in bytes to read
- * @dest_folio: copy into this folio instead of the dest buffer
  *
  * Helper function to read items from the btree.  This returns the number of
  * bytes read or < 0 for errors.  We can return short reads if the items don't
  * exist on disk or aren't big enough to fill the desired length.  Supports
- * reading into a provided buffer (dest) or into the page cache
+ * reading into a provided buffer (dest).
  *
  * Returns number of bytes read or a negative error code on failure.
  */
 static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
-			  char *dest, u64 len, struct folio *dest_folio)
+			  char *dest, u64 len)
 {
 	BTRFS_PATH_AUTO_FREE(path);
 	struct btrfs_root *root = inode->root;
@@ -320,7 +316,11 @@ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
 	if (!path)
 		return -ENOMEM;
 
-	if (dest_folio)
+	/*
+	 * Merkle items can be large and split across multiple items, so enable
+	 * readahead for such cases.
+	 */
+	if (key_type == BTRFS_VERITY_MERKLE_ITEM_KEY)
 		path->reada = READA_FORWARD;
 
 	key.objectid = btrfs_ino(inode);
@@ -364,7 +364,7 @@ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
 				break;
 		}
 
-		/* desc = NULL to just sum all the item lengths */
+		/* dest == NULL to just sum all the item lengths */
 		if (!dest)
 			copy_end = item_end;
 		else
@@ -377,16 +377,10 @@ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
 		copy_offset = offset - key.offset;
 
 		if (dest) {
-			if (dest_folio)
-				kaddr = kmap_local_folio(dest_folio, 0);
-
 			data = btrfs_item_ptr(leaf, path->slots[0], void);
 			read_extent_buffer(leaf, kaddr + dest_offset,
 					   (unsigned long)data + copy_offset,
 					   copy_bytes);
-
-			if (dest_folio)
-				kunmap_local(kaddr);
 		}
 
 		offset += copy_bytes;
@@ -677,7 +671,7 @@ int btrfs_get_verity_descriptor(struct inode *inode, void *buf, size_t buf_size)
 
 	memset(&item, 0, sizeof(item));
 	ret = read_key_bytes(BTRFS_I(inode), BTRFS_VERITY_DESC_ITEM_KEY, 0,
-			     (char *)&item, sizeof(item), NULL);
+			     (char *)&item, sizeof(item));
 	if (ret < 0)
 		return ret;
 
@@ -694,7 +688,7 @@ int btrfs_get_verity_descriptor(struct inode *inode, void *buf, size_t buf_size)
 		return -ERANGE;
 
 	ret = read_key_bytes(BTRFS_I(inode), BTRFS_VERITY_DESC_ITEM_KEY, 1,
-			     buf, buf_size, NULL);
+			     buf, buf_size);
 	if (ret < 0)
 		return ret;
 	if (ret != true_size)
@@ -722,6 +716,7 @@ static struct page *btrfs_read_merkle_tree_page(struct inode *inode,
 	struct folio *folio;
 	u64 off = (u64)index << PAGE_SHIFT;
 	loff_t merkle_pos = merkle_file_pos(inode);
+	void *kaddr;
 	int ret;
 
 	if (merkle_pos < 0)
@@ -765,6 +760,7 @@ static struct page *btrfs_read_merkle_tree_page(struct inode *inode,
 	}
 
 read_folio:
+	kaddr = kmap_local_folio(folio, 0);
 	/*
 	 * Merkle item keys are indexed from byte 0 in the merkle tree.
 	 * They have the form:
@@ -772,7 +768,8 @@ static struct page *btrfs_read_merkle_tree_page(struct inode *inode,
 	 * [ inode objectid, BTRFS_MERKLE_ITEM_KEY, offset in bytes ]
 	 */
 	ret = read_key_bytes(BTRFS_I(inode), BTRFS_VERITY_MERKLE_ITEM_KEY, off,
-			     folio_address(folio), PAGE_SIZE, folio);
+			     kaddr, PAGE_SIZE);
+	kunmap_local(kaddr);
 	if (ret < 0) {
 		folio_unlock(folio);
 		folio_put(folio);
Signature · 1 line
2.53.0
author maintainer
#1358 lore raw

PATCH 1356/2151 btrfs: fix off by one super block end offset calculation when writing super blocks

In reply to Greg Kroah-Hartman

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

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

From: Filipe Manana <[email protected]>

[ Upstream commit 7884a8f3279c28ff990e2eacd5c2479bb1c930d0 ]

We are skipping the write of a super block mirror if its end offset matches exactly the device's end offset. This happens because we are using a greater than or equals comparison instead of just a greater than comparison.

Fixes 935e5cc935bc ("Btrfs: fix wrong disk size when writing super blocks")
---
 fs/btrfs/disk-io.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
fs/btrfs/disk-io.c +2 -4
index 2af30d1009783..08680c2511e3a 100644
@@ -3824,8 +3824,7 @@ static int write_dev_supers(struct btrfs_device *device,
 			atomic_inc(&device->sb_write_errors);
 			continue;
 		}
-		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
-		    device->commit_total_bytes)
+		if (bytenr + BTRFS_SUPER_INFO_SIZE > device->commit_total_bytes)
 			break;
 
 		btrfs_set_super_bytenr(sb, bytenr_orig);
@@ -3907,8 +3906,7 @@ static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
 				primary_failed = true;
 			continue;
 		}
-		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
-		    device->commit_total_bytes)
+		if (bytenr + BTRFS_SUPER_INFO_SIZE > device->commit_total_bytes)
 			break;
 
 		folio = filemap_get_folio(device->bdev->bd_mapping,
Signature · 1 line
2.53.0
author maintainer
#1359 lore raw

PATCH 1357/2151 btrfs: fix dangling nodes in tree-mod-log after error in btrfs_tree_mod_log_insert_root()

In reply to Greg Kroah-Hartman

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

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

From: Filipe Manana <[email protected]>

[ Upstream commit 057e3c350a9185df598c88b4081168ed047c9247 ]

If in btrfs_tree_mod_log_insert_root() there is an error in the call to tree_mod_log_insert() (the only possible error is -EEXIST, which means we have a bug or some memory corruption maybe) we free all the nodes in the 'tm_list' array but we don't remove them from the tree-mod-log rbtree, which can result in use-after-free bugs later.

So make sure we remove the nodes from the rbtree before freeing them after an error.

Fixes 5de865eebb83 ("Btrfs: fix tree mod logging")
Assisted-by LLM (found the bug)
---
 fs/btrfs/tree-mod-log.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
fs/btrfs/tree-mod-log.c +10 -3
index 9e8cb3b7c0643..70e9daf2ce42a 100644
@@ -483,10 +483,17 @@ int btrfs_tree_mod_log_insert_root(struct extent_buffer *old_root,
 		goto out_unlock;
 	}
 
-	if (tm_list)
+	if (tm_list) {
 		ret = tree_mod_log_free_eb(fs_info, tm_list, nritems);
-	if (!ret)
-		ret = tree_mod_log_insert(fs_info, tm);
+		if (ret)
+			goto out_unlock;
+	}
+
+	ret = tree_mod_log_insert(fs_info, tm);
+	if (ret && tm_list) {
+		for (i = 0; i < nritems; i++)
+			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
+	}
 
 out_unlock:
 	write_unlock(&fs_info->tree_mod_log_lock);
Signature · 1 line
2.53.0
author maintainer
#1360 lore raw

PATCH 1358/2151 btrfs: zoned: fix double list add in btrfs_load_block_group_zone_info

In reply to Greg Kroah-Hartman

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

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

From: Johannes Thumshirn <[email protected]>

[ Upstream commit 9bdef63e2b5d4a88810329a1cab3642d6378a895 ]

For DUP and RAID profiles with zones in a mismatching active state, i.e. due to one of the zones of the block-group being on a conventional zone, btrfs_zone_activate() has already put the block group on the list.

This leads to a double list add and refcounting problems.

Fixes 265f7237dd25 ("btrfs: zoned: allow DUP on meta-data block groups")
Fixes 568220fa9657 ("btrfs: zoned: support RAID0/1/10 on top of raid stripe tree")
---
 fs/btrfs/zoned.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
fs/btrfs/zoned.c +5 -3
index 36c09492e0bd4..88559307bac7d 100644
@@ -1982,10 +1982,12 @@ int btrfs_load_block_group_zone_info(struct btrfs_block_group *cache, bool new)
 	if (!ret) {
 		cache->meta_write_pointer = cache->alloc_offset + cache->start;
 		if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags)) {
-			btrfs_get_block_group(cache);
 			spin_lock(&fs_info->zone_active_bgs_lock);
-			list_add_tail(&cache->active_bg_list,
-				      &fs_info->zone_active_bgs);
+			if (list_empty(&cache->active_bg_list)) {
+				btrfs_get_block_group(cache);
+				list_add_tail(&cache->active_bg_list,
+					      &fs_info->zone_active_bgs);
+			}
 			spin_unlock(&fs_info->zone_active_bgs_lock);
 		}
 	} else {
Signature · 1 line
2.53.0
author maintainer
#1361 lore raw

PATCH 1359/2151 btrfs: fix incomplete iteration over fs state when logging messages

In reply to Greg Kroah-Hartman

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

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

From: Filipe Manana <[email protected]>

[ Upstream commit d1d74665ab9a8971d42177ca865cfbe2897c1fc7 ]

In btrfs_state_to_string() we iterate over all the bits set in fs_info->fs_state using for_each_set_bit(), which requires its third argument to match the number of bits, but we pass it the number of bytes of the type used by fs_info->fs_state, an unsigned long, which is 8 on 64 bits platforms and 4 on 32 bits platforms. This means we are not iterating over bits in the ranges [8, 63] or [4, 31].

Fix this by passing BTRFS_FS_STATE_COUNT instead of sizeof(fs_state). Note that we could pass BITS_PER_TYPE(fs_state), but since BTRFS_FS_STATE_COUNT is 11 and we have no bits beyond that, it would cause pointless iterations over fs_state.

This also makes pointless the checks for the bit being inside the limit of BTRFS_FS_STATE_COUNT inside the loop.

Fixes c067da878156 ("btrfs: add filesystems state details to error messages")
---
 fs/btrfs/messages.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
fs/btrfs/messages.c +2 -3
index a0cf8effe008e..c218b2ea8566c 100644
@@ -41,9 +41,8 @@ static void btrfs_state_to_string(const struct btrfs_fs_info *info, char *buf)
 		states_printed = true;
 	}
 
-	for_each_set_bit(bit, &fs_state, sizeof(fs_state)) {
-		WARN_ON_ONCE(bit >= BTRFS_FS_STATE_COUNT);
-		if ((bit < BTRFS_FS_STATE_COUNT) && fs_state_chars[bit]) {
+	for_each_set_bit(bit, &fs_state, BTRFS_FS_STATE_COUNT) {
+		if (fs_state_chars[bit]) {
 			*curr++ = fs_state_chars[bit];
 			states_printed = true;
 		}
Signature · 1 line
2.53.0
author maintainer
#1362 lore raw

PATCH 1360/2151 btrfs: fix off-by-one end offset check in report_setget_bounds()

In reply to Greg Kroah-Hartman

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

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

From: Filipe Manana <[email protected]>

[ Upstream commit 08f750d9f8930e4ca053913b5ca3fd49fd9268c9 ]

The addressable range with an extent buffer goes from byte 0 to byte eb->len - 1, so if a byte address matches eb->len, it's already beyond the addressable range and we should log that it's bad start address and not end address.

Fixes 234fdd2815ce ("btrfs: remove redundant check in up check_setget_bounds")
---
 fs/btrfs/accessors.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/btrfs/accessors.c +1 -1
index 1248aa2535d30..d63ac6eb92deb 100644
@@ -16,7 +16,7 @@ static void __cold report_setget_bounds(const struct extent_buffer *eb,
 
 	btrfs_warn(eb->fs_info,
 		   "bad eb member %s: ptr 0x%lx start %llu member offset %lu size %d",
-		   (member_offset > eb->len ? "start" : "end"),
+		   (member_offset >= eb->len ? "start" : "end"),
 		   (unsigned long)ptr, eb->start, member_offset, size);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1363 lore raw

PATCH 1361/2151 btrfs: qgroup: do not treat "ret > 0" as error when deleting a qgroup

In reply to Greg Kroah-Hartman

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

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

From: Qu Wenruo <[email protected]>

[ Upstream commit dd906477cc2c33c82ec17e6301bd4be4ea588565 ]

[BUG]
There is a bug report that when removing a child qgroup, if removing the qgroup requires a rescan, it will delete the on-disk relation and qgroup items but not the in-memory qgroup rb entry.

This makes all later qgroup rescan to fail.

[CAUSE]
The call chain looks like the following:

btrfs_remove_qgroup()

 |- __del_qgroup_relation()
 |  |- quick_update_accounting()
 |     Which returns 1, showing this operation will require
 |     a qgroup rescan
 |- if (ret) goto out;

Which skips the del_qgroup_rb() call, leaving the in-memory qgroup rb entry still intact.

Then later qgroup rescan/update will always fail and mark qgroup inconsistent:

btrfs_run_qgroups()

 |- update_qgroup_info_item()
 |  |- btrfs_search_slot()
 |     Which returns -ENOENT, as the qgroup info item is already
 |     deleted.
 |- qgroup_mark_inconsistent()
 |- return -ENOENT;

[FIX]
Do not treat "ret > 0" as an error.

Reported-by [email protected]
Fixes 9c8b35b1ba21 ("btrfs: quota: Automatically update related qgroups or mark INCONSISTENT flags when assigning/deleting a qgroup relations.")
---
 fs/btrfs/qgroup.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/btrfs/qgroup.c +1 -1
index 87eddd5a3ea7b..f87acc9966c0e 100644
@@ -1851,7 +1851,7 @@ int btrfs_remove_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
 					struct btrfs_qgroup_list, next_group);
 		ret = __del_qgroup_relation(trans, qgroupid,
 					    list->group->qgroupid);
-		if (ret)
+		if (ret < 0)
 			goto out;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#1364 lore raw

PATCH 1362/2151 btrfs: qgroup: fix swapped blocks existence check when tracing after COW

In reply to Greg Kroah-Hartman

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

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

From: Filipe Manana <[email protected]>

[ Upstream commit 0388b5bd3a6eb8bcb20208c3b6dbee96fd30bbe0 ]

In btrfs_qgroup_trace_subtree_after_cow(), after we erase the swapped block, iterate over all possible tree levels to check if we sill have other swapped blocks. However the check is wrong, it considers that there are other swapped blocks if any rbtree for any level is empty, instead of not empty. As a consequence we set blocks->swapped to true basically every time since we always find an empty rbtree at least at level 7, since in practice it's nearly impossible to find such a huge btree. This makes every future call to btrfs_qgroup_trace_subtree_after_cow() do an unnecessary rbtree search instead of returning immediately.

Fix this by updating the condition to set swapped to true if we find an rbtree that is not empty.

Fixes f616f5cd9da7 ("btrfs: qgroup: Use delayed subtree rescan for balance")
---
 fs/btrfs/ctree.h  | 2 +-
 fs/btrfs/qgroup.c | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
fs/btrfs/ctree.h +1 -1
index 692370fc07b28..5e5856bd84d1f 100644
@@ -153,7 +153,7 @@ enum {
  */
 struct btrfs_qgroup_swapped_blocks {
 	spinlock_t lock;
-	/* RM_EMPTY_ROOT() of above blocks[] */
+	/* True if any of the rbtrees in the blocks array below is not empty. */
 	bool swapped;
 	struct rb_root blocks[BTRFS_MAX_LEVEL];
 };
fs/btrfs/qgroup.c +1 -1
index f87acc9966c0e..d434ffa1e6d2e 100644
@@ -4889,7 +4889,7 @@ int btrfs_qgroup_trace_subtree_after_cow(struct btrfs_trans_handle *trans,
 	/* Found one, remove it from @blocks first and update blocks->swapped */
 	rb_erase(&block->node, &blocks->blocks[level]);
 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
-		if (RB_EMPTY_ROOT(&blocks->blocks[i])) {
+		if (!RB_EMPTY_ROOT(&blocks->blocks[i])) {
 			swapped = true;
 			break;
 		}
Signature · 1 line
2.53.0
author maintainer
#1365 lore raw

PATCH 1363/2151 btrfs: fix lost error return value in btrfs_alloc_logged_file_extent()

In reply to Greg Kroah-Hartman

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

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

From: Filipe Manana <[email protected]>

[ Upstream commit 784cd5a83476c6c720521f21350fb823928555ff ]

If we fail to allocate a reserved file extent we then call btrfs_record_squota_delta() and assign its return value to 'ret', discarding the error from the failed allocation attempt and allowing log replay to proceed as if no errors happened, resulting in some replayed file extent item to point to an unallocated extent. At the moment btrfs_record_squota_delta() always returns 0 (success).

Fixes cecbb533b5fc ("btrfs: record simple quota deltas in delayed refs")
---
 fs/btrfs/extent-tree.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/btrfs/extent-tree.c +2 -1
index 95bff1616f4a8..2f207bca62720 100644
@@ -5011,7 +5011,8 @@ int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
 					 offset, ins, 1, root_objectid);
 	if (ret)
 		btrfs_pin_extent(trans, ins->objectid, ins->offset);
-	ret = btrfs_record_squota_delta(fs_info, &delta);
+	else
+		ret = btrfs_record_squota_delta(fs_info, &delta);
 	btrfs_put_block_group(block_group);
 	return ret;
 }
Signature · 1 line
2.53.0
author maintainer
#1366 lore raw

PATCH 1364/2151 btrfs: defrag: fix check to see if next extent can be defragged too

In reply to Greg Kroah-Hartman

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

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

From: Filipe Manana <[email protected]>

[ Upstream commit eb55bc2bfe204e6bfccfe179226d7fb5024cb010 ]

We want to check if the next extent is at maximum capacity but we are passing the current extent map to get_extent_max_capacity() and not the next extent map. For example if the current extent is compressed (its maximum capacity is 128K) and the next extent is uncompressed (its maximum capacity is 128M), then we can bail out and not defrag the next extent too - when for example the next extent as a size of 128K, is uncompressed, and the extent threshold is >= 256K.

Fixes 979b25c300db ("btrfs: defrag: don't defrag extents which are already at max capacity")
---
 fs/btrfs/defrag.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/btrfs/defrag.c +1 -1
index c59548a0b9c53..8b9766b67c333 100644
@@ -818,7 +818,7 @@ static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em,
 	 * If the next extent is at its max capacity, defragging current extent
 	 * makes no sense, as the total number of extents won't change.
 	 */
-	if (next->len >= get_extent_max_capacity(fs_info, em))
+	if (next->len >= get_extent_max_capacity(fs_info, next))
 		goto out;
 	/* Skip older extent */
 	if (next->generation < newer_than)
Signature · 1 line
2.53.0
author maintainer
#1367 lore raw

PATCH 1365/2151 power: supply: generic-adc-battery: Propagate charged GPIO errors

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 36b0abe904ac9cbdce6161d9c7c0bcac963bb3fe ]

devm_gpiod_get_optional() may return an error pointer such as -EPROBE_DEFER, but gab_probe() only checks for NULL. The error pointer is then passed to gpiod_to_irq() and the original error, including -EPROBE_DEFER, is lost.

Check the return value and propagate errors from the charged GPIO lookup.

Fixes b0327ffb133f ("power: supply: generic-adc-battery: Use GPIO descriptors")
---
 drivers/power/supply/generic-adc-battery.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/power/supply/generic-adc-battery.c +3 -0
index df5f91bc1d0f6..b1a29b04a6f0c 100644
@@ -243,6 +243,9 @@ static int gab_probe(struct platform_device *pdev)
 		return dev_err_probe(&pdev->dev, ret, "Failed to register delayed work\n");
 
 	adc_bat->charge_finished = devm_gpiod_get_optional(&pdev->dev, "charged", GPIOD_IN);
+	if (IS_ERR(adc_bat->charge_finished))
+		return dev_err_probe(&pdev->dev, PTR_ERR(adc_bat->charge_finished),
+				     "failed to get charged GPIO\n");
 	if (adc_bat->charge_finished) {
 		int irq;
 
Signature · 1 line
2.53.0
author maintainer
#1368 lore raw

PATCH 1366/2151 mtd: rawnand: pl353: fix clk reference leak in pl35x_nfc_setup_interface()

In reply to Greg Kroah-Hartman

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

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

From: Haotian Zhang <[email protected]>

[ Upstream commit 1ce45f0e74d60e8279ed380c97047e6c351aee1b ]

pl35x_nfc_setup_interface() obtains a reference to the SMC "memclk" with of_clk_get_by_name() and only uses it to read the clock rate. The reference is never released: the function has many early return paths and no clk_put() call anywhere, so the clock reference is leaked.

The hook is invoked repeatedly by the NAND core (nand_reset(), nand_setup_interface() and the NAND_DATA_IFACE_CHECK_ONLY mode probing loops), so the reference count keeps growing.

Release the clock reference with clk_put() as soon as its rate has been read.

Fixes 08d8c62164a3 ("mtd: rawnand: pl353: Add support for the ARM PL353 SMC NAND controller")
Assisted-by DeepSeek-V4.1-Flash
---
 drivers/mtd/nand/raw/pl35x-nand-controller.c | 1 +
 1 file changed, 1 insertion(+)
drivers/mtd/nand/raw/pl35x-nand-controller.c +1 -0
index 12b9e0936c8f1..8a6892f7623d9 100644
@@ -807,6 +807,7 @@ static int pl35x_nfc_setup_interface(struct nand_chip *chip, int cs,
 	 * macro to convert from one to the other.
 	 */
 	period_ns = NSEC_PER_SEC / clk_get_rate(mclk);
+	clk_put(mclk);
 
 	/*
 	 * PL35X SMC needs one extra read cycle in SDR Mode 5. This is not
Signature · 1 line
2.53.0
author maintainer
#1369 lore raw

PATCH 1367/2151 nfs: set gencount on protocol-specific remove

In reply to Greg Kroah-Hartman

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

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

From: Roberto Bergantinos Corpas <[email protected]>

[ Upstream commit 8c955dacf45f8964b98f26910ffecb5e26c02e31 ]

commit bd4928ec799b ("NFS: Avoid changing nlink when file removes and attribute updates race") avoids races on attribute cache with any inflight RPC that may modify inode attributes (and gencount) during i.e. REMOVE.

However it does not take into account that REMOVE may trigger a delegation return which also advances gencount (via the attribute refresh during delegation return), and in that case the gencount mismatch is not due to an inflight RPC that already reflected the removal.

Push the setting of gencount under each version-specific layer, reordering correctly for nfsv4 case after the delegation returns.

This fixes LTP/inotify04 failure after bd4928ec799b.

Fixes bd4928ec799b ("NFS: Avoid changing nlink when file removes and attribute updates race")
---
 fs/nfs/dir.c      | 13 +++----------
 fs/nfs/internal.h |  1 +
 fs/nfs/nfs3proc.c |  8 ++++++++
 fs/nfs/nfs4proc.c |  5 +++++
 fs/nfs/proc.c     |  8 ++++++++
 5 files changed, 25 insertions(+), 10 deletions(-)
fs/nfs/dir.c +3 -10
index f54c1a485095d..4dc91428c79cc 100644
@@ -1895,7 +1895,7 @@ static int nfs_dentry_delete(const struct dentry *dentry)
 }
 
 /* Ensure that we revalidate inode->i_nlink */
-static void nfs_drop_nlink(struct inode *inode, unsigned long gencount)
+void nfs_drop_nlink(struct inode *inode, unsigned long gencount)
 {
 	struct nfs_inode *nfsi = NFS_I(inode);
 
@@ -1909,6 +1909,7 @@ static void nfs_drop_nlink(struct inode *inode, unsigned long gencount)
 			       NFS_INO_INVALID_NLINK);
 	spin_unlock(&inode->i_lock);
 }
+EXPORT_SYMBOL_GPL(nfs_drop_nlink);
 
 /*
  * Called when the dentry loses inode.
@@ -2508,7 +2509,6 @@ EXPORT_SYMBOL_GPL(nfs_rmdir);
 static int nfs_safe_remove(struct dentry *dentry)
 {
 	struct inode *dir = d_inode(dentry->d_parent);
-	struct inode *inode = d_inode(dentry);
 	int error = -EBUSY;
 		
 	dfprintk(VFS, "NFS: safe_remove(%pd2)\n", dentry);
@@ -2520,14 +2520,7 @@ static int nfs_safe_remove(struct dentry *dentry)
 	}
 
 	trace_nfs_remove_enter(dir, dentry);
-	if (inode != NULL) {
-		unsigned long gencount = READ_ONCE(NFS_I(inode)->attr_gencount);
-
-		error = NFS_PROTO(dir)->remove(dir, dentry);
-		if (error == 0)
-			nfs_drop_nlink(inode, gencount);
-	} else
-		error = NFS_PROTO(dir)->remove(dir, dentry);
+	error = NFS_PROTO(dir)->remove(dir, dentry);
 	if (error == -ENOENT)
 		nfs_dentry_handle_enoent(dentry);
 	trace_nfs_remove_exit(dir, dentry, error);
fs/nfs/internal.h +1 -0
index 0285cc7bf3fd5..3214533b73c2c 100644
@@ -397,6 +397,7 @@ extern unsigned long nfs_access_cache_count(struct shrinker *shrink,
 					    struct shrink_control *sc);
 extern unsigned long nfs_access_cache_scan(struct shrinker *shrink,
 					   struct shrink_control *sc);
+extern void nfs_drop_nlink(struct inode *inode, unsigned long gencount);
 struct dentry *nfs_lookup(struct inode *, struct dentry *, unsigned int);
 void nfs_d_prune_case_insensitive_aliases(struct inode *inode);
 int nfs_create(struct mnt_idmap *, struct inode *, struct dentry *,
fs/nfs/nfs3proc.c +8 -0
index 993f62636a772..aef15b9f96fdc 100644
@@ -447,13 +447,21 @@ nfs3_proc_remove(struct inode *dir, struct dentry *dentry)
 		.rpc_resp = &res,
 	};
 	int status = -ENOMEM;
+	struct inode *inode = d_inode(dentry);
+	unsigned long gencount;
 
 	dprintk("NFS call  remove %pd2\n", dentry);
 	res.dir_attr = nfs_alloc_fattr();
 	if (res.dir_attr == NULL)
 		goto out;
 
+	if (inode)
+		gencount = READ_ONCE(NFS_I(inode)->attr_gencount);
+
 	status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
+	if (status == 0 && inode)
+		nfs_drop_nlink(inode, gencount);
+
 	nfs_post_op_update_inode(dir, res.dir_attr);
 	nfs_free_fattr(res.dir_attr);
 out:
fs/nfs/nfs4proc.c +5 -0
index d856be907e319..1e8c1fe993aaf 100644
@@ -4937,12 +4937,14 @@ static int nfs4_proc_remove(struct inode *dir, struct dentry *dentry)
 	};
 	struct inode *inode = d_inode(dentry);
 	int err;
+	unsigned long gencount;
 
 	if (inode) {
 		if (inode->i_nlink == 1)
 			nfs4_inode_return_delegation(inode);
 		else
 			nfs4_inode_make_writeable(inode);
+		gencount = READ_ONCE(NFS_I(inode)->attr_gencount);
 	}
 	do {
 		err = _nfs4_proc_remove(dir, &dentry->d_name, NF4REG);
@@ -4950,6 +4952,9 @@ static int nfs4_proc_remove(struct inode *dir, struct dentry *dentry)
 		err = nfs4_handle_exception(NFS_SERVER(dir), err,
 				&exception);
 	} while (exception.retry);
+
+	if (err == 0 && inode)
+		nfs_drop_nlink(inode, gencount);
 	return err;
 }
 
fs/nfs/proc.c +8 -0
index 63e71310b9f69..3467932690acb 100644
@@ -322,9 +322,17 @@ nfs_proc_remove(struct inode *dir, struct dentry *dentry)
 		.rpc_argp = &arg,
 	};
 	int			status;
+	struct inode *inode = d_inode(dentry);
+	unsigned long gencount;
 
 	dprintk("NFS call  remove %pd2\n",dentry);
+	if (inode)
+		gencount = READ_ONCE(NFS_I(inode)->attr_gencount);
+
 	status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
+	if (status == 0 && inode)
+		nfs_drop_nlink(inode, gencount);
+
 	nfs_mark_for_revalidate(dir);
 
 	dprintk("NFS reply remove: %d\n", status);
Signature · 1 line
2.53.0
author maintainer
#1370 lore raw

PATCH 1368/2151 accel/rocket: Dont tear down the scheduler when drm_sched_init() fails

In reply to Greg Kroah-Hartman

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

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

From: Sidong Yang <[email protected]>

[ Upstream commit a6709a58a01c8fc357e316bee31f369c2ea56235 ]

drm_sched_init() cleans up after itself when it fails, but rocket_job_init() then calls drm_sched_fini() on the same scheduler. That wakes a wait queue that was never initialised, dereferencing a NULL pointer, and can destroy the submit workqueue a second time.

Only destroy the reset workqueue on this path.

---
 drivers/accel/rocket/rocket_job.c | 2 --
 1 file changed, 2 deletions(-)
drivers/accel/rocket/rocket_job.c +0 -2
index 729b7d6d77d46..269c8a00410be 100644
@@ -494,8 +494,6 @@ int rocket_job_init(struct rocket_core *core)
 	return 0;
 
 err_sched:
-	drm_sched_fini(&core->sched);
-
 	destroy_workqueue(core->reset.wq);
 	return ret;
 }
Signature · 1 line
2.53.0
author maintainer
#1371 lore raw

PATCH 1369/2151 ASoC: codecs: rt5659: propagate GPIO errors

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit c1e321bd5ce6ae3702db65837cfe0c792634d603 ]

devm_gpiod_get_optional() may return an error pointer, including -EPROBE_DEFER, but rt5659_i2c_probe() does not handle these errors for the ldo1-en GPIO and does not check for errors for the reset GPIO.

Check the return values and propagate GPIO lookup errors.

---
 sound/soc/codecs/rt5659.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
sound/soc/codecs/rt5659.c +5 -1
index 805898547025d..760b1a14ce35e 100644
@@ -4112,10 +4112,14 @@ static int rt5659_i2c_probe(struct i2c_client *i2c)
 	rt5659->gpiod_ldo1_en = devm_gpiod_get_optional(&i2c->dev, "ldo1-en",
 							GPIOD_OUT_HIGH);
 	if (IS_ERR(rt5659->gpiod_ldo1_en))
-		dev_warn(&i2c->dev, "Request ldo1-en GPIO failed\n");
+		return dev_err_probe(&i2c->dev, PTR_ERR(rt5659->gpiod_ldo1_en),
+				     "failed to get ldo1-en GPIO\n");
 
 	rt5659->gpiod_reset = devm_gpiod_get_optional(&i2c->dev, "reset",
 							GPIOD_OUT_HIGH);
+	if (IS_ERR(rt5659->gpiod_reset))
+		return dev_err_probe(&i2c->dev, PTR_ERR(rt5659->gpiod_reset),
+				     "failed to get reset GPIO\n");
 
 	/* Sleep for 300 ms miniumum */
 	msleep(300);
Signature · 1 line
2.53.0
author maintainer
#1372 lore raw

PATCH 1370/2151 ASoC: codecs: wcd939x: read the SoundWire port switches per channel

In reply to Greg Kroah-Hartman

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

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

From: Joonhoe Kim <[email protected]>

[ Upstream commit e7860dc5d8d45f6a0e98bfe542c7b776c5ede2a4 ]

The "HPHL/HPHR", "ADCn" and "DMICn" switches are channels of shared SoundWire ports (ADC1-4 are channels 0-3 of the ADC_1_4 port), but wcd939x_get_swr_port() reports a per-port flag. Once one channel of a port is switched on, every switch on that port reads back as on:

amixer cset name='ADC1 Switch' on -> ADC1..ADC4 Switch all read "on"

Setting one of the others then looks like a no-op to userspace, and "alsactl store" saves all of them as on, so a later "alsactl restore" really enables the unused channels of the port.

Read the channel's own bit in the port's channel mask instead, drop the now unused port_enable[] and return 0 from the put handler when the switch does not change, as ALSA expects.

---
 sound/soc/codecs/wcd939x.c | 10 +++++++---
 sound/soc/codecs/wcd939x.h |  1 -
 2 files changed, 7 insertions(+), 4 deletions(-)
sound/soc/codecs/wcd939x.c +7 -3
index e74e6f0131318..6068e2a9ed913 100644
@@ -1793,8 +1793,9 @@ static int wcd939x_get_swr_port(struct snd_kcontrol *kcontrol,
 	struct wcd939x_priv *wcd939x = snd_soc_component_get_drvdata(comp);
 	struct wcd939x_sdw_priv *wcd = wcd939x->sdw_priv[mixer->shift];
 	unsigned int portidx = wcd->ch_info[mixer->reg].port_num;
+	u8 ch_mask = wcd->ch_info[mixer->reg].ch_mask;
 
-	ucontrol->value.integer.value[0] = wcd->port_enable[portidx] ? 1 : 0;
+	ucontrol->value.integer.value[0] = !!(wcd->port_config[portidx - 1].ch_mask & ch_mask);
 
 	return 0;
 }
@@ -1820,10 +1821,13 @@ static int wcd939x_set_swr_port(struct snd_kcontrol *kcontrol,
 	struct wcd939x_priv *wcd939x = snd_soc_component_get_drvdata(comp);
 	struct wcd939x_sdw_priv *wcd = wcd939x->sdw_priv[mixer->shift];
 	unsigned int portidx = wcd->ch_info[mixer->reg].port_num;
+	u8 ch_mask = wcd->ch_info[mixer->reg].ch_mask;
+	bool enable = !!ucontrol->value.integer.value[0];
 
-	wcd->port_enable[portidx] = !!ucontrol->value.integer.value[0];
+	if (enable == !!(wcd->port_config[portidx - 1].ch_mask & ch_mask))
+		return 0;
 
-	wcd939x_connect_port(wcd, portidx, mixer->reg, wcd->port_enable[portidx]);
+	wcd939x_connect_port(wcd, portidx, mixer->reg, enable);
 
 	return 1;
 }
sound/soc/codecs/wcd939x.h +0 -1
index 6bd2366587a8f..dab7ef108b485 100644
@@ -899,7 +899,6 @@ struct wcd939x_sdw_priv {
 	struct sdw_stream_runtime *sruntime;
 	struct sdw_port_config port_config[WCD939X_MAX_SWR_PORTS];
 	const struct wcd_sdw_ch_info *ch_info;
-	bool port_enable[WCD939X_MAX_SWR_CH_IDS];
 	int active_ports;
 	bool is_tx;
 	struct wcd939x_priv *wcd939x;
Signature · 1 line
2.53.0
author maintainer
#1373 lore raw

PATCH 1371/2151 rcutorture: Fix divide-by-zero with fwd_progress_div=1

In reply to Greg Kroah-Hartman

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

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

From: Kunwu Chan <[email protected]>

[ Upstream commit 5b748d8aa6833f2dec3f545311be69a2064bc6d1 ]

When fwd_progress_div=1, the forward-progress test computes:
sd4 = (sd + div - 1) / div = sd
dur = sd4 + torture_random(&trs) % (sd - sd4) = sd4 + % 0

The modulo operation with a zero divisor triggers an integer division by zero (undefined behavior at the C level, #DE trap on x86), causing a kernel Oops and panic. On x86_64, this manifests as:

rcu_torture_fwd_prog_nr: Starting forward-progress test 0

  Oops: divide error: 0000 [#1] SMP PTI
  RIP: 0010:rcu_torture_fwd_prog+0x90b/0x1160
  R12: 0000000000000000

The existing guard only handles non-positive values. However, fwd_progress_div=1 also makes the random range empty because sd4 == sd.

Change the guard to reject values below 2. The forward-progress test only reaches this calculation when stall_dur() is positive, so sd = stall_dur() + 1 >= 2. For fwd_progress_div >= 2, sd4 < sd, ensuring that sd - sd4 is at least 1.

Keep the existing fallback to the default value of 4 for invalid values.

Verified with QEMU/KVM: a 138-second run with fwd_progress_div=1 completed 81 forward-progress test cycles without a crash.

Fixes 1b27291b1ea4f ("rcutorture: Add forward-progress tests for RCU grace periods")
---
 kernel/rcu/rcutorture.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/rcu/rcutorture.c +1 -1
index 29fe3c01312f6..d98029cff32ce 100644
@@ -3531,7 +3531,7 @@ static int __init rcu_torture_fwd_prog_init(void)
 	}
 	if (fwd_progress_holdoff <= 0)
 		fwd_progress_holdoff = 1;
-	if (fwd_progress_div <= 0)
+	if (fwd_progress_div < 2)
 		fwd_progress_div = 4;
 	rfp = kcalloc(fwd_progress, sizeof(*rfp), GFP_KERNEL);
 	fwd_prog_tasks = kcalloc(fwd_progress, sizeof(*fwd_prog_tasks), GFP_KERNEL);
Signature · 1 line
2.53.0
author maintainer
#1374 lore raw

PATCH 1372/2151 wifi: ath10k: avoid IDR mutation during TX cleanup

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 1c1a208e65a08191901cfded3bbccc4a54e4a75c ]

ath10k_htt_flush_tx_queue() walks pending_tx with idr_for_each(). Its callback calls ath10k_txrx_tx_unref(), which removes the current entry from pending_tx through ath10k_htt_tx_free_msdu_id().

idr_for_each() keeps radix-tree iterator state across the callback. Removing the current entry can therefore invalidate that state and make the remaining walk unsafe.

Use idr_for_each_entry(), which starts a fresh lookup after each callback. The current entry can then be removed safely, while the following idr_destroy() continues to release the IDR itself.

Fixes 89d6d83565e9 ("ath10k: use idr api for msdu_ids")
[changed ath10k_htt_tx_clean_up_pending() signature]
---
 drivers/net/wireless/ath/ath10k/htt_tx.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/net/wireless/ath/ath10k/htt_tx.c +7 -5
index d6f1d85ba8713..b9a153ff82b28 100644
@@ -506,9 +506,8 @@ int ath10k_htt_tx_start(struct ath10k_htt *htt)
 	return ret;
 }
 
-static int ath10k_htt_tx_clean_up_pending(int msdu_id, void *skb, void *ctx)
+static void ath10k_htt_tx_clean_up_pending(int msdu_id, struct ath10k *ar)
 {
-	struct ath10k *ar = ctx;
 	struct ath10k_htt *htt = &ar->htt;
 	struct htt_tx_done tx_done = {};
 
@@ -518,8 +517,6 @@ static int ath10k_htt_tx_clean_up_pending(int msdu_id, void *skb, void *ctx)
 	tx_done.status = HTT_TX_COMPL_STATE_DISCARD;
 
 	ath10k_txrx_tx_unref(htt, &tx_done);
-
-	return 0;
 }
 
 void ath10k_htt_tx_destroy(struct ath10k_htt *htt)
@@ -536,8 +533,13 @@ void ath10k_htt_tx_destroy(struct ath10k_htt *htt)
 
 static void ath10k_htt_flush_tx_queue(struct ath10k_htt *htt)
 {
+	struct sk_buff *msdu;
+	int msdu_id;
+
 	ath10k_htc_stop_hl(htt->ar);
-	idr_for_each(&htt->pending_tx, ath10k_htt_tx_clean_up_pending, htt->ar);
+
+	idr_for_each_entry(&htt->pending_tx, msdu, msdu_id)
+		ath10k_htt_tx_clean_up_pending(msdu_id, htt->ar);
 }
 
 void ath10k_htt_tx_stop(struct ath10k_htt *htt)
Signature · 1 line
2.53.0
author maintainer
#1375 lore raw

PATCH 1373/2151 wifi: ath11k: avoid IDR mutation during pending mgmt TX cleanup

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 3e7f5d362b2b3a21b3adb4b860aad14b69a896ad ]

The pending management TX cleanup walks txmgmt_idr with idr_for_each(), and its callback removes the current entry. This can invalidate the radix-tree iterator retained by idr_for_each().

Use idr_for_each_entry() so every iteration starts with a fresh lookup. Continue to remove each entry under txmgmt_idr_lock before freeing its skb, preventing concurrent TX completion from finding a stale skb pointer.

---
 drivers/net/wireless/ath/ath11k/core.c |  3 +--
 drivers/net/wireless/ath/ath11k/mac.c  | 12 ++++++------
 drivers/net/wireless/ath/ath11k/mac.h  |  2 +-
 3 files changed, 8 insertions(+), 9 deletions(-)
drivers/net/wireless/ath/ath11k/core.c +1 -2
index 38ac5b820a2ce..620cb9ab3ec09 100644
@@ -2417,8 +2417,7 @@ void ath11k_core_pre_reconfigure_recovery(struct ath11k_base *ab)
 		complete(&ar->thermal.wmi_sync);
 
 		wake_up(&ar->dp.tx_empty_waitq);
-		idr_for_each(&ar->txmgmt_idr,
-			     ath11k_mac_tx_mgmt_pending_free, ar);
+		ath11k_mac_tx_mgmt_pending_free(ar);
 		idr_destroy(&ar->txmgmt_idr);
 		wake_up(&ar->txmgmt_empty_waitq);
 
drivers/net/wireless/ath/ath11k/mac.c +6 -6
index 60ffecd52280e..6f620265bf924 100644
@@ -6032,13 +6032,13 @@ static void ath11k_mac_tx_mgmt_free(struct ath11k *ar, int buf_id)
 	ath11k_mgmt_over_wmi_tx_drop(ar, msdu);
 }
 
-int ath11k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx)
+void ath11k_mac_tx_mgmt_pending_free(struct ath11k *ar)
 {
-	struct ath11k *ar = ctx;
-
-	ath11k_mac_tx_mgmt_free(ar, buf_id);
+	struct sk_buff *msdu;
+	int buf_id;
 
-	return 0;
+	idr_for_each_entry(&ar->txmgmt_idr, msdu, buf_id)
+		ath11k_mac_tx_mgmt_free(ar, buf_id);
 }
 
 static int ath11k_mac_vif_txmgmt_idr_remove(int buf_id, void *skb, void *ctx)
@@ -10244,7 +10244,7 @@ static void __ath11k_mac_unregister(struct ath11k *ar)
 
 	ieee80211_unregister_hw(ar->hw);
 
-	idr_for_each(&ar->txmgmt_idr, ath11k_mac_tx_mgmt_pending_free, ar);
+	ath11k_mac_tx_mgmt_pending_free(ar);
 	idr_destroy(&ar->txmgmt_idr);
 
 	kfree(ar->mac.sbands[NL80211_BAND_2GHZ].channels);
drivers/net/wireless/ath/ath11k/mac.h +1 -1
index 5e61eea1bb037..6dc769489c5c4 100644
@@ -162,7 +162,7 @@ struct ath11k *ath11k_mac_get_ar_by_pdev_id(struct ath11k_base *ab, u32 pdev_id)
 
 void ath11k_mac_drain_tx(struct ath11k *ar);
 void ath11k_mac_peer_cleanup_all(struct ath11k *ar);
-int ath11k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx);
+void ath11k_mac_tx_mgmt_pending_free(struct ath11k *ar);
 u8 ath11k_mac_bw_to_mac80211_bw(u8 bw);
 enum nl80211_he_gi ath11k_mac_he_gi_to_nl80211_he_gi(u8 sgi);
 enum nl80211_he_ru_alloc ath11k_mac_phy_he_ru_to_nl80211_he_ru_alloc(u16 ru_phy);
Signature · 1 line
2.53.0
author maintainer
#1376 lore raw

PATCH 1374/2151 wifi: ath11k: avoid IDR mutation during vif mgmt TX cleanup

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

ath11k_mac_op_remove_interface() walks txmgmt_idr with idr_for_each(), and its callback removes each entry belonging to the interface. Removing the current entry can invalidate the radix-tree iterator retained by idr_for_each().

Move the walk into a helper that uses idr_for_each_entry(). It performs a fresh lookup for every iteration, so each matching entry can be removed through the locked removal helper without retaining iterator state across the removal.

---
 drivers/net/wireless/ath/ath11k/mac.c | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)
drivers/net/wireless/ath/ath11k/mac.c +11 -10
index 6f620265bf924..b47e86201a3b9 100644
@@ -6041,16 +6041,18 @@ void ath11k_mac_tx_mgmt_pending_free(struct ath11k *ar)
 		ath11k_mac_tx_mgmt_free(ar, buf_id);
 }
 
-static int ath11k_mac_vif_txmgmt_idr_remove(int buf_id, void *skb, void *ctx)
+static void ath11k_mac_vif_txmgmt_cleanup(struct ath11k *ar,
+					  struct ieee80211_vif *vif)
 {
-	struct ieee80211_vif *vif = ctx;
-	struct ath11k_skb_cb *skb_cb = ATH11K_SKB_CB((struct sk_buff *)skb);
-	struct ath11k *ar = skb_cb->ar;
-
-	if (skb_cb->vif == vif)
-		ath11k_mac_tx_mgmt_free(ar, buf_id);
+	struct ath11k_skb_cb *skb_cb;
+	struct sk_buff *skb;
+	int buf_id;
 
-	return 0;
+	idr_for_each_entry(&ar->txmgmt_idr, skb, buf_id) {
+		skb_cb = ATH11K_SKB_CB(skb);
+		if (skb_cb->vif == vif)
+			ath11k_mac_tx_mgmt_free(ar, buf_id);
+	}
 }
 
 static int ath11k_mac_mgmt_tx_wmi(struct ath11k *ar, struct ath11k_vif *arvif,
@@ -7103,8 +7105,7 @@ static void ath11k_mac_op_remove_interface(struct ieee80211_hw *hw,
 
 	ath11k_peer_cleanup(ar, arvif->vdev_id);
 
-	idr_for_each(&ar->txmgmt_idr,
-		     ath11k_mac_vif_txmgmt_idr_remove, vif);
+	ath11k_mac_vif_txmgmt_cleanup(ar, vif);
 
 	for (i = 0; i < ab->hw_params.max_tx_ring; i++) {
 		spin_lock_bh(&ab->dp.tx_ring[i].tx_idr_lock);
Signature · 1 line
2.53.0
author maintainer
#1377 lore raw

PATCH 1375/2151 wifi: ath12k: avoid IDR mutation during vif mgmt TX cleanup

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 4aa45334eb23d40bf31c43405daea9b73469f2a6 ]

ath12k_mac_vdev_delete() walks txmgmt_idr with idr_for_each(), and its callback removes each entry belonging to the interface. Removing the current entry can invalidate the radix-tree iterator retained by idr_for_each().

Move the walk into a helper that uses idr_for_each_entry(). It performs a fresh lookup for every iteration, so each matching entry can be removed through the locked removal helper without retaining iterator state across the removal.

---
 drivers/net/wireless/ath/ath12k/mac.c | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)
drivers/net/wireless/ath/ath12k/mac.c +11 -10
index 7f7eddfa97719..e10a3366cd845 100644
@@ -8316,16 +8316,18 @@ int ath12k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx)
 	return 0;
 }
 
-static int ath12k_mac_vif_txmgmt_idr_remove(int buf_id, void *skb, void *ctx)
+static void ath12k_mac_vif_txmgmt_cleanup(struct ath12k *ar,
+					  struct ieee80211_vif *vif)
 {
-	struct ieee80211_vif *vif = ctx;
-	struct ath12k_skb_cb *skb_cb = ATH12K_SKB_CB(skb);
-	struct ath12k *ar = skb_cb->ar;
-
-	if (skb_cb->vif == vif)
-		ath12k_mac_tx_mgmt_free(ar, buf_id);
+	struct ath12k_skb_cb *skb_cb;
+	struct sk_buff *skb;
+	int buf_id;
 
-	return 0;
+	idr_for_each_entry(&ar->txmgmt_idr, skb, buf_id) {
+		skb_cb = ATH12K_SKB_CB(skb);
+		if (skb_cb->vif == vif)
+			ath12k_mac_tx_mgmt_free(ar, buf_id);
+	}
 }
 
 static int ath12k_mac_mgmt_tx_wmi(struct ath12k *ar, struct ath12k_link_vif *arvif,
@@ -10198,8 +10200,7 @@ static int ath12k_mac_vdev_delete(struct ath12k *ar, struct ath12k_link_vif *arv
 	ath12k_peer_cleanup(ar, arvif->vdev_id);
 	ath12k_ahvif_put_link_cache(ahvif, arvif->link_id);
 
-	idr_for_each(&ar->txmgmt_idr,
-		     ath12k_mac_vif_txmgmt_idr_remove, vif);
+	ath12k_mac_vif_txmgmt_cleanup(ar, vif);
 
 	ath12k_mac_vif_unref(&ab->dp, vif);
 	ath12k_dp_tx_put_bank_profile(&ab->dp, arvif->bank_id);
Signature · 1 line
2.53.0
author maintainer
#1378 lore raw

PATCH 1376/2151 selftests/damon: stop kdamond on error exits of no-op commit test

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

Patch series "mm/damon: misc improvements in tests and documents".

Add various improvements to DAMON tests and documents.

Patch 1 and 2 from Zenghui Yu (Huawei) let DAMON selftest to clean up its state and output after running the tests. Patch 3 from Eva Kurchatova makes a few selftest be able to run with Python's safe path mode. Patch 4 from Kunwu Chan improves coverage of DAMON kunit tests. Finally, patches 5 and 6 from Liew Rui Yan clarify and fix typos on documents for DAMOS quota behaviors.

Below are notes that can be removed in the final commit message.

This is a batched repost of DAMON patches that were individually posted. Please refer to each patch for changelog.

This patch (of 6):

The sysfs_no_op_commit_break test starts a kdamond via sysfs, but its error paths (e.g., drgn not installed) exit without stopping it. The leaked kdamond then makes subsequent tests, e.g. lru_sort.sh and reclaim.sh, skip with "Another kdamond is running".

Wrap the post-start logic in try-finally so that kdamonds.stop() is executed on every exit path.

Fixes 10725cd2b09a ("selftests/damon: test no-op commit broke DAMON status")
Assisted-by GLM-5.3 OpenCode
Cc Brendan Higgins <[email protected]>
Cc David Gow <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Eva Kurchatova <[email protected]>
Cc Kunwu Chan <[email protected]>
Cc Lian Wang <[email protected]>
Cc Liew Rui Yan <[email protected]>
---
 .../damon/sysfs_no_op_commit_break.py         | 35 ++++++++++---------
 1 file changed, 18 insertions(+), 17 deletions(-)
tools/testing/selftests/damon/sysfs_no_op_commit_break.py +18 -17
index 2c65cffe6b545..81774ddc55ac4 100755
@@ -47,26 +47,27 @@ def main():
         print('kdamond start failed: %s' % err)
         exit(1)
 
-    before_commit_status, err = \
-        dump_damon_status_dict(kdamonds.kdamonds[0].pid)
-    if err is not None:
-        print('before-commit status dump failed: %s' % err)
-        exit(1)
+    try:
+        before_commit_status, err = \
+            dump_damon_status_dict(kdamonds.kdamonds[0].pid)
+        if err is not None:
+            print('before-commit status dump failed: %s' % err)
+            exit(1)
 
-    kdamonds.kdamonds[0].commit()
+        kdamonds.kdamonds[0].commit()
 
-    after_commit_status, err = \
-        dump_damon_status_dict(kdamonds.kdamonds[0].pid)
-    if err is not None:
-        print('after-commit status dump failed: %s' % err)
-        exit(1)
-
-    if before_commit_status != after_commit_status:
-        print(f'before: {json.dumps(before_commit_status, indent=2)}')
-        print(f'after: {json.dumps(after_commit_status, indent=2)}')
-        exit(1)
+        after_commit_status, err = \
+            dump_damon_status_dict(kdamonds.kdamonds[0].pid)
+        if err is not None:
+            print('after-commit status dump failed: %s' % err)
+            exit(1)
 
-    kdamonds.stop()
+        if before_commit_status != after_commit_status:
+            print(f'before: {json.dumps(before_commit_status, indent=2)}')
+            print(f'after: {json.dumps(after_commit_status, indent=2)}')
+            exit(1)
+    finally:
+        kdamonds.stop()
 
 if __name__ == '__main__':
     main()
Signature · 1 line
2.53.0
author maintainer
#1379 lore raw

PATCH 1377/2151 selftests/cgroup: ignore memory.reclaim -EAGAIN for zswap writeback test

In reply to Greg Kroah-Hartman

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

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

From: Harry Yoo (Meta) <[email protected]>

[ Upstream commit adbb0adb434d55bd02b18c8de6356f954a077c79 ]

The zswap_writeback_enabled test fails when a write to memory.reclaim returns -EAGAIN, which means less than the requested amount was reclaimed. attempt_writeback() propagates the -EAGAIN to the caller, and the test case is marked as failed even when zswap writeback did happen.

This heavily depends on the performance of the backing swap device. Reclaim does not wait for writeback (on cgroup v2), does not count pages that are under writeback as reclaimed, and memory.reclaim gives up after MAX_RECLAIM_RETRIES passes without making progress. On a slow device where reclaim does not make any progress before writeback completes, a write to memory.reclaim fails.

On a VM with zswap enabled, where IO delay was injected via dm-delay, the success rate of the zswap writeback test drops dramatically once the delay reaches 11 ms: 7% failures at 10 ms and 79% failures at 11 ms, n = 100.

When zswap writeback is enabled, ignore -EAGAIN from memory.reclaim and determine pass/fail based on the zswpwb counter because that is what zswap_writeback_enabled actually wants to test.

With this change, the test reliably passes even on a slow swap device (tested up to 1000 ms delay). This makes the test resilient against the performance of the swap device.

Fixes 158863e5d7cc ("selftests: cgroup: add tests to verify the zswap writeback path")
Assisted-by LLM
Cc Chengming Zhou <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Joshua Hahn <[email protected]>
Cc Kiryl Shutsemau <[email protected]>
Cc Michal Koutný <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Usama Arif <[email protected]>
---
 tools/testing/selftests/cgroup/test_zswap.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
tools/testing/selftests/cgroup/test_zswap.c +10 -1
index 086a085fa6d0f..36d466cf7fcf6 100644
@@ -322,7 +322,16 @@ static int attempt_writeback(const char *cgroup, void *arg)
 	 * it can't writeback to swap.
 	 */
 	ret = cg_write_numeric(cgroup, "memory.reclaim", memsize);
-	if (!wb_enabled)
+
+	/*
+	 * When writeback is enabled, memory.reclaim may still fail to reclaim
+	 * the requested amount of memory due to a slow swap device.
+	 * Ignore -EAGAIN here. The caller determines pass/fail based on the
+	 * zswap writeback counter.
+	 */
+	if (wb_enabled && ret == -EAGAIN)
+		ret = 0;
+	else if (!wb_enabled)
 		ret = (ret == -EAGAIN) ? 0 : -1;
 
 out:
Signature · 1 line
2.53.0
author maintainer
#1380 lore raw

PATCH 1378/2151 mm/hmm/test: reject overflowing page counts

In reply to Greg Kroah-Hartman

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

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

From: Dan Carpenter <[email protected]>

[ Upstream commit b59925301211ccc351d98d70b11f6d1b2c63150f ]

The number of pages comes directly from userspace. Shifting a value larger than ULONG_MAX >> PAGE_SHIFT discards its high bits before the existing end-address check. A request for a huge number of pages can therefore be accepted and processed as a much smaller request.

Reject page counts that cannot be represented as a byte size before performing the shift.

So far as ChatGPT and I can tell this doesn't cause an issue in practice but preventing this integer overflow is the correct thing to do.

Fixes b2ef9f5a5cb3 ("mm/hmm/test: add selftest driver for HMM")
Assisted-by ChatGPT:gpt-5
Cc Jason Gunthorpe <[email protected]>
Cc Jerome Glisse <[email protected]>
Cc Leon Romanovsky <[email protected]>
Cc Ralph Campbell <[email protected]>
Cc Wei Yongjun <[email protected]>
---
 lib/test_hmm.c | 2 ++
 1 file changed, 2 insertions(+)
lib/test_hmm.c +2 -0
index ec1df4cd84807..5eaa18b80f00c 100644
@@ -1301,6 +1301,8 @@ static long dmirror_fops_unlocked_ioctl(struct file *filp,
 
 	if (cmd.addr & ~PAGE_MASK)
 		return -EINVAL;
+	if (cmd.npages > ULONG_MAX >> PAGE_SHIFT)
+		return -EINVAL;
 	if (cmd.addr >= (cmd.addr + (cmd.npages << PAGE_SHIFT)))
 		return -EINVAL;
 
Signature · 1 line
2.53.0
author maintainer
#1381 lore raw

PATCH 1379/2151 ALSA: jack: Remove debugfs before freeing unregistered jacks

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

Jack debugfs files store a raw snd_jack_kctl pointer, so their callbacks must be drained before the attachment is freed. snd_jack_dev_free() unlinks and frees the attachments before calling snd_jack_dev_disconnect(). Its late snd_jack_remove_debugfs() call then has no entries left to traverse.

With CONFIG_SND_JACK_INJECTION_DEBUG and input support enabled, an HDA codec rebind on a live card can publish a non-phantom jack's type file while its component is still in SNDRV_DEV_BUILD. A later jack-control allocation failure permits the following order:

1. hda_codec_driver_probe() creates a jack and publishes its debugfs files before reaching snd_card_register().
2. A later control-build failure calls snd_hda_codec_cleanup_for_unbind(), then snd_hda_jack_tbl_clear() and snd_device_free(). __snd_device_disconnect() skips BUILD components. snd_jack_dev_free() frees the attachment before its late disconnect, leaving the debugfs files published.
3. After cleanup, a reader opens the surviving type file and jack_type_read() dereferences the freed attachment's jack pointer.

The card's debugfs root remains live throughout this sequence. The result is a use-after-free even without an overlapping read. An already admitted callback is also not drained by this cleanup.

Call snd_jack_remove_debugfs() before unlinking any controls in the free callback. The existing debugfs_remove() rundown blocks new accesses and waits for active callbacks while the attachment, control and jack remain valid. Roots cleared by an earlier disconnect are NULL, so repeating the removal is harmless.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in jack_type_read+0x1da/0x1f0
    Read of size 8 at addr ffff8881085f9da0 by task python3/429

    CPU: 2 UID: 0 PID: 429 Comm: python3 Not tainted 7.2.0-rc6-pmb-alsa-functional-v2+ #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
     ? jack_type_read+0x1da/0x1f0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? jack_type_read+0x1da/0x1f0
     kasan_report+0xe0/0x110
     ? jack_type_read+0x1da/0x1f0
     jack_type_read+0x1da/0x1f0
     ? __pfx_jack_type_read+0x10/0x10
     ? __pfx___debugfs_file_get+0x10/0x10
     ? __pfx_cp_new_stat+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? selinux_file_permission+0x122/0x570
     full_proxy_read+0x11f/0x180
     ? __pfx_full_proxy_read+0x10/0x10
     vfs_read+0x1a0/0xc20
     ? __pfx_vfs_read+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __do_sys_newfstat+0xa6/0x100
     ? find_held_lock+0x2b/0x80
     ? __pfx___do_sys_newfstat+0x10/0x10
     ksys_read+0x111/0x200
     ? __pfx_ksys_read+0x10/0x10
     ? full_proxy_llseek+0x11e/0x170
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
    RIP: 0033:0x7f7e392e7687
    Code: 48 89 fa 4c 89 df e8 58 b3 00 00 8b 93 08 03 00 00 59 5e 48 83 f8 fc 74 1a 5b c3 0f 1f 84 00 00 00 00 00 48 8b 44 24 10 0f 05 <5b> c3 0f 1f 80 00 00 00 00 83 e2 39 83 fa 08 75 de e8 23 ff ff ff
    RSP: 002b:00007fff5f7b9180 EFLAGS: 00000202 ORIG_RAX: 0000000000000000
    RAX: ffffffffffffffda RBX: 00007f7e39253780 RCX: 00007f7e392e7687
    RDX: 0000000000002000 RSI: 000000003d2e9b00 RDI: 0000000000000003
    RBP: 0000000000000000 R08: 0000000000000000 R09: 0000000000000000
    R10: 0000000000000000 R11: 0000000000000202 R12: 00007f7e39253700
    R13: 0000000000002000 R14: 00007f7e38d7e2c0 R15: 0000000000a55b98
     </TASK>

    Allocated by task 425:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x251/0x610
     snd_jack_kctl_new+0x80/0x180
     snd_jack_new+0x4b/0x490
     snd_hda_jack_add_kctl_mst+0x19b/0x610
     add_jack_kctl+0x204/0x320
     snd_hda_jack_add_kctls+0x212/0x910
     snd_hda_gen_build_controls+0x233/0x600
     snd_hda_codec_build_controls+0x2e4/0x9f0
     hda_codec_driver_probe+0x26e/0x590
     really_probe+0x21f/0xa90
     __driver_probe_device+0x1ec/0x490
     device_driver_attach+0xdc/0x210
     bind_store+0xec/0x180
     drv_attr_store+0x79/0xb0
     sysfs_kf_write+0xed/0x140
     kernfs_fop_write_iter+0x34b/0x500
     vfs_write+0x637/0x1010
     ksys_write+0x111/0x200
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 425:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x307/0x580
     snd_jack_kctl_private_free+0x153/0x200
     __snd_ctl_remove+0x29f/0x3b0
     snd_ctl_remove+0x46/0x70
     snd_jack_dev_free+0x1b1/0x370
     __snd_device_free+0x193/0x3f0
     snd_device_free+0xcf/0x190
     snd_hda_jack_tbl_clear+0x159/0x2e0
     snd_hda_codec_cleanup_for_unbind+0x37e/0x9c0
     hda_codec_driver_probe+0x3ae/0x590
     really_probe+0x21f/0xa90
     __driver_probe_device+0x1ec/0x490
     device_driver_attach+0xdc/0x210
     bind_store+0xec/0x180
     drv_attr_store+0x79/0xb0
     sysfs_kf_write+0xed/0x140
     kernfs_fop_write_iter+0x34b/0x500
     vfs_write+0x637/0x1010
     ksys_write+0x111/0x200
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff8881085f9d80
     which belongs to the cache kmalloc-64 of size 64
    The buggy address is located 32 bytes inside of
     freed 64-byte region [ffff8881085f9d80, ffff8881085f9dc0)

    The buggy address belongs to the physical page:
    page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x1085f9
    flags: 0x200000000000000(node=0|zone=2)
    page_type: f5(slab)
    raw: 0200000000000000 ffff8881000428c0 dead000000000100 dead000000000122
    raw: 0000000000000000 0000000000200020 00000000f5000000 0000000000000000
    page dumped because: kasan: bad access detected

    Memory state around the buggy address:
     ffff8881085f9c80: 00 00 00 00 00 00 00 00 fc fc fc fc fc fc fc fc
     ffff8881085f9d00: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    >ffff8881085f9d80: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
                                   ^
     ffff8881085f9e00: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff8881085f9e80: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    ==================================================================
Fixes 495000a38634 ("ALSA: core: Remove debugfs at disconnection")
Assisted-by LLM
---
 sound/core/jack.c | 3 +++
 1 file changed, 3 insertions(+)
sound/core/jack.c +3 -0
index 71607d904e061..12a3a0fad3ccb 100644
@@ -68,6 +68,9 @@ static int snd_jack_dev_free(struct snd_device *device)
 	struct snd_card *card = device->card;
 	struct snd_jack_kctl *jack_kctl, *tmp_jack_kctl;
 
+	/* Remove debugfs while the controls are still linked. */
+	snd_jack_remove_debugfs(jack);
+
 	list_for_each_entry_safe(jack_kctl, tmp_jack_kctl, &jack->kctl_list, list) {
 		list_del_init(&jack_kctl->list);
 		snd_ctl_remove(card, jack_kctl->kctl);
Signature · 1 line
2.53.0
author maintainer
#1382 lore raw

PATCH 1380/2151 ALSA: hda: intel: Dont free card in the probe work

In reply to Greg Kroah-Hartman

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

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

From: Ali Ahmet Memiş <[email protected]>

[ Upstream commit fbaccb1b19c79e79220e3bcc5bb18ca54ffb017b ]

If the delayed probe fails, azx_probe_work() frees the card and clears the drvdata. azx_remove() reads the card before it waits for the probe work with cancel_delayed_work_sync() so when the device is removed while the probe work is running, it frees the card again after the work has already freed it.

Only disconnect the card in the work so that its slot is released right away and leave freeing it to azx_remove().

---
 sound/hda/controllers/intel.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
sound/hda/controllers/intel.c +6 -1
index 449b6fda94913..6390fc91c0a45 100644
@@ -1723,7 +1723,12 @@ static void azx_check_snoop_available(struct azx *chip)
 static void azx_probe_work(struct work_struct *work)
 {
 	struct hda_intel *hda = container_of(work, struct hda_intel, probe_work.work);
-	azx_probe_continue(&hda->chip, true);
+
+	if (azx_probe_continue(&hda->chip, false) < 0) {
+		hda->init_failed = 1;
+		complete_all(&hda->probe_wait);
+		snd_card_disconnect(hda->chip.card);
+	}
 }
 
 static int default_bdl_pos_adj(struct azx *chip)
Signature · 1 line
2.53.0
author maintainer
#1383 lore raw

PATCH 1381/2151 platform/x86: asus-wmi: validate custom fan curves on enable

In reply to Greg Kroah-Hartman

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

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

From: Ahmed Yaseen <[email protected]>

[ Upstream commit bcbdfe03566ad0d01c6af3b5476e8cadffe4d3df ]

Custom fan curves reach firmware unchecked, so a curve whose temperature or PWM decreases from one point to the next is accepted. The firmware does not respect such a curve: a first point of 100% followed by 50% leaves every point running at 100%. The kernel keeps reporting the points that were written, so sysfs stops describing what the fans are actually doing.

Check the curve when enabling and reject it if it is invalid. Validation is done on enable rather than on write because fan curves are written one point at a time and are inconsistent mid-write.

Fixes 0f0ac158d28f ("platform/x86: asus-wmi: Add support for custom fan curves")
---
 drivers/platform/x86/asus-wmi.c | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
drivers/platform/x86/asus-wmi.c +32 -0
index 75316c268a74e..777c7e18223fd 100644
@@ -3389,6 +3389,33 @@ static int fan_curve_write(struct asus_wmi *asus,
 					 arg1, arg2, arg3, arg4, &ret);
 }
 
+/*
+ * A fan curve is a set of points the firmware interpolates between, so it
+ * only makes sense if neither temperature nor PWM ever decreases along it.
+ */
+static int fan_curve_validate(struct device *dev, struct fan_curve_data *data)
+{
+	u8 *percents = data->percents;
+	u8 *temps = data->temps;
+	int i;
+
+	for (i = 1; i < FAN_CURVE_POINTS; i++) {
+		if (temps[i] < temps[i - 1]) {
+			dev_warn(dev, "fan curve: temperature decreases at point %d (%u < %u)\n",
+				 i, temps[i], temps[i - 1]);
+			return -EINVAL;
+		}
+
+		if (percents[i] < percents[i - 1]) {
+			dev_warn(dev, "fan curve: pwm decreases at point %d (%u < %u)\n",
+				 i, percents[i], percents[i - 1]);
+			return -EINVAL;
+		}
+	}
+
+	return 0;
+}
+
 static ssize_t fan_curve_store(struct device *dev,
 			       struct device_attribute *attr, const char *buf,
 			       size_t count)
@@ -3473,6 +3500,11 @@ static ssize_t fan_curve_enable_store(struct device *dev,
 	}
 
 	if (data->enabled) {
+		err = fan_curve_validate(dev, data);
+		if (err) {
+			data->enabled = false;
+			return err;
+		}
 		err = fan_curve_write(asus, data);
 		if (err)
 			return err;
Signature · 1 line
2.53.0
author maintainer
#1384 lore raw

PATCH 1382/2151 platform/x86: msi-ec: Report valid charge thresholds when unset

In reply to Greg Kroah-Hartman

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

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

From: Daasaradhi Mannava <[email protected]>

[ Upstream commit a102207eaf4a18c60c2ffbdc421ad3d30bfed591 ]

The charge thresholds are computed by subtracting a fixed offset from the raw EC value. When no charge limit has been set, the EC can hold a value below range_min (0x80 on an MSI GL65 Leopard 9SCXK), and reading the sysfs attributes returns nonsense:

charge_control_start_threshold: -10
charge_control_end_threshold: 0

Both attributes are documented to be within 0 - 100, and an end threshold of 0 wrongly suggests that charging is disabled.

The store path already rejects values outside range_min..range_max. Apply the same range to the show path and report the maximum threshold for any value outside of it.

Tested on an MSI GL65 Leopard 9SCXK (EC firmware 16U8EMS2.100) with the EC holding 0x80: the attributes now read 90 and 100.

Fixes 392cacf2aa10 ("platform/x86: Add new msi-ec driver")
Assisted-by LLM
---
 drivers/platform/x86/msi-ec.c | 9 +++++++++
 1 file changed, 9 insertions(+)
drivers/platform/x86/msi-ec.c +9 -0
index 0cec54d497d1e..e00c4ed7d7b3c 100644
@@ -1197,6 +1197,15 @@ static ssize_t charge_control_threshold_show(u8 offset,
 	if (result < 0)
 		return result;
 
+	/*
+	 * The EC may hold an out-of-range value (e.g. 0x80) when no charge
+	 * limit has been set. Report the maximum threshold instead of a
+	 * meaningless (possibly negative) percentage.
+	 */
+	if (rdata < conf.charge_control.range_min ||
+	    rdata > conf.charge_control.range_max)
+		rdata = conf.charge_control.range_max;
+
 	return sysfs_emit(buf, "%i\n", rdata - offset);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1385 lore raw

PATCH 1383/2151 platform/x86/intel: power-domains: Handle failed init in tpmi_get_linux_die_id()

In reply to Greg Kroah-Hartman

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

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

From: Kristen Carlson Accardi <[email protected]>

[ Upstream commit e7aa0a21a38afd3063fd9b4bf31025a882537d95 ]

tpmi_init() returns early with -ENODEV on CPU models that are not in tpmi_cpu_ids, before domain_die_map is allocated. When the driver is built in, tpmi_get_linux_die_id() remains callable after the failed init and dereferences the NULL domain_die_map.

This is reachable from user space: uncore-frequency-tpmi calls tpmi_get_linux_die_id() from the show function of the world-readable die_id sysfs attribute. The attribute is created on multi-die packages for clusters with the core agent type, so reading it on such a CPU that is missing from tpmi_cpu_ids oopses.

Likewise, if cpuhp_setup_state() fails, the error path frees domain_die_map but leaves the pointer set, so a later call would read freed memory.

Return -ENODEV when the map was not allocated, and clear the pointer wherever it is freed.

tpmi_get_linux_cpu_number(), tpmi_get_punit_core_number() and tpmi_get_power_domain_id() read only the static per-CPU data and hash table, so they are safe after a failed init. tpmi_get_power_domain_mask() has the same problem as this helper but no callers, so it is handled separately.

Fixes e37be5d85c60 ("platform/x86/intel: power-domains: Add interface to get Linux die ID")
Assisted-by LLM
---
 drivers/platform/x86/intel/tpmi_power_domains.c | 9 +++++++++
 1 file changed, 9 insertions(+)
drivers/platform/x86/intel/tpmi_power_domains.c +9 -0
index 7d93119a4c30c..476ad9b8cf3cf 100644
@@ -156,6 +156,13 @@ EXPORT_SYMBOL_NS_GPL(tpmi_get_power_domain_mask, "INTEL_TPMI_POWER_DOMAIN");
 
 int tpmi_get_linux_die_id(int pkg_id, int domain_id)
 {
+	/*
+	 * When built in, this stays callable after tpmi_init() failed
+	 * before allocating the map.
+	 */
+	if (!domain_die_map)
+		return -ENODEV;
+
 	if (pkg_id >= topology_max_packages() || domain_id >= MAX_POWER_DOMAINS)
 		return -EINVAL;
 
@@ -245,6 +252,7 @@ static int __init tpmi_init(void)
 
 free_domain_map:
 	kfree(domain_die_map);
+	domain_die_map = NULL;
 
 free_domain_mask:
 	kfree(tpmi_power_domain_mask);
@@ -258,6 +266,7 @@ static void __exit tpmi_exit(void)
 	cpuhp_remove_state(tpmi_hp_state);
 	kfree(tpmi_power_domain_mask);
 	kfree(domain_die_map);
+	domain_die_map = NULL;
 }
 module_exit(tpmi_exit)
 
Signature · 1 line
2.53.0
author maintainer
#1386 lore raw

PATCH 1384/2151 platform/x86: intel_telemetry: initialize default trace verbosity

In reply to Greg Kroah-Hartman

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

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

From: Aleksandrova Alyona <[email protected]>

[ Upstream commit 1b55ec81926eb7f6e4fad692fa4040a569e9daf7 ]

telemetry_def_get_trace_verbosity() returns success without initializing the output verbosity value.

The default telemetry operations are installed when the core driver is initialized and again by telemetry_clear_pltdata() when the platform driver is removed. The telemetry debugfs files can remain available after the platform driver removal.

A subsequent read of pss_trace_verbosity or ioss_trace_verbosity calls telemetry_get_trace_verbosity(), which may use the default callback and return success without setting verbosity. The uninitialized value is then passed to seq_printf().

Validate the output pointer and initialize the default verbosity to zero so callers never use an uninitialized value after a successful call.

Found by Linux Verification Center (linuxtesting.org) with SVACE.

---
 drivers/platform/x86/intel/telemetry/core.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/platform/x86/intel/telemetry/core.c +4 -0
index f312864b8d07a..62299524a07b2 100644
@@ -24,6 +24,10 @@ static struct telemetry_core_config telm_core_conf;
 static int telemetry_def_get_trace_verbosity(enum telemetry_unit telem_unit,
 					     u32 *verbosity)
 {
+	if (!verbosity)
+		return -EINVAL;
+
+	*verbosity = 0;
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1387 lore raw

PATCH 1385/2151 platform/olpc: Reserve space for a string terminator

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 1fe88b1741ff655bb59e4fd78178fe2c557b9185 ]

ec_dbgfs_cmd_write() copies user input into a zero-initialized stack buffer and passes it to sscanf(). A write that overwrites the entire buffer leaves no terminator, so the subsequent parsing can read beyond the buffer.

Limit the copy to leave room for the trailing NUL.

Fixes 6cca83d498bd ("Platform: OLPC: move debugfs support from x86 EC driver")
---
 drivers/platform/olpc/olpc-ec.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/platform/olpc/olpc-ec.c +1 -1
index 48e9861bb571f..c264c9b888f94 100644
@@ -269,7 +269,7 @@ static ssize_t ec_dbgfs_cmd_write(struct file *file, const char __user *buf,
 
 	mutex_lock(&ec_dbgfs_lock);
 
-	size = simple_write_to_buffer(cmdbuf, sizeof(cmdbuf), ppos, buf, size);
+	size = simple_write_to_buffer(cmdbuf, sizeof(cmdbuf) - 1, ppos, buf, size);
 
 	m = sscanf(cmdbuf, "%x:%u %x %x %x %x %x", &ec_cmd_int[0],
 			&ec_dbgfs_resp_bytes, &ec_cmd_int[1], &ec_cmd_int[2],
Signature · 1 line
2.53.0
author maintainer
#1388 lore raw

PATCH 1386/2151 platform/x86/amd/pmc: clear devm-managed pointers on remove to prevent stale reuse

In reply to Greg Kroah-Hartman

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

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

From: Shyam Sundar S K <[email protected]>

[ Upstream commit c9ba86f5411730ebd333d94b9e1aa8f652dc743f ]

The driver stores its state in a single file-scope static struct amd_pmc_dev, which is reused on every bind. Its regbase, smu_virt_addr, stb_virt_addr and fch_virt_addr members are MMIO mappings created with devm_ioremap().

On unbind the driver core unmaps these mappings, but it does not clear the pointers in the static struct. Since the struct is not freed, the members keep pointing at the now-unmapped addresses.

On the next bind, the probe path re-maps a region only when its pointer is still NULL, so the stale pointer is reused and the following memcpy_fromio()/ioread32() touches freed MMIO, causing use-after-unmap crash. Clear these pointers in amd_pmc_remove() so the next probe re-maps them instead of reusing stale ones.

---
 drivers/platform/x86/amd/pmc/pmc.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/platform/x86/amd/pmc/pmc.c +4 -0
index 8abb80e1803f9..5c05db31c96b3 100644
@@ -884,6 +884,10 @@ static void amd_pmc_remove(struct platform_device *pdev)
 	pci_dev_put(dev->rdev);
 	if (IS_ENABLED(CONFIG_AMD_MP2_STB))
 		amd_mp2_stb_deinit(dev);
+	dev->regbase = NULL;
+	dev->smu_virt_addr = NULL;
+	dev->stb_virt_addr = NULL;
+	dev->fch_virt_addr = NULL;
 }
 
 static const struct acpi_device_id amd_pmc_acpi_ids[] = {
Signature · 1 line
2.53.0
author maintainer
#1389 lore raw

PATCH 1387/2151 fbdev: gxt4500: Release WC setup on probe failure

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit b71e0bb7ad40c005b167e9b48be3af5a3fa51974 ]

gxt4500_probe() adds a write-combining range before allocating the cmap and registering the framebuffer. If a later step fails, the range is not released. Add the missing cleanup before unmapping the framebuffer, matching the successful remove path.

This issue was identified during our ongoing static-analysis research while reviewing kernel code.

Fixes 38fc4d45fae5 ("gxt4500: Use arch_phys_wc_* for framebuffer")
Assisted-by LLM
---
 drivers/video/fbdev/gxt4500.c | 1 +
 1 file changed, 1 insertion(+)
drivers/video/fbdev/gxt4500.c +1 -0
index 15a82c6b609ea..138f5efbf4f40 100644
@@ -719,6 +719,7 @@ static int gxt4500_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
  err_free_cmap:
 	fb_dealloc_cmap(&info->cmap);
  err_unmap_all:
+	arch_phys_wc_del(par->wc_cookie);
 	iounmap(info->screen_base);
  err_unmap_regs:
 	iounmap(par->regs);
Signature · 1 line
2.53.0
author maintainer
#1390 lore raw

PATCH 1388/2151 ALSA: rawmidi: Drain input work before freeing the runtime

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

The input runtime embeds event_work, so the work must be drained before close_substream() frees the runtime. The cancellation in snd_rawmidi_input_trigger() runs before close clears substream->opened, leaving a window for snd_rawmidi_receive() to enqueue more work.

With a sequencer subscription to a USB MIDI input port, an in-flight completion can overlap the last subscription's midisynth_unsubscribe():

1. snd_usbmidi_input_data() observes input_triggered and is delayed before calling snd_rawmidi_receive().
2. Unsubscribe enters close_substream(), clears input_triggered through the provider trigger callback and returns from cancel_work_sync(). The substream is still opened.
3. The completion resumes. snd_rawmidi_receive() takes substream->lock, sees opened set and queues runtime->event_work before dropping the lock.
4. Close clears opened under that lock, closes the provider and frees the runtime. Stopping USB URBs does not drain the raw-MIDI work.
5. The queued work runs and snd_rawmidi_input_event_work() reads event or substream from the freed runtime, causing a use-after-free.

Cancel input event_work again after clearing opened, before closing the provider or releasing the runtime's private data. Receive holds substream->lock through its opened check and work enqueue, so once close has cleared opened under that lock, no further receive can queue work. The final cancellation therefore drains any late work before the runtime is freed. Keep it outside the spinlock so a running callback can finish.

Fixes b3c705aa9e91 ("ALSA: rawmidi - Use workq for event handling")
Assisted-by LLM
---
 sound/core/rawmidi.c | 3 +++
 1 file changed, 3 insertions(+)
sound/core/rawmidi.c +3 -0
index 63c8978c98750..efbc9ff4c1150 100644
@@ -557,6 +557,9 @@ static void close_substream(struct snd_rawmidi *rmidi,
 		substream->opened = 0;
 		substream->append = 0;
 	}
+	/* Drain input work queued after the earlier cancellation. */
+	if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
+		cancel_work_sync(&substream->runtime->event_work);
 	substream->ops->close(substream);
 	if (substream->runtime->private_free)
 		substream->runtime->private_free(substream);
Signature · 1 line
2.53.0
author maintainer
#1391 lore raw

PATCH 1389/2151 ALSA: pcm: Protect delay DMA sync against concurrent HW_FREE

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 50f413b83b31ea8d8ee4276165ab95ed5ab0e10f ]

A PCM DMA buffer must remain allocated until explicit DMA synchronization finishes. snd_pcm_delay() calls snd_pcm_dma_buffer_sync() after dropping the stream lock, without participating in the buffer-access exclusion used by HW_FREE.

With a managed NONCONTIG buffer requiring explicit sync, HW_PARAMS can allocate a separate runtime descriptor when the requested ring exceeds the preallocation. In PREPARED state with mmap_count zero, concurrent HWSYNC and HW_FREE calls on the same open PCM file can interleave:

1. HWSYNC checks the state in snd_pcm_delay() under the stream lock and releases that lock.
2. The sync helper fetches runtime->dma_buffer_p and enters snd_dma_noncontig_sync() with that descriptor.
3. HW_FREE takes the negative buffer-access count, checks PREPARED under the stream lock, releases the lock, and frees the DMA allocation and dynamic descriptor through snd_pcm_lib_free_pages().
4. The sync callback resumes and reads the freed descriptor.

The stream lock does not cover the allocation's release, and the sync operation has no positive buffer-access count to prevent it. The stale read causes a use-after-free in snd_dma_noncontig_sync(). DELAY uses the same snd_pcm_delay() path.

Take a positive buffer-access count before checking the state and keep it until the DMA sync finishes, as the transfer and mmap paths already do. HW_FREE then returns -EBUSY while this access is active. If a buffer writer has already entered, snd_pcm_delay() returns -EBUSY before using the buffer. Keep the sync outside the stream lock and balance the count on the state-error path as well.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in snd_dma_noncontig_sync+0x295/0x310 [snd_pcm]
    Read of size 4 at addr ffff888108f58584 by task pcm-uaf-fixture/487

    CPU: 1 UID: 0 PID: 487 Comm: pcm-uaf-fixture Not tainted 7.2.0-rc6-pmb-alsa-functional-v2+ #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
     ? snd_dma_noncontig_sync+0x295/0x310 [snd_pcm]
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? snd_dma_noncontig_sync+0x295/0x310 [snd_pcm]
     kasan_report+0xe0/0x110
     ? snd_dma_noncontig_sync+0x295/0x310 [snd_pcm]
     ? __pfx_snd_dma_noncontig_sync+0x10/0x10 [snd_pcm]
     snd_dma_noncontig_sync+0x295/0x310 [snd_pcm]
     ? __pfx_snd_dma_noncontig_sync+0x10/0x10 [snd_pcm]
     snd_dma_buffer_sync+0xc9/0x110 [snd_pcm]
     snd_pcm_delay+0x3bd/0x550 [snd_pcm]
     snd_pcm_common_ioctl+0x1e7/0x3aa0 [snd_pcm]
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? do_vfs_ioctl+0x1f5/0x1280
     ? __pfx_do_vfs_ioctl+0x10/0x10
     ? ioctl_has_perm.constprop.0.isra.0+0x34f/0x500
     ? __pfx_snd_pcm_common_ioctl+0x10/0x10 [snd_pcm]
     ? srso_alias_return_thunk+0x5/0xfbef5
     snd_pcm_ioctl+0x76/0xb0 [snd_pcm]
     ? __pfx_snd_pcm_ioctl+0x10/0x10 [snd_pcm]
     __x64_sys_ioctl+0x163/0x1d0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
    RIP: 0033:0x7f1cae7ab91b
    Code: 00 48 89 44 24 18 31 c0 48 8d 44 24 60 c7 04 24 10 00 00 00 48 89 44 24 08 48 8d 44 24 20 48 89 44 24 10 b8 10 00 00 00 0f 05 <89> c2 3d 00 f0 ff ff 77 1c 48 8b 44 24 18 64 48 2b 04 25 28 00 00
    RSP: 002b:00007ffe12d544f0 EFLAGS: 00000246 ORIG_RAX: 0000000000000010
    RAX: ffffffffffffffda RBX: 0000000000000004 RCX: 00007f1cae7ab91b
    RDX: 0000000000000000 RSI: 0000000000004122 RDI: 0000000000000003
    RBP: 00000000000001ee R08: 0000000000000073 R09: 00000000ffffffff
    R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000003
    R13: 0000000000000001 R14: 00005584f32b1398 R15: 00005584f32b2ce8
     </TASK>

    Allocated by task 487:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x251/0x610
     snd_pcm_lib_malloc_pages+0x27c/0x9f0 [snd_pcm]
     snd_pcm_hw_params+0x171c/0x1d10 [snd_pcm]
     snd_pcm_common_ioctl+0x1f62/0x3aa0 [snd_pcm]
     snd_pcm_ioctl+0x76/0xb0 [snd_pcm]
     __x64_sys_ioctl+0x163/0x1d0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 499:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x307/0x580
     snd_pcm_lib_free_pages+0x1c9/0x420 [snd_pcm]
     snd_pcm_common_ioctl+0x2bd3/0x3aa0 [snd_pcm]
     snd_pcm_ioctl+0x76/0xb0 [snd_pcm]
     __x64_sys_ioctl+0x163/0x1d0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff888108f58580
     which belongs to the cache kmalloc-64 of size 64
    The buggy address is located 4 bytes inside of
     freed 64-byte region [ffff888108f58580, ffff888108f585c0)

    The buggy address belongs to the physical page:
    page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x108f58
    flags: 0x200000000000000(node=0|zone=2)
    page_type: f5(slab)
    raw: 0200000000000000 ffff8881000428c0 dead000000000100 dead000000000122
    raw: 0000000000000000 0000000000200020 00000000f5000000 0000000000000000
    page dumped because: kasan: bad access detected

    Memory state around the buggy address:
     ffff888108f58480: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff888108f58500: 00 00 00 00 00 06 fc fc fc fc fc fc fc fc fc fc
    >ffff888108f58580: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
                       ^
     ffff888108f58600: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff888108f58680: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    ==================================================================
    Disabling lock debugging due to kernel taint
    ------------[ cut here ]------------
    kernel BUG at kernel/dma/mapping.c:417!
    Oops: invalid opcode: 0000 [#1] SMP KASAN NOPTI
    CPU: 1 UID: 0 PID: 487 Comm: pcm-uaf-fixture Tainted: G    B               7.2.0-rc6-pmb-alsa-functional-v2+ #1 PREEMPT(lazy)
    Tainted: [B]=BAD_PAGE
    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
    RIP: 0010:__dma_sync_sg_for_cpu+0x230/0x360
    Code: df 48 c1 e8 03 80 3c 10 00 0f 85 fa 00 00 00 4c 8b 35 d4 6b 7a 09 e8 7f e2 17 00 83 fd 02 0f 86 39 fe ff ff e8 71 e2 17 00 90 <0f> 0b e8 69 e2 17 00 be 08 00 00 00 4c 89 ff e8 bc 5f 77 00 4c 89
    RSP: 0018:ffff888111f3fc50 EFLAGS: 00010293
    RAX: 0000000000000000 RBX: ffffffffc0250d10 RCX: ffffffff816d395f
    RDX: ffff88810836ba00 RSI: ffff888108f58580 RDI: ffffffffc02510d8
    RBP: 00000000ffff8881 R08: 0000000000000000 R09: fffffbfff804a239
    R10: ffffffffc02511cf R11: 6e696c6261736944 R12: ffff888108f58580
    R13: 0000000002ce00e5 R14: ffffffffc0258720 R15: 0000000000000000
    FS:  00007f1cae69c780(0000) GS:ffff8881fd861000(0000) knlGS:0000000000000000
    CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    CR2: 000055d1affa2480 CR3: 0000000108fc0003 CR4: 0000000000770ef0
    PKRU: 55555554
    Call Trace:
     <TASK>
     snd_dma_noncontig_sync+0x15a/0x310 [snd_pcm]
     ? __pfx_snd_dma_noncontig_sync+0x10/0x10 [snd_pcm]
     snd_dma_buffer_sync+0xc9/0x110 [snd_pcm]
     snd_pcm_delay+0x3bd/0x550 [snd_pcm]
     snd_pcm_common_ioctl+0x1e7/0x3aa0 [snd_pcm]
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? do_vfs_ioctl+0x1f5/0x1280
     ? __pfx_do_vfs_ioctl+0x10/0x10
     ? ioctl_has_perm.constprop.0.isra.0+0x34f/0x500
     ? __pfx_snd_pcm_common_ioctl+0x10/0x10 [snd_pcm]
     ? srso_alias_return_thunk+0x5/0xfbef5
     snd_pcm_ioctl+0x76/0xb0 [snd_pcm]
     ? __pfx_snd_pcm_ioctl+0x10/0x10 [snd_pcm]
     __x64_sys_ioctl+0x163/0x1d0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
    RIP: 0033:0x7f1cae7ab91b
    Code: 00 48 89 44 24 18 31 c0 48 8d 44 24 60 c7 04 24 10 00 00 00 48 89 44 24 08 48 8d 44 24 20 48 89 44 24 10 b8 10 00 00 00 0f 05 <89> c2 3d 00 f0 ff ff 77 1c 48 8b 44 24 18 64 48 2b 04 25 28 00 00
    RSP: 002b:00007ffe12d544f0 EFLAGS: 00000246 ORIG_RAX: 0000000000000010
    RAX: ffffffffffffffda RBX: 0000000000000004 RCX: 00007f1cae7ab91b
    RDX: 0000000000000000 RSI: 0000000000004122 RDI: 0000000000000003
    RBP: 00000000000001ee R08: 0000000000000073 R09: 00000000ffffffff
    R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000003
    R13: 0000000000000001 R14: 00005584f32b1398 R15: 00005584f32b2ce8
     </TASK>
    Modules linked in: snd_pcmtest snd_pcm
    ---[ end trace 0000000000000000 ]---
    RIP: 0010:__dma_sync_sg_for_cpu+0x230/0x360
    Code: df 48 c1 e8 03 80 3c 10 00 0f 85 fa 00 00 00 4c 8b 35 d4 6b 7a 09 e8 7f e2 17 00 83 fd 02 0f 86 39 fe ff ff e8 71 e2 17 00 90 <0f> 0b e8 69 e2 17 00 be 08 00 00 00 4c 89 ff e8 bc 5f 77 00 4c 89
    RSP: 0018:ffff888111f3fc50 EFLAGS: 00010293
    RAX: 0000000000000000 RBX: ffffffffc0250d10 RCX: ffffffff816d395f
    RDX: ffff88810836ba00 RSI: ffff888108f58580 RDI: ffffffffc02510d8
    RBP: 00000000ffff8881 R08: 0000000000000000 R09: fffffbfff804a239
    R10: ffffffffc02511cf R11: 6e696c6261736944 R12: ffff888108f58580
    R13: 0000000002ce00e5 R14: ffffffffc0258720 R15: 0000000000000000
    FS:  00007f1cae69c780(0000) GS:ffff8881fd861000(0000) knlGS:0000000000000000
    CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    CR2: 000055d1affa2480 CR3: 0000000108fc0003 CR4: 0000000000770ef0
    PKRU: 55555554
    Kernel panic - not syncing: Fatal exception
    Kernel Offset: disabled
    Rebooting in 1 seconds..
Fixes a25684a95646 ("ALSA: memalloc: Support for non-contiguous page allocation")
Assisted-by LLM
---
 sound/core/pcm_native.c | 5 +++++
 1 file changed, 5 insertions(+)
sound/core/pcm_native.c +5 -0
index 79b49d8e6a87c..b1353c3bd1892 100644
@@ -3075,14 +3075,19 @@ static snd_pcm_sframes_t snd_pcm_forward(struct snd_pcm_substream *substream,
 static int snd_pcm_delay(struct snd_pcm_substream *substream,
 			 snd_pcm_sframes_t *delay)
 {
+	struct snd_pcm_runtime *runtime = substream->runtime;
 	int err;
 
+	/* Keep the DMA buffer alive through the sync below. */
+	if (!atomic_inc_unless_negative(&runtime->buffer_accessing))
+		return -EBUSY;
 	scoped_guard(pcm_stream_lock_irq, substream) {
 		err = do_pcm_hwsync(substream);
 		if (delay && !err)
 			*delay = snd_pcm_calc_delay(substream);
 	}
 	snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_CPU);
+	atomic_dec(&runtime->buffer_accessing);
 
 	return err;
 }
Signature · 1 line
2.53.0
author maintainer
#1392 lore raw

PATCH 1390/2151 PCI: qcom: Honor IOMMU providers #iommu-cells in qcom_pcie_config_sid_1_9_0()

In reply to Greg Kroah-Hartman

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

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

From: Manivannan Sadhasivam <[email protected]>

[ Upstream commit 5121d76cb9dde74662962cd5678a64abeaf3b3e4 ]

qcom_pcie_config_sid_1_9_0() reads the "iommu-map" property as an array of fixed four-word {rid-base, phandle, sid, rid-len} entries to program the BDF to SID translation table. But that layout only holds for an IOMMU with '#iommu-cells = <1>'. The PCIe SMMUs on these SoCs use '#iommu-cells = <2>' (SID and mask), so per the pci-iommu binding each entry is really five cells long.

This used to work only because the DTs were themselves broken. They described iommu-map with four-cell entries that omitted the SID mask, which of_map_id() tolerated via its of_check_bad_map() fallback, and the four-word parsing coincidentally matched that malformed shape.

Since commit ccb2fd725d41 ("of: Respect #{iommu,msi}-cells in maps") the OF core parses such maps correctly, so the device trees were converted to proper five-cell entries, e.g. commit c41749e9554d ("arm64: dts:
qcom: sm8250: Fix the PCIe iommu-map entries"). With five-cell entries the fixed four-word stride slips by one cell for each entry after the first, so qcom_pcie_config_sid_1_9_0() reads the endpoint mapping's RID from the preceding entry's length cell and its SID from the phandle cell. As the RID is the hash key, the endpoint's real RID is never programmed into the BDF to SID table. Its DMA then hashes to an unprogrammed slot, gets tagged with SID 0 and the SMMU faults like below on QCS8300:

arm-smmu 15200000.iommu: Unhandled context fault: fsr=0x402, iova=0xffa00000, cbfrsynra=0x0, cb=1

To fix this, walk the map with a stride of 3 + '#iommu-cells' of the referenced IOMMU and take the SID from the first specifier cell, which is all the BDF to SID table needs. Validate the layout instead of trusting the array size. Also, preserve the legacy behavior of the old DTs by detecting the same pattern that of_check_bad_map() recognizes and falling back to a stride of four.

---
 drivers/pci/controller/dwc/pcie-qcom.c | 90 ++++++++++++++++++--------
 1 file changed, 64 insertions(+), 26 deletions(-)
drivers/pci/controller/dwc/pcie-qcom.c +64 -26
index fbdb5a9264785..559aa85902d51 100644
@@ -1063,50 +1063,90 @@ static void qcom_pcie_deinit_2_7_0(struct qcom_pcie *pcie)
 
 static int qcom_pcie_config_sid_1_9_0(struct qcom_pcie *pcie)
 {
-	/* iommu map structure */
-	struct {
-		u32 bdf;
-		u32 phandle;
-		u32 smmu_sid;
-		u32 smmu_sid_len;
-	} *map;
 	void __iomem *bdf_to_sid_base = pcie->parf + PARF_BDF_TO_SID_TABLE_N;
 	struct device *dev = pcie->pci->dev;
+	struct device_node *iommu_np;
 	u8 qcom_pcie_crc8_table[CRC8_TABLE_SIZE];
-	int i, nr_map, size = 0;
-	u32 smmu_sid_base;
+	const __be32 *map;
+	u32 iommu_cells, entry_cells, phandle, smmu_sid_base;
+	int i, nr_cells, nr_map, size = 0;
 	u32 val;
 
-	of_get_property(dev->of_node, "iommu-map", &size);
-	if (!size)
+	map = of_get_property(dev->of_node, "iommu-map", &size);
+	if (!map || !size)
 		return 0;
 
+	if (size % sizeof(*map)) {
+		dev_err(dev, "Malformed iommu-map property\n");
+		return -EINVAL;
+	}
+	nr_cells = size / sizeof(*map);
+
+	/*
+	 * Each iommu-map entry is: rid-base (1 cell), phandle (1 cell),
+	 * IOMMU specifier (#iommu-cells cells), length (1 cell). Read
+	 * #iommu-cells from the IOMMU provider referenced by the first
+	 * entry to compute the per-entry stride.
+	 */
+	phandle = be32_to_cpu(map[1]);
+	iommu_np = of_find_node_by_phandle(phandle);
+	if (!iommu_np) {
+		dev_err(dev, "Failed to find IOMMU node in iommu-map\n");
+		return -ENODEV;
+	}
+
+	if (of_property_read_u32(iommu_np, "#iommu-cells", &iommu_cells))
+		iommu_cells = 1;
+	of_node_put(iommu_np);
+
+	entry_cells = 3 + iommu_cells;
+
+	/*
+	 * Retain backward compatibility with DTs that describe iommu-map
+	 * with 4-cell entries against an IOMMU declaring #iommu-cells = 2,
+	 * matching the fallback in drivers/of/base.c::of_check_bad_map().
+	 */
+	if (iommu_cells == 2 && !(nr_cells % 4)) {
+		bool legacy = true;
+
+		for (i = 0; i < nr_cells; i += 4) {
+			if (be32_to_cpu(map[i + 1]) != phandle ||
+			    be32_to_cpu(map[i + 3]) != 1) {
+				legacy = false;
+				break;
+			}
+		}
+
+		if (legacy) {
+			dev_warn_once(dev, "iommu-map has 1-cell entries with #iommu-cells=2, using 1-cell\n");
+			entry_cells = 4;
+		}
+	}
+
+	if (nr_cells % entry_cells) {
+		dev_err(dev, "Malformed iommu-map property\n");
+		return -EINVAL;
+	}
+	nr_map = nr_cells / entry_cells;
+
 	/* Enable BDF to SID translation by disabling bypass mode (default) */
 	val = readl(pcie->parf + PARF_BDF_TO_SID_CFG);
 	val &= ~BDF_TO_SID_BYPASS;
 	writel(val, pcie->parf + PARF_BDF_TO_SID_CFG);
 
-	map = kzalloc(size, GFP_KERNEL);
-	if (!map)
-		return -ENOMEM;
-
-	of_property_read_u32_array(dev->of_node, "iommu-map", (u32 *)map,
-				   size / sizeof(u32));
-
-	nr_map = size / (sizeof(*map));
-
 	crc8_populate_msb(qcom_pcie_crc8_table, QCOM_PCIE_CRC8_POLYNOMIAL);
 
 	/* Registers need to be zero out first */
 	memset_io(bdf_to_sid_base, 0, CRC8_TABLE_SIZE * sizeof(u32));
 
 	/* Extract the SMMU SID base from the first entry of iommu-map */
-	smmu_sid_base = map[0].smmu_sid;
+	smmu_sid_base = be32_to_cpu(map[2]);
 
 	/* Look for an available entry to hold the mapping */
 	for (i = 0; i < nr_map; i++) {
-		__be16 bdf_be = cpu_to_be16(map[i].bdf);
-		u32 val;
+		u32 bdf = be32_to_cpu(map[i * entry_cells]);
+		u32 sid = be32_to_cpu(map[i * entry_cells + 2]);
+		__be16 bdf_be = cpu_to_be16(bdf);
 		u8 hash;
 
 		hash = crc8(qcom_pcie_crc8_table, (u8 *)&bdf_be, sizeof(bdf_be), 0);
@@ -1128,12 +1168,10 @@ static int qcom_pcie_config_sid_1_9_0(struct qcom_pcie *pcie)
 		}
 
 		/* BDF [31:16] | SID [15:8] | NEXT [7:0] */
-		val = map[i].bdf << 16 | (map[i].smmu_sid - smmu_sid_base) << 8 | 0;
+		val = bdf << 16 | (sid - smmu_sid_base) << 8 | 0;
 		writel(val, bdf_to_sid_base + hash * sizeof(u32));
 	}
 
-	kfree(map);
-
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1393 lore raw

PATCH 1391/2151 calipso: hash the cache key, not the option start, in calipso_cache_add()

In reply to Greg Kroah-Hartman

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

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

From: Joas Antonio dos Santos <[email protected]>

[ Upstream commit d538cc3ec0bc4cb7b40981b3213a6c6671959ed5 ]

calipso_cache_add() stores calipso_ptr + 2 as the cache key, but computes entry->hash over calipso_ptr, i.e. starting two bytes earlier at the option type and length. calipso_opt_getattr() looks entries up with calipso_cache_check(calipso + 2, calipso[1], ...), which hashes the key itself.

The two hashes only match on a jhash collision, so the CALIPSO label cache never hits and every labelled packet takes the full DOI lookup and category conversion path. The memcmp() on the key keeps lookups correct, so this is a performance bug only.

Hash the stored key, as cipso_v4_cache_add() does for CIPSO.

Fixes 4fee5242bf41 ("calipso: Add a label cache.")
Assisted-by Claude:claude-opus-5-5
---
 net/ipv6/calipso.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/ipv6/calipso.c +1 -1
index 22008f5a2973d..2bc3a8fac86bf 100644
@@ -284,7 +284,7 @@ static int calipso_cache_add(const unsigned char *calipso_ptr,
 		goto cache_add_failure;
 	}
 	entry->key_len = calipso_ptr_len;
-	entry->hash = calipso_map_cache_hash(calipso_ptr, calipso_ptr_len);
+	entry->hash = calipso_map_cache_hash(entry->key, calipso_ptr_len);
 	refcount_inc(&secattr->cache->refcount);
 	entry->lsm_data = secattr->cache;
 
Signature · 1 line
2.53.0
author maintainer
#1394 lore raw

PATCH 1392/2151 clocksource/drivers/timer-mediatek: Fix random crash at boot

In reply to Greg Kroah-Hartman

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

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

From: Luca Leonardo Scorcia <[email protected]>

[ Upstream commit 8496a1d234e8cf9cb15c4282cb3a11c6550bd242 ]

MediaTek bootloaders generally enable APXGPT timers at boot. This means that a timer IRQ can sometimes happen between the IRQ line request and the configuration of the clock event handler. This leads to a hard crash with an instruction abort, branch to pc 0x0 in mtk_gpt_interrupt handler as clkevt is null.

To avoid this issue request the IRQ with IRQF_NO_AUTOEN and enable it explicitly after the clock event is configured.

Issue was reported and fix tested on the Lenovo Tab E7 (TB-7104F, mt8167).

Fixes a0858f937960 ("clocksource/drivers/timer-mediatek: Convert the driver to timer-of")
---
 drivers/clocksource/timer-mediatek.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/clocksource/timer-mediatek.c +3 -1
index 7bcb4a3f26fb0..e20075b09fab0 100644
@@ -277,7 +277,7 @@ static struct timer_of to = {
 	},
 
 	.of_irq = {
-		.flags = IRQF_TIMER | IRQF_IRQPOLL,
+		.flags = IRQF_TIMER | IRQF_IRQPOLL | IRQF_NO_AUTOEN,
 	},
 };
 
@@ -298,6 +298,7 @@ static int __init mtk_syst_init(struct device_node *node)
 
 	clockevents_config_and_register(&to.clkevt, timer_of_rate(&to),
 					TIMER_SYNC_TICKS, 0xffffffff);
+	enable_irq(timer_of_irq(&to));
 
 	return 0;
 }
@@ -334,6 +335,7 @@ static int __init mtk_gpt_init(struct device_node *node)
 					TIMER_SYNC_TICKS, 0xffffffff);
 
 	mtk_gpt_enable_irq(&to, TIMER_CLK_EVT);
+	enable_irq(timer_of_irq(&to));
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#1395 lore raw

PATCH 1393/2151 RDMA/siw: Enforce IB_ACCESS_REMOTE_READ for read responses

In reply to Greg Kroah-Hartman

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

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

From: Haitam Lazaar <[email protected]>

[ Upstream commit f74eac4fc6c56274fb96c2c44ffad8f01c325f17 ]

When generating an RDMA READ response (SIW_OP_READ_RESPONSE), siw_check_sgl_tx() unconditionally passes 0 as the required permission mask:

    /* Reference memory to be tx'd w/o checking access for LOCAL_READ */
    rv = siw_check_sgl_tx(qp->pd, wqe, 0);

Because perms is 0, siw_check_mem()'s authorization test:

    if ((mem->perms & perms) < perms)

evaluates to (mem->perms & 0) < 0, which is always false. Consequently, an untrusted remote peer can issue an RDMA Read targeting any valid STag in the Protection Domain, even if the memory was registered strictly as write-only (IB_ACCESS_REMOTE_WRITE) without IB_ACCESS_REMOTE_READ.

Enforce that the target memory region was granted IB_ACCESS_REMOTE_READ when answering SIW_OP_READ_RESPONSE work queue entries, while preserving perms = 0 for standard local sends.

---
 drivers/infiniband/sw/siw/siw_qp_tx.c | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)
drivers/infiniband/sw/siw/siw_qp_tx.c +11 -7
index 54c9d97015e8f..c133c20b835d2 100644
@@ -805,17 +805,21 @@ static int siw_qp_sq_proc_tx(struct siw_qp *qp, struct siw_wqe *wqe)
 
 	if (wqe->wr_status == SIW_WR_QUEUED) {
 		if (!(wqe->sqe.flags & SIW_WQE_INLINE)) {
-			if (tx_type(wqe) == SIW_OP_READ_RESPONSE)
-				wqe->sqe.num_sge = 1;
-
 			if (tx_type(wqe) != SIW_OP_READ &&
 			    tx_type(wqe) != SIW_OP_READ_LOCAL_INV) {
+				enum ib_access_flags perms = 0;
+
 				/*
-				 * Reference memory to be tx'd w/o checking
-				 * access for LOCAL_READ permission, since
-				 * not defined in RDMA core.
+				 * Local READ permission doesn't exist in RDMA core.
+				 * A READ RESPONSE source is read by the remote peer,
+				 * so it must be checked for REMOTE_READ permission.
 				 */
-				rv = siw_check_sgl_tx(qp->pd, wqe, 0);
+				if (tx_type(wqe) == SIW_OP_READ_RESPONSE) {
+					perms = IB_ACCESS_REMOTE_READ;
+					wqe->sqe.num_sge = 1;
+				}
+
+				rv = siw_check_sgl_tx(qp->pd, wqe, perms);
 				if (rv < 0) {
 					if (tx_type(wqe) ==
 					    SIW_OP_READ_RESPONSE)
Signature · 1 line
2.53.0
author maintainer
#1396 lore raw

PATCH 1394/2151 RDMA/efa: Fix race between admin command timeout and completion

In reply to Greg Kroah-Hartman

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

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

From: Yonatan Nachum <[email protected]>

[ Upstream commit 466612f8a8020c6b3af6377c730775a4c630f12c ]

An admin command that times out can race with the interrupt handler processing its completion, in two ways.

The timeout path releases the completion context without synchronizing against the handler. A handler that has already seen the command as submitted then copies the CQE into the caller's response buffer after the waiter returned and that buffer went out of scope.

The waiter can also observe the command as completed before the CQE was copied, since the status is published first. It decodes its own uninitialized response buffer, returns success with garbage contents and leaks stack data to the caller. Both wait paths read the status without the CQ lock.

Add a timed-out state and publish it under the CQ lock in both wait paths before returning, so the handler, which only completes commands in submitted state, cannot act on an abandoned context. In the interrupt wait path test the return value of the wait instead of the status: the handler signals the completion after copying the CQE, so a successful wait implies a valid response. Read the status in the polling wait path inside the critical section that drains the CQ, which also lets a completion arriving on the last iteration be honored instead of reported as a timeout.

Fixes 0420e542569b ("RDMA/efa: Implement functions that submit and complete admin commands")
---
 drivers/infiniband/hw/efa/efa_com.c | 28 ++++++++++++++++++++--------
 1 file changed, 20 insertions(+), 8 deletions(-)
drivers/infiniband/hw/efa/efa_com.c +20 -8
index 21b9bd1c1fef2..517555760fe30 100644
@@ -27,6 +27,7 @@ enum efa_cmd_status {
 	EFA_CMD_ALLOCATED,
 	EFA_CMD_SUBMITTED,
 	EFA_CMD_COMPLETED,
+	EFA_CMD_TIMED_OUT,
 };
 
 struct efa_comp_ctx {
@@ -501,6 +502,7 @@ static int efa_com_comp_status_to_errno(u8 comp_status)
 static int efa_com_wait_and_process_admin_cq_polling(struct efa_comp_ctx *comp_ctx,
 						     struct efa_com_admin_queue *aq)
 {
+	bool comp_timeout = false;
 	unsigned long timeout;
 	unsigned long flags;
 
@@ -509,12 +511,19 @@ static int efa_com_wait_and_process_admin_cq_polling(struct efa_comp_ctx *comp_c
 	while (1) {
 		spin_lock_irqsave(&aq->cq.lock, flags);
 		efa_com_handle_admin_completion(aq);
-		spin_unlock_irqrestore(&aq->cq.lock, flags);
-
-		if (comp_ctx->status != EFA_CMD_SUBMITTED)
+		if (comp_ctx->status != EFA_CMD_SUBMITTED) {
+			spin_unlock_irqrestore(&aq->cq.lock, flags);
 			break;
+		}
 
 		if (time_is_before_jiffies(timeout)) {
+			comp_ctx->status = EFA_CMD_TIMED_OUT;
+			comp_timeout = true;
+		}
+
+		spin_unlock_irqrestore(&aq->cq.lock, flags);
+
+		if (comp_timeout) {
 			ibdev_err_ratelimited(
 				aq->efa_dev,
 				"Wait for completion (polling) timeout\n");
@@ -535,10 +544,11 @@ static int efa_com_wait_and_process_admin_cq_polling(struct efa_comp_ctx *comp_c
 static int efa_com_wait_and_process_admin_cq_interrupts(struct efa_comp_ctx *comp_ctx,
 							struct efa_com_admin_queue *aq)
 {
-	unsigned long flags;
+	unsigned long flags, remaining_jiffies;
+	bool completed;
 
-	wait_for_completion_timeout(&comp_ctx->wait_event,
-				    usecs_to_jiffies(aq->completion_timeout));
+	remaining_jiffies = wait_for_completion_timeout(
+		&comp_ctx->wait_event, usecs_to_jiffies(aq->completion_timeout));
 
 	/*
 	 * In case the command wasn't completed find out the root cause.
@@ -546,14 +556,16 @@ static int efa_com_wait_and_process_admin_cq_interrupts(struct efa_comp_ctx *com
 	 * 1) No completion (timeout reached)
 	 * 2) There is completion but the device didn't get any msi-x interrupt.
 	 */
-	if (comp_ctx->status == EFA_CMD_SUBMITTED) {
+	if (remaining_jiffies == 0) {
 		spin_lock_irqsave(&aq->cq.lock, flags);
 		efa_com_handle_admin_completion(aq);
+		completed = (comp_ctx->status == EFA_CMD_COMPLETED);
+		comp_ctx->status = EFA_CMD_TIMED_OUT;
 		spin_unlock_irqrestore(&aq->cq.lock, flags);
 
 		atomic64_inc(&aq->stats.no_completion);
 
-		if (comp_ctx->status == EFA_CMD_COMPLETED)
+		if (completed)
 			ibdev_err_ratelimited(
 				aq->efa_dev,
 				"The device sent a completion but the driver didn't receive any MSI-X interrupt for admin cmd %s(%d) status %d (id: %d, sq producer: %d, sq consumer: %d, cq consumer: %d)\n",
Signature · 1 line
2.53.0
author maintainer
#1397 lore raw

PATCH 1395/2151 wifi: mac80211: fix encryption tailroom

In reply to Greg Kroah-Hartman

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

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

From: Chien Wong <[email protected]>

[ Upstream commit c49f54fd2abff08964677db8fdc1674c713ab42c ]

BIP-CMAC-256 and BIP-GMAC append a 26-byte MME but mac80211 currently reserves only 18 bytes of encryption tailroom.

Generating 26-byte MME may happen to work because the actual skb tailroom can exceed the requested amount. For example, dev_alloc_skb() rounds the allocation to kmalloc size buckets or alignment boundaries, and the extra space may cover the 8-byte shortfall.

Reserve enough tailroom for the 26-byte MME.

Fixes 56c52da2d554 ("mac80111: Add BIP-CMAC-256 cipher")
---
 net/mac80211/ieee80211_i.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/mac80211/ieee80211_i.h +1 -1
index 0f35094b3898f..1f049720bfda4 100644
@@ -52,7 +52,7 @@ struct ieee80211_mesh_fast_tx;
 
 /* Required encryption head and tailroom */
 #define IEEE80211_ENCRYPT_HEADROOM 8
-#define IEEE80211_ENCRYPT_TAILROOM 18
+#define IEEE80211_ENCRYPT_TAILROOM 26 /* current max: GMAC/CMAC-256 MME */
 
 /* power level hasn't been configured (or set to automatic) */
 #define IEEE80211_UNSET_POWER_LEVEL	INT_MIN
Signature · 1 line
2.53.0
author maintainer
#1398 lore raw

PATCH 1396/2151 wifi: mac80211: reserve MME tailroom for protected beacons

In reply to Greg Kroah-Hartman

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

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

From: Chien Wong <[email protected]>

[ Upstream commit 48002331da85c7c962cfbc09c8bd84d219a6fe1c ]

Beacon protection appends an MME to beacons, but the skb allocation does not reserve tailroom for it. If the available tailroom is too small, the crypto path drops the beacon.

Two factors often mask this: the 256-byte TIM reservation is rarely fully used, and dev_alloc_skb() may round up the allocation, leaving extra tailroom. Neither guarantees enough room for the MME.

Reserve enough room for the largest MME.

Fixes 0a3a84360b37 ("mac80211: Beacon protection using the new BIGTK (AP)")
---
 net/mac80211/tx.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/mac80211/tx.c +2 -1
index f078bc8049a83..6f511ebc51091 100644
@@ -5673,7 +5673,8 @@ __ieee80211_beacon_get_ap(struct ieee80211_hw *hw,
 
 	skb = dev_alloc_skb(local->tx_headroom + beacon->head_len +
 			    beacon->tail_len + 256 +
-			    local->hw.extra_beacon_tailroom + mbssid_len);
+			    local->hw.extra_beacon_tailroom + mbssid_len +
+			    IEEE80211_ENCRYPT_TAILROOM);
 	if (!skb)
 		return NULL;
 
Signature · 1 line
2.53.0
author maintainer
#1399 lore raw

PATCH 1397/2151 wifi: mwifiex: append hotfix number to firmware version string

In reply to Greg Kroah-Hartman

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

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

From: Jeff Chen <[email protected]>

[ Upstream commit 958f20d5aa0aa645068454fdb62ebc625ac9a115 ]

mwifiex_ret_get_hw_spec() parses and logs the FW_HOTFIX_VER_ID TLV, but the hotfix value is not stored in the adapter structure. As a result, the hotfix number never appears in the firmware version string returned by mwifiex_drv_get_driver_version().

Store the hotfix version from FW_HOTFIX_VER_ID and append it to the firmware version string.

Assisted-by LLM sparse
Fixes 7715d79553de ("wifi: mwifiex: Support firmware hotfix version in GET_HW_SPEC responses")
---
 drivers/net/wireless/marvell/mwifiex/cmdevt.c    | 10 ++++++++--
 drivers/net/wireless/marvell/mwifiex/fw.h        |  6 ++++++
 drivers/net/wireless/marvell/mwifiex/init.c      |  1 +
 drivers/net/wireless/marvell/mwifiex/main.h      |  1 +
 drivers/net/wireless/marvell/mwifiex/sta_ioctl.c |  3 ++-
 5 files changed, 18 insertions(+), 3 deletions(-)
drivers/net/wireless/marvell/mwifiex/cmdevt.c +8 -2
index 0f466c31337fa..3eac262945667 100644
@@ -1594,11 +1594,17 @@ int mwifiex_ret_get_hw_spec(struct mwifiex_private *priv,
 						    api_rev->major_ver,
 						    api_rev->minor_ver);
 					break;
-				case FW_HOTFIX_VER_ID:
+				case FW_HOTFIX_VER_ID: {
+					struct hw_spec_fw_hotfix_ver *hf;
+
+					hf = (void *)tlv;
+					adapter->fw_hotfix_ver =
+						le16_to_cpu(hf->hotfix_ver);
 					mwifiex_dbg(adapter, INFO,
 						    "Firmware hotfix version %d\n",
-						    api_rev->major_ver);
+						    adapter->fw_hotfix_ver);
 					break;
+				}
 				default:
 					mwifiex_dbg(adapter, FATAL,
 						    "Unknown api_id: %d\n",
drivers/net/wireless/marvell/mwifiex/fw.h +6 -0
index 93561116959ac..f254d6d6e3eb9 100644
@@ -1104,6 +1104,12 @@ struct hw_spec_api_rev {
 	u8 minor_ver;
 } __packed;
 
+struct hw_spec_fw_hotfix_ver {
+	struct mwifiex_ie_types_header header;
+	__le16 api_id;
+	__le16 hotfix_ver;
+} __packed;
+
 struct host_cmd_ds_get_hw_spec {
 	__le16 hw_if_version;
 	__le16 version;
drivers/net/wireless/marvell/mwifiex/init.c +1 -0
index 5902e2c821f28..501025777adb8 100644
@@ -296,6 +296,7 @@ static void mwifiex_init_adapter(struct mwifiex_adapter *adapter)
 	adapter->config_bands = 0;
 	adapter->adhoc_start_band = 0;
 	adapter->fw_release_number = 0;
+	adapter->fw_hotfix_ver = 0;
 	adapter->fw_cap_info = 0;
 	memset(&adapter->upld_buf, 0, sizeof(adapter->upld_buf));
 	adapter->event_cause = 0;
drivers/net/wireless/marvell/mwifiex/main.h +1 -0
index 27559e2ddc317..eb47ade44e1fb 100644
@@ -1003,6 +1003,7 @@ struct mwifiex_adapter {
 	bool host_mlme_enabled;
 	struct ieee80211_txrx_stypes mwifiex_mgmt_stypes[NUM_NL80211_IFTYPES];
 	u8 fw_api_ver;
+	u16 fw_hotfix_ver;
 	u8 key_api_major_ver, key_api_minor_ver;
 	u8 max_p2p_conn, max_sta_conn;
 	struct memory_type_mapping *mem_type_mapping_tbl;
drivers/net/wireless/marvell/mwifiex/sta_ioctl.c +2 -1
index b8267a5ebcfb0..b752588e1c7c7 100644
@@ -1145,7 +1145,8 @@ mwifiex_drv_get_driver_version(struct mwifiex_adapter *adapter, char *version,
 	char fw_ver[32];
 
 	ver.l = cpu_to_le32(adapter->fw_release_number);
-	sprintf(fw_ver, "%u.%u.%u.p%u", ver.c[2], ver.c[1], ver.c[0], ver.c[3]);
+	sprintf(fw_ver, "%u.%u.%u.p%u.%u", ver.c[2], ver.c[1],
+		ver.c[0], ver.c[3], adapter->fw_hotfix_ver);
 
 	snprintf(version, max_len, driver_version, fw_ver);
 
Signature · 1 line
2.53.0
author maintainer
#1400 lore raw

PATCH 1398/2151 tcp_bic: fix divide by zero on max_increment == 0

In reply to Greg Kroah-Hartman

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

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

From: Jiayuan Chen <[email protected]>

[ Upstream commit 8edbf6c23363563e508a61f3f26f4e4b6eec9dd5 ]

max_increment is how many packets cwnd can grow per RTT, so 0 makes no sense, and bictcp_update() divides by it.

Reject values below 1 when the parameter is written.

Fixes 83803034f423 ("[TCP]: Add TCP BIC congestion control module.")
---
 net/ipv4/tcp_bic.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
net/ipv4/tcp_bic.c +12 -2
index 65444ff142413..27d2e38ff7932 100644
@@ -27,15 +27,25 @@
 					  */
 
 static int fast_convergence = 1;
-static int max_increment = 16;
+static unsigned int max_increment = 16;
 static int low_window = 14;
 static int beta = 819;		/* = 819/1024 (BICTCP_BETA_SCALE) */
 static int initial_ssthresh;
 static int smooth_part = 20;
 
+static int max_increment_set(const char *val, const struct kernel_param *kp)
+{
+	return param_set_uint_minmax(val, kp, 1, INT_MAX);
+}
+
+static const struct kernel_param_ops max_increment_ops = {
+	.set = max_increment_set,
+	.get = param_get_uint,
+};
+
 module_param(fast_convergence, int, 0644);
 MODULE_PARM_DESC(fast_convergence, "turn on/off fast convergence");
-module_param(max_increment, int, 0644);
+module_param_cb(max_increment, &max_increment_ops, &max_increment, 0644);
 MODULE_PARM_DESC(max_increment, "Limit on increment allowed during binary search");
 module_param(low_window, int, 0644);
 MODULE_PARM_DESC(low_window, "lower bound on congestion window (for TCP friendliness)");
Signature · 1 line
2.53.0
author maintainer
#1401 lore raw

PATCH 1399/2151 tcp_hybla: fix divide by zero on rtt0 == 0

In reply to Greg Kroah-Hartman

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

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

From: Jiayuan Chen <[email protected]>

[ Upstream commit f09eb97322b16a6f709a47599c95b62f786905f9 ]

rtt0 is the reference RTT in ms, so 0 makes no sense, and hybla_recalc_param() divides by it right from hybla_init().

Reject values below 1 when the parameter is written. Also cap it at U32_MAX / USEC_PER_MSEC, since rtt0 * USEC_PER_MSEC can wrap to 0 on 32-bit. An rtt0 above that (about 71 minutes) makes no sense anyway.

Fixes 835b3f0c0d7e ("[TCP]: Add TCP Hybla congestion control module.")
Fixes 740b0f1841f6 ("tcp: switch rtt estimations to usec resolution")
---
 net/ipv4/tcp_hybla.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)
net/ipv4/tcp_hybla.c +14 -2
index abd7d91807e54..b9b482180d30b 100644
@@ -26,8 +26,20 @@ struct hybla {
 };
 
 /* Hybla reference round trip time (default= 1/40 sec = 25 ms), in ms */
-static int rtt0 = 25;
-module_param(rtt0, int, 0644);
+static unsigned int rtt0 = 25;
+
+static int rtt0_set(const char *val, const struct kernel_param *kp)
+{
+	/* avoid rtt0 * USEC_PER_MSEC overflow */
+	return param_set_uint_minmax(val, kp, 1, U32_MAX / USEC_PER_MSEC);
+}
+
+static const struct kernel_param_ops rtt0_ops = {
+	.set = rtt0_set,
+	.get = param_get_uint,
+};
+
+module_param_cb(rtt0, &rtt0_ops, &rtt0, 0644);
 MODULE_PARM_DESC(rtt0, "reference rout trip time (ms)");
 
 /* This is called to refresh values for hybla parameters */
Signature · 1 line
2.53.0
author maintainer
#1402 lore raw

PATCH 1400/2151 tcp_cubic: fix divide by zero and endless loop on bad module params

In reply to Greg Kroah-Hartman

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

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

From: Jiayuan Chen <[email protected]>

[ Upstream commit 7d52b5d16afc1cf8484ae321658e217a80e3ff4d ]

beta_scale and cube_factor are computed once at module init, and beta == 1024 or bic_scale == 0 is a divide by zero right there. Other out of range values give garbage: negative beta can make beta_scale 0, and bic_scale * 10 can overflow. Reject them. Read beta once, as it can be written through sysfs before the init function runs.

A small beta also gives a small beta_scale, and (cwnd * beta_scale) >> 3 truncates to 0 for a tiny cwnd, so the TCP friendliness loop never ends. Rather than testing delta on every ACK, make sure beta_scale is at least 8 at init, so delta is >= 1 within the cwnd < 1 million packets limit this code is designed for. This slows the TCP friendly estimate for beta < 512, a backoff harder than Reno's 0.5, which is not a setting anyone should use.

---
 net/ipv4/tcp_cubic.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
net/ipv4/tcp_cubic.c +12 -2
index f891e8d1e5458..bfc18a10b5605 100644
@@ -503,16 +503,26 @@ static const struct btf_kfunc_id_set tcp_cubic_kfunc_set = {
 
 static int __init cubictcp_register(void)
 {
+	int b = READ_ONCE(beta);
 	int ret;
 
 	BUILD_BUG_ON(sizeof(struct bictcp) > ICSK_CA_PRIV_SIZE);
 
+	if (b < 0 || b >= BICTCP_BETA_SCALE ||
+	    bic_scale <= 0 || bic_scale > INT_MAX / 10) {
+		pr_err("tcp_cubic: invalid beta %d or bic_scale %d\n",
+		       b, bic_scale);
+		return -EINVAL;
+	}
+
 	/* Precompute a bunch of the scaling factors that are used per-packet
 	 * based on SRTT of 100ms
 	 */
 
-	beta_scale = 8*(BICTCP_BETA_SCALE+beta) / 3
-		/ (BICTCP_BETA_SCALE - beta);
+	beta_scale = 8 * (BICTCP_BETA_SCALE + b) / 3
+		/ (BICTCP_BETA_SCALE - b);
+	/* bictcp_update() needs (cwnd * beta_scale) >> 3 to be >= 1 */
+	beta_scale = max(beta_scale, 8U);
 
 	cube_rtt_scale = (bic_scale * 10);	/* 1024*c/rtt */
 
Signature · 1 line
2.53.0
author maintainer
#1403 lore raw

PATCH 1401/2151 serial: max310x: dont clobber the TX break bit in set_termios

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

[ Upstream commit 3b2de448ec0332c1cb8c38b4c5ff0c8e860befbc ]

A TX break asserted with TIOCSBRK ends early, with no error reported, as soon as any termios change lands on the port: a break is a state that must hold until TIOCCBRK, but max310x_set_termios() overwrites the whole LCR register, and LCR also carries the TX break bit that break_ctl() drives. No concurrency is required - a baud or parity change from the same process ends the break just as well, and break-led protocols lose their break with nothing in the logs.

Update only the LCR bits that are derived from termios and leave the TX break and RTS pin control bits untouched. Since nothing clears a break when a port is closed with the break still asserted - the tty core sends no break-off on release, and the unconditional write here was the accidental recovery - clear TXBREAK in startup(), the same way 8250 does.

Fixes f65444187a66 ("serial: New serial driver MAX310X")
Assisted-by Claude:claude-fable-5
---
 drivers/tty/serial/max310x.c |   17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)
drivers/tty/serial/max310x.c +15 -2
@@ -156,6 +156,8 @@
 #define MAX310X_LCR_FORCEPARITY_BIT	(1 << 5) /* 9-bit multidrop parity */
 #define MAX310X_LCR_TXBREAK_BIT		(1 << 6) /* TX break enable */
 #define MAX310X_LCR_RTS_BIT		(1 << 7) /* RTS pin control */
+/* LCR bits owned by termios; TX break and RTS are driven elsewhere */
+#define MAX310X_LCR_TERMIOS_MASK	GENMASK(5, 0)
 
 /* IRDA register bits */
 #define MAX310X_IRDA_IRDAEN_BIT		(1 << 0) /* IRDA mode enable */
@@ -941,8 +943,12 @@ static void max310x_set_termios(struct u
 	if (termios->c_cflag & CSTOPB)
 		lcr |= MAX310X_LCR_STOPLEN_BIT; /* 2 stops */
 
-	/* Update LCR register */
-	max310x_port_write(port, MAX310X_LCR_REG, lcr);
+	/*
+	 * Update LCR register. Leave the TX break bit alone: it is driven by
+	 * break_ctl(), and a whole-register write here would end a break in
+	 * progress.
+	 */
+	max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_TERMIOS_MASK, lcr);
 
 	/* Set read status mask */
 	port->read_status_mask = MAX310X_LSR_RXOVR_BIT;
@@ -1060,6 +1066,13 @@ static int max310x_startup(struct uart_p
 
 	max310x_power(port, 1);
 
+	/*
+	 * Clear a latched break: nothing clears TXBREAK when a port is
+	 * closed with a break still asserted, and set_termios() no longer
+	 * rewrites it.
+	 */
+	max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_TXBREAK_BIT, 0);
+
 	/* Configure MODE1 register */
 	max310x_port_update(port, MAX310X_MODE1_REG,
 			    MAX310X_MODE1_TRNSCVCTRL_BIT, 0);
author maintainer
#1404 lore raw

PATCH 1402/2151 serial: max310x: fix breaks not reaching the wire in RS485 mode

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

[ Upstream commit 4efacb600bf98b13e0659f05afa4549795277e35 ]

The chip's auto-RTS (MODE1.TRNSCVCTRL) asserts the RS485 transceiver only while FIFO data is shifting out, and a break is not FIFO data: on an RS485 port a requested break sets the TX break bit but the transceiver is never enabled, so the break never reaches the wire. Break-led protocols cannot work at all.

Disable auto-RTS for the break duration and drive RTS manually via the LCR RTS bit, then restore auto-RTS when the break ends. Track the break in tx_break and leave MODE1 alone in the rs485-config worker while it is set - a TIOCSRS485 arriving mid-break would otherwise re-enable auto-RTS on top of the manual RTS and release the transceiver before the break ends; break_ctl() restores auto-RTS from the then-current configuration when the break completes. The worker runs under port->mutex - break_ctl() and set_termios() already do - so the tx_break test and the MODE1 write cannot straddle a break starting or ending, and startup() clears tx_break alongside the latched TXBREAK bit, since a port can be closed with a break still asserted.

Only the break assertion is gated on RS485 being enabled; the restore at break end runs unconditionally and derives MODE1 from the current configuration. Returning early for a port whose RS485 was disabled mid-break - that reconfigure is deferred like any other - would leak the manually driven RTS and leave the transceiver holding the bus indefinitely after the break ends. On a non-RS485 port the restore is a no-op: nothing else writes the LCR RTS bit.

Fixes 55367c620aed ("serial: max310x: Add support for RS-485 mode")
Assisted-by Claude:claude-fable-5
---
 drivers/tty/serial/max310x.c |   49 +++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 47 insertions(+), 2 deletions(-)
drivers/tty/serial/max310x.c +47 -2
@@ -285,6 +285,7 @@ struct max310x_one {
 	struct work_struct	md_work;
 	struct work_struct	rs_work;
 	struct regmap		*regmap;
+	bool			tx_break;	/* break_ctl() owns the transceiver */
 
 	u8 rx_buf[MAX310X_FIFO_SIZE];
 };
@@ -651,6 +652,12 @@ static void max310x_batch_read(struct ua
 	regmap_noinc_read(one->regmap, MAX310X_RHR_REG, rxbuf, len);
 }
 
+static void max310x_rts_ctl(struct uart_port *port, bool rts_state)
+{
+	max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_RTS_BIT,
+			    rts_state ? MAX310X_LCR_RTS_BIT : 0);
+}
+
 static void max310x_handle_rx(struct uart_port *port, unsigned int rxlen)
 {
 	struct max310x_one *one = to_max310x_port(port);
@@ -901,9 +908,32 @@ static void max310x_set_mctrl(struct uar
 
 static void max310x_break_ctl(struct uart_port *port, int break_state)
 {
+	struct max310x_one *one = to_max310x_port(port);
+
+	one->tx_break = break_state;
+
 	max310x_port_update(port, MAX310X_LCR_REG,
 			    MAX310X_LCR_TXBREAK_BIT,
 			    break_state ? MAX310X_LCR_TXBREAK_BIT : 0);
+
+	/*
+	 * The chip's auto-RTS asserts the transceiver only while FIFO data is
+	 * shifting out, and a break is not FIFO data. Disable auto-RTS for the
+	 * break duration and drive RTS manually so the break reaches the wire;
+	 * restore auto-RTS when the break ends.
+	 */
+	if (break_state) {
+		if (!(port->rs485.flags & SER_RS485_ENABLED))
+			return;
+		max310x_port_update(port, MAX310X_MODE1_REG,
+				    MAX310X_MODE1_TRNSCVCTRL_BIT, 0);
+	} else {
+		max310x_port_update(port, MAX310X_MODE1_REG,
+				    MAX310X_MODE1_TRNSCVCTRL_BIT,
+				    (port->rs485.flags & SER_RS485_ENABLED) ?
+				    MAX310X_MODE1_TRNSCVCTRL_BIT : 0);
+	}
+	max310x_rts_ctl(port, break_state);
 }
 
 static void max310x_set_termios(struct uart_port *port,
@@ -1027,6 +1057,13 @@ static void max310x_rs_proc(struct work_
 	struct max310x_one *one = container_of(ws, struct max310x_one, rs_work);
 	unsigned int delay, mode1 = 0, mode2 = 0;
 
+	/*
+	 * Serialize against break_ctl() and set_termios(), which run under
+	 * port->mutex: the tx_break test below and the MODE1 write must not
+	 * straddle a break starting or ending.
+	 */
+	guard(mutex)(&one->port.state->port.mutex);
+
 	delay = (one->port.rs485.delay_rts_before_send << 4) |
 		one->port.rs485.delay_rts_after_send;
 	max310x_port_write(&one->port, MAX310X_HDPIXDELAY_REG, delay);
@@ -1038,8 +1075,14 @@ static void max310x_rs_proc(struct work_
 			mode2 = MAX310X_MODE2_ECHOSUPR_BIT;
 	}
 
-	max310x_port_update(&one->port, MAX310X_MODE1_REG,
-			MAX310X_MODE1_TRNSCVCTRL_BIT, mode1);
+	/*
+	 * A break owns the transceiver: break_ctl() disabled auto-RTS and
+	 * drives RTS manually, and restores it when the break ends. Leave
+	 * MODE1 alone meanwhile or the break goes undriven mid-way.
+	 */
+	if (!one->tx_break)
+		max310x_port_update(&one->port, MAX310X_MODE1_REG,
+				    MAX310X_MODE1_TRNSCVCTRL_BIT, mode1);
 	max310x_port_update(&one->port, MAX310X_MODE2_REG,
 			MAX310X_MODE2_ECHOSUPR_BIT, mode2);
 }
@@ -1062,6 +1105,7 @@ static int max310x_rs485_config(struct u
 
 static int max310x_startup(struct uart_port *port)
 {
+	struct max310x_one *one = to_max310x_port(port);
 	unsigned int val;
 
 	max310x_power(port, 1);
@@ -1071,6 +1115,7 @@ static int max310x_startup(struct uart_p
 	 * closed with a break still asserted, and set_termios() no longer
 	 * rewrites it.
 	 */
+	one->tx_break = false;
 	max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_TXBREAK_BIT, 0);
 
 	/* Configure MODE1 register */
author maintainer
#1405 lore raw

PATCH 1403/2151 serial: max310x: centralize the RS485 transceiver programming

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

[ Upstream commit 56051740bf9720335a1a56e87a99e3491c33ce54 ]

The HDPIXDELAY RTS delays and the MODE1 auto-transceiver enable are programmed in three places - the rs485-config worker, startup() and break_ctl()'s break-off restore - each with its own copy of the register sequence. Move the sequence into a helper, max310x_set_rts_ctl_params(), together with the tx_break guard that keeps the MODE1 write away from a break in progress; the break-off restore reapplies the current configuration through the same helper.

No functional change intended. The copies differed only in that startup() clamped the delays to the 4-bit field while the worker wrote them unclamped; the helper clamps, and the difference is unreachable while rs485_config() still rejects delays above 15 ms with -ERANGE. Break-off additionally rewrites HDPIXDELAY with the values it already holds, a no-op on the wire.

Stable-dep-of: 7784d6aee59a ("serial: max310x: fix RS485 delays being programmed as bit-times")

---
 drivers/tty/serial/max310x.c |   85 +++++++++++++++++++++++--------------------
 1 file changed, 47 insertions(+), 38 deletions(-)
drivers/tty/serial/max310x.c +47 -38
@@ -906,6 +906,38 @@ static void max310x_set_mctrl(struct uar
 	schedule_work(&one->md_work);
 }
 
+/*
+ * Program the chip's RS485 RTS timing (HDPIXDELAY) and the auto
+ * transceiver control (MODE1) from the current configuration. The
+ * rs485-config worker, startup() and break_ctl()'s break-off restore
+ * each carried their own copy of this sequence.
+ */
+static void max310x_set_rts_ctl_params(struct max310x_one *one)
+{
+	struct uart_port *port = &one->port;
+	unsigned int delay;
+	u8 mode1 = 0;
+
+	delay = (clamp(port->rs485.delay_rts_before_send, 0U, 15U) << 4) |
+		clamp(port->rs485.delay_rts_after_send, 0U, 15U);
+	max310x_port_write(port, MAX310X_HDPIXDELAY_REG, delay);
+
+	if (port->rs485.flags & SER_RS485_ENABLED)
+		mode1 = MAX310X_MODE1_TRNSCVCTRL_BIT;
+
+	/*
+	 * A break owns the transceiver: break_ctl() disabled auto-RTS and
+	 * drives RTS manually, and restores it from the current
+	 * configuration when the break ends. Touching MODE1 here would
+	 * release the transceiver mid-break.
+	 */
+	if (one->tx_break)
+		return;
+
+	max310x_port_update(port, MAX310X_MODE1_REG,
+			    MAX310X_MODE1_TRNSCVCTRL_BIT, mode1);
+}
+
 static void max310x_break_ctl(struct uart_port *port, int break_state)
 {
 	struct max310x_one *one = to_max310x_port(port);
@@ -928,10 +960,7 @@ static void max310x_break_ctl(struct uar
 		max310x_port_update(port, MAX310X_MODE1_REG,
 				    MAX310X_MODE1_TRNSCVCTRL_BIT, 0);
 	} else {
-		max310x_port_update(port, MAX310X_MODE1_REG,
-				    MAX310X_MODE1_TRNSCVCTRL_BIT,
-				    (port->rs485.flags & SER_RS485_ENABLED) ?
-				    MAX310X_MODE1_TRNSCVCTRL_BIT : 0);
+		max310x_set_rts_ctl_params(one);
 	}
 	max310x_rts_ctl(port, break_state);
 }
@@ -1055,36 +1084,23 @@ static void max310x_set_termios(struct u
 static void max310x_rs_proc(struct work_struct *ws)
 {
 	struct max310x_one *one = container_of(ws, struct max310x_one, rs_work);
-	unsigned int delay, mode1 = 0, mode2 = 0;
+	unsigned int mode2 = 0;
 
 	/*
 	 * Serialize against break_ctl() and set_termios(), which run under
-	 * port->mutex: the tx_break test below and the MODE1 write must not
+	 * port->mutex: the tx_break-guarded register writes must not
 	 * straddle a break starting or ending.
 	 */
 	guard(mutex)(&one->port.state->port.mutex);
 
-	delay = (one->port.rs485.delay_rts_before_send << 4) |
-		one->port.rs485.delay_rts_after_send;
-	max310x_port_write(&one->port, MAX310X_HDPIXDELAY_REG, delay);
-
-	if (one->port.rs485.flags & SER_RS485_ENABLED) {
-		mode1 = MAX310X_MODE1_TRNSCVCTRL_BIT;
+	max310x_set_rts_ctl_params(one);
 
-		if (!(one->port.rs485.flags & SER_RS485_RX_DURING_TX))
-			mode2 = MAX310X_MODE2_ECHOSUPR_BIT;
-	}
+	if (one->port.rs485.flags & SER_RS485_ENABLED &&
+	    !(one->port.rs485.flags & SER_RS485_RX_DURING_TX))
+		mode2 = MAX310X_MODE2_ECHOSUPR_BIT;
 
-	/*
-	 * A break owns the transceiver: break_ctl() disabled auto-RTS and
-	 * drives RTS manually, and restores it when the break ends. Leave
-	 * MODE1 alone meanwhile or the break goes undriven mid-way.
-	 */
-	if (!one->tx_break)
-		max310x_port_update(&one->port, MAX310X_MODE1_REG,
-				    MAX310X_MODE1_TRNSCVCTRL_BIT, mode1);
 	max310x_port_update(&one->port, MAX310X_MODE2_REG,
-			MAX310X_MODE2_ECHOSUPR_BIT, mode2);
+			    MAX310X_MODE2_ECHOSUPR_BIT, mode2);
 }
 
 static int max310x_rs485_config(struct uart_port *port, struct ktermios *termios,
@@ -1128,21 +1144,14 @@ static int max310x_startup(struct uart_p
 	max310x_port_update(port, MAX310X_MODE2_REG,
 			    MAX310X_MODE2_FIFORST_BIT, 0);
 
-	/* Configure mode1/mode2 to have rs485/rs232 enabled at startup */
-	val = (clamp(port->rs485.delay_rts_before_send, 0U, 15U) << 4) |
-		clamp(port->rs485.delay_rts_after_send, 0U, 15U);
-	max310x_port_write(port, MAX310X_HDPIXDELAY_REG, val);
-
-	if (port->rs485.flags & SER_RS485_ENABLED) {
-		max310x_port_update(port, MAX310X_MODE1_REG,
-				    MAX310X_MODE1_TRNSCVCTRL_BIT,
-				    MAX310X_MODE1_TRNSCVCTRL_BIT);
+	/* Configure the RS485 RTS timing and the RS485/RS232 mode bits. */
+	max310x_set_rts_ctl_params(one);
 
-		if (!(port->rs485.flags & SER_RS485_RX_DURING_TX))
-			max310x_port_update(port, MAX310X_MODE2_REG,
-					    MAX310X_MODE2_ECHOSUPR_BIT,
-					    MAX310X_MODE2_ECHOSUPR_BIT);
-	}
+	if (port->rs485.flags & SER_RS485_ENABLED &&
+	    !(port->rs485.flags & SER_RS485_RX_DURING_TX))
+		max310x_port_update(port, MAX310X_MODE2_REG,
+				    MAX310X_MODE2_ECHOSUPR_BIT,
+				    MAX310X_MODE2_ECHOSUPR_BIT);
 
 	/*
 	 * Configure flow control levels:
author maintainer
#1406 lore raw

PATCH 1404/2151 serial: max310x: fix RS485 delays being programmed as bit-times

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

[ Upstream commit 7784d6aee59a142505072b3fbea97932b2fd1fa0 ]

The HDPIXDELAY register counts the RTS setup and hold delays in bit-times, four bits per direction, but the driver has been writing the struct serial_rs485 delay_rts_before_send/delay_rts_after_send values into it unconverted - and the uapi expresses those in milliseconds. A requested 9 ms setup delay is programmed as 9 bit-times, which at 9600 baud is 0.94 ms, roughly a tenth of what userspace asked for; the error grows with the baud rate.

Cache the baud rate in set_termios() and convert the delays to bit-times at the current rate, rounding up so the delay on the wire is never shorter than requested, and capping at the 15 bit-times the 4-bit field can hold. The conversion lives in max310x_set_rts_ctl_params(); set_termios() now calls it as well, since the conversion depends on the baud rate.

The delays a 4-bit bit-time field can represent still fall well short of the milliseconds the uapi can express; requests beyond 15 bit-times are capped, and the -ERANGE rejection of values above 15 ms remains in place for now.

Fixes 55367c620aed ("serial: max310x: Add support for RS-485 mode")
Assisted-by Claude:claude-fable-5
---
 drivers/tty/serial/max310x.c |   40 +++++++++++++++++++++++++++++++---------
 1 file changed, 31 insertions(+), 9 deletions(-)
drivers/tty/serial/max310x.c +31 -9
@@ -163,6 +163,10 @@
 #define MAX310X_IRDA_IRDAEN_BIT		(1 << 0) /* IRDA mode enable */
 #define MAX310X_IRDA_SIR_BIT		(1 << 1) /* SIR mode enable */
 
+/* HDPIXDELAY accessor macros */
+#define MAX310X_HDPIXDELAY_SETUP(val)	(((val) & 0x0f) << 4)
+#define MAX310X_HDPIXDELAY_HOLD(val)	((val) & 0x0f)
+
 /* Flow control trigger level register masks */
 #define MAX310X_FLOWLVL_HALT_MASK	GENMASK(3, 0) /* Flow control halt level */
 #define MAX310X_FLOWLVL_RES_MASK	GENMASK(7, 4) /* Flow control resume level */
@@ -285,6 +289,7 @@ struct max310x_one {
 	struct work_struct	md_work;
 	struct work_struct	rs_work;
 	struct regmap		*regmap;
+	unsigned int		baud;
 	bool			tx_break;	/* break_ctl() owns the transceiver */
 
 	u8 rx_buf[MAX310X_FIFO_SIZE];
@@ -907,23 +912,33 @@ static void max310x_set_mctrl(struct uar
 }
 
 /*
- * Program the chip's RS485 RTS timing (HDPIXDELAY) and the auto
- * transceiver control (MODE1) from the current configuration. The
- * rs485-config worker, startup() and break_ctl()'s break-off restore
- * each carried their own copy of this sequence.
+ * Program the chip's RS485 RTS timing. The HDPIXDELAY setup and hold fields
+ * count bit-times, four bits per direction, while the uapi expresses the
+ * delays in milliseconds: convert at the current baud rate, rounding up, and
+ * cap at the field maximum.
  */
 static void max310x_set_rts_ctl_params(struct max310x_one *one)
 {
+	const unsigned int max_bit_dly = 15;
 	struct uart_port *port = &one->port;
-	unsigned int delay;
+	unsigned int setup = 0, hold = 0;
 	u8 mode1 = 0;
 
-	delay = (clamp(port->rs485.delay_rts_before_send, 0U, 15U) << 4) |
-		clamp(port->rs485.delay_rts_after_send, 0U, 15U);
-	max310x_port_write(port, MAX310X_HDPIXDELAY_REG, delay);
+	if (port->rs485.flags & SER_RS485_ENABLED) {
+		/* Convert milliseconds to bit-times, rounding up. */
+		setup = DIV_ROUND_UP(one->baud * port->rs485.delay_rts_before_send,
+				     MSEC_PER_SEC);
+		hold  = DIV_ROUND_UP(one->baud * port->rs485.delay_rts_after_send,
+				     MSEC_PER_SEC);
+		setup = min(setup, max_bit_dly);
+		hold  = min(hold,  max_bit_dly);
 
-	if (port->rs485.flags & SER_RS485_ENABLED)
 		mode1 = MAX310X_MODE1_TRNSCVCTRL_BIT;
+	}
+
+	max310x_port_write(port, MAX310X_HDPIXDELAY_REG,
+			   MAX310X_HDPIXDELAY_SETUP(setup) |
+			   MAX310X_HDPIXDELAY_HOLD(hold));
 
 	/*
 	 * A break owns the transceiver: break_ctl() disabled auto-RTS and
@@ -1079,6 +1094,13 @@ static void max310x_set_termios(struct u
 
 	/* Update timeout according to new baud rate */
 	uart_update_timeout(port, termios->c_cflag, baud);
+
+	/*
+	 * Cache the new baud rate and reprogram the RS485 RTS delays, whose
+	 * millisecond-to-bit-time conversion depends on it.
+	 */
+	to_max310x_port(port)->baud = baud;
+	max310x_set_rts_ctl_params(to_max310x_port(port));
 }
 
 static void max310x_rs_proc(struct work_struct *ws)
author maintainer
#1407 lore raw

PATCH 1405/2151 serial: max310x: dont power down the port mid-transmission on close

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

[ Upstream commit c3ad42ccd303113a08bd0b441fb5b3380f29c5bf ]

max310x_shutdown() powers the port down regardless of what the transmitter is doing. The power-off stops the UART clock mid-character, truncating the final frame, and on the auto-RTS path it freezes the RTS output at its current level: a close() with data still queued leaves the RS485 transceiver asserted until the next open, which also emits the interrupted character corrupted.

Waiting for the data to drain is no better: the tty layer's wait-until-sent is bounded by closing_wait, configurable to none, and a hangup arrives with no wait at all, so draining a full FIFO blocks close() in uninterruptible sleep for seconds at low baud rates - and forever when CTS flow control blocks the FIFO.

Instead, set MODE1 TxDisabl: the character in flight completes and the transmitter ceases with TX_ at idle. Give that character one character time (the chip has no transmitter-idle status), then reset the FIFOs so the auto-RTS engine sees the transmitter empty and releases RTS within the configured after-send hold; wait that hold plus one bit time before powering off. Abandoned data was explicitly not waited for, and startup() resets the FIFOs and TxDisabl on open anyway.

Measured on a MAX14830: a truncating close() at 50 baud takes 0.23 s, RTS releases one character plus the hold after the last stop bit on both polarities, and the reopen corruption is gone.

Fixes f65444187a66 ("serial: New serial driver MAX310X")
Assisted-by Claude:claude-fable-5
---
 drivers/tty/serial/max310x.c |   44 +++++++++++++++++++++++++++++++++++++++----
 1 file changed, 40 insertions(+), 4 deletions(-)
drivers/tty/serial/max310x.c +40 -4
@@ -289,6 +289,7 @@ struct max310x_one {
 	struct work_struct	md_work;
 	struct work_struct	rs_work;
 	struct regmap		*regmap;
+	unsigned int		char_time_us;
 	unsigned int		baud;
 	bool			tx_break;	/* break_ctl() owns the transceiver */
 
@@ -984,6 +985,7 @@ static void max310x_set_termios(struct u
 				struct ktermios *termios,
 				const struct ktermios *old)
 {
+	unsigned int frame_bits = tty_get_frame_size(termios->c_cflag);
 	unsigned int lcr = 0, flow = 0;
 	int baud;
 
@@ -1096,10 +1098,13 @@ static void max310x_set_termios(struct u
 	uart_update_timeout(port, termios->c_cflag, baud);
 
 	/*
-	 * Cache the new baud rate and reprogram the RS485 RTS delays, whose
-	 * millisecond-to-bit-time conversion depends on it.
+	 * Cache the new baud rate and the time it takes to clock out one
+	 * character before reprogramming the RS485 RTS delays: the
+	 * millisecond-to-bit-time conversion divides by the baud rate.
 	 */
 	to_max310x_port(port)->baud = baud;
+	to_max310x_port(port)->char_time_us =
+		DIV_ROUND_UP(USEC_PER_SEC * frame_bits, baud);
 	max310x_set_rts_ctl_params(to_max310x_port(port));
 }
 
@@ -1156,9 +1161,10 @@ static int max310x_startup(struct uart_p
 	one->tx_break = false;
 	max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_TXBREAK_BIT, 0);
 
-	/* Configure MODE1 register */
+	/* Configure MODE1: re-enable the transmitter shutdown() stopped */
 	max310x_port_update(port, MAX310X_MODE1_REG,
-			    MAX310X_MODE1_TRNSCVCTRL_BIT, 0);
+			    MAX310X_MODE1_TRNSCVCTRL_BIT |
+			    MAX310X_MODE1_TXDIS_BIT, 0);
 
 	/* Configure MODE2 register & Reset FIFOs*/
 	val = MAX310X_MODE2_RXEMPTINV_BIT | MAX310X_MODE2_FIFORST_BIT;
@@ -1195,9 +1201,39 @@ static int max310x_startup(struct uart_p
 
 static void max310x_shutdown(struct uart_port *port)
 {
+	struct max310x_one *one = to_max310x_port(port);
+
 	/* Disable all interrupts */
 	max310x_port_write(port, MAX310X_IRQEN_REG, 0);
 
+	/*
+	 * Stop the transmitter: the character in flight completes, data
+	 * still queued is abandoned (the next startup() resets the FIFOs).
+	 */
+	max310x_port_update(port, MAX310X_MODE1_REG,
+			    MAX310X_MODE1_TXDIS_BIT, MAX310X_MODE1_TXDIS_BIT);
+
+	/*
+	 * Let the character in flight finish (the chip has no
+	 * transmitter-idle status), then empty the FIFO: auto-RTS releases
+	 * only once the transmitter is empty, and the power-off below
+	 * would freeze an asserted pin until the next open.
+	 */
+	fsleep(one->char_time_us);
+	max310x_port_update(port, MAX310X_MODE2_REG,
+			    MAX310X_MODE2_FIFORST_BIT,
+			    MAX310X_MODE2_FIFORST_BIT);
+	max310x_port_update(port, MAX310X_MODE2_REG,
+			    MAX310X_MODE2_FIFORST_BIT, 0);
+	if (port->rs485.flags & SER_RS485_ENABLED && one->baud) {
+		unsigned int hold = DIV_ROUND_UP(one->baud *
+				port->rs485.delay_rts_after_send,
+				MSEC_PER_SEC);
+
+		fsleep(max(DIV_ROUND_UP((hold + 1) * USEC_PER_SEC,
+					one->baud), 100U));
+	}
+
 	max310x_power(port, 0);
 }
 
author maintainer
#1408 lore raw

PATCH 1406/2151 serial: max310x: register GPIO controller before adding UART ports

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

[ Upstream commit 25b51d1fd3268a219e43608b165098fff7cd9dcd ]

The MAX310x exposes four GPIOs per UART port via an in-driver gpio_chip. devm_gpiochip_add_data() used to run after the per-port uart_add_one_port() loop, so a device-tree consumer referencing one of the chip's own GPIOs (for example rs485-term-gpios = <&max310x 0 ...>) could not resolve it during port registration: the GPIO provider it waits for is the very driver still trying to register, and the lookup returns -EPROBE_DEFER on its own provider, deferring probe forever.

Split the per-port setup into two passes around the gpio_chip registration:

1. Initialise per-port state - port struct fields, regmap binding, IRQ disable, work queues. The gpio_chip callbacks dereference s->p[i].regmap via to_max310x_port() and become callable as soon as the chip is visible to gpiolib, so every entry must be populated first.
2. devm_gpiochip_add_data() - register the gpio_chip.
3. Allocate a line, uart_add_one_port(), set_bit(), max310x_power(). Keeping line allocation, registration and set_bit() together preserves the existing "bit set <=> port registered" rollback invariant that out_uart relies on.

Stable-dep-of: 33632215e1bb ("serial: max310x: drive RTS in software when hardware delays are too short")

---
 drivers/tty/serial/max310x.c |   54 ++++++++++++++++++++++++++-----------------
 1 file changed, 33 insertions(+), 21 deletions(-)
drivers/tty/serial/max310x.c +33 -21
@@ -1504,17 +1504,12 @@ static int max310x_probe(struct device *
 
 	dev_dbg(dev, "Reference clock set to %i Hz\n", uartclk);
 
+	/*
+	 * Set up each port's state before registering the gpiochip,
+	 * since the gpiochip callbacks will read s->p[i].regmap as
+	 * soon as gpiolib exposes the controller.
+	 */
 	for (i = 0; i < devtype->nr; i++) {
-		unsigned int line;
-
-		line = find_first_zero_bit(max310x_lines, MAX310X_UART_NRMAX);
-		if (line == MAX310X_UART_NRMAX) {
-			ret = -ERANGE;
-			goto out_uart;
-		}
-
-		/* Initialize port data */
-		s->p[i].port.line	= line;
 		s->p[i].port.dev	= dev;
 		s->p[i].port.irq	= irq;
 		s->p[i].port.type	= PORT_MAX310X;
@@ -1544,20 +1539,16 @@ static int max310x_probe(struct device *
 		INIT_WORK(&s->p[i].md_work, max310x_md_proc);
 		/* Initialize queue for changing RS485 mode */
 		INIT_WORK(&s->p[i].rs_work, max310x_rs_proc);
-
-		/* Register port */
-		ret = uart_add_one_port(&max310x_uart, &s->p[i].port);
-		if (ret)
-			goto out_uart;
-
-		set_bit(line, max310x_lines);
-
-		/* Go to suspend mode */
-		max310x_power(&s->p[i].port, 0);
 	}
 
 #ifdef CONFIG_GPIOLIB
-	/* Setup GPIO controller */
+	/*
+	 * Register the GPIO controller before adding the UART ports so
+	 * that consumers referencing the chip's own GPIOs from device
+	 * tree (for example rs485-term-gpios = <&max310x ...>) can
+	 * resolve them at uart_add_one_port() time instead of receiving
+	 * -EPROBE_DEFER from their own provider.
+	 */
 	s->gpio.owner		= THIS_MODULE;
 	s->gpio.parent		= dev;
 	s->gpio.label		= devtype->name;
@@ -1575,6 +1566,27 @@ static int max310x_probe(struct device *
 		goto out_uart;
 #endif
 
+	for (i = 0; i < devtype->nr; i++) {
+		unsigned int line;
+
+		line = find_first_zero_bit(max310x_lines, MAX310X_UART_NRMAX);
+		if (line == MAX310X_UART_NRMAX) {
+			ret = -ERANGE;
+			goto out_uart;
+		}
+		s->p[i].port.line = line;
+
+		/* Register port */
+		ret = uart_add_one_port(&max310x_uart, &s->p[i].port);
+		if (ret)
+			goto out_uart;
+
+		set_bit(line, max310x_lines);
+
+		/* Go to suspend mode */
+		max310x_power(&s->p[i].port, 0);
+	}
+
 	/* Setup interrupt */
 	ret = devm_request_threaded_irq(dev, irq, NULL, max310x_ist,
 					IRQF_ONESHOT | IRQF_SHARED, dev_name(dev), s);
author maintainer
#1409 lore raw

PATCH 1407/2151 serial: max310x: support active-low RTS on the hardware path

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

[ Upstream commit 7b07356e820e9543cb5b64d009c345303aad0c65 ]

The chip's auto-RTS engine asserts the RTS_ pin high while data is shifting out, so a transceiver with an active-low driver-enable could not use the hardware RS485 path at all: SER_RS485_RTS_AFTER_SEND is not in the supported flags and the core normalizes it away with "invalid RTS setting, using RTS_ON_SEND instead".

The output stage is invertible: program IRDA.RTSINVERT when the requested polarity is active-low and advertise SER_RS485_RTS_AFTER_SEND in rs485_supported. A break already drives break_state onto the RTS bit unadjusted, which remains correct because RTSINVERT inverts the output stage itself, not the register value.

Stable-dep-of: 33632215e1bb ("serial: max310x: drive RTS in software when hardware delays are too short")

---
 drivers/tty/serial/max310x.c |   18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
drivers/tty/serial/max310x.c +15 -3
@@ -162,6 +162,7 @@
 /* IRDA register bits */
 #define MAX310X_IRDA_IRDAEN_BIT		(1 << 0) /* IRDA mode enable */
 #define MAX310X_IRDA_SIR_BIT		(1 << 1) /* SIR mode enable */
+#define MAX310X_IRDA_RTSINVERT_BIT	(1 << 2) /* Invert RTS output */
 
 /* HDPIXDELAY accessor macros */
 #define MAX310X_HDPIXDELAY_SETUP(val)	(((val) & 0x0f) << 4)
@@ -923,7 +924,7 @@ static void max310x_set_rts_ctl_params(s
 	const unsigned int max_bit_dly = 15;
 	struct uart_port *port = &one->port;
 	unsigned int setup = 0, hold = 0;
-	u8 mode1 = 0;
+	u8 mode1 = 0, irda = 0;
 
 	if (port->rs485.flags & SER_RS485_ENABLED) {
 		/* Convert milliseconds to bit-times, rounding up. */
@@ -935,6 +936,12 @@ static void max310x_set_rts_ctl_params(s
 		hold  = min(hold,  max_bit_dly);
 
 		mode1 = MAX310X_MODE1_TRNSCVCTRL_BIT;
+		/*
+		 * The auto-RTS engine asserts RTS high on send; for an
+		 * active-low RTS let IRDA.RTSINVERT invert the output stage.
+		 */
+		if (!(port->rs485.flags & SER_RS485_RTS_ON_SEND))
+			irda = MAX310X_IRDA_RTSINVERT_BIT;
 	}
 
 	max310x_port_write(port, MAX310X_HDPIXDELAY_REG,
@@ -952,6 +959,8 @@ static void max310x_set_rts_ctl_params(s
 
 	max310x_port_update(port, MAX310X_MODE1_REG,
 			    MAX310X_MODE1_TRNSCVCTRL_BIT, mode1);
+	max310x_port_update(port, MAX310X_IRDA_REG,
+			    MAX310X_IRDA_RTSINVERT_BIT, irda);
 }
 
 static void max310x_break_ctl(struct uart_port *port, int break_state)
@@ -968,7 +977,9 @@ static void max310x_break_ctl(struct uar
 	 * The chip's auto-RTS asserts the transceiver only while FIFO data is
 	 * shifting out, and a break is not FIFO data. Disable auto-RTS for the
 	 * break duration and drive RTS manually so the break reaches the wire;
-	 * restore auto-RTS when the break ends.
+	 * restore auto-RTS when the break ends. For an active-low RTS,
+	 * IRDA.RTSINVERT already inverts the RTS_ output stage, so break_state
+	 * is driven as it is.
 	 */
 	if (break_state) {
 		if (!(port->rs485.flags & SER_RS485_ENABLED))
@@ -1399,7 +1410,8 @@ static int max310x_gpio_set_config(struc
 #endif
 
 static const struct serial_rs485 max310x_rs485_supported = {
-	.flags = SER_RS485_ENABLED | SER_RS485_RTS_ON_SEND | SER_RS485_RX_DURING_TX,
+	.flags = SER_RS485_ENABLED | SER_RS485_RTS_ON_SEND |
+		 SER_RS485_RTS_AFTER_SEND | SER_RS485_RX_DURING_TX,
 	.delay_rts_before_send = 1,
 	.delay_rts_after_send = 1,
 };
author maintainer
#1410 lore raw

PATCH 1408/2151 serial: max310x: drive RTS in software when hardware delays are too short

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

[ Upstream commit 33632215e1bbc6109173b761e0c9bc5c4fcdbeee ]

The chip's auto-RTS path can express at most 15 bit-times of RTS setup and hold delay - a fraction of a millisecond at typical baud rates - while the uapi expresses the delays in milliseconds up to the UART core's RS485_MAX_RTS_DELAY. Requests beyond the field were rejected with -ERANGE, which makes the core silently wipe port->rs485 and disable RS485; a device tree asking for a 20 ms setup delay ends up with no RS485 at all and an unusable bus.

Add a software-driven RTS path that takes over whenever the hardware cannot represent the requested timing, and clamp the delays to RS485_MAX_RTS_DELAY instead of rejecting them.

max310x_set_rts_ctl_params() picks the path: software if either delay exceeds what 15 bit-times encode at the current baud rate, or if the requested RTS polarity combination cannot be produced by the auto-RTS engine; hardware otherwise, as before.

On the software path the RTS envelope is driven by a single hrtimer, re-used for the before- and after-send phases (tracked in tx_state), plus a single rts_work that toggles RTS. start_tx() begins the envelope; rts_work asserts RTS and only then arms the before-send timer, so data is never shifted before RTS is on the wire. The timer expiry kicks tx_work; once the chip FIFO drains, the same timer is re-armed for one character (the byte still in the shift register) plus the after-send delay, after which rts_work releases RTS. One timer and one work keep the phases mutually exclusive and the RTS toggles ordered. A start_tx() landing while the envelope is already in its send phase only pumps the new data: rewinding it to the before-send phase would insert a spurious setup delay mid-stream.

Teardown is interlocked: shutdown() and an RS485-disabling TIOCSRS485 set tx_teardown under port->lock before cancelling the timer and works, and start_tx() checks it on entry and again after the hrtimer_try_to_cancel(-1) path retakes the dropped lock - otherwise a write racing the teardown could re-arm the timer or queue rts_work against a port being shut down, leaving the transceiver driving the bus after close. The rs485-disable path additionally kicks tx_work afterwards, since a racing write may have queued data with no envelope left to pump it, and shutdown() now also cancels tx_work, which was previously cancelled only in remove(). The interlock also fences the adoption path below, so a reconfigure racing a teardown cannot re-enable the cancelled timer, and an RS485 disable flushes a queued rts_work before the pin is settled: one already past its tx_state read would re-assert RTS after the settle.

set_rts_ctl_params() publishes sw_rts_during_tx with a single store and settles the RTS idle level only while tx_state is off, because serial_core calls set_termios() without port->lock and rs485_config() schedules a reconfigure on every TIOCSRS485 - either could otherwise release the transceiver mid-envelope. The settle also re-checks tx_state after its write and requeues rts_work if an envelope started
meanwhile: the state read and the register write are not atomic, and rts_work re-derives the level from tx_state, so this converges without locking. shutdown() gates first - the
interlock is set and the interrupts are masked before any wait, so nothing can start a new envelope or requeue tx_work behind the cancels
- then honours a running after-send hold, bounded by the after-send delay plus two character times (the transmitter is already stopped by this point), and cancels the timer and works unconditionally: a TIOCSRS485 can clear sw_rts_during_tx while an envelope is still in flight, and neither may outlive the port. A hold that did not complete within the bound is settled by the final release below regardless. break_ctl() on the software path applies the
configured RTS polarity itself.

A reconfigure can also move the port off the hardware path while the chip's auto-RTS still owns a transmission in flight - a termios change or TIOCSRS485 pushing a delay above what the hardware can time at the new rate. Such transfers are invisible to tx_state, so the idle settle would release RTS and the MODE1 write would disable auto-RTS mid-transfer, shifting the rest of the data out with the transceiver released and no error reported anywhere. Adopt the transfer instead when the chip TX FIFO or the xmit buffer is not empty: enter MAX310X_TX_SEND and drive RTS manually before auto-RTS is disabled, so the pin is never released across the handover, and the normal drain path arms the after-send hold - or the adoption arms it directly if the FIFO drained while this raced the TX-empty worker. A transfer whose last character has already left the FIFO for the transmit shift register is still invisible and keeps the old behavior: at most one character of early release.

The reverse move strands state instead: a reconfigure onto the hardware path mid-envelope left tx_state set, because nothing reset it in that direction and the TX-empty hold arming only ran while the software path was selected. A later reconfigure back off the hardware path then trusted the stale tx_state, skipped both the adoption and the idle settle, and disabled auto-RTS with the RTS register released
- the rest of the transfer in flight shifted out with the transceiver off, again with no error reported (hit twice in 79 in-flight reconfigures under a multi-process stress test). The TX-empty unwind now runs regardless of the selected path - it is a no-op outside an envelope - and the reconfigure asserts RTS for any transfer it believes exists, stale or live, before auto-RTS is disabled. The hold is armed only once no transmittable data remains, so that assert cannot cut a burst short when it lands in a FIFO refill window; output that is stopped still releases through the hold.

rts_work also derives the level from tx_break: a break can begin while the previous envelope's after-send hold is still armed - TIOCSBRK waits for the output to drain, which lands the break exactly there - and the expiring hold would otherwise release the transceiver mid-break. With break ownership in the derivation the hold expiry becomes an idempotent re-assert, and break-off restores the idle state as it already does.

shutdown() gives its final RTS release one bit time, and at least 100 us, to reach the pin before powering the port down. The power-off stops the UART channel clock, and the RTS output stage is clocked by it: a release written immediately before the clock stops reaches the register but never moves the pin, which stays asserted until the next startup restarts the clock - a close racing the after-send hold expiry left the transceiver driving the bus, with the register reading released and the pin high. The measured propagation is about one tick of the 16x oversampling clock - below 50 us at 1200 baud - so one bit time keeps a 16x margin and scales with the clock the output stage runs on; the floor covers rates where a bit is shorter than the measured bound. Handing the pin to the chip's auto-RTS engine instead was tried and rejected on the wire:
the pin level is RTSINVERT xor the selected source, so for an active-low RTS every single-register step of that handover drives the pin to the asserted level, and the same clock stop can freeze it there.

Fixes 55367c620aed ("serial: max310x: Add support for RS-485 mode")
Assisted-by Claude:claude-fable-5
---
 drivers/tty/serial/max310x.c |  484 ++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 434 insertions(+), 50 deletions(-)
drivers/tty/serial/max310x.c +434 -50
@@ -14,6 +14,7 @@
 #include <linux/delay.h>
 #include <linux/device.h>
 #include <linux/gpio/driver.h>
+#include <linux/hrtimer.h>
 #include <linux/i2c.h>
 #include <linux/module.h>
 #include <linux/mod_devicetable.h>
@@ -284,15 +285,29 @@ struct max310x_devtype {
 	u8	power_bit; /* Bit for sleep or power-off mode (active high). */
 };
 
+/* Software-timed RS485 RTS envelope phase */
+enum max310x_tx_state {
+	MAX310X_TX_OFF,			/* idle, RTS released */
+	MAX310X_TX_WAIT_BEFORE_SEND,	/* RTS asserted, before-send delay */
+	MAX310X_TX_SEND,		/* data in flight, awaiting TX-empty */
+	MAX310X_TX_WAIT_AFTER_SEND,	/* data drained, after-send hold */
+};
+
 struct max310x_one {
 	struct uart_port	port;
 	struct work_struct	tx_work;
 	struct work_struct	md_work;
 	struct work_struct	rs_work;
+	struct work_struct	rts_work;
+	struct hrtimer		tx_delay_tmr;
 	struct regmap		*regmap;
 	unsigned int		char_time_us;
 	unsigned int		baud;
+	bool			sw_rts_during_tx;
+	bool			cancel_tx_delay_tmr;
+	bool			tx_teardown;	/* envelope being torn down */
 	bool			tx_break;	/* break_ctl() owns the transceiver */
+	enum max310x_tx_state	tx_state;
 
 	u8 rx_buf[MAX310X_FIFO_SIZE];
 };
@@ -665,6 +680,38 @@ static void max310x_rts_ctl(struct uart_
 			    rts_state ? MAX310X_LCR_RTS_BIT : 0);
 }
 
+/* RTS level for the transmitting or the idle phase of an RS485 envelope */
+static bool max310x_rts_level(struct uart_port *port, bool active)
+{
+	return active ? (port->rs485.flags & SER_RS485_RTS_ON_SEND) :
+			(port->rs485.flags & SER_RS485_RTS_AFTER_SEND);
+}
+
+/*
+ * Drive the RS485 RTS line to match the current tx_state and break
+ * ownership. This is the only place that touches RTS, and it reads the
+ * state rather than a fixed assert/deassert intent, so a newer assert is
+ * never clobbered by a stale release and an expiring after-send hold never
+ * releases a break in progress. It also arms the before-send timer once the
+ * RTS edge is on the wire, so data is never shifted before RTS is asserted.
+ */
+static void max310x_rts_work_proc(struct work_struct *ws)
+{
+	struct max310x_one *one = container_of(ws, struct max310x_one, rts_work);
+	struct uart_port *port = &one->port;
+	bool rts_on = READ_ONCE(one->tx_state) != MAX310X_TX_OFF ||
+		      READ_ONCE(one->tx_break);
+
+	max310x_rts_ctl(port, max310x_rts_level(port, rts_on));
+
+	guard(spinlock_irqsave)(&port->lock);
+	if (READ_ONCE(one->tx_state) == MAX310X_TX_WAIT_BEFORE_SEND &&
+	    !one->cancel_tx_delay_tmr && !hrtimer_active(&one->tx_delay_tmr))
+		hrtimer_start(&one->tx_delay_tmr,
+			      ms_to_ktime(port->rs485.delay_rts_before_send),
+			      HRTIMER_MODE_REL);
+}
+
 static void max310x_handle_rx(struct uart_port *port, unsigned int rxlen)
 {
 	struct max310x_one *one = to_max310x_port(port);
@@ -761,6 +808,77 @@ static void max310x_handle_rx(struct uar
 	tty_flip_buffer_push(&port->state->port);
 }
 
+static enum hrtimer_restart max310x_tmr_tx(struct hrtimer *timer)
+{
+	struct max310x_one *one = container_of(timer, struct max310x_one,
+					       tx_delay_tmr);
+
+	guard(spinlock_irqsave)(&one->port.lock);
+	if (!one->cancel_tx_delay_tmr) {
+		if (READ_ONCE(one->tx_state) == MAX310X_TX_WAIT_AFTER_SEND) {
+			/* After-send hold elapsed: drop RTS via the rts worker. */
+			WRITE_ONCE(one->tx_state, MAX310X_TX_OFF);
+			schedule_work(&one->rts_work);
+		} else {
+			WRITE_ONCE(one->tx_state, MAX310X_TX_SEND);
+			schedule_work(&one->tx_work);
+		}
+	}
+
+	return HRTIMER_NORESTART;
+}
+
+static void max310x_delayed_stop_tx(struct uart_port *port)
+{
+	struct max310x_one *one = to_max310x_port(port);
+	unsigned int txlvl;
+
+	if (READ_ONCE(one->tx_state) == MAX310X_TX_OFF)
+		return;
+
+	/*
+	 * Data still queued for transmission defers the hold: a refill is
+	 * coming and the envelope is not over. Stopped output does not
+	 * count - it drains nowhere, and the envelope must end.
+	 */
+	if (!kfifo_is_empty(&port->state->port.xmit_fifo) &&
+	    !uart_tx_stopped(port))
+		return;
+
+	/*
+	 * The kfifo can be empty while the chip TX FIFO is still draining, so arm
+	 * the after-send hold only once the chip FIFO is empty too - the TX-empty
+	 * interrupt re-invokes us then. Otherwise the hold starts early and RTS
+	 * drops mid-character, clipping the last byte(s).
+	 */
+	txlvl = max310x_port_read(port, MAX310X_TXFIFOLVL_REG);
+	if (txlvl)
+		return;
+
+	/*
+	 * Runs from tx_work without port->lock, so re-check the state under it:
+	 * shutdown() may have cancelled the envelope meanwhile. Only
+	 * MAX310X_TX_SEND may arm the hold.
+	 */
+	guard(spinlock_irqsave)(&one->port.lock);
+	if (one->cancel_tx_delay_tmr ||
+	    READ_ONCE(one->tx_state) != MAX310X_TX_SEND)
+		return;
+
+	if (!hrtimer_active(&one->tx_delay_tmr)) {
+		/*
+		 * Add one character for the byte still in the shift register -
+		 * TX-empty fires as it enters, not as it leaves.
+		 */
+		ktime_t delay = us_to_ktime(one->char_time_us +
+					    port->rs485.delay_rts_after_send *
+					    USEC_PER_MSEC);
+
+		WRITE_ONCE(one->tx_state, MAX310X_TX_WAIT_AFTER_SEND);
+		hrtimer_start(&one->tx_delay_tmr, delay, HRTIMER_MODE_REL);
+	}
+}
+
 static void max310x_handle_tx(struct uart_port *port)
 {
 	struct tty_port *tport = &port->state->port;
@@ -774,8 +892,16 @@ static void max310x_handle_tx(struct uar
 		return;
 	}
 
-	if (kfifo_is_empty(&tport->xmit_fifo) || uart_tx_stopped(port))
+	if (kfifo_is_empty(&tport->xmit_fifo) || uart_tx_stopped(port)) {
+		/*
+		 * Unwind the envelope even if a reconfigure has moved the
+		 * port to the hardware path mid-envelope: a stranded
+		 * tx_state would make a later reconfigure believe a
+		 * software envelope still owns RTS.
+		 */
+		max310x_delayed_stop_tx(port);
 		return;
+	}
 
 	/*
 	 * It's a circ buffer -- wrap around.
@@ -797,11 +923,64 @@ static void max310x_handle_tx(struct uar
 		uart_write_wakeup(port);
 }
 
+/*
+ * Begin a software-timed RTS envelope: set the before-send phase and queue the
+ * rts worker to assert RTS. tx_state is set synchronously here (start_tx() holds
+ * port.lock) so close()/shutdown can see an envelope is in flight; rts_work then
+ * asserts RTS and arms the before-send timer (see there).
+ */
+static void max310x_delayed_start_tx(struct uart_port *port)
+{
+	struct max310x_one *one = to_max310x_port(port);
+
+	WRITE_ONCE(one->tx_state, MAX310X_TX_WAIT_BEFORE_SEND);
+	one->cancel_tx_delay_tmr = false;
+	schedule_work(&one->rts_work);
+}
+
+/* called with port.lock taken and irqs off */
 static void max310x_start_tx(struct uart_port *port)
 {
 	struct max310x_one *one = to_max310x_port(port);
 
-	schedule_work(&one->tx_work);
+	/* A teardown is in progress; nothing may start an envelope or TX. */
+	if (one->tx_teardown)
+		return;
+
+	if (READ_ONCE(one->sw_rts_during_tx)) {
+		/*
+		 * The before- and after-send phases share one delay timer. If an
+		 * after-send release is pending, cancel it before starting a new
+		 * TX so the just-asserted RTS is not yanked; re-arming the timer
+		 * for the before-send phase then supersedes the release.
+		 */
+		int res = 0;
+
+		if (READ_ONCE(one->tx_state) == MAX310X_TX_WAIT_AFTER_SEND)
+			res = hrtimer_try_to_cancel(&one->tx_delay_tmr);
+		if (unlikely(res == -1)) {
+			one->cancel_tx_delay_tmr = true;
+			uart_port_unlock(port);
+			hrtimer_cancel(&one->tx_delay_tmr);
+			uart_port_lock(port);
+			/*
+			 * The lock was dropped: a teardown may have run to
+			 * completion meanwhile. Re-check before starting.
+			 */
+			if (one->tx_teardown)
+				return;
+		}
+
+		/* Already sending: pump the new data, don't rewind. */
+		if (READ_ONCE(one->tx_state) == MAX310X_TX_SEND) {
+			schedule_work(&one->tx_work);
+			return;
+		}
+
+		max310x_delayed_start_tx(port);
+	} else {
+		schedule_work(&one->tx_work);
+	}
 }
 
 static irqreturn_t max310x_port_irq(struct max310x_port *s, int portno)
@@ -914,10 +1093,39 @@ static void max310x_set_mctrl(struct uar
 }
 
 /*
- * Program the chip's RS485 RTS timing. The HDPIXDELAY setup and hold fields
- * count bit-times, four bits per direction, while the uapi expresses the
- * delays in milliseconds: convert at the current baud rate, rounding up, and
- * cap at the field maximum.
+ * A reconfigure can move the port off the hardware RTS path while the chip's
+ * auto-RTS still owns a transmission in flight; tx_state does not track
+ * those. Take such a transfer over before auto-RTS is disabled: enter
+ * MAX310X_TX_SEND, so the caller keeps RTS driven across the handover and
+ * the normal drain path arms the after-send hold. Returns true when a
+ * transmission owns RTS - adopted here or started concurrently - and false
+ * when the line is really idle.
+ */
+static bool max310x_adopt_hw_tx(struct max310x_one *one)
+{
+	struct uart_port *port = &one->port;
+
+	if (!max310x_port_read(port, MAX310X_TXFIFOLVL_REG) &&
+	    kfifo_is_empty(&port->state->port.xmit_fifo))
+		return false;
+
+	scoped_guard(spinlock_irqsave, &port->lock) {
+		if (one->tx_teardown)
+			return false;
+		if (READ_ONCE(one->tx_state) != MAX310X_TX_OFF)
+			return true;
+		WRITE_ONCE(one->tx_state, MAX310X_TX_SEND);
+		one->cancel_tx_delay_tmr = false;
+	}
+
+	return true;
+}
+
+/*
+ * Pick hardware or software RTS timing for the current port. The chip can
+ * deliver up to 15 bit-times of setup/hold delay via HDPIXDELAY; anything
+ * longer (or any RTS polarity the chip cannot produce automatically) must
+ * be driven by software via tx_delay_tmr and rts_work.
  */
 static void max310x_set_rts_ctl_params(struct max310x_one *one)
 {
@@ -925,25 +1133,35 @@ static void max310x_set_rts_ctl_params(s
 	struct uart_port *port = &one->port;
 	unsigned int setup = 0, hold = 0;
 	u8 mode1 = 0, irda = 0;
+	bool sw_rts = false;
 
-	if (port->rs485.flags & SER_RS485_ENABLED) {
-		/* Convert milliseconds to bit-times, rounding up. */
-		setup = DIV_ROUND_UP(one->baud * port->rs485.delay_rts_before_send,
-				     MSEC_PER_SEC);
-		hold  = DIV_ROUND_UP(one->baud * port->rs485.delay_rts_after_send,
-				     MSEC_PER_SEC);
-		setup = min(setup, max_bit_dly);
-		hold  = min(hold,  max_bit_dly);
+	if (!(port->rs485.flags & SER_RS485_ENABLED))
+		goto out;
 
-		mode1 = MAX310X_MODE1_TRNSCVCTRL_BIT;
-		/*
-		 * The auto-RTS engine asserts RTS high on send; for an
-		 * active-low RTS let IRDA.RTSINVERT invert the output stage.
-		 */
-		if (!(port->rs485.flags & SER_RS485_RTS_ON_SEND))
-			irda = MAX310X_IRDA_RTSINVERT_BIT;
+	/* Convert milliseconds to bit-times, rounding up. */
+	setup = DIV_ROUND_UP(one->baud * port->rs485.delay_rts_before_send,
+			     MSEC_PER_SEC);
+	hold  = DIV_ROUND_UP(one->baud * port->rs485.delay_rts_after_send,
+			     MSEC_PER_SEC);
+
+	/*
+	 * Compare in bit-times: a delay of exactly max_bit_dly bit-times
+	 * must stay on the hardware path, which a nanosecond ceiling
+	 * computed from the truncated per-bit time would reject. Without
+	 * a baud rate the conversion is meaningless - use software.
+	 */
+	if (!one->baud || setup > max_bit_dly || hold > max_bit_dly ||
+	    !!(port->rs485.flags & SER_RS485_RTS_ON_SEND) ==
+	    !!(port->rs485.flags & SER_RS485_RTS_AFTER_SEND)) {
+		sw_rts = true;
+		setup = 0;
+		hold  = 0;
 	}
 
+out:
+	/* Assign once; a transient false would be seen by other readers. */
+	WRITE_ONCE(one->sw_rts_during_tx, sw_rts);
+
 	max310x_port_write(port, MAX310X_HDPIXDELAY_REG,
 			   MAX310X_HDPIXDELAY_SETUP(setup) |
 			   MAX310X_HDPIXDELAY_HOLD(hold));
@@ -951,12 +1169,66 @@ static void max310x_set_rts_ctl_params(s
 	/*
 	 * A break owns the transceiver: break_ctl() disabled auto-RTS and
 	 * drives RTS manually, and restores it from the current
-	 * configuration when the break ends. Touching MODE1 here would
+	 * configuration when the break ends. Touching them here would
 	 * release the transceiver mid-break.
 	 */
 	if (one->tx_break)
 		return;
 
+	if (port->rs485.flags & SER_RS485_ENABLED) {
+		if (sw_rts) {
+			/*
+			 * Only settle RTS at idle when no transmission owns it.
+			 * A reconfigure while one is in flight - rs_work runs
+			 * on every TIOCSRS485 - would otherwise release the
+			 * transceiver mid-character. A transfer the hardware
+			 * path owns is invisible to tx_state - adopt it
+			 * instead of settling. The reverse strand also
+			 * exists: an envelope the hardware path inherited
+			 * mid-envelope leaves tx_state set with nothing
+			 * driving the pin.
+			 */
+			if (READ_ONCE(one->tx_state) != MAX310X_TX_OFF ||
+			    max310x_adopt_hw_tx(one)) {
+				/*
+				 * The transfer may be running under auto-RTS:
+				 * assert before auto-RTS is disabled below so
+				 * the pin is never released under it, and arm
+				 * the after-send hold - with the chip FIFO
+				 * already drained no TX-empty interrupt
+				 * arrives to arm it.
+				 */
+				max310x_rts_ctl(port,
+						max310x_rts_level(port, true));
+				max310x_delayed_stop_tx(port);
+			} else {
+				max310x_rts_ctl(port,
+						max310x_rts_level(port, false));
+				/*
+				 * serial_core calls set_termios() without
+				 * port->lock, so an envelope may have started
+				 * while the idle level was written and the
+				 * settle can land after its RTS assert.
+				 * rts_work re-derives the level from
+				 * tx_state; requeue it to converge.
+				 */
+				if (READ_ONCE(one->tx_state) != MAX310X_TX_OFF)
+					schedule_work(&one->rts_work);
+			}
+		} else {
+			mode1 = MAX310X_MODE1_TRNSCVCTRL_BIT;
+			/*
+			 * The auto-RTS engine asserts RTS high on send; for an
+			 * active-low RTS let IRDA.RTSINVERT invert the output
+			 * stage.
+			 */
+			if (!(port->rs485.flags & SER_RS485_RTS_ON_SEND))
+				irda = MAX310X_IRDA_RTSINVERT_BIT;
+		}
+	} else {
+		max310x_rts_ctl(port, 0);
+	}
+
 	max310x_port_update(port, MAX310X_MODE1_REG,
 			    MAX310X_MODE1_TRNSCVCTRL_BIT, mode1);
 	max310x_port_update(port, MAX310X_IRDA_REG,
@@ -984,12 +1256,27 @@ static void max310x_break_ctl(struct uar
 	if (break_state) {
 		if (!(port->rs485.flags & SER_RS485_ENABLED))
 			return;
-		max310x_port_update(port, MAX310X_MODE1_REG,
-				    MAX310X_MODE1_TRNSCVCTRL_BIT, 0);
+		if (READ_ONCE(one->sw_rts_during_tx)) {
+			max310x_rts_ctl(port, max310x_rts_level(port, 1));
+		} else {
+			max310x_port_update(port, MAX310X_MODE1_REG,
+					    MAX310X_MODE1_TRNSCVCTRL_BIT, 0);
+			max310x_rts_ctl(port, 1);
+		}
 	} else {
+		/*
+		 * Reapply the current configuration: a reconfigure that
+		 * arrived during the break was deferred by the tx_break
+		 * guard, and RS485 may have been disabled outright - the
+		 * manually driven RTS must not leak past the break. On the
+		 * software path the helper also settles the idle level; on
+		 * the hardware path release the manual RTS - auto-RTS owns
+		 * the pin again.
+		 */
 		max310x_set_rts_ctl_params(one);
+		if (!READ_ONCE(one->sw_rts_during_tx))
+			max310x_rts_ctl(port, 0);
 	}
-	max310x_rts_ctl(port, break_state);
 }
 
 static void max310x_set_termios(struct uart_port *port,
@@ -1031,9 +1318,10 @@ static void max310x_set_termios(struct u
 		lcr |= MAX310X_LCR_STOPLEN_BIT; /* 2 stops */
 
 	/*
-	 * Update LCR register. Leave the TX break bit alone: it is driven by
-	 * break_ctl(), and a whole-register write here would end a break in
-	 * progress.
+	 * Update LCR register. Leave the TX break and RTS bits alone: they are
+	 * driven by break_ctl() and by the software-timed RS485 RTS, and a
+	 * whole-register write here would end a break in progress or release
+	 * the transceiver mid-character.
 	 */
 	max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_TERMIOS_MASK, lcr);
 
@@ -1111,7 +1399,9 @@ static void max310x_set_termios(struct u
 	/*
 	 * Cache the new baud rate and the time it takes to clock out one
 	 * character before reprogramming the RS485 RTS delays: the
-	 * millisecond-to-bit-time conversion divides by the baud rate.
+	 * millisecond-to-bit-time conversion divides by the baud rate, and
+	 * taking over an in-flight transfer arms the after-send hold from
+	 * the character time.
 	 */
 	to_max310x_port(port)->baud = baud;
 	to_max310x_port(port)->char_time_us =
@@ -1131,6 +1421,10 @@ static void max310x_rs_proc(struct work_
 	 */
 	guard(mutex)(&one->port.state->port.mutex);
 
+	/* Flush an rts_work that read tx_state before the disable cleared it. */
+	if (!(one->port.rs485.flags & SER_RS485_ENABLED))
+		cancel_work_sync(&one->rts_work);
+
 	max310x_set_rts_ctl_params(one);
 
 	if (one->port.rs485.flags & SER_RS485_ENABLED &&
@@ -1141,14 +1435,37 @@ static void max310x_rs_proc(struct work_
 			    MAX310X_MODE2_ECHOSUPR_BIT, mode2);
 }
 
+/* called with port.lock taken and irqs off */
 static int max310x_rs485_config(struct uart_port *port, struct ktermios *termios,
 				struct serial_rs485 *rs485)
 {
 	struct max310x_one *one = to_max310x_port(port);
 
-	if ((rs485->delay_rts_before_send > 0x0f) ||
-	    (rs485->delay_rts_after_send > 0x0f))
-		return -ERANGE;
+	rs485->delay_rts_before_send = min(rs485->delay_rts_before_send, 100U);
+	rs485->delay_rts_after_send  = min(rs485->delay_rts_after_send,  100U);
+
+	/*
+	 * Make sure no SW-timed RTS toggle survives an RS485 disable, even
+	 * if the delay timer happens to be running right now.
+	 */
+	if (!(rs485->flags & SER_RS485_ENABLED)) {
+		one->tx_teardown = true;
+		one->cancel_tx_delay_tmr = true;
+		if (hrtimer_try_to_cancel(&one->tx_delay_tmr) == -1) {
+			uart_port_unlock(port);
+			hrtimer_cancel(&one->tx_delay_tmr);
+			uart_port_lock(port);
+		}
+		WRITE_ONCE(one->tx_state, MAX310X_TX_OFF);
+		one->tx_teardown = false;
+		/*
+		 * The port stays alive, and a write that raced the teardown
+		 * may have left data queued with no envelope left to pump it.
+		 * Kick tx_work; RS485 is disabled, so the plain path is right.
+		 */
+		if (!kfifo_is_empty(&port->state->port.xmit_fifo))
+			schedule_work(&one->tx_work);
+	}
 
 	port->rs485 = *rs485;
 
@@ -1183,7 +1500,15 @@ static int max310x_startup(struct uart_p
 	max310x_port_update(port, MAX310X_MODE2_REG,
 			    MAX310X_MODE2_FIFORST_BIT, 0);
 
-	/* Configure the RS485 RTS timing and the RS485/RS232 mode bits. */
+	one->tx_teardown = false;
+
+	/*
+	 * Configure the RS485 RTS timing (HW auto-RTS vs software-driven) and
+	 * the RS485/RS232 mode bits. Don't hardcode HW auto-RTS here - let
+	 * max310x_set_rts_ctl_params() pick HW or SW per the configured
+	 * delays, otherwise the chip's auto-RTS would override the software
+	 * RTS hold and the after-send delay is lost.
+	 */
 	max310x_set_rts_ctl_params(one);
 
 	if (port->rs485.flags & SER_RS485_ENABLED &&
@@ -1214,7 +1539,15 @@ static void max310x_shutdown(struct uart
 {
 	struct max310x_one *one = to_max310x_port(port);
 
-	/* Disable all interrupts */
+	/*
+	 * Gate new transmissions and interrupts first: a concurrent
+	 * start_tx() either sees the interlock or happens-before it, and
+	 * nothing below may start a new envelope. The timer and the works
+	 * stay live for now - they are what completes a running after-send
+	 * hold.
+	 */
+	scoped_guard(spinlock_irqsave, &port->lock)
+		one->tx_teardown = true;
 	max310x_port_write(port, MAX310X_IRQEN_REG, 0);
 
 	/*
@@ -1224,25 +1557,69 @@ static void max310x_shutdown(struct uart
 	max310x_port_update(port, MAX310X_MODE1_REG,
 			    MAX310X_MODE1_TXDIS_BIT, MAX310X_MODE1_TXDIS_BIT);
 
+	if (READ_ONCE(one->sw_rts_during_tx)) {
+		/*
+		 * Honour a running after-send hold before the port is
+		 * powered down. The bound covers the final character -
+		 * tx_empty() cannot see the transmit shift register - plus
+		 * the hold itself. Data beyond that is abandoned: it is
+		 * only still queued when the tty layer was told not to
+		 * wait, and the release below drives RTS to idle
+		 * regardless.
+		 */
+		unsigned int tries = port->rs485.delay_rts_after_send +
+			2 * DIV_ROUND_UP(one->char_time_us, USEC_PER_MSEC);
+
+		while (READ_ONCE(one->tx_state) != MAX310X_TX_OFF && tries-- > 0)
+			fsleep(USEC_PER_MSEC);
+	} else {
+		/*
+		 * Let the character in flight finish (the chip has no
+		 * transmitter-idle status), then empty the FIFO: auto-RTS
+		 * releases only once the transmitter is empty, and the
+		 * power-off below would freeze an asserted pin until the
+		 * next open. The hold is at most 15 bit-times.
+		 */
+		fsleep(one->char_time_us);
+		max310x_port_update(port, MAX310X_MODE2_REG,
+				    MAX310X_MODE2_FIFORST_BIT,
+				    MAX310X_MODE2_FIFORST_BIT);
+		max310x_port_update(port, MAX310X_MODE2_REG,
+				    MAX310X_MODE2_FIFORST_BIT, 0);
+		if (port->rs485.flags & SER_RS485_ENABLED && one->baud) {
+			unsigned int hold = DIV_ROUND_UP(one->baud *
+					port->rs485.delay_rts_after_send,
+					MSEC_PER_SEC);
+
+			fsleep(max(DIV_ROUND_UP((hold + 1) * USEC_PER_SEC,
+						one->baud), 100U));
+		}
+	}
+
 	/*
-	 * Let the character in flight finish (the chip has no
-	 * transmitter-idle status), then empty the FIFO: auto-RTS releases
-	 * only once the transmitter is empty, and the power-off below
-	 * would freeze an asserted pin until the next open.
+	 * The wind-down is over: cancel unconditionally. The SW/HW decision
+	 * is recomputed on every reconfigure, so a TIOCSRS485 can clear
+	 * sw_rts_during_tx while an envelope is still in flight, and
+	 * neither the timer nor the works may outlive the port.
 	 */
-	fsleep(one->char_time_us);
-	max310x_port_update(port, MAX310X_MODE2_REG,
-			    MAX310X_MODE2_FIFORST_BIT,
-			    MAX310X_MODE2_FIFORST_BIT);
-	max310x_port_update(port, MAX310X_MODE2_REG,
-			    MAX310X_MODE2_FIFORST_BIT, 0);
-	if (port->rs485.flags & SER_RS485_ENABLED && one->baud) {
-		unsigned int hold = DIV_ROUND_UP(one->baud *
-				port->rs485.delay_rts_after_send,
-				MSEC_PER_SEC);
+	scoped_guard(spinlock_irqsave, &port->lock)
+		one->cancel_tx_delay_tmr = true;
+	cancel_work_sync(&one->tx_work);
+	hrtimer_cancel(&one->tx_delay_tmr);
+	cancel_work_sync(&one->rts_work);
+	WRITE_ONCE(one->tx_state, MAX310X_TX_OFF);
 
-		fsleep(max(DIV_ROUND_UP((hold + 1) * USEC_PER_SEC,
-					one->baud), 100U));
+	if (READ_ONCE(one->sw_rts_during_tx)) {
+		max310x_rts_ctl(port, max310x_rts_level(port, false));
+		/*
+		 * The power-off below stops the UART clock that moves the
+		 * RTS pin: released too late, the write reaches the register
+		 * but the pin stays at its old level until the next startup
+		 * restarts the clock. Give the release one bit time (at
+		 * least 100 us) to reach the pin - the measured propagation
+		 * is about one tick of the 16x oversampling clock.
+		 */
+		fsleep(max(one->char_time_us / 10, 100U));
 	}
 
 	max310x_power(port, 0);
@@ -1551,6 +1928,11 @@ static int max310x_probe(struct device *
 		INIT_WORK(&s->p[i].md_work, max310x_md_proc);
 		/* Initialize queue for changing RS485 mode */
 		INIT_WORK(&s->p[i].rs_work, max310x_rs_proc);
+		/* Initialize queue for software-driven RTS toggling */
+		INIT_WORK(&s->p[i].rts_work, max310x_rts_work_proc);
+		hrtimer_setup(&s->p[i].tx_delay_tmr, max310x_tmr_tx,
+			      CLOCK_MONOTONIC, HRTIMER_MODE_REL);
+		s->p[i].tx_state = MAX310X_TX_OFF;
 	}
 
 #ifdef CONFIG_GPIOLIB
@@ -1625,6 +2007,8 @@ static void max310x_remove(struct device
 	int i;
 
 	for (i = 0; i < s->devtype->nr; i++) {
+		hrtimer_cancel(&s->p[i].tx_delay_tmr);
+		cancel_work_sync(&s->p[i].rts_work);
 		cancel_work_sync(&s->p[i].tx_work);
 		cancel_work_sync(&s->p[i].md_work);
 		cancel_work_sync(&s->p[i].rs_work);
author maintainer
#1411 lore raw

PATCH 1409/2151 serial: max310x: dont transmit while an RS485 reconfigure is pending

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

[ Upstream commit ae588038e31c9dbd6836cb12bbdd82af0271c373 ]

TIOCSRS485 applies its register changes asynchronously: rs485_config() stores the new configuration and schedules rs_work, which programs HDPIXDELAY, MODE1.TRNSCVCTRL and the RTS path. A write() issued right after the ioctl therefore transmits against the old, half-switched state. On a single core the ordering is even deterministic: start_tx() picks the stale path first, then rs_work reprograms the chip, then tx_work pumps the data - with the transceiver already released. A TIOCSRS485 switching from the hardware to the software RTS path followed immediately by a write puts the whole transfer on the wire with the transceiver disabled: nothing reaches the bus and no error is reported anywhere. The inverse direction is as old as the asynchronous reconfigure itself: enabling RS485 and writing immediately shifts the first bytes out before rs_work has enabled the chip's auto-RTS.

Defer instead: rs485_config() marks the reconfigure pending under port->lock, start_tx() leaves the data in the kfifo while the mark is set, and rs_work restarts the transmission itself once the new configuration is fully applied. The rs485-disable path's direct tx_work kick is replaced by the same mechanism, which also orders that flush after the reconfigure instead of before it.

The restart kick also checks port->x_char: uart_send_xchar() reaches start_tx() too, and a lone x_char deferred by the pending gate leaves the kfifo empty, so the kick would otherwise skip it and nothing else would ever send it - an idle chip FIFO raises no TXEMPTY interrupt. And start_tx() re-checks the pending mark after the hrtimer_try_to_cancel(-1) path retakes the dropped lock, mirroring the tx_teardown re-check there: a TIOCSRS485 posted inside that window would otherwise let the transmission proceed on the stale path.

rs_work takes port->lock for that restart through uart_port_lock_irqsave(): start_tx() may drop and retake the lock through the uart_port API on its hrtimer_try_to_cancel(-1) path, and a raw spinlock guard around the call would unbalance the nbcon console handling underneath.

The restart also rewinds a send state adopted for the deferred write
itself: set_rts_ctl_params() cannot tell data the pending gate deferred apart from an in-flight transfer's refill by the xmit buffer alone, and a deferred write pumped in the adopted send phase would skip the configured before-send delay. With the chip FIFO empty the adopted state can only be the deferred write: rewind it and let the restart run the full envelope.

The chip-FIFO check for that rewind is deliberately lock-free, so a TX-empty refill can land between the read and the lock and the rewind can hit a live envelope. The consequence is bounded: the rewind runs under port->lock in a state the RTS worker reads as asserted, so the envelope pauses one before-send delay with the transceiver held - the same pause the unconditional rewind produced before patch 8's guard.

Fixes 5bdb48b501e8 ("serial: max310x: Fix RS485 handling")
Assisted-by Claude:claude-fable-5
---
 drivers/tty/serial/max310x.c |   51 +++++++++++++++++++++++++++++++++++--------
 1 file changed, 42 insertions(+), 9 deletions(-)
drivers/tty/serial/max310x.c +42 -9
@@ -306,6 +306,7 @@ struct max310x_one {
 	bool			sw_rts_during_tx;
 	bool			cancel_tx_delay_tmr;
 	bool			tx_teardown;	/* envelope being torn down */
+	bool			rs485_pending;	/* rs_work not yet applied */
 	bool			tx_break;	/* break_ctl() owns the transceiver */
 	enum max310x_tx_state	tx_state;
 
@@ -947,6 +948,16 @@ static void max310x_start_tx(struct uart
 	if (one->tx_teardown)
 		return;
 
+	/*
+	 * An RS485 reconfigure is scheduled but not applied yet: transmitting
+	 * now would use the old path against half-programmed registers - a
+	 * TIOCSRS485 switching paths followed immediately by a write puts the
+	 * data on the wire with the transceiver released. Leave the data in
+	 * the kfifo; rs_work restarts TX once the configuration is applied.
+	 */
+	if (one->rs485_pending)
+		return;
+
 	if (READ_ONCE(one->sw_rts_during_tx)) {
 		/*
 		 * The before- and after-send phases share one delay timer. If an
@@ -965,9 +976,10 @@ static void max310x_start_tx(struct uart
 			uart_port_lock(port);
 			/*
 			 * The lock was dropped: a teardown may have run to
-			 * completion meanwhile. Re-check before starting.
+			 * completion or a reconfigure may have been posted
+			 * meanwhile. Re-check before starting.
 			 */
-			if (one->tx_teardown)
+			if (one->tx_teardown || one->rs485_pending)
 				return;
 		}
 
@@ -1413,6 +1425,8 @@ static void max310x_rs_proc(struct work_
 {
 	struct max310x_one *one = container_of(ws, struct max310x_one, rs_work);
 	unsigned int mode2 = 0;
+	unsigned long flags;
+	bool chip_tx_empty;
 
 	/*
 	 * Serialize against break_ctl() and set_termios(), which run under
@@ -1433,6 +1447,31 @@ static void max310x_rs_proc(struct work_
 
 	max310x_port_update(&one->port, MAX310X_MODE2_REG,
 			    MAX310X_MODE2_ECHOSUPR_BIT, mode2);
+
+	/*
+	 * The configuration is applied: release any TX that start_tx()
+	 * deferred while the reconfigure was pending, now on the right
+	 * path. start_tx() can drop and retake the lock through the
+	 * uart_port API - a raw spinlock guard here would unbalance it.
+	 */
+	chip_tx_empty = !max310x_port_read(&one->port,
+					   MAX310X_TXFIFOLVL_REG);
+
+	uart_port_lock_irqsave(&one->port, &flags);
+	one->rs485_pending = false;
+	if (one->port.x_char ||
+	    !kfifo_is_empty(&one->port.state->port.xmit_fifo)) {
+		/*
+		 * A send state adopted without chip data is the deferred
+		 * write itself: restart it as a fresh envelope so the
+		 * before-send delay is honoured.
+		 */
+		if (chip_tx_empty &&
+		    READ_ONCE(one->tx_state) == MAX310X_TX_SEND)
+			WRITE_ONCE(one->tx_state, MAX310X_TX_OFF);
+		max310x_start_tx(&one->port);
+	}
+	uart_port_unlock_irqrestore(&one->port, flags);
 }
 
 /* called with port.lock taken and irqs off */
@@ -1458,17 +1497,11 @@ static int max310x_rs485_config(struct u
 		}
 		WRITE_ONCE(one->tx_state, MAX310X_TX_OFF);
 		one->tx_teardown = false;
-		/*
-		 * The port stays alive, and a write that raced the teardown
-		 * may have left data queued with no envelope left to pump it.
-		 * Kick tx_work; RS485 is disabled, so the plain path is right.
-		 */
-		if (!kfifo_is_empty(&port->state->port.xmit_fifo))
-			schedule_work(&one->tx_work);
 	}
 
 	port->rs485 = *rs485;
 
+	one->rs485_pending = true;
 	schedule_work(&one->rs_work);
 
 	return 0;
author maintainer
#1412 lore raw

PATCH 1410/2151 ntfs: Do not kmap pages used for reading from disk

In reply to Greg Kroah-Hartman

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

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

From: Matthew Wilcox (Oracle) <[email protected]>

[ Upstream commit 14656154d26cf244d063477a03606775eec19780 ]

These pages are accessed through DMA and vmap; they are not accessed by calling page_address(), so they do not need to be kmapped.

Stable-dep-of: 80218408836f ("fs/ntfs3: do not mark frame pages uptodate on read error")

---
 fs/ntfs3/frecord.c | 4 ----
 1 file changed, 4 deletions(-)
fs/ntfs3/frecord.c +0 -4
index 81b536a268633..af3a49283e6e7 100644
@@ -2627,7 +2627,6 @@ int ni_read_frame(struct ntfs_inode *ni, u64 frame_vbo, struct page **pages,
 		}
 		pages_disk[i] = pg;
 		lock_page(pg);
-		kmap(pg);
 	}
 
 	/* Read 'ondisk_size' bytes from disk. */
@@ -2686,7 +2685,6 @@ int ni_read_frame(struct ntfs_inode *ni, u64 frame_vbo, struct page **pages,
 	for (i = 0; i < npages_disk; i++) {
 		pg = pages_disk[i];
 		if (pg) {
-			kunmap(pg);
 			unlock_page(pg);
 			put_page(pg);
 		}
@@ -2782,7 +2780,6 @@ int ni_write_frame(struct ntfs_inode *ni, struct page **pages,
 		}
 		pages_disk[i] = pg;
 		lock_page(pg);
-		kmap(pg);
 	}
 
 	/* To simplify compress algorithm do vmap for source and target pages. */
@@ -2863,7 +2860,6 @@ int ni_write_frame(struct ntfs_inode *ni, struct page **pages,
 	for (i = 0; i < pages_per_frame; i++) {
 		pg = pages_disk[i];
 		if (pg) {
-			kunmap(pg);
 			unlock_page(pg);
 			put_page(pg);
 		}
Signature · 1 line
2.53.0
author maintainer
#1413 lore raw

PATCH 1411/2151 fs/ntfs3: remove ntfs_bio_pages and use page cache for compressed I/O

In reply to Greg Kroah-Hartman

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

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

From: Konstantin Komarov <[email protected]>

[ Upstream commit f35590ee26f5722bfe12cdff14396c4c057a8f74 ]

Replace the use of ntfs_bio_pages with the disk page cache for reading and writing compressed files. This slightly improves performance when reading compressed data and simplifies the I/O logic.

When an XPRESS or LZX compressed file is opened for writing, it is now decompressed into a normal file before modification. A new argument (int copy) is added to ni_read_frame() to handle writing of decompressed and mapped data.

Stable-dep-of: 80218408836f ("fs/ntfs3: do not mark frame pages uptodate on read error")

---
 fs/ntfs3/attrib.c  |   4 +-
 fs/ntfs3/file.c    |   6 +-
 fs/ntfs3/frecord.c | 152 ++++++++++++---------------------------------
 fs/ntfs3/fsntfs.c  | 123 ++++++++++++++++--------------------
 fs/ntfs3/inode.c   |   1 -
 fs/ntfs3/ntfs_fs.h |  20 ++++--
 6 files changed, 114 insertions(+), 192 deletions(-)
fs/ntfs3/attrib.c +1 -3
index 1feef22cc67e3..fc46e936bdbbb 100644
@@ -1482,7 +1482,6 @@ int attr_wof_frame_info(struct ntfs_inode *ni, struct ATTRIB *attr,
 		pgoff_t index = vbo[i] >> PAGE_SHIFT;
 
 		if (index != folio->index) {
-			struct page *page = &folio->page;
 			u64 from = vbo[i] & ~(u64)(PAGE_SIZE - 1);
 			u64 to = min(from + PAGE_SIZE, wof_size);
 
@@ -1492,8 +1491,7 @@ int attr_wof_frame_info(struct ntfs_inode *ni, struct ATTRIB *attr,
 			if (err)
 				goto out1;
 
-			err = ntfs_bio_pages(sbi, run, &page, 1, from,
-					     to - from, REQ_OP_READ);
+			err = ntfs_read_run(sbi, run, addr, from, to - from);
 			if (err) {
 				folio->index = -1;
 				goto out1;
fs/ntfs3/file.c +3 -3
index d5cd8fe6dd868..5ff7d86aad5fd 100644
@@ -59,7 +59,7 @@ static int ntfs_ioctl_get_volume_label(struct ntfs_sb_info *sbi, u8 __user *buf)
 
 static int ntfs_ioctl_set_volume_label(struct ntfs_sb_info *sbi, u8 __user *buf)
 {
-	u8 user[FSLABEL_MAX] = {0};
+	u8 user[FSLABEL_MAX] = { 0 };
 	int len;
 
 	if (!capable(CAP_SYS_ADMIN))
@@ -1029,7 +1029,7 @@ static ssize_t ntfs_compress_write(struct kiocb *iocb, struct iov_iter *from)
 
 		if (!frame_uptodate && off) {
 			err = ni_read_frame(ni, frame_vbo, pages,
-					    pages_per_frame);
+					    pages_per_frame, 0);
 			if (err) {
 				for (ip = 0; ip < pages_per_frame; ip++) {
 					folio = page_folio(pages[ip]);
@@ -1094,7 +1094,7 @@ static ssize_t ntfs_compress_write(struct kiocb *iocb, struct iov_iter *from)
 
 			if (off || (to < i_size && (to & (frame_size - 1)))) {
 				err = ni_read_frame(ni, frame_vbo, pages,
-						    pages_per_frame);
+						    pages_per_frame, 0);
 				if (err) {
 					for (ip = 0; ip < pages_per_frame;
 					     ip++) {
fs/ntfs3/frecord.c +39 -113

285 lines not on this page · raw message

fs/ntfs3/fsntfs.c +55 -68

154 lines not on this page · raw message

fs/ntfs3/inode.c +0 -1
index bad5d16fed2c1..07a1a925b5286 100644
@@ -2128,7 +2128,6 @@ const struct address_space_operations ntfs_aops = {
 
 const struct address_space_operations ntfs_aops_cmpr = {
 	.read_folio	= ntfs_read_folio,
-	.readahead	= ntfs_readahead,
 	.dirty_folio	= block_dirty_folio,
 	.direct_IO	= ntfs_direct_IO,
 };
fs/ntfs3/ntfs_fs.h +16 -4
index f7ca4ea54e40a..1c31b1c728378 100644
@@ -574,7 +574,7 @@ int ni_fiemap(struct ntfs_inode *ni, struct fiemap_extent_info *fieinfo,
 int ni_read_folio_cmpr(struct ntfs_inode *ni, struct folio *folio);
 int ni_decompress_file(struct ntfs_inode *ni);
 int ni_read_frame(struct ntfs_inode *ni, u64 frame_vbo, struct page **pages,
-		  u32 pages_per_frame);
+		  u32 pages_per_frame, int copy);
 int ni_write_frame(struct ntfs_inode *ni, struct page **pages,
 		   u32 pages_per_frame);
 int ni_remove_name(struct ntfs_inode *dir_ni, struct ntfs_inode *ni,
@@ -638,9 +638,21 @@ int ntfs_get_bh(struct ntfs_sb_info *sbi, const struct runs_tree *run, u64 vbo,
 		u32 bytes, struct ntfs_buffers *nb);
 int ntfs_write_bh(struct ntfs_sb_info *sbi, struct NTFS_RECORD_HEADER *rhdr,
 		  struct ntfs_buffers *nb, int sync);
-int ntfs_bio_pages(struct ntfs_sb_info *sbi, const struct runs_tree *run,
-		   struct page **pages, u32 nr_pages, u64 vbo, u32 bytes,
-		   enum req_op op);
+int ntfs_read_write_run(struct ntfs_sb_info *sbi, const struct runs_tree *run,
+			void *buf, u64 vbo, size_t bytes, int wr);
+static inline int ntfs_read_run(struct ntfs_sb_info *sbi,
+				const struct runs_tree *run, void *buf, u64 vbo,
+				size_t bytes)
+{
+	return ntfs_read_write_run(sbi, run, buf, vbo, bytes, 0);
+}
+static inline int ntfs_write_run(struct ntfs_sb_info *sbi,
+				 const struct runs_tree *run, void *buf,
+				 u64 vbo, size_t bytes)
+{
+	return ntfs_read_write_run(sbi, run, buf, vbo, bytes, 1);
+}
+
 int ntfs_bio_fill_1(struct ntfs_sb_info *sbi, const struct runs_tree *run);
 int ntfs_vbo_to_lbo(struct ntfs_sb_info *sbi, const struct runs_tree *run,
 		    u64 vbo, u64 *lbo, u64 *bytes);
Signature · 1 line
2.53.0
author maintainer
#1414 lore raw

PATCH 1412/2151 fs/ntfs3: do not mark frame pages uptodate on read error

In reply to Greg Kroah-Hartman

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

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

From: Weiming Shi <[email protected]>

[ Upstream commit 80218408836fa6fc91a9c26a9c014f81abf9e41f ]

ni_read_frame() ends with a loop that marks every page of a compressed frame uptodate regardless of whether the read succeeded:

	out:
		for (i = 0; i < pages_per_frame; i++) {
			pg = pages[i];
			SetPageUptodate(pg);
		}

Non-critical frame pages come from __filemap_get_folio(FGP_CREAT) and are not zeroed. On an error path that reaches out: before frame_mem is written, these pages keep uninitialized page-allocator contents but are still marked uptodate. A later read() is then served from the page cache and returns that stale kernel memory to user space.

For an unprivileged user mounting a crafted NTFS image this is a repeatable kernel memory disclosure.

Mark the pages uptodate only on success; on error leave them !uptodate so the read path re-reads them or reports the error.

Fixes 4342306f0f0d ("fs/ntfs3: Add file operations and implementation")
---
 fs/ntfs3/frecord.c | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
fs/ntfs3/frecord.c +4 -6
index 923b909351e96..397c120876234 100644
@@ -2422,7 +2422,6 @@ int ni_read_frame(struct ntfs_inode *ni, u64 frame_vbo, struct page **pages,
 	u64 vbo_disk;
 	size_t unc_size;
 	u32 frame_size, i, ondisk_size;
-	struct page *pg;
 	struct ATTRIB *attr;
 	CLST frame, clst_data;
 
@@ -2653,11 +2652,10 @@ int ni_read_frame(struct ntfs_inode *ni, u64 frame_vbo, struct page **pages,
 #endif
 	vunmap(frame_mem);
 out:
-	for (i = 0; i < pages_per_frame; i++) {
-		pg = pages[i];
-		if (err)
-			clear_highpage(pg);
-		SetPageUptodate(pg);
+	if (!err) {
+		for (i = 0; i < pages_per_frame; i++) {
+			SetPageUptodate(pages[i]);
+		}
 	}
 
 	return err;
Signature · 1 line
2.53.0
author maintainer
#1415 lore raw

PATCH 1413/2151 net: alacritech: fix dma_free_coherent() in error path

In reply to Greg Kroah-Hartman

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

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

From: Thomas Fourier <[email protected]>

[ Upstream commit 05b5019b01fb9443b09ae4ed34af1135a80a84c8 ]

In slic_init_stat_queue(), a series of coherent buffers is allocated with the length size. The size is then stored in stq->mem_size for normal deallocation. However, in the error path, stq->mem_size is also used but is not initialized. This error may leave the freed buffers mapped, leaking a resource and allowing the device to access freed memory.

Change the length in error path to size.

Fixes 60c140df15db ("net: ethernet: slicoss: add slicoss gigabit ethernet driver")
---
 drivers/net/ethernet/alacritech/slicoss.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/alacritech/slicoss.c +1 -1
index f62851708d4f3..4b4f44a5c6cc0 100644
@@ -813,7 +813,7 @@ static int slic_init_stat_queue(struct slic_device *sdev)
 
 free_descs:
 	while (i--) {
-		dma_free_coherent(&sdev->pdev->dev, stq->mem_size,
+		dma_free_coherent(&sdev->pdev->dev, size,
 				  stq->descs[i] - stq->addr_offset[i],
 				  stq->paddr[i] - stq->addr_offset[i]);
 	}
Signature · 1 line
2.53.0
author maintainer
#1416 lore raw

PATCH 1414/2151 comedi: comedi_parport: validate the IRQ supplied by userspace

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit 790ea6844593bcd03b0379986fc821d8c511746e ]

comedi boards are configured through the COMEDI_DEVCONFIG ioctl, so it->options[1] is a number chosen by userspace. comedi_parport passes it to request_irq() without checking it first, which lets an interrupt owned by another irqdomain -- a PCI device's IO-APIC GSI, for instance -- be claimed for this board. When the owner of that interrupt is later released the descriptor is freed while this driver's handler is still installed on it.

A parallel port asserts a legacy ISA interrupt, so the ISA range is the right bound; it is also sufficient, because mp_chip_data->isa_irq is set only by alloc_isa_irq_from_domain() and mp_unmap_irq() returns early when it is set.

syzbot hit this one:

	remove_proc_entry: removing non-empty directory 'irq/20', leaking at least 'comedi_parport'
	WARNING: fs/proc/generic.c:747 at remove_proc_entry+0x4e7/0x610 fs/proc/generic.c:747
	Call Trace:
	 <TASK>
	 unregister_irq_proc+0x206/0x2a0 kernel/irq/proc.c:406
	 free_desc+0x89/0x330 kernel/irq/irqdesc.c:482
	 irq_free_descs+0x84/0xc0 kernel/irq/irqdesc.c:865
	 irq_domain_free_irqs+0x46a/0x5c0 kernel/irq/irqdomain.c:1917
	 mp_unmap_irq+0xf8/0x130 arch/x86/kernel/apic/io_apic.c:1061
	 acpi_unregister_gsi_ioapic+0x40/0x60 arch/x86/kernel/acpi/boot.c:722
	 acpi_pci_irq_disable+0x275/0x360 drivers/acpi/pci_irq.c:517
	 pci_disable_device+0x130/0x270 drivers/pci/pci.c:2206
	 pci_device_remove+0xb2/0x1d0 drivers/pci/pci-driver.c:512
	 device_release_driver_internal+0x44e/0x620 drivers/base/dd.c:1372
	 unbind_store+0xf8/0x110 drivers/base/bus.c:244
	 </TASK>

The leaked /proc entry the warning names is the mild part. mp_chip_data->count tracks GSI mappings rather than request_irq() users, and __setup_irq() takes no reference on the descriptor, so the irq_desc is freed with the comedi irqaction still attached to it.

Bound the value before requesting it, as das16m1.c already does. An out-of-range value is ignored rather than rejected, so the board still attaches without interrupt support, exactly as it does today when request_irq() fails.

---
 drivers/comedi/drivers/comedi_parport.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/comedi/drivers/comedi_parport.c +2 -1
index db9f58792ab91..c6169f03ebbd9 100644
@@ -241,7 +241,8 @@ static int parport_attach(struct comedi_device *dev,
 	outb(0, dev->iobase + PARPORT_DATA_REG);
 	outb(0, dev->iobase + PARPORT_CTRL_REG);
 
-	if (it->options[1]) {
+	/* only ISA interrupts are valid on a parallel port */
+	if (it->options[1] >= 1 && it->options[1] <= 15) {
 		ret = request_irq(it->options[1], parport_interrupt, 0,
 				  dev->board_name, dev);
 		if (ret == 0)
Signature · 1 line
2.53.0
author maintainer
#1417 lore raw

PATCH 1415/2151 comedi: ni_atmio16d: validate the IRQ supplied by userspace

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit 71424db0ebb5f484fa3f386910f8ce9da95b8b2e ]

comedi boards are configured through the COMEDI_DEVCONFIG ioctl, so it->options[1] is a number chosen by userspace. ni_atmio16d passes it to request_irq() without checking it first, which lets an interrupt owned by another irqdomain -- a PCI device's IO-APIC GSI, for instance -- be claimed for this board. When the owner of that interrupt is later released the descriptor is freed while this driver's handler is still installed on it.

The driver already documents which interrupts the board can assert -- "0 == no irq; or 3,4,5,6,7,9,10,11,12,14,15" -- so use exactly that set rather than the whole ISA range.

Bound the value before requesting it, as das16m1.c already does. An out-of-range value is ignored rather than rejected, so the board still attaches without interrupt support, exactly as it does today when request_irq() fails.

Fixes 2323b276308a ("Staging: comedi: add ni_at_atmio16d driver")
Assisted-by LLM
---
 drivers/comedi/drivers/ni_atmio16d.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/comedi/drivers/ni_atmio16d.c +3 -1
index bf7fb6704710f..54371df0b4301 100644
@@ -592,7 +592,9 @@ static int atmio16d_attach(struct comedi_device *dev,
 	/* reset the atmio16d hardware */
 	reset_atmio16d(dev);
 
-	if (it->options[1]) {
+	/* only irqs 3, 4, 5, 6, 7, 9, 10, 11, 12, 14, and 15 are valid */
+	if (it->options[1] >= 3 && it->options[1] <= 15 &&
+	    (1 << it->options[1]) & 0xdef8) {
 		ret = request_irq(it->options[1], atmio16d_interrupt, 0,
 				  dev->board_name, dev);
 		if (ret == 0)
Signature · 1 line
2.53.0
author maintainer
#1418 lore raw

PATCH 1416/2151 comedi: dt2814: validate the IRQ supplied by userspace

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit 81026c2b3f9096cdfdfa02918f94865629fb7f90 ]

comedi boards are configured through the COMEDI_DEVCONFIG ioctl, so it->options[1] is a number chosen by userspace. dt2814 passes it to request_irq() without checking it first, which lets an interrupt owned by another irqdomain -- a PCI device's IO-APIC GSI, for instance -- be claimed for this board. When the owner of that interrupt is later released the descriptor is freed while this driver's handler is still installed on it.

Every interrupt this board can assert is a legacy ISA one, so the ISA range is the right bound; it is also sufficient, because mp_chip_data->isa_irq is set only by alloc_isa_irq_from_domain() and mp_unmap_irq() returns early when it is set.

Bound the value before requesting it, as das16m1.c already does. An out-of-range value is ignored rather than rejected, so the board still attaches without interrupt support, exactly as it does today when request_irq() fails.

Fixes a211ea977a41 ("Staging: comedi: add dt2814 driver")
Assisted-by LLM
---
 drivers/comedi/drivers/dt2814.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/comedi/drivers/dt2814.c +2 -1
index c98a5a4a7aecf..3e734e343431b 100644
@@ -315,7 +315,8 @@ static int dt2814_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 		return -EIO;
 	}
 
-	if (it->options[1]) {
+	/* only ISA interrupts are valid on this board */
+	if (it->options[1] >= 1 && it->options[1] <= 15) {
 		ret = request_irq(it->options[1], dt2814_interrupt, 0,
 				  dev->board_name, dev);
 		if (ret == 0)
Signature · 1 line
2.53.0
author maintainer
#1419 lore raw

PATCH 1417/2151 comedi: dmm32at: validate the IRQ supplied by userspace

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit 797d56d7f90864e67424f8e82639a9b3aedf37e0 ]

comedi boards are configured through the COMEDI_DEVCONFIG ioctl, so it->options[1] is a number chosen by userspace. dmm32at passes it to request_irq() without checking it first, which lets an interrupt owned by another irqdomain -- a PCI device's IO-APIC GSI, for instance -- be claimed for this board. When the owner of that interrupt is later released the descriptor is freed while this driver's handler is still installed on it.

Every interrupt this board can assert is a legacy ISA one, so the ISA range is the right bound; it is also sufficient, because mp_chip_data->isa_irq is set only by alloc_isa_irq_from_domain() and mp_unmap_irq() returns early when it is set.

Bound the value before requesting it, as das16m1.c already does. An out-of-range value is ignored rather than rejected, so the board still attaches without interrupt support, exactly as it does today when request_irq() fails.

Fixes 3c501880ac44 ("Staging: comedi: add dmm32at driver")
Assisted-by LLM
---
 drivers/comedi/drivers/dmm32at.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/comedi/drivers/dmm32at.c +2 -1
index 910cd24b1bed5..240d0711b6c2a 100644
@@ -584,7 +584,8 @@ static int dmm32at_attach(struct comedi_device *dev,
 		return ret;
 	}
 
-	if (it->options[1]) {
+	/* only ISA interrupts are valid on this board */
+	if (it->options[1] >= 1 && it->options[1] <= 15) {
 		ret = request_irq(it->options[1], dmm32at_isr, 0,
 				  dev->board_name, dev);
 		if (ret == 0)
Signature · 1 line
2.53.0
author maintainer
#1420 lore raw

PATCH 1418/2151 comedi: pcmmio: validate the IRQ supplied by userspace

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit 23c6fc62e754f8bc412ceb5c0d9aaa14f2c9ff31 ]

comedi boards are configured through the COMEDI_DEVCONFIG ioctl, so it->options[1] is a number chosen by userspace. pcmmio passes it to request_irq() without checking it first, which lets an interrupt owned by another irqdomain -- a PCI device's IO-APIC GSI, for instance -- be claimed for this board. When the owner of that interrupt is later released the descriptor is freed while this driver's handler is still installed on it.

The board's interrupt is routed in software rather than jumpered, and the driver notes that "any IRQ from 1-15 is OK", so the ISA range is exactly the right bound.

Bound the value before requesting it, as das16m1.c already does. An out-of-range value is ignored rather than rejected, so the board still attaches without interrupt support, exactly as it does today when request_irq() fails.

Fixes 6baef150380d ("Staging: comedi: add pcmmio and pcmuio drivers")
Assisted-by LLM
---
 drivers/comedi/drivers/pcmmio.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/comedi/drivers/pcmmio.c +2 -1
index db9cb3fedb48d..cd8b02e6ddc04 100644
@@ -683,7 +683,8 @@ static int pcmmio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 
 	pcmmio_reset(dev);
 
-	if (it->options[1]) {
+	/* the irq is configured in software, so any ISA irq is OK */
+	if (it->options[1] >= 1 && it->options[1] <= 15) {
 		ret = request_irq(it->options[1], interrupt_pcmmio, 0,
 				  dev->board_name, dev);
 		if (ret == 0) {
Signature · 1 line
2.53.0
author maintainer
#1421 lore raw

PATCH 1419/2151 comedi: pcmuio: validate the IRQs supplied by userspace

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit 9c325b21bba99e597771137fc11b9427c86618d8 ]

comedi boards are configured through the COMEDI_DEVCONFIG ioctl, so it->options[1] is a number chosen by userspace. pcmuio passes it to request_irq() without checking it first, which lets an interrupt owned by another irqdomain -- a PCI device's IO-APIC GSI, for instance -- be claimed for this board. When the owner of that interrupt is later released the descriptor is freed while this driver's handler is still installed on it.

Every interrupt this board can assert is a legacy ISA one, so the ISA range is the right bound; it is also sufficient, because mp_chip_data->isa_irq is set only by alloc_isa_irq_from_domain() and mp_unmap_irq() returns early when it is set.

Bound the value before requesting it, as das16m1.c already does. An out-of-range value is ignored rather than rejected, so the board still attaches without interrupt support, exactly as it does today when request_irq() fails.

This board takes two interrupts, one per ASIC, so options[1] and options[2] both need the check. The existing options[2] == dev->irq case is left alone: it covers both ASICs sharing one interrupt and neither having one, and by then options[1] has already been validated.

Fixes 6baef150380d ("Staging: comedi: add pcmmio and pcmuio drivers")
Assisted-by LLM
---
 drivers/comedi/drivers/pcmuio.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/comedi/drivers/pcmuio.c +3 -2
index 1c5fe065a91f5..84bbfdcd0953d 100644
@@ -545,7 +545,8 @@ static int pcmuio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 
 	pcmuio_reset(dev);
 
-	if (it->options[1]) {
+	/* only ISA interrupts are valid on this board */
+	if (it->options[1] >= 1 && it->options[1] <= 15) {
 		/* request the irq for the 1st asic */
 		ret = request_irq(it->options[1], pcmuio_interrupt, 0,
 				  dev->board_name, dev);
@@ -557,7 +558,7 @@ static int pcmuio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 		if (it->options[2] == dev->irq) {
 			/* the same irq (or none) is used by both asics */
 			devpriv->irq2 = it->options[2];
-		} else if (it->options[2]) {
+		} else if (it->options[2] >= 1 && it->options[2] <= 15) {
 			/* request the irq for the 2nd asic */
 			ret = request_irq(it->options[2], pcmuio_interrupt, 0,
 					  dev->board_name, dev);
Signature · 1 line
2.53.0
author maintainer
#1422 lore raw

PATCH 1420/2151 perf test attr: Source setup_python.sh instead of calling python

In reply to Greg Kroah-Hartman

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

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

From: Arnaldo Carvalho de Melo <[email protected]>

[ Upstream commit 3b05843302202598a6d25f3e2543c8182e6a930c ]

The "Perf attribute expectations test" (perf test 82) fails on machines that don't ship a bare 'python' binary, i.e. distributions that provide only python3 unless python-is-python3 or an equivalent is installed. Namhyung Kim hit this and posted the fix applied here in <[email protected]>:

/home/namhyung/project/linux/tools/perf/tests/shell/attr.sh: line 20: python: command not found ---- end(-1) ----
82: Perf attribute expectations test : FAILED!

attr.sh is the only shell test that still invokes python directly; do what the others do: source lib/setup_python.sh, which prefers python3, falls back to python and skips the test when no interpreter is found, then run $PYTHON.

Fixes 8519e4f44c2af722 ("perf test: Add a shell wrapper for "Setup struct perf_event_attr"")
Assisted-by LLM
---
 tools/perf/tests/shell/attr.sh | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
tools/perf/tests/shell/attr.sh +5 -1
index 307e1535795a3..ca3ca4a193971 100755
@@ -4,6 +4,10 @@
 
 err=0
 
+shelldir=$(dirname "$0")
+# shellcheck source=lib/setup_python.sh
+. "${shelldir}"/lib/setup_python.sh
+
 cleanup() {
   trap - EXIT TERM INT
 }
@@ -17,7 +21,7 @@ trap trap_cleanup EXIT TERM INT
 
 shelldir=$(dirname "$0")
 perf_path=$(which perf)
-python "${shelldir}"/lib/attr.py -d "${shelldir}"/attr -v -p "$perf_path"
+$PYTHON "${shelldir}"/lib/attr.py -d "${shelldir}"/attr -v -p "$perf_path"
 err=$?
 cleanup
 exit $err
Signature · 1 line
2.53.0
author maintainer
#1423 lore raw

PATCH 1421/2151 thermal/drivers/qcom-spmi-temp-alarm: Fix temp_map indexing

In reply to Greg Kroah-Hartman

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

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

From: Georgi Djakov <[email protected]>

[ Upstream commit 51c262cf2aa9dfd97591e570d4e82af493ad1689 ]

Fix the following issue noticed when booting on the db845c-dragonboard:

BUG: KASAN: global-out-of-bounds in qpnp_tm_sync_thresholds+0x11c/0x180 [qcom_spmi_temp_alarm]
Read of size 24 at addr ffffdd2495f01200 by task (udev-worker)/371

CPU: 3 UID: 0 PID: 371 Comm: (udev-worker) Not tainted 7.3.0-rc3 #116 PREEMPT
Hardware name: Thundercomm Dragonboard 845c (DT)
Call trace:
 show_stack+0x18/0x24 (C)
 dump_stack_lvl+0xa4/0xf4
 print_report+0x1f4/0x5ac
 kasan_report+0x84/0xcc
 kasan_check_range+0xf0/0x1a4
 memcpy+0x3c/0xa4
 qpnp_tm_sync_thresholds+0x11c/0x180 [qcom_spmi_temp_alarm]
 qpnp_tm_probe+0x3dc/0xae8 [qcom_spmi_temp_alarm]
 platform_probe+0xc4/0x18c
 really_probe+0x17c/0x4fc
 ...

The buggy address belongs to the variable:
 temp_map_gen1+0x60/0xc4 [qcom_spmi_temp_alarm]

It looks like temp_map is a pointer to the complete temperature map. Indexing it directly advances the entire map, rather than selecting a threshold row.

Fix this by dereferencing the temp_map before indexing it to select the requested threshold row.

Fixes 703f13285a6c ("thermal/drivers/qcom-spmi-temp-alarm: Add temp alarm data struct based on HW subtype")
Fixes 1f835c6a4c84 ("thermal/drivers/qcom-spmi-temp-alarm: Prepare to support additional Temp Alarm subtypes")
---
 drivers/thermal/qcom/qcom-spmi-temp-alarm.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/thermal/qcom/qcom-spmi-temp-alarm.c +4 -4
index f39ca0ddd17b6..67eb763276eaa 100644
@@ -345,8 +345,8 @@ static int qpnp_tm_update_critical_trip_temp(struct qpnp_tm_chip *chip,
 	}
 
 skip:
-	memcpy(chip->temp_thresh_map, chip->data->temp_map[threshold],
-		sizeof(chip->temp_thresh_map));
+	memcpy(chip->temp_thresh_map, (*chip->data->temp_map)[threshold],
+	       sizeof(chip->temp_thresh_map));
 	reg |= threshold;
 	if (disable_stage2_shutdown && !chip->require_stage2_shutdown)
 		reg |= SHUTDOWN_CTRL1_OVERRIDE_STAGE2;
@@ -535,8 +535,8 @@ static int qpnp_tm_sync_thresholds(struct qpnp_tm_chip *chip)
 		return ret;
 
 	threshold = reg & SHUTDOWN_CTRL1_THRESHOLD_MASK;
-	memcpy(chip->temp_thresh_map, chip->data->temp_map[threshold],
-		sizeof(chip->temp_thresh_map));
+	memcpy(chip->temp_thresh_map, (*chip->data->temp_map)[threshold],
+	       sizeof(chip->temp_thresh_map));
 
 	return ret;
 }
Signature · 1 line
2.53.0
author maintainer
#1424 lore raw

PATCH 1422/2151 thermal/drivers/ti-soc-thermal: Cancel pending alert work on remove

In reply to Greg Kroah-Hartman

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

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

From: Weigang He <[email protected]>

[ Upstream commit aaa6c8dec49339710f9fd2a2af5646cf4111dbd4 ]

On a threshold crossing, the talert IRQ handler calls ti_thermal_report_sensor_temperature(), which queues the work embedded in the sensor's ti_thermal_data on the system workqueue. Nothing ever cancels or flushes that work.

ti_bandgap_remove() frees the talert IRQ last. free_irq() waits for a running handler, but not for the work the handler has queued. When remove returns, devres unregisters and frees the thermal zones and then frees the devm-allocated ti_thermal_data, so a work item that is still pending runs ti_thermal_work() on freed memory:

	ti_thermal_work()
	  data = container_of(work, struct ti_thermal_data, thermal_wq);
	  thermal_zone_device_update(data->ti_thermal, ...);

Free the talert IRQ before removing the sensors, so that no new work can be queued, and cancel the work in ti_thermal_remove_sensor().

This needs an OMAP4460/4470 or OMAP5 SoC (DRA7 has TALERT but no ->report_temperature, so it never queues the work), a threshold crossing just before the driver is unbound or unloaded, and the work still pending when devres frees the data.

Found by static analysis tool CodeQL.

Fixes 445eaf871bf9 ("staging: omap-thermal: common code to expose driver to thermal framework")
Assisted-by LLM codeql
---
 drivers/thermal/ti-soc-thermal/ti-bandgap.c        | 7 ++++---
 drivers/thermal/ti-soc-thermal/ti-thermal-common.c | 4 ++++
 2 files changed, 8 insertions(+), 3 deletions(-)
drivers/thermal/ti-soc-thermal/ti-bandgap.c +4 -3
index ba43399d0b384..507fe67eaffae 100644
@@ -1077,6 +1077,10 @@ void ti_bandgap_remove(struct platform_device *pdev)
 	if (!soc_device_match(soc_no_cpu_notifier))
 		cpu_pm_unregister_notifier(&bgp->nb);
 
+	/* Stop the alerts first: they queue work on the sensors' data */
+	if (TI_BANDGAP_HAS(bgp, TALERT))
+		free_irq(bgp->irq, bgp);
+
 	/* Remove sensor interfaces */
 	for (i = 0; i < bgp->conf->sensor_count; i++) {
 		if (bgp->conf->sensors[i].unregister_cooling)
@@ -1093,9 +1097,6 @@ void ti_bandgap_remove(struct platform_device *pdev)
 	clk_put(bgp->fclock);
 	clk_put(bgp->div_clk);
 
-	if (TI_BANDGAP_HAS(bgp, TALERT))
-		free_irq(bgp->irq, bgp);
-
 	if (TI_BANDGAP_HAS(bgp, TSHUT))
 		free_irq(gpiod_to_irq(bgp->tshut_gpiod), NULL);
 }
drivers/thermal/ti-soc-thermal/ti-thermal-common.c +4 -0
index 0cf0826b805a9..4bf3b2e0fc682 100644
@@ -195,6 +195,10 @@ int ti_thermal_remove_sensor(struct ti_bandgap *bgp, int id)
 
 	data = ti_bandgap_get_sensor_data(bgp, id);
 
+	/* Work queued by the talert IRQ must not outlive the data */
+	if (!IS_ERR_OR_NULL(data))
+		cancel_work_sync(&data->thermal_wq);
+
 	if (!IS_ERR_OR_NULL(data) && data->ti_thermal) {
 		if (data->our_zone)
 			thermal_zone_device_unregister(data->ti_thermal);
Signature · 1 line
2.53.0
author maintainer
#1425 lore raw

PATCH 1423/2151 tools: hv: remove unused rte_smp_mb()

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit b67eeae485e22893b678229169024a73b87cf113 ]

rte_smp_mb() has never been used, and its "static inline __always_inline" declares inline twice, so clang warns:

vmbus_bufring.c:61:15: warning: duplicate 'inline' declaration specifier [-Wduplicate-decl-specifier] vmbus_bufring.c:62:1: warning: unused function 'rte_smp_mb' [-Wunused-function]

Remove it.

---
 tools/hv/vmbus_bufring.c | 6 ------
 1 file changed, 6 deletions(-)
tools/hv/vmbus_bufring.c +0 -6
index bac32c1109df8..23542e59a2ee9 100644
@@ -58,12 +58,6 @@ void vmbus_br_setup(struct vmbus_br *br, void *buf, unsigned int blen)
 	br->dsize = blen - sizeof(struct vmbus_bufring);
 }
 
-static inline __always_inline void
-rte_smp_mb(void)
-{
-	asm volatile("lock addl $0, -128(%%rsp); " ::: "memory");
-}
-
 static inline int
 rte_atomic32_cmpset(volatile uint32_t *dst, uint32_t exp, uint32_t src)
 {
Signature · 1 line
2.53.0
author maintainer
#1426 lore raw

PATCH 1424/2151 char: scx200_gpio: check cdev_add() return value

In reply to Greg Kroah-Hartman

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

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

From: Linkai Gong <[email protected]>

[ Upstream commit fe26c195c265c033e474d015061a0183c7a02193 ]

cdev_add() can fail. The driver currently ignores the return value and reports probe success even when the cdev was not registered, leaving a chrdev region allocated with no working file operations.

Check the return value, emit an error, and unwind the chrdev region and platform device on failure.

Fixes 635adb6cd25c ("[PATCH] scx200_gpio: use 1 cdev for N minors, not N for N")
---
 drivers/char/scx200_gpio.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/char/scx200_gpio.c +7 -1
index 700e6affea6f7..3ec17832e9c9d 100644
@@ -107,10 +107,16 @@ static int __init scx200_gpio_init(void)
 	}
 
 	cdev_init(&scx200_gpio_cdev, &scx200_gpio_fileops);
-	cdev_add(&scx200_gpio_cdev, devid, MAX_PINS);
+	rc = cdev_add(&scx200_gpio_cdev, devid, MAX_PINS);
+	if (rc) {
+		dev_err(&pdev->dev, "cdev_add err: %d\n", rc);
+		goto undo_chrdev_region;
+	}
 
 	return 0; /* succeed */
 
+undo_chrdev_region:
+	unregister_chrdev_region(devid, MAX_PINS);
 undo_platform_device_add:
 	platform_device_del(pdev);
 undo_malloc:
Signature · 1 line
2.53.0
author maintainer
#1427 lore raw

PATCH 1425/2151 bus: arm-cci: Drop CPU node reference in cci_ace_init_ports()

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 41d6c0fcd4d75bf78c304c6660d60fcf757885ce ]

cci_ace_init_ports() looks up each possible CPU's node with of_get_cpu_node(), which returns the node with its reference count raised, but never releases it: neither when the CPU has no ACE port nor after the port has been recorded. Before the commit below the loop used for_each_child_of_node(), which manages the references itself.

The node is only needed for the port lookup, so drop the reference right after __cci_ace_get_port().

Fixes 78b4d6e0fd26 ("drivers/bus: arm-cci: avoid parsing DT for cpu device nodes")
---
 drivers/bus/arm-cci.c | 1 +
 1 file changed, 1 insertion(+)
drivers/bus/arm-cci.c +1 -0
index b8184a9035837..ab9b49451f8f2 100644
@@ -199,6 +199,7 @@ static void cci_ace_init_ports(void)
 			continue;
 
 		port = __cci_ace_get_port(cpun, ACE_PORT);
+		of_node_put(cpun);
 		if (port < 0)
 			continue;
 
Signature · 1 line
2.53.0
author maintainer
#1428 lore raw

PATCH 1426/2151 bus: arm-cci: Drop cci-control-port node reference in __cci_ace_get_port()

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 810ccc792193909ba9bbb4246e0eb0de14dad724 ]

__cci_ace_get_port() looks up the device's "cci-control-port" node with of_parse_phandle(), which returns the node with its reference count raised, and only compares the pointer against the probed ports. Neither the match nor the no-match return releases it.

Drop the reference on both paths once the comparison is done.

Fixes ed69bdd8fd9b ("drivers: bus: add ARM CCI support")
---
 drivers/bus/arm-cci.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/bus/arm-cci.c +4 -1
index ab9b49451f8f2..25a741e48573f 100644
@@ -167,9 +167,12 @@ static int __cci_ace_get_port(struct device_node *dn, int type)
 	cci_portn = of_parse_phandle(dn, "cci-control-port", 0);
 	for (i = 0; i < nb_cci_ports; i++) {
 		ace_match = ports[i].type == type;
-		if (ace_match && cci_portn == ports[i].dn)
+		if (ace_match && cci_portn == ports[i].dn) {
+			of_node_put(cci_portn);
 			return i;
+		}
 	}
+	of_node_put(cci_portn);
 	return -ENODEV;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1429 lore raw

PATCH 1427/2151 clk: qcom: rpmh: Update the clock suffix for Glymur

In reply to Greg Kroah-Hartman

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

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

From: Taniya Das <[email protected]>

[ Upstream commit 3dadc1dc5e85cefc7a2f1c9d428b5622fda12d3d ]

The current RPMh VRM clock definitions do not accurately represent the hardware mapping of these clocks. While there is no functional impact, this update aligns the definitions with the hardware convention by adding the appropriate suffix to indicate the clock divider and the E0 variant for the C3A_E0, C4A_E0, C5A_E0, and C8A_E0 resources on Glymur.

Stable-dep-of: 1ebab545ee3a ("clk: qcom: rpmhcc: Add LNBB clocks support for Glymur")

---
 drivers/clk/qcom/clk-rpmh.c | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)
drivers/clk/qcom/clk-rpmh.c +10 -10
index 82f18e15cd77b..feeb288479b00 100644
@@ -388,10 +388,10 @@ DEFINE_CLK_RPMH_VRM(clk7, _a4, "clka7", 4);
 
 DEFINE_CLK_RPMH_VRM(div_clk1, _div2, "divclka1", 2);
 
-DEFINE_CLK_RPMH_VRM(clk3, _a, "C3A_E0", 1);
-DEFINE_CLK_RPMH_VRM(clk4, _a, "C4A_E0", 1);
-DEFINE_CLK_RPMH_VRM(clk5, _a, "C5A_E0", 1);
-DEFINE_CLK_RPMH_VRM(clk8, _a, "C8A_E0", 1);
+DEFINE_CLK_RPMH_VRM(clk3, _a1_e0, "C3A_E0", 1);
+DEFINE_CLK_RPMH_VRM(clk4, _a1_e0, "C4A_E0", 1);
+DEFINE_CLK_RPMH_VRM(clk5, _a1_e0, "C5A_E0", 1);
+DEFINE_CLK_RPMH_VRM(clk8, _a1_e0, "C8A_E0", 1);
 
 DEFINE_CLK_RPMH_BCM(ce, "CE0");
 DEFINE_CLK_RPMH_BCM(hwkm, "HK0");
@@ -882,12 +882,12 @@ static const struct clk_rpmh_desc clk_rpmh_sm8750 = {
 static struct clk_hw *glymur_rpmh_clocks[] = {
 	[RPMH_CXO_CLK]		= &clk_rpmh_bi_tcxo_div2.hw,
 	[RPMH_CXO_CLK_A]	= &clk_rpmh_bi_tcxo_div2_ao.hw,
-	[RPMH_RF_CLK3]		= &clk_rpmh_clk3_a.hw,
-	[RPMH_RF_CLK3_A]	= &clk_rpmh_clk3_a_ao.hw,
-	[RPMH_RF_CLK4]		= &clk_rpmh_clk4_a.hw,
-	[RPMH_RF_CLK4_A]	= &clk_rpmh_clk4_a_ao.hw,
-	[RPMH_RF_CLK5]		= &clk_rpmh_clk5_a.hw,
-	[RPMH_RF_CLK5_A]	= &clk_rpmh_clk5_a_ao.hw,
+	[RPMH_RF_CLK3]		= &clk_rpmh_clk3_a1_e0.hw,
+	[RPMH_RF_CLK3_A]	= &clk_rpmh_clk3_a1_e0_ao.hw,
+	[RPMH_RF_CLK4]		= &clk_rpmh_clk4_a1_e0.hw,
+	[RPMH_RF_CLK4_A]	= &clk_rpmh_clk4_a1_e0_ao.hw,
+	[RPMH_RF_CLK5]		= &clk_rpmh_clk5_a1_e0.hw,
+	[RPMH_RF_CLK5_A]	= &clk_rpmh_clk5_a1_e0_ao.hw,
 };
 
 static const struct clk_rpmh_desc clk_rpmh_glymur = {
Signature · 1 line
2.53.0
author maintainer
#1430 lore raw

PATCH 1428/2151 clk: qcom: rpmhcc: Add LNBB clocks support for Glymur

In reply to Greg Kroah-Hartman

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

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

From: Jagadeesh Kona <[email protected]>

[ Upstream commit 1ebab545ee3acbbee22adecb858d5d1d001de0af ]

Add support for rpmh LN_BB_CLK2 and LN_BB_CLK3 clocks on Qualcomm Glymur platform.

---
 drivers/clk/qcom/clk-rpmh.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/clk/qcom/clk-rpmh.c +5 -0
index feeb288479b00..0f148bde109f0 100644
@@ -391,6 +391,7 @@ DEFINE_CLK_RPMH_VRM(div_clk1, _div2, "divclka1", 2);
 DEFINE_CLK_RPMH_VRM(clk3, _a1_e0, "C3A_E0", 1);
 DEFINE_CLK_RPMH_VRM(clk4, _a1_e0, "C4A_E0", 1);
 DEFINE_CLK_RPMH_VRM(clk5, _a1_e0, "C5A_E0", 1);
+DEFINE_CLK_RPMH_VRM(clk7, _a1_e0, "C7A_E0", 1);
 DEFINE_CLK_RPMH_VRM(clk8, _a1_e0, "C8A_E0", 1);
 
 DEFINE_CLK_RPMH_BCM(ce, "CE0");
@@ -888,6 +889,10 @@ static struct clk_hw *glymur_rpmh_clocks[] = {
 	[RPMH_RF_CLK4_A]	= &clk_rpmh_clk4_a1_e0_ao.hw,
 	[RPMH_RF_CLK5]		= &clk_rpmh_clk5_a1_e0.hw,
 	[RPMH_RF_CLK5_A]	= &clk_rpmh_clk5_a1_e0_ao.hw,
+	[RPMH_LN_BB_CLK2]	= &clk_rpmh_clk7_a1_e0.hw,
+	[RPMH_LN_BB_CLK2_A]	= &clk_rpmh_clk7_a1_e0_ao.hw,
+	[RPMH_LN_BB_CLK3]	= &clk_rpmh_clk8_a1_e0.hw,
+	[RPMH_LN_BB_CLK3_A]	= &clk_rpmh_clk8_a1_e0_ao.hw,
 };
 
 static const struct clk_rpmh_desc clk_rpmh_glymur = {
Signature · 1 line
2.53.0
author maintainer
#1431 lore raw

PATCH 1429/2151 clk: qcom: gcc-glymur: Use clk_regmap_phy_mux_ops for GCC UFS muxes

In reply to Greg Kroah-Hartman

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

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

From: Jagadeesh Kona <[email protected]>

[ Upstream commit 20b77a88fc6e410b69bc98d3d61c035a8618fb90 ]

Use clk_regmap_phy_mux_ops for GCC UFS muxes so these muxes are automatically switched to UFS external symbol clocks during enable and safely parked at XO clk during disable.

---
 drivers/clk/qcom/gcc-glymur.c | 69 +++++++++--------------------------
 1 file changed, 18 insertions(+), 51 deletions(-)
drivers/clk/qcom/gcc-glymur.c +18 -51
index 7adbe59915f0f..4c94a42d3bca7 100644
@@ -483,36 +483,6 @@ static const struct clk_parent_data gcc_parent_data_17[] = {
 	{ .hw = &gcc_gpll0_out_even.clkr.hw },
 };
 
-static const struct parent_map gcc_parent_map_18[] = {
-	{ P_UFS_PHY_RX_SYMBOL_0_CLK, 0 },
-	{ P_BI_TCXO, 2 },
-};
-
-static const struct clk_parent_data gcc_parent_data_18[] = {
-	{ .index = DT_UFS_PHY_RX_SYMBOL_0_CLK },
-	{ .index = DT_BI_TCXO },
-};
-
-static const struct parent_map gcc_parent_map_19[] = {
-	{ P_UFS_PHY_RX_SYMBOL_1_CLK, 0 },
-	{ P_BI_TCXO, 2 },
-};
-
-static const struct clk_parent_data gcc_parent_data_19[] = {
-	{ .index = DT_UFS_PHY_RX_SYMBOL_1_CLK },
-	{ .index = DT_BI_TCXO },
-};
-
-static const struct parent_map gcc_parent_map_20[] = {
-	{ P_UFS_PHY_TX_SYMBOL_0_CLK, 0 },
-	{ P_BI_TCXO, 2 },
-};
-
-static const struct clk_parent_data gcc_parent_data_20[] = {
-	{ .index = DT_UFS_PHY_TX_SYMBOL_0_CLK },
-	{ .index = DT_BI_TCXO },
-};
-
 static const struct parent_map gcc_parent_map_21[] = {
 	{ P_GCC_USB3_PRIM_PHY_PIPE_CLK_SRC, 0 },
 	{ P_USB4_0_PHY_GCC_USB4RTR_MAX_PIPE_CLK, 1 },
@@ -909,47 +879,44 @@ static struct clk_regmap_phy_mux gcc_pcie_6_pipe_clk_src = {
 	},
 };
 
-static struct clk_regmap_mux gcc_ufs_phy_rx_symbol_0_clk_src = {
+static struct clk_regmap_phy_mux gcc_ufs_phy_rx_symbol_0_clk_src = {
 	.reg = 0x7706c,
-	.shift = 0,
-	.width = 2,
-	.parent_map = gcc_parent_map_18,
 	.clkr = {
 		.hw.init = &(const struct clk_init_data) {
 			.name = "gcc_ufs_phy_rx_symbol_0_clk_src",
-			.parent_data = gcc_parent_data_18,
-			.num_parents = ARRAY_SIZE(gcc_parent_data_18),
-			.ops = &clk_regmap_mux_closest_ops,
+			.parent_data = &(const struct clk_parent_data){
+				.index = DT_UFS_PHY_RX_SYMBOL_0_CLK,
+			},
+			.num_parents = 1,
+			.ops = &clk_regmap_phy_mux_ops,
 		},
 	},
 };
 
-static struct clk_regmap_mux gcc_ufs_phy_rx_symbol_1_clk_src = {
+static struct clk_regmap_phy_mux gcc_ufs_phy_rx_symbol_1_clk_src = {
 	.reg = 0x770f0,
-	.shift = 0,
-	.width = 2,
-	.parent_map = gcc_parent_map_19,
 	.clkr = {
 		.hw.init = &(const struct clk_init_data) {
 			.name = "gcc_ufs_phy_rx_symbol_1_clk_src",
-			.parent_data = gcc_parent_data_19,
-			.num_parents = ARRAY_SIZE(gcc_parent_data_19),
-			.ops = &clk_regmap_mux_closest_ops,
+			.parent_data = &(const struct clk_parent_data){
+				.index = DT_UFS_PHY_RX_SYMBOL_1_CLK,
+			},
+			.num_parents = 1,
+			.ops = &clk_regmap_phy_mux_ops,
 		},
 	},
 };
 
-static struct clk_regmap_mux gcc_ufs_phy_tx_symbol_0_clk_src = {
+static struct clk_regmap_phy_mux gcc_ufs_phy_tx_symbol_0_clk_src = {
 	.reg = 0x7705c,
-	.shift = 0,
-	.width = 2,
-	.parent_map = gcc_parent_map_20,
 	.clkr = {
 		.hw.init = &(const struct clk_init_data) {
 			.name = "gcc_ufs_phy_tx_symbol_0_clk_src",
-			.parent_data = gcc_parent_data_20,
-			.num_parents = ARRAY_SIZE(gcc_parent_data_20),
-			.ops = &clk_regmap_mux_closest_ops,
+			.parent_data = &(const struct clk_parent_data){
+				.index = DT_UFS_PHY_TX_SYMBOL_0_CLK,
+			},
+			.num_parents = 1,
+			.ops = &clk_regmap_phy_mux_ops,
 		},
 	},
 };
Signature · 1 line
2.53.0
author maintainer
#1432 lore raw

PATCH 1430/2151 clk: qcom: gcc-x1e80100: Dont poll the status bit of GCC_USB4_n_SYS_CLK

In reply to Greg Kroah-Hartman

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

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

From: Konrad Dybcio <[email protected]>

[ Upstream commit d42e0c55e6db7b8282e8dc63f7e70595da0f72f5 ]

These clocks are PHY-sourced and their halt bits seem not to update reliably. Ignore it to prevent spurious warnings.

Fixes 161b7c401f4b ("clk: qcom: Add Global Clock controller (GCC) driver for X1E80100")
---
 drivers/clk/qcom/gcc-x1e80100.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/clk/qcom/gcc-x1e80100.c +3 -3
index 104b1bf6a5010..827d6d52aa500 100644
@@ -5464,7 +5464,7 @@ static struct clk_branch gcc_usb4_0_sb_if_clk = {
 
 static struct clk_branch gcc_usb4_0_sys_clk = {
 	.halt_reg = 0x9f054,
-	.halt_check = BRANCH_HALT,
+	.halt_check = BRANCH_HALT_SKIP,
 	.clkr = {
 		.enable_reg = 0x9f054,
 		.enable_mask = BIT(0),
@@ -5641,7 +5641,7 @@ static struct clk_branch gcc_usb4_1_sb_if_clk = {
 
 static struct clk_branch gcc_usb4_1_sys_clk = {
 	.halt_reg = 0x2b054,
-	.halt_check = BRANCH_HALT,
+	.halt_check = BRANCH_HALT_SKIP,
 	.clkr = {
 		.enable_reg = 0x2b054,
 		.enable_mask = BIT(0),
@@ -5818,7 +5818,7 @@ static struct clk_branch gcc_usb4_2_sb_if_clk = {
 
 static struct clk_branch gcc_usb4_2_sys_clk = {
 	.halt_reg = 0x11054,
-	.halt_check = BRANCH_HALT,
+	.halt_check = BRANCH_HALT_SKIP,
 	.clkr = {
 		.enable_reg = 0x11054,
 		.enable_mask = BIT(0),
Signature · 1 line
2.53.0
author maintainer
#1433 lore raw

PATCH 1431/2151 clk: qcom: gcc-ipq5424: Fix TME reset register offsets

In reply to Greg Kroah-Hartman

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

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

From: Abel Vesa <[email protected]>

[ Upstream commit 3732dccb8d75b2cddc8857f3944cb7482ef4b46a ]

The GCC_TME_BCR and GCC_TME_SEC_BUS_BCR offsets exceed the regmap maximum of 0x3f024. Regmap therefore rejects accesses to both registers, leaving the resets ineffective while the reset operations report success.

The offsets appear to contain typographical errors. Use 0x10000 for GCC_TME_BCR, matching the offset used on IPQ9574 and the surrounding register layout. Use 0x1a030 for GCC_TME_SEC_BUS_BCR, placing it in the same register block as GCC_SEC_CTRL_BCR at 0x1a000.

---
 drivers/clk/qcom/gcc-ipq5424.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/clk/qcom/gcc-ipq5424.c +2 -2
index 71afa1b86b723..6f5c6caf4e411 100644
@@ -2945,7 +2945,7 @@ static const struct qcom_reset_map gcc_ipq5424_resets[] = {
 	[GCC_QUPV3_SPI0_BCR] = { 0x04000, 0 },
 	[GCC_QUPV3_SPI1_BCR] = { 0x05000, 0 },
 	[GCC_IMEM_BCR] = { 0x0e000, 0 },
-	[GCC_TME_BCR] = { 0x100000, 0 },
+	[GCC_TME_BCR] = { 0x10000, 0 },
 	[GCC_DDRSS_BCR] = { 0x11000, 0 },
 	[GCC_PRNG_BCR] = { 0x13020, 0 },
 	[GCC_BOOT_ROM_BCR] = { 0x13028, 0 },
@@ -2956,7 +2956,7 @@ static const struct qcom_reset_map gcc_ipq5424_resets[] = {
 	[GCC_UNIPHY2_BCR] = { 0x17064, 0 },
 	[GCC_WCSS_BCR] = { 0x18004, 0 },
 	[GCC_SEC_CTRL_BCR] = { 0x1a000, 0 },
-	[GCC_TME_SEC_BUS_BCR] = { 0xa1030, 0 },
+	[GCC_TME_SEC_BUS_BCR] = { 0x1a030, 0 },
 	[GCC_ADSS_BCR] = { 0x1c000, 0 },
 	[GCC_LPASS_BCR] = { 0x27000, 0 },
 	[GCC_PCIE0_BCR] = { 0x28000, 0 },
Signature · 1 line
2.53.0
author maintainer
#1434 lore raw

PATCH 1432/2151 clk: qcom: mmcc-msm8996: Fix FD AHB clock register offset

In reply to Greg Kroah-Hartman

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

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

From: Abel Vesa <[email protected]>

[ Upstream commit 7cb2d65286b817d8d7e26f454a9c374d65e87072 ]

The FD AHB clock branch register is at offset 0x3b74, not 0x3ba74. The incorrect offset exceeds the regmap maximum of 0xb008, so regmap rejects accesses to it and the clock cannot be enabled.

Correct both the enable and halt register offsets so the driver can enable the branch and check its status.

---
 drivers/clk/qcom/mmcc-msm8996.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/clk/qcom/mmcc-msm8996.c +2 -2
index 7d67c6f73fe13..deb90fe5aa9f8 100644
@@ -3134,9 +3134,9 @@ static struct clk_branch fd_core_uar_clk = {
 };
 
 static struct clk_branch fd_ahb_clk = {
-	.halt_reg = 0x3ba74,
+	.halt_reg = 0x3b74,
 	.clkr = {
-		.enable_reg = 0x3ba74,
+		.enable_reg = 0x3b74,
 		.enable_mask = BIT(0),
 		.hw.init = &(struct clk_init_data){
 			.name = "fd_ahb_clk",
Signature · 1 line
2.53.0
author maintainer
#1435 lore raw

PATCH 1433/2151 clk: qcom: mmcc-sdm660: Fix MDSS AHB clock HWCG register offset

In reply to Greg Kroah-Hartman

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

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

From: Abel Vesa <[email protected]>

[ Upstream commit c5f338329a2d0d60f7874aa7a1addaa0e4e75a3b ]

The MDSS AHB clock HWCG bit resides in the same register as the branch enable and halt status bits, at offset 0x2308. The current HWCG register offset of 0x8a004 exceeds the regmap maximum of 0x40000, so regmap rejects the read in clk_branch_in_hwcg_mode(). Since the read error is ignored, the helper uses an uninitialized value to decide whether to skip the halt status check.

Correct the HWCG register offset so the helper reads the actual hardware clock gating state.

---
 drivers/clk/qcom/mmcc-sdm660.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/clk/qcom/mmcc-sdm660.c +1 -1
index dbd3f561dc6d0..6d57aadedd2de 100644
@@ -2018,7 +2018,7 @@ static struct clk_branch csiphy_ahb2crif_clk = {
 static struct clk_branch mdss_ahb_clk = {
 	.halt_reg = 0x2308,
 	.halt_check = BRANCH_HALT,
-	.hwcg_reg = 0x8a004,
+	.hwcg_reg = 0x2308,
 	.hwcg_bit = 1,
 	.clkr = {
 		.enable_reg = 0x2308,
Signature · 1 line
2.53.0
author maintainer
#1436 lore raw

PATCH 1434/2151 clk: qcom: mmcc-msm8960: Configure PLL15 only on APQ8064

In reply to Greg Kroah-Hartman

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

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

From: Abel Vesa <[email protected]>

[ Upstream commit 342db3b6cf7bad2a53ccd5e2d844faf260953d9d ]

PLL15 is specific to APQ8064, but the shared probe function configures it unconditionally, including on MSM8960. Its configuration registers at offsets 0x33c through 0x348 exceed the MSM8960 regmap maximum of 0x334, so regmap rejects these accesses. The PLL configuration helper ignores the errors and probe continues.

Only configure PLL15 when the selected descriptor is for APQ8064, matching the existing variant check for the GFX3D clock adjustments.

---
 drivers/clk/qcom/mmcc-msm8960.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/clk/qcom/mmcc-msm8960.c +2 -1
index cd3c9f8455e5e..2e1551226a619 100644
@@ -3171,7 +3171,8 @@ static int mmcc_msm8960_probe(struct platform_device *pdev)
 	if (IS_ERR(regmap))
 		return PTR_ERR(regmap);
 
-	clk_pll_configure_sr(&pll15, regmap, &pll15_config, false);
+	if (desc == &mmcc_apq8064_desc)
+		clk_pll_configure_sr(&pll15, regmap, &pll15_config, false);
 
 	return qcom_cc_really_probe(&pdev->dev, desc, regmap);
 }
Signature · 1 line
2.53.0
author maintainer
#1437 lore raw

PATCH 1435/2151 clk: qcom: rcg2: Initialize shared floor clock state

In reply to Greg Kroah-Hartman

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

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

From: Konrad Dybcio <[email protected]>

[ Upstream commit 72f34d429f6e51b0ef8c43ab7667c4fb4099dd46 ]

Shared floor RCGs use the cached parked_cfg whenever CCF considers the clock disabled. Unlike the other shared RCG variants, their ops do not initialize that cache, leaving it zeroed until the first disable or rate change. This can make registration report an undivided XO configuration instead of the boot-programmed parent and divider.

Initialize parked_cfg from CFG_REG without parking or otherwise changing the hardware. Propagate read failures so a clock with unknown initial state is not registered.

Fixes aec8c0e28ce4 ("clk: qcom: rcg2: add clk_rcg2_shared_floor_ops")
Assisted-by LLM
---
 drivers/clk/qcom/clk-rcg2.c | 26 +++++++++++++-------------
 1 file changed, 13 insertions(+), 13 deletions(-)
drivers/clk/qcom/clk-rcg2.c +13 -13
index d0a5847f91114..b6e30985deab6 100644
@@ -1553,7 +1553,20 @@ const struct clk_ops clk_rcg2_shared_ops = {
 };
 EXPORT_SYMBOL_GPL(clk_rcg2_shared_ops);
 
+static int clk_rcg2_shared_no_init_park(struct clk_hw *hw)
+{
+	struct clk_rcg2 *rcg = to_clk_rcg2(hw);
+
+	/*
+	 * Read the config register so that the parent is properly mapped at
+	 * registration time.
+	 */
+	return regmap_read(rcg->clkr.regmap, rcg->cmd_rcgr + CFG_REG,
+			   &rcg->parked_cfg);
+}
+
 const struct clk_ops clk_rcg2_shared_floor_ops = {
+	.init = clk_rcg2_shared_no_init_park,
 	.enable = clk_rcg2_shared_enable,
 	.disable = clk_rcg2_shared_disable,
 	.get_parent = clk_rcg2_shared_get_parent,
@@ -1565,19 +1578,6 @@ const struct clk_ops clk_rcg2_shared_floor_ops = {
 };
 EXPORT_SYMBOL_GPL(clk_rcg2_shared_floor_ops);
 
-static int clk_rcg2_shared_no_init_park(struct clk_hw *hw)
-{
-	struct clk_rcg2 *rcg = to_clk_rcg2(hw);
-
-	/*
-	 * Read the config register so that the parent is properly mapped at
-	 * registration time.
-	 */
-	regmap_read(rcg->clkr.regmap, rcg->cmd_rcgr + CFG_REG, &rcg->parked_cfg);
-
-	return 0;
-}
-
 /*
  * Like clk_rcg2_shared_ops but skip the init so that the clk frequency is left
  * unchanged at registration time.
Signature · 1 line
2.53.0
author maintainer
#1438 lore raw

PATCH 1436/2151 clk: qcom: rcg2: Propagate force-enable status errors

In reply to Greg Kroah-Hartman

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

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

From: Konrad Dybcio <[email protected]>

[ Upstream commit 8c0f93e10fa9e34009817bd37bb75c1b5a691fa2 ]

clk_rcg2_is_enabled() returns either a hardware status or a negative regmap error. The force-enable polling loop treats every nonzero return as an enabled clock, so a failed status read is incorrectly reported as success and clock reconfiguration can continue with unknown hardware state.

Check for negative returns before testing the enabled status and propagate the read error to the caller.

Fixes 7ef6f11887bd ("clk: qcom: Configure the RCGs to a safe source as needed")
Assisted-by LLM
---
 drivers/clk/qcom/clk-rcg2.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/clk/qcom/clk-rcg2.c +4 -1
index b6e30985deab6..a7d4dfc107e53 100644
@@ -1330,7 +1330,10 @@ static int clk_rcg2_set_force_enable(struct clk_hw *hw)
 
 	/* wait for RCG to turn ON */
 	for (count = 500; count > 0; count--) {
-		if (clk_rcg2_is_enabled(hw))
+		ret = clk_rcg2_is_enabled(hw);
+		if (ret < 0)
+			return ret;
+		if (ret)
 			return 0;
 
 		udelay(1);
Signature · 1 line
2.53.0
author maintainer
#1439 lore raw

PATCH 1437/2151 clk: qcom: rcg2: Clear force enable after rate failure

In reply to Greg Kroah-Hartman

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

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

From: Konrad Dybcio <[email protected]>

[ Upstream commit d4e8c6b9aef42d06cf5755543ad10097b2217990 ]

Shared RCG rate changes assert force-enable before programming the new configuration. If programming fails, the function returns without clearing force-enable, leaving the root running while CCF can release temporary parent and resource references.

Attempt to clear force-enable on the configuration error path before returning the original programming error. This restores the same cleanup performed after a successful configuration while preserving the primary failure for callers.

Fixes 7ef6f11887bd ("clk: qcom: Configure the RCGs to a safe source as needed")
Assisted-by LLM
---
 drivers/clk/qcom/clk-rcg2.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/clk/qcom/clk-rcg2.c +3 -1
index a7d4dfc107e53..33b9cef509781 100644
@@ -1362,8 +1362,10 @@ clk_rcg2_shared_force_enable_clear(struct clk_hw *hw, const struct freq_tbl *f)
 		return ret;
 
 	ret = clk_rcg2_configure(rcg, f);
-	if (ret)
+	if (ret) {
+		clk_rcg2_clear_force_enable(hw);
 		return ret;
+	}
 
 	return clk_rcg2_clear_force_enable(hw);
 }
Signature · 1 line
2.53.0
author maintainer
#1440 lore raw

PATCH 1438/2151 s390/ptrace: Preserve ILC when updating system call number

In reply to Greg Kroah-Hartman

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

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

From: Heiko Carstens <[email protected]>

[ Upstream commit 946b9dcff33bd4669464674ae1c00683b875be55 ]

When an attached debugger changes gpr2 via PTRACE_POKEUSR while the traced process has PIF_SYSCALL set, the int_code in pt_regs is also updated. In case of an svc it contains the instruction length code (ILC), as well as the system call number.

The ptrace code sets the ILC unconditionally to a value which matches the svc instruction. However the svc instruction also may have been executed via the execute or execute relative long instruction, which have a different length. Therefore preserve the ILC and only change the system call number using syscall_set_nr().

This makes sure that in case of a PSW rewind the instruction address points to the correct instruction.

Fixes 56e62a737028 ("s390: convert to generic entry")
---
 arch/s390/kernel/ptrace.c | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
arch/s390/kernel/ptrace.c +4 -5
index 494216c4b4f3d..42fd1a42058a7 100644
@@ -35,6 +35,7 @@
 #include <asm/ptrace.h>
 #include <asm/rwonce.h>
 #include <asm/fpu.h>
+#include <asm/syscall.h>
 
 #include "entry.h"
 
@@ -350,11 +351,9 @@ static int __poke_user(struct task_struct *child, addr_t addr, addr_t data)
 				return -EINVAL;
 		}
 
-		if (test_pt_regs_flag(regs, PIF_SYSCALL) &&
-			addr == offsetof(struct user, regs.gprs[2])) {
-			struct pt_regs *regs = task_pt_regs(child);
-
-			regs->int_code = 0x20000 | (data & 0xffff);
+		if (addr == offsetof(struct user, regs.gprs[2])) {
+			if (test_pt_regs_flag(regs, PIF_SYSCALL))
+				syscall_set_nr(child, regs, data);
 		}
 		*(addr_t *)((addr_t) &regs->psw + addr) = data;
 	} else if (addr < offsetof(struct user, regs.orig_gpr2)) {
Signature · 1 line
2.53.0
author maintainer
#1441 lore raw

PATCH 1439/2151 s390/uprobes: Fix off-by-one bug in emulated PER handling

In reply to Greg Kroah-Hartman

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

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

From: Heiko Carstens <[email protected]>

[ Upstream commit 2ba01cf7b2598571486425a0605f1434909b532d ]

The uprobes code emulates some instructions, and with that also PER storage-alteration handling, in case a debugger is attached.

The PER storage-alteration handling contains an off-by-one bug, which may lead to PER traps which should not happen. Adjust the comparison in sim_stor_event() to fix that.

Fixes 8d1a2427d8fc ("s390/uprobes: fix user space PER events")
---
 arch/s390/kernel/uprobes.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/s390/kernel/uprobes.c +1 -1
index 5b0633ea8d93d..1d088c31cb610 100644
@@ -247,7 +247,7 @@ static void sim_stor_event(struct pt_regs *regs, void *addr, int len)
 		return;
 	if (!(current->thread.per_user.control & PER_EVENT_STORE))
 		return;
-	if ((void *)current->thread.per_user.start > (addr + len))
+	if ((void *)current->thread.per_user.start > (addr + len - 1))
 		return;
 	if ((void *)current->thread.per_user.end < addr)
 		return;
Signature · 1 line
2.53.0
author maintainer
#1442 lore raw

PATCH 1440/2151 nvme-tcp: store and use the callers network namespace

In reply to Greg Kroah-Hartman

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

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

From: Surabhi Gogte <[email protected]>

[ Upstream commit 87a1ac965502858f9207153a92c3aef8ecf6d4ae ]

nvme_tcp_alloc_queue() creates each socket using current->nsproxy->net_ns, which is correct for the initial connect that runs in userspace context. However, the reconnect and error recovery paths run from a workqueue where current netns is a kernel thread in init_net, so sockets created during reconnect end up in a different namespace than the one the controller was originally connected from.

Fix this by capturing the caller's network namespace at controller allocation time. Use ctrl->net for all socket creation so that every queue, on initial connect, reset, or reconnect, is created in the same namespace.

Fixes 3f2304f8c6d6 ("nvme-tcp: add NVMe over TCP host driver")
---
 drivers/nvme/host/tcp.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/nvme/host/tcp.c +6 -1
index fad2f2f969a08..72afdd73939f8 100644
@@ -221,6 +221,7 @@ struct nvme_tcp_ctrl {
 	struct delayed_work	connect_work;
 	struct nvme_tcp_request async_req;
 	u32			io_queues[HCTX_MAX_TYPES];
+	struct net		*net;
 };
 
 static LIST_HEAD(nvme_tcp_ctrl_list);
@@ -1999,7 +2000,7 @@ static int nvme_tcp_alloc_queue(struct nvme_ctrl *nctrl, int qid,
 		queue->cmnd_capsule_len = sizeof(struct nvme_command) +
 						NVME_TCP_ADMIN_CCSZ;
 
-	ret = sock_create_kern(current->nsproxy->net_ns,
+	ret = sock_create_kern(ctrl->net,
 			ctrl->addr.ss_family, SOCK_STREAM,
 			IPPROTO_TCP, &queue->sock);
 	if (ret) {
@@ -2781,6 +2782,7 @@ static void nvme_tcp_free_ctrl(struct nvme_ctrl *nctrl)
 
 	nvmf_free_options(nctrl->opts);
 free_ctrl:
+	put_net(ctrl->net);
 	kfree(ctrl->queues);
 	kfree(ctrl);
 }
@@ -3177,12 +3179,15 @@ static struct nvme_tcp_ctrl *nvme_tcp_alloc_ctrl(struct device *dev,
 		goto out_free_ctrl;
 	}
 
+	ctrl->net = get_net(current->nsproxy->net_ns);
+
 	ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_tcp_ctrl_ops, 0);
 	if (ret)
 		goto out_kfree_queues;
 
 	return ctrl;
 out_kfree_queues:
+	put_net(ctrl->net);
 	kfree(ctrl->queues);
 out_free_ctrl:
 	kfree(ctrl);
Signature · 1 line
2.53.0
author maintainer
#1443 lore raw

PATCH 1441/2151 hisi_acc_vfio_pci: fix NULL dereference in reset_prepare on PF passthrough

In reply to Greg Kroah-Hartman

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

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

From: Longfang Liu <[email protected]>

[ Upstream commit e1d2d60b1f50296828d3f7ff26c45d1a90f142ef ]

When a PF is bound to the driver via driver_override and passed through to a VM, its pf_qm stays NULL. The PCI error handler reset_prepare() runs during open_device through pci_try_reset_function(), before the mig_ops gate, and dereferences the NULL pf_qm for the timeout log, crashing the kernel.

Move the mig_ops check to the entry of reset_prepare() and aer_reset_done() so non-migration devices skip the QM_RESETTING coordination. The dev local resolved &qm->pdev->dev before the gate, so open code it at the dev_err() call where qm is known valid. Also clear set_reset_flag together with QM_RESETTING in aer_reset_done(); the flag was never cleared before, so a later timed-out reset could release a foreign lock.

Fixes b0eed085903e ("hisi_acc_vfio_pci: Add support for VFIO live migration")
Fixes a22099ed7936f ("hisi_acc_vfio_pci: fix VF reset timeout issue")
---
 drivers/vfio/pci/hisilicon/hisi_acc_vfio_pci.c | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)
drivers/vfio/pci/hisilicon/hisi_acc_vfio_pci.c +9 -5
index f141f21566c52..e2ef4e872124b 100644
@@ -1173,14 +1173,16 @@ static void hisi_acc_vf_pci_reset_prepare(struct pci_dev *pdev)
 {
 	struct hisi_acc_vf_core_device *hisi_acc_vdev = hisi_acc_drvdata(pdev);
 	struct hisi_qm *qm = hisi_acc_vdev->pf_qm;
-	struct device *dev = &qm->pdev->dev;
 	u32 delay = 0;
 
+	if (!hisi_acc_vdev->core_device.vdev.mig_ops)
+		return;
+
 	/* All reset requests need to be queued for processing */
 	while (test_and_set_bit(QM_RESETTING, &qm->misc_ctl)) {
 		msleep(1);
 		if (++delay > QM_RESET_WAIT_TIMEOUT) {
-			dev_err(dev, "reset prepare failed\n");
+			dev_err(&qm->pdev->dev, "reset prepare failed\n");
 			return;
 		}
 	}
@@ -1193,12 +1195,14 @@ static void hisi_acc_vf_pci_aer_reset_done(struct pci_dev *pdev)
 	struct hisi_acc_vf_core_device *hisi_acc_vdev = hisi_acc_drvdata(pdev);
 	struct hisi_qm *qm = hisi_acc_vdev->pf_qm;
 
-	if (hisi_acc_vdev->set_reset_flag)
-		clear_bit(QM_RESETTING, &qm->misc_ctl);
-
 	if (!hisi_acc_vdev->core_device.vdev.mig_ops)
 		return;
 
+	if (hisi_acc_vdev->set_reset_flag) {
+		clear_bit(QM_RESETTING, &qm->misc_ctl);
+		hisi_acc_vdev->set_reset_flag = false;
+	}
+
 	mutex_lock(&hisi_acc_vdev->state_mutex);
 	hisi_acc_vf_reset(hisi_acc_vdev);
 	mutex_unlock(&hisi_acc_vdev->state_mutex);
Signature · 1 line
2.53.0
author maintainer
#1444 lore raw

PATCH 1442/2151 nvmet-fc: dont drop the last assoc reference in nvmet_fc_delete_ctrl()

In reply to Greg Kroah-Hartman

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

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

From: Palla Raghunath <[email protected]>

[ Upstream commit 165301b5e2fd765fa05ea1044bbca8ba79820197 ]

syzbot hit a recursive locking report on subsys->lock when a subsystem is unlinked from an FC port.

nvmet_port_del_ctrls() holds subsys->lock while it calls ->delete_ctrl() for each controller. nvmet_fc_delete_ctrl() grabs a reference on the association, queues del_work and then drops the reference. If del_work gets to run to completion before that put, ours is the last reference. Freeing the assoc tears down the queues, the last nvmet_cq_put() drops the last ctrl reference, and nvmet_ctrl_free() goes for subsys->lock again:

WARNING: possible recursive locking detected
...

   nvmet_ctrl_free+0xa6/0x8e0 drivers/nvme/target/core.c:1766
   nvmet_cq_put+0x158/0x200 drivers/nvme/target/core.c:848
   nvmet_fc_target_assoc_free+0x418/0x2220 drivers/nvme/target/fc.c:1173
   nvmet_fc_delete_ctrl+0x717/0x7e0 drivers/nvme/target/fc.c:1581
   nvmet_port_del_ctrls+0xfb/0x150 drivers/nvme/target/core.c:311
   nvmet_port_subsys_drop_link+0x1e8/0x310 drivers/nvme/target/configfs.c:1119

It's a real hang, not only a lockdep warning. I reproduced it with fcloop by putting an msleep() before the put: rm on the configfs link gets stuck in D state for good.

I don't think we need that reference at all. del_work does list_del_rcu() and synchronize_rcu() before it drops the initial reference, so an assoc we find on assoc_list can't go away before rcu_read_unlock(). nvmet_fc_schedule_delete_assoc() doesn't sleep, so just call it inside the RCU section and get rid of the get/put. If the assoc is already being deleted, terminating is set and the call is a no-op, which matches what happened before when the get failed.

With the same msleep() in place the patched kernel unlinks cleanly and the assoc is freed from the workqueue.

---
 drivers/nvme/target/fc.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
drivers/nvme/target/fc.c +9 -6
index 89edffeb10626..bf39e4af43166 100644
@@ -1572,8 +1572,14 @@ nvmet_fc_delete_ctrl(struct nvmet_ctrl *ctrl)
 		list_for_each_entry_rcu(assoc, &tgtport->assoc_list, a_list) {
 			queue = assoc->queues[0];
 			if (queue && queue->nvme_sq.ctrl == ctrl) {
-				if (nvmet_fc_tgt_a_get(assoc))
-					found_ctrl = true;
+				/*
+				 * No assoc reference here: we're called with
+				 * subsys->lock held, and if del_work beat us,
+				 * our put would free the ctrl under that lock.
+				 * RCU keeps the assoc alive until unlock.
+				 */
+				nvmet_fc_schedule_delete_assoc(assoc);
+				found_ctrl = true;
 				break;
 			}
 		}
@@ -1581,11 +1587,8 @@ nvmet_fc_delete_ctrl(struct nvmet_ctrl *ctrl)
 
 		nvmet_fc_tgtport_put(tgtport);
 
-		if (found_ctrl) {
-			nvmet_fc_schedule_delete_assoc(assoc);
-			nvmet_fc_tgt_a_put(assoc);
+		if (found_ctrl)
 			return;
-		}
 
 		spin_lock_irqsave(&nvmet_fc_tgtlock, flags);
 	}
Signature · 1 line
2.53.0
author maintainer
#1445 lore raw

PATCH 1443/2151 nvmet-auth: reject undersized AUTH_SEND payloads

In reply to Greg Kroah-Hartman

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

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

From: Sung Byeongchan <[email protected]>

[ Upstream commit c9359401036e8294c007a10e8c8d8da7030fcc76 ]

nvmet_execute_auth_send() allocates and copies the initiator-supplied transfer length, then reads auth_type and auth_id through a common DHCHAP message pointer. The existing zero and transfer-length checks do not ensure that both common-header bytes are present.

An unauthenticated NVMe/TCP initiator can complete ICReq and admin CONNECT, then send AUTH_SEND with tl equal to one. KASAN reports a one-byte slab out-of-bounds read when auth_id is loaded.

Reject payloads that do not cover the common auth_type/auth_id header before allocating or parsing them. The one-byte trigger and header-minus-one boundary were cleanly rejected in three fixed fresh-boot runs. Exact-header, valid DHCHAP, wrong-type, mismatch, and zero-length controls remained clean, and a following valid AUTH_SEND on the same connection received a response. The touched source is unchanged at 0c2669a9f4a1d607e7591ae50ccf3c432a0aff08, where the patch applies and builds cleanly.

The demonstrated impact is unauthenticated pre-authentication target-kernel denial of service. No disclosure, controlled write, RCE, or LPE was demonstrated. The source reproducer and complete logs are available on request and are not included in this public report.

OpenAI Codex assisted source inspection, test design, patch drafting, and evidence organization.

Fixes db1312dd9548 ("nvmet: implement basic In-Band Authentication")
Assisted-by LLM
---
 drivers/nvme/target/fabrics-cmd-auth.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/nvme/target/fabrics-cmd-auth.c +6 -0
index 61a36fb54e877..846ba4c8ec249 100644
@@ -303,6 +303,12 @@ void nvmet_execute_auth_send(struct nvmet_req *req)
 		nvmet_check_transfer_len(req, tl);
 		return;
 	}
+	if (tl < offsetof(struct nvmf_auth_dhchap_success2_data, rsvd1)) {
+		status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
+		req->error_loc =
+			offsetof(struct nvmf_auth_send_command, tl);
+		goto done;
+	}
 
 	d = kmalloc(tl, GFP_KERNEL);
 	if (!d) {
Signature · 1 line
2.53.0
author maintainer
#1446 lore raw

PATCH 1444/2151 nvme: pass partition flags to passthrough checks

In reply to Greg Kroah-Hartman

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

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

From: Yao Sang <[email protected]>

[ Upstream commit 6908a702955929b0876baac9fdc57070780a76f0 ]

nvme_user_cmd() handles NVME_IOCTL_IO_CMD on namespace block devices, including partitions. It receives flags identifying a partition, but passes 0 to nvme_cmd_allowed(), bypassing the partition guard and allowing unprivileged passthrough commands to access sectors outside the partition.

Pass flags to the permission check, rejecting unprivileged commands on partitions.

Fixes 313c08c72ee7 ("nvme: don't allow unprivileged passthrough on partitions")
---
 drivers/nvme/host/ioctl.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/host/ioctl.c +1 -1
index b3e58de6f5cc5..2c0d00352f919 100644
@@ -343,7 +343,7 @@ static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
 	c.common.cdw14 = cpu_to_le32(cmd.cdw14);
 	c.common.cdw15 = cpu_to_le32(cmd.cdw15);
 
-	if (!nvme_cmd_allowed(ctrl, ns, &c, 0, open_for_write))
+	if (!nvme_cmd_allowed(ctrl, ns, &c, flags, open_for_write))
 		return -EACCES;
 
 	if (cmd.timeout_ms)
Signature · 1 line
2.53.0
author maintainer
#1447 lore raw

PATCH 1445/2151 firmware: cs_dsp: clear dsp->running on the cs_dsp_run() error path

In reply to Greg Kroah-Hartman

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

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

From: Mingxuan Guo <[email protected]>

[ Upstream commit ad6be54d13496a0b5c6d1edeea99504e438cdb7a ]

cs_dsp_run() sets dsp->running = true once the core has been started, but the error path below it only stops and disables the core, leaving the flag set. The first thing that can fail after that point is the post_run client hook, and it is reachable in mainline: wm_adsp registers wm_adsp_event_post_run(), which can fail in wm_adsp_buffer_init().

The core is then stopped and disabled, but dsp->running still reads true, and that stale state is acted on elsewhere: cs_dsp_coeff_write_ctrl() and cs_dsp_coeff_read_ctrl() talk to the DSP when ctl->dsp->running is set, and client drivers use the flag to decide whether the firmware is up (cs35l41 checks cs_dsp.running before its early events and on hibernate/resume).

The flag cannot simply be moved below the hook: post_run hooks such as wm_adsp_event_post_run() read controls while they run, and cs_dsp_coeff_read_ctrl() only goes to the DSP when the flag is set.

Clear the flag on the error path, before the core is stopped - the order cs_dsp_stop() already uses.

Fixes f6bc909e7673 ("firmware: cs_dsp: add driver to support firmware loading on Cirrus Logic DSPs")
---
 drivers/firmware/cirrus/cs_dsp.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/firmware/cirrus/cs_dsp.c +2 -0
index 7ca56777a1da5..15710c97f9fb0 100644
@@ -2911,6 +2911,8 @@ int cs_dsp_run(struct cs_dsp *dsp)
 	return 0;
 
 err:
+	dsp->running = false;
+
 	if (dsp->ops->stop_core)
 		dsp->ops->stop_core(dsp);
 	if (dsp->ops->disable_core)
Signature · 1 line
2.53.0
author maintainer
#1448 lore raw

PATCH 1446/2151 ASoC: amd: acp: Fix .close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 2c3400aa9f397da48a6760f5e84438973e01a00c ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from acp_dma_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes 623621a9f9e1 ("ASoC: amd: Add common framework to support I2S on ACP SOC")
---
 sound/soc/amd/acp/acp-platform.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/amd/acp/acp-platform.c +1 -1
index b25ac5612808c..861411c4a75c5 100644
@@ -248,7 +248,7 @@ static int acp_dma_open(struct snd_soc_component *component, struct snd_pcm_subs
 	list_add_tail(&stream->list, &chip->stream_list);
 	spin_unlock_irq(&chip->acp_lock);
 
-	return ret;
+	return 0;
 }
 
 static int acp_dma_hw_params(struct snd_soc_component *component,
Signature · 1 line
2.53.0
author maintainer
#1449 lore raw

PATCH 1447/2151 ASoC: amd: ps: Fix acp63_pdm_dma_close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 172888114dda96492d40e4a6e0ed16146cb76e2b ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from acp63_pdm_dma_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes 5137305662ef ("ASoC: amd: add acp6.2 pdm driver dma ops")
---
 sound/soc/amd/ps/ps-pdm-dma.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/amd/ps/ps-pdm-dma.c +1 -1
index 9cfbe05ad9963..1e69cb05c8832 100644
@@ -211,7 +211,7 @@ static int acp63_pdm_dma_open(struct snd_soc_component *component,
 
 	pdm_data->acp63_base = adata->acp63_base;
 	runtime->private_data = pdm_data;
-	return ret;
+	return 0;
 }
 
 static int acp63_pdm_dma_hw_params(struct snd_soc_component *component,
Signature · 1 line
2.53.0
author maintainer
#1450 lore raw

PATCH 1448/2151 ASoC: amd: ps: Fix acp63_sdw_dma_close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 45dd2b22ea8934ed69dd05e6ecbf3c66ac3baebf ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from acp63_sdw_dma_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes f722917350ee ("ASoC: amd: ps: add SoundWire dma driver dma ops")
---
 sound/soc/amd/ps/ps-sdw-dma.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/amd/ps/ps-sdw-dma.c +1 -1
index 5449323e2728c..ce55c6fe5f932 100644
@@ -337,7 +337,7 @@ static int acp63_sdw_dma_open(struct snd_soc_component *component,
 	stream->stream_id = cpu_dai->id;
 	stream->instance = amd_manager->instance;
 	runtime->private_data = stream;
-	return ret;
+	return 0;
 }
 
 static int acp63_sdw_dma_hw_params(struct snd_soc_component *component,
Signature · 1 line
2.53.0
author maintainer
#1451 lore raw

PATCH 1449/2151 ASoC: amd: raven: Fix acp3x_dma_close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 37ceef26df57c4a86a5e984b1951995aa96d4342 ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from acp3x_dma_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes 703a6e22888b ("ASoC: amd: Enabling I2S instance in DMA and DAI")
---
 sound/soc/amd/raven/acp3x-pcm-dma.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/amd/raven/acp3x-pcm-dma.c +1 -1
index bb9ed52d744d3..3ba58a7795973 100644
@@ -237,7 +237,7 @@ static int acp3x_dma_open(struct snd_soc_component *component,
 
 	i2s_data->acp3x_base = adata->acp3x_base;
 	runtime->private_data = i2s_data;
-	return ret;
+	return 0;
 }
 
 
Signature · 1 line
2.53.0
author maintainer
#1452 lore raw

PATCH 1450/2151 ASoC: amd: renoir: Fix acp_pdm_dma_close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit a92571113ef297840270e4d8d4263a842302c9c4 ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from acp_pdm_dma_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes 4a767b1d039a ("ASoC: amd: add acp3x pdm driver dma ops")
---
 sound/soc/amd/renoir/acp3x-pdm-dma.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/amd/renoir/acp3x-pdm-dma.c +1 -1
index ecb4b79520135..f89ba818075cc 100644
@@ -233,7 +233,7 @@ static int acp_pdm_dma_open(struct snd_soc_component *component,
 
 	pdm_data->acp_base = adata->acp_base;
 	runtime->private_data = pdm_data;
-	return ret;
+	return 0;
 }
 
 static int acp_pdm_dma_hw_params(struct snd_soc_component *component,
Signature · 1 line
2.53.0
author maintainer
#1453 lore raw

PATCH 1451/2151 ASoC: amd: vangogh: Fix acp5x_dma_close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 38559fcd1c518a33055ef0a2cf7c04b57bfa9215 ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from acp5x_dma_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes cab396d8b22c ("ASoC: amd: add ACP5x pcm dma driver ops")
---
 sound/soc/amd/vangogh/acp5x-pcm-dma.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/amd/vangogh/acp5x-pcm-dma.c +1 -1
index aa47268994345..bd260634f4e49 100644
@@ -231,7 +231,7 @@ static int acp5x_dma_open(struct snd_soc_component *component,
 	}
 	i2s_data->acp5x_base = adata->acp5x_base;
 	runtime->private_data = i2s_data;
-	return ret;
+	return 0;
 }
 
 static int acp5x_dma_hw_params(struct snd_soc_component *component,
Signature · 1 line
2.53.0
author maintainer
#1454 lore raw

PATCH 1452/2151 ASoC: amd: yc: Fix acp6x_pdm_dma_close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 06654a3ef5137719be880a6cd12bd453050eafc5 ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from acp6x_pdm_dma_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes ceb4fcc13ae5 ("ASoC: amd: add acp6x pdm driver dma ops")
---
 sound/soc/amd/yc/acp6x-pdm-dma.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/amd/yc/acp6x-pdm-dma.c +1 -1
index 167cd792d33da..61d685ca82f07 100644
@@ -209,7 +209,7 @@ static int acp6x_pdm_dma_open(struct snd_soc_component *component,
 
 	pdm_data->acp6x_base = adata->acp6x_base;
 	runtime->private_data = pdm_data;
-	return ret;
+	return 0;
 }
 
 static int acp6x_pdm_dma_hw_params(struct snd_soc_component *component,
Signature · 1 line
2.53.0
author maintainer
#1455 lore raw

PATCH 1453/2151 ASoC: atmel: atmel-pcm-pdc: Fix atmel_pcm_close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 50aaca643038774b6779c911c4f96bc7e0d607e9 ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from atmel_pcm_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes 92dfa6198623 ("ASoC: atmel-pcm: split into two file")
---
 sound/soc/atmel/atmel-pcm-pdc.c | 2 ++
 1 file changed, 2 insertions(+)
sound/soc/atmel/atmel-pcm-pdc.c +2 -0
index 7db8df85c54f3..ea834d3fd8c3a 100644
@@ -295,6 +295,8 @@ static int atmel_pcm_open(struct snd_soc_component *component,
 	}
 	runtime->private_data = prtd;
 
+	return 0;
+
  out:
 	return ret;
 }
Signature · 1 line
2.53.0
author maintainer
#1456 lore raw

PATCH 1454/2151 ASoC: imx-pcm-rpmsg: Fix imx_rpmsg_pcm_close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 85e56c3bbb7e8ea4626f8653afaef0d79d9cb7ba ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from imx_rpmsg_pcm_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes 3c00eceb2a53 ("ASoC: imx-pcm-rpmsg: Add platform driver for audio base on rpmsg")
---
 sound/soc/fsl/imx-pcm-rpmsg.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/fsl/imx-pcm-rpmsg.c +1 -1
index edab68ae83665..b269607d2fac1 100644
@@ -278,7 +278,7 @@ static int imx_rpmsg_pcm_open(struct snd_soc_component *component,
 	info->stream_timer[substream->stream].substream = substream;
 	timer_setup(&info->stream_timer[substream->stream].timer,
 		    imx_rpmsg_timer_callback, 0);
-	return ret;
+	return 0;
 }
 
 static int imx_rpmsg_pcm_close(struct snd_soc_component *component,
Signature · 1 line
2.53.0
author maintainer
#1457 lore raw

PATCH 1455/2151 ASoC: intel: atom: Use __free(kfree) for stream pointer

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 4889a8a73f65b8e4feb49ea434b8a41806513574 ]

Declare 'stream' with __free(kfree) so it is automatically freed when leaving scope. This allows direct returns from error paths and removes the explicit kfree(stream) call.
Set 'stream' to NULL after ownership has been transferred to runtime->private_data to prevent it from being freed on the success path.

This cleanup is a preparation step for upcoming locking changes.

Stable-dep-of: e3bb57581104 ("ASoC: intel: atom: Fix .shutdown() being skipped on rollback")

---
 sound/soc/intel/atom/sst-mfld-platform-pcm.c | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)
sound/soc/intel/atom/sst-mfld-platform-pcm.c +14 -6
index 373d68b4cf88f..516b480559026 100644
@@ -11,6 +11,7 @@
  */
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 
+#include <linux/cleanup.h>
 #include <linux/slab.h>
 #include <linux/io.h>
 #include <linux/module.h>
@@ -304,7 +305,7 @@ static int sst_media_open(struct snd_pcm_substream *substream,
 {
 	int ret_val = 0;
 	struct snd_pcm_runtime *runtime = substream->runtime;
-	struct sst_runtime_stream *stream;
+	struct sst_runtime_stream *stream __free(kfree) = NULL;
 
 	stream = kzalloc(sizeof(*stream), GFP_KERNEL);
 	if (!stream)
@@ -330,7 +331,7 @@ static int sst_media_open(struct snd_pcm_substream *substream,
 
 	ret_val = power_up_sst(stream);
 	if (ret_val < 0)
-		goto out_power_up;
+		return ret_val;
 
 	/*
 	 * Make sure the period to be multiple of 1ms to align the
@@ -347,12 +348,19 @@ static int sst_media_open(struct snd_pcm_substream *substream,
 	snd_pcm_hw_constraint_step(substream->runtime, 0,
 			   SNDRV_PCM_HW_PARAM_PERIODS, 2);
 
-	return snd_pcm_hw_constraint_integer(runtime,
-			 SNDRV_PCM_HW_PARAM_PERIODS);
+	ret_val = snd_pcm_hw_constraint_integer(runtime,
+						SNDRV_PCM_HW_PARAM_PERIODS);
+
+	if (ret_val < 0)
+		return ret_val;
+
+	stream = NULL;
+
+	return ret_val;
+
 out_ops:
 	mutex_unlock(&sst_lock);
-out_power_up:
-	kfree(stream);
+
 	return ret_val;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1458 lore raw

PATCH 1456/2151 ASoC: Intel: atom: Use scoped_guard() for scoped locking

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 08d2d5e683e85a7dc33c1abfd50fdc380bfafb5a ]

Clean up the code using scoped_guard() for mutex locks. Merely code refactoring, and no behavior change.

Stable-dep-of: e3bb57581104 ("ASoC: intel: atom: Fix .shutdown() being skipped on rollback")

---
 sound/soc/intel/atom/sst-atom-controls.c     | 38 ++++++++++----------
 sound/soc/intel/atom/sst-mfld-platform-pcm.c | 20 ++++-------
 2 files changed, 27 insertions(+), 31 deletions(-)
sound/soc/intel/atom/sst-atom-controls.c +20 -18
index 38116c7587174..ec1dd9aec2fa1 100644
@@ -761,27 +761,29 @@ int sst_handle_vb_timer(struct snd_soc_dai *dai, bool enable)
 			return ret;
 	}
 
-	mutex_lock(&drv->lock);
-	if (enable)
-		timer_usage++;
-	else
-		timer_usage--;
-
-	/*
-	 * Send the command only if this call is the first enable or last
-	 * disable
-	 */
-	if ((enable && (timer_usage == 1)) ||
-	    (!enable && (timer_usage == 0))) {
-		ret = sst_fill_and_send_cmd_unlocked(drv, SST_IPC_IA_CMD,
-				SST_FLAG_BLOCKED, SST_TASK_SBA, 0, &cmd,
-				sizeof(cmd.header) + cmd.header.length);
-		if (ret && enable) {
+	scoped_guard(mutex, &drv->lock) {
+		if (enable)
+			timer_usage++;
+		else
 			timer_usage--;
-			enable  = false;
+
+		/*
+		 * Send the command only if this call is the first enable or last
+		 * disable
+		 */
+		if ((enable && timer_usage == 1) ||
+		    (!enable && timer_usage == 0)) {
+			ret = sst_fill_and_send_cmd_unlocked(drv, SST_IPC_IA_CMD,
+							     SST_FLAG_BLOCKED,
+							     SST_TASK_SBA, 0, &cmd,
+							     sizeof(cmd.header) +
+							     cmd.header.length);
+			if (ret && enable) {
+				timer_usage--;
+				enable  = false;
+			}
 		}
 	}
-	mutex_unlock(&drv->lock);
 
 	if (!enable)
 		sst->ops->power(sst->dev, false);
sound/soc/intel/atom/sst-mfld-platform-pcm.c +7 -13
index 516b480559026..2feb09f90f8e6 100644
@@ -313,15 +313,14 @@ static int sst_media_open(struct snd_pcm_substream *substream,
 	spin_lock_init(&stream->status_lock);
 
 	/* get the sst ops */
-	mutex_lock(&sst_lock);
-	if (!sst ||
-	    !try_module_get(sst->dev->driver->owner)) {
-		dev_err(dai->dev, "no device available to run\n");
-		ret_val = -ENODEV;
-		goto out_ops;
+	scoped_guard(mutex, &sst_lock) {
+		if (!sst ||
+		    !try_module_get(sst->dev->driver->owner)) {
+			dev_err(dai->dev, "no device available to run\n");
+			return -ENODEV;
+		}
+		stream->ops = sst->ops;
 	}
-	stream->ops = sst->ops;
-	mutex_unlock(&sst_lock);
 
 	stream->stream_info.str_id = 0;
 
@@ -356,11 +355,6 @@ static int sst_media_open(struct snd_pcm_substream *substream,
 
 	stream = NULL;
 
-	return ret_val;
-
-out_ops:
-	mutex_unlock(&sst_lock);
-
 	return ret_val;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1459 lore raw

PATCH 1457/2151 ASoC: intel: atom: Fix .shutdown() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit e3bb575811042ca30ac9b7b4dacc74aab8efa512 ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from sst_media_open(). ASoC only marks the DAI as started when .startup() returns 0, so .shutdown() can be skipped on rollback.

Return 0 explicitly on success.

Fixes 4889a8a73f65 ("ASoC: intel: atom: Use __free(kfree) for stream pointer")
Fixes 6cc0f4e63994 ("ASoC: Intel: mfld_pcm: move stream handling to dai_ops")
---
 sound/soc/intel/atom/sst-mfld-platform-pcm.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/intel/atom/sst-mfld-platform-pcm.c +1 -1
index 2feb09f90f8e6..d546915534dc9 100644
@@ -355,7 +355,7 @@ static int sst_media_open(struct snd_pcm_substream *substream,
 
 	stream = NULL;
 
-	return ret_val;
+	return 0;
 }
 
 static void sst_media_close(struct snd_pcm_substream *substream,
Signature · 1 line
2.53.0
author maintainer
#1460 lore raw

PATCH 1458/2151 ASoC: renesas: msiof: Fix msiof_close() being skipped on rollback

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit b7c58a55fd9b71c0b11b0365fdf53f49702c39b5 ]

snd_pcm_hw_constraint_integer() may return 1, which is then returned from msiof_open(). ASoC only marks the component as opened when .open() returns 0, so .close() can be skipped on rollback.

Return 0 explicitly on success.

Fixes c61caec22820 ("ASoC: renesas: add MSIOF sound support")
---
 sound/soc/renesas/rcar/msiof.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
sound/soc/renesas/rcar/msiof.c +4 -2
index f2addfbac9237..8699914c8a71b 100644
@@ -432,10 +432,12 @@ static int msiof_open(struct snd_soc_component *component,
 	ret = snd_pcm_hw_constraint_integer(substream->runtime, SNDRV_PCM_HW_PARAM_PERIODS);
 
 open_err_dma:
-	if (ret < 0)
+	if (ret < 0) {
 		dma_release_channel(chan);
+		return ret;
+	}
 
-	return ret;
+	return 0;
 }
 
 static int msiof_close(struct snd_soc_component *component,
Signature · 1 line
2.53.0
author maintainer
#1461 lore raw

PATCH 1459/2151 ASoC: atmel-i2s: fix MCK generator error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 2e2da92de9bffd2cdbb9a2558fe60de7f1bb09e3 ]

Disable the gclk and reset the MCK configuration when an error occurs while enabling the MCK generator.

This prevents the gclk from remaining enabled after a failed clock configuration.

Fixes 73ad0df57290 ("ASoC: atmel-i2s: Remove unnecessary audio PLL clock (aclk)")
---
 sound/soc/atmel/atmel-i2s.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
sound/soc/atmel/atmel-i2s.c +13 -3
index 762199faf872e..f1f8a2d0008ce 100644
@@ -466,11 +466,21 @@ static int atmel_i2s_switch_mck_generator(struct atmel_i2s_dev *dev,
 	mr |= ATMEL_I2SC_MR_IMCKMODE_I2SMCK;
 	ret = regmap_update_bits(dev->regmap, ATMEL_I2SC_MR, mr_mask, mr);
 	if (ret)
-		return ret;
+		goto err_disable_gclk;
 
 	/* Finally enable the I2S Master Clock generator. */
-	return regmap_write(dev->regmap, ATMEL_I2SC_CR,
-			    ATMEL_I2SC_CR_CKEN);
+	ret = regmap_write(dev->regmap, ATMEL_I2SC_CR, ATMEL_I2SC_CR_CKEN);
+	if (ret)
+		goto err_reset_mr;
+
+	return 0;
+
+err_reset_mr:
+	regmap_update_bits(dev->regmap, ATMEL_I2SC_MR, mr_mask, 0);
+err_disable_gclk:
+	clk_disable_unprepare(dev->gclk);
+
+	return ret;
 }
 
 static int atmel_i2s_trigger(struct snd_pcm_substream *substream, int cmd,
Signature · 1 line
2.53.0
author maintainer
#1462 lore raw

PATCH 1460/2151 ASoC: atmel-i2s: use optional API for muxclk

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit be952abd69c1f2c845e42e72147751e4c910cd81 ]

The muxclk is an optional clock according to the device tree binding.

Use devm_clk_get_optional() to handle the optional muxclk instead of handling the missing clock explicitly.

When muxclk is not available, devm_clk_get_optional() returns NULL. clk_set_parent() returns 0 when passed NULL, preserving the existing behavior.

Unlike the existing code, errors other than -EPROBE_DEFER are now returned instead of being silently ignored.

Fixes b543e467d1a9 ("ASoC: atmel-i2s: add driver for the new Atmel I2S controller")
---
 sound/soc/atmel/atmel-i2s.c | 16 +++++-----------
 1 file changed, 5 insertions(+), 11 deletions(-)
sound/soc/atmel/atmel-i2s.c +5 -11
index f1f8a2d0008ce..3135445805ecf 100644
@@ -585,21 +585,15 @@ static int atmel_i2s_sama5d2_mck_init(struct atmel_i2s_dev *dev,
 				      struct device_node *np)
 {
 	struct clk *muxclk;
-	int err;
 
 	if (!dev->gclk)
 		return 0;
 
-	/* muxclk is optional, so we return error for probe defer only */
-	muxclk = devm_clk_get(dev->dev, "muxclk");
-	if (IS_ERR(muxclk)) {
-		err = PTR_ERR(muxclk);
-		if (err == -EPROBE_DEFER)
-			return -EPROBE_DEFER;
-		dev_dbg(dev->dev,
-			"failed to get the I2S clock control: %d\n", err);
-		return 0;
-	}
+	/* muxclk is optional */
+	muxclk = devm_clk_get_optional(dev->dev, "muxclk");
+	if (IS_ERR(muxclk))
+		return dev_err_probe(dev->dev, PTR_ERR(muxclk),
+				     "failed to get the I2S clock control\n");
 
 	return clk_set_parent(muxclk, dev->gclk);
 }
Signature · 1 line
2.53.0
author maintainer
#1463 lore raw

PATCH 1461/2151 ASoC: atmel-i2s: use optional API for gclk

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit b431a055fb7688c0d3725fa3c55aeef852991178 ]

The gclk is an optional clock according to the device tree binding.

Use devm_clk_get_optional() to handle the optional gclk directly.

Unlike the existing code, errors other than -EPROBE_DEFER are now returned instead of being silently ignored.

Fixes 73ad0df57290 ("ASoC: atmel-i2s: Remove unnecessary audio PLL clock (aclk)")
---
 sound/soc/atmel/atmel-i2s.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
sound/soc/atmel/atmel-i2s.c +4 -7
index 3135445805ecf..eb219223ece20 100644
@@ -666,13 +666,10 @@ static int atmel_i2s_probe(struct platform_device *pdev)
 	}
 
 	/* Get audio clock to generate the I2S Master Clock (I2S_MCK) */
-	dev->gclk = devm_clk_get(&pdev->dev, "gclk");
-	if (IS_ERR(dev->gclk)) {
-		if (PTR_ERR(dev->gclk) == -EPROBE_DEFER)
-			return -EPROBE_DEFER;
-		/* Master Mode not supported */
-		dev->gclk = NULL;
-	}
+	dev->gclk = devm_clk_get_optional(&pdev->dev, "gclk");
+	if (IS_ERR(dev->gclk))
+		return PTR_ERR(dev->gclk);
+
 	dev->dev = &pdev->dev;
 	dev->regmap = regmap;
 	platform_set_drvdata(pdev, dev);
Signature · 1 line
2.53.0
author maintainer
#1464 lore raw

PATCH 1462/2151 sh: sh7785lcr: Register the PCA9564 controller as I2C bus 0

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit 3b8386ffc0c33b6b5a6a8e64e1487c1adec57dc9 ]

Before commit 44454baa7ca7 ("i2c: Dynamically assign adapter id if it wasn't explictly specified"), a negative ID was replaced by zero, and I2C bus zero was instantiated. Since that commit, a negative ID is passed verbatim, instantiating an I2C bus with a dynamic number. As SH boards still use i2c_register_board_info(0, ...) to register I2C devices, they rely on the I2C bus being bus zero.

The SH7785LCR is the only SH board whose I2C adapter has a negative ID and its PCA9564 controller becomes i2c-1, causing registration of the R2025S/D RTC to fail and hwclock not detecting /dev/rtc0.

Set the platform device ID to 0 so that the adapter is registered as bus zero again.

Fixes 44454baa7ca7 ("i2c: Dynamically assign adapter id if it wasn't explictly specified")
Assisted-by LLM
---
 arch/sh/boards/board-sh7785lcr.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/sh/boards/board-sh7785lcr.c +1 -1
index 25c4968f0d8b0..b93423df582f7 100644
@@ -256,7 +256,7 @@ static struct i2c_pca9564_pf_platform_data i2c_platform_data = {
 
 static struct platform_device i2c_device = {
 	.name		= "i2c-pca-platform",
-	.id		= -1,
+	.id		= 0,
 	.dev		= {
 		.platform_data	= &i2c_platform_data,
 	},
Signature · 1 line
2.53.0
author maintainer
#1465 lore raw

PATCH 1463/2151 spi: spi-qpic-snand: skip BBM copy on regular raw reads

In reply to Greg Kroah-Hartman

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

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

From: Gabor Juhos <[email protected]>

[ Upstream commit 2da46f1e9b980a38bc6afd417322ca4963725e16 ]

Trying to read the raw flash contents with nanddump, the second byte of the OOB area contains 0xff instead of the real data in the flash. This happens because the qcom_spi_read_last_cw() function unconditionally copies the bad block marker into the second byte of the output buffer.

Add a new flag to the controller's private data structure, and set it when only the first two bytes of the OOB area being read in raw mode. Also change the bad block copying code to run only when the flag is set.

This ensures that the SPI NAND framework still can read the BBM bytes, but on regular raw read, the output does not contain the duplicated marker byte.

Fixes 7304d1909080 ("spi: spi-qpic: add driver for QCOM SPI NAND flash Interface")
---
 drivers/spi/spi-qpic-snand.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/spi/spi-qpic-snand.c +13 -1
index 9ac01f53c83b8..4b2e192457938 100644
@@ -111,6 +111,7 @@ struct qpic_spi_nand {
 	__le32 addr2;
 	__le32 cmd;
 	u32 num_cw;
+	bool bbm_read;
 	bool oob_rw;
 	bool page_rw;
 	bool raw_rw;
@@ -433,6 +434,16 @@ static int qcom_spi_ecc_prepare_io_req_pipelined(struct nand_device *nand,
 	if (req->mode == MTD_OPS_RAW)
 		snandc->qspi->raw_rw = true;
 
+	/*
+	 * Try to detect when the SPI NAND framework reads the first
+	 * two bytes of the OOB area searching for bad block marker
+	 * bytes.
+	 */
+	snandc->qspi->bbm_read = req->mode == MTD_OPS_RAW &&
+				 req->type == NAND_PAGE_READ &&
+				 req->dataoffs == 0 && req->datalen == 0 &&
+				 req->ooboffs == 0 && req->ooblen == 2;
+
 	return 0;
 }
 
@@ -637,7 +648,8 @@ static int qcom_spi_read_last_cw(struct qcom_nand_controller *snandc,
 	 * This can be removed once single-byte bad block marker support
 	 * gets implemented in the SPINAND code.
 	 */
-	snandc->data_buffer[bbpos + 1] = snandc->data_buffer[bbpos];
+	if (snandc->qspi->bbm_read)
+		snandc->data_buffer[bbpos + 1] = snandc->data_buffer[bbpos];
 
 	memcpy(op->data.buf.in, snandc->data_buffer + bbpos, op->data.nbytes);
 
Signature · 1 line
2.53.0
author maintainer
#1466 lore raw

PATCH 1464/2151 perf symbol: Fix symbol loading from libbfd

In reply to Greg Kroah-Hartman

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

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

From: Namhyung Kim <[email protected]>

[ Upstream commit f814d9e6cdbef6413a72d6dd6d5e4e79e815cf44 ]

The dso__load() should return a positive number (number of symbols loaded) when it succeded to load symbols. But dso__load_bfd_symbols() only returns 0 and it's hard to check if it actually loaded symbols or not. Let's return the value of dso__has_symbol() and check it in dso__load() so that it can return 1 for success.

Fixes eac9a4342e5447ca ("perf symbols: Try reading the symbol table with libbfd")
Cc Remi Bernon <[email protected]>
---
 tools/perf/tests/pe-file-parsing.c | 2 +-
 tools/perf/util/libbfd.c           | 2 +-
 tools/perf/util/symbol.c           | 4 ++--
 3 files changed, 4 insertions(+), 4 deletions(-)
tools/perf/tests/pe-file-parsing.c +1 -1
index 30c7da79e109b..3979f38bf127c 100644
@@ -59,7 +59,7 @@ static int run_dir(const char *d)
 	TEST_ASSERT_VAL("Failed to get dso", dso);
 
 	ret = dso__load_bfd_symbols(dso, debugfile);
-	TEST_ASSERT_VAL("Failed to load symbols", ret == 0);
+	TEST_ASSERT_VAL("Failed to load symbols", ret > 0);
 
 	dso__sort_by_name(dso);
 	sym = dso__find_symbol_by_name(dso, "main", &idx);
tools/perf/util/libbfd.c +1 -1
index 04e6e96f716d8..47d691e4af323 100644
@@ -428,7 +428,7 @@ int dso__load_bfd_symbols(struct dso *dso, const char *debugfile)
 	symbols__fixup_duplicate(dso__symbols(dso));
 	dso__set_adjust_symbols(dso, true);
 
-	err = 0;
+	err = dso__has_symbols(dso);
 out_free:
 	free(symbols);
 out_close:
tools/perf/util/symbol.c +2 -2
index e64668cca6b29..756b318bf6290 100644
@@ -1811,8 +1811,8 @@ int dso__load(struct dso *dso, struct map *map)
 		if (nsexit)
 			nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
 
-		if (bfdrc == 0) {
-			ret = 0;
+		if (bfdrc > 0) {
+			ret = 1;
 			break;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#1467 lore raw

PATCH 1465/2151 perf symbol: Add missing symsrc__destroy() for libbfd

In reply to Greg Kroah-Hartman

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

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

From: Namhyung Kim <[email protected]>

[ Upstream commit 35477b351e6a697c85dc7d37e5081621889f8e40 ]

When libbfd loaded symbols and there's a pending syms_ss, it'd be lost or overwrite existing symbols. Let's destroy it before breaking the loop so that it can safely return from the function.

Fixes eac9a4342e5447ca ("perf symbols: Try reading the symbol table with libbfd")
Cc Remi Bernon <[email protected]>
---
 tools/perf/util/symbol.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
tools/perf/util/symbol.c +2 -1
index 756b318bf6290..b7c854b2d43a3 100644
@@ -1813,7 +1813,7 @@ int dso__load(struct dso *dso, struct map *map)
 
 		if (bfdrc > 0) {
 			ret = 1;
-			break;
+			goto out_destroy;
 		}
 
 		if (!is_reg || sirc < 0)
@@ -1878,6 +1878,7 @@ int dso__load(struct dso *dso, struct map *map)
 			ret += nr_plt;
 	}
 
+out_destroy:
 	for (; ss_pos > 0; ss_pos--)
 		symsrc__destroy(&ss_[ss_pos - 1]);
 out_free:
Signature · 1 line
2.53.0
author maintainer
#1468 lore raw

PATCH 1466/2151 spi: axi-spi-engine: fix stale SYNC IRQ pending

In reply to Greg Kroah-Hartman

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

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

From: Jonathan Santos <[email protected]>

[ Upstream commit ea29c686f96adcb505071ef228ba8047dc951fac ]

spi_engine_setup() sends a SYNC(1) command and polls SYNC_ID to confirm it was parsed by the FPGA, but never clears the corresponding interrupt pending bit (INT_PENDING[SYNC]). When the first real SPI transfer starts and INT_SYNC is enabled, that stale pending bit fires immediately, causing the IRQ handler to see the leftover SYNC_ID from setup, match it against the current transfer's ID, and prematurely signal completion before the hardware finishes.

This race manifests at low SPI clock frequencies (~2-3 MHz), where the FPGA takes long enough to execute the transfer that handler is parsed before it finishes. At higher SCLK rates the transfer completes fast enough that the issue is masked.

Fix this by clearing INT_PENDING[SYNC] after the polled SYNC, ensuring no stale interrupt is left pending.

---
 drivers/spi/spi-axi-spi-engine.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/spi/spi-axi-spi-engine.c +10 -2
index e06f412190fd2..6a2128459f559 100644
@@ -787,6 +787,7 @@ static int spi_engine_setup(struct spi_device *device)
 	struct spi_controller *host = device->controller;
 	struct spi_engine *spi_engine = spi_controller_get_devdata(host);
 	unsigned int reg;
+	int ret;
 
 	if (device->mode & SPI_CS_HIGH)
 		spi_engine->cs_inv |= BIT(spi_get_chipselect(device, 0));
@@ -809,8 +810,15 @@ static int spi_engine_setup(struct spi_device *device)
 	writel_relaxed(SPI_ENGINE_CMD_SYNC(1),
 		       spi_engine->base + SPI_ENGINE_REG_CMD_FIFO);
 
-	return readl_relaxed_poll_timeout(spi_engine->base + SPI_ENGINE_REG_SYNC_ID,
-					  reg, reg == 1, 1, 1000);
+	ret = readl_relaxed_poll_timeout(spi_engine->base + SPI_ENGINE_REG_SYNC_ID,
+					 reg, reg == 1, 1, 1 * USEC_PER_MSEC);
+
+	/* Clear the stale SYNC pending bit so it doesn't fire when the IRQ is later enabled. */
+	writel_relaxed(SPI_ENGINE_INT_SYNC, spi_engine->base + SPI_ENGINE_REG_INT_PENDING);
+	/* Read back to flush posted write. */
+	readl_relaxed(spi_engine->base + SPI_ENGINE_REG_INT_PENDING);
+
+	return ret;
 }
 
 static int spi_engine_transfer_one_message(struct spi_controller *host,
Signature · 1 line
2.53.0
author maintainer
#1469 lore raw

PATCH 1467/2151 spi: axi-spi-engine: fix stale SYNC IRQ pending in trigger_enable

In reply to Greg Kroah-Hartman

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

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

From: Jonathan Santos <[email protected]>

[ Upstream commit 18febc10a3538b9baa2f6e4481b434f20fdbd93c ]

spi_engine_trigger_enable() sends SYNC(1) and polls SYNC_ID, it never clears the INT_PENDING[SYNC] bit afterward. This leaves a stale pending interrupt that can fire spuriously when INT_SYNC is later enabled.

Simillarly to the fix on spi_engine_setup(), clear INT_PENDING[SYNC] after polling the SYNC_ID.

---
 drivers/spi/spi-axi-spi-engine.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/spi/spi-axi-spi-engine.c +7 -1
index 6a2128459f559..47928e956dd4d 100644
@@ -914,7 +914,13 @@ static int spi_engine_trigger_enable(struct spi_offload *offload)
 		spi_engine->base + SPI_ENGINE_REG_CMD_FIFO);
 
 	ret = readl_relaxed_poll_timeout(spi_engine->base + SPI_ENGINE_REG_SYNC_ID,
-					 reg, reg == 1, 1, 1000);
+					 reg, reg == 1, 1, 1 * USEC_PER_MSEC);
+
+	/* Clear the stale SYNC pending bit so it doesn't fire when the IRQ is later enabled */
+	writel_relaxed(SPI_ENGINE_INT_SYNC, spi_engine->base + SPI_ENGINE_REG_INT_PENDING);
+	/* Read back to flush posted write. */
+	readl_relaxed(spi_engine->base + SPI_ENGINE_REG_INT_PENDING);
+
 	if (ret)
 		return ret;
 
Signature · 1 line
2.53.0