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 11 of 11

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

PATCH 1422/1536 parisc: eisa_enumerator: Fix out-of-bounds reads of the EEPROM buffer

In reply to Greg Kroah-Hartman

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

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

From: Jean Delu <[email protected]>

[ Upstream commit c0a3e153804f0c14f4159ddbd2b73483c9cb3577 ]

eisa_enumerator() trusts the contents of the EISA EEPROM.  The number of slots is read from the EEPROM header and used to access the slot records at HPEE_SLOT_INFO(i) = 20 + 48*i within the fixed-size eeprom_buf (HPEE_MAX_LENGTH, 8192 bytes) without any bound check.  As struct eeprom_eisa_slot_info is 48 bytes, only 170 records fit into the buffer, but num_slots is a u8 and may be up to 255, so a corrupted EEPROM makes the code read up to about 4 kB past the end of the buffer (e.g. record 254 is accessed at offset 20 + 48*254 = 12212).

parse_slot_config() has the same kind of problem: it clamps config_data_length against HPEE_MAX_LENGTH but does not take config_data_offset into account, so the parser can walk past the end of the buffer even when the offset itself is valid.

Clamp the number of slots so that all slot records fit into the buffer, and hand the number of bytes actually available to parse_slot_config() and bound the parse by it.

---
 drivers/parisc/eisa_enumerator.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
drivers/parisc/eisa_enumerator.c +12 -3
index f0cb31198a8f0..aa41d3abc6c22 100644
@@ -311,6 +311,7 @@ static int configure_function(const unsigned char *buf, int *more)
 
 static int parse_slot_config(int slot,
 			     const unsigned char *buf,
+			     unsigned int buflen,
 			     struct eeprom_eisa_slot_info *es, 
 			     struct resource *io_parent,
 			     struct resource *mem_parent)
