Skip to contentSkip to conversation

6.12.117-rc1 review

PATCH In review Greg Kroah-Hartman 12 participants 1,550 messages Nov 7 – Nov 9 Page 10 of 11

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

PATCH 1274/1536 f2fs: allow pinning empty compressed files

In reply to Greg Kroah-Hartman

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

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

From: Joanne Chang <[email protected]>

[ Upstream commit 2eebc31ae5f53e1066bb6238c8087c23b688ad17 ]

Commit a64a3fec11e7 ("f2fs: force out-place update for all writes on compressed file") updated f2fs_should_update_outplace() to always return true for compressed files. However, this function is also called during f2fs_ioc_set_pin_file() validation, so pinning an empty file with compression enabled now fails with -EINVAL before the compression flag can be stripped.

Fix this by guarding the f2fs_compressed_file(inode) check with fio in f2fs_should_update_outplace(). This preserves forced OPU for actual compressed writes (fio != NULL), while allowing f2fs_ioc_set_pin_file() (fio == NULL) to proceed to f2fs_disable_compressed_file(inode).

Fixes a64a3fec11e7 ("f2fs: force out-place update for all writes on compressed file")
Assisted-by LLM
---
 fs/f2fs/data.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/f2fs/data.c +1 -1
index 539b0324ccc49..47743a0bdede5 100644
@@ -2673,7 +2673,7 @@ bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio)
 	 * If IO comes from compressed write path and fallback to raw write,
 	 * force out‑place to prevent metadata‑data inconsistency.
 	 */
-	if (f2fs_compressed_file(inode))
+	if (fio && f2fs_compressed_file(inode))
 		return true;
 
 	/* swap file is migrating in aligned write mode */
Signature · 1 line
2.53.0
author maintainer
#1278 lore raw

PATCH 1275/1536 f2fs: read i_size once in f2fs_vm_page_mkwrite

In reply to Greg Kroah-Hartman

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

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

From: Nanzhe Zhao <[email protected]>

[ Upstream commit c04f209773ecb31e592cababce0d6658ee0b8d58 ]

f2fs_vm_page_mkwrite() reads i_size twice: once to check whether the folio is partially beyond EOF, and once to calculate the offset for folio_zero_segment(). But a concurrent buffered write can extend isize and cause the following race condition to corrupt data:

buffered write writes [0,3500)

CPU0 (write fault) CPU1 (buffered write)
---- ----
f2fs_vm_page_mkwrite()
folio_lock(folio)
if (((loff_t)(folio->index + 1) << PAGE_SHIFT) >
i_size_read(inode))
/* i_size_read() = 3500 */

                                           write(fd, buf, 200, 4096)
                                           /* writes into page1, does not
                                              wait for folio lock */
                                           i_size_write(inode, 4296)

offset = i_size_read(inode) & ~PAGE_MASK
/* i_size_read() = 4296, offset = 200 */ folio_zero_segment(folio, offset, folio_size(folio)) /* valid data [200, 3500) is zeroed */

Fix this by reading i_size once and using the same value for both the EOF check and the zeroing offset.

---
 fs/f2fs/file.c | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
fs/f2fs/file.c +10 -4
index 5f5ccf2676964..e85d22daaafbc 100644
@@ -123,6 +123,7 @@ static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf)
 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 	struct dnode_of_data dn;
 	bool need_alloc = !f2fs_is_pinned_file(inode);
+	loff_t isize;
 	int err = 0;
 	vm_fault_t ret;
 
@@ -177,8 +178,14 @@ static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf)
 	filemap_invalidate_lock_shared(inode->i_mapping);
 
 	folio_lock(folio);
+	/*
+	 * A concurrent buffered write can extend isize, so we store isize in a
+	 * local variable to let the zeroing offset match the EOF check below.
+	 */
+	isize = i_size_read(inode);
+
 	if (unlikely(folio->mapping != inode->i_mapping ||
-			folio_pos(folio) > i_size_read(inode) ||
+			folio_pos(folio) > isize ||
 			!folio_test_uptodate(folio))) {
 		folio_unlock(folio);
 		err = -EFAULT;
@@ -208,11 +215,10 @@ static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf)
 	f2fs_wait_on_block_writeback(inode, dn.data_blkaddr);
 
 	/* page is wholly or partially inside EOF */
-	if (((loff_t)(folio->index + 1) << PAGE_SHIFT) >
-						i_size_read(inode)) {
+	if (((loff_t)(folio->index + 1) << PAGE_SHIFT) > isize) {
 		loff_t offset;
 
-		offset = i_size_read(inode) & ~PAGE_MASK;
+		offset = isize & ~PAGE_MASK;
 		folio_zero_segment(folio, offset, folio_size(folio));
 	}
 	folio_mark_dirty(folio);
Signature · 1 line
2.53.0
author maintainer
#1279 lore raw

PATCH 1276/1536 f2fs: check every cur_*_segno[] entry on readonly images

In reply to Greg Kroah-Hartman

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

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

From: Kaixuan Li <[email protected]>

[ Upstream commit 9c4ee79190c8c23a9fb5c07d3bc87eaac514b2bb ]

sanity_check_ckpt() bounds-checks cur_node_segno[] and cur_data_segno[] against main_segs, but on an image with the RO feature the goto that skips the duplicate-segno cross-checks also leaves the enclosing loop, so only index 0 of each array is ever checked.

An unchecked index reaches __set_sit_entry_type() through build_curseg() -> reset_curseg(), which writes se->type through &sit_i->sentries[segno]. With segment_count_main 120 and cur_data_segno[1] set to 200, KASAN reports three out-of-bounds writes during mount and the mount then succeeds.

Use continue so every index is bounds-checked, and skip the node-vs-data cross-check explicitly, which is the other thing the old goto skipped.

Fixes a7d9fe3c3388 ("f2fs: support RO feature")
---
 fs/f2fs/super.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
fs/f2fs/super.c +6 -3
index 1e5aea6352497..31724ab224d4a 100644
@@ -3831,7 +3831,7 @@ int f2fs_sanity_check_ckpt(struct f2fs_sb_info *sbi)
 			return 1;
 
 		if (f2fs_sb_has_readonly(sbi))
-			goto check_data;
+			continue;
 
 		for (j = i + 1; j < NR_CURSEG_NODE_TYPE; j++) {
 			if (le32_to_cpu(ckpt->cur_node_segno[i]) ==
@@ -3843,14 +3843,14 @@ int f2fs_sanity_check_ckpt(struct f2fs_sb_info *sbi)
 			}
 		}
 	}
-check_data:
+
 	for (i = 0; i < NR_CURSEG_DATA_TYPE; i++) {
 		if (le32_to_cpu(ckpt->cur_data_segno[i]) >= main_segs ||
 			le16_to_cpu(ckpt->cur_data_blkoff[i]) >= blocks_per_seg)
 			return 1;
 
 		if (f2fs_sb_has_readonly(sbi))
-			goto skip_cross;
+			continue;
 
 		for (j = i + 1; j < NR_CURSEG_DATA_TYPE; j++) {
 			if (le32_to_cpu(ckpt->cur_data_segno[i]) ==
@@ -3862,6 +3862,9 @@ int f2fs_sanity_check_ckpt(struct f2fs_sb_info *sbi)
 			}
 		}
 	}
+	if (f2fs_sb_has_readonly(sbi))
+		goto skip_cross;
+
 	for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) {
 		for (j = 0; j < NR_CURSEG_DATA_TYPE; j++) {
 			if (le32_to_cpu(ckpt->cur_node_segno[i]) ==
Signature · 1 line
2.53.0
author maintainer
#1280 lore raw

PATCH 1277/1536 f2fs: fix defragment writeback range truncation on 32-bit

In reply to Greg Kroah-Hartman

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

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

From: Zhan Xusheng <[email protected]>

[ Upstream commit 92154fe28c3701bebf75176dc5522bec62519a8f ]

f2fs_defragment_range() flushes the range it is about to defragment:

	filemap_write_and_wait_range(inode->i_mapping,
				pg_start << PAGE_SHIFT,
				(pg_end << PAGE_SHIFT) - 1);

pg_start and pg_end are pgoff_t, 32 bits on 32-bit kernels, so both shifts are evaluated in 32 bits and truncated before they are widened to the loff_t parameters. pg_end is only capped by the file's page count, so for a file larger than 4 GiB the shift wraps.

For a 5 GiB file pg_end is 1310720 and the range collapses from [0, 5 GiB) to [0, 1 GiB), leaving the rest of the dirty pages unwritten before the blocks are moved. For 8 GiB the shift yields 0, the minus one makes it (loff_t)-1, and the range becomes [0, LLONG_MAX].

The matching call in f2fs_collapse_range() already casts:

	filemap_write_and_wait_range(inode->i_mapping,
				(loff_t)index << PAGE_SHIFT,
				((loff_t)pg_end << PAGE_SHIFT) - 1);

Do the same here. On i386 the shift changes from "shl $0xc,%ecx" to "shld", i.e. from a 32-bit shift to a double-precision one.

Fixes d323d005ac4a ("f2fs: support file defragment")
---
 fs/f2fs/file.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/f2fs/file.c +2 -2
index e85d22daaafbc..8b57b2feafa6d 100644
@@ -2931,8 +2931,8 @@ static int f2fs_defragment_range(struct f2fs_sb_info *sbi,
 
 	/* writeback all dirty pages in the range */
 	err = filemap_write_and_wait_range(inode->i_mapping,
-						pg_start << PAGE_SHIFT,
-						(pg_end << PAGE_SHIFT) - 1);
+						(loff_t)pg_start << PAGE_SHIFT,
+						((loff_t)pg_end << PAGE_SHIFT) - 1);
 	if (err)
 		goto out;
 
Signature · 1 line
2.53.0
author maintainer
#1281 lore raw

PATCH 1278/1536 f2fs: disallow mmap write and data-modifying fallocate on atomic files

In reply to Greg Kroah-Hartman

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

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

From: Daeho Jeong <[email protected]>

[ Upstream commit 06dfe4a7eb696d868b196c2a49873142f19bd862 ]

Stores through a shared writable mapping and fallocate with FALLOC_FL_PUNCH_HOLE, FALLOC_FL_ZERO_RANGE, FALLOC_FL_COLLAPSE_RANGE or FALLOC_FL_INSERT_RANGE do not go through ->write_begin, so they bypass the COW inode and modify the original inode directly. Reject them while the file is in atomic write mode, as fallocate already does for pinned and compressed files. A write fault gets SIGBUS and fallocate gets -EOPNOTSUPP.

fallocate without these flags only preallocates blocks and stays allowed.

f2fs_vm_page_mkwrite() cannot take inode_lock, so check the flag under invalidate_lock, and hold invalidate_lock in f2fs_ioc_start_atomic_write() from the flush until the flag is set. Otherwise a fault could check the flag, then start_atomic_write could flush and set the flag, and the fault would dirty the folio afterwards.

Fixes 3db1de0e582c ("f2fs: change the current atomic write way")
---
 fs/f2fs/file.c | 20 ++++++++++++++++++--
 1 file changed, 18 insertions(+), 2 deletions(-)
fs/f2fs/file.c +18 -2
index 8b57b2feafa6d..cd6e69f09e183 100644
@@ -177,6 +177,17 @@ static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf)
 	file_update_time(vmf->vma->vm_file);
 	filemap_invalidate_lock_shared(inode->i_mapping);
 
+	/*
+	 * mmap stores bypass the COW inode and would break atomicity. Check
+	 * under invalidate_lock: f2fs_ioc_start_atomic_write() holds it while
+	 * flushing dirty folios and setting FI_ATOMIC_FILE, so either it sees
+	 * our dirty folio and writes it back, or we see the flag.
+	 */
+	if (unlikely(f2fs_is_atomic_file(inode))) {
+		err = -EOPNOTSUPP;
+		goto out_sem;
+	}
+
 	folio_lock(folio);
 	/*
 	 * A concurrent buffered write can extend isize, so we store isize in a
@@ -2033,9 +2044,11 @@ static long f2fs_fallocate(struct file *file, int mode,
 
 	/*
 	 * Pinned file should not support partial truncation since the block
-	 * can be used by applications.
+	 * can be used by applications. Atomic files should not either, since
+	 * these modify the original inode directly and break atomicity.
 	 */
-	if ((f2fs_compressed_file(inode) || f2fs_is_pinned_file(inode)) &&
+	if ((f2fs_compressed_file(inode) || f2fs_is_pinned_file(inode) ||
+	     f2fs_is_atomic_file(inode)) &&
 		(mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_COLLAPSE_RANGE |
 			FALLOC_FL_ZERO_RANGE | FALLOC_FL_INSERT_RANGE))) {
 		ret = -EOPNOTSUPP;
@@ -2320,6 +2333,8 @@ static int f2fs_ioc_start_atomic_write(struct file *filp, bool truncate)
 
 	f2fs_down_write(&fi->i_gc_rwsem[WRITE]);
 	f2fs_down_write(&fi->i_gc_rwsem[READ]);
+	/* serialize with f2fs_vm_page_mkwrite(), see the comment there */
+	filemap_invalidate_lock(inode->i_mapping);
 
 	/*
 	 * Should wait end_io to count F2FS_WB_CP_DATA correctly by
@@ -2375,6 +2390,7 @@ static int f2fs_ioc_start_atomic_write(struct file *filp, bool truncate)
 	f2fs_i_size_write(fi->cow_inode, isize);
 
 out_unlock:
+	filemap_invalidate_unlock(inode->i_mapping);
 	f2fs_up_write(&fi->i_gc_rwsem[READ]);
 	f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
 	if (ret)
Signature · 1 line
2.53.0
author maintainer
#1282 lore raw

PATCH 1279/1536 spi: ljca: validate the response length before copying the data

In reply to Greg Kroah-Hartman

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

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

From: Weibin Liu <[email protected]>

[ Upstream commit 0fe4573c822c4c9152e2fd5269ab85410c9e458f ]

ljca_spi_read_write() only checks that the response from the adapter carries the packet header and a non-zero payload length before copying r_packet->len bytes from the response into the transfer buffer.

The payload length is taken from the packet the device sent back and is neither bounded by the number of bytes actually received nor by the size of the requested transfer: a misbehaving adapter can announce a payload larger than what it actually sent, and the memcpy then reads past the end of the 60-byte input buffer and writes past the end of the caller's transfer buffer.

Check that the response carries the full header before reading r_packet->len, then reject responses whose payload is not contained in the data received or is longer than the requested transfer.

Fixes caee8e38da67 ("spi: Add support for Intel LJCA USB SPI driver")
---
 drivers/spi/spi-ljca.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/spi/spi-ljca.c +6 -1
index 1cc1422ddba0b..83a47629f0ae3 100644
@@ -105,7 +105,12 @@ static int ljca_spi_read_write(struct ljca_spi_dev *ljca_spi, const u8 *w_data,
 			    (u8 *)r_packet, LJCA_SPI_BUF_SIZE);
 	if (ret < 0)
 		return ret;
-	else if (ret < sizeof(*r_packet) || r_packet->len <= 0)
+
+	if (ret < sizeof(*r_packet))
+		return -EIO;
+
+	if (!r_packet->len || ret < sizeof(*r_packet) + r_packet->len ||
+	    r_packet->len > len)
 		return -EIO;
 
 	if (r_data)
Signature · 1 line
2.53.0
author maintainer
#1283 lore raw

PATCH 1280/1536 pinctrl: stm32: Fix fwnode reference leak in stm32_gpiolib_register_bank()

In reply to Greg Kroah-Hartman

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

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

From: Ma Ke <[email protected]>

[ Upstream commit 54c66b5e47a9b10cbf4a1efe9b01301b7ffee205 ]

stm32_gpiolib_register_bank() walks the "gpio-ranges" property with fwnode_property_get_reference_args(). As documented in drivers/base/property.c:

* The caller is responsible for calling fwnode_handle_put() on the
* returned @args->fwnode pointer.

The returned reference is never put. The function calls the helper twice, once directly and then repeatedly in a while loop, and each call overwrites args, so only the last reference is even reachable and all the earlier ones are leaked for good.

Put the reference as soon as args.args[] has been consumed, both for the initial call and for every iteration of the loop.

Found by code review.

Fixes bb949ed9b16b ("pinctrl: stm32: Switch to use for_each_gpiochip_node() helper")
---
 drivers/pinctrl/stm32/pinctrl-stm32.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/pinctrl/stm32/pinctrl-stm32.c +5 -1
index 857ce101fab0c..79aff59b54f72 100644
@@ -1319,8 +1319,12 @@ static int stm32_gpiolib_register_bank(struct stm32_pinctrl *pctl, struct fwnode
 
 		/* get the last defined gpio line (offset + nb of pins) */
 		npins = args.args[0] + args.args[2];
-		while (!fwnode_property_get_reference_args(fwnode, "gpio-ranges", NULL, 3, ++i, &args))
+		fwnode_handle_put(args.fwnode);
+
+		while (!fwnode_property_get_reference_args(fwnode, "gpio-ranges", NULL, 3, ++i, &args)) {
 			npins = max(npins, (int)(args.args[0] + args.args[2]));
+			fwnode_handle_put(args.fwnode);
+		}
 	} else {
 		bank_nr = pctl->nbanks;
 		bank->gpio_chip.base = bank_nr * STM32_GPIO_PINS_PER_BANK;
Signature · 1 line
2.53.0
author maintainer
#1284 lore raw

PATCH 1281/1536 lib/decompress_bunzip2: fix off-by-one in run-length bounds check

In reply to Greg Kroah-Hartman

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

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

From: Matt Turner <[email protected]>

[ Upstream commit 69919be2b93ef3922f646729ff42b4bd9a30846b ]

The run-length path rejects a block when dbufCount+t equals dbufSize, but the loop that follows writes exactly t bytes starting at dbufCount, so a block that fills the buffer exactly is legal. bzip2 allows it too: its decompressor bounds a block at 100000 * blockSize100k and checks that limit per byte appended. Use > instead of >=.

bzip2's encoder stops filling a block 19 bytes early, so nothing it produces ever reaches the limit and the bug stays hidden. Compressors that use the full block size do reach it: an lbzip2 -9 image whose block ends on a run fails to decode, and a self-extracting kernel built that way does not boot.

This code came from busybox, which fixed the same line in 2013 in commit 932e233a491b ("bunzip2: fix off-by-one check").

I ran into this because my system uses lbzip2 as /bin/bzip2 -- a common thing on Gentoo I believe. As far as I can tell, anyone using lbzip2 as their system bzip2 would run into this and it's only because it's very uncommon these days to compress a kernel with bzip2 that no one has noticed. I only noticed because I was adding support for various compression formats on alpha.

Fixes bc22c17e12c1 ("bzip2/lzma: library support for gzip, bzip2 and lzma decompression")
Cc Alain Knaff <[email protected]>
Cc "H. Peter Anvin" <[email protected]>
---
 lib/decompress_bunzip2.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/decompress_bunzip2.c +1 -1
index ca736166f1000..4f98cdea7e0b3 100644
@@ -439,7 +439,7 @@ static int INIT get_next_block(struct bunzip_data *bd)
 		   array.) */
 		if (runPos) {
 			runPos = 0;
-			if (dbufCount+t >= dbufSize)
+			if (dbufCount+t > dbufSize)
 				return RETVAL_DATA_ERROR;
 
 			uc = symToByte[mtfSymbol[0]];
Signature · 1 line
2.53.0
author maintainer
#1285 lore raw

PATCH 1282/1536 lib: decompress_bunzip2: fix integer overflow in run-length decoding

In reply to Greg Kroah-Hartman

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

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

From: Aamir Ahmed <[email protected]>

[ Upstream commit b822ad8d702df0be9fe3f24f71caeb0522d72319 ]

The RUNA/RUNB decoder in get_next_block() accumulates a run length into the signed int t with no bound. runPos doubles per symbol, so t grows as at least 2^n-1 and reaches INT_MAX after 31 RUNA symbols. The guard that follows, dbufCount+t >= dbufSize, is itself a signed addition, and as the kernel builds with -fno-strict-overflow it wraps negative once dbufCount is nonzero, so the guard is skipped. while (t--) dbuf[dbufCount++] = uc then writes INT_MAX entries into a buffer holding at most 900000. One literal symbol ahead of the run is enough to make dbufCount nonzero.

Bound t to the block size as it is accumulated. t only grows within a run, so the value tested never exceeds the final run length; any stream that decodes today satisfies dbufCount+t < dbufSize at the flush, hence t < dbufSize throughout, and no such stream is rejected. Because t grows as at least 2^n-1 the bound trips by the 20th symbol, leaving runPos at most 2^19, so the following runPos <<= 1 cannot overflow either.

Fixes bc22c17e12c1 ("bzip2/lzma: library support for gzip, bzip2 and lzma decompression")
Assisted-by LLM
Cc Alain Knaff <[email protected]>
Cc "H. Peter Anvin" <[email protected]>
---
 lib/decompress_bunzip2.c | 4 ++++
 1 file changed, 4 insertions(+)
lib/decompress_bunzip2.c +4 -0
index 4f98cdea7e0b3..b8fb40ed06d22 100644
@@ -428,6 +428,10 @@ static int INIT get_next_block(struct bunzip_data *bd)
 			t += (runPos << nextSym);
 			/* +runPos if RUNA; +2*runPos if RUNB */
 
+			/* Bound the run so t and runPos cannot overflow. */
+			if (t >= dbufSize)
+				return RETVAL_DATA_ERROR;
+
 			runPos <<= 1;
 			continue;
 		}
Signature · 1 line
2.53.0
author maintainer
#1286 lore raw

PATCH 1283/1536 ALSA: cs46xx: fix unit mismatch in DSP code area bounds check

In reply to Greg Kroah-Hartman

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

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

From: Denis Arefev <[email protected]>

[ Upstream commit fd65108f5001ffb416dc9bd37ec1893f55cff24a ]

ins->code.offset and code->size are measured in 32-bit words, while DSP_CODE_BYTE_SIZE is the size of the DSP code area in bytes. The check ins->code.offset + code->size > DSP_CODE_BYTE_SIZE in cs46xx_dsp_load_module() therefore allowed up to four times more code than the code area can hold.

The shadow buffer ins->code.data is allocated with kmalloc(DSP_CODE_BYTE_SIZE), i.e. it holds DSP_CODE_BYTE_SIZE/4 words. A firmware file with a code segment larger than DSP_CODE_BYTE_SIZE/4 words (28 KiB) passed the check and caused an out-of-bounds write in shadow_and_reallocate_code() and an out-of-bounds read in snd_cs46xx_download().

Compare the sum in words against DSP_CODE_BYTE_SIZE/4 and cast it to u64 so that the sum cannot wrap for large code->size values.

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

---
 sound/pci/cs46xx/dsp_spos.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/pci/cs46xx/dsp_spos.c +1 -1
index 1db6bc58d6a61..dd23b7d68c164 100644
@@ -396,7 +396,7 @@ int cs46xx_dsp_load_module (struct snd_cs46xx * chip, struct dsp_module_desc * m
 		dev_dbg(chip->card->dev,
 			"dsp_spos: module got no code segment\n");
 	} else {
-		if (ins->code.offset + code->size > DSP_CODE_BYTE_SIZE) {
+		if ((u64)ins->code.offset + code->size > DSP_CODE_BYTE_SIZE / 4) {
 			dev_err(chip->card->dev,
 				"dsp_spos: no space available in DSP\n");
 			return -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#1287 lore raw

PATCH 1284/1536 platform/x86: hp-bioscfg: fix OOB reads in hp_get_string_from_buffer()

In reply to Greg Kroah-Hartman

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

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

From: Muhammad Bilal <[email protected]>

[ Upstream commit 176b38b84ae5e075850b3ebb25f906d66f95a46d ]

The escape prescan loop uses 'size' as both its bound and its accumulator, so each escape character found extends the loop and reads past the end of src[].

Use the original u16 count as the loop bound. Also include the 2-byte length prefix in the bounds check, pass the u16 count instead of the byte count to utf16s_to_utf8s(), and advance the buffer by the bytes actually consumed instead of the escape-inflated count.

Tested on HP EliteBook 840 G2 (Fedora 44, Linux 7.2.7).

---
 drivers/platform/x86/hp/hp-bioscfg/bioscfg.c | 26 +++++++++++---------
 1 file changed, 15 insertions(+), 11 deletions(-)
drivers/platform/x86/hp/hp-bioscfg/bioscfg.c +15 -11
index 1b84dad24cb68..fda99b179734b 100644
@@ -54,8 +54,8 @@ int hp_get_integer_from_buffer(u8 **buffer, u32 *buffer_size, u32 *integer)
 int hp_get_string_from_buffer(u8 **buffer, u32 *buffer_size, char *dst, u32 dst_size)
 {
 	u16 *src = (u16 *)*buffer;
+	u16 orig_size;
 	u16 src_size;
-
 	u16 size;
 	int i;
 	int conv_dst_size;
@@ -63,17 +63,21 @@ int hp_get_string_from_buffer(u8 **buffer, u32 *buffer_size, char *dst, u32 dst_
 	if (*buffer_size < sizeof(u16))
 		return -EINVAL;
 
-	src_size = *(src++);
-	/* size value in u16 chars */
-	size = src_size / sizeof(u16);
+	src_size = *src;
 
-	/* Ensure there is enough space remaining to read and convert
-	 * the string
+	/*
+	 * Ensure there is enough space remaining for the length prefix
+	 * just read plus the string data it describes.
 	 */
-	if (*buffer_size < src_size)
+	if (*buffer_size < sizeof(u16) + src_size)
 		return -EINVAL;
 
-	for (i = 0; i < size; i++)
+	src++;
+	/* size value in u16 chars */
+	orig_size = src_size / sizeof(u16);
+	size = orig_size;
+
+	for (i = 0; i < orig_size; i++)
 		if (src[i] == '\\' ||
 		    src[i] == '\r' ||
 		    src[i] == '\n' ||
@@ -91,7 +95,7 @@ int hp_get_string_from_buffer(u8 **buffer, u32 *buffer_size, char *dst, u32 dst_
 	/*
 	 * convert from UTF-16 unicode to ASCII
 	 */
-	utf16s_to_utf8s(src, src_size, UTF16_HOST_ENDIAN, dst, conv_dst_size);
+	utf16s_to_utf8s(src, orig_size, UTF16_HOST_ENDIAN, dst, conv_dst_size);
 	dst[conv_dst_size] = 0;
 
 	for (i = 0; i < conv_dst_size; i++) {
@@ -117,8 +121,8 @@ int hp_get_string_from_buffer(u8 **buffer, u32 *buffer_size, char *dst, u32 dst_
 		src++;
 	}
 
-	*buffer = (u8 *)src;
-	*buffer_size -= size * sizeof(u16);
+	*buffer += sizeof(u16) + src_size;
+	*buffer_size -= sizeof(u16) + src_size;
 
 	return size;
 }
Signature · 1 line
2.53.0
author maintainer
#1288 lore raw

PATCH 1285/1536 platform/x86: hp-bioscfg: fix non-ASCII truncation in hp_get_string_from_buffer()

In reply to Greg Kroah-Hartman

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

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

From: Muhammad Bilal <[email protected]>

[ Upstream commit 6b8d2374b32c35efa2a431b3cd2fe346f8917dcc ]

utf16s_to_utf8s() writes into dst, but the loop that follows overwrites dst from the raw UTF-16 code units with truncating casts, so any character above U+007F is mangled. For example, U+00E9 is stored as 0xe9 instead of 0xc3 0xa9.

Convert into a scratch buffer first, then escape '\\', '\r', '\n' and '\t' into dst with string_escape_mem(). Quotes are not escaped, so the existing strreplace() still handles them.

Tested on HP EliteBook 840 G2 (Fedora 44, Linux 7.2.7).

---
 drivers/platform/x86/hp/hp-bioscfg/bioscfg.c | 62 +++++---------------
 1 file changed, 14 insertions(+), 48 deletions(-)
drivers/platform/x86/hp/hp-bioscfg/bioscfg.c +14 -48
index fda99b179734b..fe336e7440065 100644
@@ -11,7 +11,7 @@
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/printk.h>
-#include <linux/string.h>
+#include <linux/string_helpers.h>
 #include <linux/wmi.h>
 #include "bioscfg.h"
 #include "../../firmware_attributes_class.h"
@@ -53,12 +53,12 @@ int hp_get_integer_from_buffer(u8 **buffer, u32 *buffer_size, u32 *integer)
 
 int hp_get_string_from_buffer(u8 **buffer, u32 *buffer_size, char *dst, u32 dst_size)
 {
+	char utf8_buf[MAX_BUFF_SIZE];
 	u16 *src = (u16 *)*buffer;
+	int escaped_len;
 	u16 orig_size;
 	u16 src_size;
-	u16 size;
-	int i;
-	int conv_dst_size;
+	int utf8_len;
 
 	if (*buffer_size < sizeof(u16))
 		return -EINVAL;
@@ -75,56 +75,22 @@ int hp_get_string_from_buffer(u8 **buffer, u32 *buffer_size, char *dst, u32 dst_
 	src++;
 	/* size value in u16 chars */
 	orig_size = src_size / sizeof(u16);
-	size = orig_size;
-
-	for (i = 0; i < orig_size; i++)
-		if (src[i] == '\\' ||
-		    src[i] == '\r' ||
-		    src[i] == '\n' ||
-		    src[i] == '\t')
-			size++;
 
-	/*
-	 * Conversion is limited to destination string max number of
-	 * bytes.
-	 */
-	conv_dst_size = size;
-	if (size >= dst_size)
-		conv_dst_size = dst_size - 1;
+	utf8_len = utf16s_to_utf8s(src, orig_size, UTF16_HOST_ENDIAN,
+				   utf8_buf, sizeof(utf8_buf));
 
-	/*
-	 * convert from UTF-16 unicode to ASCII
-	 */
-	utf16s_to_utf8s(src, orig_size, UTF16_HOST_ENDIAN, dst, conv_dst_size);
-	dst[conv_dst_size] = 0;
-
-	for (i = 0; i < conv_dst_size; i++) {
-		if (*src == '\\' ||
-		    *src == '\r' ||
-		    *src == '\n' ||
-		    *src == '\t') {
-			dst[i++] = '\\';
-			if (i == conv_dst_size)
-				break;
-		}
-
-		if (*src == '\r')
-			dst[i] = 'r';
-		else if (*src == '\n')
-			dst[i] = 'n';
-		else if (*src == '\t')
-			dst[i] = 't';
-		else if (*src == '"')
-			dst[i] = '\'';
-		else
-			dst[i] = *src;
-		src++;
-	}
+	escaped_len = string_escape_mem(utf8_buf, utf8_len, dst, dst_size - 1,
+					ESCAPE_SPACE | ESCAPE_SPECIAL,
+					"\\\r\n\t");
+	if (escaped_len > dst_size - 1)
+		escaped_len = dst_size - 1;
+	dst[escaped_len] = '\0';
+	strreplace(dst, '"', '\'');
 
 	*buffer += sizeof(u16) + src_size;
 	*buffer_size -= sizeof(u16) + src_size;
 
-	return size;
+	return escaped_len;
 }
 
 int hp_get_common_data_from_buffer(u8 **buffer_ptr, u32 *buffer_size,
Signature · 1 line
2.53.0
author maintainer
#1289 lore raw

PATCH 1286/1536 platform/x86: hp-bioscfg: return -E2BIG from validate_password_input()

In reply to Greg Kroah-Hartman

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

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

From: Muhammad Bilal <[email protected]>

[ Upstream commit a4f19c589b21e18567d3c0ac7b9294f81e29b1de ]

validate_password_input() returns the positive INVALID_BIOS_AUTH on rejection. store_password_instance() skips the store on nonzero ret, but its final "return ret < 0 ? ret : count" treats the positive value as success, so userspace sees count instead of an error.

Return -E2BIG for an invalid password length.

Tested on HP EliteBook 840 G2 (Fedora 44, Linux 7.2.7): writing 999 bytes to current_password returned 999 before this change.

---
 drivers/platform/x86/hp/hp-bioscfg/passwdobj-attributes.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/platform/x86/hp/hp-bioscfg/passwdobj-attributes.c +4 -3
index 34740f29f41a5..00e91ade56293 100644
@@ -70,12 +70,13 @@ static int validate_password_input(int instance_id, const char *buf)
 		length--;
 
 	if (length > MAX_PASSWD_SIZE)
-		return INVALID_BIOS_AUTH;
+		return -E2BIG;
 
 	if (password_data->min_password_length > length ||
 	    password_data->max_password_length < length)
-		return INVALID_BIOS_AUTH;
-	return SUCCESS;
+		return -E2BIG;
+
+	return 0;
 }
 
 ATTRIBUTE_N_PROPERTY_SHOW(is_enabled, password);
Signature · 1 line
2.53.0
author maintainer
#1290 lore raw

PATCH 1287/1536 platform/x86: hp-bioscfg: allow clearing current_password

In reply to Greg Kroah-Hartman

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

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

From: Muhammad Bilal <[email protected]>

[ Upstream commit acada379d5c4dd3a86d48fc69802e769eff29f7e ]

The ABI documents echo "" > current_password as the way to end a session, but validate_password_input() rejects an empty string when min_password_length is nonzero, so the password stays cached.

Skip the length check for an empty current_password so the write clears it.

Compile tested only.

---
 .../platform/x86/hp/hp-bioscfg/passwdobj-attributes.c    | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/platform/x86/hp/hp-bioscfg/passwdobj-attributes.c +7 -2
index 00e91ade56293..52bff847d4297 100644
@@ -60,7 +60,8 @@ int hp_get_password_instance_for_type(const char *name)
 	return -EINVAL;
 }
 
-static int validate_password_input(int instance_id, const char *buf)
+static int validate_password_input(int instance_id, const char *buf,
+				   bool is_current)
 {
 	int length;
 	struct password_data *password_data = &bioscfg_drv.password_data[instance_id];
@@ -69,6 +70,10 @@ static int validate_password_input(int instance_id, const char *buf)
 	if (length > 0 && buf[length - 1] == '\n')
 		length--;
 
+	/* An empty current_password clears the session password */
+	if (is_current && !length)
+		return 0;
+
 	if (length > MAX_PASSWD_SIZE)
 		return -E2BIG;
 
@@ -97,7 +102,7 @@ static int store_password_instance(struct kobject *kobj, const char *buf,
 		id = get_password_instance_id(kobj);
 
 		if (id >= 0)
-			ret = validate_password_input(id, buf_cp);
+			ret = validate_password_input(id, buf_cp, is_current);
 	}
 
 	if (!ret) {
Signature · 1 line
2.53.0
author maintainer
#1291 lore raw

PATCH 1288/1536 platform/x86: hp-bioscfg: NUL-terminate the SPM auth token

In reply to Greg Kroah-Hartman

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

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

From: Muhammad Bilal <[email protected]>

[ Upstream commit f2769668959f6411ac69e83080a240f8a8785e05 ]

auth_token_store() copies the token with kmemdup(), which does not NUL terminate it, but hp_calculate_security_buffer() and hp_populate_security_buffer() use it as a C string and read past the allocation.

A lone newline (echo > auth_token) is worse: kmemdup() of 0 bytes returns ZERO_SIZE_PTR, which passes the NULL checks, so a later attribute write passes it to strlen().

A userspace replica of the two helpers under ASan reports a heap buffer overflow in hp_calculate_security_buffer() for the unterminated token and a fault at address 0x10 for the lone newline, and is clean with this change.

The token is a string, so copy it with kstrndup(), which always NUL terminates and allocates at least one byte.

---
 drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c +1 -1
index abf8ce20fe15c..040964ed50ced 100644
@@ -307,7 +307,7 @@ static ssize_t auth_token_store(struct kobject *kobj,
 		length--;
 
 	/* allocate space and copy current auth token */
-	bioscfg_drv.spm_data.auth_token = kmemdup(buf, length, GFP_KERNEL);
+	bioscfg_drv.spm_data.auth_token = kstrndup(buf, length, GFP_KERNEL);
 	if (!bioscfg_drv.spm_data.auth_token) {
 		ret = -ENOMEM;
 		goto exit_token;
Signature · 1 line
2.53.0
author maintainer
#1292 lore raw

PATCH 1289/1536 serial: 8250_lpss: do not touch uninitialized line in ehl_serial_exit()

In reply to Greg Kroah-Hartman

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

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

From: Jiri Slaby (SUSE) <[email protected]>

[ Upstream commit 3e3ae95a3d84a6028f37a07ab7ad78bb14689f2e ]

lpss8250_probe() calls lpss->board->exit() on its error path. For the EHL board, that is ehl_serial_exit() and it does:
serial8250_get_port(lpss->data.line)->dma = NULL;

But when lpss8250_dma_setup() or serial8250_register_8250_port() fails, lpss->data.line was never assigned. As lpss is kzalloc()ed, line is 0 and ehl_serial_exit() clears the dma pointer of an unrelated port -- serial8250_ports[0], i.e. ttyS0, which is often the console.

Initialize lpss->data.line to -1 in probe and skip the clearing in ehl_serial_exit() if no port was registered.

Fixes 5318f70da7e8 ("serial: 8250_lpss: Balance reference count for PCI DMA device")
Assisted-by LLM
Cc "Ilpo Järvinen" <[email protected]>
Cc Andy Shevchenko <[email protected]>
---
 drivers/tty/serial/8250/8250_lpss.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/tty/serial/8250/8250_lpss.c +4 -3
index 776ec1ef29d62..325e587ae2c42 100644
@@ -183,9 +183,8 @@ static int ehl_serial_setup(struct lpss8250 *lpss, struct uart_port *port)
 
 static void ehl_serial_exit(struct lpss8250 *lpss)
 {
-	struct uart_8250_port *up = serial8250_get_port(lpss->data.line);
-
-	up->dma = NULL;
+	if (lpss->data.line >= 0)
+		serial8250_get_port(lpss->data.line)->dma = NULL;
 }
 
 #ifdef CONFIG_SERIAL_8250_DMA
@@ -329,6 +328,8 @@ static int lpss8250_probe(struct pci_dev *pdev, const struct pci_device_id *id)
 		return ret;
 
 	lpss->board = (struct lpss8250_board *)id->driver_data;
+	/* for tests in lpss->board->exit() */
+	lpss->data.line = -1;
 
 	memset(&uart, 0, sizeof(struct uart_8250_port));
 
Signature · 1 line
2.53.0
author maintainer
#1293 lore raw

PATCH 1290/1536 serial: pmac_zilog: push received data to the port that received it

In reply to Greg Kroah-Hartman

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

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

From: Tim Douglas <[email protected]>

[ Upstream commit f3dc727da3af64abc12b625bbf1eb68d55d882cc ]

pmz_interrupt() drains both channels but, since commit 2e124b4a390c ("TTY: switch tty_flip_buffer_push"), pushes the flip buffer of the port whose handler is running rather than the port that was drained. With both ports open, data received on the other port can be left in its flip buffer until something else pushes it, so its reader may not see it.

Fixes 2e124b4a390c ("TTY: switch tty_flip_buffer_push")
Assisted-by LLM
---
 drivers/tty/serial/pmac_zilog.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/tty/serial/pmac_zilog.c +2 -2
index 8969b11cc0a9a..893c59ef2fab3 100644
@@ -444,7 +444,7 @@ static irqreturn_t pmz_interrupt(int irq, void *dev_id)
  skip_a:
 	uart_port_unlock(&uap_a->port);
 	if (push)
-		tty_flip_buffer_push(&uap->port.state->port);
+		tty_flip_buffer_push(&uap_a->port.state->port);
 
 	if (!uap_b)
 		goto out;
@@ -469,7 +469,7 @@ static irqreturn_t pmz_interrupt(int irq, void *dev_id)
  skip_b:
 	uart_port_unlock(&uap_b->port);
 	if (push)
-		tty_flip_buffer_push(&uap->port.state->port);
+		tty_flip_buffer_push(&uap_b->port.state->port);
 
  out:
 	return rc;
Signature · 1 line
2.53.0
author maintainer
#1294 lore raw

PATCH 1291/1536 nvme: make the DH-HMAC-CHAP secret attributes readable by root only

In reply to Greg Kroah-Hartman

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

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

From: Martin Belanger <[email protected]>

[ Upstream commit bbca7c312ab25efd0024eb87545c51a76ab2ea39 ]

The dhchap_secret and dhchap_ctrl_secret sysfs attributes have mode 0644. Their show functions return the secret, so any local user can read the DH-HMAC-CHAP secrets of a connected controller.

Define them with DEVICE_ATTR_ADMIN_RW(), which sets mode 0600. The macro takes the show and store functions from the attribute name, so rename them. Writing the attributes was already limited to root and is not changed.

Fixes f50fff73d620 ("nvme: implement In-Band authentication")
Assisted-by LLM
---
 drivers/nvme/host/sysfs.c | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)
drivers/nvme/host/sysfs.c +6 -8
index 74f0b9ece0442..9508d582804e5 100644
@@ -549,7 +549,7 @@ static ssize_t dctype_show(struct device *dev,
 static DEVICE_ATTR_RO(dctype);
 
 #ifdef CONFIG_NVME_HOST_AUTH
-static ssize_t nvme_ctrl_dhchap_secret_show(struct device *dev,
+static ssize_t dhchap_secret_show(struct device *dev,
 		struct device_attribute *attr, char *buf)
 {
 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
@@ -560,7 +560,7 @@ static ssize_t nvme_ctrl_dhchap_secret_show(struct device *dev,
 	return sysfs_emit(buf, "%s\n", opts->dhchap_secret);
 }
 
-static ssize_t nvme_ctrl_dhchap_secret_store(struct device *dev,
+static ssize_t dhchap_secret_store(struct device *dev,
 		struct device_attribute *attr, const char *buf, size_t count)
 {
 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
@@ -604,10 +604,9 @@ static ssize_t nvme_ctrl_dhchap_secret_store(struct device *dev,
 	return count;
 }
 
-static DEVICE_ATTR(dhchap_secret, S_IRUGO | S_IWUSR,
-	nvme_ctrl_dhchap_secret_show, nvme_ctrl_dhchap_secret_store);
+static DEVICE_ATTR_ADMIN_RW(dhchap_secret);
 
-static ssize_t nvme_ctrl_dhchap_ctrl_secret_show(struct device *dev,
+static ssize_t dhchap_ctrl_secret_show(struct device *dev,
 		struct device_attribute *attr, char *buf)
 {
 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
@@ -618,7 +617,7 @@ static ssize_t nvme_ctrl_dhchap_ctrl_secret_show(struct device *dev,
 	return sysfs_emit(buf, "%s\n", opts->dhchap_ctrl_secret);
 }
 
-static ssize_t nvme_ctrl_dhchap_ctrl_secret_store(struct device *dev,
+static ssize_t dhchap_ctrl_secret_store(struct device *dev,
 		struct device_attribute *attr, const char *buf, size_t count)
 {
 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
@@ -662,8 +661,7 @@ static ssize_t nvme_ctrl_dhchap_ctrl_secret_store(struct device *dev,
 	return count;
 }
 
-static DEVICE_ATTR(dhchap_ctrl_secret, S_IRUGO | S_IWUSR,
-	nvme_ctrl_dhchap_ctrl_secret_show, nvme_ctrl_dhchap_ctrl_secret_store);
+static DEVICE_ATTR_ADMIN_RW(dhchap_ctrl_secret);
 #endif
 
 static struct attribute *nvme_dev_attrs[] = {
Signature · 1 line
2.53.0
author maintainer
#1295 lore raw

PATCH 1292/1536 spi: cadence-xspi: fix stack buffer overflow in the Marvell b0 path

In reply to Greg Kroah-Hartman

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

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

From: Weibin Liu <[email protected]>

[ Upstream commit ef9690269999ddf9b204731baca1bd6b7aea1aa7 ]

transfer_one_message_b0() falls back to a 10-byte stack buffer for transfers which carry no TX data and points both in_buffer and out_buffer into it.

With a transfer longer than 10 bytes the SDMA branch of the loop moves up to MRVL_XFER_QWORD_COUNT * MRVL_XFER_QWORD_BYTECOUNT (256) bytes through those pointers and then advances them by the same amount, so both directions overflow the scratch buffer: a read transaction copies SDMA data past the end of the buffer, a write transaction sends stack contents from beyond it to the SPI bus.

Size the scratch buffer for the largest chunk the loop can request, keep the buffer pointers pinned to it when the message does not carry the corresponding TX or RX data, and only advance the pointers which reference real transfer buffers. Also zero-initialize the scratch buffer so that padding bytes sent for TX-less transfers no longer leak uninitialized stack contents.

Fixes 5cb7651f78e1 ("Marvell HW overlay support for Cadence xSPI")
---
 drivers/spi/spi-cadence-xspi.c | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)
drivers/spi/spi-cadence-xspi.c +11 -5
index 6dcba0e0ddaa3..c3676b21e8167 100644
@@ -268,6 +268,7 @@
 #define MRVL_XFER_FUNC_START		 BIT(0)
 #define MRVL_XFER_QWORD_COUNT		 32
 #define MRVL_XFER_QWORD_BYTECOUNT	 8
+#define MRVL_XFER_MAX_LEN (MRVL_XFER_QWORD_COUNT * MRVL_XFER_QWORD_BYTECOUNT)
 
 #define MRVL_XSPI_POLL_TIMEOUT_US	1000
 #define MRVL_XSPI_POLL_DELAY_US		10
@@ -1047,7 +1048,7 @@ static int cdns_xspi_transfer_one_message_b0(struct spi_controller *controller,
 	struct spi_device *spi = m->spi;
 	struct spi_transfer *t = NULL;
 
-	const unsigned int max_len = MRVL_XFER_QWORD_BYTECOUNT * MRVL_XFER_QWORD_COUNT;
+	const unsigned int max_len = MRVL_XFER_MAX_LEN;
 	int current_transfer_len;
 	int cs = spi_get_chipselect(spi, 0);
 	int cs_change = 0;
@@ -1070,13 +1071,16 @@ static int cdns_xspi_transfer_one_message_b0(struct spi_controller *controller,
 	list_for_each_entry(t, &m->transfers, transfer_list) {
 		u8 *txd = (u8 *) t->tx_buf;
 		u8 *rxd = (u8 *) t->rx_buf;
-		u8 data[10];
+		u8 data[MRVL_XFER_MAX_LEN] = {0};
 		u32 cmd_regs[6];
 
 		if (!txd)
 			txd = data;
 
-		cdns_xspi->in_buffer = txd + 1;
+		if (rxd)
+			cdns_xspi->in_buffer = rxd;
+		else
+			cdns_xspi->in_buffer = data;
 		cdns_xspi->out_buffer = txd + 1;
 
 		while (t->len) {
@@ -1101,8 +1105,10 @@ static int cdns_xspi_transfer_one_message_b0(struct spi_controller *controller,
 				if (!cdns_xspi_is_stig_ready(cdns_xspi, true))
 					return -EIO;
 
-				cdns_xspi->in_buffer += current_transfer_len;
-				cdns_xspi->out_buffer += current_transfer_len;
+				if (rxd)
+					cdns_xspi->in_buffer += current_transfer_len;
+				if (t->tx_buf)
+					cdns_xspi->out_buffer += current_transfer_len;
 			}
 
 			if (rxd) {
Signature · 1 line
2.53.0
author maintainer
#1296 lore raw

PATCH 1293/1536 ARM: 9488/1: smp: set current pointer in assembly before jumping into C

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit f6e551e7d515579b952422c93415470fb672d848 ]

With CONFIG_KCOV_INSTRUMENT_ALL=y, secondary CPUs fail to come online on ARMv6K/ARMv7 SMP:

CPU1: failed to boot: -38

The compiler inserts a call to __sanitizer_cov_trace_pc() at the entry of secondary_start_kernel(), before set_current(task). The KCOV hook dereferences current while TPIDRURO is still uninitialized, causing a data abort before cpu_init() has installed the exception stacks. The secondary CPU consequently never completes startup.

Initialize current in the secondary assembly handoff, as __mmap_switched already does for the boot CPU.

With current set in assembly, the set_current() call in secondary_start_kernel() is redundant. Drop it together with the function and the task argument. The hotplug resuscitate path in arch_cpu_idle_dead() needs no hand-off either, as smp_ops.cpu_die() can only return if the CPU kept its register state, TPIDRURO included.

Assisted-by Claude:claude-fable-5
Fixes 50596b7559bf ("ARM: smp: Store current pointer in TPIDRURO register if available")
---
 arch/arm/include/asm/smp.h   |  2 +-
 arch/arm/kernel/head-nommu.S |  1 +
 arch/arm/kernel/head.S       |  1 +
 arch/arm/kernel/smp.c        | 15 ++-------------
 4 files changed, 5 insertions(+), 14 deletions(-)
arch/arm/include/asm/smp.h +1 -1
index 8c05a7f374d8b..84aa6a663e816 100644
@@ -43,7 +43,7 @@ extern void set_smp_ipi_range(int ipi_base, int nr_ipi);
  * Called from platform specific assembly code, this is the
  * secondary CPU entry point.
  */
-asmlinkage void secondary_start_kernel(struct task_struct *task);
+asmlinkage void secondary_start_kernel(void);
 
 
 /*
arch/arm/kernel/head-nommu.S +1 -0
index b9d6818f1ee16..f80bbfbd3a6f8 100644
@@ -116,6 +116,7 @@ ENTRY(secondary_startup)
 	ldr	r7, __secondary_data		@ reload r7
 	ldr	sp, [r7, #12]			@ set up the stack pointer
 	ldr	r0, [r7, #16]			@ set up task pointer
+	set_current r0, r1
 	mov	fp, #0
 	b	secondary_start_kernel
 ENDPROC(secondary_startup)
arch/arm/kernel/head.S +1 -0
index f22c50d4bd417..a22403a629efa 100644
@@ -442,6 +442,7 @@ ENTRY(__secondary_switched)
 	adr_l	r7, secondary_data + 12		@ get secondary_data.stack
 	ldr	sp, [r7]
 	ldr	r0, [r7, #4]			@ get secondary_data.task
+	set_current r0, r1
 	mov	fp, #0
 	b	secondary_start_kernel
 ENDPROC(__secondary_switched)
arch/arm/kernel/smp.c +2 -13
index 3431c0553f45c..f548ada379afb 100644
@@ -371,12 +371,9 @@ void __noreturn arch_cpu_idle_dead(void)
 	 */
 	__asm__("mov	sp, %0\n"
 	"	mov	fp, #0\n"
-	"	mov	r0, %1\n"
 	"	b	secondary_start_kernel"
 		:
-		: "r" (task_stack_page(current) + THREAD_SIZE - 8),
-		  "r" (current)
-		: "r0");
+		: "r" (task_stack_page(current) + THREAD_SIZE - 8));
 
 	unreachable();
 }
@@ -397,23 +394,15 @@ static void smp_store_cpu_info(unsigned int cpuid)
 	check_cpu_icache_size(cpuid);
 }
 
-static void set_current(struct task_struct *cur)
-{
-	/* Set TPIDRURO */
-	asm("mcr p15, 0, %0, c13, c0, 3" :: "r"(cur) : "memory");
-}
-
 /*
  * This is the secondary CPU boot entry.  We're using this CPUs
  * idle thread stack, but a set of temporary page tables.
  */
-asmlinkage void secondary_start_kernel(struct task_struct *task)
+asmlinkage void secondary_start_kernel(void)
 {
 	struct mm_struct *mm = &init_mm;
 	unsigned int cpu;
 
-	set_current(task);
-
 	secondary_biglittle_init();
 
 	/*
Signature · 1 line
2.53.0
author maintainer
#1297 lore raw

PATCH 1294/1536 ARM: 9491/1: alignment: restore uaccess state on emulation fault

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit 80dafbcb705cead6d25cb821cf29c47da8860c8c ]

The alignment handlers enable access to user memory while emulating unaligned instructions. If a checked access faults, its exception table fixup jumps to the handler's fault label and bypasses uaccess_restore(). This leaves DOMAIN_USER as DOMAIN_CLIENT with SW domain PAN, or leaves TTBR0 page table walks enabled with TTBR0 PAN, while the fault is handled.

An ARM926 QEMU test using LDMIA across an unmapped page boundary reports DOMAIN_USER=1 at TYPE_FAULT before this change and DOMAIN_USER=0 after it. SW domain PAN is the default on ARMv5, ARMv6, and non-LPAE ARMv7 builds.

Keep the saved uaccess state at function scope and track whether it was saved. Restore it at the fault label only when needed. Paths that did not enable user access continue to skip the restore.

Assisted-by Codex:gpt-5.6-sol
Fixes 274e91b81ed2 ("ARM: alignment: fix alignment handling for uaccess changes")
---
 arch/arm/mm/alignment.c | 51 ++++++++++++++++++++++++++++++-----------
 1 file changed, 37 insertions(+), 14 deletions(-)
arch/arm/mm/alignment.c +37 -14
index 812380f30ae36..2b470a419dda3 100644
@@ -341,6 +341,8 @@ static int
 do_alignment_ldrhstrh(unsigned long addr, u32 instr, struct pt_regs *regs)
 {
 	unsigned int rd = RD_BITS(instr);
+	unsigned int ua_flags;
+	bool ua_saved = false;
 
 	ai_half += 1;
 
@@ -364,10 +366,11 @@ do_alignment_ldrhstrh(unsigned long addr, u32 instr, struct pt_regs *regs)
  user:
 	if (LDST_L_BIT(instr)) {
 		unsigned long val;
-		unsigned int __ua_flags = uaccess_save_and_enable();
 
+		ua_flags = uaccess_save_and_enable();
+		ua_saved = true;
 		get16t_unaligned_check(val, addr);
-		uaccess_restore(__ua_flags);
+		uaccess_restore(ua_flags);
 
 		/* signed half-word? */
 		if (instr & 0x40)
@@ -375,14 +378,17 @@ do_alignment_ldrhstrh(unsigned long addr, u32 instr, struct pt_regs *regs)
 
 		regs->uregs[rd] = val;
 	} else {
-		unsigned int __ua_flags = uaccess_save_and_enable();
+		ua_flags = uaccess_save_and_enable();
+		ua_saved = true;
 		put16t_unaligned_check(regs->uregs[rd], addr);
-		uaccess_restore(__ua_flags);
+		uaccess_restore(ua_flags);
 	}
 
 	return TYPE_LDST;
 
  fault:
+	if (ua_saved)
+		uaccess_restore(ua_flags);
 	return TYPE_FAULT;
 }
 
@@ -391,6 +397,8 @@ do_alignment_ldrdstrd(unsigned long addr, u32 instr, struct pt_regs *regs)
 {
 	unsigned int rd = RD_BITS(instr);
 	unsigned int rd2;
+	unsigned int ua_flags;
+	bool ua_saved = false;
 	int load;
 
 	if ((instr & 0xfe000000) == 0xe8000000) {
@@ -425,26 +433,30 @@ do_alignment_ldrdstrd(unsigned long addr, u32 instr, struct pt_regs *regs)
  user:
 	if (load) {
 		unsigned long val, val2;
-		unsigned int __ua_flags = uaccess_save_and_enable();
 
+		ua_flags = uaccess_save_and_enable();
+		ua_saved = true;
 		get32t_unaligned_check(val, addr);
 		get32t_unaligned_check(val2, addr + 4);
 
-		uaccess_restore(__ua_flags);
+		uaccess_restore(ua_flags);
 
 		regs->uregs[rd] = val;
 		regs->uregs[rd2] = val2;
 	} else {
-		unsigned int __ua_flags = uaccess_save_and_enable();
+		ua_flags = uaccess_save_and_enable();
+		ua_saved = true;
 		put32t_unaligned_check(regs->uregs[rd], addr);
 		put32t_unaligned_check(regs->uregs[rd2], addr + 4);
-		uaccess_restore(__ua_flags);
+		uaccess_restore(ua_flags);
 	}
 
 	return TYPE_LDST;
  bad:
 	return TYPE_ERROR;
  fault:
+	if (ua_saved)
+		uaccess_restore(ua_flags);
 	return TYPE_FAULT;
 }
 
@@ -452,6 +464,8 @@ static int
 do_alignment_ldrstr(unsigned long addr, u32 instr, struct pt_regs *regs)
 {
 	unsigned int rd = RD_BITS(instr);
+	unsigned int ua_flags;
+	bool ua_saved = false;
 
 	ai_word += 1;
 
@@ -469,18 +483,22 @@ do_alignment_ldrstr(unsigned long addr, u32 instr, struct pt_regs *regs)
  trans:
 	if (LDST_L_BIT(instr)) {
 		unsigned int val;
-		unsigned int __ua_flags = uaccess_save_and_enable();
+		ua_flags = uaccess_save_and_enable();
+		ua_saved = true;
 		get32t_unaligned_check(val, addr);
-		uaccess_restore(__ua_flags);
+		uaccess_restore(ua_flags);
 		regs->uregs[rd] = val;
 	} else {
-		unsigned int __ua_flags = uaccess_save_and_enable();
+		ua_flags = uaccess_save_and_enable();
+		ua_saved = true;
 		put32t_unaligned_check(regs->uregs[rd], addr);
-		uaccess_restore(__ua_flags);
+		uaccess_restore(ua_flags);
 	}
 	return TYPE_LDST;
 
  fault:
+	if (ua_saved)
+		uaccess_restore(ua_flags);
 	return TYPE_FAULT;
 }
 
@@ -502,6 +520,8 @@ do_alignment_ldmstm(unsigned long addr, u32 instr, struct pt_regs *regs)
 {
 	unsigned int rd, rn, correction, nr_regs, regbits;
 	unsigned long eaddr, newaddr;
+	unsigned int ua_flags;
+	bool ua_saved = false;
 
 	if (LDM_S_BIT(instr))
 		goto bad;
@@ -547,7 +567,8 @@ do_alignment_ldmstm(unsigned long addr, u32 instr, struct pt_regs *regs)
 #endif
 
 	if (user_mode(regs)) {
-		unsigned int __ua_flags = uaccess_save_and_enable();
+		ua_flags = uaccess_save_and_enable();
+		ua_saved = true;
 		for (regbits = REGMASK_BITS(instr), rd = 0; regbits;
 		     regbits >>= 1, rd += 1)
 			if (regbits & 1) {
@@ -559,7 +580,7 @@ do_alignment_ldmstm(unsigned long addr, u32 instr, struct pt_regs *regs)
 					put32t_unaligned_check(regs->uregs[rd], eaddr);
 				eaddr += 4;
 			}
-		uaccess_restore(__ua_flags);
+		uaccess_restore(ua_flags);
 	} else {
 		for (regbits = REGMASK_BITS(instr), rd = 0; regbits;
 		     regbits >>= 1, rd += 1)
@@ -581,6 +602,8 @@ do_alignment_ldmstm(unsigned long addr, u32 instr, struct pt_regs *regs)
 	return TYPE_DONE;
 
 fault:
+	if (ua_saved)
+		uaccess_restore(ua_flags);
 	regs->ARM_pc -= correction;
 	return TYPE_FAULT;
 
Signature · 1 line
2.53.0
author maintainer
#1298 lore raw

PATCH 1295/1536 PCI: Set supported_speeds in set_pcie_port_type()

In reply to Greg Kroah-Hartman

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

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

From: Stian Halseth <[email protected]>

[ Upstream commit 926767a9be8866d26cc27ca46c46c03d921e2193 ]

sparc64 and powerpc create PCI devices from the device tree in of_create_pci_dev(), which calls set_pcie_port_type() but not pci_setup_device(). Since d2bd39c0456b, supported_speeds is only set in pci_setup_device(), so it stays 0 for these devices.

pcie_get_speed_cap() then returns PCI_SPEED_UNKNOWN, the sysfs 'max_link_speed' attribute reads "Unknown", and the failed link retraining quirk passes PCI_SPEED_UNKNOWN to pcie_set_target_speed(), which warns on a SPARC T7-1:

  WARNING: drivers/pci/pcie/bwctrl.c:125 at pcie_set_target_speed+0x284/0x2e0

Set supported_speeds in set_pcie_port_type(), which all three paths call.

---
 drivers/pci/probe.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/pci/probe.c +2 -3
index 718293b4bdb98..5ff2ad01235c4 100644
@@ -1596,6 +1596,8 @@ void set_pcie_port_type(struct pci_dev *pdev)
 		pdev->aspm_l1_support = 1;
 #endif
 
+	pdev->supported_speeds = pcie_get_supported_speeds(pdev);
+
 	parent = pci_upstream_bridge(pdev);
 	if (!parent)
 		return;
@@ -1981,9 +1983,6 @@ int pci_setup_device(struct pci_dev *dev)
 
 	set_pcie_untrusted(dev);
 
-	if (pci_is_pcie(dev))
-		dev->supported_speeds = pcie_get_supported_speeds(dev);
-
 	/* "Unknown power state" */
 	dev->current_state = PCI_UNKNOWN;
 
Signature · 1 line
2.53.0
author maintainer
#1299 lore raw

PATCH 1296/1536 Bluetooth: btusb: Add device ID for Realtek RTL8761BUE (StarTech AV53C1)

In reply to Greg Kroah-Hartman

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

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

From: Nikolaj Klitlund Børty <[email protected]>

[ Upstream commit 1430308fc9d47a801a305700cd444b1a0051d14a ]

Add the USB ID 0x14b0:0x047a for the StarTech AV53C1-USB-BLUETOOTH adapter, a Realtek RTL8761BUE based Bluetooth 5.3 dongle.

Without this entry btusb treats the device as a generic Bluetooth adapter and never loads the Realtek firmware, leaving the controller on its ROM firmware. In that state it advertises and scans actively, but never reports advertisements during passive scanning. LE connections initiated by the kernel wait for a passive-scan report before issuing LE Create Connection, so connecting and pairing from BlueZ time out without any error from the controller.

The same product is also sold with the ID 0x2c0a:0x8761, which is already supported.

lsusb -v output for the device:

Bus 001 Device 010: ID 14b0:047a StarTech.com Ltd. Bluetooth Radio Device Descriptor:
bcdUSB 1.10
bDeviceClass 224 Wireless
bDeviceSubClass 1 Radio Frequency
bDeviceProtocol 1 Bluetooth
idVendor 0x14b0 StarTech.com Ltd.
idProduct 0x047a
bcdDevice 2.00

  iManufacturer           1 Realtek
  iProduct                2 Bluetooth Radio
  iSerial                 3 00E04C239987
  bNumInterfaces          2

Interface Descriptor:
bInterfaceClass 224 Wireless
bInterfaceSubClass 1 Radio Frequency
bInterfaceProtocol 1 Bluetooth

---
 drivers/bluetooth/btusb.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/bluetooth/btusb.c +2 -0
index 32465e6736d2a..84b1ee064f64f 100644
@@ -816,6 +816,8 @@ static const struct usb_device_id quirks_table[] = {
 						     BTUSB_WIDEBAND_SPEECH },
 	{ USB_DEVICE(0x37ad, 0x0600), .driver_info = BTUSB_REALTEK |
 						     BTUSB_WIDEBAND_SPEECH },
+	{ USB_DEVICE(0x14b0, 0x047a), .driver_info = BTUSB_REALTEK |
+						     BTUSB_WIDEBAND_SPEECH },
 
 	/* Additional Realtek 8821AE Bluetooth devices */
 	{ USB_DEVICE(0x0b05, 0x17dc), .driver_info = BTUSB_REALTEK },
Signature · 1 line
2.53.0
author maintainer
#1300 lore raw

PATCH 1297/1536 Bluetooth: 6lowpan: Pin module for 6lowpan_control debugfs file

In reply to Greg Kroah-Hartman

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

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

From: Bui Viet Dung <[email protected]>

[ Upstream commit 8368f0c2cde48c09ed70644059f24172b0c59f52 ]

An open debugfs file retains lowpan_control_fops in the debugfs proxy state. However, lowpan_control_fops has no .owner set to THIS_MODULE. As a result, full_proxy_open_regular() calls fops_get() which succeeds without taking a reference to the bluetooth_6lowpan module.

With CONFIG_BT_6LOWPAN=m, a userspace process can keep the debugfs file descriptor for 6lowpan_control open across module unload (delete_module / rmmod bluetooth_6lowpan). When the process subsequently closes the file descriptor, full_proxy_release() accesses the already freed and unmapped lowpan_control_fops table, causing a kernel page fault or oops.

The issue was discovered via manual code audit of
net/bluetooth/6lowpan.c.

Set .owner = THIS_MODULE on lowpan_control_fops so that debugfs pins the module until all open file descriptors have finished.

Fixes 6b8d4a6a0314 ("Bluetooth: 6LoWPAN: Use connected oriented channel instead of fixed one")
---
 net/bluetooth/6lowpan.c | 1 +
 1 file changed, 1 insertion(+)
net/bluetooth/6lowpan.c +1 -0
index 1cb37fbb668f9..c0cdb99c44e2c 100644
@@ -1200,6 +1200,7 @@ static int lowpan_control_open(struct inode *inode, struct file *file)
 }
 
 static const struct file_operations lowpan_control_fops = {
+	.owner		= THIS_MODULE,
 	.open		= lowpan_control_open,
 	.read		= seq_read,
 	.write		= lowpan_control_write,
Signature · 1 line
2.53.0
author maintainer
#1301 lore raw

PATCH 1298/1536 Bluetooth: hci_debugfs: Pin module for debugfs file operations

In reply to Greg Kroah-Hartman

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

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

From: Bui Viet Dung <[email protected]>

[ Upstream commit 2a3e2287877b1ee40ffb80b7d769b633866533f3 ]

An open debugfs file retains its file_operations pointer in the debugfs proxy state. However, the file_operations defined in hci_debugfs.c (use_debug_keys_fops, sc_only_mode_fops, ssp_debug_mode_fops, force_bredr_smp_fops, force_static_address_fops, force_no_mitm_fops, dut_mode_fops, vendor_diag_fops, and the DEFINE_QUIRK_ATTRIBUTE macro) have no .owner set to THIS_MODULE.

As a result, full_proxy_open_regular() calls fops_get() which succeeds without taking a reference to the bluetooth module. When a userspace process opens any of these debugfs files, a subsequent controller removal and module unload (rmmod bluetooth) can succeed while the file descriptor remains open.

When the userspace process subsequently closes the descriptor, full_proxy_release() accesses the already unmapped file_operations structure, triggering a kernel oops in full_proxy_release():

  BUG: unable to handle page fault for address: fffffbfff8056f03
  #PF: supervisor read access in kernel mode
  Oops: 0000 [#1] SMP KASAN NOPTI
  RIP: 0010:full_proxy_release+0x8e/0x140
  Call Trace:
   <TASK>
   __fput+0x39f/0xa60
   fput_close_sync+0xff/0x200
   __x64_sys_close+0x8c/0xf0
   do_syscall_64+0x115/0x6a0
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
   </TASK>

The issue was discovered via manual code audit of net/bluetooth/hci_debugfs.c and verified on a Linux 7.3-rc6 test VM with CONFIG_BT=m.

Set .owner = THIS_MODULE on all debugfs file_operations tables in hci_debugfs.c so that debugfs keeps the module loaded until close has finished.

Fixes 0886aea6acd2 ("Bluetooth: Expose debug keys usage setting via debugfs")
---
 net/bluetooth/hci_debugfs.c | 9 +++++++++
 1 file changed, 9 insertions(+)
net/bluetooth/hci_debugfs.c +9 -0
index 8177ea2baaf77..621f0edd885f2 100644
@@ -68,6 +68,7 @@ static ssize_t __name ## _write(struct file *file,			      \
 }									      \
 									      \
 static const struct file_operations __name ## _fops = {			      \
+	.owner		= THIS_MODULE,					      \
 	.open		= simple_open,					      \
 	.read		= __name ## _read,				      \
 	.write		= __name ## _write,				      \
@@ -286,6 +287,7 @@ static ssize_t use_debug_keys_read(struct file *file, char __user *user_buf,
 }
 
 static const struct file_operations use_debug_keys_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= use_debug_keys_read,
 	.llseek		= default_llseek,
@@ -304,6 +306,7 @@ static ssize_t sc_only_mode_read(struct file *file, char __user *user_buf,
 }
 
 static const struct file_operations sc_only_mode_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= sc_only_mode_read,
 	.llseek		= default_llseek,
@@ -440,6 +443,7 @@ static ssize_t ssp_debug_mode_read(struct file *file, char __user *user_buf,
 }
 
 static const struct file_operations ssp_debug_mode_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= ssp_debug_mode_read,
 	.llseek		= default_llseek,
@@ -532,6 +536,7 @@ static ssize_t force_bredr_smp_write(struct file *file,
 }
 
 static const struct file_operations force_bredr_smp_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= force_bredr_smp_read,
 	.write		= force_bredr_smp_write,
@@ -781,6 +786,7 @@ static ssize_t force_static_address_write(struct file *file,
 }
 
 static const struct file_operations force_static_address_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= force_static_address_read,
 	.write		= force_static_address_write,
@@ -1184,6 +1190,7 @@ static ssize_t force_no_mitm_write(struct file *file,
 }
 
 static const struct file_operations force_no_mitm_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= force_no_mitm_read,
 	.write		= force_no_mitm_write,
@@ -1322,6 +1329,7 @@ static ssize_t dut_mode_write(struct file *file, const char __user *user_buf,
 }
 
 static const struct file_operations dut_mode_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= dut_mode_read,
 	.write		= dut_mode_write,
@@ -1378,6 +1386,7 @@ static ssize_t vendor_diag_write(struct file *file, const char __user *user_buf,
 }
 
 static const struct file_operations vendor_diag_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= vendor_diag_read,
 	.write		= vendor_diag_write,
Signature · 1 line
2.53.0
author maintainer
#1302 lore raw

PATCH 1299/1536 Bluetooth: L2CAP: Reject mode changes on connected channels

In reply to Greg Kroah-Hartman

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

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

From: Siwei Zhang <[email protected]>

[ Upstream commit c1398cf11b31a94c27ed810ba69515e0df5ce379 ]

A peer can send a configuration response with an RFC option for another mode to a connected channel, for example to switch it from Streaming to ERTM mode. l2cap_parse_conf_rsp() then changes chan->mode, but l2cap_ertm_init() is not called again, so the ERTM sequence lists are never allocated. The next out-of-sequence I-frame makes l2cap_seq_list_clear() write through the NULL srej_list.list.

Refuse the channel when a response tries to change the mode of a connected channel.

Fixes f2fcfcd67025 ("Bluetooth: Add configuration support for ERTM and Streaming mode")
Assisted-by Claude:claude-opus-5-5
---
 net/bluetooth/l2cap_core.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
net/bluetooth/l2cap_core.c +5 -1
index 894fcd779bd03..69e4ef4834b29 100644
@@ -3769,7 +3769,11 @@ static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len,
 		}
 	}
 
-	if (chan->mode == L2CAP_MODE_BASIC && chan->mode != rfc.mode)
+	/* A connected channel cannot change its mode, as the new mode would
+	 * not be initialized.
+	 */
+	if (chan->mode != rfc.mode &&
+	    (chan->mode == L2CAP_MODE_BASIC || chan->state == BT_CONNECTED))
 		return -ECONNREFUSED;
 
 	chan->mode = rfc.mode;
Signature · 1 line
2.53.0
author maintainer
#1303 lore raw

PATCH 1300/1536 Bluetooth: L2CAP: Reject invalid TxWindow in configuration requests

In reply to Greg Kroah-Hartman

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

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

From: Siwei Zhang <[email protected]>

[ Upstream commit c5ebb0245fe927cf5fa33510a9cb2799c4a2dd01 ]

A peer can send an ERTM RFC option with a TxWindow of zero, which is out of spec. It is stored in remote_tx_win unchanged and later passed to l2cap_seq_list_init(), where roundup_pow_of_two(0) is undefined. On some architectures this results in a ZERO_SIZE_PTR list and a remote kernel oops.

A TxWindow above 63 is out of spec as well. With 6-bit sequence numbers we would then send more unacknowledged frames than the sequence space can tell apart.

Reply with L2CAP_CONF_UNACCEPT and propose the default TxWindow instead of accepting the value, so remote_tx_win always stays within 1 to 63. Keep the parameters of an earlier request then, and do not treat the request as done because an earlier one was.

Also refuse a zero size in l2cap_seq_list_init(), so any other path that reaches it with a zero TxWindow fails the channel instead of the kernel.

Fixes f2fcfcd67025 ("Bluetooth: Add configuration support for ERTM and Streaming mode")
Assisted-by Claude:claude-opus-5-5
---
 net/bluetooth/l2cap_core.c | 35 +++++++++++++++++++++++++++--------
 1 file changed, 27 insertions(+), 8 deletions(-)
net/bluetooth/l2cap_core.c +27 -8
index 69e4ef4834b29..d8c39a4306861 100644
@@ -323,6 +323,10 @@ static int l2cap_seq_list_init(struct l2cap_seq_list *seq_list, u16 size)
 {
 	size_t alloc_size, i;
 
+	/* roundup_pow_of_two(0) is undefined */
+	if (!size)
+		return -EINVAL;
+
 	/* Allocated size is a power of 2 to map sequence numbers
 	 * (which may be up to 14 bits) in to a smaller array that is
 	 * sized for the negotiated ERTM transmit windows.
@@ -3616,18 +3620,33 @@ static int l2cap_parse_conf_req(struct l2cap_chan *chan, void *data, size_t data
 			break;
 
 		case L2CAP_MODE_ERTM:
-			if (!test_bit(CONF_EWS_RECV, &chan->conf_state))
-				chan->remote_tx_win = rfc.txwin_size;
-			else
-				rfc.txwin_size = L2CAP_DEFAULT_TX_WINDOW;
-
-			chan->remote_max_tx = rfc.max_transmit;
-
 			size = min_t(u16, le16_to_cpu(rfc.max_pdu_size),
 				     chan->conn->mtu - L2CAP_EXT_HDR_SIZE -
 				     L2CAP_SDULEN_SIZE - L2CAP_FCS_SIZE);
 			rfc.max_pdu_size = cpu_to_le16(size);
-			chan->remote_mps = size;
+
+			/* The TxWindow must be within 1 to 63, otherwise
+			 * propose the default one and keep the parameters of
+			 * an earlier request. This overrides a PENDING result
+			 * from the EFS check above, so the request is no
+			 * longer pending, nor done if an earlier one was.
+			 */
+			if (!rfc.txwin_size ||
+			    rfc.txwin_size > L2CAP_DEFAULT_TX_WINDOW) {
+				result = L2CAP_CONF_UNACCEPT;
+				clear_bit(CONF_LOC_CONF_PEND, &chan->conf_state);
+				clear_bit(CONF_OUTPUT_DONE, &chan->conf_state);
+				rfc.txwin_size = L2CAP_DEFAULT_TX_WINDOW;
+				remote_efs = 0;
+			} else {
+				if (!test_bit(CONF_EWS_RECV, &chan->conf_state))
+					chan->remote_tx_win = rfc.txwin_size;
+				else
+					rfc.txwin_size = L2CAP_DEFAULT_TX_WINDOW;
+
+				chan->remote_max_tx = rfc.max_transmit;
+				chan->remote_mps = size;
+			}
 
 			__l2cap_set_ertm_timeouts(chan, &rfc);
 
Signature · 1 line
2.53.0
author maintainer
#1304 lore raw

PATCH 1301/1536 Bluetooth: L2CAP: Use default TxWindow for zero socket option

In reply to Greg Kroah-Hartman

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

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

From: Siwei Zhang <[email protected]>

[ Upstream commit 226fa3b676cbf2236f803bccd347462433ffc2c8 ]

L2CAP_OPTIONS accepts a txwin_size of zero and
stores it in tx_win. The zero is then sent to the
peer in our configuration request, and if the
channel ends up in ERTM mode it is passed to
l2cap_seq_list_init().

Use the default TxWindow instead, as the mode can
still be changed to ERTM during configuration.

Fixes 14b5aa71ec50 ("Bluetooth: Add sockopt configuration for txWindow on L2CAP")
---
 net/bluetooth/l2cap_sock.c | 4 ++++
 1 file changed, 4 insertions(+)
net/bluetooth/l2cap_sock.c +4 -0
index f08512a57ab58..602a7e78e83ab 100644
@@ -818,6 +818,10 @@ static int l2cap_sock_setsockopt_old(struct socket *sock, int optname,
 			break;
 		}
 
+		/* A zero TxWindow is invalid, use the default instead */
+		if (!opts.txwin_size)
+			opts.txwin_size = L2CAP_DEFAULT_TX_WINDOW;
+
 		if (!l2cap_valid_mtu(chan, opts.imtu)) {
 			err = -EINVAL;
 			break;
Signature · 1 line
2.53.0
author maintainer
#1305 lore raw

PATCH 1302/1536 cpufreq: schedutil: Serialize sugov_start() against rate limit updates

In reply to Greg Kroah-Hartman

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

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

From: Hui Su <[email protected]>

[ Upstream commit ce390caf5541c493c9061e7a2d98a463e66b736a ]

The current value of sg_policy->tunables->rate_limit_us is used in sugov_start() without locking to update sg_policy->freq_update_delay_ns, so if rate_limit_us_store() runs in parallel with it, the rate limit update may go unnoticed and the new freq_update_delay_ns value may be stale until the rate limit is updated again.

To avoid that, acquire the update_lock mutex of the rate limit sysfs attribute, that is held by rate_limit_us_store() during rate limit updates, around the freq_update_delay_ns in sugov_start().

Fixes 9bdcb44e391d ("cpufreq: schedutil: New governor based on scheduler utilization data")
Cc All applicable <[email protected]>
[ rjw: Subject adjustment, new changelog, edits of the new comment ]
[ rjw: Add empty code line after guard()() ]
---
 kernel/sched/cpufreq_schedutil.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
kernel/sched/cpufreq_schedutil.c +13 -1
index 7c41ed3ec9175..5ae4a40b08627 100644
@@ -70,6 +70,18 @@ static void sugov_update_rate_limit_us(struct sugov_policy *sg_policy)
 		(s64)sg_policy->tunables->rate_limit_us * NSEC_PER_USEC;
 }
 
+static void sugov_update_rate_limit_us_sync(struct sugov_policy *sg_policy)
+{
+	/*
+	 * Serialize with rate_limit_us_store() to prevent this path from using
+	 * a stale rate limit tunable value to set the limit for the given
+	 * policy.
+	 */
+	guard(mutex)(&sg_policy->tunables->attr_set.update_lock);
+
+	sugov_update_rate_limit_us(sg_policy);
+}
+
 static bool sugov_should_update_freq(struct sugov_policy *sg_policy, u64 time)
 {
 	s64 delta_ns;
@@ -869,7 +881,7 @@ static int sugov_start(struct cpufreq_policy *policy)
 	void (*uu)(struct update_util_data *data, u64 time, unsigned int flags);
 	unsigned int cpu;
 
-	sugov_update_rate_limit_us(sg_policy);
+	sugov_update_rate_limit_us_sync(sg_policy);
 	sg_policy->last_freq_update_time	= 0;
 	sg_policy->next_freq			= 0;
 	sg_policy->work_in_progress		= false;
Signature · 1 line
2.53.0
author maintainer
#1306 lore raw

PATCH 1303/1536 PCI: xilinx-xdma: Fix device node reference leak in xilinx_pl_dma_pcie_init_irq_domain()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 73d3d81832708137ba6332fc011663feaf97deee ]

xilinx_pl_dma_pcie_init_irq_domain() takes a reference to the PCIe interrupt-controller child node with of_get_child_by_name(), but the error paths after the two irq_domain_create_linear() calls and after xilinx_pl_dma_pcie_init_msi_irq_domain() return directly without dropping it. irq_domain_create_linear() gets its own reference on the fwnode, so the domains do not consume the caller's one.

Add an err_put_node label that drops the reference before returning.

---
 drivers/pci/controller/pcie-xilinx-dma-pl.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
drivers/pci/controller/pcie-xilinx-dma-pl.c +7 -3
index 116c6e0e71457..d71b6dba75cc8 100644
@@ -588,7 +588,7 @@ static int xilinx_pl_dma_pcie_init_irq_domain(struct pl_dma_pcie *port)
 	port->pldma_domain = irq_domain_add_linear(pcie_intc_node, 32,
 						   &event_domain_ops, port);
 	if (!port->pldma_domain)
-		return -ENOMEM;
+		goto err_put_node;
 
 	irq_domain_update_bus_token(port->pldma_domain, DOMAIN_BUS_NEXUS);
 
@@ -596,7 +596,7 @@ static int xilinx_pl_dma_pcie_init_irq_domain(struct pl_dma_pcie *port)
 						  &intx_domain_ops, port);
 	if (!port->intx_domain) {
 		dev_err(dev, "Failed to get a INTx IRQ domain\n");
-		return -ENOMEM;
+		goto err_put_node;
 	}
 
 	irq_domain_update_bus_token(port->intx_domain, DOMAIN_BUS_WIRED);
@@ -604,13 +604,17 @@ static int xilinx_pl_dma_pcie_init_irq_domain(struct pl_dma_pcie *port)
 	ret = xilinx_pl_dma_pcie_init_msi_irq_domain(port);
 	if (ret != 0) {
 		irq_domain_remove(port->intx_domain);
-		return -ENOMEM;
+		goto err_put_node;
 	}
 
 	of_node_put(pcie_intc_node);
 	raw_spin_lock_init(&port->lock);
 
 	return 0;
+
+err_put_node:
+	of_node_put(pcie_intc_node);
+	return -ENOMEM;
 }
 
 static int xilinx_pl_dma_pcie_setup_irq(struct pl_dma_pcie *port)
Signature · 1 line
2.53.0
author maintainer
#1307 lore raw

PATCH 1304/1536 iommufd: Reject a zero-length dirty bitmap request

In reply to Greg Kroah-Hartman

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

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

From: Andrea Parri <[email protected]>

[ Upstream commit f6b3fd8f573e801066c21b2aec3d2e949e61e48e ]

iommufd_check_iova_range() subtracts one from bitmap->length before it checks the length, so a zero-length request wraps to SIZE_MAX. With iova = 0 the wrapped value passes the overflow and alignment checks, and the request reaches iova_bitmap_alloc() with length 0.

iova_bitmap_alloc() then sizes the bitmap from a length - 1 of SIZE_MAX, so mapped_total_index is effectively unbounded. The scan uses last_iova = ULONG_MAX, which spans the whole IOAS when an area is mapped at IOVA 0. Reject a zero length before the subtraction.

Fixes b9a60d6f850e ("iommufd: Add IOMMU_HWPT_GET_DIRTY_BITMAP")
Assisted-by LLM
---
 drivers/iommu/iommufd/io_pagetable.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/iommu/iommufd/io_pagetable.c +3 -0
index 83b953f3b327b..177e8e12f189f 100644
@@ -521,6 +521,9 @@ int iommufd_check_iova_range(struct io_pagetable *iopt,
 	size_t iommu_pgsize = iopt->iova_alignment;
 	u64 last_iova;
 
+	if (!bitmap->length)
+		return -EINVAL;
+
 	if (check_add_overflow(bitmap->iova, bitmap->length - 1, &last_iova))
 		return -EOVERFLOW;
 
Signature · 1 line
2.53.0
author maintainer
#1308 lore raw

PATCH 1305/1536 crypto: qat - initialise state_lock on every path in adf_devmgr_add_dev()

In reply to Greg Kroah-Hartman

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

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

From: Ahsan Atta <[email protected]>

[ Upstream commit 4ad7c1bd5f3dcd3fd6efbb068d6ee2a68dddfece ]

state_lock is initialised at the end of adf_devmgr_add_dev(), but the VF on host path whose id mapping already exists returns earlier via 'goto unlock'. That mapping outlives the VF, so this path is taken every time a VF is recreated on a BDF that already hosted one, e.g.:

echo 0 > sriov_numvfs
echo 32 > sriov_numvfs

accel_dev is freshly allocated on each probe, so state_lock is left zeroed and adf_dev_up() takes an uninitialised mutex. With CONFIG_DEBUG_MUTEXES this is reported on a dh895xcc with 32 host-bound VFs:

DEBUG_LOCKS_WARN_ON(lock->magic != lock)

  WARNING: kernel/locking/mutex.c:159 at mutex_lock+0x171/0x1c0
  Call Trace:
   adf_dev_up+0x27/0xe0 [intel_qat]
   adf_probe+0x700/0xa80 [qat_dh895xccvf]
   local_pci_probe+0xd5/0x190

The same happens on teardown when adf_dev_down() locks it again.

Initialise the lock next to the other per-device state, before the tables are updated, so it is done on every path.

Fixes 1bdc85550a2b ("crypto: qat - fix concurrency issue when device state changes")
---
 drivers/crypto/intel/qat/qat_common/adf_dev_mgr.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/crypto/intel/qat/qat_common/adf_dev_mgr.c +1 -1
index 9013a04f425bb..8f7cabb37056d 100644
@@ -137,6 +137,7 @@ int adf_devmgr_add_dev(struct adf_accel_dev *accel_dev,
 
 	mutex_lock(&table_lock);
 	atomic_set(&accel_dev->ref_count, 0);
+	mutex_init(&accel_dev->state_lock);
 
 	/* PF on host or VF on guest - optimized to remove redundant is_vf */
 	if (!accel_dev->is_vf || !pf) {
@@ -210,7 +211,6 @@ int adf_devmgr_add_dev(struct adf_accel_dev *accel_dev,
 		map->attached = true;
 		list_add_tail(&map->list, &vfs_table);
 	}
-	mutex_init(&accel_dev->state_lock);
 unlock:
 	mutex_unlock(&table_lock);
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#1309 lore raw

PATCH 1306/1536 crypto: qat - fix use of destroyed vf2pf_lock on VF restart

In reply to Greg Kroah-Hartman

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

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

From: Ahsan Atta <[email protected]>

[ Upstream commit 4921634ac0a9a65aaa5e41308aabda3d3f562ee3 ]

adf_dev_stop_async() sends the RESTARTING_COMPLETE message after adf_dev_down() has returned, but adf_dev_down() already destroyed the lock that message takes.

Both run in sequence in the same worker, so every PF restart locks a destroyed mutex. With CONFIG_DEBUG_MUTEXES on a dh895xcc with 32 host-bound VFs this trips on the first PF reset:

DEBUG_LOCKS_WARN_ON(lock->magic != lock)

  WARNING: kernel/locking/mutex.c:159 at mutex_lock+0x171/0x1c0
  Workqueue: adf_vf_stop_wq adf_dev_stop_async [intel_qat]
  Call Trace:
   adf_gen2_pfvf_send+0x210/0x530 [intel_qat]
   adf_vf2pf_notify_restart_complete+0x55/0x80 [intel_qat]
   adf_dev_stop_async+0xdb/0x140 [intel_qat]

The notification cannot move before adf_dev_down(): the PF waits for it before its own reset and the VF must tear down its rings first.

vf2pf_lock protects the VF2PF CSR and is unrelated to the PF2VF bottom half it is initialised alongside. Tie its lifetime to the accel device, next to state_lock in adf_devmgr_add_dev()/adf_devmgr_rm_dev(), so it stays valid for messages sent outside the device up/down cycle. It is only touched for VFs, which set is_vf before adf_devmgr_add_dev() and keep it set until adf_devmgr_rm_dev().

Fixes 6f1b5236348f ("crypto: qat - fix recovery flow for VFs")
---
 drivers/crypto/intel/qat/qat_common/adf_dev_mgr.c | 8 ++++++++
 drivers/crypto/intel/qat/qat_common/adf_vf_isr.c  | 2 --
 2 files changed, 8 insertions(+), 2 deletions(-)
drivers/crypto/intel/qat/qat_common/adf_dev_mgr.c +8 -0
index 8f7cabb37056d..58b7ea7793fe3 100644
@@ -138,6 +138,12 @@ int adf_devmgr_add_dev(struct adf_accel_dev *accel_dev,
 	mutex_lock(&table_lock);
 	atomic_set(&accel_dev->ref_count, 0);
 	mutex_init(&accel_dev->state_lock);
+	/*
+	 * The VF2PF lock is used to send messages to the PF outside of the
+	 * device up/down cycle, so it must live as long as the accel device.
+	 */
+	if (accel_dev->is_vf)
+		mutex_init(&accel_dev->vf.vf2pf_lock);
 
 	/* PF on host or VF on guest - optimized to remove redundant is_vf */
 	if (!accel_dev->is_vf || !pf) {
@@ -257,6 +263,8 @@ void adf_devmgr_rm_dev(struct adf_accel_dev *accel_dev,
 		}
 	}
 unlock:
+	if (accel_dev->is_vf)
+		mutex_destroy(&accel_dev->vf.vf2pf_lock);
 	mutex_destroy(&accel_dev->state_lock);
 	list_del(&accel_dev->list);
 	mutex_unlock(&table_lock);
drivers/crypto/intel/qat/qat_common/adf_vf_isr.c +0 -2
index a4636ec9f9cac..9ff6f66483016 100644
@@ -118,7 +118,6 @@ static int adf_setup_pf2vf_bh(struct adf_accel_dev *accel_dev)
 	tasklet_init(&accel_dev->vf.pf2vf_bh_tasklet,
 		     (void *)adf_pf2vf_bh_handler, (unsigned long)accel_dev);
 
-	mutex_init(&accel_dev->vf.vf2pf_lock);
 	return 0;
 }
 
@@ -126,7 +125,6 @@ static void adf_cleanup_pf2vf_bh(struct adf_accel_dev *accel_dev)
 {
 	tasklet_disable(&accel_dev->vf.pf2vf_bh_tasklet);
 	tasklet_kill(&accel_dev->vf.pf2vf_bh_tasklet);
-	mutex_destroy(&accel_dev->vf.vf2pf_lock);
 }
 
 static irqreturn_t adf_isr(int irq, void *privdata)
Signature · 1 line
2.53.0
author maintainer
#1310 lore raw

PATCH 1307/1536 irqchip/gic-v3-its: Dont clamp nvecs to zero when id_bits is 32

In reply to Greg Kroah-Hartman

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

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

From: Fuad Tabba <[email protected]>

[ Upstream commit 5a9d62555e7164ec79a5fe70153d79cf1fdfd614 ]

GITS_TYPER_IDBITS is five bits, so id_bits reaches 32 and min_t(unsigned int, ...) truncates BIT(32) to 0. nvecs becomes 0, its_lpi_alloc() rejects that, and its_msi_prepare() returns -ENOMEM. On 32-bit ARM the shift is undefined instead.

The clamp is correct for every value below the maximum, so only that one value is affected.

Fixes ce9e40a9a5e5c ("irqchip/gic-v3-its: Limit number of per-device MSIs to the range the ITS supports")
---
 drivers/irqchip/irq-gic-v3-its.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/irqchip/irq-gic-v3-its.c +1 -1
index fdf8f1bd157ea..7ab93108c1096 100644
@@ -3407,7 +3407,7 @@ static struct its_device *its_create_device(struct its_node *its, u32 dev_id,
 	 * Also honor the ITS's own EID limit.
 	 */
 	id_bits = FIELD_GET(GITS_TYPER_IDBITS, its->typer) + 1;
-	nvecs = min_t(unsigned int, nvecs, BIT(id_bits));
+	nvecs = min_t(u64, nvecs, BIT_ULL(id_bits));
 	nr_ites = max(2, nvecs);
 	sz = nr_ites * (FIELD_GET(GITS_TYPER_ITT_ENTRY_SIZE, its->typer) + 1);
 	sz = max(sz, ITS_ITT_ALIGN) + ITS_ITT_ALIGN - 1;
Signature · 1 line
2.53.0
author maintainer
#1311 lore raw

PATCH 1308/1536 irqchip/imx-intmux: Fix runtime PM teardown on remove

In reply to Greg Kroah-Hartman

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

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

From: Guangshuo Li <[email protected]>

[ Upstream commit b167c1a30e9e020e4c5e102c7a555943742c024b ]

imx_intmux_probe() enables the IPG clock and then drops its runtime PM reference with pm_runtime_put(). With CONFIG_PM enabled, the runtime suspend callback disables the IPG clock. With CONFIG_PM disabled, the clock remains enabled after probe.

imx_intmux_remove() accesses the CHANIER registers without first making sure that the device is runtime active. The device may therefore be runtime suspended with the IPG clock disabled when these registers are accessed. In addition, the remove path only calls pm_runtime_disable() and does not balance the clock enable when CONFIG_PM is disabled.

Resume the device and acquire a runtime PM reference before accessing the registers. If resume fails, skip the register accesses but still tear down the chained handlers and IRQ domains. Disable runtime PM afterwards, drop the acquired reference without triggering another runtime suspend, and explicitly disable the IPG clock.

This keeps the clock enabled while the hardware registers are accessed and balances the clk_prepare_enable() performed during probe for both CONFIG_PM configurations.

This issue was found by manual code inspection.

Fixes bb403111e017 ("irqchip/imx-intmux: Implement intmux runtime power management")
---
 drivers/irqchip/irq-imx-intmux.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
drivers/irqchip/irq-imx-intmux.c +12 -3
index 511adfaeec822..3dcab30606c32 100644
@@ -289,12 +289,16 @@ static int imx_intmux_probe(struct platform_device *pdev)
 static void imx_intmux_remove(struct platform_device *pdev)
 {
 	struct intmux_data *data = platform_get_drvdata(pdev);
-	int i;
+	int i, ret;
+
+	ret = pm_runtime_resume_and_get(&pdev->dev);
+	if (ret < 0)
+		dev_warn(&pdev->dev, "failed to resume device: %d\n", ret);
 
 	for (i = 0; i < data->channum; i++) {
 		/* disable all interrupt sources of this channel */
-		writel_relaxed(0, data->regs + CHANIER(i));
-
+		if (ret >= 0)
+			writel_relaxed(0, data->regs + CHANIER(i));
 		irq_set_chained_handler_and_data(data->irqchip_data[i].irq,
 						 NULL, NULL);
 
@@ -302,6 +306,11 @@ static void imx_intmux_remove(struct platform_device *pdev)
 	}
 
 	pm_runtime_disable(&pdev->dev);
+	if (ret >= 0) {
+		pm_runtime_put_noidle(&pdev->dev);
+		clk_disable_unprepare(data->ipg_clk);
+		pm_runtime_set_suspended(&pdev->dev);
+	}
 }
 
 #ifdef CONFIG_PM
Signature · 1 line
2.53.0
author maintainer
#1312 lore raw

PATCH 1309/1536 irqchip/mchp-eic: Fix clock reference leak in mchp_eic_probe()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit af9c707eb065a7d48eb92dc15acdb4346acf5db0 ]

of_clk_get_by_name() returns the clock with an elevated reference count that mchp_eic_probe() keeps for the lifetime of the driver, but none of the probe error paths drops it, so the reference is leaked whenever probe fails after the clock has been obtained.

Put the reference in the error cleanup. The clk_prepare_enable() failure path must jump there directly as it cannot call clk_disable_unprepare() on a clock that was never enabled.

Fixes 00fa3461c86d ("irqchip/mchp-eic: Add support for the Microchip EIC")
---
 drivers/irqchip/irq-mchp-eic.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/irqchip/irq-mchp-eic.c +3 -1
index 2ad3c1d02d523..7f7ae5b14a62b 100644
@@ -232,7 +232,7 @@ static int mchp_eic_init(struct device_node *node, struct device_node *parent)
 
 	ret = clk_prepare_enable(eic->clk);
 	if (ret)
-		goto unmap;
+		goto clk_put;
 
 	for (i = 0; i < MCHP_EIC_NIRQ; i++) {
 		struct of_phandle_args irq;
@@ -268,6 +268,8 @@ static int mchp_eic_init(struct device_node *node, struct device_node *parent)
 
 clk_unprepare:
 	clk_disable_unprepare(eic->clk);
+clk_put:
+	clk_put(eic->clk);
 unmap:
 	iounmap(eic->base);
 free:
Signature · 1 line
2.53.0
author maintainer
#1313 lore raw

PATCH 1310/1536 ALSA: ump: Correct return size of fill_rpn()

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 85e8c5f933ee3dbc9d061e121237797e9fa05315 ]

The RPN/NRPN conversion in fill_rpn() is supposed to return the number of bytes of the resultant UMP packet, but it returns boolean values. This would result in the incorrect ump_bytes in the converter, which will confuse stream processing. Correct to the right value 8 as a MIDI 2.0 UMP packet.

Fixes e6ce8a28c768 ("ALSA: ump: Transmit RPN/NRPN message at each MSB/LSB data reception")
---
 sound/core/ump_convert.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/core/ump_convert.c +1 -1
index 85cc67de63306..0a7972d91ec52 100644
@@ -323,7 +323,7 @@ static int fill_rpn(struct ump_cvt_to_ump_bank *cc,
 					      cc->cc_data_lsb);
 
 	reset_rpn(cc);
-	return 1;
+	return 8;
 }
 
 /* convert to a MIDI 1.0 Channel Voice message */
Signature · 1 line
2.53.0
author maintainer
#1314 lore raw

PATCH 1311/1536 gfs2: fix the escaped block copy in gfs2_before_commit()

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit 1a4aeb6d6a08af1a2e2c52c84170561625819377 ]

Commit d68d0c6c3fc7 ("gfs2: Use memcpy_{from,to}_page where appropriate") made the escaped buffer copy read from the mempool page it had just allocated instead of from the buffer, so the block written to the log is whatever the pool page last held. If the journal is replayed after a crash, the block is restored from that and the file's data is corrupted. Only escaped buffers are affected: jdata blocks whose first four bytes match GFS2_MAGIC. Copy from the buffer's folio instead.

Fixes d68d0c6c3fc7 ("gfs2: Use memcpy_{from,to}_page where appropriate")
---
 fs/gfs2/lops.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/gfs2/lops.c +3 -1
index 314ec2a70167f..f86683abd0f4b 100644
@@ -693,7 +693,9 @@ static void gfs2_before_commit(struct gfs2_sbd *sdp, unsigned int limit,
 
 				page = mempool_alloc(gfs2_page_pool, GFP_NOIO);
 				p = page_address(page);
-				memcpy_from_page(p, page, bh_offset(bd2->bd_bh), bd2->bd_bh->b_size);
+				memcpy_from_folio(p, bd2->bd_bh->b_folio,
+						  bh_offset(bd2->bd_bh),
+						  bd2->bd_bh->b_size);
 				*(__be32 *)p = 0;
 				clear_buffer_escaped(bd2->bd_bh);
 				unlock_buffer(bd2->bd_bh);
Signature · 1 line
2.53.0
author maintainer
#1315 lore raw

PATCH 1312/1536 spi: jcore: fix divide-by-zero when speed_hz is zero

In reply to Greg Kroah-Hartman

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

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

From: Weibin Liu <[email protected]>

[ Upstream commit 7db773075501248893c22b11bedc6745d6d0be45 ]

jcore_spi_baudrate() computes hw->clock_freq / 2 / speed without validating speed. The SPI core fills transfer.speed_hz from spi->max_speed_hz when it is zero, and jcore_spi_probe() never sets host->max_speed_hz, so the clamp in __spi_setup() is skipped. A spi_device created via the sysfs new_device interface (or a DT node without spi-max-frequency) therefore has max_speed_hz == 0, and any SPI_IOC_MESSAGE transfer reaches jcore_spi_baudrate() with speed == 0, causing a division by zero and a kernel panic.

Clamp speed to a minimum of 1 Hz before the division so the divisor is never zero. The computed divider then truncates to the register field width and the transfer simply runs at the slowest supported rate.

Verified by inspection of the __spi_setup() clamp and __spi_validate()'s speed_hz handling; the division-by-zero path requires the J-Core controller, which was not available.

Fixes 2cb1b3b3ac0a ("spi: add driver for J-Core SPI controller")
---
 drivers/spi/spi-jcore.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/spi/spi-jcore.c +2 -0
index e37ca22e04ba6..2bde899eb2b49 100644
@@ -84,6 +84,8 @@ static void jcore_spi_baudrate(struct jcore_spi *hw, int speed)
 {
 	if (speed == hw->speed_hz)
 		return;
+	if (speed <= 0)
+		speed = 1;
 	hw->speed_hz = speed;
 	if (speed >= hw->clock_freq / 2)
 		hw->speed_reg = 0;
Signature · 1 line
2.53.0
author maintainer
#1316 lore raw

PATCH 1313/1536 efi/libstub: Dont replace an existing LINUX_EFI_MEMRESERVE table

In reply to Greg Kroah-Hartman

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

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

From: Ard Biesheuvel <[email protected]>

[ Upstream commit aaf3ed0f46298e18ec8bc477cf0a37478e41f2ea ]

The LINUX_EFI_MEMRESERVE table is the root of a linked list of memory reservations that need to persist across kexec, such as the GICv3 LPI pending and property tables, which cannot be moved once the redistributors have been enabled. Each kernel adds its own reservations to the list that it finds via the EFI configuration table, and honours the ones made by its predecessors.

The EFI stub installs a new, empty table unconditionally, replacing any existing one. This is fine on a cold boot, but not if the stub is being executed by a loader that passes on the configuration tables of an earlier kernel, e.g., a kexec loader that runs the incoming kernel's EFI stub, as the reservations made by earlier kernels would be lost.

So leave an existing table in place, and only install a new one if none exists yet.

---
 drivers/firmware/efi/libstub/efi-stub.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/firmware/efi/libstub/efi-stub.c +8 -0
index df5ffe2364429..438c7aed2d287 100644
@@ -81,6 +81,14 @@ static void install_memreserve_table(void)
 	efi_guid_t memreserve_table_guid = LINUX_EFI_MEMRESERVE_TABLE_GUID;
 	efi_status_t status;
 
+	/*
+	 * If an earlier boot stage installed a memreserve table already, e.g.,
+	 * a kexec loader passing on the persistent reservations made by the
+	 * previous kernel, use it as is: installing a new one would replace it.
+	 */
+	if (get_efi_config_table(memreserve_table_guid))
+		return;
+
 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, sizeof(*rsv),
 			     (void **)&rsv);
 	if (status != EFI_SUCCESS) {
Signature · 1 line
2.53.0
author maintainer
#1317 lore raw

PATCH 1314/1536 KVM: arm64: Move OUTSIDE_GUEST_MODE publication past context being saved

In reply to Greg Kroah-Hartman

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

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

From: Marc Zyngier <[email protected]>

[ Upstream commit 1d4ce2901f1e25b06d447c0b02d105d6dd3550d8 ]

OUTSIDE_GUEST_MODE indicates to the rest of KVM that the vcpu has exited. So far, this is set as soon as we return from the notional hypervisor (which with VHE is just a function call away).

However, code that uses OUTSIDE_GUEST_MODE as a synchronisation point relies on the vcpu state to have been written back to the in-memory structures. Clearly, this is not what is happening.

Move the publication of OUTSIDE_GUEST_MODE to the point where the state is actually written, and give this write release semantics to ensure the correct ordering.

---
 arch/arm64/kvm/arm.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
arch/arm64/kvm/arm.c +8 -2
index 2a156ddf0c314..818a742f90ad0 100644
@@ -1199,12 +1199,12 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		smp_store_mb(vcpu->mode, IN_GUEST_MODE);
 
 		if (ret <= 0 || kvm_vcpu_exit_request(vcpu, &ret)) {
-			vcpu->mode = OUTSIDE_GUEST_MODE;
 			isb(); /* Ensure work in x_flush_hwstate is committed */
 			kvm_pmu_sync_hwstate(vcpu);
 			if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
 				kvm_timer_sync_user(vcpu);
 			kvm_vgic_sync_hwstate(vcpu);
+			smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
 			local_irq_enable();
 			preempt_enable();
 			continue;
@@ -1221,7 +1221,6 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 
 		ret = kvm_arm_vcpu_enter_exit(vcpu);
 
-		vcpu->mode = OUTSIDE_GUEST_MODE;
 		vcpu->stat.exits++;
 		/*
 		 * Back from guest
@@ -1253,6 +1252,13 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 
 		kvm_arch_vcpu_ctxsync_fp(vcpu);
 
+		/*
+		 * The state that was pushed into the CPU on entering
+		 * the guest has been synchronised back, let's
+		 * advertise we're outside of the guest.
+		 */
+		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
+
 		/*
 		 * We must ensure that any pending interrupts are taken before
 		 * we exit guest timing so that timer ticks are accounted as
Signature · 1 line
2.53.0
author maintainer
#1318 lore raw

PATCH 1315/1536 KVM: arm64: Turn vcpu->arch.pause into a counter

In reply to Greg Kroah-Hartman

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

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

From: Marc Zyngier <[email protected]>

[ Upstream commit e64309198eda29415a95113def92aa40196cd422 ]

We have situations where we can call kvm_arm_halt_guest() without holding config_lock, which means that halt and resume can overlap in funny ways when called from separate contexts, and result in situations where a vcpu is resumed while other parts of KVM assume it is halted. Consequences are left to the imagination of the reader.

Fix this sorry situation by turning kvm_vcpu_arch::pause into an atomic counter, which makes the races described above harmless.

Fixes 3b92830ad41b2 ("KVM: arm/arm64: implement kvm_arm_[halt,resume]_guest")
---
 arch/arm64/include/asm/kvm_host.h |  7 +++----
 arch/arm64/kvm/arm.c              | 21 ++++++++++++---------
 2 files changed, 15 insertions(+), 13 deletions(-)
arch/arm64/include/asm/kvm_host.h +3 -4
index 4f6afd2c042fe..d955aa0aea8c2 100644
@@ -703,11 +703,10 @@ struct kvm_vcpu_arch {
 	/*
 	 * Don't run the guest (internal implementation need).
 	 *
-	 * Contrary to the flags above, this is set/cleared outside of
-	 * a vcpu context, and thus cannot be mixed with the flags
-	 * themselves (or the flag accesses need to be made atomic).
+	 * Contrary to the flags above, this is updated outside of
+	 * a vcpu context, and thus cannot be mixed with the flags.
 	 */
-	bool pause;
+	atomic_t pause;
 
 	/*
 	 * We maintain more than a single set of debug registers to support
arch/arm64/kvm/arm.c +12 -9
index 818a742f90ad0..97d993f52b575 100644
@@ -487,6 +487,7 @@ int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
 	kvm_arm_pvtime_vcpu_init(&vcpu->arch);
 
 	vcpu->arch.hw_mmu = &vcpu->kvm->arch.mmu;
+	atomic_set(&vcpu->arch.pause, 0);
 
 	/*
 	 * This vCPU may have been created after mpidr_data was initialized.
@@ -727,6 +728,11 @@ int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
 	return ret;
 }
 
+static bool vcpu_can_run(struct kvm_vcpu *vcpu)
+{
+	return !kvm_arm_vcpu_stopped(vcpu) && !atomic_read(&vcpu->arch.pause);
+}
+
 /**
  * kvm_arch_vcpu_runnable - determine if the vcpu can be scheduled
  * @v:		The VCPU pointer
@@ -742,8 +748,7 @@ int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
 		      (kvm_timer_should_notify_user(v) ||
 		       kvm_pmu_should_notify_user(v)));
 
-	return ((irq_lines || kvm_vgic_vcpu_pending_irq(v))
-		&& !kvm_arm_vcpu_stopped(v) && !v->arch.pause);
+	return ((irq_lines || kvm_vgic_vcpu_pending_irq(v)) && vcpu_can_run(v));
 }
 
 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
@@ -897,7 +902,7 @@ void kvm_arm_halt_guest(struct kvm *kvm)
 	struct kvm_vcpu *vcpu;
 
 	kvm_for_each_vcpu(i, vcpu, kvm)
-		vcpu->arch.pause = true;
+		atomic_inc(&vcpu->arch.pause);
 	kvm_make_all_cpus_request(kvm, KVM_REQ_SLEEP);
 }
 
@@ -907,8 +912,8 @@ void kvm_arm_resume_guest(struct kvm *kvm)
 	struct kvm_vcpu *vcpu;
 
 	kvm_for_each_vcpu(i, vcpu, kvm) {
-		vcpu->arch.pause = false;
-		__kvm_vcpu_wake_up(vcpu);
+		if (atomic_dec_and_test(&vcpu->arch.pause))
+			__kvm_vcpu_wake_up(vcpu);
 	}
 }
 
@@ -916,11 +921,9 @@ static void kvm_vcpu_sleep(struct kvm_vcpu *vcpu)
 {
 	struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
 
-	rcuwait_wait_event(wait,
-			   (!kvm_arm_vcpu_stopped(vcpu)) && (!vcpu->arch.pause),
-			   TASK_INTERRUPTIBLE);
+	rcuwait_wait_event(wait, vcpu_can_run(vcpu), TASK_INTERRUPTIBLE);
 
-	if (kvm_arm_vcpu_stopped(vcpu) || vcpu->arch.pause) {
+	if (!vcpu_can_run(vcpu)) {
 		/* Awaken to handle a signal, request we sleep again later. */
 		kvm_make_request(KVM_REQ_SLEEP, vcpu);
 	}
Signature · 1 line
2.53.0
author maintainer
#1319 lore raw

PATCH 1316/1536 spi: npcm-fiu: limit UMA data_size to the 16-byte staging buffer

In reply to Greg Kroah-Hartman

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

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

From: Weibin Liu <[email protected]>

[ Upstream commit f0be928a41384ea93c876364f360779f70359249 ]

npcm_fiu_uma_read() and npcm_fiu_uma_write() use a 16-byte on-stack staging buffer (u32 data_reg[4]) and move data_size bytes to or from it. data_size comes straight from op->data.nbytes, which is supplied by the SPI MEM operation and is not bounded by the driver:
npcm_fiu_exec_op() only validates op->addr.nbytes, and no adjust_op_size callback truncates the transfer to the controller FIFO size.

A SPI MEM operation with addr.nbytes == 0 and data.nbytes > 16 therefore overflows data_reg[] on the kernel stack (write path) or reads past it (read path), corrupting the stack.

Reject data_size larger than the staging buffer in both UMA helpers by returning -EOPNOTSUPP, so spi_mem falls back to the generic SPI message path. The chunked path in npcm_fiu_manualwrite() always passes at most CHUNK_SIZE bytes, so it is unaffected.

Fixes ace55c411b11 ("spi: npcm-fiu: add NPCM FIU controller driver")
---
 drivers/spi/spi-npcm-fiu.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/spi/spi-npcm-fiu.c +8 -0
index f3bb8bbc192f2..5be83535ae865 100644
@@ -342,6 +342,10 @@ static int npcm_fiu_uma_read(struct spi_mem *mem,
 	u32 val;
 	u32 i;
 
+	/* data_reg holds at most 16 bytes */
+	if (data_size > sizeof(data_reg))
+		return -EOPNOTSUPP;
+
 	regmap_update_bits(fiu->regmap, NPCM_FIU_UMA_CTS,
 			   NPCM_FIU_UMA_CTS_DEV_NUM,
 			   (spi_get_chipselect(mem->spi, 0) <<
@@ -397,6 +401,10 @@ static int npcm_fiu_uma_write(struct spi_mem *mem,
 	u32 val;
 	u32 i;
 
+	/* data_reg holds at most 16 bytes */
+	if (data_size > sizeof(data_reg))
+		return -EOPNOTSUPP;
+
 	regmap_update_bits(fiu->regmap, NPCM_FIU_UMA_CTS,
 			   NPCM_FIU_UMA_CTS_DEV_NUM,
 			   (spi_get_chipselect(mem->spi, 0) <<
Signature · 1 line
2.53.0
author maintainer
#1320 lore raw

PATCH 1317/1536 mfd: tps65217: Fix NULL pointer dereference on IRQ init failure

In reply to Greg Kroah-Hartman

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

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

From: Radiy Zhambakiev <[email protected]>

[ Upstream commit 0473a5b0663663b75573bf284beb77459e07c461 ]

tps65217_probe() ignores the return value of tps65217_irq_init(), so when the irq domain creation fails the probe still completes and the driver ends up bound with a NULL tps->irq_domain. Unloading the module then makes tps65217_remove() call irq_domain_remove() on the NULL pointer and oops the kernel. On top of that, irq_find_mapping() may fall back to the default irq domain and dispose of mappings that belong to other interrupt controllers.

Check the return value and abort the probe on failure so the error is reported and no inconsistent state is left for removal.

---
 drivers/mfd/tps65217.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/mfd/tps65217.c +3 -1
index 029ecc32f0782..a88dd69a2febc 100644
@@ -333,7 +333,9 @@ static int tps65217_probe(struct i2c_client *client)
 	}
 
 	if (client->irq) {
-		tps65217_irq_init(tps, client->irq);
+		ret = tps65217_irq_init(tps, client->irq);
+		if (ret)
+			return ret;
 	} else {
 		int i;
 
Signature · 1 line
2.53.0
author maintainer
#1321 lore raw

PATCH 1318/1536 mfd: tps65217: Check return value when masking interrupt sources

In reply to Greg Kroah-Hartman

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

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

From: Radiy Zhambakiev <[email protected]>

[ Upstream commit 66ed12c1e5a986bee1dc63f9bd9c7f068138a69a ]

tps65217_irq_init() ignores the error returned by tps65217_set_bits() when masking all interrupt sources. A failed register write leaves the driver's software mask out of sync with the hardware and may result in spurious interrupts.

Check the return value and propagate the error to the caller.

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

Fixes 6556bdacf646fcaa ("mfd: tps65217: Add support for IRQs")
---
 drivers/mfd/tps65217.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/mfd/tps65217.c +6 -2
index a88dd69a2febc..d4f09e5bf24cd 100644
@@ -155,8 +155,12 @@ static int tps65217_irq_init(struct tps65217 *tps, int irq)
 
 	/* Mask all interrupt sources */
 	tps->irq_mask = TPS65217_INT_MASK;
-	tps65217_set_bits(tps, TPS65217_REG_INT, TPS65217_INT_MASK,
-			  TPS65217_INT_MASK, TPS65217_PROTECT_NONE);
+	ret = tps65217_set_bits(tps, TPS65217_REG_INT, TPS65217_INT_MASK,
+				TPS65217_INT_MASK, TPS65217_PROTECT_NONE);
+	if (ret) {
+		dev_err(tps->dev, "Failed to mask interrupt sources: %d\n", ret);
+		return ret;
+	}
 
 	tps->irq_domain = irq_domain_add_linear(tps->dev->of_node,
 		TPS65217_NUM_IRQ, &tps65217_irq_domain_ops, tps);
Signature · 1 line
2.53.0
author maintainer
#1322 lore raw

PATCH 1319/1536 mfd: tps65217: Use devres for IRQ domain and wake teardown

In reply to Greg Kroah-Hartman

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

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

From: Radiy Zhambakiev <[email protected]>

[ Upstream commit cffd44d2d89524e2dda6adc7b0dd59363be1c8e6 ]

Removing the parent device used to tear the IRQ domain down in tps65217_remove() before the MFD children are unbound: the i2c core only releases the parent's devres after the remove callback returns, whereas devm_mfd_add_devices() registered its own devres action which unbinds the children. Children that requested interrupts from the domain (e.g. tps65217-charger) therefore call free_irq() on virtual IRQs whose descriptors have already been disposed. With CONFIG_SPARSE_IRQ free_irq() then returns early without stopping the threaded handler, leaking the irqaction, the IRQ kthread and a module reference.

Register the domain teardown as a devres action right after the domain is created instead. Devres actions are released in reverse order of registration, so the MFD children release their IRQs first, then the parent interrupt is freed and its thread stopped, and only then is the domain torn down. The same ordering covers probe failure, which no longer needs manual cleanup, and the remove callback can be dropped entirely.

Balance the enable_irq_wake() in tps65217_irq_init() by registering disable_irq_wake() as a devres action as well. Only do so when enabling actually succeeded, since the parent chip may not support setting wake-up.

Fixes 6556bdacf646fcaa ("mfd: tps65217: Add support for IRQs")
---
 drivers/mfd/tps65217.c | 57 +++++++++++++++++++++++++++++-------------
 1 file changed, 39 insertions(+), 18 deletions(-)
drivers/mfd/tps65217.c +39 -18
index d4f09e5bf24cd..518c109a02589 100644
@@ -146,6 +146,31 @@ static const struct irq_domain_ops tps65217_irq_domain_ops = {
 	.map = tps65217_irq_map,
 };
 
+static void tps65217_irq_cleanup(void *data)
+{
+	struct tps65217 *tps = data;
+	unsigned int virq;
+
+	if (!tps->irq_domain)
+		return;
+
+	for (int i = 0; i < TPS65217_NUM_IRQ; i++) {
+		virq = irq_find_mapping(tps->irq_domain, i);
+		if (virq)
+			irq_dispose_mapping(virq);
+	}
+
+	irq_domain_remove(tps->irq_domain);
+	tps->irq_domain = NULL;
+}
+
+static void tps65217_irq_wake_disable(void *data)
+{
+	unsigned long irq = (unsigned long)data;
+
+	disable_irq_wake(irq);
+}
+
 static int tps65217_irq_init(struct tps65217 *tps, int irq)
 {
 	int ret;
@@ -169,6 +194,10 @@ static int tps65217_irq_init(struct tps65217 *tps, int irq)
 		return -ENOMEM;
 	}
 
+	ret = devm_add_action_or_reset(tps->dev, tps65217_irq_cleanup, tps);
+	if (ret)
+		return ret;
+
 	ret = devm_request_threaded_irq(tps->dev, irq, NULL,
 					tps65217_irq_thread, IRQF_ONESHOT,
 					"tps65217-irq", tps);
@@ -178,7 +207,16 @@ static int tps65217_irq_init(struct tps65217 *tps, int irq)
 		return ret;
 	}
 
-	enable_irq_wake(irq);
+	ret = enable_irq_wake(irq);
+	if (ret) {
+		dev_warn(tps->dev, "failed to enable IRQ wake: %d\n", ret);
+		return 0;
+	}
+
+	ret = devm_add_action_or_reset(tps->dev, tps65217_irq_wake_disable,
+				       (void *)(unsigned long)irq);
+	if (ret)
+		return ret;
 
 	return 0;
 }
@@ -379,22 +417,6 @@ static int tps65217_probe(struct i2c_client *client)
 	return 0;
 }
 
-static void tps65217_remove(struct i2c_client *client)
-{
-	struct tps65217 *tps = i2c_get_clientdata(client);
-	unsigned int virq;
-	int i;
-
-	for (i = 0; i < TPS65217_NUM_IRQ; i++) {
-		virq = irq_find_mapping(tps->irq_domain, i);
-		if (virq)
-			irq_dispose_mapping(virq);
-	}
-
-	irq_domain_remove(tps->irq_domain);
-	tps->irq_domain = NULL;
-}
-
 static const struct i2c_device_id tps65217_id_table[] = {
 	{"tps65217", TPS65217},
 	{ /* sentinel */ }
@@ -408,7 +430,6 @@ static struct i2c_driver tps65217_driver = {
 	},
 	.id_table	= tps65217_id_table,
 	.probe		= tps65217_probe,
-	.remove		= tps65217_remove,
 };
 
 static int __init tps65217_init(void)
Signature · 1 line
2.53.0
author maintainer
#1323 lore raw

PATCH 1320/1536 ASoC: qcom: q6apm: reset the hw pointer with the fragment queue

In reply to Greg Kroah-Hartman

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

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

From: Vladyslav Tymoshchuk <[email protected]>

[ Upstream commit 0337b8129cf676b8eb767b2a1f312955760a5460 ]

On every prepare in queue mode, q6apm_dai_prepare() frees and allocates the fragments again, and q6apm_alloc_fragments() resets dsp_buf, so the first buffer queued after it is the first one of the ring. The hw pointer that q6apm_dai_pointer() reports is left as it was.

q6apm-dai used to keep its own position and cleared it in prepare. Since commit a93dad6f4e6a ("ASoC: q6apm-dai: make use of q6apm_get_hw_pointer") the position comes from the hw pointer, so a stream that is prepared again, e.g. to recover from an xrun, reports the position of the previous run until the DSP returns its first buffer, while ALSA has reset its own pointer to 0.

Reset the hw pointer together with dsp_buf.

Fixes a93dad6f4e6a ("ASoC: q6apm-dai: make use of q6apm_get_hw_pointer")
Assisted-by Claude:claude-opus-5-5
---
 sound/soc/qcom/qdsp6/q6apm.c | 1 +
 1 file changed, 1 insertion(+)
sound/soc/qcom/qdsp6/q6apm.c +1 -0
index 50a496e665f85..426c1429d01be 100644
@@ -223,6 +223,7 @@ int q6apm_map_memory_regions(struct q6apm_graph *graph, unsigned int dir, phys_a
 	mutex_lock(&graph->lock);
 
 	data->dsp_buf = 0;
+	atomic_set(&data->hw_ptr, 0);
 
 	if (data->buf) {
 		mutex_unlock(&graph->lock);
Signature · 1 line
2.53.0
author maintainer
#1324 lore raw

PATCH 1321/1536 spi: bcm-qspi: reject oversized dummy bytes in mspi exec_mem_op

In reply to Greg Kroah-Hartman

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

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

From: Weibin Liu <[email protected]>

[ Upstream commit 9e44f0df3fff215d9033089e85980048c3ac132a ]

bcm_qspi_mspi_exec_mem_op() builds a local command buffer cmd[6] holding one opcode byte, up to four address bytes and one spare byte, and sets t[0].len = op->addr.nbytes + op->dummy.nbytes + 1. bcm_qspi_exec_mem_op() only validates op->addr.nbytes <= 4 and never bounds op->dummy.nbytes, which spi_mem_check_op() also leaves unrestricted. With addr.nbytes = 4 and dummy.nbytes >= 2 the length becomes 7 or more, so write_to_hw() reads past cmd[] on the kernel stack and pushes the leaked bytes into the hardware TXRAM.

Reject operations whose dummy phase does not fit the remaining byte of cmd[] by requiring op->dummy.nbytes <= 1, so such transfers fall back to the generic SPI path instead of overrunning the buffer.

Fixes 5f195ee7d830c ("spi: bcm-qspi: Implement the spi_mem interface")
---
 drivers/spi/spi-bcm-qspi.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/spi/spi-bcm-qspi.c +2 -1
index ae5545be0a45c..de333a4a3200d 100644
@@ -1197,8 +1197,9 @@ static int bcm_qspi_exec_mem_op(struct spi_mem *mem,
 	u32 addr = 0, len;
 	u_char *buf;
 
+	/* cmd[] holds 1 opcode + 4 address + 1 dummy byte at most */
 	if (!op->data.nbytes || !op->addr.nbytes || op->addr.nbytes > 4 ||
-	    op->data.dir != SPI_MEM_DATA_IN)
+	    op->dummy.nbytes > 1 || op->data.dir != SPI_MEM_DATA_IN)
 		return -EOPNOTSUPP;
 
 	buf = op->data.buf.in;
Signature · 1 line
2.53.0
author maintainer
#1325 lore raw

PATCH 1322/1536 spi: amd: fix len==0 underflow and FIFO overflow

In reply to Greg Kroah-Hartman

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

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

From: Weibin Liu <[email protected]>

[ Upstream commit e2f4edfc061e493fddde16c4bbe1c4f230f41e4a ]

amd_spi_fifo_xfer() unconditionally decrements xfer->len when a tx_buf is present. The SPI core does not reject zero-length transfers, so a transfer submitted through the SPI_IOC_MESSAGE ioctl with len == 0 and a tx_buf makes the u32 len wrap to 0xFFFFFFFF, and the following per-byte loop writes far past the FIFO window.

The driver also never checks the cumulative FIFO offset against AMD_SPI_FIFO_SIZE. The core splits each transfer down to the controller's max transfer size but does not bound the total message length, so a message of several transfers whose total exceeds the FIFO overflows it with out-of-bounds MMIO writes (tx) and reads (rx).

Skip zero-length transfers and reject any transfer that would run past the end of the FIFO window.

Tested with a user-space replica of the fifo_xfer length arithmetic (ASAN build): a zero-length transfer with tx_buf makes len-- wrap to 0xffffffff, and skipping zero-length transfers avoids the wrap. No AMD SPI hardware was available, so the FIFO bound check was verified by inspection against AMD_SPI_FIFO_SIZE.

Fixes bbb336f39efc ("spi: spi-amd: Add AMD SPI controller driver support")
---
 drivers/spi/spi-amd.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
drivers/spi/spi-amd.c +17 -0
index 2245ad54b03aa..8f8d1ac4f722d 100644
@@ -286,11 +286,22 @@ static inline int amd_spi_fifo_xfer(struct amd_spi *amd_spi,
 
 	list_for_each_entry(xfer, &message->transfers,
 			    transfer_list) {
+		/* Skip zero-length transfers to avoid len underflow below */
+		if (!xfer->len)
+			continue;
+
 		if (xfer->speed_hz)
 			amd_set_spi_freq(amd_spi, xfer->speed_hz);
 		else
 			amd_set_spi_freq(amd_spi, spi->max_speed_hz);
 
+		/* Reject transfers that would overflow the FIFO window */
+		if (fifo_pos + xfer->len >
+		    AMD_SPI_FIFO_BASE + AMD_SPI_FIFO_SIZE) {
+			message->status = -EMSGSIZE;
+			goto fin_msg;
+		}
+
 		if (xfer->tx_buf) {
 			buf = (u8 *)xfer->tx_buf;
 			if (!tx_len) {
@@ -333,6 +344,12 @@ static inline int amd_spi_fifo_xfer(struct amd_spi *amd_spi,
 
 		list_for_each_entry(xfer, &message->transfers, transfer_list)
 			if (xfer->rx_buf) {
+				/* Reject transfers that would overflow the FIFO window */
+				if (fifo_pos + xfer->len >
+				    AMD_SPI_FIFO_BASE + AMD_SPI_FIFO_SIZE) {
+					message->status = -EMSGSIZE;
+					goto fin_msg;
+				}
 				buf = (u8 *)xfer->rx_buf;
 				/* Read data from FIFO to receive buffer */
 				for (i = 0; i < xfer->len; i++)
Signature · 1 line
2.53.0
author maintainer
#1326 lore raw

PATCH 1323/1536 erofs: use on-disk blkszbits for lz4 max pcluster bound

In reply to Greg Kroah-Hartman

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

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

From: Gyokhan Kochmarla <[email protected]>

[ Upstream commit 90b7e4a7a16443d9f6807b5c1dde52074d9f74c0 ]

z_erofs_load_lz4_config() rejects a valid LZ4 image when the kernel's page size differs from the image's block size. It bounds the on-disk max_pclusterblks with erofs_blknr(sb, Z_EROFS_PCLUSTER_MAX_SIZE), which expands to Z_EROFS_PCLUSTER_MAX_SIZE >> sb->s_blocksize_bits.

At the point this runs, sb->s_blocksize_bits still holds PAGE_SHIFT:
erofs_fc_fill_super() seeds s_blocksize_bits to PAGE_SHIFT before reading the superblock, and only corrects it down to the on-disk blkszbits after erofs_read_superblock() returns. The LZ4 config is parsed inside erofs_read_superblock(), before that correction, so the bound is computed with the wrong shift.

On a 64K-page kernel mounting a 4K-block image (e.g. one built with mkfs.erofs -C 262144 on a 4K-page host), the bound evaluates to 1 MiB >> 16 = 16 blocks instead of the correct 1 MiB >> 12 = 256 blocks. The image's legitimate max_pclusterblks of 64 then fails the check, mount returns -EINVAL, and booting from such an image as the root filesystem panics:

erofs (device dm-0): too large lz4 pclusterblks 64

  Kernel panic - not syncing: VFS: Unable to mount root fs

sbi->blkszbits already holds the on-disk block size at this point, so compute the bound from it directly. This makes the check independent of the host page size and of superblock-parse ordering.

commit 3acea5fc3354 ("erofs: avoid hardcoded blocksize for subpage block support") already handled the same ordering hazard for the superblock checksum path by using sbi->blkszbits in erofs_superblock_csum_verify(); the lz4 config path was missed.

Fixes 3acea5fc3354 ("erofs: avoid hardcoded blocksize for subpage block support")
Assisted-by Kirocrew:gpt-5.6-sol
---
 fs/erofs/decompressor.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/erofs/decompressor.c +1 -1
index 933347416513b..970cc3f25bee9 100644
@@ -26,7 +26,7 @@ static int z_erofs_load_lz4_config(struct super_block *sb,
 		if (!sbi->lz4.max_pclusterblks) {
 			sbi->lz4.max_pclusterblks = 1;	/* reserved case */
 		} else if (sbi->lz4.max_pclusterblks >
-			   erofs_blknr(sb, Z_EROFS_PCLUSTER_MAX_SIZE)) {
+			   Z_EROFS_PCLUSTER_MAX_SIZE >> sbi->blkszbits) {
 			erofs_err(sb, "too large lz4 pclusterblks %u",
 				  sbi->lz4.max_pclusterblks);
 			return -EINVAL;
Signature · 1 line
2.53.0
author maintainer
#1327 lore raw

PATCH 1324/1536 ring-buffer: Take cpus_read_lock() when changing the subbuf order

In reply to Greg Kroah-Hartman

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

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

From: David Carlier <[email protected]>

[ Upstream commit 453d0f47b174cac387af48d303c503b84f82212e ]

A CPU coming online for the first time gets its per CPU buffer allocated by trace_rb_cpu_prepare(), which then adds it to buffer->cpumask. If that happens while ring_buffer_subbuf_order_set() is running, the CPU shows up after the allocation loop and the install loop walks it with an empty new_pages list, corrupting the buffer.

Take cpus_read_lock() as ring_buffer_resize() does.

---
 kernel/trace/ring_buffer.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/trace/ring_buffer.c +2 -0
index e894a5686be30..a203c19cebce2 100644
@@ -6828,6 +6828,8 @@ int ring_buffer_subbuf_order_set(struct trace_buffer *buffer, int order)
 	if (psize > RB_WRITE_MASK + 1)
 		return -EINVAL;
 
+	guard(cpus_read_lock)();
+
 	/* prevent another thread from changing buffer sizes */
 	guard(mutex)(&buffer->mutex);
 
Signature · 1 line
2.53.0
author maintainer
#1328 lore raw

PATCH 1325/1536 dax: Return errors from dax_core_init()

In reply to Greg Kroah-Hartman

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

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

From: Jianyun Gao <[email protected]>

[ Upstream commit 4da700e2cadf84a6e858391d5be51d64dcba080f ]

dax_core_init() returns success when either the character device number allocation or DAX bus registration fails, even though the error paths have already released the initialized resources.

For modular DAX, this allows the module to remain loaded despite failed initialization, leaving subsequent users and module removal to access resources that have already been released.

Return the error code from the failed operation so that module loading fails rather than reporting successful initialization after the resources have been released.

---
 drivers/dax/super.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/dax/super.c +1 -1
index 6eb7ecd233840..718da8ab8a002 100644
@@ -602,7 +602,7 @@ static int __init dax_core_init(void)
 	unregister_chrdev_region(dax_devt, MINORMASK+1);
 err_chrdev:
 	dax_fs_exit();
-	return 0;
+	return rc;
 }
 
 static void __exit dax_core_exit(void)
Signature · 1 line
2.53.0
author maintainer
#1329 lore raw

PATCH 1326/1536 dax: fix dax_range_compare_iter() to use correct size and address offset

In reply to Greg Kroah-Hartman

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

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

From: Jianyun Gao <[email protected]>

[ Upstream commit a4bfbfb4e98a62b589ac7ca9e73e9612bfe8cab7 ]

dax_range_compare_iter() has two bugs in how it calls dax_iomap_direct_access() and uses the returned addresses:

1. The size argument passed to dax_iomap_direct_access() is ALIGN(pos + len, PAGE_SIZE), which is an absolute file offset rather than a length. This causes the underlying dax_direct_access() to request a massively inflated nr_pages via PHYS_PFN(size).

2. The addresses returned by dax_iomap_direct_access() are page-aligned starting addresses, but memcmp() compares from saddr/daddr directly without adding the page-in-page offset of pos1/pos2. When pos1/pos2 are not page-aligned, this compares the wrong data.

Fix the size by computing ALIGN(len + offset_in_page(pos), PAGE_SIZE), matching the pattern used in dax_iomap_copy_around(). Fix the address by adding offset_in_page(pos1)/offset_in_page(pos2) to saddr/daddr in the memcmp() call.

Fixes 6f7db3894ae2 ("fsdax: dedup file range to use a compare function")
---
 fs/dax.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)
fs/dax.c +7 -5
index 756400f2a6257..ae1e9497b4168 100644
@@ -2006,6 +2006,7 @@ static loff_t dax_range_compare_iter(struct iomap_iter *it_src,
 	const struct iomap *dmap = &it_dest->iomap;
 	loff_t pos1 = it_src->pos, pos2 = it_dest->pos;
 	void *saddr, *daddr;
+	size_t size1, size2;
 	int id, ret;
 
 	len = min(len, min(smap->length, dmap->length));
@@ -2021,17 +2022,18 @@ static loff_t dax_range_compare_iter(struct iomap_iter *it_src,
 	}
 
 	id = dax_read_lock();
-	ret = dax_iomap_direct_access(smap, pos1, ALIGN(pos1 + len, PAGE_SIZE),
-				      &saddr, NULL);
+	size1 = ALIGN(len + offset_in_page(pos1), PAGE_SIZE);
+	ret = dax_iomap_direct_access(smap, pos1, size1, &saddr, NULL);
 	if (ret < 0)
 		goto out_unlock;
 
-	ret = dax_iomap_direct_access(dmap, pos2, ALIGN(pos2 + len, PAGE_SIZE),
-				      &daddr, NULL);
+	size2 = ALIGN(len + offset_in_page(pos2), PAGE_SIZE);
+	ret = dax_iomap_direct_access(dmap, pos2, size2, &daddr, NULL);
 	if (ret < 0)
 		goto out_unlock;
 
-	*same = !memcmp(saddr, daddr, len);
+	*same = !memcmp(saddr + offset_in_page(pos1),
+			daddr + offset_in_page(pos2), len);
 	if (!*same)
 		len = 0;
 	dax_read_unlock(id);
Signature · 1 line
2.53.0
author maintainer
#1330 lore raw

PATCH 1327/1536 net: skbuff: dont BUG() on a bad csum_start in skb_copy_and_csum_dev()

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 56453199d28f0072a8196fba14b2d702632e2219 ]

skb_copy_and_csum_dev() copies everything up to the checksum start out of the linear area, and BUG()s if the checksum start is past the end of the linear area. It misses the other direction: a CHECKSUM_PARTIAL skb that has been pulled past its csum_start gives a negative offset, which gets past the check and becomes a ~4GB copy. It also trusts csum_offset when it stores the folded checksum. So far skb_copy_and_csum_bits() BUG()ing on a short skb has covered for that, but once it returns instead, a bad csum_offset would write past the end of the caller's buffer.

The function returns void and its callers are drivers copying a frame into a bounce buffer just before handing it to the hardware. There's nothing for them to back out of, so check both ends of csum_start and that the checksum field fits in the frame, and if not, copy the whole frame with skb_copy_bits() without filling in the checksum, with a DEBUG_NET_WARN_ON_ONCE() for debug kernels. The frame
goes out with a bad checksum and is dropped by the receiver. If even that copy fails, zero the buffer so the driver doesn't send stale bytes.

Cc stable? The trailers only have Assisted-by: and Signed-off-by:. No
---
 net/core/skbuff.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
net/core/skbuff.c +12 -1
index 6d7e2d48cc492..04862f052adcf 100644
@@ -3887,7 +3887,18 @@ void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
 	else
 		csstart = skb_headlen(skb);
 
-	BUG_ON(csstart > skb_headlen(skb));
+	if (unlikely(csstart < 0 || csstart > skb_headlen(skb) ||
+		     (skb->ip_summed == CHECKSUM_PARTIAL &&
+		      csstart + skb->csum_offset + sizeof(__sum16) >
+		      skb->len))) {
+		DEBUG_NET_WARN_ON_ONCE(1);
+		/* Send the frame without the checksum filled in, or send
+		 * zeroes if we can't even copy it.
+		 */
+		if (skb_copy_bits(skb, 0, to, skb->len))
+			memset(to, 0, skb->len);
+		return;
+	}
 
 	skb_copy_from_linear_data(skb, to, csstart);
 
Signature · 1 line
2.53.0
author maintainer
#1331 lore raw

PATCH 1328/1536 ipv6: defrag: orphan skb before queuing

In reply to Greg Kroah-Hartman

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

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

From: Zixuan Chai <[email protected]>

[ Upstream commit 5dfa91a5ec53cfbf907a1fca095ac3ac7a4e94c9 ]

IPv4 and nf_conntrack fragment queues orphan skbs before returning -EINPROGRESS, but ip6_frag_queue() leaves the socket association intact.

Commit 18685451fc4e ("inet: inet_defrag: prevent sk release while still in use") moved skb_orphan() into ip_frag_queue() and nf_ct_frag6_queue(), but missed ip6_frag_queue().

Without orphaning, inet_frag_reasm_finish() clears fp->sk on frag_list skbs but leaves fp->destructor set to sock_pfree. Freeing the reassembled skb then calls sock_pfree() with a NULL socket. A socket using SOCK_RCU_FREE may also be released while its fragment is queued, leaving a stale socket pointer; this is a second consequence of the same missing orphan.

Orphan the skb before returning -EINPROGRESS so the queued fragment no longer retains the socket association or destructor.

---
 net/ipv6/reassembly.c | 1 +
 1 file changed, 1 insertion(+)
net/ipv6/reassembly.c +1 -0
index e8e58875fc726..29e15ff9d7c1e 100644
@@ -227,6 +227,7 @@ static int ip6_frag_queue(struct net *net,
 	}
 
 	skb_dst_drop(skb);
+	skb_orphan(skb);
 	return -EINPROGRESS;
 
 insert_error:
Signature · 1 line
2.53.0
author maintainer
#1332 lore raw

PATCH 1329/1536 sctp: hold transport reference across connect wait

In reply to Greg Kroah-Hartman

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

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

From: Seung Min Shin <[email protected]>

[ Upstream commit 5bef8649bb9ac4b2a014bcc227202ebd2df824be ]

sctp_sendmsg_to_asoc() selects a transport before waiting for a new interleaved association to become established. sctp_wait_for_connect() drops the socket lock while sleeping.

While the lock is dropped, backlog processing can handle a COOKIE ACK and an ASCONF DEL-IP that removes the selected transport. sctp_assoc_rm_peer() then marks the transport dead and drops its association-owned reference. The transport can be freed through RCU before the send path resumes.

After the wait, the stale pointer is assigned to newly created DATA or I-DATA chunks and later dereferenced by sctp_outq_select_transport().

Hold a reference to the selected transport across sctp_wait_for_connect(). After the socket lock is reacquired, abort the send if the transport was marked dead. Callers without a selected transport pass NULL and retain their existing behavior.

Fixes 668c9beb9020 ("sctp: implement assign_number for sctp_stream_interleave")
---
 net/sctp/socket.c | 26 +++++++++++++++++++-------
 1 file changed, 19 insertions(+), 7 deletions(-)
net/sctp/socket.c +19 -7
index 4c089e041caea..e2885a994314a 100644
@@ -76,7 +76,8 @@ static int sctp_wait_for_sndbuf(struct sctp_association *asoc,
 				struct sctp_transport *transport,
 				long *timeo_p, size_t msg_len);
 static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p);
-static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
+static int sctp_wait_for_connect(struct sctp_association *,
+				 struct sctp_transport *, long *timeo_p);
 static int sctp_wait_for_accept(struct sock *sk, long timeo);
 static void sctp_wait_for_close(struct sock *sk, long timeo);
 static void sctp_destruct_sock(struct sock *sk);
@@ -1245,7 +1246,7 @@ static int __sctp_connect(struct sock *sk, struct sockaddr *kaddrs,
 		*assoc_id = asoc->assoc_id;
 
 	timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
-	return sctp_wait_for_connect(asoc, &timeo);
+	return sctp_wait_for_connect(asoc, NULL, &timeo);
 
 out_free:
 	pr_debug("%s: took out_free path with asoc:%p kaddrs:%p err:%d\n",
@@ -1847,7 +1848,7 @@ static int sctp_sendmsg_to_asoc(struct sctp_association *asoc,
 
 		if (asoc->ep->intl_enable) {
 			timeo = sock_sndtimeo(sk, 0);
-			err = sctp_wait_for_connect(asoc, &timeo);
+			err = sctp_wait_for_connect(asoc, transport, &timeo);
 			if (err || sk->sk_shutdown & RCV_SHUTDOWN) {
 				err = -ESRCH;
 				goto err;
@@ -1890,7 +1891,7 @@ static int sctp_sendmsg_to_asoc(struct sctp_association *asoc,
 
 	if (unlikely(wait_connect)) {
 		timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
-		sctp_wait_for_connect(asoc, &timeo);
+		sctp_wait_for_connect(asoc, NULL, &timeo);
 	}
 
 	err = msg_len;
@@ -9364,7 +9365,9 @@ static bool sctp_writeable(const struct sock *sk)
 /* Wait for an association to go into ESTABLISHED state. If timeout is 0,
  * returns immediately with EINPROGRESS.
  */
-static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
+static int sctp_wait_for_connect(struct sctp_association *asoc,
+				 struct sctp_transport *transport,
+				 long *timeo_p)
 {
 	struct sock *sk = asoc->base.sk;
 	int err = 0;
@@ -9373,12 +9376,16 @@ static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
 
 	pr_debug("%s: asoc:%p, timeo:%ld\n", __func__, asoc, *timeo_p);
 
-	/* Increment the association's refcnt.  */
+	/* Hold references while the socket lock is dropped. */
+	if (transport)
+		sctp_transport_hold(transport);
 	sctp_association_hold(asoc);
 
 	for (;;) {
 		prepare_to_wait_exclusive(&asoc->wait, &wait,
 					  TASK_INTERRUPTIBLE);
+		if (transport && transport->dead)
+			goto do_transport_dead;
 		if (!*timeo_p)
 			goto do_nonblock;
 		if (sk->sk_shutdown & RCV_SHUTDOWN)
@@ -9407,7 +9414,8 @@ static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
 out:
 	finish_wait(&asoc->wait, &wait);
 
-	/* Release the association's refcnt.  */
+	if (transport)
+		sctp_transport_put(transport);
 	sctp_association_put(asoc);
 
 	return err;
@@ -9426,6 +9434,10 @@ static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
 do_nonblock:
 	err = -EINPROGRESS;
 	goto out;
+
+do_transport_dead:
+	err = -EAGAIN;
+	goto out;
 }
 
 static int sctp_wait_for_accept(struct sock *sk, long timeo)
Signature · 1 line
2.53.0
author maintainer
#1333 lore raw

PATCH 1330/1536 RDS/IB: validate receive fragment completions

In reply to Greg Kroah-Hartman

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

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

From: Shubham Antil <[email protected]>

[ Upstream commit 65cf6863606b0507a7c3bd1711317e4f5d6b8b7e ]

rds_ib_process_recv() accounts every receive fragment as contributing min(i_recv_data_rem, RDS_FRAG_SIZE) bytes, regardless of the completion length. When a completion is shorter than the header-declared amount, receive accounting can advance beyond the payload supplied by the completion.

Only an IB_WC_RECV completion has the buffer layout expected by this receive path. Other successful completion opcodes must not be interpreted as ordinary receive completions.

Reject successful completions with any other opcode before processing their length. For ordinary receive completions, require enough payload to cover the amount accounted to the fragment before linking its page into the incoming message.

This is compatible with the current transmit paths. MSG_ZEROCOPY is restricted to RDS/TCP, while RDS/IB copied and page-vector messages use full-sized non-final scatterlist entries.

Found during an LLM-assisted source audit and validated under KMSAN with a malformed short receive completion.

---
 net/rds/ib_recv.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
net/rds/ib_recv.c +12 -1
index 7310ac4d4be48..7f918fb377de4 100644
@@ -949,6 +949,12 @@ static void rds_ib_process_recv(struct rds_connection *conn,
 		}
 	}
 
+	if (data_len < min_t(u32, ic->i_recv_data_rem, RDS_FRAG_SIZE)) {
+		rds_ib_conn_error(conn,
+				  "fragment shorter than header-declared length; forcing reconnect\n");
+		goto done;
+	}
+
 	list_add_tail(&recv->r_frag->f_item, &ibinc->ii_frags);
 	recv->r_frag = NULL;
 
@@ -1004,7 +1010,12 @@ void rds_ib_recv_cqe_handler(struct rds_ib_connection *ic,
 	 * event is processed.
 	 */
 	if (wc->status == IB_WC_SUCCESS) {
-		rds_ib_process_recv(conn, recv, wc->byte_len, state);
+		if (wc->opcode != IB_WC_RECV)
+			rds_ib_conn_error(conn,
+					  "recv completion had unexpected opcode %u, disconnecting and reconnecting\n",
+					  wc->opcode);
+		else
+			rds_ib_process_recv(conn, recv, wc->byte_len, state);
 	} else {
 		/* We expect errors as the qp is drained during shutdown */
 		if (rds_conn_up(conn) || rds_conn_connecting(conn))
Signature · 1 line
2.53.0
author maintainer
#1334 lore raw

PATCH 1331/1536 cpufreq: loongson3: Make this driver depend on MACH_LOONGSON64

In reply to Greg Kroah-Hartman

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

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

From: Huacai Chen <[email protected]>

[ Upstream commit 48a82a3f44576a1b227f964fdb150e1cae7455bf ]

32BIT Loongson machines don't have SMC and FreqCtrl registers, so make this driver depend on MACH_LOONGSON64 (only for LoongArch based 64bit machines currently).

Fixes ccf51454145b ("cpufreq: Add Loongson-3 CPUFreq driver support")
---
 drivers/cpufreq/Kconfig | 1 +
 1 file changed, 1 insertion(+)
drivers/cpufreq/Kconfig +1 -0
index f089a1b9c0c98..42cb32e928a62 100644
@@ -263,6 +263,7 @@ endif
 if LOONGARCH
 config LOONGSON3_CPUFREQ
 	tristate "Loongson3 CPUFreq Driver"
+	depends on MACH_LOONGSON64
 	help
 	  This option adds a CPUFreq driver for Loongson processors which
 	  support software configurable cpu frequency.
Signature · 1 line
2.53.0
author maintainer
#1335 lore raw

PATCH 1332/1536 cpufreq: loongson3: Adjust the width of id and val in smc_message

In reply to Greg Kroah-Hartman

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

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

From: Huacai Chen <[email protected]>

[ Upstream commit 290814d3c22b300eb36b74dc76ad36bd7fdc1220 ]

The id field of smc_message is usually stand for the CPU ID. In the past this driver was only tested for desktop and laptop productions so 4-bits are enough. But now we have servers that can have as many as 256 cores, so we need 8-bits CPU ID.

On the other hand, the val field is usually stand for CPU frequency so 12-bits are enough to represent 4GHz, and for higher frequencies there is an extra bit to extend (enough for 8GHz).

In theory, this is a incompatible change, but fortunately the old SMC firmwares are not widely shipped and can be updated on the air, thus we can safely adjust the widths.

Fixes ccf51454145b ("cpufreq: Add Loongson-3 CPUFreq driver support")
---
 drivers/cpufreq/loongson3_cpufreq.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/cpufreq/loongson3_cpufreq.c +2 -2
index a923e196ec86e..ee7c1f2d3e519 100644
@@ -21,9 +21,9 @@
 union smc_message {
 	u32 value;
 	struct {
-		u32 id		: 4;
+		u32 id		: 8;
 		u32 info	: 4;
-		u32 val		: 16;
+		u32 val		: 12;
 		u32 cmd		: 6;
 		u32 extra	: 1;
 		u32 complete	: 1;
Signature · 1 line
2.53.0
author maintainer
#1336 lore raw

PATCH 1333/1536 cpufreq: loongson3: Replace per-package mutex with per-node

In reply to Greg Kroah-Hartman

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

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

From: Huacai Chen <[email protected]>

[ Upstream commit 5d7802ada30b3101f408706b7399b0e170d2febd ]

Our server productions (e.g. Loongson-3D6000/3E6000) can have multiple nodes in one package and SMC mailboxes are also per-node. So replace the per-package mutex with per-node one.

Fixes ccf51454145b ("cpufreq: Add Loongson-3 CPUFreq driver support")
---
 drivers/cpufreq/loongson3_cpufreq.c | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
drivers/cpufreq/loongson3_cpufreq.c +7 -7
index ee7c1f2d3e519..a2a798d921cb5 100644
@@ -169,7 +169,7 @@ struct loongson3_freq_data {
 	struct cpufreq_frequency_table table[];
 };
 
-static struct mutex cpufreq_mutex[MAX_PACKAGES];
+static struct mutex cpufreq_mutex[MAX_NUMNODES];
 static struct cpufreq_driver loongson3_cpufreq_driver;
 static DEFINE_PER_CPU(struct loongson3_freq_data *, freq_data);
 
@@ -177,14 +177,14 @@ static inline int do_service_request(u32 id, u32 info, u32 cmd, u32 val, u32 ext
 {
 	int retries;
 	unsigned int cpu = raw_smp_processor_id();
-	unsigned int package = cpu_data[cpu].package;
+	unsigned int nid = cpu_to_node(cpu);
 	union smc_message msg, last;
 
-	mutex_lock(&cpufreq_mutex[package]);
+	mutex_lock(&cpufreq_mutex[nid]);
 
 	last.value = iocsr_read32(LOONGARCH_IOCSR_SMCMBX);
 	if (!last.complete) {
-		mutex_unlock(&cpufreq_mutex[package]);
+		mutex_unlock(&cpufreq_mutex[nid]);
 		return -EPERM;
 	}
 
@@ -208,11 +208,11 @@ static inline int do_service_request(u32 id, u32 info, u32 cmd, u32 val, u32 ext
 	}
 
 	if (!msg.complete || msg.cmd != CMD_OK) {
-		mutex_unlock(&cpufreq_mutex[package]);
+		mutex_unlock(&cpufreq_mutex[nid]);
 		return -EPERM;
 	}
 
-	mutex_unlock(&cpufreq_mutex[package]);
+	mutex_unlock(&cpufreq_mutex[nid]);
 
 	return msg.val;
 }
@@ -346,7 +346,7 @@ static int loongson3_cpufreq_probe(struct platform_device *pdev)
 {
 	int i, ret;
 
-	for (i = 0; i < MAX_PACKAGES; i++) {
+	for (i = 0; i < MAX_NUMNODES; i++) {
 		ret = devm_mutex_init(&pdev->dev, &cpufreq_mutex[i]);
 		if (ret)
 			return ret;
Signature · 1 line
2.53.0
author maintainer
#1337 lore raw

PATCH 1334/1536 cpufreq: loongson3: Use global physical CPU ID in get/target callbacks

In reply to Greg Kroah-Hartman

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

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

From: Huacai Chen <[email protected]>

[ Upstream commit e38360d7c62c8fa530b58905f99a4557d4d6b352 ]

Our server productions (e.g. Loongson-3D6000/3E6000) can have discrete global physical CPU IDs while the core ID inside the packages are always continuous. In these cases we should use global physical CPU IDs to get and set frequencies.

Fixes ccf51454145b ("cpufreq: Add Loongson-3 CPUFreq driver support")
---
 drivers/cpufreq/loongson3_cpufreq.c | 23 +++++++++++++----------
 1 file changed, 13 insertions(+), 10 deletions(-)
drivers/cpufreq/loongson3_cpufreq.c +13 -10
index a2a798d921cb5..ef93d02f65804 100644
@@ -16,6 +16,7 @@
 #include <asm/idle.h>
 #include <asm/loongarch.h>
 #include <asm/loongson.h>
+#include <asm/smp.h>
 
 /* Message */
 union smc_message {
@@ -219,38 +220,40 @@ static inline int do_service_request(u32 id, u32 info, u32 cmd, u32 val, u32 ext
 
 static unsigned int loongson3_cpufreq_get(unsigned int cpu)
 {
-	int ret;
+	int ret, core = cpu_logical_map(cpu);
 
-	ret = do_service_request(cpu, FREQ_INFO_TYPE_FREQ, CMD_GET_FREQ_INFO, 0, 0);
+	ret = do_service_request(core, FREQ_INFO_TYPE_FREQ, CMD_GET_FREQ_INFO, 0, 0);
 
-	return ret * KILO;
+	return (ret < 0) ? 0 : ret * KILO;
 }
 
 static int loongson3_cpufreq_target(struct cpufreq_policy *policy, unsigned int index)
 {
-	int ret;
+	int ret, core = cpu_logical_map(policy->cpu);
 
-	ret = do_service_request(cpu_data[policy->cpu].core,
-				 FREQ_INFO_TYPE_LEVEL, CMD_SET_FREQ_INFO, index, 0);
+	ret = do_service_request(core, FREQ_INFO_TYPE_LEVEL, CMD_SET_FREQ_INFO,
+				 index, 0);
 
 	return (ret >= 0) ? 0 : ret;
 }
 
 static int configure_freq_table(int cpu)
 {
-	int i, ret, boost_level, max_level, freq_level;
+	int i, ret, core, boost_level, max_level, freq_level;
 	struct platform_device *pdev = cpufreq_get_driver_data();
 	struct loongson3_freq_data *data;
 
 	if (per_cpu(freq_data, cpu))
 		return 0;
 
-	ret = do_service_request(cpu, 0, CMD_GET_FREQ_LEVEL_NUM, 0, 0);
+	core = cpu_logical_map(cpu);
+
+	ret = do_service_request(core, 0, CMD_GET_FREQ_LEVEL_NUM, 0, 0);
 	if (ret < 0)
 		return ret;
 	max_level = ret;
 
-	ret = do_service_request(cpu, 0, CMD_GET_FREQ_BOOST_LEVEL, 0, 0);
+	ret = do_service_request(core, 0, CMD_GET_FREQ_BOOST_LEVEL, 0, 0);
 	if (ret < 0)
 		return ret;
 	boost_level = ret;
@@ -263,7 +266,7 @@ static int configure_freq_table(int cpu)
 	data->def_freq_level = boost_level - 1;
 
 	for (i = 0; i < freq_level; i++) {
-		ret = do_service_request(cpu, FREQ_INFO_TYPE_FREQ, CMD_GET_FREQ_LEVEL_INFO, i, 0);
+		ret = do_service_request(core, FREQ_INFO_TYPE_FREQ, CMD_GET_FREQ_LEVEL_INFO, i, 0);
 		if (ret < 0) {
 			devm_kfree(&pdev->dev, data);
 			return ret;
Signature · 1 line
2.53.0
author maintainer
#1338 lore raw

PATCH 1335/1536 cpufreq: loongson3: Replace IOCSR read/write with MMIO ones

In reply to Greg Kroah-Hartman

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

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

From: Huacai Chen <[email protected]>

[ Upstream commit 81792daacfb41ca07b04bd3956ea9e672080cc98 ]

Our server productions (e.g. Loongson-3D6000/3E6000) can have multiple nodes in one package and SMC mailboxes are also per-node. However, IOCSR read/write can only perform on the current node, while sometimes we want to perform on other nodes (e.g. when switch governor, the get and target callbacks are not run on target core). So replace IOCSR read/write with MMIO ones.

Fixes ccf51454145b ("cpufreq: Add Loongson-3 CPUFreq driver support")
---
 drivers/cpufreq/loongson3_cpufreq.c | 34 +++++++++++++++++++++++------
 1 file changed, 27 insertions(+), 7 deletions(-)
drivers/cpufreq/loongson3_cpufreq.c +27 -7
index ef93d02f65804..85da1bf915e15 100644
@@ -17,6 +17,7 @@
 #include <asm/loongarch.h>
 #include <asm/loongson.h>
 #include <asm/smp.h>
+#include <asm/numa.h>
 
 /* Message */
 union smc_message {
@@ -165,6 +166,12 @@ union smc_message {
 
 #define FREQ_MAX_LEVEL			16
 
+#define MMIO_SMCMBX(node) \
+	((void __iomem *)(nid_to_addrbase(node) | IO_BASE | LOONGSON_REG_BASE | LOONGARCH_IOCSR_SMCMBX))
+
+#define MMIO_MISC_FUNC(node) \
+	((void __iomem *)(nid_to_addrbase(node) | IO_BASE | LOONGSON_REG_BASE | LOONGARCH_IOCSR_MISC_FUNC))
+
 struct loongson3_freq_data {
 	unsigned int def_freq_level;
 	struct cpufreq_frequency_table table[];
@@ -177,13 +184,27 @@ static DEFINE_PER_CPU(struct loongson3_freq_data *, freq_data);
 static inline int do_service_request(u32 id, u32 info, u32 cmd, u32 val, u32 extra)
 {
 	int retries;
-	unsigned int cpu = raw_smp_processor_id();
-	unsigned int nid = cpu_to_node(cpu);
+	unsigned int cpu = 0, nid;
 	union smc_message msg, last;
 
+#ifdef CONFIG_SMP
+	switch (cmd) {
+	case CMD_GET_FREQ_INFO:
+	case CMD_SET_FREQ_INFO:
+	case CMD_GET_FREQ_LEVEL_NUM:
+	case CMD_GET_FREQ_LEVEL_INFO:
+	case CMD_GET_FREQ_BOOST_LEVEL:
+		cpu = cpu_number_map(id);
+		break;
+	default:
+		cpu = raw_smp_processor_id();
+	}
+#endif
+	nid = cpu_to_node(cpu);
+
 	mutex_lock(&cpufreq_mutex[nid]);
 
-	last.value = iocsr_read32(LOONGARCH_IOCSR_SMCMBX);
+	last.value = readl(MMIO_SMCMBX(nid));
 	if (!last.complete) {
 		mutex_unlock(&cpufreq_mutex[nid]);
 		return -EPERM;
@@ -196,12 +217,11 @@ static inline int do_service_request(u32 id, u32 info, u32 cmd, u32 val, u32 ext
 	msg.extra	= extra;
 	msg.complete	= 0;
 
-	iocsr_write32(msg.value, LOONGARCH_IOCSR_SMCMBX);
-	iocsr_write32(iocsr_read32(LOONGARCH_IOCSR_MISC_FUNC) | IOCSR_MISC_FUNC_SOFT_INT,
-		      LOONGARCH_IOCSR_MISC_FUNC);
+	writel(msg.value, MMIO_SMCMBX(nid));
+	writel(readl(MMIO_MISC_FUNC(nid)) | IOCSR_MISC_FUNC_SOFT_INT, MMIO_MISC_FUNC(nid));
 
 	for (retries = 0; retries < 10000; retries++) {
-		msg.value = iocsr_read32(LOONGARCH_IOCSR_SMCMBX);
+		msg.value = readl(MMIO_SMCMBX(nid));
 		if (msg.complete)
 			break;
 
Signature · 1 line
2.53.0
author maintainer
#1339 lore raw

PATCH 1336/1536 virtio_fs: read the vring size under virtio_fs_mutex in ->get_tree

In reply to Greg Kroah-Hartman

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

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

From: Fan Wu <[email protected]>

[ Upstream commit e7ccc777a040343b80f95f4cc5c12ce1df3187f4 ]

The vring size was read after virtio_fs_find_instance() had dropped virtio_fs_mutex, so a concurrent virtio_fs_remove() could free the virtqueue first. The reference from the lookup keeps the virtio_fs alive, but not its virtqueues.

Hold the mutex across the lookup and the read.

This issue was found by an in-house static analysis tool.

Fixes a7f0d7aab0b4 ("virtiofs: split requests that exceed virtqueue size")
Assisted-by Codex:gpt-5.6
---
 fs/fuse/virtio_fs.c | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)
fs/fuse/virtio_fs.c +11 -10
index c98e48d7220a1..06e59b820ffa8 100644
@@ -453,26 +453,23 @@ static int virtio_fs_add_instance(struct virtio_device *vdev,
 	return ret;
 }
 
-/* Return the virtio_fs with a given tag, or NULL */
+/* Return the virtio_fs with a given tag, or NULL.
+ * Callers hold virtio_fs_mutex, which also keeps the virtqueues alive.
+ */
 static struct virtio_fs *virtio_fs_find_instance(const char *tag)
 {
 	struct virtio_fs *fs;
 
-	mutex_lock(&virtio_fs_mutex);
+	lockdep_assert_held(&virtio_fs_mutex);
 
 	list_for_each_entry(fs, &virtio_fs_instances, list) {
 		if (strcmp(fs->tag, tag) == 0) {
 			kobject_get(&fs->kobj);
-			goto found;
+			return fs;
 		}
 	}
 
-	fs = NULL; /* not found */
-
-found:
-	mutex_unlock(&virtio_fs_mutex);
-
-	return fs;
+	return NULL; /* not found */
 }
 
 static void virtio_fs_free_devs(struct virtio_fs *fs)
@@ -1672,13 +1669,17 @@ static int virtio_fs_get_tree(struct fs_context *fsc)
 	 * in fc->iq->priv. Once fuse_conn is going away, it calls ->put()
 	 * to drop the reference to this object.
 	 */
+	mutex_lock(&virtio_fs_mutex);
 	fs = virtio_fs_find_instance(fsc->source);
+	if (fs)
+		virtqueue_size = virtqueue_get_vring_size(fs->vqs[VQ_REQUEST].vq);
+	mutex_unlock(&virtio_fs_mutex);
+
 	if (!fs) {
 		pr_info("virtio-fs: tag <%s> not found\n", fsc->source);
 		return -EINVAL;
 	}
 
-	virtqueue_size = virtqueue_get_vring_size(fs->vqs[VQ_REQUEST].vq);
 	if (WARN_ON(virtqueue_size <= FUSE_HEADER_OVERHEAD))
 		goto out_err;
 
Signature · 1 line
2.53.0
author maintainer
#1340 lore raw

PATCH 1337/1536 ipc, msg: Account msg_msg allocations with GFP_KERNEL_ACCOUNT again

In reply to Greg Kroah-Hartman

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

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

From: Kees Cook <[email protected]>

[ Upstream commit c57fbbe42e907fa26c5ffada52d913d4ca5fa66e ]

Since commit 734bbc1c97ea7 ("ipc, msg: Use dedicated slab buckets for alloc_msg()"), alloc_msg() allocates with GFP_KERNEL, and a msg_msg is accounted only through SLAB_ACCOUNT on its bucket caches. With CONFIG_SLAB_BUCKETS=n, kmem_buckets_create() creates no caches and kmem_buckets_alloc() is a GFP_KERNEL kmalloc() from the general caches, which do not account it; the same happens when kmem_buckets_create() fails. Either way, the allocation is not charged to the sender's memory cgroup.

Allocate with GFP_KERNEL_ACCOUNT again, as before that commit, so the allocation is charged whichever cache serves it.

Build tested ARCH=x86_64 defconfig with GCC 16.2.0, with CONFIG_SLAB_BUCKETS as y and n.

---
 ipc/msgutil.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
ipc/msgutil.c +2 -1
index c7be0c7926476..7d5fb92e6f2e3 100644
@@ -61,7 +61,8 @@ static struct msg_msg *alloc_msg(size_t len)
 	size_t alen;
 
 	alen = min(len, DATALEN_MSG);
-	msg = kmem_buckets_alloc(msg_buckets, sizeof(*msg) + alen, GFP_KERNEL);
+	msg = kmem_buckets_alloc(msg_buckets, sizeof(*msg) + alen,
+				 GFP_KERNEL_ACCOUNT);
 	if (msg == NULL)
 		return NULL;
 
Signature · 1 line
2.53.0
author maintainer
#1341 lore raw

PATCH 1338/1536 mptcp: reset msk state on early connect failure

In reply to Greg Kroah-Hartman

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

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

From: Quanye Yang <[email protected]>

[ Upstream commit 29afe67082b2d33ab2e90c56c337235d725f023f ]

mptcp_connect() can fall back before the subflow SYN is sent, for example when the netns is in an MPTCP blackhole, token allocation fails, or MD5SIG is in use. If the subsequent subflow connect() fails immediately (EAFNOSUPPORT, ENETUNREACH, ...), __inet_stream_connect() returns while the socket is still SS_UNCONNECTED and never calls ->disconnect(). This was reported by Clashiko [1].

The error path only dropped the token and moved the msk back to TCP_CLOSE. MPTCP_FALLBACK_DONE, allow_subflows and request_mptcp were left as after early fallback, so a later connect() on the same fd stayed TCP-only.

---
 net/mptcp/protocol.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
net/mptcp/protocol.c +8 -1
index 00997357d4bcb..ed41368392c95 100644
@@ -4012,9 +4012,16 @@ static int mptcp_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
 	 * subflow_finish_connect()
 	 */
 	if (unlikely(err)) {
-		/* avoid leaving a dangling token in an unconnected socket */
 		mptcp_token_destroy(msk);
 		mptcp_set_state(sk, TCP_CLOSE);
+
+		spin_lock_bh(&msk->fallback_lock);
+		msk->allow_subflows = true;
+		msk->allow_infinite_fallback = true;
+		clear_bit(MPTCP_FALLBACK_DONE, &msk->flags);
+		spin_unlock_bh(&msk->fallback_lock);
+
+		mptcp_subflow_ctx_reset(mptcp_subflow_ctx(ssk));
 		return err;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#1342 lore raw

PATCH 1339/1536 ALSA: seq: oss: Skip events until fully initialized

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 68d4a6ea6cc6091a05836f783bc17d525d266d0b ]

When an OSS sequencer device is opened, it creates a sequencer port, then further initializes the internal states like a timer instance, etc. Since the sequencer port is published, an event can be already delivered, and this may hit unexpected event handling, which can eventually cause a NULL dereference (like the timer start/stop event triggered before the timer initialization).

For avoiding such a race, introduce a simple guard and skips the event processing until the port is fully initialized.
At releasing the device, in turn, clear this guard, so that any input events will be discarded during the teardown.

---
 sound/core/seq/oss/seq_oss_device.h | 1 +
 sound/core/seq/oss/seq_oss_event.c  | 3 +++
 sound/core/seq/oss/seq_oss_init.c   | 2 ++
 3 files changed, 6 insertions(+)
sound/core/seq/oss/seq_oss_device.h +1 -0
index 98dd20b429764..eb1619c96526f 100644
@@ -73,6 +73,7 @@ struct seq_oss_devinfo {
 	int cseq;	/* sequencer client number */
 	int port;	/* sequencer port number */
 	int queue;	/* sequencer queue number */
+	bool initialized;
 
 	struct snd_seq_addr addr;	/* address of this device */
 
sound/core/seq/oss/seq_oss_event.c +3 -0
index 4699c084d018e..fa91eb1233de3 100644
@@ -427,6 +427,9 @@ snd_seq_oss_event_input(struct snd_seq_event *ev, int direct, void *private_data
 	struct seq_oss_devinfo *dp = (struct seq_oss_devinfo *)private_data;
 	union evrec *rec;
 
+	if (!dp || !smp_load_acquire(&dp->initialized))
+		return 0; /* ignored */
+
 	if (ev->type != SNDRV_SEQ_EVENT_ECHO)
 		return snd_seq_oss_midi_input(ev, direct, private_data);
 
sound/core/seq/oss/seq_oss_init.c +2 -0
index 676246fa02f15..7fb9fce9172e8 100644
@@ -258,6 +258,7 @@ snd_seq_oss_open(struct file *file, int level)
 
 	client_table[dp->index] = dp;
 	num_clients++;
+	smp_store_release(&dp->initialized, true);
 
 	return 0;
 
@@ -403,6 +404,7 @@ snd_seq_oss_release(struct seq_oss_devinfo *dp)
 
 	client_table[dp->index] = NULL;
 	num_clients--;
+	smp_store_release(&dp->initialized, false);
 
 	snd_seq_oss_reset(dp);
 
Signature · 1 line
2.53.0
author maintainer
#1343 lore raw

PATCH 1340/1536 ALSA: hda/realtek: Fix internal speakers on Acer Aspire AL16-31P

In reply to Greg Kroah-Hartman

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

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

From: Luis Gerardo Lopez Hernandez <[email protected]>

[ Upstream commit d933955c456e0573b40eae4f72a3af37ab1c15c3 ]

The Acer Aspire AL16-31P (Intel Alder Lake-N, Realtek ALC269VC, PCI/codec SSID 2782:1718) has its internal speakers wired to pin 0x1b, but the BIOS marks that pin as not connected (0x411111f0) and only exposes pin 0x14 as the speaker. As a result the internal speakers are silent while headphones, HDMI and Bluetooth work.

This is the same layout as the Infinix Y4 Max and MEDION E15433, which share the 0x2782 subsystem vendor. Reuse their fixup, which configures pin 0x1b as an internal speaker and limits the internal mic boost.

Tested by booting with snd-hda-intel model=2782:1705: the fixup is picked, pin 0x1b is used as a speaker output, the internal speakers work, and they are muted when headphones are plugged in.

---
 sound/pci/hda/patch_realtek.c | 1 +
 1 file changed, 1 insertion(+)
sound/pci/hda/patch_realtek.c +1 -0
index fb79b82e2ea6e..899394885ae81 100644
@@ -11771,6 +11771,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x2782, 0x1701, "Infinix Y4 Max", ALC269VC_FIXUP_INFINIX_Y4_MAX),
 	SND_PCI_QUIRK(0x2782, 0x1705, "MEDION E15433", ALC269VC_FIXUP_INFINIX_Y4_MAX),
 	SND_PCI_QUIRK(0x2782, 0x1707, "Vaio VJFE-ADL", ALC298_FIXUP_SPK_VOLUME),
+	SND_PCI_QUIRK(0x2782, 0x1718, "Acer Aspire AL16-31P", ALC269VC_FIXUP_INFINIX_Y4_MAX),
 	SND_PCI_QUIRK(0x2782, 0x4900, "MEDION E15443", ALC233_FIXUP_MEDION_MTL_SPK),
 	SND_PCI_QUIRK(0x7017, 0x2014, "Star Labs StarFighter", ALC233_FIXUP_STARLABS_STARFIGHTER),
 	SND_PCI_QUIRK(0x8086, 0x2073, "Intel NUC 8 Hades Canyon",
Signature · 1 line
2.53.0
author maintainer
#1344 lore raw

PATCH 1341/1536 power: supply: generic-adc-battery: fix status with no supplier

In reply to Greg Kroah-Hartman

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

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

From: Tim Douglas <[email protected]>

[ Upstream commit 8ae5a3f40045ff486826ed6b6a83e39a0f380073 ]

power_supply_am_i_supplied() returns -ENODEV when no registered power supply supplies the battery. generic-adc-battery's gab_work() tests this return value as a boolean, so -ENODEV takes the supplied branch and reports CHARGING, or NOT_CHARGING if the charge-finished GPIO is asserted, instead of DISCHARGING.

This was noticed while bringing up an out-of-tree Linux port to the
WikiReader: the driver reported CHARGING on a device powered by two AAA batteries with no charging hardware.

Only a positive return value indicates an online supplier, so treat zero and negative returns as discharging.

Fixes 46cecd130d55 ("power: supply: Fix power_supply_am_i_supplied to return -ENODEV when apropriate")
---
 drivers/power/supply/generic-adc-battery.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/power/supply/generic-adc-battery.c +1 -1
index aebc824aa2ede..43b735d4d49c3 100644
@@ -135,7 +135,7 @@ static void gab_work(struct work_struct *work)
 	adc_bat = container_of(delayed_work, struct gab, bat_work);
 	status = adc_bat->status;
 
-	if (!power_supply_am_i_supplied(adc_bat->psy))
+	if (power_supply_am_i_supplied(adc_bat->psy) <= 0)
 		adc_bat->status =  POWER_SUPPLY_STATUS_DISCHARGING;
 	else if (gab_charge_finished(adc_bat))
 		adc_bat->status = POWER_SUPPLY_STATUS_NOT_CHARGING;
Signature · 1 line
2.53.0
author maintainer
#1345 lore raw

PATCH 1342/1536 alpha: handle VM_FAULT_HWPOISON in do_page_fault()

In reply to Greg Kroah-Hartman

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

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

From: Matt Turner <[email protected]>

[ Upstream commit 4bef20bbb9e02568a009efa4d404ce2621289be5 ]

do_page_fault() handles VM_FAULT_OOM, VM_FAULT_SIGSEGV and VM_FAULT_SIGBUS and then falls into BUG() for anything else in VM_FAULT_ERROR. VM_FAULT_HWPOISON and VM_FAULT_HWPOISON_LARGE are in that set, so a fault on a poisoned page takes down the kernel instead of delivering a signal.

Alpha does not select ARCH_SUPPORTS_MEMORY_FAILURE, so the machine check paths cannot produce these. UFFDIO_POISON can: it installs a poison PTE marker without any memory failure support, and a subsequent access returns VM_FAULT_HWPOISON. Registering an anonymous range with userfaultfd, poisoning it and reading it back reliably hits the BUG():

Kernel bug at arch/alpha/mm/fault.c:188
poison(50809): Kernel Bug 1
pc is at do_page_fault+0x4e8/0x550
ra is at do_page_fault+0xfc/0x550

The BUG() fires with mmap_read_lock() still held, so the faulting task is left unkillable in D state holding the lock, and shutdown stalls behind it. A UFFD_USER_MODE_ONLY userfaultfd is always allowed, so any local user can do this.

Deliver SIGBUS with BUS_MCEERR_AR instead, reporting the size of the poisoned area, as the other architectures do. That is the huge page size for VM_FAULT_HWPOISON_LARGE, which becomes reachable once alpha implements huge pages.

Tested on an UP1500 (EV68AL): the reproducer above now takes a SIGBUS and the kernel logs

poison[373]: hardware memory error at 0000020000030000 pc 00000200010007ec

with no oops, no wedged task and no taint.

A backport needs the show_signal_msg() call dropped, since alpha only has it since commit 9ca6af1aac40 ("alpha: select SYSCTL_EXCEPTION_TRACE").

---
 arch/alpha/mm/fault.c | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
arch/alpha/mm/fault.c +19 -0
index a9816bbc9f34d..f40ac0826a854 100644
@@ -8,6 +8,7 @@
 #include <linux/sched/signal.h>
 #include <linux/kernel.h>
 #include <linux/mm.h>
+#include <linux/hugetlb.h>
 #include <asm/io.h>
 
 #define __EXTERN_INLINE inline
@@ -89,6 +90,7 @@ do_page_fault(unsigned long address, unsigned long mmcsr,
 	struct mm_struct *mm = current->mm;
 	const struct exception_table_entry *fixup;
 	int si_code = SEGV_MAPERR;
+	unsigned int lsb;
 	vm_fault_t fault;
 	unsigned int flags = FAULT_FLAG_DEFAULT;
 
@@ -161,6 +163,8 @@ do_page_fault(unsigned long address, unsigned long mmcsr,
 			goto bad_area;
 		else if (fault & VM_FAULT_SIGBUS)
 			goto do_sigbus;
+		else if (fault & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))
+			goto do_sigbus_mceerr;
 		BUG();
 	}
 
@@ -222,6 +226,21 @@ do_page_fault(unsigned long address, unsigned long mmcsr,
 		goto no_context;
 	return;
 
+ do_sigbus_mceerr:
+	mmap_read_unlock(mm);
+	if (!user_mode(regs))
+		goto no_context;
+	/*
+	 * Report the size of the poisoned area, which for a hugetlb fault
+	 * is the size of the huge page that could not be mapped.
+	 */
+	lsb = PAGE_SHIFT;
+	if (fault & VM_FAULT_HWPOISON_LARGE)
+		lsb = hstate_index_to_shift(VM_FAULT_GET_HINDEX(fault));
+	show_signal_msg(regs, address, SIGBUS, "hardware memory error");
+	force_sig_mceerr(BUS_MCEERR_AR, (void __user *) address, lsb);
+	return;
+
  do_sigsegv:
 	force_sig_fault(SIGSEGV, si_code, (void __user *) address);
 	return;
Signature · 1 line
2.53.0
author maintainer
#1346 lore raw

PATCH 1343/1536 alpha: load the MMU context when switch_mm() switches the current task

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit 9b8be19d5dc9525a408942e2e8012873199e7455 ]

ev5_switch_mm() only prepares the incoming PCB. The context is installed by PAL_swpctx, which alpha_switch_to() issues against that PCB on the way out of the scheduler.

Direct callers reach switch_mm() without going through alpha_switch_to():
kthread_use_mm(), which borrows an mm for the current kernel thread, sched_force_init_mm() on the CPU-hotplug teardown path, and do_shoot_lazy_tlb(), which switches to init_mm from an IPI. None explicitly loads the context, so the task can carry on running under whatever was loaded before. For kthread_use_mm(), current->mm then names the borrowed mm even though its context has not been loaded. The other two callers change active_mm while leaving current->mm NULL.

The stale page-table root need not be swapper_pg_dir; it may belong to a user process that ran on the CPU earlier, and the kthread's user accesses can then read and write that process's memory wherever the stale mappings allow. Translations taken that way can also end up tagged with the borrowed mm's ASN: ev5_switch_mm() writes that ASN into the PCB, which the next PAL_swpctx installs against the stale ptbr. An address the stale tables do not map faults instead, and since do_page_fault() resolves faults against current->mm without reloading the context, the same access can fault again on return.

sched_force_init_mm() needs CONFIG_HOTPLUG_CPU and do_shoot_lazy_tlb() needs CONFIG_MMU_LAZY_TLB_SHOOTDOWN. Alpha selects neither, so only kthread_use_mm() is reachable in practice. Test the caller's identity rather than special-casing individual callers.

The scheduler passes the incoming task, which is not current until alpha_switch_to() runs; all three direct callers pass current. Test for that and load the context the way activate_mm() does. All three run with interrupts disabled across the switch, so this completes before any shootdown can be taken and needs no asn_lock handshake.

---
 arch/alpha/include/asm/mmu_context.h | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
arch/alpha/include/asm/mmu_context.h +12 -1
index eee8fe836a59e..d366f89fee585 100644
@@ -130,6 +130,8 @@ __get_new_mm_context(struct mm_struct *mm, long cpu)
 	return next;
 }
 
+extern void __load_new_mm_context(struct mm_struct *);
+
 __EXTERN_INLINE void
 ev5_switch_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm,
 	      struct task_struct *next)
@@ -139,6 +141,16 @@ ev5_switch_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm,
 	unsigned long mmc;
 	long cpu = smp_processor_id();
 
+	/*
+	 * kthread_use_mm(), sched_force_init_mm() and do_shoot_lazy_tlb()
+	 * switch current's mm without alpha_switch_to(), which loads the
+	 * context. The latter two require options Alpha does not select.
+	 */
+	if (next == current) {
+		__load_new_mm_context(next_mm);
+		return;
+	}
+
 #ifdef CONFIG_SMP
 	cpu_data[cpu].asn_lock = 1;
 	barrier();
@@ -160,7 +172,6 @@ ev5_switch_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm,
 	task_thread_info(next)->pcb.asn = mmc & HARDWARE_ASN_MASK;
 }
 
-extern void __load_new_mm_context(struct mm_struct *);
 asmlinkage void do_page_fault(unsigned long address, unsigned long mmcsr,
 			      long cause, struct pt_regs *regs);
 
Signature · 1 line
2.53.0
author maintainer
#1347 lore raw

PATCH 1344/1536 alpha: run check_mmu_context() from finish_arch_post_lock_switch()

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit 020d2e70b7538b66eee3c3480d2b8921fb182f0c ]

check_mmu_context() clears asn_lock and acts on need_new_asn, but it runs only as the tail of switch_to(), after alpha_switch_to() returns.

A newly forked user task never gets there: its first context switch resumes at ret_from_fork and reaches schedule_tail() without returning to the code following alpha_switch_to().

asn_lock is left set on that CPU, so the new user task can run with interrupts enabled while shootdown IPIs keep taking the deferred path. The handshake meant to complete those invalidations never runs.

New kernel threads also reach schedule_tail(), but context_switch() does not call switch_mm() for a task without an mm. They therefore do not set asn_lock in the first place and are not affected by this bug.

Move check_mmu_context() to finish_arch_post_lock_switch(), which is called by finish_task_switch() for both existing and newly created tasks. Drop the now redundant call from switch_to().

The hook runs after finish_lock_switch() releases the rq lock and enables interrupts. An IPI arriving before asn_lock is cleared retires the slot through flush_tlb_other(); an IPI arriving afterwards can flush directly, since PAL_swpctx has already installed the incoming context.

Set need_new_asn whether ev5_switch_mm() reuses or allocates an ASN. An IPI in that interval can zero either slot. Without this, the allocated case can return to user space with a live ASN but a zero context slot, which a later context-based shootdown shortcut could mistake for an inactive CPU. check_mmu_context() reloads only when the slot is zero.

Call the hook unconditionally. Alpha selects ARCH_NO_PREEMPT, and neither kthread_use_mm() nor sched_force_init_mm() sleeps between the direct switch and this hook. RCU_STRICT_GRACE_PERIOD can enable PREEMPT_COUNT, but cannot make those callers migrate there. Testing preemptible() would only leave asn_lock set in that configuration.

This requires the preceding direct-switch fix, "alpha: load the MMU context when switch_mm() switches the current task". It installs the borrowed context before kthread_use_mm() reaches this hook, so clearing asn_lock cannot expose a targeted invalidate against the wrong context.

---
 arch/alpha/include/asm/mmu_context.h | 15 +++++++++++++--
 arch/alpha/include/asm/switch_to.h   |  1 -
 2 files changed, 13 insertions(+), 3 deletions(-)
arch/alpha/include/asm/mmu_context.h +13 -2
index d366f89fee585..f41d7c73fdd64 100644
@@ -162,8 +162,8 @@ ev5_switch_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm,
 		next_mm->context[cpu] = mmc;
 	}
 #ifdef CONFIG_SMP
-	else
-		cpu_data[cpu].need_new_asn = 1;
+	/* A deferred shootdown can also invalidate a newly allocated ASN. */
+	cpu_data[cpu].need_new_asn = 1;
 #endif
 
 	/* Always update the PCB ASN.  Another thread may have allocated
@@ -192,6 +192,17 @@ do {								\
 #define check_mmu_context()  do { } while(0)
 #endif
 
+/*
+ * Also called from kthread_use_mm() with preemption enabled. Alpha has
+ * no kernel preemption, so the task is still on the CPU that ran
+ * switch_mm().
+ */
+#define finish_arch_post_lock_switch finish_arch_post_lock_switch
+static inline void finish_arch_post_lock_switch(void)
+{
+	check_mmu_context();
+}
+
 __EXTERN_INLINE void
 ev5_activate_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm)
 {
arch/alpha/include/asm/switch_to.h +0 -1
index 762b7f975310c..35c4b2c9d9923 100644
@@ -9,7 +9,6 @@ extern struct task_struct *alpha_switch_to(unsigned long, struct task_struct *);
 #define switch_to(P,N,L)						 \
   do {									 \
     (L) = alpha_switch_to(virt_to_phys(&task_thread_info(N)->pcb), (P)); \
-    check_mmu_context();						 \
   } while (0)
 
 #endif /* __ALPHA_SWITCH_TO_H */
Signature · 1 line
2.53.0
author maintainer
#1348 lore raw

PATCH 1345/1536 alpha: only use a targeted tbi() when the target mm is really current

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit 0d92845ac5dbc79e4ac4810b33c673f4c1c227e3 ]

ipi_flush_tlb_page() gates a targeted tbi() on current->active_mm. tbi() acts on the address space context currently loaded on the CPU, so it is only guaranteed to reach an mm's translations when a thread of that mm is running there. current->active_mm is not sufficient: under lazy TLB an idle or kernel task keeps an mm as its active_mm while a different ASN is loaded, so the invalidate is issued against the wrong context and the stale entry can survive. Nothing retires the old ASN afterwards either, mm->context[cpu] still being valid, so the resuming thread can reuse it.

Test current->mm instead and otherwise fall back to flush_tlb_other(), which clears mm->context[cpu] and forces a fresh ASN at the next switch whatever is loaded now.

For an mm borrowed through kthread_use_mm(), patch 1 of this series installs the context before the task can take a shootdown IPI. The current->mm test therefore covers that case as well.

---
 arch/alpha/kernel/smp.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/alpha/kernel/smp.c +2 -1
index ed06367ece574..1ad448105201f 100644
@@ -669,7 +669,8 @@ ipi_flush_tlb_page(void *x)
 	struct flush_tlb_page_struct *data = x;
 	struct mm_struct * mm = data->mm;
 
-	if (mm == current->active_mm && !asn_locked())
+	/* A targeted tbi() needs a thread of MM to be current.  */
+	if (mm == current->mm && !asn_locked())
 		flush_tlb_current_page(mm, data->vma, data->addr);
 	else
 		flush_tlb_other(mm);
Signature · 1 line
2.53.0
author maintainer
#1349 lore raw

PATCH 1346/1536 alpha: invalidate the local context in flush_tlb_page()

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit c0db730bf05eb3c10c1fae64b19f6913dce129fc ]

When the target mm is not the calling CPU's active_mm, flush_tlb_page() does nothing locally, and smp_call_function() reaches only the other CPUs. This CPU may still hold translations for the mm and can later reuse the old ASN together with them.

Add the missing else branch. flush_tlb_other() clears mm->context[cpu] so a fresh ASN is taken at the next switch. Add this before changing the current->active_mm test to current->mm: that change will also send lazy callers here, so their local invalidate must already be in place.

The uniprocessor implementations of flush_tlb_mm() and flush_icache_user_page() in asm/tlbflush.h and asm/cacheflush.h already contain exactly this branch.

---
 arch/alpha/kernel/smp.c | 3 +++
 1 file changed, 3 insertions(+)
arch/alpha/kernel/smp.c +3 -0
index 1ad448105201f..e4ba0aab8a669 100644
@@ -697,6 +697,9 @@ flush_tlb_page(struct vm_area_struct *vma, unsigned long addr)
 			preempt_enable();
 			return;
 		}
+	} else {
+		/* smp_call_function() does not call back into this CPU.  */
+		flush_tlb_other(mm);
 	}
 
 	data.vma = vma;
Signature · 1 line
2.53.0
author maintainer
#1350 lore raw

PATCH 1347/1536 alpha: fix the local TLB invalidate in flush_tlb_page()

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit 32f4dd420d626f96128fcfeea2ab24760b4f21a6 ]

flush_tlb_page() invalidates the calling CPU itself before asking the others, and gates that on current->active_mm. For a non-executable vma that means a targeted tbi(2, addr), which acts on the context currently loaded and is only guaranteed to invalidate the intended translations when the target mm's context is the loaded one. A lazy active_mm does not establish that, so as in ipi_flush_tlb_page() the target mm's stale translations can survive, and nothing forces the old ASN to be retired afterwards.

Test current->mm instead. A lazy caller then takes the flush_tlb_other() branch added by the previous patch, retiring its local context. Adding that branch first preserves the local invalidate at every step, including on EV7 where a targeted tbi() against a foreign ASN appeared to work.

Which callers reach here with a foreign mm depends on the configuration. folio_mkclean(), from the writeback flusher kworker that has no mm of its own, accounted for about half the calls during writeback of a shared mapping and none at all on anonymous memory. Those counts were measured with CONFIG_COMPACTION=n: with COMPACTION=y, asm/pgtable.h overrides ptep_clear_flush() to call migrate_flush_tlb_page(), which rendezvouses with every CPU and handles the context itself, so folio_mkclean() does not reach this function.

---
 arch/alpha/kernel/smp.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/alpha/kernel/smp.c +2 -1
index e4ba0aab8a669..a5a42ae4a7d80 100644
@@ -684,7 +684,8 @@ flush_tlb_page(struct vm_area_struct *vma, unsigned long addr)
 
 	preempt_disable();
 
-	if (mm == current->active_mm) {
+	/* As in ipi_flush_tlb_page(): a targeted tbi() needs MM current.  */
+	if (mm == current->mm) {
 		flush_tlb_current_page(mm, vma, addr);
 		if (atomic_read(&mm->mm_users) <= 1) {
 			int cpu, this_cpu = smp_processor_id();
Signature · 1 line
2.53.0
author maintainer
#1351 lore raw

PATCH 1348/1536 alpha: fix the local TLB invalidate in the UP flush_tlb_page()

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit c825bf802a7a43fd302c879ef25c975e067a2e94 ]

The uniprocessor flush_tlb_page() in asm/tlbflush.h has the same wrong test as the SMP one: a targeted tbi() is only guaranteed to invalidate the intended translations when the target mm's context is loaded, but the gate is current->active_mm, which a lazily borrowed mm also satisfies.

Test current->mm instead. The else branch it falls to already exists here, so unlike the SMP side this is the whole fix. arch/alpha/kernel/smp.c is not built with CONFIG_SMP=n, so this is how the same defect reaches a uniprocessor, where the flusher kworker necessarily shares the only CPU with the writer.

---
 arch/alpha/include/asm/tlbflush.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/alpha/include/asm/tlbflush.h +2 -1
index 0c8529997f54e..9ae1902faf8ec 100644
@@ -87,7 +87,8 @@ flush_tlb_page(struct vm_area_struct *vma, unsigned long addr)
 {
 	struct mm_struct *mm = vma->vm_mm;
 
-	if (mm == current->active_mm)
+	/* A targeted tbi() needs a thread of MM to be current.  */
+	if (mm == current->mm)
 		flush_tlb_current_page(mm, vma, addr);
 	else
 		flush_tlb_other(mm);
Signature · 1 line
2.53.0
author maintainer
#1352 lore raw

PATCH 1349/1536 alpha: invalidate the local context in flush_tlb_mm()

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit 721bb7a129771f0ff9cef1dd5abfc106ef65feba ]

flush_tlb_mm() has the same caller-CPU omission that was fixed in flush_tlb_page(): when the target mm is not the calling CPU's active_mm nothing happens locally, and smp_call_function() handles only the other CPUs, so this CPU may later reuse the old ASN together with the translations it still holds.

The active_mm test itself is left alone here. That path calls flush_tlb_current(), which loads a fresh context through __load_new_mm_context() rather than issuing a targeted tbi() against whatever ASN happens to be loaded, so it does not depend on which context is current.

The uniprocessor implementation in asm/tlbflush.h already has the missing branch. Counted over a fork-heavy run, flush_tlb_mm() was entered with the mm not this CPU's active_mm 2934 times, and 632 times while otherwise idle.

The proposed Alpha hugetlb support routes hugetlb invalidations through flush_tlb_range(), which calls this function. Unmapping or migrating a hugetlb folio from another context will also need this local invalidate.

---
 arch/alpha/kernel/smp.c | 3 +++
 1 file changed, 3 insertions(+)
arch/alpha/kernel/smp.c +3 -0
index a5a42ae4a7d80..988e397b0b8a7 100644
@@ -649,6 +649,9 @@ flush_tlb_mm(struct mm_struct *mm)
 			preempt_enable();
 			return;
 		}
+	} else {
+		/* smp_call_function() does not call back into this CPU.  */
+		flush_tlb_other(mm);
 	}
 
 	smp_call_function(ipi_flush_tlb_mm, mm, 1);
Signature · 1 line
2.53.0
author maintainer
#1353 lore raw

PATCH 1350/1536 alpha: invalidate the local context in flush_icache_user_page()

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit 4244c555ac440a445cc168f860b2677099d761f9 ]

flush_icache_user_page() has the same caller-CPU omission that the previous patch fixed in flush_tlb_mm(): when the target mm is not the calling CPU's active_mm nothing happens locally, and smp_call_function() handles only the other CPUs, so this CPU may later reuse the old ASN together with the translations it still holds.

This matters here in particular because the function exists for operating on another process's mappings: the comment above it describes setting breakpoints through ptrace, and access_remote_vm() reaches it through copy_to_user_page(). The calling CPU is therefore often running something other than the target mm.

As in flush_tlb_mm(), the uniprocessor implementation in asm/cacheflush.h already has the missing case.

No imb() is needed, here or in ipi_flush_icache_page(). Alpha's user-space I-cache flush works by allocating a new ASN rather than by invalidating the I-cache: the entries stay, but they are tagged with the old ASN and can no longer match. An imb() is only required when the ASN space wraps and numbers are reused, and __get_new_mm_context() already does one in that case.

---
 arch/alpha/kernel/smp.c | 3 +++
 1 file changed, 3 insertions(+)
arch/alpha/kernel/smp.c +3 -0
index 988e397b0b8a7..e21bc3920bece 100644
@@ -758,6 +758,9 @@ flush_icache_user_page(struct vm_area_struct *vma, struct page *page,
 			preempt_enable();
 			return;
 		}
+	} else {
+		/* smp_call_function() does not call back into this CPU.  */
+		flush_tlb_other(mm);
 	}
 
 	smp_call_function(ipi_flush_icache_page, mm, 1);
Signature · 1 line
2.53.0
author maintainer
#1354 lore raw

PATCH 1351/1536 alpha: do not clear remote MMU contexts in migrate_flush_tlb_page()

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit 16266d50c51eb5eb98f1c345c5aa9ff359a305aa ]

After the on_each_cpu() rendezvous, migrate_flush_tlb_page() walks the other CPUs and zeroes their mm->context[cpu] when mm_users is at most one, described as mimicking flush_tlb_mm()'s mm_users<=1 optimization.

It is not one. flush_tlb_mm() tests mm_users before deciding whether to send the IPIs; here every CPU has already been visited and waited for, so nothing is saved. The callback has also just set each CPU's own slot correctly, so the loop only overwrites it, and does so while that CPU may still be running in the address space.

Remove it. The shootdown shortcuts in flush_tlb_mm(), flush_tlb_page() and flush_icache_user_page() clear remote slots too; once the next patch removes those as well, every runtime update of mm->context[cpu] is made by CPU cpu itself. That patch relies on the invariant when it reads those slots to decide whether a shootdown can be skipped, so this one is tagged for stable as its prerequisite.

Fixes dd5712f3379c ("alpha: fix user-space corruption during memory compaction")
---
 arch/alpha/mm/tlbflush.c | 16 ----------------
 1 file changed, 16 deletions(-)
arch/alpha/mm/tlbflush.c +0 -16
index ccbc317b9a348..239c72b8a7412 100644
@@ -90,22 +90,6 @@ void migrate_flush_tlb_page(struct vm_area_struct *vma, unsigned long addr)
 	 */
 	preempt_disable();
 	on_each_cpu(ipi_flush_mm_and_page, &d, 1);
-
-	/*
-	 * mimic flush_tlb_mm()'s mm_users<=1 optimization.
-	 */
-	if (atomic_read(&mm->mm_users) <= 1) {
-
-		int cpu, this_cpu;
-		this_cpu = smp_processor_id();
-
-		for (cpu = 0; cpu < NR_CPUS; cpu++) {
-			if (!cpu_online(cpu) || cpu == this_cpu)
-				continue;
-			if (READ_ONCE(mm->context[cpu]))
-				WRITE_ONCE(mm->context[cpu], 0);
-		}
-	}
 	preempt_enable();
 }
 
Signature · 1 line
2.53.0
author maintainer
#1355 lore raw

PATCH 1352/1536 alpha: do not skip TLB shootdown IPIs for kthread-borrowed mms

In reply to Greg Kroah-Hartman

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

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

From: Magnus Lindholm <[email protected]>

[ Upstream commit fe221b7b2d3ecd042dd391f74ff6a6fdeb7c2038 ]

flush_tlb_mm(), flush_tlb_page() and flush_icache_user_page() skip the shootdown IPI when mm_users <= 1, on the assumption that no other CPU can be running the mm. A task that borrows an mm through kthread_use_mm() takes mmgrab() rather than mmget(), so it never appears in mm_users, and kthread_use_mm() may be handed an mm that is already the caller's active_mm and loaded on that CPU. Such a CPU was not only left without an IPI, its mm->context[cpu] was cleared from under it.

mm->context[cpu] is already the record of which CPUs hold an ASN for the mm. Test it rather than clearing it: take the shortcut only when no other CPU has one, and otherwise fall through to the IPI, which invalidates those CPUs properly. A CPU that merely ran the mm in the past also holds a context and now costs an IPI, which errs in the safe direction.

Change ipi_flush_tlb_mm(), ipi_flush_icache_page() and the migration callback ipi_flush_mm_and_page() to test current->mm, like ipi_flush_tlb_page(). A CPU that only retains the mm lazily then clears its own slot through flush_tlb_other(), rather than publishing a new ASN on every IPI or migration rendezvous. The migration callback still does its per-VA tbi() afterwards. Returning to the mm allocates a fresh ASN through ev5_switch_mm(), or through the direct-load path when kthread_use_mm() switches current's mm.

Once these historical slots are gone, the shortcut is available again if mm_users remains at most one and no other CPU has taken or kept a context. An explicit kthread_use_mm() borrower has current->mm set and still receives the invalidate it needs.

The caller-side tests in flush_tlb_mm() and flush_icache_user_page() remain current->active_mm. A kernel thread that flushes its lazily held mm can therefore publish its own context slot. Those branches also perform the shortcut check, which excludes the calling CPU's slot, so leave them unchanged. This is distinct from a remote lazy CPU keeping its slot populated through repeated callbacks.

Together with the preceding patch, dropping these clearing loops leaves every runtime write to mm->context[] targeting the writing CPU's own slot, so the array becomes a lockless publication of which CPUs may be using the mm, with a single writer per slot. Mark the two stores that are now observed from other CPUs; flush_tlb_other() already uses WRITE_ONCE(). The uniprocessor flush_icache_user_page() is left alone, as nothing reads another CPU's slot there, and init_new_context() runs before the mm is shared.

Order the slot reads after the page-table changes with smp_mb(). On the publishing CPU, the store in ev5_switch_mm() precedes the mb() in Alpha's arch_spin_unlock(), when finish_lock_switch() drops the rq lock. This relies on Alpha's unlock implementation, not a generic scheduler promise of a full barrier on unlock; document that reliance at the store. Also issue smp_mb() after publishing in __load_new_mm_context(), before loading and using the mm.

This covers every caller, including check_mmu_context(), which can publish a replacement after finish_lock_switch() has already run.

This requires the preceding removal of remote slot clearing from migrate_flush_tlb_page(). It also requires the stale-TLB series to set need_new_asn on both the reused and newly allocated ASN paths. Otherwise an IPI between finish_lock_switch() and check_mmu_context() can zero a new slot while asn_lock is set, and the task can return to user space with a live ASN that the shortcut cannot see.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc <[email protected]> # 53ab52cfe5ce: alpha: load the MMU context when switch_mm() switches the current task
Cc <[email protected]> # 01df8f401888: alpha: run check_mmu_context() from finish_arch_post_lock_switch()
Cc <[email protected]> # ef43cfc28c42: alpha: only use a targeted tbi() when the target mm is really current
Cc <[email protected]> # 738cf8f7a78f: alpha: invalidate the local context in flush_tlb_page()
Cc <[email protected]> # 62c92086f30e: alpha: fix the local TLB invalidate in flush_tlb_page()
Cc <[email protected]> # 3faee097b939: alpha: fix the local TLB invalidate in the UP flush_tlb_page()
Cc <[email protected]> # b2c3b654bb64: alpha: invalidate the local context in flush_tlb_mm()
Cc <[email protected]> # f19ae6f51a38: alpha: invalidate the local context in flush_icache_user_page()
Cc <[email protected]> # 471e7f9c890b: alpha: do not clear remote MMU contexts in migrate_flush_tlb_page()
---
 arch/alpha/include/asm/mmu_context.h |  7 +++-
 arch/alpha/kernel/smp.c              | 52 ++++++++++++++--------------
 arch/alpha/mm/fault.c                |  4 ++-
 arch/alpha/mm/tlbflush.c             |  2 +-
 4 files changed, 36 insertions(+), 29 deletions(-)
arch/alpha/include/asm/mmu_context.h +6 -1
index f41d7c73fdd64..09f356934b90a 100644
@@ -159,7 +159,12 @@ ev5_switch_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm,
 	mmc = next_mm->context[cpu];
 	if ((mmc ^ asn) & ~HARDWARE_ASN_MASK) {
 		mmc = __get_new_mm_context(next_mm, cpu);
-		next_mm->context[cpu] = mmc;
+		/*
+		 * Ordered before any user access through the mm by the
+		 * mb() in arch_spin_unlock(), when finish_lock_switch()
+		 * drops the rq lock.
+		 */
+		WRITE_ONCE(next_mm->context[cpu], mmc);
 	}
 #ifdef CONFIG_SMP
 	/* A deferred shootdown can also invalidate a newly allocated ASN. */
arch/alpha/kernel/smp.c +26 -26

87 lines not on this page · raw message

arch/alpha/mm/fault.c +3 -1
index f40ac0826a854..53e170e965915 100644
@@ -46,7 +46,9 @@ __load_new_mm_context(struct mm_struct *next_mm)
 	struct pcb_struct *pcb;
 
 	mmc = __get_new_mm_context(next_mm, smp_processor_id());
-	next_mm->context[smp_processor_id()] = mmc;
+	WRITE_ONCE(next_mm->context[smp_processor_id()], mmc);
+	/* Publish the context before this CPU can access the mm. */
+	smp_mb();
 
 	pcb = &current_thread_info()->pcb;
 	pcb->asn = mmc & HARDWARE_ASN_MASK;
arch/alpha/mm/tlbflush.c +1 -1
index 239c72b8a7412..a2aef90e6234b 100644
@@ -66,7 +66,7 @@ static void ipi_flush_mm_and_page(void *x)
 	struct tlb_mm_and_addr *d = x;
 
 	/* Part 1: mm context side (Alpha uses ASN/context as a key mechanism). */
-	if (d->mm == current->active_mm && !asn_locked())
+	if (d->mm == current->mm && !asn_locked())
 		__load_new_mm_context(d->mm);
 	else
 		flush_tlb_other(d->mm);
Signature · 1 line
2.53.0
author maintainer
#1356 lore raw

PATCH 1353/1536 ALSA: hda/via: Apply runtime PM workaround for ASUS X55A

In reply to Greg Kroah-Hartman

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

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

From: Vasiliy Kovalev <[email protected]>

[ Upstream commit f6e8d5ebde5ceb7d3c0eef6e9e4d82862b503ade ]

ASUS X55A requires the same workaround like other machines with VT1802, otherwise it loses the codec power on a few nodes and the sound stays silent.

---
 sound/pci/hda/patch_via.c | 1 +
 1 file changed, 1 insertion(+)
sound/pci/hda/patch_via.c +1 -0
index d0893059b1b9b..456df3a7dc6da 100644
@@ -1038,6 +1038,7 @@ static const struct hda_fixup via_fixups[] = {
 static const struct hda_quirk vt2002p_fixups[] = {
 	SND_PCI_QUIRK(0x1043, 0x13f7, "Asus B23E", VIA_FIXUP_POWER_SAVE),
 	SND_PCI_QUIRK(0x1043, 0x1487, "Asus G75", VIA_FIXUP_ASUS_G75),
+	SND_PCI_QUIRK(0x1043, 0x1c33, "Asus X55A", VIA_FIXUP_POWER_SAVE),
 	SND_PCI_QUIRK(0x1043, 0x8532, "Asus X202E", VIA_FIXUP_INTMIC_BOOST),
 	SND_PCI_QUIRK_VENDOR(0x1558, "Clevo", VIA_FIXUP_POWER_SAVE),
 	{}
Signature · 1 line
2.53.0
author maintainer
#1357 lore raw

PATCH 1354/1536 spi: ch341: handle transfers without a TX or RX buffer

In reply to Greg Kroah-Hartman

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

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

From: Weibin Liu <[email protected]>

[ Upstream commit 84182c48999f856c3865e4a537c244f9569c9f6c ]

ch341_transfer_one() unconditionally copies from trans->tx_buf into the TX packet and hands trans->rx_buf to usb_bulk_msg() for the readback.

The SPI core allows half-duplex transfers where either of the buffers is NULL, so a transfer without TX data crashes the kernel on the memcpy and a transfer without RX data makes usb_bulk_msg() store the received data at address 0.

The CH341A clocks data in both directions on every transfer; there is no mode to disable a direction. Set SPI_CONTROLLER_MUST_TX and SPI_CONTROLLER_MUST_RX so the SPI core fills in dummy buffers for half-duplex transfers.

Fixes 8846739f52af ("spi: add ch341a usb2spi driver")
---
 drivers/spi/spi-ch341.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/spi/spi-ch341.c +6 -0
index 3eaa8f176f63a..170240a0dde89 100644
@@ -189,6 +189,12 @@ static int ch341_probe(struct usb_interface *intf,
 	ctrl->transfer_one = ch341_transfer_one;
 	ctrl->set_cs = ch341_set_cs;
 	ctrl->auto_runtime_pm = false;
+	/*
+	 * The CH341A SPI_STREAM command clocks data in both directions on
+	 * every transfer, so the driver always needs a TX and an RX buffer;
+	 * let the SPI core supply dummy buffers for half-duplex transfers.
+	 */
+	ctrl->flags = SPI_CONTROLLER_MUST_TX | SPI_CONTROLLER_MUST_RX;
 
 	usb_set_intfdata(intf, ch341);
 
Signature · 1 line
2.53.0
author maintainer
#1358 lore raw

PATCH 1355/1536 hwmon: (corsair-cpro) Make wait_input_report_lock IRQ safe

In reply to Greg Kroah-Hartman

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

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

From: Sanan Hasanov <[email protected]>

[ Upstream commit e4fdc82f55cf0e3d5df5c88278da5baa76a109d1 ]

ccp_raw_event() is the HID ->raw_event() callback and takes wait_input_report_lock with a plain spin_lock(). This callback can run in very different contexts depending on the transport: from process context (e.g. uhid, via a write() to /dev/uhid) with softirqs and interrupts enabled, and from URB completion, which is softirq context for HCDs using HCD_BH and hard interrupt context for HCDs that do not (e.g. OHCI, UHCI).

Taking the lock from process context with softirqs enabled while the same lock is also taken from softirq context can deadlock if the softirq interrupts the lock holder on the same CPU. Lockdep reports:

WARNING: inconsistent lock state inconsistent {SOFTIRQ-ON-W} -> {IN-SOFTIRQ-W} usage.
...

   spin_lock include/linux/spinlock.h:347 [inline]
   ccp_raw_event+0x51/0x110 drivers/hwmon/corsair-cpro.c:161
   __hid_input_report+0x41c/0x580 drivers/hid/hid-core.c:2175
   hid_irq_in+0x492/0x710 drivers/hid/usbhid/hid-core.c:287
   __usb_hcd_giveback_urb+0x378/0x540 drivers/usb/core/hcd.c:1657
   dummy_timer+0xa91/0x4cc0 drivers/usb/gadget/udc/dummy_hcd.c:2023

For the same reason, the spin_lock_bh() in send_usb_cmd() is not sufficient when ccp_raw_event() is called from hard interrupt context.

Use spin_lock_irqsave() in ccp_raw_event(), since it may be called with interrupts already disabled, and spin_lock_irq() in send_usb_cmd(), which always runs in process context.

---
 drivers/hwmon/corsair-cpro.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
drivers/hwmon/corsair-cpro.c +5 -4
index bf7775a731fbe..17bb080eb9bb6 100644
@@ -135,9 +135,9 @@ static int send_usb_cmd(struct ccp_device *ccp, u8 command, u8 byte1, u8 byte2,
 	 * the raw event parsing and marked the ccp->wait_input_report
 	 * completion as done.
 	 */
-	spin_lock_bh(&ccp->wait_input_report_lock);
+	spin_lock_irq(&ccp->wait_input_report_lock);
 	reinit_completion(&ccp->wait_input_report);
-	spin_unlock_bh(&ccp->wait_input_report_lock);
+	spin_unlock_irq(&ccp->wait_input_report_lock);
 
 	ret = hid_hw_output_report(ccp->hdev, ccp->cmd_buffer, OUT_BUFFER_SIZE);
 	if (ret < 0)
@@ -156,15 +156,16 @@ static int send_usb_cmd(struct ccp_device *ccp, u8 command, u8 byte1, u8 byte2,
 static int ccp_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size)
 {
 	struct ccp_device *ccp = hid_get_drvdata(hdev);
+	unsigned long flags;
 
 	/* only copy buffer when requested */
-	spin_lock(&ccp->wait_input_report_lock);
+	spin_lock_irqsave(&ccp->wait_input_report_lock, flags);
 	if (!completion_done(&ccp->wait_input_report)) {
 		memcpy(ccp->buffer, data, min(IN_BUFFER_SIZE, size));
 		ccp->buffer_recv_size = size;
 		complete_all(&ccp->wait_input_report);
 	}
-	spin_unlock(&ccp->wait_input_report_lock);
+	spin_unlock_irqrestore(&ccp->wait_input_report_lock, flags);
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#1359 lore raw

PATCH 1356/1536 lib/buildid: reject file offsets that do not fit in pgoff_t

In reply to Greg Kroah-Hartman

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

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

From: Nickolai Zeldovich <[email protected]>

[ Upstream commit 0007654a7bf13ef2a19afd398bbc6507087f19fd ]

On a 32-bit kernel, parsing the build ID of a crafted ELF file can copy far more than the intended bytes into a 64-byte on-stack buffer in __build_id_parse(), corrupting the stack of whatever context fetches the build ID. This might be reachable without privilege: perf records a build ID for PERF_RECORD_MMAP2 on the no-fault path when a process mmaps its own file (build_id_parse_nofault() from perf_event_mmap()), and BPF build-id stack maps do the same.

freader_get_folio() turns a 64-bit file offset into a page cache index with file_off >> PAGE_SHIFT and passes it to filemap_get_folio(). pgoff_t is unsigned long, 32-bit on a 32-bit kernel, so an ELF64 e_phoff of 2^44 + k * PAGE_SIZE truncates to index k. filemap_get_folio() returns the cached folio at index k, whose folio_pos() is far below the requested file_off. In freader_fetch() the folio does not contain file_off, so the "crossing folio boundaries" path computes part_sz = folio_off + folio_sz - file_off as a large u64 (file_off is much larger), and the following memcpy() truncates it to size_t and copies a page into the 64-byte buffer. On a 64-bit kernel the index is not truncated, the folio is not cached and the fetch returns -EFAULT, so only 32-bit kernels are affected.

Reject a file offset that cannot be represented as a page cache index before the lookup, so such a file fails the build ID parse cleanly as it already does on 64-bit.

Reproduced on i386 under QEMU with CONFIG_STACKPROTECTOR_STRONG: mmapping a crafted ELF (ELFCLASS64, e_phoff = 2^44) while a perf event with attr.build_id is open panics with "stack-protector: Kernel stack is corrupted in: __build_id_parse"; with this patch the parse returns -EFAULT and the mmap completes cleanly. Built for i386 with W=1, no new warnings.

Fixes de3ec364c3c3 ("lib/buildid: add single folio-based file reader abstraction")
Assisted-by LLM
---
 lib/buildid.c | 4 ++++
 1 file changed, 4 insertions(+)
lib/buildid.c +4 -0
index ef112a7084ef1..015a1f9d2b48b 100644
@@ -66,6 +66,10 @@ static int freader_get_folio(struct freader *r, loff_t file_off)
 
 	freader_put_folio(r);
 
+	/* the page index must fit in pgoff_t */
+	if (file_off < 0 || file_off > MAX_LFS_FILESIZE)
+		return -EFAULT;
+
 	/* only use page cache lookup - fail if not already cached */
 	r->folio = filemap_get_folio(r->file->f_mapping, file_off >> PAGE_SHIFT);
 
Signature · 1 line
2.53.0
author maintainer
#1360 lore raw

PATCH 1357/1536 netfilter: nf_reject: initialize IPCB at inet ingress

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

[ Upstream commit 73a73d442f9986353fe284bd1b504d0313d0f153 ]

The inet ingress hook runs before ip_rcv_core() and ip6_rcv_core(), so neither IPCB nor IP6CB has been initialized when nft_reject_inet passes a packet to nf_send_unreach() or nf_send_unreach6(). skb->cb can therefore retain metadata from an earlier protocol layer.

For IPv4, icmp_send() treats IPCB(skb)->opt as parsed IPv4 options. Stale option offsets can make __ip_options_echo() copy an attacker-controlled length into its 40-byte reply option buffer and overflow the stack. On an unpatched v7.2-rc5 kernel, the IPv4 reproducer produced:

  BUG: KASAN: stack-out-of-bounds in __ip_options_echo()
  Write of size 255

For IPv6, icmpv6_send() consumes IP6CB(skb) as parsed IPv6 metadata. It always uses iif for source selection and, when MIP6 is enabled, uses dsthao as an extension-header offset. These fields must not be stale.

For NF_INET_INGRESS, clear the address-family-specific control block and restore its input interface before constructing the ICMP error. This matches similar initialization normally performed by ip_rcv_core() and ip6_rcv_core().

Fixes 117ca1f8920c ("netfilter: nft_reject_inet: allow to use reject from inet ingress")
Assisted-by Codex:gpt-5.6-sol Codex:gpt-5.5-cyber
---
 net/ipv4/netfilter/nf_reject_ipv4.c | 5 +++++
 net/ipv6/netfilter/nf_reject_ipv6.c | 5 +++++
 2 files changed, 10 insertions(+)
net/ipv4/netfilter/nf_reject_ipv4.c +5 -0
index 021638aef1706..29c70e92a1722 100644
@@ -350,6 +350,11 @@ void nf_send_unreach(struct sk_buff *skb_in, int code, int hook)
 	if (!skb_valid_dst(skb_in) && nf_reject_fill_skb_dst(skb_in) < 0)
 		return;
 
+	if (hook == NF_INET_INGRESS) {
+		memset(IPCB(skb_in), 0, sizeof(*IPCB(skb_in)));
+		IPCB(skb_in)->iif = skb_in->skb_iif;
+	}
+
 	if (skb_csum_unnecessary(skb_in) ||
 	    !nf_reject_verify_csum(skb_in, dataoff, proto)) {
 		icmp_send(skb_in, ICMP_DEST_UNREACH, code, 0);
net/ipv6/netfilter/nf_reject_ipv6.c +5 -0
index 95ddd533c506c..7beb12046486f 100644
@@ -431,6 +431,11 @@ void nf_send_unreach6(struct net *net, struct sk_buff *skb_in,
 	if (hooknum == NF_INET_LOCAL_OUT && skb_in->dev == NULL)
 		skb_in->dev = net->loopback_dev;
 
+	if (hooknum == NF_INET_INGRESS) {
+		memset(IP6CB(skb_in), 0, sizeof(*IP6CB(skb_in)));
+		IP6CB(skb_in)->iif = skb_in->skb_iif;
+	}
+
 	if (!skb_valid_dst(skb_in) && nf_reject6_fill_skb_dst(skb_in) < 0)
 		return;
 
Signature · 1 line
2.53.0
author maintainer
#1361 lore raw

PATCH 1358/1536 hwmon: (coretemp) Fix handling of isolated SMT siblings

In reply to Greg Kroah-Hartman

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

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

From: Ximing Zhang <[email protected]>

[ Upstream commit 37c1974a0ec4ec4624a270291a179c53f8f4fbca ]

Commit 0f8b916bc5b5 ("hwmon: (coretemp) avoid RDMSR interrupts to isolated CPUs") prevents create_core_data() from creating temperature data for an isolated CPU. coretemp_cpu_online(), however, still adds that CPU to pdata->cpumask.

When an isolated SMT thread is processed before a housekeeping sibling, the mask makes coretemp_cpu_online() believe that the core is already represented. The housekeeping sibling then gets no temperature attributes. Package attributes are similarly not retried when the first CPU processed in a die is isolated.

The mask is also used to select a replacement CPU when a sensor target goes offline. Including isolated CPUs permits the driver to retarget a sensor to one, causing subsequent sysfs reads to send an RDMSR IPI to an isolated CPU.

Keep isolated CPUs out of pdata->cpumask by moving the housekeeping check to coretemp_cpu_online(). Sensor creation is then deferred to an eligible CPU, and hotplug replacement targets remain on housekeeping CPUs.

Tested on an Intel Core i7-10510U running 6.18.50-3-cachyos-lts, with nohz_full=1 on CPU 1 and its housekeeping SMT sibling on CPU 5. The stock driver omitted Core 1 after module load and retained its readable sensor after CPU 5 was offlined. The patched driver exposed Core 1, removed it when CPU 5 went offline, and restored it when CPU 5 returned.

Fixes 0f8b916bc5b5 ("hwmon: (coretemp) avoid RDMSR interrupts to isolated CPUs")
Cc Marcelo Tosatti <[email protected]>
---
 drivers/hwmon/coretemp.c | 26 ++++++++++++++++----------
 1 file changed, 16 insertions(+), 10 deletions(-)
drivers/hwmon/coretemp.c +16 -10
index e84ccf65b327a..04b20cf272ac8 100644
@@ -565,9 +565,6 @@ static int create_core_data(struct platform_device *pdev, unsigned int cpu,
 	u32 eax, edx;
 	int err;
 
-	if (!housekeeping_cpu(cpu, HK_TYPE_MISC))
-		return 0;
-
 	tdata = init_temp_data(pdata, cpu, pkg_flag);
 	if (!tdata)
 		return -ENOMEM;
@@ -687,6 +684,14 @@ static int coretemp_cpu_online(unsigned int cpu)
 	if (!cpu_has(c, X86_FEATURE_DTHERM))
 		return -ENODEV;
 
+	/*
+	 * Keep isolated CPUs out of pdata->cpumask. Besides tracking the CPUs
+	 * available to this driver, the mask is used to select the CPU on which
+	 * to read the temperature MSRs.
+	 */
+	if (!housekeeping_cpu(cpu, HK_TYPE_MISC))
+		return 0;
+
 	pdata = platform_get_drvdata(pdev);
 	if (!pdata->hwmon_dev) {
 		struct device *hwmon;
@@ -716,8 +721,8 @@ static int coretemp_cpu_online(unsigned int cpu)
 	}
 
 	/*
-	 * Check whether a thread sibling is already online. If not add the
-	 * interface for this CPU core.
+	 * Check whether a housekeeping thread sibling is already online. If
+	 * not, add the interface for this CPU core.
 	 */
 	if (!cpumask_intersects(&pdata->cpumask, topology_sibling_cpumask(cpu)))
 		coretemp_add_core(pdev, cpu, 0);
@@ -747,9 +752,9 @@ static int coretemp_cpu_offline(unsigned int cpu)
 	cpumask_clear_cpu(cpu, &pd->cpumask);
 
 	/*
-	 * If this is the last thread sibling, remove the CPU core
-	 * interface, If there is still a sibling online, transfer the
-	 * target cpu of that core interface to it.
+	 * If this is the last housekeeping thread sibling, remove the CPU core
+	 * interface. If there is still a housekeeping sibling online, transfer
+	 * the target CPU of that core interface to it.
 	 */
 	target = cpumask_any_and(&pd->cpumask, topology_sibling_cpumask(cpu));
 	if (target >= nr_cpu_ids) {
@@ -761,7 +766,8 @@ static int coretemp_cpu_offline(unsigned int cpu)
 	}
 
 	/*
-	 * If all cores in this pkg are offline, remove the interface.
+	 * If all housekeeping cores in this pkg are offline, remove the
+	 * interface.
 	 */
 	tdata = get_temp_data(pd, -1);
 	if (cpumask_empty(&pd->cpumask)) {
@@ -774,7 +780,7 @@ static int coretemp_cpu_offline(unsigned int cpu)
 
 	/*
 	 * Check whether this core is the target for the package
-	 * interface. We need to assign it to some other cpu.
+	 * interface. We need to assign it to some other housekeeping CPU.
 	 */
 	if (tdata && tdata->cpu == cpu) {
 		target = cpumask_first(&pd->cpumask);
Signature · 1 line
2.53.0
author maintainer
#1362 lore raw

PATCH 1359/1536 hwmon: (gigabyte_waterforce) reject short input reports

In reply to Greg Kroah-Hartman

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

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

From: Jiale Yao <[email protected]>

[ Upstream commit 400be69515c327ced60082b27ede902a8d93cbdb ]

The HID raw_event callback runs before HID core validates the received report length. waterforce_raw_event() reads command bytes and then accesses fixed offsets for firmware or status data without any length checks. A truncated report can therefore cause out-of-bounds reads and update hwmon state with unrelated data.

Require every report to contain the firmware response fields, which also covers both command bytes. After identifying a status response, require the byte at the highest status offset before accessing its payload.

Fixes 42ac68e3d4ba ("hwmon: Add driver for Gigabyte AORUS Waterforce AIO coolers")
---
 drivers/hwmon/gigabyte_waterforce.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/hwmon/gigabyte_waterforce.c +5 -0
index 4eea05f8b569c..f4d0376dd68e0 100644
@@ -257,6 +257,9 @@ static int waterforce_raw_event(struct hid_device *hdev, struct hid_report *repo
 {
 	struct waterforce_data *priv = hid_get_drvdata(hdev);
 
+	if (size <= FIRMWARE_VER_START_OFFSET_2)
+		return 0;
+
 	if (data[0] == get_firmware_ver_cmd[0] && data[1] == get_firmware_ver_cmd[1]) {
 		/* Received a firmware version report */
 		priv->firmware_version =
@@ -269,6 +272,8 @@ static int waterforce_raw_event(struct hid_device *hdev, struct hid_report *repo
 
 	if (data[0] != get_status_cmd[0] || data[1] != get_status_cmd[1])
 		return 0;
+	if (size <= WATERFORCE_TEMP_SENSOR)
+		return 0;
 
 	priv->temp_input[0] = data[WATERFORCE_TEMP_SENSOR] * 1000;
 	priv->speed_input[0] = get_unaligned_le16(data + WATERFORCE_FAN_SPEED);
Signature · 1 line
2.53.0
author maintainer
#1363 lore raw

PATCH 1360/1536 f2fs: flush SIT journal during filesystem resize

In reply to Greg Kroah-Hartman

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

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

From: Wenjie Qi <[email protected]>

[ Upstream commit a6ede405455106bf42164ec96fd84008c5aabdd9 ]

During a filesystem resize, SBI_IS_RESIZEFS prevents new SIT entries from being added to the journal and forces existing entries to the SIT area. However, f2fs_flush_sit_entries() returns early when there are no new dirty sentries, leaving existing journal entries behind.

After the main area shrinks, a later checkpoint can access a journal entry whose segment number is outside the new geometry and trigger f2fs_bug_on().

Only take the zero-dirty fast path when entries may be written back to the journal. This lets resize drain existing entries through remove_sits_in_journal() even when there are no new dirty sentries.

Fixes 04f0b2eaa3b3 ("f2fs: ioctl for removing a range from F2FS")
---
 fs/f2fs/segment.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/f2fs/segment.c +1 -1
index 1ec43e1537fb2..6abe435b9f0d8 100644
@@ -4553,7 +4553,7 @@ void f2fs_flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
 
 	down_write(&sit_i->sentry_lock);
 
-	if (!sit_i->dirty_sentries)
+	if (!sit_i->dirty_sentries && to_journal)
 		goto out;
 
 	/*
Signature · 1 line
2.53.0
author maintainer
#1364 lore raw

PATCH 1361/1536 f2fs: fix submit accounting for IPU writeback

In reply to Greg Kroah-Hartman

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

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

From: Seongjae Jeong <[email protected]>

[ Upstream commit 6d1f622b9c069378cdb83088be2b15a9b480b8a3 ]

f2fs_write_cache_pages() uses the submitted count, which is set to fio.submitted in f2fs_write_single_data_page(), to update nwritten and decrement wbc->nr_to_write.

In the OPU path, f2fs_submit_page_write() sets fio->submitted to 1. However, in the IPU path, fio->submitted is never set and remains zero. As a result, successful IPU writes are not accounted for. This can cause asynchronous writeback to continue beyond its budget.

Set fio->submitted in f2fs_inplace_write_data() after a page is successfully merged into a bio or submitted, so that successful IPU writes are included in the writeback accounting.

Fixes d68f735b3bc9 ("f2fs: check io submission more precisely")
---
 fs/f2fs/segment.c | 1 +
 1 file changed, 1 insertion(+)
fs/f2fs/segment.c +1 -0
index 6abe435b9f0d8..49146476882b1 100644
@@ -3954,6 +3954,7 @@ int f2fs_inplace_write_data(struct f2fs_io_info *fio)
 	else
 		err = f2fs_submit_page_bio(fio);
 	if (!err) {
+		fio->submitted = 1;
 		f2fs_update_device_state(fio->sbi, fio->ino,
 						fio->new_blkaddr, 1);
 		f2fs_update_iostat(fio->sbi, fio->page->mapping->host,
Signature · 1 line
2.53.0
author maintainer
#1365 lore raw

PATCH 1362/1536 rtc: cmos: Disable ACPI RTC event before handling it

In reply to Greg Kroah-Hartman

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

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

From: Gregory Price <[email protected]>

[ Upstream commit 3f67038df8b5cba07254d1cff60d73e988b49ab7 ]

Users of RTC_UIE_ON can stop receiving update interrupts when rtc-cmos handles alarms through ACPI. In one 50-run test, 40 runs passed and 10 timed out after receiving between one and four of five expected events.

The ACPI ff_rt_clk counter stopped at 218, exactly matching the number of events delivered to userspace, and reported:

218 STS disabled unmasked

rtc_handler() runs in the threaded ACPI SCI handler and calls cmos_interrupt(), which schedules rtc->irqwork. The work can run before rtc_handler() returns:

    ACPI SCI thread          rtc->irqwork

    cmos_interrupt()
      schedule_work()
                             __rtc_set_alarm()
                               rtc_wake_on()
    acpi_clear_event()
    acpi_disable_event()

The SCI thread then disables the event that the worker enabled for the next alarm. That alarm sets its status while delivery remains disabled, so no update interrupt reaches userspace.

Clear and disable the current ACPI RTC event before cmos_interrupt() schedules the work. The worker can then enable the next event without the handler undoing it. With this ordering, 150 runs delivered all 750 events without a stall.

Fixes 311ee9c151ad ("rtc: cmos: allow using ACPI for RTC alarm instead of HPET")
---
 drivers/rtc/rtc-cmos.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/rtc/rtc-cmos.c +3 -3
index 79ef0d8164788..2834c08c6e25a 100644
@@ -757,7 +757,9 @@ static u32 rtc_handler(void *context)
 	unsigned char rtc_intr;
 	unsigned long flags;
 
-
+	/* Quiesce this event before rtc->irqwork can arm the next one. */
+	acpi_clear_event(ACPI_EVENT_RTC);
+	acpi_disable_event(ACPI_EVENT_RTC, 0);
 	/*
 	 * Always update rtc irq when ACPI is used as RTC Alarm.
 	 * Or else, ACPI SCI is enabled during suspend/resume only,
@@ -780,8 +782,6 @@ static u32 rtc_handler(void *context)
 	}
 
 	pm_wakeup_hard_event(dev);
-	acpi_clear_event(ACPI_EVENT_RTC);
-	acpi_disable_event(ACPI_EVENT_RTC, 0);
 	return ACPI_INTERRUPT_HANDLED;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1366 lore raw

PATCH 1363/1536 platform/x86/amd/pmc: Fix RTC reference leak in amd_pmc_verify_czn_rtc()

In reply to Greg Kroah-Hartman

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

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

From: Ma Ke <[email protected]>

[ Upstream commit 22b9306f1fcf86f80b55f05f08d10a9951ba970a ]

amd_pmc_verify_czn_rtc() opens the RTC with rtc_class_open(), which takes both a device reference and a module reference on the RTC driver. The matching release is rtc_class_close(), and it is never called. Every return path after the device has been opened, the ones that return 0 as well as the ones that report an error, leaves both references behind, so each S0i3 suspend leaks them.

Release the reference with a __free() cleanup on the declaration, which covers every return path without adding labels.

rtc_class_close() does not accept a NULL argument, so the cleanup helper has to guard against one: rtc_class_open() may fail and the declaration still has to be cleaned up.

Found by code review.

Fixes 59348401ebed ("platform/x86: amd-pmc: Add special handling for timer based S0i3 wakeup")
---
 drivers/platform/x86/amd/pmc/pmc.c | 5 +++--
 include/linux/rtc.h                | 2 ++
 2 files changed, 5 insertions(+), 2 deletions(-)
drivers/platform/x86/amd/pmc/pmc.c +3 -2
index 44e6bd91af4ac..821a2f4dc554a 100644
@@ -14,6 +14,7 @@
 #include <linux/acpi.h>
 #include <linux/bitfield.h>
 #include <linux/bits.h>
+#include <linux/cleanup.h>
 #include <linux/debugfs.h>
 #include <linux/delay.h>
 #include <linux/dmi.h>
@@ -617,7 +618,6 @@ static int amd_pmc_wa_irq1(struct amd_pmc_dev *pdev)
 
 static int amd_pmc_verify_czn_rtc(struct amd_pmc_dev *pdev, u32 *arg)
 {
-	struct rtc_device *rtc_device;
 	time64_t then, now, duration;
 	struct rtc_wkalrm alarm;
 	struct rtc_time tm;
@@ -633,7 +633,8 @@ static int amd_pmc_verify_czn_rtc(struct amd_pmc_dev *pdev, u32 *arg)
 	if (pdev->major < 64 || (pdev->major == 64 && pdev->minor < 53))
 		return 0;
 
-	rtc_device = rtc_class_open("rtc0");
+	struct rtc_device *rtc_device __free(rtc_class_close) =
+		rtc_class_open("rtc0");
 	if (!rtc_device)
 		return 0;
 	rc = rtc_read_alarm(rtc_device, &alarm);
include/linux/rtc.h +2 -0
index 3f4d315aaec9e..ca30c0c5a1acd 100644
@@ -13,6 +13,7 @@
 #define _LINUX_RTC_H_
 
 
+#include <linux/cleanup.h>
 #include <linux/types.h>
 #include <linux/interrupt.h>
 #include <linux/nvmem-provider.h>
@@ -198,6 +199,7 @@ extern void rtc_update_irq(struct rtc_device *rtc,
 
 extern struct rtc_device *rtc_class_open(const char *name);
 extern void rtc_class_close(struct rtc_device *rtc);
+DEFINE_FREE(rtc_class_close, struct rtc_device *, if (_T) rtc_class_close(_T));
 
 extern int rtc_irq_set_state(struct rtc_device *rtc, int enabled);
 extern int rtc_irq_set_freq(struct rtc_device *rtc, int freq);
Signature · 1 line
2.53.0
author maintainer
#1367 lore raw

PATCH 1364/1536 hwmon: (sht3x) Return the consumed count for heater writes

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 817ac527100c8e20684211eb919ffd6d875adc7a ]

heater_enable_store() returns the result of i2c_master_send(), which is the two-byte command length on success rather than the sysfs input count. This can report more bytes than were supplied, or a partial write for a fully processed input. For example, writing "on\n" returns two instead of three, so a caller retrying the remaining newline gets -EINVAL even though the heater command succeeded. Retrying the remainder of "off\n" can also send the heater-off command twice.

Return count after a complete command transfer. Preserve negative I2C errors and return -EIO for nonnegative incomplete transfers, so a zero-message transfer is not reported as a successful zero-byte write. Keep the existing boolean parsing, command selection and locking.

Fixes 50c22cd154e5 ("hwmon: (sht3x) add humidity heater element control")
---
 drivers/hwmon/sht3x.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/hwmon/sht3x.c +4 -1
index 1f63c07cfb085..87f406cca6cae 100644
@@ -546,7 +546,10 @@ static ssize_t heater_enable_store(struct device *dev,
 
 	mutex_unlock(&data->i2c_lock);
 
-	return ret;
+	if (ret != SHT3X_CMD_LENGTH)
+		return ret < 0 ? ret : -EIO;
+
+	return count;
 }
 
 static int update_interval_read(struct device *dev)
Signature · 1 line
2.53.0
author maintainer
#1368 lore raw

PATCH 1365/1536 Revert "Input: matrix_keypad - force switch rows to input mode"

In reply to Greg Kroah-Hartman

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

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

From: Alexander Kochetkov <[email protected]>

[ Upstream commit 1527451f87dfe368b8ddeeb501c24ac9bde6b589 ]

This reverts commit 01c84b03d80aab9f04c4e3e1f9085f4202ff7c29.

The commit makes every scan call gpiod_direction_input() on the row GPIOs. On pin controllers where GPIO input and interrupt are separate pinmux functions this switches the row pins out of interrupt mode, and enable_row_irqs() does not switch them back: it only unmasks the interrupts. Row interrupts then never arrive and the keypad stops working. Seen with a matrix keypad on an Allwinner A64 board (PINE A64-LTS); it works again with the commit reverted.

The workaround is not needed on Ingenic either: the author of the reverted commit re-tested all available JZ47xx SoCs and they all report the live pin state in interrupt mode, see the thread in Link.

---
 drivers/input/keyboard/matrix_keypad.c | 3 ---
 1 file changed, 3 deletions(-)
drivers/input/keyboard/matrix_keypad.c +0 -3
index 3c38bae576edd..c502ee266d1a8 100644
@@ -118,9 +118,6 @@ static void matrix_keypad_scan(struct work_struct *work)
 
 	memset(new_state, 0, sizeof(new_state));
 
-	for (row = 0; row < keypad->num_row_gpios; row++)
-		gpiod_direction_input(keypad->row_gpios[row]);
-
 	/* assert each column and read the row status out */
 	for (col = 0; col < keypad->num_col_gpios; col++) {
 
Signature · 1 line
2.53.0
author maintainer
#1369 lore raw

PATCH 1366/1536 cgroup: fix cgroup.kill for exited thread group leader

In reply to Greg Kroah-Hartman

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

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

From: Kir Kolyshkin <[email protected]>

[ Upstream commit da13e0e72a7329c95642c44b2d03d194ab071e04 ]

cgroup.kill does not work in case a process' thread group leader is gone but other threads are still running. This is because __cgroup_kill() only walks the thread group leaders and sends SIGKILL to each of them with send_sig(), which uses PIDTYPE_PID:

1. The exited leader is still listed by CSS_TASK_ITER_PROCS as long as the process has live threads, but a signal directed at a single exiting task never takes effect: complete_signal() does not look for another thread to deliver it to, and __send_signal_locked() now drops it altogether. The process keeps running.

2. The live threads of such a process can be migrated to another cgroup by writing any of their IDs to cgroup.procs, while the exited leader stays behind. The destination cgroup has no thread group leader to iterate, so writing to its cgroup.kill does nothing at all.

In both cases the cgroup stays populated after cgroup.kill, and a process inside a container can use this to survive the container being killed. This also works with a private PID namespace when the init of the container is the process, as the PID namespace is not torn down while init has live threads.

Case 1 can be fixed by using do_send_sig_info(..., PIDTYPE_TGID) instead of send_sig(), so that the signal is taken by a live thread even if the task found by the iterator is exiting. Note it was pointed out by Eric in [1] while reviewing v2 of cgroup.kill patchset, and v3 was meant to switch to it, but the change was only made in cgroup_post_fork(), leaving __cgroup_kill() with send_sig().

Case 2 can only be fixed by iterating over all threads, so this is what the fix also does. Once a thread group is being killed, its other threads are skipped since they already have a fatal signal pending.

I ran some performance checks and the added cost is ~60 ns per every thread on my laptop (and less than a millisecond for 10K threads), which seems low. The time to "populated 0" seems unchanged.

The issue was found in crun by Anthropic's OSS Scanner, and crun is getting a workaround for it [2] (which does what we needed to do before cgroup.kill was added).

[1] https://lore.kernel.org/all/[email protected]/
[2] https://github.com/containers/crun/pull/2351

Fixes 661ee6280931 ("cgroup: introduce cgroup.kill")
Cc [email protected] # v5.14+
---
 kernel/cgroup/cgroup.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/cgroup/cgroup.c +2 -2
index 4983d7b71cd42..766351c0e34e6 100644
@@ -4103,7 +4103,7 @@ static void __cgroup_kill(struct cgroup *cgrp)
 	cgrp->kill_seq++;
 	spin_unlock_irq(&css_set_lock);
 
-	css_task_iter_start(&cgrp->self, CSS_TASK_ITER_PROCS | CSS_TASK_ITER_THREADED, &it);
+	css_task_iter_start(&cgrp->self, CSS_TASK_ITER_THREADED, &it);
 	while ((task = css_task_iter_next(&it))) {
 		/* Ignore kernel threads here. */
 		if (task->flags & PF_KTHREAD)
@@ -4113,7 +4113,7 @@ static void __cgroup_kill(struct cgroup *cgrp)
 		if (__fatal_signal_pending(task))
 			continue;
 
-		send_sig(SIGKILL, task, 0);
+		do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, task, PIDTYPE_TGID);
 	}
 	css_task_iter_end(&it);
 }
Signature · 1 line
2.53.0
author maintainer
#1370 lore raw

PATCH 1367/1536 netdevsim: reject cls_bpf programs bound to another device

In reply to Greg Kroah-Hartman

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

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

From: Jamal Hadi Salim <[email protected]>

[ Upstream commit 5820ca58b409402505b9e904d1ded4908e0b6b81 ]

The issue:
nsim_bpf_setup_tc_block_cb() installs any device-bound SCHED_CLS program without checking that its offload device matches the target netdev. The core cls_bpf attach path rejects a mismatching program, but a netdev that joins a shared block later is replayed the stored filter by cls_bpf_reoffload() before it is inserted into block->ports, so the attach-time check cannot see it. The driver callback is the authoritative per-device acceptance boundary and must enforce the match itself, as nfp already does in nfp_net_bpf_offload().

Without the check, replaying a device-bound program onto a different bpf_offload_dev installs it into that device's netdevsim state, which trips the WARN in nsim_bpf_uninit() (ns->bpf_offloaded set on a foreign device) and can dereference a NULL prog->aux->offload in nsim_prog_set_loaded().

The Fix:
Reject a device-bound program whose offload device does not match the target netdev, with -EINVAL and an extack so the rejected replay is not silent. The check is intentionally narrower than nfp's: it fires only for a dev-bound program, so nsim's bpf_tc_non_bound_accept mode (which admits an unbound program onto the device) is unaffected. Teardown is never blocked: the guard is on the program being installed and an unbind passes cls_bpf.prog = NULL.

Conditions to recreate the bug:
- CONFIG_NETDEVSIM=y, CONFIG_NET_CLS_BPF=y
- load and pin a dev-bound SCHED_CLS program for netdevsim device B
- install the program on a shared block owned by B
- add an independently backed netdevsim device C to that block; the bind replays the filter to C's callback, and C's ports/0/bpf_offloaded_id takes the B-bound program id.

The reported Sashiko review is at
https://netdev-ai.bots.linux.dev/sashiko/#/patchset/[email protected]

---
 drivers/net/netdevsim/bpf.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/net/netdevsim/bpf.c +11 -0
index ca64136372fca..ba4a0ce5864fd 100644
@@ -150,6 +150,17 @@ int nsim_bpf_setup_tc_block_cb(enum tc_setup_type type,
 		return -EOPNOTSUPP;
 	}
 
+	/* A dev-bound program can be replayed here when a netdev joins
+	 * a shared block, after the core attach-time check has run;
+	 * enforce the device match as nfp does.
+	 */
+	if (prog && bpf_prog_is_dev_bound(prog->aux) &&
+	    !bpf_offload_dev_match(prog, ns->netdev)) {
+		NSIM_EA(cls_bpf->common.extack,
+			"program bound to a different device");
+		return -EINVAL;
+	}
+
 	if (cls_bpf->command != TC_CLSBPF_OFFLOAD)
 		return -EOPNOTSUPP;
 
Signature · 1 line
2.53.0
author maintainer
#1371 lore raw

PATCH 1368/1536 net: gro: dont chain linear parts larger than gso_size into frag_list

In reply to Greg Kroah-Hartman

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

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

From: Sorah Fukumori <[email protected]>

[ Upstream commit 679f6929a66db9f5a6611dad37545fbd705962d5 ]

skb_gro_receive() chains an skb into the frag_list of the held packet when its payload cannot be attached as page frags: when its head is not a page fragment and still holds payload, or when its head and frags would overflow the frags[] array of the last packet. Since commit 5eddb24901ee ("gro: add support of (hw)gro packets to gro stack"), that skb may itself be a GSO packet whose linear part holds several gso_size segments. skb_segment() cannot split the linear part of a frag_list member across segments, so segmenting the aggregate in software, e.g. when forwarding it to a device without NETIF_F_FRAGLIST, hits

  BUG_ON(skb_headlen(list_skb) > len);

Fully linear GSO packets come from generic XDP. When the program does not support frags, netif_skb_check_for_xdp() linearizes any nonlinear skb with pskb_expand_head() and skb_linearize() and keeps its GSO metadata. GRO on the device runs before generic XDP, so each aggregate passed by the program carries all of its payload in a kmalloc'ed head. A tunnel that decapsulates these packets and runs GRO again through gro_cells then builds the bad frag_list. This was first seen on a router that forwards TCP received over VXLAN, with a non-frags XDP program attached in SKB mode to the underlying bond because one slave lacks native XDP:

kernel BUG at net/core/skbuff.c:4917!

  RIP: 0010:skb_segment+0xbb6/0xf40
  Call Trace:
   tcp_gso_segment
   ipv6_gso_segment
   skb_mac_gso_segment
   __skb_gso_segment
   validate_xmit_skb
   __dev_queue_xmit
   ip6_output
   ip6_sublist_rcv_finish
   ipv6_list_rcv
   netif_receive_skb_list_internal
   gro_complete
   dev_gro_receive
   gro_receive_skb
   gro_cell_poll
   __napi_poll
   net_rx_action

It reproduces with three network namespaces: TCP sent over VXLAN on an IPv6 veth link to a router namespace that has an XDP_PASS program without frags support attached to the underlay veth in generic mode and GRO enabled on its VXLAN device, and forwards to a veth with tx-scatter-gather-fraglist disabled.

A program with frags support in generic mode gives similar packets. skb_pp_cow_data() rebuilds the skb with up to about a page of linear data in a page_pool head_frag and keeps the GSO metadata, so once frags[] is full the next such packet is chained through frag_list with more than gso_size bytes in its head as well.

Refuse the merge when the linear part to be chained exceeds the held packet's gso_size. tcp_gro_receive() then flushes the held packet and the skb starts a new GRO packet as its head, whose linear length skb_segment() handles.

Fixes 5eddb24901ee ("gro: add support of (hw)gro packets to gro stack")
Assisted-by claude-opus-5-5
---
 net/core/gro.c | 4 ++++
 1 file changed, 4 insertions(+)
net/core/gro.c +4 -0
index 9ee75881b20c3..74b1ed66693f4 100644
@@ -191,6 +191,10 @@ int skb_gro_receive(struct sk_buff *p, struct sk_buff *skb)
 	}
 
 merge:
+	/* skb_segment() cannot split the linear part of a frag_list member. */
+	if (unlikely(headlen > offset + skb_shinfo(p)->gso_size))
+		return -E2BIG;
+
 	/* sk ownership - if any - completely transferred to the aggregated packet */
 	skb->destructor = NULL;
 	skb->sk = NULL;
Signature · 1 line
2.53.0
author maintainer
#1372 lore raw

PATCH 1369/1536 ALSA: compress: fix buffer leak on failed SET_PARAMS

In reply to Greg Kroah-Hartman

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

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

From: Peter Ujfalusi <[email protected]>

[ Upstream commit fbc74ca9fbf7e0b8f6872ccac62f9f4a1f3b5e53 ]

When the driver has neither ops->copy nor a preallocated dma_buffer_p, snd_compr_allocate_buffer() kmallocs runtime->buffer. If ops->set_params() then rejects the parameters, SET_PARAMS fails, the stream stays in the OPEN state and keeps the buffer. The next SET_PARAMS allocates a new buffer and overwrites the pointer, so repeated SET_PARAMS calls with parameters that the driver rejects leak one buffer per call.

Release the framework-owned buffer when ops->set_params() fails on an OPEN stream, so that a failed SET_PARAMS leaves no buffer behind and the buffer is allocated only once per successful setup. Use the same ownership check as snd_compr_free().

Fixes b21c60a4edd2 ("ALSA: core: add support for compress_offload")
---
 sound/core/compress_offload.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
sound/core/compress_offload.c +8 -1
index d81a890b60c65..0d5b3c655e849 100644
@@ -585,8 +585,15 @@ snd_compr_set_params(struct snd_compr_stream *stream, unsigned long arg)
 			return -ENOMEM;
 
 		retval = stream->ops->set_params(stream, params);
-		if (retval)
+		if (retval) {
+			/* the stream stays OPEN: drop the buffer of the rejected setup */
+			if (stream->runtime->state == SNDRV_PCM_STATE_OPEN &&
+			    !stream->runtime->dma_buffer_p) {
+				kfree(stream->runtime->buffer);
+				stream->runtime->buffer = NULL;
+			}
 			return retval;
+		}
 
 		if (stream->next_track)
 			return retval;
Signature · 1 line
2.53.0
author maintainer
#1373 lore raw

PATCH 1370/1536 ALSA: compress: reject buffer geometry change on gapless next_track

In reply to Greg Kroah-Hartman

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

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

From: Peter Ujfalusi <[email protected]>

[ Upstream commit 82da1acad6fd60b6072dd5f3383e6a55efdd2ac7 ]

snd_compr_set_params() is invoked from the gapless next_track re-entry path, which calls snd_compr_allocate_buffer() again and lets buffer_size change while total_bytes_available and total_bytes_transferred still hold values computed for the previous buffer. snd_compr_calc_avail() then derives an avail/count value from those stale counters against the new buffer_size, and snd_compr_write_data() copy_from_user()s that many bytes into the new, potentially smaller buffer, overflowing it with user-controlled length and content.

The buffer is set up once, with the initial SET_PARAMS, and neither the core nor the DSP expects it to change for a gapless track transition. Do not call snd_compr_allocate_buffer() on the next_track path and reject a request that changes the buffer geometry, so that the codec parameters that the driver receives match the buffer in use.

Fixes 9727b490e543 ("ALSA: compress: add support for gapless playback")
---
 sound/core/compress_offload.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
sound/core/compress_offload.c +13 -3
index 0d5b3c655e849..0436ed1b1284f 100644
@@ -580,9 +580,19 @@ snd_compr_set_params(struct snd_compr_stream *stream, unsigned long arg)
 		if (retval)
 			return retval;
 
-		retval = snd_compr_allocate_buffer(stream, params);
-		if (retval)
-			return -ENOMEM;
+		if (stream->next_track) {
+			/*
+			 * total_bytes_available/transferred still refer to the
+			 * current buffer; its geometry must not change.
+			 */
+			if (params->buffer.fragment_size != stream->runtime->fragment_size ||
+			    params->buffer.fragments != stream->runtime->fragments)
+				return -EINVAL;
+		} else {
+			retval = snd_compr_allocate_buffer(stream, params);
+			if (retval)
+				return retval;
+		}
 
 		retval = stream->ops->set_params(stream, params);
 		if (retval) {
Signature · 1 line
2.53.0
author maintainer
#1374 lore raw

PATCH 1371/1536 ALSA: compress: add missing OPEN-state gate to SET_METADATA

In reply to Greg Kroah-Hartman

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

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

From: Peter Ujfalusi <[email protected]>

[ Upstream commit 931f5714b7921290cd1a4742e185aeeae7270ee6 ]

snd_compr_set_metadata() calls stream->ops->set_metadata() straight after copy_from_user(), without ever checking runtime->state, even though the function's own comment says a parameter change should only be allowed once the stream has left the OPEN state. Every other metadata/param entry point in this file (SET_PARAMS, WRITE, ...) enforces that gate.

A codec driver's set_metadata callback can assume SET_PARAMS has already run and initialised its private state; calling it while the stream is still OPEN can operate on that uninitialised state.

Add the OPEN-state check the existing comment already documents.

---
 sound/core/compress_offload.c | 3 +++
 1 file changed, 3 insertions(+)
sound/core/compress_offload.c +3 -0
index 0436ed1b1284f..ae8ab99f53f86 100644
@@ -672,6 +672,9 @@ snd_compr_set_metadata(struct snd_compr_stream *stream, unsigned long arg)
 	* we should allow parameter change only when stream has been
 	* opened not in other cases
 	*/
+	if (stream->runtime->state == SNDRV_PCM_STATE_OPEN)
+		return -EBADFD;
+
 	if (copy_from_user(&metadata, (void __user *)arg, sizeof(metadata)))
 		return -EFAULT;
 
Signature · 1 line
2.53.0
author maintainer
#1375 lore raw

PATCH 1372/1536 ALSA: emux: Stop voices before freeing zones in all cases

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 8a5d87c2ba30e8de31cfbe888fd4d95f43c63db9 ]

The emux voice caches the soundfont zone pointer in vp->zone, which is referred to later, e.g. in snd_emux_send_effect(). For avoiding dangling pointers, the soundfont code calls the sample_reset callback to stop all voices before freeing zones. However, in a few cases (e.g. emu10k1's missing sample_reset or the call path via remove_info()), the sample reset isn't called properly, leaving the playing voices.

Fix it by always registering the sample_reset callback, falling back to snd_emux_terminate_all() when the driver has no own ops, and by calling sample_reset in remove_info() before freeing the zones.

---
 sound/synth/emux/emux.c      | 10 +++++++---
 sound/synth/emux/soundfont.c |  9 +++++++++
 2 files changed, 16 insertions(+), 3 deletions(-)
sound/synth/emux/emux.c +7 -3
index 01444fc960d08..863d35aff1960 100644
@@ -71,7 +71,12 @@ static int sf_sample_free(void *private_data, struct snd_sf_sample *sp,
 static void sf_sample_reset(void *private_data)
 {
 	struct snd_emux *emu = private_data;
-	emu->ops.sample_reset(emu);
+
+	/* stop all voices that might refer to zones and samples to be freed */
+	if (emu->ops.sample_reset)
+		emu->ops.sample_reset(emu);
+	else
+		snd_emux_terminate_all(emu);
 }
 
 int snd_emux_register(struct snd_emux *emu, struct snd_card *card, int index, char *name)
@@ -96,8 +101,7 @@ int snd_emux_register(struct snd_emux *emu, struct snd_card *card, int index, ch
 	sf_cb.private_data = emu;
 	sf_cb.sample_new = sf_sample_new;
 	sf_cb.sample_free = sf_sample_free;
-	if (emu->ops.sample_reset)
-		sf_cb.sample_reset = sf_sample_reset;
+	sf_cb.sample_reset = sf_sample_reset;
 	emu->sflist = snd_sf_new(&sf_cb, emu->memhdr);
 	if (emu->sflist == NULL)
 		return -ENOMEM;
sound/synth/emux/soundfont.c +9 -0
index b38a4e231790f..47137cca50b8c 100644
@@ -485,6 +485,15 @@ remove_info(struct snd_sf_list *sflist, struct snd_soundfont *sf,
 	struct snd_sf_zone *prev, *next, *p;
 	int removed = 0;
 
+	/* stop voices before freeing the zones they might refer to */
+	for (p = sf->zones; p; p = p->next) {
+		if (!p->mapped && p->bank == bank && p->instr == instr) {
+			if (sflist->callback.sample_reset)
+				sflist->callback.sample_reset(sflist->callback.private_data);
+			break;
+		}
+	}
+
 	prev = NULL;
 	for (p = sf->zones; p; p = next) {
 		next = p->next;
Signature · 1 line
2.53.0
author maintainer
#1376 lore raw

PATCH 1373/1536 gpiolib: Free chip resources when allocating the label fails

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 8381e1f15e27087fcb6f07046a526ac8b9b9b2b9 ]

If desc_set_label() fails after the chip's request callback succeeds, gpiod_request_commit() clears GPIOD_FLAG_REQUESTED without calling the free callback. The caller receives an error and has no GPIO to release, leaving resources acquired by the request callback held.

Call the chip's free callback, if present, before clearing the requested bit on label allocation failure. Leave request callback errors on the existing path to avoid freeing a failed request.

Fixes 1f2bcb8c8ccd ("gpio: protect the descriptor label with SRCU")
---
 drivers/gpio/gpiolib.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/gpio/gpiolib.c +4 -1
index bffdaa91d86c5..115bf569dbdd0 100644
@@ -2350,10 +2350,13 @@ static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
 
 	ret = desc_set_label(desc, label ? : "?");
 	if (ret)
-		goto out_clear_bit;
+		goto out_free_gpio;
 
 	return 0;
 
+out_free_gpio:
+	if (guard.gc->free)
+		guard.gc->free(guard.gc, offset);
 out_clear_bit:
 	clear_bit(FLAG_REQUESTED, &desc->flags);
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#1377 lore raw

PATCH 1374/1536 gpio: davinci: Clear interrupt status in every bank on suspend

In reply to Greg Kroah-Hartman

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

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

From: Sahaj Chaudhari <[email protected]>

[ Upstream commit 800d7627f552bbf602a1736b638aee0ada3fbf87 ]

davinci_gpio_save_context() saves the registers of each 32-GPIO register bank, but clears interrupt status only after the loop. At that point g refers to the last bank, so pending status in all preceding banks is left uncleared.

Move the interrupt-status write into the per-bank loop so that the existing suspend-time clearing covers every register bank. Single-bank controllers retain the same behavior.

Fixes 0651a730924b ("gpio: davinci: Add support for system suspend/resume PM")
---
 drivers/gpio/gpio-davinci.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/gpio/gpio-davinci.c +3 -3
index 6d12a65b07528..2011db9ccb4e5 100644
@@ -595,10 +595,10 @@ static void davinci_gpio_save_context(struct davinci_gpio_controller *chips,
 		context->set_data = readl_relaxed(&g->set_data);
 		context->set_rising = readl_relaxed(&g->set_rising);
 		context->set_falling = readl_relaxed(&g->set_falling);
-	}
 
-	/* Clear all interrupt status registers */
-	writel_relaxed(GENMASK(31, 0), &g->intstat);
+		/* Clear stale interrupt status for this bank. */
+		writel_relaxed(GENMASK(31, 0), &g->intstat);
+	}
 }
 
 static void davinci_gpio_restore_context(struct davinci_gpio_controller *chips,
Signature · 1 line
2.53.0
author maintainer
#1378 lore raw

PATCH 1375/1536 gpio: pca953x: Handle direction register read errors in IRQ paths

In reply to Greg Kroah-Hartman

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

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

From: Sahaj Chaudhari <[email protected]>

[ Upstream commit a0fe269293509acdd93b9cfb3f46636f7b91b33a ]

Three IRQ paths ignore the result of reading the direction registers and then use the destination bitmap. pca953x_read_regs() does not populate that bitmap when regmap_bulk_read() fails, leaving the callers to use uninitialized stack data.

This can select incorrect GPIOs for direction changes during IRQ bus synchronization, corrupt the saved input state during IRQ setup, or produce incorrect pending interrupt decisions.

Check the read result at all three sites. Release irq_lock without changing GPIO directions on failure, leave the IRQ history untouched when pending detection fails, and propagate the error from IRQ setup. The read helper already logs the error.

Fixes 0f25fda840a9 ("gpio: pca953x: Zap ad-hoc reg_direction cache")
---
 drivers/gpio/gpio-pca953x.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
drivers/gpio/gpio-pca953x.c +11 -3
index 1c7ae71dfe555..72a1819713ede 100644
@@ -766,6 +766,7 @@ static void pca953x_irq_bus_sync_unlock(struct irq_data *d)
 	DECLARE_BITMAP(irq_mask, MAX_LINE);
 	DECLARE_BITMAP(reg_direction, MAX_LINE);
 	int level;
+	int ret;
 
 	guard(mutex)(&chip->i2c_lock);
 
@@ -780,7 +781,9 @@ static void pca953x_irq_bus_sync_unlock(struct irq_data *d)
 	}
 
 	/* Switch direction to input if needed */
-	pca953x_read_regs(chip, chip->regs->direction, reg_direction);
+	ret = pca953x_read_regs(chip, chip->regs->direction, reg_direction);
+	if (ret)
+		goto out;
 
 	bitmap_or(irq_mask, chip->irq_trig_fall, chip->irq_trig_raise, gc->ngpio);
 	bitmap_or(irq_mask, irq_mask, chip->irq_trig_level_high, gc->ngpio);
@@ -792,6 +795,7 @@ static void pca953x_irq_bus_sync_unlock(struct irq_data *d)
 	for_each_set_bit(level, irq_mask, gc->ngpio)
 		pca953x_gpio_direction_input_unlocked(&chip->gpio_chip, level);
 
+out:
 	mutex_unlock(&chip->irq_lock);
 }
 
@@ -886,7 +890,9 @@ static bool pca953x_irq_pending(struct pca953x_chip *chip, unsigned long *pendin
 	}
 
 	/* Remove output pins from the equation */
-	pca953x_read_regs(chip, chip->regs->direction, reg_direction);
+	ret = pca953x_read_regs(chip, chip->regs->direction, reg_direction);
+	if (ret)
+		return false;
 
 	bitmap_copy(old_stat, chip->irq_stat, gc->ngpio);
 
@@ -987,7 +993,9 @@ static int pca953x_irq_setup(struct pca953x_chip *chip, int irq_base)
 	 * interrupt.  We have to rely on the previous read for
 	 * this purpose.
 	 */
-	pca953x_read_regs(chip, chip->regs->direction, reg_direction);
+	ret = pca953x_read_regs(chip, chip->regs->direction, reg_direction);
+	if (ret)
+		return ret;
 	bitmap_and(chip->irq_stat, irq_stat, reg_direction, gc->ngpio);
 	mutex_init(&chip->irq_lock);
 
Signature · 1 line
2.53.0
author maintainer
#1379 lore raw

PATCH 1376/1536 blk-mq: clear stale inactive flag on hctx reuse

In reply to Greg Kroah-Hartman

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

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

From: Nirmoy Das <[email protected]>

[ Upstream commit afc1de47a7ab607ae6403c4bfda36b0bf3cd342f ]

When the last CPU mapped to an hctx goes offline, blk_mq_hctx_notify_offline() sets BLK_MQ_S_INACTIVE. Updating the number of hardware queues exits every hctx and parks it on q->unused_hctx_list. A later update can reuse a parked hctx through blk_mq_alloc_and_init_hctx(), at any queue index, and nothing clears the flag.

If the reused hctx is mapped to an online CPU, blk_mq_get_tag() keeps returning BLK_MQ_NO_TAG for it. __blk_mq_alloc_requests() sleeps and retries, expecting CPU hotplug to move the task to another CPU, so a task that stays on that CPU never gets a tag. Onlining the original CPU doesn't recover it either, because blk_mq_hctx_notify_online() only clears the flag on the hctx that CPU now maps to.

Clear BLK_MQ_S_INACTIVE in blk_mq_init_hctx() so a reused hctx starts like a freshly allocated one. A reused hctx has no cpuhp instances at that point, so the offline callback can't set the flag again before blk_mq_add_hw_queues_cpuhp() registers it. Clearing the flag in blk_mq_exit_hctx() is not enough, because a parked hctx keeps its cpuhp instances until blk_mq_remove_hw_queues_cpuhp(). Preserve the other hctx state flags.

Reproduced with null_blk on v7.3 in a four-vCPU arm64 QEMU/KVM guest:

modprobe null_blk nr_devices=0
mkdir /sys/kernel/config/nullb/nullb0
cd /sys/kernel/config/nullb/nullb0
echo 4 > submit_queues; echo 1 > memory_backed; echo 16 > size echo 1 > power
echo 0 > /sys/devices/system/cpu/cpu3/online
echo 2 > submit_queues
echo 4 > submit_queues

Offlining CPU3 marks hctx3 inactive. After the two updates it comes back as hctx1 and is mapped to CPU0:

  # cat /sys/block/nullb0/mq/1/cpu_list
  0
  # cat /sys/kernel/debug/block/nullb0/hctx1/state
  INACTIVE

A 4K O_DIRECT read pinned to CPU0 hangs in D state, while the same read on CPU1 and CPU2 completes. Onlining CPU3 again leaves hctx1 inactive and the CPU0 read still hangs. With this change hctx1 state is empty and the reads on CPU0, CPU1 and CPU2 complete, before and after onlining CPU3.

Fixes bf0beec0607d ("blk-mq: drain I/O when all CPUs in a hctx are offline")
Assisted-by LLM
---
 block/blk-mq.c | 1 +
 1 file changed, 1 insertion(+)
block/blk-mq.c +1 -0
index 930c800f5c62c..e01437e64c740 100644
@@ -3925,6 +3925,7 @@ static int blk_mq_init_hctx(struct request_queue *q,
 		struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
 {
 	hctx->queue_num = hctx_idx;
+	clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
 
 	hctx->tags = set->tags[hctx_idx];
 
Signature · 1 line
2.53.0
author maintainer
#1380 lore raw

PATCH 1377/1536 drm/amdgpu: require _PR3 for BOCO

In reply to Greg Kroah-Hartman

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

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

From: Luigi Lauro <[email protected]>

[ Upstream commit 28f3d169f162ca7e803c5a1f7e1bb55bdc915d1c ]

amdgpu_device_supports_boco() returns true for an AMD_IS_PX device on a system with a hybrid ATPX method even when the device has no ACPI power resource (_PR3). On an APU mini PC with a discrete GPU attached over OCuLink, the iGPU's ATPX method reports hybrid graphics, the dGPU is flagged AMD_IS_PX, and runtime PM in auto mode picks BOCO:

amdgpu: ATPX Hybrid Graphics
amdgpu 0000:c6:00.0: Using BOCO for runtime pm

In BOCO mode the driver leaves powering the device off to the PCI core, which can only do it through _PR3 on the upstream bridge. No device on this dGPU's path has _PR3, so when it runtime suspends the card stays powered, with its fans at about 700 rpm.

Require has_pr3 for BOCO, as the function's description ("dGPU with ACPI power resources") says. The same card then picks BACO, which powers it down:

amdgpu 0000:c6:00.0: Using BACO for runtime pm

This only changes systems with a hybrid ATPX method and no _PR3 on the dGPU's upstream bridge, where BOCO cannot cut the power today. Tested on one such system only, an RX 9070 XT (Navi 48) over OCuLink with a Ryzen AI 9 HX 470, with the change backported to 7.2.9: the stock module logs "Using BOCO", the patched one "Using BACO"; BACO runtime suspend powers the card off and it resumes cleanly. Not tested on a hybrid laptop or a Thunderbolt eGPU.

Assisted-by Claude:claude-opus-5-5
(cherry picked from commit 1a039805354a44aab7abb2a6e685212d48b17a5e)
---
 drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +2 -4
index f022f8cc97306..a8f8bb342884f 100644
@@ -349,10 +349,8 @@ bool amdgpu_device_supports_boco(struct drm_device *dev)
 {
 	struct amdgpu_device *adev = drm_to_adev(dev);
 
-	if (adev->has_pr3 ||
-	    ((adev->flags & AMD_IS_PX) && amdgpu_is_atpx_hybrid()))
-		return true;
-	return false;
+	/* BOCO needs a platform power resource (_PR3) to cut the power */
+	return adev->has_pr3;
 }
 
 /**
Signature · 1 line
2.53.0
author maintainer
#1381 lore raw

PATCH 1378/1536 drm/amdgpu: reset CIK ASIC on Apple boards with VRAM at 0

In reply to Greg Kroah-Hartman

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

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

From: Maciej Kucharek <[email protected]>

[ Upstream commit 095f634ea0aa5b9da19495520b5fc1a155b2c137 ]

On MacBookPros with switchable graphics, the firmware puts VRAM at MC address 0 when the iGPU is enabled. A later post (S3 resume, GPU reset) moves VRAM back to the VBIOS default. The SI fix resets and posts the ASIC at load, so the driver uses the VBIOS layout from the start:

"drm/amdgpu: reset SI ASIC on MacBookPros with VRAM at 0"

No MacBookPro has a CIK GPU, and no affected CIK board is known. Add the same test to cik_need_reset_on_init(), so that SI, CIK and VI handle this firmware layout in the same way. gmc_v7_0 reads MC_VM_FB_LOCATION once at init and does not reprogram it. A CIK board with VRAM at 0 therefore has the same problem as the SI boards.

After the reset, FB_BASE is not 0, so the new test does not fire again on a module reload.

Only compile-tested.

Assisted-by Claude:claude-opus-5-5
(cherry picked from commit 6bb4b79d6a6c461b40750fd67cb4e2a070e20b67)
---
 drivers/gpu/drm/amd/amdgpu/cik.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/gpu/drm/amd/amdgpu/cik.c +10 -0
index 0a0114de11b49..46a0ba1900045 100644
@@ -1932,6 +1932,16 @@ static bool cik_need_reset_on_init(struct amdgpu_device *adev)
 {
 	u32 clock_cntl, pc;
 
+	/*
+	 * MacBookPros with switchable graphics put VRAM at 0 when the iGPU
+	 * is enabled.  Any later post (S3 resume, GPU reset) moves it back to
+	 * the vbios default, so reset and post on load to start with the
+	 * vbios layout.
+	 */
+	if (adev->pdev->subsystem_vendor == PCI_VENDOR_ID_APPLE &&
+	    !(RREG32(mmMC_VM_FB_LOCATION) & MC_VM_FB_LOCATION__FB_BASE_MASK))
+		return true;
+
 	if (adev->flags & AMD_IS_APU)
 		return false;
 
Signature · 1 line
2.53.0
author maintainer
#1382 lore raw

PATCH 1379/1536 drm/amdgpu: reset VI ASIC on Apple boards with VRAM at 0

In reply to Greg Kroah-Hartman

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

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

From: Maciej Kucharek <[email protected]>

[ Upstream commit 92a5184787b81e67f7b831ad860ca9b053505cf8 ]

On MacBookPros with switchable graphics, the firmware puts VRAM at MC address 0 when the iGPU is enabled. A later post (S3 resume, GPU reset) moves VRAM back to the VBIOS default. gmc_v8_0 reads MC_VM_FB_LOCATION once at init and reprograms it only on SR-IOV. On bare metal, the driver then keeps using the old layout.

vi_reset_quirks[] handles this for the MacBookPro14,3 by PCI ID:

commit b6b1d9721851 ("drm/amdgpu: reset VI ASIC on MacBookPro14,3")

Add the test that SI and CIK use: an Apple subsystem vendor and VRAM at
0. Other Polaris MacBookPros then get the same reset at load, for example the MacBookPro13,3 if its firmware leaves VRAM at 0. These boards are not tested.

Keep vi_reset_quirks[]. Its MacBookPro15,1 entries fix a different failure, a module reload after S3:

commit a5be7ad8f5f0 ("drm/amdgpu: reset VI ASIC on MacBookPro15,1")

VRAM is not at 0 at that point, so the new test may not cover it.

After the reset, FB_BASE is not 0, so the new test does not fire again on a module reload.

Only compile-tested.

Assisted-by Claude:claude-opus-5-5
(cherry picked from commit c2335b685b1e1e387f2fea1c67f56b5b8a8b6dc6)
---
 drivers/gpu/drm/amd/amdgpu/vi.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/gpu/drm/amd/amdgpu/vi.c +10 -0
index 0cab98957ca40..5d822a3c7e279 100644
@@ -1426,6 +1426,16 @@ static bool vi_need_reset_on_init(struct amdgpu_device *adev)
 	unsigned int i;
 	u32 clock_cntl, pc;
 
+	/*
+	 * MacBookPros with switchable graphics put VRAM at 0 when the iGPU
+	 * is enabled.  Any later post (S3 resume, GPU reset) moves it back to
+	 * the vbios default, so reset and post on load to start with the
+	 * vbios layout.
+	 */
+	if (adev->pdev->subsystem_vendor == PCI_VENDOR_ID_APPLE &&
+	    !(RREG32(mmMC_VM_FB_LOCATION) & MC_VM_FB_LOCATION__FB_BASE_MASK))
+		return true;
+
 	for (i = 0; i < ARRAY_SIZE(vi_reset_quirks); i++)
 		if (adev->pdev->device == vi_reset_quirks[i].device &&
 		    adev->pdev->subsystem_vendor == vi_reset_quirks[i].subsystem_vendor &&
Signature · 1 line
2.53.0
author maintainer
#1383 lore raw

PATCH 1380/1536 drm/amdkfd: fix doorbell allocation race creating duplicate allocations

In reply to Greg Kroah-Hartman

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

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

From: Henry Martin <[email protected]>

[ Upstream commit bebad45050945a3d668d6701fb77ae2571c5d44b ]

The check-and-allocate sequence on pdd->qpd.proc_doorbells is lockless at every call site of kfd_alloc_process_doorbells():
kfd_get_process_doorbells() (mmap of /dev/kfd), kfd_ioctl_create_queue() and the CRIU restore path each test the pointer under different locking (or none), so two racing threads can both observe NULL and each allocate a doorbell BO and bitmap, orphaning one allocation and handing the two mappings different backing pages.

Move the serialization into kfd_alloc_process_doorbells() itself, using a new per-process-device mutex so all three call sites are covered regardless of their own locking. The device-global kfd->doorbell_mutex is not suitable here: it is acquired under dqm->lock on the kernel-doorbell path (start_cpsch() -> pm_init() -> kq_initialize() -> kfd_get_kernel_doorbell()), so holding it across the sleeping allocations above would create a lock-ordering inversion with dqm->lock via TTM eviction, and it would also serialize doorbell setup of unrelated processes behind a device-wide lock for per-process state.

This issue was discovered by Tencent CodeBuddy Security.

v3 (Felix Kuehling):
- Removed unlocked check in kfd_get_process_doorbell flagged as problematic by Sashiko Bot. Fall back to the locked check inside kfd_alloc_process_doorbells
- Added missing mutex_destroy
v4 (Felix Kuehling):
- Removed unlocked checks around other kfd_alloc_process_doorbells calls

Fixes 16f0013157bf ("drm/amdkfd: Allocate doorbells only when needed")
(cherry picked from commit 4e27ba5ad5f76932d4f6cbacd25c81c2dd40ec4a)
---
 drivers/gpu/drm/amd/amdkfd/kfd_chardev.c  | 18 +++++++-----------
 drivers/gpu/drm/amd/amdkfd/kfd_doorbell.c | 23 +++++++++++++++++------
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h     |  3 +++
 drivers/gpu/drm/amd/amdkfd/kfd_process.c  |  2 ++
 4 files changed, 29 insertions(+), 17 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +7 -11
index 6aeda30797074..c556780fa6171 100644
@@ -353,12 +353,10 @@ static int kfd_ioctl_create_queue(struct file *filep, struct kfd_process *p,
 		}
 	}
 
-	if (!pdd->qpd.proc_doorbells) {
-		err = kfd_alloc_process_doorbells(dev->kfd, pdd);
-		if (err) {
-			pr_debug("failed to allocate process doorbells\n");
-			goto err_bind_process;
-		}
+	err = kfd_alloc_process_doorbells(dev->kfd, pdd);
+	if (err) {
+		pr_debug("failed to allocate process doorbells\n");
+		goto err_bind_process;
 	}
 
 	err = kfd_queue_acquire_buffers(pdd, &q_properties);
@@ -2289,11 +2287,9 @@ static int criu_restore_devices(struct kfd_process *p,
 			goto exit;
 		}
 
-		if (!pdd->qpd.proc_doorbells) {
-			ret = kfd_alloc_process_doorbells(dev->kfd, pdd);
-			if (ret)
-				goto exit;
-		}
+		ret = kfd_alloc_process_doorbells(dev->kfd, pdd);
+		if (ret)
+			goto exit;
 	}
 
 	/*
drivers/gpu/drm/amd/amdkfd/kfd_doorbell.c +17 -6
index fdcf7f2d1b5b4..6af268a031f22 100644
@@ -239,11 +239,9 @@ phys_addr_t kfd_get_process_doorbells(struct kfd_process_device *pdd)
 	struct amdgpu_device *adev = pdd->dev->adev;
 	uint32_t first_db_index;
 
-	if (!pdd->qpd.proc_doorbells) {
-		if (kfd_alloc_process_doorbells(pdd->dev->kfd, pdd))
-			/* phys_addr_t 0 is error */
-			return 0;
-	}
+	if (kfd_alloc_process_doorbells(pdd->dev->kfd, pdd))
+		/* phys_addr_t 0 is error */
+		return 0;
 
 	first_db_index = amdgpu_doorbell_index_on_bar(adev,
 						      pdd->qpd.proc_doorbells,
@@ -257,12 +255,21 @@ int kfd_alloc_process_doorbells(struct kfd_dev *kfd, struct kfd_process_device *
 	int r;
 	struct qcm_process_device *qpd = &pdd->qpd;
 
+	mutex_lock(&pdd->doorbell_mutex);
+
+	/* Another thread may have won the check-and-allocate race */
+	if (qpd->proc_doorbells) {
+		mutex_unlock(&pdd->doorbell_mutex);
+		return 0;
+	}
+
 	/* Allocate bitmap for dynamic doorbell allocation */
 	qpd->doorbell_bitmap = bitmap_zalloc(KFD_MAX_NUM_OF_QUEUES_PER_PROCESS,
 					     GFP_KERNEL);
 	if (!qpd->doorbell_bitmap) {
 		DRM_ERROR("Failed to allocate process doorbell bitmap\n");
-		return -ENOMEM;
+		r = -ENOMEM;
+		goto unlock;
 	}
 
 	r = init_doorbell_bitmap(&pdd->qpd, kfd);
@@ -284,11 +291,15 @@ int kfd_alloc_process_doorbells(struct kfd_dev *kfd, struct kfd_process_device *
 		DRM_ERROR("Failed to allocate process doorbells\n");
 		goto err;
 	}
+
+	mutex_unlock(&pdd->doorbell_mutex);
 	return 0;
 
 err:
 	bitmap_free(qpd->doorbell_bitmap);
 	qpd->doorbell_bitmap = NULL;
+unlock:
+	mutex_unlock(&pdd->doorbell_mutex);
 	return r;
 }
 
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +3 -0
index 939a6c92351b6..f8b880235e661 100644
@@ -766,6 +766,9 @@ struct kfd_process_device {
 	/* per-process-per device QCM data structure */
 	struct qcm_process_device qpd;
 
+	/* Serializes process doorbell allocation for this device */
+	struct mutex doorbell_mutex;
+
 	/*Apertures*/
 	uint64_t lds_base;
 	uint64_t lds_limit;
drivers/gpu/drm/amd/amdkfd/kfd_process.c +2 -0
index b9f00b756c509..9eca60c48483c 100644
@@ -1092,6 +1092,7 @@ static void kfd_process_destroy_pdds(struct kfd_process *p)
 		}
 
 		atomic_dec(&pdd->dev->kfd->kfd_processes_count);
+		mutex_destroy(&pdd->doorbell_mutex);
 
 		kfree(pdd);
 		p->pdds[i] = NULL;
@@ -1641,6 +1642,7 @@ struct kfd_process_device *kfd_create_process_device_data(struct kfd_node *dev,
 	pdd->dev = dev;
 	INIT_LIST_HEAD(&pdd->qpd.queues_list);
 	INIT_LIST_HEAD(&pdd->qpd.priv_queue_list);
+	mutex_init(&pdd->doorbell_mutex);
 	pdd->qpd.dqm = dev->dqm;
 	pdd->qpd.pqm = &p->pqm;
 	pdd->qpd.evicted = 0;
Signature · 1 line
2.53.0
author maintainer
#1384 lore raw

PATCH 1381/1536 drm/amd/display: dont WARN when removing an unallocated MST payload

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

[ Upstream commit b18a7c6d75bcc883b39497863cc88c9ef4c6c85f ]

[Why]
On an MST teardown that runs through the reset path (dcn31_reset_hw_ctx_wrap -> link_set_dpms_off -> deallocate_mst_payload), fill_dc_mst_payload_table_from_drm() is asked to remove a payload whose vcpi is not present in link->mst_stream_alloc_table and trips:

  WARNING: .../amdgpu_dm_helpers.c:275 fill_dc_mst_payload_table_from_drm

This is a legitimate case, not an error: deallocate_mst_payload() can be called for a stream whose MST payload was never programmed into DC's HW-maintained table (a new stream created for a modeset whose enable never completed, as already documented in deallocate_mst_payload()). There is simply nothing to remove.

[How]
Drop the ASSERT and fall through to the fill loop, which rebuilds the allocation table from the remaining entries. The table ends up unchanged, which is correct: the payload being removed was never in it.

Note the loop must not early-return here - the caller passes a zeroed proposed_table, so returning early would zero the whole link's table and drop the other MST streams sharing the link.

---
 drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_helpers.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_helpers.c +1 -1
index 9752548cc5b21..8e0ac3f236ab9 100644
@@ -194,7 +194,7 @@ fill_dc_mst_payload_table_from_drm(struct dc_link *link,
 				break;
 			}
 		}
-		ASSERT(i != copy_of_link_table.stream_count);
+		/* Payload absent from HW table when never allocated: nothing to remove. */
 	}
 
 	/* Fill payload info*/
Signature · 1 line
2.53.0
author maintainer
#1385 lore raw

PATCH 1382/1536 drm/amdgpu: reject ANONONLY userptrs that span multiple VMAs

In reply to Greg Kroah-Hartman

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

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

From: Jesse Zhang <[email protected]>

[ Upstream commit d577b68a854d0f590f480777249b041507d0708c ]

For AMDGPU_GEM_USERPTR_ANONONLY, amdgpu_ttm_tt_get_user_pages() only checks the VMA at the start of the range for a backing file, and amdgpu_hmm_range_get_pages() then faults in the whole range, across any other VMAs. The check used to reject ranges ending beyond the first VMA (vma->vm_end < end), which got lost when the code moved to HMM.

An ANONONLY userptr over one page of file-backed memory is rejected with -EPERM, but one over an anonymous page followed by the same file-backed page is accepted.

Restore the check and reject ANONONLY userptrs that cross more than one VMA. The second userptr is now rejected too.

v2: reject ranges spanning multiple VMAs instead of walking every VMA
(Christian)
v3: cast num_pages to u64 to avoid an overflow (Christian)

Fixes 6826cb3b92a3 ("drm/amdgpu: support userptr cross VMAs case with HMM")
Cc Christian König <[email protected]>
Cc Philip Yang <[email protected]>
Cc Felix Kuehling <[email protected]>
(cherry picked from commit 75d753ed4704d5efc72164d9e546b2a282e42ae2)
---
 drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c +2 -1
index 93da39a5ce492..b2a90c5168401 100644
@@ -753,7 +753,8 @@ int amdgpu_ttm_tt_get_user_pages(struct amdgpu_bo *bo, struct page **pages,
 		goto out_unlock;
 	}
 	if (unlikely((gtt->userflags & AMDGPU_GEM_USERPTR_ANONONLY) &&
-		vma->vm_file)) {
+		     (vma->vm_file ||
+		      vma->vm_end < start + (u64)ttm->num_pages * PAGE_SIZE))) {
 		r = -EPERM;
 		goto out_unlock;
 	}
Signature · 1 line
2.53.0
author maintainer
#1386 lore raw

PATCH 1383/1536 drm/amdkfd: dont drop an SVM CWSR reference that was never taken

In reply to Greg Kroah-Hartman

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

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

From: Jesse Zhang <[email protected]>

[ Upstream commit 030d47cc6720e0f07b502876cdbd266e309f9461 ]

When kfd_queue_acquire_buffers() fails, its error path calls kfd_queue_release_buffers(), which also drops a queue_refcount on the SVM range at ctx_save_restore_area_address. The SVM range is the last buffer acquired, and kfd_queue_buffer_svm_get() takes no reference when it fails, so on every error path this reference was never taken. If another queue of the process uses that CWSR range, its reference is dropped instead, and unmapping the range no longer evicts that queue while its CWSR area is unmapped from the GPU.

On navi31, with queue A using an SVM CWSR range: munmap() of the range logs

Freeing queue vital buffer 0x..., queue evicted

but after a CREATE_QUEUE that reuses A's CWSR address with an unmapped write pointer (-EINVAL), the same munmap() leaves A running without the message.

Only put the BOs on the acquire error path. The warning and the eviction are back after the failed CREATE_QUEUE.

Fixes b049504e211e ("drm/amdkfd: Validate user queue svm memory residency")
(cherry picked from commit 9a08122e6361ef73f4b512d5db9596d561305519)
---
 drivers/gpu/drm/amd/amdkfd/kfd_queue.c | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_queue.c +17 -6
index 3efbe67734877..e64eba0a92631 100644
@@ -231,6 +231,15 @@ void kfd_queue_buffer_put(struct amdgpu_bo **bo)
 	amdgpu_bo_unref(bo);
 }
 
+static void kfd_queue_put_bos(struct queue_properties *properties)
+{
+	kfd_queue_buffer_put(&properties->wptr_bo);
+	kfd_queue_buffer_put(&properties->rptr_bo);
+	kfd_queue_buffer_put(&properties->ring_bo);
+	kfd_queue_buffer_put(&properties->eop_buf_bo);
+	kfd_queue_buffer_put(&properties->cwsr_bo);
+}
+
 int kfd_queue_acquire_buffers(struct kfd_process_device *pdd, struct queue_properties *properties)
 {
 	struct kfd_topology_device *topo_dev;
@@ -341,7 +350,13 @@ int kfd_queue_acquire_buffers(struct kfd_process_device *pdd, struct queue_prope
 	 * dropping the VM reservation.
 	 */
 	kfd_queue_unref_bo_vas(pdd, properties);
-	kfd_queue_release_buffers(pdd, properties);
+	/*
+	 * The SVM CWSR range is the last thing acquired and a failed
+	 * kfd_queue_buffer_svm_get() takes nothing, so only the BOs are held
+	 * here. Dropping the SVM reference would drop the one of another queue
+	 * using the same CWSR address.
+	 */
+	kfd_queue_put_bos(properties);
 	return err;
 }
 
@@ -350,11 +365,7 @@ int kfd_queue_release_buffers(struct kfd_process_device *pdd, struct queue_prope
 	struct kfd_topology_device *topo_dev;
 	u64 total_cwsr_size;
 
-	kfd_queue_buffer_put(&properties->wptr_bo);
-	kfd_queue_buffer_put(&properties->rptr_bo);
-	kfd_queue_buffer_put(&properties->ring_bo);
-	kfd_queue_buffer_put(&properties->eop_buf_bo);
-	kfd_queue_buffer_put(&properties->cwsr_bo);
+	kfd_queue_put_bos(properties);
 
 	topo_dev = kfd_topology_device_by_id(pdd->dev->id);
 	if (!topo_dev)
Signature · 1 line
2.53.0
author maintainer
#1387 lore raw

PATCH 1384/1536 drm/amd/display: Fix swap in median3() for DSC rate control

In reply to Greg Kroah-Hartman

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

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

From: Keita Morisaki <[email protected]>

[ Upstream commit 7b23bf82ccbdb4cf0752f2b8686e7319a7ce497f ]

median3() is meant to return the median of three values, but its last compare-and-swap step swaps b and c instead of a and b. When c is smaller than both a and b, it returns max(a, b) instead of min(a, b). For example, median3(2, 3, 1) returns 3 instead of 2.

_do_calc_rc_params() always passes 0 as the first argument, and the second argument is never below 12. So whenever the third argument is negative, first_line_bpg_offset (and second_line_bpg_offset for 4:2:0) is set to the second argument instead of 0.

Fix this by swapping a and b in the last step, as intended.

Note that this change does not affect valid DSC configurations. The third argument is negative only when bits per pixel exceeds the uncompressed rate of the colour format:

- 3 * bpc for 4:4:4, 3 * bpc + 2 for RGB

- 2 * bpc for 4:2:2

- 1.5 * bpc for 4:2:0

Fixes 97bda0322b8a ("drm/amd/display: Add DSC support for Navi (v2)")
(cherry picked from commit 1ddc4bc97a62fc89d9d3681413d9f977e1fa1a83)
---
 drivers/gpu/drm/amd/display/dc/dml/dsc/rc_calc_fpu.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/amd/display/dc/dml/dsc/rc_calc_fpu.c +1 -1
index ef75eb7d5adc3..940de620e3308 100644
@@ -46,7 +46,7 @@ static int median3(int a, int b, int c)
 	if (b > c)
 		swap(b, c);
 	if (a > b)
-		swap(b, c);
+		swap(a, b);
 
 	return b;
 }
Signature · 1 line
2.53.0
author maintainer
#1388 lore raw

PATCH 1385/1536 drm/amdkfd: wait for a GPU reset before freeing a BO

In reply to Greg Kroah-Hartman

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

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

From: William Palacek <[email protected]>

[ Upstream commit 47d799a718439764432d8ef3a0952af45f025f76 ]

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

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

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

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

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

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

PATCH 1386/1536 ipv6: remove ifaddr from hash during ifdown list cleanup

In reply to Greg Kroah-Hartman

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

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

From: Daehyeon Ko <[email protected]>

[ Upstream commit 6ace56ed7b13a9c6d4cb7ef0d82d3a3d53324a63 ]

addrconf_ifdown() clears the address hash before snapshotting the per-device address list. A concurrent ipv6_add_addr() can publish an address after the hash scan and before the list snapshot.

The ifdown path then removes the address from the device list and drops the list-owned reference while it is still linked in the hash. Once the remaining references are released, inet6_ifa_finish_destroy() warns, but a DEAD address continues to kfree_rcu(). The hash therefore points to freed memory that later RCU walkers can dereference.

This follow-on was found by source review and was not separately triggered at runtime.

Remove each non-kept address from the hash immediately before removing it from the per-device list. Keeping it hashed through the delete notification blocks same-address publication until NETDEV_DOWN has been delivered. hlist_del_init_rcu() is safe when the earlier hash scan already removed the address.

This handles a late publisher captured by the list snapshot. The next change serializes publication with teardown so an add cannot miss both observations. Both changes are required when backporting the complete fix.

---
 net/ipv6/addrconf.c | 4 ++++
 1 file changed, 4 insertions(+)
net/ipv6/addrconf.c +4 -0
index 33439672b071b..d7865f915d25d 100644
@@ -4025,6 +4025,10 @@ static int addrconf_ifdown(struct net_device *dev, bool unregister)
 		}
 
 		if (!keep) {
+			spin_lock_bh(&net->ipv6.addrconf_hash_lock);
+			hlist_del_init_rcu(&ifa->addr_lst);
+			spin_unlock_bh(&net->ipv6.addrconf_hash_lock);
+
 			write_lock_bh(&idev->lock);
 			list_del_rcu(&ifa->if_list);
 			write_unlock_bh(&idev->lock);
Signature · 1 line
2.53.0
author maintainer
#1390 lore raw

PATCH 1387/1536 ipv6: serialize address publication with device teardown

In reply to Greg Kroah-Hartman

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

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

From: Daehyeon Ko <[email protected]>

[ Upstream commit 06227034e2d93942119b922cf05f2de9da0ad848 ]

ipv6_add_addr() checks idev state before allocating an ifaddr, but publishes the object later. addrconf_ifdown() can mark and detach the idev between the check and publication.

This happens when a non-loopback device MTU falls below IPV6_MIN_MTU. A forced interleaving published an address on a dead idev, and ipv6_get_ifaddr() still returned it after teardown. Later device deletion remained blocked with:

unregister_netdevice: waiting for ac0 to become free. Usage count = 3

Protect the dead indication with idev->lock and keep that lock across both hash and device-list publication. Recheck dead before publishing; if teardown wins the lock, reject the unpublished object.

Non-unregister teardown does not set dead. The preceding change covers an add that misses the initial hash scan but reaches the per-device list snapshot. Both changes are required when backporting this fix.

---
 net/ipv6/addrconf.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
net/ipv6/addrconf.c +9 -3
index d7865f915d25d..d6474f3ea114a 100644
@@ -1161,14 +1161,18 @@ ipv6_add_addr(struct inet6_dev *idev, struct ifa6_config *cfg,
 
 	rcu_read_lock();
 
-	err = ipv6_add_addr_hash(idev->dev, ifa);
+	write_lock_bh(&idev->lock);
+
+	if (idev->dead)
+		err = -ENODEV;
+	else
+		err = ipv6_add_addr_hash(idev->dev, ifa);
 	if (err < 0) {
+		write_unlock_bh(&idev->lock);
 		rcu_read_unlock();
 		goto out;
 	}
 
-	write_lock_bh(&idev->lock);
-
 	/* Add to inet6_dev unicast addr list. */
 	ipv6_link_dev_addr(idev, ifa);
 
@@ -3903,7 +3907,9 @@ static int addrconf_ifdown(struct net_device *dev, bool unregister)
 	 *	   Do not dev_put!
 	 */
 	if (unregister) {
+		write_lock_bh(&idev->lock);
 		WRITE_ONCE(idev->dead, 1);
+		write_unlock_bh(&idev->lock);
 
 		/* protected by rtnl_lock */
 		RCU_INIT_POINTER(dev->ip6_ptr, NULL);
Signature · 1 line
2.53.0
author maintainer
#1391 lore raw

PATCH 1388/1536 ipv6: initialize temporary ifaddr before publication

In reply to Greg Kroah-Hartman

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

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

From: Daehyeon Ko <[email protected]>

[ Upstream commit ed7f278812e540db507f683e5bf9b6d0a1f5bc1e ]

ipv6_create_tempaddr() holds a reference to the public ifaddr, publishes the new temporary address through ipv6_add_addr(), and only then stores the reference and final timestamps.

addrconf_ifdown() can remove the temporary address before ifpub is stored, leaking the public ifaddr reference. Publishing ifpub alone is
insufficient: manage_tempaddrs() can then find the object before cstamp and tstamp are final, update its lifetimes, and have the constructor overwrite its timestamp with an older value.

This follow-on was found by source review and was not separately triggered at runtime.

Pass the public ifaddr and both timestamps in ifa6_config. Initialize all three fields before adding the temporary address to either the hash or per-device lists. On success the existing public-ifaddr reference transfers to the temporary object. On error it remains owned and released by ipv6_create_tempaddr().

---
 include/net/addrconf.h |  3 +++
 net/ipv6/addrconf.c    | 20 +++++++++++++-------
 2 files changed, 16 insertions(+), 7 deletions(-)
include/net/addrconf.h +3 -0
index e7dc5175e236d..427a9aabf2200 100644
@@ -80,6 +80,9 @@ struct ifa6_config {
 	u8			ifa_proto;
 
 	const struct in6_addr	*peer_pfx;
+	struct inet6_ifaddr	*ifpub;
+	unsigned long		cstamp;
+	unsigned long		tstamp;
 
 	u32			rt_priority;
 	u32			ifa_flags;
net/ipv6/addrconf.c +13 -7
index d6474f3ea114a..231ec5e7f2fdf 100644
@@ -1148,10 +1148,19 @@ ipv6_add_addr(struct inet6_dev *idev, struct ifa6_config *cfg,
 		ifa->flags |= IFA_F_TENTATIVE;
 	ifa->valid_lft = cfg->valid_lft;
 	ifa->prefered_lft = cfg->preferred_lft;
-	ifa->cstamp = ifa->tstamp = jiffies;
 	ifa->tokenized = false;
 
 	ifa->rt = f6i;
+	ifa->ifpub = cfg->ifpub;
+	if (cfg->ifpub) {
+		ifa->cstamp = cfg->cstamp;
+		ifa->tstamp = cfg->tstamp;
+	} else {
+		unsigned long now = jiffies;
+
+		ifa->cstamp = now;
+		ifa->tstamp = now;
+	}
 
 	ifa->idev = idev;
 	in6_dev_hold(idev);
@@ -1484,6 +1493,9 @@ static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, bool block)
 
 	cfg.pfx = &addr;
 	cfg.scope = ipv6_addr_scope(cfg.pfx);
+	cfg.ifpub = ifp;
+	cfg.cstamp = now;
+	cfg.tstamp = tmp_tstamp;
 
 	ift = ipv6_add_addr(idev, &cfg, block, NULL);
 	if (IS_ERR(ift)) {
@@ -1494,12 +1506,6 @@ static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, bool block)
 		goto retry;
 	}
 
-	spin_lock_bh(&ift->lock);
-	ift->ifpub = ifp;
-	ift->cstamp = now;
-	ift->tstamp = tmp_tstamp;
-	spin_unlock_bh(&ift->lock);
-
 	addrconf_dad_start(ift);
 	in6_ifa_put(ift);
 	in6_dev_put(idev);
Signature · 1 line
2.53.0
author maintainer
#1392 lore raw

PATCH 1389/1536 ipv6: do not restart DAD for a dead ifaddr

In reply to Greg Kroah-Hartman

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

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

From: Daehyeon Ko <[email protected]>

[ Upstream commit ffb668669ce4144347973d8b2fad449e9be0563d ]

addrconf_dad_failure() can create a stable-privacy replacement without RTNL. After ipv6_add_addr() publishes it, addrconf_ifdown() can mark the new ifaddr DEAD, clear its route, and unlink it before the recovery path takes ifp2->lock.

The recovery path then unconditionally changes the state back to PREDAD and queues delayed DAD work. The MTU teardown path can leave IF_READY set. For an optimistic address, addrconf_dad_begin() can consequently pass the cleared NULL route to ip6_ins_rt().

This follow-on was found by source review and was not separately triggered at runtime.

The new ifaddr is already initialized in PREDAD. Under ifp2->lock, record the retry and queue DAD only if teardown has not changed the state to DEAD. If teardown wins after this check, the work observes DEAD and exits without reviving the address.

This complements the existing lock_errdad check that preserves the original ifaddr's DEAD state after the same function reacquires its lock.

---
 net/ipv6/addrconf.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
net/ipv6/addrconf.c +7 -3
index 231ec5e7f2fdf..eb32a00978447 100644
@@ -2191,6 +2191,7 @@ void addrconf_dad_failure(struct sk_buff *skb, struct inet6_ifaddr *ifp)
 			     ifp->idev->dev->name, &ifp->addr, eth_hdr(skb)->h_source);
 
 	if (ifp->flags & IFA_F_STABLE_PRIVACY) {
+		bool start_dad = false;
 		struct in6_addr new_addr;
 		struct inet6_ifaddr *ifp2;
 		int retries = ifp->stable_privacy_retry + 1;
@@ -2229,11 +2230,14 @@ void addrconf_dad_failure(struct sk_buff *skb, struct inet6_ifaddr *ifp)
 			goto lock_errdad;
 
 		spin_lock_bh(&ifp2->lock);
-		ifp2->stable_privacy_retry = retries;
-		ifp2->state = INET6_IFADDR_STATE_PREDAD;
+		if (ifp2->state != INET6_IFADDR_STATE_DEAD) {
+			ifp2->stable_privacy_retry = retries;
+			start_dad = true;
+		}
 		spin_unlock_bh(&ifp2->lock);
 
-		addrconf_mod_dad_work(ifp2, net->ipv6.sysctl.idgen_delay);
+		if (start_dad)
+			addrconf_mod_dad_work(ifp2, net->ipv6.sysctl.idgen_delay);
 		in6_ifa_put(ifp2);
 lock_errdad:
 		spin_lock_bh(&ifp->lock);
Signature · 1 line
2.53.0
author maintainer
#1393 lore raw

PATCH 1390/1536 fbdev: bitblit: Fix glyph clipping when fbcon pans

In reply to Greg Kroah-Hartman

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

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

From: Tingjie Zhong <[email protected]>

[ Upstream commit 06fccf840640d8f6b0e08a1756f8d2f0435b4cbe ]

Commit 3637d34b35b2 ("fbdev: Add bounds checking in bit_putcs to fix vmalloc-out-of-bounds") made bit_putcs() clip glyphs to var.yres. When fbcon scrolls by panning, it draws text rows up to var.yres_virtual, so after the first pan most new text is not drawn until the next full redraw. This affects fbdev drivers that set FBINFO_HWACCEL_YPAN or FBINFO_HWACCEL_YWRAP, such as vesafb with the ypan option, when CONFIG_FRAMEBUFFER_CONSOLE_LEGACY_ACCELERATION=y.

Clip to GETVYRES() instead, which fbcon_ud.c and fbcon_ccw.c already use as the drawing area height. When fbcon does not pan, GETVYRES() returns var.yres, keeping the existing bound. When fbcon pans, it returns var.yres_virtual, which the framebuffer memory must cover anyway for panning to work.

---
 drivers/video/fbdev/core/bitblit.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/video/fbdev/core/bitblit.c +5 -2
index 8f6a2d1736d39..86ae7a7252d21 100644
@@ -18,6 +18,7 @@
 #include <linux/console.h>
 #include <asm/types.h>
 #include "fbcon.h"
+#include "fbcon_rotate.h"
 
 /*
  * Accelerated handlers.
@@ -151,7 +152,9 @@ static void bit_putcs(struct vc_data *vc, struct fb_info *info,
 		      const unsigned short *s, int count, int yy, int xx,
 		      int fg, int bg)
 {
+	struct fbcon_par *par = info->fbcon_par;
 	struct fb_image image;
+	u32 vyres = GETVYRES(par->p, info);
 	u32 width = DIV_ROUND_UP(vc->vc_font.width, 8);
 	u32 cellsize = width * vc->vc_font.height;
 	u32 maxcnt = info->pixmap.size/cellsize;
@@ -168,10 +171,10 @@ static void bit_putcs(struct vc_data *vc, struct fb_info *info,
 	image.height = vc->vc_font.height;
 	image.depth = 1;
 
-	if (image.dy >= info->var.yres)
+	if (image.dy >= vyres)
 		return;
 
-	image.height = min(image.height, info->var.yres - image.dy);
+	image.height = min(image.height, vyres - image.dy);
 
 	if (attribute) {
 		buf = kmalloc(cellsize, GFP_ATOMIC);
Signature · 1 line
2.53.0
author maintainer
#1394 lore raw

PATCH 1391/1536 PCI: qcom-ep: Deinitialize endpoint on remove

In reply to Greg Kroah-Hartman

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

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

From: Guangshuo Li <[email protected]>

[ Upstream commit ed1d71e41c7b2e755e0ef8e9af9cab9b6b185c4b ]

qcom_pcie_ep_probe() initializes the DesignWare PCIe endpoint with dw_pcie_ep_init(). The probe failure paths call dw_pcie_ep_deinit() to release the corresponding endpoint resources, but the remove path does not perform the matching teardown after a successful probe.

As a result, resources initialized by the DesignWare endpoint core can remain allocated when the endpoint controller is removed.

Notify endpoint functions about EPC deinitialization and call dw_pcie_ep_deinit() before disabling the controller resources. Keep the existing early return when the link is already disabled since Qualcomm endpoint controllers depend on the host refclk for hardware cleanup.

This issue was found by manual code inspection.

Fixes f55fee56a631 ("PCI: qcom-ep: Add Qualcomm PCIe Endpoint controller driver")
---
 drivers/pci/controller/dwc/pcie-qcom-ep.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/pci/controller/dwc/pcie-qcom-ep.c +2 -0
index b5ca5260f9049..413198e5e1dfd 100644
@@ -919,6 +919,8 @@ static void qcom_pcie_ep_remove(struct platform_device *pdev)
 
 	if (pcie_ep->link_status == QCOM_PCIE_EP_LINK_DISABLED)
 		return;
+	pci_epc_deinit_notify(pcie_ep->pci.ep.epc);
+	dw_pcie_ep_deinit(&pcie_ep->pci.ep);
 
 	qcom_pcie_disable_resources(pcie_ep);
 }
Signature · 1 line
2.53.0
author maintainer
#1395 lore raw

PATCH 1392/1536 net/rds: ib: dont enable IRQs in rds_ib_conn_free()

In reply to Greg Kroah-Hartman

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

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

From: Nguyen Ngoc Thang <[email protected]>

[ Upstream commit f6fa1d60ec3ceb7e6c26aa91eadfef34f94014e1 ]

__rds_conn_create() calls trans->conn_free() with rds_conn_lock held and IRQs disabled when it loses the race to insert a connection. rds_ib_conn_free() takes the device list lock with spin_lock_irq() and releases it with spin_unlock_irq(), so IRQs are turned on while rds_conn_lock is still held:

raw_local_irq_restore() called with IRQs enabled

  WARNING: kernel/locking/irqflag-debug.c:10 at warn_bogus_irq_restore+0xc/0x20
   _raw_spin_unlock_irqrestore+0x67/0x80
   __rds_conn_create+0x1de5/0x2290
   rds_conn_create_outgoing+0x43/0x60
   rds_sendmsg+0xfca/0x20e0
   __sys_sendto+0x408/0x5a0

It needs an RDS socket bound to an address on an RDMA device (e.g. rxe) and two concurrent sendto() calls to the same new destination.

The TCP and loopback ->conn_free() callbacks already use irqsave, so do the same here.

Fixes 745cbccac3fe ("RDS: Rewrite connection cleanup, fixing oops on rmmod")
Reported-by [email protected]
---
 net/rds/ib_cm.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
net/rds/ib_cm.c +4 -2
index 1c6e3b3f39d00..c8771aa7df53a 100644
@@ -1271,6 +1271,7 @@ void rds_ib_conn_free(void *arg)
 {
 	struct rds_ib_connection *ic = arg;
 	spinlock_t	*lock_ptr;
+	unsigned long flags;
 
 	rdsdebug("ic %p\n", ic);
 
@@ -1281,9 +1282,10 @@ void rds_ib_conn_free(void *arg)
 	 */
 	lock_ptr = ic->rds_ibdev ? &ic->rds_ibdev->spinlock : &ib_nodev_conns_lock;
 
-	spin_lock_irq(lock_ptr);
+	/* May be called with IRQs already disabled (see __rds_conn_create()) */
+	spin_lock_irqsave(lock_ptr, flags);
 	list_del(&ic->ib_node);
-	spin_unlock_irq(lock_ptr);
+	spin_unlock_irqrestore(lock_ptr, flags);
 
 	rds_ib_recv_free_caches(ic);
 
Signature · 1 line
2.53.0
author maintainer
#1396 lore raw

PATCH 1393/1536 net: unix: reject negative max_dgram_qlen values

In reply to Greg Kroah-Hartman

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

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

From: Yingjie Wang <[email protected]>

[ Upstream commit 1a4e7bc6e3457ad95515a9d2c042452c3161bb2c ]

net.unix.max_dgram_qlen is parsed as a signed int and copied to the u32 sock::sk_max_ack_backlog when an AF_UNIX socket is created. Consequently, a negative value such as -1 is accepted and converted to UINT_MAX. Since the receive queue length is also u32, its fullness check cannot become true for that limit.

max_dgram_qlen has no documented negative sentinel. Its existing signed interface represents nonnegative values only through INT_MAX; negative bit patterns are not a supported encoding for the upper half of the u32 consumer range.

Switch to proc_dointvec_minmax and make the established 0..INT_MAX input range explicit. This rejects negative values without adding new accepted values or changing the default and zero-value behavior. Very large valid values can still make the queue limit impractical to reach; this change corrects the input domain rather than imposing a new resource ceiling.

---
 Documentation/networking/ip-sysctl.rst | 3 ++-
 net/unix/sysctl_net_unix.c             | 4 +++-
 2 files changed, 5 insertions(+), 2 deletions(-)
Documentation/networking/ip-sysctl.rst +2 -1
index eb2c136be63da..9e3da2008c412 100644
@@ -3300,5 +3300,6 @@ l3mdev_accept - BOOLEAN
 max_dgram_qlen - INTEGER
 	The maximum length of dgram socket receive queue
 
-	Default: 10
+	Possible values: 0 - INT_MAX
 
+	Default: 10
net/unix/sysctl_net_unix.c +3 -1
index 357b3e5f38472..cdd75f68267cc 100644
@@ -17,7 +17,9 @@ static struct ctl_table unix_table[] = {
 		.data		= &init_net.unx.sysctl_max_dgram_qlen,
 		.maxlen		= sizeof(int),
 		.mode		= 0644,
-		.proc_handler	= proc_dointvec
+		.proc_handler	= proc_dointvec_minmax,
+		.extra1		= SYSCTL_ZERO,
+		.extra2		= SYSCTL_INT_MAX,
 	},
 };
 
Signature · 1 line
2.53.0
author maintainer
#1397 lore raw

PATCH 1394/1536 net/smc: queue the copied chunk when smc_tx_sendmsg() faults

In reply to Greg Kroah-Hartman

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

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

From: Bryam Vargas <[email protected]>

[ Upstream commit c0703534b223a5c6993e0f000fd1c3abe621fb65 ]

When a send wraps the end of the send buffer, smc_tx_sendmsg() copies the data in two chunks. If memcpy_from_msg() faults on the second one, smc_tx_sendmsg() returns send_done, which already counts the first chunk, but leaves tx_curs_prep and sndbuf_space as they were. send() reports bytes the peer never receives, and the next send() overwrites them. Any caller can hit this on its own stream with a buffer whose tail is unreadable.

On a fault in the second chunk, queue the first one. The next pass retries the rest and returns send_done if it faults again, so send() reports only what it queued, as TCP does.

---
 net/smc/smc_tx.c | 7 +++++++
 1 file changed, 7 insertions(+)
net/smc/smc_tx.c +7 -0
index 214ac3cbcf9ad..8e0a40ae74bac 100644
@@ -249,6 +249,13 @@ int smc_tx_sendmsg(struct smc_sock *smc, struct msghdr *msg, size_t len)
 			rc = memcpy_from_msg(sndbuf_base + chunk_off,
 					     msg, chunk_len);
 			if (rc) {
+				if (chunk) {
+					/* send_done counts the first chunk:
+					 * queue it and retry the rest
+					 */
+					copylen -= chunk_len;
+					break;
+				}
 				smc_sndbuf_sync_sg_for_device(conn);
 				if (send_done)
 					return send_done;
Signature · 1 line
2.53.0
author maintainer
#1398 lore raw

PATCH 1395/1536 alpha: determine tininess after rounding in the FP emulation

In reply to Greg Kroah-Hartman

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

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

From: Matt Turner <[email protected]>

[ Upstream commit b74843b38da8f1186fd7d447646c835b47096a15 ]

IEEE 754 lets an architecture determine tininess of a floating-point result either before or after rounding, but requires the same choice for every operation. Alpha determines it after rounding, and stdlib's tst-tininess confirms the hardware does so for the results it produces itself.

The soft-fp emulation has no notion of the distinction and always determines tininess before rounding, so a result that the hardware would not consider tiny is reported as underflowing whenever the instruction happens to trap for software completion. The two paths then disagree on the same machine. A multiply of the largest subnormal double by 1 + 2^-52 rounds up to the smallest normal and raises no underflow when the operands are normal, but raises it when an operand is subnormal and the instruction traps:

glibc math testsuite, test-float32x-float64-mul:
Failure: mul_double (0x3.ffffffffffffcp-1024, 0x1.0000000000001p+0):
Exception "Underflow" set

Add _FP_TININESS_AFTER_ROUNDING, as glibc's copy of soft-fp has, and set it for alpha. It determines tininess by rounding a copy of the result as if the exponent range were unbounded, which is what the definition asks for. A plain check of whether the rounded result came out normal is not
equivalent: it differs for values that are still tiny once rounded with an unbounded exponent range but reach the smallest normal on the coarser subnormal grid. That plain check is what the hardware itself does (it decides tininess from the delivered result), and it is why a divide such as -0x4p-128 / 0x1.000002p+0 in FE_DOWNWARD delivers -0x1p-126 and raises nothing although the result is tiny after rounding. Such cases do not trap, so the emulation never sees them; where it does get control, it follows the definition rather than reproducing that deviation, which is what glibc's soft-fp does as well.

The macro defaults to zero, so powerpc, sh and sparc keep determining tininess before rounding as they do now.

---
 arch/alpha/include/asm/sfp-machine.h |  4 ++++
 include/math-emu/op-common.h         | 23 +++++++++++++++++++++--
 include/math-emu/soft-fp.h           |  8 ++++++++
 3 files changed, 33 insertions(+), 2 deletions(-)
arch/alpha/include/asm/sfp-machine.h +4 -0
index 5fe63afbd474f..bff1ad963c689 100644
@@ -59,6 +59,10 @@
     R##_c = FP_CLS_NAN;						\
   } while (0)
 
+/* Alpha determines tininess after rounding, so the emulation must do the
+   same as the hardware does for the results it produces itself.  */
+#define _FP_TININESS_AFTER_ROUNDING	1
+
 /* Obtain the current rounding mode. */
 #define FP_ROUNDMODE	mode
 #define FP_RND_NEAREST	(FPCR_DYN_NORMAL >> FPCR_DYN_SHIFT)
include/math-emu/op-common.h +21 -2
index 8ce066c035cfa..1d1ce5c08efcf 100644
@@ -135,6 +135,24 @@ do {								\
     else							\
       {								\
 	/* we've got a denormalized number */			\
+	int _FP_PACK_CANONICAL_is_tiny = 1;			\
+	if (_FP_TININESS_AFTER_ROUNDING && X##_e == 0)		\
+	  {							\
+	    /* Architectures that detect tininess after rounding	\
+	       only signal underflow if the result is still		\
+	       subnormal once rounded as if the exponent range	\
+	       were unbounded.  Round a copy to find out.  */	\
+	    FP_DECL_##fs(_FP_PACK_CANONICAL_T);			\
+	    /* The class field is not used by the rounding below,	\
+	       and is unused entirely where this block is dead.  */	\
+	    (void)_FP_PACK_CANONICAL_T##_c;			\
+	    _FP_FRAC_COPY_##wc(_FP_PACK_CANONICAL_T, X);	\
+	    _FP_PACK_CANONICAL_T##_s = X##_s;			\
+	    _FP_PACK_CANONICAL_T##_e = X##_e;			\
+	    _FP_ROUND(wc, _FP_PACK_CANONICAL_T);		\
+	    if (_FP_FRAC_OVERP_##wc(fs, _FP_PACK_CANONICAL_T))	\
+	      _FP_PACK_CANONICAL_is_tiny = 0;			\
+	  }							\
 	X##_e = -X##_e + 1;					\
 	if (X##_e <= _FP_WFRACBITS_##fs)			\
 	  {							\
@@ -161,8 +179,9 @@ do {								\
 		    _FP_FRAC_SRL_##wc(X, _FP_WORKBITS);		\
 		  }						\
 	      }							\
-	    if ((FP_CUR_EXCEPTIONS & FP_EX_INEXACT) ||		\
-		(FP_TRAPPING_EXCEPTIONS & FP_EX_UNDERFLOW))	\
+	    if (_FP_PACK_CANONICAL_is_tiny			\
+		&& ((FP_CUR_EXCEPTIONS & FP_EX_INEXACT) ||	\
+		    (FP_TRAPPING_EXCEPTIONS & FP_EX_UNDERFLOW)))	\
 		FP_SET_EXCEPTION(FP_EX_UNDERFLOW);		\
 	  }							\
 	else							\
include/math-emu/soft-fp.h +8 -0
index 5650c16283830..02ada0a9fca16 100644
@@ -31,6 +31,14 @@
 #include <endian.h>
 #endif
 
+/* Whether the architecture determines tininess of a floating-point
+   result after rounding rather than before it.  IEEE 754 permits either
+   but requires the same choice for every operation, so this has to agree
+   with what the hardware does for the results it produces itself.  */
+#ifndef _FP_TININESS_AFTER_ROUNDING
+#define _FP_TININESS_AFTER_ROUNDING	0
+#endif
+
 #define _FP_WORKBITS		3
 #define _FP_WORK_LSB		((_FP_W_TYPE)1 << 3)
 #define _FP_WORK_ROUND		((_FP_W_TYPE)1 << 2)
Signature · 1 line
2.53.0
author maintainer
#1399 lore raw

PATCH 1396/1536 ocfs2: reserve metadata for a new xattr block and its value tree

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit 8ad5fa0c11246d260d7b12c9672e604b1f431b2e ]

Patch series "ocfs2: fix metadata reservation for xattr value trees".

ocfs2_calc_xattr_set_need() reserves too little metadata for a new xattr value's extent tree on three paths. The reservation cannot be topped up once the transaction has started, so ocfs2_add_clusters_in_btree() gives up with RESTART_META when the value root fills and nothing is left. ocfs2_xattr_extend_allocation() turns that into -ENOSPC, after ocfs2_xa_cleanup_value_truncate() has dropped the entry and leaked the clusters already handed out; before commit 0cdc7dde00ec ("ocfs2: fix missing metadata reservation for large xattrs") it was a BUG_ON() instead. It takes a fragmented cluster allocator to get there, since the first extent always fits in the root.

Patch 1 fixes the create side of meta_guess: commit 3ed2be719eb9 ("ocfs2:
allow for more than one data extent when creating xattr") replaced the block reserved for the new xattr block with the two the value tree needs instead of adding them together.

Patch 2 fixes the arm that moves an xattr back into the inode, which charges credits for a value tree but no metadata for one.

Patch 3 drops a second copy of the same reservation on the path that falls through to meta_guess. That one is cleanup rather than a fix and is not for stable, and it must not be backported without patch 1: the duplicate it removes is what currently covers the shortfall patch 1 fixes.

This patch (of 3):

The create side of meta_guess in ocfs2_calc_xattr_set_need() reserves metadata for the new value's extent tree and nothing for the xattr block that will hold it:

        } else {
                credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS;
                if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE) {
                        struct ocfs2_extent_list *el = &def_xv.xv.xr_list;
                        meta_add += ocfs2_extend_meta_needed(el);
                        ...

Commit 3ed2be719eb9 ("ocfs2: allow for more than one data extent when creating xattr") meant to add that tree on top of the meta_add += 1 the branch already had, but it moved the 1 into the else arm instead, so the external-value case lost it. The 1 is not optional: it is what ocfs2_create_xattr_block() takes from meta_ac through ocfs2_claim_metadata(), and it is spent before the value tree exists.

ocfs2_extend_meta_needed() on the empty def_xv list returns 2, so the branch reserves 2 where 3 are needed. The xattr block consumes one, and when the cluster allocator is fragmented enough that the value needs more than one extent, ocfs2_add_clusters_in_btree() comes back around with a full value root and ocfs2_alloc_context_bits_left() of 1 against a threshold of 2. It answers RESTART_META, which ocfs2_xattr_extend_allocation() turns into a BUG_ON(). Commit 0cdc7dde00ec ("ocfs2: fix missing metadata reservation for large xattrs") downgraded that to -ENOSPC, at the cost of leaking the clusters already handed out: ocfs2_xa_cleanup_value_truncate() takes its !orig_clusters arm, drops the entry and leaves the clusters for fsck.ocfs2 to reclaim.

Reserve for the block and the tree separately.

Fixes 3ed2be719eb9 ("ocfs2: allow for more than one data extent when creating xattr")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
fs/ocfs2/xattr.c +7 -1
index 5c88f6f800852..60725da12c0cd 100644
@@ -3458,7 +3458,13 @@ static int ocfs2_calc_xattr_set_need(struct inode *inode,
 		credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS;
 		if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE) {
 			struct ocfs2_extent_list *el = &def_xv.xv.xr_list;
-			meta_add += ocfs2_extend_meta_needed(el);
+			/*
+			 * One block for the xattr block we may have to
+			 * allocate, the rest for growing the value tree it
+			 * would hold.  If ocfs2_xattr_ibody_set() succeeds
+			 * instead, that first block goes unused.
+			 */
+			meta_add += 1 + ocfs2_extend_meta_needed(el);
 			credits += ocfs2_calc_extend_credits(inode->i_sb,
 							     el);
 		} else {
Signature · 1 line
2.53.0
author maintainer
#1400 lore raw

PATCH 1397/1536 ocfs2: reserve value tree metadata when moving an xattr into the inode

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit f5aee8ae5f85f8dfa78160e5c4963494319cdd64 ]

ocfs2_calc_xattr_set_need() charges no metadata for the case where an xattr living in an xattr block or bucket moves back into the inode:

        if (old_in_xb) {
                if (ocfs2_xattr_can_be_in_inode(inode, xi, xis)) {
                        clusters_add += new_clusters;
                        credits += ...;
                        if (!ocfs2_xattr_is_local(xe))
                                credits += ocfs2_calc_extend_credits(...);
                        goto out;
                }
        }

The credits for extending a value tree are there but the matching blocks are not, so meta_add stays 0, ocfs2_init_xattr_set_ctxt() skips ocfs2_reserve_new_metadata_blocks() and ctxt->meta_ac is left NULL.

This is the shape commit 0cdc7dde00ec ("ocfs2: fix missing metadata reservation for large xattrs") fixed for the xattr block case, and it is reached the same way: namevalue_size() charges a value larger than OCFS2_XATTR_INLINE_SIZE as only OCFS2_XATTR_ROOT_SIZE, so ocfs2_xattr_can_be_in_inode() accepts a new value that will be stored outside. ocfs2_xa_prepare_entry() installs a value root from def_xv and grows it, and once the cluster allocator is fragmented enough to need a second extent ocfs2_add_clusters_in_btree() finds the root full with no meta_ac at all and answers RESTART_META. ocfs2_xattr_extend_allocation() turns that into -ENOSPC, or into a BUG_ON() without that commit, and ocfs2_xa_cleanup_value_truncate() takes its !orig_clusters arm, dropping the entry and leaking the clusters already handed out until fsck.ocfs2 reclaims them.

Reserve for the value tree here too. The entry moves back into the inode rather than into a new xattr block, so unlike the create side of meta_guess this needs no block of its own.

Fixes 78f30c314a74 ("ocfs2/xattr: Reserve meta/data at the beginning of ocfs2_xattr_set.")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 8 ++++++++
 1 file changed, 8 insertions(+)
fs/ocfs2/xattr.c +8 -0
index 60725da12c0cd..de87adb1ea976 100644
@@ -3358,6 +3358,14 @@ static int ocfs2_calc_xattr_set_need(struct inode *inode,
 				credits += ocfs2_calc_extend_credits(
 							inode->i_sb,
 							&def_xv.xv.xr_list);
+			/*
+			 * A value too big to stay inline is only charged as
+			 * OCFS2_XATTR_ROOT_SIZE above, so it can still need a
+			 * value tree of its own.  No xattr block is allocated
+			 * on this path, so the tree is all we reserve for.
+			 */
+			if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE)
+				meta_add += ocfs2_extend_meta_needed(&def_xv.xv.xr_list);
 			goto out;
 		}
 	}
Signature · 1 line
2.53.0
author maintainer
#1401 lore raw

PATCH 1398/1536 ocfs2: deal with legacy signed dir index name hash values

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit d1b49d5ea1bf43cce2b0e249a7f7a30dde133907 ]

Patch series "ocfs2: deal with legacy signed name hash values", v2.

Commit 3bc753c06dd0 ("kbuild: treat char as always unsigned") turned on -funsigned-char globally, which changed the result of two naked 'char' loads in ocfs2 hashing code:

	str2hashbuf()            val = msg[i] + (val << 8);
	ocfs2_xattr_name_hash()  hash = (hash << 5) ^ (hash >> 27) ^ *name++;

A name byte >= 0x80 used to sign-extend and now zero-extends. Both results are written to disk, the first into the dx leaf when a directory entry is indexed and the second into xe_name_hash when an xattr is stored, so anything written by a pre-6.2 kernel is looked up under a different hash and is no longer found. readdir and listxattr still list those names because neither of them hashes, which makes this look like the filesystem losing entries rather than like a lookup bug. Anderson Ferneda reported it that way for directories with non-ASCII names [1].

Patches 1 and 3 do what ext4 did in commit f3bbac32475b2 ("ext4: deal with legacy signed xattr name hash values"): look up with the current unsigned hash, retry with the legacy signed one on a miss, and always store new entries under the unsigned hash. The retry is skipped when the two hashes come out equal, so an ASCII name does not walk the index twice. Both hash functions now spell out the signedness instead of leaving it to -funsigned-char, as commit 854f0912f813 ("ext4: make xattr char unsignedness in hash explicit") did, so a backport to a kernel without the flag still computes both variants correctly.

Patch 2 is a separate fix, placed before patch 3 so that every commit in the series is correct on its own. ocfs2_check_xattr_bucket_collision() recomputes the hash of the name to decide whether splitting a full bucket can make room for the entry being set. That is right for a new entry and wrong for one that already exists, since an update leaves xe_name_hash alone. Against a bucket holding legacy hashes the comparison does not match, so the split goes ahead and cannot help: a bucket whose entries all share one hash has no divide position. How that ends depends on where the unsigned hash sorts. Below the legacy ones, the set fails with -ENOSPC after growing the tree for nothing. Above them, it lands in the empty bucket the split just appended and stores a second copy of the entry there while the original stays behind, so listxattr reports the name twice. Using the stored hash closes both.

Nothing retires a legacy hash at runtime. Deleting or updating an entry does not rewrite it, and the only code that rehashes existing dirents is ocfs2_expand_inline_dir() on the inline to extent conversion, so the retry stays for as long as the legacy entries do. Rebuilding the index offline is what removes it for good.

This patch (of 3):

Commit 3bc753c06dd0 ("kbuild: treat char as always unsigned") set -funsigned-char globally, which changed the result of the naked 'char' load in str2hashbuf():

	val = msg[i] + (val << 8);

A name byte >= 0x80 used to sign-extend and now zero-extends, so ocfs2_dx_dir_name_hash() computes a different hash pair for every name containing one. The pair is written into the dx leaf when the entry is created, so an index built by an older kernel no longer matches and ocfs2_dx_dir_search() returns -ENOENT for a name that readdir still lists.

Search with the current unsigned hash and, on a miss, retry with the legacy signed one, as ext4 does in commit f3bbac32475b2 ("ext4: deal with legacy signed xattr name hash values"). New entries are always indexed under the unsigned hash. Skip the retry when the two hashes are equal, so that a miss on an ASCII name does not walk the index twice.

The retry costs a second walk of the dx tree, so a negative lookup of a name containing a byte >= 0x80 does twice the work. That is bounded and worth it, and directories whose dx root is still inline pay nothing extra, since there the retry only rescans the root block that is already loaded. Nothing retires it at runtime: a legacy entry keeps its legacy hash, because neither deleting nor updating an entry rewrites the dx hash, and the only code that rehashes existing dirents is ocfs2_expand_inline_dir() on the inline to extent conversion. Rebuilding the index offline is what removes the cost for good.

Also spell out the signedness in str2hashbuf() instead of leaving the current hash to -funsigned-char, as commit 854f0912f813 ("ext4: make xattr char unsignedness in hash explicit") did, so that both variants stay correct if this is backported to a kernel without the flag.

---
 fs/ocfs2/dir.c | 76 ++++++++++++++++++++++++++++++++++++++++++--------
 1 file changed, 65 insertions(+), 11 deletions(-)
fs/ocfs2/dir.c +65 -11
index dc1e379e58d50..d541d41601483 100644
@@ -221,7 +221,8 @@ static void TEA_transform(__u32 buf[4], __u32 const in[])
 	buf[1] += b1;
 }
 
-static void str2hashbuf(const char *msg, int len, __u32 *buf, int num)
+static void str2hashbuf(const char *msg, int len, __u32 *buf, int num,
+			bool legacy_signed)
 {
 	__u32	pad, val;
 	int	i;
@@ -235,7 +236,10 @@ static void str2hashbuf(const char *msg, int len, __u32 *buf, int num)
 	for (i = 0; i < len; i++) {
 		if ((i % 4) == 0)
 			val = pad;
-		val = msg[i] + (val << 8);
+		if (legacy_signed)
+			val = (signed char)msg[i] + (val << 8);
+		else
+			val = (unsigned char)msg[i] + (val << 8);
 		if ((i % 4) == 3) {
 			*buf++ = val;
 			val = pad;
@@ -248,8 +252,9 @@ static void str2hashbuf(const char *msg, int len, __u32 *buf, int num)
 		*buf++ = pad;
 }
 
-static void ocfs2_dx_dir_name_hash(struct inode *dir, const char *name, int len,
-				   struct ocfs2_dx_hinfo *hinfo)
+static void __ocfs2_dx_dir_name_hash(struct inode *dir, const char *name,
+				     int len, struct ocfs2_dx_hinfo *hinfo,
+				     bool legacy_signed)
 {
 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
 	const char	*p;
@@ -279,7 +284,7 @@ static void ocfs2_dx_dir_name_hash(struct inode *dir, const char *name, int len,
 
 	p = name;
 	while (len > 0) {
-		str2hashbuf(p, len, in, 4);
+		str2hashbuf(p, len, in, 4, legacy_signed);
 		TEA_transform(buf, in);
 		len -= 16;
 		p += 16;
@@ -290,6 +295,19 @@ static void ocfs2_dx_dir_name_hash(struct inode *dir, const char *name, int len,
 	hinfo->minor_hash = buf[1];
 }
 
+static void ocfs2_dx_dir_name_hash(struct inode *dir, const char *name, int len,
+				   struct ocfs2_dx_hinfo *hinfo)
+{
+	__ocfs2_dx_dir_name_hash(dir, name, len, hinfo, false);
+}
+
+static void ocfs2_dx_dir_name_hash_signed(struct inode *dir, const char *name,
+					  int len,
+					  struct ocfs2_dx_hinfo *hinfo)
+{
+	__ocfs2_dx_dir_name_hash(dir, name, len, hinfo, true);
+}
+
 /*
  * bh passed here can be an inode block or a dir data block, depending
  * on the inode inline data flag.
@@ -953,10 +971,10 @@ static int ocfs2_dx_dir_lookup(struct inode *inode,
 	return ret;
 }
 
-static int ocfs2_dx_dir_search(const char *name, int namelen,
-			       struct inode *dir,
-			       struct ocfs2_dx_root_block *dx_root,
-			       struct ocfs2_dir_lookup_result *res)
+static int __ocfs2_dx_dir_search(const char *name, int namelen,
+				 struct inode *dir,
+				 struct ocfs2_dx_root_block *dx_root,
+				 struct ocfs2_dir_lookup_result *res)
 {
 	int ret, i, found;
 	u64 phys;
@@ -969,8 +987,6 @@ static int ocfs2_dx_dir_search(const char *name, int namelen,
 	struct ocfs2_extent_list *dr_el;
 	struct ocfs2_dx_entry_list *entry_list;
 
-	ocfs2_dx_dir_name_hash(dir, name, namelen, &res->dl_hinfo);
-
 	if (ocfs2_dx_root_inline(dx_root)) {
 		entry_list = &dx_root->dr_entries;
 		goto search;
@@ -1067,6 +1083,44 @@ static int ocfs2_dx_dir_search(const char *name, int namelen,
 	return ret;
 }
 
+static int ocfs2_dx_dir_search(const char *name, int namelen,
+			       struct inode *dir,
+			       struct ocfs2_dx_root_block *dx_root,
+			       struct ocfs2_dir_lookup_result *res)
+{
+	struct ocfs2_dx_hinfo legacy;
+	int ret;
+
+	ocfs2_dx_dir_name_hash(dir, name, namelen, &res->dl_hinfo);
+
+	ret = __ocfs2_dx_dir_search(name, namelen, dir, dx_root, res);
+	if (ret != -ENOENT)
+		return ret;
+
+	/*
+	 * Nothing under the current hash.  The entry may have been indexed by
+	 * an older kernel, which sign-extended the name bytes when hashing.
+	 * New entries are always indexed under the unsigned hash, so only fall
+	 * back to the legacy signed one when it can actually differ: an ASCII
+	 * name hashes the same either way, and a genuine miss on one should
+	 * not have to walk the index twice.
+	 */
+	ocfs2_dx_dir_name_hash_signed(dir, name, namelen, &legacy);
+	if (legacy.major_hash == res->dl_hinfo.major_hash &&
+	    legacy.minor_hash == res->dl_hinfo.minor_hash)
+		return ret;
+
+	res->dl_hinfo = legacy;
+
+	ret = __ocfs2_dx_dir_search(name, namelen, dir, dx_root, res);
+	if (ret)
+		return ret;
+
+	pr_warn_once("ocfs2: directory index with signed name hash\n");
+
+	return 0;
+}
+
 static int ocfs2_find_entry_dx(const char *name, int namelen,
 			       struct inode *dir,
 			       struct ocfs2_dir_lookup_result *lookup)
Signature · 1 line
2.53.0
author maintainer
#1402 lore raw

PATCH 1399/1536 ocfs2: use the stored hash when checking xattr bucket collision

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit e39baff18b85cf8956aee138d7944b6581e8ba36 ]

ocfs2_check_xattr_bucket_collision() decides whether splitting a full bucket can make room for the entry being set by recomputing the hash of the name:

	u32 name_hash = ocfs2_xattr_name_hash(inode, name, strlen(name));

	if (name_hash != le32_to_cpu(xh->xh_entries[0].xe_name_hash))
		return 0;

For a new entry that is the hash it will be stored under, so comparing it is correct. An existing entry keeps the hash it already has: an update never rewrites xe_name_hash, since ocfs2_xa_add_entry() is the only writer of that field for a real entry and ocfs2_xa_prepare_entry() calls it only when loc->xl_entry is NULL.

An entry stored by a kernel that sign-extended the name bytes when hashing can still be updated, because ocfs2_xattr_find_entry() searches a non-indexed xattr block by memcmp on the name and never looks at xe_name_hash. Growing it past the space left in the block converts the block into a tree, ocfs2_cp_xattr_block_to_bucket() fills the bucket in stored hash order, and the update runs out of room in the bucket too. The collision check then compares the unsigned hash against the legacy hashes in the bucket and reports no collision.

ocfs2_xattr_set_entry_index_block() goes on to allocate a bucket that ocfs2_divide_xattr_bucket() cannot fill: a bucket whose entries all share one hash has no divide position, so all it does is append an empty bucket with a sentinel hash one above the last entry's.

The re-search that follows depends on where the unsigned hash sorts. Below the legacy ones, it comes back to the full bucket and the set fails with -ENOSPC, having grown the tree for nothing. Above them, it lands on the new empty bucket, which ocfs2_xattr_bucket_find() handles explicitly and ocfs2_find_xe_in_bucket() scans zero times, so the set stores a second copy of the entry under the unsigned hash and returns success. The original stays in the full bucket, listxattr reports the name twice and getxattr returns the new copy.

Pass the hash the entry is stored under instead: the stored one for an existing entry, the unsigned one for a new entry. A tree whose entries are all stored under the unsigned hash sees no change, since there the two are the same value.

Fixes 3bc753c06dd0 ("kbuild: treat char as always unsigned")
Cc Anderson Ferneda <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc <[email protected]> # 6.2+
---
 fs/ocfs2/xattr.c | 27 +++++++++++++++++----------
 1 file changed, 17 insertions(+), 10 deletions(-)
fs/ocfs2/xattr.c +17 -10
index de87adb1ea976..8689a1ba0e43a 100644
@@ -5746,16 +5746,14 @@ static int ocfs2_rm_xattr_cluster(struct inode *inode,
 
 /*
  * check whether the xattr bucket is filled up with the same hash value.
- * If we want to insert the xattr with the same hash, return -ENOSPC.
- * If we want to insert a xattr with different hash value, go ahead
- * and ocfs2_divide_xattr_bucket will handle this.
+ * If the entry being set carries that same hash, return -ENOSPC, since
+ * ocfs2_divide_xattr_bucket() has no divide position to work with.
+ * Otherwise go ahead and ocfs2_divide_xattr_bucket() will handle this.
  */
-static int ocfs2_check_xattr_bucket_collision(struct inode *inode,
-					      struct ocfs2_xattr_bucket *bucket,
-					      const char *name)
+static int ocfs2_check_xattr_bucket_collision(struct ocfs2_xattr_bucket *bucket,
+					      u32 name_hash)
 {
 	struct ocfs2_xattr_header *xh = bucket_xh(bucket);
-	u32 name_hash = ocfs2_xattr_name_hash(inode, name, strlen(name));
 
 	if (name_hash != le32_to_cpu(xh->xh_entries[0].xe_name_hash))
 		return 0;
@@ -5824,6 +5822,7 @@ static int ocfs2_xattr_set_entry_index_block(struct inode *inode,
 					     struct ocfs2_xattr_search *xs,
 					     struct ocfs2_xattr_set_ctxt *ctxt)
 {
+	u32 name_hash;
 	int ret;
 
 	trace_ocfs2_xattr_set_entry_index_block(xi->xi_name);
@@ -5843,10 +5842,18 @@ static int ocfs2_xattr_set_entry_index_block(struct inode *inode,
 	 * the maximum number of collisions we will allow for then is
 	 * one bucket's worth, so check it here whether we need to
 	 * add a new bucket for the insert.
+	 *
+	 * An existing entry keeps the hash it was stored under, and that is
+	 * the hash a split has to work with.  A new entry is stored under the
+	 * unsigned one, which is what ocfs2_xa_add_entry() will write.
 	 */
-	ret = ocfs2_check_xattr_bucket_collision(inode,
-						 xs->bucket,
-						 xi->xi_name);
+	if (xs->not_found)
+		name_hash = ocfs2_xattr_name_hash(inode, xi->xi_name,
+						  xi->xi_name_len);
+	else
+		name_hash = le32_to_cpu(xs->here->xe_name_hash);
+
+	ret = ocfs2_check_xattr_bucket_collision(xs->bucket, name_hash);
 	if (ret) {
 		mlog_errno(ret);
 		goto out;
Signature · 1 line
2.53.0
author maintainer
#1403 lore raw

PATCH 1400/1536 ocfs2: deal with legacy signed xattr name hash values

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit 824d26d11448b4d4f19677bce27c7fe5e962f4c6 ]

Commit 3bc753c06dd0 ("kbuild: treat char as always unsigned") set -funsigned-char globally, which changed the result of the naked 'char' load in ocfs2_xattr_name_hash():

	hash = (hash << OCFS2_HASH_SHIFT) ^
	       (hash >> (8*sizeof(hash) - OCFS2_HASH_SHIFT)) ^
	       *name++;

A name byte >= 0x80 used to sign-extend and now zero-extends, so the hash no longer matches the xe_name_hash an older kernel stored. An indexed xattr tree is searched by that hash alone, and both the bucket binary search and the entry scan within it stop as soon as the wanted hash falls below an entry's, so the entry is never reached: getxattr, setxattr and removexattr return -ENODATA for a name that listxattr still lists.

Search with the current unsigned hash and, on a miss, retry with the legacy signed one, as ext4 does in commit f3bbac32475b2 ("ext4: deal with legacy signed xattr name hash values"). New entries are always stored under the unsigned hash. Skip the retry when the two hashes are equal, so that a miss on an ASCII name does not walk the tree twice.

A miss is not empty handed: ocfs2_xattr_bucket_find() leaves xs->bucket holding the bucket a new entry would go into. So after a double miss drop it and search once more with the unsigned hash, otherwise a new entry would be placed by its legacy hash and stored under its unsigned one, breaking the ordering the search relies on.

Only indexed trees are affected; inline xattrs and non-indexed xattr blocks compare names with memcmp and never look at the hash.

Also spell out the signedness instead of leaving the current hash to -funsigned-char, as commit 854f0912f813 ("ext4: make xattr char unsignedness in hash explicit") did, so that both variants stay correct if this is backported to a kernel without the flag.

Fixes 3bc753c06dd0 ("kbuild: treat char as always unsigned")
Cc Anderson Ferneda <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc <[email protected]> # 6.2+
---
 fs/ocfs2/xattr.c | 93 ++++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 82 insertions(+), 11 deletions(-)
fs/ocfs2/xattr.c +82 -11
index 8689a1ba0e43a..de4a7070d4ac5 100644
@@ -557,9 +557,10 @@ static inline const char *ocfs2_xattr_prefix(int name_index)
 	return handler ? xattr_prefix(handler) : NULL;
 }
 
-static u32 ocfs2_xattr_name_hash(struct inode *inode,
-				 const char *name,
-				 int name_len)
+static u32 __ocfs2_xattr_name_hash(struct inode *inode,
+				   const char *name,
+				   int name_len,
+				   bool legacy_signed)
 {
 	/* Get hash value of uuid from super block */
 	u32 hash = OCFS2_SB(inode->i_sb)->uuid_hash;
@@ -568,13 +569,30 @@ static u32 ocfs2_xattr_name_hash(struct inode *inode,
 	/* hash extended attribute name */
 	for (i = 0; i < name_len; i++) {
 		hash = (hash << OCFS2_HASH_SHIFT) ^
-		       (hash >> (8*sizeof(hash) - OCFS2_HASH_SHIFT)) ^
-		       *name++;
+		       (hash >> (8*sizeof(hash) - OCFS2_HASH_SHIFT));
+		if (legacy_signed)
+			hash ^= (signed char)name[i];
+		else
+			hash ^= (unsigned char)name[i];
 	}
 
 	return hash;
 }
 
+static u32 ocfs2_xattr_name_hash(struct inode *inode,
+				 const char *name,
+				 int name_len)
+{
+	return __ocfs2_xattr_name_hash(inode, name, name_len, false);
+}
+
+static u32 ocfs2_xattr_name_hash_signed(struct inode *inode,
+					const char *name,
+					int name_len)
+{
+	return __ocfs2_xattr_name_hash(inode, name, name_len, true);
+}
+
 static int ocfs2_xattr_entry_real_size(int name_len, size_t value_len)
 {
 	return namevalue_size(name_len, value_len) +
@@ -4164,11 +4182,12 @@ static int ocfs2_xattr_bucket_find(struct inode *inode,
 	return ret;
 }
 
-static int ocfs2_xattr_index_block_find(struct inode *inode,
-					struct buffer_head *root_bh,
-					int name_index,
-					const char *name,
-					struct ocfs2_xattr_search *xs)
+static int __ocfs2_xattr_index_block_find(struct inode *inode,
+					  struct buffer_head *root_bh,
+					  int name_index,
+					  const char *name,
+					  u32 name_hash,
+					  struct ocfs2_xattr_search *xs)
 {
 	int ret;
 	struct ocfs2_xattr_block *xb =
@@ -4177,7 +4196,6 @@ static int ocfs2_xattr_index_block_find(struct inode *inode,
 	struct ocfs2_extent_list *el = &xb_root->xt_list;
 	u64 p_blkno = 0;
 	u32 first_hash, num_clusters = 0;
-	u32 name_hash = ocfs2_xattr_name_hash(inode, name, strlen(name));
 
 	if (le16_to_cpu(el->l_next_free_rec) == 0)
 		return -ENODATA;
@@ -4208,6 +4226,59 @@ static int ocfs2_xattr_index_block_find(struct inode *inode,
 	return ret;
 }
 
+static int ocfs2_xattr_index_block_find(struct inode *inode,
+					struct buffer_head *root_bh,
+					int name_index,
+					const char *name,
+					struct ocfs2_xattr_search *xs)
+{
+	u32 name_hash, legacy_hash;
+	int name_len = strlen(name);
+	int ret;
+
+	name_hash = ocfs2_xattr_name_hash(inode, name, name_len);
+
+	ret = __ocfs2_xattr_index_block_find(inode, root_bh, name_index, name,
+					     name_hash, xs);
+	if (ret != -ENODATA)
+		return ret;
+
+	/*
+	 * Nothing under the current hash.  The entry may have been stored by
+	 * an older kernel, which sign-extended the name bytes when hashing.
+	 * Skip the retry when the two hashes are equal, so that a name made
+	 * only of ASCII does not have to walk the tree twice.
+	 */
+	legacy_hash = ocfs2_xattr_name_hash_signed(inode, name, name_len);
+	if (legacy_hash == name_hash)
+		return ret;
+
+	/*
+	 * A miss still leaves xs->bucket holding the bucket a new entry would
+	 * be inserted into, so drop it before searching again.
+	 */
+	ocfs2_xattr_bucket_relse(xs->bucket);
+
+	ret = __ocfs2_xattr_index_block_find(inode, root_bh, name_index, name,
+					     legacy_hash, xs);
+	if (!ret) {
+		pr_warn_once("ocfs2: xattr tree with signed name hash\n");
+		return ret;
+	}
+	if (ret != -ENODATA)
+		return ret;
+
+	/*
+	 * Not under either hash.  Restore the unsigned placement, since that
+	 * is where a new entry is stored: leaving the bucket where the legacy
+	 * hash put it would break the ordering the search relies on.
+	 */
+	ocfs2_xattr_bucket_relse(xs->bucket);
+
+	return __ocfs2_xattr_index_block_find(inode, root_bh, name_index, name,
+					      name_hash, xs);
+}
+
 static int ocfs2_iterate_xattr_buckets(struct inode *inode,
 				       u64 blkno,
 				       u32 clusters,
Signature · 1 line
2.53.0
author maintainer
#1404 lore raw

PATCH 1401/1536 ocfs2/cluster: initialize heartbeat regions before publishing them

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit c5b7a30a5172317e1e3cba61d8c9f9c588c497bb ]

A region on o2hb_all_regions must have an initialized config item and name. o2hb_heartbeat_group_make_item() currently links the zeroed region under o2hb_live_lock, drops the lock, and only then initializes hr_item. The lock therefore protects the list without protecting initialization from readers of the published item.

With global heartbeat enabled, a DLM_QUERY_REGION from the current joining node can pass the existing-domain and protocol checks while a configfs mkdir creates another region. The DLM locks are not taken by the constructor, and the network worker does not take the configfs subsystem mutex. The following ordering is possible:

Configfs mkdir O2net receive worker
-------------- --------------------
Allocate reg
Lock o2hb_live_lock
Link into o2hb_all_regions
Unlock o2hb_live_lock
dlm_query_region_handler()
dlm_match_regions()
o2hb_get_all_regions()
Lock o2hb_live_lock Copy 32 bytes from NULL name Unlock o2hb_live_lock
config_item_init_type_name()

The query thus dereferences NULL. Initialize hr_item before linking the region so the existing list lock also orders name initialization before any reader. Reject a failed name allocation, since the initialization helper does not propagate that error.

Use config_item_put() on initialized constructor failures to release the name and respect references retained by o2hb_region_pin(). Initialize the list heads, mutex and delayed works needed by o2hb_region_release() before any such put, and leave the list node self-linked after rollback. Keep the existing handler drain before removing a failed published item.

KASAN report as below:

    ==================================================================
    BUG: KASAN: null-ptr-deref in o2hb_get_all_regions+0xbb/0x1f0
    Read of size 32 at addr 0000000000000000 by task kworker/u16:1/14

    CPU: 2 UID: 0 PID: 14 Comm: kworker/u16:1 Not tainted 7.3.0-rc4-next-20260921-pmb-ocfs2-functional-v1+ #1 PREEMPT(lazy)
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Workqueue: o2net o2net_rx_until_empty
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     kasan_report+0xe0/0x110
     ? o2hb_get_all_regions+0xbb/0x1f0
     kasan_check_range+0x105/0x1b0
     __asan_memcpy+0x23/0x60
     o2hb_get_all_regions+0xbb/0x1f0
     dlm_query_region_handler+0x4c2/0xc20
     ? __pfx_dlm_query_region_handler+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on+0x18/0x160
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? kvm_clock_get_cycles+0x31/0x60
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_dlm_query_region_handler+0x10/0x10
     o2net_rx_until_empty+0x1a50/0x3200
     ? reacquire_held_locks+0xdd/0x200
     ? __pfx_o2net_rx_until_empty+0x10/0x10
     ? lock_acquire+0x190/0x300
     ? process_one_work+0x935/0x1b40
     ? process_one_work+0x834/0x1b40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x290
     ? srso_alias_return_thunk+0x5/0xfbef5
     process_one_work+0x9a8/0x1b40
     ? __pfx_process_one_work+0x10/0x10
     ? lock_acquire+0x190/0x300
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __kthread_parkme+0x177/0x220
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x351/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf70
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>
    ==================================================================
Fixes 536f0741f324 ("ocfs2/cluster: Track number of global heartbeat regions")
Assisted-by LLM
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc Heming Zhao <[email protected]>
Cc Yufan Chen <[email protected]>
Cc Christophe JAILLET <[email protected]>
Cc Kees Cook <[email protected]>
Cc Karl Mehltretter <[email protected]>
Cc Sunil Mushran <[email protected]>
Cc Jia-Ju Bai <[email protected]>
---
 fs/ocfs2/cluster/heartbeat.c | 26 +++++++++++++++++---------
 1 file changed, 17 insertions(+), 9 deletions(-)
fs/ocfs2/cluster/heartbeat.c +17 -9
index ca8c99b1cec01..94743cef12f13 100644
@@ -2124,6 +2124,18 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *g
 	}
 	reg->hr_node_num = O2NM_MAX_NODES;
 
+	INIT_LIST_HEAD(&reg->hr_all_item);
+	mutex_init(&reg->hr_arming_mutex);
+	reg->hr_stopping = true;
+	INIT_DELAYED_WORK(&reg->hr_write_timeout_work, o2hb_write_timeout);
+	INIT_DELAYED_WORK(&reg->hr_nego_timeout_work, o2hb_nego_timeout);
+	INIT_LIST_HEAD(&reg->hr_handler_list);
+	config_item_init_type_name(&reg->hr_item, name, &o2hb_region_type);
+	if (!config_item_name(&reg->hr_item)) {
+		ret = -ENOMEM;
+		goto put_item;
+	}
+
 	spin_lock(&o2hb_live_lock);
 	reg->hr_region_num = 0;
 	if (o2hb_global_heartbeat_active()) {
@@ -2132,26 +2144,19 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *g
 		if (reg->hr_region_num >= O2NM_MAX_REGIONS) {
 			spin_unlock(&o2hb_live_lock);
 			ret = -EFBIG;
-			goto free;
+			goto put_item;
 		}
 		set_bit(reg->hr_region_num, o2hb_region_bitmap);
 	}
 	list_add_tail(&reg->hr_all_item, &o2hb_all_regions);
 	spin_unlock(&o2hb_live_lock);
 
-	config_item_init_type_name(&reg->hr_item, name, &o2hb_region_type);
-
 	/* this is the same way to generate msg key as dlm, for local heartbeat,
 	 * name is also the same, so make initial crc value different to avoid
 	 * message key conflict.
 	 */
 	reg->hr_key = crc32_le(reg->hr_region_num + O2NM_MAX_REGIONS,
 		name, strlen(name));
-	mutex_init(&reg->hr_arming_mutex);
-	reg->hr_stopping = true;
-	INIT_DELAYED_WORK(&reg->hr_write_timeout_work, o2hb_write_timeout);
-	INIT_DELAYED_WORK(&reg->hr_nego_timeout_work, o2hb_nego_timeout);
-	INIT_LIST_HEAD(&reg->hr_handler_list);
 	ret = o2net_register_handler(O2HB_NEGO_TIMEOUT_MSG, reg->hr_key,
 			sizeof(struct o2hb_nego_msg),
 			o2hb_nego_timeout_handler,
@@ -2174,10 +2179,13 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *g
 	o2net_unregister_and_flush_handler_list(&reg->hr_handler_list);
 remove_item:
 	spin_lock(&o2hb_live_lock);
-	list_del(&reg->hr_all_item);
+	list_del_init(&reg->hr_all_item);
 	if (o2hb_global_heartbeat_active())
 		clear_bit(reg->hr_region_num, o2hb_region_bitmap);
 	spin_unlock(&o2hb_live_lock);
+put_item:
+	config_item_put(&reg->hr_item);
+	return ERR_PTR(ret);
 free:
 	kfree(reg);
 	return ERR_PTR(ret);
Signature · 1 line
2.53.0
author maintainer
#1405 lore raw

PATCH 1402/1536 Documentation: hyperv: Update documentation for sending VMBus packets

In reply to Greg Kroah-Hartman

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

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

From: Michael Kelley <[email protected]>

[ Upstream commit 6a3d77a0a8cf69cf3d234305e6711729eb5d10c4 ]

The functions for sending VMBus packets have changed. vmbus_sendpacket_mpb_desc() can target multiple ranges, and vmbus_sendpacket_pagebuffer() has been removed. vmbus_sendpacket_getid() has been added. Update the documentation accordingly.

Fixes 45a442fe369e ("Drivers: hv: vmbus: Remove vmbus_sendpacket_pagebuffer()")
---
 Documentation/virt/hyperv/vmbus.rst | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)
Documentation/virt/hyperv/vmbus.rst +9 -8
index 1dcef6a7fda3f..7ee27faf5e5bd 100644
@@ -141,14 +141,15 @@ Three functions exist to send VMBus channel messages:
 
 1. vmbus_sendpacket():  Control-only messages and messages with
    embedded data -- no GPAs
-2. vmbus_sendpacket_pagebuffer(): Message with list of GPAs
-   identifying data to transfer.  An offset and length is
-   associated with each GPA so that multiple discontinuous areas
-   of guest memory can be targeted.
-3. vmbus_sendpacket_mpb_desc(): Message with list of GPAs
-   identifying data to transfer.  A single offset and length is
-   associated with a list of GPAs.  The GPAs must describe a
-   single logical area of guest memory to be targeted.
+2. vmbus_sendpacket_getid(): Similar to vmbus_sendpacket() but returns
+   a transaction ID that is matched against a reply from the Hyper-V
+   host. Useful when the struct completion (or other rendezvous data)
+   must reside on the caller's stack. By invalidating the transaction
+   ID before exiting the function due to a timeout or other error, a
+   late arriving interrupt is assured to not trash the stack.
+3. vmbus_sendpacket_mpb_desc(): Message with one or more data ranges
+   to target. Each range consists of a single offset and length plus
+   a list of GPAs that describe a logical area of guest memory.
 
 Historically, Linux guests have trusted Hyper-V to send well-formed
 and valid messages, and Linux drivers for synthetic devices did not
Signature · 1 line
2.53.0
author maintainer
#1406 lore raw

PATCH 1403/1536 platform/x86: asus-wmi: fix TUF keyboard power state shutdown naming

In reply to Greg Kroah-Hartman

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

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

From: Bartu Alev <[email protected]>

[ Upstream commit 3d9a175707eeb15a2d577af1e669b98e0236719b ]

The fourth state flag of kbd_rgb_state_index is named "keyboard" and has long been treated as having no effect. In hardware the flag, BIT(7) of the payload sent to the TUF RGB state device, gates whether the keyboard backlight stays lit while the machine powers off: with the bit set the keyboard lights up white during the ACPI S5 sequence, with the bit clear the machine powers off dark. Verified by A/B testing both values on a TUF Gaming A15 (FA507NV).

Rename the fourth field and its index entry from "keyboard" to "shutdown". The write format is unchanged, the value is still positional, and the diff is two variable names and one string, so it backports cleanly.

Fixes 61f64515299e ("platform/x86: asus-wmi: Implement TUF laptop keyboard power states")
---
 drivers/platform/x86/asus-wmi.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/platform/x86/asus-wmi.c +4 -4
index af9505b2455ae..1465057b3e3d3 100644
@@ -994,10 +994,10 @@ static ssize_t kbd_rgb_state_store(struct device *dev,
 				 struct device_attribute *attr,
 				 const char *buf, size_t count)
 {
-	u32 flags, cmd, boot, awake, sleep, keyboard;
+	u32 flags, cmd, boot, awake, sleep, shutdown;
 	int err;
 
-	if (sscanf(buf, "%d %d %d %d %d", &cmd, &boot, &awake, &sleep, &keyboard) != 5)
+	if (sscanf(buf, "%d %d %d %d %d", &cmd, &boot, &awake, &sleep, &shutdown) != 5)
 		return -EINVAL;
 
 	if (cmd)
@@ -1010,7 +1010,7 @@ static ssize_t kbd_rgb_state_store(struct device *dev,
 		flags |= BIT(3);
 	if (sleep)
 		flags |= BIT(5);
-	if (keyboard)
+	if (shutdown)
 		flags |= BIT(7);
 
 	/* 0xbd is the required default arg0 for the method. Nothing happens otherwise */
@@ -1024,7 +1024,7 @@ static ssize_t kbd_rgb_state_store(struct device *dev,
 static DEVICE_ATTR_WO(kbd_rgb_state);
 
 static DEVICE_STRING_ATTR_RO(kbd_rgb_state_index, 0444,
-			     "cmd boot awake sleep keyboard");
+			     "cmd boot awake sleep shutdown");
 
 static struct attribute *kbd_rgb_state_attrs[] = {
 	&dev_attr_kbd_rgb_state.attr,
Signature · 1 line
2.53.0
author maintainer
#1408 lore raw

PATCH 1404/1536 writeback: reset dirtied_when when switching wbs

In reply to Greg Kroah-Hartman

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

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

From: Julian Sun <[email protected]>

[ Upstream commit 13b9a606dd0a6cf9bac12894c97b9546d22a7425 ]

When switching a dirty inode to another wb, inode_do_switch_wbs() puts it at the newest end of the target b_dirty list instead of searching for its sorted position. This requires updating dirtied_when, which move_expired_inodes() uses to decide where to stop scanning.

However, the switch updates dirtied_time_when instead. This leaves b_dirty out of order and can make the scan stop before reaching older inodes. It also resets the lazytime expiration timestamp, potentially delaying timestamp writeback.

Update dirtied_when instead, preserving both the constant-time insertion and the lazytime expiration timestamp. Correct the field name in the comment and document the distinction between the two inode timestamps.

---
 fs/fs-writeback.c  | 6 +++---
 include/linux/fs.h | 4 +++-
 2 files changed, 6 insertions(+), 4 deletions(-)
fs/fs-writeback.c +3 -3
index 48ac4f58605e7..925fc4a42c67d 100644
@@ -455,12 +455,12 @@ static bool inode_do_switch_wbs(struct inode *inode,
 		if (inode->i_state & I_DIRTY_ALL) {
 			/*
 			 * We need to keep b_dirty list sorted by
-			 * dirtied_time_when. However properly sorting the
+			 * dirtied_when. However properly sorting the
 			 * inode in the list gets too expensive when switching
 			 * many inodes. So just attach inode at the end of the
-			 * dirty list and clobber the dirtied_time_when.
+			 * dirty list and clobber the dirtied_when.
 			 */
-			inode->dirtied_time_when = jiffies;
+			inode->dirtied_when = jiffies;
 			inode_io_list_move_locked(inode, new_wb,
 						  &new_wb->b_dirty);
 		} else {
include/linux/fs.h +3 -1
index 19211eb49a8c0..67b57ce46b203 100644
@@ -719,7 +719,9 @@ struct inode {
 	/* 32-bit hole */
 	struct rw_semaphore	i_rwsem;
 
-	unsigned long		dirtied_when;	/* jiffies of first dirtying */
+	/* Timestamp for writeback list ordering and age checks (jiffies). */
+	unsigned long		dirtied_when;
+	/* Start time for deciding when lazytime updates need writeback (jiffies). */
 	unsigned long		dirtied_time_when;
 
 	struct hlist_node	i_hash;
Signature · 1 line
2.53.0
author maintainer
#1409 lore raw

PATCH 1405/1536 writeback: clear old wb dirty state after inode switches

In reply to Greg Kroah-Hartman

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

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

From: Julian Sun <[email protected]>

[ Upstream commit a396fe9f74ea367ae3fab2dcb70b24e83db9f0cb ]

Switching an inode to another wb updates the target wb's dirty-I/O state, but no longer checks whether the source wb's dirty-I/O lists became empty. The check was lost when inode_io_list_del_locked(inode, old_wb) was removed to support tracking clean attached inodes.

If the last dirty inode is moved, WB_has_dirty_io remains set on the old wb and its bandwidth contribution remains in bdi->tot_write_bandwidth. This can keep an empty wb scheduled for periodic writeback and overstate the total bandwidth used to distribute writeback work.

Call wb_io_lists_depopulated() on the old wb after the batch of inode switches, while its list_lock is still held. This clears the flag and removes the bandwidth contribution if its dirty-I/O lists are empty.

Fixes f3b6a6df38aa ("writeback, cgroup: keep list of inodes attached to bdi_writeback")
---
 fs/fs-writeback.c | 1 +
 1 file changed, 1 insertion(+)
fs/fs-writeback.c +1 -0
index 925fc4a42c67d..435f14b7e2cca 100644
@@ -535,6 +535,7 @@ static void process_inode_switch_wbs(struct bdi_writeback *new_wb,
 		}
 	}
 
+	wb_io_lists_depopulated(old_wb);
 	spin_unlock(&new_wb->list_lock);
 	spin_unlock(&old_wb->list_lock);
 
Signature · 1 line
2.53.0
author maintainer
#1410 lore raw

PATCH 1406/1536 ALSA: aloop: Update the PCM Slave controls for a matching playback

In reply to Greg Kroah-Hartman

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

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

From: Henrik Enquist <[email protected]>

[ Upstream commit c3bde2beacbcb40790f0e3c3f909f9e16bbced9c ]

The "PCM Slave" format, rate, channels and access controls report the parameters of the playback side of a cable. loopback_check_format() updates them when a playback starts, but returns early when a capture is open and its parameters match. The controls then keep the module defaults, or the parameters of an earlier stream.

A playback that joins an open capture with the same parameters is the normal case without notify, where it is constrained to the capture's parameters, and also with notify whenever the player happens to use them. An application that reads the controls to find the playback's parameters, for example to reopen the capture side at the right rate after a restart, then gets the wrong values.

Only skip the capture stop when the parameters match, and update the controls in every case. A value event is still sent only for a control whose value changes.

Reproducer:
arecord -D hw:Loopback,1,0 -r 44100 -f S16_LE -c 2 /dev/null & aplay -D hw:Loopback,0,0 -t raw -r 44100 -f S16_LE -c 2 /dev/zero & amixer -c Loopback cget "iface=PCM,name='PCM Slave Rate',device=1"
Before: the control reports 48000, the module default.
After: it reports 44100.

Fixes 597603d615d2 ("ALSA: introduce the snd-aloop module for the PCM loopback")
---
 sound/drivers/aloop.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
sound/drivers/aloop.c +7 -4
index bb75051be5ee1..50b8e7b3d8179 100644
@@ -364,11 +364,14 @@ static int loopback_check_format(struct loopback_cable *cable, int stream)
 			runtime->channels != cruntime->channels ||
 			is_access_interleaved(runtime->access) !=
 			is_access_interleaved(cruntime->access);
-			if (!check)
-				return 0;
-			if (stream == SNDRV_PCM_STREAM_CAPTURE)
+			/*
+			 * Matching params also go on to the update below, so that
+			 * the setup controls follow a playback that joins an open
+			 * capture.
+			 */
+			if (check && stream == SNDRV_PCM_STREAM_CAPTURE)
 				return -EIO;
-			else if (cruntime->state == SNDRV_PCM_STATE_RUNNING) {
+			else if (check && cruntime->state == SNDRV_PCM_STATE_RUNNING) {
 				/* close must not free the peer runtime below */
 				atomic_inc(&cable->stop_count);
 				stop_capture = true;
Signature · 1 line
2.53.0
author maintainer
#1411 lore raw

PATCH 1407/1536 sh: maple: Use the matching IRQ cookie when invoking free_irq()

In reply to Greg Kroah-Hartman

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

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

From: Runyu Xiao <[email protected]>

[ Upstream commit e3ef44e77b40e3cecfb34757ff3c15ecceea0309 ]

The Maple DMA and VBLANK handlers are registered with &maple_unsupported_device as their dev_id. Passing NULL to free_irq() cannot find either action, so the handlers remain registered and the IRQ core warns.

Use the same cookie when freeing both handlers on the error paths.

---
 drivers/sh/maple/maple.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/sh/maple/maple.c +2 -2
index 6dc0549f79005..3d3302c900caf 100644
@@ -863,10 +863,10 @@ static int __init maple_bus_init(void)
 	kmem_cache_destroy(maple_queue_cache);
 
 cleanup_bothirqs:
-	free_irq(HW_EVENT_VSYNC, 0);
+	free_irq(HW_EVENT_VSYNC, &maple_unsupported_device);
 
 cleanup_irq:
-	free_irq(HW_EVENT_MAPLE_DMA, 0);
+	free_irq(HW_EVENT_MAPLE_DMA, &maple_unsupported_device);
 
 cleanup_dma:
 	free_pages((unsigned long) maple_sendbuf, MAPLE_DMA_PAGES);
Signature · 1 line
2.53.0
author maintainer
#1412 lore raw

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

In reply to Greg Kroah-Hartman

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

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

From: Yu Zhang <[email protected]>

[ Upstream commit 9f426f14051181e251590783e68ce589a63e2b1c ]

nvmet_subsys_attr_qid_max_store() sets subsys->max_qid and then walks subsys->ctrls to force every controller to reconnect, but it holds only nvmet_config_sem (for write). subsys->ctrls is protected by subsys->lock:
nvmet_alloc_ctrl() adds an entry under subsys->lock, and nvmet_ctrl_free() removes it under subsys->lock with list_del() + kfree() (not kfree_rcu). The free path takes no nvmet_config_sem, so the two locks are independent.

A controller teardown (host disconnect, keep-alive timeout or fatal error -> nvmet_sq_destroy() -> nvmet_ctrl_put() -> nvmet_ctrl_free()) can therefore list_del() an entry while qid_max_store() is iterating the list, corrupting the walk.

KASAN, concurrent "echo 128 > .../subsystems/<nqn>/attr_qid_max" racing nvme-loop controllers connecting and disconnecting, panics in seconds:

  BUG: KASAN: null-ptr-deref in nvmet_subsys_attr_qid_max_store+0x10d/0x1b0
  Read of size 8 at addr 0000000000000090
  Call Trace:
   nvmet_subsys_attr_qid_max_store+0x10d/0x1b0
   configfs_write_iter+0x1a7/0x250
   vfs_write+0x5df/0x940
   ksys_write+0xfd/0x1e0

(also seen as a general-protection fault dereferencing a LIST_POISON pointer at the same instruction.)

Take subsys->lock around the list_for_each_entry() loop, matching every other subsys->ctrls accessor. ->delete_ctrl() only queues asynchronous controller teardown, so it does not re-enter subsys->lock under the loop.

Fixes 3e980f5995e0 ("nvmet: expose max queues to configfs")
---
 drivers/nvme/target/configfs.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/nvme/target/configfs.c +2 -0
index 1bec5dc7fc452..3b066601fd358 100644
@@ -1602,8 +1602,10 @@ static ssize_t nvmet_subsys_attr_qid_max_store(struct config_item *item,
 	subsys->max_qid = qid_max;
 
 	/* Force reconnect */
+	mutex_lock(&subsys->lock);
 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
 		ctrl->ops->delete_ctrl(ctrl);
+	mutex_unlock(&subsys->lock);
 	up_write(&nvmet_config_sem);
 
 	return cnt;
Signature · 1 line
2.53.0
author maintainer
#1413 lore raw

PATCH 1409/1536 net: wwan: iosm: validate msg_head before indexing msg_ring

In reply to Greg Kroah-Hartman

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

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

From: Liu Chao <[email protected]>

[ Upstream commit 46cbf85155e5451b6682ea0c17bc62ec564aec36 ]

ipc_protocol_free_msg_get() reads msg_head from shared memory and uses it directly as an index into msg_ring[]. If the head is out of range, the subsequent memset() writes beyond the message ring.

Validate head against IPC_MEM_MSG_ENTRIES before using it as an index. The ring is a circular buffer, so a value outside the valid range indicates a corrupted head pointer; report the error and fail the allocation instead of writing out of bounds.

---
 drivers/net/wwan/iosm/iosm_ipc_protocol_ops.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/net/wwan/iosm/iosm_ipc_protocol_ops.c +5 -0
index 4627847c6daab..455b3b6f09917 100644
@@ -14,6 +14,11 @@ ipc_protocol_free_msg_get(struct iosm_protocol *ipc_protocol, int *index)
 	u32 new_head = (head + 1) % IPC_MEM_MSG_ENTRIES;
 	union ipc_mem_msg_entry *msg;
 
+	if (head >= IPC_MEM_MSG_ENTRIES) {
+		dev_err(ipc_protocol->dev, "invalid message head %u", head);
+		return NULL;
+	}
+
 	if (new_head == le32_to_cpu(ipc_protocol->p_ap_shm->msg_tail)) {
 		dev_err(ipc_protocol->dev, "message ring is full");
 		return NULL;
Signature · 1 line
2.53.0
author maintainer
#1414 lore raw

PATCH 1410/1536 tipc: fix broadcast sender hang on last acker departure

In reply to Greg Kroah-Hartman

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

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

From: Henry Martin <[email protected]>

[ Upstream commit f4377bf85887f57b59abb5479f7660a81ffe4449 ]

TIPC group broadcast senders are blocked while a replicast still has outstanding member acks: tipc_group_bc_cong() returns true as long as grp->bc_ackers is non-zero, and clears *grp->open, which is what tipc_poll() uses to report EPOLLOUT (via tsk->group_is_open).

When the last outstanding acker departs before acking, tipc_group_delete_member() decrements grp->bc_ackers to zero but never restores *grp->open. As a result poll(EPOLLOUT) never fires again. A writer blocked in sendmsg() is only released if some other wakeup happens after the deletion: with TIPC_GROUP_MEMBER_EVTS the leave event delivery calls sk_data_ready() and wakes it, but without member events nothing does and it sleeps indefinitely, since the default send timeout is MAX_SCHEDULE_TIMEOUT.

Commit 99cc2a62e07a ("tipc: reject invalid and unexpected GRP_ACK_MSG to prevent bc_ackers underflow") already calls this out in its changelog as a pre-existing issue.

Restore the open state exactly on the 1->0 transition in the delete path, mirroring the GRP_ACK_MSG completion path, and invoke sk->sk_write_space() from tipc_sk_filter_rcv() when the group just became writable again.

Also make the ack accounting precise. The delete path used to test less(m->bc_acked, grp->bc_snd_nxt - 1), which also matches members that were never counted for the current replicast (JOINING/LEAVING members keep a stale bc_acked), and the GRP_ACK_MSG handler accepted an ack from any member whose bc_acked differed from the expected value. Either could zero bc_ackers on behalf of a member that owes nothing and silently void an ack still owed by a real acker. Track whether a member owes an ack for the current replicast in a new per-member bc_pending flag, set when the member is counted and cleared when its ack arrives, and use it both to accept an ack and to decide on deletion. bc_acked has no remaining user and is removed. Suggested by Tung Quang Nguyen.

This issue was discovered by Tencent CodeBuddy Security.

Fixes 2f487712b893 ("tipc: guarantee that group broadcast doesn't bypass group unicast")
---
 net/tipc/group.c  | 19 ++++++++++---------
 net/tipc/socket.c | 12 +++++++++++-
 2 files changed, 21 insertions(+), 10 deletions(-)
net/tipc/group.c +10 -9
index 0da7b27133949..a9ce1c7018b6c 100644
@@ -74,7 +74,7 @@ struct tipc_member {
 	u16 window;
 	u16 bc_rcv_nxt;
 	u16 bc_syncpt;
-	u16 bc_acked;
+	bool bc_pending;
 };
 
 struct tipc_group {
@@ -316,7 +316,6 @@ static struct tipc_member *tipc_group_create_member(struct tipc_group *grp,
 	m->node = node;
 	m->port = port;
 	m->instance = instance;
-	m->bc_acked = grp->bc_snd_nxt - 1;
 	ret = tipc_group_add_to_tree(grp, m);
 	if (ret < 0) {
 		kfree(m);
@@ -340,9 +339,12 @@ static void tipc_group_delete_member(struct tipc_group *grp,
 	rb_erase(&m->tree_node, &grp->members);
 	grp->member_cnt--;
 
-	/* Check if we were waiting for replicast ack from this member */
-	if (grp->bc_ackers && less(m->bc_acked, grp->bc_snd_nxt - 1))
-		grp->bc_ackers--;
+	/* If this member owed an ack for the current replicast and it
+	 * was the last one, restore the open state so blocked broadcast
+	 * senders can proceed.
+	 */
+	if (grp->bc_ackers && m->bc_pending && !--grp->bc_ackers)
+		*grp->open = true;
 
 	list_del_init(&m->list);
 	list_del_init(&m->small_win);
@@ -394,7 +396,6 @@ void tipc_group_update_member(struct tipc_member *m, int len)
 
 void tipc_group_update_bc_members(struct tipc_group *grp, int len, bool ack)
 {
-	u16 prev = grp->bc_snd_nxt - 1;
 	struct tipc_member *m;
 	struct rb_node *n;
 	u16 ackers = 0;
@@ -403,8 +404,8 @@ void tipc_group_update_bc_members(struct tipc_group *grp, int len, bool ack)
 		m = container_of(n, struct tipc_member, tree_node);
 		if (tipc_group_is_receiver(m)) {
 			tipc_group_update_member(m, len);
-			m->bc_acked = prev;
 			ackers++;
+			m->bc_pending = ack;
 		}
 	}
 
@@ -800,9 +801,9 @@ void tipc_group_proto_rcv(struct tipc_group *grp, bool *usr_wakeup,
 		if (!m || !grp->bc_ackers)
 			return;
 		acked = msg_grp_bc_acked(hdr);
-		if (acked != grp->bc_snd_nxt || m->bc_acked == acked)
+		if (acked != grp->bc_snd_nxt || !m->bc_pending)
 			return;
-		m->bc_acked = acked;
+		m->bc_pending = false;
 		if (--grp->bc_ackers)
 			return;
 		list_del_init(&m->small_win);
net/tipc/socket.c +11 -1
index 0ae02e8e11ff5..f9e9f05657e02 100644
@@ -2355,8 +2355,18 @@ static void tipc_sk_filter_rcv(struct sock *sk, struct sk_buff *skb,
 	if (unlikely(!msg_isdata(hdr)))
 		tipc_sk_proto_rcv(sk, &inputq, xmitq);
 
-	if (unlikely(grp))
+	if (unlikely(grp)) {
+		bool was_open = tsk->group_is_open;
+
 		tipc_group_filter_msg(grp, &inputq, xmitq);
+		/* A departing member may have held the last outstanding
+		 * replicast ack, which can restore the open state inside
+		 * tipc_group_filter_msg(); wake up senders blocked in
+		 * poll()/write() if the group just became writable.
+		 */
+		if (!was_open && tsk->group_is_open)
+			sk->sk_write_space(sk);
+	}
 
 	if (unlikely(!grp) && mtyp == TIPC_MCAST_MSG)
 		tipc_mcast_filter_msg(net, &tsk->mc_method.deferredq, &inputq);
Signature · 1 line
2.53.0
author maintainer
#1415 lore raw

PATCH 1411/1536 exportfs: Release the get_name() directory file synchronously

In reply to Greg Kroah-Hartman

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

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

From: Chuck Lever <[email protected]>

[ Upstream commit 49184daab01674ca400cbef58ee101dba6dbbb9d ]

get_name() opens the parent directory with dentry_open() and releases it with fput(). From a kernel thread, fput() defers the final __fput() to the delayed_fput work item. NFSD threads are kernel threads, and NFSD reaches get_name() through exportfs_decode_fh() whenever a file handle's dentry is not connected to the root.

On a filesystem with more directories than the dcache retains, nearly every READDIRPLUS needs a reconnect. The deferred releases arrive faster than the work item retires them, and each pending file pins the directory's readdir state. On ext4 that state is the htree fname cache for the last leaf block read. A 64-thread NFSv3 server under a parallel tree walk showed unreclaimable slab growing by about 90 MB per second, and the same workload on a 5.15 kernel ended in a global OOM.

Commit 5ff318f645eb ("nfsd: use __fput_sync() to avoid delayed closing of files.") stopped NFSD's own closes from feeding the delayed_fput queue but did not cover the exportfs reconnect path.

Release the file with __fput_sync(). get_name() opened the file itself, read-only, on a directory, so __fput() involves nothing that could wait on the caller.

Note for LTS backports: Kernels before v6.6 need the __fput_sync() call guarded by current->flags & PF_KTHREAD, with a plain fput() otherwise.

---
 fs/exportfs/expfs.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
fs/exportfs/expfs.c +5 -1
index 4f2dd4ab44864..65126f6624309 100644
@@ -337,7 +337,11 @@ static int get_name(const struct path *path, char *name, struct dentry *child)
 	}
 
 out_close:
-	fput(file);
+	/*
+	 * @file is the read-only directory opened above, so __fput()
+	 * cannot block on anything the caller holds.
+	 */
+	__fput_sync(file);
 out:
 	return error;
 }
Signature · 1 line
2.53.0
author maintainer
#1416 lore raw

PATCH 1412/1536 statmount: dont copy the reserved empty string past the buffer

In reply to Greg Kroah-Hartman

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

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

From: Christian Brauner <[email protected]>

[ Upstream commit 11eef75006819f4e71d04ca2b9a1fb1580854a55 ]

statmount_string() reserves an empty string at the start of the seq buffer before it calls the handler for the requested string. That's what the offsets of unset strings point to since commit e52e97f09fb6 ("statmount: let unset strings be empty").

If the handler emits nothing the early return from commit 75ead69a7173 ("fs: don't let statmount return empty strings") skips the size check against the caller's buffer. Back then an empty emission meant an empty seq buffer and there was nothing to copy. Now the reserved NUL byte is there and copy_statmount_to_user() copies it to buf + sizeof(struct statmount) no matter how small bufsize is.

So request a string that may turn out empty with a buffer that's smaller than struct statmount and the kernel writes one zero byte past the caller's buffer and reports a size that's larger than the buffer. STATMOUNT_MNT_UIDMAP or STATMOUNT_MNT_GIDMAP on a mount that isn't idmapped will do, so will STATMOUNT_FS_SUBTYPE on anything but fuse or STATMOUNT_OPT_ARRAY on a filesystem without ->show_options(). None of this needs privileges. The byte only lands in the caller's own address space but that's still not ok.

prepare_kstatmount() already refuses a buffer of exactly sizeof(struct statmount) for string requests. A smaller buffer can't hold a string either and it can't even hold the reserved empty string. So refuse any buffer that isn't larger than the fixed part. That's also what the uapi header says: string requests need space after the fixed part of the structure.

Reproducer, unprivileged, on any mount that isn't idmapped:

    #define _GNU_SOURCE
    #include <errno.h>
    #include <fcntl.h>
    #include <stdint.h>
    #include <stdio.h>
    #include <string.h>
    #include <sys/mman.h>
    #include <sys/syscall.h>
    #include <unistd.h>
    #define STATMOUNT_FS_SUBTYPE	0x00000100U
    #define STATMOUNT_MNT_UIDMAP	0x00002000U
    #define STATX_MNT_ID_UNIQUE	0x00004000U
    #define SM_SIZE			512 /* sizeof(struct statmount) */
    struct mnt_id_req {
    	uint32_t size, mnt_ns_fd;
    	uint64_t mnt_id, param, mnt_ns_id;
    };
    static uint64_t root_mnt_id(void)
    {
    	unsigned char stx[256]; /* struct statx, stx_mnt_id at offset 144 */
    	uint64_t id;
    	if (syscall(__NR_statx, AT_FDCWD, "/", 0, STATX_MNT_ID_UNIQUE, stx))
    		_exit(1);
    	memcpy(&id, stx + 144, sizeof(id));
    	return id;
    }
    static void probe(uint64_t mnt_id, uint64_t mask, int guard)
    {
    	struct mnt_id_req req = {
    		.size = sizeof(req), .mnt_id = mnt_id, .param = mask,
    	};
    	long page = sysconf(_SC_PAGESIZE);
    	unsigned char *map, *buf;
    	uint32_t size;
    	long ret;
    	map = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE,
    		   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    	memset(map, 0xaa, 2 * page);
    	/* 100 byte buffer ending right at the page boundary */
    	buf = map + page - 100;
    	if (guard)
    		mprotect(map + page, page, PROT_NONE);
    	errno = 0;
    	ret = syscall(__NR_statmount, &req, buf, 100, 0);
    	printf("mask 0x%04llx%s: ret %ld errno %d", (unsigned long long)mask,
    	       guard ? " guard page" : "", ret, errno);
    	if (!guard) {
    		memcpy(&size, buf, sizeof(size));
    		printf(", size 0x%x, byte[%d] 0x%02x", size, SM_SIZE,
    		       buf[SM_SIZE]);
    	}
    	printf("\n");
    	munmap(map, 2 * page);
    }
    int main(void)
    {
    	uint64_t id = root_mnt_id();
    	probe(id, STATMOUNT_MNT_UIDMAP, 0);
    	probe(id, STATMOUNT_FS_SUBTYPE, 0);
    	probe(id, STATMOUNT_MNT_UIDMAP, 1);
    	return 0;
    }

Before, on 7.3.0-rc7-00252-g4e3259b08c54 (vfs.fixes) in a VM, the same on a distro 7.1.13:

    mask 0x2000: ret 0 errno 0, size 0x65, byte[512] 0x00
    mask 0x0100: ret 0 errno 0, size 0x65, byte[512] 0x00
    mask 0x2000 guard page: ret -1 errno 14

After:

    mask 0x2000: ret -1 errno 75, size 0xaaaaaaaa, byte[512] 0xaa
    mask 0x0100: ret -1 errno 75, size 0xaaaaaaaa, byte[512] 0xaa
    mask 0x2000 guard page: ret -1 errno 75
---
 fs/namespace.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/namespace.c +2 -1
index d02a4bbb75d37..64b431555827b 100644
@@ -5385,7 +5385,8 @@ static int prepare_kstatmount(struct kstatmount *ks, struct mnt_id_req *kreq,
 	ks->bufsize = bufsize;
 
 	if (ks->mask & STATMOUNT_STRING_REQ) {
-		if (bufsize == sizeof(ks->sm))
+		/* Even the reserved empty string needs room past the fixed part. */
+		if (bufsize <= sizeof(ks->sm))
 			return -EOVERFLOW;
 
 		ks->seq.buf = kvmalloc(seq_size, GFP_KERNEL_ACCOUNT);
Signature · 1 line
2.53.0
author maintainer
#1417 lore raw

PATCH 1413/1536 listmount: dont wrap around with a U64_MAX cursor

In reply to Greg Kroah-Hartman

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

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

From: Christian Brauner <[email protected]>

[ Upstream commit 95a5412022e437691f4eb1924ff249d9044f5ed1 ]

do_listmount() takes the last mount id the caller saw and looks up the first mount after it by searching for last_mnt_id + 1. With U64_MAX that wraps around to zero and the search finds the first mount in the namespace. So a cursor at the largest possible id restarts the listing from the beginning instead of ending it. A cursor of U64_MAX - 1 correctly returns nothing.

No mount will ever have that id. Mount ids come from a counter that starts at MNT_UNIQUE_ID_OFFSET + 1 and a caller that only feeds back ids it got from us can't hit this. It's still wrong. Nothing can come after the largest possible id so return no entries for it, just like for any other cursor past the last mount.

The reverse direction isn't affected. A cursor of zero is special-cased and anything else is larger than MNT_UNIQUE_ID_OFFSET so last_mnt_id - 1 can't underflow.

Reproducer, unprivileged:

    #define _GNU_SOURCE
    #include <errno.h>
    #include <stdint.h>
    #include <stdio.h>
    #include <sys/syscall.h>
    #include <unistd.h>
    #define LSMT_ROOT 0xffffffffffffffffULL
    struct mnt_id_req {
    	uint32_t size, mnt_ns_fd;
    	uint64_t mnt_id, param, mnt_ns_id;
    };
    static void list(uint64_t cursor)
    {
    	struct mnt_id_req req = {
    		.size = sizeof(req), .mnt_id = LSMT_ROOT, .param = cursor,
    	};
    	uint64_t ids[8];
    	long ret;
    	errno = 0;
    	ret = syscall(__NR_listmount, &req, ids, 8, 0);
    	printf("cursor %llu: ret %ld errno %d", (unsigned long long)cursor,
    	       ret, errno);
    	for (long i = 0; i < ret && i < 1; i++)
    		printf("%s%llu", i ? "," : " ids ", (unsigned long long)ids[i]);
    	printf("%s\n", ret > 1 ? ",..." : "");
    }
    int main(void)
    {
    	list(0);
    	list(UINT64_MAX - 1);
    	list(UINT64_MAX);
    	return 0;
    }

Before, on 7.3.0-rc7-00252-g4e3259b08c54 (vfs.fixes) in a VM:

    cursor 0: ret 5 errno 0 ids 2147483651,...
    cursor 18446744073709551614: ret 0 errno 0
    cursor 18446744073709551615: ret 5 errno 0 ids 2147483651,...

After:

    cursor 0: ret 5 errno 0 ids 2147483651,...
    cursor 18446744073709551614: ret 0 errno 0
    cursor 18446744073709551615: ret 0 errno 0
---
 fs/namespace.c | 2 ++
 1 file changed, 2 insertions(+)
fs/namespace.c +2 -0
index 64b431555827b..fa611381c3a35 100644
@@ -5565,6 +5565,8 @@ static ssize_t do_listmount(struct klistmount *kls, bool reverse)
 	} else {
 		if (reverse)
 			first = mnt_find_id_at_reverse(ns, last_mnt_id - 1);
+		else if (last_mnt_id == U64_MAX)
+			first = NULL; /* nothing comes after the largest id */
 		else
 			first = mnt_find_id_at(ns, last_mnt_id + 1);
 	}
Signature · 1 line
2.53.0
author maintainer
#1418 lore raw

PATCH 1414/1536 ucount: take the rlimit reference before checking the limit

In reply to Greg Kroah-Hartman

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

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

From: Nickolai Zeldovich <[email protected]>

[ Upstream commit b14fcabd34e02c40f72d3cd1e9bd4fd18df40ff1 ]

inc_rlimit_get_ucounts() takes the reference that pins a ucounts level while its rlimit count is non-zero only in the walk whose increment is the 0 -> 1 transition, and only after that walk passed the limit check. A walk that raises the count from zero and then fails the limit backs out without the reference, while a concurrent walk that raised it past one keeps its increment and never takes one either:

CPU0 (obeys the limit) CPU1 (overrides it)
new = add_return(1) -> 1

                                      new = add_return(1) -> 2
                                      new != 1, no get_ucounts()

new > max -> dec_unwind
sub_return(1) -> 1 (no put)

The count is 1 with no reference held. When CPU1 drops its charge, dec_rlimit_put_ucounts() takes the count to 0 and puts a reference nobody took, which frees the live struct ucounts, and the user_namespace it pins, with kfree_rcu(). The mirror interleaving leaks the reference instead.

An unprivileged user reaches this on a kernel with CONFIG_USER_NS=y: in a user namespace with RLIMIT_SIGPENDING 0, one process taking synchronous SIGSEGVs (forced, so override_rlimit is set) races a second process in the same namespace and uid that queues real-time signals, which obey the limit. The two hold different sighand->siglock but charge the same per-namespace SIGPENDING ucounts. Unpatched, with rcuref debugging:

rcuref - imbalanced put()

  WARNING: lib/rcuref.c:266 at rcuref_put_slowpath+0xf4/0x120
   put_ucounts+0x5a/0x180
   do_dec_rlimit_put_ucounts+0x70/0x90
   __sigqueue_free+0x33/0xc0
   get_signal+0x56f/0xd20
   arch_do_signal_or_restart+0x87/0x380
   irqentry_exit+0x243/0x650
   asm_exc_page_fault+0x26/0x30

Take the reference on the 0 -> 1 transition before the limit is checked, so the walk that raises the count from zero owns that level's reference even when its request is rejected, and unwind a rejected level through do_dec_rlimit_put_ucounts(), which releases the reference when the count returns to 0. The get_ucounts() failure path is unchanged. With the patch the same interleaving, forced some 80000 times in a KASAN build, produces no warning and no KASAN report.

---
 kernel/ucount.c | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)
kernel/ucount.c +12 -9
index 8340f767c1aea..b731d13e6b766 100644
@@ -317,23 +317,26 @@ long inc_rlimit_get_ucounts(struct ucounts *ucounts, enum rlimit_type type,
 
 	for (iter = ucounts; iter; iter = iter->ns->ucounts) {
 		long new = atomic_long_add_return(1, &iter->rlimit[type]);
-		if (new < 0 || new > max)
+		/*
+		 * Take the extra reference on the 0 -> 1 transition before the
+		 * limit check: a rejected walk must not leave a concurrent one
+		 * holding the surviving increment with no reference.
+		 */
+		if (new == 1 && !get_ucounts(iter))
 			goto dec_unwind;
+		if (new < 0 || new > max) {
+			/* undo iter too, releasing the reference taken above */
+			do_dec_rlimit_put_ucounts(ucounts, iter->ns->ucounts, type);
+			return 0;
+		}
 		if (iter == ucounts)
 			ret = new;
 		if (!override_rlimit)
 			max = get_userns_rlimit_max(iter->ns, type);
-		/*
-		 * Grab an extra ucount reference for the caller when
-		 * the rlimit count was previously 0.
-		 */
-		if (new != 1)
-			continue;
-		if (!get_ucounts(iter))
-			goto dec_unwind;
 	}
 	return ret;
 dec_unwind:
+	/* get_ucounts() failed for iter: undo iter without a put */
 	dec = atomic_long_sub_return(1, &iter->rlimit[type]);
 	WARN_ON_ONCE(dec < 0);
 	do_dec_rlimit_put_ucounts(ucounts, iter, type);
Signature · 1 line
2.53.0
author maintainer
#1419 lore raw

PATCH 1415/1536 cpufreq: intel_pstate: cancel HWP notify work in driver cleanup

In reply to Greg Kroah-Hartman

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

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

From: Tristan Madani <[email protected]>

[ Upstream commit 0ffc7534a210105ba973167a5b86d5ab39d4031f ]

intel_pstate_driver_cleanup() frees per-CPU data without cancelling the pending HWP notify delayed work. If hwp_notify_work is still scheduled or running when the struct is freed, the work function accesses freed memory via container_of().

Call intel_pstate_disable_hwp_interrupt() before kfree() to disable the interrupt source and cancel the pending work, matching the pattern used in intel_pstate_suspend() and intel_pstate_hwp_offline().

Fixes d845cd901b28 ("cpufreq: intel_pstate: Support highest performance change interrupt")
Cc All applicable <[email protected]>
[ rjw: Fixed the Fixes: tag ]
---
 drivers/cpufreq/intel_pstate.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/cpufreq/intel_pstate.c +2 -0
index f1910f9109f01..8cb10f99a84be 100644
@@ -3368,6 +3368,8 @@ static void intel_pstate_driver_cleanup(void)
 			if (intel_pstate_driver == &intel_pstate)
 				intel_pstate_clear_update_util_hook(cpu);
 
+			intel_pstate_disable_hwp_interrupt(all_cpu_data[cpu]);
+
 			kfree(all_cpu_data[cpu]);
 			WRITE_ONCE(all_cpu_data[cpu], NULL);
 		}
Signature · 1 line
2.53.0
author maintainer
#1420 lore raw

PATCH 1416/1536 i2c: acpi: Fix adapter reference leak in i2c_acpi_new_device_by_fwnode()

In reply to Greg Kroah-Hartman

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

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

From: Ma Ke <[email protected]>

[ Upstream commit a65917d0a22f9b10694853b725f9cd399fc3ef4d ]

i2c_acpi_new_device_by_fwnode() obtains an i2c_adapter through i2c_acpi_find_adapter_by_handle(). That helper uses bus_find_device() internally, so it returns the adapter with a reference held:

        adapter = i2c_verify_adapter(dev);
        if (!adapter)
                put_device(dev);

        return adapter;

The reference is only put on the failure path inside that helper. The caller owns it otherwise. i2c_acpi_new_device_by_fwnode() never drops it, neither on the -EPROBE_DEFER path nor after i2c_new_client_device(), so every call leaks one reference on the adapter and the adapter can never be released.

i2c_new_client_device() does not consume that reference. It registers the new client with the adapter as its parent, and device_add() takes its own reference on the parent, which device_del() releases when the client goes away. The reference obtained by the lookup is a separate one and has to be dropped here.

i2c_acpi_notify() in the same file already does exactly this. It takes the adapter from the same helper, registers the client through i2c_acpi_register_device(), which calls i2c_new_client_device(), and then puts the reference.

i2c_new_client_device() gives the client its own reference on the adapter, so ours can be dropped unconditionally.

Found by code review.

Fixes 605f8fc22442 ("i2c: core: Add new i2c_acpi_new_device helper function")
Cc <[email protected]> # v4.12+
---
 drivers/i2c/i2c-core-acpi.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/i2c/i2c-core-acpi.c +5 -1
index b74f41b9515ae..731808ea5c3e7 100644
@@ -545,6 +545,7 @@ struct i2c_client *i2c_acpi_new_device_by_fwnode(struct fwnode_handle *fwnode,
 {
 	struct i2c_acpi_lookup lookup;
 	struct i2c_adapter *adapter;
+	struct i2c_client *client;
 	struct acpi_device *adev;
 	LIST_HEAD(resource_list);
 	int ret;
@@ -572,7 +573,10 @@ struct i2c_client *i2c_acpi_new_device_by_fwnode(struct fwnode_handle *fwnode,
 	if (!adapter)
 		return ERR_PTR(-EPROBE_DEFER);
 
-	return i2c_new_client_device(adapter, info);
+	client = i2c_new_client_device(adapter, info);
+	put_device(&adapter->dev);
+
+	return client;
 }
 EXPORT_SYMBOL_GPL(i2c_acpi_new_device_by_fwnode);
 
Signature · 1 line
2.53.0
author maintainer
#1421 lore raw

PATCH 1417/1536 i2c: designware: queue only one read command for block reads

In reply to Greg Kroah-Hartman

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

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

From: Navon John Lukose <[email protected]>

[ Upstream commit 73dae605cad7921800677d982bfaeb81cc930dec ]

i2c_dw_xfer_msg() pre-queues up to rx_fifo_depth read commands based on the initial msg.len. For I2C_M_RECV_LEN transfers the real length is unknown until the first byte arrives and i2c_dw_recv_len() runs. When a large initial length is passed, the surplus pre-queued reads leave rx_outstanding non-zero after i2c_dw_recv_len() adjusts msg.len, so the completion condition is never met and the transfer times out. In a loop, this repeatedly times out the controller and disrupts unrelated driver-bound devices on the same adapter.

Queue only one read command while I2C_M_RECV_LEN is pending. i2c_dw_recv_len() re-enables TX_EMPTY, and the rest are queued once the device-reported length is known.

Fixes c3ae106050b9 ("i2c: designware: Implement support for SMBus block read and write")
Cc <[email protected]> # v4.10+
---
 drivers/i2c/busses/i2c-designware-master.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/i2c/busses/i2c-designware-master.c +8 -0
index 196bb073c6bcc..b2e916ebb5a77 100644
@@ -495,6 +495,14 @@ i2c_dw_xfer_msg(struct dw_i2c_dev *dev)
 				if (dev->rx_outstanding >= dev->rx_fifo_depth)
 					break;
 
+				/*
+				 * For block reads, queue only the length
+				 * byte until i2c_dw_recv_len() runs.
+				 */
+				if ((flags & I2C_M_RECV_LEN) &&
+				    buf_len < msgs[dev->msg_write_idx].len)
+					break;
+
 				regmap_write(dev->map, DW_IC_DATA_CMD,
 					     cmd | 0x100);
 				rx_limit--;
Signature · 1 line
2.53.0
author maintainer
#1422 lore raw

PATCH 1418/1536 tpm: tpm_nsc: fix NULL pointer dereference on init failure

In reply to Greg Kroah-Hartman

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

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

From: Pei Xiao <[email protected]>

[ Upstream commit 1900449684cf71427a51e0bb1d7914c0c8b39152 ]

tpm_nsc_remove() is used as the release callback of the hand-created platform device and dereferences the chip drvdata unconditionally. If init fails before tpmm_chip_alloc() (e.g. request_region() cannot claim the ports), the error path drops the last device reference and the release callback runs with chip == NULL, crashing module init.

Return early when the chip has not been created yet.

---
 drivers/char/tpm/tpm_nsc.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm_nsc.c +6 -1
index 0f62bbc940daa..b165b274680d6 100644
@@ -258,7 +258,12 @@ static struct platform_device *pdev = NULL;
 static void tpm_nsc_remove(struct device *dev)
 {
 	struct tpm_chip *chip = dev_get_drvdata(dev);
-	struct tpm_nsc_priv *priv = dev_get_drvdata(&chip->dev);
+	struct tpm_nsc_priv *priv;
+
+	if (!chip)
+		return;
+
+	priv = dev_get_drvdata(&chip->dev);
 
 	tpm_chip_unregister(chip);
 	release_region(priv->base, 2);
Signature · 1 line
2.53.0
author maintainer
#1423 lore raw

PATCH 1419/1536 tpm: tpm_nsc: stop using the cleanup callback as dev.release

In reply to Greg Kroah-Hartman

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

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

From: Pei Xiao <[email protected]>

[ Upstream commit df0ef271087623439a1e900f323ed2a57204706d ]

tpm_nsc_remove() is called explicitly from cleanup_nsc() and also runs as the platform device release callback on the final platform_device_put(), so the cleanup executes twice on module exit; the second invocation operates on a chip that has already been freed by the devm cleanup, and the I/O region is released twice.

Overwriting the release callback installed by platform_device_alloc() also keeps platform_device_release() from running, leaking the platform object allocation.

Leave the default release callback in place; the explicit call in cleanup_nsc() remains the single cleanup point.

---
 drivers/char/tpm/tpm_nsc.c | 1 -
 1 file changed, 1 deletion(-)
drivers/char/tpm/tpm_nsc.c +0 -1
index b165b274680d6..2f715c195b50e 100644
@@ -326,7 +326,6 @@ static int __init init_nsc(void)
 
 	pdev->num_resources = 0;
 	pdev->dev.driver = &nsc_drv.driver;
-	pdev->dev.release = tpm_nsc_remove;
 
 	if ((rc = platform_device_add(pdev)) < 0)
 		goto err_put_dev;
Signature · 1 line
2.53.0
author maintainer
#1424 lore raw

PATCH 1420/1536 tpm: fix zero-length read discarding the pending response

In reply to Greg Kroah-Hartman

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

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

From: Pei Xiao <[email protected]>

[ Upstream commit 6fc1b05077b8ac7c3193616f0bc419f6185988c6 ]

POSIX requires that a read() with a count of zero returns zero and has no other effects. tpm_common_read() treats such a call as a consumed response: it marks the pending response as read and drops it, so the response can never be retrieved; subsequent reads return zero and the next write() is allowed to overwrite the response buffer, silently breaking the command/response pairing of the TPM character devices.

Return early when the caller passes a zero count, leaving any pending response untouched for the next read. A zero-length read will not report a deferred asynchronous error; POSIX permits read() to skip error detection for a zero count.

---
 drivers/char/tpm/tpm-dev-common.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/char/tpm/tpm-dev-common.c +3 -0
index 48ff87444f851..1bfdcb9794e20 100644
@@ -134,6 +134,9 @@ ssize_t tpm_common_read(struct file *file, char __user *buf,
 	ssize_t ret_size = 0;
 	int rc;
 
+	if (!size)
+		return 0;
+
 	mutex_lock(&priv->buffer_mutex);
 
 	if (priv->response_length) {
Signature · 1 line
2.53.0
author maintainer
#1425 lore raw

PATCH 1421/1536 gpiolib: dont report -ENOMEM for a requested line without a label

In reply to Greg Kroah-Hartman

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

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

From: Adrian Ambrozewicz <[email protected]>

[ Upstream commit dae739137441667d67fbfcc4d303a0ecc6618662 ]

gpiod_request_commit() sets GPIOD_FLAG_REQUESTED, calls ->request() and only then sets the label. A line in between has no label, so gpiochip_dup_line_label() passes NULL to kstrdup() and returns ERR_PTR(-ENOMEM), which for_each_hwgpio() then passes to kfree():

  BUG: unable to handle page fault for address: ffcc73074355ffc8
  Call Trace:
   gpio_sim_dbg_show
   gpiolib_seq_show
   seq_read_iter

Return NULL for such a line, as for an unrequested one.

Reproduced with gpio-sim: reading /sys/kernel/debug/gpio in a loop while lines are requested and released oopses within seconds; with this change, 100000 cycles pass.

---
 drivers/gpio/gpiolib.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/gpio/gpiolib.c +6 -1
index 115bf569dbdd0..02a322f8330c2 100644
@@ -2471,6 +2471,7 @@ void gpiod_free(struct gpio_desc *desc)
 char *gpiochip_dup_line_label(struct gpio_chip *gc, unsigned int offset)
 {
 	struct gpio_desc *desc;
+	const char *name;
 	char *label;
 
 	desc = gpiochip_get_desc(gc, offset);
@@ -2482,7 +2483,11 @@ char *gpiochip_dup_line_label(struct gpio_chip *gc, unsigned int offset)
 
 	guard(srcu)(&desc->gdev->desc_srcu);
 
-	label = kstrdup(gpiod_get_label(desc), GFP_KERNEL);
+	name = gpiod_get_label(desc);
+	if (!name)
+		return NULL;
+
+	label = kstrdup(name, GFP_KERNEL);
 	if (!label)
 		return ERR_PTR(-ENOMEM);
 
Signature · 1 line
2.53.0