Skip to contentSkip to conversation

6.18.63-rc1 review

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

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

PATCH 402/869 wifi: mt76: mt7925: cancel mlo_pm_work on the USB stop path

In reply to Greg Kroah-Hartman

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

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

From: Devin Wittmayer <[email protected]>

[ Upstream commit 9f299215d1d835aeeee8b269dad09e1be06f856e ]

Every other teardown path cancels this work, PCIe unbind included. USB unbind does not: PCIe has its own unregister hook for it, while USB shares a generic one and the stop callback that would have covered it is replaced in probe.

That cancel came in commit 81faf578320d ("wifi: mt76: mt7925: cancel mlo_pm_work on stop"), whose last line says it covers both buses. That's mine and it's a boo-boo.

Give the USB path its own stop that cancels the work first.

Two-link MLO on a Netgear A9000, work armed then the interface down:

stock patched
stop ran 3/3 3/3
work still ran 3/3 0/3

Skipping the stop entirely leaves both builds running it, so the zero is the cancel.

Fixes 276a56883257 ("wifi: mt76: mt7925: update the power-saving flow")
---
 drivers/net/wireless/mediatek/mt76/mt7925/usb.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
drivers/net/wireless/mediatek/mt76/mt7925/usb.c +10 -1
index 95047ee48a425..0ad86526dddc8 100644
@@ -132,6 +132,15 @@ static int mt7925u_mac_reset(struct mt792x_dev *dev)
 	return err;
 }
 
+static void mt7925u_stop(struct ieee80211_hw *hw, bool suspend)
+{
+	struct mt792x_dev *dev = mt792x_hw_dev(hw);
+
+	cancel_delayed_work_sync(&dev->mlo_pm_work);
+
+	mt792xu_stop(hw, suspend);
+}
+
 static int mt7925u_probe(struct usb_interface *usb_intf,
 			 const struct usb_device_id *id)
 {
@@ -178,7 +187,7 @@ static int mt7925u_probe(struct usb_interface *usb_intf,
 	if (!ops)
 		return -ENOMEM;
 
-	ops->stop = mt792xu_stop;
+	ops->stop = mt7925u_stop;
 
 	mdev = mt76_alloc_device(&usb_intf->dev, sizeof(*dev), ops, &drv_ops);
 	if (!mdev)
Signature · 1 line
2.53.0
author maintainer
#404 lore raw

PATCH 403/869 wifi: mt76: mt7615: cancel reset work during unregister

In reply to Greg Kroah-Hartman

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

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

From: Jiale Yao <[email protected]>

[ Upstream commit 5b779c63fb1e20e6729d3241b78be7502759296d ]

The MCU error interrupt handler queues reset_work on the device workqueue. Device removal can reach mt76_unregister_device() while that work is still pending, since the workqueue is not destroyed until mt76_free_device().

If reset_work runs in this window, it operates on an unregistered hw and can requeue mac_work after ieee80211_unregister_hw() has torn the device down. Cancel it before unregistering the device so it cannot outlive the registered hw.

Fixes 61c4fa721968 ("mt76: mt7615: implement hardware reset support")
---
 drivers/net/wireless/mediatek/mt76/mt7615/pci_init.c | 1 +
 1 file changed, 1 insertion(+)
drivers/net/wireless/mediatek/mt76/mt7615/pci_init.c +1 -0
index f607eee3fb479..5e09f43926e02 100644
@@ -116,6 +116,7 @@ void mt7615_unregister_device(struct mt7615_dev *dev)
 	mcu_running = mt7615_wait_for_mcu_init(dev);
 
 	mt7615_unregister_ext_phy(dev);
+	cancel_work_sync(&dev->reset_work);
 	mt76_unregister_device(&dev->mt76);
 	if (mcu_running)
 		mt7615_mcu_exit(dev);
Signature · 1 line
2.53.0
author maintainer
#405 lore raw

PATCH 404/869 wifi: mt76: Fix of_node reference leak in mt76_get_rate_power_limits()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 8d604c899f7bd1a76a2eb21c0b706c02878abd36 ]

mt76_find_power_limits_node() and mt76_find_channel_node() return nodes with the reference held, but mt76_get_rate_power_limits() overwrites the "txpower-<band>" node reference and never releases the channel node reference, leaking both.

Drop the intermediate and the channel node reference on every exit path, and take a reference on the fallback node returned by mt76_find_power_limits_node() so the caller's of_node_put() is balanced.

Fixes 22b980badc0f ("mt76: add functions for parsing rate power limits from DT")
---
 drivers/net/wireless/mediatek/mt76/eeprom.c | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)
drivers/net/wireless/mediatek/mt76/eeprom.c +12 -5
index 6ce8e4af18fe5..281b2c3e9e7cf 100644
@@ -224,12 +224,14 @@ mt76_find_power_limits_node(struct mt76_dev *dev)
 		struct property *regd = of_find_property(cur, "regdomain", NULL);
 
 		if (!country && !regd) {
-			fallback = cur;
+			of_node_put(fallback);
+			fallback = of_node_get(cur);
 			continue;
 		}
 
 		if (mt76_string_prop_find(country, dev->alpha2) ||
 		    mt76_string_prop_find(regd, region_name)) {
+			of_node_put(fallback);
 			of_node_put(np);
 			return cur;
 		}
@@ -356,7 +358,7 @@ s8 mt76_get_rate_power_limits(struct mt76_phy *phy,
 			      s8 target_power)
 {
 	struct mt76_dev *dev = phy->dev;
-	struct device_node *np;
+	struct device_node *np, *band_np;
 	const s8 *val;
 	char name[16];
 	u32 mcs_rates = dev->drv->mcs_rates;
@@ -389,15 +391,18 @@ s8 mt76_get_rate_power_limits(struct mt76_phy *phy,
 		band = '6';
 		break;
 	default:
+		of_node_put(np);
 		return target_power;
 	}
 
 	snprintf(name, sizeof(name), "txpower-%cg", band);
-	np = of_get_child_by_name(np, name);
-	if (!np)
+	band_np = of_get_child_by_name(np, name);
+	of_node_put(np);
+	if (!band_np)
 		return target_power;
 
-	np = mt76_find_channel_node(np, chan);
+	np = mt76_find_channel_node(band_np, chan);
+	of_node_put(band_np);
 	if (!np)
 		return target_power;
 
@@ -422,6 +427,8 @@ s8 mt76_get_rate_power_limits(struct mt76_phy *phy,
 				     ARRAY_SIZE(dest->ru), val, len,
 				     target_power, txs_delta, &max_power);
 
+	of_node_put(np);
+
 	return max_power;
 }
 EXPORT_SYMBOL_GPL(mt76_get_rate_power_limits);
Signature · 1 line
2.53.0
author maintainer
#406 lore raw

PATCH 405/869 wifi: mt76: mt7996: fix PCI device reference leak in mt7996_pci_init_hif2()

In reply to Greg Kroah-Hartman

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

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

From: Linlin Yang <[email protected]>

[ Upstream commit d92bac6b6af2602516ee82ae112709c71af27cf6 ]

pci_get_device() increments the reference count on the returned struct pci_dev. In mt7996_pci_init_hif2(), three pci_get_device() calls are made but their return values are only checked for NULL and then discarded. pci_dev_put() is never called, causing a PCI device reference count leak.

Fix this by storing the return value and calling pci_dev_put() before returning, following the same pattern already used in the sibling driver mt7915/pci.c.

Fixes 98686cd21624 ("wifi: mt76: mt7996: add driver for MediaTek Wi-Fi 7 (802.11be) devices")
---
 drivers/net/wireless/mediatek/mt76/mt7996/pci.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/net/wireless/mediatek/mt76/mt7996/pci.c +9 -3
index 3f49bbbba3b9c..1d9102b5e556a 100644
@@ -63,12 +63,18 @@ static void mt7996_put_hif2(struct mt7996_hif *hif)
 
 static struct mt7996_hif *mt7996_pci_init_hif2(struct pci_dev *pdev)
 {
+	struct pci_dev *tmp_pdev;
+
 	hif_idx++;
 
-	if (!pci_get_device(PCI_VENDOR_ID_MEDIATEK, MT7996_DEVICE_ID_2, NULL) &&
-	    !pci_get_device(PCI_VENDOR_ID_MEDIATEK, MT7992_DEVICE_ID_2, NULL) &&
-	    !pci_get_device(PCI_VENDOR_ID_MEDIATEK, MT7990_DEVICE_ID_2, NULL))
+	tmp_pdev = pci_get_device(PCI_VENDOR_ID_MEDIATEK, MT7996_DEVICE_ID_2, NULL);
+	if (!tmp_pdev)
+		tmp_pdev = pci_get_device(PCI_VENDOR_ID_MEDIATEK, MT7992_DEVICE_ID_2, NULL);
+	if (!tmp_pdev)
+		tmp_pdev = pci_get_device(PCI_VENDOR_ID_MEDIATEK, MT7990_DEVICE_ID_2, NULL);
+	if (!tmp_pdev)
 		return NULL;
+	pci_dev_put(tmp_pdev);
 
 	writel(hif_idx | MT_PCIE_RECOG_ID_SEM,
 	       pcim_iomap_table(pdev)[0] + MT_PCIE_RECOG_ID);
Signature · 1 line
2.53.0
author maintainer
#407 lore raw

PATCH 406/869 clocksource/drivers/fttmr010: Fix clk reference leak in error paths

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 277e5657237a92e279ee28da2f5c07902cc6aa0b ]

fttmr010_common_init() obtains the PCLK reference with of_clk_get_by_name() but never calls clk_put(). If clk_prepare_enable() fails the reference is leaked directly, and every error path that jumps to out_disable_clock only calls clk_disable_unprepare(), which releases the prepare/enable state but not the reference obtained from of_clk_get_by_name().

Add clk_put() to the clk_prepare_enable() failure path and to the out_disable_clock label so the clock reference is no longer leaked. The success path keeps PCLK enabled for the lifetime of the timer and is left untouched.

Fixes dd98442e17a6 ("clocksource/drivers/fttmr010: Drop Gemini specifics")
---
 drivers/clocksource/timer-fttmr010.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/clocksource/timer-fttmr010.c +2 -0
index 126fb1f259b28..0003d49768f62 100644
@@ -292,6 +292,7 @@ static int __init fttmr010_common_init(struct device_node *np,
 	ret = clk_prepare_enable(clk);
 	if (ret) {
 		pr_err("failed to enable PCLK\n");
+		clk_put(clk);
 		return ret;
 	}
 
@@ -432,6 +433,7 @@ static int __init fttmr010_common_init(struct device_node *np,
 	kfree(fttmr010);
 out_disable_clock:
 	clk_disable_unprepare(clk);
+	clk_put(clk);
 
 	return ret;
 }
Signature · 1 line
2.53.0
author maintainer
#408 lore raw

PATCH 407/869 clocksource/drivers/digicolor: Fix clk reference leak on request_irq failure

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 9cc2e18b32f12d26ae6729c62a03640423956b17 ]

digicolor_timer_init() obtains the timer clock with of_clk_get() and enables it, but the request_irq() failure path returns without releasing the clock reference, leaking both the enable/prepare state and the reference itself.

Disable and put the clock before returning on the request_irq() failure path. The success path keeps the clock enabled for the lifetime of the timer and is left untouched.

---
 drivers/clocksource/timer-digicolor.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/clocksource/timer-digicolor.c +2 -0
index 559aa96089c34..46e0c329957a2 100644
@@ -190,6 +190,8 @@ static int __init digicolor_timer_init(struct device_node *node)
 			  &dc_timer_dev.ce);
 	if (ret) {
 		pr_warn("request of timer irq %d failed (%d)\n", irq, ret);
+		clk_disable_unprepare(clk);
+		clk_put(clk);
 		return ret;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#409 lore raw

PATCH 408/869 spi: stm32: fix double free of SRAM buffer on MDMA fallback

In reply to Greg Kroah-Hartman

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

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

From: Pin-Hao Chen <[email protected]>

[ Upstream commit 0c5b0c3eb1d6daa1117dacd32589196f52109cab ]

When the "rxm2m" MDMA channel cannot be obtained, the driver frees the SRAM buffer and falls back to DMA-only mode. However, sram_rx_buf is left pointing to the freed buffer.

As a result, stm32_spi_unprepare_msg() may clear the released SRAM area, while stm32_spi_remove() or a later probe error path may free the buffer again, triggering BUG_ON() in gen_pool_free_owner().

The probe error path also checks sram_pool instead of sram_rx_buf. If the SRAM allocation failed and a later probe step fails, gen_pool_free() may therefore be called with an unallocated buffer.

Clear sram_rx_buf after freeing it on the MDMA fallback path and use the buffer pointer to determine whether cleanup is needed.

Fixes d17dd2f1d8a1 ("spi: stm32: use STM32 DMA with STM32 MDMA to enhance DDR use")
---
 drivers/spi/spi-stm32.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/spi/spi-stm32.c +2 -1
index 7a6ee93be9bd4..e5d483a9d38b1 100644
@@ -2454,6 +2454,7 @@ static int stm32_spi_probe(struct platform_device *pdev)
 					gen_pool_free(spi->sram_pool,
 						      (unsigned long)spi->sram_rx_buf,
 						      spi->sram_rx_buf_size);
+					spi->sram_rx_buf = NULL;
 					dev_warn(&pdev->dev,
 						 "failed to request rx mdma channel, DMA only\n");
 				}
@@ -2491,7 +2492,7 @@ static int stm32_spi_probe(struct platform_device *pdev)
 	if (spi->mdma_rx)
 		dma_release_channel(spi->mdma_rx);
 err_pool_free:
-	if (spi->sram_pool)
+	if (spi->sram_rx_buf)
 		gen_pool_free(spi->sram_pool, (unsigned long)spi->sram_rx_buf,
 			      spi->sram_rx_buf_size);
 err_dma_release:
Signature · 1 line
2.53.0
author maintainer
#410 lore raw

PATCH 409/869 aoe: pull in the headers each received packet type reads

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit e1274a6bc40a4618f6fbaebbdc51cca865d51bed ]

aoenet_rcv() only pulls the AoE and ATA headers into the skb head when the packet is long enough to hold both. A shorter packet goes through unpulled, and aoenet_rcv() reads the AoE header from it anyway. CFG responses go on to aoecmd_cfg_rsp(), which reads the config header after it, and ATA responses get queued for ktiocomplete(), which skb_pull()s both headers. Ethernet pads frames to 60 bytes, so this mostly takes a virtual link, but nothing stops a short frame from getting here.

Pull the AoE header up front and drop the packet if it isn't there, then pull the ATA or config header in the switch arm that hands the packet on, so each path gets the headers it reads. This also replaces the open-coded __pskb_pull_tail() with pskb_may_pull().

---
 drivers/block/aoe/aoenet.c | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)
drivers/block/aoe/aoenet.c +6 -8
index 66e617664c143..cd7c735bb43b7 100644
@@ -131,9 +131,7 @@ static int
 aoenet_rcv(struct sk_buff *skb, struct net_device *ifp, struct packet_type *pt, struct net_device *orig_dev)
 {
 	struct aoe_hdr *h;
-	struct aoe_atahdr *ah;
 	u32 n;
-	int sn;
 
 	if (dev_net(ifp) != &init_net)
 		goto exit;
@@ -144,12 +142,8 @@ aoenet_rcv(struct sk_buff *skb, struct net_device *ifp, struct packet_type *pt,
 	if (!is_aoe_netif(ifp))
 		goto exit;
 	skb_push(skb, ETH_HLEN);	/* (1) */
-	sn = sizeof(*h) + sizeof(*ah);
-	if (skb->len >= sn) {
-		sn -= skb_headlen(skb);
-		if (sn > 0 && !__pskb_pull_tail(skb, sn))
-			goto exit;
-	}
+	if (!pskb_may_pull(skb, sizeof(*h)))
+		goto exit;
 	h = (struct aoe_hdr *) skb->data;
 	n = get_unaligned_be32(&h->tag);
 	if ((h->verfl & AOEFL_RSP) == 0 || (n & 1<<31))
@@ -171,10 +165,14 @@ aoenet_rcv(struct sk_buff *skb, struct net_device *ifp, struct packet_type *pt,
 
 	switch (h->cmd) {
 	case AOECMD_ATA:
+		if (!pskb_may_pull(skb, sizeof(*h) + sizeof(struct aoe_atahdr)))
+			goto exit;
 		/* ata_rsp may keep skb for later processing or give it back */
 		skb = aoecmd_ata_rsp(skb);
 		break;
 	case AOECMD_CFG:
+		if (!pskb_may_pull(skb, sizeof(*h) + sizeof(struct aoe_cfghdr)))
+			goto exit;
 		aoecmd_cfg_rsp(skb);
 		break;
 	default:
Signature · 1 line
2.53.0
author maintainer
#411 lore raw

PATCH 410/869 PCI/sysfs: Pass the device name length in UTF-16 code units

In reply to Greg Kroah-Hartman

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

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

From: Krzysztof Wilczyński <[email protected]>

[ Upstream commit af5ca2d75147bf283239e8ef0fbf6e5e0488ca91 ]

Currently, dsm_label_utf16s_to_utf8s() passes the ACPI buffer length to utf16s_to_utf8s() unchanged. The Device Name _DSM may return the device name as a buffer holding a UTF-16 string, and the ACPI length counts bytes while the converter counts wchar_t elements. The converter therefore receives a count twice the number of code units the buffer holds, and that count is its only bound on the input.

A NUL code unit ends the conversion early, so a name that carries one is converted correctly and the error stays hidden. ACPICA zeroes the entire result allocation, and the padding placed after the buffer supplies that NUL for most lengths. Lengths that leave no padding, or a single byte of it, do not, and the conversion then runs up to its own length in bytes past the end of the allocation. The bytes beyond the allocation are decoded into the "label" attribute, which is world readable.

Divide the buffer length by the size of wchar_t so that the converter receives a count of code units. The division truncates, so the converter is never told to read more bytes than the buffer holds, including for an odd length.

Reaching the out of bounds read needs firmware that returns the name as a buffer and omits the terminator.

Fixes 6058989bad05 ("PCI: Export ACPI _DSM provided firmware instance number and string name to sysfs")
---
 drivers/pci/pci-label.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/pci/pci-label.c +1 -1
index 0c64465196404..c224619b9a266 100644
@@ -144,7 +144,7 @@ static int dsm_label_utf16s_to_utf8s(union acpi_object *obj, char *buf)
 	int len;
 
 	len = utf16s_to_utf8s((const wchar_t *)obj->buffer.pointer,
-			      obj->buffer.length,
+			      obj->buffer.length / sizeof(wchar_t),
 			      UTF16_LITTLE_ENDIAN,
 			      buf, PAGE_SIZE - 1);
 	buf[len++] = '\n';
Signature · 1 line
2.53.0
author maintainer
#412 lore raw

PATCH 411/869 wifi: rtw89: fix IE length passed to cfg80211_find_ie() in WoW AKM

In reply to Greg Kroah-Hartman

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

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

From: Tristan Madani <[email protected]>

[ Upstream commit 6c17c57d45ef1652d80f79a9834597b25412fd26 ]

__rtw89_wow_parse_akm() computes a pointer to the IE area from an association request frame:

    ies = mgmt->u.assoc_req.variable;

but then passes skb->len as the IE data length to cfg80211_find_ie(). Since skb->len covers the entire frame including the 28-byte management header and fixed fields, cfg80211_find_ie() may read past the end of the actual IE data.

Fix by computing the correct IE data length as skb->len minus the header offset, and validating the minimum frame length before parsing.

Fixes 92790c4e50d2 ("wifi: rtw89: wow: parsing Auth Key Management from associate request")
---
 drivers/net/wireless/realtek/rtw89/wow.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/net/wireless/realtek/rtw89/wow.c +5 -1
index 90046d6f620ef..144c4c2801bdb 100644
@@ -16,10 +16,14 @@ void __rtw89_wow_parse_akm(struct rtw89_dev *rtwdev, struct sk_buff *skb)
 {
 	struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)skb->data;
 	struct rtw89_wow_param *rtw_wow = &rtwdev->wow;
+	size_t hdr_len = offsetof(struct ieee80211_mgmt, u.assoc_req.variable);
 	const u8 *rsn, *ies = mgmt->u.assoc_req.variable;
 	struct rtw89_rsn_ie *rsn_ie;
 
-	rsn = cfg80211_find_ie(WLAN_EID_RSN, ies, skb->len);
+	if (skb->len < hdr_len)
+		return;
+
+	rsn = cfg80211_find_ie(WLAN_EID_RSN, ies, skb->len - hdr_len);
 	if (!rsn)
 		return;
 
Signature · 1 line
2.53.0
author maintainer
#413 lore raw

PATCH 412/869 crypto: algif_skcipher - rewind rounded output bytes

In reply to Greg Kroah-Hartman

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

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

From: Daehyeon Ko <[email protected]>

[ Upstream commit 2f90facc7b94934653eb7ebfadcc25d503b89196 ]

af_alg_get_rsgl() advances the receive iterator by the unrounded RX scatterlist length. For a continuing skcipher request, _skcipher_recvmsg() then rounds its local length down to a whole chunksize without restoring the iterator.

A later chunk starts after bytes which the provider never wrote, while the syscall returns only the processed length. When copy_splice_read() supplies non-zeroed pages and publishes that return as a dense prefix, the gap exposes stale bytes from a previous page lifetime.

With unprivileged xts(aes), a 31-byte MSG_MORE request followed by one final byte advances a 47-byte destination while returning 32 bytes. A hardened v7.2-rc5 image retained all 15 seeded stale bytes in 4,829 of 4,829 records. With init_on_alloc enabled, all 72,345 gap bytes observed were zero.

Rewind the iterator by the tail excluded during rounding, before rejecting a zero processed length. The crypto request uses only the rounded length; af_alg_free_resources() releases the entire RX list before another receive iteration.

The fixed target-like kernel returned byte-identical dense 48-byte output in 4,771 of 4,771 rounds. The unmodified kernel returned the vulnerable 32-byte short record in 2,409 of 2,409 rounds.

Fixes e870456d8e7c ("crypto: algif_skcipher - overhaul memory management")
Assisted-by LLM
---
 crypto/algif_skcipher.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
crypto/algif_skcipher.c +6 -2
index 35ebc3e0201b0..b245d37db76b7 100644
@@ -116,12 +116,16 @@ static int _skcipher_recvmsg(struct socket *sock, struct msghdr *msg,
 	 * full block size buffers.
 	 */
 	if (ctx->more || len < ctx->used) {
-		if (len < bs) {
+		size_t excess = len % bs;
+
+		len -= excess;
+		iov_iter_revert(&msg->msg_iter, excess);
+
+		if (!len) {
 			err = -EINVAL;
 			goto free;
 		}
 
-		len -= len % bs;
 		cflags |= CRYPTO_SKCIPHER_REQ_NOTFINAL;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#414 lore raw

PATCH 413/869 ALSA: hda/hdmi: clamp num_cvts against cvt_nids[] in hdmi_read_pin_conn

In reply to Greg Kroah-Hartman

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

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

From: Peter Ujfalusi <[email protected]>

[ Upstream commit 6cf3ab38b0d53d41f00fe594b2986849bdf994ae ]

hdmi_add_cvt() stores each converter's NID into the fixed-size spec->cvt_nids[] array (used only by the Intel Haswell pin-connection fixup), but only when spec->num_cvts is still within ARRAY_SIZE(cvt_nids); the num_cvts counter itself is incremented unconditionally regardless of whether the store happened. A codec that reports more converters than cvt_nids[] can hold therefore ends up with num_cvts > ARRAY_SIZE(cvt_nids).

hdmi_read_pin_conn(), on the intel_hsw_fixup path, copies num_cvts elements from cvt_nids[] with memcpy(), so once num_cvts exceeds the array size this reads past cvt_nids[] and writes the resulting garbage NIDs into per_pin->mux_nids[].

Clamp the copy length to the actual size of cvt_nids[] instead of trusting num_cvts, which is also used unbounded as the size of the separate, dynamically-sized spec->cvts array and must not be truncated at the source.

Fixes bce0d2a80e42 ("ALSA: hda - Allow unlimited pins and converters in patch_hdmi.c")
---
 sound/hda/codecs/hdmi/hdmi.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
sound/hda/codecs/hdmi/hdmi.c +2 -1
index 480d1c5f129fd..a30072139f352 100644
@@ -983,7 +983,8 @@ static int hdmi_read_pin_conn(struct hda_codec *codec, int pin_idx)
 	snd_hda_set_dev_select(codec, pin_nid, dev_id);
 
 	if (spec->intel_hsw_fixup) {
-		conns = spec->num_cvts;
+		/* spec->cvt_nids[] only has ARRAY_SIZE(spec->cvt_nids) slots */
+		conns = min_t(int, spec->num_cvts, ARRAY_SIZE(spec->cvt_nids));
 		memcpy(per_pin->mux_nids, spec->cvt_nids,
 		       sizeof(hda_nid_t) * conns);
 	} else {
Signature · 1 line
2.53.0
author maintainer
#415 lore raw

PATCH 414/869 ALSA: hda/hdmi: clamp sad_count in ELD proc write handler

In reply to Greg Kroah-Hartman

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

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

From: Peter Ujfalusi <[email protected]>

[ Upstream commit b3e7ddd694f8429217ba509b55b910a0e4361dfb ]

snd_hdmi_write_eld_info() parses a "sad_count N" line from the root-writable ELD proc interface and assigns N directly to e->sad_count with no upper bound, unlike the per-index "sadN_*" lines a few lines below which are already bounded to ELD_MAX_SAD.

snd_hdmi_eld_update_pcm_info() later iterates
"for (i = 0; i < e->sad_count; i++)" over the fixed e->sad[ELD_MAX_SAD] array, so an oversized sad_count read from the proc file causes it to walk past the array.

Reject sad_count values above ELD_MAX_SAD, matching the existing per-index guard.

Fixes acb059938810 ("ALSA: hda - ELD proc interface write updates")
---
 sound/hda/codecs/hdmi/eld.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
sound/hda/codecs/hdmi/eld.c +4 -2
index 1464fd1c675bc..fc6fe1b0873c3 100644
@@ -155,9 +155,11 @@ void snd_hdmi_write_eld_info(struct hdmi_eld *eld,
 			e->aud_synch_delay = val;
 		else if (!strcmp(name, "speakers"))
 			e->spk_alloc = val;
-		else if (!strcmp(name, "sad_count"))
+		else if (!strcmp(name, "sad_count")) {
+			if (val > ELD_MAX_SAD)
+				continue;
 			e->sad_count = val;
-		else if (!strncmp(name, "sad", 3)) {
+		} else if (!strncmp(name, "sad", 3)) {
 			sname = name + 4;
 			n = name[3] - '0';
 			if (name[4] >= '0' && name[4] <= '9') {
Signature · 1 line
2.53.0
author maintainer
#416 lore raw

PATCH 415/869 fanotify: report names longer than NAME_MAX

In reply to Greg Kroah-Hartman

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

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

From: Matthias Goergens <[email protected]>

[ Upstream commit ff05910cb1b77c2b229c5e6e260c6173a17b579b ]

fanotify keeps the length of a reported name in a u8, so it drops any name longer than NAME_MAX and warns:

  WARNING: fs/notify/fanotify/fanotify.h:217 at fanotify_handle_event+0x2e82/0x39f0

Such names are legitimate on some filesystems. vfat mounted with utf8 takes up to 255 UTF-16 characters, which are up to 765 bytes of UTF-8, and FUSE accepts names up to PATH_MAX - 1. readdir() and inotify report them in full. fanotify sends the event without the name, and for FAN_RENAME it trips a second warning in copy_fid_info_to_user(), after which read() fails with EFAULT and the event is lost.

When syzbot hit this, Jan suggested accommodating names up to PATH_MAX [1], the limit readdir() already applies to a name (verify_dirent_name()). Store the name lengths as u16, which keeps struct fanotify_info at 8 bytes, and drop without a warning only names of PATH_MAX bytes or more, which no path can refer to. An event with such a name can exceed a page, so allocate name events with kvmalloc(), as Jan also suggested. Names up to NAME_MAX are reported exactly as before, and the record format is unchanged: an event with a long name is just longer.

---
 fs/notify/fanotify/fanotify.c |  7 +++++--
 fs/notify/fanotify/fanotify.h | 21 ++++++++++++---------
 2 files changed, 17 insertions(+), 11 deletions(-)
fs/notify/fanotify/fanotify.c +5 -2
index cdb69c23e2e6c..bb12baebd0c94 100644
@@ -650,6 +650,9 @@ static struct fanotify_event *fanotify_alloc_name_event(struct inode *dir,
 	unsigned long name2_len = name2 ? name2->len : 0;
 	unsigned int len, size;
 
+	if (WARN_ON_ONCE(name_len >= PATH_MAX || name2_len >= PATH_MAX))
+		return NULL;
+
 	/* Reserve terminating null byte even for empty name */
 	size = sizeof(*fne) + name_len + name2_len + 2;
 	if (dir_fh_len)
@@ -658,7 +661,7 @@ static struct fanotify_event *fanotify_alloc_name_event(struct inode *dir,
 		size += FANOTIFY_FH_HDR_LEN + dir2_fh_len;
 	if (child_fh_len)
 		size += FANOTIFY_FH_HDR_LEN + child_fh_len;
-	fne = kmalloc(size, gfp);
+	fne = kvmalloc(size, gfp);
 	if (!fne)
 		return NULL;
 
@@ -1048,7 +1051,7 @@ static void fanotify_free_fid_event(struct fanotify_event *event)
 
 static void fanotify_free_name_event(struct fanotify_event *event)
 {
-	kfree(FANOTIFY_NE(event));
+	kvfree(FANOTIFY_NE(event));
 }
 
 static void fanotify_free_error_event(struct fsnotify_group *group,
fs/notify/fanotify/fanotify.h +12 -9
index eb2ba71d5c81a..775f55080dd4d 100644
@@ -42,9 +42,16 @@ struct fanotify_info {
 	u8 dir_fh_totlen;
 	u8 dir2_fh_totlen;
 	u8 file_fh_totlen;
-	u8 name_len;
-	u8 name2_len;
-	u8 pad[3];
+	u8 pad;
+	/*
+	 * Deliberately not limited to NAME_MAX: some filesystems return longer
+	 * names (vfat up to 255 UTF-16 characters, as Windows allows, which is
+	 * up to 765 bytes of UTF-8; FUSE up to PATH_MAX - 1), and readdir() and
+	 * inotify report them in full. Only names of PATH_MAX bytes or more,
+	 * which no path can refer to, are dropped.
+	 */
+	u16 name_len;
+	u16 name2_len;
 	unsigned char buf[];
 	/*
 	 * (struct fanotify_fh) dir_fh starts at buf[0]
@@ -167,7 +174,7 @@ static inline char *fanotify_info_name2(struct fanotify_info *info)
 static inline void fanotify_info_init(struct fanotify_info *info)
 {
 	BUILD_BUG_ON(FANOTIFY_FH_HDR_LEN + MAX_HANDLE_SZ > U8_MAX);
-	BUILD_BUG_ON(NAME_MAX > U8_MAX);
+	BUILD_BUG_ON(PATH_MAX > U16_MAX);
 
 	info->dir_fh_totlen = 0;
 	info->dir2_fh_totlen = 0;
@@ -213,8 +220,7 @@ static inline void fanotify_info_set_file_fh(struct fanotify_info *info,
 static inline void fanotify_info_copy_name(struct fanotify_info *info,
 					   const struct qstr *name)
 {
-	if (WARN_ON_ONCE(name->len > NAME_MAX) ||
-	    WARN_ON_ONCE(info->name2_len > 0))
+	if (WARN_ON_ONCE(info->name2_len > 0))
 		return;
 
 	info->name_len = name->len;
@@ -224,9 +230,6 @@ static inline void fanotify_info_copy_name(struct fanotify_info *info,
 static inline void fanotify_info_copy_name2(struct fanotify_info *info,
 					    const struct qstr *name)
 {
-	if (WARN_ON_ONCE(name->len > NAME_MAX))
-		return;
-
 	info->name2_len = name->len;
 	strcpy(fanotify_info_name2(info), name->name);
 }
Signature · 1 line
2.53.0
author maintainer
#417 lore raw

PATCH 416/869 ext4: only update tune mount options when requested

In reply to Greg Kroah-Hartman

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

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

From: guzebing <[email protected]>

[ Upstream commit 981eec6c300bd4e84ffac8f3c28b762d00f13e9c ]

EXT4_IOC_SET_TUNE_SB_PARAM uses set_flags to indicate which superblock fields the caller wants to update. ext4_sb_setparams() checks set_flags before updating the other supported fields, but always copied mount_opts into the on-disk s_mount_opts field.

As a result, callers that do not set EXT4_TUNE_FL_MOUNT_OPTS can still clear or alter the on-disk default mount options through their unused mount_opts buffer. This can affect subsequent mounts by changing the filesystem's stored default mount options.

Only copy mount_opts into s_mount_opts when EXT4_TUNE_FL_MOUNT_OPTS is set, matching the set_flags semantics used by the other tuneable superblock fields.

Fixes 04a91570ac67 ("ext4: implemet new ioctls to set and get superblock parameters")
---
 fs/ext4/ioctl.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/ext4/ioctl.c +2 -1
index 9aec4ee780a7e..cc85786be2704 100644
@@ -1360,7 +1360,8 @@ static void ext4_sb_setparams(struct ext4_sb_info *sbi,
 		es->s_encoding = cpu_to_le16(params->encoding);
 	if (params->set_flags & EXT4_TUNE_FL_ENCODING_FLAGS)
 		es->s_encoding_flags = cpu_to_le16(params->encoding_flags);
-	strscpy_pad(es->s_mount_opts, params->mount_opts);
+	if (params->set_flags & EXT4_TUNE_FL_MOUNT_OPTS)
+		strscpy_pad(es->s_mount_opts, params->mount_opts);
 	if (params->set_flags & EXT4_TUNE_FL_EDIT_FEATURES) {
 		es->s_feature_compat |=
 			cpu_to_le32(params->set_feature_compat_mask);
Signature · 1 line
2.53.0
author maintainer
#418 lore raw

PATCH 417/869 ext4: fix fast commit replay failing on a read-only mount

In reply to Greg Kroah-Hartman

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

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

From: Hsiu-Hsien Lee <[email protected]>

[ Upstream commit e1a881ea4674876721cab97680d1d8308f90e9a4 ]

A filesystem with fast_commit that needs recovery cannot be mounted read-only:

EXT4-fs (dm-0): INFO: recovery required on readonly filesystem EXT4-fs (dm-0): write access will be enabled during recovery

  WARNING: CPU: 22 PID: 5544 at fs/ext4/ext4_jbd2.c:73
   ext4_journal_check_start
   __ext4_journal_start_sb
   __ext4_unlink
   ext4_fc_replay
   do_one_pass
   jbd2_journal_recover
   jbd2_journal_load
   __ext4_fill_super
  JBD2: journal recovery failed
  EXT4-fs (dm-0): error loading journal

Fast commit replay runs ext4 metadata operations instead of writing blocks through the buffer cache: ext4_fc_replay_{unlink,link,create}() reach __ext4_unlink() and __ext4_link(), which start a handle. ext4_journal_check_start() returns -EROFS on a read-only sb, and as that is not -ENOENT it propagates out of jbd2_journal_recover() and kills the whole recovery. The EXT4_FC_REPLAY check that would hand out a no-journal handle sits after the sb_rdonly() test, so replay can never complete read-only.

ext4_load_journal() has already promised that write access will be enabled during recovery, so make that true for the superblock as well:
clear SB_RDONLY across jbd2_journal_load() when recovery is needed on a read-only mount and the devices are writable, as ext4_orphan_cleanup() does. Unlike ext4_handle_error(), which avoids SB_RDONLY because it would need s_umount, the sb here is still inside ext4_fill_super() and not published, so nothing can observe it.

The failure is not clean either: the replay handlers passing a NULL handle (ext4_fc_replay_inode(), _add_range(), _del_range()) never hit ext4_journal_check_start() and do write, leaving a partially applied fast commit behind.

Reproducer, where the unlink only ever reaches the fast commit area:

mke2fs -q -F -t ext4 -O fast_commit -b 4096 /dev/sdb3 262144 mount /dev/sdb3 /mnt
dd if=/dev/zero of=/mnt/victim bs=4k count=1 conv=fsync
sync # victim now in a full commit
rm /mnt/victim
dd if=/dev/zero of=/mnt/trigger bs=4k count=1 conv=fsync <crash, or snapshot the device while mounted and write it back> mount -o ro /dev/sdb3 /mnt

Without this patch that mount fails; with it recovery completes and victim is gone, i.e. the UNLINK record was really replayed.

---
 fs/ext4/super.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
fs/ext4/super.c +14 -0
index b4ff7e692986b..2762628bbfc95 100644
@@ -6016,6 +6016,7 @@ static int ext4_load_journal(struct super_block *sb,
 	int err = 0;
 	int really_read_only;
 	int journal_dev_ro;
+	bool enable_write = false;
 
 	if (WARN_ON_ONCE(!ext4_has_feature_journal(sb)))
 		return -EFSCORRUPTED;
@@ -6072,6 +6073,7 @@ static int ext4_load_journal(struct super_block *sb,
 			}
 			ext4_msg(sb, KERN_INFO, "write access will "
 			       "be enabled during recovery");
+			enable_write = true;
 		}
 	}
 
@@ -6088,7 +6090,19 @@ static int ext4_load_journal(struct super_block *sb,
 		if (save)
 			memcpy(save, ((char *) es) +
 			       EXT4_S_ERR_START, EXT4_S_ERR_LEN);
+		/*
+		 * Fast commit replay performs regular ext4 metadata updates
+		 * (see ext4_fc_replay()) which refuse to run on a read-only
+		 * superblock.  We promised write access above, so make that
+		 * true for the duration of the recovery, the same way
+		 * ext4_orphan_cleanup() does.  The superblock is not published
+		 * yet, so nothing can observe the transient state.
+		 */
+		if (enable_write)
+			sb->s_flags &= ~SB_RDONLY;
 		err = jbd2_journal_load(journal);
+		if (enable_write)
+			sb->s_flags |= SB_RDONLY;
 		if (save && memcmp(((char *) es) + EXT4_S_ERR_START,
 				   save, EXT4_S_ERR_LEN)) {
 			memcpy(((char *) es) + EXT4_S_ERR_START,
Signature · 1 line
2.53.0
author maintainer
#419 lore raw

PATCH 418/869 ext4: reject delalloc to nodelalloc before applying remount options

In reply to Greg Kroah-Hartman

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

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

From: guzebing <[email protected]>

[ Upstream commit 26a3ff309c91986dbedb05d0e0f0050ea0aa629c ]

Commit 97f5ec3b166d ("ext4: prevent delalloc to nodelalloc on remount") rejects switching a mounted filesystem from delalloc to nodelalloc. However, it performs the check after ext4_apply_options() has already cleared EXT4_MOUNT_DELALLOC in the live superblock. The failure path eventually restores the bit, but leaves a window where other CPUs can observe nodelalloc.

test_opt() reads s_mount_opt directly without a lock shared with remount. If a concurrent truncate's __es_remove_extent() hits this window and observes nodelalloc, it sets count_reserved to false. Delayed extent status entries are then removed without calculating their cluster reservations, leaving reserved at zero. ext4_es_remove_extent() therefore calls ext4_da_release_space() with zero, leaving i_reserved_data_blocks and s_dirtyclusters_counter elevated. When the inode is later evicted after unlink, ext4_destroy_inode() reports:

i_reserved_data_blocks (...) not cleared!

CPU 0 CPU 1

                                  ksys_truncate()
                                    ...
                                    ext4_es_remove_extent()

ext4_reconfigure()
ext4_check_opt_consistency()
__ext4_remount()
ext4_apply_options()
clear EXT4_MOUNT_DELALLOC
__es_remove_extent()
test_opt() sees !DELALLOC count_reserved = false
reject delalloc -> nodelalloc
restore EXT4_MOUNT_DELALLOC
remove delayed ES
ext4_da_release_space(0)

Follow the pre-apply validation approach used by ext4_check_quota_consistency() and reject the transition in ext4_check_opt_consistency(), before ext4_apply_options() changes live state. Use mask_s_mount_opt to determine whether delalloc/nodelalloc was specified and ctx_test_mount_opt() to check the final parsed value.

---
 fs/ext4/super.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)
fs/ext4/super.c +8 -7
index 2762628bbfc95..613b04b64b14d 100644
@@ -2783,6 +2783,14 @@ static int ext4_check_opt_consistency(struct fs_context *fc,
 	}
 
 	if (is_remount) {
+		if (test_opt(sb, DELALLOC) &&
+		    (ctx->mask_s_mount_opt & EXT4_MOUNT_DELALLOC) &&
+		    !ctx_test_mount_opt(ctx, EXT4_MOUNT_DELALLOC)) {
+			ext4_msg(sb, KERN_ERR,
+				 "can't disable delalloc during remount");
+			return -EINVAL;
+		}
+
 		if (!sbi->s_journal &&
 		    ctx_test_mount_opt(ctx, EXT4_MOUNT_DATA_ERR_ABORT)) {
 			ext4_msg(NULL, KERN_WARNING,
@@ -6595,13 +6603,6 @@ static int __ext4_remount(struct fs_context *fc, struct super_block *sb)
 		goto restore_opts;
 	}
 
-	if ((old_opts.s_mount_opt & EXT4_MOUNT_DELALLOC) &&
-	    !test_opt(sb, DELALLOC)) {
-		ext4_msg(sb, KERN_ERR, "can't disable delalloc during remount");
-		err = -EINVAL;
-		goto restore_opts;
-	}
-
 	sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
 		(test_opt(sb, POSIX_ACL) ? SB_POSIXACL : 0);
 
Signature · 1 line
2.53.0
author maintainer
#420 lore raw

PATCH 419/869 jbd2: dont advance j_fc_off before the buffer is recorded

In reply to Greg Kroah-Hartman

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

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

From: Daejun Park <[email protected]>

[ Upstream commit 9f359c031885bb50add7d23c7a5a0e9755b134c9 ]

jbd2_fc_get_buf() increments journal->j_fc_off before jbd2_journal_bmap() and __getblk() have had a chance to fail. When either does, the slot j_fc_wbuf[fc_off] is never assigned, but j_fc_off already counts it.

ext4 then fails the fast commit and falls back, and the fallback path reaches jbd2_fc_release_bufs() via ext4_fc_commit -> jbd2_fc_end_commit_fallback -> __jbd2_fc_end_commit -> ext4_fc_cleanup. That walks down from j_fc_off - 1 and put_bh()es every slot until it sees NULL, so it also touches the slot that was never written. j_fc_wbuf comes from a plain kmalloc() and is never zeroed, so a slot used for the first time holds uninitialised heap data.

Advance j_fc_off only after the buffer head has been stored. That restores the invariant that j_fc_off covers exactly the filled slots, which is what jbd2_fc_release_bufs() relies on: the live buffers of the current fast commit sit above the NULLs the previous one released, so stopping at the first NULL is correct.

Reproduced on a KASAN kernel with an ext4 fast_commit filesystem on a loop device, truncating the backing file under the live mount so that only the journal's fast-commit region falls past the end of the device. __getblk() then fails for the first fast-commit block while the rest of the journal is still addressable, so the journal is not aborted and the fast commit reaches the fallback path. j_fc_wbuf was poisoned to make the read of the never-written slot visible:

  BUG: KASAN: wild-memory-access in jbd2_fc_release_bufs+0x6b/0xd0
  Write of size 4 at addr 5a5a5a5a5a5a5ab2 by task sync/961
   jbd2_fc_release_bufs+0x6b/0xd0
   ext4_fc_cleanup+0x97/0x830
   __jbd2_fc_end_commit+0x37/0xc0
   ext4_fc_commit+0x524/0x560
   ext4_sync_file+0x3c4/0x4b0
   __x64_sys_fsync+0x20/0x30

With this patch the same run leaves j_fc_off at 0 across repeated __getblk() failures and completes cleanly.

---
 fs/jbd2/journal.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/jbd2/journal.c +1 -1
index fa0fb738db0c4..1184dbad43e57 100644
@@ -844,7 +844,6 @@ int jbd2_fc_get_buf(journal_t *journal, struct buffer_head **bh_out)
 
 	fc_off = journal->j_fc_off;
 	blocknr = journal->j_fc_first + fc_off;
-	journal->j_fc_off++;
 	ret = jbd2_journal_bmap(journal, blocknr, &pblock);
 	if (ret)
 		return ret;
@@ -854,6 +853,7 @@ int jbd2_fc_get_buf(journal_t *journal, struct buffer_head **bh_out)
 		return -ENOMEM;
 
 	journal->j_fc_wbuf[fc_off] = bh;
+	journal->j_fc_off++;
 
 	*bh_out = bh;
 
Signature · 1 line
2.53.0
author maintainer
#421 lore raw

PATCH 420/869 ext4: skip extra isize expansion while unmounting

In reply to Greg Kroah-Hartman

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

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

From: Hemanth Selam <[email protected]>

[ Upstream commit 418adcde99032194416248168df810535a1a93f9 ]

syzbot reports a WARN from ext4_xattr_inode_create() reached through the unmount path:

EXT4-fs warning (device loop0): ext4_xattr_inode_create:1485: refuse to create EA inode when umounting

  WARNING: fs/ext4/xattr.c:1486 at ext4_xattr_inode_lookup_create
   ext4_xattr_block_set
   ext4_expand_extra_isize_ea
   __ext4_expand_extra_isize
   __ext4_mark_inode_dirty
   ext4_dirty_inode
   __mark_inode_dirty
   sync_lazytime
   iput
   dentry_kill
   shrink_dentry_list
   shrink_dcache_for_umount
   generic_shutdown_super
   kill_block_super
   ext4_kill_sb

shrink_dcache_for_umount() clears s_root before generic_shutdown_super() clears SB_ACTIVE, so during the dcache shrink the last iput() of a lazytime inode still redirties it and reaches the isize expansion. The expansion can move xattrs out to a block, and creating the EA inode for them needs s_root, which ext4_xattr_inode_create() refuses without.

ext4_try_to_expand_extra_isize() already declines to expand when the superblock is not active, but that test does not cover this window. Decline while s_root is gone as well. The expansion is best effort and __ext4_mark_inode_dirty() ignores its return value, so nothing else changes; the inode can be expanded on a later mount.

Running the syzbot reproducer for 60 seconds produced 3583 splats before this change and none after it, with the same number of mount cycles.

---
 fs/ext4/inode.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
fs/ext4/inode.c +7 -1
index ed51c11f43ffb..47ce682ae17fa 100644
@@ -6479,8 +6479,14 @@ static int ext4_try_to_expand_extra_isize(struct inode *inode,
 	 * When !SB_ACTIVE, iput triggers write_inode_now() which acquires
 	 * s_writepages_rwsem, causing a deadlock with the caller's active
 	 * jbd2 handle (lock order: s_writepages_rwsem -> jbd2_handle).
+	 *
+	 * Skip it while unmounting as well.  shrink_dcache_for_umount()
+	 * clears s_root before generic_shutdown_super() clears SB_ACTIVE, and
+	 * the last iput() of a lazytime inode in that window redirties it and
+	 * lands here.  Moving xattrs out to a block then needs a new EA inode,
+	 * which ext4_xattr_inode_create() refuses without s_root.
 	 */
-	if (unlikely(!(inode->i_sb->s_flags & SB_ACTIVE)))
+	if (unlikely(!(inode->i_sb->s_flags & SB_ACTIVE) || !inode->i_sb->s_root))
 		return -EBUSY;
 
 	/*
Signature · 1 line
2.53.0
author maintainer
#422 lore raw

PATCH 421/869 ext4: dont report delalloc data as a hole on indirect-mapped inodes

In reply to Greg Kroah-Hartman

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

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

From: Daejun Park <[email protected]>

[ Upstream commit aed43f47e1edeee1454eea86006a8c09480e5ed3 ]

When a plain lookup finds no block, ext4_ind_map_blocks() sizes the hole it reports by counting the empty subtrees under 'partial' in the on-disk indirect tree. That count knows nothing about delayed allocation, so a range holding delalloc data that has not been written back yet is reported as a plain hole. The extent-mapped path does not have this
problem: it trims the hole it found at the first delayed extent before returning it.

ext4_map_blocks() consults the extent status tree before it calls into the mapping layer, so a query that starts exactly on the delayed block still finds it. A query that starts earlier does not, because the hole reported for the earlier block already spans the delayed one. On a 4k-block filesystem, lseek(SEEK_DATA) from offset 0 on a file whose only data block is at logical block N and is still dirty returns:

  N = 0..11      direct blocks                 N << 12
  N = 12         first single-indirect block   N << 12
  N = 13..1035   inside that indirect block    -1 ENXIO
  N = 1036       first double-indirect block   N << 12

Blocks 12 and 1036 survive because the query lands on the delayed block itself. Blocks 13..1035 are swallowed by the 1024-block hole reported for block 12. fiemap loses the same data for the same reason.

An ext3 filesystem mounted as ext4 hits this during ordinary use: ext3 inodes stay indirect mapped, while mount -t ext4 turns on delayed allocation even though mounting ext3 with -o delalloc is explicitly rejected. install(1) from coreutils uses SEEK_DATA to locate data in its source file, so installing a sparse file that has not been written back silently produces a destination of the right size holding none of the data:

  truncate -s 1G img && mkfs.ext3 -F img && mount -t ext4 img mnt
  echo | dd of=mnt/src bs=1 count=1 seek=64K
  install mnt/src mnt/dst
  cmp mnt/src mnt/dst        # differ: char 65537

Reconciling a hole with the extent status tree does not depend on how the hole was found, so instead of open coding it a second time, split the delalloc handling out of ext4_ext_determine_insert_hole() into ext4_determine_insert_hole(), which takes the hole the caller located, and call that from ext4_ind_map_blocks() as well. All the special cases and the comments explaining them stay in one place.

Two things change for indirect-mapped inodes. They now cache the holes they report, as the extent-mapped path already does: ext4_punch_hole() already puts EXTENT_STATUS_HOLE on such inodes, ext4_map_blocks() and ext4_da_map_blocks() already handle a cached hole, the latter by replacing it with the delayed extent, and consecutive hole entries merge, so the tree does not grow with the length of a scan. And when a delayed extent covers the queried block itself - a race, since ext4_map_blocks() found nothing in the tree just before - the hole is now reported only up to the end of that extent instead of in full.

The indirect path passes hole_start == lblk, so the "delalloc extent in front of the queried range" case cannot be reached there:
__es_tree_search() never returns an extent ending before the block it was searched for.

With this the sweep above returns N << 12 for every N, while the nodelalloc and extent-mapped controls are unchanged. generic/225, generic/285, generic/448 and generic/490 pass on ext4 made both with and without the extent feature. generic/286 and generic/436 pass on extent-mapped ext4 and are skipped without it, since they need fallocate.

---
 fs/ext4/ext4.h     |  3 +++
 fs/ext4/extents.c  | 26 +++++++++++++-------------
 fs/ext4/indirect.c | 17 +++++++++++++++++
 3 files changed, 33 insertions(+), 13 deletions(-)
fs/ext4/ext4.h +3 -0
index ed546c52ebc32..9c67a2c28faf5 100644
@@ -3809,6 +3809,9 @@ extern void ext4_ext_tree_init(handle_t *handle, struct inode *inode);
 extern int ext4_ext_index_trans_blocks(struct inode *inode, int extents);
 extern int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
 			       struct ext4_map_blocks *map, int flags);
+ext4_lblk_t ext4_determine_insert_hole(struct inode *inode, ext4_lblk_t lblk,
+				       ext4_lblk_t hole_start,
+				       ext4_lblk_t hole_len);
 extern int ext4_ext_truncate(handle_t *, struct inode *);
 extern int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
 				 ext4_lblk_t end);
fs/ext4/extents.c +13 -13
index 21fba12520a8e..80d41be515644 100644
@@ -4160,21 +4160,19 @@ static int get_implied_cluster_alloc(struct super_block *sb,
 }
 
 /*
- * Determine hole length around the given logical block, first try to
- * locate and expand the hole from the given @path, and then adjust it
- * if it's partially or completely converted to delayed extents, insert
- * it into the extent cache tree if it's indeed a hole, finally return
- * the length of the determined extent.
+ * Adjust the hole [@hole_start, @hole_start + @hole_len) the caller found
+ * around the queried block @lblk if it's partially or completely converted
+ * to delayed extents, insert it into the extent cache tree if it's indeed a
+ * hole, finally return the length of the determined extent starting at
+ * @lblk.  @hole_start must not be behind @lblk.
  */
-static ext4_lblk_t ext4_ext_determine_insert_hole(struct inode *inode,
-						  struct ext4_ext_path *path,
-						  ext4_lblk_t lblk)
+ext4_lblk_t ext4_determine_insert_hole(struct inode *inode, ext4_lblk_t lblk,
+				       ext4_lblk_t hole_start,
+				       ext4_lblk_t hole_len)
 {
-	ext4_lblk_t hole_start, len;
+	ext4_lblk_t len = hole_len;
 	struct extent_status es;
 
-	hole_start = lblk;
-	len = ext4_ext_find_hole(inode, path, &hole_start);
 again:
 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
 				  hole_start + len - 1, &es);
@@ -4342,9 +4340,11 @@ int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
 	 * we couldn't try to create block if flags doesn't contain EXT4_GET_BLOCKS_CREATE
 	 */
 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
-		ext4_lblk_t len;
+		ext4_lblk_t hole_start = map->m_lblk, len;
 
-		len = ext4_ext_determine_insert_hole(inode, path, map->m_lblk);
+		len = ext4_ext_find_hole(inode, path, &hole_start);
+		len = ext4_determine_insert_hole(inode, map->m_lblk,
+						 hole_start, len);
 
 		map->m_pblk = 0;
 		map->m_len = min_t(unsigned int, map->m_len, len);
fs/ext4/indirect.c +17 -0
index da76353b3a575..50c567123b42d 100644
@@ -586,6 +586,23 @@ int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,
 		for (i = partial - chain + 1; i < depth; i++)
 			count = count * epb + (epb - offsets[i] - 1);
 		count++;
+
+		/*
+		 * The count knows nothing about delayed allocation, so let
+		 * the common helper reconcile it with the extent status
+		 * tree.  Only when the lookup really did find a hole:
+		 * ext4_get_branch() also returns a non-NULL partial when it
+		 * failed, and caching a hole for a range it could not read
+		 * would answer every later read from that cache instead of
+		 * retrying.  Clamp the count first, a subtree can be bigger
+		 * than the logical block space when the block size is large.
+		 */
+		if (!err) {
+			count = umin(count, EXT_MAX_BLOCKS - map->m_lblk);
+			count = ext4_determine_insert_hole(inode, map->m_lblk,
+							   map->m_lblk, count);
+		}
+
 		/* Fill in size of a hole we found */
 		map->m_pblk = 0;
 		map->m_len = umin(map->m_len, count);
Signature · 1 line
2.53.0
author maintainer
#423 lore raw

PATCH 422/869 ext4: fix ABBA deadlock in ext4_rmdir()

In reply to Greg Kroah-Hartman

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

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

From: Sergey Senozhatsky <[email protected]>

[ Upstream commit 19e16597f9baf1b5719a3a6c710486446f6808fd ]

We observe the following ABBA deadlock (casefolding enabled):

 INFO: task jbd2/dm-13-8:447 blocked for more than 720 seconds.
 task:jbd2/dm-13-8    state:D stack:0     pid:447   tgid:447   ppid:2
 Call Trace:
  <TASK>
  __schedule+0xc2c/0xe60
  schedule+0x40/0xe0
  jbd2_journal_wait_updates+0x8f/0xf0
  jbd2_journal_commit_transaction+0x321/0x1850
  kjournald2+0xa9/0x230
  kthread+0x226/0x2a0
  ret_from_fork+0x101/0x1e0
  ret_from_fork_asm+0x1a/0x30

 INFO: task Thread-10:4161 blocked for more than 720 seconds.
 task:Thread-10       state:D stack:0     pid:4161  tgid:3848  ppid:540
 Call Trace:
  <TASK>
  __schedule+0xc2c/0xe60
  schedule+0x40/0xe0
  wait_transaction_locked+0x8c/0xd0
  start_this_handle+0x252/0x870
  jbd2__journal_start+0x120/0x280
  __ext4_journal_start_sb+0x11a/0x250
  ext4_evict_inode+0x208/0x760
  iput+0x222/0x5c0
  dput+0x293/0x690
  ____fput+0x145/0x2b0
  task_work_run+0x7a/0xb0
  exit_to_user_mode_loop+0xc0/0xd0
  do_syscall_64+0x14b/0xf10
  entry_SYSCALL_64_after_hwframe+0x76/0x7e

NMI backtrace for cpu 0

 CPU: 0 UID: 1010216 PID: 4160 Comm: Thread-7
 RIP: 0010:d_walk+0x0/0x290
[..]
 Call Trace:
 <TASK>
  shrink_dcache_parent+0xb2/0x100
  d_invalidate+0x50/0x110
  ext4_rmdir+0x3a2/0x3d0
  vfs_rmdir+0x9d/0x1d0
  do_rmdir+0xf0/0x330
  __x64_sys_unlinkat+0x34/0x50
  do_syscall_64+0x61/0xf10

The problem is that ext4_rmdir() calls d_invalidate() before stopping the jbd2 transaction handle. Because d_invalidate() traverses child dentries it can encounter dying or in-use dentries. If a concurrent thread executing __dentry_kill() on a child dentry invokes ext4_evict_inode(), it requests a new transaction handle via ext4_journal_start(), which waits for all running handles to close. However, the thread executing ext4_rmdir() still holds its active transaction handle while looping in shrink_dcache_parent() waiting for the dying child dentry to complete eviction.

Stop transaction handle in ext4_rmdir() before calling d_invalidate().

---
 fs/ext4/namei.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
fs/ext4/namei.c +6 -5
index 2c661155158f8..49bd70aab2255 100644
@@ -3204,19 +3204,20 @@ static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
 	ext4_fc_track_unlink(handle, dentry);
 	retval = ext4_mark_inode_dirty(handle, dir);
 
+end_rmdir:
+	brelse(bh);
+	if (handle)
+		ext4_journal_stop(handle);
+
 	/* VFS negative dentries are incompatible with Encoding and
 	 * Case-insensitiveness. Eventually we'll want avoid
 	 * invalidating the dentries here, alongside with returning the
 	 * negative dentries at ext4_lookup(), when it is better
 	 * supported by the VFS for the CI case.
 	 */
-	if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir))
+	if (!retval && IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir))
 		d_invalidate(dentry);
 
-end_rmdir:
-	brelse(bh);
-	if (handle)
-		ext4_journal_stop(handle);
 	return retval;
 }
 
Signature · 1 line
2.53.0
author maintainer
#424 lore raw

PATCH 423/869 ext4: fix out-of-bounds read in ext4_get_group_info()

In reply to Greg Kroah-Hartman

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

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

From: Jinjie Ruan <[email protected]>

[ Upstream commit b067d3c1f90b536e9aa9f48b19580475a0b34f0f ]

A plain read of s_groups_count in ext4_get_group_info() allows CPU load-load reordering. On weak memory models, speculative prefetch of s_group_info prior to the boundary check could lead to an out-of-bounds read if a concurrent online resize expands the array and increments s_groups_count.

The data race occurs between the ioctl configuration path (holding the resize lock via ext4_resize_begin) and the lockless metadata lookup path:

CPU 0 (Writer, Resize Lock) CPU 1 (Reader, Lockless)
--------------------------- ------------------------
ext4_ioctl()

     [EXT4_IOC_GROUP_ADD]
     ext4_ioctl_group_add()
       ext4_resize_begin() // Takes lock
       ext4_group_add()
         ext4_mb_alloc_groupinfo()
           // Publishes expanded array via RCU
           rcu_assign_pointer(s_group_info, ...)

         ext4_flex_group_add()
           ext4_update_super()
                                              ext4_get_group_info()
                                                // Speculative / out-of-order read
                                                [Loads old/smaller s_group_info pointer]
             [Plain C store / smp_wmb()]
             sbi->s_groups_count += ...;
                                                // Reads new s_groups_count,
                                                // boundary check passes
                                                if (group >= s_groups_count)

                                                // Out-of-bounds array access!
                                                sbi_array_rcu_deref(..., s_group_info)

Fix this by using ext4_get_groups_count() to enforce acquire semantics.

---
 fs/ext4/balloc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ext4/balloc.c +1 -1
index 08556dd45760d..b7d59eec7b3f6 100644
@@ -329,7 +329,7 @@ struct ext4_group_info *ext4_get_group_info(struct super_block *sb,
 	struct ext4_group_info **grp_info;
 	long indexv, indexh;
 
-	if (unlikely(group >= EXT4_SB(sb)->s_groups_count))
+	if (unlikely(group >= ext4_get_groups_count(sb)))
 		return NULL;
 	if (unlikely(!EXT4_SB(sb)->s_group_info))
 		return NULL;
Signature · 1 line
2.53.0
author maintainer
#425 lore raw

PATCH 424/869 nilfs2: validate directory position after llseek in readdir

In reply to Greg Kroah-Hartman

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

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

From: Jake Labelle <[email protected]>

[ Upstream commit de7f49c12566cc5c7437a2f26c6c754b9d4d5648 ]

nilfs_readdir() uses ctx->pos, which userspace can set to an arbitrary value via llseek, as an offset into the directory folio and parses whatever bytes sit there as a directory entry. A position pointing into the middle of an entry -- or at unused bytes of a corrupted image that the page validator never inspected -- makes dir_emit() copy up to 255 (name_len) bytes from a bogus entry, possibly reading past the end of the folio and returning unrelated memory contents to userspace.

Snap unaligned positions onto a valid entry boundary by walking the rec_len chain from the chunk start before parsing, as ext2 does in ext2_validate_entry().

[ryusuke: fixed offset wrap-around in nilfs_validate_entry() and
conformed AI tag to guidelines]

Fixes 2ba466d74ed7 ("nilfs2: directory entry operations")
Assisted-by Claude:claude-mythos-5
---
 fs/nilfs2/dir.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
fs/nilfs2/dir.c +34 -0
index 6ca3d74be1e16..3e137c9ca1382 100644
@@ -231,11 +231,27 @@ static struct nilfs_dir_entry *nilfs_next_entry(struct nilfs_dir_entry *p)
 					  nilfs_rec_len_from_disk(p->rec_len));
 }
 
+static inline unsigned int
+nilfs_validate_entry(char *base, unsigned int offset, unsigned int mask)
+{
+	struct nilfs_dir_entry *de = (struct nilfs_dir_entry *)(base + offset);
+	struct nilfs_dir_entry *p =
+		(struct nilfs_dir_entry *)(base + (offset & mask));
+
+	while ((char *)p < (char *)de) {
+		if (p->rec_len == 0)
+			break;
+		p = nilfs_next_entry(p);
+	}
+	return (char *)p - base;
+}
+
 static int nilfs_readdir(struct file *file, struct dir_context *ctx)
 {
 	loff_t pos = ctx->pos;
 	struct inode *inode = file_inode(file);
 	struct super_block *sb = inode->i_sb;
+	unsigned int chunk_size = nilfs_chunk_size(inode);
 	unsigned int offset = pos & ~PAGE_MASK;
 	unsigned long n = pos >> PAGE_SHIFT;
 	unsigned long npages = dir_pages(inode);
@@ -254,6 +270,24 @@ static int nilfs_readdir(struct file *file, struct dir_context *ctx)
 			ctx->pos += PAGE_SIZE - offset;
 			return -EIO;
 		}
+		/*
+		 * ctx->pos comes from userspace via llseek and may point
+		 * into the middle of an entry -- or at unvalidated bytes
+		 * of a crafted image. offset is only nonzero here on the
+		 * very first iteration (subsequent pages always start at
+		 * offset 0, which -- like any chunk boundary -- is always
+		 * a legitimate entry start, since no rec_len chain crosses
+		 * a chunk boundary). Snap a non-chunk-aligned offset onto
+		 * a real entry boundary by walking the chain from the
+		 * enclosing chunk's start, as ext2 does; otherwise
+		 * dir_emit() copies name_len bytes from a fake entry,
+		 * reading past the end of the folio.
+		 */
+		if (offset & (chunk_size - 1)) {
+			offset = nilfs_validate_entry(kaddr, offset,
+					~(chunk_size - 1));
+			ctx->pos = ((loff_t)n << PAGE_SHIFT) + offset;
+		}
 		de = (struct nilfs_dir_entry *)(kaddr + offset);
 		limit = kaddr + nilfs_last_byte(inode, n) -
 			NILFS_DIR_REC_LEN(1);
Signature · 1 line
2.53.0
author maintainer
#426 lore raw

PATCH 425/869 md: dont hand out the array before md_alloc() has added mddev->kobj

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit d1472ca2ca5de8ecd2b358411eb14c031404ecf0 ]

md_alloc() publishes the gendisk before it is done setting the mddev up:

	disk->private_data = mddev;
	...
	error = add_disk(disk);
	if (error)
		goto out_put_disk;

	kobject_init(&mddev->kobj, &md_ktype);
	error = kobject_add(&mddev->kobj, &disk_to_dev(disk)->kobj, "%s", "md");

add_disk() makes /dev/mdN openable. mddev comes from mddev_alloc() and is zeroed, so anything that gets in between add_disk() and kobject_add() sees an mddev->kobj that has never been through kobject_init() - no ktype, no kref, state_initialized clear.

syzbot opens the array in that window and issues ADD_NEW_DISK:

kobject: '(null)' (ffff8880120640f0): is not initialized, yet kobject_get() is being called.

  WARNING: lib/kobject.c:642 at kobject_add_internal+0xea/0xcd0 lib/kobject.c:225
   kobject_add_varg lib/kobject.c:374 [inline]
   kobject_add+0x163/0x240 lib/kobject.c:426
   bind_rdev_to_array+0x80c/0xdd0 drivers/md/md.c:2621
   md_add_new_disk+0xe3b/0x1850 drivers/md/md.c:7684
   md_ioctl+0x200a/0x2610 drivers/md/md.c:8499

bind_rdev_to_array() is not the only way in. md_run() calls sysfs_create_group(&mddev->kobj, &md_redundancy_group), and internal_create_group() has its own WARN_ON(!kobj->sd), so RUN_ARRAY in the same window warns too.

Every ioctl that can reach mddev->kobj runs under reconfig_mutex, so hold it across add_disk() and kobject_add(). An ioctl issued in the window now waits for md_alloc() to finish instead of seeing a half-built mddev, and opening the array still succeeds. The ioctls md_ioctl() serves without the mutex only read array state and return -ENODEV on an array with no disks.

Hoisting kobject_init() above add_disk() is not an option: commit ca39f7502425 ("md: fix mddev->kobj lifetime") moved it below add_disk() so that md_alloc()'s error paths, which free the mddev directly, never see an initialised kobject.

---
 drivers/md/md.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
drivers/md/md.c +11 -1
index 8d9e111939f64..937a2f4da84ba 100644
@@ -6258,12 +6258,22 @@ struct mddev *md_alloc(dev_t dev, char *name)
 
 	disk->events |= DISK_EVENT_MEDIA_CHANGE;
 	mddev->gendisk = disk;
+
+	/*
+	 * add_disk() makes the array openable before mddev->kobj exists.
+	 * Hold reconfig_mutex until kobject_add() is done so that ioctls
+	 * issued in between wait instead of using an uninitialised kobj.
+	 */
+	mddev_lock_nointr(mddev);
 	error = add_disk(disk);
-	if (error)
+	if (error) {
+		mddev_unlock(mddev);
 		goto out_put_disk;
+	}
 
 	kobject_init(&mddev->kobj, &md_ktype);
 	error = kobject_add(&mddev->kobj, &disk_to_dev(disk)->kobj, "%s", "md");
+	mddev_unlock(mddev);
 	if (error) {
 		/*
 		 * The disk is already live at this point.  Clear the hold flag
Signature · 1 line
2.53.0
author maintainer
#427 lore raw

PATCH 426/869 mm/memory: constrain generic_access_phys() to page boundary

In reply to Greg Kroah-Hartman

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

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

From: Luxiao Xu <[email protected]>

[ Upstream commit ae0298a5fbeff32951c0d31398ccec97ec6aa0ea ]

This patch addresses an issue in generic_access_phys() where accessing memory across page boundaries in PFNMAP VMAs assumes physical pages are contiguous, which can lead to accessing unintended physical memory or exceeding VMA boundaries.

generic_access_phys() improperly validates the memory access range: it only validates the start address using follow_pfnmap_start() and passes PAGE_ALIGN(len + offset) to ioremap_prot().

This poses two problems:
1. In PFNMAP VMAs, consecutive virtual pages are not guaranteed to be physically contiguous, and individual PTEs may have different access permissions or writability.
2. The mapping may cross VMA boundaries if len extends beyond vma->vm_end.

Constrain the access in generic_access_phys() to at most the current page boundary (PAGE_SIZE - offset) and map only a single PAGE_SIZE via ioremap_prot(). Since the caller __access_remote_vm() already loops over the requested length and handles partial transfers, it will naturally iterate over the remaining pages.

Also add a missing (resource_size_t) cast during PFN re-validation to avoid truncation on 32-bit PAE systems.

Fixes 9cb12d7b4cca ("mm/memory.c: actually remap enough memory")
Assisted-by LLM
Cc Grazvydas Ignotas <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
---
 mm/memory.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
mm/memory.c +8 -2
index 72793ec631072..d755b5c1f1287 100644
@@ -6813,6 +6813,12 @@ int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
 	bool writable;
 	struct follow_pfnmap_args args = { .vma = vma, .address = addr };
 
+	/*
+	 * Limit access to one page at a time, as that's what follow_pfnmap_start()
+	 * guarantees; expect the caller to retry to read larger ranges.
+	 */
+	len = min_t(int, len, PAGE_SIZE - offset);
+
 retry:
 	if (follow_pfnmap_start(&args))
 		return -EINVAL;
@@ -6824,7 +6830,7 @@ int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
 	if ((write & FOLL_WRITE) && !writable)
 		return -EINVAL;
 
-	maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
+	maddr = ioremap_prot(phys_addr, PAGE_SIZE, prot);
 	if (!maddr)
 		return -ENOMEM;
 
@@ -6832,7 +6838,7 @@ int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
 		goto out_unmap;
 
 	if ((pgprot_val(prot) != pgprot_val(args.pgprot)) ||
-	    (phys_addr != (args.pfn << PAGE_SHIFT)) ||
+	    (phys_addr != ((resource_size_t)args.pfn << PAGE_SHIFT)) ||
 	    (writable != args.writable)) {
 		follow_pfnmap_end(&args);
 		iounmap(maddr);
Signature · 1 line
2.53.0
author maintainer
#428 lore raw

PATCH 427/869 mm/execmem: free ROX cache chunks only when they span an entire vm area

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 52d95a55a0113408acd2d4ce0294a72c527f5092 ]

Patch series "mm/execmem: fixes and cleanups for the ROX cache".

Sashiko review of the ROX cache refill path asked what happens when the PMD_SIZE allocation fails there. Pulling that thread uncovered a bit more than the fallback.

Patch 1 fixes a real bug, although rare bug: execmem_cache_clean() can free a chunk that is still partially in use, because a PMD sized and PMD aligned free range in the middle of a larger chunk looks exactly like a chunk that nobody uses.

Patch 2 handles maple tree allocation failures in the cache. They are unlikely, but silently dropping an area from the tree is not a great way to deal with them.

Patch 3 deals with the fallback that started all this. The cache exists to keep the direct map free of unnecessary splits, and the fallback happily filled it with base page mapped areas that could never be freed from the cache again. Ask vmalloc for a huge mapping or nothing, and serve whatever does not fit outside the cache.

Patches 4 and 5 convert the ROX cache to scope based cleanup.

The series was tested on x86 with module load/unload cycles, with PTDUMP confirming that the cache is using 2M mappings, and with nohugevmalloc to exercise the uncached fallback.

This patch (of 5):

When execmem refills the ROX cache, it vmalloc()s multiples of PMD_SIZE aligned to PMD_SIZE. For every such allocation vmalloc creates a vm area.

The first part of the vmalloc()ed chunk is returned to the allocation that triggered the cache refill and the remaining part is added to the cache and handed out for subsequent allocations with execmem_alloc().

When only the first part is freed, the entire vm area remains in the ROX cache and can be handed out again.

In the case when the first allocation is larger than PMD_SIZE and the second allocation from the freed first part of the chunk is exactly PMD_SIZE, execmem_cache_clean() will free the entire chunk while part of it is still in use.

For example:

	/*
	 * vmalloc(4M), return p0 to the caller
	 * add [p0 + 3M, p0 + 4M) to the cache
	 */
	p0 = execmem_alloc(3M);

	/* return p0 + 3M from the cache to the caller */
	p1 = execmem_alloc(1M);

	/* put [p0, p0 + 3M) back into the cache */
	execmem_free(p0);

	/* return p0 from the cache to the caller */
	p2 = execmem_alloc(2M);

	/* return p0 + 2M from the cache to the caller */
	p3 = execmem_alloc(1M);

	/* bah! execmem_cache_clean() frees the entire 4M chunk */
	execmem_free(p2);

Make sure that the ranges that execmem_cache_clean() frees cover the entire vm area.

Fixes 2e45474ab14f ("execmem: add support for cache of large ROX pages")
Assisted-by copilot:claude-opus-5
Cc Benjamin Tissoires <[email protected]>
Cc Jiri Kosina <[email protected]>
Cc Luis Chamberalin <[email protected]>
Cc "Uladzislau Rezki (Sony)" <[email protected]>
---
 mm/execmem.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/execmem.c +3 -1
index 084a207e4278b..9560441e57ab1 100644
@@ -164,9 +164,11 @@ static void execmem_cache_clean(struct work_struct *work)
 
 	mutex_lock(mutex);
 	mas_for_each(&mas, area, ULONG_MAX) {
+		struct vm_struct *vm = find_vm_area(area);
 		size_t size = mas_range_len(&mas);
 
-		if (IS_ALIGNED(size, PMD_SIZE) &&
+		if (vm && get_vm_area_size(vm) == size &&
+		    IS_ALIGNED(size, PMD_SIZE) &&
 		    IS_ALIGNED(mas.index, PMD_SIZE)) {
 			struct vm_struct *vm = find_vm_area(area);
 
Signature · 1 line
2.53.0
author maintainer
#429 lore raw

PATCH 428/869 mm/nommu: reject wrapping ranges in access_remote_vm()

In reply to Greg Kroah-Hartman

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

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

From: Anastasios Papagiannis <[email protected]>

[ Upstream commit 51a8de81fd2edbf87d8046e352060329bb216fad ]

The NOMMU implementation of access_process_vm() rejects address ranges whose end wraps around, but access_remote_vm() bypasses this check even though both functions delegate to __access_remote_vm().

Move the wraparound check into __access_remote_vm() so it applies to both entry points.

This is originally reported in [1].

---
 mm/nommu.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
mm/nommu.c +3 -3
index c3a23b082adb9..d609ecdcf022b 100644
@@ -1644,6 +1644,9 @@ static int __access_remote_vm(struct mm_struct *mm, unsigned long addr,
 	struct vm_area_struct *vma;
 	int write = gup_flags & FOLL_WRITE;
 
+	if (addr + len < addr)
+		return 0;
+
 	if (mmap_read_lock_killable(mm))
 		return 0;
 
@@ -1697,9 +1700,6 @@ int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, in
 {
 	struct mm_struct *mm;
 
-	if (addr + len < addr)
-		return 0;
-
 	mm = get_task_mm(tsk);
 	if (!mm)
 		return 0;
Signature · 1 line
2.53.0
author maintainer
#430 lore raw

PATCH 429/869 mm/hugetlb: fix subpool minimum reservation rollback

In reply to Greg Kroah-Hartman

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

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

From: Jinmeng Zhou <[email protected]>

[ Upstream commit e4949a80f3b07e52dca76c34ce353633927a28a5 ]

When a reservation request is partially covered by a subpool minimum and the remaining global reservation fails, the error path first calls hugepage_subpool_put_pages() for the subpool-backed portion. It removes the failed global portion from used_hpages only afterwards.

hugepage_subpool_put_pages() uses used_hpages to decide whether rsv_hpages should be restored. Since used_hpages still includes the global portion, it can remain at or above min_hpages and prevent that restoration. It then reports the subpool reservation as releasable, causing hugetlb_acct_memory() to incorrectly decrement h->resv_huge_pages.

This was reproduced with four 2 MB huge pages and a hugetlbfs mount with size=10M,min_size=8M. After a successful three-page reservation, a two-page reservation which needed one subpool page and one global page failed with -ENOMEM. HugePages_Rsvd incorrectly dropped from four to three even though the subpool minimum was still four pages.

Roll back the failed global portion from used_hpages first, so that hugepage_subpool_put_pages() evaluates the minimum reservation against the current usage and returns the correct global adjustment.

Fixes a833a693a490 ("mm: hugetlb: fix incorrect fallback for subpool")
Cc David Hildenbrand <[email protected]>
Cc Ma Wupeng <[email protected]>
Cc Oscar Salvador <[email protected]>
---
 mm/hugetlb.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)
mm/hugetlb.c +9 -9
index ebc78406335b3..8832923dfbcd8 100644
@@ -7427,15 +7427,6 @@ long hugetlb_reserve_pages(struct inode *inode,
 
 out_put_pages:
 	spool_resv = chg - gbl_reserve;
-	if (spool_resv) {
-		/* put sub pool's reservation back, chg - gbl_reserve */
-		gbl_resv = hugepage_subpool_put_pages(spool, spool_resv);
-		/*
-		 * subpool's reserved pages can not be put back due to race,
-		 * return to hstate.
-		 */
-		hugetlb_acct_memory(h, -gbl_resv);
-	}
 	/* Restore used_hpages for pages that failed global reservation */
 	if (gbl_reserve && spool) {
 		unsigned long flags;
@@ -7445,6 +7436,15 @@ long hugetlb_reserve_pages(struct inode *inode,
 			spool->used_hpages -= gbl_reserve;
 		unlock_or_release_subpool(spool, flags);
 	}
+	if (spool_resv) {
+		/* put sub pool's reservation back, chg - gbl_reserve */
+		gbl_resv = hugepage_subpool_put_pages(spool, spool_resv);
+		/*
+		 * subpool's reserved pages can not be put back due to race,
+		 * return to hstate.
+		 */
+		hugetlb_acct_memory(h, -gbl_resv);
+	}
 out_uncharge_cgroup:
 	hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
 					    chg * pages_per_huge_page(h), h_cg);
Signature · 1 line
2.53.0
author maintainer
#431 lore raw

PATCH 430/869 mm/zswap: publish the initial pool with list_add_rcu()

In reply to Greg Kroah-Hartman

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

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

From: Longlong Xia <[email protected]>

[ Upstream commit c1dd5e24a82d19bff8eef50ba8205d4776584aff ]

zswap_setup() publishes the pool on the zswap_pools list with a plain list_add(), but the list is walked by concurrent RCU readers holding nothing but rcu_read_lock() through zswap_total_pages(), e.g. /proc/meminfo and the shrinker count path.

    CPU 0 (writer)                          CPU 1 (reader)
    --------------                          --------------
    zswap_pool_create():
      pool->zs_pool = zs_create_pool(); (1)
    list_add() -> __list_add():
      WRITE_ONCE(zswap_pools.next,
          &pool->list);                (2)   zswap_total_pages():
                                                pool = READ_ONCE(     (a)
                                                    zswap_pools.next);
                                                zs_get_total_pages(   (b)
                                                    pool->zs_pool);

If (2) becomes visible to CPU 1 before (1), CPU 1 finds the pool at (a) but dereferences a wild pointer at (b). Publish the node with list_add_rcu().

---
 mm/zswap.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/zswap.c +1 -1
index 18249dd96ef86..e4b2f6abefafb 100644
@@ -1818,7 +1818,7 @@ static int zswap_setup(void)
 	pool = __zswap_pool_create_fallback();
 	if (pool) {
 		pr_info("loaded using pool %s\n", pool->tfm_name);
-		list_add(&pool->list, &zswap_pools);
+		list_add_rcu(&pool->list, &zswap_pools);
 		zswap_has_pool = true;
 		static_branch_enable(&zswap_ever_enabled);
 	} else {
Signature · 1 line
2.53.0
author maintainer
#432 lore raw

PATCH 431/869 mm/zswap: enable zswap_ever_enabled in zswap_pool_create()

In reply to Greg Kroah-Hartman

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

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

From: Longlong Xia <[email protected]>

[ Upstream commit 91b4edb993e1549afdc3c2495216734b9f13f00e ]

If zswap is enabled by default at boot and pool creation fails, then a pool is later created by updating the compressor, data written to zswap is corrupted on swapin.

Enable the static key in zswap_pool_create(), covering boot-time and runtime pool creation with a single site.

Verified with fault injection on a stock kernel (compressor builtin, CONFIG_ZSWAP_DEFAULT_ON=n):

1. Boot with zswap.enabled=1; pool creation fails, init completes pool-less (static key off).
2. Echo an available compressor name to zswap.compressor.
3. Enable zswap.
4. madvise(MADV_PAGEOUT) a pattern-verified 512 MiB region, then fault it back in and verify.

Step 4 reads back 131072/131072 zeroed pages (zswpin=0, zswpout=131072) without this patch; all pages intact (zswpin=131072) with it.

Fixes 2d4d2b1cfb85 ("mm: zswap: add zswap_never_enabled()")
Assisted-by Zcode:GLM-5.3
Cc Chengming Zhou <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Nhat Pham <[email protected]>
---
 mm/zswap.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/zswap.c +2 -1
index e4b2f6abefafb..d2e5f0cff71db 100644
@@ -288,6 +288,8 @@ static struct zswap_pool *zswap_pool_create(char *compressor)
 
 	zswap_pool_debug("created", pool);
 
+	static_branch_enable(&zswap_ever_enabled);
+
 	return pool;
 
 ref_fail:
@@ -1820,7 +1822,6 @@ static int zswap_setup(void)
 		pr_info("loaded using pool %s\n", pool->tfm_name);
 		list_add_rcu(&pool->list, &zswap_pools);
 		zswap_has_pool = true;
-		static_branch_enable(&zswap_ever_enabled);
 	} else {
 		pr_err("pool creation failed\n");
 		zswap_enabled = false;
Signature · 1 line
2.53.0
author maintainer
#433 lore raw

PATCH 432/869 clk: imx: Fix clock reference leak in imx_get_clk_hw_by_name()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 8e177ca735761a1f03e1dedffd7ab00d6d0540ae ]

imx_get_clk_hw_by_name() obtains a consumer clock with of_clk_get_by_name(), extracts the hardware pointer with __clk_get_hw() and returns it without ever calling clk_put(), leaking the consumer reference on both return paths.

Extract the hardware pointer first and drop the clock reference with clk_put() before returning.

Fixes 3b315214e091 ("clk: imx: implement new clk_hw based APIs")
---
 drivers/clk/imx/clk.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/clk/imx/clk.c +5 -1
index df83bd939492e..542b58ccf120b 100644
@@ -119,12 +119,16 @@ struct clk_hw *imx_obtain_fixed_of_clock(struct device_node *np,
 struct clk_hw *imx_get_clk_hw_by_name(struct device_node *np, const char *name)
 {
 	struct clk *clk;
+	struct clk_hw *hw;
 
 	clk = of_clk_get_by_name(np, name);
 	if (IS_ERR(clk))
 		return ERR_PTR(-ENOENT);
 
-	return __clk_get_hw(clk);
+	hw = __clk_get_hw(clk);
+	clk_put(clk);
+
+	return hw;
 }
 EXPORT_SYMBOL_GPL(imx_get_clk_hw_by_name);
 
Signature · 1 line
2.53.0
author maintainer
#434 lore raw

PATCH 433/869 clk: imx: Fix clock reference leak in imx_obtain_fixed_clock_hw()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 52d4d1b26a5bc64de95099d0a3dd8b90dba1f3a3 ]

imx_obtain_fixed_clock_hw() obtains the clock through imx_obtain_fixed_clock_from_dt(), which creates a consumer reference via of_clk_get_from_provider(). The reference is discarded right after __clk_get_hw() returns the hardware pointer, leaking it.

Keep the imx_clk_fixed() fallback unchanged and drop the DT-obtained consumer reference with clk_put() once the hardware pointer has been extracted.

Fixes a4a4069f4523 ("clk: imx: Add imx_obtain_fixed_clock clk_hw based variant")
---
 drivers/clk/imx/clk.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/clk/imx/clk.c +7 -2
index 542b58ccf120b..153e7405eae4d 100644
@@ -95,11 +95,16 @@ struct clk_hw *imx_obtain_fixed_clock_hw(
 			const char *name, unsigned long rate)
 {
 	struct clk *clk;
+	struct clk_hw *hw;
 
 	clk = imx_obtain_fixed_clock_from_dt(name);
 	if (IS_ERR(clk))
-		clk = imx_clk_fixed(name, rate);
-	return __clk_get_hw(clk);
+		return __clk_get_hw(imx_clk_fixed(name, rate));
+
+	hw = __clk_get_hw(clk);
+	clk_put(clk);
+
+	return hw;
 }
 
 struct clk_hw *imx_obtain_fixed_of_clock(struct device_node *np,
Signature · 1 line
2.53.0
author maintainer
#435 lore raw

PATCH 434/869 xen/gntdev: prevent private mappings from becoming writable

In reply to Greg Kroah-Hartman

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

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

From: Abdifatah Suruur <[email protected]>

[ Upstream commit 2176dea8d8c19cb43a9b3651bfa1cb21eab1b31a ]

gntdev_mmap() rejects writable private (non-shared) mappings of foreign grant pages, because a private writable mapping takes the COW path on pages that have no proper struct-page backing. However, VM_MAYWRITE is left set, so userspace can map the grant read-only and then upgrade the mapping to writable with mprotect(), hitting the same COW path the check was written to prevent.

Clear VM_MAYWRITE for private mappings, as i915 does for its read-only objects and as fixed in drm/vc4 (CVE-2026-68445) and drm/panthor (CVE-2024-53071) and ptp: vmclock (commit a5edadbae57e2298a56cf7a4e774a027905a331f).

Fixes ab31523c2fcac ("xen/gntdev: allow usermode to map granted pages")

Message-ID: <[email protected]>

---
 drivers/xen/gntdev.c | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/xen/gntdev.c +7 -0
index 1e21b75114e5e..02ebbdba86101 100644
@@ -1072,6 +1072,13 @@ static int gntdev_mmap(struct file *flip, struct vm_area_struct *vma)
 	if ((vma->vm_flags & VM_WRITE) && !(vma->vm_flags & VM_SHARED))
 		return -EINVAL;
 
+	/*
+	 * Private mappings of foreign grant pages must never become
+	 * writable: they would take the COW path on granted pages.
+	 */
+	if (!(vma->vm_flags & VM_SHARED))
+		vm_flags_clear(vma, VM_MAYWRITE);
+
 	pr_debug("map %d+%d at %lx (pgoff %lx)\n",
 		 index, count, vma->vm_start, vma->vm_pgoff);
 
Signature · 1 line
2.53.0
author maintainer
#436 lore raw

PATCH 435/869 soc: fsl: cpm1: tsa: Fix clock leak in tsa_of_parse_tdms()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 46201d760c48e771fa2febfcb0787f22c3b71387 ]

The error cleanup loop puts l1rsync_clk and l1rclk_clk a second time and never puts l1tsync_clk or l1tclk_clk, because the branches that guard the transmit clocks use the receive clock field names.

Use the matching field in each branch so every clock acquired by tsa_of_parse_tdms() is released exactly once.

Fixes 1d4ba0b81c1c ("soc: fsl: cpm1: Add support for TSA")
[chleroy: Fixed the same in tsa_remove()]
---
 drivers/soc/fsl/qe/tsa.c | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)
drivers/soc/fsl/qe/tsa.c +8 -8
index 4a88e54d25b94..502e2ffe86898 100644
@@ -865,12 +865,12 @@ static int tsa_of_parse_tdms(struct tsa *tsa, struct device_node *np)
 			clk_put(tsa->tdm[i].l1rclk_clk);
 		}
 		if (tsa->tdm[i].l1tsync_clk) {
-			clk_disable_unprepare(tsa->tdm[i].l1rsync_clk);
-			clk_put(tsa->tdm[i].l1rsync_clk);
+			clk_disable_unprepare(tsa->tdm[i].l1tsync_clk);
+			clk_put(tsa->tdm[i].l1tsync_clk);
 		}
 		if (tsa->tdm[i].l1tclk_clk) {
-			clk_disable_unprepare(tsa->tdm[i].l1rclk_clk);
-			clk_put(tsa->tdm[i].l1rclk_clk);
+			clk_disable_unprepare(tsa->tdm[i].l1tclk_clk);
+			clk_put(tsa->tdm[i].l1tclk_clk);
 		}
 	}
 	return ret;
@@ -1039,12 +1039,12 @@ static void tsa_remove(struct platform_device *pdev)
 			clk_put(tsa->tdm[i].l1rclk_clk);
 		}
 		if (tsa->tdm[i].l1tsync_clk) {
-			clk_disable_unprepare(tsa->tdm[i].l1rsync_clk);
-			clk_put(tsa->tdm[i].l1rsync_clk);
+			clk_disable_unprepare(tsa->tdm[i].l1tsync_clk);
+			clk_put(tsa->tdm[i].l1tsync_clk);
 		}
 		if (tsa->tdm[i].l1tclk_clk) {
-			clk_disable_unprepare(tsa->tdm[i].l1rclk_clk);
-			clk_put(tsa->tdm[i].l1rclk_clk);
+			clk_disable_unprepare(tsa->tdm[i].l1tclk_clk);
+			clk_put(tsa->tdm[i].l1tclk_clk);
 		}
 	}
 }
Signature · 1 line
2.53.0
author maintainer
#437 lore raw

PATCH 436/869 soc: fsl: dpio: Fix cleanup on IRQ registration failure

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit 45ecea8c55521d424513178fb612cefffb09a9f5 ]

IRQ registration happens after dpaa2_io_create(), but its failure path only releases the IRQ resources and the MC portal. The I/O object stays allocated and published in the service list and per-CPU lookup table, while devres unmaps its portal registers after probe fails.

Call dpaa2_io_down() on IRQ registration failure to remove the object from those lookup structures and free it. Reorder the error labels so that a failed dpaa2_io_create() still skips this cleanup.

Remove unregister_dpio_irq_handlers() from the probe error path, since no IRQ handler or affinity hint has been installed when registration fails.

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

Fixes fe8fe7723a3a ("soc: fsl: dpio: register dpio irq handlers after dpio create")
Assisted-by LLM
---
 drivers/soc/fsl/dpio/dpio-driver.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/soc/fsl/dpio/dpio-driver.c +2 -2
index 9e3fddd8f5a91..7dc65f38d2fdb 100644
@@ -248,9 +248,9 @@ static int dpaa2_dpio_probe(struct fsl_mc_device *dpio_dev)
 
 	return 0;
 
-err_dpaa2_io_create:
-	unregister_dpio_irq_handlers(dpio_dev);
 err_register_dpio_irq:
+	dpaa2_io_down(priv->io);
+err_dpaa2_io_create:
 	fsl_mc_free_irqs(dpio_dev);
 err_allocate_irqs:
 	dpio_disable(dpio_dev->mc_io, 0, dpio_dev->mc_handle);
Signature · 1 line
2.53.0
author maintainer
#438 lore raw

PATCH 437/869 soc: fsl: dpio: Free the IRQ before releasing the I/O object

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit a7831c657c90e8f9165f6bbe0cc56262fee075e8 ]

The DPIO interrupt handler accesses priv->io, but dpaa2_dpio_remove() releases that object before tearing down the interrupts. The IRQ was requested with devm_request_irq(), and unregister_dpio_irq_handlers() only clears its affinity hint. fsl_mc_free_irqs() returns IRQ resources to the MC resource pool without freeing the handler. An interrupt can therefore access the freed I/O object before devres releases the IRQ.

Explicitly free the managed IRQ in unregister_dpio_irq_handlers() before returning its resource to the pool, and perform IRQ teardown before releasing the I/O object. This also waits for an in-flight handler while the object is still valid.

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

---
 drivers/soc/fsl/dpio/dpio-driver.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/soc/fsl/dpio/dpio-driver.c +3 -2
index 7dc65f38d2fdb..2962e66e2e413 100644
@@ -88,6 +88,7 @@ static void unregister_dpio_irq_handlers(struct fsl_mc_device *dpio_dev)
 
 	/* clear the affinity hint */
 	irq_set_affinity_hint(irq->virq, NULL);
+	devm_free_irq(&dpio_dev->dev, irq->virq, &dpio_dev->dev);
 }
 
 static int register_dpio_irq_handlers(struct fsl_mc_device *dpio_dev, int cpu)
@@ -280,10 +281,10 @@ static void dpaa2_dpio_remove(struct fsl_mc_device *dpio_dev)
 	priv = dev_get_drvdata(dev);
 	cpu = dpaa2_io_get_cpu(priv->io);
 
-	dpaa2_io_down(priv->io);
-
 	dpio_teardown_irqs(dpio_dev);
 
+	dpaa2_io_down(priv->io);
+
 	cpumask_set_cpu(cpu, cpus_unused_mask);
 
 	err = dpio_open(dpio_dev->mc_io, 0, dpio_dev->obj_desc.id,
Signature · 1 line
2.53.0
author maintainer
#439 lore raw

PATCH 438/869 xen/privcmd: Only claim ioreqs matching an ioeventfd

In reply to Greg Kroah-Hartman

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

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

From: Koichiro Den <[email protected]>

[ Upstream commit 908019e5999161ca89da310c05ddbf7fc89c129e ]

The ioeventfd handler shares its event channel with the userspace device model. It must only claim requests that match a registered ioeventfd. Other requests are left for userspace.

ioeventfd_interrupt() currently marks every MMIO write INPROCESS before looking for a match. For an unmatched request it drops the lock and restores READY. Userspace may see INPROCESS and skip it. Restoring READY does not send another notification. If userspace handles the request at the same time, the READY store may overwrite its state.

Find a matching ioeventfd before changing the request state.

The lock now protects only the ioeventfd list. Use explicit virt_*mb() barriers for the ioreq shared with Xen.

Fixes f0d7db7b3324 ("xen: privcmd: Add support for ioeventfd")

Message-ID: <[email protected]>

---
 drivers/xen/privcmd.c | 47 +++++++++++++++++--------------------------
 1 file changed, 18 insertions(+), 29 deletions(-)
drivers/xen/privcmd.c +18 -29
index f37d8d212c066..fc21473672d4b 100644
@@ -1168,51 +1168,40 @@ static irqreturn_t ioeventfd_interrupt(int irq, void *dev_id)
 	struct privcmd_kernel_ioreq *kioreq = port->kioreq;
 	struct ioreq *ioreq = &kioreq->ioreq[port->vcpu];
 	struct privcmd_kernel_ioeventfd *kioeventfd;
-	unsigned int state = STATE_IOREQ_READY;
+	bool matched = false;
 
-	if (ioreq->state != STATE_IOREQ_READY ||
-	    ioreq->type != IOREQ_TYPE_COPY || ioreq->dir != IOREQ_WRITE)
+	if (ioreq->state != STATE_IOREQ_READY)
 		return IRQ_NONE;
 
-	/*
-	 * We need a barrier, smp_mb(), here to ensure reads are finished before
-	 * `state` is updated. Since the lock implementation ensures that
-	 * appropriate barrier will be added anyway, we can avoid adding
-	 * explicit barrier here.
-	 *
-	 * Ideally we don't need to update `state` within the locks, but we do
-	 * that here to avoid adding explicit barrier.
-	 */
+	/* Xen publishes the request before changing its state to READY. */
+	virt_rmb();
 
-	spin_lock(&kioreq->lock);
-	ioreq->state = STATE_IOREQ_INPROCESS;
+	if (ioreq->type != IOREQ_TYPE_COPY || ioreq->dir != IOREQ_WRITE)
+		return IRQ_NONE;
 
+	spin_lock(&kioreq->lock);
 	list_for_each_entry(kioeventfd, &kioreq->ioeventfds, list) {
 		if (ioreq->addr == kioeventfd->addr + VIRTIO_MMIO_QUEUE_NOTIFY &&
 		    ioreq->size == kioeventfd->addr_len &&
 		    (ioreq->data & QUEUE_NOTIFY_VQ_MASK) == kioeventfd->vq) {
+			/* Finish reading the request before claiming it. */
+			virt_mb();
+			ioreq->state = STATE_IOREQ_INPROCESS;
 			eventfd_signal(kioeventfd->eventfd);
-			state = STATE_IORESP_READY;
+			matched = true;
 			break;
 		}
 	}
 	spin_unlock(&kioreq->lock);
 
-	/*
-	 * We need a barrier, smp_mb(), here to ensure writes are finished
-	 * before `state` is updated. Since the lock implementation ensures that
-	 * appropriate barrier will be added anyway, we can avoid adding
-	 * explicit barrier here.
-	 */
-
-	ioreq->state = state;
-
-	if (state == STATE_IORESP_READY) {
-		notify_remote_via_evtchn(port->port);
-		return IRQ_HANDLED;
-	}
+	if (!matched)
+		return IRQ_NONE;
 
-	return IRQ_NONE;
+	/* Publish the response only after signaling the eventfd. */
+	virt_wmb();
+	ioreq->state = STATE_IORESP_READY;
+	notify_remote_via_evtchn(port->port);
+	return IRQ_HANDLED;
 }
 
 static void ioreq_free(struct privcmd_kernel_ioreq *kioreq)
Signature · 1 line
2.53.0
author maintainer
#440 lore raw

PATCH 439/869 xen/pcifront: check that an AER callback exists before calling it

In reply to Greg Kroah-Hartman

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

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

From: Yehyeong Lee <[email protected]>

[ Upstream commit 3b4854b69ee70fffb2fa7acac09e715a7efcbae1 ]

pcifront_common_process() handles an AER request from the backend by dispatching on aer_op.cmd to the bound driver's PCI error handler. It only checks that err_handler and err_handler->error_detected are present, then for the mmio_enabled, slot_reset and resume commands it calls the corresponding callback unconditionally. Those three callbacks are optional -- the PCI core NULL-checks each of them individually before use -- and many drivers (for example igb, igc, ice and ixgbevf) install error_detected without all of them.

aer_op.cmd comes from the shared ring, so a malicious or buggy backend can send XEN_PCI_OP_aer_mmio (or _slotreset/_resume) for a device whose driver leaves that callback NULL and make the frontend call through a NULL pointer, crashing the guest.

Check each callback before calling it. When mmio_enabled or slot_reset is absent, return PCI_ERS_RESULT_RECOVERED so recovery proceeds, as the PCI core does for a missing callback; returning PCI_ERS_RESULT_NONE would instead make xen-pciback tear the guest domain down.

Fixes 956a9202cd12 ("xen-pcifront: Xen PCI frontend driver.")

Message-ID: <[email protected]>

---
 drivers/pci/xen-pcifront.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
drivers/pci/xen-pcifront.c +8 -3
index 11636634ae512..451476ce10ae9 100644
@@ -599,11 +599,16 @@ static pci_ers_result_t pcifront_common_process(int cmd,
 		case XEN_PCI_OP_aer_detected:
 			return pdrv->err_handler->error_detected(pcidev, state);
 		case XEN_PCI_OP_aer_mmio:
-			return pdrv->err_handler->mmio_enabled(pcidev);
+			if (pdrv->err_handler->mmio_enabled)
+				return pdrv->err_handler->mmio_enabled(pcidev);
+			return PCI_ERS_RESULT_RECOVERED;
 		case XEN_PCI_OP_aer_slotreset:
-			return pdrv->err_handler->slot_reset(pcidev);
+			if (pdrv->err_handler->slot_reset)
+				return pdrv->err_handler->slot_reset(pcidev);
+			return PCI_ERS_RESULT_RECOVERED;
 		case XEN_PCI_OP_aer_resume:
-			pdrv->err_handler->resume(pcidev);
+			if (pdrv->err_handler->resume)
+				pdrv->err_handler->resume(pcidev);
 			return PCI_ERS_RESULT_NONE;
 		default:
 			dev_err(&pdev->xdev->dev,
Signature · 1 line
2.53.0
author maintainer
#441 lore raw

PATCH 440/869 xen-pciback: Fix pcistub_device ref leak in pcistub_get_gsi_from_sbdf()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit cfaf31becde901f7a2376d36db628f8be0bc7283 ]

pcistub_get_gsi_from_sbdf() obtains the stub device with pcistub_device_find(), which returns it with its kref incremented, and returns psdev->gsi without dropping that reference again. The caller cannot release it either, so every lookup leaks one reference to the stub device.

Release the reference after reading gsi.

Fixes 2fae6bb7be32 ("xen/privcmd: Add new syscall to get gsi from dev")

Message-ID: <[email protected]>

---
 drivers/xen/xen-pciback/pci_stub.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/xen/xen-pciback/pci_stub.c +5 -2
index 7de2fa67743c6..b128ceeee21bc 100644
@@ -234,13 +234,16 @@ static int pcistub_get_gsi_from_sbdf(unsigned int sbdf)
 	int bus = PCI_BUS_NUM(sbdf);
 	int slot = PCI_SLOT(sbdf);
 	int func = PCI_FUNC(sbdf);
+	int gsi;
 
 	psdev = pcistub_device_find(domain, bus, slot, func);
-
 	if (!psdev)
 		return -ENODEV;
 
-	return psdev->gsi;
+	gsi = psdev->gsi;
+	pcistub_device_put(psdev);
+
+	return gsi;
 }
 #endif
 
Signature · 1 line
2.53.0
author maintainer
#442 lore raw

PATCH 441/869 iommu/dma: Catch scatterlist length overflows

In reply to Greg Kroah-Hartman

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

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

From: Krzysztof Karas <[email protected]>

[ Upstream commit 1c8f6308e557f32412e9d4678b3f029f47f6d9aa ]

It is possible, when a very large mapping uses only one scatterlist, that padding overflows scatterlist's length field. This results in:
1) silently wrapping the value
2) smaller than desired mappings produced by iommu_map_sg
3) leaving mapped bytes in memory (no iommu_unmap)

Address this issue by adding overflow detection for scatterlist length field.

Fixes 809eac54cdd6 ("iommu/dma: Implement scatterlist segment merging")
Assisted-by LLM
---
 drivers/iommu/dma-iommu.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
drivers/iommu/dma-iommu.c +19 -1
index 9da773ba550ba..aa9ebf2bc96ed 100644
@@ -1453,6 +1453,11 @@ int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
 		sg_dma_len(s) = s_length;
 		s->offset -= s_iova_off;
 		s_length = iova_align(iovad, s_length + s_iova_off);
+		if (overflows_type(s_length, s->length)) {
+			ret = -EOVERFLOW;
+
+			goto out_restore_sg;
+		}
 		s->length = s_length;
 
 		/*
@@ -1469,7 +1474,20 @@ int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
 		 *   time through here (i.e. before it has a meaningful value).
 		 */
 		if (pad_len && pad_len < s_length - 1) {
-			prev->length += pad_len;
+			unsigned int new_prev_len;
+
+			/*
+			 * For large mappings spanning multiple GBs we
+			 * may not be able to fit all needed padding into
+			 * sg->length.
+			 */
+			if (check_add_overflow(prev->length, pad_len, &new_prev_len)) {
+				ret = -EOVERFLOW;
+
+				goto out_restore_sg;
+			}
+
+			prev->length = new_prev_len;
 			iova_len += pad_len;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#443 lore raw

PATCH 442/869 drm/ttm: return an error when kmapping a BO without pages

In reply to Greg Kroah-Hartman

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

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

From: Jesse Zhang <[email protected]>

[ Upstream commit fd485d47437ba1700dd47205a63b9f389a00aa36 ]

ttm_tt objects for imported sg tables (ttm_bo_type_sg, set up by ttm_sg_tt_init() with TTM_TT_FLAG_EXTERNAL) only have DMA addresses and no pages array. ttm_bo_kmap() and ttm_bo_vmap() still dereference ttm->pages for them, so a driver that tries to CPU map such a BO oopses instead of getting an error:

  BUG: kernel NULL pointer dereference, address: 0000000000000000
  RIP: 0010:ttm_bo_kmap+0x26c/0x300 [ttm]
  Call Trace:
   amdgpu_bo_kmap+0x89/0xb0 [amdgpu]
   amdgpu_userq_fence_read_wptr+0x116/0x170 [amdgpu]
   amdgpu_userq_signal_ioctl+0x3fe/0xbb0 [amdgpu]

Return -EINVAL in that case, like ttm_bo_kmap_try_from_panic() already checks for a missing pages array.

---
 drivers/gpu/drm/ttm/ttm_bo_util.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/gpu/drm/ttm/ttm_bo_util.c +9 -2
index 7aa35899e33ce..7c1edf8c5c2df 100644
@@ -359,6 +359,10 @@ static int ttm_bo_kmap_ttm(struct ttm_buffer_object *bo,
 	if (ret)
 		return ret;
 
+	/* Imported sg tables only come with DMA addresses, no pages to map. */
+	if (!ttm->pages)
+		return -EINVAL;
+
 	if (num_pages == 1 && ttm->caching == ttm_cached &&
 	    !(man->use_tt && (ttm->page_flags & TTM_TT_FLAG_DECRYPTED))) {
 		/*
@@ -422,7 +426,7 @@ EXPORT_SYMBOL(ttm_bo_kmap_try_from_panic);
  *
  * Returns
  * -ENOMEM: Out of memory.
- * -EINVAL: Invalid range.
+ * -EINVAL: Invalid range or the BO has no pages to map.
  */
 int ttm_bo_kmap(struct ttm_buffer_object *bo,
 		unsigned long start_page, unsigned long num_pages,
@@ -496,7 +500,7 @@ EXPORT_SYMBOL(ttm_bo_kunmap);
  *
  * Returns
  * -ENOMEM: Out of memory.
- * -EINVAL: Invalid range.
+ * -EINVAL: Invalid range or the BO has no pages to map.
  */
 int ttm_bo_vmap(struct ttm_buffer_object *bo, struct iosys_map *map)
 {
@@ -543,6 +547,9 @@ int ttm_bo_vmap(struct ttm_buffer_object *bo, struct iosys_map *map)
 		if (ret)
 			return ret;
 
+		if (!ttm->pages)
+			return -EINVAL;
+
 		/*
 		 * We need to use vmap to get the desired page protection
 		 * or to make the buffer object look contiguous.
Signature · 1 line
2.53.0
author maintainer
#444 lore raw

PATCH 443/869 ALSA: usb-audio: Add mic resolution quirk for Logitech Webcam C200

In reply to Greg Kroah-Hartman

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

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

From: Olivier Kaloudoff <[email protected]>

[ Upstream commit 874323b68c93c6808e034dc0113681e822e6fb42 ]

The C200 (046d:0802) reports a mic capture volume range of 1536..7680 with a resolution of 1 (6144 steps), triggering "Warning! Unlikely big volume step count (=6144), linear volume or wrong cval->res?" at probe and exposing a uselessly fine-grained mixer control. This is the same firmware behavior as the other UVC-era Logitech webcams already carrying QUIRK_FLAG_MIC_RES_384 (C500, C600, C210, C270, C310, C510, C525, ...), so apply the same
quirk: CTL_MSG_DELAY_1M (which the Logitech VENDOR_FLG would provide if the device-specific entry did not short-circuit the lookup) plus MIC_RES_384.

Verified on real hardware: with the quirk the warning disappears and the driver logs "set resolution quirk: cval->res = 384".

---
 sound/usb/quirks.c | 2 ++
 1 file changed, 2 insertions(+)
sound/usb/quirks.c +2 -0
index be80d9d14e0ad..01a5564eda7af 100644
@@ -2161,6 +2161,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = {
 		   QUIRK_FLAG_DISABLE_AUTOSUSPEND),
 	DEVICE_FLG(0x045e, 0x070f, /* MS LifeChat LX-3000 Headset */
 		   QUIRK_FLAG_MIXER_PLAYBACK_MIN_MUTE),
+	DEVICE_FLG(0x046d, 0x0802, /* Logitech Webcam C200 */
+		   QUIRK_FLAG_CTL_MSG_DELAY_1M | QUIRK_FLAG_MIC_RES_384),
 	DEVICE_FLG(0x046d, 0x0807, /* Logitech Webcam C500 */
 		   QUIRK_FLAG_CTL_MSG_DELAY_1M | QUIRK_FLAG_MIC_RES_384),
 	DEVICE_FLG(0x046d, 0x0808, /* Logitech Webcam C600 */
Signature · 1 line
2.53.0
author maintainer
#445 lore raw

PATCH 444/869 wifi: ath12k: validate MAC/PHY capability count before saving

In reply to Greg Kroah-Hartman

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

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

From: Jiale Yao <[email protected]>

[ Upstream commit 86f2537877d6029487811bc3e0cd9e086a196000 ]

Firmware supplies the hardware mode count and the PHY bitmap for each mode in the service-ready-ext event. ath12k_wmi_save_all_mac_phy_info() uses those bitmaps to populate svc_ext_info->mac_phy_info, but the destination is a fixed array of ATH12K_MAX_MAC_PHY_CAP elements.

If the total number of advertised PHY entries exceeds that limit, the loop writes beyond mac_phy_info and corrupts adjacent memory.

ath12k_wmi_mac_phy_caps_parse() allocates the source array for tot_phy_id entries and rejects excess capability TLVs. However, if the event contains fewer capability TLVs than advertised, the remaining allocated entries stay zeroed and are saved as invalid PHY information.

After parsing the MAC/PHY capability TLVs, validate the destination capacity and reject an incomplete capability list before saving any entries.

Fixes 062ade23991e ("wifi: ath12k: parse and save hardware mode info from WMI_SERVICE_READY_EXT_EVENTID event for later use")
---
 drivers/net/wireless/ath/ath12k/wmi.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
drivers/net/wireless/ath/ath12k/wmi.c +17 -0
index 91f293ab70137..67c9174a30aab 100644
@@ -4814,6 +4814,7 @@ static int ath12k_wmi_svc_rdy_ext_parse(struct ath12k_base *ab,
 					u16 tag, u16 len,
 					const void *ptr, void *data)
 {
+	struct ath12k_svc_ext_info *svc_ext_info = &ab->wmi_ab.svc_ext_info;
 	struct ath12k_wmi_pdev *wmi_handle = &ab->wmi_ab.wmi[0];
 	struct ath12k_wmi_svc_rdy_ext_parse *svc_rdy_ext = data;
 	int ret;
@@ -4858,6 +4859,22 @@ static int ath12k_wmi_svc_rdy_ext_parse(struct ath12k_base *ab,
 				return ret;
 			}
 
+			if (svc_rdy_ext->tot_phy_id >
+			    ARRAY_SIZE(svc_ext_info->mac_phy_info)) {
+				ath12k_warn(ab, "too many PHY entries %u (max %zu)\n",
+					    svc_rdy_ext->tot_phy_id,
+					    ARRAY_SIZE(svc_ext_info->mac_phy_info));
+				return -EINVAL;
+			}
+
+			if (svc_rdy_ext->n_mac_phy_caps < svc_rdy_ext->tot_phy_id) {
+				ath12k_warn(ab,
+					    "not enough MAC/PHY caps %u, expected %u\n",
+					    svc_rdy_ext->n_mac_phy_caps,
+					    svc_rdy_ext->tot_phy_id);
+				return -EINVAL;
+			}
+
 			ath12k_wmi_save_all_mac_phy_info(ab, svc_rdy_ext);
 
 			svc_rdy_ext->mac_phy_done = true;
Signature · 1 line
2.53.0
author maintainer
#446 lore raw

PATCH 445/869 USB: cdc-acm: fix urb leak on disconnect

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

[ Upstream commit 648b08aa37c1b24a61662ad78964f2bca659ca26 ]

Make sure to drop the reference taken by usb_anchor_urb() when removing URBs from the delayed URB anchor to prevent them from leaking when the device is later disconnected.

---
 drivers/usb/class/cdc-acm.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/class/cdc-acm.c +2 -1
index b980cb08d675b..884dc80868ca9 100644
@@ -782,6 +782,7 @@ static void acm_port_shutdown(struct tty_port *port)
 		urb = usb_get_from_anchor(&acm->delayed);
 		if (!urb)
 			break;
+		usb_put_urb(urb);
 		wb = urb->context;
 		wb->use = false;
 		usb_autopm_put_interface_async(acm->control);
@@ -1710,7 +1711,7 @@ static int acm_resume(struct usb_interface *intf)
 			urb = usb_get_from_anchor(&acm->delayed);
 			if (!urb)
 				break;
-
+			usb_put_urb(urb);
 			acm_start_wb(acm, urb->context);
 		}
 
Signature · 1 line
2.53.0
author maintainer
#447 lore raw

PATCH 446/869 USB: serial: option: add Rolling Wireless RN947R

In reply to Greg Kroah-Hartman

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

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

From: Reinhard Speyerer <[email protected]>

[ Upstream commit 931aad81f3f2d26276fff6b7bda6793267a65725 ]

Add Rolling Wireless RN947R 0x9300 compositions:

Standard mode: DIAG + ADB + NMEA + MODEM + RMNET + QDSS + ADPL

T:  Bus=01 Lev=01 Prnt=01 Port=02 Cnt=02 Dev#=  6 Spd=480  MxCh= 0
D:  Ver= 2.10 Cls=ef(misc ) Sub=02 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=33f8 ProdID=9300 Rev= 0.00
S:  Manufacturer=Rolling Wireless
S:  Product=RN947R
S:  SerialNumber=xxxxxxxxxxx
C:* #Ifs= 7 Cfg#= 1 Atr=a0 MxPwr=500mA
I:* If#= 0 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=ff Prot=30 Driver=option
E:  Ad=01(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=81(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#= 1 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=42 Prot=01 Driver=usbfs
E:  Ad=02(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=82(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#= 2 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=ff Prot=40 Driver=option
E:  Ad=84(I) Atr=03(Int.) MxPS=  10 Ivl=32ms
E:  Ad=83(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=03(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#= 3 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=ff Prot=40 Driver=option
E:  Ad=86(I) Atr=03(Int.) MxPS=  10 Ivl=32ms
E:  Ad=85(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=04(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#= 8 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=ff Prot=50 Driver=qmi_wwan
E:  Ad=88(I) Atr=03(Int.) MxPS=   8 Ivl=32ms
E:  Ad=87(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=05(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms

I:* If#=21 Alt= 0 #EPs= 1 Cls=ff(vend.) Sub=ff Prot=70 Driver=(none)
E: Ad=89(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#=22 Alt= 0 #EPs= 1 Cls=ff(vend.) Sub=ff Prot=80 Driver=(none)
E: Ad=8a(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms

QDL mode:

T:  Bus=01 Lev=01 Prnt=01 Port=02 Cnt=02 Dev#= 12 Spd=480  MxCh= 0
D:  Ver= 2.10 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=33f8 ProdID=9300 Rev= 0.00
S:  Manufacturer=Rolling Wireless
S:  Product=RN947R
S:  SerialNumber=xxxxxxxxxxx
C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=  2mA
I:* If#= 0 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=ff Prot=10 Driver=option
E:  Ad=81(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=01(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
---
 drivers/usb/serial/option.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/usb/serial/option.c +4 -0
index 0f9a7a4c1f66e..416ec012b0ace 100644
@@ -2511,6 +2511,10 @@ static const struct usb_device_id option_ids[] = {
 	  .driver_info = RSVD(5) },
 	{ USB_DEVICE_INTERFACE_CLASS(0x33f8, 0x1003, 0xff),			/* Rolling RW135R-GL (laptop MBIM) */
 	  .driver_info = RSVD(5) },
+	{ USB_DEVICE_AND_INTERFACE_INFO(0x33f8, 0x9300, 0xff, 0xff, 0x30) },	/* Rolling RN947R */
+	{ USB_DEVICE_AND_INTERFACE_INFO(0x33f8, 0x9300, 0xff, 0xff, 0x40) },
+	{ USB_DEVICE_AND_INTERFACE_INFO(0x33f8, 0x9300, 0xff, 0xff, 0x10),
+	  .driver_info = ZLP },
 	{ USB_DEVICE_INTERFACE_CLASS(0x3466, 0x3301, 0xff) },			/* TDTECH MT5710-CN */
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x3731, 0x0100, 0xff, 0xff, 0x30) },	/* NetPrisma LCUK54-WWD for Global */
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x3731, 0x0100, 0xff, 0x00, 0x40) },
Signature · 1 line
2.53.0
author maintainer
#448 lore raw

PATCH 447/869 USB: serial: option: add support for ASR 1286:4e3c modem

In reply to Greg Kroah-Hartman

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

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

From: Michael Wyraz <[email protected]>

[ Upstream commit 87c56085bcdfec305f5c350fe1c58a62a7f65843 ]

The ASR modem used in the Tuoshi LT22M exposes an RNDIS function on interfaces 0 and 1, a diagnostic port on interface 2, and AT ports on interfaces 3 and 4. Match only the vendor-specific serial interfaces so option does not bind to the RNDIS function.

---
 drivers/usb/serial/option.c | 1 +
 1 file changed, 1 insertion(+)
drivers/usb/serial/option.c +1 -0
index 416ec012b0ace..2f83e7b866f60 100644
@@ -2444,6 +2444,7 @@ static const struct usb_device_id option_ids[] = {
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x04b7, 0x8217, 0xff, 0xff, 0x30) },	/* Compal EXM-G1x */
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x04b7, 0x8217, 0xff, 0xff, 0x40) },
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x04b7, 0x8217, 0xff, 0xff, 0x60) },
+	{ USB_DEVICE_INTERFACE_CLASS(0x1286, 0x4e3c, 0xff) },			/* ASR modem */
 	{ USB_DEVICE(0x1508, 0x1001),						/* Fibocom NL668 (IOT version) */
 	  .driver_info = RSVD(4) | RSVD(5) | RSVD(6) },
 	{ USB_DEVICE(0x1782, 0x4d10) },						/* Fibocom L610 (AT mode) */
Signature · 1 line
2.53.0
author maintainer
#449 lore raw

PATCH 448/869 USB: serial: usb_wwan: fix urb leak on disconnect

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

[ Upstream commit c78dd373b5c56a5a02da591b583c6b48d0d62954 ]

Make sure to drop the reference taken by usb_anchor_urb() when removing URBs from the delayed URB anchor to prevent them from leaking when the device is later disconnected.

Fixes 383cedc3bb43 ("USB: serial: full autosuspend support for the option driver")
Cc [email protected] # 2.6.32
Cc Oliver Neukum <[email protected]>
---
 drivers/usb/serial/usb_wwan.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/usb/serial/usb_wwan.c +3 -0
index 0017f6e969e12..67e1820bbbafe 100644
@@ -402,6 +402,7 @@ void usb_wwan_close(struct usb_serial_port *port)
 		urb = usb_get_from_anchor(&portdata->delayed);
 		if (!urb)
 			break;
+		usb_put_urb(urb);
 		unbusy_queued_urb(urb, portdata);
 		usb_autopm_put_interface_async(serial->interface);
 	}
@@ -579,6 +580,8 @@ static int usb_wwan_submit_delayed_urbs(struct usb_serial_port *port)
 		if (!urb)
 			break;
 
+		usb_put_urb(urb);
+
 		err = usb_submit_urb(urb, GFP_ATOMIC);
 		if (err) {
 			dev_err(&port->dev, "%s: submit urb failed: %d\n",
Signature · 1 line
2.53.0
author maintainer
#450 lore raw

PATCH 449/869 slimbus: messaging: fix leaked PM vote on tid allocation failure

In reply to Greg Kroah-Hartman

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

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

From: Zongmin Zhou <[email protected]>

[ Upstream commit c26cc979e28f5193310e4379e14aa6417375c565 ]

In slim_do_transfer(), when a transaction needs a tid and slim_alloc_txn_tid() fails, the function returns directly instead of jumping to slim_xfer_err. The runtime PM vote taken earlier with pm_runtime_get_sync() is then never released, leaving the controller permanently powered up.

As txn->tid is still 0 at that point, jumping to slim_xfer_err drops the vote exactly like it is done for other failed transactions.

---
 drivers/slimbus/messaging.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/slimbus/messaging.c +1 -1
index e2dbe4a66b703..ee127ef42046b 100644
@@ -139,7 +139,7 @@ int slim_do_transfer(struct slim_controller *ctrl, struct slim_msg_txn *txn)
 	if (need_tid) {
 		ret = slim_alloc_txn_tid(ctrl, txn);
 		if (ret)
-			return ret;
+			goto slim_xfer_err;
 
 		if (!txn->msg->comp)
 			txn->comp = &done;
Signature · 1 line
2.53.0
author maintainer
#451 lore raw

PATCH 450/869 xen-blkfront: Fix IO race during unplug

In reply to Greg Kroah-Hartman

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

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

From: Ross Lagerwall <[email protected]>

[ Upstream commit 61b6d1df1d6234c38a6ea7e4f58e7da035ef6ab4 ]

During unplug, blkfront stops the hw queues and marks the disk as dead, then later during removal calls del_gendisk(). However, IO issued after the hw queues are stopped but before the call to del_gendisk() will be queued but never handled. This causes del_gendisk() to hang forever waiting for the queue refcount to drop to zero.

This can be reproduced by issuing IO during an artificial delay after stopping the hw queues.

Fix this by simply not stopping the hw queues directly. Marking the disk as dead already freezes the queue which prevents new requests being added and it synchronously runs the hw queues to clear anything pending. If the hw queues are stopped when calling blk_mark_disk_dead(), running the hw queues is a no-op and can leave queued requests unprocessed.

Message-ID: <[email protected]>

---
 drivers/block/xen-blkfront.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/block/xen-blkfront.c +1 -3
index f37290fd3c5db..79fe0b107887c 100644
@@ -2133,10 +2133,8 @@ static void blkfront_closing(struct blkfront_info *info)
 		return;
 
 	/* No more blkif_request(). */
-	if (info->rq && info->gd) {
-		blk_mq_stop_hw_queues(info->rq);
+	if (info->gd)
 		blk_mark_disk_dead(info->gd);
-	}
 
 	for_each_rinfo(info, rinfo, i) {
 		/* No more gnttab callback work. */
Signature · 1 line
2.53.0
author maintainer
#452 lore raw

PATCH 451/869 RISC-V: KVM: Fix IPI delivery for out-of-order vcpu_id

In reply to Greg Kroah-Hartman

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

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

From: Xiaofeng Yuan <[email protected]>

[ Upstream commit c367d3bf721f2bc391d6cfb47f6884e99d563df0 ]

The SBI IPI handler walks vCPUs with kvm_for_each_vcpu(), which iterates by vcpu_idx (creation order) rather than vcpu_id order. Since vcpu_id can be assigned out of order by userspace, a vCPU whose hart_bit falls outside the XLEN-bit hart_mask range may be reached before vCPUs the mask actually targets. In that case the handler jumps to "done" and stops sending IPIs, leaving valid target vCPUs without an interrupt.

Replace the early "goto done" with "continue" so vCPUs outside the hart_mask range are skipped without aborting the loop.

Reproduced with a minimal userspace VMM driving KVM inside a QEMU (RISC-V virt) guest: three vCPUs are created with ids 100, 0, 1 (in creation order) and sbi_send_ipi(hart_mask=bit0, hbase=0) is called from vcpu_id 1. Before this change the IPI is dropped and the ecall returns SBI_ERR_INVALID_PARAM; with this change the IPI is delivered and the ecall returns SBI_SUCCESS.

---
 arch/riscv/kvm/vcpu_sbi_replace.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
arch/riscv/kvm/vcpu_sbi_replace.c +10 -2
index b490ed1428a68..df3818fec0bfa 100644
@@ -64,8 +64,17 @@ static int kvm_sbi_ext_ipi_handler(struct kvm_vcpu *vcpu, struct kvm_run *run,
 			if (tmp->vcpu_id < hbase)
 				continue;
 			hart_bit = tmp->vcpu_id - hbase;
+			/*
+			 * kvm_for_each_vcpu() walks kvm->vcpus[] by
+			 * vcpu_idx, i.e. the creation order, which has
+			 * nothing to do with the vcpu_id (hart id) space
+			 * that the SBI IPI operates on. vcpu_ids need not
+			 * increase along the iteration, so harts outside
+			 * the hart_mask window must be skipped instead of
+			 * aborting the loop.
+			 */
 			if (hart_bit >= __riscv_xlen)
-				goto done;
+				continue;
 			if (!(hmask & (1UL << hart_bit)))
 				continue;
 		}
@@ -76,7 +85,6 @@ static int kvm_sbi_ext_ipi_handler(struct kvm_vcpu *vcpu, struct kvm_run *run,
 		kvm_riscv_vcpu_pmu_incr_fw(tmp, SBI_PMU_FW_IPI_RCVD);
 	}
 
-done:
 	if (hbase != -1UL && (hmask ^ sentmask))
 		retdata->err_val = SBI_ERR_INVALID_PARAM;
 
Signature · 1 line
2.53.0
author maintainer
#453 lore raw

PATCH 452/869 vfio/mlx5: Fix boundary check in set_report_output()

In reply to Greg Kroah-Hartman

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

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

From: Seongjun Hong <[email protected]>

[ Upstream commit 37b2ee6747b7857920ebc71eabc25208a39164a4 ]

Use > instead of >= on boundary check of recv_buf to avoid the bug which the full message in the last slot of recv_buf is ignored even though the received data size does not overflow the recv_buf.

---
 drivers/vfio/pci/mlx5/cmd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/vfio/pci/mlx5/cmd.c +1 -1
index a92b095b90f6a..a870ea1c0e9d3 100644
@@ -1627,7 +1627,7 @@ set_report_output(u32 size, int index, struct mlx5_vhca_qp *qp,
 	int i;
 
 	buf_offset = index * qp->max_msg_size;
-	if (WARN_ON(buf_offset + size >= qp->recv_buf.npages * PAGE_SIZE ||
+	if (WARN_ON(buf_offset + size > qp->recv_buf.npages * PAGE_SIZE ||
 		    (nent > qp->max_msg_size / entry_size)))
 		return;
 
Signature · 1 line
2.53.0
author maintainer
#454 lore raw

PATCH 453/869 cxl/pci: Program the Port GPF timeouts before caching the DVSEC

In reply to Greg Kroah-Hartman

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

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

From: Guixin Liu <[email protected]>

[ Upstream commit ec2e30a682945616d194d7999cf96606b7ee5a88 ]

cxl_gpf_port_setup() caches the Port GPF DVSEC offset in the dport before programming the phase timeouts, and ignores the return value of both update_gpf_port_dvsec() calls: the function always reports success.

A failing config write is therefore not only silent, it is also
permanent: the timeouts stay at the hardware defaults instead of the maximum flush window the kernel is asking for, and the cached offset keeps any later endpoint attach from retrying the update.

Propagate the errors and cache the offset only after both phases are programmed, so the next endpoint attach retries the setup.

Fixes 6af941db6a60 ("cxl/pci: Update Port GPF timeout only when the first EP attaching")
Assisted-by LLM
---
 drivers/cxl/core/pci.c | 30 +++++++++++++++++++++---------
 1 file changed, 21 insertions(+), 9 deletions(-)
drivers/cxl/core/pci.c +21 -9
index 68859eba30db3..3e88c2e3304a3 100644
@@ -860,7 +860,7 @@ static int update_gpf_port_dvsec(struct pci_dev *pdev, int dvsec, int phase)
 
 	rc = pci_read_config_word(pdev, dvsec + offset, &ctrl);
 	if (rc)
-		return rc;
+		return pcibios_err_to_errno(rc);
 
 	if (FIELD_GET(base, ctrl) == GPF_TIMEOUT_BASE_MAX &&
 	    FIELD_GET(scale, ctrl) == GPF_TIMEOUT_SCALE_MAX)
@@ -870,11 +870,17 @@ static int update_gpf_port_dvsec(struct pci_dev *pdev, int dvsec, int phase)
 	ctrl |= FIELD_PREP(scale, GPF_TIMEOUT_SCALE_MAX);
 
 	rc = pci_write_config_word(pdev, dvsec + offset, ctrl);
-	if (!rc)
-		pci_dbg(pdev, "Port GPF phase %d timeout: %d0 secs\n",
-			phase, GPF_TIMEOUT_BASE_MAX);
+	if (rc) {
+		rc = pcibios_err_to_errno(rc);
+		pci_warn(pdev, "Port GPF phase %d timeout write failed: %d\n",
+			 phase, rc);
+		return rc;
+	}
+
+	pci_dbg(pdev, "Port GPF phase %d timeout: %d0 secs\n",
+		phase, GPF_TIMEOUT_BASE_MAX);
 
-	return rc;
+	return 0;
 }
 
 int cxl_gpf_port_setup(struct cxl_dport *dport)
@@ -884,16 +890,22 @@ int cxl_gpf_port_setup(struct cxl_dport *dport)
 
 	if (!dport->gpf_dvsec) {
 		struct pci_dev *pdev;
-		int dvsec;
+		int dvsec, rc;
 
 		dvsec = cxl_gpf_get_dvsec(dport->dport_dev);
 		if (!dvsec)
 			return -EINVAL;
 
-		dport->gpf_dvsec = dvsec;
 		pdev = to_pci_dev(dport->dport_dev);
-		update_gpf_port_dvsec(pdev, dport->gpf_dvsec, 1);
-		update_gpf_port_dvsec(pdev, dport->gpf_dvsec, 2);
+		rc = update_gpf_port_dvsec(pdev, dvsec, 1);
+		if (rc)
+			return rc;
+
+		rc = update_gpf_port_dvsec(pdev, dvsec, 2);
+		if (rc)
+			return rc;
+
+		dport->gpf_dvsec = dvsec;
 	}
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#455 lore raw

PATCH 454/869 cxl/port: Convert PCIe link latency to nanoseconds

In reply to Greg Kroah-Hartman

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

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

From: Koichiro Den <[email protected]>

[ Upstream commit 16440d6e4bf1175cda83438d9f9a8ae84bfcf0ee ]

Commit 51293c565cf4 ("cxl: Fix incorrect region perf data calculation") converted CDAT latencies to nanoseconds and removed the conversion in cxl_region_perf_data_calculate(), but left PCIe link latencies in picoseconds.

This inflates the FlitLatency contribution to region and node latencies by a factor of 1000, exposing incorrect values in sysfs. The resulting abstract distances can incorrectly reverse the memory tier ordering of nodes.

Convert the FlitLatency contribution to nanoseconds before adding it to the access coordinates, rounding up as cdat_normalize() does.

---
 drivers/cxl/core/port.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/cxl/core/port.c +3 -0
index 8d2dc4b741781..599aa9d9eddca 100644
@@ -2286,6 +2286,9 @@ EXPORT_SYMBOL_NS_GPL(schedule_cxl_memdev_detach, "CXL");
 
 static void add_latency(struct access_coordinate *c, long latency)
 {
+	/* Convert link latency from picoseconds to nanoseconds. */
+	latency = DIV_ROUND_UP(latency, 1000);
+
 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) {
 		c[i].write_latency += latency;
 		c[i].read_latency += latency;
Signature · 1 line
2.53.0
author maintainer
#456 lore raw

PATCH 455/869 cxl: Account for link width in latency calculation

In reply to Greg Kroah-Hartman

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

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

From: Koichiro Den <[email protected]>

[ Upstream commit db4503d4575cdd2fad7e8a13a8a8ffcbc86d152d ]

cxl_pci_get_latency() derives bandwidth from the per-lane speed returned by pcie_link_speed_mbps(), ignoring the negotiated link width. This overestimates the FlitLatency contribution for multi-lane links. Sections 2.11.3 and 2.11.4 of the Intel CXL Memory Device Software Guide describe the link bandwidth as the product of the negotiated speed and width.

Replace pcie_link_speed_mbps() with pcie_link_bandwidth_mbps() and migrate both CXL callers (the only users of the API). The new helper obtains speed and width from a single Link Status read. The CXL bandwidth calculation no longer needs a separate width read and multiplication.

While at it, make error handling more robust by converting PCI config read errors to negative errno values and checking for zero bandwidth before calculating latency.

---
 drivers/cxl/core/pci.c | 22 ++++++++--------------
 drivers/pci/pci.c      | 23 ++++++++++++++++++-----
 include/linux/pci.h    |  2 +-
 3 files changed, 27 insertions(+), 20 deletions(-)
drivers/cxl/core/pci.c +8 -14
index 3e88c2e3304a3..48c1f3854b799 100644
@@ -738,8 +738,8 @@ long cxl_pci_get_latency(struct pci_dev *pdev)
 {
 	long bw;
 
-	bw = pcie_link_speed_mbps(pdev);
-	if (bw < 0)
+	bw = pcie_link_bandwidth_mbps(pdev);
+	if (bw <= 0)
 		return 0;
 	bw /= BITS_PER_BYTE;
 
@@ -777,18 +777,12 @@ EXPORT_SYMBOL_NS_GPL(cxl_endpoint_decoder_reset_detected, "CXL");
 
 int cxl_pci_get_bandwidth(struct pci_dev *pdev, struct access_coordinate *c)
 {
-	int speed, bw;
-	u16 lnksta;
-	u32 width;
-
-	speed = pcie_link_speed_mbps(pdev);
-	if (speed < 0)
-		return speed;
-	speed /= BITS_PER_BYTE;
-
-	pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnksta);
-	width = FIELD_GET(PCI_EXP_LNKSTA_NLW, lnksta);
-	bw = speed * width;
+	int bw;
+
+	bw = pcie_link_bandwidth_mbps(pdev);
+	if (bw < 0)
+		return bw;
+	bw /= BITS_PER_BYTE;
 
 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) {
 		c[i].read_bandwidth = bw;
drivers/pci/pci.c +18 -5
index bab3213bafbda..8cfcd71163031 100644
@@ -5892,18 +5892,31 @@ static enum pci_bus_speed to_pcie_link_speed(u16 lnksta)
 	return pcie_link_speed[FIELD_GET(PCI_EXP_LNKSTA_CLS, lnksta)];
 }
 
-int pcie_link_speed_mbps(struct pci_dev *pdev)
+/**
+ * pcie_link_bandwidth_mbps - get the current bandwidth of a single PCIe link
+ * @pdev: PCI device to query
+ *
+ * The bandwidth includes all negotiated lanes and does not account for
+ * encoding overhead. A negotiated width of zero gives zero bandwidth.
+ *
+ * Return: Bandwidth in Mb/s, or a negative errno on failure.
+ */
+int pcie_link_bandwidth_mbps(struct pci_dev *pdev)
 {
 	u16 lnksta;
-	int err;
+	int speed, err;
 
 	err = pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnksta);
 	if (err)
-		return err;
+		return pcibios_err_to_errno(err);
+
+	speed = pcie_dev_speed_mbps(to_pcie_link_speed(lnksta));
+	if (speed < 0)
+		return speed;
 
-	return pcie_dev_speed_mbps(to_pcie_link_speed(lnksta));
+	return speed * FIELD_GET(PCI_EXP_LNKSTA_NLW, lnksta);
 }
-EXPORT_SYMBOL(pcie_link_speed_mbps);
+EXPORT_SYMBOL(pcie_link_bandwidth_mbps);
 
 /**
  * pcie_bandwidth_available - determine minimum link settings of a PCIe
include/linux/pci.h +1 -1
index 95c77e2a1d1f5..72d1ca12aaa8c 100644
@@ -1413,7 +1413,7 @@ int pcie_set_mps(struct pci_dev *dev, int mps);
 u32 pcie_bandwidth_available(struct pci_dev *dev, struct pci_dev **limiting_dev,
 			     enum pci_bus_speed *speed,
 			     enum pcie_link_width *width);
-int pcie_link_speed_mbps(struct pci_dev *pdev);
+int pcie_link_bandwidth_mbps(struct pci_dev *pdev);
 void pcie_print_link_status(struct pci_dev *dev);
 int pcie_reset_flr(struct pci_dev *dev, bool probe);
 int pcie_flr(struct pci_dev *dev);
Signature · 1 line
2.53.0
author maintainer
#457 lore raw

PATCH 456/869 cxl/acpi: Convert QTG _DSM latencies to picoseconds

In reply to Greg Kroah-Hartman

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

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

From: Koichiro Den <[email protected]>

[ Upstream commit 2658c66a5efb5f30f5ced708a5de831845b43f6d ]

The QTG _DSM expects read and write latencies in picoseconds, as specified in CXL 3.0, Table 9-30.

The code base originally kept the latencies passed to the QTG _DSM in picoseconds in effect. Commit 51293c565cf4 ("cxl: Fix incorrect region perf data calculation") normalized CDAT and host bridge latencies to nanoseconds, but did not add a conversion back to picoseconds when constructing the _DSM input. Firmware can therefore select QTG IDs using understated latencies.

Convert the latencies to picoseconds when constructing the _DSM input package. Multiply in 64 bits and reject latencies that cannot fit in the DWORD inputs defined by the specification.

---
 drivers/cxl/acpi.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/cxl/acpi.c +8 -2
index 5e9bb0df46dd8..eeb6921950fc2 100644
@@ -205,9 +205,10 @@ cxl_acpi_evaluate_qtg_dsm(acpi_handle handle, struct access_coordinate *coord,
 			  int entries, int *qos_class)
 {
 	union acpi_object *out_obj, *out_buf, *obj;
+	/* QTG _DSM expects latencies in picoseconds. */
 	union acpi_object in_array[4] = {
-		[0].integer = { ACPI_TYPE_INTEGER, coord->read_latency },
-		[1].integer = { ACPI_TYPE_INTEGER, coord->write_latency },
+		[0].integer = { ACPI_TYPE_INTEGER, coord->read_latency * 1000ULL },
+		[1].integer = { ACPI_TYPE_INTEGER, coord->write_latency * 1000ULL },
 		[2].integer = { ACPI_TYPE_INTEGER, coord->read_bandwidth },
 		[3].integer = { ACPI_TYPE_INTEGER, coord->write_bandwidth },
 	};
@@ -225,6 +226,11 @@ cxl_acpi_evaluate_qtg_dsm(acpi_handle handle, struct access_coordinate *coord,
 	if (!entries)
 		return -EINVAL;
 
+	/* Latency inputs must fit in the DWORD fields defined by the spec. */
+	if (coord->read_latency > U32_MAX / 1000 ||
+	    coord->write_latency > U32_MAX / 1000)
+		return -ERANGE;
+
 	out_obj = acpi_evaluate_dsm(handle, &acpi_cxl_qtg_id_guid, 1, 1, &in_obj);
 	if (!out_obj)
 		return -ENXIO;
Signature · 1 line
2.53.0
author maintainer
#458 lore raw

PATCH 457/869 lib/plist: fix plist_requeue() corrupting order in the last bucket

In reply to Greg Kroah-Hartman

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

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

From: Adam Harshbarger <[email protected]>

[ Upstream commit 43c91b1522435429a63d175f5a953e6f727a4f88 ]

plist_requeue() is meant to move a node to the end of its own priority run. When the node heads the *last* priority bucket it is instead placed at the head of the whole list, leaving the plist unsorted:

built: A(prio 0) B(prio 1) C(prio 1)
requeue(B): B(prio 1) A(prio 0) C(prio 1)
expected: A(prio 0) C(prio 1) B(prio 1)

prio_list is a *headless* circular ring of the nodes that lead each priority bucket. The shortcut added by commit 95d4b3450ebe ("lib/plist.c:
add shortcut for plist_requeue()") takes

	iter = list_entry(iter->prio_list.next, struct plist_node,
			  prio_list);
	node_next = &iter->node_list;

which from the last bucket wraps round to the *first* bucket, so node_next ends up pointing at the head of the list rather than at its end. The plist_for_each_continue() loop immediately below it computes the correct answer (&head->node_list) for that case.

With any bucket after it the shortcut is correct, which is why this went
unnoticed: the benchmark in that commit measured elapsed time and never checked the resulting order.

Keep the shortcut -- it is a real win -- but exclude the case where iter's bucket is the last one, which is exactly when its ring successor is the first bucket again.

Reachable from mm/swapfile.c, which rotates swap_avail_heads[] with plist_requeue(). It takes three or more swap devices: at least two distinct priorities, so that a later bucket exists for the ring to wrap round from, and two or more devices sharing the lowest priority, so that plist_requeue() does not return early. One device per priority returns early at the node->prio != iter->prio test. A single priority is also safe, but for a different reason worth stating: with one bucket no node is ever linked onto prio_list at all -- plist_add() skips it for the first node and for every node whose predecessor shares its priority -- so list_empty(&iter->prio_list) holds and the shortcut is never entered.

Tested by driving three implementations -- the pre-95d4b3450ebe code, current mainline, and this patch -- through 1,084,492 identical random add/del/requeue operations over 24 nodes and 1..5 distinct priorities, comparing the resulting node_list node for node after every operation:

variant differs from pre-95d4b3450ebe left list unsorted
pre-95d4b3450ebe -- (reference) 0
mainline 289,297 276,660
this patch 0 0

Fixes 95d4b3450ebe ("lib/plist.c: add shortcut for plist_requeue()")
Assisted-by Claude:claude-opus-5
Cc I Hsin Cheng <[email protected]>
Cc <[email protected]> # v6.15+
---
 lib/plist.c | 7 +++++++
 1 file changed, 7 insertions(+)
lib/plist.c +7 -0
index 330febb4bd7d7..1e9cb0e35af7f 100644
@@ -174,8 +174,15 @@ void plist_requeue(struct plist_node *node, struct plist_head *head)
 	/*
 	 * After plist_del(), iter is the replacement of the node.  If the node
 	 * was on prio_list, take shortcut to find node_next instead of looping.
+	 *
+	 * prio_list is a headless ring, so from the LAST bucket ->next wraps
+	 * round to the first one; in that case node_next is the list head.
 	 */
 	if (!list_empty(&iter->prio_list)) {
+		struct plist_node *first = plist_first(head);
+
+		if (iter->prio_list.next == &first->prio_list)
+			goto queue;
 		iter = list_entry(iter->prio_list.next, struct plist_node,
 				  prio_list);
 		node_next = &iter->node_list;
Signature · 1 line
2.53.0
author maintainer
#459 lore raw

PATCH 458/869 USB: cdc-acm: add VeriFone VX820 device ID

In reply to Greg Kroah-Hartman

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

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

From: Drobyshev Vladimir <[email protected]>

[ Upstream commit ddbddee6592ecf6cf6c24d888780f9ad45a3e30b ]

Add USB ID 11ca:0219 for the VeriFone VX820 to the cdc-acm device table and apply the SINGLE_RX_URB quirk.

---
 drivers/usb/class/cdc-acm.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/usb/class/cdc-acm.c +3 -0
index 884dc80868ca9..990482982a28e 100644
@@ -1819,6 +1819,9 @@ static const struct usb_device_id acm_ids[] = {
 	{ USB_DEVICE(0x11ca, 0x0201), /* VeriFone Mx870 Gadget Serial */
 	.driver_info = SINGLE_RX_URB,
 	},
+	{ USB_DEVICE(0x11ca, 0x0219), /* VeriFone Vx820 Gadget Serial */
+	.driver_info = SINGLE_RX_URB,
+	},
 	{ USB_DEVICE(0x1901, 0x0006), /* GE Healthcare Patient Monitor UI Controller */
 	.driver_info = DISABLE_ECHO, /* DISABLE ECHO in termios flag */
 	},
Signature · 1 line
2.53.0
author maintainer
#460 lore raw

PATCH 459/869 USB: quirks: add USB_QUIRK_WINDOWS_CONFIG_REQ_SIZE for GameSir G7 SE

In reply to Greg Kroah-Hartman

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

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

From: Ali Resool Tuama <[email protected]>

[ Upstream commit 40224df29729618ecd88c5c0077e71b1e82c7a3a ]

The GameSir G7 SE wired controller first enumerates as 3537:10a0 and then re-enumerates in a mode it picks from how the host enumerated it.

When the configuration descriptor is fetched the Linux way, 9 bytes followed by the full 80, the controller disconnects about 1 ms after its string descriptors have been read, before SET_CONFIGURATION, and comes back as 3537:1082, a generic HID gamepad without force feedback.

When the configuration descriptor is fetched in one 255-byte request, as Windows does, it comes back as 3537:1010 in Xbox One (GIP) mode, which xpad already supports, including rumble.

Skipping the device qualifier requests (USB_QUIRK_DEVICE_QUALIFIER) makes no difference; the configuration descriptor request size alone decides the mode. Add USB_QUIRK_WINDOWS_CONFIG_REQ_SIZE for the 10a0 identity, as is already done for the ShanWan Wireless Gamepad.

---
 drivers/usb/core/quirks.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/usb/core/quirks.c +3 -0
index 0f804a52ab763..a8e5016fee982 100644
@@ -613,6 +613,9 @@ static const struct usb_device_id usb_quirk_list[] = {
 	/* ezcap401 - BOS descriptor fetch hangs at SuperSpeed Plus */
 	{ USB_DEVICE(0x32ed, 0x0401), .driver_info = USB_QUIRK_NO_BOS },
 
+	/* GameSir G7 SE */
+	{ USB_DEVICE(0x3537, 0x10a0), .driver_info = USB_QUIRK_WINDOWS_CONFIG_REQ_SIZE },
+
 	/* DELL USB GEN2 */
 	{ USB_DEVICE(0x413c, 0xb062), .driver_info = USB_QUIRK_NO_LPM | USB_QUIRK_RESET_RESUME },
 
Signature · 1 line
2.53.0
author maintainer
#461 lore raw

PATCH 460/869 usb: typec: ucsi: ccg: Validate altmode index in GET_CURRENT_CAM response

In reply to Greg Kroah-Hartman

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

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

From: Seungjin Bae <[email protected]>

[ Upstream commit 02ee864e8d2142c5648998944c3306ea6a763c26 ]

When the PPM reports more than one DisplayPort alternate mode for a connector, ucsi_ccg_update_altmodes() merges them into a single entry in uc->updated[] and sets uc->has_multiple_dp. In that case, ucsi_ccg_update_get_current_cam_cmd() rewrites the response of the GET_CURRENT_CAM command. The response is a single byte holding the index of the currently active alternate mode, and it is provided by the PPM firmware.

The function uses this byte directly as an index into uc->orig[], and then uses the linked_idx read from that entry as the translated index into uc->updated[]. Both arrays have UCSI_MAX_ALTMODES entries, but neither index is checked against that size.

If a malicious or buggy PPM reports a value of UCSI_MAX_ALTMODES or larger, e.g. 0xFF, uc->orig[cam].linked_idx reads over the end of uc->orig[]. The byte read from there is then used as the index for writing cam into uc->updated[new_cam].active_idx, so the out-of-bounds read is followed by an out-of-bounds write. This happens without any userspace action, since the UCSI core issues GET_CURRENT_CAM on its own when handling connector changes.

Fix this by rejecting responses whose index is out of range, printing an error and returning -EPROTO, so that the caller cannot accept this. Also check linked_idx before using it as an index, so that the write into uc->updated[] is always within bounds.

The response is now only processed when the command completed without an error. ucsi_sync_control_common() only reads the response when the CCI reports command completion, so otherwise the buffer is not filled and must not be mistaken for an invalid index.

This bug was found with a Python script that traces where firmware input is used.

Fixes 170a6726d0e2 ("usb: typec: ucsi: add support for separate DP altmode devices")
Cc stable <[email protected]>
Assisted-by LLM
---
 drivers/usb/typec/ucsi/ucsi_ccg.c | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)
drivers/usb/typec/ucsi/ucsi_ccg.c +19 -3
index 6c1f62c78ac25..18236d5c30922 100644
@@ -383,14 +383,28 @@ static int ucsi_ccg_init(struct ucsi_ccg *uc)
 	return -ETIMEDOUT;
 }
 
-static void ucsi_ccg_update_get_current_cam_cmd(struct ucsi_ccg *uc, u8 *data)
+static int ucsi_ccg_update_get_current_cam_cmd(struct ucsi_ccg *uc, u8 *data)
 {
 	u8 cam, new_cam;
 
 	cam = data[0];
+	if (cam >= UCSI_MAX_ALTMODES) {
+		dev_err(uc->dev, "PPM returned invalid alternate mode index %u\n",
+			cam);
+		return -EPROTO;
+	}
+
 	new_cam = uc->orig[cam].linked_idx;
+	if (new_cam >= UCSI_MAX_ALTMODES) {
+		dev_err(uc->dev, "invalid linked alternate mode index %u for %u\n",
+			new_cam, cam);
+		return -EPROTO;
+	}
+
 	uc->updated[new_cam].active_idx = cam;
 	data[0] = new_cam;
+
+	return 0;
 }
 
 static bool ucsi_ccg_update_altmodes(struct ucsi *ucsi,
@@ -633,8 +647,10 @@ static int ucsi_ccg_sync_control(struct ucsi *ucsi, u64 command, u32 *cci,
 
 	switch (UCSI_COMMAND(command)) {
 	case UCSI_GET_CURRENT_CAM:
-		if (uc->has_multiple_dp)
-			ucsi_ccg_update_get_current_cam_cmd(uc, (u8 *)data);
+		if (!ret && uc->has_multiple_dp &&
+		    (*cci & UCSI_CCI_COMMAND_COMPLETE) &&
+		    !(*cci & UCSI_CCI_ERROR))
+			ret = ucsi_ccg_update_get_current_cam_cmd(uc, (u8 *)data);
 		break;
 	case UCSI_GET_ALTERNATE_MODES:
 		if (UCSI_ALTMODE_RECIPIENT(command) == UCSI_RECIPIENT_SOP) {
Signature · 1 line
2.53.0
author maintainer
#462 lore raw

PATCH 461/869 usb: xhci: Fix bounce buffer overflow

In reply to Greg Kroah-Hartman

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

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

From: Michal Pecio <[email protected]>

[ Upstream commit 68c5cb7574c567e83ba95258cb146db95e069a87 ]

High-speed devices with out of spec 1024 byte bulk endpoints exist and are allowed by USB core, but xhci-hcd always sets packet size to 512. The exact nature of these devices isn't documented, commit fb5ee84ea72c ("USB: Accept bulk endpoints with 1024-byte maxpacket") only states that they "don't work with xHCI host controllers", whatever it means.

But somebody (or a malicious device) can try, and then the driver will allocate a 512 byte bounce buffer for this endpoint and may write up to 1024 bytes into it if particular scatter-gather URBs are used, because xhci_align_td() obtains packet size from the descriptor. Fix this.

As a side effect, TRBs will be aligned to the packet size chosen by the driver on all endpoints of all speeds. Alignment serves the xHC, not device, so this is fine. Only out of spec devices are affected anyway.

---
 drivers/usb/host/xhci-ring.c | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)
drivers/usb/host/xhci-ring.c +3 -6
index dc18da8385a21..071a0310d6100 100644
@@ -3600,15 +3600,13 @@ static u32 xhci_td_remainder(struct xhci_hcd *xhci, int transferred,
 
 
 static int xhci_align_td(struct xhci_hcd *xhci, struct urb *urb, u32 enqd_len,
-			 u32 *trb_buff_len, struct xhci_segment *seg)
+			 u32 *trb_buff_len, struct xhci_segment *seg, u32 max_pkt)
 {
 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
 	unsigned int unalign;
-	unsigned int max_pkt;
 	u32 new_buff_len;
 	size_t len;
 
-	max_pkt = xhci_usb_endpoint_maxp(urb->dev, urb->ep);
 	unalign = (enqd_len + *trb_buff_len) % max_pkt;
 
 	/* we got lucky, last normal TRB data on segment is packet aligned */
@@ -3753,9 +3751,8 @@ int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
 		if (enqd_len + trb_buff_len < full_len) {
 			field |= TRB_CHAIN;
 			if (trb_is_link(ring->enqueue + 1)) {
-				if (xhci_align_td(xhci, urb, enqd_len,
-						  &trb_buff_len,
-						  ring->enq_seg)) {
+				if (xhci_align_td(xhci, urb, enqd_len, &trb_buff_len,
+						ring->enq_seg, ring->bounce_buf_len)) {
 					send_addr = ring->enq_seg->bounce_dma;
 					/* TD bounced at least, and last on this seg */
 					td->bounce_seg = ring->enq_seg;
Signature · 1 line
2.53.0
author maintainer
#463 lore raw

PATCH 462/869 xhci: Prevent invalid vdev dereference during sideband unregister

In reply to Greg Kroah-Hartman

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

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

From: Mathias Nyman <[email protected]>

[ Upstream commit fd616dc74e8f58f351f2b295620027116cd6e92e ]

Offloaded USB audio devices using the xhci-sideband API store a pointer to the xhci virtual device (vdev) in the sideband structure when registering.

This pointer typically remains valid throughout the lifetime of the USB device. If a configured offloaded device requires a reset, the USB core usually unbinds or notifies the audio driver beforehand, ensuring that the sideband is unregistered before the vdev is freed.

An exception occurs when the USB core resets a device to recover from a failed resume, but a subsequent 'address device' request also fails. To recover in this specific scenario, the xHCI driver disables and re-enables the slot, which frees and re-allocates the vdev.

xhci_sideband_unregister() later dereferences the stale, previously freed vdev pointer during disconnect, triggering a kernel oops:

 Unable to handle kernel paging request at virtual address dead000000000122
 Call trace:
  xhci_get_ep_ctx+0x0/0x38
  xhci_sideband_unregister+0x68/0xf0
  uaudio_disconnect+0x70/0x144
  usb_audio_disconnect+0x7c/0x268
  usb_unbind_interface+0x13c/0x340
  device_release_driver_internal+0x1c4/0x2bc
  usb_disable_device+0x84/0x190
  usb_disconnect+0xe8/0x338
  hub_event+0xbd8/0x19ac

Fix this by preventing the reallocation of the vdev in this specific error path if the device is registered for sideband use.

Just propagate the error directly to the USB core. It should either retry enumeration or detect the disconnected device, and handle it accordingly.

Debugging this issue to the dangling vdev pointer, reporting it, testing, and initial patch with different solution by Lianqin Hu

---
 drivers/usb/host/xhci.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
drivers/usb/host/xhci.c +7 -4
index a4fab82da76b6..b894ba988a3d9 100644
@@ -4435,10 +4435,13 @@ static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
 		dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
 
 		mutex_unlock(&xhci->mutex);
-		ret = xhci_disable_and_free_slot(xhci, udev->slot_id);
-		if (!ret) {
-			if (xhci_alloc_dev(hcd, udev) == 1)
-				xhci_setup_addressable_virt_dev(xhci, udev);
+
+		if (!virt_dev->sideband) {
+			ret = xhci_disable_and_free_slot(xhci, udev->slot_id);
+			if (!ret) {
+				if (xhci_alloc_dev(hcd, udev) == 1)
+					xhci_setup_addressable_virt_dev(xhci, udev);
+			}
 		}
 		kfree(command->completion);
 		kfree(command);
Signature · 1 line
2.53.0
author maintainer
#464 lore raw

PATCH 463/869 usb: typec: ucsi_ccg: Add retry mechanism in ccg_read

In reply to Greg Kroah-Hartman

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

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

From: Wayne Chang <[email protected]>

[ Upstream commit bbf6b99a57b2479bf51c3c8ad0946f4b8c33ed69 ]

CCG4 firmware occasionally fails to respond to I2C read requests, especially when reading cci and intr_reg from the ISR path. In these cases, i2c_transfer() returns -EREMOTEIO.

The CCG4 is EOL, and Infineon no longer supports firmware updates, so a software workaround is necessary.

Attempt the read up to CCG_READ_MAX_RETRIES (4) times in total when -EREMOTEIO is returned, sleeping ~1 ms via fsleep() between attempts. This allows recovery from transient I2C failures without affecting other error paths.

The sleep is safe because ccg_read() is called both from process context and from ccg_irq_handler(), which runs in threaded IRQ context (registered via request_threaded_irq() with a NULL hard-IRQ handler), so sleeping is allowed in both cases.

---
 drivers/usb/typec/ucsi/ucsi_ccg.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/usb/typec/ucsi/ucsi_ccg.c +14 -1
index 18236d5c30922..55dbe7508ea7f 100644
@@ -134,6 +134,8 @@ struct version_format {
 #define NVIDIA_FTB_DP_OFFSET	(2)
 #define NVIDIA_FTB_DBG_OFFSET	(3)
 
+#define CCG_READ_MAX_RETRIES	4
+
 struct version_info {
 	struct version_format base;
 	struct version_format app;
@@ -254,6 +256,7 @@ static int ccg_read(struct ucsi_ccg *uc, u16 rab, u8 *data, u32 len)
 	};
 	u32 rlen, rem_len = len, max_read_len = len;
 	int status;
+	int retry_count;
 
 	/* check any max_read_len limitation on i2c adapter */
 	if (quirks && quirks->max_read_len)
@@ -265,7 +268,17 @@ static int ccg_read(struct ucsi_ccg *uc, u16 rab, u8 *data, u32 len)
 		rlen = min_t(u16, rem_len, max_read_len);
 		msgs[1].len = rlen;
 		put_unaligned_le16(rab, buf);
-		status = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
+
+		for (retry_count = 0; retry_count < CCG_READ_MAX_RETRIES; retry_count++) {
+			status = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
+
+			/* Only retry on -EREMOTEIO, and not after the last attempt */
+			if (status != -EREMOTEIO || retry_count == CCG_READ_MAX_RETRIES - 1)
+				break;
+
+			fsleep(1000);
+		}
+
 		if (status < 0) {
 			dev_err(uc->dev, "i2c_transfer failed %d\n", status);
 			pm_runtime_put_sync(uc->dev);
Signature · 1 line
2.53.0
author maintainer
#465 lore raw

PATCH 464/869 mailbox: altera: shut down RX polling timer on channel teardown

In reply to Greg Kroah-Hartman

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

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

From: Runyu Xiao <[email protected]>

[ Upstream commit 0cf10e65639cba32d05994f85e6a8f08dd0ffe08 ]

The RX polling callback unconditionally rearms the timer after it processes mailbox data. altera_mbox_shutdown() uses timer_delete_sync(), which waits for a running callback but does not prevent that callback from rearming the timer after the deletion.

Use timer_shutdown_sync() for the final polling teardown so the timer cannot be queued again while the mailbox channel is being released. The timer is reinitialized with timer_setup() on a later channel startup, so polling mode remains reusable.

Fixes f62092f6d77d ("mailbox: Add Altera mailbox driver")
Assisted-by Codex:GPT-5
---
 drivers/mailbox/mailbox-altera.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/mailbox/mailbox-altera.c +1 -1
index 17278c2571d34..7cb91413ef7fc 100644
@@ -270,7 +270,7 @@ static void altera_mbox_shutdown(struct mbox_chan *chan)
 		writel_relaxed(~0, mbox->mbox_base + MAILBOX_INTMASK_REG);
 		free_irq(mbox->irq, chan);
 	} else if (!mbox->is_sender) {
-		timer_delete_sync(&mbox->rxpoll_timer);
+		timer_shutdown_sync(&mbox->rxpoll_timer);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#466 lore raw

PATCH 465/869 mailbox: bcm74110: Cap rx_svc_init_list growth to prevent PMC-induced OOM

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit eb2ee504757674450a5e03e36e6b9340f064e599 ]

bcm74110_rx_push_init_msg() allocates a GFP_ATOMIC struct for every BCM_MSG_SVC_INIT word received from the PMC co-processor and appends it to rx_svc_init_list with no cap on list length. The only consumers of this list (bcm74110_rx_pop_init_msg_block / bcm74110_rx_flush_msg) are called only during probe and at shutdown respectively; after probe completes, PMC firmware can continuously inject BCM_MSG_SVC_INIT words, exhausting GFP_ATOMIC reserves and causing a whole-device denial of service.

Add BCM74110_INIT_MSG_MAX (16 entries) as the maximum list depth. bcm74110_rx_push_init_msg() now checks the count under the existing rx_svc_list_lock before allocating; if the cap is reached the message is dropped and a rate-limited warning is emitted. The new rx_svc_init_count field is decremented by bcm74110_rx_pop_init_msg() on successful dequeue and reset to zero by bcm74110_rx_flush_msg() on shutdown.

Fixes 52436007b862 ("mailbox: Add support for bcm74110")
Assisted-by Anthropic:claude-sonnet-4.6 cursor
---
 drivers/mailbox/bcm74110-mailbox.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
drivers/mailbox/bcm74110-mailbox.c +13 -0
index 2e7e86f3e6a4a..0ae6c56b87869 100644
@@ -97,6 +97,8 @@ struct bcm74110_mbox_chan {
 	int				type;
 };
 
+#define BCM74110_INIT_MSG_MAX		16
+
 struct bcm74110_mbox {
 	struct platform_device		*pdev;
 	void __iomem			*base;
@@ -105,6 +107,7 @@ struct bcm74110_mbox {
 	int				rx_chan;
 	int				rx_irq;
 	struct list_head		rx_svc_init_list;
+	unsigned int			rx_svc_init_count;
 	spinlock_t			rx_svc_list_lock;
 
 	struct mbox_controller		controller;
@@ -148,7 +151,15 @@ static void bcm74110_rx_push_init_msg(struct bcm74110_mbox *mbox, u32 val)
 	msg->msg = val;
 
 	spin_lock(&mbox->rx_svc_list_lock);
+	if (mbox->rx_svc_init_count >= BCM74110_INIT_MSG_MAX) {
+		spin_unlock(&mbox->rx_svc_list_lock);
+		kfree(msg);
+		dev_warn_ratelimited(&mbox->pdev->dev,
+				     "PMC INIT msg list full, dropping message\n");
+		return;
+	}
 	list_add_tail(&msg->list_entry, &mbox->rx_svc_init_list);
+	mbox->rx_svc_init_count++;
 	spin_unlock(&mbox->rx_svc_list_lock);
 }
 
@@ -225,6 +236,7 @@ static int bcm74110_rx_pop_init_msg(struct bcm74110_mbox *mbox, u32 func_type,
 				 list_entry) {
 		if (BCM_MSG_GET_FIELD(msg->msg, FUNC) == func_type) {
 			list_del(&msg->list_entry);
+			mbox->rx_svc_init_count--;
 			found = true;
 			break;
 		}
@@ -248,6 +260,7 @@ static void bcm74110_rx_flush_msg(struct bcm74110_mbox *mbox)
 
 	spin_lock_irqsave(&mbox->rx_svc_list_lock, flags);
 	list_splice_init(&mbox->rx_svc_init_list, &list_temp);
+	mbox->rx_svc_init_count = 0;
 	spin_unlock_irqrestore(&mbox->rx_svc_list_lock, flags);
 
 	list_for_each_entry_safe(msg, msg_tmp, &list_temp, list_entry) {
Signature · 1 line
2.53.0
author maintainer
#467 lore raw

PATCH 466/869 mailbox: mtk-cmdq: Fix runtime PM leak in cmdq_mbox_flush()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 18e3e979826795b62e8916743bec4de660e7cb22 ]

pm_runtime_get_sync() leaves the runtime PM usage counter incremented even when it fails, but cmdq_mbox_flush() returns the error without dropping it. The same happens when the GCE thread does not drain in time and the function bails out with -EFAULT.

Undo the reference on both error paths.

Fixes b0524f7c9635 ("mailbox: mediatek: implement flush function")
---
 drivers/mailbox/mtk-cmdq-mailbox.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/mailbox/mtk-cmdq-mailbox.c +6 -1
index a1360b70b83fb..6e915ec5deaae 100644
@@ -506,8 +506,10 @@ static int cmdq_mbox_flush(struct mbox_chan *chan, unsigned long timeout)
 	int ret;
 
 	ret = pm_runtime_get_sync(cmdq->mbox.dev);
-	if (ret < 0)
+	if (ret < 0) {
+		pm_runtime_put_noidle(cmdq->mbox.dev);
 		return ret;
+	}
 
 	spin_lock_irqsave(&thread->chan->lock, flags);
 	if (list_empty(&thread->task_busy_list))
@@ -544,6 +546,9 @@ static int cmdq_mbox_flush(struct mbox_chan *chan, unsigned long timeout)
 		dev_err(cmdq->mbox.dev, "Fail to wait GCE thread 0x%x done\n",
 			(u32)(thread->base - cmdq->base));
 
+		pm_runtime_mark_last_busy(cmdq->mbox.dev);
+		pm_runtime_put_autosuspend(cmdq->mbox.dev);
+
 		return -EFAULT;
 	}
 	pm_runtime_mark_last_busy(cmdq->mbox.dev);
Signature · 1 line
2.53.0
author maintainer
#468 lore raw

PATCH 467/869 mailbox: qcom-ipcc: Guard against NULL con_priv in send_data()

In reply to Greg Kroah-Hartman

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

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

From: Anup Vishwakarma <[email protected]>

[ Upstream commit 7b3cc361b5942ac600f38e5dff7aed009be34964 ]

qcom_ipcc_mbox_shutdown() clears chan->con_priv with no locking. qcom_ipcc_mbox_send_data() dereferences the same field without checking for NULL first, so a send racing a concurrent shutdown can crash:

  mchan = chan->con_priv;
  ...
  hwirq = qcom_ipcc_get_hwirq(mchan->client_id, mchan->signal_id);

Add the same NULL guard mbox_send_message() already uses for chan->cl, and bail out before dereferencing a cleared con_priv.

To close the remaining race where send_data() reads con_priv a moment before a concurrent shutdown clears it, acquire the spinlock in qcom_ipcc_mbox_shutdown() using the modern guard(spinlock_irqsave) primitive before setting con_priv to NULL.

Fixes d6fbfdbc1274 ("mailbox: qcom-ipcc: Fix IPCC mbox channel exhaustion")
---
 drivers/mailbox/qcom-ipcc.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/mailbox/qcom-ipcc.c +6 -0
index dead907aa7a28..b0b4e40d9202a 100644
@@ -10,6 +10,7 @@
 #include <linux/mailbox_controller.h>
 #include <linux/module.h>
 #include <linux/platform_device.h>
+#include <linux/spinlock.h>
 
 #include <dt-bindings/mailbox/qcom-ipcc.h>
 
@@ -151,6 +152,9 @@ static int qcom_ipcc_mbox_send_data(struct mbox_chan *chan, void *data)
 	struct qcom_ipcc_chan_info *mchan = chan->con_priv;
 	u32 hwirq;
 
+	if (!mchan)
+		return -EINVAL;
+
 	hwirq = qcom_ipcc_get_hwirq(mchan->client_id, mchan->signal_id);
 	writel(hwirq, ipcc->base + IPCC_REG_SEND_ID);
 
@@ -159,6 +163,8 @@ static int qcom_ipcc_mbox_send_data(struct mbox_chan *chan, void *data)
 
 static void qcom_ipcc_mbox_shutdown(struct mbox_chan *chan)
 {
+	guard(spinlock_irqsave)(&chan->lock);
+
 	chan->con_priv = NULL;
 }
 
Signature · 1 line
2.53.0
author maintainer
#469 lore raw

PATCH 468/869 USB: serial: sierra: fix urb leak on write completion

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

[ Upstream commit e7daa54802c566ed3f22e81513f84c8c9197c5d1 ]

Make sure to drop the reference taken by usb_anchor_urb() also on successful submission of delayed write URBs during runtime resume to prevent them from leaking on completion.

Fixes e6929a9020ac ("USB: support for autosuspend in sierra while online")
Cc [email protected] # 2.6.32
Cc Oliver Neukum <[email protected]>
---
 drivers/usb/serial/sierra.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/serial/sierra.c +2 -1
index 741e68e461396..bac926cfee282 100644
@@ -972,12 +972,13 @@ static int sierra_submit_delayed_urbs(struct usb_serial_port *port)
 			intfdata->in_flight--;
 			usb_unanchor_urb(urb);
 			kfree(urb->transfer_buffer);
-			usb_free_urb(urb);
 
 			spin_lock(&portdata->lock);
 			portdata->outstanding_urbs--;
 			spin_unlock(&portdata->lock);
 		}
+
+		usb_put_urb(urb);
 	}
 
 	if (ec)
Signature · 1 line
2.53.0
author maintainer
#470 lore raw

PATCH 469/869 dm-snapshot: fix crash if dm_io_client_create fails

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

[ Upstream commit 829c4d21148a205eca864429e06530319e1f92d5 ]

If dm_io_client_create() fails, it stores error into the ps->io_client variable. The code would try to free it later with dm_io_client_destroy(ps->io_client), causing an invalid pointer dereference. Fix this by setting ps->io_client = NULL.

Assisted-by Claude:claude-opus-5
---
 drivers/md/dm-snap-persistent.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/md/dm-snap-persistent.c +5 -2
index 0dc429eb26924..989f958c229bc 100644
@@ -325,8 +325,11 @@ static int read_header(struct pstore *ps, int *new_snapshot)
 	}
 
 	ps->io_client = dm_io_client_create();
-	if (IS_ERR(ps->io_client))
-		return PTR_ERR(ps->io_client);
+	if (IS_ERR(ps->io_client)) {
+		r = PTR_ERR(ps->io_client);
+		ps->io_client = NULL;
+		return r;
+	}
 
 	r = alloc_area(ps);
 	if (r)
Signature · 1 line
2.53.0
author maintainer
#471 lore raw

PATCH 470/869 arm64/efi: Clear PTE_WRITE when applying EFI_MEMORY_RO

In reply to Greg Kroah-Hartman

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

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

From: Ard Biesheuvel <[email protected]>

[ Upstream commit 215d7b6622733603751f546b9faf9b84b0c281d4 ]

set_permissions() sets PTE_RDONLY for regions that the Memory Attributes Table describes as read-only, but leaves PTE_WRITE set. PTE_WRITE is the DBM bit, so when hardware dirty state management is enabled (TCR_EL1.HD), such a descriptor is writable-clean rather than read-only, and a write by the firmware will be permitted by the hardware (which marks the entry dirty) instead of faulting.

Clear PTE_WRITE as well, as pte_wrprotect() does.

---
 arch/arm64/kernel/efi.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
arch/arm64/kernel/efi.c +7 -1
index 6c371b158b99f..a3c0d5c2e9f74 100644
@@ -116,8 +116,14 @@ static int __init set_permissions(pte_t *ptep, unsigned long addr, void *data)
 	const efi_memory_desc_t *md = spd->md;
 	pte_t pte = __ptep_get(ptep);
 
+	/*
+	 * Clear PTE_WRITE as well: it doubles as the DBM bit, and leaving it
+	 * set would permit the hardware to make the mapping writable again
+	 * when TCR_EL1.HD is set.
+	 */
 	if (md->attribute & EFI_MEMORY_RO)
-		pte = set_pte_bit(pte, __pgprot(PTE_RDONLY));
+		pte = set_pte_bit(clear_pte_bit(pte, __pgprot(PTE_WRITE)),
+				  __pgprot(PTE_RDONLY));
 	if (md->attribute & EFI_MEMORY_XP)
 		pte = set_pte_bit(pte, __pgprot(PTE_PXN));
 	else if (system_supports_bti_kernel() && spd->has_bti)
Signature · 1 line
2.53.0
author maintainer
#472 lore raw

PATCH 471/869 btrfs: zoned: fix block group reference leak in btrfs_repair_one_zone()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 886f1aa6e6b30a02901aa7f140149d466e10a873 ]

btrfs_repair_one_zone() hands the block group reference taken by btrfs_lookup_block_group() over to relocating_repair_kthread(), which drops it. However the return value of kthread_run() is not checked, so when the kernel thread fails to spawn, nothing executes the put and the block group reference is leaked.

Check kthread_run() and drop the reference if the thread failed to start.

Fixes f7ef5287a63d ("btrfs: zoned: relocate block group to repair IO failure in zoned filesystems")
---
 fs/btrfs/volumes.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
fs/btrfs/volumes.c +4 -2
index 200b4e4a07994..a07b5a4d6e4df 100644
@@ -8302,6 +8302,7 @@ static int relocating_repair_kthread(void *data)
 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
 {
 	struct btrfs_block_group *cache;
+	struct task_struct *task;
 
 	if (!btrfs_is_zoned(fs_info))
 		return false;
@@ -8319,8 +8320,9 @@ bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
 		return true;
 	}
 
-	kthread_run(relocating_repair_kthread, cache,
-		    "btrfs-relocating-repair");
+	task = kthread_run(relocating_repair_kthread, cache, "btrfs-relocating-repair");
+	if (IS_ERR(task))
+		btrfs_put_block_group(cache);
 
 	return true;
 }
Signature · 1 line
2.53.0
author maintainer
#473 lore raw

PATCH 472/869 btrfs: return -ENOTTY for unknown ioctls on the control device

In reply to Greg Kroah-Hartman

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

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

From: Hengyu Liang <[email protected]>

[ Upstream commit 9985f1643ac3f8595862e2f82108f0ccae4cf959 ]

Commit 5ab2b180884c ("btrfs: factor out validation of btrfs_ioctl_vol_args::name") made btrfs_control_ioctl() store the result of btrfs_check_ioctl_vol_args_path() in ret before it looks at the command.

However, ret is initialized to -ENOTTY and the switch has no default case, so this initial value was what an unknown command returned. As of now, every unknown ioctl on /dev/btrfs-control returns 0. A tool that tries a control ioctl which the running kernel does not have is told that the ioctl succeeded.

The issue can be reproduced with a simple C program, run as root:

    #include <fcntl.h>
    #include <stdio.h>
    #include <sys/ioctl.h>

    int main(void)
    {
            static char buf[4096];
            int fd = open("/dev/btrfs-control", O_RDWR);

            if (ioctl(fd, TCGETS, buf) < 0)
                    perror("ioctl");
            else
                    printf("ioctl succeeded\n");
            return 0;
    }

Before commit 5ab2b180884c ("btrfs: factor out validation of btrfs_ioctl_vol_args::name"), the result is:

ioctl: Inappropriate ioctl for device

After that commit, the result is:

ioctl succeeded

This patch will add a default case that returns -ENOTTY.

Fixes 5ab2b180884c ("btrfs: factor out validation of btrfs_ioctl_vol_args::name")
---
 fs/btrfs/super.c | 3 +++
 1 file changed, 3 insertions(+)
fs/btrfs/super.c +3 -0
index 6cc4fe2ccd8a7..61a0575fd162a 100644
@@ -2284,6 +2284,9 @@ static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
 		ret = btrfs_ioctl_get_supported_features((void __user*)arg);
 		break;
+	default:
+		ret = -ENOTTY;
+		break;
 	}
 
 out:
Signature · 1 line
2.53.0
author maintainer
#474 lore raw

PATCH 473/869 mtd: rawnand: qcom: fix read location register usage in config_nand_cw_read()

In reply to Greg Kroah-Hartman

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

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

From: Gabor Juhos <[email protected]>

[ Upstream commit 94623942a66e031826756f9c92dbde9a12e2b4d2 ]

On QPIC v2 controllers, when the last codeword is being read, the read location values must be programmed into the READ_LOCATION_LAST_CW_* registers. Prior to commit 8c52932da5e6 ("mtd: rawnand: qcom: cleanup qcom_nandc driver"), the config_nand_cw_read() function did it right, but since then it always writes the read location values to the READ_LOCATION_* registers even if the actual codeword is the last one.

Change the function to always configure the registers corresponding to the actual codeword to restore the correct behaviour.

Fixes 8c52932da5e6 ("mtd: rawnand: qcom: cleanup qcom_nandc driver")
---
 drivers/mtd/nand/raw/qcom_nandc.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/mtd/nand/raw/qcom_nandc.c +5 -3
index 4dd6f1a4e7978..b469c01aacf97 100644
@@ -328,14 +328,16 @@ config_nand_cw_read(struct nand_chip *chip, bool use_ecc, int cw)
 {
 	struct qcom_nand_controller *nandc = get_qcom_nand_controller(chip);
 	struct nand_ecc_ctrl *ecc = &chip->ecc;
-
 	__le32 *reg = &nandc->regs->read_location0;
+	int reg_base = NAND_READ_LOCATION_0;
 
-	if (nandc->props->qpic_version2 && qcom_nandc_is_last_cw(ecc, cw))
+	if (nandc->props->qpic_version2 && qcom_nandc_is_last_cw(ecc, cw)) {
 		reg = &nandc->regs->read_location_last0;
+		reg_base = NAND_READ_LOCATION_LAST_CW_0;
+	}
 
 	if (nandc->props->supports_bam)
-		qcom_write_reg_dma(nandc, reg, NAND_READ_LOCATION_0, 4, NAND_BAM_NEXT_SGL);
+		qcom_write_reg_dma(nandc, reg, reg_base, 4, NAND_BAM_NEXT_SGL);
 
 	qcom_write_reg_dma(nandc, &nandc->regs->cmd, NAND_FLASH_CMD, 1, NAND_BAM_NEXT_SGL);
 	qcom_write_reg_dma(nandc, &nandc->regs->exec, NAND_EXEC_CMD, 1, NAND_BAM_NEXT_SGL);
Signature · 1 line
2.53.0
author maintainer
#475 lore raw

PATCH 474/869 mtd: parsers: qcom: fix offset/size overflow on large partitions

In reply to Greg Kroah-Hartman

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

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

From: Weigang He <[email protected]>

[ Upstream commit 2f7fa8d90694d21dce68ceabd8383252b111cfea ]

In parse_qcomsmem_part() the partition offset and size are computed as

	parts[j].offset = le32_to_cpu(pentry->offset) * mtd->erasesize;
	parts[j].size   = le32_to_cpu(pentry->length) * mtd->erasesize;

Both le32_to_cpu() and mtd->erasesize are 32-bit (u32). The multiply is therefore evaluated in 32-bit arithmetic and the product is truncated to 32 bits before being widened and stored into the 64-bit (u64) parts[j].offset / parts[j].size fields, so the 64-bit destinations are never used at their full width.

The SMEM partition table is firmware-provided and the per-entry offset and length are not bounds-checked against the device geometry (only numparts is capped). On a sufficiently large flash, a partition whose (offset|length) * erasesize is >= 2^32 gets a silently truncated offset/size and is mapped to the wrong region of the master MTD, which can overlap or extend into an unintended area.

Cast one operand to u64 so the multiplication is performed in 64-bit and the result fits the 64-bit fields without truncation.

Found by static analysis tool CodeQL.

Fixes 803eb124e1a6 ("mtd: parsers: Add Qcom SMEM parser")
Assisted-by LLM codeql
---
 drivers/mtd/parsers/qcomsmempart.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/mtd/parsers/qcomsmempart.c +2 -2
index 4311b89d8df00..b12d87c3b0232 100644
@@ -143,9 +143,9 @@ static int parse_qcomsmem_part(struct mtd_info *mtd,
 			*c = tolower(*c);
 
 		parts[j].name = name;
-		parts[j].offset = le32_to_cpu(pentry->offset) * mtd->erasesize;
+		parts[j].offset = (u64)le32_to_cpu(pentry->offset) * mtd->erasesize;
 		parts[j].mask_flags = pentry->attr;
-		parts[j].size = le32_to_cpu(pentry->length) * mtd->erasesize;
+		parts[j].size = (u64)le32_to_cpu(pentry->length) * mtd->erasesize;
 		pr_debug("%d: %s offs=0x%08x size=0x%08x attr:0x%08x\n",
 			 i, pentry->name, le32_to_cpu(pentry->offset),
 			 le32_to_cpu(pentry->length), pentry->attr);
Signature · 1 line
2.53.0
author maintainer
#476 lore raw

PATCH 475/869 xprtrdma: prevent disconnect feedback during endpoint teardown

In reply to Greg Kroah-Hartman

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

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

From: Tim Menninger <[email protected]>

[ Upstream commit 0b5bb4e586f7b0a449f4d90a524f76a3be5db355 ]

xprt_autoclose() clears XPRT_CLOSE_WAIT before invoking the transport's ->close() operation. For RPC/RDMA, ->close() calls rpcrdma_xprt_disconnect(), which disconnects the RDMA CM endpoint and drains its QP.

Since commit 31e62d25b5b8 ("xprtrdma: Simplify RPC wake-ups on connect"), RDMA_CM_EVENT_DISCONNECTED requests a SUNRPC transport disconnect. Today that path, along with failed completion handling, reaches xprt_force_disconnect() through rpcrdma_force_disconnect().

Commit c487eb7d8e41 ("xprtrdma: Clean up disconnect") later added re_force_disconnect to ensure that multiple failure indications request only one SUNRPC disconnect. However, the gate remains open when SUNRPC itself begins endpoint teardown.

If re_force_disconnect is still clear, either a CM disconnect event or a completion error can set XPRT_CLOSE_WAIT again while the current close is in progress. When the transport send lock is subsequently released, xprt_clear_locked() observes XPRT_CLOSE_WAIT and queues another autoclose.

Requesting a disconnect this way is necessary when a connection is lost unexpectedly, but not when the event was generated by rpcrdma_xprt_disconnect() itself. In that case SUNRPC is already committed to closing the transport.

Mark re_force_disconnect before initiating local endpoint teardown so that CM events and completion errors caused by that teardown cannot request another close. An unexpected error that wins the race before local endpoint teardown begins can still request a disconnect normally.

Use a fully ordered exchange so that the gate is globally closed before rdma_disconnect() can transition the QP to error and generate the callbacks that the gate suppresses.

In 30-second traces of a sustained recovery loop, without this change there were 7,693 xprt_force_disconnect() calls, 6,267 SUNRPC autocloses, and 172,892 receive-side IB_WC_WR_FLUSH_ERR completions. With this change, the same tracepoints recorded 3,512 xprt_force_disconnect() calls, 3,212 autocloses, and 131,287 receive-side flush completions. Thus QP teardown continues to produce flushed completions, but closing the disconnect gate before teardown substantially reduces their feedback into the SUNRPC close path.

Fixes 31e62d25b5b8 ("xprtrdma: Simplify RPC wake-ups on connect")
---
 net/sunrpc/xprtrdma/verbs.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
net/sunrpc/xprtrdma/verbs.c +6 -3
index 8449107b2a095..111c415f1aeda 100644
@@ -114,9 +114,9 @@ static void rpcrdma_xprt_drain(struct rpcrdma_xprt *r_xprt)
 	rpcrdma_ep_put(ep);
 }
 
-/* Ensure xprt_force_disconnect() is invoked exactly once when a
- * connection is closed or lost. (The important thing is it needs
- * to be invoked "at least" once).
+/* Ensure xprt_force_disconnect() is invoked at most once for an
+ * unexpected endpoint failure. Local endpoint teardown closes this
+ * gate before it can generate CM events and flushed completions.
  */
 void rpcrdma_force_disconnect(struct rpcrdma_ep *ep)
 {
@@ -587,6 +587,9 @@ void rpcrdma_xprt_disconnect(struct rpcrdma_xprt *r_xprt)
 	if (!ep)
 		return;
 
+	/* Prevent teardown-generated events from requesting another close. */
+	atomic_xchg(&ep->re_force_disconnect, 1);
+
 	id = ep->re_id;
 	rc = rdma_disconnect(id);
 	trace_xprtrdma_disconnect(r_xprt, rc);
Signature · 1 line
2.53.0
author maintainer
#477 lore raw

PATCH 476/869 xprtrdma: trim head iovec when the payload arrives via a Write chunk

In reply to Greg Kroah-Hartman

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

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

From: Yongjian Mu <[email protected]>

[ Upstream commit 9ee534a75912361308b1f956bc3e7895a082a422 ]

The upper layer sets rq_rcv_buf.head[0].iov_len from its estimate of the reply header size. For RPCSEC_GSS that estimate includes auth->au_ralign, which gss_create_new() initializes to GSS_VERF_SLACK >> 2 (25 XDR words, or 100 bytes) and which is corrected to the real verifier size only after the first reply on that rpc_auth has been unwrapped. In this case, the krb5 MIC verifier is 36 bytes, so every request encoded before the first reply completes has a head that is 64 bytes too long.

On TCP this is harmless: xdr_realign_pages() moves the excess head bytes, which are genuine reply data, into the page list. With RPC-over-RDMA and a Write chunk (sec=krb5, i.e. RPC_GSS_SVC_NONE, where DDP is allowed), the payload has already been placed directly into the page list, and the receive buffer holds only the inline part of the reply. rpcrdma_inline_fixup() clamps its local copy of the head length to the inline length but leaves head.iov_len untouched, so xdr_realign_pages() still sees iov_len > cur and shifts whatever lies past the inline reply in the receive buffer into the front of the directly-placed payload:

rpc_xdr_recvfrom: head=[...,196] page=524288 tail=[...,64]
rpc_xdr_alignment: nfsv4 READ offset=132 copied=64

The first 64 bytes returned by each such READ are incorrect (zeroed, or shifted right by 64 bytes depending on the kernel's xdr_shrink_bufhead() implementation). This is readily hit with pNFS flexfiles over RDMA and sec=krb5: the per-DS rpc_clnt gets a fresh rpc_auth whose first RPC is a large READ. Reads following the first completed reply return the expected data.

Commit cb0ae1fbb2f5 ("xprtrdma: Do not update {head, tail}.iov_len in rpcrdma_inline_fixup()") removed the head-length correction while fixing the handling of pure-inline krb5p replies.

When a Write chunk conveyed the payload, trim head.iov_len (in both rq_rcv_buf and rq_private_buf, which call_decode() expects to match) to the inline length actually received so that the XDR layer does not realign the page list. These READ replies have no trailing inline fields, and the payload is already in the page list, so the upper layer's head estimate can be safely reduced. Reduce buflen by the same amount to avoid treating unused head capacity as additional tail capacity. Pure inline replies and Reply chunk replies are unchanged.

Tested on Linux 6.8.0 and 7.3-rc4 with NFSv4.1 pNFS flexfiles over RPC/RDMA and sec=krb5.

Fixes cb0ae1fbb2f5 ("xprtrdma: Do not update {head, tail}.iov_len in rpcrdma_inline_fixup()")
---
 net/sunrpc/xprtrdma/rpc_rdma.c | 27 +++++++++++++++++++++++----
 1 file changed, 23 insertions(+), 4 deletions(-)
net/sunrpc/xprtrdma/rpc_rdma.c +23 -4
index e2694fb03ba1b..091b8cb415ec7 100644
@@ -1033,12 +1033,16 @@ void rpcrdma_reset_cwnd(struct rpcrdma_xprt *r_xprt)
  * @rqst: controlling RPC request
  * @srcp: points to RPC message payload in receive buffer
  * @copy_len: remaining length of receive buffer content
- * @pad: Write chunk pad bytes needed (zero for pure inline)
+ * @writelist: bytes conveyed by the Write chunk (zero for pure inline)
  *
  * The upper layer has set the maximum number of bytes it can
  * receive in each component of rq_rcv_buf. These values are set in
  * the head.iov_len, page_len, tail.iov_len, and buflen fields.
  *
+ * For READ replies with a Write chunk, the payload is already in
+ * the page list. An overestimated head length and buflen can be
+ * reduced without moving reply data.
+ *
  * Unlike the TCP equivalent (xdr_partial_copy_from_skb), in
  * many cases this function simply updates iov_base pointers in
  * rq_rcv_buf to point directly to the received reply data, to
@@ -1047,13 +1051,16 @@ void rpcrdma_reset_cwnd(struct rpcrdma_xprt *r_xprt)
  * Returns the count of bytes which had to be memcopied.
  */
 static unsigned long
-rpcrdma_inline_fixup(struct rpc_rqst *rqst, char *srcp, int copy_len, int pad)
+rpcrdma_inline_fixup(struct rpc_rqst *rqst, char *srcp, int copy_len,
+		     u32 writelist)
 {
 	unsigned long fixup_copy_count;
 	int i, npages, curlen;
 	char *destp;
 	struct page **ppages;
 	int page_base;
+	int pad = writelist & 3;
+	unsigned int delta;
 
 	/* The head iovec is redirected to the RPC reply message
 	 * in the receive buffer, to avoid a memcopy.
@@ -1065,8 +1072,20 @@ rpcrdma_inline_fixup(struct rpc_rqst *rqst, char *srcp, int copy_len, int pad)
 	 * head.iov_len bytes are copied into the page list.
 	 */
 	curlen = rqst->rq_rcv_buf.head[0].iov_len;
-	if (curlen > copy_len)
+	if (curlen > copy_len) {
+		/* These READ replies have no inline fields after the payload.
+		 * Trim the head without moving the directly-placed data.
+		 */
+		if (writelist) {
+			delta = curlen - copy_len;
+
+			rqst->rq_rcv_buf.head[0].iov_len = copy_len;
+			rqst->rq_private_buf.head[0].iov_len = copy_len;
+			rqst->rq_rcv_buf.buflen -= delta;
+			rqst->rq_private_buf.buflen -= delta;
+		}
 		curlen = copy_len;
+	}
 	srcp += curlen;
 	copy_len -= curlen;
 
@@ -1294,7 +1313,7 @@ rpcrdma_decode_msg(struct rpcrdma_xprt *r_xprt, struct rpcrdma_rep *rep,
 	base = (char *)xdr_inline_decode(xdr, 0);
 	rpclen = xdr_stream_remaining(xdr);
 	r_xprt->rx_stats.fixup_copy_count +=
-		rpcrdma_inline_fixup(rqst, base, rpclen, writelist & 3);
+		rpcrdma_inline_fixup(rqst, base, rpclen, writelist);
 
 	r_xprt->rx_stats.total_rdma_reply += writelist;
 	return rpclen + xdr_align_size(writelist);
Signature · 1 line
2.53.0
author maintainer
#478 lore raw

PATCH 477/869 PCI: Avoid D3 on PLX PEX 8532/8533/8548 downstream ports

In reply to Greg Kroah-Hartman

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

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

From: Imre Kaloz <[email protected]>

[ Upstream commit 8e923e51892c7da91687dd5b8081ddb1f0fb395a ]

Runtime PM suspends an idle downstream port of a PLX/Broadcom PEX 8532/8533/8548 switch to D3hot, but that takes the whole switch down with it: any device behind another port of the same switch then faults with a fatal bus error on its next access, e.g. mptsas probe on a Sun Ultra 45.

This surfaced on sparc64 once commit a5fb3ff63287 ("PCI: Allow PCI bridges to go to D3Hot on all non-x86") let bridges enter D3hot. Keep these downstream ports out of D3 by setting PCI_DEV_FLAGS_NO_D3.

Fixes a5fb3ff63287 ("PCI: Allow PCI bridges to go to D3Hot on all non-x86")
---
 drivers/pci/quirks.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
drivers/pci/quirks.c +18 -0
index d29ff1da29b17..812b01d24fc47 100644
@@ -2386,6 +2386,24 @@ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050,
 DECLARE_PCI_FIXUP_HEADER(0x1402, 0x2000, quirk_plx_pci9050);
 DECLARE_PCI_FIXUP_HEADER(0x1402, 0x2600, quirk_plx_pci9050);
 
+/*
+ * An idle downstream port of a PLX/Broadcom PEX 8532/8533/8548 switch
+ * autosuspends into D3hot, and that takes the whole switch down with
+ * it -- any device behind another port of the same switch then sees a
+ * fatal, non-recoverable bus fault on its next access. Keep these
+ * ports out of D3 entirely.
+ */
+static void quirk_plx_pex_no_d3(struct pci_dev *dev)
+{
+	if (pci_pcie_type(dev) == PCI_EXP_TYPE_DOWNSTREAM) {
+		dev->dev_flags |= PCI_DEV_FLAGS_NO_D3;
+		pci_info(dev, "avoiding D3 on this downstream port\n");
+	}
+}
+DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_PLX, 0x8532, quirk_plx_pex_no_d3);
+DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_PLX, 0x8533, quirk_plx_pex_no_d3);
+DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_PLX, 0x8548, quirk_plx_pex_no_d3);
+
 static void quirk_netmos(struct pci_dev *dev)
 {
 	unsigned int num_parallel = (dev->subsystem_device & 0xf0) >> 4;
Signature · 1 line
2.53.0
author maintainer
#479 lore raw

PATCH 478/869 mm/damon/sysfs-schemes: read sysfs_filter->addr_range only once

In reply to Greg Kroah-Hartman

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

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

From: SJ Park <[email protected]>

[ Upstream commit 60e58be27d5e16d35e0728298f994dcae9f208a5 ]

Patch series "mm/damon: move damos filter range arguments validation to core".

DAMOS filter range arguments are being validated in the DAMON sysfs interface. Some of those have minor time-of-check to time-of-use (TOCTOU) bugs. In future, other callers might have duplicated validations with similar bugs.

Fix the bugs and further refactor the code to move the validation to the core layer. Also add kunit test cases for the validations.

Patches 1 and 2 fix the existing TOCTOU bugs. Patches 3 and 4 adds the validation in the core layer. Patch 5 drops the replicated validation in DAMON sysfs interface. Patch 6 further cleanup the code. Patches 7 and 8 extends kunit tests to test the validation.

This patch (of 8):

DAMON sysfs interface reads the user-provided address range arguments for addr type DAMOS filter twice. Once for validation, and once again for assignments to the variable that will be passed to the core layer. If the user updates the argument in parallel, an invalid address range could be passed to the core layer. Avoid it by doing the assignments first, and then validating the assigned variables before passing those to the core layer.

User impact of the bug should be trivial. From the core layer's perspective, the invalid address range is not really invalid. It just works as having a weird address range. No critical issues such as a crash or a leak could happen. And sane users ain't do such parallel arguments update anyway. If they do, such racy behavior is arguably somewhat expected and deserved. That said, there is no reason to keep such races.

Fixes 2f1abcfccd86 ("mm/damon/sysfs-schemes: support address range type DAMOS filter")
Cc Brendan Higgins <[email protected]>
Cc David Gow <[email protected]>
Cc Usama Arif <[email protected]>
---
 mm/damon/sysfs-schemes.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
mm/damon/sysfs-schemes.c +3 -3
index 37e0a8bef4b1f..e95cddca0a10d 100644
@@ -2484,12 +2484,12 @@ static int damon_sysfs_add_scheme_filters(struct damos *scheme,
 				return err;
 			}
 		} else if (filter->type == DAMOS_FILTER_TYPE_ADDR) {
-			if (sysfs_filter->addr_range.end <
-					sysfs_filter->addr_range.start) {
+			filter->addr_range = sysfs_filter->addr_range;
+			if (filter->addr_range.end <
+					filter->addr_range.start) {
 				damos_destroy_filter(filter);
 				return -EINVAL;
 			}
-			filter->addr_range = sysfs_filter->addr_range;
 		} else if (filter->type == DAMOS_FILTER_TYPE_TARGET) {
 			filter->target_idx = sysfs_filter->target_idx;
 		} else if (filter->type == DAMOS_FILTER_TYPE_HUGEPAGE_SIZE) {
Signature · 1 line
2.53.0
author maintainer
#480 lore raw

PATCH 479/869 mm/madvise: reclaim isolated folios if PTE restart fails

In reply to Greg Kroah-Hartman

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

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

From: Gregory Price <[email protected]>

[ Upstream commit 5445a6359d717354dd76d509b8e693f13403ec61 ]

MADV_PAGEOUT collects isolated folios on a local list before reclaiming them after the PTE walk. The reschedule path drops the PTE lock and then restarts the mapping with pte_offset_map_lock().

A concurrent operation can remove or replace the PTE table while the lock is dropped, causing pte_offset_map_lock() to return NULL. Returning directly in that case bypasses reclaim_pages(), leaving the collected folios off the LRU with elevated references.

This results in a permanent memory leak. nr_isolated_anon increases reliably and does not decrease when the process dies.

Route the failure through the existing cleanup path so any isolated folios are reclaimed or put back.

Simplest userland pseudo-code reproducer:

p = mmap(PMD_SIZE, ANONYMOUS);
touch_every_page(p, PMD_SIZE);
parallel {
while (1) madvise(p, PMD_SIZE, MADV_PAGEOUT);

   while (1) {
       madvise(p, PMD_SIZE, MADV_DONTNEED);
       touch_every_page(p, PMD_SIZE);

}
}

Reproduced in qemu trivially with some explicit widening of the race window.

Fixes b2f557a21bc8 ("mm/madvise: add cond_resched() in madvise_cold_or_pageout_pte_range()")
Assisted-by LLM
Cc David Hildenbrand <[email protected]>
Cc Jann Horn <[email protected]>
Cc Jiexun Wang <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
---
 mm/madvise.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/madvise.c +2 -1
index b8c25fea4fab9..6b62e01f31911 100644
@@ -460,7 +460,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 restart:
 	start_pte = pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
 	if (!start_pte)
-		return 0;
+		goto out;
 	flush_tlb_batched_pending(mm);
 	arch_enter_lazy_mmu_mode();
 	for (; addr < end; pte += nr, addr += nr * PAGE_SIZE) {
@@ -564,6 +564,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 			folio_deactivate(folio);
 	}
 
+out:
 	if (start_pte) {
 		arch_leave_lazy_mmu_mode();
 		pte_unmap_unlock(start_pte, ptl);
Signature · 1 line
2.53.0
author maintainer
#481 lore raw

PATCH 480/869 mm/madvise: use folio_trylock() in the cold/pageout PMD split

In reply to Greg Kroah-Hartman

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

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

From: Gregory Price <[email protected]>

[ Upstream commit 5a6c9cf117fca3c38a98fb2a2d5549795c8b0b73 ]

MADV_COLD or MADV_PAGEOUT over part of a PMD splits the THP in madvise_cold_or_pageout_pte_range(). Two threads doing that to the same THP create spurious failures.

CPU0 CPU1
---- ----
folio_get()
spin_unlock(ptl)
folio_lock()
folio_get() spin_unlock(ptl) folio_lock() <- blocks, keeps its ref
split_folio()

    folio_expected_ref_count(folio) != folio_ref_count(folio) - 1
    -EAGAIN

CPU1 cannot drop its reference until it gets the lock CPU0 holds, so CPU0's split always fails. folio_trylock() makes CPU1 leave without ever taking a reference. The PTE branch of this same function already does this, as do madvise_free_pte_range() and madvise_free_huge_pmd().

Reproducer: 400 rounds of eight threads calling MADV_COLD on half of each of eight THPs, re-formed with MADV_COLLAPSE between rounds. From /proc/vmstat:

thp_split_page thp_split_page_failed
before 3186 860
after 3200 0

The short before count is rounds where every thread failed and the advice was dropped for that THP entirely.

On failure the walker returns 0 and nothing retries. The PMD path becomes best effort when the folio lock is held elsewhere - same as the PTE path.

---
 mm/madvise.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/madvise.c +2 -1
index 6b62e01f31911..505a580cd9c4c 100644
@@ -415,9 +415,10 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 		if (next - addr != HPAGE_PMD_SIZE) {
 			int err;
 
+			if (!folio_trylock(folio))
+				goto huge_unlock;
 			folio_get(folio);
 			spin_unlock(ptl);
-			folio_lock(folio);
 			err = split_folio(folio);
 			folio_unlock(folio);
 			folio_put(folio);
Signature · 1 line
2.53.0
author maintainer
#482 lore raw

PATCH 481/869 mm/page_alloc: do not boost watermarks in kdump capture kernels

In reply to Greg Kroah-Hartman

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

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

From: Yuanhe Shu <[email protected]>

[ Upstream commit 331f94007d79b3c02d3098eea469a92aea3efc2c ]

A watermark boost is not confined to one watermark: wmark_pages() adds it to min, low and high alike, so every watermark check sees it, including should_reclaim_retry() and the last ditch ALLOC_WMARK_HIGH attempt in __alloc_pages_may_oom(). Once the boost exceeds the memory still free the allocator gives up and invokes the OOM killer, and a capture kernel that is still booting has nothing to kill: the boot panics and the vmcore is lost.

Seen on an arm64 machine with 64K pages, CONFIG_PAGE_BLOCK_MAX_ORDER=10 (pageblock = 64M) and crashkernel=512M, running a distribution kernel based on 7.0.14. A high order UNMOVABLE allocation fell back to a MOVABLE pageblock while the capture kernel was still in do_initcalls():

Node 0 DMA free:68096kB boost:65536kB min:68160kB low:68800kB high:69440kB managed:479168kB Out of memory and no killable processes...

  Kernel panic - not syncing: System is deadlocked on memory

The zone was not short of memory. Subtracting the boost gives min:2624kB low:3264kB high:3904kB, so the 68096kB still free sat 17 times above the high watermark and the allocator would not even have entered its slow path. The boost supplied 65536kB of the 68160kB min and by itself put the zone 64kB under water. It is that large because boost_watermark() clamps it with max(pageblock_nr_pages, max_boost); watermark_boost_factor alone would have allowed 5824kB.

Commit 14f69140ff9c ("mm: limit boost_watermark on small zones") already tried to protect capture kernels, but it infers them from the zone size and skips the boost only below four pageblocks. arm64 64K pageblocks were 512M then, so the guard reached zones up to 2G; CONFIG_PAGE_BLOCK_MAX_ORDER can cap them at 64M, which shrinks the guard to zones under 256M and lets this 468M zone through.

kdump is a property of the kernel, not of the zone, so test for it directly. A capture kernel exits within seconds and never uses the fragmentation avoidance the boost buys. Normal kernels are unaffected:
the size based check still covers their genuinely tiny zones.

Passing sysctl.vm.watermark_boost_factor=0 to the capture kernel does not cover this window: sysctl.* parameters are written through procfs by do_sysctl_args(), which runs after do_initcalls() where the panic above happened, and watermark_boost_factor has no early_param of its own.

Fixes 1c30844d2dfe ("mm: reclaim small amounts of memory when an external fragmentation event occurs")
Cc Henry Willard <[email protected]>
Cc Brendan Jackman <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Zi Yan <[email protected]>
Cc <[email protected]> # v5.0
---
 mm/page_alloc.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
mm/page_alloc.c +10 -2
index ff863a87f2b85..b866357339c56 100644
@@ -38,6 +38,7 @@
 #include <linux/vmstat.h>
 #include <linux/fault-inject.h>
 #include <linux/compaction.h>
+#include <linux/crash_dump.h>
 #include <trace/events/kmem.h>
 #include <trace/events/oom.h>
 #include <linux/prefetch.h>
@@ -2206,10 +2207,17 @@ static inline bool boost_watermark(struct zone *zone)
 
 	if (!watermark_boost_factor)
 		return false;
+
+	/*
+	 * A kdump capture kernel exits before a boost can pay off, while
+	 * the raised watermark can exceed the memory left for the dump.
+	 */
+	if (is_kdump_kernel())
+		return false;
+
 	/*
 	 * Don't bother in zones that are unlikely to produce results.
-	 * On small machines, including kdump capture kernels running
-	 * in a small area, boosting the watermark can cause an out of
+	 * On small machines, boosting the watermark can cause an out of
 	 * memory situation immediately.
 	 */
 	if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
Signature · 1 line
2.53.0
author maintainer
#483 lore raw

PATCH 482/869 mm/hugetlb_cgroup: move per-node usage on cross node migration

In reply to Greg Kroah-Hartman

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

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

From: Hongfu Li <[email protected]>

[ Upstream commit fe0ba1909c59660f078560f5130e7af7c6004f12 ]

Patch series "mm/hugetlb_cgroup: move the per-node usage along with the folio", v2.

The per-node usage reported by hugetlb.<size>.numa_stat is accounted against folio_nid() in __hugetlb_cgroup_commit_charge() and __hugetlb_cgroup_uncharge_folio(), so it is only correct while a folio stays charged on the same node and in the same hugetlb_cgroup.

Two paths move a folio which stays charged, and neither moves the usage with it. hugetlb_cgroup_migrate() only moves the hugetlb_cgroup pointers of a folio migrated to another node, and hugetlb_cgroup_move_parent() only moves the page_counter charges and the hugetlb_cgroup pointer of the folios of a dying cgroup. In both cases the node (or cgroup) which was charged keeps a usage which never goes away, while the node (or cgroup) which ends up uncharging the folio underflows as soon as the folio is freed.

Patch 1/2 moves the usage along with the folio on cross node migration, patch 2/2 does the same for the folios a dying cgroup reparents.

This patch (of 2):

hugetlb.<size>.numa_stat uses folio_nid() to account usage in __hugetlb_cgroup_commit_charge() and __hugetlb_cgroup_uncharge_folio(). hugetlb_cgroup_migrate() only moves hugetlb_cgroup pointers, leaving per-node usage behind on the source node during cross-node migration.

When the migrated folio gets uncharged, we subtract usage from the destination node counter. This creates stale usage on the source node and unsigned long counter underflow on the destination node. The hugetlb.<size>.numa_stat interface exposes these incorrect per-node usage values to userspace.

Add a hugetlb_cgroup_move_usage() helper which moves the usage from the old node to the new node, and call it from hugetlb_cgroup_migrate().

Fixes f47761999052 ("hugetlb: add hugetlb.*.numa_stat file")
Cc Colin Ian King <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Kees Cook <[email protected]>
Cc Mina Almasry <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Shakeel Butt <[email protected]>
---
 mm/hugetlb_cgroup.c | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
mm/hugetlb_cgroup.c +31 -0
index b6537a3e4f62c..00b20c4ff222f 100644
@@ -187,6 +187,34 @@ static void hugetlb_cgroup_css_free(struct cgroup_subsys_state *css)
 	hugetlb_cgroup_free(hugetlb_cgroup_from_css(css));
 }
 
+static void hugetlb_cgroup_move_usage(struct hugetlb_cgroup *from,
+				      struct hugetlb_cgroup *to,
+				      struct folio *from_folio,
+				      struct folio *to_folio)
+{
+	int idx = hstate_index(folio_hstate(from_folio));
+	unsigned long nr_pages = folio_nr_pages(from_folio);
+	int from_nid = folio_nid(from_folio);
+	int to_nid = folio_nid(to_folio);
+	unsigned long usage;
+
+	lockdep_assert_held(&hugetlb_lock);
+
+	if (!from || !to)
+		return;
+
+	if (from == to && from_nid == to_nid)
+		return;
+
+	usage = from->nodeinfo[from_nid]->usage[idx];
+	if (WARN_ON_ONCE(usage < nr_pages))
+		return;
+	WRITE_ONCE(from->nodeinfo[from_nid]->usage[idx], usage - nr_pages);
+
+	usage = to->nodeinfo[to_nid]->usage[idx];
+	WRITE_ONCE(to->nodeinfo[to_nid]->usage[idx], usage + nr_pages);
+}
+
 /*
  * Should be called with hugetlb_lock held.
  * Since we are holding hugetlb_lock, pages cannot get moved from
@@ -914,6 +942,9 @@ void hugetlb_cgroup_migrate(struct folio *old_folio, struct folio *new_folio)
 	/* move the h_cg details to new cgroup */
 	set_hugetlb_cgroup(new_folio, h_cg);
 	set_hugetlb_cgroup_rsvd(new_folio, h_cg_rsvd);
+
+	hugetlb_cgroup_move_usage(h_cg, h_cg, old_folio, new_folio);
+
 	list_move(&new_folio->lru, &h->hugepage_activelist);
 	spin_unlock_irq(&hugetlb_lock);
 }
Signature · 1 line
2.53.0
author maintainer
#484 lore raw

PATCH 483/869 mm/hugetlb_cgroup: move per-node usage on cgroup reparenting

In reply to Greg Kroah-Hartman

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

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

From: Hongfu Li <[email protected]>

[ Upstream commit 23fac055c21176f66ed453394b533bdfc00f7fba ]

hugetlb_cgroup_css_offline() hands the folios of a dying cgroup over to its parent with hugetlb_cgroup_move_parent(), which moves the page_counter charges and the hugetlb_cgroup pointer of the folio but not its per-node usage. The parent's hugetlb.<size>.numa_stat is short by that usage while they are charged, and underflows once they are freed, exposing incorrect per-node usage values to userspace.

Move the per-node usage to the parent as well. The folios keep their node here, so only the cgroup which holds the usage changes.

Fixes f47761999052 ("hugetlb: add hugetlb.*.numa_stat file")
Cc Colin Ian King <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Kees Cook <[email protected]>
Cc Mina Almasry <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Shakeel Butt <[email protected]>
---
 mm/hugetlb_cgroup.c | 2 ++
 1 file changed, 2 insertions(+)
mm/hugetlb_cgroup.c +2 -0
index 00b20c4ff222f..7c59c20d68574 100644
@@ -249,6 +249,8 @@ static void hugetlb_cgroup_move_parent(int idx, struct hugetlb_cgroup *h_cg,
 	/* Take the pages off the local counter */
 	page_counter_cancel(counter, nr_pages);
 
+	hugetlb_cgroup_move_usage(h_cg, parent, folio, folio);
+
 	set_hugetlb_cgroup(folio, parent);
 out:
 	return;
Signature · 1 line
2.53.0
author maintainer
#485 lore raw

PATCH 484/869 mm/shmem: report RCU-tasks quiescent states while undoing a range

In reply to Greg Kroah-Hartman

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

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

From: Breno Leitao <[email protected]>

[ Upstream commit ebd1a08c192109c83a87ddf42793ed6283180faf ]

This shows up in the Meta fleet on ftruncate() of large tmpfs files:

  INFO: rcu_tasks detected stalls on tasks:
  00000000752fd185: .. nvcsw: 59455/59455 holdout: 1 idle_cpu: -1/0
  task:rocksdb:bottom  state:R  running task
    __folio_split
    find_get_entry
    find_get_entries
    truncate_inode_partial_folio
    shmem_undo_range
    shmem_setattr
    notify_change
    do_ftruncate
    __x64_sys_ftruncate
    do_syscall_64

shmem_undo_range() walks the whole of the requested range in folio_batch sized steps, twice, and its two cond_resched() calls are the only reschedule points in that walk.

cond_resched() is not an RCU-tasks quiescent state. Use cond_resched_tasks_rcu_qs() at both points so the walk reports an RCU-tasks quiescent state as it proceeds.

Fixes 8315f42295d2 ("rcu: Add call_rcu_tasks()")
Cc Baolin Wang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc "Paul E . McKenney" <[email protected]>
---
 mm/shmem.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/shmem.c +2 -2
index 0100110f77b8e..f2b5a11e88a55 100644
@@ -1129,7 +1129,7 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
 		}
 		folio_batch_remove_exceptionals(&fbatch);
 		folio_batch_release(&fbatch);
-		cond_resched();
+		cond_resched_tasks_rcu_qs();
 	}
 
 	/*
@@ -1170,7 +1170,7 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
 
 	index = start;
 	while (index < end) {
-		cond_resched();
+		cond_resched_tasks_rcu_qs();
 
 		if (!find_get_entries(mapping, &index, end - 1, &fbatch,
 				indices)) {
Signature · 1 line
2.53.0
author maintainer
#486 lore raw

PATCH 485/869 mm/alloc_tag: account for reserved tag ids in the kernel tag check

In reply to Greg Kroah-Hartman

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

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

From: Hao Ge <[email protected]>

[ Upstream commit c6e5c0b9a493891634d0a413c3485930a28a8903 ]

The tag ids stored in the page flags include two reserved markers. Id 0 means the page has no tag and id 1 means the tag was cleared, so real tags start at CODETAG_ID_FIRST. The kernel-side check in alloc_tag_sec_init() compared kernel_tags.count alone against the addressable limit, so with the count at or just under the limit the last tag ids wrapped into those markers. Pages allocated through them then look the same as untagged pages on free, nothing is ever subtracted from the real tag and /proc/allocinfo shows that memory as still allocated.

Add the missing CODETAG_ID_FIRST, same as tags_addressable().

Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")
---
 lib/alloc_tag.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/alloc_tag.c +1 -1
index 7c6d3a086fdc4..fbe9e6c995210 100644
@@ -276,7 +276,7 @@ void __init alloc_tag_sec_init(void)
 	kernel_tags.count = last_codetag - kernel_tags.first_tag;
 
 	/* Check if kernel tags fit into page flags */
-	if (kernel_tags.count > (1UL << NR_UNUSED_PAGEFLAG_BITS)) {
+	if (CODETAG_ID_FIRST + kernel_tags.count > (1UL << NR_UNUSED_PAGEFLAG_BITS)) {
 		shutdown_mem_profiling(false); /* allocinfo file does not exist yet */
 		pr_err("%lu allocation tags cannot be references using %d available page flag bits. Memory allocation profiling is disabled!\n",
 			kernel_tags.count, NR_UNUSED_PAGEFLAG_BITS);
Signature · 1 line
2.53.0
author maintainer
#487 lore raw

PATCH 486/869 mm/damon/core: charge only the part of a region the filter left

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit 4ff3b4a54a32142497fb44b79d0920aa6ba3393d ]

Patch series "mm/damon/core: fix the size charged for a filter-trimmed region", v2.

An address range DAMOS filter that partially overlaps a monitoring region splits it, so the scheme action reaches only one side of the boundary. damos_apply_scheme() reads the region size before that split and never re-reads it, so the quota charge and schemes/<S>/stats/sz_tried account for the whole original region.

Patch 1 re-reads the size after the core filters have run. Patch 2 adds KUnit coverage for what the function charges and reports, for the trimmed cases and for the cases that must not change.

This patch (of 2):

An address range DAMOS filter that partially overlaps a monitoring region splits the region at the filter boundary, so the scheme action is applied to only one side of it. damos_apply_scheme() reads the region size once on entry, before damos_core_filter_out() performs that split.

The quota charge and the statistics update therefore account for the region as it was before the trim. schemes/<S>/stats/sz_tried counts memory the filter excluded, which Documentation/mm/damon/design.rst says is not counted as tried, and with quotas/bytes set the excluded part is charged against the budget, throttling the scheme to a fraction of what was configured.

User impact is that DAMOS could unexpectedly slowly run, due to over-charged quota. DAMOS stat could also be confusing. No critical events such as crashes or leask happen.

Re-read the region size after the core filters have run.

---
 mm/damon/core.c | 1 +
 1 file changed, 1 insertion(+)
mm/damon/core.c +1 -0
index 0bed1cd9e3a23..56f2343ffefac 100644
@@ -2004,6 +2004,7 @@ static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
 		}
 		if (damos_filter_out(c, t, r, s))
 			return;
+		sz = damon_sz_region(r);
 		ktime_get_coarse_ts64(&begin);
 		trace_damos_before_apply(cidx, sidx, tidx, r,
 				damon_nr_regions(t), do_trace);
Signature · 1 line
2.53.0
author maintainer
#488 lore raw

PATCH 487/869 mm/damon/tests/core-kunit: test the size charged for a filter-trimmed region

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit 1c335228206392b96d327c6b49cea68cbb806d8a ]

damos_test_filter_out() checks that an address range filter splits a region at the filter boundary, and stops there. Nothing checks what damos_apply_scheme() then charges to the quota and reports as tried.

damos_test_apply_scheme_filtered_sz() covers the two ways such a filter trims a region: one that starts before the filter's range, and one that starts inside it.

damos_test_apply_scheme_filter_sz_unchanged() and damos_test_apply_scheme_quota_sz() cover the cases whose accounting must not change: a region wholly inside a reject range, one wholly inside an allow range, two filters trimming in a single call, a filter type that never splits, no filter at all, a region the quota trims, and a quota remainder too small for one region.

---
 mm/damon/tests/core-kunit.h | 316 ++++++++++++++++++++++++++++++++++++
 1 file changed, 316 insertions(+)
mm/damon/tests/core-kunit.h +316 -0
index 0ce6481319432..ddf4cc37188fd 100644
@@ -624,6 +624,319 @@ static void damos_test_filter_out(struct kunit *test)
 	damos_free_filter(f);
 }
 
+static unsigned long damos_test_apply_scheme_stub(struct damon_ctx *c,
+		struct damon_target *t, struct damon_region *r,
+		struct damos *s, unsigned long *sz_filter_passed)
+{
+	return 0;
+}
+
+static void damos_test_apply_scheme_filtered_sz(struct kunit *test)
+{
+	struct damos_access_pattern pattern = {
+		.min_sz_region = 0,
+		.max_sz_region = ULONG_MAX,
+		.min_nr_accesses = 0,
+		.max_nr_accesses = UINT_MAX,
+		.min_age_region = 0,
+		.max_age_region = UINT_MAX,
+	};
+	unsigned long min_sz = DAMON_MIN_REGION_SZ;
+	struct damos_watermarks wmarks = {};
+	struct damos_quota quota = {};
+	struct damon_ctx *c;
+	struct damon_target *t;
+	struct damon_region *r;
+	struct damos_filter *f;
+	struct damos *s;
+
+	c = damon_new_ctx();
+	if (!c)
+		kunit_skip(test, "ctx alloc fail");
+	c->ops.apply_scheme = damos_test_apply_scheme_stub;
+
+	s = damon_new_scheme(&pattern, DAMOS_STAT, 0, &quota, &wmarks,
+			NUMA_NO_NODE);
+	if (!s) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "scheme alloc fail");
+	}
+	damon_add_scheme(c, s);
+
+	t = damon_new_target();
+	if (!t) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "target alloc fail");
+	}
+	damon_add_target(c, t);
+
+	f = damos_new_filter(DAMOS_FILTER_TYPE_ADDR, true, false);
+	if (!f) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "filter alloc fail");
+	}
+	f->addr_range = (struct damon_addr_range){
+		.start = 2 * min_sz,
+		.end = 8 * min_sz
+	};
+	damos_add_filter(s, f);
+	damos_set_filters_default_reject(s);
+
+	/* reject filter, region starting before the range */
+	r = damon_new_region(0, 4 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 2);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+
+	if (damon_nr_regions(t) != 2)
+		goto out;
+	damon_destroy_region(damon_next_region(r), t);
+	damon_destroy_region(r, t);
+	s->stat = (struct damos_stat){};
+
+	/* allow filter, region starting inside the range */
+	f->allow = true;
+	damos_set_filters_default_reject(s);
+	r = damon_new_region(2 * min_sz, 10 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 2);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 8 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 6 * min_sz);
+
+out:
+	damon_destroy_ctx(c);
+}
+
+static void damos_test_apply_scheme_filter_sz_unchanged(struct kunit *test)
+{
+	struct damos_access_pattern pattern = {
+		.min_sz_region = 0,
+		.max_sz_region = ULONG_MAX,
+		.min_nr_accesses = 0,
+		.max_nr_accesses = UINT_MAX,
+		.min_age_region = 0,
+		.max_age_region = UINT_MAX,
+	};
+	unsigned long min_sz = DAMON_MIN_REGION_SZ;
+	struct damos_watermarks wmarks = {};
+	struct damos_quota quota = {};
+	struct damos_filter *f, *f2;
+	struct damon_ctx *c;
+	struct damon_target *t;
+	struct damon_region *r;
+	struct damos *s;
+
+	c = damon_new_ctx();
+	if (!c)
+		kunit_skip(test, "ctx alloc fail");
+	c->ops.apply_scheme = damos_test_apply_scheme_stub;
+
+	s = damon_new_scheme(&pattern, DAMOS_STAT, 0, &quota, &wmarks,
+			NUMA_NO_NODE);
+	if (!s) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "scheme alloc fail");
+	}
+	damon_add_scheme(c, s);
+
+	t = damon_new_target();
+	if (!t) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "target alloc fail");
+	}
+	damon_add_target(c, t);
+
+	f = damos_new_filter(DAMOS_FILTER_TYPE_ADDR, true, false);
+	if (!f) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "filter alloc fail");
+	}
+	f->addr_range = (struct damon_addr_range){
+		.start = 2 * min_sz, .end = 8 * min_sz};
+	damos_add_filter(s, f);
+	damos_set_filters_default_reject(s);
+
+	/* wholly inside a reject range: not counted at all */
+	r = damon_new_region(4 * min_sz, 6 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.nr_tried, 0);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 0);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 1);
+
+	/* wholly inside an allow range: counted whole, not split */
+	f->allow = true;
+	damos_set_filters_default_reject(s);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 1);
+
+	/* two filters, each trimming: the size left after both is counted */
+	damon_destroy_region(r, t);
+	s->stat = (struct damos_stat){};
+	f->allow = false;
+	f->addr_range = (struct damon_addr_range){
+		.start = 4 * min_sz, .end = 12 * min_sz};
+	f2 = damos_new_filter(DAMOS_FILTER_TYPE_ADDR, true, false);
+	if (!f2) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "filter alloc fail");
+	}
+	f2->addr_range = (struct damon_addr_range){
+		.start = 2 * min_sz, .end = 3 * min_sz};
+	damos_add_filter(s, f2);
+	damos_set_filters_default_reject(s);
+
+	r = damon_new_region(0, 8 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 3);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+
+	/* a core filter that never splits: counted whole */
+	damos_destroy_filter(f2);
+	damos_destroy_filter(f);
+	f = damos_new_filter(DAMOS_FILTER_TYPE_TARGET, true, true);
+	if (!f) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "filter alloc fail");
+	}
+	f->target_idx = 0;
+	damos_add_filter(s, f);
+	damos_set_filters_default_reject(s);
+	s->stat = (struct damos_stat){};
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 3);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+
+	damon_destroy_ctx(c);
+}
+
+static void damos_test_apply_scheme_quota_sz(struct kunit *test)
+{
+	struct damos_access_pattern pattern = {
+		.min_sz_region = 0,
+		.max_sz_region = ULONG_MAX,
+		.min_nr_accesses = 0,
+		.max_nr_accesses = UINT_MAX,
+		.min_age_region = 0,
+		.max_age_region = UINT_MAX,
+	};
+	unsigned long min_sz = DAMON_MIN_REGION_SZ;
+	struct damos_watermarks wmarks = {};
+	struct damos_quota quota = {};
+	struct damon_region *r, *next;
+	struct damon_ctx *c;
+	struct damon_target *t;
+	struct damos *s;
+
+	c = damon_new_ctx();
+	if (!c)
+		kunit_skip(test, "ctx alloc fail");
+
+	s = damon_new_scheme(&pattern, DAMOS_STAT, 0, &quota, &wmarks,
+			NUMA_NO_NODE);
+	if (!s) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "scheme alloc fail");
+	}
+	damon_add_scheme(c, s);
+	damos_set_filters_default_reject(s);
+
+	t = damon_new_target();
+	if (!t) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "target alloc fail");
+	}
+	damon_add_target(c, t);
+
+	/* no apply_scheme operation: the whole region is counted */
+	r = damon_new_region(0, 4 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 4 * min_sz);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 1);
+
+	/* no filter and no quota: the whole region is counted */
+	c->ops.apply_scheme = damos_test_apply_scheme_stub;
+	s->stat = (struct damos_stat){};
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 4 * min_sz);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 1);
+
+	/* the quota trims the region: the trimmed size is counted */
+	damon_for_each_region_safe(r, next, t)
+		damon_destroy_region(r, t);
+	s->stat = (struct damos_stat){};
+	s->quota.esz = 2 * min_sz;
+	s->quota.charged_sz = 0;
+
+	r = damon_new_region(0, 8 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+
+	/* quota remainder below one region: tried, but nothing counted */
+	damon_for_each_region_safe(r, next, t)
+		damon_destroy_region(r, t);
+	s->stat = (struct damos_stat){};
+	s->quota.esz = 1;
+	s->quota.charged_sz = 0;
+
+	r = damon_new_region(0, 4 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.nr_tried, 1);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 0);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 4 * min_sz);
+
+	damon_destroy_ctx(c);
+}
+
 static void damon_test_feed_loop_next_input(struct kunit *test)
 {
 	unsigned long last_input = 900000, current_score = 200;
@@ -750,6 +1063,9 @@ static struct kunit_case damon_test_cases[] = {
 	KUNIT_CASE(damos_test_new_filter),
 	KUNIT_CASE(damos_test_commit_filter),
 	KUNIT_CASE(damos_test_filter_out),
+	KUNIT_CASE(damos_test_apply_scheme_filtered_sz),
+	KUNIT_CASE(damos_test_apply_scheme_filter_sz_unchanged),
+	KUNIT_CASE(damos_test_apply_scheme_quota_sz),
 	KUNIT_CASE(damon_test_feed_loop_next_input),
 	KUNIT_CASE(damon_test_set_filters_default_reject),
 	{},
Signature · 1 line
2.53.0
maintainer
#489 lore raw

Re: [PATCH 6.18 487/869] mm/damon/tests/core-kunit: test the size charged for a filter-trimmed region

Quoted 1 line · On Sat, 7 Nov 2026 08:52:49 -0500 Greg Kroah-Hartman…

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

Please drop this. This is not intended to be picked for stable tree, and causing a DAMON kunit test failure.

The Cc:stable@ tag was wrongly added due to a mix of Cc:stable@ and non-Cc:stable@ patches in a series.

Thanks,
SJ

[...]

author maintainer
#490 lore raw

PATCH 488/869 platform/x86/amd/pmf: Validate the APTS state index

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

[ Upstream commit 192dddd5aa45166450820cef16521bdf23976a73 ]

The static slider APTS state index is supplied by the BIOS as an 8-bit value, but apts_config_store contains only APTS_MAX_STATES entries. An invalid firmware value can therefore cause amd_pmf_update_slider_v2() to read beyond the end of the array.

Validate the selected index before applying the slider values and return an error when it is out of range.

Fixes 8362e862fb87 ("platform/x86/amd/pmf: Update sps power thermals according to the platform-profiles")
---
 drivers/platform/x86/amd/pmf/sps.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
drivers/platform/x86/amd/pmf/sps.c +7 -3
index c28f3c5744c25..bf101e527b115 100644
@@ -248,20 +248,24 @@ static int amd_pmf_update_sps_power_limits_v2(struct amd_pmf_dev *pdev, int pwr_
 	switch (pwr_mode) {
 	case POWER_MODE_PERFORMANCE:
 		index = config_store_v2.sps_idx.power_states[src][POWER_MODE_BEST_PERFORMANCE];
-		amd_pmf_update_slider_v2(pdev, index);
 		break;
 	case POWER_MODE_BALANCED_POWER:
 		index = config_store_v2.sps_idx.power_states[src][POWER_MODE_BALANCED];
-		amd_pmf_update_slider_v2(pdev, index);
 		break;
 	case POWER_MODE_POWER_SAVER:
 		index = config_store_v2.sps_idx.power_states[src][POWER_MODE_BEST_POWER_EFFICIENCY];
-		amd_pmf_update_slider_v2(pdev, index);
 		break;
 	default:
 		return -EINVAL;
 	}
 
+	if (index >= APTS_MAX_STATES) {
+		dev_err(pdev->dev, "Invalid APTS index: %d\n", index);
+		return -EINVAL;
+	}
+
+	amd_pmf_update_slider_v2(pdev, index);
+
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#491 lore raw

PATCH 489/869 platform/x86/amd: Stop counting intermediate cycles with metrics table

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

[ Upstream commit 0c2c928ea7d33c8131b0785bda4e26a32dce5caa ]

The metrics table doesn't increment for all cases that can cause an intermediate wakeup if the cycle is very fast. This can make the intent from commit 9f5595d5f03fd ("platform/x86/amd: pmc: Require at least 2.5 seconds between HW sleep cycles") not work properly.

That commit originally was measured to work properly, but it was accidental due to a logic error. The logic error was fixed in commit 4dbd11796f3a8 ("platform/x86/amd: pmc: Clear metrics table at start of cycle") but this now masked the table doesn't always update.

Since that code was introduced, Daniel Gibson added a number of changes to the logic which includes a state variable introduced in commit 037f0b03c663a ("platform/x86/amd/pmc: Don't log during intermediate wakeups").

Utilize that state variable to instead decide if a single sequence has started.

Cc Daniel Gibson <[email protected]>
Cc [email protected] # 7.1.y: 037f0b03c663a platform/x86/amd/pmc: Don't log during intermediate wakeups
Cc [email protected] # 6.18.y: 037f0b03c663a platform/x86/amd/pmc: Don't log during intermediate wakeups
Fixes 4dbd11796f3a8 ("platform/x86/amd: pmc: Clear metrics table at start of cycle")
---
 drivers/platform/x86/amd/pmc/pmc.c | 15 +--------------
 1 file changed, 1 insertion(+), 14 deletions(-)
drivers/platform/x86/amd/pmc/pmc.c +1 -14
index 000f876e27ebb..fea41c8c1899a 100644
@@ -604,19 +604,6 @@ static int amd_pmc_verify_czn_rtc(struct amd_pmc_dev *pdev, u32 *arg)
 	return rc;
 }
 
-static bool amd_pmc_intermediate_wakeup_need_delay(struct amd_pmc_dev *pdev)
-{
-	/*
-	 * Starting a new HW sleep cycle right after waking from one
-	 * can cause electrical problems triggering the over voltage protection.
-	 * That is avoided by delaying the next suspend a bit, see also
-	 * https://lore.kernel.org/all/[email protected]/
-	 */
-	struct smu_metrics table;
-
-	return get_metrics_table(pdev, &table) == 0 && table.s0i3_last_entry_status;
-}
-
 static bool amd_pmc_want_suspend_delay(struct amd_pmc_dev *pdev)
 {
 	/*
@@ -709,7 +696,7 @@ static void amd_pmc_s2idle_check(void)
 	struct amd_pmc_dev *pdev = &pmc;
 	int rc;
 
-	if (amd_pmc_intermediate_wakeup_need_delay(pdev) ||
+	if (!pdev->is_first_check_after_suspend ||
 	    amd_pmc_want_suspend_delay(pdev))
 		msleep(2500);
 
Signature · 1 line
2.53.0
author maintainer
#492 lore raw

PATCH 490/869 platform/x86: asus-wmi: fix unclear usage of bd->props.power

In reply to Greg Kroah-Hartman

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

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

From: Denis Benato <[email protected]>

[ Upstream commit fd83d81ddf058d487e6d6489b18094f068e66a59 ]

The bd->props.power is checked in parts of the driver correctly comparing with BACKLIGHT_POWER_ON, while in others with a raw usage of bd->props.power and !bd->props.power, moreover in certain checks the logic has been inverted due to BACKLIGHT_POWER_ON being defined as 0: fix both the wrong usage and the inconsistencies by using proper comparisons.

---
 drivers/platform/x86/asus-wmi.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/platform/x86/asus-wmi.c +9 -3
index 9f0f79030b5b8..adff9f49b5677 100644
@@ -4156,7 +4156,8 @@ static int update_screenpad_bl_status(struct backlight_device *bd)
 	u32 ctrl_param = bd->props.brightness;
 	int err = 0;
 
-	if (bd->props.power) {
+	switch (bd->props.power) {
+	case BACKLIGHT_POWER_ON:
 		err = asus_wmi_set_devstate(ASUS_WMI_DEVID_SCREENPAD_POWER, 1, NULL);
 		if (err < 0)
 			return err;
@@ -4164,12 +4165,17 @@ static int update_screenpad_bl_status(struct backlight_device *bd)
 		err = asus_wmi_set_devstate(ASUS_WMI_DEVID_SCREENPAD_LIGHT, ctrl_param, NULL);
 		if (err < 0)
 			return err;
-	}
+		break;
 
-	if (!bd->props.power) {
+	case BACKLIGHT_POWER_OFF:
 		err = asus_wmi_set_devstate(ASUS_WMI_DEVID_SCREENPAD_POWER, 0, NULL);
 		if (err < 0)
 			return err;
+		break;
+
+	default:
+		pr_warn("Invalid screenpad backlight power state: %d\n", bd->props.power);
+		return -EINVAL;
 	}
 
 	return err;
Signature · 1 line
2.53.0
author maintainer
#493 lore raw

PATCH 491/869 platform/x86: asus-wmi: fix screenpad power state detection

In reply to Greg Kroah-Hartman

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

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

From: Denis Benato <[email protected]>

[ Upstream commit f9a1cd14b392a82fdc73474894bf8b198757dfb2 ]

On some models, e.g. the UX5400EA, the screenpad power state cannot be read back: DSTS(ASUS_WMI_DEVID_SCREENPAD_POWER) never sets ASUS_WMI_DSTS_STATUS_BIT, so asus_wmi_get_devstate_simple() reports the panel as powered off regardless of its real state.

The DSDT shows DSTS 0x00050031 (POWER) and DSTS 0x00050032 (LIGHT) both read the same two-byte EC register, each returning a different
byte: byte 0 is a raw EC status byte, which is 0xa0 when the panel is powered and 0x00 when it is off, and byte 1 is the brightness. Read the power state from the low byte instead of
ASUS_WMI_DSTS_STATUS_BIT: firmware reporting the power through the status bit is covered too, since ASUS_WMI_DSTS_STATUS_BIT lies inside ASUS_WMI_DSTS_BRIGHTNESS_MASK.

Reuse read_screenpad_backlight_power() in asus_screenpad_init() in place of the raw devstate read. This makes the brightness read reachable on models like the UX5400EA, so mask the SCREENPAD_LIGHT value with ASUS_WMI_DSTS_BRIGHTNESS_MASK before storing it: the unmasked devstate (0x0001ffa0 when the panel is on) would otherwise be exposed to userspace as an out-of-range brightness (max_brightness is
255) which systemd-backlight then persists.

While at it, pass asus_wmi_get_devstate() the u32 it expects.

---
 drivers/platform/x86/asus-wmi.c | 22 +++++++++++++++-------
 1 file changed, 15 insertions(+), 7 deletions(-)
drivers/platform/x86/asus-wmi.c +15 -7
index adff9f49b5677..486c12b232d14 100644
@@ -4122,13 +4122,20 @@ static int is_display_toggle(int code)
 
 static int read_screenpad_backlight_power(struct asus_wmi *asus)
 {
-	int ret;
+	int ret, retval;
 
-	ret = asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_SCREENPAD_POWER);
+	ret = asus_wmi_get_devstate(asus, ASUS_WMI_DEVID_SCREENPAD_POWER, &retval);
 	if (ret < 0)
 		return ret;
-	/* 1 == powered */
-	return ret ? BACKLIGHT_POWER_ON : BACKLIGHT_POWER_OFF;
+
+	/*
+	 * The firmware reports the panel power in the low byte of the
+	 * devstate as a raw EC status byte that is non-zero when the
+	 * panel is powered; other models report it through
+	 * ASUS_WMI_DSTS_STATUS_BIT, which lies inside the same mask.
+	 */
+	return (retval & ASUS_WMI_DSTS_BRIGHTNESS_MASK) ?
+		BACKLIGHT_POWER_ON : BACKLIGHT_POWER_OFF;
 }
 
 static int read_screenpad_brightness(struct backlight_device *bd)
@@ -4192,16 +4199,17 @@ static int asus_screenpad_init(struct asus_wmi *asus)
 	struct backlight_device *bd;
 	struct backlight_properties props;
 	int err, power;
-	int brightness = 0;
+	u32 brightness = 0;
 
-	power = asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_SCREENPAD_POWER);
+	power = read_screenpad_backlight_power(asus);
 	if (power < 0)
 		return power;
 
-	if (power) {
+	if (power == BACKLIGHT_POWER_ON) {
 		err = asus_wmi_get_devstate(asus, ASUS_WMI_DEVID_SCREENPAD_LIGHT, &brightness);
 		if (err < 0)
 			return err;
+		brightness &= ASUS_WMI_DSTS_BRIGHTNESS_MASK;
 	}
 
 	memset(&props, 0, sizeof(struct backlight_properties));
Signature · 1 line
2.53.0
author maintainer
#494 lore raw

PATCH 492/869 platform/x86: hp-bioscfg: fix 16-byte heap overflow for empty auth token

In reply to Greg Kroah-Hartman

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

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

From: Muhammad Bilal <[email protected]>

[ Upstream commit 540b8ae192afb5566c1b13b6884aee87107a26b9 ]

hp_calculate_security_buffer() special-cases an empty authentication string and returns a fixed 4 bytes (sizeof(u16) * 2). But hp_populate_security_buffer() does not special-case that same input:
for any authentication string that does not start with BEAM_PREFIX, including the empty string, it always builds "UTF_PREFIX + authentication" and converts the result to UTF-16, writing a 2-byte length header plus 2 bytes per character of "<utf-16/>" (9 characters), 20 bytes total, regardless of how long "authentication" itself is.

The caller, hp_set_attribute(), sizes its kmalloc() buffer using hp_calculate_security_buffer()'s return value, so for an empty authentication token it allocates 4 bytes for the security area but hp_populate_security_buffer() then writes 20 bytes into it, causing a 16-byte heap buffer overflow.

The authentication token used here is the current admin/setup password, which is an empty string by default until one is configured. Any write to a writable BIOS attribute while no admin password has been set reaches this path.

Fix by removing the special-case early return for an empty string in hp_calculate_security_buffer(). The generic calculation that follows already accounts for the UTF_PREFIX correctly, which naturally yields the same 20 bytes that hp_populate_security_buffer() writes for an empty string, avoiding duplicate logic for special cases.

---
 drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c | 3 ---
 1 file changed, 3 deletions(-)
drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c +0 -3
index 4d94e48c1a4c8..abf8ce20fe15c 100644
@@ -47,9 +47,6 @@ size_t hp_calculate_security_buffer(const char *authentication)
 		return sizeof(u16) * 2;
 
 	authlen = strlen(authentication);
-	if (!authlen)
-		return sizeof(u16) * 2;
-
 	size = sizeof(u16) + authlen * sizeof(u16);
 	if (!strstarts(authentication, BEAM_PREFIX))
 		size += strlen(UTF_PREFIX) * sizeof(u16);
Signature · 1 line
2.53.0
author maintainer
#495 lore raw

PATCH 493/869 platform/x86: hp-wmi: fix heap OOB read and memory corruption in hp_wmi_perform_query()

In reply to Greg Kroah-Hartman

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

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

From: Muhammad Bilal <[email protected]>

[ Upstream commit 6dea092b261f04d632411c2be52d13190f5f67b1 ]

hp_wmi_perform_query() evaluates an ACPI WMI method and expects a struct bios_return header in the returned buffer. However, it only checks that the ACPI object type is ACPI_TYPE_BUFFER without verifying that obj->buffer.length is at least sizeof(*bios_return) (8 bytes).

If the firmware or ACPI method returns a buffer shorter than 8 bytes:

1. bios_return->return_code at offset 4 reads out of bounds from the allocated ACPI buffer slab.

2. If return_code evaluates to 0 and outsize is non-zero, (int)(obj->buffer.length - sizeof(*bios_return)) evaluates to a negative integer (e.g. -8 for a 0-length buffer). actual_outsize is set to this negative value and passed to memcpy(buffer, ..., actual_outsize), where the signed negative value is cast to size_t (e.g. 0xfffffffffffffff8), attempting to copy ~18 Exabytes and triggering an immediate kernel crash. Additionally, memset(buffer + actual_outsize, ...) performs an out-of-bounds write before buffer.

Fix this by ensuring obj->buffer.length is at least sizeof(*bios_return) before accessing the return code, and compute actual_outsize safely using min_t(u32, ...), which is sound specifically because the guard above already rules out obj->buffer.length being smaller than sizeof(*bios_return) by the time that subtraction runs.

Fixes c3021ea1beee ("hp-wmi: allow setting input and output buffer sizes separately")
---
 drivers/platform/x86/hp/hp-wmi.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/platform/x86/hp/hp-wmi.c +4 -3
index 5eb2aade44cca..f92bb3dca2e30 100644
@@ -491,8 +491,9 @@ static int hp_wmi_perform_query(int query, enum hp_wmi_command command,
 		goto out_free;
 	}
 
-	if (obj->type != ACPI_TYPE_BUFFER) {
-		pr_warn("query 0x%x returned an invalid object 0x%x\n", query, ret);
+	if (obj->type != ACPI_TYPE_BUFFER ||
+	    obj->buffer.length < sizeof(*bios_return)) {
+		pr_warn("query 0x%x returned wrong type or too small buffer\n", query);
 		ret = -EINVAL;
 		goto out_free;
 	}
@@ -511,7 +512,7 @@ static int hp_wmi_perform_query(int query, enum hp_wmi_command command,
 	if (!outsize)
 		goto out_free;
 
-	actual_outsize = min(outsize, (int)(obj->buffer.length - sizeof(*bios_return)));
+	actual_outsize = min_t(u32, outsize, obj->buffer.length - sizeof(*bios_return));
 	memcpy(buffer, obj->buffer.pointer + sizeof(*bios_return), actual_outsize);
 	memset(buffer + actual_outsize, 0, outsize - actual_outsize);
 
Signature · 1 line
2.53.0
author maintainer
#496 lore raw

PATCH 494/869 platform/x86/amd/pmf: Fix power_supply refcount leak in amd_pmf_get_battery_prop()

In reply to Greg Kroah-Hartman

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

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

From: Jack Boykin <[email protected]>

[ Upstream commit 9f3eebbbd1033de0abcc2694ba4b455d30fe33f9 ]

power_supply_get_by_name() takes a reference that is only dropped on the error path. On success it leaks, five times per policy evaluation. Unregistering the battery later trips the use_cnt WARN_ON in power_supply_unregister() and never frees it.

While here, return -ENODEV instead of an uninitialised 'value' when no battery matches, and stop at the first supply found rather than letting the last one in the table win.

Found by reading the code. Fix and changelog drafted with Claude Code (Fable 5.1) and reviewed by hand. Compile-tested only (allmodconfig, W=1, sparse); not run on Smart PC hardware.

Fixes f4627dfd0e19 ("platform/x86/amd/pmf: Add support to get inputs from other subsystems")
Assisted-by LLM sparse
---
 drivers/platform/x86/amd/pmf/spc.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)
drivers/platform/x86/amd/pmf/spc.c +3 -5
index 85192c7536b80..cbe4eef5b8bb4 100644
@@ -244,13 +244,11 @@ static int amd_pmf_get_battery_prop(enum power_supply_property prop)
 			continue;
 
 		ret = power_supply_get_property(psy, prop, &value);
-		if (ret) {
-			power_supply_put(psy);
-			return ret;
-		}
+		power_supply_put(psy);
+		return ret ? ret : value.intval;
 	}
 
-	return value.intval;
+	return -ENODEV;
 }
 
 static int amd_pmf_get_battery_info(struct amd_pmf_dev *dev, struct ta_pmf_enact_table *in)
Signature · 1 line
2.53.0
author maintainer
#497 lore raw

PATCH 495/869 platform/x86: oxpec: Fix Apex charge limit control

In reply to Greg Kroah-Hartman

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

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

From: Antheas Kapenekakis <[email protected]>

[ Upstream commit 0ccdf9a1381c7fb6d9e84abeb8e5d6c85dd07059 ]

The OneXPlayer Apex uses E5/E6 for battery bypass / charge limit, making it the first device to deviate. This was verified by a user on Windows with BIOS version 2.17 and later by running this kernel patch.

Drop X1_ from the MASK variables as they are common in all devices, introduce a board enum for Apex, and make it use the new E5/E6 registers for charge limit / bypass. Apply the same quirks as oxp_fly, since APEX uses the same registers otherwise.

---
 drivers/platform/x86/oxpec.c | 68 ++++++++++++++++++++++++++++--------
 1 file changed, 53 insertions(+), 15 deletions(-)
drivers/platform/x86/oxpec.c +53 -15
index a30845ba37969..4fc9310296342 100644
@@ -60,6 +60,7 @@ enum oxp_board {
 	oxp_x1,
 	oxp_g1_i,
 	oxp_g1_a,
+	oxp_apex,
 };
 
 static enum oxp_board board;
@@ -103,11 +104,14 @@ static struct device *oxp_dev;
 #define OXP_X1_CHARGE_LIMIT_REG		0xA3 /* X1 charge limit (%) */
 #define OXP_X1_CHARGE_INHIBIT_REG	0xA4 /* X1 bypass charging */
 
-#define OXP_X1_CHARGE_INHIBIT_MASK_AWAKE	0x01
+#define OXP_APEX_CHARGE_LIMIT_REG	0xE5 /* Apex charge limit (%) */
+#define OXP_APEX_CHARGE_INHIBIT_REG	0xE6 /* Apex bypass charging */
+
+#define OXP_CHARGE_INHIBIT_MASK_AWAKE	0x01
 /* X1 Mask is 0x0A, F1Pro is 0x02 but the extra bit on the X1 does nothing. */
-#define OXP_X1_CHARGE_INHIBIT_MASK_OFF		0x02
-#define OXP_X1_CHARGE_INHIBIT_MASK_ALWAYS	(OXP_X1_CHARGE_INHIBIT_MASK_AWAKE | \
-						 OXP_X1_CHARGE_INHIBIT_MASK_OFF)
+#define OXP_CHARGE_INHIBIT_MASK_OFF		0x02
+#define OXP_CHARGE_INHIBIT_MASK_ALWAYS	(OXP_CHARGE_INHIBIT_MASK_AWAKE | \
+					 OXP_CHARGE_INHIBIT_MASK_OFF)
 
 static const struct dmi_system_id dmi_table[] = {
 	{
@@ -220,7 +224,7 @@ static const struct dmi_system_id dmi_table[] = {
 			DMI_MATCH(DMI_BOARD_VENDOR, "ONE-NETBOOK"),
 			DMI_EXACT_MATCH(DMI_BOARD_NAME, "ONEXPLAYER APEX"),
 		},
-		.driver_data = (void *)oxp_fly,
+		.driver_data = (void *)oxp_apex,
 	},
 	{
 		.matches = {
@@ -404,6 +408,7 @@ static umode_t tt_toggle_is_visible(struct kobject *kobj,
 	case oxp_x1:
 	case oxp_g1_i:
 	case oxp_g1_a:
+	case oxp_apex:
 		return attr->mode;
 	default:
 		break;
@@ -433,6 +438,7 @@ static ssize_t tt_toggle_store(struct device *dev,
 	case oxp_fly:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 		reg = OXP_TURBO_SWITCH_REG;
 		mask = OXP_TURBO_TAKE_VAL;
 		break;
@@ -479,6 +485,7 @@ static ssize_t tt_toggle_show(struct device *dev,
 	case oxp_fly:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 		reg = OXP_TURBO_SWITCH_REG;
 		mask = OXP_TURBO_TAKE_VAL;
 		break;
@@ -576,6 +583,7 @@ static bool oxp_psy_ext_supported(void)
 	case oxp_g1_i:
 	case oxp_g1_a:
 	case oxp_fly:
+	case oxp_apex:
 		return true;
 	default:
 		break;
@@ -589,12 +597,24 @@ static int oxp_psy_ext_get_prop(struct power_supply *psy,
 				enum power_supply_property psp,
 				union power_supply_propval *val)
 {
+	u8 limit_reg, inhibit_reg;
 	long raw_val;
 	int ret;
 
+	switch (board) {
+	case oxp_apex:
+		limit_reg = OXP_APEX_CHARGE_LIMIT_REG;
+		inhibit_reg = OXP_APEX_CHARGE_INHIBIT_REG;
+		break;
+	default:
+		limit_reg = OXP_X1_CHARGE_LIMIT_REG;
+		inhibit_reg = OXP_X1_CHARGE_INHIBIT_REG;
+		break;
+	}
+
 	switch (psp) {
 	case POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD:
-		ret = read_from_ec(OXP_X1_CHARGE_LIMIT_REG, 1, &raw_val);
+		ret = read_from_ec(limit_reg, 1, &raw_val);
 		if (ret)
 			return ret;
 		if (raw_val < 0 || raw_val > 100)
@@ -602,14 +622,14 @@ static int oxp_psy_ext_get_prop(struct power_supply *psy,
 		val->intval = raw_val;
 		return 0;
 	case POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR:
-		ret = read_from_ec(OXP_X1_CHARGE_INHIBIT_REG, 1, &raw_val);
+		ret = read_from_ec(inhibit_reg, 1, &raw_val);
 		if (ret)
 			return ret;
-		if ((raw_val & OXP_X1_CHARGE_INHIBIT_MASK_ALWAYS) ==
-		    OXP_X1_CHARGE_INHIBIT_MASK_ALWAYS)
+		if ((raw_val & OXP_CHARGE_INHIBIT_MASK_ALWAYS) ==
+		    OXP_CHARGE_INHIBIT_MASK_ALWAYS)
 			val->intval = POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE;
-		else if ((raw_val & OXP_X1_CHARGE_INHIBIT_MASK_AWAKE) ==
-			 OXP_X1_CHARGE_INHIBIT_MASK_AWAKE)
+		else if ((raw_val & OXP_CHARGE_INHIBIT_MASK_AWAKE) ==
+			 OXP_CHARGE_INHIBIT_MASK_AWAKE)
 			val->intval = POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE_AWAKE;
 		else
 			val->intval = POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO;
@@ -625,29 +645,41 @@ static int oxp_psy_ext_set_prop(struct power_supply *psy,
 				enum power_supply_property psp,
 				const union power_supply_propval *val)
 {
+	u8 limit_reg, inhibit_reg;
 	long raw_val;
 
+	switch (board) {
+	case oxp_apex:
+		limit_reg = OXP_APEX_CHARGE_LIMIT_REG;
+		inhibit_reg = OXP_APEX_CHARGE_INHIBIT_REG;
+		break;
+	default:
+		limit_reg = OXP_X1_CHARGE_LIMIT_REG;
+		inhibit_reg = OXP_X1_CHARGE_INHIBIT_REG;
+		break;
+	}
+
 	switch (psp) {
 	case POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD:
 		if (val->intval < 0 || val->intval > 100)
 			return -EINVAL;
-		return write_to_ec(OXP_X1_CHARGE_LIMIT_REG, val->intval);
+		return write_to_ec(limit_reg, val->intval);
 	case POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR:
 		switch (val->intval) {
 		case POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO:
 			raw_val = 0;
 			break;
 		case POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE_AWAKE:
-			raw_val = OXP_X1_CHARGE_INHIBIT_MASK_AWAKE;
+			raw_val = OXP_CHARGE_INHIBIT_MASK_AWAKE;
 			break;
 		case POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE:
-			raw_val = OXP_X1_CHARGE_INHIBIT_MASK_ALWAYS;
+			raw_val = OXP_CHARGE_INHIBIT_MASK_ALWAYS;
 			break;
 		default:
 			return -EINVAL;
 		}
 
-		return write_to_ec(OXP_X1_CHARGE_INHIBIT_REG, raw_val);
+		return write_to_ec(inhibit_reg, raw_val);
 	default:
 		return -EINVAL;
 	}
@@ -715,6 +747,7 @@ static int oxp_pwm_enable(void)
 	case oxp_x1:
 	case oxp_g1_i:
 	case oxp_g1_a:
+	case oxp_apex:
 		return write_to_ec(OXP_SENSOR_PWM_ENABLE_REG, PWM_MODE_MANUAL);
 	default:
 		return -EINVAL;
@@ -743,6 +776,7 @@ static int oxp_pwm_disable(void)
 	case oxp_x1:
 	case oxp_g1_i:
 	case oxp_g1_a:
+	case oxp_apex:
 		return write_to_ec(OXP_SENSOR_PWM_ENABLE_REG, PWM_MODE_AUTO);
 	default:
 		return -EINVAL;
@@ -771,6 +805,7 @@ static int oxp_pwm_read(long *val)
 	case oxp_x1:
 	case oxp_g1_i:
 	case oxp_g1_a:
+	case oxp_apex:
 		return read_from_ec(OXP_SENSOR_PWM_ENABLE_REG, 1, val);
 	default:
 		return -EOPNOTSUPP;
@@ -815,6 +850,7 @@ static int oxp_pwm_fan_speed(long *val)
 	case oxp_mini_amd_a07:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 		return read_from_ec(OXP_SENSOR_FAN_REG, 2, val);
 	default:
 		return -EOPNOTSUPP;
@@ -855,6 +891,7 @@ static int oxp_pwm_input_write(long val)
 	case oxp_fly:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 		return write_to_ec(OXP_SENSOR_PWM_REG, val);
 	default:
 		return -EOPNOTSUPP;
@@ -902,6 +939,7 @@ static int oxp_pwm_input_read(long *val)
 	case oxp_fly:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 	default:
 		ret = read_from_ec(OXP_SENSOR_PWM_REG, 1, val);
 		if (ret)
Signature · 1 line
2.53.0
author maintainer
#498 lore raw

PATCH 496/869 platform/x86: simatic-ipc: fix platform device leak on registration failure

In reply to Greg Kroah-Hartman

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

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

From: Guangshuo Li <[email protected]>

[ Upstream commit 9523698252fd583d6987582b9c34ec6500d10986 ]

register_platform_devices() registers the battery, LED, and watchdog platform devices in sequence. If LED registration fails, the battery device remains registered. If watchdog registration fails, the LED and battery devices remain registered.

These failure paths leave successful platform_device_register_data() calls without the matching platform_device_unregister() calls.

Add an unwind ladder to unregister previously registered platform devices in reverse order before returning the registration error.

The issue was identified by a static analysis tool I developed and confirmed by manual review.

Fixes dd123e62bded ("platform/x86: simatic-ipc: add main driver for Siemens devices")
---
 drivers/platform/x86/siemens/simatic-ipc.c | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)
drivers/platform/x86/siemens/simatic-ipc.c +17 -4
index 7039874d8f112..4a4509fc9263e 100644
@@ -92,6 +92,7 @@ static int register_platform_devices(u32 station_id)
 	u8 wdtmode = SIMATIC_IPC_DEVICE_NONE;
 	u8 battmode = SIMATIC_IPC_DEVICE_NONE;
 	char *pdevname;
+	int ret;
 	int i;
 
 	for (i = 0; i < ARRAY_SIZE(device_modes); i++) {
@@ -139,8 +140,10 @@ static int register_platform_devices(u32 station_id)
 				pdevname, PLATFORM_DEVID_NONE,
 				&platform_data,
 				sizeof(struct simatic_ipc_platform));
-		if (IS_ERR(ipc_led_platform_device))
-			return PTR_ERR(ipc_led_platform_device);
+		if (IS_ERR(ipc_led_platform_device)) {
+			ret = PTR_ERR(ipc_led_platform_device);
+			goto err_unregister_batt;
+		}
 
 		pr_debug("device=%s created\n",
 			 ipc_led_platform_device->name);
@@ -153,8 +156,10 @@ static int register_platform_devices(u32 station_id)
 				KBUILD_MODNAME "_wdt", PLATFORM_DEVID_NONE,
 				&platform_data,
 				sizeof(struct simatic_ipc_platform));
-		if (IS_ERR(ipc_wdt_platform_device))
-			return PTR_ERR(ipc_wdt_platform_device);
+		if (IS_ERR(ipc_wdt_platform_device)) {
+			ret = PTR_ERR(ipc_wdt_platform_device);
+			goto err_unregister_led;
+		}
 
 		pr_debug("device=%s created\n",
 			 ipc_wdt_platform_device->name);
@@ -169,6 +174,14 @@ static int register_platform_devices(u32 station_id)
 	}
 
 	return 0;
+
+err_unregister_led:
+	if (ledmode != SIMATIC_IPC_DEVICE_NONE)
+		platform_device_unregister(ipc_led_platform_device);
+err_unregister_batt:
+	if (battmode != SIMATIC_IPC_DEVICE_NONE)
+		platform_device_unregister(ipc_batt_platform_device);
+	return ret;
 }
 
 static void request_additional_modules(u32 station_id)
Signature · 1 line
2.53.0
author maintainer
#499 lore raw

PATCH 497/869 platform/x86/amd: hfi: Fix out-of-bounds reads when parsing ranking data

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

[ Upstream commit b7b273844b94af9cc64907dccd9e7997c2b60f1a ]

amd_hfi_fill_metadata() parses CPU core ranking data out of the firmware-provided PCC shared memory but trusts two values it should not:

- n_bitmaps is used to bound the outer loop that reads the APIC ID bitmaps from table_data[], but it is never validated against the size of the shared memory region (pcct_ext->length). A firmware-supplied count larger than the region reads past the end of table_data.

- When resolving the base of the ranking data for a processor, the pointer is shifted by an extra "i * nr_class" term, where i is the current bitmap index. The per-processor offset is already applied through apic_index, which uses the running count of active processors (apic_start). The extra shift compounds for every logical processor beyond the first bitmap (APIC ID >= 32), reading out of bounds.

Both result in out-of-bounds reads that can corrupt the ranking metrics, oops, or otherwise destabilise the system.

Reject an n_bitmaps value that would not fit within the shared memory region, and drop the bogus "i * nr_class" term so the ranking data is addressed only through its correct per-processor offset.

Fixes d4e95ea7a78e ("platform/x86: hfi: Parse CPU core ranking data from shared memory")
---
 drivers/platform/x86/amd/hfi/hfi.c | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)
drivers/platform/x86/amd/hfi/hfi.c +16 -4
index ac6ef0b5b95b2..1d12a3b8f32f1 100644
@@ -21,6 +21,7 @@
 #include <linux/module.h>
 #include <linux/mailbox_client.h>
 #include <linux/mutex.h>
+#include <linux/overflow.h>
 #include <linux/percpu-defs.h>
 #include <linux/platform_device.h>
 #include <linux/smp.h>
@@ -169,6 +170,21 @@ static int amd_hfi_fill_metadata(struct amd_hfi_data *amd_hfi_data)
 		return -EINVAL;
 	}
 
+	/*
+	 * The bitmaps enumerating the APIC IDs occupy the first n_bitmaps
+	 * words of table_data.  Reject a firmware-provided count that would
+	 * push those reads past the end of the shared memory region.
+	 */
+	if (struct_size(amd_hfi_data->shmem, table_data, amd_hfi_data->shmem->n_bitmaps) >
+	    pcct_ext->length) {
+		dev_err(amd_hfi_data->dev, "invalid number of bitmaps: %u\n",
+			amd_hfi_data->shmem->n_bitmaps);
+		return -EINVAL;
+	}
+
+	/* The ranking data for each processor follows the bitmaps */
+	u32 *table = amd_hfi_data->shmem->table_data + amd_hfi_data->shmem->n_bitmaps;
+
 	for (unsigned int i = 0; i < amd_hfi_data->shmem->n_bitmaps; i++) {
 		u32 bitmap = amd_hfi_data->shmem->table_data[i];
 
@@ -193,10 +209,6 @@ static int amd_hfi_fill_metadata(struct amd_hfi_data *amd_hfi_data)
 			info = per_cpu_ptr(&amd_hfi_cpuinfo, cpu_index);
 			apic_index = apic_start * info->nr_class * 2;
 			for (unsigned int k = 0; k < info->nr_class; k++) {
-				u32 *table = amd_hfi_data->shmem->table_data +
-					     amd_hfi_data->shmem->n_bitmaps +
-					     i * info->nr_class;
-
 				info->amd_hfi_classes[k].eff = table[apic_index + 2 * k];
 				info->amd_hfi_classes[k].perf = table[apic_index + 2 * k + 1];
 			}
Signature · 1 line
2.53.0
author maintainer
#500 lore raw

PATCH 498/869 platform/x86/intel-uncore-freq: Continue restoring limits on resume

In reply to Greg Kroah-Hartman

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

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

From: Guixiong Wei <[email protected]>

[ Upstream commit 38998529f45c02edcf96b0a3ddd3c83de6d11bbe ]

The PM notifier iterates over every uncore frequency instance to restore user-configured MSR_UNCORE_RATIO_LIMIT values after resume. Entries that have never been configured legitimately have stored_uncore_data set to zero.

The refactoring that split common and enumeration code changed the iteration from active control CPUs to all allocated instances. It also changed the skip for an invalid or unconfigured entry from continue to return, causing that entry to terminate the entire restore operation.

On a multi-package or multi-die system, configuring only a later instance therefore leaves its limit unrestored after suspend, hibernation, or restore if an earlier entry is invalid or unconfigured.

Use continue to skip only the current entry and restore all remaining configured instances.

---
 drivers/platform/x86/intel/uncore-frequency/uncore-frequency.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/platform/x86/intel/uncore-frequency/uncore-frequency.c +1 -1
index 0dfc552b28024..3836d76943f5a 100644
@@ -211,7 +211,7 @@ static int uncore_pm_notify(struct notifier_block *nb, unsigned long mode,
 			struct uncore_data *data = &uncore_instances[i];
 
 			if (!data || !data->valid || !data->stored_uncore_data)
-				return 0;
+				continue;
 
 			wrmsrq_on_cpu(data->control_cpu, MSR_UNCORE_RATIO_LIMIT,
 				      data->stored_uncore_data);
Signature · 1 line
2.53.0
author maintainer
#501 lore raw

PATCH 499/869 platform/x86/intel/vsec: Fix inverted walk_header() test in get_features()

In reply to Greg Kroah-Hartman

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

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

From: David E. Box <[email protected]>

[ Upstream commit 3678e39c6aaeb9aa380c7357b24f7d55955543f8 ]

intel_vsec_walk_header() used to return a bool that was true when devices were found. It was converted to return 0 on success and a negative errno on failure, but the boolean test in intel_vsec_get_features() was left unchanged, so its meaning is now inverted.

A successful walk returns 0 and leaves found set to false, while a failed walk returns an error that evaluates to true. When no other capabilities are present, intel_vsec_pci_init() then returns -ENODEV even though the auxiliary devices were created, and the driver core tears them back down.

This affects platforms that have no DVSEC or VSEC capabilities and describe their features through device_data instead, which today means DG1. Test the return value for success explicitly.

Fixes a6ce8bf3c993 ("platform/x86/intel/vsec: Return real error codes from registration path")
Assisted-by LLM
---
 drivers/platform/x86/intel/vsec.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/platform/x86/intel/vsec.c +1 -1
index 1e292eaeb209d..814e418bea82b 100644
@@ -617,7 +617,7 @@ static bool intel_vsec_get_features(struct pci_dev *pdev,
 		found = true;
 
 	if (info && (info->quirks & VSEC_QUIRK_NO_DVSEC) &&
-	    intel_vsec_walk_header(&pdev->dev, info))
+	    !intel_vsec_walk_header(&pdev->dev, info))
 		found = true;
 
 	return found;
Signature · 1 line
2.53.0
author maintainer
#502 lore raw

PATCH 500/869 fbdev: ssd1307fb: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 81ae1f9a6c850efab3e5dec6b7c9aa5c587f92b7 ]

fb_deferred_io_init() allocates deferred I/O state, populating info->fbdefio_state, or leaving it NULL if an error occurs.

Currently ssd1307fb_probe() ignores its return value.

Therefore if an error arises in fb_deferred_io_init() (for instance, due to an allocation failure) info->fbdefio_state is left NULL.

When the file is subsequently opened, fb_open() will dereference a NULL pointer (calling fb_deferred_io_open()).

Fix this by checking for the error.

Fixes 56c134f7f1b5 ("fbdev: Track deferred-I/O pages in pageref struct")
---
 drivers/video/fbdev/ssd1307fb.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/video/fbdev/ssd1307fb.c +5 -1
index 0df3ac694f4e0..e4559312a9265 100644
@@ -763,7 +763,11 @@ static int ssd1307fb_probe(struct i2c_client *client)
 	info->fix.smem_start = __pa(vmem);
 	info->fix.smem_len = vmem_size;
 
-	fb_deferred_io_init(info);
+	ret = fb_deferred_io_init(info);
+	if (ret) {
+		dev_err(dev, "failed to init fb deferred io: %d\n", ret);
+		goto fb_defio_error;
+	}
 
 	i2c_set_clientdata(client, info);
 
Signature · 1 line
2.53.0
author maintainer
#503 lore raw

PATCH 501/869 fbdev: xen-fbfront: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 5b234b0dd29d79207c059c7b40851dd1e934fa3a ]

fb_deferred_io_init() allocates deferred I/O state, populating info->fbdefio_state, or leaving it NULL if an error occurs.

Currently xenfb_probe() ignores its return value.

Therefore if an error arises in fb_deferred_io_init() (for instance, due to an allocation failure) info->fbdefio_state is left NULL.

When the file is subsequently opened, fb_open() will dereference a NULL pointer (calling fb_deferred_io_open()).

Fix this by checking for the error.

Fixes 56c134f7f1b5 ("fbdev: Track deferred-I/O pages in pageref struct")
---
 drivers/video/fbdev/xen-fbfront.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/video/fbdev/xen-fbfront.c +6 -1
index d8f3bfb2dd6c9..22aaafd2c11f5 100644
@@ -443,7 +443,11 @@ static int xenfb_probe(struct xenbus_device *dev,
 	}
 
 	fb_info->fbdefio = &xenfb_defio;
-	fb_deferred_io_init(fb_info);
+	ret = fb_deferred_io_init(fb_info);
+	if (ret < 0) {
+		xenbus_dev_fatal(dev, ret, "fb_deferred_io_init");
+		goto error_cmap;
+	}
 
 	xenfb_init_shared_page(info, fb_info);
 
@@ -465,6 +469,7 @@ static int xenfb_probe(struct xenbus_device *dev,
 
 error_fb:
 	fb_deferred_io_cleanup(fb_info);
+error_cmap:
 	fb_dealloc_cmap(&fb_info->cmap);
 	framebuffer_release(fb_info);
 error_nomem:
Signature · 1 line
2.53.0
author maintainer
#504 lore raw

PATCH 502/869 fbdev: udlfb: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit eae055f33e41e1d3e1a7e905bdcb1e9f196ed31d ]

fb_deferred_io_init() allocates deferred I/O state, populating info->fbdefio_state, or leaving it NULL if an error occurs.

Currently dlfb_ops_open() ignores its return value.

Therefore if an error arises in fb_deferred_io_init() (for instance, due to an allocation failure) info->fbdefio_state is left NULL.

fb_open() will then dereference a NULL pointer (calling fb_deferred_io_open()) as soon as dlfb_ops_open() returns.

Additionally, if the allocation of info->fbdefio itself fails, dlfb_ops_open() sets info->fbdefio to NULL and invokes fb_deferred_io_init() regardless, hitting BUG_ON(!fbdefio).

Fix this by only invoking fb_deferred_io_init() if the allocation succeeded, and checking for the error.

The driver already supports operating without deferred I/O, so in either case fall back to that by setting info->fbdefio to NULL.

The ignored return value was introduced in commit 56c134f7f1b5 ("fbdev:
Track deferred-I/O pages in pageref struct").

However, the BUG_ON() issue originates from the earlier commit 5bea1fbf9423 ("staging: udlfb: fix incorrect fb_defio implementation for multiple framebuffers"), so target that for the fix.

Fixes 5bea1fbf9423 ("staging: udlfb: fix incorrect fb_defio implementation for multiple framebuffers")
---
 drivers/video/fbdev/udlfb.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/video/fbdev/udlfb.c +6 -3
index f6da680c29eac..abaac2ed22a98 100644
@@ -947,10 +947,13 @@ static int dlfb_ops_open(struct fb_info *info, int user)
 			fbdefio->delay = DL_DEFIO_WRITE_DELAY;
 			fbdefio->sort_pagereflist = true;
 			fbdefio->deferred_io = dlfb_dpy_deferred_io;
-		}
 
-		info->fbdefio = fbdefio;
-		fb_deferred_io_init(info);
+			info->fbdefio = fbdefio;
+			if (fb_deferred_io_init(info)) {
+				kfree(fbdefio);
+				info->fbdefio = NULL;
+			}
+		}
 	}
 
 	dev_dbg(info->dev, "open, user=%d fb_info=%p count=%d\n",
Signature · 1 line
2.53.0
author maintainer
#505 lore raw

PATCH 503/869 fbdev: smscufx: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 8ea6c6e77ccf887f3e68c64f4c261071a345da1e ]

fb_deferred_io_init() allocates deferred I/O state, populating info->fbdefio_state, or leaving it NULL if an error occurs.

Currently ufx_ops_open() ignores its return value.

Therefore if an error arises in fb_deferred_io_init() (for instance, due to an allocation failure) info->fbdefio_state is left NULL.

fb_open() will then dereference a NULL pointer (calling fb_deferred_io_open()) as soon as ufx_ops_open() returns.

Additionally, if the allocation of info->fbdefio itself fails, ufx_ops_open() sets info->fbdefio to NULL and invokes fb_deferred_io_init() regardless, hitting BUG_ON(!fbdefio).

Fix this by only invoking fb_deferred_io_init() if the allocation succeeded, and checking for the error.

The driver already supports operating without deferred I/O, so in either case fall back to that by setting info->fbdefio to NULL.

The ignored return value was introduced in commit 56c134f7f1b5 ("fbdev:
Track deferred-I/O pages in pageref struct").

However, the BUG_ON() issue originates from the earlier commit 3c8a63e22a08 ("Add support for SMSC UFX6000/7000 USB display adapters"), so target that for the fix.

Fixes 3c8a63e22a08 ("Add support for SMSC UFX6000/7000 USB display adapters")
---
 drivers/video/fbdev/smscufx.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/video/fbdev/smscufx.c +6 -3
index 891ce7b76d637..30a94d85fc8c1 100644
@@ -1041,10 +1041,13 @@ static int ufx_ops_open(struct fb_info *info, int user)
 		if (fbdefio) {
 			fbdefio->delay = UFX_DEFIO_WRITE_DELAY;
 			fbdefio->deferred_io = ufx_dpy_deferred_io;
-		}
 
-		info->fbdefio = fbdefio;
-		fb_deferred_io_init(info);
+			info->fbdefio = fbdefio;
+			if (fb_deferred_io_init(info)) {
+				kfree(fbdefio);
+				info->fbdefio = NULL;
+			}
+		}
 	}
 
 	pr_debug("open /dev/fb%d user=%d fb_info=%p count=%d",
Signature · 1 line
2.53.0
author maintainer
#506 lore raw

PATCH 504/869 fbdev: sh_mobile_lcdc: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 5192201aaac2a923ff98306e3ccda58718ee395f ]

fb_deferred_io_init() allocates deferred I/O state, populating info->fbdefio_state, or leaving it NULL if an error occurs.

Currently sh_mobile_lcdc_start() ignores its return value.

Therefore if an error arises in fb_deferred_io_init() (for instance, due to an allocation failure) info->fbdefio_state is left NULL.

When the file is subsequently opened, fb_open() will dereference a NULL pointer (calling fb_deferred_io_open()).

Fix this by checking for the error.

Also clear info->fbdefio in that case, so that sh_mobile_lcdc_stop() does not attempt to clean up deferred I/O state that was never initialised.

Fixes 56c134f7f1b5 ("fbdev: Track deferred-I/O pages in pageref struct")
---
 drivers/video/fbdev/sh_mobile_lcdcfb.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/video/fbdev/sh_mobile_lcdcfb.c +5 -1
index 6038f217ab427..c6da5a62f8c5f 100644
@@ -1042,7 +1042,11 @@ static int sh_mobile_lcdc_start(struct sh_mobile_lcdc_priv *priv)
 			ch->defio.deferred_io = sh_mobile_lcdc_deferred_io;
 			ch->defio.delay = msecs_to_jiffies(tmp);
 			ch->info->fbdefio = &ch->defio;
-			fb_deferred_io_init(ch->info);
+			ret = fb_deferred_io_init(ch->info);
+			if (ret) {
+				ch->info->fbdefio = NULL;
+				return ret;
+			}
 		}
 
 		sh_mobile_lcdc_display_on(ch);
Signature · 1 line
2.53.0
author maintainer
#507 lore raw

PATCH 505/869 fbdev: kyro: Release WC setup on registration failure

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit d3bc005a62945aec57059201092b12b7c955e5a7 ]

If register_framebuffer() fails, kyrofb_probe() frees the framebuffer without releasing its write-combining range. Release the range before freeing the framebuffer. Earlier failures still skip this cleanup.

The missing cleanup already exists in the initial Git import, before the conversion from mtrr_add() to arch_phys_wc_add().

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

---
 drivers/video/fbdev/kyro/fbdev.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/video/fbdev/kyro/fbdev.c +3 -1
index c44d6809859e5..fc350edb41a82 100644
@@ -766,7 +766,7 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
 	fb_memset_io(info->screen_base, 0, size);
 
 	if (register_framebuffer(info) < 0)
-		goto out_free_fb;
+		goto out_free_wc;
 
 	fb_info(info, "%s frame buffer device, at %dx%d@%d using %ldk/%ldk of VRAM\n",
 		info->fix.id,
@@ -777,6 +777,8 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
 
 	return 0;
 
+out_free_wc:
+	arch_phys_wc_del(currentpar->wc_cookie);
 out_free_fb:
 	framebuffer_release(info);
 
Signature · 1 line
2.53.0
author maintainer
#508 lore raw

PATCH 506/869 serial: 8250_exar: store the GPIO platform device in struct exar8250

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 33d337816e00994daaf670243186d9e537ee090d ]

The GPIO platform device is registered via platform->register_gpio() when port 0 is being set up. It is stored to port->port.private_data of the on-stack uart template (and from there it is copied into every registered port). pci_xr17v35x_exit() then fetches it back by serial8250_get_port(priv->line[0]).

But port 0 does not have to exist at that point. If serial8250_register_8250_port() fails for port 0, priv->line[0] holds a negative error code. The probe still succeeds (it only breaks the loop), so on unbind, priv->line[0] (a negative value) is passed to serial8250_get_port(). The GPIO device is never unregistered and a bogus port is accessed.

The same problem would also occur after the planned conversion of serial8250_register_8250_port() to return a uart port instead of a line. As Sashiko pointed out in that case:
If board->setup() fails for the first port (i=0) in exar_pci_probe(), priv->uport[0] remains NULL. If serial8250_register_8250_port() fails, it returns an ERR_PTR. In either case, the loop breaks and probe returns success. When the device is later unbound, pci_xr17v35x_exit() unconditionally passes priv->uport[0] to platform->unregister_gpio(), which will dereference it without checking for validity.

The GPIO device belongs to the PCI device, not to any particular port. So store it in a new struct exar8250::gpio member. Pass priv to both ->register_gpio() and ->unregister_gpio(), so that pci_xr17v35x_exit() does not need to look up any port at all.

---
 drivers/tty/serial/8250/8250_exar.c | 36 ++++++++++++++---------------
 1 file changed, 18 insertions(+), 18 deletions(-)
drivers/tty/serial/8250/8250_exar.c +18 -18
index b9cc0b786ca62..f9f9c10246e12 100644
@@ -231,8 +231,9 @@ struct exar8250_platform {
 	int (*rs485_config)(struct uart_port *port, struct ktermios *termios,
 			    struct serial_rs485 *rs485);
 	const struct serial_rs485 *rs485_supported;
-	int (*register_gpio)(struct pci_dev *pcidev, struct uart_8250_port *port);
-	void (*unregister_gpio)(struct uart_8250_port *port);
+	int (*register_gpio)(struct exar8250 *priv, struct pci_dev *pcidev,
+			     struct uart_8250_port *port);
+	void (*unregister_gpio)(struct exar8250 *priv);
 };
 
 /**
@@ -256,6 +257,7 @@ struct exar8250 {
 	struct exar8250_board	*board;
 	struct eeprom_93cx6	eeprom;
 	void __iomem		*virt;
+	struct platform_device	*gpio;
 	int			line[];
 };
 
@@ -1174,22 +1176,21 @@ static const struct software_node exar_gpio_node = {
 	.properties = exar_gpio_properties,
 };
 
-static int xr17v35x_register_gpio(struct pci_dev *pcidev, struct uart_8250_port *port)
+static int xr17v35x_register_gpio(struct exar8250 *priv, struct pci_dev *pcidev,
+				  struct uart_8250_port *port)
 {
 	if (pcidev->vendor == PCI_VENDOR_ID_EXAR)
-		port->port.private_data =
-			__xr17v35x_register_gpio(pcidev, &exar_gpio_node);
+		priv->gpio = __xr17v35x_register_gpio(pcidev, &exar_gpio_node);
 
 	return 0;
 }
 
-static void xr17v35x_unregister_gpio(struct uart_8250_port *port)
+static void xr17v35x_unregister_gpio(struct exar8250 *priv)
 {
-	if (!port->port.private_data)
-		return;
-
-	__xr17v35x_unregister_gpio(port->port.private_data);
-	port->port.private_data = NULL;
+	if (priv->gpio) {
+		__xr17v35x_unregister_gpio(priv->gpio);
+		priv->gpio = NULL;
+	}
 }
 
 static int sealevel_rs485_config(struct uart_port *port, struct ktermios *termios,
@@ -1286,8 +1287,9 @@ static const struct software_node iot2040_gpio_node = {
 	.properties = iot2040_gpio_properties,
 };
 
-static int iot2040_register_gpio(struct pci_dev *pcidev,
-			      struct uart_8250_port *port)
+static int iot2040_register_gpio(struct exar8250 *priv,
+				 struct pci_dev *pcidev,
+				 struct uart_8250_port *port)
 {
 	u8 __iomem *p = port->port.membase;
 
@@ -1296,8 +1298,7 @@ static int iot2040_register_gpio(struct pci_dev *pcidev,
 	writeb(IOT2040_UARTS_ENABLE, p + UART_EXAR_MPIOLVL_15_8);
 	writeb(IOT2040_UARTS_GPIO_HI_MODE, p + UART_EXAR_MPIOSEL_15_8);
 
-	port->port.private_data =
-		__xr17v35x_register_gpio(pcidev, &iot2040_gpio_node);
+	priv->gpio = __xr17v35x_register_gpio(pcidev, &iot2040_gpio_node);
 
 	return 0;
 }
@@ -1374,7 +1375,7 @@ pci_xr17v35x_setup(struct exar8250 *priv, struct pci_dev *pcidev,
 		/* Setup Multipurpose Input/Output pins. */
 		setup_gpio(pcidev, p);
 
-		ret = platform->register_gpio(pcidev, port);
+		ret = platform->register_gpio(priv, pcidev, port);
 	}
 
 	return ret;
@@ -1384,9 +1385,8 @@ static void pci_xr17v35x_exit(struct pci_dev *pcidev)
 {
 	const struct exar8250_platform *platform = exar_get_platform();
 	struct exar8250 *priv = pci_get_drvdata(pcidev);
-	struct uart_8250_port *port = serial8250_get_port(priv->line[0]);
 
-	platform->unregister_gpio(port);
+	platform->unregister_gpio(priv);
 }
 
 static inline void exar_misc_clear(struct exar8250 *priv)
Signature · 1 line
2.53.0
author maintainer
#509 lore raw

PATCH 507/869 dm-bufio: fix non-working memory limit

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

[ Upstream commit 1190dbeaeaa026a4879e675b8556a150c36a7ced ]

The function evict_old is supposed to loop and evict buffers while the allocated size is above the threshold. However if it hits one bufio client that is empty, it stops and doesn't attempt to scan other clients.

This commit fixes it, so that it skips empty clients and retries up to dm_bufio_client_count times.

Fixes 450e8dee51aa ("dm bufio: improve concurrent IO performance")
Assisted-by Claude:claude-opus-5
---
 drivers/md/dm-bufio.c | 41 +++++++++++++++++++++++++++++++++++++----
 1 file changed, 37 insertions(+), 4 deletions(-)
drivers/md/dm-bufio.c +37 -4
index 59e5d8aa42b71..6d76511953a25 100644
@@ -2521,6 +2521,13 @@ struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsign
 	init_waitqueue_head(&c->free_buffer_wait);
 	c->async_write_error = 0;
 
+	/*
+	 * A client with no buffers yet is not holding the oldest buffer in
+	 * the system; leaving this zeroed would claim exactly that and keep
+	 * the client pinned at the front of dm_bufio_all_clients.
+	 */
+	c->oldest_buffer = jiffies;
+
 	c->dm_io = dm_io_client_create();
 	if (IS_ERR(c->dm_io)) {
 		r = PTR_ERR(c->dm_io);
@@ -2755,9 +2762,23 @@ static unsigned long __evict_a_few(unsigned long nr_buffers)
 
 	dm_bufio_unlock(c);
 
-	if (count)
+	if (count) {
 		c->oldest_buffer = oldest_buffer;
-	__insert_client(c);
+		__insert_client(c);
+	} else {
+		/*
+		 * We evicted nothing, so 'oldest_buffer' tells us nothing new
+		 * and the client keeps its old, possibly very stale, value.
+		 * Requeue it at the back rather than by that value, otherwise
+		 * __insert_client() would put it straight back at the front
+		 * and every subsequent call would pop this same client again,
+		 * never reaching any of the others.
+		 *
+		 * This leaves the list slightly out of order, which is fine -
+		 * it is only ever an approximation.
+		 */
+		list_add_tail(&c->client_list, &dm_bufio_all_clients);
+	}
 
 	return count;
 }
@@ -2782,11 +2803,23 @@ static void evict_old(void)
 {
 	unsigned long threshold = dm_bufio_cache_size -
 		dm_bufio_cache_size / DM_BUFIO_LOW_WATERMARK_RATIO;
+	int unproductive = 0;
 
 	mutex_lock(&dm_bufio_clients_lock);
 	while (dm_bufio_current_allocated > threshold) {
-		if (!__evict_a_few(64))
-			break;
+		if (__evict_a_few(64)) {
+			unproductive = 0;
+		} else {
+			/*
+			 * This client had nothing to give.  Try the others
+			 * before giving up: one idle client, or one whose
+			 * buffers are all held, must not stop us evicting
+			 * from everybody else.  Stop once a whole sweep of
+			 * the client list has freed nothing.
+			 */
+			if (++unproductive >= dm_bufio_client_count)
+				break;
+		}
 		cond_resched();
 	}
 	mutex_unlock(&dm_bufio_clients_lock);
Signature · 1 line
2.53.0
author maintainer
#510 lore raw

PATCH 508/869 dm-bufio: fix a race leading to an unsigned integer underflow

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

[ Upstream commit 005d2ec5723cd4ac740de678274623f1fadd6a6e ]

The function __scan tests "count - freed <= retain_target" and then sets "atomic_long_set(&c->need_shrink, 0);" It exits with the condition "if (!atomic_long_read(&c->need_shrink)) break;" It may be possible that between these two statements, another thread sets &c->need_shrink to a non-zero value. In this case, the function __scan continues and it may possibly the "freed" variable is larger than the "count" variable. The expression "count - freed" underflows and the function __scan will continue to free all the buffers, even those that are below retain_target.

Fix this bug by immediatelly exiting if we set "atomic_long_set(&c->need_shrink, 0)"; and don't attempt to re-read c->need_shrink afterwards.

Fixes 450e8dee51aa ("dm bufio: improve concurrent IO performance")
Assisted-by Claude:claude-opus-5
---
 drivers/md/dm-bufio.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-bufio.c +3 -1
index 6d76511953a25..07e2f0fccefe5 100644
@@ -2402,8 +2402,10 @@ static void __scan(struct dm_bufio_client *c)
 
 	for (l = 0; l < LIST_SIZE; l++) {
 		while (true) {
-			if (count - freed <= retain_target)
+			if (count - freed <= retain_target) {
 				atomic_long_set(&c->need_shrink, 0);
+				break;
+			}
 			if (!atomic_long_read(&c->need_shrink))
 				break;
 
Signature · 1 line
2.53.0
author maintainer
#511 lore raw

PATCH 509/869 mei: vsc: Fix packet CRC computed over pointer size

In reply to Greg Kroah-Hartman

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

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

From: Wentao Guan <[email protected]>

[ Upstream commit 1d2a50533aac7046488da78b0d25f69673cbb028 ]

vsc_tp_xfer() computes the packet CRC over sizeof(pkt) + olen bytes, but pkt is a pointer, so sizeof(pkt) evaluates to the pointer size instead of the size of struct vsc_tp_packet_hdr. The value correctly match the 8-byte header on 64-bit builds.

Use sizeof(pkt->hdr), consistent with the header size used everywhere else in the driver, e.g. in VSC_TP_PACKET_SIZE().

---
 drivers/misc/mei/vsc-tp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/misc/mei/vsc-tp.c +1 -1
index 5ecf99883996b..e70c07aa0d604 100644
@@ -293,7 +293,7 @@ int vsc_tp_xfer(struct vsc_tp *tp, u8 cmd, const void *obuf, size_t olen,
 	pkt->hdr.seq = cpu_to_le32(++tp->seq);
 	memcpy(pkt->buf, obuf, olen);
 
-	crc = ~crc32(~0, (u8 *)pkt, sizeof(pkt) + olen);
+	crc = ~crc32(~0, (u8 *)pkt, sizeof(pkt->hdr) + olen);
 	memcpy(pkt->buf + olen, &crc, sizeof(crc));
 
 	ret = vsc_tp_wakeup_request(tp);
Signature · 1 line
2.53.0
author maintainer
#512 lore raw

PATCH 510/869 speakup: Fix NULL pointer dereference on VT switch + selection

In reply to Greg Kroah-Hartman

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

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

From: Samuel Thibault <[email protected]>

[ Upstream commit e1301ab8a8411fccc7effe0711fc09939a94953c ]

When selecting/pasting very quickly after VT switch, the tty is not set yet, leading to a NULL dereference. We can just abort the operation.

---
 drivers/accessibility/speakup/selection.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/accessibility/speakup/selection.c +6 -0
index 7df7afad5ab42..463a7ef19315e 100644
@@ -61,6 +61,9 @@ static struct speakup_selection_work speakup_sel_work = {
 
 int speakup_set_selection(struct tty_struct *tty)
 {
+	if (!tty)
+		return -ENODEV;
+
 	/* we get kref here first in order to avoid a subtle race when
 	 * cancelling selection work. getting kref first establishes the
 	 * invariant that if speakup_sel_work.tty is not NULL when
@@ -120,6 +123,9 @@ static struct speakup_selection_work speakup_paste_work = {
 
 int speakup_paste_selection(struct tty_struct *tty)
 {
+	if (!tty)
+		return -ENODEV;
+
 	tty_kref_get(tty);
 	if (cmpxchg(&speakup_paste_work.tty, NULL, tty)) {
 		tty_kref_put(tty);
Signature · 1 line
2.53.0
author maintainer
#513 lore raw

PATCH 511/869 clk: qcom: ipq-cmn-pll: Assign .num before accessing .hws

In reply to Greg Kroah-Hartman

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

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

From: Aamir Ahmed <[email protected]>

[ Upstream commit 231bbd135772390522be3656b34b49ea3039eccf ]

hw_data->hws[] is annotated with __counted_by(num), so hw_data->num must hold the element count before the array is accessed. ipq_cmn_pll_register_clks() assigns it only after storing the fixed rate output clocks and the CMN PLL, and the unwind loop under unregister_fixed_clk reads .hws[] with .num still zero. Both are out-of-bounds accesses under CONFIG_UBSAN_BOUNDS.

Move the assignment to right after the allocation.

---
 drivers/clk/qcom/ipq-cmn-pll.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/clk/qcom/ipq-cmn-pll.c +2 -1
index 369798d1ce427..e01c8ccf17311 100644
@@ -351,6 +351,8 @@ static int ipq_cmn_pll_register_clks(struct platform_device *pdev)
 	if (!hw_data)
 		return -ENOMEM;
 
+	hw_data->num = num_clks + 1;
+
 	/*
 	 * Register the CMN PLL clock, which is the parent clock of
 	 * the fixed rate output clocks.
@@ -377,7 +379,6 @@ static int ipq_cmn_pll_register_clks(struct platform_device *pdev)
 	 * is configured to 12 GHZ by DT property assigned-clock-rates-u64.
 	 */
 	hw_data->hws[CMN_PLL_CLK] = cmn_pll_hw;
-	hw_data->num = num_clks + 1;
 
 	ret = devm_of_clk_add_hw_provider(dev, of_clk_hw_onecell_get, hw_data);
 	if (ret)
Signature · 1 line
2.53.0
author maintainer
#514 lore raw

PATCH 512/869 clk: qcom: ipq5018: add 24MHz rate for USB UTMI clock

In reply to Greg Kroah-Hartman

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

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

From: Kathiravan Thirumoorthy <[email protected]>

[ Upstream commit 75e893169fc5c9ec28d5f9dffde40ce29b59a5de ]

The USB UTMI reference clock must operate at 24 MHz, as recommended by the hardware team, for reliable USB operation.

Validation showed that USB 3.2 hub enumeration with USB 2.0 devices fails when the UTMI reference clock is not configured to the required 24 MHz rate. Configuring the UTMI reference clock to 24 MHz to resolve the enumeration failure and ensure successful device detection.

Fixes e3fdbef1bab8 ("clk: qcom: Add Global Clock controller (GCC) driver for IPQ5018")
---
 drivers/clk/qcom/gcc-ipq5018.c | 1 +
 1 file changed, 1 insertion(+)
drivers/clk/qcom/gcc-ipq5018.c +1 -0
index e2d01cdc39c96..78ccd70199fc9 100644
@@ -1270,6 +1270,7 @@ static struct clk_rcg2 usb0_master_clk_src = {
 };
 
 static const struct freq_tbl ftbl_usb0_mock_utmi_clk_src[] = {
+	F(24000000, P_XO, 1, 0, 0),
 	F(60000000, P_GPLL4, 10, 1, 2),
 	{ }
 };
Signature · 1 line
2.53.0
author maintainer
#515 lore raw

PATCH 513/869 clk: qcom: ipq5332: add 24MHz rate for USB UTMI clock

In reply to Greg Kroah-Hartman

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

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

From: Kathiravan Thirumoorthy <[email protected]>

[ Upstream commit 19b62f31e15ef70dc927aab91b1576ea6c37f992 ]

The USB UTMI reference clock must operate at 24 MHz, as recommended by the hardware team, for reliable USB operation.

Validation showed that USB 3.2 hub enumeration with USB 2.0 devices fails when the UTMI reference clock is not configured to the required 24 MHz rate. Configuring the UTMI reference clock to 24 MHz to resolve the enumeration failure and ensure successful device detection.

Fixes 3d89d52970fd ("clk: qcom: add Global Clock controller (GCC) driver for IPQ5332 SoC")
---
 drivers/clk/qcom/gcc-ipq5332.c | 1 +
 1 file changed, 1 insertion(+)
drivers/clk/qcom/gcc-ipq5332.c +1 -0
index 9246e97d785a1..1d02c35c67225 100644
@@ -1039,6 +1039,7 @@ static struct clk_rcg2 gcc_usb0_master_clk_src = {
 };
 
 static const struct freq_tbl ftbl_gcc_usb0_mock_utmi_clk_src[] = {
+	F(24000000, P_XO, 1, 0, 0),
 	F(60000000, P_GPLL4_OUT_AUX, 10, 1, 2),
 	{ }
 };
Signature · 1 line
2.53.0
author maintainer
#516 lore raw

PATCH 514/869 iomap: dont lose a fiemap iteration error when emitting the last extent

In reply to Greg Kroah-Hartman

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

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

From: Andrea Parri <[email protected]>

[ Upstream commit 0d0104adc2c8316433b660cdf6d182a09881864f ]

iomap_fiemap() emits extents one behind: iomap_fiemap_iter() flushes the previous extent and remembers the current one, and the remembered extent is written with FIEMAP_EXTENT_LAST after the iteration loop.

That final flush overwrites ret, so when ->iomap_begin() fails partway through the iteration the error is replaced by the result of iomap_to_fiemap() (zero on success) and iomap_fiemap() returns success with a truncated extent list whose last entry is wrongly marked as the last extent in the file. The pre-iomap_iter code returned the error from inside the loop, before flushing the pending extent.

Check for the iteration error before flushing the pending extent, so that real errors are propagated and only a successful iteration emits the final FIEMAP_EXTENT_LAST extent. -ENOENT (no mapping) is still not an error, and the pending extent is still emitted in that case.

---
 fs/iomap/fiemap.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
fs/iomap/fiemap.c +4 -4
index d11dadff82865..54b824b7edb5c 100644
@@ -76,15 +76,15 @@ int iomap_fiemap(struct inode *inode, struct fiemap_extent_info *fi,
 	while ((ret = iomap_iter(&iter, ops)) > 0)
 		iter.status = iomap_fiemap_iter(&iter, fi, &prev);
 
+	/* inode with no (attribute) mapping will give ENOENT */
+	if (ret < 0 && ret != -ENOENT)
+		return ret;
+
 	if (prev.type != IOMAP_HOLE) {
 		ret = iomap_to_fiemap(fi, &prev, FIEMAP_EXTENT_LAST);
 		if (ret < 0)
 			return ret;
 	}
-
-	/* inode with no (attribute) mapping will give ENOENT */
-	if (ret < 0 && ret != -ENOENT)
-		return ret;
 	return 0;
 }
 EXPORT_SYMBOL_GPL(iomap_fiemap);
Signature · 1 line
2.53.0
author maintainer
#517 lore raw

PATCH 515/869 nvme-rdma: dont complete a request after a bogus remote invalidation

In reply to Greg Kroah-Hartman

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

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

From: Yehyeong Lee <[email protected]>

[ Upstream commit 909307cea08aff4e486cdb7491de5c76a2c31341 ]

When a remote invalidation names an rkey that is not the one we handed out for this request, nvme_rdma_process_nvme_rsp() logs and schedules error recovery, then falls through to nvme_rdma_end_request(). The request is completed with req->mr never invalidated, and nvme_rdma_unmap_data() hands it back with ib_mr_pool_put(), which only puts it on a list. The rkey stays valid and still maps the pages the completed read filled, so a controller that sent the bogus invalidation can write into those pages after pread() has returned.

Return instead, the way the local invalidation path below already does, and leave the request for error recovery to cancel.

Fixes 3ef0279bb0031 ("nvme-rdma: Check remotely invalidated rkey matches our expected rkey")
---
 drivers/nvme/host/rdma.c | 1 +
 1 file changed, 1 insertion(+)
drivers/nvme/host/rdma.c +1 -0
index 19a9dd7caed8d..dbaf503b7de9c 100644
@@ -1713,6 +1713,7 @@ static void nvme_rdma_process_nvme_rsp(struct nvme_rdma_queue *queue,
 				"Bogus remote invalidation for rkey %#x\n",
 				req->mr ? req->mr->rkey : 0);
 			nvme_rdma_error_recovery(queue->ctrl);
+			return;
 		}
 	} else if (req->mr) {
 		int ret;
Signature · 1 line
2.53.0
author maintainer
#518 lore raw

PATCH 516/869 nvmet: fix preempt of another registrant by the reservation holder

In reply to Greg Kroah-Hartman

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

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

From: Daejun Park <[email protected]>

[ Upstream commit d9e84d4e19994818b80846bd2abb7b396e4116a9 ]

Unless the reservation is of an All Registrants type, nvmet_pr_preempt() treats every Reservation Acquire command with the Preempt or Preempt and Abort action that is sent by the reservation holder as the holder preempting itself. It updates the reservation type to RTYPE and completes the command successfully without looking at PRKEY.

NVMe Base Specification 2.1, section 8.1.22.7 makes the action depend on PRKEY for these reservation types, no matter which registrant sends the command:

- PRKEY matches the key of the reservation holder: the reservation is preempted. This is how a holder preempts itself.
- PRKEY does not match the key of the holder and is not 0h: the registrants whose key matches PRKEY are unregistered.
- PRKEY does not match the key of the holder and is 0h: the command is aborted with Invalid Field in Command.

With the current code, a holder that preempts with the key of another registrant leaves that registrant registered, changes the reservation type to RTYPE and still gets a successful completion. With hosts A, B and C registered with the keys 0xa, 0xb and 0xc, and A holding an Exclusive Access - Registrants Only reservation, A sends:

  # nvme resv-acquire /dev/nvme1 -n 1 --crkey=0xa --prkey=0xb \
        --rtype=4 --racqa=1
  NVME Reservation Acquire success
  # nvme resv-report /dev/nvme1 -n 1 --eds | grep '^regctl '
  regctl    : 3

and B can still write to the namespace. Preempt and Abort (--racqa=2) gives the same result. When C sends the preempt instead (--crkey=0xc), B is unregistered and its writes fail with Reservation Conflict.

This defeats fencing in the pNFS SCSI layout server. nfsd holds the reservation and fences a client that does not return its layout by calling pr_preempt() with the key of that client and the abort flag, which is the command RFC 9561 section 2.2.3 asks for. On an nvmet namespace the preempt succeeds, nfsd logs the client as fenced, and the client keeps writing to the device. In a test with an nfsd server and two clients on an nvmet-tcp namespace, the namespace still had three registrants after the fence and the fenced client went on writing to it. With this patch two registrants are left and the writes of the fenced client fail with a reservation conflict.

Take the self preempt path only when PRKEY is the key of the holder. Any other PRKEY sent by the holder is then handled by the code that already serves a non-holder registrant, for Preempt and for Preempt and Abort. For a host that holds the reservation this changes the following:

- A preempt with the key of another registrant unregisters the registrants with that key, sends them the registration preempted notification and leaves the reservation type alone.
- A preempt with PRKEY 0h fails with Invalid Field in Command. A holder that changed its reservation type this way has to pass its own key in PRKEY, which works with and without this patch.
- A preempt with a PRKEY that matches no registrant fails with Reservation Conflict. The specification defines that status only for the All Registrants types. It is what nvmet already returns to a non-holder registrant in this case and what the SCSI target returns for an unregistered key. nfsd treats it as a successful fence.

Not changed: when the holder preempts itself, registrants that share its key stay registered.

Fixes 5a47c2080a73 ("nvmet: support reservation feature")
---
 drivers/nvme/target/pr.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/target/pr.c +1 -1
index 9ab50f821ad69..0f696840b168b 100644
@@ -589,7 +589,7 @@ static u16 nvmet_pr_preempt(struct nvmet_req *req,
 				&ctrl->hostid, abort);
 	}
 
-	if (holder == reg) {
+	if (holder == reg && prkey == holder->rkey) {
 		status = nvmet_pr_update_reg_attr(pr, holder,
 				nvmet_pr_update_holder_rtype, &rtype);
 		if (!status && original_rtype != rtype)
Signature · 1 line
2.53.0
author maintainer
#519 lore raw

PATCH 517/869 nvme-auth: fail when the controller does not authenticate itself

In reply to Greg Kroah-Hartman

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

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

From: Yehyeong Lee <[email protected]>

[ Upstream commit f9e43d924bc74feeb56197de82b2845de2a4b85a ]

nvme_auth_process_dhchap_success1() returns success as soon as the controller clears the rvalid flag in its DH-HMAC-CHAP success1 message, without looking at whether the host had asked the controller to authenticate. A host configured with a controller secret sends a challenge in its reply, computes the expected controller response, and sets chap->bi_directional; if the controller then answers with rvalid = 0 the response is never compared, the host still sends success2, and the queue is marked as authenticated.

A malicious or man-in-the-middle controller therefore only has to clear one flag to turn the configured bidirectional authentication into a one-way one, without holding any secret of its own. The target side already treats the mirror image of this as fatal: when the host supplied a challenge but no controller key is configured, nvmet_auth_success1() fails the authentication rather than answering with rvalid = 0.

Refuse the connection if the controller returns no response although bidirectional authentication was requested. chap->bi_directional is the right condition rather than ctrl->ctrl_key, because secure concatenation sends a challenge only to derive the PSK and deliberately clears bi_directional; a one-way setup without a controller secret keeps returning success as before.

Fixes f50fff73d620 ("nvme: implement In-Band authentication")
---
 drivers/nvme/host/auth.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/nvme/host/auth.c +14 -1
index 9d73713d6f828..38506314248f6 100644
@@ -378,8 +378,21 @@ static int nvme_auth_process_dhchap_success1(struct nvme_ctrl *ctrl,
 			 nvme_auth_hmac_name(chap->hash_id),
 			 nvme_auth_dhgroup_name(chap->dhgroup_id));
 
-	if (!data->rvalid)
+	if (!data->rvalid) {
+		/*
+		 * The controller did not return a response.  If we asked it to
+		 * authenticate itself the session must not be used, otherwise
+		 * mutual authentication would silently degrade to one-way.
+		 */
+		if (chap->bi_directional) {
+			dev_warn(ctrl->device,
+				 "qid %d: controller did not authenticate\n",
+				 chap->qid);
+			chap->status = NVME_AUTH_DHCHAP_FAILURE_FAILED;
+			return -ECONNREFUSED;
+		}
 		return 0;
+	}
 
 	/* Validate controller response */
 	if (crypto_memneq(chap->response, data->rval, data->hl)) {
Signature · 1 line
2.53.0
author maintainer
#520 lore raw

PATCH 518/869 nvmet: free the bvec on file namespace range errors

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 9d820d55b3cb4859c7cf42a74dc78f6154f97398 ]

nvmet_file_execute_rw() allocates the bvec before nvmet_file_execute_io() checks whether the request fits in the backing file. If the request extends beyond the file, nvmet_file_execute_io() calls nvmet_req_complete() to return an error. This skips nvmet_file_io_done(), so the allocated memory is never freed. Repeated requests can exhaust memory.

Use nvmet_file_io_done() to free the bvec before returning the range error to the client.

Fixes 50a909db36f2 ("nvmet: use IOCB_NOWAIT for file-ns buffered I/O")
Assisted-by LLM
---
 drivers/nvme/target/io-cmd-file.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/nvme/target/io-cmd-file.c +2 -2
index 2d068439b129c..6e14700164724 100644
@@ -133,8 +133,8 @@ static bool nvmet_file_execute_io(struct nvmet_req *req, int ki_flags)
 
 	pos = le64_to_cpu(req->cmd->rw.slba) << req->ns->blksize_shift;
 	if (unlikely(pos + req->transfer_len > req->ns->size)) {
-		nvmet_req_complete(req, errno_to_nvme_status(req, -ENOSPC));
-		return true;
+		ret = -ENOSPC;
+		goto complete;
 	}
 
 	memset(&req->f.iocb, 0, sizeof(struct kiocb));
Signature · 1 line
2.53.0
author maintainer
#521 lore raw

PATCH 519/869 nvmet: require authentication before property set

In reply to Greg Kroah-Hartman

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

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

From: Sung Byeongchan <[email protected]>

[ Upstream commit 44512543ff0413031516a02cde67323a55e0f769 ]

I/O queues do not perform independent DH-HMAC-CHAP authentication. They instead rely on authentication of the controller's admin queue. Fabrics property commands, however, are dispatched before the general admin command authentication check.

An unauthenticated peer can consequently set CC.EN, connect an I/O queue, and access a namespace after admin CONNECT reported that authentication was required. Reject PROPERTY_SET until the admin queue has authenticated. Targets without a configured authentication key are unchanged.

This was found by source review with AI assistance. A localhost NVMe/TCP wire reproducer retrieved a known 4 KiB namespace block in two independent boots without completing AUTH_SEND or AUTH_RECEIVE. With this change, PROPERTY_SET returned NVME_SC_AUTH_REQUIRED and the namespace data was not returned; the no-authentication control continued to work.

Fixes c91a20129185 ("nvmet-auth: authenticate on admin queue only")
Assisted-by LLM
---
 drivers/nvme/target/fabrics-cmd.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/nvme/target/fabrics-cmd.c +4 -0
index bc837fbfada15..9aedab2603bdd 100644
@@ -14,6 +14,10 @@ static void nvmet_execute_prop_set(struct nvmet_req *req)
 
 	if (!nvmet_check_transfer_len(req, 0))
 		return;
+	if (!nvmet_check_auth_status(req)) {
+		status = NVME_SC_AUTH_REQUIRED | NVME_STATUS_DNR;
+		goto out;
+	}
 
 	if (req->cmd->prop_set.attrib & 1) {
 		req->error_loc =
Signature · 1 line
2.53.0
author maintainer
#522 lore raw

PATCH 520/869 nvme: bound FDP config log reads to the received buffer

In reply to Greg Kroah-Hartman

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

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

From: Yehyeong Lee <[email protected]>

[ Upstream commit 3cf6de080d97d0d9641fbdb613d546c0734905dd ]

nvme_query_fdp_granularity() parses the FDP Configurations log using sizes the controller returns, without checking that they fit the buffer it was given. The log size is only bounded from above before kvmalloc(), so a size below the log header makes le16_to_cpu(h->numfdpc) read past the allocation, and a size of zero yields ZERO_SIZE_PTR and faults. Each configuration descriptor is then dereferenced (dsze while walking, and nrg and runs on the selected one) without checking that the whole descriptor lies within the buffer, so a descriptor at or past the end is read out of bounds. The out-of-bounds runs value is then exposed to userspace through /sys/block/nvmeXnY/queue/write_stream_granularity.

A device-supplied dsze that is not a multiple of eight also leaves the following descriptors unaligned, and the structure is not packed, so reading nrg and runs from one can fault on architectures without efficient unaligned access.

A malicious or buggy controller triggers this during namespace scan with a short FDP Configurations log:

[    1.104828] BUG: KASAN: slab-out-of-bounds in nvme_alloc_ns+0x39a6/0x4480
[    1.104848] Read of size 8 at addr ffff888009fd8fe0 by task kworker/u8:3/52
[    1.104852]
[    1.104857] CPU: 1 UID: 0 PID: 52 Comm: kworker/u8:3 Not tainted 7.3.0-rc6-00063-g0c2669a9f4a1 #1 PREEMPT(lazy)
[    1.104862] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS rel-1.17.0-0-gb52ca86e094d-prebuilt.qemu.org 04/01/2014
[    1.104866] Workqueue: async async_run_entry_fn
[    1.104873] Call Trace:
[    1.104876]  <TASK>
[    1.104878]  dump_stack_lvl+0x66/0xa0
[    1.104886]  print_report+0xd0/0x630
[    1.104893]  ? nvme_alloc_ns+0x39a6/0x4480
[    1.104897]  ? __virt_addr_valid+0x209/0x3f0
[    1.104903]  ? nvme_alloc_ns+0x39a6/0x4480
[    1.104907]  kasan_report+0xe4/0x120
[    1.104913]  ? nvme_alloc_ns+0x39a6/0x4480
[    1.104919]  nvme_alloc_ns+0x39a6/0x4480
[    1.104926]  ? __pfx_nvme_alloc_ns+0x10/0x10
[    1.104931]  ? check_prev_add+0xfd/0xe80
[    1.104942]  ? lock_acquire+0x18d/0x300
[    1.104948]  ? nvme_find_get_ns+0xbb/0x2e0
[    1.104952]  ? find_held_lock+0x2b/0x80
[    1.104956]  ? nvme_find_get_ns+0x221/0x2e0
[    1.104962]  ? nvme_find_get_ns+0x231/0x2e0
[    1.104967]  ? nvme_scan_ns+0x2e1/0x8d0
[    1.104971]  ? kfree+0x2e5/0x510
[    1.104976]  ? __lock_acquire+0x570/0x1b00
[    1.104982]  nvme_scan_ns+0x56a/0x8d0
[    1.104987]  ? __pfx_nvme_scan_ns+0x10/0x10
[    1.104994]  ? lockdep_hardirqs_on_prepare+0xdc/0x190
[    1.104999]  ? trace_hardirqs_on+0x18/0x160
[    1.105005]  ? kvm_clock_get_cycles+0x19/0x40
[    1.105011]  ? __pfx_nvme_scan_ns_async+0x10/0x10
[    1.105015]  async_run_entry_fn+0x8d/0x290
[    1.105020]  process_one_work+0x8ac/0x1b00
[    1.105029]  ? __pfx_process_one_work+0x10/0x10
[    1.105034]  ? lock_acquire+0x18d/0x300
[    1.105040]  ? lock_is_held_type+0x8f/0x100
[    1.105046]  ? __pfx_async_run_entry_fn+0x10/0x10
[    1.105050]  worker_thread+0x4ee/0xe70
[    1.105056]  ? lockdep_hardirqs_on_prepare+0xdc/0x190
[    1.105061]  ? trace_hardirqs_on+0x18/0x160
[    1.105066]  ? __pfx_worker_thread+0x10/0x10
[    1.105071]  ? __pfx_worker_thread+0x10/0x10
[    1.105076]  kthread+0x2ce/0x3b0
[    1.105080]  ? __pfx_kthread+0x10/0x10
[    1.105085]  ret_from_fork+0x52e/0x780
[    1.105090]  ? __pfx_ret_from_fork+0x10/0x10
[    1.105094]  ? __switch_to+0x572/0xde0
[    1.105101]  ? __pfx_kthread+0x10/0x10
[    1.105105]  ret_from_fork_asm+0x1a/0x30
[    1.105114]  </TASK>
[    1.105116]
[    1.105117] Allocated by task 52:
[    1.105119]  kasan_save_stack+0x33/0x60
[    1.105123]  kasan_save_track+0x14/0x30
[    1.105126]  __kasan_kmalloc+0x8f/0xa0
[    1.105129]  __kvmalloc_node_noprof+0x2e1/0x820
[    1.105134]  nvme_alloc_ns+0x1097/0x4480
[    1.105138]  nvme_scan_ns+0x56a/0x8d0
[    1.105142]  async_run_entry_fn+0x8d/0x290
[    1.105145]  process_one_work+0x8ac/0x1b00
[    1.105148]  worker_thread+0x4ee/0xe70
[    1.105152]  kthread+0x2ce/0x3b0
[    1.105155]  ret_from_fork+0x52e/0x780
[    1.105159]  ret_from_fork_asm+0x1a/0x30
[    1.105163]
[    1.105164] The buggy address belongs to the object at ffff888009fd8fc0
[    1.105164]  which belongs to the cache kmalloc-32 of size 32
[    1.105167] The buggy address is located 8 bytes to the right of
[    1.105167]  allocated 24-byte region [ffff888009fd8fc0, ffff888009fd8fd8)
[    1.105171]
[    1.105172] The buggy address belongs to the physical page:
[    1.105175] page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x9fd8
[    1.105179] flags: 0x100000000000000(node=0|zone=1)
[    1.105183] page_type: f5(slab)
[    1.105188] raw: 0100000000000000 ffff888008c41780 dead000000000100 dead000000000122
[    1.105192] raw: 0000000000000000 0000000000400040 00000000f5000000 0000000000000000
[    1.105194] page dumped because: kasan: bad access detected
[    1.105195]
[    1.105196] Memory state around the buggy address:
[    1.105198]  ffff888009fd8e80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[    1.105201]  ffff888009fd8f00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[    1.105203] >ffff888009fd8f80: fc fc fc fc fc fc fc fc 00 00 00 fc fc fc fc fc
[    1.105205]                                                        ^
[    1.105207]  ffff888009fd9000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 fc
[    1.105210]  ffff888009fd9080: fc fc fc fc fc fc fc fc 00 00 00 00 00 00 00 00
[    1.105212] ==================================================================

Reject a log smaller than its header plus one configuration descriptor, zero the buffer so a short transfer leaves no uninitialized tail to parse, require each descriptor's declared size to be at least a descriptor and to leave room for the next one before walking it, and read the descriptor fields with the unaligned accessors.

Fixes 30b5f20bb2dda ("nvme: register fdp parameters with the block layer")
---
 drivers/nvme/host/core.c | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/nvme/host/core.c +10 -5
index ad725e346c94e..99a8e2953b02a 100644
@@ -2210,13 +2210,18 @@ static int nvme_query_fdp_granularity(struct nvme_ctrl *ctrl,
 	}
 
 	size = le32_to_cpu(hdr.sze);
+	if (size < sizeof(*h) + sizeof(*desc)) {
+		dev_warn(ctrl->device, "FDP config size too small:%zu\n",
+			 size);
+		return 0;
+	}
 	if (size > PAGE_SIZE * MAX_ORDER_NR_PAGES) {
 		dev_warn(ctrl->device, "FDP config size too large:%zu\n",
 			 size);
 		return 0;
 	}
 
-	h = kvmalloc(size, GFP_KERNEL);
+	h = kvzalloc(size, GFP_KERNEL);
 	if (!h)
 		return -ENOMEM;
 
@@ -2242,9 +2247,9 @@ static int nvme_query_fdp_granularity(struct nvme_ctrl *ctrl,
 	desc = log;
 	end = log + size - sizeof(*h);
 	for (i = 0; i < fdp_idx; i++) {
-		u16 dsze = le16_to_cpu(desc->dsze);
+		u16 dsze = get_unaligned_le16(&desc->dsze);
 
-		if (!dsze || log + dsze > end) {
+		if (dsze < sizeof(*desc) || log + dsze + sizeof(*desc) > end) {
 			dev_warn(ctrl->device,
 				 "FDP invalid config descriptor at index %d\n", i);
 			ret = 0;
@@ -2254,13 +2259,13 @@ static int nvme_query_fdp_granularity(struct nvme_ctrl *ctrl,
 		desc = log;
 	}
 
-	if (le32_to_cpu(desc->nrg) > 1) {
+	if (get_unaligned_le32(&desc->nrg) > 1) {
 		dev_warn(ctrl->device, "FDP NRG > 1 not supported\n");
 		ret = 0;
 		goto out;
 	}
 
-	info->runs = le64_to_cpu(desc->runs);
+	info->runs = get_unaligned_le64(&desc->runs);
 out:
 	kvfree(h);
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#523 lore raw

PATCH 521/869 nvmet: zns: dont leak stale memory in zone management receive

In reply to Greg Kroah-Hartman

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

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

From: Andrea Parri <[email protected]>

[ Upstream commit 31b8a6af19b73e6167c4b655cd5e86681bac1c41 ]

A Zone Management Receive report returns the full buffer the host asked for, but nvmet_bdev_zone_zmgmt_recv_work() writes only the 8-byte Number of Zones field and one 64-byte descriptor for each matching zone that fits. The 56 reserved header bytes and every descriptor slot past the last match keep whatever the buffer held before. A 4096-byte report covering a single zone leaves 4024 bytes unwritten.

The tcp, rdma and fc transports allocate that buffer with sgl_alloc() and pci-epf with kmalloc(), none with __GFP_ZERO, and on success each sends the whole buffer to the host (nvmet_setup_c2h_data_pdu() for tcp), so the host receives old kernel memory from the target.

nvmet_bdev_execute_zone_mgmt_recv() also never checks the transport data length against NUMD, so on transports where the host sets that length, the buffer sent back can be much larger than the report NUMD describes. pci-epf derives its data length from NUMD, so the length check below does not apply there, but the zeroing still covers the report.

Reject a data length that does not match NUMD with nvmet_check_transfer_len(), as nvmet_bdev_execute_zone_append() does, and zero the report with nvmet_zero_sgl() before filling it. Zeroing NUMD bytes is only enough because of the length check, so the two go together.

Allocating with __GFP_ZERO in the transports would also close the leak, but it adds a memset to every read command to fix one handler, so the transports are left alone.

Tested over the loop, tcp, rdma and fc transports with a zoned null_blk namespace: before this patch, zone reports carried stale bytes and a data length larger than NUMD was accepted; with it, reports are fully initialized and such a length fails with Data SGL Length Invalid.

Fixes aaf2e048af27 ("nvmet: add ZBD over ZNS backend support")
Assisted-by LLM
---
 drivers/nvme/target/zns.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/nvme/target/zns.c +10 -0
index 95af4b67108c7..00f694ac3986c 100644
@@ -286,6 +286,11 @@ static void nvmet_bdev_zone_zmgmt_recv_work(struct work_struct *w)
 	if (status)
 		goto out;
 
+	/* Only the zone count and matching descriptors are written below. */
+	status = nvmet_zero_sgl(req, 0, out_bufsize);
+	if (status)
+		goto out;
+
 	if (!req_slba_nr_zones) {
 		status = NVME_SC_SUCCESS;
 		goto out;
@@ -314,6 +319,11 @@ static void nvmet_bdev_zone_zmgmt_recv_work(struct work_struct *w)
 
 void nvmet_bdev_execute_zone_mgmt_recv(struct nvmet_req *req)
 {
+	u32 out_bufsize = (le32_to_cpu(req->cmd->zmr.numd) + 1) << 2;
+
+	if (!nvmet_check_transfer_len(req, out_bufsize))
+		return;
+
 	INIT_WORK(&req->z.zmgmt_work, nvmet_bdev_zone_zmgmt_recv_work);
 	queue_work(zbd_wq, &req->z.zmgmt_work);
 }
Signature · 1 line
2.53.0
author maintainer
#524 lore raw

PATCH 522/869 f2fs: convert inline quota files when turning quota on

In reply to Greg Kroah-Hartman

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

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

From: Daeho Jeong <[email protected]>

[ Upstream commit a85e09bd6cc80059b9e0ef5cd1467719aa3129a8 ]

With a block size larger than 4KB, the inline data area is large enough to hold a freshly created quota file (quotacheck writes 6KB), so aquota.user/aquota.group stay inline after quotaon. f2fs does not expect quota files to be inline, and this causes two problems:

1. Quota file corruption. f2fs_write_single_data_page() sends quota inodes straight to f2fs_do_write_data_page(), which sees NULL_ADDR for index 0, treats the folio as truncated and drops it. Updates to the quota file are lost once the folio is reclaimed, so the quota tree reads stale data: chown/chgrp fail with EIO and quota entries of users disappear. For example, the kernel log shows:

find_free_dqentry: Data block full but it shouldn't
qtree_write_dquot: Error -5 occurred while creating quota

2. Deadlock. Writing a quota file past MAX_INLINE_DATA converts it from f2fs_write_begin() under f2fs_lock_op(). dquot_transfer() is called from f2fs_setattr() with f2fs_lock_op() already held, so chown/chgrp take cp_rwsem for read twice and hang, together with the checkpoint and every other writer, once a checkpoint waits for cp_rwsem in between (seen with generic/232).

Quota files only grow and there are at most MAXQUOTAS of them, so there is no point in keeping them inline. Convert them in f2fs_quota_on() and after dquot_quota_on_mount(), which keeps every block size on the same path as 4KB blocks, where quota files never fit inline. Quota sysfiles are created by mkfs with real blocks and are not affected.

Fixes d7e9a9037de2 ("f2fs: Support Block Size == Page Size")
---
 fs/f2fs/super.c | 33 ++++++++++++++++++++++++++++++++-
 1 file changed, 32 insertions(+), 1 deletion(-)
fs/f2fs/super.c +32 -1
index 74b12c1ef8211..146bd977bb591 100644
@@ -3171,15 +3171,42 @@ static qsize_t *f2fs_get_reserved_space(struct inode *inode)
 	return &F2FS_I(inode)->i_reserved_quota;
 }
 
+/*
+ * Quota files only grow and there are at most MAXQUOTAS of them, so there is
+ * no point in keeping them inline. Writeback of quota files does not handle
+ * inline data and would drop what was written to them.
+ */
+static int f2fs_quota_convert_inline(struct inode *inode)
+{
+	int err;
+
+	if (!f2fs_has_inline_data(inode))
+		return 0;
+
+	inode_lock(inode);
+	err = f2fs_convert_inline_inode(inode);
+	inode_unlock(inode);
+	return err;
+}
+
 static int f2fs_quota_on_mount(struct f2fs_sb_info *sbi, int type)
 {
+	int err;
+
 	if (is_set_ckpt_flags(sbi, CP_QUOTA_NEED_FSCK_FLAG)) {
 		f2fs_err(sbi, "quota sysfile may be corrupted, skip loading it");
 		return 0;
 	}
 
-	return dquot_quota_on_mount(sbi->sb, F2FS_OPTION(sbi).s_qf_names[type],
+	err = dquot_quota_on_mount(sbi->sb, F2FS_OPTION(sbi).s_qf_names[type],
 					F2FS_OPTION(sbi).s_jquota_fmt, type);
+	if (err)
+		return err;
+
+	err = f2fs_quota_convert_inline(sb_dqopt(sbi->sb)->files[type]);
+	if (err)
+		dquot_quota_off(sbi->sb, type);
+	return err;
 }
 
 int f2fs_enable_quota_files(struct f2fs_sb_info *sbi, bool rdonly)
@@ -3391,6 +3418,10 @@ static int f2fs_quota_on(struct super_block *sb, int type, int format_id,
 
 	inode = d_inode(path->dentry);
 
+	err = f2fs_quota_convert_inline(inode);
+	if (err)
+		goto out;
+
 	err = filemap_fdatawrite(inode->i_mapping);
 	if (err)
 		goto out;
Signature · 1 line
2.53.0
author maintainer
#525 lore raw

PATCH 523/869 PCI: rockchip-ep: Do not attempt 5.0 GT/s retraining

In reply to Greg Kroah-Hartman

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

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

From: Geraldo Nascimento <[email protected]>

[ Upstream commit 7f173bfa6d42742de4ab647e001232c1165ab28e ]

Drop the 5.0 GT/s Link Speed retraining code block from Rockchip PCIe EP driver. The reason is that Shawn Lin from Rockchip has reiterated that there may be danger of "catastrophic failure" in using their PCIe with 5.0 GT/s speeds.

While Rockchip has done so informally without issuing a proper errata, and the particulars are thus unknown, this may cause data loss or worse.

This change is corroborated by RK3399 official datasheet [1], which states maximum link speed for this platform is 2.5 GT/s.

[1] https://opensource.rock-chips.com/images/d/d7/Rockchip_RK3399_Datasheet_V2.1-20200323.pdf

---
 drivers/pci/controller/pcie-rockchip-ep.c | 13 -------------
 1 file changed, 13 deletions(-)
drivers/pci/controller/pcie-rockchip-ep.c +0 -13
index 799461335762e..9ebc227a1ef84 100644
@@ -553,19 +553,6 @@ static void rockchip_pcie_ep_link_training(struct work_struct *work)
 	if (ret)
 		goto again;
 
-	/*
-	 * Check the current speed: if gen2 speed was requested and we are not
-	 * at gen2 speed yet, retrain again for gen2.
-	 */
-	val = rockchip_pcie_read(rockchip, PCIE_CORE_CTRL);
-	if (!PCIE_LINK_IS_GEN2(val) && rockchip->link_gen == 2) {
-		/* Enable retrain for gen2 */
-		rockchip_pcie_ep_retrain_link(rockchip);
-		readl_poll_timeout(rockchip->apb_base + PCIE_CORE_CTRL,
-				   val, PCIE_LINK_IS_GEN2(val), 50,
-				   LINK_TRAIN_TIMEOUT);
-	}
-
 	/* Check again that the link is up */
 	if (!rockchip_pcie_ep_link_up(rockchip))
 		goto again;
Signature · 1 line
2.53.0
author maintainer
#526 lore raw

PATCH 524/869 PCI: rockchip-host: Do not attempt 5.0 GT/s retraining

In reply to Greg Kroah-Hartman

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

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

From: Geraldo Nascimento <[email protected]>

[ Upstream commit 2a1e6c382fb7567679c07bd6a7060fefc7a5edc9 ]

Drop the 5.0 GT/s Link Speed retraining from Rockchip PCIe Root Complex Mode Operation, so-called host driver.

The reason is that Shawn Lin from Rockchip has reiterated that there may be danger of "catastrophic failure" in using their PCIe with 5.0GT/s speeds.

While Rockchip has done so informally without issuing a proper errata, and the particulars are thus unknown, this may cause data loss or worse.

This change is corroborated by RK3399 official datasheet [1], which states maximum link speed for this platform is 2.5 GT/s.

[1] https://opensource.rock-chips.com/images/d/d7/Rockchip_RK3399_Datasheet_V2.1-20200323.pdf

---
 drivers/pci/controller/pcie-rockchip-host.c | 20 --------------------
 1 file changed, 20 deletions(-)
drivers/pci/controller/pcie-rockchip-host.c +0 -20
index d203c4876d304..0b52f2e370f41 100644
@@ -328,26 +328,6 @@ static int rockchip_pcie_host_init_port(struct rockchip_pcie *rockchip)
 		goto err_power_off_phy;
 	}
 
-	if (rockchip->link_gen == 2) {
-		/*
-		 * Enable retrain for gen2. This should be configured only after
-		 * gen1 finished.
-		 */
-		status = rockchip_pcie_read(rockchip, PCIE_RC_CONFIG_CR + PCI_EXP_LNKCTL2);
-		status &= ~PCI_EXP_LNKCTL2_TLS;
-		status |= PCI_EXP_LNKCTL2_TLS_5_0GT;
-		rockchip_pcie_write(rockchip, status, PCIE_RC_CONFIG_CR + PCI_EXP_LNKCTL2);
-		status = rockchip_pcie_read(rockchip, PCIE_RC_CONFIG_CR + PCI_EXP_LNKCTL);
-		status |= PCI_EXP_LNKCTL_RL;
-		rockchip_pcie_write(rockchip, status, PCIE_RC_CONFIG_CR + PCI_EXP_LNKCTL);
-
-		err = readl_poll_timeout(rockchip->apb_base + PCIE_CORE_CTRL,
-					 status, PCIE_LINK_IS_GEN2(status), 20,
-					 500 * USEC_PER_MSEC);
-		if (err)
-			dev_dbg(dev, "PCIe link training gen2 timeout, fall back to gen1!\n");
-	}
-
 	/* Check the final link width from negotiated lane counter from MGMT */
 	status = rockchip_pcie_read(rockchip, PCIE_CORE_CTRL);
 	status = 0x1 << ((status & PCIE_CORE_PL_CONF_LANE_MASK) >>
Signature · 1 line
2.53.0
author maintainer
#527 lore raw

PATCH 525/869 PCI: rockchip: Drive at 2.5 GT/s, error other speeds

In reply to Greg Kroah-Hartman

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

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

From: Geraldo Nascimento <[email protected]>

[ Upstream commit 84d08ff902f1ec01177fef1a21a38934927f5aee ]

Configure the core to be driven at 2.5 GT/s Link Speed and ignore any other speed with a warning. Also drop the 5.0 GT/s Link Speed defines from Rockchip PCIe header.

The reason is that Shawn Lin from Rockchip has reiterated that there may be danger of "catastrophic failure" in using their PCIe with 5.0 GT/s speeds.

While Rockchip has done so informally without issuing a proper errata, and the particulars are thus unknown, this may cause data loss or worse.

This change is corroborated by RK3399 official datasheet [1], which states maximum link speed for this platform is 2.5 GT/s.

[1] https://opensource.rock-chips.com/images/d/d7/Rockchip_RK3399_Datasheet_V2.1-20200323.pdf

---
 drivers/pci/controller/pcie-rockchip.c | 14 ++++++--------
 drivers/pci/controller/pcie-rockchip.h |  3 ---
 2 files changed, 6 insertions(+), 11 deletions(-)
drivers/pci/controller/pcie-rockchip.c +6 -8
index 0f88da3788054..456dcfd676ed7 100644
@@ -66,8 +66,10 @@ int rockchip_pcie_parse_dt(struct rockchip_pcie *rockchip)
 	}
 
 	rockchip->link_gen = of_pci_get_max_link_speed(node);
-	if (rockchip->link_gen < 0 || rockchip->link_gen > 2)
-		rockchip->link_gen = 2;
+	if (rockchip->link_gen < 0 || rockchip->link_gen >= 2) {
+		rockchip->link_gen = 1;
+		dev_warn(dev, "invalid max-link-speed, limited to 2.5 GT/s\n");
+	}
 
 	for (i = 0; i < ROCKCHIP_NUM_PM_RSTS; i++)
 		rockchip->pm_rsts[i].id = rockchip_pci_pm_rsts[i];
@@ -147,12 +149,8 @@ int rockchip_pcie_init_port(struct rockchip_pcie *rockchip)
 		goto err_exit_phy;
 	}
 
-	if (rockchip->link_gen == 2)
-		rockchip_pcie_write(rockchip, PCIE_CLIENT_GEN_SEL_2,
-				    PCIE_CLIENT_CONFIG);
-	else
-		rockchip_pcie_write(rockchip, PCIE_CLIENT_GEN_SEL_1,
-				    PCIE_CLIENT_CONFIG);
+	rockchip_pcie_write(rockchip, PCIE_CLIENT_GEN_SEL_1,
+			    PCIE_CLIENT_CONFIG);
 
 	regs = PCIE_CLIENT_ARI_ENABLE |
 	       PCIE_CLIENT_CONF_LANE_NUM(rockchip->lanes);
drivers/pci/controller/pcie-rockchip.h +0 -3
index 3e82a69b9c006..b5da15601b585 100644
@@ -42,7 +42,6 @@
 #define   PCIE_CLIENT_MODE_RC			HWORD_SET_BIT(0x0040)
 #define   PCIE_CLIENT_MODE_EP			HWORD_CLR_BIT(0x0040)
 #define   PCIE_CLIENT_GEN_SEL_1			HWORD_CLR_BIT(0x0080)
-#define   PCIE_CLIENT_GEN_SEL_2			HWORD_SET_BIT(0x0080)
 #define PCIE_CLIENT_LEGACY_INT_CTRL	(PCIE_CLIENT_BASE + 0x0c)
 #define   PCIE_CLIENT_INT_IN_ASSERT		HWORD_SET_BIT(0x0002)
 #define   PCIE_CLIENT_INT_IN_DEASSERT		HWORD_CLR_BIT(0x0002)
@@ -197,8 +196,6 @@
 	(((x) & PCIE_CORE_PL_CONF_LS_MASK) == PCIE_CORE_PL_CONF_LS_READY)
 #define PCIE_LINK_UP(x) \
 	(((x) & PCIE_CLIENT_LINK_STATUS_MASK) == PCIE_CLIENT_LINK_STATUS_UP)
-#define PCIE_LINK_IS_GEN2(x) \
-	(((x) & PCIE_CORE_PL_CONF_SPEED_MASK) == PCIE_CORE_PL_CONF_SPEED_5G)
 
 #define RC_REGION_0_ADDR_TRANS_H		0x00000000
 #define RC_REGION_0_ADDR_TRANS_L		0x00000000
Signature · 1 line
2.53.0
author maintainer
#528 lore raw

PATCH 526/869 sh: intc: Sort the prio and sense lists after filling them

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit 94a219eda3b5fb1d1753a5ecf28b171c8f308a27 ]

register_intc_controller() sorts d->prio and d->sense right after allocating them, with hw->nr_prio_regs and hw->nr_sense_regs as the element count. The lists hold hw->nr_vectors entries and are only filled later, by intc_register_irq().

On SH7785, sh7785-irq0123 and sh7785-irq4567 have four vectors but the SoC's eleven priority registers, so sort() swaps 88 bytes in a 32 byte kmalloc object at boot. slub_debug=FZPU reports "Right Redzone overwritten" in kmalloc-32, and v6.5 and v6.6 panic in __kmem_cache_alloc_node() while registering sh7785-irq0123.

Found with a custom QEMU model of the SH7785LCR. On it, v6.4 sh7785lcr_defconfig boots with SLAB, the defconfig default before v6.5, and hangs before the console is up when built with SLUB.

Sort the lists once all vectors are registered, with the number of entries that were added.

---
 drivers/sh/intc/core.c | 11 +++++------
 1 file changed, 5 insertions(+), 6 deletions(-)
drivers/sh/intc/core.c +5 -6
index 3dde703b77668..137a7a94d9cb8 100644
@@ -277,9 +277,6 @@ int __init register_intc_controller(struct intc_desc *desc)
 			k += save_reg(d, k, hw->prio_regs[i].set_reg, smp);
 			k += save_reg(d, k, hw->prio_regs[i].clr_reg, smp);
 		}
-
-		sort(d->prio, hw->nr_prio_regs, sizeof(*d->prio),
-		     intc_handle_int_cmp, NULL);
 	}
 
 	if (hw->sense_regs) {
@@ -290,9 +287,6 @@ int __init register_intc_controller(struct intc_desc *desc)
 
 		for (i = 0; i < hw->nr_sense_regs; i++)
 			k += save_reg(d, k, hw->sense_regs[i].reg, 0);
-
-		sort(d->sense, hw->nr_sense_regs, sizeof(*d->sense),
-		     intc_handle_int_cmp, NULL);
 	}
 
 	if (hw->subgroups)
@@ -360,6 +354,11 @@ int __init register_intc_controller(struct intc_desc *desc)
 		}
 	}
 
+	sort(d->prio, d->nr_prio, sizeof(*d->prio),
+	     intc_handle_int_cmp, NULL);
+	sort(d->sense, d->nr_sense, sizeof(*d->sense),
+	     intc_handle_int_cmp, NULL);
+
 	intc_subgroup_init(desc, d);
 
 	/* enable bits matching force_enable after registering irqs */
Signature · 1 line
2.53.0
author maintainer
#529 lore raw

PATCH 527/869 f2fs: remove mappedtodisk flag usage in mmap write path

In reply to Greg Kroah-Hartman

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

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

From: Nanzhe Zhao <[email protected]>

[ Upstream commit b3c9843589257631bac18f30655e82d88970688a ]

PG_mappedtodisk was inherited from the nobh/buffer-head era. However, f2fs has no buffer heads and the flag is no longer meaningful. The only user of the flag is the "no holes" shortcut in f2fs_vm_page_mkwrite(), which makes mmap write faults skip marking the folio dirty. Moreover, it causes the following race condition with filesystem freezing:

CPU0 (write fault) CPU1 (freeze_super)
---- ----
f2fs_vm_page_mkwrite()
sb_start_pagefault()
/* shortcut: no dirty */
sb_end_pagefault()

                        sb_wait_write(SB_FREEZE_PAGEFAULT)
                        /* no waiter, passes */
                        sync_filesystem()
                        /* folio not dirty, skipped */

finish_fault()
/* PTE writable */
fault_dirty_shared_page()
folio_mark_dirty()
/* dirty folio on a frozen fs */

It will also skip APP_MAPPED_IO iostat/REQ_TIME updates and post-EOF folio zeroing.

Remove this shortcut in f2fs_vm_page_mkwrite() and stop setting it in f2fs_read_single_page().

---
 fs/f2fs/data.c | 1 -
 fs/f2fs/file.c | 6 ------
 2 files changed, 7 deletions(-)
fs/f2fs/data.c +0 -1
index aa6a844ed34dd..52bdfb2785f06 100644
@@ -2186,7 +2186,6 @@ static int f2fs_read_single_page(struct inode *inode, struct folio *folio,
 got_it:
 	if ((map->m_flags & F2FS_MAP_MAPPED)) {
 		block_nr = map->m_pblk + block_in_file - map->m_lblk;
-		folio_set_mappedtodisk(folio);
 
 		if (!f2fs_is_valid_blkaddr(F2FS_I_SB(inode), block_nr,
 						DATA_GENERIC_ENHANCE_READ)) {
fs/f2fs/file.c +0 -6
index 49febaa660815..e5de7c3557260 100644
@@ -207,12 +207,6 @@ static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf)
 	/* wait for GCed page writeback via META_MAPPING */
 	f2fs_wait_on_block_writeback(inode, dn.data_blkaddr);
 
-	/*
-	 * check to see if the page is mapped already (no holes)
-	 */
-	if (folio_test_mappedtodisk(folio))
-		goto out_sem;
-
 	/* page is wholly or partially inside EOF */
 	if (((loff_t)(folio->index + 1) << PAGE_SHIFT) >
 						i_size_read(inode)) {
Signature · 1 line
2.53.0
author maintainer
#530 lore raw

PATCH 528/869 f2fs: allow pinning empty compressed files

In reply to Greg Kroah-Hartman

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

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

From: Joanne Chang <[email protected]>

[ Upstream commit 2eebc31ae5f53e1066bb6238c8087c23b688ad17 ]

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

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

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

PATCH 529/869 f2fs: read i_size once in f2fs_vm_page_mkwrite

In reply to Greg Kroah-Hartman

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

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

From: Nanzhe Zhao <[email protected]>

[ Upstream commit c04f209773ecb31e592cababce0d6658ee0b8d58 ]

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

buffered write writes [0,3500)

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

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

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

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

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

PATCH 530/869 f2fs: check every cur_*_segno[] entry on readonly images

In reply to Greg Kroah-Hartman

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

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

From: Kaixuan Li <[email protected]>

[ Upstream commit 9c4ee79190c8c23a9fb5c07d3bc87eaac514b2bb ]

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

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

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

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

PATCH 531/869 f2fs: fix defragment writeback range truncation on 32-bit

In reply to Greg Kroah-Hartman

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

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

From: Zhan Xusheng <[email protected]>

[ Upstream commit 92154fe28c3701bebf75176dc5522bec62519a8f ]

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

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

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

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

The matching call in f2fs_collapse_range() already casts:

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

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

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

PATCH 532/869 f2fs: disallow mmap write and data-modifying fallocate on atomic files

In reply to Greg Kroah-Hartman

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

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

From: Daeho Jeong <[email protected]>

[ Upstream commit 06dfe4a7eb696d868b196c2a49873142f19bd862 ]

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

fallocate without these flags only preallocates blocks and stays allowed.

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

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

PATCH 533/869 spi: ljca: validate the response length before copying the data

In reply to Greg Kroah-Hartman

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

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

From: Weibin Liu <[email protected]>

[ Upstream commit 0fe4573c822c4c9152e2fd5269ab85410c9e458f ]

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

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

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

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

PATCH 534/869 pinctrl: stm32: Fix fwnode reference leak in stm32_gpiolib_register_bank()

In reply to Greg Kroah-Hartman

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

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

From: Ma Ke <[email protected]>

[ Upstream commit 54c66b5e47a9b10cbf4a1efe9b01301b7ffee205 ]

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

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

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

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

Found by code review.

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

PATCH 535/869 lib/decompress_bunzip2: fix off-by-one in run-length bounds check

In reply to Greg Kroah-Hartman

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

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

From: Matt Turner <[email protected]>

[ Upstream commit 69919be2b93ef3922f646729ff42b4bd9a30846b ]

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

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

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

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

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

PATCH 536/869 panic: flatten nmi_panic control flow

In reply to Greg Kroah-Hartman

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

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

From: Bradley Morgan <[email protected]>

[ Upstream commit 75eb687ff2bcec9fba31bbe266e5f91e5c283efe ]

panic() is __noreturn, so the else after panic_try_start() is dead. Drop it so the force_cpu path can be added cleanly on top.

---
 kernel/panic.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/panic.c +2 -1
index b13f040680ac1..7f8725f2154b8 100644
@@ -364,7 +364,8 @@ void nmi_panic(struct pt_regs *regs, const char *msg)
 {
 	if (panic_try_start())
 		panic("%s", msg);
-	else if (panic_on_other_cpu())
+
+	if (panic_on_other_cpu())
 		nmi_panic_self_stop(regs);
 }
 EXPORT_SYMBOL(nmi_panic);
Signature · 1 line
2.53.0
author maintainer
#539 lore raw

PATCH 537/869 lib: decompress_bunzip2: fix integer overflow in run-length decoding

In reply to Greg Kroah-Hartman

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

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

From: Aamir Ahmed <[email protected]>

[ Upstream commit b822ad8d702df0be9fe3f24f71caeb0522d72319 ]

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

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

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

PATCH 538/869 tmpfs: fix unicode_map leaks in casefold option handling

In reply to Greg Kroah-Hartman

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

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

From: Kazuki Hanai <[email protected]>

[ Upstream commit f439d79e8cd19f89e04cbb3b532347edacd72c79 ]

shmem_parse_opt_casefold() stores the unicode_map returned by utf8_load() in ctx->encoding. A filesystem context can receive the casefold parameter more than once, and a second successful parse overwrites the stored map without releasing it.

The map is also leaked when an unmounted filesystem context is freed. This includes the temporary context used for remount, because shmem_reconfigure() does not take ownership of ctx->encoding.

Reject a second casefold setting, clear ctx->encoding after transferring ownership to the superblock, and release any remaining map from shmem_free_fc().

An unprivileged user can repeatedly create tmpfs filesystem contexts, set the casefold parameter, and close them from a user namespace. This causes unbounded kernel memory consumption and can result in a local denial of service.

Fixes 58e55efd6c72 ("tmpfs: Add casefold lookup support")
Cc Hugh Dickins <[email protected]>
Cc Baolin Wang <[email protected]>
Cc André Almeida <[email protected]>
Cc Christian Brauner <[email protected]>
---
 mm/shmem.c | 7 +++++++
 1 file changed, 7 insertions(+)
mm/shmem.c +7 -0
index f2b5a11e88a55..68a3a0734e3df 100644
@@ -4595,6 +4595,9 @@ static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *
 	struct unicode_map *encoding;
 	char *version_str = param->string + 5;
 
+	if (ctx->encoding)
+		return invalfc(fc, "casefold parameter cannot be specified twice\n");
+
 	if (!latest_version) {
 		if (strncmp(param->string, "utf8-", 5))
 			return invalfc(fc, "Only UTF-8 encodings are supported "
@@ -5081,6 +5084,7 @@ static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
 
 	if (ctx->encoding) {
 		sb->s_encoding = ctx->encoding;
+		ctx->encoding = NULL;
 		set_default_d_op(sb, &shmem_ci_dentry_ops);
 		if (ctx->strict_encoding)
 			sb->s_encoding_flags = SB_ENC_STRICT_MODE_FL;
@@ -5177,6 +5181,9 @@ static void shmem_free_fc(struct fs_context *fc)
 	struct shmem_options *ctx = fc->fs_private;
 
 	if (ctx) {
+#if IS_ENABLED(CONFIG_UNICODE)
+		utf8_unload(ctx->encoding);
+#endif
 		mpol_put(ctx->mpol);
 		kfree(ctx);
 	}
Signature · 1 line
2.53.0
author maintainer
#541 lore raw

PATCH 539/869 ALSA: hda/tas2781: Skip invalid TAS2563 UEFI calibration data

In reply to Greg Kroah-Hartman

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

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

From: Gergo Koteles <[email protected]>

[ Upstream commit a0f0325e92e505db6a6879d79da5aa88e94a36ab ]

Some Lenovo 14ARB7 laptops do not have proper calibration data.

Skip these zero calibration values and fall back to the calibration data provided by the DSP firmware.

---
 sound/hda/codecs/side-codecs/tas2781_hda_i2c.c | 5 +++++
 1 file changed, 5 insertions(+)
sound/hda/codecs/side-codecs/tas2781_hda_i2c.c +5 -0
index ebfc08b5fb283..6eb9e4b8ba2e8 100644
@@ -375,6 +375,11 @@ static int tas2563_save_calibration(struct tas2781_hda *h)
 					i, j, status);
 				return -EINVAL;
 			}
+			if (*(uint32_t *)&data[offset] == 0) {
+				dev_warn(p->dev,
+					 "Dev %d: Caldat[%d] is zero\n", i, j);
+				return -EINVAL;
+			}
 			bedata = cpu_to_be32(*(uint32_t *)&data[offset]);
 			memcpy(&data[offset], &bedata, sizeof(bedata));
 			offset += TAS2563_CAL_DATA_SIZE;
Signature · 1 line
2.53.0