@@ -333,8 +334,8 @@ static int parse_slot_config(int slot,
 	printk(KERN_INFO "EISA slot %d: %s %s ", 
 	       slot, board, es->flags&HPEE_FLAG_BOARD_IS_ISA ? "ISA" : "EISA");
 	
-	maxlen = es->config_data_length < HPEE_MAX_LENGTH ?
-			 es->config_data_length : HPEE_MAX_LENGTH;
+	/* never parse beyond the data that is actually in the buffer */
+	maxlen = min_t(unsigned int, es->config_data_length, buflen);
 	while ((pos < maxlen) && (num_func <= es->num_functions)) {
 		pos+=configure_function(buf+pos, &function_len); 
 		
@@ -491,6 +492,13 @@ int eisa_enumerator(unsigned long eeprom_addr,
 	printk(KERN_INFO "Enumerating EISA bus\n");
 		    	
 	eh = (struct eeprom_header*)(eeprom_buf);
+	/*
+	 * The EEPROM contents are not to be trusted: clamp the number of
+	 * slots so that all slot records fit into eeprom_buf.
+	 */
+	eh->num_slots = min_t(u8, eh->num_slots,
+				(HPEE_MAX_LENGTH - sizeof(*eh)) /
+				sizeof(struct eeprom_eisa_slot_info));
 	for (i=0;i<eh->num_slots;i++) {
 		struct eeprom_eisa_slot_info *es;
 		
@@ -503,7 +511,8 @@ int eisa_enumerator(unsigned long eeprom_addr,
 		
 		if (es->config_data_offset < HPEE_MAX_LENGTH) {
 			if (parse_slot_config(i+1, &eeprom_buf[es->config_data_offset],
-					      es, io_parent, mem_parent)) {
+						HPEE_MAX_LENGTH - es->config_data_offset,
+						es, io_parent, mem_parent)) {
 				return -1;
 			}
 		} else {
Signature · 1 line
2.53.0
author maintainer
#1427 lore raw

PATCH 1423/1536 ASoC: tlv320aic32x4: Prevent division by zero in divider callbacks

In reply to Greg Kroah-Hartman

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

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

From: Alex Kazinsky <[email protected]>

[ Upstream commit 8cf9607d2d855629260fc78e6b54ea7a98525708 ]

A zero rate requested through clk_set_rate() or clk_round_rate() reaches clk_aic32x4_div_determine_rate() when the minimum rate is zero. Clamping the requested rate to the allowed range leaves it unchanged, causing division by zero when calculating the divisor.

A zero parent rate can also cause division by zero in determine_rate(). For example, if reading a parent divider's register fails, clk_aic32x4_div_recalc_rate() returns zero, which the clock framework caches as the parent's rate. A subsequent rate request for a child divider receives this value in best_parent_rate. With a nonzero requested rate, the calculated divisor is zero. It passes the existing upper-bound check and causes division by zero in the resulting rate calculation.

The set_rate callback can receive a zero rate when an ancestor's rate changes. clk_calc_subtree() calculates descendant rates through recalc_rate() without calling their determine_rate callbacks. If reading a descendant divider's register fails, clk_aic32x4_div_recalc_rate() returns zero. This becomes the descendant's new_rate, which clk_change_rate() passes to clk_aic32x4_div_set_rate(), causing division by zero.

Reject zero rates in both callbacks and reject a zero divisor in clk_aic32x4_div_determine_rate().

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

Fixes a51b50062091 ("ASoC: tlv320aic32x4: Model DAC/ADC dividers in CCF")
---
 sound/soc/codecs/tlv320aic32x4-clk.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
sound/soc/codecs/tlv320aic32x4-clk.c +7 -1
index 5c0a76a4a106b..1a815de909097 100644
@@ -320,6 +320,9 @@ static int clk_aic32x4_div_set_rate(struct clk_hw *hw, unsigned long rate,
 	struct clk_aic32x4 *div = to_clk_aic32x4(hw);
 	u8 divisor;
 
+	if (!rate)
+		return -EINVAL;
+
 	divisor = DIV_ROUND_UP(parent_rate, rate);
 	if (divisor > AIC32X4_DIV_MAX)
 		return -EINVAL;
@@ -333,8 +336,11 @@ static int clk_aic32x4_div_determine_rate(struct clk_hw *hw,
 {
 	unsigned long divisor;
 
+	if (!req->rate)
+		return -EINVAL;
+
 	divisor = DIV_ROUND_UP(req->best_parent_rate, req->rate);
-	if (divisor > AIC32X4_DIV_MAX)
+	if (!divisor || divisor > AIC32X4_DIV_MAX)
 		return -EINVAL;
 
 	req->rate = DIV_ROUND_UP(req->best_parent_rate, divisor);
Signature · 1 line
2.53.0
author maintainer
#1428 lore raw

PATCH 1424/1536 i2c: mt7621: fix copying uninitialized kernel stack with reduced page_len

In reply to Greg Kroah-Hartman

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

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

From: Christian Marangi <[email protected]>

[ Upstream commit b7fd977fec0d3f2bdd4f13bb59949c817a365652 ]

When a page_len is less than 5 bytes in mtk_i2c_xfer, uninitialized kernel stack data is copied and written to REG_SM0D1_REG. Equally on the read part, an unnecessary read is done.

Guard these extra copy/write and read for the page_len to fix leaking uninitialized stack memory.

Fixes d04913ec5f89 ("i2c: mt7621: Add MediaTek MT7621/7628/7688 I2C driver")
Cc <[email protected]> # v5.3+
---
 drivers/i2c/busses/i2c-mt7621.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/i2c/busses/i2c-mt7621.c +6 -3
index 23d417ff5e71c..9fbdd6c056e3e 100644
@@ -144,7 +144,6 @@ static int mtk_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
 	u16 addr;
 	int i, j, ret, len, page_len;
 	u32 cmd;
-	u32 data[2];
 
 	i2c = i2c_get_adapdata(adap);
 
@@ -190,6 +189,8 @@ static int mtk_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
 
 		/* transfer data */
 		for (len = pmsg->len, j = 0; len > 0; len -= 8, j += 8) {
+			u32 data[2] = { };
+
 			page_len = (len >= 8) ? 8 : len;
 
 			if (pmsg->flags & I2C_M_RD) {
@@ -198,7 +199,8 @@ static int mtk_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
 			} else {
 				memcpy(data, &pmsg->buf[j], page_len);
 				iowrite32(data[0], i2c->base + REG_SM0D0_REG);
-				iowrite32(data[1], i2c->base + REG_SM0D1_REG);
+				if (page_len > 4)
+					iowrite32(data[1], i2c->base + REG_SM0D1_REG);
 				cmd = SM0CTL1_WRITE;
 			}
 
@@ -208,7 +210,8 @@ static int mtk_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
 
 			if (pmsg->flags & I2C_M_RD) {
 				data[0] = ioread32(i2c->base + REG_SM0D0_REG);
-				data[1] = ioread32(i2c->base + REG_SM0D1_REG);
+				if (page_len > 4)
+					data[1] = ioread32(i2c->base + REG_SM0D1_REG);
 				memcpy(&pmsg->buf[j], data, page_len);
 			} else {
 				if (!(pmsg->flags & I2C_M_IGNORE_NAK)) {
Signature · 1 line
2.53.0
author maintainer
#1429 lore raw

PATCH 1425/1536 spi: zynq-qspi: fix address buffer corruption and support 4-byte address

In reply to Greg Kroah-Hartman

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

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

From: Pufan Jin <[email protected]>

[ Upstream commit dc5ca34f5e8dc10c566ef39aa3b1a201a17ca734 ]

In zynq_qspi_exec_mem_op(), when transmitting address bytes, the driver iterates over op->addr.nbytes and populates xqspi->txbuf[i]. However, xqspi->txbuf is never re-assigned before populating the address, meaning it still points to (u8 *)&op->cmd.opcode from the command phase.

This causes two severe issues:
1. Memory corruption: Writing into xqspi->txbuf writes past the opcode buffer on the stack (which was passed as const struct spi_mem_op *). If opcode is zero, xqspi->txbuf is uninitialized.
2. In zynq_qspi_supports_op(), operations with op->addr.nbytes > 3 are rejected. When paired with SPI NOR flashes larger than 16MB (such as Winbond W25Q256), spi_nor_spimem_check_read_pp_op() tests 4-byte address support, which fails and causes spi_nor_select_read() to drop all read capabilities, failing probe with -EINVAL (-22).

The Zynq-7000 QSPI controller hardware in manual I/O mode natively supports transmitting 1 to 4 address bytes via its TXD FIFO registers (ZYNQ_QSPI_TXD_00_00_OFFSET).

Fix this by introducing a local opaddr[4] buffer in zynq_qspi_exec_mem_op() and explicitly setting xqspi->txbuf = opaddr before populating address bytes. Also allow up to 4 address bytes in zynq_qspi_supports_op().

Fixes 67dca5e580f1 ("spi: spi-mem: Add support for Zynq QSPI controller")
---
 drivers/spi/spi-zynq-qspi.c | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)
drivers/spi/spi-zynq-qspi.c +7 -6
index 8c4f4345c1a93..1dcd67a7198bc 100644
@@ -229,11 +229,10 @@ static bool zynq_qspi_supports_op(struct spi_mem *mem,
 		return false;
 
 	/*
-	 * The number of address bytes should be equal to or less than 3 bytes.
+	 * The number of address bytes should be equal to or less than 4 bytes.
 	 */
-	if (op->addr.nbytes > 3)
+	if (op->addr.nbytes > 4)
 		return false;
-
 	return true;
 }
 
@@ -524,6 +523,7 @@ static int zynq_qspi_exec_mem_op(struct spi_mem *mem,
 				 const struct spi_mem_op *op)
 {
 	struct zynq_qspi *xqspi = spi_controller_get_devdata(mem->spi->controller);
+	u8 opaddr[4] __aligned(4);
 	int err = 0, i;
 	u8 *tmpbuf;
 
@@ -549,12 +549,13 @@ static int zynq_qspi_exec_mem_op(struct spi_mem *mem,
 	}
 
 	if (op->addr.nbytes) {
-		for (i = 0; i < op->addr.nbytes; i++) {
-			xqspi->txbuf[i] = op->addr.val >>
+		for (i = 0; i < op->addr.nbytes; i++)
+			opaddr[i] = op->addr.val >>
 					(8 * (op->addr.nbytes - i - 1));
-		}
 
 		reinit_completion(&xqspi->data_completion);
+		xqspi->txbuf = opaddr;
+
 		xqspi->rxbuf = NULL;
 		xqspi->tx_bytes = op->addr.nbytes;
 		xqspi->rx_bytes = op->addr.nbytes;
Signature · 1 line
2.53.0
author maintainer
#1430 lore raw

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

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang (Microsoft) <[email protected]>

[ Upstream commit 8ccd731b63a0183ca2b0e18f3ca15864b3f37eda ]

do_cpu_nanosleep() sleeps on a temporary k_itimer whose reference on the target's struct pid is taken by posix_cpu_timer_create() and dropped by posix_cpu_timer_del(). When a signal ends the sleep, the timer is disarmed with posix_cpu_timer_set(), but posix_cpu_timer_del() is only called for a result of 0 or TIMER_RETRY. If the target thread or process has exited in the meantime, timer_lock_sighand() finds no task, posix_cpu_timer_set() returns -ESRCH and the pid reference is leaked.

An unprivileged user can trigger this: sleep on the CPU clock of a thread, let that thread exit, then signal the sleeper. Each round leaks one struct pid. Repeating it exhausts unreclaimable slab memory within minutes:

Out of memory: Killed process 150 (poc) total-vm:789292kB, anon-rss:484kB

  Kernel panic - not syncing: System is deadlocked on memory

Fix this by also calling posix_cpu_timer_del() on -ESRCH. With the target gone, the deletion is safe. It finds no task either and only drops the pid reference.

---
 kernel/time/posix-cpu-timers.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/time/posix-cpu-timers.c +2 -2
index f0471fbe87288..33211c78d02a5 100644
@@ -1584,8 +1584,8 @@ static int do_cpu_nanosleep(const clockid_t which_clock, int flags,
 		 */
 		expires = cpu_timer_getexpires(&timer.it.cpu);
 		error = posix_cpu_timer_set(&timer, 0, &zero_it, &it);
-		if (!error) {
-			/* Timer is now unarmed, deletion can not fail. */
+		if (error != TIMER_RETRY) {
+			/* Unarmed or target gone (-ESRCH), deletion can not fail. */
 			posix_cpu_timer_del(&timer);
 		} else {
 			while (error == TIMER_RETRY) {
Signature · 1 line
2.53.0
author maintainer
#1431 lore raw

PATCH 1427/1536 timekeeping: Update offsets on sequence counter retry in ktime_get_update_offsets_now()

In reply to Greg Kroah-Hartman

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

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

From: Thomas Weißschuh (Schneider Electric) <[email protected]>

[ Upstream commit 6541fbc942f3b63bb8bd44e34eee6223e0abe719 ]

The sequence counter of the cwsseq target is modified during the sequence counter loop. If the loop retries, cwsseq will now match but the offsets contain the values from the previous loop iteration. These are not guaranteed to be consistent in themselves or with the current loops "now.

Save the target's original sequence counter value so that the update also happens on loop retries.

---
 kernel/time/timekeeping.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/time/timekeeping.c +2 -1
index 626fbb2a1a8cf..cac3a0df3a780 100644
@@ -2359,6 +2359,7 @@ ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
 				     ktime_t *offs_boot, ktime_t *offs_tai)
 {
 	struct timekeeper *tk = &tk_core.timekeeper;
+	u32 cwsseq_orig = *cwsseq;
 	unsigned int seq;
 	ktime_t base;
 	u64 nsecs;
@@ -2370,7 +2371,7 @@ ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
 		base = ktime_add_ns(base, nsecs);
 
-		if (*cwsseq != tk->clock_was_set_seq) {
+		if (cwsseq_orig != tk->clock_was_set_seq) {
 			*cwsseq = tk->clock_was_set_seq;
 			*offs_real = tk->offs_real;
 			*offs_boot = tk->offs_boot;
Signature · 1 line
2.53.0
author maintainer
#1432 lore raw

PATCH 1428/1536 cgroup: dont kill migrated processes through their exiting threads

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit 5f4a3f743acc96987ae5c2e966947942c34ba56c ]

Since commit da13e0e72a73 ("cgroup: fix cgroup.kill for exited thread group leader"), __cgroup_kill() visits every thread in the cgroup and sends SIGKILL with PIDTYPE_TGID, so each visited thread takes down its whole thread group.

A thread that has started exiting can stay in a cgroup after its process has been moved out of it. cgroup_migrate_add_task() skips PF_EXITING tasks, and the thread is only unlinked by cgroup_task_dead() after its final context switch. mm_release() clears the thread's clear_child_tid word and wakes the joiner well before that, so pthread_join() can return while the thread is still in the old cgroup.

If cgroup.kill is written in that window, __cgroup_kill() finds the exiting thread and complete_signal() passes the group-wide SIGKILL on to a live thread, killing a process that already left the cgroup. The cgroup selftest test_stress.sh runs into this: test_cgcore_proc_migration() joins its threads, moves itself back to the root cgroup, and cg_destroy() falls back to cgroup.kill on the old cgroup when rmdir() fails with EBUSY, so test_core kills itself. KernelCI has been reporting "with_stress.sh: line 94: ... Killed" on several arm64 boards since the commit reached linux-next.

Keep visiting every thread, but go back to sending SIGKILL to the thread that was found. A SIGKILL sent to a live thread still kills its whole thread group, so both cases fixed by that commit stay fixed, and task_can_queue_signal() drops one sent to a thread that is already exiting.

Fixes da13e0e72a73 ("cgroup: fix cgroup.kill for exited thread group leader")
Cc [email protected] # v5.14+
---
 kernel/cgroup/cgroup.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/cgroup/cgroup.c +1 -1
index 766351c0e34e6..98e0e7584257d 100644
@@ -4113,7 +4113,7 @@ static void __cgroup_kill(struct cgroup *cgrp)
 		if (__fatal_signal_pending(task))
 			continue;
 
-		do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, task, PIDTYPE_TGID);
+		send_sig(SIGKILL, task, 0);
 	}
 	css_task_iter_end(&it);
 }
Signature · 1 line
2.53.0
author maintainer
#1433 lore raw

PATCH 1429/1536 gve: fix out-of-bounds read in gve_get_flow_rule_entry()

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 45e0a63f9c86a558afc70d79b6df38f8ec7f502a ]

gve_get_flow_rule_entry() checks the requested location against the first and last cached rules, but rules_cache_num can be 0 while rules_cache_synced is true: GVE_FLOW_RULE_QUERY_RULES returns the rules from the requested location onwards, so a request past the last installed rule - or any request when no rules are installed - returns zero rules, which the driver accepts and marks as synced.

The next query evaluates rules_cache[*cache_num - 1] with *cache_num == 0. The zero-initialised cache does not trip the earlier comparison, *cache_num - 1 wraps to 0xFFFFFFFF in u32, and the read faults about 352 GiB past the cache. ETHTOOL_GRXCLSRULE needs no capability, so an unprivileged user can trigger it:

    BUG: unable to handle page fault for address: ff240996c4c64fa8
    #PF: supervisor read access in kernel mode
    RIP: gve_get_flow_rule_entry+0xd4/0x110 [gve]

Treat an empty cache as a cache miss and re-query.

---
 drivers/net/ethernet/google/gve/gve_flow_rule.c | 1 +
 1 file changed, 1 insertion(+)
drivers/net/ethernet/google/gve/gve_flow_rule.c +1 -0
index 0bb8cd1876a3f..426a264af8b26 100644
@@ -206,6 +206,7 @@ int gve_get_flow_rule_entry(struct gve_priv *priv, struct ethtool_rxnfc *cmd)
 		return -EOPNOTSUPP;
 
 	if (!priv->flow_rules_cache.rules_cache_synced ||
+	    !*cache_num ||
 	    fsp->location < be32_to_cpu(rules_cache[0].location) ||
 	    fsp->location > be32_to_cpu(rules_cache[*cache_num - 1].location)) {
 		err = gve_adminq_query_flow_rules(priv, GVE_FLOW_RULE_QUERY_RULES, fsp->location);
Signature · 1 line
2.53.0
author maintainer
#1434 lore raw

PATCH 1430/1536 veth: fix stale peer max_mtu on XDP program replacement

In reply to Greg Kroah-Hartman

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

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

From: yanxia <[email protected]>

[ Upstream commit c955325db639e9503941227e14e1f1ccc99442a1 ]

veth_xdp_set() calculates the peer MTU limit from the incoming program's XDP fragment capability, but only stores it when no program was attached. Replacing a program with one having a different fragment capability therefore leaves the peer's max_mtu stale.

Replacing a regular program with an xdp.frags program keeps rejecting otherwise valid jumbo MTUs. The opposite replacement leaves a larger limit in place and permits MTUs which a fresh attachment of the regular program would reject.

Update peer->max_mtu after every successful attachment or replacement. Keep the GSO feature update conditional on the first attachment.

Found during review of the XDP replacement path and confirmed with native XDP on an isolated veth pair. Before the fix, direct replacement rejects MTU 9000 after switching to xdp.frags, and accepts it after switching back to a regular program. Detaching and attaching instead produces the expected results in both directions.

UML tests on net reproduce the problem before this change and match the detach/attach controls afterwards, with both devices up or down and with either endpoint receiving XDP. Failed replacements preserve the previous state; same-type replacements and detach also behave as expected. Small-frame traffic passes in the devices-up cases.

Fixes 7cda76d858a4 ("veth: Allow jumbo frames in xdp mode")
---
 drivers/net/veth.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/net/veth.c +2 -3
index 31b9c9feb47d9..564bf57bc8979 100644
@@ -1621,10 +1621,9 @@ static int veth_xdp_set(struct net_device *dev, struct bpf_prog *prog,
 			}
 		}
 
-		if (!old_prog) {
+		if (!old_prog)
 			peer->hw_features &= ~NETIF_F_GSO_SOFTWARE;
-			peer->max_mtu = max_mtu;
-		}
+		peer->max_mtu = max_mtu;
 
 		xdp_features_set_redirect_target(peer, true);
 	}
Signature · 1 line
2.53.0
author maintainer
#1435 lore raw

PATCH 1431/1536 scsi: ufs: bsg: Complete the job on error

In reply to Greg Kroah-Hartman

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

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

From: Stanley Jhu <[email protected]>

[ Upstream commit cc0ce3fe8fac073ecded4f32c8ee5b89da1397e8 ]

When ufs_bsg_request() fails, it returns a non-zero status without calling bsg_job_done(). bsg_queue_rq() then ends the request with BLK_STS_IOERR without running bsg_complete(), leaking the job's device reference and mapped scatterlists.

Always complete the job via bsg_job_done() and return 0, matching other BSG transports. Requests failing with a negative errno now return it from SG_IO with the 4-byte result in the reply, while positive status codes still return 0 from SG_IO with the reply header.

---
 drivers/ufs/core/ufs_bsg.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)
drivers/ufs/core/ufs_bsg.c +3 -5
index bb6ff8ca5c7a8..237ade1f0cd83 100644
@@ -194,14 +194,12 @@ static int ufs_bsg_request(struct bsg_job *job)
 	ufshcd_rpm_put_sync(hba);
 	kfree(buff);
 	bsg_reply->result = ret;
-	/* complete the job here only if no error */
-	if (ret == 0) {
+	if (ret == 0)
 		job->reply_len = rpmb ? sizeof(struct ufs_rpmb_reply) :
 					sizeof(struct ufs_bsg_reply);
-		bsg_job_done(job, ret, bsg_reply->reply_payload_rcv_len);
-	}
+	bsg_job_done(job, ret, bsg_reply->reply_payload_rcv_len);
 
-	return ret;
+	return 0;
 }
 
 /**
Signature · 1 line
2.53.0
author maintainer
#1436 lore raw

PATCH 1432/1536 scsi: ufs: bsg: Clear the reply buffer before use

In reply to Greg Kroah-Hartman

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

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

From: Stanley Jhu <[email protected]>

[ Upstream commit 2e63ac76cc08ea376ba61fef52f7b7849e35024d ]

The reply buffer is allocated once per tag and reused. Requests that complete with a positive status do not fill all of it, so user space receives bytes from an earlier request on the same tag.

Clear the whole reply buffer on entry to ufs_bsg_request().

---
 drivers/ufs/core/ufs_bsg.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/ufs/core/ufs_bsg.c +1 -1
index 237ade1f0cd83..0e0b08a3821c4 100644
@@ -142,7 +142,7 @@ static int ufs_bsg_request(struct bsg_job *job)
 	int ret;
 	bool rpmb = false;
 
-	bsg_reply->reply_payload_rcv_len = 0;
+	memset(job->reply, 0, job->reply_len);
 
 	ufshcd_rpm_get_sync(hba);
 
Signature · 1 line
2.53.0
author maintainer
#1437 lore raw

PATCH 1433/1536 scsi: ufs: core: Clear stale UIC result byte before peer DME retries

In reply to Greg Kroah-Hartman

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

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

From: Stanley Jhu <[email protected]>

[ Upstream commit e4a9b7640914b248eb7537d4507aa42db080586a ]

Peer DME get and set retry a failed attempt with the same struct uic_command. UIC completion ORs the ConfigResultCode into argument2[7:0], and nothing clears it before the next attempt. Once an attempt fails, every retry keeps reporting that error code, even when the device returns success, so a transient failure becomes a hard failure after three retries. Each such retry also triggers the WARN_ON_ONCE() in ufshcd_dispatch_uic_cmd(). In ufshcd_dme_set_attr(), ufshcd_uic_cmd_compl() also overwrites argument3 with the register readback before the next attempt.

Clear the result byte and restore argument3 in ufshcd_dme_set_attr() when an attempt fails.

---
 drivers/ufs/core/ufshcd.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/ufs/core/ufshcd.c +7 -2
index c8f007f5a0597..69d043053340b 100644
@@ -4181,9 +4181,12 @@ int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
 	do {
 		/* for peer attributes we retry upon failure */
 		ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
-		if (ret)
+		if (ret) {
 			dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
 				set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
+			uic_cmd.argument2 &= ~MASK_UIC_COMMAND_RESULT;
+			uic_cmd.argument3 = mib_val;
+		}
 	} while (ret && peer && --retries);
 
 	if (ret)
@@ -4247,9 +4250,11 @@ int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
 	do {
 		/* for peer attributes we retry upon failure */
 		ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
-		if (ret)
+		if (ret) {
 			dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
 				get, UIC_GET_ATTR_ID(attr_sel), ret);
+			uic_cmd.argument2 &= ~MASK_UIC_COMMAND_RESULT;
+		}
 	} while (ret && peer && --retries);
 
 	if (ret)
Signature · 1 line
2.53.0
author maintainer
#1438 lore raw

PATCH 1434/1536 scsi: libiscsi_tcp: Prevent R2T range check overflow

In reply to Greg Kroah-Hartman

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

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

From: Ratnaker Gautam <[email protected]>

[ Upstream commit eb7aa7fd673fdc1582223cd133bcc5f54e7af19f ]

An iSCSI target controls the R2T data offset and length as 32-bit values. Adding them before comparing the result with the SCSI data buffer length can wrap. An R2T with offset 1 and length U32_MAX then passes the check for a 4096-byte write.

The transmit path treats the wrapped range as valid, exhausts the command scatterlist, and dereferences the NULL next entry in iscsi_tcp_segment_done().

Check the offset first, then compare the length with the remaining bytes in the data buffer.

---
 drivers/scsi/libiscsi_tcp.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/scsi/libiscsi_tcp.c +2 -1
index 646a2142ed666..4cce6bfb55c57 100644
@@ -612,7 +612,8 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr)
 			      data_length, session->max_burst);
 
 	data_offset = be32_to_cpu(rhdr->data_offset);
-	if (data_offset + data_length > task->sc->sdb.length) {
+	if (data_offset > task->sc->sdb.length ||
+	    data_length > task->sc->sdb.length - data_offset) {
 		iscsi_conn_printk(KERN_ERR, conn,
 				  "invalid R2T with data len %u at offset %u "
 				  "and total length %d\n", data_length,
Signature · 1 line
2.53.0
author maintainer
#1439 lore raw

PATCH 1435/1536 scsi: ufs: core: Remove an always-false WARN_ONCE()

In reply to Greg Kroah-Hartman

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

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

From: Stanley Jhu <[email protected]>

[ Upstream commit cd37a69c367b6a5f685db0ac7d01f08545081a30 ]

The WARN_ONCE() in ufshcd_poll() can never fire. completed_reqs is set to ~tr_doorbell & hba->outstanding_reqs on the line above, and hba->outstanding_reqs cannot change in between because ufshcd_poll() holds hba->outstanding_lock. So completed_reqs & ~hba->outstanding_reqs is always zero. Remove it. No functional change.

---
 drivers/ufs/core/ufshcd.c | 3 ---
 1 file changed, 3 deletions(-)
drivers/ufs/core/ufshcd.c +0 -3
index 69d043053340b..cc730a2463df2 100644
@@ -5673,9 +5673,6 @@ static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
 	spin_lock_irqsave(&hba->outstanding_lock, flags);
 	tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
 	completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
-	WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
-		  "completed: %#lx; outstanding: %#lx\n", completed_reqs,
-		  hba->outstanding_reqs);
 	if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
 		/* Do not complete polled requests from interrupt context. */
 		ufshcd_clear_polled(hba, &completed_reqs);
Signature · 1 line
2.53.0
author maintainer
#1440 lore raw

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

In reply to Greg Kroah-Hartman

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

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

From: Stanley Jhu <[email protected]>

[ Upstream commit 7cfdfdd6557906fd09cf0a9a564a07012e7fb0c1 ]

In SDB mode, a command that times out right as the controller finishes it can be completed twice:

1. The command times out and scsi_timeout() schedules ufshcd_abort().

2. The controller finishes the command and clears its doorbell bit in REG_UTP_TRANSFER_REQ_DOOR_BELL, while the completion handler has not yet cleared BIT(tag) in hba->outstanding_reqs.

3. ufshcd_abort() sees the doorbell bit clear and calls __ufshcd_transfer_req_compl() without clearing BIT(tag) in hba->outstanding_reqs.

4. The normal completion handler or the logical unit reset that follows sees BIT(tag) still set in hba->outstanding_reqs and completes the same command a second time.

This branch only exists for a rare corner case, a completion interrupt that is lost or arrives late. Remove it to simplify the abort path and leave such a command to the SCSI error handler, like any other command that cannot be aborted. The cost is a slower recovery in this corner case, which is acceptable since it only happens after a timeout.

---
 drivers/ufs/core/ufshcd.c | 9 ---------
 1 file changed, 9 deletions(-)
drivers/ufs/core/ufshcd.c +0 -9
index cc730a2463df2..4a78a5d9cd8b4 100644
@@ -7700,15 +7700,6 @@ static int ufshcd_abort(struct scsi_cmnd *cmd)
 	}
 	hba->req_abort_count++;
 
-	if (!hba->mcq_enabled && !(reg & (1 << tag))) {
-		/* only execute this code in single doorbell mode */
-		dev_err(hba->dev,
-		"%s: cmd was completed, but without a notifying intr, tag = %d",
-		__func__, tag);
-		__ufshcd_transfer_req_compl(hba, 1UL << tag);
-		goto release;
-	}
-
 	/*
 	 * Task abort to the device W-LUN is illegal. When this command
 	 * will fail, due to spec violation, scsi err handling next step
Signature · 1 line
2.53.0
author maintainer
#1441 lore raw

PATCH 1437/1536 compat: avoid double rounding in times()

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit 6b30c39a5e333cfb1475acf0f73de6ef954eea8a ]

do_sys_times() already converts CPU time to USER_HZ ticks. The compat path converts each value back to jiffies before converting it to COMPAT_USER_HZ. This round trip can lose precision even when the two userspace rates match.

With HZ=250 and USER_HZ=COMPAT_USER_HZ=100, one user tick becomes two jiffies and then zero compat ticks. Every odd tick count loses one tick, so any of the four tms fields can underreport CPU time by an additional 10 ms.

Return the value directly when the native and compat units match. Keep the existing conversion for differing rates.

Fixes f06febc96ba8 ("timers: fix itimer/many thread hang")
Cc Arnd Bergmann <[email protected]>
Cc Thomas Gleixner <[email protected]>
---
 kernel/sys.c | 3 +++
 1 file changed, 3 insertions(+)
kernel/sys.c +3 -0
index 6c870636ea73c..fe64ebfddf010 100644
@@ -1045,6 +1045,9 @@ SYSCALL_DEFINE1(times, struct tms __user *, tbuf)
 #ifdef CONFIG_COMPAT
 static compat_clock_t clock_t_to_compat_clock_t(clock_t x)
 {
+	if (USER_HZ == COMPAT_USER_HZ)
+		return x;
+
 	return compat_jiffies_to_clock_t(clock_t_to_jiffies(x));
 }
 
Signature · 1 line
2.53.0
author maintainer
#1442 lore raw

PATCH 1438/1536 ocfs2: snapshot the dentry name while tracing file release

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 5898987d4a92b70ae73fd8355cc3a388b4dfa4e6 ]

ocfs2_file_release() passes the live dentry name and length to a trace event while holding oi->ip_lock. This lock protects the open count and delays RCU reclamation of external names, but it does not serialize name changes during rename. The dentry can switch between inline and external names, and a separately loaded length can describe a different name.

The ocfs2__file_ops event sizes and copies its __string separately. A concurrently rewritten inline name need not remain consistent between those operations. External names can also be selected at this call site; the existing spinlock critical section protects their allocation lifetime, while a snapshot additionally pairs a stable name with its length.

Take a name snapshot before acquiring oi->ip_lock and release it after dropping the lock. Keep the trace call and open-count argument inside the original critical section. Cache the event-enabled check so the snapshot stays paired even if tracing is toggled meanwhile.

---
 fs/ocfs2/file.c | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)
fs/ocfs2/file.c +13 -5
index 76c1a7e7b4e17..451f0c5a53528 100644
@@ -140,18 +140,26 @@ static int ocfs2_file_open(struct inode *inode, struct file *file)
 static int ocfs2_file_release(struct inode *inode, struct file *file)
 {
 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
+	struct dentry *dentry = file->f_path.dentry;
+	struct name_snapshot name;
+	bool trace_enabled = trace_ocfs2_file_release_enabled();
+
+	if (trace_enabled)
+		take_dentry_name_snapshot(&name, dentry);
 
 	spin_lock(&oi->ip_lock);
 	if (!--oi->ip_open_count)
 		oi->ip_flags &= ~OCFS2_INODE_OPEN_DIRECT;
 
-	trace_ocfs2_file_release(inode, file, file->f_path.dentry,
-				 oi->ip_blkno,
-				 file->f_path.dentry->d_name.len,
-				 file->f_path.dentry->d_name.name,
-				 oi->ip_open_count);
+	if (trace_enabled)
+		trace_ocfs2_file_release(inode, file, dentry,
+					 oi->ip_blkno, name.name.len,
+					 name.name.name, oi->ip_open_count);
 	spin_unlock(&oi->ip_lock);
 
+	if (trace_enabled)
+		release_dentry_name_snapshot(&name);
+
 	ocfs2_free_file_private(inode, file);
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#1443 lore raw

PATCH 1439/1536 ocfs2/cluster: remove zero-address nodes from IP tree on teardown

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

o2nm_node_ipv4_address_store() accepts 0.0.0.0. It sets O2NM_NODE_ATTR_ADDRESS and links nd_ip_node into cl_node_ip_tree under cl_nodes_lock, but o2nm_node_group_drop_item() uses nd_ipv4_address as a membership test. A zero address therefore leaves the rbtree node linked when config_item_put() releases and frees struct o2nm_node. A later address store or IP lookup can then walk the stale node and dereference freed memory.

During teardown, drop_item takes cl_nodes_lock, skips rb_erase() for the zero key, and then calls config_item_put(). A later o2nm_node_ipv4_address_store() duplicate check or o2nm_get_node_by_ip() lookup takes the same lock and walks the stale cl_node_ip_tree entry. Use O2NM_NODE_ATTR_ADDRESS for teardown so every published nd_ip_node is erased before configfs can release the node, without rejecting 0.0.0.0 or changing lookup semantics.

---
 fs/ocfs2/cluster/nodemanager.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
fs/ocfs2/cluster/nodemanager.c +5 -2
index 87aeb1a7a90ae..bfc7c0fb2be05 100644
@@ -626,8 +626,11 @@ static void o2nm_node_group_drop_item(struct config_group *group,
 
 	write_lock(&cluster->cl_nodes_lock);
 
-	/* XXX sloppy */
-	if (node->nd_ipv4_address)
+	/*
+	 * 0.0.0.0 is a valid configured address, so nd_ipv4_address does
+	 * not tell us whether nd_ip_node was published in the IP tree.
+	 */
+	if (test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes))
 		rb_erase(&node->nd_ip_node, &cluster->cl_node_ip_tree);
 
 	/* nd_num might be 0 if the node number hasn't been set.. */
Signature · 1 line
2.53.0
author maintainer
#1444 lore raw

PATCH 1440/1536 mm/madvise: add cond_resched() in THP branch of madvise_cold_or_pageout_pte_range()

In reply to Greg Kroah-Hartman

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

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

From: Wei Yang <[email protected]>

[ Upstream commit f5cfc8e3b20ad71949a1e5623ff45882c063a71b ]

During stress testing with stress-ng on a 256-CPU system, a softlockup was observed when madvise(MADV_COLD) was called on a 31GB memory region backed by transparent hugepages. The region contains 15935 THP PMD entries, and the softlockup was triggered after 14485 of them had been processed.

The THP branch of madvise_cold_or_pageout_pte_range() has no scheduling point. walk_pmd_range() invokes it once per 2MB PMD entry with no cond_resched() anywhere in the loop. Each iteration calls pmdp_invalidate() which issues a synchronous TLB shootdown (dsb ish) waiting for all CPUs to acknowledge. This operation can be time-consuming under heavy system load, causing the accumulated time across all PMD entries to exceed the softlockup threshold (20s) and panic when softlockup_panic=1. On a CONFIG_PREEMPT_NONE=y kernel, there is no other opportunity to reschedule during this entire traversal.

The regular PTE path already has an unconditional cond_resched() at the function tail (introduced by commit 9c276cc65a58 ("mm: introduce MADV_COLD") and commit 1a4e58cce84e ("mm: introduce MADV_PAGEOUT") when MADV_COLD and MADV_PAGEOUT were first introduced) and a conditional one inside the loop (commit b2f557a21bc8 ("mm/madvise: add cond_resched() in madvise_cold_or_pageout_pte_range()")). The THP branch never received equivalent treatment.

Fix by adding cond_resched() at the huge_unlock exit path after spin_unlock(ptl) and reclaim_pages(), which is the single exit point for all goto paths in the THP branch.

Crash log:

  watchdog: BUG: soft lockup - CPU#63 stuck for 23s! [stress-ng-vm:1665914]
  ...
  Call trace:
  pmdp_invalidate+0x48/0x68
  madvise_cold_or_pageout_pte_range+0x84c/0xb00
  walk_pmd_range.isra.0+0x1ac/0x3b0
  walk_pud_range+0x120/0x190
  walk_pgd_range+0x170/0x1b8
  __walk_page_range+0x184/0x198
  walk_page_range_vma+0x94/0x128
  madvise_cold+0xd8/0x198
  madvise_vma_behavior+0x234/0x638
  madvise_walk_vmas.constprop.0+0xdc/0x210
  madvise_do_behavior+0xa8/0x328
  do_madvise+0xd8/0x140
  __arm64_sys_madvise+0x2c/0xe0
---
 mm/madvise.c | 1 +
 1 file changed, 1 insertion(+)
mm/madvise.c +1 -0
index dbbb777110358..e1470b35d43ae 100644
@@ -432,6 +432,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 		spin_unlock(ptl);
 		if (pageout)
 			reclaim_pages(&folio_list);
+		cond_resched();
 		return 0;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#1445 lore raw

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

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

mlock_fixup() adjusts mm->locked_vm, an unsigned long, by the number of pages whose VM_LOCKED state it changes, but computes that number in an int:

	int nr_pages;
	...
	nr_pages = (end - start) >> PAGE_SHIFT;
	...
	mm->locked_vm += nr_pages;

When a single VMA range of 2^31 pages (8 TiB with 4 KiB pages) or more is locked or unlocked, the count is truncated to 32 bits and then sign-extended, so locked_vm is changed by the wrong amount, while munmap(), mremap() and the other paths that maintain locked_vm use the full unsigned long page count.

Such a range is reachable on 64-bit architectures with a 47-bit or larger user address space (x86_64, arm64 with 48-bit VA, riscv64 Sv48) by a task with CAP_IPC_LOCK or a raised RLIMIT_MEMLOCK, which do_mlock() checks against the full untruncated length. It costs nothing with MAP_NORESERVE and MLOCK_ONFAULT/MCL_ONFAULT, since then no page is populated. On x86_64, after

	p = mmap(NULL, 8UL << 40, PROT_READ | PROT_WRITE,
		 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
	mlock2(p, 8UL << 40, MLOCK_ONFAULT);

VmLck in /proc/self/status reads 18446744065119617024 kB instead of 8589934592 kB; munmap() of the region then subtracts the true size and leaves VmLck at 18446744056529682432 kB instead of 0. With 16 TiB, locked_vm is not changed at all, VmLck stays 0 kB, and after the task drops CAP_IPC_LOCK or lowers RLIMIT_MEMLOCK, mlock(), mmap(MAP_LOCKED) and the other mlock_future_ok() and account_locked_vm() users enforce RLIMIT_MEMLOCK against that count, so they let the task lock memory beyond its limit (or, in the 8 TiB case, refuse every further lock). The error persists for the life of the mm; unlocking the range in pieces skews it further. The wrong count is per-mm accounting only: it does not change which pages are locked.

The int has been there since before git history (the variable was named "pages" until it was renamed in 2.6.28); every other updater of locked_vm uses an unsigned long or long count. Make nr_pages a long, which holds the page count of any user range and its negation, so the existing sign handling is unchanged.

Found by formal verification of mm/mlock.c against the kernel binary.

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

PATCH 1442/1536 mm/percpu: account full object size for percpu memory allocations

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit c7a467fbcbbc31e57a5077bfc9456d9f29cb1571 ]

When memory allocation profiling is enabled, the pages backing percpu memory chunks are attributed to func:pcpu_alloc_pages. However, the accounting of individual percpu memory allocations via alloc_percpu() and friends record only the size of a single object rather than its full size across all CPUs.

As a result, it is often not straightforward to identify which kernel code is actually responsible for percpu memory, because the size is under-accounted by a factor of num_possible_cpus().

Account full object size with pcpu_obj_full_size(size) instead, which multiplies the object size by num_possible_cpus() and adds the objcg pointer overhead. This is consistent with what memcg already does for charging percpu allocations.

Verified with 64-CPU VM by spawning 400 processes in a memory cgroup and measuring mm_init()'s rss_stat counters.

Delta of kernel/fork.c:1142 func:mm_init in /proc/allocinfo:

bytes calls per allocation
unpatched 6320 395 16
patched 418176 396 1056

'percpu' field in memory.stat: 422400 (1056 bytes per process)

Memory allocation profiling now accounts the same amount of memory as what memcg charges.

Fixes 60fa4a9e2323 ("mm: percpu: add codetag reference into pcpuobj_ext")
Assisted-by LLM # Verification
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Hao Ge <[email protected]>
---
 mm/percpu.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/percpu.c +3 -2
index 44764720b6d8f..cd28926438da5 100644
@@ -1705,14 +1705,15 @@ static void pcpu_alloc_tag_alloc_hook(struct pcpu_chunk *chunk, int off,
 {
 	if (mem_alloc_profiling_enabled() && likely(chunk->obj_exts)) {
 		alloc_tag_add(&chunk->obj_exts[off >> PCPU_MIN_ALLOC_SHIFT].tag,
-			      current->alloc_tag, size);
+			      current->alloc_tag, pcpu_obj_full_size(size));
 	}
 }
 
 static void pcpu_alloc_tag_free_hook(struct pcpu_chunk *chunk, int off, size_t size)
 {
 	if (mem_alloc_profiling_enabled() && likely(chunk->obj_exts))
-		alloc_tag_sub(&chunk->obj_exts[off >> PCPU_MIN_ALLOC_SHIFT].tag, size);
+		alloc_tag_sub(&chunk->obj_exts[off >> PCPU_MIN_ALLOC_SHIFT].tag,
+			      pcpu_obj_full_size(size));
 }
 #else
 static void pcpu_alloc_tag_alloc_hook(struct pcpu_chunk *chunk, int off,
Signature · 1 line
2.53.0
author maintainer
#1447 lore raw

PATCH 1443/1536 mm/madvise: atomically clear the young bit on THP MADV_COLD

In reply to Greg Kroah-Hartman

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

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

From: Pedro Falcato <[email protected]>

[ Upstream commit 246c8cc33438a71c28f9b86baa492d9a0a130316 ]

As-is, madvise_cold_or_pageout_pte_range() discards the hardware young bit by invalidating the PMD, doing pmd_mkold() and subsequently writing to the pmd again. However, it does so in a racy manner, looking at a possibly-stale snapshot. It's entirely possible that a write elsewhere set the hardware D bit, which this logic now loses.

Fix it by using pmdp_test_and_clear_young(). This is an atomic modification of the PMD entry, and thus safe against any possible racing writes. As a (nice) side-effect, this elides one non-required TLB flush in pmdp_invalidate().

This bug can interact with the swapping system in complicated ways, leading to data loss. For instance, if a folio is marked lazyfree, but was later read from, and then MADV_COLD'd while racing a write to that same THP, dropping the dirty bit may lead to data loss as reclaim/MADV_PAGEOUT drops the "clean" anon folio:

T0 T1
================================================================
MADV_FREE(thp) |
folio marked lazyfree |
read(thp) |
PMD marked young by hardware |
| MADV_COLD(thp)
write(thp) | if (pmd_young(pmd)) {
PMD marked dirty by hardware | set(pmdp, pmd_mkold(pmd));
MADV_PAGEOUT/reclaim |
dirty bit may or may not be |
set |
reclaim/pageout may drop |
the folio |

---
 mm/madvise.c | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)
mm/madvise.c +1 -4
index e1470b35d43ae..ea966d402f073 100644
@@ -408,10 +408,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 		}
 
 		if (!pageout && pmd_young(orig_pmd)) {
-			pmdp_invalidate(vma, addr, pmd);
-			orig_pmd = pmd_mkold(orig_pmd);
-
-			set_pmd_at(mm, addr, pmd, orig_pmd);
+			pmdp_test_and_clear_young(vma, addr, pmd);
 			tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
 		}
 
Signature · 1 line
2.53.0
author maintainer
#1448 lore raw

PATCH 1444/1536 ipc/shm: fix RSS accounting for hugetlb shared memory

In reply to Greg Kroah-Hartman

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

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

From: Weilin Tong <[email protected]>

[ Upstream commit e387ebe5cd31720b1e0281fd045be4eef36fadb3 ]

Commit a08c7193e4f1 ("mm/filemap: remove hugetlb special casing in filemap.c") changed mapping->nrpages to count base pages for hugetlb folios. However, shm_add_rss_swap() still multiplies it by pages_per_huge_page(), overcounting RSS in both SHM_INFO and /proc/sysvipc/shm.

Use mapping->nrpages for RSS accounting across all backing types, and account swap only for non-hugetlb shmem. Use READ_ONCE() for both counters instead of info->lock, which does not protect nrpages and cannot provide a consistent snapshot.

Fixes a08c7193e4f1 ("mm/filemap: remove hugetlb special casing in filemap.c")
Cc Oscar Salvador <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Sidhartha Kumar <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Dan Carpenter <[email protected]>
Cc Baolin Wang <[email protected]>
---
 ipc/shm.c | 23 ++++-------------------
 1 file changed, 4 insertions(+), 19 deletions(-)
ipc/shm.c +4 -19
index f70a503e61295..77ee6d9ebd9d0 100644
@@ -934,26 +934,11 @@ static inline unsigned long copy_shminfo_to_user(void __user *buf, struct shminf
 static void shm_add_rss_swap(struct shmid_kernel *shp,
 	unsigned long *rss_add, unsigned long *swp_add)
 {
-	struct inode *inode;
+	struct inode *inode = file_inode(shp->shm_file);
 
-	inode = file_inode(shp->shm_file);
-
-	if (is_file_hugepages(shp->shm_file)) {
-		struct address_space *mapping = inode->i_mapping;
-		struct hstate *h = hstate_file(shp->shm_file);
-		*rss_add += pages_per_huge_page(h) * mapping->nrpages;
-	} else {
-#ifdef CONFIG_SHMEM
-		struct shmem_inode_info *info = SHMEM_I(inode);
-
-		spin_lock_irq(&info->lock);
-		*rss_add += inode->i_mapping->nrpages;
-		*swp_add += info->swapped;
-		spin_unlock_irq(&info->lock);
-#else
-		*rss_add += inode->i_mapping->nrpages;
-#endif
-	}
+	*rss_add += READ_ONCE(inode->i_mapping->nrpages);
+	if (IS_ENABLED(CONFIG_SHMEM) && !is_file_hugepages(shp->shm_file))
+		*swp_add += READ_ONCE(SHMEM_I(inode)->swapped);
 }
 
 /*
Signature · 1 line
2.53.0
author maintainer
#1449 lore raw

PATCH 1445/1536 mm/page_alloc: count guard pages as free again when their buddy merges

In reply to Greg Kroah-Hartman

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

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

From: Rik van Riel <[email protected]>

[ Upstream commit 1503710b3b0cec02b531978129c6c1eb70a7c490 ]

With debug_guardpage_minorder set, expand() turns the unused halves of a split into guard pages, which page_del_and_expand() leaves out of the free counts. Freeing the allocated half credits only that half, and __free_one_page() then merges the guard buddy with clear_page_guard(), which no longer touches the counters.

The merged block goes on a free list with the guard pages never counted, so NR_FREE_PAGES falls behind the free lists by every guard that merges. Before commit e0932b6c1f94 ("mm: page_alloc: consolidate free page accounting"), __set_page_guard() and __clear_page_guard() adjusted the counts themselves; that commit dropped both adjustments but kept the subtraction implicit in expand().

Count the guard pages under the merged block's migratetype when the buddy is cleared. account_freepages() skips an isolated block as it does for every other free page, and moving the block off the isolated list counts it then.

Booting a 16GB VM with debug_pagealloc=on debug_guardpage_minorder=1, check the difference in free pages reported between /proc/vmstat and /proc/buddyinfo.

At three points (idle, after a read and file-creation load, after a second load), check the difference between nr_free_pages and the buddyinfo numbers in the normal zone, as a number of pages:

idle after load after second load
unpatched -130 79205 99121
patched -16 45 0

The small remaining difference seems to be due to the numbers not being read at exactly the same time, and is also seen without guard pages.

Fixes e0932b6c1f94 ("mm: page_alloc: consolidate free page accounting")
Assisted-by LLM
Cc Suren Baghdasaryan <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Brendan Jackman <[email protected]>
Cc Kairui Song <[email protected]>
Cc Qi Zheng <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Baoquan He <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Frank van der Linden <[email protected]>
---
 mm/page_alloc.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
mm/page_alloc.c +4 -2
index e68a47d8485c8..a649f0245e3bf 100644
@@ -858,10 +858,12 @@ static inline void __free_one_page(struct page *page,
 		 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
 		 * merge with it and move up one order.
 		 */
-		if (page_is_guard(buddy))
+		if (page_is_guard(buddy)) {
 			clear_page_guard(zone, buddy, order);
-		else
+			account_freepages(zone, 1 << order, migratetype);
+		} else {
 			__del_page_from_free_list(buddy, zone, order, buddy_mt);
+		}
 
 		if (unlikely(buddy_mt != migratetype)) {
 			/*
Signature · 1 line
2.53.0
author maintainer
#1450 lore raw

PATCH 1446/1536 mm/mempolicy: apply bind policies against the scoped allocation zone

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit d4ea410ce4b8aa46a316476ea2624a357bf31fa9 ]

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

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

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

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

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

page allocation failure:

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

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

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

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

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

PATCH 1447/1536 riscv: mm: exclude invalid THP PMDs from page table check

In reply to Greg Kroah-Hartman

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

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

From: Yunhui Cui <[email protected]>

[ Upstream commit bdda2887cbf3937c2d0f56589c2124c4167324e1 ]

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

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

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

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

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

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

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

In reply to Greg Kroah-Hartman

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

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

From: Siddharth Chintamaneni <[email protected]>

[ Upstream commit 183895979c441e52dbd651b388553b09eaa35cfa ]

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

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

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

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

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

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

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

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

PATCH 1449/1536 fscrypt: Fix missing barrier in fscrypt_find_mode_key()

In reply to Greg Kroah-Hartman

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

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

From: Baokun Li <[email protected]>

[ Upstream commit cf66375465b9ca531f5c294f468db1df293c178c ]

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

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

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

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

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

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

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

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

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

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

PATCH 1450/1536 fbdev: atmel_lcdfb: fix list_first_entry() on possibly empty modelist in probe

In reply to Greg Kroah-Hartman

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

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

From: Wang Haoran <[email protected]>

[ Upstream commit 01d1204582f16e8b7bfce29648e5cf77a585d962 ]

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

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

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

PATCH 1451/1536 timers/itimer: Keep a nonzero value at CPU timer expiry

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit ef60f61208a30eb5b941b707debdf04517271b4f ]

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

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

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

PATCH 1452/1536 time/namespace: Fix overflow when converting absolute deadlines

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit d69cfd33b5a8d176124c564513b9ceb933595d93 ]

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

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

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

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

PATCH 1453/1536 ceph: avoid pending truncate during nonblocking cap acquire

In reply to Greg Kroah-Hartman

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

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

From: Max Kellermann <[email protected]>

[ Upstream commit 979b7ed4457a04c5a41c36f86052ecc6b76c67d9 ]

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

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

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

PATCH 1454/1536 ceph: fix out-of-bounds read in ceph_netfs_issue_op_inline()

In reply to Greg Kroah-Hartman

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

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

From: Guanglei Zhu <[email protected]>

[ Upstream commit cdbb60f00f87297a9db2652847dfc0eaaf3c45aa ]

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

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

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

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

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

PATCH 1455/1536 ceph: reject mdsmaps that claim more than CEPH_MAX_MDS ranks

In reply to Greg Kroah-Hartman

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

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

From: Xiang Mei <[email protected]>

[ Upstream commit c1742590d2b2fc5fb217e1a9b520108f1fe282e5 ]

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

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

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

PATCH 1456/1536 ceph: require the dentry lease record to cover struct ceph_mds_reply_lease

In reply to Greg Kroah-Hartman

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

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

From: Xiang Mei <[email protected]>

[ Upstream commit 7286b2ffe04d4b39b4e9884f714792589d94f316 ]

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

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

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

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

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

PATCH 1457/1536 libceph: only set read_from_replica on read requests

In reply to Greg Kroah-Hartman

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

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

From: Xiubo Li <[email protected]>

[ Upstream commit d6c7a5fcd08873c45a2dcd645a0690fd1443af50 ]

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

Gate the flag on CEPH_OSD_FLAG_READ.

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

PATCH 1458/1536 libceph: Fix unsafe decode in ceph_redirect_decode()

In reply to Greg Kroah-Hartman

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

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

From: Raphael Zimmer <[email protected]>

[ Upstream commit 0405670e50f213594366ab7eddc07002bd7f84c0 ]

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

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

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

PATCH 1459/1536 libceph: Fix multiple unsafe decodes in ceph_oloc_decode()

In reply to Greg Kroah-Hartman

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

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

From: Raphael Zimmer <[email protected]>

[ Upstream commit 10655007b9b679e46a9e383202c7bb791e5d1d13 ]

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

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

[ idryomov: use ceph_decode_64_safe() for hash ]

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

PATCH 1460/1536 libceph: reject mismatched CRUSH weight-set sizes

In reply to Greg Kroah-Hartman

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

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

From: Felix Hoffmann <[email protected]>

[ Upstream commit d8fc89b5bfe4cb3aebe4c8a818247d11291b841c ]

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

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

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

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

PATCH 1461/1536 libceph: reject an initial monmap with no monitors

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit 94dbce2ae4fdb57bdb53ffa3456da777a5cfb981 ]

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

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

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

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

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

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

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

PATCH 1462/1536 ceph: fix integer overflow in the snap trace bounds check

In reply to Greg Kroah-Hartman

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

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

From: Xiang Mei <[email protected]>

[ Upstream commit b3bf89767e3ca9506f1c7167cac97c41ec254d42 ]

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

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

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

PATCH 1463/1536 ceph: Fix xattr buffer leak in __send_cap()

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

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

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

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

PATCH 1464/1536 ceph: Fix mds session leak in __open_export_target_session()

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 6c80207392fdb86107d7acbdbf4c86cac38da1af ]

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

Drop the session reference before returning the error.

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

PATCH 1465/1536 ceph: fix 32-bit overflow in readdir reply count check

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 52913831ba56efceaafd80b501d68fa00f79bde6 ]

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

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

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

PATCH 1466/1536 libceph: fix out-of-bounds reads from repeated CRUSH bucket entries

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 569a9bb1e5615c2b88b8d76f03a4ab82e65a673e ]

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

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

A malformed monitor OSDMap triggers this during RBD placement:

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

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

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

PATCH 1467/1536 ceph: clamp MDS reply result code to the errno range

In reply to Greg Kroah-Hartman

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

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

From: Yuanfu Xie <[email protected]>

[ Upstream commit ec8d583469ed64b4973192a21b5a41c33219721f ]

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

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

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

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

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

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

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

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

PATCH 1468/1536 ceph: dont fail write_begin with -EAGAIN after flushing old snapc

In reply to Greg Kroah-Hartman

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

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

From: Venky Shankar <[email protected]>

[ Upstream commit 6ff7920ca78f6edcabc26c63d20f681d938027c7 ]

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

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

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

ld: final link failed: Resource temporarily unavailable

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

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

PATCH 1469/1536 ceph: validate fscrypt auth blob length

In reply to Greg Kroah-Hartman

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

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

From: sung byeongchan <[email protected]>

[ Upstream commit bc418e234e5be14b97dec90e84a680e615b4134e ]

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

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

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

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

PATCH 1470/1536 ceph: bound name skips in ceph_mdsmap_decode() by the message end

In reply to Greg Kroah-Hartman

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

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

From: sung byeongchan <[email protected]>

[ Upstream commit 7f702e1703c9648fcb02a217d66c880d00417150 ]

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

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

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

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

PATCH 1471/1536 ceph: validate MDS reply fragtree split array length

In reply to Greg Kroah-Hartman

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

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

From: sung byeongchan <[email protected]>

[ Upstream commit 8cab7e7461f81ea1e0fd45082b50bb3c04c0bb10 ]

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

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

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

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

PATCH 1472/1536 ceph: validate encoded xattr name lengths

In reply to Greg Kroah-Hartman

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

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

From: sung byeongchan <[email protected]>

[ Upstream commit 166375898d29fea050a9abec855da6075050d5c9 ]

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

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

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

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

PATCH 1473/1536 ceph: fix uninitialized err in ceph_netfs_issue_read()

In reply to Greg Kroah-Hartman

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

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

From: Alex Markuze <[email protected]>

[ Upstream commit 823d21c78453fcdf58dbd8ecefbb41f4f3eb6540 ]

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

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

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

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

PATCH 1474/1536 ASoC: qcom: qdsp6: q6afe: fix clk vote response type mismatch

In reply to Greg Kroah-Hartman

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

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

From: Val Packett <[email protected]>

[ Upstream commit f3c7bee984aa0ba2b48a44e16a6f3ec2c27f851e ]

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

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

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

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

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

PATCH 1475/1536 ASoC: codecs: wsa884x: Accept temperatures across the full trim range

In reply to Greg Kroah-Hartman

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

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

From: Srinivas Kandagatla <[email protected]>

[ Upstream commit 00535515e3c14fbee20de4a1aa61cfb3390f0f50 ]

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

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

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

PATCH 1476/1536 net: usb: pegasus: check rx pkt_len against the received length

In reply to Greg Kroah-Hartman

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

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

From: Wei Jie Law <[email protected]>

[ Upstream commit efee699f6de06611234ef9b0abd52db1340e5452 ]

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

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

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

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

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

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

PATCH 1477/1536 bonding: fix out-of-bounds read of arp_ip_target

In reply to Greg Kroah-Hartman

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

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

From: Jiayuan Chen <[email protected]>

[ Upstream commit a81513bf5bdf29cf00c0a11f56be515c1ec260f4 ]

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

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

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

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

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

PATCH 1478/1536 ipmr: fully initialize the synthetic IP header in ipmr_get_route()

In reply to Greg Kroah-Hartman

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

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

From: Ido Schimmel <[email protected]>

[ Upstream commit 134351edc28e083c61012b6c69e8e54dd7fa5bcc ]

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

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

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

[1]

BUG: KMSAN: kernel-infoleak in _copy_to_iter
 raw_recvmsg

Uninit was stored to memory at:
ipmr_cache_report
ipmr_cache_unresolved
ipmr_get_route

Uninit was created at:
pskb_expand_head
skb_realloc_headroom
ipmr_get_route

Byte 1 of 28 is uninitialized

[2]

BUG: KMSAN: kernel-infoleak in _copy_to_iter
 raw_recvmsg

Uninit was stored to memory at:
ipmr_cache_report
ipmr_cache_unresolved
ipmr_get_route

Uninit was created at:
pskb_expand_head
skb_realloc_headroom
ipmr_get_route

Bytes 4-7 of 28 are uninitialized

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

PATCH 1479/1536 dt-bindings: clock: ma35d1: Document the missing crystal inputs

In reply to Greg Kroah-Hartman

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

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

From: Miquel Raynal <[email protected]>

[ Upstream commit ea1f41802312e77b58113146a060fb0546b2234d ]

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

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

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

PATCH 1480/1536 tcp: limit tcp_tso_rtt_log to a valid shift count

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 850a7225bc61cdfaf0c4b02ff341ae7cb54902f5 ]

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

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

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

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

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

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

PATCH 1481/1536 xsk: restore UMEM flags after failed pool assignment

In reply to Greg Kroah-Hartman

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

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

From: Paul Moses <[email protected]>

[ Upstream commit b88b826ec54a06f48a42580c609ba81293ebec8e ]

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

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

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

Discovered during development of AF_XDP changes for igc.

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

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

In reply to Greg Kroah-Hartman

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

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

From: Dominik Maier <[email protected]>

[ Upstream commit 87409eedc543d288cdd49c2174f7d61eca7b8db5 ]

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

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

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

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

PATCH 1483/1536 ALSA: hda: Reject codec reset on ASoC (ext_ops) buses

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

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

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

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

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

PATCH 1484/1536 ixgbe: reserve TX timestamp after skb preparation

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit f75062536e2d45ee182828f0e47e0124be2fdc8d ]

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

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

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

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

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

PATCH 1485/1536 ASoC: hdac_hda: Balance the runtime PM disable in codec remove

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

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

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

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

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

PATCH 1486/1536 LoongArch: Use pa_to_nid()/nid_to_addrbase() rather than hard-code

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 244eb26bbd152896f976db6415550993cd60b46d ]

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

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

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

In reply to Greg Kroah-Hartman

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

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

From: Tiezhu Yang <[email protected]>

[ Upstream commit 85cebdfee765e92e748e71b9b91889eef5988282 ]

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

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

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

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

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

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

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

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

PATCH 1488/1536 LoongArch: Remove redundant call in update_bp_registers()

In reply to Greg Kroah-Hartman

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

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

From: Tiezhu Yang <[email protected]>

[ Upstream commit 23534c6efeb718e8a4d9107fa7d6707b5b1f5859 ]

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

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

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

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

PATCH 1489/1536 LoongArch: Fix bitmask corruption in update_bp_registers()

In reply to Greg Kroah-Hartman

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

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

From: Tiezhu Yang <[email protected]>

[ Upstream commit 30c52672bf456decf675c11f3c65acd73a6bcca8 ]

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

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

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

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

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

PATCH 1490/1536 LoongArch: Fix architectural naming typo for CSR_FWPS_SKIP

In reply to Greg Kroah-Hartman

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

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

From: Tiezhu Yang <[email protected]>

[ Upstream commit f322ebfdfda2bce91fb1d3fb0072c735051fed85 ]

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

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

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

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

PATCH 1491/1536 LoongArch: Only send SIGTRAP signal if necessary in do_watch()

In reply to Greg Kroah-Hartman

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

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

From: Tiezhu Yang <[email protected]>

[ Upstream commit f087903018e35d38b8932e18b010ee2e8699d1a1 ]

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

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

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

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

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

PATCH 1492/1536 LoongArch: Fix perf hardware breakpoint failure via installation

In reply to Greg Kroah-Hartman

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

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

From: Tiezhu Yang <[email protected]>

[ Upstream commit f5c0f8427469e703465c719c4304ce91282a32eb ]

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

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

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

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

(1) Test program (test_perf_install.c):

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

  static int var = 0;

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

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

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

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

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

  	close(fd);
  	return 0;
  }

(2) Test steps:

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

(3) Test results:

Without this patch:

Watchpoint counts: expected = 1, actual = 0

With this patch:

Watchpoint counts: expected = 1, actual = 1

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

PATCH 1493/1536 cpufreq: stats: Fix potential out-of-bounds access in deferred reset

In reply to Greg Kroah-Hartman

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

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

From: Zhongqiu Han <[email protected]>

[ Upstream commit 8a702989677216489e471a6f27599da53f753567 ]

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

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

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

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

PATCH 1494/1536 arm64/mm: restrict transparent contpte mappings to valid PTEs

In reply to Greg Kroah-Hartman

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

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

From: Zhao Gongyi <[email protected]>

[ Upstream commit 486d396b19e93f6e56e0a0ba96c14a9ccc1a5977 ]

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

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

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

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

clear_refs_pte_range() then reached the marker through:

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

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

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

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

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

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

PATCH 1495/1536 drm/amdkfd: stop restore retries on device unplug

In reply to Greg Kroah-Hartman

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

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

From: Olivier Kaloudoff <[email protected]>

[ Upstream commit 3254ed0b15f2fe656c9cb36ccb59b92422440bf8 ]

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

Treat -ENODEV as terminal in both workers.

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

PATCH 1496/1536 drm/amd/display: take a runtime PM reference only when a CRTC turns on

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

amdgpu_dm_commit_streams() takes a runtime PM reference for every active CRTC that needs a modeset and has a new stream, but amdgpu_dm_atomic_commit_tail() drops one only for each CRTC that goes from active to inactive. A modeset of a CRTC that is already active (a mode change, or anything else that needs a full modeset) therefore leaks one reference. Once that has happened, the usage count no longer returns to zero with every CRTC off, and the device cannot runtime suspend again until reboot. The two also disagree the other way when a CRTC turns on without a stream ("Failed to create new stream"): no reference is taken, but one is dropped when it turns off.

Take the reference in the loop that counts the disabled CRTCs, on the mirror condition: when the CRTC goes from inactive to active, which is what the commit that added it intended ("every time we enable a previously disabled CRTC"). Each active CRTC then holds exactly one reference.

Tested on an RX 9070 XT (Navi 48) over OCuLink, with the change backported to 7.2.9: an unplugged connector forced on, then mode A on a CRTC, mode B on the same active CRTC, and the CRTC off, three rounds in a row. The usage count rose by 3 with the stock module, by 0 with this patch, and by 3 again after reloading the stock module.

Fixes 97028037a38a ("drm/amdgpu: Grab/put runtime PM references in atomic_commit_tail()")
Assisted-by Claude:claude-opus-5-5
(cherry picked from commit 59ef9a435499777b8e1c4e0eff52f813c64fb920)
---
 drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +7 -4
index de992c58fb7f7..305a9fe006de4 100644
@@ -9768,8 +9768,6 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
 			if (dm_old_crtc_state->stream)
 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
 
-			pm_runtime_get_noresume(dev->dev);
-
 			acrtc->enabled = true;
 			acrtc->hw_mode = new_crtc_state->mode;
 			crtc->hwmode = new_crtc_state->mode;
@@ -10234,8 +10232,13 @@ static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
 #ifdef CONFIG_DEBUG_FS
 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
 #endif
-		/* Count number of newly disabled CRTCs for dropping PM refs later. */
-		if (old_crtc_state->active && !new_crtc_state->active)
+		/*
+		 * One runtime PM reference per active CRTC: take it when the
+		 * CRTC turns on, count it when it turns off for dropping later.
+		 */
+		if (!old_crtc_state->active && new_crtc_state->active)
+			pm_runtime_get_noresume(dev->dev);
+		else if (old_crtc_state->active && !new_crtc_state->active)
 			crtc_disable_count++;
 
 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
Signature · 1 line
2.53.0
author maintainer
#1501 lore raw

PATCH 1497/1536 drm/amdkfd: split vram_pages of SVM ranges prefetched without a GPU mapping

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 52957e813f2f025c86e4aa6e86cb4963ef94fd00 ]

When an SVM range is split, svm_range_split_pages() gives the new range the number of VRAM pages counted in its part of the dma_addr arrays and subtracts it from the old range. Pages migrated to VRAM by a prefetch have no dma_addr entries until the range is mapped on a GPU, e.g. with no ACCESS attribute, or with XNACK off before the delayed restore worker mapped it, so the new range gets 0 and the old one keeps the count for both.

Migrating the parts back to system memory then gets the accounting
wrong: the old part keeps a VRAM page count after all its pages are gone, so its svm_bo is never freed, and the new part underflows. On navi31, as an unprivileged process: prefetch 4 MiB to the GPU, prefetch the upper 2 MiB and then the lower 2 MiB back to system memory:

Recorded vram pages(0x0) should not be less than migration pages(0x200).

  WARNING: ../amdkfd/kfd_migrate.c:922 at svm_migrate_vram_to_ram+0xbdc/0xcd0 [amdgpu]

and /sys/class/kfd/kfd/proc/<pid>/vram_<gpu_id> stays at 4194304 until the process exits.

Without dma_addr arrays, the split is still exact when the old range is completely in VRAM, which is what a prefetch of the whole range leaves. Give the new range all its pages in that case. The warning is gone and the VRAM usage drops back to 0.

This doesn't cover a range that is only partly in VRAM without dma_addr arrays, e.g. after a partial migration, since svm_migrate_ram_to_vram() only counts the pages it actually migrated. That would need VRAM residency to be tracked per page independently of dma_addr.

v2:
- Rename counted to has_dma_addr and compare against old->npages (Philip)
- Mention the XNACK off case and the partial migration limitation (Philip)

Fixes 006ad514a50c ("drm/amdkfd: Use partial hmm page walk during buffer validation in SVM")
(cherry picked from commit 7ca6f3359b557a267c7b07a2fd748b1473395e10)
---
 drivers/gpu/drm/amd/amdkfd/kfd_svm.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/amdkfd/kfd_svm.c +12 -1
index 27085694697a2..7bbeb9768a56f 100644
@@ -986,9 +986,12 @@ svm_range_split_pages(struct svm_range *new, struct svm_range *old,
 		      uint64_t start, uint64_t last)
 {
 	uint64_t npages = last - start + 1;
+	bool has_dma_addr = false;
 	int i, r;
 
 	for (i = 0; i < MAX_GPU_INSTANCE; i++) {
+		if (old->dma_addr[i])
+			has_dma_addr = true;
 		r = svm_range_split_array(&new->dma_addr[i], &old->dma_addr[i],
 					  sizeof(*old->dma_addr[i]), old->start,
 					  npages, new->start, new->npages,
@@ -996,8 +999,16 @@ svm_range_split_pages(struct svm_range *new, struct svm_range *old,
 		if (r)
 			return r;
 	}
-	if (old->actual_loc)
+	if (old->actual_loc) {
+		/*
+		 * Pages migrated by prefetch have no dma_addr until they are
+		 * mapped on a GPU. A fully resident range still splits exactly,
+		 * old->npages isn't adjusted yet here.
+		 */
+		if (!has_dma_addr && old->vram_pages == old->npages)
+			new->vram_pages = new->npages;
 		old->vram_pages -= new->vram_pages;
+	}
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#1502 lore raw

PATCH 1498/1536 drm/amd/display: Initialize missing TD-LUT programming inputs

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 167df3b94680b8670c4cacc08af232e3bfcab5ff ]

dml_core_mode_programming() memsets (clears) its scratch structure before calculating TD-LUT settings, but does not initialize tdlut_mpc_width_flag or is_gfx11.

Both inputs therefore remain false regardless of the plane configuration which can result in incorrect calculations.

Initialize both fields using the same sources as the mode support path (now both paths are aligned).

Fixes 70839da63605 ("drm/amd/display: Add new DCN401 sources")
(cherry picked from commit ad8d216e7d9fc050cdf39278e5fae17f61c36931)
---
 .../display/dc/dml2/dml21/src/dml2_core/dml2_core_dcn4_calcs.c  | 2 ++
 1 file changed, 2 insertions(+)
drivers/gpu/drm/amd/display/dc/dml2/dml21/src/dml2_core/dml2_core_dcn4_calcs.c +2 -0
index 37dd05d917685..043baa4283311 100644
@@ -10557,6 +10557,8 @@ static bool dml_core_mode_programming(struct dml2_core_calcs_mode_programming_ex
 		calculate_tdlut_setting_params->cursor_buffer_size = mode_lib->ip.cursor_buffer_size;
 		calculate_tdlut_setting_params->gpuvm_enable = display_cfg->gpuvm_enable;
 		calculate_tdlut_setting_params->gpuvm_page_size_kbytes = display_cfg->plane_descriptors[k].overrides.gpuvm_min_page_size_kbytes;
+		calculate_tdlut_setting_params->tdlut_mpc_width_flag = display_cfg->plane_descriptors[k].tdlut.tdlut_mpc_width_flag;
+		calculate_tdlut_setting_params->is_gfx11 = dml_get_gfx_version(display_cfg->plane_descriptors[k].surface.tiling);
 
 		// output
 		calculate_tdlut_setting_params->tdlut_pte_bytes_per_frame = &s->tdlut_pte_bytes_per_frame[k];
Signature · 1 line
2.53.0
author maintainer
#1503 lore raw

PATCH 1499/1536 drm/amdkfd: validate SRAT subtables before parsing

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 9866cb13ba4d39aa8fed34b765d4aecabe04f02e ]

The KFD SRAT walker reads the first subtable length without checking that a header is present and trusts subsequent lengths when accessing CPU and generic affinity records. Invalid firmware lengths can therefore cause out-of-bounds reads.

Validate the table header, every generic subtable range, and each supported typed record before reading its fields.

Fixes ddec8d3be0f8 ("drm/amdkfd: add ACPI SRAT parsing for topology")
(cherry picked from commit d76b655c98e8cc9e791b31502ad274f47dee2aae)
---
 drivers/gpu/drm/amd/amdkfd/kfd_crat.c | 35 ++++++++++++++++++---------
 1 file changed, 24 insertions(+), 11 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_crat.c +24 -11
index f4e40ed231fb0..22dfabc829b40 100644
@@ -2048,27 +2048,33 @@ static void kfd_find_numa_node_in_srat(struct kfd_node *kdev)
 		return;
 	}
 
+	if (table_header->length < sizeof(struct acpi_table_srat))
+		goto invalid_srat;
+
 	table_end = (unsigned long)table_header + table_header->length;
 
 	/* Parse all entries looking for a match. */
 	sub_header = (struct acpi_subtable_header *)
 			((unsigned long)table_header +
 			sizeof(struct acpi_table_srat));
-	subtable_len = sub_header->length;
 
-	while (((unsigned long)sub_header) + subtable_len  < table_end) {
-		/*
-		 * If length is 0, break from this loop to avoid
-		 * infinite loop.
-		 */
-		if (subtable_len == 0) {
-			pr_err("SRAT invalid zero length\n");
-			break;
-		}
+	while ((unsigned long)sub_header < table_end) {
+		unsigned long start = (unsigned long)sub_header;
+
+		if (table_end - start < sizeof(*sub_header))
+			goto invalid_srat;
+
+		subtable_len = sub_header->length;
+		if (subtable_len < sizeof(*sub_header) ||
+		    subtable_len > table_end - start)
+			goto invalid_srat;
 
 		switch (sub_header->type) {
 		case ACPI_SRAT_TYPE_CPU_AFFINITY:
 			cpu = (struct acpi_srat_cpu_affinity *)sub_header;
+			if (subtable_len < sizeof(*cpu))
+				goto invalid_srat;
+
 			pxm = *((u32 *)cpu->proximity_domain_hi) << 8 |
 					cpu->proximity_domain_lo;
 			if (pxm > max_pxm)
@@ -2076,6 +2082,9 @@ static void kfd_find_numa_node_in_srat(struct kfd_node *kdev)
 			break;
 		case ACPI_SRAT_TYPE_GENERIC_AFFINITY:
 			gpu = (struct acpi_srat_generic_affinity *)sub_header;
+			if (subtable_len < sizeof(*gpu))
+				goto invalid_srat;
+
 			bdf = *((u16 *)(&gpu->device_handle[0])) << 16 |
 					*((u16 *)(&gpu->device_handle[2]));
 			if (bdf == pci_id) {
@@ -2092,9 +2101,13 @@ static void kfd_find_numa_node_in_srat(struct kfd_node *kdev)
 
 		sub_header = (struct acpi_subtable_header *)
 				((unsigned long)sub_header + subtable_len);
-		subtable_len = sub_header->length;
 	}
 
+	goto out;
+
+invalid_srat:
+	pr_err("SRAT contains an invalid subtable\n");
+out:
 	acpi_put_table(table_header);
 
 	/* Workaround bad cpu-gpu binding case */
Signature · 1 line
2.53.0
author maintainer
#1504 lore raw

PATCH 1500/1536 drm/amdkfd: evict the queues only once for CRIU PROCESS_INFO

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

criu_process_info() evicts the queues of the process on every call, and each kfd_process_evict_queues() increments qpd->evicted, but CRIU UNPAUSE restores them only once. After PROCESS_INFO twice and UNPAUSE the queues stay evicted for good. On navi31, a barrier-AND packet on an HSA queue completes after PROCESS_INFO + UNPAUSE, but times out after PROCESS_INFO, PROCESS_INFO, UNPAUSE.

The error path has a related problem: when kfd_process_evict_queues() itself fails, it has already rolled back its partial eviction, and the kfd_process_restore_queues() in the error path restores once more.

Evict only when the queues are not paused yet, and on errors only undo an eviction done by this call. The barrier now completes after any number of PROCESS_INFO calls followed by UNPAUSE.

Fixes cd9f79103003 ("drm/amdkfd: CRIU Implement KFD unpause operation")
(cherry picked from commit 4d79c9e3c32c677fcadf5ca10ab81ee0a4b81f99)
---
 drivers/gpu/drm/amd/amdkfd/kfd_chardev.c | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +10 -5
index 5224733a1de39..9cdf7a0fbdf84 100644
@@ -2702,6 +2702,7 @@ static int criu_process_info(struct file *filep,
 				struct kfd_process *p,
 				struct kfd_ioctl_criu_args *args)
 {
+	bool paused_here = false;
 	int ret = 0;
 
 	mutex_lock(&p->mutex);
@@ -2712,11 +2713,15 @@ static int criu_process_info(struct file *filep,
 		goto err_unlock;
 	}
 
-	ret = kfd_process_evict_queues(p, KFD_QUEUE_EVICTION_CRIU_CHECKPOINT);
-	if (ret)
-		goto err_unlock;
+	/* UNPAUSE restores the queues once, so evict them only once */
+	if (!p->queues_paused) {
+		ret = kfd_process_evict_queues(p, KFD_QUEUE_EVICTION_CRIU_CHECKPOINT);
+		if (ret)
+			goto err_unlock;
 
-	p->queues_paused = true;
+		p->queues_paused = true;
+		paused_here = true;
+	}
 
 	args->pid = task_pid_nr_ns(p->lead_thread,
 					task_active_pid_ns(p->lead_thread));
@@ -2731,7 +2736,7 @@ static int criu_process_info(struct file *filep,
 				args->priv_data_size);
 
 err_unlock:
-	if (ret) {
+	if (ret && paused_here) {
 		kfd_process_restore_queues(p);
 		p->queues_paused = false;
 	}
Signature · 1 line
2.53.0
author maintainer
#1505 lore raw

PATCH 1501/1536 macvlan: fix passthru promiscuity accounting while down

In reply to Greg Kroah-Hartman

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

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

From: Xia Yan <[email protected]>

[ Upstream commit b6743653d134c9ef8436e2db1be1ad4c1e0d0091 ]

macvlan_changelink() adjusts the lower device's promiscuity count when NOPROMISC changes, even if the passthru macvlan is down. The reference is acquired in macvlan_open() and released in macvlan_stop(), so a down interface has no reference to change.

Clearing NOPROMISC while down leaves an extra reference after the next open/stop cycle. Setting it while down can remove a reference held by another user of the lower device.

Guard the count adjustment with netif_running(dev). Keep storing the requested flags while down so the next open uses the new setting.

Comparing changelink with open/stop exposed the unmatched count changes; the same issue was also described in earlier macvlan reviews. A netlink test on UML reproduced both DOWN cases before the fix and verified the expected counts afterwards. Repeated flag updates, two open/stop cycles, deletion and bidirectional small-frame delivery were also checked.

Full x86_64 builds completed with WERROR disabled for allmodconfig, and WERROR and KASAN disabled for allyesconfig, including the resulting dependency changes. Neither comparison showed new diagnostics.

---
 drivers/net/macvlan.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/macvlan.c +2 -1
index 4d1aae8e89cf0..03adfac510b4e 100644
@@ -1626,7 +1626,8 @@ static int macvlan_changelink(struct net_device *dev,
 	if (data && data[IFLA_MACVLAN_FLAGS]) {
 		__u16 flags = nla_get_u16(data[IFLA_MACVLAN_FLAGS]);
 		bool promisc = (flags ^ vlan->flags) & MACVLAN_FLAG_NOPROMISC;
-		if (macvlan_passthru(vlan->port) && promisc) {
+		if (macvlan_passthru(vlan->port) && promisc &&
+		    netif_running(dev)) {
 			int err;
 
 			if (flags & MACVLAN_FLAG_NOPROMISC)
Signature · 1 line
2.53.0
author maintainer
#1506 lore raw

PATCH 1502/1536 net: hisilicon: hisi_femac: Stop the receiver before releasing the RX ring

In reply to Greg Kroah-Hartman

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

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

From: David Yang <[email protected]>

[ Upstream commit d54b21d824302af52d06574870817fbe14774dab ]

hisi_femac_net_close() frees the receive ring while the RX address queue still holds every address that was pushed to IQ_ADDR.

A port that keeps receiving then DMAs arrived frames into buffers that other slab caches have already taken back; on an EC6108V9C (hi3798mv100) the queue still held all 52 armed addresses right after the interface was closed, and had dropped to 43 after 15 s of broadcast traffic.

Reset the port before the buffers are released, so that the receiver no longer holds any of their addresses.

Fixes 542ae60af24f ("net: hisilicon: Add Fast Ethernet MAC driver")
---
 drivers/net/ethernet/hisilicon/hisi_femac.c | 1 +
 1 file changed, 1 insertion(+)
drivers/net/ethernet/hisilicon/hisi_femac.c +1 -0
index 2406263c9dd3a..deb6ea79ac758 100644
@@ -491,6 +491,7 @@ static int hisi_femac_net_close(struct net_device *dev)
 	netif_stop_queue(dev);
 	napi_disable(&priv->napi);
 
+	hisi_femac_port_reset(priv);
 	hisi_femac_free_skb_rings(priv);
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#1507 lore raw

PATCH 1503/1536 fs/ntfs3: bound CreateAttribute asize against record_size in do_action

In reply to Greg Kroah-Hartman

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

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

From: Hyeontae Lee <[email protected]>

[ Upstream commit fb0f0ef7b5a6bc761b372ce00764d4b6e0b91a47 ]

In do_action()'s CreateAttribute case (fslog.c:3286), attr2 points into the on-disk log record and asize = le32_to_cpu(attr2->size) is therefore attacker-controlled on mount. The guard bounds asize only against the log record itself,

Add2Ptr(attr2, asize) > Add2Ptr(lrh, rec_len)

where rec_len is the client data length, and separately bounds dlen against the MFT record. Nothing bounds asize against record_size, but all three writes that follow are into rec, a kmalloc(sbi->record_size) buffer allocated by mi_init() (record.c:105):

	memmove(Add2Ptr(attr, asize), attr, used - roff);
	memcpy(attr, attr2, asize);
	rec->used = cpu_to_le32(used + asize);

With record_size 0x400, roff 0x38, used 0x160 and asize 0x800 the memcpy writes 2048 bytes at rec + 0x38, 0x438 bytes past the allocation, and rec->used is left at 0x960. dlen is 0x18 here, so the existing dlen check passes: dlen bounds nothing about the size of the copy.

The equivalent non-replay path already refuses this. mi_insert_attr() performs the same insert and starts with (record.c:488):

	if (used + asize > sbi->record_size)
		return NULL;

Apply the same bound, spelled as a subtraction to match the neighbouring clause. used <= record_size holds here because check_file_record() validates it (fslog.c:2826) and is called on this record at fslog.c:3172; roff <= used - 4 follows from check_if_attr() together with the ATTR_END check at fslog.c:2844, so bounding used + asize bounds both copies.

The sibling WriteEndOfFileRecordSegment case does the equivalent check against record_size at fslog.c:3277.

Reproduced by mounting a crafted image on v7.2-rc5 under KASAN:

  BUG: KASAN: slab-out-of-bounds in do_action.isra.0+0x41f6/0x83a0
  Write of size 2048 at addr ffff888005c74838 by task mount/69

  CPU: 0 UID: 0 PID: 69 Comm: mount Not tainted 7.2.0-rc5-00300-g8ba098e6b6ff #2
  Call Trace:
   kasan_report+0xce/0x100
   kasan_check_range+0x105/0x1b0
   __asan_memcpy+0x3c/0x60
   do_action.isra.0+0x41f6/0x83a0
   log_replay+0x920a/0xd300
   ntfs_loadlog_and_replay+0x3ef/0x510
   ntfs_fill_super+0x1d23/0x4550
   get_tree_bdev_flags+0x2ef/0x550
   vfs_get_tree+0x82/0x2f0
   fc_mount+0x10/0x1b0
   path_mount+0x517/0x1df0
   __x64_sys_mount+0x20b/0x270
   do_syscall_64+0xf9/0x540
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

  Allocated by task 69:
   __kasan_kmalloc+0x8f/0xa0
   __kmalloc_noprof+0x1b4/0x460
   mi_init+0x81/0x110
   mi_get+0x6a/0x220
   do_action.isra.0+0x1db4/0x83a0
   log_replay+0x920a/0xd300
   ntfs_loadlog_and_replay+0x3ef/0x510
   ntfs_fill_super+0x1d23/0x4550

  The buggy address belongs to the object at ffff888005c74800
   which belongs to the cache kmalloc-1k of size 1024
  The buggy address is located 56 bytes inside of
   allocated 1024-byte region [ffff888005c74800, ffff888005c74c00)
Fixes b46acd6a6a62 ("fs/ntfs3: Add NTFS journal")
Assisted-by Claude:claude-opus-5
---
 fs/ntfs3/fslog.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
fs/ntfs3/fslog.c +6 -1
index ab803ba6c5674..e3d0a859c230b 100644
@@ -3304,10 +3304,15 @@ static int do_action(struct ntfs_log *log, struct OPEN_ATTR_ENRTY *oe,
 		asize = le32_to_cpu(attr2->size);
 		used = le32_to_cpu(rec->used);
 
+		/*
+		 * attr2->size is taken from the log record and is bounded only
+		 * by the log record length, not by the MFT record.  Refuse an
+		 * attribute that does not fit, as mi_insert_attr() does.
+		 */
 		if (!check_if_attr(rec, lrh) || dlen < SIZEOF_RESIDENT ||
 		    !IS_ALIGNED(asize, 8) ||
 		    Add2Ptr(attr2, asize) > Add2Ptr(lrh, rec_len) ||
-		    dlen > record_size - used) {
+		    dlen > record_size - used || asize > record_size - used) {
 			goto dirty_vol;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#1508 lore raw

PATCH 1504/1536 fs/ntfs3: bound DeleteAttribute asize against rec->used in do_action

In reply to Greg Kroah-Hartman

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

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

From: Hyeontae Lee <[email protected]>

[ Upstream commit 408216b66afd9ddadaba2dce56fd4af6793e95a2 ]

In do_action()'s DeleteAttribute case (fslog.c:3316), attr is Add2Ptr(rec, roff) with roff taken from the on-disk lrh->record_off, and asize = le32_to_cpu(attr->size) is read straight out of the MFT record:

	asize = le32_to_cpu(attr->size);
	used  = le32_to_cpu(rec->used);

	if (!check_if_attr(rec, lrh))
		goto dirty_vol;
	...
	memmove(attr, Add2Ptr(attr, asize), used - asize - roff);

check_if_attr() (fslog.c:2869) walks the attribute chain from rec->attr_off and returns o == ro. Its loop breaks on ATTR_END, so ro may legitimately equal the offset of the ATTR_END marker; that is exactly how CreateAttribute appends to a record. But check_file_record()'s walk (fslog.c:2831) also stops at ATTR_END, so check_attr() never inspects the bytes there. When roff is the ATTR_END offset, those never-validated bytes are what gets read as attr->size, and used - asize - roff underflows.

The read itself is also unbounded: roff is a u16 and attr->size is dereferenced at fslog.c:3317, before check_if_attr() has constrained roff at all, so it can be up to ~64K past a record_size-sized object.

Commit 0ca0485e4b2e ("fs/ntfs3: validate rec->used in journal-replay file record check") added at fslog.c:2844

	if (used < PtrOffset(rec, attr) + sizeof(attr->type))
		return false;

and its changelog names this very memmove. It bounds rec->used against the ATTR_END offset; it does not bound asize. With record_size 0x400, attr_off 0x38, a valid three-attribute chain ending in ATTR_END at 0x158 and used 0x160, a record whose four bytes at 0x15c read 0x100 gives

	used - asize - roff = 0x160 - 0x100 - 0x158 = 0xffffff08

i.e. a ~4 GiB memmove whose source and destination both run off the end of rec, a kmalloc(sbi->record_size) object (record.c:105).

The equivalent non-replay path already refuses this. mi_remove_attr() performs the same removal and starts with (record.c:548):

	if (aoff + asize > used)
		return false;

Apply the same bound, spelled as a subtraction to match the neighbouring cases, and move the attr->size read after check_if_attr() so that the header is known to lie inside the record before it is dereferenced. Requiring roff + SIZEOF_RESIDENT <= used rejects the ATTR_END offset without rejecting any real attribute: for an attribute the walk validated, roff + asize <= off(ATTR_END) <= used - 4, and any attribute a DeleteAttribute record can legitimately name carries a full resident header, so roff + SIZEOF_RESIDENT <= roff + asize <= used - 4. check_attr() itself imposes no lower bound on asize, so a crafted sub-header asize can still pass the first test; the second test then bounds it and the memmove stays inside the record.

Reproduced by mounting a crafted image on v7.2-rc5, which already contains 0ca0485e4b2e, under KASAN. The image is an ordinary mkfs.ntfs volume with four bytes of one MFT record changed and a crafted $LogFile:

  BUG: KASAN: slab-out-of-bounds in do_action.isra.0+0x3211/0x83c0
  Read of size 4294967048 at addr ffff888002423258 by task mount/66

  CPU: 1 UID: 0 PID: 66 Comm: mount Not tainted 7.2.0-rc5 #3
  Call Trace:
   kasan_report+0xce/0x100
   kasan_check_range+0x105/0x1b0
   __asan_memmove+0x23/0x60
   do_action.isra.0+0x3211/0x83c0
   log_replay+0x920a/0xd300
   ntfs_loadlog_and_replay+0x3ef/0x510
   ntfs_fill_super+0x1d23/0x4550
   get_tree_bdev_flags+0x2ef/0x550
   vfs_get_tree+0x82/0x2f0
   fc_mount+0x10/0x1b0
   path_mount+0x517/0x1df0
   __x64_sys_mount+0x20b/0x270
   do_syscall_64+0xf9/0x540
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

  Allocated by task 66:
   __kasan_kmalloc+0x8f/0xa0
   __kmalloc_noprof+0x1b4/0x460
   mi_init+0x81/0x110
   mi_get+0x6a/0x220
   do_action.isra.0+0x1dbf/0x83c0
   log_replay+0x920a/0xd300
   ntfs_loadlog_and_replay+0x3ef/0x510
   ntfs_fill_super+0x1d23/0x4550

  The buggy address belongs to the object at ffff888002423000
   which belongs to the cache kmalloc-1k of size 1024
  The buggy address is located 600 bytes inside of
   allocated 1024-byte region [ffff888002423000, ffff888002423400)

KASAN reports the source side because __asan_memmove() (mm/kasan/shadow.c:94) validates src before dest and returns without copying. Both ends are out of bounds, and on a kernel built without KASAN the copy is performed.

rec->used is also left at used - asize by fslog.c:3323 before the memmove, so the record stays inconsistent even when the copy is suppressed; the same mount goes on to report "ino=1a, mi_enum_attr" and marks the volume dirty.

Fixes b46acd6a6a62 ("fs/ntfs3: Add NTFS journal")
Assisted-by Claude:claude-opus-5
---
 fs/ntfs3/fslog.c | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)
fs/ntfs3/fslog.c +13 -2
index e3d0a859c230b..5774fc1bd0683 100644
@@ -3342,10 +3342,21 @@ static int do_action(struct ntfs_log *log, struct OPEN_ATTR_ENRTY *oe,
 		break;
 
 	case DeleteAttribute:
-		asize = le32_to_cpu(attr->size);
 		used = le32_to_cpu(rec->used);
 
-		if (!check_if_attr(rec, lrh))
+		/*
+		 * check_if_attr() accepts a record_off that points at the
+		 * ATTR_END marker, which is how CreateAttribute appends.  The
+		 * bytes there are not an attribute and check_attr() never
+		 * validated them, so refuse an offset that cannot hold a
+		 * resident header before reading attr->size, and then bound it
+		 * as mi_remove_attr() does.
+		 */
+		if (!check_if_attr(rec, lrh) || roff + SIZEOF_RESIDENT > used)
+			goto dirty_vol;
+
+		asize = le32_to_cpu(attr->size);
+		if (asize > used - roff)
 			goto dirty_vol;
 
 		rec->used = cpu_to_le32(used - asize);
Signature · 1 line
2.53.0
author maintainer
#1509 lore raw

PATCH 1505/1536 ntfs3: fix mapping pairs bounds check for alignment

In reply to Greg Kroah-Hartman

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

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

From: Hongling Zeng <[email protected]>

[ Upstream commit f517cae6333121783043d9ba5142b50f5d1cf75b ]

In the UpdateMappingPairs action, the expansion check compares the unaligned new attribute size with the available record space. The new size is aligned to an 8-byte boundary before the mapping pairs are updated, so the check can underestimate the required space by up to seven bytes.

Use the aligned size in the expansion check to ensure that the subsequent update cannot exceed the available record space.

Fixes b46acd6a6a62 ("fs/ntfs3: Add NTFS journal")
---
 fs/ntfs3/fslog.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/ntfs3/fslog.c +2 -1
index 5774fc1bd0683..2a1f1a7f5b012 100644
@@ -3438,7 +3438,8 @@ static int do_action(struct ntfs_log *log, struct OPEN_ATTR_ENRTY *oe,
 
 		if (!check_if_attr(rec, lrh) || !attr->non_res ||
 		    aoff < le16_to_cpu(attr->nres.run_off) || aoff > asize ||
-		    (nsize > asize && nsize - asize > record_size - used)) {
+		    (nsize > asize &&
+		     ALIGN(nsize, 8) - asize > record_size - used)) {
 			goto dirty_vol;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#1510 lore raw

PATCH 1506/1536 ASoC: hdac_hda: Keep runtime PM state in sync across codec remove/probe

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 99203e8d8968def973e82bb712ea959c6a46c16e ]

After the codec has been removed, its runtime PM status is RPM_SUSPENDED while hdac_hda_codec_probe() powers the codec up via snd_hda_codec_device_new(). The pm_runtime_put()/snd_hda_power_down() calls on probe and registration then see an already suspended device, the codec suspend callback is not called and the codec, its HDA link and the codec_powered bit stay set, preventing the controller from runtime suspending.

The remove has a similar problem with the codec link accounting:
hdac_hda_codec_remove() drops the link reference taken in probe without looking at the runtime PM state of the codec. If the codec was already runtime suspended, the link reference has been dropped by the codec suspend callback and the remove drops it a second time.

Resume the codec in hdac_hda_codec_remove() before disabling runtime PM so that the link reference and the codec_powered bit are always in the same state as after the probe, and mark the device active on probe once the codec has been powered up.

Finally mark the codec device suspended at the end of the remove. Its runtime PM is disabled at this point and if only the ASoC card is unbound (e.g. by unbinding the machine driver), a following system suspend would otherwise call the runtime suspend callback on the already cleaned up codec via pm_runtime_force_suspend().

This is a followup patch to address Sashiko reports.

---
 sound/soc/codecs/hdac_hda.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
sound/soc/codecs/hdac_hda.c +12 -0
index 9c4a4b5779293..25a145cb8a510 100644
@@ -517,6 +517,9 @@ static int hdac_hda_codec_probe(struct snd_soc_component *component)
 		snd_hdac_display_power(hdev->bus,
 				       HDA_CODEC_IDX_CONTROLLER, false);
 
+	/* The codec is in D0, the status is RPM_SUSPENDED after a previous unbind */
+	pm_runtime_set_active(&hdev->dev);
+
 	/* match for forbid call in snd_hda_codec_device_new() */
 	pm_runtime_allow(&hdev->dev);
 
@@ -556,6 +559,12 @@ static void hdac_hda_codec_remove(struct snd_soc_component *component)
 		return;
 	}
 
+	/*
+	 * Resume the codec to have its link reference (dropped below) and
+	 * codec_powered bit in the same state as after the probe.
+	 */
+	pm_runtime_get_sync(&hdev->dev);
+
 	/* prevent runtime PM callbacks while the link and the codec are torn down */
 	pm_runtime_disable(&hdev->dev);
 	snd_hdac_ext_bus_link_put(hdev->bus, hlink);
@@ -567,6 +576,9 @@ static void hdac_hda_codec_remove(struct snd_soc_component *component)
 
 	/* Balances the disable above, cleanup_for_unbind keeps runtime PM disabled */
 	pm_runtime_enable(&hdev->dev);
+	pm_runtime_put_noidle(&hdev->dev);
+	/* The codec is cleaned up, system suspend must skip it from now on */
+	pm_runtime_set_suspended(&hdev->dev);
 }
 
 static const struct snd_soc_dapm_route hdac_hda_dapm_routes[] = {
Signature · 1 line
2.53.0
author maintainer
#1511 lore raw

PATCH 1507/1536 ppp: fix stale pointer access after pskb_may_pull in ppp_ccp_peek

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

ppp_ccp_peek() caches a pointer to skb->data in dp after the first pskb_may_pull(), then uses dp after a second pskb_may_pull(skb, len + 2) in the CCP_CONFACK handler. If the second pull triggers pskb_expand_head() due to a cloned skb or frag linearization, skb->head is freed and reallocated, leaving dp stale.

The stale dp is subsequently used in CCP_OPT_LENGTH() and passed to decomp_init()/comp_init() which read from the freed memory.

Re-derive dp from skb->data after the second pskb_may_pull.

Fixes 1da177e4c3f41 ("Linux-2.6.12-rc2")
---
 drivers/net/ppp/ppp_generic.c | 1 +
 1 file changed, 1 insertion(+)
drivers/net/ppp/ppp_generic.c +1 -0
index 5d6d69632c847..4d4591ea443a9 100644
@@ -3158,6 +3158,7 @@ ppp_ccp_peek(struct ppp *ppp, struct sk_buff *skb, int inbound)
 		len = CCP_LENGTH(dp);
 		if (!pskb_may_pull(skb, len + 2))
 			return;		/* too short */
+		dp = skb->data + 2;
 		dp += CCP_HDRLEN;
 		len -= CCP_HDRLEN;
 		if (len < CCP_OPT_MINLEN || len < CCP_OPT_LENGTH(dp))
Signature · 1 line
2.53.0
author maintainer
#1512 lore raw

PATCH 1508/1536 nvmet-rdma: reject short connection requests

In reply to Greg Kroah-Hartman

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

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

From: Weiming Shi <[email protected]>

[ Upstream commit 635e760169a87abf03874cd4636cd91b580cb427 ]

nvmet_rdma_parse_cm_connect_req() treats RDMA-CM private data as a struct nvme_rdma_cm_req but accepts any nonzero private_data_len. The iWARP path allocates exactly the peer-provided length, so a six-byte MPA request reaches the parser and the hsqsize load reads two bytes past the allocation.

Require the complete request structure before reading any of its fields. The decoded KASAN report is:

  BUG: KASAN: slab-out-of-bounds in nvmet_rdma_cm_handler
    (drivers/nvme/target/rdma.c:1427 drivers/nvme/target/rdma.c:1475
     drivers/nvme/target/rdma.c:1614 drivers/nvme/target/rdma.c:1814)
  Read of size 2 at addr ff1100010459d366 by task kworker/u16:1/41
  Workqueue: iw_cm_wq cm_work_handler
  Call Trace:
   <TASK>
   dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120)
   print_report (mm/kasan/report.c:378 mm/kasan/report.c:482)
   kasan_report (mm/kasan/report.c:595)
   nvmet_rdma_cm_handler
    (drivers/nvme/target/rdma.c:1427 drivers/nvme/target/rdma.c:1475
     drivers/nvme/target/rdma.c:1614 drivers/nvme/target/rdma.c:1814)
   cma_cm_event_handler (drivers/infiniband/core/cma.c:2181)
   iw_conn_req_handler (drivers/infiniband/core/cma.c:2640)
   cm_work_handler
    (drivers/infiniband/core/cm.c:2502
     drivers/infiniband/core/cm.c:3858)
   process_one_work (kernel/workqueue.c:3396)
   worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560)
   kthread (kernel/kthread.c:436)
   ret_from_fork (arch/x86/kernel/process.c:158)
   ret_from_fork_asm (arch/x86/entry/entry_64.S:245)
   </TASK>

  Allocated by task 12:
   __kasan_kmalloc (mm/kasan/common.c:398 mm/kasan/common.c:415)
   __kmalloc_node_track_caller_noprof
    (mm/slub.c:5414 mm/slub.c:5545)
   kmemdup_noprof (mm/util.c:138)
   cm_event_handler
    (drivers/infiniband/core/iwcm.c:194
     drivers/infiniband/core/iwcm.c:1076)
   siw_cm_upcall (drivers/infiniband/sw/siw/siw_cm.c:408)
   siw_proc_mpareq (drivers/infiniband/sw/siw/siw_cm.c:750)
   siw_cm_work_handler (drivers/infiniband/sw/siw/siw_cm.c:1086)

The buggy address is located 0 bytes to the right of allocated 6-byte region [ff1100010459d360, ff1100010459d366)

Fixes 8f000cac6e7a ("nvmet-rdma: add a NVMe over Fabrics RDMA target driver")
Assisted-by LLM
---
 drivers/nvme/target/rdma.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/target/rdma.c +1 -1
index c5227d2670c4b..01b7722afb5e8 100644
@@ -1410,7 +1410,7 @@ nvmet_rdma_parse_cm_connect_req(struct rdma_conn_param *conn,
 	struct nvme_rdma_cm_req *req;
 
 	req = (struct nvme_rdma_cm_req *)conn->private_data;
-	if (!req || conn->private_data_len == 0)
+	if (!req || conn->private_data_len < sizeof(*req))
 		return NVME_RDMA_CM_INVALID_LEN;
 
 	if (le16_to_cpu(req->recfmt) != NVME_RDMA_CM_FMT_1_0)
Signature · 1 line
2.53.0
author maintainer
#1513 lore raw

PATCH 1509/1536 nvmet-fc: only send read data for successful commands

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 94f93c61b1a5dd08d011be58172ce4392b849008 ]

When a read command completes with an error, __nvmet_fc_fcp_nvme_cmd_done() still pushes the whole data buffer to the host before the response. nvmet_fc_alloc_tgt_pgs() allocates that buffer with sgl_alloc() and no __GFP_ZERO, and a command rejected by nvmet_check_transfer_len() leaves it untouched, so the host receives stale target memory.

The buffer is as large as the data length in the command IU, so the amount of stale memory returned is up to the host.

The tcp and rdma targets send data only when cqe->status is zero (see nvmet_tcp_need_data_out() and nvmet_rdma_need_data_out()), so no nvmet command can rely on returning data with an error status. Do the same for fc. The ERSP then reports a transferred length of fod->offset, which is 0, matching what nvme_fc_fcpio_done() checks on the host.

Tested over nvme-fcloop: a failed read command no longer transfers data and still completes with its error status, and successful reads are unaffected.

Fixes c53432030d86 ("nvme-fabrics: Add target support for FC transport")
---
 drivers/nvme/target/fc.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/nvme/target/fc.c +4 -4
index 4e54681ab4936..90948e09b5d2a 100644
@@ -2468,11 +2468,11 @@ __nvmet_fc_fcp_nvme_cmd_done(struct nvmet_fc_tgtport *tgtport,
 	} else {
 
 		/*
-		 * try to push the data even if the SQE status is non-zero.
-		 * There may be a status where data still was intended to
-		 * be moved
+		 * A failed command may not have filled its read buffer, so
+		 * only push data for success, as the tcp and rdma targets do.
 		 */
-		if ((fod->io_dir == NVMET_FCP_READ) && (fod->data_sg_cnt)) {
+		if (fod->io_dir == NVMET_FCP_READ && fod->data_sg_cnt &&
+		    !cqe->status) {
 			/* push the data over before sending rsp */
 			nvmet_fc_transfer_fcp_data(tgtport, fod,
 						NVMET_FCOP_READDATA);
Signature · 1 line
2.53.0
author maintainer
#1514 lore raw

PATCH 1510/1536 nvmet-auth: fix error handling on CHALLENGE failure

In reply to Greg Kroah-Hartman

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

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

From: Shao Mingyin <[email protected]>

[ Upstream commit 96da408bb4a24bf87b366b13f41c2687d3c05671 ]

In nvmet_execute_auth_receive(), when nvmet_auth_challenge() fails (for example when the initiator-supplied allocation length is shorter than the DH-HMAC-CHAP challenge response, or the challenge nonce allocation fails), the error path sets status = NVME_SC_INTERNAL and breaks out of the switch. The unconditional

    status = nvmet_copy_to_sgl(req, 0, d, al);

after the switch then overwrites the error status (nvmet_copy_to_sgl() returns 0 on success), so the AUTH_RECEIVE command incorrectly completes with SUCCESS and the initiator proceeds with a truncated/empty challenge.

Fix this by freeing the buffer and jumping to the common done: label on CHALLENGE failure, skipping the copy_to_sgl() entirely and preserving the NVME_SC_INTERNAL status.

Fixes db1312dd9548 ("nvmet: implement basic In-Band Authentication")
---
 drivers/nvme/target/fabrics-cmd-auth.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/nvme/target/fabrics-cmd-auth.c +4 -3
index de1a6d1a27a33..72446965028c5 100644
@@ -551,10 +551,11 @@ void nvmet_execute_auth_receive(struct nvmet_req *req)
 	switch (req->sq->dhchap_step) {
 	case NVME_AUTH_DHCHAP_MESSAGE_CHALLENGE:
 		if (nvmet_auth_challenge(req, d, al) < 0) {
-			pr_warn("ctrl %d qid %d: challenge error (%d)\n",
-				ctrl->cntlid, req->sq->qid, status);
+			pr_warn("ctrl %d qid %d: challenge error\n",
+				ctrl->cntlid, req->sq->qid);
 			status = NVME_SC_INTERNAL;
-			break;
+			kfree(d);
+			goto done;
 		}
 		req->sq->dhchap_step = NVME_AUTH_DHCHAP_MESSAGE_REPLY;
 		break;
Signature · 1 line
2.53.0
author maintainer
#1515 lore raw

PATCH 1511/1536 nvmet-fc: Tear down the association when the admin queue allocation fails

In reply to Greg Kroah-Hartman

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

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

From: Guixin Liu <[email protected]>

[ Upstream commit 11db8ab55e1a7533e9cfe57687ab142ba67d3c84 ]

When the initial admin queue allocation fails after a new association was created, nvmet_fc_ls_create_association() only drops the association reference, which frees the association. By then the association is already on the target port's assoc_list, though, and removal from that list only happens in nvmet_fc_delete_target_assoc(), which this error path never calls. The freed association stays on the list, where later lookups and the port teardown can access it, and the target port reference taken at allocation time leaks.

A remote host can trigger this reliably with a Create Association LS requesting a queue too large to allocate.

Schedule the regular association teardown instead of dropping the reference directly. The teardown removes the association from the list and releases the target port reference before the final reference drop frees it.

Fixes 0cab4404874f ("nvme-fc: fix a missing queue put in nvmet_fc_ls_create_association")
---
 drivers/nvme/target/fc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/target/fc.c +1 -1
index 90948e09b5d2a..f20338e7b669e 100644
@@ -1685,7 +1685,7 @@ nvmet_fc_ls_create_association(struct nvmet_fc_tgtport *tgtport,
 					be16_to_cpu(rqst->assoc_cmd.sqsize));
 			if (!queue) {
 				ret = VERR_QUEUE_ALLOC_FAIL;
-				nvmet_fc_tgt_a_put(iod->assoc);
+				nvmet_fc_schedule_delete_assoc(iod->assoc);
 			}
 		}
 	}
Signature · 1 line
2.53.0
author maintainer
#1516 lore raw

PATCH 1512/1536 nvme-tcp: start error recovery when read_sock fails

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 288cfa187208cc9d0809eb8e1508658151a444dd ]

nvme_tcp_recv_skb() disables the queue and starts error recovery for errors it detects itself. An error returned by the transport reaches nvme_tcp_try_recv() without either action.

nvme_tcp_io_work() returns on a negative result and does not requeue itself, so the queue stops receiving and remains stalled until a command times out.

Report the error and start error recovery when the queue is still enabled, which indicates that the error was not handled by the actor. Do this under the socket lock, as nvme_tcp_recv_skb() does.

Fixes be8e82caa685 ("nvme-tcp: enable TLS handshake upcall")
Assisted-by LLM
---
 drivers/nvme/host/tcp.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
drivers/nvme/host/tcp.c +13 -0
index 93e743d6e9846..67d02cfb47ec7 100644
@@ -1421,6 +1421,19 @@ static int nvme_tcp_try_recv(struct nvme_tcp_queue *queue)
 	lock_sock(sk);
 	queue->nr_cqe = 0;
 	consumed = sock->ops->read_sock(sk, &rd_desc, nvme_tcp_recv_skb);
+	/*
+	 * nvme_tcp_recv_skb() handles its own errors, so a queue that is
+	 * still enabled failed inside read_sock(). Handle it before
+	 * release_sock() processes the backlog.
+	 */
+	if (unlikely(consumed < 0 && consumed != -EAGAIN &&
+		     queue->rd_enabled)) {
+		dev_err(queue->ctrl->ctrl.device,
+			"queue %d: receive failed: %d\n",
+			nvme_tcp_queue_id(queue), consumed);
+		queue->rd_enabled = false;
+		nvme_tcp_error_recovery(&queue->ctrl->ctrl);
+	}
 	release_sock(sk);
 	return consumed == -EAGAIN ? 0 : consumed;
 }
Signature · 1 line
2.53.0
author maintainer
#1517 lore raw

PATCH 1513/1536 nvmet: Finish the blk plug when integrity allocation fails

In reply to Greg Kroah-Hartman

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

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

From: Guixin Liu <[email protected]>

[ Upstream commit 18fc5f6f1ca945630dae5404265de55d65194e22 ]

nvmet_bdev_execute_rw() starts a plug before building the bios, but the two error exits taken when nvmet_bdev_alloc_bip() fails return without calling blk_finish_plug(). current->plug is left pointing at the stack frame of the returned function, so the next blk_flush_plug() walks a stale list.

Route both failures through a common exit that finishes the plug.

Fixes c6e3f13398123 ("nvmet: add metadata support for block devices")
---
 drivers/nvme/target/io-cmd-bdev.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/nvme/target/io-cmd-bdev.c +3 -2
index ff6082d03edaf..3b081f421c81d 100644
@@ -298,7 +298,7 @@ static void nvmet_bdev_execute_rw(struct nvmet_req *req)
 							  &prot_miter);
 				if (unlikely(rc)) {
 					bio_io_error(bio);
-					return;
+					goto out_plug;
 				}
 			}
 
@@ -318,11 +318,12 @@ static void nvmet_bdev_execute_rw(struct nvmet_req *req)
 		rc = nvmet_bdev_alloc_bip(req, bio, &prot_miter);
 		if (unlikely(rc)) {
 			bio_io_error(bio);
-			return;
+			goto out_plug;
 		}
 	}
 
 	submit_bio(bio);
+out_plug:
 	blk_finish_plug(&plug);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1518 lore raw

PATCH 1514/1536 nvmet: Free the old negotiation state when restarting authentication

In reply to Greg Kroah-Hartman

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

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

From: Guixin Liu <[email protected]>

[ Upstream commit 5c279fcabb0ea7ba61881c13027b15d8054b8abd ]

Restarting a DH-HMAC-CHAP negotiation with SEND(NEGOTIATE) resets sq->dhchap_step but does not release the previous c1/c2/skey, which are only freed in nvmet_auth_sq_free() at teardown. The next CHALLENGE/REPLY exchange then overwrites those pointers with fresh allocations.

An unauthenticated host can repeat the negotiate message endlessly, leaking a few dozen bytes per round and slowly exhausting target memory.

Clear the old negotiation state with nvmet_auth_sq_free() before setting up the new one. Also reset dhchap_skey_len to zero: if a DH session key was already established, a following round with dhvlen=0 would otherwise pass a NULL skey with a stale non-zero length to the HMAC code and dereference it.

Fixes db1312dd95488 ("nvmet: implement basic In-Band Authentication")
---
 drivers/nvme/target/auth.c             | 1 +
 drivers/nvme/target/fabrics-cmd-auth.c | 1 +
 2 files changed, 2 insertions(+)
drivers/nvme/target/auth.c +1 -0
index ba12b59c67304..de4fd9eeeafb0 100644
@@ -240,6 +240,7 @@ void nvmet_auth_sq_free(struct nvmet_sq *sq)
 	sq->dhchap_c2 = NULL;
 	kfree(sq->dhchap_skey);
 	sq->dhchap_skey = NULL;
+	sq->dhchap_skey_len = 0;
 }
 
 void nvmet_auth_sq_destroy(struct nvmet_sq *sq)
drivers/nvme/target/fabrics-cmd-auth.c +1 -0
index 72446965028c5..cfd1fc6032593 100644
@@ -279,6 +279,7 @@ void nvmet_execute_auth_send(struct nvmet_req *req)
 			/* Restart negotiation */
 			pr_debug("%s: ctrl %d qid %d reset negotiation\n",
 				 __func__, ctrl->cntlid, req->sq->qid);
+			nvmet_auth_sq_free(req->sq);
 			if (!req->sq->qid) {
 				dhchap_status = nvmet_setup_auth(ctrl);
 				if (dhchap_status) {
Signature · 1 line
2.53.0
author maintainer
#1519 lore raw

PATCH 1515/1536 kgdb: Fix buffer overflow in the m packet handler

In reply to Greg Kroah-Hartman

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

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

From: Fang Xieyan <[email protected]>

[ Upstream commit ac0159129e2cb99a70c4b80cfbf58d03e092dc7b ]

gdb_cmd_memread() passes the length of the 'm' packet straight to kgdb_mem2hex(), which hex-encodes the reply into remcom_out_buffer[BUFMAX] without checking that the reply fits. A client on the KGDB I/O console can ask for a read of any size, and the hex encoding runs off the end of the buffer. kgdb_mem2hex() takes that length as an int count, so 2^31 truncates to a negative value and copy_from_kernel_nofault() is handed buf + count as its destination.

On x86 BUFMAX is 1024, so a read of 512 bytes overruns by the single byte that terminates the hex string:

  BUG: KASAN: global-out-of-bounds in kgdb_mem2hex+0x1dd/0x230
  Write of size 1 at addr ffffffff87651780 by task sh/1
  ...
  The buggy address belongs to the variable:
   remcom_out_buffer+0x400/0x420

Bounds check the length before the hex encoding:

		if (length > (BUFMAX - 1) / 2) {
			error_packet(remcom_out_buffer, -EINVAL);
			return;
		}

gdbstub_msg_write() already bounds the count it hex-encodes against BUFMAX. Reads over the limit never returned valid data, so an error reply loses nothing.

Fixes dc7d55270521 ("kgdb: core")
Assisted-by Hawkeye:GLM-5.3-flash
Assisted-by Qoder:Qwen3.8-Max
---
 kernel/debug/gdbstub.c | 8 ++++++++
 1 file changed, 8 insertions(+)
kernel/debug/gdbstub.c +8 -0
index f625172d4b676..4a17b27b3e5b2 100644
@@ -561,6 +561,14 @@ static void gdb_cmd_memread(struct kgdb_state *ks)
 
 	if (kgdb_hex2long(&ptr, &addr) > 0 && *ptr++ == ',' &&
 					kgdb_hex2long(&ptr, &length) > 0) {
+		/*
+		 * The hex-encoded reply needs 2 * length + 1 bytes
+		 * in remcom_out_buffer[BUFMAX].
+		 */
+		if (length > (BUFMAX - 1) / 2) {
+			error_packet(remcom_out_buffer, -EINVAL);
+			return;
+		}
 		err = kgdb_mem2hex((char *)addr, remcom_out_buffer, length);
 		if (!err)
 			error_packet(remcom_out_buffer, -EINVAL);
Signature · 1 line
2.53.0
author maintainer
#1520 lore raw

PATCH 1516/1536 kgdb: Fix buffer overflow in the M and X packet handlers

In reply to Greg Kroah-Hartman

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

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

From: Fang Xieyan <[email protected]>

[ Upstream commit 13962ef7021ef2531a4f6650eca87c363e6c9c32 ]

write_mem_msg() passes the length claimed by an 'M' or 'X' packet directly to kgdb_hex2mem() or kgdb_ebin2mem(). A malformed packet can claim more data than was actually received, causing the decoders to read past remcom_in_buffer.

Record the received payload length in get_packet() and use it to bound the decoders. 'M' carries two hex characters per byte, while 'X' carries one byte per output byte except that a 0x7d escape consumes an additional input byte. Pass the packet end to kgdb_ebin2mem() so both reads are checked against the received data.

Keep zero-length 'X' packets valid, as GDB uses them to probe binary download support.

Fixes dc7d55270521 ("kgdb: core")
Assisted-by Hawkeye:GLM-5.3-flash
Assisted-by Qoder:Qwen3.8-Max
---
 kernel/debug/gdbstub.c | 45 +++++++++++++++++++++++++++++++++++-------
 1 file changed, 38 insertions(+), 7 deletions(-)
kernel/debug/gdbstub.c +38 -7
index 4a17b27b3e5b2..cc3159b0b6ab6 100644
@@ -41,6 +41,8 @@
 /* Our I/O buffers. */
 static char			remcom_in_buffer[BUFMAX];
 static char			remcom_out_buffer[BUFMAX];
+/* Payload bytes get_packet() stored in remcom_in_buffer, excluding the NUL. */
+static int			remcom_in_len;
 static int			gdbstub_use_prev_in_buf;
 static int			gdbstub_prev_in_buf_pos;
 
@@ -85,7 +87,7 @@ static int gdbstub_read_wait(void)
 }
 #endif
 /* scan for the sequence $<data>#<checksum> */
-static void get_packet(char *buffer)
+static int get_packet(char *buffer)
 {
 	unsigned char checksum;
 	unsigned char xmitcsum;
@@ -133,6 +135,8 @@ static void get_packet(char *buffer)
 		}
 		buffer[count] = 0;
 	} while (checksum != xmitcsum);
+
+	return count;
 }
 
 /*
@@ -319,16 +323,26 @@ int kgdb_hex2long(char **ptr, unsigned long *long_val)
  * Copy the binary array pointed to by buf into mem.  Fix $, #, and
  * 0x7d escaped with 0x7d. Return -EFAULT on failure or 0 on success.
  * The input buf is overwritten with the result to write to mem.
+ *
+ * buf_end points one past the last byte received for this packet. Each
+ * 0x7d escape consumes a second input byte, so decoding count bytes can
+ * read up to 2 * count input bytes; stop at buf_end rather than running
+ * off the end of remcom_in_buffer.
  */
-static int kgdb_ebin2mem(char *buf, char *mem, int count)
+static int kgdb_ebin2mem(char *buf, char *mem, int count, char *buf_end)
 {
 	int size = 0;
 	char *c = buf;
 
 	while (count-- > 0) {
+		if (buf >= buf_end)
+			return -EINVAL;
 		c[size] = *buf++;
-		if (c[size] == 0x7d)
+		if (c[size] == 0x7d) {
+			if (buf >= buf_end)
+				return -EINVAL;
 			c[size] = *buf++ ^ 0x20;
+		}
 		size++;
 	}
 
@@ -365,16 +379,33 @@ void gdb_regs_to_pt_regs(unsigned long *gdb_regs, struct pt_regs *regs)
 static int write_mem_msg(int binary)
 {
 	char *ptr = &remcom_in_buffer[1];
+	char *buf_end = &remcom_in_buffer[remcom_in_len];
 	unsigned long addr;
 	unsigned long length;
 	int err;
 
 	if (kgdb_hex2long(&ptr, &addr) > 0 && *(ptr++) == ',' &&
 	    kgdb_hex2long(&ptr, &length) > 0 && *(ptr++) == ':') {
-		if (binary)
-			err = kgdb_ebin2mem(ptr, (char *)addr, length);
-		else
+		/*
+		 * Trust only the bytes actually received, not length: the
+		 * client can claim more payload than it sent. 'M' decodes two
+		 * hex chars per byte in place, so it needs 2 * length bytes at
+		 * ptr; 'X' decodes one byte per byte, and kgdb_ebin2mem() bounds
+		 * its extra 0x7d-escape reads against buf_end itself.
+		 */
+		if (ptr >= buf_end)
+			return -EINVAL;
+
+		if (binary) {
+			if (length > (unsigned long)(buf_end - ptr))
+				return -EINVAL;
+			err = kgdb_ebin2mem(ptr, (char *)addr, length, buf_end);
+		} else {
+			if (length > (unsigned long)(buf_end - ptr) / 2)
+				return -EINVAL;
 			err = kgdb_hex2mem(ptr, (char *)addr, length);
+		}
+
 		if (err)
 			return err;
 		if (CACHE_FLUSH_IS_SAFE)
@@ -991,7 +1022,7 @@ int gdb_serial_stub(struct kgdb_state *ks)
 		/* Clear the out buffer. */
 		memset(remcom_out_buffer, 0, sizeof(remcom_out_buffer));
 
-		get_packet(remcom_in_buffer);
+		remcom_in_len = get_packet(remcom_in_buffer);
 
 		switch (remcom_in_buffer[0]) {
 		case '?': /* gdbserial status */
Signature · 1 line
2.53.0
author maintainer
#1521 lore raw

PATCH 1517/1536 kgdb: Fix buffer overflow in the qRcmd packet handler

In reply to Greg Kroah-Hartman

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

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

From: Fang Xieyan <[email protected]>

[ Upstream commit 9ca9e8c857b55a081d5a1f8039b27cbb4d646b49 ]

gdb_cmd_query() decodes the hex payload of a qRcmd packet (the GDB "monitor" command passthrough to kdb) into remcom_out_buffer and hands it to kdb_parse(). It sizes the decode with strlen() of the payload:

	int len = strlen(remcom_in_buffer + 6);
	...
	kgdb_hex2mem(remcom_in_buffer + 6,
		     remcom_out_buffer, len);
	len = len / 2;

kgdb_hex2mem() takes count as the number of bytes to produce and decodes them in place at buf, reading and writing 2 * count bytes there. len here is the hex character count, twice the decoded size, so the decode runs over 2 * len bytes at remcom_in_buffer + 6, off the end of the buffer. On x86 BUFMAX is 1024, so a 256-byte monitor command (512 hex characters) overruns remcom_in_buffer during the in-place decode:

  BUG: KASAN: global-out-of-bounds in kgdb_hex2mem+0x131/0x160
  Read of size 1 at addr ffffffff8765ef05 by task sh/1
  ...
  kgdb_hex2mem+0x131/0x160
  gdb_serial_stub+0x16d4/0x3170
  kgdb_cpu_enter+0xb68/0x1520
  ...
  The buggy address belongs to the variable:
   remcom_in_buffer+0x405/0x420

Halve len before the call so kgdb_hex2mem() gets the decoded byte count. It then reads the len hex characters already in remcom_in_buffer and writes len / 2 bytes, all inside the buffer, and remcom_out_buffer holds the same command as before.

---
 kernel/debug/gdbstub.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/debug/gdbstub.c +1 -1
index cc3159b0b6ab6..2833c77692096 100644
@@ -815,9 +815,9 @@ static void gdb_cmd_query(struct kgdb_state *ks)
 				strcpy(remcom_out_buffer, "E01");
 				break;
 			}
+			len = len / 2;
 			kgdb_hex2mem(remcom_in_buffer + 6,
 				     remcom_out_buffer, len);
-			len = len / 2;
 			remcom_out_buffer[len++] = 0;
 
 			kdb_common_init_state(ks);
Signature · 1 line
2.53.0
author maintainer
#1522 lore raw

PATCH 1518/1536 fsverity: Be more careful with return value of ->get_verity_descriptor()

In reply to Greg Kroah-Hartman

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

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

From: Eric Biggers <[email protected]>

[ Upstream commit 8f8faec82aa902b1997ae578c46bcc84afbad811 ]

If fsverity_operations::get_verity_descriptor() returns that the verity descriptor has 0 size, then a zero-size buffer is allocated to hold it, and it's called again with bufsize=0.

But bufsize=0 is a special case that says to return the actual size. If in the meantime the filesystem has decided that the size is some actually valid size, it will return that size, and then validate_fsverity_descriptor() will read from ZERO_SIZE_PTR and crash.

Of course, for the filesystem to misbehave in that strange way, it generally would require direct writes to the block device.

Regardless, fsverity_get_descriptor() might as well guard against it. Make it do so. Specifically, validate that the first call to ->get_verity_descriptor() returns at least the minimum descriptor size, and validate that the second call returns the same size as the first.

Fixes fd2d1acfcadf ("fs-verity: add the hook for file ->open()")
---
 fs/verity/open.c | 38 +++++++++++++++++++-------------------
 1 file changed, 19 insertions(+), 19 deletions(-)
fs/verity/open.c +19 -19
index bd0497da5cea3..9c1b37a3b96a8 100644
@@ -280,12 +280,6 @@ static bool validate_fsverity_descriptor(struct inode *inode,
 					 const struct fsverity_descriptor *desc,
 					 size_t desc_size)
 {
-	if (desc_size < sizeof(*desc)) {
-		fsverity_err(inode, "Unrecognized descriptor size: %zu bytes",
-			     desc_size);
-		return false;
-	}
-
 	if (desc->version != 1) {
 		fsverity_err(inode, "Unrecognized descriptor version: %u",
 			     desc->version);
@@ -324,31 +318,37 @@ static bool validate_fsverity_descriptor(struct inode *inode,
 int fsverity_get_descriptor(struct inode *inode,
 			    struct fsverity_descriptor **desc_ret)
 {
-	int res;
+	int size, res;
 	struct fsverity_descriptor *desc;
 
-	res = inode->i_sb->s_vop->get_verity_descriptor(inode, NULL, 0);
-	if (res < 0) {
-		fsverity_err(inode,
-			     "Error %d getting verity descriptor size", res);
-		return res;
+	size = inode->i_sb->s_vop->get_verity_descriptor(inode, NULL, 0);
+	if (size < 0) {
+		fsverity_err(inode, "Error %d getting verity descriptor size",
+			     size);
+		return size;
 	}
-	if (res > FS_VERITY_MAX_DESCRIPTOR_SIZE) {
-		fsverity_err(inode, "Verity descriptor is too large (%d bytes)",
-			     res);
+	if (size < sizeof(*desc) || size > FS_VERITY_MAX_DESCRIPTOR_SIZE) {
+		fsverity_err(inode,
+			     "Verity descriptor has invalid size (%d bytes)",
+			     size);
 		return -EMSGSIZE;
 	}
-	desc = kmalloc(res, GFP_KERNEL);
+	desc = kmalloc(size, GFP_KERNEL);
 	if (!desc)
 		return -ENOMEM;
-	res = inode->i_sb->s_vop->get_verity_descriptor(inode, desc, res);
+	res = inode->i_sb->s_vop->get_verity_descriptor(inode, desc, size);
 	if (res < 0) {
 		fsverity_err(inode, "Error %d reading verity descriptor", res);
 		kfree(desc);
 		return res;
 	}
-
-	if (!validate_fsverity_descriptor(inode, desc, res)) {
+	if (res != size) {
+		fsverity_err(inode, "Verity descriptor size changed (%d => %d)",
+			     size, res);
+		kfree(desc);
+		return -EINVAL;
+	}
+	if (!validate_fsverity_descriptor(inode, desc, size)) {
 		kfree(desc);
 		return -EINVAL;
 	}
Signature · 1 line
2.53.0
author maintainer
#1523 lore raw

PATCH 1519/1536 irqchip/riscv-imsic: Report successful hardware retrigger

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit a2f482407d33ebe7f12e30d6cf383ffb1c7d709d ]

imsic_irq_retrigger() writes to the IMSIC MSI register to retrigger an interrupt, but returns 0. The IRQ core treats zero as failure and may schedule a software resend despite the hardware retrigger.

Return 1 after the MSI write to report successful hardware retriggering and prevent the unnecessary software resend.

Fixes 027e125acdba ("irqchip/riscv-imsic: Add device MSI domain support for platform devices")
---
 drivers/irqchip/irq-riscv-imsic-platform.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/irqchip/irq-riscv-imsic-platform.c +1 -1
index 5d7c30ad8855b..d0c303882ed1b 100644
@@ -60,7 +60,7 @@ static int imsic_irq_retrigger(struct irq_data *d)
 
 	local = per_cpu_ptr(imsic->global.local, vec->cpu);
 	writel_relaxed(vec->local_id, local->msi_va);
-	return 0;
+	return 1;
 }
 
 static void imsic_irq_compose_vector_msg(struct imsic_vector *vec, struct msi_msg *msg)
Signature · 1 line
2.53.0
author maintainer
#1524 lore raw

PATCH 1520/1536 irqchip/irq-msi-lib: Free wired MSI descriptors

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 1c16bc2b1122f78f9d51c5785f7a78b36d44972b ]

msi_device_domain_alloc_wired() allocates a descriptor for each interrupt, but wired MSI domains do not set MSI_FLAG_FREE_MSI_DESCS. msi_device_domain_free_wired() releases the IRQ without freeing its descriptor, eventually exhausting the domain. Failed allocations also leave descriptors behind.

Set MSI_FLAG_FREE_MSI_DESCS for wired MSI domains so both paths release the descriptors.

Fixes 64a855324311 ("irqchip/irq-msi-lib: Prepare for DOMAIN_BUS_WIRED_TO_MSI")
---
 drivers/irqchip/irq-msi-lib.c | 1 +
 1 file changed, 1 insertion(+)
drivers/irqchip/irq-msi-lib.c +1 -0
index d8e29fc0d4068..34707593df49a 100644
@@ -71,6 +71,7 @@ bool msi_lib_init_dev_msi_info(struct device *dev, struct irq_domain *domain,
 		info->flags = MSI_FLAG_ALLOC_SIMPLE_MSI_DESCS | MSI_FLAG_FREE_MSI_DESCS;
 		fallthrough;
 	case DOMAIN_BUS_WIRED_TO_MSI:
+		info->flags |= MSI_FLAG_FREE_MSI_DESCS;
 		/* Remove PCI specific flags */
 		required_flags &= ~MSI_FLAG_PCI_MSI_MASK_PARENT;
 		break;
Signature · 1 line
2.53.0
author maintainer
#1525 lore raw

PATCH 1521/1536 mount: refuse setns() with a shared fs_struct again

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 948e604aca8af30490accf7d46d44814ffa26f80 ]

mntns_install() refuses to switch the mount namespace of a task that shares its fs_struct, since root and cwd of the others would move to a namespace they are not in. It looks at nsset->fs for that. If more than the mount namespace is asked for, that is a private copy made by prepare_nsset(), which has one user by definition; commit_nsset() then writes root and cwd of the copy to the fs_struct of the task.

A thread of a process with two threads, pidfd of a task in another mount namespace:

setns(pidfd, CLONE_NEWNS) -EINVAL
setns(pidfd, CLONE_NEWNS | CLONE_NEWUTS) 0

and after the second call the other thread, still in the old mount namespace, has lost its cwd (/tmp became /) and sees the mounts of the other namespace under /.

Look at the fs_struct that is going to be changed. The second call then fails with -EINVAL like the first one.

Fixes 303cc571d107 ("nsproxy: attach to namespaces via pidfds")
---
 fs/namespace.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/namespace.c +1 -1
index fa611381c3a35..d188ad61f40ae 100644
@@ -5942,7 +5942,7 @@ static int mntns_install(struct nsset *nsset, struct ns_common *ns)
 	if (is_anon_ns(mnt_ns))
 		return -EINVAL;
 
-	if (fs->users != 1)
+	if (current->fs->users != 1)
 		return -EINVAL;
 
 	get_mnt_ns(mnt_ns);
Signature · 1 line
2.53.0
author maintainer
#1526 lore raw

PATCH 1522/1536 blk-iocost: abort weight transfer on invalid donation weights

In reply to Greg Kroah-Hartman

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

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

From: Kunhai Dai <[email protected]>

[ Upstream commit c810ee88cdab27f443c32270dc7c0eaad2cca3f8 ]

transfer_surpluses() warns and then keeps going when the donation calculation produced invalid weights. The following propagation can then divide by a zero hweight_inuse, so the warning is immediately followed by a divide error.

When the check trips, abandon this period's donation transfer and release the walk lists. This trades one period without donation for not crashing; the invalid state is not expected on the normal path.

Developed with assistance from Claude Code (Anthropic): the assistant analysed the failure path, drafted the change and ran the checks listed below. The author reviewed the result and remains responsible for it.

Fixes e08d02aa5fc9 ("blk-iocost: implement Andy's method for donation weight updates")
---
 block/blk-iocost.c | 2 ++
 1 file changed, 2 insertions(+)
block/blk-iocost.c +2 -0
index 8b775dd95ba57..4707b93493055 100644
@@ -1965,6 +1965,7 @@ static void transfer_surpluses(struct list_head *surpluses, struct ioc_now *now)
 			pr_cont(": active=%u donating=%u after=%u\n",
 				iocg->hweight_active, iocg->hweight_donating,
 				iocg->hweight_after_donation);
+			goto out;
 		}
 	}
 
@@ -2063,6 +2064,7 @@ static void transfer_surpluses(struct list_head *surpluses, struct ioc_now *now)
 		__propagate_weights(iocg, iocg->active, inuse, true, now);
 	}
 
+out:
 	/* walk list should be dissolved after use */
 	list_for_each_entry_safe(iocg, tiocg, &inner_walk, walk_list)
 		list_del_init(&iocg->walk_list);
Signature · 1 line
2.53.0
author maintainer
#1527 lore raw

PATCH 1523/1536 tcp: check congestion control restriction first

In reply to Greg Kroah-Hartman

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

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

From: Zhiling Zou <[email protected]>

[ Upstream commit dda51b73721684637ab8e9bd97c78228b99c4bd2 ]

tcp_set_default_congestion_control() takes a reference to an algorithm before checking whether a non-init network namespace may select it. A rejected request returns -EPERM without dropping the reference.

This affects module-backed algorithms too; BPF is not required. For example, after root loads tcp_bbr, a user with CAP_NET_ADMIN in a non-init network namespace can repeatedly request it as the default although it is not in tcp_allowed_congestion_control. Each rejected write leaks a module reference. Since module->refcnt is an atomic_t, 2^31 such writes can make it negative; later module_put() calls warn, and rmmod can hit the BUG_ON() in try_release_module_ref().

Check the namespace restriction before acquiring the reference, as tcp_set_congestion_control() already does.

---
 net/ipv4/tcp_cong.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
net/ipv4/tcp_cong.c +2 -2
index f3c516da0a942..cfef6dbac6421 100644
@@ -286,12 +286,12 @@ int tcp_set_default_congestion_control(struct net *net, const char *name)
 	ca = tcp_ca_find_autoload(name);
 	if (!ca) {
 		ret = -ENOENT;
-	} else if (!bpf_try_module_get(ca, ca->owner)) {
-		ret = -EBUSY;
 	} else if (!net_eq(net, &init_net) &&
 			!(ca->flags & TCP_CONG_NON_RESTRICTED)) {
 		/* Only init netns can set default to a restricted algorithm */
 		ret = -EPERM;
+	} else if (!bpf_try_module_get(ca, ca->owner)) {
+		ret = -EBUSY;
 	} else {
 		prev = xchg(&net->ipv4.tcp_congestion_control, ca);
 		if (prev)
Signature · 1 line
2.53.0
author maintainer
#1528 lore raw

PATCH 1524/1536 apparmor: fix refcount leak in aa_get_newest_profile()

In reply to Greg Kroah-Hartman

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

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

From: John Johansen <[email protected]>

[ Upstream commit 33ed50716251d5b2875706c40d0c8082d46be0b1 ]

The labels_profile() macro is evaluating its argument twice

  #define labels_profile(X) ((X)->vec[(X)->size - 1])

unfortunately aa_get_newest_profile() passes
aa_get_newest_label(&p->label)
so every call to aa_get_newest_profile results in 2 refcounts being taken with one being leaked.

There is no need for labels_profile() to be a macro. Convert it to an inline fn, which ensures all uses are passing the correct struct and removes the double evaluation.

Fixes 637f688dc3dc ("apparmor: switch from profiles to using labels on contexts")
---
 security/apparmor/include/label.h | 6 +++++-
 security/apparmor/label.c         | 1 -
 2 files changed, 5 insertions(+), 2 deletions(-)
security/apparmor/include/label.h +5 -1
index 4ca505d4c3a10..a687be022ad17 100644
@@ -147,7 +147,11 @@ do {							\
 #define labels_ns(X) (vec_ns(&((X)->vec[0]), (X)->size))
 #define labels_set(X) (&labels_ns(X)->labels)
 #define labels_view(X) labels_ns(X)
-#define labels_profile(X) ((X)->vec[(X)->size - 1])
+
+static inline struct aa_profile *labels_profile(const struct aa_label *label)
+{
+	return label->vec[label->size - 1];
+}
 
 
 int aa_label_next_confined(struct aa_label *l, int i);
security/apparmor/label.c +0 -1
index 04fe4d16952d1..6508f13e9544f 100644
@@ -382,7 +382,6 @@ void aa_label_kref(struct kref *kref)
 		label_free_switch(label);
 		return;
 	}
-	/* TODO: update labels_profile macro so it works here */
 	AA_BUG(label_isprofile(label) &&
 	       on_list_rcu(&label->vec[0]->base.profiles));
 	AA_BUG(label_isprofile(label) &&
Signature · 1 line
2.53.0
author maintainer
#1529 lore raw

PATCH 1525/1536 net/packet: check TX_RING fragments before memory accounting

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

tpacket_fill_skb() adds the full non-linear payload length to skb->truesize and sk_wmem_alloc before checking MAX_SKB_FRAGS. With PACKET_VNET_HDR, userspace can submit a ring-sized frame even when it greatly exceeds the device MTU.

A near-INT_MAX frame can saturate sk_wmem_alloc before the fragment loop rejects it. A subsequent refcount_add(0x40000001) can temporarily turn REFCOUNT_SATURATED into 1. A concurrent TX completion can then drop that apparent last reference and free the still-live packet socket before refcount_warn_saturate() restores the counter.

Check that the remaining payload fits in MAX_SKB_FRAGS pages before accounting it. Include the initial page offset in the calculation, and move the existing -EFAULT handling out of the fragment loop. This preserves the accepted packet sizes and error code while preventing an invalid frame from injecting an oversized byte charge.

Fixes 69e3c75f4d54 ("net: TX_RING and packet mmap")
Cc Willem de Bruijn <[email protected]>
[edumazet: use net_warn_ratelimited() instead of pr_err(), add a Fixes: tag]
---
 net/packet/af_packet.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
net/packet/af_packet.c +6 -6
index 048dc025b911b..1f5353b5d7500 100644
@@ -2699,6 +2699,12 @@ static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
 	}
 
 	offset = offset_in_page(data);
+	if (unlikely(to_write > MAX_SKB_FRAGS * PAGE_SIZE - offset)) {
+		net_warn_ratelimited("Packet exceed the number of skb frags(%u)\n",
+				     (unsigned int)MAX_SKB_FRAGS);
+		return -EFAULT;
+	}
+
 	len_max = PAGE_SIZE - offset;
 	len = ((to_write > len_max) ? len_max : to_write);
 
@@ -2710,12 +2716,6 @@ static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
 	while (likely(to_write)) {
 		nr_frags = skb_shinfo(skb)->nr_frags;
 
-		if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
-			pr_err("Packet exceed the number of skb frags(%u)\n",
-			       (unsigned int)MAX_SKB_FRAGS);
-			return -EFAULT;
-		}
-
 		page = pgv_to_page(data);
 		data += len;
 		flush_dcache_page(page);
Signature · 1 line
2.53.0
author maintainer
#1530 lore raw

PATCH 1526/1536 tcp: fix reordering addition overflow in MTU probing

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

Commit efb8763d7bbb ("net: ipv4: bound TCP reordering sysctl writes and MTU probe sizes") widened size_needed and the MSS multiplication, but tp->reordering + 1 is still evaluated as u32. RTAX_REORDERING accepts an unrestricted u32, and tcp_init_metrics() can install U32_MAX.

In that case the extra-data requirement becomes zero. A write queue with probe_size - 1 data bytes and a FIN satisfies the sequence-space check. The coalescing walk can pass the queue head to tcp_skb_can_collapse(), and tcp_clone_payload() can produce an skb whose advertised payload exceeds the data in its fragments. Local delivery followed by TCP_ZEROCOPY_RECEIVE can then walk beyond the fragment array. KASAN reports a slab-out-of-bounds read in can_map_frag().

Cast reordering before incrementing it so the arithmetic handles the entire u32 metric range. For U32_MAX, the required size exceeds the 32-bit queue and window limits, so the existing checks skip the probe. The calculation is unchanged for all other reordering values.

---
 net/ipv4/tcp_output.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/ipv4/tcp_output.c +1 -1
index 6f4da22ccbdf1..eadf5956a79df 100644
@@ -2476,7 +2476,7 @@ static int tcp_mtu_probe(struct sock *sk)
 	mss_now = tcp_current_mss(sk);
 	probe_size = tcp_mtu_to_mss(sk, (icsk->icsk_mtup.search_high +
 				    icsk->icsk_mtup.search_low) >> 1);
-	size_needed = probe_size + (tp->reordering + 1) * (u64)tp->mss_cache;
+	size_needed = probe_size + ((u64)tp->reordering + 1) * tp->mss_cache;
 	interval = icsk->icsk_mtup.search_high - icsk->icsk_mtup.search_low;
 	/* When misfortune happens, we are reprobing actively,
 	 * and then reprobe timer has expired. We stick with current
Signature · 1 line
2.53.0
author maintainer
#1531 lore raw

PATCH 1527/1536 apparmor: remove fs entries created by a failed policy load

In reply to Greg Kroah-Hartman

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

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

From: Georgia Garcia <[email protected]>

[ Upstream commit 6ec46f8f1977d218bf2494ce276152b2d01424af ]

aa_replace_profiles() creates the raw_data/<rev> directory for the loaddata and the profile directories for new profiles before the last checks that can fail. When one of those checks fails, the fail path releases the ns lock without removing what this load created.

The raw_data directory is named after the current ns revision, and the revision is only bumped by a successful load. The stale directory is only removed once the loaddata's last profile reference is dropped, from a workqueue. Until then, every load fails to create raw_data/<rev> with -EEXIST. If the new profiles are never freed, which is the case when their dents are left behind pinning the proxy, that never happens and no policy can be loaded until reboot.

While still holding the ns lock in the fail path, remove the profile directories of the new profiles and, if this load created it, the raw_data directory.

Fixes 5d5182cae401 ("apparmor: move to per loaddata files, instead of replicating in profiles")
---
 security/apparmor/policy.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
security/apparmor/policy.c +14 -0
index b3a602c9c23d7..efa11a1a297d4 100644
@@ -1132,6 +1132,7 @@ ssize_t aa_replace_profiles(struct aa_ns *policy_ns, struct aa_label *label,
 	struct aa_loaddata *rawdata_ent;
 	const char *op;
 	ssize_t count, error;
+	bool rawdata_created = false;
 	LIST_HEAD(lh);
 
 	op = mask & AA_MAY_REPLACE_POLICY ? OP_PROF_REPL : OP_PROF_LOAD;
@@ -1271,6 +1272,7 @@ ssize_t aa_replace_profiles(struct aa_ns *policy_ns, struct aa_label *label,
 			ent = NULL;
 			goto fail_lock;
 		}
+		rawdata_created = true;
 	}
 	list_for_each_entry(ent, &lh, list) {
 		if (!ent->old) {
@@ -1366,6 +1368,18 @@ ssize_t aa_replace_profiles(struct aa_ns *policy_ns, struct aa_label *label,
 	return udata_sz;
 
 fail_lock:
+	/*
+	 * Remove fs entries created by this load. Nothing else references
+	 * them yet, and leaving them behind would leak the new profiles
+	 * (their dents pin the proxy) and make the next load at the same,
+	 * unbumped ns revision fail with -EEXIST on its raw_data dir.
+	 */
+	list_for_each_entry(tmp, &lh, list) {
+		if (!tmp->old)
+			__aafs_profile_rmdir(tmp->new);
+	}
+	if (rawdata_created)
+		__aa_fs_remove_rawdata(udata);
 	mutex_unlock(&ns->lock);
 
 	/* audit cause of failure */
Signature · 1 line
2.53.0
author maintainer
#1532 lore raw

PATCH 1528/1536 aio: fix NULL deref when a fault races ring truncation

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit d53b5aa5cfae27e4d236fc0ab9581085d27f7d33 ]

The aio ring lives in a file on the aio pseudo filesystem and the ring VMA uses filemap_fault(). aio_ctx_aops doesn't have a ->read_folio because aio_setup_ring() puts all folios of the ring into the page cache. So a fault on the ring only works as long as it finds its folio in the page cache. If it doesn't, filemap_fault() calls ->read_folio without checking and we jump to NULL.

We already fixed this twice this year. A forked child could inherit the ring mapping, fixed by commit c03ce4173c7b ("fs: aio: set VMA_DONTCOPY_BIT in mmap to fix NULL-pointer-dereference error"). And a partial mremap() could leave part of the ring mapped, fixed by commit 3adf7ae18bf4 ("fs: aio: reject partial mremap to avoid Null-pointer-dereference error"). Both times a VMA outlived the ring and the ring file was truncated under it.

There's a third way to get there. kill_ioctx() and the error path of ioctx_alloc() unmap the ring with vm_munmap() and ignore the return value. If vm_munmap() has to wait for mmap_lock and a fatal signal is pending it returns -EINTR and the VMA stays. free_ioctx() then calls put_aio_ring_file() which truncates the ring file to zero. A fault that passed the i_size check in filemap_fault() before that doesn't find its folio anymore, allocates a new one and calls ->read_folio:

fault on the ring io_destroy() with SIGKILL pending
================= =================================
vm_munmap() returns -EINTR
filemap_fault()
i_size check passes
free_ioctx()
put_aio_ring_file()
truncate_setsize(inode, 0)
no folio, allocate a new one
filemap_read_folio()
->read_folio == NULL

All that's needed is a second process that shares the mm. If a CLONE_VM child calls io_destroy() and gets SIGKILLed while it waits for mmap_lock the ring stays mapped for the threads of the parent. Any user can do that.

Instead of plugging the routes one by one give the ring a ->read_folio that unlocks the folio and returns -EIO. All folios of a live ring are in the page cache so a fault can only end up there if the ring was truncated. The fault now gets SIGBUS. Nothing else reads the ring file and the aio filesystem uses noop_backing_dev_info so there's no readahead either.

Making vm_munmap() unkillable in those two places would only close this one route and bring back what commit ae7987835643 ("mm: make vm_munmap killable") fixed.

---
 fs/aio.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
fs/aio.c +11 -0
index 59620eb01df49..44447e4af6286 100644
@@ -474,7 +474,18 @@ static int aio_migrate_folio(struct address_space *mapping, struct folio *dst,
 #define aio_migrate_folio NULL
 #endif
 
+/*
+ * filemap_fault() reads a folio that it did not find in the page cache. All
+ * folios of a live ring are there, so the ring was truncated under the fault.
+ */
+static int aio_read_folio(struct file *file, struct folio *folio)
+{
+	folio_unlock(folio);
+	return -EIO;
+}
+
 static const struct address_space_operations aio_ctx_aops = {
+	.read_folio	= aio_read_folio,
 	.dirty_folio	= noop_dirty_folio,
 	.migrate_folio	= aio_migrate_folio,
 };
Signature · 1 line
2.53.0
author maintainer
#1533 lore raw

PATCH 1529/1536 splice: avoid stale f_pos writeback on error

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 79b496ebe382866e3a05090b7dc9ae95e85e65b2 ]

do_splice() snapshots an implicit file position before calling the splice helper. Since splice does not take f_pos_lock, another operation on the same open file description can update f_pos while the helper is blocked. If the helper then fails, the unconditional writeback restores the stale snapshot.

For a directory without ->splice_read, a file-to-pipe splice fails with -EINVAL. A concurrent directory mutation and getdents() call can advance f_pos and refresh the filesystem's revalidation cookie before that failure restores only the old position. The next ext2 readdir can then trust an offset inside a directory entry and copy data from the adjacent page to userspace.

Only update an implicit file position when splice returns a non-negative result, matching read and write. Keep explicit offset updates unchanged.

Fixes 7995bd287134 ("splice: don't pass the address of ->f_pos to methods")
---
 fs/splice.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
fs/splice.c +6 -6
index ed8177f6d620f..a8f4ec2b7de10 100644
@@ -1357,10 +1357,10 @@ ssize_t do_splice(struct file *in, loff_t *off_in, struct file *out,
 		ret = do_splice_from(ipipe, out, &offset, len, flags);
 		file_end_write(out);
 
-		if (!off_out)
-			out->f_pos = offset;
-		else
+		if (off_out)
 			*off_out = offset;
+		else if (ret >= 0)
+			out->f_pos = offset;
 	} else if (opipe) {
 		if (off_out)
 			return -ESPIPE;
@@ -1381,10 +1381,10 @@ ssize_t do_splice(struct file *in, loff_t *off_in, struct file *out,
 
 		ret = splice_file_to_pipe(in, opipe, &offset, len, flags);
 
-		if (!off_in)
-			in->f_pos = offset;
-		else
+		if (off_in)
 			*off_in = offset;
+		else if (ret >= 0)
+			in->f_pos = offset;
 	} else {
 		ret = -EINVAL;
 	}
Signature · 1 line
2.53.0
author maintainer
#1534 lore raw

PATCH 1530/1536 fs: skip copy_file_range write limits when there is no data

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit 81dfa035891f0502674332ee97db348a16486de0 ]

generic_copy_file_checks() reduces count to zero for a source offset at or beyond EOF, but still checks the destination write limits. If pos_out is at RLIMIT_FSIZE, this sends SIGXFSZ and returns -EFBIG even though there is no data to write.

For example, GNU cat copying a 1024-byte regular file to another regular file with RLIMIT_FSIZE=1024 copies all bytes and is then killed by its next copy_file_range() call at EOF. A zero-length request can fail in the same way.

Check write limits only when count is nonzero, as the ordinary write checks already do. Keep the other copy validation in place.

---
 fs/read_write.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
fs/read_write.c +5 -3
index 430c06993b758..d908478b7e833 100644
@@ -1554,9 +1554,11 @@ static int generic_copy_file_checks(struct file *file_in, loff_t pos_in,
 	else
 		count = min(count, size_in - (uint64_t)pos_in);
 
-	ret = generic_write_check_limits(file_out, pos_out, &count);
-	if (ret)
-		return ret;
+	if (count) {
+		ret = generic_write_check_limits(file_out, pos_out, &count);
+		if (ret)
+			return ret;
+	}
 
 	/* Don't allow overlapped copying within the same file. */
 	if (inode_in == inode_out &&
Signature · 1 line
2.53.0
author maintainer
#1535 lore raw

PATCH 1531/1536 fs: dont fail __d_obtain_alias() for unlinked inodes

In reply to Greg Kroah-Hartman

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

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

From: Amir Goldstein <[email protected]>

[ Upstream commit a522dd871024a0f065bfa7638afdb929607f58fc ]

Commit 669bb5af15d4 ("fs: make sure to call fsnotify_inoderemove() only once when inode is dead") did two things. It made dentry_unlink_inode() call fsnotify_inoderemove() only once the inode has neither links nor aliases left. And it made __d_obtain_alias() fail with -ESTALE for an inode in that state so that open_by_handle_at() can't create a new alias after FS_DELETE_SELF has been reported and the inode marks are gone.

The second part is wrong for network filesystems. __d_obtain_alias() backs d_obtain_alias() and d_obtain_root(). Those are what the ->fh_to_dentry() and ->get_parent() methods use to turn the inode they looked up into a dentry for exportfs_decode_fh_raw(), i.e., for open_by_handle_at() and for nfsd file handle decoding.

For a local filesystem an in-core inode without links and aliases is an orphan that goes away on the final iput(). For a network filesystem that's not true. i_nlink is just the link count the server last reported and whether the object is still reachable through its file handle is up to the server. If a file is unlinked while it is still open elsewhere, e.g., by another NFSv4 client or by a process on the server, the server keeps the object alive and its file handle stays valid. nfs_fh_to_dentry() fetches the attributes for such a handle, nfs_fhget() sets i_nlink to 0 from them, the new inode has no aliases yet and so __d_obtain_alias() now fails with -ESTALE. The same applies to fuse_get_dentry() which takes i_nlink from the fuse server. Filesystems that care about unlinked inodes already make that decision themselves in ->fh_to_dentry(), e.g., ceph's __fh_to_dentry() fetches the link count with CEPH_CAP_LINK_SHARED and only refuses an unlinked inode if it isn't open.

Note that on a network filesystem i_nlink drops to zero through attribute updates when another client unlinks the file. So the inode might never have gone through dentry_unlink_inode() with i_nlink == 0, i.e., fsnotify_inoderemove() might never have been called for it and there's nothing for the -ESTALE to protect.

So drop the two checks from __d_obtain_alias() again and go back to the unconditional alias lookup. While at it, update the comment above inode_notify_dead() since it no longer blocks new aliases.

Amir sent this as v3 to replace 669bb5af15d4 but that commit was already in mainline by then. So do it as a fix on top. The resulting code is identical to v3.

This means open_by_handle_at() can again create a new alias for an unlinked inode after FS_DELETE_SELF has been reported. Closing that file reports a second FS_DELETE_SELF and the file has none of the inode marks that were torn down. That's what Daehyeon's open_by_handle_at() LTP test checks so it is expected to fail again. This needs to be handled separately. A mark that is added through such a file while fsnotify_destroy_marks() is still running is rejected with -ENOENT since 36ebddca56b9 ("fsnotify: prevent mark additions during connector teardown") so it can't end up on a detached connector.

Christian Brauner <[email protected]> says:

Amir's v3 replaced 669bb5af15d4 as a whole. I turned it into an incremental fix on top of mainline and wrote a new commit message. Jan's Reviewed-by was given on v3 and the resulting code is identical.

---
 fs/dcache.c | 19 +++++--------------
 1 file changed, 5 insertions(+), 14 deletions(-)
fs/dcache.c +5 -14
index 482b8b6d0eeeb..ff9d401e18539 100644
@@ -389,10 +389,9 @@ static void dentry_free(struct dentry *dentry)
 }
 
 /*
- * If inode is unlinked and doesn't have any aliases (i.e., all fds pointing to
- * it are closed), it is pretty much dead. Except that file handle lookup could
- * still revive it which causes issues to fsnotify. So once inode reaches this
- * state we make sure to block creating any new aliases.
+ * When inode is unlinked and doesn't have any aliases (i.e., all fds pointing
+ * to it are closed) we report FS_DELETE_SELF to fsnotify and cleanup all inode
+ * marks.
  */
 static bool inode_notify_dead(struct inode *inode)
 {
@@ -1966,12 +1965,7 @@ static struct dentry *__d_obtain_alias(struct inode *inode, bool disconnected)
 
 	sb = inode->i_sb;
 
-	spin_lock(&inode->i_lock);
-	if (!inode_notify_dead(inode))
-		res = __d_find_any_alias(inode);	/* existing alias? */
-	else
-		res = ERR_PTR(-ESTALE);
-	spin_unlock(&inode->i_lock);
+	res = d_find_any_alias(inode); /* existing alias? */
 	if (res)
 		goto out;
 
@@ -1983,10 +1977,7 @@ static struct dentry *__d_obtain_alias(struct inode *inode, bool disconnected)
 
 	security_d_instantiate(new, inode);
 	spin_lock(&inode->i_lock);
-	if (!inode_notify_dead(inode))
-		res = __d_find_any_alias(inode);	/* recheck under lock */
-	else
-		res = ERR_PTR(-ESTALE);
+	res = __d_find_any_alias(inode); /* recheck under lock */
 	if (likely(!res)) { /* still no alias, attach a disconnected dentry */
 		unsigned add_flags = d_flags_for_inode(inode);
 
Signature · 1 line
2.53.0
author maintainer
#1536 lore raw

PATCH 1532/1536 init/bootconfig: pass init arguments in documented order

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 278b2abf660a3e0991eb9f16f11bd9e9514a286d ]

start_kernel() appends command-line init arguments before bootconfig init arguments, while setup_command_line() places them in the opposite order. As a result, the arguments passed to init do not match the saved command line, reversing the intended precedence of options.

Parse extra_init_args before after_dashes so command-line init arguments are passed last.

Fixes b66fbbe8d482 ("init/bootconfig: Reorder init parameter from bootconfig and cmdline")
---
 init/main.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
init/main.c +3 -3
index 34bb284f64191..bad880340de43 100644
@@ -914,12 +914,12 @@ void start_kernel(void)
 				  __stop___param - __start___param,
 				  -1, -1, NULL, &unknown_bootoption);
 	print_unknown_bootoptions();
-	if (!IS_ERR_OR_NULL(after_dashes))
-		parse_args("Setting init args", after_dashes, NULL, 0, -1, -1,
-			   NULL, set_init_arg);
 	if (extra_init_args)
 		parse_args("Setting extra init args", extra_init_args,
 			   NULL, 0, -1, -1, NULL, set_init_arg);
+	if (!IS_ERR_OR_NULL(after_dashes))
+		parse_args("Setting init args", after_dashes, NULL, 0, -1, -1,
+			   NULL, set_init_arg);
 
 	/* Architectural and non-timekeeping rng init, before allocator init */
 	random_init_early(command_line);
Signature · 1 line
2.53.0
author maintainer
#1537 lore raw

PATCH 1533/1536 wifi: brcmfmac: map msgbuf RX packet IDs bidirectional

In reply to Greg Kroah-Hartman

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

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

From: Jason Perlow <[email protected]>

[ Upstream commit 7ed5dce55fa8393972b1bf2bf5af1c818c5e7dc2 ]

Commit f0ba5fd51ff2 ("wifi: brcmfmac: Set DMA direction for msgbuf packet IDs") maps the RX packet ID buffers DMA_FROM_DEVICE. The BCM4364 firmware also reads posted RX buffers, so with VT-d translation enabled every such read faults ("PTE Read access is not set") and the firmware crashes and resets in a loop.

Map the RX pool DMA_BIDIRECTIONAL again, as before that commit. TX keeps DMA_TO_DEVICE.

---
 drivers/net/wireless/broadcom/brcm80211/brcmfmac/msgbuf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/wireless/broadcom/brcm80211/brcmfmac/msgbuf.c +1 -1
index f850e64108c41..24f083f42bb75 100644
@@ -1639,7 +1639,7 @@ int brcmf_proto_msgbuf_attach(struct brcmf_pub *drvr)
 	if (!msgbuf->tx_pktids)
 		goto fail;
 	msgbuf->rx_pktids = brcmf_msgbuf_init_pktids(NR_RX_PKTIDS,
-						     DMA_FROM_DEVICE);
+						     DMA_BIDIRECTIONAL);
 	if (!msgbuf->rx_pktids)
 		goto fail;
 
Signature · 1 line
2.53.0
author maintainer
#1538 lore raw

PATCH 1534/1536 ALSA: hda/realtek: Fix audio after Windows reboot on ASUS Q423SA

In reply to Greg Kroah-Hartman

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

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

From: Scott Gauche <[email protected]>

[ Upstream commit 8acd6469f42784f38872ad83b14c41152d986b63 ]

The ASUS Vivobook S 14 Q423SA-U5512 (DMI family S5406SA) with the ALC294 codec has working analog audio when booted directly after a full shutdown. After a warm reboot from Windows 11, audio works briefly during Linux startup, then both the internal speakers and headphones become silent. PCM playback continues without errors.

Coefficient 0x1b is 0x4e4b on a direct cold boot, but 0x4a4b after the Windows warm reboot. Restoring bit 10 changes it back to 0x4e4b and immediately enables both analog outputs. Speaker playback, headphone playback, jack switching, cold boot, and suspend/resume were tested successfully. The same 0x4a4b state and immediate recovery with 0x4e4b were independently confirmed on another S5406SA with subsystem 1043:10c4.

The same coefficient write is already used by ALC294_FIXUP_ASUS_COEF_1B for the ASUS UX431DA. That fixup cannot be reused here because it chains to ALC289_FIXUP_ASUS_GA401 and applies unrelated DAC routing and microphone pin configuration.

Add a model-specific fixup for subsystem 1043:10c4 and chain it to the existing ALC2XX_FIXUP_HEADSET_MIC fixup instead.

Fixes f2d08f3651fb ("ALSA: hda/realtek: Fix headset mic on ASUS Vivobook S14 S5406SA")
---
 sound/pci/hda/patch_realtek.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
sound/pci/hda/patch_realtek.c +13 -1
index 899394885ae81..0b370a9eb9f2d 100644
@@ -8104,6 +8104,7 @@ enum {
 	ALC294_FIXUP_ASUS_MIC,
 	ALC294_FIXUP_ASUS_HEADSET_MIC,
 	ALC294_FIXUP_ASUS_SPK,
+	ALC294_FIXUP_ASUS_Q423SA,
 	ALC293_FIXUP_SYSTEM76_MIC_NO_PRESENCE,
 	ALC285_FIXUP_LENOVO_PC_BEEP_IN_NOISE,
 	ALC255_FIXUP_ACER_HEADSET_MIC,
@@ -9481,6 +9482,17 @@ static const struct hda_fixup alc269_fixups[] = {
 		.chained = true,
 		.chain_id = ALC294_FIXUP_ASUS_HEADSET_MIC
 	},
+	[ALC294_FIXUP_ASUS_Q423SA] = {
+		.type = HDA_FIXUP_VERBS,
+		.v.verbs = (const struct hda_verb[]) {
+			/* Restore bit 10 lost after reboot from Windows */
+			{ 0x20, AC_VERB_SET_COEF_INDEX, 0x1b },
+			{ 0x20, AC_VERB_SET_PROC_COEF, 0x4e4b },
+			{ }
+		},
+		.chained = true,
+		.chain_id = ALC2XX_FIXUP_HEADSET_MIC,
+	},
 	[ALC295_FIXUP_CHROME_BOOK] = {
 		.type = HDA_FIXUP_FUNC,
 		.v.func = alc295_fixup_chromebook,
@@ -11250,7 +11262,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x1043, 0x10a1, "ASUS UX391UA", ALC294_FIXUP_ASUS_SPK),
 	SND_PCI_QUIRK(0x1043, 0x10a4, "ASUS TP3407SA", ALC287_FIXUP_TAS2781_I2C),
 	SND_PCI_QUIRK(0x1043, 0x10c0, "ASUS X540SA", ALC256_FIXUP_ASUS_MIC),
-	SND_PCI_QUIRK(0x1043, 0x10c4, "ASUS Vivobook S14 S5406SA", ALC2XX_FIXUP_HEADSET_MIC),
+	SND_PCI_QUIRK(0x1043, 0x10c4, "ASUS S5406SA/Q423SA", ALC294_FIXUP_ASUS_Q423SA),
 	SND_PCI_QUIRK(0x1043, 0x10d0, "ASUS X540LA/X540LJ", ALC255_FIXUP_ASUS_MIC_NO_PRESENCE),
 	SND_PCI_QUIRK(0x1043, 0x10d3, "ASUS K6500ZC", ALC294_FIXUP_ASUS_SPK),
 	SND_PCI_QUIRK(0x1043, 0x1154, "ASUS TP3607SH", ALC287_FIXUP_TAS2781_I2C),
Signature · 1 line
2.53.0
author maintainer
#1539 lore raw

PATCH 1535/1536 ocfs2: read the xattr entry hash before defragmenting the bucket

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

Patch series "ocfs2: fix stale xattr entry pointers and empty header reads", v1.

Five defects in the ocfs2 extended attribute code, plus one robustness measure that belongs with them, all on the paths that move entries between a block, a bucket and an index tree. They fall into two groups.

Stale entry pointers (patches 1 to 3)

ocfs2_xa_set() writes through a pointer into xh_entries[] that two of its callers invalidate first. Defragmenting a bucket ends in a sort() on xe_name_hash, and lib/sort.c is an unstable heapsort, so entries that share a hash can trade slots. Copying a block into a bucket changes the order outright, since a block holds its entries in insertion order while a bucket holds them by hash, yet ocfs2_xattr_update_xattr_search() relocates the search by the index the entry had in the block. Neither path compares the entry's name with the one being set, so setxattr() can replace a neighbouring attribute's value and still report success, or trip ocfs2_xa_reuse_entry()'s BUG_ON. Patch 1 takes the hash before the sort; patches 2 and 3 look the entry up again afterwards.

Reads of an empty entry array (patches 4 to 6)

A block and a bucket may both hold no entries: ocfs2_xa_remove_entry() keeps the last slot when it removes the only one, so an empty bucket still carries the hash it is keyed by. Three sites index xh_entries[] without checking xh_count and so read xh_entries[-1], which lands on the header and comes back as xh_count | xh_free_start << 16. Nothing faults, but the value is acted on: the collision check reports no collision for an empty bucket, the divide commits a sentinel hash that hides part of the key space from ocfs2_xattr_bucket_find(), and the block to bucket copy claims storage the bucket does not hold. Patches 4 to 6 guard each site and keep the one read of xh_entries[0] that ocfs2_xa_remove_entry() documents as intentional.

This patch (of 6):

ocfs2_xattr_set_entry_index_block() takes the hash a bucket split has to work with out of xs->here, but only after ocfs2_xattr_set_entry_bucket() has tried and failed to fit the entry. That call defragments the bucket when it runs out of room, and ocfs2_defrag_xattr_bucket() finishes by sorting the entry array by name hash. lib/sort.c is not stable, so two entries sharing a hash may trade slots and xs->here is left naming an entry other than the one the search found.

The hash value itself survives the permutation -- the array is already sorted, so a slot can only exchange with an equal-hash neighbour -- but there is no reason to depend on that. Pick the hash up before the set, where xs->here is unambiguously the entry the search landed on.

No functional change intended.

Fixes e39baff18b85 ("ocfs2: use the stored hash when checking xattr bucket collision")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 26 ++++++++++++++++----------
 1 file changed, 16 insertions(+), 10 deletions(-)
fs/ocfs2/xattr.c +16 -10
index de4a7070d4ac5..f73bfcfcde546 100644
@@ -5898,6 +5898,22 @@ static int ocfs2_xattr_set_entry_index_block(struct inode *inode,
 
 	trace_ocfs2_xattr_set_entry_index_block(xi->xi_name);
 
+	/*
+	 * 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.
+	 *
+	 * Read it before the set below.  Filling the bucket may defragment it,
+	 * and ocfs2_defrag_xattr_bucket() re-sorts the entry array, so
+	 * afterwards xs->here only denotes whichever entry the sort left in
+	 * that slot.
+	 */
+	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_xattr_set_entry_bucket(inode, xi, xs, ctxt);
 	if (!ret)
 		goto out;
@@ -5913,17 +5929,7 @@ 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.
 	 */
-	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);
Signature · 1 line
2.53.0
author maintainer
#1540 lore raw

PATCH 1536/1536 apparmor: on failed load ensure profile files are removed before parent

In reply to Greg Kroah-Hartman

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

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

From: John Johansen <[email protected]>

[ Upstream commit 97ba44a2aa4c7ab011a93ce94cb595200fe4ea4f ]

The load interface does not guarantee the order profiles are loaded. When a parent is loaded after its child, and the load fails, the current code will issue a warning, and leak a dentry.

For the loaded set of profiles, ensure that on failure list is ordered is traversed in reverse so any children processed after their parent is freed first. We do not need to deal with the cases where the children are processed before their parent, because either a parent outside the list already exists or a dummy parent outside of the list is created, and the list walk will not put those parents before their children.

Fixes 6ec46f8f1977d ("apparmor: remove fs entries created by a failed policy load")
---
 security/apparmor/policy.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
security/apparmor/policy.c +3 -1
index efa11a1a297d4..c9ffb1eec7a7c 100644
@@ -1373,8 +1373,10 @@ ssize_t aa_replace_profiles(struct aa_ns *policy_ns, struct aa_label *label,
 	 * them yet, and leaving them behind would leak the new profiles
 	 * (their dents pin the proxy) and make the next load at the same,
 	 * unbumped ns revision fail with -EEXIST on its raw_data dir.
+	 * ensure children (which are at the end of the list are removed
+	 * before their parent
 	 */
-	list_for_each_entry(tmp, &lh, list) {
+	list_for_each_entry_reverse(tmp, &lh, list) {
 		if (!tmp->old)
 			__aafs_profile_rmdir(tmp->new);
 	}
Signature · 1 line
2.53.0
Tested-by on the v1 series
#1541 lore raw
In reply to Greg Kroah-Hartman

Am 07.11.2026 um 14:33 schrieb Greg Kroah-Hartman:

Quoted 4 lines

This is the start of the stable review cycle for the 6.12.117 release. There are 1536 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

Builds, boots and works on my 2-socket Ivy Bridge Xeon E5-2697v2 server. No dmesg oddities or regressions found.

Beste Grüße,
Peter Schneider

Signature · 8 lines
Climb the mountain not to plant your flag, but to embrace the challenge,
enjoy the air and behold the view. Climb it so you can see the world,
not so the world can see you.                    -- David McCullough Jr.

OpenPGP:  0xA3828BD796CCE11A8CADE8866E3A92C92C3FF244
Download: https://www.peters-netzplatz.de/download/pschneider1968_pub.asc
https://keys.mailvelope.com/pks/lookup?op=get&[email protected]
https://keys.mailvelope.com/pks/lookup?op=get&[email protected]
maintainer Tested-by on the v1 series
#1542 lore raw
In reply to Greg Kroah-Hartman
Quoted 8 lines · On Sat, 07 Nov 2026 08:33:36 -0500 Greg Kroah-Hartman…

This is the start of the stable review cycle for the 6.12.117 release. There are 1536 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

Responses should be made by Mon, 09 Nov 2026 13:46:08 +0000. Anything received after that time might be too late.

I did another run with the Rust block one reverted, and with that, I get my usuals results:

https://lore.kernel.org/stable/[email protected]/

i.e.

Boot-tested under QEMU for Rust x86_64, arm64 and riscv64; built-tested for loongarch64:

I hope that helps!

Cheers,
Miguel

Tested-by on the v1 series
#1543 lore raw
In reply to Greg Kroah-Hartman
Quoted 9 lines · Greg Kroah-Hartman

This is the start of the stable review cycle for the 6.12.117 release. There are 1536 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

Responses should be made by Mon, 09 Nov 2026 13:46:08 +0000. Anything received after that time might be too late.

The whole patch series can be found in one patch at:

Quoted 8 lines
	https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.117-rc1.gz

or in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.git linux-6.12.y
and the diffstat can be found below.

thanks,

greg k-h

I took 6.12.116 and applied the stable-queue as of commit 39e32a361d2fca269cec12e8669e2bd3b84844d9 ("drop 24 patches based on RC review feedback"). So this dropped the build-breaking XFS patch, but still had "smb: client: validate NT transaction response layout and offsets".

Tested on my Lenovo ThinkPad T14 Gen 1 and an arm64 virtual machine. Working well, no regressions observed.

Signature · 1 line
-Barry K. Nathan  <[email protected]>
Tested-by on the v1 series
#1544 lore raw
In reply to Greg Kroah-Hartman
Quoted 9 lines · Greg Kroah-Hartman

This is the start of the stable review cycle for the 6.12.117 release. There are 1536 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

Responses should be made by Mon, 09 Nov 2026 13:46:08 +0000. Anything received after that time might be too late.

The whole patch series can be found in one patch at:

Quoted 8 lines
	https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.117-rc1.gz

or in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.git linux-6.12.y
and the diffstat can be found below.

thanks,

greg k-h

Built and booted successfully on RISC-V RV64 (HiFive Unmatched).

#1545 lore raw
In reply to Greg Kroah-Hartman

Hi!

Quoted 4 lines

This is the start of the stable review cycle for the 6.12.117 release. There are 1536 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

I see build problems in -cip testing:

arch/arm/mach-imx/pm-imx6.c: In function 'imx6q_suspend_init':
618
16:02:42
arch/arm/mach-imx/pm-imx6.c:589:17: error: implicit declaration of function 'cfi_get_func_hash' [-Wimplicit-function-declaration] 619
16:02:42
589 | cfi_get_func_hash((void *)((uintptr_t)&imx6_suspend & ~1UL));
620
16:02:42

      |                 ^~~~~~~~~~~~~~~~~

621

https://gitlab.com/cip-project/cip-testing/linux-stable-rc-ci/-/pipelines/3040183502
https://gitlab.com/cip-project/cip-testing/linux-stable-rc-ci/-/tree/linux-6.12.y

Best regards,
Pavel

maintainer
#1546 lore raw
Quoted 18 lines · Pavel Machek

Hi!

Quoted 4 lines

This is the start of the stable review cycle for the 6.12.117 release. There are 1536 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

I see build problems in -cip testing:

arch/arm/mach-imx/pm-imx6.c: In function 'imx6q_suspend_init':
618
16:02:42
arch/arm/mach-imx/pm-imx6.c:589:17: error: implicit declaration of function 'cfi_get_func_hash' [-Wimplicit-function-declaration] 619
16:02:42
589 | cfi_get_func_hash((void *)((uintptr_t)&imx6_suspend & ~1UL));
620
16:02:42

Quoted 2 lines
      |                 ^~~~~~~~~~~~~~~~~

621

I am observing the same build issue with this update.

Jon

Signature · 1 line
nvpublic
maintainer
#1547 lore raw
In reply to Pavel Machek
Quoted 4 lines · Pavel Machek

I see build problems in -cip testing:

arch/arm/mach-imx/pm-imx6.c: In function 'imx6q_suspend_init':
arch/arm/mach-imx/pm-imx6.c:589:17: error: implicit declaration of function 'cfi_get_func_hash' [-Wimplicit-function-declaration]

"ARM: imx: Fix suspend/resume crash with Clang CFI" (upstream 242757d109bd) was already dropped from the 6.12 queue on 11-08 (stable-queue commit 39e32a361d), after 6.12.117-rc1 had been generated, so it will not be in the 6.12 release.

Thanks for the report.

Signature · 2 lines
Thanks,
Sasha
Tested-by on the v1 series
#1548 lore raw
In reply to Greg Kroah-Hartman
Quoted 9 lines · Greg Kroah-Hartman

This is the start of the stable review cycle for the 6.12.117 release. There are 1536 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

Responses should be made by Mon, 09 Nov 2026 13:46:08 +0000. Anything received after that time might be too late.

The whole patch series can be found in one patch at:

Quoted 8 lines
	https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.117-rc1.gz

or in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.git linux-6.12.y
and the diffstat can be found below.

thanks,

greg k-h

On ARCH_BRCMSTB using 32-bit and 64-bit ARM kernels, build tested with BMIPS_GENERIC:

Signature · 1 line
Florian
Tested-by on the v1 series
#1549 lore raw
In reply to Greg Kroah-Hartman
Quoted 9 lines · Greg Kroah-Hartman

This is the start of the stable review cycle for the 6.12.117 release. There are 1536 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

Responses should be made by Mon, 09 Nov 2026 13:46:08 +0000. Anything received after that time might be too late.

The whole patch series can be found in one patch at:

Quoted 9 lines
	https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.117-rc1.gz

or in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.git linux-6.12.y
and the diffstat can be found below.

thanks,

greg k-h

Compiled and booted on my test system. No dmesg regressions.

thanks,
-- Shuah